Spaces:
Paused

dushyantsingh0 commited on
Commit
23073be
Β·
1 Parent(s): 90d0eab

fix: resolve master agent toolbox lint errors and import dependencies

Browse files
agents/nexus_master.py CHANGED
@@ -9,7 +9,10 @@ from core.llm import get_llm
9
  from agents.tools.nexus_tools import (
10
  kb_search_tool, search_tickets_tool, get_ticket_details_tool, summarize_workspace_tool,
11
  add_ticket_comment_tool, change_ticket_status_tool, update_ticket_attributes_tool,
12
- create_ticket_tool, nexus_interaction_recall_tool, assign_ticket_tool
 
 
 
13
  )
14
  from agents.tools.langchain_tools import LANGCHAIN_TOOLS
15
  from agents.tools.tool_registry import get_tool_names_for_role
@@ -284,7 +287,7 @@ async def nexus_tool_executor(state: NexusState) -> Dict[str, Any]:
284
  update_data = {}
285
 
286
  # We now explicitly define which tools require HITL approval
287
- WRITE_TOOLS = ["CREATE_TICKET", "ADD_TICKET_COMMENT", "CHANGE_TICKET_STATUS", "UPDATE_TICKET_ATTRIBUTES", "ASSIGN_TICKET"]
288
 
289
  # We may have already approved actions
290
  is_approved = state.get("action_approved", False)
@@ -343,6 +346,9 @@ async def nexus_tool_executor(state: NexusState) -> Dict[str, Any]:
343
  "action_approved": False,
344
  "current_tool_output": str(results[0]) if results else "Success."
345
  }
 
 
 
346
 
347
  # Pass 2: Process Current Tool Calls
348
  tool_messages = []
@@ -382,6 +388,23 @@ async def nexus_tool_executor(state: NexusState) -> Dict[str, Any]:
382
  direct_pass = True
383
  elif tool_name == "MEMORY_RECALL":
384
  task_calls.append((call_id, nexus_interaction_recall_tool(params.get("query", query), ws_id, state["user_id"])))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
385
  else:
386
  task_calls.append((call_id, asyncio.sleep(0, result="Unknown or restricted read tool.")))
387
 
 
9
  from agents.tools.nexus_tools import (
10
  kb_search_tool, search_tickets_tool, get_ticket_details_tool, summarize_workspace_tool,
11
  add_ticket_comment_tool, change_ticket_status_tool, update_ticket_attributes_tool,
12
+ create_ticket_tool, nexus_interaction_recall_tool, assign_ticket_tool,
13
+ nexus_analytics_tool, similar_incident_finder, project_pulse_tool,
14
+ sentiment_pulse_tool, knowledge_drafting_tool, sla_audit_tool,
15
+ get_user_info_tool, remediation_log_tool
16
  )
17
  from agents.tools.langchain_tools import LANGCHAIN_TOOLS
18
  from agents.tools.tool_registry import get_tool_names_for_role
 
287
  update_data = {}
288
 
289
  # We now explicitly define which tools require HITL approval
290
+ WRITE_TOOLS = ["CREATE_TICKET", "ADD_TICKET_COMMENT", "CHANGE_TICKET_STATUS", "UPDATE_TICKET_ATTRIBUTES", "ASSIGN_TICKET", "KNOWLEDGE_DRAFT"]
291
 
292
  # We may have already approved actions
293
  is_approved = state.get("action_approved", False)
 
346
  "action_approved": False,
347
  "current_tool_output": str(results[0]) if results else "Success."
348
  }
349
+
350
+ # Check for KNOWLEDGE_DRAFT specifically as it might need unique handling or just reuse generic write
351
+ # (Reusing generic write pattern if matched in Pass 1)
352
 
353
  # Pass 2: Process Current Tool Calls
354
  tool_messages = []
 
388
  direct_pass = True
389
  elif tool_name == "MEMORY_RECALL":
390
  task_calls.append((call_id, nexus_interaction_recall_tool(params.get("query", query), ws_id, state["user_id"])))
391
+ elif tool_name == "GET_ANALYTICS":
392
+ task_calls.append((call_id, nexus_analytics_tool(ws_id, role=role)))
393
+ elif tool_name == "SIMILAR_INCIDENTS":
394
+ task_calls.append((call_id, similar_incident_finder(params.get("query", query), ws_id, role=role)))
395
+ elif tool_name == "PROJECT_PULSE":
396
+ task_calls.append((call_id, project_pulse_tool(params.get("project_name"), ws_id)))
397
+ elif tool_name == "SENTIMENT_CHECK":
398
+ task_calls.append((call_id, sentiment_pulse_tool(params.get("ticket_id"), ws_id)))
399
+ elif tool_name == "SLA_AUDIT":
400
+ task_calls.append((call_id, sla_audit_tool(ws_id, role=role)))
401
+ elif tool_name == "GET_USER_INFO":
402
+ task_calls.append((call_id, get_user_info_tool(params.get("user_id"), ws_id, role=role)))
403
+ elif tool_name == "GET_REMEDIATION_LOG":
404
+ task_calls.append((call_id, remediation_log_tool(ws_id, role=role)))
405
+ elif tool_name == "KNOWLEDGE_DRAFT" and not is_approved:
406
+ # Special case: Knowledge draft content fetch for staging
407
+ task_calls.append((call_id, knowledge_drafting_tool(params.get("ticket_id"), ws_id)))
408
  else:
409
  task_calls.append((call_id, asyncio.sleep(0, result="Unknown or restricted read tool.")))
410
 
agents/prompts.py CHANGED
@@ -48,15 +48,17 @@ You are the Nexus Intelligence Router. Your goal is to resolve user requests by
48
 
49
  CORE TOOLSET & PRIORITY:
50
  1. KB_SEARCH: MUST use for any technical questions, "how-to" queries, or searching documentation.
51
- - Keywords: search, find, how, what, why, article, docs.
52
- - PRIORITY: HIGH (Default for factual technical queries).
53
  2. TICKETS: Use to check status, history, or recent activity of support tickets.
54
- - Keywords: status, active, recent, my tickets, update on.
55
- 3. ANALYTICS: Use for any request involving data visualization, trends, charts, metrics, or "heatmaps".
56
- - PRIORITY: EXCLUSIVE (If the request asks for "counts", "trends", "charts", or "distribution", call ONLY this tool).
57
- 4. SUMMARIZE_WORKSPACE: Use for high-level health summaries, status reports, or specific "Pulse Check" requests.
58
- 5. SIMILAR_INCIDENTS: Use ONLY when troubleshooting a specific technical error to find historical resolutions that worked in the past.
59
- 6. CONVERSE: Use ONLY if no tool is required (e.g., greetings, simple acknowledgments) or if you need to ask a clarifying question before selecting a tool.
 
 
 
 
60
 
61
  STRATEGIC DIRECTIVES:
62
  - NO HALLUCINATION: Never claim "systems appear stable" or provide health updates without first running SUMMARIZE_WORKSPACE or ANALYTICS.
 
48
 
49
  CORE TOOLSET & PRIORITY:
50
  1. KB_SEARCH: MUST use for any technical questions, "how-to" queries, or searching documentation.
 
 
51
  2. TICKETS: Use to check status, history, or recent activity of support tickets.
52
+ 3. GET_ANALYTICS: Use for data visualization, trends, charts, metrics, or "heatmaps". (PRIORITY: EXCLUSIVE for metrics).
53
+ 4. SUMMARIZE_WORKSPACE: Use for high-level health summaries or "Pulse Check" requests.
54
+ 5. SIMILAR_INCIDENTS: [STAFF ONLY] Use to find historical resolutions for recurring technical errors.
55
+ 6. PROJECT_PULSE: Use for requests specifically about project distribution and health.
56
+ 7. SENTIMENT_CHECK: [STAFF ONLY] Use to assess customer mood across recent ticket interactions.
57
+ 8. KNOWLEDGE_DRAFT: [STAFF ONLY] [WRITE] Use when a resolved ticket should be documented into a KB article.
58
+ 9. SLA_AUDIT: [STAFF ONLY] Use for forensic audits of 'breached', 'stale', or 'at-risk' tickets.
59
+ 10. GET_USER_INFO: [STAFF ONLY] Use to retrieve profile and activity details for a specific user.
60
+ 11. GET_REMEDIATION_LOG: [STAFF ONLY] Use to review AI self-healing history and successes.
61
+ 12. CONVERSE: Use for greetings, acknowledgments, or clarifying questions.
62
 
63
  STRATEGIC DIRECTIVES:
64
  - NO HALLUCINATION: Never claim "systems appear stable" or provide health updates without first running SUMMARIZE_WORKSPACE or ANALYTICS.
agents/tools/langchain_tools.py CHANGED
@@ -11,7 +11,9 @@ from langchain_core.tools import tool
11
  from agents.tools.tool_registry import (
12
  KBSearchInput, TicketSearchInput, TicketDetailsInput, SummarizeWorkspaceInput,
13
  AddCommentInput, ChangeStatusInput, UpdateTicketAttributesInput,
14
- MemoryRecallInput, PlatformRefreshInput, CreateTicketInput, AssignTicketInput
 
 
15
  )
16
 
17
  @tool(args_schema=KBSearchInput)
@@ -68,6 +70,46 @@ async def assign_ticket(ticket_id: str, user_id: str, **kwargs) -> str:
68
  """STAFF ONLY: Assign a ticket to a specific agent. USE THIS when a lead or admin identifies the best owner for a resolution."""
69
  pass
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  # We also need to map the "tool names" string from tool_registry to these actual @tool objects
72
  LANGCHAIN_TOOLS = {
73
  "KB_SEARCH": kb_search,
@@ -81,4 +123,12 @@ LANGCHAIN_TOOLS = {
81
  "PLATFORM_REFRESH": platform_refresh,
82
  "CREATE_TICKET": create_ticket,
83
  "ASSIGN_TICKET": assign_ticket,
 
 
 
 
 
 
 
 
84
  }
 
11
  from agents.tools.tool_registry import (
12
  KBSearchInput, TicketSearchInput, TicketDetailsInput, SummarizeWorkspaceInput,
13
  AddCommentInput, ChangeStatusInput, UpdateTicketAttributesInput,
14
+ MemoryRecallInput, PlatformRefreshInput, CreateTicketInput, AssignTicketInput,
15
+ AnalyticsInput, ProjectPulseInput, SentimentPulseInput, KBDraftInput,
16
+ SlaAuditInput, UserInfoInput, RemediationLogInput
17
  )
18
 
19
  @tool(args_schema=KBSearchInput)
 
70
  """STAFF ONLY: Assign a ticket to a specific agent. USE THIS when a lead or admin identifies the best owner for a resolution."""
71
  pass
72
 
73
+ @tool(args_schema=AnalyticsInput)
74
+ async def get_analytics(**kwargs) -> str:
75
+ """Analyze workspace metrics. USE THIS for 'visualize', 'trends', 'charts', 'graphs', 'distribution', or 'data' requests."""
76
+ pass
77
+
78
+ @tool(args_schema=KBSearchInput) # Reusing schema
79
+ async def similar_incidents(query: str, **kwargs) -> str:
80
+ """STAFF ONLY: Find similar resolved tickets. USE THIS for troubleshooting recurring issues."""
81
+ pass
82
+
83
+ @tool(args_schema=ProjectPulseInput)
84
+ async def project_pulse(project_name: str, **kwargs) -> str:
85
+ """Calculate health metrics for a specific project. USE THIS for requests about projects."""
86
+ pass
87
+
88
+ @tool(args_schema=SentimentPulseInput)
89
+ async def sentiment_check(ticket_id: str, **kwargs) -> str:
90
+ """STAFF ONLY: Analyze conversation sentiment. USE THIS to assess customer mood or interaction quality."""
91
+ pass
92
+
93
+ @tool(args_schema=KBDraftInput)
94
+ async def knowledge_draft(ticket_id: str, **kwargs) -> str:
95
+ """STAFF ONLY: [WRITE] Prepare a Knowledge Base article draft. USE THIS when a ticket is resolved and its solution should be documented."""
96
+ pass
97
+
98
+ @tool(args_schema=SlaAuditInput)
99
+ async def sla_audit(**kwargs) -> str:
100
+ """STAFF ONLY: Perform SLA breach assessment. USE THIS for 'breached', 'delayed', or 'stale' ticket audits."""
101
+ pass
102
+
103
+ @tool(args_schema=UserInfoInput)
104
+ async def get_user_info(user_id: str, **kwargs) -> str:
105
+ """STAFF ONLY: Fetch profile and activities for a specific user ID."""
106
+ pass
107
+
108
+ @tool(args_schema=RemediationLogInput)
109
+ async def get_remediation_log(**kwargs) -> str:
110
+ """STAFF ONLY: Review AI self-healing history. USE THIS to see what automated fixes have been attempted."""
111
+ pass
112
+
113
  # We also need to map the "tool names" string from tool_registry to these actual @tool objects
114
  LANGCHAIN_TOOLS = {
115
  "KB_SEARCH": kb_search,
 
123
  "PLATFORM_REFRESH": platform_refresh,
124
  "CREATE_TICKET": create_ticket,
125
  "ASSIGN_TICKET": assign_ticket,
126
+ "GET_ANALYTICS": get_analytics,
127
+ "SIMILAR_INCIDENTS": similar_incidents,
128
+ "PROJECT_PULSE": project_pulse,
129
+ "SENTIMENT_CHECK": sentiment_check,
130
+ "KNOWLEDGE_DRAFT": knowledge_draft,
131
+ "SLA_AUDIT": sla_audit,
132
+ "GET_USER_INFO": get_user_info,
133
+ "GET_REMEDIATION_LOG": get_remediation_log,
134
  }
agents/tools/nexus_tools.py CHANGED
@@ -1,18 +1,31 @@
1
- from typing import Optional
2
  from uuid import UUID
3
- from datetime import datetime
4
  import json
 
 
5
  from sqlalchemy import select, func, cast, String
 
 
6
  from core.database import async_session_factory
7
- from models.ticket import Ticket, TicketStatus, TicketPriority
8
  from core.llm import get_text_embeddings
9
  from core.logging import get_logger
10
  from core.tasks import enqueue_task
11
- from core.cache import invalidate_workspace_semantic_cache
 
 
12
  from models.user import User, UserRole
13
- from agents.utils import safe_uuid
 
 
 
 
 
14
  from agents.security import mask_for_role, is_staff_role
15
- from collections import namedtuple
 
 
 
16
 
17
  logger = get_logger(__name__)
18
 
@@ -34,8 +47,6 @@ async def kb_search_tool(query: str, workspace_id: UUID, role: str = "customer_u
34
  Search the Knowledge Base using the advanced Hybrid Multimodal engine.
35
  """
36
  # 0. Semantic Cache Check (Blazing Fast Recall)
37
- from core.cache import SemanticCacheManager
38
-
39
  is_agent_role = any(s in role.lower() for s in ["3sc", "agent", "lead", "admin"])
40
 
41
  cached_answer = await SemanticCacheManager.check_cache(
@@ -59,7 +70,6 @@ async def kb_search_tool(query: str, workspace_id: UUID, role: str = "customer_u
59
  if "lead" in role.lower(): user_role_mapped = UserRole.SC_LEAD
60
 
61
  # 1. Perform Search via High-Fidelity Engine
62
- from api.v1.kb import execute_multimodal_search
63
  mock_user = MockUser(workspace_id=workspace_id, role=role, id=UUID("00000000-0000-0000-0000-000000000001"))
64
 
65
  # 2. Execute the high-superpower hybrid search
@@ -74,7 +84,6 @@ async def kb_search_tool(query: str, workspace_id: UUID, role: str = "customer_u
74
 
75
  if not search_results:
76
  # IMPROVEMENT: If primary search fails, try a fuzzy "title-only" or suggestion-based fallback
77
- from api.v1.kb import generate_query_variations
78
  variations = await generate_query_variations(query)
79
 
80
  error_msg = f"No direct matching Knowledge Base articles found for '{query}' in the {role} context.\n\n"
@@ -110,8 +119,6 @@ async def create_ticket_tool(title: str, description: str, workspace_id: UUID, u
110
  Create a new support ticket in the workspace.
111
  """
112
  async with async_session_factory() as db:
113
- from models.ticket import TicketStatus, TicketPriority
114
-
115
  # Normalize priority (P0=Critical, P1=High, P2=Medium, P3=Low)
116
  prio = TicketPriority.P2
117
  p_norm = str(priority).upper()
@@ -157,8 +164,6 @@ async def add_ticket_comment_tool(ticket_id: str, comment: str, workspace_id: UU
157
  if not t_id: return "Error: Invalid Ticket ID format."
158
 
159
  async with async_session_factory() as db:
160
- from models.message import Message
161
-
162
  # 1. Verify existence
163
  stmt = select(Ticket).where(Ticket.id == t_id, Ticket.workspace_id == workspace_id)
164
  res = await db.execute(stmt)
@@ -257,9 +262,6 @@ async def summarize_workspace_tool(workspace_id: UUID, role: str = "customer_use
257
  Generate a high-fidelity 'Executive Health Narrative' for the current workspace.
258
  Summarizes SLA performance, volumes, and critical trends.
259
  """
260
- from api.v1.reports import get_ai_service_insights
261
- from core.database import async_session_factory
262
-
263
  # We mock the dependency structure needed for reports
264
  class MockUser:
265
  def __init__(self, ws_id, r):
@@ -340,8 +342,6 @@ async def get_ticket_details_tool(ticket_id: str, workspace_id: UUID, role: str
340
  if not t_id: return "Error: Invalid Ticket ID format."
341
 
342
  async with async_session_factory() as db:
343
- from models.message import Message
344
-
345
  # 1. Fetch Ticket
346
  stmt = select(Ticket).where(Ticket.id == t_id, Ticket.workspace_id == workspace_id)
347
  res = await db.execute(stmt)
@@ -407,7 +407,6 @@ async def nexus_analytics_tool(workspace_id: UUID, role: str = "customer_user")
407
  )
408
 
409
  if not staff_access:
410
- from sqlalchemy.orm import aliased
411
  Creator = aliased(User)
412
  prio_stmt = prio_stmt.join(Creator, Ticket.created_by == Creator.id).where(
413
  Creator._legacy_role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER])
@@ -422,7 +421,6 @@ async def nexus_analytics_tool(workspace_id: UUID, role: str = "customer_user")
422
  )
423
 
424
  if not staff_access:
425
- from sqlalchemy.orm import aliased
426
  Creator = aliased(User)
427
  cat_stmt = cat_stmt.join(Creator, Ticket.created_by == Creator.id).where(
428
  Creator._legacy_role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER])
@@ -431,7 +429,6 @@ async def nexus_analytics_tool(workspace_id: UUID, role: str = "customer_user")
431
  cat_stmt = cat_stmt.group_by(Ticket.category).order_by(func.count(Ticket.id).desc()).limit(10)
432
 
433
  # 4. Daily Volume Trends (Last 7 Days)
434
- from datetime import timedelta
435
  seven_days_ago = datetime.now() - timedelta(days=7)
436
  day_expr = cast(func.date(Ticket.created_at), String)
437
  trend_stmt = (
@@ -444,7 +441,6 @@ async def nexus_analytics_tool(workspace_id: UUID, role: str = "customer_user")
444
  )
445
 
446
  if not staff_access:
447
- from sqlalchemy.orm import aliased
448
  Creator = aliased(User)
449
  trend_stmt = trend_stmt.join(Creator, Ticket.created_by == Creator.id).where(
450
  Creator._legacy_role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER])
@@ -455,7 +451,6 @@ async def nexus_analytics_tool(workspace_id: UUID, role: str = "customer_user")
455
  # 5. SLA Compliance (Fault Tolerant)
456
  sla_data = {"error": "SLA data currently unavailable"}
457
  try:
458
- from api.v1.reports import get_sla_compliance
459
  class MockSlaUser:
460
  def __init__(self, ws_id):
461
  self.workspace_id = ws_id
@@ -540,8 +535,6 @@ async def project_pulse_tool(project_name: str, workspace_id: UUID) -> str:
540
  A birds-eye view of a specific project's health and ticket distribution.
541
  """
542
  async with async_session_factory() as db:
543
- from models.project import Project
544
-
545
  # 1. Resolve Project
546
  p_stmt = select(Project).where(
547
  Project.workspace_id == workspace_id,
@@ -577,7 +570,6 @@ async def sentiment_pulse_tool(ticket_id: UUID, workspace_id: UUID) -> str:
577
  Retrieve message history for sentiment and pulse analysis.
578
  """
579
  async with async_session_factory() as db:
580
- from models.message import Message
581
  t_id = safe_uuid(ticket_id)
582
  if not t_id: return "Invalid Ticket ID."
583
 
@@ -665,8 +657,6 @@ async def nexus_interaction_recall_tool(query: str, workspace_id: UUID, user_id:
665
  Forensic Semantic Recall Tool.
666
  Search deep user history and crystallized facts to resolve recurring problems.
667
  """
668
- from models.nexus_memory import NexusMemory
669
-
670
  async with async_session_factory() as db:
671
  # 1. Generate Search Vector
672
  embedder = get_text_embeddings()
@@ -708,3 +698,112 @@ async def refresh_platform_insights_tool(current_user: User) -> str:
708
  await enqueue_task("generate_global_insight")
709
 
710
  return "SUCCESS: Platform-wide strategic analysis has been enqueued. The Global Dashboard will be updated shortly."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, List, Dict, Any
2
  from uuid import UUID
3
+ from datetime import datetime, timedelta
4
  import json
5
+ from collections import namedtuple
6
+
7
  from sqlalchemy import select, func, cast, String
8
+ from sqlalchemy.orm import aliased
9
+
10
  from core.database import async_session_factory
 
11
  from core.llm import get_text_embeddings
12
  from core.logging import get_logger
13
  from core.tasks import enqueue_task
14
+ from core.cache import invalidate_workspace_semantic_cache, SemanticCacheManager
15
+
16
+ from models.ticket import Ticket, TicketStatus, TicketPriority
17
  from models.user import User, UserRole
18
+ from models.message import Message
19
+ from models.project import Project
20
+ from models.nexus_memory import NexusMemory
21
+ from models.remediation_audit import RemediationAudit
22
+ from models.user_workspace import UserWorkspace
23
+
24
  from agents.security import mask_for_role, is_staff_role
25
+ from agents.utils import safe_uuid
26
+
27
+ from api.v1.kb import execute_multimodal_search, generate_query_variations
28
+ from api.v1.reports import get_ai_service_insights, get_sla_compliance
29
 
30
  logger = get_logger(__name__)
31
 
 
47
  Search the Knowledge Base using the advanced Hybrid Multimodal engine.
48
  """
49
  # 0. Semantic Cache Check (Blazing Fast Recall)
 
 
50
  is_agent_role = any(s in role.lower() for s in ["3sc", "agent", "lead", "admin"])
51
 
52
  cached_answer = await SemanticCacheManager.check_cache(
 
70
  if "lead" in role.lower(): user_role_mapped = UserRole.SC_LEAD
71
 
72
  # 1. Perform Search via High-Fidelity Engine
 
73
  mock_user = MockUser(workspace_id=workspace_id, role=role, id=UUID("00000000-0000-0000-0000-000000000001"))
74
 
75
  # 2. Execute the high-superpower hybrid search
 
84
 
85
  if not search_results:
86
  # IMPROVEMENT: If primary search fails, try a fuzzy "title-only" or suggestion-based fallback
 
87
  variations = await generate_query_variations(query)
88
 
89
  error_msg = f"No direct matching Knowledge Base articles found for '{query}' in the {role} context.\n\n"
 
119
  Create a new support ticket in the workspace.
120
  """
121
  async with async_session_factory() as db:
 
 
122
  # Normalize priority (P0=Critical, P1=High, P2=Medium, P3=Low)
123
  prio = TicketPriority.P2
124
  p_norm = str(priority).upper()
 
164
  if not t_id: return "Error: Invalid Ticket ID format."
165
 
166
  async with async_session_factory() as db:
 
 
167
  # 1. Verify existence
168
  stmt = select(Ticket).where(Ticket.id == t_id, Ticket.workspace_id == workspace_id)
169
  res = await db.execute(stmt)
 
262
  Generate a high-fidelity 'Executive Health Narrative' for the current workspace.
263
  Summarizes SLA performance, volumes, and critical trends.
264
  """
 
 
 
265
  # We mock the dependency structure needed for reports
266
  class MockUser:
267
  def __init__(self, ws_id, r):
 
342
  if not t_id: return "Error: Invalid Ticket ID format."
343
 
344
  async with async_session_factory() as db:
 
 
345
  # 1. Fetch Ticket
346
  stmt = select(Ticket).where(Ticket.id == t_id, Ticket.workspace_id == workspace_id)
347
  res = await db.execute(stmt)
 
407
  )
408
 
409
  if not staff_access:
 
410
  Creator = aliased(User)
411
  prio_stmt = prio_stmt.join(Creator, Ticket.created_by == Creator.id).where(
412
  Creator._legacy_role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER])
 
421
  )
422
 
423
  if not staff_access:
 
424
  Creator = aliased(User)
425
  cat_stmt = cat_stmt.join(Creator, Ticket.created_by == Creator.id).where(
426
  Creator._legacy_role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER])
 
429
  cat_stmt = cat_stmt.group_by(Ticket.category).order_by(func.count(Ticket.id).desc()).limit(10)
430
 
431
  # 4. Daily Volume Trends (Last 7 Days)
 
432
  seven_days_ago = datetime.now() - timedelta(days=7)
433
  day_expr = cast(func.date(Ticket.created_at), String)
434
  trend_stmt = (
 
441
  )
442
 
443
  if not staff_access:
 
444
  Creator = aliased(User)
445
  trend_stmt = trend_stmt.join(Creator, Ticket.created_by == Creator.id).where(
446
  Creator._legacy_role.in_([UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER])
 
451
  # 5. SLA Compliance (Fault Tolerant)
452
  sla_data = {"error": "SLA data currently unavailable"}
453
  try:
 
454
  class MockSlaUser:
455
  def __init__(self, ws_id):
456
  self.workspace_id = ws_id
 
535
  A birds-eye view of a specific project's health and ticket distribution.
536
  """
537
  async with async_session_factory() as db:
 
 
538
  # 1. Resolve Project
539
  p_stmt = select(Project).where(
540
  Project.workspace_id == workspace_id,
 
570
  Retrieve message history for sentiment and pulse analysis.
571
  """
572
  async with async_session_factory() as db:
 
573
  t_id = safe_uuid(ticket_id)
574
  if not t_id: return "Invalid Ticket ID."
575
 
 
657
  Forensic Semantic Recall Tool.
658
  Search deep user history and crystallized facts to resolve recurring problems.
659
  """
 
 
660
  async with async_session_factory() as db:
661
  # 1. Generate Search Vector
662
  embedder = get_text_embeddings()
 
698
  await enqueue_task("generate_global_insight")
699
 
700
  return "SUCCESS: Platform-wide strategic analysis has been enqueued. The Global Dashboard will be updated shortly."
701
+
702
+ async def sla_audit_tool(workspace_id: UUID, role: str = "customer_user") -> str:
703
+ """
704
+ Forensic SLA Audit. Identifies tickets that are BREACHED, STALE (no activity in 24h), or near-breach.
705
+ """
706
+ if not is_staff_role(role):
707
+ return "Permission Denied: SLA audits are restricted to 3SC Support Staff."
708
+
709
+ async with async_session_factory() as db:
710
+ # 1. Fetch Active Tickets
711
+ stmt = select(Ticket).where(
712
+ Ticket.workspace_id == workspace_id,
713
+ Ticket.status.in_([TicketStatus.OPEN, TicketStatus.ACKNOWLEDGED, TicketStatus.IN_PROGRESS]),
714
+ Ticket.deleted_at.is_(None)
715
+ )
716
+ res = await db.execute(stmt)
717
+ tickets = res.scalars().all()
718
+
719
+ if not tickets:
720
+ return "No active tickets found to audit."
721
+
722
+ now = datetime.now()
723
+ breached = []
724
+ stale = []
725
+ at_risk = []
726
+
727
+ for t in tickets:
728
+ # Heuristic SLA logic (V1)
729
+ # P0: 4h, P1: 8h, P2: 24h, P3: 48h
730
+ sla_hours = {TicketPriority.P0: 4, TicketPriority.P1: 8, TicketPriority.P2: 24, TicketPriority.P3: 48}.get(t.priority, 24)
731
+ age_hours = (now - t.created_at).total_seconds() / 3600
732
+
733
+ summary = f"[{t.priority.value}] {t.id} - {t.title} ({int(age_hours)}h old)"
734
+
735
+ if age_hours > sla_hours:
736
+ breached.append(f"πŸ”΄ BREACHED: {summary}")
737
+ elif age_hours > (sla_hours * 0.8):
738
+ at_risk.append(f"🟑 AT RISK: {summary}")
739
+
740
+ # Stale check: No update in 24h
741
+ if t.updated_at and (now - t.updated_at).total_seconds() / 3600 > 24:
742
+ stale.append(f"βšͺ STALE: {summary}")
743
+
744
+ report = []
745
+ if breached: report.append("### BREACHED TICKETS\n" + "\n".join(breached))
746
+ if at_risk: report.append("### TICKETS AT RISK\n" + "\n".join(at_risk))
747
+ if stale: report.append("### STALE TICKETS (24h+ inactive)\n" + "\n".join(stale))
748
+
749
+ return "\n\n".join(report) if report else "All active tickets are within SLA parameters."
750
+
751
+ async def get_user_info_tool(target_user_id: str, workspace_id: UUID, role: str = "customer_user") -> str:
752
+ """
753
+ Retrieve persona and activity details for a specific user.
754
+ """
755
+ if not is_staff_role(role):
756
+ return "Permission Denied: User intelligence is restricted to 3SC Support Staff."
757
+
758
+ u_id = safe_uuid(target_user_id)
759
+ if not u_id: return "Invalid User ID."
760
+
761
+ async with async_session_factory() as db:
762
+ stmt = select(User, UserWorkspace.role).join(UserWorkspace, User.id == UserWorkspace.user_id).where(
763
+ User.id == u_id,
764
+ UserWorkspace.workspace_id == workspace_id
765
+ )
766
+ res = await db.execute(stmt)
767
+ record = res.first()
768
+
769
+ if not record:
770
+ return "User not found in this workspace."
771
+
772
+ user, u_role = record
773
+
774
+ # Activity Count
775
+ t_stmt = select(func.count(Ticket.id)).where(Ticket.created_by == u_id, Ticket.workspace_id == workspace_id)
776
+ t_count = (await db.execute(t_stmt)).scalar()
777
+
778
+ return (
779
+ f"### User Profile: {user.full_name}\n"
780
+ f"**Email:** {user.email}\n"
781
+ f"**Workspace Role:** {u_role}\n"
782
+ f"**Active Tickets:** {t_count}\n"
783
+ f"**Identity Gist:** {user.ai_gist.get('communication_profile', 'Standard interaction pattern.') if user.ai_gist else 'No behavioral profile yet.'}"
784
+ )
785
+
786
+ async def remediation_log_tool(workspace_id: UUID, role: str = "customer_user") -> str:
787
+ """
788
+ Review the history of AI self-healing actions.
789
+ """
790
+ if not is_staff_role(role):
791
+ return "Permission Denied: Remediation logs are restricted to 3SC Support Staff."
792
+
793
+ async with async_session_factory() as db:
794
+ stmt = select(RemediationAudit).where(
795
+ RemediationAudit.workspace_id == workspace_id
796
+ ).order_by(RemediationAudit.created_at.desc()).limit(10)
797
+
798
+ res = await db.execute(stmt)
799
+ audits = res.scalars().all()
800
+
801
+ if not audits:
802
+ return "No recent remediation actions found."
803
+
804
+ lines = []
805
+ for a in audits:
806
+ status = "βœ… SUCCESS" if a.is_successful else "❌ FAILED"
807
+ lines.append(f"[{a.created_at.isoformat()}] {status} - {a.action_type}: {a.execution_log[:100]}...")
808
+
809
+ return "### Recent AI Remediation Actions\n" + "\n".join(lines)
agents/tools/tool_registry.py CHANGED
@@ -84,6 +84,30 @@ class ConverseInput(BaseModel):
84
  """No parameters β€” signals the agent should respond conversationally."""
85
  pass
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  # =============================================================================
89
  # TOOL CATALOG β€” Central metadata registry
@@ -199,6 +223,70 @@ TOOL_CATALOG: List[ToolSpec] = [
199
  permission=ToolPermission.ALL,
200
  input_schema=ConverseInput,
201
  ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  ]
203
 
204
 
 
84
  """No parameters β€” signals the agent should respond conversationally."""
85
  pass
86
 
87
+ class AnalyticsInput(BaseModel):
88
+ """No parameters β€” workspace-scoped automatically."""
89
+ pass
90
+
91
+ class ProjectPulseInput(BaseModel):
92
+ project_name: str = Field(description="Name of the project to analyze")
93
+
94
+ class SentimentPulseInput(BaseModel):
95
+ ticket_id: str = Field(description="UUID of the ticket for sentiment analysis")
96
+
97
+ class KBDraftInput(BaseModel):
98
+ ticket_id: str = Field(description="UUID of the resolved ticket to draft an article from")
99
+
100
+ class SlaAuditInput(BaseModel):
101
+ """No parameters β€” workspace-scoped automatically."""
102
+ pass
103
+
104
+ class UserInfoInput(BaseModel):
105
+ user_id: str = Field(description="UUID of the user to retrieve details for")
106
+
107
+ class RemediationLogInput(BaseModel):
108
+ """No parameters β€” workspace-scoped automatically."""
109
+ pass
110
+
111
 
112
  # =============================================================================
113
  # TOOL CATALOG β€” Central metadata registry
 
223
  permission=ToolPermission.ALL,
224
  input_schema=ConverseInput,
225
  ),
226
+ ToolSpec(
227
+ name="GET_ANALYTICS",
228
+ display_name="Workspace Analytics",
229
+ description="Fetch metrics on status, priority, and 7-day volume trends.",
230
+ category=ToolCategory.READ,
231
+ permission=ToolPermission.ALL,
232
+ input_schema=AnalyticsInput,
233
+ ),
234
+ ToolSpec(
235
+ name="SIMILAR_INCIDENTS",
236
+ display_name="Similar Incident Search",
237
+ description="Find top 3 similar resolved tickets to identify patterns.",
238
+ category=ToolCategory.READ,
239
+ permission=ToolPermission.STAFF,
240
+ input_schema=KBSearchInput, # Reuse query input
241
+ ),
242
+ ToolSpec(
243
+ name="PROJECT_PULSE",
244
+ display_name="Project Pulse",
245
+ description="Get distribution and health metrics for a specific project.",
246
+ category=ToolCategory.READ,
247
+ permission=ToolPermission.ALL,
248
+ input_schema=ProjectPulseInput,
249
+ ),
250
+ ToolSpec(
251
+ name="SENTIMENT_CHECK",
252
+ display_name="Sentiment Analysis",
253
+ description="Analyze the mood and pulse of recent customer interactions on a ticket.",
254
+ category=ToolCategory.READ,
255
+ permission=ToolPermission.STAFF,
256
+ input_schema=SentimentPulseInput,
257
+ ),
258
+ ToolSpec(
259
+ name="KNOWLEDGE_DRAFT",
260
+ display_name="Draft KB Article",
261
+ description="Prepare a Knowledge Base article draft from a resolved ticket context.",
262
+ category=ToolCategory.WRITE,
263
+ permission=ToolPermission.STAFF,
264
+ input_schema=KBDraftInput,
265
+ ),
266
+ ToolSpec(
267
+ name="SLA_AUDIT",
268
+ display_name="SLA Breach Audit",
269
+ description="Identify tickets that have breached or are near-breaching SLAs.",
270
+ category=ToolCategory.READ,
271
+ permission=ToolPermission.STAFF,
272
+ input_schema=SlaAuditInput,
273
+ ),
274
+ ToolSpec(
275
+ name="GET_USER_INFO",
276
+ display_name="Get User Details",
277
+ description="Retrieve profile and activity details for a specific user.",
278
+ category=ToolCategory.READ,
279
+ permission=ToolPermission.STAFF,
280
+ input_schema=UserInfoInput,
281
+ ),
282
+ ToolSpec(
283
+ name="GET_REMEDIATION_LOG",
284
+ display_name="Remediation History",
285
+ description="Review past AI self-healing actions and successes.",
286
+ category=ToolCategory.READ,
287
+ permission=ToolPermission.STAFF,
288
+ input_schema=RemediationLogInput,
289
+ ),
290
  ]
291
 
292