@fitchmultz/pi-subagents 0.0.0-stage → 0.44.4

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 (342) hide show
  1. package/CHANGELOG.md +1645 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1529 -2
  4. package/agents/context-builder.md +97 -0
  5. package/agents/debugger.md +51 -0
  6. package/agents/delegate.md +13 -0
  7. package/agents/fixer.md +37 -0
  8. package/agents/oracle.md +71 -0
  9. package/agents/planner.md +72 -0
  10. package/agents/researcher.md +51 -0
  11. package/agents/reviewer-claude.md +69 -0
  12. package/agents/reviewer-gpt.md +68 -0
  13. package/agents/reviewer-ponytail.md +82 -0
  14. package/agents/reviewer-security.md +81 -0
  15. package/agents/reviewer.md +69 -0
  16. package/agents/scout.md +66 -0
  17. package/agents/ui-designer.md +51 -0
  18. package/agents/watcher.md +26 -0
  19. package/agents/worker.md +46 -0
  20. package/agents/writer.md +36 -0
  21. package/dist/agents/agent-management.js +923 -0
  22. package/dist/agents/agent-scope.js +7 -0
  23. package/dist/agents/agent-selection.js +20 -0
  24. package/dist/agents/agent-serializer.js +100 -0
  25. package/dist/agents/agents.js +752 -0
  26. package/dist/agents/chain-serializer.js +367 -0
  27. package/dist/agents/frontmatter.js +21 -0
  28. package/dist/agents/identity.js +29 -0
  29. package/dist/agents/skills.js +570 -0
  30. package/dist/extension/build-info.js +1 -0
  31. package/dist/extension/compact-tools.js +112 -0
  32. package/dist/extension/config.js +22 -0
  33. package/dist/extension/control-notices.js +29 -0
  34. package/dist/extension/doctor.js +143 -0
  35. package/dist/extension/fanout-child.js +326 -0
  36. package/dist/extension/index.js +577 -0
  37. package/dist/extension/schemas.js +416 -0
  38. package/dist/extension/tool-input.js +20 -0
  39. package/dist/extension/tool-result.js +14 -0
  40. package/dist/history/canonical-result.js +81 -0
  41. package/dist/history/database.js +72 -0
  42. package/dist/history/index.js +194 -0
  43. package/dist/history/ingest.js +447 -0
  44. package/dist/history/queries.js +350 -0
  45. package/dist/history/store.js +216 -0
  46. package/dist/history/types.js +4 -0
  47. package/dist/history/worker.js +461 -0
  48. package/dist/intercom/intercom-bridge.js +112 -0
  49. package/dist/intercom/live-intercom.js +94 -0
  50. package/dist/intercom/result-intercom.js +373 -0
  51. package/dist/pi-intercom/agent-dir.js +10 -0
  52. package/dist/pi-intercom/broker/broker.js +426 -0
  53. package/dist/pi-intercom/broker/client.js +492 -0
  54. package/dist/pi-intercom/broker/framing.js +65 -0
  55. package/dist/pi-intercom/broker/paths.js +42 -0
  56. package/dist/pi-intercom/broker/pid.js +66 -0
  57. package/dist/pi-intercom/broker/spawn.js +221 -0
  58. package/dist/pi-intercom/config.js +102 -0
  59. package/dist/pi-intercom/index.js +2942 -0
  60. package/dist/pi-intercom/reply-tracker.js +182 -0
  61. package/dist/pi-intercom/session-targets.js +128 -0
  62. package/dist/pi-intercom/subagent-live-events.js +132 -0
  63. package/dist/pi-intercom/topics.js +157 -0
  64. package/dist/pi-intercom/types.js +163 -0
  65. package/dist/pi-intercom/ui/compose.js +269 -0
  66. package/dist/pi-intercom/ui/inline-message.js +80 -0
  67. package/dist/pi-intercom/ui/session-list.js +124 -0
  68. package/dist/runs/background/async-control.js +95 -0
  69. package/dist/runs/background/async-execution.js +676 -0
  70. package/dist/runs/background/async-job-tracker.js +383 -0
  71. package/dist/runs/background/async-result-file.js +58 -0
  72. package/dist/runs/background/async-resume.js +305 -0
  73. package/dist/runs/background/async-status.js +442 -0
  74. package/dist/runs/background/completion-dedupe.js +69 -0
  75. package/dist/runs/background/completion-delivery.js +245 -0
  76. package/dist/runs/background/notify.js +71 -0
  77. package/dist/runs/background/parallel-groups.js +55 -0
  78. package/dist/runs/background/result-watcher.js +426 -0
  79. package/dist/runs/background/run-id-resolver.js +64 -0
  80. package/dist/runs/background/run-status.js +382 -0
  81. package/dist/runs/background/stale-run-reconciler.js +335 -0
  82. package/dist/runs/background/subagent-runner-launcher.js +55 -0
  83. package/dist/runs/background/subagent-runner.js +1872 -0
  84. package/dist/runs/background/top-level-async.js +5 -0
  85. package/dist/runs/foreground/chain-clarify.js +1152 -0
  86. package/dist/runs/foreground/clarify-invocation.js +72 -0
  87. package/dist/runs/foreground/execution-input.js +423 -0
  88. package/dist/runs/foreground/foreground-control.js +817 -0
  89. package/dist/runs/foreground/question-control.js +77 -0
  90. package/dist/runs/foreground/run-async-path.js +205 -0
  91. package/dist/runs/foreground/subagent-executor.js +442 -0
  92. package/dist/runs/foreground/subagent-params.js +165 -0
  93. package/dist/runs/foreground/wait-run.js +139 -0
  94. package/dist/runs/shared/acceptance-contract.js +253 -0
  95. package/dist/runs/shared/acceptance-evaluation.js +256 -0
  96. package/dist/runs/shared/acceptance-finalization.js +280 -0
  97. package/dist/runs/shared/acceptance-reports.js +147 -0
  98. package/dist/runs/shared/acceptance.js +4 -0
  99. package/dist/runs/shared/chain-outputs.js +110 -0
  100. package/dist/runs/shared/child-attempt.js +693 -0
  101. package/dist/runs/shared/child-execution-cwd.js +96 -0
  102. package/dist/runs/shared/child-observations.js +114 -0
  103. package/dist/runs/shared/claude-code.js +199 -0
  104. package/dist/runs/shared/completion-guard.js +31 -0
  105. package/dist/runs/shared/dynamic-fanout.js +274 -0
  106. package/dist/runs/shared/history-index.js +72 -0
  107. package/dist/runs/shared/mcp-direct-tool-allowlist.js +334 -0
  108. package/dist/runs/shared/model-fallback.js +185 -0
  109. package/dist/runs/shared/mutating-tool-guard.js +170 -0
  110. package/dist/runs/shared/native-finalization.js +101 -0
  111. package/dist/runs/shared/native-usage.js +153 -0
  112. package/dist/runs/shared/nested-events.js +700 -0
  113. package/dist/runs/shared/nested-path.js +48 -0
  114. package/dist/runs/shared/nested-render.js +108 -0
  115. package/dist/runs/shared/parallel-utils.js +61 -0
  116. package/dist/runs/shared/parent-receipts.js +68 -0
  117. package/dist/runs/shared/parent-usage.js +121 -0
  118. package/dist/runs/shared/pi-args.js +310 -0
  119. package/dist/runs/shared/pi-spawn.js +52 -0
  120. package/dist/runs/shared/run-history-queries.js +45 -0
  121. package/dist/runs/shared/run-history.js +103 -0
  122. package/dist/runs/shared/run-id-ambiguity.js +4 -0
  123. package/dist/runs/shared/run-records.js +679 -0
  124. package/dist/runs/shared/session-cwd-preload.js +33 -0
  125. package/dist/runs/shared/single-output.js +222 -0
  126. package/dist/runs/shared/streaming-text.js +15 -0
  127. package/dist/runs/shared/structured-output.js +55 -0
  128. package/dist/runs/shared/subagent-control.js +179 -0
  129. package/dist/runs/shared/subagent-prompt-runtime.js +197 -0
  130. package/dist/runs/shared/subagent-tool-loop-guard.js +66 -0
  131. package/dist/runs/shared/supervisor-questions.js +320 -0
  132. package/dist/runs/shared/workflow-graph.js +214 -0
  133. package/dist/runs/shared/workflow-policy.js +84 -0
  134. package/dist/runs/shared/worktree.js +525 -0
  135. package/dist/shared/agent-context-policy.js +126 -0
  136. package/dist/shared/artifacts.js +96 -0
  137. package/dist/shared/atomic-json.js +13 -0
  138. package/dist/shared/cooperative.js +20 -0
  139. package/dist/shared/execution-cwd.js +14 -0
  140. package/dist/shared/file-coalescer.js +21 -0
  141. package/dist/shared/fork-context.js +49 -0
  142. package/dist/shared/formatters.js +85 -0
  143. package/dist/shared/journal-reader.js +407 -0
  144. package/dist/shared/lazy-tools.js +32 -0
  145. package/dist/shared/model-info.js +68 -0
  146. package/dist/shared/native-session.js +15 -0
  147. package/dist/shared/native-tui.js +18 -0
  148. package/dist/shared/native-typebox.js +20 -0
  149. package/dist/shared/post-exit-stdio-guard.js +197 -0
  150. package/dist/shared/prompt-sections.js +8 -0
  151. package/dist/shared/session-entries.js +52 -0
  152. package/dist/shared/session-identity.js +14 -0
  153. package/dist/shared/settings.js +254 -0
  154. package/dist/shared/status-format.js +111 -0
  155. package/dist/shared/temp-root.js +114 -0
  156. package/dist/shared/types.js +207 -0
  157. package/dist/shared/ui-mode.js +3 -0
  158. package/dist/shared/utils.js +334 -0
  159. package/dist/slash/prompt-template-bridge.js +298 -0
  160. package/dist/slash/slash-bridge.js +116 -0
  161. package/dist/slash/slash-commands.js +607 -0
  162. package/dist/slash/slash-live-state.js +246 -0
  163. package/dist/tui/action-hints.js +75 -0
  164. package/dist/tui/agent-history.js +197 -0
  165. package/dist/tui/agent-view.js +1656 -0
  166. package/dist/tui/render.js +1515 -0
  167. package/docs/intercom.md +579 -0
  168. package/docs/performance.md +121 -0
  169. package/package.json +101 -4
  170. package/prompts/gather-context-and-clarify.md +14 -0
  171. package/prompts/parallel-cleanup.md +62 -0
  172. package/prompts/parallel-context-build.md +56 -0
  173. package/prompts/parallel-handoff-plan.md +62 -0
  174. package/prompts/parallel-research.md +51 -0
  175. package/prompts/parallel-review.md +59 -0
  176. package/prompts/review-loop.md +42 -0
  177. package/scripts/build.mjs +134 -0
  178. package/scripts/check-compat.mjs +48 -0
  179. package/scripts/compat-host.mjs +19 -0
  180. package/scripts/linux-smoke.sh +51 -0
  181. package/scripts/local-install-smoke.mjs +66 -0
  182. package/scripts/native-package-smoke.mjs +82 -0
  183. package/scripts/package-smoke.mjs +205 -0
  184. package/scripts/prepare.mjs +67 -0
  185. package/scripts/real-pi-smoke.mjs +415 -0
  186. package/scripts/run-tests.mjs +149 -0
  187. package/skills/pi-intercom/SKILL.md +113 -0
  188. package/skills/pi-intercom/evals/evals.json +29 -0
  189. package/skills/pi-intercom/evals/trigger-evals.json +47 -0
  190. package/skills/pi-intercom/references/peer-sessions.md +69 -0
  191. package/skills/pi-subagents/SKILL.md +76 -0
  192. package/skills/pi-subagents/evals/evals.json +29 -0
  193. package/skills/pi-subagents/evals/trigger-evals.json +42 -0
  194. package/skills/pi-subagents/references/full-orchestration-guide.md +863 -0
  195. package/src/agents/agent-management.ts +813 -0
  196. package/src/agents/agent-scope.ts +7 -0
  197. package/src/agents/agent-selection.ts +23 -0
  198. package/src/agents/agent-serializer.ts +99 -0
  199. package/src/agents/agents.ts +916 -0
  200. package/src/agents/chain-serializer.ts +329 -0
  201. package/src/agents/frontmatter.ts +21 -0
  202. package/src/agents/identity.ts +30 -0
  203. package/src/agents/skills.ts +637 -0
  204. package/src/extension/build-info.ts +2 -0
  205. package/src/extension/compact-tools.ts +114 -0
  206. package/src/extension/config.ts +23 -0
  207. package/src/extension/control-notices.ts +47 -0
  208. package/src/extension/doctor.ts +171 -0
  209. package/src/extension/fanout-child.ts +312 -0
  210. package/src/extension/index.ts +649 -0
  211. package/src/extension/schemas.ts +444 -0
  212. package/src/extension/tool-input.ts +19 -0
  213. package/src/extension/tool-result.ts +16 -0
  214. package/src/history/canonical-result.ts +62 -0
  215. package/src/history/database.ts +59 -0
  216. package/src/history/index.ts +152 -0
  217. package/src/history/ingest.ts +332 -0
  218. package/src/history/queries.ts +241 -0
  219. package/src/history/store.ts +203 -0
  220. package/src/history/types.ts +166 -0
  221. package/src/history/worker.ts +317 -0
  222. package/src/intercom/intercom-bridge.ts +123 -0
  223. package/src/intercom/live-intercom.ts +104 -0
  224. package/src/intercom/result-intercom.ts +429 -0
  225. package/src/pi-intercom/agent-dir.ts +9 -0
  226. package/src/pi-intercom/broker/broker.ts +463 -0
  227. package/src/pi-intercom/broker/client.ts +558 -0
  228. package/src/pi-intercom/broker/framing.ts +77 -0
  229. package/src/pi-intercom/broker/paths.ts +47 -0
  230. package/src/pi-intercom/broker/pid.ts +59 -0
  231. package/src/pi-intercom/broker/spawn.ts +248 -0
  232. package/src/pi-intercom/config.ts +142 -0
  233. package/src/pi-intercom/index.ts +2929 -0
  234. package/src/pi-intercom/reply-tracker.ts +211 -0
  235. package/src/pi-intercom/session-targets.ts +172 -0
  236. package/src/pi-intercom/subagent-live-events.ts +133 -0
  237. package/src/pi-intercom/topics.ts +125 -0
  238. package/src/pi-intercom/types.ts +271 -0
  239. package/src/pi-intercom/ui/compose.ts +289 -0
  240. package/src/pi-intercom/ui/inline-message.ts +92 -0
  241. package/src/pi-intercom/ui/session-list.ts +139 -0
  242. package/src/runs/background/async-control.ts +89 -0
  243. package/src/runs/background/async-execution.ts +850 -0
  244. package/src/runs/background/async-job-tracker.ts +385 -0
  245. package/src/runs/background/async-result-file.ts +62 -0
  246. package/src/runs/background/async-resume.ts +333 -0
  247. package/src/runs/background/async-status.ts +481 -0
  248. package/src/runs/background/completion-dedupe.ts +79 -0
  249. package/src/runs/background/completion-delivery.ts +195 -0
  250. package/src/runs/background/notify.ts +123 -0
  251. package/src/runs/background/parallel-groups.ts +53 -0
  252. package/src/runs/background/result-watcher.ts +423 -0
  253. package/src/runs/background/run-id-resolver.ts +69 -0
  254. package/src/runs/background/run-status.ts +384 -0
  255. package/src/runs/background/stale-run-reconciler.ts +369 -0
  256. package/src/runs/background/subagent-runner-launcher.ts +56 -0
  257. package/src/runs/background/subagent-runner.ts +2053 -0
  258. package/src/runs/background/top-level-async.ts +13 -0
  259. package/src/runs/foreground/chain-clarify.ts +1340 -0
  260. package/src/runs/foreground/clarify-invocation.ts +77 -0
  261. package/src/runs/foreground/execution-input.ts +467 -0
  262. package/src/runs/foreground/foreground-control.ts +821 -0
  263. package/src/runs/foreground/question-control.ts +70 -0
  264. package/src/runs/foreground/run-async-path.ts +243 -0
  265. package/src/runs/foreground/subagent-executor.ts +501 -0
  266. package/src/runs/foreground/subagent-params.ts +320 -0
  267. package/src/runs/foreground/wait-run.ts +121 -0
  268. package/src/runs/shared/acceptance-contract.ts +257 -0
  269. package/src/runs/shared/acceptance-evaluation.ts +275 -0
  270. package/src/runs/shared/acceptance-finalization.ts +353 -0
  271. package/src/runs/shared/acceptance-reports.ts +152 -0
  272. package/src/runs/shared/acceptance.ts +33 -0
  273. package/src/runs/shared/chain-outputs.ts +114 -0
  274. package/src/runs/shared/child-attempt.ts +623 -0
  275. package/src/runs/shared/child-execution-cwd.ts +91 -0
  276. package/src/runs/shared/child-observations.ts +99 -0
  277. package/src/runs/shared/claude-code.ts +243 -0
  278. package/src/runs/shared/completion-guard.ts +35 -0
  279. package/src/runs/shared/dynamic-fanout.ts +295 -0
  280. package/src/runs/shared/history-index.ts +69 -0
  281. package/src/runs/shared/mcp-direct-tool-allowlist.ts +376 -0
  282. package/src/runs/shared/model-fallback.ts +219 -0
  283. package/src/runs/shared/mutating-tool-guard.ts +194 -0
  284. package/src/runs/shared/native-finalization.ts +128 -0
  285. package/src/runs/shared/native-usage.ts +113 -0
  286. package/src/runs/shared/nested-events.ts +752 -0
  287. package/src/runs/shared/nested-path.ts +52 -0
  288. package/src/runs/shared/nested-render.ts +119 -0
  289. package/src/runs/shared/parallel-utils.ts +153 -0
  290. package/src/runs/shared/parent-receipts.ts +59 -0
  291. package/src/runs/shared/parent-usage.ts +121 -0
  292. package/src/runs/shared/pi-args.ts +350 -0
  293. package/src/runs/shared/pi-spawn.ts +52 -0
  294. package/src/runs/shared/run-history-queries.ts +44 -0
  295. package/src/runs/shared/run-history.ts +93 -0
  296. package/src/runs/shared/run-id-ambiguity.ts +4 -0
  297. package/src/runs/shared/run-records.ts +607 -0
  298. package/src/runs/shared/session-cwd-preload.ts +27 -0
  299. package/src/runs/shared/single-output.ts +267 -0
  300. package/src/runs/shared/streaming-text.ts +18 -0
  301. package/src/runs/shared/structured-output.ts +68 -0
  302. package/src/runs/shared/subagent-control.ts +219 -0
  303. package/src/runs/shared/subagent-prompt-runtime.ts +201 -0
  304. package/src/runs/shared/subagent-tool-loop-guard.ts +89 -0
  305. package/src/runs/shared/supervisor-questions.ts +372 -0
  306. package/src/runs/shared/workflow-graph.ts +220 -0
  307. package/src/runs/shared/workflow-policy.ts +125 -0
  308. package/src/runs/shared/worktree.ts +635 -0
  309. package/src/shared/agent-context-policy.ts +184 -0
  310. package/src/shared/artifacts.ts +95 -0
  311. package/src/shared/atomic-json.ts +16 -0
  312. package/src/shared/cooperative.ts +21 -0
  313. package/src/shared/execution-cwd.ts +14 -0
  314. package/src/shared/file-coalescer.ts +29 -0
  315. package/src/shared/fork-context.ts +68 -0
  316. package/src/shared/formatters.ts +84 -0
  317. package/src/shared/journal-reader.ts +333 -0
  318. package/src/shared/lazy-tools.ts +36 -0
  319. package/src/shared/model-info.ts +81 -0
  320. package/src/shared/native-session.ts +8 -0
  321. package/src/shared/native-tui.ts +10 -0
  322. package/src/shared/native-typebox.ts +14 -0
  323. package/src/shared/post-exit-stdio-guard.ts +204 -0
  324. package/src/shared/prompt-sections.ts +10 -0
  325. package/src/shared/session-entries.ts +49 -0
  326. package/src/shared/session-identity.ts +18 -0
  327. package/src/shared/settings.ts +384 -0
  328. package/src/shared/status-format.ts +123 -0
  329. package/src/shared/temp-root.ts +107 -0
  330. package/src/shared/types.ts +1259 -0
  331. package/src/shared/ui-mode.ts +5 -0
  332. package/src/shared/utils.ts +342 -0
  333. package/src/slash/prompt-template-bridge.ts +408 -0
  334. package/src/slash/slash-bridge.ts +178 -0
  335. package/src/slash/slash-commands.ts +617 -0
  336. package/src/slash/slash-live-state.ts +292 -0
  337. package/src/tui/action-hints.ts +69 -0
  338. package/src/tui/agent-history.ts +210 -0
  339. package/src/tui/agent-view.ts +1323 -0
  340. package/src/tui/render.ts +1550 -0
  341. package/tsconfig.build.json +12 -0
  342. package/tsconfig.json +19 -0
@@ -0,0 +1,623 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { addAbortListener } from "node:events";
4
+ import { mkdirSync, writeFileSync, mkdtempSync, openSync, readSync, writeSync, closeSync, rmSync, fstatSync, ftruncateSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { StringDecoder } from "node:string_decoder";
7
+ import * as path from "node:path";
8
+ import type { Message } from "@earendil-works/pi-ai";
9
+ import { attachChildProcessLifecycle } from "../../shared/post-exit-stdio-guard.ts";
10
+ import { applyIntercomBridgeToAgent, resolveIntercomBridge } from "../../intercom/intercom-bridge.ts";
11
+ import { providerQualifiedModelId } from "../../shared/model-info.ts";
12
+ import { getSubagentDepthEnv, type AgentProcessExit, type ResourceLimitExceeded, type Usage } from "../../shared/types.ts";
13
+ import { extractTextFromContent, extractToolArgsPreview, formatResourceLimitExceeded, getFinalOutput, findLatestSessionFile } from "../../shared/utils.ts";
14
+ import { readFinalizationReport, resolveExecutionOutcome } from "./acceptance.ts";
15
+ import { readStructuredOutput } from "./structured-output.ts";
16
+ import {
17
+ appendClaudeCodeMessage, buildClaudeCodeInvocation, claudeCodeMessageFromResult, isClaudeCodeModel, writeClaudeCodeSessionMetadata,
18
+ type ClaudeCodeInvocation, type ClaudeCodeResultEvent,
19
+ } from "./claude-code.ts";
20
+ import { createMutationCompletionTracker, resolveCurrentPath, type MutationToolResult } from "./mutating-tool-guard.ts";
21
+ import { applyThinkingSuffix, buildPiArgs } from "./pi-args.ts";
22
+ import { FINALIZATION_EVENT, nativeFinalizationLaunch, type NativeFinalizationConfig, type NativeFinalizationEvent } from "./native-finalization.ts";
23
+ import { addUsage, nativeUsageCollector, readNativeUsage, snapshotNativeBaseline, validateNativeUsage, type NativeUsageMetadata } from "./native-usage.ts";
24
+ import { sumAttemptUsage } from "./model-fallback.ts";
25
+ import { getPiSpawnCommand } from "./pi-spawn.ts";
26
+ import type { StructuredOutputRuntime } from "./structured-output.ts";
27
+ import type { updateStreamingText } from "./streaming-text.ts";
28
+ import { createRepeatedSubagentCallGuardState, recordToolEndForSubagentLoopGuard, recordToolStartForSubagentLoopGuard } from "./subagent-tool-loop-guard.ts";
29
+ import { JournalFrames, NativeJournal, nativeProjection, scanJournal, type Projection } from "../../shared/journal-reader.ts";
30
+ import { compactObservedMessage, createMessageReferenceIndex, ExitCodeObservation } from "./child-observations.ts";
31
+
32
+ const liveProjection: Projection = (path, root) => {
33
+ if (!path.length) return true;
34
+ if (["messages", "toolResults"].includes(String(path[0]))) return false;
35
+ if (path[0] === "entry") return path.length === 1 || ["id", "type", "parentId", "timestamp", "customType", "usage", "provider", "model"].includes(String(path[1])) ? 4096 : false;
36
+ if (path[0] === "assistantMessageEvent") return path.length === 1 || ["type", "delta", "contentIndex"].includes(String(path[1])) ? 8192 : false;
37
+ if (path[0] === "result" && root?.type !== "result") return false;
38
+ if (path[0] === "message") {
39
+ if (path.length > 1 && !["role", "timestamp", "provider", "model", "responseModel", "usage", "stopReason", "errorMessage", "toolCallId", "toolName", "isError", "content", "details"].includes(String(path[1]))) return false;
40
+ if (path[1] === "content" && root?.type !== "message_end") return false;
41
+ if (path[1] === "content" && path.length === 2) return 4096;
42
+ if (path[1] === "details") return path.length === 2 || ["preview", "modifiedFiles"].includes(String(path[2])) ? 4096 : false;
43
+ if (path[1] === "content" && path.length > 3) {
44
+ if (path[3] === "thinking" || path[3] === "data") return false;
45
+ if (path[3] === "text") return root?.message?.role === "assistant" ? true : 4096;
46
+ if (path[3] === "arguments") return root?.message?.content?.[Number(path[2])]?.name === "structured_output" ? true : nativeProjection(path, root);
47
+ }
48
+ }
49
+ // ponytail: explicitly consumed tool arguments and structured reports must
50
+ // fit their guard/schema consumer's heap; lifecycle aggregates are skipped.
51
+ return true;
52
+ };
53
+ const liveKeyLimit = (path: readonly (string | number)[]) => path[0] === "args" || path[0] === "structured_output" || path.includes("arguments") ? Infinity : 4096;
54
+
55
+ export function buildChildInvocation(input: Omit<Parameters<typeof buildPiArgs>[0], "baseArgs"> & { nativeFinalization?: NativeFinalizationConfig }): {
56
+ args: string[];
57
+ env: Record<string, string | undefined>;
58
+ tempDir?: string;
59
+ claudeCodeInvocation?: ClaudeCodeInvocation;
60
+ } {
61
+ const model = applyThinkingSuffix(input.model, input.thinking);
62
+ if (!model || !isClaudeCodeModel(model)) {
63
+ if (input.orchestratorIntercomTarget) {
64
+ const bridged = applyIntercomBridgeToAgent({ systemPrompt: input.systemPrompt ?? "",
65
+ tools: input.tools, extensions: input.extensions }, resolveIntercomBridge(input.orchestratorIntercomTarget));
66
+ input = { ...input, systemPrompt: bridged.systemPrompt, tools: bridged.tools, extensions: bridged.extensions };
67
+ }
68
+ const built = buildPiArgs({ ...input, structuredOutput: input.nativeFinalization ? undefined : input.structuredOutput, baseArgs: ["--mode", "json", "-p"] });
69
+ if (input.nativeFinalization) {
70
+ const runtime = nativeFinalizationLaunch(input.nativeFinalization);
71
+ built.args.push("--extension", runtime.extension);
72
+ Object.assign(built.env, runtime.env);
73
+ const tools = built.args.indexOf("--tools");
74
+ if (tools >= 0 && !built.args[tools + 1]!.split(",").includes("structured_output")) built.args[tools + 1] += ",structured_output";
75
+ }
76
+ return built;
77
+ }
78
+ const claudeCodeInvocation = buildClaudeCodeInvocation({ ...input, model, systemPrompt: input.systemPrompt ?? undefined,
79
+ sessionName: input.intercomSessionName, outputSchema: input.structuredOutput?.schema });
80
+ return { args: claudeCodeInvocation.args, env: claudeCodeInvocation.env, claudeCodeInvocation };
81
+ }
82
+
83
+ export interface ChildEvent {
84
+ type?: string;
85
+ assistantMessageEvent?: Parameters<typeof updateStreamingText>[1]["assistantMessageEvent"];
86
+ message?: Message;
87
+ toolCallId?: string;
88
+ toolName?: string;
89
+ args?: Record<string, unknown>;
90
+ isError?: boolean;
91
+ }
92
+
93
+ export interface NativeAttemptSegment {
94
+ event: NativeFinalizationEvent;
95
+ messages: Message[];
96
+ usage: Usage;
97
+ durationMs: number;
98
+ execution?: Pick<ChildAttemptResult, "exitCode" | "error" | "interrupted" | "timedOut" | "resourceLimitExceeded" | "terminalFailure">;
99
+ }
100
+
101
+ export interface ChildAttemptResult {
102
+ accounting?: { state: "complete" | "incomplete"; error?: string };
103
+ nativeSessionId?: string;
104
+ terminalLeafId?: string | null;
105
+ terminalEntryId?: string;
106
+ effectiveConfiguration?: { model?: string; thinking?: string; modelRecordedAt?: number };
107
+ attemptBaseline?: string[];
108
+ auditPath?: string;
109
+ auditSaveError?: string;
110
+ auditRecords?: Array<{ kind: string; messageNumber?: number; offset: number; length: number }>;
111
+ nativeReferences?: Array<{ messageNumber?: number; entryId: string }>;
112
+ messageCount?: number;
113
+ finalization?: NativeAttemptSegment[];
114
+ stderr: string;
115
+ agentProcessExit?: AgentProcessExit;
116
+ exitCode: number;
117
+ messages: Message[];
118
+ usage: Usage;
119
+ model?: string;
120
+ error?: string;
121
+ finalOutput: string;
122
+ interrupted?: boolean;
123
+ timedOut?: boolean;
124
+ terminalFailure?: boolean;
125
+ observedCompletedMutation: boolean;
126
+ resourceLimitExceeded?: ResourceLimitExceeded;
127
+ durationMs: number;
128
+ }
129
+
130
+ export interface ChildAttemptControl {
131
+ pid?: number;
132
+ readonly stopping: boolean;
133
+ stop(outcome: Pick<ChildAttemptResult, "error" | "timedOut" | "interrupted">): void;
134
+ }
135
+
136
+ interface ChildAttemptOptions {
137
+ args: string[];
138
+ cwd: string;
139
+ env?: Record<string, string | undefined>;
140
+ agent: string;
141
+ model?: string;
142
+ maxSubagentDepth?: number;
143
+ maxExecutionTimeMs?: number;
144
+ maxTokens?: number;
145
+ claudeCodeInvocation?: ClaudeCodeInvocation;
146
+ sessionFile?: string;
147
+ auditPath?: string;
148
+ structuredOutput?: StructuredOutputRuntime;
149
+ reportRuntime?: StructuredOutputRuntime;
150
+ nativeFinalization?: NativeFinalizationConfig;
151
+ signal?: AbortSignal;
152
+ interruptSignal?: AbortSignal;
153
+ onStart?: (control: ChildAttemptControl, result: ChildAttemptResult) => void;
154
+ onEvent?: (event: ChildEvent, result: ChildAttemptResult, mutation?: MutationToolResult) => void;
155
+ onFailure?: (result: ChildAttemptResult) => void;
156
+ onOutput?: (text: string) => void;
157
+ onRawLine?: (stream: "stdout" | "stderr", line: string) => void;
158
+ onStderr?: (text: string) => void;
159
+ }
160
+
161
+ /** One owned process group and finalized JSON event stream for either native backend. */
162
+ export function runChildAttempt(options: ChildAttemptOptions): Promise<ChildAttemptResult> {
163
+ const result: ChildAttemptResult = {
164
+ stderr: "", exitCode: 0, messages: [], model: options.model,
165
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 },
166
+ finalOutput: "", observedCompletedMutation: false, durationMs: 0,
167
+ };
168
+ if (options.signal?.aborted || options.interruptSignal?.aborted) {
169
+ Object.assign(result, resolveExecutionOutcome({ result, signal: options.signal, interruptSignal: options.interruptSignal }));
170
+ result.finalOutput = result.error ?? "Interrupted. Waiting for explicit next action.";
171
+ return Promise.resolve(result);
172
+ }
173
+ const sessionDirectoryArg = options.args.indexOf("--session-dir");
174
+ const sessionDirectory = sessionDirectoryArg >= 0 ? options.args[sessionDirectoryArg + 1] : undefined;
175
+ const nativeSessionFile = () => options.claudeCodeInvocation ? undefined : options.sessionFile ?? (sessionDirectory ? findLatestSessionFile(sessionDirectory) ?? undefined : undefined);
176
+ let baseline: Set<string>;
177
+ let baselineSnapshot: ReturnType<typeof snapshotNativeBaseline>;
178
+ try { baselineSnapshot = snapshotNativeBaseline(nativeSessionFile()); baseline = baselineSnapshot.ids; } catch (error) {
179
+ return Promise.resolve({ ...result, exitCode: 1, terminalFailure: true, error: `Cannot capture native usage baseline: ${error instanceof Error ? error.message : String(error)}` });
180
+ }
181
+ const streamId = randomUUID();
182
+ let wireDirectory = "", wireFd = -1, textFd = -1, stderrFd = -1;
183
+ try {
184
+ const parent = options.auditPath ? path.dirname(options.auditPath) : tmpdir();
185
+ mkdirSync(parent, { recursive: true });
186
+ wireDirectory = mkdtempSync(path.join(parent, ".pi-subagents-wire-"));
187
+ wireFd = openSync(path.join(wireDirectory, "stdout"), "wx+");
188
+ textFd = openSync(path.join(wireDirectory, "text"), "wx+");
189
+ stderrFd = openSync(path.join(wireDirectory, "stderr"), "wx+");
190
+ } catch (error) {
191
+ if (wireFd >= 0) closeSync(wireFd);
192
+ if (textFd >= 0) closeSync(textFd);
193
+ if (stderrFd >= 0) closeSync(stderrFd);
194
+ if (wireDirectory) rmSync(wireDirectory, { recursive: true, force: true });
195
+ return Promise.resolve({ ...result, exitCode: 1, terminalFailure: true, error: `Cannot prepare child observations: ${String(error)}` });
196
+ }
197
+ return new Promise((resolve) => {
198
+ const startedAt = Date.now();
199
+ const invocation = options.claudeCodeInvocation;
200
+ const command = invocation ?? getPiSpawnCommand(options.args);
201
+ const child = spawn(command.command, command.args, {
202
+ cwd: options.cwd,
203
+ env: { ...process.env, ...options.env, ...getSubagentDepthEnv(options.maxSubagentDepth), PI_SUBAGENT_NATIVE_BASELINE_COUNT: baselineSnapshot.legacy ? String(baselineSnapshot.entryCount) : "" },
204
+ stdio: ["ignore", "pipe", "pipe"],
205
+ detached: true,
206
+ });
207
+ const lifecycle = attachChildProcessLifecycle(child);
208
+ const mutations = createMutationCompletionTracker();
209
+ const toolLoop = createRepeatedSubagentCallGuardState();
210
+ const wirePath = path.join(wireDirectory, "stdout");
211
+ let textOffset = 0;
212
+ const observations: Array<{ start: number; end: number; kind: string; number?: number; message?: Message; nativeEntryId?: string }> = [];
213
+ const references = createMessageReferenceIndex<(typeof observations)[number]>();
214
+ const referenceMessage = (entry: NativeUsageMetadata) => baseline.has(entry.id) ? undefined : references.reference(entry);
215
+ let rawOutput = "", lastOutput = "", boundariesCursor = 0;
216
+ let receiverFailed = false;
217
+ const acceptedEntries = new Map<string, NativeUsageMetadata>();
218
+ let nativeMessageCount = 0;
219
+ const pendingBoundary = Symbol("pending boundary");
220
+ let textWritten = false, exitObservation = new ExitCodeObservation(), firstTextPath: string | undefined;
221
+ let outputTextPath: string | undefined, pendingSurrogate = "";
222
+ let reproject = false, replayOutput = false;
223
+ result.attemptBaseline = [...baseline];
224
+ let assistantError: string | undefined;
225
+ let cleanAssistantStop = false;
226
+ let settled = false;
227
+ let resourceTimer: NodeJS.Timeout | undefined;
228
+ let attemptStartedAt = startedAt;
229
+ let messageOffset = 0;
230
+ // maxTokens bounds this assistant; billing also includes nested tools and summaries.
231
+ let assistantTokens = 0;
232
+ let attemptAssistantTokens = 0;
233
+ const attemptUsage = { ...result.usage };
234
+ const resetResourceTimer = () => {
235
+ clearTimeout(resourceTimer);
236
+ if (options.maxExecutionTimeMs !== undefined) {
237
+ const limit = options.maxExecutionTimeMs;
238
+ resourceTimer = setTimeout(() => {
239
+ syncFinalization();
240
+ if (Date.now() - attemptStartedAt >= limit) resourceLimit("maxExecutionTimeMs", limit);
241
+ else resetResourceTimer();
242
+ }, Math.max(0, limit - (Date.now() - attemptStartedAt)));
243
+ resourceTimer.unref();
244
+ }
245
+ };
246
+
247
+ const stop = (outcome: Pick<ChildAttemptResult, "error" | "timedOut" | "interrupted">) => {
248
+ if (settled) return;
249
+ Object.assign(result, outcome);
250
+ result.durationMs = Date.now() - startedAt;
251
+ if (outcome.error) options.onOutput?.(`${outcome.error}\n`);
252
+ options.onFailure?.(result);
253
+ lifecycle.terminate();
254
+ };
255
+ const resourceLimit = (kind: ResourceLimitExceeded["kind"], limit: number, observed?: number) => {
256
+ if (settled || result.resourceLimitExceeded || result.timedOut || lifecycle.stopping) return;
257
+ const message = formatResourceLimitExceeded({ agent: options.agent, kind, limit, observed });
258
+ result.resourceLimitExceeded = { kind, limit, ...(observed !== undefined ? { observed } : {}), message };
259
+ stop({ error: message });
260
+ };
261
+ const syncFinalization = () => {
262
+ if (!options.nativeFinalization) return;
263
+ const file = path.join(path.dirname(options.nativeFinalization.reportRuntime.schemaPath), "boundaries.jsonl");
264
+ try { scanJournal(file, () => true, ({ value, end }) => {
265
+ const marker = value as NativeFinalizationEvent;
266
+ if (marker.nonce !== options.nativeFinalization!.nonce) throw new Error("Unexpected finalization nonce");
267
+ if (marker.messageCount > nativeMessageCount) throw pendingBoundary;
268
+ const messages = result.messages.filter((message) => ["assistant", "user", "toolResult"].includes(message.role));
269
+ const segmentMessages = messages.slice(messageOffset, marker.messageCount);
270
+ const usage: Usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
271
+ let segmentAssistantTokens = 0;
272
+ for (const message of segmentMessages) {
273
+ if (message.role === "assistant") {
274
+ usage.turns++;
275
+ segmentAssistantTokens += (message.usage?.input ?? 0) + (message.usage?.output ?? 0);
276
+ }
277
+ if ((message.role === "assistant" || message.role === "toolResult") && message.usage) addUsage(usage, message.usage);
278
+ }
279
+ (result.finalization ??= []).push({ event: marker, messages: segmentMessages, usage, durationMs: marker.at - attemptStartedAt });
280
+ if (options.maxTokens !== undefined && segmentAssistantTokens >= options.maxTokens) resourceLimit("maxTokens", options.maxTokens, segmentAssistantTokens);
281
+ if (options.maxExecutionTimeMs !== undefined && marker.at - attemptStartedAt >= options.maxExecutionTimeMs) resourceLimit("maxExecutionTimeMs", options.maxExecutionTimeMs);
282
+ if (marker.nextPrompt) {
283
+ messageOffset = marker.messageCount;
284
+ attemptAssistantTokens += segmentAssistantTokens;
285
+ for (const key of ["input", "output", "cacheRead", "cacheWrite", "cost", "turns"] as const) attemptUsage[key] += usage[key];
286
+ attemptStartedAt = marker.at;
287
+ resetResourceTimer();
288
+ }
289
+ options.onEvent?.(marker, result);
290
+ boundariesCursor = end;
291
+ }, { policy: "live", start: boundariesCursor }); } catch (error) { if (error !== pendingBoundary && (error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
292
+ };
293
+ const processEvent = (input: ChildEvent) => {
294
+ let event = input;
295
+ if (!event || typeof event !== "object") return;
296
+ if (event.type === "message_end" && !event.message) throw new Error("Child message_end event is missing its message");
297
+ if (event.type !== "message_update") syncFinalization();
298
+ if (event.type === "subagent.native_baseline") {
299
+ const value = event as ChildEvent & { sessionId: string; entryIds: string[] };
300
+ if (!baselineSnapshot.legacy || value.sessionId !== baselineSnapshot.sessionId || !Array.isArray(value.entryIds)
301
+ || new Set(value.entryIds).size !== baselineSnapshot.entryCount || value.entryIds.some((id) => typeof id !== "string" || !id)) throw new Error("Cannot reconcile native legacy baseline");
302
+ baseline.clear(); baseline.add(value.sessionId); for (const id of value.entryIds) baseline.add(id);
303
+ result.attemptBaseline = [...baseline];
304
+ }
305
+ if (event.type === "subagent.native") {
306
+ const native = event as ChildEvent & { sessionId: string; leafId: string | null; persisted?: boolean; configuration: ChildAttemptResult["effectiveConfiguration"]; entries: Array<NativeUsageMetadata & { message?: { role: string; timestamp: number; toolCallId?: string } }> };
307
+ result.nativeSessionId = native.sessionId;
308
+ result.terminalLeafId = native.leafId;
309
+ result.terminalEntryId = native.entries.at(-1)?.id ?? result.terminalEntryId;
310
+ result.effectiveConfiguration = native.configuration;
311
+ if (!native.persisted) for (const entry of native.entries) acceptedEntries.set(entry.id, entry);
312
+ const nativeReferences = [];
313
+ if (native.persisted) for (const entry of native.entries) if (entry.message) {
314
+ const observation = referenceMessage(entry);
315
+ if (observation) {
316
+ nativeReferences.push({ messageNumber: observation.number, entryId: entry.id });
317
+ }
318
+ }
319
+ Object.assign(event, { nativeReferences, referenceState: "observed" });
320
+ }
321
+ lifecycle.observeEvent(invocation && event.type === "result" ? "agent_settled" : event.type);
322
+ if (invocation && event.type === "result") {
323
+ const nativeResult = event as ClaudeCodeResultEvent;
324
+ // Claude reports totals, not a native per-category cost receipt. Keep
325
+ // that observation rather than inventing zero-valued category costs.
326
+ result.accounting = { state: "incomplete", error: "Claude Code did not provide the complete native usage/cost receipt. Reported totals and its audit were retained." };
327
+ if (options.structuredOutput && nativeResult.structured_output !== undefined) {
328
+ mkdirSync(path.dirname(options.structuredOutput.outputPath), { recursive: true });
329
+ writeFileSync(options.structuredOutput.outputPath, `${JSON.stringify(nativeResult.structured_output)}\n`, "utf8");
330
+ }
331
+ const message = claudeCodeMessageFromResult(nativeResult, invocation.model.inputModel);
332
+ if (options.sessionFile) {
333
+ writeClaudeCodeSessionMetadata(options.sessionFile, {
334
+ sessionId: nativeResult.session_id || invocation.sessionId,
335
+ model: invocation.model.inputModel, cliModel: invocation.model.cliModel,
336
+ family: invocation.model.family, context: invocation.model.context, updatedAt: Date.now(),
337
+ });
338
+ const { result: _result, structured_output: _structured, ...observation } = nativeResult;
339
+ appendClaudeCodeMessage(options.sessionFile, message, observation);
340
+ }
341
+ event = { type: "message_end", message };
342
+ }
343
+ let mutation: MutationToolResult | undefined;
344
+ let loopFailure: string | undefined;
345
+ if (event.type === "tool_execution_start") {
346
+ loopFailure = recordToolStartForSubagentLoopGuard({ state: toolLoop, ...event, toolName: event.toolName, args: event.args });
347
+ mutations.recordToolStart({ id: event.toolCallId, toolName: event.toolName, args: event.args,
348
+ path: resolveCurrentPath(event.toolName, event.args), startedAt: Date.now() });
349
+ const args = extractToolArgsPreview(event.args ?? {});
350
+ if (event.toolName) options.onOutput?.(`${event.toolName}${args ? `: ${args}` : ""}\n`);
351
+ } else if (event.type === "tool_execution_end") {
352
+ loopFailure = recordToolEndForSubagentLoopGuard({ state: toolLoop, ...event, toolName: event.toolName, isError: event.isError });
353
+ } else if (event.type === "message_end" && event.message) {
354
+ const message = event.message;
355
+ if (message.role === "assistant" && !message.usage) result.accounting = { state: "incomplete", error: "Required assistant usage is unavailable; execution was not repeated." };
356
+ const final = getFinalOutput([message]);
357
+ if (final) lastOutput = final;
358
+ result.messages.push(compactObservedMessage(message));
359
+ if (["assistant", "user", "toolResult"].includes(message.role)) nativeMessageCount++;
360
+ result.messageCount = nativeMessageCount;
361
+ const text = extractTextFromContent(message.content);
362
+ if (textWritten) options.onOutput?.("\n");
363
+ else if (invocation && text) options.onOutput?.(`${text}\n`);
364
+ if ((message.role === "assistant" || message.role === "toolResult") && message.usage) {
365
+ try { addUsage(result.usage, message.usage, { id: `stream:${streamId}:${result.messages.length}`,
366
+ provider: message.role === "assistant" ? message.provider : undefined,
367
+ model: message.role === "assistant" ? message.responseModel ?? message.model : undefined });
368
+ validateNativeUsage(message.usage);
369
+ } catch (error) { result.accounting = { state: "incomplete", error: String(error) }; }
370
+ }
371
+ if (message.role === "toolResult") {
372
+ mutation = mutations.recordToolResult(message);
373
+ if (mutation?.completedMutation) result.observedCompletedMutation = true;
374
+ } else if (message.role === "assistant") {
375
+ result.model ??= providerQualifiedModelId(message.provider, message.model);
376
+ result.usage.turns++;
377
+ assistantTokens += (message.usage?.input ?? 0) + (message.usage?.output ?? 0);
378
+ if (message.errorMessage) assistantError = message.errorMessage;
379
+ cleanAssistantStop = message.stopReason === "stop" && !message.errorMessage
380
+ && !message.content.some((part) => part.type === "toolCall");
381
+ if (cleanAssistantStop && text.trim()) assistantError = undefined;
382
+ }
383
+ }
384
+ result.durationMs = Date.now() - startedAt;
385
+ options.onEvent?.(event, result, mutation);
386
+ if (loopFailure && !lifecycle.stopping) {
387
+ result.terminalFailure = true;
388
+ stop({ error: loopFailure });
389
+ }
390
+ if (event.type === "message_end") syncFinalization();
391
+ const tokens = assistantTokens - attemptAssistantTokens;
392
+ if (options.maxTokens !== undefined && tokens >= options.maxTokens) resourceLimit("maxTokens", options.maxTokens, tokens);
393
+ };
394
+
395
+ const copyBytes = (fd: number, start: number, end: number, consume: (bytes: Buffer) => void) => {
396
+ const buffer = Buffer.allocUnsafe(64 * 1024);
397
+ for (let position = start; position < end;) {
398
+ const count = readSync(fd, buffer, 0, Math.min(buffer.length, end - position), position);
399
+ if (!count) throw new Error("Missing child audit bytes");
400
+ consume(buffer.subarray(0, count)); position += count;
401
+ }
402
+ };
403
+ const appendText = (text: string) => {
404
+ const bytes = Buffer.from(text);
405
+ for (let offset = 0; offset < bytes.length;) {
406
+ const count = writeSync(textFd, bytes, offset, bytes.length - offset, textOffset + offset);
407
+ if (!count) throw new Error("Cannot write child output spool");
408
+ offset += count;
409
+ }
410
+ textOffset += bytes.length;
411
+ };
412
+ const resetRecord = () => {
413
+ textWritten = false; exitObservation = new ExitCodeObservation(); firstTextPath = undefined;
414
+ pendingSurrogate = ""; outputTextPath = undefined; reproject = false; replayOutput = false;
415
+ textOffset = 0; ftruncateSync(textFd, 0);
416
+ };
417
+ const consumeMessageText = (path: readonly (string | number)[], text: string, root?: Record<string, any>) => {
418
+ if (root?.type !== "message_end" || path[0] !== "message" || path[1] !== "content" || path.at(-1) !== "text" && path.length !== 2) return;
419
+ const key = path.join(".");
420
+ if (outputTextPath !== key) {
421
+ if (pendingSurrogate) { textWritten = true; appendText(pendingSurrogate); }
422
+ pendingSurrogate = "";
423
+ if (textWritten && text) appendText("\n");
424
+ outputTextPath = key;
425
+ }
426
+ // Unpacked JSON escape tokens can split a surrogate pair. Join that one
427
+ // code unit before handing text to an output writer.
428
+ const joined = pendingSurrogate + text;
429
+ pendingSurrogate = /[\uD800-\uDBFF]/.test(joined.at(-1) ?? "") ? joined.at(-1)! : "";
430
+ const output = pendingSurrogate ? joined.slice(0, -1) : joined;
431
+ if (output) { textWritten = true; appendText(output); }
432
+ if (path.length !== 4) return;
433
+ firstTextPath ??= key;
434
+ if (firstTextPath === key) exitObservation.write(text);
435
+ };
436
+ const stdout = new JournalFrames((path, root) => {
437
+ if (invocation) return !path.length || ["type", "subtype", "is_error", "api_error_status", "result", "stop_reason", "session_id", "total_cost_usd", "usage", "modelUsage", "structured_output"].includes(String(path[0]));
438
+ if (path[0] === "message" && path[1] === "content" && !root?.type) replayOutput = true;
439
+ if (path[0] === "message" && path[1] === "content" && (!root?.type || path.at(-1) === "text" && !root.message?.role
440
+ || path.includes("arguments") && !root.message?.content?.[Number(path[2])]?.name)) reproject = true;
441
+ return liveProjection(path, root);
442
+ }, ({ value: projected, start, end }) => {
443
+ if (!projected || typeof projected !== "object" || Array.isArray(projected)) { resetRecord(); return; }
444
+ let value = projected;
445
+ if (reproject && value.type === "message_end") {
446
+ // JSON member order is not semantic. Revisit only this selected value
447
+ // when attribution/call names appeared after their payloads.
448
+ for (let pass = 0; pass < 2; pass++) {
449
+ const known = value;
450
+ scanJournal(wirePath, (path, root) => liveProjection(path, { ...root, type: known.type,
451
+ message: { ...root?.message, role: known.message?.role, content: known.message?.content ?? root?.message?.content } }),
452
+ (record) => { value = record.value; }, { start, end, policy: "strict", keys: liveKeyLimit,
453
+ ...(pass === 0 && replayOutput ? { stringChunk: (path, text, root) => consumeMessageText(path, text, { ...root, type: known.type }) } : {}) });
454
+ }
455
+ }
456
+ reproject = false; replayOutput = false;
457
+ if (pendingSurrogate) { textWritten = true; appendText(pendingSurrogate); }
458
+ pendingSurrogate = ""; outputTextPath = undefined;
459
+ const decoder = new StringDecoder("utf8");
460
+ copyBytes(textFd, 0, textOffset, (bytes) => options.onOutput?.(decoder.write(bytes)));
461
+ const tail = decoder.end(); if (tail) options.onOutput?.(tail);
462
+ if (exitObservation.value !== undefined && value.type === "message_end" && value.message?.role === "toolResult") value.message.observedExitCode = exitObservation.value;
463
+ processEvent(value as ChildEvent);
464
+ if (["message_end", "tool_execution_end"].includes(value.type) || invocation && (value.type !== "result" || !options.sessionFile)) {
465
+ const observation = { start, end, kind: value.type,
466
+ ...(value.type === "message_end" ? { number: nativeMessageCount, message: result.messages.at(-1) } : {}) };
467
+ observations.push(observation);
468
+ references.add(observation);
469
+ }
470
+ resetRecord();
471
+ }, "inspect", 0, (start, end) => {
472
+ observations.push({ start, end, kind: "diagnostic" });
473
+ const decoder = new StringDecoder("utf8");
474
+ copyBytes(wireFd, start, end, (bytes) => {
475
+ const text = decoder.write(bytes);
476
+ rawOutput = (rawOutput + text).slice(-16384);
477
+ options.onOutput?.(text); options.onRawLine?.("stdout", text);
478
+ });
479
+ const tail = decoder.end(); if (tail) options.onOutput?.(tail);
480
+ resetRecord();
481
+ }, consumeMessageText, liveKeyLimit);
482
+ child.stderr.setEncoding("utf8");
483
+ child.stdout.on("data", (bytes: Buffer) => {
484
+ try { writeFileSync(wireFd, bytes); if (!receiverFailed) stdout.write(bytes); } catch (error) {
485
+ receiverFailed = true;
486
+ result.terminalFailure = true; stop({ error: `Cannot receive child events: ${String(error)}` });
487
+ }
488
+ });
489
+ child.stderr.on("data", (text: string) => {
490
+ try {
491
+ writeFileSync(stderrFd, text);
492
+ result.stderr = (result.stderr + text).slice(-16384);
493
+ options.onStderr?.(text);
494
+ } catch (error) {
495
+ result.terminalFailure = true; stop({ error: `Cannot save child diagnostics: ${String(error)}` });
496
+ }
497
+ });
498
+ const abortListener = options.signal && addAbortListener(options.signal, () => {
499
+ const reason = options.signal?.reason;
500
+ stop({ error: reason instanceof Error && reason.name === "TimeoutError" ? reason.message : "Subagent cancelled.",
501
+ timedOut: reason instanceof Error && reason.name === "TimeoutError" || undefined, interrupted: false });
502
+ });
503
+ const interruptListener = options.interruptSignal && addAbortListener(options.interruptSignal, () => {
504
+ if (options.signal?.aborted || result.resourceLimitExceeded || result.timedOut) return;
505
+ stop({ interrupted: true, error: undefined });
506
+ });
507
+ const finish = (code: number | null, signal?: NodeJS.Signals | null, spawnError?: Error) => {
508
+ if (settled) return;
509
+ // Sealed stdout may retain an EOF observation; native publication is verified separately.
510
+ try { if (!receiverFailed) stdout.finish(); } catch (error) { receiverFailed = true; result.error ??= String(error); result.terminalFailure = true; }
511
+ try { syncFinalization(); } catch (error) { result.error ??= `Cannot read finalization boundary: ${String(error)}`; result.terminalFailure = true; }
512
+ settled = true;
513
+ clearTimeout(resourceTimer);
514
+ abortListener?.[Symbol.dispose]();
515
+ interruptListener?.[Symbol.dispose]();
516
+ result.agentProcessExit = lifecycle.agentProcessExit;
517
+ result.durationMs = Date.now() - startedAt;
518
+ const reportRuntime = options.nativeFinalization?.reportRuntime ?? options.reportRuntime;
519
+ const report = reportRuntime && readFinalizationReport(result.messages, reportRuntime).output;
520
+ const structured = options.structuredOutput && readStructuredOutput(options.structuredOutput);
521
+ const completedOutput = cleanAssistantStop || report || structured && !structured.error;
522
+ if (report) assistantError = undefined;
523
+ result.error ??= assistantError ?? spawnError?.message;
524
+ const drainedSuccess = lifecycle.settledCleanup && (cleanAssistantStop || report) && !result.error;
525
+ if (code !== 0 && !result.error && !drainedSuccess && !result.interrupted) result.error = result.stderr.trim() || undefined;
526
+ result.exitCode = result.timedOut ? 124 : result.resourceLimitExceeded || result.terminalFailure ? 1
527
+ : result.interrupted || drainedSuccess ? 0 : lifecycle.stopping || signal ? code ?? 1 : code ?? 0;
528
+ if (result.interrupted) result.error = undefined;
529
+ if (result.exitCode === 0 && !result.interrupted && !result.error && !completedOutput) {
530
+ result.error = options.nativeFinalization ? "Native self-review boundary did not return a result." : "Child exit was observed, but no completed assistant result was returned.";
531
+ result.exitCode = 1; result.terminalFailure = true;
532
+ }
533
+ result.finalOutput = result.resourceLimitExceeded?.message ?? (lastOutput || rawOutput.trim());
534
+ if (options.nativeFinalization) {
535
+ const previous = result.finalization?.at(-1);
536
+ if (previous?.event.nextPrompt) {
537
+ const usage = { ...result.usage, contributions: result.usage.contributions?.slice(attemptUsage.contributions?.length ?? 0) };
538
+ for (const key of ["input", "output", "cacheRead", "cacheWrite", "cost", "turns"] as const) usage[key] -= attemptUsage[key];
539
+ result.finalization!.push({ event: { type: FINALIZATION_EVENT, nonce: options.nativeFinalization.nonce,
540
+ turn: previous.event.turn + 1, messageCount: result.messages.length, at: Date.now(), submission: { output: "" }, resolvedOutput: previous.event.resolvedOutput },
541
+ messages: result.messages.slice(messageOffset), usage, durationMs: Date.now() - attemptStartedAt });
542
+ }
543
+ const final = result.finalization?.at(-1);
544
+ if (final) {
545
+ if (final.event.turn > 0) final.event.submission = { ...readFinalizationReport(result.messages, options.nativeFinalization.reportRuntime, { messageOffset }), error: final.event.submission.error };
546
+ final.execution = { exitCode: result.exitCode, error: result.error, interrupted: result.interrupted,
547
+ timedOut: result.timedOut, resourceLimitExceeded: result.resourceLimitExceeded, terminalFailure: result.terminalFailure };
548
+ } else if (result.exitCode === 0 && !result.error && !result.interrupted) {
549
+ result.error = "Native self-review boundary did not return a result.";
550
+ result.exitCode = 1;
551
+ result.terminalFailure = true;
552
+ }
553
+ }
554
+ const publishedIds = new Set<string>();
555
+ try {
556
+ const native = readNativeUsage(nativeSessionFile(), baseline, result.finalization?.map((segment) => segment.event.lastEntryId), {
557
+ onEntry: (entry) => { if (entry.type === "message") { publishedIds.add(entry.id); referenceMessage(entry); } },
558
+ onBoundary: ({ sessionId, lastEntryId }) => { result.nativeSessionId = sessionId; result.terminalEntryId = lastEntryId; },
559
+ });
560
+ const accepted = !native && result.nativeSessionId && acceptedEntries.size
561
+ ? nativeUsageCollector(result.nativeSessionId, baseline, result.finalization?.map((segment) => segment.event.lastEntryId)) : undefined;
562
+ if (accepted) for (const entry of acceptedEntries.values()) accepted.append(entry);
563
+ const totals = native ?? accepted?.totals;
564
+ if (totals) {
565
+ if (native && observations.some((item) => item.message && (item.message.role === "assistant" || item.message.role === "toolResult" && item.message.usage)
566
+ && (!item.nativeEntryId || !publishedIds.has(item.nativeEntryId)))) throw new Error("Finalized message usage has no verified native commit; its reported usage and audit remain available.");
567
+ result.accounting = { state: "complete" };
568
+ result.usage = sumAttemptUsage(totals.map((usage) => ({ model: result.model ?? "default", success: true, usage })));
569
+ result.finalization?.forEach((segment, index) => { segment.usage = totals[index]!; });
570
+ }
571
+ } catch (error) {
572
+ result.accounting = { state: "incomplete", error: `Cannot read finalized native usage: ${error instanceof Error ? error.message : String(error)}` };
573
+ }
574
+ for (const item of observations) if (item.nativeEntryId) {
575
+ if (publishedIds.has(item.nativeEntryId)) (result.nativeReferences ??= []).push({ messageNumber: item.number, entryId: item.nativeEntryId });
576
+ else item.nativeEntryId = undefined;
577
+ }
578
+ result.accounting ??= { state: "complete" };
579
+ const file = nativeSessionFile();
580
+ if (!result.effectiveConfiguration && file) try {
581
+ const journal = new NativeJournal(file, "inspect", true);
582
+ const terminal = journal.records.findLast((record) => record.value.type !== "session");
583
+ result.terminalEntryId ??= terminal?.value.id;
584
+ result.terminalLeafId ??= result.terminalEntryId;
585
+ result.effectiveConfiguration = journal.configuration(undefined, result.terminalLeafId);
586
+ } catch (error) { result.accounting = { state: "incomplete", error: result.accounting.error ?? `Cannot capture terminal native selection: ${String(error)}` }; }
587
+ const retained = receiverFailed ? [{ start: 0, end: fstatSync(wireFd).size, kind: "receiver_failure", number: undefined }] : observations.filter((item) => !item.nativeEntryId);
588
+ const auditPath = options.auditPath ?? path.join(wireDirectory, "observations.log");
589
+ const stderrLength = fstatSync(stderrFd).size;
590
+ let retainedWire = false;
591
+ try { if (retained.length || stderrLength) {
592
+ const audit = openSync(auditPath, "a", 0o600);
593
+ try {
594
+ let offset = fstatSync(audit).size;
595
+ for (const item of retained) {
596
+ copyBytes(wireFd, item.start, item.end, (bytes) => writeFileSync(audit, bytes));
597
+ (result.auditRecords ??= []).push({ kind: item.kind, messageNumber: item.number, offset, length: item.end - item.start });
598
+ offset += item.end - item.start;
599
+ }
600
+ if (stderrLength) {
601
+ copyBytes(stderrFd, 0, stderrLength, (bytes) => writeFileSync(audit, bytes));
602
+ (result.auditRecords ??= []).push({ kind: "stderr", offset, length: stderrLength });
603
+ }
604
+ result.auditPath = auditPath;
605
+ } finally { closeSync(audit); }
606
+ }
607
+ } catch (error) { retainedWire = true; result.auditSaveError = String(error); result.auditPath = wireDirectory; }
608
+ finally {
609
+ closeSync(wireFd); closeSync(textFd); closeSync(stderrFd);
610
+ if (!retainedWire) {
611
+ if (result.auditPath?.startsWith(`${wireDirectory}${path.sep}`)) {
612
+ rmSync(wirePath); rmSync(path.join(wireDirectory, "text")); rmSync(path.join(wireDirectory, "stderr"));
613
+ } else rmSync(wireDirectory, { recursive: true, force: true });
614
+ }
615
+ }
616
+ resolve(result);
617
+ };
618
+ child.on("close", (code, signal) => finish(code, signal));
619
+ child.on("error", (error) => finish(1, undefined, error));
620
+ resetResourceTimer();
621
+ options.onStart?.({ pid: child.pid, get stopping() { return lifecycle.stopping; }, stop }, result);
622
+ });
623
+ }