@xzzpig/pi-subagents 0.1.0

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 (196) hide show
  1. package/CHANGELOG.md +1621 -0
  2. package/LICENSE +21 -0
  3. package/README.md +118 -0
  4. package/agents/delegate.md +14 -0
  5. package/agents/oracle.md +74 -0
  6. package/agents/researcher.md +52 -0
  7. package/agents/reviewer.md +79 -0
  8. package/agents/scout.md +50 -0
  9. package/agents/worker.md +58 -0
  10. package/index.ts +1 -0
  11. package/inspector-runner.mjs +11 -0
  12. package/install.mjs +93 -0
  13. package/package.json +105 -0
  14. package/prompts/gather-context-and-clarify.md +13 -0
  15. package/prompts/parallel-cleanup.md +59 -0
  16. package/prompts/parallel-research.md +50 -0
  17. package/prompts/parallel-review.md +54 -0
  18. package/prompts/review-loop.md +43 -0
  19. package/skills/pi-subagents/SKILL.md +41 -0
  20. package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
  21. package/skills/pi-subagents/references/execution-controls.md +428 -0
  22. package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
  24. package/src/agents/agent-management.ts +1256 -0
  25. package/src/agents/agent-memory.ts +254 -0
  26. package/src/agents/agent-refinements.ts +624 -0
  27. package/src/agents/agent-scope.ts +6 -0
  28. package/src/agents/agent-selection.ts +25 -0
  29. package/src/agents/agent-serializer.ts +163 -0
  30. package/src/agents/agents.ts +1889 -0
  31. package/src/agents/chain-serializer.ts +280 -0
  32. package/src/agents/frontmatter.ts +149 -0
  33. package/src/agents/identity.ts +30 -0
  34. package/src/agents/proactive-skills.ts +194 -0
  35. package/src/agents/skills.ts +761 -0
  36. package/src/api/background-work.ts +197 -0
  37. package/src/api/capability-ceiling.ts +17 -0
  38. package/src/api/control-channel.ts +4 -0
  39. package/src/api/delegation.ts +119 -0
  40. package/src/api/external-runs.ts +129 -0
  41. package/src/api/intercom-bridge.ts +3 -0
  42. package/src/api/pi-args.ts +5 -0
  43. package/src/api/preflight.ts +403 -0
  44. package/src/api/shared-types.ts +19 -0
  45. package/src/extension/config.ts +76 -0
  46. package/src/extension/control-notices.ts +58 -0
  47. package/src/extension/doctor.ts +230 -0
  48. package/src/extension/fanout-child.ts +201 -0
  49. package/src/extension/index.ts +805 -0
  50. package/src/extension/public-execution.ts +71 -0
  51. package/src/extension/rpc.ts +653 -0
  52. package/src/extension/schemas.ts +375 -0
  53. package/src/extension/steering-notices.ts +35 -0
  54. package/src/extension/tool-description.ts +164 -0
  55. package/src/inspectors/herdr/actions.ts +229 -0
  56. package/src/inspectors/herdr/client.ts +130 -0
  57. package/src/inspectors/herdr/inspector-runner.ts +141 -0
  58. package/src/inspectors/herdr/project-panes.ts +154 -0
  59. package/src/integrations/herdr-status.ts +330 -0
  60. package/src/intercom/intercom-bridge.ts +187 -0
  61. package/src/intercom/native-supervisor-channel.ts +715 -0
  62. package/src/intercom/result-intercom.ts +421 -0
  63. package/src/missions/actions.ts +410 -0
  64. package/src/missions/goal-driver.ts +162 -0
  65. package/src/missions/lifecycle.ts +346 -0
  66. package/src/missions/store.ts +507 -0
  67. package/src/missions/types.ts +157 -0
  68. package/src/missions/workflow-state.ts +250 -0
  69. package/src/policy/authority.ts +46 -0
  70. package/src/profiles/profiles.ts +661 -0
  71. package/src/runs/background/async-execution.ts +1574 -0
  72. package/src/runs/background/async-job-tracker.ts +511 -0
  73. package/src/runs/background/async-resume.ts +539 -0
  74. package/src/runs/background/async-status.ts +542 -0
  75. package/src/runs/background/auto-drain.ts +67 -0
  76. package/src/runs/background/chain-append.ts +328 -0
  77. package/src/runs/background/chain-root-attachment.ts +199 -0
  78. package/src/runs/background/completion-batcher.ts +168 -0
  79. package/src/runs/background/completion-dedupe.ts +54 -0
  80. package/src/runs/background/control-channel.ts +692 -0
  81. package/src/runs/background/fleet-view.ts +540 -0
  82. package/src/runs/background/notify.ts +332 -0
  83. package/src/runs/background/parallel-groups.ts +45 -0
  84. package/src/runs/background/process-terminal.ts +280 -0
  85. package/src/runs/background/result-watcher.ts +414 -0
  86. package/src/runs/background/retained-children.ts +68 -0
  87. package/src/runs/background/run-id-resolver.ts +167 -0
  88. package/src/runs/background/run-status.ts +504 -0
  89. package/src/runs/background/scheduled-runs.ts +753 -0
  90. package/src/runs/background/stale-run-reconciler.ts +396 -0
  91. package/src/runs/background/steering.ts +239 -0
  92. package/src/runs/background/subagent-runner.ts +4718 -0
  93. package/src/runs/background/subagent-wait.ts +661 -0
  94. package/src/runs/background/top-level-async.ts +14 -0
  95. package/src/runs/background/wait-completions.ts +112 -0
  96. package/src/runs/background/wait-config.ts +36 -0
  97. package/src/runs/background/wait-subscriptions.ts +253 -0
  98. package/src/runs/background/wait-tool.ts +34 -0
  99. package/src/runs/foreground/async-steering-action.ts +256 -0
  100. package/src/runs/foreground/async-stop-action.ts +65 -0
  101. package/src/runs/foreground/chain-clarify.ts +1354 -0
  102. package/src/runs/foreground/chain-execution.ts +1527 -0
  103. package/src/runs/foreground/execution.ts +1868 -0
  104. package/src/runs/foreground/foreground-control.ts +132 -0
  105. package/src/runs/foreground/subagent-executor.ts +5532 -0
  106. package/src/runs/shared/acceptance.ts +1365 -0
  107. package/src/runs/shared/agent-contract.ts +38 -0
  108. package/src/runs/shared/capability-ceiling.ts +209 -0
  109. package/src/runs/shared/chain-outputs.ts +118 -0
  110. package/src/runs/shared/child-protocol.ts +401 -0
  111. package/src/runs/shared/completion-guard.ts +95 -0
  112. package/src/runs/shared/context-mode.ts +44 -0
  113. package/src/runs/shared/dynamic-fanout.ts +297 -0
  114. package/src/runs/shared/external-cli-runner.ts +130 -0
  115. package/src/runs/shared/long-running-guard.ts +220 -0
  116. package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
  117. package/src/runs/shared/model-fallback.ts +336 -0
  118. package/src/runs/shared/model-scope.ts +128 -0
  119. package/src/runs/shared/nested-events.ts +1076 -0
  120. package/src/runs/shared/nested-path.ts +52 -0
  121. package/src/runs/shared/nested-render.ts +123 -0
  122. package/src/runs/shared/parallel-handoff.ts +238 -0
  123. package/src/runs/shared/parallel-utils.ts +256 -0
  124. package/src/runs/shared/permissions.ts +95 -0
  125. package/src/runs/shared/pi-args.ts +808 -0
  126. package/src/runs/shared/pi-spawn.ts +163 -0
  127. package/src/runs/shared/process-signal.ts +19 -0
  128. package/src/runs/shared/run-history.ts +181 -0
  129. package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
  130. package/src/runs/shared/session-lease.ts +299 -0
  131. package/src/runs/shared/single-output.ts +235 -0
  132. package/src/runs/shared/spawn-budget.ts +128 -0
  133. package/src/runs/shared/structured-output.ts +182 -0
  134. package/src/runs/shared/subagent-control.ts +231 -0
  135. package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
  136. package/src/runs/shared/subagent-startup-retry.ts +104 -0
  137. package/src/runs/shared/task-intent.ts +181 -0
  138. package/src/runs/shared/tool-availability.ts +83 -0
  139. package/src/runs/shared/tool-budget.ts +80 -0
  140. package/src/runs/shared/turn-budget.ts +98 -0
  141. package/src/runs/shared/usage-budget.ts +65 -0
  142. package/src/runs/shared/workflow-graph.ts +231 -0
  143. package/src/runs/shared/worktree.ts +759 -0
  144. package/src/shared/accessible-dir.ts +47 -0
  145. package/src/shared/artifacts.ts +285 -0
  146. package/src/shared/atomic-json.ts +61 -0
  147. package/src/shared/child-transcript.ts +264 -0
  148. package/src/shared/file-coalescer.ts +40 -0
  149. package/src/shared/file-system-retry.ts +47 -0
  150. package/src/shared/fork-context.ts +213 -0
  151. package/src/shared/formatters.ts +133 -0
  152. package/src/shared/jsonl-writer.ts +81 -0
  153. package/src/shared/launch-contract.ts +124 -0
  154. package/src/shared/model-info.ts +81 -0
  155. package/src/shared/post-exit-stdio-guard.ts +85 -0
  156. package/src/shared/session-identity.ts +10 -0
  157. package/src/shared/session-tokens.ts +44 -0
  158. package/src/shared/settings.ts +501 -0
  159. package/src/shared/status-format.ts +55 -0
  160. package/src/shared/types.ts +2069 -0
  161. package/src/shared/utils.ts +613 -0
  162. package/src/slash/delegation-adapters.ts +434 -0
  163. package/src/slash/delegation-json.ts +108 -0
  164. package/src/slash/delegation-request.ts +166 -0
  165. package/src/slash/prompt-template-bridge.ts +383 -0
  166. package/src/slash/prompt-workflows.ts +300 -0
  167. package/src/slash/selector.ts +147 -0
  168. package/src/slash/slash-bridge.ts +192 -0
  169. package/src/slash/slash-commands.ts +994 -0
  170. package/src/slash/slash-live-state.ts +296 -0
  171. package/src/slash/subagents-admin.ts +432 -0
  172. package/src/tui/fleet-status.ts +564 -0
  173. package/src/tui/fleet-transcript.ts +577 -0
  174. package/src/tui/fleet.ts +879 -0
  175. package/src/tui/render-helpers.ts +80 -0
  176. package/src/tui/render.ts +2029 -0
  177. package/src/types/pi-runtime-compat.d.ts +8 -0
  178. package/src/watchdog/change-signature.ts +220 -0
  179. package/src/watchdog/child-status.ts +205 -0
  180. package/src/watchdog/emission-guard.ts +123 -0
  181. package/src/watchdog/lsp-diagnostics.ts +537 -0
  182. package/src/watchdog/model-selection.ts +167 -0
  183. package/src/watchdog/permission-arbiter.ts +145 -0
  184. package/src/watchdog/register-child.ts +117 -0
  185. package/src/watchdog/register-main.ts +440 -0
  186. package/src/watchdog/render.ts +54 -0
  187. package/src/watchdog/review.ts +302 -0
  188. package/src/watchdog/runtime.ts +868 -0
  189. package/src/watchdog/scope.ts +62 -0
  190. package/src/watchdog/settings.ts +568 -0
  191. package/src/watchdog/tool-actions.ts +155 -0
  192. package/src/watchdog/turn-delta.ts +161 -0
  193. package/src/watchdog/types.ts +198 -0
  194. package/src/watchdog/warning-format.ts +73 -0
  195. package/src/workflows/chat-progress.ts +140 -0
  196. package/src/workflows/scripted-workflow.ts +506 -0
@@ -0,0 +1,4718 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import * as fs from "node:fs";
4
+ import * as path from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import type { Message } from "@earendil-works/pi-ai";
7
+ import { writeAtomicJson } from "../../shared/atomic-json.ts";
8
+ import { createChildTranscriptWriter, type ChildTranscriptWriter } from "../../shared/child-transcript.ts";
9
+ import { closeSteerInbox, consumeInterruptRequest, consumeSteerRequests, deliverInterruptRequest, deliverStopRequest, deliverTimeoutRequest, enqueueStepSteer, steerAcksDir, steerCapabilityPath, stepSteerInboxDir, watchAsyncControlInbox, type SteerAck, type SteerCapability, type SteerRequest } from "./control-channel.ts";
10
+ import { appendJsonl as appendRawJsonl, formatOutputArtifactContent, getArtifactPaths, writeArtifact, writeMetadata } from "../../shared/artifacts.ts";
11
+ import { PI_CODING_AGENT_PACKAGE, getPiSpawnCommand, resolveInstalledPiPackageRoot } from "../shared/pi-spawn.ts";
12
+ import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, injectOutputPathSystemPrompt, injectSingleOutputInstruction, resolveSingleOutput, type SingleOutputSnapshot } from "../shared/single-output.ts";
13
+ import {
14
+ type ActivityState,
15
+ type ArtifactConfig,
16
+ type ExternalCliRunnerStatus,
17
+ type ExternalProcessStatus,
18
+ type ArtifactPaths,
19
+ type AsyncParallelGroupStatus,
20
+ type AsyncStatus,
21
+ type ChainOutputMap,
22
+ type CostSummary,
23
+ type LaunchResolvedChildExtensionsV1,
24
+ type RuntimeAcknowledgedChildExtensionsV1,
25
+ type ModelAttempt,
26
+ type NestedRouteInfo,
27
+ type NestedRunSummary,
28
+ type ResolvedControlConfig,
29
+ type ResolvedTurnBudget,
30
+ type ResolvedToolBudget,
31
+ type SubagentRunMode,
32
+ type SubagentOutputState,
33
+ type UsageBudgetConfig,
34
+ type ToolBudgetState,
35
+ type TurnBudgetState,
36
+ type Usage,
37
+ type WorkflowGraphSnapshot,
38
+ type SteeringStatus,
39
+ type SteeringTargetState,
40
+ type SteeringTargetStatus,
41
+ DEFAULT_MAX_OUTPUT,
42
+ type MaxOutputConfig,
43
+ SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
44
+ POLL_INTERVAL_MS,
45
+ truncateOutput,
46
+ getSubagentDepthEnv,
47
+ } from "../../shared/types.ts";
48
+ import {
49
+ DEFAULT_CONTROL_CONFIG,
50
+ buildControlEvent,
51
+ deriveActivityState,
52
+ claimControlNotification,
53
+ formatControlIntercomMessage,
54
+ formatControlNoticeMessage,
55
+ } from "../shared/subagent-control.ts";
56
+ import {
57
+ type RunnerSubagentStep as SubagentStep,
58
+ type RunnerStep,
59
+ isCheckpointRunnerStep,
60
+ isDynamicRunnerGroup,
61
+ isParallelGroup,
62
+ flattenSteps,
63
+ mapConcurrent,
64
+ aggregateParallelOutputs,
65
+ MAX_PARALLEL_CONCURRENCY,
66
+ DEFAULT_GLOBAL_CONCURRENCY_LIMIT,
67
+ Semaphore,
68
+ } from "../shared/parallel-utils.ts";
69
+ import { applyThinkingSuffix, buildPiArgs, cleanupTempDir, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/pi-args.ts";
70
+ import { readRuntimeAcknowledgedExtensions } from "../shared/runtime-acknowledged-extensions.ts";
71
+ import { outputEntryFromAsyncResult, resolveOutputReferences } from "../shared/chain-outputs.ts";
72
+ import { createStructuredOutputRuntime, MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput } from "../shared/structured-output.ts";
73
+ import { formatProcessSignalError, isUnexplainedProcessSignal } from "../shared/process-signal.ts";
74
+ import { readChildToolDiagnosticError } from "../shared/tool-availability.ts";
75
+ import { collectDynamicResults, DynamicFanoutError, materializeDynamicParallelStep, validateDynamicCollection } from "../shared/dynamic-fanout.ts";
76
+ import { nestedSummaryFromAsyncStatus, projectNestedEvents, resolveNestedAsyncDir, writeNestedEvent } from "../shared/nested-events.ts";
77
+ import { formatModelAttemptNote, isRetryableModelFailure } from "../shared/model-fallback.ts";
78
+ import {
79
+ SUBAGENT_STARTUP_RETRY_DELAYS_MS,
80
+ formatSubagentStartupRetryExhaustedError,
81
+ formatSubagentStartupRetryNote,
82
+ isRetryableSubagentStartupFailure,
83
+ waitForSubagentStartupRetry,
84
+ } from "../shared/subagent-startup-retry.ts";
85
+ import { markProcessTerminalCandidateLeaseRelease, writeProcessTerminalCandidate, type ProcessTerminalCandidate } from "./process-terminal.ts";
86
+ import { createSteeringStatus, recordSteeringRequest, steeringStatus, terminalSteeringNoticeState, updateSteeringTarget } from "./steering.ts";
87
+ import { attachPostExitStdioGuard, trySignalChild } from "../../shared/post-exit-stdio-guard.ts";
88
+ import { detectSubagentError, extractTextFromContent, extractToolArgsPreview, getFinalOutput, hasEmptyTerminalAssistantResponse, readStatus } from "../../shared/utils.ts";
89
+ import { evaluateCompletionMutationGuard } from "../shared/completion-guard.ts";
90
+ import {
91
+ createMutatingFailureState,
92
+ didMutatingToolFail,
93
+ isMutatingTool,
94
+ nextLongRunningTrigger,
95
+ recordMutatingFailure,
96
+ resetMutatingFailureState,
97
+ resolveCurrentPath,
98
+ shouldEscalateMutatingFailures,
99
+ summarizeRecentMutatingFailures,
100
+ } from "../shared/long-running-guard.ts";
101
+ import { parseSessionTokens } from "../../shared/session-tokens.ts";
102
+ import type { TokenUsage } from "../../shared/types.ts";
103
+ import {
104
+ cleanupWorktrees,
105
+ createWorktrees,
106
+ diffWorktrees,
107
+ findWorktreeTaskCwdConflict,
108
+ formatWorktreeDiffSummary,
109
+ formatWorktreeTaskCwdConflict,
110
+ type WorktreeSetup,
111
+ } from "../shared/worktree.ts";
112
+ import { resolveEffectiveThinking } from "../../shared/model-info.ts";
113
+ import { launchBindingDigest } from "../../shared/launch-contract.ts";
114
+ import { writeInitialProgressFile } from "../../shared/settings.ts";
115
+ import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.ts";
116
+ import { acceptanceFailureMessage, aggregateAcceptanceReport, buildSkippedAcceptanceLedger, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport } from "../shared/acceptance.ts";
117
+ import { attachContractProjections, isAgentContractV1 } from "../shared/agent-contract.ts";
118
+ import { waitForImportedAsyncRoot } from "./chain-root-attachment.ts";
119
+ import { appendRunnerStepsToStatus, consumeChainAppendRequests, countPendingChainAppendRequests, statusStepDescription } from "./chain-append.ts";
120
+ import { appendTurnBudgetSystemPrompt, formatTurnBudgetOutput, initialTurnBudgetState, turnBudgetDecision, turnBudgetDeferredNote, turnBudgetDeferredState, turnBudgetExceededMessage, turnBudgetSoftNote, turnBudgetState } from "../shared/turn-budget.ts";
121
+ import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
122
+ import { usageBudgetExceededMessage, usageBudgetState } from "../shared/usage-budget.ts";
123
+ import { formatParallelHandoffError, formatParallelHandoffReference, parallelHandoffPath, writeParallelHandoffGroup, writePendingParallelHandoff } from "../shared/parallel-handoff.ts";
124
+ import { resolveWatchdogConfig } from "../../watchdog/settings.ts";
125
+ import { createBoundedByteTail, createBoundedLineReader, formatProtocolOutputLimit, MAX_CHILD_STDERR_BYTES, PI_AGGREGATE_EVENT_PROJECTOR, projectChildLifecycle, type ChildLifecycleAction, type ProtocolOutputLimit } from "../shared/child-protocol.ts";
126
+ import { acquireSessionLease, type SessionLeaseRequest } from "../shared/session-lease.ts";
127
+ import { buildExternalCliPrompt, runExternalCli } from "../shared/external-cli-runner.ts";
128
+ import { decodeSubagentCapabilityCeiling, SUBAGENT_CAPABILITY_CEILING_ENV, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
129
+ import {
130
+ CHILD_WATCHDOG_CONFIG_ENV,
131
+ acceptChildWatchdogEvent,
132
+ childWatchdogIsActive,
133
+ decodeChildWatchdogConfig,
134
+ isChildWatchdogStatusEvent,
135
+ resolveChildWatchdogConfig,
136
+ type ChildWatchdogStateSnapshot,
137
+ } from "../../watchdog/child-status.ts";
138
+
139
+ interface SubagentRunConfig {
140
+ id: string;
141
+ steps: RunnerStep[];
142
+ resultPath: string;
143
+ cwd: string;
144
+ placeholder: string;
145
+ taskIndex?: number;
146
+ totalTasks?: number;
147
+ maxOutput?: MaxOutputConfig;
148
+ artifactsDir?: string;
149
+ artifactConfig?: Partial<ArtifactConfig>;
150
+ share?: boolean;
151
+ sessionDir?: string;
152
+ asyncDir: string;
153
+ sessionId?: string | null;
154
+ piPackageRoot?: string;
155
+ piArgv1?: string;
156
+ worktreeSetupHook?: string;
157
+ worktreeSetupHookTimeoutMs?: number;
158
+ worktreeBaseDir?: string;
159
+ controlConfig?: ResolvedControlConfig;
160
+ controlIntercomTarget?: string;
161
+ childIntercomTargets?: Array<string | undefined>;
162
+ resultMode?: SubagentRunMode;
163
+ mode?: SubagentRunMode;
164
+ dynamicFanoutMaxItems?: number;
165
+ workflowGraph?: WorkflowGraphSnapshot;
166
+ nestedRoute?: NestedRouteInfo;
167
+ nestedSelf?: { parentRunId: string; parentStepIndex?: number; depth: number; path?: Array<{ runId: string; stepIndex?: number; agent?: string }> };
168
+ timeoutMs?: number;
169
+ deadlineAt?: number;
170
+ turnBudget?: ResolvedTurnBudget;
171
+ toolBudget?: ResolvedToolBudget;
172
+ usageBudget?: UsageBudgetConfig;
173
+ revivalLease?: SessionLeaseRequest;
174
+ revivalLeaseToken?: string;
175
+ /** Global cap on simultaneously-running subagent tasks within this run. */
176
+ globalConcurrencyLimit?: number;
177
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
178
+ launchContractDigest?: string;
179
+ launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
180
+ runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
181
+ runnerProcessInstanceId?: string;
182
+ parentWorkflowRunId?: string;
183
+ workflowKey?: string;
184
+ }
185
+
186
+ interface StepResult {
187
+ agent: string;
188
+ context?: "fresh" | "fork";
189
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
190
+ capabilityAudit?: import("../shared/capability-ceiling.ts").SubagentCapabilityAudit;
191
+ launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
192
+ runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
193
+ output: string;
194
+ outputState?: SubagentOutputState;
195
+ error?: string;
196
+ protocolError?: ProtocolOutputLimit;
197
+ success?: boolean;
198
+ exitCode: number | null;
199
+ usage?: Usage;
200
+ savedOutputPath?: string;
201
+ skipped?: boolean;
202
+ interrupted?: boolean;
203
+ timedOut?: boolean;
204
+ stopped?: boolean;
205
+ processSignal?: string | null;
206
+ turnBudget?: TurnBudgetState;
207
+ turnBudgetExceeded?: boolean;
208
+ wrapUpRequested?: boolean;
209
+ toolBudget?: ToolBudgetState;
210
+ toolBudgetBlocked?: boolean;
211
+ sessionFile?: string;
212
+ intercomTarget?: string;
213
+ model?: string;
214
+ attemptedModels?: string[];
215
+ modelAttempts?: ModelAttempt[];
216
+ totalCost?: CostSummary;
217
+ artifactPaths?: ArtifactPaths;
218
+ outputSaveError?: string;
219
+ metadataSaveError?: string;
220
+ truncated?: boolean;
221
+ transcriptPath?: string;
222
+ transcriptError?: string;
223
+ agentContract?: import("../../shared/types.ts").AgentContract;
224
+ launchContractDigest?: string;
225
+ execution?: import("../../shared/types.ts").ExecutionProjection;
226
+ review?: import("../../shared/types.ts").ReviewProjection;
227
+ effects?: import("../../shared/types.ts").EffectsProjection;
228
+ structuredOutput?: unknown;
229
+ structuredOutputPath?: string;
230
+ structuredOutputSchemaPath?: string;
231
+ acceptance?: import("../../shared/types.ts").AcceptanceLedger;
232
+ watchdog?: import("../../shared/types.ts").ChildWatchdogProgress;
233
+ writerProcesses?: Array<{ processInstanceId: string; kind: "pi-writer"; attempt: number; closeObservedAt: number; exitCode: number | null; signal: string | null }>;
234
+ writerAttemptCount?: number;
235
+ runner?: ExternalCliRunnerStatus;
236
+ externalProcess?: ExternalProcessStatus;
237
+ }
238
+
239
+ function persistStepArtifacts(input: {
240
+ artifactPaths: ArtifactPaths;
241
+ artifactConfig?: Partial<ArtifactConfig>;
242
+ output: string;
243
+ metadata: object;
244
+ }): { outputSaveError?: string; metadataSaveError?: string } {
245
+ const errors: { outputSaveError?: string; metadataSaveError?: string } = {};
246
+ if (input.artifactConfig?.includeOutput !== false) {
247
+ try {
248
+ writeArtifact(input.artifactPaths.outputPath, input.output);
249
+ } catch (error) {
250
+ errors.outputSaveError = `Artifact output post-processing failed: ${error instanceof Error ? error.message : String(error)}`;
251
+ }
252
+ }
253
+ if (input.artifactConfig?.includeMetadata !== false) {
254
+ try {
255
+ writeMetadata(input.artifactPaths.metadataPath, input.metadata);
256
+ } catch (error) {
257
+ errors.metadataSaveError = `Artifact metadata post-processing failed: ${error instanceof Error ? error.message : String(error)}`;
258
+ }
259
+ }
260
+ return errors;
261
+ }
262
+
263
+ const ASYNC_INTERRUPT_SIGNAL: NodeJS.Signals = process.platform === "win32" ? "SIGBREAK" : "SIGUSR2";
264
+ const DEFAULT_MAX_ASYNC_EVENTS_BYTES = 50 * 1024 * 1024;
265
+ const ASYNC_EVENTS_MAX_BYTES_ENV = "PI_SUBAGENT_ASYNC_EVENTS_MAX_BYTES";
266
+ const TRUNCATED_EVENT_TYPE = "subagent.events.truncated";
267
+ const TRUNCATION_MARKER_RESERVE_BYTES = 512;
268
+
269
+ interface AsyncEventLogState {
270
+ bytes: number;
271
+ diagnosticsTruncated: boolean;
272
+ }
273
+
274
+ const asyncEventLogStates = new Map<string, AsyncEventLogState>();
275
+
276
+ function maxAsyncEventsBytes(): number {
277
+ const raw = process.env[ASYNC_EVENTS_MAX_BYTES_ENV];
278
+ if (!raw) return DEFAULT_MAX_ASYNC_EVENTS_BYTES;
279
+ const parsed = Number(raw);
280
+ if (!Number.isFinite(parsed) || parsed < 0) return DEFAULT_MAX_ASYNC_EVENTS_BYTES;
281
+ return Math.floor(parsed);
282
+ }
283
+
284
+ function eventLogState(filePath: string): AsyncEventLogState {
285
+ let state = asyncEventLogStates.get(filePath);
286
+ if (state) return state;
287
+ let bytes = 0;
288
+ try {
289
+ bytes = fs.statSync(filePath).size;
290
+ } catch (error) {
291
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
292
+ // Diagnostic event accounting is best-effort; writes below are also safe.
293
+ }
294
+ }
295
+ state = { bytes, diagnosticsTruncated: false };
296
+ asyncEventLogStates.set(filePath, state);
297
+ return state;
298
+ }
299
+
300
+ function appendJsonl(filePath: string, line: string): void {
301
+ try {
302
+ appendRawJsonl(filePath, line);
303
+ const state = asyncEventLogStates.get(filePath);
304
+ if (state) state.bytes += Buffer.byteLength(`${line}\n`, "utf-8");
305
+ } catch {
306
+ // Async event logging is diagnostic and must not fail the run.
307
+ }
308
+ }
309
+
310
+ function appendDiagnosticJsonl(filePath: string, line: string, droppedEventType?: string): void {
311
+ if (!line.trim()) return;
312
+ const state = eventLogState(filePath);
313
+ if (state.diagnosticsTruncated) return;
314
+ const maxBytes = maxAsyncEventsBytes();
315
+ const chunkBytes = Buffer.byteLength(`${line}\n`, "utf-8");
316
+ const diagnosticBudget = Math.max(0, maxBytes - TRUNCATION_MARKER_RESERVE_BYTES);
317
+ if (state.bytes + chunkBytes <= diagnosticBudget) {
318
+ appendJsonl(filePath, line);
319
+ return;
320
+ }
321
+
322
+ const marker = JSON.stringify({
323
+ type: TRUNCATED_EVENT_TYPE,
324
+ ts: Date.now(),
325
+ maxBytes,
326
+ droppedEventType,
327
+ });
328
+ if (state.bytes + Buffer.byteLength(`${marker}\n`, "utf-8") <= maxBytes) {
329
+ appendJsonl(filePath, marker);
330
+ }
331
+ state.diagnosticsTruncated = true;
332
+ }
333
+
334
+ function shouldPersistChildEvent(event: Record<string, unknown>): boolean {
335
+ return event.type !== "message_update";
336
+ }
337
+
338
+ function isBlockingSupervisorTool(toolName: string | undefined, args: unknown): boolean {
339
+ if (!args || typeof args !== "object" || Array.isArray(args)) return false;
340
+ if (toolName === "contact_supervisor") {
341
+ const reason = (args as Record<string, unknown>).reason;
342
+ return reason === "need_decision" || reason === "interview_request";
343
+ }
344
+ return toolName === "intercom" && (args as Record<string, unknown>).action === "ask";
345
+ }
346
+
347
+ function findLatestSessionFile(sessionDir: string): string | null {
348
+ try {
349
+ const files = fs
350
+ .readdirSync(sessionDir)
351
+ .filter((f) => f.endsWith(".jsonl"))
352
+ .map((f) => path.join(sessionDir, f));
353
+ if (files.length === 0) return null;
354
+ files.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs);
355
+ return files[0] ?? null;
356
+ } catch {
357
+ // Session lookup is optional metadata.
358
+ return null;
359
+ }
360
+ }
361
+
362
+ function emptyUsage(): Usage {
363
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
364
+ }
365
+
366
+ function tokenUsageFromAttempts(attempts: ModelAttempt[] | undefined): TokenUsage | null {
367
+ if (!attempts || attempts.length === 0) return null;
368
+ let input = 0;
369
+ let output = 0;
370
+ for (const attempt of attempts) {
371
+ input += attempt.usage?.input ?? 0;
372
+ output += attempt.usage?.output ?? 0;
373
+ }
374
+ const total = input + output;
375
+ return total > 0 ? { input, output, total } : null;
376
+ }
377
+
378
+ function costSummaryFromAttempts(attempts: ModelAttempt[] | undefined): CostSummary | undefined {
379
+ if (!attempts || attempts.length === 0) return undefined;
380
+ let inputTokens = 0;
381
+ let outputTokens = 0;
382
+ let costUsd = 0;
383
+ for (const attempt of attempts) {
384
+ inputTokens += attempt.usage?.input ?? 0;
385
+ outputTokens += attempt.usage?.output ?? 0;
386
+ costUsd += attempt.usage?.cost ?? 0;
387
+ }
388
+ return inputTokens > 0 || outputTokens > 0 || costUsd > 0
389
+ ? { inputTokens, outputTokens, costUsd }
390
+ : undefined;
391
+ }
392
+
393
+ function appendRecentStepOutput(step: RunnerStatusStep, lines: string[]): void {
394
+ const nonEmpty = lines.filter((line) => line.trim());
395
+ if (nonEmpty.length === 0) return;
396
+ step.recentOutput ??= [];
397
+ step.recentOutput.push(...nonEmpty);
398
+ if (step.recentOutput.length > 50) {
399
+ step.recentOutput.splice(0, step.recentOutput.length - 50);
400
+ }
401
+ }
402
+
403
+ function assistantStartsToolCall(message: Message): boolean {
404
+ return Array.isArray(message.content)
405
+ && message.content.some((part) => (part as { type?: string }).type === "toolCall");
406
+ }
407
+
408
+ function isTerminalAssistantStop(message: Message): boolean {
409
+ return (message as { stopReason?: string }).stopReason === "stop" && !assistantStartsToolCall(message);
410
+ }
411
+
412
+ type UndefinedOmitted<T extends object> = {
413
+ [K in keyof T]: Exclude<T[K], undefined>;
414
+ };
415
+
416
+ function omitUndefinedProperties<const T extends object>(value: T): UndefinedOmitted<T> {
417
+ for (const key in value) {
418
+ if (value[key] === undefined) delete value[key];
419
+ }
420
+ return value as UndefinedOmitted<T>;
421
+ }
422
+
423
+ type WithUndefinedOptionals<T extends object> = {
424
+ [K in keyof T]: {} extends Pick<T, K> ? T[K] | undefined : T[K];
425
+ };
426
+
427
+ type RequiredKeysAllowingUndefined<T extends object> = {
428
+ [K in keyof T]-?: {} extends Pick<T, K> ? never : undefined extends T[K] ? K : never;
429
+ }[keyof T];
430
+
431
+ function compactOptional<T extends object>(
432
+ value: WithUndefinedOptionals<T> & (RequiredKeysAllowingUndefined<T> extends never ? unknown : never),
433
+ ): T {
434
+ for (const key of Object.keys(value) as Array<keyof T>) {
435
+ if (value[key] === undefined) delete value[key];
436
+ }
437
+ return value as T;
438
+ }
439
+
440
+ function setOptionalProperty<T extends object, K extends keyof T>(target: T, key: K, value: T[K]): void {
441
+ if (value === undefined) delete target[key];
442
+ else target[key] = value;
443
+ }
444
+
445
+ function resetStepLiveDetail(step: RunnerStatusStep): void {
446
+ delete step.currentTool;
447
+ delete step.currentToolArgs;
448
+ delete step.currentToolStartedAt;
449
+ delete step.currentPath;
450
+ step.recentTools = [];
451
+ step.recentOutput = [];
452
+ }
453
+
454
+ interface ChildEventContext {
455
+ eventsPath: string;
456
+ runId: string;
457
+ stepIndex: number;
458
+ agent: string;
459
+ }
460
+
461
+ interface ChildUsage {
462
+ input?: number;
463
+ inputTokens?: number;
464
+ output?: number;
465
+ outputTokens?: number;
466
+ cacheRead?: number;
467
+ cacheWrite?: number;
468
+ cost?: { total?: number };
469
+ }
470
+
471
+ type ChildMessage = Message & {
472
+ model?: string;
473
+ errorMessage?: string;
474
+ usage?: ChildUsage;
475
+ };
476
+
477
+ interface ChildEvent {
478
+ type?: string;
479
+ message?: ChildMessage;
480
+ toolName?: string;
481
+ args?: Record<string, unknown>;
482
+ willRetry?: unknown;
483
+ }
484
+
485
+ interface RunPiStreamingResult {
486
+ stderr: string;
487
+ exitCode: number | null;
488
+ messages: Message[];
489
+ usage: Usage;
490
+ toolCount: number;
491
+ durationMs: number;
492
+ model?: string;
493
+ error?: string;
494
+ protocolError?: ProtocolOutputLimit;
495
+ finalOutput: string;
496
+ outputState: SubagentOutputState;
497
+ interrupted?: boolean;
498
+ timedOut?: boolean;
499
+ stopped?: boolean;
500
+ turnBudget?: TurnBudgetState;
501
+ turnBudgetExceeded?: boolean;
502
+ wrapUpRequested?: boolean;
503
+ toolBudget?: ToolBudgetState;
504
+ toolBudgetBlocked?: boolean;
505
+ observedMutationAttempt?: boolean;
506
+ structuredOutputToolInvoked?: boolean;
507
+ structuredOutputMessageStartIndex?: number;
508
+ watchdog?: ChildWatchdogStateSnapshot;
509
+ runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
510
+ processInstanceId: string;
511
+ processCloseObservedAt?: number;
512
+ processSignal?: string | null;
513
+ }
514
+
515
+ function runPiStreaming(
516
+ args: string[],
517
+ cwd: string,
518
+ outputFile: string,
519
+ env?: Record<string, string | undefined>,
520
+ piPackageRoot?: string,
521
+ piArgv1?: string,
522
+ maxSubagentDepth?: number,
523
+ childEventContext?: ChildEventContext,
524
+ registerInterrupt?: (interrupt: (() => void) | undefined) => void,
525
+ onChildEvent?: (event: ChildEvent) => void,
526
+ transcriptWriter?: ChildTranscriptWriter,
527
+ registerTimeout?: (interrupt: (() => void) | undefined) => void,
528
+ timeoutMessage?: string,
529
+ registerStop?: (stop: (() => void) | undefined) => void,
530
+ stopMessage?: string,
531
+ registerTurnBudgetAbort?: (abort: ((message: string, state?: TurnBudgetState) => void) | undefined) => void,
532
+ onWriterProcess?: (writer: { state: "none" | "spawning" } | { state: "running"; pid: number }) => void,
533
+ ): Promise<RunPiStreamingResult> {
534
+ return new Promise((resolve) => {
535
+ const startedAt = Date.now();
536
+ const processInstanceId = randomUUID();
537
+ onWriterProcess?.({ state: "spawning" });
538
+ const outputStream = fs.createWriteStream(outputFile, { flags: "w" });
539
+ const spawnEnv = { ...process.env, ...(env ?? {}), ...getSubagentDepthEnv(maxSubagentDepth) };
540
+ const spawnSpec = getPiSpawnCommand(args, {
541
+ ...(piPackageRoot ? { piPackageRoot } : {}),
542
+ ...(piArgv1 ? { argv1: piArgv1 } : {}),
543
+ });
544
+ const child = spawn(spawnSpec.command, spawnSpec.args, {
545
+ cwd,
546
+ stdio: ["ignore", "pipe", "pipe"],
547
+ env: spawnEnv,
548
+ windowsHide: true,
549
+ });
550
+ const stderrTail = createBoundedByteTail();
551
+ const rawStdoutTail = createBoundedByteTail();
552
+ const messages: Message[] = [];
553
+ const usage = emptyUsage();
554
+ let model: string | undefined;
555
+ let writerRegistrationError: string | undefined;
556
+ if (typeof child.pid === "number") {
557
+ try {
558
+ onWriterProcess?.({ state: "running", pid: child.pid });
559
+ } catch (writerError) {
560
+ writerRegistrationError = `Failed to record revived Pi writer ownership: ${writerError instanceof Error ? writerError.message : String(writerError)}`;
561
+ trySignalChild(child, "SIGKILL");
562
+ }
563
+ }
564
+ let error: string | undefined = writerRegistrationError;
565
+ let assistantError: string | undefined;
566
+ let interrupted = false;
567
+ let timedOut = false;
568
+ let stopped = false;
569
+ let turnBudgetExceeded = false;
570
+ let turnBudgetMessage: string | undefined;
571
+ let turnBudget: TurnBudgetState | undefined;
572
+ let observedMutationAttempt = false;
573
+ let structuredOutputToolInvoked = false;
574
+ let structuredOutputMessageStartIndex: number | undefined;
575
+ let toolCount = 0;
576
+ const childWatchdogConfig = decodeChildWatchdogConfig(env?.[CHILD_WATCHDOG_CONFIG_ENV]);
577
+ let childWatchdogState: ChildWatchdogStateSnapshot | undefined;
578
+ let applyChildLifecycle = (_action: ChildLifecycleAction): void => {};
579
+ const updateChildWatchdogState = (snapshot: ChildWatchdogStateSnapshot): void => {
580
+ childWatchdogState = snapshot;
581
+ };
582
+
583
+ const writeOutputLine = (line: string) => {
584
+ if (!line.trim()) return;
585
+ outputStream.write(`${line}\n`);
586
+ };
587
+
588
+ const writeOutputText = (text: string) => {
589
+ for (const line of text.split("\n")) {
590
+ writeOutputLine(line);
591
+ }
592
+ };
593
+
594
+ const appendChildEvent = (event: Record<string, unknown>) => {
595
+ if (!childEventContext) return;
596
+ if (!shouldPersistChildEvent(event)) return;
597
+ appendDiagnosticJsonl(childEventContext.eventsPath, JSON.stringify({
598
+ ...event,
599
+ subagentSource: "child",
600
+ subagentRunId: childEventContext.runId,
601
+ subagentStepIndex: childEventContext.stepIndex,
602
+ subagentAgent: childEventContext.agent,
603
+ observedAt: Date.now(),
604
+ }), typeof event.type === "string" ? event.type : undefined);
605
+ };
606
+
607
+ const appendChildLine = (type: "subagent.child.stdout" | "subagent.child.stderr", line: string) => {
608
+ appendChildEvent({ type, line });
609
+ if (type === "subagent.child.stdout") transcriptWriter?.writeStdoutLine(line);
610
+ else transcriptWriter?.writeStderrLine(line);
611
+ };
612
+
613
+ const processStdoutLine = (line: string) => {
614
+ if (!line.trim()) return;
615
+ let event: ChildEvent;
616
+ try {
617
+ event = JSON.parse(line) as ChildEvent;
618
+ } catch {
619
+ rawStdoutTail.push(`${line}\n`);
620
+ writeOutputLine(line);
621
+ appendChildLine("subagent.child.stdout", line);
622
+ return;
623
+ }
624
+
625
+ appendChildEvent(event as unknown as Record<string, unknown>);
626
+ transcriptWriter?.writeChildEvent(event);
627
+ if (event.type === "agent_settled") agentSettledReceived = true;
628
+ applyChildLifecycle(projectChildLifecycle(event));
629
+
630
+ if (isChildWatchdogStatusEvent(event)) {
631
+ if (!childWatchdogConfig) return;
632
+ const next = acceptChildWatchdogEvent({
633
+ current: childWatchdogState,
634
+ event,
635
+ ...(childEventContext ? {
636
+ runId: childEventContext.runId,
637
+ agent: childEventContext.agent,
638
+ childIndex: childEventContext.stepIndex,
639
+ } : {}),
640
+ });
641
+ if (!next) return;
642
+ updateChildWatchdogState(next);
643
+ onChildEvent?.(event);
644
+ if (childWatchdogIsActive(next)) {
645
+ if (finalDrainTimer) {
646
+ clearTimeout(finalDrainTimer);
647
+ finalDrainTimer = undefined;
648
+ }
649
+ if (finalHardKillTimer) {
650
+ clearTimeout(finalHardKillTimer);
651
+ finalHardKillTimer = undefined;
652
+ }
653
+ armWatchdogTail();
654
+ } else {
655
+ clearWatchdogTailTimer();
656
+ if (cleanTerminalAssistantStopReceived || agentSettledReceived) startFinalDrain();
657
+ }
658
+ return;
659
+ }
660
+
661
+ onChildEvent?.(event);
662
+
663
+ if (event.type === "tool_execution_start" && event.toolName) {
664
+ toolCount += 1;
665
+ if (event.toolName === "structured_output") {
666
+ structuredOutputToolInvoked = true;
667
+ structuredOutputMessageStartIndex = messages.length;
668
+ }
669
+ observedMutationAttempt = observedMutationAttempt || isMutatingTool(event.toolName, event.args);
670
+ const toolArgs = extractToolArgsPreview(event.args ?? {});
671
+ writeOutputLine(toolArgs ? `${event.toolName}: ${toolArgs}` : event.toolName);
672
+ return;
673
+ }
674
+
675
+ if ((event.type === "message_end" || event.type === "tool_result_end") && event.message) {
676
+ messages.push(event.message);
677
+ const text = extractTextFromContent(event.message.content);
678
+ if (text) writeOutputText(text);
679
+
680
+ if (event.type !== "message_end" || event.message.role !== "assistant") return;
681
+ if (event.message.model) model = event.message.model;
682
+ if (event.message.errorMessage) assistantError = event.message.errorMessage;
683
+ const eventUsage = event.message.usage;
684
+ if (eventUsage) {
685
+ usage.turns++;
686
+ usage.input += eventUsage.input ?? eventUsage.inputTokens ?? 0;
687
+ usage.output += eventUsage.output ?? eventUsage.outputTokens ?? 0;
688
+ usage.cacheRead += eventUsage.cacheRead ?? 0;
689
+ usage.cacheWrite += eventUsage.cacheWrite ?? 0;
690
+ usage.cost += eventUsage.cost?.total ?? 0;
691
+ }
692
+ if (isTerminalAssistantStop(event.message)) {
693
+ if (!event.message.errorMessage && extractTextFromContent(event.message.content).trim()) assistantError = undefined;
694
+ cleanTerminalAssistantStopReceived ||= !event.message.errorMessage;
695
+ applyChildLifecycle(projectChildLifecycle(event, true));
696
+ }
697
+ }
698
+ };
699
+
700
+ // Guard both cases that can leave the parent waiting on `close` forever:
701
+ // a lingering stdio holder after `exit`, or a child that never exits.
702
+ const FINAL_STOP_GRACE_MS = 1000;
703
+ const HARD_KILL_MS = 3000;
704
+ const TIMEOUT_HARD_KILL_MS = 3000;
705
+ let childExited = false;
706
+ let forcedTerminationSignal = false;
707
+ let cleanTerminalAssistantStopReceived = false;
708
+ let agentSettledReceived = false;
709
+ let finalDrainTimer: NodeJS.Timeout | undefined;
710
+ let finalHardKillTimer: NodeJS.Timeout | undefined;
711
+ let watchdogTailTimer: NodeJS.Timeout | undefined;
712
+ let timeoutHardKillTimer: NodeJS.Timeout | undefined;
713
+ let turnBudgetTerminationTimer: NodeJS.Timeout | undefined;
714
+ let turnBudgetHardKillTimer: NodeJS.Timeout | undefined;
715
+ let protocolHardKillTimer: NodeJS.Timeout | undefined;
716
+ let protocolError: ProtocolOutputLimit | undefined;
717
+ let settled = false;
718
+ applyChildLifecycle = (action: ChildLifecycleAction): void => {
719
+ if (action === "cancel-drain") {
720
+ if (finalDrainTimer) {
721
+ clearTimeout(finalDrainTimer);
722
+ finalDrainTimer = undefined;
723
+ }
724
+ if (finalHardKillTimer) {
725
+ clearTimeout(finalHardKillTimer);
726
+ finalHardKillTimer = undefined;
727
+ }
728
+ clearWatchdogTailTimer();
729
+ return;
730
+ }
731
+ if (action === "start-drain") startFinalDrain();
732
+ };
733
+ const failProtocol = (limit: ProtocolOutputLimit): void => {
734
+ if (protocolError) return;
735
+ protocolError = limit;
736
+ error = formatProtocolOutputLimit(limit);
737
+ if (!childExited) {
738
+ trySignalChild(child, "SIGTERM");
739
+ protocolHardKillTimer = setTimeout(() => {
740
+ if (!settled) trySignalChild(child, "SIGKILL");
741
+ }, 3000);
742
+ protocolHardKillTimer.unref?.();
743
+ }
744
+ };
745
+ const stdoutReader = createBoundedLineReader({
746
+ oversizedLineProjector: PI_AGGREGATE_EVENT_PROJECTOR,
747
+ onLine: processStdoutLine,
748
+ onLimit: failProtocol,
749
+ });
750
+ const stderrReader = createBoundedLineReader({
751
+ stream: "stderr",
752
+ maxPendingLineBytes: MAX_CHILD_STDERR_BYTES,
753
+ onLine: (line) => appendChildLine("subagent.child.stderr", line),
754
+ onLimit: (limit) => appendChildLine("subagent.child.stderr", formatProtocolOutputLimit(limit)),
755
+ });
756
+ const clearStdioGuard = attachPostExitStdioGuard(child, { idleMs: 2000, hardMs: 8000 });
757
+ child.stdout.on("data", (chunk: Buffer) => stdoutReader.push(chunk));
758
+ child.stderr.on("data", (chunk: Buffer) => {
759
+ stderrTail.push(chunk);
760
+ stderrReader.push(chunk);
761
+ outputStream.write(chunk);
762
+ });
763
+ registerInterrupt?.(() => {
764
+ if (settled || timedOut || stopped) return;
765
+ interrupted = true;
766
+ if (!error) error = "Interrupted. Waiting for explicit next action.";
767
+ trySignalChild(child, "SIGINT");
768
+ setTimeout(() => {
769
+ if (!settled && !timedOut && !stopped) trySignalChild(child, "SIGTERM");
770
+ }, 1000).unref?.();
771
+ });
772
+ registerTimeout?.(() => {
773
+ if (settled || timedOut || stopped) return;
774
+ timedOut = true;
775
+ interrupted = false;
776
+ error = timeoutMessage ?? "Subagent timed out.";
777
+ trySignalChild(child, "SIGTERM");
778
+ timeoutHardKillTimer = setTimeout(() => {
779
+ if (!settled) trySignalChild(child, "SIGKILL");
780
+ }, TIMEOUT_HARD_KILL_MS);
781
+ timeoutHardKillTimer.unref?.();
782
+ });
783
+ registerStop?.(() => {
784
+ if (settled || timedOut || stopped) return;
785
+ stopped = true;
786
+ interrupted = false;
787
+ error = stopMessage ?? "Subagent stopped by user.";
788
+ trySignalChild(child, "SIGTERM");
789
+ timeoutHardKillTimer = setTimeout(() => {
790
+ if (!settled) trySignalChild(child, "SIGKILL");
791
+ }, TIMEOUT_HARD_KILL_MS);
792
+ timeoutHardKillTimer.unref?.();
793
+ });
794
+ registerTurnBudgetAbort?.((message, state) => {
795
+ if (settled || timedOut || stopped || turnBudgetExceeded) return;
796
+ turnBudgetExceeded = true;
797
+ turnBudgetMessage = message;
798
+ turnBudget = state;
799
+ interrupted = false;
800
+ error = message;
801
+ trySignalChild(child, "SIGINT");
802
+ turnBudgetTerminationTimer = setTimeout(() => {
803
+ if (!settled && !timedOut && !stopped) trySignalChild(child, "SIGTERM");
804
+ }, 1000);
805
+ turnBudgetTerminationTimer.unref?.();
806
+ turnBudgetHardKillTimer = setTimeout(() => {
807
+ if (!settled && !timedOut && !stopped) trySignalChild(child, "SIGKILL");
808
+ }, 4000);
809
+ turnBudgetHardKillTimer.unref?.();
810
+ });
811
+ const clearDrainTimers = () => {
812
+ if (finalDrainTimer) {
813
+ clearTimeout(finalDrainTimer);
814
+ finalDrainTimer = undefined;
815
+ }
816
+ if (finalHardKillTimer) {
817
+ clearTimeout(finalHardKillTimer);
818
+ finalHardKillTimer = undefined;
819
+ }
820
+ clearWatchdogTailTimer();
821
+ if (timeoutHardKillTimer) {
822
+ clearTimeout(timeoutHardKillTimer);
823
+ timeoutHardKillTimer = undefined;
824
+ }
825
+ if (turnBudgetTerminationTimer) {
826
+ clearTimeout(turnBudgetTerminationTimer);
827
+ turnBudgetTerminationTimer = undefined;
828
+ }
829
+ if (turnBudgetHardKillTimer) {
830
+ clearTimeout(turnBudgetHardKillTimer);
831
+ turnBudgetHardKillTimer = undefined;
832
+ }
833
+ if (protocolHardKillTimer) {
834
+ clearTimeout(protocolHardKillTimer);
835
+ protocolHardKillTimer = undefined;
836
+ }
837
+ };
838
+ function startFinalDrain(): void {
839
+ if (childWatchdogIsActive(childWatchdogState)) {
840
+ armWatchdogTail();
841
+ return;
842
+ }
843
+ if (childExited || finalDrainTimer || settled) return;
844
+ finalDrainTimer = setTimeout(() => {
845
+ if (settled) return;
846
+ const termSent = trySignalChild(child, "SIGTERM");
847
+ if (!termSent) return;
848
+ forcedTerminationSignal = true;
849
+ if (!cleanTerminalAssistantStopReceived && !agentSettledReceived && !error && !assistantError) {
850
+ error = `Subagent process did not exit within ${FINAL_STOP_GRACE_MS}ms after its terminal event. Forcing termination.`;
851
+ }
852
+ finalHardKillTimer = setTimeout(() => {
853
+ if (settled) return;
854
+ forcedTerminationSignal = trySignalChild(child, "SIGKILL") || forcedTerminationSignal;
855
+ }, HARD_KILL_MS);
856
+ finalHardKillTimer.unref?.();
857
+ }, FINAL_STOP_GRACE_MS);
858
+ finalDrainTimer.unref?.();
859
+ }
860
+ function clearWatchdogTailTimer(): void {
861
+ if (watchdogTailTimer) {
862
+ clearTimeout(watchdogTailTimer);
863
+ watchdogTailTimer = undefined;
864
+ }
865
+ }
866
+ function armWatchdogTail(): void {
867
+ if ((!cleanTerminalAssistantStopReceived && !agentSettledReceived) || watchdogTailTimer || settled) return;
868
+ watchdogTailTimer = setTimeout(() => {
869
+ watchdogTailTimer = undefined;
870
+ updateChildWatchdogState({
871
+ phase: "stale",
872
+ seq: (childWatchdogState?.seq ?? 0) + 1,
873
+ lastUpdate: Date.now(),
874
+ followUpPending: false,
875
+ reason: "child watchdog tail timeout",
876
+ timedOut: true,
877
+ });
878
+ startFinalDrain();
879
+ }, childWatchdogConfig?.watchdogTailTimeoutMs ?? 120_000);
880
+ watchdogTailTimer.unref?.();
881
+ }
882
+ child.on("exit", () => {
883
+ childExited = true;
884
+ clearDrainTimers();
885
+ });
886
+ child.on("close", (exitCode, signal) => {
887
+ settled = true;
888
+ const processCloseObservedAt = Date.now();
889
+ try {
890
+ onWriterProcess?.({ state: "none" });
891
+ } catch {
892
+ // The runner still owns and releases the lease during finalization.
893
+ }
894
+ registerInterrupt?.(undefined);
895
+ registerTimeout?.(undefined);
896
+ registerStop?.(undefined);
897
+ registerTurnBudgetAbort?.(undefined);
898
+ clearDrainTimers();
899
+ clearStdioGuard();
900
+ stdoutReader.end();
901
+ stderrReader.end();
902
+ outputStream.end();
903
+ const stderr = stderrTail.text();
904
+ const finalOutput = getFinalOutput(messages) || rawStdoutTail.text().trim();
905
+ const finalError = error ?? assistantError;
906
+ const forcedDrainAfterFinalSuccess = Boolean(forcedTerminationSignal || signal) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !finalError;
907
+ const signalError = isUnexplainedProcessSignal({
908
+ processSignal: signal,
909
+ interrupted,
910
+ timedOut,
911
+ stopped,
912
+ turnBudgetExceeded,
913
+ forcedDrainAfterFinalSuccess,
914
+ }) ? formatProcessSignalError(signal!) : undefined;
915
+ resolve(omitUndefinedProperties({
916
+ stderr,
917
+ exitCode: timedOut || stopped ? 1 : turnBudgetExceeded ? 1 : interrupted || forcedDrainAfterFinalSuccess ? 0 : forcedTerminationSignal || signal ? (exitCode ?? 1) : exitCode,
918
+ messages,
919
+ usage,
920
+ toolCount,
921
+ durationMs: Date.now() - startedAt,
922
+ model,
923
+ error: stopped ? (stopMessage ?? "Subagent stopped by user.") : timedOut ? (timeoutMessage ?? "Subagent timed out.") : turnBudgetExceeded ? turnBudgetMessage : interrupted || forcedDrainAfterFinalSuccess ? undefined : finalError ?? signalError,
924
+ protocolError,
925
+ finalOutput: (timedOut || stopped) && !finalOutput.trim() ? (stopped ? stopMessage ?? "Subagent stopped by user." : timeoutMessage ?? "Subagent timed out.") : finalOutput,
926
+ outputState: finalOutput.trim() ? "present" : "absent",
927
+ interrupted,
928
+ timedOut,
929
+ stopped,
930
+ turnBudget,
931
+ turnBudgetExceeded,
932
+ wrapUpRequested: turnBudget?.outcome === "wrap-up-requested" || turnBudget?.outcome === "termination-deferred" || turnBudgetExceeded || undefined,
933
+ observedMutationAttempt,
934
+ structuredOutputToolInvoked,
935
+ structuredOutputMessageStartIndex,
936
+ watchdog: childWatchdogState,
937
+ processInstanceId,
938
+ processCloseObservedAt,
939
+ processSignal: signal,
940
+ }));
941
+ });
942
+
943
+ child.on("error", (spawnError) => {
944
+ settled = true;
945
+ try {
946
+ onWriterProcess?.({ state: "none" });
947
+ } catch {
948
+ // The runner still owns and releases the lease during finalization.
949
+ }
950
+ registerInterrupt?.(undefined);
951
+ registerTimeout?.(undefined);
952
+ registerStop?.(undefined);
953
+ registerTurnBudgetAbort?.(undefined);
954
+ clearDrainTimers();
955
+ clearStdioGuard();
956
+ stdoutReader.end();
957
+ stderrReader.end();
958
+ outputStream.end();
959
+ const stderr = stderrTail.text();
960
+ const finalOutput = getFinalOutput(messages) || rawStdoutTail.text().trim();
961
+ const spawnErrorMessage = spawnError instanceof Error ? spawnError.message : String(spawnError);
962
+ resolve(omitUndefinedProperties({ stderr, exitCode: 1, messages, usage, toolCount, durationMs: Date.now() - startedAt, model, error: stopped ? (stopMessage ?? "Subagent stopped by user.") : timedOut ? (timeoutMessage ?? "Subagent timed out.") : turnBudgetExceeded ? turnBudgetMessage : error ?? assistantError ?? spawnErrorMessage, protocolError, finalOutput: (timedOut || stopped) && !finalOutput.trim() ? (stopped ? stopMessage ?? "Subagent stopped by user." : timeoutMessage ?? "Subagent timed out.") : finalOutput, outputState: finalOutput.trim() ? "present" : "absent", timedOut, stopped, turnBudget, turnBudgetExceeded, wrapUpRequested: turnBudget?.outcome === "wrap-up-requested" || turnBudget?.outcome === "termination-deferred" || turnBudgetExceeded || undefined, observedMutationAttempt, structuredOutputToolInvoked, structuredOutputMessageStartIndex, watchdog: childWatchdogState, processInstanceId }));
963
+ });
964
+ });
965
+ }
966
+
967
+ function resolvePiPackageRootFallback(): string {
968
+ const root = resolveInstalledPiPackageRoot();
969
+ if (root) return root;
970
+ throw new Error(`Could not resolve ${PI_CODING_AGENT_PACKAGE} package root`);
971
+ }
972
+
973
+ async function exportSessionHtml(sessionFile: string, outputDir: string, piPackageRoot?: string): Promise<string> {
974
+ const pkgRoot = piPackageRoot ?? resolvePiPackageRootFallback();
975
+ const exportModulePath = path.join(pkgRoot, "dist", "core", "export-html", "index.js");
976
+ const moduleUrl = pathToFileURL(exportModulePath).href;
977
+ const mod = await import(moduleUrl);
978
+ const exportFromFile = (mod as { exportFromFile?: (inputPath: string, options?: { outputPath?: string }) => string })
979
+ .exportFromFile;
980
+ if (typeof exportFromFile !== "function") {
981
+ throw new Error("exportFromFile not available");
982
+ }
983
+ const outputPath = path.join(outputDir, `${path.basename(sessionFile, ".jsonl")}.html`);
984
+ return exportFromFile(sessionFile, { outputPath });
985
+ }
986
+
987
+ function createShareLink(htmlPath: string): { shareUrl: string; gistUrl: string } | { error: string } {
988
+ try {
989
+ const auth = spawnSync("gh", ["auth", "status"], { encoding: "utf-8" });
990
+ if (auth.status !== 0) {
991
+ return { error: "GitHub CLI is not logged in. Run 'gh auth login' first." };
992
+ }
993
+ } catch {
994
+ return { error: "GitHub CLI (gh) is not installed." };
995
+ }
996
+
997
+ try {
998
+ const result = spawnSync("gh", ["gist", "create", htmlPath], { encoding: "utf-8" });
999
+ if (result.status !== 0) {
1000
+ const err = (result.stderr || "").trim() || "Failed to create gist.";
1001
+ return { error: err };
1002
+ }
1003
+ const gistUrl = (result.stdout || "").trim();
1004
+ const gistId = gistUrl.split("/").pop();
1005
+ if (!gistId) return { error: "Failed to parse gist ID." };
1006
+ const shareUrl = `https://shittycodingagent.ai/session/?${gistId}`;
1007
+ return { shareUrl, gistUrl };
1008
+ } catch (err) {
1009
+ return { error: String(err) };
1010
+ }
1011
+ }
1012
+
1013
+ function formatDuration(ms: number): string {
1014
+ if (ms < 1000) return `${ms}ms`;
1015
+ if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
1016
+ const minutes = Math.floor(ms / 60000);
1017
+ const seconds = Math.floor((ms % 60000) / 1000);
1018
+ return `${minutes}m${seconds}s`;
1019
+ }
1020
+
1021
+ function writeRunLog(
1022
+ logPath: string,
1023
+ input: {
1024
+ id: string;
1025
+ mode: SubagentRunMode;
1026
+ cwd: string;
1027
+ startedAt: number;
1028
+ endedAt: number;
1029
+ steps: Array<{
1030
+ agent: string;
1031
+ status: string;
1032
+ durationMs?: number;
1033
+ }>;
1034
+ summary: string;
1035
+ truncated: boolean;
1036
+ artifactsDir?: string;
1037
+ sessionFile?: string;
1038
+ shareUrl?: string;
1039
+ shareError?: string;
1040
+ },
1041
+ ): void {
1042
+ const lines: string[] = [];
1043
+ lines.push(`# Subagent run ${input.id}`);
1044
+ lines.push("");
1045
+ lines.push(`- **Mode:** ${input.mode}`);
1046
+ lines.push(`- **CWD:** ${input.cwd}`);
1047
+ lines.push(`- **Started:** ${new Date(input.startedAt).toISOString()}`);
1048
+ lines.push(`- **Ended:** ${new Date(input.endedAt).toISOString()}`);
1049
+ lines.push(`- **Duration:** ${formatDuration(input.endedAt - input.startedAt)}`);
1050
+ if (input.sessionFile) lines.push(`- **Session:** ${input.sessionFile}`);
1051
+ if (input.shareUrl) lines.push(`- **Share:** ${input.shareUrl}`);
1052
+ if (input.shareError) lines.push(`- **Share error:** ${input.shareError}`);
1053
+ if (input.artifactsDir) lines.push(`- **Artifacts:** ${input.artifactsDir}`);
1054
+ lines.push("");
1055
+ lines.push("## Steps");
1056
+ lines.push("| Step | Agent | Status | Duration |");
1057
+ lines.push("| --- | --- | --- | --- |");
1058
+ input.steps.forEach((step, i) => {
1059
+ const duration = step.durationMs !== undefined ? formatDuration(step.durationMs) : "-";
1060
+ lines.push(`| ${i + 1} | ${step.agent} | ${step.status} | ${duration} |`);
1061
+ });
1062
+ lines.push("");
1063
+ lines.push("## Summary");
1064
+ if (input.truncated) {
1065
+ lines.push("_Output truncated_");
1066
+ lines.push("");
1067
+ }
1068
+ lines.push(input.summary.trim() || "(no output)");
1069
+ lines.push("");
1070
+ fs.writeFileSync(logPath, lines.join("\n"), "utf-8");
1071
+ }
1072
+
1073
+ /** Context for running a single step */
1074
+ interface SingleStepContext {
1075
+ previousOutput: string;
1076
+ outputs?: ChainOutputMap;
1077
+ placeholder: string;
1078
+ cwd: string;
1079
+ sessionEnabled: boolean;
1080
+ sessionDir?: string;
1081
+ artifactsDir?: string;
1082
+ artifactConfig?: Partial<ArtifactConfig>;
1083
+ id: string;
1084
+ flatIndex: number;
1085
+ flatStepCount: number;
1086
+ outputFile: string;
1087
+ steerInboxDir?: string;
1088
+ steerCapabilityPath?: string;
1089
+ steerAckDir?: string;
1090
+ transcriptPath?: string;
1091
+ piPackageRoot?: string;
1092
+ piArgv1?: string;
1093
+ registerInterrupt?: (interrupt: (() => void) | undefined) => void;
1094
+ registerTimeout?: (interrupt: (() => void) | undefined) => void;
1095
+ registerStop?: (stop: (() => void) | undefined) => void;
1096
+ registerTurnBudgetAbort?: (abort: ((message: string, state?: TurnBudgetState) => void) | undefined) => void;
1097
+ timeoutSignal?: AbortSignal;
1098
+ stopSignal?: AbortSignal;
1099
+ timeoutMessage?: string;
1100
+ stopMessage?: string;
1101
+ turnBudget?: ResolvedTurnBudget;
1102
+ childIntercomTarget?: string;
1103
+ orchestratorIntercomTarget?: string;
1104
+ nestedRoute?: NestedRouteInfo;
1105
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
1106
+ onAttemptStart?: (attempt: { model?: string; thinking?: string }) => void;
1107
+ onChildEvent?: (event: ChildEvent) => void;
1108
+ onWriterProcess?: (writer: { state: "none" | "spawning" } | { state: "running"; pid: number }) => void;
1109
+ onExternalProcess?: (process: ExternalProcessStatus) => void;
1110
+ skipAcceptance?: () => boolean;
1111
+ }
1112
+
1113
+ /** Run a single pi agent step, returning output and metadata */
1114
+ async function runSingleStep(
1115
+ step: SubagentStep,
1116
+ ctx: SingleStepContext,
1117
+ ): Promise<StepResult & { completionGuardTriggered?: boolean }> {
1118
+ if (step.importAsyncRoot) {
1119
+ let importTimedOut = false;
1120
+ let importStopped = false;
1121
+ ctx.registerTimeout?.(() => {
1122
+ importTimedOut = true;
1123
+ let pid: number | undefined;
1124
+ try {
1125
+ pid = readStatus(step.importAsyncRoot!.asyncDir)?.pid;
1126
+ } catch {
1127
+ pid = undefined;
1128
+ }
1129
+ try {
1130
+ deliverTimeoutRequest(omitUndefinedProperties({ asyncDir: step.importAsyncRoot!.asyncDir, pid, source: "ancestor-timeout" }));
1131
+ } catch {
1132
+ // The parent runner's own timeout result is authoritative for the attached step.
1133
+ }
1134
+ });
1135
+ ctx.registerStop?.(() => {
1136
+ importStopped = true;
1137
+ let pid: number | undefined;
1138
+ try {
1139
+ pid = readStatus(step.importAsyncRoot!.asyncDir)?.pid;
1140
+ } catch {
1141
+ pid = undefined;
1142
+ }
1143
+ try {
1144
+ deliverStopRequest(omitUndefinedProperties({ asyncDir: step.importAsyncRoot!.asyncDir, pid, source: "ancestor-stop" }));
1145
+ } catch {
1146
+ // The parent runner's own stopped result is authoritative for the attached step.
1147
+ }
1148
+ });
1149
+ try {
1150
+ const imported = await waitForImportedAsyncRoot(step.importAsyncRoot, omitUndefinedProperties({
1151
+ shouldAbort: () => importTimedOut || importStopped || ctx.timeoutSignal?.aborted === true || ctx.stopSignal?.aborted === true || ctx.skipAcceptance?.() === true,
1152
+ timeoutMessage: importStopped || ctx.stopSignal?.aborted === true ? ctx.stopMessage : ctx.timeoutMessage,
1153
+ }));
1154
+ try {
1155
+ fs.writeFileSync(ctx.outputFile, imported.output, "utf-8");
1156
+ } catch {
1157
+ // Output files are observability only for imported roots.
1158
+ }
1159
+ const stopped = importStopped || imported.stopped === true || ctx.stopSignal?.aborted === true;
1160
+ const timedOut = !stopped && (importTimedOut || imported.timedOut === true || ctx.timeoutSignal?.aborted === true || ctx.skipAcceptance?.() === true);
1161
+ const message = stopped ? ctx.stopMessage ?? "Subagent stopped by user." : ctx.timeoutMessage ?? "Subagent timed out.";
1162
+ return omitUndefinedProperties({
1163
+ agent: imported.agent,
1164
+ output: timedOut || stopped ? message : imported.output,
1165
+ exitCode: timedOut || stopped ? 1 : imported.exitCode,
1166
+ error: timedOut || stopped ? message : imported.error,
1167
+ timedOut: timedOut ? true : undefined,
1168
+ stopped: stopped ? true : undefined,
1169
+ sessionFile: imported.sessionFile,
1170
+ intercomTarget: imported.intercomTarget,
1171
+ model: imported.model,
1172
+ attemptedModels: imported.attemptedModels,
1173
+ modelAttempts: imported.modelAttempts,
1174
+ totalCost: imported.totalCost,
1175
+ structuredOutput: timedOut || stopped ? undefined : imported.structuredOutput,
1176
+ structuredOutputPath: timedOut || stopped ? undefined : imported.structuredOutputPath,
1177
+ structuredOutputSchemaPath: timedOut || stopped ? undefined : imported.structuredOutputSchemaPath,
1178
+ acceptance: timedOut || stopped ? undefined : imported.acceptance,
1179
+ });
1180
+ } finally {
1181
+ ctx.registerTimeout?.(undefined);
1182
+ ctx.registerStop?.(undefined);
1183
+ }
1184
+ }
1185
+
1186
+ const effectiveStructuredOutput = step.structuredOutput ?? (step.structuredOutputSchema
1187
+ ? createStructuredOutputRuntime(step.structuredOutputSchema, path.join(path.dirname(ctx.outputFile), "structured-output"))
1188
+ : undefined);
1189
+ const placeholderRegex = new RegExp(ctx.placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
1190
+ let task = step.task.replace(placeholderRegex, () => ctx.previousOutput);
1191
+ if (ctx.outputs) task = resolveOutputReferences(task, ctx.outputs);
1192
+ const taskForCompletionGuard = task;
1193
+ if (step.effectiveAcceptance) {
1194
+ const acceptancePrompt = formatAcceptancePrompt(step.effectiveAcceptance, { reportOptional: isAgentContractV1(step.agentContract) });
1195
+ if (acceptancePrompt) task = `${task}\n${acceptancePrompt}`;
1196
+ }
1197
+ const sessionEnabled = Boolean(step.sessionFile) || ctx.sessionEnabled;
1198
+ const sessionDir = step.sessionFile ? undefined : ctx.sessionDir;
1199
+
1200
+ let artifactPaths: ArtifactPaths | undefined;
1201
+ let transcriptWriter: ChildTranscriptWriter | undefined;
1202
+ if (ctx.artifactsDir && ctx.artifactConfig?.enabled !== false) {
1203
+ const index = ctx.flatStepCount > 1 ? ctx.flatIndex : undefined;
1204
+ artifactPaths = getArtifactPaths(ctx.artifactsDir, ctx.id, step.agent, index);
1205
+ fs.mkdirSync(ctx.artifactsDir, { recursive: true });
1206
+ if (ctx.artifactConfig?.includeInput !== false) {
1207
+ fs.writeFileSync(artifactPaths.inputPath, `# Task for ${step.agent}\n\n${task}`, "utf-8");
1208
+ }
1209
+ if (ctx.artifactConfig?.includeTranscript !== false) {
1210
+ transcriptWriter = createChildTranscriptWriter({
1211
+ transcriptPath: artifactPaths.transcriptPath,
1212
+ source: "async",
1213
+ runId: ctx.id,
1214
+ agent: step.agent,
1215
+ childIndex: ctx.flatIndex,
1216
+ cwd: step.cwd ?? ctx.cwd,
1217
+ });
1218
+ }
1219
+ }
1220
+ transcriptWriter?.writeInitialUserMessage(task);
1221
+
1222
+ if (step.runner?.type === "external-cli") {
1223
+ const runner: ExternalCliRunnerStatus = {
1224
+ type: "external-cli",
1225
+ command: step.runner.command,
1226
+ args: step.runner.args ?? [],
1227
+ promptDelivery: step.runner.promptDelivery ?? "stdin",
1228
+ capabilities: { stop: true, steer: false, resume: false, structuredOutput: false, toolEvents: false },
1229
+ };
1230
+ const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
1231
+ const external = await runExternalCli(omitUndefinedProperties({
1232
+ command: runner.command,
1233
+ args: runner.args,
1234
+ cwd: step.cwd ?? ctx.cwd,
1235
+ prompt: buildExternalCliPrompt(step.systemPrompt ?? "", task),
1236
+ asyncDir: path.dirname(ctx.outputFile),
1237
+ stepIndex: ctx.flatIndex,
1238
+ registerTimeout: ctx.registerTimeout,
1239
+ registerStop: ctx.registerStop,
1240
+ timeoutMessage: ctx.timeoutMessage,
1241
+ stopMessage: ctx.stopMessage,
1242
+ onProcess: ctx.onExternalProcess,
1243
+ }));
1244
+ try { fs.writeFileSync(ctx.outputFile, external.output, "utf-8"); } catch { /* Observability output is best-effort. */ }
1245
+ const resolvedOutput = step.outputPath && external.exitCode === 0
1246
+ ? resolveSingleOutput(step.outputPath, external.output, outputSnapshot)
1247
+ : { fullOutput: external.output };
1248
+ const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, resolvedOutput.fullOutput) : undefined;
1249
+ const finalizedOutput = finalizeSingleOutput(omitUndefinedProperties({
1250
+ fullOutput: resolvedOutput.fullOutput,
1251
+ outputPath: step.outputPath,
1252
+ outputMode: step.outputMode,
1253
+ exitCode: external.exitCode ?? 1,
1254
+ savedPath: resolvedOutput.savedPath,
1255
+ outputReference,
1256
+ saveError: resolvedOutput.saveError,
1257
+ }));
1258
+ const artifactErrors = artifactPaths && ctx.artifactConfig?.enabled !== false
1259
+ ? persistStepArtifacts({
1260
+ artifactPaths,
1261
+ artifactConfig: ctx.artifactConfig,
1262
+ output: formatOutputArtifactContent(omitUndefinedProperties({ output: resolvedOutput.fullOutput, error: external.error, metadataPath: ctx.artifactConfig?.includeMetadata === false ? undefined : artifactPaths.metadataPath })),
1263
+ metadata: { runId: ctx.id, agent: step.agent, task, runner, externalProcess: external.externalProcess, exitCode: external.exitCode, error: external.error, timestamp: Date.now() },
1264
+ })
1265
+ : {};
1266
+ return omitUndefinedProperties({
1267
+ agent: step.agent,
1268
+ context: step.context,
1269
+ output: finalizedOutput.displayOutput,
1270
+ outputState: external.output.trim() ? "present" : "absent",
1271
+ exitCode: external.exitCode,
1272
+ error: external.error,
1273
+ timedOut: external.timedOut,
1274
+ stopped: external.stopped,
1275
+ processSignal: external.processSignal,
1276
+ artifactPaths,
1277
+ outputSaveError: artifactErrors.outputSaveError,
1278
+ metadataSaveError: artifactErrors.metadataSaveError,
1279
+ runner,
1280
+ externalProcess: external.externalProcess,
1281
+ });
1282
+ }
1283
+
1284
+ const candidates = step.modelCandidates && step.modelCandidates.length > 0
1285
+ ? step.modelCandidates
1286
+ : step.model
1287
+ ? [step.model]
1288
+ : [undefined];
1289
+ const attemptedModels: string[] = [];
1290
+ let capabilityAudit: import("../shared/capability-ceiling.ts").SubagentCapabilityAudit | undefined;
1291
+ let launchResolvedExtensions = step.launchResolvedExtensions;
1292
+ const modelAttempts: ModelAttempt[] = [];
1293
+ const writerProcesses: Array<{ processInstanceId: string; kind: "pi-writer"; attempt: number; closeObservedAt: number; exitCode: number | null; signal: string | null }> = [];
1294
+ let writerAttemptCount = 0;
1295
+ const attemptNotes: string[] = [];
1296
+ const eventsPath = path.join(path.dirname(ctx.outputFile), "events.jsonl");
1297
+ let finalResult: RunPiStreamingResult | undefined;
1298
+ let finalOutputSnapshot: SingleOutputSnapshot | undefined;
1299
+ let completionGuardTriggeredFinal = false;
1300
+ let turnBudget = ctx.turnBudget ? initialTurnBudgetState(ctx.turnBudget) : undefined;
1301
+ let toolBudget = step.toolBudget ? initialToolBudgetState(step.toolBudget) : undefined;
1302
+ let toolBudgetBlocked = false;
1303
+ let actualLaunchContractDigest = step.launchContractDigest;
1304
+
1305
+ let modelIndex = 0;
1306
+ let startupAttemptIndex = 0;
1307
+ modelAttemptsLoop: while (modelIndex < candidates.length) {
1308
+ if (ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break;
1309
+ const candidate = candidates[modelIndex];
1310
+ ctx.onAttemptStart?.(omitUndefinedProperties({ model: candidate, thinking: resolveEffectiveThinking(candidate, step.thinking) }));
1311
+ const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
1312
+ if (effectiveStructuredOutput) {
1313
+ try {
1314
+ if (fs.existsSync(effectiveStructuredOutput.outputPath)) fs.unlinkSync(effectiveStructuredOutput.outputPath);
1315
+ } catch {
1316
+ // Missing/stale structured-output files are handled after the child exits.
1317
+ }
1318
+ }
1319
+ const watchdogConfig = resolveWatchdogConfig(step.cwd ?? ctx.cwd);
1320
+ const childWatchdog = watchdogConfig.ok
1321
+ ? resolveChildWatchdogConfig({
1322
+ config: watchdogConfig.config,
1323
+ agent: step.agent,
1324
+ runId: ctx.id,
1325
+ childIndex: ctx.flatIndex,
1326
+ })
1327
+ : undefined;
1328
+ const { args, env, tempDir, toolDiagnosticPath, runtimeAcknowledgedExtensionsPath, capabilityAudit: attemptCapabilityAudit } = buildPiArgs(omitUndefinedProperties({
1329
+ parentSessionId: step.parentSessionId,
1330
+ baseArgs: ["--mode", "json", "-p"],
1331
+ task,
1332
+ sessionEnabled,
1333
+ sessionDir,
1334
+ sessionFile: step.sessionFile,
1335
+ model: candidate,
1336
+ inheritProjectContext: step.inheritProjectContext,
1337
+ inheritSkills: step.inheritSkills,
1338
+ requireReadTool: Boolean(step.skills?.length),
1339
+ tools: step.tools,
1340
+ extensions: step.extensions,
1341
+ subagentOnlyExtensions: step.subagentOnlyExtensions,
1342
+ systemPrompt: appendTurnBudgetSystemPrompt(step.systemPrompt ?? "", ctx.turnBudget),
1343
+ systemPromptMode: step.systemPromptMode,
1344
+ mcpDirectTools: step.mcpDirectTools,
1345
+ capabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,
1346
+ cwd: step.cwd ?? ctx.cwd,
1347
+ promptFileStem: step.agent,
1348
+ intercomSessionName: ctx.childIntercomTarget,
1349
+ orchestratorIntercomTarget: ctx.orchestratorIntercomTarget,
1350
+ runId: ctx.id,
1351
+ childAgentName: step.agent,
1352
+ childIndex: ctx.flatIndex,
1353
+ parentEventSink: ctx.nestedRoute?.eventSink,
1354
+ parentControlInbox: ctx.nestedRoute?.controlInbox,
1355
+ parentRootRunId: ctx.nestedRoute?.rootRunId,
1356
+ parentCapabilityToken: ctx.nestedRoute?.capabilityToken,
1357
+ steerInboxDir: ctx.steerInboxDir,
1358
+ steerCapabilityPath: ctx.steerCapabilityPath,
1359
+ steerAckDir: ctx.steerAckDir,
1360
+ structuredOutput: effectiveStructuredOutput,
1361
+ toolBudget: step.toolBudget,
1362
+ permissionRules: step.permissionRules,
1363
+ permissionAuditPath: step.permissionRules && ctx.artifactsDir
1364
+ ? path.join(ctx.artifactsDir, "permission-audit", `${ctx.id}-${ctx.flatIndex}.jsonl`)
1365
+ : undefined,
1366
+ childWatchdog,
1367
+ waitToolEnabled: step.waitToolEnabled,
1368
+ }));
1369
+ if (step.definitionDigest) {
1370
+ const toolPlan = resolvePiLaunchToolPlan(omitUndefinedProperties({
1371
+ tools: step.tools,
1372
+ extensions: step.extensions,
1373
+ subagentOnlyExtensions: step.subagentOnlyExtensions,
1374
+ mcpDirectTools: step.mcpDirectTools,
1375
+ cwd: step.cwd ?? ctx.cwd,
1376
+ requireReadTool: Boolean(step.skills?.length),
1377
+ structuredOutput: Boolean(effectiveStructuredOutput),
1378
+ capabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,
1379
+ inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
1380
+ }));
1381
+ launchResolvedExtensions = projectLaunchResolvedChildExtensions(toolPlan);
1382
+ actualLaunchContractDigest = launchBindingDigest(omitUndefinedProperties({
1383
+ definitionDigest: step.definitionDigest,
1384
+ task: step.launchBindingTask ?? task,
1385
+ ...(candidate ? { model: candidate } : {}),
1386
+ modelCandidates: candidates as string[],
1387
+ ...(resolveEffectiveThinking(candidate, step.thinking) ? { thinking: resolveEffectiveThinking(candidate, step.thinking) } : {}),
1388
+ systemPrompt: appendTurnBudgetSystemPrompt(step.systemPrompt ?? "", ctx.turnBudget),
1389
+ systemPromptMode: step.systemPromptMode,
1390
+ inheritProjectContext: step.inheritProjectContext,
1391
+ inheritSkills: step.inheritSkills,
1392
+ skills: step.skills,
1393
+ tools: toolPlan.effectiveToolAllowlist,
1394
+ extensions: toolPlan.extensionArgs,
1395
+ mcpDirectTools: toolPlan.effectiveMcpTools,
1396
+ ...(step.outputPath ? { outputPath: step.outputPath } : {}),
1397
+ ...(step.outputMode ? { outputMode: step.outputMode } : {}),
1398
+ ...(step.structuredOutputSchema ? { structuredOutputSchema: step.structuredOutputSchema } : {}),
1399
+ }));
1400
+ }
1401
+ capabilityAudit = attemptCapabilityAudit;
1402
+ writerAttemptCount += 1;
1403
+ const run = await runPiStreaming(
1404
+ args,
1405
+ step.cwd ?? ctx.cwd,
1406
+ ctx.outputFile,
1407
+ env,
1408
+ ctx.piPackageRoot,
1409
+ ctx.piArgv1,
1410
+ step.maxSubagentDepth,
1411
+ { eventsPath, runId: ctx.id, stepIndex: ctx.flatIndex, agent: step.agent },
1412
+ ctx.registerInterrupt,
1413
+ ctx.onChildEvent,
1414
+ transcriptWriter,
1415
+ ctx.registerTimeout,
1416
+ ctx.timeoutMessage,
1417
+ ctx.registerStop,
1418
+ ctx.stopMessage,
1419
+ ctx.registerTurnBudgetAbort,
1420
+ ctx.onWriterProcess,
1421
+ );
1422
+ if (run.processCloseObservedAt !== undefined) {
1423
+ writerProcesses.push({
1424
+ processInstanceId: run.processInstanceId,
1425
+ kind: "pi-writer",
1426
+ attempt: writerAttemptCount - 1,
1427
+ closeObservedAt: run.processCloseObservedAt,
1428
+ exitCode: run.exitCode,
1429
+ signal: run.processSignal ?? null,
1430
+ });
1431
+ }
1432
+ if (run.turnBudget) turnBudget = run.turnBudget;
1433
+ else if (ctx.turnBudget) {
1434
+ const assistantMessages = run.messages.filter((message) => message.role === "assistant");
1435
+ const turnCount = assistantMessages.length;
1436
+ const lastAssistantMessage = assistantMessages.at(-1);
1437
+ if (turnCount > 0 && turnCount < ctx.turnBudget.maxTurns) {
1438
+ turnBudget = { ...ctx.turnBudget, outcome: "within-budget", turnCount };
1439
+ } else if (turnCount >= ctx.turnBudget.maxTurns) {
1440
+ const decision = turnBudgetDecision(
1441
+ ctx.turnBudget,
1442
+ turnCount,
1443
+ lastAssistantMessage ? isTerminalAssistantStop(lastAssistantMessage) : false,
1444
+ lastAssistantMessage ? assistantStartsToolCall(lastAssistantMessage) : false,
1445
+ );
1446
+ turnBudget = decision === "defer"
1447
+ ? turnBudgetDeferredState(ctx.turnBudget, turnCount)
1448
+ : turnBudgetState(ctx.turnBudget, turnCount, decision === "abort");
1449
+ }
1450
+ }
1451
+ const toolAvailabilityError = run.exitCode === 0 && !run.error
1452
+ ? readChildToolDiagnosticError(toolDiagnosticPath)
1453
+ : undefined;
1454
+ const runtimeAcknowledgedExtensions = readRuntimeAcknowledgedExtensions(runtimeAcknowledgedExtensionsPath);
1455
+ cleanupTempDir(tempDir);
1456
+
1457
+ let structuredOutput: unknown;
1458
+ let structuredError: string | undefined;
1459
+ let validatedStructuredOutput = false;
1460
+ if (effectiveStructuredOutput && run.exitCode === 0 && !run.error && !toolAvailabilityError) {
1461
+ if (!run.structuredOutputToolInvoked) {
1462
+ structuredError = MISSING_STRUCTURED_OUTPUT_CALL_ERROR;
1463
+ } else {
1464
+ const structured = await readStructuredOutput({
1465
+ schema: effectiveStructuredOutput.schema,
1466
+ schemaPath: effectiveStructuredOutput.schemaPath,
1467
+ outputPath: effectiveStructuredOutput.outputPath,
1468
+ });
1469
+ if (structured.error) structuredError = structured.error;
1470
+ else {
1471
+ structuredOutput = structured.value;
1472
+ validatedStructuredOutput = true;
1473
+ }
1474
+ }
1475
+ }
1476
+ const errorMessages = validatedStructuredOutput
1477
+ ? run.messages.slice(run.structuredOutputMessageStartIndex ?? run.messages.length)
1478
+ : run.messages;
1479
+ const hiddenError = run.exitCode === 0 && !run.error && !toolAvailabilityError && !structuredError
1480
+ ? detectSubagentError(errorMessages)
1481
+ : null;
1482
+ const emptyOutputError = run.exitCode === 0
1483
+ && !run.error
1484
+ && !toolAvailabilityError
1485
+ && !structuredError
1486
+ && !run.finalOutput.trim()
1487
+ && !validatedStructuredOutput
1488
+ && (!hiddenError?.hasError || hasEmptyTerminalAssistantResponse(run.messages))
1489
+ ? "Subagent produced no output (possible model cold-start or empty response)."
1490
+ : undefined;
1491
+ const completionGuardEnabled = isAgentContractV1(step.agentContract) ? step.completionGuard === true : step.completionGuard !== false;
1492
+ const completionGuard = run.exitCode === 0 && !run.error && !toolAvailabilityError && !structuredError && !hiddenError?.hasError && !emptyOutputError && completionGuardEnabled
1493
+ ? evaluateCompletionMutationGuard(omitUndefinedProperties({
1494
+ agent: step.agent,
1495
+ task: taskForCompletionGuard,
1496
+ messages: run.messages,
1497
+ tools: step.tools,
1498
+ mcpDirectTools: step.mcpDirectTools,
1499
+ }))
1500
+ : undefined;
1501
+ const completionGuardTriggered = completionGuard?.triggered === true && !run.observedMutationAttempt;
1502
+ const fileMutationEffect = completionGuard
1503
+ ? {
1504
+ status: completionGuard.expectedMutation ? completionGuardTriggered ? "missing" as const : "observed" as const : "not-applicable" as const,
1505
+ expected: completionGuard.expectedMutation,
1506
+ attempted: completionGuard.attemptedMutation || run.observedMutationAttempt === true,
1507
+ ...(completionGuardTriggered ? { message: "Subagent completed without making edits for an implementation task." } : {}),
1508
+ }
1509
+ : undefined;
1510
+ const completionGuardError = completionGuardTriggered && !isAgentContractV1(step.agentContract)
1511
+ ? "Subagent completed without making edits for an implementation task.\nIt appears to have returned planning or scratchpad output instead of applying changes."
1512
+ : undefined;
1513
+ const effectiveExitCode = toolAvailabilityError || (completionGuardTriggered && !isAgentContractV1(step.agentContract)) || structuredError || emptyOutputError
1514
+ ? 1
1515
+ : hiddenError?.hasError
1516
+ ? (hiddenError.exitCode ?? 1)
1517
+ : run.error && run.exitCode === 0
1518
+ ? 1
1519
+ : run.exitCode;
1520
+ const signalError = run.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
1521
+ processSignal: run.processSignal,
1522
+ interrupted: run.interrupted,
1523
+ timedOut: run.timedOut,
1524
+ stopped: run.stopped,
1525
+ turnBudgetExceeded: run.turnBudgetExceeded,
1526
+ })) ? formatProcessSignalError(run.processSignal!) : undefined;
1527
+ const error = toolAvailabilityError
1528
+ ?? completionGuardError
1529
+ ?? structuredError
1530
+ ?? emptyOutputError
1531
+ ?? (hiddenError?.hasError
1532
+ ? hiddenError.details
1533
+ ? `${hiddenError.errorType} failed (exit ${effectiveExitCode}): ${hiddenError.details}`
1534
+ : `${hiddenError.errorType} failed with exit code ${effectiveExitCode}`
1535
+ : run.error || signalError || (run.exitCode !== 0 && run.stderr.trim() ? run.stderr.trim() : undefined));
1536
+ const attempt: ModelAttempt = omitUndefinedProperties({
1537
+ model: candidate ?? run.model ?? step.model ?? "default",
1538
+ success: effectiveExitCode === 0 && !error,
1539
+ exitCode: effectiveExitCode,
1540
+ error,
1541
+ usage: run.usage,
1542
+ });
1543
+ modelAttempts.push(attempt);
1544
+ if (candidate && startupAttemptIndex === 0) attemptedModels.push(candidate);
1545
+ completionGuardTriggeredFinal = completionGuardTriggered;
1546
+ finalOutputSnapshot = outputSnapshot;
1547
+ if (step.toolBudget) {
1548
+ const toolMessages = run.messages.filter((message) => message.role === "toolResult");
1549
+ const blockedMessage = toolMessages.find((message) => extractTextFromContent(message.content).includes("Tool budget hard limit reached"));
1550
+ toolBudgetBlocked = Boolean(blockedMessage);
1551
+ toolBudget = toolBudgetState(step.toolBudget, toolMessages.length, blockedMessage ? (blockedMessage as { toolName?: string }).toolName : undefined);
1552
+ }
1553
+ finalResult = { ...run, exitCode: effectiveExitCode, model: candidate ?? run.model, error, structuredOutput, runtimeAcknowledgedExtensions, ...(step.agentContract ? { agentContract: step.agentContract } : {}), ...(fileMutationEffect ? { effects: { fileMutation: fileMutationEffect } } : {}) } as RunPiStreamingResult & { structuredOutput?: unknown; agentContract?: import("../../shared/types.ts").AgentContract; effects?: import("../../shared/types.ts").EffectsProjection };
1554
+ if (run.turnBudgetExceeded) break modelAttemptsLoop;
1555
+ if (run.stopped || run.timedOut || ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break modelAttemptsLoop;
1556
+ if (attempt.success || completionGuardTriggered) break modelAttemptsLoop;
1557
+
1558
+ const startupFailure = isRetryableSubagentStartupFailure(omitUndefinedProperties({
1559
+ exitCode: effectiveExitCode,
1560
+ error,
1561
+ finalOutput: run.finalOutput,
1562
+ messageCount: run.messages.length,
1563
+ toolCount: run.toolCount,
1564
+ usage: run.usage,
1565
+ durationMs: run.durationMs,
1566
+ protocolError: run.protocolError,
1567
+ processSignal: run.processSignal,
1568
+ observedMutationAttempt: run.observedMutationAttempt,
1569
+ interrupted: run.interrupted,
1570
+ timedOut: run.timedOut,
1571
+ stopped: run.stopped,
1572
+ turnBudgetExceeded: run.turnBudgetExceeded,
1573
+ }));
1574
+ const retryDelayMs = SUBAGENT_STARTUP_RETRY_DELAYS_MS[startupAttemptIndex];
1575
+ if (startupFailure && retryDelayMs !== undefined) {
1576
+ const retryNote = formatSubagentStartupRetryNote({
1577
+ model: attempt.model,
1578
+ attempt: startupAttemptIndex + 1,
1579
+ maxAttempts: SUBAGENT_STARTUP_RETRY_DELAYS_MS.length + 1,
1580
+ delayMs: retryDelayMs,
1581
+ });
1582
+ const shouldRetry = await waitForSubagentStartupRetry(retryDelayMs, [ctx.timeoutSignal, ctx.stopSignal]);
1583
+ if (!shouldRetry || ctx.skipAcceptance?.()) break modelAttemptsLoop;
1584
+ attempt.error = retryNote;
1585
+ attemptNotes.push(retryNote);
1586
+ startupAttemptIndex += 1;
1587
+ continue;
1588
+ }
1589
+ if (startupFailure) {
1590
+ const startupError = formatSubagentStartupRetryExhaustedError({
1591
+ model: attempt.model,
1592
+ attempts: startupAttemptIndex + 1,
1593
+ });
1594
+ attempt.error = startupError;
1595
+ finalResult.error = startupError;
1596
+ finalResult.finalOutput = startupError;
1597
+ break modelAttemptsLoop;
1598
+ }
1599
+ if (!isRetryableModelFailure(error) || modelIndex === candidates.length - 1) break modelAttemptsLoop;
1600
+ attemptNotes.push(formatModelAttemptNote(attempt, candidates[modelIndex + 1]));
1601
+ modelIndex += 1;
1602
+ startupAttemptIndex = 0;
1603
+ }
1604
+
1605
+ const rawOutput = finalResult?.finalOutput ?? "";
1606
+ const outputForPersistence = stripAcceptanceReport(rawOutput);
1607
+ const resolvedOutput = step.outputPath && finalResult?.exitCode === 0
1608
+ ? resolveSingleOutput(step.outputPath, outputForPersistence, finalOutputSnapshot)
1609
+ : { fullOutput: outputForPersistence };
1610
+ const output = stripAcceptanceReport(resolvedOutput.fullOutput);
1611
+ const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, output) : undefined;
1612
+ let outputForSummary = output;
1613
+ if (attemptNotes.length > 0) {
1614
+ outputForSummary = `${attemptNotes.join("\n")}\n\n${outputForSummary}`.trim();
1615
+ }
1616
+ if (finalResult?.stopped && !outputForSummary.trim()) {
1617
+ outputForSummary = ctx.stopMessage ?? "Subagent stopped by user.";
1618
+ } else if (!finalResult?.timedOut && !finalResult?.stopped && finalResult?.turnBudgetExceeded && turnBudget) {
1619
+ outputForSummary = formatTurnBudgetOutput(turnBudgetExceededMessage(turnBudget, turnBudget.turnCount), outputForSummary);
1620
+ } else if (!finalResult?.timedOut && !finalResult?.stopped && turnBudget?.outcome === "termination-deferred") {
1621
+ const note = turnBudgetDeferredNote(turnBudget, turnBudget.terminationDeferredAtTurn ?? turnBudget.turnCount);
1622
+ outputForSummary = outputForSummary.trim() ? `${note}\n\n${outputForSummary}` : note;
1623
+ } else if (!finalResult?.timedOut && !finalResult?.stopped && turnBudget?.outcome === "wrap-up-requested") {
1624
+ const note = turnBudgetSoftNote(turnBudget, turnBudget.wrapUpRequestedAtTurn ?? turnBudget.turnCount);
1625
+ outputForSummary = outputForSummary.trim() ? `${note}\n\n${outputForSummary}` : note;
1626
+ }
1627
+ const outputForAcceptance = rawOutput;
1628
+ const childWrittenOutput = step.outputPath
1629
+ ? extractChildWrittenOutput(finalResult?.messages, step.outputPath, step.cwd ?? ctx.cwd)
1630
+ : undefined;
1631
+ const outputState: SubagentOutputState = finalResult?.outputState === "present"
1632
+ || (finalResult as (RunPiStreamingResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput !== undefined
1633
+ || Boolean(childWrittenOutput?.trim())
1634
+ ? "present"
1635
+ : resolvedOutput.savedPath
1636
+ ? "unknown"
1637
+ : finalResult?.outputState ?? "unknown";
1638
+ const finalizedOutput = finalizeSingleOutput(omitUndefinedProperties({
1639
+ fullOutput: outputForSummary,
1640
+ outputPath: step.outputPath,
1641
+ outputMode: step.outputMode,
1642
+ exitCode: finalResult?.exitCode ?? 1,
1643
+ savedPath: resolvedOutput.savedPath,
1644
+ outputReference,
1645
+ saveError: resolvedOutput.saveError,
1646
+ }));
1647
+ outputForSummary = finalizedOutput.displayOutput;
1648
+ const acceptance = step.effectiveAcceptance && !finalResult?.stopped && !finalResult?.turnBudgetExceeded && !ctx.timeoutSignal?.aborted && !ctx.stopSignal?.aborted && !ctx.skipAcceptance?.()
1649
+ ? await evaluateAcceptance(omitUndefinedProperties({
1650
+ acceptance: step.effectiveAcceptance,
1651
+ output: outputForAcceptance,
1652
+ fileOutput: childWrittenOutput !== undefined && step.outputPath
1653
+ ? { content: childWrittenOutput, path: step.outputPath, authoritative: step.outputMode === "file-only" }
1654
+ : undefined,
1655
+ cwd: step.cwd ?? ctx.cwd,
1656
+ signal: combinedAbortSignal([ctx.timeoutSignal, ctx.stopSignal]),
1657
+ abortMessage: ctx.stopSignal?.aborted ? ctx.stopMessage ?? "Subagent stopped by user." : ctx.timeoutMessage ?? "Subagent timed out.",
1658
+ reportOptional: isAgentContractV1(step.agentContract),
1659
+ artifactsDir: ctx.artifactsDir,
1660
+ runId: ctx.id,
1661
+ }))
1662
+ : undefined;
1663
+ const stoppedAfterAcceptance = finalResult?.stopped === true || ctx.stopSignal?.aborted === true;
1664
+ const timedOutAfterAcceptance = !stoppedAfterAcceptance && (finalResult?.timedOut === true || ctx.timeoutSignal?.aborted === true);
1665
+ const turnBudgetExceeded = finalResult?.turnBudgetExceeded === true;
1666
+ const effectiveAcceptance = step.effectiveAcceptance
1667
+ ? stoppedAfterAcceptance
1668
+ ? buildSkippedAcceptanceLedger(step.effectiveAcceptance, { id: "stopped", message: "Acceptance was not evaluated because the subagent was stopped." })
1669
+ : timedOutAfterAcceptance
1670
+ ? buildSkippedAcceptanceLedger(step.effectiveAcceptance, { id: "timeout", message: "Acceptance was not evaluated because the subagent timed out." })
1671
+ : turnBudgetExceeded
1672
+ ? buildSkippedAcceptanceLedger(step.effectiveAcceptance, { id: "turn-budget", message: "Acceptance was not evaluated because the subagent exceeded its turn budget." })
1673
+ : acceptance
1674
+ : undefined;
1675
+ const acceptanceFailure = effectiveAcceptance ? acceptanceFailureMessage(effectiveAcceptance) : undefined;
1676
+ const acceptanceCanFailRun = acceptanceFailure && effectiveAcceptance?.explicit && (finalResult?.exitCode ?? 1) === 0 && !finalResult?.interrupted && !timedOutAfterAcceptance && !stoppedAfterAcceptance && !turnBudgetExceeded && !isAgentContractV1(step.agentContract);
1677
+ const effectiveFinalExitCode = timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? 1 : acceptanceCanFailRun ? 1 : finalResult?.exitCode ?? 1;
1678
+ const effectiveFinalError = stoppedAfterAcceptance
1679
+ ? ctx.stopMessage ?? "Subagent stopped by user."
1680
+ : timedOutAfterAcceptance
1681
+ ? ctx.timeoutMessage ?? "Subagent timed out."
1682
+ : turnBudgetExceeded
1683
+ ? finalResult?.error ?? (turnBudget ? turnBudgetExceededMessage(turnBudget, turnBudget.turnCount) : "Subagent exceeded turn budget.")
1684
+ : acceptanceCanFailRun
1685
+ ? (finalResult?.error ? `${finalResult.error}\n${acceptanceFailure}` : acceptanceFailure)
1686
+ : finalResult?.error;
1687
+
1688
+ const artifactErrors = artifactPaths && ctx.artifactConfig?.enabled !== false
1689
+ ? persistStepArtifacts({
1690
+ artifactPaths,
1691
+ artifactConfig: ctx.artifactConfig,
1692
+ output: formatOutputArtifactContent(omitUndefinedProperties({
1693
+ output,
1694
+ error: effectiveFinalError,
1695
+ transcriptPath: transcriptWriter ? artifactPaths.transcriptPath : undefined,
1696
+ metadataPath: ctx.artifactConfig?.includeMetadata === false ? undefined : artifactPaths.metadataPath,
1697
+ })),
1698
+ metadata: {
1699
+ runId: ctx.id,
1700
+ agent: step.agent,
1701
+ task,
1702
+ exitCode: effectiveFinalExitCode,
1703
+ model: finalResult?.model,
1704
+ attemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,
1705
+ modelAttempts,
1706
+ error: effectiveFinalError,
1707
+ acceptance: effectiveAcceptance,
1708
+ ...(capabilityAudit ? { capabilityCeiling: capabilityAudit.ceiling, capabilityAudit } : {}),
1709
+ launchContractDigest: actualLaunchContractDigest,
1710
+ launchResolvedExtensions,
1711
+ ...((finalResult as (RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }) | undefined)?.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: (finalResult as RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }).runtimeAcknowledgedExtensions } : {}),
1712
+ ...(transcriptWriter ? { transcriptPath: artifactPaths.transcriptPath } : {}),
1713
+ transcriptError: transcriptWriter?.getError(),
1714
+ skills: step.skills,
1715
+ timestamp: Date.now(),
1716
+ },
1717
+ })
1718
+ : {};
1719
+
1720
+ const result: StepResult & { completionGuardTriggered?: boolean } = omitUndefinedProperties({
1721
+ agent: step.agent,
1722
+ context: step.context,
1723
+ ...(step.agentContract ? { agentContract: step.agentContract } : {}),
1724
+ launchContractDigest: actualLaunchContractDigest,
1725
+ output: outputForSummary,
1726
+ outputState,
1727
+ exitCode: effectiveFinalExitCode,
1728
+ error: effectiveFinalError,
1729
+ protocolError: finalResult?.protocolError,
1730
+ sessionFile: step.sessionFile,
1731
+ intercomTarget: ctx.childIntercomTarget,
1732
+ model: finalResult?.model,
1733
+ attemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,
1734
+ modelAttempts,
1735
+ totalCost: costSummaryFromAttempts(modelAttempts),
1736
+ artifactPaths,
1737
+ outputSaveError: artifactErrors.outputSaveError,
1738
+ metadataSaveError: artifactErrors.metadataSaveError,
1739
+ transcriptPath: transcriptWriter ? artifactPaths?.transcriptPath : undefined,
1740
+ transcriptError: transcriptWriter?.getError(),
1741
+ interrupted: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? false : finalResult?.interrupted,
1742
+ timedOut: timedOutAfterAcceptance ? true : finalResult?.timedOut,
1743
+ stopped: stoppedAfterAcceptance ? true : finalResult?.stopped,
1744
+ processSignal: finalResult?.processSignal,
1745
+ turnBudget,
1746
+ turnBudgetExceeded: turnBudgetExceeded || undefined,
1747
+ wrapUpRequested: finalResult?.wrapUpRequested || turnBudget?.outcome === "wrap-up-requested" || turnBudget?.outcome === "termination-deferred" || turnBudgetExceeded || undefined,
1748
+ toolBudget,
1749
+ toolBudgetBlocked: toolBudgetBlocked || undefined,
1750
+ completionGuardTriggered: completionGuardTriggeredFinal,
1751
+ ...((finalResult as (RunPiStreamingResult & { effects?: import("../../shared/types.ts").EffectsProjection }) | undefined)?.effects ? { effects: (finalResult as RunPiStreamingResult & { effects?: import("../../shared/types.ts").EffectsProjection }).effects } : {}),
1752
+ structuredOutput: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? undefined : (finalResult as (RunPiStreamingResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput,
1753
+ structuredOutputPath: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? undefined : effectiveStructuredOutput?.outputPath,
1754
+ structuredOutputSchemaPath: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? undefined : effectiveStructuredOutput?.schemaPath,
1755
+ acceptance: effectiveAcceptance,
1756
+ watchdog: finalResult?.watchdog,
1757
+ ...(capabilityAudit ? { capabilityCeiling: capabilityAudit.ceiling, capabilityAudit } : {}),
1758
+ launchResolvedExtensions,
1759
+ ...((finalResult as (RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }) | undefined)?.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: (finalResult as RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }).runtimeAcknowledgedExtensions } : {}),
1760
+ writerProcesses,
1761
+ writerAttemptCount,
1762
+ });
1763
+ return isAgentContractV1(step.agentContract) ? attachContractProjections(result as unknown as import("../../shared/types.ts").SingleResult) as unknown as typeof result : result;
1764
+ }
1765
+
1766
+ type RunnerStatusStep = NonNullable<AsyncStatus["steps"]>[number] & {
1767
+ exitCode?: number | null;
1768
+ description?: string;
1769
+ };
1770
+
1771
+ function externalRunnerStatus(runner: SubagentStep["runner"]): ExternalCliRunnerStatus | undefined {
1772
+ if (runner?.type !== "external-cli") return undefined;
1773
+ return {
1774
+ type: "external-cli",
1775
+ command: runner.command,
1776
+ args: runner.args ?? [],
1777
+ promptDelivery: runner.promptDelivery ?? "stdin",
1778
+ capabilities: { stop: true, steer: false, resume: false, structuredOutput: false, toolEvents: false },
1779
+ };
1780
+ }
1781
+
1782
+ function appendCapabilityCeilingAppliedEvent(eventsPath: string, runId: string, stepIndex: number, agent: string, result: StepResult): void {
1783
+ if (!result.capabilityCeiling) return;
1784
+ appendJsonl(eventsPath, JSON.stringify({
1785
+ type: "subagent.capability-ceiling.applied",
1786
+ ts: Date.now(),
1787
+ runId,
1788
+ stepIndex,
1789
+ agent,
1790
+ capabilityCeiling: result.capabilityCeiling,
1791
+ ...(result.capabilityAudit ? { capabilityAudit: result.capabilityAudit } : {}),
1792
+ }));
1793
+ }
1794
+
1795
+ type RunnerStatusPayload = Omit<AsyncStatus, "steps" | "parallelGroups" | "pid" | "cwd" | "currentStep" | "chainStepCount" | "lastUpdate"> & {
1796
+ pid: number;
1797
+ cwd: string;
1798
+ currentStep: number;
1799
+ chainStepCount: number;
1800
+ parallelGroups: AsyncParallelGroupStatus[];
1801
+ steps: RunnerStatusStep[];
1802
+ lastUpdate: number;
1803
+ artifactsDir?: string;
1804
+ shareUrl?: string;
1805
+ gistUrl?: string;
1806
+ shareError?: string;
1807
+ error?: string;
1808
+ };
1809
+
1810
+ function requiredStatusStep(statusPayload: RunnerStatusPayload, index: number): RunnerStatusStep {
1811
+ const step = statusPayload.steps[index];
1812
+ if (!step) throw new Error(`Missing status step at index ${index}`);
1813
+ return step;
1814
+ }
1815
+
1816
+ function markParallelGroupSetupFailure(input: {
1817
+ statusPayload: RunnerStatusPayload;
1818
+ results: StepResult[];
1819
+ group: Extract<RunnerStep, { parallel: SubagentStep[] }>;
1820
+ groupStartFlatIndex: number;
1821
+ setupError: string;
1822
+ failedAt: number;
1823
+ statusPath: string;
1824
+ eventsPath: string;
1825
+ asyncDir: string;
1826
+ runId: string;
1827
+ stepIndex: number;
1828
+ }): void {
1829
+ for (let taskIndex = 0; taskIndex < input.group.parallel.length; taskIndex++) {
1830
+ const flatTaskIndex = input.groupStartFlatIndex + taskIndex;
1831
+ const statusStep = requiredStatusStep(input.statusPayload, flatTaskIndex);
1832
+ const task = input.group.parallel[taskIndex];
1833
+ if (!task) throw new Error(`Missing parallel task at index ${taskIndex}`);
1834
+ statusStep.status = "failed";
1835
+ statusStep.startedAt = input.failedAt;
1836
+ statusStep.endedAt = input.failedAt;
1837
+ statusStep.durationMs = 0;
1838
+ statusStep.exitCode = 1;
1839
+ input.results.push(omitUndefinedProperties({ agent: task.agent, context: task.context, output: input.setupError, success: false, exitCode: 1, sessionFile: task.sessionFile }));
1840
+ }
1841
+ input.statusPayload.currentStep = input.groupStartFlatIndex;
1842
+ input.statusPayload.lastUpdate = input.failedAt;
1843
+ input.statusPayload.outputFile = path.join(input.asyncDir, `output-${input.groupStartFlatIndex}.log`);
1844
+ writeAtomicJson(input.statusPath, input.statusPayload);
1845
+ appendJsonl(input.eventsPath, JSON.stringify({
1846
+ type: "subagent.parallel.completed",
1847
+ ts: input.failedAt,
1848
+ runId: input.runId,
1849
+ stepIndex: input.stepIndex,
1850
+ success: false,
1851
+ }));
1852
+ }
1853
+
1854
+ function markParallelGroupRunning(input: {
1855
+ statusPayload: RunnerStatusPayload;
1856
+ group: Extract<RunnerStep, { parallel: SubagentStep[] }>;
1857
+ groupStartFlatIndex: number;
1858
+ groupStartTime: number;
1859
+ statusPath: string;
1860
+ eventsPath: string;
1861
+ asyncDir: string;
1862
+ runId: string;
1863
+ stepIndex: number;
1864
+ }): void {
1865
+ for (let taskIndex = 0; taskIndex < input.group.parallel.length; taskIndex++) {
1866
+ const flatTaskIndex = input.groupStartFlatIndex + taskIndex;
1867
+ const statusStep = requiredStatusStep(input.statusPayload, flatTaskIndex);
1868
+ statusStep.status = "pending";
1869
+ delete statusStep.startedAt;
1870
+ delete statusStep.endedAt;
1871
+ delete statusStep.durationMs;
1872
+ delete statusStep.lastActivityAt;
1873
+ delete statusStep.activityState;
1874
+ delete statusStep.error;
1875
+ }
1876
+ input.statusPayload.currentStep = input.groupStartFlatIndex;
1877
+ delete input.statusPayload.activityState;
1878
+ input.statusPayload.lastActivityAt = input.groupStartTime;
1879
+ input.statusPayload.lastUpdate = input.groupStartTime;
1880
+ input.statusPayload.outputFile = path.join(input.asyncDir, `output-${input.groupStartFlatIndex}.log`);
1881
+ writeAtomicJson(input.statusPath, input.statusPayload);
1882
+ appendJsonl(input.eventsPath, JSON.stringify({
1883
+ type: "subagent.parallel.started",
1884
+ ts: input.groupStartTime,
1885
+ runId: input.runId,
1886
+ stepIndex: input.stepIndex,
1887
+ agents: input.group.parallel.map((task) => task.agent),
1888
+ count: input.group.parallel.length,
1889
+ }));
1890
+ }
1891
+
1892
+ function prepareParallelTaskRun(
1893
+ task: SubagentStep,
1894
+ cwd: string,
1895
+ worktreeSetup: WorktreeSetup | undefined,
1896
+ taskIndex: number,
1897
+ ): { taskForRun: SubagentStep; taskCwd: string } {
1898
+ if (!worktreeSetup) return { taskForRun: task, taskCwd: cwd };
1899
+ const { cwd: _taskCwd, ...taskForRun } = task;
1900
+ return {
1901
+ taskForRun,
1902
+ taskCwd: worktreeSetup.worktrees[taskIndex]!.agentCwd,
1903
+ };
1904
+ }
1905
+
1906
+ function captureParallelWorktreeDiffs(
1907
+ worktreeSetup: WorktreeSetup,
1908
+ asyncDir: string,
1909
+ stepIndex: number,
1910
+ group: Extract<RunnerStep, { parallel: SubagentStep[] }>,
1911
+ ): { diffs: ReturnType<typeof diffWorktrees>; summary: string } {
1912
+ const diffsDir = path.join(asyncDir, "worktree-diffs", `step-${stepIndex}`);
1913
+ const diffs = diffWorktrees(worktreeSetup, group.parallel.map((task) => task.agent), diffsDir);
1914
+ return { diffs, summary: formatWorktreeDiffSummary(diffs) };
1915
+ }
1916
+
1917
+ function ensureParallelProgressFile(cwd: string, group: Extract<RunnerStep, { parallel: SubagentStep[] }>): void {
1918
+ const progressPath = path.join(cwd, "progress.md");
1919
+ if (!group.parallel.some((task) => task.task.includes(`Update progress at: ${progressPath}`))) return;
1920
+ writeInitialProgressFile(cwd);
1921
+ }
1922
+
1923
+ function resolveAsyncStepTranscriptPath(input: {
1924
+ artifactsDir?: string;
1925
+ artifactConfig?: Partial<ArtifactConfig>;
1926
+ runId: string;
1927
+ agent: string;
1928
+ flatIndex: number;
1929
+ flatStepCount: number;
1930
+ }): string | undefined {
1931
+ if (!input.artifactsDir || input.artifactConfig?.enabled === false || input.artifactConfig?.includeTranscript === false) return undefined;
1932
+ return getArtifactPaths(
1933
+ input.artifactsDir,
1934
+ input.runId,
1935
+ input.agent,
1936
+ input.flatStepCount > 1 ? input.flatIndex : undefined,
1937
+ ).transcriptPath;
1938
+ }
1939
+
1940
+ type SingleStepResult = Awaited<ReturnType<typeof runSingleStep>>;
1941
+
1942
+ function combinedAbortSignal(signals: Array<AbortSignal | undefined>): AbortSignal | undefined {
1943
+ const activeSignals = signals.filter((signal): signal is AbortSignal => Boolean(signal));
1944
+ if (activeSignals.length === 0) return undefined;
1945
+ if (activeSignals.length === 1) return activeSignals[0];
1946
+ const controller = new AbortController();
1947
+ const abort = (): void => controller.abort();
1948
+ for (const signal of activeSignals) {
1949
+ if (signal.aborted) {
1950
+ abort();
1951
+ break;
1952
+ }
1953
+ signal.addEventListener("abort", abort, { once: true });
1954
+ }
1955
+ return controller.signal;
1956
+ }
1957
+
1958
+ async function runSubagent(
1959
+ config: SubagentRunConfig,
1960
+ onWriterProcess?: (writer: { state: "none" | "spawning" } | { state: "running"; pid: number }) => void,
1961
+ ): Promise<void> {
1962
+ const { id, steps, resultPath, cwd, placeholder, taskIndex, totalTasks, maxOutput, artifactsDir, artifactConfig } =
1963
+ config;
1964
+ const globalSemaphore = new Semaphore(config.globalConcurrencyLimit ?? DEFAULT_GLOBAL_CONCURRENCY_LIMIT);
1965
+ let previousOutput = "";
1966
+ const outputs: ChainOutputMap = {};
1967
+ const results: StepResult[] = [];
1968
+ const overallStartTime = Date.now();
1969
+ const shareEnabled = config.share === true;
1970
+ const asyncDir = config.asyncDir;
1971
+ const statusPath = path.join(asyncDir, "status.json");
1972
+ const eventsPath = path.join(asyncDir, "events.jsonl");
1973
+ const logPath = path.join(asyncDir, `subagent-log-${id}.md`);
1974
+ const controlConfig = config.controlConfig ?? DEFAULT_CONTROL_CONFIG;
1975
+ const activeChildInterrupts = new Map<number, () => void>();
1976
+ const activeChildTimeouts = new Map<number, () => void>();
1977
+ const activeChildStops = new Map<number, () => void>();
1978
+ const activeChildTurnBudgetAborts = new Map<number, (message: string, state?: TurnBudgetState) => void>();
1979
+ const pendingStepSteers: SteerRequest[] = [];
1980
+ const steeringCapabilities = new Map<number, SteerCapability>();
1981
+ let interrupted = false;
1982
+ let currentActivityState: ActivityState | undefined;
1983
+ let activityTimer: NodeJS.Timeout | undefined;
1984
+ let timeoutTimer: NodeJS.Timeout | undefined;
1985
+ let timedOut = false;
1986
+ let stopped = false;
1987
+ let turnBudgetExceeded = false;
1988
+ let usageBudgetExceeded = false;
1989
+ let checkpointRejected = false;
1990
+ let pendingCheckpointDecision: "approved" | "rejected" | undefined;
1991
+ let wakeCheckpointDecision: (() => void) | undefined;
1992
+ const timeoutMessage = config.timeoutMs !== undefined ? `Subagent timed out after ${config.timeoutMs}ms.` : undefined;
1993
+ const stopMessage = "Subagent stopped by user.";
1994
+ const timeoutAbortController = new AbortController();
1995
+ const stopAbortController = new AbortController();
1996
+ let previousCumulativeTokens: TokenUsage = { input: 0, output: 0, total: 0 };
1997
+ let latestSessionFile: string | undefined;
1998
+
1999
+ const flatSteps = flattenSteps(steps);
2000
+ const initialFlatStepCount = flatSteps.length;
2001
+ const parallelGroups: Array<{ start: number; count: number; stepIndex: number }> = [];
2002
+ const initialStatusSteps: RunnerStatusStep[] = [];
2003
+ let flatStepCount = 0;
2004
+ for (let stepIndex = 0; stepIndex < steps.length; stepIndex++) {
2005
+ const step = steps[stepIndex]!;
2006
+ if (isCheckpointRunnerStep(step)) {
2007
+ initialStatusSteps.push(omitUndefinedProperties({
2008
+ agent: `checkpoint:${step.checkpoint}`,
2009
+ phase: step.phase,
2010
+ label: step.label ?? step.checkpoint,
2011
+ status: "pending",
2012
+ checkpoint: { name: step.checkpoint, ...(step.message ? { message: step.message } : {}), status: "pending", stepIndex },
2013
+ recentTools: [],
2014
+ recentOutput: [],
2015
+ }));
2016
+ flatStepCount++;
2017
+ continue;
2018
+ }
2019
+ if (isParallelGroup(step)) {
2020
+ parallelGroups.push({ start: flatStepCount, count: step.parallel.length, stepIndex });
2021
+ for (const task of step.parallel) {
2022
+ const taskFlatIndex = flatStepCount;
2023
+ const transcriptPath = resolveAsyncStepTranscriptPath(omitUndefinedProperties({ artifactsDir, artifactConfig, runId: id, agent: task.agent, flatIndex: taskFlatIndex, flatStepCount: initialFlatStepCount }));
2024
+ initialStatusSteps.push(omitUndefinedProperties({
2025
+ agent: task.agent,
2026
+ ...(externalRunnerStatus(task.runner) ? { runner: externalRunnerStatus(task.runner) } : {}),
2027
+ ...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),
2028
+ ...(task.context ? { context: task.context } : {}),
2029
+ phase: task.phase,
2030
+ label: task.label,
2031
+ outputName: task.outputName,
2032
+ structured: task.structured,
2033
+ ...(task.agentContract ? { agentContract: task.agentContract } : {}),
2034
+ ...(task.launchContractDigest ? { launchContractDigest: task.launchContractDigest } : {}),
2035
+ ...(task.launchResolvedExtensions ? { launchResolvedExtensions: task.launchResolvedExtensions } : {}),
2036
+ ...(task.capabilityCeiling ? { capabilityCeiling: task.capabilityCeiling } : {}),
2037
+ status: "pending",
2038
+ ...(task.toolBudget ? { toolBudget: initialToolBudgetState(task.toolBudget) } : {}),
2039
+ ...(task.sessionFile ? { sessionFile: task.sessionFile } : {}),
2040
+ ...(transcriptPath ? { transcriptPath } : {}),
2041
+ skills: task.skills,
2042
+ model: task.model,
2043
+ thinking: task.thinking,
2044
+ attemptedModels: task.modelCandidates && task.modelCandidates.length > 0 ? task.modelCandidates : task.model ? [task.model] : undefined,
2045
+ recentTools: [],
2046
+ recentOutput: [],
2047
+ }));
2048
+ flatStepCount++;
2049
+ }
2050
+ } else if (isDynamicRunnerGroup(step)) {
2051
+ parallelGroups.push({ start: flatStepCount, count: 1, stepIndex });
2052
+ initialStatusSteps.push(omitUndefinedProperties({
2053
+ agent: `expand:${step.parallel.agent}`,
2054
+ ...(externalRunnerStatus(step.parallel.runner) ? { runner: externalRunnerStatus(step.parallel.runner) } : {}),
2055
+ ...(step.parallel.context ? { context: step.parallel.context } : {}),
2056
+ phase: step.phase ?? step.parallel.phase,
2057
+ label: step.label ?? step.parallel.label ?? `Dynamic fanout (${step.collect.as})`,
2058
+ outputName: step.collect.as,
2059
+ structured: Boolean(step.collect.outputSchema),
2060
+ ...(step.agentContract ? { agentContract: step.agentContract } : {}),
2061
+ ...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
2062
+ status: "pending",
2063
+ ...(step.parallel.toolBudget ? { toolBudget: initialToolBudgetState(step.parallel.toolBudget) } : {}),
2064
+ recentTools: [],
2065
+ recentOutput: [],
2066
+ }));
2067
+ flatStepCount++;
2068
+ } else {
2069
+ const stepFlatIndex = flatStepCount;
2070
+ const transcriptPath = resolveAsyncStepTranscriptPath(omitUndefinedProperties({ artifactsDir, artifactConfig, runId: id, agent: step.agent, flatIndex: stepFlatIndex, flatStepCount: initialFlatStepCount }));
2071
+ initialStatusSteps.push(omitUndefinedProperties({
2072
+ agent: step.agent,
2073
+ ...(externalRunnerStatus(step.runner) ? { runner: externalRunnerStatus(step.runner) } : {}),
2074
+ ...(statusStepDescription(step.task) ? { description: statusStepDescription(step.task) } : {}),
2075
+ ...(step.context ? { context: step.context } : {}),
2076
+ phase: step.phase,
2077
+ label: step.label,
2078
+ outputName: step.outputName,
2079
+ structured: step.structured,
2080
+ ...(step.agentContract ? { agentContract: step.agentContract } : {}),
2081
+ ...(step.launchContractDigest ? { launchContractDigest: step.launchContractDigest } : {}),
2082
+ ...(step.launchResolvedExtensions ? { launchResolvedExtensions: step.launchResolvedExtensions } : {}),
2083
+ ...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
2084
+ status: "pending",
2085
+ ...(step.toolBudget ? { toolBudget: initialToolBudgetState(step.toolBudget) } : {}),
2086
+ ...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
2087
+ ...(transcriptPath ? { transcriptPath } : {}),
2088
+ skills: step.skills,
2089
+ model: step.model,
2090
+ thinking: step.thinking,
2091
+ attemptedModels: step.modelCandidates && step.modelCandidates.length > 0 ? step.modelCandidates : step.model ? [step.model] : undefined,
2092
+ recentTools: [],
2093
+ recentOutput: [],
2094
+ }));
2095
+ flatStepCount++;
2096
+ }
2097
+ }
2098
+ const sessionEnabled = Boolean(config.sessionDir)
2099
+ || shareEnabled
2100
+ || flatSteps.some((step) => Boolean(step.sessionFile));
2101
+ if (config.runnerProcessInstanceId) {
2102
+ for (const step of initialStatusSteps) {
2103
+ step.processTerminal = { version: 1, state: "pending", runId: id, runnerProcessInstanceId: config.runnerProcessInstanceId };
2104
+ }
2105
+ }
2106
+ const statusPayload: RunnerStatusPayload = omitUndefinedProperties({
2107
+ lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
2108
+ runId: id,
2109
+ ...(config.sessionId ? { sessionId: config.sessionId } : {}),
2110
+ mode: config.resultMode ?? (flatSteps.length > 1 ? "chain" : "single"),
2111
+ ...(config.nestedRoute ? { isNested: true } : {}),
2112
+ state: "running",
2113
+ steering: createSteeringStatus(),
2114
+ lastActivityAt: overallStartTime,
2115
+ startedAt: overallStartTime,
2116
+ lastUpdate: overallStartTime,
2117
+ ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),
2118
+ ...(config.deadlineAt !== undefined ? { deadlineAt: config.deadlineAt } : {}),
2119
+ ...(config.turnBudget ? { turnBudget: initialTurnBudgetState(config.turnBudget) } : {}),
2120
+ ...(config.toolBudget ? { toolBudget: initialToolBudgetState(config.toolBudget) } : {}),
2121
+ ...(config.usageBudget ? { usageBudget: usageBudgetState(config.usageBudget, undefined) } : {}),
2122
+ pid: process.pid,
2123
+ cwd,
2124
+ currentStep: 0,
2125
+ chainStepCount: steps.length,
2126
+ parallelGroups,
2127
+ workflowGraph: config.workflowGraph,
2128
+ ...(config.launchContractDigest ? { launchContractDigest: config.launchContractDigest } : {}),
2129
+ ...(config.launchResolvedExtensions ? { launchResolvedExtensions: config.launchResolvedExtensions } : {}),
2130
+ ...(config.capabilityCeiling ? { capabilityCeiling: config.capabilityCeiling } : {}),
2131
+ ...(config.parentWorkflowRunId ? { parentWorkflowRunId: config.parentWorkflowRunId } : {}),
2132
+ ...(config.workflowKey ? { workflowKey: config.workflowKey } : {}),
2133
+ ...(config.runnerProcessInstanceId ? { processTerminal: { version: 1 as const, state: "pending" as const, runId: id, runnerProcessInstanceId: config.runnerProcessInstanceId } } : {}),
2134
+ steps: initialStatusSteps,
2135
+ artifactsDir,
2136
+ sessionDir: config.sessionDir,
2137
+ outputFile: path.join(asyncDir, "output-0.log"),
2138
+ });
2139
+
2140
+ fs.mkdirSync(asyncDir, { recursive: true });
2141
+ writeAtomicJson(statusPath, statusPayload);
2142
+ let pendingParallelUsageCost: CostSummary = { inputTokens: 0, outputTokens: 0, costUsd: 0 };
2143
+ const currentUsageTotals = (): CostSummary => {
2144
+ const cost = results.reduce<CostSummary>((sum, result) => ({
2145
+ inputTokens: sum.inputTokens + (result.totalCost?.inputTokens ?? result.usage?.input ?? 0),
2146
+ outputTokens: sum.outputTokens + (result.totalCost?.outputTokens ?? result.usage?.output ?? 0),
2147
+ costUsd: sum.costUsd + (result.totalCost?.costUsd ?? result.usage?.cost ?? 0),
2148
+ }), { inputTokens: pendingParallelUsageCost.inputTokens, outputTokens: pendingParallelUsageCost.outputTokens, costUsd: pendingParallelUsageCost.costUsd });
2149
+ return {
2150
+ inputTokens: Math.max(cost.inputTokens, statusPayload.totalTokens?.input ?? 0),
2151
+ outputTokens: Math.max(cost.outputTokens, statusPayload.totalTokens?.output ?? 0),
2152
+ costUsd: cost.costUsd,
2153
+ };
2154
+ };
2155
+ const refreshUsageBudget = () => {
2156
+ setOptionalProperty(statusPayload, "usageBudget", usageBudgetState(config.usageBudget, currentUsageTotals()));
2157
+ return statusPayload.usageBudget;
2158
+ };
2159
+ const emitNestedSelfEvent = (type: "subagent.nested.updated" | "subagent.nested.completed"): void => {
2160
+ if (!config.nestedRoute || !config.nestedSelf) return;
2161
+ try {
2162
+ writeNestedEvent(config.nestedRoute, omitUndefinedProperties({
2163
+ type,
2164
+ ts: Date.now(),
2165
+ parentRunId: config.nestedSelf.parentRunId,
2166
+ parentStepIndex: config.nestedSelf.parentStepIndex,
2167
+ child: nestedSummaryFromAsyncStatus(statusPayload, asyncDir, omitUndefinedProperties({
2168
+ id,
2169
+ parentRunId: config.nestedSelf.parentRunId,
2170
+ parentStepIndex: config.nestedSelf.parentStepIndex,
2171
+ depth: config.nestedSelf.depth,
2172
+ path: config.nestedSelf.path,
2173
+ mode: statusPayload.mode,
2174
+ ts: Date.now(),
2175
+ })),
2176
+ }));
2177
+ } catch (error) {
2178
+ console.error("Failed to emit nested async status event:", error);
2179
+ }
2180
+ };
2181
+ const refreshWorkflowGraph = (): void => {
2182
+ if (!config.workflowGraph) return;
2183
+ const graph = structuredClone(statusPayload.workflowGraph ?? config.workflowGraph);
2184
+ const normalize = (status: RunnerStatusStep["status"]): "pending" | "running" | "completed" | "failed" | "paused" | "stopped" | "detached" | "rejected" => {
2185
+ if (status === "complete" || status === "completed") return "completed";
2186
+ if (status === "running" || status === "failed" || status === "paused" || status === "stopped" || status === "pending" || status === "rejected") return status;
2187
+ return "pending";
2188
+ };
2189
+ const updateNode = (node: NonNullable<typeof graph.nodes>[number]): void => {
2190
+ if (node.flatIndex !== undefined) {
2191
+ const step = statusPayload.steps[node.flatIndex];
2192
+ if (step) {
2193
+ node.status = normalize(step.status);
2194
+ setOptionalProperty(node, "error", step.error);
2195
+ setOptionalProperty(node, "acceptanceStatus", step.acceptance?.status);
2196
+ setOptionalProperty(node, "checkpoint", step.checkpoint);
2197
+ }
2198
+ if (statusPayload.currentStep === node.flatIndex) graph.currentNodeId = node.id;
2199
+ }
2200
+ for (const child of node.children ?? []) updateNode(child);
2201
+ if (node.children?.length) {
2202
+ if (node.children.every((child) => child.status === "completed")) node.status = "completed";
2203
+ else if (node.children.some((child) => child.status === "running")) node.status = "running";
2204
+ else if (node.children.some((child) => child.status === "stopped")) node.status = "stopped";
2205
+ else if (node.children.some((child) => child.status === "rejected")) node.status = "rejected";
2206
+ else if (node.children.some((child) => child.status === "failed")) node.status = "failed";
2207
+ else if (node.children.some((child) => child.status === "paused")) node.status = "paused";
2208
+ }
2209
+ if (node.error && node.status !== "stopped" && node.status !== "rejected") node.status = "failed";
2210
+ };
2211
+ for (const node of graph.nodes) updateNode(node);
2212
+ statusPayload.workflowGraph = graph;
2213
+ };
2214
+ const writeStatusPayload = (): void => {
2215
+ refreshWorkflowGraph();
2216
+ writeAtomicJson(statusPath, statusPayload);
2217
+ emitNestedSelfEvent(statusPayload.state === "running" || statusPayload.state === "queued" ? "subagent.nested.updated" : "subagent.nested.completed");
2218
+ };
2219
+ const updateExternalProcess = (index: number, process: ExternalProcessStatus): void => {
2220
+ requiredStatusStep(statusPayload, index).externalProcess = process;
2221
+ statusPayload.lastUpdate = Date.now();
2222
+ writeStatusPayload();
2223
+ };
2224
+ const registerStepInterrupt = (flatIndex: number, interrupt: (() => void) | undefined): void => {
2225
+ if (!interrupt) {
2226
+ activeChildInterrupts.delete(flatIndex);
2227
+ return;
2228
+ }
2229
+ activeChildInterrupts.set(flatIndex, interrupt);
2230
+ if (interrupted) interrupt();
2231
+ };
2232
+ const registerStepTimeout = (flatIndex: number, interrupt: (() => void) | undefined): void => {
2233
+ if (!interrupt) {
2234
+ activeChildTimeouts.delete(flatIndex);
2235
+ return;
2236
+ }
2237
+ activeChildTimeouts.set(flatIndex, interrupt);
2238
+ if (timedOut) interrupt();
2239
+ };
2240
+ const registerStepStop = (flatIndex: number, stop: (() => void) | undefined): void => {
2241
+ if (!stop) {
2242
+ activeChildStops.delete(flatIndex);
2243
+ return;
2244
+ }
2245
+ activeChildStops.set(flatIndex, stop);
2246
+ if (stopped) stop();
2247
+ };
2248
+ const registerStepTurnBudgetAbort = (flatIndex: number, abort: ((message: string, state?: TurnBudgetState) => void) | undefined): void => {
2249
+ if (!abort) {
2250
+ activeChildTurnBudgetAborts.delete(flatIndex);
2251
+ return;
2252
+ }
2253
+ activeChildTurnBudgetAborts.set(flatIndex, abort);
2254
+ };
2255
+ const interruptActiveChildren = (): void => {
2256
+ for (const interrupt of [...activeChildInterrupts.values()]) interrupt();
2257
+ };
2258
+ const timeoutActiveChildren = (): void => {
2259
+ for (const interrupt of [...activeChildTimeouts.values()]) interrupt();
2260
+ };
2261
+ const stopActiveChildren = (): void => {
2262
+ for (const stop of [...activeChildStops.values()]) stop();
2263
+ };
2264
+ const nestedRuns = function* (children: NestedRunSummary[] | undefined): Generator<NestedRunSummary> {
2265
+ for (const child of children ?? []) {
2266
+ yield child;
2267
+ yield* nestedRuns(child.children);
2268
+ yield* nestedRuns(child.steps?.flatMap((step) => step.children ?? []));
2269
+ }
2270
+ };
2271
+ const interruptNestedAsyncDescendants = (): void => {
2272
+ if (!config.nestedRoute) return;
2273
+ let registry: ReturnType<typeof projectNestedEvents>;
2274
+ try {
2275
+ registry = projectNestedEvents(config.nestedRoute);
2276
+ } catch (error) {
2277
+ appendJsonl(eventsPath, JSON.stringify({
2278
+ type: "subagent.nested.interrupt_failed",
2279
+ ts: Date.now(),
2280
+ runId: id,
2281
+ message: error instanceof Error ? error.message : String(error),
2282
+ }));
2283
+ return;
2284
+ }
2285
+ for (const run of nestedRuns(registry.children)) {
2286
+ if (run.state !== "running" && run.state !== "queued") continue;
2287
+ const nestedAsyncDir = run.asyncDir ?? resolveNestedAsyncDir(config.nestedRoute.rootRunId, run);
2288
+ if (!nestedAsyncDir) continue;
2289
+ try {
2290
+ deliverInterruptRequest(omitUndefinedProperties({ asyncDir: nestedAsyncDir, pid: run.pid, source: "ancestor-interrupt" }));
2291
+ } catch (error) {
2292
+ appendJsonl(eventsPath, JSON.stringify({
2293
+ type: "subagent.nested.interrupt_failed",
2294
+ ts: Date.now(),
2295
+ runId: id,
2296
+ targetRunId: run.id,
2297
+ message: error instanceof Error ? error.message : String(error),
2298
+ }));
2299
+ }
2300
+ }
2301
+ };
2302
+ const stopNestedAsyncDescendants = (): void => {
2303
+ if (!config.nestedRoute) return;
2304
+ let registry: ReturnType<typeof projectNestedEvents>;
2305
+ try {
2306
+ registry = projectNestedEvents(config.nestedRoute);
2307
+ } catch (error) {
2308
+ appendJsonl(eventsPath, JSON.stringify({
2309
+ type: "subagent.nested.stop_failed",
2310
+ ts: Date.now(),
2311
+ runId: id,
2312
+ message: error instanceof Error ? error.message : String(error),
2313
+ }));
2314
+ return;
2315
+ }
2316
+ for (const run of nestedRuns(registry.children)) {
2317
+ if (run.state !== "running" && run.state !== "queued") continue;
2318
+ const nestedAsyncDir = run.asyncDir ?? resolveNestedAsyncDir(config.nestedRoute.rootRunId, run);
2319
+ if (!nestedAsyncDir) continue;
2320
+ try {
2321
+ deliverStopRequest(omitUndefinedProperties({ asyncDir: nestedAsyncDir, pid: run.pid, source: "ancestor-stop" }));
2322
+ } catch (error) {
2323
+ appendJsonl(eventsPath, JSON.stringify({
2324
+ type: "subagent.nested.stop_failed",
2325
+ ts: Date.now(),
2326
+ runId: id,
2327
+ targetRunId: run.id,
2328
+ message: error instanceof Error ? error.message : String(error),
2329
+ }));
2330
+ }
2331
+ }
2332
+ };
2333
+ const timeoutNestedAsyncDescendants = (): void => {
2334
+ if (!config.nestedRoute) return;
2335
+ let registry: ReturnType<typeof projectNestedEvents>;
2336
+ try {
2337
+ registry = projectNestedEvents(config.nestedRoute);
2338
+ } catch (error) {
2339
+ appendJsonl(eventsPath, JSON.stringify({
2340
+ type: "subagent.nested.timeout_failed",
2341
+ ts: Date.now(),
2342
+ runId: id,
2343
+ message: error instanceof Error ? error.message : String(error),
2344
+ }));
2345
+ return;
2346
+ }
2347
+ for (const run of nestedRuns(registry.children)) {
2348
+ if (run.state !== "running" && run.state !== "queued") continue;
2349
+ const nestedAsyncDir = run.asyncDir ?? resolveNestedAsyncDir(config.nestedRoute.rootRunId, run);
2350
+ if (!nestedAsyncDir) continue;
2351
+ try {
2352
+ deliverTimeoutRequest(omitUndefinedProperties({ asyncDir: nestedAsyncDir, pid: run.pid, source: "ancestor-timeout" }));
2353
+ } catch (error) {
2354
+ appendJsonl(eventsPath, JSON.stringify({
2355
+ type: "subagent.nested.timeout_failed",
2356
+ ts: Date.now(),
2357
+ runId: id,
2358
+ targetRunId: run.id,
2359
+ message: error instanceof Error ? error.message : String(error),
2360
+ }));
2361
+ }
2362
+ }
2363
+ };
2364
+ const pausedStepResult = (agent: string, context?: "fresh" | "fork"): SingleStepResult => omitUndefinedProperties({
2365
+ agent,
2366
+ context,
2367
+ output: "Paused after interrupt. Waiting for explicit next action.",
2368
+ exitCode: 0,
2369
+ interrupted: true,
2370
+ });
2371
+ const timedOutStepResult = (agent: string, context?: "fresh" | "fork"): SingleStepResult => omitUndefinedProperties({
2372
+ agent,
2373
+ context,
2374
+ output: timeoutMessage ?? "Subagent timed out.",
2375
+ error: timeoutMessage ?? "Subagent timed out.",
2376
+ exitCode: 1,
2377
+ timedOut: true,
2378
+ });
2379
+ const stoppedStepResult = (agent: string, context?: "fresh" | "fork"): SingleStepResult => omitUndefinedProperties({
2380
+ agent,
2381
+ context,
2382
+ output: stopMessage,
2383
+ error: stopMessage,
2384
+ exitCode: 1,
2385
+ stopped: true,
2386
+ });
2387
+ const consumePendingAppendRequests = (): void => {
2388
+ if (statusPayload.mode !== "chain" || statusPayload.state !== "running") return;
2389
+ const requests = consumeChainAppendRequests(asyncDir);
2390
+ if (requests.length === 0) {
2391
+ const pendingAppends = countPendingChainAppendRequests(asyncDir);
2392
+ if ((statusPayload.pendingAppends ?? 0) !== pendingAppends) {
2393
+ statusPayload.pendingAppends = pendingAppends;
2394
+ statusPayload.lastUpdate = Date.now();
2395
+ writeStatusPayload();
2396
+ }
2397
+ return;
2398
+ }
2399
+ const appendedSteps = requests.flatMap((request) => request.steps);
2400
+ steps.push(...appendedSteps);
2401
+ const now = Date.now();
2402
+ const pendingAppends = countPendingChainAppendRequests(asyncDir);
2403
+ const added = appendRunnerStepsToStatus({
2404
+ status: statusPayload,
2405
+ steps: appendedSteps,
2406
+ now,
2407
+ pendingAppends,
2408
+ });
2409
+ mutatingFailureStates.push(...Array.from({ length: added.addedFlatSteps }, () => createMutatingFailureState()));
2410
+ pendingToolResults.push(...Array.from({ length: added.addedFlatSteps }, () => undefined));
2411
+ if (config.childIntercomTargets) {
2412
+ config.childIntercomTargets = statusPayload.steps.map((statusStep, index) => resolveSubagentIntercomTarget(id, statusStep.agent, index));
2413
+ }
2414
+ writeStatusPayload();
2415
+ for (const request of requests) {
2416
+ appendJsonl(eventsPath, JSON.stringify({
2417
+ type: "subagent.chain.append.accepted",
2418
+ ts: now,
2419
+ runId: id,
2420
+ requestId: request.id,
2421
+ stepCount: request.steps.length,
2422
+ pendingAppends,
2423
+ }));
2424
+ }
2425
+ };
2426
+ const markDynamicGraphGroup = (stepIndex: number, status: "completed" | "failed" | "running" | "stopped", error?: string, acceptance?: import("../../shared/types.ts").AcceptanceLedger): void => {
2427
+ const groupNode = statusPayload.workflowGraph?.nodes.find((node) => node.id === `step-${stepIndex}`);
2428
+ if (!groupNode) return;
2429
+ groupNode.status = status;
2430
+ setOptionalProperty(groupNode, "error", error);
2431
+ setOptionalProperty(groupNode, "acceptanceStatus", acceptance?.status ?? groupNode.acceptanceStatus);
2432
+ };
2433
+
2434
+ const stepOutputActivityAt = (index: number): number => {
2435
+ const step = statusPayload.steps[index];
2436
+ let lastActivityAt = step?.lastActivityAt ?? step?.startedAt ?? overallStartTime;
2437
+ const outputPath = path.join(asyncDir, `output-${index}.log`);
2438
+ try {
2439
+ lastActivityAt = Math.max(lastActivityAt, fs.statSync(outputPath).mtimeMs);
2440
+ } catch (error) {
2441
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
2442
+ console.error(`Failed to inspect async output file '${outputPath}':`, error);
2443
+ }
2444
+ }
2445
+ return lastActivityAt;
2446
+ };
2447
+ const emittedControlEventKeys = new Set<string>();
2448
+ const activeLongRunningSteps = new Set<number>();
2449
+ const mutatingFailureStates = initialStatusSteps.map(() => createMutatingFailureState());
2450
+ const pendingToolResults: Array<{ tool: string; path?: string; mutates: boolean; startedAt?: number } | undefined> = initialStatusSteps.map(() => undefined);
2451
+ const supervisorAttentionSteps = new Map<number, ActivityState | undefined>();
2452
+ const mutatingFailureWindowMs = 5 * 60_000;
2453
+ const appendControlEvent = (event: ReturnType<typeof buildControlEvent>) => {
2454
+ if (!controlConfig.enabled) return;
2455
+ const childIntercomTarget = config.childIntercomTargets?.[event.index ?? statusPayload.currentStep];
2456
+ const channels = event.type === "active_long_running"
2457
+ ? controlConfig.notifyChannels.filter((channel) => channel !== "intercom")
2458
+ : controlConfig.notifyChannels;
2459
+ if (channels.length === 0 || !claimControlNotification(controlConfig, event, emittedControlEventKeys, childIntercomTarget)) return;
2460
+ appendJsonl(eventsPath, JSON.stringify({
2461
+ type: "subagent.control",
2462
+ event,
2463
+ channels,
2464
+ childIntercomTarget,
2465
+ noticeText: formatControlNoticeMessage(event, childIntercomTarget),
2466
+ ...(config.controlIntercomTarget && channels.includes("intercom") ? {
2467
+ intercom: {
2468
+ to: config.controlIntercomTarget,
2469
+ message: formatControlIntercomMessage(event, childIntercomTarget),
2470
+ },
2471
+ } : {}),
2472
+ }));
2473
+ };
2474
+ const syncTopLevelCurrentTool = (): void => {
2475
+ const activeStep = statusPayload.steps
2476
+ .filter((step) => step.status === "running" && typeof step.currentTool === "string" && step.currentTool.length > 0)
2477
+ .sort((left, right) => (right.currentToolStartedAt ?? 0) - (left.currentToolStartedAt ?? 0))[0];
2478
+ setOptionalProperty(statusPayload, "currentTool", activeStep?.currentTool);
2479
+ setOptionalProperty(statusPayload, "currentToolStartedAt", activeStep?.currentToolStartedAt);
2480
+ setOptionalProperty(statusPayload, "currentPath", activeStep?.currentPath);
2481
+ };
2482
+ const syncAggregateActivityState = (): void => {
2483
+ const nextRunState = statusPayload.steps.some((step) => step.activityState === "needs_attention")
2484
+ ? "needs_attention"
2485
+ : statusPayload.steps.some((step) => step.activityState === "active_long_running")
2486
+ ? "active_long_running"
2487
+ : undefined;
2488
+ currentActivityState = nextRunState;
2489
+ setOptionalProperty(statusPayload, "activityState", nextRunState);
2490
+ };
2491
+ const maybeEmitActiveLongRunning = (flatIndex: number, now: number): boolean => {
2492
+ if (!controlConfig.enabled || activeLongRunningSteps.has(flatIndex)) return false;
2493
+ const step = statusPayload.steps[flatIndex];
2494
+ if (!step || step.status !== "running" || step.activityState === "needs_attention") return false;
2495
+ const reason = nextLongRunningTrigger(controlConfig, {
2496
+ startedAt: step.startedAt ?? overallStartTime,
2497
+ now,
2498
+ turns: step.turnCount ?? 0,
2499
+ tokens: step.tokens?.total ?? 0,
2500
+ });
2501
+ if (!reason) return false;
2502
+ activeLongRunningSteps.add(flatIndex);
2503
+ const previous = step.activityState;
2504
+ step.activityState = "active_long_running";
2505
+ statusPayload.activityState = statusPayload.activityState === "needs_attention" ? "needs_attention" : "active_long_running";
2506
+ const event = buildControlEvent(omitUndefinedProperties({
2507
+ type: "active_long_running",
2508
+ from: previous,
2509
+ to: "active_long_running",
2510
+ runId: id,
2511
+ agent: step.agent,
2512
+ index: flatIndex,
2513
+ ts: now,
2514
+ message: `${step.agent} is still active but long-running`,
2515
+ reason,
2516
+ turns: step.turnCount,
2517
+ tokens: step.tokens?.total,
2518
+ toolCount: step.toolCount,
2519
+ currentTool: step.currentTool,
2520
+ currentToolDurationMs: step.currentToolStartedAt ? Math.max(0, now - step.currentToolStartedAt) : undefined,
2521
+ currentPath: step.currentPath,
2522
+ elapsedMs: now - (step.startedAt ?? overallStartTime),
2523
+ }));
2524
+ appendControlEvent(event);
2525
+ return true;
2526
+ };
2527
+ const steeringMarkerPath = (requestId: string): string => path.join(asyncDir, "control", "steer-recovery", `${Buffer.from(requestId).toString("base64url")}.json`);
2528
+ const markSteeringAttention = (index: number): void => {
2529
+ const step = statusPayload.steps[index];
2530
+ if (step) step.activityState = "needs_attention";
2531
+ statusPayload.activityState = "needs_attention";
2532
+ };
2533
+ const emitSteeringEvent = (type: string, request: SteerRequest, index?: number, extra: Record<string, unknown> = {}): void => {
2534
+ appendJsonl(eventsPath, JSON.stringify({ type, ts: Date.now(), runId: id, requestId: request.id, ...(index !== undefined ? { index } : {}), ...extra }));
2535
+ };
2536
+ const emitSteeringNotice = (requestId: string, state: "failed" | "partial" | "recovered", message: string): void => {
2537
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.steering.notice", ts: Date.now(), runId: id, requestId, state, message, ...(config.sessionId ? { currentSessionId: config.sessionId } : {}) }));
2538
+ };
2539
+ const recordSteeringLifecycle = (request: SteerRequest, targets: Array<{ index: number; state: SteeringTargetState; reason?: string }>): void => {
2540
+ const lifecycle = steeringStatus(statusPayload);
2541
+ recordSteeringRequest(lifecycle, omitUndefinedProperties({ id: request.id, requestedAt: request.ts, source: request.source, message: request.message, targets }));
2542
+ for (const target of targets) {
2543
+ const step = statusPayload.steps[target.index];
2544
+ if (!step) continue;
2545
+ step.steering ??= createSteeringStatus();
2546
+ recordSteeringRequest(step.steering, omitUndefinedProperties({ id: request.id, requestedAt: request.ts, source: request.source, message: request.message, targets: [target] }));
2547
+ }
2548
+ };
2549
+ const updateSteeringLifecycleTarget = (
2550
+ requestId: string,
2551
+ index: number,
2552
+ state: SteeringTargetState,
2553
+ now: number,
2554
+ fields: Pick<SteeringTargetStatus, "reason" | "replacementRunId"> = {},
2555
+ ): SteeringTargetStatus | undefined => {
2556
+ const updated = updateSteeringTarget(steeringStatus(statusPayload), requestId, index, state, now, fields);
2557
+ const step = statusPayload.steps[index];
2558
+ if (step?.steering) updateSteeringTarget(step.steering, requestId, index, state, now, fields);
2559
+ return updated;
2560
+ };
2561
+ const emitTerminalSteeringNotice = (requestId: string, failureMessage: string): void => {
2562
+ const state = terminalSteeringNoticeState(steeringStatus(statusPayload), requestId);
2563
+ if (state === "partial") emitSteeringNotice(requestId, "partial", `Steering partially delivered for run ${id}.`);
2564
+ else if (state === "failed") emitSteeringNotice(requestId, "failed", failureMessage);
2565
+ };
2566
+ const deliverSteerRequest = (request: SteerRequest): void => {
2567
+ if (statusPayload.state !== "running") {
2568
+ const reason = `run became ${statusPayload.state} before steering request was consumed`;
2569
+ const indexes = request.targetIndex !== undefined
2570
+ ? [request.targetIndex]
2571
+ : request.targetIndexes?.length
2572
+ ? request.targetIndexes
2573
+ : statusPayload.steps.map((_, index) => index);
2574
+ const targets = indexes.map((index) => ({ index, state: "failed" as const, reason }));
2575
+ recordSteeringLifecycle(request, targets);
2576
+ emitSteeringEvent("subagent.steer.requested", request, undefined, { targets });
2577
+ for (const target of targets) emitSteeringEvent("subagent.steer.failed", request, target.index, { reason });
2578
+ emitTerminalSteeringNotice(request.id, `Steering failed for run ${id}: ${reason}.`);
2579
+ statusPayload.lastUpdate = Date.now();
2580
+ writeStatusPayload();
2581
+ return;
2582
+ }
2583
+ const runningIndexes = statusPayload.steps
2584
+ .map((step, index) => ({ step, index }))
2585
+ .filter(({ step }) => step.status === "running")
2586
+ .map(({ index }) => index);
2587
+ const targets = request.targetIndex !== undefined
2588
+ ? [request.targetIndex]
2589
+ : request.targetIndexes?.length
2590
+ ? request.targetIndexes
2591
+ : runningIndexes.length > 0
2592
+ ? runningIndexes
2593
+ : statusPayload.mode === "single" && statusPayload.steps[0]?.status === "pending"
2594
+ ? [0]
2595
+ : [];
2596
+ const now = Date.now();
2597
+ const targetStates = targets.map((index) => {
2598
+ const step = statusPayload.steps[index];
2599
+ if (!step) return { index, state: "failed" as const, reason: "child index out of range" };
2600
+ if (step.status === "pending") return { index, state: "scheduled" as const };
2601
+ if (step.status !== "running") return { index, state: "failed" as const, reason: `child is ${step.status}` };
2602
+ if (steeringCapabilities.get(index)?.supported === false) return { index, state: "failed" as const, reason: "child Pi session does not support steering" };
2603
+ return { index, state: "routed" as const };
2604
+ });
2605
+ recordSteeringLifecycle(request, targetStates);
2606
+ emitSteeringEvent("subagent.steer.requested", request, undefined, { targets: targetStates });
2607
+ for (const target of targetStates) {
2608
+ if (target.state === "routed") {
2609
+ try {
2610
+ enqueueStepSteer(asyncDir, target.index, request);
2611
+ updateSteeringLifecycleTarget(request.id, target.index, "routed", now);
2612
+ emitSteeringEvent("subagent.steer.routed", request, target.index);
2613
+ } catch (error) {
2614
+ markSteeringAttention(target.index);
2615
+ updateSteeringLifecycleTarget(request.id, target.index, "failed", now, { reason: error instanceof Error ? error.message : String(error) });
2616
+ emitSteeringEvent("subagent.steer.failed", request, target.index, { reason: error instanceof Error ? error.message : String(error) });
2617
+ }
2618
+ } else if (target.state === "failed") {
2619
+ markSteeringAttention(target.index);
2620
+ emitSteeringEvent("subagent.steer.failed", request, target.index, { reason: target.reason });
2621
+ } else {
2622
+ emitSteeringEvent("subagent.steer.scheduled", request, target.index);
2623
+ }
2624
+ }
2625
+ emitTerminalSteeringNotice(request.id, `Steering failed for run ${id}: no requested child remained steerable.`);
2626
+ statusPayload.lastUpdate = now;
2627
+ writeStatusPayload();
2628
+ };
2629
+ const consumeSteerAck = (ack: SteerAck): void => {
2630
+ const lifecycle = steeringStatus(statusPayload);
2631
+ const request = lifecycle.recent.find((candidate) => candidate.id === ack.requestId);
2632
+ if (!request || !request.targets.some((target) => target.index === ack.index)) return;
2633
+ const late = fs.existsSync(steeringMarkerPath(ack.requestId));
2634
+ const now = Date.now();
2635
+ if (ack.state === "delivered") {
2636
+ updateSteeringLifecycleTarget(ack.requestId, ack.index, late ? "late" : "delivered", now, omitUndefinedProperties({ reason: late ? "acknowledged after recovery commit" : undefined }));
2637
+ emitSteeringEvent("subagent.steer.delivered", { type: "steer", id: ack.requestId, ts: now, message: ack.message }, ack.index, { late, deliveryStatus: "delivered", message: ack.message });
2638
+ } else if (ack.state === "queued") {
2639
+ updateSteeringLifecycleTarget(ack.requestId, ack.index, "queued", now);
2640
+ emitSteeringEvent("subagent.steer.queued", { type: "steer", id: ack.requestId, ts: now, message: ack.message }, ack.index, { deliveryStatus: "queued", message: ack.message });
2641
+ } else {
2642
+ markSteeringAttention(ack.index);
2643
+ updateSteeringLifecycleTarget(ack.requestId, ack.index, "failed", now, { reason: ack.message });
2644
+ emitSteeringEvent("subagent.steer.failed", { type: "steer", id: ack.requestId, ts: now, message: ack.message }, ack.index, { reason: ack.message });
2645
+ }
2646
+ emitTerminalSteeringNotice(ack.requestId, `Steering failed for run ${id}: ${ack.message}`);
2647
+ statusPayload.lastUpdate = now;
2648
+ writeStatusPayload();
2649
+ };
2650
+ const flushPendingStepSteers = (flatIndex: number): void => {
2651
+ const remaining: SteerRequest[] = [];
2652
+ for (const request of pendingStepSteers.splice(0)) {
2653
+ if (request.targetIndex === undefined) deliverSteerRequest({ ...request, targetIndex: flatIndex });
2654
+ else if (request.targetIndex === flatIndex) deliverSteerRequest(request);
2655
+ else remaining.push(request);
2656
+ }
2657
+ pendingStepSteers.push(...remaining);
2658
+ };
2659
+ const updateStepModel = (flatIndex: number, model: string | undefined, thinking: string | undefined, now = Date.now()): void => {
2660
+ const step = statusPayload.steps[flatIndex];
2661
+ if (!step) return;
2662
+ setOptionalProperty(step, "model", model);
2663
+ setOptionalProperty(step, "thinking", thinking);
2664
+ statusPayload.lastUpdate = now;
2665
+ writeStatusPayload();
2666
+ };
2667
+ const updateStepTurnBudget = (
2668
+ flatIndex: number,
2669
+ turnCount: number,
2670
+ now: number,
2671
+ terminalAssistantStop: boolean,
2672
+ toolWorkActiveOrStarting: boolean,
2673
+ ): void => {
2674
+ const budget = config.turnBudget;
2675
+ const step = statusPayload.steps[flatIndex];
2676
+ if (!budget || !step || timedOut || stopped || turnBudgetExceeded || step.turnBudgetExceeded) return;
2677
+ if (turnCount < budget.maxTurns) {
2678
+ const state: TurnBudgetState = { ...budget, outcome: "within-budget", turnCount };
2679
+ step.turnBudget = state;
2680
+ statusPayload.turnBudget = state;
2681
+ return;
2682
+ }
2683
+ if (!step.wrapUpRequested) {
2684
+ step.wrapUpRequested = true;
2685
+ statusPayload.wrapUpRequested = true;
2686
+ appendRecentStepOutput(step, [turnBudgetSoftNote(budget, turnCount)]);
2687
+ }
2688
+ const decision = turnBudgetDecision(budget, turnCount, terminalAssistantStop, toolWorkActiveOrStarting);
2689
+ if (decision === "defer") {
2690
+ const firstDeferredTurn = step.turnBudget?.terminationDeferredAtTurn;
2691
+ const deferredState = turnBudgetDeferredState(budget, turnCount, firstDeferredTurn);
2692
+ step.turnBudget = deferredState;
2693
+ statusPayload.turnBudget = deferredState;
2694
+ if (firstDeferredTurn === undefined) {
2695
+ appendJsonl(eventsPath, JSON.stringify({
2696
+ type: "subagent.step.turn_budget_deferred",
2697
+ ts: now,
2698
+ runId: id,
2699
+ stepIndex: flatIndex,
2700
+ agent: step.agent,
2701
+ turnCount,
2702
+ maxTurns: budget.maxTurns,
2703
+ graceTurns: budget.graceTurns,
2704
+ }));
2705
+ }
2706
+ return;
2707
+ }
2708
+ const state = turnBudgetState(budget, turnCount, false);
2709
+ step.turnBudget = state;
2710
+ statusPayload.turnBudget = state;
2711
+ if (decision !== "abort") return;
2712
+ const exceededState = turnBudgetState(budget, turnCount, true);
2713
+ const message = turnBudgetExceededMessage(budget, turnCount);
2714
+ step.turnBudget = exceededState;
2715
+ step.turnBudgetExceeded = true;
2716
+ step.wrapUpRequested = true;
2717
+ step.error = message;
2718
+ turnBudgetExceeded = true;
2719
+ statusPayload.turnBudget = exceededState;
2720
+ statusPayload.turnBudgetExceeded = true;
2721
+ statusPayload.wrapUpRequested = true;
2722
+ statusPayload.error = message;
2723
+ statusPayload.lastUpdate = now;
2724
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.step.turn_budget_exceeded", ts: now, runId: id, stepIndex: flatIndex, agent: step.agent, turnCount, maxTurns: budget.maxTurns, graceTurns: budget.graceTurns, message }));
2725
+ activeChildTurnBudgetAborts.get(flatIndex)?.(message, exceededState);
2726
+ };
2727
+ const updateStepFromChildEvent = (flatIndex: number, event: ChildEvent): void => {
2728
+ const step = statusPayload.steps[flatIndex];
2729
+ if (!step) return;
2730
+ const now = Date.now();
2731
+ statusPayload.currentStep = flatIndex;
2732
+ if (isChildWatchdogStatusEvent(event)) {
2733
+ const next = acceptChildWatchdogEvent({
2734
+ current: step.watchdog,
2735
+ event,
2736
+ runId: id,
2737
+ agent: step.agent,
2738
+ childIndex: flatIndex,
2739
+ });
2740
+ if (!next) return;
2741
+ step.watchdog = next;
2742
+ step.lastActivityAt = now;
2743
+ statusPayload.lastActivityAt = now;
2744
+ statusPayload.lastUpdate = now;
2745
+ writeStatusPayload();
2746
+ return;
2747
+ }
2748
+ if (event.type === "tool_execution_start" && event.toolName) {
2749
+ const mutates = isMutatingTool(event.toolName, event.args);
2750
+ const currentPath = resolveCurrentPath(event.toolName, event.args);
2751
+ step.toolCount = (step.toolCount ?? 0) + 1;
2752
+ const configuredToolBudget = flatSteps[flatIndex]?.toolBudget;
2753
+ if (configuredToolBudget) {
2754
+ step.toolBudget = toolBudgetState(configuredToolBudget, step.toolCount);
2755
+ statusPayload.toolBudget = step.toolBudget;
2756
+ }
2757
+ step.currentTool = event.toolName;
2758
+ step.currentToolArgs = extractToolArgsPreview(event.args ?? {});
2759
+ step.currentToolStartedAt = now;
2760
+ setOptionalProperty(step, "currentPath", currentPath);
2761
+ pendingToolResults[flatIndex] = omitUndefinedProperties({ tool: event.toolName, path: currentPath, mutates, startedAt: now });
2762
+ statusPayload.toolCount = (statusPayload.toolCount ?? 0) + 1;
2763
+ syncTopLevelCurrentTool();
2764
+ if (controlConfig.enabled && isBlockingSupervisorTool(event.toolName, event.args) && step.activityState !== "needs_attention") {
2765
+ const previous = step.activityState;
2766
+ step.activityState = "needs_attention";
2767
+ supervisorAttentionSteps.set(flatIndex, previous);
2768
+ currentActivityState = "needs_attention";
2769
+ statusPayload.activityState = "needs_attention";
2770
+ appendControlEvent(buildControlEvent(omitUndefinedProperties({
2771
+ type: "needs_attention",
2772
+ from: previous,
2773
+ to: "needs_attention",
2774
+ runId: id,
2775
+ agent: step.agent,
2776
+ index: flatIndex,
2777
+ ts: now,
2778
+ message: `${step.agent} is waiting for a supervisor reply`,
2779
+ reason: "supervisor_request",
2780
+ turns: step.turnCount,
2781
+ tokens: step.tokens?.total,
2782
+ toolCount: step.toolCount,
2783
+ currentTool: step.currentTool,
2784
+ currentToolDurationMs: 0,
2785
+ currentPath: step.currentPath,
2786
+ })));
2787
+ }
2788
+ } else if (event.type === "tool_execution_end") {
2789
+ if (step.currentTool) {
2790
+ step.recentTools ??= [];
2791
+ step.recentTools.push({ tool: step.currentTool, args: step.currentToolArgs || "", endMs: now });
2792
+ }
2793
+ const supervisorPreviousActivity = supervisorAttentionSteps.get(flatIndex);
2794
+ const clearedSupervisorAttention = supervisorAttentionSteps.delete(flatIndex);
2795
+ delete step.currentTool;
2796
+ delete step.currentToolArgs;
2797
+ delete step.currentToolStartedAt;
2798
+ delete step.currentPath;
2799
+ if (clearedSupervisorAttention && step.activityState === "needs_attention") {
2800
+ setOptionalProperty(step, "activityState", supervisorPreviousActivity);
2801
+ syncAggregateActivityState();
2802
+ }
2803
+ syncTopLevelCurrentTool();
2804
+ } else if (event.type === "tool_result_end" && event.message) {
2805
+ const toolSnapshot = pendingToolResults[flatIndex];
2806
+ pendingToolResults[flatIndex] = undefined;
2807
+ const resultText = extractTextFromContent(event.message.content);
2808
+ if (toolSnapshot && resultText.includes("Tool budget hard limit reached")) {
2809
+ const configuredToolBudget = flatSteps[flatIndex]?.toolBudget;
2810
+ if (configuredToolBudget) {
2811
+ step.toolBudget = toolBudgetState(configuredToolBudget, step.toolCount ?? 0, toolSnapshot.tool);
2812
+ step.toolBudgetBlocked = true;
2813
+ statusPayload.toolBudget = step.toolBudget;
2814
+ statusPayload.toolBudgetBlocked = true;
2815
+ }
2816
+ }
2817
+ appendRecentStepOutput(step, resultText.split("\n").slice(-10));
2818
+ if (toolSnapshot?.mutates && didMutatingToolFail(resultText)) {
2819
+ const state = mutatingFailureStates[flatIndex]!;
2820
+ recordMutatingFailure(state, omitUndefinedProperties({
2821
+ tool: toolSnapshot.tool,
2822
+ path: toolSnapshot.path,
2823
+ error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
2824
+ ts: now,
2825
+ }), mutatingFailureWindowMs);
2826
+ if (controlConfig.enabled && shouldEscalateMutatingFailures(state, controlConfig.failedToolAttemptsBeforeAttention) && step.activityState !== "needs_attention") {
2827
+ const previous = step.activityState;
2828
+ step.activityState = "needs_attention";
2829
+ statusPayload.activityState = "needs_attention";
2830
+ appendControlEvent(buildControlEvent(omitUndefinedProperties({
2831
+ type: "needs_attention",
2832
+ from: previous,
2833
+ to: "needs_attention",
2834
+ runId: id,
2835
+ agent: step.agent,
2836
+ index: flatIndex,
2837
+ ts: now,
2838
+ message: `${step.agent} needs attention after repeated mutating tool failures`,
2839
+ reason: "tool_failures",
2840
+ turns: step.turnCount,
2841
+ tokens: step.tokens?.total,
2842
+ toolCount: step.toolCount,
2843
+ currentTool: toolSnapshot.tool,
2844
+ currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
2845
+ currentPath: toolSnapshot.path,
2846
+ recentFailureSummary: summarizeRecentMutatingFailures(state),
2847
+ })));
2848
+ }
2849
+ } else if (toolSnapshot?.mutates) {
2850
+ resetMutatingFailureState(mutatingFailureStates[flatIndex]!);
2851
+ }
2852
+ } else if (event.type === "message_end" && event.message?.role === "assistant") {
2853
+ appendRecentStepOutput(step, stripAcceptanceReport(extractTextFromContent(event.message.content)).split("\n").slice(-10));
2854
+ step.turnCount = (step.turnCount ?? 0) + 1;
2855
+ const usage = event.message.usage;
2856
+ if (usage) {
2857
+ const input = usage.input ?? usage.inputTokens ?? 0;
2858
+ const output = usage.output ?? usage.outputTokens ?? 0;
2859
+ const previousInput = step.tokens?.input ?? 0;
2860
+ const previousOutput = step.tokens?.output ?? 0;
2861
+ step.tokens = { input: previousInput + input, output: previousOutput + output, total: previousInput + previousOutput + input + output };
2862
+ const totalInput = statusPayload.totalTokens?.input ?? 0;
2863
+ const totalOutput = statusPayload.totalTokens?.output ?? 0;
2864
+ statusPayload.totalTokens = { input: totalInput + input, output: totalOutput + output, total: totalInput + totalOutput + input + output };
2865
+ refreshUsageBudget();
2866
+ }
2867
+ statusPayload.turnCount = Math.max(statusPayload.turnCount ?? 0, step.turnCount);
2868
+ updateStepTurnBudget(
2869
+ flatIndex,
2870
+ step.turnCount,
2871
+ now,
2872
+ isTerminalAssistantStop(event.message),
2873
+ assistantStartsToolCall(event.message) || Boolean(step.currentTool),
2874
+ );
2875
+ }
2876
+ syncTopLevelCurrentTool();
2877
+ step.lastActivityAt = now;
2878
+ statusPayload.lastActivityAt = now;
2879
+ statusPayload.lastUpdate = now;
2880
+ maybeEmitActiveLongRunning(flatIndex, now);
2881
+ writeStatusPayload();
2882
+ };
2883
+ const updateRunnerActivityState = (now: number): boolean => {
2884
+ if (!controlConfig.enabled) return false;
2885
+ let changed = false;
2886
+ let runLastActivityAt = statusPayload.lastActivityAt ?? overallStartTime;
2887
+ for (let index = 0; index < statusPayload.steps.length; index++) {
2888
+ const step = statusPayload.steps[index]!;
2889
+ if (step.status !== "running") continue;
2890
+ const lastActivityAt = stepOutputActivityAt(index);
2891
+ runLastActivityAt = Math.max(runLastActivityAt, lastActivityAt);
2892
+ if (step.lastActivityAt !== lastActivityAt) {
2893
+ step.lastActivityAt = lastActivityAt;
2894
+ changed = true;
2895
+ }
2896
+ const idleState = deriveActivityState(omitUndefinedProperties({
2897
+ config: controlConfig,
2898
+ startedAt: step.startedAt ?? overallStartTime,
2899
+ lastActivityAt,
2900
+ currentTool: step.currentTool,
2901
+ now,
2902
+ }));
2903
+ if (idleState === "needs_attention") {
2904
+ const previous = step.activityState;
2905
+ step.activityState = "needs_attention";
2906
+ if (previous !== "needs_attention") {
2907
+ appendControlEvent(buildControlEvent(omitUndefinedProperties({
2908
+ from: previous,
2909
+ to: "needs_attention",
2910
+ runId: id,
2911
+ agent: step.agent,
2912
+ index,
2913
+ ts: now,
2914
+ lastActivityAt,
2915
+ })));
2916
+ changed = true;
2917
+ }
2918
+ } else if (maybeEmitActiveLongRunning(index, now)) {
2919
+ changed = true;
2920
+ }
2921
+ }
2922
+ if (statusPayload.lastActivityAt !== runLastActivityAt) {
2923
+ statusPayload.lastActivityAt = runLastActivityAt;
2924
+ changed = true;
2925
+ }
2926
+ const nextRunState = statusPayload.steps.some((step) => step.activityState === "needs_attention")
2927
+ ? "needs_attention"
2928
+ : statusPayload.steps.some((step) => step.activityState === "active_long_running")
2929
+ ? "active_long_running"
2930
+ : undefined;
2931
+ if (nextRunState !== currentActivityState) {
2932
+ currentActivityState = nextRunState;
2933
+ setOptionalProperty(statusPayload, "activityState", nextRunState);
2934
+ changed = true;
2935
+ }
2936
+ statusPayload.lastUpdate = now;
2937
+ if (changed) writeStatusPayload();
2938
+ return changed;
2939
+ };
2940
+ if (controlConfig.enabled) {
2941
+ activityTimer = setInterval(() => {
2942
+ if (statusPayload.state !== "running") return;
2943
+ const now = Date.now();
2944
+ updateRunnerActivityState(now);
2945
+ }, 1000);
2946
+ activityTimer.unref?.();
2947
+ }
2948
+
2949
+ const interruptRunner = () => {
2950
+ consumeInterruptRequest(asyncDir);
2951
+ if (interrupted || statusPayload.state !== "running") return;
2952
+ interrupted = true;
2953
+ const now = Date.now();
2954
+ statusPayload.state = "paused";
2955
+ currentActivityState = undefined;
2956
+ delete statusPayload.activityState;
2957
+ statusPayload.lastUpdate = now;
2958
+ for (const step of statusPayload.steps) {
2959
+ if (step.status === "running") {
2960
+ step.status = "paused";
2961
+ delete step.activityState;
2962
+ step.endedAt = now;
2963
+ setOptionalProperty(step, "durationMs", step.startedAt ? now - step.startedAt : undefined);
2964
+ step.lastActivityAt = now;
2965
+ }
2966
+ }
2967
+ writeStatusPayload();
2968
+ appendJsonl(eventsPath, JSON.stringify({
2969
+ type: "subagent.run.paused",
2970
+ ts: now,
2971
+ runId: id,
2972
+ }));
2973
+ interruptNestedAsyncDescendants();
2974
+ interruptActiveChildren();
2975
+ };
2976
+ const stopRunner = () => {
2977
+ if (stopped || timedOut || interrupted || statusPayload.state !== "running") return;
2978
+ stopped = true;
2979
+ const now = Date.now();
2980
+ statusPayload.state = "stopped";
2981
+ statusPayload.stopped = true;
2982
+ statusPayload.error = stopMessage;
2983
+ currentActivityState = undefined;
2984
+ delete statusPayload.activityState;
2985
+ statusPayload.lastUpdate = now;
2986
+ for (const step of statusPayload.steps) {
2987
+ if (step.status !== "running" && step.status !== "pending") continue;
2988
+ step.status = "stopped";
2989
+ step.error = stopMessage;
2990
+ step.exitCode = 1;
2991
+ step.stopped = true;
2992
+ delete step.activityState;
2993
+ step.endedAt = now;
2994
+ step.durationMs = step.startedAt ? now - step.startedAt : 0;
2995
+ step.lastActivityAt = now;
2996
+ }
2997
+ writeStatusPayload();
2998
+ appendJsonl(eventsPath, JSON.stringify({
2999
+ type: "subagent.run.stopped",
3000
+ ts: now,
3001
+ runId: id,
3002
+ message: stopMessage,
3003
+ }));
3004
+ stopAbortController.abort();
3005
+ stopNestedAsyncDescendants();
3006
+ stopActiveChildren();
3007
+ };
3008
+ const timeoutRunner = () => {
3009
+ if (timedOut || stopped || interrupted || statusPayload.state !== "running") return;
3010
+ timedOut = true;
3011
+ const now = Date.now();
3012
+ const message = timeoutMessage ?? "Subagent timed out.";
3013
+ statusPayload.state = "failed";
3014
+ statusPayload.timedOut = true;
3015
+ statusPayload.error = message;
3016
+ currentActivityState = undefined;
3017
+ delete statusPayload.activityState;
3018
+ statusPayload.lastUpdate = now;
3019
+ for (const step of statusPayload.steps) {
3020
+ if (step.status !== "running" && step.status !== "pending") continue;
3021
+ step.status = "failed";
3022
+ step.error = message;
3023
+ step.exitCode = 1;
3024
+ step.timedOut = true;
3025
+ delete step.activityState;
3026
+ step.endedAt = now;
3027
+ step.durationMs = step.startedAt ? now - step.startedAt : 0;
3028
+ step.lastActivityAt = now;
3029
+ }
3030
+ writeStatusPayload();
3031
+ appendJsonl(eventsPath, JSON.stringify({
3032
+ type: "subagent.run.timed_out",
3033
+ ts: now,
3034
+ runId: id,
3035
+ timeoutMs: config.timeoutMs,
3036
+ deadlineAt: config.deadlineAt,
3037
+ message,
3038
+ }));
3039
+ timeoutAbortController.abort();
3040
+ timeoutNestedAsyncDescendants();
3041
+ timeoutActiveChildren();
3042
+ };
3043
+ process.on(ASYNC_INTERRUPT_SIGNAL, interruptRunner);
3044
+ // Portable control inbox: the parent drops control request files here when
3045
+ // it cannot deliver OS signals (e.g. ENOSYS on Windows) or when steering a
3046
+ // live child. Interrupts still route into the same graceful interruptRunner().
3047
+ const disposeControlInbox = watchAsyncControlInbox(asyncDir, {
3048
+ onInterrupt: interruptRunner,
3049
+ onTimeout: timeoutRunner,
3050
+ onStop: stopRunner,
3051
+ onCheckpointDecision: (decision) => {
3052
+ pendingCheckpointDecision = decision;
3053
+ wakeCheckpointDecision?.();
3054
+ },
3055
+ onSteer: (request) => {
3056
+ const targetStep = request.targetIndex !== undefined ? statusPayload.steps[request.targetIndex] : undefined;
3057
+ if (targetStep?.status === "pending") {
3058
+ deliverSteerRequest(request);
3059
+ pendingStepSteers.push(request);
3060
+ } else if (request.targetIndexes !== undefined || request.targetIndex !== undefined || statusPayload.steps.some((step) => step.status === "running")) {
3061
+ deliverSteerRequest(request);
3062
+ } else {
3063
+ deliverSteerRequest(request);
3064
+ pendingStepSteers.push(request);
3065
+ }
3066
+ },
3067
+ onSteerCapability: (capability) => {
3068
+ steeringCapabilities.set(capability.index, capability);
3069
+ if (!capability.supported) {
3070
+ const now = Date.now();
3071
+ const lifecycle = steeringStatus(statusPayload);
3072
+ for (const request of lifecycle.recent) {
3073
+ if (!request.targets.some((target) => target.index === capability.index && (target.state === "routed" || target.state === "scheduled"))) continue;
3074
+ markSteeringAttention(capability.index);
3075
+ updateSteeringLifecycleTarget(request.id, capability.index, "failed", now, { reason: "child Pi session does not support steering" });
3076
+ emitSteeringEvent("subagent.steer.failed", { type: "steer", id: request.id, ts: request.requestedAt, message: "child Pi session does not support steering" }, capability.index, { reason: "child Pi session does not support steering" });
3077
+ emitTerminalSteeringNotice(request.id, `Steering failed for run ${id}: child ${capability.index} does not support steering.`);
3078
+ }
3079
+ statusPayload.lastUpdate = now;
3080
+ writeStatusPayload();
3081
+ }
3082
+ },
3083
+ onSteerAck: consumeSteerAck,
3084
+ });
3085
+ if (config.deadlineAt !== undefined) {
3086
+ const remainingMs = Math.max(0, config.deadlineAt - Date.now());
3087
+ timeoutTimer = setTimeout(timeoutRunner, remainingMs);
3088
+ timeoutTimer.unref?.();
3089
+ }
3090
+ appendJsonl(
3091
+ eventsPath,
3092
+ JSON.stringify({
3093
+ type: "subagent.run.started",
3094
+ lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
3095
+ ts: overallStartTime,
3096
+ runId: id,
3097
+ mode: statusPayload.mode,
3098
+ cwd,
3099
+ pid: process.pid,
3100
+ }),
3101
+ );
3102
+
3103
+ let flatIndex = 0;
3104
+ let stepCursor = 0;
3105
+ const waitForCheckpointDecision = async (): Promise<"approved" | "rejected" | undefined> => {
3106
+ while (!pendingCheckpointDecision && !interrupted && !timedOut && !stopped) {
3107
+ await new Promise<void>((resolve) => {
3108
+ wakeCheckpointDecision = resolve;
3109
+ const timer = setTimeout(resolve, POLL_INTERVAL_MS);
3110
+ timer.unref?.();
3111
+ });
3112
+ wakeCheckpointDecision = undefined;
3113
+ }
3114
+ const decision = pendingCheckpointDecision;
3115
+ pendingCheckpointDecision = undefined;
3116
+ return decision;
3117
+ };
3118
+
3119
+ while (true) {
3120
+ if (interrupted || timedOut || stopped || turnBudgetExceeded) break;
3121
+ consumePendingAppendRequests();
3122
+ if (stepCursor >= steps.length) break;
3123
+ refreshUsageBudget();
3124
+ if (statusPayload.usageBudget?.exhausted) {
3125
+ usageBudgetExceeded = true;
3126
+ statusPayload.state = "failed";
3127
+ statusPayload.error = usageBudgetExceededMessage(statusPayload.usageBudget);
3128
+ statusPayload.currentStep = flatIndex;
3129
+ statusPayload.lastUpdate = Date.now();
3130
+ writeStatusPayload();
3131
+ break;
3132
+ }
3133
+ const stepIndex = stepCursor++;
3134
+ const step = steps[stepIndex]!;
3135
+
3136
+ if (isCheckpointRunnerStep(step)) {
3137
+ const now = Date.now();
3138
+ const statusStep = statusPayload.steps[flatIndex];
3139
+ const checkpoint = { name: step.checkpoint, ...(step.message ? { message: step.message } : {}), status: "pending" as const, stepIndex };
3140
+ statusPayload.state = "paused";
3141
+ statusPayload.currentStep = flatIndex;
3142
+ statusPayload.checkpoint = checkpoint;
3143
+ delete statusPayload.activityState;
3144
+ statusPayload.lastUpdate = now;
3145
+ if (statusStep) {
3146
+ statusStep.status = "paused";
3147
+ statusStep.startedAt = now;
3148
+ statusStep.checkpoint = checkpoint;
3149
+ }
3150
+ writeStatusPayload();
3151
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.checkpoint.paused", ts: now, runId: id, stepIndex, checkpoint }));
3152
+ const decision = await waitForCheckpointDecision();
3153
+ if (decision === "approved") {
3154
+ const approvedAt = Date.now();
3155
+ const approved = { ...checkpoint, status: "approved" as const, approvedAt };
3156
+ statusPayload.state = "running";
3157
+ statusPayload.checkpoint = approved;
3158
+ if (statusStep) {
3159
+ statusStep.status = "complete";
3160
+ statusStep.endedAt = approvedAt;
3161
+ statusStep.durationMs = approvedAt - now;
3162
+ statusStep.exitCode = 0;
3163
+ statusStep.checkpoint = approved;
3164
+ }
3165
+ statusPayload.lastUpdate = approvedAt;
3166
+ writeStatusPayload();
3167
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.checkpoint.approved", ts: approvedAt, runId: id, stepIndex, checkpoint: approved }));
3168
+ flatIndex++;
3169
+ continue;
3170
+ }
3171
+ if (decision === "rejected") {
3172
+ const rejectedAt = Date.now();
3173
+ const rejected = { ...checkpoint, status: "rejected" as const, rejectedAt };
3174
+ checkpointRejected = true;
3175
+ statusPayload.state = "rejected";
3176
+ statusPayload.error = `Checkpoint '${step.checkpoint}' rejected.`;
3177
+ statusPayload.checkpoint = rejected;
3178
+ if (statusStep) {
3179
+ statusStep.status = "rejected";
3180
+ statusStep.error = statusPayload.error;
3181
+ statusStep.endedAt = rejectedAt;
3182
+ statusStep.durationMs = rejectedAt - now;
3183
+ statusStep.exitCode = 1;
3184
+ statusStep.checkpoint = rejected;
3185
+ }
3186
+ statusPayload.lastUpdate = rejectedAt;
3187
+ writeStatusPayload();
3188
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.checkpoint.rejected", ts: rejectedAt, runId: id, stepIndex, checkpoint: rejected }));
3189
+ break;
3190
+ }
3191
+ break;
3192
+ }
3193
+
3194
+ if (isDynamicRunnerGroup(step)) {
3195
+ const groupStartFlatIndex = flatIndex;
3196
+ let materialized: ReturnType<typeof materializeDynamicParallelStep>;
3197
+ try {
3198
+ materialized = materializeDynamicParallelStep(step as Parameters<typeof materializeDynamicParallelStep>[0], outputs, stepIndex, omitUndefinedProperties({ maxItems: config.dynamicFanoutMaxItems, allowRunnerFields: true }));
3199
+ if (materialized.parallel.length > 1 && step.parallel.outputPath && !step.parallel.namespaceOutputPath) {
3200
+ throw new DynamicFanoutError(`Dynamic chain step ${stepIndex + 1} materialized ${materialized.parallel.length} items that resolve output to the same path: ${step.parallel.outputPath}. Remove the explicit output path or use an inherited relative agent output so each item can be isolated.`);
3201
+ }
3202
+ if (materialized.collectedOnEmpty) await validateDynamicCollection(step.collect.outputSchema, materialized.collectedOnEmpty);
3203
+ } catch (error) {
3204
+ const now = Date.now();
3205
+ const message = error instanceof DynamicFanoutError ? error.message : error instanceof Error ? error.message : String(error);
3206
+ statusPayload.state = "failed";
3207
+ statusPayload.error = message;
3208
+ statusPayload.currentStep = flatIndex;
3209
+ const placeholder = statusPayload.steps[groupStartFlatIndex];
3210
+ if (placeholder) {
3211
+ placeholder.status = "failed";
3212
+ placeholder.error = message;
3213
+ placeholder.startedAt = now;
3214
+ placeholder.endedAt = now;
3215
+ placeholder.durationMs = 0;
3216
+ placeholder.exitCode = 1;
3217
+ }
3218
+ statusPayload.lastUpdate = now;
3219
+ markDynamicGraphGroup(stepIndex, "failed", message);
3220
+ writeStatusPayload();
3221
+ results.push(omitUndefinedProperties({ agent: step.parallel.agent, context: step.parallel.context, output: message, error: message, success: false, exitCode: 1 }));
3222
+ break;
3223
+ }
3224
+
3225
+ const effectiveDynamicGroupAcceptance = resolveEffectiveAcceptance(omitUndefinedProperties({
3226
+ explicit: step.acceptanceInput,
3227
+ agentName: step.parallel.agent,
3228
+ acceptanceRole: step.acceptanceRole,
3229
+ task: materialized.parallel.map((task) => task.task ?? step.parallel.task).join("\n") || step.parallel.task,
3230
+ mode: config.mode,
3231
+ async: true,
3232
+ dynamicGroup: true,
3233
+ agentContract: step.agentContract,
3234
+ }));
3235
+
3236
+ if (materialized.parallel.length === 0) {
3237
+ const now = Date.now();
3238
+ const collection = materialized.collectedOnEmpty ?? [];
3239
+ outputs[step.collect.as] = {
3240
+ text: JSON.stringify(collection),
3241
+ structured: collection,
3242
+ agent: step.parallel.agent,
3243
+ stepIndex,
3244
+ };
3245
+ statusPayload.outputs = outputs;
3246
+ const placeholder = statusPayload.steps[groupStartFlatIndex];
3247
+ if (placeholder) {
3248
+ placeholder.status = "complete";
3249
+ placeholder.startedAt = now;
3250
+ placeholder.endedAt = now;
3251
+ placeholder.durationMs = 0;
3252
+ }
3253
+ previousOutput = "Dynamic fanout produced 0 results.";
3254
+ const groupAcceptance = effectiveDynamicGroupAcceptance.explicit && !timedOut && !stopped
3255
+ ? await evaluateAcceptance(omitUndefinedProperties({
3256
+ acceptance: effectiveDynamicGroupAcceptance,
3257
+ output: "",
3258
+ report: aggregateAcceptanceReport({
3259
+ results: [],
3260
+ notes: "Dynamic fanout produced 0 results.",
3261
+ }),
3262
+ cwd,
3263
+ signal: combinedAbortSignal([timeoutAbortController.signal, stopAbortController.signal]),
3264
+ abortMessage: stopAbortController.signal.aborted ? stopMessage : timeoutMessage ?? "Subagent timed out.",
3265
+ reportOptional: isAgentContractV1(step.agentContract),
3266
+ }))
3267
+ : undefined;
3268
+ const groupStopped = stopped || stopAbortController.signal.aborted;
3269
+ const groupTimedOut = !groupStopped && (timedOut || timeoutAbortController.signal.aborted);
3270
+ const effectiveGroupAcceptance = groupTimedOut || groupStopped ? undefined : groupAcceptance;
3271
+ if (placeholder && effectiveGroupAcceptance) placeholder.acceptance = effectiveGroupAcceptance;
3272
+ const groupAcceptanceFailure = effectiveGroupAcceptance && (!isAgentContractV1(step.agentContract) || step.gateOn === "acceptance") ? acceptanceFailureMessage(effectiveGroupAcceptance) : undefined;
3273
+ if (groupTimedOut || groupStopped || groupAcceptanceFailure) {
3274
+ const errorMessage = groupStopped ? stopMessage : groupTimedOut ? timeoutMessage ?? "Subagent timed out." : groupAcceptanceFailure!;
3275
+ statusPayload.state = groupStopped ? "stopped" : "failed";
3276
+ statusPayload.error = errorMessage;
3277
+ setOptionalProperty(statusPayload, "stopped", groupStopped ? true : statusPayload.stopped);
3278
+ if (placeholder) {
3279
+ placeholder.status = groupStopped ? "stopped" : "failed";
3280
+ placeholder.error = errorMessage;
3281
+ placeholder.exitCode = 1;
3282
+ setOptionalProperty(placeholder, "timedOut", groupTimedOut ? true : undefined);
3283
+ setOptionalProperty(placeholder, "stopped", groupStopped ? true : undefined);
3284
+ }
3285
+ markDynamicGraphGroup(stepIndex, groupStopped ? "stopped" : "failed", errorMessage, effectiveGroupAcceptance);
3286
+ statusPayload.lastUpdate = Date.now();
3287
+ writeStatusPayload();
3288
+ results.push(omitUndefinedProperties({ agent: step.parallel.agent, context: step.parallel.context, output: errorMessage, error: errorMessage, success: false, exitCode: 1, timedOut: groupTimedOut ? true : undefined, stopped: groupStopped ? true : undefined, acceptance: effectiveGroupAcceptance }));
3289
+ break;
3290
+ }
3291
+ flatIndex++;
3292
+ statusPayload.lastUpdate = now;
3293
+ markDynamicGraphGroup(stepIndex, "completed", undefined, effectiveGroupAcceptance);
3294
+ writeStatusPayload();
3295
+ continue;
3296
+ }
3297
+
3298
+ const dynamicSteps = materialized.parallel.map((task, itemIndex) => {
3299
+ const thinkingOverride = step.thinkingOverrides?.[itemIndex];
3300
+ const model = thinkingOverride ? applyThinkingSuffix(step.parallel.model, thinkingOverride, true) : step.parallel.model;
3301
+ const thinking = thinkingOverride ? resolveEffectiveThinking(model, thinkingOverride) : undefined;
3302
+ const outputPath = step.parallel.namespaceOutputPath && step.parallel.outputPath
3303
+ ? path.join(path.dirname(step.parallel.outputPath), `dynamic-${stepIndex}`, `${itemIndex}-${step.parallel.agent}`, path.basename(step.parallel.outputPath))
3304
+ : step.parallel.outputPath;
3305
+ const taskText = task.task ?? step.parallel.task;
3306
+ const materializedTask = step.parallel.namespaceOutputPath ? injectSingleOutputInstruction(taskText, outputPath, step.parallel) : taskText;
3307
+ return omitUndefinedProperties({
3308
+ ...step.parallel,
3309
+ task: materializedTask,
3310
+ effectiveAcceptance: resolveEffectiveAcceptance(omitUndefinedProperties({
3311
+ explicit: step.parallel.acceptanceInput,
3312
+ agentName: step.parallel.agent,
3313
+ acceptanceRole: step.parallel.acceptanceRole,
3314
+ task: materializedTask,
3315
+ mode: config.mode,
3316
+ async: true,
3317
+ dynamic: step.parallel.acceptanceInput === undefined,
3318
+ agentContract: step.parallel.agentContract ?? step.agentContract,
3319
+ })),
3320
+ systemPrompt: step.parallel.namespaceOutputPath ? injectOutputPathSystemPrompt(step.parallel.systemPrompt ?? "", outputPath, step.parallel) : step.parallel.systemPrompt,
3321
+ outputPath,
3322
+ label: task.label ?? step.parallel.label,
3323
+ ...(step.sessionFiles?.[itemIndex] ? { sessionFile: step.sessionFiles[itemIndex] } : {}),
3324
+ ...(thinkingOverride ? {
3325
+ ...(model ? { model } : {}),
3326
+ ...(thinking ? { thinking } : {}),
3327
+ ...(step.parallel.modelCandidates ? { modelCandidates: step.parallel.modelCandidates.flatMap((candidate) => {
3328
+ const resolved = applyThinkingSuffix(candidate, thinkingOverride, true);
3329
+ return resolved ? [resolved] : [];
3330
+ }) } : {}),
3331
+ } : {}),
3332
+ structuredOutputSchema: step.parallel.structuredOutputSchema ?? step.parallel.structuredOutput?.schema,
3333
+ });
3334
+ });
3335
+ const dynamicFlatStepCount = Math.max(statusPayload.steps.length - 1 + dynamicSteps.length, 1);
3336
+ const dynamicStatusSteps: RunnerStatusStep[] = dynamicSteps.map((task, itemIndex) => {
3337
+ const transcriptPath = resolveAsyncStepTranscriptPath(omitUndefinedProperties({ artifactsDir, artifactConfig, runId: id, agent: task.agent, flatIndex: groupStartFlatIndex + itemIndex, flatStepCount: dynamicFlatStepCount }));
3338
+ return omitUndefinedProperties({
3339
+ agent: task.agent,
3340
+ ...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),
3341
+ ...(task.context ? { context: task.context } : {}),
3342
+ ...(task.phase ?? step.phase ? { phase: task.phase ?? step.phase } : {}),
3343
+ ...(task.label ? { label: task.label } : {}),
3344
+ structured: Boolean(task.structuredOutputSchema),
3345
+ ...(task.agentContract ? { agentContract: task.agentContract } : {}),
3346
+ ...(task.launchResolvedExtensions ? { launchResolvedExtensions: task.launchResolvedExtensions } : {}),
3347
+ ...(task.capabilityCeiling ? { capabilityCeiling: task.capabilityCeiling } : {}),
3348
+ status: "pending",
3349
+ ...(task.sessionFile ? { sessionFile: task.sessionFile } : {}),
3350
+ ...(transcriptPath ? { transcriptPath } : {}),
3351
+ ...(task.skills ? { skills: task.skills } : {}),
3352
+ ...(task.model ? { model: task.model } : {}),
3353
+ ...(task.thinking ? { thinking: task.thinking } : {}),
3354
+ ...(task.modelCandidates && task.modelCandidates.length > 0 ? { attemptedModels: task.modelCandidates } : task.model ? { attemptedModels: [task.model] } : {}),
3355
+ recentTools: [],
3356
+ recentOutput: [],
3357
+ });
3358
+ });
3359
+ statusPayload.steps.splice(groupStartFlatIndex, 1, ...dynamicStatusSteps);
3360
+ if (config.childIntercomTargets) {
3361
+ config.childIntercomTargets = statusPayload.steps.map((statusStep, index) => resolveSubagentIntercomTarget(id, statusStep.agent, index));
3362
+ }
3363
+ mutatingFailureStates.splice(groupStartFlatIndex, 1, ...dynamicStatusSteps.map(() => createMutatingFailureState()));
3364
+ pendingToolResults.splice(groupStartFlatIndex, 1, ...dynamicStatusSteps.map(() => undefined));
3365
+ const materializedDelta = dynamicStatusSteps.length - 1;
3366
+ for (const group of statusPayload.parallelGroups) {
3367
+ if (group.stepIndex === stepIndex) {
3368
+ group.start = groupStartFlatIndex;
3369
+ group.count = dynamicStatusSteps.length;
3370
+ } else if (group.start > groupStartFlatIndex) {
3371
+ group.start += materializedDelta;
3372
+ }
3373
+ }
3374
+ if (statusPayload.workflowGraph) {
3375
+ const shiftFlatIndexes = (nodes: NonNullable<typeof statusPayload.workflowGraph>["nodes"]): void => {
3376
+ for (const node of nodes) {
3377
+ if (node.stepIndex !== undefined && node.stepIndex > stepIndex && node.flatIndex !== undefined && node.flatIndex >= groupStartFlatIndex) {
3378
+ node.flatIndex += dynamicStatusSteps.length;
3379
+ }
3380
+ if (node.children) shiftFlatIndexes(node.children);
3381
+ }
3382
+ };
3383
+ shiftFlatIndexes(statusPayload.workflowGraph.nodes);
3384
+ const groupNode = statusPayload.workflowGraph.nodes.find((node) => node.id === `step-${stepIndex}`);
3385
+ if (groupNode) {
3386
+ groupNode.children = materialized.items.map((item, itemIndex) => omitUndefinedProperties({
3387
+ id: `step-${stepIndex}-item-${item.idKey}`,
3388
+ kind: "agent",
3389
+ agent: step.parallel.agent,
3390
+ phase: dynamicSteps[itemIndex]?.phase ?? step.phase,
3391
+ label: dynamicSteps[itemIndex]?.label?.trim() || `${step.parallel.agent} ${item.key}`,
3392
+ status: "pending",
3393
+ flatIndex: groupStartFlatIndex + itemIndex,
3394
+ stepIndex,
3395
+ itemKey: item.key,
3396
+ structured: Boolean(dynamicSteps[itemIndex]?.structuredOutputSchema),
3397
+ }));
3398
+ }
3399
+ }
3400
+ writeStatusPayload();
3401
+
3402
+ const concurrency = step.concurrency ?? MAX_PARALLEL_CONCURRENCY;
3403
+ const failFast = step.failFast ?? false;
3404
+ let aborted = false;
3405
+ const parallelResults = await mapConcurrent(dynamicSteps, concurrency, async (task, taskIdx): Promise<StepResult> => {
3406
+ const fi = groupStartFlatIndex + taskIdx;
3407
+ refreshUsageBudget();
3408
+ if (statusPayload.usageBudget?.exhausted) {
3409
+ const skippedAt = Date.now();
3410
+ const message = usageBudgetExceededMessage(statusPayload.usageBudget);
3411
+ requiredStatusStep(statusPayload, fi).status = "failed";
3412
+ requiredStatusStep(statusPayload, fi).error = message;
3413
+ requiredStatusStep(statusPayload, fi).startedAt = skippedAt;
3414
+ requiredStatusStep(statusPayload, fi).endedAt = skippedAt;
3415
+ requiredStatusStep(statusPayload, fi).durationMs = 0;
3416
+ requiredStatusStep(statusPayload, fi).exitCode = 1;
3417
+ statusPayload.lastUpdate = skippedAt;
3418
+ usageBudgetExceeded = true;
3419
+ writeStatusPayload();
3420
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.step.failed", ts: skippedAt, runId: id, stepIndex: fi, agent: task.agent, exitCode: 1, durationMs: 0 }));
3421
+ return omitUndefinedProperties({ agent: task.agent, context: task.context, output: message, error: message, exitCode: 1 as number | null, skipped: true });
3422
+ }
3423
+ if (timedOut) return timedOutStepResult(task.agent, task.context);
3424
+ if (stopped) return stoppedStepResult(task.agent, task.context);
3425
+ if (interrupted) return pausedStepResult(task.agent, task.context);
3426
+ if (aborted && failFast) {
3427
+ const skippedAt = Date.now();
3428
+ requiredStatusStep(statusPayload, fi).status = "failed";
3429
+ requiredStatusStep(statusPayload, fi).error = "Skipped due to fail-fast";
3430
+ requiredStatusStep(statusPayload, fi).startedAt = skippedAt;
3431
+ requiredStatusStep(statusPayload, fi).endedAt = skippedAt;
3432
+ requiredStatusStep(statusPayload, fi).durationMs = 0;
3433
+ requiredStatusStep(statusPayload, fi).exitCode = -1;
3434
+ statusPayload.lastUpdate = skippedAt;
3435
+ writeStatusPayload();
3436
+ return omitUndefinedProperties({ agent: task.agent, context: task.context, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true });
3437
+ }
3438
+ const taskStartTime = Date.now();
3439
+ statusPayload.currentStep = fi;
3440
+ requiredStatusStep(statusPayload, fi).status = "running";
3441
+ delete requiredStatusStep(statusPayload, fi).error;
3442
+ delete requiredStatusStep(statusPayload, fi).activityState;
3443
+ resetStepLiveDetail(requiredStatusStep(statusPayload, fi));
3444
+ requiredStatusStep(statusPayload, fi).startedAt = taskStartTime;
3445
+ requiredStatusStep(statusPayload, fi).lastActivityAt = taskStartTime;
3446
+ statusPayload.outputFile = path.join(asyncDir, `output-${fi}.log`);
3447
+ statusPayload.lastActivityAt = taskStartTime;
3448
+ statusPayload.lastUpdate = taskStartTime;
3449
+ writeStatusPayload();
3450
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.step.started", ts: taskStartTime, runId: id, stepIndex: fi, agent: task.agent }));
3451
+ flushPendingStepSteers(fi);
3452
+ const singleResult = await runSingleStep(task, compactOptional<SingleStepContext>({
3453
+ previousOutput, placeholder, cwd, sessionEnabled,
3454
+ outputs,
3455
+ sessionDir: config.sessionDir ? path.join(config.sessionDir, `dynamic-${stepIndex}-${taskIdx}`) : undefined,
3456
+ artifactsDir, artifactConfig, id,
3457
+ flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
3458
+ outputFile: path.join(asyncDir, `output-${fi}.log`),
3459
+ steerInboxDir: stepSteerInboxDir(asyncDir, fi),
3460
+ steerCapabilityPath: steerCapabilityPath(asyncDir, fi),
3461
+ steerAckDir: steerAcksDir(asyncDir, fi),
3462
+ piPackageRoot: config.piPackageRoot,
3463
+ piArgv1: config.piArgv1,
3464
+ childIntercomTarget: config.childIntercomTargets?.[fi],
3465
+ orchestratorIntercomTarget: config.controlIntercomTarget,
3466
+ nestedRoute: config.nestedRoute,
3467
+ capabilityCeiling: config.capabilityCeiling,
3468
+ registerInterrupt: (interrupt) => registerStepInterrupt(fi, interrupt),
3469
+ registerTimeout: (interrupt) => registerStepTimeout(fi, interrupt),
3470
+ registerStop: (stop) => registerStepStop(fi, stop),
3471
+ registerTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(fi, abort),
3472
+ timeoutSignal: timeoutAbortController.signal,
3473
+ stopSignal: stopAbortController.signal,
3474
+ timeoutMessage,
3475
+ stopMessage,
3476
+ turnBudget: config.turnBudget,
3477
+ onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking),
3478
+ onChildEvent: (event) => updateStepFromChildEvent(fi, event),
3479
+ onWriterProcess,
3480
+ onExternalProcess: (process) => updateExternalProcess(fi, process),
3481
+ skipAcceptance: () => timedOut || stopped,
3482
+ }));
3483
+ const taskEndTime = Date.now();
3484
+ const childInterrupted = singleResult.interrupted === true;
3485
+ const childStopped = singleResult.stopped === true;
3486
+ requiredStatusStep(statusPayload, fi).status = stopped || childStopped ? "stopped" : timedOut ? "failed" : childInterrupted ? "paused" : singleResult.exitCode === 0 ? "complete" : "failed";
3487
+ requiredStatusStep(statusPayload, fi).endedAt = taskEndTime;
3488
+ requiredStatusStep(statusPayload, fi).durationMs = taskEndTime - taskStartTime;
3489
+ requiredStatusStep(statusPayload, fi).exitCode = stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;
3490
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "timedOut", timedOut || singleResult.timedOut ? true : undefined);
3491
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "stopped", stopped || childStopped ? true : undefined);
3492
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "turnBudget", singleResult.turnBudget);
3493
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "turnBudgetExceeded", singleResult.turnBudgetExceeded);
3494
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "wrapUpRequested", singleResult.wrapUpRequested);
3495
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudget", singleResult.toolBudget);
3496
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudgetBlocked", singleResult.toolBudgetBlocked);
3497
+ if (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;
3498
+ if (singleResult.toolBudgetBlocked) statusPayload.toolBudgetBlocked = true;
3499
+ if (singleResult.turnBudget) statusPayload.turnBudget = singleResult.turnBudget;
3500
+ if (singleResult.turnBudgetExceeded) statusPayload.turnBudgetExceeded = true;
3501
+ if (singleResult.wrapUpRequested) statusPayload.wrapUpRequested = true;
3502
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "model", singleResult.model);
3503
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "thinking", resolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, fi).thinking));
3504
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "attemptedModels", singleResult.attemptedModels);
3505
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "modelAttempts", singleResult.modelAttempts);
3506
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "totalCost", singleResult.totalCost);
3507
+ if (singleResult.totalCost) {
3508
+ pendingParallelUsageCost = {
3509
+ inputTokens: pendingParallelUsageCost.inputTokens + singleResult.totalCost.inputTokens,
3510
+ outputTokens: pendingParallelUsageCost.outputTokens + singleResult.totalCost.outputTokens,
3511
+ costUsd: pendingParallelUsageCost.costUsd + singleResult.totalCost.costUsd,
3512
+ };
3513
+ refreshUsageBudget();
3514
+ }
3515
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "error", stopped || childStopped ? stopMessage : timedOut ? (timeoutMessage ?? "Subagent timed out.") : singleResult.error);
3516
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "transcriptPath", singleResult.transcriptPath ?? requiredStatusStep(statusPayload, fi).transcriptPath);
3517
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "transcriptError", singleResult.transcriptError);
3518
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "agentContract", singleResult.agentContract);
3519
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "launchContractDigest", singleResult.launchContractDigest);
3520
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "launchResolvedExtensions", singleResult.launchResolvedExtensions);
3521
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "runtimeAcknowledgedExtensions", singleResult.runtimeAcknowledgedExtensions);
3522
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "effects", singleResult.effects);
3523
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "execution", singleResult.execution);
3524
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "review", singleResult.review);
3525
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "structuredOutput", singleResult.structuredOutput);
3526
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "structuredOutputPath", singleResult.structuredOutputPath);
3527
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "structuredOutputSchemaPath", singleResult.structuredOutputSchemaPath);
3528
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "acceptance", singleResult.acceptance);
3529
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "watchdog", singleResult.watchdog);
3530
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "capabilityCeiling", singleResult.capabilityCeiling);
3531
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "capabilityAudit", singleResult.capabilityAudit);
3532
+ if (singleResult.capabilityCeiling) statusPayload.capabilityCeiling = singleResult.capabilityCeiling;
3533
+ if (singleResult.capabilityAudit) statusPayload.capabilityAudit = singleResult.capabilityAudit;
3534
+ statusPayload.lastUpdate = taskEndTime;
3535
+ writeStatusPayload();
3536
+ appendCapabilityCeilingAppliedEvent(eventsPath, id, fi, task.agent, singleResult);
3537
+ appendJsonl(eventsPath, JSON.stringify({
3538
+ type: stopped || childStopped ? "subagent.step.stopped" : timedOut ? "subagent.step.failed" : childInterrupted ? "subagent.step.paused" : singleResult.exitCode === 0 ? "subagent.step.completed" : "subagent.step.failed",
3539
+ ts: taskEndTime, runId: id, stepIndex: fi, agent: task.agent,
3540
+ exitCode: stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode, durationMs: taskEndTime - taskStartTime,
3541
+ }));
3542
+ if (singleResult.exitCode !== 0 && failFast) aborted = true;
3543
+ return stopped || childStopped ? { ...singleResult, output: stopMessage, error: stopMessage, exitCode: 1, interrupted: false, timedOut: false, stopped: true, skipped: false } : timedOut ? { ...singleResult, output: timeoutMessage ?? "Subagent timed out.", error: timeoutMessage ?? "Subagent timed out.", exitCode: 1, interrupted: false, timedOut: true, skipped: false } : { ...singleResult, skipped: false };
3544
+ }, globalSemaphore);
3545
+
3546
+ flatIndex += dynamicSteps.length;
3547
+ for (const pr of parallelResults) {
3548
+ results.push(omitUndefinedProperties({
3549
+ agent: pr.agent,
3550
+ context: pr.context,
3551
+ agentContract: pr.agentContract,
3552
+ launchContractDigest: pr.launchContractDigest,
3553
+ launchResolvedExtensions: pr.launchResolvedExtensions,
3554
+ runtimeAcknowledgedExtensions: pr.runtimeAcknowledgedExtensions,
3555
+ output: pr.output,
3556
+ outputState: pr.outputState,
3557
+ error: pr.error,
3558
+ protocolError: pr.protocolError,
3559
+ success: pr.stopped !== true && pr.interrupted !== true && pr.exitCode === 0,
3560
+ exitCode: pr.interrupted === true ? 0 : pr.exitCode,
3561
+ skipped: pr.skipped,
3562
+ interrupted: pr.interrupted,
3563
+ timedOut: pr.timedOut,
3564
+ stopped: pr.stopped,
3565
+ turnBudget: pr.turnBudget,
3566
+ turnBudgetExceeded: pr.turnBudgetExceeded,
3567
+ wrapUpRequested: pr.wrapUpRequested,
3568
+ toolBudget: pr.toolBudget,
3569
+ toolBudgetBlocked: pr.toolBudgetBlocked,
3570
+ sessionFile: pr.sessionFile,
3571
+ intercomTarget: pr.intercomTarget,
3572
+ model: pr.model,
3573
+ attemptedModels: pr.attemptedModels,
3574
+ modelAttempts: pr.modelAttempts,
3575
+ totalCost: pr.totalCost,
3576
+ artifactPaths: pr.artifactPaths,
3577
+ transcriptPath: pr.transcriptPath,
3578
+ transcriptError: pr.transcriptError,
3579
+ effects: pr.effects,
3580
+ execution: pr.execution,
3581
+ review: pr.review,
3582
+ structuredOutput: pr.structuredOutput,
3583
+ structuredOutputPath: pr.structuredOutputPath,
3584
+ structuredOutputSchemaPath: pr.structuredOutputSchemaPath,
3585
+ acceptance: pr.acceptance,
3586
+ watchdog: pr.watchdog,
3587
+ capabilityCeiling: pr.capabilityCeiling,
3588
+ capabilityAudit: pr.capabilityAudit,
3589
+ }));
3590
+ }
3591
+ pendingParallelUsageCost = { inputTokens: 0, outputTokens: 0, costUsd: 0 };
3592
+ refreshUsageBudget();
3593
+ const collection = collectDynamicResults(step as Parameters<typeof collectDynamicResults>[0], materialized.items, parallelResults);
3594
+ const failures = parallelResults.filter((result) => result.exitCode !== 0 && result.exitCode !== -1);
3595
+ const acceptanceFailures = parallelResults
3596
+ .map((result, originalIndex) => ({ result, originalIndex, task: dynamicSteps[originalIndex] }))
3597
+ .filter(({ result, task }) => isAgentContractV1(task?.agentContract ?? step.agentContract) && task?.gateOn === "acceptance" && result.acceptance?.status === "rejected");
3598
+ if (acceptanceFailures.length > 0) {
3599
+ const message = acceptanceFailures
3600
+ .map(({ result, originalIndex }) => `Dynamic item ${originalIndex + 1} (${result.agent}, key ${materialized.items[originalIndex]?.key ?? originalIndex}) acceptance rejected: ${(result.acceptance ? acceptanceFailureMessage(result.acceptance) : undefined) ?? "acceptance rejected"}`)
3601
+ .join("\n");
3602
+ results.push(omitUndefinedProperties({ agent: step.parallel.agent, context: step.parallel.context, output: message, error: message, success: false, exitCode: 1, structuredOutput: collection }));
3603
+ statusPayload.error = message;
3604
+ markDynamicGraphGroup(stepIndex, "failed", message);
3605
+ }
3606
+ if (failures.length === 0 && acceptanceFailures.length === 0) {
3607
+ try {
3608
+ await validateDynamicCollection(step.collect.outputSchema, collection);
3609
+ outputs[step.collect.as] = {
3610
+ text: JSON.stringify(collection),
3611
+ structured: collection,
3612
+ agent: step.parallel.agent,
3613
+ stepIndex,
3614
+ };
3615
+ statusPayload.outputs = outputs;
3616
+ const groupAcceptance = !timedOut && !stopped
3617
+ ? await evaluateAcceptance(omitUndefinedProperties({
3618
+ acceptance: effectiveDynamicGroupAcceptance,
3619
+ output: "",
3620
+ report: aggregateAcceptanceReport({
3621
+ results: parallelResults,
3622
+ notes: `Dynamic fanout collected ${collection.length} result(s) into ${step.collect.as}.`,
3623
+ }),
3624
+ cwd,
3625
+ signal: combinedAbortSignal([timeoutAbortController.signal, stopAbortController.signal]),
3626
+ abortMessage: stopAbortController.signal.aborted ? stopMessage : timeoutMessage ?? "Subagent timed out.",
3627
+ reportOptional: isAgentContractV1(step.agentContract),
3628
+ }))
3629
+ : undefined;
3630
+ const groupStopped = stopped || stopAbortController.signal.aborted;
3631
+ const groupTimedOut = !groupStopped && (timedOut || timeoutAbortController.signal.aborted);
3632
+ const effectiveGroupAcceptance = groupTimedOut || groupStopped ? undefined : groupAcceptance;
3633
+ const groupAcceptanceFailure = effectiveDynamicGroupAcceptance.explicit && effectiveGroupAcceptance && (!isAgentContractV1(step.agentContract) || step.gateOn === "acceptance") ? acceptanceFailureMessage(effectiveGroupAcceptance) : undefined;
3634
+ const groupError = groupStopped ? stopMessage : groupTimedOut ? timeoutMessage ?? "Subagent timed out." : groupAcceptanceFailure;
3635
+ markDynamicGraphGroup(stepIndex, groupError ? groupStopped ? "stopped" : "failed" : "completed", groupError, effectiveGroupAcceptance);
3636
+ if (groupError) {
3637
+ results.push(omitUndefinedProperties({
3638
+ agent: step.parallel.agent,
3639
+ output: groupError,
3640
+ error: groupError,
3641
+ success: false,
3642
+ exitCode: 1,
3643
+ timedOut: groupTimedOut ? true : undefined,
3644
+ stopped: groupStopped ? true : undefined,
3645
+ structuredOutput: collection,
3646
+ acceptance: effectiveGroupAcceptance,
3647
+ }));
3648
+ statusPayload.error = groupError;
3649
+ setOptionalProperty(statusPayload, "stopped", groupStopped ? true : statusPayload.stopped);
3650
+ }
3651
+ } catch (error) {
3652
+ const message = error instanceof DynamicFanoutError ? error.message : error instanceof Error ? error.message : String(error);
3653
+ results.push(omitUndefinedProperties({ agent: step.parallel.agent, context: step.parallel.context, output: message, error: message, success: false, exitCode: 1, structuredOutput: collection }));
3654
+ statusPayload.error = message;
3655
+ markDynamicGraphGroup(stepIndex, "failed", message);
3656
+ }
3657
+ }
3658
+ previousOutput = aggregateParallelOutputs(
3659
+ parallelResults.map((r, i) => omitUndefinedProperties({
3660
+ agent: r.agent,
3661
+ taskIndex: i,
3662
+ output: r.output,
3663
+ exitCode: r.exitCode,
3664
+ error: r.error,
3665
+ })),
3666
+ (i, agent) => `=== Dynamic Item ${i + 1} (${agent}, key ${materialized.items[i]?.key ?? i}) ===`,
3667
+ );
3668
+ appendJsonl(eventsPath, JSON.stringify({
3669
+ type: "subagent.dynamic.completed",
3670
+ ts: Date.now(),
3671
+ runId: id,
3672
+ stepIndex,
3673
+ success: failures.length === 0 && acceptanceFailures.length === 0,
3674
+ }));
3675
+ if (failures.length > 0) markDynamicGraphGroup(stepIndex, "failed", failures[0]?.error ?? "Dynamic fanout child failed.");
3676
+ statusPayload.lastUpdate = Date.now();
3677
+ writeStatusPayload();
3678
+ if (failures.length > 0 || statusPayload.error) break;
3679
+ continue;
3680
+ }
3681
+
3682
+ if (isParallelGroup(step)) {
3683
+ const group = step;
3684
+ const concurrency = group.concurrency ?? MAX_PARALLEL_CONCURRENCY;
3685
+ const failFast = group.failFast ?? false;
3686
+ const groupStartFlatIndex = flatIndex;
3687
+ let aborted = false;
3688
+ let worktreeSetup: WorktreeSetup | undefined;
3689
+ let worktreeFinalized = false;
3690
+ if (group.worktree) {
3691
+ const worktreeTaskCwdConflict = findWorktreeTaskCwdConflict(group.parallel, cwd);
3692
+ if (worktreeTaskCwdConflict) {
3693
+ const failedAt = Date.now();
3694
+ markParallelGroupSetupFailure({
3695
+ statusPayload,
3696
+ results,
3697
+ group,
3698
+ groupStartFlatIndex,
3699
+ setupError: formatWorktreeTaskCwdConflict(worktreeTaskCwdConflict, cwd),
3700
+ failedAt,
3701
+ statusPath,
3702
+ eventsPath,
3703
+ asyncDir,
3704
+ runId: id,
3705
+ stepIndex,
3706
+ });
3707
+ flatIndex += group.parallel.length;
3708
+ break;
3709
+ }
3710
+ try {
3711
+ worktreeSetup = createWorktrees(cwd, `${id}-s${stepIndex}`, group.parallel.length, omitUndefinedProperties({
3712
+ agents: group.parallel.map((task) => task.agent),
3713
+ setupHook: config.worktreeSetupHook
3714
+ ? omitUndefinedProperties({ hookPath: config.worktreeSetupHook, timeoutMs: config.worktreeSetupHookTimeoutMs })
3715
+ : undefined,
3716
+ baseDir: config.worktreeBaseDir,
3717
+ }));
3718
+ } catch (error) {
3719
+ const setupError = error instanceof Error ? error.message : String(error);
3720
+ const failedAt = Date.now();
3721
+ markParallelGroupSetupFailure({
3722
+ statusPayload,
3723
+ results,
3724
+ group,
3725
+ groupStartFlatIndex,
3726
+ setupError,
3727
+ failedAt,
3728
+ statusPath,
3729
+ eventsPath,
3730
+ asyncDir,
3731
+ runId: id,
3732
+ stepIndex,
3733
+ });
3734
+ flatIndex += group.parallel.length;
3735
+ break;
3736
+ }
3737
+ }
3738
+
3739
+ try {
3740
+ if (worktreeSetup) {
3741
+ writePendingParallelHandoff({
3742
+ manifestPath: parallelHandoffPath(asyncDir),
3743
+ runId: id,
3744
+ mode: (config.resultMode ?? statusPayload.mode) === "parallel" ? "parallel" : "chain",
3745
+ source: "async",
3746
+ cwd,
3747
+ stepIndex,
3748
+ flatStartIndex: groupStartFlatIndex,
3749
+ setup: worktreeSetup,
3750
+ });
3751
+ }
3752
+ if (group.worktree) ensureParallelProgressFile(cwd, group);
3753
+ const groupStartTime = Date.now();
3754
+ markParallelGroupRunning({
3755
+ statusPayload,
3756
+ group,
3757
+ groupStartFlatIndex,
3758
+ groupStartTime,
3759
+ statusPath,
3760
+ eventsPath,
3761
+ asyncDir,
3762
+ runId: id,
3763
+ stepIndex,
3764
+ });
3765
+ const parallelResults = await mapConcurrent(
3766
+ group.parallel,
3767
+ concurrency,
3768
+ async (task, taskIdx): Promise<StepResult> => {
3769
+ const fi = groupStartFlatIndex + taskIdx;
3770
+ refreshUsageBudget();
3771
+ if (statusPayload.usageBudget?.exhausted) {
3772
+ const skippedAt = Date.now();
3773
+ const message = usageBudgetExceededMessage(statusPayload.usageBudget);
3774
+ requiredStatusStep(statusPayload, fi).status = "failed";
3775
+ requiredStatusStep(statusPayload, fi).error = message;
3776
+ requiredStatusStep(statusPayload, fi).startedAt = skippedAt;
3777
+ requiredStatusStep(statusPayload, fi).endedAt = skippedAt;
3778
+ requiredStatusStep(statusPayload, fi).durationMs = 0;
3779
+ requiredStatusStep(statusPayload, fi).exitCode = 1;
3780
+ delete requiredStatusStep(statusPayload, fi).activityState;
3781
+ statusPayload.lastUpdate = skippedAt;
3782
+ usageBudgetExceeded = true;
3783
+ writeStatusPayload();
3784
+ appendJsonl(eventsPath, JSON.stringify({
3785
+ type: "subagent.step.failed", ts: skippedAt, runId: id, stepIndex: fi, agent: task.agent, exitCode: 1, durationMs: 0,
3786
+ }));
3787
+ return omitUndefinedProperties({ agent: task.agent, context: task.context, output: message, error: message, exitCode: 1 as number | null, skipped: true });
3788
+ }
3789
+ if (timedOut) return timedOutStepResult(task.agent, task.context);
3790
+ if (stopped) return stoppedStepResult(task.agent, task.context);
3791
+ if (interrupted) return pausedStepResult(task.agent, task.context);
3792
+ if (aborted && failFast) {
3793
+ const skippedAt = Date.now();
3794
+ requiredStatusStep(statusPayload, fi).status = "failed";
3795
+ requiredStatusStep(statusPayload, fi).error = "Skipped due to fail-fast";
3796
+ requiredStatusStep(statusPayload, fi).startedAt = skippedAt;
3797
+ requiredStatusStep(statusPayload, fi).endedAt = skippedAt;
3798
+ requiredStatusStep(statusPayload, fi).durationMs = 0;
3799
+ requiredStatusStep(statusPayload, fi).exitCode = -1;
3800
+ delete requiredStatusStep(statusPayload, fi).activityState;
3801
+ statusPayload.lastUpdate = skippedAt;
3802
+ writeStatusPayload();
3803
+ appendJsonl(eventsPath, JSON.stringify({
3804
+ type: "subagent.step.failed", ts: skippedAt, runId: id, stepIndex: fi, agent: task.agent, exitCode: -1, durationMs: 0,
3805
+ }));
3806
+ return omitUndefinedProperties({ agent: task.agent, context: task.context, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true });
3807
+ }
3808
+
3809
+ const taskStartTime = Date.now();
3810
+ statusPayload.currentStep = fi;
3811
+ requiredStatusStep(statusPayload, fi).status = "running";
3812
+ delete requiredStatusStep(statusPayload, fi).error;
3813
+ delete requiredStatusStep(statusPayload, fi).activityState;
3814
+ resetStepLiveDetail(requiredStatusStep(statusPayload, fi));
3815
+ requiredStatusStep(statusPayload, fi).startedAt = taskStartTime;
3816
+ delete requiredStatusStep(statusPayload, fi).endedAt;
3817
+ delete requiredStatusStep(statusPayload, fi).durationMs;
3818
+ requiredStatusStep(statusPayload, fi).lastActivityAt = taskStartTime;
3819
+ statusPayload.outputFile = path.join(asyncDir, `output-${fi}.log`);
3820
+ statusPayload.lastActivityAt = taskStartTime;
3821
+ statusPayload.lastUpdate = taskStartTime;
3822
+ writeStatusPayload();
3823
+
3824
+ appendJsonl(eventsPath, JSON.stringify({
3825
+ type: "subagent.step.started", ts: taskStartTime, runId: id, stepIndex: fi, agent: task.agent,
3826
+ }));
3827
+
3828
+ const taskSessionDir = config.sessionDir
3829
+ ? path.join(config.sessionDir, `parallel-${taskIdx}`)
3830
+ : undefined;
3831
+ const { taskForRun, taskCwd } = prepareParallelTaskRun(task, cwd, worktreeSetup, taskIdx);
3832
+ flushPendingStepSteers(fi);
3833
+
3834
+ const singleResult = await runSingleStep(taskForRun, compactOptional<SingleStepContext>({
3835
+ previousOutput, placeholder, cwd: taskCwd, sessionEnabled,
3836
+ outputs,
3837
+ sessionDir: taskSessionDir,
3838
+ artifactsDir, artifactConfig, id,
3839
+ flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
3840
+ outputFile: path.join(asyncDir, `output-${fi}.log`),
3841
+ steerInboxDir: stepSteerInboxDir(asyncDir, fi),
3842
+ steerCapabilityPath: steerCapabilityPath(asyncDir, fi),
3843
+ steerAckDir: steerAcksDir(asyncDir, fi),
3844
+ piPackageRoot: config.piPackageRoot,
3845
+ piArgv1: config.piArgv1,
3846
+ childIntercomTarget: config.childIntercomTargets?.[fi],
3847
+ orchestratorIntercomTarget: config.controlIntercomTarget,
3848
+ nestedRoute: config.nestedRoute,
3849
+ capabilityCeiling: config.capabilityCeiling,
3850
+ registerInterrupt: (interrupt) => registerStepInterrupt(fi, interrupt),
3851
+ registerTimeout: (interrupt) => registerStepTimeout(fi, interrupt),
3852
+ registerStop: (stop) => registerStepStop(fi, stop),
3853
+ registerTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(fi, abort),
3854
+ timeoutSignal: timeoutAbortController.signal,
3855
+ stopSignal: stopAbortController.signal,
3856
+ timeoutMessage,
3857
+ stopMessage,
3858
+ turnBudget: config.turnBudget,
3859
+ onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking),
3860
+ onChildEvent: (event) => updateStepFromChildEvent(fi, event),
3861
+ onWriterProcess,
3862
+ onExternalProcess: (process) => updateExternalProcess(fi, process),
3863
+ skipAcceptance: () => timedOut || stopped,
3864
+ }));
3865
+ if (task.sessionFile) {
3866
+ latestSessionFile = task.sessionFile;
3867
+ }
3868
+
3869
+ const taskEndTime = Date.now();
3870
+ const taskDuration = taskEndTime - taskStartTime;
3871
+ const childInterrupted = singleResult.interrupted === true;
3872
+ const childStopped = singleResult.stopped === true;
3873
+
3874
+ requiredStatusStep(statusPayload, fi).status = stopped || childStopped ? "stopped" : timedOut ? "failed" : childInterrupted ? "paused" : singleResult.exitCode === 0 ? "complete" : "failed";
3875
+ requiredStatusStep(statusPayload, fi).endedAt = taskEndTime;
3876
+ requiredStatusStep(statusPayload, fi).durationMs = taskDuration;
3877
+ requiredStatusStep(statusPayload, fi).exitCode = stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;
3878
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "timedOut", timedOut || singleResult.timedOut ? true : undefined);
3879
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "stopped", stopped || childStopped ? true : undefined);
3880
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "turnBudget", singleResult.turnBudget);
3881
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "turnBudgetExceeded", singleResult.turnBudgetExceeded);
3882
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "wrapUpRequested", singleResult.wrapUpRequested);
3883
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudget", singleResult.toolBudget);
3884
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudgetBlocked", singleResult.toolBudgetBlocked);
3885
+ if (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;
3886
+ if (singleResult.toolBudgetBlocked) statusPayload.toolBudgetBlocked = true;
3887
+ if (singleResult.turnBudget) statusPayload.turnBudget = singleResult.turnBudget;
3888
+ if (singleResult.turnBudgetExceeded) statusPayload.turnBudgetExceeded = true;
3889
+ if (singleResult.wrapUpRequested) statusPayload.wrapUpRequested = true;
3890
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "model", singleResult.model);
3891
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "thinking", resolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, fi).thinking));
3892
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "attemptedModels", singleResult.attemptedModels);
3893
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "modelAttempts", singleResult.modelAttempts);
3894
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "totalCost", singleResult.totalCost);
3895
+ if (singleResult.totalCost) {
3896
+ pendingParallelUsageCost = {
3897
+ inputTokens: pendingParallelUsageCost.inputTokens + singleResult.totalCost.inputTokens,
3898
+ outputTokens: pendingParallelUsageCost.outputTokens + singleResult.totalCost.outputTokens,
3899
+ costUsd: pendingParallelUsageCost.costUsd + singleResult.totalCost.costUsd,
3900
+ };
3901
+ refreshUsageBudget();
3902
+ }
3903
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "error", stopped || childStopped ? stopMessage : timedOut ? (timeoutMessage ?? "Subagent timed out.") : singleResult.error);
3904
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "transcriptPath", singleResult.transcriptPath ?? requiredStatusStep(statusPayload, fi).transcriptPath);
3905
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "transcriptError", singleResult.transcriptError);
3906
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "agentContract", singleResult.agentContract);
3907
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "launchResolvedExtensions", singleResult.launchResolvedExtensions);
3908
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "runtimeAcknowledgedExtensions", singleResult.runtimeAcknowledgedExtensions);
3909
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "effects", singleResult.effects);
3910
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "execution", singleResult.execution);
3911
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "review", singleResult.review);
3912
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "structuredOutput", singleResult.structuredOutput);
3913
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "structuredOutputPath", singleResult.structuredOutputPath);
3914
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "structuredOutputSchemaPath", singleResult.structuredOutputSchemaPath);
3915
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "acceptance", singleResult.acceptance);
3916
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "watchdog", singleResult.watchdog);
3917
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "capabilityCeiling", singleResult.capabilityCeiling);
3918
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "capabilityAudit", singleResult.capabilityAudit);
3919
+ if (singleResult.capabilityCeiling) statusPayload.capabilityCeiling = singleResult.capabilityCeiling;
3920
+ if (singleResult.capabilityAudit) statusPayload.capabilityAudit = singleResult.capabilityAudit;
3921
+ statusPayload.lastUpdate = taskEndTime;
3922
+ writeStatusPayload();
3923
+ appendCapabilityCeilingAppliedEvent(eventsPath, id, fi, task.agent, singleResult);
3924
+
3925
+ appendJsonl(eventsPath, JSON.stringify({
3926
+ type: stopped || childStopped ? "subagent.step.stopped" : timedOut ? "subagent.step.failed" : childInterrupted ? "subagent.step.paused" : singleResult.exitCode === 0 ? "subagent.step.completed" : "subagent.step.failed",
3927
+ ts: taskEndTime, runId: id, stepIndex: fi, agent: task.agent,
3928
+ exitCode: stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode, durationMs: taskDuration,
3929
+ }));
3930
+ if (singleResult.completionGuardTriggered) {
3931
+ const event = buildControlEvent(omitUndefinedProperties({
3932
+ from: requiredStatusStep(statusPayload, fi).activityState,
3933
+ to: "needs_attention",
3934
+ runId: id,
3935
+ agent: task.agent,
3936
+ index: fi,
3937
+ ts: taskEndTime,
3938
+ message: `${task.agent} completed without making edits for an implementation task`,
3939
+ reason: "completion_guard",
3940
+ }));
3941
+ appendControlEvent(event);
3942
+ }
3943
+
3944
+ if (singleResult.exitCode !== 0 && failFast) aborted = true;
3945
+ return stopped || childStopped ? { ...singleResult, output: stopMessage, error: stopMessage, exitCode: 1, interrupted: false, timedOut: false, stopped: true, skipped: false } : timedOut ? { ...singleResult, output: timeoutMessage ?? "Subagent timed out.", error: timeoutMessage ?? "Subagent timed out.", exitCode: 1, interrupted: false, timedOut: true, skipped: false } : { ...singleResult, skipped: false };
3946
+ },
3947
+ globalSemaphore,
3948
+ );
3949
+
3950
+ flatIndex += group.parallel.length;
3951
+
3952
+ for (let t = 0; t < group.parallel.length; t++) {
3953
+ const fi = groupStartFlatIndex + t;
3954
+ const sessionTokens = config.sessionDir
3955
+ ? parseSessionTokens(path.join(config.sessionDir, `parallel-${t}`))
3956
+ : null;
3957
+ const taskTokens = sessionTokens ?? tokenUsageFromAttempts(parallelResults[t]?.modelAttempts);
3958
+ if (!taskTokens) continue;
3959
+ requiredStatusStep(statusPayload, fi).tokens = taskTokens;
3960
+ previousCumulativeTokens = {
3961
+ input: previousCumulativeTokens.input + taskTokens.input,
3962
+ output: previousCumulativeTokens.output + taskTokens.output,
3963
+ total: previousCumulativeTokens.total + taskTokens.total,
3964
+ };
3965
+ }
3966
+ statusPayload.totalTokens = { ...previousCumulativeTokens };
3967
+ statusPayload.lastUpdate = Date.now();
3968
+ writeStatusPayload();
3969
+
3970
+ for (const pr of parallelResults) {
3971
+ results.push(omitUndefinedProperties({
3972
+ agent: pr.agent,
3973
+ context: pr.context,
3974
+ agentContract: pr.agentContract,
3975
+ launchContractDigest: pr.launchContractDigest,
3976
+ launchResolvedExtensions: pr.launchResolvedExtensions,
3977
+ output: pr.output,
3978
+ outputState: pr.outputState,
3979
+ error: pr.error,
3980
+ protocolError: pr.protocolError,
3981
+ success: pr.stopped !== true && pr.interrupted !== true && pr.exitCode === 0,
3982
+ exitCode: pr.interrupted === true ? 0 : pr.exitCode,
3983
+ skipped: pr.skipped,
3984
+ interrupted: pr.interrupted,
3985
+ timedOut: pr.timedOut,
3986
+ stopped: pr.stopped,
3987
+ turnBudget: pr.turnBudget,
3988
+ turnBudgetExceeded: pr.turnBudgetExceeded,
3989
+ wrapUpRequested: pr.wrapUpRequested,
3990
+ toolBudget: pr.toolBudget,
3991
+ toolBudgetBlocked: pr.toolBudgetBlocked,
3992
+ sessionFile: pr.sessionFile,
3993
+ intercomTarget: pr.intercomTarget,
3994
+ model: pr.model,
3995
+ attemptedModels: pr.attemptedModels,
3996
+ modelAttempts: pr.modelAttempts,
3997
+ totalCost: pr.totalCost,
3998
+ artifactPaths: pr.artifactPaths,
3999
+ transcriptPath: pr.transcriptPath,
4000
+ transcriptError: pr.transcriptError,
4001
+ effects: pr.effects,
4002
+ execution: pr.execution,
4003
+ review: pr.review,
4004
+ structuredOutput: pr.structuredOutput,
4005
+ structuredOutputPath: pr.structuredOutputPath,
4006
+ structuredOutputSchemaPath: pr.structuredOutputSchemaPath,
4007
+ acceptance: pr.acceptance,
4008
+ watchdog: pr.watchdog,
4009
+ }));
4010
+ }
4011
+ pendingParallelUsageCost = { inputTokens: 0, outputTokens: 0, costUsd: 0 };
4012
+ refreshUsageBudget();
4013
+ for (let t = 0; t < group.parallel.length; t++) {
4014
+ const outputName = group.parallel[t]?.outputName;
4015
+ if (outputName) outputs[outputName] = outputEntryFromAsyncResult({
4016
+ agent: parallelResults[t]!.agent,
4017
+ output: parallelResults[t]!.output,
4018
+ structuredOutput: parallelResults[t]!.structuredOutput,
4019
+ }, stepIndex);
4020
+ }
4021
+ statusPayload.outputs = outputs;
4022
+
4023
+ previousOutput = aggregateParallelOutputs(
4024
+ parallelResults.map((r) => omitUndefinedProperties({
4025
+ agent: r.agent,
4026
+ output: r.output,
4027
+ exitCode: r.exitCode,
4028
+ error: r.error,
4029
+ model: r.model,
4030
+ attemptedModels: r.attemptedModels,
4031
+ })),
4032
+ );
4033
+ if (worktreeSetup) {
4034
+ const captured = captureParallelWorktreeDiffs(worktreeSetup, asyncDir, stepIndex, group);
4035
+ if (captured.summary) previousOutput = `${previousOutput}\n\n${captured.summary}`;
4036
+ worktreeFinalized = true;
4037
+ const manifestPath = parallelHandoffPath(asyncDir);
4038
+ const handoff = {
4039
+ manifestPath,
4040
+ runId: id,
4041
+ mode: (config.resultMode ?? statusPayload.mode) === "parallel" ? "parallel" as const : "chain" as const,
4042
+ source: "async" as const,
4043
+ cwd,
4044
+ stepIndex,
4045
+ flatStartIndex: groupStartFlatIndex,
4046
+ setup: worktreeSetup,
4047
+ diffs: captured.diffs,
4048
+ results: parallelResults.map((result) => ({
4049
+ agent: result.agent,
4050
+ status: result.stopped || (result.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
4051
+ processSignal: result.processSignal,
4052
+ interrupted: result.interrupted,
4053
+ timedOut: result.timedOut,
4054
+ stopped: result.stopped,
4055
+ turnBudgetExceeded: result.turnBudgetExceeded,
4056
+ }))) ? "stopped" as const : result.interrupted ? "paused" as const : result.exitCode === 0 ? "completed" as const : "failed" as const,
4057
+ summary: result.output || result.error || "(no output)",
4058
+ ...(result.artifactPaths?.outputPath ? { outputPath: result.artifactPaths.outputPath } : {}),
4059
+ ...(result.structuredOutput !== undefined ? { structuredOutput: result.structuredOutput } : {}),
4060
+ ...(result.structuredOutputPath ? { structuredOutputPath: result.structuredOutputPath } : {}),
4061
+ ...(result.sessionFile ? { sessionPath: result.sessionFile } : {}),
4062
+ })),
4063
+ };
4064
+ try {
4065
+ writeParallelHandoffGroup(handoff);
4066
+ const cleanup = cleanupWorktrees(worktreeSetup, { kind: "preserve", capturedDiffs: captured.diffs, handoffManifestPath: manifestPath });
4067
+ statusPayload.parallelHandoff = writeParallelHandoffGroup({ ...handoff, cleanup });
4068
+ previousOutput = `${previousOutput}\n\n${formatParallelHandoffReference(statusPayload.parallelHandoff)}`;
4069
+ } catch (error) {
4070
+ previousOutput = `${previousOutput}\n\n${formatParallelHandoffError(error)}`;
4071
+ }
4072
+ writeStatusPayload();
4073
+ }
4074
+
4075
+ appendJsonl(eventsPath, JSON.stringify({
4076
+ type: "subagent.parallel.completed",
4077
+ ts: Date.now(),
4078
+ runId: id,
4079
+ stepIndex,
4080
+ success: parallelResults.every((r) => r.exitCode === 0 || r.exitCode === -1)
4081
+ && parallelResults.every((result, index) => !(isAgentContractV1(group.parallel[index]?.agentContract) && group.parallel[index]?.gateOn === "acceptance" && result.acceptance?.status === "rejected")),
4082
+ }));
4083
+
4084
+ const acceptanceGateFailure = parallelResults
4085
+ .map((result, index) => ({ result, index, task: group.parallel[index] }))
4086
+ .find(({ result, task }) => isAgentContractV1(task?.agentContract) && task?.gateOn === "acceptance" && result.acceptance?.status === "rejected");
4087
+ if (acceptanceGateFailure) {
4088
+ statusPayload.error = (acceptanceGateFailure.result.acceptance ? acceptanceFailureMessage(acceptanceGateFailure.result.acceptance) : undefined) ?? "Parallel acceptance gate rejected the step.";
4089
+ writeStatusPayload();
4090
+ break;
4091
+ }
4092
+ if (parallelResults.some((r) => r.exitCode !== 0 && r.exitCode !== -1)) {
4093
+ break;
4094
+ }
4095
+ } finally {
4096
+ if (worktreeSetup && !worktreeFinalized) cleanupWorktrees(worktreeSetup);
4097
+ }
4098
+ } else {
4099
+ const seqStep = step as SubagentStep;
4100
+ const stepStartTime = Date.now();
4101
+ statusPayload.currentStep = flatIndex;
4102
+ requiredStatusStep(statusPayload, flatIndex).status = "running";
4103
+ delete requiredStatusStep(statusPayload, flatIndex).activityState;
4104
+ delete statusPayload.activityState;
4105
+ resetStepLiveDetail(requiredStatusStep(statusPayload, flatIndex));
4106
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "skills", seqStep.skills);
4107
+ requiredStatusStep(statusPayload, flatIndex).startedAt = stepStartTime;
4108
+ requiredStatusStep(statusPayload, flatIndex).lastActivityAt = stepStartTime;
4109
+ statusPayload.lastActivityAt = stepStartTime;
4110
+ statusPayload.lastUpdate = stepStartTime;
4111
+ statusPayload.outputFile = path.join(asyncDir, `output-${flatIndex}.log`);
4112
+ writeStatusPayload();
4113
+
4114
+ appendJsonl(eventsPath, JSON.stringify({
4115
+ type: "subagent.step.started",
4116
+ ts: stepStartTime,
4117
+ runId: id,
4118
+ stepIndex: flatIndex,
4119
+ agent: seqStep.agent,
4120
+ }));
4121
+
4122
+ flushPendingStepSteers(flatIndex);
4123
+ const singleResult = await runSingleStep(seqStep, compactOptional<SingleStepContext>({
4124
+ previousOutput, placeholder, cwd, sessionEnabled,
4125
+ outputs: statusPayload.mode === "single" ? undefined : outputs,
4126
+ sessionDir: config.sessionDir,
4127
+ artifactsDir, artifactConfig, id,
4128
+ flatIndex, flatStepCount: Math.max(statusPayload.steps.length, 1),
4129
+ outputFile: path.join(asyncDir, `output-${flatIndex}.log`),
4130
+ steerInboxDir: stepSteerInboxDir(asyncDir, flatIndex),
4131
+ steerCapabilityPath: steerCapabilityPath(asyncDir, flatIndex),
4132
+ steerAckDir: steerAcksDir(asyncDir, flatIndex),
4133
+ piPackageRoot: config.piPackageRoot,
4134
+ piArgv1: config.piArgv1,
4135
+ childIntercomTarget: config.childIntercomTargets?.[flatIndex],
4136
+ orchestratorIntercomTarget: config.controlIntercomTarget,
4137
+ nestedRoute: config.nestedRoute,
4138
+ capabilityCeiling: config.capabilityCeiling,
4139
+ registerInterrupt: (interrupt) => registerStepInterrupt(flatIndex, interrupt),
4140
+ registerTimeout: (interrupt) => registerStepTimeout(flatIndex, interrupt),
4141
+ registerStop: (stop) => registerStepStop(flatIndex, stop),
4142
+ registerTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(flatIndex, abort),
4143
+ timeoutSignal: timeoutAbortController.signal,
4144
+ stopSignal: stopAbortController.signal,
4145
+ timeoutMessage,
4146
+ stopMessage,
4147
+ turnBudget: config.turnBudget,
4148
+ onAttemptStart: (attempt) => updateStepModel(flatIndex, attempt.model, attempt.thinking),
4149
+ onChildEvent: (event) => updateStepFromChildEvent(flatIndex, event),
4150
+ onWriterProcess,
4151
+ onExternalProcess: (process) => updateExternalProcess(flatIndex, process),
4152
+ skipAcceptance: () => timedOut || stopped,
4153
+ }));
4154
+ if (seqStep.sessionFile) {
4155
+ latestSessionFile = seqStep.sessionFile;
4156
+ }
4157
+
4158
+ previousOutput = singleResult.output;
4159
+ const childStopped = singleResult.stopped === true;
4160
+ results.push(omitUndefinedProperties({
4161
+ agent: singleResult.agent,
4162
+ context: singleResult.context,
4163
+ agentContract: singleResult.agentContract,
4164
+ launchContractDigest: singleResult.launchContractDigest,
4165
+ launchResolvedExtensions: singleResult.launchResolvedExtensions,
4166
+ runtimeAcknowledgedExtensions: singleResult.runtimeAcknowledgedExtensions,
4167
+ output: stopped || childStopped ? stopMessage : timedOut ? (timeoutMessage ?? "Subagent timed out.") : singleResult.output,
4168
+ outputState: singleResult.outputState,
4169
+ error: stopped || childStopped ? stopMessage : timedOut ? (timeoutMessage ?? "Subagent timed out.") : singleResult.error,
4170
+ protocolError: singleResult.protocolError,
4171
+ success: !stopped && !childStopped && !timedOut && singleResult.interrupted !== true && singleResult.exitCode === 0,
4172
+ exitCode: stopped || childStopped ? 1 : timedOut ? 1 : singleResult.interrupted === true ? 0 : singleResult.exitCode,
4173
+ sessionFile: singleResult.sessionFile,
4174
+ intercomTarget: singleResult.intercomTarget,
4175
+ model: singleResult.model,
4176
+ attemptedModels: singleResult.attemptedModels,
4177
+ modelAttempts: singleResult.modelAttempts,
4178
+ totalCost: singleResult.totalCost,
4179
+ artifactPaths: singleResult.artifactPaths,
4180
+ transcriptPath: singleResult.transcriptPath,
4181
+ transcriptError: singleResult.transcriptError,
4182
+ effects: singleResult.effects,
4183
+ execution: singleResult.execution,
4184
+ review: singleResult.review,
4185
+ structuredOutput: singleResult.structuredOutput,
4186
+ structuredOutputPath: singleResult.structuredOutputPath,
4187
+ structuredOutputSchemaPath: singleResult.structuredOutputSchemaPath,
4188
+ acceptance: singleResult.acceptance,
4189
+ watchdog: singleResult.watchdog,
4190
+ capabilityCeiling: singleResult.capabilityCeiling,
4191
+ capabilityAudit: singleResult.capabilityAudit,
4192
+ interrupted: singleResult.interrupted,
4193
+ timedOut: timedOut || singleResult.timedOut ? true : undefined,
4194
+ stopped: stopped || childStopped ? true : undefined,
4195
+ turnBudget: singleResult.turnBudget,
4196
+ turnBudgetExceeded: singleResult.turnBudgetExceeded,
4197
+ wrapUpRequested: singleResult.wrapUpRequested,
4198
+ toolBudget: singleResult.toolBudget,
4199
+ toolBudgetBlocked: singleResult.toolBudgetBlocked,
4200
+ runner: singleResult.runner,
4201
+ externalProcess: singleResult.externalProcess,
4202
+ }));
4203
+ if (seqStep.outputName) {
4204
+ outputs[seqStep.outputName] = outputEntryFromAsyncResult({
4205
+ agent: singleResult.agent,
4206
+ output: singleResult.output,
4207
+ structuredOutput: singleResult.structuredOutput,
4208
+ }, stepIndex);
4209
+ }
4210
+ statusPayload.outputs = outputs;
4211
+
4212
+ const cumulativeTokens = config.sessionDir ? parseSessionTokens(config.sessionDir) : null;
4213
+ let stepTokens: TokenUsage | null = cumulativeTokens
4214
+ ? {
4215
+ input: cumulativeTokens.input - previousCumulativeTokens.input,
4216
+ output: cumulativeTokens.output - previousCumulativeTokens.output,
4217
+ total: cumulativeTokens.total - previousCumulativeTokens.total,
4218
+ }
4219
+ : null;
4220
+ if (cumulativeTokens) {
4221
+ previousCumulativeTokens = cumulativeTokens;
4222
+ } else {
4223
+ stepTokens = tokenUsageFromAttempts(singleResult.modelAttempts);
4224
+ if (stepTokens) {
4225
+ previousCumulativeTokens = {
4226
+ input: previousCumulativeTokens.input + stepTokens.input,
4227
+ output: previousCumulativeTokens.output + stepTokens.output,
4228
+ total: previousCumulativeTokens.total + stepTokens.total,
4229
+ };
4230
+ }
4231
+ }
4232
+
4233
+ const stepEndTime = Date.now();
4234
+ const childInterrupted = singleResult.interrupted === true;
4235
+ requiredStatusStep(statusPayload, flatIndex).status = stopped || childStopped ? "stopped" : timedOut ? "failed" : childInterrupted ? "paused" : singleResult.exitCode === 0 ? "complete" : "failed";
4236
+ requiredStatusStep(statusPayload, flatIndex).endedAt = stepEndTime;
4237
+ requiredStatusStep(statusPayload, flatIndex).durationMs = stepEndTime - stepStartTime;
4238
+ requiredStatusStep(statusPayload, flatIndex).exitCode = stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;
4239
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "timedOut", timedOut || singleResult.timedOut ? true : undefined);
4240
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "stopped", stopped || childStopped ? true : undefined);
4241
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "turnBudget", singleResult.turnBudget);
4242
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "turnBudgetExceeded", singleResult.turnBudgetExceeded);
4243
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "wrapUpRequested", singleResult.wrapUpRequested);
4244
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "toolBudget", singleResult.toolBudget);
4245
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "toolBudgetBlocked", singleResult.toolBudgetBlocked);
4246
+ if (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;
4247
+ if (singleResult.toolBudgetBlocked) statusPayload.toolBudgetBlocked = true;
4248
+ if (singleResult.turnBudget) statusPayload.turnBudget = singleResult.turnBudget;
4249
+ if (singleResult.turnBudgetExceeded) statusPayload.turnBudgetExceeded = true;
4250
+ if (singleResult.wrapUpRequested) statusPayload.wrapUpRequested = true;
4251
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "model", singleResult.model);
4252
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "thinking", resolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, flatIndex).thinking));
4253
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "attemptedModels", singleResult.attemptedModels);
4254
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "modelAttempts", singleResult.modelAttempts);
4255
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "totalCost", singleResult.totalCost);
4256
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "error", stopped || childStopped ? stopMessage : timedOut ? (timeoutMessage ?? "Subagent timed out.") : singleResult.error);
4257
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "transcriptPath", singleResult.transcriptPath ?? requiredStatusStep(statusPayload, flatIndex).transcriptPath);
4258
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "transcriptError", singleResult.transcriptError);
4259
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "agentContract", singleResult.agentContract);
4260
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "launchResolvedExtensions", singleResult.launchResolvedExtensions);
4261
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "runtimeAcknowledgedExtensions", singleResult.runtimeAcknowledgedExtensions);
4262
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "effects", singleResult.effects);
4263
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "execution", singleResult.execution);
4264
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "review", singleResult.review);
4265
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "structuredOutput", singleResult.structuredOutput);
4266
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "structuredOutputPath", singleResult.structuredOutputPath);
4267
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "structuredOutputSchemaPath", singleResult.structuredOutputSchemaPath);
4268
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "acceptance", singleResult.acceptance);
4269
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "watchdog", singleResult.watchdog);
4270
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "capabilityCeiling", singleResult.capabilityCeiling);
4271
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "capabilityAudit", singleResult.capabilityAudit);
4272
+ if (singleResult.capabilityCeiling) statusPayload.capabilityCeiling = singleResult.capabilityCeiling;
4273
+ if (singleResult.capabilityAudit) statusPayload.capabilityAudit = singleResult.capabilityAudit;
4274
+ if (stepTokens) {
4275
+ requiredStatusStep(statusPayload, flatIndex).tokens = stepTokens;
4276
+ statusPayload.totalTokens = { ...previousCumulativeTokens };
4277
+ }
4278
+ statusPayload.lastUpdate = stepEndTime;
4279
+ writeStatusPayload();
4280
+ appendCapabilityCeilingAppliedEvent(eventsPath, id, flatIndex, seqStep.agent, singleResult);
4281
+
4282
+ appendJsonl(eventsPath, JSON.stringify({
4283
+ type: stopped || childStopped ? "subagent.step.stopped" : timedOut ? "subagent.step.failed" : childInterrupted ? "subagent.step.paused" : singleResult.exitCode === 0 ? "subagent.step.completed" : "subagent.step.failed",
4284
+ ts: stepEndTime,
4285
+ runId: id,
4286
+ stepIndex: flatIndex,
4287
+ agent: seqStep.agent,
4288
+ exitCode: stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode,
4289
+ durationMs: stepEndTime - stepStartTime,
4290
+ tokens: stepTokens,
4291
+ }));
4292
+ if (singleResult.completionGuardTriggered) {
4293
+ const event = buildControlEvent(omitUndefinedProperties({
4294
+ from: requiredStatusStep(statusPayload, flatIndex).activityState,
4295
+ to: "needs_attention",
4296
+ runId: id,
4297
+ agent: seqStep.agent,
4298
+ index: flatIndex,
4299
+ ts: stepEndTime,
4300
+ message: `${seqStep.agent} completed without making edits for an implementation task`,
4301
+ reason: "completion_guard",
4302
+ }));
4303
+ appendControlEvent(event);
4304
+ }
4305
+
4306
+ flatIndex++;
4307
+ if (isAgentContractV1(seqStep.agentContract) && seqStep.gateOn === "acceptance" && singleResult.acceptance?.status === "rejected") {
4308
+ statusPayload.error = acceptanceFailureMessage(singleResult.acceptance) ?? "Chain acceptance gate rejected the step.";
4309
+ writeStatusPayload();
4310
+ break;
4311
+ }
4312
+ if (singleResult.exitCode !== 0) {
4313
+ break;
4314
+ }
4315
+ }
4316
+ }
4317
+
4318
+ let summary = results.map((r) => `${r.agent}:\n${r.output}`).join("\n\n");
4319
+ let truncated = false;
4320
+
4321
+ if (maxOutput) {
4322
+ const config = { ...DEFAULT_MAX_OUTPUT, ...maxOutput };
4323
+ const lastArtifactPath = results[results.length - 1]?.artifactPaths?.outputPath;
4324
+ const truncResult = truncateOutput(summary, config, lastArtifactPath);
4325
+ if (truncResult.truncated) {
4326
+ summary = truncResult.text;
4327
+ truncated = true;
4328
+ }
4329
+ }
4330
+
4331
+ const resultMode = config.resultMode ?? statusPayload.mode;
4332
+ const singleRuntimeAcknowledgedExtensions = results.length === 1 ? results[0]?.runtimeAcknowledgedExtensions : undefined;
4333
+ const totalCost = results.reduce<CostSummary>((sum, result) => ({
4334
+ inputTokens: sum.inputTokens + (result.totalCost?.inputTokens ?? 0),
4335
+ outputTokens: sum.outputTokens + (result.totalCost?.outputTokens ?? 0),
4336
+ costUsd: sum.costUsd + (result.totalCost?.costUsd ?? 0),
4337
+ }), { inputTokens: 0, outputTokens: 0, costUsd: 0 });
4338
+ const finalTotalCost = totalCost.inputTokens > 0 || totalCost.outputTokens > 0 || totalCost.costUsd > 0 ? totalCost : undefined;
4339
+ const finalFlatAgents = statusPayload.steps.map((step) => step.agent);
4340
+ const agentName = finalFlatAgents.length === 1
4341
+ ? finalFlatAgents[0]!
4342
+ : resultMode === "parallel"
4343
+ ? `parallel:${finalFlatAgents.join("+")}`
4344
+ : `chain:${finalFlatAgents.join("->")}`;
4345
+ let sessionFile: string | undefined;
4346
+ let shareUrl: string | undefined;
4347
+ let gistUrl: string | undefined;
4348
+ let shareError: string | undefined;
4349
+
4350
+ if (shareEnabled) {
4351
+ sessionFile = config.sessionDir
4352
+ ? (findLatestSessionFile(config.sessionDir) ?? undefined)
4353
+ : undefined;
4354
+ if (!sessionFile && latestSessionFile) {
4355
+ sessionFile = latestSessionFile;
4356
+ }
4357
+ if (sessionFile) {
4358
+ try {
4359
+ const exportDir = config.sessionDir ?? path.dirname(sessionFile);
4360
+ const htmlPath = await exportSessionHtml(sessionFile, exportDir, config.piPackageRoot);
4361
+ const share = createShareLink(htmlPath);
4362
+ if ("error" in share) shareError = share.error;
4363
+ else {
4364
+ shareUrl = share.shareUrl;
4365
+ gistUrl = share.gistUrl;
4366
+ }
4367
+ } catch (err) {
4368
+ shareError = String(err);
4369
+ }
4370
+ } else {
4371
+ shareError = "Session file not found.";
4372
+ }
4373
+ }
4374
+
4375
+ if (activityTimer) {
4376
+ clearInterval(activityTimer);
4377
+ activityTimer = undefined;
4378
+ }
4379
+ if (timeoutTimer) {
4380
+ clearTimeout(timeoutTimer);
4381
+ timeoutTimer = undefined;
4382
+ }
4383
+ const signalTerminated = !stopped && !timedOut && !turnBudgetExceeded && !interrupted && results.some((result) => result.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
4384
+ processSignal: result.processSignal,
4385
+ interrupted: result.interrupted,
4386
+ timedOut: result.timedOut,
4387
+ stopped: result.stopped,
4388
+ turnBudgetExceeded: result.turnBudgetExceeded,
4389
+ })));
4390
+ statusPayload.state = checkpointRejected ? "rejected" : stopped || signalTerminated ? "stopped" : timedOut || turnBudgetExceeded || usageBudgetExceeded || statusPayload.error ? "failed" : interrupted ? "paused" : results.every((r) => r.success) ? "complete" : "failed";
4391
+ closeSteerInbox(asyncDir, statusPayload.state);
4392
+ disposeControlInbox();
4393
+ for (const request of consumeSteerRequests(asyncDir)) deliverSteerRequest(request);
4394
+ const effectiveSessionFile = sessionFile ?? latestSessionFile;
4395
+ const steeringLifecycle = steeringStatus(statusPayload);
4396
+ for (const request of steeringLifecycle.recent) {
4397
+ let changed = false;
4398
+ for (const target of request.targets) {
4399
+ if (target.state !== "scheduled" && target.state !== "routed" && target.state !== "queued") continue;
4400
+ changed = true;
4401
+ const reason = target.state === "queued" ? "run ended before queued follow-up delivery" : "child terminated before steering delivery";
4402
+ updateSteeringLifecycleTarget(request.id, target.index, "failed", Date.now(), { reason });
4403
+ markSteeringAttention(target.index);
4404
+ emitSteeringEvent("subagent.steer.failed", { type: "steer", id: request.id, ts: request.requestedAt, message: reason }, target.index, { reason });
4405
+ }
4406
+ if (changed) emitTerminalSteeringNotice(request.id, `Steering failed for run ${id}: child terminated before delivery.`);
4407
+ }
4408
+ const runEndedAt = Date.now();
4409
+ delete statusPayload.activityState;
4410
+ if (stopped) {
4411
+ statusPayload.stopped = true;
4412
+ statusPayload.error = stopMessage;
4413
+ } else if (signalTerminated && !statusPayload.error) {
4414
+ setOptionalProperty(statusPayload, "error", results.find((result) => result.processSignal)?.error);
4415
+ }
4416
+ if (timedOut) {
4417
+ statusPayload.timedOut = true;
4418
+ statusPayload.error = timeoutMessage ?? "Subagent timed out.";
4419
+ }
4420
+ if (turnBudgetExceeded && !statusPayload.error) {
4421
+ const budget = statusPayload.turnBudget;
4422
+ statusPayload.error = budget ? turnBudgetExceededMessage(budget, budget.turnCount) : "Subagent exceeded turn budget.";
4423
+ }
4424
+ if (usageBudgetExceeded && statusPayload.usageBudget && !statusPayload.error) {
4425
+ statusPayload.error = usageBudgetExceededMessage(statusPayload.usageBudget);
4426
+ }
4427
+ statusPayload.endedAt = runEndedAt;
4428
+ statusPayload.lastUpdate = runEndedAt;
4429
+ setOptionalProperty(statusPayload, "sessionFile", effectiveSessionFile);
4430
+ if (singleRuntimeAcknowledgedExtensions) statusPayload.runtimeAcknowledgedExtensions = singleRuntimeAcknowledgedExtensions;
4431
+ setOptionalProperty(statusPayload, "totalCost", finalTotalCost);
4432
+ setOptionalProperty(statusPayload, "usageBudget", usageBudgetState(config.usageBudget, currentUsageTotals()));
4433
+ setOptionalProperty(statusPayload, "shareUrl", shareUrl);
4434
+ setOptionalProperty(statusPayload, "gistUrl", gistUrl);
4435
+ setOptionalProperty(statusPayload, "shareError", shareError);
4436
+ if (statusPayload.state === "failed" && !statusPayload.error) {
4437
+ const failedStep = statusPayload.steps.find((s) => s.status === "failed");
4438
+ if (failedStep?.agent) {
4439
+ statusPayload.error = `Step failed: ${failedStep.agent}`;
4440
+ }
4441
+ }
4442
+ try {
4443
+ writeAtomicJson(resultPath, {
4444
+ lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
4445
+ id,
4446
+ agent: agentName,
4447
+ mode: resultMode,
4448
+ success: !checkpointRejected && !stopped && !timedOut && !turnBudgetExceeded && !usageBudgetExceeded && !interrupted && !signalTerminated && results.every((r) => r.success),
4449
+ state: checkpointRejected ? "rejected" : stopped || signalTerminated ? "stopped" : timedOut || turnBudgetExceeded || usageBudgetExceeded ? "failed" : interrupted ? "paused" : results.every((r) => r.success) ? "complete" : "failed",
4450
+ summary: checkpointRejected ? (statusPayload.error ?? "Checkpoint rejected.") : stopped ? stopMessage : signalTerminated ? (statusPayload.error ?? "Subagent process terminated by signal.") : timedOut ? (timeoutMessage ?? "Subagent timed out.") : turnBudgetExceeded ? (statusPayload.error ?? "Subagent exceeded turn budget.") : usageBudgetExceeded ? (statusPayload.error ?? "Usage budget exhausted.") : interrupted ? "Paused after interrupt. Waiting for explicit next action." : summary,
4451
+ ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),
4452
+ ...(config.deadlineAt !== undefined ? { deadlineAt: config.deadlineAt } : {}),
4453
+ ...(statusPayload.turnBudget ? { turnBudget: statusPayload.turnBudget } : {}),
4454
+ ...(statusPayload.turnBudgetExceeded ? { turnBudgetExceeded: true } : {}),
4455
+ ...(statusPayload.wrapUpRequested ? { wrapUpRequested: true } : {}),
4456
+ ...(statusPayload.toolBudget ? { toolBudget: statusPayload.toolBudget } : {}),
4457
+ ...(statusPayload.toolBudgetBlocked ? { toolBudgetBlocked: true } : {}),
4458
+ ...(statusPayload.usageBudget ? { usageBudget: statusPayload.usageBudget } : {}),
4459
+ ...(statusPayload.checkpoint ? { checkpoint: statusPayload.checkpoint } : {}),
4460
+ ...(stopped ? { stopped: true, error: stopMessage } : timedOut ? { timedOut: true, error: timeoutMessage ?? "Subagent timed out." } : turnBudgetExceeded ? { error: statusPayload.error ?? "Subagent exceeded turn budget." } : usageBudgetExceeded ? { error: statusPayload.error ?? "Usage budget exhausted." } : {}),
4461
+ results: results.map((r) => omitUndefinedProperties({
4462
+ agent: r.agent,
4463
+ context: r.context,
4464
+ output: r.output,
4465
+ outputState: r.outputState,
4466
+ error: r.error,
4467
+ protocolError: r.protocolError,
4468
+ success: r.success,
4469
+ skipped: r.skipped || undefined,
4470
+ interrupted: r.interrupted || undefined,
4471
+ timedOut: r.timedOut || undefined,
4472
+ stopped: r.stopped || undefined,
4473
+ processSignal: r.processSignal || undefined,
4474
+ turnBudget: r.turnBudget,
4475
+ turnBudgetExceeded: r.turnBudgetExceeded || undefined,
4476
+ wrapUpRequested: r.wrapUpRequested || undefined,
4477
+ toolBudget: r.toolBudget,
4478
+ toolBudgetBlocked: r.toolBudgetBlocked || undefined,
4479
+ sessionFile: r.sessionFile,
4480
+ intercomTarget: r.intercomTarget,
4481
+ model: r.model,
4482
+ attemptedModels: r.attemptedModels,
4483
+ modelAttempts: r.modelAttempts,
4484
+ totalCost: r.totalCost,
4485
+ artifactPaths: r.artifactPaths,
4486
+ outputSaveError: r.outputSaveError,
4487
+ metadataSaveError: r.metadataSaveError,
4488
+ truncated: r.truncated,
4489
+ transcriptPath: r.transcriptPath,
4490
+ transcriptError: r.transcriptError,
4491
+ agentContract: r.agentContract,
4492
+ launchContractDigest: r.launchContractDigest,
4493
+ launchResolvedExtensions: r.launchResolvedExtensions,
4494
+ runtimeAcknowledgedExtensions: r.runtimeAcknowledgedExtensions,
4495
+ runner: r.runner,
4496
+ externalProcess: r.externalProcess,
4497
+ execution: r.execution,
4498
+ review: r.review,
4499
+ effects: r.effects,
4500
+ structuredOutput: r.structuredOutput,
4501
+ structuredOutputPath: r.structuredOutputPath,
4502
+ structuredOutputSchemaPath: r.structuredOutputSchemaPath,
4503
+ acceptance: r.acceptance,
4504
+ watchdog: r.watchdog,
4505
+ capabilityCeiling: r.capabilityCeiling,
4506
+ capabilityAudit: r.capabilityAudit,
4507
+ })),
4508
+ outputs,
4509
+ workflowGraph: statusPayload.workflowGraph,
4510
+ parallelHandoff: statusPayload.parallelHandoff,
4511
+ capabilityCeiling: statusPayload.capabilityCeiling,
4512
+ capabilityAudit: statusPayload.capabilityAudit,
4513
+ ...(config.parentWorkflowRunId ? { parentWorkflowRunId: config.parentWorkflowRunId } : {}),
4514
+ ...(config.workflowKey ? { workflowKey: config.workflowKey } : {}),
4515
+ exitCode: checkpointRejected || stopped || timedOut || turnBudgetExceeded || usageBudgetExceeded ? 1 : interrupted || results.every((r) => r.success) ? 0 : 1,
4516
+ timestamp: runEndedAt,
4517
+ durationMs: runEndedAt - overallStartTime,
4518
+ totalTokens: statusPayload.totalTokens,
4519
+ totalCost: finalTotalCost,
4520
+ usageBudget: statusPayload.usageBudget,
4521
+ checkpoint: statusPayload.checkpoint,
4522
+ truncated,
4523
+ artifactsDir,
4524
+ cwd,
4525
+ asyncDir,
4526
+ launchContractDigest: config.launchContractDigest,
4527
+ launchResolvedExtensions: config.launchResolvedExtensions,
4528
+ runtimeAcknowledgedExtensions: singleRuntimeAcknowledgedExtensions,
4529
+ sessionId: config.sessionId,
4530
+ sessionFile: effectiveSessionFile,
4531
+ intercomTarget: config.controlIntercomTarget,
4532
+ shareUrl,
4533
+ gistUrl,
4534
+ shareError,
4535
+ ...(taskIndex !== undefined && { taskIndex }),
4536
+ ...(totalTasks !== undefined && { totalTasks }),
4537
+ });
4538
+ } catch (err) {
4539
+ console.error(`Failed to write result file ${resultPath}:`, err);
4540
+ }
4541
+ appendJsonl(
4542
+ eventsPath,
4543
+ JSON.stringify({
4544
+ type: "subagent.run.completed",
4545
+ lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
4546
+ ts: runEndedAt,
4547
+ runId: id,
4548
+ status: statusPayload.state,
4549
+ durationMs: runEndedAt - overallStartTime,
4550
+ totalTokens: statusPayload.totalTokens,
4551
+ totalCost: finalTotalCost,
4552
+ usageBudget: statusPayload.usageBudget,
4553
+ }),
4554
+ );
4555
+ writeRunLog(logPath, omitUndefinedProperties({
4556
+ id,
4557
+ mode: statusPayload.mode,
4558
+ cwd,
4559
+ startedAt: overallStartTime,
4560
+ endedAt: runEndedAt,
4561
+ steps: statusPayload.steps.map((step) => omitUndefinedProperties({
4562
+ agent: step.agent,
4563
+ status: step.status,
4564
+ durationMs: step.durationMs,
4565
+ })),
4566
+ summary,
4567
+ truncated,
4568
+ artifactsDir,
4569
+ sessionFile: effectiveSessionFile,
4570
+ shareUrl,
4571
+ shareError,
4572
+ }));
4573
+ if (config.runnerProcessInstanceId) {
4574
+ const writers: Record<string, Array<{ processInstanceId: string; kind: "pi-writer"; attempt: number; closeObservedAt: number; exitCode: number | null; signal: string | null }>> = {};
4575
+ const expectedWriters: Record<string, number> = {};
4576
+ for (const [index, result] of results.entries()) {
4577
+ writers[String(index)] = result.writerProcesses ?? [];
4578
+ expectedWriters[String(index)] = result.writerAttemptCount ?? 0;
4579
+ }
4580
+ const candidate: ProcessTerminalCandidate = {
4581
+ version: 1,
4582
+ runId: id,
4583
+ runnerProcessInstanceId: config.runnerProcessInstanceId,
4584
+ writers,
4585
+ expectedWriters,
4586
+ ...(config.revivalLease?.sessionFile ? { sessionFile: config.revivalLease.sessionFile } : {}),
4587
+ ...(config.revivalLeaseToken ? { revivalLeaseToken: config.revivalLeaseToken } : {}),
4588
+ };
4589
+ try {
4590
+ writeProcessTerminalCandidate(asyncDir, candidate);
4591
+ } catch (error) {
4592
+ console.error(`Failed to write process-terminal candidate for '${id}':`, error);
4593
+ }
4594
+ }
4595
+ writeStatusPayload();
4596
+ }
4597
+
4598
+ async function waitForStartupControl(
4599
+ controlPath: string,
4600
+ token: string,
4601
+ action: "ack" | "proceed",
4602
+ timeoutMs = 30_000,
4603
+ ): Promise<void> {
4604
+ const deadline = Date.now() + timeoutMs;
4605
+ while (Date.now() <= deadline) {
4606
+ if (fs.existsSync(controlPath)) {
4607
+ let payload: { action?: unknown; token?: unknown };
4608
+ try {
4609
+ payload = JSON.parse(fs.readFileSync(controlPath, "utf-8")) as { action?: unknown; token?: unknown };
4610
+ } catch (error) {
4611
+ throw new Error(`Failed to read runner startup control '${controlPath}': ${error instanceof Error ? error.message : String(error)}`);
4612
+ }
4613
+ if (payload.token !== token) throw new Error("Runner startup control token does not match the acquired session lease.");
4614
+ if (payload.action === action) return;
4615
+ if (payload.action !== "ack" && payload.action !== "proceed") throw new Error("Runner startup control action is invalid.");
4616
+ }
4617
+ await new Promise((resolve) => setTimeout(resolve, 20));
4618
+ }
4619
+ throw new Error(`Timed out after ${timeoutMs}ms waiting for runner startup control '${action}'.`);
4620
+ }
4621
+
4622
+ async function runConfiguredSubagent(config: SubagentRunConfig): Promise<void> {
4623
+ let lease: ReturnType<typeof acquireSessionLease> | undefined;
4624
+ let startupCommitted = config.revivalLease === undefined;
4625
+ const startupPath = path.join(config.asyncDir, "runner-startup.json");
4626
+ const startupAckPath = path.join(config.asyncDir, "runner-startup-ack.json");
4627
+ const startupProceedPath = path.join(config.asyncDir, "runner-startup-proceed.json");
4628
+ const releaseOnExit = (): void => {
4629
+ try {
4630
+ lease?.release();
4631
+ } catch {
4632
+ // Exit cleanup is best effort; a dead-owner lease is reclaimed on the next revival.
4633
+ }
4634
+ };
4635
+ process.once("exit", releaseOnExit);
4636
+ try {
4637
+ if (config.revivalLease) {
4638
+ lease = acquireSessionLease(config.revivalLease);
4639
+ config.revivalLeaseToken = lease.owner.token;
4640
+ writeAtomicJson(startupPath, { state: "ready", token: lease.owner.token, pid: process.pid, owner: lease.owner });
4641
+ await waitForStartupControl(startupAckPath, lease.owner.token, "ack");
4642
+ writeAtomicJson(startupPath, { state: "acknowledged", token: lease.owner.token, pid: process.pid });
4643
+ await waitForStartupControl(startupProceedPath, lease.owner.token, "proceed");
4644
+ startupCommitted = true;
4645
+ for (const controlPath of [startupAckPath, startupProceedPath]) {
4646
+ try {
4647
+ fs.rmSync(controlPath, { force: true });
4648
+ } catch {
4649
+ // Startup control cleanup is best effort after the parent commits the run.
4650
+ }
4651
+ }
4652
+ }
4653
+ await runSubagent(config, lease ? (writer) => lease!.updateWriter(writer) : undefined);
4654
+ } catch (error) {
4655
+ if (config.revivalLease && !startupCommitted) {
4656
+ try {
4657
+ writeAtomicJson(startupPath, { state: "error", pid: process.pid, error: error instanceof Error ? error.message : String(error) });
4658
+ } catch {
4659
+ // The parent will time out and terminate this runner if the handshake cannot be written.
4660
+ }
4661
+ }
4662
+ throw error;
4663
+ } finally {
4664
+ process.off("exit", releaseOnExit);
4665
+ if (lease) {
4666
+ let acknowledged = false;
4667
+ try {
4668
+ acknowledged = lease.release();
4669
+ } catch (error) {
4670
+ console.error("Failed to release session revival lease:", error);
4671
+ }
4672
+ try {
4673
+ markProcessTerminalCandidateLeaseRelease(config.asyncDir, lease.owner.token, acknowledged);
4674
+ } catch (error) {
4675
+ console.error("Failed to record session revival lease release:", error);
4676
+ }
4677
+ }
4678
+ }
4679
+ }
4680
+
4681
+ function startConfiguredSubagent(config: SubagentRunConfig): void {
4682
+ runConfiguredSubagent(config).catch((runErr) => {
4683
+ console.error("Subagent runner error:", runErr);
4684
+ process.exit(1);
4685
+ });
4686
+ }
4687
+
4688
+ const configArg = process.argv[2];
4689
+ if (configArg) {
4690
+ try {
4691
+ const configJson = fs.readFileSync(configArg, "utf-8");
4692
+ const config = JSON.parse(configJson) as SubagentRunConfig;
4693
+ try {
4694
+ fs.unlinkSync(configArg);
4695
+ } catch {
4696
+ // Temp config cleanup is best effort.
4697
+ }
4698
+ startConfiguredSubagent(config);
4699
+ } catch (err) {
4700
+ console.error("Subagent runner error:", err);
4701
+ process.exit(1);
4702
+ }
4703
+ } else {
4704
+ let input = "";
4705
+ process.stdin.setEncoding("utf-8");
4706
+ process.stdin.on("data", (chunk) => {
4707
+ input += chunk;
4708
+ });
4709
+ process.stdin.on("end", () => {
4710
+ try {
4711
+ const config = JSON.parse(input) as SubagentRunConfig;
4712
+ startConfiguredSubagent(config);
4713
+ } catch (err) {
4714
+ console.error("Subagent runner error:", err);
4715
+ process.exit(1);
4716
+ }
4717
+ });
4718
+ }