@xzzpig/pi-subagents 0.8.0 → 0.10.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 (221) hide show
  1. package/CHANGELOG.md +477 -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 +195 -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 +7 -6
  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 +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -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 +42 -21
  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 +77 -21
  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 +65 -29
  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 +7 -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 +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -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 +204 -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 +718 -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 +489 -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 +1223 -402
  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 +364 -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 +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -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 +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  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 +20 -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/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. 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,51 @@ 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";
132
+ import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
139
133
  import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
140
134
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, toolTimeoutCallKey } from "../shared/tool-timeout.ts";
141
135
  import { usageBudgetExceededMessage, usageBudgetState } from "../shared/usage-budget.ts";
142
136
  import { formatParallelHandoffError, formatParallelHandoffReference, parallelHandoffPath, writeParallelHandoffGroup, writePendingParallelHandoff } from "../shared/parallel-handoff.ts";
143
137
  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
138
  import { acquireSessionLease, type SessionLeaseRequest } from "../shared/session-lease.ts";
146
139
  import { buildExternalCliPrompt, runExternalCli } from "../shared/external-cli-runner.ts";
140
+ import { resolveClaudeCodeLaunch } from "../shared/claude-code-adapter.ts";
141
+ import { resolveCodexExecLaunch } from "../shared/codex-exec-adapter.ts";
142
+ import { resolveCursorAgentLaunch } from "../shared/cursor-agent-adapter.ts";
143
+ import { resolveExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
147
144
  import { runExternalJob } from "../shared/external-job-runner.ts";
148
145
  import { createOrcaProgressTab, type OrcaProgressTab } from "../shared/orca-progress-tabs.ts";
149
- import { decodeSubagentCapabilityCeiling, SUBAGENT_CAPABILITY_CEILING_ENV, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
146
+ import { clearSandboxStartupDiagnostic, readSandboxStartupDiagnostic } from "../shared/sandbox-startup-diagnostics.ts";
147
+ import type { ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
150
148
  import {
151
- CHILD_WATCHDOG_CONFIG_ENV,
152
149
  acceptChildWatchdogEvent,
153
- childWatchdogIsActive,
154
- decodeChildWatchdogConfig,
150
+ applyChildWatchdogMessage,
155
151
  isChildWatchdogStatusEvent,
156
152
  resolveChildWatchdogConfig,
157
- type ChildWatchdogStateSnapshot,
153
+ type ChildWatchdogStatusEvent,
158
154
  } from "../../watchdog/child-status.ts";
159
155
 
160
156
  const INTERCOM_DETACH_RECEIPT = "Detached for intercom coordination before task completion.";
161
157
 
158
+ // This process hosts child sessions. An ambient copy of pi-subagents loaded
159
+ // into one of them must register nothing; the variable marks the process as a
160
+ // child host.
161
+ process.env[SUBAGENT_CHILD_ENV] = "1";
162
+
162
163
  interface SubagentRunConfig {
163
164
  id: string;
164
165
  steps: RunnerStep[];
@@ -176,10 +177,16 @@ interface SubagentRunConfig {
176
177
  sessionId?: string | null;
177
178
  completionOwnerId?: string;
178
179
  piPackageRoot?: string;
179
- piArgv1?: string;
180
+ /** Test seam: module the runner imports its `ChildSessionFactory` from. */
181
+ childSessionFactoryModule?: string;
182
+ /** The launching executor's own child runtime when it was itself an in-process child. */
183
+ inheritedChildRuntime?: InheritedChildRuntime;
180
184
  worktreeSetupHook?: string;
181
185
  worktreeSetupHookTimeoutMs?: number;
182
186
  worktreeBaseDir?: string;
187
+ baseRef?: string;
188
+ worktreeProvider?: import("../../shared/types.ts").WorktreeProvider;
189
+ worktreeBranchPrefix?: string;
183
190
  controlConfig?: ResolvedControlConfig;
184
191
  controlIntercomTarget?: string;
185
192
  childIntercomTargets?: Array<string | undefined>;
@@ -193,7 +200,6 @@ interface SubagentRunConfig {
193
200
  deadlineAt?: number;
194
201
  /** Resolved configured hard per-tool-call timeout (ms); fast tools still have a default when undefined. */
195
202
  toolTimeoutMs?: number;
196
- turnBudget?: ResolvedTurnBudget;
197
203
  toolBudget?: ResolvedToolBudget;
198
204
  usageBudget?: UsageBudgetConfig;
199
205
  revivalLease?: SessionLeaseRequest;
@@ -206,13 +212,18 @@ interface SubagentRunConfig {
206
212
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
207
213
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
208
214
  runnerProcessInstanceId?: string;
215
+ launchBarrierToken?: string;
209
216
  parentWorkflowRunId?: string;
210
217
  workflowKey?: string;
218
+ lane?: WorkflowLaneMetadata;
211
219
  }
212
220
 
213
221
  interface StepResult {
214
222
  agent: string;
223
+ /** Human-readable display name for the child session, when derived at launch. */
224
+ sessionName?: string;
215
225
  context?: "fresh" | "fork";
226
+ sandbox?: string;
216
227
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
217
228
  capabilityAudit?: import("../shared/capability-ceiling.ts").SubagentCapabilityAudit;
218
229
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
@@ -220,7 +231,6 @@ interface StepResult {
220
231
  output: string;
221
232
  outputState?: SubagentOutputState;
222
233
  error?: string;
223
- protocolError?: ProtocolOutputLimit;
224
234
  success?: boolean;
225
235
  exitCode: number | null;
226
236
  usage?: Usage;
@@ -232,14 +242,12 @@ interface StepResult {
232
242
  stopped?: boolean;
233
243
  processSignal?: string | null;
234
244
  timeoutRecovery?: import("../../shared/types.ts").TimeoutRecoverySummary;
235
- turnBudget?: TurnBudgetState;
236
- turnBudgetExceeded?: boolean;
237
- wrapUpRequested?: boolean;
238
245
  toolBudget?: ToolBudgetState;
239
246
  toolBudgetBlocked?: boolean;
240
247
  sessionFile?: string;
241
248
  intercomTarget?: string;
242
249
  model?: string;
250
+ thinking?: string;
243
251
  attemptedModels?: string[];
244
252
  modelAttempts?: ModelAttempt[];
245
253
  /** True when the dispatch failed because the input exceeded the model's context window. */
@@ -261,13 +269,21 @@ interface StepResult {
261
269
  structuredOutputSchemaPath?: string;
262
270
  acceptance?: import("../../shared/types.ts").AcceptanceLedger;
263
271
  watchdog?: import("../../shared/types.ts").ChildWatchdogProgress;
264
- writerProcesses?: PiWriterProcessInstanceExitV1[];
265
- writerAttemptCount?: number;
266
272
  runner?: ExternalCliRunnerStatus | ExternalJobRunnerStatus;
267
273
  externalProcess?: ExternalProcessStatus;
268
274
  externalJob?: ExternalJobStatus;
269
275
  }
270
276
 
277
+ function commonSandboxProfile(steps: readonly RunnerStatusStep[]): string | undefined {
278
+ const profile = steps[0]?.sandbox;
279
+ if (!profile || !steps.every((step) => step.sandbox === profile)) return undefined;
280
+ try {
281
+ return validateSandboxProfileName(profile);
282
+ } catch {
283
+ return undefined;
284
+ }
285
+ }
286
+
271
287
  function persistStepArtifacts(input: {
272
288
  artifactPaths: ArtifactPaths;
273
289
  artifactConfig?: Partial<ArtifactConfig>;
@@ -363,10 +379,6 @@ function appendDiagnosticJsonl(filePath: string, line: string, droppedEventType?
363
379
  state.diagnosticsTruncated = true;
364
380
  }
365
381
 
366
- function shouldPersistChildEvent(event: Record<string, unknown>): boolean {
367
- return event.type !== "message_update";
368
- }
369
-
370
382
  function isBlockingSupervisorTool(toolName: string | undefined, args: unknown): boolean {
371
383
  if (!args || typeof args !== "object" || Array.isArray(args)) return false;
372
384
  if (toolName === "contact_supervisor") {
@@ -422,6 +434,23 @@ function costSummaryFromAttempts(attempts: ModelAttempt[] | undefined): CostSumm
422
434
  : undefined;
423
435
  }
424
436
 
437
+ function usageFromAttempts(attempts: ModelAttempt[] | undefined): Usage | undefined {
438
+ if (!attempts || attempts.length === 0) return undefined;
439
+ const usage = emptyUsage();
440
+ for (const attempt of attempts) {
441
+ if (!attempt.usage) continue;
442
+ usage.input += attempt.usage.input;
443
+ usage.output += attempt.usage.output;
444
+ usage.cacheRead += attempt.usage.cacheRead;
445
+ usage.cacheWrite += attempt.usage.cacheWrite;
446
+ usage.cost += attempt.usage.cost;
447
+ usage.turns += attempt.usage.turns;
448
+ }
449
+ return usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0
450
+ ? usage
451
+ : undefined;
452
+ }
453
+
425
454
  function appendRecentStepOutput(step: RunnerStatusStep, lines: string[]): void {
426
455
  const nonEmpty = lines.filter((line) => line.trim());
427
456
  if (nonEmpty.length === 0) return;
@@ -432,15 +461,6 @@ function appendRecentStepOutput(step: RunnerStatusStep, lines: string[]): void {
432
461
  }
433
462
  }
434
463
 
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
464
  type UndefinedOmitted<T extends object> = {
445
465
  [K in keyof T]: Exclude<T[K], undefined>;
446
466
  };
@@ -483,595 +503,38 @@ function resetStepLiveDetail(step: RunnerStatusStep): void {
483
503
  step.recentOutput = [];
484
504
  }
485
505
 
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
- }
502
-
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
- }
506
+ const MAX_CHILD_FAILURE_DIAGNOSTIC_CHARS = 8_192;
516
507
 
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;
508
+ function formatRequiredOutputError(requiredOutput: {
509
+ kind: "file-only" | "structured";
510
+ path: string;
511
+ missing: boolean;
512
+ } | undefined): string | undefined {
513
+ if (!requiredOutput?.missing) return undefined;
514
+ return `Required ${requiredOutput.kind} output was not produced: ${requiredOutput.path.slice(0, 2_048)}`;
549
515
  }
550
516
 
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
- });
517
+ function formatChildFailureDiagnostic(input: {
518
+ error: string | undefined;
519
+ afterCompactionSettlement?: boolean;
520
+ abortRecoveryDiagnostic?: string;
521
+ requiredOutput?: {
522
+ kind: "file-only" | "structured";
523
+ path: string;
524
+ missing: boolean;
525
+ };
526
+ }): string | undefined {
527
+ const missingOutput = formatRequiredOutputError(input.requiredOutput);
528
+ const notes = [
529
+ input.abortRecoveryDiagnostic,
530
+ input.afterCompactionSettlement ? "Child failure followed session compaction and agent settlement." : undefined,
531
+ missingOutput && input.error !== missingOutput ? missingOutput : undefined,
532
+ ].filter((note): note is string => Boolean(note));
533
+ if (notes.length === 0) return input.error;
534
+ const context = notes.join("\n");
535
+ const errorLimit = MAX_CHILD_FAILURE_DIAGNOSTIC_CHARS - (context ? context.length + 1 : 0);
536
+ const baseError = input.error || "Subagent failed.";
537
+ return `${baseError.slice(0, Math.max(0, errorLimit))}${context ? `\n${context}` : ""}`;
1075
538
  }
1076
539
 
1077
540
  function resolvePiPackageRootFallback(): string {
@@ -1195,16 +658,17 @@ interface SingleStepContext {
1195
658
  flatIndex: number;
1196
659
  flatStepCount: number;
1197
660
  outputFile: string;
1198
- steerInboxDir?: string;
1199
- steerCapabilityPath?: string;
1200
- steerAckDir?: string;
1201
661
  transcriptPath?: string;
1202
662
  piPackageRoot?: string;
1203
- piArgv1?: string;
663
+ /** Factory the runner creates this step's child session through. */
664
+ childSessions: ChildSessionFactory;
665
+ /** The launching executor's own child runtime; nested route, depth, and ceilings come from here. */
666
+ inheritedChildRuntime?: InheritedChildRuntime;
1204
667
  registerInterrupt?: (interrupt: (() => void) | undefined) => void;
1205
668
  registerTimeout?: (interrupt: (() => void) | undefined) => void;
1206
669
  registerStop?: (stop: (() => void) | undefined) => void;
1207
- registerTurnBudgetAbort?: (abort: ((message: string, state?: TurnBudgetState) => void) | undefined) => void;
670
+ /** Receives the live child's steer handler while its session runs. */
671
+ registerSteer?: (steer: StepSteerHandler | undefined) => void;
1208
672
  timeoutSignal?: AbortSignal;
1209
673
  stopSignal?: AbortSignal;
1210
674
  timeoutMessage?: string;
@@ -1213,18 +677,17 @@ interface SingleStepContext {
1213
677
  toolTimeoutMs?: number;
1214
678
  /** Effective step deadline (Date.now() + effective timeout) when a run budget exists. */
1215
679
  deadlineAt?: number;
1216
- turnBudget?: ResolvedTurnBudget;
1217
680
  childIntercomTarget?: string;
1218
681
  orchestratorIntercomTarget?: string;
1219
682
  nestedRoute?: NestedRouteInfo;
1220
683
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
1221
684
  runFanoutBudget?: RunFanoutBudgetDescriptor;
1222
- onAttemptStart?: (attempt: { model?: string; thinking?: string }) => void;
685
+ onAttemptStart?: (attempt: { model?: string; thinking?: string; contextLimit?: number }) => void;
1223
686
  onChildEvent?: (event: ChildEvent) => void;
1224
- onWriterProcess?: (writer: { state: "none" | "spawning" } | { state: "running"; pid: number }) => void;
1225
687
  onExternalProcess?: (process: ExternalProcessStatus) => void;
1226
688
  onExternalJob?: (status: ExternalJobStatus) => void;
1227
689
  skipAcceptance?: () => boolean;
690
+ usageBudgetExhausted?: () => boolean;
1228
691
  /** False when sibling work in the same Git worktree could have caused the tracked diff. */
1229
692
  trackedMutationEvidenceForCompletionGuard?: boolean;
1230
693
  orcaProgressTab?: OrcaProgressTab;
@@ -1293,10 +756,13 @@ async function runSingleStepInner(
1293
756
  modelAttempts: imported.modelAttempts,
1294
757
  contextOverflow: imported.contextOverflow,
1295
758
  totalCost: imported.totalCost,
759
+ usage: imported.usage,
1296
760
  structuredOutput: timedOut || stopped ? undefined : imported.structuredOutput,
1297
761
  structuredOutputPath: timedOut || stopped ? undefined : imported.structuredOutputPath,
1298
762
  structuredOutputSchemaPath: timedOut || stopped ? undefined : imported.structuredOutputSchemaPath,
1299
763
  acceptance: timedOut || stopped ? undefined : imported.acceptance,
764
+ execution: timedOut || stopped ? undefined : imported.execution,
765
+ effects: timedOut || stopped ? undefined : imported.effects,
1300
766
  });
1301
767
  } finally {
1302
768
  ctx.registerTimeout?.(undefined);
@@ -1305,7 +771,7 @@ async function runSingleStepInner(
1305
771
  }
1306
772
 
1307
773
  const effectiveStructuredOutput = step.structuredOutput ?? (step.structuredOutputSchema
1308
- ? createStructuredOutputRuntime(step.structuredOutputSchema, path.join(path.dirname(ctx.outputFile), "structured-output"))
774
+ ? createStructuredOutputRuntime(step.structuredOutputSchema, path.join(path.dirname(ctx.outputFile), "structured-output"), { acceptanceReport: resolveAcceptanceReportMode(step.acceptanceInput) })
1309
775
  : undefined);
1310
776
  const placeholderRegex = new RegExp(ctx.placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
1311
777
  let task = step.task.replace(placeholderRegex, () => ctx.previousOutput);
@@ -1315,6 +781,8 @@ async function runSingleStepInner(
1315
781
  if (!step.runner) {
1316
782
  resolvedTaskToolPlan = resolvePiLaunchToolPlan(omitUndefinedProperties({
1317
783
  tools: step.tools,
784
+ excludeTools: step.excludeTools,
785
+ allowNestedSubagents: step.allowNestedSubagents,
1318
786
  extensions: step.extensions,
1319
787
  subagentOnlyExtensions: step.subagentOnlyExtensions,
1320
788
  fast: step.fast,
@@ -1325,8 +793,9 @@ async function runSingleStepInner(
1325
793
  requireReadTool: Boolean(step.skills?.length),
1326
794
  structuredOutput: Boolean(effectiveStructuredOutput),
1327
795
  capabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,
1328
- inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
796
+ inheritedCapabilityCeiling: ctx.inheritedChildRuntime?.capabilityCeiling,
1329
797
  permissionRules: step.permissionRules,
798
+ sandbox: step.sandbox,
1330
799
  }));
1331
800
  const contractTools = resolvedTaskToolPlan.explicitToolAllowlist ? resolvedTaskToolPlan.effectiveToolAllowlist : undefined;
1332
801
  const contractError = validateImplementationToolContract({
@@ -1351,6 +820,9 @@ async function runSingleStepInner(
1351
820
  });
1352
821
  }
1353
822
  }
823
+ // Derive from the pre-acceptance task so internal acceptance/recovery
824
+ // instructions never leak into the display name.
825
+ const childSessionName = step.sessionName ?? deriveChildSessionName({ agent: step.agent, task, label: step.label });
1354
826
  if (step.effectiveAcceptance) {
1355
827
  const acceptancePrompt = formatAcceptancePrompt(step.effectiveAcceptance, { reportOptional: isAgentContractV1(step.agentContract), structuredOutput: Boolean(step.structuredOutput?.acceptanceReportPath) });
1356
828
  if (acceptancePrompt) task = `${task}\n${acceptancePrompt}`;
@@ -1381,21 +853,29 @@ async function runSingleStepInner(
1381
853
  transcriptWriter?.writeInitialUserMessage(`${PROMPT_REDACTED}; live Prompt Audit only.`);
1382
854
 
1383
855
  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
- };
856
+ const externalCwd = step.cwd ?? ctx.cwd;
857
+ const adapterLaunch = step.runner.adapter === "codex-exec" || step.runner.adapter === "codex-exec-writer"
858
+ ? resolveCodexExecLaunch({ adapter: step.runner.adapter, command: step.runner.command, asyncDir: path.dirname(ctx.outputFile), stepIndex: ctx.flatIndex })
859
+ : step.runner.adapter === "claude-code" || step.runner.adapter === "claude-code-writer"
860
+ ? resolveClaudeCodeLaunch({ adapter: step.runner.adapter, command: step.runner.command })
861
+ : step.runner.adapter === "cursor-agent" || step.runner.adapter === "cursor-agent-writer"
862
+ ? resolveCursorAgentLaunch({ adapter: step.runner.adapter, command: step.runner.command, cwd: externalCwd, asyncDir: path.dirname(ctx.outputFile), stepIndex: ctx.flatIndex })
863
+ : undefined;
864
+ const runner = resolveExternalCliRunnerStatus({ ...step.runner, ...(adapterLaunch ? { args: adapterLaunch.args } : {}) });
1391
865
  const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
1392
866
  const external = await runExternalCli(omitUndefinedProperties({
1393
- command: runner.command,
1394
- args: runner.args,
1395
- cwd: step.cwd ?? ctx.cwd,
867
+ command: adapterLaunch?.command ?? runner.command,
868
+ args: adapterLaunch?.args ?? runner.args,
869
+ cwd: externalCwd,
1396
870
  prompt: buildExternalCliPrompt(step.systemPrompt ?? "", task),
1397
871
  asyncDir: path.dirname(ctx.outputFile),
1398
872
  stepIndex: ctx.flatIndex,
873
+ environment: adapterLaunch?.environment,
874
+ preflight: adapterLaunch?.preflight,
875
+ parser: adapterLaunch?.parser,
876
+ finalOutputPath: adapterLaunch?.finalOutputPath,
877
+ promptFilePath: adapterLaunch?.promptFilePath,
878
+ temporaryDirectories: adapterLaunch?.temporaryDirectories,
1399
879
  registerTimeout: ctx.registerTimeout,
1400
880
  registerStop: ctx.registerStop,
1401
881
  timeoutMessage: ctx.timeoutMessage,
@@ -1406,14 +886,18 @@ async function runSingleStepInner(
1406
886
  }));
1407
887
  try { fs.writeFileSync(ctx.outputFile, external.output, "utf-8"); } catch { /* Observability output is best-effort. */ }
1408
888
  const resolvedOutput = step.outputPath && external.exitCode === 0
1409
- ? resolveSingleOutput(step.outputPath, external.output, outputSnapshot)
889
+ ? resolveSingleOutput(step.outputPath, external.output, outputSnapshot, step.outputClaimPath)
1410
890
  : { fullOutput: external.output };
1411
891
  const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, resolvedOutput.fullOutput) : undefined;
892
+ const exitCode = resolvedOutput.fatalError ? 1 : external.exitCode;
893
+ const error = resolvedOutput.fatalError && resolvedOutput.saveError
894
+ ? external.error ? `${external.error}\n${resolvedOutput.saveError}` : resolvedOutput.saveError
895
+ : external.error;
1412
896
  const finalizedOutput = finalizeSingleOutput(omitUndefinedProperties({
1413
897
  fullOutput: resolvedOutput.fullOutput,
1414
898
  outputPath: step.outputPath,
1415
899
  outputMode: step.outputMode,
1416
- exitCode: external.exitCode ?? 1,
900
+ exitCode: exitCode ?? 1,
1417
901
  savedPath: resolvedOutput.savedPath,
1418
902
  outputReference,
1419
903
  saveError: resolvedOutput.saveError,
@@ -1428,16 +912,17 @@ async function runSingleStepInner(
1428
912
  : {};
1429
913
  return omitUndefinedProperties({
1430
914
  agent: step.agent,
915
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
1431
916
  context: step.context,
1432
917
  output: finalizedOutput.displayOutput,
1433
918
  outputState: external.output.trim() ? "present" : "absent",
1434
- exitCode: external.exitCode,
1435
- error: external.error,
919
+ exitCode,
920
+ error,
1436
921
  timedOut: external.timedOut,
1437
922
  stopped: external.stopped,
1438
923
  processSignal: external.processSignal,
1439
924
  artifactPaths,
1440
- outputSaveError: artifactErrors.outputSaveError,
925
+ outputSaveError: [resolvedOutput.saveError, artifactErrors.outputSaveError].filter(Boolean).join("\n") || undefined,
1441
926
  metadataSaveError: artifactErrors.metadataSaveError,
1442
927
  runner,
1443
928
  externalProcess: external.externalProcess,
@@ -1471,14 +956,18 @@ async function runSingleStepInner(
1471
956
  }));
1472
957
  try { fs.writeFileSync(ctx.outputFile, external.output, "utf-8"); } catch { /* Observability output is best-effort. */ }
1473
958
  const resolvedOutput = step.outputPath && external.exitCode === 0
1474
- ? resolveSingleOutput(step.outputPath, external.output, outputSnapshot)
959
+ ? resolveSingleOutput(step.outputPath, external.output, outputSnapshot, step.outputClaimPath)
1475
960
  : { fullOutput: external.output };
1476
961
  const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, resolvedOutput.fullOutput) : undefined;
962
+ const exitCode = resolvedOutput.fatalError ? 1 : external.exitCode;
963
+ const error = resolvedOutput.fatalError && resolvedOutput.saveError
964
+ ? external.error ? `${external.error}\n${resolvedOutput.saveError}` : resolvedOutput.saveError
965
+ : external.error;
1477
966
  const finalizedOutput = finalizeSingleOutput(omitUndefinedProperties({
1478
967
  fullOutput: resolvedOutput.fullOutput,
1479
968
  outputPath: step.outputPath,
1480
969
  outputMode: step.outputMode,
1481
- exitCode: external.exitCode,
970
+ exitCode: exitCode ?? 1,
1482
971
  savedPath: resolvedOutput.savedPath,
1483
972
  outputReference,
1484
973
  saveError: resolvedOutput.saveError,
@@ -1493,21 +982,29 @@ async function runSingleStepInner(
1493
982
  : {};
1494
983
  return omitUndefinedProperties({
1495
984
  agent: step.agent,
985
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
1496
986
  context: step.context,
1497
987
  output: finalizedOutput.displayOutput,
1498
988
  outputState: external.output.trim() ? "present" : "absent",
1499
- exitCode: external.exitCode,
1500
- error: external.error,
989
+ exitCode,
990
+ error,
1501
991
  timedOut: external.timedOut,
1502
992
  stopped: external.stopped,
1503
993
  artifactPaths,
1504
- outputSaveError: artifactErrors.outputSaveError,
994
+ outputSaveError: [resolvedOutput.saveError, artifactErrors.outputSaveError].filter(Boolean).join("\n") || undefined,
1505
995
  metadataSaveError: artifactErrors.metadataSaveError,
1506
996
  runner,
1507
997
  externalJob: external.externalJob,
1508
998
  });
1509
999
  }
1510
1000
 
1001
+ const effectiveCwd = step.cwd ?? ctx.cwd;
1002
+ const cwdError = preflightLaunchCwd(step.requestedCwd ?? effectiveCwd, effectiveCwd);
1003
+ if (cwdError) return { agent: step.agent, output: cwdError, error: cwdError, exitCode: 1, context: step.context };
1004
+ if (step.context === "fork" && step.sessionFile && fs.existsSync(step.sessionFile)) {
1005
+ alignForkedSessionCwd(step.sessionFile, effectiveCwd);
1006
+ }
1007
+
1511
1008
  const candidates = step.modelCandidates !== undefined
1512
1009
  ? step.modelCandidates.length > 0 ? step.modelCandidates : [undefined]
1513
1010
  : step.model
@@ -1517,16 +1014,14 @@ async function runSingleStepInner(
1517
1014
  let capabilityAudit: import("../shared/capability-ceiling.ts").SubagentCapabilityAudit | undefined;
1518
1015
  let launchResolvedExtensions = step.launchResolvedExtensions;
1519
1016
  const modelAttempts: ModelAttempt[] = [];
1520
- const writerProcesses: PiWriterProcessInstanceExitV1[] = [];
1521
- let writerAttemptCount = 0;
1522
1017
  const attemptNotes: string[] = [];
1018
+ let finalRequiredOutputMissing: boolean | undefined;
1523
1019
  const eventsPath = path.join(path.dirname(ctx.outputFile), "events.jsonl");
1524
- let finalResult: RunPiStreamingResult | undefined;
1020
+ let finalResult: RunChildSessionResult | undefined;
1525
1021
  let finalOutputSnapshot: SingleOutputSnapshot | undefined;
1526
1022
  let structuredAcceptanceReport: unknown;
1527
1023
  let structuredAcceptanceReportError: string | undefined;
1528
1024
  let completionGuardTriggeredFinal = false;
1529
- let turnBudget = ctx.turnBudget ? initialTurnBudgetState(ctx.turnBudget) : undefined;
1530
1025
  let toolBudget = step.toolBudget ? initialToolBudgetState(step.toolBudget) : undefined;
1531
1026
  let toolBudgetBlocked = false;
1532
1027
  let actualLaunchContractDigest = step.launchContractDigest;
@@ -1534,29 +1029,32 @@ async function runSingleStepInner(
1534
1029
  let finalMutationEvidence = collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
1535
1030
 
1536
1031
  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
1032
  let contextOverflow = false;
1542
1033
  let launchWarningsEmitted = false;
1034
+ let abortRecoveryAttempted = false;
1035
+ let nextAttemptTask = task;
1543
1036
  modelAttemptsLoop: while (modelIndex < candidates.length) {
1544
1037
  if (ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break;
1038
+ const recoveringAbort = abortRecoveryAttempted;
1039
+ const attemptTask = nextAttemptTask;
1545
1040
  const candidate = candidates[modelIndex];
1546
1041
  const expectedModelForVerification = candidate && !(step.skipPrimaryModelVerification && modelIndex === 0) ? candidate : undefined;
1547
1042
  try {
1548
- assertThinkingWithinCeiling({ model: candidate, configThinking: step.thinking, ceiling: step.thinkingCeiling ?? decodeThinkingCeiling(process.env[SUBAGENT_THINKING_CEILING_ENV]), agent: step.agent, runId: ctx.id });
1043
+ assertThinkingWithinCeiling({ model: candidate, configThinking: step.thinking, ceiling: step.thinkingCeiling, agent: step.agent, runId: ctx.id });
1549
1044
  } catch (error) {
1550
1045
  const message = error instanceof Error ? error.message : String(error);
1551
1046
  return omitUndefinedProperties({ agent: step.agent, output: message, error: message, exitCode: 1, context: step.context, thinkingCeiling: step.thinkingCeiling });
1552
1047
  }
1553
- ctx.onAttemptStart?.(omitUndefinedProperties({ model: candidate, thinking: resolveEffectiveThinking(candidate, step.thinking) }));
1048
+ ctx.onAttemptStart?.(omitUndefinedProperties({
1049
+ model: candidate,
1050
+ thinking: resolveEffectiveThinking(candidate, step.thinking),
1051
+ contextLimit: findModelInfo(candidate, step.modelVerificationRegistry)?.contextWindow,
1052
+ }));
1554
1053
  const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
1555
1054
  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.
1055
+ const cleanupError = clearStructuredOutputCaptures(effectiveStructuredOutput);
1056
+ if (cleanupError) {
1057
+ return omitUndefinedProperties({ agent: step.agent, output: cleanupError, error: cleanupError, exitCode: 1, context: step.context });
1560
1058
  }
1561
1059
  }
1562
1060
  const watchdogConfig = resolveWatchdogConfig(step.cwd ?? ctx.cwd);
@@ -1569,56 +1067,65 @@ async function runSingleStepInner(
1569
1067
  childIndex: ctx.flatIndex,
1570
1068
  })
1571
1069
  : undefined;
1572
- const { args, env, tempDir, toolDiagnosticPath, runtimeAcknowledgedExtensionsPath, capabilityAudit: attemptCapabilityAudit, warnings } = buildPiArgs(omitUndefinedProperties({
1070
+ let watchdogSink: ((event: ChildWatchdogStatusEvent) => void) | undefined;
1071
+ const launch = buildInProcessChildLaunch(omitUndefinedProperties({
1573
1072
  parentSessionId: step.parentSessionId,
1574
- baseArgs: ["--mode", "json", "-p"],
1575
- task,
1576
- taskDelivery: taskDeliveryOverride,
1073
+ forkCacheKey: step.context === "fork" ? deriveForkPromptCacheKey(step.parentSessionId) : undefined,
1577
1074
  sessionEnabled,
1578
1075
  sessionDir,
1579
1076
  sessionFile: step.sessionFile,
1580
1077
  model: candidate,
1581
1078
  inheritProjectContext: step.inheritProjectContext,
1079
+ inheritGlobalContext: step.inheritGlobalContext,
1582
1080
  inheritSkills: step.inheritSkills,
1583
1081
  requireReadTool: Boolean(step.skills?.length),
1584
1082
  tools: step.tools,
1083
+ excludeTools: step.excludeTools,
1084
+ allowNestedSubagents: step.allowNestedSubagents,
1585
1085
  extensions: step.extensions,
1586
1086
  subagentOnlyExtensions: step.subagentOnlyExtensions,
1587
1087
  fast: step.fast,
1588
1088
  modelCandidates: step.modelCandidates,
1589
- systemPrompt: appendTurnBudgetSystemPrompt(step.systemPrompt ?? "", ctx.turnBudget),
1089
+ systemPrompt: step.systemPrompt ?? "",
1590
1090
  systemPromptMode: step.systemPromptMode,
1591
1091
  mcpDirectTools: step.mcpDirectTools,
1092
+ extensionBindings,
1592
1093
  capabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,
1593
1094
  cwd: step.cwd ?? ctx.cwd,
1594
- promptFileStem: step.agent,
1595
1095
  intercomSessionName: ctx.childIntercomTarget,
1096
+ sessionName: childSessionName,
1596
1097
  orchestratorIntercomTarget: ctx.orchestratorIntercomTarget,
1597
1098
  runId: ctx.id,
1598
1099
  childAgentName: step.agent,
1599
1100
  childIndex: ctx.flatIndex,
1600
- parentEventSink: ctx.nestedRoute?.eventSink,
1601
- parentControlInbox: ctx.nestedRoute?.controlInbox,
1602
- parentRootRunId: ctx.nestedRoute?.rootRunId,
1603
- parentCapabilityToken: ctx.nestedRoute?.capabilityToken,
1101
+ nestedRoute: ctx.nestedRoute,
1604
1102
  runFanoutBudget: ctx.runFanoutBudget ? {
1605
1103
  ...ctx.runFanoutBudget,
1606
1104
  ...(step.runFanoutPath ? { parentPath: `${ctx.runFanoutBudget.parentPath ? `${ctx.runFanoutBudget.parentPath}/` : ""}${step.runFanoutPath}` } : {}),
1607
1105
  } : undefined,
1608
- steerInboxDir: ctx.steerInboxDir,
1609
- steerCapabilityPath: ctx.steerCapabilityPath,
1610
- steerAckDir: ctx.steerAckDir,
1611
1106
  structuredOutput: effectiveStructuredOutput,
1612
1107
  toolBudget: step.toolBudget,
1613
1108
  permissionRules: step.permissionRules,
1109
+ projectTrusted: step.projectTrusted,
1110
+ trustedProjectCwd: step.trustedProjectCwd,
1111
+ sandbox: step.sandbox,
1614
1112
  permissionAuditPath: step.permissionRules && ctx.artifactsDir
1615
1113
  ? path.join(ctx.artifactsDir, "permission-audit", `${ctx.id}-${ctx.flatIndex}.jsonl`)
1616
1114
  : undefined,
1617
1115
  childWatchdog,
1116
+ watchdogStatus: (event) => watchdogSink?.(event),
1618
1117
  waitToolEnabled: step.waitToolEnabled,
1118
+ waitToolDefaultTimeoutMs: step.waitToolDefaultTimeoutMs,
1619
1119
  thinkingCeiling: step.thinkingCeiling,
1620
- extensionBindings,
1120
+ maxSubagentDepth: step.maxSubagentDepth,
1121
+ inherited: ctx.inheritedChildRuntime,
1122
+ host: "runner",
1621
1123
  }));
1124
+ if (effectiveStructuredOutput && launch.config.structuredOutput) {
1125
+ // The runner reads the value back from the runtime's files after the run.
1126
+ launch.config.structuredOutput.capture = createStructuredOutputFileCapture(effectiveStructuredOutput);
1127
+ }
1128
+ const { warnings, capabilityAudit: attemptCapabilityAudit } = launch;
1622
1129
  if (!launchWarningsEmitted && warnings.length > 0) {
1623
1130
  for (const warning of warnings) console.warn(`[pi-subagents] ${warning}`);
1624
1131
  launchWarningsEmitted = true;
@@ -1626,6 +1133,8 @@ async function runSingleStepInner(
1626
1133
  if (step.definitionDigest) {
1627
1134
  const toolPlan = resolvedTaskToolPlan ?? resolvePiLaunchToolPlan(omitUndefinedProperties({
1628
1135
  tools: step.tools,
1136
+ excludeTools: step.excludeTools,
1137
+ allowNestedSubagents: step.allowNestedSubagents,
1629
1138
  extensions: step.extensions,
1630
1139
  subagentOnlyExtensions: step.subagentOnlyExtensions,
1631
1140
  fast: step.fast,
@@ -1636,8 +1145,9 @@ async function runSingleStepInner(
1636
1145
  requireReadTool: Boolean(step.skills?.length),
1637
1146
  structuredOutput: Boolean(effectiveStructuredOutput),
1638
1147
  capabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,
1639
- inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
1148
+ inheritedCapabilityCeiling: ctx.inheritedChildRuntime?.capabilityCeiling,
1640
1149
  permissionRules: step.permissionRules,
1150
+ sandbox: step.sandbox,
1641
1151
  }));
1642
1152
  launchResolvedExtensions = projectLaunchResolvedChildExtensions(toolPlan);
1643
1153
  actualLaunchContractDigest = launchBindingDigest(omitUndefinedProperties({
@@ -1648,12 +1158,15 @@ async function runSingleStepInner(
1648
1158
  ...(step.fast !== undefined ? { fast: step.fast } : {}),
1649
1159
  ...(resolveEffectiveThinking(candidate, step.thinking) ? { thinking: resolveEffectiveThinking(candidate, step.thinking) } : {}),
1650
1160
  ...(step.thinkingCeiling ? { thinkingCeiling: step.thinkingCeiling } : {}),
1651
- systemPrompt: appendTurnBudgetSystemPrompt(step.systemPrompt ?? "", ctx.turnBudget),
1161
+ systemPrompt: step.systemPrompt ?? "",
1652
1162
  systemPromptMode: step.systemPromptMode,
1653
1163
  inheritProjectContext: step.inheritProjectContext,
1164
+ inheritGlobalContext: step.inheritGlobalContext,
1654
1165
  inheritSkills: step.inheritSkills,
1166
+ sandbox: step.sandbox,
1655
1167
  skills: step.skills,
1656
1168
  tools: toolPlan.effectiveToolAllowlist,
1169
+ ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
1657
1170
  extensions: toolPlan.extensionArgs,
1658
1171
  mcpDirectTools: toolPlan.effectiveMcpTools,
1659
1172
  ...(step.outputPath ? { outputPath: step.outputPath } : {}),
@@ -1663,71 +1176,55 @@ async function runSingleStepInner(
1663
1176
  }));
1664
1177
  }
1665
1178
  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,
1179
+ // Each attempt rewrites the step output log; synchronous appends keep a
1180
+ // retried attempt from interleaving with the previous attempt's flush.
1181
+ fs.writeFileSync(ctx.outputFile, "", "utf-8");
1182
+ const run = await runChildSession(omitUndefinedProperties({
1183
+ factory: ctx.childSessions,
1184
+ launch,
1185
+ prompt: `Task: ${attemptTask}`,
1186
+ childWatchdog,
1187
+ childEventContext: { runId: ctx.id, stepIndex: ctx.flatIndex, agent: step.agent },
1188
+ appendChildEvent: (event) => appendDiagnosticJsonl(eventsPath, JSON.stringify(event), typeof event.type === "string" ? event.type : undefined),
1189
+ writeOutputLine: (line) => {
1190
+ try {
1191
+ fs.appendFileSync(ctx.outputFile, `${line}\n`, "utf-8");
1192
+ } catch {
1193
+ // The output log is observability only.
1194
+ }
1195
+ ctx.orcaProgressTab?.append(`${line}\n`);
1196
+ },
1197
+ registerInterrupt: ctx.registerInterrupt,
1198
+ registerTimeout: ctx.registerTimeout,
1199
+ registerStop: ctx.registerStop,
1200
+ registerSteer: ctx.registerSteer,
1201
+ registerWatchdogStatus: (sink) => { watchdogSink = sink; },
1202
+ timeoutMessage: ctx.timeoutMessage,
1203
+ stopMessage: ctx.stopMessage,
1204
+ onChildEvent: ctx.onChildEvent,
1678
1205
  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,
1206
+ toolTimeoutMs: ctx.toolTimeoutMs,
1207
+ runDeadlineAt: ctx.deadlineAt,
1688
1208
  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)
1209
+ modelVerificationRegistry: step.modelVerificationRegistry,
1210
+ mutationTools: step.mutationTools,
1211
+ }));
1212
+ const toolDiagnostic = run.exitCode === 0 && !run.error ? launch.capture.toolDiagnostic() : undefined;
1213
+ const toolAvailabilityError = toolDiagnostic ? formatChildToolDiagnostic(toolDiagnostic) : undefined;
1214
+ const runtimeAcknowledgedExtensions = launch.capture.runtimeAcknowledgedExtensions();
1215
+ const midToolExitError = run.currentTool
1216
+ && isOrdinaryToolForMidToolExit(run.currentTool)
1217
+ && !run.interrupted
1218
+ && !run.timedOut
1219
+ && !run.stopped
1220
+ && !toolAvailabilityError
1221
+ ? formatMidToolExitError({ toolName: run.currentTool })
1723
1222
  : undefined;
1724
- const runtimeAcknowledgedExtensions = readRuntimeAcknowledgedExtensions(runtimeAcknowledgedExtensionsPath);
1725
- cleanupTempDir(tempDir);
1726
1223
 
1727
1224
  let structuredOutput: unknown;
1728
1225
  let structuredError: string | undefined;
1729
1226
  let validatedStructuredOutput = false;
1730
- if (effectiveStructuredOutput && run.exitCode === 0 && !run.error && !toolAvailabilityError) {
1227
+ if (effectiveStructuredOutput && run.exitCode === 0 && !run.error && !toolAvailabilityError && !midToolExitError) {
1731
1228
  if (!run.structuredOutputToolInvoked) {
1732
1229
  structuredError = MISSING_STRUCTURED_OUTPUT_CALL_ERROR;
1733
1230
  } else {
@@ -1749,79 +1246,82 @@ async function runSingleStepInner(
1749
1246
  const errorMessages = validatedStructuredOutput
1750
1247
  ? run.messages.slice(run.structuredOutputMessageStartIndex ?? run.messages.length)
1751
1248
  : run.messages;
1752
- const hiddenError = run.exitCode === 0 && !run.error && !toolAvailabilityError && !structuredError
1249
+ const hiddenError = run.exitCode === 0 && !run.error && !toolAvailabilityError && !structuredError && !midToolExitError
1753
1250
  ? detectSubagentError(errorMessages)
1754
1251
  : null;
1252
+ const terminalEmptyAfterUsefulWork = !validatedStructuredOutput
1253
+ && hasEmptyTerminalAssistantResponse(run.messages)
1254
+ && (run.toolCount > 0 || Boolean(run.finalOutput.trim()));
1255
+ // A startup guard can block the child's first turn, which leaves no message to
1256
+ // inspect; prefer the reason the blocked child published for the launcher.
1257
+ const sandboxStartupDiagnostic = readSandboxStartupDiagnostic(launch.sandboxDiagnosticsPath);
1755
1258
  const emptyOutputError = run.exitCode === 0
1756
1259
  && !run.error
1757
1260
  && !toolAvailabilityError
1758
1261
  && !structuredError
1759
- && !run.finalOutput.trim()
1760
1262
  && !validatedStructuredOutput
1263
+ && (!run.finalOutput.trim() || terminalEmptyAfterUsefulWork)
1761
1264
  && (!hiddenError?.hasError || hasEmptyTerminalAssistantResponse(run.messages))
1762
- ? "Subagent produced no output (possible model cold-start or empty response)."
1265
+ ? sandboxStartupDiagnostic?.reason ?? formatEmptyTerminalAssistantResponseError(run.messages)
1763
1266
  : undefined;
1267
+ const startupBlocked = sandboxStartupDiagnostic !== undefined && emptyOutputError === sandboxStartupDiagnostic.reason;
1268
+ if (startupBlocked) clearSandboxStartupDiagnostic(launch.sandboxDiagnosticsPath);
1764
1269
  const completionGuardEnabled = isAgentContractV1(step.agentContract) ? step.completionGuard === true : step.completionGuard !== false;
1765
1270
  const completionToolPlan = resolvedTaskToolPlan;
1271
+ const completionTools = completionToolPlan ? (completionToolPlan.explicitToolAllowlist ? completionToolPlan.effectiveToolAllowlist : undefined) : step.tools;
1766
1272
  const mutationEvidence = collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
1767
1273
  finalMutationEvidence = mutationEvidence;
1768
1274
  const completionMutationEvidence = ctx.trackedMutationEvidenceForCompletionGuard === false ? undefined : mutationEvidence;
1769
- const completionGuard = run.exitCode === 0 && !run.error && !structuredError && !hiddenError?.hasError && !emptyOutputError && completionGuardEnabled
1275
+ const completionGuard = run.exitCode === 0 && !run.error && !structuredError && !hiddenError?.hasError && !midToolExitError && !emptyOutputError && completionGuardEnabled
1770
1276
  ? evaluateCompletionMutationGuard(omitUndefinedProperties({
1771
1277
  agent: step.agent,
1772
1278
  task: taskForCompletionGuard,
1773
1279
  messages: run.messages,
1774
- tools: completionToolPlan ? (completionToolPlan.explicitToolAllowlist ? completionToolPlan.effectiveToolAllowlist : undefined) : step.tools,
1280
+ tools: completionTools,
1775
1281
  mcpDirectTools: completionToolPlan?.effectiveMcpTools ?? step.mcpDirectTools,
1282
+ mutationTools: step.mutationTools,
1776
1283
  toolAvailabilityError,
1777
1284
  mutationEvidence: completionMutationEvidence,
1778
1285
  }))
1779
1286
  : undefined;
1780
1287
  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."
1288
+ const completionEvidence = planCompletionEvidence({
1289
+ guard: completionGuard,
1290
+ completionGuardEnabled,
1291
+ mutationCapable: hasMutationToolCapability(completionTools, completionToolPlan?.effectiveMcpTools ?? step.mcpDirectTools),
1292
+ implementationMutationExpected: expectsImplementationMutation(step.agent, taskForCompletionGuard),
1293
+ mutationAttemptObserved,
1294
+ mutationEvidence: completionMutationEvidence,
1295
+ agentContractV1: isAgentContractV1(step.agentContract),
1296
+ });
1297
+ const finalOutputHasPersistableFileContent = run.exitCode === 0 && !run.error && !emptyOutputError && Boolean(stripAcceptanceReport(run.finalOutput).trim());
1298
+ const requiredOutput = step.outputMode === "file-only" && step.outputPath
1299
+ ? { kind: "file-only" as const, path: step.outputPath, missing: !fs.existsSync(step.outputPath) && !finalOutputHasPersistableFileContent }
1300
+ : effectiveStructuredOutput
1301
+ ? { kind: "structured" as const, path: effectiveStructuredOutput.outputPath, missing: !fs.existsSync(effectiveStructuredOutput.outputPath) }
1795
1302
  : undefined;
1796
- const effectiveExitCode = toolAvailabilityError || (completionGuardTriggered && !isAgentContractV1(step.agentContract)) || structuredError || emptyOutputError
1303
+ finalRequiredOutputMissing = requiredOutput?.missing;
1304
+ const missingRequiredOutputError = formatRequiredOutputError(requiredOutput);
1305
+ const missingRequiredOutputAfterMutation = Boolean(missingRequiredOutputError) && (mutationAttemptObserved || Boolean(mutationEvidence.changedFiles.length));
1306
+ const effectiveExitCode = toolAvailabilityError || completionEvidence.legacyFailureError || midToolExitError || structuredError || emptyOutputError || missingRequiredOutputError
1797
1307
  ? 1
1798
1308
  : hiddenError?.hasError
1799
1309
  ? (hiddenError.exitCode ?? 1)
1800
1310
  : run.error && run.exitCode === 0
1801
1311
  ? 1
1802
1312
  : 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
- );
1313
+ const underlyingError = toolAvailabilityError
1314
+ ?? midToolExitError
1315
+ ?? structuredError
1316
+ ?? run.error
1317
+ ?? emptyOutputError
1318
+ ?? (missingRequiredOutputAfterMutation ? missingRequiredOutputError : undefined)
1319
+ ?? (hiddenError?.hasError
1320
+ ? hiddenError.details
1321
+ ? `${hiddenError.errorType} failed (exit ${effectiveExitCode}): ${hiddenError.details}`
1322
+ : `${hiddenError.errorType} failed with exit code ${effectiveExitCode}`
1323
+ : undefined);
1324
+ const error = underlyingError ?? missingRequiredOutputError ?? completionEvidence.legacyFailureError;
1825
1325
  const attempt: ModelAttempt = omitUndefinedProperties({
1826
1326
  model: candidate ?? run.model ?? step.model ?? "default",
1827
1327
  success: effectiveExitCode === 0 && !error,
@@ -1830,8 +1330,8 @@ async function runSingleStepInner(
1830
1330
  usage: run.usage,
1831
1331
  });
1832
1332
  modelAttempts.push(attempt);
1833
- if (candidate && startupAttemptIndex === 0) attemptedModels.push(candidate);
1834
- completionGuardTriggeredFinal = completionGuardTriggered;
1333
+ if (!recoveringAbort && candidate) attemptedModels.push(candidate);
1334
+ completionGuardTriggeredFinal = completionEvidence.guardTriggered && !underlyingError && !missingRequiredOutputError;
1835
1335
  finalOutputSnapshot = outputSnapshot;
1836
1336
  if (step.toolBudget) {
1837
1337
  const toolMessages = run.messages.filter((message) => message.role === "toolResult");
@@ -1839,57 +1339,49 @@ async function runSingleStepInner(
1839
1339
  toolBudgetBlocked = Boolean(blockedMessage);
1840
1340
  toolBudget = toolBudgetState(step.toolBudget, toolMessages.length, blockedMessage ? (blockedMessage as { toolName?: string }).toolName : undefined);
1841
1341
  }
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,
1342
+ const settlementDiagnostic = projectSettlementDiagnostic(completionEvidence, {
1343
+ terminalFailed: effectiveExitCode !== 0,
1344
+ finalTextPresent: Boolean(stripAcceptanceReport(run.finalOutput).trim()),
1345
+ mutationObserved: mutationEvidence.attemptedMutation,
1346
+ requiredOutput,
1347
+ afterCompactionSettlement: run.afterCompactionSettlement === true,
1348
+ });
1349
+ const fileMutationEffect = completionEvidence.fileMutation ?? (missingRequiredOutputAfterMutation ? { status: "observed" as const, expected: completionEvidence.mutationExpected, attempted: true, evidence: mutationEvidence } : undefined);
1350
+ 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;
1351
+ const abortRecovery = !attempt.success ? planAbortRecovery({
1352
+ messages: run.messages,
1849
1353
  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,
1354
+ sessionAvailable: Boolean(step.sessionFile && fs.existsSync(step.sessionFile)),
1355
+ alreadyResumed: abortRecoveryAttempted,
1356
+ stopped: run.stopped || ctx.stopSignal?.aborted || ctx.skipAcceptance?.(),
1858
1357
  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;
1358
+ timedOut: run.timedOut || ctx.timeoutSignal?.aborted,
1359
+ toolBudgetExhausted: run.toolBudgetBlocked || toolBudgetBlocked,
1360
+ usageBudgetExhausted: ctx.usageBudgetExhausted?.(),
1361
+ structuredOutputFailed: Boolean(structuredError),
1362
+ acceptanceFailed: false,
1363
+ currentTool: run.currentTool,
1364
+ afterCompactionSettlement: run.afterCompactionSettlement,
1365
+ }) : undefined;
1366
+ if (abortRecovery?.action === "settle" && abortRecovery.diagnostic) {
1367
+ attempt.error = attempt.error
1368
+ ? `${abortRecovery.diagnostic}\n${attempt.error.slice(0, 8_000)}`
1369
+ : abortRecovery.diagnostic;
1370
+ if (finalResult) finalResult.abortRecoveryDiagnostic = abortRecovery.diagnostic;
1881
1371
  }
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;
1372
+ if (run.stopped || run.timedOut || ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break modelAttemptsLoop;
1373
+ if (abortRecovery?.action === "settle" && abortRecovery.diagnostic) break modelAttemptsLoop;
1374
+ if (attempt.success) break modelAttemptsLoop;
1375
+ if (recoveringAbort) break modelAttemptsLoop;
1376
+ if (abortRecovery?.action === "resume") {
1377
+ abortRecoveryAttempted = true;
1378
+ nextAttemptTask = abortRecovery.prompt;
1379
+ attemptNotes.push("[abort-recovery] provider/transport abort after useful progress; resuming the retained child session once.");
1380
+ continue;
1891
1381
  }
1892
- const retryableModelFailure = isRetryableModelFailure(error);
1382
+ if (completionEvidence.guardTriggered) break modelAttemptsLoop;
1383
+
1384
+ const retryableModelFailure = isRetryableModelFailureAttempt({ error, messages: run.messages, toolCount: run.toolCount, ...(startupBlocked ? { startupBlocked: true } : {}) });
1893
1385
  if (retryableModelFailure) recordRetryableModelFailure(candidate ?? run.model ?? step.model, error);
1894
1386
  if (isContextOverflow(error)) {
1895
1387
  contextOverflow = true;
@@ -1899,14 +1391,19 @@ async function runSingleStepInner(
1899
1391
  if (!retryableModelFailure || modelIndex === candidates.length - 1) break modelAttemptsLoop;
1900
1392
  attemptNotes.push(formatModelAttemptNote(attempt, candidates[modelIndex + 1]));
1901
1393
  modelIndex += 1;
1902
- startupAttemptIndex = 0;
1903
1394
  }
1904
1395
 
1905
1396
  const rawOutput = finalResult?.finalOutput ?? "";
1906
1397
  const outputForPersistence = stripAcceptanceReport(rawOutput);
1907
1398
  const resolvedOutput = step.outputPath && finalResult?.exitCode === 0
1908
- ? resolveSingleOutput(step.outputPath, outputForPersistence, finalOutputSnapshot)
1399
+ ? resolveSingleOutput(step.outputPath, outputForPersistence, finalOutputSnapshot, step.outputClaimPath)
1909
1400
  : { fullOutput: outputForPersistence };
1401
+ if (resolvedOutput.fatalError) {
1402
+ if (finalResult) {
1403
+ finalResult.exitCode = 1;
1404
+ finalResult.error = finalResult.error ? `${finalResult.error}\n${resolvedOutput.saveError}` : resolvedOutput.saveError;
1405
+ }
1406
+ }
1910
1407
  const output = stripAcceptanceReport(resolvedOutput.fullOutput);
1911
1408
  const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, output) : undefined;
1912
1409
  let outputForSummary = output;
@@ -1915,21 +1412,13 @@ async function runSingleStepInner(
1915
1412
  }
1916
1413
  if (finalResult?.stopped && !outputForSummary.trim()) {
1917
1414
  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
1415
  }
1927
1416
  const outputForAcceptance = rawOutput;
1928
1417
  const childWrittenOutput = step.outputPath
1929
1418
  ? extractChildWrittenOutput(finalResult?.messages, step.outputPath, step.cwd ?? ctx.cwd)
1930
1419
  : undefined;
1931
1420
  const outputState: SubagentOutputState = finalResult?.outputState === "present"
1932
- || (finalResult as (RunPiStreamingResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput !== undefined
1421
+ || (finalResult as (RunChildSessionResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput !== undefined
1933
1422
  || Boolean(childWrittenOutput?.trim())
1934
1423
  ? "present"
1935
1424
  : resolvedOutput.savedPath
@@ -1939,6 +1428,7 @@ async function runSingleStepInner(
1939
1428
  ? buildTimeoutRecoverySummary({
1940
1429
  termination: "timed-out",
1941
1430
  evidence: finalMutationEvidence,
1431
+ requiredOutputMissing: finalRequiredOutputMissing,
1942
1432
  currentTool: finalResult?.currentTool,
1943
1433
  currentToolArgs: finalResult?.currentToolArgs,
1944
1434
  currentPath: finalResult?.currentPath,
@@ -1960,14 +1450,14 @@ async function runSingleStepInner(
1960
1450
  saveError: resolvedOutput.saveError,
1961
1451
  }));
1962
1452
  outputForSummary = finalizedOutput.displayOutput;
1963
- const acceptance = step.effectiveAcceptance && !finalResult?.stopped && !finalResult?.turnBudgetExceeded && !ctx.timeoutSignal?.aborted && !ctx.stopSignal?.aborted && !ctx.skipAcceptance?.()
1453
+ const acceptance = step.effectiveAcceptance && !finalResult?.stopped && !ctx.timeoutSignal?.aborted && !ctx.stopSignal?.aborted && !ctx.skipAcceptance?.()
1964
1454
  ? await evaluateAcceptance(omitUndefinedProperties({
1965
1455
  acceptance: step.effectiveAcceptance,
1966
1456
  output: outputForAcceptance,
1967
1457
  report: structuredAcceptanceReport as import("../../shared/types.ts").AcceptanceReport | undefined,
1968
1458
  reportError: structuredAcceptanceReportError,
1969
1459
  fileOutput: childWrittenOutput !== undefined && step.outputPath
1970
- ? { content: childWrittenOutput, path: step.outputPath, authoritative: step.outputMode === "file-only" }
1460
+ ? { content: childWrittenOutput, path: step.outputPath, authoritative: step.outputMode === "file-only", durable: resolvedOutput.savedPath !== undefined }
1971
1461
  : undefined,
1972
1462
  cwd: step.cwd ?? ctx.cwd,
1973
1463
  signal: combinedAbortSignal([ctx.timeoutSignal, ctx.stopSignal]),
@@ -1975,33 +1465,36 @@ async function runSingleStepInner(
1975
1465
  reportOptional: isAgentContractV1(step.agentContract),
1976
1466
  artifactsDir: ctx.artifactsDir,
1977
1467
  runId: ctx.id,
1468
+ watchdog: finalResult?.watchdog,
1978
1469
  }))
1979
1470
  : undefined;
1980
1471
  const stoppedAfterAcceptance = finalResult?.stopped === true || ctx.stopSignal?.aborted === true;
1981
1472
  const timedOutAfterAcceptance = !stoppedAfterAcceptance && (finalResult?.timedOut === true || ctx.timeoutSignal?.aborted === true);
1982
- const turnBudgetExceeded = finalResult?.turnBudgetExceeded === true;
1983
1473
  const effectiveAcceptance = step.effectiveAcceptance
1984
1474
  ? stoppedAfterAcceptance
1985
1475
  ? buildSkippedAcceptanceLedger(step.effectiveAcceptance, { id: "stopped", message: "Acceptance was not evaluated because the subagent was stopped." })
1986
1476
  : timedOutAfterAcceptance
1987
1477
  ? 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
1478
+ : acceptance
1991
1479
  : undefined;
1992
1480
  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;
1481
+ const acceptanceCanFailRun = acceptanceFailure && effectiveAcceptance?.explicit && (finalResult?.exitCode ?? 1) === 0 && !finalResult?.interrupted && !timedOutAfterAcceptance && !stoppedAfterAcceptance && !isAgentContractV1(step.agentContract);
1482
+ const effectiveFinalExitCode = timedOutAfterAcceptance || stoppedAfterAcceptance ? 1 : acceptanceCanFailRun ? 1 : finalResult?.exitCode ?? 1;
1995
1483
  const intercomDetachReceipt = finalResult?.finalOutput === INTERCOM_DETACH_RECEIPT;
1996
- const effectiveFinalError = stoppedAfterAcceptance
1484
+ const baseFinalError = stoppedAfterAcceptance
1997
1485
  ? ctx.stopMessage ?? "Subagent stopped by user."
1998
1486
  : timedOutAfterAcceptance
1999
1487
  ? finalResult?.error ?? ctx.timeoutMessage ?? "Subagent timed out."
2000
- : turnBudgetExceeded
2001
- ? finalResult?.error ?? (turnBudget ? turnBudgetExceededMessage(turnBudget, turnBudget.turnCount) : "Subagent exceeded turn budget.")
2002
- : acceptanceCanFailRun
1488
+ : acceptanceCanFailRun
2003
1489
  ? (finalResult?.error ? `${finalResult.error}\n${acceptanceFailure}` : acceptanceFailure)
2004
1490
  : finalResult?.error ?? (intercomDetachReceipt ? INTERCOM_DETACH_RECEIPT : undefined);
1491
+ const effectiveFinalError = formatChildFailureDiagnostic({
1492
+ error: baseFinalError,
1493
+ afterCompactionSettlement: effectiveFinalExitCode !== 0 ? finalResult?.afterCompactionSettlement : undefined,
1494
+ abortRecoveryDiagnostic: effectiveFinalExitCode !== 0 ? finalResult?.abortRecoveryDiagnostic : undefined,
1495
+ requiredOutput: effectiveFinalExitCode !== 0 ? finalResult?.effects?.settlementDiagnostic?.requiredOutput : undefined,
1496
+ });
1497
+ const usage = usageFromAttempts(modelAttempts);
2005
1498
 
2006
1499
  const artifactErrors = artifactPaths && ctx.artifactConfig?.enabled !== false
2007
1500
  ? persistStepArtifacts({
@@ -2021,12 +1514,14 @@ async function runSingleStepInner(
2021
1514
  model: finalResult?.model,
2022
1515
  attemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,
2023
1516
  modelAttempts,
1517
+ usage,
2024
1518
  error: effectiveFinalError,
2025
1519
  acceptance: effectiveAcceptance,
2026
1520
  ...(capabilityAudit ? { capabilityCeiling: capabilityAudit.ceiling, capabilityAudit } : {}),
1521
+ sandbox: step.sandbox,
2027
1522
  launchContractDigest: actualLaunchContractDigest,
2028
1523
  launchResolvedExtensions,
2029
- ...((finalResult as (RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }) | undefined)?.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: (finalResult as RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }).runtimeAcknowledgedExtensions } : {}),
1524
+ ...((finalResult as (RunChildSessionResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }) | undefined)?.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: (finalResult as RunChildSessionResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }).runtimeAcknowledgedExtensions } : {}),
2030
1525
  ...(transcriptWriter ? { transcriptPath: artifactPaths.transcriptPath } : {}),
2031
1526
  transcriptError: transcriptWriter?.getError(),
2032
1527
  skills: step.skills,
@@ -2037,49 +1532,49 @@ async function runSingleStepInner(
2037
1532
 
2038
1533
  const result: StepResult & { completionGuardTriggered?: boolean } = omitUndefinedProperties({
2039
1534
  agent: step.agent,
1535
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
2040
1536
  context: step.context,
1537
+ ...(step.sandbox ? { sandbox: step.sandbox } : {}),
2041
1538
  ...(step.agentContract ? { agentContract: step.agentContract } : {}),
2042
1539
  launchContractDigest: actualLaunchContractDigest,
2043
1540
  output: outputForSummary,
2044
1541
  outputState,
2045
1542
  exitCode: effectiveFinalExitCode,
2046
1543
  error: effectiveFinalError,
2047
- protocolError: finalResult?.protocolError,
2048
1544
  sessionFile: step.sessionFile,
2049
1545
  intercomTarget: ctx.childIntercomTarget,
2050
1546
  model: finalResult?.model,
1547
+ thinking: resolveEffectiveThinking(finalResult?.model, step.thinking),
2051
1548
  attemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,
2052
1549
  modelAttempts,
2053
1550
  contextOverflow: contextOverflow || undefined,
2054
1551
  totalCost: costSummaryFromAttempts(modelAttempts),
1552
+ usage,
2055
1553
  artifactPaths,
2056
- outputSaveError: artifactErrors.outputSaveError,
1554
+ outputSaveError: [resolvedOutput.saveError, artifactErrors.outputSaveError].filter(Boolean).join("\n") || undefined,
2057
1555
  metadataSaveError: artifactErrors.metadataSaveError,
2058
1556
  transcriptPath: transcriptWriter ? artifactPaths?.transcriptPath : undefined,
2059
1557
  transcriptError: transcriptWriter?.getError(),
2060
- interrupted: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? false : finalResult?.interrupted,
1558
+ interrupted: timedOutAfterAcceptance || stoppedAfterAcceptance ? false : finalResult?.interrupted,
2061
1559
  timedOut: timedOutAfterAcceptance ? true : finalResult?.timedOut,
2062
1560
  stopped: stoppedAfterAcceptance ? true : finalResult?.stopped,
2063
- processSignal: finalResult?.processSignal,
2064
1561
  timeoutRecovery,
2065
- turnBudget,
2066
- turnBudgetExceeded: turnBudgetExceeded || undefined,
2067
- wrapUpRequested: finalResult?.wrapUpRequested || turnBudget?.outcome === "wrap-up-requested" || turnBudget?.outcome === "termination-deferred" || turnBudgetExceeded || undefined,
2068
1562
  toolBudget,
2069
1563
  toolBudgetBlocked: toolBudgetBlocked || undefined,
2070
1564
  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,
1565
+ ...((finalResult as (RunChildSessionResult & { effects?: import("../../shared/types.ts").EffectsProjection }) | undefined)?.effects ? { effects: (finalResult as RunChildSessionResult & { effects?: import("../../shared/types.ts").EffectsProjection }).effects } : {}),
1566
+ structuredOutput: timedOutAfterAcceptance || stoppedAfterAcceptance ? undefined : (finalResult as (RunChildSessionResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput,
1567
+ structuredOutputPath: timedOutAfterAcceptance || stoppedAfterAcceptance ? undefined : effectiveStructuredOutput?.outputPath,
1568
+ structuredOutputSchemaPath: timedOutAfterAcceptance || stoppedAfterAcceptance ? undefined : effectiveStructuredOutput?.schemaPath,
2075
1569
  acceptance: effectiveAcceptance,
2076
1570
  watchdog: finalResult?.watchdog,
2077
1571
  ...(capabilityAudit ? { capabilityCeiling: capabilityAudit.ceiling, capabilityAudit } : {}),
2078
1572
  launchResolvedExtensions,
2079
- ...((finalResult as (RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }) | undefined)?.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: (finalResult as RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }).runtimeAcknowledgedExtensions } : {}),
2080
- writerProcesses,
2081
- writerAttemptCount,
1573
+ ...((finalResult as (RunChildSessionResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }) | undefined)?.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: (finalResult as RunChildSessionResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }).runtimeAcknowledgedExtensions } : {}),
2082
1574
  });
1575
+ // SAFETY: `result` is the step result assembled above for this same run; agent-contract
1576
+ // projections are attached to that object and re-narrowed to its own type, so the
1577
+ // assertion only re-states the shape the builders already produced here.
2083
1578
  return isAgentContractV1(step.agentContract) ? attachContractProjections(result as unknown as import("../../shared/types.ts").SingleResult) as unknown as typeof result : result;
2084
1579
  }
2085
1580
 
@@ -2098,13 +1593,7 @@ type RunnerStatusStep = NonNullable<AsyncStatus["steps"]>[number] & {
2098
1593
 
2099
1594
  function externalRunnerStatus(runner: SubagentStep["runner"]): ExternalCliRunnerStatus | ExternalJobRunnerStatus | undefined {
2100
1595
  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
- };
1596
+ return resolveExternalCliRunnerStatus(runner);
2108
1597
  }
2109
1598
  if (runner?.type === "external-job") {
2110
1599
  return {
@@ -2151,6 +1640,13 @@ function requiredStatusStep(statusPayload: RunnerStatusPayload, index: number):
2151
1640
  return step;
2152
1641
  }
2153
1642
 
1643
+ function setStatusWorktreeReference(statusStep: RunnerStatusStep, worktree: WorktreeSetup["worktrees"][number]): void {
1644
+ statusStep.worktreePath = worktree.path;
1645
+ statusStep.branch = worktree.branch;
1646
+ if (worktree.provider) statusStep.provider = worktree.provider;
1647
+ if (worktree.naming) statusStep.naming = worktree.naming;
1648
+ }
1649
+
2154
1650
  function markParallelGroupSetupFailure(input: {
2155
1651
  statusPayload: RunnerStatusPayload;
2156
1652
  results: StepResult[];
@@ -2229,6 +1725,18 @@ function markParallelGroupRunning(input: {
2229
1725
  }));
2230
1726
  }
2231
1727
 
1728
+ function bindWorktreeCwd(step: SubagentStep, worktreeCwd: string): SubagentStep {
1729
+ const bind = <T extends string | null | undefined>(value: T): T => value === null || value === undefined ? value : value.replaceAll(WORKTREE_AGENT_CWD_PLACEHOLDER, worktreeCwd) as T;
1730
+ return {
1731
+ ...step,
1732
+ task: bind(step.task) ?? step.task,
1733
+ ...(step.systemPrompt !== undefined ? { systemPrompt: bind(step.systemPrompt) } : {}),
1734
+ ...(step.outputPath !== undefined ? { outputPath: bind(step.outputPath) } : {}),
1735
+ ...(step.launchBindingTask !== undefined ? { launchBindingTask: bind(step.launchBindingTask) } : {}),
1736
+ ...(step.requestedCwd !== undefined ? { requestedCwd: bind(step.requestedCwd) } : {}),
1737
+ };
1738
+ }
1739
+
2232
1740
  function prepareParallelTaskRun(
2233
1741
  task: SubagentStep,
2234
1742
  cwd: string,
@@ -2237,8 +1745,9 @@ function prepareParallelTaskRun(
2237
1745
  ): { taskForRun: SubagentStep; taskCwd: string } {
2238
1746
  if (!worktreeSetup) return { taskForRun: task, taskCwd: cwd };
2239
1747
  const { cwd: _taskCwd, ...taskForRun } = task;
1748
+ const boundTask = bindWorktreeCwd(taskForRun, worktreeSetup.worktrees[taskIndex]!.agentCwd);
2240
1749
  return {
2241
- taskForRun,
1750
+ taskForRun: boundTask,
2242
1751
  taskCwd: worktreeSetup.worktrees[taskIndex]!.agentCwd,
2243
1752
  };
2244
1753
  }
@@ -2279,6 +1788,25 @@ function resolveAsyncStepTranscriptPath(input: {
2279
1788
 
2280
1789
  type SingleStepResult = Awaited<ReturnType<typeof runSingleStep>>;
2281
1790
 
1791
+ function missingRequiredOutputAfterUsefulMutation(result: SingleStepResult): boolean {
1792
+ const effects = result.effects;
1793
+ return effects?.settlementDiagnostic?.requiredOutput?.missing === true
1794
+ && (effects.settlementDiagnostic.mutation.attempted || effects.fileMutation?.attempted === true || Boolean(effects.fileMutation?.evidence?.changedFiles.length));
1795
+ }
1796
+
1797
+ function partialExecutionWithUsefulMutation(result: SingleStepResult): boolean {
1798
+ const fileMutation = result.effects?.fileMutation;
1799
+ return result.execution?.status === "partial" && (fileMutation?.attempted === true || Boolean(fileMutation?.evidence?.changedFiles.length));
1800
+ }
1801
+
1802
+ function partialEvidenceResult(result: SingleStepResult): boolean {
1803
+ return missingRequiredOutputAfterUsefulMutation(result) || partialExecutionWithUsefulMutation(result);
1804
+ }
1805
+
1806
+ function concreteFailureResult(result: SingleStepResult): boolean {
1807
+ return result.success === false && !partialEvidenceResult(result);
1808
+ }
1809
+
2282
1810
  function combinedAbortSignal(signals: Array<AbortSignal | undefined>): AbortSignal | undefined {
2283
1811
  const activeSignals = signals.filter((signal): signal is AbortSignal => Boolean(signal));
2284
1812
  if (activeSignals.length === 0) return undefined;
@@ -2339,7 +1867,7 @@ async function runSingleStepWithTimeout(
2339
1867
 
2340
1868
  async function runSubagent(
2341
1869
  config: SubagentRunConfig,
2342
- onWriterProcess?: (writer: { state: "none" | "spawning" } | { state: "running"; pid: number }) => void,
1870
+ childSessions: ChildSessionFactory,
2343
1871
  ): Promise<void> {
2344
1872
  const { id, steps, resultPath, cwd, placeholder, taskIndex, totalTasks, maxOutput, artifactsDir, artifactConfig } =
2345
1873
  config;
@@ -2350,6 +1878,8 @@ async function runSubagent(
2350
1878
  const overallStartTime = Date.now();
2351
1879
  const shareEnabled = config.share === true;
2352
1880
  const asyncDir = config.asyncDir;
1881
+ const handoffWorkflowKey = config.workflowKey;
1882
+ const handoffChildRunId = handoffWorkflowKey ? id : undefined;
2353
1883
  const statusPath = path.join(asyncDir, "status.json");
2354
1884
  const eventsPath = path.join(asyncDir, "events.jsonl");
2355
1885
  const logPath = path.join(asyncDir, `subagent-log-${id}.md`);
@@ -2357,17 +1887,17 @@ async function runSubagent(
2357
1887
  const activeChildInterrupts = new Map<number, () => void>();
2358
1888
  const activeChildTimeouts = new Map<number, () => void>();
2359
1889
  const activeChildStops = new Map<number, () => void>();
1890
+ const activeChildSteers = new Map<number, StepSteerHandler>();
1891
+ /** Steers routed to a running step before its session was created. */
1892
+ const queuedStepSteers = new Map<number, SteerRequest[]>();
2360
1893
  const childStopRequests = new Map<number, { childId: string; requestedAt: number }>();
2361
- const activeChildTurnBudgetAborts = new Map<number, (message: string, state?: TurnBudgetState) => void>();
2362
1894
  const pendingStepSteers: SteerRequest[] = [];
2363
- const steeringCapabilities = new Map<number, SteerCapability>();
2364
1895
  let interrupted = false;
2365
1896
  let currentActivityState: ActivityState | undefined;
2366
1897
  let activityTimer: NodeJS.Timeout | undefined;
2367
1898
  let timeoutTimer: NodeJS.Timeout | undefined;
2368
1899
  let timedOut = false;
2369
1900
  let stopped = false;
2370
- let turnBudgetExceeded = false;
2371
1901
  let usageBudgetExceeded = false;
2372
1902
  const timeoutMessage = config.timeoutMs !== undefined ? `Subagent timed out after ${config.timeoutMs}ms.` : undefined;
2373
1903
  const stopMessage = "Subagent stopped by user.";
@@ -2388,8 +1918,11 @@ async function runSubagent(
2388
1918
  for (const task of step.parallel) {
2389
1919
  const taskFlatIndex = flatStepCount;
2390
1920
  const transcriptPath = resolveAsyncStepTranscriptPath(omitUndefinedProperties({ artifactsDir, artifactConfig, runId: id, agent: task.agent, flatIndex: taskFlatIndex, flatStepCount: initialFlatStepCount }));
1921
+ const taskSessionName = task.sessionName ?? deriveChildSessionName({ agent: task.agent, task: task.task, label: task.label });
2391
1922
  initialStatusSteps.push(omitUndefinedProperties({
2392
1923
  agent: task.agent,
1924
+ ...(task.lane ? { lane: task.lane } : config.lane ? { lane: config.lane } : {}),
1925
+ ...(taskSessionName ? { sessionName: taskSessionName } : {}),
2393
1926
  ...(externalRunnerStatus(task.runner) ? { runner: externalRunnerStatus(task.runner) } : {}),
2394
1927
  ...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),
2395
1928
  ...(task.context ? { context: task.context } : {}),
@@ -2398,6 +1931,7 @@ async function runSubagent(
2398
1931
  outputName: task.outputName,
2399
1932
  structured: task.structured,
2400
1933
  ...(task.agentContract ? { agentContract: task.agentContract } : {}),
1934
+ ...(task.sandbox ? { sandbox: task.sandbox } : {}),
2401
1935
  ...(task.launchContractDigest ? { launchContractDigest: task.launchContractDigest } : {}),
2402
1936
  ...(task.launchResolvedExtensions ? { launchResolvedExtensions: task.launchResolvedExtensions } : {}),
2403
1937
  ...(task.capabilityCeiling ? { capabilityCeiling: task.capabilityCeiling } : {}),
@@ -2408,6 +1942,7 @@ async function runSubagent(
2408
1942
  ...(transcriptPath ? { transcriptPath } : {}),
2409
1943
  skills: task.skills,
2410
1944
  model: task.model,
1945
+ ...(task.contextLimit !== undefined ? { contextLimit: task.contextLimit } : {}),
2411
1946
  thinking: task.thinking,
2412
1947
  attemptedModels: task.modelCandidates && task.modelCandidates.length > 0 ? task.modelCandidates : task.model ? [task.model] : undefined,
2413
1948
  recentTools: [],
@@ -2425,7 +1960,9 @@ async function runSubagent(
2425
1960
  label: step.label ?? step.parallel.label ?? `Dynamic fanout (${step.collect.as})`,
2426
1961
  outputName: step.collect.as,
2427
1962
  structured: Boolean(step.collect.outputSchema),
1963
+ ...(step.parallel.contextLimit !== undefined ? { contextLimit: step.parallel.contextLimit } : {}),
2428
1964
  ...(step.agentContract ? { agentContract: step.agentContract } : {}),
1965
+ ...(step.parallel.sandbox ? { sandbox: step.parallel.sandbox } : {}),
2429
1966
  ...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
2430
1967
  ...(step.thinkingCeiling ? { thinkingCeiling: step.thinkingCeiling } : {}),
2431
1968
  status: "pending",
@@ -2437,8 +1974,11 @@ async function runSubagent(
2437
1974
  } else {
2438
1975
  const stepFlatIndex = flatStepCount;
2439
1976
  const transcriptPath = resolveAsyncStepTranscriptPath(omitUndefinedProperties({ artifactsDir, artifactConfig, runId: id, agent: step.agent, flatIndex: stepFlatIndex, flatStepCount: initialFlatStepCount }));
1977
+ const stepSessionName = step.sessionName ?? deriveChildSessionName({ agent: step.agent, task: step.task, label: step.label });
2440
1978
  initialStatusSteps.push(omitUndefinedProperties({
2441
1979
  agent: step.agent,
1980
+ ...(step.lane ? { lane: step.lane } : config.lane ? { lane: config.lane } : {}),
1981
+ ...(stepSessionName ? { sessionName: stepSessionName } : {}),
2442
1982
  ...(externalRunnerStatus(step.runner) ? { runner: externalRunnerStatus(step.runner) } : {}),
2443
1983
  ...(statusStepDescription(step.task) ? { description: statusStepDescription(step.task) } : {}),
2444
1984
  ...(step.context ? { context: step.context } : {}),
@@ -2447,6 +1987,7 @@ async function runSubagent(
2447
1987
  outputName: step.outputName,
2448
1988
  structured: step.structured,
2449
1989
  ...(step.agentContract ? { agentContract: step.agentContract } : {}),
1990
+ ...(step.sandbox ? { sandbox: step.sandbox } : {}),
2450
1991
  ...(step.launchContractDigest ? { launchContractDigest: step.launchContractDigest } : {}),
2451
1992
  ...(step.launchResolvedExtensions ? { launchResolvedExtensions: step.launchResolvedExtensions } : {}),
2452
1993
  ...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
@@ -2457,6 +1998,7 @@ async function runSubagent(
2457
1998
  ...(transcriptPath ? { transcriptPath } : {}),
2458
1999
  skills: step.skills,
2459
2000
  model: step.model,
2001
+ ...(step.contextLimit !== undefined ? { contextLimit: step.contextLimit } : {}),
2460
2002
  thinking: step.thinking,
2461
2003
  attemptedModels: step.modelCandidates && step.modelCandidates.length > 0 ? step.modelCandidates : step.model ? [step.model] : undefined,
2462
2004
  recentTools: [],
@@ -2473,6 +2015,7 @@ async function runSubagent(
2473
2015
  step.processTerminal = { version: 1, state: "pending", runId: id, runnerProcessInstanceId: config.runnerProcessInstanceId };
2474
2016
  }
2475
2017
  }
2018
+ const initialSandbox = commonSandboxProfile(initialStatusSteps);
2476
2019
  const initialAgentLabel = initialStatusSteps.length === 1
2477
2020
  ? initialStatusSteps[0]!.agent
2478
2021
  : (config.resultMode ?? (flatSteps.length > 1 ? "chain" : "single")) === "parallel"
@@ -2500,7 +2043,6 @@ async function runSubagent(
2500
2043
  lastUpdate: overallStartTime,
2501
2044
  ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),
2502
2045
  ...(config.deadlineAt !== undefined ? { deadlineAt: config.deadlineAt } : {}),
2503
- ...(config.turnBudget ? { turnBudget: initialTurnBudgetState(config.turnBudget) } : {}),
2504
2046
  ...(config.toolBudget ? { toolBudget: initialToolBudgetState(config.toolBudget) } : {}),
2505
2047
  ...(config.usageBudget ? { usageBudget: usageBudgetState(config.usageBudget, undefined) } : {}),
2506
2048
  pid: process.pid,
@@ -2509,12 +2051,14 @@ async function runSubagent(
2509
2051
  chainStepCount: steps.length,
2510
2052
  parallelGroups,
2511
2053
  workflowGraph: config.workflowGraph,
2054
+ ...(initialSandbox ? { sandbox: initialSandbox } : {}),
2512
2055
  ...(config.launchContractDigest ? { launchContractDigest: config.launchContractDigest } : {}),
2513
2056
  ...(config.launchResolvedExtensions ? { launchResolvedExtensions: config.launchResolvedExtensions } : {}),
2514
2057
  ...(config.capabilityCeiling ? { capabilityCeiling: config.capabilityCeiling } : {}),
2515
2058
  ...(config.runFanoutBudget ? { runFanoutBudget: getRunFanoutBudgetSnapshot(config.runFanoutBudget) } : {}),
2516
2059
  ...(config.parentWorkflowRunId ? { parentWorkflowRunId: config.parentWorkflowRunId } : {}),
2517
2060
  ...(config.workflowKey ? { workflowKey: config.workflowKey } : {}),
2061
+ ...(config.lane ? { lane: config.lane } : {}),
2518
2062
  ...(config.runnerProcessInstanceId ? { processTerminal: { version: 1 as const, state: "pending" as const, runId: id, runnerProcessInstanceId: config.runnerProcessInstanceId } } : {}),
2519
2063
  steps: initialStatusSteps,
2520
2064
  artifactsDir,
@@ -2632,6 +2176,7 @@ async function runSubagent(
2632
2176
  const statusResultSummary = (state: AsyncStatus["state"]): string => {
2633
2177
  if (statusPayload.error) return statusPayload.error;
2634
2178
  if (state === "paused") return "Paused after interrupt. Waiting for explicit next action.";
2179
+ if (state === "partial") return "Subagent needs attention after partial work.";
2635
2180
  if (state === "stopped") return stopMessage;
2636
2181
  if (state === "rejected") return "Subagent rejected.";
2637
2182
  return state === "complete" ? "Subagent completed." : "Subagent failed.";
@@ -2640,12 +2185,13 @@ async function runSubagent(
2640
2185
  if (step.status === "complete" || step.status === "completed") return true;
2641
2186
  if (step.status === "failed" || step.status === "stopped" || step.status === "rejected") return false;
2642
2187
  if (state === "complete") return true;
2643
- if (state === "failed" || state === "stopped" || state === "rejected") return false;
2188
+ if (state === "failed" || state === "partial" || state === "stopped" || state === "rejected") return false;
2644
2189
  return undefined;
2645
2190
  };
2646
2191
  const writeRecoverableStatusResult = (): void => {
2647
2192
  const state = statusResultState();
2648
2193
  if (!state || finalResultCommitted || !config.sessionId) return;
2194
+ if ((state as string) === "complete") return;
2649
2195
  const now = statusPayload.endedAt ?? statusPayload.lastUpdate ?? Date.now();
2650
2196
  const summary = statusResultSummary(state);
2651
2197
  runPersistence.write(resultPath, omitUndefinedProperties({
@@ -2657,17 +2203,22 @@ async function runSubagent(
2657
2203
  success: state === "complete",
2658
2204
  state,
2659
2205
  summary,
2660
- error: state === "failed" || state === "stopped" || state === "rejected" ? summary : undefined,
2206
+ ...(statusPayload.sandbox ? { sandbox: statusPayload.sandbox } : {}),
2207
+ error: state === "failed" || state === "partial" || state === "stopped" || state === "rejected" ? summary : undefined,
2661
2208
  stopped: state === "stopped" ? true : undefined,
2662
2209
  results: statusPayload.steps.map((step) => omitUndefinedProperties({
2663
2210
  agent: step.agent,
2211
+ ...(step.sessionName ? { sessionName: step.sessionName } : {}),
2664
2212
  output: step.status === "complete" || step.status === "completed" ? "" : step.error ?? summary,
2665
2213
  error: step.error,
2666
2214
  success: statusResultSuccess(state, step),
2667
2215
  sessionFile: step.sessionFile,
2668
2216
  model: step.model,
2217
+ thinking: step.thinking,
2218
+ sandbox: step.sandbox,
2669
2219
  attemptedModels: step.attemptedModels,
2670
2220
  modelAttempts: step.modelAttempts,
2221
+ usage: usageFromAttempts(step.modelAttempts),
2671
2222
  contextOverflow: step.contextOverflow,
2672
2223
  })),
2673
2224
  exitCode: state === "complete" || state === "paused" ? 0 : 1,
@@ -2762,7 +2313,7 @@ async function runSubagent(
2762
2313
  };
2763
2314
  const childStopResult = (index: number, agent: string, context?: "fresh" | "fork"): SingleStepResult => {
2764
2315
  markChildStopped(index);
2765
- return stoppedStepResult(agent, context);
2316
+ return stoppedStepResult(agent, context, requiredStatusStep(statusPayload, index).sessionName);
2766
2317
  };
2767
2318
  const stopChildStep = (request: StopRequest): void => {
2768
2319
  if (request.targetIndex === undefined) {
@@ -2805,12 +2356,15 @@ async function runSubagent(
2805
2356
  activeChildStops.set(flatIndex, stop);
2806
2357
  if (stopped || childStopRequests.has(flatIndex)) stop();
2807
2358
  };
2808
- const registerStepTurnBudgetAbort = (flatIndex: number, abort: ((message: string, state?: TurnBudgetState) => void) | undefined): void => {
2809
- if (!abort) {
2810
- activeChildTurnBudgetAborts.delete(flatIndex);
2359
+ const registerStepSteer = (flatIndex: number, steer: StepSteerHandler | undefined): void => {
2360
+ if (!steer) {
2361
+ activeChildSteers.delete(flatIndex);
2811
2362
  return;
2812
2363
  }
2813
- activeChildTurnBudgetAborts.set(flatIndex, abort);
2364
+ activeChildSteers.set(flatIndex, steer);
2365
+ const queued = queuedStepSteers.get(flatIndex);
2366
+ queuedStepSteers.delete(flatIndex);
2367
+ for (const request of queued ?? []) steerLiveChild(flatIndex, request);
2814
2368
  };
2815
2369
  const interruptActiveChildren = (): void => {
2816
2370
  for (const interrupt of [...activeChildInterrupts.values()]) interrupt();
@@ -2921,23 +2475,26 @@ async function runSubagent(
2921
2475
  }
2922
2476
  }
2923
2477
  };
2924
- const pausedStepResult = (agent: string, context?: "fresh" | "fork"): SingleStepResult => omitUndefinedProperties({
2478
+ const pausedStepResult = (agent: string, context?: "fresh" | "fork", sessionName?: string): SingleStepResult => omitUndefinedProperties({
2925
2479
  agent,
2480
+ sessionName,
2926
2481
  context,
2927
2482
  output: "Paused after interrupt. Waiting for explicit next action.",
2928
2483
  exitCode: 0,
2929
2484
  interrupted: true,
2930
2485
  });
2931
- const timedOutStepResult = (agent: string, context?: "fresh" | "fork"): SingleStepResult => omitUndefinedProperties({
2486
+ const timedOutStepResult = (agent: string, context?: "fresh" | "fork", sessionName?: string): SingleStepResult => omitUndefinedProperties({
2932
2487
  agent,
2488
+ sessionName,
2933
2489
  context,
2934
2490
  output: timeoutMessage ?? "Subagent timed out.",
2935
2491
  error: timeoutMessage ?? "Subagent timed out.",
2936
2492
  exitCode: 1,
2937
2493
  timedOut: true,
2938
2494
  });
2939
- const stoppedStepResult = (agent: string, context?: "fresh" | "fork"): SingleStepResult => omitUndefinedProperties({
2495
+ const stoppedStepResult = (agent: string, context?: "fresh" | "fork", sessionName?: string): SingleStepResult => omitUndefinedProperties({
2940
2496
  agent,
2497
+ sessionName,
2941
2498
  context,
2942
2499
  output: stopMessage,
2943
2500
  error: stopMessage,
@@ -3261,22 +2818,15 @@ async function runSubagent(
3261
2818
  if (!step) return { index, state: "failed" as const, reason: "child index out of range" };
3262
2819
  if (step.status === "pending") return { index, state: "scheduled" as const };
3263
2820
  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
2821
  return { index, state: "routed" as const };
3266
2822
  });
3267
2823
  recordSteeringLifecycle(request, targetStates);
3268
2824
  emitSteeringEvent("subagent.steer.requested", request, undefined, { targets: targetStates });
3269
2825
  for (const target of targetStates) {
3270
2826
  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
- }
2827
+ updateSteeringLifecycleTarget(request.id, target.index, "routed", now);
2828
+ emitSteeringEvent("subagent.steer.routed", request, target.index);
2829
+ steerLiveChild(target.index, request);
3280
2830
  } else if (target.state === "failed") {
3281
2831
  markSteeringAttention(target.index);
3282
2832
  emitSteeringEvent("subagent.steer.failed", request, target.index, { reason: target.reason });
@@ -3288,27 +2838,42 @@ async function runSubagent(
3288
2838
  statusPayload.lastUpdate = now;
3289
2839
  writeStatusPayload();
3290
2840
  };
3291
- const consumeSteerAck = (ack: SteerAck): void => {
2841
+ /** Record the outcome of handing a routed steer to the live child session. */
2842
+ const applySteerDelivery = (requestId: string, index: number, delivery: { state: "delivered" | "queued" | "failed"; message: string }): void => {
3292
2843
  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));
2844
+ const request = lifecycle.recent.find((candidate) => candidate.id === requestId);
2845
+ if (!request || !request.targets.some((target) => target.index === index)) return;
2846
+ const late = fs.existsSync(steeringMarkerPath(requestId));
3296
2847
  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 });
2848
+ if (delivery.state === "delivered") {
2849
+ updateSteeringLifecycleTarget(requestId, index, late ? "late" : "delivered", now, omitUndefinedProperties({ reason: late ? "acknowledged after recovery commit" : undefined }));
2850
+ emitSteeringEvent("subagent.steer.delivered", { type: "steer", id: requestId, ts: now, message: delivery.message }, index, { late, deliveryStatus: "delivered", message: delivery.message });
2851
+ } else if (delivery.state === "queued") {
2852
+ updateSteeringLifecycleTarget(requestId, index, "queued", now);
2853
+ emitSteeringEvent("subagent.steer.queued", { type: "steer", id: requestId, ts: now, message: delivery.message }, index, { deliveryStatus: "queued", message: delivery.message });
3303
2854
  } 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 });
2855
+ markSteeringAttention(index);
2856
+ updateSteeringLifecycleTarget(requestId, index, "failed", now, { reason: delivery.message });
2857
+ emitSteeringEvent("subagent.steer.failed", { type: "steer", id: requestId, ts: now, message: delivery.message }, index, { reason: delivery.message });
3307
2858
  }
3308
- emitTerminalSteeringNotice(ack.requestId, `Steering failed for run ${id}: ${ack.message}`);
2859
+ emitTerminalSteeringNotice(requestId, `Steering failed for run ${id}: ${delivery.message}`);
3309
2860
  statusPayload.lastUpdate = now;
3310
2861
  writeStatusPayload();
3311
2862
  };
2863
+ /** Hand a routed steer to the step's live session, or hold it until the session exists. */
2864
+ const steerLiveChild = (index: number, request: SteerRequest): void => {
2865
+ const steer = activeChildSteers.get(index);
2866
+ if (!steer) {
2867
+ const queued = queuedStepSteers.get(index) ?? [];
2868
+ queued.push(request);
2869
+ queuedStepSteers.set(index, queued);
2870
+ return;
2871
+ }
2872
+ void steer(request).then(
2873
+ (delivery) => applySteerDelivery(request.id, index, delivery),
2874
+ (error) => applySteerDelivery(request.id, index, { state: "failed", message: error instanceof Error ? error.message : String(error) }),
2875
+ );
2876
+ };
3312
2877
  const flushPendingStepSteers = (flatIndex: number): void => {
3313
2878
  const remaining: SteerRequest[] = [];
3314
2879
  for (const request of pendingStepSteers.splice(0)) {
@@ -3318,74 +2883,15 @@ async function runSubagent(
3318
2883
  }
3319
2884
  pendingStepSteers.push(...remaining);
3320
2885
  };
3321
- const updateStepModel = (flatIndex: number, model: string | undefined, thinking: string | undefined, now = Date.now()): void => {
2886
+ const updateStepModel = (flatIndex: number, model: string | undefined, thinking: string | undefined, contextLimit?: number, now = Date.now()): void => {
3322
2887
  const step = statusPayload.steps[flatIndex];
3323
2888
  if (!step) return;
3324
2889
  setOptionalProperty(step, "model", model);
3325
2890
  setOptionalProperty(step, "thinking", thinking);
2891
+ setOptionalProperty(step, "contextLimit", contextLimit);
3326
2892
  statusPayload.lastUpdate = now;
3327
2893
  writeStatusPayload();
3328
2894
  };
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
2895
  const updateStepFromChildEvent = (flatIndex: number, event: ChildEvent): void => {
3390
2896
  const step = statusPayload.steps[flatIndex];
3391
2897
  if (!step) return;
@@ -3407,8 +2913,17 @@ async function runSubagent(
3407
2913
  writeStatusPayload(false);
3408
2914
  return;
3409
2915
  }
2916
+ if (event.type === "message_end") {
2917
+ const next = applyChildWatchdogMessage(step.watchdog, event.message, now);
2918
+ if (next) step.watchdog = next;
2919
+ if (next && (event.message as { role?: unknown } | undefined)?.role === "custom") {
2920
+ statusPayload.lastUpdate = now;
2921
+ writeStatusPayload(false);
2922
+ return;
2923
+ }
2924
+ }
3410
2925
  if (event.type === "tool_execution_start" && event.toolName) {
3411
- const mutates = isMutatingTool(event.toolName, event.args);
2926
+ const mutates = isMutatingTool(event.toolName, event.args, flatSteps[flatIndex]?.mutationTools);
3412
2927
  const currentPath = resolveCurrentPath(event.toolName, event.args);
3413
2928
  const argsPreview = extractToolArgsPreview(event.args ?? {});
3414
2929
  const blocksSupervisor = isBlockingSupervisorTool(event.toolName, event.args);
@@ -3442,6 +2957,7 @@ async function runSubagent(
3442
2957
  tokens: step.tokens?.total,
3443
2958
  toolCount: step.toolCount,
3444
2959
  currentTool: step.currentTool,
2960
+ toolCallId: event.toolCallId,
3445
2961
  currentToolDurationMs: 0,
3446
2962
  currentPath: step.currentPath,
3447
2963
  })));
@@ -3516,22 +3032,16 @@ async function runSubagent(
3516
3032
  if (usage) {
3517
3033
  const input = usage.input ?? usage.inputTokens ?? 0;
3518
3034
  const output = usage.output ?? usage.outputTokens ?? 0;
3035
+ const window = input + (usage.cacheRead ?? usage.cacheReadTokens ?? 0);
3519
3036
  const previousInput = step.tokens?.input ?? 0;
3520
3037
  const previousOutput = step.tokens?.output ?? 0;
3521
- step.tokens = { input: previousInput + input, output: previousOutput + output, total: previousInput + previousOutput + input + output };
3038
+ step.tokens = { input: previousInput + input, output: previousOutput + output, total: previousInput + previousOutput + input + output, window, windowPeak: Math.max(step.tokens?.windowPeak ?? 0, window) };
3522
3039
  const totalInput = statusPayload.totalTokens?.input ?? 0;
3523
3040
  const totalOutput = statusPayload.totalTokens?.output ?? 0;
3524
- statusPayload.totalTokens = { input: totalInput + input, output: totalOutput + output, total: totalInput + totalOutput + input + output };
3041
+ statusPayload.totalTokens = { input: totalInput + input, output: totalOutput + output, total: totalInput + totalOutput + input + output, window, windowPeak: Math.max(statusPayload.totalTokens?.windowPeak ?? 0, window) };
3525
3042
  refreshUsageBudget();
3526
3043
  }
3527
3044
  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
3045
  }
3536
3046
  syncTopLevelCurrentTool();
3537
3047
  step.lastActivityAt = now;
@@ -3557,6 +3067,7 @@ async function runSubagent(
3557
3067
  config: controlConfig,
3558
3068
  startedAt: step.startedAt ?? overallStartTime,
3559
3069
  lastActivityAt,
3070
+ turnCount: step.turnCount,
3560
3071
  currentTool: step.currentTool,
3561
3072
  thinking: step.thinking,
3562
3073
  now,
@@ -3721,23 +3232,6 @@ async function runSubagent(
3721
3232
  pendingStepSteers.push(request);
3722
3233
  }
3723
3234
  },
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
3235
  });
3742
3236
  if (config.deadlineAt !== undefined) {
3743
3237
  const remainingMs = Math.max(0, config.deadlineAt - Date.now());
@@ -3760,7 +3254,7 @@ async function runSubagent(
3760
3254
  let flatIndex = 0;
3761
3255
  let stepCursor = 0;
3762
3256
  while (true) {
3763
- if (interrupted || timedOut || stopped || turnBudgetExceeded) break;
3257
+ if (interrupted || timedOut || stopped) break;
3764
3258
  consumePendingAppendRequests();
3765
3259
  if (stepCursor >= steps.length) break;
3766
3260
  refreshUsageBudget();
@@ -3794,7 +3288,7 @@ async function runSubagent(
3794
3288
  : [undefined]
3795
3289
  : model ? [model] : [undefined];
3796
3290
  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 });
3291
+ assertThinkingWithinCeiling({ model: candidate, configThinking, ceiling: step.parallel.thinkingCeiling, agent: step.parallel.agent, runId: id });
3798
3292
  }
3799
3293
  }
3800
3294
  if (materialized.collectedOnEmpty) await validateDynamicCollection(step.collect.outputSchema, materialized.collectedOnEmpty);
@@ -3905,10 +3399,12 @@ async function runSubagent(
3905
3399
  : step.parallel.outputPath;
3906
3400
  const taskText = task.task ?? step.parallel.task;
3907
3401
  const materializedTask = step.parallel.namespaceOutputPath ? injectSingleOutputInstruction(taskText, outputPath, step.parallel) : taskText;
3402
+ const sessionName = deriveChildSessionName({ agent: step.parallel.agent, task: taskText, label: task.label ?? step.parallel.label });
3908
3403
  return omitUndefinedProperties({
3909
3404
  ...step.parallel,
3910
3405
  runFanoutPath: `chain[${stepIndex}].expand[${itemIndex}]`,
3911
3406
  task: materializedTask,
3407
+ ...(sessionName ? { sessionName } : {}),
3912
3408
  effectiveAcceptance: resolveEffectiveAcceptance(omitUndefinedProperties({
3913
3409
  explicit: step.parallel.acceptanceInput,
3914
3410
  agentName: step.parallel.agent,
@@ -3939,6 +3435,7 @@ async function runSubagent(
3939
3435
  const transcriptPath = resolveAsyncStepTranscriptPath(omitUndefinedProperties({ artifactsDir, artifactConfig, runId: id, agent: task.agent, flatIndex: groupStartFlatIndex + itemIndex, flatStepCount: dynamicFlatStepCount }));
3940
3436
  return omitUndefinedProperties({
3941
3437
  agent: task.agent,
3438
+ ...(task.sessionName ? { sessionName: task.sessionName } : {}),
3942
3439
  ...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),
3943
3440
  ...(task.context ? { context: task.context } : {}),
3944
3441
  ...(task.phase ?? step.phase ? { phase: task.phase ?? step.phase } : {}),
@@ -3952,6 +3449,7 @@ async function runSubagent(
3952
3449
  ...(transcriptPath ? { transcriptPath } : {}),
3953
3450
  ...(task.skills ? { skills: task.skills } : {}),
3954
3451
  ...(task.model ? { model: task.model } : {}),
3452
+ ...(task.contextLimit !== undefined ? { contextLimit: task.contextLimit } : {}),
3955
3453
  ...(task.thinking ? { thinking: task.thinking } : {}),
3956
3454
  ...(task.thinkingCeiling ? { thinkingCeiling: task.thinkingCeiling } : {}),
3957
3455
  ...(task.modelCandidates && task.modelCandidates.length > 0 ? { attemptedModels: task.modelCandidates } : task.model ? { attemptedModels: [task.model] } : {}),
@@ -4021,12 +3519,12 @@ async function runSubagent(
4021
3519
  usageBudgetExceeded = true;
4022
3520
  writeStatusPayload();
4023
3521
  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 });
3522
+ 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
3523
  }
4026
- if (timedOut) return timedOutStepResult(task.agent, task.context);
4027
- if (stopped) return stoppedStepResult(task.agent, task.context);
3524
+ if (timedOut) return timedOutStepResult(task.agent, task.context, task.sessionName);
3525
+ if (stopped) return stoppedStepResult(task.agent, task.context, task.sessionName);
4028
3526
  if (childStopRequests.has(fi)) return childStopResult(fi, task.agent, task.context);
4029
- if (interrupted) return pausedStepResult(task.agent, task.context);
3527
+ if (interrupted) return pausedStepResult(task.agent, task.context, task.sessionName);
4030
3528
  if (aborted && failFast) {
4031
3529
  const skippedAt = Date.now();
4032
3530
  requiredStatusStep(statusPayload, fi).status = "failed";
@@ -4037,7 +3535,7 @@ async function runSubagent(
4037
3535
  requiredStatusStep(statusPayload, fi).exitCode = -1;
4038
3536
  statusPayload.lastUpdate = skippedAt;
4039
3537
  writeStatusPayload();
4040
- return omitUndefinedProperties({ agent: task.agent, context: task.context, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true });
3538
+ 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
3539
  }
4042
3540
  const taskStartTime = Date.now();
4043
3541
  statusPayload.currentStep = fi;
@@ -4060,11 +3558,9 @@ async function runSubagent(
4060
3558
  artifactsDir, artifactConfig, id,
4061
3559
  flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
4062
3560
  outputFile: path.join(asyncDir, `output-${fi}.log`),
4063
- steerInboxDir: stepSteerInboxDir(asyncDir, fi),
4064
- steerCapabilityPath: steerCapabilityPath(asyncDir, fi),
4065
- steerAckDir: steerAcksDir(asyncDir, fi),
4066
3561
  piPackageRoot: config.piPackageRoot,
4067
- piArgv1: config.piArgv1,
3562
+ childSessions,
3563
+ inheritedChildRuntime: config.inheritedChildRuntime,
4068
3564
  childIntercomTarget: config.childIntercomTargets?.[fi],
4069
3565
  orchestratorIntercomTarget: config.controlIntercomTarget,
4070
3566
  nestedRoute: config.nestedRoute,
@@ -4073,20 +3569,19 @@ async function runSubagent(
4073
3569
  registerInterrupt: (interrupt) => registerStepInterrupt(fi, interrupt),
4074
3570
  registerTimeout: (interrupt) => registerStepTimeout(fi, interrupt),
4075
3571
  registerStop: (stop) => registerStepStop(fi, stop),
4076
- registerTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(fi, abort),
3572
+ registerSteer: (steer) => registerStepSteer(fi, steer),
4077
3573
  timeoutSignal: timeoutAbortController.signal,
4078
3574
  stopSignal: stopAbortController.signal,
4079
3575
  trackedMutationEvidenceForCompletionGuard: false,
4080
3576
  timeoutMessage,
4081
3577
  stopMessage,
4082
- turnBudget: config.turnBudget,
4083
3578
  toolTimeoutMs: task.toolTimeoutMs ?? config.toolTimeoutMs,
4084
- onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking),
3579
+ onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking, attempt.contextLimit),
4085
3580
  onChildEvent: (event) => updateStepFromChildEvent(fi, event),
4086
- onWriterProcess,
4087
3581
  onExternalProcess: (process) => updateExternalProcess(fi, process),
4088
3582
  onExternalJob: (externalJob) => updateExternalJob(fi, externalJob),
4089
3583
  skipAcceptance: () => timedOut || stopped || childStopRequests.has(fi),
3584
+ usageBudgetExhausted: () => refreshUsageBudget()?.exhausted === true,
4090
3585
  orcaProgressTab,
4091
3586
  }), config.deadlineAt);
4092
3587
  const taskEndTime = Date.now();
@@ -4098,16 +3593,11 @@ async function runSubagent(
4098
3593
  requiredStatusStep(statusPayload, fi).exitCode = stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;
4099
3594
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "timedOut", timedOut || singleResult.timedOut ? true : undefined);
4100
3595
  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
3596
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudget", singleResult.toolBudget);
4105
3597
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudgetBlocked", singleResult.toolBudgetBlocked);
4106
3598
  if (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;
4107
3599
  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;
3600
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "sessionName", singleResult.sessionName);
4111
3601
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "model", singleResult.model);
4112
3602
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "thinking", resolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, fi).thinking));
4113
3603
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "attemptedModels", singleResult.attemptedModels);
@@ -4126,6 +3616,7 @@ async function runSubagent(
4126
3616
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "transcriptPath", singleResult.transcriptPath ?? requiredStatusStep(statusPayload, fi).transcriptPath);
4127
3617
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "transcriptError", singleResult.transcriptError);
4128
3618
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "agentContract", singleResult.agentContract);
3619
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "sandbox", singleResult.sandbox);
4129
3620
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "launchContractDigest", singleResult.launchContractDigest);
4130
3621
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "launchResolvedExtensions", singleResult.launchResolvedExtensions);
4131
3622
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "runtimeAcknowledgedExtensions", singleResult.runtimeAcknowledgedExtensions);
@@ -4159,33 +3650,33 @@ async function runSubagent(
4159
3650
  for (const pr of parallelResults) {
4160
3651
  results.push(omitUndefinedProperties({
4161
3652
  agent: pr.agent,
3653
+ ...(pr.sessionName ? { sessionName: pr.sessionName } : {}),
4162
3654
  context: pr.context,
4163
3655
  agentContract: pr.agentContract,
3656
+ sandbox: pr.sandbox,
4164
3657
  launchContractDigest: pr.launchContractDigest,
4165
3658
  launchResolvedExtensions: pr.launchResolvedExtensions,
4166
3659
  runtimeAcknowledgedExtensions: pr.runtimeAcknowledgedExtensions,
4167
3660
  output: pr.output,
4168
3661
  outputState: pr.outputState,
4169
3662
  error: pr.error,
4170
- protocolError: pr.protocolError,
4171
3663
  success: pr.stopped !== true && pr.interrupted !== true && pr.exitCode === 0,
4172
3664
  exitCode: pr.interrupted === true ? 0 : pr.exitCode,
4173
3665
  skipped: pr.skipped,
4174
3666
  interrupted: pr.interrupted,
4175
3667
  timedOut: pr.timedOut,
4176
3668
  stopped: pr.stopped,
4177
- turnBudget: pr.turnBudget,
4178
- turnBudgetExceeded: pr.turnBudgetExceeded,
4179
- wrapUpRequested: pr.wrapUpRequested,
4180
3669
  toolBudget: pr.toolBudget,
4181
3670
  toolBudgetBlocked: pr.toolBudgetBlocked,
4182
3671
  sessionFile: pr.sessionFile,
4183
3672
  intercomTarget: pr.intercomTarget,
4184
3673
  model: pr.model,
3674
+ thinking: pr.thinking,
4185
3675
  attemptedModels: pr.attemptedModels,
4186
3676
  modelAttempts: pr.modelAttempts,
4187
3677
  contextOverflow: pr.contextOverflow,
4188
3678
  totalCost: pr.totalCost,
3679
+ usage: pr.usage,
4189
3680
  artifactPaths: pr.artifactPaths,
4190
3681
  transcriptPath: pr.transcriptPath,
4191
3682
  transcriptError: pr.transcriptError,
@@ -4325,10 +3816,32 @@ async function runSubagent(
4325
3816
  try {
4326
3817
  worktreeSetup = createWorktrees(cwd, `${id}-s${stepIndex}`, group.parallel.length, omitUndefinedProperties({
4327
3818
  agents: group.parallel.map((task) => task.agent),
3819
+ labels: group.parallel.map((task) => task.lane?.key ?? config.workflowKey ?? task.outputName ?? task.label),
3820
+ tasks: group.parallel.map((task) => task.task),
3821
+ provider: config.worktreeProvider,
3822
+ baseRef: config.baseRef,
3823
+ branchPrefix: config.worktreeBranchPrefix,
4328
3824
  setupHook: config.worktreeSetupHook
4329
3825
  ? omitUndefinedProperties({ hookPath: config.worktreeSetupHook, timeoutMs: config.worktreeSetupHookTimeoutMs })
4330
3826
  : undefined,
4331
3827
  baseDir: config.worktreeBaseDir,
3828
+ beforeCreate: (plannedSetup) => {
3829
+ for (const worktree of plannedSetup.worktrees) setStatusWorktreeReference(requiredStatusStep(statusPayload, groupStartFlatIndex + worktree.index), worktree);
3830
+ const pendingHandoff = writePendingParallelHandoff({
3831
+ manifestPath: parallelHandoffPath(asyncDir),
3832
+ runId: id,
3833
+ mode: (config.resultMode ?? statusPayload.mode) === "parallel" ? "parallel" : "chain",
3834
+ source: "async",
3835
+ cwd,
3836
+ stepIndex,
3837
+ flatStartIndex: groupStartFlatIndex,
3838
+ setup: plannedSetup,
3839
+ laneBindings: handoffWorkflowKey || config.lane ? [{ index: groupStartFlatIndex, taskIndex: 0, ...(handoffWorkflowKey ? { workflowKey: handoffWorkflowKey } : {}), ...(handoffChildRunId ? { runId: handoffChildRunId } : {}), ...(config.lane ? { lane: config.lane } : {}) }] : undefined,
3840
+ });
3841
+ statusPayload.parallelHandoff = pendingHandoff;
3842
+ statusPayload.lastUpdate = Date.now();
3843
+ writeStatusPayload();
3844
+ },
4332
3845
  }));
4333
3846
  } catch (error) {
4334
3847
  const setupError = error instanceof Error ? error.message : String(error);
@@ -4353,18 +3866,6 @@ async function runSubagent(
4353
3866
  }
4354
3867
 
4355
3868
  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
3869
  if (group.worktree) ensureParallelProgressFile(cwd, group);
4369
3870
  const groupStartTime = Date.now();
4370
3871
  markParallelGroupRunning({
@@ -4401,12 +3902,12 @@ async function runSubagent(
4401
3902
  appendJsonl(eventsPath, JSON.stringify({
4402
3903
  type: "subagent.step.failed", ts: skippedAt, runId: id, stepIndex: fi, agent: task.agent, exitCode: 1, durationMs: 0,
4403
3904
  }));
4404
- return omitUndefinedProperties({ agent: task.agent, context: task.context, output: message, error: message, exitCode: 1 as number | null, skipped: true });
3905
+ 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
3906
  }
4406
- if (timedOut) return timedOutStepResult(task.agent, task.context);
4407
- if (stopped) return stoppedStepResult(task.agent, task.context);
3907
+ if (timedOut) return timedOutStepResult(task.agent, task.context, task.sessionName);
3908
+ if (stopped) return stoppedStepResult(task.agent, task.context, task.sessionName);
4408
3909
  if (childStopRequests.has(fi)) return childStopResult(fi, task.agent, task.context);
4409
- if (interrupted) return pausedStepResult(task.agent, task.context);
3910
+ if (interrupted) return pausedStepResult(task.agent, task.context, task.sessionName);
4410
3911
  if (aborted && failFast) {
4411
3912
  const skippedAt = Date.now();
4412
3913
  requiredStatusStep(statusPayload, fi).status = "failed";
@@ -4421,7 +3922,7 @@ async function runSubagent(
4421
3922
  appendJsonl(eventsPath, JSON.stringify({
4422
3923
  type: "subagent.step.failed", ts: skippedAt, runId: id, stepIndex: fi, agent: task.agent, exitCode: -1, durationMs: 0,
4423
3924
  }));
4424
- return omitUndefinedProperties({ agent: task.agent, context: task.context, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true });
3925
+ 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
3926
  }
4426
3927
 
4427
3928
  const taskStartTime = Date.now();
@@ -4456,11 +3957,9 @@ async function runSubagent(
4456
3957
  artifactsDir, artifactConfig, id,
4457
3958
  flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
4458
3959
  outputFile: path.join(asyncDir, `output-${fi}.log`),
4459
- steerInboxDir: stepSteerInboxDir(asyncDir, fi),
4460
- steerCapabilityPath: steerCapabilityPath(asyncDir, fi),
4461
- steerAckDir: steerAcksDir(asyncDir, fi),
4462
3960
  piPackageRoot: config.piPackageRoot,
4463
- piArgv1: config.piArgv1,
3961
+ childSessions,
3962
+ inheritedChildRuntime: config.inheritedChildRuntime,
4464
3963
  childIntercomTarget: config.childIntercomTargets?.[fi],
4465
3964
  orchestratorIntercomTarget: config.controlIntercomTarget,
4466
3965
  nestedRoute: config.nestedRoute,
@@ -4469,20 +3968,19 @@ async function runSubagent(
4469
3968
  registerInterrupt: (interrupt) => registerStepInterrupt(fi, interrupt),
4470
3969
  registerTimeout: (interrupt) => registerStepTimeout(fi, interrupt),
4471
3970
  registerStop: (stop) => registerStepStop(fi, stop),
4472
- registerTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(fi, abort),
3971
+ registerSteer: (steer) => registerStepSteer(fi, steer),
4473
3972
  timeoutSignal: timeoutAbortController.signal,
4474
3973
  stopSignal: stopAbortController.signal,
4475
3974
  trackedMutationEvidenceForCompletionGuard: Boolean(worktreeSetup),
4476
3975
  timeoutMessage,
4477
3976
  stopMessage,
4478
- turnBudget: config.turnBudget,
4479
3977
  toolTimeoutMs: taskForRun.toolTimeoutMs ?? config.toolTimeoutMs,
4480
- onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking),
3978
+ onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking, attempt.contextLimit),
4481
3979
  onChildEvent: (event) => updateStepFromChildEvent(fi, event),
4482
- onWriterProcess,
4483
3980
  onExternalProcess: (process) => updateExternalProcess(fi, process),
4484
3981
  onExternalJob: (externalJob) => updateExternalJob(fi, externalJob),
4485
3982
  skipAcceptance: () => timedOut || stopped || childStopRequests.has(fi),
3983
+ usageBudgetExhausted: () => refreshUsageBudget()?.exhausted === true,
4486
3984
  orcaProgressTab,
4487
3985
  }), config.deadlineAt);
4488
3986
  if (task.sessionFile) {
@@ -4500,16 +3998,11 @@ async function runSubagent(
4500
3998
  requiredStatusStep(statusPayload, fi).exitCode = stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;
4501
3999
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "timedOut", timedOut || singleResult.timedOut ? true : undefined);
4502
4000
  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
4001
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudget", singleResult.toolBudget);
4507
4002
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudgetBlocked", singleResult.toolBudgetBlocked);
4508
4003
  if (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;
4509
4004
  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;
4005
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "sessionName", singleResult.sessionName);
4513
4006
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "model", singleResult.model);
4514
4007
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "thinking", resolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, fi).thinking));
4515
4008
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "attemptedModels", singleResult.attemptedModels);
@@ -4528,6 +4021,7 @@ async function runSubagent(
4528
4021
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "transcriptPath", singleResult.transcriptPath ?? requiredStatusStep(statusPayload, fi).transcriptPath);
4529
4022
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "transcriptError", singleResult.transcriptError);
4530
4023
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "agentContract", singleResult.agentContract);
4024
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "sandbox", singleResult.sandbox);
4531
4025
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "launchResolvedExtensions", singleResult.launchResolvedExtensions);
4532
4026
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "runtimeAcknowledgedExtensions", singleResult.runtimeAcknowledgedExtensions);
4533
4027
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "effects", singleResult.effects);
@@ -4580,13 +4074,21 @@ async function runSubagent(
4580
4074
  const sessionTokens = config.sessionDir
4581
4075
  ? parseSessionTokens(path.join(config.sessionDir, `parallel-${t}`))
4582
4076
  : null;
4583
- const taskTokens = sessionTokens ?? tokenUsageFromAttempts(parallelResults[t]?.modelAttempts);
4077
+ const fallbackTokens = tokenUsageFromAttempts(parallelResults[t]?.modelAttempts);
4078
+ const observedTokens = requiredStatusStep(statusPayload, fi).tokens;
4079
+ const taskTokens = sessionTokens ?? (fallbackTokens
4080
+ ? { ...fallbackTokens, ...(observedTokens?.window !== undefined ? { window: observedTokens.window } : {}), ...(observedTokens?.windowPeak !== undefined ? { windowPeak: observedTokens.windowPeak } : {}) }
4081
+ : null);
4584
4082
  if (!taskTokens) continue;
4585
4083
  requiredStatusStep(statusPayload, fi).tokens = taskTokens;
4586
4084
  previousCumulativeTokens = {
4587
4085
  input: previousCumulativeTokens.input + taskTokens.input,
4588
4086
  output: previousCumulativeTokens.output + taskTokens.output,
4589
4087
  total: previousCumulativeTokens.total + taskTokens.total,
4088
+ ...(taskTokens.window !== undefined ? { window: taskTokens.window } : {}),
4089
+ ...(previousCumulativeTokens.windowPeak !== undefined || taskTokens.windowPeak !== undefined
4090
+ ? { windowPeak: Math.max(previousCumulativeTokens.windowPeak ?? 0, taskTokens.windowPeak ?? 0) }
4091
+ : {}),
4590
4092
  };
4591
4093
  }
4592
4094
  statusPayload.totalTokens = { ...previousCumulativeTokens };
@@ -4598,30 +4100,29 @@ async function runSubagent(
4598
4100
  agent: pr.agent,
4599
4101
  context: pr.context,
4600
4102
  agentContract: pr.agentContract,
4103
+ sandbox: pr.sandbox,
4601
4104
  launchContractDigest: pr.launchContractDigest,
4602
4105
  launchResolvedExtensions: pr.launchResolvedExtensions,
4603
4106
  output: pr.output,
4604
4107
  outputState: pr.outputState,
4605
4108
  error: pr.error,
4606
- protocolError: pr.protocolError,
4607
4109
  success: pr.stopped !== true && pr.interrupted !== true && pr.exitCode === 0,
4608
4110
  exitCode: pr.interrupted === true ? 0 : pr.exitCode,
4609
4111
  skipped: pr.skipped,
4610
4112
  interrupted: pr.interrupted,
4611
4113
  timedOut: pr.timedOut,
4612
4114
  stopped: pr.stopped,
4613
- turnBudget: pr.turnBudget,
4614
- turnBudgetExceeded: pr.turnBudgetExceeded,
4615
- wrapUpRequested: pr.wrapUpRequested,
4616
4115
  toolBudget: pr.toolBudget,
4617
4116
  toolBudgetBlocked: pr.toolBudgetBlocked,
4618
4117
  sessionFile: pr.sessionFile,
4619
4118
  intercomTarget: pr.intercomTarget,
4620
4119
  model: pr.model,
4120
+ thinking: pr.thinking,
4621
4121
  attemptedModels: pr.attemptedModels,
4622
4122
  modelAttempts: pr.modelAttempts,
4623
4123
  contextOverflow: pr.contextOverflow,
4624
4124
  totalCost: pr.totalCost,
4125
+ usage: pr.usage,
4625
4126
  artifactPaths: pr.artifactPaths,
4626
4127
  transcriptPath: pr.transcriptPath,
4627
4128
  transcriptError: pr.transcriptError,
@@ -4675,12 +4176,14 @@ async function runSubagent(
4675
4176
  diffs: captured.diffs,
4676
4177
  results: parallelResults.map((result) => ({
4677
4178
  agent: result.agent,
4179
+ ...(handoffWorkflowKey ? { workflowKey: handoffWorkflowKey } : {}),
4180
+ ...(handoffChildRunId ? { runId: handoffChildRunId } : {}),
4181
+ ...(config.lane ? { lane: config.lane } : {}),
4678
4182
  status: result.stopped || (result.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
4679
4183
  processSignal: result.processSignal,
4680
4184
  interrupted: result.interrupted,
4681
4185
  timedOut: result.timedOut,
4682
4186
  stopped: result.stopped,
4683
- turnBudgetExceeded: result.turnBudgetExceeded,
4684
4187
  }))) ? "stopped" as const : result.interrupted ? "paused" as const : result.exitCode === 0 ? "completed" as const : "failed" as const,
4685
4188
  summary: result.output || result.error || "(no output)",
4686
4189
  ...(result.artifactPaths?.outputPath ? { outputPath: result.artifactPaths.outputPath } : {}),
@@ -4726,12 +4229,12 @@ async function runSubagent(
4726
4229
  } else {
4727
4230
  const seqStep = step as SubagentStep;
4728
4231
  if (timedOut) {
4729
- results.push(timedOutStepResult(seqStep.agent, seqStep.context));
4232
+ results.push(timedOutStepResult(seqStep.agent, seqStep.context, seqStep.sessionName));
4730
4233
  flatIndex++;
4731
4234
  continue;
4732
4235
  }
4733
4236
  if (stopped) {
4734
- results.push(stoppedStepResult(seqStep.agent, seqStep.context));
4237
+ results.push(stoppedStepResult(seqStep.agent, seqStep.context, seqStep.sessionName));
4735
4238
  flatIndex++;
4736
4239
  continue;
4737
4240
  }
@@ -4741,7 +4244,7 @@ async function runSubagent(
4741
4244
  continue;
4742
4245
  }
4743
4246
  if (interrupted) {
4744
- results.push(pausedStepResult(seqStep.agent, seqStep.context));
4247
+ results.push(pausedStepResult(seqStep.agent, seqStep.context, seqStep.sessionName));
4745
4248
  flatIndex++;
4746
4249
  continue;
4747
4250
  }
@@ -4750,21 +4253,36 @@ async function runSubagent(
4750
4253
  try {
4751
4254
  singleWorktreeSetup = createWorktrees(cwd, `${id}-s${stepIndex}`, 1, omitUndefinedProperties({
4752
4255
  agents: [seqStep.agent],
4256
+ labels: [seqStep.lane?.key ?? config.workflowKey ?? seqStep.outputName ?? seqStep.label],
4257
+ tasks: [seqStep.task],
4258
+ provider: config.worktreeProvider,
4259
+ baseRef: config.baseRef,
4260
+ branchPrefix: config.worktreeBranchPrefix,
4753
4261
  setupHook: config.worktreeSetupHook
4754
4262
  ? omitUndefinedProperties({ hookPath: config.worktreeSetupHook, timeoutMs: config.worktreeSetupHookTimeoutMs })
4755
4263
  : undefined,
4756
4264
  baseDir: config.worktreeBaseDir,
4265
+ beforeCreate: (plannedSetup) => {
4266
+ const worktree = plannedSetup.worktrees[0];
4267
+ if (worktree) {
4268
+ setStatusWorktreeReference(requiredStatusStep(statusPayload, flatIndex), worktree);
4269
+ }
4270
+ const pendingHandoff = writePendingParallelHandoff({
4271
+ manifestPath: parallelHandoffPath(asyncDir),
4272
+ runId: id,
4273
+ mode: "single",
4274
+ source: "async",
4275
+ cwd,
4276
+ stepIndex,
4277
+ flatStartIndex: flatIndex,
4278
+ setup: plannedSetup,
4279
+ laneBindings: handoffWorkflowKey || config.lane ? [{ index: flatIndex, taskIndex: 0, ...(handoffWorkflowKey ? { workflowKey: handoffWorkflowKey } : {}), ...(handoffChildRunId ? { runId: handoffChildRunId } : {}), ...(config.lane ? { lane: config.lane } : {}) }] : undefined,
4280
+ });
4281
+ statusPayload.parallelHandoff = pendingHandoff;
4282
+ statusPayload.lastUpdate = Date.now();
4283
+ writeStatusPayload();
4284
+ },
4757
4285
  }));
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
4286
  } catch (error) {
4769
4287
  if (singleWorktreeSetup) cleanupWorktrees(singleWorktreeSetup);
4770
4288
  throw error;
@@ -4794,7 +4312,9 @@ async function runSubagent(
4794
4312
  }));
4795
4313
 
4796
4314
  flushPendingStepSteers(flatIndex);
4797
- const executionStep = singleWorktreeSetup ? { ...seqStep, cwd: singleCwd } : seqStep;
4315
+ const executionStep = singleWorktreeSetup
4316
+ ? bindWorktreeCwd({ ...seqStep, cwd: singleCwd }, singleCwd)
4317
+ : seqStep;
4798
4318
  let singleResult: Awaited<ReturnType<typeof runSingleStepWithTimeout>>;
4799
4319
  try {
4800
4320
  singleResult = await runSingleStepWithTimeout(executionStep, compactOptional<SingleStepContext>({
@@ -4804,11 +4324,9 @@ async function runSubagent(
4804
4324
  artifactsDir, artifactConfig, id,
4805
4325
  flatIndex, flatStepCount: Math.max(statusPayload.steps.length, 1),
4806
4326
  outputFile: path.join(asyncDir, `output-${flatIndex}.log`),
4807
- steerInboxDir: stepSteerInboxDir(asyncDir, flatIndex),
4808
- steerCapabilityPath: steerCapabilityPath(asyncDir, flatIndex),
4809
- steerAckDir: steerAcksDir(asyncDir, flatIndex),
4810
4327
  piPackageRoot: config.piPackageRoot,
4811
- piArgv1: config.piArgv1,
4328
+ childSessions,
4329
+ inheritedChildRuntime: config.inheritedChildRuntime,
4812
4330
  childIntercomTarget: config.childIntercomTargets?.[flatIndex],
4813
4331
  orchestratorIntercomTarget: config.controlIntercomTarget,
4814
4332
  nestedRoute: config.nestedRoute,
@@ -4817,19 +4335,18 @@ async function runSubagent(
4817
4335
  registerInterrupt: (interrupt) => registerStepInterrupt(flatIndex, interrupt),
4818
4336
  registerTimeout: (interrupt) => registerStepTimeout(flatIndex, interrupt),
4819
4337
  registerStop: (stop) => registerStepStop(flatIndex, stop),
4820
- registerTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(flatIndex, abort),
4338
+ registerSteer: (steer) => registerStepSteer(flatIndex, steer),
4821
4339
  timeoutSignal: timeoutAbortController.signal,
4822
4340
  stopSignal: stopAbortController.signal,
4823
4341
  timeoutMessage,
4824
4342
  stopMessage,
4825
- turnBudget: config.turnBudget,
4826
4343
  toolTimeoutMs: seqStep.toolTimeoutMs ?? config.toolTimeoutMs,
4827
- onAttemptStart: (attempt) => updateStepModel(flatIndex, attempt.model, attempt.thinking),
4344
+ onAttemptStart: (attempt) => updateStepModel(flatIndex, attempt.model, attempt.thinking, attempt.contextLimit),
4828
4345
  onChildEvent: (event) => updateStepFromChildEvent(flatIndex, event),
4829
- onWriterProcess,
4830
4346
  onExternalProcess: (process) => updateExternalProcess(flatIndex, process),
4831
4347
  onExternalJob: (externalJob) => updateExternalJob(flatIndex, externalJob),
4832
4348
  skipAcceptance: () => timedOut || stopped || childStopRequests.has(flatIndex),
4349
+ usageBudgetExhausted: () => refreshUsageBudget()?.exhausted === true,
4833
4350
  orcaProgressTab,
4834
4351
  }), config.deadlineAt);
4835
4352
  } catch (error) {
@@ -4844,24 +4361,27 @@ async function runSubagent(
4844
4361
  const childStopped = singleResult.stopped === true;
4845
4362
  results.push(omitUndefinedProperties({
4846
4363
  agent: singleResult.agent,
4364
+ ...(singleResult.sessionName ? { sessionName: singleResult.sessionName } : {}),
4847
4365
  context: singleResult.context,
4848
4366
  agentContract: singleResult.agentContract,
4367
+ sandbox: singleResult.sandbox,
4849
4368
  launchContractDigest: singleResult.launchContractDigest,
4850
4369
  launchResolvedExtensions: singleResult.launchResolvedExtensions,
4851
4370
  runtimeAcknowledgedExtensions: singleResult.runtimeAcknowledgedExtensions,
4852
4371
  output: stopped || childStopped ? stopMessage : timedOut ? singleResult.output || (timeoutMessage ?? "Subagent timed out.") : singleResult.output,
4853
4372
  outputState: singleResult.outputState,
4854
4373
  error: stopped || childStopped ? stopMessage : timedOut ? (timeoutMessage ?? "Subagent timed out.") : singleResult.error,
4855
- protocolError: singleResult.protocolError,
4856
4374
  success: !stopped && !childStopped && !timedOut && singleResult.interrupted !== true && singleResult.exitCode === 0,
4857
4375
  exitCode: stopped || childStopped ? 1 : timedOut ? 1 : singleResult.interrupted === true ? 0 : singleResult.exitCode,
4858
4376
  sessionFile: singleResult.sessionFile,
4859
4377
  intercomTarget: singleResult.intercomTarget,
4860
4378
  model: singleResult.model,
4379
+ thinking: singleResult.thinking,
4861
4380
  attemptedModels: singleResult.attemptedModels,
4862
4381
  modelAttempts: singleResult.modelAttempts,
4863
4382
  contextOverflow: singleResult.contextOverflow,
4864
4383
  totalCost: singleResult.totalCost,
4384
+ usage: singleResult.usage,
4865
4385
  artifactPaths: singleResult.artifactPaths,
4866
4386
  transcriptPath: singleResult.transcriptPath,
4867
4387
  transcriptError: singleResult.transcriptError,
@@ -4879,9 +4399,6 @@ async function runSubagent(
4879
4399
  interrupted: singleResult.interrupted,
4880
4400
  timedOut: timedOut || singleResult.timedOut ? true : undefined,
4881
4401
  stopped: stopped || childStopped ? true : undefined,
4882
- turnBudget: singleResult.turnBudget,
4883
- turnBudgetExceeded: singleResult.turnBudgetExceeded,
4884
- wrapUpRequested: singleResult.wrapUpRequested,
4885
4402
  toolBudget: singleResult.toolBudget,
4886
4403
  toolBudgetBlocked: singleResult.toolBudgetBlocked,
4887
4404
  runner: singleResult.runner,
@@ -4903,17 +4420,27 @@ async function runSubagent(
4903
4420
  input: cumulativeTokens.input - previousCumulativeTokens.input,
4904
4421
  output: cumulativeTokens.output - previousCumulativeTokens.output,
4905
4422
  total: cumulativeTokens.total - previousCumulativeTokens.total,
4423
+ ...(cumulativeTokens.window !== undefined ? { window: cumulativeTokens.window } : {}),
4424
+ ...(cumulativeTokens.windowPeak !== undefined ? { windowPeak: cumulativeTokens.windowPeak } : {}),
4906
4425
  }
4907
4426
  : null;
4908
4427
  if (cumulativeTokens) {
4909
4428
  previousCumulativeTokens = cumulativeTokens;
4910
4429
  } else {
4911
- stepTokens = tokenUsageFromAttempts(singleResult.modelAttempts);
4430
+ const fallbackTokens = tokenUsageFromAttempts(singleResult.modelAttempts);
4431
+ const observedTokens = requiredStatusStep(statusPayload, flatIndex).tokens;
4432
+ stepTokens = fallbackTokens
4433
+ ? { ...fallbackTokens, ...(observedTokens?.window !== undefined ? { window: observedTokens.window } : {}), ...(observedTokens?.windowPeak !== undefined ? { windowPeak: observedTokens.windowPeak } : {}) }
4434
+ : null;
4912
4435
  if (stepTokens) {
4913
4436
  previousCumulativeTokens = {
4914
4437
  input: previousCumulativeTokens.input + stepTokens.input,
4915
4438
  output: previousCumulativeTokens.output + stepTokens.output,
4916
4439
  total: previousCumulativeTokens.total + stepTokens.total,
4440
+ ...(stepTokens.window !== undefined ? { window: stepTokens.window } : {}),
4441
+ ...(previousCumulativeTokens.windowPeak !== undefined || stepTokens.windowPeak !== undefined
4442
+ ? { windowPeak: Math.max(previousCumulativeTokens.windowPeak ?? 0, stepTokens.windowPeak ?? 0) }
4443
+ : {}),
4917
4444
  };
4918
4445
  }
4919
4446
  }
@@ -4926,16 +4453,11 @@ async function runSubagent(
4926
4453
  requiredStatusStep(statusPayload, flatIndex).exitCode = stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;
4927
4454
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "timedOut", timedOut || singleResult.timedOut ? true : undefined);
4928
4455
  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
4456
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "toolBudget", singleResult.toolBudget);
4933
4457
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "toolBudgetBlocked", singleResult.toolBudgetBlocked);
4934
4458
  if (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;
4935
4459
  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;
4460
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "sessionName", singleResult.sessionName);
4939
4461
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "model", singleResult.model);
4940
4462
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "thinking", resolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, flatIndex).thinking));
4941
4463
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "attemptedModels", singleResult.attemptedModels);
@@ -4996,6 +4518,9 @@ async function runSubagent(
4996
4518
  diffs,
4997
4519
  results: [{
4998
4520
  agent: singleResult.agent,
4521
+ ...(handoffWorkflowKey ? { workflowKey: handoffWorkflowKey } : {}),
4522
+ ...(handoffChildRunId ? { runId: handoffChildRunId } : {}),
4523
+ ...(config.lane ? { lane: config.lane } : {}),
4999
4524
  status: singleResult.stopped ? "stopped" as const : singleResult.interrupted ? "paused" as const : singleResult.exitCode === 0 ? "completed" as const : "failed" as const,
5000
4525
  summary: singleResult.output || singleResult.error || "(no output)",
5001
4526
  ...(singleResult.artifactPaths?.outputPath ? { outputPath: singleResult.artifactPaths.outputPath } : {}),
@@ -5048,7 +4573,7 @@ async function runSubagent(
5048
4573
  }
5049
4574
  }
5050
4575
 
5051
- let summary = results.map((r) => `${r.agent}:\n${r.output}`).join("\n\n");
4576
+ let summary = results.map((r) => `${r.agent}:\n${r.output || (r.exitCode !== 0 ? r.error : undefined) || "(no output)"}`).join("\n\n");
5052
4577
  let truncated = false;
5053
4578
 
5054
4579
  if (maxOutput) {
@@ -5113,17 +4638,17 @@ async function runSubagent(
5113
4638
  clearTimeout(timeoutTimer);
5114
4639
  timeoutTimer = undefined;
5115
4640
  }
5116
- if (!timedOut && !stopped && !interrupted && config.timeoutMs !== undefined && results.some((result) => result.timedOut === true && result.error === timeoutMessage)) {
4641
+ if (!timedOut && !stopped && !interrupted && config.timeoutMs !== undefined && timeoutMessage !== undefined && results.some((result) => result.timedOut === true && result.error?.startsWith(timeoutMessage))) {
5117
4642
  timedOut = true;
5118
4643
  }
5119
- const signalTerminated = !stopped && !timedOut && !turnBudgetExceeded && !interrupted && results.some((result) => result.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
4644
+ const signalTerminated = !stopped && !timedOut && !interrupted && results.some((result) => result.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
5120
4645
  processSignal: result.processSignal,
5121
4646
  interrupted: result.interrupted,
5122
4647
  timedOut: result.timedOut,
5123
4648
  stopped: result.stopped,
5124
- turnBudgetExceeded: result.turnBudgetExceeded,
5125
4649
  })));
5126
- statusPayload.state = stopped || signalTerminated ? "stopped" : timedOut || turnBudgetExceeded || usageBudgetExceeded || statusPayload.error ? "failed" : interrupted ? "paused" : results.every((r) => r.success) ? "complete" : "failed";
4650
+ const partialWithEvidence = !stopped && !signalTerminated && !timedOut && !usageBudgetExceeded && !interrupted && results.some(partialEvidenceResult) && !results.some(concreteFailureResult);
4651
+ statusPayload.state = stopped || signalTerminated ? "stopped" : timedOut || usageBudgetExceeded ? "failed" : interrupted ? "paused" : results.every((r) => r.success) ? "complete" : partialWithEvidence ? "partial" : "failed";
5127
4652
  closeSteerInbox(asyncDir, statusPayload.state, (filePath, payload) => runPersistence.write(filePath, payload));
5128
4653
  disposeControlInbox();
5129
4654
  for (const request of consumeSteerRequests(asyncDir)) deliverSteerRequest(request);
@@ -5153,13 +4678,17 @@ async function runSubagent(
5153
4678
  statusPayload.timedOut = true;
5154
4679
  statusPayload.error = timeoutMessage ?? "Subagent timed out.";
5155
4680
  }
5156
- if (turnBudgetExceeded && !statusPayload.error) {
5157
- const budget = statusPayload.turnBudget;
5158
- statusPayload.error = budget ? turnBudgetExceededMessage(budget, budget.turnCount) : "Subagent exceeded turn budget.";
5159
- }
5160
4681
  if (usageBudgetExceeded && statusPayload.usageBudget && !statusPayload.error) {
5161
4682
  statusPayload.error = usageBudgetExceededMessage(statusPayload.usageBudget);
5162
4683
  }
4684
+ if (partialWithEvidence) {
4685
+ const partialResult = results.find(partialEvidenceResult);
4686
+ statusPayload.activityState = "needs_attention";
4687
+ statusPayload.error = partialResult?.error ?? statusPayload.error;
4688
+ for (const step of statusPayload.steps) {
4689
+ if (step.status === "failed") step.activityState = "needs_attention";
4690
+ }
4691
+ }
5163
4692
  statusPayload.endedAt = runEndedAt;
5164
4693
  statusPayload.lastUpdate = runEndedAt;
5165
4694
  setOptionalProperty(statusPayload, "sessionFile", effectiveSessionFile);
@@ -5169,56 +4698,53 @@ async function runSubagent(
5169
4698
  setOptionalProperty(statusPayload, "shareUrl", shareUrl);
5170
4699
  setOptionalProperty(statusPayload, "gistUrl", gistUrl);
5171
4700
  setOptionalProperty(statusPayload, "shareError", shareError);
5172
- if (statusPayload.state === "failed" && !statusPayload.error) {
5173
- const failedStep = statusPayload.steps.find((s) => s.status === "failed");
4701
+ if ((statusPayload.state === "failed" || statusPayload.state === "partial") && !statusPayload.error) {
4702
+ const concreteFailure = results.find(concreteFailureResult);
4703
+ const failedStep = concreteFailure ? undefined : statusPayload.steps.find((s) => s.status === "failed");
4704
+ if (concreteFailure?.error) statusPayload.error = concreteFailure.error;
5174
4705
  if (failedStep?.agent) {
5175
4706
  statusPayload.error = `Step failed: ${failedStep.agent}`;
5176
4707
  }
5177
4708
  }
5178
- writeStatusPayload();
5179
4709
  try {
5180
4710
  runPersistence.write(resultPath, {
5181
4711
  lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
5182
4712
  id,
5183
4713
  agent: agentName,
5184
4714
  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,
4715
+ success: statusPayload.state === "complete",
4716
+ state: statusPayload.state,
4717
+ 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
4718
  ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),
5189
4719
  ...(config.deadlineAt !== undefined ? { deadlineAt: config.deadlineAt } : {}),
5190
- ...(statusPayload.turnBudget ? { turnBudget: statusPayload.turnBudget } : {}),
5191
- ...(statusPayload.turnBudgetExceeded ? { turnBudgetExceeded: true } : {}),
5192
- ...(statusPayload.wrapUpRequested ? { wrapUpRequested: true } : {}),
5193
4720
  ...(statusPayload.toolBudget ? { toolBudget: statusPayload.toolBudget } : {}),
5194
4721
  ...(statusPayload.toolBudgetBlocked ? { toolBudgetBlocked: true } : {}),
5195
4722
  ...(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." } : {}),
4723
+ ...(stopped ? { stopped: true, error: stopMessage } : timedOut ? { timedOut: true, error: timeoutMessage ?? "Subagent timed out." } : usageBudgetExceeded ? { error: statusPayload.error ?? "Usage budget exhausted." } : {}),
5197
4724
  results: results.map((r) => omitUndefinedProperties({
5198
4725
  agent: r.agent,
4726
+ ...(r.sessionName ? { sessionName: r.sessionName } : {}),
5199
4727
  context: r.context,
5200
4728
  output: r.output,
5201
4729
  outputState: r.outputState,
5202
4730
  error: r.error,
5203
- protocolError: r.protocolError,
5204
4731
  success: r.success,
5205
4732
  skipped: r.skipped || undefined,
5206
4733
  interrupted: r.interrupted || undefined,
5207
4734
  timedOut: r.timedOut || undefined,
5208
4735
  stopped: r.stopped || undefined,
5209
4736
  processSignal: r.processSignal || undefined,
5210
- turnBudget: r.turnBudget,
5211
- turnBudgetExceeded: r.turnBudgetExceeded || undefined,
5212
- wrapUpRequested: r.wrapUpRequested || undefined,
5213
4737
  toolBudget: r.toolBudget,
5214
4738
  toolBudgetBlocked: r.toolBudgetBlocked || undefined,
5215
4739
  sessionFile: r.sessionFile,
5216
4740
  intercomTarget: r.intercomTarget,
5217
4741
  model: r.model,
4742
+ thinking: r.thinking,
5218
4743
  attemptedModels: r.attemptedModels,
5219
4744
  modelAttempts: r.modelAttempts,
5220
4745
  contextOverflow: r.contextOverflow,
5221
4746
  totalCost: r.totalCost,
4747
+ usage: r.usage,
5222
4748
  artifactPaths: r.artifactPaths,
5223
4749
  outputSaveError: r.outputSaveError,
5224
4750
  metadataSaveError: r.metadataSaveError,
@@ -5226,6 +4752,7 @@ async function runSubagent(
5226
4752
  transcriptPath: r.transcriptPath,
5227
4753
  transcriptError: r.transcriptError,
5228
4754
  agentContract: r.agentContract,
4755
+ sandbox: r.sandbox,
5229
4756
  launchContractDigest: r.launchContractDigest,
5230
4757
  launchResolvedExtensions: r.launchResolvedExtensions,
5231
4758
  runtimeAcknowledgedExtensions: r.runtimeAcknowledgedExtensions,
@@ -5251,7 +4778,7 @@ async function runSubagent(
5251
4778
  capabilityAudit: statusPayload.capabilityAudit,
5252
4779
  ...(config.parentWorkflowRunId ? { parentWorkflowRunId: config.parentWorkflowRunId } : {}),
5253
4780
  ...(config.workflowKey ? { workflowKey: config.workflowKey } : {}),
5254
- exitCode: stopped || timedOut || turnBudgetExceeded || usageBudgetExceeded ? 1 : interrupted || results.every((r) => r.success) ? 0 : 1,
4781
+ exitCode: statusPayload.state === "complete" || statusPayload.state === "paused" ? 0 : 1,
5255
4782
  timestamp: runEndedAt,
5256
4783
  durationMs: runEndedAt - overallStartTime,
5257
4784
  totalTokens: statusPayload.totalTokens,
@@ -5283,7 +4810,7 @@ async function runSubagent(
5283
4810
  statusPayload.lastUpdate = Date.now();
5284
4811
  }
5285
4812
  writeStatusPayload();
5286
- orcaProgressTab?.finish(statusPayload.state === "complete" ? "completed" : statusPayload.state === "stopped" ? "stopped" : "failed", effectiveSessionFile);
4813
+ await orcaProgressTab?.finish(statusPayload.state === "complete" ? "completed" : statusPayload.state === "stopped" ? "stopped" : "failed", effectiveSessionFile);
5287
4814
  appendJsonl(
5288
4815
  eventsPath,
5289
4816
  JSON.stringify({
@@ -5318,14 +4845,21 @@ async function runSubagent(
5318
4845
  }), (filePath, content) => runPersistence.write(filePath, { content }, (_path, payload) => {
5319
4846
  fs.writeFileSync(_path, (payload as { content: string }).content, "utf-8");
5320
4847
  }));
5321
- if (runPersistence.pendingCount() === 0) runPersistence.dispose();
5322
- if (indexPersistence.pendingCount() === 0) indexPersistence.dispose();
4848
+ // The run is committed: release the child sessions first, then wait for the
4849
+ // storage-capacity retries that may still hold the final status or result.
4850
+ await childSessions.dispose().catch((error: unknown) => console.error("Failed to dispose runner child sessions:", error));
4851
+ while (runPersistence.pendingCount() + indexPersistence.pendingCount() > 0) {
4852
+ await new Promise((resolve) => setTimeout(resolve, 200));
4853
+ }
4854
+ runPersistence.dispose();
4855
+ indexPersistence.dispose();
5323
4856
  if (config.runnerProcessInstanceId) {
4857
+ // Children run inside this process, so no step has writer processes to prove terminal.
5324
4858
  const writers: Record<string, PiWriterProcessInstanceExitV1[]> = {};
5325
4859
  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;
4860
+ for (const index of results.keys()) {
4861
+ writers[String(index)] = [];
4862
+ expectedWriters[String(index)] = 0;
5329
4863
  }
5330
4864
  const candidate: ProcessTerminalCandidate = {
5331
4865
  version: 1,
@@ -5359,7 +4893,7 @@ async function waitForStartupControl(
5359
4893
  } catch (error) {
5360
4894
  throw new Error(`Failed to read runner startup control '${controlPath}': ${error instanceof Error ? error.message : String(error)}`);
5361
4895
  }
5362
- if (payload.token !== token) throw new Error("Runner startup control token does not match the acquired session lease.");
4896
+ if (payload.token !== token) throw new Error("Runner startup control token does not match.");
5363
4897
  if (payload.action === action) return;
5364
4898
  if (payload.action !== "ack" && payload.action !== "proceed") throw new Error("Runner startup control action is invalid.");
5365
4899
  }
@@ -5370,7 +4904,7 @@ async function waitForStartupControl(
5370
4904
 
5371
4905
  async function runConfiguredSubagent(config: SubagentRunConfig): Promise<void> {
5372
4906
  let lease: ReturnType<typeof acquireSessionLease> | undefined;
5373
- let startupCommitted = config.revivalLease === undefined;
4907
+ let startupCommitted = config.revivalLease === undefined && config.launchBarrierToken === undefined;
5374
4908
  const startupPath = path.join(config.asyncDir, "runner-startup.json");
5375
4909
  const startupAckPath = path.join(config.asyncDir, "runner-startup-ack.json");
5376
4910
  const startupProceedPath = path.join(config.asyncDir, "runner-startup-proceed.json");
@@ -5383,7 +4917,15 @@ async function runConfiguredSubagent(config: SubagentRunConfig): Promise<void> {
5383
4917
  };
5384
4918
  process.once("exit", releaseOnExit);
5385
4919
  try {
5386
- if (config.revivalLease) {
4920
+ if (config.launchBarrierToken) {
4921
+ await waitForStartupControl(startupProceedPath, config.launchBarrierToken, "proceed");
4922
+ startupCommitted = true;
4923
+ try {
4924
+ fs.rmSync(startupProceedPath, { force: true });
4925
+ } catch {
4926
+ // Startup control cleanup is best effort after the parent commits the run.
4927
+ }
4928
+ } else if (config.revivalLease) {
5387
4929
  lease = acquireSessionLease(config.revivalLease);
5388
4930
  config.revivalLeaseToken = lease.owner.token;
5389
4931
  writeAtomicJson(startupPath, { state: "ready", token: lease.owner.token, pid: process.pid, owner: lease.owner });
@@ -5399,9 +4941,18 @@ async function runConfiguredSubagent(config: SubagentRunConfig): Promise<void> {
5399
4941
  }
5400
4942
  }
5401
4943
  }
5402
- await runSubagent(config, lease ? (writer) => lease!.updateWriter(writer) : undefined);
4944
+ const childSessions = await loadRunnerChildSessionFactory(config);
4945
+ try {
4946
+ await runSubagent(config, childSessions);
4947
+ } finally {
4948
+ try {
4949
+ await childSessions.dispose();
4950
+ } catch (error) {
4951
+ console.error("Failed to dispose runner child sessions:", error);
4952
+ }
4953
+ }
5403
4954
  } catch (error) {
5404
- if (config.revivalLease && !startupCommitted) {
4955
+ if (!startupCommitted) {
5405
4956
  try {
5406
4957
  writeAtomicJson(startupPath, { state: "error", pid: process.pid, error: error instanceof Error ? error.message : String(error) });
5407
4958
  } catch {
@@ -5428,10 +4979,16 @@ async function runConfiguredSubagent(config: SubagentRunConfig): Promise<void> {
5428
4979
  }
5429
4980
 
5430
4981
  function startConfiguredSubagent(config: SubagentRunConfig): void {
5431
- runConfiguredSubagent(config).catch((runErr) => {
5432
- console.error("Subagent runner error:", runErr);
5433
- process.exit(1);
5434
- });
4982
+ // Child sessions and the extensions loaded into them may leave handles
4983
+ // behind even after shutdown; the run is fully persisted by now, so exit
4984
+ // explicitly instead of waiting for the event loop to drain.
4985
+ runConfiguredSubagent(config).then(
4986
+ () => process.exit(0),
4987
+ (runErr) => {
4988
+ console.error("Subagent runner error:", runErr);
4989
+ process.exit(1);
4990
+ },
4991
+ );
5435
4992
  }
5436
4993
 
5437
4994
  const configArg = process.argv[2];