Spaces:
Runtime error

File size: 8,797 Bytes
64fb1e7
 
 
 
 
 
 
 
93117c2
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93117c2
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93117c2
 
 
 
 
 
 
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import asyncio
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import Optional, Any

from session.conversation_state import ConversationStateManager
from session.orchestrator_state import OrchestratorState
from voice.conversational_context import ConversationalContext, ConversationMemorySummary
from voice.conversation_policy import ConversationPolicy
from voice.turn_context import TurnExecutionContext


class TurnState(Enum):
    IDLE                 = "idle"
    USER_SPEAKING        = "user_speaking"
    PROCESSING           = "processing"            # STT done, orchestration running
    ASSISTANT_SPEAKING   = "assistant_speaking"
    INTERRUPTED          = "interrupted"
    WAITING_CONFIRMATION = "waiting_confirmation"  # pending_slot or pending_cancel active
    ESCALATING           = "escalating"


@dataclass
class EscalationScores:
    """Three-score escalation model. Frustration derived from session.sentiment_scores."""
    comprehension_failures: int  = 0   # consecutive RECOVERY-tier turns
    explicit_handoff:       bool = False  # ESCALATE directive or explicit keyword
    technical_failures:     int  = 0   # LLM + tool errors combined


@dataclass
class CallSession:
    call_id: str
    conversation_history: list[dict] = field(default_factory=list)
    sentiment_scores: list[float] = field(default_factory=list)
    conv_state: ConversationStateManager = field(default_factory=ConversationStateManager)
    orchestrator_state: OrchestratorState = field(default_factory=OrchestratorState)
    _seen_transcripts: set = field(default_factory=set)
    kb_hits_used: list[str] = field(default_factory=list)
    started_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
    escalated: bool = False
    escalation_reason: Optional[str] = None
    human_joined: bool = False

    # Workflow orchestration (Phase B+)
    workflow: Any = None                          # WorkflowSession β€” set after first intent
    workflow_lock: asyncio.Lock = field(default_factory=asyncio.Lock)

    # Turn ordering β€” stale async result protection
    turn_counter: int = 0
    active_turn_id: int = 0

    # LLM fallback tracking
    llm_fallback_level: int = 0                   # 0=primary, 1=mini, 2=canned, 3=full_fast_mode
    llm_consecutive_failures: int = 0

    # Identity guard
    identity_corrected: bool = False              # True after first name-confusion correction

    # Verified customer β€” set after verify_account succeeds (fintech Fin flow)
    customer_id: Optional[str] = None

    # Tool tracking
    _last_tool_attempted: Optional[str] = None
    _tool_last_called: dict = field(default_factory=dict)   # tool_name β†’ datetime

    # Pending action expiry signal
    _pending_action_expired: bool = False

    # Dedup
    _last_transcript: Optional[str] = None
    _last_transcript_hash: Optional[int] = None

    # Idempotency store: key β†’ (result, expires_at)
    _idempotency_store: dict = field(default_factory=dict)

    # Rate limiting
    turn_count: int = 0
    tool_calls_this_turn: int = 0
    cumulative_tokens: int = 0

    # Pre-selected topic from the issue selector (set at call start)
    initial_topic: Optional[str] = None

    # Agent WebSocket β€” set when escalated
    agent_ws: Any = None

    # Handoff bundle β€” stored at escalation so late-connecting agents receive it
    handoff_bundle: dict = field(default_factory=dict)

    # Escalation room β€” separate LiveKit room for human-agent ↔ customer audio.
    # Created at escalation time; Fin AI room is never used for human audio.
    esc_room_name: Optional[str] = None
    agent_esc_token: Optional[str] = None

    # Orchestration β€” actions already executed this call; prevents companion re-suggesting them
    completed_actions: set = field(default_factory=set)

    # Cached customer profile β€” set after verify_account succeeds.
    # Contains: name, first_name, email, phone, account_type, account_status,
    # fraud_hold_active, kyc_status, masked_phone, masked_email, transactions.
    # Available to tools, handoff bundle, and coaching.
    customer_profile: dict = field(default_factory=dict)

    # OTP flow β€” generated by send_otp, validated by verify_otp
    otp_code:              Optional[str]      = None
    otp_verified:          bool               = False
    otp_sent_at:           Optional[datetime] = None   # expiry: 5 min from send
    otp_attempts:          int                = 0      # wrong-code counter; resets on new send
    otp_locked:            bool               = False  # True after 3 wrong attempts
    otp_resend_count:      int                = 0      # total sends this session; never resets

    # Account lookup hardening
    verify_account_attempts: int = 0                  # increments on not-found; resets on success

    # Refund idempotency β€” set on first successful initiate_refund call
    refund_case_id: Optional[str] = None

    # KB prefetch β€” set by WavvyAgent.on_user_turn_completed, consumed by llm_node
    _pending_kb: Optional[dict] = field(default=None)

    # LiveKit AgentSession β€” set in agent_session.entrypoint; used by REST /end to stop the session
    agent_session: Any = None

    # LiveKit SDK participant ID (PA_xxx) of the human agent β€” set when they join.
    # Used to filter their audio from STT so it isn't transcribed as customer speech.
    human_agent_sid: Optional[str] = None

    # Set when the agent-say endpoint is processing a typed message β†’ prevents
    # on_item_added from interrupting the human-typed TTS.
    human_agent_say_active: bool = False

    # Set to True when escalation permanently fails (all retries exhausted).
    # Prevents infinite retry loops β€” _trigger_escalation checks this before retrying.
    escalation_failed: bool = False

    # Timestamp of the last recovery speech ("Hit a brief issue") to enforce cooldown.
    _last_recovery_speech_ts: float = 0.0

    # Timestamp of the last automatic escalation trigger (monotonic).
    # Enforces a 120-second cooldown so unstable unknown-threshold loops cannot
    # spam escalation. Customer-initiated requests bypass this cooldown.
    _last_escalation_ts: float = 0.0

    # Set when an auto-escalation asks for user confirmation instead of immediately
    # transferring. Cleared on CONFIRM (β†’ escalate), CANCEL_PENDING (β†’ continue),
    # or any non-yes/no utterance (β†’ route normally, drop the pending prompt).
    pending_escalation: bool = False

    # ── Phase 1: Conversational orchestration infrastructure ──────────────────

    # Conversational context β€” domain/intent/goal, repair state, KB cache
    conv_context: ConversationalContext = field(default_factory=ConversationalContext)

    # Rolling memory summary (rebuilt every 5 turns, injected into LLM messages)
    memory: ConversationMemorySummary = field(default_factory=ConversationMemorySummary)

    # Policy layer β€” pure decision functions, no side effects
    policy: ConversationPolicy = field(default_factory=ConversationPolicy)

    # Turn state machine (formalizes BargeInManager + is_stale_turn logic)
    turn_state: TurnState = TurnState.IDLE

    # Response ID β€” set before each LLM stream; checked inside async for loop
    # to abort stale token delivery after barge-in (ghost speech guard)
    current_response_id: Optional[str] = None

    # Barge-in tracking
    last_barge_in_at: float = 0.0
    barge_in_count:   int   = 0

    # Three-score escalation model
    escalation_scores: EscalationScores = field(default_factory=EscalationScores)

    # Active turn cancellation scope (set at start of each _orchestrate() call)
    current_turn_ctx: Optional[TurnExecutionContext] = None

    # Monotonic start time (for duration-based escalation check in ConversationPolicy)
    _started_monotonic: float = field(default_factory=time.monotonic)

    # Companion AI nudge dedup β€” last nudge sent to agent; companion must not repeat it
    _last_nudge: Optional[str] = None

    # Live documentation β€” built continuously by investigation + companion agents.
    # Zero-ACW: on end_call, send this directly without an LLM call.
    _live_documentation: dict = field(default_factory=dict)


# Global in-memory call registry β€” keyed by call_id, never persisted
ACTIVE_CALLS: dict[str, CallSession] = {}


def get_session(call_id: str) -> Optional[CallSession]:
    return ACTIVE_CALLS.get(call_id)


def create_session(call_id: str) -> CallSession:
    session = CallSession(call_id=call_id)
    ACTIVE_CALLS[call_id] = session
    return session


def remove_session(call_id: str) -> Optional[CallSession]:
    return ACTIVE_CALLS.pop(call_id, None)