@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,1872 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { spawnSync } from "node:child_process";
10
+ import { readChildProcessIdentity } from "../../shared/post-exit-stdio-guard.js";
11
+ import * as fs from "node:fs";
12
+ import * as path from "node:path";
13
+ import { pathToFileURL } from "node:url";
14
+ import { writeAtomicJson } from "../../shared/atomic-json.js";
15
+ import { readAsyncControlRequests } from "./async-control.js";
16
+ import { appendJsonl, getArtifactPaths } from "../../shared/artifacts.js";
17
+ import { PI_CODING_AGENT_PACKAGE, resolveInstalledPiPackageRoot } from "../shared/pi-spawn.js";
18
+ import { captureSingleOutputSnapshot, cleanupSingleOutputFile, finalizeSingleOutput, findDuplicateOutputPath, formatConsumedOutputReference, formatSavedOutputReference, injectSingleOutputInstruction, resolveSingleOutput } from "../shared/single-output.js";
19
+ import { DEFAULT_MAX_OUTPUT, truncateOutput, } from "../../shared/types.js";
20
+ import { DEFAULT_CONTROL_CONFIG, buildControlEvent, deriveActivityState, claimControlNotification, formatControlIntercomMessage, formatControlNoticeMessage, } from "../shared/subagent-control.js";
21
+ import { isDynamicRunnerGroup, isParallelGroup, flattenSteps, MAX_PARALLEL_CONCURRENCY, } from "../shared/parallel-utils.js";
22
+ import { cleanupTempDir, SUBAGENT_CHILD_ENV, SUBAGENT_FANOUT_CHILD_ENV } from "../shared/pi-args.js";
23
+ import { isClaudeCodeModel, } from "../shared/claude-code.js";
24
+ import { renderChainTask } from "../shared/chain-outputs.js";
25
+ import { createStructuredOutputRuntime, readStructuredOutput } from "../shared/structured-output.js";
26
+ import { DynamicFanoutError, materializeDynamicParallelStep } from "../shared/dynamic-fanout.js";
27
+ import { completeWorkflowStep, runParallelTasks, workflowChildSucceeded } from "../shared/workflow-policy.js";
28
+ import { nestedSummaryFromAsyncStatus, writeNestedEvent } from "../shared/nested-events.js";
29
+ import { runModelAttempts, sumAttemptUsage } from "../shared/model-fallback.js";
30
+ import { buildChildInvocation, runChildAttempt } from "../shared/child-attempt.js";
31
+ import { createNativeFinalization, FINALIZATION_EVENT } from "../shared/native-finalization.js";
32
+ import { updateStreamingText } from "../shared/streaming-text.js";
33
+ import { pendingSupervisorQuestion, saveAsyncRunResult, saveRunStatus, saveQuestionContract } from "../shared/supervisor-questions.js";
34
+ import { compactForegroundResult, detectSubagentError, extractTextFromContent, extractToolArgsPreview, findLatestSessionFile } from "../../shared/utils.js";
35
+ import { hasCompletedMutationToolCall, resolveCompletionPolicy } from "../shared/completion-guard.js";
36
+ import { createMutatingFailureState, recordMutatingFailure, resetMutatingFailureState, resolveCurrentPath, shouldEscalateMutatingFailures, summarizeRecentMutatingFailures, } from "../shared/mutating-tool-guard.js";
37
+ import { appendWorktreeSummary, cleanupWorktrees, createWorktrees, findWorktreeTaskCwdConflict, formatParallelWorktreeSummary, formatWorktreeTaskCwdConflict, WorktreeCleanupError, } from "../shared/worktree.js";
38
+ import { recordRun } from "../shared/run-history.js";
39
+ import { resolveEffectiveThinking } from "../../shared/model-info.js";
40
+ import { namespaceParallelOutput, writeInitialProgressFile } from "../../shared/settings.js";
41
+ import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.js";
42
+ import { evaluateRunAcceptance, acceptanceHumanAction, createFinalizationReportRuntime, readFinalizationReport, formatUnconfirmedFinalizationOutput, resolveExecutionOutcome, resolveFinalizationOutput, formatAcceptancePrompt, stripAcceptanceReport, } from "../shared/acceptance.js";
43
+ const ASYNC_INTERRUPT_SIGNAL = "SIGUSR2";
44
+ function formatProcessExitFailure(input) {
45
+ const duration = input.durationMs !== undefined ? ` after ${input.durationMs}ms` : "";
46
+ if (input.exitCode === 143) {
47
+ return `${input.agent} exited with code 143${duration}. The child process received SIGTERM or exited as if terminated by SIGTERM; if this was close to 300000ms, Pi's default HTTP idle timeout is a likely provider-side cause.`;
48
+ }
49
+ return `${input.agent} exited with code ${input.exitCode ?? 1}${duration} without producing a final assistant response.`;
50
+ }
51
+ function emptyUsage() {
52
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
53
+ }
54
+ function tokenUsageFromAttempts(attempts) {
55
+ if (!attempts || attempts.length === 0)
56
+ return null;
57
+ let input = 0;
58
+ let output = 0;
59
+ for (const attempt of attempts) {
60
+ input += attempt.usage?.input ?? 0;
61
+ output += attempt.usage?.output ?? 0;
62
+ }
63
+ const total = input + output;
64
+ return total > 0 ? { input, output, total } : null;
65
+ }
66
+ function appendRecentStepOutput(step, lines) {
67
+ const nonEmpty = lines.filter((line) => line.trim());
68
+ if (nonEmpty.length === 0)
69
+ return;
70
+ step.recentOutput ??= [];
71
+ step.recentOutput.push(...nonEmpty);
72
+ if (step.recentOutput.length > 50) {
73
+ step.recentOutput.splice(0, step.recentOutput.length - 50);
74
+ }
75
+ }
76
+ function clearStepCurrentActivity(step) {
77
+ step.currentTool = undefined;
78
+ step.currentToolArgs = undefined;
79
+ step.currentToolStartedAt = undefined;
80
+ step.currentPath = undefined;
81
+ }
82
+ function resetStepLiveDetail(step) {
83
+ clearStepCurrentActivity(step);
84
+ step.recentTools = [];
85
+ step.recentOutput = [];
86
+ }
87
+ function markStepPaused(step, now) {
88
+ step.status = "paused";
89
+ step.activityState = undefined;
90
+ clearStepCurrentActivity(step);
91
+ step.startedAt ??= now;
92
+ step.endedAt = now;
93
+ step.durationMs = step.startedAt !== undefined ? now - step.startedAt : undefined;
94
+ step.lastActivityAt = now;
95
+ step.exitCode = 0;
96
+ }
97
+ // Durable run records have no age cleanup. Streaming deltas and cumulative tool
98
+ // progress repeat what message_end and tool_execution_end already record.
99
+ const TRANSIENT_CHILD_EVENT_TYPES = new Set(["message_update", "tool_execution_update"]);
100
+ async function runPiStreaming(options, outputFile, context) {
101
+ const outputFd = fs.openSync(outputFile, "w", 0o600);
102
+ const auditPath = `${outputFile}.audit.log`;
103
+ const appendEvent = (event) => appendJsonl(context.eventsPath, JSON.stringify({
104
+ ...event, recordVersion: 3, subagentSource: "child", subagentRunId: context.runId,
105
+ subagentStepIndex: context.stepIndex, subagentAgent: context.agent, observedAt: Date.now(),
106
+ }));
107
+ const output = (text) => { fs.writeFileSync(outputFd, text); };
108
+ try {
109
+ const result = await runChildAttempt({
110
+ ...options, auditPath,
111
+ onStart: (control, result) => {
112
+ if (control.pid)
113
+ saveQuestionContract(context.runId, context.stepIndex, { pid: control.pid, processIdentity: readChildProcessIdentity(control.pid), sessionFile: options.sessionFile, attemptBaseline: result.attemptBaseline, updatedAt: Date.now() });
114
+ options.onStart?.(control, result);
115
+ },
116
+ onOutput: output,
117
+ onStderr: (text) => {
118
+ appendEvent({ type: "subagent.child.stderr", auditPath, length: Buffer.byteLength(text) });
119
+ },
120
+ onEvent: (event, result, mutation) => {
121
+ // Preserve live callback ordering; only the disk representation is reduced.
122
+ options.onEvent?.(event, result, mutation);
123
+ if (TRANSIENT_CHILD_EVENT_TYPES.has(event.type ?? ""))
124
+ return;
125
+ if (event.type === "subagent.native_baseline") {
126
+ appendEvent(event);
127
+ saveQuestionContract(context.runId, context.stepIndex, { attemptBaseline: result.attemptBaseline, baselineSource: "native-migration" });
128
+ }
129
+ else if (event.type === "subagent.native") {
130
+ appendEvent(event);
131
+ saveQuestionContract(context.runId, context.stepIndex, { nativeSessionId: result.nativeSessionId, terminalLeafId: result.terminalLeafId, effectiveConfiguration: result.effectiveConfiguration, updatedAt: Date.now() });
132
+ }
133
+ else if (event.type === FINALIZATION_EVENT) {
134
+ const marker = event;
135
+ const file = `${outputFile}.boundaries.jsonl`;
136
+ fs.appendFileSync(file, `${JSON.stringify(marker)}\n`, { mode: 0o600 });
137
+ appendEvent({ type: marker.type, nonce: marker.nonce, turn: marker.turn, lastEntryId: marker.lastEntryId, messageCount: marker.messageCount, at: marker.at, boundaryFile: file });
138
+ }
139
+ else {
140
+ appendEvent({ type: event.type, messageNumber: result.messageCount,
141
+ ...(event.message ? { role: event.message.role, timestamp: event.message.timestamp } : {}),
142
+ toolCallId: event.toolCallId, toolName: event.toolName, isError: event.isError,
143
+ ...(event.type === "tool_execution_start" ? { argsPreview: extractToolArgsPreview(event.args ?? {}) } : {}),
144
+ ...(event.type === "tool_execution_end" ? { auditPath } : {}) });
145
+ }
146
+ },
147
+ });
148
+ appendEvent({ type: "subagent.child.finalized", agentProcessExit: result.agentProcessExit, exitCode: result.exitCode,
149
+ accounting: result.accounting, nativeSessionId: result.nativeSessionId, terminalLeafId: result.terminalLeafId,
150
+ terminalEntryId: result.terminalEntryId, nativeReferences: result.nativeReferences, auditPath: result.auditPath, auditRecords: result.auditRecords, auditSaveError: result.auditSaveError, outputFile });
151
+ saveQuestionContract(context.runId, context.stepIndex, { nativeSessionId: result.nativeSessionId, terminalLeafId: result.terminalLeafId, terminalEntryId: result.terminalEntryId,
152
+ effectiveConfiguration: result.effectiveConfiguration, accounting: result.accounting, auditPath: result.auditPath, updatedAt: Date.now() });
153
+ return result;
154
+ }
155
+ finally {
156
+ fs.closeSync(outputFd);
157
+ }
158
+ }
159
+ function resolvePiPackageRootFallback() {
160
+ const root = resolveInstalledPiPackageRoot();
161
+ if (root)
162
+ return root;
163
+ throw new Error(`Could not resolve ${PI_CODING_AGENT_PACKAGE} package root`);
164
+ }
165
+ async function exportSessionHtml(sessionFile, outputDir, piPackageRoot) {
166
+ const pkgRoot = piPackageRoot ?? resolvePiPackageRootFallback();
167
+ const exportModulePath = path.join(pkgRoot, "dist", "core", "export-html", "index.js");
168
+ const moduleUrl = pathToFileURL(exportModulePath).href;
169
+ const mod = await import(__rewriteRelativeImportExtension(moduleUrl));
170
+ const exportFromFile = mod
171
+ .exportFromFile;
172
+ if (typeof exportFromFile !== "function") {
173
+ throw new Error("exportFromFile not available");
174
+ }
175
+ const outputPath = path.join(outputDir, `${path.basename(sessionFile, ".jsonl")}.html`);
176
+ return exportFromFile(sessionFile, { outputPath });
177
+ }
178
+ function createShareLink(htmlPath) {
179
+ try {
180
+ const auth = spawnSync("gh", ["auth", "status"], { encoding: "utf-8" });
181
+ if (auth.status !== 0) {
182
+ return { error: "GitHub CLI is not logged in. Run 'gh auth login' first." };
183
+ }
184
+ }
185
+ catch {
186
+ return { error: "GitHub CLI (gh) is not installed." };
187
+ }
188
+ try {
189
+ const result = spawnSync("gh", ["gist", "create", htmlPath], { encoding: "utf-8" });
190
+ if (result.status !== 0) {
191
+ const err = (result.stderr || "").trim() || "Failed to create gist.";
192
+ return { error: err };
193
+ }
194
+ const gistUrl = (result.stdout || "").trim();
195
+ const gistId = gistUrl.split("/").pop();
196
+ if (!gistId)
197
+ return { error: "Failed to parse gist ID." };
198
+ const shareUrl = `https://shittycodingagent.ai/session/?${gistId}`;
199
+ return { shareUrl, gistUrl };
200
+ }
201
+ catch (err) {
202
+ return { error: String(err) };
203
+ }
204
+ }
205
+ function formatDuration(ms) {
206
+ if (ms < 1000)
207
+ return `${ms}ms`;
208
+ if (ms < 60000)
209
+ return `${(ms / 1000).toFixed(1)}s`;
210
+ const minutes = Math.floor(ms / 60000);
211
+ const seconds = Math.floor((ms % 60000) / 1000);
212
+ return `${minutes}m${seconds}s`;
213
+ }
214
+ function writeRunLog(logPath, input) {
215
+ const lines = [];
216
+ lines.push(`# Subagent run ${input.id}`);
217
+ lines.push("");
218
+ lines.push(`- **Mode:** ${input.mode}`);
219
+ lines.push(`- **Launch cwd:** ${input.cwd}`);
220
+ lines.push(`- **Started:** ${new Date(input.startedAt).toISOString()}`);
221
+ lines.push(`- **Ended:** ${new Date(input.endedAt).toISOString()}`);
222
+ lines.push(`- **Duration:** ${formatDuration(input.endedAt - input.startedAt)}`);
223
+ if (input.sessionFile)
224
+ lines.push(`- **Session:** ${input.sessionFile}`);
225
+ if (input.shareUrl)
226
+ lines.push(`- **Share:** ${input.shareUrl}`);
227
+ if (input.shareError)
228
+ lines.push(`- **Share error:** ${input.shareError}`);
229
+ if (input.artifactsDir)
230
+ lines.push(`- **Artifacts:** ${input.artifactsDir}`);
231
+ lines.push("");
232
+ lines.push("## Steps");
233
+ lines.push("| Step | Agent | Status | Duration |");
234
+ lines.push("| --- | --- | --- | --- |");
235
+ input.steps.forEach((step, i) => {
236
+ const duration = step.durationMs !== undefined ? formatDuration(step.durationMs) : "-";
237
+ lines.push(`| ${i + 1} | ${step.agent} | ${step.status} | ${duration} |`);
238
+ });
239
+ lines.push("");
240
+ lines.push("## Summary");
241
+ if (input.truncated) {
242
+ lines.push("_Output truncated_");
243
+ lines.push("");
244
+ }
245
+ lines.push(input.summary.trim() || "(no output)");
246
+ lines.push("");
247
+ fs.writeFileSync(logPath, lines.join("\n"), "utf-8");
248
+ }
249
+ /** Run a single pi agent step, returning output and metadata */
250
+ async function runSingleStep(step, ctx) {
251
+ const startedAt = Date.now();
252
+ let toolCount = 0;
253
+ const toolCalls = [];
254
+ if (ctx.signal?.aborted)
255
+ return { agent: step.agent, output: "", exitCode: 1, error: "Subagent cancelled." };
256
+ if (ctx.nativeFinalization && step.effectiveAcceptance?.explicit && !step.sessionFile) {
257
+ step = { ...step, sessionFile: path.join(path.dirname(ctx.outputFile), `session-${ctx.flatIndex}.jsonl`) };
258
+ }
259
+ saveQuestionContract(ctx.id, ctx.flatIndex, { task: step.task, label: step.label, effectiveAcceptance: step.effectiveAcceptance, output: step.outputPath ?? false, outputMode: step.outputMode, outputSchema: step.structuredOutputSchema ?? step.structuredOutput?.schema, launch: step.launch ? { ...step.launch, cwd: step.cwd ?? ctx.cwd, output: step.outputPath ?? false, outputMode: step.outputMode ?? "inline", outputSchema: step.structuredOutputSchema ?? step.structuredOutput?.schema, model: step.model, thinking: step.thinking } : undefined, sessionFile: step.sessionFile });
260
+ const interruptController = new AbortController();
261
+ ctx.registerInterrupt?.(() => interruptController.abort());
262
+ const interruptSignal = AbortSignal.any([ctx.interruptSignal, interruptController.signal].filter((signal) => signal !== undefined));
263
+ const verificationSignal = AbortSignal.any([ctx.signal, interruptSignal].filter((signal) => signal !== undefined));
264
+ const effectiveStructuredOutput = step.structuredOutput ?? (step.structuredOutputSchema
265
+ ? createStructuredOutputRuntime(step.structuredOutputSchema, path.join(path.dirname(ctx.outputFile), "structured-output"))
266
+ : undefined);
267
+ let task = step.task;
268
+ if (step.effectiveAcceptance) {
269
+ const acceptancePrompt = formatAcceptancePrompt(step.effectiveAcceptance);
270
+ if (acceptancePrompt)
271
+ task = `${task}\n${acceptancePrompt}`;
272
+ }
273
+ const sessionEnabled = Boolean(step.sessionFile) || ctx.sessionEnabled;
274
+ const sessionDir = step.sessionFile ? undefined : ctx.sessionDir;
275
+ let artifactPaths;
276
+ if (ctx.artifactsDir) {
277
+ const index = ctx.flatStepCount > 1 ? ctx.flatIndex : undefined;
278
+ artifactPaths = getArtifactPaths(ctx.artifactsDir, ctx.id, step.agent, index);
279
+ fs.mkdirSync(ctx.artifactsDir, { recursive: true });
280
+ fs.writeFileSync(artifactPaths.inputPath, `# Task for ${step.agent}\n\n${task}`, "utf-8");
281
+ }
282
+ const eventsPath = path.join(path.dirname(ctx.outputFile), "events.jsonl");
283
+ let nativeExecution;
284
+ let nativeSegments = [];
285
+ const nativeAttempt = (segment) => {
286
+ const state = segment.execution;
287
+ const error = state?.error ?? segment.event.submission.error
288
+ ?? (state?.exitCode && !state.interrupted ? formatProcessExitFailure({ agent: step.agent, exitCode: state.exitCode, durationMs: segment.durationMs }) : undefined);
289
+ return {
290
+ ...nativeExecution, exitCode: error && !state?.exitCode ? 1 : state?.exitCode ?? 0, error,
291
+ interrupted: state?.interrupted, timedOut: state?.timedOut, resourceLimitExceeded: state?.resourceLimitExceeded,
292
+ terminalFailure: Boolean(segment.event.submission.error) || state?.terminalFailure,
293
+ messages: segment.messages, usage: segment.usage, durationMs: segment.durationMs,
294
+ finalOutput: segment.event.submission.output, reportSubmission: segment.event.turn > 0 ? segment.event.submission : undefined,
295
+ resolvedOutput: segment.event.resolvedOutput, finalization: undefined,
296
+ };
297
+ };
298
+ async function runAttempt(prompt, model, review) {
299
+ if (verificationSignal.aborted) {
300
+ const outcome = resolveExecutionOutcome({ result: { exitCode: 1 }, signal: ctx.signal, interruptSignal });
301
+ return { stderr: "", messages: [], usage: emptyUsage(), durationMs: 0, observedCompletedMutation: false, finalOutput: outcome.error ?? "Interrupted. Waiting for explicit next action.",
302
+ ...outcome, exitCode: outcome.exitCode ?? 1, model, terminalFailure: true, resolvedOutput: { fullOutput: "" } };
303
+ }
304
+ ctx.onAttemptStart?.({ model, thinking: resolveEffectiveThinking(model, step.thinking) });
305
+ const structuredRuntime = review ? review.reportRuntime : effectiveStructuredOutput;
306
+ const outputSnapshot = review ? review.outputSnapshot : captureSingleOutputSnapshot(step.outputPath);
307
+ if (structuredRuntime) {
308
+ try {
309
+ fs.rmSync(structuredRuntime.outputPath, { force: true });
310
+ }
311
+ catch {
312
+ // readStructuredOutput reports unreadable or stale output after the attempt.
313
+ }
314
+ }
315
+ let args;
316
+ let env;
317
+ let tempDir;
318
+ let claudeCodeInvocation;
319
+ const sessionFile = review?.sessionFile ?? step.sessionFile;
320
+ const nativeFinalization = ctx.nativeFinalization && !review && !isClaudeCodeModel(model) && step.effectiveAcceptance?.explicit
321
+ ? createNativeFinalization(step.effectiveAcceptance, structuredRuntime, step.outputPath) : undefined;
322
+ try {
323
+ const built = buildChildInvocation({
324
+ task: prompt, model, thinking: step.thinking,
325
+ sessionEnabled: review ? true : sessionEnabled, sessionDir: review ? undefined : sessionDir, sessionFile,
326
+ inheritProjectContext: step.inheritProjectContext, inheritSkills: step.inheritSkills,
327
+ tools: step.tools, allowSubagents: step.allowSubagents, extensions: step.extensions,
328
+ systemPrompt: step.systemPrompt, systemPromptMode: step.systemPromptMode, mcpDirectTools: step.mcpDirectTools,
329
+ cwd: step.cwd ?? ctx.cwd, intercomSessionName: ctx.childIntercomTarget, orchestratorIntercomTarget: ctx.orchestratorIntercomTarget,
330
+ runId: ctx.id, childAgentName: step.agent, childIndex: ctx.flatIndex, rootSessionId: ctx.rootSessionId,
331
+ parentEventSink: ctx.nestedRoute?.eventSink, parentControlInbox: ctx.nestedRoute?.controlInbox,
332
+ parentRootRunId: ctx.nestedRoute?.rootRunId, parentCapabilityToken: ctx.nestedRoute?.capabilityToken,
333
+ structuredOutput: structuredRuntime, projectTrust: ctx.projectTrust, nativeFinalization,
334
+ });
335
+ args = built.args;
336
+ env = built.env;
337
+ tempDir = built.tempDir;
338
+ claudeCodeInvocation = built.claudeCodeInvocation;
339
+ }
340
+ catch (error) {
341
+ if (nativeFinalization)
342
+ cleanupTempDir(path.dirname(nativeFinalization.reportRuntime.schemaPath));
343
+ const message = error instanceof Error ? error.message : String(error);
344
+ return { stderr: message, exitCode: 1, messages: [], usage: emptyUsage(), durationMs: 0, observedCompletedMutation: false, model, error: message,
345
+ finalOutput: message, terminalFailure: true, resolvedOutput: { fullOutput: message } };
346
+ }
347
+ let run;
348
+ try {
349
+ run = await runPiStreaming({ args, cwd: step.cwd ?? ctx.cwd, env, agent: step.agent, model,
350
+ maxSubagentDepth: step.maxSubagentDepth, maxExecutionTimeMs: step.maxExecutionTimeMs, maxTokens: step.maxTokens,
351
+ interruptSignal, signal: ctx.signal, claudeCodeInvocation, sessionFile,
352
+ structuredOutput: structuredRuntime, reportRuntime: review?.reportRuntime, nativeFinalization,
353
+ onEvent: (event, result, mutation) => {
354
+ if (event.type === "tool_execution_start")
355
+ toolCount++;
356
+ if (event.type === "message_end" && event.message?.role === "assistant") {
357
+ toolCalls.push(...(compactForegroundResult({ agent: step.agent, task: step.task, exitCode: 0, usage: result.usage, messages: [event.message] }).toolCalls ?? []));
358
+ }
359
+ ctx.onChildEvent?.(event, mutation);
360
+ },
361
+ }, review ? `${ctx.outputFile}.finalization-${review.turn}.log` : ctx.outputFile, { eventsPath, runId: ctx.id, stepIndex: ctx.flatIndex, agent: step.agent });
362
+ }
363
+ finally {
364
+ cleanupTempDir(tempDir);
365
+ if (nativeFinalization)
366
+ cleanupTempDir(path.dirname(nativeFinalization.reportRuntime.schemaPath));
367
+ }
368
+ const initialSegment = nativeFinalization ? run.finalization?.[0] : undefined;
369
+ if (initialSegment) {
370
+ nativeExecution = run;
371
+ nativeSegments = run.finalization.slice(1);
372
+ run = nativeAttempt(initialSegment);
373
+ }
374
+ const reportSubmission = review?.reportRuntime ? readFinalizationReport(run.messages, review.reportRuntime, { structuredResult: Boolean(claudeCodeInvocation) }) : undefined;
375
+ const hiddenError = run.exitCode === 0 && !run.error && !reportSubmission?.output ? detectSubagentError(run.messages) : undefined;
376
+ let structuredOutput;
377
+ let structuredError;
378
+ if (!review && structuredRuntime && run.exitCode === 0 && !run.error && !hiddenError?.hasError && !run.interrupted) {
379
+ const structured = readStructuredOutput(structuredRuntime);
380
+ structuredError = structured.error;
381
+ structuredOutput = structured.value;
382
+ }
383
+ const completionGuardTriggered = !review && run.exitCode === 0 && !run.error && !hiddenError?.hasError && !run.interrupted
384
+ && resolveCompletionPolicy({ completionGuardEnabled: step.completionGuard === true, usesAcceptanceContract: step.effectiveAcceptance?.explicit === true }) === "mutation-guard"
385
+ && !run.observedCompletedMutation && !hasCompletedMutationToolCall(run.messages);
386
+ let error = completionGuardTriggered
387
+ ? "Subagent completed without making edits required by completionGuard: true.\nUse an acceptance contract when a valid no-op is allowed."
388
+ : structuredError ?? (hiddenError?.hasError
389
+ ? hiddenError.details ? `${hiddenError.errorType} failed (exit ${hiddenError.exitCode ?? 1}): ${hiddenError.details}` : `${hiddenError.errorType} failed with exit code ${hiddenError.exitCode ?? 1}`
390
+ : run.error || (run.exitCode !== 0 ? run.stderr.trim() || formatProcessExitFailure({ agent: step.agent, exitCode: run.exitCode, durationMs: run.durationMs }) : undefined));
391
+ let exitCode = completionGuardTriggered || structuredError ? 1 : hiddenError?.hasError ? hiddenError.exitCode ?? 1 : error && run.exitCode === 0 ? 1 : run.exitCode;
392
+ const finalOutput = reportSubmission?.output ?? run.finalOutput;
393
+ const fullOutput = review ? resolveFinalizationOutput(finalOutput, review.previousOutput) : stripAcceptanceReport(finalOutput);
394
+ const resolvedOutput = initialSegment ? initialSegment.event.resolvedOutput : step.outputPath && exitCode === 0 && !run.interrupted && !reportSubmission?.reportSubmissionError
395
+ ? resolveSingleOutput(step.outputPath, fullOutput, outputSnapshot)
396
+ : { fullOutput };
397
+ if (resolvedOutput.saveError) {
398
+ exitCode = 1;
399
+ error = `Failed to save output file '${step.outputPath}': ${resolvedOutput.saveError}`;
400
+ }
401
+ return { ...run, exitCode, error, model: model ?? run.model, structuredOutput, reportSubmission, finalOutput, resolvedOutput, completionGuardTriggered,
402
+ terminalFailure: Boolean(completionGuardTriggered || structuredError || hiddenError?.hasError || resolvedOutput.saveError) };
403
+ }
404
+ const { result: initial, modelAttempts, attemptedModels, notes: attemptNotes } = await runModelAttempts({
405
+ candidates: step.modelCandidates?.length ? step.modelCandidates : [step.model], signal: verificationSignal,
406
+ runAttempt: (model) => runAttempt(task, model),
407
+ });
408
+ for (const segment of nativeSegments) {
409
+ const attempt = nativeAttempt(segment);
410
+ modelAttempts.push({ model: attempt.model ?? "default", success: attempt.exitCode === 0 && !attempt.error && !attempt.interrupted,
411
+ exitCode: attempt.exitCode, error: attempt.error, accounting: attempt.accounting, usage: { ...attempt.usage } });
412
+ }
413
+ let execution = initial;
414
+ let structuredOutput = initial.structuredOutput;
415
+ let resolvedOutput = initial.resolvedOutput;
416
+ let output = stripAcceptanceReport(resolvedOutput.fullOutput);
417
+ const initialOutput = output;
418
+ const sessionFile = step.sessionFile ?? (sessionDir ? findLatestSessionFile(sessionDir) ?? undefined : undefined);
419
+ const nativeReport = !initial.model || !isClaudeCodeModel(initial.model);
420
+ const acceptance = step.effectiveAcceptance ? await evaluateRunAcceptance({
421
+ acceptance: step.effectiveAcceptance, initial, initialOutput: initial.finalOutput, sessionFile, cwd: step.cwd ?? ctx.cwd, signal: verificationSignal, nativeReport, outputSchema: effectiveStructuredOutput?.schema, recordedTurns: nativeSegments.length,
422
+ initialAcceptance: nativeExecution?.finalization?.[0]?.event.acceptance,
423
+ runTurn: async (prompt, turn, sessionFile) => {
424
+ const cached = nativeSegments[turn - 1];
425
+ const reportRuntime = !cached && (nativeReport || effectiveStructuredOutput) ? createFinalizationReportRuntime(effectiveStructuredOutput?.schema) : undefined;
426
+ let reviewed;
427
+ try {
428
+ reviewed = cached ? nativeAttempt(cached) : await runAttempt(prompt, initial.model ?? step.model, { turn, sessionFile, previousOutput: output, reportRuntime,
429
+ outputSnapshot: nativeReport ? resolvedOutput.writtenSnapshot : undefined });
430
+ }
431
+ finally {
432
+ if (reportRuntime)
433
+ cleanupTempDir(path.dirname(reportRuntime.schemaPath));
434
+ }
435
+ execution = reviewed;
436
+ if (!cached)
437
+ modelAttempts.push({ model: reviewed.model ?? "default", success: reviewed.exitCode === 0 && !reviewed.error && !reviewed.interrupted,
438
+ exitCode: reviewed.exitCode, error: reviewed.error, accounting: reviewed.accounting, usage: { ...reviewed.usage } });
439
+ if (reviewed.exitCode !== 0 || reviewed.error || reviewed.interrupted)
440
+ return { ...reviewed.reportSubmission, output: reviewed.finalOutput,
441
+ error: reviewed.error ?? reviewed.resourceLimitExceeded?.message ?? "Acceptance finalization turn did not complete successfully." };
442
+ if (reviewed.reportSubmission?.reportSubmissionError)
443
+ return reviewed.reportSubmission;
444
+ if (effectiveStructuredOutput && reviewed.reportSubmission?.structuredOutput !== undefined) {
445
+ structuredOutput = reviewed.reportSubmission.structuredOutput;
446
+ fs.writeFileSync(effectiveStructuredOutput.outputPath, JSON.stringify(structuredOutput), { mode: 0o600 });
447
+ }
448
+ resolvedOutput = reviewed.resolvedOutput;
449
+ output = stripAcceptanceReport(resolvedOutput.fullOutput);
450
+ return { ...reviewed.reportSubmission, output: reviewed.finalOutput, acceptance: cached?.event.acceptance };
451
+ },
452
+ }) : undefined;
453
+ const outcome = resolveExecutionOutcome({ result: execution, acceptance, signal: ctx.signal, interruptSignal });
454
+ const previousError = modelAttempts.slice(0, -1).reverse().find((attempt) => attempt.error)?.error;
455
+ if (outcome.exitCode !== 0 && outcome.error && previousError && execution.usage.turns === 0) {
456
+ const context = `Previous attempt before the empty retry failed with: ${previousError}`;
457
+ outcome.error += `\n${context}`;
458
+ output = output ? `${output}\n${context}` : outcome.error;
459
+ }
460
+ if (acceptance?.unconfirmedOutput !== undefined) {
461
+ const auditOutput = resolvedOutput.savedPath && !resolvedOutput.writtenSnapshot ? output : acceptance.unconfirmedOutput;
462
+ output = formatUnconfirmedFinalizationOutput(auditOutput);
463
+ }
464
+ if (outcome.timedOut) {
465
+ const reason = outcome.error ?? "Timed out.";
466
+ const partial = output.trim();
467
+ output = partial && partial !== reason ? `${reason}\n\nPartial output before timeout:\n${partial}` : reason;
468
+ }
469
+ const effectiveFinalExitCode = outcome.exitCode ?? 1;
470
+ const cleanup = effectiveFinalExitCode === 0 && !outcome.interrupted && resolvedOutput.savedPath && step.outputMode !== "file-only" && step.outputPathFromAgentDefault === true
471
+ ? cleanupSingleOutputFile(resolvedOutput.savedPath, output, undefined)
472
+ : undefined;
473
+ if (ctx.worktreePath && resolvedOutput.savedPath && (!cleanup || cleanup.action === "skipped")) {
474
+ const relative = path.relative(ctx.worktreePath, resolvedOutput.savedPath);
475
+ if (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) {
476
+ const savedPath = path.join(path.dirname(ctx.outputFile), "outputs", String(ctx.flatIndex), path.basename(resolvedOutput.savedPath));
477
+ fs.mkdirSync(path.dirname(savedPath), { recursive: true });
478
+ fs.copyFileSync(resolvedOutput.savedPath, savedPath);
479
+ resolvedOutput.savedPath = savedPath;
480
+ }
481
+ }
482
+ const outputReference = resolvedOutput.savedPath
483
+ ? cleanup ? formatConsumedOutputReference(resolvedOutput.savedPath, output, cleanup) : formatSavedOutputReference(resolvedOutput.savedPath, output)
484
+ : undefined;
485
+ const outputForSummary = finalizeSingleOutput({
486
+ fullOutput: attemptNotes.length ? `${attemptNotes.join("\n")}\n\n${output}`.trim() : output,
487
+ outputPath: step.outputPath, outputMode: step.outputMode, exitCode: effectiveFinalExitCode,
488
+ savedPath: resolvedOutput.savedPath, outputReference, saveError: resolvedOutput.saveError, cleanup,
489
+ }).displayOutput;
490
+ const usage = sumAttemptUsage(modelAttempts);
491
+ const progressSummary = { toolCount, tokens: usage.input + usage.output, durationMs: Date.now() - startedAt };
492
+ recordRun(step.agent, step.task, effectiveFinalExitCode, progressSummary.durationMs);
493
+ if (artifactPaths) {
494
+ fs.writeFileSync(artifactPaths.outputPath, output, "utf-8");
495
+ fs.writeFileSync(artifactPaths.metadataPath, JSON.stringify({
496
+ runId: ctx.id, agent: step.agent, task, exitCode: effectiveFinalExitCode, interrupted: outcome.interrupted, agentProcessExit: execution.agentProcessExit,
497
+ error: outcome.error, acceptance, initialOutput: acceptance?.finalization ? initialOutput : undefined, usage,
498
+ model: initial.model, attemptedModels: attemptedModels.length ? attemptedModels : undefined, modelAttempts,
499
+ resourceLimitExceeded: outcome.resourceLimitExceeded, skills: step.skills, timestamp: Date.now(),
500
+ }, null, 2), "utf-8");
501
+ }
502
+ const result = {
503
+ accounting: modelAttempts.find((attempt) => attempt.accounting?.state === "incomplete")?.accounting ?? execution.accounting,
504
+ nativeSessionId: execution.nativeSessionId, terminalLeafId: execution.terminalLeafId, terminalEntryId: execution.terminalEntryId,
505
+ auditPath: execution.auditPath, auditSaveError: execution.auditSaveError,
506
+ agent: step.agent, output: outputForSummary, exitCode: effectiveFinalExitCode, error: outcome.error, agentProcessExit: execution.agentProcessExit,
507
+ usage, timedOut: outcome.timedOut, task: step.task, skills: step.skills,
508
+ finalOutput: step.outputMode === "file-only" ? outputForSummary : output,
509
+ initialOutput: acceptance?.finalization ? initialOutput : undefined,
510
+ outputMode: step.outputMode ?? "inline", outputReference, outputCleanup: cleanup, outputSaveError: resolvedOutput.saveError,
511
+ savedOutputPath: cleanup && cleanup.action !== "skipped" ? undefined : resolvedOutput.savedPath,
512
+ toolCalls: toolCalls.length ? toolCalls : undefined, progressSummary,
513
+ sessionFile, intercomTarget: ctx.childIntercomTarget, model: initial.model,
514
+ attemptedModels: attemptedModels.length ? attemptedModels : undefined, modelAttempts, artifactPaths,
515
+ interrupted: outcome.interrupted, completionGuardTriggered: initial.completionGuardTriggered,
516
+ structuredOutput, structuredOutputPath: effectiveStructuredOutput?.outputPath,
517
+ structuredOutputSchemaPath: effectiveStructuredOutput?.schemaPath, acceptance, resourceLimitExceeded: outcome.resourceLimitExceeded,
518
+ };
519
+ saveQuestionContract(ctx.id, ctx.flatIndex, { result: { ...result, task: step.task, usage, finalOutput: result.finalOutput }, updatedAt: Date.now() });
520
+ return result;
521
+ }
522
+ function markParallelGroupSetupFailure(input) {
523
+ for (let taskIndex = 0; taskIndex < input.group.parallel.length; taskIndex++) {
524
+ const flatTaskIndex = input.groupStartFlatIndex + taskIndex;
525
+ input.statusPayload.steps[flatTaskIndex].status = "failed";
526
+ input.statusPayload.steps[flatTaskIndex].startedAt = input.failedAt;
527
+ input.statusPayload.steps[flatTaskIndex].endedAt = input.failedAt;
528
+ input.statusPayload.steps[flatTaskIndex].durationMs = 0;
529
+ input.statusPayload.steps[flatTaskIndex].exitCode = 1;
530
+ input.results.push({ agent: input.group.parallel[taskIndex].agent, output: input.setupError, success: false, exitCode: 1, sessionFile: input.group.parallel[taskIndex].sessionFile });
531
+ }
532
+ input.statusPayload.currentStep = input.groupStartFlatIndex;
533
+ input.statusPayload.lastUpdate = input.failedAt;
534
+ input.statusPayload.outputFile = path.join(input.asyncDir, `output-${input.groupStartFlatIndex}.log`);
535
+ writeAtomicJson(input.statusPath, input.statusPayload);
536
+ appendJsonl(input.eventsPath, JSON.stringify({
537
+ type: "subagent.parallel.completed",
538
+ ts: input.failedAt,
539
+ runId: input.runId,
540
+ stepIndex: input.stepIndex,
541
+ success: false,
542
+ }));
543
+ }
544
+ function markParallelGroupRunning(input) {
545
+ for (let taskIndex = 0; taskIndex < input.group.parallel.length; taskIndex++) {
546
+ const flatTaskIndex = input.groupStartFlatIndex + taskIndex;
547
+ input.statusPayload.steps[flatTaskIndex].status = "pending";
548
+ input.statusPayload.steps[flatTaskIndex].startedAt = undefined;
549
+ input.statusPayload.steps[flatTaskIndex].endedAt = undefined;
550
+ input.statusPayload.steps[flatTaskIndex].durationMs = undefined;
551
+ input.statusPayload.steps[flatTaskIndex].lastActivityAt = undefined;
552
+ input.statusPayload.steps[flatTaskIndex].activityState = undefined;
553
+ input.statusPayload.steps[flatTaskIndex].error = undefined;
554
+ }
555
+ input.statusPayload.currentStep = input.groupStartFlatIndex;
556
+ input.statusPayload.activityState = undefined;
557
+ input.statusPayload.lastActivityAt = input.groupStartTime;
558
+ input.statusPayload.lastUpdate = input.groupStartTime;
559
+ input.statusPayload.outputFile = path.join(input.asyncDir, `output-${input.groupStartFlatIndex}.log`);
560
+ writeAtomicJson(input.statusPath, input.statusPayload);
561
+ appendJsonl(input.eventsPath, JSON.stringify({
562
+ type: "subagent.parallel.started",
563
+ ts: input.groupStartTime,
564
+ runId: input.runId,
565
+ stepIndex: input.stepIndex,
566
+ agents: input.group.parallel.map((task) => task.agent),
567
+ count: input.group.parallel.length,
568
+ }));
569
+ }
570
+ function prepareParallelTaskRun(task, cwd, worktreeSetup, taskIndex) {
571
+ if (!worktreeSetup)
572
+ return { taskForRun: task, taskCwd: cwd };
573
+ return {
574
+ taskForRun: { ...task, cwd: undefined },
575
+ taskCwd: worktreeSetup.worktrees[taskIndex].agentCwd,
576
+ };
577
+ }
578
+ function formatRunnerWorktreeSummary(worktreeSetup, asyncDir, stepIndex, group) {
579
+ return formatParallelWorktreeSummary(worktreeSetup, path.join(asyncDir, "worktree-diffs", `step-${stepIndex}`), group.parallel.map((task) => task.agent));
580
+ }
581
+ function ensureParallelProgressFile(cwd, group) {
582
+ const progressPath = path.join(cwd, "progress.md");
583
+ if (!group.parallel.some((task) => task.task.includes(`Update progress at: ${progressPath}`)))
584
+ return;
585
+ writeInitialProgressFile(cwd);
586
+ }
587
+ function materializeDynamicOutputPath(input) {
588
+ if (!input.step.output || !input.step.outputPath)
589
+ return input.step;
590
+ const output = namespaceParallelOutput(input.step.output, input.step.agent, input.stepIndex, input.taskIndex);
591
+ if (!output)
592
+ return input.step;
593
+ const outputPath = path.resolve(input.chainDir, output);
594
+ const task = input.step.task.includes(input.step.outputPath)
595
+ ? input.step.task.split(input.step.outputPath).join(outputPath)
596
+ : injectSingleOutputInstruction(input.step.task, outputPath);
597
+ return { ...input.step, task, outputPath };
598
+ }
599
+ async function runSubagent(config) {
600
+ const { id, steps, resultPath, cwd, placeholder, taskIndex, totalTasks, maxOutput, artifactsDir } = config;
601
+ let previousOutput = "";
602
+ const outputs = {};
603
+ const renderTask = (template, item) => config.resultMode === "single" || config.resultMode === "parallel" ? template
604
+ : renderChainTask(template, { originalTask: config.originalTask, previousOutput, chainDir: config.chainDir, outputs, item }, placeholder);
605
+ const results = [];
606
+ const worktreeSummaries = [];
607
+ let setupCleanupWarning = "";
608
+ const overallStartTime = Date.now();
609
+ const shareEnabled = config.share === true;
610
+ const asyncDir = config.asyncDir;
611
+ const statusPath = path.join(asyncDir, "status.json");
612
+ const eventsPath = path.join(asyncDir, "events.jsonl");
613
+ const logPath = path.join(asyncDir, `subagent-log-${id}.md`);
614
+ const controlConfig = config.controlConfig ?? DEFAULT_CONTROL_CONFIG;
615
+ const cancellation = new AbortController();
616
+ const cancelRunner = () => cancellation.abort();
617
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"])
618
+ process.on(signal, cancelRunner);
619
+ const activeChildInterrupts = new Map();
620
+ const interruption = new AbortController();
621
+ let interrupted = false;
622
+ let currentActivityState;
623
+ let activityTimer;
624
+ let controlRequestTimer;
625
+ let latestSessionFile;
626
+ const parallelGroups = [];
627
+ const initialStatusSteps = [];
628
+ let flatStepCount = 0;
629
+ for (let stepIndex = 0; stepIndex < steps.length; stepIndex++) {
630
+ const step = steps[stepIndex];
631
+ if (isParallelGroup(step)) {
632
+ parallelGroups.push({ start: flatStepCount, count: step.parallel.length, stepIndex });
633
+ for (const task of step.parallel) {
634
+ initialStatusSteps.push({
635
+ agent: task.agent,
636
+ phase: task.phase,
637
+ label: task.label,
638
+ outputName: task.outputName,
639
+ structured: task.structured,
640
+ status: "pending",
641
+ ...(task.sessionFile ? { sessionFile: task.sessionFile } : {}),
642
+ skills: task.skills,
643
+ model: task.model,
644
+ thinking: task.thinking,
645
+ attemptedModels: task.modelCandidates && task.modelCandidates.length > 0 ? task.modelCandidates : task.model ? [task.model] : undefined,
646
+ recentTools: [],
647
+ recentOutput: [],
648
+ });
649
+ }
650
+ flatStepCount += step.parallel.length;
651
+ }
652
+ else if (isDynamicRunnerGroup(step)) {
653
+ parallelGroups.push({ start: flatStepCount, count: 1, stepIndex });
654
+ initialStatusSteps.push({
655
+ agent: `expand:${step.parallel.agent}`,
656
+ phase: step.phase ?? step.parallel.phase,
657
+ label: step.label ?? step.parallel.label ?? `Dynamic fanout (${step.collect.as})`,
658
+ outputName: step.collect.as,
659
+ structured: Boolean(step.collect.outputSchema),
660
+ status: "pending",
661
+ recentTools: [],
662
+ recentOutput: [],
663
+ });
664
+ flatStepCount++;
665
+ }
666
+ else {
667
+ initialStatusSteps.push({
668
+ agent: step.agent,
669
+ phase: step.phase,
670
+ label: step.label,
671
+ outputName: step.outputName,
672
+ structured: step.structured,
673
+ status: "pending",
674
+ ...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
675
+ skills: step.skills,
676
+ model: step.model,
677
+ thinking: step.thinking,
678
+ attemptedModels: step.modelCandidates && step.modelCandidates.length > 0 ? step.modelCandidates : step.model ? [step.model] : undefined,
679
+ recentTools: [],
680
+ recentOutput: [],
681
+ });
682
+ flatStepCount++;
683
+ }
684
+ }
685
+ const flatSteps = flattenSteps(steps);
686
+ const sessionEnabled = Boolean(config.sessionDir)
687
+ || shareEnabled
688
+ || flatSteps.some((step) => Boolean(step.sessionFile));
689
+ const statusPayload = {
690
+ runId: id,
691
+ runtimeVersion: config.runtimeVersion,
692
+ indexedControl: true,
693
+ controlRequestFiles: true,
694
+ ...(config.sessionId ? { sessionId: config.sessionId } : {}),
695
+ mode: config.resultMode ?? (flatSteps.length > 1 ? "chain" : "single"),
696
+ state: "running",
697
+ lastActivityAt: overallStartTime,
698
+ startedAt: overallStartTime,
699
+ lastUpdate: overallStartTime,
700
+ pid: process.pid,
701
+ cwd,
702
+ currentStep: 0,
703
+ chainStepCount: steps.length,
704
+ parallelGroups,
705
+ workflowGraph: config.workflowGraph,
706
+ steps: initialStatusSteps,
707
+ artifactsDir,
708
+ sessionDir: config.sessionDir,
709
+ outputFile: path.join(asyncDir, "output-0.log"),
710
+ };
711
+ fs.mkdirSync(asyncDir, { recursive: true });
712
+ writeAtomicJson(statusPath, statusPayload);
713
+ if (config.runtimeVersion !== 2)
714
+ saveRunStatus(id, statusPayload);
715
+ const emitNestedSelfEvent = (type) => {
716
+ if (!config.nestedRoute || !config.nestedSelf)
717
+ return;
718
+ try {
719
+ writeNestedEvent(config.nestedRoute, {
720
+ type,
721
+ ts: Date.now(),
722
+ parentRunId: config.nestedSelf.parentRunId,
723
+ parentStepIndex: config.nestedSelf.parentStepIndex,
724
+ child: nestedSummaryFromAsyncStatus(statusPayload, asyncDir, {
725
+ id,
726
+ parentRunId: config.nestedSelf.parentRunId,
727
+ parentStepIndex: config.nestedSelf.parentStepIndex,
728
+ depth: config.nestedSelf.depth,
729
+ path: config.nestedSelf.path,
730
+ mode: statusPayload.mode,
731
+ ts: Date.now(),
732
+ }),
733
+ });
734
+ }
735
+ catch (error) {
736
+ console.error("Failed to emit nested async status event:", error);
737
+ }
738
+ };
739
+ const refreshWorkflowGraph = () => {
740
+ if (!config.workflowGraph)
741
+ return;
742
+ const graph = structuredClone(statusPayload.workflowGraph ?? config.workflowGraph);
743
+ const normalize = (status) => {
744
+ if (status === "complete" || status === "completed")
745
+ return "completed";
746
+ if (status === "running" || status === "failed" || status === "blocked" || status === "paused" || status === "pending")
747
+ return status;
748
+ return "pending";
749
+ };
750
+ const updateNode = (node) => {
751
+ if (node.flatIndex !== undefined) {
752
+ const step = statusPayload.steps[node.flatIndex];
753
+ if (step) {
754
+ node.status = normalize(step.status);
755
+ node.error = step.error;
756
+ node.acceptanceStatus = step.acceptance?.status;
757
+ }
758
+ if (statusPayload.currentStep === node.flatIndex)
759
+ graph.currentNodeId = node.id;
760
+ }
761
+ for (const child of node.children ?? [])
762
+ updateNode(child);
763
+ if (node.children?.length) {
764
+ if (node.children.every((child) => child.status === "completed"))
765
+ node.status = "completed";
766
+ else if (node.children.some((child) => child.status === "running"))
767
+ node.status = "running";
768
+ else if (node.children.some((child) => child.status === "failed"))
769
+ node.status = "failed";
770
+ else if (node.children.some((child) => child.status === "blocked"))
771
+ node.status = "blocked";
772
+ else if (node.children.some((child) => child.status === "paused"))
773
+ node.status = "paused";
774
+ }
775
+ if (node.error)
776
+ node.status = "failed";
777
+ };
778
+ for (const node of graph.nodes)
779
+ updateNode(node);
780
+ statusPayload.workflowGraph = graph;
781
+ };
782
+ let statusWriteTimer;
783
+ const writeStatusPayload = () => {
784
+ if (statusWriteTimer) {
785
+ clearTimeout(statusWriteTimer);
786
+ statusWriteTimer = undefined;
787
+ }
788
+ refreshWorkflowGraph();
789
+ writeAtomicJson(statusPath, statusPayload);
790
+ if (config.runtimeVersion !== 2)
791
+ saveRunStatus(id, statusPayload);
792
+ emitNestedSelfEvent(statusPayload.state === "running" || statusPayload.state === "queued" ? "subagent.nested.updated" : "subagent.nested.completed");
793
+ };
794
+ const scheduleStatusWrite = () => {
795
+ if (statusWriteTimer)
796
+ return;
797
+ statusWriteTimer = setTimeout(writeStatusPayload, 200);
798
+ statusWriteTimer.unref?.();
799
+ };
800
+ let deadlineTimer;
801
+ statusPayload.timeoutAt = config.timeoutMs !== undefined ? overallStartTime + config.timeoutMs : undefined;
802
+ const scheduleDeadline = () => {
803
+ clearTimeout(deadlineTimer);
804
+ if (statusPayload.timeoutAt === undefined || cancellation.signal.aborted)
805
+ return;
806
+ const expire = () => {
807
+ statusPayload.timedOut = true;
808
+ statusPayload.error = `Timed out after ${statusPayload.timeoutAt - overallStartTime}ms.`;
809
+ cancellation.abort(new DOMException(statusPayload.error, "TimeoutError"));
810
+ writeStatusPayload();
811
+ };
812
+ const remaining = statusPayload.timeoutAt - Date.now();
813
+ if (remaining <= 0)
814
+ expire();
815
+ else {
816
+ deadlineTimer = setTimeout(expire, remaining);
817
+ deadlineTimer.unref();
818
+ }
819
+ };
820
+ scheduleDeadline();
821
+ writeStatusPayload();
822
+ const markDynamicGraphGroup = (stepIndex, status, error, acceptance) => {
823
+ const groupNode = statusPayload.workflowGraph?.nodes.find((node) => node.id === `step-${stepIndex}`);
824
+ if (!groupNode)
825
+ return;
826
+ groupNode.status = status;
827
+ groupNode.error = error;
828
+ groupNode.acceptanceStatus = acceptance?.status ?? groupNode.acceptanceStatus;
829
+ };
830
+ const refreshUsageTotals = () => {
831
+ statusPayload.totalTokens = statusPayload.steps.reduce((total, step) => ({
832
+ input: total.input + (step.tokens?.input ?? 0), output: total.output + (step.tokens?.output ?? 0), total: total.total + (step.tokens?.total ?? 0),
833
+ }), { input: 0, output: 0, total: 0 });
834
+ };
835
+ const stepOutputActivityAt = (index) => {
836
+ const step = statusPayload.steps[index];
837
+ let lastActivityAt = step?.lastActivityAt ?? step?.startedAt ?? overallStartTime;
838
+ const outputPath = path.join(asyncDir, `output-${index}.log`);
839
+ try {
840
+ lastActivityAt = Math.max(lastActivityAt, fs.statSync(outputPath).mtimeMs);
841
+ }
842
+ catch (error) {
843
+ if (error.code !== "ENOENT") {
844
+ console.error(`Failed to inspect async output file '${outputPath}':`, error);
845
+ }
846
+ }
847
+ return lastActivityAt;
848
+ };
849
+ const childSafeControls = Boolean(config.nestedSelf) || (process.env[SUBAGENT_CHILD_ENV] === "1" && process.env[SUBAGENT_FANOUT_CHILD_ENV] === "1");
850
+ const emittedControlEventKeys = new Set();
851
+ const mutatingFailureStates = initialStatusSteps.map(() => createMutatingFailureState());
852
+ const mutatingFailureWindowMs = 5 * 60_000;
853
+ const appendControlEvent = (event) => {
854
+ if (!controlConfig.enabled)
855
+ return;
856
+ const childIntercomTarget = config.childIntercomTargets?.[event.index ?? statusPayload.currentStep];
857
+ const channels = controlConfig.notifyChannels;
858
+ if (channels.length === 0 || !claimControlNotification(controlConfig, event, emittedControlEventKeys, childIntercomTarget))
859
+ return;
860
+ appendJsonl(eventsPath, JSON.stringify({
861
+ type: "subagent.control",
862
+ event,
863
+ channels,
864
+ childIntercomTarget,
865
+ noticeText: formatControlNoticeMessage(event, childIntercomTarget, childSafeControls),
866
+ ...(config.controlIntercomTarget && channels.includes("intercom") ? {
867
+ intercom: {
868
+ to: config.controlIntercomTarget,
869
+ message: formatControlIntercomMessage(event, childIntercomTarget, childSafeControls),
870
+ },
871
+ } : {}),
872
+ }));
873
+ };
874
+ const syncTopLevelCurrentTool = () => {
875
+ const activeStep = statusPayload.steps
876
+ .filter((step) => step.status === "running" && typeof step.currentTool === "string" && step.currentTool.length > 0)
877
+ .sort((left, right) => (right.currentToolStartedAt ?? 0) - (left.currentToolStartedAt ?? 0))[0];
878
+ statusPayload.currentTool = activeStep?.currentTool;
879
+ statusPayload.currentToolStartedAt = activeStep?.currentToolStartedAt;
880
+ statusPayload.currentPath = activeStep?.currentPath;
881
+ };
882
+ const updateStepModel = (flatIndex, model, thinking, now = Date.now()) => {
883
+ const step = statusPayload.steps[flatIndex];
884
+ if (!step)
885
+ return;
886
+ step.model = model;
887
+ step.thinking = thinking;
888
+ step.modelStartedAt = now;
889
+ statusPayload.lastUpdate = now;
890
+ writeStatusPayload();
891
+ };
892
+ const clearControlNotificationKeys = (flatIndex) => {
893
+ const childKey = config.childIntercomTargets?.[flatIndex] ?? `${config.id}:${flatIndex}`;
894
+ for (const key of emittedControlEventKeys)
895
+ if (key.startsWith(`${childKey}:`))
896
+ emittedControlEventKeys.delete(key);
897
+ };
898
+ const updateStepFromChildEvent = (flatIndex, event, toolSnapshot) => {
899
+ const step = statusPayload.steps[flatIndex];
900
+ if (!step)
901
+ return;
902
+ const now = Date.now();
903
+ statusPayload.currentStep = flatIndex;
904
+ if (step.activityState === "needs_attention") {
905
+ step.activityState = undefined;
906
+ clearControlNotificationKeys(flatIndex);
907
+ statusPayload.activityState = statusPayload.steps.some((candidate) => candidate.activityState === "needs_attention")
908
+ ? "needs_attention"
909
+ : undefined;
910
+ }
911
+ step.streamingText = updateStreamingText(step.streamingText, event);
912
+ if (event.type === "tool_execution_start" && event.toolName) {
913
+ const currentPath = resolveCurrentPath(event.toolName, event.args);
914
+ step.toolCount = (step.toolCount ?? 0) + 1;
915
+ step.currentTool = event.toolName;
916
+ step.currentToolArgs = extractToolArgsPreview(event.args ?? {});
917
+ step.currentToolStartedAt = now;
918
+ step.currentPath = currentPath;
919
+ statusPayload.toolCount = (statusPayload.toolCount ?? 0) + 1;
920
+ syncTopLevelCurrentTool();
921
+ }
922
+ else if (event.type === "tool_execution_end") {
923
+ if (step.currentTool) {
924
+ step.recentTools ??= [];
925
+ step.recentTools.push({ tool: step.currentTool, args: step.currentToolArgs || "", endMs: now });
926
+ }
927
+ step.currentTool = undefined;
928
+ step.currentToolArgs = undefined;
929
+ step.currentToolStartedAt = undefined;
930
+ step.currentPath = undefined;
931
+ syncTopLevelCurrentTool();
932
+ }
933
+ else if (event.type === "message_end" && event.message?.role === "toolResult") {
934
+ const resultText = extractTextFromContent(event.message.content);
935
+ appendRecentStepOutput(step, resultText.split("\n").slice(-10));
936
+ if (toolSnapshot?.mutates && toolSnapshot.errored) {
937
+ const state = mutatingFailureStates[flatIndex];
938
+ recordMutatingFailure(state, {
939
+ tool: toolSnapshot.tool,
940
+ path: toolSnapshot.path,
941
+ error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
942
+ ts: now,
943
+ }, mutatingFailureWindowMs);
944
+ if (controlConfig.enabled && shouldEscalateMutatingFailures(state, controlConfig.failedToolAttemptsBeforeAttention) && step.activityState !== "needs_attention") {
945
+ const previous = step.activityState;
946
+ step.activityState = "needs_attention";
947
+ statusPayload.activityState = "needs_attention";
948
+ appendControlEvent(buildControlEvent({
949
+ type: "needs_attention",
950
+ from: previous,
951
+ to: "needs_attention",
952
+ runId: id,
953
+ agent: step.agent,
954
+ index: flatIndex,
955
+ ts: now,
956
+ message: `${step.agent} needs attention after repeated mutating tool failures`,
957
+ reason: "tool_failures",
958
+ turns: step.turnCount,
959
+ tokens: step.tokens?.total,
960
+ toolCount: step.toolCount,
961
+ currentTool: toolSnapshot.tool,
962
+ currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
963
+ currentPath: toolSnapshot.path,
964
+ recentFailureSummary: summarizeRecentMutatingFailures(state),
965
+ }));
966
+ }
967
+ }
968
+ else if (toolSnapshot?.mutates) {
969
+ resetMutatingFailureState(mutatingFailureStates[flatIndex]);
970
+ }
971
+ }
972
+ else if (event.type === "message_end" && event.message?.role === "assistant") {
973
+ appendRecentStepOutput(step, stripAcceptanceReport(extractTextFromContent(event.message.content)).split("\n").slice(-10));
974
+ step.turnCount = (step.turnCount ?? 0) + 1;
975
+ const usage = event.message.usage;
976
+ if (usage) {
977
+ const input = usage.input ?? 0;
978
+ const output = usage.output ?? 0;
979
+ const previousInput = step.tokens?.input ?? 0;
980
+ const previousOutput = step.tokens?.output ?? 0;
981
+ step.tokens = { input: previousInput + input, output: previousOutput + output, total: previousInput + previousOutput + input + output };
982
+ const totalInput = statusPayload.totalTokens?.input ?? 0;
983
+ const totalOutput = statusPayload.totalTokens?.output ?? 0;
984
+ statusPayload.totalTokens = { input: totalInput + input, output: totalOutput + output, total: totalInput + totalOutput + input + output };
985
+ }
986
+ statusPayload.turnCount = Math.max(statusPayload.turnCount ?? 0, step.turnCount);
987
+ }
988
+ syncTopLevelCurrentTool();
989
+ step.lastActivityAt = now;
990
+ statusPayload.lastActivityAt = now;
991
+ statusPayload.lastUpdate = now;
992
+ scheduleStatusWrite();
993
+ };
994
+ const updateRunnerActivityState = (now) => {
995
+ if (!controlConfig.enabled)
996
+ return false;
997
+ let changed = false;
998
+ let runLastActivityAt = statusPayload.lastActivityAt ?? overallStartTime;
999
+ for (let index = 0; index < statusPayload.steps.length; index++) {
1000
+ const step = statusPayload.steps[index];
1001
+ if (step.status !== "running")
1002
+ continue;
1003
+ const lastActivityAt = stepOutputActivityAt(index);
1004
+ runLastActivityAt = Math.max(runLastActivityAt, lastActivityAt);
1005
+ if (step.lastActivityAt !== lastActivityAt) {
1006
+ step.lastActivityAt = lastActivityAt;
1007
+ changed = true;
1008
+ }
1009
+ const idleState = deriveActivityState({
1010
+ config: controlConfig,
1011
+ startedAt: step.startedAt ?? overallStartTime,
1012
+ lastActivityAt,
1013
+ now,
1014
+ });
1015
+ if (idleState === "needs_attention") {
1016
+ const previous = step.activityState;
1017
+ step.activityState = "needs_attention";
1018
+ if (previous !== "needs_attention") {
1019
+ appendControlEvent(buildControlEvent({
1020
+ from: previous,
1021
+ to: "needs_attention",
1022
+ runId: id,
1023
+ agent: step.agent,
1024
+ index,
1025
+ ts: now,
1026
+ lastActivityAt,
1027
+ currentTool: step.currentTool,
1028
+ currentToolDurationMs: step.currentToolStartedAt !== undefined ? Math.max(0, now - step.currentToolStartedAt) : undefined,
1029
+ supervisorQuestion: pendingSupervisorQuestion({ runId: id, agent: step.agent, index, sessionFile: step.sessionFile }),
1030
+ }));
1031
+ changed = true;
1032
+ }
1033
+ }
1034
+ else if (step.activityState === "needs_attention") {
1035
+ step.activityState = undefined;
1036
+ clearControlNotificationKeys(index);
1037
+ changed = true;
1038
+ }
1039
+ }
1040
+ if (statusPayload.lastActivityAt !== runLastActivityAt) {
1041
+ statusPayload.lastActivityAt = runLastActivityAt;
1042
+ changed = true;
1043
+ }
1044
+ const nextRunState = statusPayload.steps.some((step) => step.activityState === "needs_attention")
1045
+ ? "needs_attention"
1046
+ : undefined;
1047
+ if (nextRunState !== currentActivityState) {
1048
+ currentActivityState = nextRunState;
1049
+ statusPayload.activityState = nextRunState;
1050
+ changed = true;
1051
+ }
1052
+ statusPayload.lastUpdate = now;
1053
+ if (changed)
1054
+ writeStatusPayload();
1055
+ return changed;
1056
+ };
1057
+ if (controlConfig.enabled) {
1058
+ activityTimer = setInterval(() => {
1059
+ if (statusPayload.state !== "running")
1060
+ return;
1061
+ const now = Date.now();
1062
+ updateRunnerActivityState(now);
1063
+ }, 1000);
1064
+ activityTimer.unref?.();
1065
+ }
1066
+ const interruptRunner = () => {
1067
+ if (interrupted || statusPayload.state !== "running")
1068
+ return;
1069
+ interrupted = true;
1070
+ interruption.abort();
1071
+ const now = Date.now();
1072
+ currentActivityState = undefined;
1073
+ statusPayload.activityState = undefined;
1074
+ statusPayload.lastUpdate = now;
1075
+ writeStatusPayload();
1076
+ appendJsonl(eventsPath, JSON.stringify({
1077
+ type: "subagent.run.stop-requested",
1078
+ ts: now,
1079
+ runId: id,
1080
+ }));
1081
+ for (const interrupt of activeChildInterrupts.values())
1082
+ interrupt();
1083
+ };
1084
+ process.on(ASYNC_INTERRUPT_SIGNAL, interruptRunner);
1085
+ controlRequestTimer = setInterval(() => {
1086
+ for (const request of readAsyncControlRequests(asyncDir, id)) {
1087
+ if (request.action === "extend") {
1088
+ if (statusPayload.timeoutAt === undefined || cancellation.signal.aborted || interrupted)
1089
+ continue;
1090
+ statusPayload.timeoutAt = Math.max(statusPayload.timeoutAt, Date.now()) + request.extendMs;
1091
+ scheduleDeadline();
1092
+ writeStatusPayload();
1093
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.run.extended", requestId: request.requestId, runId: id, ts: Date.now(), timeoutAt: statusPayload.timeoutAt }));
1094
+ }
1095
+ else if (request.action === "cancel")
1096
+ cancellation.abort();
1097
+ else if (request.index === undefined)
1098
+ interruptRunner();
1099
+ else
1100
+ activeChildInterrupts.get(request.index)?.();
1101
+ }
1102
+ }, 100);
1103
+ controlRequestTimer.unref?.();
1104
+ appendJsonl(eventsPath, JSON.stringify({
1105
+ type: "subagent.run.started",
1106
+ ts: overallStartTime,
1107
+ runId: id,
1108
+ mode: statusPayload.mode,
1109
+ cwd,
1110
+ pid: process.pid,
1111
+ }));
1112
+ const stoppedParallelChild = (task, index, reason) => {
1113
+ const now = Date.now();
1114
+ const step = statusPayload.steps[index];
1115
+ const paused = reason === "interrupted";
1116
+ const error = `Skipped due to ${reason}`;
1117
+ const exitCode = paused ? 0 : -1;
1118
+ if (paused)
1119
+ markStepPaused(step, now);
1120
+ else
1121
+ Object.assign(step, { status: "failed", error, startedAt: now, endedAt: now, durationMs: 0, exitCode });
1122
+ statusPayload.lastUpdate = now;
1123
+ writeStatusPayload();
1124
+ appendJsonl(eventsPath, JSON.stringify({ type: paused ? "subagent.step.paused" : "subagent.step.failed", ts: now, runId: id, stepIndex: index, agent: task.agent, exitCode, interrupted: paused, durationMs: 0 }));
1125
+ return { agent: task.agent, output: error, error, exitCode, interrupted: paused, skipped: true };
1126
+ };
1127
+ const runParallelChild = async (input) => {
1128
+ const { task, flatIndex: fi } = input;
1129
+ const taskStartTime = Date.now();
1130
+ const statusStep = statusPayload.steps[fi];
1131
+ statusPayload.currentStep = fi;
1132
+ statusStep.status = "running";
1133
+ statusStep.error = undefined;
1134
+ statusStep.activityState = undefined;
1135
+ resetStepLiveDetail(statusStep);
1136
+ statusStep.startedAt = taskStartTime;
1137
+ if (input.resetTiming) {
1138
+ statusStep.endedAt = undefined;
1139
+ statusStep.durationMs = undefined;
1140
+ }
1141
+ statusStep.lastActivityAt = taskStartTime;
1142
+ statusPayload.outputFile = path.join(asyncDir, `output-${fi}.log`);
1143
+ statusPayload.lastActivityAt = taskStartTime;
1144
+ statusPayload.lastUpdate = taskStartTime;
1145
+ writeStatusPayload();
1146
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.step.started", ts: taskStartTime, runId: id, stepIndex: fi, agent: task.agent }));
1147
+ const singleResult = await runSingleStep({ ...task, task: renderTask(task.task, input.item) }, {
1148
+ nativeFinalization: config.runtimeVersion === 2,
1149
+ worktreePath: input.worktreePath,
1150
+ cwd: input.taskCwd, sessionEnabled,
1151
+ sessionDir: input.sessionDir,
1152
+ artifactsDir, id,
1153
+ flatIndex: fi, flatStepCount: input.flatStepCount,
1154
+ outputFile: path.join(asyncDir, `output-${fi}.log`),
1155
+ childIntercomTarget: config.childIntercomTargets?.[fi],
1156
+ orchestratorIntercomTarget: config.childIntercomTargets?.[fi] ? config.controlIntercomTarget : undefined,
1157
+ nestedRoute: config.nestedRoute,
1158
+ projectTrust: config.projectTrust,
1159
+ rootSessionId: config.rootSessionId,
1160
+ signal: cancellation.signal,
1161
+ interruptSignal: input.interruptSignal,
1162
+ registerInterrupt: (interrupt) => {
1163
+ if (interrupt)
1164
+ activeChildInterrupts.set(fi, interrupt);
1165
+ else
1166
+ activeChildInterrupts.delete(fi);
1167
+ },
1168
+ onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking),
1169
+ onChildEvent: (event, mutation) => updateStepFromChildEvent(fi, event, mutation),
1170
+ });
1171
+ activeChildInterrupts.delete(fi);
1172
+ if (input.trackSession && task.sessionFile)
1173
+ latestSessionFile = task.sessionFile;
1174
+ const taskEndTime = Date.now();
1175
+ statusStep.status = singleResult.interrupted ? "paused" : singleResult.exitCode === 0 ? singleResult.acceptance?.status === "blocked" ? "blocked" : "complete" : "failed";
1176
+ clearStepCurrentActivity(statusStep);
1177
+ statusStep.endedAt = taskEndTime;
1178
+ statusStep.durationMs = taskEndTime - taskStartTime;
1179
+ statusStep.exitCode = singleResult.exitCode;
1180
+ statusStep.agentProcessExit = singleResult.agentProcessExit;
1181
+ statusStep.model = singleResult.model;
1182
+ statusStep.thinking = resolveEffectiveThinking(singleResult.model, statusStep.thinking);
1183
+ statusStep.attemptedModels = singleResult.attemptedModels;
1184
+ statusStep.modelAttempts = singleResult.modelAttempts;
1185
+ statusStep.tokens = tokenUsageFromAttempts(singleResult.modelAttempts) ?? undefined;
1186
+ refreshUsageTotals();
1187
+ statusStep.error = singleResult.error;
1188
+ statusStep.structuredOutput = singleResult.structuredOutput;
1189
+ statusStep.structuredOutputPath = singleResult.structuredOutputPath;
1190
+ statusStep.structuredOutputSchemaPath = singleResult.structuredOutputSchemaPath;
1191
+ statusStep.acceptance = singleResult.acceptance;
1192
+ statusStep.resourceLimitExceeded = singleResult.resourceLimitExceeded;
1193
+ statusPayload.lastUpdate = taskEndTime;
1194
+ writeStatusPayload();
1195
+ appendJsonl(eventsPath, JSON.stringify({
1196
+ type: singleResult.interrupted ? "subagent.step.paused" : singleResult.exitCode !== 0 ? "subagent.step.failed" : singleResult.acceptance?.status === "blocked" ? "subagent.step.blocked" : "subagent.step.completed",
1197
+ ts: taskEndTime, runId: id, stepIndex: fi, agent: task.agent,
1198
+ exitCode: singleResult.exitCode, durationMs: taskEndTime - taskStartTime,
1199
+ interrupted: singleResult.interrupted, agentProcessExit: singleResult.agentProcessExit,
1200
+ resourceLimitExceeded: singleResult.resourceLimitExceeded,
1201
+ }));
1202
+ if (input.notifyCompletionGuard && singleResult.completionGuardTriggered) {
1203
+ appendControlEvent(buildControlEvent({
1204
+ from: statusStep.activityState,
1205
+ to: "needs_attention",
1206
+ runId: id,
1207
+ agent: task.agent,
1208
+ index: fi,
1209
+ ts: taskEndTime,
1210
+ message: `${task.agent} completed without making edits for an implementation task`,
1211
+ reason: "completion_guard",
1212
+ }));
1213
+ }
1214
+ return { ...singleResult, skipped: false };
1215
+ };
1216
+ let flatIndex = 0;
1217
+ let workflowComplete = false;
1218
+ for (let stepIndex = 0; stepIndex < steps.length; stepIndex++) {
1219
+ if (interrupted || cancellation.signal.aborted)
1220
+ break;
1221
+ const step = steps[stepIndex];
1222
+ if (isDynamicRunnerGroup(step)) {
1223
+ const groupStartFlatIndex = flatIndex;
1224
+ let materialized;
1225
+ try {
1226
+ materialized = materializeDynamicParallelStep(step, outputs, stepIndex, { maxItems: config.dynamicFanoutMaxItems, allowRunnerFields: true });
1227
+ }
1228
+ catch (error) {
1229
+ const now = Date.now();
1230
+ const message = error instanceof DynamicFanoutError ? error.message : error instanceof Error ? error.message : String(error);
1231
+ statusPayload.state = "failed";
1232
+ statusPayload.error = message;
1233
+ statusPayload.currentStep = flatIndex;
1234
+ const placeholder = statusPayload.steps[groupStartFlatIndex];
1235
+ if (placeholder) {
1236
+ placeholder.status = "failed";
1237
+ placeholder.error = message;
1238
+ placeholder.startedAt = now;
1239
+ placeholder.endedAt = now;
1240
+ placeholder.durationMs = 0;
1241
+ placeholder.exitCode = 1;
1242
+ }
1243
+ statusPayload.lastUpdate = now;
1244
+ markDynamicGraphGroup(stepIndex, "failed", message);
1245
+ writeStatusPayload();
1246
+ break;
1247
+ }
1248
+ const dynamicSteps = materialized.parallel.map((task, itemIndex) => materializeDynamicOutputPath({
1249
+ step: {
1250
+ ...step.parallel,
1251
+ label: task.label ?? step.parallel.label,
1252
+ sessionFile: step.sessionFiles?.[itemIndex],
1253
+ structuredOutput: undefined,
1254
+ structuredOutputSchema: step.parallel.structuredOutputSchema ?? step.parallel.structuredOutput?.schema,
1255
+ },
1256
+ chainDir: config.chainDir ?? cwd,
1257
+ stepIndex,
1258
+ taskIndex: itemIndex,
1259
+ }));
1260
+ const duplicateOutputError = findDuplicateOutputPath(dynamicSteps);
1261
+ if (duplicateOutputError) {
1262
+ const now = Date.now();
1263
+ statusPayload.state = "failed";
1264
+ statusPayload.error = duplicateOutputError;
1265
+ statusPayload.currentStep = flatIndex;
1266
+ const placeholderStep = statusPayload.steps[groupStartFlatIndex];
1267
+ if (placeholderStep) {
1268
+ placeholderStep.status = "failed";
1269
+ placeholderStep.error = duplicateOutputError;
1270
+ placeholderStep.startedAt = now;
1271
+ placeholderStep.endedAt = now;
1272
+ placeholderStep.durationMs = 0;
1273
+ placeholderStep.exitCode = 1;
1274
+ }
1275
+ statusPayload.lastUpdate = now;
1276
+ markDynamicGraphGroup(stepIndex, "failed", duplicateOutputError);
1277
+ writeStatusPayload();
1278
+ break;
1279
+ }
1280
+ const dynamicStatusSteps = dynamicSteps.map((task) => ({
1281
+ agent: task.agent,
1282
+ phase: task.phase ?? step.phase,
1283
+ label: task.label,
1284
+ outputName: undefined,
1285
+ structured: Boolean(task.structuredOutputSchema),
1286
+ status: "pending",
1287
+ ...(task.sessionFile ? { sessionFile: task.sessionFile } : {}),
1288
+ skills: task.skills,
1289
+ model: task.model,
1290
+ thinking: task.thinking,
1291
+ attemptedModels: task.modelCandidates && task.modelCandidates.length > 0 ? task.modelCandidates : task.model ? [task.model] : undefined,
1292
+ recentTools: [],
1293
+ recentOutput: [],
1294
+ }));
1295
+ const previousChildIntercomTargets = config.childIntercomTargets;
1296
+ statusPayload.steps.splice(groupStartFlatIndex, 1, ...dynamicStatusSteps);
1297
+ if (previousChildIntercomTargets) {
1298
+ const dynamicGroupUsesIntercom = previousChildIntercomTargets[groupStartFlatIndex] !== undefined;
1299
+ config.childIntercomTargets = statusPayload.steps.map((statusStep, index) => {
1300
+ if (index >= groupStartFlatIndex && index < groupStartFlatIndex + dynamicStatusSteps.length) {
1301
+ return dynamicGroupUsesIntercom ? resolveSubagentIntercomTarget(id, statusStep.agent, index) : undefined;
1302
+ }
1303
+ const previousIndex = index < groupStartFlatIndex ? index : index - (dynamicStatusSteps.length - 1);
1304
+ return previousChildIntercomTargets[previousIndex] !== undefined
1305
+ ? resolveSubagentIntercomTarget(id, statusStep.agent, index)
1306
+ : undefined;
1307
+ });
1308
+ }
1309
+ mutatingFailureStates.splice(groupStartFlatIndex, 1, ...dynamicStatusSteps.map(() => createMutatingFailureState()));
1310
+ const materializedDelta = dynamicStatusSteps.length - 1;
1311
+ for (const group of statusPayload.parallelGroups) {
1312
+ if (group.stepIndex === stepIndex) {
1313
+ group.start = groupStartFlatIndex;
1314
+ group.count = dynamicStatusSteps.length;
1315
+ }
1316
+ else if (group.stepIndex > stepIndex) {
1317
+ group.start += materializedDelta;
1318
+ }
1319
+ }
1320
+ if (statusPayload.workflowGraph) {
1321
+ const shiftFlatIndexes = (nodes) => {
1322
+ for (const node of nodes) {
1323
+ if (node.stepIndex !== undefined && node.stepIndex > stepIndex && node.flatIndex !== undefined && node.flatIndex >= groupStartFlatIndex) {
1324
+ node.flatIndex += dynamicStatusSteps.length;
1325
+ }
1326
+ if (node.children)
1327
+ shiftFlatIndexes(node.children);
1328
+ }
1329
+ };
1330
+ shiftFlatIndexes(statusPayload.workflowGraph.nodes);
1331
+ const groupNode = statusPayload.workflowGraph.nodes.find((node) => node.id === `step-${stepIndex}`);
1332
+ if (groupNode) {
1333
+ groupNode.children = materialized.items.map((item, itemIndex) => ({
1334
+ id: `step-${stepIndex}-item-${item.idKey}`,
1335
+ kind: "agent",
1336
+ agent: step.parallel.agent,
1337
+ phase: dynamicSteps[itemIndex]?.phase ?? step.phase,
1338
+ label: dynamicSteps[itemIndex]?.label?.trim() || `${step.parallel.agent} ${item.key}`,
1339
+ status: "pending",
1340
+ flatIndex: groupStartFlatIndex + itemIndex,
1341
+ stepIndex,
1342
+ itemKey: item.key,
1343
+ structured: Boolean(dynamicSteps[itemIndex]?.structuredOutputSchema),
1344
+ }));
1345
+ }
1346
+ }
1347
+ writeStatusPayload();
1348
+ const parallelResults = await runParallelTasks({
1349
+ tasks: dynamicSteps,
1350
+ concurrency: step.concurrency ?? MAX_PARALLEL_CONCURRENCY,
1351
+ failFast: step.failFast,
1352
+ signal: cancellation.signal,
1353
+ interruptSignal: interruption.signal,
1354
+ stoppedTask: (task, index, reason) => stoppedParallelChild(task, groupStartFlatIndex + index, reason),
1355
+ runTask: (task, taskIdx, failFastSignal) => runParallelChild({
1356
+ task,
1357
+ flatIndex: groupStartFlatIndex + taskIdx,
1358
+ interruptSignal: failFastSignal,
1359
+ item: { name: step.expand.item ?? "item", value: materialized.items[taskIdx].item },
1360
+ taskCwd: cwd,
1361
+ sessionDir: config.sessionDir ? path.join(config.sessionDir, `dynamic-${stepIndex}-${taskIdx}`) : undefined,
1362
+ flatStepCount: Math.max(statusPayload.steps.length, 1),
1363
+ }),
1364
+ });
1365
+ flatIndex += dynamicSteps.length;
1366
+ for (const pr of parallelResults)
1367
+ results.push({ ...pr, success: workflowChildSucceeded(pr) });
1368
+ const completion = completeWorkflowStep({ stepIndex, stepCount: steps.length, results: parallelResults, previousOutput, dynamic: { step, items: materialized.items } });
1369
+ Object.assign(outputs, completion.outputs);
1370
+ statusPayload.outputs = outputs;
1371
+ if (completion.error) {
1372
+ statusPayload.error = completion.error;
1373
+ }
1374
+ previousOutput = completion.previousOutput;
1375
+ workflowComplete = completion.complete;
1376
+ const error = completion.error ?? parallelResults[completion.failedIndices[0]]?.error;
1377
+ markDynamicGraphGroup(stepIndex, completion.status === "completed" ? "completed" : completion.status === "blocked" ? "blocked" : completion.status === "paused" ? "paused" : "failed", error);
1378
+ appendJsonl(eventsPath, JSON.stringify({
1379
+ type: "subagent.dynamic.completed",
1380
+ ts: Date.now(),
1381
+ runId: id,
1382
+ stepIndex,
1383
+ success: completion.advance,
1384
+ state: completion.status === "completed" ? "complete" : completion.status,
1385
+ }));
1386
+ statusPayload.lastUpdate = Date.now();
1387
+ writeStatusPayload();
1388
+ if (!completion.advance)
1389
+ break;
1390
+ continue;
1391
+ }
1392
+ if (isParallelGroup(step)) {
1393
+ const group = step;
1394
+ const groupCwd = group.cwd ?? cwd;
1395
+ const groupStartFlatIndex = flatIndex;
1396
+ let worktreeSetup;
1397
+ if (group.worktree) {
1398
+ const worktreeTaskCwdConflict = findWorktreeTaskCwdConflict(group.parallel, groupCwd);
1399
+ if (worktreeTaskCwdConflict) {
1400
+ const failedAt = Date.now();
1401
+ markParallelGroupSetupFailure({
1402
+ statusPayload,
1403
+ results,
1404
+ group,
1405
+ groupStartFlatIndex,
1406
+ setupError: formatWorktreeTaskCwdConflict(worktreeTaskCwdConflict, groupCwd),
1407
+ failedAt,
1408
+ statusPath,
1409
+ eventsPath,
1410
+ asyncDir,
1411
+ runId: id,
1412
+ stepIndex,
1413
+ });
1414
+ flatIndex += group.parallel.length;
1415
+ break;
1416
+ }
1417
+ try {
1418
+ worktreeSetup = await createWorktrees(groupCwd, `${id}-s${stepIndex}`, group.parallel.length, {
1419
+ agents: group.parallel.map((task) => task.agent),
1420
+ signal: AbortSignal.any([cancellation.signal, interruption.signal]),
1421
+ setupHook: config.worktreeSetupHook
1422
+ ? { hookPath: config.worktreeSetupHook, timeoutMs: config.worktreeSetupHookTimeoutMs }
1423
+ : undefined,
1424
+ });
1425
+ }
1426
+ catch (error) {
1427
+ const setupError = error instanceof Error ? error.message : String(error);
1428
+ if (interrupted && !cancellation.signal.aborted) {
1429
+ if (error instanceof WorktreeCleanupError)
1430
+ setupCleanupWarning = setupError;
1431
+ for (const [index, task] of group.parallel.entries()) {
1432
+ const stopped = stoppedParallelChild(task, groupStartFlatIndex + index, "interrupted");
1433
+ if (error instanceof WorktreeCleanupError)
1434
+ stopped.output += `\n\n${setupError}`;
1435
+ results.push({ ...stopped, success: false });
1436
+ }
1437
+ flatIndex += group.parallel.length;
1438
+ break;
1439
+ }
1440
+ const failedAt = Date.now();
1441
+ markParallelGroupSetupFailure({
1442
+ statusPayload,
1443
+ results,
1444
+ group,
1445
+ groupStartFlatIndex,
1446
+ setupError,
1447
+ failedAt,
1448
+ statusPath,
1449
+ eventsPath,
1450
+ asyncDir,
1451
+ runId: id,
1452
+ stepIndex,
1453
+ });
1454
+ flatIndex += group.parallel.length;
1455
+ break;
1456
+ }
1457
+ }
1458
+ try {
1459
+ if (group.worktree)
1460
+ ensureParallelProgressFile(groupCwd, group);
1461
+ const groupStartTime = Date.now();
1462
+ markParallelGroupRunning({
1463
+ statusPayload,
1464
+ group,
1465
+ groupStartFlatIndex,
1466
+ groupStartTime,
1467
+ statusPath,
1468
+ eventsPath,
1469
+ asyncDir,
1470
+ runId: id,
1471
+ stepIndex,
1472
+ });
1473
+ const parallelResults = await runParallelTasks({
1474
+ tasks: group.parallel,
1475
+ concurrency: group.concurrency ?? MAX_PARALLEL_CONCURRENCY,
1476
+ failFast: group.failFast,
1477
+ signal: cancellation.signal,
1478
+ interruptSignal: interruption.signal,
1479
+ stoppedTask: (task, index, reason) => stoppedParallelChild(task, groupStartFlatIndex + index, reason),
1480
+ runTask: (task, taskIdx, failFastSignal) => {
1481
+ const { taskForRun, taskCwd } = prepareParallelTaskRun(task, groupCwd, worktreeSetup, taskIdx);
1482
+ return runParallelChild({
1483
+ task: taskForRun,
1484
+ worktreePath: worktreeSetup?.worktrees[taskIdx]?.path,
1485
+ flatIndex: groupStartFlatIndex + taskIdx,
1486
+ interruptSignal: failFastSignal,
1487
+ taskCwd,
1488
+ sessionDir: config.sessionDir ? path.join(config.sessionDir, `parallel-${taskIdx}`) : undefined,
1489
+ flatStepCount: flatSteps.length,
1490
+ resetTiming: true,
1491
+ trackSession: true,
1492
+ notifyCompletionGuard: true,
1493
+ });
1494
+ },
1495
+ });
1496
+ flatIndex += group.parallel.length;
1497
+ refreshUsageTotals();
1498
+ statusPayload.lastUpdate = Date.now();
1499
+ writeStatusPayload();
1500
+ for (const pr of parallelResults)
1501
+ results.push({ ...pr, success: workflowChildSucceeded(pr) });
1502
+ const completion = completeWorkflowStep({
1503
+ stepIndex, stepCount: steps.length, results: parallelResults, previousOutput, parallel: true,
1504
+ outputNames: group.parallel.map((task) => task.outputName),
1505
+ });
1506
+ Object.assign(outputs, completion.outputs);
1507
+ statusPayload.outputs = outputs;
1508
+ const worktreeSummary = formatRunnerWorktreeSummary(worktreeSetup, asyncDir, stepIndex, group);
1509
+ previousOutput = completion.advance ? appendWorktreeSummary(completion.previousOutput, worktreeSummary) : completion.previousOutput;
1510
+ workflowComplete = completion.complete;
1511
+ if (worktreeSummary)
1512
+ worktreeSummaries.push(worktreeSummary);
1513
+ appendJsonl(eventsPath, JSON.stringify({
1514
+ type: "subagent.parallel.completed",
1515
+ ts: Date.now(),
1516
+ runId: id,
1517
+ stepIndex,
1518
+ success: completion.advance,
1519
+ state: completion.status === "completed" ? "complete" : completion.status,
1520
+ }));
1521
+ writeStatusPayload();
1522
+ if (!completion.advance)
1523
+ break;
1524
+ }
1525
+ catch (error) {
1526
+ if (worktreeSetup)
1527
+ worktreeSetup.preserveOnCleanup = true;
1528
+ throw error;
1529
+ }
1530
+ finally {
1531
+ if (worktreeSetup)
1532
+ cleanupWorktrees(worktreeSetup);
1533
+ }
1534
+ }
1535
+ else {
1536
+ const seqStep = step;
1537
+ const stepStartTime = Date.now();
1538
+ statusPayload.currentStep = flatIndex;
1539
+ statusPayload.steps[flatIndex].status = "running";
1540
+ statusPayload.steps[flatIndex].activityState = undefined;
1541
+ statusPayload.activityState = undefined;
1542
+ resetStepLiveDetail(statusPayload.steps[flatIndex]);
1543
+ statusPayload.steps[flatIndex].skills = seqStep.skills;
1544
+ statusPayload.steps[flatIndex].startedAt = stepStartTime;
1545
+ statusPayload.steps[flatIndex].lastActivityAt = stepStartTime;
1546
+ statusPayload.lastActivityAt = stepStartTime;
1547
+ statusPayload.lastUpdate = stepStartTime;
1548
+ statusPayload.outputFile = path.join(asyncDir, `output-${flatIndex}.log`);
1549
+ writeStatusPayload();
1550
+ appendJsonl(eventsPath, JSON.stringify({
1551
+ type: "subagent.step.started",
1552
+ ts: stepStartTime,
1553
+ runId: id,
1554
+ stepIndex: flatIndex,
1555
+ agent: seqStep.agent,
1556
+ }));
1557
+ const singleResult = await runSingleStep({ ...seqStep, task: renderTask(seqStep.task) }, {
1558
+ nativeFinalization: config.runtimeVersion === 2,
1559
+ cwd, sessionEnabled,
1560
+ sessionDir: config.sessionDir,
1561
+ artifactsDir, id,
1562
+ flatIndex, flatStepCount: flatSteps.length,
1563
+ outputFile: path.join(asyncDir, `output-${flatIndex}.log`),
1564
+ childIntercomTarget: config.childIntercomTargets?.[flatIndex],
1565
+ orchestratorIntercomTarget: config.childIntercomTargets?.[flatIndex] ? config.controlIntercomTarget : undefined,
1566
+ nestedRoute: config.nestedRoute,
1567
+ projectTrust: config.projectTrust,
1568
+ rootSessionId: config.rootSessionId,
1569
+ signal: cancellation.signal,
1570
+ registerInterrupt: (interrupt) => {
1571
+ if (interrupt)
1572
+ activeChildInterrupts.set(flatIndex, interrupt);
1573
+ else
1574
+ activeChildInterrupts.delete(flatIndex);
1575
+ },
1576
+ onAttemptStart: (attempt) => updateStepModel(flatIndex, attempt.model, attempt.thinking),
1577
+ onChildEvent: (event, mutation) => updateStepFromChildEvent(flatIndex, event, mutation),
1578
+ });
1579
+ activeChildInterrupts.delete(flatIndex);
1580
+ if (seqStep.sessionFile) {
1581
+ latestSessionFile = seqStep.sessionFile;
1582
+ }
1583
+ const completion = completeWorkflowStep({ stepIndex, stepCount: steps.length, results: [singleResult], previousOutput, outputNames: [seqStep.outputName] });
1584
+ previousOutput = completion.previousOutput;
1585
+ workflowComplete = completion.complete;
1586
+ results.push({ ...singleResult, success: workflowChildSucceeded(singleResult) });
1587
+ Object.assign(outputs, completion.outputs);
1588
+ statusPayload.outputs = outputs;
1589
+ const stepTokens = tokenUsageFromAttempts(singleResult.modelAttempts);
1590
+ const stepEndTime = Date.now();
1591
+ statusPayload.steps[flatIndex].status = singleResult.interrupted ? "paused" : singleResult.exitCode === 0 ? singleResult.acceptance?.status === "blocked" ? "blocked" : "complete" : "failed";
1592
+ clearStepCurrentActivity(statusPayload.steps[flatIndex]);
1593
+ statusPayload.steps[flatIndex].endedAt = stepEndTime;
1594
+ statusPayload.steps[flatIndex].durationMs = stepEndTime - stepStartTime;
1595
+ statusPayload.steps[flatIndex].exitCode = singleResult.exitCode;
1596
+ statusPayload.steps[flatIndex].agentProcessExit = singleResult.agentProcessExit;
1597
+ statusPayload.steps[flatIndex].model = singleResult.model;
1598
+ statusPayload.steps[flatIndex].thinking = resolveEffectiveThinking(singleResult.model, statusPayload.steps[flatIndex].thinking);
1599
+ statusPayload.steps[flatIndex].attemptedModels = singleResult.attemptedModels;
1600
+ statusPayload.steps[flatIndex].modelAttempts = singleResult.modelAttempts;
1601
+ statusPayload.steps[flatIndex].error = singleResult.error;
1602
+ statusPayload.steps[flatIndex].structuredOutput = singleResult.structuredOutput;
1603
+ statusPayload.steps[flatIndex].structuredOutputPath = singleResult.structuredOutputPath;
1604
+ statusPayload.steps[flatIndex].structuredOutputSchemaPath = singleResult.structuredOutputSchemaPath;
1605
+ statusPayload.steps[flatIndex].acceptance = singleResult.acceptance;
1606
+ statusPayload.steps[flatIndex].resourceLimitExceeded = singleResult.resourceLimitExceeded;
1607
+ if (stepTokens) {
1608
+ statusPayload.steps[flatIndex].tokens = stepTokens;
1609
+ refreshUsageTotals();
1610
+ }
1611
+ statusPayload.lastUpdate = stepEndTime;
1612
+ writeStatusPayload();
1613
+ appendJsonl(eventsPath, JSON.stringify({
1614
+ type: singleResult.interrupted ? "subagent.step.paused" : singleResult.exitCode !== 0 ? "subagent.step.failed" : singleResult.acceptance?.status === "blocked" ? "subagent.step.blocked" : "subagent.step.completed",
1615
+ ts: stepEndTime,
1616
+ runId: id,
1617
+ stepIndex: flatIndex,
1618
+ agent: seqStep.agent,
1619
+ exitCode: singleResult.exitCode,
1620
+ durationMs: stepEndTime - stepStartTime,
1621
+ interrupted: singleResult.interrupted, agentProcessExit: singleResult.agentProcessExit,
1622
+ tokens: stepTokens,
1623
+ resourceLimitExceeded: singleResult.resourceLimitExceeded,
1624
+ }));
1625
+ if (singleResult.completionGuardTriggered) {
1626
+ const event = buildControlEvent({
1627
+ from: statusPayload.steps[flatIndex].activityState,
1628
+ to: "needs_attention",
1629
+ runId: id,
1630
+ agent: seqStep.agent,
1631
+ index: flatIndex,
1632
+ ts: stepEndTime,
1633
+ message: `${seqStep.agent} completed without making edits for an implementation task`,
1634
+ reason: "completion_guard",
1635
+ });
1636
+ appendControlEvent(event);
1637
+ }
1638
+ flatIndex++;
1639
+ if (!completion.advance)
1640
+ break;
1641
+ }
1642
+ }
1643
+ const resultMode = config.resultMode ?? statusPayload.mode;
1644
+ const childText = (result) => result.error && !result.output.includes(result.error) ? `${result.error}\n${result.output}`.trim() : result.output;
1645
+ let summary = resultMode === "single" && results.length === 1 ? childText(results[0]) : results.map((result) => `${result.agent}:\n${childText(result)}`).join("\n\n");
1646
+ if (statusPayload.error && !summary.includes(statusPayload.error))
1647
+ summary = `${statusPayload.error}\n\n${summary}`.trim();
1648
+ if (statusPayload.timedOut)
1649
+ summary = [
1650
+ `${resultMode === "parallel" ? "Parallel run" : resultMode === "chain" ? "Chain" : "Run"} timed out.`,
1651
+ summary,
1652
+ ].filter(Boolean).join("\n\n");
1653
+ if (worktreeSummaries.length > 0)
1654
+ summary = appendWorktreeSummary(summary, worktreeSummaries.join("\n\n"));
1655
+ const fullSummary = summary;
1656
+ let truncated = false;
1657
+ const outputLimits = { ...DEFAULT_MAX_OUTPUT, ...maxOutput };
1658
+ const lastArtifactPath = results[results.length - 1]?.artifactPaths?.outputPath;
1659
+ const referenceOnly = resultMode === "single" && results.length === 1 && results[0]?.outputMode === "file-only" && results[0].exitCode === 0 && results[0].outputReference;
1660
+ const truncResult = referenceOnly ? { text: summary, truncated: false } : truncateOutput(summary, outputLimits, lastArtifactPath);
1661
+ if (truncResult.truncated) {
1662
+ summary = truncResult.text;
1663
+ truncated = true;
1664
+ }
1665
+ const agentName = flatSteps.length === 1
1666
+ ? flatSteps[0].agent
1667
+ : resultMode === "parallel"
1668
+ ? `parallel:${flatSteps.map((s) => s.agent).join("+")}`
1669
+ : `chain:${flatSteps.map((s) => s.agent).join("->")}`;
1670
+ let sessionFile;
1671
+ let shareUrl;
1672
+ let gistUrl;
1673
+ let shareError;
1674
+ if (shareEnabled) {
1675
+ sessionFile = config.sessionDir
1676
+ ? (findLatestSessionFile(config.sessionDir) ?? undefined)
1677
+ : undefined;
1678
+ if (!sessionFile && latestSessionFile) {
1679
+ sessionFile = latestSessionFile;
1680
+ }
1681
+ if (sessionFile) {
1682
+ try {
1683
+ const exportDir = config.sessionDir ?? path.dirname(sessionFile);
1684
+ fs.mkdirSync(exportDir, { recursive: true });
1685
+ const htmlPath = await exportSessionHtml(sessionFile, exportDir, config.piPackageRoot);
1686
+ const share = createShareLink(htmlPath);
1687
+ if ("error" in share)
1688
+ shareError = share.error;
1689
+ else {
1690
+ shareUrl = share.shareUrl;
1691
+ gistUrl = share.gistUrl;
1692
+ }
1693
+ }
1694
+ catch (err) {
1695
+ shareError = String(err);
1696
+ }
1697
+ }
1698
+ else {
1699
+ shareError = "Session file not found.";
1700
+ }
1701
+ }
1702
+ clearTimeout(deadlineTimer);
1703
+ if (activityTimer) {
1704
+ clearInterval(activityTimer);
1705
+ activityTimer = undefined;
1706
+ }
1707
+ if (controlRequestTimer) {
1708
+ clearInterval(controlRequestTimer);
1709
+ controlRequestTimer = undefined;
1710
+ }
1711
+ process.off(ASYNC_INTERRUPT_SIGNAL, interruptRunner);
1712
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"])
1713
+ process.off(signal, cancelRunner);
1714
+ const effectiveSessionFile = sessionFile ?? latestSessionFile ?? undefined;
1715
+ const runEndedAt = Date.now();
1716
+ if (interrupted) {
1717
+ for (let index = 0; index < statusPayload.steps.length; index++) {
1718
+ const step = statusPayload.steps[index];
1719
+ if (step.status !== "pending")
1720
+ continue;
1721
+ markStepPaused(step, runEndedAt);
1722
+ appendJsonl(eventsPath, JSON.stringify({
1723
+ type: "subagent.step.paused",
1724
+ ts: runEndedAt,
1725
+ runId: id,
1726
+ stepIndex: index,
1727
+ agent: step.agent,
1728
+ interrupted: true,
1729
+ durationMs: 0,
1730
+ }));
1731
+ }
1732
+ }
1733
+ const hasFailedSteps = statusPayload.steps.some((step) => step.status === "failed");
1734
+ const hasPausedSteps = statusPayload.steps.some((step) => step.status === "paused");
1735
+ const finalRunState = hasFailedSteps || statusPayload.error || cancellation.signal.aborted ? "failed"
1736
+ : statusPayload.steps.some((step) => step.status === "blocked") ? "blocked"
1737
+ : interrupted || hasPausedSteps ? "paused" : workflowComplete ? "complete" : "failed";
1738
+ statusPayload.state = finalRunState;
1739
+ statusPayload.activityState = undefined;
1740
+ statusPayload.currentTool = undefined;
1741
+ statusPayload.currentToolStartedAt = undefined;
1742
+ statusPayload.currentPath = undefined;
1743
+ statusPayload.endedAt = runEndedAt;
1744
+ statusPayload.lastUpdate = runEndedAt;
1745
+ statusPayload.sessionFile = effectiveSessionFile;
1746
+ statusPayload.shareUrl = shareUrl;
1747
+ statusPayload.gistUrl = gistUrl;
1748
+ statusPayload.shareError = shareError;
1749
+ if (statusPayload.state === "failed" && !statusPayload.error) {
1750
+ const failedStep = statusPayload.steps.find((s) => s.status === "failed");
1751
+ if (failedStep?.agent) {
1752
+ statusPayload.error = `Step failed: ${failedStep.agent}`;
1753
+ }
1754
+ else if (cancellation.signal.aborted) {
1755
+ statusPayload.error = "Subagent cancelled.";
1756
+ }
1757
+ }
1758
+ writeStatusPayload();
1759
+ appendJsonl(eventsPath, JSON.stringify({
1760
+ type: "subagent.run.completed",
1761
+ ts: runEndedAt,
1762
+ runId: id,
1763
+ status: statusPayload.state,
1764
+ durationMs: runEndedAt - overallStartTime,
1765
+ }));
1766
+ writeRunLog(logPath, {
1767
+ id,
1768
+ mode: statusPayload.mode,
1769
+ cwd,
1770
+ startedAt: overallStartTime,
1771
+ endedAt: runEndedAt,
1772
+ steps: statusPayload.steps.map((step) => ({
1773
+ agent: step.agent,
1774
+ status: step.status,
1775
+ durationMs: step.durationMs,
1776
+ })),
1777
+ summary: fullSummary,
1778
+ truncated: false,
1779
+ artifactsDir,
1780
+ sessionFile: effectiveSessionFile,
1781
+ shareUrl,
1782
+ shareError,
1783
+ });
1784
+ try {
1785
+ const resultData = {
1786
+ id,
1787
+ runtimeVersion: config.runtimeVersion,
1788
+ maxOutput: outputLimits, error: statusPayload.error,
1789
+ timedOut: statusPayload.timedOut,
1790
+ agent: agentName,
1791
+ mode: resultMode,
1792
+ success: finalRunState === "complete",
1793
+ state: finalRunState,
1794
+ summary: finalRunState === "blocked" ? `Needs your action — acceptance incomplete.\n${results.map((result) => acceptanceHumanAction(result.acceptance)).filter(Boolean).join("\n")}` : finalRunState === "paused" ? `Paused after interrupt. Waiting for explicit next action.${setupCleanupWarning ? `\n\n${setupCleanupWarning}` : ""}` : summary,
1795
+ results: results.map((r) => {
1796
+ const referenceOnly = r.outputMode === "file-only" && r.exitCode === 0 && r.outputReference;
1797
+ const childOutput = referenceOnly ? { text: referenceOnly.message, truncated: false } : truncateOutput(r.output, outputLimits, r.artifactPaths?.outputPath);
1798
+ return { ...r, output: childOutput.text,
1799
+ finalOutput: referenceOnly ? referenceOnly.message : r.finalOutput === undefined ? undefined : truncateOutput(r.finalOutput, outputLimits, r.artifactPaths?.outputPath).text,
1800
+ initialOutput: r.initialOutput === undefined ? undefined : truncateOutput(r.initialOutput, outputLimits, r.artifactPaths?.outputPath).text,
1801
+ truncated: r.truncated || childOutput.truncated || undefined };
1802
+ }),
1803
+ outputs,
1804
+ workflowGraph: statusPayload.workflowGraph,
1805
+ exitCode: statusPayload.timedOut ? 124 : finalRunState === "failed" ? 1 : 0,
1806
+ timestamp: runEndedAt,
1807
+ durationMs: runEndedAt - overallStartTime,
1808
+ truncated,
1809
+ artifactsDir,
1810
+ cwd,
1811
+ asyncDir,
1812
+ sessionId: config.sessionId ?? undefined,
1813
+ sessionFile: effectiveSessionFile,
1814
+ intercomTarget: config.controlIntercomTarget,
1815
+ shareUrl,
1816
+ gistUrl,
1817
+ shareError,
1818
+ ...(taskIndex !== undefined && { taskIndex }),
1819
+ ...(totalTasks !== undefined && { totalTasks }),
1820
+ };
1821
+ const saved = saveAsyncRunResult(id, resultData);
1822
+ resultData.completionId = saved.completionId;
1823
+ resultData.recordVersion = 3;
1824
+ if (config.runtimeVersion !== 2 || path.resolve(resultPath) !== path.resolve(asyncDir, "result.json"))
1825
+ writeAtomicJson(resultPath, resultData);
1826
+ }
1827
+ catch (err) {
1828
+ console.error(`Failed to write result file ${resultPath}:`, err);
1829
+ }
1830
+ }
1831
+ const configArg = process.argv[2];
1832
+ if (configArg) {
1833
+ try {
1834
+ const configJson = fs.readFileSync(configArg, "utf-8");
1835
+ const config = JSON.parse(configJson);
1836
+ try {
1837
+ if (config.runtimeVersion !== 2)
1838
+ fs.unlinkSync(configArg);
1839
+ }
1840
+ catch {
1841
+ // Temp config cleanup is best effort.
1842
+ }
1843
+ runSubagent(config).catch((runErr) => {
1844
+ console.error("Subagent runner error:", runErr);
1845
+ process.exit(1);
1846
+ });
1847
+ }
1848
+ catch (err) {
1849
+ console.error("Subagent runner error:", err);
1850
+ process.exit(1);
1851
+ }
1852
+ }
1853
+ else {
1854
+ let input = "";
1855
+ process.stdin.setEncoding("utf-8");
1856
+ process.stdin.on("data", (chunk) => {
1857
+ input += chunk;
1858
+ });
1859
+ process.stdin.on("end", () => {
1860
+ try {
1861
+ const config = JSON.parse(input);
1862
+ runSubagent(config).catch((runErr) => {
1863
+ console.error("Subagent runner error:", runErr);
1864
+ process.exit(1);
1865
+ });
1866
+ }
1867
+ catch (err) {
1868
+ console.error("Subagent runner error:", err);
1869
+ process.exit(1);
1870
+ }
1871
+ });
1872
+ }