prizmkit 1.1.191 → 1.1.192

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/bundled/VERSION.json +3 -3
  2. package/bundled/adapters/antigravity/skill-adapter.js +13 -4
  3. package/bundled/adapters/codex/skill-adapter.js +28 -8
  4. package/bundled/adapters/cursor/skill-adapter.js +13 -4
  5. package/bundled/adapters/pi/skill-adapter.js +28 -7
  6. package/bundled/dev-pipeline/.env.example +4 -12
  7. package/bundled/dev-pipeline/README.md +5 -10
  8. package/bundled/dev-pipeline/assets/skill-subagent-integration.md +3 -6
  9. package/bundled/dev-pipeline/prizmkit_runtime/atomic_io.py +48 -0
  10. package/bundled/dev-pipeline/prizmkit_runtime/checkpoint_state.py +66 -23
  11. package/bundled/dev-pipeline/prizmkit_runtime/cli.py +10 -7
  12. package/bundled/dev-pipeline/prizmkit_runtime/commands.py +2 -21
  13. package/bundled/dev-pipeline/prizmkit_runtime/config.py +24 -76
  14. package/bundled/dev-pipeline/prizmkit_runtime/daemon.py +125 -67
  15. package/bundled/dev-pipeline/prizmkit_runtime/gitops.py +77 -430
  16. package/bundled/dev-pipeline/prizmkit_runtime/heartbeat.py +93 -49
  17. package/bundled/dev-pipeline/prizmkit_runtime/interoperability.py +1 -3
  18. package/bundled/dev-pipeline/prizmkit_runtime/paths.py +0 -6
  19. package/bundled/dev-pipeline/prizmkit_runtime/platform_detection.py +36 -14
  20. package/bundled/dev-pipeline/prizmkit_runtime/processes.py +206 -151
  21. package/bundled/dev-pipeline/prizmkit_runtime/reset.py +2 -23
  22. package/bundled/dev-pipeline/prizmkit_runtime/reset_preserve.py +15 -134
  23. package/bundled/dev-pipeline/prizmkit_runtime/results.py +25 -0
  24. package/bundled/dev-pipeline/prizmkit_runtime/runner_bookkeeping.py +68 -83
  25. package/bundled/dev-pipeline/prizmkit_runtime/runner_classification.py +15 -5
  26. package/bundled/dev-pipeline/prizmkit_runtime/runner_models.py +1 -29
  27. package/bundled/dev-pipeline/prizmkit_runtime/runner_prompts.py +0 -2
  28. package/bundled/dev-pipeline/prizmkit_runtime/runner_status.py +7 -2
  29. package/bundled/dev-pipeline/prizmkit_runtime/runners.py +276 -217
  30. package/bundled/dev-pipeline/prizmkit_runtime/runtime_commit.py +124 -122
  31. package/bundled/dev-pipeline/prizmkit_runtime/runtime_helper.py +90 -9
  32. package/bundled/dev-pipeline/prizmkit_runtime/sessions.py +183 -130
  33. package/bundled/dev-pipeline/prizmkit_runtime/status.py +1 -3
  34. package/bundled/dev-pipeline/prizmkit_runtime/stream_progress.py +2780 -0
  35. package/bundled/dev-pipeline/prizmkit_runtime/task_checkout.py +27 -101
  36. package/bundled/dev-pipeline/prizmkit_runtime/test_result.py +58 -4
  37. package/bundled/dev-pipeline/scripts/check-session-status.py +43 -19
  38. package/bundled/dev-pipeline/scripts/continuation.py +6 -4
  39. package/bundled/dev-pipeline/scripts/detect-stuck.py +28 -28
  40. package/bundled/dev-pipeline/scripts/generate-bootstrap-prompt.py +7 -2
  41. package/bundled/dev-pipeline/scripts/generate-bugfix-prompt.py +7 -2
  42. package/bundled/dev-pipeline/scripts/init-bugfix-pipeline.py +10 -7
  43. package/bundled/dev-pipeline/scripts/init-change-artifact.py +8 -2
  44. package/bundled/dev-pipeline/scripts/init-pipeline.py +14 -69
  45. package/bundled/dev-pipeline/scripts/parse-stream-progress.py +31 -2616
  46. package/bundled/dev-pipeline/scripts/patch-completion-notes.py +4 -24
  47. package/bundled/dev-pipeline/scripts/prompt_framework.py +56 -9
  48. package/bundled/dev-pipeline/scripts/status_common.py +591 -0
  49. package/bundled/dev-pipeline/scripts/update-bug-status.py +85 -463
  50. package/bundled/dev-pipeline/scripts/update-checkpoint.py +227 -65
  51. package/bundled/dev-pipeline/scripts/update-feature-status.py +76 -509
  52. package/bundled/dev-pipeline/scripts/utils.py +5 -12
  53. package/bundled/dev-pipeline/templates/bootstrap-tier3.md +4 -4
  54. package/bundled/dev-pipeline/templates/bug-fix-list-schema.json +7 -0
  55. package/bundled/dev-pipeline/templates/bugfix-bootstrap-prompt.md +1 -1
  56. package/bundled/dev-pipeline/templates/sections/artifact-manifest.md +1 -1
  57. package/bundled/dev-pipeline/templates/sections/bugfix-phase-manual-verification.md +1 -1
  58. package/bundled/dev-pipeline/templates/sections/bugfix-phase-review.md +1 -1
  59. package/bundled/dev-pipeline/templates/sections/bugfix-phase-test.md +2 -1
  60. package/bundled/dev-pipeline/templates/sections/checkpoint-system.md +1 -1
  61. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-auto.md +1 -1
  62. package/bundled/dev-pipeline/templates/sections/phase-browser-verification-opencli.md +2 -2
  63. package/bundled/dev-pipeline/templates/sections/phase-browser-verification.md +2 -2
  64. package/bundled/dev-pipeline/templates/sections/phase-prizmkit-test.md +2 -1
  65. package/bundled/dev-pipeline/templates/sections/phase-review-full.md +1 -1
  66. package/bundled/dev-pipeline/templates/sections/phase-specify-plan-full.md +3 -6
  67. package/bundled/dev-pipeline/templates/session-status-schema.json +2 -5
  68. package/bundled/dev-pipeline/tests/_helpers.py +418 -0
  69. package/bundled/dev-pipeline/tests/conftest.py +45 -1
  70. package/bundled/dev-pipeline/tests/test_auto_skip.py +4 -69
  71. package/bundled/dev-pipeline/tests/test_checkpoint_state.py +126 -1
  72. package/bundled/dev-pipeline/tests/test_daemon_and_scripts.py +257 -0
  73. package/bundled/dev-pipeline/tests/test_e2e_pipeline_run.py +500 -0
  74. package/bundled/dev-pipeline/tests/test_generate_bootstrap_prompt.py +59 -117
  75. package/bundled/dev-pipeline/tests/test_generate_bugfix_prompt.py +12 -10
  76. package/bundled/dev-pipeline/tests/test_python_runner_parity.py +431 -3099
  77. package/bundled/dev-pipeline/tests/test_recovery_workflow.py +7 -8
  78. package/bundled/dev-pipeline/tests/test_repository_bootstrap.py +0 -1
  79. package/bundled/dev-pipeline/tests/test_reset_modes.py +15 -27
  80. package/bundled/dev-pipeline/tests/test_reset_preserve.py +54 -139
  81. package/bundled/dev-pipeline/tests/test_runner_bookkeeping.py +766 -0
  82. package/bundled/dev-pipeline/tests/test_runner_lifecycle.py +1257 -0
  83. package/bundled/dev-pipeline/tests/test_runtime_helper.py +97 -20
  84. package/bundled/dev-pipeline/tests/test_session_launch.py +1101 -0
  85. package/bundled/dev-pipeline/tests/test_stream_progress.py +585 -0
  86. package/bundled/dev-pipeline/tests/test_unified_cli.py +155 -2034
  87. package/bundled/dev-pipeline/tests/test_utils.py +3 -3
  88. package/bundled/skills/_metadata.json +9 -63
  89. package/bundled/skills/app-planner/SKILL.md +32 -303
  90. package/bundled/skills/app-planner/references/app-design-guide.md +0 -4
  91. package/bundled/skills/app-planner/references/generated-plan-review.md +2 -1
  92. package/bundled/skills/app-planner/references/project-brief-guide.md +14 -0
  93. package/bundled/skills/app-planner/references/project-conventions-discovery.md +4 -6
  94. package/bundled/skills/app-planner/references/project-state-detection.md +2 -3
  95. package/bundled/skills/bug-fix-workflow/SKILL.md +1 -2
  96. package/bundled/skills/bug-fix-workflow/references/bug-diagnosis.md +4 -7
  97. package/bundled/skills/bug-planner/SKILL.md +54 -435
  98. package/bundled/skills/bug-planner/references/generated-plan-review.md +3 -2
  99. package/bundled/skills/bug-planner/references/input-formats.md +32 -0
  100. package/bundled/skills/bugfix-pipeline-launcher/SKILL.md +4 -6
  101. package/bundled/skills/bugfix-pipeline-launcher/references/configuration.md +4 -28
  102. package/bundled/skills/feature-pipeline-launcher/SKILL.md +4 -6
  103. package/bundled/skills/feature-pipeline-launcher/references/configuration.md +4 -28
  104. package/bundled/skills/feature-planner/SKILL.md +60 -439
  105. package/bundled/skills/feature-planner/assets/planning-guide.md +1 -1
  106. package/bundled/skills/feature-planner/references/completeness-review.md +34 -0
  107. package/bundled/skills/feature-planner/references/decomposition-patterns.md +2 -2
  108. package/bundled/skills/feature-planner/references/error-recovery.md +1 -1
  109. package/bundled/skills/feature-planner/references/generated-plan-review.md +3 -2
  110. package/bundled/skills/feature-planner/references/incremental-feature-planning.md +3 -1
  111. package/bundled/skills/feature-workflow/SKILL.md +1 -2
  112. package/bundled/skills/prizmkit/SKILL.md +7 -1
  113. package/bundled/skills/prizmkit-code-review/SKILL.md +14 -6
  114. package/bundled/skills/prizmkit-code-review/references/independent-code-review.md +7 -4
  115. package/bundled/skills/prizmkit-code-review/references/review-report-template.md +16 -0
  116. package/bundled/skills/prizmkit-code-review/scripts/render_review_report.py +58 -20
  117. package/bundled/skills/prizmkit-implement/SKILL.md +1 -1
  118. package/bundled/skills/prizmkit-init/SKILL.md +24 -127
  119. package/bundled/skills/prizmkit-init/assets/project-brief-template.md +3 -3
  120. package/bundled/skills/prizmkit-plan/SKILL.md +6 -8
  121. package/bundled/skills/prizmkit-plan/references/clarify-guide.md +1 -1
  122. package/bundled/skills/prizmkit-plan/references/independent-plan-review.md +5 -2
  123. package/bundled/skills/prizmkit-plan/references/review-plan-spec-loop.md +6 -5
  124. package/bundled/skills/prizmkit-prizm-docs/SKILL.md +1 -13
  125. package/bundled/skills/prizmkit-prizm-docs/references/op-update.md +1 -1
  126. package/bundled/skills/prizmkit-retrospective/SKILL.md +6 -4
  127. package/bundled/skills/prizmkit-test/SKILL.md +25 -133
  128. package/bundled/skills/prizmkit-test/references/independent-test-review.md +5 -2
  129. package/bundled/skills/prizmkit-test/references/test-coverage-model.md +6 -0
  130. package/bundled/skills/prizmkit-workflow/SKILL.md +2 -3
  131. package/bundled/skills/prizmkit-workflow/references/workflow-state-protocol.md +4 -3
  132. package/bundled/skills/recovery-workflow/SKILL.md +7 -7
  133. package/bundled/skills/recovery-workflow/evals/evals.json +1 -1
  134. package/bundled/skills/recovery-workflow/references/detection.md +1 -3
  135. package/bundled/skills/recovery-workflow/scripts/detect-recovery-state.py +0 -6
  136. package/bundled/templates/project-memory-template.md +1 -2
  137. package/package.json +1 -1
  138. package/src/scaffold.js +28 -7
  139. package/bundled/dev-pipeline/SCHEMA_ANALYSIS.md +0 -53
  140. package/bundled/dev-pipeline/scripts/generate-refactor-prompt.py +0 -649
  141. package/bundled/dev-pipeline/scripts/init-refactor-pipeline.py +0 -463
  142. package/bundled/dev-pipeline/scripts/update-refactor-status.py +0 -1512
  143. package/bundled/dev-pipeline/templates/refactor-bootstrap-prompt.md +0 -240
  144. package/bundled/dev-pipeline/templates/refactor-list-schema.json +0 -266
  145. package/bundled/dev-pipeline/templates/sections/refactor-critical-paths.md +0 -15
  146. package/bundled/dev-pipeline/templates/sections/refactor-mission.md +0 -9
  147. package/bundled/dev-pipeline/templates/sections/refactor-phase-commit-report.md +0 -24
  148. package/bundled/dev-pipeline/templates/sections/refactor-phase-implement.md +0 -16
  149. package/bundled/dev-pipeline/templates/sections/refactor-phase-init.md +0 -9
  150. package/bundled/dev-pipeline/templates/sections/refactor-phase-plan.md +0 -22
  151. package/bundled/dev-pipeline/templates/sections/refactor-phase-review.md +0 -19
  152. package/bundled/dev-pipeline/templates/sections/refactor-phase-test.md +0 -24
  153. package/bundled/dev-pipeline/templates/sections/refactor-reminders.md +0 -12
  154. package/bundled/dev-pipeline/templates/sections/refactor-session-context.md +0 -6
  155. package/bundled/dev-pipeline/templates/sections/refactor-task-contract.md +0 -52
  156. package/bundled/dev-pipeline/tests/test_generate_refactor_prompt.py +0 -478
  157. package/bundled/skills/feature-planner/assets/evaluation-guide.md +0 -44
  158. package/bundled/skills/refactor-pipeline-launcher/SKILL.md +0 -219
  159. package/bundled/skills/refactor-pipeline-launcher/references/configuration.md +0 -78
  160. package/bundled/skills/refactor-planner/SKILL.md +0 -467
  161. package/bundled/skills/refactor-planner/assets/planning-guide.md +0 -291
  162. package/bundled/skills/refactor-planner/references/behavior-preservation.md +0 -187
  163. package/bundled/skills/refactor-planner/references/error-recovery.md +0 -45
  164. package/bundled/skills/refactor-planner/references/fast-path.md +0 -59
  165. package/bundled/skills/refactor-planner/references/generated-plan-review.md +0 -107
  166. package/bundled/skills/refactor-planner/references/planning-phases.md +0 -172
  167. package/bundled/skills/refactor-planner/references/refactor-scoping-guide.md +0 -230
  168. package/bundled/skills/refactor-planner/scripts/validate-and-generate-refactor.py +0 -1120
  169. package/bundled/skills/refactor-workflow/SKILL.md +0 -205
@@ -0,0 +1,2780 @@
1
+ """Real-time stream-json progress tracker and semantic log normalizer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import re
9
+ import time
10
+ from collections import Counter, deque
11
+ from contextlib import nullcontext
12
+ from dataclasses import dataclass
13
+ from datetime import datetime, timezone
14
+ from pathlib import Path
15
+
16
+ from .atomic_io import write_json_atomic
17
+
18
+ # Ordered pipeline phases — index defines forward-only progression.
19
+ # Phase detection is monotonic: once a phase is reached, earlier phases
20
+ # cannot be re-entered (prevents false positives from file content mentions).
21
+ PHASE_ORDER = ["plan", "implement", "code-review", "retrospective", "commit"]
22
+
23
+ # Keywords for phase detection.
24
+ # "strong" keywords are skill invocations — high confidence, but still
25
+ # forward-only (a mention of prizmkit-plan while in commit phase is noise).
26
+ # "weak" keywords are contextual hints — also forward-only, used when no
27
+ # strong keyword matches.
28
+ PHASE_KEYWORDS = {
29
+ "plan": {
30
+ "strong": ["prizmkit-plan"],
31
+ "weak": [
32
+ "spec.md",
33
+ "plan.md",
34
+ "specification",
35
+ "architecture",
36
+ "task checklist",
37
+ "task breakdown",
38
+ "gathering requirements",
39
+ ],
40
+ },
41
+ "implement": {
42
+ "strong": ["prizmkit-implement"],
43
+ "weak": ["implement", "writing code", "TDD", "coding"],
44
+ },
45
+ "code-review": {
46
+ "strong": ["prizmkit-code-review"],
47
+ "weak": ["code review", "review verdict", "reviewing"],
48
+ },
49
+ "retrospective": {
50
+ "strong": ["prizmkit-retrospective"],
51
+ "weak": [
52
+ "retrospective",
53
+ "structural sync",
54
+ "architecture knowledge",
55
+ ".prizmkit/prizm-docs/ sync",
56
+ ],
57
+ },
58
+ "commit": {
59
+ "strong": ["prizmkit-committer"],
60
+ "weak": ["git commit", "committing", "feat(", "fix("],
61
+ },
62
+ }
63
+
64
+ CONTEXT_OVERFLOW_CODE = "context_overflow"
65
+
66
+ # Exact machine/wrapper signals. These are only treated as self-sufficient when
67
+ # they appear in structured error-code fields or as explicit wrapper markers.
68
+ CONTEXT_CODE_PATTERNS = [
69
+ re.compile(pattern, re.IGNORECASE)
70
+ for pattern in (
71
+ r"\bcontext_overflow\b",
72
+ r"\bcontext_too_large\b",
73
+ r"\bcontext_length_exceeded\b",
74
+ r"\bmodel_context_window_exceeded\b",
75
+ )
76
+ ]
77
+
78
+ WRAPPER_CONTEXT_ERROR_PATTERNS = [
79
+ re.compile(pattern, re.IGNORECASE)
80
+ for pattern in (
81
+ r"\bPRIZMKIT_FATAL_ERROR\s*=\s*context_overflow\b",
82
+ )
83
+ ]
84
+
85
+ # Natural-language provider messages are weak signals: they require an adjacent
86
+ # runtime/API error context unless a structured field already proves the result
87
+ # is an error.
88
+ WEAK_CONTEXT_ERROR_PATTERNS = [
89
+ re.compile(pattern, re.IGNORECASE)
90
+ for pattern in (
91
+ r"Your input exceeds the context window",
92
+ r"input exceeds (?:the )?(?:model )?context window",
93
+ r"context window of this model",
94
+ r"context window (?:was )?exceeded",
95
+ r"exceeded (?:the )?context window",
96
+ r"maximum context length exceeded",
97
+ r"prompt is too long",
98
+ r"too many tokens",
99
+ r"input token count exceeds",
100
+ r"input tokens? exceeds?",
101
+ r"token count exceeds",
102
+ )
103
+ ]
104
+
105
+ REQUEST_TOO_LARGE_PATTERN = re.compile(r"\brequest (?:is )?too large\b", re.IGNORECASE)
106
+ REQUEST_TOO_LARGE_SEMANTIC_PATTERN = re.compile(
107
+ r"\b(context|token|tokens|prompt|input|model)\b",
108
+ re.IGNORECASE,
109
+ )
110
+
111
+ ERROR_CONTEXT_PATTERNS = [
112
+ re.compile(pattern, re.IGNORECASE)
113
+ for pattern in (
114
+ r"\bapi error\b",
115
+ r"invalid_request_error",
116
+ r"\bbad request\b",
117
+ r"\bstatus\s*[:=]?\s*(400|413)\b",
118
+ r"\bapi_error_status\b",
119
+ r"\bapi_error_code\b",
120
+ r"\blast_result_is_error\b\s*[\"':=]*\s*true\b",
121
+ r"\bis_error\b\s*[\"':=]*\s*true\b",
122
+ r"\berror\s*[:=]",
123
+ r"\bfatal\s*[:=]",
124
+ )
125
+ ]
126
+
127
+ PERMISSION_DENIAL_MARKERS = (
128
+ "permission denied",
129
+ "permission_denied",
130
+ "permission denial",
131
+ "denied by user",
132
+ "user denied",
133
+ "not permitted",
134
+ )
135
+
136
+
137
+ def _has_error_context(text):
138
+ """Return true when free text looks like a runtime/provider error."""
139
+ if not text:
140
+ return False
141
+ return any(pattern.search(text) for pattern in ERROR_CONTEXT_PATTERNS)
142
+
143
+
144
+ def _has_context_overflow_signal(text, structured_code=False):
145
+ """Return true when text contains a context-window/token overflow signal."""
146
+ if not text:
147
+ return False
148
+ if any(pattern.search(text) for pattern in WRAPPER_CONTEXT_ERROR_PATTERNS):
149
+ return True
150
+ if structured_code and any(pattern.search(text) for pattern in CONTEXT_CODE_PATTERNS):
151
+ return True
152
+ if any(pattern.search(text) for pattern in CONTEXT_CODE_PATTERNS):
153
+ return True
154
+ if any(pattern.search(text) for pattern in WEAK_CONTEXT_ERROR_PATTERNS):
155
+ return True
156
+ if REQUEST_TOO_LARGE_PATTERN.search(text) and REQUEST_TOO_LARGE_SEMANTIC_PATTERN.search(text):
157
+ return True
158
+ return False
159
+
160
+
161
+ def detect_api_error_code(text, require_error_context=False, structured_code=False):
162
+ """Return a normalized fatal/runtime error code from terminal text.
163
+
164
+ Structured error-code fields and explicit wrapper markers can be matched
165
+ directly. Natural-language provider messages require runtime/API context to
166
+ avoid false positives from prompts, tests, or documentation that merely
167
+ mention context windows or token limits.
168
+ """
169
+ if not text:
170
+ return ""
171
+ if any(pattern.search(text) for pattern in WRAPPER_CONTEXT_ERROR_PATTERNS):
172
+ return CONTEXT_OVERFLOW_CODE
173
+ if structured_code and any(pattern.search(text) for pattern in CONTEXT_CODE_PATTERNS):
174
+ return CONTEXT_OVERFLOW_CODE
175
+ if require_error_context and not _has_error_context(text):
176
+ return ""
177
+ if _has_context_overflow_signal(text, structured_code=structured_code):
178
+ return CONTEXT_OVERFLOW_CODE
179
+ return ""
180
+
181
+
182
+ TERMINAL_SUBAGENT_STATUSES = {
183
+ "completed",
184
+ "failed",
185
+ "cancelled",
186
+ "canceled",
187
+ "killed",
188
+ "stopped",
189
+ "success",
190
+ "error",
191
+ }
192
+
193
+
194
+ def _stable_subagent_digest(*parts):
195
+ """Return a short stable digest for provider events without durable ids."""
196
+ canonical = json.dumps(parts, ensure_ascii=False, sort_keys=True, default=str)
197
+ return hashlib.sha1(canonical.encode("utf-8")).hexdigest()[:16]
198
+
199
+
200
+ def _normalize_status(status, default="unknown"):
201
+ """Normalize provider status values while preserving provider-specific names."""
202
+ text = str(status or "").strip().lower()
203
+ if not text:
204
+ return default
205
+ if text == "cancelled":
206
+ return "canceled"
207
+ return text
208
+
209
+
210
+ def _cursor_tool_call_parts(event):
211
+ """Return Cursor tool name, arguments, result, and error signal."""
212
+ tool_call = event.get("tool_call") if isinstance(event, dict) else None
213
+ if not isinstance(tool_call, dict) or not tool_call:
214
+ return "unknown", {}, {}, False
215
+ key, payload = next(iter(tool_call.items()))
216
+ payload = payload if isinstance(payload, dict) else {}
217
+ if key == "function":
218
+ name = str(payload.get("name") or "function")
219
+ arguments = payload.get("arguments") or payload.get("args") or {}
220
+ else:
221
+ name = re.sub(r"ToolCall$", "", str(key)) or "unknown"
222
+ name = name[:1].upper() + name[1:]
223
+ arguments = payload.get("args") or {}
224
+ result = payload.get("result") or {}
225
+ is_error = bool(event.get("is_error"))
226
+ if isinstance(result, dict):
227
+ is_error = is_error or bool(result.get("error") or result.get("failure"))
228
+ return name, arguments, result, is_error
229
+
230
+
231
+ def _cursor_compact_value(value, limit=800):
232
+ """Render tool metadata without copying full file content into logs."""
233
+
234
+ def compact(item, key=""):
235
+ if (
236
+ key in {"fileText", "content", "Content", "Replacement", "TargetContent", "CodeContent"}
237
+ and isinstance(item, str)
238
+ ):
239
+ return f"<{len(item)} chars>"
240
+ if isinstance(item, dict):
241
+ return {child_key: compact(child, child_key) for child_key, child in item.items()}
242
+ if isinstance(item, list):
243
+ return [compact(child) for child in item]
244
+ return item
245
+
246
+ value = compact(value)
247
+ rendered = (
248
+ value
249
+ if isinstance(value, str)
250
+ else json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
251
+ )
252
+ return rendered[:limit]
253
+
254
+
255
+ def _extract_error_text(value) -> str:
256
+ """Safely render a heterogeneous provider error field into bounded text."""
257
+ if value in (None, ""):
258
+ return ""
259
+ if isinstance(value, str):
260
+ return value
261
+ if isinstance(value, dict):
262
+ msg = value.get("message")
263
+ if isinstance(msg, str) and msg.strip():
264
+ return msg
265
+ parts = [str(value.get(k)) for k in ("type", "code", "message") if value.get(k)]
266
+ if parts:
267
+ return " ".join(parts)
268
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
269
+ if isinstance(value, list):
270
+ return "; ".join(_extract_error_text(item) for item in value[:3] if item not in (None, ""))
271
+ return str(value)
272
+
273
+
274
+ @dataclass(frozen=True)
275
+ class SemanticLogEvent:
276
+ """One provider-neutral semantic fragment destined for session.log."""
277
+
278
+ kind: str
279
+ payload: str = ""
280
+ stream_id: str = ""
281
+ mode: str = "complete"
282
+ deduplicate: bool = False
283
+
284
+
285
+ class SemanticLogRenderer:
286
+ """Render semantic fragments without consulting their source format."""
287
+
288
+ LABELS = {
289
+ "think": "[THINK]",
290
+ "action": "[ACTION]",
291
+ "observation": "[OBSERVATION]",
292
+ "error": "[ERROR]",
293
+ "final": "[FINAL]",
294
+ "session_end": "[SESSION_END]",
295
+ "output": "[OUTPUT]",
296
+ }
297
+
298
+ def __init__(self):
299
+ self._active_stream = ""
300
+
301
+ def _close_active(self):
302
+ if not self._active_stream:
303
+ return ""
304
+ self._active_stream = ""
305
+ return "\n"
306
+
307
+ def render(self, event):
308
+ label = self.LABELS.get(event.kind, "[OUTPUT]")
309
+ payload = str(event.payload or "")
310
+ mode = event.mode or "complete"
311
+ stream_id = event.stream_id or f"{event.kind}:anonymous"
312
+
313
+ if mode == "complete":
314
+ prefix = self._close_active()
315
+ suffix = "" if payload.endswith("\n") else "\n"
316
+ spacer = " " if payload else ""
317
+ return f"{prefix}{label}{spacer}{payload}{suffix}"
318
+
319
+ if mode == "start":
320
+ prefix = self._close_active()
321
+ self._active_stream = stream_id
322
+ return f"{prefix}{label} {payload}"
323
+
324
+ if mode == "delta":
325
+ if self._active_stream == stream_id:
326
+ return payload
327
+ prefix = self._close_active()
328
+ self._active_stream = stream_id
329
+ return f"{prefix}{label} {payload}"
330
+
331
+ if mode == "end":
332
+ if self._active_stream == stream_id:
333
+ self._active_stream = ""
334
+ return f"{payload}\n"
335
+ if not payload:
336
+ return ""
337
+ prefix = self._close_active()
338
+ suffix = "" if payload.endswith("\n") else "\n"
339
+ return f"{prefix}{label} {payload}{suffix}"
340
+
341
+ return self.render(SemanticLogEvent(event.kind, payload, stream_id, "complete"))
342
+
343
+ def finish(self):
344
+ return self._close_active()
345
+
346
+
347
+ class SemanticLogNormalizer:
348
+ """Adapt supported structured shapes into one compact semantic log stream."""
349
+
350
+ _SUCCESS_STOPS = {"stop", "end_turn", "completed", "success"}
351
+ _ERROR_STOPS = {"error", "aborted", "failed", "cancelled", "canceled"}
352
+
353
+ def __init__(self):
354
+ self.renderer = SemanticLogRenderer()
355
+ self._scope = 0
356
+ self._block_streams = {}
357
+ self._stream_buffers = {}
358
+ self._snapshots = {}
359
+ self._recent_digests = deque()
360
+ self._recent_digest_set = set()
361
+ self._recent_action_ids = deque()
362
+ self._recent_action_id_set = set()
363
+ self._recent_output_ids = deque()
364
+ self._recent_output_id_set = set()
365
+ self._max_recent = 256
366
+ self._terminal_emitted = False
367
+
368
+ @staticmethod
369
+ def _json_text(value):
370
+ if isinstance(value, str):
371
+ return value
372
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
373
+
374
+ @classmethod
375
+ def _value_text(cls, value):
376
+ if value in (None, ""):
377
+ return ""
378
+ if isinstance(value, str):
379
+ return value
380
+ if isinstance(value, list):
381
+ return "".join(cls._value_text(item) for item in value)
382
+ if isinstance(value, dict):
383
+ for key in ("text", "output", "content"):
384
+ if key in value:
385
+ return cls._value_text(value.get(key))
386
+ return cls._json_text(value)
387
+ return str(value)
388
+
389
+ def _digest(self, kind, payload):
390
+ canonical_payload = str(payload or "").rstrip()
391
+ return hashlib.sha1(f"{self._scope}\0{kind}\0{canonical_payload}".encode("utf-8")).hexdigest()
392
+
393
+ def _remember_digest(self, kind, payload):
394
+ if not payload:
395
+ return
396
+ digest = self._digest(kind, payload)
397
+ if digest in self._recent_digest_set:
398
+ return
399
+ if len(self._recent_digests) >= self._max_recent:
400
+ old = self._recent_digests.popleft()
401
+ self._recent_digest_set.discard(old)
402
+ self._recent_digests.append(digest)
403
+ self._recent_digest_set.add(digest)
404
+
405
+ def _is_recent(self, kind, payload):
406
+ return bool(payload) and self._digest(kind, payload) in self._recent_digest_set
407
+
408
+ def _remember_action_id(self, action_id):
409
+ action_id = str(action_id or "")
410
+ if not action_id or action_id in self._recent_action_id_set:
411
+ return
412
+ if len(self._recent_action_ids) >= self._max_recent:
413
+ old = self._recent_action_ids.popleft()
414
+ self._recent_action_id_set.discard(old)
415
+ self._recent_action_ids.append(action_id)
416
+ self._recent_action_id_set.add(action_id)
417
+
418
+ def _remember_output_id(self, output_id):
419
+ output_id = str(output_id or "")
420
+ if not output_id or output_id in self._recent_output_id_set:
421
+ return
422
+ if len(self._recent_output_ids) >= self._max_recent:
423
+ old = self._recent_output_ids.popleft()
424
+ self._recent_output_id_set.discard(old)
425
+ self._recent_output_ids.append(output_id)
426
+ self._recent_output_id_set.add(output_id)
427
+
428
+ def _emit(self, event):
429
+ payload = str(event.payload or "")
430
+ if event.mode == "complete":
431
+ if event.deduplicate and self._is_recent(event.kind, payload):
432
+ return ""
433
+ if event.deduplicate:
434
+ self._remember_digest(event.kind, payload)
435
+ return self.renderer.render(event)
436
+
437
+ stream_id = event.stream_id or f"{event.kind}:anonymous"
438
+ if event.mode == "start":
439
+ self._stream_buffers[stream_id] = payload
440
+ elif event.mode == "delta":
441
+ self._stream_buffers[stream_id] = self._stream_buffers.get(stream_id, "") + payload
442
+ elif event.mode == "end":
443
+ complete = self._stream_buffers.pop(stream_id, "") + payload
444
+ self._remember_digest(event.kind, complete)
445
+ return self.renderer.render(event)
446
+
447
+ def _complete(self, kind, payload, *, deduplicate=False):
448
+ payload = str(payload or "")
449
+ if not payload:
450
+ return ""
451
+ return self._emit(SemanticLogEvent(kind, payload, deduplicate=deduplicate))
452
+
453
+ def _session_end(self, payload):
454
+ if self._terminal_emitted:
455
+ return ""
456
+ self._terminal_emitted = True
457
+ return self._complete("session_end", payload)
458
+
459
+ def _stream(self, kind, stream_id, mode, payload=""):
460
+ return self._emit(SemanticLogEvent(kind, str(payload or ""), stream_id, mode))
461
+
462
+ def _snapshot(self, kind, stream_id, value, final=False):
463
+ """Render cumulative snapshots while retaining only one active full value."""
464
+ value = str(value or "")
465
+ previous = self._snapshots.get(stream_id)
466
+ rendered = ""
467
+ if previous is None:
468
+ self._snapshots[stream_id] = value
469
+ if value:
470
+ rendered += self.renderer.render(SemanticLogEvent(kind, value, stream_id, "start"))
471
+ elif value == previous:
472
+ pass
473
+ elif value.startswith(previous):
474
+ self._snapshots[stream_id] = value
475
+ rendered += self.renderer.render(
476
+ SemanticLogEvent(kind, value[len(previous) :], stream_id, "delta")
477
+ )
478
+ else:
479
+ rendered += self.renderer.render(SemanticLogEvent(kind, "", stream_id, "end"))
480
+ self._snapshots[stream_id] = value
481
+ if value:
482
+ rendered += self.renderer.render(SemanticLogEvent(kind, value, stream_id, "start"))
483
+ if final:
484
+ rendered += self.renderer.render(SemanticLogEvent(kind, "", stream_id, "end"))
485
+ self._snapshots.pop(stream_id, None)
486
+ return rendered
487
+
488
+ def _message_parts(self, message):
489
+ if not isinstance(message, dict):
490
+ return ""
491
+ rendered = ""
492
+ content = message.get("content")
493
+ if isinstance(content, str):
494
+ rendered += self._complete("final", content)
495
+ elif isinstance(content, list):
496
+ for block in content:
497
+ if not isinstance(block, dict):
498
+ continue
499
+ block_type = str(block.get("type") or "")
500
+ if block_type in {"text", "output_text"}:
501
+ rendered += self._complete(
502
+ "final",
503
+ block.get("text") or block.get("content") or "",
504
+ deduplicate=True,
505
+ )
506
+ elif block_type in {"thinking", "reasoning"}:
507
+ rendered += self._complete(
508
+ "think",
509
+ block.get("thinking") or block.get("text") or "",
510
+ deduplicate=True,
511
+ )
512
+ elif block_type == "tool_use":
513
+ action_id = block.get("id") or block.get("tool_use_id")
514
+ self._remember_action_id(action_id)
515
+ rendered += self._complete(
516
+ "action",
517
+ f"{block.get('name') or 'tool'} {self._json_text(block.get('input') or {})}",
518
+ )
519
+ elif block_type == "tool_result":
520
+ rendered += self._complete("observation", self._value_text(block.get("content")))
521
+ return rendered
522
+
523
+ def _tool_result_parts(self, message):
524
+ if not isinstance(message, dict):
525
+ return ""
526
+ rendered = ""
527
+ content = message.get("content")
528
+ if not isinstance(content, list):
529
+ return rendered
530
+ for block in content:
531
+ if isinstance(block, dict) and block.get("type") == "tool_result":
532
+ rendered += self._complete("observation", self._value_text(block.get("content")))
533
+ return rendered
534
+
535
+ def _pi_message_update(self, event):
536
+ update = event.get("assistantMessageEvent")
537
+ if not isinstance(update, dict):
538
+ return ""
539
+ subtype = str(update.get("type") or "")
540
+ index = update.get("contentIndex", 0)
541
+ stream_id = f"turn:{self._scope}:content:{index}"
542
+ if subtype == "thinking_start":
543
+ return self._stream("think", f"{stream_id}:think", "start")
544
+ if subtype == "thinking_delta":
545
+ return self._stream("think", f"{stream_id}:think", "delta", update.get("delta"))
546
+ if subtype == "thinking_end":
547
+ return self._stream("think", f"{stream_id}:think", "end")
548
+ if subtype == "text_start":
549
+ return self._stream("final", f"{stream_id}:final", "start")
550
+ if subtype == "text_delta":
551
+ return self._stream("final", f"{stream_id}:final", "delta", update.get("delta"))
552
+ if subtype == "text_end":
553
+ return self._stream("final", f"{stream_id}:final", "end")
554
+ if subtype == "toolcall_start":
555
+ partial = update.get("partial")
556
+ blocks = partial.get("content") if isinstance(partial, dict) else []
557
+ block = blocks[index] if isinstance(blocks, list) and isinstance(index, int) and index < len(blocks) else {}
558
+ action_id = block.get("id") if isinstance(block, dict) else ""
559
+ self._remember_action_id(action_id)
560
+ prefix = f"{block.get('name') or 'tool'} " if isinstance(block, dict) else "tool "
561
+ return self._stream("action", f"{stream_id}:action", "start", prefix)
562
+ if subtype == "toolcall_delta":
563
+ return self._stream("action", f"{stream_id}:action", "delta", update.get("delta"))
564
+ if subtype == "toolcall_end":
565
+ tool_call = update.get("toolCall")
566
+ if isinstance(tool_call, dict):
567
+ self._remember_action_id(tool_call.get("id"))
568
+ return self._stream("action", f"{stream_id}:action", "end")
569
+ return ""
570
+
571
+ def _content_block_event(self, event):
572
+ event_type = str(event.get("type") or "")
573
+ index = event.get("index", 0)
574
+ stream_id = f"block:{self._scope}:{index}"
575
+ if event_type == "content_block_start":
576
+ block = event.get("content_block") if isinstance(event.get("content_block"), dict) else {}
577
+ block_type = str(block.get("type") or "")
578
+ if block_type in {"thinking", "reasoning"}:
579
+ self._block_streams[index] = ("think", stream_id)
580
+ return self._stream("think", stream_id, "start", block.get("thinking") or "")
581
+ if block_type == "text":
582
+ self._block_streams[index] = ("final", stream_id)
583
+ return self._stream("final", stream_id, "start", block.get("text") or "")
584
+ if block_type == "tool_use":
585
+ self._block_streams[index] = ("action", stream_id)
586
+ self._remember_action_id(block.get("id"))
587
+ return self._stream("action", stream_id, "start", f"{block.get('name') or 'tool'} ")
588
+ return ""
589
+ if event_type == "content_block_delta":
590
+ delta = event.get("delta") if isinstance(event.get("delta"), dict) else {}
591
+ delta_type = str(delta.get("type") or "")
592
+ if delta_type in {"thinking_delta", "reasoning_delta"}:
593
+ kind = "think"
594
+ payload = delta.get("thinking") or delta.get("text") or ""
595
+ elif delta_type == "text_delta":
596
+ kind = "final"
597
+ payload = delta.get("text") or ""
598
+ elif delta_type == "input_json_delta":
599
+ kind = "action"
600
+ payload = delta.get("partial_json") or ""
601
+ else:
602
+ return ""
603
+ active_kind, active_id = self._block_streams.get(index, (kind, stream_id))
604
+ return self._stream(active_kind, active_id, "delta", payload)
605
+ if event_type == "content_block_stop":
606
+ kind, active_id = self._block_streams.pop(index, ("output", stream_id))
607
+ return self._stream(kind, active_id, "end")
608
+ return ""
609
+
610
+ def process_text(self, text):
611
+ text = str(text or "")
612
+ return self._complete("output", text.rstrip("\n")) if text.strip() else ""
613
+
614
+ def _antigravity_event(self, event):
615
+ ag_event = str(event.get("event") or "")
616
+ rendered = ""
617
+ if ag_event == "init":
618
+ self._scope += 1
619
+ return ""
620
+ if ag_event == "step_update":
621
+ payload = event.get("step_update") if isinstance(event.get("step_update"), dict) else event
622
+ step_index = payload.get("step_index", 0)
623
+ step_type = str(payload.get("step_type") or "")
624
+ state = str(payload.get("state") or "").upper()
625
+
626
+ think_id = f"ag:{self._scope}:{step_index}:think"
627
+ thinking_delta = payload.get("thinking_delta")
628
+ thinking_text = payload.get("thinking")
629
+ if isinstance(thinking_delta, str) and thinking_delta:
630
+ rendered += self._stream("think", think_id, "delta", thinking_delta)
631
+ elif step_type == "thinking" and isinstance(thinking_text, str) and thinking_text:
632
+ rendered += self._complete("think", thinking_text, deduplicate=True)
633
+ if state in {"DONE", "COMPLETED"} and think_id in self._stream_buffers:
634
+ rendered += self._stream("think", think_id, "end")
635
+
636
+ final_id = f"ag:{self._scope}:{step_index}:final"
637
+ text_delta = payload.get("text_delta")
638
+ text = payload.get("text") or payload.get("response")
639
+ if isinstance(text_delta, str) and text_delta:
640
+ rendered += self._stream("final", final_id, "delta", text_delta)
641
+ elif (
642
+ step_type == "agent_response"
643
+ and isinstance(text, str)
644
+ and text
645
+ and final_id not in self._stream_buffers
646
+ ):
647
+ if state in {"DONE", "COMPLETED"}:
648
+ rendered += self._complete("final", text, deduplicate=True)
649
+ else:
650
+ rendered += self._snapshot("final", final_id, text, final=False)
651
+ if state in {"DONE", "COMPLETED"}:
652
+ if final_id in self._stream_buffers:
653
+ rendered += self._stream("final", final_id, "end")
654
+ elif final_id in self._snapshots:
655
+ rendered += self._snapshot("final", final_id, self._snapshots[final_id], final=True)
656
+
657
+ tool_info = payload.get("tool_info") if isinstance(payload.get("tool_info"), dict) else None
658
+ if step_type == "tool" or tool_info is not None:
659
+ info = tool_info or {}
660
+ tool_name = str(info.get("name") or payload.get("tool_name") or "tool")
661
+ params = info.get("parameters") or info.get("args") or {}
662
+ action_key = f"ag:{self._scope}:{step_index}:{tool_name}"
663
+ if action_key not in self._recent_action_id_set:
664
+ self._remember_action_id(action_key)
665
+ rendered += self._complete("action", f"{tool_name} {_cursor_compact_value(params)}")
666
+ if (
667
+ state in {"DONE", "COMPLETED", "ERROR", "FAILED"}
668
+ or info.get("output") not in (None, "")
669
+ or info.get("error")
670
+ ):
671
+ output = info.get("output")
672
+ obs_key = f"{action_key}:obs"
673
+ if output not in (None, "") and obs_key not in self._recent_output_id_set:
674
+ self._remember_output_id(obs_key)
675
+ rendered += self._complete("observation", f"{tool_name} {_cursor_compact_value(output)}")
676
+ tool_err = info.get("error")
677
+ err_key = f"{action_key}:err"
678
+ if tool_err and err_key not in self._recent_output_id_set:
679
+ self._remember_output_id(err_key)
680
+ rendered += self._complete("error", f"{tool_name} failed: {self._value_text(tool_err)}")
681
+
682
+ step_err = payload.get("error")
683
+ if step_err:
684
+ rendered += self._complete("error", self._value_text(step_err))
685
+ return rendered
686
+
687
+ if ag_event == "result":
688
+ for sid in list(self._stream_buffers):
689
+ kind = "final" if sid.endswith(":final") else "think"
690
+ rendered += self._stream(kind, sid, "end")
691
+ for sid in list(self._snapshots):
692
+ kind = "final" if sid.endswith(":final") else "think"
693
+ rendered += self._snapshot(kind, sid, self._snapshots[sid], final=True)
694
+ result_payload = event.get("result") if isinstance(event.get("result"), dict) else event
695
+ raw_status = str(result_payload.get("status") or event.get("status") or "")
696
+ err_val = result_payload.get("error") if result_payload.get("error") is not None else event.get("error")
697
+ normalized_status = raw_status.strip().lower()
698
+ is_error = bool(
699
+ event.get("is_error")
700
+ or result_payload.get("is_error")
701
+ or err_val
702
+ or normalized_status in self._ERROR_STOPS
703
+ or normalized_status.startswith(("error", "failed", "failure", "cancel"))
704
+ )
705
+ resp_val = (
706
+ result_payload.get("response")
707
+ or result_payload.get("result")
708
+ or result_payload.get("message")
709
+ or event.get("response")
710
+ or event.get("message")
711
+ or ""
712
+ )
713
+ if isinstance(resp_val, dict):
714
+ resp_val = ""
715
+ if err_val and is_error:
716
+ rendered += self._complete("error", self._value_text(err_val))
717
+ elif resp_val:
718
+ rendered += self._complete(
719
+ "error" if is_error else "final",
720
+ self._value_text(resp_val),
721
+ deduplicate=not is_error,
722
+ )
723
+ rendered += self._session_end(f"status={'error' if is_error else 'success'}")
724
+ return rendered
725
+
726
+ if ag_event == "error":
727
+ return self._complete(
728
+ "error",
729
+ self._value_text(event.get("error") or event.get("message") or "runtime error"),
730
+ )
731
+ return ""
732
+
733
+ def process_event(self, event):
734
+ if not isinstance(event, dict):
735
+ return self.process_text(event)
736
+ if isinstance(event.get("event"), str) and not event.get("type"):
737
+ return self._antigravity_event(event)
738
+ event_type = str(event.get("type") or "")
739
+ rendered = ""
740
+
741
+ if event_type == "turn_start" or event_type == "turn.started":
742
+ self._scope += 1
743
+
744
+ if event_type == "message_update" and isinstance(event.get("assistantMessageEvent"), dict):
745
+ return self._pi_message_update(event)
746
+
747
+ if event_type == "message_end":
748
+ message = event.get("message")
749
+ if isinstance(message, dict):
750
+ role = str(message.get("role") or "")
751
+ if role == "assistant":
752
+ rendered += self._message_parts(message)
753
+ elif role == "toolResult":
754
+ output_id = str(message.get("toolCallId") or "")
755
+ if output_id not in self._recent_output_id_set:
756
+ self._remember_output_id(output_id)
757
+ rendered += self._complete("observation", self._value_text(message.get("content")))
758
+ stop_reason = str(message.get("stopReason") or "")
759
+ if stop_reason in self._ERROR_STOPS:
760
+ rendered += self._complete("error", message.get("errorMessage") or stop_reason)
761
+ return rendered
762
+
763
+ if event_type in {"turn_end", "agent_settled", "agent_start", "session", "thread.started", "turn.started"}:
764
+ return ""
765
+
766
+ if event_type == "tool_execution_start":
767
+ action_id = str(event.get("toolCallId") or event.get("id") or "")
768
+ if action_id in self._recent_action_id_set:
769
+ return ""
770
+ self._remember_action_id(action_id)
771
+ return self._complete(
772
+ "action",
773
+ f"{event.get('toolName') or 'tool'} {self._json_text(event.get('args') or {})}",
774
+ )
775
+
776
+ if event_type == "tool_execution_update":
777
+ stream_id = f"tool:{event.get('toolCallId') or event.get('id') or 'active'}:output"
778
+ return self._snapshot("observation", stream_id, self._value_text(event.get("partialResult")))
779
+
780
+ if event_type == "tool_execution_end":
781
+ output_id = str(event.get("toolCallId") or event.get("id") or "")
782
+ self._remember_output_id(output_id)
783
+ stream_id = f"tool:{output_id or 'active'}:output"
784
+ result_text = self._value_text(event.get("result"))
785
+ had_output = stream_id in self._snapshots and bool(self._snapshots.get(stream_id))
786
+ rendered += self._snapshot("observation", stream_id, result_text, final=True)
787
+ if event.get("isError"):
788
+ error_payload = f"{event.get('toolName') or 'tool'} failed"
789
+ if not had_output and result_text:
790
+ error_payload = f"{error_payload}: {result_text}"
791
+ rendered += self._complete("error", error_payload)
792
+ return rendered
793
+
794
+ if event_type == "auto_retry_start":
795
+ message = event.get("errorMessage") or event.get("finalError") or "retrying transient error"
796
+ return self._complete("error", f"retry attempt {event.get('attempt') or '?'}: {message}")
797
+ if event_type in {"auto_retry_end", "queue_update"}:
798
+ return ""
799
+ if event_type == "compaction_start":
800
+ return self._complete("action", "context compaction started")
801
+ if event_type == "compaction_end":
802
+ if event.get("errorMessage") or event.get("finalError"):
803
+ return self._complete("error", event.get("errorMessage") or event.get("finalError"))
804
+ return self._complete("observation", "context compaction completed")
805
+
806
+ if event_type == "agent_end":
807
+ messages = event.get("messages") if isinstance(event.get("messages"), list) else []
808
+ last_message = messages[-1] if messages and isinstance(messages[-1], dict) else {}
809
+ stop_reason = str(last_message.get("stopReason") or "")
810
+ will_retry = bool(event.get("willRetry"))
811
+ if will_retry:
812
+ return ""
813
+ status = "error" if stop_reason in self._ERROR_STOPS else "success"
814
+ details = f"status={status}"
815
+ if stop_reason:
816
+ details += f" stop_reason={stop_reason}"
817
+ return self._session_end(details)
818
+
819
+ if event_type in {"content_block_start", "content_block_delta", "content_block_stop"}:
820
+ return self._content_block_event(event)
821
+ if event_type == "message_start":
822
+ self._scope += 1
823
+ return ""
824
+ if event_type == "message_stop":
825
+ return self.renderer.finish()
826
+
827
+ if event_type == "tool_call":
828
+ tool_name, arguments, result, is_error = _cursor_tool_call_parts(event)
829
+ call_id = str(event.get("call_id") or "")
830
+ if event.get("subtype") == "started":
831
+ self._remember_action_id(call_id)
832
+ return self._complete("action", f"{tool_name} {_cursor_compact_value(arguments)}")
833
+ if event.get("subtype") == "completed":
834
+ rendered += self._complete("observation", f"{tool_name} {_cursor_compact_value(result)}")
835
+ if is_error:
836
+ rendered += self._complete("error", f"{tool_name} failed")
837
+ return rendered
838
+ return ""
839
+
840
+ if event_type == "assistant":
841
+ self._scope += 1
842
+ return self._message_parts(event.get("message"))
843
+ if event_type == "message" and isinstance(event.get("sessionId"), str):
844
+ if event.get("role") == "assistant":
845
+ self._scope += 1
846
+ return self._message_parts(event)
847
+ return ""
848
+ if event_type == "tool_result":
849
+ return self._complete("observation", self._value_text(event.get("content")))
850
+ if event_type == "user" and not isinstance(event.get("sessionId"), str):
851
+ return self._tool_result_parts(event.get("message"))
852
+ if event_type == "function_call":
853
+ self._remember_action_id(event.get("id") or event.get("call_id"))
854
+ return self._complete(
855
+ "action",
856
+ f"{event.get('name') or 'tool'} {self._value_text(event.get('arguments'))}",
857
+ )
858
+ if event_type == "function_call_result":
859
+ return self._complete("observation", self._value_text(event.get("output") or event.get("result")))
860
+
861
+ if event_type in {"item.started", "item.completed"}:
862
+ item = event.get("item") if isinstance(event.get("item"), dict) else {}
863
+ item_type = str(item.get("type") or "")
864
+ item_id = str(item.get("id") or item.get("call_id") or _stable_subagent_digest(item))
865
+ if item_type in {"reasoning", "analysis"} and event_type == "item.completed":
866
+ return self._complete("think", self._value_text(item.get("text") or item.get("summary") or ""))
867
+ if item_type == "agent_message" and event_type == "item.completed":
868
+ return self._complete("final", item.get("text") or "")
869
+ if item_type in {"command_execution", "mcp_tool_call", "collab_tool_call"}:
870
+ command = item.get("command") or item.get("tool") or item.get("name") or item_type
871
+ if event_type == "item.started":
872
+ self._remember_action_id(item_id)
873
+ return self._complete("action", self._value_text(command))
874
+ if item_id not in self._recent_action_id_set:
875
+ self._remember_action_id(item_id)
876
+ rendered += self._complete("action", self._value_text(command))
877
+ output = item.get("aggregated_output") or item.get("output") or item.get("result")
878
+ rendered += self._complete("observation", self._value_text(output))
879
+ if str(item.get("status") or "") in self._ERROR_STOPS:
880
+ rendered += self._complete("error", self._value_text(item.get("error") or "command failed"))
881
+ return rendered
882
+ if event_type == "item.completed" and item_type in {"file_change", "web_search"}:
883
+ return self._complete("action", self._value_text(item))
884
+ return ""
885
+
886
+ if event_type == "turn.completed":
887
+ return self._session_end("status=success")
888
+ if event_type == "turn.failed":
889
+ error_text = self._value_text(event.get("error") or event.get("message") or "turn failed")
890
+ return self._complete("error", error_text) + self._session_end("status=error")
891
+ if event_type == "result":
892
+ subtype = str(event.get("subtype") or event.get("result_subtype") or "")
893
+ normalized_subtype = subtype.lower()
894
+ is_error = (
895
+ bool(event.get("is_error"))
896
+ or normalized_subtype in self._ERROR_STOPS
897
+ or normalized_subtype.startswith(("error", "failed", "cancel"))
898
+ )
899
+ result_text = self._value_text(event.get("result") or event.get("message"))
900
+ if result_text:
901
+ rendered += self._complete(
902
+ "error" if is_error else "final",
903
+ result_text,
904
+ deduplicate=not is_error,
905
+ )
906
+ rendered += self._session_end(
907
+ f"status={'error' if is_error else 'success'}"
908
+ + (f" stop_reason={event.get('stop_reason')}" if event.get("stop_reason") else ""),
909
+ )
910
+ return rendered
911
+ if event_type == "error" or event.get("error"):
912
+ return self._complete(
913
+ "error",
914
+ self._value_text(event.get("error") or event.get("message") or "runtime error"),
915
+ )
916
+ return ""
917
+
918
+ def finish(self):
919
+ rendered = self.renderer.finish()
920
+ if not self._terminal_emitted:
921
+ rendered += self._session_end("status=stream_closed")
922
+ self._stream_buffers.clear()
923
+ self._snapshots.clear()
924
+ return rendered
925
+
926
+
927
+ class ProgressTracker:
928
+ """Tracks progress state from stream-json events."""
929
+
930
+ SUPPORTS_UNLOCKED_CHILD_REFRESH = True
931
+
932
+ def __init__(self, session_log=None, provider_hint=None):
933
+ self.session_log_path = Path(session_log).expanduser() if session_log else None
934
+ self.provider_hint = str(provider_hint or "").strip().lower()
935
+ self.message_count = 0
936
+ self.event_type_counts = Counter()
937
+ self.current_tool = None
938
+ self.current_tool_input_summary = ""
939
+ self.current_phase = None
940
+ self.detected_phases = []
941
+ self.tool_call_counts = Counter()
942
+ self.total_tool_calls = 0
943
+ self.last_text_snippet = ""
944
+ self.last_result_is_error = False
945
+ self.api_error_status = None
946
+ self.api_error_code = ""
947
+ self.terminal_result_text = ""
948
+ self.terminal_success_at = ""
949
+ self.fatal_error_code = ""
950
+ self.is_active = True
951
+ self.errors = []
952
+ self.event_format = ""
953
+ self.active_subagents = 0
954
+ self.subagent_status_counts = Counter()
955
+ self.subagents_spawned = 0
956
+ self.subagent_records = {}
957
+ self.subagent_aliases = {}
958
+ self.subagent_source_providers = set()
959
+ self.subagent_source_events = Counter()
960
+ self.parent_subagent_activity_ids = set()
961
+ self.codex_child_thread_ids = set()
962
+ self.cb_session_id = ""
963
+ self.cursor_session_id = ""
964
+ self.antigravity_session_id = ""
965
+ self._ag_seen_response_steps = set()
966
+ self._ag_seen_tool_steps = set()
967
+ self.result_subtype = ""
968
+ self.stop_reason = ""
969
+ self.has_usage = False
970
+ self.permission_denials = []
971
+ self.cb_cwd = ""
972
+ self.claude_session_id = ""
973
+ self.claude_cwd = ""
974
+ self.claude_task_states = {}
975
+ self.child_session_files = []
976
+ self.child_total_bytes = 0
977
+ self.child_activity_signature = ""
978
+ self.last_child_activity_at = ""
979
+ self._codex_child_session_paths = {}
980
+ self._claude_child_session_files = []
981
+ self._cb_child_session_files = []
982
+ self._last_child_scan_at = 0.0
983
+ self._last_claude_fallback_scan_at = 0.0
984
+ self._last_claude_fallback_scan_key = ""
985
+ self._claude_fallback_scan_interval_seconds = 10.0
986
+ self._text_buffer = ""
987
+ self._in_tool_use = False
988
+ self._current_tool_input_parts = []
989
+ self._current_tool_input_len = 0
990
+ self._current_tool_id = ""
991
+ self._pi_retrying_terminal_error = False
992
+
993
+ def _append_error(self, error_entry) -> None:
994
+ if error_entry in (None, ""):
995
+ return
996
+ if isinstance(error_entry, str):
997
+ entry = error_entry[:500]
998
+ else:
999
+ entry = error_entry
1000
+ self.errors.append(entry)
1001
+ if len(self.errors) > 20:
1002
+ self.errors = self.errors[-20:]
1003
+
1004
+ def process_event(self, event):
1005
+ """Process a single stream-json event and update state.
1006
+
1007
+ Supports Claude API/CLI, CodeBuddy, Codex JSONL, Pi JSONL, Cursor, and Antigravity formats.
1008
+ """
1009
+ if not isinstance(event, dict):
1010
+ return
1011
+ event_type = str(event.get("type") or event.get("event") or "")
1012
+ if event_type:
1013
+ self.event_type_counts[event_type] += 1
1014
+ self._detect_structured_terminal_fields(event)
1015
+ self._record_usage_and_permission_metadata(event)
1016
+ parent_tool_use_id = event.get("parent_tool_use_id")
1017
+ if isinstance(parent_tool_use_id, str) and parent_tool_use_id.strip():
1018
+ parent_tool_use_id = parent_tool_use_id.strip()
1019
+ self.parent_subagent_activity_ids.add(parent_tool_use_id)
1020
+ self._record_subagent_event(
1021
+ "claude",
1022
+ "parent_tool_use_id",
1023
+ identifier=parent_tool_use_id,
1024
+ aliases=[parent_tool_use_id],
1025
+ status="running",
1026
+ active=True,
1027
+ spawn=False,
1028
+ metadata={"parent_tool_use_id": parent_tool_use_id},
1029
+ )
1030
+
1031
+ self._record_structured_subagent_metadata(event)
1032
+
1033
+ # ── Antigravity agy --output-format stream-json ──────────────
1034
+ is_antigravity_event = (
1035
+ self.provider_hint == "antigravity"
1036
+ or self.event_format == "antigravity-stream-json"
1037
+ or (
1038
+ not event.get("type")
1039
+ and event.get("event") in {"init", "step_update", "result", "error"}
1040
+ )
1041
+ )
1042
+ if is_antigravity_event:
1043
+ self.event_format = "antigravity-stream-json"
1044
+ for container in (event, event.get("init"), event.get("step_update"), event.get("result")):
1045
+ if isinstance(container, dict):
1046
+ conv_id = container.get("conversation_id")
1047
+ if isinstance(conv_id, str) and conv_id.strip() and not self.antigravity_session_id:
1048
+ self.antigravity_session_id = conv_id.strip()
1049
+ break
1050
+ if event_type == "init":
1051
+ self.is_active = True
1052
+ elif event_type == "step_update":
1053
+ self.is_active = True
1054
+ payload = event.get("step_update") if isinstance(event.get("step_update"), dict) else event
1055
+ step_index = payload.get("step_index")
1056
+ step_type = str(payload.get("step_type") or "")
1057
+ state = str(payload.get("state") or "").upper()
1058
+ if step_type == "agent_response" or payload.get("text_delta") or payload.get("text"):
1059
+ if step_index is not None:
1060
+ if step_index not in self._ag_seen_response_steps:
1061
+ self._ag_seen_response_steps.add(step_index)
1062
+ self.message_count += 1
1063
+ else:
1064
+ self.message_count += 1
1065
+ text = str(payload.get("text") or payload.get("text_delta") or "")
1066
+ if text.strip():
1067
+ self.last_text_snippet = text.strip()[-120:]
1068
+ self._detect_phase(text)
1069
+ self._detect_terminal_error(text, require_error_context=True)
1070
+ if step_type == "tool" or isinstance(payload.get("tool_info"), dict):
1071
+ info = payload.get("tool_info") if isinstance(payload.get("tool_info"), dict) else {}
1072
+ tool_name = str(info.get("name") or payload.get("tool_name") or "unknown")
1073
+ params = info.get("parameters") or info.get("args") or {}
1074
+ tool_key = (step_index, tool_name) if step_index is not None else None
1075
+ if tool_key is None or tool_key not in self._ag_seen_tool_steps:
1076
+ if tool_key is not None:
1077
+ self._ag_seen_tool_steps.add(tool_key)
1078
+ self.current_tool = tool_name
1079
+ self.tool_call_counts[tool_name] += 1
1080
+ self.total_tool_calls += 1
1081
+ if isinstance(params, dict):
1082
+ self._extract_tool_summary_from_dict(params)
1083
+ else:
1084
+ self._extract_tool_summary(str(params))
1085
+ self._detect_phase(_cursor_compact_value(params, 500))
1086
+ if tool_name == "invoke_subagent" and isinstance(params, dict):
1087
+ self._record_subagent_event(
1088
+ "antigravity",
1089
+ "step_update.tool",
1090
+ identifier=str(tool_key or f"ag-subagent-{self.total_tool_calls}"),
1091
+ status=(
1092
+ "error"
1093
+ if info.get("error")
1094
+ else ("completed" if state in {"DONE", "COMPLETED"} else "running")
1095
+ ),
1096
+ active=state not in {"DONE", "COMPLETED", "ERROR", "FAILED"},
1097
+ spawn=True,
1098
+ metadata={
1099
+ "tool": tool_name,
1100
+ "subagent_type": params.get("TypeName", ""),
1101
+ "description": params.get("Role", ""),
1102
+ },
1103
+ )
1104
+ if state in {"DONE", "COMPLETED", "ERROR", "FAILED"}:
1105
+ self.current_tool = None
1106
+ if tool_name == "invoke_subagent":
1107
+ self._record_subagent_event(
1108
+ "antigravity",
1109
+ "step_update.tool",
1110
+ identifier=str(tool_key or f"ag-subagent-{self.total_tool_calls}"),
1111
+ status="error" if info.get("error") else "completed",
1112
+ active=False,
1113
+ spawn=True,
1114
+ )
1115
+ tool_err = info.get("error")
1116
+ if tool_err:
1117
+ error_text = _cursor_compact_value(tool_err, 500)
1118
+ self._append_error(error_text)
1119
+ self._detect_terminal_error(error_text, require_error_context=False)
1120
+ step_err = payload.get("error")
1121
+ if step_err:
1122
+ error_text = _cursor_compact_value(step_err, 500)
1123
+ self._append_error(error_text)
1124
+ self._detect_terminal_error(error_text, require_error_context=False)
1125
+ elif event_type == "result":
1126
+ self.current_tool = None
1127
+ self.is_active = False
1128
+ result_payload = event.get("result") if isinstance(event.get("result"), dict) else event
1129
+ raw_status = str(
1130
+ result_payload.get("status")
1131
+ or event.get("status")
1132
+ or result_payload.get("subtype")
1133
+ or event.get("subtype")
1134
+ or ""
1135
+ )
1136
+ error_obj = (
1137
+ result_payload.get("error") if result_payload.get("error") is not None else event.get("error")
1138
+ )
1139
+ normalized_status = raw_status.strip().lower()
1140
+ is_error = bool(
1141
+ event.get("is_error")
1142
+ or result_payload.get("is_error")
1143
+ or error_obj
1144
+ or normalized_status in {"error", "failed", "failure", "aborted", "cancelled", "canceled"}
1145
+ )
1146
+ if is_error:
1147
+ self.result_subtype = "error"
1148
+ elif normalized_status in {"", "success", "ok", "completed"}:
1149
+ self.result_subtype = "success"
1150
+ else:
1151
+ self.result_subtype = normalized_status
1152
+ resp_text = (
1153
+ result_payload.get("response")
1154
+ or result_payload.get("result")
1155
+ or result_payload.get("message")
1156
+ or event.get("response")
1157
+ or event.get("message")
1158
+ or ""
1159
+ )
1160
+ if isinstance(resp_text, dict):
1161
+ resp_text = ""
1162
+ err_code = str(
1163
+ result_payload.get("error_code")
1164
+ or event.get("error_code")
1165
+ or event.get("api_error_code")
1166
+ or ""
1167
+ )
1168
+ err_msg = ""
1169
+ if isinstance(error_obj, dict):
1170
+ if not err_code:
1171
+ err_code = str(error_obj.get("code") or error_obj.get("type") or "")
1172
+ err_msg = " ".join(
1173
+ str(error_obj.get(key) or "")
1174
+ for key in ("type", "code", "message")
1175
+ if error_obj.get(key)
1176
+ )
1177
+ elif error_obj:
1178
+ err_msg = str(error_obj)
1179
+ if err_msg:
1180
+ self._append_error(err_msg)
1181
+ combined_text = " ".join(part for part in (str(resp_text), err_msg) if part)
1182
+ self._record_terminal_result(
1183
+ text=combined_text,
1184
+ is_error=is_error,
1185
+ api_error_status=result_payload.get("api_error_status") or event.get("api_error_status"),
1186
+ api_error_code=err_code,
1187
+ stop_reason=str(result_payload.get("stop_reason") or event.get("stop_reason") or raw_status),
1188
+ )
1189
+ elif event_type == "error":
1190
+ err_obj = event.get("error")
1191
+ error_text = (
1192
+ err_obj.get("message")
1193
+ if isinstance(err_obj, dict)
1194
+ else (err_obj or event.get("message") or "Antigravity CLI error")
1195
+ )
1196
+ self._append_error(str(error_text))
1197
+ self._detect_terminal_error(str(error_text), require_error_context=False)
1198
+ return
1199
+
1200
+ # ── Cursor Agent --output-format stream-json ─────────────────
1201
+ is_cursor_event = (
1202
+ self.provider_hint == "cursor"
1203
+ or event_type == "tool_call"
1204
+ or self.event_format == "cursor-stream-json"
1205
+ )
1206
+ if is_cursor_event:
1207
+ self.event_format = "cursor-stream-json"
1208
+ if event_type == "tool_call" and not self.cursor_session_id and self.claude_session_id:
1209
+ self.cursor_session_id = self.claude_session_id
1210
+ self.claude_session_id = ""
1211
+ self.claude_cwd = ""
1212
+ session_id = event.get("session_id")
1213
+ if isinstance(session_id, str) and session_id.strip() and not self.cursor_session_id:
1214
+ self.cursor_session_id = session_id.strip()
1215
+ if event_type == "system" and event.get("subtype") == "init":
1216
+ self.is_active = True
1217
+ elif event_type == "assistant":
1218
+ self.message_count += 1
1219
+ self.is_active = True
1220
+ message = event.get("message") if isinstance(event.get("message"), dict) else {}
1221
+ content = message.get("content")
1222
+ texts = []
1223
+ if isinstance(content, str):
1224
+ texts = [content]
1225
+ elif isinstance(content, list):
1226
+ texts = [
1227
+ str(item.get("text") or "")
1228
+ for item in content
1229
+ if isinstance(item, dict) and item.get("type") in {"text", "output_text"}
1230
+ ]
1231
+ text = "\n".join(part for part in texts if part)
1232
+ if text.strip():
1233
+ self.last_text_snippet = text.strip()[-120:]
1234
+ self._detect_phase(text)
1235
+ self._detect_terminal_error(text, require_error_context=True)
1236
+ elif event_type == "tool_call":
1237
+ tool_name, arguments, result, is_error = _cursor_tool_call_parts(event)
1238
+ subtype = str(event.get("subtype") or "")
1239
+ if subtype == "started":
1240
+ self.current_tool = tool_name
1241
+ self.tool_call_counts[tool_name] += 1
1242
+ self.total_tool_calls += 1
1243
+ self.is_active = True
1244
+ if isinstance(arguments, dict):
1245
+ self._extract_tool_summary_from_dict(arguments)
1246
+ else:
1247
+ self._extract_tool_summary(str(arguments))
1248
+ self._detect_phase(_cursor_compact_value(arguments, 500))
1249
+ self._record_agent_tool_call(
1250
+ "cursor",
1251
+ tool_name,
1252
+ arguments,
1253
+ source_event="tool_call.started",
1254
+ event_id=str(event.get("call_id") or ""),
1255
+ )
1256
+ elif subtype == "completed":
1257
+ self.current_tool = None
1258
+ if is_error:
1259
+ error_text = _cursor_compact_value(result, 500)
1260
+ self._append_error(error_text)
1261
+ self._detect_terminal_error(error_text, require_error_context=True)
1262
+ elif event_type == "result":
1263
+ self.current_tool = None
1264
+ self.is_active = False
1265
+ self.result_subtype = str(event.get("subtype") or "")
1266
+ result_text = str(event.get("result") or event.get("message") or "")
1267
+ self._record_terminal_result(
1268
+ text=result_text,
1269
+ is_error=bool(event.get("is_error")) or self.result_subtype.lower() != "success",
1270
+ api_error_status=event.get("api_error_status"),
1271
+ api_error_code=str(event.get("error_code") or ""),
1272
+ stop_reason=str(event.get("stop_reason") or ""),
1273
+ )
1274
+ elif event_type == "error":
1275
+ error_text = _extract_error_text(event.get("error") or event.get("message") or "Cursor Agent error")
1276
+ self._append_error(error_text)
1277
+ self._detect_terminal_error(error_text, require_error_context=True)
1278
+ return
1279
+
1280
+ # ── Pi --mode json JSONL format ─────────────────────────────
1281
+ pi_unique_start_events = {
1282
+ "session",
1283
+ "agent_start",
1284
+ "agent_end",
1285
+ "turn_start",
1286
+ "turn_end",
1287
+ "message_update",
1288
+ "message_end",
1289
+ "tool_execution_start",
1290
+ "tool_execution_update",
1291
+ "tool_execution_end",
1292
+ "queue_update",
1293
+ "compaction_start",
1294
+ "compaction_end",
1295
+ "auto_retry_start",
1296
+ "auto_retry_end",
1297
+ }
1298
+ pi_event_types = pi_unique_start_events | {"message_start"}
1299
+ is_pi_event = (
1300
+ event_type in pi_unique_start_events
1301
+ or (self.provider_hint == "pi" and event_type in pi_event_types)
1302
+ or (self.event_format == "pi-json" and event_type in pi_event_types)
1303
+ )
1304
+ if is_pi_event:
1305
+ self.event_format = "pi-json"
1306
+ if event_type in {
1307
+ "agent_start",
1308
+ "turn_start",
1309
+ "message_start",
1310
+ "message_update",
1311
+ "tool_execution_start",
1312
+ "tool_execution_update",
1313
+ "compaction_start",
1314
+ "auto_retry_start",
1315
+ }:
1316
+ self.is_active = True
1317
+ if event_type == "agent_start" and self._pi_retrying_terminal_error:
1318
+ self.result_subtype = ""
1319
+ self.stop_reason = ""
1320
+ self.last_result_is_error = False
1321
+ self.api_error_status = None
1322
+ self.api_error_code = ""
1323
+ self.fatal_error_code = ""
1324
+ self.terminal_result_text = ""
1325
+ self.terminal_success_at = ""
1326
+ if event_type == "turn_start":
1327
+ self.message_count += 1
1328
+ elif event_type in {"message_update", "message_end"}:
1329
+ assistant_event = event.get("assistantMessageEvent")
1330
+ message = event.get("message")
1331
+ text = ""
1332
+ if isinstance(assistant_event, dict):
1333
+ text = str(assistant_event.get("delta") or assistant_event.get("text") or "")
1334
+ if not text and isinstance(message, dict):
1335
+ content = message.get("content")
1336
+ if isinstance(content, str):
1337
+ text = content
1338
+ elif isinstance(content, list):
1339
+ text = "\n".join(
1340
+ str(item.get("text") or "")
1341
+ for item in content
1342
+ if isinstance(item, dict)
1343
+ )
1344
+ if text.strip():
1345
+ self.last_text_snippet = text.strip()[-120:]
1346
+ self._detect_phase(text)
1347
+ if (
1348
+ event_type == "message_end"
1349
+ and isinstance(message, dict)
1350
+ and message.get("role") == "assistant"
1351
+ ):
1352
+ stop_reason = str(message.get("stopReason") or "")
1353
+ if stop_reason:
1354
+ self.stop_reason = stop_reason
1355
+ if stop_reason in {"error", "aborted"}:
1356
+ error_text = str(message.get("errorMessage") or stop_reason)
1357
+ self.result_subtype = "error"
1358
+ self.last_result_is_error = True
1359
+ self.terminal_result_text = error_text[:1000]
1360
+ self._append_error(error_text)
1361
+ self._detect_terminal_error(error_text, require_error_context=True)
1362
+ elif event_type == "tool_execution_start":
1363
+ tool_name = str(event.get("toolName") or "unknown")
1364
+ self.current_tool = tool_name
1365
+ self.tool_call_counts[tool_name] += 1
1366
+ self.total_tool_calls += 1
1367
+ args = event.get("args")
1368
+ if isinstance(args, dict):
1369
+ self._extract_tool_summary_from_dict(args)
1370
+ self._detect_phase(json.dumps(args, ensure_ascii=False)[:500])
1371
+ elif event_type == "tool_execution_end":
1372
+ self.current_tool = None
1373
+ if event.get("isError"):
1374
+ result = event.get("result")
1375
+ error_text = json.dumps(result, ensure_ascii=False, default=str)
1376
+ self._append_error(error_text)
1377
+ self._detect_terminal_error(error_text, require_error_context=True)
1378
+ elif event_type in {"compaction_end", "auto_retry_end"}:
1379
+ error_text = str(event.get("errorMessage") or event.get("finalError") or "")
1380
+ if error_text:
1381
+ self._append_error(error_text)
1382
+ self._detect_terminal_error(error_text, require_error_context=True)
1383
+ elif event_type == "agent_end":
1384
+ self.current_tool = None
1385
+ self.is_active = False
1386
+ messages = event.get("messages") if isinstance(event.get("messages"), list) else []
1387
+ final_message = messages[-1] if messages and isinstance(messages[-1], dict) else {}
1388
+ final_stop_reason = str(final_message.get("stopReason") or self.stop_reason or "")
1389
+ will_retry = bool(event.get("willRetry"))
1390
+ if will_retry:
1391
+ self._pi_retrying_terminal_error = bool(
1392
+ self.result_subtype == "error"
1393
+ or self.last_result_is_error
1394
+ or self.fatal_error_code
1395
+ )
1396
+ elif final_stop_reason not in {"error", "aborted", "failed", "cancelled", "canceled"} and (
1397
+ self.result_subtype != "error" or self._pi_retrying_terminal_error
1398
+ ):
1399
+ self.result_subtype = "success"
1400
+ self.stop_reason = final_stop_reason or self.stop_reason
1401
+ self.last_result_is_error = False
1402
+ if self._pi_retrying_terminal_error:
1403
+ self.api_error_status = None
1404
+ self.api_error_code = ""
1405
+ self.fatal_error_code = ""
1406
+ final_text = ""
1407
+ content = final_message.get("content") if isinstance(final_message, dict) else None
1408
+ if isinstance(content, str):
1409
+ final_text = content
1410
+ elif isinstance(content, list):
1411
+ final_text = "\n".join(
1412
+ str(item.get("text") or "")
1413
+ for item in content
1414
+ if isinstance(item, dict) and item.get("type") == "text"
1415
+ )
1416
+ if final_text.strip():
1417
+ self.terminal_result_text = final_text[:1000]
1418
+ self.last_text_snippet = final_text.strip()[-120:]
1419
+ self.terminal_success_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
1420
+ self._pi_retrying_terminal_error = False
1421
+ return
1422
+
1423
+ # ── Codex exec --json JSONL format ──────────────────────────
1424
+ codex_only_events = {
1425
+ "thread.started",
1426
+ "turn.started",
1427
+ "turn.completed",
1428
+ "turn.failed",
1429
+ "item.started",
1430
+ "item.completed",
1431
+ }
1432
+ is_codex_event = event_type in codex_only_events or (
1433
+ event_type == "error"
1434
+ and (self.provider_hint == "codex" or self.event_format == "codex-json")
1435
+ )
1436
+ if is_codex_event:
1437
+ self.event_format = "codex-json"
1438
+ if event_type in {"thread.started", "turn.started", "item.started", "item.completed"}:
1439
+ self.is_active = True
1440
+
1441
+ if event_type == "turn.started":
1442
+ self.message_count += 1
1443
+
1444
+ elif event_type in ("item.started", "item.completed"):
1445
+ item = event.get("item")
1446
+ item = item if isinstance(item, dict) else {}
1447
+ item_type = str(item.get("type") or "")
1448
+ item_status = _normalize_status(item.get("status"), default="")
1449
+
1450
+ if item_type == "agent_message":
1451
+ text = str(item.get("text") or "")
1452
+ if text.strip():
1453
+ self.last_text_snippet = text.strip()[:120]
1454
+ self._detect_phase(text)
1455
+
1456
+ elif item_type == "collab_tool_call":
1457
+ tool_name = str(item.get("tool") or "collab")
1458
+ if event_type == "item.started":
1459
+ self.current_tool = tool_name
1460
+ self.tool_call_counts[tool_name] += 1
1461
+ self.total_tool_calls += 1
1462
+ elif event_type == "item.completed" or item_status in TERMINAL_SUBAGENT_STATUSES:
1463
+ self.current_tool = None
1464
+ self._extract_tool_summary_from_dict(item)
1465
+
1466
+ prompt = item.get("prompt")
1467
+ if isinstance(prompt, str) and prompt:
1468
+ self._detect_phase(prompt)
1469
+
1470
+ else:
1471
+ tool_name = item.get("tool") or item.get("name")
1472
+ if tool_name:
1473
+ if event_type == "item.started":
1474
+ self.current_tool = str(tool_name)
1475
+ self.tool_call_counts[str(tool_name)] += 1
1476
+ self.total_tool_calls += 1
1477
+ elif event_type == "item.completed" or item_status in TERMINAL_SUBAGENT_STATUSES:
1478
+ self.current_tool = None
1479
+ self._extract_tool_summary_from_dict(item)
1480
+
1481
+ elif event_type == "turn.completed":
1482
+ self.current_tool = None
1483
+ self.is_active = False
1484
+ if not self.fatal_error_code:
1485
+ self.result_subtype = "success"
1486
+ self.stop_reason = "completed"
1487
+ self.last_result_is_error = False
1488
+ self.terminal_success_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
1489
+
1490
+ elif event_type == "turn.failed":
1491
+ error_text = _extract_error_text(event.get("error") or event.get("message") or "Codex turn failed")
1492
+ self._append_error(error_text)
1493
+ self._detect_terminal_error(error_text)
1494
+ self.result_subtype = "error"
1495
+ self.stop_reason = "failed"
1496
+ self.last_result_is_error = True
1497
+ self.terminal_result_text = error_text[:1000]
1498
+ self.current_tool = None
1499
+ self.is_active = False
1500
+
1501
+ elif event_type == "error":
1502
+ error_text = _extract_error_text(event.get("error") or event.get("message") or "Unknown error")
1503
+ self._append_error(error_text)
1504
+ self._detect_terminal_error(error_text)
1505
+
1506
+ return
1507
+
1508
+ # ── CodeBuddy stream-json format ──────────────────────────────
1509
+ if event_type == "message" and isinstance(event.get("sessionId"), str):
1510
+ self.event_format = self.event_format or "stream-json"
1511
+ role = event.get("role", "")
1512
+ sid = event.get("sessionId", "")
1513
+ cwd = event.get("cwd", "")
1514
+ if sid and not self.cb_session_id:
1515
+ self.cb_session_id = sid.strip()
1516
+ if isinstance(cwd, str) and cwd and not self.cb_cwd:
1517
+ self.cb_cwd = cwd.strip()
1518
+ if role == "assistant":
1519
+ self.message_count += 1
1520
+ self.is_active = True
1521
+ content = event.get("content", [])
1522
+ if isinstance(content, list):
1523
+ for block in content:
1524
+ if not isinstance(block, dict):
1525
+ continue
1526
+ block_type = block.get("type", "")
1527
+ if block_type == "tool_use":
1528
+ tool_name = str(block.get("name") or "unknown")
1529
+ self.current_tool = tool_name
1530
+ self.tool_call_counts[tool_name] += 1
1531
+ self.total_tool_calls += 1
1532
+ tool_input = block.get("input", {})
1533
+ if isinstance(tool_input, dict):
1534
+ self._extract_tool_summary_from_dict(tool_input)
1535
+ self._detect_phase(json.dumps(tool_input, ensure_ascii=False, default=str)[:500])
1536
+ self._record_cb_agent_tool_call(
1537
+ tool_name,
1538
+ tool_input,
1539
+ event_id=str(
1540
+ block.get("id") or block.get("tool_use_id") or block.get("call_id") or ""
1541
+ ),
1542
+ source_event="message.tool_use",
1543
+ )
1544
+ elif block_type == "tool_result":
1545
+ self.current_tool = None
1546
+ elif block_type == "text":
1547
+ text = str(block.get("text") or "")
1548
+ if text.strip():
1549
+ self.last_text_snippet = text.strip()[:120]
1550
+ self._detect_phase(text)
1551
+ self._detect_terminal_error(text, require_error_context=True)
1552
+ elif role == "user":
1553
+ content = event.get("content")
1554
+ if isinstance(content, list) and any(
1555
+ isinstance(b, dict) and b.get("type") == "tool_result" for b in content
1556
+ ):
1557
+ self.current_tool = None
1558
+ return
1559
+
1560
+ # CodeBuddy function_call / function_call_result in stream-json
1561
+ if event_type in ("function_call", "function_call_result"):
1562
+ self.event_format = self.event_format or "stream-json"
1563
+ sid = event.get("sessionId", "")
1564
+ cwd = event.get("cwd", "")
1565
+ if isinstance(sid, str) and sid and not self.cb_session_id:
1566
+ self.cb_session_id = sid.strip()
1567
+ if isinstance(cwd, str) and cwd and not self.cb_cwd:
1568
+ self.cb_cwd = cwd.strip()
1569
+ if event_type == "function_call":
1570
+ tool_name = str(event.get("name") or "unknown")
1571
+ self.current_tool = tool_name
1572
+ self.tool_call_counts[tool_name] += 1
1573
+ self.total_tool_calls += 1
1574
+ self.is_active = True
1575
+ raw_args = event.get("arguments", "")
1576
+ if isinstance(raw_args, str) and raw_args.strip():
1577
+ self._extract_tool_summary(raw_args)
1578
+ self._detect_phase(raw_args[:500])
1579
+ self._record_cb_agent_tool_call(
1580
+ tool_name,
1581
+ raw_args,
1582
+ event_id=str(event.get("id") or event.get("call_id") or event.get("callId") or ""),
1583
+ source_event="function_call",
1584
+ )
1585
+ elif event_type == "function_call_result":
1586
+ self.current_tool = None
1587
+ result_text = event.get("output") or ""
1588
+ if result_text and isinstance(result_text, str):
1589
+ stripped = result_text.strip()
1590
+ if stripped:
1591
+ self.last_text_snippet = stripped[:120]
1592
+ self._detect_phase(stripped)
1593
+ self._detect_terminal_error(stripped, require_error_context=True)
1594
+ return
1595
+
1596
+ # ── Claude Code verbose format ──────────────────────────────
1597
+ if event_type == "assistant":
1598
+ self.event_format = self.event_format or "stream-json"
1599
+ self.message_count += 1
1600
+ self.is_active = True
1601
+ message = event.get("message")
1602
+ message = message if isinstance(message, dict) else {}
1603
+ content_blocks = message.get("content", [])
1604
+ if isinstance(content_blocks, str):
1605
+ if content_blocks.strip():
1606
+ self.last_text_snippet = content_blocks.strip()[:120]
1607
+ self._detect_phase(content_blocks)
1608
+ self._detect_terminal_error(content_blocks, require_error_context=True)
1609
+ content_blocks = []
1610
+ elif not isinstance(content_blocks, list):
1611
+ content_blocks = []
1612
+ for block in content_blocks:
1613
+ if not isinstance(block, dict):
1614
+ continue
1615
+ block_type = block.get("type", "")
1616
+ if block_type == "tool_use":
1617
+ tool_name = str(block.get("name") or "unknown")
1618
+ self.current_tool = tool_name
1619
+ self.tool_call_counts[tool_name] += 1
1620
+ self.total_tool_calls += 1
1621
+ tool_input = block.get("input", {})
1622
+ if isinstance(tool_input, dict):
1623
+ self._extract_tool_summary_from_dict(tool_input)
1624
+ self._detect_phase(json.dumps(tool_input, ensure_ascii=False, default=str)[:500])
1625
+ self._record_agent_tool_call(
1626
+ "claude",
1627
+ tool_name,
1628
+ tool_input,
1629
+ source_event="assistant.tool_use",
1630
+ event_id=str(block.get("id") or block.get("tool_use_id") or ""),
1631
+ )
1632
+ elif block_type == "text":
1633
+ text = str(block.get("text") or "")
1634
+ if text.strip():
1635
+ self.last_text_snippet = text.strip()[:120]
1636
+ self._detect_phase(text)
1637
+ self._detect_terminal_error(text, require_error_context=True)
1638
+
1639
+ elif event_type == "tool_result" or (
1640
+ event_type == "user" and not isinstance(event.get("sessionId"), str)
1641
+ ):
1642
+ self.event_format = self.event_format or "stream-json"
1643
+ self.is_active = True
1644
+
1645
+ content_candidates = []
1646
+ saw_tool_result = event_type == "tool_result"
1647
+
1648
+ if event_type == "tool_result":
1649
+ content_candidates.append(str(event.get("content", "")))
1650
+
1651
+ if event_type == "user":
1652
+ message = event.get("message")
1653
+ message = message if isinstance(message, dict) else {}
1654
+ content_list = message.get("content", [])
1655
+ if isinstance(content_list, list):
1656
+ for item in content_list:
1657
+ if isinstance(item, dict) and item.get("type") == "tool_result":
1658
+ saw_tool_result = True
1659
+ content_candidates.append(str(item.get("content", "")))
1660
+
1661
+ recorded_tool = self.current_tool
1662
+ for result_text in content_candidates:
1663
+ if "shorter than the provided offset" in result_text:
1664
+ self._append_error({
1665
+ "type": "read_offset_overflow",
1666
+ "tool": recorded_tool,
1667
+ "at": datetime.now(timezone.utc).isoformat(),
1668
+ })
1669
+ break
1670
+ if "Wasted call" in result_text:
1671
+ self._append_error({
1672
+ "type": "wasted_call",
1673
+ "tool": recorded_tool,
1674
+ "at": datetime.now(timezone.utc).isoformat(),
1675
+ })
1676
+ break
1677
+
1678
+ if saw_tool_result:
1679
+ self.current_tool = None
1680
+
1681
+ elif event_type == "system":
1682
+ self.event_format = self.event_format or "stream-json"
1683
+ subtype = event.get("subtype", "")
1684
+ if subtype == "init":
1685
+ self.is_active = True
1686
+ session_id = event.get("session_id")
1687
+ if isinstance(session_id, str) and session_id.strip():
1688
+ self.claude_session_id = session_id.strip()
1689
+ cwd = event.get("cwd")
1690
+ if isinstance(cwd, str) and cwd.strip():
1691
+ self.claude_cwd = cwd.strip()
1692
+ elif subtype == "task_started":
1693
+ task_id = event.get("task_id")
1694
+ if isinstance(task_id, str) and task_id.strip():
1695
+ tid = task_id.strip()
1696
+ self.claude_task_states[tid] = {
1697
+ "status": "running",
1698
+ "summary": str(event.get("description") or "")[:120],
1699
+ "tool_use_id": str(event.get("tool_use_id") or ""),
1700
+ "task_type": str(event.get("task_type") or ""),
1701
+ "subagent_type": str(event.get("subagent_type") or ""),
1702
+ }
1703
+ self._update_claude_subagent_status_counts(tid)
1704
+ elif subtype in ("task_updated", "task_progress"):
1705
+ task_id = event.get("task_id")
1706
+ if isinstance(task_id, str) and task_id.strip():
1707
+ tid = task_id.strip()
1708
+ state = self.claude_task_states.setdefault(tid, {})
1709
+ patch = event.get("patch") if isinstance(event.get("patch"), dict) else {}
1710
+ status = patch.get("status") or event.get("status")
1711
+ if status:
1712
+ state["status"] = str(status)
1713
+ summary = (
1714
+ patch.get("summary")
1715
+ or patch.get("description")
1716
+ or event.get("summary")
1717
+ or event.get("description")
1718
+ )
1719
+ if summary:
1720
+ state["summary"] = str(summary)[:120]
1721
+ else:
1722
+ state.setdefault("summary", "")
1723
+ tool_use_id = patch.get("tool_use_id") or event.get("tool_use_id")
1724
+ if tool_use_id:
1725
+ state["tool_use_id"] = str(tool_use_id)
1726
+ else:
1727
+ state.setdefault("tool_use_id", "")
1728
+ task_type = patch.get("task_type") or event.get("task_type")
1729
+ if task_type:
1730
+ state["task_type"] = str(task_type)
1731
+ else:
1732
+ state.setdefault("task_type", "")
1733
+ subagent_type = patch.get("subagent_type") or event.get("subagent_type")
1734
+ if subagent_type:
1735
+ state["subagent_type"] = str(subagent_type)
1736
+ else:
1737
+ state.setdefault("subagent_type", "")
1738
+ self._update_claude_subagent_status_counts(tid)
1739
+ elif subtype == "task_notification":
1740
+ task_id = event.get("task_id")
1741
+ if isinstance(task_id, str) and task_id.strip():
1742
+ tid = task_id.strip()
1743
+ state = self.claude_task_states.setdefault(tid, {})
1744
+ status = event.get("status") or "completed"
1745
+ state["status"] = str(status)
1746
+ state["summary"] = str(event.get("summary") or state.get("summary") or "")[:120]
1747
+ state.setdefault("tool_use_id", str(event.get("tool_use_id") or ""))
1748
+ task_type = event.get("task_type")
1749
+ if task_type:
1750
+ state["task_type"] = str(task_type)
1751
+ else:
1752
+ state.setdefault("task_type", "")
1753
+ subagent_type = event.get("subagent_type")
1754
+ if subagent_type:
1755
+ state["subagent_type"] = str(subagent_type)
1756
+ else:
1757
+ state.setdefault("subagent_type", "")
1758
+ self._update_claude_subagent_status_counts(tid)
1759
+
1760
+ elif event_type == "result":
1761
+ self.current_tool = None
1762
+ self.result_subtype = str(event.get("subtype") or event.get("result_subtype") or "")
1763
+ self.stop_reason = str(event.get("stop_reason") or "")
1764
+ self.event_format = self.event_format or "stream-json"
1765
+ self.is_active = False
1766
+ result_text = event.get("result") or event.get("message") or ""
1767
+ error_obj = event.get("error")
1768
+ if isinstance(error_obj, dict):
1769
+ error_text = " ".join(
1770
+ str(error_obj.get(key) or "")
1771
+ for key in ("type", "code", "message")
1772
+ if error_obj.get(key)
1773
+ )
1774
+ result_text = " ".join(part for part in (str(result_text), error_text) if part)
1775
+ api_error_code = event.get("api_error_code") or event.get("error_code") or ""
1776
+ if isinstance(error_obj, dict) and not api_error_code:
1777
+ api_error_code = error_obj.get("code") or error_obj.get("type") or ""
1778
+ self._record_terminal_result(
1779
+ text=str(result_text or ""),
1780
+ is_error=bool(event.get("is_error")),
1781
+ api_error_status=event.get("api_error_status"),
1782
+ api_error_code=str(api_error_code or ""),
1783
+ stop_reason=str(event.get("stop_reason") or ""),
1784
+ )
1785
+
1786
+ # ── Claude API raw stream format ────────────────────────────
1787
+ elif event_type == "message_start":
1788
+ self.event_format = self.event_format or "stream-json"
1789
+ self.message_count += 1
1790
+ self.is_active = True
1791
+
1792
+ elif event_type == "message_stop":
1793
+ self.current_tool = None
1794
+ self.current_tool_input_summary = ""
1795
+ self._in_tool_use = False
1796
+ self._current_tool_input_parts = []
1797
+ self._current_tool_input_len = 0
1798
+ self._current_tool_id = ""
1799
+
1800
+ elif event_type == "content_block_start":
1801
+ content_block = event.get("content_block")
1802
+ content_block = content_block if isinstance(content_block, dict) else {}
1803
+ block_type = content_block.get("type", "")
1804
+
1805
+ if block_type == "tool_use":
1806
+ tool_name = str(content_block.get("name") or "unknown")
1807
+ self.current_tool = tool_name
1808
+ self.current_tool_input_summary = ""
1809
+ self.tool_call_counts[tool_name] += 1
1810
+ self.total_tool_calls += 1
1811
+ self._in_tool_use = True
1812
+ self._current_tool_input_parts = []
1813
+ self._current_tool_input_len = 0
1814
+ self._current_tool_id = str(
1815
+ content_block.get("id") or content_block.get("tool_use_id") or ""
1816
+ )
1817
+
1818
+ elif block_type == "text":
1819
+ self._text_buffer = ""
1820
+ self._in_tool_use = False
1821
+ self._current_tool_id = ""
1822
+
1823
+ elif event_type == "content_block_delta":
1824
+ delta = event.get("delta")
1825
+ delta = delta if isinstance(delta, dict) else {}
1826
+ delta_type = delta.get("type", "")
1827
+
1828
+ if delta_type == "text_delta":
1829
+ text = str(delta.get("text") or "")
1830
+ self._text_buffer += text
1831
+ stripped = text.strip()
1832
+ if stripped:
1833
+ self.last_text_snippet = stripped[:120]
1834
+ self._detect_phase(text)
1835
+ self._detect_terminal_error(text, require_error_context=True)
1836
+
1837
+ elif delta_type == "input_json_delta":
1838
+ partial = str(delta.get("partial_json") or "")
1839
+ self._current_tool_input_parts.append(partial)
1840
+ if len(self.current_tool_input_summary) < 150:
1841
+ self.current_tool_input_summary = (self.current_tool_input_summary + partial)[:150]
1842
+ self._current_tool_input_len += len(partial)
1843
+
1844
+ elif event_type == "content_block_stop":
1845
+ if self._in_tool_use:
1846
+ full_input = "".join(self._current_tool_input_parts)
1847
+ self._extract_tool_summary(full_input)
1848
+ self._detect_phase(full_input)
1849
+ self._record_agent_tool_call(
1850
+ "claude",
1851
+ self.current_tool,
1852
+ full_input,
1853
+ source_event="content_block.tool_use",
1854
+ event_id=self._current_tool_id,
1855
+ )
1856
+ else:
1857
+ if self._text_buffer:
1858
+ self._detect_phase(self._text_buffer)
1859
+ self._detect_terminal_error(self._text_buffer, require_error_context=True)
1860
+ self._in_tool_use = False
1861
+ self._current_tool_input_parts = []
1862
+ self._current_tool_input_len = 0
1863
+ self._current_tool_id = ""
1864
+
1865
+ elif event_type == "error":
1866
+ self.event_format = self.event_format or "stream-json"
1867
+ errors = event.get("errors") or []
1868
+ if isinstance(errors, list) and errors:
1869
+ error_msg = _extract_error_text(errors)
1870
+ else:
1871
+ error_msg = _extract_error_text(
1872
+ event.get("error") if event.get("error") is not None else event.get("message")
1873
+ ) or "Unknown error"
1874
+ self._append_error(error_msg)
1875
+ self._detect_terminal_error(error_msg, require_error_context=False)
1876
+
1877
+ elif event_type == "file-history-snapshot":
1878
+ return
1879
+
1880
+ def _canonical_subagent_key(self, provider, identifier, aliases=()):
1881
+ """Return the existing canonical key for any alias, otherwise a new key."""
1882
+ provider = str(provider or "unknown").strip() or "unknown"
1883
+ keys = []
1884
+ if identifier:
1885
+ keys.append(f"{provider}:{identifier}")
1886
+ for alias in aliases or ():
1887
+ if alias:
1888
+ alias_text = str(alias).strip()
1889
+ if alias_text:
1890
+ keys.append(f"{provider}:{alias_text}")
1891
+ for key in keys:
1892
+ canonical = self.subagent_aliases.get(key)
1893
+ if canonical:
1894
+ return canonical
1895
+ return keys[0] if keys else f"{provider}:unknown:{len(self.subagent_records) + 1}"
1896
+
1897
+ def _record_subagent_event(
1898
+ self,
1899
+ provider,
1900
+ source_event,
1901
+ *,
1902
+ identifier="",
1903
+ aliases=(),
1904
+ status="unknown",
1905
+ active=None,
1906
+ spawn=False,
1907
+ metadata=None,
1908
+ ):
1909
+ """Record authoritative session-log-derived subagent statistics."""
1910
+ provider = str(provider or "unknown").strip() or "unknown"
1911
+ source_event = str(source_event or "unknown").strip() or "unknown"
1912
+ identifier = str(identifier or "").strip()
1913
+ alias_values = [str(alias).strip() for alias in aliases or () if str(alias or "").strip()]
1914
+ canonical = self._canonical_subagent_key(provider, identifier, alias_values)
1915
+ record = self.subagent_records.setdefault(
1916
+ canonical,
1917
+ {
1918
+ "id": identifier or canonical.split(":", 1)[-1],
1919
+ "provider": provider,
1920
+ "source_events": set(),
1921
+ "aliases": set(),
1922
+ "status": "unknown",
1923
+ "active": False,
1924
+ "spawned": False,
1925
+ "metadata": {},
1926
+ },
1927
+ )
1928
+ for alias in [identifier, *alias_values]:
1929
+ if alias:
1930
+ alias_key = f"{provider}:{alias}"
1931
+ self.subagent_aliases[alias_key] = canonical
1932
+ record["aliases"].add(alias)
1933
+ if identifier:
1934
+ if not record.get("id") or str(record.get("id", "")).startswith("unknown:"):
1935
+ record["id"] = identifier
1936
+ record.setdefault("observed_ids", set()).add(identifier)
1937
+ for alias in alias_values:
1938
+ record.setdefault("observed_ids", set()).add(alias)
1939
+ record["source_events"].add(source_event)
1940
+ self.subagent_source_providers.add(provider)
1941
+ self.subagent_source_events[f"{provider}:{source_event}"] += 1
1942
+ existing_status = _normalize_status(record.get("status"), default="unknown")
1943
+ normalized_status = _normalize_status(status, default=existing_status)
1944
+ if source_event == "parent_tool_use_id" and existing_status in TERMINAL_SUBAGENT_STATUSES:
1945
+ normalized_status = existing_status
1946
+ active = False
1947
+ if normalized_status:
1948
+ record["status"] = normalized_status
1949
+ if active is None:
1950
+ record["active"] = record["status"] not in TERMINAL_SUBAGENT_STATUSES
1951
+ else:
1952
+ record["active"] = bool(active)
1953
+ if spawn:
1954
+ record["spawned"] = True
1955
+ if isinstance(metadata, dict):
1956
+ for key, value in metadata.items():
1957
+ if value not in (None, "", [], {}):
1958
+ record["metadata"][str(key)] = str(value)[:200]
1959
+ self._refresh_normalized_subagent_totals()
1960
+ return canonical
1961
+
1962
+ def _refresh_normalized_subagent_totals(self):
1963
+ """Refresh normalized totals from authoritative subagent records."""
1964
+ counts = Counter()
1965
+ active = 0
1966
+ spawned = 0
1967
+ for record in self.subagent_records.values():
1968
+ status = _normalize_status(record.get("status"), default="unknown")
1969
+ counts[status] += 1
1970
+ if bool(record.get("active")):
1971
+ active += 1
1972
+ if bool(record.get("spawned")):
1973
+ spawned += 1
1974
+ self.subagent_status_counts = counts
1975
+ self.active_subagents = active
1976
+ self.subagents_spawned = spawned
1977
+
1978
+ def _subagent_statistics(self):
1979
+ """Return additive normalized subagent statistics for progress.json."""
1980
+ records = []
1981
+ for key, record in sorted(self.subagent_records.items()):
1982
+ records.append(
1983
+ {
1984
+ "key": key,
1985
+ "id": str(record.get("id") or ""),
1986
+ "provider": str(record.get("provider") or "unknown"),
1987
+ "status": _normalize_status(record.get("status"), default="unknown"),
1988
+ "active": bool(record.get("active")),
1989
+ "spawned": bool(record.get("spawned")),
1990
+ "source_events": sorted(record.get("source_events") or []),
1991
+ "aliases": sorted(record.get("aliases") or []),
1992
+ "observed_ids": sorted(record.get("observed_ids") or []),
1993
+ "metadata": dict(record.get("metadata") or {}),
1994
+ }
1995
+ )
1996
+ observed_ids = []
1997
+ for record in records:
1998
+ identifier = record.get("id") or record.get("key")
1999
+ if identifier:
2000
+ observed_ids.append(str(identifier))
2001
+ for observed in record.get("observed_ids") or []:
2002
+ observed_ids.append(str(observed))
2003
+ states = [
2004
+ {"status": status, "count": count}
2005
+ for status, count in self.subagent_status_counts.most_common()
2006
+ ]
2007
+ return {
2008
+ "source": "session_log",
2009
+ "providers": sorted(self.subagent_source_providers),
2010
+ "spawned": self.subagents_spawned,
2011
+ "active": self.active_subagents,
2012
+ "status_counts": dict(self.subagent_status_counts),
2013
+ "states": states,
2014
+ "observed_ids": sorted(set(observed_ids)),
2015
+ "source_events": dict(sorted(self.subagent_source_events.items())),
2016
+ "parent_activity_ids": sorted(self.parent_subagent_activity_ids),
2017
+ "records": records,
2018
+ "child_activity_source": "filesystem_liveness_only",
2019
+ }
2020
+
2021
+ def _record_structured_subagent_metadata(self, event):
2022
+ """Extract provider-specific subagent metadata when fields appear anywhere."""
2023
+ if not isinstance(event, dict):
2024
+ return
2025
+ receiver_ids = event.get("receiver_thread_ids")
2026
+ if isinstance(receiver_ids, list):
2027
+ self._record_codex_child_thread_ids(receiver_ids)
2028
+ agents_states = event.get("agents_states")
2029
+ if isinstance(agents_states, dict):
2030
+ self._update_subagent_status_counts(agents_states)
2031
+ item = event.get("item")
2032
+ if isinstance(item, dict):
2033
+ nested_receivers = item.get("receiver_thread_ids")
2034
+ if isinstance(nested_receivers, list):
2035
+ self._record_codex_child_thread_ids(nested_receivers)
2036
+ nested_states = item.get("agents_states")
2037
+ if isinstance(nested_states, dict):
2038
+ self._update_subagent_status_counts(nested_states)
2039
+
2040
+ def _permission_error_candidates(self, event: dict) -> list[object]:
2041
+ """Collect error-bearing subtrees to avoid false positives from Read payloads."""
2042
+ candidates: list[object] = []
2043
+ event_type = str(event.get("type") or event.get("event") or "")
2044
+ for key in ("error", "errors", "errorMessage", "finalError", "permission_denials"):
2045
+ val = event.get(key)
2046
+ if val not in (None, "", [], {}):
2047
+ candidates.append(val)
2048
+
2049
+ subtype = str(event.get("subtype") or "").lower()
2050
+ status = str(event.get("status") or "").lower()
2051
+ if (
2052
+ event.get("is_error")
2053
+ or event.get("isError")
2054
+ or event_type == "error"
2055
+ or "denied" in subtype
2056
+ or "denied" in status
2057
+ or subtype in {"error", "failed"}
2058
+ or status in {"error", "failed"}
2059
+ ):
2060
+ for key in ("message", "result", "content", "output", "reason"):
2061
+ val = event.get(key)
2062
+ if val not in (None, "", [], {}):
2063
+ candidates.append(val)
2064
+
2065
+ step_update = event.get("step_update")
2066
+ if isinstance(step_update, dict):
2067
+ if step_update.get("error"):
2068
+ candidates.append(step_update.get("error"))
2069
+ tool_info = step_update.get("tool_info")
2070
+ if isinstance(tool_info, dict):
2071
+ if tool_info.get("error"):
2072
+ candidates.append(tool_info.get("error"))
2073
+ if str(step_update.get("state") or "").upper() in {"ERROR", "FAILED"} and tool_info.get("output"):
2074
+ candidates.append(tool_info.get("output"))
2075
+
2076
+ result_obj = event.get("result")
2077
+ if isinstance(result_obj, dict) and (result_obj.get("error") or result_obj.get("is_error") or str(result_obj.get("status") or "").lower() in {"error", "failed"}):
2078
+ candidates.append(result_obj)
2079
+
2080
+ tool_call = event.get("tool_call")
2081
+ if isinstance(tool_call, dict):
2082
+ for payload in tool_call.values():
2083
+ if isinstance(payload, dict):
2084
+ res = payload.get("result")
2085
+ if isinstance(res, dict) and (res.get("error") or res.get("failure") or event.get("is_error")):
2086
+ candidates.append(res)
2087
+
2088
+ item = event.get("item")
2089
+ if isinstance(item, dict):
2090
+ if item.get("error"):
2091
+ candidates.append(item.get("error"))
2092
+
2093
+ if event_type == "user":
2094
+ message = event.get("message")
2095
+ if isinstance(message, dict) and isinstance(message.get("content"), list):
2096
+ for block in message["content"]:
2097
+ if isinstance(block, dict) and block.get("type") == "tool_result" and block.get("is_error"):
2098
+ candidates.append(block.get("content"))
2099
+
2100
+ return candidates
2101
+
2102
+ def _record_usage_and_permission_metadata(self, event):
2103
+ """Record additive metadata required by Python runtime parity tests."""
2104
+ if not isinstance(event, dict):
2105
+ return
2106
+ if event.get("usage") not in (None, "", {}):
2107
+ self.has_usage = True
2108
+ else:
2109
+ for container_key in ("result", "step_update"):
2110
+ container = event.get(container_key)
2111
+ if isinstance(container, dict) and container.get("usage") not in (None, "", {}):
2112
+ self.has_usage = True
2113
+ break
2114
+
2115
+ explicit_denials = event.get("permission_denials")
2116
+ if isinstance(explicit_denials, list) and explicit_denials:
2117
+ self.permission_denials.append(json.dumps(explicit_denials, ensure_ascii=False, default=str)[:500])
2118
+ self.permission_denials = self.permission_denials[-10:]
2119
+ return
2120
+
2121
+ candidates = self._permission_error_candidates(event)
2122
+ if not candidates:
2123
+ return
2124
+ denial_text = json.dumps(candidates, ensure_ascii=False, default=str).lower()
2125
+ if any(marker in denial_text for marker in PERMISSION_DENIAL_MARKERS):
2126
+ self.permission_denials.append(json.dumps(event, ensure_ascii=False, default=str)[:500])
2127
+ self.permission_denials = self.permission_denials[-10:]
2128
+
2129
+ def _detect_structured_terminal_fields(self, event):
2130
+ """Detect provider-neutral terminal/context errors before format routing."""
2131
+ if not isinstance(event, dict):
2132
+ return
2133
+
2134
+ code_parts = []
2135
+ text_parts = []
2136
+ terminal_parts = []
2137
+
2138
+ for key in ("fatal_error_code", "api_error_code", "error_code", "stop_reason"):
2139
+ value = event.get(key)
2140
+ if isinstance(value, (str, int, float)) and str(value).strip():
2141
+ code_parts.append(str(value))
2142
+
2143
+ for key in ("terminal_result_text", "message", "result"):
2144
+ value = event.get(key)
2145
+ if isinstance(value, (str, int, float)) and str(value).strip():
2146
+ text_parts.append(str(value))
2147
+ terminal_parts.append(str(value))
2148
+
2149
+ error_obj = event.get("error")
2150
+ if isinstance(error_obj, dict):
2151
+ for key in ("type", "code", "message"):
2152
+ value = error_obj.get(key)
2153
+ if isinstance(value, (str, int, float)) and str(value).strip():
2154
+ text_parts.append(str(value))
2155
+ terminal_parts.append(str(value))
2156
+ elif isinstance(error_obj, (str, int, float)) and str(error_obj).strip():
2157
+ text_parts.append(str(error_obj))
2158
+ terminal_parts.append(str(error_obj))
2159
+
2160
+ combined_code_text = " ".join(code_parts)
2161
+ combined_text = " ".join(code_parts + text_parts)
2162
+ if not combined_text:
2163
+ return
2164
+
2165
+ error_like = (
2166
+ bool(code_parts)
2167
+ or event.get("api_error_status") not in (None, "")
2168
+ or bool(event.get("last_result_is_error"))
2169
+ or bool(event.get("is_error"))
2170
+ or _has_error_context(combined_text)
2171
+ )
2172
+ normalized_code = detect_api_error_code(
2173
+ combined_code_text,
2174
+ require_error_context=False,
2175
+ structured_code=True,
2176
+ ) or detect_api_error_code(
2177
+ combined_text,
2178
+ require_error_context=not error_like,
2179
+ structured_code=bool(code_parts),
2180
+ )
2181
+ if not normalized_code:
2182
+ return
2183
+
2184
+ self.last_result_is_error = True
2185
+ api_error_status = event.get("api_error_status") or event.get("status")
2186
+ if api_error_status not in (None, ""):
2187
+ try:
2188
+ self.api_error_status = int(api_error_status)
2189
+ except (TypeError, ValueError):
2190
+ self.api_error_status = api_error_status
2191
+ self.api_error_code = normalized_code
2192
+ self.fatal_error_code = normalized_code
2193
+ terminal_text = " ".join(terminal_parts) or combined_text
2194
+ self.terminal_result_text = terminal_text[:1000]
2195
+ if terminal_text.strip():
2196
+ self.last_text_snippet = terminal_text.strip()[:120]
2197
+ if not self.errors or self.errors[-1] != normalized_code:
2198
+ self._append_error(normalized_code)
2199
+
2200
+ def _record_agent_tool_call(self, provider, tool_name, raw_args, *, source_event="tool_use", event_id=""):
2201
+ """Record delegated execution tool calls as session-log subagent spawns."""
2202
+ if tool_name not in {"Agent", "Task"}:
2203
+ return
2204
+ if isinstance(raw_args, dict):
2205
+ args = raw_args
2206
+ elif isinstance(raw_args, str):
2207
+ try:
2208
+ args = json.loads(raw_args)
2209
+ except (json.JSONDecodeError, TypeError):
2210
+ args = {"raw_args": raw_args}
2211
+ else:
2212
+ args = {}
2213
+ if not isinstance(args, dict):
2214
+ args = {}
2215
+ if not any(args.get(key) for key in ("subagent_type", "prompt", "description")):
2216
+ return
2217
+ explicit_ids = []
2218
+ for key in ("id", "tool_use_id", "call_id", "callId", "task_id", "taskId"):
2219
+ value = args.get(key)
2220
+ if value:
2221
+ explicit_ids.append(str(value))
2222
+ if event_id:
2223
+ explicit_ids.append(str(event_id))
2224
+ fallback = _stable_subagent_digest(provider, tool_name, args)
2225
+ identifier = explicit_ids[0] if explicit_ids else f"{tool_name}:{fallback}"
2226
+ aliases = [*explicit_ids, f"{tool_name}:{fallback}"]
2227
+ metadata = {
2228
+ "tool": tool_name,
2229
+ "subagent_type": args.get("subagent_type", ""),
2230
+ "description": args.get("description", ""),
2231
+ "run_in_background": args.get("run_in_background", ""),
2232
+ }
2233
+ self._record_subagent_event(
2234
+ provider,
2235
+ source_event,
2236
+ identifier=identifier,
2237
+ aliases=aliases,
2238
+ status="running",
2239
+ active=True,
2240
+ spawn=True,
2241
+ metadata=metadata,
2242
+ )
2243
+
2244
+ def _record_cb_agent_tool_call(self, tool_name, raw_args, *, event_id="", source_event="tool_use"):
2245
+ """Record a CodeBuddy delegated execution invocation for sub-agent tracking."""
2246
+ self._record_agent_tool_call(
2247
+ "codebuddy",
2248
+ tool_name,
2249
+ raw_args,
2250
+ source_event=source_event,
2251
+ event_id=event_id,
2252
+ )
2253
+
2254
+ def _record_terminal_result(self, text="", is_error=False, api_error_status=None, api_error_code="", stop_reason=""):
2255
+ """Record a Claude Code terminal result event."""
2256
+ terminal_text = str(text or "")
2257
+ self.last_result_is_error = bool(is_error)
2258
+ if api_error_status not in (None, ""):
2259
+ try:
2260
+ self.api_error_status = int(api_error_status)
2261
+ except (TypeError, ValueError):
2262
+ self.api_error_status = api_error_status
2263
+ error_like_result = (
2264
+ self.last_result_is_error
2265
+ or api_error_status not in (None, "")
2266
+ or bool(api_error_code)
2267
+ or _has_error_context(terminal_text)
2268
+ )
2269
+ normalized_code = detect_api_error_code(
2270
+ " ".join([str(api_error_code or ""), terminal_text]),
2271
+ require_error_context=not error_like_result,
2272
+ )
2273
+ if normalized_code:
2274
+ self.api_error_code = normalized_code
2275
+ self.fatal_error_code = normalized_code
2276
+ elif api_error_code:
2277
+ self.api_error_code = str(api_error_code)
2278
+ self.terminal_result_text = terminal_text[:1000]
2279
+ if terminal_text.strip():
2280
+ self.last_text_snippet = terminal_text.strip()[:120]
2281
+ if not self.last_result_is_error and not self.fatal_error_code:
2282
+ self.terminal_success_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
2283
+ elif self.fatal_error_code:
2284
+ self._append_error(self.fatal_error_code)
2285
+
2286
+ def _detect_terminal_error(self, text, require_error_context=False):
2287
+ """Detect fatal context-window errors from unstructured text."""
2288
+ code = detect_api_error_code(
2289
+ str(text or ""),
2290
+ require_error_context=require_error_context,
2291
+ )
2292
+ if not code:
2293
+ return
2294
+ self.last_result_is_error = True
2295
+ self.api_error_code = code
2296
+ self.fatal_error_code = code
2297
+ self.terminal_result_text = str(text or "")[:1000]
2298
+ if text:
2299
+ self.last_text_snippet = str(text).strip()[:120]
2300
+
2301
+ def _detect_phase(self, text):
2302
+ """Detect pipeline phase from text content (monotonic forward-only)."""
2303
+ text_lower = text.lower()
2304
+ current_idx = (
2305
+ PHASE_ORDER.index(self.current_phase)
2306
+ if self.current_phase in PHASE_ORDER
2307
+ else -1
2308
+ )
2309
+
2310
+ for phase, kw_groups in PHASE_KEYWORDS.items():
2311
+ phase_idx = PHASE_ORDER.index(phase)
2312
+
2313
+ for keyword in kw_groups.get("strong", []):
2314
+ if keyword.lower() in text_lower:
2315
+ if phase_idx >= current_idx:
2316
+ self.current_phase = phase
2317
+ if phase not in self.detected_phases:
2318
+ self.detected_phases.append(phase)
2319
+ return
2320
+ break
2321
+
2322
+ if phase_idx >= current_idx:
2323
+ for keyword in kw_groups.get("weak", []):
2324
+ if keyword.lower() in text_lower:
2325
+ self.current_phase = phase
2326
+ if phase not in self.detected_phases:
2327
+ self.detected_phases.append(phase)
2328
+ return
2329
+
2330
+ def _extract_tool_summary(self, raw_input):
2331
+ """Extract a human-readable summary from tool input JSON string."""
2332
+ try:
2333
+ data = json.loads(raw_input)
2334
+ self._extract_tool_summary_from_dict(data)
2335
+ except (json.JSONDecodeError, TypeError):
2336
+ pass
2337
+
2338
+ def _extract_tool_summary_from_dict(self, data):
2339
+ """Extract a human-readable summary from tool input dict."""
2340
+ if isinstance(data, dict):
2341
+ for key in (
2342
+ "description",
2343
+ "command",
2344
+ "CommandLine",
2345
+ "file_path",
2346
+ "Path",
2347
+ "AbsolutePath",
2348
+ "TargetFile",
2349
+ "pattern",
2350
+ "SearchPath",
2351
+ "query",
2352
+ "Query",
2353
+ "prompt",
2354
+ ):
2355
+ if key in data and data[key] not in (None, ""):
2356
+ self.current_tool_input_summary = str(data[key])[:100]
2357
+ return
2358
+
2359
+ def _update_subagent_status_counts(self, agents_states):
2360
+ """Track Codex subagent state counts from session-log collab items."""
2361
+ if not isinstance(agents_states, dict):
2362
+ return
2363
+ for agent_id, state in agents_states.items():
2364
+ if not isinstance(state, dict):
2365
+ continue
2366
+ status = _normalize_status(state.get("status"), default="unknown")
2367
+ message = state.get("message")
2368
+ if message:
2369
+ self.last_text_snippet = str(message).strip()[:120]
2370
+ self._detect_phase(str(message))
2371
+ identifier = str(state.get("thread_id") or state.get("id") or agent_id or "")
2372
+ aliases = [agent_id, state.get("thread_id", ""), state.get("id", "")]
2373
+ self._record_subagent_event(
2374
+ "codex",
2375
+ "agents_states",
2376
+ identifier=identifier,
2377
+ aliases=aliases,
2378
+ status=status,
2379
+ active=status not in TERMINAL_SUBAGENT_STATUSES,
2380
+ spawn=True,
2381
+ metadata={
2382
+ "message": message or "",
2383
+ "name": state.get("name", ""),
2384
+ "role": state.get("role", ""),
2385
+ },
2386
+ )
2387
+
2388
+ def _record_codex_child_thread_ids(self, thread_ids):
2389
+ """Remember Codex child thread IDs reported by session-log collab tool calls."""
2390
+ if not isinstance(thread_ids, list):
2391
+ return
2392
+ for thread_id in thread_ids:
2393
+ if isinstance(thread_id, str) and thread_id.strip():
2394
+ thread_id = thread_id.strip()
2395
+ self.codex_child_thread_ids.add(thread_id)
2396
+ self._record_subagent_event(
2397
+ "codex",
2398
+ "receiver_thread_ids",
2399
+ identifier=thread_id,
2400
+ aliases=[thread_id],
2401
+ status="running",
2402
+ active=True,
2403
+ spawn=True,
2404
+ metadata={"thread_id": thread_id},
2405
+ )
2406
+
2407
+ def _codex_sessions_dir(self):
2408
+ """Return the Codex sessions directory for the current environment."""
2409
+ codex_home = os.environ.get("CODEX_HOME")
2410
+ if codex_home:
2411
+ return Path(codex_home).expanduser() / "sessions"
2412
+ return Path.home() / ".codex" / "sessions"
2413
+
2414
+ def _find_codex_child_session_file(self, thread_id):
2415
+ """Find a Codex transcript file for a child thread ID."""
2416
+ sessions_dir = self._codex_sessions_dir()
2417
+ try:
2418
+ if not sessions_dir.exists():
2419
+ return None
2420
+ matches = list(sessions_dir.rglob(f"*{thread_id}.jsonl"))
2421
+ except OSError:
2422
+ return None
2423
+
2424
+ if not matches:
2425
+ return None
2426
+
2427
+ try:
2428
+ matches.sort(key=lambda path: path.stat().st_mtime, reverse=True)
2429
+ except OSError:
2430
+ pass
2431
+ return str(matches[0])
2432
+
2433
+ def _is_tracked_claude_subagent_state(self, state):
2434
+ """Return true for Claude Code task events representing in-process agents."""
2435
+ if not isinstance(state, dict):
2436
+ return False
2437
+ task_type = str(state.get("task_type") or "")
2438
+ task_type_lower = task_type.lower()
2439
+ subagent_type = str(state.get("subagent_type") or "")
2440
+ if task_type_lower == "local_bash":
2441
+ return False
2442
+ tracked_types = {"in_process_teammate", "subagent", "agent", "teammate"}
2443
+ if task_type_lower in tracked_types:
2444
+ return True
2445
+ if task_type_lower == "local_agent" and subagent_type:
2446
+ return True
2447
+ summary = str(state.get("summary") or "")
2448
+ return bool(not task_type and summary.lower().startswith(("dev:", "reviewer:", "agent:")))
2449
+
2450
+ def _has_tracked_claude_subagent_task(self):
2451
+ """Return true once a Claude Code local-agent/subagent task has been observed."""
2452
+ return any(
2453
+ self._is_tracked_claude_subagent_state(state)
2454
+ for state in self.claude_task_states.values()
2455
+ )
2456
+
2457
+ def _update_claude_subagent_status_counts(self, updated_task_id=None):
2458
+ """Track Claude Code in-process teammate task state counts from session.log."""
2459
+ items = (
2460
+ [(updated_task_id, self.claude_task_states[updated_task_id])]
2461
+ if updated_task_id is not None and updated_task_id in self.claude_task_states
2462
+ else list(self.claude_task_states.items())
2463
+ )
2464
+ for task_id, state in items:
2465
+ if not self._is_tracked_claude_subagent_state(state):
2466
+ continue
2467
+ status = _normalize_status(state.get("status"), default="unknown")
2468
+ summary = state.get("summary") or state.get("subagent_type")
2469
+ if summary:
2470
+ self.last_text_snippet = str(summary).strip()[:120]
2471
+ self._detect_phase(str(summary))
2472
+ self._record_subagent_event(
2473
+ "claude",
2474
+ "system.task",
2475
+ identifier=str(task_id),
2476
+ aliases=[state.get("tool_use_id", "")],
2477
+ status=status,
2478
+ active=status not in TERMINAL_SUBAGENT_STATUSES,
2479
+ spawn=True,
2480
+ metadata={
2481
+ "task_type": state.get("task_type", ""),
2482
+ "subagent_type": state.get("subagent_type", ""),
2483
+ "summary": state.get("summary", ""),
2484
+ "tool_use_id": state.get("tool_use_id", ""),
2485
+ },
2486
+ )
2487
+
2488
+ def _claude_projects_dir(self):
2489
+ """Return the Claude Code projects directory for transcript lookup."""
2490
+ projects_dir = os.environ.get("CLAUDE_PROJECTS_DIR")
2491
+ if projects_dir:
2492
+ return Path(projects_dir).expanduser()
2493
+ claude_config_dir = os.environ.get("CLAUDE_CONFIG_DIR")
2494
+ if claude_config_dir:
2495
+ return Path(claude_config_dir).expanduser() / "projects"
2496
+ claude_home = os.environ.get("CLAUDE_HOME")
2497
+ if claude_home:
2498
+ return Path(claude_home).expanduser() / "projects"
2499
+ return Path.home() / ".claude" / "projects"
2500
+
2501
+ def _claude_project_key(self):
2502
+ """Encode cwd the same way Claude Code stores project transcript dirs."""
2503
+ cwd = self.claude_cwd
2504
+ if not cwd:
2505
+ return ""
2506
+ return cwd.replace("\\", "-").replace("/", "-").replace(":", "")
2507
+
2508
+ def _claude_candidate_project_keys(self, cwd: str) -> list[str]:
2509
+ if not cwd:
2510
+ return []
2511
+ keys = [cwd.replace("\\", "-").replace("/", "-").replace(":", "")]
2512
+ sanitized = re.sub(r"[^A-Za-z0-9-]", "-", cwd)
2513
+ if sanitized and sanitized not in keys:
2514
+ keys.append(sanitized)
2515
+ return keys
2516
+
2517
+ def _find_claude_child_session_files(
2518
+ self,
2519
+ *,
2520
+ claude_session_id: str,
2521
+ claude_cwd: str,
2522
+ has_tracked_task: bool,
2523
+ last_fallback_key: str,
2524
+ last_fallback_at: float,
2525
+ cached_files: list[Path],
2526
+ ) -> tuple[list[Path], str, float]:
2527
+ """Find Claude Code subagent transcripts for this parent session."""
2528
+ if not claude_session_id:
2529
+ return [], last_fallback_key, last_fallback_at
2530
+
2531
+ projects_dir = self._claude_projects_dir()
2532
+ try:
2533
+ if not projects_dir.exists():
2534
+ return [], last_fallback_key, last_fallback_at
2535
+ except OSError:
2536
+ return [], last_fallback_key, last_fallback_at
2537
+
2538
+ for project_key in self._claude_candidate_project_keys(claude_cwd):
2539
+ candidate = projects_dir / project_key / claude_session_id / "subagents"
2540
+ try:
2541
+ if candidate.exists():
2542
+ return sorted(candidate.glob("*.jsonl")), last_fallback_key, last_fallback_at
2543
+ except OSError:
2544
+ return [], last_fallback_key, last_fallback_at
2545
+
2546
+ if not has_tracked_task:
2547
+ return [], last_fallback_key, last_fallback_at
2548
+
2549
+ fallback_scan_key = f"{projects_dir}:{claude_session_id}"
2550
+ now = time.monotonic()
2551
+ if (
2552
+ last_fallback_key == fallback_scan_key
2553
+ and now - last_fallback_at < self._claude_fallback_scan_interval_seconds
2554
+ ):
2555
+ return list(cached_files), last_fallback_key, last_fallback_at
2556
+ try:
2557
+ matches = sorted(projects_dir.rglob(f"{claude_session_id}/subagents/*.jsonl"))
2558
+ except OSError:
2559
+ return [], fallback_scan_key, now
2560
+ return matches, fallback_scan_key, now
2561
+
2562
+ def _cb_projects_dir(self):
2563
+ """Return the CodeBuddy projects directory for transcript lookup."""
2564
+ cb_config = os.environ.get("CODEBUDDY_CONFIG_DIR")
2565
+ if cb_config:
2566
+ return Path(cb_config).expanduser() / "projects"
2567
+ cb_home = os.environ.get("CODEBUDDY_HOME")
2568
+ if cb_home:
2569
+ return Path(cb_home).expanduser() / "projects"
2570
+ return Path.home() / ".codebuddy" / "projects"
2571
+
2572
+ def _cb_project_key(self):
2573
+ """Encode cwd the same way CodeBuddy stores project subdirs."""
2574
+ cwd = self.cb_cwd
2575
+ if not cwd:
2576
+ return ""
2577
+ return cwd.replace("\\", "-").replace("/", "-").replace(":", "").lstrip("-")
2578
+
2579
+ def _cb_candidate_project_keys(self, cwd: str) -> list[str]:
2580
+ if not cwd:
2581
+ return []
2582
+ keys = [cwd.replace("\\", "-").replace("/", "-").replace(":", "").lstrip("-")]
2583
+ sanitized = re.sub(r"[^A-Za-z0-9-]", "-", cwd).lstrip("-")
2584
+ if sanitized and sanitized not in keys:
2585
+ keys.append(sanitized)
2586
+ return keys
2587
+
2588
+ def _find_cb_child_session_files(self, *, cb_session_id: str, cb_cwd: str) -> list[Path]:
2589
+ """Find CodeBuddy subagent transcript data for this parent session."""
2590
+ if not cb_session_id:
2591
+ return []
2592
+
2593
+ projects_dir = self._cb_projects_dir()
2594
+ try:
2595
+ if not projects_dir.exists():
2596
+ return []
2597
+ for project_key in self._cb_candidate_project_keys(cb_cwd):
2598
+ subagents_dir = projects_dir / project_key / cb_session_id / "subagents"
2599
+ if subagents_dir.exists():
2600
+ return sorted(p for p in subagents_dir.glob("**/*") if p.is_file())
2601
+ except OSError:
2602
+ return []
2603
+ return []
2604
+
2605
+ def refresh_child_session_activity(self, force=False, *, lock=None):
2606
+ """Refresh child transcript file stats (safe to perform I/O outside lock)."""
2607
+ lock_ctx = lock if lock is not None else nullcontext()
2608
+ with lock_ctx:
2609
+ previous_signature = self.child_activity_signature
2610
+ provider_hint = self.provider_hint
2611
+ event_format = self.event_format
2612
+ codex_ids = sorted(self.codex_child_thread_ids)
2613
+ claude_sid = self.claude_session_id if provider_hint in {"", "claude"} and event_format in {"", "stream-json"} else ""
2614
+ claude_cwd = self.claude_cwd
2615
+ has_tracked_claude = self._has_tracked_claude_subagent_task()
2616
+ cb_sid = self.cb_session_id if provider_hint in {"", "codebuddy"} and event_format in {"", "stream-json"} else ""
2617
+ cb_cwd = self.cb_cwd
2618
+
2619
+ if not codex_ids and not claude_sid and not cb_sid:
2620
+ self.child_session_files = []
2621
+ self.child_total_bytes = 0
2622
+ self.child_activity_signature = ""
2623
+ self.last_child_activity_at = ""
2624
+ return previous_signature != self.child_activity_signature
2625
+
2626
+ now = time.monotonic()
2627
+ should_scan = (
2628
+ force
2629
+ or self._last_child_scan_at == 0.0
2630
+ or (now - self._last_child_scan_at >= 2.0)
2631
+ )
2632
+ codex_paths = dict(self._codex_child_session_paths)
2633
+ claude_files = list(self._claude_child_session_files)
2634
+ cb_files = list(self._cb_child_session_files)
2635
+ last_fallback_key = self._last_claude_fallback_scan_key
2636
+ last_fallback_at = self._last_claude_fallback_scan_at
2637
+
2638
+ # Perform all filesystem probes & stats outside lock so stdout reader never stalls.
2639
+ if should_scan:
2640
+ for thread_id in codex_ids:
2641
+ path = codex_paths.get(thread_id)
2642
+ try:
2643
+ exists = bool(path and os.path.exists(path))
2644
+ except OSError:
2645
+ exists = False
2646
+ if not exists:
2647
+ found = self._find_codex_child_session_file(thread_id)
2648
+ if found:
2649
+ codex_paths[thread_id] = found
2650
+ claude_files, last_fallback_key, last_fallback_at = self._find_claude_child_session_files(
2651
+ claude_session_id=claude_sid,
2652
+ claude_cwd=claude_cwd,
2653
+ has_tracked_task=has_tracked_claude,
2654
+ last_fallback_key=last_fallback_key,
2655
+ last_fallback_at=last_fallback_at,
2656
+ cached_files=claude_files,
2657
+ )
2658
+ cb_files = self._find_cb_child_session_files(cb_session_id=cb_sid, cb_cwd=cb_cwd)
2659
+ scan_completed_at = time.monotonic()
2660
+ else:
2661
+ scan_completed_at = None
2662
+
2663
+ files = []
2664
+ signature_parts = []
2665
+ total_bytes = 0
2666
+ max_mtime = 0.0
2667
+
2668
+ def add_file(kind, identifier, path):
2669
+ nonlocal total_bytes, max_mtime
2670
+ try:
2671
+ stat = os.stat(path)
2672
+ except OSError:
2673
+ return
2674
+ path_str = str(path)
2675
+ total_bytes += stat.st_size
2676
+ max_mtime = max(max_mtime, stat.st_mtime)
2677
+ mtime_ns = getattr(stat, "st_mtime_ns", int(stat.st_mtime * 1_000_000_000))
2678
+ signature_parts.append(f"{kind}:{identifier}:{stat.st_size}:{mtime_ns}")
2679
+ files.append(
2680
+ {
2681
+ "kind": kind,
2682
+ "thread_id": identifier,
2683
+ "path": path_str,
2684
+ "size": stat.st_size,
2685
+ "mtime": datetime.fromtimestamp(stat.st_mtime, timezone.utc).strftime(
2686
+ "%Y-%m-%dT%H:%M:%SZ"
2687
+ ),
2688
+ }
2689
+ )
2690
+
2691
+ for thread_id in codex_ids:
2692
+ path = codex_paths.get(thread_id)
2693
+ if path:
2694
+ add_file("codex", thread_id, path)
2695
+
2696
+ for path in claude_files:
2697
+ add_file("claude", path.stem, path)
2698
+
2699
+ for path in cb_files:
2700
+ parent_name = path.parent.name if hasattr(path, "parent") else ""
2701
+ identifier = parent_name if parent_name.startswith("agent-") else path.name
2702
+ add_file("codebuddy", identifier, path)
2703
+
2704
+ new_signature = "|".join(signature_parts)
2705
+ last_activity_at = (
2706
+ datetime.fromtimestamp(max_mtime, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
2707
+ if max_mtime
2708
+ else ""
2709
+ )
2710
+
2711
+ with lock_ctx:
2712
+ if should_scan:
2713
+ self._codex_child_session_paths.update(codex_paths)
2714
+ self._claude_child_session_files = claude_files
2715
+ self._cb_child_session_files = cb_files
2716
+ self._last_claude_fallback_scan_key = last_fallback_key
2717
+ self._last_claude_fallback_scan_at = last_fallback_at
2718
+ if scan_completed_at is not None:
2719
+ self._last_child_scan_at = scan_completed_at
2720
+ self.child_session_files = files
2721
+ self.child_total_bytes = total_bytes
2722
+ self.child_activity_signature = new_signature
2723
+ self.last_child_activity_at = last_activity_at
2724
+ return previous_signature != self.child_activity_signature
2725
+
2726
+ def to_dict(self, *, refresh_child_activity=True):
2727
+ """Export current state as a dictionary for JSON serialization."""
2728
+ if refresh_child_activity:
2729
+ self.refresh_child_session_activity()
2730
+ tool_calls = [
2731
+ {"name": name, "count": count}
2732
+ for name, count in self.tool_call_counts.most_common()
2733
+ ]
2734
+ subagent_stats = self._subagent_statistics()
2735
+ return {
2736
+ "updated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
2737
+ "event_format": self.event_format,
2738
+ "event_type_counts": dict(self.event_type_counts),
2739
+ "claude_session_id": self.claude_session_id,
2740
+ "result_subtype": self.result_subtype,
2741
+ "stop_reason": self.stop_reason,
2742
+ "cursor_session_id": self.cursor_session_id,
2743
+ "antigravity_session_id": self.antigravity_session_id,
2744
+ "has_usage": self.has_usage,
2745
+ "permission_denial_count": len(self.permission_denials),
2746
+ "permission_denials": self.permission_denials[-10:],
2747
+ "message_count": self.message_count,
2748
+ "current_tool": self.current_tool,
2749
+ "current_tool_input_summary": self.current_tool_input_summary,
2750
+ "current_phase": self.current_phase,
2751
+ "detected_phases": self.detected_phases,
2752
+ "tool_calls": tool_calls,
2753
+ "total_tool_calls": self.total_tool_calls,
2754
+ "subagent_statistics": subagent_stats,
2755
+ "child_activity_source": "filesystem_liveness_only",
2756
+ "child_thread_ids": sorted(self.codex_child_thread_ids),
2757
+ "child_session_files": self.child_session_files,
2758
+ "child_total_bytes": self.child_total_bytes,
2759
+ "child_activity_signature": self.child_activity_signature,
2760
+ "last_child_activity_at": self.last_child_activity_at,
2761
+ "cb_session_id": self.cb_session_id,
2762
+ "cb_cwd": self.cb_cwd,
2763
+ "last_text_snippet": self.last_text_snippet,
2764
+ "last_result_is_error": self.last_result_is_error,
2765
+ "api_error_status": self.api_error_status,
2766
+ "api_error_code": self.api_error_code,
2767
+ "terminal_result_text": self.terminal_result_text,
2768
+ "terminal_success_at": self.terminal_success_at,
2769
+ "fatal_error_code": self.fatal_error_code,
2770
+ "is_active": self.is_active,
2771
+ "errors": self.errors[-10:],
2772
+ }
2773
+
2774
+
2775
+ def atomic_write_json(data, filepath):
2776
+ """Write JSON data atomically across all platforms."""
2777
+ try:
2778
+ write_json_atomic(filepath, data, indent=2, sort_keys=False, ensure_ascii=False, fsync=False)
2779
+ except OSError:
2780
+ pass