@xzzpig/pi-subagents 0.14.0 → 0.15.1

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 (206) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/README.md +7 -6
  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 +55 -136
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -74
  9. package/docs/fork-extensions.md +184 -0
  10. package/docs/missions.md +10 -2
  11. package/docs/models.md +11 -22
  12. package/docs/observability.md +63 -11
  13. package/docs/standalone-background.md +59 -0
  14. package/docs/tool-reference.md +42 -23
  15. package/docs/watchdog.md +39 -10
  16. package/docs/workflows.md +58 -19
  17. package/index.ts +5 -2
  18. package/inspector-runner.mjs +2 -2
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  21. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  22. package/package.json +9 -4
  23. package/prompts/parallel-review.md +1 -1
  24. package/runner-peer-loader.mjs +24 -0
  25. package/runner-peer-preload.mjs +36 -0
  26. package/skills/pi-subagents/SKILL.md +34 -22
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  28. package/skills/pi-subagents/references/execution-controls.md +27 -8
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  32. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  33. package/src/agents/advertised-agent-prompt.ts +94 -0
  34. package/src/agents/agent-eject.ts +339 -0
  35. package/src/agents/agent-management.ts +79 -387
  36. package/src/agents/agent-serializer.ts +6 -3
  37. package/src/agents/agents.ts +198 -72
  38. package/src/agents/builtin-names.ts +1 -0
  39. package/src/agents/chain-serializer.ts +5 -0
  40. package/src/agents/runtime-agent-registry.ts +7 -6
  41. package/src/api/agent-management.ts +2 -2
  42. package/src/api/delegation.ts +4 -0
  43. package/src/api/preflight.ts +131 -86
  44. package/src/api/required-child-extensions.ts +6 -0
  45. package/src/api/shared-types.ts +3 -1
  46. package/src/api/workflow-resources.ts +6 -0
  47. package/src/extension/config.ts +14 -37
  48. package/src/extension/fanout-child.ts +68 -5
  49. package/src/extension/herdr-pi-bridge.ts +164 -0
  50. package/src/extension/index.ts +141 -51
  51. package/src/extension/public-execution.ts +7 -6
  52. package/src/extension/rpc.ts +8 -21
  53. package/src/extension/schemas.ts +86 -84
  54. package/src/extension/tool-description.ts +32 -79
  55. package/src/inspectors/actions.ts +148 -0
  56. package/src/inspectors/ghostty/actions.ts +74 -0
  57. package/src/inspectors/ghostty/plugin.ts +17 -0
  58. package/src/inspectors/herdr/actions.ts +99 -179
  59. package/src/inspectors/herdr/plugin.ts +20 -0
  60. package/src/inspectors/herdr/project-panes.ts +4 -1
  61. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  62. package/src/inspectors/plugins.ts +8 -0
  63. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  64. package/src/inspectors/types.ts +51 -0
  65. package/src/integrations/pi-web-session-liveness.ts +73 -0
  66. package/src/intercom/intercom-bridge.ts +50 -8
  67. package/src/intercom/native-supervisor-channel.ts +142 -115
  68. package/src/intercom/supervisor-ui.ts +3 -2
  69. package/src/missions/workflow-state.ts +37 -16
  70. package/src/policy/authority.ts +4 -0
  71. package/src/profiles/profiles.ts +12 -6
  72. package/src/runs/background/active-async-capacity.ts +22 -18
  73. package/src/runs/background/active-run-index.ts +17 -1
  74. package/src/runs/background/async-execution.ts +359 -176
  75. package/src/runs/background/async-job-tracker.ts +41 -7
  76. package/src/runs/background/async-resume.ts +19 -12
  77. package/src/runs/background/async-retention.ts +20 -0
  78. package/src/runs/background/async-status-snapshot.ts +10 -12
  79. package/src/runs/background/async-status.ts +38 -35
  80. package/src/runs/background/auto-drain.ts +59 -35
  81. package/src/runs/background/binary-bootstrap.ts +38 -0
  82. package/src/runs/background/chain-append.ts +1 -1
  83. package/src/runs/background/chain-root-attachment.ts +22 -33
  84. package/src/runs/background/control-channel.ts +78 -44
  85. package/src/runs/background/fleet-view.ts +30 -2
  86. package/src/runs/background/notify.ts +193 -19
  87. package/src/runs/background/owned-process-tree.ts +35 -8
  88. package/src/runs/background/process-terminal.ts +23 -23
  89. package/src/runs/background/result-files.ts +8 -4
  90. package/src/runs/background/result-watcher.ts +19 -2
  91. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  92. package/src/runs/background/run-child-session.ts +118 -41
  93. package/src/runs/background/run-status.ts +78 -5
  94. package/src/runs/background/runner-aliases.ts +22 -5
  95. package/src/runs/background/runner-child-launch.ts +93 -0
  96. package/src/runs/background/runner-child-sessions.ts +5 -4
  97. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  98. package/src/runs/background/scheduled-runs.ts +51 -18
  99. package/src/runs/background/stale-run-reconciler.ts +38 -12
  100. package/src/runs/background/steering.ts +20 -2
  101. package/src/runs/background/subagent-runner.ts +770 -444
  102. package/src/runs/background/subagent-wait.ts +179 -28
  103. package/src/runs/background/wait-completions.ts +79 -27
  104. package/src/runs/background/wait-subscriptions.ts +9 -3
  105. package/src/runs/background/wait-tool.ts +5 -3
  106. package/src/runs/foreground/async-steering-action.ts +37 -7
  107. package/src/runs/foreground/async-stop-action.ts +93 -3
  108. package/src/runs/foreground/execution.ts +174 -194
  109. package/src/runs/foreground/foreground-history.ts +5 -2
  110. package/src/runs/foreground/prompt-audit.ts +12 -6
  111. package/src/runs/foreground/subagent-executor.ts +915 -411
  112. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  113. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  114. package/src/runs/shared/acceptance.ts +54 -14
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +172 -78
  117. package/src/runs/shared/capability-ceiling.ts +2 -0
  118. package/src/runs/shared/child-hooks.ts +167 -3
  119. package/src/runs/shared/child-launch-plan.ts +15 -3
  120. package/src/runs/shared/child-launch.ts +49 -85
  121. package/src/runs/shared/child-lifecycle.ts +6 -3
  122. package/src/runs/shared/child-runtime-config.ts +8 -1
  123. package/src/runs/shared/child-session.ts +130 -24
  124. package/src/runs/shared/child-tool-plan.ts +149 -112
  125. package/src/runs/shared/completion-evidence.ts +2 -2
  126. package/src/runs/shared/completion-guard.ts +6 -3
  127. package/src/runs/shared/dynamic-fanout.ts +2 -2
  128. package/src/runs/shared/effective-system-prompt.ts +33 -0
  129. package/src/runs/shared/external-cli-contract.ts +11 -1
  130. package/src/runs/shared/external-cli-preflight.ts +6 -2
  131. package/src/runs/shared/external-cli-runner.ts +9 -7
  132. package/src/runs/shared/herdr-connection.ts +134 -0
  133. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  134. package/src/runs/shared/herdr-machine.ts +279 -0
  135. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  136. package/src/runs/shared/herdr-placed-run.ts +263 -0
  137. package/src/runs/shared/host-step-status.ts +11 -11
  138. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  139. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  140. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  141. package/src/runs/shared/model-scope.ts +1 -1
  142. package/src/runs/shared/nested-events.ts +27 -34
  143. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  144. package/src/runs/shared/parallel-handoff.ts +57 -12
  145. package/src/runs/shared/parallel-utils.ts +10 -4
  146. package/src/runs/shared/pi-spawn.ts +10 -0
  147. package/src/runs/shared/profile-extensions.ts +134 -0
  148. package/src/runs/shared/profile-launch-env.ts +113 -0
  149. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  150. package/src/runs/shared/run-fanout-budget.ts +8 -8
  151. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  152. package/src/runs/shared/sandbox-profile-guard.ts +34 -0
  153. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  154. package/src/runs/shared/task-intent.ts +46 -13
  155. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  156. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  157. package/src/runs/shared/worktree-setup-command.ts +213 -0
  158. package/src/runs/shared/worktree.ts +437 -214
  159. package/src/shared/child-cache-retention.ts +43 -0
  160. package/src/shared/fork-context.ts +15 -72
  161. package/src/shared/launch-contract.ts +70 -8
  162. package/src/shared/model-response-aliases.ts +13 -0
  163. package/src/shared/opencode-session-headers.ts +30 -0
  164. package/src/shared/permission-profile.ts +14 -0
  165. package/src/shared/pruned-fork.ts +1 -1
  166. package/src/shared/required-child-extensions.ts +81 -0
  167. package/src/shared/sandbox-profile.ts +14 -0
  168. package/src/shared/settings.ts +5 -2
  169. package/src/shared/shortcuts.ts +0 -4
  170. package/src/shared/types.ts +163 -90
  171. package/src/shared/utils.ts +10 -2
  172. package/src/shared/watch-strategy.ts +2 -0
  173. package/src/shared/workflow-child-permit.ts +18 -13
  174. package/src/slash/delegation-adapters.ts +3 -1
  175. package/src/slash/delegation-request.ts +14 -0
  176. package/src/slash/slash-commands.ts +2 -7
  177. package/src/slash/subagents-admin.ts +31 -14
  178. package/src/tui/fleet-status.ts +165 -20
  179. package/src/tui/fleet.ts +30 -19
  180. package/src/tui/render.ts +210 -50
  181. package/src/watchdog/child-status.ts +28 -28
  182. package/src/watchdog/lsp-diagnostics.ts +1 -1
  183. package/src/watchdog/model-selection.ts +21 -1
  184. package/src/watchdog/permission-arbiter.ts +5 -2
  185. package/src/watchdog/register-child.ts +10 -2
  186. package/src/watchdog/register-main.ts +39 -35
  187. package/src/watchdog/render.ts +1 -1
  188. package/src/watchdog/review.ts +122 -74
  189. package/src/watchdog/rules.ts +1 -1
  190. package/src/watchdog/runtime.ts +100 -27
  191. package/src/watchdog/scope.ts +1 -1
  192. package/src/watchdog/settings.ts +3 -0
  193. package/src/watchdog/tool-actions.ts +13 -12
  194. package/src/watchdog/turn-delta.ts +23 -0
  195. package/src/watchdog/types.ts +5 -3
  196. package/src/watchdog/warning-format.ts +1 -1
  197. package/src/workflows/chat-progress.ts +3 -3
  198. package/src/workflows/scripted-workflow.ts +349 -26
  199. package/src/workflows/workflow-checklist.ts +17 -20
  200. package/src/workflows/workflow-child-summary.ts +57 -8
  201. package/src/workflows/workflow-preflight.ts +19 -19
  202. package/src/workflows/workflow-receipt.ts +24 -6
  203. package/src/workflows/workflow-resources.ts +108 -22
  204. package/src/workflows/workflow-settlement.ts +3 -0
  205. package/src/runs/shared/model-exclusions.ts +0 -373
  206. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -28,7 +28,11 @@ 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 { projectScopedProfileTrustError } from "../shared/sandbox-profile-guard.ts";
35
+ import { projectChainOutputSchemas, resolveEffectiveOutputSchema } from "../shared/child-launch-plan.ts";
32
36
  import { formatRetainedChildren, listRetainedChildren } from "../background/retained-children.ts";
33
37
  import { resolveModelScopesForAgent, type ModelScopeConfig } from "../shared/model-scope.ts";
34
38
  import { recordRun } from "../shared/run-history.ts";
@@ -49,10 +53,11 @@ import { updateActiveRunIndex } from "../background/active-run-index.ts";
49
53
  import { steeringReceipt } from "../background/steering.ts";
50
54
  import { acquireActiveAsyncCapacity, ActiveAsyncCapacityError, getActiveAsyncCapacitySnapshot, resolveAbandonedSlotReleaseAfterMs, resolveMaxActiveAsyncRunsPerSession, transferActiveAsyncCapacity, type ActiveAsyncCapacityHandle } from "../background/active-async-capacity.ts";
51
55
  import { isScheduledRunAction } from "../background/scheduled-runs.ts";
56
+ import { encodeIndexSegment } from "../background/index-segment.ts";
52
57
  import { enqueueChainAppendRequest, readPendingChainAppendRequests, runnerStepOutputNames } from "../background/chain-append.ts";
53
58
  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";
59
+ import { normalizeGateAcceptance, resolveAcceptanceReportMode, validateAcceptanceInput, validateExecutionAcceptance, validateExecutionAcceptancePolicy } from "../shared/acceptance.ts";
60
+ import { canPreferFork, createForkContextResolver, resolveSubagentLaunchContext } from "../../shared/fork-context.ts";
56
61
  import { createPrunedForkSessionWriter } from "../../shared/pruned-fork.ts";
57
62
  import { resolveCurrentSessionId } from "../../shared/session-identity.ts";
58
63
  import { currentCompletionOwnerId } from "../../shared/completion-owner.ts";
@@ -60,16 +65,18 @@ import { applyIntercomBridgeToAgent, INTERCOM_BRIDGE_MARKER, resolveIntercomBrid
60
65
  import { formatControlIntercomMessage, formatControlNoticeMessage, resolveControlConfig, shouldNotifyControlEvent } from "../shared/subagent-control.ts";
61
66
  import { formatSpawnBudget, getSpawnBudgetSnapshot, grantSpawnBudget, preflightSpawnBudget, preflightSpawnBudgetGrant, reserveSpawnBudget } from "../shared/spawn-budget.ts";
62
67
  import { claimRunFanoutBatch, claimRunFanoutBatchWithCommit, createRunFanoutBudget, formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor, RunFanoutLimitError, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
68
+ import { retainLiveForegroundNestedRoute } from "../../integrations/pi-web-session-liveness.ts";
63
69
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
64
70
  import { usageBudgetExceededMessage, usageBudgetState, validateUsageBudgetConfig } from "../shared/usage-budget.ts";
65
71
  import { intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
66
- import { isAgentContractV1 } from "../shared/agent-contract.ts";
72
+ import { isAgentContract } from "../shared/agent-contract.ts";
67
73
  import { normalizeExtensionBindings, type ExtensionBindings } from "../shared/extension-bindings.ts";
74
+ import { resolveRequiredChildExtensions } from "../../shared/required-child-extensions.ts";
68
75
  import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, outputPathMappingFromTask, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
69
76
  import { assertJsonSchemaObject, cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
70
77
  import { compactForegroundDetails, getSingleResultOutput, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage, toAgentToolUsage } from "../../shared/utils.ts";
71
78
  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";
79
+ import { discardPreservedWorktrees, formatParallelHandoffError, formatParallelHandoffReference, formatStoredParallelHandoffCleanup, parallelHandoffPath, readParallelHandoffManifest, recordParallelHandoffMerge, recordParallelHandoffSupersession, writeParallelHandoffGroup, writeWorktreeSetupHandoff } from "../shared/parallel-handoff.ts";
73
80
  import { summarizeContextModes, type ContextMode, type ContextSummary } from "../shared/context-mode.ts";
74
81
  import {
75
82
  attachNestedChildrenToResultChildren,
@@ -80,19 +87,20 @@ import {
80
87
  stripDetailsOutputsForIntercomReceipt,
81
88
  } from "../../intercom/result-intercom.ts";
82
89
  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";
90
+ import { closeSteerInbox, consumeSteerRequests, deliverInterruptRequest, readRevivalBriefs, requestAsyncSteer, watchAsyncControlInbox, type SteerDeliveryMode, type SteerRequest } from "../background/control-channel.ts";
91
+ import { createSteeringStatus, recordSteeringRequest, steeringStatus, updateSteeringTarget, waitForSteeringAction } from "../background/steering.ts";
85
92
  import { canQueueRetainedAsyncFollowUp, steerAsyncRun } from "./async-steering-action.ts";
86
93
  import {
87
94
  resolveWorkflowForegroundSteeringTarget,
88
95
  steerWorkflowForegroundTarget,
96
+ steerWorkflowRun,
89
97
  } from "./workflow-foreground-steering.ts";
90
98
  import { stopAsyncRun } from "./async-stop-action.ts";
91
99
  import { dismissRecoveredWorkflow } from "./async-dismiss-action.ts";
92
100
  import { promotePausedWorkflowIfSettled, reconcileDetachedWorkflowChildCompletion } from "./workflow-detach-reconcile.ts";
93
101
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
94
102
  import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
95
- import { resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
103
+ import { fallbackResultPayloadPathForSessionRun, removeResultIndex, resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
96
104
  import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, inheritedNestedParentAddressOf, inheritedNestedRouteOf, resolveNestedAsyncDir, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedParentAddress, type NestedRoute, type NestedRunResolutionScope } from "../shared/nested-events.ts";
97
105
  import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
98
106
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
@@ -102,6 +110,7 @@ import { inspectSubagentStatus } from "../background/run-status.ts";
102
110
  import { getExternalJobProvider } from "../../api/external-job-provider.ts";
103
111
  import { externalJobFollowUpRequestDigest, externalJobFollowUpRequestId, externalJobFollowUpRunId, externalJobPromptDigest, externalJobStableJson } from "../shared/external-job-runner.ts";
104
112
  import { externalCliReceiptMetadata, normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
113
+ import { formatHerdrMachineRunnerUnsupported, resolveHerdrMachinePlacement } from "../shared/herdr-machine.ts";
105
114
  import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.ts";
106
115
  import { handleMissionAction, MISSION_ACTIONS } from "../../missions/actions.ts";
107
116
  import { attachMissionToLaunchResult, prepareMissionLaunch, writeMissionAsyncBinding, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
@@ -109,14 +118,16 @@ import { MissionNotFoundError, updateMission } from "../../missions/store.ts";
109
118
  import type { MissionWorkflowChildUpdate } from "../../missions/types.ts";
110
119
  import { createMissionWorkflowState } from "../../missions/workflow-state.ts";
111
120
  import { resolveAuthorityDecision } from "../../policy/authority.ts";
112
- import { handleHerdrInspectorAction, HERDR_INSPECTOR_ACTIONS } from "../../inspectors/herdr/actions.ts";
121
+ import { handleInspectorAction, INSPECTOR_ACTIONS } from "../../inspectors/actions.ts";
122
+ import { createBuiltinInspectorPlugins } from "../../inspectors/plugins.ts";
113
123
  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";
124
+ import { previewSimpleWorkflowRun, runWorkflowScript, validateWorkflowScript, WorkflowScriptError, type WorkflowChildSettledNotification, type WorkflowLanePlan, type WorkflowReceiptResumeReference, type WorkflowScriptChildResult, type WorkflowScriptTraceEntry, type WorkflowSteerOptions, type WorkflowSteerResult } from "../../workflows/scripted-workflow.ts";
125
+ import { formatIncrementalChildCompletion, incrementalChildCompletionTriggersTurn } from "../background/notify.ts";
115
126
  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";
127
+ import { buildWorkflowReceipt, readWorkflowReceipt, workflowReceiptPath, resolveWorkflowReceiptResumeEntry, writeWorkflowReceipt, type WorkflowReceipt, type WorkflowReceiptState } from "../../workflows/workflow-receipt.ts";
117
128
  import { upsertHostStep, validHostStepNodes } from "../shared/host-step-status.ts";
118
129
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
119
- import { parseWorkflowChildSummary, workflowChildSummary } from "../../workflows/workflow-child-summary.ts";
130
+ import { parseWorkflowChildSummary, workflowChildProgress, workflowChildSummary } from "../../workflows/workflow-child-summary.ts";
120
131
  import { resolveWorkflowChatProgress, type WorkflowChatProgressProjection } from "../../workflows/chat-progress.ts";
121
132
  import { annotateWorkflowPreflightTrace, formatWorkflowPreflight, formatWorkflowPreflightWarnings, normalizeWorkflowPreflight, workflowPreflightWarnings } from "../../workflows/workflow-preflight.ts";
122
133
  import {
@@ -129,10 +140,14 @@ import {
129
140
  type WorkflowResourceAuthority,
130
141
  type WorkflowResourcePermit,
131
142
  } from "../../shared/workflow-child-permit.ts";
132
- import { resolveWorkflowResource } from "../../workflows/workflow-resources.ts";
143
+ import { deepFreezeWorkflowArgs, normalizeWorkflowArgs, resolveWorkflowResource } from "../../workflows/workflow-resources.ts";
144
+ import { stableJsonDigest } from "../../shared/launch-contract.ts";
133
145
  import {
134
146
  cleanupWorktrees,
135
147
  createWorktrees,
148
+ preflightWorktreeSource,
149
+ withWorktreeTransaction,
150
+ type WorktreeSetupProgress,
136
151
  diffWorktrees,
137
152
  formatWorktreeDiffSummary,
138
153
  type WorktreeSetup,
@@ -155,7 +170,7 @@ import {
155
170
  type ForegroundSteerInput,
156
171
  type ForegroundSteerOutcome,
157
172
  type ForegroundRunControl,
158
- type HostStepNodeV1,
173
+ type HostStepNode,
159
174
  type IntercomBridgeConfig,
160
175
  type IntercomEventBus,
161
176
  type JsonSchemaObject,
@@ -172,7 +187,7 @@ import {
172
187
  type ToolBudgetConfig,
173
188
  type Usage,
174
189
  type UsageBudgetConfig,
175
- type WorkflowResourceProvenanceV1,
190
+ type WorkflowResourceProvenance,
176
191
  type WorkflowGraphNode,
177
192
  type WorkflowGraphSnapshot,
178
193
  type WorkflowNodeStatus,
@@ -192,6 +207,7 @@ import {
192
207
  resolveMaxSubagentSpawnsPerRun,
193
208
  wrapForkTask,
194
209
  type ScheduleOrigin,
210
+ type SteeringTargetState,
195
211
  } from "../../shared/types.ts";
196
212
  import { deriveChildSessionName } from "../../shared/child-session-name.ts";
197
213
 
@@ -277,6 +293,7 @@ interface TaskParam {
277
293
  agent: string;
278
294
  task: string;
279
295
  cwd?: string;
296
+ machine?: string;
280
297
  count?: number;
281
298
  output?: string | boolean;
282
299
  outputMode?: "inline" | "file-only";
@@ -285,7 +302,7 @@ interface TaskParam {
285
302
  model?: string;
286
303
  fast?: boolean;
287
304
  skill?: string | string[] | boolean;
288
- outputSchema?: JsonSchemaObject;
305
+ outputSchema?: JsonSchemaObject | false;
289
306
  acceptance?: AcceptanceInput;
290
307
  agentContract?: AgentContract;
291
308
  toolBudget?: ToolBudgetConfig;
@@ -324,7 +341,7 @@ export interface SubagentParamsLike {
324
341
  workflowScriptPath?: string;
325
342
  globalConcurrencyLimit?: number;
326
343
  maxSubagentSpawnsPerRun?: number;
327
- preflight?: import("../../shared/types.ts").WorkflowPreflightV1;
344
+ preflight?: import("../../shared/types.ts").WorkflowPreflight;
328
345
  chatProgress?: "auto" | "off" | "live-card";
329
346
  isolation?: "none" | "worktree";
330
347
  step?: ChainStep;
@@ -361,6 +378,8 @@ export interface SubagentParamsLike {
361
378
  foregroundOnly?: boolean;
362
379
  timeoutMs?: number;
363
380
  maxRuntimeMs?: number;
381
+ /** Async runs only: steer the child to checkpoint and stop this many ms before the run deadline. */
382
+ checkpointBeforeDeadlineMs?: number;
364
383
  /** Optional hard per-tool-call timeout (ms). Known-fast tools also have a default. */
365
384
  toolTimeoutMs?: number;
366
385
  toolBudget?: ToolBudgetConfig;
@@ -370,6 +389,9 @@ export interface SubagentParamsLike {
370
389
  control?: ControlConfig;
371
390
  sessionDir?: string;
372
391
  cwd?: string;
392
+ machine?: string;
393
+ /** Internal: the typed cwd when a machine is set, kept as a remote path and never resolved locally. */
394
+ machineCwd?: string;
373
395
  maxOutput?: MaxOutputConfig;
374
396
  artifacts?: boolean;
375
397
  includeProgress?: boolean;
@@ -389,7 +411,7 @@ export interface SubagentParamsLike {
389
411
  /** Internal-only; not part of the public tool schema. Wired for single-run reads (chain steps use their own field). */
390
412
  reads?: string[] | false;
391
413
  outputMode?: "inline" | "file-only";
392
- outputSchema?: JsonSchemaObject;
414
+ outputSchema?: JsonSchemaObject | false;
393
415
  agentScope?: unknown;
394
416
  chainDir?: string;
395
417
  acceptance?: AcceptanceInput;
@@ -398,6 +420,7 @@ export interface SubagentParamsLike {
398
420
  at?: string;
399
421
  every?: string;
400
422
  sessionOnly?: boolean;
423
+ quiet?: boolean;
401
424
  on?: string | number;
402
425
  timezone?: string;
403
426
  overlap?: "skip";
@@ -435,9 +458,12 @@ interface ExecutorDeps {
435
458
  getSubagentSessionRoot: (parentSessionFile: string | null) => string;
436
459
  expandTilde: (p: string) => string;
437
460
  discoverAgents: (cwd: string, scope: AgentScope, preferredModelProvider?: string) => { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig; maxThinking?: AgentConfig["maxThinking"]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] };
461
+ onAgentsChanged?: () => void;
438
462
  allowMutatingManagementActions?: boolean;
439
463
  activateSupervisorTransport?: () => void;
464
+ findPendingAsks?: Parameters<typeof steerAsyncRun>[0]["findPendingAsks"];
440
465
  refreshResultDelivery?: () => void;
466
+ trackRetainedNestedRoute?: (rootRunId: string) => void;
441
467
  kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
442
468
  /** Set when this executor runs inside a child session; carries the runtime settings the host passes instead of environment variables. */
443
469
  childRuntime?: ChildRuntimeConfig;
@@ -457,7 +483,7 @@ function inheritedRunFanoutBudget(deps: Pick<ExecutorDeps, "childRuntime">): Run
457
483
 
458
484
  type ForkSessionFileForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean, modelOrigin?: ModelOrigin) => string | undefined;
459
485
  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;
486
+ type ThinkingOverrideForTask = () => AgentConfig["thinking"] | undefined;
461
487
 
462
488
  interface ExecutionContextData {
463
489
  params: SubagentParamsLike;
@@ -477,7 +503,7 @@ interface ExecutionContextData {
477
503
  sessionDirForIndex: (idx?: number) => string;
478
504
  sessionFileForIndex: (idx?: number) => string | undefined;
479
505
  sessionFileForTask: ForkSessionFileForTask;
480
- thinkingOverrideForTask: ForkThinkingOverrideForTask;
506
+ thinkingOverrideForTask: ThinkingOverrideForTask;
481
507
  artifactConfig: ArtifactConfig;
482
508
  artifactsDir: string;
483
509
  backgroundRequestedWhileClarifying: boolean;
@@ -494,6 +520,8 @@ interface ExecutionContextData {
494
520
  configToolTimeoutMs?: number;
495
521
  toolBudget?: ResolvedToolBudget;
496
522
  usageBudget?: UsageBudgetConfig;
523
+ /** Parent workflow owns this allowance; presence vetoes unverifiable child continuation. */
524
+ inheritedUsageBudget?: UsageBudgetConfig;
497
525
  allowZeroToolBudget?: boolean;
498
526
  configToolBudget?: ResolvedToolBudget;
499
527
  contextPolicy: AgentDefaultContextPolicy;
@@ -535,28 +563,39 @@ function trustedProjectCwd(ctx: ExtensionContext): string | undefined {
535
563
  }
536
564
 
537
565
  function sandboxProfileTrustError(agent: AgentConfig, ctx: ExtensionContext, childCwd: string): string | undefined {
538
- if (!agent.sandbox || (agent.source !== "project" && agent.override?.scope !== "project")) return undefined;
539
- const trustedCwd = trustedProjectCwd(ctx);
540
- if (trustedCwd && trustedCwd === path.resolve(childCwd)) return undefined;
541
- if (!trustedCwd) {
542
- return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the project is not trusted. Trust the project and retry.`;
543
- }
544
- return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' 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.`;
566
+ return projectScopedProfileTrustError({
567
+ kind: "sandbox",
568
+ agentName: agent.name,
569
+ profileName: agent.sandbox ?? "",
570
+ projectScoped: Boolean(agent.sandbox) && (agent.source === "project" || agent.override?.scope === "project"),
571
+ trustedCwd: trustedProjectCwd(ctx),
572
+ effectiveCwd: path.resolve(childCwd),
573
+ messageStyle: "executor",
574
+ });
545
575
  }
546
576
 
547
577
  function permissionProfileTrustError(agent: AgentConfig, ctx: ExtensionContext, childCwd: string): string | undefined {
548
- if (!agent.permissionProfile || (agent.source !== "project" && agent.override?.scope !== "project")) return undefined;
549
- const trustedCwd = trustedProjectCwd(ctx);
550
- if (trustedCwd && trustedCwd === path.resolve(childCwd)) return undefined;
551
- if (!trustedCwd) {
552
- return `Agent '${agent.name}' selects permission profile '${agent.permissionProfile}' from project scope, but the project is not trusted. Trust the project and retry.`;
553
- }
554
- 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.`;
578
+ return projectScopedProfileTrustError({
579
+ kind: "permission",
580
+ agentName: agent.name,
581
+ profileName: agent.permissionProfile ?? "",
582
+ projectScoped: Boolean(agent.permissionProfile) && (agent.source === "project" || agent.override?.scope === "project"),
583
+ trustedCwd: trustedProjectCwd(ctx),
584
+ effectiveCwd: path.resolve(childCwd),
585
+ messageStyle: "executor",
586
+ });
555
587
  }
556
588
 
557
- function removeForegroundControlIfIdle(state: SubagentState, runId: string): boolean {
589
+ export function removeForegroundControlIfIdle(state: SubagentState, runId: string, trackRetainedNestedRoute?: (rootRunId: string) => void): boolean {
558
590
  const control = state.foregroundControls.get(runId);
559
591
  if (control && (!foregroundSchedulingSettled(control) || (control.activeChildren?.size ?? 0) > 0)) return false;
592
+ if (control?.nestedRoute && trackRetainedNestedRoute) {
593
+ try {
594
+ if (retainLiveForegroundNestedRoute(state, control.nestedRoute)) trackRetainedNestedRoute(runId);
595
+ } catch (error) {
596
+ console.error(`Failed to retain live nested descendants for foreground run '${runId}':`, error);
597
+ }
598
+ }
560
599
  state.foregroundControls.delete(runId);
561
600
  if (state.lastForegroundControlId === runId) state.lastForegroundControlId = null;
562
601
  return true;
@@ -751,7 +790,7 @@ function foregroundChildActivityFromProgress(progress: SingleResult["progress"]
751
790
  };
752
791
  }
753
792
 
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 {
793
+ 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
794
  state.foregroundRuns ??= new Map();
756
795
  const previous = state.foregroundRuns.get(input.runId);
757
796
  const updatedAt = Date.now();
@@ -763,6 +802,7 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
763
802
  updatedAt,
764
803
  children: input.results.map((result, index) => {
765
804
  const resumeContract = omitUndefinedProperties({
805
+ modelResponseAliases: input.modelResponseAliases,
766
806
  outputSchema: input.params.outputSchema,
767
807
  agentContract: input.params.agentContract,
768
808
  acceptance: input.params.acceptance,
@@ -805,6 +845,7 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
805
845
  ...(result.permissionProfile ? { permissionProfile: result.permissionProfile } : {}),
806
846
  ...(result.launchContractDigest ? { launchContractDigest: result.launchContractDigest } : {}),
807
847
  ...(input.extensionBindings ? { extensionBindings: input.extensionBindings } : {}),
848
+ ...(input.requiredExtensions?.length ? { requiredExtensions: input.requiredExtensions } : {}),
808
849
  ...(result.launchResolvedExtensions ? { launchResolvedExtensions: result.launchResolvedExtensions } : {}),
809
850
  ...(result.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: result.runtimeAcknowledgedExtensions } : {}),
810
851
  ...(result.capabilityCeiling ? { capabilityCeiling: result.capabilityCeiling } : {}),
@@ -960,6 +1001,7 @@ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: Subage
960
1001
  ...(child.launchContractDigest ? { launchContractDigest: child.launchContractDigest } : {}),
961
1002
  ...(child.resumeContract ? { resumeContract: child.resumeContract } : {}),
962
1003
  ...(child.extensionBindings ? { extensionBindings: normalizeExtensionBindings(child.extensionBindings)!.value } : {}),
1004
+ ...(child.requiredExtensions ? { requiredExtensions: child.requiredExtensions } : {}),
963
1005
  ...(child.capabilityCeiling ? { capabilityCeiling: child.capabilityCeiling } : {}),
964
1006
  };
965
1007
  }
@@ -1252,10 +1294,14 @@ function appendStepToAsyncChain(input: {
1252
1294
  };
1253
1295
  }
1254
1296
  const chain = [input.params.step];
1255
- const acceptanceErrors = validateExecutionAcceptance({ ...input.params, chain } as Parameters<typeof validateExecutionAcceptance>[0]);
1256
- if (acceptanceErrors.length > 0) {
1297
+ const validationParams = { ...input.params, chain } as SubagentParamsLike;
1298
+ const acceptancePolicyErrors = validateExecutionAcceptancePolicy(validationParams);
1299
+ const outputSchemaError = validateLaunchOutputSchemaOverrides(validationParams);
1300
+ const earlyErrors = [...acceptancePolicyErrors];
1301
+ if (outputSchemaError) earlyErrors.push(outputSchemaError);
1302
+ if (earlyErrors.length > 0) {
1257
1303
  return {
1258
- content: [{ type: "text", text: `Cannot append step: ${acceptanceErrors.join(" ")}` }],
1304
+ content: [{ type: "text", text: `Cannot append step: ${earlyErrors.join(" ")}` }],
1259
1305
  isError: true,
1260
1306
  details: { mode: "management", results: [] },
1261
1307
  };
@@ -1337,6 +1383,14 @@ function appendStepToAsyncChain(input: {
1337
1383
  const scope: AgentScope = resolveExecutionAgentScope(input.params.agentScope);
1338
1384
  const discoveredForAppend = input.deps.discoverAgents(input.requestCwd, scope, input.parentModel?.provider);
1339
1385
  const agents = discoveredForAppend.agents;
1386
+ const acceptanceErrors = validateExecutionAcceptance(projectEffectiveAcceptanceSchemas(validationParams, agents));
1387
+ if (acceptanceErrors.length > 0) {
1388
+ return {
1389
+ content: [{ type: "text", text: `Cannot append step: ${acceptanceErrors.join(" ")}` }],
1390
+ isError: true,
1391
+ details: { mode: "management", results: [] },
1392
+ };
1393
+ }
1340
1394
  const contextPolicy = resolveExplicitContextPolicy(input.params);
1341
1395
  const chainSkillInput = normalizeSkillInput(input.params.skill);
1342
1396
  const chainSkills = chainSkillInput === false ? [] : (chainSkillInput ?? []);
@@ -1351,6 +1405,7 @@ function appendStepToAsyncChain(input: {
1351
1405
  modelScope: discoveredForAppend.modelScope,
1352
1406
  projectTrusted: currentProjectTrusted(input.ctx),
1353
1407
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
1408
+ modelResponseAliases: input.deps.config.modelResponseAliases,
1354
1409
  interactive: input.ctx.hasUI,
1355
1410
  permissions: input.deps.config.permissions,
1356
1411
  childRuntime: input.deps.childRuntime,
@@ -1719,7 +1774,7 @@ async function resumeExternalJobFollowUp(input: {
1719
1774
  ...input.baseAgentConfig,
1720
1775
  runner: { type: "external-job", provider: runner.provider, options: runner.options },
1721
1776
  };
1722
- const result = executeAsyncSingle(runId, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
1777
+ const result = await executeAsyncSingle(runId, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
1723
1778
  agent: input.target.agent,
1724
1779
  task: input.followUp,
1725
1780
  goal: input.followUp,
@@ -1733,6 +1788,7 @@ async function resumeExternalJobFollowUp(input: {
1733
1788
  currentModelProvider: parentModel?.provider,
1734
1789
  currentModel: parentModel,
1735
1790
  modelScope: input.modelScope,
1791
+ modelResponseAliases: input.deps.config.modelResponseAliases,
1736
1792
  interactive: input.ctx.hasUI,
1737
1793
  permissions: input.deps.config.permissions,
1738
1794
  childRuntime: input.deps.childRuntime,
@@ -1768,6 +1824,28 @@ async function resumeExternalJobFollowUp(input: {
1768
1824
  return externalJobFollowUpStarted({ sourceRunId: input.target.runId, runId: result.details.asyncId ?? runId, asyncDir: result.details.asyncDir ?? asyncDir, interactive: input.ctx.hasUI });
1769
1825
  }
1770
1826
 
1827
+ function resolveRequestedResumeTarget(params: SubagentParamsLike, deps: ExecutorDeps, parentSessionFile: string | null): ResumeSourceTarget | { kind: "live-nested"; target: ResolvedSubagentRunId & { kind: "nested" } } {
1828
+ const requestedId = params.id ?? params.runId;
1829
+ let resolved: ResolvedSubagentRunId | undefined;
1830
+ try {
1831
+ resolved = requestedId ? resolveSubagentRunId(requestedId, omitUndefinedProperties({ state: deps.state, nested: nestedResolutionScopeForExecutor(deps) })) : undefined;
1832
+ } catch (error) {
1833
+ const message = error instanceof Error ? error.message : "";
1834
+ const asyncMatches = message.match(/async:/g)?.length ?? 0;
1835
+ if (!isResumeAmbiguity(error) || !message.includes("foreground:") || asyncMatches !== 1) throw error;
1836
+ }
1837
+ if (resolved?.kind === "nested") {
1838
+ if (params.chain?.length) throw new Error("Attaching a running subagent as a chain root is currently available for top-level async runs only.");
1839
+ if (resolved.match.run.state === "running" || resolved.match.run.state === "queued") return { kind: "live-nested", target: resolved };
1840
+ const trustedSessionRoots = [
1841
+ ...(deps.config.defaultSessionDir ? [path.resolve(deps.expandTilde(deps.config.defaultSessionDir))] : []),
1842
+ ...(parentSessionFile ? [deps.getSubagentSessionRoot(parentSessionFile)] : []),
1843
+ ];
1844
+ return resolveNestedResumeTarget(resolved, trustedSessionRoots);
1845
+ }
1846
+ return resolveResumeTarget(params, deps.state, { asyncRequireSessionFile: false });
1847
+ }
1848
+
1771
1849
  async function resumeAsyncRun(input: {
1772
1850
  params: SubagentParamsLike;
1773
1851
  requestCwd: string;
@@ -1793,47 +1871,22 @@ async function resumeAsyncRun(input: {
1793
1871
  details: { mode: "management", results: [] },
1794
1872
  };
1795
1873
  }
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
- };
1874
+ const acceptancePolicyErrors = validateExecutionAcceptancePolicy(input.params);
1875
+ if (acceptancePolicyErrors.length > 0) {
1876
+ return { content: [{ type: "text", text: `Cannot resume: ${acceptancePolicyErrors.join(" ")}` }], isError: true, details: { mode: "management", results: [] } };
1877
+ }
1878
+ const outputSchemaError = validateLaunchOutputSchemaOverrides(input.params);
1879
+ if (outputSchemaError) {
1880
+ return { content: [{ type: "text", text: `Cannot resume: ${outputSchemaError}` }], isError: true, details: { mode: "management", results: [] } };
1803
1881
  }
1804
1882
  input.deps.state.currentSessionId = resolveCurrentSessionId(input.ctx.sessionManager);
1805
1883
 
1806
1884
  let target: ResumeSourceTarget;
1807
1885
  const parentSessionFile = input.ctx.sessionManager.getSessionFile() ?? null;
1808
1886
  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
- }
1887
+ const resolved = resolveRequestedResumeTarget(input.params, input.deps, parentSessionFile);
1888
+ if (resolved.kind === "live-nested") return resumeLiveNestedRun({ target: resolved.target, message: followUp });
1889
+ target = resolved;
1837
1890
  } catch (error) {
1838
1891
  const message = error instanceof Error ? error.message : String(error);
1839
1892
  return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
@@ -1941,6 +1994,10 @@ async function resumeAsyncRun(input: {
1941
1994
  details: { mode: "chain", results: [] },
1942
1995
  };
1943
1996
  }
1997
+ const acceptanceErrors = validateExecutionAcceptance(projectEffectiveAcceptanceSchemas(input.params, agents));
1998
+ if (acceptanceErrors.length > 0) {
1999
+ return { content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }], isError: true, details: { mode: "chain", results: [] } };
2000
+ }
1944
2001
  const runId = randomUUID();
1945
2002
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
1946
2003
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
@@ -1988,8 +2045,9 @@ async function resumeAsyncRun(input: {
1988
2045
  modelScope,
1989
2046
  projectTrusted: currentProjectTrusted(input.ctx),
1990
2047
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
1991
- interactive: input.ctx.hasUI,
1992
- permissions: input.deps.config.permissions,
2048
+ modelResponseAliases: input.deps.config.modelResponseAliases,
2049
+ interactive: input.ctx.hasUI,
2050
+ permissions: input.deps.config.permissions,
1993
2051
  childRuntime: input.deps.childRuntime,
1994
2052
  }),
1995
2053
  availableModels,
@@ -2010,6 +2068,7 @@ async function resumeAsyncRun(input: {
2010
2068
  worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
2011
2069
  worktreeBaseDir: input.deps.config.worktreeBaseDir,
2012
2070
  baseRef: input.params.baseRef ?? target.recoveryDescriptor?.baseRef,
2071
+ ...(recoveryDescriptor?.requiredExtensions ? { requiredExtensions: recoveryDescriptor.requiredExtensions } : {}),
2013
2072
  worktreeProvider: input.deps.config.worktreeProvider,
2014
2073
  worktreeBranchPrefix: input.deps.config.worktreeBranchPrefix,
2015
2074
  controlConfig: resolveControlConfig(input.deps.config.control, input.params.control),
@@ -2049,6 +2108,23 @@ async function resumeAsyncRun(input: {
2049
2108
  if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
2050
2109
  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
2110
  }
2111
+ const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
2112
+ const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
2113
+ const foregroundContract = target.source === "foreground" ? target.resumeContract : undefined;
2114
+ const outputSchema = Object.hasOwn(input.params, "outputSchema")
2115
+ ? input.params.outputSchema
2116
+ : Object.hasOwn(foregroundContract ?? {}, "outputSchema")
2117
+ ? foregroundContract?.outputSchema
2118
+ : recoveryDescriptor?.structuredOutputSchema;
2119
+ const acceptance = input.params.acceptance !== undefined
2120
+ ? input.params.acceptance
2121
+ : foregroundContract?.acceptance !== undefined
2122
+ ? foregroundContract.acceptance
2123
+ : recoveryDescriptor?.acceptance;
2124
+ const acceptanceErrors = validateExecutionAcceptance({ ...input.params, acceptance, outputSchema });
2125
+ if (acceptanceErrors.length > 0) {
2126
+ return { content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }], isError: true, details: { mode: "management", results: [] } };
2127
+ }
2052
2128
  const runId = randomUUID();
2053
2129
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
2054
2130
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
@@ -2072,17 +2148,13 @@ async function resumeAsyncRun(input: {
2072
2148
  if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "single", results: [], activeAsyncCapacity: error.snapshot } };
2073
2149
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "single", results: [] } };
2074
2150
  }
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
2151
  const agentContract = input.params.agentContract ?? foregroundContract?.agentContract ?? recoveryDescriptor?.agentContract;
2080
2152
  const artifactConfig: ArtifactConfig = recoveryDescriptor?.artifactConfig ?? omitUndefinedProperties({ ...DEFAULT_ARTIFACT_CONFIG, enabled: input.params.artifacts !== false, dir: input.deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir });
2081
2153
  const artifactsDir = recoveryDescriptor?.artifactsDir ?? getArtifactsDir(parentSessionFile, effectiveCwd, artifactConfig.dir);
2082
2154
  const availableModels = input.ctx.modelRegistry.getAvailable().map(toModelInfo);
2083
2155
  const parentModel = input.parentModel;
2084
2156
  const revivalAsyncDir = path.join(DIRS.async, runId);
2085
- const result = executeAsyncSingle(runId, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
2157
+ const result = await executeAsyncSingle(runId, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
2086
2158
  agent: target.agent,
2087
2159
  task: buildRevivedAsyncTask(target as Parameters<typeof buildRevivedAsyncTask>[0], effectiveFollowUp),
2088
2160
  goal: effectiveFollowUp,
@@ -2099,6 +2171,8 @@ async function resumeAsyncRun(input: {
2099
2171
  modelScope,
2100
2172
  projectTrusted: currentProjectTrusted(input.ctx),
2101
2173
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2174
+ // Absence in the retained contract is meaningful; never acquire current aliases.
2175
+ modelResponseAliases: recoveryDescriptor ? recoveryDescriptor.modelResponseAliases : foregroundContract?.modelResponseAliases,
2102
2176
  interactive: input.ctx.hasUI,
2103
2177
  permissions: input.deps.config.permissions,
2104
2178
  childRuntime: input.deps.childRuntime,
@@ -2125,6 +2199,7 @@ async function resumeAsyncRun(input: {
2125
2199
  thinkingOverride: recoveryDescriptor?.thinking ?? target.thinking,
2126
2200
  thinkingCeiling: recoveryDescriptor?.thinkingCeiling ?? ("thinkingCeiling" in target ? target.thinkingCeiling : undefined),
2127
2201
  extensionBindings: recoveryDescriptor?.extensionBindings ?? ("extensionBindings" in target ? target.extensionBindings : undefined),
2202
+ requiredExtensions: recoveryDescriptor?.requiredExtensions ?? (target as { requiredExtensions?: SteeringRecoveryDescriptor["requiredExtensions"] }).requiredExtensions,
2128
2203
  outputBaseDir: resolveSingleRunOutputBaseDir(input.deps, artifactsDir, runId),
2129
2204
  maxSubagentDepth: recoveryDescriptor?.maxSubagentDepth ?? resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime),
2130
2205
  waitToolEnabled: input.deps.waitToolEnabled,
@@ -2146,10 +2221,11 @@ async function resumeAsyncRun(input: {
2146
2221
  availableModels,
2147
2222
  output: input.params.output !== undefined ? input.params.output : foregroundContract?.output ?? recoveryDescriptor?.outputPath,
2148
2223
  outputMode: input.params.outputMode ?? foregroundContract?.outputMode ?? recoveryDescriptor?.outputMode,
2224
+ outputClaimPath: input.params.workflowOutputClaimPath,
2149
2225
  ...(agentContract ? { agentContract } : {}),
2150
2226
  ...(outputSchema ? { structuredOutputSchema: outputSchema } : {}),
2151
2227
  ...(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 } : {}),
2228
+ ...(acceptance !== undefined ? { acceptance } : {}),
2153
2229
  ...(input.params.timeoutMs !== undefined ? { timeoutMs: input.params.timeoutMs } : {}),
2154
2230
  ...(input.absoluteDeadlineAt !== undefined ? { absoluteDeadlineAt: input.absoluteDeadlineAt } : {}),
2155
2231
  ...(input.params.toolBudget !== undefined ? { toolBudget: input.params.toolBudget } : {}),
@@ -2198,7 +2274,7 @@ async function resumeAsyncRun(input: {
2198
2274
  } finally {
2199
2275
  input.signal?.removeEventListener("abort", stopOnAbort);
2200
2276
  }
2201
- fs.rmSync(resultPath, { force: true });
2277
+ if (completed.importedPublication) removeWorkflowAwaitedResult(asyncDir, resultPath, revivedId, completed.importedPublication);
2202
2278
  const usage = importedAsyncRootUsage(completed);
2203
2279
  const childResult: SingleResult = {
2204
2280
  index: 0,
@@ -2214,14 +2290,14 @@ async function resumeAsyncRun(input: {
2214
2290
  ...(completed.stopped ? { stopped: true } : {}),
2215
2291
  ...(completed.sessionFile ? { sessionFile: completed.sessionFile } : {}),
2216
2292
  ...(completed.model ? { model: completed.model } : {}),
2217
- ...(completed.attemptedModels ? { attemptedModels: completed.attemptedModels } : {}),
2218
- ...(completed.modelAttempts ? { modelAttempts: completed.modelAttempts } : {}),
2293
+ ...(completed.requestedModel ? { requestedModel: completed.requestedModel } : {}),
2219
2294
  ...(completed.contextOverflow ? { contextOverflow: true } : {}),
2220
2295
  ...(completed.structuredOutput !== undefined ? { structuredOutput: completed.structuredOutput } : {}),
2221
2296
  ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
2222
2297
  ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
2223
2298
  ...(completed.acceptance ? { acceptance: completed.acceptance } : {}),
2224
2299
  ...(completed.artifactPaths ? { artifactPaths: completed.artifactPaths } : {}),
2300
+ ...(completed.savedOutputPath ? { savedOutputPath: completed.savedOutputPath } : {}),
2225
2301
  ...(completed.outputSaveError ? { outputSaveError: completed.outputSaveError } : {}),
2226
2302
  ...(completed.transcriptPath ? { transcriptPath: completed.transcriptPath } : {}),
2227
2303
  ...(completed.transcriptError ? { transcriptError: completed.transcriptError } : {}),
@@ -2423,6 +2499,8 @@ function canonicalizeExecutionParams(params: SubagentParamsLike, agents: AgentCo
2423
2499
  params = omitUndefinedProperties({ ...params, agent: result.name });
2424
2500
  const agent = agents.find((candidate) => candidate.name === result.name);
2425
2501
  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}'.` };
2502
+ 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;
2503
+ if (machineError) return { error: machineError };
2426
2504
  }
2427
2505
  if (params.extensionBindings !== undefined) {
2428
2506
  try {
@@ -2475,6 +2553,18 @@ function canonicalizeExecutionParams(params: SubagentParamsLike, agents: AgentCo
2475
2553
  return { params };
2476
2554
  }
2477
2555
 
2556
+ function projectEffectiveAcceptanceSchemas(params: SubagentParamsLike, agents: AgentConfig[]): SubagentParamsLike {
2557
+ const withEffectiveSchema = <T extends { agent: string; outputSchema?: JsonSchemaObject | false }>(step: T): T => {
2558
+ const agent = agents.find((candidate) => candidate.name === step.agent);
2559
+ return agent ? { ...step, outputSchema: resolveEffectiveOutputSchema(agent, step.outputSchema) } : step;
2560
+ };
2561
+ return {
2562
+ ...params,
2563
+ ...(params.tasks ? { tasks: params.tasks.map(withEffectiveSchema) } : {}),
2564
+ ...(params.chain ? { chain: projectChainOutputSchemas(params.chain, agents) as ChainStep[] } : {}),
2565
+ };
2566
+ }
2567
+
2478
2568
  function validateExecutionInput(
2479
2569
  params: SubagentParamsLike,
2480
2570
  agents: AgentConfig[],
@@ -2497,7 +2587,7 @@ function validateExecutionInput(
2497
2587
  };
2498
2588
  }
2499
2589
 
2500
- const acceptanceErrors = validateExecutionAcceptance(params as Parameters<typeof validateExecutionAcceptance>[0]);
2590
+ const acceptanceErrors = validateExecutionAcceptance(projectEffectiveAcceptanceSchemas(params, agents));
2501
2591
  if (acceptanceErrors.length > 0) {
2502
2592
  return {
2503
2593
  content: [{ type: "text", text: acceptanceErrors.join(" ") }],
@@ -2749,6 +2839,7 @@ function applySingleAgentLaunchDefaults(params: SubagentParamsLike, agents: Agen
2749
2839
  const parentTimeoutMs = params.timeoutMs === undefined && params.maxRuntimeMs === undefined && agent.defaultTimeoutMs === undefined && params.workflowParentDeadlineAt !== undefined
2750
2840
  ? Math.max(1, params.workflowParentDeadlineAt - Date.now())
2751
2841
  : undefined;
2842
+ const outputSchema = params.outputSchema === false ? false : resolveEffectiveOutputSchema(agent, params.outputSchema);
2752
2843
  return {
2753
2844
  ...params,
2754
2845
  ...(params.async === undefined && agent.defaultAsync !== undefined ? { async: agent.defaultAsync } : {}),
@@ -2759,9 +2850,28 @@ function applySingleAgentLaunchDefaults(params: SubagentParamsLike, agents: Agen
2759
2850
  ...(params.acceptance === undefined && agent.defaultAcceptance !== undefined
2760
2851
  ? { acceptance: agent.defaultAcceptance }
2761
2852
  : {}),
2853
+ ...(outputSchema !== undefined ? { outputSchema } : {}),
2762
2854
  };
2763
2855
  }
2764
2856
 
2857
+ function validateLaunchOutputSchemaOverrides(params: SubagentParamsLike): string | undefined {
2858
+ const values: unknown[] = [params.outputSchema, ...(params.tasks ?? []).map((task) => task.outputSchema)];
2859
+ for (const step of params.chain ?? []) {
2860
+ if (isParallelStep(step)) values.push(...step.parallel.map((task) => task.outputSchema));
2861
+ else if (isDynamicParallelStep(step)) values.push(step.parallel.outputSchema);
2862
+ else values.push(step.outputSchema);
2863
+ }
2864
+ for (const value of values) {
2865
+ if (value === undefined || value === false) continue;
2866
+ try {
2867
+ assertJsonSchemaObject(value, "outputSchema");
2868
+ } catch (error) {
2869
+ return error instanceof Error ? error.message : String(error);
2870
+ }
2871
+ }
2872
+ return undefined;
2873
+ }
2874
+
2765
2875
  export const DEFAULT_FOREGROUND_TIMEOUT_MS = 30 * 60 * 1000;
2766
2876
 
2767
2877
  // Async single-agent runs also need a wall-clock backstop: a child whose bash
@@ -2925,24 +3035,20 @@ function withResolvedContext(
2925
3035
  }
2926
3036
 
2927
3037
  function withAggregatedToolUsage(result: AgentToolResult<Details>): AgentToolResult<Details> {
2928
- if (result.details.results.length === 0) return result;
2929
- const usage = sumResultsUsage(result.details.results);
3038
+ const highWarnings = result.details.results.flatMap((child) => child.watchdog?.warnings?.filter((warning) => warning.importance === "high") ?? []);
3039
+ const projected: AgentToolResult<Details> = {
3040
+ ...result,
3041
+ ...(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") }] } : {}),
3042
+ details: {
3043
+ ...result.details,
3044
+ results: result.details.results.map((child) => ({ ...child, ...(child.watchdog ? { watchdog: childWatchdogProgressForModel(child.watchdog) } : {}) })),
3045
+ },
3046
+ };
3047
+ if (projected.details.results.length === 0) return projected;
3048
+ const usage = sumResultsUsage(projected.details.results);
2930
3049
  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 }] };
3050
+ ? { ...projected, usage: toAgentToolUsage(usage) }
3051
+ : projected;
2946
3052
  }
2947
3053
 
2948
3054
  function toExecutionErrorResult(params: SubagentParamsLike, error: unknown, contextSummary?: ContextSummary): AgentToolResult<Details> {
@@ -2968,7 +3074,7 @@ function resolveStaticLaunchSummary(input: {
2968
3074
  availableModels: ModelInfo[];
2969
3075
  currentProvider?: string;
2970
3076
  modelScope?: ModelScopeConfig;
2971
- thinkingOverrideForTask: ForkThinkingOverrideForTask;
3077
+ thinkingOverrideForTask: ThinkingOverrideForTask;
2972
3078
  }): StaticLaunchSummary {
2973
3079
  const agentConfig = input.agents.find((agent) => agent.name === input.agent);
2974
3080
  const externalRunner = agentConfig?.runner?.type === "external-cli" || agentConfig?.runner?.type === "external-job";
@@ -2983,7 +3089,7 @@ function resolveStaticLaunchSummary(input: {
2983
3089
  agentConfig?.modelProvider ?? input.currentProvider,
2984
3090
  modelScopes.length === 0 ? {} : { scope: modelScopes },
2985
3091
  );
2986
- const thinkingOverride = externalRunner ? undefined : input.thinkingOverrideForTask(input.agent, input.index, model);
3092
+ const thinkingOverride = externalRunner ? undefined : input.thinkingOverrideForTask();
2987
3093
  const thinking = externalRunner ? undefined : resolveEffectiveThinking(model, thinkingOverride ?? agentConfig?.thinking);
2988
3094
  return {
2989
3095
  agent: input.agent,
@@ -3000,7 +3106,7 @@ function collectStaticLaunchSummaries(input: {
3000
3106
  availableModels: ModelInfo[];
3001
3107
  currentProvider?: string;
3002
3108
  modelScope?: ModelScopeConfig;
3003
- thinkingOverrideForTask: ForkThinkingOverrideForTask;
3109
+ thinkingOverrideForTask: ThinkingOverrideForTask;
3004
3110
  dynamicFanoutMaxItems?: number;
3005
3111
  }): StaticLaunchSummary[] {
3006
3112
  const summary = (agent: string, index: number, explicitModel?: string) => resolveStaticLaunchSummary({
@@ -3154,6 +3260,15 @@ function importedAsyncRootUsage(completed: Awaited<ReturnType<typeof waitForImpo
3154
3260
  };
3155
3261
  }
3156
3262
 
3263
+ function removeWorkflowAwaitedResult(asyncDir: string, resultPath: string, runId: string, publication: NonNullable<Awaited<ReturnType<typeof waitForImportedAsyncRoot>>["importedPublication"]>): void {
3264
+ try {
3265
+ fs.rmSync(resultPath, { force: true });
3266
+ } catch {
3267
+ // Payload cleanup must not replace an already imported delivery.
3268
+ }
3269
+ removeResultIndex(asyncDir, publication.sessionId, runId, publication.toolCallId);
3270
+ }
3271
+
3157
3272
  async function waitForWorkflowAsyncSingleResult(
3158
3273
  params: SubagentParamsLike,
3159
3274
  launchResult: AgentToolResult<Details>,
@@ -3174,7 +3289,7 @@ async function waitForWorkflowAsyncSingleResult(
3174
3289
  } finally {
3175
3290
  options.signal?.removeEventListener("abort", stopOnAbort);
3176
3291
  }
3177
- fs.rmSync(resultPath, { force: true });
3292
+ if (completed.importedPublication) removeWorkflowAwaitedResult(asyncDir, resultPath, options.runId, completed.importedPublication);
3178
3293
  const usage = importedAsyncRootUsage(completed);
3179
3294
  const childResult: SingleResult = omitUndefinedProperties({
3180
3295
  index: 0,
@@ -3190,14 +3305,14 @@ async function waitForWorkflowAsyncSingleResult(
3190
3305
  ...(completed.stopped ? { stopped: true } : {}),
3191
3306
  ...(completed.sessionFile ? { sessionFile: completed.sessionFile } : {}),
3192
3307
  ...(completed.model ? { model: completed.model } : {}),
3193
- ...(completed.attemptedModels ? { attemptedModels: completed.attemptedModels } : {}),
3194
- ...(completed.modelAttempts ? { modelAttempts: completed.modelAttempts } : {}),
3308
+ ...(completed.requestedModel ? { requestedModel: completed.requestedModel } : {}),
3195
3309
  ...(completed.contextOverflow ? { contextOverflow: true } : {}),
3196
3310
  ...(completed.structuredOutput !== undefined ? { structuredOutput: completed.structuredOutput } : {}),
3197
3311
  ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
3198
3312
  ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
3199
3313
  ...(completed.acceptance ? { acceptance: completed.acceptance } : {}),
3200
3314
  ...(completed.artifactPaths ? { artifactPaths: completed.artifactPaths } : {}),
3315
+ ...(completed.savedOutputPath ? { savedOutputPath: completed.savedOutputPath } : {}),
3201
3316
  ...(completed.outputSaveError ? { outputSaveError: completed.outputSaveError } : {}),
3202
3317
  ...(completed.transcriptPath ? { transcriptPath: completed.transcriptPath } : {}),
3203
3318
  ...(completed.transcriptError ? { transcriptError: completed.transcriptError } : {}),
@@ -3257,7 +3372,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3257
3372
  modelScope: data.modelScope,
3258
3373
  projectTrusted: currentProjectTrusted(ctx),
3259
3374
  ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3260
- interactive: ctx.hasUI,
3375
+ modelResponseAliases: deps.config.modelResponseAliases, interactive: ctx.hasUI,
3261
3376
  permissions: deps.config.permissions,
3262
3377
  childRuntime: deps.childRuntime,
3263
3378
  });
@@ -3317,7 +3432,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3317
3432
  const modelOverrideFromParent = modelOrigin === "inherited";
3318
3433
  const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: a.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
3319
3434
  if (launchRuleError) return toExecutionErrorResult(params, new Error(launchRuleError), data.contextPolicy.contextSummary);
3320
- const asyncResult = executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
3435
+ const asyncResult = await executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
3321
3436
  agent: params.agent!,
3322
3437
  task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(params.task ?? "") : (params.task ?? ""),
3323
3438
  goal: params.task ?? "",
@@ -3327,6 +3442,8 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3327
3442
  availableModels,
3328
3443
  cwd: effectiveCwd,
3329
3444
  requestedCwd: data.requestedCwd,
3445
+ machine: params.machine,
3446
+ machineCwd: params.machineCwd,
3330
3447
  maxOutput: params.maxOutput,
3331
3448
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3332
3449
  artifactConfig,
@@ -3345,7 +3462,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3345
3462
  fast: params.fast,
3346
3463
  modelOverrideFromParent,
3347
3464
  modelOrigin,
3348
- thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
3465
+ thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(),
3349
3466
  thinkingCeiling: a.maxThinking,
3350
3467
  maxSubagentDepth,
3351
3468
  waitToolEnabled: deps.waitToolEnabled,
@@ -3363,7 +3480,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3363
3480
  childIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(agent, index) : undefined,
3364
3481
  nestedRoute,
3365
3482
  agentContract: params.agentContract,
3366
- structuredOutputSchema: params.outputSchema,
3483
+ structuredOutputSchema: params.outputSchema || undefined,
3367
3484
  extensionBindings: params.extensionBindings,
3368
3485
  acceptance: params.acceptance,
3369
3486
  timeoutMs: data.timeoutMs,
@@ -3371,6 +3488,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3371
3488
  usageBudget: data.usageBudget,
3372
3489
  configToolBudget: data.configToolBudget,
3373
3490
  toolTimeoutMs: data.params?.toolTimeoutMs,
3491
+ checkpointBeforeDeadlineMs: data.params?.checkpointBeforeDeadlineMs ?? deps.config.checkpointBeforeDeadlineMs,
3374
3492
  configToolTimeoutMs: data.configToolTimeoutMs,
3375
3493
  capabilityCeiling: data.capabilityCeiling,
3376
3494
  runFanoutBudget: data.runFanoutBudget,
@@ -3385,8 +3503,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3385
3503
  return null;
3386
3504
  }
3387
3505
 
3388
- function createSingleWorktreeSetup(
3389
- enabled: boolean | undefined,
3506
+ async function createSingleWorktreeSetup(
3390
3507
  cwd: string,
3391
3508
  runId: string,
3392
3509
  agent: string,
@@ -3398,12 +3515,13 @@ function createSingleWorktreeSetup(
3398
3515
  branchPrefix: ExtensionConfig["worktreeBranchPrefix"],
3399
3516
  label?: string,
3400
3517
  task?: string,
3401
- beforeCreate?: (setup: WorktreeSetup) => void,
3402
- ): { setup?: WorktreeSetup; errorResult?: AgentToolResult<Details> } {
3403
- if (!enabled) return {};
3518
+ onProgress?: (snapshot: WorktreeSetupProgress) => void,
3519
+ signal?: AbortSignal,
3520
+ deadlineAt?: number,
3521
+ ): Promise<{ setup?: WorktreeSetup; errorResult?: AgentToolResult<Details> }> {
3404
3522
  try {
3405
3523
  return {
3406
- setup: createWorktrees(cwd, runId, 1, omitUndefinedProperties({
3524
+ setup: await createWorktrees(cwd, runId, 1, omitUndefinedProperties({
3407
3525
  agents: [agent],
3408
3526
  setupHook: setupHook
3409
3527
  ? { hookPath: setupHook, ...(setupHookTimeoutMs === undefined ? {} : { timeoutMs: setupHookTimeoutMs }) }
@@ -3414,7 +3532,9 @@ function createSingleWorktreeSetup(
3414
3532
  branchPrefix,
3415
3533
  labels: [label],
3416
3534
  tasks: [task],
3417
- beforeCreate,
3535
+ onProgress,
3536
+ signal,
3537
+ deadlineAt,
3418
3538
  })),
3419
3539
  };
3420
3540
  } catch (error) {
@@ -3440,15 +3560,6 @@ function resolveSingleRunOutputBaseDir(deps: ExecutorDeps, artifactsDir: string,
3440
3560
  return resolveConfiguredSingleRunOutputBaseDir(deps) ?? path.join(artifactsDir, "outputs", sanitizeRunPathSegment(runId));
3441
3561
  }
3442
3562
 
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
3563
  function workflowChildDefaultOutput(aggregateOutputPath: string | undefined, artifactsDir: string, workflowRunId: string, workflowKey: string): string {
3453
3564
  if (aggregateOutputPath) {
3454
3565
  const parsed = path.parse(aggregateOutputPath);
@@ -3496,6 +3607,23 @@ function appendWorkflowOutputWarning(text: string, warning: string | undefined):
3496
3607
  return warning ? `${text}\n\n${warning}` : text;
3497
3608
  }
3498
3609
 
3610
+ export function resolveWorkflowChildLocalCwd(input: {
3611
+ workflowCwd: string;
3612
+ discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3613
+ agents: AgentConfig[];
3614
+ workflowAgentScope?: unknown;
3615
+ params: Record<string, unknown>;
3616
+ }): string {
3617
+ if (input.params.machine !== undefined) return input.workflowCwd;
3618
+ if (typeof input.params.agent === "string") {
3619
+ const agentScope = resolveExecutionAgentScope(input.params.agentScope ?? input.workflowAgentScope);
3620
+ const workflowAgents = input.discoverAgents(input.workflowCwd, agentScope).agents;
3621
+ const agent = resolveAgentName(input.params.agent, workflowAgents).agent ?? resolveAgentName(input.params.agent, input.agents).agent;
3622
+ if (agent?.machine !== undefined) return input.workflowCwd;
3623
+ }
3624
+ return typeof input.params.cwd === "string" ? resolveChildCwd(input.workflowCwd, input.params.cwd) : input.workflowCwd;
3625
+ }
3626
+
3499
3627
  function resolveWorkflowChildOutputPath(input: {
3500
3628
  ctxCwd: string;
3501
3629
  workflowCwd: string;
@@ -3510,7 +3638,9 @@ function resolveWorkflowChildOutputPath(input: {
3510
3638
  key: string;
3511
3639
  params: Record<string, unknown>;
3512
3640
  }): { path?: string; inherited: boolean } {
3513
- if (typeof input.params.resume === "string") {
3641
+ const rawOutput = input.params.output;
3642
+ const hasExplicitOutput = typeof rawOutput === "string" || typeof rawOutput === "boolean";
3643
+ if (typeof input.params.resume === "string" && (!hasExplicitOutput || rawOutput === true || rawOutput === "true")) {
3514
3644
  if (!input.state) return { path: undefined, inherited: false };
3515
3645
  const index = input.params.index;
3516
3646
  const target = resolveResumeTarget({
@@ -3519,15 +3649,16 @@ function resolveWorkflowChildOutputPath(input: {
3519
3649
  }, input.state);
3520
3650
  return { path: "recoveryDescriptor" in target ? target.recoveryDescriptor?.outputPath : undefined, inherited: false };
3521
3651
  }
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;
3652
+ const childCwd = resolveWorkflowChildLocalCwd(input);
3653
+ let agentOutput: string | undefined;
3654
+ if (rawOutput === true || rawOutput === "true" || (!hasExplicitOutput && !input.aggregateOutputPath)) {
3655
+ const agentScope = resolveExecutionAgentScope(input.params.agentScope ?? input.workflowAgentScope);
3656
+ const discoveredAgents = input.discoverAgents(childCwd, agentScope).agents;
3657
+ const agent = typeof input.params.agent === "string"
3658
+ ? resolveAgentName(input.params.agent, discoveredAgents).agent ?? resolveAgentName(input.params.agent, input.agents).agent
3659
+ : undefined;
3660
+ agentOutput = typeof agent?.output === "string" ? agent.output : undefined;
3661
+ }
3531
3662
  const output = rawOutput === true || rawOutput === "true"
3532
3663
  ? agentOutput
3533
3664
  : hasExplicitOutput
@@ -3616,11 +3747,11 @@ function prepareWorkflowChildLaunchParams(input: {
3616
3747
  childParams = { ...input.childParams, output: input.outputOverride };
3617
3748
  } else if (usesDefaultOutput && input.aggregateOutputPath !== undefined) {
3618
3749
  childParams = { ...input.childParams, output: workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.parentWorkflowRunId, input.workflowKey) };
3619
- } else if (input.childParams.resume === undefined) {
3750
+ } else if (input.childParams.resume === undefined || input.childParams.output !== undefined) {
3620
3751
  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
3752
  if (resolvedOutput.path) childParams = { ...input.childParams, output: resolvedOutput.path };
3622
3753
  }
3623
- const childCwd = typeof childParams.cwd === "string" ? resolveChildCwd(input.workflowCwd, childParams.cwd) : input.workflowCwd;
3754
+ const childCwd = resolveWorkflowChildLocalCwd({ ...input, params: childParams });
3624
3755
  const agentScope = resolveExecutionAgentScope(childParams.agentScope ?? input.workflowAgentScope);
3625
3756
  const discoveredAgents = input.discoverAgents(childCwd, agentScope).agents;
3626
3757
  const agent = typeof childParams.agent === "string"
@@ -3630,7 +3761,7 @@ function prepareWorkflowChildLaunchParams(input: {
3630
3761
  return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, { ...input.options, externalAsyncRequired, outputClaimPath: input.outputClaimPath });
3631
3762
  }
3632
3763
 
3633
- function finalizeSingleWorktreeHandoff(input: {
3764
+ async function finalizeSingleWorktreeHandoff(input: {
3634
3765
  worktreeSetup: WorktreeSetup;
3635
3766
  artifactsDir: string;
3636
3767
  runId: string;
@@ -3639,55 +3770,78 @@ function finalizeSingleWorktreeHandoff(input: {
3639
3770
  result: SingleResult;
3640
3771
  workflowKey?: string;
3641
3772
  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
- };
3773
+ }): Promise<{ suffix: string; reference?: NonNullable<Details["parallelHandoff"]> }> {
3774
+ let admitted = false;
3680
3775
  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
- };
3776
+ return await withWorktreeTransaction(() => {
3777
+ admitted = true;
3778
+ const diffsDir = path.join(input.artifactsDir, "worktree-diffs", input.runId);
3779
+ const diffs = diffWorktrees(input.worktreeSetup, [input.agent], diffsDir);
3780
+ const diffSummary = formatWorktreeDiffSummary(diffs);
3781
+ const manifestPath = parallelHandoffPath(input.artifactsDir, input.runId);
3782
+ const handoff = {
3783
+ manifestPath,
3784
+ runId: input.runId,
3785
+ mode: "single" as const,
3786
+ source: "foreground" as const,
3787
+ cwd: input.cwd,
3788
+ stepIndex: 0,
3789
+ flatStartIndex: 0,
3790
+ setup: input.worktreeSetup,
3791
+ 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,
3792
+ diffs,
3793
+ results: [{
3794
+ agent: input.result.agent,
3795
+ ...(input.workflowKey ? { workflowKey: input.workflowKey } : {}),
3796
+ ...(input.workflowKey ? { runId: input.runId } : {}),
3797
+ ...(input.lane ? { lane: input.lane } : {}),
3798
+ status: resolveSubagentResultStatus(omitUndefinedProperties({
3799
+ exitCode: input.result.exitCode,
3800
+ interrupted: input.result.interrupted,
3801
+ detached: input.result.detached,
3802
+ state: input.result.stopped ? "stopped" : undefined,
3803
+ processSignal: input.result.processSignal,
3804
+ timedOut: input.result.timedOut,
3805
+ stopped: input.result.stopped,
3806
+ turnBudgetExceeded: input.result.turnBudgetExceeded,
3807
+ })),
3808
+ summary: resultSummaryForIntercom(input.result),
3809
+ ...(input.result.artifactPaths?.outputPath ? { outputPath: input.result.artifactPaths.outputPath } : {}),
3810
+ ...(input.result.structuredOutput !== undefined ? { structuredOutput: input.result.structuredOutput } : {}),
3811
+ ...(input.result.structuredOutputPath ? { structuredOutputPath: input.result.structuredOutputPath } : {}),
3812
+ ...(input.result.sessionFile ? { sessionPath: input.result.sessionFile } : {}),
3813
+ }],
3814
+ };
3815
+ try {
3816
+ writeParallelHandoffGroup(handoff);
3817
+ const cleanup = cleanupWorktrees(input.worktreeSetup, { kind: "preserve", capturedDiffs: diffs, handoffManifestPath: manifestPath });
3818
+ const reference = writeParallelHandoffGroup({ ...handoff, cleanup });
3819
+ return {
3820
+ suffix: [diffSummary, formatParallelHandoffReference(reference)].filter(Boolean).join("\n\n"),
3821
+ reference,
3822
+ };
3823
+ } catch (error) {
3824
+ return { suffix: [diffSummary, formatParallelHandoffError(error)].filter(Boolean).join("\n\n") };
3825
+ }
3826
+ });
3688
3827
  } catch (error) {
3689
- return { suffix: [diffSummary, formatParallelHandoffError(error)].filter(Boolean).join("\n\n") };
3690
- }
3828
+ if (admitted) throw error;
3829
+ const reference = retainSingleWorktreeHandoff(input, error);
3830
+ return { suffix: `${formatParallelHandoffError(error)}\n\n${formatParallelHandoffReference(reference)}`, reference };
3831
+ }
3832
+ }
3833
+
3834
+ function retainSingleWorktreeHandoff(input: { worktreeSetup: WorktreeSetup; artifactsDir: string; runId: string; cwd: string }, error: unknown): NonNullable<Details["parallelHandoff"]> {
3835
+ const reason = `Worktree finalization retained; manual reconciliation required: ${error instanceof Error ? error.message : String(error)}`;
3836
+ return writeParallelHandoffGroup({
3837
+ manifestPath: parallelHandoffPath(input.artifactsDir, input.runId), runId: input.runId,
3838
+ mode: "single", source: "foreground", cwd: input.cwd, stepIndex: 0, flatStartIndex: 0,
3839
+ setup: input.worktreeSetup, diffs: [], results: [],
3840
+ cleanup: { state: "partial", pruned: false, errors: [reason], tasks: input.worktreeSetup.worktrees.map((worktree) => ({
3841
+ index: worktree.index, path: worktree.path, branch: worktree.branch, provider: worktree.provider, naming: worktree.naming,
3842
+ worktreeRemoved: false, branchRemoved: false, preserved: true, reason,
3843
+ })) },
3844
+ });
3691
3845
  }
3692
3846
 
3693
3847
  async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Promise<AgentToolResult<Details>> {
@@ -3729,6 +3883,12 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3729
3883
  details: { mode: "single", results: [] },
3730
3884
  };
3731
3885
  }
3886
+ let foregroundMachine: import("../../shared/types.ts").HerdrMachineReference | undefined;
3887
+ const requestedMachine = params.machine ?? agentConfig.machine;
3888
+ if (requestedMachine) {
3889
+ try { foregroundMachine = resolveHerdrMachinePlacement({ machine: requestedMachine, cwd: ctx.cwd, stepCwd: params.machineCwd }).machine; }
3890
+ catch (error) { return toExecutionErrorResult(params, error instanceof Error ? error : new Error(String(error)), data.contextPolicy.contextSummary); }
3891
+ }
3732
3892
  const effectiveToolBudget = resolveEffectiveToolBudget(omitUndefinedProperties({ runBudget: data.toolBudget, agentBudget: agentConfig.toolBudget, configBudget: data.configToolBudget }));
3733
3893
  if (effectiveToolBudget.error) return toExecutionErrorResult(params, new Error(effectiveToolBudget.error), data.contextPolicy.contextSummary);
3734
3894
 
@@ -3766,10 +3926,9 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3766
3926
  const maxSubagentDepth = resolveChildMaxSubagentDepth(currentMaxSubagentDepth, agentConfig.maxSubagentDepth);
3767
3927
 
3768
3928
 
3769
- const sourceCwd = effectiveCwd;
3929
+ const sourceCwd = foregroundMachine?.cwd ?? effectiveCwd;
3770
3930
  let pendingHandoff: Details["parallelHandoff"];
3771
- const { setup: worktreeSetup, errorResult: worktreeSetupError } = createSingleWorktreeSetup(
3772
- params.worktree,
3931
+ const { setup: worktreeSetup, errorResult: worktreeSetupError } = params.worktree ? await createSingleWorktreeSetup(
3773
3932
  sourceCwd,
3774
3933
  runId,
3775
3934
  params.agent!,
@@ -3781,8 +3940,8 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3781
3940
  deps.config.worktreeBranchPrefix,
3782
3941
  params.lane?.key ?? params.workflowKey,
3783
3942
  task,
3784
- (plannedSetup) => {
3785
- pendingHandoff = writePendingParallelHandoff({
3943
+ (progress) => {
3944
+ pendingHandoff = writeWorktreeSetupHandoff({
3786
3945
  manifestPath: parallelHandoffPath(artifactsDir, runId),
3787
3946
  runId,
3788
3947
  mode: "single",
@@ -3790,12 +3949,20 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3790
3949
  cwd: sourceCwd,
3791
3950
  stepIndex: 0,
3792
3951
  flatStartIndex: 0,
3793
- setup: plannedSetup,
3952
+ progress,
3794
3953
  laneBindings: params.workflowKey || lane ? [{ index: 0, taskIndex: 0, ...(params.workflowKey ? { workflowKey: params.workflowKey, runId } : {}), ...(lane ? { lane } : {}) }] : undefined,
3795
3954
  });
3796
3955
  },
3797
- );
3798
- if (worktreeSetupError) return worktreeSetupError;
3956
+ signal,
3957
+ data.deadlineAt,
3958
+ ) : {};
3959
+ if (worktreeSetupError) {
3960
+ if (pendingHandoff) {
3961
+ worktreeSetupError.details!.parallelHandoff = pendingHandoff;
3962
+ worktreeSetupError.content.push({ type: "text", text: formatParallelHandoffReference(pendingHandoff) });
3963
+ }
3964
+ return worktreeSetupError;
3965
+ }
3799
3966
  const singleCwd = worktreeSetup?.worktrees[0]?.agentCwd ?? sourceCwd;
3800
3967
  const sandboxTrustError = sandboxProfileTrustError(agentConfig, ctx, singleCwd);
3801
3968
  if (sandboxTrustError) {
@@ -3807,6 +3974,27 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3807
3974
  if (worktreeSetup) cleanupWorktrees(worktreeSetup);
3808
3975
  return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }], isError: true, details: { mode: "single", results: [] } };
3809
3976
  }
3977
+ const cleanupSingleWorktree = async () => {
3978
+ if (!worktreeSetup) return;
3979
+ let admitted = false;
3980
+ try { await withWorktreeTransaction(() => {
3981
+ if (data.deadlineAt !== undefined && Date.now() >= data.deadlineAt) throw new Error("Run deadline expired before unlaunched worktree cleanup");
3982
+ admitted = true;
3983
+ const cleanup = cleanupWorktrees(worktreeSetup);
3984
+ pendingHandoff = writeParallelHandoffGroup({
3985
+ manifestPath: parallelHandoffPath(artifactsDir, runId), runId, mode: "single", source: "foreground",
3986
+ cwd: sourceCwd, stepIndex: 0, flatStartIndex: 0, setup: worktreeSetup, diffs: [], results: [], cleanup,
3987
+ });
3988
+ }); }
3989
+ catch (error) {
3990
+ if (admitted) throw error;
3991
+ pendingHandoff = retainSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd }, error);
3992
+ }
3993
+ };
3994
+ if (worktreeSetup && (signal?.aborted || (data.deadlineAt !== undefined && Date.now() >= data.deadlineAt))) {
3995
+ await cleanupSingleWorktree();
3996
+ return { content: [{ type: "text", text: "Subagent setup canceled before child launch." }], isError: true, details: { mode: "single", results: [], parallelHandoff: pendingHandoff } };
3997
+ }
3810
3998
 
3811
3999
  const authoredTask = task;
3812
4000
  if (shouldForkAgent(contextPolicy, params.agent!)) {
@@ -3816,8 +4004,8 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3816
4004
  const outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, singleCwd, resolveSingleRunOutputBaseDir(deps, artifactsDir, runId));
3817
4005
  const validationError = validateFileOnlyOutputMode(effectiveOutputMode, outputPath, `Single run (${params.agent})`);
3818
4006
  if (validationError) {
3819
- if (worktreeSetup) cleanupWorktrees(worktreeSetup);
3820
- return { content: [{ type: "text", text: validationError }], isError: true, details: { mode: "single", results: [] } };
4007
+ await cleanupSingleWorktree();
4008
+ return { content: [{ type: "text", text: validationError }], isError: true, details: { mode: "single", results: [], parallelHandoff: pendingHandoff } };
3821
4009
  }
3822
4010
  const structuredRuntime = params.outputSchema
3823
4011
  ? createStructuredOutputRuntime(params.outputSchema, artifactConfig.enabled ? path.join(artifactsDir, "structured-output", runId) : undefined, { acceptanceReport: resolveAcceptanceReportMode(params.acceptance) })
@@ -3825,7 +4013,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3825
4013
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
3826
4014
  // absolute paths pass through; relative paths resolve against the child cwd.
3827
4015
  const reads = readsOverride !== undefined ? readsOverride : agentConfig.defaultReads ?? false;
3828
- const readPaths = Array.isArray(reads) ? resolveExistingReadPaths(reads, singleCwd) : [];
4016
+ const readPaths = !foregroundMachine && Array.isArray(reads) ? resolveExistingReadPaths(reads, singleCwd) : [];
3829
4017
  const readsInstruction = readPaths.length > 0
3830
4018
  ? `[Read from: ${readPaths.join(", ")}]\n\n`
3831
4019
  : "";
@@ -3843,7 +4031,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3843
4031
  let childSessionControls: ForegroundChildSessionControls | undefined;
3844
4032
  const foregroundControl = deps.state.foregroundControls.get(runId);
3845
4033
  if (foregroundControl) {
3846
- const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin));
4034
+ const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask());
3847
4035
  beginForegroundChild(foregroundControl, omitUndefinedProperties({
3848
4036
  index: 0,
3849
4037
  agent: params.agent!,
@@ -3875,8 +4063,11 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3875
4063
  }
3876
4064
  },
3877
4065
  }));
4066
+ // Capture the owned mailbox before a child can start and finish between polling ticks.
4067
+ if (deps.childRuntime?.fanoutChild) deps.activateSupervisorTransport?.();
3878
4068
  }
3879
4069
 
4070
+ const modelResponseAliases = deps.config.modelResponseAliases === undefined ? undefined : structuredClone(deps.config.modelResponseAliases);
3880
4071
  const forwardSingleUpdate = onUpdate
3881
4072
  ? (update: AgentToolResult<Details>) => {
3882
4073
  if (foregroundControl) updateForegroundChild(foregroundControl, 0, update.details?.progress?.[0]);
@@ -3885,6 +4076,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3885
4076
  : undefined;
3886
4077
 
3887
4078
  const deadlineAt = data.deadlineAt ?? (data.timeoutMs !== undefined ? Date.now() + data.timeoutMs : undefined);
4079
+ const requiredExtensions = deps.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(data.parentPiSessionId);
3888
4080
  let r: Awaited<ReturnType<typeof runSync>> | undefined;
3889
4081
  let resolveDetachedWorkflowChild: ((result: Awaited<ReturnType<typeof runSync>>) => void) | undefined;
3890
4082
  const detachedWorkflowChild = params.workflowAwaitDetached === true
@@ -3892,12 +4084,17 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3892
4084
  : undefined;
3893
4085
  try {
3894
4086
  const launched = await runSync(ctx.cwd, agents, params.agent!, task, compactOptional<Parameters<typeof runSync>[4]>({
4087
+ machine: foregroundMachine,
4088
+ parentProviderRegistry: ctx.modelRegistry,
4089
+ remoteReads: foregroundMachine ? readsOverride : undefined,
3895
4090
  permissions: deps.config.permissions,
3896
4091
  runtimeSnapshotHost: deps.pi,
4092
+ hostAvailableBuiltins: getHostBuiltinToolNames(deps.pi),
3897
4093
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
3898
4094
  projectTrusted: currentProjectTrusted(ctx),
3899
4095
  ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3900
- llmIntentArbiter: createTaskMutationArbiter(ctx),
4096
+ requiredExtensions,
4097
+ llmIntentArbiter: createTaskMutationArbiter({ model: ctx.model, modelRegistry: ctx.modelRegistry, sessionId: ctx.sessionManager.getSessionId() }),
3901
4098
  childRuntime: deps.childRuntime,
3902
4099
  onChildSession: (controls) => { childSessionControls = controls; },
3903
4100
  context: data.contextPolicy.contextForAgent(params.agent!),
@@ -3934,10 +4131,11 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3934
4131
  fast: params.fast,
3935
4132
  modelOverrideFromParent,
3936
4133
  modelOrigin,
3937
- thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
4134
+ thinkingOverride: thinkingOverrideForTask(),
3938
4135
  thinkingCeiling: agentConfig.maxThinking,
3939
4136
  extensionBindings: params.extensionBindings,
3940
4137
  availableModels,
4138
+ modelResponseAliases,
3941
4139
  preferredModelProvider: currentProvider,
3942
4140
  modelScope: modelScopes,
3943
4141
  skills: effectiveSkills,
@@ -3950,14 +4148,14 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3950
4148
  onDetachReady: (detach) => {
3951
4149
  detachForeground = detach;
3952
4150
  },
3953
- onDetachedExit: (result) => {
4151
+ onDetachedExit: async (result) => {
3954
4152
  if (resolveDetachedWorkflowChild) {
3955
4153
  resolveDetachedWorkflowChild(result);
3956
4154
  return;
3957
4155
  }
3958
4156
  try {
3959
4157
  if (worktreeSetup) {
3960
- finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result, workflowKey: params.workflowKey, lane });
4158
+ await finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result, workflowKey: params.workflowKey, lane });
3961
4159
  }
3962
4160
  try {
3963
4161
  updateRememberedForegroundChild(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, index: 0, result, events: deps.pi.events, notify: true });
@@ -3982,7 +4180,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3982
4180
  try {
3983
4181
  if (foregroundControl) finishForegroundChild(foregroundControl, 0);
3984
4182
  } finally {
3985
- removeForegroundControlIfIdle(deps.state, runId);
4183
+ removeForegroundControlIfIdle(deps.state, runId, deps.trackRetainedNestedRoute);
3986
4184
  }
3987
4185
  }
3988
4186
  }
@@ -3993,12 +4191,13 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3993
4191
  toolTimeoutMs: params.toolTimeoutMs,
3994
4192
  configToolTimeoutMs: data.configToolTimeoutMs,
3995
4193
  toolBudget: effectiveToolBudget.toolBudget,
4194
+ usageBudget: data.usageBudget ?? data.inheritedUsageBudget,
3996
4195
  capabilityCeiling: data.capabilityCeiling,
3997
4196
  allowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,
3998
4197
  }));
3999
4198
  r = launched.detached && detachedWorkflowChild ? await detachedWorkflowChild : launched;
4000
4199
  } catch (error) {
4001
- if (worktreeSetup) cleanupWorktrees(worktreeSetup);
4200
+ await cleanupSingleWorktree();
4002
4201
  throw error;
4003
4202
  } finally {
4004
4203
  // An attached runSync rejection still owns its child and structured runtime.
@@ -4013,11 +4212,11 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4013
4212
  recordRun(params.agent!, cleanTask, r.exitCode, r.progressSummary?.durationMs ?? 0, r);
4014
4213
  }
4015
4214
 
4016
- let worktreeHandoff: ReturnType<typeof finalizeSingleWorktreeHandoff> | undefined;
4215
+ let worktreeHandoff: Awaited<ReturnType<typeof finalizeSingleWorktreeHandoff>> | undefined;
4017
4216
  if (worktreeSetup) {
4018
4217
  worktreeHandoff = r.detached
4019
4218
  ? { suffix: pendingHandoff ? formatParallelHandoffReference(pendingHandoff) : "", reference: pendingHandoff }
4020
- : finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result: r, workflowKey: params.workflowKey, lane });
4219
+ : await finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result: r, workflowKey: params.workflowKey, lane });
4021
4220
  }
4022
4221
 
4023
4222
  if (r.progress) allProgress.push(r.progress);
@@ -4055,7 +4254,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4055
4254
  usageBudget: usageBudgetState(data.usageBudget, totalCost),
4056
4255
  ...(worktreeHandoff?.reference ? { parallelHandoff: worktreeHandoff.reference } : {}),
4057
4256
  }));
4058
- rememberForegroundRun(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: details.results, params, effectiveOutput, effectiveOutputMode, extensionBindings: params.extensionBindings });
4257
+ rememberForegroundRun(deps.state, { modelResponseAliases, runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: details.results, params, effectiveOutput, effectiveOutputMode, extensionBindings: params.extensionBindings, requiredExtensions });
4059
4258
 
4060
4259
  const suppressRoutineResultIntercom = shouldSuppressRoutineResultIntercom({ suppressRoutineResultIntercom: params.suppressRoutineResultIntercom, results: [r] });
4061
4260
  if (!r.detached && !r.interrupted && !suppressRoutineResultIntercom) {
@@ -4131,6 +4330,7 @@ function duplicateSubagentCallResult(params: SubagentParamsLike): AgentToolResul
4131
4330
  }
4132
4331
 
4133
4332
  const workflowLaunchObservers = new WeakMap<object, (launch: { agent: string; sessionName?: string; sessionFile?: string; async: boolean; runId?: string }) => void>();
4333
+ const workflowOwnedUsageBudgets = new WeakMap<object, UsageBudgetConfig>();
4134
4334
 
4135
4335
  /**
4136
4336
  * Terminal-mission retention can remove a mission while its children still
@@ -4211,9 +4411,13 @@ function workflowChildResult(
4211
4411
  ? result.details.results[0].finalOutput
4212
4412
  : receiptOutput;
4213
4413
  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}`
4414
+ const failureErrorBase = childError && receiptOutput
4415
+ ? receiptOutput.includes(childError) ? receiptOutput : `${childError}\n\n${receiptOutput}`
4216
4416
  : childError || receiptOutput || output || "Child run failed.";
4417
+ const savedOutputEvidence = [...new Set(result.details.results.map((child) => child.savedOutputPath).filter((value): value is string => Boolean(value)))]
4418
+ .filter((savedOutputPath) => !failureErrorBase.includes(savedOutputPath))
4419
+ .map((savedOutputPath) => `Saved output: ${savedOutputPath}`);
4420
+ const failureError = [failureErrorBase, ...savedOutputEvidence].join("\n");
4217
4421
  const detached = result.details.results.some((child) => child.detached);
4218
4422
  const interrupted = result.details.results.some((child) => child.interrupted);
4219
4423
  const stopped = result.details.results.some((child) => child.stopped);
@@ -4252,8 +4456,6 @@ function workflowChildResult(
4252
4456
  }
4253
4457
  const requestedContext = childParams.context === "fresh" || childParams.context === "fork" ? childParams.context : undefined;
4254
4458
  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
4459
  const outputReference = result.details.results.find((child) => child.savedOutputPath)?.savedOutputPath
4258
4460
  ?? result.details.results.find((child) => child.outputReference?.path)?.outputReference?.path;
4259
4461
  const outputPathMapping = typeof childParams.task === "string" ? outputPathMappingFromTask(childParams.task, outputReference) : undefined;
@@ -4286,7 +4488,7 @@ function workflowChildResult(
4286
4488
  ...(outputPathMapping ? { outputPathMapping } : {}),
4287
4489
  ...(externalAdapter ? { externalAdapter } : {}),
4288
4490
  resumability,
4289
- continuation: { runIds: continuationRunIds },
4491
+ continuation: { runIds: runId ? [runId] : [] },
4290
4492
  artifactPaths: [...artifactPaths],
4291
4493
  results: result.details.results,
4292
4494
  };
@@ -4399,10 +4601,33 @@ function missingWorkflowReceiptResumeHint(reference: WorkflowReceiptResumeRefere
4399
4601
  }
4400
4602
  }
4401
4603
 
4402
- function resolveKeyedWorkflowResume(
4403
- reference: WorkflowReceiptResumeReference,
4404
- state: SubagentState,
4405
- ): { runId: string; runIds: string[] } {
4604
+ function resolveWorkflowResume(
4605
+ reference: WorkflowReceiptResumeReference | string,
4606
+ deps: ExecutorDeps,
4607
+ parentSessionFile: string | null,
4608
+ index?: number,
4609
+ ): string | { runId: string; runIds: string[] } {
4610
+ const state = deps.state;
4611
+ if (typeof reference === "string") {
4612
+ const target = resolveRequestedResumeTarget({ id: reference.trim(), ...(index !== undefined ? { index } : {}) }, deps, parentSessionFile);
4613
+ // Live routing stays with action=resume and does not claim retained lineage.
4614
+ if (target.kind !== "revive") return reference.trim();
4615
+ const runId = target.runId;
4616
+ const status = target.source === "async" && target.asyncDir ? readStatus(target.asyncDir) : undefined;
4617
+ if (status?.runId === runId && status.parentWorkflowRunId && status.workflowKey) {
4618
+ // Only follow the validated child's recorded owner; never search other workflows.
4619
+ const receiptPath = workflowReceiptPath(DIRS.async, status.parentWorkflowRunId);
4620
+ try {
4621
+ fs.statSync(receiptPath);
4622
+ } catch (error) {
4623
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { runId, runIds: [runId] };
4624
+ throw error;
4625
+ }
4626
+ const entry = readWorkflowReceipt(DIRS.async, status.parentWorkflowRunId).entries[status.workflowKey];
4627
+ if (entry?.latestRunId === runId) return { runId, runIds: entry.continuation.runIds };
4628
+ }
4629
+ return { runId, runIds: [runId] };
4630
+ }
4406
4631
  try {
4407
4632
  const entry = resolveWorkflowReceiptResumeEntry({
4408
4633
  reference,
@@ -4412,9 +4637,7 @@ function resolveKeyedWorkflowResume(
4412
4637
  if (target.kind !== "revive") throw new Error(`Workflow receipt child '${reference.key}' latest run '${runId}' is still running.`);
4413
4638
  },
4414
4639
  });
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 };
4640
+ return { runId: entry.latestRunId, runIds: entry.continuation.runIds };
4418
4641
  } catch (error) {
4419
4642
  const workflowRunId = reference.workflowRunId.trim();
4420
4643
  if (isMissingWorkflowReceiptDiagnostic(error, workflowRunId)) {
@@ -4433,8 +4656,9 @@ function terminalWorkflowReceipt(
4433
4656
  terminalOutcome?: WorkflowTerminalOutcome,
4434
4657
  hostSteps?: WorkflowReceipt["hostSteps"],
4435
4658
  resource?: WorkflowReceipt["resource"],
4659
+ argsDigest?: string,
4436
4660
  ): WorkflowReceipt {
4437
- return buildWorkflowReceipt({ workflowRunId, state, children, workflowChildren, terminalOutcome, hostSteps, resource });
4661
+ return buildWorkflowReceipt({ workflowRunId, state, children, workflowChildren, terminalOutcome, hostSteps, resource, ...(argsDigest ? { argsDigest } : {}) });
4438
4662
  }
4439
4663
 
4440
4664
  function workflowFailureTerminalOutcome(error: unknown, _children: WorkflowScriptChildResult[], usageBudget: ReturnType<typeof usageBudgetState>): WorkflowTerminalOutcome | undefined {
@@ -4517,6 +4741,35 @@ export async function steerWorkflowChildByKey(input: {
4517
4741
  }
4518
4742
  }
4519
4743
 
4744
+ export async function preflightWorkflowWorktrees(input: {
4745
+ workflowDefaults: SubagentParamsLike;
4746
+ defaultWorktree?: boolean;
4747
+ calls: Array<{ key: string; params: Record<string, unknown> }>;
4748
+ ctxCwd: string;
4749
+ signal: AbortSignal;
4750
+ deadlineAt?: number;
4751
+ }): Promise<void> {
4752
+ const sources = new Map<string, string[]>();
4753
+ for (const { key, params } of input.calls) {
4754
+ // The workflow validates retained IDs/receipt references before admission; resolution follows it.
4755
+ if (params.resume !== undefined) continue;
4756
+ const effective = prepareWorkflowLaunchParams(input.workflowDefaults, params, "preflight", key);
4757
+ if ((effective.worktree ?? input.defaultWorktree) !== true) continue;
4758
+ // Match recursive execute's resolution, including relative default/child cwd.
4759
+ const cwd = resolveRequestedCwd(input.ctxCwd, effective.cwd);
4760
+ const keys = sources.get(cwd) ?? [];
4761
+ keys.push(key);
4762
+ sources.set(cwd, keys);
4763
+ }
4764
+ for (const [cwd, keys] of sources) {
4765
+ try { await preflightWorktreeSource(cwd, { signal: input.signal, deadlineAt: input.deadlineAt }); }
4766
+ catch (error) {
4767
+ 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 });
4768
+ }
4769
+ }
4770
+ input.signal.throwIfAborted();
4771
+ }
4772
+
4520
4773
  export function prepareWorkflowLaunchParams(
4521
4774
  workflowDefaults: SubagentParamsLike,
4522
4775
  childParams: Record<string, unknown>,
@@ -4551,9 +4804,9 @@ export function prepareWorkflowLaunchParams(
4551
4804
  const worktree = childParams.worktree ?? workflowDefaults.worktree;
4552
4805
  const baseRef = Object.hasOwn(childParams, "baseRef") ? childParams.baseRef : undefined;
4553
4806
  const outputSchema = Object.hasOwn(childParams, "outputSchema") ? childParams.outputSchema : workflowDefaults.outputSchema;
4554
- if (outputSchema !== undefined) assertJsonSchemaObject(outputSchema, "outputSchema");
4807
+ if (outputSchema !== undefined && outputSchema !== false) assertJsonSchemaObject(outputSchema, "outputSchema");
4555
4808
  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 }.");
4809
+ if (agentContract !== undefined && !isAgentContract(agentContract as AgentContract)) throw new Error("agentContract must be { version: 1 }.");
4557
4810
  const acceptance = Object.hasOwn(childParams, "acceptance") ? childParams.acceptance : workflowDefaults.acceptance;
4558
4811
  const output = Object.hasOwn(childParams, "output") ? childParams.output : workflowDefaults.output;
4559
4812
  if (output !== undefined && typeof output !== "string" && typeof output !== "boolean") throw new Error("output must be a path string or boolean.");
@@ -4567,10 +4820,11 @@ export function prepareWorkflowLaunchParams(
4567
4820
  message: typeof childParams.task === "string" ? childParams.task.trim() : "",
4568
4821
  workflowParentRunId: parentWorkflowRunId,
4569
4822
  workflowKey,
4823
+ ...(options.outputClaimPath ? { workflowOutputClaimPath: options.outputClaimPath } : {}),
4570
4824
  ...(lane ? { lane } : {}),
4571
4825
  ...(worktree !== undefined ? { worktree: worktree as boolean } : {}),
4572
4826
  ...(baseRef !== undefined ? { baseRef: baseRef as string } : {}),
4573
- ...(outputSchema !== undefined ? { outputSchema: outputSchema as JsonSchemaObject } : {}),
4827
+ ...(outputSchema !== undefined ? { outputSchema } : {}),
4574
4828
  ...(agentContract !== undefined ? { agentContract: agentContract as AgentContract } : {}),
4575
4829
  ...(acceptance !== undefined ? { acceptance: acceptance as AcceptanceInput } : {}),
4576
4830
  ...(output !== undefined ? { output: output as string | boolean } : {}),
@@ -4585,12 +4839,13 @@ export function prepareWorkflowLaunchParams(
4585
4839
  };
4586
4840
  }
4587
4841
  const control = mergeWorkflowControlOverrides(workflowDefaults.control, childParams.control as ControlConfig | undefined);
4842
+ const asyncOmitted = childParams.async === undefined && workflowDefaults.async === undefined;
4588
4843
  const launchParams = {
4589
4844
  ...workflowDefaults,
4590
- async: options.externalAsyncRequired === true && childParams.async === undefined && workflowDefaults.async === undefined ? true : false,
4845
+ ...(options.externalAsyncRequired === true && asyncOmitted ? { async: true } : {}),
4591
4846
  ...childParams,
4592
4847
  ...(control !== undefined ? { control } : {}),
4593
- ...(options.externalAsyncRequired === true && childParams.async === undefined && workflowDefaults.async === undefined ? { workflowAwaitAsync: true } : {}),
4848
+ ...(asyncOmitted ? { workflowAwaitAsync: true } : {}),
4594
4849
  ...(options.missionDetached ? { mission: false } : {}),
4595
4850
  workflowParentRunId: parentWorkflowRunId,
4596
4851
  workflowKey,
@@ -4728,14 +4983,14 @@ function applyWorkflowLaneTrace(graph: WorkflowGraphSnapshot, trace: WorkflowScr
4728
4983
  else delete graph.currentNodeId;
4729
4984
  }
4730
4985
 
4731
- function workflowChatProgressUpdate(
4986
+ function workflowProgressUpdate(
4732
4987
  runId: string,
4733
4988
  chatProgress: WorkflowChatProgressProjection,
4734
4989
  workflow: NonNullable<Details["workflow"]>,
4735
4990
  workflowChildren?: Details["workflowChildren"],
4736
- preflight?: import("../../shared/types.ts").WorkflowPreflightV1,
4737
- ): AgentToolResult<Details> | undefined {
4738
- if (chatProgress.mode !== "live-card") return undefined;
4991
+ preflight?: import("../../shared/types.ts").WorkflowPreflight,
4992
+ ): AgentToolResult<Details> {
4993
+ // chatProgress controls the TUI projection, not transport-level progress.
4739
4994
  return {
4740
4995
  content: [{ type: "text", text: "Workflow running." }],
4741
4996
  details: { mode: "workflow", runId, results: [], workflow, ...(preflight ? { preflight } : {}), ...(workflowChildren ? { workflowChildren } : {}), chatProgress },
@@ -4811,6 +5066,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4811
5066
  signal: AbortSignal,
4812
5067
  ctx: ExtensionContext,
4813
5068
  ) => Promise<AgentToolResult<Details>>;
5069
+ /** Scheduled state visible to the current runtime supervisor owner only. */
5070
+ getCurrentSupervisorOwnerStates: () => Iterable<SubagentState>;
4814
5071
  } {
4815
5072
  const delegatedThinkingOverrides = new WeakMap<object, AgentConfig["thinking"]>();
4816
5073
  const delegatedZeroToolBudgets = new WeakSet<object>();
@@ -4819,7 +5076,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4819
5076
  const workflowResourcePermits = new WeakMap<object, WorkflowResourcePermit>();
4820
5077
  const workflowPermitContexts = new WeakMap<object, { root: WorkflowChildPermit } | { child: WorkflowChildPermitContext }>();
4821
5078
  const warnedArtifactPackageDirs = new Set<string>();
4822
- const scheduledOwnerExecutors = new Map<string, ReturnType<typeof createSubagentExecutor>>();
5079
+ const scheduledOwnerExecutors = new Map<string | null, Map<string, { state: SubagentState; executor: ReturnType<typeof createSubagentExecutor> }>>();
4823
5080
  const execute = async (
4824
5081
  _id: string,
4825
5082
  params: SubagentParamsLike,
@@ -4830,6 +5087,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4830
5087
  parentModelOverride?: ParentModel | null,
4831
5088
  ): Promise<AgentToolResult<Details>> => {
4832
5089
  const workflowLaunchObserver = workflowLaunchObservers.get(params);
5090
+ const inheritedUsageBudget = workflowOwnedUsageBudgets.get(params);
4833
5091
  const delegatedThinkingOverride = delegatedThinkingOverrides.get(params);
4834
5092
  const allowZeroToolBudget = delegatedZeroToolBudgets.has(params);
4835
5093
  const delegatedExecution = delegatedExecutions.has(params);
@@ -4847,7 +5105,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4847
5105
  let requestParams = normalizedGate.params;
4848
5106
  const capacityOverrideError = validateWorkflowCapacityOverrides(requestParams);
4849
5107
  if (capacityOverrideError) return buildRequestedModeError(requestParams, capacityOverrideError);
4850
- let workflowPreflight: import("../../shared/types.ts").WorkflowPreflightV1 | undefined;
5108
+ let workflowPreflight: import("../../shared/types.ts").WorkflowPreflight | undefined;
4851
5109
  try {
4852
5110
  if (requestParams.preflight !== undefined && requestParams.workflowScript === undefined && requestParams.workflowScriptPath === undefined) {
4853
5111
  throw new Error("preflight requires workflowScript or workflowScriptPath.");
@@ -4857,7 +5115,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4857
5115
  } catch (error) {
4858
5116
  const message = error instanceof Error ? error.message : String(error);
4859
5117
  if (requestParams.action?.trim() === "validate") {
4860
- const validation = validateWorkflowScript(requestParams.workflowScript ?? "");
5118
+ const validation = validateWorkflowScript(requestParams.workflowScript ?? "", {
5119
+ maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
5120
+ });
4861
5121
  const invalidValidation = { ...validation, ok: false, errors: [...validation.errors, { message }] };
4862
5122
  return {
4863
5123
  content: [{ type: "text", text: JSON.stringify(invalidValidation) }],
@@ -4868,7 +5128,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4868
5128
  return buildRequestedModeError(requestParams, message);
4869
5129
  }
4870
5130
  if (requestParams.action?.trim() === "validate") {
4871
- const validation = validateWorkflowScript(requestParams.workflowScript ?? "");
5131
+ const validation = validateWorkflowScript(requestParams.workflowScript ?? "", {
5132
+ maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
5133
+ });
4872
5134
  const payload = workflowPreflight ? { ...validation, preflight: workflowPreflight } : validation;
4873
5135
  return {
4874
5136
  content: [{ type: "text", text: JSON.stringify(payload) }],
@@ -4878,7 +5140,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4878
5140
  }
4879
5141
  const normalizedAction = typeof requestParams.action === "string" ? requestParams.action.trim() : requestParams.action;
4880
5142
  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;
5143
+ let workflowResource: { permit: WorkflowResourcePermit; provenance: WorkflowResourceProvenance; authority: WorkflowResourceAuthority } | undefined;
4882
5144
  if (workflowResourcePermit) {
4883
5145
  if (typeof requestParams.workflowScript !== "string") return buildRequestedModeError(requestParams, "Resolved workflow resource is missing its workflow script.");
4884
5146
  const consumed = consumeWorkflowResourcePermit(workflowResourcePermit, requestParams.workflowScript);
@@ -4886,8 +5148,22 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4886
5148
  workflowResource = { permit: workflowResourcePermit, ...consumed };
4887
5149
  }
4888
5150
  if (requestParams.workflowScript !== undefined && normalizedAction === undefined) {
5151
+ const workflowArgsEvidence = requestParams.args === undefined ? undefined : { args: requestParams.args, argsDigest: stableJsonDigest(requestParams.args) };
5152
+ const workflowArgs = workflowArgsEvidence?.args;
5153
+ const workflowArgsDigest = workflowArgsEvidence?.argsDigest;
5154
+ const spawnBudgetValidation = validateWorkflowScript(requestParams.workflowScript, {
5155
+ maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
5156
+ });
5157
+ const spawnBudgetErrors = spawnBudgetValidation.errors.filter((error) => error.kind === "spawn-budget");
5158
+ if (spawnBudgetErrors.length > 0) {
5159
+ return buildRequestedModeError(requestParams, `workflowScript validation failed before child launch; no children launched. ${spawnBudgetErrors.map((error) => error.message).join(" ")}`);
5160
+ }
5161
+ for (const warning of spawnBudgetValidation.warnings ?? []) console.warn(`[pi-subagents] ${warning.message}`);
5162
+ const acceptanceErrors = validateAcceptanceInput(requestParams.acceptance);
5163
+ if (acceptanceErrors.length > 0) return buildRequestedModeError(requestParams, acceptanceErrors.join(" "));
5164
+ const foregroundWorkflowRunId = encodeIndexSegment(_id);
4889
5165
  if (delegatedWorkflowPermit) {
4890
- const permitError = validateWorkflowChildPermitRoot(delegatedWorkflowPermit, _id);
5166
+ const permitError = validateWorkflowChildPermitRoot(delegatedWorkflowPermit, foregroundWorkflowRunId);
4891
5167
  if (permitError) return buildRequestedModeError(requestParams, permitError);
4892
5168
  if (requestParams.async !== false) return buildRequestedModeError(requestParams, "Workflow child permit supports foreground workflow roots only; set async:false.");
4893
5169
  }
@@ -5042,7 +5318,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5042
5318
  pid: process.pid,
5043
5319
  steps: [],
5044
5320
  ...(workflowPreflight ? { preflight: workflowPreflight } : {}),
5045
- workflow: { trace: [], emits: [], console: [], ...(workflowResource ? { resource: workflowResource.provenance } : {}) },
5321
+ workflow: { trace: [], emits: [], console: [], ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}) },
5046
5322
  workflowChildren: workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState: "running", inventoryComplete: false }),
5047
5323
  runFanoutBudget: getRunFanoutBudgetSnapshot(workflowFanoutBudget),
5048
5324
  };
@@ -5062,18 +5338,58 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5062
5338
  onSuccess: (_filePath, payload) => { indexedState = (payload as { state: AsyncStatus["state"] }).state; },
5063
5339
  onError: (error, filePath) => console.error(`Failed to update async workflow index '${filePath}':`, error),
5064
5340
  });
5065
- const queueActiveRunIndex = (): void => {
5066
- const state = status.state;
5341
+ const queueActiveRunIndex = (snapshot: AsyncStatus = status): void => {
5342
+ const state = snapshot.state;
5067
5343
  if (indexedState === state && indexPersistence.pendingCount() === 0) return;
5068
- indexPersistence.write(asyncDir, { state, toolCallId: status.toolCallId }, (_filePath, payload) => {
5344
+ indexPersistence.write(asyncDir, { state, toolCallId: snapshot.toolCallId }, (_filePath, payload) => {
5069
5345
  const indexPayload = payload as { state: AsyncStatus["state"]; toolCallId?: string };
5070
5346
  updateActiveRunIndex(asyncDir, indexPayload.state, indexPayload.toolCallId, { retryCapacityErrors: true });
5071
5347
  });
5072
5348
  };
5349
+ let pendingResultPublication: Promise<boolean> | undefined;
5350
+ let settleResultPublication: ((published: boolean) => void) | undefined;
5351
+ let resultWriteFailureWakeDelivered = false;
5352
+ const reportResultWriteFailure = (error: unknown): boolean => {
5353
+ const message = `Failed to write async workflow result ${resultPath}: ${error instanceof Error ? error.message : String(error)}`;
5354
+ console.error(message, error);
5355
+ try {
5356
+ if (currentSessionId && fallbackResultPayloadPathForSessionRun(path.dirname(resultPath), currentSessionId, workflowRunId)) return true;
5357
+ } catch (pendingError) {
5358
+ console.error(`Failed to verify pending async workflow result '${workflowRunId}':`, pendingError);
5359
+ }
5360
+ appendWorkflowEvent({ type: "subagent.workflow.result_write_failed", error: message });
5361
+ // A missing result file means the result watcher will never deliver the
5362
+ // terminal completion wake. Intermediate child notices are context-only
5363
+ // once their turns are suppressed, so surface the failure as its own
5364
+ // actionable wake instead of leaving the parent asleep.
5365
+ if (resultWriteFailureWakeDelivered) return false;
5366
+ if (deps.state.currentSessionId !== currentSessionId || deps.state.completionOwnerId !== completionOwnerId) return false;
5367
+ try {
5368
+ deps.pi.sendMessage(
5369
+ {
5370
+ customType: "subagent-workflow-result-write-failed",
5371
+ content: message,
5372
+ display: true,
5373
+ },
5374
+ { triggerTurn: true },
5375
+ );
5376
+ resultWriteFailureWakeDelivered = true;
5377
+ } catch (sendError) {
5378
+ console.error(`Failed to send workflow result write failure notification for '${workflowRunId}':`, sendError);
5379
+ }
5380
+ deps.refreshResultDelivery?.();
5381
+ return false;
5382
+ };
5073
5383
  const runPersistence = createCapacityResilientJsonWriter({
5074
5384
  keepAlive: true,
5075
- onSuccess: (filePath) => { if (filePath === statusPath) queueActiveRunIndex(); },
5076
- onError: (error, filePath) => console.error(`Failed to persist async workflow state '${filePath}':`, error),
5385
+ onSuccess: (filePath, payload) => {
5386
+ if (filePath === statusPath) queueActiveRunIndex(payload as AsyncStatus);
5387
+ if (filePath === resultPath) settleResultPublication?.(true);
5388
+ },
5389
+ onError: (error, filePath) => {
5390
+ if (filePath === resultPath) settleResultPublication?.(reportResultWriteFailure(error));
5391
+ else console.error(`Failed to persist async workflow state '${filePath}':`, error);
5392
+ },
5077
5393
  write: (filePath, payload) => filePath === resultPath
5078
5394
  ? writeAsyncResultFile(filePath, payload as Record<string, unknown>)
5079
5395
  : writeAtomicJson(filePath, payload),
@@ -5101,7 +5417,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5101
5417
  queueActiveRunIndex();
5102
5418
  } else if (options.tolerateStatusWriteFailure) {
5103
5419
  try {
5104
- runPersistence.write(statusPath, status);
5420
+ runPersistence.write(statusPath, { ...status });
5105
5421
  statusPersistenceDegraded = false;
5106
5422
  } catch (error) {
5107
5423
  const message = `Failed to persist async workflow state ${statusPath}: ${error instanceof Error ? error.message : String(error)}`;
@@ -5116,7 +5432,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5116
5432
  }
5117
5433
  }
5118
5434
  } else {
5119
- runPersistence.write(statusPath, status);
5435
+ runPersistence.write(statusPath, { ...status });
5120
5436
  }
5121
5437
  if (liveJob) {
5122
5438
  liveJob.status = status.state;
@@ -5144,13 +5460,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5144
5460
  };
5145
5461
  const writeWorkflowResult = (payload: Record<string, unknown>): boolean => {
5146
5462
  try {
5463
+ let resultPublished = false;
5464
+ settleResultPublication = (published) => { resultPublished = published; };
5465
+ pendingResultPublication = undefined;
5147
5466
  runPersistence.write(resultPath, payload);
5467
+ // Only capacity deferral yields; ordinary publication remains synchronous.
5468
+ if (!resultPublished) pendingResultPublication = new Promise<boolean>((resolve) => { settleResultPublication = resolve; });
5148
5469
  return true;
5149
5470
  } 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;
5471
+ return reportResultWriteFailure(error);
5154
5472
  }
5155
5473
  };
5156
5474
  const projectWorkflowActivity = () => {
@@ -5188,16 +5506,157 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5188
5506
  indexPersistence.dispose();
5189
5507
  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
5508
  }
5191
- appendWorkflowEvent({ type: "subagent.workflow.started" });
5509
+ appendWorkflowEvent({ type: "subagent.workflow.started", ...(workflowArgsDigest ? { argsDigest: workflowArgsDigest } : {}) });
5510
+ // The runner does not execute workflow scripts: this active owner must consume its own
5511
+ // durable steer inbox, deliver through in-process child controls, and persist receipts.
5512
+ const emitWorkflowSteerEvent = (type: string, requestId: string, index?: number, extra: Record<string, unknown> = {}): void => {
5513
+ appendWorkflowEvent({ type, requestId, ...(index !== undefined ? { index } : {}), ...extra });
5514
+ };
5515
+ const recordWorkflowSteerTargets = (request: SteerRequest, targets: Array<{ index: number; state: SteeringTargetState; reason?: string }>): void => {
5516
+ status.steering ??= createSteeringStatus();
5517
+ recordSteeringRequest(steeringStatus(status), {
5518
+ id: request.id,
5519
+ requestedAt: request.ts,
5520
+ ...(request.source ? { source: request.source } : {}),
5521
+ message: request.message,
5522
+ targets,
5523
+ });
5524
+ };
5525
+ const explicitWorkflowSteerIndexes = (request: SteerRequest): number[] | undefined => request.targetIndex !== undefined ? [request.targetIndex] : request.targetIndexes;
5526
+ const failWorkflowSteer = (request: SteerRequest, indexes: number[], reason: string): void => {
5527
+ const targets = indexes.map((index) => ({ index, state: "failed" as const, reason }));
5528
+ recordWorkflowSteerTargets(request, targets);
5529
+ emitWorkflowSteerEvent("subagent.steer.requested", request.id, undefined, { targets });
5530
+ for (const index of indexes) emitWorkflowSteerEvent("subagent.steer.failed", request.id, index, { reason });
5531
+ persist({ tolerateStatusWriteFailure: true });
5532
+ };
5533
+ const pendingWorkflowSteers = new Set<(state: "delivered" | "queued" | "failed", reason?: string) => void>();
5534
+ const deliverWorkflowSteerRequest = (request: SteerRequest): void => {
5535
+ let indexes = explicitWorkflowSteerIndexes(request);
5536
+ if (status.state !== "running") {
5537
+ failWorkflowSteer(request, indexes ?? [0], `run became ${status.state} before steering request was consumed`);
5538
+ return;
5539
+ }
5540
+ const liveControls = [...deps.state.foregroundControls.values()].filter((candidate) => candidate.parentWorkflowRunId === workflowRunId && (candidate.activeChildren?.size ?? 0) > 0);
5541
+ if (indexes === undefined) {
5542
+ if (liveControls.length !== 1) {
5543
+ failWorkflowSteer(request, [0], liveControls.length > 1
5544
+ ? `workflow has ${liveControls.length} live children; steer a child run id instead`
5545
+ : "workflow child is not live in this process");
5546
+ return;
5547
+ }
5548
+ const index = status.steps?.findIndex((step) => !!step.workflowKey && step.workflowKey === liveControls[0]!.workflowKey) ?? -1;
5549
+ if (index < 0) {
5550
+ failWorkflowSteer(request, [0], "live workflow child has no projected step");
5551
+ return;
5552
+ }
5553
+ indexes = [index];
5554
+ }
5555
+ // Normalize and record the whole set once: recordSteeringRequest is idempotent by id.
5556
+ // Explicit indexes resolve only by their projected key, never by a live sibling.
5557
+ const resolved = indexes.map((index) => {
5558
+ const step = status.steps?.[index];
5559
+ const control = step?.workflowKey ? liveControls.find((candidate) => candidate.workflowKey === step.workflowKey) : undefined;
5560
+ return { index, control, reason: !step ? "child index out of range" : !control ? "workflow child is not live in this process" : undefined };
5561
+ });
5562
+ const targets = resolved.map(({ index, reason }) => ({ index, state: reason ? "failed" as const : "routed" as const, ...(reason ? { reason } : {}) }));
5563
+ recordWorkflowSteerTargets(request, targets);
5564
+ emitWorkflowSteerEvent("subagent.steer.requested", request.id, undefined, { targets });
5565
+ persist({ tolerateStatusWriteFailure: true });
5566
+ for (const { index, control, reason } of resolved) {
5567
+ if (!control) {
5568
+ emitWorkflowSteerEvent("subagent.steer.failed", request.id, index, { reason });
5569
+ continue;
5570
+ }
5571
+ emitWorkflowSteerEvent("subagent.steer.routed", request.id, index);
5572
+ const applyWorkflowSteerDelivery = (state: "delivered" | "queued" | "failed", reason?: string): void => {
5573
+ // Shutdown settles unresolved receipts synchronously; late SDK callbacks cannot rewrite them.
5574
+ if (!pendingWorkflowSteers.has(applyWorkflowSteerDelivery)) return;
5575
+ // Queuing is not confirmation of delivery: retain ownership until terminal settlement.
5576
+ if (state !== "queued") pendingWorkflowSteers.delete(applyWorkflowSteerDelivery);
5577
+ const now = Date.now();
5578
+ const steering = steeringStatus(status);
5579
+ // This callback owns a pending target, even after bounded display history
5580
+ // evicts its request. Account independently; queued still represents one pending target.
5581
+ if (state !== "queued") steering.pending = Math.max(0, steering.pending - 1);
5582
+ if (state === "delivered") {
5583
+ steering.delivered++;
5584
+ steering.lastDeliveredAt = now;
5585
+ } else if (state === "failed") steering.failed++;
5586
+ const receipt = steering.recent.find((candidate) => candidate.id === request.id)?.targets.find((target) => target.index === index);
5587
+ if (receipt) {
5588
+ receipt.state = state;
5589
+ if (state === "delivered") receipt.deliveredAt = now;
5590
+ if (state === "failed") receipt.failedAt = now;
5591
+ if (reason) receipt.reason = reason;
5592
+ }
5593
+ if (state === "failed") {
5594
+ const failedStep = status.steps?.[index];
5595
+ if (failedStep) failedStep.activityState = "needs_attention";
5596
+ status.activityState = "needs_attention";
5597
+ }
5598
+ emitWorkflowSteerEvent(`subagent.steer.${state}`, request.id, index, state === "failed" ? { reason } : { deliveryStatus: state, message: request.message });
5599
+ persist({ tolerateStatusWriteFailure: true });
5600
+ };
5601
+ pendingWorkflowSteers.add(applyWorkflowSteerDelivery);
5602
+ void steerWorkflowForegroundTarget({
5603
+ target: { control, workflowRunId, sourceRunId: workflowRunId },
5604
+ message: request.message,
5605
+ ...(request.mode ? { mode: request.mode } : {}),
5606
+ }).then(
5607
+ (result) => {
5608
+ const target = result.details.steering?.targets[0];
5609
+ applyWorkflowSteerDelivery(target?.state === "delivered" ? "delivered" : target?.state === "queued" ? "queued" : "failed", target?.reason ?? (target ? undefined : "steering produced no target receipt"));
5610
+ },
5611
+ (error) => applyWorkflowSteerDelivery("failed", error instanceof Error ? error.message : String(error)),
5612
+ );
5613
+ }
5614
+ };
5615
+ let disposeWorkflowSteerInbox: (() => void) | undefined;
5616
+ try {
5617
+ disposeWorkflowSteerInbox = watchAsyncControlInbox(asyncDir, {
5618
+ onSteer: deliverWorkflowSteerRequest,
5619
+ onError: (error, phase, request) => {
5620
+ const reason = error instanceof Error ? error.message : String(error);
5621
+ appendWorkflowEvent({ type: "subagent.workflow.steer_inbox_unavailable", phase, error: reason });
5622
+ if (request) failWorkflowSteer(request, explicitWorkflowSteerIndexes(request) ?? [0], `steer consumer failed: ${reason}`);
5623
+ },
5624
+ });
5625
+ } catch (error) {
5626
+ // Steering is an optional control surface, so a watcher that cannot install must not fail the run.
5627
+ appendWorkflowEvent({ type: "subagent.workflow.steer_inbox_unavailable", error: error instanceof Error ? error.message : String(error) });
5628
+ }
5629
+ deps.activateSupervisorTransport?.();
5192
5630
  const { workflowScript, async: _workflowAsync, chatProgress: _chatProgress, ...workflowRequest } = requestParams;
5631
+ let workflowSteerInboxClosed = false;
5632
+ const settleWorkflowSteerInbox = (outcome = status.state): void => {
5633
+ if (workflowSteerInboxClosed) return;
5634
+ workflowSteerInboxClosed = true;
5635
+ disposeWorkflowSteerInbox?.();
5636
+ // Consumed deliveries are not files anymore. Fail unresolved SDK operations without awaiting them.
5637
+ for (const settle of pendingWorkflowSteers) settle("failed", `run became ${outcome} before steering delivery settled; delivery unconfirmed`);
5638
+ try {
5639
+ closeSteerInbox(asyncDir, outcome);
5640
+ // Separately drain requests that never reached the consumer.
5641
+ const undelivered = consumeSteerRequests(asyncDir, undefined, (error) => {
5642
+ appendWorkflowEvent({ type: "subagent.workflow.steer_inbox_unavailable", phase: "drain", error: error instanceof Error ? error.message : String(error) });
5643
+ });
5644
+ for (const request of undelivered) failWorkflowSteer(request, explicitWorkflowSteerIndexes(request) ?? [0], `run became ${outcome} before steering request was consumed`);
5645
+ } catch (error) {
5646
+ appendWorkflowEvent({ type: "subagent.workflow.steer_inbox_unavailable", phase: "close", error: error instanceof Error ? error.message : String(error) });
5647
+ }
5648
+ // Commit receipts while run status is still nonterminal. Result/index publication
5649
+ // can fail next; teardown must not publish the subsequently computed terminal status.
5650
+ persist();
5651
+ };
5193
5652
  void Promise.resolve().then(async () => {
5194
5653
  const workflowDeadlineAt = timeout === undefined ? undefined : Date.now() + timeout;
5195
5654
  const workflowResults: SingleResult[] = [];
5196
5655
  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;
5656
+ 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
5657
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
5199
5658
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
5200
- const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, parentCwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId));
5659
+ const workflowAggregateOutputPath = resolveSingleOutputPath(workflowOutput, parentCwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId));
5201
5660
  const claimedOutputPaths = new Map<string, string>();
5202
5661
  const childOutputOverrides = new Map<string, string>();
5203
5662
  const childOutputClaimPaths = new Map<string, string>();
@@ -5319,6 +5778,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5319
5778
  try {
5320
5779
  const workflow = await runWorkflowScript({
5321
5780
  script: workflowScript,
5781
+ ...(workflowArgs ? { args: workflowArgs } : {}),
5782
+ workflowRunId,
5783
+ processCwd: ctx.cwd,
5322
5784
  globalConcurrencyLimit: requestParams.globalConcurrencyLimit ?? deps.config.globalConcurrencyLimit,
5323
5785
  timeoutMs: timeout,
5324
5786
  signal: controller.signal,
@@ -5334,6 +5796,28 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5334
5796
  },
5335
5797
  ...(workflowState ? { state: workflowState } : {}),
5336
5798
  onTrace: updateTrace,
5799
+ onChildSettled: (notification) => {
5800
+ appendWorkflowEvent({
5801
+ type: "subagent.workflow.child_settled",
5802
+ childKey: notification.childKey,
5803
+ ...(notification.childRunId ? { childRunId: notification.childRunId } : {}),
5804
+ outcome: notification.outcome,
5805
+ workflowRunning: notification.workflowRunning,
5806
+ });
5807
+ try {
5808
+ deps.pi.sendMessage(
5809
+ {
5810
+ customType: "subagent-incremental-child-notify",
5811
+ content: formatIncrementalChildCompletion(notification),
5812
+ display: notification.outcome !== "completed",
5813
+ },
5814
+ { triggerTurn: incrementalChildCompletionTriggersTurn(notification, requestParams.scheduleOrigin) },
5815
+ );
5816
+ } catch (sendError) {
5817
+ console.error(`Failed to send incremental child completion notification for '${notification.childKey}':`, sendError);
5818
+ }
5819
+ deps.refreshResultDelivery?.();
5820
+ },
5337
5821
  onLanePlan: (lanes) => {
5338
5822
  status.workflowGraph = buildWorkflowLaneGraph(workflowRunId, lanes, status.workflowGraph);
5339
5823
  applyWorkflowLaneTrace(status.workflowGraph, status.workflow?.trace ?? []);
@@ -5346,7 +5830,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5346
5830
  persist({ tolerateStatusWriteFailure: true });
5347
5831
  } });
5348
5832
  },
5349
- admit: (calls) => {
5833
+ admit: async (calls, admissionSignal) => {
5834
+ await preflightWorkflowWorktrees({ workflowDefaults: workflowChildDefaults, defaultWorktree: deps.config.worktree, calls, ctxCwd: parentCwd, signal: admissionSignal, deadlineAt: workflowDeadlineAt });
5350
5835
  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
5836
  if (outputClaims.error) throw new Error(outputClaims.error);
5352
5837
  status.runFanoutBudget = claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
@@ -5382,6 +5867,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5382
5867
  deps.asyncByDefault,
5383
5868
  );
5384
5869
  preparedChildParams = childRequest;
5870
+ if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
5385
5871
  workflowLaunchObservers.set(childRequest, (launch) => {
5386
5872
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
5387
5873
  if (step) {
@@ -5430,7 +5916,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5430
5916
  if (child.runId) workflowChildRunIds.set(key, child.runId);
5431
5917
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
5432
5918
  if (step) {
5433
- step.async = Boolean(result.details.asyncId || result.details.asyncDir);
5919
+ step.async = step.async === true || Boolean(result.details.asyncId || result.details.asyncDir);
5434
5920
  if (child.runId) step.runId = child.runId;
5435
5921
  if (child.lane) step.lane = child.lane;
5436
5922
  }
@@ -5452,7 +5938,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5452
5938
  return child;
5453
5939
  },
5454
5940
  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),
5941
+ resolveResume: (reference, _signal, index) => resolveWorkflowResume(reference, deps, ctx.sessionManager.getSessionFile() ?? null, index),
5456
5942
  steer: (key, message, options, workflowSignal) => steerWorkflowChildByKey({ state: deps.state, workflowRunId, key, message, options, signal: workflowSignal, resolveRunId: () => workflowChildRunIds.get(key) }),
5457
5943
  });
5458
5944
  const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, workflow.trace, { settled: true });
@@ -5463,20 +5949,24 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5463
5949
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, summary, producedChildOutputPaths);
5464
5950
  const resultSummary = appendWorkflowOutputWarning(summary, outputWarning);
5465
5951
  const workflowUsage = sumResultsUsage(workflowResults);
5952
+ settleWorkflowSteerInbox("complete");
5466
5953
  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);
5954
+ 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) };
5955
+ const receipt = terminalWorkflowReceipt(workflowRunId, "complete", workflow.children, workflowChildren, undefined, validHostStepNodes(status.workflowGraph), workflowResource?.provenance, workflowArgsDigest);
5956
+ delete status.workflowReceiptPath;
5469
5957
  let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
5470
5958
  try {
5471
5959
  workflowReceipt = { path: writeWorkflowReceipt(asyncDir, receipt), receipt };
5960
+ status.workflowReceiptPath = workflowReceipt.path;
5472
5961
  } catch (receiptError) {
5473
5962
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
5474
5963
  }
5475
5964
  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;
5965
+ if (pendingResultPublication && !await pendingResultPublication) return;
5476
5966
  persist();
5477
5967
  deps.refreshResultDelivery?.();
5478
5968
  persistClosed = true;
5479
- appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(status.error ? { error: status.error } : {}) });
5969
+ appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(workflowArgsDigest ? { argsDigest: workflowArgsDigest } : {}), ...(status.error ? { error: status.error } : {}) });
5480
5970
  } catch (error) {
5481
5971
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
5482
5972
  const stopped = controller.signal.aborted;
@@ -5496,10 +5986,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5496
5986
  }
5497
5987
  }
5498
5988
  const workflowState = state === "paused" ? "paused" : state === "stopped" ? "stopped" : "failed";
5989
+ settleWorkflowSteerInbox(state);
5499
5990
  const workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState, inventoryComplete: true, trace: partial.trace, children: partial.children, steps: status.steps });
5500
5991
  const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, partial.trace, { settled: true });
5501
5992
  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 });
5993
+ 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
5994
  if (pauseForDetached) {
5504
5995
  const promoted = promotePausedWorkflowIfSettled(status);
5505
5996
  if (promoted) status = promoted;
@@ -5511,19 +6002,28 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5511
6002
  const resultSummary = appendWorkflowOutputWarning(terminalSummary, outputWarning);
5512
6003
  const receiptState: WorkflowReceiptState = status.state === "complete" ? "complete" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "failed";
5513
6004
  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);
6005
+ const receipt = terminalWorkflowReceipt(workflowRunId, receiptState, partial.children, workflowChildren, terminalOutcome, validHostStepNodes(status.workflowGraph), workflowResource?.provenance, workflowArgsDigest);
6006
+ delete status.workflowReceiptPath;
5515
6007
  let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
5516
6008
  try {
5517
6009
  workflowReceipt = { path: writeWorkflowReceipt(asyncDir, receipt), receipt };
6010
+ status.workflowReceiptPath = workflowReceipt.path;
5518
6011
  } catch (receiptError) {
5519
6012
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
5520
6013
  }
5521
6014
  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;
6015
+ if (pendingResultPublication && !await pendingResultPublication) return;
5522
6016
  persist();
5523
6017
  deps.refreshResultDelivery?.();
5524
6018
  persistClosed = true;
5525
- appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(terminalOutcome ? { terminalOutcome } : {}), ...(status.error ? { error: status.error } : {}), ...(status.activityState ? { activityState: status.activityState } : {}) });
6019
+ appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(workflowArgsDigest ? { argsDigest: workflowArgsDigest } : {}), ...(terminalOutcome ? { terminalOutcome } : {}), ...(status.error ? { error: status.error } : {}), ...(status.activityState ? { activityState: status.activityState } : {}) });
5526
6020
  } finally {
6021
+ // Idempotent cleanup only: a failed result/index write must not authorize terminal status.
6022
+ try {
6023
+ settleWorkflowSteerInbox();
6024
+ } catch (error) {
6025
+ console.error(`Failed to close async workflow steer inbox '${asyncDir}':`, error);
6026
+ }
5527
6027
  persistClosed = true;
5528
6028
  deps.state.workflowControllers?.delete(workflowRunId);
5529
6029
  deps.state.workflowChildStops?.delete(workflowRunId);
@@ -5536,10 +6036,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5536
6036
  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
6037
  }, workflowFanoutBudget));
5538
6038
  }
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;
6039
+ 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
6040
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
5541
6041
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
5542
- const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, _id));
6042
+ const workflowAggregateOutputPath = resolveSingleOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, foregroundWorkflowRunId));
5543
6043
  const claimedOutputPaths = new Map<string, string>();
5544
6044
  const childOutputOverrides = new Map<string, string>();
5545
6045
  const childOutputClaimPaths = new Map<string, string>();
@@ -5549,7 +6049,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5549
6049
  const runHostCommand = workflowHostCommandRunner({
5550
6050
  workflowCwd,
5551
6051
  artifactsDir: workflowArtifactsDir,
5552
- workflowRunId: _id,
6052
+ workflowRunId: foregroundWorkflowRunId,
5553
6053
  claimedOutputPaths,
5554
6054
  producedOutputPaths: producedChildOutputPaths,
5555
6055
  ...(workflowResource ? { authorize: (key, params) => authorizeWorkflowResourceHost(workflowResource!.permit, key, params.command) } : {}),
@@ -5559,19 +6059,29 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5559
6059
  : workflowResource
5560
6060
  ? workflowResource.authority.host ? runHostCommand : undefined
5561
6061
  : publicExecution ? undefined : runHostCommand;
5562
- const workflowHostSteps = new Map<string, HostStepNodeV1>();
6062
+ const workflowHostSteps = new Map<string, HostStepNode>();
5563
6063
  let liveWorkflow: NonNullable<Details["workflow"]> = { trace: [], emits: [], console: [], ...(workflowResource ? { resource: workflowResource.provenance } : {}) };
5564
- let liveWorkflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "running", inventoryComplete: false });
6064
+ const childProgress = new Map<string, ReturnType<typeof workflowChildProgress>>();
6065
+ let activityTimer: ReturnType<typeof setTimeout> | undefined;
6066
+ let lastProgressAt = 0;
6067
+ let workflowProgressClosed = false;
5565
6068
  const workflowDeadlineAt = timeout === undefined ? undefined : Date.now() + timeout;
5566
6069
  const workflowCapabilityCeiling = intersectSubagentCapabilityCeilings(requestParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(resolveCurrentSessionId(ctx.sessionManager)));
5567
6070
  const sendWorkflowProgress = () => {
5568
- const update = workflowChatProgressUpdate(_id, chatProgress, liveWorkflow, liveWorkflowChildren, workflowPreflight);
5569
- if (update) onUpdate?.(update);
6071
+ if (workflowProgressClosed) return;
6072
+ if (activityTimer) clearTimeout(activityTimer);
6073
+ activityTimer = undefined;
6074
+ lastProgressAt = Date.now();
6075
+ const liveWorkflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "running", inventoryComplete: false, trace: liveWorkflow.trace, progress: childProgress });
6076
+ onUpdate?.(workflowProgressUpdate(foregroundWorkflowRunId, chatProgress, liveWorkflow, liveWorkflowChildren, workflowPreflight));
5570
6077
  };
5571
6078
  try {
5572
6079
  const workflow = await runWorkflowScript({
5573
6080
  script: requestParams.workflowScript,
5574
- ...(delegatedWorkflowPermit ? { oneUsePermit: { claim: (key: string) => claimWorkflowChildPermit(delegatedWorkflowPermit, _id, key) } } : {}),
6081
+ ...(workflowArgs ? { args: workflowArgs } : {}),
6082
+ workflowRunId: foregroundWorkflowRunId,
6083
+ processCwd: ctx.cwd,
6084
+ ...(delegatedWorkflowPermit ? { oneUsePermit: { claim: (key: string) => claimWorkflowChildPermit(delegatedWorkflowPermit, foregroundWorkflowRunId, key) } } : {}),
5575
6085
  globalConcurrencyLimit: requestParams.globalConcurrencyLimit ?? deps.config.globalConcurrencyLimit,
5576
6086
  timeoutMs: timeout,
5577
6087
  signal,
@@ -5584,11 +6094,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5584
6094
  const projectedTrace = annotateWorkflowPreflightTrace(trace, workflowPreflight);
5585
6095
  const preflightWarnings = workflowPreflightWarnings(workflowPreflight, trace);
5586
6096
  liveWorkflow = { ...liveWorkflow, trace: projectedTrace, ...(preflightWarnings.length ? { preflightWarnings } : {}) };
5587
- liveWorkflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "running", inventoryComplete: false, trace });
6097
+ for (const entry of trace) {
6098
+ if (entry.operation === "run" && ["completed", "failed", "stopped", "detached"].includes(entry.state)) childProgress.delete(entry.key);
6099
+ }
5588
6100
  sendWorkflowProgress();
5589
6101
  },
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 });
6102
+ admit: async (calls, admissionSignal) => {
6103
+ await preflightWorkflowWorktrees({ workflowDefaults: workflowChildDefaults, defaultWorktree: deps.config.worktree, calls, ctxCwd: ctx.cwd, signal: admissionSignal, deadlineAt: workflowDeadlineAt });
6104
+ 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
6105
  if (outputClaims.error) throw new Error(outputClaims.error);
5593
6106
  claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
5594
6107
  if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
@@ -5608,7 +6121,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5608
6121
  if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state, { state: "partial", reason: "budget_exhausted" });
5609
6122
  const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
5610
6123
  const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
5611
- recordMissionWorkflowChild(missionBinding, _id, key, {
6124
+ recordMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, {
5612
6125
  status: "running",
5613
6126
  ...(typeof childParams.agent === "string" && childParams.agent.trim() ? { agent: childParams.agent.trim() } : {}),
5614
6127
  ...(childLabel ? { label: childLabel } : {}),
@@ -5616,13 +6129,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5616
6129
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
5617
6130
  });
5618
6131
  let preparedChildParams: SubagentParamsLike | undefined;
5619
- const result = await runMissionWorkflowChild(missionBinding, _id, key, childPhase, () => {
6132
+ const result = await runMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, childPhase, () => {
5620
6133
  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 },
6134
+ { ...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
6135
  missionBinding,
5623
6136
  deps.asyncByDefault,
5624
6137
  );
5625
6138
  preparedChildParams = childRequest;
6139
+ if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
5626
6140
  if (delegatedWorkflowPermit) {
5627
6141
  if (childRequest.async !== false) throw new Error("Workflow child permit supports one foreground child only.");
5628
6142
  const childCwd = resolveRequestedCwd(workflowCwd, childRequest.cwd);
@@ -5630,9 +6144,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5630
6144
  ? resolveAgentName(childRequest.agent, discoverWorkflowAgents(childCwd, resolveExecutionAgentScope(childRequest.agentScope)).agents).agent
5631
6145
  : undefined;
5632
6146
  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 } });
6147
+ workflowPermitContexts.set(childRequest, { child: { permit: delegatedWorkflowPermit, workflowRunId: foregroundWorkflowRunId, childKey: key } });
5634
6148
  }
5635
- workflowLaunchObservers.set(childRequest, (launch) => recordMissionWorkflowChild(missionBinding, _id, key, {
6149
+ workflowLaunchObservers.set(childRequest, (launch) => recordMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, {
5636
6150
  status: "running",
5637
6151
  agent: launch.agent,
5638
6152
  ...(launch.sessionFile ? { sessionPath: launch.sessionFile } : {}),
@@ -5640,8 +6154,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5640
6154
  return execute(randomUUID(), childRequest, workflowSignal, (update) => {
5641
6155
  const progress = update.details.progress?.[0];
5642
6156
  if (!progress) return;
6157
+ if (onUpdate && !workflowProgressClosed) {
6158
+ if (progress.status === "running") childProgress.set(key, workflowChildProgress(progress));
6159
+ else childProgress.delete(key);
6160
+ if (!activityTimer) {
6161
+ const delay = 100 - (Date.now() - lastProgressAt);
6162
+ if (delay <= 0) sendWorkflowProgress();
6163
+ else activityTimer = setTimeout(sendWorkflowProgress, delay);
6164
+ }
6165
+ }
5643
6166
  const progressStatus = progress.status === "completed" ? "completed" : progress.status === "failed" ? "failed" : "running";
5644
- recordMissionWorkflowChild(missionBinding, _id, key, {
6167
+ recordMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, {
5645
6168
  status: progressStatus,
5646
6169
  heartbeat: { status: progressStatus, ...(childPhase ? { phase: childPhase } : {}) },
5647
6170
  });
@@ -5655,7 +6178,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5655
6178
  const child = workflowChildResult(key, result, preparedChildParams ?? childParams, deps.state);
5656
6179
  if (child.runId) workflowChildRunIds.set(key, child.runId);
5657
6180
  const childStatus = missionWorkflowChildStatus(result);
5658
- recordMissionWorkflowChild(missionBinding, _id, key, {
6181
+ recordMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, {
5659
6182
  status: childStatus,
5660
6183
  ...(child.runId ? { runId: child.runId } : {}),
5661
6184
  ...(result.details.results[0]?.agent ? { agent: result.details.results[0].agent } : {}),
@@ -5667,13 +6190,13 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5667
6190
  return child;
5668
6191
  },
5669
6192
  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) }),
6193
+ resolveResume: (reference, _signal, index) => resolveWorkflowResume(reference, deps, ctx.sessionManager.getSessionFile() ?? null, index),
6194
+ steer: (key, message, options, workflowSignal) => steerWorkflowChildByKey({ state: deps.state, workflowRunId: foregroundWorkflowRunId, key, message, options, signal: workflowSignal, resolveRunId: () => workflowChildRunIds.get(key) }),
5672
6195
  });
5673
6196
  const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, workflow.trace, { settled: true });
5674
6197
  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);
6198
+ const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children });
6199
+ const receipt = terminalWorkflowReceipt(foregroundWorkflowRunId, "complete", workflow.children, workflowChildren, undefined, [...workflowHostSteps.values()], workflowResource?.provenance, workflowArgsDigest);
5677
6200
  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
6201
  const sections = [
5679
6202
  ...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []),
@@ -5691,11 +6214,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5691
6214
  const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
5692
6215
  return attachWorkflowMission(withRunFanoutBudget({
5693
6216
  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 }),
6217
+ 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
6218
  }, workflowFanoutBudget));
5696
6219
  } catch (error) {
5697
6220
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
5698
- const text = workflowFailureMessage(error, _id, partial.children);
6221
+ const text = workflowFailureMessage(error, foregroundWorkflowRunId, partial.children);
5699
6222
  const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, partial.trace, { settled: true });
5700
6223
  const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
5701
6224
  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 +6235,39 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5712
6235
  const workflowText = sections.join("\n\n");
5713
6236
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText, producedChildOutputPaths);
5714
6237
  const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
5715
- const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "failed", inventoryComplete: true, trace: partial.trace, children: partial.children });
6238
+ const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "failed", inventoryComplete: true, trace: partial.trace, children: partial.children });
5716
6239
  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);
6240
+ const receipt = terminalWorkflowReceipt(foregroundWorkflowRunId, "failed", partial.children, workflowChildren, terminalOutcome, [...workflowHostSteps.values()], workflowResource?.provenance, workflowArgsDigest);
5718
6241
  return attachWorkflowMission(withRunFanoutBudget({
5719
6242
  content: [{ type: "text", text: displayText }],
5720
6243
  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 }),
6244
+ 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
6245
  }, workflowFanoutBudget));
6246
+ } finally {
6247
+ workflowProgressClosed = true;
6248
+ if (activityTimer) clearTimeout(activityTimer);
6249
+ childProgress.clear();
5723
6250
  }
5724
6251
  }
5725
6252
  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 };
6253
+ // With a machine, cwd names a directory on that machine: keep it out of every local path resolution.
6254
+ // Placement can also come from the agent's frontmatter or settings override, so the agent is resolved first (discovery is fingerprint-cached).
6255
+ const placedByAgent = (): boolean => {
6256
+ if (directParams.machine !== undefined || directParams.cwd === undefined || typeof directParams.agent !== "string") return false;
6257
+ try {
6258
+ return resolveAgentName(directParams.agent, deps.discoverAgents(ctx.cwd, resolveExecutionAgentScope(directParams.agentScope)).agents).agent?.machine !== undefined;
6259
+ } catch {
6260
+ return false; // Discovery errors surface from the launch path itself.
6261
+ }
6262
+ };
6263
+ const remotePlacement = directParams.action === undefined && (directParams.machine !== undefined || placedByAgent());
6264
+ const requestedCwd = remotePlacement ? undefined : directParams.cwd;
6265
+ const requestCwd = remotePlacement ? ctx.cwd : resolveRequestedCwd(ctx.cwd, directParams.cwd);
6266
+ const paramsWithResolvedCwd = directParams.cwd === undefined
6267
+ ? directParams
6268
+ : remotePlacement
6269
+ ? omitUndefinedProperties({ ...directParams, cwd: undefined, machineCwd: directParams.cwd })
6270
+ : { ...directParams, cwd: requestCwd };
5729
6271
  const action = paramsWithResolvedCwd.action;
5730
6272
  let requestSessionId = "";
5731
6273
  let requestPiSessionId: string | undefined;
@@ -5790,10 +6332,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5790
6332
  }
5791
6333
  if (!confirmed) return { content: [{ type: "text", text: "Worktree discard canceled; preserved worktrees were not changed." }], details: { mode: "management", results: [] } };
5792
6334
  try {
5793
- const discarded = discardPreservedWorktrees(
5794
- path.isAbsolute(paramsWithResolvedCwd.handoffPath) ? paramsWithResolvedCwd.handoffPath : path.resolve(requestCwd, paramsWithResolvedCwd.handoffPath),
6335
+ const manifestPath = path.isAbsolute(paramsWithResolvedCwd.handoffPath) ? paramsWithResolvedCwd.handoffPath : path.resolve(requestCwd, paramsWithResolvedCwd.handoffPath);
6336
+ const discarded = await withWorktreeTransaction(() => discardPreservedWorktrees(
6337
+ manifestPath,
5795
6338
  { kind: decision === "confirm" ? "confirmed" : "policy", ...(deps.config.authorityPolicy ? { policy: deps.config.authorityPolicy } : {}) },
5796
- );
6339
+ ));
5797
6340
  return { content: [{ type: "text", text: discarded.text }], details: { mode: "management", results: [] } };
5798
6341
  } catch (error) {
5799
6342
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
@@ -5823,6 +6366,24 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5823
6366
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
5824
6367
  }
5825
6368
  }
6369
+ const policyAction = action === "stop" ? "stopRun" : action === "steer" ? "steerRun" : action === "schedule.create" ? "scheduleCreate" : action === "inspector.open" ? "inspectorOpen" : action === "project.open" ? "projectOpen" : undefined;
6370
+ if (policyAction) {
6371
+ // Child-safe mode is a hard capability boundary; the policy is an operator
6372
+ // preference. Refuse first, so the gate never prompts for an action that is
6373
+ // going to be rejected anyway and never masks the more specific reason.
6374
+ if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
6375
+ return { content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }], isError: true, details: { mode: "management", results: [] } };
6376
+ }
6377
+ const decision = resolveAuthorityDecision({ action: policyAction, ...(deps.config.authorityPolicy === undefined ? {} : { policy: deps.config.authorityPolicy }) });
6378
+ if (decision === "forbid") {
6379
+ return { content: [{ type: "text", text: `Authority policy forbids action '${action}'.` }], isError: true, details: { mode: "management", results: [] } };
6380
+ }
6381
+ if (decision === "confirm") {
6382
+ 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: [] } };
6383
+ const confirmed = await ctx.ui.confirm(`Authorize subagent ${action}?`, `Authority policy requires confirmation before '${action}'.`);
6384
+ if (!confirmed) return { content: [{ type: "text", text: `Action '${action}' canceled; authority was not granted.` }], details: { mode: "management", results: [] } };
6385
+ }
6386
+ }
5826
6387
  if ((HERDR_PROJECT_PANE_ACTIONS as readonly string[]).includes(action)) {
5827
6388
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
5828
6389
  return { content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }], isError: true, details: { mode: "management", results: [] } };
@@ -5830,16 +6391,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5830
6391
  deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
5831
6392
  return handleHerdrProjectPaneAction(action as (typeof HERDR_PROJECT_PANE_ACTIONS)[number], paramsWithResolvedCwd, { cwd: requestCwd, state: deps.state, signal });
5832
6393
  }
5833
- if ((HERDR_INSPECTOR_ACTIONS as readonly string[]).includes(action)) {
6394
+ if ((INSPECTOR_ACTIONS as readonly string[]).includes(action)) {
5834
6395
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
5835
6396
  return { content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }], isError: true, details: { mode: "management", results: [] } };
5836
6397
  }
5837
6398
  deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
5838
- return handleHerdrInspectorAction(action as (typeof HERDR_INSPECTOR_ACTIONS)[number], paramsWithResolvedCwd, {
6399
+ return handleInspectorAction(action as (typeof INSPECTOR_ACTIONS)[number], paramsWithResolvedCwd, {
5839
6400
  state: deps.state,
5840
6401
  cwd: requestCwd,
5841
6402
  ...(deps.config.missions ? { missions: deps.config.missions } : {}),
5842
6403
  ...(deps.config.authorityPolicy ? { authorityPolicy: deps.config.authorityPolicy } : {}),
6404
+ plugins: createBuiltinInspectorPlugins(),
5843
6405
  signal,
5844
6406
  });
5845
6407
  }
@@ -5858,18 +6420,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5858
6420
  ...(currentSessionId ? { currentSessionId } : {}),
5859
6421
  });
5860
6422
  }
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
6423
  if ((WATCHDOG_TOOL_ACTIONS as readonly string[]).includes(action)) {
5874
6424
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
5875
6425
  return {
@@ -6062,7 +6612,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6062
6612
  }
6063
6613
  return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots, abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })));
6064
6614
  }
6065
- if (paramsWithResolvedCwd.view === "fleet") {
6615
+ if (paramsWithResolvedCwd.view === "fleet" || paramsWithResolvedCwd.view === "transcript") {
6066
6616
  return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots, abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })));
6067
6617
  }
6068
6618
  if (targetRunId) {
@@ -6071,12 +6621,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6071
6621
  if (resolved?.kind === "foreground") {
6072
6622
  const foreground = getForegroundControl(deps.state, resolved.id);
6073
6623
  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
6624
  return withBudget(foregroundStatusResult(foreground));
6081
6625
  }
6082
6626
  }
@@ -6086,13 +6630,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6086
6630
  }
6087
6631
  } else if (!hasDirectoryTarget) {
6088
6632
  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
- }
6633
+ if (foreground) return withBudget(foregroundStatusResult(foreground));
6096
6634
  }
6097
6635
  return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots, abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })));
6098
6636
  }
@@ -6113,9 +6651,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6113
6651
  const runId = location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir);
6114
6652
  const directoryStatus = location.asyncDir ? readStatus(location.asyncDir) : null;
6115
6653
  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 });
6654
+ return steerWorkflowRun({ state: deps.state, runId, asyncDir: location.asyncDir!, message, mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode), index: paramsWithResolvedCwd.index, signal });
6119
6655
  }
6120
6656
  if (location.asyncDir) {
6121
6657
  const unsupported = externalRunnerControlError(location.asyncDir, "steer");
@@ -6123,6 +6659,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6123
6659
  }
6124
6660
  return steerAsyncRun(compactOptional<Parameters<typeof steerAsyncRun>[0]>({
6125
6661
  state: deps.state,
6662
+ findPendingAsks: deps.findPendingAsks,
6126
6663
  runId,
6127
6664
  message,
6128
6665
  mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode),
@@ -6160,9 +6697,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6160
6697
  if (resolved?.kind !== "async") return { content: [{ type: "text", text: `No async run found for '${targetRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
6161
6698
  const resolvedStatus = resolved.location.asyncDir ? readStatus(resolved.location.asyncDir) : null;
6162
6699
  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 });
6700
+ return steerWorkflowRun({ state: deps.state, runId: resolved.id, asyncDir: resolved.location.asyncDir!, message, mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode), index: paramsWithResolvedCwd.index, signal });
6166
6701
  }
6167
6702
  if (resolved.location.asyncDir) {
6168
6703
  const unsupported = externalRunnerControlError(resolved.location.asyncDir, "steer");
@@ -6170,6 +6705,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6170
6705
  }
6171
6706
  return steerAsyncRun(compactOptional<Parameters<typeof steerAsyncRun>[0]>({
6172
6707
  state: deps.state,
6708
+ findPendingAsks: deps.findPendingAsks,
6173
6709
  runId: resolved.id,
6174
6710
  message,
6175
6711
  mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode),
@@ -6371,6 +6907,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6371
6907
  config: deps.config,
6372
6908
  currentSessionId: deps.state.currentSessionId ?? ctx.sessionManager.getSessionId() ?? undefined,
6373
6909
  runtimeAgentOwner: deps.pi,
6910
+ onAgentsChanged: deps.onAgentsChanged,
6374
6911
  });
6375
6912
  }
6376
6913
 
@@ -6394,6 +6931,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6394
6931
  const normalized = normalizeRepeatedParallelCounts(paramsWithResolvedCwd);
6395
6932
  if (normalized.error) return normalized.error;
6396
6933
  const normalizedParams = normalized.params!;
6934
+ const outputSchemaError = validateLaunchOutputSchemaOverrides(normalizedParams);
6935
+ if (outputSchemaError) return buildRequestedModeError(normalizedParams, outputSchemaError);
6397
6936
 
6398
6937
  let effectiveParams = applyForceTopLevelAsyncOverride(
6399
6938
  normalizedParams,
@@ -6483,65 +7022,20 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6483
7022
 
6484
7023
  let forkSessionFileForIndex: (idx?: number) => string | undefined = () => undefined;
6485
7024
  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>();
7025
+ // Forked children keep their requested thinking level. Signed Anthropic thinking
7026
+ // blocks are stripped from the inherited transcript by the resolver (they are bound
7027
+ // to the parent session), which is not a reason to disable the child's own reasoning.
6490
7028
  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
7029
  const pruneSession = contextPolicy.usesFork && deps.config.forkContext?.mode === "pruned"
6536
7030
  ? await createPrunedForkSessionWriter(ctx, deps.config.forkContext, signal)
6537
7031
  : undefined;
6538
- const forkContextResolver = createForkContextResolver(ctx.sessionManager, contextPolicy.usesFork ? "fork" : undefined, {
6539
- forceThinkingOffForIndex: (index) => forkThinkingRequirements.get(index) ?? true,
6540
- ...(pruneSession ? { pruneSession } : {}),
6541
- });
7032
+ const forkContextResolver = createForkContextResolver(
7033
+ ctx.sessionManager,
7034
+ contextPolicy.usesFork ? "fork" : undefined,
7035
+ pruneSession ? { pruneSession } : {},
7036
+ );
6542
7037
  prepareForkSessionForIndex = forkContextResolver.prepareSessionForIndex;
6543
7038
  forkSessionFileForIndex = forkContextResolver.sessionFileForIndex;
6544
- forkThinkingOverrideForIndex = forkContextResolver.thinkingOverrideForIndex;
6545
7039
  } catch (error) {
6546
7040
  return toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);
6547
7041
  }
@@ -6622,7 +7116,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6622
7116
 
6623
7117
  let sessionRoot: string;
6624
7118
  if (effectiveParams.sessionDir) {
6625
- sessionRoot = path.resolve(deps.expandTilde(effectiveParams.sessionDir));
7119
+ // An explicit sessionDir is a root keyed by this launch's run id so
7120
+ // concurrent children resolve distinct per-child session files.
7121
+ sessionRoot = path.join(path.resolve(deps.expandTilde(effectiveParams.sessionDir)), runId);
6626
7122
  } else {
6627
7123
  const baseSessionRoot = deps.config.defaultSessionDir
6628
7124
  ? path.resolve(deps.expandTilde(deps.config.defaultSessionDir))
@@ -6642,23 +7138,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6642
7138
  }
6643
7139
  const sessionDirForIndex = (idx?: number) =>
6644
7140
  path.join(sessionRoot, `run-${idx ?? 0}`);
6645
- const forkSessionFileForTask: ForkSessionFileForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent, modelOrigin) => {
7141
+ const forkSessionFileForTask: ForkSessionFileForTask = (agentName, idx = 0) => {
6646
7142
  if (!shouldForkAgent(contextPolicy, agentName)) return undefined;
6647
- prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin);
6648
7143
  return forkSessionFileForIndex(idx);
6649
7144
  };
6650
- const prepareForkSessionForTask: PrepareForkSessionForTask = async (agentName, idx = 0, modelOverride, modelOverrideFromParent, modelOrigin) => {
7145
+ const prepareForkSessionForTask: PrepareForkSessionForTask = async (agentName, idx = 0) => {
6651
7146
  if (!shouldForkAgent(contextPolicy, agentName)) return;
6652
- prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin);
6653
7147
  await prepareForkSessionForIndex(idx);
6654
7148
  };
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
- };
7149
+ const thinkingOverrideForTask: ThinkingOverrideForTask = () => delegatedThinkingOverride;
6662
7150
  const childSessionFileForTask: ForkSessionFileForTask = (agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin) =>
6663
7151
  forkSessionFileForTask(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin) ?? path.join(sessionDirForIndex(idx), "session.jsonl");
6664
7152
  const childSessionFileForIndex = (idx?: number) =>
@@ -6747,7 +7235,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6747
7235
  sessionDirForIndex,
6748
7236
  sessionFileForIndex: childSessionFileForIndex,
6749
7237
  sessionFileForTask: childSessionFileForTask,
6750
- thinkingOverrideForTask: forkThinkingOverrideForTask,
7238
+ thinkingOverrideForTask,
6751
7239
  artifactConfig,
6752
7240
  artifactsDir,
6753
7241
  backgroundRequestedWhileClarifying,
@@ -6760,6 +7248,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6760
7248
  timeoutMs: foregroundTimeout.timeoutMs,
6761
7249
  toolBudget: runToolBudget.toolBudget,
6762
7250
  usageBudget: usageBudget.budget,
7251
+ inheritedUsageBudget,
6763
7252
  allowZeroToolBudget,
6764
7253
  configToolBudget: configToolBudget.toolBudget,
6765
7254
  configToolTimeoutMs: deps.config.toolTimeoutMs,
@@ -6860,7 +7349,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6860
7349
  availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
6861
7350
  currentProvider: requestParentModel?.provider,
6862
7351
  modelScope,
6863
- thinkingOverrideForTask: forkThinkingOverrideForTask,
7352
+ thinkingOverrideForTask,
6864
7353
  dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
6865
7354
  });
6866
7355
  } catch (error) {
@@ -6954,7 +7443,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6954
7443
  const asyncResult = await runAsyncPath(execData, deps);
6955
7444
  if (asyncResult) {
6956
7445
  asyncLaunchFailed = asyncResult.isError === true;
6957
- return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(asyncResult, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget));
7446
+ return attachMission(withRunFanoutBudget(withResolvedContext(asyncResult, contextPolicy.contextSummary), runFanoutBudget));
6958
7447
  }
6959
7448
  if (foregroundControl) {
6960
7449
  writeNestedForegroundEvent("subagent.nested.started");
@@ -6964,11 +7453,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6964
7453
  if (hasSingle) {
6965
7454
  const result = await runSinglePath(execData, deps);
6966
7455
  writeNestedForegroundEvent("subagent.nested.completed", result);
6967
- return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget, { annotateContent: runFanoutAnnotateContent }));
7456
+ return attachMission(withRunFanoutBudget(withResolvedContext(result, contextPolicy.contextSummary), runFanoutBudget, { annotateContent: runFanoutAnnotateContent }));
6968
7457
  }
6969
7458
  } catch (error) {
6970
7459
  asyncLaunchFailed = effectiveAsync;
6971
- const errorResult = withForkThinkingNotes(toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary), forkThinkingDowngrades);
7460
+ const errorResult = toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);
6972
7461
  if (nestedForegroundStarted) writeNestedForegroundEvent("subagent.nested.completed", errorResult);
6973
7462
  return attachMission(errorResult);
6974
7463
  } finally {
@@ -6976,7 +7465,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6976
7465
  if (activeAsyncCapacity && !activeAsyncCapacity.owner.runnerStartedAt) activeAsyncCapacity.rollback();
6977
7466
  if (foregroundControl) {
6978
7467
  settleForegroundSchedulingOwner(foregroundControl);
6979
- removeForegroundControlIfIdle(deps.state, runId);
7468
+ removeForegroundControlIfIdle(deps.state, runId, deps.trackRetainedNestedRoute);
6980
7469
  }
6981
7470
  }
6982
7471
 
@@ -7023,11 +7512,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7023
7512
  }
7024
7513
  let publicParams = normalized.params as SubagentParamsLike;
7025
7514
  if (publicParams.workflow !== undefined) {
7026
- const resolved = resolveWorkflowResource(publicParams.workflow, publicParams.args);
7515
+ const resolved = resolveWorkflowResource(publicParams.workflow, publicParams.args, ctx.sessionManager.getSessionId() ?? undefined);
7027
7516
  if (!resolved.ok) return Promise.resolve({ content: [{ type: "text", text: resolved.error }], isError: true, details: { mode: "workflow", results: [] } });
7028
7517
  const { workflow: _workflow, args: _args, ...withoutResourceInput } = publicParams;
7029
7518
  publicParams = { ...withoutResourceInput, workflowScript: resolved.resource.script };
7030
7519
  workflowResourcePermits.set(publicParams, resolved.resource.permit);
7520
+ } else if (publicParams.workflowScript !== undefined || publicParams.workflowScriptPath !== undefined) {
7521
+ const normalizedArgs = normalizeWorkflowArgs(publicParams.args);
7522
+ if ("error" in normalizedArgs) return Promise.resolve({ content: [{ type: "text", text: normalizedArgs.error }], isError: true, details: { mode: publicParams.action ? "management" : "workflow", results: [] } });
7523
+ publicParams = { ...publicParams, args: deepFreezeWorkflowArgs(normalizedArgs.args) };
7031
7524
  }
7032
7525
  const loaded = loadWorkflowScriptPath(publicParams, ctx.cwd);
7033
7526
  if (loaded.error) {
@@ -7070,16 +7563,27 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7070
7563
  ctx: ExtensionContext,
7071
7564
  ) => {
7072
7565
  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);
7566
+ const runtimeOwnerId = ctx.sessionManager.getSessionId() || null;
7567
+ let ownerExecutors = scheduledOwnerExecutors.get(runtimeOwnerId);
7568
+ if (!ownerExecutors) {
7569
+ ownerExecutors = new Map();
7570
+ scheduledOwnerExecutors.set(runtimeOwnerId, ownerExecutors);
7080
7571
  }
7081
- return ownerExecutor.executePublic(id, params, signal, undefined, ctx);
7572
+ let owner = ownerExecutors.get(ownerSessionId);
7573
+ if (!owner) {
7574
+ const state = createScheduledOwnerState(deps.state, ownerSessionId, ctx);
7575
+ owner = { state, executor: createSubagentExecutor({ ...deps, state }) };
7576
+ ownerExecutors.set(ownerSessionId, owner);
7577
+ }
7578
+ return owner.executor.executePublic(id, params, signal, undefined, ctx);
7082
7579
  };
7083
7580
 
7084
- return { execute: executeWithSingleDispatchGuard, executePublic, executeDelegated, executeScheduled };
7581
+ function* getCurrentSupervisorOwnerStates(): Iterable<SubagentState> {
7582
+ const ownerId = deps.state.supervisorOwnerSessionId;
7583
+ if (!ownerId) return;
7584
+ // File transitions remain separate entries; other runtime owners are never scanned.
7585
+ for (const owner of scheduledOwnerExecutors.get(ownerId)?.values() ?? []) yield owner.state;
7586
+ }
7587
+
7588
+ return { execute: executeWithSingleDispatchGuard, executePublic, executeDelegated, executeScheduled, getCurrentSupervisorOwnerStates };
7085
7589
  }