@fitchmultz/pi-subagents 0.0.0-stage → 0.44.5

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