Spaces:
Paused

File size: 4,787 Bytes
6c62840
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3f9f1f
6c62840
 
 
 
e3f9f1f
 
 
 
6c62840
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a813598
 
 
 
 
 
 
 
 
 
 
 
 
 
9571a8e
a813598
 
 
 
 
 
 
 
 
6ba1c48
a813598
 
6ba1c48
a813598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b040964
 
a813598
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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 [m for m in [mask_for_role(item, role) for item in data] if m is not None]
    
    if not isinstance(data, dict):
        return data

    # 0. BLOCK Internal Data for Customers
    if not has_staff_access and data.get("is_internal"):
        return None

    # 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
        )
        .order_by(NexusInteraction.created_at.asc())
    )
    result = await db.execute(stmt)
    rows = result.all()
    
    if not rows:
        return []
        
    # Convert to dicts for masking without SQLAlchemy internal state
    interaction_dicts = []
    for i, full_name in rows:
        d = {c.name: getattr(i, c.name) for c in i.__table__.columns}
        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