from typing import Any, Dict, List, Union from uuid import UUID import logging logger = logging.getLogger(__name__) def is_staff_role(role: str) -> bool: """Helper to determine if a role has internal staff privileges.""" if not role: return False r_lower = str(role).lower() return any(s in r_lower for s in ["3sc", "agent", "lead", "admin"]) def mask_for_role(data: Union[Dict[str, Any], List[Dict[str, Any]]], role: str) -> Any: """ Centralized Zero-Trust Masking Utility. Strips internal details if the role is not authorized for staff-level data. """ has_staff_access = is_staff_role(role) if isinstance(data, list): return [mask_for_role(item, role) for item in data] if not isinstance(data, dict): return data # 1. Processing a TICKET object or dict if "ai_metadata" in data: # Clone to avoid mutating shared cache objects inadvertently meta = dict(data["ai_metadata"]) summaries = meta.get("summaries", {}) if not has_staff_access: # STRIP internal summary if "internal_summary" in summaries: del summaries["internal_summary"] # If ONLY internal summary existed, provide a graceful fallback if not summaries.get("customer_summary"): summaries["customer_summary"] = "Context active. Detailed internal notes are restricted." meta["summaries"] = summaries data["ai_metadata"] = meta # 2. Processing MESSAGE history if "messages" in data and isinstance(data["messages"], list): if not has_staff_access: # Filter out internal messages data["messages"] = [m for m in data["messages"] if not m.get("is_internal", False)] # 3. Processing NEXUS INTERACTION / AUDIT if "ai_answer" in data: answer = str(data["ai_answer"]) if not has_staff_access: # Strip internal diagnostic tags that might have leaked from the LLM answer = answer.replace("[INTERNAL_DIAGNOSTIC]", "") answer = answer.replace("[STAFF_ONLY]", "") data["ai_answer"] = answer.strip() if "tool_trace" in data and not has_staff_access: # Mask sensitive tool parameters if they leak infrastructure details trace = data["tool_trace"] if isinstance(trace, list): # For customers, we might just want to show "Used Tool: Knowledge Base" instead of exact params # But the requirement is to handle queries gracefully. # We'll keep tool names but mask complex params if needed. pass return data async def get_thread_history_messages(db: Any, thread_id: UUID, workspace_id: UUID, role: str) -> List[Dict[str, Any]]: """ Synchronous utility to retrieve, mask, and format conversational history for a Nexus thread. Used for instant UI hydration without background jobs. """ from models.nexus_interaction import NexusInteraction from models.user import User as UserTable from sqlalchemy import select stmt = ( select(NexusInteraction, UserTable.full_name) .join(UserTable, NexusInteraction.user_id == UserTable.id) .where( NexusInteraction.thread_id == thread_id, NexusInteraction.workspace_id == workspace_id ) .order_by(NexusInteraction.created_at.asc()) ) result = await db.execute(stmt) rows = result.all() if not rows: return [] # Convert to dicts for masking interaction_dicts = [] for i, full_name in rows: d = i.__dict__.copy() d["sender_name"] = full_name # Ensure dates are strings for cleaner output if d.get("created_at"): d["created_at"] = d["created_at"].isoformat() interaction_dicts.append(d) # Apply role-based masking masked = mask_for_role(interaction_dicts, role) # Flatten into conversational messages history = [] for i in masked: history.append({ "role": "user", "content": i["input_query"], "senderName": i.get("sender_name", "User"), "timestamp": i.get("created_at", "") }) history.append({ "role": "assistant", "content": i["ai_answer"], "senderName": "Nexus", "timestamp": i.get("created_at", "") }) logger.info(f"🧠 [Nexus History] Flattened {len(history)} messages for thread {thread_id}") return history