@xzzpig/pi-subagents 0.14.0 → 0.15.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 (198) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/README.md +6 -5
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +56 -15
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -19
  9. package/docs/missions.md +10 -2
  10. package/docs/models.md +11 -22
  11. package/docs/observability.md +63 -11
  12. package/docs/standalone-background.md +59 -0
  13. package/docs/tool-reference.md +42 -23
  14. package/docs/watchdog.md +39 -10
  15. package/docs/workflows.md +58 -19
  16. package/index.ts +5 -2
  17. package/inspector-runner.mjs +2 -2
  18. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  20. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  21. package/package.json +9 -4
  22. package/prompts/parallel-review.md +1 -1
  23. package/runner-peer-loader.mjs +24 -0
  24. package/runner-peer-preload.mjs +36 -0
  25. package/skills/pi-subagents/SKILL.md +34 -22
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  27. package/skills/pi-subagents/references/execution-controls.md +27 -8
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  31. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  32. package/src/agents/advertised-agent-prompt.ts +94 -0
  33. package/src/agents/agent-management.ts +71 -59
  34. package/src/agents/agent-serializer.ts +6 -3
  35. package/src/agents/agents.ts +198 -72
  36. package/src/agents/builtin-names.ts +1 -0
  37. package/src/agents/chain-serializer.ts +5 -0
  38. package/src/agents/runtime-agent-registry.ts +7 -6
  39. package/src/api/delegation.ts +4 -0
  40. package/src/api/preflight.ts +110 -71
  41. package/src/api/required-child-extensions.ts +6 -0
  42. package/src/api/shared-types.ts +3 -1
  43. package/src/api/workflow-resources.ts +6 -0
  44. package/src/extension/config.ts +14 -37
  45. package/src/extension/fanout-child.ts +68 -5
  46. package/src/extension/herdr-pi-bridge.ts +164 -0
  47. package/src/extension/index.ts +141 -51
  48. package/src/extension/public-execution.ts +7 -6
  49. package/src/extension/rpc.ts +8 -21
  50. package/src/extension/schemas.ts +86 -84
  51. package/src/extension/tool-description.ts +32 -79
  52. package/src/inspectors/actions.ts +148 -0
  53. package/src/inspectors/ghostty/actions.ts +74 -0
  54. package/src/inspectors/ghostty/plugin.ts +17 -0
  55. package/src/inspectors/herdr/actions.ts +99 -179
  56. package/src/inspectors/herdr/plugin.ts +20 -0
  57. package/src/inspectors/herdr/project-panes.ts +4 -1
  58. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  59. package/src/inspectors/plugins.ts +8 -0
  60. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  61. package/src/inspectors/types.ts +51 -0
  62. package/src/integrations/pi-web-session-liveness.ts +73 -0
  63. package/src/intercom/intercom-bridge.ts +50 -8
  64. package/src/intercom/native-supervisor-channel.ts +142 -115
  65. package/src/intercom/supervisor-ui.ts +3 -2
  66. package/src/missions/workflow-state.ts +37 -16
  67. package/src/policy/authority.ts +4 -0
  68. package/src/profiles/profiles.ts +12 -6
  69. package/src/runs/background/active-async-capacity.ts +22 -18
  70. package/src/runs/background/active-run-index.ts +17 -1
  71. package/src/runs/background/async-execution.ts +359 -176
  72. package/src/runs/background/async-job-tracker.ts +41 -7
  73. package/src/runs/background/async-resume.ts +19 -12
  74. package/src/runs/background/async-retention.ts +20 -0
  75. package/src/runs/background/async-status-snapshot.ts +10 -12
  76. package/src/runs/background/async-status.ts +32 -13
  77. package/src/runs/background/auto-drain.ts +59 -35
  78. package/src/runs/background/binary-bootstrap.ts +38 -0
  79. package/src/runs/background/chain-append.ts +1 -1
  80. package/src/runs/background/chain-root-attachment.ts +22 -33
  81. package/src/runs/background/control-channel.ts +78 -44
  82. package/src/runs/background/fleet-view.ts +30 -2
  83. package/src/runs/background/notify.ts +193 -19
  84. package/src/runs/background/owned-process-tree.ts +35 -8
  85. package/src/runs/background/process-terminal.ts +23 -23
  86. package/src/runs/background/result-files.ts +8 -4
  87. package/src/runs/background/result-watcher.ts +19 -2
  88. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  89. package/src/runs/background/run-child-session.ts +118 -41
  90. package/src/runs/background/run-status.ts +78 -5
  91. package/src/runs/background/runner-aliases.ts +22 -5
  92. package/src/runs/background/runner-child-launch.ts +93 -0
  93. package/src/runs/background/runner-child-sessions.ts +5 -4
  94. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  95. package/src/runs/background/scheduled-runs.ts +51 -18
  96. package/src/runs/background/stale-run-reconciler.ts +38 -12
  97. package/src/runs/background/steering.ts +20 -2
  98. package/src/runs/background/subagent-runner.ts +766 -432
  99. package/src/runs/background/subagent-wait.ts +179 -28
  100. package/src/runs/background/wait-completions.ts +79 -27
  101. package/src/runs/background/wait-subscriptions.ts +9 -3
  102. package/src/runs/background/wait-tool.ts +5 -3
  103. package/src/runs/foreground/async-steering-action.ts +37 -7
  104. package/src/runs/foreground/async-stop-action.ts +93 -3
  105. package/src/runs/foreground/execution.ts +174 -194
  106. package/src/runs/foreground/foreground-history.ts +5 -2
  107. package/src/runs/foreground/prompt-audit.ts +12 -6
  108. package/src/runs/foreground/subagent-executor.ts +896 -397
  109. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  110. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  111. package/src/runs/shared/acceptance.ts +54 -14
  112. package/src/runs/shared/agent-contract.ts +1 -1
  113. package/src/runs/shared/async-status-projection.ts +172 -78
  114. package/src/runs/shared/capability-ceiling.ts +2 -0
  115. package/src/runs/shared/child-hooks.ts +167 -3
  116. package/src/runs/shared/child-launch-plan.ts +15 -3
  117. package/src/runs/shared/child-launch.ts +44 -16
  118. package/src/runs/shared/child-lifecycle.ts +6 -3
  119. package/src/runs/shared/child-runtime-config.ts +8 -1
  120. package/src/runs/shared/child-session.ts +130 -24
  121. package/src/runs/shared/child-tool-plan.ts +145 -14
  122. package/src/runs/shared/completion-evidence.ts +2 -2
  123. package/src/runs/shared/completion-guard.ts +6 -3
  124. package/src/runs/shared/dynamic-fanout.ts +2 -2
  125. package/src/runs/shared/effective-system-prompt.ts +33 -0
  126. package/src/runs/shared/external-cli-contract.ts +11 -1
  127. package/src/runs/shared/external-cli-preflight.ts +6 -2
  128. package/src/runs/shared/external-cli-runner.ts +9 -7
  129. package/src/runs/shared/herdr-connection.ts +134 -0
  130. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  131. package/src/runs/shared/herdr-machine.ts +279 -0
  132. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  133. package/src/runs/shared/herdr-placed-run.ts +263 -0
  134. package/src/runs/shared/host-step-status.ts +11 -11
  135. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  136. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  137. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  138. package/src/runs/shared/model-scope.ts +1 -1
  139. package/src/runs/shared/nested-events.ts +19 -10
  140. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  141. package/src/runs/shared/parallel-handoff.ts +57 -12
  142. package/src/runs/shared/parallel-utils.ts +10 -4
  143. package/src/runs/shared/pi-spawn.ts +10 -0
  144. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  145. package/src/runs/shared/run-fanout-budget.ts +8 -8
  146. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  147. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  148. package/src/runs/shared/task-intent.ts +46 -13
  149. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  150. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  151. package/src/runs/shared/worktree-setup-command.ts +213 -0
  152. package/src/runs/shared/worktree.ts +437 -214
  153. package/src/shared/child-cache-retention.ts +43 -0
  154. package/src/shared/fork-context.ts +15 -72
  155. package/src/shared/launch-contract.ts +70 -8
  156. package/src/shared/model-response-aliases.ts +13 -0
  157. package/src/shared/opencode-session-headers.ts +30 -0
  158. package/src/shared/pruned-fork.ts +1 -1
  159. package/src/shared/required-child-extensions.ts +81 -0
  160. package/src/shared/settings.ts +5 -2
  161. package/src/shared/shortcuts.ts +0 -4
  162. package/src/shared/types.ts +163 -90
  163. package/src/shared/utils.ts +10 -2
  164. package/src/shared/watch-strategy.ts +2 -0
  165. package/src/shared/workflow-child-permit.ts +18 -13
  166. package/src/slash/delegation-adapters.ts +3 -1
  167. package/src/slash/delegation-request.ts +14 -0
  168. package/src/slash/slash-commands.ts +2 -7
  169. package/src/slash/subagents-admin.ts +31 -14
  170. package/src/tui/fleet-status.ts +165 -20
  171. package/src/tui/fleet.ts +30 -19
  172. package/src/tui/render.ts +210 -50
  173. package/src/watchdog/child-status.ts +28 -28
  174. package/src/watchdog/lsp-diagnostics.ts +1 -1
  175. package/src/watchdog/model-selection.ts +21 -1
  176. package/src/watchdog/permission-arbiter.ts +5 -2
  177. package/src/watchdog/register-child.ts +10 -2
  178. package/src/watchdog/register-main.ts +39 -35
  179. package/src/watchdog/render.ts +1 -1
  180. package/src/watchdog/review.ts +122 -74
  181. package/src/watchdog/rules.ts +1 -1
  182. package/src/watchdog/runtime.ts +100 -27
  183. package/src/watchdog/scope.ts +1 -1
  184. package/src/watchdog/settings.ts +3 -0
  185. package/src/watchdog/tool-actions.ts +13 -12
  186. package/src/watchdog/turn-delta.ts +23 -0
  187. package/src/watchdog/types.ts +5 -3
  188. package/src/watchdog/warning-format.ts +1 -1
  189. package/src/workflows/chat-progress.ts +3 -3
  190. package/src/workflows/scripted-workflow.ts +349 -26
  191. package/src/workflows/workflow-checklist.ts +17 -20
  192. package/src/workflows/workflow-child-summary.ts +57 -8
  193. package/src/workflows/workflow-preflight.ts +19 -19
  194. package/src/workflows/workflow-receipt.ts +24 -6
  195. package/src/workflows/workflow-resources.ts +108 -22
  196. package/src/workflows/workflow-settlement.ts +3 -0
  197. package/src/runs/shared/model-exclusions.ts +0 -373
  198. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -28,7 +28,10 @@ import { runSync } from "./execution.ts";
28
28
  import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/tool-actions.ts";
29
29
  import type { MainWatchdogRuntime } from "../../watchdog/runtime.ts";
30
30
  import { applyWatchdogLaunchRules } from "../../watchdog/rules.ts";
31
- import { buildModelCandidates, normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, type ModelOrigin, type ParentModel } from "../shared/model-fallback.ts";
31
+ import { childWatchdogProgressForModel } from "../../watchdog/child-status.ts";
32
+ import { normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, resolveModelSelection, type ModelOrigin, type ParentModel } from "../shared/model-resolution.ts";
33
+ import { getHostBuiltinToolNames } from "../shared/child-tool-plan.ts";
34
+ import { projectChainOutputSchemas, resolveEffectiveOutputSchema } from "../shared/child-launch-plan.ts";
32
35
  import { formatRetainedChildren, listRetainedChildren } from "../background/retained-children.ts";
33
36
  import { resolveModelScopesForAgent, type ModelScopeConfig } from "../shared/model-scope.ts";
34
37
  import { recordRun } from "../shared/run-history.ts";
@@ -49,10 +52,11 @@ import { updateActiveRunIndex } from "../background/active-run-index.ts";
49
52
  import { steeringReceipt } from "../background/steering.ts";
50
53
  import { acquireActiveAsyncCapacity, ActiveAsyncCapacityError, getActiveAsyncCapacitySnapshot, resolveAbandonedSlotReleaseAfterMs, resolveMaxActiveAsyncRunsPerSession, transferActiveAsyncCapacity, type ActiveAsyncCapacityHandle } from "../background/active-async-capacity.ts";
51
54
  import { isScheduledRunAction } from "../background/scheduled-runs.ts";
55
+ import { encodeIndexSegment } from "../background/index-segment.ts";
52
56
  import { enqueueChainAppendRequest, readPendingChainAppendRequests, runnerStepOutputNames } from "../background/chain-append.ts";
53
57
  import { ChainOutputValidationError, validateChainOutputBindingsWithContext } from "../shared/chain-outputs.ts";
54
- import { normalizeGateAcceptance, resolveAcceptanceReportMode, validateExecutionAcceptance } from "../shared/acceptance.ts";
55
- import { canPreferFork, createForkContextResolver, forkedChildRequiresThinkingOff, resolveSubagentLaunchContext } from "../../shared/fork-context.ts";
58
+ import { normalizeGateAcceptance, resolveAcceptanceReportMode, validateAcceptanceInput, validateExecutionAcceptance, validateExecutionAcceptancePolicy } from "../shared/acceptance.ts";
59
+ import { canPreferFork, createForkContextResolver, resolveSubagentLaunchContext } from "../../shared/fork-context.ts";
56
60
  import { createPrunedForkSessionWriter } from "../../shared/pruned-fork.ts";
57
61
  import { resolveCurrentSessionId } from "../../shared/session-identity.ts";
58
62
  import { currentCompletionOwnerId } from "../../shared/completion-owner.ts";
@@ -60,16 +64,18 @@ import { applyIntercomBridgeToAgent, INTERCOM_BRIDGE_MARKER, resolveIntercomBrid
60
64
  import { formatControlIntercomMessage, formatControlNoticeMessage, resolveControlConfig, shouldNotifyControlEvent } from "../shared/subagent-control.ts";
61
65
  import { formatSpawnBudget, getSpawnBudgetSnapshot, grantSpawnBudget, preflightSpawnBudget, preflightSpawnBudgetGrant, reserveSpawnBudget } from "../shared/spawn-budget.ts";
62
66
  import { claimRunFanoutBatch, claimRunFanoutBatchWithCommit, createRunFanoutBudget, formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor, RunFanoutLimitError, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
67
+ import { retainLiveForegroundNestedRoute } from "../../integrations/pi-web-session-liveness.ts";
63
68
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
64
69
  import { usageBudgetExceededMessage, usageBudgetState, validateUsageBudgetConfig } from "../shared/usage-budget.ts";
65
70
  import { intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
66
- import { isAgentContractV1 } from "../shared/agent-contract.ts";
71
+ import { isAgentContract } from "../shared/agent-contract.ts";
67
72
  import { normalizeExtensionBindings, type ExtensionBindings } from "../shared/extension-bindings.ts";
73
+ import { resolveRequiredChildExtensions } from "../../shared/required-child-extensions.ts";
68
74
  import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, outputPathMappingFromTask, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
69
75
  import { assertJsonSchemaObject, cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
70
76
  import { compactForegroundDetails, getSingleResultOutput, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage, toAgentToolUsage } from "../../shared/utils.ts";
71
77
  import { createTaskMutationArbiter } from "../shared/llm-intent-arbiter.ts";
72
- import { discardPreservedWorktrees, formatParallelHandoffError, formatParallelHandoffReference, formatStoredParallelHandoffCleanup, parallelHandoffPath, readParallelHandoffManifest, recordParallelHandoffMerge, recordParallelHandoffSupersession, writeParallelHandoffGroup, writePendingParallelHandoff } from "../shared/parallel-handoff.ts";
78
+ import { discardPreservedWorktrees, formatParallelHandoffError, formatParallelHandoffReference, formatStoredParallelHandoffCleanup, parallelHandoffPath, readParallelHandoffManifest, recordParallelHandoffMerge, recordParallelHandoffSupersession, writeParallelHandoffGroup, writeWorktreeSetupHandoff } from "../shared/parallel-handoff.ts";
73
79
  import { summarizeContextModes, type ContextMode, type ContextSummary } from "../shared/context-mode.ts";
74
80
  import {
75
81
  attachNestedChildrenToResultChildren,
@@ -80,19 +86,20 @@ import {
80
86
  stripDetailsOutputsForIntercomReceipt,
81
87
  } from "../../intercom/result-intercom.ts";
82
88
  import { applySteeringRecoveryAgentConfig, asyncReviveRequiresRecoveryDescriptor, buildRevivedAsyncTask, readAsyncRecoveryDescriptor, resolveAsyncResumeTarget, resolveAsyncRunLocation } from "../background/async-resume.ts";
83
- import { deliverInterruptRequest, readRevivalBriefs, requestAsyncSteer, type SteerDeliveryMode } from "../background/control-channel.ts";
84
- import { updateSteeringTarget, waitForSteeringAction } from "../background/steering.ts";
89
+ import { closeSteerInbox, consumeSteerRequests, deliverInterruptRequest, readRevivalBriefs, requestAsyncSteer, watchAsyncControlInbox, type SteerDeliveryMode, type SteerRequest } from "../background/control-channel.ts";
90
+ import { createSteeringStatus, recordSteeringRequest, steeringStatus, updateSteeringTarget, waitForSteeringAction } from "../background/steering.ts";
85
91
  import { canQueueRetainedAsyncFollowUp, steerAsyncRun } from "./async-steering-action.ts";
86
92
  import {
87
93
  resolveWorkflowForegroundSteeringTarget,
88
94
  steerWorkflowForegroundTarget,
95
+ steerWorkflowRun,
89
96
  } from "./workflow-foreground-steering.ts";
90
97
  import { stopAsyncRun } from "./async-stop-action.ts";
91
98
  import { dismissRecoveredWorkflow } from "./async-dismiss-action.ts";
92
99
  import { promotePausedWorkflowIfSettled, reconcileDetachedWorkflowChildCompletion } from "./workflow-detach-reconcile.ts";
93
100
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
94
101
  import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
95
- import { resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
102
+ import { fallbackResultPayloadPathForSessionRun, removeResultIndex, resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
96
103
  import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, inheritedNestedParentAddressOf, inheritedNestedRouteOf, resolveNestedAsyncDir, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedParentAddress, type NestedRoute, type NestedRunResolutionScope } from "../shared/nested-events.ts";
97
104
  import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
98
105
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
@@ -102,6 +109,7 @@ import { inspectSubagentStatus } from "../background/run-status.ts";
102
109
  import { getExternalJobProvider } from "../../api/external-job-provider.ts";
103
110
  import { externalJobFollowUpRequestDigest, externalJobFollowUpRequestId, externalJobFollowUpRunId, externalJobPromptDigest, externalJobStableJson } from "../shared/external-job-runner.ts";
104
111
  import { externalCliReceiptMetadata, normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
112
+ import { formatHerdrMachineRunnerUnsupported, resolveHerdrMachinePlacement } from "../shared/herdr-machine.ts";
105
113
  import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.ts";
106
114
  import { handleMissionAction, MISSION_ACTIONS } from "../../missions/actions.ts";
107
115
  import { attachMissionToLaunchResult, prepareMissionLaunch, writeMissionAsyncBinding, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
@@ -109,14 +117,16 @@ import { MissionNotFoundError, updateMission } from "../../missions/store.ts";
109
117
  import type { MissionWorkflowChildUpdate } from "../../missions/types.ts";
110
118
  import { createMissionWorkflowState } from "../../missions/workflow-state.ts";
111
119
  import { resolveAuthorityDecision } from "../../policy/authority.ts";
112
- import { handleHerdrInspectorAction, HERDR_INSPECTOR_ACTIONS } from "../../inspectors/herdr/actions.ts";
120
+ import { handleInspectorAction, INSPECTOR_ACTIONS } from "../../inspectors/actions.ts";
121
+ import { createBuiltinInspectorPlugins } from "../../inspectors/plugins.ts";
113
122
  import { handleHerdrProjectPaneAction, HERDR_PROJECT_PANE_ACTIONS } from "../../inspectors/herdr/project-panes.ts";
114
- import { previewSimpleWorkflowRun, runWorkflowScript, validateWorkflowScript, WorkflowScriptError, type WorkflowLanePlan, type WorkflowReceiptResumeReference, type WorkflowScriptChildResult, type WorkflowScriptTraceEntry, type WorkflowSteerOptions, type WorkflowSteerResult } from "../../workflows/scripted-workflow.ts";
123
+ import { previewSimpleWorkflowRun, runWorkflowScript, validateWorkflowScript, WorkflowScriptError, type WorkflowChildSettledNotification, type WorkflowLanePlan, type WorkflowReceiptResumeReference, type WorkflowScriptChildResult, type WorkflowScriptTraceEntry, type WorkflowSteerOptions, type WorkflowSteerResult } from "../../workflows/scripted-workflow.ts";
124
+ import { formatIncrementalChildCompletion, incrementalChildCompletionTriggersTurn } from "../background/notify.ts";
115
125
  import { executeWorkflowHostCommand, resolveWorkflowHostOutputClaimPath, type WorkflowHostCommandParams, type WorkflowHostCommandResult } from "../../workflows/host-command.ts";
116
- import { buildWorkflowReceipt, resolveWorkflowReceiptResumeEntry, writeWorkflowReceipt, type WorkflowReceipt, type WorkflowReceiptState } from "../../workflows/workflow-receipt.ts";
126
+ import { buildWorkflowReceipt, readWorkflowReceipt, workflowReceiptPath, resolveWorkflowReceiptResumeEntry, writeWorkflowReceipt, type WorkflowReceipt, type WorkflowReceiptState } from "../../workflows/workflow-receipt.ts";
117
127
  import { upsertHostStep, validHostStepNodes } from "../shared/host-step-status.ts";
118
128
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
119
- import { parseWorkflowChildSummary, workflowChildSummary } from "../../workflows/workflow-child-summary.ts";
129
+ import { parseWorkflowChildSummary, workflowChildProgress, workflowChildSummary } from "../../workflows/workflow-child-summary.ts";
120
130
  import { resolveWorkflowChatProgress, type WorkflowChatProgressProjection } from "../../workflows/chat-progress.ts";
121
131
  import { annotateWorkflowPreflightTrace, formatWorkflowPreflight, formatWorkflowPreflightWarnings, normalizeWorkflowPreflight, workflowPreflightWarnings } from "../../workflows/workflow-preflight.ts";
122
132
  import {
@@ -129,10 +139,14 @@ import {
129
139
  type WorkflowResourceAuthority,
130
140
  type WorkflowResourcePermit,
131
141
  } from "../../shared/workflow-child-permit.ts";
132
- import { resolveWorkflowResource } from "../../workflows/workflow-resources.ts";
142
+ import { deepFreezeWorkflowArgs, normalizeWorkflowArgs, resolveWorkflowResource } from "../../workflows/workflow-resources.ts";
143
+ import { stableJsonDigest } from "../../shared/launch-contract.ts";
133
144
  import {
134
145
  cleanupWorktrees,
135
146
  createWorktrees,
147
+ preflightWorktreeSource,
148
+ withWorktreeTransaction,
149
+ type WorktreeSetupProgress,
136
150
  diffWorktrees,
137
151
  formatWorktreeDiffSummary,
138
152
  type WorktreeSetup,
@@ -155,7 +169,7 @@ import {
155
169
  type ForegroundSteerInput,
156
170
  type ForegroundSteerOutcome,
157
171
  type ForegroundRunControl,
158
- type HostStepNodeV1,
172
+ type HostStepNode,
159
173
  type IntercomBridgeConfig,
160
174
  type IntercomEventBus,
161
175
  type JsonSchemaObject,
@@ -172,7 +186,7 @@ import {
172
186
  type ToolBudgetConfig,
173
187
  type Usage,
174
188
  type UsageBudgetConfig,
175
- type WorkflowResourceProvenanceV1,
189
+ type WorkflowResourceProvenance,
176
190
  type WorkflowGraphNode,
177
191
  type WorkflowGraphSnapshot,
178
192
  type WorkflowNodeStatus,
@@ -192,6 +206,7 @@ import {
192
206
  resolveMaxSubagentSpawnsPerRun,
193
207
  wrapForkTask,
194
208
  type ScheduleOrigin,
209
+ type SteeringTargetState,
195
210
  } from "../../shared/types.ts";
196
211
  import { deriveChildSessionName } from "../../shared/child-session-name.ts";
197
212
 
@@ -277,6 +292,7 @@ interface TaskParam {
277
292
  agent: string;
278
293
  task: string;
279
294
  cwd?: string;
295
+ machine?: string;
280
296
  count?: number;
281
297
  output?: string | boolean;
282
298
  outputMode?: "inline" | "file-only";
@@ -285,7 +301,7 @@ interface TaskParam {
285
301
  model?: string;
286
302
  fast?: boolean;
287
303
  skill?: string | string[] | boolean;
288
- outputSchema?: JsonSchemaObject;
304
+ outputSchema?: JsonSchemaObject | false;
289
305
  acceptance?: AcceptanceInput;
290
306
  agentContract?: AgentContract;
291
307
  toolBudget?: ToolBudgetConfig;
@@ -324,7 +340,7 @@ export interface SubagentParamsLike {
324
340
  workflowScriptPath?: string;
325
341
  globalConcurrencyLimit?: number;
326
342
  maxSubagentSpawnsPerRun?: number;
327
- preflight?: import("../../shared/types.ts").WorkflowPreflightV1;
343
+ preflight?: import("../../shared/types.ts").WorkflowPreflight;
328
344
  chatProgress?: "auto" | "off" | "live-card";
329
345
  isolation?: "none" | "worktree";
330
346
  step?: ChainStep;
@@ -361,6 +377,8 @@ export interface SubagentParamsLike {
361
377
  foregroundOnly?: boolean;
362
378
  timeoutMs?: number;
363
379
  maxRuntimeMs?: number;
380
+ /** Async runs only: steer the child to checkpoint and stop this many ms before the run deadline. */
381
+ checkpointBeforeDeadlineMs?: number;
364
382
  /** Optional hard per-tool-call timeout (ms). Known-fast tools also have a default. */
365
383
  toolTimeoutMs?: number;
366
384
  toolBudget?: ToolBudgetConfig;
@@ -370,6 +388,9 @@ export interface SubagentParamsLike {
370
388
  control?: ControlConfig;
371
389
  sessionDir?: string;
372
390
  cwd?: string;
391
+ machine?: string;
392
+ /** Internal: the typed cwd when a machine is set, kept as a remote path and never resolved locally. */
393
+ machineCwd?: string;
373
394
  maxOutput?: MaxOutputConfig;
374
395
  artifacts?: boolean;
375
396
  includeProgress?: boolean;
@@ -389,7 +410,7 @@ export interface SubagentParamsLike {
389
410
  /** Internal-only; not part of the public tool schema. Wired for single-run reads (chain steps use their own field). */
390
411
  reads?: string[] | false;
391
412
  outputMode?: "inline" | "file-only";
392
- outputSchema?: JsonSchemaObject;
413
+ outputSchema?: JsonSchemaObject | false;
393
414
  agentScope?: unknown;
394
415
  chainDir?: string;
395
416
  acceptance?: AcceptanceInput;
@@ -398,6 +419,7 @@ export interface SubagentParamsLike {
398
419
  at?: string;
399
420
  every?: string;
400
421
  sessionOnly?: boolean;
422
+ quiet?: boolean;
401
423
  on?: string | number;
402
424
  timezone?: string;
403
425
  overlap?: "skip";
@@ -435,9 +457,12 @@ interface ExecutorDeps {
435
457
  getSubagentSessionRoot: (parentSessionFile: string | null) => string;
436
458
  expandTilde: (p: string) => string;
437
459
  discoverAgents: (cwd: string, scope: AgentScope, preferredModelProvider?: string) => { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig; maxThinking?: AgentConfig["maxThinking"]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] };
460
+ onAgentsChanged?: () => void;
438
461
  allowMutatingManagementActions?: boolean;
439
462
  activateSupervisorTransport?: () => void;
463
+ findPendingAsks?: Parameters<typeof steerAsyncRun>[0]["findPendingAsks"];
440
464
  refreshResultDelivery?: () => void;
465
+ trackRetainedNestedRoute?: (rootRunId: string) => void;
441
466
  kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
442
467
  /** Set when this executor runs inside a child session; carries the runtime settings the host passes instead of environment variables. */
443
468
  childRuntime?: ChildRuntimeConfig;
@@ -457,7 +482,7 @@ function inheritedRunFanoutBudget(deps: Pick<ExecutorDeps, "childRuntime">): Run
457
482
 
458
483
  type ForkSessionFileForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean, modelOrigin?: ModelOrigin) => string | undefined;
459
484
  type PrepareForkSessionForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean, modelOrigin?: ModelOrigin) => Promise<void>;
460
- type ForkThinkingOverrideForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean, modelOrigin?: ModelOrigin) => AgentConfig["thinking"] | undefined;
485
+ type ThinkingOverrideForTask = () => AgentConfig["thinking"] | undefined;
461
486
 
462
487
  interface ExecutionContextData {
463
488
  params: SubagentParamsLike;
@@ -477,7 +502,7 @@ interface ExecutionContextData {
477
502
  sessionDirForIndex: (idx?: number) => string;
478
503
  sessionFileForIndex: (idx?: number) => string | undefined;
479
504
  sessionFileForTask: ForkSessionFileForTask;
480
- thinkingOverrideForTask: ForkThinkingOverrideForTask;
505
+ thinkingOverrideForTask: ThinkingOverrideForTask;
481
506
  artifactConfig: ArtifactConfig;
482
507
  artifactsDir: string;
483
508
  backgroundRequestedWhileClarifying: boolean;
@@ -494,6 +519,8 @@ interface ExecutionContextData {
494
519
  configToolTimeoutMs?: number;
495
520
  toolBudget?: ResolvedToolBudget;
496
521
  usageBudget?: UsageBudgetConfig;
522
+ /** Parent workflow owns this allowance; presence vetoes unverifiable child continuation. */
523
+ inheritedUsageBudget?: UsageBudgetConfig;
497
524
  allowZeroToolBudget?: boolean;
498
525
  configToolBudget?: ResolvedToolBudget;
499
526
  contextPolicy: AgentDefaultContextPolicy;
@@ -554,9 +581,16 @@ function permissionProfileTrustError(agent: AgentConfig, ctx: ExtensionContext,
554
581
  return `Agent '${agent.name}' selects permission profile '${agent.permissionProfile}' from project scope, but child cwd '${path.resolve(childCwd)}' does not match the trusted project cwd '${trustedCwd}'. Launch from the trusted project cwd and retry.`;
555
582
  }
556
583
 
557
- function removeForegroundControlIfIdle(state: SubagentState, runId: string): boolean {
584
+ export function removeForegroundControlIfIdle(state: SubagentState, runId: string, trackRetainedNestedRoute?: (rootRunId: string) => void): boolean {
558
585
  const control = state.foregroundControls.get(runId);
559
586
  if (control && (!foregroundSchedulingSettled(control) || (control.activeChildren?.size ?? 0) > 0)) return false;
587
+ if (control?.nestedRoute && trackRetainedNestedRoute) {
588
+ try {
589
+ if (retainLiveForegroundNestedRoute(state, control.nestedRoute)) trackRetainedNestedRoute(runId);
590
+ } catch (error) {
591
+ console.error(`Failed to retain live nested descendants for foreground run '${runId}':`, error);
592
+ }
593
+ }
560
594
  state.foregroundControls.delete(runId);
561
595
  if (state.lastForegroundControlId === runId) state.lastForegroundControlId = null;
562
596
  return true;
@@ -751,7 +785,7 @@ function foregroundChildActivityFromProgress(progress: SingleResult["progress"]
751
785
  };
752
786
  }
753
787
 
754
- function rememberForegroundRun(state: SubagentState, input: { runId: string; mode: "single" | "parallel" | "chain"; cwd: string; sessionId: string | null; results: SingleResult[]; params: SubagentParamsLike; effectiveOutput?: string | boolean; effectiveOutputMode: OutputMode; extensionBindings?: ExtensionBindings }): void {
788
+ function rememberForegroundRun(state: SubagentState, input: { modelResponseAliases?: Record<string, string[]>; runId: string; mode: "single" | "parallel" | "chain"; cwd: string; sessionId: string | null; results: SingleResult[]; params: SubagentParamsLike; effectiveOutput?: string | boolean; effectiveOutputMode: OutputMode; extensionBindings?: ExtensionBindings; requiredExtensions?: SteeringRecoveryDescriptor["requiredExtensions"] }): void {
755
789
  state.foregroundRuns ??= new Map();
756
790
  const previous = state.foregroundRuns.get(input.runId);
757
791
  const updatedAt = Date.now();
@@ -763,6 +797,7 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
763
797
  updatedAt,
764
798
  children: input.results.map((result, index) => {
765
799
  const resumeContract = omitUndefinedProperties({
800
+ modelResponseAliases: input.modelResponseAliases,
766
801
  outputSchema: input.params.outputSchema,
767
802
  agentContract: input.params.agentContract,
768
803
  acceptance: input.params.acceptance,
@@ -805,6 +840,7 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
805
840
  ...(result.permissionProfile ? { permissionProfile: result.permissionProfile } : {}),
806
841
  ...(result.launchContractDigest ? { launchContractDigest: result.launchContractDigest } : {}),
807
842
  ...(input.extensionBindings ? { extensionBindings: input.extensionBindings } : {}),
843
+ ...(input.requiredExtensions?.length ? { requiredExtensions: input.requiredExtensions } : {}),
808
844
  ...(result.launchResolvedExtensions ? { launchResolvedExtensions: result.launchResolvedExtensions } : {}),
809
845
  ...(result.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: result.runtimeAcknowledgedExtensions } : {}),
810
846
  ...(result.capabilityCeiling ? { capabilityCeiling: result.capabilityCeiling } : {}),
@@ -960,6 +996,7 @@ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: Subage
960
996
  ...(child.launchContractDigest ? { launchContractDigest: child.launchContractDigest } : {}),
961
997
  ...(child.resumeContract ? { resumeContract: child.resumeContract } : {}),
962
998
  ...(child.extensionBindings ? { extensionBindings: normalizeExtensionBindings(child.extensionBindings)!.value } : {}),
999
+ ...(child.requiredExtensions ? { requiredExtensions: child.requiredExtensions } : {}),
963
1000
  ...(child.capabilityCeiling ? { capabilityCeiling: child.capabilityCeiling } : {}),
964
1001
  };
965
1002
  }
@@ -1252,10 +1289,14 @@ function appendStepToAsyncChain(input: {
1252
1289
  };
1253
1290
  }
1254
1291
  const chain = [input.params.step];
1255
- const acceptanceErrors = validateExecutionAcceptance({ ...input.params, chain } as Parameters<typeof validateExecutionAcceptance>[0]);
1256
- if (acceptanceErrors.length > 0) {
1292
+ const validationParams = { ...input.params, chain } as SubagentParamsLike;
1293
+ const acceptancePolicyErrors = validateExecutionAcceptancePolicy(validationParams);
1294
+ const outputSchemaError = validateLaunchOutputSchemaOverrides(validationParams);
1295
+ const earlyErrors = [...acceptancePolicyErrors];
1296
+ if (outputSchemaError) earlyErrors.push(outputSchemaError);
1297
+ if (earlyErrors.length > 0) {
1257
1298
  return {
1258
- content: [{ type: "text", text: `Cannot append step: ${acceptanceErrors.join(" ")}` }],
1299
+ content: [{ type: "text", text: `Cannot append step: ${earlyErrors.join(" ")}` }],
1259
1300
  isError: true,
1260
1301
  details: { mode: "management", results: [] },
1261
1302
  };
@@ -1337,6 +1378,14 @@ function appendStepToAsyncChain(input: {
1337
1378
  const scope: AgentScope = resolveExecutionAgentScope(input.params.agentScope);
1338
1379
  const discoveredForAppend = input.deps.discoverAgents(input.requestCwd, scope, input.parentModel?.provider);
1339
1380
  const agents = discoveredForAppend.agents;
1381
+ const acceptanceErrors = validateExecutionAcceptance(projectEffectiveAcceptanceSchemas(validationParams, agents));
1382
+ if (acceptanceErrors.length > 0) {
1383
+ return {
1384
+ content: [{ type: "text", text: `Cannot append step: ${acceptanceErrors.join(" ")}` }],
1385
+ isError: true,
1386
+ details: { mode: "management", results: [] },
1387
+ };
1388
+ }
1340
1389
  const contextPolicy = resolveExplicitContextPolicy(input.params);
1341
1390
  const chainSkillInput = normalizeSkillInput(input.params.skill);
1342
1391
  const chainSkills = chainSkillInput === false ? [] : (chainSkillInput ?? []);
@@ -1351,6 +1400,7 @@ function appendStepToAsyncChain(input: {
1351
1400
  modelScope: discoveredForAppend.modelScope,
1352
1401
  projectTrusted: currentProjectTrusted(input.ctx),
1353
1402
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
1403
+ modelResponseAliases: input.deps.config.modelResponseAliases,
1354
1404
  interactive: input.ctx.hasUI,
1355
1405
  permissions: input.deps.config.permissions,
1356
1406
  childRuntime: input.deps.childRuntime,
@@ -1719,7 +1769,7 @@ async function resumeExternalJobFollowUp(input: {
1719
1769
  ...input.baseAgentConfig,
1720
1770
  runner: { type: "external-job", provider: runner.provider, options: runner.options },
1721
1771
  };
1722
- const result = executeAsyncSingle(runId, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
1772
+ const result = await executeAsyncSingle(runId, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
1723
1773
  agent: input.target.agent,
1724
1774
  task: input.followUp,
1725
1775
  goal: input.followUp,
@@ -1733,6 +1783,7 @@ async function resumeExternalJobFollowUp(input: {
1733
1783
  currentModelProvider: parentModel?.provider,
1734
1784
  currentModel: parentModel,
1735
1785
  modelScope: input.modelScope,
1786
+ modelResponseAliases: input.deps.config.modelResponseAliases,
1736
1787
  interactive: input.ctx.hasUI,
1737
1788
  permissions: input.deps.config.permissions,
1738
1789
  childRuntime: input.deps.childRuntime,
@@ -1768,6 +1819,28 @@ async function resumeExternalJobFollowUp(input: {
1768
1819
  return externalJobFollowUpStarted({ sourceRunId: input.target.runId, runId: result.details.asyncId ?? runId, asyncDir: result.details.asyncDir ?? asyncDir, interactive: input.ctx.hasUI });
1769
1820
  }
1770
1821
 
1822
+ function resolveRequestedResumeTarget(params: SubagentParamsLike, deps: ExecutorDeps, parentSessionFile: string | null): ResumeSourceTarget | { kind: "live-nested"; target: ResolvedSubagentRunId & { kind: "nested" } } {
1823
+ const requestedId = params.id ?? params.runId;
1824
+ let resolved: ResolvedSubagentRunId | undefined;
1825
+ try {
1826
+ resolved = requestedId ? resolveSubagentRunId(requestedId, omitUndefinedProperties({ state: deps.state, nested: nestedResolutionScopeForExecutor(deps) })) : undefined;
1827
+ } catch (error) {
1828
+ const message = error instanceof Error ? error.message : "";
1829
+ const asyncMatches = message.match(/async:/g)?.length ?? 0;
1830
+ if (!isResumeAmbiguity(error) || !message.includes("foreground:") || asyncMatches !== 1) throw error;
1831
+ }
1832
+ if (resolved?.kind === "nested") {
1833
+ if (params.chain?.length) throw new Error("Attaching a running subagent as a chain root is currently available for top-level async runs only.");
1834
+ if (resolved.match.run.state === "running" || resolved.match.run.state === "queued") return { kind: "live-nested", target: resolved };
1835
+ const trustedSessionRoots = [
1836
+ ...(deps.config.defaultSessionDir ? [path.resolve(deps.expandTilde(deps.config.defaultSessionDir))] : []),
1837
+ ...(parentSessionFile ? [deps.getSubagentSessionRoot(parentSessionFile)] : []),
1838
+ ];
1839
+ return resolveNestedResumeTarget(resolved, trustedSessionRoots);
1840
+ }
1841
+ return resolveResumeTarget(params, deps.state, { asyncRequireSessionFile: false });
1842
+ }
1843
+
1771
1844
  async function resumeAsyncRun(input: {
1772
1845
  params: SubagentParamsLike;
1773
1846
  requestCwd: string;
@@ -1793,47 +1866,22 @@ async function resumeAsyncRun(input: {
1793
1866
  details: { mode: "management", results: [] },
1794
1867
  };
1795
1868
  }
1796
- const acceptanceErrors = validateExecutionAcceptance(input.params as Parameters<typeof validateExecutionAcceptance>[0]);
1797
- if (acceptanceErrors.length > 0) {
1798
- return {
1799
- content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }],
1800
- isError: true,
1801
- details: { mode: "management", results: [] },
1802
- };
1869
+ const acceptancePolicyErrors = validateExecutionAcceptancePolicy(input.params);
1870
+ if (acceptancePolicyErrors.length > 0) {
1871
+ return { content: [{ type: "text", text: `Cannot resume: ${acceptancePolicyErrors.join(" ")}` }], isError: true, details: { mode: "management", results: [] } };
1872
+ }
1873
+ const outputSchemaError = validateLaunchOutputSchemaOverrides(input.params);
1874
+ if (outputSchemaError) {
1875
+ return { content: [{ type: "text", text: `Cannot resume: ${outputSchemaError}` }], isError: true, details: { mode: "management", results: [] } };
1803
1876
  }
1804
1877
  input.deps.state.currentSessionId = resolveCurrentSessionId(input.ctx.sessionManager);
1805
1878
 
1806
1879
  let target: ResumeSourceTarget;
1807
1880
  const parentSessionFile = input.ctx.sessionManager.getSessionFile() ?? null;
1808
1881
  try {
1809
- const requestedId = input.params.id ?? input.params.runId;
1810
- let resolved: ResolvedSubagentRunId | undefined;
1811
- try {
1812
- resolved = requestedId ? resolveSubagentRunId(requestedId, omitUndefinedProperties({ state: input.deps.state, nested: nestedResolutionScopeForExecutor(input.deps) })) : undefined;
1813
- } catch (error) {
1814
- const message = error instanceof Error ? error.message : "";
1815
- const asyncMatches = message.match(/async:/g)?.length ?? 0;
1816
- if (!isResumeAmbiguity(error) || !message.includes("foreground:") || asyncMatches !== 1) throw error;
1817
- }
1818
- if (resolved?.kind === "nested") {
1819
- if (attachChain) {
1820
- return {
1821
- content: [{ type: "text", text: "Attaching a running subagent as a chain root is currently available for top-level async runs only." }],
1822
- isError: true,
1823
- details: { mode: "management", results: [] },
1824
- };
1825
- }
1826
- if (resolved.match.run.state === "running" || resolved.match.run.state === "queued") {
1827
- return resumeLiveNestedRun({ target: resolved, message: followUp });
1828
- }
1829
- const trustedSessionRoots = [
1830
- ...(input.deps.config.defaultSessionDir ? [path.resolve(input.deps.expandTilde(input.deps.config.defaultSessionDir))] : []),
1831
- ...(parentSessionFile ? [input.deps.getSubagentSessionRoot(parentSessionFile)] : []),
1832
- ];
1833
- target = resolveNestedResumeTarget(resolved, trustedSessionRoots);
1834
- } else {
1835
- target = resolveResumeTarget(input.params, input.deps.state, { asyncRequireSessionFile: false });
1836
- }
1882
+ const resolved = resolveRequestedResumeTarget(input.params, input.deps, parentSessionFile);
1883
+ if (resolved.kind === "live-nested") return resumeLiveNestedRun({ target: resolved.target, message: followUp });
1884
+ target = resolved;
1837
1885
  } catch (error) {
1838
1886
  const message = error instanceof Error ? error.message : String(error);
1839
1887
  return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
@@ -1941,6 +1989,10 @@ async function resumeAsyncRun(input: {
1941
1989
  details: { mode: "chain", results: [] },
1942
1990
  };
1943
1991
  }
1992
+ const acceptanceErrors = validateExecutionAcceptance(projectEffectiveAcceptanceSchemas(input.params, agents));
1993
+ if (acceptanceErrors.length > 0) {
1994
+ return { content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }], isError: true, details: { mode: "chain", results: [] } };
1995
+ }
1944
1996
  const runId = randomUUID();
1945
1997
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
1946
1998
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
@@ -1988,8 +2040,9 @@ async function resumeAsyncRun(input: {
1988
2040
  modelScope,
1989
2041
  projectTrusted: currentProjectTrusted(input.ctx),
1990
2042
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
1991
- interactive: input.ctx.hasUI,
1992
- permissions: input.deps.config.permissions,
2043
+ modelResponseAliases: input.deps.config.modelResponseAliases,
2044
+ interactive: input.ctx.hasUI,
2045
+ permissions: input.deps.config.permissions,
1993
2046
  childRuntime: input.deps.childRuntime,
1994
2047
  }),
1995
2048
  availableModels,
@@ -2010,6 +2063,7 @@ async function resumeAsyncRun(input: {
2010
2063
  worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
2011
2064
  worktreeBaseDir: input.deps.config.worktreeBaseDir,
2012
2065
  baseRef: input.params.baseRef ?? target.recoveryDescriptor?.baseRef,
2066
+ ...(recoveryDescriptor?.requiredExtensions ? { requiredExtensions: recoveryDescriptor.requiredExtensions } : {}),
2013
2067
  worktreeProvider: input.deps.config.worktreeProvider,
2014
2068
  worktreeBranchPrefix: input.deps.config.worktreeBranchPrefix,
2015
2069
  controlConfig: resolveControlConfig(input.deps.config.control, input.params.control),
@@ -2049,6 +2103,23 @@ async function resumeAsyncRun(input: {
2049
2103
  if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
2050
2104
  return { content: [{ type: "text", text: "Cannot resume with baseRef: retained managed-worktree children continue in their existing worktree. Start a new worktree run from that base ref instead." }], isError: true, details: { mode: "management", results: [] } };
2051
2105
  }
2106
+ const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
2107
+ const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
2108
+ const foregroundContract = target.source === "foreground" ? target.resumeContract : undefined;
2109
+ const outputSchema = Object.hasOwn(input.params, "outputSchema")
2110
+ ? input.params.outputSchema
2111
+ : Object.hasOwn(foregroundContract ?? {}, "outputSchema")
2112
+ ? foregroundContract?.outputSchema
2113
+ : recoveryDescriptor?.structuredOutputSchema;
2114
+ const acceptance = input.params.acceptance !== undefined
2115
+ ? input.params.acceptance
2116
+ : foregroundContract?.acceptance !== undefined
2117
+ ? foregroundContract.acceptance
2118
+ : recoveryDescriptor?.acceptance;
2119
+ const acceptanceErrors = validateExecutionAcceptance({ ...input.params, acceptance, outputSchema });
2120
+ if (acceptanceErrors.length > 0) {
2121
+ return { content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }], isError: true, details: { mode: "management", results: [] } };
2122
+ }
2052
2123
  const runId = randomUUID();
2053
2124
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
2054
2125
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
@@ -2072,17 +2143,13 @@ async function resumeAsyncRun(input: {
2072
2143
  if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "single", results: [], activeAsyncCapacity: error.snapshot } };
2073
2144
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "single", results: [] } };
2074
2145
  }
2075
- const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
2076
- const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
2077
- const foregroundContract = target.source === "foreground" ? target.resumeContract : undefined;
2078
- const outputSchema = input.params.outputSchema ?? foregroundContract?.outputSchema ?? recoveryDescriptor?.structuredOutputSchema;
2079
2146
  const agentContract = input.params.agentContract ?? foregroundContract?.agentContract ?? recoveryDescriptor?.agentContract;
2080
2147
  const artifactConfig: ArtifactConfig = recoveryDescriptor?.artifactConfig ?? omitUndefinedProperties({ ...DEFAULT_ARTIFACT_CONFIG, enabled: input.params.artifacts !== false, dir: input.deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir });
2081
2148
  const artifactsDir = recoveryDescriptor?.artifactsDir ?? getArtifactsDir(parentSessionFile, effectiveCwd, artifactConfig.dir);
2082
2149
  const availableModels = input.ctx.modelRegistry.getAvailable().map(toModelInfo);
2083
2150
  const parentModel = input.parentModel;
2084
2151
  const revivalAsyncDir = path.join(DIRS.async, runId);
2085
- const result = executeAsyncSingle(runId, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
2152
+ const result = await executeAsyncSingle(runId, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
2086
2153
  agent: target.agent,
2087
2154
  task: buildRevivedAsyncTask(target as Parameters<typeof buildRevivedAsyncTask>[0], effectiveFollowUp),
2088
2155
  goal: effectiveFollowUp,
@@ -2099,6 +2166,8 @@ async function resumeAsyncRun(input: {
2099
2166
  modelScope,
2100
2167
  projectTrusted: currentProjectTrusted(input.ctx),
2101
2168
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2169
+ // Absence in the retained contract is meaningful; never acquire current aliases.
2170
+ modelResponseAliases: recoveryDescriptor ? recoveryDescriptor.modelResponseAliases : foregroundContract?.modelResponseAliases,
2102
2171
  interactive: input.ctx.hasUI,
2103
2172
  permissions: input.deps.config.permissions,
2104
2173
  childRuntime: input.deps.childRuntime,
@@ -2125,6 +2194,7 @@ async function resumeAsyncRun(input: {
2125
2194
  thinkingOverride: recoveryDescriptor?.thinking ?? target.thinking,
2126
2195
  thinkingCeiling: recoveryDescriptor?.thinkingCeiling ?? ("thinkingCeiling" in target ? target.thinkingCeiling : undefined),
2127
2196
  extensionBindings: recoveryDescriptor?.extensionBindings ?? ("extensionBindings" in target ? target.extensionBindings : undefined),
2197
+ requiredExtensions: recoveryDescriptor?.requiredExtensions ?? (target as { requiredExtensions?: SteeringRecoveryDescriptor["requiredExtensions"] }).requiredExtensions,
2128
2198
  outputBaseDir: resolveSingleRunOutputBaseDir(input.deps, artifactsDir, runId),
2129
2199
  maxSubagentDepth: recoveryDescriptor?.maxSubagentDepth ?? resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime),
2130
2200
  waitToolEnabled: input.deps.waitToolEnabled,
@@ -2146,10 +2216,11 @@ async function resumeAsyncRun(input: {
2146
2216
  availableModels,
2147
2217
  output: input.params.output !== undefined ? input.params.output : foregroundContract?.output ?? recoveryDescriptor?.outputPath,
2148
2218
  outputMode: input.params.outputMode ?? foregroundContract?.outputMode ?? recoveryDescriptor?.outputMode,
2219
+ outputClaimPath: input.params.workflowOutputClaimPath,
2149
2220
  ...(agentContract ? { agentContract } : {}),
2150
2221
  ...(outputSchema ? { structuredOutputSchema: outputSchema } : {}),
2151
2222
  ...(recoveryDescriptor?.skills ? { skills: [...recoveryDescriptor.skills] } : {}),
2152
- ...(input.params.acceptance !== undefined ? { acceptance: input.params.acceptance } : foregroundContract?.acceptance !== undefined ? { acceptance: foregroundContract.acceptance } : recoveryDescriptor?.acceptance !== undefined ? { acceptance: recoveryDescriptor.acceptance } : {}),
2223
+ ...(acceptance !== undefined ? { acceptance } : {}),
2153
2224
  ...(input.params.timeoutMs !== undefined ? { timeoutMs: input.params.timeoutMs } : {}),
2154
2225
  ...(input.absoluteDeadlineAt !== undefined ? { absoluteDeadlineAt: input.absoluteDeadlineAt } : {}),
2155
2226
  ...(input.params.toolBudget !== undefined ? { toolBudget: input.params.toolBudget } : {}),
@@ -2198,7 +2269,7 @@ async function resumeAsyncRun(input: {
2198
2269
  } finally {
2199
2270
  input.signal?.removeEventListener("abort", stopOnAbort);
2200
2271
  }
2201
- fs.rmSync(resultPath, { force: true });
2272
+ if (completed.importedPublication) removeWorkflowAwaitedResult(asyncDir, resultPath, revivedId, completed.importedPublication);
2202
2273
  const usage = importedAsyncRootUsage(completed);
2203
2274
  const childResult: SingleResult = {
2204
2275
  index: 0,
@@ -2214,14 +2285,14 @@ async function resumeAsyncRun(input: {
2214
2285
  ...(completed.stopped ? { stopped: true } : {}),
2215
2286
  ...(completed.sessionFile ? { sessionFile: completed.sessionFile } : {}),
2216
2287
  ...(completed.model ? { model: completed.model } : {}),
2217
- ...(completed.attemptedModels ? { attemptedModels: completed.attemptedModels } : {}),
2218
- ...(completed.modelAttempts ? { modelAttempts: completed.modelAttempts } : {}),
2288
+ ...(completed.requestedModel ? { requestedModel: completed.requestedModel } : {}),
2219
2289
  ...(completed.contextOverflow ? { contextOverflow: true } : {}),
2220
2290
  ...(completed.structuredOutput !== undefined ? { structuredOutput: completed.structuredOutput } : {}),
2221
2291
  ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
2222
2292
  ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
2223
2293
  ...(completed.acceptance ? { acceptance: completed.acceptance } : {}),
2224
2294
  ...(completed.artifactPaths ? { artifactPaths: completed.artifactPaths } : {}),
2295
+ ...(completed.savedOutputPath ? { savedOutputPath: completed.savedOutputPath } : {}),
2225
2296
  ...(completed.outputSaveError ? { outputSaveError: completed.outputSaveError } : {}),
2226
2297
  ...(completed.transcriptPath ? { transcriptPath: completed.transcriptPath } : {}),
2227
2298
  ...(completed.transcriptError ? { transcriptError: completed.transcriptError } : {}),
@@ -2423,6 +2494,8 @@ function canonicalizeExecutionParams(params: SubagentParamsLike, agents: AgentCo
2423
2494
  params = omitUndefinedProperties({ ...params, agent: result.name });
2424
2495
  const agent = agents.find((candidate) => candidate.name === result.name);
2425
2496
  if (params.extensionBindings !== undefined && (agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job")) return { error: `extensionBindings is not supported for runner.type='${agent.runner.type}'.` };
2497
+ const machineError = agent ? formatHerdrMachineRunnerUnsupported({ machine: params.machine ?? agent.machine, agentName: agent.name, runnerType: agent.runner?.type, adapter: agent.runner?.type === "external-cli" ? agent.runner.adapter : undefined, worktree: params.worktree }) : undefined;
2498
+ if (machineError) return { error: machineError };
2426
2499
  }
2427
2500
  if (params.extensionBindings !== undefined) {
2428
2501
  try {
@@ -2475,6 +2548,18 @@ function canonicalizeExecutionParams(params: SubagentParamsLike, agents: AgentCo
2475
2548
  return { params };
2476
2549
  }
2477
2550
 
2551
+ function projectEffectiveAcceptanceSchemas(params: SubagentParamsLike, agents: AgentConfig[]): SubagentParamsLike {
2552
+ const withEffectiveSchema = <T extends { agent: string; outputSchema?: JsonSchemaObject | false }>(step: T): T => {
2553
+ const agent = agents.find((candidate) => candidate.name === step.agent);
2554
+ return agent ? { ...step, outputSchema: resolveEffectiveOutputSchema(agent, step.outputSchema) } : step;
2555
+ };
2556
+ return {
2557
+ ...params,
2558
+ ...(params.tasks ? { tasks: params.tasks.map(withEffectiveSchema) } : {}),
2559
+ ...(params.chain ? { chain: projectChainOutputSchemas(params.chain, agents) as ChainStep[] } : {}),
2560
+ };
2561
+ }
2562
+
2478
2563
  function validateExecutionInput(
2479
2564
  params: SubagentParamsLike,
2480
2565
  agents: AgentConfig[],
@@ -2497,7 +2582,7 @@ function validateExecutionInput(
2497
2582
  };
2498
2583
  }
2499
2584
 
2500
- const acceptanceErrors = validateExecutionAcceptance(params as Parameters<typeof validateExecutionAcceptance>[0]);
2585
+ const acceptanceErrors = validateExecutionAcceptance(projectEffectiveAcceptanceSchemas(params, agents));
2501
2586
  if (acceptanceErrors.length > 0) {
2502
2587
  return {
2503
2588
  content: [{ type: "text", text: acceptanceErrors.join(" ") }],
@@ -2749,6 +2834,7 @@ function applySingleAgentLaunchDefaults(params: SubagentParamsLike, agents: Agen
2749
2834
  const parentTimeoutMs = params.timeoutMs === undefined && params.maxRuntimeMs === undefined && agent.defaultTimeoutMs === undefined && params.workflowParentDeadlineAt !== undefined
2750
2835
  ? Math.max(1, params.workflowParentDeadlineAt - Date.now())
2751
2836
  : undefined;
2837
+ const outputSchema = params.outputSchema === false ? false : resolveEffectiveOutputSchema(agent, params.outputSchema);
2752
2838
  return {
2753
2839
  ...params,
2754
2840
  ...(params.async === undefined && agent.defaultAsync !== undefined ? { async: agent.defaultAsync } : {}),
@@ -2759,9 +2845,28 @@ function applySingleAgentLaunchDefaults(params: SubagentParamsLike, agents: Agen
2759
2845
  ...(params.acceptance === undefined && agent.defaultAcceptance !== undefined
2760
2846
  ? { acceptance: agent.defaultAcceptance }
2761
2847
  : {}),
2848
+ ...(outputSchema !== undefined ? { outputSchema } : {}),
2762
2849
  };
2763
2850
  }
2764
2851
 
2852
+ function validateLaunchOutputSchemaOverrides(params: SubagentParamsLike): string | undefined {
2853
+ const values: unknown[] = [params.outputSchema, ...(params.tasks ?? []).map((task) => task.outputSchema)];
2854
+ for (const step of params.chain ?? []) {
2855
+ if (isParallelStep(step)) values.push(...step.parallel.map((task) => task.outputSchema));
2856
+ else if (isDynamicParallelStep(step)) values.push(step.parallel.outputSchema);
2857
+ else values.push(step.outputSchema);
2858
+ }
2859
+ for (const value of values) {
2860
+ if (value === undefined || value === false) continue;
2861
+ try {
2862
+ assertJsonSchemaObject(value, "outputSchema");
2863
+ } catch (error) {
2864
+ return error instanceof Error ? error.message : String(error);
2865
+ }
2866
+ }
2867
+ return undefined;
2868
+ }
2869
+
2765
2870
  export const DEFAULT_FOREGROUND_TIMEOUT_MS = 30 * 60 * 1000;
2766
2871
 
2767
2872
  // Async single-agent runs also need a wall-clock backstop: a child whose bash
@@ -2925,24 +3030,20 @@ function withResolvedContext(
2925
3030
  }
2926
3031
 
2927
3032
  function withAggregatedToolUsage(result: AgentToolResult<Details>): AgentToolResult<Details> {
2928
- if (result.details.results.length === 0) return result;
2929
- const usage = sumResultsUsage(result.details.results);
3033
+ const highWarnings = result.details.results.flatMap((child) => child.watchdog?.warnings?.filter((warning) => warning.importance === "high") ?? []);
3034
+ const projected: AgentToolResult<Details> = {
3035
+ ...result,
3036
+ ...(highWarnings.length ? { content: [...result.content, { type: "text", text: ["High-importance watchdog findings:", ...highWarnings.map((warning) => `- ${warning.severity}: ${warning.summary}\n Evidence: ${warning.evidence}\n Recommended action: ${warning.recommendedAction}`)].join("\n") }] } : {}),
3037
+ details: {
3038
+ ...result.details,
3039
+ results: result.details.results.map((child) => ({ ...child, ...(child.watchdog ? { watchdog: childWatchdogProgressForModel(child.watchdog) } : {}) })),
3040
+ },
3041
+ };
3042
+ if (projected.details.results.length === 0) return projected;
3043
+ const usage = sumResultsUsage(projected.details.results);
2930
3044
  return usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0
2931
- ? { ...result, usage: toAgentToolUsage(usage) }
2932
- : result;
2933
- }
2934
-
2935
- function withForkThinkingNotes(
2936
- result: AgentToolResult<Details>,
2937
- downgrades: Map<number, string>,
2938
- ): AgentToolResult<Details> {
2939
- if (downgrades.size === 0) return result;
2940
- const children = [...downgrades.entries()]
2941
- .sort(([a], [b]) => a - b)
2942
- .map(([index, agent]) => `${agent} (child ${index})`)
2943
- .join(", ");
2944
- const note = `Note: fork context forced thinking off for ${children}. The forked transcript contained signed Anthropic thinking blocks that were sanitized, and Anthropic children cannot resume such a transcript with thinking enabled. Use context: "fresh" when an Anthropic child needs thinking.`;
2945
- return { ...result, content: [...result.content, { type: "text", text: note }] };
3045
+ ? { ...projected, usage: toAgentToolUsage(usage) }
3046
+ : projected;
2946
3047
  }
2947
3048
 
2948
3049
  function toExecutionErrorResult(params: SubagentParamsLike, error: unknown, contextSummary?: ContextSummary): AgentToolResult<Details> {
@@ -2968,7 +3069,7 @@ function resolveStaticLaunchSummary(input: {
2968
3069
  availableModels: ModelInfo[];
2969
3070
  currentProvider?: string;
2970
3071
  modelScope?: ModelScopeConfig;
2971
- thinkingOverrideForTask: ForkThinkingOverrideForTask;
3072
+ thinkingOverrideForTask: ThinkingOverrideForTask;
2972
3073
  }): StaticLaunchSummary {
2973
3074
  const agentConfig = input.agents.find((agent) => agent.name === input.agent);
2974
3075
  const externalRunner = agentConfig?.runner?.type === "external-cli" || agentConfig?.runner?.type === "external-job";
@@ -2983,7 +3084,7 @@ function resolveStaticLaunchSummary(input: {
2983
3084
  agentConfig?.modelProvider ?? input.currentProvider,
2984
3085
  modelScopes.length === 0 ? {} : { scope: modelScopes },
2985
3086
  );
2986
- const thinkingOverride = externalRunner ? undefined : input.thinkingOverrideForTask(input.agent, input.index, model);
3087
+ const thinkingOverride = externalRunner ? undefined : input.thinkingOverrideForTask();
2987
3088
  const thinking = externalRunner ? undefined : resolveEffectiveThinking(model, thinkingOverride ?? agentConfig?.thinking);
2988
3089
  return {
2989
3090
  agent: input.agent,
@@ -3000,7 +3101,7 @@ function collectStaticLaunchSummaries(input: {
3000
3101
  availableModels: ModelInfo[];
3001
3102
  currentProvider?: string;
3002
3103
  modelScope?: ModelScopeConfig;
3003
- thinkingOverrideForTask: ForkThinkingOverrideForTask;
3104
+ thinkingOverrideForTask: ThinkingOverrideForTask;
3004
3105
  dynamicFanoutMaxItems?: number;
3005
3106
  }): StaticLaunchSummary[] {
3006
3107
  const summary = (agent: string, index: number, explicitModel?: string) => resolveStaticLaunchSummary({
@@ -3154,6 +3255,15 @@ function importedAsyncRootUsage(completed: Awaited<ReturnType<typeof waitForImpo
3154
3255
  };
3155
3256
  }
3156
3257
 
3258
+ function removeWorkflowAwaitedResult(asyncDir: string, resultPath: string, runId: string, publication: NonNullable<Awaited<ReturnType<typeof waitForImportedAsyncRoot>>["importedPublication"]>): void {
3259
+ try {
3260
+ fs.rmSync(resultPath, { force: true });
3261
+ } catch {
3262
+ // Payload cleanup must not replace an already imported delivery.
3263
+ }
3264
+ removeResultIndex(asyncDir, publication.sessionId, runId, publication.toolCallId);
3265
+ }
3266
+
3157
3267
  async function waitForWorkflowAsyncSingleResult(
3158
3268
  params: SubagentParamsLike,
3159
3269
  launchResult: AgentToolResult<Details>,
@@ -3174,7 +3284,7 @@ async function waitForWorkflowAsyncSingleResult(
3174
3284
  } finally {
3175
3285
  options.signal?.removeEventListener("abort", stopOnAbort);
3176
3286
  }
3177
- fs.rmSync(resultPath, { force: true });
3287
+ if (completed.importedPublication) removeWorkflowAwaitedResult(asyncDir, resultPath, options.runId, completed.importedPublication);
3178
3288
  const usage = importedAsyncRootUsage(completed);
3179
3289
  const childResult: SingleResult = omitUndefinedProperties({
3180
3290
  index: 0,
@@ -3190,14 +3300,14 @@ async function waitForWorkflowAsyncSingleResult(
3190
3300
  ...(completed.stopped ? { stopped: true } : {}),
3191
3301
  ...(completed.sessionFile ? { sessionFile: completed.sessionFile } : {}),
3192
3302
  ...(completed.model ? { model: completed.model } : {}),
3193
- ...(completed.attemptedModels ? { attemptedModels: completed.attemptedModels } : {}),
3194
- ...(completed.modelAttempts ? { modelAttempts: completed.modelAttempts } : {}),
3303
+ ...(completed.requestedModel ? { requestedModel: completed.requestedModel } : {}),
3195
3304
  ...(completed.contextOverflow ? { contextOverflow: true } : {}),
3196
3305
  ...(completed.structuredOutput !== undefined ? { structuredOutput: completed.structuredOutput } : {}),
3197
3306
  ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
3198
3307
  ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
3199
3308
  ...(completed.acceptance ? { acceptance: completed.acceptance } : {}),
3200
3309
  ...(completed.artifactPaths ? { artifactPaths: completed.artifactPaths } : {}),
3310
+ ...(completed.savedOutputPath ? { savedOutputPath: completed.savedOutputPath } : {}),
3201
3311
  ...(completed.outputSaveError ? { outputSaveError: completed.outputSaveError } : {}),
3202
3312
  ...(completed.transcriptPath ? { transcriptPath: completed.transcriptPath } : {}),
3203
3313
  ...(completed.transcriptError ? { transcriptError: completed.transcriptError } : {}),
@@ -3257,7 +3367,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3257
3367
  modelScope: data.modelScope,
3258
3368
  projectTrusted: currentProjectTrusted(ctx),
3259
3369
  ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3260
- interactive: ctx.hasUI,
3370
+ modelResponseAliases: deps.config.modelResponseAliases, interactive: ctx.hasUI,
3261
3371
  permissions: deps.config.permissions,
3262
3372
  childRuntime: deps.childRuntime,
3263
3373
  });
@@ -3317,7 +3427,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3317
3427
  const modelOverrideFromParent = modelOrigin === "inherited";
3318
3428
  const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: a.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
3319
3429
  if (launchRuleError) return toExecutionErrorResult(params, new Error(launchRuleError), data.contextPolicy.contextSummary);
3320
- const asyncResult = executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
3430
+ const asyncResult = await executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
3321
3431
  agent: params.agent!,
3322
3432
  task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(params.task ?? "") : (params.task ?? ""),
3323
3433
  goal: params.task ?? "",
@@ -3327,6 +3437,8 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3327
3437
  availableModels,
3328
3438
  cwd: effectiveCwd,
3329
3439
  requestedCwd: data.requestedCwd,
3440
+ machine: params.machine,
3441
+ machineCwd: params.machineCwd,
3330
3442
  maxOutput: params.maxOutput,
3331
3443
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3332
3444
  artifactConfig,
@@ -3345,7 +3457,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3345
3457
  fast: params.fast,
3346
3458
  modelOverrideFromParent,
3347
3459
  modelOrigin,
3348
- thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
3460
+ thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(),
3349
3461
  thinkingCeiling: a.maxThinking,
3350
3462
  maxSubagentDepth,
3351
3463
  waitToolEnabled: deps.waitToolEnabled,
@@ -3363,7 +3475,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3363
3475
  childIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(agent, index) : undefined,
3364
3476
  nestedRoute,
3365
3477
  agentContract: params.agentContract,
3366
- structuredOutputSchema: params.outputSchema,
3478
+ structuredOutputSchema: params.outputSchema || undefined,
3367
3479
  extensionBindings: params.extensionBindings,
3368
3480
  acceptance: params.acceptance,
3369
3481
  timeoutMs: data.timeoutMs,
@@ -3371,6 +3483,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3371
3483
  usageBudget: data.usageBudget,
3372
3484
  configToolBudget: data.configToolBudget,
3373
3485
  toolTimeoutMs: data.params?.toolTimeoutMs,
3486
+ checkpointBeforeDeadlineMs: data.params?.checkpointBeforeDeadlineMs ?? deps.config.checkpointBeforeDeadlineMs,
3374
3487
  configToolTimeoutMs: data.configToolTimeoutMs,
3375
3488
  capabilityCeiling: data.capabilityCeiling,
3376
3489
  runFanoutBudget: data.runFanoutBudget,
@@ -3385,8 +3498,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3385
3498
  return null;
3386
3499
  }
3387
3500
 
3388
- function createSingleWorktreeSetup(
3389
- enabled: boolean | undefined,
3501
+ async function createSingleWorktreeSetup(
3390
3502
  cwd: string,
3391
3503
  runId: string,
3392
3504
  agent: string,
@@ -3398,12 +3510,13 @@ function createSingleWorktreeSetup(
3398
3510
  branchPrefix: ExtensionConfig["worktreeBranchPrefix"],
3399
3511
  label?: string,
3400
3512
  task?: string,
3401
- beforeCreate?: (setup: WorktreeSetup) => void,
3402
- ): { setup?: WorktreeSetup; errorResult?: AgentToolResult<Details> } {
3403
- if (!enabled) return {};
3513
+ onProgress?: (snapshot: WorktreeSetupProgress) => void,
3514
+ signal?: AbortSignal,
3515
+ deadlineAt?: number,
3516
+ ): Promise<{ setup?: WorktreeSetup; errorResult?: AgentToolResult<Details> }> {
3404
3517
  try {
3405
3518
  return {
3406
- setup: createWorktrees(cwd, runId, 1, omitUndefinedProperties({
3519
+ setup: await createWorktrees(cwd, runId, 1, omitUndefinedProperties({
3407
3520
  agents: [agent],
3408
3521
  setupHook: setupHook
3409
3522
  ? { hookPath: setupHook, ...(setupHookTimeoutMs === undefined ? {} : { timeoutMs: setupHookTimeoutMs }) }
@@ -3414,7 +3527,9 @@ function createSingleWorktreeSetup(
3414
3527
  branchPrefix,
3415
3528
  labels: [label],
3416
3529
  tasks: [task],
3417
- beforeCreate,
3530
+ onProgress,
3531
+ signal,
3532
+ deadlineAt,
3418
3533
  })),
3419
3534
  };
3420
3535
  } catch (error) {
@@ -3440,15 +3555,6 @@ function resolveSingleRunOutputBaseDir(deps: ExecutorDeps, artifactsDir: string,
3440
3555
  return resolveConfiguredSingleRunOutputBaseDir(deps) ?? path.join(artifactsDir, "outputs", sanitizeRunPathSegment(runId));
3441
3556
  }
3442
3557
 
3443
- function resolveWorkflowAggregateOutputPath(
3444
- output: string | boolean | undefined,
3445
- ctxCwd: string,
3446
- workflowCwd: string,
3447
- outputBaseDir: string,
3448
- ): string | undefined {
3449
- return resolveSingleOutputPath(output, ctxCwd, workflowCwd, outputBaseDir);
3450
- }
3451
-
3452
3558
  function workflowChildDefaultOutput(aggregateOutputPath: string | undefined, artifactsDir: string, workflowRunId: string, workflowKey: string): string {
3453
3559
  if (aggregateOutputPath) {
3454
3560
  const parsed = path.parse(aggregateOutputPath);
@@ -3496,6 +3602,23 @@ function appendWorkflowOutputWarning(text: string, warning: string | undefined):
3496
3602
  return warning ? `${text}\n\n${warning}` : text;
3497
3603
  }
3498
3604
 
3605
+ export function resolveWorkflowChildLocalCwd(input: {
3606
+ workflowCwd: string;
3607
+ discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3608
+ agents: AgentConfig[];
3609
+ workflowAgentScope?: unknown;
3610
+ params: Record<string, unknown>;
3611
+ }): string {
3612
+ if (input.params.machine !== undefined) return input.workflowCwd;
3613
+ if (typeof input.params.agent === "string") {
3614
+ const agentScope = resolveExecutionAgentScope(input.params.agentScope ?? input.workflowAgentScope);
3615
+ const workflowAgents = input.discoverAgents(input.workflowCwd, agentScope).agents;
3616
+ const agent = resolveAgentName(input.params.agent, workflowAgents).agent ?? resolveAgentName(input.params.agent, input.agents).agent;
3617
+ if (agent?.machine !== undefined) return input.workflowCwd;
3618
+ }
3619
+ return typeof input.params.cwd === "string" ? resolveChildCwd(input.workflowCwd, input.params.cwd) : input.workflowCwd;
3620
+ }
3621
+
3499
3622
  function resolveWorkflowChildOutputPath(input: {
3500
3623
  ctxCwd: string;
3501
3624
  workflowCwd: string;
@@ -3510,7 +3633,9 @@ function resolveWorkflowChildOutputPath(input: {
3510
3633
  key: string;
3511
3634
  params: Record<string, unknown>;
3512
3635
  }): { path?: string; inherited: boolean } {
3513
- if (typeof input.params.resume === "string") {
3636
+ const rawOutput = input.params.output;
3637
+ const hasExplicitOutput = typeof rawOutput === "string" || typeof rawOutput === "boolean";
3638
+ if (typeof input.params.resume === "string" && (!hasExplicitOutput || rawOutput === true || rawOutput === "true")) {
3514
3639
  if (!input.state) return { path: undefined, inherited: false };
3515
3640
  const index = input.params.index;
3516
3641
  const target = resolveResumeTarget({
@@ -3519,15 +3644,16 @@ function resolveWorkflowChildOutputPath(input: {
3519
3644
  }, input.state);
3520
3645
  return { path: "recoveryDescriptor" in target ? target.recoveryDescriptor?.outputPath : undefined, inherited: false };
3521
3646
  }
3522
- const rawOutput = input.params.output;
3523
- const hasExplicitOutput = typeof rawOutput === "string" || typeof rawOutput === "boolean";
3524
- const childCwd = typeof input.params.cwd === "string" ? resolveChildCwd(input.workflowCwd, input.params.cwd) : input.workflowCwd;
3525
- const agentScope = resolveExecutionAgentScope(input.params.agentScope ?? input.workflowAgentScope);
3526
- const discoveredAgents = input.discoverAgents(childCwd, agentScope).agents;
3527
- const agent = typeof input.params.agent === "string"
3528
- ? resolveAgentName(input.params.agent, discoveredAgents).agent ?? resolveAgentName(input.params.agent, input.agents).agent
3529
- : undefined;
3530
- const agentOutput = typeof agent?.output === "string" ? agent.output : undefined;
3647
+ const childCwd = resolveWorkflowChildLocalCwd(input);
3648
+ let agentOutput: string | undefined;
3649
+ if (rawOutput === true || rawOutput === "true" || (!hasExplicitOutput && !input.aggregateOutputPath)) {
3650
+ const agentScope = resolveExecutionAgentScope(input.params.agentScope ?? input.workflowAgentScope);
3651
+ const discoveredAgents = input.discoverAgents(childCwd, agentScope).agents;
3652
+ const agent = typeof input.params.agent === "string"
3653
+ ? resolveAgentName(input.params.agent, discoveredAgents).agent ?? resolveAgentName(input.params.agent, input.agents).agent
3654
+ : undefined;
3655
+ agentOutput = typeof agent?.output === "string" ? agent.output : undefined;
3656
+ }
3531
3657
  const output = rawOutput === true || rawOutput === "true"
3532
3658
  ? agentOutput
3533
3659
  : hasExplicitOutput
@@ -3616,11 +3742,11 @@ function prepareWorkflowChildLaunchParams(input: {
3616
3742
  childParams = { ...input.childParams, output: input.outputOverride };
3617
3743
  } else if (usesDefaultOutput && input.aggregateOutputPath !== undefined) {
3618
3744
  childParams = { ...input.childParams, output: workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.parentWorkflowRunId, input.workflowKey) };
3619
- } else if (input.childParams.resume === undefined) {
3745
+ } else if (input.childParams.resume === undefined || input.childParams.output !== undefined) {
3620
3746
  const resolvedOutput = resolveWorkflowChildOutputPath({ ctxCwd: input.ctxCwd, workflowCwd: input.workflowCwd, artifactsDir: input.artifactsDir, workflowRunId: input.parentWorkflowRunId, aggregateOutputPath: input.aggregateOutputPath, configuredOutputBaseDir: input.configuredOutputBaseDir, discoverAgents: input.discoverAgents, agents: input.agents, workflowAgentScope: input.workflowAgentScope, key: input.workflowKey, params: input.childParams });
3621
3747
  if (resolvedOutput.path) childParams = { ...input.childParams, output: resolvedOutput.path };
3622
3748
  }
3623
- const childCwd = typeof childParams.cwd === "string" ? resolveChildCwd(input.workflowCwd, childParams.cwd) : input.workflowCwd;
3749
+ const childCwd = resolveWorkflowChildLocalCwd({ ...input, params: childParams });
3624
3750
  const agentScope = resolveExecutionAgentScope(childParams.agentScope ?? input.workflowAgentScope);
3625
3751
  const discoveredAgents = input.discoverAgents(childCwd, agentScope).agents;
3626
3752
  const agent = typeof childParams.agent === "string"
@@ -3630,7 +3756,7 @@ function prepareWorkflowChildLaunchParams(input: {
3630
3756
  return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, { ...input.options, externalAsyncRequired, outputClaimPath: input.outputClaimPath });
3631
3757
  }
3632
3758
 
3633
- function finalizeSingleWorktreeHandoff(input: {
3759
+ async function finalizeSingleWorktreeHandoff(input: {
3634
3760
  worktreeSetup: WorktreeSetup;
3635
3761
  artifactsDir: string;
3636
3762
  runId: string;
@@ -3639,55 +3765,78 @@ function finalizeSingleWorktreeHandoff(input: {
3639
3765
  result: SingleResult;
3640
3766
  workflowKey?: string;
3641
3767
  lane?: import("../../shared/types.ts").WorkflowLaneMetadata;
3642
- }): { suffix: string; reference?: NonNullable<Details["parallelHandoff"]> } {
3643
- const diffsDir = path.join(input.artifactsDir, "worktree-diffs", input.runId);
3644
- const diffs = diffWorktrees(input.worktreeSetup, [input.agent], diffsDir);
3645
- const diffSummary = formatWorktreeDiffSummary(diffs);
3646
- const manifestPath = parallelHandoffPath(input.artifactsDir, input.runId);
3647
- const handoff = {
3648
- manifestPath,
3649
- runId: input.runId,
3650
- mode: "single" as const,
3651
- source: "foreground" as const,
3652
- cwd: input.cwd,
3653
- stepIndex: 0,
3654
- flatStartIndex: 0,
3655
- setup: input.worktreeSetup,
3656
- laneBindings: input.workflowKey || input.lane ? [{ index: 0, taskIndex: 0, ...(input.workflowKey ? { workflowKey: input.workflowKey } : {}), runId: input.workflowKey ? input.runId : undefined, ...(input.lane ? { lane: input.lane } : {}) }] : undefined,
3657
- diffs,
3658
- results: [{
3659
- agent: input.result.agent,
3660
- ...(input.workflowKey ? { workflowKey: input.workflowKey } : {}),
3661
- ...(input.workflowKey ? { runId: input.runId } : {}),
3662
- ...(input.lane ? { lane: input.lane } : {}),
3663
- status: resolveSubagentResultStatus(omitUndefinedProperties({
3664
- exitCode: input.result.exitCode,
3665
- interrupted: input.result.interrupted,
3666
- detached: input.result.detached,
3667
- state: input.result.stopped ? "stopped" : undefined,
3668
- processSignal: input.result.processSignal,
3669
- timedOut: input.result.timedOut,
3670
- stopped: input.result.stopped,
3671
- turnBudgetExceeded: input.result.turnBudgetExceeded,
3672
- })),
3673
- summary: resultSummaryForIntercom(input.result),
3674
- ...(input.result.artifactPaths?.outputPath ? { outputPath: input.result.artifactPaths.outputPath } : {}),
3675
- ...(input.result.structuredOutput !== undefined ? { structuredOutput: input.result.structuredOutput } : {}),
3676
- ...(input.result.structuredOutputPath ? { structuredOutputPath: input.result.structuredOutputPath } : {}),
3677
- ...(input.result.sessionFile ? { sessionPath: input.result.sessionFile } : {}),
3678
- }],
3679
- };
3768
+ }): Promise<{ suffix: string; reference?: NonNullable<Details["parallelHandoff"]> }> {
3769
+ let admitted = false;
3680
3770
  try {
3681
- writeParallelHandoffGroup(handoff);
3682
- const cleanup = cleanupWorktrees(input.worktreeSetup, { kind: "preserve", capturedDiffs: diffs, handoffManifestPath: manifestPath });
3683
- const reference = writeParallelHandoffGroup({ ...handoff, cleanup });
3684
- return {
3685
- suffix: [diffSummary, formatParallelHandoffReference(reference)].filter(Boolean).join("\n\n"),
3686
- reference,
3687
- };
3771
+ return await withWorktreeTransaction(() => {
3772
+ admitted = true;
3773
+ const diffsDir = path.join(input.artifactsDir, "worktree-diffs", input.runId);
3774
+ const diffs = diffWorktrees(input.worktreeSetup, [input.agent], diffsDir);
3775
+ const diffSummary = formatWorktreeDiffSummary(diffs);
3776
+ const manifestPath = parallelHandoffPath(input.artifactsDir, input.runId);
3777
+ const handoff = {
3778
+ manifestPath,
3779
+ runId: input.runId,
3780
+ mode: "single" as const,
3781
+ source: "foreground" as const,
3782
+ cwd: input.cwd,
3783
+ stepIndex: 0,
3784
+ flatStartIndex: 0,
3785
+ setup: input.worktreeSetup,
3786
+ laneBindings: input.workflowKey || input.lane ? [{ index: 0, taskIndex: 0, ...(input.workflowKey ? { workflowKey: input.workflowKey } : {}), runId: input.workflowKey ? input.runId : undefined, ...(input.lane ? { lane: input.lane } : {}) }] : undefined,
3787
+ diffs,
3788
+ results: [{
3789
+ agent: input.result.agent,
3790
+ ...(input.workflowKey ? { workflowKey: input.workflowKey } : {}),
3791
+ ...(input.workflowKey ? { runId: input.runId } : {}),
3792
+ ...(input.lane ? { lane: input.lane } : {}),
3793
+ status: resolveSubagentResultStatus(omitUndefinedProperties({
3794
+ exitCode: input.result.exitCode,
3795
+ interrupted: input.result.interrupted,
3796
+ detached: input.result.detached,
3797
+ state: input.result.stopped ? "stopped" : undefined,
3798
+ processSignal: input.result.processSignal,
3799
+ timedOut: input.result.timedOut,
3800
+ stopped: input.result.stopped,
3801
+ turnBudgetExceeded: input.result.turnBudgetExceeded,
3802
+ })),
3803
+ summary: resultSummaryForIntercom(input.result),
3804
+ ...(input.result.artifactPaths?.outputPath ? { outputPath: input.result.artifactPaths.outputPath } : {}),
3805
+ ...(input.result.structuredOutput !== undefined ? { structuredOutput: input.result.structuredOutput } : {}),
3806
+ ...(input.result.structuredOutputPath ? { structuredOutputPath: input.result.structuredOutputPath } : {}),
3807
+ ...(input.result.sessionFile ? { sessionPath: input.result.sessionFile } : {}),
3808
+ }],
3809
+ };
3810
+ try {
3811
+ writeParallelHandoffGroup(handoff);
3812
+ const cleanup = cleanupWorktrees(input.worktreeSetup, { kind: "preserve", capturedDiffs: diffs, handoffManifestPath: manifestPath });
3813
+ const reference = writeParallelHandoffGroup({ ...handoff, cleanup });
3814
+ return {
3815
+ suffix: [diffSummary, formatParallelHandoffReference(reference)].filter(Boolean).join("\n\n"),
3816
+ reference,
3817
+ };
3818
+ } catch (error) {
3819
+ return { suffix: [diffSummary, formatParallelHandoffError(error)].filter(Boolean).join("\n\n") };
3820
+ }
3821
+ });
3688
3822
  } catch (error) {
3689
- return { suffix: [diffSummary, formatParallelHandoffError(error)].filter(Boolean).join("\n\n") };
3690
- }
3823
+ if (admitted) throw error;
3824
+ const reference = retainSingleWorktreeHandoff(input, error);
3825
+ return { suffix: `${formatParallelHandoffError(error)}\n\n${formatParallelHandoffReference(reference)}`, reference };
3826
+ }
3827
+ }
3828
+
3829
+ function retainSingleWorktreeHandoff(input: { worktreeSetup: WorktreeSetup; artifactsDir: string; runId: string; cwd: string }, error: unknown): NonNullable<Details["parallelHandoff"]> {
3830
+ const reason = `Worktree finalization retained; manual reconciliation required: ${error instanceof Error ? error.message : String(error)}`;
3831
+ return writeParallelHandoffGroup({
3832
+ manifestPath: parallelHandoffPath(input.artifactsDir, input.runId), runId: input.runId,
3833
+ mode: "single", source: "foreground", cwd: input.cwd, stepIndex: 0, flatStartIndex: 0,
3834
+ setup: input.worktreeSetup, diffs: [], results: [],
3835
+ cleanup: { state: "partial", pruned: false, errors: [reason], tasks: input.worktreeSetup.worktrees.map((worktree) => ({
3836
+ index: worktree.index, path: worktree.path, branch: worktree.branch, provider: worktree.provider, naming: worktree.naming,
3837
+ worktreeRemoved: false, branchRemoved: false, preserved: true, reason,
3838
+ })) },
3839
+ });
3691
3840
  }
3692
3841
 
3693
3842
  async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Promise<AgentToolResult<Details>> {
@@ -3729,6 +3878,12 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3729
3878
  details: { mode: "single", results: [] },
3730
3879
  };
3731
3880
  }
3881
+ let foregroundMachine: import("../../shared/types.ts").HerdrMachineReference | undefined;
3882
+ const requestedMachine = params.machine ?? agentConfig.machine;
3883
+ if (requestedMachine) {
3884
+ try { foregroundMachine = resolveHerdrMachinePlacement({ machine: requestedMachine, cwd: ctx.cwd, stepCwd: params.machineCwd }).machine; }
3885
+ catch (error) { return toExecutionErrorResult(params, error instanceof Error ? error : new Error(String(error)), data.contextPolicy.contextSummary); }
3886
+ }
3732
3887
  const effectiveToolBudget = resolveEffectiveToolBudget(omitUndefinedProperties({ runBudget: data.toolBudget, agentBudget: agentConfig.toolBudget, configBudget: data.configToolBudget }));
3733
3888
  if (effectiveToolBudget.error) return toExecutionErrorResult(params, new Error(effectiveToolBudget.error), data.contextPolicy.contextSummary);
3734
3889
 
@@ -3766,10 +3921,9 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3766
3921
  const maxSubagentDepth = resolveChildMaxSubagentDepth(currentMaxSubagentDepth, agentConfig.maxSubagentDepth);
3767
3922
 
3768
3923
 
3769
- const sourceCwd = effectiveCwd;
3924
+ const sourceCwd = foregroundMachine?.cwd ?? effectiveCwd;
3770
3925
  let pendingHandoff: Details["parallelHandoff"];
3771
- const { setup: worktreeSetup, errorResult: worktreeSetupError } = createSingleWorktreeSetup(
3772
- params.worktree,
3926
+ const { setup: worktreeSetup, errorResult: worktreeSetupError } = params.worktree ? await createSingleWorktreeSetup(
3773
3927
  sourceCwd,
3774
3928
  runId,
3775
3929
  params.agent!,
@@ -3781,8 +3935,8 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3781
3935
  deps.config.worktreeBranchPrefix,
3782
3936
  params.lane?.key ?? params.workflowKey,
3783
3937
  task,
3784
- (plannedSetup) => {
3785
- pendingHandoff = writePendingParallelHandoff({
3938
+ (progress) => {
3939
+ pendingHandoff = writeWorktreeSetupHandoff({
3786
3940
  manifestPath: parallelHandoffPath(artifactsDir, runId),
3787
3941
  runId,
3788
3942
  mode: "single",
@@ -3790,12 +3944,20 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3790
3944
  cwd: sourceCwd,
3791
3945
  stepIndex: 0,
3792
3946
  flatStartIndex: 0,
3793
- setup: plannedSetup,
3947
+ progress,
3794
3948
  laneBindings: params.workflowKey || lane ? [{ index: 0, taskIndex: 0, ...(params.workflowKey ? { workflowKey: params.workflowKey, runId } : {}), ...(lane ? { lane } : {}) }] : undefined,
3795
3949
  });
3796
3950
  },
3797
- );
3798
- if (worktreeSetupError) return worktreeSetupError;
3951
+ signal,
3952
+ data.deadlineAt,
3953
+ ) : {};
3954
+ if (worktreeSetupError) {
3955
+ if (pendingHandoff) {
3956
+ worktreeSetupError.details!.parallelHandoff = pendingHandoff;
3957
+ worktreeSetupError.content.push({ type: "text", text: formatParallelHandoffReference(pendingHandoff) });
3958
+ }
3959
+ return worktreeSetupError;
3960
+ }
3799
3961
  const singleCwd = worktreeSetup?.worktrees[0]?.agentCwd ?? sourceCwd;
3800
3962
  const sandboxTrustError = sandboxProfileTrustError(agentConfig, ctx, singleCwd);
3801
3963
  if (sandboxTrustError) {
@@ -3807,6 +3969,27 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3807
3969
  if (worktreeSetup) cleanupWorktrees(worktreeSetup);
3808
3970
  return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }], isError: true, details: { mode: "single", results: [] } };
3809
3971
  }
3972
+ const cleanupSingleWorktree = async () => {
3973
+ if (!worktreeSetup) return;
3974
+ let admitted = false;
3975
+ try { await withWorktreeTransaction(() => {
3976
+ if (data.deadlineAt !== undefined && Date.now() >= data.deadlineAt) throw new Error("Run deadline expired before unlaunched worktree cleanup");
3977
+ admitted = true;
3978
+ const cleanup = cleanupWorktrees(worktreeSetup);
3979
+ pendingHandoff = writeParallelHandoffGroup({
3980
+ manifestPath: parallelHandoffPath(artifactsDir, runId), runId, mode: "single", source: "foreground",
3981
+ cwd: sourceCwd, stepIndex: 0, flatStartIndex: 0, setup: worktreeSetup, diffs: [], results: [], cleanup,
3982
+ });
3983
+ }); }
3984
+ catch (error) {
3985
+ if (admitted) throw error;
3986
+ pendingHandoff = retainSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd }, error);
3987
+ }
3988
+ };
3989
+ if (worktreeSetup && (signal?.aborted || (data.deadlineAt !== undefined && Date.now() >= data.deadlineAt))) {
3990
+ await cleanupSingleWorktree();
3991
+ return { content: [{ type: "text", text: "Subagent setup canceled before child launch." }], isError: true, details: { mode: "single", results: [], parallelHandoff: pendingHandoff } };
3992
+ }
3810
3993
 
3811
3994
  const authoredTask = task;
3812
3995
  if (shouldForkAgent(contextPolicy, params.agent!)) {
@@ -3816,8 +3999,8 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3816
3999
  const outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, singleCwd, resolveSingleRunOutputBaseDir(deps, artifactsDir, runId));
3817
4000
  const validationError = validateFileOnlyOutputMode(effectiveOutputMode, outputPath, `Single run (${params.agent})`);
3818
4001
  if (validationError) {
3819
- if (worktreeSetup) cleanupWorktrees(worktreeSetup);
3820
- return { content: [{ type: "text", text: validationError }], isError: true, details: { mode: "single", results: [] } };
4002
+ await cleanupSingleWorktree();
4003
+ return { content: [{ type: "text", text: validationError }], isError: true, details: { mode: "single", results: [], parallelHandoff: pendingHandoff } };
3821
4004
  }
3822
4005
  const structuredRuntime = params.outputSchema
3823
4006
  ? createStructuredOutputRuntime(params.outputSchema, artifactConfig.enabled ? path.join(artifactsDir, "structured-output", runId) : undefined, { acceptanceReport: resolveAcceptanceReportMode(params.acceptance) })
@@ -3825,7 +4008,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3825
4008
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
3826
4009
  // absolute paths pass through; relative paths resolve against the child cwd.
3827
4010
  const reads = readsOverride !== undefined ? readsOverride : agentConfig.defaultReads ?? false;
3828
- const readPaths = Array.isArray(reads) ? resolveExistingReadPaths(reads, singleCwd) : [];
4011
+ const readPaths = !foregroundMachine && Array.isArray(reads) ? resolveExistingReadPaths(reads, singleCwd) : [];
3829
4012
  const readsInstruction = readPaths.length > 0
3830
4013
  ? `[Read from: ${readPaths.join(", ")}]\n\n`
3831
4014
  : "";
@@ -3843,7 +4026,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3843
4026
  let childSessionControls: ForegroundChildSessionControls | undefined;
3844
4027
  const foregroundControl = deps.state.foregroundControls.get(runId);
3845
4028
  if (foregroundControl) {
3846
- const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin));
4029
+ const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask());
3847
4030
  beginForegroundChild(foregroundControl, omitUndefinedProperties({
3848
4031
  index: 0,
3849
4032
  agent: params.agent!,
@@ -3875,8 +4058,11 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3875
4058
  }
3876
4059
  },
3877
4060
  }));
4061
+ // Capture the owned mailbox before a child can start and finish between polling ticks.
4062
+ if (deps.childRuntime?.fanoutChild) deps.activateSupervisorTransport?.();
3878
4063
  }
3879
4064
 
4065
+ const modelResponseAliases = deps.config.modelResponseAliases === undefined ? undefined : structuredClone(deps.config.modelResponseAliases);
3880
4066
  const forwardSingleUpdate = onUpdate
3881
4067
  ? (update: AgentToolResult<Details>) => {
3882
4068
  if (foregroundControl) updateForegroundChild(foregroundControl, 0, update.details?.progress?.[0]);
@@ -3885,6 +4071,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3885
4071
  : undefined;
3886
4072
 
3887
4073
  const deadlineAt = data.deadlineAt ?? (data.timeoutMs !== undefined ? Date.now() + data.timeoutMs : undefined);
4074
+ const requiredExtensions = deps.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(data.parentPiSessionId);
3888
4075
  let r: Awaited<ReturnType<typeof runSync>> | undefined;
3889
4076
  let resolveDetachedWorkflowChild: ((result: Awaited<ReturnType<typeof runSync>>) => void) | undefined;
3890
4077
  const detachedWorkflowChild = params.workflowAwaitDetached === true
@@ -3892,12 +4079,17 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3892
4079
  : undefined;
3893
4080
  try {
3894
4081
  const launched = await runSync(ctx.cwd, agents, params.agent!, task, compactOptional<Parameters<typeof runSync>[4]>({
4082
+ machine: foregroundMachine,
4083
+ parentProviderRegistry: ctx.modelRegistry,
4084
+ remoteReads: foregroundMachine ? readsOverride : undefined,
3895
4085
  permissions: deps.config.permissions,
3896
4086
  runtimeSnapshotHost: deps.pi,
4087
+ hostAvailableBuiltins: getHostBuiltinToolNames(deps.pi),
3897
4088
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
3898
4089
  projectTrusted: currentProjectTrusted(ctx),
3899
4090
  ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3900
- llmIntentArbiter: createTaskMutationArbiter(ctx),
4091
+ requiredExtensions,
4092
+ llmIntentArbiter: createTaskMutationArbiter({ model: ctx.model, modelRegistry: ctx.modelRegistry, sessionId: ctx.sessionManager.getSessionId() }),
3901
4093
  childRuntime: deps.childRuntime,
3902
4094
  onChildSession: (controls) => { childSessionControls = controls; },
3903
4095
  context: data.contextPolicy.contextForAgent(params.agent!),
@@ -3934,10 +4126,11 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3934
4126
  fast: params.fast,
3935
4127
  modelOverrideFromParent,
3936
4128
  modelOrigin,
3937
- thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
4129
+ thinkingOverride: thinkingOverrideForTask(),
3938
4130
  thinkingCeiling: agentConfig.maxThinking,
3939
4131
  extensionBindings: params.extensionBindings,
3940
4132
  availableModels,
4133
+ modelResponseAliases,
3941
4134
  preferredModelProvider: currentProvider,
3942
4135
  modelScope: modelScopes,
3943
4136
  skills: effectiveSkills,
@@ -3950,14 +4143,14 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3950
4143
  onDetachReady: (detach) => {
3951
4144
  detachForeground = detach;
3952
4145
  },
3953
- onDetachedExit: (result) => {
4146
+ onDetachedExit: async (result) => {
3954
4147
  if (resolveDetachedWorkflowChild) {
3955
4148
  resolveDetachedWorkflowChild(result);
3956
4149
  return;
3957
4150
  }
3958
4151
  try {
3959
4152
  if (worktreeSetup) {
3960
- finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result, workflowKey: params.workflowKey, lane });
4153
+ await finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result, workflowKey: params.workflowKey, lane });
3961
4154
  }
3962
4155
  try {
3963
4156
  updateRememberedForegroundChild(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, index: 0, result, events: deps.pi.events, notify: true });
@@ -3982,7 +4175,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3982
4175
  try {
3983
4176
  if (foregroundControl) finishForegroundChild(foregroundControl, 0);
3984
4177
  } finally {
3985
- removeForegroundControlIfIdle(deps.state, runId);
4178
+ removeForegroundControlIfIdle(deps.state, runId, deps.trackRetainedNestedRoute);
3986
4179
  }
3987
4180
  }
3988
4181
  }
@@ -3993,12 +4186,13 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3993
4186
  toolTimeoutMs: params.toolTimeoutMs,
3994
4187
  configToolTimeoutMs: data.configToolTimeoutMs,
3995
4188
  toolBudget: effectiveToolBudget.toolBudget,
4189
+ usageBudget: data.usageBudget ?? data.inheritedUsageBudget,
3996
4190
  capabilityCeiling: data.capabilityCeiling,
3997
4191
  allowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,
3998
4192
  }));
3999
4193
  r = launched.detached && detachedWorkflowChild ? await detachedWorkflowChild : launched;
4000
4194
  } catch (error) {
4001
- if (worktreeSetup) cleanupWorktrees(worktreeSetup);
4195
+ await cleanupSingleWorktree();
4002
4196
  throw error;
4003
4197
  } finally {
4004
4198
  // An attached runSync rejection still owns its child and structured runtime.
@@ -4013,11 +4207,11 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4013
4207
  recordRun(params.agent!, cleanTask, r.exitCode, r.progressSummary?.durationMs ?? 0, r);
4014
4208
  }
4015
4209
 
4016
- let worktreeHandoff: ReturnType<typeof finalizeSingleWorktreeHandoff> | undefined;
4210
+ let worktreeHandoff: Awaited<ReturnType<typeof finalizeSingleWorktreeHandoff>> | undefined;
4017
4211
  if (worktreeSetup) {
4018
4212
  worktreeHandoff = r.detached
4019
4213
  ? { suffix: pendingHandoff ? formatParallelHandoffReference(pendingHandoff) : "", reference: pendingHandoff }
4020
- : finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result: r, workflowKey: params.workflowKey, lane });
4214
+ : await finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result: r, workflowKey: params.workflowKey, lane });
4021
4215
  }
4022
4216
 
4023
4217
  if (r.progress) allProgress.push(r.progress);
@@ -4055,7 +4249,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4055
4249
  usageBudget: usageBudgetState(data.usageBudget, totalCost),
4056
4250
  ...(worktreeHandoff?.reference ? { parallelHandoff: worktreeHandoff.reference } : {}),
4057
4251
  }));
4058
- rememberForegroundRun(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: details.results, params, effectiveOutput, effectiveOutputMode, extensionBindings: params.extensionBindings });
4252
+ rememberForegroundRun(deps.state, { modelResponseAliases, runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: details.results, params, effectiveOutput, effectiveOutputMode, extensionBindings: params.extensionBindings, requiredExtensions });
4059
4253
 
4060
4254
  const suppressRoutineResultIntercom = shouldSuppressRoutineResultIntercom({ suppressRoutineResultIntercom: params.suppressRoutineResultIntercom, results: [r] });
4061
4255
  if (!r.detached && !r.interrupted && !suppressRoutineResultIntercom) {
@@ -4131,6 +4325,7 @@ function duplicateSubagentCallResult(params: SubagentParamsLike): AgentToolResul
4131
4325
  }
4132
4326
 
4133
4327
  const workflowLaunchObservers = new WeakMap<object, (launch: { agent: string; sessionName?: string; sessionFile?: string; async: boolean; runId?: string }) => void>();
4328
+ const workflowOwnedUsageBudgets = new WeakMap<object, UsageBudgetConfig>();
4134
4329
 
4135
4330
  /**
4136
4331
  * Terminal-mission retention can remove a mission while its children still
@@ -4211,9 +4406,13 @@ function workflowChildResult(
4211
4406
  ? result.details.results[0].finalOutput
4212
4407
  : receiptOutput;
4213
4408
  const childError = result.details.results.map((child) => child.error).find((error): error is string => Boolean(error));
4214
- const failureError = childError && receiptOutput && receiptOutput !== childError
4215
- ? `${childError}\n\n${receiptOutput}`
4409
+ const failureErrorBase = childError && receiptOutput
4410
+ ? receiptOutput.includes(childError) ? receiptOutput : `${childError}\n\n${receiptOutput}`
4216
4411
  : childError || receiptOutput || output || "Child run failed.";
4412
+ const savedOutputEvidence = [...new Set(result.details.results.map((child) => child.savedOutputPath).filter((value): value is string => Boolean(value)))]
4413
+ .filter((savedOutputPath) => !failureErrorBase.includes(savedOutputPath))
4414
+ .map((savedOutputPath) => `Saved output: ${savedOutputPath}`);
4415
+ const failureError = [failureErrorBase, ...savedOutputEvidence].join("\n");
4217
4416
  const detached = result.details.results.some((child) => child.detached);
4218
4417
  const interrupted = result.details.results.some((child) => child.interrupted);
4219
4418
  const stopped = result.details.results.some((child) => child.stopped);
@@ -4252,8 +4451,6 @@ function workflowChildResult(
4252
4451
  }
4253
4452
  const requestedContext = childParams.context === "fresh" || childParams.context === "fork" ? childParams.context : undefined;
4254
4453
  const resolvedContext = result.details.context ?? (resolvedContexts.length === 1 ? resolvedContexts[0] : resolvedContexts.length > 1 ? "mixed" : undefined);
4255
- const resumeSourceRunId = typeof childParams.resume === "string" && childParams.resume.trim() ? childParams.resume.trim() : undefined;
4256
- const continuationRunIds = [...new Set([resumeSourceRunId, runId].filter((value): value is string => Boolean(value)))];
4257
4454
  const outputReference = result.details.results.find((child) => child.savedOutputPath)?.savedOutputPath
4258
4455
  ?? result.details.results.find((child) => child.outputReference?.path)?.outputReference?.path;
4259
4456
  const outputPathMapping = typeof childParams.task === "string" ? outputPathMappingFromTask(childParams.task, outputReference) : undefined;
@@ -4286,7 +4483,7 @@ function workflowChildResult(
4286
4483
  ...(outputPathMapping ? { outputPathMapping } : {}),
4287
4484
  ...(externalAdapter ? { externalAdapter } : {}),
4288
4485
  resumability,
4289
- continuation: { runIds: continuationRunIds },
4486
+ continuation: { runIds: runId ? [runId] : [] },
4290
4487
  artifactPaths: [...artifactPaths],
4291
4488
  results: result.details.results,
4292
4489
  };
@@ -4399,10 +4596,33 @@ function missingWorkflowReceiptResumeHint(reference: WorkflowReceiptResumeRefere
4399
4596
  }
4400
4597
  }
4401
4598
 
4402
- function resolveKeyedWorkflowResume(
4403
- reference: WorkflowReceiptResumeReference,
4404
- state: SubagentState,
4405
- ): { runId: string; runIds: string[] } {
4599
+ function resolveWorkflowResume(
4600
+ reference: WorkflowReceiptResumeReference | string,
4601
+ deps: ExecutorDeps,
4602
+ parentSessionFile: string | null,
4603
+ index?: number,
4604
+ ): string | { runId: string; runIds: string[] } {
4605
+ const state = deps.state;
4606
+ if (typeof reference === "string") {
4607
+ const target = resolveRequestedResumeTarget({ id: reference.trim(), ...(index !== undefined ? { index } : {}) }, deps, parentSessionFile);
4608
+ // Live routing stays with action=resume and does not claim retained lineage.
4609
+ if (target.kind !== "revive") return reference.trim();
4610
+ const runId = target.runId;
4611
+ const status = target.source === "async" && target.asyncDir ? readStatus(target.asyncDir) : undefined;
4612
+ if (status?.runId === runId && status.parentWorkflowRunId && status.workflowKey) {
4613
+ // Only follow the validated child's recorded owner; never search other workflows.
4614
+ const receiptPath = workflowReceiptPath(DIRS.async, status.parentWorkflowRunId);
4615
+ try {
4616
+ fs.statSync(receiptPath);
4617
+ } catch (error) {
4618
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { runId, runIds: [runId] };
4619
+ throw error;
4620
+ }
4621
+ const entry = readWorkflowReceipt(DIRS.async, status.parentWorkflowRunId).entries[status.workflowKey];
4622
+ if (entry?.latestRunId === runId) return { runId, runIds: entry.continuation.runIds };
4623
+ }
4624
+ return { runId, runIds: [runId] };
4625
+ }
4406
4626
  try {
4407
4627
  const entry = resolveWorkflowReceiptResumeEntry({
4408
4628
  reference,
@@ -4412,9 +4632,7 @@ function resolveKeyedWorkflowResume(
4412
4632
  if (target.kind !== "revive") throw new Error(`Workflow receipt child '${reference.key}' latest run '${runId}' is still running.`);
4413
4633
  },
4414
4634
  });
4415
- const runId = entry.latestRunId;
4416
- if (!runId) throw new Error(`Workflow receipt child '${reference.key}' has no retained run id.`);
4417
- return { runId, runIds: entry.continuation.runIds };
4635
+ return { runId: entry.latestRunId, runIds: entry.continuation.runIds };
4418
4636
  } catch (error) {
4419
4637
  const workflowRunId = reference.workflowRunId.trim();
4420
4638
  if (isMissingWorkflowReceiptDiagnostic(error, workflowRunId)) {
@@ -4433,8 +4651,9 @@ function terminalWorkflowReceipt(
4433
4651
  terminalOutcome?: WorkflowTerminalOutcome,
4434
4652
  hostSteps?: WorkflowReceipt["hostSteps"],
4435
4653
  resource?: WorkflowReceipt["resource"],
4654
+ argsDigest?: string,
4436
4655
  ): WorkflowReceipt {
4437
- return buildWorkflowReceipt({ workflowRunId, state, children, workflowChildren, terminalOutcome, hostSteps, resource });
4656
+ return buildWorkflowReceipt({ workflowRunId, state, children, workflowChildren, terminalOutcome, hostSteps, resource, ...(argsDigest ? { argsDigest } : {}) });
4438
4657
  }
4439
4658
 
4440
4659
  function workflowFailureTerminalOutcome(error: unknown, _children: WorkflowScriptChildResult[], usageBudget: ReturnType<typeof usageBudgetState>): WorkflowTerminalOutcome | undefined {
@@ -4517,6 +4736,35 @@ export async function steerWorkflowChildByKey(input: {
4517
4736
  }
4518
4737
  }
4519
4738
 
4739
+ export async function preflightWorkflowWorktrees(input: {
4740
+ workflowDefaults: SubagentParamsLike;
4741
+ defaultWorktree?: boolean;
4742
+ calls: Array<{ key: string; params: Record<string, unknown> }>;
4743
+ ctxCwd: string;
4744
+ signal: AbortSignal;
4745
+ deadlineAt?: number;
4746
+ }): Promise<void> {
4747
+ const sources = new Map<string, string[]>();
4748
+ for (const { key, params } of input.calls) {
4749
+ // The workflow validates retained IDs/receipt references before admission; resolution follows it.
4750
+ if (params.resume !== undefined) continue;
4751
+ const effective = prepareWorkflowLaunchParams(input.workflowDefaults, params, "preflight", key);
4752
+ if ((effective.worktree ?? input.defaultWorktree) !== true) continue;
4753
+ // Match recursive execute's resolution, including relative default/child cwd.
4754
+ const cwd = resolveRequestedCwd(input.ctxCwd, effective.cwd);
4755
+ const keys = sources.get(cwd) ?? [];
4756
+ keys.push(key);
4757
+ sources.set(cwd, keys);
4758
+ }
4759
+ for (const [cwd, keys] of sources) {
4760
+ try { await preflightWorktreeSource(cwd, { signal: input.signal, deadlineAt: input.deadlineAt }); }
4761
+ catch (error) {
4762
+ throw new Error(`Worktree admission failed for ${keys.map((key) => `'${key}'`).join(", ")} at ${cwd}: ${error instanceof Error ? error.message : String(error)} Select the correct cwd or arrange an operator-approved commit/stash.`, { cause: error });
4763
+ }
4764
+ }
4765
+ input.signal.throwIfAborted();
4766
+ }
4767
+
4520
4768
  export function prepareWorkflowLaunchParams(
4521
4769
  workflowDefaults: SubagentParamsLike,
4522
4770
  childParams: Record<string, unknown>,
@@ -4551,9 +4799,9 @@ export function prepareWorkflowLaunchParams(
4551
4799
  const worktree = childParams.worktree ?? workflowDefaults.worktree;
4552
4800
  const baseRef = Object.hasOwn(childParams, "baseRef") ? childParams.baseRef : undefined;
4553
4801
  const outputSchema = Object.hasOwn(childParams, "outputSchema") ? childParams.outputSchema : workflowDefaults.outputSchema;
4554
- if (outputSchema !== undefined) assertJsonSchemaObject(outputSchema, "outputSchema");
4802
+ if (outputSchema !== undefined && outputSchema !== false) assertJsonSchemaObject(outputSchema, "outputSchema");
4555
4803
  const agentContract = Object.hasOwn(childParams, "agentContract") ? childParams.agentContract : workflowDefaults.agentContract;
4556
- if (agentContract !== undefined && !isAgentContractV1(agentContract as AgentContract)) throw new Error("agentContract must be { version: 1 }.");
4804
+ if (agentContract !== undefined && !isAgentContract(agentContract as AgentContract)) throw new Error("agentContract must be { version: 1 }.");
4557
4805
  const acceptance = Object.hasOwn(childParams, "acceptance") ? childParams.acceptance : workflowDefaults.acceptance;
4558
4806
  const output = Object.hasOwn(childParams, "output") ? childParams.output : workflowDefaults.output;
4559
4807
  if (output !== undefined && typeof output !== "string" && typeof output !== "boolean") throw new Error("output must be a path string or boolean.");
@@ -4567,10 +4815,11 @@ export function prepareWorkflowLaunchParams(
4567
4815
  message: typeof childParams.task === "string" ? childParams.task.trim() : "",
4568
4816
  workflowParentRunId: parentWorkflowRunId,
4569
4817
  workflowKey,
4818
+ ...(options.outputClaimPath ? { workflowOutputClaimPath: options.outputClaimPath } : {}),
4570
4819
  ...(lane ? { lane } : {}),
4571
4820
  ...(worktree !== undefined ? { worktree: worktree as boolean } : {}),
4572
4821
  ...(baseRef !== undefined ? { baseRef: baseRef as string } : {}),
4573
- ...(outputSchema !== undefined ? { outputSchema: outputSchema as JsonSchemaObject } : {}),
4822
+ ...(outputSchema !== undefined ? { outputSchema } : {}),
4574
4823
  ...(agentContract !== undefined ? { agentContract: agentContract as AgentContract } : {}),
4575
4824
  ...(acceptance !== undefined ? { acceptance: acceptance as AcceptanceInput } : {}),
4576
4825
  ...(output !== undefined ? { output: output as string | boolean } : {}),
@@ -4585,12 +4834,13 @@ export function prepareWorkflowLaunchParams(
4585
4834
  };
4586
4835
  }
4587
4836
  const control = mergeWorkflowControlOverrides(workflowDefaults.control, childParams.control as ControlConfig | undefined);
4837
+ const asyncOmitted = childParams.async === undefined && workflowDefaults.async === undefined;
4588
4838
  const launchParams = {
4589
4839
  ...workflowDefaults,
4590
- async: options.externalAsyncRequired === true && childParams.async === undefined && workflowDefaults.async === undefined ? true : false,
4840
+ ...(options.externalAsyncRequired === true && asyncOmitted ? { async: true } : {}),
4591
4841
  ...childParams,
4592
4842
  ...(control !== undefined ? { control } : {}),
4593
- ...(options.externalAsyncRequired === true && childParams.async === undefined && workflowDefaults.async === undefined ? { workflowAwaitAsync: true } : {}),
4843
+ ...(asyncOmitted ? { workflowAwaitAsync: true } : {}),
4594
4844
  ...(options.missionDetached ? { mission: false } : {}),
4595
4845
  workflowParentRunId: parentWorkflowRunId,
4596
4846
  workflowKey,
@@ -4728,14 +4978,14 @@ function applyWorkflowLaneTrace(graph: WorkflowGraphSnapshot, trace: WorkflowScr
4728
4978
  else delete graph.currentNodeId;
4729
4979
  }
4730
4980
 
4731
- function workflowChatProgressUpdate(
4981
+ function workflowProgressUpdate(
4732
4982
  runId: string,
4733
4983
  chatProgress: WorkflowChatProgressProjection,
4734
4984
  workflow: NonNullable<Details["workflow"]>,
4735
4985
  workflowChildren?: Details["workflowChildren"],
4736
- preflight?: import("../../shared/types.ts").WorkflowPreflightV1,
4737
- ): AgentToolResult<Details> | undefined {
4738
- if (chatProgress.mode !== "live-card") return undefined;
4986
+ preflight?: import("../../shared/types.ts").WorkflowPreflight,
4987
+ ): AgentToolResult<Details> {
4988
+ // chatProgress controls the TUI projection, not transport-level progress.
4739
4989
  return {
4740
4990
  content: [{ type: "text", text: "Workflow running." }],
4741
4991
  details: { mode: "workflow", runId, results: [], workflow, ...(preflight ? { preflight } : {}), ...(workflowChildren ? { workflowChildren } : {}), chatProgress },
@@ -4811,6 +5061,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4811
5061
  signal: AbortSignal,
4812
5062
  ctx: ExtensionContext,
4813
5063
  ) => Promise<AgentToolResult<Details>>;
5064
+ /** Scheduled state visible to the current runtime supervisor owner only. */
5065
+ getCurrentSupervisorOwnerStates: () => Iterable<SubagentState>;
4814
5066
  } {
4815
5067
  const delegatedThinkingOverrides = new WeakMap<object, AgentConfig["thinking"]>();
4816
5068
  const delegatedZeroToolBudgets = new WeakSet<object>();
@@ -4819,7 +5071,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4819
5071
  const workflowResourcePermits = new WeakMap<object, WorkflowResourcePermit>();
4820
5072
  const workflowPermitContexts = new WeakMap<object, { root: WorkflowChildPermit } | { child: WorkflowChildPermitContext }>();
4821
5073
  const warnedArtifactPackageDirs = new Set<string>();
4822
- const scheduledOwnerExecutors = new Map<string, ReturnType<typeof createSubagentExecutor>>();
5074
+ const scheduledOwnerExecutors = new Map<string | null, Map<string, { state: SubagentState; executor: ReturnType<typeof createSubagentExecutor> }>>();
4823
5075
  const execute = async (
4824
5076
  _id: string,
4825
5077
  params: SubagentParamsLike,
@@ -4830,6 +5082,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4830
5082
  parentModelOverride?: ParentModel | null,
4831
5083
  ): Promise<AgentToolResult<Details>> => {
4832
5084
  const workflowLaunchObserver = workflowLaunchObservers.get(params);
5085
+ const inheritedUsageBudget = workflowOwnedUsageBudgets.get(params);
4833
5086
  const delegatedThinkingOverride = delegatedThinkingOverrides.get(params);
4834
5087
  const allowZeroToolBudget = delegatedZeroToolBudgets.has(params);
4835
5088
  const delegatedExecution = delegatedExecutions.has(params);
@@ -4847,7 +5100,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4847
5100
  let requestParams = normalizedGate.params;
4848
5101
  const capacityOverrideError = validateWorkflowCapacityOverrides(requestParams);
4849
5102
  if (capacityOverrideError) return buildRequestedModeError(requestParams, capacityOverrideError);
4850
- let workflowPreflight: import("../../shared/types.ts").WorkflowPreflightV1 | undefined;
5103
+ let workflowPreflight: import("../../shared/types.ts").WorkflowPreflight | undefined;
4851
5104
  try {
4852
5105
  if (requestParams.preflight !== undefined && requestParams.workflowScript === undefined && requestParams.workflowScriptPath === undefined) {
4853
5106
  throw new Error("preflight requires workflowScript or workflowScriptPath.");
@@ -4857,7 +5110,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4857
5110
  } catch (error) {
4858
5111
  const message = error instanceof Error ? error.message : String(error);
4859
5112
  if (requestParams.action?.trim() === "validate") {
4860
- const validation = validateWorkflowScript(requestParams.workflowScript ?? "");
5113
+ const validation = validateWorkflowScript(requestParams.workflowScript ?? "", {
5114
+ maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
5115
+ });
4861
5116
  const invalidValidation = { ...validation, ok: false, errors: [...validation.errors, { message }] };
4862
5117
  return {
4863
5118
  content: [{ type: "text", text: JSON.stringify(invalidValidation) }],
@@ -4868,7 +5123,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4868
5123
  return buildRequestedModeError(requestParams, message);
4869
5124
  }
4870
5125
  if (requestParams.action?.trim() === "validate") {
4871
- const validation = validateWorkflowScript(requestParams.workflowScript ?? "");
5126
+ const validation = validateWorkflowScript(requestParams.workflowScript ?? "", {
5127
+ maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
5128
+ });
4872
5129
  const payload = workflowPreflight ? { ...validation, preflight: workflowPreflight } : validation;
4873
5130
  return {
4874
5131
  content: [{ type: "text", text: JSON.stringify(payload) }],
@@ -4878,7 +5135,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4878
5135
  }
4879
5136
  const normalizedAction = typeof requestParams.action === "string" ? requestParams.action.trim() : requestParams.action;
4880
5137
  if (normalizedAction === "resume" && requestParams.extensionBindings !== undefined) return buildRequestedModeError(requestParams, "extensionBindings is not supported with action='resume'; resume uses the original retained child binding.");
4881
- let workflowResource: { permit: WorkflowResourcePermit; provenance: WorkflowResourceProvenanceV1; authority: WorkflowResourceAuthority } | undefined;
5138
+ let workflowResource: { permit: WorkflowResourcePermit; provenance: WorkflowResourceProvenance; authority: WorkflowResourceAuthority } | undefined;
4882
5139
  if (workflowResourcePermit) {
4883
5140
  if (typeof requestParams.workflowScript !== "string") return buildRequestedModeError(requestParams, "Resolved workflow resource is missing its workflow script.");
4884
5141
  const consumed = consumeWorkflowResourcePermit(workflowResourcePermit, requestParams.workflowScript);
@@ -4886,8 +5143,22 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4886
5143
  workflowResource = { permit: workflowResourcePermit, ...consumed };
4887
5144
  }
4888
5145
  if (requestParams.workflowScript !== undefined && normalizedAction === undefined) {
5146
+ const workflowArgsEvidence = requestParams.args === undefined ? undefined : { args: requestParams.args, argsDigest: stableJsonDigest(requestParams.args) };
5147
+ const workflowArgs = workflowArgsEvidence?.args;
5148
+ const workflowArgsDigest = workflowArgsEvidence?.argsDigest;
5149
+ const spawnBudgetValidation = validateWorkflowScript(requestParams.workflowScript, {
5150
+ maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
5151
+ });
5152
+ const spawnBudgetErrors = spawnBudgetValidation.errors.filter((error) => error.kind === "spawn-budget");
5153
+ if (spawnBudgetErrors.length > 0) {
5154
+ return buildRequestedModeError(requestParams, `workflowScript validation failed before child launch; no children launched. ${spawnBudgetErrors.map((error) => error.message).join(" ")}`);
5155
+ }
5156
+ for (const warning of spawnBudgetValidation.warnings ?? []) console.warn(`[pi-subagents] ${warning.message}`);
5157
+ const acceptanceErrors = validateAcceptanceInput(requestParams.acceptance);
5158
+ if (acceptanceErrors.length > 0) return buildRequestedModeError(requestParams, acceptanceErrors.join(" "));
5159
+ const foregroundWorkflowRunId = encodeIndexSegment(_id);
4889
5160
  if (delegatedWorkflowPermit) {
4890
- const permitError = validateWorkflowChildPermitRoot(delegatedWorkflowPermit, _id);
5161
+ const permitError = validateWorkflowChildPermitRoot(delegatedWorkflowPermit, foregroundWorkflowRunId);
4891
5162
  if (permitError) return buildRequestedModeError(requestParams, permitError);
4892
5163
  if (requestParams.async !== false) return buildRequestedModeError(requestParams, "Workflow child permit supports foreground workflow roots only; set async:false.");
4893
5164
  }
@@ -5042,7 +5313,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5042
5313
  pid: process.pid,
5043
5314
  steps: [],
5044
5315
  ...(workflowPreflight ? { preflight: workflowPreflight } : {}),
5045
- workflow: { trace: [], emits: [], console: [], ...(workflowResource ? { resource: workflowResource.provenance } : {}) },
5316
+ workflow: { trace: [], emits: [], console: [], ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}) },
5046
5317
  workflowChildren: workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState: "running", inventoryComplete: false }),
5047
5318
  runFanoutBudget: getRunFanoutBudgetSnapshot(workflowFanoutBudget),
5048
5319
  };
@@ -5062,18 +5333,58 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5062
5333
  onSuccess: (_filePath, payload) => { indexedState = (payload as { state: AsyncStatus["state"] }).state; },
5063
5334
  onError: (error, filePath) => console.error(`Failed to update async workflow index '${filePath}':`, error),
5064
5335
  });
5065
- const queueActiveRunIndex = (): void => {
5066
- const state = status.state;
5336
+ const queueActiveRunIndex = (snapshot: AsyncStatus = status): void => {
5337
+ const state = snapshot.state;
5067
5338
  if (indexedState === state && indexPersistence.pendingCount() === 0) return;
5068
- indexPersistence.write(asyncDir, { state, toolCallId: status.toolCallId }, (_filePath, payload) => {
5339
+ indexPersistence.write(asyncDir, { state, toolCallId: snapshot.toolCallId }, (_filePath, payload) => {
5069
5340
  const indexPayload = payload as { state: AsyncStatus["state"]; toolCallId?: string };
5070
5341
  updateActiveRunIndex(asyncDir, indexPayload.state, indexPayload.toolCallId, { retryCapacityErrors: true });
5071
5342
  });
5072
5343
  };
5344
+ let pendingResultPublication: Promise<boolean> | undefined;
5345
+ let settleResultPublication: ((published: boolean) => void) | undefined;
5346
+ let resultWriteFailureWakeDelivered = false;
5347
+ const reportResultWriteFailure = (error: unknown): boolean => {
5348
+ const message = `Failed to write async workflow result ${resultPath}: ${error instanceof Error ? error.message : String(error)}`;
5349
+ console.error(message, error);
5350
+ try {
5351
+ if (currentSessionId && fallbackResultPayloadPathForSessionRun(path.dirname(resultPath), currentSessionId, workflowRunId)) return true;
5352
+ } catch (pendingError) {
5353
+ console.error(`Failed to verify pending async workflow result '${workflowRunId}':`, pendingError);
5354
+ }
5355
+ appendWorkflowEvent({ type: "subagent.workflow.result_write_failed", error: message });
5356
+ // A missing result file means the result watcher will never deliver the
5357
+ // terminal completion wake. Intermediate child notices are context-only
5358
+ // once their turns are suppressed, so surface the failure as its own
5359
+ // actionable wake instead of leaving the parent asleep.
5360
+ if (resultWriteFailureWakeDelivered) return false;
5361
+ if (deps.state.currentSessionId !== currentSessionId || deps.state.completionOwnerId !== completionOwnerId) return false;
5362
+ try {
5363
+ deps.pi.sendMessage(
5364
+ {
5365
+ customType: "subagent-workflow-result-write-failed",
5366
+ content: message,
5367
+ display: true,
5368
+ },
5369
+ { triggerTurn: true },
5370
+ );
5371
+ resultWriteFailureWakeDelivered = true;
5372
+ } catch (sendError) {
5373
+ console.error(`Failed to send workflow result write failure notification for '${workflowRunId}':`, sendError);
5374
+ }
5375
+ deps.refreshResultDelivery?.();
5376
+ return false;
5377
+ };
5073
5378
  const runPersistence = createCapacityResilientJsonWriter({
5074
5379
  keepAlive: true,
5075
- onSuccess: (filePath) => { if (filePath === statusPath) queueActiveRunIndex(); },
5076
- onError: (error, filePath) => console.error(`Failed to persist async workflow state '${filePath}':`, error),
5380
+ onSuccess: (filePath, payload) => {
5381
+ if (filePath === statusPath) queueActiveRunIndex(payload as AsyncStatus);
5382
+ if (filePath === resultPath) settleResultPublication?.(true);
5383
+ },
5384
+ onError: (error, filePath) => {
5385
+ if (filePath === resultPath) settleResultPublication?.(reportResultWriteFailure(error));
5386
+ else console.error(`Failed to persist async workflow state '${filePath}':`, error);
5387
+ },
5077
5388
  write: (filePath, payload) => filePath === resultPath
5078
5389
  ? writeAsyncResultFile(filePath, payload as Record<string, unknown>)
5079
5390
  : writeAtomicJson(filePath, payload),
@@ -5101,7 +5412,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5101
5412
  queueActiveRunIndex();
5102
5413
  } else if (options.tolerateStatusWriteFailure) {
5103
5414
  try {
5104
- runPersistence.write(statusPath, status);
5415
+ runPersistence.write(statusPath, { ...status });
5105
5416
  statusPersistenceDegraded = false;
5106
5417
  } catch (error) {
5107
5418
  const message = `Failed to persist async workflow state ${statusPath}: ${error instanceof Error ? error.message : String(error)}`;
@@ -5116,7 +5427,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5116
5427
  }
5117
5428
  }
5118
5429
  } else {
5119
- runPersistence.write(statusPath, status);
5430
+ runPersistence.write(statusPath, { ...status });
5120
5431
  }
5121
5432
  if (liveJob) {
5122
5433
  liveJob.status = status.state;
@@ -5144,13 +5455,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5144
5455
  };
5145
5456
  const writeWorkflowResult = (payload: Record<string, unknown>): boolean => {
5146
5457
  try {
5458
+ let resultPublished = false;
5459
+ settleResultPublication = (published) => { resultPublished = published; };
5460
+ pendingResultPublication = undefined;
5147
5461
  runPersistence.write(resultPath, payload);
5462
+ // Only capacity deferral yields; ordinary publication remains synchronous.
5463
+ if (!resultPublished) pendingResultPublication = new Promise<boolean>((resolve) => { settleResultPublication = resolve; });
5148
5464
  return true;
5149
5465
  } catch (error) {
5150
- const message = `Failed to write async workflow result ${resultPath}: ${error instanceof Error ? error.message : String(error)}`;
5151
- console.error(message, error);
5152
- appendWorkflowEvent({ type: "subagent.workflow.result_write_failed", error: message });
5153
- return false;
5466
+ return reportResultWriteFailure(error);
5154
5467
  }
5155
5468
  };
5156
5469
  const projectWorkflowActivity = () => {
@@ -5188,16 +5501,157 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5188
5501
  indexPersistence.dispose();
5189
5502
  return { content: [{ type: "text", text: `Failed to create async workflow storage: ${error instanceof Error ? error.message : String(error)}` }], isError: true, details: { mode: "workflow", results: [] } };
5190
5503
  }
5191
- appendWorkflowEvent({ type: "subagent.workflow.started" });
5504
+ appendWorkflowEvent({ type: "subagent.workflow.started", ...(workflowArgsDigest ? { argsDigest: workflowArgsDigest } : {}) });
5505
+ // The runner does not execute workflow scripts: this active owner must consume its own
5506
+ // durable steer inbox, deliver through in-process child controls, and persist receipts.
5507
+ const emitWorkflowSteerEvent = (type: string, requestId: string, index?: number, extra: Record<string, unknown> = {}): void => {
5508
+ appendWorkflowEvent({ type, requestId, ...(index !== undefined ? { index } : {}), ...extra });
5509
+ };
5510
+ const recordWorkflowSteerTargets = (request: SteerRequest, targets: Array<{ index: number; state: SteeringTargetState; reason?: string }>): void => {
5511
+ status.steering ??= createSteeringStatus();
5512
+ recordSteeringRequest(steeringStatus(status), {
5513
+ id: request.id,
5514
+ requestedAt: request.ts,
5515
+ ...(request.source ? { source: request.source } : {}),
5516
+ message: request.message,
5517
+ targets,
5518
+ });
5519
+ };
5520
+ const explicitWorkflowSteerIndexes = (request: SteerRequest): number[] | undefined => request.targetIndex !== undefined ? [request.targetIndex] : request.targetIndexes;
5521
+ const failWorkflowSteer = (request: SteerRequest, indexes: number[], reason: string): void => {
5522
+ const targets = indexes.map((index) => ({ index, state: "failed" as const, reason }));
5523
+ recordWorkflowSteerTargets(request, targets);
5524
+ emitWorkflowSteerEvent("subagent.steer.requested", request.id, undefined, { targets });
5525
+ for (const index of indexes) emitWorkflowSteerEvent("subagent.steer.failed", request.id, index, { reason });
5526
+ persist({ tolerateStatusWriteFailure: true });
5527
+ };
5528
+ const pendingWorkflowSteers = new Set<(state: "delivered" | "queued" | "failed", reason?: string) => void>();
5529
+ const deliverWorkflowSteerRequest = (request: SteerRequest): void => {
5530
+ let indexes = explicitWorkflowSteerIndexes(request);
5531
+ if (status.state !== "running") {
5532
+ failWorkflowSteer(request, indexes ?? [0], `run became ${status.state} before steering request was consumed`);
5533
+ return;
5534
+ }
5535
+ const liveControls = [...deps.state.foregroundControls.values()].filter((candidate) => candidate.parentWorkflowRunId === workflowRunId && (candidate.activeChildren?.size ?? 0) > 0);
5536
+ if (indexes === undefined) {
5537
+ if (liveControls.length !== 1) {
5538
+ failWorkflowSteer(request, [0], liveControls.length > 1
5539
+ ? `workflow has ${liveControls.length} live children; steer a child run id instead`
5540
+ : "workflow child is not live in this process");
5541
+ return;
5542
+ }
5543
+ const index = status.steps?.findIndex((step) => !!step.workflowKey && step.workflowKey === liveControls[0]!.workflowKey) ?? -1;
5544
+ if (index < 0) {
5545
+ failWorkflowSteer(request, [0], "live workflow child has no projected step");
5546
+ return;
5547
+ }
5548
+ indexes = [index];
5549
+ }
5550
+ // Normalize and record the whole set once: recordSteeringRequest is idempotent by id.
5551
+ // Explicit indexes resolve only by their projected key, never by a live sibling.
5552
+ const resolved = indexes.map((index) => {
5553
+ const step = status.steps?.[index];
5554
+ const control = step?.workflowKey ? liveControls.find((candidate) => candidate.workflowKey === step.workflowKey) : undefined;
5555
+ return { index, control, reason: !step ? "child index out of range" : !control ? "workflow child is not live in this process" : undefined };
5556
+ });
5557
+ const targets = resolved.map(({ index, reason }) => ({ index, state: reason ? "failed" as const : "routed" as const, ...(reason ? { reason } : {}) }));
5558
+ recordWorkflowSteerTargets(request, targets);
5559
+ emitWorkflowSteerEvent("subagent.steer.requested", request.id, undefined, { targets });
5560
+ persist({ tolerateStatusWriteFailure: true });
5561
+ for (const { index, control, reason } of resolved) {
5562
+ if (!control) {
5563
+ emitWorkflowSteerEvent("subagent.steer.failed", request.id, index, { reason });
5564
+ continue;
5565
+ }
5566
+ emitWorkflowSteerEvent("subagent.steer.routed", request.id, index);
5567
+ const applyWorkflowSteerDelivery = (state: "delivered" | "queued" | "failed", reason?: string): void => {
5568
+ // Shutdown settles unresolved receipts synchronously; late SDK callbacks cannot rewrite them.
5569
+ if (!pendingWorkflowSteers.has(applyWorkflowSteerDelivery)) return;
5570
+ // Queuing is not confirmation of delivery: retain ownership until terminal settlement.
5571
+ if (state !== "queued") pendingWorkflowSteers.delete(applyWorkflowSteerDelivery);
5572
+ const now = Date.now();
5573
+ const steering = steeringStatus(status);
5574
+ // This callback owns a pending target, even after bounded display history
5575
+ // evicts its request. Account independently; queued still represents one pending target.
5576
+ if (state !== "queued") steering.pending = Math.max(0, steering.pending - 1);
5577
+ if (state === "delivered") {
5578
+ steering.delivered++;
5579
+ steering.lastDeliveredAt = now;
5580
+ } else if (state === "failed") steering.failed++;
5581
+ const receipt = steering.recent.find((candidate) => candidate.id === request.id)?.targets.find((target) => target.index === index);
5582
+ if (receipt) {
5583
+ receipt.state = state;
5584
+ if (state === "delivered") receipt.deliveredAt = now;
5585
+ if (state === "failed") receipt.failedAt = now;
5586
+ if (reason) receipt.reason = reason;
5587
+ }
5588
+ if (state === "failed") {
5589
+ const failedStep = status.steps?.[index];
5590
+ if (failedStep) failedStep.activityState = "needs_attention";
5591
+ status.activityState = "needs_attention";
5592
+ }
5593
+ emitWorkflowSteerEvent(`subagent.steer.${state}`, request.id, index, state === "failed" ? { reason } : { deliveryStatus: state, message: request.message });
5594
+ persist({ tolerateStatusWriteFailure: true });
5595
+ };
5596
+ pendingWorkflowSteers.add(applyWorkflowSteerDelivery);
5597
+ void steerWorkflowForegroundTarget({
5598
+ target: { control, workflowRunId, sourceRunId: workflowRunId },
5599
+ message: request.message,
5600
+ ...(request.mode ? { mode: request.mode } : {}),
5601
+ }).then(
5602
+ (result) => {
5603
+ const target = result.details.steering?.targets[0];
5604
+ applyWorkflowSteerDelivery(target?.state === "delivered" ? "delivered" : target?.state === "queued" ? "queued" : "failed", target?.reason ?? (target ? undefined : "steering produced no target receipt"));
5605
+ },
5606
+ (error) => applyWorkflowSteerDelivery("failed", error instanceof Error ? error.message : String(error)),
5607
+ );
5608
+ }
5609
+ };
5610
+ let disposeWorkflowSteerInbox: (() => void) | undefined;
5611
+ try {
5612
+ disposeWorkflowSteerInbox = watchAsyncControlInbox(asyncDir, {
5613
+ onSteer: deliverWorkflowSteerRequest,
5614
+ onError: (error, phase, request) => {
5615
+ const reason = error instanceof Error ? error.message : String(error);
5616
+ appendWorkflowEvent({ type: "subagent.workflow.steer_inbox_unavailable", phase, error: reason });
5617
+ if (request) failWorkflowSteer(request, explicitWorkflowSteerIndexes(request) ?? [0], `steer consumer failed: ${reason}`);
5618
+ },
5619
+ });
5620
+ } catch (error) {
5621
+ // Steering is an optional control surface, so a watcher that cannot install must not fail the run.
5622
+ appendWorkflowEvent({ type: "subagent.workflow.steer_inbox_unavailable", error: error instanceof Error ? error.message : String(error) });
5623
+ }
5624
+ deps.activateSupervisorTransport?.();
5192
5625
  const { workflowScript, async: _workflowAsync, chatProgress: _chatProgress, ...workflowRequest } = requestParams;
5626
+ let workflowSteerInboxClosed = false;
5627
+ const settleWorkflowSteerInbox = (outcome = status.state): void => {
5628
+ if (workflowSteerInboxClosed) return;
5629
+ workflowSteerInboxClosed = true;
5630
+ disposeWorkflowSteerInbox?.();
5631
+ // Consumed deliveries are not files anymore. Fail unresolved SDK operations without awaiting them.
5632
+ for (const settle of pendingWorkflowSteers) settle("failed", `run became ${outcome} before steering delivery settled; delivery unconfirmed`);
5633
+ try {
5634
+ closeSteerInbox(asyncDir, outcome);
5635
+ // Separately drain requests that never reached the consumer.
5636
+ const undelivered = consumeSteerRequests(asyncDir, undefined, (error) => {
5637
+ appendWorkflowEvent({ type: "subagent.workflow.steer_inbox_unavailable", phase: "drain", error: error instanceof Error ? error.message : String(error) });
5638
+ });
5639
+ for (const request of undelivered) failWorkflowSteer(request, explicitWorkflowSteerIndexes(request) ?? [0], `run became ${outcome} before steering request was consumed`);
5640
+ } catch (error) {
5641
+ appendWorkflowEvent({ type: "subagent.workflow.steer_inbox_unavailable", phase: "close", error: error instanceof Error ? error.message : String(error) });
5642
+ }
5643
+ // Commit receipts while run status is still nonterminal. Result/index publication
5644
+ // can fail next; teardown must not publish the subsequently computed terminal status.
5645
+ persist();
5646
+ };
5193
5647
  void Promise.resolve().then(async () => {
5194
5648
  const workflowDeadlineAt = timeout === undefined ? undefined : Date.now() + timeout;
5195
5649
  const workflowResults: SingleResult[] = [];
5196
5650
  const workflowChildRunIds = new Map<string, string>();
5197
- const { action: _action, agent: _agent, task: _task, resume: _resume, tasks: _tasks, chain: _chain, concurrency: _concurrency, foregroundOnly: _foregroundOnly, clarify: _clarify, timeoutMs: _timeoutMs, maxRuntimeMs: _maxRuntimeMs, usageBudget: _usageBudget, missionId: _missionId, mission: _mission, preflight: _preflight, globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowChildDefaults } = workflowRequest;
5651
+ const { args: _args, action: _action, agent: _agent, task: _task, resume: _resume, tasks: _tasks, chain: _chain, concurrency: _concurrency, foregroundOnly: _foregroundOnly, clarify: _clarify, timeoutMs: _timeoutMs, maxRuntimeMs: _maxRuntimeMs, usageBudget: _usageBudget, missionId: _missionId, mission: _mission, preflight: _preflight, globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowChildDefaults } = workflowRequest;
5198
5652
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
5199
5653
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
5200
- const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, parentCwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId));
5654
+ const workflowAggregateOutputPath = resolveSingleOutputPath(workflowOutput, parentCwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId));
5201
5655
  const claimedOutputPaths = new Map<string, string>();
5202
5656
  const childOutputOverrides = new Map<string, string>();
5203
5657
  const childOutputClaimPaths = new Map<string, string>();
@@ -5319,6 +5773,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5319
5773
  try {
5320
5774
  const workflow = await runWorkflowScript({
5321
5775
  script: workflowScript,
5776
+ ...(workflowArgs ? { args: workflowArgs } : {}),
5777
+ workflowRunId,
5778
+ processCwd: ctx.cwd,
5322
5779
  globalConcurrencyLimit: requestParams.globalConcurrencyLimit ?? deps.config.globalConcurrencyLimit,
5323
5780
  timeoutMs: timeout,
5324
5781
  signal: controller.signal,
@@ -5334,6 +5791,28 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5334
5791
  },
5335
5792
  ...(workflowState ? { state: workflowState } : {}),
5336
5793
  onTrace: updateTrace,
5794
+ onChildSettled: (notification) => {
5795
+ appendWorkflowEvent({
5796
+ type: "subagent.workflow.child_settled",
5797
+ childKey: notification.childKey,
5798
+ ...(notification.childRunId ? { childRunId: notification.childRunId } : {}),
5799
+ outcome: notification.outcome,
5800
+ workflowRunning: notification.workflowRunning,
5801
+ });
5802
+ try {
5803
+ deps.pi.sendMessage(
5804
+ {
5805
+ customType: "subagent-incremental-child-notify",
5806
+ content: formatIncrementalChildCompletion(notification),
5807
+ display: notification.outcome !== "completed",
5808
+ },
5809
+ { triggerTurn: incrementalChildCompletionTriggersTurn(notification, requestParams.scheduleOrigin) },
5810
+ );
5811
+ } catch (sendError) {
5812
+ console.error(`Failed to send incremental child completion notification for '${notification.childKey}':`, sendError);
5813
+ }
5814
+ deps.refreshResultDelivery?.();
5815
+ },
5337
5816
  onLanePlan: (lanes) => {
5338
5817
  status.workflowGraph = buildWorkflowLaneGraph(workflowRunId, lanes, status.workflowGraph);
5339
5818
  applyWorkflowLaneTrace(status.workflowGraph, status.workflow?.trace ?? []);
@@ -5346,7 +5825,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5346
5825
  persist({ tolerateStatusWriteFailure: true });
5347
5826
  } });
5348
5827
  },
5349
- admit: (calls) => {
5828
+ admit: async (calls, admissionSignal) => {
5829
+ await preflightWorkflowWorktrees({ workflowDefaults: workflowChildDefaults, defaultWorktree: deps.config.worktree, calls, ctxCwd: parentCwd, signal: admissionSignal, deadlineAt: workflowDeadlineAt });
5350
5830
  const outputClaims = workflowChildOutputClaims({ ctxCwd: parentCwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
5351
5831
  if (outputClaims.error) throw new Error(outputClaims.error);
5352
5832
  status.runFanoutBudget = claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
@@ -5382,6 +5862,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5382
5862
  deps.asyncByDefault,
5383
5863
  );
5384
5864
  preparedChildParams = childRequest;
5865
+ if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
5385
5866
  workflowLaunchObservers.set(childRequest, (launch) => {
5386
5867
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
5387
5868
  if (step) {
@@ -5430,7 +5911,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5430
5911
  if (child.runId) workflowChildRunIds.set(key, child.runId);
5431
5912
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
5432
5913
  if (step) {
5433
- step.async = Boolean(result.details.asyncId || result.details.asyncDir);
5914
+ step.async = step.async === true || Boolean(result.details.asyncId || result.details.asyncDir);
5434
5915
  if (child.runId) step.runId = child.runId;
5435
5916
  if (child.lane) step.lane = child.lane;
5436
5917
  }
@@ -5452,7 +5933,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5452
5933
  return child;
5453
5934
  },
5454
5935
  status: async (keyOrRunId, workflowSignal) => workflowChildResult(keyOrRunId, await execute(randomUUID(), { action: "status", id: keyOrRunId }, workflowSignal, undefined, ctx, preserveActiveSession, workflowParentModel)),
5455
- resolveResume: (reference) => resolveKeyedWorkflowResume(reference, deps.state),
5936
+ resolveResume: (reference, _signal, index) => resolveWorkflowResume(reference, deps, ctx.sessionManager.getSessionFile() ?? null, index),
5456
5937
  steer: (key, message, options, workflowSignal) => steerWorkflowChildByKey({ state: deps.state, workflowRunId, key, message, options, signal: workflowSignal, resolveRunId: () => workflowChildRunIds.get(key) }),
5457
5938
  });
5458
5939
  const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, workflow.trace, { settled: true });
@@ -5463,20 +5944,24 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5463
5944
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, summary, producedChildOutputPaths);
5464
5945
  const resultSummary = appendWorkflowOutputWarning(summary, outputWarning);
5465
5946
  const workflowUsage = sumResultsUsage(workflowResults);
5947
+ settleWorkflowSteerInbox("complete");
5466
5948
  const workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children, steps: status.steps });
5467
- status = { ...status, state: "complete", endedAt: Date.now(), workflow: { value: workflow.value, trace: finalPreflightTrace, emits: workflow.emits, console: workflow.console, ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}) }, workflowChildren, totalTokens: { input: workflowUsage.input, output: workflowUsage.output, total: workflowUsage.input + workflowUsage.output }, totalCost: sumResultsCost(workflowResults) };
5468
- const receipt = terminalWorkflowReceipt(workflowRunId, "complete", workflow.children, workflowChildren, undefined, validHostStepNodes(status.workflowGraph), workflowResource?.provenance);
5949
+ status = { ...status, state: "complete", endedAt: Date.now(), workflow: { value: workflow.value, trace: finalPreflightTrace, emits: workflow.emits, console: workflow.console, ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}) }, workflowChildren, totalTokens: { input: workflowUsage.input, output: workflowUsage.output, total: workflowUsage.input + workflowUsage.output }, totalCost: sumResultsCost(workflowResults) };
5950
+ const receipt = terminalWorkflowReceipt(workflowRunId, "complete", workflow.children, workflowChildren, undefined, validHostStepNodes(status.workflowGraph), workflowResource?.provenance, workflowArgsDigest);
5951
+ delete status.workflowReceiptPath;
5469
5952
  let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
5470
5953
  try {
5471
5954
  workflowReceipt = { path: writeWorkflowReceipt(asyncDir, receipt), receipt };
5955
+ status.workflowReceiptPath = workflowReceipt.path;
5472
5956
  } catch (receiptError) {
5473
5957
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
5474
5958
  }
5475
5959
  if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary: resultSummary, output: resultSummary, workflowChildren, results: workflow.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(status.steps?.find((step) => step.workflowKey === child.key)?.sessionName ? { sessionName: status.steps?.find((step) => step.workflowKey === child.key)?.sessionName } : {}), ...workflowChildAccountingFields(child), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.outputReference ? { outputReference: child.outputReference } : {}), ...(child.outputPathMapping ? { outputPathMapping: child.outputPathMapping } : {}), ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
5960
+ if (pendingResultPublication && !await pendingResultPublication) return;
5476
5961
  persist();
5477
5962
  deps.refreshResultDelivery?.();
5478
5963
  persistClosed = true;
5479
- appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(status.error ? { error: status.error } : {}) });
5964
+ appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(workflowArgsDigest ? { argsDigest: workflowArgsDigest } : {}), ...(status.error ? { error: status.error } : {}) });
5480
5965
  } catch (error) {
5481
5966
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
5482
5967
  const stopped = controller.signal.aborted;
@@ -5496,10 +5981,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5496
5981
  }
5497
5982
  }
5498
5983
  const workflowState = state === "paused" ? "paused" : state === "stopped" ? "stopped" : "failed";
5984
+ settleWorkflowSteerInbox(state);
5499
5985
  const workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState, inventoryComplete: true, trace: partial.trace, children: partial.children, steps: status.steps });
5500
5986
  const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, partial.trace, { settled: true });
5501
5987
  const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
5502
- status = compactOptional<AsyncStatus>({ ...status, state, stopped: stopped || undefined, activityState: pauseForDetached ? "needs_attention" : undefined, error: workflowFailureMessage(error, workflowRunId, partial.children), endedAt: Date.now(), workflow: { trace: finalPreflightTrace, emits: partial.emits, console: partial.console, ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}) }, workflowChildren });
5988
+ status = compactOptional<AsyncStatus>({ ...status, state, stopped: stopped || undefined, activityState: pauseForDetached || status.activityState === "needs_attention" ? "needs_attention" : undefined, error: workflowFailureMessage(error, workflowRunId, partial.children), endedAt: Date.now(), workflow: { trace: finalPreflightTrace, emits: partial.emits, console: partial.console, ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}) }, workflowChildren });
5503
5989
  if (pauseForDetached) {
5504
5990
  const promoted = promotePausedWorkflowIfSettled(status);
5505
5991
  if (promoted) status = promoted;
@@ -5511,19 +5997,28 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5511
5997
  const resultSummary = appendWorkflowOutputWarning(terminalSummary, outputWarning);
5512
5998
  const receiptState: WorkflowReceiptState = status.state === "complete" ? "complete" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "failed";
5513
5999
  const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
5514
- const receipt = terminalWorkflowReceipt(workflowRunId, receiptState, partial.children, workflowChildren, terminalOutcome, validHostStepNodes(status.workflowGraph), workflowResource?.provenance);
6000
+ const receipt = terminalWorkflowReceipt(workflowRunId, receiptState, partial.children, workflowChildren, terminalOutcome, validHostStepNodes(status.workflowGraph), workflowResource?.provenance, workflowArgsDigest);
6001
+ delete status.workflowReceiptPath;
5515
6002
  let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
5516
6003
  try {
5517
6004
  workflowReceipt = { path: writeWorkflowReceipt(asyncDir, receipt), receipt };
6005
+ status.workflowReceiptPath = workflowReceipt.path;
5518
6006
  } catch (receiptError) {
5519
6007
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
5520
6008
  }
5521
6009
  if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: status.state === "complete", state: status.state, summary: resultSummary, error: status.state === "complete" ? undefined : status.error, stopped: status.stopped, activityState: status.activityState, workflowChildren, ...(terminalOutcome ? { terminalOutcome } : {}), results: partial.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(status.steps?.find((step) => step.workflowKey === child.key)?.sessionName ? { sessionName: status.steps?.find((step) => step.workflowKey === child.key)?.sessionName } : {}), ...workflowChildAccountingFields(child), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.outputReference ? { outputReference: child.outputReference } : {}), ...(child.terminalOutcome ? { terminalOutcome: child.terminalOutcome } : {}), ...(child.outputPathMapping ? { outputPathMapping: child.outputPathMapping } : {}), ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(child.detached && status.state !== "complete" ? { detached: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
6010
+ if (pendingResultPublication && !await pendingResultPublication) return;
5522
6011
  persist();
5523
6012
  deps.refreshResultDelivery?.();
5524
6013
  persistClosed = true;
5525
- appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(terminalOutcome ? { terminalOutcome } : {}), ...(status.error ? { error: status.error } : {}), ...(status.activityState ? { activityState: status.activityState } : {}) });
6014
+ appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(workflowArgsDigest ? { argsDigest: workflowArgsDigest } : {}), ...(terminalOutcome ? { terminalOutcome } : {}), ...(status.error ? { error: status.error } : {}), ...(status.activityState ? { activityState: status.activityState } : {}) });
5526
6015
  } finally {
6016
+ // Idempotent cleanup only: a failed result/index write must not authorize terminal status.
6017
+ try {
6018
+ settleWorkflowSteerInbox();
6019
+ } catch (error) {
6020
+ console.error(`Failed to close async workflow steer inbox '${asyncDir}':`, error);
6021
+ }
5527
6022
  persistClosed = true;
5528
6023
  deps.state.workflowControllers?.delete(workflowRunId);
5529
6024
  deps.state.workflowChildStops?.delete(workflowRunId);
@@ -5536,10 +6031,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5536
6031
  details: { mode: "workflow", runId: workflowRunId, toolCallId, asyncId: workflowRunId, asyncDir, results: [], ...(workflowPreflight ? { preflight: workflowPreflight } : {}), workflow: status.workflow, workflowChildren: status.workflowChildren, chatProgress, ...(deps.state.activeAsyncCapacity ? { activeAsyncCapacity: deps.state.activeAsyncCapacity } : {}) },
5537
6032
  }, workflowFanoutBudget));
5538
6033
  }
5539
- const { workflowScript: _workflowScript, action: _action, agent: _agent, task: _task, resume: _resume, tasks: _tasks, chain: _chain, concurrency: _concurrency, async: _async, foregroundOnly: _foregroundOnly, clarify: _clarify, timeoutMs: _timeoutMs, maxRuntimeMs: _maxRuntimeMs, usageBudget: _usageBudget, chatProgress: _chatProgress, missionId: _missionId, mission: _mission, preflight: _preflight, globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowChildDefaults } = requestParams;
6034
+ const { workflowScript: _workflowScript, args: _args, action: _action, agent: _agent, task: _task, resume: _resume, tasks: _tasks, chain: _chain, concurrency: _concurrency, async: _async, foregroundOnly: _foregroundOnly, clarify: _clarify, timeoutMs: _timeoutMs, maxRuntimeMs: _maxRuntimeMs, usageBudget: _usageBudget, chatProgress: _chatProgress, missionId: _missionId, mission: _mission, preflight: _preflight, globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowChildDefaults } = requestParams;
5540
6035
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
5541
6036
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
5542
- const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, _id));
6037
+ const workflowAggregateOutputPath = resolveSingleOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, foregroundWorkflowRunId));
5543
6038
  const claimedOutputPaths = new Map<string, string>();
5544
6039
  const childOutputOverrides = new Map<string, string>();
5545
6040
  const childOutputClaimPaths = new Map<string, string>();
@@ -5549,7 +6044,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5549
6044
  const runHostCommand = workflowHostCommandRunner({
5550
6045
  workflowCwd,
5551
6046
  artifactsDir: workflowArtifactsDir,
5552
- workflowRunId: _id,
6047
+ workflowRunId: foregroundWorkflowRunId,
5553
6048
  claimedOutputPaths,
5554
6049
  producedOutputPaths: producedChildOutputPaths,
5555
6050
  ...(workflowResource ? { authorize: (key, params) => authorizeWorkflowResourceHost(workflowResource!.permit, key, params.command) } : {}),
@@ -5559,19 +6054,29 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5559
6054
  : workflowResource
5560
6055
  ? workflowResource.authority.host ? runHostCommand : undefined
5561
6056
  : publicExecution ? undefined : runHostCommand;
5562
- const workflowHostSteps = new Map<string, HostStepNodeV1>();
6057
+ const workflowHostSteps = new Map<string, HostStepNode>();
5563
6058
  let liveWorkflow: NonNullable<Details["workflow"]> = { trace: [], emits: [], console: [], ...(workflowResource ? { resource: workflowResource.provenance } : {}) };
5564
- let liveWorkflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "running", inventoryComplete: false });
6059
+ const childProgress = new Map<string, ReturnType<typeof workflowChildProgress>>();
6060
+ let activityTimer: ReturnType<typeof setTimeout> | undefined;
6061
+ let lastProgressAt = 0;
6062
+ let workflowProgressClosed = false;
5565
6063
  const workflowDeadlineAt = timeout === undefined ? undefined : Date.now() + timeout;
5566
6064
  const workflowCapabilityCeiling = intersectSubagentCapabilityCeilings(requestParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(resolveCurrentSessionId(ctx.sessionManager)));
5567
6065
  const sendWorkflowProgress = () => {
5568
- const update = workflowChatProgressUpdate(_id, chatProgress, liveWorkflow, liveWorkflowChildren, workflowPreflight);
5569
- if (update) onUpdate?.(update);
6066
+ if (workflowProgressClosed) return;
6067
+ if (activityTimer) clearTimeout(activityTimer);
6068
+ activityTimer = undefined;
6069
+ lastProgressAt = Date.now();
6070
+ const liveWorkflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "running", inventoryComplete: false, trace: liveWorkflow.trace, progress: childProgress });
6071
+ onUpdate?.(workflowProgressUpdate(foregroundWorkflowRunId, chatProgress, liveWorkflow, liveWorkflowChildren, workflowPreflight));
5570
6072
  };
5571
6073
  try {
5572
6074
  const workflow = await runWorkflowScript({
5573
6075
  script: requestParams.workflowScript,
5574
- ...(delegatedWorkflowPermit ? { oneUsePermit: { claim: (key: string) => claimWorkflowChildPermit(delegatedWorkflowPermit, _id, key) } } : {}),
6076
+ ...(workflowArgs ? { args: workflowArgs } : {}),
6077
+ workflowRunId: foregroundWorkflowRunId,
6078
+ processCwd: ctx.cwd,
6079
+ ...(delegatedWorkflowPermit ? { oneUsePermit: { claim: (key: string) => claimWorkflowChildPermit(delegatedWorkflowPermit, foregroundWorkflowRunId, key) } } : {}),
5575
6080
  globalConcurrencyLimit: requestParams.globalConcurrencyLimit ?? deps.config.globalConcurrencyLimit,
5576
6081
  timeoutMs: timeout,
5577
6082
  signal,
@@ -5584,11 +6089,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5584
6089
  const projectedTrace = annotateWorkflowPreflightTrace(trace, workflowPreflight);
5585
6090
  const preflightWarnings = workflowPreflightWarnings(workflowPreflight, trace);
5586
6091
  liveWorkflow = { ...liveWorkflow, trace: projectedTrace, ...(preflightWarnings.length ? { preflightWarnings } : {}) };
5587
- liveWorkflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "running", inventoryComplete: false, trace });
6092
+ for (const entry of trace) {
6093
+ if (entry.operation === "run" && ["completed", "failed", "stopped", "detached"].includes(entry.state)) childProgress.delete(entry.key);
6094
+ }
5588
6095
  sendWorkflowProgress();
5589
6096
  },
5590
- admit: (calls) => {
5591
- const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId: _id, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
6097
+ admit: async (calls, admissionSignal) => {
6098
+ await preflightWorkflowWorktrees({ workflowDefaults: workflowChildDefaults, defaultWorktree: deps.config.worktree, calls, ctxCwd: ctx.cwd, signal: admissionSignal, deadlineAt: workflowDeadlineAt });
6099
+ const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId: foregroundWorkflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
5592
6100
  if (outputClaims.error) throw new Error(outputClaims.error);
5593
6101
  claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
5594
6102
  if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
@@ -5608,7 +6116,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5608
6116
  if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state, { state: "partial", reason: "budget_exhausted" });
5609
6117
  const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
5610
6118
  const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
5611
- recordMissionWorkflowChild(missionBinding, _id, key, {
6119
+ recordMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, {
5612
6120
  status: "running",
5613
6121
  ...(typeof childParams.agent === "string" && childParams.agent.trim() ? { agent: childParams.agent.trim() } : {}),
5614
6122
  ...(childLabel ? { label: childLabel } : {}),
@@ -5616,13 +6124,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5616
6124
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
5617
6125
  });
5618
6126
  let preparedChildParams: SubagentParamsLike | undefined;
5619
- const result = await runMissionWorkflowChild(missionBinding, _id, key, childPhase, () => {
6127
+ const result = await runMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, childPhase, () => {
5620
6128
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
5621
- { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: _id, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
6129
+ { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams: delegatedWorkflowPermit ? { ...childParams, async: false } : childParams, parentWorkflowRunId: foregroundWorkflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
5622
6130
  missionBinding,
5623
6131
  deps.asyncByDefault,
5624
6132
  );
5625
6133
  preparedChildParams = childRequest;
6134
+ if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
5626
6135
  if (delegatedWorkflowPermit) {
5627
6136
  if (childRequest.async !== false) throw new Error("Workflow child permit supports one foreground child only.");
5628
6137
  const childCwd = resolveRequestedCwd(workflowCwd, childRequest.cwd);
@@ -5630,9 +6139,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5630
6139
  ? resolveAgentName(childRequest.agent, discoverWorkflowAgents(childCwd, resolveExecutionAgentScope(childRequest.agentScope)).agents).agent
5631
6140
  : undefined;
5632
6141
  if (childAgent?.runner?.type === "external-cli" || childAgent?.runner?.type === "external-job") throw new Error("Workflow child permit supports native Pi children only.");
5633
- workflowPermitContexts.set(childRequest, { child: { permit: delegatedWorkflowPermit, workflowRunId: _id, childKey: key } });
6142
+ workflowPermitContexts.set(childRequest, { child: { permit: delegatedWorkflowPermit, workflowRunId: foregroundWorkflowRunId, childKey: key } });
5634
6143
  }
5635
- workflowLaunchObservers.set(childRequest, (launch) => recordMissionWorkflowChild(missionBinding, _id, key, {
6144
+ workflowLaunchObservers.set(childRequest, (launch) => recordMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, {
5636
6145
  status: "running",
5637
6146
  agent: launch.agent,
5638
6147
  ...(launch.sessionFile ? { sessionPath: launch.sessionFile } : {}),
@@ -5640,8 +6149,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5640
6149
  return execute(randomUUID(), childRequest, workflowSignal, (update) => {
5641
6150
  const progress = update.details.progress?.[0];
5642
6151
  if (!progress) return;
6152
+ if (onUpdate && !workflowProgressClosed) {
6153
+ if (progress.status === "running") childProgress.set(key, workflowChildProgress(progress));
6154
+ else childProgress.delete(key);
6155
+ if (!activityTimer) {
6156
+ const delay = 100 - (Date.now() - lastProgressAt);
6157
+ if (delay <= 0) sendWorkflowProgress();
6158
+ else activityTimer = setTimeout(sendWorkflowProgress, delay);
6159
+ }
6160
+ }
5643
6161
  const progressStatus = progress.status === "completed" ? "completed" : progress.status === "failed" ? "failed" : "running";
5644
- recordMissionWorkflowChild(missionBinding, _id, key, {
6162
+ recordMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, {
5645
6163
  status: progressStatus,
5646
6164
  heartbeat: { status: progressStatus, ...(childPhase ? { phase: childPhase } : {}) },
5647
6165
  });
@@ -5655,7 +6173,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5655
6173
  const child = workflowChildResult(key, result, preparedChildParams ?? childParams, deps.state);
5656
6174
  if (child.runId) workflowChildRunIds.set(key, child.runId);
5657
6175
  const childStatus = missionWorkflowChildStatus(result);
5658
- recordMissionWorkflowChild(missionBinding, _id, key, {
6176
+ recordMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, {
5659
6177
  status: childStatus,
5660
6178
  ...(child.runId ? { runId: child.runId } : {}),
5661
6179
  ...(result.details.results[0]?.agent ? { agent: result.details.results[0].agent } : {}),
@@ -5667,13 +6185,13 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5667
6185
  return child;
5668
6186
  },
5669
6187
  status: async (keyOrRunId, workflowSignal) => workflowChildResult(keyOrRunId, await execute(randomUUID(), { action: "status", id: keyOrRunId }, workflowSignal, undefined, ctx, preserveActiveSession, workflowParentModel)),
5670
- resolveResume: (reference) => resolveKeyedWorkflowResume(reference, deps.state),
5671
- steer: (key, message, options, workflowSignal) => steerWorkflowChildByKey({ state: deps.state, workflowRunId: _id, key, message, options, signal: workflowSignal, resolveRunId: () => workflowChildRunIds.get(key) }),
6188
+ resolveResume: (reference, _signal, index) => resolveWorkflowResume(reference, deps, ctx.sessionManager.getSessionFile() ?? null, index),
6189
+ steer: (key, message, options, workflowSignal) => steerWorkflowChildByKey({ state: deps.state, workflowRunId: foregroundWorkflowRunId, key, message, options, signal: workflowSignal, resolveRunId: () => workflowChildRunIds.get(key) }),
5672
6190
  });
5673
6191
  const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, workflow.trace, { settled: true });
5674
6192
  const finalPreflightTrace = annotateWorkflowPreflightTrace(workflow.trace, workflowPreflight);
5675
- const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children });
5676
- const receipt = terminalWorkflowReceipt(_id, "complete", workflow.children, workflowChildren, undefined, [...workflowHostSteps.values()], workflowResource?.provenance);
6193
+ const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children });
6194
+ const receipt = terminalWorkflowReceipt(foregroundWorkflowRunId, "complete", workflow.children, workflowChildren, undefined, [...workflowHostSteps.values()], workflowResource?.provenance, workflowArgsDigest);
5677
6195
  const traceLines = finalPreflightTrace.map((entry) => `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.durationMs !== undefined ? ` in ${entry.durationMs}ms` : ""}${entry.warning ? ` — ${entry.warning}` : ""}${entry.error ? ` — ${entry.error}` : ""}`);
5678
6196
  const sections = [
5679
6197
  ...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []),
@@ -5691,11 +6209,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5691
6209
  const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
5692
6210
  return attachWorkflowMission(withRunFanoutBudget({
5693
6211
  content: [{ type: "text", text: displayText }],
5694
- details: compactOptional<Details>({ mode: "workflow", runId: _id, results: workflowDetailsResults(workflow.children), ...(workflowPreflight ? { preflight: workflowPreflight } : {}), workflowChildren, totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { value: workflow.value, trace: finalPreflightTrace, emits: workflow.emits, console: workflow.console, ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}), receipt }, chatProgress }),
6212
+ details: compactOptional<Details>({ mode: "workflow", runId: foregroundWorkflowRunId, results: workflowDetailsResults(workflow.children), ...(workflowPreflight ? { preflight: workflowPreflight } : {}), workflowChildren, totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { value: workflow.value, trace: finalPreflightTrace, emits: workflow.emits, console: workflow.console, ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}), receipt }, chatProgress }),
5695
6213
  }, workflowFanoutBudget));
5696
6214
  } catch (error) {
5697
6215
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
5698
- const text = workflowFailureMessage(error, _id, partial.children);
6216
+ const text = workflowFailureMessage(error, foregroundWorkflowRunId, partial.children);
5699
6217
  const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, partial.trace, { settled: true });
5700
6218
  const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
5701
6219
  const traceLines = finalPreflightTrace.map((entry) => `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.warning ? ` — ${entry.warning}` : ""}${entry.error ? ` — ${entry.error}` : ""}`);
@@ -5712,20 +6230,39 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5712
6230
  const workflowText = sections.join("\n\n");
5713
6231
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText, producedChildOutputPaths);
5714
6232
  const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
5715
- const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "failed", inventoryComplete: true, trace: partial.trace, children: partial.children });
6233
+ const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "failed", inventoryComplete: true, trace: partial.trace, children: partial.children });
5716
6234
  const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
5717
- const receipt = terminalWorkflowReceipt(_id, "failed", partial.children, workflowChildren, terminalOutcome, [...workflowHostSteps.values()], workflowResource?.provenance);
6235
+ const receipt = terminalWorkflowReceipt(foregroundWorkflowRunId, "failed", partial.children, workflowChildren, terminalOutcome, [...workflowHostSteps.values()], workflowResource?.provenance, workflowArgsDigest);
5718
6236
  return attachWorkflowMission(withRunFanoutBudget({
5719
6237
  content: [{ type: "text", text: displayText }],
5720
6238
  isError: true,
5721
- details: compactOptional<Details>({ mode: "workflow", runId: _id, results: workflowDetailsResults(partial.children), ...(workflowPreflight ? { preflight: workflowPreflight } : {}), workflowChildren, totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { trace: finalPreflightTrace, emits: partial.emits, console: partial.console, ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}), receipt }, chatProgress }),
6239
+ details: compactOptional<Details>({ mode: "workflow", runId: foregroundWorkflowRunId, results: workflowDetailsResults(partial.children), ...(workflowPreflight ? { preflight: workflowPreflight } : {}), workflowChildren, totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { trace: finalPreflightTrace, emits: partial.emits, console: partial.console, ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}), receipt }, chatProgress }),
5722
6240
  }, workflowFanoutBudget));
6241
+ } finally {
6242
+ workflowProgressClosed = true;
6243
+ if (activityTimer) clearTimeout(activityTimer);
6244
+ childProgress.clear();
5723
6245
  }
5724
6246
  }
5725
6247
  const directParams = requestParams;
5726
- const requestedCwd = directParams.cwd;
5727
- const requestCwd = resolveRequestedCwd(ctx.cwd, directParams.cwd);
5728
- const paramsWithResolvedCwd = directParams.cwd === undefined ? directParams : { ...directParams, cwd: requestCwd };
6248
+ // With a machine, cwd names a directory on that machine: keep it out of every local path resolution.
6249
+ // Placement can also come from the agent's frontmatter or settings override, so the agent is resolved first (discovery is fingerprint-cached).
6250
+ const placedByAgent = (): boolean => {
6251
+ if (directParams.machine !== undefined || directParams.cwd === undefined || typeof directParams.agent !== "string") return false;
6252
+ try {
6253
+ return resolveAgentName(directParams.agent, deps.discoverAgents(ctx.cwd, resolveExecutionAgentScope(directParams.agentScope)).agents).agent?.machine !== undefined;
6254
+ } catch {
6255
+ return false; // Discovery errors surface from the launch path itself.
6256
+ }
6257
+ };
6258
+ const remotePlacement = directParams.action === undefined && (directParams.machine !== undefined || placedByAgent());
6259
+ const requestedCwd = remotePlacement ? undefined : directParams.cwd;
6260
+ const requestCwd = remotePlacement ? ctx.cwd : resolveRequestedCwd(ctx.cwd, directParams.cwd);
6261
+ const paramsWithResolvedCwd = directParams.cwd === undefined
6262
+ ? directParams
6263
+ : remotePlacement
6264
+ ? omitUndefinedProperties({ ...directParams, cwd: undefined, machineCwd: directParams.cwd })
6265
+ : { ...directParams, cwd: requestCwd };
5729
6266
  const action = paramsWithResolvedCwd.action;
5730
6267
  let requestSessionId = "";
5731
6268
  let requestPiSessionId: string | undefined;
@@ -5790,10 +6327,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5790
6327
  }
5791
6328
  if (!confirmed) return { content: [{ type: "text", text: "Worktree discard canceled; preserved worktrees were not changed." }], details: { mode: "management", results: [] } };
5792
6329
  try {
5793
- const discarded = discardPreservedWorktrees(
5794
- path.isAbsolute(paramsWithResolvedCwd.handoffPath) ? paramsWithResolvedCwd.handoffPath : path.resolve(requestCwd, paramsWithResolvedCwd.handoffPath),
6330
+ const manifestPath = path.isAbsolute(paramsWithResolvedCwd.handoffPath) ? paramsWithResolvedCwd.handoffPath : path.resolve(requestCwd, paramsWithResolvedCwd.handoffPath);
6331
+ const discarded = await withWorktreeTransaction(() => discardPreservedWorktrees(
6332
+ manifestPath,
5795
6333
  { kind: decision === "confirm" ? "confirmed" : "policy", ...(deps.config.authorityPolicy ? { policy: deps.config.authorityPolicy } : {}) },
5796
- );
6334
+ ));
5797
6335
  return { content: [{ type: "text", text: discarded.text }], details: { mode: "management", results: [] } };
5798
6336
  } catch (error) {
5799
6337
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
@@ -5823,6 +6361,24 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5823
6361
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
5824
6362
  }
5825
6363
  }
6364
+ const policyAction = action === "stop" ? "stopRun" : action === "steer" ? "steerRun" : action === "schedule.create" ? "scheduleCreate" : action === "inspector.open" ? "inspectorOpen" : action === "project.open" ? "projectOpen" : undefined;
6365
+ if (policyAction) {
6366
+ // Child-safe mode is a hard capability boundary; the policy is an operator
6367
+ // preference. Refuse first, so the gate never prompts for an action that is
6368
+ // going to be rejected anyway and never masks the more specific reason.
6369
+ if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
6370
+ return { content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }], isError: true, details: { mode: "management", results: [] } };
6371
+ }
6372
+ const decision = resolveAuthorityDecision({ action: policyAction, ...(deps.config.authorityPolicy === undefined ? {} : { policy: deps.config.authorityPolicy }) });
6373
+ if (decision === "forbid") {
6374
+ return { content: [{ type: "text", text: `Authority policy forbids action '${action}'.` }], isError: true, details: { mode: "management", results: [] } };
6375
+ }
6376
+ if (decision === "confirm") {
6377
+ if (!ctx.hasUI) return { content: [{ type: "text", text: `Authority policy requires user confirmation for action '${action}', but this session has no interactive UI.` }], isError: true, details: { mode: "management", results: [] } };
6378
+ const confirmed = await ctx.ui.confirm(`Authorize subagent ${action}?`, `Authority policy requires confirmation before '${action}'.`);
6379
+ if (!confirmed) return { content: [{ type: "text", text: `Action '${action}' canceled; authority was not granted.` }], details: { mode: "management", results: [] } };
6380
+ }
6381
+ }
5826
6382
  if ((HERDR_PROJECT_PANE_ACTIONS as readonly string[]).includes(action)) {
5827
6383
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
5828
6384
  return { content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }], isError: true, details: { mode: "management", results: [] } };
@@ -5830,16 +6386,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5830
6386
  deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
5831
6387
  return handleHerdrProjectPaneAction(action as (typeof HERDR_PROJECT_PANE_ACTIONS)[number], paramsWithResolvedCwd, { cwd: requestCwd, state: deps.state, signal });
5832
6388
  }
5833
- if ((HERDR_INSPECTOR_ACTIONS as readonly string[]).includes(action)) {
6389
+ if ((INSPECTOR_ACTIONS as readonly string[]).includes(action)) {
5834
6390
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
5835
6391
  return { content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }], isError: true, details: { mode: "management", results: [] } };
5836
6392
  }
5837
6393
  deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
5838
- return handleHerdrInspectorAction(action as (typeof HERDR_INSPECTOR_ACTIONS)[number], paramsWithResolvedCwd, {
6394
+ return handleInspectorAction(action as (typeof INSPECTOR_ACTIONS)[number], paramsWithResolvedCwd, {
5839
6395
  state: deps.state,
5840
6396
  cwd: requestCwd,
5841
6397
  ...(deps.config.missions ? { missions: deps.config.missions } : {}),
5842
6398
  ...(deps.config.authorityPolicy ? { authorityPolicy: deps.config.authorityPolicy } : {}),
6399
+ plugins: createBuiltinInspectorPlugins(),
5843
6400
  signal,
5844
6401
  });
5845
6402
  }
@@ -5858,18 +6415,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5858
6415
  ...(currentSessionId ? { currentSessionId } : {}),
5859
6416
  });
5860
6417
  }
5861
- const policyAction = action === "stop" ? "stopRun" : action === "steer" ? "steerRun" : action === "schedule.create" ? "scheduleCreate" : undefined;
5862
- if (policyAction) {
5863
- const decision = resolveAuthorityDecision({ action: policyAction, ...(deps.config.authorityPolicy === undefined ? {} : { policy: deps.config.authorityPolicy }) });
5864
- if (decision === "forbid") {
5865
- return { content: [{ type: "text", text: `Authority policy forbids action '${action}'.` }], isError: true, details: { mode: "management", results: [] } };
5866
- }
5867
- if (decision === "confirm") {
5868
- if (!ctx.hasUI) return { content: [{ type: "text", text: `Authority policy requires user confirmation for action '${action}', but this session has no interactive UI.` }], isError: true, details: { mode: "management", results: [] } };
5869
- const confirmed = await ctx.ui.confirm(`Authorize subagent ${action}?`, `Authority policy requires confirmation before '${action}'.`);
5870
- if (!confirmed) return { content: [{ type: "text", text: `Action '${action}' canceled; authority was not granted.` }], details: { mode: "management", results: [] } };
5871
- }
5872
- }
5873
6418
  if ((WATCHDOG_TOOL_ACTIONS as readonly string[]).includes(action)) {
5874
6419
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
5875
6420
  return {
@@ -6062,7 +6607,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6062
6607
  }
6063
6608
  return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots, abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })));
6064
6609
  }
6065
- if (paramsWithResolvedCwd.view === "fleet") {
6610
+ if (paramsWithResolvedCwd.view === "fleet" || paramsWithResolvedCwd.view === "transcript") {
6066
6611
  return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots, abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })));
6067
6612
  }
6068
6613
  if (targetRunId) {
@@ -6071,12 +6616,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6071
6616
  if (resolved?.kind === "foreground") {
6072
6617
  const foreground = getForegroundControl(deps.state, resolved.id);
6073
6618
  if (foreground) {
6074
- if (paramsWithResolvedCwd.view === "transcript") {
6075
- return withBudget({
6076
- content: [{ type: "text", text: "Live foreground transcript is already visible in the expanded running subagent result. Persisted session transcript becomes inspectable after the foreground run completes when sessions are enabled." }],
6077
- details: { mode: "management", results: [] },
6078
- });
6079
- }
6080
6619
  return withBudget(foregroundStatusResult(foreground));
6081
6620
  }
6082
6621
  }
@@ -6086,13 +6625,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6086
6625
  }
6087
6626
  } else if (!hasDirectoryTarget) {
6088
6627
  const foreground = getForegroundControl(deps.state, undefined);
6089
- if (foreground && paramsWithResolvedCwd.view !== "transcript") return withBudget(foregroundStatusResult(foreground));
6090
- if (foreground && paramsWithResolvedCwd.view === "transcript") {
6091
- return withBudget({
6092
- content: [{ type: "text", text: "Live foreground transcript is already visible in the expanded running subagent result. Pass an async run id to inspect a background transcript." }],
6093
- details: { mode: "management", results: [] },
6094
- });
6095
- }
6628
+ if (foreground) return withBudget(foregroundStatusResult(foreground));
6096
6629
  }
6097
6630
  return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots, abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })));
6098
6631
  }
@@ -6113,9 +6646,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6113
6646
  const runId = location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir);
6114
6647
  const directoryStatus = location.asyncDir ? readStatus(location.asyncDir) : null;
6115
6648
  if (directoryStatus?.mode === "workflow") {
6116
- const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, workflowRunId: directoryStatus.runId || runId, asyncDirRoot: DIRS.async });
6117
- if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
6118
- return steerWorkflowForegroundTarget({ target: route.target, message, mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode), index: paramsWithResolvedCwd.index });
6649
+ return steerWorkflowRun({ state: deps.state, runId, asyncDir: location.asyncDir!, message, mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode), index: paramsWithResolvedCwd.index, signal });
6119
6650
  }
6120
6651
  if (location.asyncDir) {
6121
6652
  const unsupported = externalRunnerControlError(location.asyncDir, "steer");
@@ -6123,6 +6654,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6123
6654
  }
6124
6655
  return steerAsyncRun(compactOptional<Parameters<typeof steerAsyncRun>[0]>({
6125
6656
  state: deps.state,
6657
+ findPendingAsks: deps.findPendingAsks,
6126
6658
  runId,
6127
6659
  message,
6128
6660
  mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode),
@@ -6160,9 +6692,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6160
6692
  if (resolved?.kind !== "async") return { content: [{ type: "text", text: `No async run found for '${targetRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
6161
6693
  const resolvedStatus = resolved.location.asyncDir ? readStatus(resolved.location.asyncDir) : null;
6162
6694
  if (resolvedStatus?.mode === "workflow") {
6163
- const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, workflowRunId: resolvedStatus.runId || resolved.id, asyncDirRoot: DIRS.async });
6164
- if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
6165
- return steerWorkflowForegroundTarget({ target: route.target, message, mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode), index: paramsWithResolvedCwd.index });
6695
+ return steerWorkflowRun({ state: deps.state, runId: resolved.id, asyncDir: resolved.location.asyncDir!, message, mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode), index: paramsWithResolvedCwd.index, signal });
6166
6696
  }
6167
6697
  if (resolved.location.asyncDir) {
6168
6698
  const unsupported = externalRunnerControlError(resolved.location.asyncDir, "steer");
@@ -6170,6 +6700,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6170
6700
  }
6171
6701
  return steerAsyncRun(compactOptional<Parameters<typeof steerAsyncRun>[0]>({
6172
6702
  state: deps.state,
6703
+ findPendingAsks: deps.findPendingAsks,
6173
6704
  runId: resolved.id,
6174
6705
  message,
6175
6706
  mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode),
@@ -6371,6 +6902,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6371
6902
  config: deps.config,
6372
6903
  currentSessionId: deps.state.currentSessionId ?? ctx.sessionManager.getSessionId() ?? undefined,
6373
6904
  runtimeAgentOwner: deps.pi,
6905
+ onAgentsChanged: deps.onAgentsChanged,
6374
6906
  });
6375
6907
  }
6376
6908
 
@@ -6394,6 +6926,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6394
6926
  const normalized = normalizeRepeatedParallelCounts(paramsWithResolvedCwd);
6395
6927
  if (normalized.error) return normalized.error;
6396
6928
  const normalizedParams = normalized.params!;
6929
+ const outputSchemaError = validateLaunchOutputSchemaOverrides(normalizedParams);
6930
+ if (outputSchemaError) return buildRequestedModeError(normalizedParams, outputSchemaError);
6397
6931
 
6398
6932
  let effectiveParams = applyForceTopLevelAsyncOverride(
6399
6933
  normalizedParams,
@@ -6483,65 +7017,20 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6483
7017
 
6484
7018
  let forkSessionFileForIndex: (idx?: number) => string | undefined = () => undefined;
6485
7019
  let prepareForkSessionForIndex: (idx?: number) => Promise<void> = async () => {};
6486
- let forkThinkingOverrideForIndex: (idx?: number) => AgentConfig["thinking"] | undefined = () => undefined;
6487
- let prepareForkThinking = (_agentName: string, _index: number, _modelOverride?: string, _modelOverrideFromParent?: boolean, _modelOrigin?: ModelOrigin): void => {};
6488
- const forkThinkingRequirements = new Map<number, boolean>();
6489
- const forkThinkingDowngrades = new Map<number, string>();
7020
+ // Forked children keep their requested thinking level. Signed Anthropic thinking
7021
+ // blocks are stripped from the inherited transcript by the resolver (they are bound
7022
+ // to the parent session), which is not a reason to disable the child's own reasoning.
6490
7023
  try {
6491
- const forkAvailableModels = contextPolicy.usesFork ? ctx.modelRegistry.getAvailable().map(toModelInfo) : [];
6492
- const parentModel = requestParentModel;
6493
- prepareForkThinking = (agentName, index, modelOverride, modelOverrideFromParent, storedOrigin) => {
6494
- const agentConfig = agents.find((agent) => agent.name === agentName);
6495
- if (agentConfig?.runner?.type === "external-cli" || agentConfig?.runner?.type === "external-job") {
6496
- forkThinkingRequirements.set(index, true);
6497
- return;
6498
- }
6499
- const effectiveStoredOrigin = storedOrigin === "configured" && modelOverride === undefined && agentConfig?.model === undefined
6500
- ? undefined
6501
- : storedOrigin;
6502
- const origin = resolveModelOrigin({
6503
- fromParent: modelOverrideFromParent,
6504
- storedOrigin: effectiveStoredOrigin,
6505
- explicitModel: modelOverrideFromParent || effectiveStoredOrigin === "configured" ? undefined : modelOverride,
6506
- agentModel: agentConfig?.model,
6507
- parentModel,
6508
- });
6509
- const primaryModel = modelOverrideFromParent
6510
- ? modelOverride
6511
- : resolveEffectiveSubagentModel(
6512
- effectiveStoredOrigin === "configured" ? undefined : modelOverride,
6513
- agentConfig?.model,
6514
- parentModel,
6515
- forkAvailableModels,
6516
- agentConfig?.modelProvider ?? parentModel?.provider,
6517
- { source: origin === "explicit" ? "explicit" : "inherited" },
6518
- );
6519
- const candidates = buildModelCandidates(
6520
- primaryModel,
6521
- agentConfig?.fallbackModels,
6522
- forkAvailableModels,
6523
- agentConfig?.modelProvider ?? parentModel?.provider,
6524
- {
6525
- primaryModelFromParent: origin === "inherited",
6526
- origin,
6527
- },
6528
- );
6529
- forkThinkingRequirements.set(
6530
- index,
6531
- candidates.length === 0
6532
- || candidates.some((candidate) => forkedChildRequiresThinkingOff(candidate, forkAvailableModels, parentModel?.provider)),
6533
- );
6534
- };
6535
7024
  const pruneSession = contextPolicy.usesFork && deps.config.forkContext?.mode === "pruned"
6536
7025
  ? await createPrunedForkSessionWriter(ctx, deps.config.forkContext, signal)
6537
7026
  : undefined;
6538
- const forkContextResolver = createForkContextResolver(ctx.sessionManager, contextPolicy.usesFork ? "fork" : undefined, {
6539
- forceThinkingOffForIndex: (index) => forkThinkingRequirements.get(index) ?? true,
6540
- ...(pruneSession ? { pruneSession } : {}),
6541
- });
7027
+ const forkContextResolver = createForkContextResolver(
7028
+ ctx.sessionManager,
7029
+ contextPolicy.usesFork ? "fork" : undefined,
7030
+ pruneSession ? { pruneSession } : {},
7031
+ );
6542
7032
  prepareForkSessionForIndex = forkContextResolver.prepareSessionForIndex;
6543
7033
  forkSessionFileForIndex = forkContextResolver.sessionFileForIndex;
6544
- forkThinkingOverrideForIndex = forkContextResolver.thinkingOverrideForIndex;
6545
7034
  } catch (error) {
6546
7035
  return toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);
6547
7036
  }
@@ -6622,7 +7111,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6622
7111
 
6623
7112
  let sessionRoot: string;
6624
7113
  if (effectiveParams.sessionDir) {
6625
- sessionRoot = path.resolve(deps.expandTilde(effectiveParams.sessionDir));
7114
+ // An explicit sessionDir is a root keyed by this launch's run id so
7115
+ // concurrent children resolve distinct per-child session files.
7116
+ sessionRoot = path.join(path.resolve(deps.expandTilde(effectiveParams.sessionDir)), runId);
6626
7117
  } else {
6627
7118
  const baseSessionRoot = deps.config.defaultSessionDir
6628
7119
  ? path.resolve(deps.expandTilde(deps.config.defaultSessionDir))
@@ -6642,23 +7133,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6642
7133
  }
6643
7134
  const sessionDirForIndex = (idx?: number) =>
6644
7135
  path.join(sessionRoot, `run-${idx ?? 0}`);
6645
- const forkSessionFileForTask: ForkSessionFileForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent, modelOrigin) => {
7136
+ const forkSessionFileForTask: ForkSessionFileForTask = (agentName, idx = 0) => {
6646
7137
  if (!shouldForkAgent(contextPolicy, agentName)) return undefined;
6647
- prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin);
6648
7138
  return forkSessionFileForIndex(idx);
6649
7139
  };
6650
- const prepareForkSessionForTask: PrepareForkSessionForTask = async (agentName, idx = 0, modelOverride, modelOverrideFromParent, modelOrigin) => {
7140
+ const prepareForkSessionForTask: PrepareForkSessionForTask = async (agentName, idx = 0) => {
6651
7141
  if (!shouldForkAgent(contextPolicy, agentName)) return;
6652
- prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin);
6653
7142
  await prepareForkSessionForIndex(idx);
6654
7143
  };
6655
- const forkThinkingOverrideForTask: ForkThinkingOverrideForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent, modelOrigin) => {
6656
- if (!shouldForkAgent(contextPolicy, agentName)) return delegatedThinkingOverride;
6657
- prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin);
6658
- const override = forkThinkingOverrideForIndex(idx);
6659
- if (override === "off") forkThinkingDowngrades.set(idx, agentName);
6660
- return override ?? delegatedThinkingOverride;
6661
- };
7144
+ const thinkingOverrideForTask: ThinkingOverrideForTask = () => delegatedThinkingOverride;
6662
7145
  const childSessionFileForTask: ForkSessionFileForTask = (agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin) =>
6663
7146
  forkSessionFileForTask(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin) ?? path.join(sessionDirForIndex(idx), "session.jsonl");
6664
7147
  const childSessionFileForIndex = (idx?: number) =>
@@ -6747,7 +7230,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6747
7230
  sessionDirForIndex,
6748
7231
  sessionFileForIndex: childSessionFileForIndex,
6749
7232
  sessionFileForTask: childSessionFileForTask,
6750
- thinkingOverrideForTask: forkThinkingOverrideForTask,
7233
+ thinkingOverrideForTask,
6751
7234
  artifactConfig,
6752
7235
  artifactsDir,
6753
7236
  backgroundRequestedWhileClarifying,
@@ -6760,6 +7243,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6760
7243
  timeoutMs: foregroundTimeout.timeoutMs,
6761
7244
  toolBudget: runToolBudget.toolBudget,
6762
7245
  usageBudget: usageBudget.budget,
7246
+ inheritedUsageBudget,
6763
7247
  allowZeroToolBudget,
6764
7248
  configToolBudget: configToolBudget.toolBudget,
6765
7249
  configToolTimeoutMs: deps.config.toolTimeoutMs,
@@ -6860,7 +7344,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6860
7344
  availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
6861
7345
  currentProvider: requestParentModel?.provider,
6862
7346
  modelScope,
6863
- thinkingOverrideForTask: forkThinkingOverrideForTask,
7347
+ thinkingOverrideForTask,
6864
7348
  dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
6865
7349
  });
6866
7350
  } catch (error) {
@@ -6954,7 +7438,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6954
7438
  const asyncResult = await runAsyncPath(execData, deps);
6955
7439
  if (asyncResult) {
6956
7440
  asyncLaunchFailed = asyncResult.isError === true;
6957
- return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(asyncResult, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget));
7441
+ return attachMission(withRunFanoutBudget(withResolvedContext(asyncResult, contextPolicy.contextSummary), runFanoutBudget));
6958
7442
  }
6959
7443
  if (foregroundControl) {
6960
7444
  writeNestedForegroundEvent("subagent.nested.started");
@@ -6964,11 +7448,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6964
7448
  if (hasSingle) {
6965
7449
  const result = await runSinglePath(execData, deps);
6966
7450
  writeNestedForegroundEvent("subagent.nested.completed", result);
6967
- return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget, { annotateContent: runFanoutAnnotateContent }));
7451
+ return attachMission(withRunFanoutBudget(withResolvedContext(result, contextPolicy.contextSummary), runFanoutBudget, { annotateContent: runFanoutAnnotateContent }));
6968
7452
  }
6969
7453
  } catch (error) {
6970
7454
  asyncLaunchFailed = effectiveAsync;
6971
- const errorResult = withForkThinkingNotes(toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary), forkThinkingDowngrades);
7455
+ const errorResult = toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);
6972
7456
  if (nestedForegroundStarted) writeNestedForegroundEvent("subagent.nested.completed", errorResult);
6973
7457
  return attachMission(errorResult);
6974
7458
  } finally {
@@ -6976,7 +7460,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6976
7460
  if (activeAsyncCapacity && !activeAsyncCapacity.owner.runnerStartedAt) activeAsyncCapacity.rollback();
6977
7461
  if (foregroundControl) {
6978
7462
  settleForegroundSchedulingOwner(foregroundControl);
6979
- removeForegroundControlIfIdle(deps.state, runId);
7463
+ removeForegroundControlIfIdle(deps.state, runId, deps.trackRetainedNestedRoute);
6980
7464
  }
6981
7465
  }
6982
7466
 
@@ -7023,11 +7507,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7023
7507
  }
7024
7508
  let publicParams = normalized.params as SubagentParamsLike;
7025
7509
  if (publicParams.workflow !== undefined) {
7026
- const resolved = resolveWorkflowResource(publicParams.workflow, publicParams.args);
7510
+ const resolved = resolveWorkflowResource(publicParams.workflow, publicParams.args, ctx.sessionManager.getSessionId() ?? undefined);
7027
7511
  if (!resolved.ok) return Promise.resolve({ content: [{ type: "text", text: resolved.error }], isError: true, details: { mode: "workflow", results: [] } });
7028
7512
  const { workflow: _workflow, args: _args, ...withoutResourceInput } = publicParams;
7029
7513
  publicParams = { ...withoutResourceInput, workflowScript: resolved.resource.script };
7030
7514
  workflowResourcePermits.set(publicParams, resolved.resource.permit);
7515
+ } else if (publicParams.workflowScript !== undefined || publicParams.workflowScriptPath !== undefined) {
7516
+ const normalizedArgs = normalizeWorkflowArgs(publicParams.args);
7517
+ if ("error" in normalizedArgs) return Promise.resolve({ content: [{ type: "text", text: normalizedArgs.error }], isError: true, details: { mode: publicParams.action ? "management" : "workflow", results: [] } });
7518
+ publicParams = { ...publicParams, args: deepFreezeWorkflowArgs(normalizedArgs.args) };
7031
7519
  }
7032
7520
  const loaded = loadWorkflowScriptPath(publicParams, ctx.cwd);
7033
7521
  if (loaded.error) {
@@ -7070,16 +7558,27 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7070
7558
  ctx: ExtensionContext,
7071
7559
  ) => {
7072
7560
  const ownerSessionId = resolveCurrentSessionId(ctx.sessionManager);
7073
- let ownerExecutor = scheduledOwnerExecutors.get(ownerSessionId);
7074
- if (!ownerExecutor) {
7075
- ownerExecutor = createSubagentExecutor({
7076
- ...deps,
7077
- state: createScheduledOwnerState(deps.state, ownerSessionId, ctx),
7078
- });
7079
- scheduledOwnerExecutors.set(ownerSessionId, ownerExecutor);
7561
+ const runtimeOwnerId = ctx.sessionManager.getSessionId() || null;
7562
+ let ownerExecutors = scheduledOwnerExecutors.get(runtimeOwnerId);
7563
+ if (!ownerExecutors) {
7564
+ ownerExecutors = new Map();
7565
+ scheduledOwnerExecutors.set(runtimeOwnerId, ownerExecutors);
7080
7566
  }
7081
- return ownerExecutor.executePublic(id, params, signal, undefined, ctx);
7567
+ let owner = ownerExecutors.get(ownerSessionId);
7568
+ if (!owner) {
7569
+ const state = createScheduledOwnerState(deps.state, ownerSessionId, ctx);
7570
+ owner = { state, executor: createSubagentExecutor({ ...deps, state }) };
7571
+ ownerExecutors.set(ownerSessionId, owner);
7572
+ }
7573
+ return owner.executor.executePublic(id, params, signal, undefined, ctx);
7082
7574
  };
7083
7575
 
7084
- return { execute: executeWithSingleDispatchGuard, executePublic, executeDelegated, executeScheduled };
7576
+ function* getCurrentSupervisorOwnerStates(): Iterable<SubagentState> {
7577
+ const ownerId = deps.state.supervisorOwnerSessionId;
7578
+ if (!ownerId) return;
7579
+ // File transitions remain separate entries; other runtime owners are never scanned.
7580
+ for (const owner of scheduledOwnerExecutors.get(ownerId)?.values() ?? []) yield owner.state;
7581
+ }
7582
+
7583
+ return { execute: executeWithSingleDispatchGuard, executePublic, executeDelegated, executeScheduled, getCurrentSupervisorOwnerStates };
7085
7584
  }