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