Spaces:
Runtime error

File size: 29,211 Bytes
64fb1e7
 
 
 
 
 
 
 
 
 
93117c2
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93117c2
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
 
93117c2
 
64fb1e7
93117c2
64fb1e7
93117c2
 
 
 
 
 
 
 
 
64fb1e7
 
 
93117c2
 
 
 
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93117c2
64fb1e7
 
93117c2
 
 
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
93117c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93117c2
 
 
 
64fb1e7
 
 
 
 
 
 
 
93117c2
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93117c2
64fb1e7
93117c2
64fb1e7
 
 
 
 
 
 
 
93117c2
64fb1e7
93117c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e978f7
 
 
 
 
 
64fb1e7
 
 
 
 
 
 
6e978f7
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
93117c2
 
 
 
 
 
 
 
 
 
 
 
64fb1e7
 
 
 
 
 
 
 
93117c2
 
 
 
 
 
 
 
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
import asyncio
import json
import logging
import httpx
from datetime import datetime, timezone
from fastapi import APIRouter, Request, WebSocket, WebSocketDisconnect
from agents.companion_agent import run_mid_call_companion, run_acw_agent
from routers.auth_router import verify_agent_token
from session.call_session import ACTIVE_CALLS
from config import settings
from agents.investigation_agent import run_case_investigation

logger = logging.getLogger(__name__)

router = APIRouter()

# agent_id → WebSocket (one per agent desktop session)
# Stored on app.state.connected_agents so ws_voice can access it
# app.state.agent_statuses: agent_id → "active" | "busy" | "inactive"


def _get_statuses(app_state) -> dict:
    if not hasattr(app_state, "agent_statuses"):
        app_state.agent_statuses = {}
    return app_state.agent_statuses


def get_active_agent_count(app_state) -> int:
    """Count agents currently in 'active' status."""
    connected = getattr(app_state, "connected_agents", {})
    statuses  = _get_statuses(app_state)
    return sum(1 for aid in connected if statuses.get(aid, "active") == "active")


@router.get("/api/agents/availability")
async def agent_availability(request: Request):
    count = get_active_agent_count(request.app.state)
    return {"available": count > 0, "active_count": count}


async def route_event_to_agent(app_state, event: dict) -> bool:
    """Send an event to any connected agent. Returns True if delivered."""
    connected: dict = getattr(app_state, "connected_agents", {})
    if not connected:
        return False
    # Broadcast to all connected agents (demo: single agent scenario)
    payload = json.dumps(event)
    dead = []
    for agent_id, ws in connected.items():
        try:
            await ws.send_text(payload)
        except Exception:
            dead.append(agent_id)
    for agent_id in dead:
        connected.pop(agent_id, None)
    return len(connected) > 0


@router.websocket("/ws/agent")
async def agent_websocket(websocket: WebSocket, token: str = ""):
    # Validate JWT — accept first so we can send a readable error to the client
    try:
        claims = verify_agent_token(token)
    except Exception as exc:
        logger.warning("Agent WS rejected — invalid token: %s", exc)
        await websocket.accept()
        await websocket.send_text(json.dumps({
            "type":   "auth_error",
            "reason": "invalid_or_expired_token",
        }))
        await websocket.close(code=4401)
        return

    agent_name  = claims.get("name", "Agent")
    agent_email = claims.get("email", "")

    await websocket.accept()

    # Register this agent connection
    app_state = websocket.app.state
    if not hasattr(app_state, "connected_agents"):
        app_state.connected_agents = {}

    agent_id = f"agent_{id(websocket)}"
    app_state.connected_agents[agent_id] = websocket
    # Default to active when they connect
    _get_statuses(app_state)[agent_id] = "active"
    logger.info(f"Agent connected: {agent_id} ({agent_name})")

    # Flush any queued escalations that arrived while no agent was connected
    pending: list = getattr(app_state, "pending_escalations", [])
    if pending:
        app_state.pending_escalations = []
        for item in pending:
            asyncio.create_task(
                _send_escalation_to_agent(app_state, app_state.connected_agents, item)
            )

    # Re-deliver escalated calls whose assigned agent WebSocket is no longer connected.
    # This handles the race where escalation was sent to a WebSocket that disconnected
    # before the frontend could render the incoming_call UI.
    active_sockets = set(app_state.connected_agents.values())
    for call_id, sess in list(ACTIVE_CALLS.items()):
        if not (sess.escalated and sess.handoff_bundle):
            continue
        # Only re-deliver if the previously assigned socket is gone
        if sess.agent_ws is not None and sess.agent_ws in active_sockets:
            continue
        _role_map = {"user": "customer", "assistant": "voice_ai"}
        voice_transcript = [
            {
                "speaker": _role_map.get(m.get("role", ""), "customer"),
                "text": m.get("content", ""),
            }
            for m in sess.conversation_history
            if m.get("content")
        ]
        logger.info(f"Re-delivering escalated call {call_id} to newly connected agent {agent_id}")
        asyncio.create_task(
            _send_escalation_to_agent(
                app_state,
                {agent_id: websocket},
                {
                    "call_id": call_id,
                    "customer": {},
                    "handoff_bundle": sess.handoff_bundle,
                    "voice_transcript": voice_transcript,
                },
            )
        )

    # Track state for this agent session
    current_call_id: str | None = None
    current_customer: dict = {}
    transcript_buffer: list[dict] = []
    previous_mood: str = "calm"

    def _find_call_id_for_ws() -> str | None:
        """Find the active call_id that assigned this websocket as its agent."""
        for cid, sess in ACTIVE_CALLS.items():
            if getattr(sess, "agent_ws", None) is websocket:
                return cid
        return current_call_id  # fallback to locally tracked value

    try:
        while True:
            raw = await websocket.receive()

            if raw.get("type") == "websocket.disconnect":
                break

            text = raw.get("text")
            if not text:
                continue

            try:
                msg = json.loads(text)
            except json.JSONDecodeError:
                continue

            msg_type = msg.get("type")

            if msg_type == "agent_ready":
                # Agent desktop signals it's ready — honour any initial status
                initial_status = msg.get("status", "active")
                if initial_status in ("active", "busy", "inactive"):
                    _get_statuses(app_state)[agent_id] = initial_status
                await websocket.send_text(json.dumps({
                    "type": "agent_ready_ack",
                    "agent_name": agent_name,
                    "agent_email": agent_email,
                    "status": _get_statuses(app_state).get(agent_id, "active"),
                }))

            elif msg_type == "set_status":
                new_status = msg.get("status", "active")
                if new_status in ("active", "busy", "inactive"):
                    _get_statuses(app_state)[agent_id] = new_status
                    logger.info(f"Agent {agent_name} status → {new_status}")
                await websocket.send_text(json.dumps({
                    "type": "status_updated",
                    "status": _get_statuses(app_state).get(agent_id, "active"),
                }))

            elif msg_type == "transcript_line":
                # Agent sends their own spoken words (typed or mic STT).
                # The frontend adds the line directly to liveTx — no echo needed here.
                # We only buffer it for companion context and ACW generation.
                line = {
                    "speaker": "agent",
                    "text": msg.get("text", ""),
                }
                transcript_buffer.append(line)

                # Trigger companion update after agent speech — include handoff_bundle context
                resolved_call_id = msg.get("call_id") or _find_call_id_for_ws()
                if resolved_call_id:
                    current_call_id = resolved_call_id
                    sess = ACTIVE_CALLS.get(resolved_call_id)
                    asyncio.create_task(
                        _send_companion_update(
                            websocket,
                            transcript_buffer,
                            current_customer,
                            sess.handoff_bundle if sess else None,
                            previous_mood=previous_mood,
                            workflow_type=_get_workflow_type(sess),
                            completed_actions=sess.completed_actions if sess else None,
                            session=sess,
                        )
                    )

            elif msg_type == "decline_call":
                # Agent actively declines — cancel escalation and return customer to AI
                declined_call_id = msg.get("call_id") or _find_call_id_for_ws()
                if declined_call_id:
                    asyncio.create_task(_decline_escalation(declined_call_id))
                    logger.info(f"Agent {agent_name} declined call {declined_call_id}")
                current_call_id = None
                current_customer = {}
                transcript_buffer = []

            elif msg_type == "end_call":
                # Frontend must send call_id; fall back to session scan if missing
                resolved_call_id = msg.get("call_id") or _find_call_id_for_ws()
                if resolved_call_id:
                    current_call_id = resolved_call_id
                    sess = ACTIVE_CALLS.get(resolved_call_id)
                    # Zero-ACW path: use pre-built live_documentation if available
                    live_doc = getattr(sess, "_live_documentation", None) if sess else None
                    if live_doc and live_doc.get("summary"):
                        await websocket.send_text(json.dumps({"type": "acw_ready", **live_doc}))
                    else:
                        # Fallback: LLM-generated ACW.
                        # _build_transcript_from_session maps role→speaker correctly
                        # (skips system messages; maps user→customer, assistant→fin).
                        acw_transcript = _build_transcript_from_session(sess) if sess else []
                        for line in transcript_buffer:
                            if line not in acw_transcript:
                                acw_transcript.append(line)
                        asyncio.create_task(
                            _send_acw(websocket, acw_transcript, current_customer, resolved_call_id,
                                      handoff_bundle=sess.handoff_bundle if sess else None)
                        )

            elif msg_type == "acw_submit":
                resolved_call_id = _find_call_id_for_ws()
                if resolved_call_id:
                    asyncio.create_task(
                        _persist_acw(resolved_call_id, msg.get("acw", {}))
                    )
                    await websocket.send_text(json.dumps({
                        "type": "call_closed",
                        "call_id": resolved_call_id,
                    }))
                    current_call_id = None
                    current_customer = {}
                    transcript_buffer = []

            elif msg_type == "action_approved":
                action_name  = msg.get("action")
                payload      = msg.get("payload", {})
                execution_id = msg.get("execution_id", "")
                resolved_call_id = msg.get("call_id") or _find_call_id_for_ws()
                if resolved_call_id:
                    current_call_id = resolved_call_id
                if action_name and resolved_call_id and execution_id:
                    asyncio.create_task(
                        _execute_approved_action(
                            websocket, action_name, payload,
                            execution_id, agent_id, resolved_call_id,
                        )
                    )
                elif action_name and not resolved_call_id:
                    logger.warning(
                        "action_approved for '%s' dropped — could not resolve call_id",
                        action_name,
                    )

            elif msg_type == "action_rejected":
                action_name = msg.get("action", "unknown")
                resolved_call_id = msg.get("call_id") or _find_call_id_for_ws()
                if resolved_call_id:
                    current_call_id = resolved_call_id
                logger.info(
                    "Agent %s rejected action '%s' for call %s",
                    agent_name, action_name, resolved_call_id,
                )
                # Emit rejection to timeline
                await websocket.send_text(json.dumps({
                    "type": "activity_event",
                    "kind": "action_rejected",
                    "action": action_name,
                    "message": f"Agent rejected: {action_name.replace('_', ' ').title()}",
                    "timestamp": datetime.now(timezone.utc).isoformat(),
                }))

    except WebSocketDisconnect:
        pass
    except Exception as e:
        logger.error(f"Agent WS error: {e}")
    finally:
        app_state.connected_agents.pop(agent_id, None)
        _get_statuses(app_state).pop(agent_id, None)
        logger.info(f"Agent disconnected: {agent_id} ({agent_name})")


async def deliver_incoming_call(
    app_state,
    call_id: str,
    customer: dict,
    handoff_bundle: dict,
    voice_transcript: list[dict],
    escalation_token: str | None = None,
    esc_room_name: str | None = None,
    livekit_url: str | None = None,
) -> bool:
    """Called from ws_voice when a call is escalated. Delivers to first active agent.
    Queues the escalation (never drops) if no active agent is available right now."""
    connected: dict = getattr(app_state, "connected_agents", {})

    pending_item = {
        "call_id": call_id,
        "customer": customer,
        "handoff_bundle": handoff_bundle,
        "voice_transcript": voice_transcript,
        "escalation_token": escalation_token,
        "esc_room_name": esc_room_name,
        "livekit_url": livekit_url,
    }

    if not connected or get_active_agent_count(app_state) == 0:
        # No active agent right now — queue and deliver when one connects/reconnects.
        # Do NOT drop: the re-delivery hook on WS connect will flush this queue.
        if not hasattr(app_state, "pending_escalations"):
            app_state.pending_escalations = []
        app_state.pending_escalations.append(pending_item)
        logger.warning(f"Escalation for {call_id} queued — no active agents connected")
        return True

    await _send_escalation_to_agent(app_state, connected, pending_item)
    return True


async def _send_escalation_to_agent(app_state, connected: dict, item: dict) -> None:
    """Send one pending escalation item to the first active agent."""
    call_id          = item["call_id"]
    customer         = item["customer"]
    handoff_bundle   = item["handoff_bundle"]
    voice_transcript = item["voice_transcript"]
    escalation_token = item.get("escalation_token")
    esc_room_name    = item.get("esc_room_name")
    livekit_url      = item.get("livekit_url")
    statuses = _get_statuses(app_state)

    payload_dict = {
        "type": "incoming_call",
        "call_id": call_id,
        "customer": customer,
        "handoff_bundle": handoff_bundle,
        "voice_transcript": voice_transcript,
    }
    if escalation_token:
        payload_dict["escalation_token"] = escalation_token
    if esc_room_name:
        payload_dict["esc_room_name"] = esc_room_name
    if livekit_url:
        payload_dict["livekit_url"] = livekit_url
    payload = json.dumps(payload_dict)

    for agent_id, ws in list(connected.items()):
        if statuses.get(agent_id, "active") != "active":
            continue  # skip busy/inactive agents
        try:
            await ws.send_text(payload)
            session = ACTIVE_CALLS.get(call_id)
            if session:
                session.agent_ws = ws
            asyncio.create_task(
                _send_companion_update(
                    ws,
                    voice_transcript,
                    customer,
                    handoff_bundle,
                    workflow_type=_get_workflow_type(session),
                    completed_actions=session.completed_actions if session else None,
                    session=session,
                )
            )
            # Fire Case Intelligence Engine — runs concurrently, delivers before agent answers
            if session:
                asyncio.create_task(run_case_investigation(ws, session, call_id))
            logger.info(f"Escalated call {call_id} delivered to agent {agent_id}")
            return
        except Exception as e:
            logger.error(f"Failed to deliver to agent {agent_id}: {e}")
            connected.pop(agent_id, None)

    # All agents failed — re-queue
    if not hasattr(app_state, "pending_escalations"):
        app_state.pending_escalations = []
    app_state.pending_escalations.append(item)
    logger.warning(f"Escalation for {call_id} re-queued — all agents unreachable")


async def _update_sentiment(ws: WebSocket, session, call_id: str, text: str) -> None:
    """Score customer sentiment and send a sentiment_update event to the agent console."""
    try:
        from voice.sentiment import score_sentiment
        score = await score_sentiment(text)
        if score is None:
            return
        if session:
            session.sentiment_scores.append(score)
        if score >= 0.65:
            mood = "satisfied"
        elif score >= 0.5:
            mood = "calm"
        elif score >= 0.35:
            mood = "curious"
        elif score >= 0.2:
            mood = "frustrated"
        else:
            mood = "angry"
        await ws.send_text(json.dumps({
            "type":    "sentiment_update",
            "score":   score,
            "mood":    mood,
            "call_id": call_id,
        }))
    except Exception as exc:
        logger.debug("Sentiment scoring skipped: %s", exc)


async def _decline_escalation(call_id: str) -> None:
    """Called when an agent clicks Decline — cancels escalation and returns customer to AI."""
    try:
        async with httpx.AsyncClient(timeout=5.0) as client:
            await client.post(
                f"{settings.backend_internal_url}/api/calls/{call_id}/cancel-escalation"
            )
    except Exception as exc:
        logger.warning("[%s] _decline_escalation cancel request failed: %s", call_id, exc)


async def deliver_transcript_line(app_state, speaker: str, text: str, call_id: str) -> None:
    """Forward live transcript lines to the agent desktop during an escalated call.

    Also fires a companion_update so the agent receives nudges and KB hits
    immediately after the customer speaks — not just after the agent speaks.
    """
    session = ACTIVE_CALLS.get(call_id)
    if not session or not session.agent_ws:
        return

    ws = session.agent_ws

    # Push transcript events for both customer AND agent speech.
    # The frontend deduplicates within a 3s window so Web Speech API + Deepgram don't double-print.
    if speaker in ("customer", "agent"):
        try:
            await ws.send_text(json.dumps({
                "type": "transcript",
                "speaker": speaker,
                "text": text,
                "is_final": True,
                "source": "deepgram",  # tag so frontend can deduplicate against Web Speech API
            }))
        except Exception:
            return  # WS is dead — nothing else to do

    # Fire companion updates on both customer AND agent speech.
    if speaker not in ("customer", "agent"):
        return

    transcript = [
        {"speaker": m.get("role", "user"), "text": m.get("content", "")}
        for m in session.conversation_history
        if m.get("content")
    ]
    transcript.append({"speaker": speaker, "text": text})

    # Real-time sentiment scoring for customer utterances
    if speaker == "customer":
        asyncio.create_task(_update_sentiment(ws, session, call_id, text))

    asyncio.create_task(
        _send_companion_update(
            ws,
            transcript,
            {},
            session.handoff_bundle,
            workflow_type=_get_workflow_type(session),
            completed_actions=session.completed_actions,
            session=session,
        )
    )


async def deliver_otp_to_agent(app_state, call_id: str, otp_code: str) -> None:
    """Forward an OTP generated by the voice AI to the agent console activity timeline."""
    session = ACTIVE_CALLS.get(call_id)
    if not session or not session.agent_ws:
        return
    ws = session.agent_ws
    try:
        await ws.send_text(json.dumps({
            "type": "activity_event",
            "kind": "otp_sent_by_ai",
            "action": "send_otp",
            "message": f"Fin AI sent OTP: {otp_code} — customer will read this back.",
            "timestamp": __import__("datetime").datetime.now(__import__("datetime").timezone.utc).isoformat(),
        }))
    except Exception:
        pass


def _get_workflow_type(session) -> str | None:
    if not session:
        return None
    wf = getattr(session, "workflow", None)
    if wf:
        return getattr(wf, "workflow_type", None) or getattr(wf, "intent", None)
    return getattr(session, "workflow_type", None)


async def _send_companion_update(
    ws: WebSocket,
    transcript: list[dict],
    customer: dict,
    handoff_bundle: dict | None = None,
    previous_mood: str = "calm",
    workflow_type: str | None = None,
    completed_actions: set | None = None,
    session=None,
) -> dict:
    previous_nudge = getattr(session, "_last_nudge", None) if session else None
    try:
        update = await run_mid_call_companion(
            transcript,
            customer,
            handoff_bundle,
            workflow_type=workflow_type,
            previous_mood=previous_mood,
            completed_actions=completed_actions,
            previous_nudge=previous_nudge,
        )
        # Track nudge for dedup on next turn
        nudge = update.get("nudge")
        if session and nudge:
            session._last_nudge = nudge
        # Merge documentation_update into session._live_documentation
        doc_update = update.get("documentation_update")
        if session and isinstance(doc_update, dict):
            if not session._live_documentation:
                session._live_documentation = {}
            if doc_update.get("summary"):
                session._live_documentation["summary"] = doc_update["summary"]
            new_items = doc_update.get("action_items") or []
            if new_items:
                existing = session._live_documentation.get("action_items", [])
                session._live_documentation["action_items"] = existing + new_items
        await ws.send_text(json.dumps({"type": "companion_update", **update}))
        return update
    except Exception as e:
        logger.error(f"Companion update error: {e}")
        return {}


async def _execute_approved_action(
    ws: WebSocket,
    action_name: str,
    payload: dict,
    execution_id: str,
    approved_by: str,
    call_id: str,
) -> None:
    """Execute an approved action: validate, run handler, audit log, notify frontend."""
    from orchestration.engine import execute_action
    from orchestration.action_registry import ActionExecutionError, ActionNotFoundError, WorkflowMismatchError
    from database import AsyncSessionLocal

    ts = datetime.now(timezone.utc).isoformat()

    # Emit "activity_event: approved" before execution (timeline UX)
    try:
        await ws.send_text(json.dumps({
            "type": "activity_event",
            "kind": "action_approved",
            "action": action_name,
            "message": f"Agent approved: {action_name.replace('_', ' ').title()}",
            "timestamp": ts,
        }))
    except Exception:
        pass

    # Enrich payload with customer_id from session if the LLM omitted it
    payload = dict(payload)
    if not payload.get("customer_id"):
        sess = ACTIVE_CALLS.get(call_id)
        if sess:
            profile = sess.customer_profile or {}
            cid = sess.customer_id or profile.get("customer_id")
            if cid:
                payload["customer_id"] = cid

    try:
        async with AsyncSessionLocal() as db:
            result = await execute_action(
                action_name=action_name,
                payload=payload,
                approved_by=approved_by,
                execution_id=execution_id,
                call_id=call_id,
                db=db,
            )

        # Mark action completed in session so companion won't re-suggest it
        sess = ACTIVE_CALLS.get(call_id)
        if sess:
            sess.completed_actions.add(action_name)

        # Collect any reference numbers generated by this action so the agent
        # can read them to the customer or record them in the case notes.
        _ref_keys = ("inc_number", "res_number", "rfn_number", "dsp_number",
                     "fraud_number", "case_number", "reference_number")
        reference_numbers = {k: result[k] for k in _ref_keys if result.get(k)}

        # Notify frontend: success
        await ws.send_text(json.dumps({
            "type": "action_result",
            "action": action_name,
            "success": True,
            "message": result.get("message", "Action completed successfully."),
            "updated_entities": result.get("updated_entities", {}),
            "reference_numbers": reference_numbers,
        }))

        # Emit executed event to activity timeline
        await ws.send_text(json.dumps({
            "type": "activity_event",
            "kind": "action_executed",
            "action": action_name,
            "message": result.get("message", ""),
            "timestamp": datetime.now(timezone.utc).isoformat(),
        }))

        logger.info("[%s] Action '%s' executed by %s", call_id, action_name, approved_by)

        # Re-fire companion so nudge updates to reflect the completed action
        sess = ACTIVE_CALLS.get(call_id)
        if sess:
            _tx = _build_transcript_from_session(sess)
            _customer = sess.customer_profile or {}
            asyncio.create_task(_send_companion_update(
                ws, _tx, _customer,
                handoff_bundle=sess.handoff_bundle,
                completed_actions=sess.completed_actions,
                session=sess,
            ))

    except (ActionNotFoundError, WorkflowMismatchError, ActionExecutionError) as exc:
        await ws.send_text(json.dumps({
            "type": "action_result",
            "action": action_name,
            "success": False,
            "message": str(exc),
        }))
        logger.warning("[%s] Action '%s' failed: %s", call_id, action_name, exc)
        # Re-fire companion even on failure so nudge updates with the error context
        sess = ACTIVE_CALLS.get(call_id)
        if sess:
            asyncio.create_task(_send_companion_update(
                ws, _build_transcript_from_session(sess), sess.customer_profile or {},
                handoff_bundle=sess.handoff_bundle,
                completed_actions=sess.completed_actions, session=sess,
            ))
    except Exception as exc:
        await ws.send_text(json.dumps({
            "type": "action_result",
            "action": action_name,
            "success": False,
            "message": f"Unexpected error — please try again.",
        }))
        logger.exception("[%s] Unexpected error in action '%s'", call_id, action_name)


def _build_transcript_from_session(sess) -> list[dict]:
    """Convert conversation_history (OpenAI format) to speaker/text list for companion + ACW."""
    lines = []
    for m in (getattr(sess, "conversation_history", None) or []):
        role    = m.get("role", "")
        content = m.get("content") or ""
        if not content or role == "system":
            continue
        speaker = "customer" if role == "user" else "fin"
        lines.append({"speaker": speaker, "text": content[:400]})
    return lines


async def _send_acw(
    ws: WebSocket,
    transcript: list[dict],
    customer: dict,
    call_id: str,
    handoff_bundle: dict | None = None,
) -> None:
    try:
        acw = await run_acw_agent(transcript, customer, call_id, handoff_bundle=handoff_bundle)
        await ws.send_text(json.dumps({"type": "acw_ready", **acw}))
    except Exception as e:
        logger.error(f"ACW generation error: {e}")


async def _persist_acw(call_id: str, acw: dict) -> None:
    """Persist ACW data — updates calls.acw_summary and resolution."""
    try:
        from database import AsyncSessionLocal
        from models.call import Call
        from sqlalchemy import update as sql_update
        import uuid

        async with AsyncSessionLocal() as db:
            await db.execute(
                sql_update(Call)
                .where(Call.id == uuid.UUID(call_id))
                .values(
                    acw_summary=acw.get("summary", ""),
                    resolution=acw.get("resolution", "unresolved"),
                    crm_updated=True,
                )
            )
            await db.commit()
        logger.info(f"ACW persisted for call {call_id}")
    except Exception as e:
        logger.error(f"ACW persist error: {e}")