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)