@fitchmultz/pi-subagents 0.0.0-stage → 0.44.5

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