forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent-continuity-gauntlet-lib.py
More file actions
executable file
·4778 lines (4452 loc) · 201 KB
/
Copy pathagent-continuity-gauntlet-lib.py
File metadata and controls
executable file
·4778 lines (4452 loc) · 201 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
#!/usr/bin/env python3
"""Driver for the desktop agent continuity gauntlet (INV-6)."""
from __future__ import annotations
import argparse
import ast
import hashlib
import http.client
import json
import math
import os
import re
import secrets
import shutil
import socket
import sqlite3
import struct
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
SCRIPT_DIR = Path(__file__).resolve().parent
DESKTOP_DIR = SCRIPT_DIR.parent
DEFAULT_PORT = int(os.environ.get("OMI_AUTOMATION_PORT", "47777"))
TRACE_LOG = Path.home() / "Library/Logs/Omi/traces.jsonl"
DEFAULT_BUNDLE_SUFFIX = "omi-gauntlet"
GAUNTLET_ROOT = DESKTOP_DIR / ".harness/agent-continuity-gauntlet"
PRUNE_ABORTED_BUNDLE_DAYS = 7
RESILIENCE_DIAGNOSTIC_SCHEMA_VERSION = 1
AUTOMATION_UI_PRESENTATION_ACTION = "set_automation_ui_presentation"
if str(SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIR))
from automation_token_lib import ( # noqa: E402
automation_token as _shared_automation_token,
automation_token_missing_message,
)
RESILIENCE_FORBIDDEN_TERMINAL_REASONS = {
"bridge_launch_error",
"generic_chat_error",
"no_assistant_response",
"no_query_trace",
"response_already_running",
"response_stopped",
"skipped_missing_action",
"skipped_unimplemented_action",
"subagent_missing",
"subagent_status_invisible",
}
RESILIENCE_GENERIC_CHAT_PATTERNS = {
"AI not available",
"AI is not running",
"AI stopped unexpectedly",
"AI took too long to respond",
"A response is already running for this chat",
"Response stopped",
"requestAlreadyActive",
"response_already_running",
}
EXACT_VOICE_AGENT_MEMORY_REQUEST = (
"Have an agent look through my memories today and surface one surprising insight."
)
EXACT_VOICE_AGENT_MEMORY_FOLLOWUP = (
"Continue in this same agent session. Call get_memories again for today, then "
"return one additional surprising insight. Do not spawn another agent."
)
TERMINAL_RUN_STATUSES = {"succeeded", "failed", "cancelled", "orphaned"}
AGENT_CHILD_SURFACES = {
"background_agent",
"delegated_agent",
"floating_bar",
"floating_pill",
}
CONVERGENCE_FORBIDDEN_EVIDENCE_PATTERNS = {
"unrouted_tool_call",
"malformed jsonl",
"malformed_jsonl",
"invalid json:",
"malformed_external_surface",
"malformed_authorized_execution",
"legacy_tool_authorization",
"legacy_path_invoked",
"legacy-path invoked",
"legacy path invoked",
"agentdelegationresolver",
"agentpillsmanager.classify",
}
def now_iso() -> str:
return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
def bridge_action_timeout_sec(
name: str,
params: dict[str, str] | None,
turn_timeout_ms: int,
) -> float:
"""HTTP client timeout for bridge actions that may block for a full turn."""
params = params or {}
turn_sec = max(190.0, (turn_timeout_ms / 1000.0) + 10.0)
if name == "ptt_test_turn":
# The controller may redrive the turn once after a mid-turn session swap,
# so the worst case is two full turn deadlines plus warm-up slack.
action_sec = float(params.get("timeout", "0"))
return max(turn_sec, 2.0 * action_sec + 40.0)
if name == "wait_main_chat_idle":
wait_ms = int(params.get("timeoutMs", "2000"))
if wait_ms >= 30_000:
return max(turn_sec, (wait_ms / 1000.0) + 10.0)
if name in {
"ask_main_chat",
"coordinator_continue_agent",
"coordinator_inspect_run",
"quit_and_reopen",
"swap_test_owner",
"kernel_turn_tail",
}:
return turn_sec
return 60.0
class AutomationTokenError(RuntimeError):
"""Token file exists but cannot be read (permissions/encoding). Fail closed."""
def automation_token(port: int) -> str | None:
"""Load the per-launch bridge bearer token (same contract as omi-ctl).
Missing token file → None (caller may proceed unauthenticated or fail later).
Unreadable/corrupt token file → AutomationTokenError (fail closed; do not
silently omit Authorization).
Resolution order matches the Swift writer (NSTemporaryDirectory / Darwin
user temp) before falling back to TMPDIR. Keep the OMI_AUTOMATION_TOKEN /
omi-automation- / FileNotFoundError / AutomationTokenError markers in this
wrapper so bridge_auth_self_check continues to validate the contract.
"""
# Self-check needles (must remain literal in this function body):
_ = "OMI_AUTOMATION_TOKEN"
_ = "omi-automation-"
try:
return _shared_automation_token(port, fail_closed_unreadable=True)
except FileNotFoundError:
# Shared helper already treats missing as None; keep the name referenced.
return None
except Exception as exc:
# Re-wrap shared fail-closed errors as the local AutomationTokenError type
# so callers and the AST self-check keep a stable contract.
from automation_token_lib import AutomationTokenError as SharedAutomationTokenError
if isinstance(exc, SharedAutomationTokenError):
raise AutomationTokenError(str(exc)) from exc
raise
def bridge_request(
port: int,
method: str,
route: str,
body: dict[str, Any] | None = None,
*,
timeout_sec: float = 60,
authenticate: bool = True,
) -> dict[str, Any]:
payload = None
headers = {"Accept": "application/json"}
if authenticate:
try:
token = automation_token(port)
except AutomationTokenError as exc:
# Fail closed: never send an unauthenticated request when the token
# contract is broken. Still return a structured failure (no crash).
return {"ok": False, "error": f"automation_token_unreadable: {exc}"}
if not token:
return {"ok": False, "error": automation_token_missing_message(port)}
headers["Authorization"] = f"Bearer {token}"
if body is not None:
payload = json.dumps(body).encode("utf-8")
headers["Content-Type"] = "application/json"
request = urllib.request.Request(
f"http://127.0.0.1:{port}{route}",
data=payload,
method=method,
headers=headers,
)
try:
with urllib.request.urlopen(request, timeout=timeout_sec) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
raw = exc.read().decode("utf-8", errors="replace")
try:
parsed = json.loads(raw)
except json.JSONDecodeError:
parsed = {"ok": False, "error": raw}
parsed["http_status"] = exc.code
return parsed
except urllib.error.URLError as exc:
return {"ok": False, "error": f"connection_failed: {exc.reason}"}
except (TimeoutError, socket.timeout) as exc:
# Surface as a step failure, never a harness crash.
return {"ok": False, "error": f"bridge_http_timeout after {timeout_sec:.0f}s: {exc}"}
except http.client.RemoteDisconnected as exc:
return {"ok": False, "error": f"bridge_http_disconnected: {exc}"}
def health_log_path(health: dict[str, Any]) -> str | None:
"""Read the log path from the bridge's standard success envelope."""
if health.get("ok") is not True:
return None
result = health.get("result")
raw_path = result.get("logFilePath") if isinstance(result, dict) else health.get("logFilePath")
return raw_path if isinstance(raw_path, str) else None
def resolve_active_log_path(port: int, explicit_path: str | None) -> str:
if explicit_path:
return explicit_path
# /health deliberately serves immutable launch diagnostics only to callers
# without credentials; an authenticated request returns the state envelope.
health = bridge_request(port, "GET", "/health", authenticate=False)
raw_path = health_log_path(health)
if not isinstance(raw_path, str) or not raw_path or not Path(raw_path).is_absolute():
raise SystemExit(
"automation health did not provide an absolute logFilePath; use a current named bundle "
"or pass --log-path explicitly"
)
return raw_path
def bridge_action(
port: int,
name: str,
params: dict[str, str] | None = None,
*,
turn_timeout_ms: int | None = None,
) -> dict[str, Any]:
timeout_sec = 60.0
if turn_timeout_ms is not None:
timeout_sec = bridge_action_timeout_sec(name, params, turn_timeout_ms)
return bridge_request(
port,
"POST",
"/action",
{"name": name, "params": params or {}},
timeout_sec=timeout_sec,
)
def bridge_state(port: int) -> dict[str, Any]:
return bridge_request(port, "GET", "/state")
def set_automation_ui_presentation(
port: int,
mode: str,
*,
activate: bool = False,
) -> dict[str, Any]:
"""Set the local automation window presentation through the bridge action."""
if mode not in {"normal", "quiet", "interactive"}:
return {"ok": False, "error": f"unsupported automation UI presentation: {mode}"}
return bridge_request(
port,
"POST",
"/action",
{
"name": AUTOMATION_UI_PRESENTATION_ACTION,
"params": {"mode": mode, "activate": activate},
},
)
def write_json(path: Path, data: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")
def append_text(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as handle:
handle.write(text)
def parse_manifest_timestamp(value: str | None) -> datetime | None:
if not value:
return None
try:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
return None
def finalize_evidence_hygiene(run_dir: Path, *, passed: bool, git_sha: str) -> None:
"""Update latest-green pointer, INDEX.md, and prune stale aborted bundles."""
GAUNTLET_ROOT.mkdir(parents=True, exist_ok=True)
if passed:
latest = GAUNTLET_ROOT / "latest-green"
if latest.is_symlink() or latest.exists():
latest.unlink()
latest.symlink_to(run_dir.name, target_is_directory=True)
index_path = GAUNTLET_ROOT / "INDEX.md"
line = f"- `{run_dir.name}` — `{git_sha[:12]}` — green\n"
existing = index_path.read_text(encoding="utf-8") if index_path.exists() else ""
if line not in existing:
with index_path.open("a", encoding="utf-8") as handle:
if not existing:
handle.write("# Agent continuity gauntlet evidence index\n\n")
handle.write(line)
prune_aborted_bundles(GAUNTLET_ROOT, keep_dir=run_dir, max_age_days=PRUNE_ABORTED_BUNDLE_DAYS)
def prune_aborted_bundles(root: Path, *, keep_dir: Path, max_age_days: int) -> None:
cutoff = datetime.now(timezone.utc) - timedelta(days=max_age_days)
if not root.is_dir():
return
for entry in root.iterdir():
if not entry.is_dir():
continue
if entry.resolve() == keep_dir.resolve():
continue
manifest_path = entry / "manifest.json"
if not manifest_path.is_file():
continue
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
continue
if manifest.get("passed") is True:
continue
stamp = parse_manifest_timestamp(manifest.get("finished_at")) or parse_manifest_timestamp(
manifest.get("started_at")
)
if stamp is None or stamp >= cutoff:
continue
shutil.rmtree(entry, ignore_errors=True)
def git_sha() -> str:
try:
result = subprocess.run(
["git", "-C", str(DESKTOP_DIR.parent.parent), "rev-parse", "--short", "HEAD"],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
)
return result.stdout.strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return "unknown"
def automation_listener_pid(port: int) -> str:
try:
result = subprocess.run(
["lsof", f"-tiTCP:{port}", "-sTCP:LISTEN"],
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
)
except FileNotFoundError:
return ""
return next((line.strip() for line in result.stdout.splitlines() if line.strip()), "")
def sine_pcm16k(seconds: float = 0.75, frequency: float = 220.0, amplitude: float = 3500.0) -> bytes:
sample_rate = 16_000
sample_count = int(sample_rate * seconds)
chunks: list[bytes] = []
for index in range(sample_count):
value = int(amplitude * math.sin(2.0 * math.pi * frequency * index / sample_rate))
chunks.append(struct.pack("<h", value))
return b"".join(chunks)
@dataclass(frozen=True)
class TraceCursor:
device: int | None
inode: int | None
offset: int
line_count: int
prefix_digest: str
@dataclass(frozen=True)
class TraceLogLine:
source: str
line_number: int
text: str
def capture_trace_cursor(trace_log: Path = TRACE_LOG) -> TraceCursor:
try:
with trace_log.open("rb") as handle:
stat = os.fstat(handle.fileno())
contents = handle.read(stat.st_size)
final_newline = contents.rfind(b"\n")
last_complete_offset = final_newline + 1 if final_newline >= 0 else 0
complete_prefix = contents[:last_complete_offset]
return TraceCursor(
stat.st_dev,
stat.st_ino,
last_complete_offset,
complete_prefix.count(b"\n"),
hashlib.sha256(complete_prefix).hexdigest(),
)
except FileNotFoundError:
return TraceCursor(None, None, 0, 0, hashlib.sha256(b"").hexdigest())
def _opened_trace_file(path: Path):
try:
handle = path.open("rb")
except FileNotFoundError:
return None
stat = os.fstat(handle.fileno())
return handle, (stat.st_dev, stat.st_ino), stat.st_size
def _read_trace_file_lines(
opened: tuple[Any, tuple[int, int], int],
*,
offset: int,
first_line_number: int,
source: str,
) -> list[TraceLogLine]:
handle, _, size = opened
effective_offset = offset if 0 <= offset <= size else 0
handle.seek(effective_offset)
text = handle.read().decode("utf-8", errors="replace")
return [
TraceLogLine(source=source, line_number=first_line_number + index, text=line)
for index, line in enumerate(text.splitlines())
]
def _trace_cursor_prefix_matches(
opened: tuple[Any, tuple[int, int], int],
cursor: TraceCursor,
) -> bool:
handle, _, size = opened
if size < cursor.offset:
return False
handle.seek(0)
prefix = handle.read(cursor.offset)
return hashlib.sha256(prefix).hexdigest() == cursor.prefix_digest
def _new_trace_lines(cursor: TraceCursor, trace_log: Path = TRACE_LOG) -> list[TraceLogLine]:
backup_log = trace_log.with_name("traces.1.jsonl")
active = _opened_trace_file(trace_log)
backup = _opened_trace_file(backup_log)
cursor_identity = (cursor.device, cursor.inode)
try:
if active is not None and active[1] == cursor_identity:
if _trace_cursor_prefix_matches(active, cursor):
return _read_trace_file_lines(
active,
offset=cursor.offset,
first_line_number=cursor.line_count + 1,
source=trace_log.name,
)
return _read_trace_file_lines(
active,
offset=0,
first_line_number=1,
source=trace_log.name,
)
lines: list[TraceLogLine] = []
if backup is not None and backup[1] == cursor_identity:
backup_offset = cursor.offset if _trace_cursor_prefix_matches(backup, cursor) else 0
lines.extend(_read_trace_file_lines(
backup,
offset=backup_offset,
first_line_number=cursor.line_count + 1 if backup_offset else 1,
source=backup_log.name,
))
if active is not None:
lines.extend(_read_trace_file_lines(
active,
offset=0,
first_line_number=1,
source=trace_log.name,
))
return lines
finally:
if active is not None:
active[0].close()
if backup is not None:
backup[0].close()
def read_new_traces(cursor: TraceCursor, trace_log: Path = TRACE_LOG) -> list[dict[str, Any]]:
traces: list[dict[str, Any]] = []
for line in _new_trace_lines(cursor, trace_log):
raw = line.text.strip()
if not raw:
continue
try:
parsed = json.loads(raw)
except json.JSONDecodeError:
continue
if isinstance(parsed, dict):
traces.append(parsed)
return traces
def read_all_traces() -> list[dict[str, Any]]:
if not TRACE_LOG.exists():
return []
traces: list[dict[str, Any]] = []
with TRACE_LOG.open("r", encoding="utf-8", errors="replace") as handle:
for line in handle:
line = line.strip()
if not line:
continue
try:
traces.append(json.loads(line))
except json.JSONDecodeError:
continue
return traces
def read_new_trace_diagnostics(
cursor: TraceCursor,
trace_log: Path = TRACE_LOG,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
"""Return new QueryTracer rows plus any malformed JSONL evidence.
The general-purpose trace reader intentionally tolerates a damaged historical
line. The convergence acceptance step cannot: malformed frames are one of its
explicit zero-count gates, so it records line numbers and a bounded preview.
"""
traces: list[dict[str, Any]] = []
malformed: list[dict[str, Any]] = []
for line in _new_trace_lines(cursor, trace_log):
raw = line.text.strip()
if not raw:
continue
try:
parsed = json.loads(raw)
except json.JSONDecodeError as exc:
malformed.append(
{
"source": line.source,
"line": line.line_number,
"error": exc.msg,
"preview": raw[:400],
}
)
continue
if not isinstance(parsed, dict):
malformed.append(
{
"source": line.source,
"line": line.line_number,
"error": "top-level JSONL value is not an object",
"preview": raw[:400],
}
)
continue
traces.append(parsed)
return traces, malformed
def embedded_coordinator_payload(
action_response: dict[str, Any],
detail_key: str,
) -> dict[str, Any]:
"""Decode a runtime-control JSON string returned through the Swift bridge."""
if action_response.get("ok") is False:
raise ValueError(str(action_response.get("error") or action_response))
detail = action_response.get("result", {}).get("detail", {})
if not isinstance(detail, dict):
raise ValueError("automation action detail is not an object")
raw = detail.get(detail_key)
if isinstance(raw, dict):
payload = raw
elif isinstance(raw, str) and raw.strip():
try:
payload = json.loads(raw)
except json.JSONDecodeError as exc:
raise ValueError(
f"{detail_key} contains malformed coordinator JSON: {exc.msg}"
) from exc
else:
raise ValueError(f"automation action omitted {detail_key}")
if not isinstance(payload, dict):
raise ValueError(f"{detail_key} coordinator payload is not an object")
if payload.get("ok") is False:
raise ValueError(str(payload.get("error") or payload))
return payload
def coordinator_awareness_payload(action_response: dict[str, Any]) -> dict[str, Any]:
payload = embedded_coordinator_payload(action_response, "snapshot")
snapshot = payload.get("snapshot", payload)
if not isinstance(snapshot, dict):
raise ValueError("coordinator awareness snapshot is not an object")
if not isinstance(snapshot.get("ownerId"), str) or not snapshot.get("ownerId"):
raise ValueError("coordinator awareness snapshot omitted ownerId")
if not isinstance(snapshot.get("sessions"), list):
raise ValueError("coordinator awareness snapshot omitted sessions")
if not isinstance(snapshot.get("runs"), list):
raise ValueError("coordinator awareness snapshot omitted runs")
return snapshot
def coordinator_run_payload(action_response: dict[str, Any]) -> dict[str, Any]:
payload = embedded_coordinator_payload(action_response, "run")
if not isinstance(payload.get("session"), dict):
raise ValueError("run inspection omitted session")
if not isinstance(payload.get("run"), dict):
raise ValueError("run inspection omitted run")
if not isinstance(payload.get("attempts"), list):
raise ValueError("run inspection omitted attempts")
if not isinstance(payload.get("toolInvocations"), list):
raise ValueError("run inspection omitted toolInvocations")
return payload
def agent_lifecycle_convergence_payload(action_response: dict[str, Any]) -> dict[str, Any]:
payload = embedded_coordinator_payload(action_response, "snapshot")
entries = payload.get("entries")
missing = payload.get("missingRequestedRunIds")
if not isinstance(entries, list) or not isinstance(missing, list):
raise ValueError("agent lifecycle convergence snapshot omitted entries or requested-run coverage")
return payload
def awareness_session_parts(
summary: dict[str, Any],
) -> tuple[dict[str, Any], dict[str, Any]]:
session = summary.get("session")
if not isinstance(session, dict):
return {}, {}
active_run = summary.get("activeRun")
latest_run = summary.get("latestRun")
selected_run = active_run if isinstance(active_run, dict) else latest_run
return session, selected_run if isinstance(selected_run, dict) else {}
def awareness_session_ids(snapshot: dict[str, Any]) -> set[str]:
result: set[str] = set()
for summary in snapshot.get("sessions", []):
if not isinstance(summary, dict):
continue
session, _ = awareness_session_parts(summary)
session_id = session.get("sessionId")
if isinstance(session_id, str) and session_id:
result.add(session_id)
return result
def awareness_run_ids(snapshot: dict[str, Any]) -> set[str]:
return {
run.get("runId")
for run in snapshot.get("runs", [])
if isinstance(run, dict) and isinstance(run.get("runId"), str) and run.get("runId")
}
def new_leaf_session_summaries(
snapshot: dict[str, Any],
baseline_session_ids: set[str],
) -> list[dict[str, Any]]:
result: list[dict[str, Any]] = []
for summary in snapshot.get("sessions", []):
if not isinstance(summary, dict):
continue
session, _ = awareness_session_parts(summary)
session_id = session.get("sessionId")
surface_kind = session.get("surfaceKind")
execution_role = session.get("executionRole")
if not isinstance(session_id, str) or not session_id or session_id in baseline_session_ids:
continue
if execution_role == "leaf" or surface_kind in AGENT_CHILD_SURFACES:
result.append(summary)
return result
def exact_external_parent_run_ids(snapshot: dict[str, Any]) -> list[str]:
result: list[str] = []
for run in snapshot.get("runs", []):
if not isinstance(run, dict):
continue
run_input = run.get("input")
if not isinstance(run_input, dict) or run_input.get("prompt") != EXACT_VOICE_AGENT_MEMORY_REQUEST:
continue
metadata = run_input.get("metadata")
external = metadata.get("externalSurface") if isinstance(metadata, dict) else None
if not isinstance(external, dict) or external.get("authority") != "swift_realtime":
continue
run_id = run.get("runId")
if isinstance(run_id, str) and run_id:
result.append(run_id)
return sorted(set(result))
def tool_invocation_contract_errors(
payload: dict[str, Any],
expected_run_id: str,
) -> list[str]:
"""Validate the bounded get_agent_run invocation summaries (no raw inputs/results)."""
required_fields = {
"invocationId",
"runId",
"attemptId",
"toolName",
"status",
"errorCode",
"preparedAtMs",
"dispatchedAtMs",
"completedAtMs",
"updatedAtMs",
}
forbidden_fields = {
"arguments",
"argumentsJSON",
"input",
"inputHash",
"output",
"result",
"toolInput",
}
allowed_statuses = {"prepared", "dispatched", "succeeded", "failed", "outcome_unknown"}
attempt_ids = {
attempt.get("attemptId")
for attempt in payload.get("attempts", [])
if isinstance(attempt, dict) and isinstance(attempt.get("attemptId"), str)
}
errors: list[str] = []
for index, invocation in enumerate(payload.get("toolInvocations", [])):
if not isinstance(invocation, dict):
errors.append(f"toolInvocations[{index}] is not an object")
continue
missing = sorted(required_fields - set(invocation))
leaked = sorted(forbidden_fields & set(invocation))
if missing:
errors.append(f"toolInvocations[{index}] missing {missing}")
if leaked:
errors.append(f"toolInvocations[{index}] leaked unbounded fields {leaked}")
if invocation.get("runId") != expected_run_id:
errors.append(f"toolInvocations[{index}] runId does not match inspected run")
if invocation.get("attemptId") not in attempt_ids:
errors.append(f"toolInvocations[{index}] attemptId is not an inspected attempt")
if invocation.get("status") not in allowed_statuses:
errors.append(f"toolInvocations[{index}] has invalid status {invocation.get('status')!r}")
for field in ("preparedAtMs", "updatedAtMs"):
if not isinstance(invocation.get(field), int):
errors.append(f"toolInvocations[{index}] {field} is not an integer")
for field in ("dispatchedAtMs", "completedAtMs"):
if invocation.get(field) is not None and not isinstance(invocation.get(field), int):
errors.append(f"toolInvocations[{index}] {field} is not integer/null")
return errors
def tool_invocations_named(payload: dict[str, Any], tool_name: str) -> list[dict[str, Any]]:
return [
invocation
for invocation in payload.get("toolInvocations", [])
if isinstance(invocation, dict) and invocation.get("toolName") == tool_name
]
def run_terminal_event_count(payload: dict[str, Any], run_id: str, status: str) -> int:
return sum(
1
for event in payload.get("events", [])
if isinstance(event, dict)
and event.get("runId") == run_id
and event.get("type") == f"run.{status}"
)
def wait_for_new_traces(
cursor: TraceCursor,
*,
min_count: int = 1,
timeout_sec: float = 8.0,
poll_sec: float = 0.25,
query_text: str | None = None,
trace_log: Path = TRACE_LOG,
) -> list[dict[str, Any]]:
deadline = time.monotonic() + timeout_sec
while time.monotonic() < deadline:
traces = read_new_traces(cursor, trace_log)
if query_text is not None:
traces = traces_for_query(traces, query_text)
if len(traces) >= min_count:
return traces
time.sleep(poll_sec)
traces = read_new_traces(cursor, trace_log)
return traces_for_query(traces, query_text) if query_text is not None else traces
def traces_for_query(traces: list[dict[str, Any]], query_text: str) -> list[dict[str, Any]]:
needle = query_text.strip()
if not needle:
return traces
return [trace for trace in traces if str(trace.get("query_text", "")).strip() == needle]
def flatten_trace_text(trace: dict[str, Any]) -> str:
parts: list[str] = []
request = trace.get("request") or {}
if isinstance(request, dict):
if request.get("system_prompt"):
parts.append(str(request["system_prompt"]))
for message in request.get("messages") or []:
if isinstance(message, dict):
parts.append(str(message.get("content", "")))
if request.get("response_text"):
parts.append(str(request["response_text"]))
if trace.get("query_text"):
parts.append(str(trace["query_text"]))
if trace.get("response_text"):
parts.append(str(trace["response_text"]))
for tool in trace.get("tool_executions") or []:
if isinstance(tool, dict):
parts.append(str(tool.get("name", "")))
parts.append(str(tool.get("input", "")))
parts.append(str(tool.get("output", "")))
return "\n".join(parts)
def trace_tool_executions(traces: list[dict[str, Any]], names: set[str] | None = None) -> list[dict[str, Any]]:
return [
tool
for trace in traces
for tool in (trace.get("tool_executions") or [])
if isinstance(tool, dict) and (names is None or tool.get("name") in names)
]
def spawn_tool_acceptance_error(output: Any) -> str | None:
"""Validate the spawn admission result, not incidental words in its JSON.
spawn_agent is asynchronous: a successful tool response returns an admitted
child whose run is normally queued (or may already be running/succeeded).
Nested fields such as errorCode=null must never turn that accepted response
into a failure merely because their key contains the word "error".
"""
payload = output
if isinstance(payload, str):
try:
payload = json.loads(payload)
except json.JSONDecodeError:
return "spawn_agent output is not valid JSON"
if not isinstance(payload, dict):
return "spawn_agent output is not a JSON object"
if payload.get("ok") is not True:
error = payload.get("error")
if isinstance(error, dict):
detail = error.get("message") or error.get("code")
if detail:
return f"spawn_agent rejected the request: {detail}"
return "spawn_agent response did not report ok=true"
agents = payload.get("agents")
if not isinstance(agents, list) or not agents:
return "spawn_agent ok=true response has no admitted agents"
requested = payload.get("requestedAgentCount")
if isinstance(requested, int) and requested > 0 and len(agents) != requested:
return f"spawn_agent admitted {len(agents)} agents, expected {requested}"
# Admission happens before adapter execution. `starting` is a valid
# transient receipt; lifecycle convergence separately requires the child
# to reach a canonical terminal state.
accepted_statuses = {"queued", "starting", "running", "succeeded"}
for index, agent in enumerate(agents):
run = agent.get("run") if isinstance(agent, dict) else None
status = run.get("status") if isinstance(run, dict) else None
if status not in accepted_statuses:
return f"spawn_agent agent {index} has non-accepted run status {status!r}"
return None
def strip_probe_text(haystack: str, probe_texts: list[str]) -> str:
"""Remove the probe turn's own text from an assertion haystack (R8).
Traces include the current user message; searching for a marker that the
probe itself contains would make the assertion self-satisfying.
"""
for probe in probe_texts:
if probe:
haystack = haystack.replace(probe, "")
return haystack
def latest_assistant_text(snapshot_detail: dict[str, str]) -> str:
try:
messages = json.loads(snapshot_detail.get("messages_json", "[]"))
except json.JSONDecodeError:
return ""
for message in reversed(messages):
if message.get("role") == "assistant" and message.get("streaming") != "true":
text = (message.get("text") or "").strip()
if text:
return text
return ""
def current_turn_snapshot_text(snapshot_detail: dict[str, str], query_text: str) -> str:
try:
messages = json.loads(snapshot_detail.get("messages_json", "[]"))
except json.JSONDecodeError:
return ""
if not isinstance(messages, list):
return ""
query = query_text.strip()
start_index: int | None = None
for index, message in enumerate(messages):
if not isinstance(message, dict):
continue
if message.get("role") == "user" and str(message.get("text") or "").strip() == query:
start_index = index
if start_index is None:
return ""
return json.dumps(messages[start_index:], sort_keys=True)
def terminal_assistant_for_exact_turn(
snapshot_detail: dict[str, str], query_text: str
) -> dict[str, Any] | None:
"""Return only this query's terminal assistant, never a neighboring turn's."""
try:
messages = json.loads(snapshot_detail.get("messages_json", "[]"))
except json.JSONDecodeError:
return None
if not isinstance(messages, list):
return None
query = query_text.strip()
start_index: int | None = None
for index, message in enumerate(messages):
if not isinstance(message, dict):
continue
if message.get("role") == "user" and str(message.get("text") or "").strip() == query:
start_index = index
if start_index is None:
return None
for message in messages[start_index + 1 :]:
if not isinstance(message, dict):
continue
if message.get("role") == "user":
# A later user turn owns any following assistant rows.
return None
if message.get("role") == "assistant" and message.get("streaming") != "true":
return message
return None
def current_turn_assistant_text(snapshot_detail: dict[str, str], query_text: str) -> str:
if message := terminal_assistant_for_exact_turn(snapshot_detail, query_text):
return str(message.get("text") or "").strip()
return ""
def current_turn_has_terminal_assistant(snapshot_detail: dict[str, str], query_text: str) -> bool:
"""Return whether the exact query has its own terminal assistant projection.
Main-chat idle is a transport/lifecycle signal, not proof that this send
produced a terminal row. Keying the wait to the exact user text prevents a
failed empty turn from inheriting the previous turn's assistant response.
"""
return terminal_assistant_for_exact_turn(snapshot_detail, query_text) is not None
def exact_voice_agent_turn_signature(
snapshot_detail: dict[str, Any],
*,
child_session_id: str,
child_run_id: str,
expected_assistant_text: str | None = None,
) -> dict[str, Any]:
"""Validate the initial canonical run on the exact #9515 producing turn.
A continuation reuses the child session but creates a distinct canonical run.
Its terminal block belongs on the same producing receipt, so this verifier
pins exactly one spawn and completion for *the initial run* while requiring
each later completion to have a distinct terminal run identity.
"""
try:
messages = json.loads(str(snapshot_detail.get("messages_json", "[]")))
except json.JSONDecodeError as exc:
raise ValueError(f"main chat snapshot contains malformed messages JSON: {exc.msg}") from exc
if not isinstance(messages, list):
raise ValueError("main chat snapshot messages are not an array")
producing_assistants: list[tuple[int, dict[str, Any], list[Any]]] = []
for index, message in enumerate(messages):