@xzzpig/pi-subagents 0.8.0 → 0.9.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 (218) hide show
  1. package/CHANGELOG.md +443 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +151 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +5 -4
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +370 -114
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +12 -2
  35. package/src/agents/agents.ts +919 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +31 -20
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +48 -18
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +57 -21
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +2 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +366 -128
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +45 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +189 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +676 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +468 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1172 -400
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +314 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +342 -0
  115. package/src/runs/shared/child-tool-plan.ts +540 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +142 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +38 -48
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +15 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/single-output.ts +89 -22
  149. package/src/runs/shared/structured-output.ts +49 -9
  150. package/src/runs/shared/subagent-control.ts +6 -2
  151. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  152. package/src/runs/shared/task-intent.ts +21 -7
  153. package/src/runs/shared/tool-availability.ts +18 -62
  154. package/src/runs/shared/tool-budget.ts +0 -14
  155. package/src/runs/shared/tool-timeout.ts +1 -1
  156. package/src/runs/shared/workflow-graph.ts +16 -0
  157. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  158. package/src/runs/shared/worktree.ts +571 -62
  159. package/src/shared/atomic-json.ts +3 -1
  160. package/src/shared/child-session-name.ts +46 -0
  161. package/src/shared/extension-context.ts +24 -0
  162. package/src/shared/fork-context.ts +21 -12
  163. package/src/shared/fork-session-cwd.ts +27 -0
  164. package/src/shared/formatters.ts +18 -3
  165. package/src/shared/jsonl-writer.ts +11 -0
  166. package/src/shared/launch-contract.ts +8 -1
  167. package/src/shared/pruned-fork.ts +450 -0
  168. package/src/shared/session-file-trust.ts +19 -0
  169. package/src/shared/session-tokens.ts +14 -3
  170. package/src/shared/settings.ts +19 -105
  171. package/src/shared/shortcuts.ts +17 -0
  172. package/src/shared/thinking-ceiling.ts +0 -6
  173. package/src/shared/types.ts +524 -70
  174. package/src/shared/utils.ts +60 -93
  175. package/src/shared/workflow-child-permit.ts +207 -0
  176. package/src/slash/delegation-adapters.ts +1 -9
  177. package/src/slash/delegation-request.ts +0 -4
  178. package/src/slash/prompt-template-bridge.ts +37 -1
  179. package/src/slash/slash-bridge.ts +1 -2
  180. package/src/slash/slash-commands.ts +383 -116
  181. package/src/slash/slash-live-state.ts +22 -11
  182. package/src/slash/subagents-admin.ts +29 -12
  183. package/src/tui/fleet-native-transcript.ts +4 -0
  184. package/src/tui/fleet-status.ts +217 -82
  185. package/src/tui/fleet-transcript.ts +11 -5
  186. package/src/tui/fleet.ts +54 -28
  187. package/src/tui/render-helpers.ts +31 -0
  188. package/src/tui/render.ts +1429 -163
  189. package/src/watchdog/change-signature.ts +40 -1
  190. package/src/watchdog/child-status.ts +54 -34
  191. package/src/watchdog/diff-tool.ts +77 -0
  192. package/src/watchdog/emission-guard.ts +5 -3
  193. package/src/watchdog/guidance.ts +20 -0
  194. package/src/watchdog/register-child.ts +28 -25
  195. package/src/watchdog/register-main.ts +10 -9
  196. package/src/watchdog/render.ts +4 -5
  197. package/src/watchdog/review.ts +15 -4
  198. package/src/watchdog/rules.ts +70 -0
  199. package/src/watchdog/runtime.ts +75 -92
  200. package/src/watchdog/scope.ts +0 -11
  201. package/src/watchdog/settings.ts +48 -104
  202. package/src/watchdog/turn-delta.ts +1 -1
  203. package/src/watchdog/types.ts +18 -32
  204. package/src/watchdog/warning-format.ts +0 -1
  205. package/src/workflows/chat-progress.ts +7 -3
  206. package/src/workflows/host-command.ts +235 -0
  207. package/src/workflows/scripted-workflow.ts +988 -59
  208. package/src/workflows/workflow-checklist.ts +439 -0
  209. package/src/workflows/workflow-child-summary.ts +121 -0
  210. package/src/workflows/workflow-preflight.ts +297 -0
  211. package/src/workflows/workflow-receipt.ts +232 -6
  212. package/src/workflows/workflow-resources.ts +150 -0
  213. package/src/workflows/workflow-settlement.ts +246 -0
  214. package/src/runs/shared/child-protocol.ts +0 -401
  215. package/src/runs/shared/pi-args.ts +0 -935
  216. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  217. package/src/runs/shared/turn-budget.ts +0 -98
  218. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -1,5 +1,4 @@
1
- import { spawn, spawnSync } from "node:child_process";
2
- import { randomUUID } from "node:crypto";
1
+ import { spawnSync } from "node:child_process";
3
2
  import * as fs from "node:fs";
4
3
  import * as path from "node:path";
5
4
  import { pathToFileURL } from "node:url";
@@ -11,9 +10,10 @@ import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilie
11
10
  import { isStorageCapacityError } from "../../shared/file-system-retry.ts";
12
11
  import { updateActiveRunIndex } from "./active-run-index.ts";
13
12
  import { createChildTranscriptWriter, type ChildTranscriptWriter } from "../../shared/child-transcript.ts";
14
- import { closeSteerInbox, consumeInterruptRequest, consumeSteerRequests, deliverInterruptRequest, deliverStopRequest, deliverTimeoutRequest, enqueueStepSteer, steerAcksDir, steerCapabilityPath, stepSteerInboxDir, watchAsyncControlInbox, type SteerAck, type SteerCapability, type SteerRequest, type StopRequest } from "./control-channel.ts";
13
+ import { closeSteerInbox, consumeInterruptRequest, consumeSteerRequests, deliverInterruptRequest, deliverStopRequest, deliverTimeoutRequest, watchAsyncControlInbox, type SteerRequest, type StopRequest } from "./control-channel.ts";
15
14
  import { appendJsonl as appendRawJsonl, formatOutputArtifactContent, getArtifactPaths, writeArtifact, writeMetadata } from "../../shared/artifacts.ts";
16
- import { PI_CODING_AGENT_PACKAGE, getPiSpawnCommand, resolveInstalledPiPackageRoot } from "../shared/pi-spawn.ts";
15
+ import { PI_CODING_AGENT_PACKAGE, resolveInstalledPiPackageRoot } from "../shared/pi-spawn.ts";
16
+ import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
17
17
  import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, injectOutputPathSystemPrompt, injectSingleOutputInstruction, resolveSingleOutput, type SingleOutputSnapshot } from "../shared/single-output.ts";
18
18
  import {
19
19
  type ActivityState,
@@ -31,30 +31,25 @@ import {
31
31
  type RuntimeAcknowledgedChildExtensionsV1,
32
32
  type ModelAttempt,
33
33
  type PiWriterProcessInstanceExitV1,
34
- type ProcessTreeTerminalV1,
35
34
  type NestedRouteInfo,
36
35
  type NestedRunSummary,
37
36
  type ResolvedControlConfig,
38
- type ResolvedTurnBudget,
39
37
  type ResolvedToolBudget,
40
38
  type RunFanoutBudgetDescriptor,
41
39
  type SubagentRunMode,
42
40
  type SubagentOutputState,
43
41
  type UsageBudgetConfig,
44
42
  type ToolBudgetState,
45
- type TurnBudgetState,
46
43
  type Usage,
47
44
  type WorkflowGraphSnapshot,
48
- type SteeringStatus,
49
45
  type SteeringTargetState,
50
46
  type SteeringTargetStatus,
51
47
  type SubagentChildStatusEvent,
48
+ type WorkflowLaneMetadata,
52
49
  DEFAULT_MAX_OUTPUT,
53
50
  type MaxOutputConfig,
54
51
  SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
55
- POLL_INTERVAL_MS,
56
52
  truncateOutput,
57
- getSubagentDepthEnv,
58
53
  } from "../../shared/types.ts";
59
54
  import {
60
55
  DEFAULT_CONTROL_CONFIG,
@@ -77,31 +72,29 @@ import {
77
72
  DEFAULT_GLOBAL_CONCURRENCY_LIMIT,
78
73
  Semaphore,
79
74
  } from "../shared/parallel-utils.ts";
80
- import { applyThinkingSuffix, buildPiArgs, cleanupTempDir, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan, type SubagentTaskDelivery } from "../shared/pi-args.ts";
81
- import { readRuntimeAcknowledgedExtensions } from "../shared/runtime-acknowledged-extensions.ts";
75
+ import { applyThinkingSuffix, deriveForkPromptCacheKey, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/child-tool-plan.ts";
76
+ import { buildInProcessChildLaunch, type InheritedChildRuntime } from "../shared/child-launch.ts";
77
+ import type { ChildSessionFactory } from "../shared/child-session.ts";
78
+ import { runChildSession, type ChildEvent, type RunChildSessionResult, type StepSteerHandler } from "./run-child-session.ts";
79
+ import { loadRunnerChildSessionFactory } from "./runner-child-sessions.ts";
80
+ import { SUBAGENT_CHILD_ENV } from "../shared/child-runtime-config.ts";
81
+ import { deriveChildSessionName } from "../../shared/child-session-name.ts";
82
+ import { alignForkedSessionCwd } from "../../shared/fork-session-cwd.ts";
82
83
  import { outputEntryFromAsyncResult, resolveOutputReferences } from "../shared/chain-outputs.ts";
83
- import { createStructuredOutputRuntime, MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput, readStructuredOutputAcceptanceReport } from "../shared/structured-output.ts";
84
- import { formatProcessSignalError, isUnexplainedProcessSignal } from "../shared/process-signal.ts";
85
- import { readChildToolDiagnosticError } from "../shared/tool-availability.ts";
84
+ import { clearStructuredOutputCaptures, createStructuredOutputFileCapture, createStructuredOutputRuntime, MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput, readStructuredOutputAcceptanceReport } from "../shared/structured-output.ts";
85
+ import { formatMidToolExitError, isOrdinaryToolForMidToolExit, isUnexplainedProcessSignal } from "../shared/process-signal.ts";
86
+ import { formatChildToolDiagnostic } from "../shared/tool-availability.ts";
86
87
  import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.ts";
87
88
  import { collectDynamicResults, DynamicFanoutError, materializeDynamicParallelStep, validateDynamicCollection } from "../shared/dynamic-fanout.ts";
88
89
  import { claimRunFanoutBatch, getRunFanoutBudgetSnapshot } from "../shared/run-fanout-budget.ts";
89
90
  import { nestedSummaryFromAsyncStatus, projectNestedEvents, resolveNestedAsyncDir, writeNestedEvent } from "../shared/nested-events.ts";
90
- import { formatModelAttemptNote, formatSubagentModelVerificationError, isContextOverflow, isRetryableModelFailure, recordRetryableModelFailure } from "../shared/model-fallback.ts";
91
- import {
92
- SUBAGENT_STARTUP_RETRY_DELAYS_MS,
93
- formatSubagentExtensionConflictError,
94
- formatSubagentStartupRetryExhaustedError,
95
- formatSubagentStartupRetryNote,
96
- isRetryableSubagentStartupFailure,
97
- waitForSubagentStartupRetry,
98
- } from "../shared/subagent-startup-retry.ts";
91
+ import { formatModelAttemptNote, formatSubagentModelVerificationError, isContextOverflow, isRetryableModelFailureAttempt, recordRetryableModelFailure } from "../shared/model-fallback.ts";
99
92
  import { markProcessTerminalCandidateLeaseRelease, writeProcessTerminalCandidate, type ProcessTerminalCandidate } from "./process-terminal.ts";
100
- import { createOwnedProcessTreeController, type OwnedProcessTreeController } from "./owned-process-tree.ts";
101
93
  import { createSteeringStatus, recordSteeringRequest, steeringStatus, terminalSteeringNoticeState, updateSteeringTarget } from "./steering.ts";
102
- import { attachPostExitStdioGuard, trySignalChild } from "../../shared/post-exit-stdio-guard.ts";
103
- import { PROMPT_REDACTED, detectSubagentError, extractTextFromContent, extractToolArgsPreview, getFinalOutput, hasEmptyTerminalAssistantResponse, readStatus } from "../../shared/utils.ts";
104
- import { evaluateCompletionMutationGuard, validateImplementationToolContract } from "../shared/completion-guard.ts";
94
+ import { PROMPT_REDACTED, detectSubagentError, extractTextFromContent, extractToolArgsPreview, formatEmptyTerminalAssistantResponseError, getFinalOutput, hasEmptyTerminalAssistantResponse, readStatus } from "../../shared/utils.ts";
95
+ import { evaluateCompletionMutationGuard, expectsImplementationMutation, hasMutationToolCapability, validateImplementationToolContract } from "../shared/completion-guard.ts";
96
+ import { planCompletionEvidence, projectSettlementDiagnostic } from "../shared/completion-evidence.ts";
97
+ import { planAbortRecovery } from "../shared/abort-recovery.ts";
105
98
  import {
106
99
  createMutatingFailureState,
107
100
  didMutatingToolFail,
@@ -122,43 +115,49 @@ import {
122
115
  findWorktreeTaskCwdConflict,
123
116
  formatWorktreeDiffSummary,
124
117
  formatWorktreeTaskCwdConflict,
118
+ WORKTREE_AGENT_CWD_PLACEHOLDER,
125
119
  type WorktreeSetup,
126
120
  } from "../shared/worktree.ts";
127
- import { resolveEffectiveThinking } from "../../shared/model-info.ts";
128
- import { assertThinkingWithinCeiling, decodeThinkingCeiling, SUBAGENT_THINKING_CEILING_ENV } from "../../shared/thinking-ceiling.ts";
121
+ import { findModelInfo, resolveEffectiveThinking } from "../../shared/model-info.ts";
122
+ import { assertThinkingWithinCeiling } from "../../shared/thinking-ceiling.ts";
129
123
  import { launchBindingDigest } from "../../shared/launch-contract.ts";
130
124
  import { writeInitialProgressFile } from "../../shared/settings.ts";
131
125
  import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.ts";
132
- import { acceptanceFailureMessage, aggregateAcceptanceReport, buildSkippedAcceptanceLedger, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport } from "../shared/acceptance.ts";
126
+ import { acceptanceFailureMessage, aggregateAcceptanceReport, buildSkippedAcceptanceLedger, evaluateAcceptance, formatAcceptancePrompt, resolveAcceptanceReportMode, resolveEffectiveAcceptance, stripAcceptanceReport } from "../shared/acceptance.ts";
133
127
  import { attachContractProjections, isAgentContractV1 } from "../shared/agent-contract.ts";
134
128
  import { waitForImportedAsyncRoot } from "./chain-root-attachment.ts";
135
129
  import { normalizeExtensionBindings } from "../shared/extension-bindings.ts";
136
130
  import { appendRunnerStepsToStatus, consumeChainAppendRequests, countPendingChainAppendRequests, statusStepDescription } from "./chain-append.ts";
137
131
  import { asyncStatusChildIdentity } from "../shared/child-identity.ts";
138
- import { appendTurnBudgetSystemPrompt, formatTurnBudgetOutput, initialTurnBudgetState, turnBudgetDecision, turnBudgetDeferredNote, turnBudgetDeferredState, turnBudgetExceededMessage, turnBudgetSoftNote, turnBudgetState } from "../shared/turn-budget.ts";
139
132
  import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
140
133
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, toolTimeoutCallKey } from "../shared/tool-timeout.ts";
141
134
  import { usageBudgetExceededMessage, usageBudgetState } from "../shared/usage-budget.ts";
142
135
  import { formatParallelHandoffError, formatParallelHandoffReference, parallelHandoffPath, writeParallelHandoffGroup, writePendingParallelHandoff } from "../shared/parallel-handoff.ts";
143
136
  import { resolveWatchdogConfig } from "../../watchdog/settings.ts";
144
- import { createBoundedByteTail, createBoundedLineReader, formatProtocolOutputLimit, MAX_CHILD_STDERR_BYTES, PI_AGGREGATE_EVENT_PROJECTOR, projectChildLifecycle, type ChildLifecycleAction, type ProtocolOutputLimit } from "../shared/child-protocol.ts";
145
137
  import { acquireSessionLease, type SessionLeaseRequest } from "../shared/session-lease.ts";
146
138
  import { buildExternalCliPrompt, runExternalCli } from "../shared/external-cli-runner.ts";
139
+ import { resolveClaudeCodeLaunch } from "../shared/claude-code-adapter.ts";
140
+ import { resolveCodexExecLaunch } from "../shared/codex-exec-adapter.ts";
141
+ import { resolveCursorAgentLaunch } from "../shared/cursor-agent-adapter.ts";
142
+ import { resolveExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
147
143
  import { runExternalJob } from "../shared/external-job-runner.ts";
148
144
  import { createOrcaProgressTab, type OrcaProgressTab } from "../shared/orca-progress-tabs.ts";
149
- import { decodeSubagentCapabilityCeiling, SUBAGENT_CAPABILITY_CEILING_ENV, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
145
+ import type { ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
150
146
  import {
151
- CHILD_WATCHDOG_CONFIG_ENV,
152
147
  acceptChildWatchdogEvent,
153
- childWatchdogIsActive,
154
- decodeChildWatchdogConfig,
148
+ applyChildWatchdogMessage,
155
149
  isChildWatchdogStatusEvent,
156
150
  resolveChildWatchdogConfig,
157
- type ChildWatchdogStateSnapshot,
151
+ type ChildWatchdogStatusEvent,
158
152
  } from "../../watchdog/child-status.ts";
159
153
 
160
154
  const INTERCOM_DETACH_RECEIPT = "Detached for intercom coordination before task completion.";
161
155
 
156
+ // This process hosts child sessions. An ambient copy of pi-subagents loaded
157
+ // into one of them must register nothing; the variable marks the process as a
158
+ // child host.
159
+ process.env[SUBAGENT_CHILD_ENV] = "1";
160
+
162
161
  interface SubagentRunConfig {
163
162
  id: string;
164
163
  steps: RunnerStep[];
@@ -176,10 +175,16 @@ interface SubagentRunConfig {
176
175
  sessionId?: string | null;
177
176
  completionOwnerId?: string;
178
177
  piPackageRoot?: string;
179
- piArgv1?: string;
178
+ /** Test seam: module the runner imports its `ChildSessionFactory` from. */
179
+ childSessionFactoryModule?: string;
180
+ /** The launching executor's own child runtime when it was itself an in-process child. */
181
+ inheritedChildRuntime?: InheritedChildRuntime;
180
182
  worktreeSetupHook?: string;
181
183
  worktreeSetupHookTimeoutMs?: number;
182
184
  worktreeBaseDir?: string;
185
+ baseRef?: string;
186
+ worktreeProvider?: import("../../shared/types.ts").WorktreeProvider;
187
+ worktreeBranchPrefix?: string;
183
188
  controlConfig?: ResolvedControlConfig;
184
189
  controlIntercomTarget?: string;
185
190
  childIntercomTargets?: Array<string | undefined>;
@@ -193,7 +198,6 @@ interface SubagentRunConfig {
193
198
  deadlineAt?: number;
194
199
  /** Resolved configured hard per-tool-call timeout (ms); fast tools still have a default when undefined. */
195
200
  toolTimeoutMs?: number;
196
- turnBudget?: ResolvedTurnBudget;
197
201
  toolBudget?: ResolvedToolBudget;
198
202
  usageBudget?: UsageBudgetConfig;
199
203
  revivalLease?: SessionLeaseRequest;
@@ -206,12 +210,16 @@ interface SubagentRunConfig {
206
210
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
207
211
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
208
212
  runnerProcessInstanceId?: string;
213
+ launchBarrierToken?: string;
209
214
  parentWorkflowRunId?: string;
210
215
  workflowKey?: string;
216
+ lane?: WorkflowLaneMetadata;
211
217
  }
212
218
 
213
219
  interface StepResult {
214
220
  agent: string;
221
+ /** Human-readable display name for the child session, when derived at launch. */
222
+ sessionName?: string;
215
223
  context?: "fresh" | "fork";
216
224
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
217
225
  capabilityAudit?: import("../shared/capability-ceiling.ts").SubagentCapabilityAudit;
@@ -220,7 +228,6 @@ interface StepResult {
220
228
  output: string;
221
229
  outputState?: SubagentOutputState;
222
230
  error?: string;
223
- protocolError?: ProtocolOutputLimit;
224
231
  success?: boolean;
225
232
  exitCode: number | null;
226
233
  usage?: Usage;
@@ -232,14 +239,12 @@ interface StepResult {
232
239
  stopped?: boolean;
233
240
  processSignal?: string | null;
234
241
  timeoutRecovery?: import("../../shared/types.ts").TimeoutRecoverySummary;
235
- turnBudget?: TurnBudgetState;
236
- turnBudgetExceeded?: boolean;
237
- wrapUpRequested?: boolean;
238
242
  toolBudget?: ToolBudgetState;
239
243
  toolBudgetBlocked?: boolean;
240
244
  sessionFile?: string;
241
245
  intercomTarget?: string;
242
246
  model?: string;
247
+ thinking?: string;
243
248
  attemptedModels?: string[];
244
249
  modelAttempts?: ModelAttempt[];
245
250
  /** True when the dispatch failed because the input exceeded the model's context window. */
@@ -261,8 +266,6 @@ interface StepResult {
261
266
  structuredOutputSchemaPath?: string;
262
267
  acceptance?: import("../../shared/types.ts").AcceptanceLedger;
263
268
  watchdog?: import("../../shared/types.ts").ChildWatchdogProgress;
264
- writerProcesses?: PiWriterProcessInstanceExitV1[];
265
- writerAttemptCount?: number;
266
269
  runner?: ExternalCliRunnerStatus | ExternalJobRunnerStatus;
267
270
  externalProcess?: ExternalProcessStatus;
268
271
  externalJob?: ExternalJobStatus;
@@ -363,10 +366,6 @@ function appendDiagnosticJsonl(filePath: string, line: string, droppedEventType?
363
366
  state.diagnosticsTruncated = true;
364
367
  }
365
368
 
366
- function shouldPersistChildEvent(event: Record<string, unknown>): boolean {
367
- return event.type !== "message_update";
368
- }
369
-
370
369
  function isBlockingSupervisorTool(toolName: string | undefined, args: unknown): boolean {
371
370
  if (!args || typeof args !== "object" || Array.isArray(args)) return false;
372
371
  if (toolName === "contact_supervisor") {
@@ -422,6 +421,23 @@ function costSummaryFromAttempts(attempts: ModelAttempt[] | undefined): CostSumm
422
421
  : undefined;
423
422
  }
424
423
 
424
+ function usageFromAttempts(attempts: ModelAttempt[] | undefined): Usage | undefined {
425
+ if (!attempts || attempts.length === 0) return undefined;
426
+ const usage = emptyUsage();
427
+ for (const attempt of attempts) {
428
+ if (!attempt.usage) continue;
429
+ usage.input += attempt.usage.input;
430
+ usage.output += attempt.usage.output;
431
+ usage.cacheRead += attempt.usage.cacheRead;
432
+ usage.cacheWrite += attempt.usage.cacheWrite;
433
+ usage.cost += attempt.usage.cost;
434
+ usage.turns += attempt.usage.turns;
435
+ }
436
+ return usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0
437
+ ? usage
438
+ : undefined;
439
+ }
440
+
425
441
  function appendRecentStepOutput(step: RunnerStatusStep, lines: string[]): void {
426
442
  const nonEmpty = lines.filter((line) => line.trim());
427
443
  if (nonEmpty.length === 0) return;
@@ -432,15 +448,6 @@ function appendRecentStepOutput(step: RunnerStatusStep, lines: string[]): void {
432
448
  }
433
449
  }
434
450
 
435
- function assistantStartsToolCall(message: Message): boolean {
436
- return Array.isArray(message.content)
437
- && message.content.some((part) => (part as { type?: string }).type === "toolCall");
438
- }
439
-
440
- function isTerminalAssistantStop(message: Message): boolean {
441
- return (message as { stopReason?: string }).stopReason === "stop" && !assistantStartsToolCall(message);
442
- }
443
-
444
451
  type UndefinedOmitted<T extends object> = {
445
452
  [K in keyof T]: Exclude<T[K], undefined>;
446
453
  };
@@ -483,595 +490,38 @@ function resetStepLiveDetail(step: RunnerStatusStep): void {
483
490
  step.recentOutput = [];
484
491
  }
485
492
 
486
- interface ChildEventContext {
487
- eventsPath: string;
488
- runId: string;
489
- stepIndex: number;
490
- agent: string;
491
- }
492
-
493
- interface ChildUsage {
494
- input?: number;
495
- inputTokens?: number;
496
- output?: number;
497
- outputTokens?: number;
498
- cacheRead?: number;
499
- cacheWrite?: number;
500
- cost?: { total?: number };
501
- }
493
+ const MAX_CHILD_FAILURE_DIAGNOSTIC_CHARS = 8_192;
502
494
 
503
- type ChildMessage = Message & {
504
- model?: string;
505
- errorMessage?: string;
506
- usage?: ChildUsage;
507
- };
508
-
509
- interface ChildEvent {
510
- type?: string;
511
- message?: ChildMessage;
512
- toolName?: string;
513
- args?: Record<string, unknown>;
514
- willRetry?: unknown;
515
- }
516
-
517
- interface RunPiStreamingResult {
518
- stderr: string;
519
- exitCode: number | null;
520
- messages: Message[];
521
- usage: Usage;
522
- toolCount: number;
523
- durationMs: number;
524
- model?: string;
525
- error?: string;
526
- protocolError?: ProtocolOutputLimit;
527
- finalOutput: string;
528
- outputState: SubagentOutputState;
529
- interrupted?: boolean;
530
- timedOut?: boolean;
531
- stopped?: boolean;
532
- turnBudget?: TurnBudgetState;
533
- turnBudgetExceeded?: boolean;
534
- wrapUpRequested?: boolean;
535
- toolBudget?: ToolBudgetState;
536
- toolBudgetBlocked?: boolean;
537
- observedMutationAttempt?: boolean;
538
- structuredOutputToolInvoked?: boolean;
539
- structuredOutputMessageStartIndex?: number;
540
- watchdog?: ChildWatchdogStateSnapshot;
541
- runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
542
- processInstanceId: string;
543
- processCloseObservedAt?: number;
544
- processSignal?: string | null;
545
- processTree: ProcessTreeTerminalV1;
546
- currentTool?: string;
547
- currentToolArgs?: string;
548
- currentPath?: string;
495
+ function formatRequiredOutputError(requiredOutput: {
496
+ kind: "file-only" | "structured";
497
+ path: string;
498
+ missing: boolean;
499
+ } | undefined): string | undefined {
500
+ if (!requiredOutput?.missing) return undefined;
501
+ return `Required ${requiredOutput.kind} output was not produced: ${requiredOutput.path.slice(0, 2_048)}`;
549
502
  }
550
503
 
551
- function runPiStreaming(
552
- args: string[],
553
- cwd: string,
554
- outputFile: string,
555
- env?: Record<string, string | undefined>,
556
- piPackageRoot?: string,
557
- piArgv1?: string,
558
- maxSubagentDepth?: number,
559
- childEventContext?: ChildEventContext,
560
- registerInterrupt?: (interrupt: (() => void) | undefined) => void,
561
- onChildEvent?: (event: ChildEvent) => void,
562
- transcriptWriter?: ChildTranscriptWriter,
563
- registerTimeout?: (interrupt: (() => void) | undefined) => void,
564
- timeoutMessage?: string,
565
- registerStop?: (stop: (() => void) | undefined) => void,
566
- stopMessage?: string,
567
- registerTurnBudgetAbort?: (abort: ((message: string, state?: TurnBudgetState) => void) | undefined) => void,
568
- onWriterProcess?: (writer: { state: "none" | "spawning" } | { state: "running"; pid: number }) => void,
569
- toolTimeoutMs?: number,
570
- runDeadlineAt?: number,
571
- orcaProgressTab?: OrcaProgressTab,
572
- expectedModelForVerification?: string,
573
- modelVerificationRegistry?: Array<{ provider: string; id: string; fullId: string }>,
574
- ): Promise<RunPiStreamingResult> {
575
- return new Promise((resolve) => {
576
- const startedAt = Date.now();
577
- const processInstanceId = randomUUID();
578
- onWriterProcess?.({ state: "spawning" });
579
- const outputStream = fs.createWriteStream(outputFile, { flags: "w" });
580
- const spawnEnv = { ...process.env, ...(env ?? {}), ...getSubagentDepthEnv(maxSubagentDepth) };
581
- const spawnSpec = getPiSpawnCommand(args, {
582
- ...(piPackageRoot ? { piPackageRoot } : {}),
583
- ...(piArgv1 ? { argv1: piArgv1 } : {}),
584
- });
585
- const child = spawn(spawnSpec.command, spawnSpec.args, {
586
- cwd,
587
- stdio: ["ignore", "pipe", "pipe"],
588
- env: spawnEnv,
589
- windowsHide: true,
590
- detached: process.platform !== "win32",
591
- });
592
- let processTreeController: OwnedProcessTreeController | undefined;
593
- const stderrTail = createBoundedByteTail();
594
- const rawStdoutTail = createBoundedByteTail();
595
- const messages: Message[] = [];
596
- const usage = emptyUsage();
597
- let model: string | undefined;
598
- let writerRegistrationError: string | undefined;
599
- if (typeof child.pid === "number") {
600
- processTreeController = createOwnedProcessTreeController(child.pid);
601
- try {
602
- onWriterProcess?.({ state: "running", pid: child.pid });
603
- } catch (writerError) {
604
- writerRegistrationError = `Failed to record revived Pi writer ownership: ${writerError instanceof Error ? writerError.message : String(writerError)}`;
605
- trySignalChild(child, "SIGKILL");
606
- }
607
- }
608
- let error: string | undefined = writerRegistrationError;
609
- let assistantError: string | undefined;
610
- let interrupted = false;
611
- let timedOut = false;
612
- let stopped = false;
613
- let turnBudgetExceeded = false;
614
- let turnBudgetMessage: string | undefined;
615
- let turnBudget: TurnBudgetState | undefined;
616
- let observedMutationAttempt = false;
617
- let structuredOutputToolInvoked = false;
618
- let structuredOutputMessageStartIndex: number | undefined;
619
- let currentTool: string | undefined;
620
- let currentToolArgs: string | undefined;
621
- let currentPath: string | undefined;
622
- let toolCount = 0;
623
- const childWatchdogConfig = decodeChildWatchdogConfig(env?.[CHILD_WATCHDOG_CONFIG_ENV]);
624
- let childWatchdogState: ChildWatchdogStateSnapshot | undefined;
625
- let applyChildLifecycle = (_action: ChildLifecycleAction): void => {};
626
- const updateChildWatchdogState = (snapshot: ChildWatchdogStateSnapshot): void => {
627
- childWatchdogState = snapshot;
628
- };
629
-
630
- const writeOutputLine = (line: string) => {
631
- if (!line.trim()) return;
632
- outputStream.write(`${line}\n`);
633
- orcaProgressTab?.append(`${line}\n`);
634
- };
635
-
636
- const writeOutputText = (text: string) => {
637
- for (const line of text.split("\n")) {
638
- writeOutputLine(line);
639
- }
640
- };
641
-
642
- const appendChildEvent = (event: Record<string, unknown>) => {
643
- if (!childEventContext) return;
644
- if (!shouldPersistChildEvent(event)) return;
645
- appendDiagnosticJsonl(childEventContext.eventsPath, JSON.stringify({
646
- ...event,
647
- subagentSource: "child",
648
- subagentRunId: childEventContext.runId,
649
- subagentStepIndex: childEventContext.stepIndex,
650
- subagentAgent: childEventContext.agent,
651
- observedAt: Date.now(),
652
- }), typeof event.type === "string" ? event.type : undefined);
653
- };
654
-
655
- const appendChildLine = (type: "subagent.child.stdout" | "subagent.child.stderr", line: string) => {
656
- appendChildEvent({ type, line });
657
- if (type === "subagent.child.stdout") transcriptWriter?.writeStdoutLine(line);
658
- else transcriptWriter?.writeStderrLine(line);
659
- };
660
-
661
- const processStdoutLine = (line: string) => {
662
- if (!line.trim()) return;
663
- let event: ChildEvent;
664
- try {
665
- event = JSON.parse(line) as ChildEvent;
666
- } catch {
667
- rawStdoutTail.push(`${line}\n`);
668
- writeOutputLine(line);
669
- appendChildLine("subagent.child.stdout", line);
670
- return;
671
- }
672
-
673
- appendChildEvent(event as unknown as Record<string, unknown>);
674
- transcriptWriter?.writeChildEvent(event);
675
- if (event.type === "agent_settled") agentSettledReceived = true;
676
- applyChildLifecycle(projectChildLifecycle(event));
677
-
678
- if (isChildWatchdogStatusEvent(event)) {
679
- if (!childWatchdogConfig) return;
680
- const next = acceptChildWatchdogEvent({
681
- current: childWatchdogState,
682
- event,
683
- ...(childEventContext ? {
684
- runId: childEventContext.runId,
685
- agent: childEventContext.agent,
686
- childIndex: childEventContext.stepIndex,
687
- } : {}),
688
- });
689
- if (!next) return;
690
- updateChildWatchdogState(next);
691
- onChildEvent?.(event);
692
- if (childWatchdogIsActive(next)) {
693
- if (finalDrainTimer) {
694
- clearTimeout(finalDrainTimer);
695
- finalDrainTimer = undefined;
696
- }
697
- if (finalHardKillTimer) {
698
- clearTimeout(finalHardKillTimer);
699
- finalHardKillTimer = undefined;
700
- }
701
- armWatchdogTail();
702
- } else {
703
- clearWatchdogTailTimer();
704
- if (cleanTerminalAssistantStopReceived || agentSettledReceived) startFinalDrain();
705
- }
706
- return;
707
- }
708
-
709
- onChildEvent?.(event);
710
-
711
- if (event.type === "tool_execution_end") {
712
- clearActiveToolTimeout(event);
713
- currentTool = undefined;
714
- currentToolArgs = undefined;
715
- currentPath = undefined;
716
- return;
717
- }
718
-
719
- if (event.type === "tool_execution_start" && event.toolName) {
720
- toolCount += 1;
721
- armToolTimeout({ toolCallId: (event as { toolCallId?: unknown }).toolCallId, toolName: event.toolName });
722
- currentTool = event.toolName;
723
- currentToolArgs = extractToolArgsPreview(event.args ?? {});
724
- currentPath = resolveCurrentPath(event.toolName, event.args);
725
- if (event.toolName === "structured_output") {
726
- structuredOutputToolInvoked = true;
727
- structuredOutputMessageStartIndex = messages.length;
728
- }
729
- observedMutationAttempt = observedMutationAttempt || isMutatingTool(event.toolName, event.args);
730
- const toolArgs = extractToolArgsPreview(event.args ?? {});
731
- writeOutputLine(toolArgs ? `${event.toolName}: ${toolArgs}` : event.toolName);
732
- return;
733
- }
734
-
735
- if ((event.type === "message_end" || event.type === "tool_result_end") && event.message) {
736
- messages.push(event.message);
737
- const text = extractTextFromContent(event.message.content);
738
- if (text) writeOutputText(text);
739
-
740
- if (event.type !== "message_end" || event.message.role !== "assistant") return;
741
- const hasToolCall = assistantStartsToolCall(event.message);
742
- if (event.message.model) {
743
- model = event.message.model;
744
- if (expectedModelForVerification && !hasToolCall) {
745
- const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, event.message.model, modelVerificationRegistry);
746
- if (modelVerificationError && !error) error = modelVerificationError;
747
- }
748
- }
749
- if (event.message.errorMessage) assistantError = event.message.errorMessage;
750
- const eventUsage = event.message.usage;
751
- if (eventUsage) {
752
- usage.turns++;
753
- usage.input += eventUsage.input ?? eventUsage.inputTokens ?? 0;
754
- usage.output += eventUsage.output ?? eventUsage.outputTokens ?? 0;
755
- usage.cacheRead += eventUsage.cacheRead ?? 0;
756
- usage.cacheWrite += eventUsage.cacheWrite ?? 0;
757
- usage.cost += eventUsage.cost?.total ?? 0;
758
- }
759
- if (isTerminalAssistantStop(event.message)) {
760
- if (!event.message.errorMessage && extractTextFromContent(event.message.content).trim()) assistantError = undefined;
761
- cleanTerminalAssistantStopReceived ||= !event.message.errorMessage;
762
- applyChildLifecycle(projectChildLifecycle(event, true));
763
- }
764
- }
765
- };
766
-
767
- // Guard both cases that can leave the parent waiting on `close` forever:
768
- // a lingering stdio holder after `exit`, or a child that never exits.
769
- const FINAL_STOP_GRACE_MS = 1000;
770
- const HARD_KILL_MS = 3000;
771
- let childExited = false;
772
- let forcedTerminationSignal = false;
773
- let cleanTerminalAssistantStopReceived = false;
774
- let agentSettledReceived = false;
775
- let finalDrainTimer: NodeJS.Timeout | undefined;
776
- let finalHardKillTimer: NodeJS.Timeout | undefined;
777
- let watchdogTailTimer: NodeJS.Timeout | undefined;
778
- let turnBudgetTerminationTimer: NodeJS.Timeout | undefined;
779
- let turnBudgetHardKillTimer: NodeJS.Timeout | undefined;
780
- let protocolHardKillTimer: NodeJS.Timeout | undefined;
781
- let protocolError: ProtocolOutputLimit | undefined;
782
- let settled = false;
783
- applyChildLifecycle = (action: ChildLifecycleAction): void => {
784
- if (action === "cancel-drain") {
785
- if (finalDrainTimer) {
786
- clearTimeout(finalDrainTimer);
787
- finalDrainTimer = undefined;
788
- }
789
- if (finalHardKillTimer) {
790
- clearTimeout(finalHardKillTimer);
791
- finalHardKillTimer = undefined;
792
- }
793
- clearWatchdogTailTimer();
794
- return;
795
- }
796
- if (action === "start-drain") startFinalDrain();
797
- };
798
- const failProtocol = (limit: ProtocolOutputLimit): void => {
799
- if (protocolError) return;
800
- protocolError = limit;
801
- error = formatProtocolOutputLimit(limit);
802
- if (!childExited) {
803
- trySignalChild(child, "SIGTERM");
804
- protocolHardKillTimer = setTimeout(() => {
805
- if (!settled) trySignalChild(child, "SIGKILL");
806
- }, 3000);
807
- protocolHardKillTimer.unref?.();
808
- }
809
- };
810
- const stdoutReader = createBoundedLineReader({
811
- oversizedLineProjector: PI_AGGREGATE_EVENT_PROJECTOR,
812
- onLine: processStdoutLine,
813
- onLimit: failProtocol,
814
- });
815
- const stderrReader = createBoundedLineReader({
816
- stream: "stderr",
817
- maxPendingLineBytes: MAX_CHILD_STDERR_BYTES,
818
- onLine: (line) => appendChildLine("subagent.child.stderr", line),
819
- onLimit: (limit) => appendChildLine("subagent.child.stderr", formatProtocolOutputLimit(limit)),
820
- });
821
- const clearStdioGuard = attachPostExitStdioGuard(child, { idleMs: 2000, hardMs: 8000 });
822
- child.stdout.on("data", (chunk: Buffer) => stdoutReader.push(chunk));
823
- child.stderr.on("data", (chunk: Buffer) => {
824
- stderrTail.push(chunk);
825
- stderrReader.push(chunk);
826
- outputStream.write(chunk);
827
- orcaProgressTab?.append(chunk.toString("utf-8"));
828
- });
829
- registerInterrupt?.(() => {
830
- if (settled || timedOut || stopped) return;
831
- interrupted = true;
832
- if (!error) error = "Interrupted. Waiting for explicit next action.";
833
- trySignalChild(child, "SIGINT");
834
- setTimeout(() => {
835
- if (!settled && !timedOut && !stopped) trySignalChild(child, "SIGTERM");
836
- }, 1000).unref?.();
837
- });
838
- const terminateForTimeout = (message: string): void => {
839
- if (settled || timedOut || stopped) return;
840
- timedOut = true;
841
- // runPiStreaming's terminal result derives the timeout error from this
842
- // message, so retain the tool-specific reason through finalization.
843
- timeoutMessage = message;
844
- interrupted = false;
845
- error = message;
846
- if (processTreeController) void processTreeController.terminate();
847
- else trySignalChild(child, "SIGTERM");
848
- };
849
- let toolTimeoutSequence = 0;
850
- const activeToolTimeouts = new Map<string, { toolName: string; timer: ReturnType<typeof setTimeout> }>();
851
- const activeToolTimeoutKeysByName = new Map<string, string[]>();
852
- const removeToolTimeoutKey = (key: string): void => {
853
- const active = activeToolTimeouts.get(key);
854
- if (!active) return;
855
- clearTimeout(active.timer);
856
- activeToolTimeouts.delete(key);
857
- const keys = activeToolTimeoutKeysByName.get(active.toolName)?.filter((candidate) => candidate !== key) ?? [];
858
- if (keys.length > 0) activeToolTimeoutKeysByName.set(active.toolName, keys);
859
- else activeToolTimeoutKeysByName.delete(active.toolName);
860
- };
861
- const clearActiveToolTimeout = (event: { toolCallId?: unknown; toolName?: unknown }): void => {
862
- const key = typeof event.toolCallId === "string" && event.toolCallId.length > 0
863
- ? `id:${event.toolCallId}`
864
- : typeof event.toolName === "string"
865
- ? activeToolTimeoutKeysByName.get(event.toolName)?.[0]
866
- : activeToolTimeouts.size === 1
867
- ? [...activeToolTimeouts.keys()][0]
868
- : undefined;
869
- if (key) removeToolTimeoutKey(key);
870
- };
871
- const clearAllToolTimeouts = (): void => {
872
- for (const key of [...activeToolTimeouts.keys()]) removeToolTimeoutKey(key);
873
- };
874
- const armToolTimeout = (event: { toolCallId?: unknown; toolName: string }): void => {
875
- const timeoutForTool = effectiveToolTimeoutMs(event.toolName, toolTimeoutMs);
876
- if (timeoutForTool === undefined) return;
877
- const runRemaining = runDeadlineAt === undefined ? undefined : Math.max(0, runDeadlineAt - Date.now());
878
- if (runRemaining !== undefined && timeoutForTool >= runRemaining) return;
879
- const key = toolTimeoutCallKey(event, ++toolTimeoutSequence);
880
- const toolName = event.toolName;
881
- const timer = setTimeout(() => {
882
- removeToolTimeoutKey(key);
883
- terminateForTimeout(formatToolTimeoutMessage(toolName, timeoutForTool));
884
- }, timeoutForTool);
885
- timer.unref?.();
886
- activeToolTimeouts.set(key, { toolName, timer });
887
- const keys = activeToolTimeoutKeysByName.get(toolName) ?? [];
888
- keys.push(key);
889
- activeToolTimeoutKeysByName.set(toolName, keys);
890
- };
891
- registerTimeout?.(() => terminateForTimeout(timeoutMessage ?? "Subagent timed out."));
892
- registerStop?.(() => {
893
- if (settled || timedOut || stopped) return;
894
- stopped = true;
895
- interrupted = false;
896
- error = stopMessage ?? "Subagent stopped by user.";
897
- if (processTreeController) void processTreeController.terminate();
898
- else trySignalChild(child, "SIGTERM");
899
- });
900
- registerTurnBudgetAbort?.((message, state) => {
901
- if (settled || timedOut || stopped || turnBudgetExceeded) return;
902
- turnBudgetExceeded = true;
903
- turnBudgetMessage = message;
904
- turnBudget = state;
905
- interrupted = false;
906
- error = message;
907
- trySignalChild(child, "SIGINT");
908
- turnBudgetTerminationTimer = setTimeout(() => {
909
- if (!settled && !timedOut && !stopped) trySignalChild(child, "SIGTERM");
910
- }, 1000);
911
- turnBudgetTerminationTimer.unref?.();
912
- turnBudgetHardKillTimer = setTimeout(() => {
913
- if (!settled && !timedOut && !stopped) trySignalChild(child, "SIGKILL");
914
- }, 4000);
915
- turnBudgetHardKillTimer.unref?.();
916
- });
917
- const clearDrainTimers = () => {
918
- clearAllToolTimeouts();
919
- if (finalDrainTimer) {
920
- clearTimeout(finalDrainTimer);
921
- finalDrainTimer = undefined;
922
- }
923
- if (finalHardKillTimer) {
924
- clearTimeout(finalHardKillTimer);
925
- finalHardKillTimer = undefined;
926
- }
927
- clearWatchdogTailTimer();
928
- if (turnBudgetTerminationTimer) {
929
- clearTimeout(turnBudgetTerminationTimer);
930
- turnBudgetTerminationTimer = undefined;
931
- }
932
- if (turnBudgetHardKillTimer) {
933
- clearTimeout(turnBudgetHardKillTimer);
934
- turnBudgetHardKillTimer = undefined;
935
- }
936
- if (protocolHardKillTimer) {
937
- clearTimeout(protocolHardKillTimer);
938
- protocolHardKillTimer = undefined;
939
- }
940
- };
941
- function startFinalDrain(): void {
942
- if (childWatchdogIsActive(childWatchdogState)) {
943
- armWatchdogTail();
944
- return;
945
- }
946
- if (childExited || finalDrainTimer || settled) return;
947
- finalDrainTimer = setTimeout(() => {
948
- if (settled) return;
949
- const termSent = trySignalChild(child, "SIGTERM");
950
- if (!termSent) return;
951
- forcedTerminationSignal = true;
952
- if (!cleanTerminalAssistantStopReceived && !agentSettledReceived && !error && !assistantError) {
953
- error = `Subagent process did not exit within ${FINAL_STOP_GRACE_MS}ms after its terminal event. Forcing termination.`;
954
- }
955
- finalHardKillTimer = setTimeout(() => {
956
- if (settled) return;
957
- forcedTerminationSignal = trySignalChild(child, "SIGKILL") || forcedTerminationSignal;
958
- }, HARD_KILL_MS);
959
- finalHardKillTimer.unref?.();
960
- }, FINAL_STOP_GRACE_MS);
961
- finalDrainTimer.unref?.();
962
- }
963
- function clearWatchdogTailTimer(): void {
964
- if (watchdogTailTimer) {
965
- clearTimeout(watchdogTailTimer);
966
- watchdogTailTimer = undefined;
967
- }
968
- }
969
- function armWatchdogTail(): void {
970
- if ((!cleanTerminalAssistantStopReceived && !agentSettledReceived) || watchdogTailTimer || settled) return;
971
- watchdogTailTimer = setTimeout(() => {
972
- watchdogTailTimer = undefined;
973
- updateChildWatchdogState({
974
- phase: "stale",
975
- seq: (childWatchdogState?.seq ?? 0) + 1,
976
- lastUpdate: Date.now(),
977
- followUpPending: false,
978
- reason: "child watchdog tail timeout",
979
- timedOut: true,
980
- });
981
- startFinalDrain();
982
- }, childWatchdogConfig?.watchdogTailTimeoutMs ?? 120_000);
983
- watchdogTailTimer.unref?.();
984
- }
985
- child.on("exit", () => {
986
- childExited = true;
987
- clearDrainTimers();
988
- });
989
- child.on("close", async (exitCode, signal) => {
990
- settled = true;
991
- const processCloseObservedAt = Date.now();
992
- const processTree = processTreeController
993
- ? await processTreeController.finishAfterWriterClose()
994
- : { state: "unknown" as const, reason: "verification-failed" as const, diagnostic: "Writer PID was unavailable." };
995
- try {
996
- onWriterProcess?.({ state: "none" });
997
- } catch {
998
- // The runner still owns and releases the lease during finalization.
999
- }
1000
- registerInterrupt?.(undefined);
1001
- registerTimeout?.(undefined);
1002
- registerStop?.(undefined);
1003
- registerTurnBudgetAbort?.(undefined);
1004
- clearDrainTimers();
1005
- clearStdioGuard();
1006
- stdoutReader.end();
1007
- stderrReader.end();
1008
- outputStream.end();
1009
- const stderr = stderrTail.text();
1010
- const finalOutput = getFinalOutput(messages) || rawStdoutTail.text().trim();
1011
- const finalError = error ?? assistantError;
1012
- const forcedDrainAfterFinalSuccess = Boolean(forcedTerminationSignal || signal) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !finalError;
1013
- const signalError = isUnexplainedProcessSignal({
1014
- processSignal: signal,
1015
- interrupted,
1016
- timedOut,
1017
- stopped,
1018
- turnBudgetExceeded,
1019
- forcedDrainAfterFinalSuccess,
1020
- }) ? formatProcessSignalError(signal!) : undefined;
1021
- resolve(omitUndefinedProperties({
1022
- stderr,
1023
- exitCode: timedOut || stopped ? 1 : turnBudgetExceeded ? 1 : interrupted || forcedDrainAfterFinalSuccess ? 0 : forcedTerminationSignal || signal ? (exitCode ?? 1) : exitCode,
1024
- messages,
1025
- usage,
1026
- toolCount,
1027
- durationMs: Date.now() - startedAt,
1028
- model,
1029
- error: stopped ? (stopMessage ?? "Subagent stopped by user.") : timedOut ? (timeoutMessage ?? "Subagent timed out.") : turnBudgetExceeded ? turnBudgetMessage : interrupted || forcedDrainAfterFinalSuccess ? undefined : finalError ?? signalError,
1030
- protocolError,
1031
- finalOutput: (timedOut || stopped) && !finalOutput.trim() ? (stopped ? stopMessage ?? "Subagent stopped by user." : timeoutMessage ?? "Subagent timed out.") : finalOutput,
1032
- outputState: finalOutput.trim() ? "present" : "absent",
1033
- interrupted,
1034
- timedOut,
1035
- stopped,
1036
- turnBudget,
1037
- turnBudgetExceeded,
1038
- wrapUpRequested: turnBudget?.outcome === "wrap-up-requested" || turnBudget?.outcome === "termination-deferred" || turnBudgetExceeded || undefined,
1039
- observedMutationAttempt,
1040
- structuredOutputToolInvoked,
1041
- structuredOutputMessageStartIndex,
1042
- watchdog: childWatchdogState,
1043
- processInstanceId,
1044
- processCloseObservedAt,
1045
- processSignal: signal,
1046
- processTree,
1047
- currentTool,
1048
- currentToolArgs,
1049
- currentPath,
1050
- }));
1051
- });
1052
-
1053
- child.on("error", (spawnError) => {
1054
- settled = true;
1055
- try {
1056
- onWriterProcess?.({ state: "none" });
1057
- } catch {
1058
- // The runner still owns and releases the lease during finalization.
1059
- }
1060
- registerInterrupt?.(undefined);
1061
- registerTimeout?.(undefined);
1062
- registerStop?.(undefined);
1063
- registerTurnBudgetAbort?.(undefined);
1064
- clearDrainTimers();
1065
- clearStdioGuard();
1066
- stdoutReader.end();
1067
- stderrReader.end();
1068
- outputStream.end();
1069
- const stderr = stderrTail.text();
1070
- const finalOutput = getFinalOutput(messages) || rawStdoutTail.text().trim();
1071
- const spawnErrorMessage = spawnError instanceof Error ? spawnError.message : String(spawnError);
1072
- 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, processTree: { state: "unknown", reason: "verification-failed", diagnostic: spawnErrorMessage } }));
1073
- });
1074
- });
504
+ function formatChildFailureDiagnostic(input: {
505
+ error: string | undefined;
506
+ afterCompactionSettlement?: boolean;
507
+ abortRecoveryDiagnostic?: string;
508
+ requiredOutput?: {
509
+ kind: "file-only" | "structured";
510
+ path: string;
511
+ missing: boolean;
512
+ };
513
+ }): string | undefined {
514
+ const missingOutput = formatRequiredOutputError(input.requiredOutput);
515
+ const notes = [
516
+ input.abortRecoveryDiagnostic,
517
+ input.afterCompactionSettlement ? "Child failure followed session compaction and agent settlement." : undefined,
518
+ missingOutput && input.error !== missingOutput ? missingOutput : undefined,
519
+ ].filter((note): note is string => Boolean(note));
520
+ if (notes.length === 0) return input.error;
521
+ const context = notes.join("\n");
522
+ const errorLimit = MAX_CHILD_FAILURE_DIAGNOSTIC_CHARS - (context ? context.length + 1 : 0);
523
+ const baseError = input.error || "Subagent failed.";
524
+ return `${baseError.slice(0, Math.max(0, errorLimit))}${context ? `\n${context}` : ""}`;
1075
525
  }
1076
526
 
1077
527
  function resolvePiPackageRootFallback(): string {
@@ -1195,16 +645,17 @@ interface SingleStepContext {
1195
645
  flatIndex: number;
1196
646
  flatStepCount: number;
1197
647
  outputFile: string;
1198
- steerInboxDir?: string;
1199
- steerCapabilityPath?: string;
1200
- steerAckDir?: string;
1201
648
  transcriptPath?: string;
1202
649
  piPackageRoot?: string;
1203
- piArgv1?: string;
650
+ /** Factory the runner creates this step's child session through. */
651
+ childSessions: ChildSessionFactory;
652
+ /** The launching executor's own child runtime; nested route, depth, and ceilings come from here. */
653
+ inheritedChildRuntime?: InheritedChildRuntime;
1204
654
  registerInterrupt?: (interrupt: (() => void) | undefined) => void;
1205
655
  registerTimeout?: (interrupt: (() => void) | undefined) => void;
1206
656
  registerStop?: (stop: (() => void) | undefined) => void;
1207
- registerTurnBudgetAbort?: (abort: ((message: string, state?: TurnBudgetState) => void) | undefined) => void;
657
+ /** Receives the live child's steer handler while its session runs. */
658
+ registerSteer?: (steer: StepSteerHandler | undefined) => void;
1208
659
  timeoutSignal?: AbortSignal;
1209
660
  stopSignal?: AbortSignal;
1210
661
  timeoutMessage?: string;
@@ -1213,18 +664,17 @@ interface SingleStepContext {
1213
664
  toolTimeoutMs?: number;
1214
665
  /** Effective step deadline (Date.now() + effective timeout) when a run budget exists. */
1215
666
  deadlineAt?: number;
1216
- turnBudget?: ResolvedTurnBudget;
1217
667
  childIntercomTarget?: string;
1218
668
  orchestratorIntercomTarget?: string;
1219
669
  nestedRoute?: NestedRouteInfo;
1220
670
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
1221
671
  runFanoutBudget?: RunFanoutBudgetDescriptor;
1222
- onAttemptStart?: (attempt: { model?: string; thinking?: string }) => void;
672
+ onAttemptStart?: (attempt: { model?: string; thinking?: string; contextLimit?: number }) => void;
1223
673
  onChildEvent?: (event: ChildEvent) => void;
1224
- onWriterProcess?: (writer: { state: "none" | "spawning" } | { state: "running"; pid: number }) => void;
1225
674
  onExternalProcess?: (process: ExternalProcessStatus) => void;
1226
675
  onExternalJob?: (status: ExternalJobStatus) => void;
1227
676
  skipAcceptance?: () => boolean;
677
+ usageBudgetExhausted?: () => boolean;
1228
678
  /** False when sibling work in the same Git worktree could have caused the tracked diff. */
1229
679
  trackedMutationEvidenceForCompletionGuard?: boolean;
1230
680
  orcaProgressTab?: OrcaProgressTab;
@@ -1293,10 +743,13 @@ async function runSingleStepInner(
1293
743
  modelAttempts: imported.modelAttempts,
1294
744
  contextOverflow: imported.contextOverflow,
1295
745
  totalCost: imported.totalCost,
746
+ usage: imported.usage,
1296
747
  structuredOutput: timedOut || stopped ? undefined : imported.structuredOutput,
1297
748
  structuredOutputPath: timedOut || stopped ? undefined : imported.structuredOutputPath,
1298
749
  structuredOutputSchemaPath: timedOut || stopped ? undefined : imported.structuredOutputSchemaPath,
1299
750
  acceptance: timedOut || stopped ? undefined : imported.acceptance,
751
+ execution: timedOut || stopped ? undefined : imported.execution,
752
+ effects: timedOut || stopped ? undefined : imported.effects,
1300
753
  });
1301
754
  } finally {
1302
755
  ctx.registerTimeout?.(undefined);
@@ -1305,7 +758,7 @@ async function runSingleStepInner(
1305
758
  }
1306
759
 
1307
760
  const effectiveStructuredOutput = step.structuredOutput ?? (step.structuredOutputSchema
1308
- ? createStructuredOutputRuntime(step.structuredOutputSchema, path.join(path.dirname(ctx.outputFile), "structured-output"))
761
+ ? createStructuredOutputRuntime(step.structuredOutputSchema, path.join(path.dirname(ctx.outputFile), "structured-output"), { acceptanceReport: resolveAcceptanceReportMode(step.acceptanceInput) })
1309
762
  : undefined);
1310
763
  const placeholderRegex = new RegExp(ctx.placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
1311
764
  let task = step.task.replace(placeholderRegex, () => ctx.previousOutput);
@@ -1315,6 +768,8 @@ async function runSingleStepInner(
1315
768
  if (!step.runner) {
1316
769
  resolvedTaskToolPlan = resolvePiLaunchToolPlan(omitUndefinedProperties({
1317
770
  tools: step.tools,
771
+ excludeTools: step.excludeTools,
772
+ allowNestedSubagents: step.allowNestedSubagents,
1318
773
  extensions: step.extensions,
1319
774
  subagentOnlyExtensions: step.subagentOnlyExtensions,
1320
775
  fast: step.fast,
@@ -1325,7 +780,7 @@ async function runSingleStepInner(
1325
780
  requireReadTool: Boolean(step.skills?.length),
1326
781
  structuredOutput: Boolean(effectiveStructuredOutput),
1327
782
  capabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,
1328
- inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
783
+ inheritedCapabilityCeiling: ctx.inheritedChildRuntime?.capabilityCeiling,
1329
784
  permissionRules: step.permissionRules,
1330
785
  }));
1331
786
  const contractTools = resolvedTaskToolPlan.explicitToolAllowlist ? resolvedTaskToolPlan.effectiveToolAllowlist : undefined;
@@ -1351,6 +806,9 @@ async function runSingleStepInner(
1351
806
  });
1352
807
  }
1353
808
  }
809
+ // Derive from the pre-acceptance task so internal acceptance/recovery
810
+ // instructions never leak into the display name.
811
+ const childSessionName = step.sessionName ?? deriveChildSessionName({ agent: step.agent, task, label: step.label });
1354
812
  if (step.effectiveAcceptance) {
1355
813
  const acceptancePrompt = formatAcceptancePrompt(step.effectiveAcceptance, { reportOptional: isAgentContractV1(step.agentContract), structuredOutput: Boolean(step.structuredOutput?.acceptanceReportPath) });
1356
814
  if (acceptancePrompt) task = `${task}\n${acceptancePrompt}`;
@@ -1381,21 +839,29 @@ async function runSingleStepInner(
1381
839
  transcriptWriter?.writeInitialUserMessage(`${PROMPT_REDACTED}; live Prompt Audit only.`);
1382
840
 
1383
841
  if (step.runner?.type === "external-cli") {
1384
- const runner: ExternalCliRunnerStatus = {
1385
- type: "external-cli",
1386
- command: step.runner.command,
1387
- args: step.runner.args ?? [],
1388
- promptDelivery: step.runner.promptDelivery ?? "stdin",
1389
- capabilities: { stop: true, steer: false, resume: false, structuredOutput: false, toolEvents: false },
1390
- };
842
+ const externalCwd = step.cwd ?? ctx.cwd;
843
+ const adapterLaunch = step.runner.adapter === "codex-exec" || step.runner.adapter === "codex-exec-writer"
844
+ ? resolveCodexExecLaunch({ adapter: step.runner.adapter, command: step.runner.command, asyncDir: path.dirname(ctx.outputFile), stepIndex: ctx.flatIndex })
845
+ : step.runner.adapter === "claude-code" || step.runner.adapter === "claude-code-writer"
846
+ ? resolveClaudeCodeLaunch({ adapter: step.runner.adapter, command: step.runner.command })
847
+ : step.runner.adapter === "cursor-agent" || step.runner.adapter === "cursor-agent-writer"
848
+ ? resolveCursorAgentLaunch({ adapter: step.runner.adapter, command: step.runner.command, cwd: externalCwd, asyncDir: path.dirname(ctx.outputFile), stepIndex: ctx.flatIndex })
849
+ : undefined;
850
+ const runner = resolveExternalCliRunnerStatus({ ...step.runner, ...(adapterLaunch ? { args: adapterLaunch.args } : {}) });
1391
851
  const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
1392
852
  const external = await runExternalCli(omitUndefinedProperties({
1393
- command: runner.command,
1394
- args: runner.args,
1395
- cwd: step.cwd ?? ctx.cwd,
853
+ command: adapterLaunch?.command ?? runner.command,
854
+ args: adapterLaunch?.args ?? runner.args,
855
+ cwd: externalCwd,
1396
856
  prompt: buildExternalCliPrompt(step.systemPrompt ?? "", task),
1397
857
  asyncDir: path.dirname(ctx.outputFile),
1398
858
  stepIndex: ctx.flatIndex,
859
+ environment: adapterLaunch?.environment,
860
+ preflight: adapterLaunch?.preflight,
861
+ parser: adapterLaunch?.parser,
862
+ finalOutputPath: adapterLaunch?.finalOutputPath,
863
+ promptFilePath: adapterLaunch?.promptFilePath,
864
+ temporaryDirectories: adapterLaunch?.temporaryDirectories,
1399
865
  registerTimeout: ctx.registerTimeout,
1400
866
  registerStop: ctx.registerStop,
1401
867
  timeoutMessage: ctx.timeoutMessage,
@@ -1406,14 +872,18 @@ async function runSingleStepInner(
1406
872
  }));
1407
873
  try { fs.writeFileSync(ctx.outputFile, external.output, "utf-8"); } catch { /* Observability output is best-effort. */ }
1408
874
  const resolvedOutput = step.outputPath && external.exitCode === 0
1409
- ? resolveSingleOutput(step.outputPath, external.output, outputSnapshot)
875
+ ? resolveSingleOutput(step.outputPath, external.output, outputSnapshot, step.outputClaimPath)
1410
876
  : { fullOutput: external.output };
1411
877
  const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, resolvedOutput.fullOutput) : undefined;
878
+ const exitCode = resolvedOutput.fatalError ? 1 : external.exitCode;
879
+ const error = resolvedOutput.fatalError && resolvedOutput.saveError
880
+ ? external.error ? `${external.error}\n${resolvedOutput.saveError}` : resolvedOutput.saveError
881
+ : external.error;
1412
882
  const finalizedOutput = finalizeSingleOutput(omitUndefinedProperties({
1413
883
  fullOutput: resolvedOutput.fullOutput,
1414
884
  outputPath: step.outputPath,
1415
885
  outputMode: step.outputMode,
1416
- exitCode: external.exitCode ?? 1,
886
+ exitCode: exitCode ?? 1,
1417
887
  savedPath: resolvedOutput.savedPath,
1418
888
  outputReference,
1419
889
  saveError: resolvedOutput.saveError,
@@ -1428,16 +898,17 @@ async function runSingleStepInner(
1428
898
  : {};
1429
899
  return omitUndefinedProperties({
1430
900
  agent: step.agent,
901
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
1431
902
  context: step.context,
1432
903
  output: finalizedOutput.displayOutput,
1433
904
  outputState: external.output.trim() ? "present" : "absent",
1434
- exitCode: external.exitCode,
1435
- error: external.error,
905
+ exitCode,
906
+ error,
1436
907
  timedOut: external.timedOut,
1437
908
  stopped: external.stopped,
1438
909
  processSignal: external.processSignal,
1439
910
  artifactPaths,
1440
- outputSaveError: artifactErrors.outputSaveError,
911
+ outputSaveError: [resolvedOutput.saveError, artifactErrors.outputSaveError].filter(Boolean).join("\n") || undefined,
1441
912
  metadataSaveError: artifactErrors.metadataSaveError,
1442
913
  runner,
1443
914
  externalProcess: external.externalProcess,
@@ -1471,14 +942,18 @@ async function runSingleStepInner(
1471
942
  }));
1472
943
  try { fs.writeFileSync(ctx.outputFile, external.output, "utf-8"); } catch { /* Observability output is best-effort. */ }
1473
944
  const resolvedOutput = step.outputPath && external.exitCode === 0
1474
- ? resolveSingleOutput(step.outputPath, external.output, outputSnapshot)
945
+ ? resolveSingleOutput(step.outputPath, external.output, outputSnapshot, step.outputClaimPath)
1475
946
  : { fullOutput: external.output };
1476
947
  const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, resolvedOutput.fullOutput) : undefined;
948
+ const exitCode = resolvedOutput.fatalError ? 1 : external.exitCode;
949
+ const error = resolvedOutput.fatalError && resolvedOutput.saveError
950
+ ? external.error ? `${external.error}\n${resolvedOutput.saveError}` : resolvedOutput.saveError
951
+ : external.error;
1477
952
  const finalizedOutput = finalizeSingleOutput(omitUndefinedProperties({
1478
953
  fullOutput: resolvedOutput.fullOutput,
1479
954
  outputPath: step.outputPath,
1480
955
  outputMode: step.outputMode,
1481
- exitCode: external.exitCode,
956
+ exitCode: exitCode ?? 1,
1482
957
  savedPath: resolvedOutput.savedPath,
1483
958
  outputReference,
1484
959
  saveError: resolvedOutput.saveError,
@@ -1493,21 +968,29 @@ async function runSingleStepInner(
1493
968
  : {};
1494
969
  return omitUndefinedProperties({
1495
970
  agent: step.agent,
971
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
1496
972
  context: step.context,
1497
973
  output: finalizedOutput.displayOutput,
1498
974
  outputState: external.output.trim() ? "present" : "absent",
1499
- exitCode: external.exitCode,
1500
- error: external.error,
975
+ exitCode,
976
+ error,
1501
977
  timedOut: external.timedOut,
1502
978
  stopped: external.stopped,
1503
979
  artifactPaths,
1504
- outputSaveError: artifactErrors.outputSaveError,
980
+ outputSaveError: [resolvedOutput.saveError, artifactErrors.outputSaveError].filter(Boolean).join("\n") || undefined,
1505
981
  metadataSaveError: artifactErrors.metadataSaveError,
1506
982
  runner,
1507
983
  externalJob: external.externalJob,
1508
984
  });
1509
985
  }
1510
986
 
987
+ const effectiveCwd = step.cwd ?? ctx.cwd;
988
+ const cwdError = preflightLaunchCwd(step.requestedCwd ?? effectiveCwd, effectiveCwd);
989
+ if (cwdError) return { agent: step.agent, output: cwdError, error: cwdError, exitCode: 1, context: step.context };
990
+ if (step.context === "fork" && step.sessionFile && fs.existsSync(step.sessionFile)) {
991
+ alignForkedSessionCwd(step.sessionFile, effectiveCwd);
992
+ }
993
+
1511
994
  const candidates = step.modelCandidates !== undefined
1512
995
  ? step.modelCandidates.length > 0 ? step.modelCandidates : [undefined]
1513
996
  : step.model
@@ -1517,16 +1000,14 @@ async function runSingleStepInner(
1517
1000
  let capabilityAudit: import("../shared/capability-ceiling.ts").SubagentCapabilityAudit | undefined;
1518
1001
  let launchResolvedExtensions = step.launchResolvedExtensions;
1519
1002
  const modelAttempts: ModelAttempt[] = [];
1520
- const writerProcesses: PiWriterProcessInstanceExitV1[] = [];
1521
- let writerAttemptCount = 0;
1522
1003
  const attemptNotes: string[] = [];
1004
+ let finalRequiredOutputMissing: boolean | undefined;
1523
1005
  const eventsPath = path.join(path.dirname(ctx.outputFile), "events.jsonl");
1524
- let finalResult: RunPiStreamingResult | undefined;
1006
+ let finalResult: RunChildSessionResult | undefined;
1525
1007
  let finalOutputSnapshot: SingleOutputSnapshot | undefined;
1526
1008
  let structuredAcceptanceReport: unknown;
1527
1009
  let structuredAcceptanceReportError: string | undefined;
1528
1010
  let completionGuardTriggeredFinal = false;
1529
- let turnBudget = ctx.turnBudget ? initialTurnBudgetState(ctx.turnBudget) : undefined;
1530
1011
  let toolBudget = step.toolBudget ? initialToolBudgetState(step.toolBudget) : undefined;
1531
1012
  let toolBudgetBlocked = false;
1532
1013
  let actualLaunchContractDigest = step.launchContractDigest;
@@ -1534,29 +1015,32 @@ async function runSingleStepInner(
1534
1015
  let finalMutationEvidence = collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
1535
1016
 
1536
1017
  let modelIndex = 0;
1537
- let startupAttemptIndex = 0;
1538
- // Escalated to "file" after an unexplained zero-activity startup failure so
1539
- // retries keep the task text out of argv (endpoint pre-exec scans may deny it).
1540
- let taskDeliveryOverride: SubagentTaskDelivery | undefined;
1541
1018
  let contextOverflow = false;
1542
1019
  let launchWarningsEmitted = false;
1020
+ let abortRecoveryAttempted = false;
1021
+ let nextAttemptTask = task;
1543
1022
  modelAttemptsLoop: while (modelIndex < candidates.length) {
1544
1023
  if (ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break;
1024
+ const recoveringAbort = abortRecoveryAttempted;
1025
+ const attemptTask = nextAttemptTask;
1545
1026
  const candidate = candidates[modelIndex];
1546
1027
  const expectedModelForVerification = candidate && !(step.skipPrimaryModelVerification && modelIndex === 0) ? candidate : undefined;
1547
1028
  try {
1548
- assertThinkingWithinCeiling({ model: candidate, configThinking: step.thinking, ceiling: step.thinkingCeiling ?? decodeThinkingCeiling(process.env[SUBAGENT_THINKING_CEILING_ENV]), agent: step.agent, runId: ctx.id });
1029
+ assertThinkingWithinCeiling({ model: candidate, configThinking: step.thinking, ceiling: step.thinkingCeiling, agent: step.agent, runId: ctx.id });
1549
1030
  } catch (error) {
1550
1031
  const message = error instanceof Error ? error.message : String(error);
1551
1032
  return omitUndefinedProperties({ agent: step.agent, output: message, error: message, exitCode: 1, context: step.context, thinkingCeiling: step.thinkingCeiling });
1552
1033
  }
1553
- ctx.onAttemptStart?.(omitUndefinedProperties({ model: candidate, thinking: resolveEffectiveThinking(candidate, step.thinking) }));
1034
+ ctx.onAttemptStart?.(omitUndefinedProperties({
1035
+ model: candidate,
1036
+ thinking: resolveEffectiveThinking(candidate, step.thinking),
1037
+ contextLimit: findModelInfo(candidate, step.modelVerificationRegistry)?.contextWindow,
1038
+ }));
1554
1039
  const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
1555
1040
  if (effectiveStructuredOutput) {
1556
- try {
1557
- if (fs.existsSync(effectiveStructuredOutput.outputPath)) fs.unlinkSync(effectiveStructuredOutput.outputPath);
1558
- } catch {
1559
- // Missing/stale structured-output files are handled after the child exits.
1041
+ const cleanupError = clearStructuredOutputCaptures(effectiveStructuredOutput);
1042
+ if (cleanupError) {
1043
+ return omitUndefinedProperties({ agent: step.agent, output: cleanupError, error: cleanupError, exitCode: 1, context: step.context });
1560
1044
  }
1561
1045
  }
1562
1046
  const watchdogConfig = resolveWatchdogConfig(step.cwd ?? ctx.cwd);
@@ -1569,45 +1053,42 @@ async function runSingleStepInner(
1569
1053
  childIndex: ctx.flatIndex,
1570
1054
  })
1571
1055
  : undefined;
1572
- const { args, env, tempDir, toolDiagnosticPath, runtimeAcknowledgedExtensionsPath, capabilityAudit: attemptCapabilityAudit, warnings } = buildPiArgs(omitUndefinedProperties({
1056
+ let watchdogSink: ((event: ChildWatchdogStatusEvent) => void) | undefined;
1057
+ const launch = buildInProcessChildLaunch(omitUndefinedProperties({
1573
1058
  parentSessionId: step.parentSessionId,
1574
- baseArgs: ["--mode", "json", "-p"],
1575
- task,
1576
- taskDelivery: taskDeliveryOverride,
1059
+ forkCacheKey: step.context === "fork" ? deriveForkPromptCacheKey(step.parentSessionId) : undefined,
1577
1060
  sessionEnabled,
1578
1061
  sessionDir,
1579
1062
  sessionFile: step.sessionFile,
1580
1063
  model: candidate,
1581
1064
  inheritProjectContext: step.inheritProjectContext,
1065
+ inheritGlobalContext: step.inheritGlobalContext,
1582
1066
  inheritSkills: step.inheritSkills,
1583
1067
  requireReadTool: Boolean(step.skills?.length),
1584
1068
  tools: step.tools,
1069
+ excludeTools: step.excludeTools,
1070
+ allowNestedSubagents: step.allowNestedSubagents,
1585
1071
  extensions: step.extensions,
1586
1072
  subagentOnlyExtensions: step.subagentOnlyExtensions,
1587
1073
  fast: step.fast,
1588
1074
  modelCandidates: step.modelCandidates,
1589
- systemPrompt: appendTurnBudgetSystemPrompt(step.systemPrompt ?? "", ctx.turnBudget),
1075
+ systemPrompt: step.systemPrompt ?? "",
1590
1076
  systemPromptMode: step.systemPromptMode,
1591
1077
  mcpDirectTools: step.mcpDirectTools,
1078
+ extensionBindings,
1592
1079
  capabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,
1593
1080
  cwd: step.cwd ?? ctx.cwd,
1594
- promptFileStem: step.agent,
1595
1081
  intercomSessionName: ctx.childIntercomTarget,
1082
+ sessionName: childSessionName,
1596
1083
  orchestratorIntercomTarget: ctx.orchestratorIntercomTarget,
1597
1084
  runId: ctx.id,
1598
1085
  childAgentName: step.agent,
1599
1086
  childIndex: ctx.flatIndex,
1600
- parentEventSink: ctx.nestedRoute?.eventSink,
1601
- parentControlInbox: ctx.nestedRoute?.controlInbox,
1602
- parentRootRunId: ctx.nestedRoute?.rootRunId,
1603
- parentCapabilityToken: ctx.nestedRoute?.capabilityToken,
1087
+ nestedRoute: ctx.nestedRoute,
1604
1088
  runFanoutBudget: ctx.runFanoutBudget ? {
1605
1089
  ...ctx.runFanoutBudget,
1606
1090
  ...(step.runFanoutPath ? { parentPath: `${ctx.runFanoutBudget.parentPath ? `${ctx.runFanoutBudget.parentPath}/` : ""}${step.runFanoutPath}` } : {}),
1607
1091
  } : undefined,
1608
- steerInboxDir: ctx.steerInboxDir,
1609
- steerCapabilityPath: ctx.steerCapabilityPath,
1610
- steerAckDir: ctx.steerAckDir,
1611
1092
  structuredOutput: effectiveStructuredOutput,
1612
1093
  toolBudget: step.toolBudget,
1613
1094
  permissionRules: step.permissionRules,
@@ -1615,10 +1096,19 @@ async function runSingleStepInner(
1615
1096
  ? path.join(ctx.artifactsDir, "permission-audit", `${ctx.id}-${ctx.flatIndex}.jsonl`)
1616
1097
  : undefined,
1617
1098
  childWatchdog,
1099
+ watchdogStatus: (event) => watchdogSink?.(event),
1618
1100
  waitToolEnabled: step.waitToolEnabled,
1101
+ waitToolDefaultTimeoutMs: step.waitToolDefaultTimeoutMs,
1619
1102
  thinkingCeiling: step.thinkingCeiling,
1620
- extensionBindings,
1103
+ maxSubagentDepth: step.maxSubagentDepth,
1104
+ inherited: ctx.inheritedChildRuntime,
1105
+ host: "runner",
1621
1106
  }));
1107
+ if (effectiveStructuredOutput && launch.config.structuredOutput) {
1108
+ // The runner reads the value back from the runtime's files after the run.
1109
+ launch.config.structuredOutput.capture = createStructuredOutputFileCapture(effectiveStructuredOutput);
1110
+ }
1111
+ const { warnings, capabilityAudit: attemptCapabilityAudit } = launch;
1622
1112
  if (!launchWarningsEmitted && warnings.length > 0) {
1623
1113
  for (const warning of warnings) console.warn(`[pi-subagents] ${warning}`);
1624
1114
  launchWarningsEmitted = true;
@@ -1626,6 +1116,8 @@ async function runSingleStepInner(
1626
1116
  if (step.definitionDigest) {
1627
1117
  const toolPlan = resolvedTaskToolPlan ?? resolvePiLaunchToolPlan(omitUndefinedProperties({
1628
1118
  tools: step.tools,
1119
+ excludeTools: step.excludeTools,
1120
+ allowNestedSubagents: step.allowNestedSubagents,
1629
1121
  extensions: step.extensions,
1630
1122
  subagentOnlyExtensions: step.subagentOnlyExtensions,
1631
1123
  fast: step.fast,
@@ -1636,7 +1128,7 @@ async function runSingleStepInner(
1636
1128
  requireReadTool: Boolean(step.skills?.length),
1637
1129
  structuredOutput: Boolean(effectiveStructuredOutput),
1638
1130
  capabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,
1639
- inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
1131
+ inheritedCapabilityCeiling: ctx.inheritedChildRuntime?.capabilityCeiling,
1640
1132
  permissionRules: step.permissionRules,
1641
1133
  }));
1642
1134
  launchResolvedExtensions = projectLaunchResolvedChildExtensions(toolPlan);
@@ -1648,12 +1140,14 @@ async function runSingleStepInner(
1648
1140
  ...(step.fast !== undefined ? { fast: step.fast } : {}),
1649
1141
  ...(resolveEffectiveThinking(candidate, step.thinking) ? { thinking: resolveEffectiveThinking(candidate, step.thinking) } : {}),
1650
1142
  ...(step.thinkingCeiling ? { thinkingCeiling: step.thinkingCeiling } : {}),
1651
- systemPrompt: appendTurnBudgetSystemPrompt(step.systemPrompt ?? "", ctx.turnBudget),
1143
+ systemPrompt: step.systemPrompt ?? "",
1652
1144
  systemPromptMode: step.systemPromptMode,
1653
1145
  inheritProjectContext: step.inheritProjectContext,
1146
+ inheritGlobalContext: step.inheritGlobalContext,
1654
1147
  inheritSkills: step.inheritSkills,
1655
1148
  skills: step.skills,
1656
1149
  tools: toolPlan.effectiveToolAllowlist,
1150
+ ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
1657
1151
  extensions: toolPlan.extensionArgs,
1658
1152
  mcpDirectTools: toolPlan.effectiveMcpTools,
1659
1153
  ...(step.outputPath ? { outputPath: step.outputPath } : {}),
@@ -1663,71 +1157,55 @@ async function runSingleStepInner(
1663
1157
  }));
1664
1158
  }
1665
1159
  capabilityAudit = attemptCapabilityAudit;
1666
- writerAttemptCount += 1;
1667
- const run = await runPiStreaming(
1668
- args,
1669
- step.cwd ?? ctx.cwd,
1670
- ctx.outputFile,
1671
- env,
1672
- ctx.piPackageRoot,
1673
- ctx.piArgv1,
1674
- step.maxSubagentDepth,
1675
- { eventsPath, runId: ctx.id, stepIndex: ctx.flatIndex, agent: step.agent },
1676
- ctx.registerInterrupt,
1677
- ctx.onChildEvent,
1160
+ // Each attempt rewrites the step output log; synchronous appends keep a
1161
+ // retried attempt from interleaving with the previous attempt's flush.
1162
+ fs.writeFileSync(ctx.outputFile, "", "utf-8");
1163
+ const run = await runChildSession(omitUndefinedProperties({
1164
+ factory: ctx.childSessions,
1165
+ launch,
1166
+ prompt: `Task: ${attemptTask}`,
1167
+ childWatchdog,
1168
+ childEventContext: { runId: ctx.id, stepIndex: ctx.flatIndex, agent: step.agent },
1169
+ appendChildEvent: (event) => appendDiagnosticJsonl(eventsPath, JSON.stringify(event), typeof event.type === "string" ? event.type : undefined),
1170
+ writeOutputLine: (line) => {
1171
+ try {
1172
+ fs.appendFileSync(ctx.outputFile, `${line}\n`, "utf-8");
1173
+ } catch {
1174
+ // The output log is observability only.
1175
+ }
1176
+ ctx.orcaProgressTab?.append(`${line}\n`);
1177
+ },
1178
+ registerInterrupt: ctx.registerInterrupt,
1179
+ registerTimeout: ctx.registerTimeout,
1180
+ registerStop: ctx.registerStop,
1181
+ registerSteer: ctx.registerSteer,
1182
+ registerWatchdogStatus: (sink) => { watchdogSink = sink; },
1183
+ timeoutMessage: ctx.timeoutMessage,
1184
+ stopMessage: ctx.stopMessage,
1185
+ onChildEvent: ctx.onChildEvent,
1678
1186
  transcriptWriter,
1679
- ctx.registerTimeout,
1680
- ctx.timeoutMessage,
1681
- ctx.registerStop,
1682
- ctx.stopMessage,
1683
- ctx.registerTurnBudgetAbort,
1684
- ctx.onWriterProcess,
1685
- ctx.toolTimeoutMs,
1686
- ctx.deadlineAt,
1687
- ctx.orcaProgressTab,
1187
+ toolTimeoutMs: ctx.toolTimeoutMs,
1188
+ runDeadlineAt: ctx.deadlineAt,
1688
1189
  expectedModelForVerification,
1689
- step.modelVerificationRegistry,
1690
- );
1691
- if (run.processCloseObservedAt !== undefined) {
1692
- writerProcesses.push({
1693
- processInstanceId: run.processInstanceId,
1694
- kind: "pi-writer",
1695
- attempt: writerAttemptCount - 1,
1696
- closeObservedAt: run.processCloseObservedAt,
1697
- exitCode: run.exitCode,
1698
- signal: run.processSignal ?? null,
1699
- processTree: run.processTree,
1700
- });
1701
- }
1702
- if (run.turnBudget) turnBudget = run.turnBudget;
1703
- else if (ctx.turnBudget) {
1704
- const assistantMessages = run.messages.filter((message) => message.role === "assistant");
1705
- const turnCount = assistantMessages.length;
1706
- const lastAssistantMessage = assistantMessages.at(-1);
1707
- if (turnCount > 0 && turnCount < ctx.turnBudget.maxTurns) {
1708
- turnBudget = { ...ctx.turnBudget, outcome: "within-budget", turnCount };
1709
- } else if (turnCount >= ctx.turnBudget.maxTurns) {
1710
- const decision = turnBudgetDecision(
1711
- ctx.turnBudget,
1712
- turnCount,
1713
- lastAssistantMessage ? isTerminalAssistantStop(lastAssistantMessage) : false,
1714
- lastAssistantMessage ? assistantStartsToolCall(lastAssistantMessage) : false,
1715
- );
1716
- turnBudget = decision === "defer"
1717
- ? turnBudgetDeferredState(ctx.turnBudget, turnCount)
1718
- : turnBudgetState(ctx.turnBudget, turnCount, decision === "abort");
1719
- }
1720
- }
1721
- const toolAvailabilityError = run.exitCode === 0 && !run.error
1722
- ? readChildToolDiagnosticError(toolDiagnosticPath)
1190
+ modelVerificationRegistry: step.modelVerificationRegistry,
1191
+ mutationTools: step.mutationTools,
1192
+ }));
1193
+ const toolDiagnostic = run.exitCode === 0 && !run.error ? launch.capture.toolDiagnostic() : undefined;
1194
+ const toolAvailabilityError = toolDiagnostic ? formatChildToolDiagnostic(toolDiagnostic) : undefined;
1195
+ const runtimeAcknowledgedExtensions = launch.capture.runtimeAcknowledgedExtensions();
1196
+ const midToolExitError = run.currentTool
1197
+ && isOrdinaryToolForMidToolExit(run.currentTool)
1198
+ && !run.interrupted
1199
+ && !run.timedOut
1200
+ && !run.stopped
1201
+ && !toolAvailabilityError
1202
+ ? formatMidToolExitError({ toolName: run.currentTool })
1723
1203
  : undefined;
1724
- const runtimeAcknowledgedExtensions = readRuntimeAcknowledgedExtensions(runtimeAcknowledgedExtensionsPath);
1725
- cleanupTempDir(tempDir);
1726
1204
 
1727
1205
  let structuredOutput: unknown;
1728
1206
  let structuredError: string | undefined;
1729
1207
  let validatedStructuredOutput = false;
1730
- if (effectiveStructuredOutput && run.exitCode === 0 && !run.error && !toolAvailabilityError) {
1208
+ if (effectiveStructuredOutput && run.exitCode === 0 && !run.error && !toolAvailabilityError && !midToolExitError) {
1731
1209
  if (!run.structuredOutputToolInvoked) {
1732
1210
  structuredError = MISSING_STRUCTURED_OUTPUT_CALL_ERROR;
1733
1211
  } else {
@@ -1749,79 +1227,77 @@ async function runSingleStepInner(
1749
1227
  const errorMessages = validatedStructuredOutput
1750
1228
  ? run.messages.slice(run.structuredOutputMessageStartIndex ?? run.messages.length)
1751
1229
  : run.messages;
1752
- const hiddenError = run.exitCode === 0 && !run.error && !toolAvailabilityError && !structuredError
1230
+ const hiddenError = run.exitCode === 0 && !run.error && !toolAvailabilityError && !structuredError && !midToolExitError
1753
1231
  ? detectSubagentError(errorMessages)
1754
1232
  : null;
1233
+ const terminalEmptyAfterUsefulWork = !validatedStructuredOutput
1234
+ && hasEmptyTerminalAssistantResponse(run.messages)
1235
+ && (run.toolCount > 0 || Boolean(run.finalOutput.trim()));
1755
1236
  const emptyOutputError = run.exitCode === 0
1756
1237
  && !run.error
1757
1238
  && !toolAvailabilityError
1758
1239
  && !structuredError
1759
- && !run.finalOutput.trim()
1760
1240
  && !validatedStructuredOutput
1241
+ && (!run.finalOutput.trim() || terminalEmptyAfterUsefulWork)
1761
1242
  && (!hiddenError?.hasError || hasEmptyTerminalAssistantResponse(run.messages))
1762
- ? "Subagent produced no output (possible model cold-start or empty response)."
1243
+ ? formatEmptyTerminalAssistantResponseError(run.messages)
1763
1244
  : undefined;
1764
1245
  const completionGuardEnabled = isAgentContractV1(step.agentContract) ? step.completionGuard === true : step.completionGuard !== false;
1765
1246
  const completionToolPlan = resolvedTaskToolPlan;
1247
+ const completionTools = completionToolPlan ? (completionToolPlan.explicitToolAllowlist ? completionToolPlan.effectiveToolAllowlist : undefined) : step.tools;
1766
1248
  const mutationEvidence = collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
1767
1249
  finalMutationEvidence = mutationEvidence;
1768
1250
  const completionMutationEvidence = ctx.trackedMutationEvidenceForCompletionGuard === false ? undefined : mutationEvidence;
1769
- const completionGuard = run.exitCode === 0 && !run.error && !structuredError && !hiddenError?.hasError && !emptyOutputError && completionGuardEnabled
1251
+ const completionGuard = run.exitCode === 0 && !run.error && !structuredError && !hiddenError?.hasError && !midToolExitError && !emptyOutputError && completionGuardEnabled
1770
1252
  ? evaluateCompletionMutationGuard(omitUndefinedProperties({
1771
1253
  agent: step.agent,
1772
1254
  task: taskForCompletionGuard,
1773
1255
  messages: run.messages,
1774
- tools: completionToolPlan ? (completionToolPlan.explicitToolAllowlist ? completionToolPlan.effectiveToolAllowlist : undefined) : step.tools,
1256
+ tools: completionTools,
1775
1257
  mcpDirectTools: completionToolPlan?.effectiveMcpTools ?? step.mcpDirectTools,
1258
+ mutationTools: step.mutationTools,
1776
1259
  toolAvailabilityError,
1777
1260
  mutationEvidence: completionMutationEvidence,
1778
1261
  }))
1779
1262
  : undefined;
1780
1263
  const mutationAttemptObserved = run.observedMutationAttempt === true || completionMutationEvidence?.attemptedMutation === true;
1781
- const completionGuardTriggered = completionGuard?.triggered === true && !mutationAttemptObserved;
1782
- const completionGuardBlocked = completionGuard?.blocked === true;
1783
- const fileMutationEffect = completionGuard
1784
- ? {
1785
- status: completionGuardBlocked ? "blocked" as const : completionGuard.expectedMutation ? completionGuardTriggered ? "missing" as const : "observed" as const : "not-applicable" as const,
1786
- expected: completionGuard.expectedMutation,
1787
- attempted: completionGuardBlocked ? false : completionGuard.attemptedMutation || mutationAttemptObserved,
1788
- ...(completionMutationEvidence ? { evidence: completionMutationEvidence } : {}),
1789
- ...(completionGuardBlocked && completionGuard.message ? { message: completionGuard.message } : {}),
1790
- ...(completionGuardTriggered ? { message: "Subagent completed without making edits for an implementation task." } : {}),
1791
- }
1792
- : undefined;
1793
- const completionGuardError = completionGuardTriggered && !isAgentContractV1(step.agentContract)
1794
- ? "Subagent completed without making edits for an implementation task.\nIt appears to have returned planning or scratchpad output instead of applying changes."
1264
+ const completionEvidence = planCompletionEvidence({
1265
+ guard: completionGuard,
1266
+ completionGuardEnabled,
1267
+ mutationCapable: hasMutationToolCapability(completionTools, completionToolPlan?.effectiveMcpTools ?? step.mcpDirectTools),
1268
+ implementationMutationExpected: expectsImplementationMutation(step.agent, taskForCompletionGuard),
1269
+ mutationAttemptObserved,
1270
+ mutationEvidence: completionMutationEvidence,
1271
+ agentContractV1: isAgentContractV1(step.agentContract),
1272
+ });
1273
+ const finalOutputHasPersistableFileContent = run.exitCode === 0 && !run.error && !emptyOutputError && Boolean(stripAcceptanceReport(run.finalOutput).trim());
1274
+ const requiredOutput = step.outputMode === "file-only" && step.outputPath
1275
+ ? { kind: "file-only" as const, path: step.outputPath, missing: !fs.existsSync(step.outputPath) && !finalOutputHasPersistableFileContent }
1276
+ : effectiveStructuredOutput
1277
+ ? { kind: "structured" as const, path: effectiveStructuredOutput.outputPath, missing: !fs.existsSync(effectiveStructuredOutput.outputPath) }
1795
1278
  : undefined;
1796
- const effectiveExitCode = toolAvailabilityError || (completionGuardTriggered && !isAgentContractV1(step.agentContract)) || structuredError || emptyOutputError
1279
+ finalRequiredOutputMissing = requiredOutput?.missing;
1280
+ const missingRequiredOutputError = formatRequiredOutputError(requiredOutput);
1281
+ const missingRequiredOutputAfterMutation = Boolean(missingRequiredOutputError) && (mutationAttemptObserved || Boolean(mutationEvidence.changedFiles.length));
1282
+ const effectiveExitCode = toolAvailabilityError || completionEvidence.legacyFailureError || midToolExitError || structuredError || emptyOutputError || missingRequiredOutputError
1797
1283
  ? 1
1798
1284
  : hiddenError?.hasError
1799
1285
  ? (hiddenError.exitCode ?? 1)
1800
1286
  : run.error && run.exitCode === 0
1801
1287
  ? 1
1802
1288
  : run.exitCode;
1803
- const signalError = run.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
1804
- processSignal: run.processSignal,
1805
- interrupted: run.interrupted,
1806
- timedOut: run.timedOut,
1807
- stopped: run.stopped,
1808
- turnBudgetExceeded: run.turnBudgetExceeded,
1809
- })) ? formatProcessSignalError(run.processSignal!) : undefined;
1810
- const error = formatSubagentExtensionConflictError(
1811
- toolAvailabilityError
1812
- ?? completionGuardError
1813
- ?? structuredError
1814
- ?? emptyOutputError
1815
- ?? (hiddenError?.hasError
1816
- ? hiddenError.details
1817
- ? `${hiddenError.errorType} failed (exit ${effectiveExitCode}): ${hiddenError.details}`
1818
- : `${hiddenError.errorType} failed with exit code ${effectiveExitCode}`
1819
- : run.error || signalError || (run.exitCode !== 0 && run.stderr.trim() ? run.stderr.trim() : undefined)),
1820
- {
1821
- agent: step.agent,
1822
- ambientExtensionsEnabled: launchResolvedExtensions?.disableAmbientExtensions === false,
1823
- },
1824
- );
1289
+ const underlyingError = toolAvailabilityError
1290
+ ?? midToolExitError
1291
+ ?? structuredError
1292
+ ?? run.error
1293
+ ?? emptyOutputError
1294
+ ?? (missingRequiredOutputAfterMutation ? missingRequiredOutputError : undefined)
1295
+ ?? (hiddenError?.hasError
1296
+ ? hiddenError.details
1297
+ ? `${hiddenError.errorType} failed (exit ${effectiveExitCode}): ${hiddenError.details}`
1298
+ : `${hiddenError.errorType} failed with exit code ${effectiveExitCode}`
1299
+ : undefined);
1300
+ const error = underlyingError ?? missingRequiredOutputError ?? completionEvidence.legacyFailureError;
1825
1301
  const attempt: ModelAttempt = omitUndefinedProperties({
1826
1302
  model: candidate ?? run.model ?? step.model ?? "default",
1827
1303
  success: effectiveExitCode === 0 && !error,
@@ -1830,8 +1306,8 @@ async function runSingleStepInner(
1830
1306
  usage: run.usage,
1831
1307
  });
1832
1308
  modelAttempts.push(attempt);
1833
- if (candidate && startupAttemptIndex === 0) attemptedModels.push(candidate);
1834
- completionGuardTriggeredFinal = completionGuardTriggered;
1309
+ if (!recoveringAbort && candidate) attemptedModels.push(candidate);
1310
+ completionGuardTriggeredFinal = completionEvidence.guardTriggered && !underlyingError && !missingRequiredOutputError;
1835
1311
  finalOutputSnapshot = outputSnapshot;
1836
1312
  if (step.toolBudget) {
1837
1313
  const toolMessages = run.messages.filter((message) => message.role === "toolResult");
@@ -1839,57 +1315,49 @@ async function runSingleStepInner(
1839
1315
  toolBudgetBlocked = Boolean(blockedMessage);
1840
1316
  toolBudget = toolBudgetState(step.toolBudget, toolMessages.length, blockedMessage ? (blockedMessage as { toolName?: string }).toolName : undefined);
1841
1317
  }
1842
- 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 };
1843
- if (run.turnBudgetExceeded) break modelAttemptsLoop;
1844
- if (run.stopped || run.timedOut || ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break modelAttemptsLoop;
1845
- if (attempt.success || completionGuardTriggered) break modelAttemptsLoop;
1846
-
1847
- const startupFailure = isRetryableSubagentStartupFailure(omitUndefinedProperties({
1848
- exitCode: effectiveExitCode,
1318
+ const settlementDiagnostic = projectSettlementDiagnostic(completionEvidence, {
1319
+ terminalFailed: effectiveExitCode !== 0,
1320
+ finalTextPresent: Boolean(stripAcceptanceReport(run.finalOutput).trim()),
1321
+ mutationObserved: mutationEvidence.attemptedMutation,
1322
+ requiredOutput,
1323
+ afterCompactionSettlement: run.afterCompactionSettlement === true,
1324
+ });
1325
+ const fileMutationEffect = completionEvidence.fileMutation ?? (missingRequiredOutputAfterMutation ? { status: "observed" as const, expected: completionEvidence.mutationExpected, attempted: true, evidence: mutationEvidence } : undefined);
1326
+ finalResult = { ...run, exitCode: effectiveExitCode, model: candidate ?? run.model, error, structuredOutput, runtimeAcknowledgedExtensions, ...(step.agentContract ? { agentContract: step.agentContract } : {}), ...(fileMutationEffect || settlementDiagnostic ? { effects: { ...(fileMutationEffect ? { fileMutation: fileMutationEffect } : {}), ...(settlementDiagnostic ? { settlementDiagnostic } : {}) } } : {}) } as RunChildSessionResult;
1327
+ const abortRecovery = !attempt.success ? planAbortRecovery({
1328
+ messages: run.messages,
1849
1329
  error,
1850
- finalOutput: run.finalOutput,
1851
- messageCount: run.messages.length,
1852
- toolCount: run.toolCount,
1853
- usage: run.usage,
1854
- durationMs: run.durationMs,
1855
- protocolError: run.protocolError,
1856
- processSignal: run.processSignal,
1857
- observedMutationAttempt: run.observedMutationAttempt,
1330
+ sessionAvailable: Boolean(step.sessionFile && fs.existsSync(step.sessionFile)),
1331
+ alreadyResumed: abortRecoveryAttempted,
1332
+ stopped: run.stopped || ctx.stopSignal?.aborted || ctx.skipAcceptance?.(),
1858
1333
  interrupted: run.interrupted,
1859
- timedOut: run.timedOut,
1860
- stopped: run.stopped,
1861
- turnBudgetExceeded: run.turnBudgetExceeded,
1862
- }));
1863
- const retryDelayMs = SUBAGENT_STARTUP_RETRY_DELAYS_MS[startupAttemptIndex];
1864
- if (startupFailure && retryDelayMs !== undefined) {
1865
- const retryNote = formatSubagentStartupRetryNote({
1866
- model: attempt.model,
1867
- attempt: startupAttemptIndex + 1,
1868
- maxAttempts: SUBAGENT_STARTUP_RETRY_DELAYS_MS.length + 1,
1869
- delayMs: retryDelayMs,
1870
- });
1871
- const shouldRetry = await waitForSubagentStartupRetry(retryDelayMs, [ctx.timeoutSignal, ctx.stopSignal]);
1872
- if (!shouldRetry || ctx.skipAcceptance?.()) break modelAttemptsLoop;
1873
- if (!taskDeliveryOverride && run.processSignal === "SIGKILL") {
1874
- taskDeliveryOverride = "file";
1875
- attemptNotes.push("[startup-retry] retrying with file task delivery to keep the task text out of the child process argv.");
1876
- }
1877
- attempt.error = retryNote;
1878
- attemptNotes.push(retryNote);
1879
- startupAttemptIndex += 1;
1880
- continue;
1334
+ timedOut: run.timedOut || ctx.timeoutSignal?.aborted,
1335
+ toolBudgetExhausted: run.toolBudgetBlocked || toolBudgetBlocked,
1336
+ usageBudgetExhausted: ctx.usageBudgetExhausted?.(),
1337
+ structuredOutputFailed: Boolean(structuredError),
1338
+ acceptanceFailed: false,
1339
+ currentTool: run.currentTool,
1340
+ afterCompactionSettlement: run.afterCompactionSettlement,
1341
+ }) : undefined;
1342
+ if (abortRecovery?.action === "settle" && abortRecovery.diagnostic) {
1343
+ attempt.error = attempt.error
1344
+ ? `${abortRecovery.diagnostic}\n${attempt.error.slice(0, 8_000)}`
1345
+ : abortRecovery.diagnostic;
1346
+ if (finalResult) finalResult.abortRecoveryDiagnostic = abortRecovery.diagnostic;
1881
1347
  }
1882
- if (startupFailure) {
1883
- const startupError = formatSubagentStartupRetryExhaustedError({
1884
- model: attempt.model,
1885
- attempts: startupAttemptIndex + 1,
1886
- });
1887
- attempt.error = startupError;
1888
- finalResult.error = startupError;
1889
- finalResult.finalOutput = startupError;
1890
- break modelAttemptsLoop;
1348
+ if (run.stopped || run.timedOut || ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break modelAttemptsLoop;
1349
+ if (abortRecovery?.action === "settle" && abortRecovery.diagnostic) break modelAttemptsLoop;
1350
+ if (attempt.success) break modelAttemptsLoop;
1351
+ if (recoveringAbort) break modelAttemptsLoop;
1352
+ if (abortRecovery?.action === "resume") {
1353
+ abortRecoveryAttempted = true;
1354
+ nextAttemptTask = abortRecovery.prompt;
1355
+ attemptNotes.push("[abort-recovery] provider/transport abort after useful progress; resuming the retained child session once.");
1356
+ continue;
1891
1357
  }
1892
- const retryableModelFailure = isRetryableModelFailure(error);
1358
+ if (completionEvidence.guardTriggered) break modelAttemptsLoop;
1359
+
1360
+ const retryableModelFailure = isRetryableModelFailureAttempt({ error, messages: run.messages, toolCount: run.toolCount });
1893
1361
  if (retryableModelFailure) recordRetryableModelFailure(candidate ?? run.model ?? step.model, error);
1894
1362
  if (isContextOverflow(error)) {
1895
1363
  contextOverflow = true;
@@ -1899,14 +1367,19 @@ async function runSingleStepInner(
1899
1367
  if (!retryableModelFailure || modelIndex === candidates.length - 1) break modelAttemptsLoop;
1900
1368
  attemptNotes.push(formatModelAttemptNote(attempt, candidates[modelIndex + 1]));
1901
1369
  modelIndex += 1;
1902
- startupAttemptIndex = 0;
1903
1370
  }
1904
1371
 
1905
1372
  const rawOutput = finalResult?.finalOutput ?? "";
1906
1373
  const outputForPersistence = stripAcceptanceReport(rawOutput);
1907
1374
  const resolvedOutput = step.outputPath && finalResult?.exitCode === 0
1908
- ? resolveSingleOutput(step.outputPath, outputForPersistence, finalOutputSnapshot)
1375
+ ? resolveSingleOutput(step.outputPath, outputForPersistence, finalOutputSnapshot, step.outputClaimPath)
1909
1376
  : { fullOutput: outputForPersistence };
1377
+ if (resolvedOutput.fatalError) {
1378
+ if (finalResult) {
1379
+ finalResult.exitCode = 1;
1380
+ finalResult.error = finalResult.error ? `${finalResult.error}\n${resolvedOutput.saveError}` : resolvedOutput.saveError;
1381
+ }
1382
+ }
1910
1383
  const output = stripAcceptanceReport(resolvedOutput.fullOutput);
1911
1384
  const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, output) : undefined;
1912
1385
  let outputForSummary = output;
@@ -1915,21 +1388,13 @@ async function runSingleStepInner(
1915
1388
  }
1916
1389
  if (finalResult?.stopped && !outputForSummary.trim()) {
1917
1390
  outputForSummary = ctx.stopMessage ?? "Subagent stopped by user.";
1918
- } else if (!finalResult?.timedOut && !finalResult?.stopped && finalResult?.turnBudgetExceeded && turnBudget) {
1919
- outputForSummary = formatTurnBudgetOutput(turnBudgetExceededMessage(turnBudget, turnBudget.turnCount), outputForSummary);
1920
- } else if (!finalResult?.timedOut && !finalResult?.stopped && turnBudget?.outcome === "termination-deferred") {
1921
- const note = turnBudgetDeferredNote(turnBudget, turnBudget.terminationDeferredAtTurn ?? turnBudget.turnCount);
1922
- outputForSummary = outputForSummary.trim() ? `${note}\n\n${outputForSummary}` : note;
1923
- } else if (!finalResult?.timedOut && !finalResult?.stopped && turnBudget?.outcome === "wrap-up-requested") {
1924
- const note = turnBudgetSoftNote(turnBudget, turnBudget.wrapUpRequestedAtTurn ?? turnBudget.turnCount);
1925
- outputForSummary = outputForSummary.trim() ? `${note}\n\n${outputForSummary}` : note;
1926
1391
  }
1927
1392
  const outputForAcceptance = rawOutput;
1928
1393
  const childWrittenOutput = step.outputPath
1929
1394
  ? extractChildWrittenOutput(finalResult?.messages, step.outputPath, step.cwd ?? ctx.cwd)
1930
1395
  : undefined;
1931
1396
  const outputState: SubagentOutputState = finalResult?.outputState === "present"
1932
- || (finalResult as (RunPiStreamingResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput !== undefined
1397
+ || (finalResult as (RunChildSessionResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput !== undefined
1933
1398
  || Boolean(childWrittenOutput?.trim())
1934
1399
  ? "present"
1935
1400
  : resolvedOutput.savedPath
@@ -1939,6 +1404,7 @@ async function runSingleStepInner(
1939
1404
  ? buildTimeoutRecoverySummary({
1940
1405
  termination: "timed-out",
1941
1406
  evidence: finalMutationEvidence,
1407
+ requiredOutputMissing: finalRequiredOutputMissing,
1942
1408
  currentTool: finalResult?.currentTool,
1943
1409
  currentToolArgs: finalResult?.currentToolArgs,
1944
1410
  currentPath: finalResult?.currentPath,
@@ -1960,14 +1426,14 @@ async function runSingleStepInner(
1960
1426
  saveError: resolvedOutput.saveError,
1961
1427
  }));
1962
1428
  outputForSummary = finalizedOutput.displayOutput;
1963
- const acceptance = step.effectiveAcceptance && !finalResult?.stopped && !finalResult?.turnBudgetExceeded && !ctx.timeoutSignal?.aborted && !ctx.stopSignal?.aborted && !ctx.skipAcceptance?.()
1429
+ const acceptance = step.effectiveAcceptance && !finalResult?.stopped && !ctx.timeoutSignal?.aborted && !ctx.stopSignal?.aborted && !ctx.skipAcceptance?.()
1964
1430
  ? await evaluateAcceptance(omitUndefinedProperties({
1965
1431
  acceptance: step.effectiveAcceptance,
1966
1432
  output: outputForAcceptance,
1967
1433
  report: structuredAcceptanceReport as import("../../shared/types.ts").AcceptanceReport | undefined,
1968
1434
  reportError: structuredAcceptanceReportError,
1969
1435
  fileOutput: childWrittenOutput !== undefined && step.outputPath
1970
- ? { content: childWrittenOutput, path: step.outputPath, authoritative: step.outputMode === "file-only" }
1436
+ ? { content: childWrittenOutput, path: step.outputPath, authoritative: step.outputMode === "file-only", durable: resolvedOutput.savedPath !== undefined }
1971
1437
  : undefined,
1972
1438
  cwd: step.cwd ?? ctx.cwd,
1973
1439
  signal: combinedAbortSignal([ctx.timeoutSignal, ctx.stopSignal]),
@@ -1975,33 +1441,36 @@ async function runSingleStepInner(
1975
1441
  reportOptional: isAgentContractV1(step.agentContract),
1976
1442
  artifactsDir: ctx.artifactsDir,
1977
1443
  runId: ctx.id,
1444
+ watchdog: finalResult?.watchdog,
1978
1445
  }))
1979
1446
  : undefined;
1980
1447
  const stoppedAfterAcceptance = finalResult?.stopped === true || ctx.stopSignal?.aborted === true;
1981
1448
  const timedOutAfterAcceptance = !stoppedAfterAcceptance && (finalResult?.timedOut === true || ctx.timeoutSignal?.aborted === true);
1982
- const turnBudgetExceeded = finalResult?.turnBudgetExceeded === true;
1983
1449
  const effectiveAcceptance = step.effectiveAcceptance
1984
1450
  ? stoppedAfterAcceptance
1985
1451
  ? buildSkippedAcceptanceLedger(step.effectiveAcceptance, { id: "stopped", message: "Acceptance was not evaluated because the subagent was stopped." })
1986
1452
  : timedOutAfterAcceptance
1987
1453
  ? buildSkippedAcceptanceLedger(step.effectiveAcceptance, { id: "timeout", message: "Acceptance was not evaluated because the subagent timed out." })
1988
- : turnBudgetExceeded
1989
- ? buildSkippedAcceptanceLedger(step.effectiveAcceptance, { id: "turn-budget", message: "Acceptance was not evaluated because the subagent exceeded its turn budget." })
1990
- : acceptance
1454
+ : acceptance
1991
1455
  : undefined;
1992
1456
  const acceptanceFailure = effectiveAcceptance ? acceptanceFailureMessage(effectiveAcceptance) : undefined;
1993
- const acceptanceCanFailRun = acceptanceFailure && effectiveAcceptance?.explicit && (finalResult?.exitCode ?? 1) === 0 && !finalResult?.interrupted && !timedOutAfterAcceptance && !stoppedAfterAcceptance && !turnBudgetExceeded && !isAgentContractV1(step.agentContract);
1994
- const effectiveFinalExitCode = timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? 1 : acceptanceCanFailRun ? 1 : finalResult?.exitCode ?? 1;
1457
+ const acceptanceCanFailRun = acceptanceFailure && effectiveAcceptance?.explicit && (finalResult?.exitCode ?? 1) === 0 && !finalResult?.interrupted && !timedOutAfterAcceptance && !stoppedAfterAcceptance && !isAgentContractV1(step.agentContract);
1458
+ const effectiveFinalExitCode = timedOutAfterAcceptance || stoppedAfterAcceptance ? 1 : acceptanceCanFailRun ? 1 : finalResult?.exitCode ?? 1;
1995
1459
  const intercomDetachReceipt = finalResult?.finalOutput === INTERCOM_DETACH_RECEIPT;
1996
- const effectiveFinalError = stoppedAfterAcceptance
1460
+ const baseFinalError = stoppedAfterAcceptance
1997
1461
  ? ctx.stopMessage ?? "Subagent stopped by user."
1998
1462
  : timedOutAfterAcceptance
1999
1463
  ? finalResult?.error ?? ctx.timeoutMessage ?? "Subagent timed out."
2000
- : turnBudgetExceeded
2001
- ? finalResult?.error ?? (turnBudget ? turnBudgetExceededMessage(turnBudget, turnBudget.turnCount) : "Subagent exceeded turn budget.")
2002
- : acceptanceCanFailRun
1464
+ : acceptanceCanFailRun
2003
1465
  ? (finalResult?.error ? `${finalResult.error}\n${acceptanceFailure}` : acceptanceFailure)
2004
1466
  : finalResult?.error ?? (intercomDetachReceipt ? INTERCOM_DETACH_RECEIPT : undefined);
1467
+ const effectiveFinalError = formatChildFailureDiagnostic({
1468
+ error: baseFinalError,
1469
+ afterCompactionSettlement: effectiveFinalExitCode !== 0 ? finalResult?.afterCompactionSettlement : undefined,
1470
+ abortRecoveryDiagnostic: effectiveFinalExitCode !== 0 ? finalResult?.abortRecoveryDiagnostic : undefined,
1471
+ requiredOutput: effectiveFinalExitCode !== 0 ? finalResult?.effects?.settlementDiagnostic?.requiredOutput : undefined,
1472
+ });
1473
+ const usage = usageFromAttempts(modelAttempts);
2005
1474
 
2006
1475
  const artifactErrors = artifactPaths && ctx.artifactConfig?.enabled !== false
2007
1476
  ? persistStepArtifacts({
@@ -2021,12 +1490,13 @@ async function runSingleStepInner(
2021
1490
  model: finalResult?.model,
2022
1491
  attemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,
2023
1492
  modelAttempts,
1493
+ usage,
2024
1494
  error: effectiveFinalError,
2025
1495
  acceptance: effectiveAcceptance,
2026
1496
  ...(capabilityAudit ? { capabilityCeiling: capabilityAudit.ceiling, capabilityAudit } : {}),
2027
1497
  launchContractDigest: actualLaunchContractDigest,
2028
1498
  launchResolvedExtensions,
2029
- ...((finalResult as (RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }) | undefined)?.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: (finalResult as RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }).runtimeAcknowledgedExtensions } : {}),
1499
+ ...((finalResult as (RunChildSessionResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }) | undefined)?.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: (finalResult as RunChildSessionResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }).runtimeAcknowledgedExtensions } : {}),
2030
1500
  ...(transcriptWriter ? { transcriptPath: artifactPaths.transcriptPath } : {}),
2031
1501
  transcriptError: transcriptWriter?.getError(),
2032
1502
  skills: step.skills,
@@ -2037,6 +1507,7 @@ async function runSingleStepInner(
2037
1507
 
2038
1508
  const result: StepResult & { completionGuardTriggered?: boolean } = omitUndefinedProperties({
2039
1509
  agent: step.agent,
1510
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
2040
1511
  context: step.context,
2041
1512
  ...(step.agentContract ? { agentContract: step.agentContract } : {}),
2042
1513
  launchContractDigest: actualLaunchContractDigest,
@@ -2044,41 +1515,36 @@ async function runSingleStepInner(
2044
1515
  outputState,
2045
1516
  exitCode: effectiveFinalExitCode,
2046
1517
  error: effectiveFinalError,
2047
- protocolError: finalResult?.protocolError,
2048
1518
  sessionFile: step.sessionFile,
2049
1519
  intercomTarget: ctx.childIntercomTarget,
2050
1520
  model: finalResult?.model,
1521
+ thinking: resolveEffectiveThinking(finalResult?.model, step.thinking),
2051
1522
  attemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,
2052
1523
  modelAttempts,
2053
1524
  contextOverflow: contextOverflow || undefined,
2054
1525
  totalCost: costSummaryFromAttempts(modelAttempts),
1526
+ usage,
2055
1527
  artifactPaths,
2056
- outputSaveError: artifactErrors.outputSaveError,
1528
+ outputSaveError: [resolvedOutput.saveError, artifactErrors.outputSaveError].filter(Boolean).join("\n") || undefined,
2057
1529
  metadataSaveError: artifactErrors.metadataSaveError,
2058
1530
  transcriptPath: transcriptWriter ? artifactPaths?.transcriptPath : undefined,
2059
1531
  transcriptError: transcriptWriter?.getError(),
2060
- interrupted: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? false : finalResult?.interrupted,
1532
+ interrupted: timedOutAfterAcceptance || stoppedAfterAcceptance ? false : finalResult?.interrupted,
2061
1533
  timedOut: timedOutAfterAcceptance ? true : finalResult?.timedOut,
2062
1534
  stopped: stoppedAfterAcceptance ? true : finalResult?.stopped,
2063
- processSignal: finalResult?.processSignal,
2064
1535
  timeoutRecovery,
2065
- turnBudget,
2066
- turnBudgetExceeded: turnBudgetExceeded || undefined,
2067
- wrapUpRequested: finalResult?.wrapUpRequested || turnBudget?.outcome === "wrap-up-requested" || turnBudget?.outcome === "termination-deferred" || turnBudgetExceeded || undefined,
2068
1536
  toolBudget,
2069
1537
  toolBudgetBlocked: toolBudgetBlocked || undefined,
2070
1538
  completionGuardTriggered: completionGuardTriggeredFinal,
2071
- ...((finalResult as (RunPiStreamingResult & { effects?: import("../../shared/types.ts").EffectsProjection }) | undefined)?.effects ? { effects: (finalResult as RunPiStreamingResult & { effects?: import("../../shared/types.ts").EffectsProjection }).effects } : {}),
2072
- structuredOutput: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? undefined : (finalResult as (RunPiStreamingResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput,
2073
- structuredOutputPath: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? undefined : effectiveStructuredOutput?.outputPath,
2074
- structuredOutputSchemaPath: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? undefined : effectiveStructuredOutput?.schemaPath,
1539
+ ...((finalResult as (RunChildSessionResult & { effects?: import("../../shared/types.ts").EffectsProjection }) | undefined)?.effects ? { effects: (finalResult as RunChildSessionResult & { effects?: import("../../shared/types.ts").EffectsProjection }).effects } : {}),
1540
+ structuredOutput: timedOutAfterAcceptance || stoppedAfterAcceptance ? undefined : (finalResult as (RunChildSessionResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput,
1541
+ structuredOutputPath: timedOutAfterAcceptance || stoppedAfterAcceptance ? undefined : effectiveStructuredOutput?.outputPath,
1542
+ structuredOutputSchemaPath: timedOutAfterAcceptance || stoppedAfterAcceptance ? undefined : effectiveStructuredOutput?.schemaPath,
2075
1543
  acceptance: effectiveAcceptance,
2076
1544
  watchdog: finalResult?.watchdog,
2077
1545
  ...(capabilityAudit ? { capabilityCeiling: capabilityAudit.ceiling, capabilityAudit } : {}),
2078
1546
  launchResolvedExtensions,
2079
- ...((finalResult as (RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }) | undefined)?.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: (finalResult as RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }).runtimeAcknowledgedExtensions } : {}),
2080
- writerProcesses,
2081
- writerAttemptCount,
1547
+ ...((finalResult as (RunChildSessionResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }) | undefined)?.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: (finalResult as RunChildSessionResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }).runtimeAcknowledgedExtensions } : {}),
2082
1548
  });
2083
1549
  return isAgentContractV1(step.agentContract) ? attachContractProjections(result as unknown as import("../../shared/types.ts").SingleResult) as unknown as typeof result : result;
2084
1550
  }
@@ -2098,13 +1564,7 @@ type RunnerStatusStep = NonNullable<AsyncStatus["steps"]>[number] & {
2098
1564
 
2099
1565
  function externalRunnerStatus(runner: SubagentStep["runner"]): ExternalCliRunnerStatus | ExternalJobRunnerStatus | undefined {
2100
1566
  if (runner?.type === "external-cli") {
2101
- return {
2102
- type: "external-cli",
2103
- command: runner.command,
2104
- args: runner.args ?? [],
2105
- promptDelivery: runner.promptDelivery ?? "stdin",
2106
- capabilities: { stop: true, steer: false, resume: false, structuredOutput: false, toolEvents: false },
2107
- };
1567
+ return resolveExternalCliRunnerStatus(runner);
2108
1568
  }
2109
1569
  if (runner?.type === "external-job") {
2110
1570
  return {
@@ -2151,6 +1611,13 @@ function requiredStatusStep(statusPayload: RunnerStatusPayload, index: number):
2151
1611
  return step;
2152
1612
  }
2153
1613
 
1614
+ function setStatusWorktreeReference(statusStep: RunnerStatusStep, worktree: WorktreeSetup["worktrees"][number]): void {
1615
+ statusStep.worktreePath = worktree.path;
1616
+ statusStep.branch = worktree.branch;
1617
+ if (worktree.provider) statusStep.provider = worktree.provider;
1618
+ if (worktree.naming) statusStep.naming = worktree.naming;
1619
+ }
1620
+
2154
1621
  function markParallelGroupSetupFailure(input: {
2155
1622
  statusPayload: RunnerStatusPayload;
2156
1623
  results: StepResult[];
@@ -2229,6 +1696,18 @@ function markParallelGroupRunning(input: {
2229
1696
  }));
2230
1697
  }
2231
1698
 
1699
+ function bindWorktreeCwd(step: SubagentStep, worktreeCwd: string): SubagentStep {
1700
+ const bind = <T extends string | null | undefined>(value: T): T => value === null || value === undefined ? value : value.replaceAll(WORKTREE_AGENT_CWD_PLACEHOLDER, worktreeCwd) as T;
1701
+ return {
1702
+ ...step,
1703
+ task: bind(step.task) ?? step.task,
1704
+ ...(step.systemPrompt !== undefined ? { systemPrompt: bind(step.systemPrompt) } : {}),
1705
+ ...(step.outputPath !== undefined ? { outputPath: bind(step.outputPath) } : {}),
1706
+ ...(step.launchBindingTask !== undefined ? { launchBindingTask: bind(step.launchBindingTask) } : {}),
1707
+ ...(step.requestedCwd !== undefined ? { requestedCwd: bind(step.requestedCwd) } : {}),
1708
+ };
1709
+ }
1710
+
2232
1711
  function prepareParallelTaskRun(
2233
1712
  task: SubagentStep,
2234
1713
  cwd: string,
@@ -2237,8 +1716,9 @@ function prepareParallelTaskRun(
2237
1716
  ): { taskForRun: SubagentStep; taskCwd: string } {
2238
1717
  if (!worktreeSetup) return { taskForRun: task, taskCwd: cwd };
2239
1718
  const { cwd: _taskCwd, ...taskForRun } = task;
1719
+ const boundTask = bindWorktreeCwd(taskForRun, worktreeSetup.worktrees[taskIndex]!.agentCwd);
2240
1720
  return {
2241
- taskForRun,
1721
+ taskForRun: boundTask,
2242
1722
  taskCwd: worktreeSetup.worktrees[taskIndex]!.agentCwd,
2243
1723
  };
2244
1724
  }
@@ -2279,6 +1759,25 @@ function resolveAsyncStepTranscriptPath(input: {
2279
1759
 
2280
1760
  type SingleStepResult = Awaited<ReturnType<typeof runSingleStep>>;
2281
1761
 
1762
+ function missingRequiredOutputAfterUsefulMutation(result: SingleStepResult): boolean {
1763
+ const effects = result.effects;
1764
+ return effects?.settlementDiagnostic?.requiredOutput?.missing === true
1765
+ && (effects.settlementDiagnostic.mutation.attempted || effects.fileMutation?.attempted === true || Boolean(effects.fileMutation?.evidence?.changedFiles.length));
1766
+ }
1767
+
1768
+ function partialExecutionWithUsefulMutation(result: SingleStepResult): boolean {
1769
+ const fileMutation = result.effects?.fileMutation;
1770
+ return result.execution?.status === "partial" && (fileMutation?.attempted === true || Boolean(fileMutation?.evidence?.changedFiles.length));
1771
+ }
1772
+
1773
+ function partialEvidenceResult(result: SingleStepResult): boolean {
1774
+ return missingRequiredOutputAfterUsefulMutation(result) || partialExecutionWithUsefulMutation(result);
1775
+ }
1776
+
1777
+ function concreteFailureResult(result: SingleStepResult): boolean {
1778
+ return result.success === false && !partialEvidenceResult(result);
1779
+ }
1780
+
2282
1781
  function combinedAbortSignal(signals: Array<AbortSignal | undefined>): AbortSignal | undefined {
2283
1782
  const activeSignals = signals.filter((signal): signal is AbortSignal => Boolean(signal));
2284
1783
  if (activeSignals.length === 0) return undefined;
@@ -2339,7 +1838,7 @@ async function runSingleStepWithTimeout(
2339
1838
 
2340
1839
  async function runSubagent(
2341
1840
  config: SubagentRunConfig,
2342
- onWriterProcess?: (writer: { state: "none" | "spawning" } | { state: "running"; pid: number }) => void,
1841
+ childSessions: ChildSessionFactory,
2343
1842
  ): Promise<void> {
2344
1843
  const { id, steps, resultPath, cwd, placeholder, taskIndex, totalTasks, maxOutput, artifactsDir, artifactConfig } =
2345
1844
  config;
@@ -2350,6 +1849,8 @@ async function runSubagent(
2350
1849
  const overallStartTime = Date.now();
2351
1850
  const shareEnabled = config.share === true;
2352
1851
  const asyncDir = config.asyncDir;
1852
+ const handoffWorkflowKey = config.workflowKey;
1853
+ const handoffChildRunId = handoffWorkflowKey ? id : undefined;
2353
1854
  const statusPath = path.join(asyncDir, "status.json");
2354
1855
  const eventsPath = path.join(asyncDir, "events.jsonl");
2355
1856
  const logPath = path.join(asyncDir, `subagent-log-${id}.md`);
@@ -2357,17 +1858,17 @@ async function runSubagent(
2357
1858
  const activeChildInterrupts = new Map<number, () => void>();
2358
1859
  const activeChildTimeouts = new Map<number, () => void>();
2359
1860
  const activeChildStops = new Map<number, () => void>();
1861
+ const activeChildSteers = new Map<number, StepSteerHandler>();
1862
+ /** Steers routed to a running step before its session was created. */
1863
+ const queuedStepSteers = new Map<number, SteerRequest[]>();
2360
1864
  const childStopRequests = new Map<number, { childId: string; requestedAt: number }>();
2361
- const activeChildTurnBudgetAborts = new Map<number, (message: string, state?: TurnBudgetState) => void>();
2362
1865
  const pendingStepSteers: SteerRequest[] = [];
2363
- const steeringCapabilities = new Map<number, SteerCapability>();
2364
1866
  let interrupted = false;
2365
1867
  let currentActivityState: ActivityState | undefined;
2366
1868
  let activityTimer: NodeJS.Timeout | undefined;
2367
1869
  let timeoutTimer: NodeJS.Timeout | undefined;
2368
1870
  let timedOut = false;
2369
1871
  let stopped = false;
2370
- let turnBudgetExceeded = false;
2371
1872
  let usageBudgetExceeded = false;
2372
1873
  const timeoutMessage = config.timeoutMs !== undefined ? `Subagent timed out after ${config.timeoutMs}ms.` : undefined;
2373
1874
  const stopMessage = "Subagent stopped by user.";
@@ -2388,8 +1889,11 @@ async function runSubagent(
2388
1889
  for (const task of step.parallel) {
2389
1890
  const taskFlatIndex = flatStepCount;
2390
1891
  const transcriptPath = resolveAsyncStepTranscriptPath(omitUndefinedProperties({ artifactsDir, artifactConfig, runId: id, agent: task.agent, flatIndex: taskFlatIndex, flatStepCount: initialFlatStepCount }));
1892
+ const taskSessionName = task.sessionName ?? deriveChildSessionName({ agent: task.agent, task: task.task, label: task.label });
2391
1893
  initialStatusSteps.push(omitUndefinedProperties({
2392
1894
  agent: task.agent,
1895
+ ...(task.lane ? { lane: task.lane } : config.lane ? { lane: config.lane } : {}),
1896
+ ...(taskSessionName ? { sessionName: taskSessionName } : {}),
2393
1897
  ...(externalRunnerStatus(task.runner) ? { runner: externalRunnerStatus(task.runner) } : {}),
2394
1898
  ...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),
2395
1899
  ...(task.context ? { context: task.context } : {}),
@@ -2408,6 +1912,7 @@ async function runSubagent(
2408
1912
  ...(transcriptPath ? { transcriptPath } : {}),
2409
1913
  skills: task.skills,
2410
1914
  model: task.model,
1915
+ ...(task.contextLimit !== undefined ? { contextLimit: task.contextLimit } : {}),
2411
1916
  thinking: task.thinking,
2412
1917
  attemptedModels: task.modelCandidates && task.modelCandidates.length > 0 ? task.modelCandidates : task.model ? [task.model] : undefined,
2413
1918
  recentTools: [],
@@ -2425,6 +1930,7 @@ async function runSubagent(
2425
1930
  label: step.label ?? step.parallel.label ?? `Dynamic fanout (${step.collect.as})`,
2426
1931
  outputName: step.collect.as,
2427
1932
  structured: Boolean(step.collect.outputSchema),
1933
+ ...(step.parallel.contextLimit !== undefined ? { contextLimit: step.parallel.contextLimit } : {}),
2428
1934
  ...(step.agentContract ? { agentContract: step.agentContract } : {}),
2429
1935
  ...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
2430
1936
  ...(step.thinkingCeiling ? { thinkingCeiling: step.thinkingCeiling } : {}),
@@ -2437,8 +1943,11 @@ async function runSubagent(
2437
1943
  } else {
2438
1944
  const stepFlatIndex = flatStepCount;
2439
1945
  const transcriptPath = resolveAsyncStepTranscriptPath(omitUndefinedProperties({ artifactsDir, artifactConfig, runId: id, agent: step.agent, flatIndex: stepFlatIndex, flatStepCount: initialFlatStepCount }));
1946
+ const stepSessionName = step.sessionName ?? deriveChildSessionName({ agent: step.agent, task: step.task, label: step.label });
2440
1947
  initialStatusSteps.push(omitUndefinedProperties({
2441
1948
  agent: step.agent,
1949
+ ...(step.lane ? { lane: step.lane } : config.lane ? { lane: config.lane } : {}),
1950
+ ...(stepSessionName ? { sessionName: stepSessionName } : {}),
2442
1951
  ...(externalRunnerStatus(step.runner) ? { runner: externalRunnerStatus(step.runner) } : {}),
2443
1952
  ...(statusStepDescription(step.task) ? { description: statusStepDescription(step.task) } : {}),
2444
1953
  ...(step.context ? { context: step.context } : {}),
@@ -2457,6 +1966,7 @@ async function runSubagent(
2457
1966
  ...(transcriptPath ? { transcriptPath } : {}),
2458
1967
  skills: step.skills,
2459
1968
  model: step.model,
1969
+ ...(step.contextLimit !== undefined ? { contextLimit: step.contextLimit } : {}),
2460
1970
  thinking: step.thinking,
2461
1971
  attemptedModels: step.modelCandidates && step.modelCandidates.length > 0 ? step.modelCandidates : step.model ? [step.model] : undefined,
2462
1972
  recentTools: [],
@@ -2500,7 +2010,6 @@ async function runSubagent(
2500
2010
  lastUpdate: overallStartTime,
2501
2011
  ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),
2502
2012
  ...(config.deadlineAt !== undefined ? { deadlineAt: config.deadlineAt } : {}),
2503
- ...(config.turnBudget ? { turnBudget: initialTurnBudgetState(config.turnBudget) } : {}),
2504
2013
  ...(config.toolBudget ? { toolBudget: initialToolBudgetState(config.toolBudget) } : {}),
2505
2014
  ...(config.usageBudget ? { usageBudget: usageBudgetState(config.usageBudget, undefined) } : {}),
2506
2015
  pid: process.pid,
@@ -2515,6 +2024,7 @@ async function runSubagent(
2515
2024
  ...(config.runFanoutBudget ? { runFanoutBudget: getRunFanoutBudgetSnapshot(config.runFanoutBudget) } : {}),
2516
2025
  ...(config.parentWorkflowRunId ? { parentWorkflowRunId: config.parentWorkflowRunId } : {}),
2517
2026
  ...(config.workflowKey ? { workflowKey: config.workflowKey } : {}),
2027
+ ...(config.lane ? { lane: config.lane } : {}),
2518
2028
  ...(config.runnerProcessInstanceId ? { processTerminal: { version: 1 as const, state: "pending" as const, runId: id, runnerProcessInstanceId: config.runnerProcessInstanceId } } : {}),
2519
2029
  steps: initialStatusSteps,
2520
2030
  artifactsDir,
@@ -2632,6 +2142,7 @@ async function runSubagent(
2632
2142
  const statusResultSummary = (state: AsyncStatus["state"]): string => {
2633
2143
  if (statusPayload.error) return statusPayload.error;
2634
2144
  if (state === "paused") return "Paused after interrupt. Waiting for explicit next action.";
2145
+ if (state === "partial") return "Subagent needs attention after partial work.";
2635
2146
  if (state === "stopped") return stopMessage;
2636
2147
  if (state === "rejected") return "Subagent rejected.";
2637
2148
  return state === "complete" ? "Subagent completed." : "Subagent failed.";
@@ -2640,12 +2151,13 @@ async function runSubagent(
2640
2151
  if (step.status === "complete" || step.status === "completed") return true;
2641
2152
  if (step.status === "failed" || step.status === "stopped" || step.status === "rejected") return false;
2642
2153
  if (state === "complete") return true;
2643
- if (state === "failed" || state === "stopped" || state === "rejected") return false;
2154
+ if (state === "failed" || state === "partial" || state === "stopped" || state === "rejected") return false;
2644
2155
  return undefined;
2645
2156
  };
2646
2157
  const writeRecoverableStatusResult = (): void => {
2647
2158
  const state = statusResultState();
2648
2159
  if (!state || finalResultCommitted || !config.sessionId) return;
2160
+ if ((state as string) === "complete") return;
2649
2161
  const now = statusPayload.endedAt ?? statusPayload.lastUpdate ?? Date.now();
2650
2162
  const summary = statusResultSummary(state);
2651
2163
  runPersistence.write(resultPath, omitUndefinedProperties({
@@ -2657,17 +2169,20 @@ async function runSubagent(
2657
2169
  success: state === "complete",
2658
2170
  state,
2659
2171
  summary,
2660
- error: state === "failed" || state === "stopped" || state === "rejected" ? summary : undefined,
2172
+ error: state === "failed" || state === "partial" || state === "stopped" || state === "rejected" ? summary : undefined,
2661
2173
  stopped: state === "stopped" ? true : undefined,
2662
2174
  results: statusPayload.steps.map((step) => omitUndefinedProperties({
2663
2175
  agent: step.agent,
2176
+ ...(step.sessionName ? { sessionName: step.sessionName } : {}),
2664
2177
  output: step.status === "complete" || step.status === "completed" ? "" : step.error ?? summary,
2665
2178
  error: step.error,
2666
2179
  success: statusResultSuccess(state, step),
2667
2180
  sessionFile: step.sessionFile,
2668
2181
  model: step.model,
2182
+ thinking: step.thinking,
2669
2183
  attemptedModels: step.attemptedModels,
2670
2184
  modelAttempts: step.modelAttempts,
2185
+ usage: usageFromAttempts(step.modelAttempts),
2671
2186
  contextOverflow: step.contextOverflow,
2672
2187
  })),
2673
2188
  exitCode: state === "complete" || state === "paused" ? 0 : 1,
@@ -2762,7 +2277,7 @@ async function runSubagent(
2762
2277
  };
2763
2278
  const childStopResult = (index: number, agent: string, context?: "fresh" | "fork"): SingleStepResult => {
2764
2279
  markChildStopped(index);
2765
- return stoppedStepResult(agent, context);
2280
+ return stoppedStepResult(agent, context, requiredStatusStep(statusPayload, index).sessionName);
2766
2281
  };
2767
2282
  const stopChildStep = (request: StopRequest): void => {
2768
2283
  if (request.targetIndex === undefined) {
@@ -2805,12 +2320,15 @@ async function runSubagent(
2805
2320
  activeChildStops.set(flatIndex, stop);
2806
2321
  if (stopped || childStopRequests.has(flatIndex)) stop();
2807
2322
  };
2808
- const registerStepTurnBudgetAbort = (flatIndex: number, abort: ((message: string, state?: TurnBudgetState) => void) | undefined): void => {
2809
- if (!abort) {
2810
- activeChildTurnBudgetAborts.delete(flatIndex);
2323
+ const registerStepSteer = (flatIndex: number, steer: StepSteerHandler | undefined): void => {
2324
+ if (!steer) {
2325
+ activeChildSteers.delete(flatIndex);
2811
2326
  return;
2812
2327
  }
2813
- activeChildTurnBudgetAborts.set(flatIndex, abort);
2328
+ activeChildSteers.set(flatIndex, steer);
2329
+ const queued = queuedStepSteers.get(flatIndex);
2330
+ queuedStepSteers.delete(flatIndex);
2331
+ for (const request of queued ?? []) steerLiveChild(flatIndex, request);
2814
2332
  };
2815
2333
  const interruptActiveChildren = (): void => {
2816
2334
  for (const interrupt of [...activeChildInterrupts.values()]) interrupt();
@@ -2921,23 +2439,26 @@ async function runSubagent(
2921
2439
  }
2922
2440
  }
2923
2441
  };
2924
- const pausedStepResult = (agent: string, context?: "fresh" | "fork"): SingleStepResult => omitUndefinedProperties({
2442
+ const pausedStepResult = (agent: string, context?: "fresh" | "fork", sessionName?: string): SingleStepResult => omitUndefinedProperties({
2925
2443
  agent,
2444
+ sessionName,
2926
2445
  context,
2927
2446
  output: "Paused after interrupt. Waiting for explicit next action.",
2928
2447
  exitCode: 0,
2929
2448
  interrupted: true,
2930
2449
  });
2931
- const timedOutStepResult = (agent: string, context?: "fresh" | "fork"): SingleStepResult => omitUndefinedProperties({
2450
+ const timedOutStepResult = (agent: string, context?: "fresh" | "fork", sessionName?: string): SingleStepResult => omitUndefinedProperties({
2932
2451
  agent,
2452
+ sessionName,
2933
2453
  context,
2934
2454
  output: timeoutMessage ?? "Subagent timed out.",
2935
2455
  error: timeoutMessage ?? "Subagent timed out.",
2936
2456
  exitCode: 1,
2937
2457
  timedOut: true,
2938
2458
  });
2939
- const stoppedStepResult = (agent: string, context?: "fresh" | "fork"): SingleStepResult => omitUndefinedProperties({
2459
+ const stoppedStepResult = (agent: string, context?: "fresh" | "fork", sessionName?: string): SingleStepResult => omitUndefinedProperties({
2940
2460
  agent,
2461
+ sessionName,
2941
2462
  context,
2942
2463
  output: stopMessage,
2943
2464
  error: stopMessage,
@@ -3261,22 +2782,15 @@ async function runSubagent(
3261
2782
  if (!step) return { index, state: "failed" as const, reason: "child index out of range" };
3262
2783
  if (step.status === "pending") return { index, state: "scheduled" as const };
3263
2784
  if (step.status !== "running") return { index, state: "failed" as const, reason: `child is ${step.status}` };
3264
- if (steeringCapabilities.get(index)?.supported === false) return { index, state: "failed" as const, reason: "child Pi session does not support steering" };
3265
2785
  return { index, state: "routed" as const };
3266
2786
  });
3267
2787
  recordSteeringLifecycle(request, targetStates);
3268
2788
  emitSteeringEvent("subagent.steer.requested", request, undefined, { targets: targetStates });
3269
2789
  for (const target of targetStates) {
3270
2790
  if (target.state === "routed") {
3271
- try {
3272
- enqueueStepSteer(asyncDir, target.index, request);
3273
- updateSteeringLifecycleTarget(request.id, target.index, "routed", now);
3274
- emitSteeringEvent("subagent.steer.routed", request, target.index);
3275
- } catch (error) {
3276
- markSteeringAttention(target.index);
3277
- updateSteeringLifecycleTarget(request.id, target.index, "failed", now, { reason: error instanceof Error ? error.message : String(error) });
3278
- emitSteeringEvent("subagent.steer.failed", request, target.index, { reason: error instanceof Error ? error.message : String(error) });
3279
- }
2791
+ updateSteeringLifecycleTarget(request.id, target.index, "routed", now);
2792
+ emitSteeringEvent("subagent.steer.routed", request, target.index);
2793
+ steerLiveChild(target.index, request);
3280
2794
  } else if (target.state === "failed") {
3281
2795
  markSteeringAttention(target.index);
3282
2796
  emitSteeringEvent("subagent.steer.failed", request, target.index, { reason: target.reason });
@@ -3288,27 +2802,42 @@ async function runSubagent(
3288
2802
  statusPayload.lastUpdate = now;
3289
2803
  writeStatusPayload();
3290
2804
  };
3291
- const consumeSteerAck = (ack: SteerAck): void => {
2805
+ /** Record the outcome of handing a routed steer to the live child session. */
2806
+ const applySteerDelivery = (requestId: string, index: number, delivery: { state: "delivered" | "queued" | "failed"; message: string }): void => {
3292
2807
  const lifecycle = steeringStatus(statusPayload);
3293
- const request = lifecycle.recent.find((candidate) => candidate.id === ack.requestId);
3294
- if (!request || !request.targets.some((target) => target.index === ack.index)) return;
3295
- const late = fs.existsSync(steeringMarkerPath(ack.requestId));
2808
+ const request = lifecycle.recent.find((candidate) => candidate.id === requestId);
2809
+ if (!request || !request.targets.some((target) => target.index === index)) return;
2810
+ const late = fs.existsSync(steeringMarkerPath(requestId));
3296
2811
  const now = Date.now();
3297
- if (ack.state === "delivered") {
3298
- updateSteeringLifecycleTarget(ack.requestId, ack.index, late ? "late" : "delivered", now, omitUndefinedProperties({ reason: late ? "acknowledged after recovery commit" : undefined }));
3299
- emitSteeringEvent("subagent.steer.delivered", { type: "steer", id: ack.requestId, ts: now, message: ack.message }, ack.index, { late, deliveryStatus: "delivered", message: ack.message });
3300
- } else if (ack.state === "queued") {
3301
- updateSteeringLifecycleTarget(ack.requestId, ack.index, "queued", now);
3302
- emitSteeringEvent("subagent.steer.queued", { type: "steer", id: ack.requestId, ts: now, message: ack.message }, ack.index, { deliveryStatus: "queued", message: ack.message });
2812
+ if (delivery.state === "delivered") {
2813
+ updateSteeringLifecycleTarget(requestId, index, late ? "late" : "delivered", now, omitUndefinedProperties({ reason: late ? "acknowledged after recovery commit" : undefined }));
2814
+ emitSteeringEvent("subagent.steer.delivered", { type: "steer", id: requestId, ts: now, message: delivery.message }, index, { late, deliveryStatus: "delivered", message: delivery.message });
2815
+ } else if (delivery.state === "queued") {
2816
+ updateSteeringLifecycleTarget(requestId, index, "queued", now);
2817
+ emitSteeringEvent("subagent.steer.queued", { type: "steer", id: requestId, ts: now, message: delivery.message }, index, { deliveryStatus: "queued", message: delivery.message });
3303
2818
  } else {
3304
- markSteeringAttention(ack.index);
3305
- updateSteeringLifecycleTarget(ack.requestId, ack.index, "failed", now, { reason: ack.message });
3306
- emitSteeringEvent("subagent.steer.failed", { type: "steer", id: ack.requestId, ts: now, message: ack.message }, ack.index, { reason: ack.message });
2819
+ markSteeringAttention(index);
2820
+ updateSteeringLifecycleTarget(requestId, index, "failed", now, { reason: delivery.message });
2821
+ emitSteeringEvent("subagent.steer.failed", { type: "steer", id: requestId, ts: now, message: delivery.message }, index, { reason: delivery.message });
3307
2822
  }
3308
- emitTerminalSteeringNotice(ack.requestId, `Steering failed for run ${id}: ${ack.message}`);
2823
+ emitTerminalSteeringNotice(requestId, `Steering failed for run ${id}: ${delivery.message}`);
3309
2824
  statusPayload.lastUpdate = now;
3310
2825
  writeStatusPayload();
3311
2826
  };
2827
+ /** Hand a routed steer to the step's live session, or hold it until the session exists. */
2828
+ const steerLiveChild = (index: number, request: SteerRequest): void => {
2829
+ const steer = activeChildSteers.get(index);
2830
+ if (!steer) {
2831
+ const queued = queuedStepSteers.get(index) ?? [];
2832
+ queued.push(request);
2833
+ queuedStepSteers.set(index, queued);
2834
+ return;
2835
+ }
2836
+ void steer(request).then(
2837
+ (delivery) => applySteerDelivery(request.id, index, delivery),
2838
+ (error) => applySteerDelivery(request.id, index, { state: "failed", message: error instanceof Error ? error.message : String(error) }),
2839
+ );
2840
+ };
3312
2841
  const flushPendingStepSteers = (flatIndex: number): void => {
3313
2842
  const remaining: SteerRequest[] = [];
3314
2843
  for (const request of pendingStepSteers.splice(0)) {
@@ -3318,74 +2847,15 @@ async function runSubagent(
3318
2847
  }
3319
2848
  pendingStepSteers.push(...remaining);
3320
2849
  };
3321
- const updateStepModel = (flatIndex: number, model: string | undefined, thinking: string | undefined, now = Date.now()): void => {
2850
+ const updateStepModel = (flatIndex: number, model: string | undefined, thinking: string | undefined, contextLimit?: number, now = Date.now()): void => {
3322
2851
  const step = statusPayload.steps[flatIndex];
3323
2852
  if (!step) return;
3324
2853
  setOptionalProperty(step, "model", model);
3325
2854
  setOptionalProperty(step, "thinking", thinking);
2855
+ setOptionalProperty(step, "contextLimit", contextLimit);
3326
2856
  statusPayload.lastUpdate = now;
3327
2857
  writeStatusPayload();
3328
2858
  };
3329
- const updateStepTurnBudget = (
3330
- flatIndex: number,
3331
- turnCount: number,
3332
- now: number,
3333
- terminalAssistantStop: boolean,
3334
- toolWorkActiveOrStarting: boolean,
3335
- ): void => {
3336
- const budget = config.turnBudget;
3337
- const step = statusPayload.steps[flatIndex];
3338
- if (!budget || !step || timedOut || stopped || turnBudgetExceeded || step.turnBudgetExceeded) return;
3339
- if (turnCount < budget.maxTurns) {
3340
- const state: TurnBudgetState = { ...budget, outcome: "within-budget", turnCount };
3341
- step.turnBudget = state;
3342
- statusPayload.turnBudget = state;
3343
- return;
3344
- }
3345
- if (!step.wrapUpRequested) {
3346
- step.wrapUpRequested = true;
3347
- statusPayload.wrapUpRequested = true;
3348
- appendRecentStepOutput(step, [turnBudgetSoftNote(budget, turnCount)]);
3349
- }
3350
- const decision = turnBudgetDecision(budget, turnCount, terminalAssistantStop, toolWorkActiveOrStarting);
3351
- if (decision === "defer") {
3352
- const firstDeferredTurn = step.turnBudget?.terminationDeferredAtTurn;
3353
- const deferredState = turnBudgetDeferredState(budget, turnCount, firstDeferredTurn);
3354
- step.turnBudget = deferredState;
3355
- statusPayload.turnBudget = deferredState;
3356
- if (firstDeferredTurn === undefined) {
3357
- appendJsonl(eventsPath, JSON.stringify({
3358
- type: "subagent.step.turn_budget_deferred",
3359
- ts: now,
3360
- runId: id,
3361
- stepIndex: flatIndex,
3362
- agent: step.agent,
3363
- turnCount,
3364
- maxTurns: budget.maxTurns,
3365
- graceTurns: budget.graceTurns,
3366
- }));
3367
- }
3368
- return;
3369
- }
3370
- const state = turnBudgetState(budget, turnCount, false);
3371
- step.turnBudget = state;
3372
- statusPayload.turnBudget = state;
3373
- if (decision !== "abort") return;
3374
- const exceededState = turnBudgetState(budget, turnCount, true);
3375
- const message = turnBudgetExceededMessage(budget, turnCount);
3376
- step.turnBudget = exceededState;
3377
- step.turnBudgetExceeded = true;
3378
- step.wrapUpRequested = true;
3379
- step.error = message;
3380
- turnBudgetExceeded = true;
3381
- statusPayload.turnBudget = exceededState;
3382
- statusPayload.turnBudgetExceeded = true;
3383
- statusPayload.wrapUpRequested = true;
3384
- statusPayload.error = message;
3385
- statusPayload.lastUpdate = now;
3386
- 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 }));
3387
- activeChildTurnBudgetAborts.get(flatIndex)?.(message, exceededState);
3388
- };
3389
2859
  const updateStepFromChildEvent = (flatIndex: number, event: ChildEvent): void => {
3390
2860
  const step = statusPayload.steps[flatIndex];
3391
2861
  if (!step) return;
@@ -3407,8 +2877,17 @@ async function runSubagent(
3407
2877
  writeStatusPayload(false);
3408
2878
  return;
3409
2879
  }
2880
+ if (event.type === "message_end") {
2881
+ const next = applyChildWatchdogMessage(step.watchdog, event.message, now);
2882
+ if (next) step.watchdog = next;
2883
+ if (next && (event.message as { role?: unknown } | undefined)?.role === "custom") {
2884
+ statusPayload.lastUpdate = now;
2885
+ writeStatusPayload(false);
2886
+ return;
2887
+ }
2888
+ }
3410
2889
  if (event.type === "tool_execution_start" && event.toolName) {
3411
- const mutates = isMutatingTool(event.toolName, event.args);
2890
+ const mutates = isMutatingTool(event.toolName, event.args, flatSteps[flatIndex]?.mutationTools);
3412
2891
  const currentPath = resolveCurrentPath(event.toolName, event.args);
3413
2892
  const argsPreview = extractToolArgsPreview(event.args ?? {});
3414
2893
  const blocksSupervisor = isBlockingSupervisorTool(event.toolName, event.args);
@@ -3442,6 +2921,7 @@ async function runSubagent(
3442
2921
  tokens: step.tokens?.total,
3443
2922
  toolCount: step.toolCount,
3444
2923
  currentTool: step.currentTool,
2924
+ toolCallId: event.toolCallId,
3445
2925
  currentToolDurationMs: 0,
3446
2926
  currentPath: step.currentPath,
3447
2927
  })));
@@ -3516,22 +2996,16 @@ async function runSubagent(
3516
2996
  if (usage) {
3517
2997
  const input = usage.input ?? usage.inputTokens ?? 0;
3518
2998
  const output = usage.output ?? usage.outputTokens ?? 0;
2999
+ const window = input + (usage.cacheRead ?? usage.cacheReadTokens ?? 0);
3519
3000
  const previousInput = step.tokens?.input ?? 0;
3520
3001
  const previousOutput = step.tokens?.output ?? 0;
3521
- step.tokens = { input: previousInput + input, output: previousOutput + output, total: previousInput + previousOutput + input + output };
3002
+ step.tokens = { input: previousInput + input, output: previousOutput + output, total: previousInput + previousOutput + input + output, window, windowPeak: Math.max(step.tokens?.windowPeak ?? 0, window) };
3522
3003
  const totalInput = statusPayload.totalTokens?.input ?? 0;
3523
3004
  const totalOutput = statusPayload.totalTokens?.output ?? 0;
3524
- statusPayload.totalTokens = { input: totalInput + input, output: totalOutput + output, total: totalInput + totalOutput + input + output };
3005
+ statusPayload.totalTokens = { input: totalInput + input, output: totalOutput + output, total: totalInput + totalOutput + input + output, window, windowPeak: Math.max(statusPayload.totalTokens?.windowPeak ?? 0, window) };
3525
3006
  refreshUsageBudget();
3526
3007
  }
3527
3008
  statusPayload.turnCount = Math.max(statusPayload.turnCount ?? 0, step.turnCount);
3528
- updateStepTurnBudget(
3529
- flatIndex,
3530
- step.turnCount,
3531
- now,
3532
- isTerminalAssistantStop(event.message),
3533
- assistantStartsToolCall(event.message) || Boolean(step.currentTool),
3534
- );
3535
3009
  }
3536
3010
  syncTopLevelCurrentTool();
3537
3011
  step.lastActivityAt = now;
@@ -3557,6 +3031,7 @@ async function runSubagent(
3557
3031
  config: controlConfig,
3558
3032
  startedAt: step.startedAt ?? overallStartTime,
3559
3033
  lastActivityAt,
3034
+ turnCount: step.turnCount,
3560
3035
  currentTool: step.currentTool,
3561
3036
  thinking: step.thinking,
3562
3037
  now,
@@ -3721,23 +3196,6 @@ async function runSubagent(
3721
3196
  pendingStepSteers.push(request);
3722
3197
  }
3723
3198
  },
3724
- onSteerCapability: (capability) => {
3725
- steeringCapabilities.set(capability.index, capability);
3726
- if (!capability.supported) {
3727
- const now = Date.now();
3728
- const lifecycle = steeringStatus(statusPayload);
3729
- for (const request of lifecycle.recent) {
3730
- if (!request.targets.some((target) => target.index === capability.index && (target.state === "routed" || target.state === "scheduled"))) continue;
3731
- markSteeringAttention(capability.index);
3732
- updateSteeringLifecycleTarget(request.id, capability.index, "failed", now, { reason: "child Pi session does not support steering" });
3733
- 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" });
3734
- emitTerminalSteeringNotice(request.id, `Steering failed for run ${id}: child ${capability.index} does not support steering.`);
3735
- }
3736
- statusPayload.lastUpdate = now;
3737
- writeStatusPayload();
3738
- }
3739
- },
3740
- onSteerAck: consumeSteerAck,
3741
3199
  });
3742
3200
  if (config.deadlineAt !== undefined) {
3743
3201
  const remainingMs = Math.max(0, config.deadlineAt - Date.now());
@@ -3760,7 +3218,7 @@ async function runSubagent(
3760
3218
  let flatIndex = 0;
3761
3219
  let stepCursor = 0;
3762
3220
  while (true) {
3763
- if (interrupted || timedOut || stopped || turnBudgetExceeded) break;
3221
+ if (interrupted || timedOut || stopped) break;
3764
3222
  consumePendingAppendRequests();
3765
3223
  if (stepCursor >= steps.length) break;
3766
3224
  refreshUsageBudget();
@@ -3794,7 +3252,7 @@ async function runSubagent(
3794
3252
  : [undefined]
3795
3253
  : model ? [model] : [undefined];
3796
3254
  for (const candidate of candidates) {
3797
- assertThinkingWithinCeiling({ model: candidate, configThinking, ceiling: step.parallel.thinkingCeiling ?? decodeThinkingCeiling(process.env[SUBAGENT_THINKING_CEILING_ENV]), agent: step.parallel.agent, runId: id });
3255
+ assertThinkingWithinCeiling({ model: candidate, configThinking, ceiling: step.parallel.thinkingCeiling, agent: step.parallel.agent, runId: id });
3798
3256
  }
3799
3257
  }
3800
3258
  if (materialized.collectedOnEmpty) await validateDynamicCollection(step.collect.outputSchema, materialized.collectedOnEmpty);
@@ -3905,10 +3363,12 @@ async function runSubagent(
3905
3363
  : step.parallel.outputPath;
3906
3364
  const taskText = task.task ?? step.parallel.task;
3907
3365
  const materializedTask = step.parallel.namespaceOutputPath ? injectSingleOutputInstruction(taskText, outputPath, step.parallel) : taskText;
3366
+ const sessionName = deriveChildSessionName({ agent: step.parallel.agent, task: taskText, label: task.label ?? step.parallel.label });
3908
3367
  return omitUndefinedProperties({
3909
3368
  ...step.parallel,
3910
3369
  runFanoutPath: `chain[${stepIndex}].expand[${itemIndex}]`,
3911
3370
  task: materializedTask,
3371
+ ...(sessionName ? { sessionName } : {}),
3912
3372
  effectiveAcceptance: resolveEffectiveAcceptance(omitUndefinedProperties({
3913
3373
  explicit: step.parallel.acceptanceInput,
3914
3374
  agentName: step.parallel.agent,
@@ -3939,6 +3399,7 @@ async function runSubagent(
3939
3399
  const transcriptPath = resolveAsyncStepTranscriptPath(omitUndefinedProperties({ artifactsDir, artifactConfig, runId: id, agent: task.agent, flatIndex: groupStartFlatIndex + itemIndex, flatStepCount: dynamicFlatStepCount }));
3940
3400
  return omitUndefinedProperties({
3941
3401
  agent: task.agent,
3402
+ ...(task.sessionName ? { sessionName: task.sessionName } : {}),
3942
3403
  ...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),
3943
3404
  ...(task.context ? { context: task.context } : {}),
3944
3405
  ...(task.phase ?? step.phase ? { phase: task.phase ?? step.phase } : {}),
@@ -3952,6 +3413,7 @@ async function runSubagent(
3952
3413
  ...(transcriptPath ? { transcriptPath } : {}),
3953
3414
  ...(task.skills ? { skills: task.skills } : {}),
3954
3415
  ...(task.model ? { model: task.model } : {}),
3416
+ ...(task.contextLimit !== undefined ? { contextLimit: task.contextLimit } : {}),
3955
3417
  ...(task.thinking ? { thinking: task.thinking } : {}),
3956
3418
  ...(task.thinkingCeiling ? { thinkingCeiling: task.thinkingCeiling } : {}),
3957
3419
  ...(task.modelCandidates && task.modelCandidates.length > 0 ? { attemptedModels: task.modelCandidates } : task.model ? { attemptedModels: [task.model] } : {}),
@@ -4021,12 +3483,12 @@ async function runSubagent(
4021
3483
  usageBudgetExceeded = true;
4022
3484
  writeStatusPayload();
4023
3485
  appendJsonl(eventsPath, JSON.stringify({ type: "subagent.step.failed", ts: skippedAt, runId: id, stepIndex: fi, agent: task.agent, exitCode: 1, durationMs: 0 }));
4024
- return omitUndefinedProperties({ agent: task.agent, context: task.context, output: message, error: message, exitCode: 1 as number | null, skipped: true });
3486
+ return omitUndefinedProperties({ agent: task.agent, ...(task.sessionName ? { sessionName: task.sessionName } : {}), context: task.context, output: message, error: message, exitCode: 1 as number | null, skipped: true });
4025
3487
  }
4026
- if (timedOut) return timedOutStepResult(task.agent, task.context);
4027
- if (stopped) return stoppedStepResult(task.agent, task.context);
3488
+ if (timedOut) return timedOutStepResult(task.agent, task.context, task.sessionName);
3489
+ if (stopped) return stoppedStepResult(task.agent, task.context, task.sessionName);
4028
3490
  if (childStopRequests.has(fi)) return childStopResult(fi, task.agent, task.context);
4029
- if (interrupted) return pausedStepResult(task.agent, task.context);
3491
+ if (interrupted) return pausedStepResult(task.agent, task.context, task.sessionName);
4030
3492
  if (aborted && failFast) {
4031
3493
  const skippedAt = Date.now();
4032
3494
  requiredStatusStep(statusPayload, fi).status = "failed";
@@ -4037,7 +3499,7 @@ async function runSubagent(
4037
3499
  requiredStatusStep(statusPayload, fi).exitCode = -1;
4038
3500
  statusPayload.lastUpdate = skippedAt;
4039
3501
  writeStatusPayload();
4040
- return omitUndefinedProperties({ agent: task.agent, context: task.context, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true });
3502
+ return omitUndefinedProperties({ agent: task.agent, ...(task.sessionName ? { sessionName: task.sessionName } : {}), context: task.context, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true });
4041
3503
  }
4042
3504
  const taskStartTime = Date.now();
4043
3505
  statusPayload.currentStep = fi;
@@ -4060,11 +3522,9 @@ async function runSubagent(
4060
3522
  artifactsDir, artifactConfig, id,
4061
3523
  flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
4062
3524
  outputFile: path.join(asyncDir, `output-${fi}.log`),
4063
- steerInboxDir: stepSteerInboxDir(asyncDir, fi),
4064
- steerCapabilityPath: steerCapabilityPath(asyncDir, fi),
4065
- steerAckDir: steerAcksDir(asyncDir, fi),
4066
3525
  piPackageRoot: config.piPackageRoot,
4067
- piArgv1: config.piArgv1,
3526
+ childSessions,
3527
+ inheritedChildRuntime: config.inheritedChildRuntime,
4068
3528
  childIntercomTarget: config.childIntercomTargets?.[fi],
4069
3529
  orchestratorIntercomTarget: config.controlIntercomTarget,
4070
3530
  nestedRoute: config.nestedRoute,
@@ -4073,20 +3533,19 @@ async function runSubagent(
4073
3533
  registerInterrupt: (interrupt) => registerStepInterrupt(fi, interrupt),
4074
3534
  registerTimeout: (interrupt) => registerStepTimeout(fi, interrupt),
4075
3535
  registerStop: (stop) => registerStepStop(fi, stop),
4076
- registerTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(fi, abort),
3536
+ registerSteer: (steer) => registerStepSteer(fi, steer),
4077
3537
  timeoutSignal: timeoutAbortController.signal,
4078
3538
  stopSignal: stopAbortController.signal,
4079
3539
  trackedMutationEvidenceForCompletionGuard: false,
4080
3540
  timeoutMessage,
4081
3541
  stopMessage,
4082
- turnBudget: config.turnBudget,
4083
3542
  toolTimeoutMs: task.toolTimeoutMs ?? config.toolTimeoutMs,
4084
- onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking),
3543
+ onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking, attempt.contextLimit),
4085
3544
  onChildEvent: (event) => updateStepFromChildEvent(fi, event),
4086
- onWriterProcess,
4087
3545
  onExternalProcess: (process) => updateExternalProcess(fi, process),
4088
3546
  onExternalJob: (externalJob) => updateExternalJob(fi, externalJob),
4089
3547
  skipAcceptance: () => timedOut || stopped || childStopRequests.has(fi),
3548
+ usageBudgetExhausted: () => refreshUsageBudget()?.exhausted === true,
4090
3549
  orcaProgressTab,
4091
3550
  }), config.deadlineAt);
4092
3551
  const taskEndTime = Date.now();
@@ -4098,16 +3557,11 @@ async function runSubagent(
4098
3557
  requiredStatusStep(statusPayload, fi).exitCode = stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;
4099
3558
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "timedOut", timedOut || singleResult.timedOut ? true : undefined);
4100
3559
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "stopped", stopped || childStopped ? true : undefined);
4101
- setOptionalProperty(requiredStatusStep(statusPayload, fi), "turnBudget", singleResult.turnBudget);
4102
- setOptionalProperty(requiredStatusStep(statusPayload, fi), "turnBudgetExceeded", singleResult.turnBudgetExceeded);
4103
- setOptionalProperty(requiredStatusStep(statusPayload, fi), "wrapUpRequested", singleResult.wrapUpRequested);
4104
3560
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudget", singleResult.toolBudget);
4105
3561
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudgetBlocked", singleResult.toolBudgetBlocked);
4106
3562
  if (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;
4107
3563
  if (singleResult.toolBudgetBlocked) statusPayload.toolBudgetBlocked = true;
4108
- if (singleResult.turnBudget) statusPayload.turnBudget = singleResult.turnBudget;
4109
- if (singleResult.turnBudgetExceeded) statusPayload.turnBudgetExceeded = true;
4110
- if (singleResult.wrapUpRequested) statusPayload.wrapUpRequested = true;
3564
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "sessionName", singleResult.sessionName);
4111
3565
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "model", singleResult.model);
4112
3566
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "thinking", resolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, fi).thinking));
4113
3567
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "attemptedModels", singleResult.attemptedModels);
@@ -4159,6 +3613,7 @@ async function runSubagent(
4159
3613
  for (const pr of parallelResults) {
4160
3614
  results.push(omitUndefinedProperties({
4161
3615
  agent: pr.agent,
3616
+ ...(pr.sessionName ? { sessionName: pr.sessionName } : {}),
4162
3617
  context: pr.context,
4163
3618
  agentContract: pr.agentContract,
4164
3619
  launchContractDigest: pr.launchContractDigest,
@@ -4167,25 +3622,23 @@ async function runSubagent(
4167
3622
  output: pr.output,
4168
3623
  outputState: pr.outputState,
4169
3624
  error: pr.error,
4170
- protocolError: pr.protocolError,
4171
3625
  success: pr.stopped !== true && pr.interrupted !== true && pr.exitCode === 0,
4172
3626
  exitCode: pr.interrupted === true ? 0 : pr.exitCode,
4173
3627
  skipped: pr.skipped,
4174
3628
  interrupted: pr.interrupted,
4175
3629
  timedOut: pr.timedOut,
4176
3630
  stopped: pr.stopped,
4177
- turnBudget: pr.turnBudget,
4178
- turnBudgetExceeded: pr.turnBudgetExceeded,
4179
- wrapUpRequested: pr.wrapUpRequested,
4180
3631
  toolBudget: pr.toolBudget,
4181
3632
  toolBudgetBlocked: pr.toolBudgetBlocked,
4182
3633
  sessionFile: pr.sessionFile,
4183
3634
  intercomTarget: pr.intercomTarget,
4184
3635
  model: pr.model,
3636
+ thinking: pr.thinking,
4185
3637
  attemptedModels: pr.attemptedModels,
4186
3638
  modelAttempts: pr.modelAttempts,
4187
3639
  contextOverflow: pr.contextOverflow,
4188
3640
  totalCost: pr.totalCost,
3641
+ usage: pr.usage,
4189
3642
  artifactPaths: pr.artifactPaths,
4190
3643
  transcriptPath: pr.transcriptPath,
4191
3644
  transcriptError: pr.transcriptError,
@@ -4325,10 +3778,32 @@ async function runSubagent(
4325
3778
  try {
4326
3779
  worktreeSetup = createWorktrees(cwd, `${id}-s${stepIndex}`, group.parallel.length, omitUndefinedProperties({
4327
3780
  agents: group.parallel.map((task) => task.agent),
3781
+ labels: group.parallel.map((task) => task.lane?.key ?? config.workflowKey ?? task.outputName ?? task.label),
3782
+ tasks: group.parallel.map((task) => task.task),
3783
+ provider: config.worktreeProvider,
3784
+ baseRef: config.baseRef,
3785
+ branchPrefix: config.worktreeBranchPrefix,
4328
3786
  setupHook: config.worktreeSetupHook
4329
3787
  ? omitUndefinedProperties({ hookPath: config.worktreeSetupHook, timeoutMs: config.worktreeSetupHookTimeoutMs })
4330
3788
  : undefined,
4331
3789
  baseDir: config.worktreeBaseDir,
3790
+ beforeCreate: (plannedSetup) => {
3791
+ for (const worktree of plannedSetup.worktrees) setStatusWorktreeReference(requiredStatusStep(statusPayload, groupStartFlatIndex + worktree.index), worktree);
3792
+ const pendingHandoff = writePendingParallelHandoff({
3793
+ manifestPath: parallelHandoffPath(asyncDir),
3794
+ runId: id,
3795
+ mode: (config.resultMode ?? statusPayload.mode) === "parallel" ? "parallel" : "chain",
3796
+ source: "async",
3797
+ cwd,
3798
+ stepIndex,
3799
+ flatStartIndex: groupStartFlatIndex,
3800
+ setup: plannedSetup,
3801
+ laneBindings: handoffWorkflowKey || config.lane ? [{ index: groupStartFlatIndex, taskIndex: 0, ...(handoffWorkflowKey ? { workflowKey: handoffWorkflowKey } : {}), ...(handoffChildRunId ? { runId: handoffChildRunId } : {}), ...(config.lane ? { lane: config.lane } : {}) }] : undefined,
3802
+ });
3803
+ statusPayload.parallelHandoff = pendingHandoff;
3804
+ statusPayload.lastUpdate = Date.now();
3805
+ writeStatusPayload();
3806
+ },
4332
3807
  }));
4333
3808
  } catch (error) {
4334
3809
  const setupError = error instanceof Error ? error.message : String(error);
@@ -4353,18 +3828,6 @@ async function runSubagent(
4353
3828
  }
4354
3829
 
4355
3830
  try {
4356
- if (worktreeSetup) {
4357
- writePendingParallelHandoff({
4358
- manifestPath: parallelHandoffPath(asyncDir),
4359
- runId: id,
4360
- mode: (config.resultMode ?? statusPayload.mode) === "parallel" ? "parallel" : "chain",
4361
- source: "async",
4362
- cwd,
4363
- stepIndex,
4364
- flatStartIndex: groupStartFlatIndex,
4365
- setup: worktreeSetup,
4366
- });
4367
- }
4368
3831
  if (group.worktree) ensureParallelProgressFile(cwd, group);
4369
3832
  const groupStartTime = Date.now();
4370
3833
  markParallelGroupRunning({
@@ -4401,12 +3864,12 @@ async function runSubagent(
4401
3864
  appendJsonl(eventsPath, JSON.stringify({
4402
3865
  type: "subagent.step.failed", ts: skippedAt, runId: id, stepIndex: fi, agent: task.agent, exitCode: 1, durationMs: 0,
4403
3866
  }));
4404
- return omitUndefinedProperties({ agent: task.agent, context: task.context, output: message, error: message, exitCode: 1 as number | null, skipped: true });
3867
+ return omitUndefinedProperties({ agent: task.agent, ...(task.sessionName ? { sessionName: task.sessionName } : {}), context: task.context, output: message, error: message, exitCode: 1 as number | null, skipped: true });
4405
3868
  }
4406
- if (timedOut) return timedOutStepResult(task.agent, task.context);
4407
- if (stopped) return stoppedStepResult(task.agent, task.context);
3869
+ if (timedOut) return timedOutStepResult(task.agent, task.context, task.sessionName);
3870
+ if (stopped) return stoppedStepResult(task.agent, task.context, task.sessionName);
4408
3871
  if (childStopRequests.has(fi)) return childStopResult(fi, task.agent, task.context);
4409
- if (interrupted) return pausedStepResult(task.agent, task.context);
3872
+ if (interrupted) return pausedStepResult(task.agent, task.context, task.sessionName);
4410
3873
  if (aborted && failFast) {
4411
3874
  const skippedAt = Date.now();
4412
3875
  requiredStatusStep(statusPayload, fi).status = "failed";
@@ -4421,7 +3884,7 @@ async function runSubagent(
4421
3884
  appendJsonl(eventsPath, JSON.stringify({
4422
3885
  type: "subagent.step.failed", ts: skippedAt, runId: id, stepIndex: fi, agent: task.agent, exitCode: -1, durationMs: 0,
4423
3886
  }));
4424
- return omitUndefinedProperties({ agent: task.agent, context: task.context, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true });
3887
+ return omitUndefinedProperties({ agent: task.agent, ...(task.sessionName ? { sessionName: task.sessionName } : {}), context: task.context, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true });
4425
3888
  }
4426
3889
 
4427
3890
  const taskStartTime = Date.now();
@@ -4456,11 +3919,9 @@ async function runSubagent(
4456
3919
  artifactsDir, artifactConfig, id,
4457
3920
  flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
4458
3921
  outputFile: path.join(asyncDir, `output-${fi}.log`),
4459
- steerInboxDir: stepSteerInboxDir(asyncDir, fi),
4460
- steerCapabilityPath: steerCapabilityPath(asyncDir, fi),
4461
- steerAckDir: steerAcksDir(asyncDir, fi),
4462
3922
  piPackageRoot: config.piPackageRoot,
4463
- piArgv1: config.piArgv1,
3923
+ childSessions,
3924
+ inheritedChildRuntime: config.inheritedChildRuntime,
4464
3925
  childIntercomTarget: config.childIntercomTargets?.[fi],
4465
3926
  orchestratorIntercomTarget: config.controlIntercomTarget,
4466
3927
  nestedRoute: config.nestedRoute,
@@ -4469,20 +3930,19 @@ async function runSubagent(
4469
3930
  registerInterrupt: (interrupt) => registerStepInterrupt(fi, interrupt),
4470
3931
  registerTimeout: (interrupt) => registerStepTimeout(fi, interrupt),
4471
3932
  registerStop: (stop) => registerStepStop(fi, stop),
4472
- registerTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(fi, abort),
3933
+ registerSteer: (steer) => registerStepSteer(fi, steer),
4473
3934
  timeoutSignal: timeoutAbortController.signal,
4474
3935
  stopSignal: stopAbortController.signal,
4475
3936
  trackedMutationEvidenceForCompletionGuard: Boolean(worktreeSetup),
4476
3937
  timeoutMessage,
4477
3938
  stopMessage,
4478
- turnBudget: config.turnBudget,
4479
3939
  toolTimeoutMs: taskForRun.toolTimeoutMs ?? config.toolTimeoutMs,
4480
- onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking),
3940
+ onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking, attempt.contextLimit),
4481
3941
  onChildEvent: (event) => updateStepFromChildEvent(fi, event),
4482
- onWriterProcess,
4483
3942
  onExternalProcess: (process) => updateExternalProcess(fi, process),
4484
3943
  onExternalJob: (externalJob) => updateExternalJob(fi, externalJob),
4485
3944
  skipAcceptance: () => timedOut || stopped || childStopRequests.has(fi),
3945
+ usageBudgetExhausted: () => refreshUsageBudget()?.exhausted === true,
4486
3946
  orcaProgressTab,
4487
3947
  }), config.deadlineAt);
4488
3948
  if (task.sessionFile) {
@@ -4500,16 +3960,11 @@ async function runSubagent(
4500
3960
  requiredStatusStep(statusPayload, fi).exitCode = stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;
4501
3961
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "timedOut", timedOut || singleResult.timedOut ? true : undefined);
4502
3962
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "stopped", stopped || childStopped ? true : undefined);
4503
- setOptionalProperty(requiredStatusStep(statusPayload, fi), "turnBudget", singleResult.turnBudget);
4504
- setOptionalProperty(requiredStatusStep(statusPayload, fi), "turnBudgetExceeded", singleResult.turnBudgetExceeded);
4505
- setOptionalProperty(requiredStatusStep(statusPayload, fi), "wrapUpRequested", singleResult.wrapUpRequested);
4506
3963
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudget", singleResult.toolBudget);
4507
3964
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudgetBlocked", singleResult.toolBudgetBlocked);
4508
3965
  if (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;
4509
3966
  if (singleResult.toolBudgetBlocked) statusPayload.toolBudgetBlocked = true;
4510
- if (singleResult.turnBudget) statusPayload.turnBudget = singleResult.turnBudget;
4511
- if (singleResult.turnBudgetExceeded) statusPayload.turnBudgetExceeded = true;
4512
- if (singleResult.wrapUpRequested) statusPayload.wrapUpRequested = true;
3967
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "sessionName", singleResult.sessionName);
4513
3968
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "model", singleResult.model);
4514
3969
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "thinking", resolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, fi).thinking));
4515
3970
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "attemptedModels", singleResult.attemptedModels);
@@ -4580,13 +4035,21 @@ async function runSubagent(
4580
4035
  const sessionTokens = config.sessionDir
4581
4036
  ? parseSessionTokens(path.join(config.sessionDir, `parallel-${t}`))
4582
4037
  : null;
4583
- const taskTokens = sessionTokens ?? tokenUsageFromAttempts(parallelResults[t]?.modelAttempts);
4038
+ const fallbackTokens = tokenUsageFromAttempts(parallelResults[t]?.modelAttempts);
4039
+ const observedTokens = requiredStatusStep(statusPayload, fi).tokens;
4040
+ const taskTokens = sessionTokens ?? (fallbackTokens
4041
+ ? { ...fallbackTokens, ...(observedTokens?.window !== undefined ? { window: observedTokens.window } : {}), ...(observedTokens?.windowPeak !== undefined ? { windowPeak: observedTokens.windowPeak } : {}) }
4042
+ : null);
4584
4043
  if (!taskTokens) continue;
4585
4044
  requiredStatusStep(statusPayload, fi).tokens = taskTokens;
4586
4045
  previousCumulativeTokens = {
4587
4046
  input: previousCumulativeTokens.input + taskTokens.input,
4588
4047
  output: previousCumulativeTokens.output + taskTokens.output,
4589
4048
  total: previousCumulativeTokens.total + taskTokens.total,
4049
+ ...(taskTokens.window !== undefined ? { window: taskTokens.window } : {}),
4050
+ ...(previousCumulativeTokens.windowPeak !== undefined || taskTokens.windowPeak !== undefined
4051
+ ? { windowPeak: Math.max(previousCumulativeTokens.windowPeak ?? 0, taskTokens.windowPeak ?? 0) }
4052
+ : {}),
4590
4053
  };
4591
4054
  }
4592
4055
  statusPayload.totalTokens = { ...previousCumulativeTokens };
@@ -4603,25 +4066,23 @@ async function runSubagent(
4603
4066
  output: pr.output,
4604
4067
  outputState: pr.outputState,
4605
4068
  error: pr.error,
4606
- protocolError: pr.protocolError,
4607
4069
  success: pr.stopped !== true && pr.interrupted !== true && pr.exitCode === 0,
4608
4070
  exitCode: pr.interrupted === true ? 0 : pr.exitCode,
4609
4071
  skipped: pr.skipped,
4610
4072
  interrupted: pr.interrupted,
4611
4073
  timedOut: pr.timedOut,
4612
4074
  stopped: pr.stopped,
4613
- turnBudget: pr.turnBudget,
4614
- turnBudgetExceeded: pr.turnBudgetExceeded,
4615
- wrapUpRequested: pr.wrapUpRequested,
4616
4075
  toolBudget: pr.toolBudget,
4617
4076
  toolBudgetBlocked: pr.toolBudgetBlocked,
4618
4077
  sessionFile: pr.sessionFile,
4619
4078
  intercomTarget: pr.intercomTarget,
4620
4079
  model: pr.model,
4080
+ thinking: pr.thinking,
4621
4081
  attemptedModels: pr.attemptedModels,
4622
4082
  modelAttempts: pr.modelAttempts,
4623
4083
  contextOverflow: pr.contextOverflow,
4624
4084
  totalCost: pr.totalCost,
4085
+ usage: pr.usage,
4625
4086
  artifactPaths: pr.artifactPaths,
4626
4087
  transcriptPath: pr.transcriptPath,
4627
4088
  transcriptError: pr.transcriptError,
@@ -4675,12 +4136,14 @@ async function runSubagent(
4675
4136
  diffs: captured.diffs,
4676
4137
  results: parallelResults.map((result) => ({
4677
4138
  agent: result.agent,
4139
+ ...(handoffWorkflowKey ? { workflowKey: handoffWorkflowKey } : {}),
4140
+ ...(handoffChildRunId ? { runId: handoffChildRunId } : {}),
4141
+ ...(config.lane ? { lane: config.lane } : {}),
4678
4142
  status: result.stopped || (result.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
4679
4143
  processSignal: result.processSignal,
4680
4144
  interrupted: result.interrupted,
4681
4145
  timedOut: result.timedOut,
4682
4146
  stopped: result.stopped,
4683
- turnBudgetExceeded: result.turnBudgetExceeded,
4684
4147
  }))) ? "stopped" as const : result.interrupted ? "paused" as const : result.exitCode === 0 ? "completed" as const : "failed" as const,
4685
4148
  summary: result.output || result.error || "(no output)",
4686
4149
  ...(result.artifactPaths?.outputPath ? { outputPath: result.artifactPaths.outputPath } : {}),
@@ -4726,12 +4189,12 @@ async function runSubagent(
4726
4189
  } else {
4727
4190
  const seqStep = step as SubagentStep;
4728
4191
  if (timedOut) {
4729
- results.push(timedOutStepResult(seqStep.agent, seqStep.context));
4192
+ results.push(timedOutStepResult(seqStep.agent, seqStep.context, seqStep.sessionName));
4730
4193
  flatIndex++;
4731
4194
  continue;
4732
4195
  }
4733
4196
  if (stopped) {
4734
- results.push(stoppedStepResult(seqStep.agent, seqStep.context));
4197
+ results.push(stoppedStepResult(seqStep.agent, seqStep.context, seqStep.sessionName));
4735
4198
  flatIndex++;
4736
4199
  continue;
4737
4200
  }
@@ -4741,7 +4204,7 @@ async function runSubagent(
4741
4204
  continue;
4742
4205
  }
4743
4206
  if (interrupted) {
4744
- results.push(pausedStepResult(seqStep.agent, seqStep.context));
4207
+ results.push(pausedStepResult(seqStep.agent, seqStep.context, seqStep.sessionName));
4745
4208
  flatIndex++;
4746
4209
  continue;
4747
4210
  }
@@ -4750,21 +4213,36 @@ async function runSubagent(
4750
4213
  try {
4751
4214
  singleWorktreeSetup = createWorktrees(cwd, `${id}-s${stepIndex}`, 1, omitUndefinedProperties({
4752
4215
  agents: [seqStep.agent],
4216
+ labels: [seqStep.lane?.key ?? config.workflowKey ?? seqStep.outputName ?? seqStep.label],
4217
+ tasks: [seqStep.task],
4218
+ provider: config.worktreeProvider,
4219
+ baseRef: config.baseRef,
4220
+ branchPrefix: config.worktreeBranchPrefix,
4753
4221
  setupHook: config.worktreeSetupHook
4754
4222
  ? omitUndefinedProperties({ hookPath: config.worktreeSetupHook, timeoutMs: config.worktreeSetupHookTimeoutMs })
4755
4223
  : undefined,
4756
4224
  baseDir: config.worktreeBaseDir,
4225
+ beforeCreate: (plannedSetup) => {
4226
+ const worktree = plannedSetup.worktrees[0];
4227
+ if (worktree) {
4228
+ setStatusWorktreeReference(requiredStatusStep(statusPayload, flatIndex), worktree);
4229
+ }
4230
+ const pendingHandoff = writePendingParallelHandoff({
4231
+ manifestPath: parallelHandoffPath(asyncDir),
4232
+ runId: id,
4233
+ mode: "single",
4234
+ source: "async",
4235
+ cwd,
4236
+ stepIndex,
4237
+ flatStartIndex: flatIndex,
4238
+ setup: plannedSetup,
4239
+ laneBindings: handoffWorkflowKey || config.lane ? [{ index: flatIndex, taskIndex: 0, ...(handoffWorkflowKey ? { workflowKey: handoffWorkflowKey } : {}), ...(handoffChildRunId ? { runId: handoffChildRunId } : {}), ...(config.lane ? { lane: config.lane } : {}) }] : undefined,
4240
+ });
4241
+ statusPayload.parallelHandoff = pendingHandoff;
4242
+ statusPayload.lastUpdate = Date.now();
4243
+ writeStatusPayload();
4244
+ },
4757
4245
  }));
4758
- writePendingParallelHandoff({
4759
- manifestPath: parallelHandoffPath(asyncDir),
4760
- runId: id,
4761
- mode: "single",
4762
- source: "async",
4763
- cwd,
4764
- stepIndex,
4765
- flatStartIndex: flatIndex,
4766
- setup: singleWorktreeSetup,
4767
- });
4768
4246
  } catch (error) {
4769
4247
  if (singleWorktreeSetup) cleanupWorktrees(singleWorktreeSetup);
4770
4248
  throw error;
@@ -4794,7 +4272,9 @@ async function runSubagent(
4794
4272
  }));
4795
4273
 
4796
4274
  flushPendingStepSteers(flatIndex);
4797
- const executionStep = singleWorktreeSetup ? { ...seqStep, cwd: singleCwd } : seqStep;
4275
+ const executionStep = singleWorktreeSetup
4276
+ ? bindWorktreeCwd({ ...seqStep, cwd: singleCwd }, singleCwd)
4277
+ : seqStep;
4798
4278
  let singleResult: Awaited<ReturnType<typeof runSingleStepWithTimeout>>;
4799
4279
  try {
4800
4280
  singleResult = await runSingleStepWithTimeout(executionStep, compactOptional<SingleStepContext>({
@@ -4804,11 +4284,9 @@ async function runSubagent(
4804
4284
  artifactsDir, artifactConfig, id,
4805
4285
  flatIndex, flatStepCount: Math.max(statusPayload.steps.length, 1),
4806
4286
  outputFile: path.join(asyncDir, `output-${flatIndex}.log`),
4807
- steerInboxDir: stepSteerInboxDir(asyncDir, flatIndex),
4808
- steerCapabilityPath: steerCapabilityPath(asyncDir, flatIndex),
4809
- steerAckDir: steerAcksDir(asyncDir, flatIndex),
4810
4287
  piPackageRoot: config.piPackageRoot,
4811
- piArgv1: config.piArgv1,
4288
+ childSessions,
4289
+ inheritedChildRuntime: config.inheritedChildRuntime,
4812
4290
  childIntercomTarget: config.childIntercomTargets?.[flatIndex],
4813
4291
  orchestratorIntercomTarget: config.controlIntercomTarget,
4814
4292
  nestedRoute: config.nestedRoute,
@@ -4817,19 +4295,18 @@ async function runSubagent(
4817
4295
  registerInterrupt: (interrupt) => registerStepInterrupt(flatIndex, interrupt),
4818
4296
  registerTimeout: (interrupt) => registerStepTimeout(flatIndex, interrupt),
4819
4297
  registerStop: (stop) => registerStepStop(flatIndex, stop),
4820
- registerTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(flatIndex, abort),
4298
+ registerSteer: (steer) => registerStepSteer(flatIndex, steer),
4821
4299
  timeoutSignal: timeoutAbortController.signal,
4822
4300
  stopSignal: stopAbortController.signal,
4823
4301
  timeoutMessage,
4824
4302
  stopMessage,
4825
- turnBudget: config.turnBudget,
4826
4303
  toolTimeoutMs: seqStep.toolTimeoutMs ?? config.toolTimeoutMs,
4827
- onAttemptStart: (attempt) => updateStepModel(flatIndex, attempt.model, attempt.thinking),
4304
+ onAttemptStart: (attempt) => updateStepModel(flatIndex, attempt.model, attempt.thinking, attempt.contextLimit),
4828
4305
  onChildEvent: (event) => updateStepFromChildEvent(flatIndex, event),
4829
- onWriterProcess,
4830
4306
  onExternalProcess: (process) => updateExternalProcess(flatIndex, process),
4831
4307
  onExternalJob: (externalJob) => updateExternalJob(flatIndex, externalJob),
4832
4308
  skipAcceptance: () => timedOut || stopped || childStopRequests.has(flatIndex),
4309
+ usageBudgetExhausted: () => refreshUsageBudget()?.exhausted === true,
4833
4310
  orcaProgressTab,
4834
4311
  }), config.deadlineAt);
4835
4312
  } catch (error) {
@@ -4844,6 +4321,7 @@ async function runSubagent(
4844
4321
  const childStopped = singleResult.stopped === true;
4845
4322
  results.push(omitUndefinedProperties({
4846
4323
  agent: singleResult.agent,
4324
+ ...(singleResult.sessionName ? { sessionName: singleResult.sessionName } : {}),
4847
4325
  context: singleResult.context,
4848
4326
  agentContract: singleResult.agentContract,
4849
4327
  launchContractDigest: singleResult.launchContractDigest,
@@ -4852,16 +4330,17 @@ async function runSubagent(
4852
4330
  output: stopped || childStopped ? stopMessage : timedOut ? singleResult.output || (timeoutMessage ?? "Subagent timed out.") : singleResult.output,
4853
4331
  outputState: singleResult.outputState,
4854
4332
  error: stopped || childStopped ? stopMessage : timedOut ? (timeoutMessage ?? "Subagent timed out.") : singleResult.error,
4855
- protocolError: singleResult.protocolError,
4856
4333
  success: !stopped && !childStopped && !timedOut && singleResult.interrupted !== true && singleResult.exitCode === 0,
4857
4334
  exitCode: stopped || childStopped ? 1 : timedOut ? 1 : singleResult.interrupted === true ? 0 : singleResult.exitCode,
4858
4335
  sessionFile: singleResult.sessionFile,
4859
4336
  intercomTarget: singleResult.intercomTarget,
4860
4337
  model: singleResult.model,
4338
+ thinking: singleResult.thinking,
4861
4339
  attemptedModels: singleResult.attemptedModels,
4862
4340
  modelAttempts: singleResult.modelAttempts,
4863
4341
  contextOverflow: singleResult.contextOverflow,
4864
4342
  totalCost: singleResult.totalCost,
4343
+ usage: singleResult.usage,
4865
4344
  artifactPaths: singleResult.artifactPaths,
4866
4345
  transcriptPath: singleResult.transcriptPath,
4867
4346
  transcriptError: singleResult.transcriptError,
@@ -4879,9 +4358,6 @@ async function runSubagent(
4879
4358
  interrupted: singleResult.interrupted,
4880
4359
  timedOut: timedOut || singleResult.timedOut ? true : undefined,
4881
4360
  stopped: stopped || childStopped ? true : undefined,
4882
- turnBudget: singleResult.turnBudget,
4883
- turnBudgetExceeded: singleResult.turnBudgetExceeded,
4884
- wrapUpRequested: singleResult.wrapUpRequested,
4885
4361
  toolBudget: singleResult.toolBudget,
4886
4362
  toolBudgetBlocked: singleResult.toolBudgetBlocked,
4887
4363
  runner: singleResult.runner,
@@ -4903,17 +4379,27 @@ async function runSubagent(
4903
4379
  input: cumulativeTokens.input - previousCumulativeTokens.input,
4904
4380
  output: cumulativeTokens.output - previousCumulativeTokens.output,
4905
4381
  total: cumulativeTokens.total - previousCumulativeTokens.total,
4382
+ ...(cumulativeTokens.window !== undefined ? { window: cumulativeTokens.window } : {}),
4383
+ ...(cumulativeTokens.windowPeak !== undefined ? { windowPeak: cumulativeTokens.windowPeak } : {}),
4906
4384
  }
4907
4385
  : null;
4908
4386
  if (cumulativeTokens) {
4909
4387
  previousCumulativeTokens = cumulativeTokens;
4910
4388
  } else {
4911
- stepTokens = tokenUsageFromAttempts(singleResult.modelAttempts);
4389
+ const fallbackTokens = tokenUsageFromAttempts(singleResult.modelAttempts);
4390
+ const observedTokens = requiredStatusStep(statusPayload, flatIndex).tokens;
4391
+ stepTokens = fallbackTokens
4392
+ ? { ...fallbackTokens, ...(observedTokens?.window !== undefined ? { window: observedTokens.window } : {}), ...(observedTokens?.windowPeak !== undefined ? { windowPeak: observedTokens.windowPeak } : {}) }
4393
+ : null;
4912
4394
  if (stepTokens) {
4913
4395
  previousCumulativeTokens = {
4914
4396
  input: previousCumulativeTokens.input + stepTokens.input,
4915
4397
  output: previousCumulativeTokens.output + stepTokens.output,
4916
4398
  total: previousCumulativeTokens.total + stepTokens.total,
4399
+ ...(stepTokens.window !== undefined ? { window: stepTokens.window } : {}),
4400
+ ...(previousCumulativeTokens.windowPeak !== undefined || stepTokens.windowPeak !== undefined
4401
+ ? { windowPeak: Math.max(previousCumulativeTokens.windowPeak ?? 0, stepTokens.windowPeak ?? 0) }
4402
+ : {}),
4917
4403
  };
4918
4404
  }
4919
4405
  }
@@ -4926,16 +4412,11 @@ async function runSubagent(
4926
4412
  requiredStatusStep(statusPayload, flatIndex).exitCode = stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;
4927
4413
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "timedOut", timedOut || singleResult.timedOut ? true : undefined);
4928
4414
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "stopped", stopped || childStopped ? true : undefined);
4929
- setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "turnBudget", singleResult.turnBudget);
4930
- setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "turnBudgetExceeded", singleResult.turnBudgetExceeded);
4931
- setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "wrapUpRequested", singleResult.wrapUpRequested);
4932
4415
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "toolBudget", singleResult.toolBudget);
4933
4416
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "toolBudgetBlocked", singleResult.toolBudgetBlocked);
4934
4417
  if (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;
4935
4418
  if (singleResult.toolBudgetBlocked) statusPayload.toolBudgetBlocked = true;
4936
- if (singleResult.turnBudget) statusPayload.turnBudget = singleResult.turnBudget;
4937
- if (singleResult.turnBudgetExceeded) statusPayload.turnBudgetExceeded = true;
4938
- if (singleResult.wrapUpRequested) statusPayload.wrapUpRequested = true;
4419
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "sessionName", singleResult.sessionName);
4939
4420
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "model", singleResult.model);
4940
4421
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "thinking", resolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, flatIndex).thinking));
4941
4422
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "attemptedModels", singleResult.attemptedModels);
@@ -4996,6 +4477,9 @@ async function runSubagent(
4996
4477
  diffs,
4997
4478
  results: [{
4998
4479
  agent: singleResult.agent,
4480
+ ...(handoffWorkflowKey ? { workflowKey: handoffWorkflowKey } : {}),
4481
+ ...(handoffChildRunId ? { runId: handoffChildRunId } : {}),
4482
+ ...(config.lane ? { lane: config.lane } : {}),
4999
4483
  status: singleResult.stopped ? "stopped" as const : singleResult.interrupted ? "paused" as const : singleResult.exitCode === 0 ? "completed" as const : "failed" as const,
5000
4484
  summary: singleResult.output || singleResult.error || "(no output)",
5001
4485
  ...(singleResult.artifactPaths?.outputPath ? { outputPath: singleResult.artifactPaths.outputPath } : {}),
@@ -5048,7 +4532,7 @@ async function runSubagent(
5048
4532
  }
5049
4533
  }
5050
4534
 
5051
- let summary = results.map((r) => `${r.agent}:\n${r.output}`).join("\n\n");
4535
+ let summary = results.map((r) => `${r.agent}:\n${r.output || (r.exitCode !== 0 ? r.error : undefined) || "(no output)"}`).join("\n\n");
5052
4536
  let truncated = false;
5053
4537
 
5054
4538
  if (maxOutput) {
@@ -5113,17 +4597,17 @@ async function runSubagent(
5113
4597
  clearTimeout(timeoutTimer);
5114
4598
  timeoutTimer = undefined;
5115
4599
  }
5116
- if (!timedOut && !stopped && !interrupted && config.timeoutMs !== undefined && results.some((result) => result.timedOut === true && result.error === timeoutMessage)) {
4600
+ if (!timedOut && !stopped && !interrupted && config.timeoutMs !== undefined && timeoutMessage !== undefined && results.some((result) => result.timedOut === true && result.error?.startsWith(timeoutMessage))) {
5117
4601
  timedOut = true;
5118
4602
  }
5119
- const signalTerminated = !stopped && !timedOut && !turnBudgetExceeded && !interrupted && results.some((result) => result.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
4603
+ const signalTerminated = !stopped && !timedOut && !interrupted && results.some((result) => result.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
5120
4604
  processSignal: result.processSignal,
5121
4605
  interrupted: result.interrupted,
5122
4606
  timedOut: result.timedOut,
5123
4607
  stopped: result.stopped,
5124
- turnBudgetExceeded: result.turnBudgetExceeded,
5125
4608
  })));
5126
- statusPayload.state = stopped || signalTerminated ? "stopped" : timedOut || turnBudgetExceeded || usageBudgetExceeded || statusPayload.error ? "failed" : interrupted ? "paused" : results.every((r) => r.success) ? "complete" : "failed";
4609
+ const partialWithEvidence = !stopped && !signalTerminated && !timedOut && !usageBudgetExceeded && !interrupted && results.some(partialEvidenceResult) && !results.some(concreteFailureResult);
4610
+ statusPayload.state = stopped || signalTerminated ? "stopped" : timedOut || usageBudgetExceeded ? "failed" : interrupted ? "paused" : results.every((r) => r.success) ? "complete" : partialWithEvidence ? "partial" : "failed";
5127
4611
  closeSteerInbox(asyncDir, statusPayload.state, (filePath, payload) => runPersistence.write(filePath, payload));
5128
4612
  disposeControlInbox();
5129
4613
  for (const request of consumeSteerRequests(asyncDir)) deliverSteerRequest(request);
@@ -5153,13 +4637,17 @@ async function runSubagent(
5153
4637
  statusPayload.timedOut = true;
5154
4638
  statusPayload.error = timeoutMessage ?? "Subagent timed out.";
5155
4639
  }
5156
- if (turnBudgetExceeded && !statusPayload.error) {
5157
- const budget = statusPayload.turnBudget;
5158
- statusPayload.error = budget ? turnBudgetExceededMessage(budget, budget.turnCount) : "Subagent exceeded turn budget.";
5159
- }
5160
4640
  if (usageBudgetExceeded && statusPayload.usageBudget && !statusPayload.error) {
5161
4641
  statusPayload.error = usageBudgetExceededMessage(statusPayload.usageBudget);
5162
4642
  }
4643
+ if (partialWithEvidence) {
4644
+ const partialResult = results.find(partialEvidenceResult);
4645
+ statusPayload.activityState = "needs_attention";
4646
+ statusPayload.error = partialResult?.error ?? statusPayload.error;
4647
+ for (const step of statusPayload.steps) {
4648
+ if (step.status === "failed") step.activityState = "needs_attention";
4649
+ }
4650
+ }
5163
4651
  statusPayload.endedAt = runEndedAt;
5164
4652
  statusPayload.lastUpdate = runEndedAt;
5165
4653
  setOptionalProperty(statusPayload, "sessionFile", effectiveSessionFile);
@@ -5169,56 +4657,53 @@ async function runSubagent(
5169
4657
  setOptionalProperty(statusPayload, "shareUrl", shareUrl);
5170
4658
  setOptionalProperty(statusPayload, "gistUrl", gistUrl);
5171
4659
  setOptionalProperty(statusPayload, "shareError", shareError);
5172
- if (statusPayload.state === "failed" && !statusPayload.error) {
5173
- const failedStep = statusPayload.steps.find((s) => s.status === "failed");
4660
+ if ((statusPayload.state === "failed" || statusPayload.state === "partial") && !statusPayload.error) {
4661
+ const concreteFailure = results.find(concreteFailureResult);
4662
+ const failedStep = concreteFailure ? undefined : statusPayload.steps.find((s) => s.status === "failed");
4663
+ if (concreteFailure?.error) statusPayload.error = concreteFailure.error;
5174
4664
  if (failedStep?.agent) {
5175
4665
  statusPayload.error = `Step failed: ${failedStep.agent}`;
5176
4666
  }
5177
4667
  }
5178
- writeStatusPayload();
5179
4668
  try {
5180
4669
  runPersistence.write(resultPath, {
5181
4670
  lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
5182
4671
  id,
5183
4672
  agent: agentName,
5184
4673
  mode: resultMode,
5185
- success: !stopped && !timedOut && !turnBudgetExceeded && !usageBudgetExceeded && !interrupted && !signalTerminated && results.every((r) => r.success),
5186
- state: stopped || signalTerminated ? "stopped" : timedOut || turnBudgetExceeded || usageBudgetExceeded ? "failed" : interrupted ? "paused" : results.every((r) => r.success) ? "complete" : "failed",
5187
- summary: 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,
4674
+ success: statusPayload.state === "complete",
4675
+ state: statusPayload.state,
4676
+ summary: stopped ? stopMessage : signalTerminated ? (statusPayload.error ?? "Subagent process terminated by signal.") : timedOut ? (timeoutMessage ?? "Subagent timed out.") : usageBudgetExceeded ? (statusPayload.error ?? "Usage budget exhausted.") : interrupted ? "Paused after interrupt. Waiting for explicit next action." : statusPayload.state === "partial" ? (statusPayload.error ?? summary) : summary,
5188
4677
  ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),
5189
4678
  ...(config.deadlineAt !== undefined ? { deadlineAt: config.deadlineAt } : {}),
5190
- ...(statusPayload.turnBudget ? { turnBudget: statusPayload.turnBudget } : {}),
5191
- ...(statusPayload.turnBudgetExceeded ? { turnBudgetExceeded: true } : {}),
5192
- ...(statusPayload.wrapUpRequested ? { wrapUpRequested: true } : {}),
5193
4679
  ...(statusPayload.toolBudget ? { toolBudget: statusPayload.toolBudget } : {}),
5194
4680
  ...(statusPayload.toolBudgetBlocked ? { toolBudgetBlocked: true } : {}),
5195
4681
  ...(statusPayload.usageBudget ? { usageBudget: statusPayload.usageBudget } : {}),
5196
- ...(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." } : {}),
4682
+ ...(stopped ? { stopped: true, error: stopMessage } : timedOut ? { timedOut: true, error: timeoutMessage ?? "Subagent timed out." } : usageBudgetExceeded ? { error: statusPayload.error ?? "Usage budget exhausted." } : {}),
5197
4683
  results: results.map((r) => omitUndefinedProperties({
5198
4684
  agent: r.agent,
4685
+ ...(r.sessionName ? { sessionName: r.sessionName } : {}),
5199
4686
  context: r.context,
5200
4687
  output: r.output,
5201
4688
  outputState: r.outputState,
5202
4689
  error: r.error,
5203
- protocolError: r.protocolError,
5204
4690
  success: r.success,
5205
4691
  skipped: r.skipped || undefined,
5206
4692
  interrupted: r.interrupted || undefined,
5207
4693
  timedOut: r.timedOut || undefined,
5208
4694
  stopped: r.stopped || undefined,
5209
4695
  processSignal: r.processSignal || undefined,
5210
- turnBudget: r.turnBudget,
5211
- turnBudgetExceeded: r.turnBudgetExceeded || undefined,
5212
- wrapUpRequested: r.wrapUpRequested || undefined,
5213
4696
  toolBudget: r.toolBudget,
5214
4697
  toolBudgetBlocked: r.toolBudgetBlocked || undefined,
5215
4698
  sessionFile: r.sessionFile,
5216
4699
  intercomTarget: r.intercomTarget,
5217
4700
  model: r.model,
4701
+ thinking: r.thinking,
5218
4702
  attemptedModels: r.attemptedModels,
5219
4703
  modelAttempts: r.modelAttempts,
5220
4704
  contextOverflow: r.contextOverflow,
5221
4705
  totalCost: r.totalCost,
4706
+ usage: r.usage,
5222
4707
  artifactPaths: r.artifactPaths,
5223
4708
  outputSaveError: r.outputSaveError,
5224
4709
  metadataSaveError: r.metadataSaveError,
@@ -5251,7 +4736,7 @@ async function runSubagent(
5251
4736
  capabilityAudit: statusPayload.capabilityAudit,
5252
4737
  ...(config.parentWorkflowRunId ? { parentWorkflowRunId: config.parentWorkflowRunId } : {}),
5253
4738
  ...(config.workflowKey ? { workflowKey: config.workflowKey } : {}),
5254
- exitCode: stopped || timedOut || turnBudgetExceeded || usageBudgetExceeded ? 1 : interrupted || results.every((r) => r.success) ? 0 : 1,
4739
+ exitCode: statusPayload.state === "complete" || statusPayload.state === "paused" ? 0 : 1,
5255
4740
  timestamp: runEndedAt,
5256
4741
  durationMs: runEndedAt - overallStartTime,
5257
4742
  totalTokens: statusPayload.totalTokens,
@@ -5283,7 +4768,7 @@ async function runSubagent(
5283
4768
  statusPayload.lastUpdate = Date.now();
5284
4769
  }
5285
4770
  writeStatusPayload();
5286
- orcaProgressTab?.finish(statusPayload.state === "complete" ? "completed" : statusPayload.state === "stopped" ? "stopped" : "failed", effectiveSessionFile);
4771
+ await orcaProgressTab?.finish(statusPayload.state === "complete" ? "completed" : statusPayload.state === "stopped" ? "stopped" : "failed", effectiveSessionFile);
5287
4772
  appendJsonl(
5288
4773
  eventsPath,
5289
4774
  JSON.stringify({
@@ -5318,14 +4803,21 @@ async function runSubagent(
5318
4803
  }), (filePath, content) => runPersistence.write(filePath, { content }, (_path, payload) => {
5319
4804
  fs.writeFileSync(_path, (payload as { content: string }).content, "utf-8");
5320
4805
  }));
5321
- if (runPersistence.pendingCount() === 0) runPersistence.dispose();
5322
- if (indexPersistence.pendingCount() === 0) indexPersistence.dispose();
4806
+ // The run is committed: release the child sessions first, then wait for the
4807
+ // storage-capacity retries that may still hold the final status or result.
4808
+ await childSessions.dispose().catch((error: unknown) => console.error("Failed to dispose runner child sessions:", error));
4809
+ while (runPersistence.pendingCount() + indexPersistence.pendingCount() > 0) {
4810
+ await new Promise((resolve) => setTimeout(resolve, 200));
4811
+ }
4812
+ runPersistence.dispose();
4813
+ indexPersistence.dispose();
5323
4814
  if (config.runnerProcessInstanceId) {
4815
+ // Children run inside this process, so no step has writer processes to prove terminal.
5324
4816
  const writers: Record<string, PiWriterProcessInstanceExitV1[]> = {};
5325
4817
  const expectedWriters: Record<string, number> = {};
5326
- for (const [index, result] of results.entries()) {
5327
- writers[String(index)] = result.writerProcesses ?? [];
5328
- expectedWriters[String(index)] = result.writerAttemptCount ?? 0;
4818
+ for (const index of results.keys()) {
4819
+ writers[String(index)] = [];
4820
+ expectedWriters[String(index)] = 0;
5329
4821
  }
5330
4822
  const candidate: ProcessTerminalCandidate = {
5331
4823
  version: 1,
@@ -5359,7 +4851,7 @@ async function waitForStartupControl(
5359
4851
  } catch (error) {
5360
4852
  throw new Error(`Failed to read runner startup control '${controlPath}': ${error instanceof Error ? error.message : String(error)}`);
5361
4853
  }
5362
- if (payload.token !== token) throw new Error("Runner startup control token does not match the acquired session lease.");
4854
+ if (payload.token !== token) throw new Error("Runner startup control token does not match.");
5363
4855
  if (payload.action === action) return;
5364
4856
  if (payload.action !== "ack" && payload.action !== "proceed") throw new Error("Runner startup control action is invalid.");
5365
4857
  }
@@ -5370,7 +4862,7 @@ async function waitForStartupControl(
5370
4862
 
5371
4863
  async function runConfiguredSubagent(config: SubagentRunConfig): Promise<void> {
5372
4864
  let lease: ReturnType<typeof acquireSessionLease> | undefined;
5373
- let startupCommitted = config.revivalLease === undefined;
4865
+ let startupCommitted = config.revivalLease === undefined && config.launchBarrierToken === undefined;
5374
4866
  const startupPath = path.join(config.asyncDir, "runner-startup.json");
5375
4867
  const startupAckPath = path.join(config.asyncDir, "runner-startup-ack.json");
5376
4868
  const startupProceedPath = path.join(config.asyncDir, "runner-startup-proceed.json");
@@ -5383,7 +4875,15 @@ async function runConfiguredSubagent(config: SubagentRunConfig): Promise<void> {
5383
4875
  };
5384
4876
  process.once("exit", releaseOnExit);
5385
4877
  try {
5386
- if (config.revivalLease) {
4878
+ if (config.launchBarrierToken) {
4879
+ await waitForStartupControl(startupProceedPath, config.launchBarrierToken, "proceed");
4880
+ startupCommitted = true;
4881
+ try {
4882
+ fs.rmSync(startupProceedPath, { force: true });
4883
+ } catch {
4884
+ // Startup control cleanup is best effort after the parent commits the run.
4885
+ }
4886
+ } else if (config.revivalLease) {
5387
4887
  lease = acquireSessionLease(config.revivalLease);
5388
4888
  config.revivalLeaseToken = lease.owner.token;
5389
4889
  writeAtomicJson(startupPath, { state: "ready", token: lease.owner.token, pid: process.pid, owner: lease.owner });
@@ -5399,9 +4899,18 @@ async function runConfiguredSubagent(config: SubagentRunConfig): Promise<void> {
5399
4899
  }
5400
4900
  }
5401
4901
  }
5402
- await runSubagent(config, lease ? (writer) => lease!.updateWriter(writer) : undefined);
4902
+ const childSessions = await loadRunnerChildSessionFactory(config);
4903
+ try {
4904
+ await runSubagent(config, childSessions);
4905
+ } finally {
4906
+ try {
4907
+ await childSessions.dispose();
4908
+ } catch (error) {
4909
+ console.error("Failed to dispose runner child sessions:", error);
4910
+ }
4911
+ }
5403
4912
  } catch (error) {
5404
- if (config.revivalLease && !startupCommitted) {
4913
+ if (!startupCommitted) {
5405
4914
  try {
5406
4915
  writeAtomicJson(startupPath, { state: "error", pid: process.pid, error: error instanceof Error ? error.message : String(error) });
5407
4916
  } catch {
@@ -5428,10 +4937,16 @@ async function runConfiguredSubagent(config: SubagentRunConfig): Promise<void> {
5428
4937
  }
5429
4938
 
5430
4939
  function startConfiguredSubagent(config: SubagentRunConfig): void {
5431
- runConfiguredSubagent(config).catch((runErr) => {
5432
- console.error("Subagent runner error:", runErr);
5433
- process.exit(1);
5434
- });
4940
+ // Child sessions and the extensions loaded into them may leave handles
4941
+ // behind even after shutdown; the run is fully persisted by now, so exit
4942
+ // explicitly instead of waiting for the event loop to drain.
4943
+ runConfiguredSubagent(config).then(
4944
+ () => process.exit(0),
4945
+ (runErr) => {
4946
+ console.error("Subagent runner error:", runErr);
4947
+ process.exit(1);
4948
+ },
4949
+ );
5435
4950
  }
5436
4951
 
5437
4952
  const configArg = process.argv[2];