-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket_handler.py
More file actions
2199 lines (2054 loc) · 112 KB
/
websocket_handler.py
File metadata and controls
2199 lines (2054 loc) · 112 KB
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""WebSocket handler — encapsulates the per-session async logic.
Extracted from ``server.websocket_endpoint()`` to reduce the monolithic
closure. All former nested functions are now async methods on
:class:`WebSocketHandler`; shared local state lives in ``SessionState``
(created by Phase 1).
"""
import asyncio
import base64
import json
import logging
import time
from datetime import datetime, timezone
from importlib.util import find_spec
from fastapi import WebSocket, WebSocketDisconnect
from google.adk.agents.live_request_queue import LiveRequestQueue
from google.adk.runners import Runner
from google.genai import types
from starlette.websockets import WebSocketState
from api.utils import _coerce_bool, _json_safe
from app_globals import (
_NEEDS_SESSION_ID_MAPPING,
AGENT_TEXT_REPEAT_SUPPRESS_SEC,
FACE_LIBRARY_REFRESH_SEC,
OCR_PREFEEDBACK_COOLDOWN_SEC,
OCR_REPEAT_SUPPRESS_SEC,
PASSIVE_SPEECH_GUARD_SEC,
SESSION_TIMEOUT_SEC,
VISION_PREFEEDBACK_COOLDOWN_SEC,
VISION_REPEAT_SUPPRESS_SEC,
WS_INACTIVITY_TIMEOUT_SEC,
MessageType,
_face_available,
_memory_available,
_memory_extractor_available,
_ocr_available,
_vision_available,
session_manager,
)
from context.spatial_change_detector import SpatialChangeDetector
from context_injection import ContextInjectionQueue, ModelState, TokenBudgetMonitor
from dispatch.tool_dispatcher import (
_dispatch_function_call as _dispatch_function_call_impl,
)
from dispatch.tool_dispatcher import _extract_function_calls
from formatters import (
_INTERNAL_TAG_RE,
_format_face_results,
_format_ocr_result,
_format_vision_result,
)
from intent.voice_intent import (
_allow_navigation_tool_call,
_detect_voice_intent,
_has_location_query_intent,
_has_navigation_intent,
_is_repeated_text,
_recent_user_utterances,
_should_reset_interrupted_on_activity_start,
)
from live_api.direct_intents import (
DirectIntentMixin,
)
from live_api.direct_intents import (
tool_preference_hint as _tool_preference_hint,
)
from live_api.direct_intents import (
tool_result_fallback_text as _tool_result_fallback_text,
)
from live_api.downstream_recovery import (
compute_retry_backoff,
flatten_exception_text,
is_retryable_transport_error,
)
from live_api.tts_fallback import (
synthesize_local_pcm as synthesize_local_fallback_pcm,
)
from live_api.tts_fallback import (
synthesize_pcm as synthesize_fallback_pcm,
)
from lod import (
build_full_dynamic_prompt,
build_lod_update_message,
decide_lod,
on_lod_change,
)
from lod.lod_engine import should_speak
from session_state import SessionState
from telemetry.signature import (
TELEMETRY_FORCE_REFRESH_SEC,
_build_telemetry_signature,
_changed_signature_fields,
_should_inject_telemetry_context,
)
from telemetry.telemetry_parser import parse_telemetry, parse_telemetry_to_ephemeral
from tools import ALL_FUNCTIONS, build_tool_manifest_entries
from tools.navigation import NAVIGATION_FUNCTIONS
from tools.ocr_tool import clear_session as _ocr_clear_session
from tools.ocr_tool import set_latest_frame as _ocr_set_latest_frame
from tools.tool_behavior import ToolBehavior, behavior_to_text, resolve_tool_behavior
logger = logging.getLogger("sightline.server")
_STALE_QUEUE_CATEGORIES = {
"echo_cancel",
"face",
"lod",
"lod_resume",
"ocr",
"telemetry",
"vad",
"vision",
}
_SILENT_TURN_WATCHDOG_SEC = 18.0
_LIVE_SESSION_READY_TIMEOUT_SEC = 60.0
async def _dispatch_function_call(func_name: str, func_args: dict, session_id: str, user_id: str) -> dict:
return await _dispatch_function_call_impl(
func_name,
func_args,
session_id,
user_id,
session_manager=session_manager,
)
class WebSocketHandler(DirectIntentMixin):
"""Manages a single WebSocket session's upstream/downstream lifecycle.
All former nested functions from ``websocket_endpoint()`` live here as
async methods. Per-session mutable state is held in a ``SessionState``
dataclass instance (``self.state``).
"""
def __init__(
self,
*,
websocket: WebSocket,
user_id: str,
session_id: str,
state: SessionState,
live_request_queue: LiveRequestQueue,
runner: Runner,
ctx_queue: ContextInjectionQueue,
token_monitor: TokenBudgetMonitor,
session_ctx,
session_meta,
user_profile,
telemetry_agg,
stop_downstream: asyncio.Event,
tool_dedup,
tool_mutex,
audio_gate,
run_config,
location_ctx_service,
lod_evaluator,
assembled_profile,
memory_budget,
initial_memories: list | None = None,
resume_requested: bool = False,
) -> None:
self.websocket = websocket
self.user_id = user_id
self.session_id = session_id
self.state = state
self.live_request_queue = live_request_queue
self.runner = runner
self.ctx_queue = ctx_queue
self.token_monitor = token_monitor
self.session_ctx = session_ctx
self.session_meta = session_meta
self.user_profile = user_profile
self.telemetry_agg = telemetry_agg
self.stop_downstream = stop_downstream
self.tool_dedup = tool_dedup
self.tool_mutex = tool_mutex
self.audio_gate = audio_gate
self.run_config = run_config
self._location_ctx_service = location_ctx_service
self._lod_evaluator = lod_evaluator
self._assembled_profile = assembled_profile
self.memory_budget = memory_budget
self._initial_memories = initial_memories or []
self._response_watchdog_task: asyncio.Task | None = None
self._resume_requested = resume_requested
self._pending_resume_context: str | None = None
self._downstream_ready = asyncio.Event()
self._downstream_init_error: Exception | None = None
self._spatial_detector = SpatialChangeDetector()
def _current_run_config(self):
language_code = getattr(self.user_profile, "language", "") or ""
self.run_config = session_manager.get_run_config(
self.session_id,
lod=self.session_ctx.current_lod,
language_code=language_code,
)
return self.run_config
def _is_stale_turn(self, origin_turn_seq: int | None) -> bool:
return origin_turn_seq is not None and origin_turn_seq < self.state.user_turn_seq
def _register_user_activity(
self,
*,
explicit_turn_start: bool = False,
source: str = "generic",
) -> bool:
"""Mark fresh user activity and discard queued context from older turns."""
now_mono = time.monotonic()
idle_gap = now_mono - self.state.last_user_activity_at
hinted_turn_continues = (
explicit_turn_start
and source == "activity_start"
and self.state.last_text_hint_at > 0
and (now_mono - self.state.last_text_hint_at) <= self.state.USER_TURN_GAP_SEC
)
is_new_turn = (explicit_turn_start or idle_gap >= self.state.USER_TURN_GAP_SEC) and not hinted_turn_continues
self.state.last_user_activity_at = now_mono
if not is_new_turn:
return False
self.state.user_turn_seq += 1
self.state.turn_output_seen = False
self.state.turn_audio_output_seen = False
self.state.latest_agent_transcript_for_turn = ""
self.state.pending_fallback_text = None
self.state.pending_fallback_turn_seq = self.state.user_turn_seq
self.state.recent_agent_texts.clear()
self._schedule_response_watchdog(self.state.user_turn_seq)
discard_stale = getattr(self.ctx_queue, "discard_stale", None)
if callable(discard_stale):
discard_stale(
min_turn_seq=self.state.user_turn_seq,
categories=_STALE_QUEUE_CATEGORIES,
)
return True
def _should_reconnect_silent_turn(self) -> bool:
return self.state.user_turn_seq > 0 and not self.state.turn_output_seen
def _cancel_response_watchdog(self) -> None:
if self._response_watchdog_task is not None:
self._response_watchdog_task.cancel()
self._response_watchdog_task = None
def _schedule_response_watchdog(
self,
turn_seq: int,
*,
delay_sec: float = _SILENT_TURN_WATCHDOG_SEC,
) -> None:
self._cancel_response_watchdog()
try:
asyncio.get_running_loop()
except RuntimeError:
return
self._response_watchdog_task = asyncio.create_task(
self._response_watchdog(turn_seq, delay_sec)
)
async def _response_watchdog(self, turn_seq: int, delay_sec: float) -> None:
try:
await asyncio.sleep(delay_sec)
if self.stop_downstream.is_set():
return
if turn_seq != self.state.user_turn_seq:
return
if self.state.turn_output_seen:
return
if await self._emit_pending_fallback_output(turn_seq):
return
if self._is_current_turn_farewell():
await self._emit_local_agent_response(
"You're welcome. Goodbye for now.",
source="farewell_fallback",
)
return
fallback_text = self._silent_turn_fallback_text()
if fallback_text:
logger.warning(
"No client-visible output for turn %d within %.1fs; emitting local fallback instead of reconnect",
turn_seq,
delay_sec,
)
await self._emit_local_agent_response(
fallback_text,
source="silent_turn_fallback",
)
return
logger.warning(
"No client-visible output for turn %d within %.1fs; requesting reconnect",
turn_seq,
delay_sec,
)
await self._safe_send_json({
"type": MessageType.GO_AWAY,
"retry_ms": 750,
"message": "No response generated for the last turn. Reconnecting.",
})
self.stop_downstream.set()
try:
await self.websocket.close(code=1012, reason="silent_turn_watchdog")
except Exception:
pass
except asyncio.CancelledError:
return
async def _emit_pending_fallback_output(self, turn_seq: int) -> bool:
if not (
self.state.pending_fallback_text
and self.state.pending_fallback_turn_seq == turn_seq
):
return False
fallback_text = self.state.pending_fallback_text
pcm = b""
try:
pcm = await synthesize_fallback_pcm(fallback_text)
except Exception:
logger.exception("Fallback TTS synthesis failed")
sent = await self._safe_send_json({
"type": MessageType.TRANSCRIPT,
"text": fallback_text,
"role": "agent",
"source": "tool_fallback",
})
if not sent:
return False
if pcm:
await self._safe_send_bytes(pcm)
self.state.turn_output_seen = True
self.state.pending_fallback_text = None
self._cancel_response_watchdog()
logger.info("Emitted tool-result fallback output for turn %d", turn_seq)
return True
async def _emit_local_agent_response(self, text: str, *, source: str) -> bool:
clean = (text or "").strip()
if not clean:
return False
sent = await self._safe_send_json({
"type": MessageType.TRANSCRIPT,
"text": clean,
"role": "agent",
"source": source,
})
if not sent:
return False
self.state.latest_agent_transcript_for_turn = clean
self.state.turn_output_seen = True
try:
pcm = await synthesize_local_fallback_pcm(clean)
except Exception:
logger.exception("Local agent-response TTS synthesis failed")
return sent
if pcm:
await self._safe_send_bytes(pcm)
return sent
async def _emit_prefeedback_output(self, text: str) -> bool:
return await self._emit_local_agent_response(text, source="prefeedback")
# ── Main entry point ───────────────────────────────────────────────
async def run(self) -> None:
"""Run the upstream/downstream loop until the session ends.
Sends session_ready, tools_manifest, and the initial greeting/context
before starting the upstream/downstream tasks.
"""
downstream_task = asyncio.create_task(self._downstream())
try:
await asyncio.wait_for(
self._downstream_ready.wait(),
timeout=_LIVE_SESSION_READY_TIMEOUT_SEC,
)
except asyncio.TimeoutError:
logger.error(
"Timed out waiting for Live session init: user=%s session=%s",
self.user_id, self.session_id,
)
downstream_task.cancel()
try:
await downstream_task
except (asyncio.CancelledError, Exception):
pass
await self._safe_send_json({
"type": MessageType.ERROR,
"error": "Live session initialization timed out. Please retry.",
})
await self._cleanup()
return
if self._downstream_init_error is not None:
logger.exception(
"Live session init failed before session_ready: user=%s session=%s",
self.user_id, self.session_id,
exc_info=self._downstream_init_error,
)
await self._safe_send_json({
"type": MessageType.ERROR,
"error": "Failed to initialize live session. Please retry.",
})
await self._cleanup()
return
# Notify client the WebSocket is live
if not await self._safe_send_json({"type": MessageType.SESSION_READY}):
logger.info(
"WebSocket closed before session_ready: user=%s session=%s",
self.user_id, self.session_id,
)
downstream_task.cancel()
try:
await downstream_task
except (asyncio.CancelledError, Exception):
pass
await self._cleanup()
return
asyncio.create_task(self.session_meta.write_session_start())
# Send tools manifest so iOS Dev Console shows tool/context status
await self._safe_send_json(self._build_tools_manifest())
_initial_prompt = build_full_dynamic_prompt(
lod=self.session_ctx.current_lod,
profile=self.user_profile,
ephemeral_semantic="",
session=self.session_ctx,
memories=self._initial_memories if self._initial_memories else None,
assembled_profile=self._assembled_profile,
)
if self._resume_requested:
self._pending_resume_context = (
"[CONTEXT UPDATE - DO NOT SPEAK]\n"
+ _initial_prompt
+ "\n\n[SESSION RESUME] This session has resumed after an interruption. "
"Do not greet again. Continue helping with the user's current request "
"or wait silently for their next input."
)
logger.info(
"Resume requested for session %s; queued silent resume context for next user turn",
self.session_id,
)
else:
# Inject combined context (LOD + greeting) so model speaks once
_greeting_parts: list[str] = [
"[SESSION START] Greet the user briefly (1-2 sentences).",
"Let them know you're ready to help.",
]
if self.user_profile and self.user_profile.preferred_name:
_greeting_parts.append(
f"Address them as '{self.user_profile.preferred_name}'."
)
_greeting_parts.append("Keep it natural and concise — no instructions or tutorials.")
_combined_content = types.Content(
parts=[
types.Part(text="[CONTEXT UPDATE - DO NOT SPEAK]\n" + _initial_prompt),
types.Part(text=" ".join(_greeting_parts)),
],
role="user",
)
self.ctx_queue.inject_immediate(_combined_content)
logger.info(
"Injected combined context (LOD %d) + greeting for session %s",
self.session_ctx.current_lod, self.session_id,
)
if self.state.face_library_task is not None:
self.state.face_library_refresh_task = asyncio.create_task(
self._finish_initial_face_library_load()
)
try:
upstream_task = asyncio.create_task(self._upstream())
done, pending = await asyncio.wait(
[upstream_task, downstream_task],
timeout=SESSION_TIMEOUT_SEC,
return_when=asyncio.FIRST_COMPLETED,
)
self.stop_downstream.set()
for task in pending:
task.cancel()
try:
await task
except (asyncio.CancelledError, Exception):
pass
for task in done:
if task.exception() and not isinstance(
task.exception(), asyncio.CancelledError
):
logger.exception(
"Session task failed: user=%s session=%s",
self.user_id, self.session_id,
exc_info=task.exception(),
)
except asyncio.TimeoutError:
logger.info(
"Session timeout (%ds): user=%s session=%s",
SESSION_TIMEOUT_SEC, self.user_id, self.session_id,
)
except Exception:
logger.exception(
"Session error: user=%s session=%s",
self.user_id, self.session_id,
)
finally:
await self._cleanup()
async def _cleanup(self) -> None:
"""Post-session cleanup: extract memories, write metadata, release resources."""
self._cancel_response_watchdog()
if _memory_extractor_available and _memory_available and self.state.transcript_history:
try:
from memory.memory_bank import MemoryBankService
from memory.memory_budget import MemoryBudgetTracker
from memory.memory_extractor import MemoryExtractor
extractor = MemoryExtractor()
bank = MemoryBankService(self.user_id)
budget = self.memory_budget or MemoryBudgetTracker()
count = await asyncio.to_thread(
extractor.extract_and_store,
user_id=self.user_id,
session_id=self.session_id,
transcript_history=list(self.state.transcript_history),
memory_bank=bank,
budget=budget,
)
logger.info(
"Auto-extracted %d memories for user=%s session=%s",
count, self.user_id, self.session_id,
)
except Exception:
logger.exception(
"Memory auto-extraction failed for user=%s session=%s",
self.user_id, self.session_id,
)
try:
if self.state.current_location_ctx:
place = getattr(self.state.current_location_ctx, "place_name", "")
if place and place not in self.session_meta.locations_visited:
self.session_meta.locations_visited.append(place)
except Exception:
logger.debug("ACE session end data failed", exc_info=True)
self.session_meta.space_transitions = list(self.session_ctx.space_transitions)
self.session_meta.set_trip_purpose(self.session_ctx.trip_purpose or "")
await self.session_meta.write_session_end()
self.ctx_queue.stop()
self.live_request_queue.close()
_ocr_clear_session(self.session_id)
session_manager.remove_session(self.session_id)
if _memory_available:
from memory.memory_bank import evict_stale_banks
evict_stale_banks(max_age_sec=SESSION_TIMEOUT_SEC)
logger.info("Session cleaned up: user=%s session=%s", self.user_id, self.session_id)
# ── Transcript helpers ─────────────────────────────────────────────
def _has_sentence_boundary(self, text: str) -> bool:
return bool(self.state.SENTENCE_BOUNDARY_RE.search(text))
async def _flush_transcript_buffer(self) -> bool:
text = self.state.transcript_buffer.strip()
self.state.transcript_buffer = ""
self.state.transcript_buffer_started_at = 0.0
if not text:
return True
now_mono = time.monotonic()
self.state.recent_agent_texts.append((now_mono, text))
cutoff = now_mono - 10.0
while self.state.recent_agent_texts and self.state.recent_agent_texts[0][0] < cutoff:
self.state.recent_agent_texts.pop(0)
return await self._forward_agent_transcript(text)
def _is_websocket_open(self) -> bool:
return (
self.websocket.client_state == WebSocketState.CONNECTED
and self.websocket.application_state == WebSocketState.CONNECTED
)
async def _safe_send_json(self, payload: dict) -> bool:
if not self._is_websocket_open():
self.stop_downstream.set()
return False
try:
async with self.state.ws_write_lock:
await self.websocket.send_json(payload)
return True
except (WebSocketDisconnect, RuntimeError):
self.stop_downstream.set()
return False
async def _safe_send_prioritized_bytes(self, pcm: bytes, priority: int) -> bool:
"""Send PCM audio with priority tag. Format: [0x03, priority_byte, ...pcm_data]."""
header = bytes([0x03, priority])
return await self._safe_send_bytes(header + pcm)
async def _safe_send_bytes(self, payload: bytes) -> bool:
if not self._is_websocket_open():
self.stop_downstream.set()
return False
try:
async with self.state.ws_write_lock:
await self.websocket.send_bytes(payload)
if payload and self.state.user_turn_seq > 0:
self.state.turn_output_seen = True
self.state.turn_audio_output_seen = True
self.state.pending_fallback_text = None
self._cancel_response_watchdog()
return True
except (WebSocketDisconnect, RuntimeError):
self.stop_downstream.set()
return False
async def _forward_agent_transcript(self, text: str) -> bool:
now_mono = time.monotonic()
can_repeat = now_mono <= self.state.allow_agent_repeat_until
is_repeat = _is_repeated_text(
text,
previous_text=self.state.last_agent_text,
now_ts=now_mono,
previous_ts=self.state.last_agent_text_sent_at,
cooldown_sec=AGENT_TEXT_REPEAT_SUPPRESS_SEC,
)
if is_repeat and not can_repeat:
logger.debug("Suppressed repeated downstream transcript: %s", text[:120])
return True
clean_text = _INTERNAL_TAG_RE.sub("", text).strip()
if not clean_text:
return True
sent = await self._safe_send_json({
"type": MessageType.TRANSCRIPT,
"text": clean_text,
"role": "agent",
})
if sent:
self.state.last_agent_text = clean_text
self.state.last_agent_text_sent_at = now_mono
self.state.latest_agent_transcript_for_turn = clean_text
if self.state.user_turn_seq > 0:
self.state.turn_output_seen = True
self.state.pending_fallback_text = None
self._cancel_response_watchdog()
return sent
def _is_likely_echo(self, candidate: str, now_ts: float) -> bool:
words_candidate = set(candidate.lower().split())
model_speaking = (now_ts - self.state.model_audio_last_seen_at) < 3.0
min_words = 1 if model_speaking else 3
jaccard_threshold = 0.35 if model_speaking else 0.6
window_sec = 8.0 if model_speaking else 5.0
if len(words_candidate) < min_words:
return False
cutoff = now_ts - window_sec
for ts, agent_text in reversed(self.state.recent_agent_texts):
if ts < cutoff:
break
words_agent = set(agent_text.lower().split())
if not words_agent:
continue
intersection = words_candidate & words_agent
union = words_candidate | words_agent
jaccard = len(intersection) / len(union) if union else 0.0
if jaccard > jaccard_threshold:
return True
return False
# ── Event emitters ─────────────────────────────────────────────────
async def _emit_tool_event(self, tool: str, behavior, *, status: str, data: dict | None = None) -> None:
payload: dict = {
"type": MessageType.TOOL_EVENT,
"tool": tool,
"behavior": behavior_to_text(behavior),
"status": status,
}
if data:
payload["data"] = _json_safe(data)
await self._safe_send_json(payload)
# Thinking sound lifecycle: start on invoked, stop on completed/error
if status == "invoked":
sound_state = "thinking" if tool == "analyze_scene" else "searching"
await self._safe_send_json({"type": "thinking_sound", "state": sound_state, "tool": tool})
elif status in ("completed", "error", "unavailable"):
await self._safe_send_json({"type": "thinking_sound", "state": "idle"})
async def _emit_capability_degraded(self, capability: str, reason: str, recoverable: bool = True) -> None:
await self._safe_send_json({
"type": MessageType.CAPABILITY_DEGRADED,
"capability": capability,
"reason": reason,
"recoverable": recoverable,
})
async def _emit_identity_event(self, *, person_name: str, matched: bool, similarity: float = 0.0, source: str = "face_pipeline") -> None:
payload = {
"type": MessageType.IDENTITY_UPDATE,
"person_name": person_name,
"matched": matched,
"similarity": similarity,
"source": source,
"behavior": behavior_to_text(ToolBehavior.SILENT),
}
await self._safe_send_json(payload)
if matched:
await self._safe_send_json({
"type": MessageType.PERSON_IDENTIFIED,
"person_name": person_name,
"similarity": similarity,
"source": source,
"behavior": behavior_to_text(ToolBehavior.SILENT),
})
# ── Face library helpers ───────────────────────────────────────────
async def _finish_initial_face_library_load(self) -> None:
if self.state.face_library_task is None:
return
try:
loaded = await self.state.face_library_task
self.state.face_library = loaded
self.state.face_library_loaded_at = time.monotonic()
logger.info("Loaded %d face(s) for user %s", len(self.state.face_library), self.user_id)
except Exception:
logger.exception("Failed to load face library for user %s", self.user_id)
finally:
self.state.face_library_task = None
self.state.face_library_refresh_task = None
async def _refresh_face_library_background(self) -> None:
try:
from tools.face_tools import load_face_library
refreshed = await asyncio.to_thread(load_face_library, self.user_id)
self.state.face_library = refreshed
self.state.face_library_loaded_at = time.monotonic()
logger.info("Refreshed face library (%d faces) for user %s", len(self.state.face_library), self.user_id)
except Exception:
logger.exception("Failed to refresh face library for user %s", self.user_id)
finally:
self.state.face_library_refresh_task = None
async def _inject_face_memories(self, known_faces: list[dict]) -> None:
if not _memory_available:
return
from memory.memory_bank import load_relevant_memories
names = [
str(face.get("person_name", "")).strip()
for face in known_faces
if str(face.get("person_name", "")).strip() and face.get("person_name") != "unknown"
]
if not names:
return
memory_tasks = [
asyncio.to_thread(load_relevant_memories, self.user_id, f"person {name}", 2)
for name in names
]
results = await asyncio.gather(*memory_tasks, return_exceptions=True)
memory_lines: list[str] = []
for name, result in zip(names, results, strict=False):
if isinstance(result, Exception):
logger.debug("Failed to load memories for person %s", name, exc_info=True)
continue
if not result:
continue
memory_lines.append(f"{name}:")
memory_lines.extend(f"- {memory}" for memory in result)
if not memory_lines:
return
self.ctx_queue.enqueue(
category="face_memory",
text="[FACE MEMORY]\n" + "\n".join(memory_lines),
priority=3,
speak=False,
)
# ── Tools manifest ─────────────────────────────────────────────────
def _build_tools_manifest(self) -> dict:
tools_list = build_tool_manifest_entries(
lod=self.session_ctx.current_lod,
is_user_speaking=self.session_ctx.current_activity_state == "user_speaking",
)
_entity_graph_available = find_spec("context.entity_graph") is not None
context_modules = [
{"name": "LocationContext", "status": "ready" if self._location_ctx_service is not None else "unavailable"},
{"name": "LODEvaluator", "status": "ready" if self._lod_evaluator is not None else "unavailable"},
{"name": "ProfileAssembler", "status": "ready" if self._assembled_profile is not None else "unavailable"},
{"name": "HabitDetector", "status": "ready" if self.state.proactive_hints is not None else "unavailable"},
{"name": "SceneMatcher", "status": "ready" if self._location_ctx_service is not None else "unavailable"},
{"name": "EntityGraph", "status": "ready" if _entity_graph_available else "unavailable"},
]
return {
"type": MessageType.TOOLS_MANIFEST,
"tools": tools_list,
"context_modules": context_modules,
"sub_agents": {
"vision": "ready",
"ocr": "ready",
"face": "ready" if _face_available else "unavailable",
},
}
# ── LOD helpers ────────────────────────────────────────────────────
async def _send_lod_update(self, new_lod: int, ephemeral_ctx, reason: str) -> None:
memories = await self._load_session_memories(
context_hint=self.session_ctx.active_task or self.session_ctx.trip_purpose or ""
)
lod_message = build_lod_update_message(
lod=new_lod,
ephemeral=ephemeral_ctx,
session=self.session_ctx,
profile=self.user_profile,
reason=reason,
memories=memories,
assembled_profile=self._assembled_profile,
location_ctx=self.state.current_location_ctx,
)
self.ctx_queue.enqueue(
category="lod",
text=lod_message,
priority=3,
speak=False,
turn_seq=self.state.user_turn_seq,
)
logger.info("Injected [LOD UPDATE] -> LOD %d (%s)", new_lod, reason)
async def _load_session_memories(self, context_hint: str = "") -> list[str]:
try:
if _memory_available:
from memory.memory_bank import MemoryBankService
def _retrieve_memories_sync(hint: str) -> list[dict]:
bank = MemoryBankService(self.user_id)
return bank.retrieve_memories(hint, top_k=3)
raw_results = await asyncio.to_thread(_retrieve_memories_sync, context_hint)
self.state.memory_top3 = [m["content"] for m in raw_results][:3]
self.state.memory_top3_detailed = [{
"content": m.get("content", "")[:120],
"category": m.get("category", "general"),
"importance": round(float(m.get("importance", 0.5)), 2),
"score": round(float(m.get("_composite_score", 0)), 3),
} for m in raw_results][:3]
return self.state.memory_top3
return []
except Exception:
logger.exception("Failed to load memories for user %s", self.user_id)
return []
async def _sync_runtime_vad_update(self, new_lod: int) -> dict:
from live_api.session_manager import (
build_vad_runtime_update_message,
build_vad_runtime_update_payload,
supports_runtime_vad_reconfiguration,
)
supported, reason = supports_runtime_vad_reconfiguration()
payload = build_vad_runtime_update_payload(new_lod)
payload["runtime_hot_reconfig_supported"] = supported
payload["runtime_note"] = "transport_hot_update_applied" if supported else reason
self.ctx_queue.enqueue(
category="vad",
text=build_vad_runtime_update_message(new_lod),
priority=7,
speak=False,
turn_seq=self.state.user_turn_seq,
)
if supported:
logger.info("Injected runtime VAD update payload for LOD %d: %s", new_lod, payload)
else:
logger.warning("Runtime VAD transport hot-update unavailable (%s); injected sync marker only: %s", reason, payload)
return payload
async def _notify_ios_lod_change(self, new_lod: int, reason: str, debug_dict: dict, vad_update: dict | None = None) -> None:
await self._safe_send_json({"type": MessageType.LOD_UPDATE, "lod": new_lod, "reason": reason})
debug_dict["memory_top3"] = self.state.memory_top3
debug_dict["memory_top3_detailed"] = self.state.memory_top3_detailed
if vad_update:
debug_dict["vad_update"] = vad_update
await self._safe_send_json({"type": MessageType.DEBUG_LOD, "data": debug_dict})
async def _emit_activity_debug_event(self, *, event_name: str, queue_status: str, queue_note: str = "", source: str = "ios_client") -> None:
ts = datetime.now(timezone.utc)
is_activity_start = event_name == "activity_start"
self.session_ctx.current_activity_state = "user_speaking" if is_activity_start else "idle"
self.session_ctx.last_activity_event = event_name
self.session_ctx.last_activity_event_ts = ts
self.session_ctx.last_activity_source = source
self.session_ctx.activity_event_count += 1
await self._safe_send_json({
"type": MessageType.DEBUG_ACTIVITY,
"data": {
"event": event_name,
"state": self.session_ctx.current_activity_state,
"source": source,
"queue_status": queue_status,
"queue_note": queue_note,
"timestamp": ts.isoformat(),
"event_count": self.session_ctx.activity_event_count,
},
})
# ── Sub-agent runners ──────────────────────────────────────────────
async def _run_vision_analysis(
self,
image_base64: str,
origin_turn_seq: int | None = None,
) -> None:
if not _vision_available:
await self._emit_tool_event("analyze_scene", ToolBehavior.WHEN_IDLE, status="unavailable", data={"reason": "vision_agent_unavailable"})
return
async with self.state.vision_lock:
if self.state.vision_in_progress:
return
self.state.vision_in_progress = True
now_mono = time.monotonic()
if self.state.camera_activated_at > 0 and (now_mono - self.state.camera_activated_at) < self.state.CAMERA_GRACE_PERIOD_SEC:
logger.info("Suppressed vision: camera activation grace period (%.1fs)", now_mono - self.state.camera_activated_at)
async with self.state.vision_lock:
self.state.vision_in_progress = False
return
if (now_mono - self.state.last_vision_prefeedback_at >= VISION_PREFEEDBACK_COOLDOWN_SEC
and (self.state.camera_activated_at <= 0 or now_mono - self.state.camera_activated_at >= self.state.CAMERA_GRACE_PERIOD_SEC)
and not self.ctx_queue.vision_spoken_cooldown_active
and not self.state.first_vision_after_camera):
await self._emit_prefeedback_output("Let me look at that for you...")
self.state.last_vision_prefeedback_at = now_mono
try:
from agents.vision_agent import analyze_scene
ephemeral_ctx = session_manager.get_ephemeral_context(self.session_id)
ctx_dict = {
"space_type": self.session_ctx.space_type,
"trip_purpose": self.session_ctx.trip_purpose,
"active_task": self.session_ctx.active_task,
"motion_state": ephemeral_ctx.motion_state,
"has_guide_dog": self.user_profile.has_guide_dog,
"depth_center": getattr(ephemeral_ctx, "depth_center", None),
"depth_min": getattr(ephemeral_ctx, "depth_min", None),
"depth_min_region": getattr(ephemeral_ctx, "depth_min_region", None),
"depth_quadrants": getattr(ephemeral_ctx, "depth_quadrants", None),
}
result = await analyze_scene(image_base64, self.session_ctx.current_lod, ctx_dict)
if self._is_stale_turn(origin_turn_seq):
logger.info(
"Dropping stale vision result from turn %s (current=%d)",
origin_turn_seq,
self.state.user_turn_seq,
)
await self._emit_tool_event(
"analyze_scene",
ToolBehavior.WHEN_IDLE,
status="stale",
data={
"origin_turn_seq": origin_turn_seq,
"current_turn_seq": self.state.user_turn_seq,
},
)
return
result_status = str(result.get("status", "ok")).lower()
if result_status in {"unavailable", "timeout"}:
await self._emit_tool_event("analyze_scene", ToolBehavior.WHEN_IDLE, status="unavailable" if result_status == "unavailable" else "error", data={"reason": f"vision_{result_status}"})
await self._emit_capability_degraded("vision", f"vision_{result_status}")
return
vision_text = _format_vision_result(result, self.session_ctx.current_lod)
now_mono = time.monotonic()
repeated = _is_repeated_text(vision_text, previous_text=self.state.last_vision_context_text, now_ts=now_mono, previous_ts=self.state.last_vision_context_sent_at, cooldown_sec=VISION_REPEAT_SUPPRESS_SEC)
if not repeated:
await self._safe_send_json({"type": MessageType.VISION_RESULT, "summary": result.get("scene_description", ""), "behavior": behavior_to_text(ToolBehavior.WHEN_IDLE), "data": _json_safe(result)})
self.state.last_vision_context_text = vision_text
self.state.last_vision_context_sent_at = now_mono
else:
logger.debug("Suppressed repeated vision summary within %.1fs window", VISION_REPEAT_SUPPRESS_SEC)
await self._safe_send_json({"type": MessageType.VISION_DEBUG, "data": {"bounding_boxes": _json_safe(result.get("bounding_boxes", [])), "confidence": float(result.get("confidence", 0.0)), "lod": self.session_ctx.current_lod}})
await self._emit_tool_event("analyze_scene", ToolBehavior.WHEN_IDLE, status="completed", data={"confidence": float(result.get("confidence", 0.0)), "repeat_suppressed": repeated})
# Spatial change detection — may override speak decision
_prev_vision = {
"safety_warnings": self.state.last_vision_safety_warnings,
"people_count": self.state.last_vision_people_count,