@xzzpig/pi-subagents 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  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 +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. 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 } 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,29 +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,
47
+ type SubagentChildStatusEvent,
48
+ type WorkflowLaneMetadata,
51
49
  DEFAULT_MAX_OUTPUT,
52
50
  type MaxOutputConfig,
53
51
  SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
54
- POLL_INTERVAL_MS,
55
52
  truncateOutput,
56
- getSubagentDepthEnv,
57
53
  } from "../../shared/types.ts";
58
54
  import {
59
55
  DEFAULT_CONTROL_CONFIG,
@@ -76,30 +72,29 @@ import {
76
72
  DEFAULT_GLOBAL_CONCURRENCY_LIMIT,
77
73
  Semaphore,
78
74
  } from "../shared/parallel-utils.ts";
79
- import { applyThinkingSuffix, buildPiArgs, cleanupTempDir, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan, type SubagentTaskDelivery } from "../shared/pi-args.ts";
80
- 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";
81
83
  import { outputEntryFromAsyncResult, resolveOutputReferences } from "../shared/chain-outputs.ts";
82
- import { createStructuredOutputRuntime, MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput } from "../shared/structured-output.ts";
83
- import { formatProcessSignalError, isUnexplainedProcessSignal } from "../shared/process-signal.ts";
84
- 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";
87
+ import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.ts";
85
88
  import { collectDynamicResults, DynamicFanoutError, materializeDynamicParallelStep, validateDynamicCollection } from "../shared/dynamic-fanout.ts";
86
89
  import { claimRunFanoutBatch, getRunFanoutBudgetSnapshot } from "../shared/run-fanout-budget.ts";
87
90
  import { nestedSummaryFromAsyncStatus, projectNestedEvents, resolveNestedAsyncDir, writeNestedEvent } from "../shared/nested-events.ts";
88
- import { formatModelAttemptNote, isRetryableModelFailure, recordRetryableModelFailure } from "../shared/model-fallback.ts";
89
- import {
90
- SUBAGENT_STARTUP_RETRY_DELAYS_MS,
91
- formatSubagentExtensionConflictError,
92
- formatSubagentStartupRetryExhaustedError,
93
- formatSubagentStartupRetryNote,
94
- isRetryableSubagentStartupFailure,
95
- waitForSubagentStartupRetry,
96
- } from "../shared/subagent-startup-retry.ts";
91
+ import { formatModelAttemptNote, formatSubagentModelVerificationError, isContextOverflow, isRetryableModelFailureAttempt, recordRetryableModelFailure } from "../shared/model-fallback.ts";
97
92
  import { markProcessTerminalCandidateLeaseRelease, writeProcessTerminalCandidate, type ProcessTerminalCandidate } from "./process-terminal.ts";
98
- import { createOwnedProcessTreeController, type OwnedProcessTreeController } from "./owned-process-tree.ts";
99
93
  import { createSteeringStatus, recordSteeringRequest, steeringStatus, terminalSteeringNoticeState, updateSteeringTarget } from "./steering.ts";
100
- import { attachPostExitStdioGuard, trySignalChild } from "../../shared/post-exit-stdio-guard.ts";
101
- import { PROMPT_REDACTED, detectSubagentError, extractTextFromContent, extractToolArgsPreview, getFinalOutput, hasEmptyTerminalAssistantResponse, readStatus } from "../../shared/utils.ts";
102
- import { evaluateCompletionMutationGuard } 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";
103
98
  import {
104
99
  createMutatingFailureState,
105
100
  didMutatingToolFail,
@@ -120,40 +115,49 @@ import {
120
115
  findWorktreeTaskCwdConflict,
121
116
  formatWorktreeDiffSummary,
122
117
  formatWorktreeTaskCwdConflict,
118
+ WORKTREE_AGENT_CWD_PLACEHOLDER,
123
119
  type WorktreeSetup,
124
120
  } from "../shared/worktree.ts";
125
- import { resolveEffectiveThinking } from "../../shared/model-info.ts";
121
+ import { findModelInfo, resolveEffectiveThinking } from "../../shared/model-info.ts";
122
+ import { assertThinkingWithinCeiling } from "../../shared/thinking-ceiling.ts";
126
123
  import { launchBindingDigest } from "../../shared/launch-contract.ts";
127
124
  import { writeInitialProgressFile } from "../../shared/settings.ts";
128
125
  import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.ts";
129
- 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";
130
127
  import { attachContractProjections, isAgentContractV1 } from "../shared/agent-contract.ts";
131
128
  import { waitForImportedAsyncRoot } from "./chain-root-attachment.ts";
129
+ import { normalizeExtensionBindings } from "../shared/extension-bindings.ts";
132
130
  import { appendRunnerStepsToStatus, consumeChainAppendRequests, countPendingChainAppendRequests, statusStepDescription } from "./chain-append.ts";
133
- import { appendTurnBudgetSystemPrompt, formatTurnBudgetOutput, initialTurnBudgetState, turnBudgetDecision, turnBudgetDeferredNote, turnBudgetDeferredState, turnBudgetExceededMessage, turnBudgetSoftNote, turnBudgetState } from "../shared/turn-budget.ts";
131
+ import { asyncStatusChildIdentity } from "../shared/child-identity.ts";
134
132
  import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
135
133
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, toolTimeoutCallKey } from "../shared/tool-timeout.ts";
136
134
  import { usageBudgetExceededMessage, usageBudgetState } from "../shared/usage-budget.ts";
137
135
  import { formatParallelHandoffError, formatParallelHandoffReference, parallelHandoffPath, writeParallelHandoffGroup, writePendingParallelHandoff } from "../shared/parallel-handoff.ts";
138
136
  import { resolveWatchdogConfig } from "../../watchdog/settings.ts";
139
- import { createBoundedByteTail, createBoundedLineReader, formatProtocolOutputLimit, MAX_CHILD_STDERR_BYTES, PI_AGGREGATE_EVENT_PROJECTOR, projectChildLifecycle, type ChildLifecycleAction, type ProtocolOutputLimit } from "../shared/child-protocol.ts";
140
137
  import { acquireSessionLease, type SessionLeaseRequest } from "../shared/session-lease.ts";
141
138
  import { buildExternalCliPrompt, runExternalCli } from "../shared/external-cli-runner.ts";
139
+ import { resolveClaudeCodeLaunch } from "../shared/claude-code-adapter.ts";
140
+ import { resolveCodexExecLaunch } from "../shared/codex-exec-adapter.ts";
141
+ import { resolveCursorAgentLaunch } from "../shared/cursor-agent-adapter.ts";
142
+ import { resolveExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
142
143
  import { runExternalJob } from "../shared/external-job-runner.ts";
143
144
  import { createOrcaProgressTab, type OrcaProgressTab } from "../shared/orca-progress-tabs.ts";
144
- import { decodeSubagentCapabilityCeiling, SUBAGENT_CAPABILITY_CEILING_ENV, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
145
+ import type { ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
145
146
  import {
146
- CHILD_WATCHDOG_CONFIG_ENV,
147
147
  acceptChildWatchdogEvent,
148
- childWatchdogIsActive,
149
- decodeChildWatchdogConfig,
148
+ applyChildWatchdogMessage,
150
149
  isChildWatchdogStatusEvent,
151
150
  resolveChildWatchdogConfig,
152
- type ChildWatchdogStateSnapshot,
151
+ type ChildWatchdogStatusEvent,
153
152
  } from "../../watchdog/child-status.ts";
154
153
 
155
154
  const INTERCOM_DETACH_RECEIPT = "Detached for intercom coordination before task completion.";
156
155
 
156
+ // This process hosts child sessions. An ambient copy of pi-subagents loaded
157
+ // into one of them must register nothing; the variable marks the process as a
158
+ // child host.
159
+ process.env[SUBAGENT_CHILD_ENV] = "1";
160
+
157
161
  interface SubagentRunConfig {
158
162
  id: string;
159
163
  steps: RunnerStep[];
@@ -171,10 +175,16 @@ interface SubagentRunConfig {
171
175
  sessionId?: string | null;
172
176
  completionOwnerId?: string;
173
177
  piPackageRoot?: string;
174
- piArgv1?: string;
178
+ /** Test seam: module the runner imports its `ChildSessionFactory` from. */
179
+ childSessionFactoryModule?: string;
180
+ /** The launching executor's own child runtime when it was itself an in-process child. */
181
+ inheritedChildRuntime?: InheritedChildRuntime;
175
182
  worktreeSetupHook?: string;
176
183
  worktreeSetupHookTimeoutMs?: number;
177
184
  worktreeBaseDir?: string;
185
+ baseRef?: string;
186
+ worktreeProvider?: import("../../shared/types.ts").WorktreeProvider;
187
+ worktreeBranchPrefix?: string;
178
188
  controlConfig?: ResolvedControlConfig;
179
189
  controlIntercomTarget?: string;
180
190
  childIntercomTargets?: Array<string | undefined>;
@@ -188,7 +198,6 @@ interface SubagentRunConfig {
188
198
  deadlineAt?: number;
189
199
  /** Resolved configured hard per-tool-call timeout (ms); fast tools still have a default when undefined. */
190
200
  toolTimeoutMs?: number;
191
- turnBudget?: ResolvedTurnBudget;
192
201
  toolBudget?: ResolvedToolBudget;
193
202
  usageBudget?: UsageBudgetConfig;
194
203
  revivalLease?: SessionLeaseRequest;
@@ -201,12 +210,16 @@ interface SubagentRunConfig {
201
210
  launchResolvedExtensions?: LaunchResolvedChildExtensionsV1;
202
211
  runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
203
212
  runnerProcessInstanceId?: string;
213
+ launchBarrierToken?: string;
204
214
  parentWorkflowRunId?: string;
205
215
  workflowKey?: string;
216
+ lane?: WorkflowLaneMetadata;
206
217
  }
207
218
 
208
219
  interface StepResult {
209
220
  agent: string;
221
+ /** Human-readable display name for the child session, when derived at launch. */
222
+ sessionName?: string;
210
223
  context?: "fresh" | "fork";
211
224
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
212
225
  capabilityAudit?: import("../shared/capability-ceiling.ts").SubagentCapabilityAudit;
@@ -215,7 +228,6 @@ interface StepResult {
215
228
  output: string;
216
229
  outputState?: SubagentOutputState;
217
230
  error?: string;
218
- protocolError?: ProtocolOutputLimit;
219
231
  success?: boolean;
220
232
  exitCode: number | null;
221
233
  usage?: Usage;
@@ -226,16 +238,17 @@ interface StepResult {
226
238
  timedOut?: boolean;
227
239
  stopped?: boolean;
228
240
  processSignal?: string | null;
229
- turnBudget?: TurnBudgetState;
230
- turnBudgetExceeded?: boolean;
231
- wrapUpRequested?: boolean;
241
+ timeoutRecovery?: import("../../shared/types.ts").TimeoutRecoverySummary;
232
242
  toolBudget?: ToolBudgetState;
233
243
  toolBudgetBlocked?: boolean;
234
244
  sessionFile?: string;
235
245
  intercomTarget?: string;
236
246
  model?: string;
247
+ thinking?: string;
237
248
  attemptedModels?: string[];
238
249
  modelAttempts?: ModelAttempt[];
250
+ /** True when the dispatch failed because the input exceeded the model's context window. */
251
+ contextOverflow?: boolean;
239
252
  totalCost?: CostSummary;
240
253
  artifactPaths?: ArtifactPaths;
241
254
  outputSaveError?: string;
@@ -253,8 +266,6 @@ interface StepResult {
253
266
  structuredOutputSchemaPath?: string;
254
267
  acceptance?: import("../../shared/types.ts").AcceptanceLedger;
255
268
  watchdog?: import("../../shared/types.ts").ChildWatchdogProgress;
256
- writerProcesses?: PiWriterProcessInstanceExitV1[];
257
- writerAttemptCount?: number;
258
269
  runner?: ExternalCliRunnerStatus | ExternalJobRunnerStatus;
259
270
  externalProcess?: ExternalProcessStatus;
260
271
  externalJob?: ExternalJobStatus;
@@ -355,10 +366,6 @@ function appendDiagnosticJsonl(filePath: string, line: string, droppedEventType?
355
366
  state.diagnosticsTruncated = true;
356
367
  }
357
368
 
358
- function shouldPersistChildEvent(event: Record<string, unknown>): boolean {
359
- return event.type !== "message_update";
360
- }
361
-
362
369
  function isBlockingSupervisorTool(toolName: string | undefined, args: unknown): boolean {
363
370
  if (!args || typeof args !== "object" || Array.isArray(args)) return false;
364
371
  if (toolName === "contact_supervisor") {
@@ -414,6 +421,23 @@ function costSummaryFromAttempts(attempts: ModelAttempt[] | undefined): CostSumm
414
421
  : undefined;
415
422
  }
416
423
 
424
+ function usageFromAttempts(attempts: ModelAttempt[] | undefined): Usage | undefined {
425
+ if (!attempts || attempts.length === 0) return undefined;
426
+ const usage = emptyUsage();
427
+ for (const attempt of attempts) {
428
+ if (!attempt.usage) continue;
429
+ usage.input += attempt.usage.input;
430
+ usage.output += attempt.usage.output;
431
+ usage.cacheRead += attempt.usage.cacheRead;
432
+ usage.cacheWrite += attempt.usage.cacheWrite;
433
+ usage.cost += attempt.usage.cost;
434
+ usage.turns += attempt.usage.turns;
435
+ }
436
+ return usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0
437
+ ? usage
438
+ : undefined;
439
+ }
440
+
417
441
  function appendRecentStepOutput(step: RunnerStatusStep, lines: string[]): void {
418
442
  const nonEmpty = lines.filter((line) => line.trim());
419
443
  if (nonEmpty.length === 0) return;
@@ -424,15 +448,6 @@ function appendRecentStepOutput(step: RunnerStatusStep, lines: string[]): void {
424
448
  }
425
449
  }
426
450
 
427
- function assistantStartsToolCall(message: Message): boolean {
428
- return Array.isArray(message.content)
429
- && message.content.some((part) => (part as { type?: string }).type === "toolCall");
430
- }
431
-
432
- function isTerminalAssistantStop(message: Message): boolean {
433
- return (message as { stopReason?: string }).stopReason === "stop" && !assistantStartsToolCall(message);
434
- }
435
-
436
451
  type UndefinedOmitted<T extends object> = {
437
452
  [K in keyof T]: Exclude<T[K], undefined>;
438
453
  };
@@ -475,571 +490,38 @@ function resetStepLiveDetail(step: RunnerStatusStep): void {
475
490
  step.recentOutput = [];
476
491
  }
477
492
 
478
- interface ChildEventContext {
479
- eventsPath: string;
480
- runId: string;
481
- stepIndex: number;
482
- agent: string;
483
- }
493
+ const MAX_CHILD_FAILURE_DIAGNOSTIC_CHARS = 8_192;
484
494
 
485
- interface ChildUsage {
486
- input?: number;
487
- inputTokens?: number;
488
- output?: number;
489
- outputTokens?: number;
490
- cacheRead?: number;
491
- cacheWrite?: number;
492
- cost?: { total?: number };
495
+ function formatRequiredOutputError(requiredOutput: {
496
+ kind: "file-only" | "structured";
497
+ path: string;
498
+ missing: boolean;
499
+ } | undefined): string | undefined {
500
+ if (!requiredOutput?.missing) return undefined;
501
+ return `Required ${requiredOutput.kind} output was not produced: ${requiredOutput.path.slice(0, 2_048)}`;
493
502
  }
494
503
 
495
- type ChildMessage = Message & {
496
- model?: string;
497
- errorMessage?: string;
498
- usage?: ChildUsage;
499
- };
500
-
501
- interface ChildEvent {
502
- type?: string;
503
- message?: ChildMessage;
504
- toolName?: string;
505
- args?: Record<string, unknown>;
506
- willRetry?: unknown;
507
- }
508
-
509
- interface RunPiStreamingResult {
510
- stderr: string;
511
- exitCode: number | null;
512
- messages: Message[];
513
- usage: Usage;
514
- toolCount: number;
515
- durationMs: number;
516
- model?: string;
517
- error?: string;
518
- protocolError?: ProtocolOutputLimit;
519
- finalOutput: string;
520
- outputState: SubagentOutputState;
521
- interrupted?: boolean;
522
- timedOut?: boolean;
523
- stopped?: boolean;
524
- turnBudget?: TurnBudgetState;
525
- turnBudgetExceeded?: boolean;
526
- wrapUpRequested?: boolean;
527
- toolBudget?: ToolBudgetState;
528
- toolBudgetBlocked?: boolean;
529
- observedMutationAttempt?: boolean;
530
- structuredOutputToolInvoked?: boolean;
531
- structuredOutputMessageStartIndex?: number;
532
- watchdog?: ChildWatchdogStateSnapshot;
533
- runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1;
534
- processInstanceId: string;
535
- processCloseObservedAt?: number;
536
- processSignal?: string | null;
537
- processTree: ProcessTreeTerminalV1;
538
- }
539
-
540
- function runPiStreaming(
541
- args: string[],
542
- cwd: string,
543
- outputFile: string,
544
- env?: Record<string, string | undefined>,
545
- piPackageRoot?: string,
546
- piArgv1?: string,
547
- maxSubagentDepth?: number,
548
- childEventContext?: ChildEventContext,
549
- registerInterrupt?: (interrupt: (() => void) | undefined) => void,
550
- onChildEvent?: (event: ChildEvent) => void,
551
- transcriptWriter?: ChildTranscriptWriter,
552
- registerTimeout?: (interrupt: (() => void) | undefined) => void,
553
- timeoutMessage?: string,
554
- registerStop?: (stop: (() => void) | undefined) => void,
555
- stopMessage?: string,
556
- registerTurnBudgetAbort?: (abort: ((message: string, state?: TurnBudgetState) => void) | undefined) => void,
557
- onWriterProcess?: (writer: { state: "none" | "spawning" } | { state: "running"; pid: number }) => void,
558
- toolTimeoutMs?: number,
559
- runDeadlineAt?: number,
560
- orcaProgressTab?: OrcaProgressTab,
561
- ): Promise<RunPiStreamingResult> {
562
- return new Promise((resolve) => {
563
- const startedAt = Date.now();
564
- const processInstanceId = randomUUID();
565
- onWriterProcess?.({ state: "spawning" });
566
- const outputStream = fs.createWriteStream(outputFile, { flags: "w" });
567
- const spawnEnv = { ...process.env, ...(env ?? {}), ...getSubagentDepthEnv(maxSubagentDepth) };
568
- const spawnSpec = getPiSpawnCommand(args, {
569
- ...(piPackageRoot ? { piPackageRoot } : {}),
570
- ...(piArgv1 ? { argv1: piArgv1 } : {}),
571
- });
572
- const child = spawn(spawnSpec.command, spawnSpec.args, {
573
- cwd,
574
- stdio: ["ignore", "pipe", "pipe"],
575
- env: spawnEnv,
576
- windowsHide: true,
577
- detached: process.platform !== "win32",
578
- });
579
- let processTreeController: OwnedProcessTreeController | undefined;
580
- const stderrTail = createBoundedByteTail();
581
- const rawStdoutTail = createBoundedByteTail();
582
- const messages: Message[] = [];
583
- const usage = emptyUsage();
584
- let model: string | undefined;
585
- let writerRegistrationError: string | undefined;
586
- if (typeof child.pid === "number") {
587
- processTreeController = createOwnedProcessTreeController(child.pid);
588
- try {
589
- onWriterProcess?.({ state: "running", pid: child.pid });
590
- } catch (writerError) {
591
- writerRegistrationError = `Failed to record revived Pi writer ownership: ${writerError instanceof Error ? writerError.message : String(writerError)}`;
592
- trySignalChild(child, "SIGKILL");
593
- }
594
- }
595
- let error: string | undefined = writerRegistrationError;
596
- let assistantError: string | undefined;
597
- let interrupted = false;
598
- let timedOut = false;
599
- let stopped = false;
600
- let turnBudgetExceeded = false;
601
- let turnBudgetMessage: string | undefined;
602
- let turnBudget: TurnBudgetState | undefined;
603
- let observedMutationAttempt = false;
604
- let structuredOutputToolInvoked = false;
605
- let structuredOutputMessageStartIndex: number | undefined;
606
- let toolCount = 0;
607
- const childWatchdogConfig = decodeChildWatchdogConfig(env?.[CHILD_WATCHDOG_CONFIG_ENV]);
608
- let childWatchdogState: ChildWatchdogStateSnapshot | undefined;
609
- let applyChildLifecycle = (_action: ChildLifecycleAction): void => {};
610
- const updateChildWatchdogState = (snapshot: ChildWatchdogStateSnapshot): void => {
611
- childWatchdogState = snapshot;
612
- };
613
-
614
- const writeOutputLine = (line: string) => {
615
- if (!line.trim()) return;
616
- outputStream.write(`${line}\n`);
617
- orcaProgressTab?.append(`${line}\n`);
618
- };
619
-
620
- const writeOutputText = (text: string) => {
621
- for (const line of text.split("\n")) {
622
- writeOutputLine(line);
623
- }
624
- };
625
-
626
- const appendChildEvent = (event: Record<string, unknown>) => {
627
- if (!childEventContext) return;
628
- if (!shouldPersistChildEvent(event)) return;
629
- appendDiagnosticJsonl(childEventContext.eventsPath, JSON.stringify({
630
- ...event,
631
- subagentSource: "child",
632
- subagentRunId: childEventContext.runId,
633
- subagentStepIndex: childEventContext.stepIndex,
634
- subagentAgent: childEventContext.agent,
635
- observedAt: Date.now(),
636
- }), typeof event.type === "string" ? event.type : undefined);
637
- };
638
-
639
- const appendChildLine = (type: "subagent.child.stdout" | "subagent.child.stderr", line: string) => {
640
- appendChildEvent({ type, line });
641
- if (type === "subagent.child.stdout") transcriptWriter?.writeStdoutLine(line);
642
- else transcriptWriter?.writeStderrLine(line);
643
- };
644
-
645
- const processStdoutLine = (line: string) => {
646
- if (!line.trim()) return;
647
- let event: ChildEvent;
648
- try {
649
- event = JSON.parse(line) as ChildEvent;
650
- } catch {
651
- rawStdoutTail.push(`${line}\n`);
652
- writeOutputLine(line);
653
- appendChildLine("subagent.child.stdout", line);
654
- return;
655
- }
656
-
657
- appendChildEvent(event as unknown as Record<string, unknown>);
658
- transcriptWriter?.writeChildEvent(event);
659
- if (event.type === "agent_settled") agentSettledReceived = true;
660
- applyChildLifecycle(projectChildLifecycle(event));
661
-
662
- if (isChildWatchdogStatusEvent(event)) {
663
- if (!childWatchdogConfig) return;
664
- const next = acceptChildWatchdogEvent({
665
- current: childWatchdogState,
666
- event,
667
- ...(childEventContext ? {
668
- runId: childEventContext.runId,
669
- agent: childEventContext.agent,
670
- childIndex: childEventContext.stepIndex,
671
- } : {}),
672
- });
673
- if (!next) return;
674
- updateChildWatchdogState(next);
675
- onChildEvent?.(event);
676
- if (childWatchdogIsActive(next)) {
677
- if (finalDrainTimer) {
678
- clearTimeout(finalDrainTimer);
679
- finalDrainTimer = undefined;
680
- }
681
- if (finalHardKillTimer) {
682
- clearTimeout(finalHardKillTimer);
683
- finalHardKillTimer = undefined;
684
- }
685
- armWatchdogTail();
686
- } else {
687
- clearWatchdogTailTimer();
688
- if (cleanTerminalAssistantStopReceived || agentSettledReceived) startFinalDrain();
689
- }
690
- return;
691
- }
692
-
693
- onChildEvent?.(event);
694
-
695
- if (event.type === "tool_execution_end") {
696
- clearActiveToolTimeout(event);
697
- return;
698
- }
699
-
700
- if (event.type === "tool_execution_start" && event.toolName) {
701
- toolCount += 1;
702
- armToolTimeout({ toolCallId: (event as { toolCallId?: unknown }).toolCallId, toolName: event.toolName });
703
- if (event.toolName === "structured_output") {
704
- structuredOutputToolInvoked = true;
705
- structuredOutputMessageStartIndex = messages.length;
706
- }
707
- observedMutationAttempt = observedMutationAttempt || isMutatingTool(event.toolName, event.args);
708
- const toolArgs = extractToolArgsPreview(event.args ?? {});
709
- writeOutputLine(toolArgs ? `${event.toolName}: ${toolArgs}` : event.toolName);
710
- return;
711
- }
712
-
713
- if ((event.type === "message_end" || event.type === "tool_result_end") && event.message) {
714
- messages.push(event.message);
715
- const text = extractTextFromContent(event.message.content);
716
- if (text) writeOutputText(text);
717
-
718
- if (event.type !== "message_end" || event.message.role !== "assistant") return;
719
- if (event.message.model) model = event.message.model;
720
- if (event.message.errorMessage) assistantError = event.message.errorMessage;
721
- const eventUsage = event.message.usage;
722
- if (eventUsage) {
723
- usage.turns++;
724
- usage.input += eventUsage.input ?? eventUsage.inputTokens ?? 0;
725
- usage.output += eventUsage.output ?? eventUsage.outputTokens ?? 0;
726
- usage.cacheRead += eventUsage.cacheRead ?? 0;
727
- usage.cacheWrite += eventUsage.cacheWrite ?? 0;
728
- usage.cost += eventUsage.cost?.total ?? 0;
729
- }
730
- if (isTerminalAssistantStop(event.message)) {
731
- if (!event.message.errorMessage && extractTextFromContent(event.message.content).trim()) assistantError = undefined;
732
- cleanTerminalAssistantStopReceived ||= !event.message.errorMessage;
733
- applyChildLifecycle(projectChildLifecycle(event, true));
734
- }
735
- }
736
- };
737
-
738
- // Guard both cases that can leave the parent waiting on `close` forever:
739
- // a lingering stdio holder after `exit`, or a child that never exits.
740
- const FINAL_STOP_GRACE_MS = 1000;
741
- const HARD_KILL_MS = 3000;
742
- let childExited = false;
743
- let forcedTerminationSignal = false;
744
- let cleanTerminalAssistantStopReceived = false;
745
- let agentSettledReceived = false;
746
- let finalDrainTimer: NodeJS.Timeout | undefined;
747
- let finalHardKillTimer: NodeJS.Timeout | undefined;
748
- let watchdogTailTimer: NodeJS.Timeout | undefined;
749
- let turnBudgetTerminationTimer: NodeJS.Timeout | undefined;
750
- let turnBudgetHardKillTimer: NodeJS.Timeout | undefined;
751
- let protocolHardKillTimer: NodeJS.Timeout | undefined;
752
- let protocolError: ProtocolOutputLimit | undefined;
753
- let settled = false;
754
- applyChildLifecycle = (action: ChildLifecycleAction): void => {
755
- if (action === "cancel-drain") {
756
- if (finalDrainTimer) {
757
- clearTimeout(finalDrainTimer);
758
- finalDrainTimer = undefined;
759
- }
760
- if (finalHardKillTimer) {
761
- clearTimeout(finalHardKillTimer);
762
- finalHardKillTimer = undefined;
763
- }
764
- clearWatchdogTailTimer();
765
- return;
766
- }
767
- if (action === "start-drain") startFinalDrain();
768
- };
769
- const failProtocol = (limit: ProtocolOutputLimit): void => {
770
- if (protocolError) return;
771
- protocolError = limit;
772
- error = formatProtocolOutputLimit(limit);
773
- if (!childExited) {
774
- trySignalChild(child, "SIGTERM");
775
- protocolHardKillTimer = setTimeout(() => {
776
- if (!settled) trySignalChild(child, "SIGKILL");
777
- }, 3000);
778
- protocolHardKillTimer.unref?.();
779
- }
780
- };
781
- const stdoutReader = createBoundedLineReader({
782
- oversizedLineProjector: PI_AGGREGATE_EVENT_PROJECTOR,
783
- onLine: processStdoutLine,
784
- onLimit: failProtocol,
785
- });
786
- const stderrReader = createBoundedLineReader({
787
- stream: "stderr",
788
- maxPendingLineBytes: MAX_CHILD_STDERR_BYTES,
789
- onLine: (line) => appendChildLine("subagent.child.stderr", line),
790
- onLimit: (limit) => appendChildLine("subagent.child.stderr", formatProtocolOutputLimit(limit)),
791
- });
792
- const clearStdioGuard = attachPostExitStdioGuard(child, { idleMs: 2000, hardMs: 8000 });
793
- child.stdout.on("data", (chunk: Buffer) => stdoutReader.push(chunk));
794
- child.stderr.on("data", (chunk: Buffer) => {
795
- stderrTail.push(chunk);
796
- stderrReader.push(chunk);
797
- outputStream.write(chunk);
798
- orcaProgressTab?.append(chunk.toString("utf-8"));
799
- });
800
- registerInterrupt?.(() => {
801
- if (settled || timedOut || stopped) return;
802
- interrupted = true;
803
- if (!error) error = "Interrupted. Waiting for explicit next action.";
804
- trySignalChild(child, "SIGINT");
805
- setTimeout(() => {
806
- if (!settled && !timedOut && !stopped) trySignalChild(child, "SIGTERM");
807
- }, 1000).unref?.();
808
- });
809
- const terminateForTimeout = (message: string): void => {
810
- if (settled || timedOut || stopped) return;
811
- timedOut = true;
812
- // runPiStreaming's terminal result derives the timeout error from this
813
- // message, so retain the tool-specific reason through finalization.
814
- timeoutMessage = message;
815
- interrupted = false;
816
- error = message;
817
- if (processTreeController) void processTreeController.terminate();
818
- else trySignalChild(child, "SIGTERM");
819
- };
820
- let toolTimeoutSequence = 0;
821
- const activeToolTimeouts = new Map<string, { toolName: string; timer: ReturnType<typeof setTimeout> }>();
822
- const activeToolTimeoutKeysByName = new Map<string, string[]>();
823
- const removeToolTimeoutKey = (key: string): void => {
824
- const active = activeToolTimeouts.get(key);
825
- if (!active) return;
826
- clearTimeout(active.timer);
827
- activeToolTimeouts.delete(key);
828
- const keys = activeToolTimeoutKeysByName.get(active.toolName)?.filter((candidate) => candidate !== key) ?? [];
829
- if (keys.length > 0) activeToolTimeoutKeysByName.set(active.toolName, keys);
830
- else activeToolTimeoutKeysByName.delete(active.toolName);
831
- };
832
- const clearActiveToolTimeout = (event: { toolCallId?: unknown; toolName?: unknown }): void => {
833
- const key = typeof event.toolCallId === "string" && event.toolCallId.length > 0
834
- ? `id:${event.toolCallId}`
835
- : typeof event.toolName === "string"
836
- ? activeToolTimeoutKeysByName.get(event.toolName)?.[0]
837
- : activeToolTimeouts.size === 1
838
- ? [...activeToolTimeouts.keys()][0]
839
- : undefined;
840
- if (key) removeToolTimeoutKey(key);
841
- };
842
- const clearAllToolTimeouts = (): void => {
843
- for (const key of [...activeToolTimeouts.keys()]) removeToolTimeoutKey(key);
844
- };
845
- const armToolTimeout = (event: { toolCallId?: unknown; toolName: string }): void => {
846
- const timeoutForTool = effectiveToolTimeoutMs(event.toolName, toolTimeoutMs);
847
- if (timeoutForTool === undefined) return;
848
- const runRemaining = runDeadlineAt === undefined ? undefined : Math.max(0, runDeadlineAt - Date.now());
849
- if (runRemaining !== undefined && timeoutForTool >= runRemaining) return;
850
- const key = toolTimeoutCallKey(event, ++toolTimeoutSequence);
851
- const toolName = event.toolName;
852
- const timer = setTimeout(() => {
853
- removeToolTimeoutKey(key);
854
- terminateForTimeout(formatToolTimeoutMessage(toolName, timeoutForTool));
855
- }, timeoutForTool);
856
- timer.unref?.();
857
- activeToolTimeouts.set(key, { toolName, timer });
858
- const keys = activeToolTimeoutKeysByName.get(toolName) ?? [];
859
- keys.push(key);
860
- activeToolTimeoutKeysByName.set(toolName, keys);
861
- };
862
- registerTimeout?.(() => terminateForTimeout(timeoutMessage ?? "Subagent timed out."));
863
- registerStop?.(() => {
864
- if (settled || timedOut || stopped) return;
865
- stopped = true;
866
- interrupted = false;
867
- error = stopMessage ?? "Subagent stopped by user.";
868
- if (processTreeController) void processTreeController.terminate();
869
- else trySignalChild(child, "SIGTERM");
870
- });
871
- registerTurnBudgetAbort?.((message, state) => {
872
- if (settled || timedOut || stopped || turnBudgetExceeded) return;
873
- turnBudgetExceeded = true;
874
- turnBudgetMessage = message;
875
- turnBudget = state;
876
- interrupted = false;
877
- error = message;
878
- trySignalChild(child, "SIGINT");
879
- turnBudgetTerminationTimer = setTimeout(() => {
880
- if (!settled && !timedOut && !stopped) trySignalChild(child, "SIGTERM");
881
- }, 1000);
882
- turnBudgetTerminationTimer.unref?.();
883
- turnBudgetHardKillTimer = setTimeout(() => {
884
- if (!settled && !timedOut && !stopped) trySignalChild(child, "SIGKILL");
885
- }, 4000);
886
- turnBudgetHardKillTimer.unref?.();
887
- });
888
- const clearDrainTimers = () => {
889
- clearAllToolTimeouts();
890
- if (finalDrainTimer) {
891
- clearTimeout(finalDrainTimer);
892
- finalDrainTimer = undefined;
893
- }
894
- if (finalHardKillTimer) {
895
- clearTimeout(finalHardKillTimer);
896
- finalHardKillTimer = undefined;
897
- }
898
- clearWatchdogTailTimer();
899
- if (turnBudgetTerminationTimer) {
900
- clearTimeout(turnBudgetTerminationTimer);
901
- turnBudgetTerminationTimer = undefined;
902
- }
903
- if (turnBudgetHardKillTimer) {
904
- clearTimeout(turnBudgetHardKillTimer);
905
- turnBudgetHardKillTimer = undefined;
906
- }
907
- if (protocolHardKillTimer) {
908
- clearTimeout(protocolHardKillTimer);
909
- protocolHardKillTimer = undefined;
910
- }
911
- };
912
- function startFinalDrain(): void {
913
- if (childWatchdogIsActive(childWatchdogState)) {
914
- armWatchdogTail();
915
- return;
916
- }
917
- if (childExited || finalDrainTimer || settled) return;
918
- finalDrainTimer = setTimeout(() => {
919
- if (settled) return;
920
- const termSent = trySignalChild(child, "SIGTERM");
921
- if (!termSent) return;
922
- forcedTerminationSignal = true;
923
- if (!cleanTerminalAssistantStopReceived && !agentSettledReceived && !error && !assistantError) {
924
- error = `Subagent process did not exit within ${FINAL_STOP_GRACE_MS}ms after its terminal event. Forcing termination.`;
925
- }
926
- finalHardKillTimer = setTimeout(() => {
927
- if (settled) return;
928
- forcedTerminationSignal = trySignalChild(child, "SIGKILL") || forcedTerminationSignal;
929
- }, HARD_KILL_MS);
930
- finalHardKillTimer.unref?.();
931
- }, FINAL_STOP_GRACE_MS);
932
- finalDrainTimer.unref?.();
933
- }
934
- function clearWatchdogTailTimer(): void {
935
- if (watchdogTailTimer) {
936
- clearTimeout(watchdogTailTimer);
937
- watchdogTailTimer = undefined;
938
- }
939
- }
940
- function armWatchdogTail(): void {
941
- if ((!cleanTerminalAssistantStopReceived && !agentSettledReceived) || watchdogTailTimer || settled) return;
942
- watchdogTailTimer = setTimeout(() => {
943
- watchdogTailTimer = undefined;
944
- updateChildWatchdogState({
945
- phase: "stale",
946
- seq: (childWatchdogState?.seq ?? 0) + 1,
947
- lastUpdate: Date.now(),
948
- followUpPending: false,
949
- reason: "child watchdog tail timeout",
950
- timedOut: true,
951
- });
952
- startFinalDrain();
953
- }, childWatchdogConfig?.watchdogTailTimeoutMs ?? 120_000);
954
- watchdogTailTimer.unref?.();
955
- }
956
- child.on("exit", () => {
957
- childExited = true;
958
- clearDrainTimers();
959
- });
960
- child.on("close", async (exitCode, signal) => {
961
- settled = true;
962
- const processCloseObservedAt = Date.now();
963
- const processTree = processTreeController
964
- ? await processTreeController.finishAfterWriterClose()
965
- : { state: "unknown" as const, reason: "verification-failed" as const, diagnostic: "Writer PID was unavailable." };
966
- try {
967
- onWriterProcess?.({ state: "none" });
968
- } catch {
969
- // The runner still owns and releases the lease during finalization.
970
- }
971
- registerInterrupt?.(undefined);
972
- registerTimeout?.(undefined);
973
- registerStop?.(undefined);
974
- registerTurnBudgetAbort?.(undefined);
975
- clearDrainTimers();
976
- clearStdioGuard();
977
- stdoutReader.end();
978
- stderrReader.end();
979
- outputStream.end();
980
- const stderr = stderrTail.text();
981
- const finalOutput = getFinalOutput(messages) || rawStdoutTail.text().trim();
982
- const finalError = error ?? assistantError;
983
- const forcedDrainAfterFinalSuccess = Boolean(forcedTerminationSignal || signal) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !finalError;
984
- const signalError = isUnexplainedProcessSignal({
985
- processSignal: signal,
986
- interrupted,
987
- timedOut,
988
- stopped,
989
- turnBudgetExceeded,
990
- forcedDrainAfterFinalSuccess,
991
- }) ? formatProcessSignalError(signal!) : undefined;
992
- resolve(omitUndefinedProperties({
993
- stderr,
994
- exitCode: timedOut || stopped ? 1 : turnBudgetExceeded ? 1 : interrupted || forcedDrainAfterFinalSuccess ? 0 : forcedTerminationSignal || signal ? (exitCode ?? 1) : exitCode,
995
- messages,
996
- usage,
997
- toolCount,
998
- durationMs: Date.now() - startedAt,
999
- model,
1000
- error: stopped ? (stopMessage ?? "Subagent stopped by user.") : timedOut ? (timeoutMessage ?? "Subagent timed out.") : turnBudgetExceeded ? turnBudgetMessage : interrupted || forcedDrainAfterFinalSuccess ? undefined : finalError ?? signalError,
1001
- protocolError,
1002
- finalOutput: (timedOut || stopped) && !finalOutput.trim() ? (stopped ? stopMessage ?? "Subagent stopped by user." : timeoutMessage ?? "Subagent timed out.") : finalOutput,
1003
- outputState: finalOutput.trim() ? "present" : "absent",
1004
- interrupted,
1005
- timedOut,
1006
- stopped,
1007
- turnBudget,
1008
- turnBudgetExceeded,
1009
- wrapUpRequested: turnBudget?.outcome === "wrap-up-requested" || turnBudget?.outcome === "termination-deferred" || turnBudgetExceeded || undefined,
1010
- observedMutationAttempt,
1011
- structuredOutputToolInvoked,
1012
- structuredOutputMessageStartIndex,
1013
- watchdog: childWatchdogState,
1014
- processInstanceId,
1015
- processCloseObservedAt,
1016
- processSignal: signal,
1017
- processTree,
1018
- }));
1019
- });
1020
-
1021
- child.on("error", (spawnError) => {
1022
- settled = true;
1023
- try {
1024
- onWriterProcess?.({ state: "none" });
1025
- } catch {
1026
- // The runner still owns and releases the lease during finalization.
1027
- }
1028
- registerInterrupt?.(undefined);
1029
- registerTimeout?.(undefined);
1030
- registerStop?.(undefined);
1031
- registerTurnBudgetAbort?.(undefined);
1032
- clearDrainTimers();
1033
- clearStdioGuard();
1034
- stdoutReader.end();
1035
- stderrReader.end();
1036
- outputStream.end();
1037
- const stderr = stderrTail.text();
1038
- const finalOutput = getFinalOutput(messages) || rawStdoutTail.text().trim();
1039
- const spawnErrorMessage = spawnError instanceof Error ? spawnError.message : String(spawnError);
1040
- 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 } }));
1041
- });
1042
- });
504
+ function formatChildFailureDiagnostic(input: {
505
+ error: string | undefined;
506
+ afterCompactionSettlement?: boolean;
507
+ abortRecoveryDiagnostic?: string;
508
+ requiredOutput?: {
509
+ kind: "file-only" | "structured";
510
+ path: string;
511
+ missing: boolean;
512
+ };
513
+ }): string | undefined {
514
+ const missingOutput = formatRequiredOutputError(input.requiredOutput);
515
+ const notes = [
516
+ input.abortRecoveryDiagnostic,
517
+ input.afterCompactionSettlement ? "Child failure followed session compaction and agent settlement." : undefined,
518
+ missingOutput && input.error !== missingOutput ? missingOutput : undefined,
519
+ ].filter((note): note is string => Boolean(note));
520
+ if (notes.length === 0) return input.error;
521
+ const context = notes.join("\n");
522
+ const errorLimit = MAX_CHILD_FAILURE_DIAGNOSTIC_CHARS - (context ? context.length + 1 : 0);
523
+ const baseError = input.error || "Subagent failed.";
524
+ return `${baseError.slice(0, Math.max(0, errorLimit))}${context ? `\n${context}` : ""}`;
1043
525
  }
1044
526
 
1045
527
  function resolvePiPackageRootFallback(): string {
@@ -1163,16 +645,17 @@ interface SingleStepContext {
1163
645
  flatIndex: number;
1164
646
  flatStepCount: number;
1165
647
  outputFile: string;
1166
- steerInboxDir?: string;
1167
- steerCapabilityPath?: string;
1168
- steerAckDir?: string;
1169
648
  transcriptPath?: string;
1170
649
  piPackageRoot?: string;
1171
- piArgv1?: string;
650
+ /** Factory the runner creates this step's child session through. */
651
+ childSessions: ChildSessionFactory;
652
+ /** The launching executor's own child runtime; nested route, depth, and ceilings come from here. */
653
+ inheritedChildRuntime?: InheritedChildRuntime;
1172
654
  registerInterrupt?: (interrupt: (() => void) | undefined) => void;
1173
655
  registerTimeout?: (interrupt: (() => void) | undefined) => void;
1174
656
  registerStop?: (stop: (() => void) | undefined) => void;
1175
- registerTurnBudgetAbort?: (abort: ((message: string, state?: TurnBudgetState) => void) | undefined) => void;
657
+ /** Receives the live child's steer handler while its session runs. */
658
+ registerSteer?: (steer: StepSteerHandler | undefined) => void;
1176
659
  timeoutSignal?: AbortSignal;
1177
660
  stopSignal?: AbortSignal;
1178
661
  timeoutMessage?: string;
@@ -1181,18 +664,19 @@ interface SingleStepContext {
1181
664
  toolTimeoutMs?: number;
1182
665
  /** Effective step deadline (Date.now() + effective timeout) when a run budget exists. */
1183
666
  deadlineAt?: number;
1184
- turnBudget?: ResolvedTurnBudget;
1185
667
  childIntercomTarget?: string;
1186
668
  orchestratorIntercomTarget?: string;
1187
669
  nestedRoute?: NestedRouteInfo;
1188
670
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
1189
671
  runFanoutBudget?: RunFanoutBudgetDescriptor;
1190
- onAttemptStart?: (attempt: { model?: string; thinking?: string }) => void;
672
+ onAttemptStart?: (attempt: { model?: string; thinking?: string; contextLimit?: number }) => void;
1191
673
  onChildEvent?: (event: ChildEvent) => void;
1192
- onWriterProcess?: (writer: { state: "none" | "spawning" } | { state: "running"; pid: number }) => void;
1193
674
  onExternalProcess?: (process: ExternalProcessStatus) => void;
1194
675
  onExternalJob?: (status: ExternalJobStatus) => void;
1195
676
  skipAcceptance?: () => boolean;
677
+ usageBudgetExhausted?: () => boolean;
678
+ /** False when sibling work in the same Git worktree could have caused the tracked diff. */
679
+ trackedMutationEvidenceForCompletionGuard?: boolean;
1196
680
  orcaProgressTab?: OrcaProgressTab;
1197
681
  }
1198
682
 
@@ -1257,11 +741,15 @@ async function runSingleStepInner(
1257
741
  model: imported.model,
1258
742
  attemptedModels: imported.attemptedModels,
1259
743
  modelAttempts: imported.modelAttempts,
744
+ contextOverflow: imported.contextOverflow,
1260
745
  totalCost: imported.totalCost,
746
+ usage: imported.usage,
1261
747
  structuredOutput: timedOut || stopped ? undefined : imported.structuredOutput,
1262
748
  structuredOutputPath: timedOut || stopped ? undefined : imported.structuredOutputPath,
1263
749
  structuredOutputSchemaPath: timedOut || stopped ? undefined : imported.structuredOutputSchemaPath,
1264
750
  acceptance: timedOut || stopped ? undefined : imported.acceptance,
751
+ execution: timedOut || stopped ? undefined : imported.execution,
752
+ effects: timedOut || stopped ? undefined : imported.effects,
1265
753
  });
1266
754
  } finally {
1267
755
  ctx.registerTimeout?.(undefined);
@@ -1270,14 +758,59 @@ async function runSingleStepInner(
1270
758
  }
1271
759
 
1272
760
  const effectiveStructuredOutput = step.structuredOutput ?? (step.structuredOutputSchema
1273
- ? createStructuredOutputRuntime(step.structuredOutputSchema, path.join(path.dirname(ctx.outputFile), "structured-output"))
761
+ ? createStructuredOutputRuntime(step.structuredOutputSchema, path.join(path.dirname(ctx.outputFile), "structured-output"), { acceptanceReport: resolveAcceptanceReportMode(step.acceptanceInput) })
1274
762
  : undefined);
1275
763
  const placeholderRegex = new RegExp(ctx.placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
1276
764
  let task = step.task.replace(placeholderRegex, () => ctx.previousOutput);
1277
765
  if (ctx.outputs) task = resolveOutputReferences(task, ctx.outputs);
1278
766
  const taskForCompletionGuard = task;
767
+ let resolvedTaskToolPlan: ReturnType<typeof resolvePiLaunchToolPlan> | undefined;
768
+ if (!step.runner) {
769
+ resolvedTaskToolPlan = resolvePiLaunchToolPlan(omitUndefinedProperties({
770
+ tools: step.tools,
771
+ excludeTools: step.excludeTools,
772
+ allowNestedSubagents: step.allowNestedSubagents,
773
+ extensions: step.extensions,
774
+ subagentOnlyExtensions: step.subagentOnlyExtensions,
775
+ fast: step.fast,
776
+ model: step.model,
777
+ modelCandidates: step.modelCandidates,
778
+ mcpDirectTools: step.mcpDirectTools,
779
+ cwd: step.cwd ?? ctx.cwd,
780
+ requireReadTool: Boolean(step.skills?.length),
781
+ structuredOutput: Boolean(effectiveStructuredOutput),
782
+ capabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,
783
+ inheritedCapabilityCeiling: ctx.inheritedChildRuntime?.capabilityCeiling,
784
+ permissionRules: step.permissionRules,
785
+ }));
786
+ const contractTools = resolvedTaskToolPlan.explicitToolAllowlist ? resolvedTaskToolPlan.effectiveToolAllowlist : undefined;
787
+ const contractError = validateImplementationToolContract({
788
+ agent: step.agent,
789
+ task: taskForCompletionGuard,
790
+ tools: contractTools,
791
+ mcpDirectTools: resolvedTaskToolPlan.effectiveMcpTools,
792
+ configuredExtensions: resolvedTaskToolPlan.configuredExtensions,
793
+ requestedTools: resolvedTaskToolPlan.requestedBuiltinTools,
794
+ acceptanceRole: step.acceptanceRole,
795
+ completionGuard: step.completionGuard,
796
+ });
797
+ if (contractError) {
798
+ return omitUndefinedProperties({
799
+ agent: step.agent,
800
+ context: step.context,
801
+ output: contractError,
802
+ error: contractError,
803
+ exitCode: 1,
804
+ capabilityCeiling: resolvedTaskToolPlan.capabilityCeiling,
805
+ capabilityAudit: resolvedTaskToolPlan.capabilityAudit,
806
+ });
807
+ }
808
+ }
809
+ // Derive from the pre-acceptance task so internal acceptance/recovery
810
+ // instructions never leak into the display name.
811
+ const childSessionName = step.sessionName ?? deriveChildSessionName({ agent: step.agent, task, label: step.label });
1279
812
  if (step.effectiveAcceptance) {
1280
- const acceptancePrompt = formatAcceptancePrompt(step.effectiveAcceptance, { reportOptional: isAgentContractV1(step.agentContract) });
813
+ const acceptancePrompt = formatAcceptancePrompt(step.effectiveAcceptance, { reportOptional: isAgentContractV1(step.agentContract), structuredOutput: Boolean(step.structuredOutput?.acceptanceReportPath) });
1281
814
  if (acceptancePrompt) task = `${task}\n${acceptancePrompt}`;
1282
815
  }
1283
816
  const sessionEnabled = Boolean(step.sessionFile) || ctx.sessionEnabled;
@@ -1306,21 +839,29 @@ async function runSingleStepInner(
1306
839
  transcriptWriter?.writeInitialUserMessage(`${PROMPT_REDACTED}; live Prompt Audit only.`);
1307
840
 
1308
841
  if (step.runner?.type === "external-cli") {
1309
- const runner: ExternalCliRunnerStatus = {
1310
- type: "external-cli",
1311
- command: step.runner.command,
1312
- args: step.runner.args ?? [],
1313
- promptDelivery: step.runner.promptDelivery ?? "stdin",
1314
- capabilities: { stop: true, steer: false, resume: false, structuredOutput: false, toolEvents: false },
1315
- };
842
+ const externalCwd = step.cwd ?? ctx.cwd;
843
+ const adapterLaunch = step.runner.adapter === "codex-exec" || step.runner.adapter === "codex-exec-writer"
844
+ ? resolveCodexExecLaunch({ adapter: step.runner.adapter, command: step.runner.command, asyncDir: path.dirname(ctx.outputFile), stepIndex: ctx.flatIndex })
845
+ : step.runner.adapter === "claude-code" || step.runner.adapter === "claude-code-writer"
846
+ ? resolveClaudeCodeLaunch({ adapter: step.runner.adapter, command: step.runner.command })
847
+ : step.runner.adapter === "cursor-agent" || step.runner.adapter === "cursor-agent-writer"
848
+ ? resolveCursorAgentLaunch({ adapter: step.runner.adapter, command: step.runner.command, cwd: externalCwd, asyncDir: path.dirname(ctx.outputFile), stepIndex: ctx.flatIndex })
849
+ : undefined;
850
+ const runner = resolveExternalCliRunnerStatus({ ...step.runner, ...(adapterLaunch ? { args: adapterLaunch.args } : {}) });
1316
851
  const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
1317
852
  const external = await runExternalCli(omitUndefinedProperties({
1318
- command: runner.command,
1319
- args: runner.args,
1320
- cwd: step.cwd ?? ctx.cwd,
853
+ command: adapterLaunch?.command ?? runner.command,
854
+ args: adapterLaunch?.args ?? runner.args,
855
+ cwd: externalCwd,
1321
856
  prompt: buildExternalCliPrompt(step.systemPrompt ?? "", task),
1322
857
  asyncDir: path.dirname(ctx.outputFile),
1323
858
  stepIndex: ctx.flatIndex,
859
+ environment: adapterLaunch?.environment,
860
+ preflight: adapterLaunch?.preflight,
861
+ parser: adapterLaunch?.parser,
862
+ finalOutputPath: adapterLaunch?.finalOutputPath,
863
+ promptFilePath: adapterLaunch?.promptFilePath,
864
+ temporaryDirectories: adapterLaunch?.temporaryDirectories,
1324
865
  registerTimeout: ctx.registerTimeout,
1325
866
  registerStop: ctx.registerStop,
1326
867
  timeoutMessage: ctx.timeoutMessage,
@@ -1331,14 +872,18 @@ async function runSingleStepInner(
1331
872
  }));
1332
873
  try { fs.writeFileSync(ctx.outputFile, external.output, "utf-8"); } catch { /* Observability output is best-effort. */ }
1333
874
  const resolvedOutput = step.outputPath && external.exitCode === 0
1334
- ? resolveSingleOutput(step.outputPath, external.output, outputSnapshot)
875
+ ? resolveSingleOutput(step.outputPath, external.output, outputSnapshot, step.outputClaimPath)
1335
876
  : { fullOutput: external.output };
1336
877
  const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, resolvedOutput.fullOutput) : undefined;
878
+ const exitCode = resolvedOutput.fatalError ? 1 : external.exitCode;
879
+ const error = resolvedOutput.fatalError && resolvedOutput.saveError
880
+ ? external.error ? `${external.error}\n${resolvedOutput.saveError}` : resolvedOutput.saveError
881
+ : external.error;
1337
882
  const finalizedOutput = finalizeSingleOutput(omitUndefinedProperties({
1338
883
  fullOutput: resolvedOutput.fullOutput,
1339
884
  outputPath: step.outputPath,
1340
885
  outputMode: step.outputMode,
1341
- exitCode: external.exitCode ?? 1,
886
+ exitCode: exitCode ?? 1,
1342
887
  savedPath: resolvedOutput.savedPath,
1343
888
  outputReference,
1344
889
  saveError: resolvedOutput.saveError,
@@ -1353,16 +898,17 @@ async function runSingleStepInner(
1353
898
  : {};
1354
899
  return omitUndefinedProperties({
1355
900
  agent: step.agent,
901
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
1356
902
  context: step.context,
1357
903
  output: finalizedOutput.displayOutput,
1358
904
  outputState: external.output.trim() ? "present" : "absent",
1359
- exitCode: external.exitCode,
1360
- error: external.error,
905
+ exitCode,
906
+ error,
1361
907
  timedOut: external.timedOut,
1362
908
  stopped: external.stopped,
1363
909
  processSignal: external.processSignal,
1364
910
  artifactPaths,
1365
- outputSaveError: artifactErrors.outputSaveError,
911
+ outputSaveError: [resolvedOutput.saveError, artifactErrors.outputSaveError].filter(Boolean).join("\n") || undefined,
1366
912
  metadataSaveError: artifactErrors.metadataSaveError,
1367
913
  runner,
1368
914
  externalProcess: external.externalProcess,
@@ -1392,17 +938,22 @@ async function runSingleStepInner(
1392
938
  timeoutMessage: ctx.timeoutMessage,
1393
939
  stopMessage: ctx.stopMessage,
1394
940
  onExternalJob: ctx.onExternalJob,
941
+ followUp: step.externalJobFollowUp,
1395
942
  }));
1396
943
  try { fs.writeFileSync(ctx.outputFile, external.output, "utf-8"); } catch { /* Observability output is best-effort. */ }
1397
944
  const resolvedOutput = step.outputPath && external.exitCode === 0
1398
- ? resolveSingleOutput(step.outputPath, external.output, outputSnapshot)
945
+ ? resolveSingleOutput(step.outputPath, external.output, outputSnapshot, step.outputClaimPath)
1399
946
  : { fullOutput: external.output };
1400
947
  const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, resolvedOutput.fullOutput) : undefined;
948
+ const exitCode = resolvedOutput.fatalError ? 1 : external.exitCode;
949
+ const error = resolvedOutput.fatalError && resolvedOutput.saveError
950
+ ? external.error ? `${external.error}\n${resolvedOutput.saveError}` : resolvedOutput.saveError
951
+ : external.error;
1401
952
  const finalizedOutput = finalizeSingleOutput(omitUndefinedProperties({
1402
953
  fullOutput: resolvedOutput.fullOutput,
1403
954
  outputPath: step.outputPath,
1404
955
  outputMode: step.outputMode,
1405
- exitCode: external.exitCode,
956
+ exitCode: exitCode ?? 1,
1406
957
  savedPath: resolvedOutput.savedPath,
1407
958
  outputReference,
1408
959
  saveError: resolvedOutput.saveError,
@@ -1417,21 +968,29 @@ async function runSingleStepInner(
1417
968
  : {};
1418
969
  return omitUndefinedProperties({
1419
970
  agent: step.agent,
971
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
1420
972
  context: step.context,
1421
973
  output: finalizedOutput.displayOutput,
1422
974
  outputState: external.output.trim() ? "present" : "absent",
1423
- exitCode: external.exitCode,
1424
- error: external.error,
975
+ exitCode,
976
+ error,
1425
977
  timedOut: external.timedOut,
1426
978
  stopped: external.stopped,
1427
979
  artifactPaths,
1428
- outputSaveError: artifactErrors.outputSaveError,
980
+ outputSaveError: [resolvedOutput.saveError, artifactErrors.outputSaveError].filter(Boolean).join("\n") || undefined,
1429
981
  metadataSaveError: artifactErrors.metadataSaveError,
1430
982
  runner,
1431
983
  externalJob: external.externalJob,
1432
984
  });
1433
985
  }
1434
986
 
987
+ const effectiveCwd = step.cwd ?? ctx.cwd;
988
+ const cwdError = preflightLaunchCwd(step.requestedCwd ?? effectiveCwd, effectiveCwd);
989
+ if (cwdError) return { agent: step.agent, output: cwdError, error: cwdError, exitCode: 1, context: step.context };
990
+ if (step.context === "fork" && step.sessionFile && fs.existsSync(step.sessionFile)) {
991
+ alignForkedSessionCwd(step.sessionFile, effectiveCwd);
992
+ }
993
+
1435
994
  const candidates = step.modelCandidates !== undefined
1436
995
  ? step.modelCandidates.length > 0 ? step.modelCandidates : [undefined]
1437
996
  : step.model
@@ -1441,36 +1000,51 @@ async function runSingleStepInner(
1441
1000
  let capabilityAudit: import("../shared/capability-ceiling.ts").SubagentCapabilityAudit | undefined;
1442
1001
  let launchResolvedExtensions = step.launchResolvedExtensions;
1443
1002
  const modelAttempts: ModelAttempt[] = [];
1444
- const writerProcesses: PiWriterProcessInstanceExitV1[] = [];
1445
- let writerAttemptCount = 0;
1446
1003
  const attemptNotes: string[] = [];
1004
+ let finalRequiredOutputMissing: boolean | undefined;
1447
1005
  const eventsPath = path.join(path.dirname(ctx.outputFile), "events.jsonl");
1448
- let finalResult: RunPiStreamingResult | undefined;
1006
+ let finalResult: RunChildSessionResult | undefined;
1449
1007
  let finalOutputSnapshot: SingleOutputSnapshot | undefined;
1008
+ let structuredAcceptanceReport: unknown;
1009
+ let structuredAcceptanceReportError: string | undefined;
1450
1010
  let completionGuardTriggeredFinal = false;
1451
- let turnBudget = ctx.turnBudget ? initialTurnBudgetState(ctx.turnBudget) : undefined;
1452
1011
  let toolBudget = step.toolBudget ? initialToolBudgetState(step.toolBudget) : undefined;
1453
1012
  let toolBudgetBlocked = false;
1454
1013
  let actualLaunchContractDigest = step.launchContractDigest;
1014
+ const mutationSnapshot = snapshotTrackedMutations(step.cwd ?? ctx.cwd);
1015
+ let finalMutationEvidence = collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
1455
1016
 
1456
1017
  let modelIndex = 0;
1457
- let startupAttemptIndex = 0;
1458
- // Escalated to "file" after an unexplained zero-activity startup failure so
1459
- // retries keep the task text out of argv (endpoint pre-exec scans may deny it).
1460
- let taskDeliveryOverride: SubagentTaskDelivery | undefined;
1018
+ let contextOverflow = false;
1019
+ let launchWarningsEmitted = false;
1020
+ let abortRecoveryAttempted = false;
1021
+ let nextAttemptTask = task;
1461
1022
  modelAttemptsLoop: while (modelIndex < candidates.length) {
1462
1023
  if (ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break;
1024
+ const recoveringAbort = abortRecoveryAttempted;
1025
+ const attemptTask = nextAttemptTask;
1463
1026
  const candidate = candidates[modelIndex];
1464
- ctx.onAttemptStart?.(omitUndefinedProperties({ model: candidate, thinking: resolveEffectiveThinking(candidate, step.thinking) }));
1027
+ const expectedModelForVerification = candidate && !(step.skipPrimaryModelVerification && modelIndex === 0) ? candidate : undefined;
1028
+ try {
1029
+ assertThinkingWithinCeiling({ model: candidate, configThinking: step.thinking, ceiling: step.thinkingCeiling, agent: step.agent, runId: ctx.id });
1030
+ } catch (error) {
1031
+ const message = error instanceof Error ? error.message : String(error);
1032
+ return omitUndefinedProperties({ agent: step.agent, output: message, error: message, exitCode: 1, context: step.context, thinkingCeiling: step.thinkingCeiling });
1033
+ }
1034
+ ctx.onAttemptStart?.(omitUndefinedProperties({
1035
+ model: candidate,
1036
+ thinking: resolveEffectiveThinking(candidate, step.thinking),
1037
+ contextLimit: findModelInfo(candidate, step.modelVerificationRegistry)?.contextWindow,
1038
+ }));
1465
1039
  const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
1466
1040
  if (effectiveStructuredOutput) {
1467
- try {
1468
- if (fs.existsSync(effectiveStructuredOutput.outputPath)) fs.unlinkSync(effectiveStructuredOutput.outputPath);
1469
- } catch {
1470
- // Missing/stale structured-output files are handled after the child exits.
1041
+ const cleanupError = clearStructuredOutputCaptures(effectiveStructuredOutput);
1042
+ if (cleanupError) {
1043
+ return omitUndefinedProperties({ agent: step.agent, output: cleanupError, error: cleanupError, exitCode: 1, context: step.context });
1471
1044
  }
1472
1045
  }
1473
1046
  const watchdogConfig = resolveWatchdogConfig(step.cwd ?? ctx.cwd);
1047
+ const extensionBindings = normalizeExtensionBindings(step.extensionBindings)?.value;
1474
1048
  const childWatchdog = watchdogConfig.ok
1475
1049
  ? resolveChildWatchdogConfig({
1476
1050
  config: watchdogConfig.config,
@@ -1479,43 +1053,42 @@ async function runSingleStepInner(
1479
1053
  childIndex: ctx.flatIndex,
1480
1054
  })
1481
1055
  : undefined;
1482
- const { args, env, tempDir, toolDiagnosticPath, runtimeAcknowledgedExtensionsPath, capabilityAudit: attemptCapabilityAudit } = buildPiArgs(omitUndefinedProperties({
1056
+ let watchdogSink: ((event: ChildWatchdogStatusEvent) => void) | undefined;
1057
+ const launch = buildInProcessChildLaunch(omitUndefinedProperties({
1483
1058
  parentSessionId: step.parentSessionId,
1484
- baseArgs: ["--mode", "json", "-p"],
1485
- task,
1486
- taskDelivery: taskDeliveryOverride,
1059
+ forkCacheKey: step.context === "fork" ? deriveForkPromptCacheKey(step.parentSessionId) : undefined,
1487
1060
  sessionEnabled,
1488
1061
  sessionDir,
1489
1062
  sessionFile: step.sessionFile,
1490
1063
  model: candidate,
1491
1064
  inheritProjectContext: step.inheritProjectContext,
1065
+ inheritGlobalContext: step.inheritGlobalContext,
1492
1066
  inheritSkills: step.inheritSkills,
1493
1067
  requireReadTool: Boolean(step.skills?.length),
1494
1068
  tools: step.tools,
1069
+ excludeTools: step.excludeTools,
1070
+ allowNestedSubagents: step.allowNestedSubagents,
1495
1071
  extensions: step.extensions,
1496
1072
  subagentOnlyExtensions: step.subagentOnlyExtensions,
1497
- systemPrompt: appendTurnBudgetSystemPrompt(step.systemPrompt ?? "", ctx.turnBudget),
1073
+ fast: step.fast,
1074
+ modelCandidates: step.modelCandidates,
1075
+ systemPrompt: step.systemPrompt ?? "",
1498
1076
  systemPromptMode: step.systemPromptMode,
1499
1077
  mcpDirectTools: step.mcpDirectTools,
1078
+ extensionBindings,
1500
1079
  capabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,
1501
1080
  cwd: step.cwd ?? ctx.cwd,
1502
- promptFileStem: step.agent,
1503
1081
  intercomSessionName: ctx.childIntercomTarget,
1082
+ sessionName: childSessionName,
1504
1083
  orchestratorIntercomTarget: ctx.orchestratorIntercomTarget,
1505
1084
  runId: ctx.id,
1506
1085
  childAgentName: step.agent,
1507
1086
  childIndex: ctx.flatIndex,
1508
- parentEventSink: ctx.nestedRoute?.eventSink,
1509
- parentControlInbox: ctx.nestedRoute?.controlInbox,
1510
- parentRootRunId: ctx.nestedRoute?.rootRunId,
1511
- parentCapabilityToken: ctx.nestedRoute?.capabilityToken,
1087
+ nestedRoute: ctx.nestedRoute,
1512
1088
  runFanoutBudget: ctx.runFanoutBudget ? {
1513
1089
  ...ctx.runFanoutBudget,
1514
1090
  ...(step.runFanoutPath ? { parentPath: `${ctx.runFanoutBudget.parentPath ? `${ctx.runFanoutBudget.parentPath}/` : ""}${step.runFanoutPath}` } : {}),
1515
1091
  } : undefined,
1516
- steerInboxDir: ctx.steerInboxDir,
1517
- steerCapabilityPath: ctx.steerCapabilityPath,
1518
- steerAckDir: ctx.steerAckDir,
1519
1092
  structuredOutput: effectiveStructuredOutput,
1520
1093
  toolBudget: step.toolBudget,
1521
1094
  permissionRules: step.permissionRules,
@@ -1523,19 +1096,40 @@ async function runSingleStepInner(
1523
1096
  ? path.join(ctx.artifactsDir, "permission-audit", `${ctx.id}-${ctx.flatIndex}.jsonl`)
1524
1097
  : undefined,
1525
1098
  childWatchdog,
1099
+ watchdogStatus: (event) => watchdogSink?.(event),
1526
1100
  waitToolEnabled: step.waitToolEnabled,
1101
+ waitToolDefaultTimeoutMs: step.waitToolDefaultTimeoutMs,
1102
+ thinkingCeiling: step.thinkingCeiling,
1103
+ maxSubagentDepth: step.maxSubagentDepth,
1104
+ inherited: ctx.inheritedChildRuntime,
1105
+ host: "runner",
1527
1106
  }));
1107
+ if (effectiveStructuredOutput && launch.config.structuredOutput) {
1108
+ // The runner reads the value back from the runtime's files after the run.
1109
+ launch.config.structuredOutput.capture = createStructuredOutputFileCapture(effectiveStructuredOutput);
1110
+ }
1111
+ const { warnings, capabilityAudit: attemptCapabilityAudit } = launch;
1112
+ if (!launchWarningsEmitted && warnings.length > 0) {
1113
+ for (const warning of warnings) console.warn(`[pi-subagents] ${warning}`);
1114
+ launchWarningsEmitted = true;
1115
+ }
1528
1116
  if (step.definitionDigest) {
1529
- const toolPlan = resolvePiLaunchToolPlan(omitUndefinedProperties({
1117
+ const toolPlan = resolvedTaskToolPlan ?? resolvePiLaunchToolPlan(omitUndefinedProperties({
1530
1118
  tools: step.tools,
1119
+ excludeTools: step.excludeTools,
1120
+ allowNestedSubagents: step.allowNestedSubagents,
1531
1121
  extensions: step.extensions,
1532
1122
  subagentOnlyExtensions: step.subagentOnlyExtensions,
1123
+ fast: step.fast,
1124
+ model: step.model,
1125
+ modelCandidates: step.modelCandidates,
1533
1126
  mcpDirectTools: step.mcpDirectTools,
1534
1127
  cwd: step.cwd ?? ctx.cwd,
1535
1128
  requireReadTool: Boolean(step.skills?.length),
1536
1129
  structuredOutput: Boolean(effectiveStructuredOutput),
1537
1130
  capabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,
1538
- inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
1131
+ inheritedCapabilityCeiling: ctx.inheritedChildRuntime?.capabilityCeiling,
1132
+ permissionRules: step.permissionRules,
1539
1133
  }));
1540
1134
  launchResolvedExtensions = projectLaunchResolvedChildExtensions(toolPlan);
1541
1135
  actualLaunchContractDigest = launchBindingDigest(omitUndefinedProperties({
@@ -1543,84 +1137,75 @@ async function runSingleStepInner(
1543
1137
  task: step.launchBindingTask ?? task,
1544
1138
  ...(candidate ? { model: candidate } : {}),
1545
1139
  modelCandidates: candidates as string[],
1140
+ ...(step.fast !== undefined ? { fast: step.fast } : {}),
1546
1141
  ...(resolveEffectiveThinking(candidate, step.thinking) ? { thinking: resolveEffectiveThinking(candidate, step.thinking) } : {}),
1547
- systemPrompt: appendTurnBudgetSystemPrompt(step.systemPrompt ?? "", ctx.turnBudget),
1142
+ ...(step.thinkingCeiling ? { thinkingCeiling: step.thinkingCeiling } : {}),
1143
+ systemPrompt: step.systemPrompt ?? "",
1548
1144
  systemPromptMode: step.systemPromptMode,
1549
1145
  inheritProjectContext: step.inheritProjectContext,
1146
+ inheritGlobalContext: step.inheritGlobalContext,
1550
1147
  inheritSkills: step.inheritSkills,
1551
1148
  skills: step.skills,
1552
1149
  tools: toolPlan.effectiveToolAllowlist,
1150
+ ...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
1553
1151
  extensions: toolPlan.extensionArgs,
1554
1152
  mcpDirectTools: toolPlan.effectiveMcpTools,
1555
1153
  ...(step.outputPath ? { outputPath: step.outputPath } : {}),
1556
1154
  ...(step.outputMode ? { outputMode: step.outputMode } : {}),
1557
1155
  ...(step.structuredOutputSchema ? { structuredOutputSchema: step.structuredOutputSchema } : {}),
1156
+ ...(extensionBindings ? { extensionBindings } : {}),
1558
1157
  }));
1559
1158
  }
1560
1159
  capabilityAudit = attemptCapabilityAudit;
1561
- writerAttemptCount += 1;
1562
- const run = await runPiStreaming(
1563
- args,
1564
- step.cwd ?? ctx.cwd,
1565
- ctx.outputFile,
1566
- env,
1567
- ctx.piPackageRoot,
1568
- ctx.piArgv1,
1569
- step.maxSubagentDepth,
1570
- { eventsPath, runId: ctx.id, stepIndex: ctx.flatIndex, agent: step.agent },
1571
- ctx.registerInterrupt,
1572
- ctx.onChildEvent,
1160
+ // Each attempt rewrites the step output log; synchronous appends keep a
1161
+ // retried attempt from interleaving with the previous attempt's flush.
1162
+ fs.writeFileSync(ctx.outputFile, "", "utf-8");
1163
+ const run = await runChildSession(omitUndefinedProperties({
1164
+ factory: ctx.childSessions,
1165
+ launch,
1166
+ prompt: `Task: ${attemptTask}`,
1167
+ childWatchdog,
1168
+ childEventContext: { runId: ctx.id, stepIndex: ctx.flatIndex, agent: step.agent },
1169
+ appendChildEvent: (event) => appendDiagnosticJsonl(eventsPath, JSON.stringify(event), typeof event.type === "string" ? event.type : undefined),
1170
+ writeOutputLine: (line) => {
1171
+ try {
1172
+ fs.appendFileSync(ctx.outputFile, `${line}\n`, "utf-8");
1173
+ } catch {
1174
+ // The output log is observability only.
1175
+ }
1176
+ ctx.orcaProgressTab?.append(`${line}\n`);
1177
+ },
1178
+ registerInterrupt: ctx.registerInterrupt,
1179
+ registerTimeout: ctx.registerTimeout,
1180
+ registerStop: ctx.registerStop,
1181
+ registerSteer: ctx.registerSteer,
1182
+ registerWatchdogStatus: (sink) => { watchdogSink = sink; },
1183
+ timeoutMessage: ctx.timeoutMessage,
1184
+ stopMessage: ctx.stopMessage,
1185
+ onChildEvent: ctx.onChildEvent,
1573
1186
  transcriptWriter,
1574
- ctx.registerTimeout,
1575
- ctx.timeoutMessage,
1576
- ctx.registerStop,
1577
- ctx.stopMessage,
1578
- ctx.registerTurnBudgetAbort,
1579
- ctx.onWriterProcess,
1580
- ctx.toolTimeoutMs,
1581
- ctx.deadlineAt,
1582
- ctx.orcaProgressTab,
1583
- );
1584
- if (run.processCloseObservedAt !== undefined) {
1585
- writerProcesses.push({
1586
- processInstanceId: run.processInstanceId,
1587
- kind: "pi-writer",
1588
- attempt: writerAttemptCount - 1,
1589
- closeObservedAt: run.processCloseObservedAt,
1590
- exitCode: run.exitCode,
1591
- signal: run.processSignal ?? null,
1592
- processTree: run.processTree,
1593
- });
1594
- }
1595
- if (run.turnBudget) turnBudget = run.turnBudget;
1596
- else if (ctx.turnBudget) {
1597
- const assistantMessages = run.messages.filter((message) => message.role === "assistant");
1598
- const turnCount = assistantMessages.length;
1599
- const lastAssistantMessage = assistantMessages.at(-1);
1600
- if (turnCount > 0 && turnCount < ctx.turnBudget.maxTurns) {
1601
- turnBudget = { ...ctx.turnBudget, outcome: "within-budget", turnCount };
1602
- } else if (turnCount >= ctx.turnBudget.maxTurns) {
1603
- const decision = turnBudgetDecision(
1604
- ctx.turnBudget,
1605
- turnCount,
1606
- lastAssistantMessage ? isTerminalAssistantStop(lastAssistantMessage) : false,
1607
- lastAssistantMessage ? assistantStartsToolCall(lastAssistantMessage) : false,
1608
- );
1609
- turnBudget = decision === "defer"
1610
- ? turnBudgetDeferredState(ctx.turnBudget, turnCount)
1611
- : turnBudgetState(ctx.turnBudget, turnCount, decision === "abort");
1612
- }
1613
- }
1614
- const toolAvailabilityError = run.exitCode === 0 && !run.error
1615
- ? readChildToolDiagnosticError(toolDiagnosticPath)
1187
+ toolTimeoutMs: ctx.toolTimeoutMs,
1188
+ runDeadlineAt: ctx.deadlineAt,
1189
+ expectedModelForVerification,
1190
+ modelVerificationRegistry: step.modelVerificationRegistry,
1191
+ mutationTools: step.mutationTools,
1192
+ }));
1193
+ const toolDiagnostic = run.exitCode === 0 && !run.error ? launch.capture.toolDiagnostic() : undefined;
1194
+ const toolAvailabilityError = toolDiagnostic ? formatChildToolDiagnostic(toolDiagnostic) : undefined;
1195
+ const runtimeAcknowledgedExtensions = launch.capture.runtimeAcknowledgedExtensions();
1196
+ const midToolExitError = run.currentTool
1197
+ && isOrdinaryToolForMidToolExit(run.currentTool)
1198
+ && !run.interrupted
1199
+ && !run.timedOut
1200
+ && !run.stopped
1201
+ && !toolAvailabilityError
1202
+ ? formatMidToolExitError({ toolName: run.currentTool })
1616
1203
  : undefined;
1617
- const runtimeAcknowledgedExtensions = readRuntimeAcknowledgedExtensions(runtimeAcknowledgedExtensionsPath);
1618
- cleanupTempDir(tempDir);
1619
1204
 
1620
1205
  let structuredOutput: unknown;
1621
1206
  let structuredError: string | undefined;
1622
1207
  let validatedStructuredOutput = false;
1623
- if (effectiveStructuredOutput && run.exitCode === 0 && !run.error && !toolAvailabilityError) {
1208
+ if (effectiveStructuredOutput && run.exitCode === 0 && !run.error && !toolAvailabilityError && !midToolExitError) {
1624
1209
  if (!run.structuredOutputToolInvoked) {
1625
1210
  structuredError = MISSING_STRUCTURED_OUTPUT_CALL_ERROR;
1626
1211
  } else {
@@ -1632,6 +1217,9 @@ async function runSingleStepInner(
1632
1217
  if (structured.error) structuredError = structured.error;
1633
1218
  else {
1634
1219
  structuredOutput = structured.value;
1220
+ const acceptanceReport = readStructuredOutputAcceptanceReport(effectiveStructuredOutput);
1221
+ structuredAcceptanceReport = acceptanceReport.value;
1222
+ structuredAcceptanceReportError = acceptanceReport.error;
1635
1223
  validatedStructuredOutput = true;
1636
1224
  }
1637
1225
  }
@@ -1639,69 +1227,77 @@ async function runSingleStepInner(
1639
1227
  const errorMessages = validatedStructuredOutput
1640
1228
  ? run.messages.slice(run.structuredOutputMessageStartIndex ?? run.messages.length)
1641
1229
  : run.messages;
1642
- const hiddenError = run.exitCode === 0 && !run.error && !toolAvailabilityError && !structuredError
1230
+ const hiddenError = run.exitCode === 0 && !run.error && !toolAvailabilityError && !structuredError && !midToolExitError
1643
1231
  ? detectSubagentError(errorMessages)
1644
1232
  : null;
1233
+ const terminalEmptyAfterUsefulWork = !validatedStructuredOutput
1234
+ && hasEmptyTerminalAssistantResponse(run.messages)
1235
+ && (run.toolCount > 0 || Boolean(run.finalOutput.trim()));
1645
1236
  const emptyOutputError = run.exitCode === 0
1646
1237
  && !run.error
1647
1238
  && !toolAvailabilityError
1648
1239
  && !structuredError
1649
- && !run.finalOutput.trim()
1650
1240
  && !validatedStructuredOutput
1241
+ && (!run.finalOutput.trim() || terminalEmptyAfterUsefulWork)
1651
1242
  && (!hiddenError?.hasError || hasEmptyTerminalAssistantResponse(run.messages))
1652
- ? "Subagent produced no output (possible model cold-start or empty response)."
1243
+ ? formatEmptyTerminalAssistantResponseError(run.messages)
1653
1244
  : undefined;
1654
1245
  const completionGuardEnabled = isAgentContractV1(step.agentContract) ? step.completionGuard === true : step.completionGuard !== false;
1655
- const completionGuard = run.exitCode === 0 && !run.error && !toolAvailabilityError && !structuredError && !hiddenError?.hasError && !emptyOutputError && completionGuardEnabled
1246
+ const completionToolPlan = resolvedTaskToolPlan;
1247
+ const completionTools = completionToolPlan ? (completionToolPlan.explicitToolAllowlist ? completionToolPlan.effectiveToolAllowlist : undefined) : step.tools;
1248
+ const mutationEvidence = collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
1249
+ finalMutationEvidence = mutationEvidence;
1250
+ const completionMutationEvidence = ctx.trackedMutationEvidenceForCompletionGuard === false ? undefined : mutationEvidence;
1251
+ const completionGuard = run.exitCode === 0 && !run.error && !structuredError && !hiddenError?.hasError && !midToolExitError && !emptyOutputError && completionGuardEnabled
1656
1252
  ? evaluateCompletionMutationGuard(omitUndefinedProperties({
1657
1253
  agent: step.agent,
1658
1254
  task: taskForCompletionGuard,
1659
1255
  messages: run.messages,
1660
- tools: step.tools,
1661
- mcpDirectTools: step.mcpDirectTools,
1256
+ tools: completionTools,
1257
+ mcpDirectTools: completionToolPlan?.effectiveMcpTools ?? step.mcpDirectTools,
1258
+ mutationTools: step.mutationTools,
1259
+ toolAvailabilityError,
1260
+ mutationEvidence: completionMutationEvidence,
1662
1261
  }))
1663
1262
  : undefined;
1664
- const completionGuardTriggered = completionGuard?.triggered === true && !run.observedMutationAttempt;
1665
- const fileMutationEffect = completionGuard
1666
- ? {
1667
- status: completionGuard.expectedMutation ? completionGuardTriggered ? "missing" as const : "observed" as const : "not-applicable" as const,
1668
- expected: completionGuard.expectedMutation,
1669
- attempted: completionGuard.attemptedMutation || run.observedMutationAttempt === true,
1670
- ...(completionGuardTriggered ? { message: "Subagent completed without making edits for an implementation task." } : {}),
1671
- }
1672
- : undefined;
1673
- const completionGuardError = completionGuardTriggered && !isAgentContractV1(step.agentContract)
1674
- ? "Subagent completed without making edits for an implementation task.\nIt appears to have returned planning or scratchpad output instead of applying changes."
1263
+ const mutationAttemptObserved = run.observedMutationAttempt === true || completionMutationEvidence?.attemptedMutation === true;
1264
+ const completionEvidence = planCompletionEvidence({
1265
+ guard: completionGuard,
1266
+ completionGuardEnabled,
1267
+ mutationCapable: hasMutationToolCapability(completionTools, completionToolPlan?.effectiveMcpTools ?? step.mcpDirectTools),
1268
+ implementationMutationExpected: expectsImplementationMutation(step.agent, taskForCompletionGuard),
1269
+ mutationAttemptObserved,
1270
+ mutationEvidence: completionMutationEvidence,
1271
+ agentContractV1: isAgentContractV1(step.agentContract),
1272
+ });
1273
+ const finalOutputHasPersistableFileContent = run.exitCode === 0 && !run.error && !emptyOutputError && Boolean(stripAcceptanceReport(run.finalOutput).trim());
1274
+ const requiredOutput = step.outputMode === "file-only" && step.outputPath
1275
+ ? { kind: "file-only" as const, path: step.outputPath, missing: !fs.existsSync(step.outputPath) && !finalOutputHasPersistableFileContent }
1276
+ : effectiveStructuredOutput
1277
+ ? { kind: "structured" as const, path: effectiveStructuredOutput.outputPath, missing: !fs.existsSync(effectiveStructuredOutput.outputPath) }
1675
1278
  : undefined;
1676
- const effectiveExitCode = toolAvailabilityError || (completionGuardTriggered && !isAgentContractV1(step.agentContract)) || structuredError || emptyOutputError
1279
+ finalRequiredOutputMissing = requiredOutput?.missing;
1280
+ const missingRequiredOutputError = formatRequiredOutputError(requiredOutput);
1281
+ const missingRequiredOutputAfterMutation = Boolean(missingRequiredOutputError) && (mutationAttemptObserved || Boolean(mutationEvidence.changedFiles.length));
1282
+ const effectiveExitCode = toolAvailabilityError || completionEvidence.legacyFailureError || midToolExitError || structuredError || emptyOutputError || missingRequiredOutputError
1677
1283
  ? 1
1678
1284
  : hiddenError?.hasError
1679
1285
  ? (hiddenError.exitCode ?? 1)
1680
1286
  : run.error && run.exitCode === 0
1681
1287
  ? 1
1682
1288
  : run.exitCode;
1683
- const signalError = run.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
1684
- processSignal: run.processSignal,
1685
- interrupted: run.interrupted,
1686
- timedOut: run.timedOut,
1687
- stopped: run.stopped,
1688
- turnBudgetExceeded: run.turnBudgetExceeded,
1689
- })) ? formatProcessSignalError(run.processSignal!) : undefined;
1690
- const error = formatSubagentExtensionConflictError(
1691
- toolAvailabilityError
1692
- ?? completionGuardError
1693
- ?? structuredError
1694
- ?? emptyOutputError
1695
- ?? (hiddenError?.hasError
1696
- ? hiddenError.details
1697
- ? `${hiddenError.errorType} failed (exit ${effectiveExitCode}): ${hiddenError.details}`
1698
- : `${hiddenError.errorType} failed with exit code ${effectiveExitCode}`
1699
- : run.error || signalError || (run.exitCode !== 0 && run.stderr.trim() ? run.stderr.trim() : undefined)),
1700
- {
1701
- agent: step.agent,
1702
- ambientExtensionsEnabled: launchResolvedExtensions?.disableAmbientExtensions === false,
1703
- },
1704
- );
1289
+ const underlyingError = toolAvailabilityError
1290
+ ?? midToolExitError
1291
+ ?? structuredError
1292
+ ?? run.error
1293
+ ?? emptyOutputError
1294
+ ?? (missingRequiredOutputAfterMutation ? missingRequiredOutputError : undefined)
1295
+ ?? (hiddenError?.hasError
1296
+ ? hiddenError.details
1297
+ ? `${hiddenError.errorType} failed (exit ${effectiveExitCode}): ${hiddenError.details}`
1298
+ : `${hiddenError.errorType} failed with exit code ${effectiveExitCode}`
1299
+ : undefined);
1300
+ const error = underlyingError ?? missingRequiredOutputError ?? completionEvidence.legacyFailureError;
1705
1301
  const attempt: ModelAttempt = omitUndefinedProperties({
1706
1302
  model: candidate ?? run.model ?? step.model ?? "default",
1707
1303
  success: effectiveExitCode === 0 && !error,
@@ -1710,8 +1306,8 @@ async function runSingleStepInner(
1710
1306
  usage: run.usage,
1711
1307
  });
1712
1308
  modelAttempts.push(attempt);
1713
- if (candidate && startupAttemptIndex === 0) attemptedModels.push(candidate);
1714
- completionGuardTriggeredFinal = completionGuardTriggered;
1309
+ if (!recoveringAbort && candidate) attemptedModels.push(candidate);
1310
+ completionGuardTriggeredFinal = completionEvidence.guardTriggered && !underlyingError && !missingRequiredOutputError;
1715
1311
  finalOutputSnapshot = outputSnapshot;
1716
1312
  if (step.toolBudget) {
1717
1313
  const toolMessages = run.messages.filter((message) => message.role === "toolResult");
@@ -1719,69 +1315,71 @@ async function runSingleStepInner(
1719
1315
  toolBudgetBlocked = Boolean(blockedMessage);
1720
1316
  toolBudget = toolBudgetState(step.toolBudget, toolMessages.length, blockedMessage ? (blockedMessage as { toolName?: string }).toolName : undefined);
1721
1317
  }
1722
- 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 };
1723
- if (run.turnBudgetExceeded) break modelAttemptsLoop;
1724
- if (run.stopped || run.timedOut || ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break modelAttemptsLoop;
1725
- if (attempt.success || completionGuardTriggered) break modelAttemptsLoop;
1726
-
1727
- const startupFailure = isRetryableSubagentStartupFailure(omitUndefinedProperties({
1728
- exitCode: effectiveExitCode,
1318
+ const settlementDiagnostic = projectSettlementDiagnostic(completionEvidence, {
1319
+ terminalFailed: effectiveExitCode !== 0,
1320
+ finalTextPresent: Boolean(stripAcceptanceReport(run.finalOutput).trim()),
1321
+ mutationObserved: mutationEvidence.attemptedMutation,
1322
+ requiredOutput,
1323
+ afterCompactionSettlement: run.afterCompactionSettlement === true,
1324
+ });
1325
+ const fileMutationEffect = completionEvidence.fileMutation ?? (missingRequiredOutputAfterMutation ? { status: "observed" as const, expected: completionEvidence.mutationExpected, attempted: true, evidence: mutationEvidence } : undefined);
1326
+ finalResult = { ...run, exitCode: effectiveExitCode, model: candidate ?? run.model, error, structuredOutput, runtimeAcknowledgedExtensions, ...(step.agentContract ? { agentContract: step.agentContract } : {}), ...(fileMutationEffect || settlementDiagnostic ? { effects: { ...(fileMutationEffect ? { fileMutation: fileMutationEffect } : {}), ...(settlementDiagnostic ? { settlementDiagnostic } : {}) } } : {}) } as RunChildSessionResult;
1327
+ const abortRecovery = !attempt.success ? planAbortRecovery({
1328
+ messages: run.messages,
1729
1329
  error,
1730
- finalOutput: run.finalOutput,
1731
- messageCount: run.messages.length,
1732
- toolCount: run.toolCount,
1733
- usage: run.usage,
1734
- durationMs: run.durationMs,
1735
- protocolError: run.protocolError,
1736
- processSignal: run.processSignal,
1737
- observedMutationAttempt: run.observedMutationAttempt,
1330
+ sessionAvailable: Boolean(step.sessionFile && fs.existsSync(step.sessionFile)),
1331
+ alreadyResumed: abortRecoveryAttempted,
1332
+ stopped: run.stopped || ctx.stopSignal?.aborted || ctx.skipAcceptance?.(),
1738
1333
  interrupted: run.interrupted,
1739
- timedOut: run.timedOut,
1740
- stopped: run.stopped,
1741
- turnBudgetExceeded: run.turnBudgetExceeded,
1742
- }));
1743
- const retryDelayMs = SUBAGENT_STARTUP_RETRY_DELAYS_MS[startupAttemptIndex];
1744
- if (startupFailure && retryDelayMs !== undefined) {
1745
- const retryNote = formatSubagentStartupRetryNote({
1746
- model: attempt.model,
1747
- attempt: startupAttemptIndex + 1,
1748
- maxAttempts: SUBAGENT_STARTUP_RETRY_DELAYS_MS.length + 1,
1749
- delayMs: retryDelayMs,
1750
- });
1751
- const shouldRetry = await waitForSubagentStartupRetry(retryDelayMs, [ctx.timeoutSignal, ctx.stopSignal]);
1752
- if (!shouldRetry || ctx.skipAcceptance?.()) break modelAttemptsLoop;
1753
- if (!taskDeliveryOverride && run.processSignal === "SIGKILL") {
1754
- taskDeliveryOverride = "file";
1755
- attemptNotes.push("[startup-retry] retrying with file task delivery to keep the task text out of the child process argv.");
1756
- }
1757
- attempt.error = retryNote;
1758
- attemptNotes.push(retryNote);
1759
- startupAttemptIndex += 1;
1334
+ timedOut: run.timedOut || ctx.timeoutSignal?.aborted,
1335
+ toolBudgetExhausted: run.toolBudgetBlocked || toolBudgetBlocked,
1336
+ usageBudgetExhausted: ctx.usageBudgetExhausted?.(),
1337
+ structuredOutputFailed: Boolean(structuredError),
1338
+ acceptanceFailed: false,
1339
+ currentTool: run.currentTool,
1340
+ afterCompactionSettlement: run.afterCompactionSettlement,
1341
+ }) : undefined;
1342
+ if (abortRecovery?.action === "settle" && abortRecovery.diagnostic) {
1343
+ attempt.error = attempt.error
1344
+ ? `${abortRecovery.diagnostic}\n${attempt.error.slice(0, 8_000)}`
1345
+ : abortRecovery.diagnostic;
1346
+ if (finalResult) finalResult.abortRecoveryDiagnostic = abortRecovery.diagnostic;
1347
+ }
1348
+ if (run.stopped || run.timedOut || ctx.timeoutSignal?.aborted || ctx.stopSignal?.aborted || ctx.skipAcceptance?.()) break modelAttemptsLoop;
1349
+ if (abortRecovery?.action === "settle" && abortRecovery.diagnostic) break modelAttemptsLoop;
1350
+ if (attempt.success) break modelAttemptsLoop;
1351
+ if (recoveringAbort) break modelAttemptsLoop;
1352
+ if (abortRecovery?.action === "resume") {
1353
+ abortRecoveryAttempted = true;
1354
+ nextAttemptTask = abortRecovery.prompt;
1355
+ attemptNotes.push("[abort-recovery] provider/transport abort after useful progress; resuming the retained child session once.");
1760
1356
  continue;
1761
1357
  }
1762
- if (startupFailure) {
1763
- const startupError = formatSubagentStartupRetryExhaustedError({
1764
- model: attempt.model,
1765
- attempts: startupAttemptIndex + 1,
1766
- });
1767
- attempt.error = startupError;
1768
- finalResult.error = startupError;
1769
- finalResult.finalOutput = startupError;
1358
+ if (completionEvidence.guardTriggered) break modelAttemptsLoop;
1359
+
1360
+ const retryableModelFailure = isRetryableModelFailureAttempt({ error, messages: run.messages, toolCount: run.toolCount });
1361
+ if (retryableModelFailure) recordRetryableModelFailure(candidate ?? run.model ?? step.model, error);
1362
+ if (isContextOverflow(error)) {
1363
+ contextOverflow = true;
1364
+ attemptNotes.push(`[fallback] ${attempt.model} failed: context overflow — the input exceeds this model's context window. Reduce the task input or use a model with a larger context window.`);
1770
1365
  break modelAttemptsLoop;
1771
1366
  }
1772
- const retryableModelFailure = isRetryableModelFailure(error);
1773
- if (retryableModelFailure) recordRetryableModelFailure(candidate ?? run.model ?? step.model, error);
1774
1367
  if (!retryableModelFailure || modelIndex === candidates.length - 1) break modelAttemptsLoop;
1775
1368
  attemptNotes.push(formatModelAttemptNote(attempt, candidates[modelIndex + 1]));
1776
1369
  modelIndex += 1;
1777
- startupAttemptIndex = 0;
1778
1370
  }
1779
1371
 
1780
1372
  const rawOutput = finalResult?.finalOutput ?? "";
1781
1373
  const outputForPersistence = stripAcceptanceReport(rawOutput);
1782
1374
  const resolvedOutput = step.outputPath && finalResult?.exitCode === 0
1783
- ? resolveSingleOutput(step.outputPath, outputForPersistence, finalOutputSnapshot)
1375
+ ? resolveSingleOutput(step.outputPath, outputForPersistence, finalOutputSnapshot, step.outputClaimPath)
1784
1376
  : { fullOutput: outputForPersistence };
1377
+ if (resolvedOutput.fatalError) {
1378
+ if (finalResult) {
1379
+ finalResult.exitCode = 1;
1380
+ finalResult.error = finalResult.error ? `${finalResult.error}\n${resolvedOutput.saveError}` : resolvedOutput.saveError;
1381
+ }
1382
+ }
1785
1383
  const output = stripAcceptanceReport(resolvedOutput.fullOutput);
1786
1384
  const outputReference = resolvedOutput.savedPath ? formatSavedOutputReference(resolvedOutput.savedPath, output) : undefined;
1787
1385
  let outputForSummary = output;
@@ -1790,26 +1388,34 @@ async function runSingleStepInner(
1790
1388
  }
1791
1389
  if (finalResult?.stopped && !outputForSummary.trim()) {
1792
1390
  outputForSummary = ctx.stopMessage ?? "Subagent stopped by user.";
1793
- } else if (!finalResult?.timedOut && !finalResult?.stopped && finalResult?.turnBudgetExceeded && turnBudget) {
1794
- outputForSummary = formatTurnBudgetOutput(turnBudgetExceededMessage(turnBudget, turnBudget.turnCount), outputForSummary);
1795
- } else if (!finalResult?.timedOut && !finalResult?.stopped && turnBudget?.outcome === "termination-deferred") {
1796
- const note = turnBudgetDeferredNote(turnBudget, turnBudget.terminationDeferredAtTurn ?? turnBudget.turnCount);
1797
- outputForSummary = outputForSummary.trim() ? `${note}\n\n${outputForSummary}` : note;
1798
- } else if (!finalResult?.timedOut && !finalResult?.stopped && turnBudget?.outcome === "wrap-up-requested") {
1799
- const note = turnBudgetSoftNote(turnBudget, turnBudget.wrapUpRequestedAtTurn ?? turnBudget.turnCount);
1800
- outputForSummary = outputForSummary.trim() ? `${note}\n\n${outputForSummary}` : note;
1801
1391
  }
1802
1392
  const outputForAcceptance = rawOutput;
1803
1393
  const childWrittenOutput = step.outputPath
1804
1394
  ? extractChildWrittenOutput(finalResult?.messages, step.outputPath, step.cwd ?? ctx.cwd)
1805
1395
  : undefined;
1806
1396
  const outputState: SubagentOutputState = finalResult?.outputState === "present"
1807
- || (finalResult as (RunPiStreamingResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput !== undefined
1397
+ || (finalResult as (RunChildSessionResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput !== undefined
1808
1398
  || Boolean(childWrittenOutput?.trim())
1809
1399
  ? "present"
1810
1400
  : resolvedOutput.savedPath
1811
1401
  ? "unknown"
1812
1402
  : finalResult?.outputState ?? "unknown";
1403
+ const timeoutRecovery = finalResult?.timedOut === true || ctx.timeoutSignal?.aborted === true
1404
+ ? buildTimeoutRecoverySummary({
1405
+ termination: "timed-out",
1406
+ evidence: finalMutationEvidence,
1407
+ requiredOutputMissing: finalRequiredOutputMissing,
1408
+ currentTool: finalResult?.currentTool,
1409
+ currentToolArgs: finalResult?.currentToolArgs,
1410
+ currentPath: finalResult?.currentPath,
1411
+ sessionFile: step.sessionFile,
1412
+ transcriptPath: transcriptWriter ? artifactPaths?.transcriptPath : undefined,
1413
+ artifactPaths,
1414
+ })
1415
+ : undefined;
1416
+ if (timeoutRecovery) outputForSummary = outputForSummary.trim()
1417
+ ? `${outputForSummary}\n\n${timeoutRecovery.message}`
1418
+ : timeoutRecovery.message;
1813
1419
  const finalizedOutput = finalizeSingleOutput(omitUndefinedProperties({
1814
1420
  fullOutput: outputForSummary,
1815
1421
  outputPath: step.outputPath,
@@ -1820,12 +1426,14 @@ async function runSingleStepInner(
1820
1426
  saveError: resolvedOutput.saveError,
1821
1427
  }));
1822
1428
  outputForSummary = finalizedOutput.displayOutput;
1823
- const acceptance = step.effectiveAcceptance && !finalResult?.stopped && !finalResult?.turnBudgetExceeded && !ctx.timeoutSignal?.aborted && !ctx.stopSignal?.aborted && !ctx.skipAcceptance?.()
1429
+ const acceptance = step.effectiveAcceptance && !finalResult?.stopped && !ctx.timeoutSignal?.aborted && !ctx.stopSignal?.aborted && !ctx.skipAcceptance?.()
1824
1430
  ? await evaluateAcceptance(omitUndefinedProperties({
1825
1431
  acceptance: step.effectiveAcceptance,
1826
1432
  output: outputForAcceptance,
1433
+ report: structuredAcceptanceReport as import("../../shared/types.ts").AcceptanceReport | undefined,
1434
+ reportError: structuredAcceptanceReportError,
1827
1435
  fileOutput: childWrittenOutput !== undefined && step.outputPath
1828
- ? { content: childWrittenOutput, path: step.outputPath, authoritative: step.outputMode === "file-only" }
1436
+ ? { content: childWrittenOutput, path: step.outputPath, authoritative: step.outputMode === "file-only", durable: resolvedOutput.savedPath !== undefined }
1829
1437
  : undefined,
1830
1438
  cwd: step.cwd ?? ctx.cwd,
1831
1439
  signal: combinedAbortSignal([ctx.timeoutSignal, ctx.stopSignal]),
@@ -1833,33 +1441,36 @@ async function runSingleStepInner(
1833
1441
  reportOptional: isAgentContractV1(step.agentContract),
1834
1442
  artifactsDir: ctx.artifactsDir,
1835
1443
  runId: ctx.id,
1444
+ watchdog: finalResult?.watchdog,
1836
1445
  }))
1837
1446
  : undefined;
1838
1447
  const stoppedAfterAcceptance = finalResult?.stopped === true || ctx.stopSignal?.aborted === true;
1839
1448
  const timedOutAfterAcceptance = !stoppedAfterAcceptance && (finalResult?.timedOut === true || ctx.timeoutSignal?.aborted === true);
1840
- const turnBudgetExceeded = finalResult?.turnBudgetExceeded === true;
1841
1449
  const effectiveAcceptance = step.effectiveAcceptance
1842
1450
  ? stoppedAfterAcceptance
1843
1451
  ? buildSkippedAcceptanceLedger(step.effectiveAcceptance, { id: "stopped", message: "Acceptance was not evaluated because the subagent was stopped." })
1844
1452
  : timedOutAfterAcceptance
1845
1453
  ? buildSkippedAcceptanceLedger(step.effectiveAcceptance, { id: "timeout", message: "Acceptance was not evaluated because the subagent timed out." })
1846
- : turnBudgetExceeded
1847
- ? buildSkippedAcceptanceLedger(step.effectiveAcceptance, { id: "turn-budget", message: "Acceptance was not evaluated because the subagent exceeded its turn budget." })
1848
- : acceptance
1454
+ : acceptance
1849
1455
  : undefined;
1850
1456
  const acceptanceFailure = effectiveAcceptance ? acceptanceFailureMessage(effectiveAcceptance) : undefined;
1851
- const acceptanceCanFailRun = acceptanceFailure && effectiveAcceptance?.explicit && (finalResult?.exitCode ?? 1) === 0 && !finalResult?.interrupted && !timedOutAfterAcceptance && !stoppedAfterAcceptance && !turnBudgetExceeded && !isAgentContractV1(step.agentContract);
1852
- const effectiveFinalExitCode = timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? 1 : acceptanceCanFailRun ? 1 : finalResult?.exitCode ?? 1;
1457
+ const acceptanceCanFailRun = acceptanceFailure && effectiveAcceptance?.explicit && (finalResult?.exitCode ?? 1) === 0 && !finalResult?.interrupted && !timedOutAfterAcceptance && !stoppedAfterAcceptance && !isAgentContractV1(step.agentContract);
1458
+ const effectiveFinalExitCode = timedOutAfterAcceptance || stoppedAfterAcceptance ? 1 : acceptanceCanFailRun ? 1 : finalResult?.exitCode ?? 1;
1853
1459
  const intercomDetachReceipt = finalResult?.finalOutput === INTERCOM_DETACH_RECEIPT;
1854
- const effectiveFinalError = stoppedAfterAcceptance
1460
+ const baseFinalError = stoppedAfterAcceptance
1855
1461
  ? ctx.stopMessage ?? "Subagent stopped by user."
1856
1462
  : timedOutAfterAcceptance
1857
1463
  ? finalResult?.error ?? ctx.timeoutMessage ?? "Subagent timed out."
1858
- : turnBudgetExceeded
1859
- ? finalResult?.error ?? (turnBudget ? turnBudgetExceededMessage(turnBudget, turnBudget.turnCount) : "Subagent exceeded turn budget.")
1860
- : acceptanceCanFailRun
1464
+ : acceptanceCanFailRun
1861
1465
  ? (finalResult?.error ? `${finalResult.error}\n${acceptanceFailure}` : acceptanceFailure)
1862
1466
  : finalResult?.error ?? (intercomDetachReceipt ? INTERCOM_DETACH_RECEIPT : undefined);
1467
+ const effectiveFinalError = formatChildFailureDiagnostic({
1468
+ error: baseFinalError,
1469
+ afterCompactionSettlement: effectiveFinalExitCode !== 0 ? finalResult?.afterCompactionSettlement : undefined,
1470
+ abortRecoveryDiagnostic: effectiveFinalExitCode !== 0 ? finalResult?.abortRecoveryDiagnostic : undefined,
1471
+ requiredOutput: effectiveFinalExitCode !== 0 ? finalResult?.effects?.settlementDiagnostic?.requiredOutput : undefined,
1472
+ });
1473
+ const usage = usageFromAttempts(modelAttempts);
1863
1474
 
1864
1475
  const artifactErrors = artifactPaths && ctx.artifactConfig?.enabled !== false
1865
1476
  ? persistStepArtifacts({
@@ -1879,12 +1490,13 @@ async function runSingleStepInner(
1879
1490
  model: finalResult?.model,
1880
1491
  attemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,
1881
1492
  modelAttempts,
1493
+ usage,
1882
1494
  error: effectiveFinalError,
1883
1495
  acceptance: effectiveAcceptance,
1884
1496
  ...(capabilityAudit ? { capabilityCeiling: capabilityAudit.ceiling, capabilityAudit } : {}),
1885
1497
  launchContractDigest: actualLaunchContractDigest,
1886
1498
  launchResolvedExtensions,
1887
- ...((finalResult as (RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }) | undefined)?.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: (finalResult as RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }).runtimeAcknowledgedExtensions } : {}),
1499
+ ...((finalResult as (RunChildSessionResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }) | undefined)?.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: (finalResult as RunChildSessionResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }).runtimeAcknowledgedExtensions } : {}),
1888
1500
  ...(transcriptWriter ? { transcriptPath: artifactPaths.transcriptPath } : {}),
1889
1501
  transcriptError: transcriptWriter?.getError(),
1890
1502
  skills: step.skills,
@@ -1895,6 +1507,7 @@ async function runSingleStepInner(
1895
1507
 
1896
1508
  const result: StepResult & { completionGuardTriggered?: boolean } = omitUndefinedProperties({
1897
1509
  agent: step.agent,
1510
+ ...(childSessionName ? { sessionName: childSessionName } : {}),
1898
1511
  context: step.context,
1899
1512
  ...(step.agentContract ? { agentContract: step.agentContract } : {}),
1900
1513
  launchContractDigest: actualLaunchContractDigest,
@@ -1902,39 +1515,36 @@ async function runSingleStepInner(
1902
1515
  outputState,
1903
1516
  exitCode: effectiveFinalExitCode,
1904
1517
  error: effectiveFinalError,
1905
- protocolError: finalResult?.protocolError,
1906
1518
  sessionFile: step.sessionFile,
1907
1519
  intercomTarget: ctx.childIntercomTarget,
1908
1520
  model: finalResult?.model,
1521
+ thinking: resolveEffectiveThinking(finalResult?.model, step.thinking),
1909
1522
  attemptedModels: attemptedModels.length > 0 ? attemptedModels : undefined,
1910
1523
  modelAttempts,
1524
+ contextOverflow: contextOverflow || undefined,
1911
1525
  totalCost: costSummaryFromAttempts(modelAttempts),
1526
+ usage,
1912
1527
  artifactPaths,
1913
- outputSaveError: artifactErrors.outputSaveError,
1528
+ outputSaveError: [resolvedOutput.saveError, artifactErrors.outputSaveError].filter(Boolean).join("\n") || undefined,
1914
1529
  metadataSaveError: artifactErrors.metadataSaveError,
1915
1530
  transcriptPath: transcriptWriter ? artifactPaths?.transcriptPath : undefined,
1916
1531
  transcriptError: transcriptWriter?.getError(),
1917
- interrupted: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? false : finalResult?.interrupted,
1532
+ interrupted: timedOutAfterAcceptance || stoppedAfterAcceptance ? false : finalResult?.interrupted,
1918
1533
  timedOut: timedOutAfterAcceptance ? true : finalResult?.timedOut,
1919
1534
  stopped: stoppedAfterAcceptance ? true : finalResult?.stopped,
1920
- processSignal: finalResult?.processSignal,
1921
- turnBudget,
1922
- turnBudgetExceeded: turnBudgetExceeded || undefined,
1923
- wrapUpRequested: finalResult?.wrapUpRequested || turnBudget?.outcome === "wrap-up-requested" || turnBudget?.outcome === "termination-deferred" || turnBudgetExceeded || undefined,
1535
+ timeoutRecovery,
1924
1536
  toolBudget,
1925
1537
  toolBudgetBlocked: toolBudgetBlocked || undefined,
1926
1538
  completionGuardTriggered: completionGuardTriggeredFinal,
1927
- ...((finalResult as (RunPiStreamingResult & { effects?: import("../../shared/types.ts").EffectsProjection }) | undefined)?.effects ? { effects: (finalResult as RunPiStreamingResult & { effects?: import("../../shared/types.ts").EffectsProjection }).effects } : {}),
1928
- structuredOutput: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? undefined : (finalResult as (RunPiStreamingResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput,
1929
- structuredOutputPath: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? undefined : effectiveStructuredOutput?.outputPath,
1930
- structuredOutputSchemaPath: timedOutAfterAcceptance || stoppedAfterAcceptance || turnBudgetExceeded ? undefined : effectiveStructuredOutput?.schemaPath,
1539
+ ...((finalResult as (RunChildSessionResult & { effects?: import("../../shared/types.ts").EffectsProjection }) | undefined)?.effects ? { effects: (finalResult as RunChildSessionResult & { effects?: import("../../shared/types.ts").EffectsProjection }).effects } : {}),
1540
+ structuredOutput: timedOutAfterAcceptance || stoppedAfterAcceptance ? undefined : (finalResult as (RunChildSessionResult & { structuredOutput?: unknown }) | undefined)?.structuredOutput,
1541
+ structuredOutputPath: timedOutAfterAcceptance || stoppedAfterAcceptance ? undefined : effectiveStructuredOutput?.outputPath,
1542
+ structuredOutputSchemaPath: timedOutAfterAcceptance || stoppedAfterAcceptance ? undefined : effectiveStructuredOutput?.schemaPath,
1931
1543
  acceptance: effectiveAcceptance,
1932
1544
  watchdog: finalResult?.watchdog,
1933
1545
  ...(capabilityAudit ? { capabilityCeiling: capabilityAudit.ceiling, capabilityAudit } : {}),
1934
1546
  launchResolvedExtensions,
1935
- ...((finalResult as (RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }) | undefined)?.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: (finalResult as RunPiStreamingResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }).runtimeAcknowledgedExtensions } : {}),
1936
- writerProcesses,
1937
- writerAttemptCount,
1547
+ ...((finalResult as (RunChildSessionResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }) | undefined)?.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: (finalResult as RunChildSessionResult & { runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensionsV1 }).runtimeAcknowledgedExtensions } : {}),
1938
1548
  });
1939
1549
  return isAgentContractV1(step.agentContract) ? attachContractProjections(result as unknown as import("../../shared/types.ts").SingleResult) as unknown as typeof result : result;
1940
1550
  }
@@ -1943,21 +1553,8 @@ async function runSingleStep(
1943
1553
  step: SubagentStep,
1944
1554
  ctx: SingleStepContext,
1945
1555
  ): Promise<StepResult & { completionGuardTriggered?: boolean }> {
1946
- if (step.importAsyncRoot) return runSingleStepInner(step, ctx);
1947
- const orcaProgressTab = createOrcaProgressTab({
1948
- cwd: step.cwd ?? ctx.cwd,
1949
- runId: ctx.id,
1950
- agent: step.agent,
1951
- index: ctx.flatIndex,
1952
- });
1953
- try {
1954
- const result = await runSingleStepInner(step, { ...ctx, orcaProgressTab });
1955
- orcaProgressTab?.finish(result.stopped ? "stopped" : result.exitCode === 0 && !result.error ? "completed" : "failed", result.sessionFile);
1956
- return result;
1957
- } catch (error) {
1958
- orcaProgressTab?.finish("failed");
1959
- throw error;
1960
- }
1556
+ if (!step.importAsyncRoot) ctx.orcaProgressTab?.section({ agent: step.agent, index: ctx.flatIndex, count: ctx.flatStepCount });
1557
+ return runSingleStepInner(step, ctx);
1961
1558
  }
1962
1559
 
1963
1560
  type RunnerStatusStep = NonNullable<AsyncStatus["steps"]>[number] & {
@@ -1967,13 +1564,7 @@ type RunnerStatusStep = NonNullable<AsyncStatus["steps"]>[number] & {
1967
1564
 
1968
1565
  function externalRunnerStatus(runner: SubagentStep["runner"]): ExternalCliRunnerStatus | ExternalJobRunnerStatus | undefined {
1969
1566
  if (runner?.type === "external-cli") {
1970
- return {
1971
- type: "external-cli",
1972
- command: runner.command,
1973
- args: runner.args ?? [],
1974
- promptDelivery: runner.promptDelivery ?? "stdin",
1975
- capabilities: { stop: true, steer: false, resume: false, structuredOutput: false, toolEvents: false },
1976
- };
1567
+ return resolveExternalCliRunnerStatus(runner);
1977
1568
  }
1978
1569
  if (runner?.type === "external-job") {
1979
1570
  return {
@@ -2020,6 +1611,13 @@ function requiredStatusStep(statusPayload: RunnerStatusPayload, index: number):
2020
1611
  return step;
2021
1612
  }
2022
1613
 
1614
+ function setStatusWorktreeReference(statusStep: RunnerStatusStep, worktree: WorktreeSetup["worktrees"][number]): void {
1615
+ statusStep.worktreePath = worktree.path;
1616
+ statusStep.branch = worktree.branch;
1617
+ if (worktree.provider) statusStep.provider = worktree.provider;
1618
+ if (worktree.naming) statusStep.naming = worktree.naming;
1619
+ }
1620
+
2023
1621
  function markParallelGroupSetupFailure(input: {
2024
1622
  statusPayload: RunnerStatusPayload;
2025
1623
  results: StepResult[];
@@ -2098,6 +1696,18 @@ function markParallelGroupRunning(input: {
2098
1696
  }));
2099
1697
  }
2100
1698
 
1699
+ function bindWorktreeCwd(step: SubagentStep, worktreeCwd: string): SubagentStep {
1700
+ const bind = <T extends string | null | undefined>(value: T): T => value === null || value === undefined ? value : value.replaceAll(WORKTREE_AGENT_CWD_PLACEHOLDER, worktreeCwd) as T;
1701
+ return {
1702
+ ...step,
1703
+ task: bind(step.task) ?? step.task,
1704
+ ...(step.systemPrompt !== undefined ? { systemPrompt: bind(step.systemPrompt) } : {}),
1705
+ ...(step.outputPath !== undefined ? { outputPath: bind(step.outputPath) } : {}),
1706
+ ...(step.launchBindingTask !== undefined ? { launchBindingTask: bind(step.launchBindingTask) } : {}),
1707
+ ...(step.requestedCwd !== undefined ? { requestedCwd: bind(step.requestedCwd) } : {}),
1708
+ };
1709
+ }
1710
+
2101
1711
  function prepareParallelTaskRun(
2102
1712
  task: SubagentStep,
2103
1713
  cwd: string,
@@ -2106,8 +1716,9 @@ function prepareParallelTaskRun(
2106
1716
  ): { taskForRun: SubagentStep; taskCwd: string } {
2107
1717
  if (!worktreeSetup) return { taskForRun: task, taskCwd: cwd };
2108
1718
  const { cwd: _taskCwd, ...taskForRun } = task;
1719
+ const boundTask = bindWorktreeCwd(taskForRun, worktreeSetup.worktrees[taskIndex]!.agentCwd);
2109
1720
  return {
2110
- taskForRun,
1721
+ taskForRun: boundTask,
2111
1722
  taskCwd: worktreeSetup.worktrees[taskIndex]!.agentCwd,
2112
1723
  };
2113
1724
  }
@@ -2148,6 +1759,25 @@ function resolveAsyncStepTranscriptPath(input: {
2148
1759
 
2149
1760
  type SingleStepResult = Awaited<ReturnType<typeof runSingleStep>>;
2150
1761
 
1762
+ function missingRequiredOutputAfterUsefulMutation(result: SingleStepResult): boolean {
1763
+ const effects = result.effects;
1764
+ return effects?.settlementDiagnostic?.requiredOutput?.missing === true
1765
+ && (effects.settlementDiagnostic.mutation.attempted || effects.fileMutation?.attempted === true || Boolean(effects.fileMutation?.evidence?.changedFiles.length));
1766
+ }
1767
+
1768
+ function partialExecutionWithUsefulMutation(result: SingleStepResult): boolean {
1769
+ const fileMutation = result.effects?.fileMutation;
1770
+ return result.execution?.status === "partial" && (fileMutation?.attempted === true || Boolean(fileMutation?.evidence?.changedFiles.length));
1771
+ }
1772
+
1773
+ function partialEvidenceResult(result: SingleStepResult): boolean {
1774
+ return missingRequiredOutputAfterUsefulMutation(result) || partialExecutionWithUsefulMutation(result);
1775
+ }
1776
+
1777
+ function concreteFailureResult(result: SingleStepResult): boolean {
1778
+ return result.success === false && !partialEvidenceResult(result);
1779
+ }
1780
+
2151
1781
  function combinedAbortSignal(signals: Array<AbortSignal | undefined>): AbortSignal | undefined {
2152
1782
  const activeSignals = signals.filter((signal): signal is AbortSignal => Boolean(signal));
2153
1783
  if (activeSignals.length === 0) return undefined;
@@ -2208,7 +1838,7 @@ async function runSingleStepWithTimeout(
2208
1838
 
2209
1839
  async function runSubagent(
2210
1840
  config: SubagentRunConfig,
2211
- onWriterProcess?: (writer: { state: "none" | "spawning" } | { state: "running"; pid: number }) => void,
1841
+ childSessions: ChildSessionFactory,
2212
1842
  ): Promise<void> {
2213
1843
  const { id, steps, resultPath, cwd, placeholder, taskIndex, totalTasks, maxOutput, artifactsDir, artifactConfig } =
2214
1844
  config;
@@ -2219,6 +1849,8 @@ async function runSubagent(
2219
1849
  const overallStartTime = Date.now();
2220
1850
  const shareEnabled = config.share === true;
2221
1851
  const asyncDir = config.asyncDir;
1852
+ const handoffWorkflowKey = config.workflowKey;
1853
+ const handoffChildRunId = handoffWorkflowKey ? id : undefined;
2222
1854
  const statusPath = path.join(asyncDir, "status.json");
2223
1855
  const eventsPath = path.join(asyncDir, "events.jsonl");
2224
1856
  const logPath = path.join(asyncDir, `subagent-log-${id}.md`);
@@ -2226,16 +1858,17 @@ async function runSubagent(
2226
1858
  const activeChildInterrupts = new Map<number, () => void>();
2227
1859
  const activeChildTimeouts = new Map<number, () => void>();
2228
1860
  const activeChildStops = new Map<number, () => void>();
2229
- const activeChildTurnBudgetAborts = new Map<number, (message: string, state?: TurnBudgetState) => void>();
1861
+ const activeChildSteers = new Map<number, StepSteerHandler>();
1862
+ /** Steers routed to a running step before its session was created. */
1863
+ const queuedStepSteers = new Map<number, SteerRequest[]>();
1864
+ const childStopRequests = new Map<number, { childId: string; requestedAt: number }>();
2230
1865
  const pendingStepSteers: SteerRequest[] = [];
2231
- const steeringCapabilities = new Map<number, SteerCapability>();
2232
1866
  let interrupted = false;
2233
1867
  let currentActivityState: ActivityState | undefined;
2234
1868
  let activityTimer: NodeJS.Timeout | undefined;
2235
1869
  let timeoutTimer: NodeJS.Timeout | undefined;
2236
1870
  let timedOut = false;
2237
1871
  let stopped = false;
2238
- let turnBudgetExceeded = false;
2239
1872
  let usageBudgetExceeded = false;
2240
1873
  const timeoutMessage = config.timeoutMs !== undefined ? `Subagent timed out after ${config.timeoutMs}ms.` : undefined;
2241
1874
  const stopMessage = "Subagent stopped by user.";
@@ -2256,8 +1889,11 @@ async function runSubagent(
2256
1889
  for (const task of step.parallel) {
2257
1890
  const taskFlatIndex = flatStepCount;
2258
1891
  const transcriptPath = resolveAsyncStepTranscriptPath(omitUndefinedProperties({ artifactsDir, artifactConfig, runId: id, agent: task.agent, flatIndex: taskFlatIndex, flatStepCount: initialFlatStepCount }));
1892
+ const taskSessionName = task.sessionName ?? deriveChildSessionName({ agent: task.agent, task: task.task, label: task.label });
2259
1893
  initialStatusSteps.push(omitUndefinedProperties({
2260
1894
  agent: task.agent,
1895
+ ...(task.lane ? { lane: task.lane } : config.lane ? { lane: config.lane } : {}),
1896
+ ...(taskSessionName ? { sessionName: taskSessionName } : {}),
2261
1897
  ...(externalRunnerStatus(task.runner) ? { runner: externalRunnerStatus(task.runner) } : {}),
2262
1898
  ...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),
2263
1899
  ...(task.context ? { context: task.context } : {}),
@@ -2269,12 +1905,14 @@ async function runSubagent(
2269
1905
  ...(task.launchContractDigest ? { launchContractDigest: task.launchContractDigest } : {}),
2270
1906
  ...(task.launchResolvedExtensions ? { launchResolvedExtensions: task.launchResolvedExtensions } : {}),
2271
1907
  ...(task.capabilityCeiling ? { capabilityCeiling: task.capabilityCeiling } : {}),
1908
+ ...(task.thinkingCeiling ? { thinkingCeiling: task.thinkingCeiling } : {}),
2272
1909
  status: "pending",
2273
1910
  ...(task.toolBudget ? { toolBudget: initialToolBudgetState(task.toolBudget) } : {}),
2274
1911
  ...(task.sessionFile ? { sessionFile: task.sessionFile } : {}),
2275
1912
  ...(transcriptPath ? { transcriptPath } : {}),
2276
1913
  skills: task.skills,
2277
1914
  model: task.model,
1915
+ ...(task.contextLimit !== undefined ? { contextLimit: task.contextLimit } : {}),
2278
1916
  thinking: task.thinking,
2279
1917
  attemptedModels: task.modelCandidates && task.modelCandidates.length > 0 ? task.modelCandidates : task.model ? [task.model] : undefined,
2280
1918
  recentTools: [],
@@ -2292,8 +1930,10 @@ async function runSubagent(
2292
1930
  label: step.label ?? step.parallel.label ?? `Dynamic fanout (${step.collect.as})`,
2293
1931
  outputName: step.collect.as,
2294
1932
  structured: Boolean(step.collect.outputSchema),
1933
+ ...(step.parallel.contextLimit !== undefined ? { contextLimit: step.parallel.contextLimit } : {}),
2295
1934
  ...(step.agentContract ? { agentContract: step.agentContract } : {}),
2296
1935
  ...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
1936
+ ...(step.thinkingCeiling ? { thinkingCeiling: step.thinkingCeiling } : {}),
2297
1937
  status: "pending",
2298
1938
  ...(step.parallel.toolBudget ? { toolBudget: initialToolBudgetState(step.parallel.toolBudget) } : {}),
2299
1939
  recentTools: [],
@@ -2303,8 +1943,11 @@ async function runSubagent(
2303
1943
  } else {
2304
1944
  const stepFlatIndex = flatStepCount;
2305
1945
  const transcriptPath = resolveAsyncStepTranscriptPath(omitUndefinedProperties({ artifactsDir, artifactConfig, runId: id, agent: step.agent, flatIndex: stepFlatIndex, flatStepCount: initialFlatStepCount }));
1946
+ const stepSessionName = step.sessionName ?? deriveChildSessionName({ agent: step.agent, task: step.task, label: step.label });
2306
1947
  initialStatusSteps.push(omitUndefinedProperties({
2307
1948
  agent: step.agent,
1949
+ ...(step.lane ? { lane: step.lane } : config.lane ? { lane: config.lane } : {}),
1950
+ ...(stepSessionName ? { sessionName: stepSessionName } : {}),
2308
1951
  ...(externalRunnerStatus(step.runner) ? { runner: externalRunnerStatus(step.runner) } : {}),
2309
1952
  ...(statusStepDescription(step.task) ? { description: statusStepDescription(step.task) } : {}),
2310
1953
  ...(step.context ? { context: step.context } : {}),
@@ -2316,12 +1959,14 @@ async function runSubagent(
2316
1959
  ...(step.launchContractDigest ? { launchContractDigest: step.launchContractDigest } : {}),
2317
1960
  ...(step.launchResolvedExtensions ? { launchResolvedExtensions: step.launchResolvedExtensions } : {}),
2318
1961
  ...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
1962
+ ...(step.thinkingCeiling ? { thinkingCeiling: step.thinkingCeiling } : {}),
2319
1963
  status: "pending",
2320
1964
  ...(step.toolBudget ? { toolBudget: initialToolBudgetState(step.toolBudget) } : {}),
2321
1965
  ...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
2322
1966
  ...(transcriptPath ? { transcriptPath } : {}),
2323
1967
  skills: step.skills,
2324
1968
  model: step.model,
1969
+ ...(step.contextLimit !== undefined ? { contextLimit: step.contextLimit } : {}),
2325
1970
  thinking: step.thinking,
2326
1971
  attemptedModels: step.modelCandidates && step.modelCandidates.length > 0 ? step.modelCandidates : step.model ? [step.model] : undefined,
2327
1972
  recentTools: [],
@@ -2338,6 +1983,19 @@ async function runSubagent(
2338
1983
  step.processTerminal = { version: 1, state: "pending", runId: id, runnerProcessInstanceId: config.runnerProcessInstanceId };
2339
1984
  }
2340
1985
  }
1986
+ const initialAgentLabel = initialStatusSteps.length === 1
1987
+ ? initialStatusSteps[0]!.agent
1988
+ : (config.resultMode ?? (flatSteps.length > 1 ? "chain" : "single")) === "parallel"
1989
+ ? `parallel:${initialStatusSteps.map((step) => step.agent).join("+")}`
1990
+ : `chain:${initialStatusSteps.map((step) => step.agent).join("->")}`;
1991
+ const orcaProgressTab = flatSteps.every((step) => step.importAsyncRoot) ? undefined : createOrcaProgressTab({
1992
+ cwd,
1993
+ runId: id,
1994
+ agent: initialAgentLabel,
1995
+ index: 0,
1996
+ stepCount: Math.max(initialStatusSteps.length, 1),
1997
+ });
1998
+
2341
1999
  const statusPayload: RunnerStatusPayload = omitUndefinedProperties({
2342
2000
  lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
2343
2001
  runId: id,
@@ -2352,7 +2010,6 @@ async function runSubagent(
2352
2010
  lastUpdate: overallStartTime,
2353
2011
  ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),
2354
2012
  ...(config.deadlineAt !== undefined ? { deadlineAt: config.deadlineAt } : {}),
2355
- ...(config.turnBudget ? { turnBudget: initialTurnBudgetState(config.turnBudget) } : {}),
2356
2013
  ...(config.toolBudget ? { toolBudget: initialToolBudgetState(config.toolBudget) } : {}),
2357
2014
  ...(config.usageBudget ? { usageBudget: usageBudgetState(config.usageBudget, undefined) } : {}),
2358
2015
  pid: process.pid,
@@ -2367,6 +2024,7 @@ async function runSubagent(
2367
2024
  ...(config.runFanoutBudget ? { runFanoutBudget: getRunFanoutBudgetSnapshot(config.runFanoutBudget) } : {}),
2368
2025
  ...(config.parentWorkflowRunId ? { parentWorkflowRunId: config.parentWorkflowRunId } : {}),
2369
2026
  ...(config.workflowKey ? { workflowKey: config.workflowKey } : {}),
2027
+ ...(config.lane ? { lane: config.lane } : {}),
2370
2028
  ...(config.runnerProcessInstanceId ? { processTerminal: { version: 1 as const, state: "pending" as const, runId: id, runnerProcessInstanceId: config.runnerProcessInstanceId } } : {}),
2371
2029
  steps: initialStatusSteps,
2372
2030
  artifactsDir,
@@ -2484,6 +2142,7 @@ async function runSubagent(
2484
2142
  const statusResultSummary = (state: AsyncStatus["state"]): string => {
2485
2143
  if (statusPayload.error) return statusPayload.error;
2486
2144
  if (state === "paused") return "Paused after interrupt. Waiting for explicit next action.";
2145
+ if (state === "partial") return "Subagent needs attention after partial work.";
2487
2146
  if (state === "stopped") return stopMessage;
2488
2147
  if (state === "rejected") return "Subagent rejected.";
2489
2148
  return state === "complete" ? "Subagent completed." : "Subagent failed.";
@@ -2492,12 +2151,13 @@ async function runSubagent(
2492
2151
  if (step.status === "complete" || step.status === "completed") return true;
2493
2152
  if (step.status === "failed" || step.status === "stopped" || step.status === "rejected") return false;
2494
2153
  if (state === "complete") return true;
2495
- if (state === "failed" || state === "stopped" || state === "rejected") return false;
2154
+ if (state === "failed" || state === "partial" || state === "stopped" || state === "rejected") return false;
2496
2155
  return undefined;
2497
2156
  };
2498
2157
  const writeRecoverableStatusResult = (): void => {
2499
2158
  const state = statusResultState();
2500
2159
  if (!state || finalResultCommitted || !config.sessionId) return;
2160
+ if ((state as string) === "complete") return;
2501
2161
  const now = statusPayload.endedAt ?? statusPayload.lastUpdate ?? Date.now();
2502
2162
  const summary = statusResultSummary(state);
2503
2163
  runPersistence.write(resultPath, omitUndefinedProperties({
@@ -2509,17 +2169,21 @@ async function runSubagent(
2509
2169
  success: state === "complete",
2510
2170
  state,
2511
2171
  summary,
2512
- error: state === "failed" || state === "stopped" || state === "rejected" ? summary : undefined,
2172
+ error: state === "failed" || state === "partial" || state === "stopped" || state === "rejected" ? summary : undefined,
2513
2173
  stopped: state === "stopped" ? true : undefined,
2514
2174
  results: statusPayload.steps.map((step) => omitUndefinedProperties({
2515
2175
  agent: step.agent,
2176
+ ...(step.sessionName ? { sessionName: step.sessionName } : {}),
2516
2177
  output: step.status === "complete" || step.status === "completed" ? "" : step.error ?? summary,
2517
2178
  error: step.error,
2518
2179
  success: statusResultSuccess(state, step),
2519
2180
  sessionFile: step.sessionFile,
2520
2181
  model: step.model,
2182
+ thinking: step.thinking,
2521
2183
  attemptedModels: step.attemptedModels,
2522
2184
  modelAttempts: step.modelAttempts,
2185
+ usage: usageFromAttempts(step.modelAttempts),
2186
+ contextOverflow: step.contextOverflow,
2523
2187
  })),
2524
2188
  exitCode: state === "complete" || state === "paused" ? 0 : 1,
2525
2189
  timestamp: now,
@@ -2555,6 +2219,83 @@ async function runSubagent(
2555
2219
  statusPayload.lastUpdate = Date.now();
2556
2220
  writeStatusPayload();
2557
2221
  };
2222
+ const childStopTargetId = (index: number): string => asyncStatusChildIdentity(requiredStatusStep(statusPayload, index), index);
2223
+ const appendChildStatusEvent = (index: number, childId: string, status: "stopping" | "stopped", now = Date.now()): void => {
2224
+ const step = requiredStatusStep(statusPayload, index);
2225
+ appendJsonl(eventsPath, JSON.stringify({
2226
+ type: "subagent.child-status",
2227
+ version: 1,
2228
+ ts: now,
2229
+ runId: id,
2230
+ childId,
2231
+ status,
2232
+ reason: "user",
2233
+ source: "async",
2234
+ stepIndex: index,
2235
+ agent: step.agent,
2236
+ ...(step.runId ? { childRunId: step.runId } : {}),
2237
+ ...(step.workflowKey ? { workflowKey: step.workflowKey } : {}),
2238
+ ...(step.phase ? { phase: step.phase } : {}),
2239
+ ...(step.label ? { label: step.label } : {}),
2240
+ } satisfies SubagentChildStatusEvent));
2241
+ };
2242
+ const appendTerminalChildStatusEvent = (index: number, now = Date.now()): void => {
2243
+ const request = childStopRequests.get(index);
2244
+ if (request) appendChildStatusEvent(index, request.childId, "stopped", now);
2245
+ };
2246
+ const markChildStopRequested = (index: number, childId: string, now = Date.now()): boolean => {
2247
+ const step = statusPayload.steps[index];
2248
+ if (!step || (step.status !== "pending" && step.status !== "running")) return false;
2249
+ childStopRequests.set(index, { childId, requestedAt: now });
2250
+ step.stopRequested = true;
2251
+ step.stopRequestedAt = now;
2252
+ delete step.activityState;
2253
+ statusPayload.lastUpdate = now;
2254
+ writeStatusPayload();
2255
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.step.stop_requested", ts: now, runId: id, stepIndex: index, childId, agent: step.agent }));
2256
+ appendChildStatusEvent(index, childId, "stopping", now);
2257
+ return true;
2258
+ };
2259
+ const markChildStopped = (index: number, now = Date.now()): void => {
2260
+ const step = requiredStatusStep(statusPayload, index);
2261
+ if (step.status === "stopped") return;
2262
+ step.status = "stopped";
2263
+ step.error = stopMessage;
2264
+ step.exitCode = 1;
2265
+ step.stopped = true;
2266
+ step.stopRequested = true;
2267
+ step.stopRequestedAt = childStopRequests.get(index)?.requestedAt ?? step.stopRequestedAt ?? now;
2268
+ delete step.activityState;
2269
+ step.endedAt = now;
2270
+ step.durationMs = step.startedAt ? now - step.startedAt : 0;
2271
+ step.lastActivityAt = now;
2272
+ statusPayload.lastUpdate = now;
2273
+ writeStatusPayload();
2274
+ const childId = childStopRequests.get(index)?.childId ?? childStopTargetId(index);
2275
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.step.stopped", ts: now, runId: id, stepIndex: index, childId, agent: step.agent, exitCode: 1, durationMs: step.durationMs }));
2276
+ appendChildStatusEvent(index, childId, "stopped", now);
2277
+ };
2278
+ const childStopResult = (index: number, agent: string, context?: "fresh" | "fork"): SingleStepResult => {
2279
+ markChildStopped(index);
2280
+ return stoppedStepResult(agent, context, requiredStatusStep(statusPayload, index).sessionName);
2281
+ };
2282
+ const stopChildStep = (request: StopRequest): void => {
2283
+ if (request.targetIndex === undefined) {
2284
+ stopRunner();
2285
+ return;
2286
+ }
2287
+ const childId = request.childId ?? childStopTargetId(request.targetIndex);
2288
+ const now = Date.now();
2289
+ if (!markChildStopRequested(request.targetIndex, childId, now)) {
2290
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.step.stop_failed", ts: now, runId: id, stepIndex: request.targetIndex, childId, message: "Child is not pending or running." }));
2291
+ return;
2292
+ }
2293
+ const stop = activeChildStops.get(request.targetIndex);
2294
+ if (stop) stop();
2295
+ else if (requiredStatusStep(statusPayload, request.targetIndex).status === "pending") {
2296
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.step.stop_queued", ts: now, runId: id, stepIndex: request.targetIndex, childId }));
2297
+ }
2298
+ };
2558
2299
  const registerStepInterrupt = (flatIndex: number, interrupt: (() => void) | undefined): void => {
2559
2300
  if (!interrupt) {
2560
2301
  activeChildInterrupts.delete(flatIndex);
@@ -2577,14 +2318,17 @@ async function runSubagent(
2577
2318
  return;
2578
2319
  }
2579
2320
  activeChildStops.set(flatIndex, stop);
2580
- if (stopped) stop();
2321
+ if (stopped || childStopRequests.has(flatIndex)) stop();
2581
2322
  };
2582
- const registerStepTurnBudgetAbort = (flatIndex: number, abort: ((message: string, state?: TurnBudgetState) => void) | undefined): void => {
2583
- if (!abort) {
2584
- activeChildTurnBudgetAborts.delete(flatIndex);
2323
+ const registerStepSteer = (flatIndex: number, steer: StepSteerHandler | undefined): void => {
2324
+ if (!steer) {
2325
+ activeChildSteers.delete(flatIndex);
2585
2326
  return;
2586
2327
  }
2587
- activeChildTurnBudgetAborts.set(flatIndex, abort);
2328
+ activeChildSteers.set(flatIndex, steer);
2329
+ const queued = queuedStepSteers.get(flatIndex);
2330
+ queuedStepSteers.delete(flatIndex);
2331
+ for (const request of queued ?? []) steerLiveChild(flatIndex, request);
2588
2332
  };
2589
2333
  const interruptActiveChildren = (): void => {
2590
2334
  for (const interrupt of [...activeChildInterrupts.values()]) interrupt();
@@ -2695,23 +2439,26 @@ async function runSubagent(
2695
2439
  }
2696
2440
  }
2697
2441
  };
2698
- const pausedStepResult = (agent: string, context?: "fresh" | "fork"): SingleStepResult => omitUndefinedProperties({
2442
+ const pausedStepResult = (agent: string, context?: "fresh" | "fork", sessionName?: string): SingleStepResult => omitUndefinedProperties({
2699
2443
  agent,
2444
+ sessionName,
2700
2445
  context,
2701
2446
  output: "Paused after interrupt. Waiting for explicit next action.",
2702
2447
  exitCode: 0,
2703
2448
  interrupted: true,
2704
2449
  });
2705
- const timedOutStepResult = (agent: string, context?: "fresh" | "fork"): SingleStepResult => omitUndefinedProperties({
2450
+ const timedOutStepResult = (agent: string, context?: "fresh" | "fork", sessionName?: string): SingleStepResult => omitUndefinedProperties({
2706
2451
  agent,
2452
+ sessionName,
2707
2453
  context,
2708
2454
  output: timeoutMessage ?? "Subagent timed out.",
2709
2455
  error: timeoutMessage ?? "Subagent timed out.",
2710
2456
  exitCode: 1,
2711
2457
  timedOut: true,
2712
2458
  });
2713
- const stoppedStepResult = (agent: string, context?: "fresh" | "fork"): SingleStepResult => omitUndefinedProperties({
2459
+ const stoppedStepResult = (agent: string, context?: "fresh" | "fork", sessionName?: string): SingleStepResult => omitUndefinedProperties({
2714
2460
  agent,
2461
+ sessionName,
2715
2462
  context,
2716
2463
  output: stopMessage,
2717
2464
  error: stopMessage,
@@ -3035,22 +2782,15 @@ async function runSubagent(
3035
2782
  if (!step) return { index, state: "failed" as const, reason: "child index out of range" };
3036
2783
  if (step.status === "pending") return { index, state: "scheduled" as const };
3037
2784
  if (step.status !== "running") return { index, state: "failed" as const, reason: `child is ${step.status}` };
3038
- if (steeringCapabilities.get(index)?.supported === false) return { index, state: "failed" as const, reason: "child Pi session does not support steering" };
3039
2785
  return { index, state: "routed" as const };
3040
2786
  });
3041
2787
  recordSteeringLifecycle(request, targetStates);
3042
2788
  emitSteeringEvent("subagent.steer.requested", request, undefined, { targets: targetStates });
3043
2789
  for (const target of targetStates) {
3044
2790
  if (target.state === "routed") {
3045
- try {
3046
- enqueueStepSteer(asyncDir, target.index, request);
3047
- updateSteeringLifecycleTarget(request.id, target.index, "routed", now);
3048
- emitSteeringEvent("subagent.steer.routed", request, target.index);
3049
- } catch (error) {
3050
- markSteeringAttention(target.index);
3051
- updateSteeringLifecycleTarget(request.id, target.index, "failed", now, { reason: error instanceof Error ? error.message : String(error) });
3052
- emitSteeringEvent("subagent.steer.failed", request, target.index, { reason: error instanceof Error ? error.message : String(error) });
3053
- }
2791
+ updateSteeringLifecycleTarget(request.id, target.index, "routed", now);
2792
+ emitSteeringEvent("subagent.steer.routed", request, target.index);
2793
+ steerLiveChild(target.index, request);
3054
2794
  } else if (target.state === "failed") {
3055
2795
  markSteeringAttention(target.index);
3056
2796
  emitSteeringEvent("subagent.steer.failed", request, target.index, { reason: target.reason });
@@ -3062,27 +2802,42 @@ async function runSubagent(
3062
2802
  statusPayload.lastUpdate = now;
3063
2803
  writeStatusPayload();
3064
2804
  };
3065
- const consumeSteerAck = (ack: SteerAck): void => {
2805
+ /** Record the outcome of handing a routed steer to the live child session. */
2806
+ const applySteerDelivery = (requestId: string, index: number, delivery: { state: "delivered" | "queued" | "failed"; message: string }): void => {
3066
2807
  const lifecycle = steeringStatus(statusPayload);
3067
- const request = lifecycle.recent.find((candidate) => candidate.id === ack.requestId);
3068
- if (!request || !request.targets.some((target) => target.index === ack.index)) return;
3069
- const late = fs.existsSync(steeringMarkerPath(ack.requestId));
2808
+ const request = lifecycle.recent.find((candidate) => candidate.id === requestId);
2809
+ if (!request || !request.targets.some((target) => target.index === index)) return;
2810
+ const late = fs.existsSync(steeringMarkerPath(requestId));
3070
2811
  const now = Date.now();
3071
- if (ack.state === "delivered") {
3072
- updateSteeringLifecycleTarget(ack.requestId, ack.index, late ? "late" : "delivered", now, omitUndefinedProperties({ reason: late ? "acknowledged after recovery commit" : undefined }));
3073
- emitSteeringEvent("subagent.steer.delivered", { type: "steer", id: ack.requestId, ts: now, message: ack.message }, ack.index, { late, deliveryStatus: "delivered", message: ack.message });
3074
- } else if (ack.state === "queued") {
3075
- updateSteeringLifecycleTarget(ack.requestId, ack.index, "queued", now);
3076
- emitSteeringEvent("subagent.steer.queued", { type: "steer", id: ack.requestId, ts: now, message: ack.message }, ack.index, { deliveryStatus: "queued", message: ack.message });
2812
+ if (delivery.state === "delivered") {
2813
+ updateSteeringLifecycleTarget(requestId, index, late ? "late" : "delivered", now, omitUndefinedProperties({ reason: late ? "acknowledged after recovery commit" : undefined }));
2814
+ emitSteeringEvent("subagent.steer.delivered", { type: "steer", id: requestId, ts: now, message: delivery.message }, index, { late, deliveryStatus: "delivered", message: delivery.message });
2815
+ } else if (delivery.state === "queued") {
2816
+ updateSteeringLifecycleTarget(requestId, index, "queued", now);
2817
+ emitSteeringEvent("subagent.steer.queued", { type: "steer", id: requestId, ts: now, message: delivery.message }, index, { deliveryStatus: "queued", message: delivery.message });
3077
2818
  } else {
3078
- markSteeringAttention(ack.index);
3079
- updateSteeringLifecycleTarget(ack.requestId, ack.index, "failed", now, { reason: ack.message });
3080
- emitSteeringEvent("subagent.steer.failed", { type: "steer", id: ack.requestId, ts: now, message: ack.message }, ack.index, { reason: ack.message });
2819
+ markSteeringAttention(index);
2820
+ updateSteeringLifecycleTarget(requestId, index, "failed", now, { reason: delivery.message });
2821
+ emitSteeringEvent("subagent.steer.failed", { type: "steer", id: requestId, ts: now, message: delivery.message }, index, { reason: delivery.message });
3081
2822
  }
3082
- emitTerminalSteeringNotice(ack.requestId, `Steering failed for run ${id}: ${ack.message}`);
2823
+ emitTerminalSteeringNotice(requestId, `Steering failed for run ${id}: ${delivery.message}`);
3083
2824
  statusPayload.lastUpdate = now;
3084
2825
  writeStatusPayload();
3085
2826
  };
2827
+ /** Hand a routed steer to the step's live session, or hold it until the session exists. */
2828
+ const steerLiveChild = (index: number, request: SteerRequest): void => {
2829
+ const steer = activeChildSteers.get(index);
2830
+ if (!steer) {
2831
+ const queued = queuedStepSteers.get(index) ?? [];
2832
+ queued.push(request);
2833
+ queuedStepSteers.set(index, queued);
2834
+ return;
2835
+ }
2836
+ void steer(request).then(
2837
+ (delivery) => applySteerDelivery(request.id, index, delivery),
2838
+ (error) => applySteerDelivery(request.id, index, { state: "failed", message: error instanceof Error ? error.message : String(error) }),
2839
+ );
2840
+ };
3086
2841
  const flushPendingStepSteers = (flatIndex: number): void => {
3087
2842
  const remaining: SteerRequest[] = [];
3088
2843
  for (const request of pendingStepSteers.splice(0)) {
@@ -3092,74 +2847,15 @@ async function runSubagent(
3092
2847
  }
3093
2848
  pendingStepSteers.push(...remaining);
3094
2849
  };
3095
- const updateStepModel = (flatIndex: number, model: string | undefined, thinking: string | undefined, now = Date.now()): void => {
2850
+ const updateStepModel = (flatIndex: number, model: string | undefined, thinking: string | undefined, contextLimit?: number, now = Date.now()): void => {
3096
2851
  const step = statusPayload.steps[flatIndex];
3097
2852
  if (!step) return;
3098
2853
  setOptionalProperty(step, "model", model);
3099
2854
  setOptionalProperty(step, "thinking", thinking);
2855
+ setOptionalProperty(step, "contextLimit", contextLimit);
3100
2856
  statusPayload.lastUpdate = now;
3101
2857
  writeStatusPayload();
3102
2858
  };
3103
- const updateStepTurnBudget = (
3104
- flatIndex: number,
3105
- turnCount: number,
3106
- now: number,
3107
- terminalAssistantStop: boolean,
3108
- toolWorkActiveOrStarting: boolean,
3109
- ): void => {
3110
- const budget = config.turnBudget;
3111
- const step = statusPayload.steps[flatIndex];
3112
- if (!budget || !step || timedOut || stopped || turnBudgetExceeded || step.turnBudgetExceeded) return;
3113
- if (turnCount < budget.maxTurns) {
3114
- const state: TurnBudgetState = { ...budget, outcome: "within-budget", turnCount };
3115
- step.turnBudget = state;
3116
- statusPayload.turnBudget = state;
3117
- return;
3118
- }
3119
- if (!step.wrapUpRequested) {
3120
- step.wrapUpRequested = true;
3121
- statusPayload.wrapUpRequested = true;
3122
- appendRecentStepOutput(step, [turnBudgetSoftNote(budget, turnCount)]);
3123
- }
3124
- const decision = turnBudgetDecision(budget, turnCount, terminalAssistantStop, toolWorkActiveOrStarting);
3125
- if (decision === "defer") {
3126
- const firstDeferredTurn = step.turnBudget?.terminationDeferredAtTurn;
3127
- const deferredState = turnBudgetDeferredState(budget, turnCount, firstDeferredTurn);
3128
- step.turnBudget = deferredState;
3129
- statusPayload.turnBudget = deferredState;
3130
- if (firstDeferredTurn === undefined) {
3131
- appendJsonl(eventsPath, JSON.stringify({
3132
- type: "subagent.step.turn_budget_deferred",
3133
- ts: now,
3134
- runId: id,
3135
- stepIndex: flatIndex,
3136
- agent: step.agent,
3137
- turnCount,
3138
- maxTurns: budget.maxTurns,
3139
- graceTurns: budget.graceTurns,
3140
- }));
3141
- }
3142
- return;
3143
- }
3144
- const state = turnBudgetState(budget, turnCount, false);
3145
- step.turnBudget = state;
3146
- statusPayload.turnBudget = state;
3147
- if (decision !== "abort") return;
3148
- const exceededState = turnBudgetState(budget, turnCount, true);
3149
- const message = turnBudgetExceededMessage(budget, turnCount);
3150
- step.turnBudget = exceededState;
3151
- step.turnBudgetExceeded = true;
3152
- step.wrapUpRequested = true;
3153
- step.error = message;
3154
- turnBudgetExceeded = true;
3155
- statusPayload.turnBudget = exceededState;
3156
- statusPayload.turnBudgetExceeded = true;
3157
- statusPayload.wrapUpRequested = true;
3158
- statusPayload.error = message;
3159
- statusPayload.lastUpdate = now;
3160
- 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 }));
3161
- activeChildTurnBudgetAborts.get(flatIndex)?.(message, exceededState);
3162
- };
3163
2859
  const updateStepFromChildEvent = (flatIndex: number, event: ChildEvent): void => {
3164
2860
  const step = statusPayload.steps[flatIndex];
3165
2861
  if (!step) return;
@@ -3181,8 +2877,17 @@ async function runSubagent(
3181
2877
  writeStatusPayload(false);
3182
2878
  return;
3183
2879
  }
2880
+ if (event.type === "message_end") {
2881
+ const next = applyChildWatchdogMessage(step.watchdog, event.message, now);
2882
+ if (next) step.watchdog = next;
2883
+ if (next && (event.message as { role?: unknown } | undefined)?.role === "custom") {
2884
+ statusPayload.lastUpdate = now;
2885
+ writeStatusPayload(false);
2886
+ return;
2887
+ }
2888
+ }
3184
2889
  if (event.type === "tool_execution_start" && event.toolName) {
3185
- const mutates = isMutatingTool(event.toolName, event.args);
2890
+ const mutates = isMutatingTool(event.toolName, event.args, flatSteps[flatIndex]?.mutationTools);
3186
2891
  const currentPath = resolveCurrentPath(event.toolName, event.args);
3187
2892
  const argsPreview = extractToolArgsPreview(event.args ?? {});
3188
2893
  const blocksSupervisor = isBlockingSupervisorTool(event.toolName, event.args);
@@ -3216,6 +2921,7 @@ async function runSubagent(
3216
2921
  tokens: step.tokens?.total,
3217
2922
  toolCount: step.toolCount,
3218
2923
  currentTool: step.currentTool,
2924
+ toolCallId: event.toolCallId,
3219
2925
  currentToolDurationMs: 0,
3220
2926
  currentPath: step.currentPath,
3221
2927
  })));
@@ -3290,22 +2996,16 @@ async function runSubagent(
3290
2996
  if (usage) {
3291
2997
  const input = usage.input ?? usage.inputTokens ?? 0;
3292
2998
  const output = usage.output ?? usage.outputTokens ?? 0;
2999
+ const window = input + (usage.cacheRead ?? usage.cacheReadTokens ?? 0);
3293
3000
  const previousInput = step.tokens?.input ?? 0;
3294
3001
  const previousOutput = step.tokens?.output ?? 0;
3295
- step.tokens = { input: previousInput + input, output: previousOutput + output, total: previousInput + previousOutput + input + output };
3002
+ step.tokens = { input: previousInput + input, output: previousOutput + output, total: previousInput + previousOutput + input + output, window, windowPeak: Math.max(step.tokens?.windowPeak ?? 0, window) };
3296
3003
  const totalInput = statusPayload.totalTokens?.input ?? 0;
3297
3004
  const totalOutput = statusPayload.totalTokens?.output ?? 0;
3298
- statusPayload.totalTokens = { input: totalInput + input, output: totalOutput + output, total: totalInput + totalOutput + input + output };
3005
+ statusPayload.totalTokens = { input: totalInput + input, output: totalOutput + output, total: totalInput + totalOutput + input + output, window, windowPeak: Math.max(statusPayload.totalTokens?.windowPeak ?? 0, window) };
3299
3006
  refreshUsageBudget();
3300
3007
  }
3301
3008
  statusPayload.turnCount = Math.max(statusPayload.turnCount ?? 0, step.turnCount);
3302
- updateStepTurnBudget(
3303
- flatIndex,
3304
- step.turnCount,
3305
- now,
3306
- isTerminalAssistantStop(event.message),
3307
- assistantStartsToolCall(event.message) || Boolean(step.currentTool),
3308
- );
3309
3009
  }
3310
3010
  syncTopLevelCurrentTool();
3311
3011
  step.lastActivityAt = now;
@@ -3331,6 +3031,7 @@ async function runSubagent(
3331
3031
  config: controlConfig,
3332
3032
  startedAt: step.startedAt ?? overallStartTime,
3333
3033
  lastActivityAt,
3034
+ turnCount: step.turnCount,
3334
3035
  currentTool: step.currentTool,
3335
3036
  thinking: step.thinking,
3336
3037
  now,
@@ -3482,7 +3183,7 @@ async function runSubagent(
3482
3183
  const disposeControlInbox = watchAsyncControlInbox(asyncDir, {
3483
3184
  onInterrupt: interruptRunner,
3484
3185
  onTimeout: timeoutRunner,
3485
- onStop: stopRunner,
3186
+ onStop: stopChildStep,
3486
3187
  onSteer: (request) => {
3487
3188
  const targetStep = request.targetIndex !== undefined ? statusPayload.steps[request.targetIndex] : undefined;
3488
3189
  if (targetStep?.status === "pending") {
@@ -3495,23 +3196,6 @@ async function runSubagent(
3495
3196
  pendingStepSteers.push(request);
3496
3197
  }
3497
3198
  },
3498
- onSteerCapability: (capability) => {
3499
- steeringCapabilities.set(capability.index, capability);
3500
- if (!capability.supported) {
3501
- const now = Date.now();
3502
- const lifecycle = steeringStatus(statusPayload);
3503
- for (const request of lifecycle.recent) {
3504
- if (!request.targets.some((target) => target.index === capability.index && (target.state === "routed" || target.state === "scheduled"))) continue;
3505
- markSteeringAttention(capability.index);
3506
- updateSteeringLifecycleTarget(request.id, capability.index, "failed", now, { reason: "child Pi session does not support steering" });
3507
- 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" });
3508
- emitTerminalSteeringNotice(request.id, `Steering failed for run ${id}: child ${capability.index} does not support steering.`);
3509
- }
3510
- statusPayload.lastUpdate = now;
3511
- writeStatusPayload();
3512
- }
3513
- },
3514
- onSteerAck: consumeSteerAck,
3515
3199
  });
3516
3200
  if (config.deadlineAt !== undefined) {
3517
3201
  const remainingMs = Math.max(0, config.deadlineAt - Date.now());
@@ -3534,7 +3218,7 @@ async function runSubagent(
3534
3218
  let flatIndex = 0;
3535
3219
  let stepCursor = 0;
3536
3220
  while (true) {
3537
- if (interrupted || timedOut || stopped || turnBudgetExceeded) break;
3221
+ if (interrupted || timedOut || stopped) break;
3538
3222
  consumePendingAppendRequests();
3539
3223
  if (stepCursor >= steps.length) break;
3540
3224
  refreshUsageBudget();
@@ -3558,6 +3242,19 @@ async function runSubagent(
3558
3242
  if (materialized.parallel.length > 1 && step.parallel.outputPath && !step.parallel.namespaceOutputPath) {
3559
3243
  throw new DynamicFanoutError(`Dynamic chain step ${stepIndex + 1} materialized ${materialized.parallel.length} items that resolve output to the same path: ${step.parallel.outputPath}. Remove the explicit output path or use an inherited relative agent output so each item can be isolated.`);
3560
3244
  }
3245
+ for (const [itemIndex] of materialized.parallel.entries()) {
3246
+ const thinkingOverride = step.thinkingOverrides?.[itemIndex];
3247
+ const model = thinkingOverride ? applyThinkingSuffix(step.parallel.model, thinkingOverride, true) : step.parallel.model;
3248
+ const configThinking = thinkingOverride ? thinkingOverride : step.parallel.thinking;
3249
+ const candidates = step.parallel.modelCandidates !== undefined
3250
+ ? step.parallel.modelCandidates.length > 0
3251
+ ? step.parallel.modelCandidates.map((candidate) => thinkingOverride ? applyThinkingSuffix(candidate, thinkingOverride, true) ?? candidate : candidate)
3252
+ : [undefined]
3253
+ : model ? [model] : [undefined];
3254
+ for (const candidate of candidates) {
3255
+ assertThinkingWithinCeiling({ model: candidate, configThinking, ceiling: step.parallel.thinkingCeiling, agent: step.parallel.agent, runId: id });
3256
+ }
3257
+ }
3561
3258
  if (materialized.collectedOnEmpty) await validateDynamicCollection(step.collect.outputSchema, materialized.collectedOnEmpty);
3562
3259
  if (!config.runFanoutBudget) throw new Error("Async runner is missing its run fan-out budget identity.");
3563
3260
  const runFanoutBudget = claimRunFanoutBatch(config.runFanoutBudget, materialized.parallel.map((_, itemIndex) => `chain[${stepIndex}].expand[${itemIndex}]`));
@@ -3666,10 +3363,12 @@ async function runSubagent(
3666
3363
  : step.parallel.outputPath;
3667
3364
  const taskText = task.task ?? step.parallel.task;
3668
3365
  const materializedTask = step.parallel.namespaceOutputPath ? injectSingleOutputInstruction(taskText, outputPath, step.parallel) : taskText;
3366
+ const sessionName = deriveChildSessionName({ agent: step.parallel.agent, task: taskText, label: task.label ?? step.parallel.label });
3669
3367
  return omitUndefinedProperties({
3670
3368
  ...step.parallel,
3671
3369
  runFanoutPath: `chain[${stepIndex}].expand[${itemIndex}]`,
3672
3370
  task: materializedTask,
3371
+ ...(sessionName ? { sessionName } : {}),
3673
3372
  effectiveAcceptance: resolveEffectiveAcceptance(omitUndefinedProperties({
3674
3373
  explicit: step.parallel.acceptanceInput,
3675
3374
  agentName: step.parallel.agent,
@@ -3700,6 +3399,7 @@ async function runSubagent(
3700
3399
  const transcriptPath = resolveAsyncStepTranscriptPath(omitUndefinedProperties({ artifactsDir, artifactConfig, runId: id, agent: task.agent, flatIndex: groupStartFlatIndex + itemIndex, flatStepCount: dynamicFlatStepCount }));
3701
3400
  return omitUndefinedProperties({
3702
3401
  agent: task.agent,
3402
+ ...(task.sessionName ? { sessionName: task.sessionName } : {}),
3703
3403
  ...(statusStepDescription(task.task) ? { description: statusStepDescription(task.task) } : {}),
3704
3404
  ...(task.context ? { context: task.context } : {}),
3705
3405
  ...(task.phase ?? step.phase ? { phase: task.phase ?? step.phase } : {}),
@@ -3713,7 +3413,9 @@ async function runSubagent(
3713
3413
  ...(transcriptPath ? { transcriptPath } : {}),
3714
3414
  ...(task.skills ? { skills: task.skills } : {}),
3715
3415
  ...(task.model ? { model: task.model } : {}),
3416
+ ...(task.contextLimit !== undefined ? { contextLimit: task.contextLimit } : {}),
3716
3417
  ...(task.thinking ? { thinking: task.thinking } : {}),
3418
+ ...(task.thinkingCeiling ? { thinkingCeiling: task.thinkingCeiling } : {}),
3717
3419
  ...(task.modelCandidates && task.modelCandidates.length > 0 ? { attemptedModels: task.modelCandidates } : task.model ? { attemptedModels: [task.model] } : {}),
3718
3420
  recentTools: [],
3719
3421
  recentOutput: [],
@@ -3781,11 +3483,12 @@ async function runSubagent(
3781
3483
  usageBudgetExceeded = true;
3782
3484
  writeStatusPayload();
3783
3485
  appendJsonl(eventsPath, JSON.stringify({ type: "subagent.step.failed", ts: skippedAt, runId: id, stepIndex: fi, agent: task.agent, exitCode: 1, durationMs: 0 }));
3784
- return omitUndefinedProperties({ agent: task.agent, context: task.context, output: message, error: message, exitCode: 1 as number | null, skipped: true });
3486
+ return omitUndefinedProperties({ agent: task.agent, ...(task.sessionName ? { sessionName: task.sessionName } : {}), context: task.context, output: message, error: message, exitCode: 1 as number | null, skipped: true });
3785
3487
  }
3786
- if (timedOut) return timedOutStepResult(task.agent, task.context);
3787
- if (stopped) return stoppedStepResult(task.agent, task.context);
3788
- if (interrupted) return pausedStepResult(task.agent, task.context);
3488
+ if (timedOut) return timedOutStepResult(task.agent, task.context, task.sessionName);
3489
+ if (stopped) return stoppedStepResult(task.agent, task.context, task.sessionName);
3490
+ if (childStopRequests.has(fi)) return childStopResult(fi, task.agent, task.context);
3491
+ if (interrupted) return pausedStepResult(task.agent, task.context, task.sessionName);
3789
3492
  if (aborted && failFast) {
3790
3493
  const skippedAt = Date.now();
3791
3494
  requiredStatusStep(statusPayload, fi).status = "failed";
@@ -3796,7 +3499,7 @@ async function runSubagent(
3796
3499
  requiredStatusStep(statusPayload, fi).exitCode = -1;
3797
3500
  statusPayload.lastUpdate = skippedAt;
3798
3501
  writeStatusPayload();
3799
- return omitUndefinedProperties({ agent: task.agent, context: task.context, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true });
3502
+ return omitUndefinedProperties({ agent: task.agent, ...(task.sessionName ? { sessionName: task.sessionName } : {}), context: task.context, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true });
3800
3503
  }
3801
3504
  const taskStartTime = Date.now();
3802
3505
  statusPayload.currentStep = fi;
@@ -3819,11 +3522,9 @@ async function runSubagent(
3819
3522
  artifactsDir, artifactConfig, id,
3820
3523
  flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
3821
3524
  outputFile: path.join(asyncDir, `output-${fi}.log`),
3822
- steerInboxDir: stepSteerInboxDir(asyncDir, fi),
3823
- steerCapabilityPath: steerCapabilityPath(asyncDir, fi),
3824
- steerAckDir: steerAcksDir(asyncDir, fi),
3825
3525
  piPackageRoot: config.piPackageRoot,
3826
- piArgv1: config.piArgv1,
3526
+ childSessions,
3527
+ inheritedChildRuntime: config.inheritedChildRuntime,
3827
3528
  childIntercomTarget: config.childIntercomTargets?.[fi],
3828
3529
  orchestratorIntercomTarget: config.controlIntercomTarget,
3829
3530
  nestedRoute: config.nestedRoute,
@@ -3832,19 +3533,20 @@ async function runSubagent(
3832
3533
  registerInterrupt: (interrupt) => registerStepInterrupt(fi, interrupt),
3833
3534
  registerTimeout: (interrupt) => registerStepTimeout(fi, interrupt),
3834
3535
  registerStop: (stop) => registerStepStop(fi, stop),
3835
- registerTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(fi, abort),
3536
+ registerSteer: (steer) => registerStepSteer(fi, steer),
3836
3537
  timeoutSignal: timeoutAbortController.signal,
3837
3538
  stopSignal: stopAbortController.signal,
3539
+ trackedMutationEvidenceForCompletionGuard: false,
3838
3540
  timeoutMessage,
3839
3541
  stopMessage,
3840
- turnBudget: config.turnBudget,
3841
3542
  toolTimeoutMs: task.toolTimeoutMs ?? config.toolTimeoutMs,
3842
- onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking),
3543
+ onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking, attempt.contextLimit),
3843
3544
  onChildEvent: (event) => updateStepFromChildEvent(fi, event),
3844
- onWriterProcess,
3845
3545
  onExternalProcess: (process) => updateExternalProcess(fi, process),
3846
3546
  onExternalJob: (externalJob) => updateExternalJob(fi, externalJob),
3847
- skipAcceptance: () => timedOut || stopped,
3547
+ skipAcceptance: () => timedOut || stopped || childStopRequests.has(fi),
3548
+ usageBudgetExhausted: () => refreshUsageBudget()?.exhausted === true,
3549
+ orcaProgressTab,
3848
3550
  }), config.deadlineAt);
3849
3551
  const taskEndTime = Date.now();
3850
3552
  const childInterrupted = singleResult.interrupted === true;
@@ -3855,20 +3557,16 @@ async function runSubagent(
3855
3557
  requiredStatusStep(statusPayload, fi).exitCode = stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;
3856
3558
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "timedOut", timedOut || singleResult.timedOut ? true : undefined);
3857
3559
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "stopped", stopped || childStopped ? true : undefined);
3858
- setOptionalProperty(requiredStatusStep(statusPayload, fi), "turnBudget", singleResult.turnBudget);
3859
- setOptionalProperty(requiredStatusStep(statusPayload, fi), "turnBudgetExceeded", singleResult.turnBudgetExceeded);
3860
- setOptionalProperty(requiredStatusStep(statusPayload, fi), "wrapUpRequested", singleResult.wrapUpRequested);
3861
3560
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudget", singleResult.toolBudget);
3862
3561
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudgetBlocked", singleResult.toolBudgetBlocked);
3863
3562
  if (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;
3864
3563
  if (singleResult.toolBudgetBlocked) statusPayload.toolBudgetBlocked = true;
3865
- if (singleResult.turnBudget) statusPayload.turnBudget = singleResult.turnBudget;
3866
- if (singleResult.turnBudgetExceeded) statusPayload.turnBudgetExceeded = true;
3867
- if (singleResult.wrapUpRequested) statusPayload.wrapUpRequested = true;
3564
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "sessionName", singleResult.sessionName);
3868
3565
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "model", singleResult.model);
3869
3566
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "thinking", resolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, fi).thinking));
3870
3567
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "attemptedModels", singleResult.attemptedModels);
3871
3568
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "modelAttempts", singleResult.modelAttempts);
3569
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "contextOverflow", singleResult.contextOverflow);
3872
3570
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "totalCost", singleResult.totalCost);
3873
3571
  if (singleResult.totalCost) {
3874
3572
  pendingParallelUsageCost = {
@@ -3892,6 +3590,7 @@ async function runSubagent(
3892
3590
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "structuredOutputPath", singleResult.structuredOutputPath);
3893
3591
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "structuredOutputSchemaPath", singleResult.structuredOutputSchemaPath);
3894
3592
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "acceptance", singleResult.acceptance);
3593
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "timeoutRecovery", singleResult.timeoutRecovery);
3895
3594
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "watchdog", singleResult.watchdog);
3896
3595
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "capabilityCeiling", singleResult.capabilityCeiling);
3897
3596
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "capabilityAudit", singleResult.capabilityAudit);
@@ -3900,19 +3599,21 @@ async function runSubagent(
3900
3599
  statusPayload.lastUpdate = taskEndTime;
3901
3600
  writeStatusPayload();
3902
3601
  appendCapabilityCeilingAppliedEvent(eventsPath, id, fi, task.agent, singleResult);
3903
- appendJsonl(eventsPath, JSON.stringify({
3904
- type: stopped || childStopped ? "subagent.step.stopped" : timedOut ? "subagent.step.failed" : childInterrupted ? "subagent.step.paused" : singleResult.exitCode === 0 ? "subagent.step.completed" : "subagent.step.failed",
3905
- ts: taskEndTime, runId: id, stepIndex: fi, agent: task.agent,
3906
- exitCode: stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode, durationMs: taskEndTime - taskStartTime,
3907
- }));
3908
- if (singleResult.exitCode !== 0 && failFast) aborted = true;
3909
- return stopped || childStopped ? { ...singleResult, output: stopMessage, error: stopMessage, exitCode: 1, interrupted: false, timedOut: false, stopped: true, skipped: false } : timedOut ? { ...singleResult, output: timeoutMessage ?? "Subagent timed out.", error: timeoutMessage ?? "Subagent timed out.", exitCode: 1, interrupted: false, timedOut: true, skipped: false } : { ...singleResult, skipped: false };
3602
+ appendJsonl(eventsPath, JSON.stringify({
3603
+ type: stopped || childStopped ? "subagent.step.stopped" : timedOut ? "subagent.step.failed" : childInterrupted ? "subagent.step.paused" : singleResult.exitCode === 0 ? "subagent.step.completed" : "subagent.step.failed",
3604
+ ts: taskEndTime, runId: id, stepIndex: fi, agent: task.agent,
3605
+ exitCode: stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode, durationMs: taskEndTime - taskStartTime,
3606
+ }));
3607
+ if (stopped || childStopped) appendTerminalChildStatusEvent(fi, taskEndTime);
3608
+ if (singleResult.exitCode !== 0 && failFast && !childStopped) aborted = true;
3609
+ return stopped || childStopped ? { ...singleResult, output: stopMessage, error: stopMessage, exitCode: 1, interrupted: false, timedOut: false, stopped: true, skipped: false } : timedOut ? { ...singleResult, output: singleResult.output || (timeoutMessage ?? "Subagent timed out."), error: singleResult.error ?? timeoutMessage ?? "Subagent timed out.", exitCode: 1, interrupted: false, timedOut: true, skipped: false } : { ...singleResult, skipped: false };
3910
3610
  }, globalSemaphore);
3911
3611
 
3912
3612
  flatIndex += dynamicSteps.length;
3913
3613
  for (const pr of parallelResults) {
3914
3614
  results.push(omitUndefinedProperties({
3915
3615
  agent: pr.agent,
3616
+ ...(pr.sessionName ? { sessionName: pr.sessionName } : {}),
3916
3617
  context: pr.context,
3917
3618
  agentContract: pr.agentContract,
3918
3619
  launchContractDigest: pr.launchContractDigest,
@@ -3921,30 +3622,30 @@ async function runSubagent(
3921
3622
  output: pr.output,
3922
3623
  outputState: pr.outputState,
3923
3624
  error: pr.error,
3924
- protocolError: pr.protocolError,
3925
3625
  success: pr.stopped !== true && pr.interrupted !== true && pr.exitCode === 0,
3926
3626
  exitCode: pr.interrupted === true ? 0 : pr.exitCode,
3927
3627
  skipped: pr.skipped,
3928
3628
  interrupted: pr.interrupted,
3929
3629
  timedOut: pr.timedOut,
3930
3630
  stopped: pr.stopped,
3931
- turnBudget: pr.turnBudget,
3932
- turnBudgetExceeded: pr.turnBudgetExceeded,
3933
- wrapUpRequested: pr.wrapUpRequested,
3934
3631
  toolBudget: pr.toolBudget,
3935
3632
  toolBudgetBlocked: pr.toolBudgetBlocked,
3936
3633
  sessionFile: pr.sessionFile,
3937
3634
  intercomTarget: pr.intercomTarget,
3938
3635
  model: pr.model,
3636
+ thinking: pr.thinking,
3939
3637
  attemptedModels: pr.attemptedModels,
3940
3638
  modelAttempts: pr.modelAttempts,
3639
+ contextOverflow: pr.contextOverflow,
3941
3640
  totalCost: pr.totalCost,
3641
+ usage: pr.usage,
3942
3642
  artifactPaths: pr.artifactPaths,
3943
3643
  transcriptPath: pr.transcriptPath,
3944
3644
  transcriptError: pr.transcriptError,
3945
3645
  effects: pr.effects,
3946
3646
  execution: pr.execution,
3947
3647
  review: pr.review,
3648
+ timeoutRecovery: pr.timeoutRecovery,
3948
3649
  structuredOutput: pr.structuredOutput,
3949
3650
  structuredOutputPath: pr.structuredOutputPath,
3950
3651
  structuredOutputSchemaPath: pr.structuredOutputSchemaPath,
@@ -4077,10 +3778,32 @@ async function runSubagent(
4077
3778
  try {
4078
3779
  worktreeSetup = createWorktrees(cwd, `${id}-s${stepIndex}`, group.parallel.length, omitUndefinedProperties({
4079
3780
  agents: group.parallel.map((task) => task.agent),
3781
+ labels: group.parallel.map((task) => task.lane?.key ?? config.workflowKey ?? task.outputName ?? task.label),
3782
+ tasks: group.parallel.map((task) => task.task),
3783
+ provider: config.worktreeProvider,
3784
+ baseRef: config.baseRef,
3785
+ branchPrefix: config.worktreeBranchPrefix,
4080
3786
  setupHook: config.worktreeSetupHook
4081
3787
  ? omitUndefinedProperties({ hookPath: config.worktreeSetupHook, timeoutMs: config.worktreeSetupHookTimeoutMs })
4082
3788
  : undefined,
4083
3789
  baseDir: config.worktreeBaseDir,
3790
+ beforeCreate: (plannedSetup) => {
3791
+ for (const worktree of plannedSetup.worktrees) setStatusWorktreeReference(requiredStatusStep(statusPayload, groupStartFlatIndex + worktree.index), worktree);
3792
+ const pendingHandoff = writePendingParallelHandoff({
3793
+ manifestPath: parallelHandoffPath(asyncDir),
3794
+ runId: id,
3795
+ mode: (config.resultMode ?? statusPayload.mode) === "parallel" ? "parallel" : "chain",
3796
+ source: "async",
3797
+ cwd,
3798
+ stepIndex,
3799
+ flatStartIndex: groupStartFlatIndex,
3800
+ setup: plannedSetup,
3801
+ laneBindings: handoffWorkflowKey || config.lane ? [{ index: groupStartFlatIndex, taskIndex: 0, ...(handoffWorkflowKey ? { workflowKey: handoffWorkflowKey } : {}), ...(handoffChildRunId ? { runId: handoffChildRunId } : {}), ...(config.lane ? { lane: config.lane } : {}) }] : undefined,
3802
+ });
3803
+ statusPayload.parallelHandoff = pendingHandoff;
3804
+ statusPayload.lastUpdate = Date.now();
3805
+ writeStatusPayload();
3806
+ },
4084
3807
  }));
4085
3808
  } catch (error) {
4086
3809
  const setupError = error instanceof Error ? error.message : String(error);
@@ -4105,18 +3828,6 @@ async function runSubagent(
4105
3828
  }
4106
3829
 
4107
3830
  try {
4108
- if (worktreeSetup) {
4109
- writePendingParallelHandoff({
4110
- manifestPath: parallelHandoffPath(asyncDir),
4111
- runId: id,
4112
- mode: (config.resultMode ?? statusPayload.mode) === "parallel" ? "parallel" : "chain",
4113
- source: "async",
4114
- cwd,
4115
- stepIndex,
4116
- flatStartIndex: groupStartFlatIndex,
4117
- setup: worktreeSetup,
4118
- });
4119
- }
4120
3831
  if (group.worktree) ensureParallelProgressFile(cwd, group);
4121
3832
  const groupStartTime = Date.now();
4122
3833
  markParallelGroupRunning({
@@ -4153,11 +3864,12 @@ async function runSubagent(
4153
3864
  appendJsonl(eventsPath, JSON.stringify({
4154
3865
  type: "subagent.step.failed", ts: skippedAt, runId: id, stepIndex: fi, agent: task.agent, exitCode: 1, durationMs: 0,
4155
3866
  }));
4156
- return omitUndefinedProperties({ agent: task.agent, context: task.context, output: message, error: message, exitCode: 1 as number | null, skipped: true });
3867
+ return omitUndefinedProperties({ agent: task.agent, ...(task.sessionName ? { sessionName: task.sessionName } : {}), context: task.context, output: message, error: message, exitCode: 1 as number | null, skipped: true });
4157
3868
  }
4158
- if (timedOut) return timedOutStepResult(task.agent, task.context);
4159
- if (stopped) return stoppedStepResult(task.agent, task.context);
4160
- if (interrupted) return pausedStepResult(task.agent, task.context);
3869
+ if (timedOut) return timedOutStepResult(task.agent, task.context, task.sessionName);
3870
+ if (stopped) return stoppedStepResult(task.agent, task.context, task.sessionName);
3871
+ if (childStopRequests.has(fi)) return childStopResult(fi, task.agent, task.context);
3872
+ if (interrupted) return pausedStepResult(task.agent, task.context, task.sessionName);
4161
3873
  if (aborted && failFast) {
4162
3874
  const skippedAt = Date.now();
4163
3875
  requiredStatusStep(statusPayload, fi).status = "failed";
@@ -4172,7 +3884,7 @@ async function runSubagent(
4172
3884
  appendJsonl(eventsPath, JSON.stringify({
4173
3885
  type: "subagent.step.failed", ts: skippedAt, runId: id, stepIndex: fi, agent: task.agent, exitCode: -1, durationMs: 0,
4174
3886
  }));
4175
- return omitUndefinedProperties({ agent: task.agent, context: task.context, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true });
3887
+ return omitUndefinedProperties({ agent: task.agent, ...(task.sessionName ? { sessionName: task.sessionName } : {}), context: task.context, output: "(skipped — fail-fast)", exitCode: -1 as number | null, skipped: true });
4176
3888
  }
4177
3889
 
4178
3890
  const taskStartTime = Date.now();
@@ -4207,11 +3919,9 @@ async function runSubagent(
4207
3919
  artifactsDir, artifactConfig, id,
4208
3920
  flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
4209
3921
  outputFile: path.join(asyncDir, `output-${fi}.log`),
4210
- steerInboxDir: stepSteerInboxDir(asyncDir, fi),
4211
- steerCapabilityPath: steerCapabilityPath(asyncDir, fi),
4212
- steerAckDir: steerAcksDir(asyncDir, fi),
4213
3922
  piPackageRoot: config.piPackageRoot,
4214
- piArgv1: config.piArgv1,
3923
+ childSessions,
3924
+ inheritedChildRuntime: config.inheritedChildRuntime,
4215
3925
  childIntercomTarget: config.childIntercomTargets?.[fi],
4216
3926
  orchestratorIntercomTarget: config.controlIntercomTarget,
4217
3927
  nestedRoute: config.nestedRoute,
@@ -4220,19 +3930,20 @@ async function runSubagent(
4220
3930
  registerInterrupt: (interrupt) => registerStepInterrupt(fi, interrupt),
4221
3931
  registerTimeout: (interrupt) => registerStepTimeout(fi, interrupt),
4222
3932
  registerStop: (stop) => registerStepStop(fi, stop),
4223
- registerTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(fi, abort),
3933
+ registerSteer: (steer) => registerStepSteer(fi, steer),
4224
3934
  timeoutSignal: timeoutAbortController.signal,
4225
3935
  stopSignal: stopAbortController.signal,
3936
+ trackedMutationEvidenceForCompletionGuard: Boolean(worktreeSetup),
4226
3937
  timeoutMessage,
4227
3938
  stopMessage,
4228
- turnBudget: config.turnBudget,
4229
3939
  toolTimeoutMs: taskForRun.toolTimeoutMs ?? config.toolTimeoutMs,
4230
- onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking),
3940
+ onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking, attempt.contextLimit),
4231
3941
  onChildEvent: (event) => updateStepFromChildEvent(fi, event),
4232
- onWriterProcess,
4233
3942
  onExternalProcess: (process) => updateExternalProcess(fi, process),
4234
3943
  onExternalJob: (externalJob) => updateExternalJob(fi, externalJob),
4235
- skipAcceptance: () => timedOut || stopped,
3944
+ skipAcceptance: () => timedOut || stopped || childStopRequests.has(fi),
3945
+ usageBudgetExhausted: () => refreshUsageBudget()?.exhausted === true,
3946
+ orcaProgressTab,
4236
3947
  }), config.deadlineAt);
4237
3948
  if (task.sessionFile) {
4238
3949
  latestSessionFile = task.sessionFile;
@@ -4249,20 +3960,16 @@ async function runSubagent(
4249
3960
  requiredStatusStep(statusPayload, fi).exitCode = stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;
4250
3961
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "timedOut", timedOut || singleResult.timedOut ? true : undefined);
4251
3962
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "stopped", stopped || childStopped ? true : undefined);
4252
- setOptionalProperty(requiredStatusStep(statusPayload, fi), "turnBudget", singleResult.turnBudget);
4253
- setOptionalProperty(requiredStatusStep(statusPayload, fi), "turnBudgetExceeded", singleResult.turnBudgetExceeded);
4254
- setOptionalProperty(requiredStatusStep(statusPayload, fi), "wrapUpRequested", singleResult.wrapUpRequested);
4255
3963
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudget", singleResult.toolBudget);
4256
3964
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "toolBudgetBlocked", singleResult.toolBudgetBlocked);
4257
3965
  if (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;
4258
3966
  if (singleResult.toolBudgetBlocked) statusPayload.toolBudgetBlocked = true;
4259
- if (singleResult.turnBudget) statusPayload.turnBudget = singleResult.turnBudget;
4260
- if (singleResult.turnBudgetExceeded) statusPayload.turnBudgetExceeded = true;
4261
- if (singleResult.wrapUpRequested) statusPayload.wrapUpRequested = true;
3967
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "sessionName", singleResult.sessionName);
4262
3968
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "model", singleResult.model);
4263
3969
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "thinking", resolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, fi).thinking));
4264
3970
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "attemptedModels", singleResult.attemptedModels);
4265
3971
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "modelAttempts", singleResult.modelAttempts);
3972
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "contextOverflow", singleResult.contextOverflow);
4266
3973
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "totalCost", singleResult.totalCost);
4267
3974
  if (singleResult.totalCost) {
4268
3975
  pendingParallelUsageCost = {
@@ -4285,6 +3992,7 @@ async function runSubagent(
4285
3992
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "structuredOutputPath", singleResult.structuredOutputPath);
4286
3993
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "structuredOutputSchemaPath", singleResult.structuredOutputSchemaPath);
4287
3994
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "acceptance", singleResult.acceptance);
3995
+ setOptionalProperty(requiredStatusStep(statusPayload, fi), "timeoutRecovery", singleResult.timeoutRecovery);
4288
3996
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "watchdog", singleResult.watchdog);
4289
3997
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "capabilityCeiling", singleResult.capabilityCeiling);
4290
3998
  setOptionalProperty(requiredStatusStep(statusPayload, fi), "capabilityAudit", singleResult.capabilityAudit);
@@ -4299,6 +4007,7 @@ async function runSubagent(
4299
4007
  ts: taskEndTime, runId: id, stepIndex: fi, agent: task.agent,
4300
4008
  exitCode: stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode, durationMs: taskDuration,
4301
4009
  }));
4010
+ if (stopped || childStopped) appendTerminalChildStatusEvent(fi, taskEndTime);
4302
4011
  if (singleResult.completionGuardTriggered) {
4303
4012
  const event = buildControlEvent(omitUndefinedProperties({
4304
4013
  from: requiredStatusStep(statusPayload, fi).activityState,
@@ -4313,8 +4022,8 @@ async function runSubagent(
4313
4022
  appendControlEvent(event);
4314
4023
  }
4315
4024
 
4316
- if (singleResult.exitCode !== 0 && failFast) aborted = true;
4317
- return stopped || childStopped ? { ...singleResult, output: stopMessage, error: stopMessage, exitCode: 1, interrupted: false, timedOut: false, stopped: true, skipped: false } : timedOut ? { ...singleResult, output: timeoutMessage ?? "Subagent timed out.", error: timeoutMessage ?? "Subagent timed out.", exitCode: 1, interrupted: false, timedOut: true, skipped: false } : { ...singleResult, skipped: false };
4025
+ if (singleResult.exitCode !== 0 && failFast && !childStopped) aborted = true;
4026
+ return stopped || childStopped ? { ...singleResult, output: stopMessage, error: stopMessage, exitCode: 1, interrupted: false, timedOut: false, stopped: true, skipped: false } : timedOut ? { ...singleResult, output: singleResult.output || (timeoutMessage ?? "Subagent timed out."), error: singleResult.error ?? timeoutMessage ?? "Subagent timed out.", exitCode: 1, interrupted: false, timedOut: true, skipped: false } : { ...singleResult, skipped: false };
4318
4027
  },
4319
4028
  globalSemaphore,
4320
4029
  );
@@ -4326,13 +4035,21 @@ async function runSubagent(
4326
4035
  const sessionTokens = config.sessionDir
4327
4036
  ? parseSessionTokens(path.join(config.sessionDir, `parallel-${t}`))
4328
4037
  : null;
4329
- const taskTokens = sessionTokens ?? tokenUsageFromAttempts(parallelResults[t]?.modelAttempts);
4038
+ const fallbackTokens = tokenUsageFromAttempts(parallelResults[t]?.modelAttempts);
4039
+ const observedTokens = requiredStatusStep(statusPayload, fi).tokens;
4040
+ const taskTokens = sessionTokens ?? (fallbackTokens
4041
+ ? { ...fallbackTokens, ...(observedTokens?.window !== undefined ? { window: observedTokens.window } : {}), ...(observedTokens?.windowPeak !== undefined ? { windowPeak: observedTokens.windowPeak } : {}) }
4042
+ : null);
4330
4043
  if (!taskTokens) continue;
4331
4044
  requiredStatusStep(statusPayload, fi).tokens = taskTokens;
4332
4045
  previousCumulativeTokens = {
4333
4046
  input: previousCumulativeTokens.input + taskTokens.input,
4334
4047
  output: previousCumulativeTokens.output + taskTokens.output,
4335
4048
  total: previousCumulativeTokens.total + taskTokens.total,
4049
+ ...(taskTokens.window !== undefined ? { window: taskTokens.window } : {}),
4050
+ ...(previousCumulativeTokens.windowPeak !== undefined || taskTokens.windowPeak !== undefined
4051
+ ? { windowPeak: Math.max(previousCumulativeTokens.windowPeak ?? 0, taskTokens.windowPeak ?? 0) }
4052
+ : {}),
4336
4053
  };
4337
4054
  }
4338
4055
  statusPayload.totalTokens = { ...previousCumulativeTokens };
@@ -4349,31 +4066,31 @@ async function runSubagent(
4349
4066
  output: pr.output,
4350
4067
  outputState: pr.outputState,
4351
4068
  error: pr.error,
4352
- protocolError: pr.protocolError,
4353
4069
  success: pr.stopped !== true && pr.interrupted !== true && pr.exitCode === 0,
4354
4070
  exitCode: pr.interrupted === true ? 0 : pr.exitCode,
4355
4071
  skipped: pr.skipped,
4356
4072
  interrupted: pr.interrupted,
4357
4073
  timedOut: pr.timedOut,
4358
4074
  stopped: pr.stopped,
4359
- turnBudget: pr.turnBudget,
4360
- turnBudgetExceeded: pr.turnBudgetExceeded,
4361
- wrapUpRequested: pr.wrapUpRequested,
4362
4075
  toolBudget: pr.toolBudget,
4363
4076
  toolBudgetBlocked: pr.toolBudgetBlocked,
4364
4077
  sessionFile: pr.sessionFile,
4365
4078
  intercomTarget: pr.intercomTarget,
4366
4079
  model: pr.model,
4080
+ thinking: pr.thinking,
4367
4081
  attemptedModels: pr.attemptedModels,
4368
4082
  modelAttempts: pr.modelAttempts,
4083
+ contextOverflow: pr.contextOverflow,
4369
4084
  totalCost: pr.totalCost,
4085
+ usage: pr.usage,
4370
4086
  artifactPaths: pr.artifactPaths,
4371
4087
  transcriptPath: pr.transcriptPath,
4372
4088
  transcriptError: pr.transcriptError,
4373
- effects: pr.effects,
4374
- execution: pr.execution,
4375
- review: pr.review,
4376
- structuredOutput: pr.structuredOutput,
4089
+ effects: pr.effects,
4090
+ execution: pr.execution,
4091
+ review: pr.review,
4092
+ timeoutRecovery: pr.timeoutRecovery,
4093
+ structuredOutput: pr.structuredOutput,
4377
4094
  structuredOutputPath: pr.structuredOutputPath,
4378
4095
  structuredOutputSchemaPath: pr.structuredOutputSchemaPath,
4379
4096
  acceptance: pr.acceptance,
@@ -4419,12 +4136,14 @@ async function runSubagent(
4419
4136
  diffs: captured.diffs,
4420
4137
  results: parallelResults.map((result) => ({
4421
4138
  agent: result.agent,
4139
+ ...(handoffWorkflowKey ? { workflowKey: handoffWorkflowKey } : {}),
4140
+ ...(handoffChildRunId ? { runId: handoffChildRunId } : {}),
4141
+ ...(config.lane ? { lane: config.lane } : {}),
4422
4142
  status: result.stopped || (result.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
4423
4143
  processSignal: result.processSignal,
4424
4144
  interrupted: result.interrupted,
4425
4145
  timedOut: result.timedOut,
4426
4146
  stopped: result.stopped,
4427
- turnBudgetExceeded: result.turnBudgetExceeded,
4428
4147
  }))) ? "stopped" as const : result.interrupted ? "paused" as const : result.exitCode === 0 ? "completed" as const : "failed" as const,
4429
4148
  summary: result.output || result.error || "(no output)",
4430
4149
  ...(result.artifactPaths?.outputPath ? { outputPath: result.artifactPaths.outputPath } : {}),
@@ -4469,26 +4188,61 @@ async function runSubagent(
4469
4188
  }
4470
4189
  } else {
4471
4190
  const seqStep = step as SubagentStep;
4191
+ if (timedOut) {
4192
+ results.push(timedOutStepResult(seqStep.agent, seqStep.context, seqStep.sessionName));
4193
+ flatIndex++;
4194
+ continue;
4195
+ }
4196
+ if (stopped) {
4197
+ results.push(stoppedStepResult(seqStep.agent, seqStep.context, seqStep.sessionName));
4198
+ flatIndex++;
4199
+ continue;
4200
+ }
4201
+ if (childStopRequests.has(flatIndex)) {
4202
+ results.push(childStopResult(flatIndex, seqStep.agent, seqStep.context));
4203
+ flatIndex++;
4204
+ continue;
4205
+ }
4206
+ if (interrupted) {
4207
+ results.push(pausedStepResult(seqStep.agent, seqStep.context, seqStep.sessionName));
4208
+ flatIndex++;
4209
+ continue;
4210
+ }
4472
4211
  let singleWorktreeSetup: WorktreeSetup | undefined;
4473
4212
  if (seqStep.worktree) {
4474
4213
  try {
4475
4214
  singleWorktreeSetup = createWorktrees(cwd, `${id}-s${stepIndex}`, 1, omitUndefinedProperties({
4476
4215
  agents: [seqStep.agent],
4216
+ labels: [seqStep.lane?.key ?? config.workflowKey ?? seqStep.outputName ?? seqStep.label],
4217
+ tasks: [seqStep.task],
4218
+ provider: config.worktreeProvider,
4219
+ baseRef: config.baseRef,
4220
+ branchPrefix: config.worktreeBranchPrefix,
4477
4221
  setupHook: config.worktreeSetupHook
4478
4222
  ? omitUndefinedProperties({ hookPath: config.worktreeSetupHook, timeoutMs: config.worktreeSetupHookTimeoutMs })
4479
4223
  : undefined,
4480
4224
  baseDir: config.worktreeBaseDir,
4225
+ beforeCreate: (plannedSetup) => {
4226
+ const worktree = plannedSetup.worktrees[0];
4227
+ if (worktree) {
4228
+ setStatusWorktreeReference(requiredStatusStep(statusPayload, flatIndex), worktree);
4229
+ }
4230
+ const pendingHandoff = writePendingParallelHandoff({
4231
+ manifestPath: parallelHandoffPath(asyncDir),
4232
+ runId: id,
4233
+ mode: "single",
4234
+ source: "async",
4235
+ cwd,
4236
+ stepIndex,
4237
+ flatStartIndex: flatIndex,
4238
+ setup: plannedSetup,
4239
+ laneBindings: handoffWorkflowKey || config.lane ? [{ index: flatIndex, taskIndex: 0, ...(handoffWorkflowKey ? { workflowKey: handoffWorkflowKey } : {}), ...(handoffChildRunId ? { runId: handoffChildRunId } : {}), ...(config.lane ? { lane: config.lane } : {}) }] : undefined,
4240
+ });
4241
+ statusPayload.parallelHandoff = pendingHandoff;
4242
+ statusPayload.lastUpdate = Date.now();
4243
+ writeStatusPayload();
4244
+ },
4481
4245
  }));
4482
- writePendingParallelHandoff({
4483
- manifestPath: parallelHandoffPath(asyncDir),
4484
- runId: id,
4485
- mode: "single",
4486
- source: "async",
4487
- cwd,
4488
- stepIndex,
4489
- flatStartIndex: flatIndex,
4490
- setup: singleWorktreeSetup,
4491
- });
4492
4246
  } catch (error) {
4493
4247
  if (singleWorktreeSetup) cleanupWorktrees(singleWorktreeSetup);
4494
4248
  throw error;
@@ -4518,7 +4272,9 @@ async function runSubagent(
4518
4272
  }));
4519
4273
 
4520
4274
  flushPendingStepSteers(flatIndex);
4521
- const executionStep = singleWorktreeSetup ? { ...seqStep, cwd: singleCwd } : seqStep;
4275
+ const executionStep = singleWorktreeSetup
4276
+ ? bindWorktreeCwd({ ...seqStep, cwd: singleCwd }, singleCwd)
4277
+ : seqStep;
4522
4278
  let singleResult: Awaited<ReturnType<typeof runSingleStepWithTimeout>>;
4523
4279
  try {
4524
4280
  singleResult = await runSingleStepWithTimeout(executionStep, compactOptional<SingleStepContext>({
@@ -4528,11 +4284,9 @@ async function runSubagent(
4528
4284
  artifactsDir, artifactConfig, id,
4529
4285
  flatIndex, flatStepCount: Math.max(statusPayload.steps.length, 1),
4530
4286
  outputFile: path.join(asyncDir, `output-${flatIndex}.log`),
4531
- steerInboxDir: stepSteerInboxDir(asyncDir, flatIndex),
4532
- steerCapabilityPath: steerCapabilityPath(asyncDir, flatIndex),
4533
- steerAckDir: steerAcksDir(asyncDir, flatIndex),
4534
4287
  piPackageRoot: config.piPackageRoot,
4535
- piArgv1: config.piArgv1,
4288
+ childSessions,
4289
+ inheritedChildRuntime: config.inheritedChildRuntime,
4536
4290
  childIntercomTarget: config.childIntercomTargets?.[flatIndex],
4537
4291
  orchestratorIntercomTarget: config.controlIntercomTarget,
4538
4292
  nestedRoute: config.nestedRoute,
@@ -4541,19 +4295,19 @@ async function runSubagent(
4541
4295
  registerInterrupt: (interrupt) => registerStepInterrupt(flatIndex, interrupt),
4542
4296
  registerTimeout: (interrupt) => registerStepTimeout(flatIndex, interrupt),
4543
4297
  registerStop: (stop) => registerStepStop(flatIndex, stop),
4544
- registerTurnBudgetAbort: (abort) => registerStepTurnBudgetAbort(flatIndex, abort),
4298
+ registerSteer: (steer) => registerStepSteer(flatIndex, steer),
4545
4299
  timeoutSignal: timeoutAbortController.signal,
4546
4300
  stopSignal: stopAbortController.signal,
4547
4301
  timeoutMessage,
4548
4302
  stopMessage,
4549
- turnBudget: config.turnBudget,
4550
4303
  toolTimeoutMs: seqStep.toolTimeoutMs ?? config.toolTimeoutMs,
4551
- onAttemptStart: (attempt) => updateStepModel(flatIndex, attempt.model, attempt.thinking),
4304
+ onAttemptStart: (attempt) => updateStepModel(flatIndex, attempt.model, attempt.thinking, attempt.contextLimit),
4552
4305
  onChildEvent: (event) => updateStepFromChildEvent(flatIndex, event),
4553
- onWriterProcess,
4554
4306
  onExternalProcess: (process) => updateExternalProcess(flatIndex, process),
4555
4307
  onExternalJob: (externalJob) => updateExternalJob(flatIndex, externalJob),
4556
- skipAcceptance: () => timedOut || stopped,
4308
+ skipAcceptance: () => timedOut || stopped || childStopRequests.has(flatIndex),
4309
+ usageBudgetExhausted: () => refreshUsageBudget()?.exhausted === true,
4310
+ orcaProgressTab,
4557
4311
  }), config.deadlineAt);
4558
4312
  } catch (error) {
4559
4313
  if (singleWorktreeSetup) cleanupWorktrees(singleWorktreeSetup);
@@ -4567,29 +4321,33 @@ async function runSubagent(
4567
4321
  const childStopped = singleResult.stopped === true;
4568
4322
  results.push(omitUndefinedProperties({
4569
4323
  agent: singleResult.agent,
4324
+ ...(singleResult.sessionName ? { sessionName: singleResult.sessionName } : {}),
4570
4325
  context: singleResult.context,
4571
4326
  agentContract: singleResult.agentContract,
4572
4327
  launchContractDigest: singleResult.launchContractDigest,
4573
4328
  launchResolvedExtensions: singleResult.launchResolvedExtensions,
4574
4329
  runtimeAcknowledgedExtensions: singleResult.runtimeAcknowledgedExtensions,
4575
- output: stopped || childStopped ? stopMessage : timedOut ? (timeoutMessage ?? "Subagent timed out.") : singleResult.output,
4330
+ output: stopped || childStopped ? stopMessage : timedOut ? singleResult.output || (timeoutMessage ?? "Subagent timed out.") : singleResult.output,
4576
4331
  outputState: singleResult.outputState,
4577
4332
  error: stopped || childStopped ? stopMessage : timedOut ? (timeoutMessage ?? "Subagent timed out.") : singleResult.error,
4578
- protocolError: singleResult.protocolError,
4579
4333
  success: !stopped && !childStopped && !timedOut && singleResult.interrupted !== true && singleResult.exitCode === 0,
4580
4334
  exitCode: stopped || childStopped ? 1 : timedOut ? 1 : singleResult.interrupted === true ? 0 : singleResult.exitCode,
4581
4335
  sessionFile: singleResult.sessionFile,
4582
4336
  intercomTarget: singleResult.intercomTarget,
4583
4337
  model: singleResult.model,
4338
+ thinking: singleResult.thinking,
4584
4339
  attemptedModels: singleResult.attemptedModels,
4585
4340
  modelAttempts: singleResult.modelAttempts,
4341
+ contextOverflow: singleResult.contextOverflow,
4586
4342
  totalCost: singleResult.totalCost,
4343
+ usage: singleResult.usage,
4587
4344
  artifactPaths: singleResult.artifactPaths,
4588
4345
  transcriptPath: singleResult.transcriptPath,
4589
4346
  transcriptError: singleResult.transcriptError,
4590
4347
  effects: singleResult.effects,
4591
4348
  execution: singleResult.execution,
4592
4349
  review: singleResult.review,
4350
+ timeoutRecovery: singleResult.timeoutRecovery,
4593
4351
  structuredOutput: singleResult.structuredOutput,
4594
4352
  structuredOutputPath: singleResult.structuredOutputPath,
4595
4353
  structuredOutputSchemaPath: singleResult.structuredOutputSchemaPath,
@@ -4600,9 +4358,6 @@ async function runSubagent(
4600
4358
  interrupted: singleResult.interrupted,
4601
4359
  timedOut: timedOut || singleResult.timedOut ? true : undefined,
4602
4360
  stopped: stopped || childStopped ? true : undefined,
4603
- turnBudget: singleResult.turnBudget,
4604
- turnBudgetExceeded: singleResult.turnBudgetExceeded,
4605
- wrapUpRequested: singleResult.wrapUpRequested,
4606
4361
  toolBudget: singleResult.toolBudget,
4607
4362
  toolBudgetBlocked: singleResult.toolBudgetBlocked,
4608
4363
  runner: singleResult.runner,
@@ -4624,17 +4379,27 @@ async function runSubagent(
4624
4379
  input: cumulativeTokens.input - previousCumulativeTokens.input,
4625
4380
  output: cumulativeTokens.output - previousCumulativeTokens.output,
4626
4381
  total: cumulativeTokens.total - previousCumulativeTokens.total,
4382
+ ...(cumulativeTokens.window !== undefined ? { window: cumulativeTokens.window } : {}),
4383
+ ...(cumulativeTokens.windowPeak !== undefined ? { windowPeak: cumulativeTokens.windowPeak } : {}),
4627
4384
  }
4628
4385
  : null;
4629
4386
  if (cumulativeTokens) {
4630
4387
  previousCumulativeTokens = cumulativeTokens;
4631
4388
  } else {
4632
- stepTokens = tokenUsageFromAttempts(singleResult.modelAttempts);
4389
+ const fallbackTokens = tokenUsageFromAttempts(singleResult.modelAttempts);
4390
+ const observedTokens = requiredStatusStep(statusPayload, flatIndex).tokens;
4391
+ stepTokens = fallbackTokens
4392
+ ? { ...fallbackTokens, ...(observedTokens?.window !== undefined ? { window: observedTokens.window } : {}), ...(observedTokens?.windowPeak !== undefined ? { windowPeak: observedTokens.windowPeak } : {}) }
4393
+ : null;
4633
4394
  if (stepTokens) {
4634
4395
  previousCumulativeTokens = {
4635
4396
  input: previousCumulativeTokens.input + stepTokens.input,
4636
4397
  output: previousCumulativeTokens.output + stepTokens.output,
4637
4398
  total: previousCumulativeTokens.total + stepTokens.total,
4399
+ ...(stepTokens.window !== undefined ? { window: stepTokens.window } : {}),
4400
+ ...(previousCumulativeTokens.windowPeak !== undefined || stepTokens.windowPeak !== undefined
4401
+ ? { windowPeak: Math.max(previousCumulativeTokens.windowPeak ?? 0, stepTokens.windowPeak ?? 0) }
4402
+ : {}),
4638
4403
  };
4639
4404
  }
4640
4405
  }
@@ -4647,20 +4412,16 @@ async function runSubagent(
4647
4412
  requiredStatusStep(statusPayload, flatIndex).exitCode = stopped || childStopped ? 1 : timedOut ? 1 : childInterrupted ? 0 : singleResult.exitCode;
4648
4413
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "timedOut", timedOut || singleResult.timedOut ? true : undefined);
4649
4414
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "stopped", stopped || childStopped ? true : undefined);
4650
- setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "turnBudget", singleResult.turnBudget);
4651
- setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "turnBudgetExceeded", singleResult.turnBudgetExceeded);
4652
- setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "wrapUpRequested", singleResult.wrapUpRequested);
4653
4415
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "toolBudget", singleResult.toolBudget);
4654
4416
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "toolBudgetBlocked", singleResult.toolBudgetBlocked);
4655
4417
  if (singleResult.toolBudget) statusPayload.toolBudget = singleResult.toolBudget;
4656
4418
  if (singleResult.toolBudgetBlocked) statusPayload.toolBudgetBlocked = true;
4657
- if (singleResult.turnBudget) statusPayload.turnBudget = singleResult.turnBudget;
4658
- if (singleResult.turnBudgetExceeded) statusPayload.turnBudgetExceeded = true;
4659
- if (singleResult.wrapUpRequested) statusPayload.wrapUpRequested = true;
4419
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "sessionName", singleResult.sessionName);
4660
4420
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "model", singleResult.model);
4661
4421
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "thinking", resolveEffectiveThinking(singleResult.model, requiredStatusStep(statusPayload, flatIndex).thinking));
4662
4422
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "attemptedModels", singleResult.attemptedModels);
4663
4423
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "modelAttempts", singleResult.modelAttempts);
4424
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "contextOverflow", singleResult.contextOverflow);
4664
4425
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "totalCost", singleResult.totalCost);
4665
4426
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "error", stopped || childStopped ? stopMessage : timedOut ? (timeoutMessage ?? "Subagent timed out.") : singleResult.error);
4666
4427
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "transcriptPath", singleResult.transcriptPath ?? requiredStatusStep(statusPayload, flatIndex).transcriptPath);
@@ -4675,6 +4436,7 @@ async function runSubagent(
4675
4436
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "structuredOutputPath", singleResult.structuredOutputPath);
4676
4437
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "structuredOutputSchemaPath", singleResult.structuredOutputSchemaPath);
4677
4438
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "acceptance", singleResult.acceptance);
4439
+ setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "timeoutRecovery", singleResult.timeoutRecovery);
4678
4440
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "watchdog", singleResult.watchdog);
4679
4441
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "capabilityCeiling", singleResult.capabilityCeiling);
4680
4442
  setOptionalProperty(requiredStatusStep(statusPayload, flatIndex), "capabilityAudit", singleResult.capabilityAudit);
@@ -4698,6 +4460,7 @@ async function runSubagent(
4698
4460
  durationMs: stepEndTime - stepStartTime,
4699
4461
  tokens: stepTokens,
4700
4462
  }));
4463
+ if (stopped || childStopped) appendTerminalChildStatusEvent(flatIndex, stepEndTime);
4701
4464
  if (singleWorktreeSetup && !singleResult.detached) {
4702
4465
  const diffs = diffWorktrees(singleWorktreeSetup, [seqStep.agent], path.join(asyncDir, "worktree-diffs", `step-${stepIndex}`));
4703
4466
  const diffSummary = formatWorktreeDiffSummary(diffs);
@@ -4714,6 +4477,9 @@ async function runSubagent(
4714
4477
  diffs,
4715
4478
  results: [{
4716
4479
  agent: singleResult.agent,
4480
+ ...(handoffWorkflowKey ? { workflowKey: handoffWorkflowKey } : {}),
4481
+ ...(handoffChildRunId ? { runId: handoffChildRunId } : {}),
4482
+ ...(config.lane ? { lane: config.lane } : {}),
4717
4483
  status: singleResult.stopped ? "stopped" as const : singleResult.interrupted ? "paused" as const : singleResult.exitCode === 0 ? "completed" as const : "failed" as const,
4718
4484
  summary: singleResult.output || singleResult.error || "(no output)",
4719
4485
  ...(singleResult.artifactPaths?.outputPath ? { outputPath: singleResult.artifactPaths.outputPath } : {}),
@@ -4766,7 +4532,7 @@ async function runSubagent(
4766
4532
  }
4767
4533
  }
4768
4534
 
4769
- let summary = results.map((r) => `${r.agent}:\n${r.output}`).join("\n\n");
4535
+ let summary = results.map((r) => `${r.agent}:\n${r.output || (r.exitCode !== 0 ? r.error : undefined) || "(no output)"}`).join("\n\n");
4770
4536
  let truncated = false;
4771
4537
 
4772
4538
  if (maxOutput) {
@@ -4831,17 +4597,17 @@ async function runSubagent(
4831
4597
  clearTimeout(timeoutTimer);
4832
4598
  timeoutTimer = undefined;
4833
4599
  }
4834
- if (!timedOut && !stopped && !interrupted && config.timeoutMs !== undefined && results.some((result) => result.timedOut === true && result.error === timeoutMessage)) {
4600
+ if (!timedOut && !stopped && !interrupted && config.timeoutMs !== undefined && timeoutMessage !== undefined && results.some((result) => result.timedOut === true && result.error?.startsWith(timeoutMessage))) {
4835
4601
  timedOut = true;
4836
4602
  }
4837
- const signalTerminated = !stopped && !timedOut && !turnBudgetExceeded && !interrupted && results.some((result) => result.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
4603
+ const signalTerminated = !stopped && !timedOut && !interrupted && results.some((result) => result.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
4838
4604
  processSignal: result.processSignal,
4839
4605
  interrupted: result.interrupted,
4840
4606
  timedOut: result.timedOut,
4841
4607
  stopped: result.stopped,
4842
- turnBudgetExceeded: result.turnBudgetExceeded,
4843
4608
  })));
4844
- statusPayload.state = stopped || signalTerminated ? "stopped" : timedOut || turnBudgetExceeded || usageBudgetExceeded || statusPayload.error ? "failed" : interrupted ? "paused" : results.every((r) => r.success) ? "complete" : "failed";
4609
+ const partialWithEvidence = !stopped && !signalTerminated && !timedOut && !usageBudgetExceeded && !interrupted && results.some(partialEvidenceResult) && !results.some(concreteFailureResult);
4610
+ statusPayload.state = stopped || signalTerminated ? "stopped" : timedOut || usageBudgetExceeded ? "failed" : interrupted ? "paused" : results.every((r) => r.success) ? "complete" : partialWithEvidence ? "partial" : "failed";
4845
4611
  closeSteerInbox(asyncDir, statusPayload.state, (filePath, payload) => runPersistence.write(filePath, payload));
4846
4612
  disposeControlInbox();
4847
4613
  for (const request of consumeSteerRequests(asyncDir)) deliverSteerRequest(request);
@@ -4871,13 +4637,17 @@ async function runSubagent(
4871
4637
  statusPayload.timedOut = true;
4872
4638
  statusPayload.error = timeoutMessage ?? "Subagent timed out.";
4873
4639
  }
4874
- if (turnBudgetExceeded && !statusPayload.error) {
4875
- const budget = statusPayload.turnBudget;
4876
- statusPayload.error = budget ? turnBudgetExceededMessage(budget, budget.turnCount) : "Subagent exceeded turn budget.";
4877
- }
4878
4640
  if (usageBudgetExceeded && statusPayload.usageBudget && !statusPayload.error) {
4879
4641
  statusPayload.error = usageBudgetExceededMessage(statusPayload.usageBudget);
4880
4642
  }
4643
+ if (partialWithEvidence) {
4644
+ const partialResult = results.find(partialEvidenceResult);
4645
+ statusPayload.activityState = "needs_attention";
4646
+ statusPayload.error = partialResult?.error ?? statusPayload.error;
4647
+ for (const step of statusPayload.steps) {
4648
+ if (step.status === "failed") step.activityState = "needs_attention";
4649
+ }
4650
+ }
4881
4651
  statusPayload.endedAt = runEndedAt;
4882
4652
  statusPayload.lastUpdate = runEndedAt;
4883
4653
  setOptionalProperty(statusPayload, "sessionFile", effectiveSessionFile);
@@ -4887,55 +4657,53 @@ async function runSubagent(
4887
4657
  setOptionalProperty(statusPayload, "shareUrl", shareUrl);
4888
4658
  setOptionalProperty(statusPayload, "gistUrl", gistUrl);
4889
4659
  setOptionalProperty(statusPayload, "shareError", shareError);
4890
- if (statusPayload.state === "failed" && !statusPayload.error) {
4891
- const failedStep = statusPayload.steps.find((s) => s.status === "failed");
4660
+ if ((statusPayload.state === "failed" || statusPayload.state === "partial") && !statusPayload.error) {
4661
+ const concreteFailure = results.find(concreteFailureResult);
4662
+ const failedStep = concreteFailure ? undefined : statusPayload.steps.find((s) => s.status === "failed");
4663
+ if (concreteFailure?.error) statusPayload.error = concreteFailure.error;
4892
4664
  if (failedStep?.agent) {
4893
4665
  statusPayload.error = `Step failed: ${failedStep.agent}`;
4894
4666
  }
4895
4667
  }
4896
- writeStatusPayload();
4897
4668
  try {
4898
4669
  runPersistence.write(resultPath, {
4899
4670
  lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
4900
4671
  id,
4901
4672
  agent: agentName,
4902
4673
  mode: resultMode,
4903
- success: !stopped && !timedOut && !turnBudgetExceeded && !usageBudgetExceeded && !interrupted && !signalTerminated && results.every((r) => r.success),
4904
- state: stopped || signalTerminated ? "stopped" : timedOut || turnBudgetExceeded || usageBudgetExceeded ? "failed" : interrupted ? "paused" : results.every((r) => r.success) ? "complete" : "failed",
4905
- summary: stopped ? stopMessage : signalTerminated ? (statusPayload.error ?? "Subagent process terminated by signal.") : timedOut ? (timeoutMessage ?? "Subagent timed out.") : turnBudgetExceeded ? (statusPayload.error ?? "Subagent exceeded turn budget.") : usageBudgetExceeded ? (statusPayload.error ?? "Usage budget exhausted.") : interrupted ? "Paused after interrupt. Waiting for explicit next action." : summary,
4674
+ success: statusPayload.state === "complete",
4675
+ state: statusPayload.state,
4676
+ summary: stopped ? stopMessage : signalTerminated ? (statusPayload.error ?? "Subagent process terminated by signal.") : timedOut ? (timeoutMessage ?? "Subagent timed out.") : usageBudgetExceeded ? (statusPayload.error ?? "Usage budget exhausted.") : interrupted ? "Paused after interrupt. Waiting for explicit next action." : statusPayload.state === "partial" ? (statusPayload.error ?? summary) : summary,
4906
4677
  ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),
4907
4678
  ...(config.deadlineAt !== undefined ? { deadlineAt: config.deadlineAt } : {}),
4908
- ...(statusPayload.turnBudget ? { turnBudget: statusPayload.turnBudget } : {}),
4909
- ...(statusPayload.turnBudgetExceeded ? { turnBudgetExceeded: true } : {}),
4910
- ...(statusPayload.wrapUpRequested ? { wrapUpRequested: true } : {}),
4911
4679
  ...(statusPayload.toolBudget ? { toolBudget: statusPayload.toolBudget } : {}),
4912
4680
  ...(statusPayload.toolBudgetBlocked ? { toolBudgetBlocked: true } : {}),
4913
4681
  ...(statusPayload.usageBudget ? { usageBudget: statusPayload.usageBudget } : {}),
4914
- ...(stopped ? { stopped: true, error: stopMessage } : timedOut ? { timedOut: true, error: timeoutMessage ?? "Subagent timed out." } : turnBudgetExceeded ? { error: statusPayload.error ?? "Subagent exceeded turn budget." } : usageBudgetExceeded ? { error: statusPayload.error ?? "Usage budget exhausted." } : {}),
4682
+ ...(stopped ? { stopped: true, error: stopMessage } : timedOut ? { timedOut: true, error: timeoutMessage ?? "Subagent timed out." } : usageBudgetExceeded ? { error: statusPayload.error ?? "Usage budget exhausted." } : {}),
4915
4683
  results: results.map((r) => omitUndefinedProperties({
4916
4684
  agent: r.agent,
4685
+ ...(r.sessionName ? { sessionName: r.sessionName } : {}),
4917
4686
  context: r.context,
4918
4687
  output: r.output,
4919
4688
  outputState: r.outputState,
4920
4689
  error: r.error,
4921
- protocolError: r.protocolError,
4922
4690
  success: r.success,
4923
4691
  skipped: r.skipped || undefined,
4924
4692
  interrupted: r.interrupted || undefined,
4925
4693
  timedOut: r.timedOut || undefined,
4926
4694
  stopped: r.stopped || undefined,
4927
4695
  processSignal: r.processSignal || undefined,
4928
- turnBudget: r.turnBudget,
4929
- turnBudgetExceeded: r.turnBudgetExceeded || undefined,
4930
- wrapUpRequested: r.wrapUpRequested || undefined,
4931
4696
  toolBudget: r.toolBudget,
4932
4697
  toolBudgetBlocked: r.toolBudgetBlocked || undefined,
4933
4698
  sessionFile: r.sessionFile,
4934
4699
  intercomTarget: r.intercomTarget,
4935
4700
  model: r.model,
4701
+ thinking: r.thinking,
4936
4702
  attemptedModels: r.attemptedModels,
4937
4703
  modelAttempts: r.modelAttempts,
4704
+ contextOverflow: r.contextOverflow,
4938
4705
  totalCost: r.totalCost,
4706
+ usage: r.usage,
4939
4707
  artifactPaths: r.artifactPaths,
4940
4708
  outputSaveError: r.outputSaveError,
4941
4709
  metadataSaveError: r.metadataSaveError,
@@ -4957,6 +4725,7 @@ async function runSubagent(
4957
4725
  structuredOutputSchemaPath: r.structuredOutputSchemaPath,
4958
4726
  acceptance: r.acceptance,
4959
4727
  watchdog: r.watchdog,
4728
+ timeoutRecovery: r.timeoutRecovery,
4960
4729
  capabilityCeiling: r.capabilityCeiling,
4961
4730
  capabilityAudit: r.capabilityAudit,
4962
4731
  })),
@@ -4967,7 +4736,7 @@ async function runSubagent(
4967
4736
  capabilityAudit: statusPayload.capabilityAudit,
4968
4737
  ...(config.parentWorkflowRunId ? { parentWorkflowRunId: config.parentWorkflowRunId } : {}),
4969
4738
  ...(config.workflowKey ? { workflowKey: config.workflowKey } : {}),
4970
- exitCode: stopped || timedOut || turnBudgetExceeded || usageBudgetExceeded ? 1 : interrupted || results.every((r) => r.success) ? 0 : 1,
4739
+ exitCode: statusPayload.state === "complete" || statusPayload.state === "paused" ? 0 : 1,
4971
4740
  timestamp: runEndedAt,
4972
4741
  durationMs: runEndedAt - overallStartTime,
4973
4742
  totalTokens: statusPayload.totalTokens,
@@ -4999,6 +4768,7 @@ async function runSubagent(
4999
4768
  statusPayload.lastUpdate = Date.now();
5000
4769
  }
5001
4770
  writeStatusPayload();
4771
+ await orcaProgressTab?.finish(statusPayload.state === "complete" ? "completed" : statusPayload.state === "stopped" ? "stopped" : "failed", effectiveSessionFile);
5002
4772
  appendJsonl(
5003
4773
  eventsPath,
5004
4774
  JSON.stringify({
@@ -5033,14 +4803,21 @@ async function runSubagent(
5033
4803
  }), (filePath, content) => runPersistence.write(filePath, { content }, (_path, payload) => {
5034
4804
  fs.writeFileSync(_path, (payload as { content: string }).content, "utf-8");
5035
4805
  }));
5036
- if (runPersistence.pendingCount() === 0) runPersistence.dispose();
5037
- if (indexPersistence.pendingCount() === 0) indexPersistence.dispose();
4806
+ // The run is committed: release the child sessions first, then wait for the
4807
+ // storage-capacity retries that may still hold the final status or result.
4808
+ await childSessions.dispose().catch((error: unknown) => console.error("Failed to dispose runner child sessions:", error));
4809
+ while (runPersistence.pendingCount() + indexPersistence.pendingCount() > 0) {
4810
+ await new Promise((resolve) => setTimeout(resolve, 200));
4811
+ }
4812
+ runPersistence.dispose();
4813
+ indexPersistence.dispose();
5038
4814
  if (config.runnerProcessInstanceId) {
4815
+ // Children run inside this process, so no step has writer processes to prove terminal.
5039
4816
  const writers: Record<string, PiWriterProcessInstanceExitV1[]> = {};
5040
4817
  const expectedWriters: Record<string, number> = {};
5041
- for (const [index, result] of results.entries()) {
5042
- writers[String(index)] = result.writerProcesses ?? [];
5043
- expectedWriters[String(index)] = result.writerAttemptCount ?? 0;
4818
+ for (const index of results.keys()) {
4819
+ writers[String(index)] = [];
4820
+ expectedWriters[String(index)] = 0;
5044
4821
  }
5045
4822
  const candidate: ProcessTerminalCandidate = {
5046
4823
  version: 1,
@@ -5074,7 +4851,7 @@ async function waitForStartupControl(
5074
4851
  } catch (error) {
5075
4852
  throw new Error(`Failed to read runner startup control '${controlPath}': ${error instanceof Error ? error.message : String(error)}`);
5076
4853
  }
5077
- if (payload.token !== token) throw new Error("Runner startup control token does not match the acquired session lease.");
4854
+ if (payload.token !== token) throw new Error("Runner startup control token does not match.");
5078
4855
  if (payload.action === action) return;
5079
4856
  if (payload.action !== "ack" && payload.action !== "proceed") throw new Error("Runner startup control action is invalid.");
5080
4857
  }
@@ -5085,7 +4862,7 @@ async function waitForStartupControl(
5085
4862
 
5086
4863
  async function runConfiguredSubagent(config: SubagentRunConfig): Promise<void> {
5087
4864
  let lease: ReturnType<typeof acquireSessionLease> | undefined;
5088
- let startupCommitted = config.revivalLease === undefined;
4865
+ let startupCommitted = config.revivalLease === undefined && config.launchBarrierToken === undefined;
5089
4866
  const startupPath = path.join(config.asyncDir, "runner-startup.json");
5090
4867
  const startupAckPath = path.join(config.asyncDir, "runner-startup-ack.json");
5091
4868
  const startupProceedPath = path.join(config.asyncDir, "runner-startup-proceed.json");
@@ -5098,7 +4875,15 @@ async function runConfiguredSubagent(config: SubagentRunConfig): Promise<void> {
5098
4875
  };
5099
4876
  process.once("exit", releaseOnExit);
5100
4877
  try {
5101
- if (config.revivalLease) {
4878
+ if (config.launchBarrierToken) {
4879
+ await waitForStartupControl(startupProceedPath, config.launchBarrierToken, "proceed");
4880
+ startupCommitted = true;
4881
+ try {
4882
+ fs.rmSync(startupProceedPath, { force: true });
4883
+ } catch {
4884
+ // Startup control cleanup is best effort after the parent commits the run.
4885
+ }
4886
+ } else if (config.revivalLease) {
5102
4887
  lease = acquireSessionLease(config.revivalLease);
5103
4888
  config.revivalLeaseToken = lease.owner.token;
5104
4889
  writeAtomicJson(startupPath, { state: "ready", token: lease.owner.token, pid: process.pid, owner: lease.owner });
@@ -5114,9 +4899,18 @@ async function runConfiguredSubagent(config: SubagentRunConfig): Promise<void> {
5114
4899
  }
5115
4900
  }
5116
4901
  }
5117
- await runSubagent(config, lease ? (writer) => lease!.updateWriter(writer) : undefined);
4902
+ const childSessions = await loadRunnerChildSessionFactory(config);
4903
+ try {
4904
+ await runSubagent(config, childSessions);
4905
+ } finally {
4906
+ try {
4907
+ await childSessions.dispose();
4908
+ } catch (error) {
4909
+ console.error("Failed to dispose runner child sessions:", error);
4910
+ }
4911
+ }
5118
4912
  } catch (error) {
5119
- if (config.revivalLease && !startupCommitted) {
4913
+ if (!startupCommitted) {
5120
4914
  try {
5121
4915
  writeAtomicJson(startupPath, { state: "error", pid: process.pid, error: error instanceof Error ? error.message : String(error) });
5122
4916
  } catch {
@@ -5143,10 +4937,16 @@ async function runConfiguredSubagent(config: SubagentRunConfig): Promise<void> {
5143
4937
  }
5144
4938
 
5145
4939
  function startConfiguredSubagent(config: SubagentRunConfig): void {
5146
- runConfiguredSubagent(config).catch((runErr) => {
5147
- console.error("Subagent runner error:", runErr);
5148
- process.exit(1);
5149
- });
4940
+ // Child sessions and the extensions loaded into them may leave handles
4941
+ // behind even after shutdown; the run is fully persisted by now, so exit
4942
+ // explicitly instead of waiting for the event loop to drain.
4943
+ runConfiguredSubagent(config).then(
4944
+ () => process.exit(0),
4945
+ (runErr) => {
4946
+ console.error("Subagent runner error:", runErr);
4947
+ process.exit(1);
4948
+ },
4949
+ );
5150
4950
  }
5151
4951
 
5152
4952
  const configArg = process.argv[2];