@xzzpig/pi-subagents 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/CHANGELOG.md +443 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +151 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +5 -4
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +370 -114
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +12 -2
  35. package/src/agents/agents.ts +919 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +31 -20
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +48 -18
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +57 -21
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +2 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +366 -128
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +45 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +189 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +676 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +468 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1172 -400
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +314 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +342 -0
  115. package/src/runs/shared/child-tool-plan.ts +540 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +142 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +38 -48
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +15 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/single-output.ts +89 -22
  149. package/src/runs/shared/structured-output.ts +49 -9
  150. package/src/runs/shared/subagent-control.ts +6 -2
  151. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  152. package/src/runs/shared/task-intent.ts +21 -7
  153. package/src/runs/shared/tool-availability.ts +18 -62
  154. package/src/runs/shared/tool-budget.ts +0 -14
  155. package/src/runs/shared/tool-timeout.ts +1 -1
  156. package/src/runs/shared/workflow-graph.ts +16 -0
  157. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  158. package/src/runs/shared/worktree.ts +571 -62
  159. package/src/shared/atomic-json.ts +3 -1
  160. package/src/shared/child-session-name.ts +46 -0
  161. package/src/shared/extension-context.ts +24 -0
  162. package/src/shared/fork-context.ts +21 -12
  163. package/src/shared/fork-session-cwd.ts +27 -0
  164. package/src/shared/formatters.ts +18 -3
  165. package/src/shared/jsonl-writer.ts +11 -0
  166. package/src/shared/launch-contract.ts +8 -1
  167. package/src/shared/pruned-fork.ts +450 -0
  168. package/src/shared/session-file-trust.ts +19 -0
  169. package/src/shared/session-tokens.ts +14 -3
  170. package/src/shared/settings.ts +19 -105
  171. package/src/shared/shortcuts.ts +17 -0
  172. package/src/shared/thinking-ceiling.ts +0 -6
  173. package/src/shared/types.ts +524 -70
  174. package/src/shared/utils.ts +60 -93
  175. package/src/shared/workflow-child-permit.ts +207 -0
  176. package/src/slash/delegation-adapters.ts +1 -9
  177. package/src/slash/delegation-request.ts +0 -4
  178. package/src/slash/prompt-template-bridge.ts +37 -1
  179. package/src/slash/slash-bridge.ts +1 -2
  180. package/src/slash/slash-commands.ts +383 -116
  181. package/src/slash/slash-live-state.ts +22 -11
  182. package/src/slash/subagents-admin.ts +29 -12
  183. package/src/tui/fleet-native-transcript.ts +4 -0
  184. package/src/tui/fleet-status.ts +217 -82
  185. package/src/tui/fleet-transcript.ts +11 -5
  186. package/src/tui/fleet.ts +54 -28
  187. package/src/tui/render-helpers.ts +31 -0
  188. package/src/tui/render.ts +1429 -163
  189. package/src/watchdog/change-signature.ts +40 -1
  190. package/src/watchdog/child-status.ts +54 -34
  191. package/src/watchdog/diff-tool.ts +77 -0
  192. package/src/watchdog/emission-guard.ts +5 -3
  193. package/src/watchdog/guidance.ts +20 -0
  194. package/src/watchdog/register-child.ts +28 -25
  195. package/src/watchdog/register-main.ts +10 -9
  196. package/src/watchdog/render.ts +4 -5
  197. package/src/watchdog/review.ts +15 -4
  198. package/src/watchdog/rules.ts +70 -0
  199. package/src/watchdog/runtime.ts +75 -92
  200. package/src/watchdog/scope.ts +0 -11
  201. package/src/watchdog/settings.ts +48 -104
  202. package/src/watchdog/turn-delta.ts +1 -1
  203. package/src/watchdog/types.ts +18 -32
  204. package/src/watchdog/warning-format.ts +0 -1
  205. package/src/workflows/chat-progress.ts +7 -3
  206. package/src/workflows/host-command.ts +235 -0
  207. package/src/workflows/scripted-workflow.ts +988 -59
  208. package/src/workflows/workflow-checklist.ts +439 -0
  209. package/src/workflows/workflow-child-summary.ts +121 -0
  210. package/src/workflows/workflow-preflight.ts +297 -0
  211. package/src/workflows/workflow-receipt.ts +232 -6
  212. package/src/workflows/workflow-resources.ts +150 -0
  213. package/src/workflows/workflow-settlement.ts +246 -0
  214. package/src/runs/shared/child-protocol.ts +0 -401
  215. package/src/runs/shared/pi-args.ts +0 -935
  216. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  217. package/src/runs/shared/turn-budget.ts +0 -98
  218. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -3,8 +3,8 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
5
5
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
6
- import { findBlockingAgentDiagnostic, resolveAgentName, type AgentConfig, type AgentDiscoveryDiagnostic, type AgentScope } from "../../agents/agents.ts";
7
- import { getArtifactsDir, getChainRunsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir } from "../../shared/artifacts.ts";
6
+ import { discoverAgents, findBlockingAgentDiagnostic, formatUnknownAgentError, resolveAgentName, unknownAgentDiagnosticContext, type AgentConfig, type AgentDiscoveryDiagnostic, type AgentScope, type UnknownAgentDiagnosticContext } from "../../agents/agents.ts";
7
+ import { getArtifactsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir } from "../../shared/artifacts.ts";
8
8
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
9
9
  import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilient-json.ts";
10
10
  import { isStorageCapacityError } from "../../shared/file-system-retry.ts";
@@ -13,7 +13,6 @@ import {
13
13
  beginForegroundChild,
14
14
  finishForegroundChild,
15
15
  foregroundSchedulingSettled,
16
- retainForegroundSchedulingOwner,
17
16
  settleForegroundSchedulingOwner,
18
17
  updateForegroundChild,
19
18
  } from "./foreground-control.ts";
@@ -24,62 +23,53 @@ import { handleManagementAction } from "../../agents/agent-management.ts";
24
23
  import { handleRefinementAction } from "../../agents/agent-refinements.ts";
25
24
  import { buildDoctorReport } from "../../extension/doctor.ts";
26
25
  import { readSubagentGuide } from "../../extension/subagent-guide.ts";
27
- import { normalizePublicSubagentExecution } from "../../extension/public-execution.ts";
26
+ import { normalizePublicSubagentExecution, validateWorkflowCapacityOverrides } from "../../extension/public-execution.ts";
28
27
  import { runSync } from "./execution.ts";
29
28
  import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/tool-actions.ts";
30
29
  import type { MainWatchdogRuntime } from "../../watchdog/runtime.ts";
31
- import { buildModelCandidates, inheritsParentModel, normalizeParentModel, resolveEffectiveSubagentModel, resolveModelCandidate, type ParentModel } from "../shared/model-fallback.ts";
30
+ import { applyWatchdogLaunchRules } from "../../watchdog/rules.ts";
31
+ import { buildModelCandidates, normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, type ModelOrigin, type ParentModel } from "../shared/model-fallback.ts";
32
32
  import { formatRetainedChildren, listRetainedChildren } from "../background/retained-children.ts";
33
33
  import { resolveModelScopesForAgent, type ModelScopeConfig } from "../shared/model-scope.ts";
34
- import { aggregateParallelOutputs } from "../shared/parallel-utils.ts";
35
34
  import { recordRun } from "../shared/run-history.ts";
36
35
  import {
37
- buildChainInstructions,
38
- writeInitialProgressFile,
39
36
  getStepAgents,
40
37
  isParallelStep,
41
38
  isDynamicParallelStep,
42
- resolveChainPath,
43
39
  resolveExistingReadPaths,
44
- resolveStepBehavior,
45
- suppressProgressForReadOnlyTask,
46
- taskDisallowsFileUpdates,
47
40
  type ChainStep,
48
41
  type DynamicParallelStep,
49
42
  type ParallelStep,
50
43
  type ParallelTaskItem,
51
- type ResolvedStepBehavior,
52
44
  type SequentialStep,
53
- type StepOverrides,
54
45
  } from "../../shared/settings.ts";
55
- import { discoverAvailableSkills, normalizeSkillInput } from "../../agents/skills.ts";
46
+ import { normalizeSkillInput } from "../../agents/skills.ts";
56
47
  import { buildAsyncRunnerSteps, DEFAULT_ASYNC_TIMEOUT_MS, executeAsyncChain, executeAsyncSingle, formatAsyncStartedMessage, isAsyncAvailable, workflowAwaitedAsyncResultPath } from "../background/async-execution.ts";
57
48
  import { updateActiveRunIndex } from "../background/active-run-index.ts";
58
49
  import { steeringReceipt } from "../background/steering.ts";
59
- import { acquireActiveAsyncCapacity, ActiveAsyncCapacityError, getActiveAsyncCapacitySnapshot, resolveMaxActiveAsyncRunsPerSession, transferActiveAsyncCapacity, type ActiveAsyncCapacityHandle } from "../background/active-async-capacity.ts";
60
- import { isScheduledRunAction, type ScheduledRunAction } from "../background/scheduled-runs.ts";
50
+ import { acquireActiveAsyncCapacity, ActiveAsyncCapacityError, getActiveAsyncCapacitySnapshot, resolveAbandonedSlotReleaseAfterMs, resolveMaxActiveAsyncRunsPerSession, transferActiveAsyncCapacity, type ActiveAsyncCapacityHandle } from "../background/active-async-capacity.ts";
51
+ import { isScheduledRunAction } from "../background/scheduled-runs.ts";
61
52
  import { enqueueChainAppendRequest, readPendingChainAppendRequests, runnerStepOutputNames } from "../background/chain-append.ts";
62
53
  import { ChainOutputValidationError, validateChainOutputBindingsWithContext } from "../shared/chain-outputs.ts";
63
- import { normalizeGateAcceptance, validateExecutionAcceptance } from "../shared/acceptance.ts";
54
+ import { normalizeGateAcceptance, resolveAcceptanceReportMode, validateExecutionAcceptance } from "../shared/acceptance.ts";
64
55
  import { canPreferFork, createForkContextResolver, forkedChildRequiresThinkingOff, resolveSubagentLaunchContext } from "../../shared/fork-context.ts";
56
+ import { createPrunedForkSessionWriter } from "../../shared/pruned-fork.ts";
65
57
  import { resolveCurrentSessionId } from "../../shared/session-identity.ts";
66
58
  import { currentCompletionOwnerId } from "../../shared/completion-owner.ts";
67
59
  import { applyIntercomBridgeToAgent, INTERCOM_BRIDGE_MARKER, resolveIntercomBridge, resolveIntercomSessionTarget, resolveSubagentIntercomTarget, type IntercomBridgeState } from "../../intercom/intercom-bridge.ts";
68
60
  import { formatControlIntercomMessage, formatControlNoticeMessage, resolveControlConfig, shouldNotifyControlEvent } from "../shared/subagent-control.ts";
69
- import { resolveTurnBudgetConfig } from "../shared/turn-budget.ts";
70
61
  import { formatSpawnBudget, getSpawnBudgetSnapshot, grantSpawnBudget, preflightSpawnBudget, preflightSpawnBudgetGrant, reserveSpawnBudget } from "../shared/spawn-budget.ts";
71
- import { claimRunFanoutBatch, claimRunFanoutBatchWithCommit, createRunFanoutBudget, decodeRunFanoutBudgetDescriptor, formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor, RunFanoutLimitError, RUN_FANOUT_BUDGET_ENV, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
62
+ import { claimRunFanoutBatch, claimRunFanoutBatchWithCommit, createRunFanoutBudget, formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor, RunFanoutLimitError, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
72
63
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
73
64
  import { usageBudgetExceededMessage, usageBudgetState, validateUsageBudgetConfig } from "../shared/usage-budget.ts";
74
65
  import { intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
75
66
  import { isAgentContractV1 } from "../shared/agent-contract.ts";
76
67
  import { normalizeExtensionBindings, type ExtensionBindings } from "../shared/extension-bindings.ts";
77
- import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
78
- import { cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
79
- import { compactForegroundDetails, getSingleResultOutput, mapConcurrent, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage } from "../../shared/utils.ts";
68
+ import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, outputPathMappingFromTask, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
69
+ import { assertJsonSchemaObject, cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
70
+ import { compactForegroundDetails, getSingleResultOutput, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage, toAgentToolUsage } from "../../shared/utils.ts";
80
71
  import { createTaskMutationArbiter } from "../shared/llm-intent-arbiter.ts";
81
- import { DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore } from "../shared/parallel-utils.ts";
82
- import { discardPreservedWorktrees, formatParallelHandoffError, formatParallelHandoffReference, parallelHandoffPath, writeParallelHandoffGroup, writePendingParallelHandoff } from "../shared/parallel-handoff.ts";
72
+ import { discardPreservedWorktrees, formatParallelHandoffError, formatParallelHandoffReference, formatStoredParallelHandoffCleanup, parallelHandoffPath, readParallelHandoffManifest, recordParallelHandoffMerge, recordParallelHandoffSupersession, writeParallelHandoffGroup, writePendingParallelHandoff } from "../shared/parallel-handoff.ts";
83
73
  import { summarizeContextModes, type ContextMode, type ContextSummary } from "../shared/context-mode.ts";
84
74
  import {
85
75
  attachNestedChildrenToResultChildren,
@@ -94,11 +84,8 @@ import { deliverInterruptRequest, readRevivalBriefs, requestAsyncSteer, type Ste
94
84
  import { updateSteeringTarget, waitForSteeringAction } from "../background/steering.ts";
95
85
  import { canQueueRetainedAsyncFollowUp, steerAsyncRun } from "./async-steering-action.ts";
96
86
  import {
97
- removeWorkflowForegroundSteeringRoute,
98
87
  resolveWorkflowForegroundSteeringTarget,
99
88
  steerWorkflowForegroundTarget,
100
- workflowForegroundSteeringDir,
101
- workflowForegroundSteeringLaunchOptions,
102
89
  } from "./workflow-foreground-steering.ts";
103
90
  import { stopAsyncRun } from "./async-stop-action.ts";
104
91
  import { dismissRecoveredWorkflow } from "./async-dismiss-action.ts";
@@ -106,13 +93,15 @@ import { promotePausedWorkflowIfSettled, reconcileDetachedWorkflowChildCompletio
106
93
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
107
94
  import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
108
95
  import { resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
109
- import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, resolveInheritedNestedRouteFromEnv, resolveNestedAsyncDir, resolveNestedParentAddressFromEnv, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedRunResolutionScope } from "../shared/nested-events.ts";
96
+ import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, inheritedNestedParentAddressOf, inheritedNestedRouteOf, resolveNestedAsyncDir, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedParentAddress, type NestedRoute, type NestedRunResolutionScope } from "../shared/nested-events.ts";
97
+ import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
110
98
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
111
99
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
112
- import { isStoppableAsyncStatusStep, resolveAsyncStatusChild } from "../shared/child-identity.ts";
100
+ import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, stopStoppableAsyncStatusChildren } from "../shared/child-identity.ts";
113
101
  import { inspectSubagentStatus } from "../background/run-status.ts";
114
102
  import { getExternalJobProvider } from "../../api/external-job-provider.ts";
115
103
  import { externalJobFollowUpRequestDigest, externalJobFollowUpRequestId, externalJobFollowUpRunId, externalJobPromptDigest, externalJobStableJson } from "../shared/external-job-runner.ts";
104
+ import { externalCliReceiptMetadata, normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
116
105
  import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.ts";
117
106
  import { handleMissionAction, MISSION_ACTIONS } from "../../missions/actions.ts";
118
107
  import { attachMissionToLaunchResult, prepareMissionLaunch, writeMissionAsyncBinding, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
@@ -122,18 +111,33 @@ import { createMissionWorkflowState } from "../../missions/workflow-state.ts";
122
111
  import { resolveAuthorityDecision } from "../../policy/authority.ts";
123
112
  import { handleHerdrInspectorAction, HERDR_INSPECTOR_ACTIONS } from "../../inspectors/herdr/actions.ts";
124
113
  import { handleHerdrProjectPaneAction, HERDR_PROJECT_PANE_ACTIONS } from "../../inspectors/herdr/project-panes.ts";
125
- import { previewSimpleWorkflowRun, runWorkflowScript, WorkflowScriptError, type WorkflowReceiptResumeReference, type WorkflowScriptChildResult, type WorkflowSteerOptions, type WorkflowSteerResult } from "../../workflows/scripted-workflow.ts";
114
+ import { previewSimpleWorkflowRun, runWorkflowScript, validateWorkflowScript, WorkflowScriptError, type WorkflowLanePlan, type WorkflowReceiptResumeReference, type WorkflowScriptChildResult, type WorkflowScriptTraceEntry, type WorkflowSteerOptions, type WorkflowSteerResult } from "../../workflows/scripted-workflow.ts";
115
+ import { executeWorkflowHostCommand, resolveWorkflowHostOutputClaimPath, type WorkflowHostCommandParams, type WorkflowHostCommandResult } from "../../workflows/host-command.ts";
126
116
  import { buildWorkflowReceipt, resolveWorkflowReceiptResumeEntry, writeWorkflowReceipt, type WorkflowReceipt, type WorkflowReceiptState } from "../../workflows/workflow-receipt.ts";
117
+ import { upsertHostStep, validHostStepNodes } from "../shared/host-step-status.ts";
118
+ import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
119
+ import { parseWorkflowChildSummary, workflowChildSummary } from "../../workflows/workflow-child-summary.ts";
127
120
  import { resolveWorkflowChatProgress, type WorkflowChatProgressProjection } from "../../workflows/chat-progress.ts";
121
+ import { annotateWorkflowPreflightTrace, formatWorkflowPreflight, formatWorkflowPreflightWarnings, normalizeWorkflowPreflight, workflowPreflightWarnings } from "../../workflows/workflow-preflight.ts";
122
+ import {
123
+ authorizeWorkflowResourceHost,
124
+ claimWorkflowChildPermit,
125
+ consumeWorkflowResourcePermit,
126
+ validateWorkflowChildPermitRoot,
127
+ type WorkflowChildPermit,
128
+ type WorkflowChildPermitContext,
129
+ type WorkflowResourceAuthority,
130
+ type WorkflowResourcePermit,
131
+ } from "../../shared/workflow-child-permit.ts";
132
+ import { resolveWorkflowResource } from "../../workflows/workflow-resources.ts";
128
133
  import {
129
134
  cleanupWorktrees,
130
135
  createWorktrees,
131
136
  diffWorktrees,
132
- findWorktreeTaskCwdConflict,
133
137
  formatWorktreeDiffSummary,
134
- formatWorktreeTaskCwdConflict,
135
138
  type WorktreeSetup,
136
139
  } from "../shared/worktree.ts";
140
+ import { createWorktreeCleanupPlan, formatWorktreeCleanupPlan } from "../shared/worktree-cleanup-plan.ts";
137
141
  import {
138
142
  type AgentProgress,
139
143
  type AsyncJobState,
@@ -146,23 +150,33 @@ import {
146
150
  type ControlEvent,
147
151
  type Details,
148
152
  type ExtensionConfig,
153
+ type ForegroundResumeChild,
154
+ type ForegroundChildSessionControls,
155
+ type ForegroundSteerInput,
156
+ type ForegroundSteerOutcome,
149
157
  type ForegroundRunControl,
158
+ type HostStepNodeV1,
150
159
  type IntercomBridgeConfig,
151
160
  type IntercomEventBus,
152
161
  type JsonSchemaObject,
153
162
  type MaxOutputConfig,
154
163
  type NestedRouteInfo,
155
164
  type NestedRunSummary,
165
+ type OutputMode,
156
166
  type ResolvedControlConfig,
157
- type ResolvedTurnBudget,
158
167
  type ResolvedToolBudget,
159
168
  type RunFanoutBudgetDescriptor,
160
169
  type SteeringRecoveryDescriptor,
161
170
  type SingleResult,
162
171
  type SubagentChildStatusEvent,
163
172
  type ToolBudgetConfig,
164
- type TurnBudgetConfig,
173
+ type Usage,
165
174
  type UsageBudgetConfig,
175
+ type WorkflowResourceProvenanceV1,
176
+ type WorkflowGraphNode,
177
+ type WorkflowGraphSnapshot,
178
+ type WorkflowNodeStatus,
179
+ type WorkflowTerminalOutcome,
166
180
  type SubagentRunMode,
167
181
  type SubagentState,
168
182
  DIRS,
@@ -173,18 +187,21 @@ import {
173
187
  SUBAGENT_CONTROL_INTERCOM_EVENT,
174
188
  SUBAGENT_FOREGROUND_COMPLETE_EVENT,
175
189
  checkSubagentDepth,
176
- resolveTopLevelParallelConcurrency,
177
- resolveTopLevelParallelMaxTasks,
178
190
  resolveChildMaxSubagentDepth,
179
191
  resolveCurrentMaxSubagentDepth,
180
192
  resolveMaxSubagentSpawnsPerRun,
181
193
  wrapForkTask,
182
194
  type ScheduleOrigin,
183
195
  } from "../../shared/types.ts";
196
+ import { deriveChildSessionName } from "../../shared/child-session-name.ts";
184
197
 
185
- const MUTATING_MANAGEMENT_ACTIONS = new Set(["create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "refine", "refine.rollback", "dismiss", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
198
+ const MUTATING_MANAGEMENT_ACTIONS = new Set(["create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "worktree.cleanup", "lane.recordMerge", "lane.recordSupersession", "refine", "refine.rollback", "dismiss", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
186
199
  const DESTRUCTIVE_MANAGEMENT_ACTIONS = new Set(["delete", "eject", "disable", "reset", "mission.close", "worktree.discard", "refine.rollback", "inspector.close", "project.close", "stop", "interrupt", "schedule.delete"]);
187
200
 
201
+ function resolveSteerDeliveryMode(mode: SubagentParamsLike["mode"]): SteerDeliveryMode | undefined {
202
+ return mode === "steer" || mode === "follow_up" || mode === "auto" ? mode : undefined;
203
+ }
204
+
188
205
  function editDistance(left: string, right: string): number {
189
206
  const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
190
207
  for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
@@ -280,6 +297,9 @@ export interface SubagentParamsLike {
280
297
  runId?: string;
281
298
  dir?: string;
282
299
  handoffPath?: string;
300
+ laneId?: string;
301
+ merge?: unknown;
302
+ supersession?: unknown;
283
303
  index?: number;
284
304
  childId?: string;
285
305
  view?: "fleet" | "transcript";
@@ -291,24 +311,35 @@ export interface SubagentParamsLike {
291
311
  type?: string;
292
312
  agent?: string;
293
313
  task?: string;
314
+ capabilities?: boolean;
294
315
  extensionBindings?: ExtensionBindings;
295
316
  /** Retained async child run id. Valid only on workflow runs.run items. */
296
317
  resume?: string;
297
318
  message?: string;
298
319
  steeringRecovery?: boolean;
299
- mode?: SteerDeliveryMode;
320
+ mode?: SteerDeliveryMode | "plan" | "apply";
321
+ repo?: string;
322
+ planId?: string;
300
323
  workflowScript?: string;
324
+ workflowScriptPath?: string;
325
+ globalConcurrencyLimit?: number;
326
+ maxSubagentSpawnsPerRun?: number;
327
+ preflight?: import("../../shared/types.ts").WorkflowPreflightV1;
301
328
  chatProgress?: "auto" | "off" | "live-card";
302
329
  isolation?: "none" | "worktree";
303
330
  step?: ChainStep;
304
331
  /** Internal workflow ownership metadata; not part of the public schema. */
305
332
  workflowParentRunId?: string;
306
333
  workflowKey?: string;
334
+ lane?: import("../../shared/types.ts").WorkflowLaneMetadata;
307
335
  /** Set by the scheduler so this run's completion can name the schedule that produced it. */
308
336
  scheduleOrigin?: ScheduleOrigin;
309
337
  workflowChildAsyncId?: string;
310
338
  workflowAwaitAsync?: boolean;
339
+ /** Internal async-workflow bridge: keep the live VM await pending across supervisor detachment. */
340
+ workflowAwaitDetached?: boolean;
311
341
  workflowParentDeadlineAt?: number;
342
+ workflowOutputClaimPath?: string;
312
343
  suppressRoutineResultIntercom?: boolean;
313
344
  /** Internal inherited cumulative run-tree budget. */
314
345
  runFanoutBudget?: RunFanoutBudgetDescriptor;
@@ -321,6 +352,8 @@ export interface SubagentParamsLike {
321
352
  tasks?: TaskParam[];
322
353
  concurrency?: number;
323
354
  worktree?: boolean;
355
+ /** Git ref used as the managed worktree base. */
356
+ baseRef?: string;
324
357
  context?: "fresh" | "fork" | "profile";
325
358
  /** Per-run intercom bridge config. It replaces the global config for this launch only. */
326
359
  intercomBridge?: IntercomBridgeConfig;
@@ -330,9 +363,6 @@ export interface SubagentParamsLike {
330
363
  maxRuntimeMs?: number;
331
364
  /** Optional hard per-tool-call timeout (ms). Known-fast tools also have a default. */
332
365
  toolTimeoutMs?: number;
333
- turnBudget?: TurnBudgetConfig;
334
- /** Internal-only strict turn-boundary enforcement for versioned foreground delegation. */
335
- enforceHardTurnLimit?: boolean;
336
366
  toolBudget?: ToolBudgetConfig;
337
367
  usageBudget?: UsageBudgetConfig;
338
368
  clarify?: boolean;
@@ -344,8 +374,13 @@ export interface SubagentParamsLike {
344
374
  artifacts?: boolean;
345
375
  includeProgress?: boolean;
346
376
  model?: string;
377
+ /** Internal recovery provenance for a resolved model override. */
378
+ modelOrigin?: ModelOrigin;
347
379
  fast?: boolean;
348
380
  thinking?: string | false;
381
+ /** Public named workflow resource. Resolved before entering the workflow sandbox. */
382
+ workflow?: string;
383
+ args?: Record<string, unknown>;
349
384
  scope?: string;
350
385
  target?: string;
351
386
  focus?: boolean;
@@ -362,6 +397,7 @@ export interface SubagentParamsLike {
362
397
  agentContract?: AgentContract;
363
398
  at?: string;
364
399
  every?: string;
400
+ sessionOnly?: boolean;
365
401
  on?: string | number;
366
402
  timezone?: string;
367
403
  overlap?: "skip";
@@ -392,28 +428,47 @@ interface ExecutorDeps {
392
428
  config: ExtensionConfig;
393
429
  asyncByDefault: boolean;
394
430
  waitToolEnabled?: boolean;
431
+ waitToolDefaultTimeoutMs?: number;
395
432
  handleScheduledRunAction?: (params: SubagentParamsLike, ctx: ExtensionContext) => Promise<AgentToolResult<Details>>;
396
433
  watchdog?: MainWatchdogRuntime;
397
434
  tempArtifactsDir: string;
398
435
  getSubagentSessionRoot: (parentSessionFile: string | null) => string;
399
436
  expandTilde: (p: string) => string;
400
- discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig; maxThinking?: AgentConfig["maxThinking"] };
437
+ discoverAgents: (cwd: string, scope: AgentScope, preferredModelProvider?: string) => { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig; maxThinking?: AgentConfig["maxThinking"]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] };
401
438
  allowMutatingManagementActions?: boolean;
402
439
  activateSupervisorTransport?: () => void;
403
440
  refreshResultDelivery?: () => void;
404
441
  kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
442
+ /** Set when this executor runs inside a child session; carries the runtime settings the host passes instead of environment variables. */
443
+ childRuntime?: ChildRuntimeConfig;
444
+ }
445
+
446
+ function inheritedNestedRoute(deps: Pick<ExecutorDeps, "childRuntime">): NestedRoute | undefined {
447
+ return inheritedNestedRouteOf(deps.childRuntime);
448
+ }
449
+
450
+ function inheritedNestedParentAddress(deps: Pick<ExecutorDeps, "childRuntime">): NestedParentAddress | undefined {
451
+ return inheritedNestedParentAddressOf(deps.childRuntime);
405
452
  }
406
453
 
407
- type ForkSessionFileForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean) => string | undefined;
408
- type ForkThinkingOverrideForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean) => AgentConfig["thinking"] | undefined;
454
+ function inheritedRunFanoutBudget(deps: Pick<ExecutorDeps, "childRuntime">): RunFanoutBudgetDescriptor | undefined {
455
+ return deps.childRuntime?.runFanoutBudget;
456
+ }
457
+
458
+ type ForkSessionFileForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean, modelOrigin?: ModelOrigin) => string | undefined;
459
+ 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;
409
461
 
410
462
  interface ExecutionContextData {
411
463
  params: SubagentParamsLike;
412
464
  effectiveCwd: string;
465
+ requestedCwd?: string;
413
466
  ctx: ExtensionContext;
414
467
  signal: AbortSignal;
415
468
  onUpdate?: (r: AgentToolResult<Details>) => void;
416
469
  agents: AgentConfig[];
470
+ /** Exact filesystem discovery provenance retained through defensive execution backstops. */
471
+ unknownAgentDiagnosticContext: UnknownAgentDiagnosticContext;
417
472
  /** Discovered agent definitions before per-run bridge injection. */
418
473
  recoveryAgents: AgentConfig[];
419
474
  runId: string;
@@ -429,13 +484,14 @@ interface ExecutionContextData {
429
484
  effectiveAsync: boolean;
430
485
  asyncRunId: string;
431
486
  controlConfig: ResolvedControlConfig;
487
+ /** Structured delegation consumers do not need duration-only heartbeat snapshots. */
488
+ suppressUnchangedDelegationUpdates?: boolean;
432
489
  intercomBridge: IntercomBridgeState;
433
490
  nestedRoute?: NestedRouteInfo;
434
491
  timeoutMs?: number;
435
492
  deadlineAt?: number;
436
493
  /** Raw global config.toolTimeoutMs, for per-step resolution in async runners. */
437
494
  configToolTimeoutMs?: number;
438
- turnBudget?: ResolvedTurnBudget;
439
495
  toolBudget?: ResolvedToolBudget;
440
496
  usageBudget?: UsageBudgetConfig;
441
497
  allowZeroToolBudget?: boolean;
@@ -449,16 +505,30 @@ interface ExecutionContextData {
449
505
  runFanoutBudget: RunFanoutBudgetDescriptor;
450
506
  topLevelAsyncCapacityEligible: boolean;
451
507
  activeAsyncCapacity?: ActiveAsyncCapacityHandle;
508
+ workflowChildPermitLaunch?: WorkflowChildPermitContext;
452
509
  }
453
510
 
454
511
  function resolveRequestedCwd(runtimeCwd: string, requestedCwd: string | undefined): string {
455
512
  return requestedCwd ? path.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
456
513
  }
457
514
 
515
+ function loadWorkflowScriptPath(params: SubagentParamsLike, runtimeCwd: string): { params?: SubagentParamsLike; error?: string } {
516
+ if (params.workflowScriptPath === undefined) return { params };
517
+ const scriptPath = path.resolve(resolveRequestedCwd(runtimeCwd, params.cwd), params.workflowScriptPath);
518
+ let workflowScript: string;
519
+ try {
520
+ workflowScript = fs.readFileSync(scriptPath, "utf8");
521
+ } catch (error) {
522
+ return { error: `Failed to read workflowScriptPath '${scriptPath}': ${error instanceof Error ? error.message : String(error)}` };
523
+ }
524
+ if (!workflowScript.trim()) return { error: `workflowScriptPath file '${scriptPath}' is empty.` };
525
+ const { workflowScriptPath: _workflowScriptPath, ...rest } = params;
526
+ return { params: { ...rest, workflowScript } };
527
+ }
528
+
458
529
  function removeForegroundControlIfIdle(state: SubagentState, runId: string): boolean {
459
530
  const control = state.foregroundControls.get(runId);
460
531
  if (control && (!foregroundSchedulingSettled(control) || (control.activeChildren?.size ?? 0) > 0)) return false;
461
- if (control) removeWorkflowForegroundSteeringRoute(control);
462
532
  state.foregroundControls.delete(runId);
463
533
  if (state.lastForegroundControlId === runId) state.lastForegroundControlId = null;
464
534
  return true;
@@ -477,12 +547,13 @@ function getForegroundControl(state: SubagentState, runId: string | undefined) {
477
547
  return newest;
478
548
  }
479
549
 
480
- function promptAuditRedoParams(value: unknown, rewrittenTask: string): SubagentParamsLike {
550
+ export function promptAuditRedoParams(value: unknown, rewrittenTask: string): SubagentParamsLike {
481
551
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Prompt redo is missing a safe live launch contract.");
482
552
  const params = { ...(value as SubagentParamsLike), task: rewrittenTask, async: false };
483
553
  delete params.workflowParentRunId;
484
554
  delete params.workflowKey;
485
555
  delete params.workflowChildAsyncId;
556
+ delete params.workflowAwaitDetached;
486
557
  delete params.workflowParentDeadlineAt;
487
558
  delete params.suppressRoutineResultIntercom;
488
559
  if (params.worktree === true && Array.isArray(params.tasks)) delete params.cwd;
@@ -510,8 +581,8 @@ function formatForegroundActivity(control: SubagentState["foregroundControls"] e
510
581
 
511
582
  function nestedResolutionScopeForExecutor(deps: ExecutorDeps): NestedRunResolutionScope | undefined {
512
583
  if (deps.allowMutatingManagementActions !== false) return undefined;
513
- const route = resolveInheritedNestedRouteFromEnv();
514
- const address = route ? resolveNestedParentAddressFromEnv() : undefined;
584
+ const route = inheritedNestedRoute(deps);
585
+ const address = route ? inheritedNestedParentAddress(deps) : undefined;
515
586
  return {
516
587
  routes: route ? [route] : [],
517
588
  ...(address ? { descendantOf: { parentRunId: address.parentRunId, ...(address.parentStepIndex !== undefined ? { parentStepIndex: address.parentStepIndex } : {}) } } : {}),
@@ -543,6 +614,7 @@ function withSpawnBudgetStatus(
543
614
  const activeAsyncCapacity = sessionId
544
615
  ? getActiveAsyncCapacitySnapshot(sessionId, resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession), {
545
616
  liveWorkflowRunIds: new Set(state.workflowControllers?.keys() ?? []),
617
+ abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(config.capacity?.abandonedSlotReleaseAfterMs),
546
618
  })
547
619
  : { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession) ?? 0 };
548
620
  state.activeAsyncCapacity = activeAsyncCapacity;
@@ -645,11 +717,13 @@ function foregroundChildActivityFromProgress(progress: SingleResult["progress"]
645
717
  ...(progress?.currentPath ? { currentPath: progress.currentPath } : {}),
646
718
  ...(progress?.turnCount !== undefined ? { turnCount: progress.turnCount } : {}),
647
719
  ...(progress?.tokens !== undefined ? { tokens: progress.tokens } : {}),
720
+ ...(progress?.window !== undefined ? { window: progress.window } : {}),
721
+ ...(progress?.windowPeak !== undefined ? { windowPeak: progress.windowPeak } : {}),
648
722
  ...(progress?.toolCount !== undefined ? { toolCount: progress.toolCount } : {}),
649
723
  };
650
724
  }
651
725
 
652
- function rememberForegroundRun(state: SubagentState, input: { runId: string; mode: "single" | "parallel" | "chain"; cwd: string; sessionId: string | null; results: SingleResult[]; extensionBindings?: ExtensionBindings }): void {
726
+ 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 {
653
727
  state.foregroundRuns ??= new Map();
654
728
  const previous = state.foregroundRuns.get(input.runId);
655
729
  const updatedAt = Date.now();
@@ -660,9 +734,17 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
660
734
  ...(input.sessionId ? { sessionId: input.sessionId } : {}),
661
735
  updatedAt,
662
736
  children: input.results.map((result, index) => {
737
+ const resumeContract = omitUndefinedProperties({
738
+ outputSchema: input.params.outputSchema,
739
+ agentContract: input.params.agentContract,
740
+ acceptance: input.params.acceptance,
741
+ output: input.effectiveOutput,
742
+ outputMode: input.effectiveOutputMode,
743
+ });
663
744
  const child = {
664
745
  agent: result.agent,
665
746
  index,
747
+ ...(result.sessionName ? { sessionName: result.sessionName } : {}),
666
748
  ...(result.context ? { context: result.context } : {}),
667
749
  status: resolveSubagentResultStatus(omitUndefinedProperties({
668
750
  exitCode: result.exitCode,
@@ -690,6 +772,7 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
690
772
  ...(result.transcriptError ? { transcriptError: result.transcriptError } : {}),
691
773
  ...(result.detachedReason ? { detachedReason: result.detachedReason } : {}),
692
774
  ...(result.acceptance ? { acceptance: result.acceptance } : {}),
775
+ ...(Object.keys(resumeContract).length ? { resumeContract } : {}),
693
776
  ...(result.launchContractDigest ? { launchContractDigest: result.launchContractDigest } : {}),
694
777
  ...(input.extensionBindings ? { extensionBindings: input.extensionBindings } : {}),
695
778
  ...(result.launchResolvedExtensions ? { launchResolvedExtensions: result.launchResolvedExtensions } : {}),
@@ -810,7 +893,7 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
810
893
  });
811
894
  }
812
895
 
813
- function resolveForegroundResumeTarget(params: SubagentParamsLike, state: SubagentState, options: { exactOnly?: boolean } = {}): { runId: string; mode: SubagentRunMode; state: "complete"; agent: string; index: number; cwd: string; sessionFile: string; model?: string; thinking?: string; launchContractDigest?: string; extensionBindings?: ExtensionBindings; capabilityCeiling?: ResolvedSubagentCapabilityCeiling } | undefined {
896
+ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: SubagentState, options: { exactOnly?: boolean } = {}): { runId: string; mode: SubagentRunMode; state: "complete"; agent: string; index: number; cwd: string; sessionFile: string; model?: string; thinking?: string; launchContractDigest?: string; resumeContract?: ForegroundResumeChild["resumeContract"]; extensionBindings?: ExtensionBindings; capabilityCeiling?: ResolvedSubagentCapabilityCeiling } | undefined {
814
897
  const requested = (params.id ?? params.runId)?.trim();
815
898
  if (!requested || !state.foregroundRuns?.size || !state.currentSessionId) return undefined;
816
899
  const direct = state.foregroundRuns.get(requested);
@@ -820,7 +903,7 @@ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: Subage
820
903
  if (matches.length === 0) return undefined;
821
904
  if (matches.length > 1) throw new Error(`Ambiguous foreground run id prefix '${requested}' matched: ${matches.map((run) => run.runId).join(", ")}. Provide a longer id.`);
822
905
  const run = matches[0]!;
823
- if (run.children.some((child) => child.status === "detached")) throw new Error(`Foreground run '${run.runId}' is detached for intercom coordination and cannot be revived safely while any child may still be live. Reply to the supervisor request first, then wait with subagent_wait({ id: "${run.runId}" }); use status to recover the result and do not launch a replacement while it remains detached.`);
906
+ if (run.children.some((child) => child.status === "detached")) throw new Error(`Foreground run '${run.runId}' is detached for intercom coordination and cannot be revived safely while any child may still be live. Reply to the supervisor request first, then wait with bg_wait({ id: "${run.runId}" }); use status to recover the result and do not launch a replacement while it remains detached.`);
824
907
  if (run.children.length > 1 && params.index === undefined) throw new Error(`Foreground run '${run.runId}' has ${run.children.length} children. Provide index to choose one.`);
825
908
  const index = params.index ?? 0;
826
909
  if (!Number.isInteger(index)) throw new Error(`Foreground run '${run.runId}' index must be an integer.`);
@@ -841,6 +924,7 @@ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: Subage
841
924
  ...(child.model ? { model: child.model } : {}),
842
925
  ...(child.thinking ? { thinking: child.thinking } : {}),
843
926
  ...(child.launchContractDigest ? { launchContractDigest: child.launchContractDigest } : {}),
927
+ ...(child.resumeContract ? { resumeContract: child.resumeContract } : {}),
844
928
  ...(child.extensionBindings ? { extensionBindings: normalizeExtensionBindings(child.extensionBindings)!.value } : {}),
845
929
  ...(child.capabilityCeiling ? { capabilityCeiling: child.capabilityCeiling } : {}),
846
930
  };
@@ -1215,7 +1299,7 @@ function appendStepToAsyncChain(input: {
1215
1299
  }
1216
1300
 
1217
1301
  const scope: AgentScope = resolveExecutionAgentScope(input.params.agentScope);
1218
- const discoveredForAppend = input.deps.discoverAgents(input.requestCwd, scope);
1302
+ const discoveredForAppend = input.deps.discoverAgents(input.requestCwd, scope, input.parentModel?.provider);
1219
1303
  const agents = discoveredForAppend.agents;
1220
1304
  const contextPolicy = resolveExplicitContextPolicy(input.params);
1221
1305
  const chainSkillInput = normalizeSkillInput(input.params.skill);
@@ -1231,6 +1315,7 @@ function appendStepToAsyncChain(input: {
1231
1315
  modelScope: discoveredForAppend.modelScope,
1232
1316
  interactive: input.ctx.hasUI,
1233
1317
  permissions: input.deps.config.permissions,
1318
+ childRuntime: input.deps.childRuntime,
1234
1319
  });
1235
1320
  const built = buildAsyncRunnerSteps(resolved.id, compactOptional<Parameters<typeof buildAsyncRunnerSteps>[1]>({
1236
1321
  chain: wrapChainTasksForFork(chain, contextPolicy),
@@ -1239,12 +1324,17 @@ function appendStepToAsyncChain(input: {
1239
1324
  agents,
1240
1325
  ctx: asyncCtx,
1241
1326
  availableModels: input.ctx.modelRegistry.getAvailable().map(toModelInfo),
1327
+ unknownAgentDiagnosticContext: diagnosticContextFromDiscovery(discoveredForAppend, input.requestCwd, scope),
1242
1328
  cwd: status.cwd ?? input.requestCwd,
1243
1329
  chainSkills,
1244
1330
  dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,
1245
- maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
1331
+ maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime),
1246
1332
  waitToolEnabled: input.deps.waitToolEnabled,
1333
+ waitToolDefaultTimeoutMs: input.deps.waitToolDefaultTimeoutMs,
1247
1334
  contextForAgent: contextPolicy.contextForAgent,
1335
+ worktreeBaseDir: input.deps.config.worktreeBaseDir,
1336
+ worktreeProvider: input.deps.config.worktreeProvider,
1337
+ worktreeBranchPrefix: input.deps.config.worktreeBranchPrefix,
1248
1338
  asyncDir: resolved.location.asyncDir,
1249
1339
  validateOutputBindings: false,
1250
1340
  capabilityCeiling: intersectSubagentCapabilityCeilings(status.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(asyncCtx.currentSessionId)),
@@ -1514,9 +1604,14 @@ function externalJobFollowUpStarted(input: { sourceRunId: string; runId: string;
1514
1604
  function externalRunnerControlError(asyncDir: string, action: "steer" | "resume"): AgentToolResult<Details> | undefined {
1515
1605
  const status = readStatus(asyncDir);
1516
1606
  if (!status?.steps?.length || !status.steps.every((step) => step.runner?.type === "external-cli" || step.runner?.type === "external-job")) return undefined;
1517
- const message = action === "steer"
1518
- ? "External runners do not accept live steer messages."
1519
- : "External runners do not persist Pi sessions and cannot be resumed.";
1607
+ const externalCli = normalizeExternalCliRunnerStatus(status.steps.find((step) => step.runner?.type === "external-cli")?.runner);
1608
+ const message = externalCli
1609
+ ? action === "steer"
1610
+ ? `External adapter '${externalCli.adapter.id}' does not support runs.steer: ${externalCli.unsupportedReasons.steer}`
1611
+ : `External adapter '${externalCli.adapter.id}' cannot resume: ${externalCli.nonResumableReason}`
1612
+ : action === "steer"
1613
+ ? "External runners do not accept live steer messages."
1614
+ : "External runners do not persist Pi sessions and cannot be resumed.";
1520
1615
  return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
1521
1616
  }
1522
1617
 
@@ -1559,11 +1654,11 @@ async function resumeExternalJobFollowUp(input: {
1559
1654
  return externalJobFollowUpStarted({ sourceRunId: input.target.runId, runId, asyncDir, duplicate: true, interactive: input.ctx.hasUI });
1560
1655
  }
1561
1656
 
1562
- const depthState = checkSubagentDepth(input.deps.config.maxSubagentDepth);
1657
+ const depthState = checkSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime);
1563
1658
  if (depthState.blocked) {
1564
1659
  return { content: [{ type: "text", text: `Nested subagent resume blocked (depth=${depthState.depth}, max=${depthState.maxDepth}). Complete the follow-up directly instead.` }], isError: true, details: { mode: "management", results: [] } };
1565
1660
  }
1566
- const topLevelResume = depthState.depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.deps.state.workflowControllers?.has(input.target.runId);
1661
+ const topLevelResume = depthState.depth === 0 && !inheritedNestedRoute(input.deps) && !input.deps.state.workflowControllers?.has(input.target.runId);
1567
1662
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1568
1663
  try {
1569
1664
  activeAsyncCapacity = topLevelResume ? acquireActiveAsyncCapacity({
@@ -1572,7 +1667,7 @@ async function resumeExternalJobFollowUp(input: {
1572
1667
  runId,
1573
1668
  kind: "runner",
1574
1669
  asyncDir,
1575
- }, { liveWorkflowRunIds: new Set(input.deps.state.workflowControllers?.keys() ?? []) }) : undefined;
1670
+ }, { liveWorkflowRunIds: new Set(input.deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(input.deps.config.capacity?.abandonedSlotReleaseAfterMs) }) : undefined;
1576
1671
  } catch (error) {
1577
1672
  if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "single", results: [], activeAsyncCapacity: error.snapshot } };
1578
1673
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "single", results: [] } };
@@ -1601,17 +1696,21 @@ async function resumeExternalJobFollowUp(input: {
1601
1696
  modelScope: input.modelScope,
1602
1697
  interactive: input.ctx.hasUI,
1603
1698
  permissions: input.deps.config.permissions,
1699
+ childRuntime: input.deps.childRuntime,
1604
1700
  }),
1605
1701
  cwd: input.effectiveCwd,
1606
1702
  artifactsDir,
1607
1703
  artifactConfig,
1608
1704
  shareEnabled: false,
1609
1705
  ...(input.parentSessionFile ? { sessionRoot: input.deps.getSubagentSessionRoot(input.parentSessionFile) } : {}),
1610
- maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
1706
+ maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime),
1611
1707
  waitToolEnabled: input.deps.waitToolEnabled,
1708
+ waitToolDefaultTimeoutMs: input.deps.waitToolDefaultTimeoutMs,
1612
1709
  worktreeSetupHook: input.deps.config.worktreeSetupHook,
1613
1710
  worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
1614
1711
  worktreeBaseDir: input.deps.config.worktreeBaseDir,
1712
+ worktreeProvider: input.deps.config.worktreeProvider,
1713
+ worktreeBranchPrefix: input.deps.config.worktreeBranchPrefix,
1615
1714
  controlConfig: resolveControlConfig(input.deps.config.control, undefined),
1616
1715
  controlIntercomTarget: input.intercomBridge.active ? input.intercomBridge.orchestratorTarget : undefined,
1617
1716
  childIntercomTarget: input.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : undefined,
@@ -1715,7 +1814,7 @@ async function resumeAsyncRun(input: {
1715
1814
  };
1716
1815
  }
1717
1816
 
1718
- const { blocked, depth, maxDepth } = checkSubagentDepth(input.deps.config.maxSubagentDepth);
1817
+ const { blocked, depth, maxDepth } = checkSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime);
1719
1818
  if (blocked) {
1720
1819
  return {
1721
1820
  content: [{ type: "text", text: `Nested subagent resume blocked (depth=${depth}, max=${maxDepth}). Complete the follow-up directly instead.` }],
@@ -1727,8 +1826,9 @@ async function resumeAsyncRun(input: {
1727
1826
  input.deps.state.currentSessionId = resolveCurrentSessionId(input.ctx.sessionManager);
1728
1827
  const effectiveCwd = target.cwd ?? input.requestCwd;
1729
1828
  const scope: AgentScope = resolveExecutionAgentScope(input.params.agentScope);
1730
- const discovered = input.deps.discoverAgents(effectiveCwd, scope);
1829
+ const discovered = input.deps.discoverAgents(effectiveCwd, scope, input.parentModel?.provider);
1731
1830
  const discoveredAgents = discovered.agents;
1831
+ const unknownAgentDiagnosticContext = diagnosticContextFromDiscovery(discovered, effectiveCwd, scope);
1732
1832
  const modelScope = discovered.modelScope;
1733
1833
  const sessionName = resolveIntercomSessionTarget(input.deps.pi.getSessionName(), input.ctx.sessionManager.getSessionId());
1734
1834
  const recoveryDescriptor = "recoveryDescriptor" in target ? target.recoveryDescriptor : undefined;
@@ -1749,6 +1849,7 @@ async function resumeAsyncRun(input: {
1749
1849
  systemPrompt: "",
1750
1850
  systemPromptMode: recoveryDescriptor.systemPromptMode,
1751
1851
  inheritProjectContext: recoveryDescriptor.inheritProjectContext,
1852
+ inheritGlobalContext: recoveryDescriptor.inheritGlobalContext,
1752
1853
  inheritSkills: recoveryDescriptor.inheritSkills,
1753
1854
  source: "project",
1754
1855
  filePath: recoveryDescriptor.agentFilePath ?? path.join(getProjectSubagentsDir(recoveryDescriptor.cwd), "recovery-agent"),
@@ -1756,13 +1857,17 @@ async function resumeAsyncRun(input: {
1756
1857
  } : undefined);
1757
1858
  if (!baseAgentConfig) {
1758
1859
  return {
1759
- content: [{ type: "text", text: `Unknown agent for resume: ${target.agent}` }],
1860
+ content: [{ type: "text", text: formatUnknownAgentError(target.agent, unknownAgentDiagnosticContext, "Unknown agent for resume") }],
1760
1861
  isError: true,
1761
1862
  details: { mode: "management", results: [] },
1762
1863
  };
1763
1864
  }
1764
1865
  if (target.source === "async" && target.runner?.type === "external-cli") {
1765
- return { content: [{ type: "text", text: "External runners do not persist Pi sessions and cannot be resumed." }], isError: true, details: { mode: "management", results: [] } };
1866
+ const runner = normalizeExternalCliRunnerStatus(target.runner);
1867
+ const message = runner
1868
+ ? `External adapter '${runner.adapter.id}' cannot resume: ${runner.nonResumableReason}`
1869
+ : "External runners do not persist Pi sessions and cannot be resumed.";
1870
+ return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
1766
1871
  }
1767
1872
  if (target.source === "async" && target.runner?.type === "external-job") {
1768
1873
  if (attachChain) return { content: [{ type: "text", text: "External-job follow-up does not support chain attachment. Use action='resume' with message instead." }], isError: true, details: { mode: "management", results: [] } };
@@ -1798,7 +1903,7 @@ async function resumeAsyncRun(input: {
1798
1903
  };
1799
1904
  }
1800
1905
  const runId = randomUUID();
1801
- const topLevelResume = depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.params.workflowParentRunId;
1906
+ const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
1802
1907
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1803
1908
  try {
1804
1909
  activeAsyncCapacity = topLevelResume ? acquireActiveAsyncCapacity({
@@ -1807,7 +1912,7 @@ async function resumeAsyncRun(input: {
1807
1912
  runId,
1808
1913
  kind: "runner",
1809
1914
  asyncDir: path.join(DIRS.async, runId),
1810
- }, { liveWorkflowRunIds: new Set(input.deps.state.workflowControllers?.keys() ?? []) }) : undefined;
1915
+ }, { liveWorkflowRunIds: new Set(input.deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(input.deps.config.capacity?.abandonedSlotReleaseAfterMs) }) : undefined;
1811
1916
  } catch (error) {
1812
1917
  if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "chain", results: [], activeAsyncCapacity: error.snapshot } };
1813
1918
  throw error;
@@ -1833,6 +1938,7 @@ async function resumeAsyncRun(input: {
1833
1938
  label: `Attached ${target.runId}`,
1834
1939
  },
1835
1940
  agents,
1941
+ unknownAgentDiagnosticContext,
1836
1942
  ctx: compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
1837
1943
  pi: input.deps.pi,
1838
1944
  cwd: input.requestCwd,
@@ -1843,6 +1949,7 @@ async function resumeAsyncRun(input: {
1843
1949
  modelScope,
1844
1950
  interactive: input.ctx.hasUI,
1845
1951
  permissions: input.deps.config.permissions,
1952
+ childRuntime: input.deps.childRuntime,
1846
1953
  }),
1847
1954
  availableModels,
1848
1955
  cwd: effectiveCwd,
@@ -1855,11 +1962,15 @@ async function resumeAsyncRun(input: {
1855
1962
  agentContract: input.params.agentContract,
1856
1963
  fast: input.params.fast,
1857
1964
  dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,
1858
- maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
1965
+ maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime),
1859
1966
  waitToolEnabled: input.deps.waitToolEnabled,
1967
+ waitToolDefaultTimeoutMs: input.deps.waitToolDefaultTimeoutMs,
1860
1968
  worktreeSetupHook: input.deps.config.worktreeSetupHook,
1861
1969
  worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
1862
1970
  worktreeBaseDir: input.deps.config.worktreeBaseDir,
1971
+ baseRef: input.params.baseRef ?? target.recoveryDescriptor?.baseRef,
1972
+ worktreeProvider: input.deps.config.worktreeProvider,
1973
+ worktreeBranchPrefix: input.deps.config.worktreeBranchPrefix,
1863
1974
  controlConfig: resolveControlConfig(input.deps.config.control, input.params.control),
1864
1975
  controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : undefined,
1865
1976
  childIntercomTarget: intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : undefined,
@@ -1894,8 +2005,11 @@ async function resumeAsyncRun(input: {
1894
2005
  if (target.source === "async" && asyncReviveRequiresRecoveryDescriptor(target)) {
1895
2006
  return { content: [{ type: "text", text: `Async child '${target.runId}' is missing its required run fan-out recovery identity. Start a new run instead.` }], isError: true, details: { mode: "management", results: [] } };
1896
2007
  }
2008
+ if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
2009
+ 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: [] } };
2010
+ }
1897
2011
  const runId = randomUUID();
1898
- const topLevelResume = depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.params.workflowParentRunId;
2012
+ const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
1899
2013
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1900
2014
  try {
1901
2015
  activeAsyncCapacity = !topLevelResume ? undefined : target.source === "async"
@@ -1905,20 +2019,23 @@ async function resumeAsyncRun(input: {
1905
2019
  sourceRunId: target.runId,
1906
2020
  runId,
1907
2021
  asyncDir: path.join(DIRS.async, runId),
1908
- })
2022
+ }, { abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(input.deps.config.capacity?.abandonedSlotReleaseAfterMs) })
1909
2023
  : acquireActiveAsyncCapacity({
1910
2024
  sessionId: input.deps.state.currentSessionId!,
1911
2025
  limit: resolveMaxActiveAsyncRunsPerSession(input.deps.config.maxActiveAsyncRunsPerSession),
1912
2026
  runId,
1913
2027
  kind: "runner",
1914
2028
  asyncDir: path.join(DIRS.async, runId),
1915
- });
2029
+ }, { abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(input.deps.config.capacity?.abandonedSlotReleaseAfterMs) });
1916
2030
  } catch (error) {
1917
2031
  if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "single", results: [], activeAsyncCapacity: error.snapshot } };
1918
2032
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "single", results: [] } };
1919
2033
  }
1920
2034
  const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
1921
2035
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
2036
+ const foregroundContract = target.source === "foreground" ? target.resumeContract : undefined;
2037
+ const outputSchema = input.params.outputSchema ?? foregroundContract?.outputSchema ?? recoveryDescriptor?.structuredOutputSchema;
2038
+ const agentContract = input.params.agentContract ?? foregroundContract?.agentContract ?? recoveryDescriptor?.agentContract;
1922
2039
  const artifactConfig: ArtifactConfig = recoveryDescriptor?.artifactConfig ?? omitUndefinedProperties({ ...DEFAULT_ARTIFACT_CONFIG, enabled: input.params.artifacts !== false, dir: input.deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir });
1923
2040
  const artifactsDir = recoveryDescriptor?.artifactsDir ?? getArtifactsDir(parentSessionFile, effectiveCwd, artifactConfig.dir);
1924
2041
  const availableModels = input.ctx.modelRegistry.getAvailable().map(toModelInfo);
@@ -1940,6 +2057,7 @@ async function resumeAsyncRun(input: {
1940
2057
  modelScope,
1941
2058
  interactive: input.ctx.hasUI,
1942
2059
  permissions: input.deps.config.permissions,
2060
+ childRuntime: input.deps.childRuntime,
1943
2061
  }),
1944
2062
  cwd: effectiveCwd,
1945
2063
  maxOutput: input.params.maxOutput ?? recoveryDescriptor?.maxOutput,
@@ -1959,30 +2077,37 @@ async function resumeAsyncRun(input: {
1959
2077
  modelOverride: recoveryDescriptor?.model ?? target.model,
1960
2078
  fast: recoveryDescriptor?.fast,
1961
2079
  modelOverrideFromParent: recoveryDescriptor?.modelOverrideFromParent,
2080
+ modelOrigin: recoveryDescriptor?.modelOrigin ?? (recoveryDescriptor?.modelOverrideFromParent ? "inherited" : undefined),
1962
2081
  thinkingOverride: recoveryDescriptor?.thinking ?? target.thinking,
1963
2082
  thinkingCeiling: recoveryDescriptor?.thinkingCeiling ?? ("thinkingCeiling" in target ? target.thinkingCeiling : undefined),
1964
2083
  extensionBindings: recoveryDescriptor?.extensionBindings ?? ("extensionBindings" in target ? target.extensionBindings : undefined),
1965
2084
  outputBaseDir: resolveSingleRunOutputBaseDir(input.deps, artifactsDir, runId),
1966
- maxSubagentDepth: recoveryDescriptor?.maxSubagentDepth ?? resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
2085
+ maxSubagentDepth: recoveryDescriptor?.maxSubagentDepth ?? resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime),
1967
2086
  waitToolEnabled: input.deps.waitToolEnabled,
2087
+ waitToolDefaultTimeoutMs: input.deps.waitToolDefaultTimeoutMs,
1968
2088
  worktreeSetupHook: input.deps.config.worktreeSetupHook,
1969
2089
  worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
1970
2090
  worktreeBaseDir: input.deps.config.worktreeBaseDir,
1971
- worktree: input.params.worktree === true,
1972
- controlConfig: recoveryDescriptor?.controlConfig ?? resolveControlConfig(input.deps.config.control, input.params.control),
2091
+ baseRef: input.params.baseRef ?? recoveryDescriptor?.baseRef,
2092
+ worktreeProvider: input.deps.config.worktreeProvider,
2093
+ worktreeBranchPrefix: input.deps.config.worktreeBranchPrefix,
2094
+ // A retained async child already owns the recorded worktree. Resume it in
2095
+ // place rather than allocating a second provider worktree around it.
2096
+ worktree: input.params.worktree === true && !("managedWorktree" in target && target.managedWorktree === true),
2097
+ lane: input.params.lane ?? recoveryDescriptor?.lane,
2098
+ controlConfig: resolveRevivalControlConfig({ globalConfig: input.deps.config.control, requestedControl: input.params.control, recoveryControlConfig: recoveryDescriptor?.controlConfig }),
1973
2099
  intercomBridge: input.params.intercomBridge ?? recoveryDescriptor?.intercomBridge,
1974
2100
  controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : undefined,
1975
2101
  childIntercomTarget: intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : undefined,
1976
2102
  availableModels,
1977
- output: typeof input.params.output === "string" ? input.params.output : recoveryDescriptor?.outputPath,
1978
- outputMode: input.params.outputMode ?? recoveryDescriptor?.outputMode,
1979
- ...(recoveryDescriptor?.agentContract ? { agentContract: recoveryDescriptor.agentContract } : {}),
1980
- ...(recoveryDescriptor?.structuredOutputSchema ? { structuredOutputSchema: recoveryDescriptor.structuredOutputSchema } : {}),
2103
+ output: input.params.output !== undefined ? input.params.output : foregroundContract?.output ?? recoveryDescriptor?.outputPath,
2104
+ outputMode: input.params.outputMode ?? foregroundContract?.outputMode ?? recoveryDescriptor?.outputMode,
2105
+ ...(agentContract ? { agentContract } : {}),
2106
+ ...(outputSchema ? { structuredOutputSchema: outputSchema } : {}),
1981
2107
  ...(recoveryDescriptor?.skills ? { skills: [...recoveryDescriptor.skills] } : {}),
1982
- ...(recoveryDescriptor?.acceptance !== undefined && input.params.acceptance === undefined ? { acceptance: recoveryDescriptor.acceptance } : {}),
2108
+ ...(input.params.acceptance !== undefined ? { acceptance: input.params.acceptance } : foregroundContract?.acceptance !== undefined ? { acceptance: foregroundContract.acceptance } : recoveryDescriptor?.acceptance !== undefined ? { acceptance: recoveryDescriptor.acceptance } : {}),
1983
2109
  ...(input.params.timeoutMs !== undefined ? { timeoutMs: input.params.timeoutMs } : {}),
1984
2110
  ...(input.absoluteDeadlineAt !== undefined ? { absoluteDeadlineAt: input.absoluteDeadlineAt } : {}),
1985
- ...(input.params.turnBudget !== undefined ? { turnBudget: input.params.turnBudget } : {}),
1986
2111
  ...(input.params.toolBudget !== undefined ? { toolBudget: input.params.toolBudget } : {}),
1987
2112
  capabilityCeiling: intersectSubagentCapabilityCeilings("capabilityCeiling" in target ? target.capabilityCeiling : undefined, recoveryDescriptor?.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId)),
1988
2113
  runFanoutBudget: input.params.runFanoutBudget ?? recoveryDescriptor?.runFanoutBudget ?? createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(input.deps.config.maxSubagentSpawnsPerRun)),
@@ -2030,20 +2155,14 @@ async function resumeAsyncRun(input: {
2030
2155
  input.signal?.removeEventListener("abort", stopOnAbort);
2031
2156
  }
2032
2157
  fs.rmSync(resultPath, { force: true });
2033
- const totalCost = completed.totalCost;
2158
+ const usage = importedAsyncRootUsage(completed);
2034
2159
  const childResult: SingleResult = {
2035
2160
  index: 0,
2036
2161
  agent: completed.agent,
2162
+ ...(completed.sessionName ? { sessionName: completed.sessionName } : {}),
2037
2163
  task: effectiveFollowUp,
2038
2164
  exitCode: completed.exitCode,
2039
- usage: {
2040
- input: totalCost?.inputTokens ?? 0,
2041
- output: totalCost?.outputTokens ?? 0,
2042
- cacheRead: 0,
2043
- cacheWrite: 0,
2044
- cost: totalCost?.costUsd ?? 0,
2045
- turns: 0,
2046
- },
2165
+ usage,
2047
2166
  finalOutput: completed.output,
2048
2167
  outputState: completed.output.trim() ? "present" : "absent",
2049
2168
  ...(completed.error ? { error: completed.error } : {}),
@@ -2058,9 +2177,13 @@ async function resumeAsyncRun(input: {
2058
2177
  ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
2059
2178
  ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
2060
2179
  ...(completed.acceptance ? { acceptance: completed.acceptance } : {}),
2180
+ ...(completed.artifactPaths ? { artifactPaths: completed.artifactPaths } : {}),
2181
+ ...(completed.outputSaveError ? { outputSaveError: completed.outputSaveError } : {}),
2182
+ ...(completed.transcriptPath ? { transcriptPath: completed.transcriptPath } : {}),
2183
+ ...(completed.transcriptError ? { transcriptError: completed.transcriptError } : {}),
2061
2184
  };
2062
2185
  return {
2063
- content: [{ type: "text", text: completed.output || completed.error || `Revived ${target.source} subagent ${revivedId} completed without output.` }],
2186
+ content: [{ type: "text", text: completed.success ? completed.output || completed.error || `Revived ${target.source} subagent ${revivedId} completed without output.` : completed.error || completed.output || `Revived ${target.source} subagent ${revivedId} completed without output.` }],
2064
2187
  ...(completed.success ? {} : { isError: true }),
2065
2188
  details: {
2066
2189
  ...result.details,
@@ -2176,6 +2299,7 @@ async function emitForegroundResultIntercom(input: {
2176
2299
  if (!input.intercomBridge.active || !input.intercomBridge.resultDelivery || !input.intercomBridge.orchestratorTarget) return null;
2177
2300
  const children = input.results.flatMap((result, index) => result.detached ? [] : [omitUndefinedProperties({
2178
2301
  agent: result.agent,
2302
+ ...(result.sessionName ? { sessionName: result.sessionName } : {}),
2179
2303
  status: foregroundResultIntercomStatus(result),
2180
2304
  outputState: result.outputState ?? "unknown",
2181
2305
  summary: resultSummaryForIntercom(result),
@@ -2225,19 +2349,28 @@ async function maybeBuildForegroundIntercomReceipt(input: {
2225
2349
  };
2226
2350
  }
2227
2351
 
2228
- function canonicalizeAgentName(name: string, agents: AgentConfig[], diagnostics?: AgentDiscoveryDiagnostic[]): { name?: string; error?: string } {
2352
+ function diagnosticContextFromDiscovery(
2353
+ discovered: { agents: AgentConfig[]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] },
2354
+ cwd: string,
2355
+ scope: AgentScope,
2356
+ ): UnknownAgentDiagnosticContext {
2357
+ if (discovered.cwd && discovered.scope && discovered.directories) return unknownAgentDiagnosticContext({ ...discovered, cwd: discovered.cwd, scope: discovered.scope, directories: discovered.directories });
2358
+ return unknownAgentDiagnosticContext(discoverAgents(path.resolve(cwd), scope));
2359
+ }
2360
+
2361
+ function canonicalizeAgentName(name: string, agents: AgentConfig[], diagnostics: AgentDiscoveryDiagnostic[] | undefined, context: UnknownAgentDiagnosticContext): { name?: string; error?: string } {
2229
2362
  const resolved = resolveAgentName(name, agents);
2230
2363
  const candidates = resolved.error ? agents.filter((agent) => resolveAgentName(name, [agent]).agent) : resolved.agent;
2231
2364
  const diagnostic = findBlockingAgentDiagnostic(name, candidates, diagnostics);
2232
2365
  if (diagnostic) return { error: `Agent '${name}' has invalid configuration: ${diagnostic.error}` };
2233
2366
  if (resolved.error) return { error: resolved.error };
2234
- if (!resolved.agent) return { error: `Unknown agent: ${name}` };
2367
+ if (!resolved.agent) return { error: formatUnknownAgentError(name, context) };
2235
2368
  return { name: resolved.agent.name };
2236
2369
  }
2237
2370
 
2238
- function canonicalizeExecutionParams(params: SubagentParamsLike, agents: AgentConfig[], diagnostics?: AgentDiscoveryDiagnostic[]): { params?: SubagentParamsLike; error?: string } {
2371
+ function canonicalizeExecutionParams(params: SubagentParamsLike, agents: AgentConfig[], diagnostics: AgentDiscoveryDiagnostic[] | undefined, context: UnknownAgentDiagnosticContext): { params?: SubagentParamsLike; error?: string } {
2239
2372
  const resolve = (name: string, location?: string): { name?: string; error?: string } => {
2240
- const result = canonicalizeAgentName(name, agents, diagnostics);
2373
+ const result = canonicalizeAgentName(name, agents, diagnostics, context);
2241
2374
  return result.error && location ? { error: `${result.error} (${location})` } : result;
2242
2375
  };
2243
2376
  if (params.agent) {
@@ -2305,6 +2438,7 @@ function validateExecutionInput(
2305
2438
  hasTasks: boolean,
2306
2439
  hasSingle: boolean,
2307
2440
  allowClarifyTaskPrompt: boolean,
2441
+ context: UnknownAgentDiagnosticContext,
2308
2442
  ): AgentToolResult<Details> | null {
2309
2443
  if (Number(hasChain) + Number(hasTasks) + Number(hasSingle) !== 1) {
2310
2444
  return {
@@ -2330,7 +2464,7 @@ function validateExecutionInput(
2330
2464
 
2331
2465
  if (hasSingle && params.agent && !agents.find((agent) => agent.name === params.agent)) {
2332
2466
  return {
2333
- content: [{ type: "text", text: `Unknown agent: ${params.agent}` }],
2467
+ content: [{ type: "text", text: formatUnknownAgentError(params.agent, context) }],
2334
2468
  isError: true,
2335
2469
  details: { mode: "single" as const, results: [] },
2336
2470
  };
@@ -2341,7 +2475,7 @@ function validateExecutionInput(
2341
2475
  const task = params.tasks[i]!;
2342
2476
  if (!agents.find((agent) => agent.name === task.agent)) {
2343
2477
  return {
2344
- content: [{ type: "text", text: `Unknown agent: ${task.agent} (task ${i + 1})` }],
2478
+ content: [{ type: "text", text: `${formatUnknownAgentError(task.agent, context)} (task ${i + 1})` }],
2345
2479
  isError: true,
2346
2480
  details: { mode: "parallel" as const, results: [] },
2347
2481
  };
@@ -2386,7 +2520,7 @@ function validateExecutionInput(
2386
2520
  for (const agentName of stepAgents) {
2387
2521
  if (!agents.find((a) => a.name === agentName)) {
2388
2522
  return {
2389
- content: [{ type: "text", text: `Unknown agent: ${agentName} (step ${i + 1})` }],
2523
+ content: [{ type: "text", text: `${formatUnknownAgentError(agentName, context)} (step ${i + 1})` }],
2390
2524
  isError: true,
2391
2525
  details: { mode: "chain" as const, results: [] },
2392
2526
  };
@@ -2578,9 +2712,6 @@ function applySingleAgentLaunchDefaults(params: SubagentParamsLike, agents: Agen
2578
2712
  ? { timeoutMs: agent.defaultTimeoutMs }
2579
2713
  : {}),
2580
2714
  ...(parentTimeoutMs !== undefined ? { timeoutMs: parentTimeoutMs } : {}),
2581
- ...(params.turnBudget === undefined && agent.defaultTurnBudget !== undefined
2582
- ? { turnBudget: agent.defaultTurnBudget }
2583
- : {}),
2584
2715
  ...(params.acceptance === undefined && agent.defaultAcceptance !== undefined
2585
2716
  ? { acceptance: agent.defaultAcceptance }
2586
2717
  : {}),
@@ -2749,6 +2880,14 @@ function withResolvedContext(
2749
2880
  };
2750
2881
  }
2751
2882
 
2883
+ function withAggregatedToolUsage(result: AgentToolResult<Details>): AgentToolResult<Details> {
2884
+ if (result.details.results.length === 0) return result;
2885
+ const usage = sumResultsUsage(result.details.results);
2886
+ return usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0
2887
+ ? { ...result, usage: toAgentToolUsage(usage) }
2888
+ : result;
2889
+ }
2890
+
2752
2891
  function withForkThinkingNotes(
2753
2892
  result: AgentToolResult<Details>,
2754
2893
  downgrades: Map<number, string>,
@@ -2774,66 +2913,6 @@ function toExecutionErrorResult(params: SubagentParamsLike, error: unknown, cont
2774
2913
  );
2775
2914
  }
2776
2915
 
2777
- function collectChainSessionFiles(
2778
- chain: ChainStep[],
2779
- sessionFileForTask: ForkSessionFileForTask,
2780
- dynamicFanoutMaxItems?: number,
2781
- ): (string | undefined)[] {
2782
- const sessionFiles: (string | undefined)[] = [];
2783
- let flatIndex = 0;
2784
- for (const step of chain) {
2785
- if (isParallelStep(step)) {
2786
- for (const task of step.parallel) {
2787
- sessionFiles.push(sessionFileForTask(task.agent, flatIndex, task.model));
2788
- flatIndex++;
2789
- }
2790
- continue;
2791
- }
2792
- if (isDynamicParallelStep(step)) {
2793
- const maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
2794
- for (let itemIndex = 0; itemIndex < maxItems; itemIndex++) {
2795
- sessionFiles.push(sessionFileForTask(step.parallel.agent, flatIndex, step.parallel.model));
2796
- flatIndex++;
2797
- }
2798
- continue;
2799
- }
2800
- const sequential = step as SequentialStep;
2801
- sessionFiles.push(sessionFileForTask(sequential.agent, flatIndex, sequential.model));
2802
- flatIndex++;
2803
- }
2804
- return sessionFiles;
2805
- }
2806
-
2807
- function collectChainThinkingOverrides(
2808
- chain: ChainStep[],
2809
- thinkingOverrideForTask: ForkThinkingOverrideForTask,
2810
- dynamicFanoutMaxItems?: number,
2811
- ): (AgentConfig["thinking"] | undefined)[] {
2812
- const thinkingOverrides: (AgentConfig["thinking"] | undefined)[] = [];
2813
- let flatIndex = 0;
2814
- for (const step of chain) {
2815
- if (isParallelStep(step)) {
2816
- for (const task of step.parallel) {
2817
- thinkingOverrides.push(thinkingOverrideForTask(task.agent, flatIndex, task.model));
2818
- flatIndex++;
2819
- }
2820
- continue;
2821
- }
2822
- if (isDynamicParallelStep(step)) {
2823
- const maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
2824
- for (let itemIndex = 0; itemIndex < maxItems; itemIndex++) {
2825
- thinkingOverrides.push(thinkingOverrideForTask(step.parallel.agent, flatIndex, step.parallel.model));
2826
- flatIndex++;
2827
- }
2828
- continue;
2829
- }
2830
- const sequential = step as SequentialStep;
2831
- thinkingOverrides.push(thinkingOverrideForTask(sequential.agent, flatIndex, sequential.model));
2832
- flatIndex++;
2833
- }
2834
- return thinkingOverrides;
2835
- }
2836
-
2837
2916
  type StaticLaunchSummary = { agent: string; model?: string; thinking?: string };
2838
2917
 
2839
2918
  function resolveStaticLaunchSummary(input: {
@@ -2919,14 +2998,6 @@ function collectStaticLaunchSummaries(input: {
2919
2998
  return input.params.agent ? [summary(input.params.agent, 0, input.params.model as string | undefined)] : [];
2920
2999
  }
2921
3000
 
2922
- function firstChainAgent(chain: ChainStep[]): string | undefined {
2923
- const first = chain[0];
2924
- if (!first) return undefined;
2925
- if (isParallelStep(first)) return first.parallel[0]?.agent;
2926
- if (isDynamicParallelStep(first)) return first.parallel.agent;
2927
- return (first as SequentialStep).agent;
2928
- }
2929
-
2930
3001
  function firstRawChainTask(chain: ChainStep[]): string | undefined {
2931
3002
  const first = chain[0];
2932
3003
  if (!first) return undefined;
@@ -2977,21 +3048,29 @@ function wrapChainTasksForFork(chain: ChainStep[], contextPolicy: AgentDefaultCo
2977
3048
  });
2978
3049
  }
2979
3050
 
2980
- function preflightForkSessionsForStaticTasks(
3051
+ async function preflightForkSessionsForStaticTasks(
2981
3052
  params: SubagentParamsLike,
2982
3053
  contextPolicy: AgentDefaultContextPolicy,
2983
- sessionFileForTask: ForkSessionFileForTask,
3054
+ prepareSessionForTask: PrepareForkSessionForTask,
2984
3055
  dynamicFanoutMaxItems?: number,
2985
- ): void {
3056
+ ): Promise<void> {
2986
3057
  if (!contextPolicy.usesFork) return;
2987
3058
  if (params.agent) {
2988
- if (shouldForkAgent(contextPolicy, params.agent)) sessionFileForTask(params.agent, 0, params.model);
3059
+ if (shouldForkAgent(contextPolicy, params.agent)) {
3060
+ await prepareSessionForTask(
3061
+ params.agent,
3062
+ 0,
3063
+ params.model,
3064
+ params.modelOrigin === "inherited",
3065
+ params.modelOrigin,
3066
+ );
3067
+ }
2989
3068
  return;
2990
3069
  }
2991
3070
  if (params.tasks) {
2992
- params.tasks.forEach((task, index) => {
2993
- if (shouldForkAgent(contextPolicy, task.agent)) sessionFileForTask(task.agent, index, task.model);
2994
- });
3071
+ for (const [index, task] of params.tasks.entries()) {
3072
+ if (shouldForkAgent(contextPolicy, task.agent)) await prepareSessionForTask(task.agent, index, task.model);
3073
+ }
2995
3074
  return;
2996
3075
  }
2997
3076
  if (!params.chain?.length) return;
@@ -2999,7 +3078,7 @@ function preflightForkSessionsForStaticTasks(
2999
3078
  for (const step of params.chain) {
3000
3079
  if (isParallelStep(step)) {
3001
3080
  for (const task of step.parallel) {
3002
- if (shouldForkAgent(contextPolicy, task.agent)) sessionFileForTask(task.agent, flatIndex, task.model);
3081
+ if (shouldForkAgent(contextPolicy, task.agent)) await prepareSessionForTask(task.agent, flatIndex, task.model);
3003
3082
  flatIndex++;
3004
3083
  }
3005
3084
  continue;
@@ -3007,17 +3086,29 @@ function preflightForkSessionsForStaticTasks(
3007
3086
  if (isDynamicParallelStep(step)) {
3008
3087
  const maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
3009
3088
  if (shouldForkAgent(contextPolicy, step.parallel.agent)) {
3010
- for (let itemIndex = 0; itemIndex < maxItems; itemIndex++) sessionFileForTask(step.parallel.agent, flatIndex + itemIndex, step.parallel.model);
3089
+ for (let itemIndex = 0; itemIndex < maxItems; itemIndex++) await prepareSessionForTask(step.parallel.agent, flatIndex + itemIndex, step.parallel.model);
3011
3090
  }
3012
3091
  flatIndex += maxItems;
3013
3092
  continue;
3014
3093
  }
3015
3094
  const sequential = step as SequentialStep;
3016
- if (shouldForkAgent(contextPolicy, sequential.agent)) sessionFileForTask(sequential.agent, flatIndex, sequential.model);
3095
+ if (shouldForkAgent(contextPolicy, sequential.agent)) await prepareSessionForTask(sequential.agent, flatIndex, sequential.model);
3017
3096
  flatIndex++;
3018
3097
  }
3019
3098
  }
3020
3099
 
3100
+ function importedAsyncRootUsage(completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>): Usage {
3101
+ const totalCost = completed.totalCost;
3102
+ return completed.usage ?? {
3103
+ input: totalCost?.inputTokens ?? 0,
3104
+ output: totalCost?.outputTokens ?? 0,
3105
+ cacheRead: 0,
3106
+ cacheWrite: 0,
3107
+ cost: totalCost?.costUsd ?? 0,
3108
+ turns: 0,
3109
+ };
3110
+ }
3111
+
3021
3112
  async function waitForWorkflowAsyncSingleResult(
3022
3113
  params: SubagentParamsLike,
3023
3114
  launchResult: AgentToolResult<Details>,
@@ -3039,20 +3130,14 @@ async function waitForWorkflowAsyncSingleResult(
3039
3130
  options.signal?.removeEventListener("abort", stopOnAbort);
3040
3131
  }
3041
3132
  fs.rmSync(resultPath, { force: true });
3042
- const totalCost = completed.totalCost;
3133
+ const usage = importedAsyncRootUsage(completed);
3043
3134
  const childResult: SingleResult = omitUndefinedProperties({
3044
3135
  index: 0,
3045
3136
  agent: completed.agent,
3137
+ ...(completed.sessionName ? { sessionName: completed.sessionName } : {}),
3046
3138
  task: options.task,
3047
3139
  exitCode: completed.exitCode,
3048
- usage: {
3049
- input: totalCost?.inputTokens ?? 0,
3050
- output: totalCost?.outputTokens ?? 0,
3051
- cacheRead: 0,
3052
- cacheWrite: 0,
3053
- cost: totalCost?.costUsd ?? 0,
3054
- turns: 0,
3055
- },
3140
+ usage,
3056
3141
  finalOutput: completed.output,
3057
3142
  outputState: completed.output.trim() ? "present" as const : "absent" as const,
3058
3143
  ...(completed.error ? { error: completed.error } : {}),
@@ -3067,9 +3152,13 @@ async function waitForWorkflowAsyncSingleResult(
3067
3152
  ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
3068
3153
  ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
3069
3154
  ...(completed.acceptance ? { acceptance: completed.acceptance } : {}),
3155
+ ...(completed.artifactPaths ? { artifactPaths: completed.artifactPaths } : {}),
3156
+ ...(completed.outputSaveError ? { outputSaveError: completed.outputSaveError } : {}),
3157
+ ...(completed.transcriptPath ? { transcriptPath: completed.transcriptPath } : {}),
3158
+ ...(completed.transcriptError ? { transcriptError: completed.transcriptError } : {}),
3070
3159
  });
3071
3160
  return {
3072
- content: [{ type: "text", text: completed.output || completed.error || `Async workflow child ${options.runId} completed without output.` }],
3161
+ content: [{ type: "text", text: completed.success ? completed.output || completed.error || `Async workflow child ${options.runId} completed without output.` : completed.error || completed.output || `Async workflow child ${options.runId} completed without output.` }],
3073
3162
  ...(completed.success ? {} : { isError: true }),
3074
3163
  details: {
3075
3164
  ...launchResult.details,
@@ -3087,7 +3176,6 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3087
3176
  ctx,
3088
3177
  shareEnabled,
3089
3178
  sessionRoot,
3090
- sessionFileForIndex,
3091
3179
  sessionFileForTask,
3092
3180
  thinkingOverrideForTask,
3093
3181
  artifactConfig,
@@ -3097,6 +3185,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3097
3185
  intercomBridge,
3098
3186
  nestedRoute,
3099
3187
  contextPolicy,
3188
+ unknownAgentDiagnosticContext,
3100
3189
  } = data;
3101
3190
  const hasChain = (params.chain?.length ?? 0) > 0;
3102
3191
  const hasTasks = (params.tasks?.length ?? 0) > 0;
@@ -3123,9 +3212,10 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3123
3212
  modelScope: data.modelScope,
3124
3213
  interactive: ctx.hasUI,
3125
3214
  permissions: deps.config.permissions,
3215
+ childRuntime: deps.childRuntime,
3126
3216
  });
3127
3217
  const availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);
3128
- const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);
3218
+ const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth, deps.childRuntime);
3129
3219
  const currentProvider = parentModel?.provider;
3130
3220
  const controlIntercomTarget = resolveRunLevelIntercomTarget(intercomBridge, contextPolicy);
3131
3221
  const childIntercomTarget = resolveChildIntercomTargetFactory(intercomBridge, contextPolicy, id);
@@ -3135,7 +3225,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3135
3225
  const a = agents.find((x) => x.name === params.agent);
3136
3226
  if (!a) {
3137
3227
  return {
3138
- content: [{ type: "text", text: `Unknown agent: ${params.agent}` }],
3228
+ content: [{ type: "text", text: formatUnknownAgentError(params.agent!, unknownAgentDiagnosticContext) }],
3139
3229
  isError: true,
3140
3230
  details: { mode: "single" as const, results: [] },
3141
3231
  };
@@ -3153,10 +3243,21 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3153
3243
  return buildRequestedModeError(params, `Agent '${a.name}' uses runner.type='${a.runner.type}' and does not support fast mode.`);
3154
3244
  }
3155
3245
  const modelScopes = resolveModelScopesForAgent(data.modelScope, a.name, parentModel);
3246
+ const modelOrigin = resolveModelOrigin({
3247
+ storedOrigin: params.modelOrigin as ModelOrigin | undefined,
3248
+ explicitModel: params.model as string | undefined,
3249
+ agentModel: a.model,
3250
+ parentModel,
3251
+ });
3156
3252
  const modelOverride = a.runner?.type === "external-cli" || a.runner?.type === "external-job"
3157
3253
  ? params.model ?? (externalRunnerWithoutExplicitModel ? undefined : a.model)
3158
- : resolveEffectiveSubagentModel(params.model as string | undefined, a.model, parentModel, availableModels, a.modelProvider ?? currentProvider, modelScopes.length === 0 ? {} : { scope: modelScopes });
3159
- const modelOverrideFromParent = inheritsParentModel(params.model as string | undefined, a.model, parentModel);
3254
+ : resolveEffectiveSubagentModel(params.model as string | undefined, a.model, parentModel, availableModels, a.modelProvider ?? currentProvider, {
3255
+ ...(modelScopes.length === 0 ? {} : { scope: modelScopes }),
3256
+ source: modelOrigin === "explicit" ? "explicit" : "inherited",
3257
+ });
3258
+ const modelOverrideFromParent = modelOrigin === "inherited";
3259
+ const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: a.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
3260
+ if (launchRuleError) return toExecutionErrorResult(params, new Error(launchRuleError), data.contextPolicy.contextSummary);
3160
3261
  const asyncResult = executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
3161
3262
  agent: params.agent!,
3162
3263
  task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(params.task ?? "") : (params.task ?? ""),
@@ -3166,30 +3267,37 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3166
3267
  ctx: asyncCtx,
3167
3268
  availableModels,
3168
3269
  cwd: effectiveCwd,
3270
+ requestedCwd: data.requestedCwd,
3169
3271
  maxOutput: params.maxOutput,
3170
3272
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3171
3273
  artifactConfig,
3172
3274
  shareEnabled,
3173
3275
  activeAsyncCapacity: data.activeAsyncCapacity,
3174
3276
  sessionRoot,
3175
- sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
3277
+ sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
3176
3278
  context: contextPolicy.contextForAgent(params.agent!),
3177
3279
  skills,
3178
3280
  output: effectiveOutput,
3179
3281
  outputMode: effectiveOutputMode,
3282
+ outputClaimPath: params.workflowOutputClaimPath,
3180
3283
  ...(params.reads !== undefined ? { reads: params.reads } : {}),
3181
3284
  outputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),
3182
3285
  modelOverride,
3183
3286
  fast: params.fast,
3184
3287
  modelOverrideFromParent,
3185
- thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
3288
+ modelOrigin,
3289
+ thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
3186
3290
  thinkingCeiling: a.maxThinking,
3187
3291
  maxSubagentDepth,
3188
3292
  waitToolEnabled: deps.waitToolEnabled,
3293
+ waitToolDefaultTimeoutMs: deps.waitToolDefaultTimeoutMs,
3189
3294
  ...(params.worktree === true ? { worktree: true } : {}),
3190
3295
  worktreeSetupHook: deps.config.worktreeSetupHook,
3191
3296
  worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
3192
3297
  worktreeBaseDir: deps.config.worktreeBaseDir,
3298
+ baseRef: params.baseRef,
3299
+ worktreeProvider: deps.config.worktreeProvider,
3300
+ worktreeBranchPrefix: deps.config.worktreeBranchPrefix,
3193
3301
  controlConfig,
3194
3302
  intercomBridge: params.intercomBridge,
3195
3303
  controlIntercomTarget,
@@ -3200,7 +3308,6 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3200
3308
  extensionBindings: params.extensionBindings,
3201
3309
  acceptance: params.acceptance,
3202
3310
  timeoutMs: data.timeoutMs,
3203
- turnBudget: data.turnBudget,
3204
3311
  toolBudget: data.toolBudget,
3205
3312
  usageBudget: data.usageBudget,
3206
3313
  configToolBudget: data.configToolBudget,
@@ -3210,6 +3317,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3210
3317
  runFanoutBudget: data.runFanoutBudget,
3211
3318
  parentWorkflowRunId: params.workflowParentRunId,
3212
3319
  workflowKey: params.workflowKey,
3320
+ lane: params.lane,
3213
3321
  workflowAwaitAsync: params.workflowAwaitAsync,
3214
3322
  }));
3215
3323
  return waitForWorkflowAsyncSingleResult(params, asyncResult, { runId: id, task: params.task ?? "", signal: data.signal, state: deps.state, kill: deps.kill });
@@ -3226,6 +3334,12 @@ function createSingleWorktreeSetup(
3226
3334
  setupHook: ExtensionConfig["worktreeSetupHook"],
3227
3335
  setupHookTimeoutMs: ExtensionConfig["worktreeSetupHookTimeoutMs"],
3228
3336
  baseDir: ExtensionConfig["worktreeBaseDir"],
3337
+ baseRef: string | undefined,
3338
+ provider: ExtensionConfig["worktreeProvider"],
3339
+ branchPrefix: ExtensionConfig["worktreeBranchPrefix"],
3340
+ label?: string,
3341
+ task?: string,
3342
+ beforeCreate?: (setup: WorktreeSetup) => void,
3229
3343
  ): { setup?: WorktreeSetup; errorResult?: AgentToolResult<Details> } {
3230
3344
  if (!enabled) return {};
3231
3345
  try {
@@ -3236,6 +3350,12 @@ function createSingleWorktreeSetup(
3236
3350
  ? { hookPath: setupHook, ...(setupHookTimeoutMs === undefined ? {} : { timeoutMs: setupHookTimeoutMs }) }
3237
3351
  : undefined,
3238
3352
  baseDir,
3353
+ baseRef,
3354
+ provider,
3355
+ branchPrefix,
3356
+ labels: [label],
3357
+ tasks: [task],
3358
+ beforeCreate,
3239
3359
  })),
3240
3360
  };
3241
3361
  } catch (error) {
@@ -3278,10 +3398,33 @@ function workflowChildDefaultOutput(aggregateOutputPath: string | undefined, art
3278
3398
  return path.join(artifactsDir, "outputs", sanitizeRunPathSegment(workflowRunId), `${workflowKey}.md`);
3279
3399
  }
3280
3400
 
3401
+ function workflowHostCommandRunner(input: {
3402
+ workflowCwd: string;
3403
+ artifactsDir: string;
3404
+ workflowRunId: string;
3405
+ claimedOutputPaths: Map<string, string>;
3406
+ producedOutputPaths: Set<string>;
3407
+ authorize?: (key: string, params: WorkflowHostCommandParams) => string | undefined;
3408
+ }) {
3409
+ return async (key: string, params: WorkflowHostCommandParams, signal: AbortSignal): Promise<WorkflowHostCommandResult> => {
3410
+ const authorizationError = input.authorize?.(key, params);
3411
+ if (authorizationError) throw new Error(authorizationError);
3412
+ const defaultOutputPath = path.join(input.artifactsDir, "outputs", sanitizeRunPathSegment(input.workflowRunId), "host", `${sanitizeRunPathSegment(key)}.log`);
3413
+ const outputPath = params.output ? path.resolve(input.workflowCwd, params.output) : defaultOutputPath;
3414
+ const claimPath = resolveWorkflowHostOutputClaimPath(outputPath);
3415
+ const previous = input.claimedOutputPaths.get(claimPath);
3416
+ if (previous) throw new Error(`runs.host('${key}') output path is already claimed by '${previous}': ${outputPath}.`);
3417
+ input.claimedOutputPaths.set(claimPath, `host:${key}`);
3418
+ const result = await executeWorkflowHostCommand({ key, params, cwd: input.workflowCwd, defaultOutputPath, claimedOutputPath: claimPath, signal });
3419
+ input.producedOutputPaths.add(resolveWorkflowHostOutputClaimPath(result.outputPath));
3420
+ return result;
3421
+ };
3422
+ }
3423
+
3281
3424
  function writeWorkflowAggregateOutput(outputPath: string | undefined, text: string, producedChildOutputPaths: ReadonlySet<string>): string | undefined {
3282
3425
  if (!outputPath) return undefined;
3283
3426
  try {
3284
- if (producedChildOutputPaths.has(outputPath)) return undefined;
3427
+ if (producedChildOutputPaths.has(resolveWorkflowHostOutputClaimPath(outputPath))) return undefined;
3285
3428
  fs.mkdirSync(path.dirname(outputPath), { recursive: true });
3286
3429
  fs.writeFileSync(outputPath, text, "utf-8");
3287
3430
  return undefined;
@@ -3352,7 +3495,7 @@ function workflowChildOutputClaims(input: {
3352
3495
  state: SubagentState;
3353
3496
  claimedOutputPaths: Map<string, string>;
3354
3497
  entries: Array<{ key: string; params: Record<string, unknown> }>;
3355
- }): { error?: string; claims?: Map<string, string>; overrides?: Map<string, string> } {
3498
+ }): { error?: string; claims?: Map<string, string>; childClaims?: Map<string, string>; overrides?: Map<string, string> } {
3356
3499
  const resolvedEntries = input.entries.map(({ key, params }) => ({
3357
3500
  key,
3358
3501
  ...resolveWorkflowChildOutputPath({ ...input, key, params }),
@@ -3360,24 +3503,30 @@ function workflowChildOutputClaims(input: {
3360
3503
  const paths = new Map<string, number>();
3361
3504
  for (const claimedPath of input.claimedOutputPaths.keys()) paths.set(claimedPath, 1);
3362
3505
  for (const { path: resolved } of resolvedEntries) {
3363
- if (resolved) paths.set(resolved, (paths.get(resolved) ?? 0) + 1);
3506
+ if (resolved) {
3507
+ const claimPath = resolveWorkflowHostOutputClaimPath(resolved);
3508
+ paths.set(claimPath, (paths.get(claimPath) ?? 0) + 1);
3509
+ }
3364
3510
  }
3365
3511
  const overrides = new Map<string, string>();
3366
3512
  for (const entry of resolvedEntries) {
3367
- if (entry.inherited && entry.path && (paths.get(entry.path) ?? 0) > 1) {
3513
+ if (entry.inherited && entry.path && (paths.get(resolveWorkflowHostOutputClaimPath(entry.path)) ?? 0) > 1) {
3368
3514
  const output = workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.workflowRunId, entry.key);
3369
3515
  overrides.set(entry.key, output);
3370
3516
  entry.path = output;
3371
3517
  }
3372
3518
  }
3373
3519
  const claims = new Map(input.claimedOutputPaths);
3520
+ const childClaims = new Map<string, string>();
3374
3521
  for (const { key, path: resolved } of resolvedEntries) {
3375
3522
  if (!resolved) continue;
3376
- const previous = claims.get(resolved);
3523
+ const claimPath = resolveWorkflowHostOutputClaimPath(resolved);
3524
+ const previous = claims.get(claimPath);
3377
3525
  if (previous) return { error: `Workflow children '${previous}' and '${key}' resolve output to the same path: ${resolved}. Use distinct child output paths.` };
3378
- claims.set(resolved, key);
3526
+ claims.set(claimPath, key);
3527
+ childClaims.set(key, claimPath);
3379
3528
  }
3380
- return { claims, overrides };
3529
+ return { claims, childClaims, overrides };
3381
3530
  }
3382
3531
 
3383
3532
  function applyWorkflowChildOutputClaims(target: Map<string, string>, claims: Map<string, string>): void {
@@ -3399,12 +3548,14 @@ function prepareWorkflowChildLaunchParams(input: {
3399
3548
  agents: AgentConfig[];
3400
3549
  workflowAgentScope?: unknown;
3401
3550
  outputOverride?: string;
3402
- options?: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number; capabilityCeiling?: ResolvedSubagentCapabilityCeiling };
3551
+ outputClaimPath?: string;
3552
+ options?: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; awaitDetachedChild?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number; capabilityCeiling?: ResolvedSubagentCapabilityCeiling };
3403
3553
  }): SubagentParamsLike {
3404
3554
  let childParams = input.childParams;
3405
- if (input.childParams.output === undefined && input.childParams.resume === undefined && input.outputOverride !== undefined) {
3555
+ const usesDefaultOutput = input.childParams.output === undefined && input.childParams.resume === undefined;
3556
+ if (usesDefaultOutput && input.outputOverride !== undefined) {
3406
3557
  childParams = { ...input.childParams, output: input.outputOverride };
3407
- } else if (input.childParams.output === undefined && input.childParams.resume === undefined && input.aggregateOutputPath !== undefined) {
3558
+ } else if (usesDefaultOutput && input.aggregateOutputPath !== undefined) {
3408
3559
  childParams = { ...input.childParams, output: workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.parentWorkflowRunId, input.workflowKey) };
3409
3560
  } else if (input.childParams.resume === undefined) {
3410
3561
  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 });
@@ -3417,7 +3568,7 @@ function prepareWorkflowChildLaunchParams(input: {
3417
3568
  ? resolveAgentName(childParams.agent, discoveredAgents).agent ?? resolveAgentName(childParams.agent, input.agents).agent
3418
3569
  : undefined;
3419
3570
  const externalAsyncRequired = agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job";
3420
- return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, { ...input.options, externalAsyncRequired });
3571
+ return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, { ...input.options, externalAsyncRequired, outputClaimPath: input.outputClaimPath });
3421
3572
  }
3422
3573
 
3423
3574
  function finalizeSingleWorktreeHandoff(input: {
@@ -3427,6 +3578,8 @@ function finalizeSingleWorktreeHandoff(input: {
3427
3578
  cwd: string;
3428
3579
  agent: string;
3429
3580
  result: SingleResult;
3581
+ workflowKey?: string;
3582
+ lane?: import("../../shared/types.ts").WorkflowLaneMetadata;
3430
3583
  }): { suffix: string; reference?: NonNullable<Details["parallelHandoff"]> } {
3431
3584
  const diffsDir = path.join(input.artifactsDir, "worktree-diffs", input.runId);
3432
3585
  const diffs = diffWorktrees(input.worktreeSetup, [input.agent], diffsDir);
@@ -3441,9 +3594,13 @@ function finalizeSingleWorktreeHandoff(input: {
3441
3594
  stepIndex: 0,
3442
3595
  flatStartIndex: 0,
3443
3596
  setup: input.worktreeSetup,
3597
+ 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,
3444
3598
  diffs,
3445
3599
  results: [{
3446
3600
  agent: input.result.agent,
3601
+ ...(input.workflowKey ? { workflowKey: input.workflowKey } : {}),
3602
+ ...(input.workflowKey ? { runId: input.runId } : {}),
3603
+ ...(input.lane ? { lane: input.lane } : {}),
3447
3604
  status: resolveSubagentResultStatus(omitUndefinedProperties({
3448
3605
  exitCode: input.result.exitCode,
3449
3606
  interrupted: input.result.interrupted,
@@ -3489,10 +3646,17 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3489
3646
  artifactConfig,
3490
3647
  artifactsDir,
3491
3648
  onUpdate,
3492
- sessionRoot,
3493
3649
  controlConfig,
3494
3650
  contextPolicy,
3651
+ suppressUnchangedDelegationUpdates,
3495
3652
  } = data;
3653
+ let lane: import("../../shared/types.ts").WorkflowLaneMetadata | undefined;
3654
+ try {
3655
+ lane = normalizeWorkflowLaneMetadata(params.lane, "lane");
3656
+ assertWorkflowLaneKey(lane, params.workflowKey, "lane");
3657
+ } catch (error) {
3658
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "single", results: [] } };
3659
+ }
3496
3660
  const onControlEvent = createForegroundControlNotifier(data, deps);
3497
3661
  const childBridgeActive = intercomBridgeAppliesToAgent(data.intercomBridge, contextPolicy, params.agent!);
3498
3662
  const childIntercomTarget = childBridgeActive ? resolveSubagentIntercomTarget(runId, params.agent!, 0) : undefined;
@@ -3501,7 +3665,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3501
3665
  const agentConfig = agents.find((a) => a.name === params.agent);
3502
3666
  if (!agentConfig) {
3503
3667
  return {
3504
- content: [{ type: "text", text: `Unknown agent: ${params.agent}` }],
3668
+ content: [{ type: "text", text: formatUnknownAgentError(params.agent!, data.unknownAgentDiagnosticContext) }],
3505
3669
  isError: true,
3506
3670
  details: { mode: "single", results: [] },
3507
3671
  };
@@ -3513,26 +3677,38 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3513
3677
  const currentProvider = parentModel?.provider;
3514
3678
  const availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);
3515
3679
  const modelScopes = resolveModelScopesForAgent(data.modelScope, agentConfig.name, parentModel);
3516
- let task = params.task ?? "";
3680
+ let task = typeof params.task === "string" ? params.task : "";
3681
+ const modelOrigin = resolveModelOrigin({
3682
+ storedOrigin: params.modelOrigin as ModelOrigin | undefined,
3683
+ explicitModel: params.model as string | undefined,
3684
+ agentModel: agentConfig.model,
3685
+ parentModel,
3686
+ });
3517
3687
  let modelOverride: string | undefined = resolveEffectiveSubagentModel(
3518
3688
  params.model as string | undefined,
3519
3689
  agentConfig.model,
3520
3690
  parentModel,
3521
3691
  availableModels,
3522
3692
  agentConfig.modelProvider ?? currentProvider,
3523
- modelScopes.length === 0 ? {} : { scope: modelScopes },
3693
+ {
3694
+ ...(modelScopes.length === 0 ? {} : { scope: modelScopes }),
3695
+ source: modelOrigin === "explicit" ? "explicit" : "inherited",
3696
+ },
3524
3697
  );
3525
- const modelOverrideFromParent = inheritsParentModel(params.model as string | undefined, agentConfig.model, parentModel);
3698
+ const modelOverrideFromParent = modelOrigin === "inherited";
3699
+ const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: agentConfig.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
3700
+ if (launchRuleError) return toExecutionErrorResult(params, new Error(launchRuleError), data.contextPolicy.contextSummary);
3526
3701
  let skillOverride: string[] | false | undefined = normalizeSkillInput(params.skill);
3527
3702
  let readsOverride: string[] | false | undefined = params.reads;
3528
3703
  const rawOutput = params.output !== undefined ? params.output : agentConfig.output;
3529
3704
  let effectiveOutput = normalizeSingleOutputOverride(rawOutput, agentConfig.output);
3530
3705
  const effectiveOutputMode = params.outputMode ?? agentConfig.outputMode ?? "inline";
3531
- const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);
3706
+ const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth, deps.childRuntime);
3532
3707
  const maxSubagentDepth = resolveChildMaxSubagentDepth(currentMaxSubagentDepth, agentConfig.maxSubagentDepth);
3533
3708
 
3534
3709
 
3535
3710
  const sourceCwd = effectiveCwd;
3711
+ let pendingHandoff: Details["parallelHandoff"];
3536
3712
  const { setup: worktreeSetup, errorResult: worktreeSetupError } = createSingleWorktreeSetup(
3537
3713
  params.worktree,
3538
3714
  sourceCwd,
@@ -3541,12 +3717,12 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3541
3717
  deps.config.worktreeSetupHook,
3542
3718
  deps.config.worktreeSetupHookTimeoutMs,
3543
3719
  deps.config.worktreeBaseDir,
3544
- );
3545
- if (worktreeSetupError) return worktreeSetupError;
3546
- const singleCwd = worktreeSetup?.worktrees[0]?.agentCwd ?? sourceCwd;
3547
- let pendingHandoff: Details["parallelHandoff"];
3548
- if (worktreeSetup) {
3549
- try {
3720
+ params.baseRef,
3721
+ deps.config.worktreeProvider,
3722
+ deps.config.worktreeBranchPrefix,
3723
+ params.lane?.key ?? params.workflowKey,
3724
+ task,
3725
+ (plannedSetup) => {
3550
3726
  pendingHandoff = writePendingParallelHandoff({
3551
3727
  manifestPath: parallelHandoffPath(artifactsDir, runId),
3552
3728
  runId,
@@ -3555,13 +3731,13 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3555
3731
  cwd: sourceCwd,
3556
3732
  stepIndex: 0,
3557
3733
  flatStartIndex: 0,
3558
- setup: worktreeSetup,
3734
+ setup: plannedSetup,
3735
+ laneBindings: params.workflowKey || lane ? [{ index: 0, taskIndex: 0, ...(params.workflowKey ? { workflowKey: params.workflowKey, runId } : {}), ...(lane ? { lane } : {}) }] : undefined,
3559
3736
  });
3560
- } catch (error) {
3561
- cleanupWorktrees(worktreeSetup);
3562
- return { content: [{ type: "text", text: formatParallelHandoffError(error) }], isError: true, details: { mode: "single", results: [] } };
3563
- }
3564
- }
3737
+ },
3738
+ );
3739
+ if (worktreeSetupError) return worktreeSetupError;
3740
+ const singleCwd = worktreeSetup?.worktrees[0]?.agentCwd ?? sourceCwd;
3565
3741
 
3566
3742
  const authoredTask = task;
3567
3743
  if (shouldForkAgent(contextPolicy, params.agent!)) {
@@ -3575,7 +3751,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3575
3751
  return { content: [{ type: "text", text: validationError }], isError: true, details: { mode: "single", results: [] } };
3576
3752
  }
3577
3753
  const structuredRuntime = params.outputSchema
3578
- ? createStructuredOutputRuntime(params.outputSchema, artifactConfig.enabled ? path.join(artifactsDir, "structured-output", runId) : undefined, { captureAcceptanceReport: params.acceptance !== false })
3754
+ ? createStructuredOutputRuntime(params.outputSchema, artifactConfig.enabled ? path.join(artifactsDir, "structured-output", runId) : undefined, { acceptanceReport: resolveAcceptanceReportMode(params.acceptance) })
3579
3755
  : undefined;
3580
3756
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
3581
3757
  // absolute paths pass through; relative paths resolve against the child cwd.
@@ -3595,9 +3771,10 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3595
3771
  }
3596
3772
  const interruptController = new AbortController();
3597
3773
  let detachForeground: ((reason?: string) => boolean) | undefined;
3774
+ let childSessionControls: ForegroundChildSessionControls | undefined;
3598
3775
  const foregroundControl = deps.state.foregroundControls.get(runId);
3599
3776
  if (foregroundControl) {
3600
- const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent));
3777
+ const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin));
3601
3778
  beginForegroundChild(foregroundControl, omitUndefinedProperties({
3602
3779
  index: 0,
3603
3780
  agent: params.agent!,
@@ -3615,6 +3792,19 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3615
3792
  return true;
3616
3793
  },
3617
3794
  detach: () => detachForeground?.("user request") === true,
3795
+ steer: async (input: ForegroundSteerInput): Promise<ForegroundSteerOutcome> => {
3796
+ if (!childSessionControls) return { state: "failed", reason: CHILD_SESSION_NOT_RUNNING_YET };
3797
+ try {
3798
+ if (input.mode === "follow_up") {
3799
+ await childSessionControls.followUp(input.message);
3800
+ return { state: "queued" };
3801
+ }
3802
+ await childSessionControls.steer(input.message);
3803
+ return { state: "delivered" };
3804
+ } catch (error) {
3805
+ return { state: "failed", reason: error instanceof Error ? error.message : String(error) };
3806
+ }
3807
+ },
3618
3808
  }));
3619
3809
  }
3620
3810
 
@@ -3627,31 +3817,42 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3627
3817
 
3628
3818
  const deadlineAt = data.deadlineAt ?? (data.timeoutMs !== undefined ? Date.now() + data.timeoutMs : undefined);
3629
3819
  let r: Awaited<ReturnType<typeof runSync>> | undefined;
3820
+ let resolveDetachedWorkflowChild: ((result: Awaited<ReturnType<typeof runSync>>) => void) | undefined;
3821
+ const detachedWorkflowChild = params.workflowAwaitDetached === true
3822
+ ? new Promise<Awaited<ReturnType<typeof runSync>>>((resolve) => { resolveDetachedWorkflowChild = resolve; })
3823
+ : undefined;
3630
3824
  try {
3631
- r = await runSync(ctx.cwd, agents, params.agent!, task, compactOptional<Parameters<typeof runSync>[4]>({
3825
+ const launched = await runSync(ctx.cwd, agents, params.agent!, task, compactOptional<Parameters<typeof runSync>[4]>({
3632
3826
  permissions: deps.config.permissions,
3827
+ runtimeSnapshotHost: deps.pi,
3633
3828
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
3634
3829
  llmIntentArbiter: createTaskMutationArbiter(ctx),
3635
- ...workflowForegroundSteeringLaunchOptions(foregroundControl, 0),
3830
+ childRuntime: deps.childRuntime,
3831
+ onChildSession: (controls) => { childSessionControls = controls; },
3636
3832
  context: data.contextPolicy.contextForAgent(params.agent!),
3833
+ unknownAgentDiagnosticContext: data.unknownAgentDiagnosticContext,
3637
3834
  runFanoutBudget: params.runFanoutAdmitted ? data.runFanoutBudget : { ...data.runFanoutBudget, parentPath: `${data.runFanoutBudget.parentPath ? `${data.runFanoutBudget.parentPath}/` : ""}single` },
3638
3835
  cwd: singleCwd,
3836
+ requestedCwd: data.requestedCwd,
3639
3837
  signal,
3640
3838
  interruptSignal: interruptController.signal,
3641
3839
  allowIntercomDetach: agentConfig.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,
3642
3840
  intercomEvents: deps.pi.events,
3643
3841
  runId,
3644
3842
  sessionDir: sessionDirForIndex(0),
3645
- sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
3843
+ sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
3646
3844
  share: shareEnabled,
3647
3845
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3648
3846
  artifactConfig,
3649
3847
  maxOutput: params.maxOutput,
3650
3848
  outputPath,
3849
+ outputClaimPath: params.workflowOutputClaimPath,
3651
3850
  outputMode: effectiveOutputMode,
3652
3851
  maxSubagentDepth,
3653
3852
  waitToolEnabled: deps.waitToolEnabled,
3853
+ waitToolDefaultTimeoutMs: deps.waitToolDefaultTimeoutMs,
3654
3854
  onUpdate: forwardSingleUpdate,
3855
+ suppressUnchangedDelegationUpdates,
3655
3856
  controlConfig,
3656
3857
  onControlEvent,
3657
3858
  intercomSessionName: childIntercomTarget,
@@ -3661,7 +3862,8 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3661
3862
  modelOverride,
3662
3863
  fast: params.fast,
3663
3864
  modelOverrideFromParent,
3664
- thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
3865
+ modelOrigin,
3866
+ thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
3665
3867
  thinkingCeiling: agentConfig.maxThinking,
3666
3868
  extensionBindings: params.extensionBindings,
3667
3869
  availableModels,
@@ -3672,12 +3874,20 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3672
3874
  agentContract: params.agentContract,
3673
3875
  acceptance: params.acceptance,
3674
3876
  acceptanceContext: { mode: "single" },
3877
+ workflowChildPermitLaunch: data.workflowChildPermitLaunch,
3675
3878
  onEffectivePrompt: foregroundControl ? (prompt) => updateLiveEffectivePrompt(foregroundControl, 0, prompt) : undefined,
3676
3879
  onDetachReady: (detach) => {
3677
3880
  detachForeground = detach;
3678
3881
  },
3679
3882
  onDetachedExit: (result) => {
3883
+ if (resolveDetachedWorkflowChild) {
3884
+ resolveDetachedWorkflowChild(result);
3885
+ return;
3886
+ }
3680
3887
  try {
3888
+ if (worktreeSetup) {
3889
+ finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result, workflowKey: params.workflowKey, lane });
3890
+ }
3681
3891
  try {
3682
3892
  updateRememberedForegroundChild(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, index: 0, result, events: deps.pi.events, notify: true });
3683
3893
  } catch {
@@ -3705,18 +3915,17 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3705
3915
  }
3706
3916
  }
3707
3917
  }
3708
- recordRun(params.agent!, cleanTask, result.exitCode, result.progressSummary?.durationMs ?? 0);
3918
+ recordRun(params.agent!, cleanTask, result.exitCode, result.progressSummary?.durationMs ?? 0, result);
3709
3919
  },
3710
3920
  timeoutMs: data.timeoutMs,
3711
3921
  deadlineAt,
3712
3922
  toolTimeoutMs: params.toolTimeoutMs,
3713
3923
  configToolTimeoutMs: data.configToolTimeoutMs,
3714
- turnBudget: data.turnBudget,
3715
- enforceHardTurnLimit: params.enforceHardTurnLimit,
3716
3924
  toolBudget: effectiveToolBudget.toolBudget,
3717
3925
  capabilityCeiling: data.capabilityCeiling,
3718
3926
  allowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,
3719
3927
  }));
3928
+ r = launched.detached && detachedWorkflowChild ? await detachedWorkflowChild : launched;
3720
3929
  } catch (error) {
3721
3930
  if (worktreeSetup) cleanupWorktrees(worktreeSetup);
3722
3931
  throw error;
@@ -3730,14 +3939,14 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3730
3939
  }
3731
3940
  }
3732
3941
  if (!r.detached) {
3733
- recordRun(params.agent!, cleanTask, r.exitCode, r.progressSummary?.durationMs ?? 0);
3942
+ recordRun(params.agent!, cleanTask, r.exitCode, r.progressSummary?.durationMs ?? 0, r);
3734
3943
  }
3735
3944
 
3736
3945
  let worktreeHandoff: ReturnType<typeof finalizeSingleWorktreeHandoff> | undefined;
3737
3946
  if (worktreeSetup) {
3738
3947
  worktreeHandoff = r.detached
3739
3948
  ? { suffix: pendingHandoff ? formatParallelHandoffReference(pendingHandoff) : "", reference: pendingHandoff }
3740
- : finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result: r });
3949
+ : finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result: r, workflowKey: params.workflowKey, lane });
3741
3950
  }
3742
3951
 
3743
3952
  if (r.progress) allProgress.push(r.progress);
@@ -3766,7 +3975,6 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3766
3975
  runId,
3767
3976
  timeoutMs: data.timeoutMs,
3768
3977
  results: [r],
3769
- ...(data.turnBudget ? { turnBudget: data.turnBudget } : {}),
3770
3978
  ...(effectiveToolBudget.toolBudget ? { toolBudget: effectiveToolBudget.toolBudget } : {}),
3771
3979
  progress: params.includeProgress ? allProgress : undefined,
3772
3980
  artifacts: allArtifactPaths.length ? { dir: artifactsDir, files: allArtifactPaths } : undefined,
@@ -3776,7 +3984,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3776
3984
  usageBudget: usageBudgetState(data.usageBudget, totalCost),
3777
3985
  ...(worktreeHandoff?.reference ? { parallelHandoff: worktreeHandoff.reference } : {}),
3778
3986
  }));
3779
- rememberForegroundRun(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: details.results, extensionBindings: params.extensionBindings });
3987
+ rememberForegroundRun(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: details.results, params, effectiveOutput, effectiveOutputMode, extensionBindings: params.extensionBindings });
3780
3988
 
3781
3989
  const suppressRoutineResultIntercom = shouldSuppressRoutineResultIntercom({ suppressRoutineResultIntercom: params.suppressRoutineResultIntercom, results: [r] });
3782
3990
  if (!r.detached && !r.interrupted && !suppressRoutineResultIntercom) {
@@ -3802,11 +4010,11 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3802
4010
  const worktreeSuffix = worktreeHandoff?.suffix ? `\n\n${worktreeHandoff.suffix}` : "";
3803
4011
  if (r.detached) {
3804
4012
  const statusRecovery = `subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
3805
- const blockingRecovery = `subagent_wait({ id: "${runId}" }). Use ${statusRecovery}`;
4013
+ const blockingRecovery = `bg_wait({ id: "${runId}" }). Use ${statusRecovery}`;
3806
4014
  const message = r.detachedReason === "intercom coordination"
3807
4015
  ? `Detached for intercom coordination: ${params.agent}. Reply to the supervisor request first, then wait with ${blockingRecovery}`
3808
4016
  : r.detachedReason === "user request"
3809
- ? `Detached at user request: ${params.agent}. The child continues independently. Register a completion wake-up with subagent_wait({ id: "${runId}", nonBlocking: true }), or use ${statusRecovery}`
4017
+ ? `Detached at user request: ${params.agent}. The child continues independently. Register a completion wake-up with bg_wait({ id: "${runId}", nonBlocking: true }), or use ${statusRecovery}`
3810
4018
  : `Detached before task completion: ${params.agent}. Wait with ${blockingRecovery}`;
3811
4019
  return {
3812
4020
  content: [{ type: "text", text: `${message}${worktreeSuffix}` }],
@@ -3851,7 +4059,7 @@ function duplicateSubagentCallResult(params: SubagentParamsLike): AgentToolResul
3851
4059
  };
3852
4060
  }
3853
4061
 
3854
- const workflowLaunchObservers = new WeakMap<object, (launch: { agent: string; sessionFile?: string; async: boolean; runId?: string }) => void>();
4062
+ const workflowLaunchObservers = new WeakMap<object, (launch: { agent: string; sessionName?: string; sessionFile?: string; async: boolean; runId?: string }) => void>();
3855
4063
 
3856
4064
  /**
3857
4065
  * Terminal-mission retention can remove a mission while its children still
@@ -3923,17 +4131,29 @@ export function bindMissionWorkflowChildAsyncLaunch(
3923
4131
  function workflowChildResult(
3924
4132
  key: string,
3925
4133
  result: AgentToolResult<Details>,
3926
- childParams: Record<string, unknown> = {},
4134
+ childParams: SubagentParamsLike | Record<string, unknown> = {},
3927
4135
  resumeState?: SubagentState,
4136
+ forcedTerminalOutcome?: WorkflowTerminalOutcome,
3928
4137
  ): WorkflowScriptChildResult {
3929
4138
  const receiptOutput = result.content.map((part) => part.type === "text" ? part.text : "").filter(Boolean).join("\n");
3930
4139
  const output = result.details.results.length === 1 && result.details.results[0]?.finalOutput !== undefined
3931
4140
  ? result.details.results[0].finalOutput
3932
4141
  : receiptOutput;
4142
+ const childError = result.details.results.map((child) => child.error).find((error): error is string => Boolean(error));
4143
+ const failureError = childError && receiptOutput && receiptOutput !== childError
4144
+ ? `${childError}\n\n${receiptOutput}`
4145
+ : childError || receiptOutput || output || "Child run failed.";
3933
4146
  const detached = result.details.results.some((child) => child.detached);
3934
4147
  const interrupted = result.details.results.some((child) => child.interrupted);
3935
4148
  const stopped = result.details.results.some((child) => child.stopped);
3936
- const ok = result.isError !== true && !detached && !interrupted && !stopped;
4149
+ const terminalOutcome = forcedTerminalOutcome
4150
+ ?? (result.details.results.some((child) => child.timedOut)
4151
+ ? { state: "partial" as const, reason: "timeout" as const }
4152
+ : result.details.usageBudget?.exhausted || result.details.results.some((child) => child.turnBudgetExceeded || child.toolBudgetBlocked)
4153
+ ? { state: "partial" as const, reason: "budget_exhausted" as const }
4154
+ : undefined);
4155
+ const acceptanceRecovery = result.details.results.find((child) => child.acceptance?.recovery)?.acceptance?.recovery;
4156
+ const ok = result.isError !== true && !detached && !interrupted && !stopped && acceptanceRecovery === undefined;
3937
4157
  const artifactPaths = new Set<string>();
3938
4158
  if (result.details.asyncDir) artifactPaths.add(result.details.asyncDir);
3939
4159
  if (result.details.parallelHandoff?.path) artifactPaths.add(result.details.parallelHandoff.path);
@@ -3965,13 +4185,25 @@ function workflowChildResult(
3965
4185
  const continuationRunIds = [...new Set([resumeSourceRunId, runId].filter((value): value is string => Boolean(value)))];
3966
4186
  const outputReference = result.details.results.find((child) => child.savedOutputPath)?.savedOutputPath
3967
4187
  ?? result.details.results.find((child) => child.outputReference?.path)?.outputReference?.path;
4188
+ const outputPathMapping = typeof childParams.task === "string" ? outputPathMappingFromTask(childParams.task, outputReference) : undefined;
4189
+ const externalResult = result.details.results.length === 1 && result.details.results[0]?.runner?.type === "external-cli" ? result.details.results[0] : undefined;
4190
+ const externalStatus = result.details.asyncDir ? readStatus(result.details.asyncDir) : undefined;
4191
+ const externalStatusStep = externalStatus?.steps?.length === 1 && externalStatus.steps[0]?.runner?.type === "external-cli" ? externalStatus.steps[0] : undefined;
4192
+ const externalRunner = normalizeExternalCliRunnerStatus(externalResult?.runner ?? externalStatusStep?.runner);
4193
+ const externalProcess = externalResult?.externalProcess ?? externalStatusStep?.externalProcess;
4194
+ const externalAdapter = externalRunner ? externalCliReceiptMetadata({ runner: externalRunner, externalProcess, outputReference }) : undefined;
4195
+ if (externalAdapter) resumability = { state: "not-resumable", reason: externalAdapter.nonResumableReason };
4196
+ const lane = normalizeWorkflowLaneMetadata(childParams.lane, `workflow child '${key}'.lane`);
4197
+ assertWorkflowLaneKey(lane, key, `workflow child '${key}'.lane`);
3968
4198
  return {
3969
4199
  key,
3970
4200
  ok,
4201
+ ...(lane ? { lane } : {}),
4202
+ ...(terminalOutcome ? { terminalOutcome } : {}),
3971
4203
  ...(resolvedAgents.length === 1 ? { agent: resolvedAgents[0] } : {}),
3972
4204
  ...(runId ? { runId } : {}),
3973
4205
  output,
3974
- ...(!ok ? { error: receiptOutput || output || "Child run failed." } : {}),
4206
+ ...(!ok ? { error: failureError } : {}),
3975
4207
  ...(detached ? { detached: true } : {}),
3976
4208
  ...(interrupted ? { interrupted: true } : {}),
3977
4209
  ...(stopped ? { stopped: true } : {}),
@@ -3979,6 +4211,9 @@ function workflowChildResult(
3979
4211
  ...(requestedContext ? { requestedContext } : {}),
3980
4212
  ...(resolvedContext ? { resolvedContext } : {}),
3981
4213
  ...(outputReference ? { outputReference } : {}),
4214
+ ...(acceptanceRecovery ? { recovery: acceptanceRecovery } : {}),
4215
+ ...(outputPathMapping ? { outputPathMapping } : {}),
4216
+ ...(externalAdapter ? { externalAdapter } : {}),
3982
4217
  resumability,
3983
4218
  continuation: { runIds: continuationRunIds },
3984
4219
  artifactPaths: [...artifactPaths],
@@ -3986,6 +4221,28 @@ function workflowChildResult(
3986
4221
  };
3987
4222
  }
3988
4223
 
4224
+ function workflowChildAccountingFields(child: WorkflowScriptChildResult): { usage?: Usage; sessionFile?: string; recovery?: import("../../shared/types.ts").AcceptanceRecoveryMetadata } {
4225
+ if (!child.results?.length) return {};
4226
+ const usage = sumResultsUsage(child.results);
4227
+ const sessionFile = child.results.find((result) => result.sessionFile)?.sessionFile;
4228
+ return {
4229
+ ...(usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0 ? { usage } : {}),
4230
+ ...(sessionFile ? { sessionFile } : {}),
4231
+ ...(child.recovery ? { recovery: child.recovery } : {}),
4232
+ };
4233
+ }
4234
+
4235
+ function workflowOutputPathMappingSummary(children: WorkflowScriptChildResult[]): string {
4236
+ const mappings = children.flatMap((child) => child.outputPathMapping
4237
+ ? [`'${child.key}': requested ${child.outputPathMapping.requestedPath} -> saved ${child.outputPathMapping.savedPath}`]
4238
+ : []);
4239
+ return mappings.length > 0 ? ` Output path mappings: ${mappings.join("; ")}.` : "";
4240
+ }
4241
+
4242
+ function workflowDetailsResults(children: WorkflowScriptChildResult[]): SingleResult[] {
4243
+ return children.flatMap((child) => (child.results ?? []).map((result) => result.workflowKey ? result : { ...result, workflowKey: child.key }));
4244
+ }
4245
+
3989
4246
  function workflowSteerReceipt(key: string, result: AgentToolResult<Details>): WorkflowSteerResult {
3990
4247
  const steering = result.details.steering;
3991
4248
  const error = result.content.map((part) => part.type === "text" ? part.text : "").filter(Boolean).join("\n") || undefined;
@@ -4003,29 +4260,124 @@ function workflowSteerReceipt(key: string, result: AgentToolResult<Details>): Wo
4003
4260
  };
4004
4261
  }
4005
4262
 
4263
+ const CHILD_SESSION_NOT_RUNNING_YET = "Child session is not running yet.";
4264
+ const MAX_WORKFLOW_RESUME_HINT_BYTES = 1024;
4265
+ const MAX_WORKFLOW_CHILD_RUN_ID_BYTES = 256;
4266
+ const WORKFLOW_RESUME_HINT_PARENT_STATES = new Set(["complete", "failed", "partial"]);
4267
+ const WORKFLOW_STEP_STATES = new Set(["pending", "running", "complete", "completed", "failed", "partial", "paused", "stopped", "rejected"]);
4268
+
4269
+ function isSafeWorkflowChildRunId(value: unknown): value is string {
4270
+ if (typeof value !== "string") return false;
4271
+ const runId = value.trim();
4272
+ return value === runId
4273
+ && Boolean(runId)
4274
+ && Buffer.byteLength(runId, "utf8") <= MAX_WORKFLOW_CHILD_RUN_ID_BYTES
4275
+ && path.basename(runId) === runId
4276
+ && path.win32.basename(runId) === runId
4277
+ && !/[\\/]/.test(runId)
4278
+ && !runId.includes("..")
4279
+ && !/[\u0000-\u001f\u007f]/.test(runId);
4280
+ }
4281
+
4282
+ function isMissingWorkflowReceiptDiagnostic(error: unknown, workflowRunId: string): error is Error {
4283
+ return error instanceof Error
4284
+ && error.message.startsWith(`Workflow receipt '${workflowRunId}' is not available because the workflow may still be active or terminal receipt writing failed.`);
4285
+ }
4286
+
4287
+ function missingWorkflowReceiptResumeHint(reference: WorkflowReceiptResumeReference, state: SubagentState): string | undefined {
4288
+ try {
4289
+ if (!state.currentSessionId) return undefined;
4290
+ const workflowRunId = reference.workflowRunId.trim();
4291
+ const workflowStatus = readStatus(path.join(DIRS.async, workflowRunId));
4292
+ if (!workflowStatus
4293
+ || workflowStatus.runId !== workflowRunId
4294
+ || workflowStatus.mode !== "workflow"
4295
+ || workflowStatus.sessionId !== state.currentSessionId
4296
+ || typeof workflowStatus.startedAt !== "number"
4297
+ || !Number.isFinite(workflowStatus.startedAt)
4298
+ || !WORKFLOW_RESUME_HINT_PARENT_STATES.has(workflowStatus.state)
4299
+ || !Array.isArray(workflowStatus.steps)
4300
+ || workflowStatus.steps.some((step) => {
4301
+ if (!step || typeof step !== "object" || Array.isArray(step)) return true;
4302
+ const record = step as Record<string, unknown>;
4303
+ return typeof record.agent !== "string"
4304
+ || typeof record.status !== "string"
4305
+ || !WORKFLOW_STEP_STATES.has(record.status)
4306
+ || (record.workflowKey !== undefined && typeof record.workflowKey !== "string")
4307
+ || (record.runId !== undefined && typeof record.runId !== "string");
4308
+ })) return undefined;
4309
+ const matchingSteps = workflowStatus.steps.filter((step) => step.workflowKey === reference.key);
4310
+ if (matchingSteps.length !== 1) return undefined;
4311
+ const childRunId = matchingSteps[0]?.runId;
4312
+ if (!isSafeWorkflowChildRunId(childRunId)) return undefined;
4313
+
4314
+ const workflowChildren = parseWorkflowChildSummary(workflowStatus.workflowChildren);
4315
+ if (workflowChildren) {
4316
+ if (workflowChildren.workflowRunId !== workflowRunId) return undefined;
4317
+ const matchingChildren = workflowChildren.children.filter((child) => child.childId === reference.key);
4318
+ if (matchingChildren.length > 1 || (workflowChildren.inventoryComplete && matchingChildren.length !== 1)) return undefined;
4319
+ if (matchingChildren.length === 1 && matchingChildren[0]?.runId !== childRunId) return undefined;
4320
+ }
4321
+
4322
+ const target = resolveResumeTarget({ id: childRunId }, state, { asyncRequireSessionFile: true, exactOnly: true });
4323
+ if (target.kind !== "revive") return undefined;
4324
+ const hint = `Direct resumable child for workflow key '${reference.key}': subagent({ action: "resume", id: ${JSON.stringify(childRunId)}, message: "..." })`;
4325
+ return Buffer.byteLength(hint, "utf8") <= MAX_WORKFLOW_RESUME_HINT_BYTES ? hint : undefined;
4326
+ } catch {
4327
+ return undefined;
4328
+ }
4329
+ }
4330
+
4006
4331
  function resolveKeyedWorkflowResume(
4007
4332
  reference: WorkflowReceiptResumeReference,
4008
4333
  state: SubagentState,
4009
4334
  ): { runId: string; runIds: string[] } {
4010
- const entry = resolveWorkflowReceiptResumeEntry({
4011
- reference,
4012
- asyncDirRoot: DIRS.async,
4013
- assertResumable(runId) {
4014
- const target = resolveResumeTarget({ id: runId }, state, { asyncRequireSessionFile: true, exactOnly: true });
4015
- if (target.kind !== "revive") throw new Error(`Workflow receipt child '${reference.key}' latest run '${runId}' is still running.`);
4016
- },
4017
- });
4018
- const runId = entry.latestRunId;
4019
- if (!runId) throw new Error(`Workflow receipt child '${reference.key}' has no retained run id.`);
4020
- return { runId, runIds: entry.continuation.runIds };
4335
+ try {
4336
+ const entry = resolveWorkflowReceiptResumeEntry({
4337
+ reference,
4338
+ asyncDirRoot: DIRS.async,
4339
+ assertResumable(runId) {
4340
+ const target = resolveResumeTarget({ id: runId }, state, { asyncRequireSessionFile: true, exactOnly: true });
4341
+ if (target.kind !== "revive") throw new Error(`Workflow receipt child '${reference.key}' latest run '${runId}' is still running.`);
4342
+ },
4343
+ });
4344
+ const runId = entry.latestRunId;
4345
+ if (!runId) throw new Error(`Workflow receipt child '${reference.key}' has no retained run id.`);
4346
+ return { runId, runIds: entry.continuation.runIds };
4347
+ } catch (error) {
4348
+ const workflowRunId = reference.workflowRunId.trim();
4349
+ if (isMissingWorkflowReceiptDiagnostic(error, workflowRunId)) {
4350
+ const hint = missingWorkflowReceiptResumeHint(reference, state);
4351
+ if (hint) throw new Error(`${error.message} ${hint}`, { cause: error });
4352
+ }
4353
+ throw error;
4354
+ }
4021
4355
  }
4022
4356
 
4023
4357
  function terminalWorkflowReceipt(
4024
4358
  workflowRunId: string,
4025
4359
  state: WorkflowReceiptState,
4026
4360
  children: WorkflowScriptChildResult[],
4361
+ workflowChildren?: WorkflowReceipt["workflowChildren"],
4362
+ terminalOutcome?: WorkflowTerminalOutcome,
4363
+ hostSteps?: WorkflowReceipt["hostSteps"],
4364
+ resource?: WorkflowReceipt["resource"],
4027
4365
  ): WorkflowReceipt {
4028
- return buildWorkflowReceipt({ workflowRunId, state, children });
4366
+ return buildWorkflowReceipt({ workflowRunId, state, children, workflowChildren, terminalOutcome, hostSteps, resource });
4367
+ }
4368
+
4369
+ function workflowFailureTerminalOutcome(error: unknown, _children: WorkflowScriptChildResult[], usageBudget: ReturnType<typeof usageBudgetState>): WorkflowTerminalOutcome | undefined {
4370
+ if (usageBudget?.exhausted) return { state: "partial", reason: "budget_exhausted" };
4371
+ return error instanceof WorkflowScriptError && error.errorKind === "timeout" ? { state: "partial", reason: "timeout" } : undefined;
4372
+ }
4373
+
4374
+ function workflowFailureMessage(error: unknown, workflowRunId: string, children: WorkflowScriptChildResult[]): string {
4375
+ const text = error instanceof Error ? error.message : String(error);
4376
+ const validationPrefix = "workflowScript validation failed before child launch; no children launched.";
4377
+ if (children.length === 0 && text.includes(validationPrefix)) {
4378
+ return `Workflow '${workflowRunId}' validation failed before child launch; no children launched.${text.slice(text.indexOf(validationPrefix) + validationPrefix.length)}`;
4379
+ }
4380
+ return text;
4029
4381
  }
4030
4382
 
4031
4383
  export async function steerWorkflowChildByKey(input: {
@@ -4044,7 +4396,6 @@ export async function steerWorkflowChildByKey(input: {
4044
4396
  while (true) {
4045
4397
  const control = [...input.state.foregroundControls.values()].find((candidate) => candidate.parentWorkflowRunId === input.workflowRunId
4046
4398
  && candidate.workflowKey === input.key
4047
- && Boolean(candidate.workflowSteeringDir)
4048
4399
  && (candidate.activeChildren?.size ?? 0) > 0);
4049
4400
  if (control) {
4050
4401
  const result = await steerWorkflowForegroundTarget({
@@ -4052,10 +4403,9 @@ export async function steerWorkflowChildByKey(input: {
4052
4403
  message: input.message,
4053
4404
  mode: input.options.mode,
4054
4405
  index: input.options.index,
4055
- ackTimeoutMs: Math.max(1, deadline - Date.now()),
4056
- signal: input.signal,
4057
4406
  });
4058
- return workflowSteerReceipt(input.key, result);
4407
+ // The control registers before its child session exists; keep polling until the steer can route.
4408
+ if (!result.details.steering?.targets.some((target) => target.reason === CHILD_SESSION_NOT_RUNNING_YET) || Date.now() >= deadline) return workflowSteerReceipt(input.key, result);
4059
4409
  }
4060
4410
 
4061
4411
  const workflowStatus = readStatus(path.join(asyncDirRoot, input.workflowRunId));
@@ -4068,6 +4418,8 @@ export async function steerWorkflowChildByKey(input: {
4068
4418
  return { key: input.key, state: "missed", error: `Workflow child '${input.key}' is ${childStatus.state}.` };
4069
4419
  }
4070
4420
  if (childStatus) {
4421
+ const unsupported = externalRunnerControlError(asyncDir, "steer");
4422
+ if (unsupported) return workflowSteerReceipt(input.key, unsupported);
4071
4423
  const result = await steerAsyncRun({
4072
4424
  state: input.state,
4073
4425
  runId: childRunId,
@@ -4099,9 +4451,15 @@ export function prepareWorkflowLaunchParams(
4099
4451
  childParams: Record<string, unknown>,
4100
4452
  parentWorkflowRunId: string,
4101
4453
  workflowKey: string,
4102
- options: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number; externalAsyncRequired?: boolean; capabilityCeiling?: ResolvedSubagentCapabilityCeiling } = {},
4454
+ options: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; awaitDetachedChild?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number; externalAsyncRequired?: boolean; capabilityCeiling?: ResolvedSubagentCapabilityCeiling; outputClaimPath?: string } = {},
4103
4455
  ): SubagentParamsLike {
4456
+ const { globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowDefaultsWithoutCapacity } = workflowDefaults;
4457
+ const { globalConcurrencyLimit: _childGlobalConcurrencyLimit, maxSubagentSpawnsPerRun: _childMaxSubagentSpawnsPerRun, ...childParamsWithoutCapacity } = childParams;
4458
+ workflowDefaults = workflowDefaultsWithoutCapacity;
4459
+ childParams = childParamsWithoutCapacity;
4104
4460
  const capabilityCeiling = intersectSubagentCapabilityCeilings(workflowDefaults.capabilityCeiling, options.capabilityCeiling);
4461
+ const lane = normalizeWorkflowLaneMetadata(Object.hasOwn(childParams, "lane") ? childParams.lane : workflowDefaults.lane, `workflow child '${workflowKey}'.lane`);
4462
+ assertWorkflowLaneKey(lane, workflowKey, `workflow child '${workflowKey}'.lane`);
4105
4463
  const parentTimeoutMs = options.parentDeadlineAt === undefined
4106
4464
  || childParams.timeoutMs !== undefined
4107
4465
  || childParams.maxRuntimeMs !== undefined
@@ -4117,10 +4475,20 @@ export function prepareWorkflowLaunchParams(
4117
4475
  throw new Error("gate is not supported with retained resume; resume uses the retained child contract.");
4118
4476
  }
4119
4477
  const timeoutMs = childParams.timeoutMs ?? childParams.maxRuntimeMs ?? workflowDefaults.timeoutMs ?? workflowDefaults.maxRuntimeMs;
4120
- const turnBudget = childParams.turnBudget ?? workflowDefaults.turnBudget;
4121
4478
  const toolBudget = childParams.toolBudget ?? workflowDefaults.toolBudget;
4122
4479
  const intercomBridge = childParams.intercomBridge ?? workflowDefaults.intercomBridge;
4123
4480
  const worktree = childParams.worktree ?? workflowDefaults.worktree;
4481
+ const baseRef = Object.hasOwn(childParams, "baseRef") ? childParams.baseRef : undefined;
4482
+ const outputSchema = Object.hasOwn(childParams, "outputSchema") ? childParams.outputSchema : workflowDefaults.outputSchema;
4483
+ if (outputSchema !== undefined) assertJsonSchemaObject(outputSchema, "outputSchema");
4484
+ const agentContract = Object.hasOwn(childParams, "agentContract") ? childParams.agentContract : workflowDefaults.agentContract;
4485
+ if (agentContract !== undefined && !isAgentContractV1(agentContract as AgentContract)) throw new Error("agentContract must be { version: 1 }.");
4486
+ const acceptance = Object.hasOwn(childParams, "acceptance") ? childParams.acceptance : workflowDefaults.acceptance;
4487
+ const output = Object.hasOwn(childParams, "output") ? childParams.output : workflowDefaults.output;
4488
+ if (output !== undefined && typeof output !== "string" && typeof output !== "boolean") throw new Error("output must be a path string or boolean.");
4489
+ const outputMode = Object.hasOwn(childParams, "outputMode") ? childParams.outputMode : workflowDefaults.outputMode;
4490
+ if (outputMode !== undefined && outputMode !== "inline" && outputMode !== "file-only") throw new Error("outputMode must be 'inline' or 'file-only'.");
4491
+ const control = mergeWorkflowControlOverrides(workflowDefaults.control, childParams.control as ControlConfig | undefined);
4124
4492
  return {
4125
4493
  action: "resume",
4126
4494
  id: childParams.resume.trim(),
@@ -4128,24 +4496,36 @@ export function prepareWorkflowLaunchParams(
4128
4496
  message: typeof childParams.task === "string" ? childParams.task.trim() : "",
4129
4497
  workflowParentRunId: parentWorkflowRunId,
4130
4498
  workflowKey,
4499
+ ...(lane ? { lane } : {}),
4131
4500
  ...(worktree !== undefined ? { worktree: worktree as boolean } : {}),
4501
+ ...(baseRef !== undefined ? { baseRef: baseRef as string } : {}),
4502
+ ...(outputSchema !== undefined ? { outputSchema: outputSchema as JsonSchemaObject } : {}),
4503
+ ...(agentContract !== undefined ? { agentContract: agentContract as AgentContract } : {}),
4504
+ ...(acceptance !== undefined ? { acceptance: acceptance as AcceptanceInput } : {}),
4505
+ ...(output !== undefined ? { output: output as string | boolean } : {}),
4506
+ ...(outputMode !== undefined ? { outputMode: outputMode as OutputMode } : {}),
4132
4507
  ...(options.runFanoutBudget ? { runFanoutBudget: { ...options.runFanoutBudget, parentPath: `${options.runFanoutBudget.parentPath ? `${options.runFanoutBudget.parentPath}/` : ""}workflow[${workflowKey}]` } } : {}),
4133
4508
  ...(options.missionDetached ? { mission: false } : {}),
4134
4509
  ...(timeoutMs !== undefined ? { timeoutMs: timeoutMs as number } : {}),
4135
- ...(turnBudget !== undefined ? { turnBudget: turnBudget as TurnBudgetConfig } : {}),
4136
4510
  ...(toolBudget !== undefined ? { toolBudget: toolBudget as ToolBudgetConfig } : {}),
4511
+ ...(control !== undefined ? { control } : {}),
4137
4512
  ...(intercomBridge !== undefined ? { intercomBridge: intercomBridge as IntercomBridgeConfig } : {}),
4138
4513
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
4139
4514
  };
4140
4515
  }
4516
+ const control = mergeWorkflowControlOverrides(workflowDefaults.control, childParams.control as ControlConfig | undefined);
4141
4517
  const launchParams = {
4142
4518
  ...workflowDefaults,
4143
4519
  async: options.externalAsyncRequired === true && childParams.async === undefined && workflowDefaults.async === undefined ? true : false,
4144
4520
  ...childParams,
4521
+ ...(control !== undefined ? { control } : {}),
4145
4522
  ...(options.externalAsyncRequired === true && childParams.async === undefined && workflowDefaults.async === undefined ? { workflowAwaitAsync: true } : {}),
4146
4523
  ...(options.missionDetached ? { mission: false } : {}),
4147
4524
  workflowParentRunId: parentWorkflowRunId,
4148
4525
  workflowKey,
4526
+ ...(options.outputClaimPath ? { workflowOutputClaimPath: options.outputClaimPath } : {}),
4527
+ ...(options.awaitDetachedChild ? { workflowAwaitDetached: true } : {}),
4528
+ ...(lane ? { lane } : {}),
4149
4529
  ...(parentTimeoutMs !== undefined ? { workflowParentDeadlineAt: options.parentDeadlineAt } : {}),
4150
4530
  ...(options.runFanoutBudget ? { runFanoutBudget: { ...options.runFanoutBudget, parentPath: `${options.runFanoutBudget.parentPath ? `${options.runFanoutBudget.parentPath}/` : ""}workflow[${workflowKey}]` } } : {}),
4151
4531
  ...(options.suppressRoutineResultIntercom ? { suppressRoutineResultIntercom: true } : {}),
@@ -4157,6 +4537,17 @@ export function prepareWorkflowLaunchParams(
4157
4537
  return normalizedGate.params;
4158
4538
  }
4159
4539
 
4540
+ function mergeWorkflowControlOverrides(workflowControl: ControlConfig | undefined, childControl: ControlConfig | undefined): ControlConfig | undefined {
4541
+ if (childControl === undefined) return workflowControl;
4542
+ if (workflowControl === undefined) return childControl;
4543
+ return { ...workflowControl, ...childControl };
4544
+ }
4545
+
4546
+ export function resolveRevivalControlConfig(input: { globalConfig?: ControlConfig; requestedControl?: ControlConfig; recoveryControlConfig?: ResolvedControlConfig }): ResolvedControlConfig {
4547
+ if (input.requestedControl === undefined) return input.recoveryControlConfig ?? resolveControlConfig(input.globalConfig, undefined);
4548
+ return resolveControlConfig(input.recoveryControlConfig ?? input.globalConfig, input.requestedControl);
4549
+ }
4550
+
4160
4551
  type GateParamsNormalizationResult =
4161
4552
  | { ok: true; params: SubagentParamsLike }
4162
4553
  | { ok: false; error: string };
@@ -4182,15 +4573,101 @@ function formatWorkflowValue(value: unknown): string {
4182
4573
  }
4183
4574
  }
4184
4575
 
4576
+ function buildWorkflowLaneGraph(runId: string, lanes: WorkflowLanePlan[], existing?: WorkflowGraphSnapshot): WorkflowGraphSnapshot {
4577
+ const plannedIds = new Set(lanes.flatMap((lane) => lane.stages.map((stage) => stage.generatedKey)));
4578
+ const previousById = new Map((existing?.nodes ?? []).map((node) => [node.id, node]));
4579
+ const nodes: WorkflowGraphNode[] = [];
4580
+ const phases: WorkflowGraphSnapshot["phases"] = [];
4581
+ let flatIndex = 0;
4582
+ for (const lane of lanes) {
4583
+ const nodeIds: string[] = [];
4584
+ for (const [stageIndex, stage] of lane.stages.entries()) {
4585
+ const previous = previousById.get(stage.generatedKey);
4586
+ const outputName = stage.outputName || previous?.outputName;
4587
+ const structured = stage.structured ?? previous?.structured;
4588
+ const node: WorkflowGraphNode = {
4589
+ id: stage.generatedKey,
4590
+ kind: "step",
4591
+ agent: stage.agent ?? previous?.agent,
4592
+ phase: stage.phase ?? previous?.phase,
4593
+ label: stage.label ?? stage.key,
4594
+ status: previous?.status ?? (stageIndex === 0 ? "running" : "pending"),
4595
+ flatIndex,
4596
+ stepIndex: flatIndex,
4597
+ ...(outputName ? { outputName } : {}),
4598
+ ...(structured !== undefined ? { structured } : {}),
4599
+ ...(previous?.acceptanceStatus ? { acceptanceStatus: previous.acceptanceStatus } : {}),
4600
+ ...(previous?.error ? { error: previous.error } : {}),
4601
+ };
4602
+ nodes.push(node);
4603
+ nodeIds.push(node.id);
4604
+ flatIndex++;
4605
+ }
4606
+ if (nodeIds.length > 0) phases.push({ title: lane.key, nodeIds });
4607
+ }
4608
+ for (const node of existing?.nodes ?? []) {
4609
+ if (!plannedIds.has(node.id)) nodes.push(node);
4610
+ }
4611
+ for (const phase of existing?.phases ?? []) {
4612
+ const retainedNodeIds = phase.nodeIds.filter((nodeId) => !plannedIds.has(nodeId));
4613
+ if (retainedNodeIds.length === 0) continue;
4614
+ const currentPhase = phases.find((candidate) => candidate.title === phase.title);
4615
+ if (currentPhase) currentPhase.nodeIds.push(...retainedNodeIds);
4616
+ else phases.push({ title: phase.title, nodeIds: retainedNodeIds });
4617
+ }
4618
+ const currentNodeId = nodes.find((node) => node.status === "running")?.id ?? existing?.currentNodeId;
4619
+ return { runId, mode: "workflow", phases, nodes, ...(currentNodeId ? { currentNodeId } : {}) };
4620
+ }
4621
+
4622
+ function workflowLaneTraceStatus(state: WorkflowScriptTraceEntry["state"]): WorkflowNodeStatus | undefined {
4623
+ switch (state) {
4624
+ case "started":
4625
+ return "running";
4626
+ case "reused":
4627
+ return undefined;
4628
+ case "completed":
4629
+ return "completed";
4630
+ case "failed":
4631
+ return "failed";
4632
+ case "detached":
4633
+ return "detached";
4634
+ case "stopped":
4635
+ return "stopped";
4636
+ default:
4637
+ return undefined;
4638
+ }
4639
+ }
4640
+
4641
+ function applyWorkflowLaneTrace(graph: WorkflowGraphSnapshot, trace: WorkflowScriptTraceEntry[]): void {
4642
+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
4643
+ for (const entry of trace) {
4644
+ if (entry.operation !== "run") continue;
4645
+ const node = nodesById.get(entry.key);
4646
+ if (!node) continue;
4647
+ const status = workflowLaneTraceStatus(entry.state);
4648
+ if (status) node.status = status;
4649
+ if (entry.agent) node.agent = entry.agent;
4650
+ if (entry.phase && (entry.phase !== "auto-resume" || node.phase === undefined)) node.phase = entry.phase;
4651
+ if (entry.label) node.label = entry.label;
4652
+ if (entry.error) node.error = entry.error;
4653
+ else if (status === "completed" || status === "running") delete node.error;
4654
+ }
4655
+ const currentNodeId = graph.nodes.find((node) => node.status === "running")?.id;
4656
+ if (currentNodeId) graph.currentNodeId = currentNodeId;
4657
+ else delete graph.currentNodeId;
4658
+ }
4659
+
4185
4660
  function workflowChatProgressUpdate(
4186
4661
  runId: string,
4187
4662
  chatProgress: WorkflowChatProgressProjection,
4188
4663
  workflow: NonNullable<Details["workflow"]>,
4664
+ workflowChildren?: Details["workflowChildren"],
4665
+ preflight?: import("../../shared/types.ts").WorkflowPreflightV1,
4189
4666
  ): AgentToolResult<Details> | undefined {
4190
4667
  if (chatProgress.mode !== "live-card") return undefined;
4191
4668
  return {
4192
4669
  content: [{ type: "text", text: "Workflow running." }],
4193
- details: { mode: "workflow", runId, results: [], workflow, chatProgress },
4670
+ details: { mode: "workflow", runId, results: [], workflow, ...(preflight ? { preflight } : {}), ...(workflowChildren ? { workflowChildren } : {}), chatProgress },
4194
4671
  };
4195
4672
  }
4196
4673
 
@@ -4201,10 +4678,12 @@ function createScheduledOwnerState(source: SubagentState, ownerSessionId: string
4201
4678
  grantHistory: [...(source.subagentSpawns.grantHistory ?? [])],
4202
4679
  }
4203
4680
  : undefined;
4681
+ const ownerParentModel = source.currentSessionId === ownerSessionId ? source.lastParentModel : undefined;
4204
4682
  return {
4205
4683
  ...source,
4206
4684
  baseCwd: ctx.cwd,
4207
4685
  currentSessionId: ownerSessionId,
4686
+ lastParentModel: ownerParentModel,
4208
4687
  parentSessionFile: ctx.sessionManager.getSessionFile() ?? null,
4209
4688
  subagentInProgress: false,
4210
4689
  ...(ownerSpawns ? { subagentSpawns: ownerSpawns } : { subagentSpawns: undefined }),
@@ -4265,6 +4744,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4265
4744
  const delegatedThinkingOverrides = new WeakMap<object, AgentConfig["thinking"]>();
4266
4745
  const delegatedZeroToolBudgets = new WeakSet<object>();
4267
4746
  const delegatedExecutions = new WeakSet<object>();
4747
+ const publicExecutions = new WeakSet<object>();
4748
+ const workflowResourcePermits = new WeakMap<object, WorkflowResourcePermit>();
4749
+ const workflowPermitContexts = new WeakMap<object, { root: WorkflowChildPermit } | { child: WorkflowChildPermitContext }>();
4268
4750
  const warnedArtifactPackageDirs = new Set<string>();
4269
4751
  const scheduledOwnerExecutors = new Map<string, ReturnType<typeof createSubagentExecutor>>();
4270
4752
  const execute = async (
@@ -4274,21 +4756,78 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4274
4756
  onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
4275
4757
  ctx: ExtensionContext,
4276
4758
  preserveActiveSession = false,
4759
+ parentModelOverride?: ParentModel | null,
4277
4760
  ): Promise<AgentToolResult<Details>> => {
4278
4761
  const workflowLaunchObserver = workflowLaunchObservers.get(params);
4279
4762
  const delegatedThinkingOverride = delegatedThinkingOverrides.get(params);
4280
4763
  const allowZeroToolBudget = delegatedZeroToolBudgets.has(params);
4281
4764
  const delegatedExecution = delegatedExecutions.has(params);
4765
+ const publicExecution = publicExecutions.has(params);
4766
+ const workflowResourcePermit = workflowResourcePermits.get(params);
4767
+ const workflowPermitContext = workflowPermitContexts.get(params);
4768
+ const delegatedWorkflowPermit = workflowPermitContext && "root" in workflowPermitContext ? workflowPermitContext.root : undefined;
4769
+ const workflowChildPermitLaunch = workflowPermitContext && "child" in workflowPermitContext ? workflowPermitContext.child : undefined;
4282
4770
  if (!preserveActiveSession) deps.state.baseCwd = ctx.cwd;
4283
4771
  deps.state.foregroundRuns ??= new Map();
4284
4772
  deps.state.foregroundControls ??= new Map();
4285
4773
  deps.state.lastForegroundControlId ??= null;
4286
4774
  const normalizedGate = normalizeGateParams(params);
4287
4775
  if (!normalizedGate.ok) return buildRequestedModeError(params, normalizedGate.error);
4288
- const requestParams = normalizedGate.params;
4776
+ let requestParams = normalizedGate.params;
4777
+ const capacityOverrideError = validateWorkflowCapacityOverrides(requestParams);
4778
+ if (capacityOverrideError) return buildRequestedModeError(requestParams, capacityOverrideError);
4779
+ let workflowPreflight: import("../../shared/types.ts").WorkflowPreflightV1 | undefined;
4780
+ try {
4781
+ if (requestParams.preflight !== undefined && requestParams.workflowScript === undefined && requestParams.workflowScriptPath === undefined) {
4782
+ throw new Error("preflight requires workflowScript or workflowScriptPath.");
4783
+ }
4784
+ workflowPreflight = normalizeWorkflowPreflight(requestParams.preflight);
4785
+ if (workflowPreflight) requestParams = { ...requestParams, preflight: workflowPreflight };
4786
+ } catch (error) {
4787
+ const message = error instanceof Error ? error.message : String(error);
4788
+ if (requestParams.action?.trim() === "validate") {
4789
+ const validation = validateWorkflowScript(requestParams.workflowScript ?? "");
4790
+ const invalidValidation = { ...validation, ok: false, errors: [...validation.errors, { message }] };
4791
+ return {
4792
+ content: [{ type: "text", text: JSON.stringify(invalidValidation) }],
4793
+ isError: true,
4794
+ details: { mode: "management", results: [] },
4795
+ };
4796
+ }
4797
+ return buildRequestedModeError(requestParams, message);
4798
+ }
4799
+ if (requestParams.action?.trim() === "validate") {
4800
+ const validation = validateWorkflowScript(requestParams.workflowScript ?? "");
4801
+ const payload = workflowPreflight ? { ...validation, preflight: workflowPreflight } : validation;
4802
+ return {
4803
+ content: [{ type: "text", text: JSON.stringify(payload) }],
4804
+ ...(validation.ok ? {} : { isError: true }),
4805
+ details: { mode: "management", results: [] },
4806
+ };
4807
+ }
4289
4808
  const normalizedAction = typeof requestParams.action === "string" ? requestParams.action.trim() : requestParams.action;
4290
4809
  if (normalizedAction === "resume" && requestParams.extensionBindings !== undefined) return buildRequestedModeError(requestParams, "extensionBindings is not supported with action='resume'; resume uses the original retained child binding.");
4810
+ let workflowResource: { permit: WorkflowResourcePermit; provenance: WorkflowResourceProvenanceV1; authority: WorkflowResourceAuthority } | undefined;
4811
+ if (workflowResourcePermit) {
4812
+ if (typeof requestParams.workflowScript !== "string") return buildRequestedModeError(requestParams, "Resolved workflow resource is missing its workflow script.");
4813
+ const consumed = consumeWorkflowResourcePermit(workflowResourcePermit, requestParams.workflowScript);
4814
+ if (typeof consumed === "string") return buildRequestedModeError(requestParams, consumed);
4815
+ workflowResource = { permit: workflowResourcePermit, ...consumed };
4816
+ }
4291
4817
  if (requestParams.workflowScript !== undefined && normalizedAction === undefined) {
4818
+ if (delegatedWorkflowPermit) {
4819
+ const permitError = validateWorkflowChildPermitRoot(delegatedWorkflowPermit, _id);
4820
+ if (permitError) return buildRequestedModeError(requestParams, permitError);
4821
+ if (requestParams.async !== false) return buildRequestedModeError(requestParams, "Workflow child permit supports foreground workflow roots only; set async:false.");
4822
+ }
4823
+ const workflowParentModel = parentModelOverride !== undefined
4824
+ ? parentModelOverride
4825
+ : (() => {
4826
+ const currentParentModel = normalizeParentModel(ctx.model);
4827
+ return (preserveActiveSession
4828
+ ? currentParentModel
4829
+ : rememberParentModel(deps.state, resolveCurrentSessionId(ctx.sessionManager), currentParentModel)) ?? null;
4830
+ })();
4292
4831
  if (requestParams.extensionBindings !== undefined) {
4293
4832
  try {
4294
4833
  requestParams.extensionBindings = normalizeExtensionBindings(requestParams.extensionBindings)!.value;
@@ -4301,7 +4840,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4301
4840
  const workflowUsageBudget = validateUsageBudgetConfig(requestParams.usageBudget ?? deps.config.usageBudget, requestParams.usageBudget ? "usageBudget" : "config.usageBudget");
4302
4841
  if (workflowUsageBudget.error) return buildRequestedModeError(requestParams, workflowUsageBudget.error);
4303
4842
  const workflowCwd = resolveRequestedCwd(parentCwd, requestParams.cwd);
4304
- const workflowAgents = deps.discoverAgents(workflowCwd, resolveExecutionAgentScope(requestParams.agentScope)).agents;
4843
+ const discoverWorkflowAgents = (cwd: string, scope: AgentScope) => deps.discoverAgents(cwd, scope, workflowParentModel?.provider);
4844
+ const workflowAgents = discoverWorkflowAgents(workflowCwd, resolveExecutionAgentScope(requestParams.agentScope)).agents;
4305
4845
  const workflowArtifactConfig: ArtifactConfig = omitUndefinedProperties({
4306
4846
  ...DEFAULT_ARTIFACT_CONFIG,
4307
4847
  enabled: requestParams.artifacts !== false,
@@ -4323,11 +4863,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4323
4863
  const scriptFirstLine = requestParams.workflowScript.split(/\r?\n/).map((line) => line.trim()).find(Boolean) || "Workflow";
4324
4864
  const boundedScriptPreview = scriptFirstLine.length > 100 ? `${scriptFirstLine.slice(0, 97)}...` : scriptFirstLine;
4325
4865
  const derivedObjective = previewAgent ? `Workflow: ${previewAgent}` : boundedScriptPreview;
4326
- const workflowDepth = checkSubagentDepth(deps.config.maxSubagentDepth).depth;
4866
+ const workflowDepth = checkSubagentDepth(deps.config.maxSubagentDepth, deps.childRuntime).depth;
4327
4867
  const asyncWorkflow = requestParams.async !== false;
4328
4868
  const topLevelAsyncWorkflow = asyncWorkflow
4329
4869
  && workflowDepth === 0
4330
- && !resolveInheritedNestedRouteFromEnv()
4870
+ && !inheritedNestedRoute(deps)
4331
4871
  && !requestParams.workflowParentRunId;
4332
4872
  const workflowRunId = asyncWorkflow ? randomUUID() : undefined;
4333
4873
  let workflowCapacity: ActiveAsyncCapacityHandle | undefined;
@@ -4340,7 +4880,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4340
4880
  runId: workflowRunId,
4341
4881
  kind: "workflow",
4342
4882
  asyncDir: path.join(DIRS.async, workflowRunId),
4343
- }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) });
4883
+ }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) });
4344
4884
  } catch (error) {
4345
4885
  if (error instanceof ActiveAsyncCapacityError) {
4346
4886
  deps.state.activeAsyncCapacity = error.snapshot;
@@ -4352,8 +4892,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4352
4892
  let workflowFanoutBudget: RunFanoutBudgetDescriptor;
4353
4893
  try {
4354
4894
  workflowFanoutBudget = requestParams.runFanoutBudget
4355
- ?? decodeRunFanoutBudgetDescriptor(process.env[RUN_FANOUT_BUDGET_ENV])
4356
- ?? createRunFanoutBudget(_id, resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun));
4895
+ ?? inheritedRunFanoutBudget(deps)
4896
+ ?? createRunFanoutBudget(_id, requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun));
4357
4897
  } catch (error) {
4358
4898
  workflowCapacity?.rollback();
4359
4899
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "workflow", results: [] } };
@@ -4414,7 +4954,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4414
4954
  deps.state.workflowChildStops ??= new Map();
4415
4955
  deps.state.workflowControllers.set(workflowRunId, controller);
4416
4956
  workflowCapacity?.markWorkflowStarted();
4417
- if (workflowCapacity) deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers.keys()) });
4957
+ if (workflowCapacity) deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers.keys()), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) });
4418
4958
  let status: AsyncStatus = {
4419
4959
  runId: workflowRunId,
4420
4960
  toolCallId,
@@ -4430,7 +4970,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4430
4970
  ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}),
4431
4971
  pid: process.pid,
4432
4972
  steps: [],
4433
- workflow: { trace: [], emits: [], console: [] },
4973
+ ...(workflowPreflight ? { preflight: workflowPreflight } : {}),
4974
+ workflow: { trace: [], emits: [], console: [], ...(workflowResource ? { resource: workflowResource.provenance } : {}) },
4975
+ workflowChildren: workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState: "running", inventoryComplete: false }),
4434
4976
  runFanoutBudget: getRunFanoutBudgetSnapshot(workflowFanoutBudget),
4435
4977
  };
4436
4978
  const appendWorkflowEvent = (event: Record<string, unknown>) => {
@@ -4479,6 +5021,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4479
5021
  if (persistClosed) return;
4480
5022
  const liveJob = deps.state.asyncJobs.get(workflowRunId);
4481
5023
  if (liveJob && (liveJob.status === "complete" || liveJob.status === "failed") && status.state !== "complete" && status.state !== "failed") return;
5024
+ const workflowState = status.state === "complete" ? "completed" : status.state === "failed" || status.state === "rejected" ? "failed" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "running";
5025
+ status.workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState, inventoryComplete: workflowState !== "running", trace: status.workflow?.trace, steps: status.steps });
4482
5026
  status.lastUpdate = Date.now();
4483
5027
  if (!initialPersistenceComplete) {
4484
5028
  writeAtomicJson(statusPath, status);
@@ -4514,6 +5058,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4514
5058
  liveJob.turnCount = status.turnCount;
4515
5059
  liveJob.toolCount = status.toolCount;
4516
5060
  liveJob.currentStep = status.currentStep;
5061
+ liveJob.preflight = status.preflight;
5062
+ liveJob.workflowGraph = status.workflowGraph;
4517
5063
  if (status.steps) {
4518
5064
  liveJob.steps = status.steps.map((step, index) => ({ ...step, index }));
4519
5065
  liveJob.agents = status.steps.map((step) => step.agent);
@@ -4522,6 +5068,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4522
5068
  delete liveJob.agents;
4523
5069
  }
4524
5070
  liveJob.workflow = status.workflow;
5071
+ liveJob.workflowChildren = status.workflowChildren;
4525
5072
  }
4526
5073
  };
4527
5074
  const writeWorkflowResult = (payload: Record<string, unknown>): boolean => {
@@ -4556,7 +5103,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4556
5103
  status.toolCount = toolCounts.length > 0 ? toolCounts.reduce((total, count) => total + count, 0) : undefined;
4557
5104
  status.currentStep = runningSteps.length === 1 ? steps.indexOf(runningSteps[0]!) : undefined;
4558
5105
  };
4559
- const workflowJob: AsyncJobState = { asyncId: workflowRunId, asyncDir, toolCallId, cwd: workflowCwd, ...(workflowSessionRoot ? { sessionRoot: workflowSessionRoot } : {}), status: "running", sessionId: currentSessionId ?? undefined, mode: "workflow", agents: [], steps: [], startedAt, updatedAt: startedAt, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), ...(timeout !== undefined ? { timeoutMs: timeout, deadlineAt: startedAt + timeout } : {}), workflow: status.workflow };
5106
+ const workflowJob: AsyncJobState = { asyncId: workflowRunId, asyncDir, toolCallId, cwd: workflowCwd, ...(workflowSessionRoot ? { sessionRoot: workflowSessionRoot } : {}), status: "running", sessionId: currentSessionId ?? undefined, mode: "workflow", agents: [], steps: [], ...(workflowPreflight ? { preflight: workflowPreflight } : {}), startedAt, updatedAt: startedAt, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), ...(timeout !== undefined ? { timeoutMs: timeout, deadlineAt: startedAt + timeout } : {}), workflow: status.workflow, workflowChildren: status.workflowChildren };
4560
5107
  deps.state.asyncJobs.set(workflowRunId, workflowJob);
4561
5108
  deps.state.fleetJobs ??= new Map();
4562
5109
  deps.state.fleetJobs.set(workflowRunId, workflowJob);
@@ -4576,18 +5123,37 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4576
5123
  const workflowDeadlineAt = timeout === undefined ? undefined : Date.now() + timeout;
4577
5124
  const workflowResults: SingleResult[] = [];
4578
5125
  const workflowChildRunIds = new Map<string, string>();
4579
- 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, ...workflowChildDefaults } = workflowRequest;
5126
+ 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;
4580
5127
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
4581
5128
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
4582
- const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId));
5129
+ const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, parentCwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId));
4583
5130
  const claimedOutputPaths = new Map<string, string>();
4584
5131
  const childOutputOverrides = new Map<string, string>();
5132
+ const childOutputClaimPaths = new Map<string, string>();
4585
5133
  const producedChildOutputPaths = new Set<string>();
4586
5134
  const workflowSteps = new Map<string, NonNullable<AsyncStatus["steps"]>[number]>();
5135
+ const runHostCommand = workflowHostCommandRunner({
5136
+ workflowCwd,
5137
+ artifactsDir: workflowArtifactsDir,
5138
+ workflowRunId,
5139
+ claimedOutputPaths,
5140
+ producedOutputPaths: producedChildOutputPaths,
5141
+ ...(workflowResource ? { authorize: (key, params) => authorizeWorkflowResourceHost(workflowResource!.permit, key, params.command) } : {}),
5142
+ });
5143
+ const workflowHost = workflowResource
5144
+ ? workflowResource.authority.host ? runHostCommand : undefined
5145
+ : publicExecution ? undefined : runHostCommand;
4587
5146
  let projectedTraceLength = 0;
4588
5147
  let projectedTraceTail: NonNullable<Details["workflow"]>["trace"][number] | undefined;
4589
5148
  const updateTrace = (trace: NonNullable<Details["workflow"]>["trace"]) => {
4590
- status.workflow = { ...(status.workflow ?? { emits: [], console: [] }), trace };
5149
+ const projectedTrace = annotateWorkflowPreflightTrace(trace, workflowPreflight);
5150
+ const preflightWarnings = workflowPreflightWarnings(workflowPreflight, trace);
5151
+ status.workflow = {
5152
+ ...(status.workflow ?? { emits: [], console: [] }),
5153
+ trace: projectedTrace,
5154
+ ...(preflightWarnings.length ? { preflightWarnings } : {}),
5155
+ };
5156
+ if (status.workflowGraph) applyWorkflowLaneTrace(status.workflowGraph, trace);
4591
5157
  const rebuild = trace.length < projectedTraceLength
4592
5158
  || (projectedTraceLength > 0 && trace[projectedTraceLength - 1] !== projectedTraceTail);
4593
5159
  if (rebuild) {
@@ -4600,8 +5166,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4600
5166
  for (let index = projectedTraceLength; index < trace.length; index += 1) {
4601
5167
  const entry = trace[index]!;
4602
5168
  if (entry.operation !== "run") continue;
5169
+ const entryLabel = entry.label?.trim() || undefined;
5170
+ const entryPhase = entry.phase?.trim() || undefined;
5171
+ const shouldProjectPhase = entryPhase !== undefined && (entryPhase !== "auto-resume" || workflowSteps.get(entry.key)?.phase === undefined);
4603
5172
  const existing = workflowSteps.get(entry.key);
4604
- if (entry.state === "reused" && existing) continue;
5173
+ if (existing) {
5174
+ if (entryLabel) existing.label = entryLabel;
5175
+ if (shouldProjectPhase) existing.phase = entryPhase;
5176
+ }
5177
+ if (entry.state === "reused" && existing) {
5178
+ continue;
5179
+ }
4605
5180
  const mapped = entry.state === "started" || entry.state === "reused"
4606
5181
  ? "running"
4607
5182
  : entry.state === "completed"
@@ -4625,13 +5200,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4625
5200
  if (entry.durationMs === undefined) delete existing.durationMs;
4626
5201
  else existing.durationMs = entry.durationMs;
4627
5202
  } else {
5203
+ // Naming uses the explicit label only — never the workflow key — so the
5204
+ // placeholder cannot diverge from the task-derived name the child
5205
+ // session actually gets (launch/progress updates overwrite this).
5206
+ const stepSessionName = deriveChildSessionName({ agent: entry.agent ?? entry.key, label: entryLabel });
4628
5207
  const step: NonNullable<AsyncStatus["steps"]>[number] = {
4629
5208
  agent: entry.agent ?? entry.key,
4630
- label: entry.key,
5209
+ ...(stepSessionName ? { sessionName: stepSessionName } : {}),
5210
+ label: entryLabel ?? entry.key,
4631
5211
  workflowKey: entry.key,
4632
5212
  parentWorkflowRunId: workflowRunId,
4633
5213
  status: mapped,
4634
5214
  startedAt: Date.now(),
5215
+ ...(entryPhase ? { phase: entryPhase } : {}),
4635
5216
  ...(entry.runId ? { runId: entry.runId } : {}),
4636
5217
  ...(entry.state === "failed" && !entry.runId ? { async: false } : {}),
4637
5218
  ...(entry.state === "detached" ? { activityState: "needs_attention" as const } : {}),
@@ -4647,7 +5228,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4647
5228
  version: 1,
4648
5229
  childId: entry.key,
4649
5230
  status: "stopped",
4650
- reason: "user",
5231
+ reason: "subagent-action",
4651
5232
  source: "async",
4652
5233
  stepIndex: status.steps?.indexOf(projectedStep),
4653
5234
  agent: projectedStep.agent,
@@ -4667,19 +5248,39 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4667
5248
  try {
4668
5249
  const workflow = await runWorkflowScript({
4669
5250
  script: workflowScript,
5251
+ globalConcurrencyLimit: requestParams.globalConcurrencyLimit ?? deps.config.globalConcurrencyLimit,
4670
5252
  timeoutMs: timeout,
4671
5253
  signal: controller.signal,
5254
+ continueAfterAbortWhenChildrenSettled: (abortError) => {
5255
+ if (abortError.message !== "Workflow stopped because the extension session was replaced or reloaded.") return false;
5256
+ const activeAsyncChild = [...(deps.state.asyncJobs?.values() ?? [])].some((job) => job.parentWorkflowRunId === workflowRunId && (job.status === "queued" || job.status === "running"));
5257
+ const activeForegroundChild = [...deps.state.foregroundControls.values()].some((control) => control.parentWorkflowRunId === workflowRunId && (control.activeChildren?.size ?? 0) > 0);
5258
+ return !activeAsyncChild && !activeForegroundChild;
5259
+ },
4672
5260
  registerStopChild: (stop) => {
4673
5261
  if (stop) deps.state.workflowChildStops?.set(workflowRunId, stop);
4674
5262
  else deps.state.workflowChildStops?.delete(workflowRunId);
4675
5263
  },
4676
5264
  ...(workflowState ? { state: workflowState } : {}),
4677
5265
  onTrace: updateTrace,
5266
+ onLanePlan: (lanes) => {
5267
+ status.workflowGraph = buildWorkflowLaneGraph(workflowRunId, lanes, status.workflowGraph);
5268
+ applyWorkflowLaneTrace(status.workflowGraph, status.workflow?.trace ?? []);
5269
+ persist({ tolerateStatusWriteFailure: true });
5270
+ },
5271
+ ...(workflowHost ? { host: workflowHost } : {}),
5272
+ onHostStep: (hostStep) => {
5273
+ status = upsertHostStep({ status, hostStep, persist: (nextStatus) => {
5274
+ status = nextStatus;
5275
+ persist({ tolerateStatusWriteFailure: true });
5276
+ } });
5277
+ },
4678
5278
  admit: (calls) => {
4679
- const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
5279
+ 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 });
4680
5280
  if (outputClaims.error) throw new Error(outputClaims.error);
4681
5281
  status.runFanoutBudget = claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
4682
5282
  if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
5283
+ if (outputClaims.childClaims) for (const [key, claimPath] of outputClaims.childClaims) childOutputClaimPaths.set(key, claimPath);
4683
5284
  if (outputClaims.overrides) for (const [key, output] of outputClaims.overrides) childOutputOverrides.set(key, output);
4684
5285
  persist({ tolerateStatusWriteFailure: true });
4685
5286
  },
@@ -4692,7 +5293,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4692
5293
  launch: async (key, childParams, workflowSignal, admission) => {
4693
5294
  if (workflowUsageBudget.budget && childParams.async === true) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, "workflow usageBudget does not support async runs.run launches."), childParams, deps.state);
4694
5295
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
4695
- if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state);
5296
+ if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state, { state: "partial", reason: "budget_exhausted" });
4696
5297
  const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
4697
5298
  const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
4698
5299
  recordMissionWorkflowChild(missionBinding, workflowRunId, key, {
@@ -4702,19 +5303,23 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4702
5303
  ...(childPhase ? { phase: childPhase } : {}),
4703
5304
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
4704
5305
  });
5306
+ let preparedChildParams: SubagentParamsLike | undefined;
4705
5307
  const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, () => {
4706
5308
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
4707
- { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), options: { missionDetached: detachWorkflowChildMissions, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
5309
+ { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: parentCwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, awaitDetachedChild: true, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
4708
5310
  missionBinding,
4709
5311
  deps.asyncByDefault,
4710
5312
  );
5313
+ preparedChildParams = childRequest;
4711
5314
  workflowLaunchObservers.set(childRequest, (launch) => {
4712
5315
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
4713
5316
  if (step) {
4714
5317
  step.agent = launch.agent;
5318
+ if (launch.sessionName) step.sessionName = launch.sessionName;
4715
5319
  step.sessionFile = launch.sessionFile;
4716
5320
  step.async = launch.async;
4717
5321
  if (launch.runId) step.runId = launch.runId;
5322
+ if (childRequest.lane) step.lane = childRequest.lane;
4718
5323
  persist({ tolerateStatusWriteFailure: true });
4719
5324
  }
4720
5325
  recordMissionWorkflowChild(missionBinding, workflowRunId, key, { status: "running", agent: launch.agent, ...(launch.sessionFile ? { sessionPath: launch.sessionFile } : {}) });
@@ -4736,6 +5341,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4736
5341
  step.toolCount = progress.toolCount;
4737
5342
  step.model = progress.model;
4738
5343
  step.thinking = progress.thinking;
5344
+ if (progress.sessionName) step.sessionName = progress.sessionName;
4739
5345
  step.error = progress.error;
4740
5346
  projectWorkflowActivity();
4741
5347
  persist({ tolerateStatusWriteFailure: true });
@@ -4743,18 +5349,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4743
5349
  status: step.status,
4744
5350
  heartbeat: { status: step.status, ...(childPhase ? { phase: childPhase } : {}) },
4745
5351
  });
4746
- }, ctx, preserveActiveSession);
5352
+ }, ctx, preserveActiveSession, workflowParentModel);
4747
5353
  });
4748
5354
  workflowResults.push(...result.details.results);
4749
5355
  for (const childResult of result.details.results) {
4750
- if (childResult.savedOutputPath) producedChildOutputPaths.add(childResult.savedOutputPath);
5356
+ if (childResult.savedOutputPath) producedChildOutputPaths.add(resolveWorkflowHostOutputClaimPath(childResult.savedOutputPath));
4751
5357
  }
4752
- const child = workflowChildResult(key, result, childParams, deps.state);
5358
+ const child = workflowChildResult(key, result, preparedChildParams ?? childParams, deps.state);
4753
5359
  if (child.runId) workflowChildRunIds.set(key, child.runId);
4754
5360
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
4755
5361
  if (step) {
4756
5362
  step.async = Boolean(result.details.asyncId || result.details.asyncDir);
4757
5363
  if (child.runId) step.runId = child.runId;
5364
+ if (child.lane) step.lane = child.lane;
4758
5365
  }
4759
5366
  if (result.details.asyncDir && missionBinding) writeMissionAsyncBinding(result.details.asyncDir, missionBinding);
4760
5367
  const childStatus = missionWorkflowChildStatus(result);
@@ -4773,26 +5380,30 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4773
5380
  }
4774
5381
  return child;
4775
5382
  },
4776
- status: async (keyOrRunId, workflowSignal) => workflowChildResult(keyOrRunId, await execute(randomUUID(), { action: "status", id: keyOrRunId }, workflowSignal, undefined, ctx, preserveActiveSession)),
5383
+ status: async (keyOrRunId, workflowSignal) => workflowChildResult(keyOrRunId, await execute(randomUUID(), { action: "status", id: keyOrRunId }, workflowSignal, undefined, ctx, preserveActiveSession, workflowParentModel)),
4777
5384
  resolveResume: (reference) => resolveKeyedWorkflowResume(reference, deps.state),
4778
5385
  steer: (key, message, options, workflowSignal) => steerWorkflowChildByKey({ state: deps.state, workflowRunId, key, message, options, signal: workflowSignal, resolveRunId: () => workflowChildRunIds.get(key) }),
4779
5386
  });
5387
+ const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, workflow.trace, { settled: true });
5388
+ const finalPreflightTrace = annotateWorkflowPreflightTrace(workflow.trace, workflowPreflight);
4780
5389
  const returnPreview = formatWorkflowValue(workflow.value).slice(0, 1_000);
4781
5390
  const emitPreview = workflow.emits.length > 0 ? ` Emitted: ${workflow.emits.map(formatWorkflowValue).join(", ").slice(0, 1_000)}` : "";
4782
- const summary = `Workflow completed with ${workflow.children.length} child run(s). Return: ${returnPreview}${emitPreview} Trace: ${workflow.trace.length} event(s).`;
5391
+ const summary = `Workflow completed with ${workflow.children.length} child run(s). Return: ${returnPreview}${emitPreview} Trace: ${workflow.trace.length} event(s).${workflowOutputPathMappingSummary(workflow.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
4783
5392
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, summary, producedChildOutputPaths);
4784
5393
  const resultSummary = appendWorkflowOutputWarning(summary, outputWarning);
4785
5394
  const workflowUsage = sumResultsUsage(workflowResults);
4786
- status = { ...status, state: "complete", endedAt: Date.now(), workflow: { value: workflow.value, trace: workflow.trace, emits: workflow.emits, console: workflow.console }, totalTokens: { input: workflowUsage.input, output: workflowUsage.output, total: workflowUsage.input + workflowUsage.output }, totalCost: sumResultsCost(workflowResults) };
4787
- const receipt = terminalWorkflowReceipt(workflowRunId, "complete", workflow.children);
5395
+ const workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children, steps: status.steps });
5396
+ 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) };
5397
+ const receipt = terminalWorkflowReceipt(workflowRunId, "complete", workflow.children, workflowChildren, undefined, validHostStepNodes(status.workflowGraph), workflowResource?.provenance);
4788
5398
  let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
4789
5399
  try {
4790
5400
  workflowReceipt = { path: writeWorkflowReceipt(asyncDir, receipt), receipt };
4791
5401
  } catch (receiptError) {
4792
5402
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
4793
5403
  }
4794
- if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary: resultSummary, output: resultSummary, results: workflow.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(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;
5404
+ 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;
4795
5405
  persist();
5406
+ deps.refreshResultDelivery?.();
4796
5407
  persistClosed = true;
4797
5408
  appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(status.error ? { error: status.error } : {}) });
4798
5409
  } catch (error) {
@@ -4813,28 +5424,34 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4813
5424
  delete step.activityState;
4814
5425
  }
4815
5426
  }
4816
- status = compactOptional<AsyncStatus>({ ...status, state, stopped: stopped || undefined, activityState: pauseForDetached ? "needs_attention" : undefined, error: error instanceof Error ? error.message : String(error), endedAt: Date.now(), workflow: { trace: partial.trace, emits: partial.emits, console: partial.console } });
5427
+ const workflowState = state === "paused" ? "paused" : state === "stopped" ? "stopped" : "failed";
5428
+ const workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState, inventoryComplete: true, trace: partial.trace, children: partial.children, steps: status.steps });
5429
+ const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, partial.trace, { settled: true });
5430
+ const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
5431
+ 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 });
4817
5432
  if (pauseForDetached) {
4818
5433
  const promoted = promotePausedWorkflowIfSettled(status);
4819
5434
  if (promoted) status = promoted;
4820
5435
  }
4821
- const terminalSummary = status.state === "complete"
5436
+ const terminalSummary = `${status.state === "complete"
4822
5437
  ? "Workflow completed after detached child finished."
4823
- : status.error ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.");
5438
+ : status.error ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.")}${workflowOutputPathMappingSummary(partial.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
4824
5439
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, terminalSummary, producedChildOutputPaths);
4825
5440
  const resultSummary = appendWorkflowOutputWarning(terminalSummary, outputWarning);
4826
5441
  const receiptState: WorkflowReceiptState = status.state === "complete" ? "complete" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "failed";
4827
- const receipt = terminalWorkflowReceipt(workflowRunId, receiptState, partial.children);
5442
+ const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
5443
+ const receipt = terminalWorkflowReceipt(workflowRunId, receiptState, partial.children, workflowChildren, terminalOutcome, validHostStepNodes(status.workflowGraph), workflowResource?.provenance);
4828
5444
  let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
4829
5445
  try {
4830
5446
  workflowReceipt = { path: writeWorkflowReceipt(asyncDir, receipt), receipt };
4831
5447
  } catch (receiptError) {
4832
5448
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
4833
5449
  }
4834
- 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, results: partial.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(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;
5450
+ 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;
4835
5451
  persist();
5452
+ deps.refreshResultDelivery?.();
4836
5453
  persistClosed = true;
4837
- appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(status.error ? { error: status.error } : {}), ...(status.activityState ? { activityState: status.activityState } : {}) });
5454
+ appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(terminalOutcome ? { terminalOutcome } : {}), ...(status.error ? { error: status.error } : {}), ...(status.activityState ? { activityState: status.activityState } : {}) });
4838
5455
  } finally {
4839
5456
  persistClosed = true;
4840
5457
  deps.state.workflowControllers?.delete(workflowRunId);
@@ -4844,41 +5461,67 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4844
5461
  }
4845
5462
  });
4846
5463
  return attachWorkflowMission(withRunFanoutBudget({
4847
- content: [{ type: "text", text: formatAsyncStartedMessage(`Async workflow [${workflowRunId}]`, ctx.hasUI === true) }],
4848
- details: { mode: "workflow", runId: workflowRunId, toolCallId, asyncId: workflowRunId, asyncDir, results: [], chatProgress, ...(deps.state.activeAsyncCapacity ? { activeAsyncCapacity: deps.state.activeAsyncCapacity } : {}) },
5464
+ content: [{ type: "text", text: `${workflowPreflight ? `${formatWorkflowPreflight(workflowPreflight)}\n\n` : ""}${formatAsyncStartedMessage(`Async workflow [${workflowRunId}]`, ctx.hasUI === true)}` }],
5465
+ 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 } : {}) },
4849
5466
  }, workflowFanoutBudget));
4850
5467
  }
4851
- 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, ...workflowChildDefaults } = requestParams;
5468
+ 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;
4852
5469
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
4853
5470
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
4854
5471
  const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, _id));
4855
5472
  const claimedOutputPaths = new Map<string, string>();
4856
5473
  const childOutputOverrides = new Map<string, string>();
5474
+ const childOutputClaimPaths = new Map<string, string>();
4857
5475
  const producedChildOutputPaths = new Set<string>();
4858
5476
  const workflowResults: SingleResult[] = [];
4859
5477
  const workflowChildRunIds = new Map<string, string>();
4860
- let liveWorkflow: NonNullable<Details["workflow"]> = { trace: [], emits: [], console: [] };
5478
+ const runHostCommand = workflowHostCommandRunner({
5479
+ workflowCwd,
5480
+ artifactsDir: workflowArtifactsDir,
5481
+ workflowRunId: _id,
5482
+ claimedOutputPaths,
5483
+ producedOutputPaths: producedChildOutputPaths,
5484
+ ...(workflowResource ? { authorize: (key, params) => authorizeWorkflowResourceHost(workflowResource!.permit, key, params.command) } : {}),
5485
+ });
5486
+ const workflowHost = delegatedWorkflowPermit
5487
+ ? undefined
5488
+ : workflowResource
5489
+ ? workflowResource.authority.host ? runHostCommand : undefined
5490
+ : publicExecution ? undefined : runHostCommand;
5491
+ const workflowHostSteps = new Map<string, HostStepNodeV1>();
5492
+ let liveWorkflow: NonNullable<Details["workflow"]> = { trace: [], emits: [], console: [], ...(workflowResource ? { resource: workflowResource.provenance } : {}) };
5493
+ let liveWorkflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "running", inventoryComplete: false });
4861
5494
  const workflowDeadlineAt = timeout === undefined ? undefined : Date.now() + timeout;
4862
5495
  const workflowCapabilityCeiling = intersectSubagentCapabilityCeilings(requestParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(resolveCurrentSessionId(ctx.sessionManager)));
4863
5496
  const sendWorkflowProgress = () => {
4864
- const update = workflowChatProgressUpdate(_id, chatProgress, liveWorkflow);
5497
+ const update = workflowChatProgressUpdate(_id, chatProgress, liveWorkflow, liveWorkflowChildren, workflowPreflight);
4865
5498
  if (update) onUpdate?.(update);
4866
5499
  };
4867
5500
  try {
4868
5501
  const workflow = await runWorkflowScript({
4869
5502
  script: requestParams.workflowScript,
5503
+ ...(delegatedWorkflowPermit ? { oneUsePermit: { claim: (key: string) => claimWorkflowChildPermit(delegatedWorkflowPermit, _id, key) } } : {}),
5504
+ globalConcurrencyLimit: requestParams.globalConcurrencyLimit ?? deps.config.globalConcurrencyLimit,
4870
5505
  timeoutMs: timeout,
4871
5506
  signal,
4872
5507
  ...(workflowState ? { state: workflowState } : {}),
5508
+ ...(workflowHost ? { host: workflowHost } : {}),
5509
+ onHostStep: (hostStep) => {
5510
+ workflowHostSteps.set(hostStep.id, { ...hostStep, ...(hostStep.freshness ? { freshness: { ...hostStep.freshness } } : {}) });
5511
+ },
4873
5512
  onTrace: (trace) => {
4874
- liveWorkflow = { ...liveWorkflow, trace };
5513
+ const projectedTrace = annotateWorkflowPreflightTrace(trace, workflowPreflight);
5514
+ const preflightWarnings = workflowPreflightWarnings(workflowPreflight, trace);
5515
+ liveWorkflow = { ...liveWorkflow, trace: projectedTrace, ...(preflightWarnings.length ? { preflightWarnings } : {}) };
5516
+ liveWorkflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "running", inventoryComplete: false, trace });
4875
5517
  sendWorkflowProgress();
4876
5518
  },
4877
5519
  admit: (calls) => {
4878
- const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId: _id, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
5520
+ 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 });
4879
5521
  if (outputClaims.error) throw new Error(outputClaims.error);
4880
5522
  claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
4881
5523
  if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
5524
+ if (outputClaims.childClaims) for (const [key, claimPath] of outputClaims.childClaims) childOutputClaimPaths.set(key, claimPath);
4882
5525
  if (outputClaims.overrides) for (const [key, output] of outputClaims.overrides) childOutputOverrides.set(key, output);
4883
5526
  },
4884
5527
  onEmit: (emits) => {
@@ -4886,9 +5529,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4886
5529
  sendWorkflowProgress();
4887
5530
  },
4888
5531
  launch: async (key, childParams, workflowSignal, admission) => {
5532
+ if (delegatedWorkflowPermit && admission.batch) throw new Error("Workflow child permit does not support runs.all.");
5533
+ if (delegatedWorkflowPermit && childParams.resume !== undefined) throw new Error("Workflow child permit does not support retained resume.");
5534
+ if (delegatedWorkflowPermit && childParams.async === true) throw new Error("Workflow child permit supports one foreground child only.");
4889
5535
  if (workflowUsageBudget.budget && childParams.async === true) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, "workflow usageBudget does not support async runs.run launches."), childParams, deps.state);
4890
5536
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
4891
- if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state);
5537
+ if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state, { state: "partial", reason: "budget_exhausted" });
4892
5538
  const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
4893
5539
  const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
4894
5540
  recordMissionWorkflowChild(missionBinding, _id, key, {
@@ -4898,12 +5544,23 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4898
5544
  ...(childPhase ? { phase: childPhase } : {}),
4899
5545
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
4900
5546
  });
5547
+ let preparedChildParams: SubagentParamsLike | undefined;
4901
5548
  const result = await runMissionWorkflowChild(missionBinding, _id, key, childPhase, () => {
4902
5549
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
4903
- { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: _id, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
5550
+ { ...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 },
4904
5551
  missionBinding,
4905
5552
  deps.asyncByDefault,
4906
5553
  );
5554
+ preparedChildParams = childRequest;
5555
+ if (delegatedWorkflowPermit) {
5556
+ if (childRequest.async !== false) throw new Error("Workflow child permit supports one foreground child only.");
5557
+ const childCwd = resolveRequestedCwd(workflowCwd, childRequest.cwd);
5558
+ const childAgent = typeof childRequest.agent === "string"
5559
+ ? resolveAgentName(childRequest.agent, discoverWorkflowAgents(childCwd, resolveExecutionAgentScope(childRequest.agentScope)).agents).agent
5560
+ : undefined;
5561
+ if (childAgent?.runner?.type === "external-cli" || childAgent?.runner?.type === "external-job") throw new Error("Workflow child permit supports native Pi children only.");
5562
+ workflowPermitContexts.set(childRequest, { child: { permit: delegatedWorkflowPermit, workflowRunId: _id, childKey: key } });
5563
+ }
4907
5564
  workflowLaunchObservers.set(childRequest, (launch) => recordMissionWorkflowChild(missionBinding, _id, key, {
4908
5565
  status: "running",
4909
5566
  agent: launch.agent,
@@ -4917,14 +5574,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4917
5574
  status: progressStatus,
4918
5575
  heartbeat: { status: progressStatus, ...(childPhase ? { phase: childPhase } : {}) },
4919
5576
  });
4920
- }, ctx, preserveActiveSession);
5577
+ }, ctx, preserveActiveSession, workflowParentModel);
4921
5578
  });
4922
5579
  workflowResults.push(...result.details.results);
4923
5580
  for (const childResult of result.details.results) {
4924
- if (childResult.savedOutputPath) producedChildOutputPaths.add(childResult.savedOutputPath);
5581
+ if (childResult.savedOutputPath) producedChildOutputPaths.add(resolveWorkflowHostOutputClaimPath(childResult.savedOutputPath));
4925
5582
  }
4926
5583
  if (result.details.asyncDir && missionBinding) writeMissionAsyncBinding(result.details.asyncDir, missionBinding);
4927
- const child = workflowChildResult(key, result, childParams, deps.state);
5584
+ const child = workflowChildResult(key, result, preparedChildParams ?? childParams, deps.state);
4928
5585
  if (child.runId) workflowChildRunIds.set(key, child.runId);
4929
5586
  const childStatus = missionWorkflowChildStatus(result);
4930
5587
  recordMissionWorkflowChild(missionBinding, _id, key, {
@@ -4938,43 +5595,64 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4938
5595
  });
4939
5596
  return child;
4940
5597
  },
4941
- status: async (keyOrRunId, workflowSignal) => workflowChildResult(keyOrRunId, await execute(randomUUID(), { action: "status", id: keyOrRunId }, workflowSignal, undefined, ctx, preserveActiveSession)),
5598
+ status: async (keyOrRunId, workflowSignal) => workflowChildResult(keyOrRunId, await execute(randomUUID(), { action: "status", id: keyOrRunId }, workflowSignal, undefined, ctx, preserveActiveSession, workflowParentModel)),
4942
5599
  resolveResume: (reference) => resolveKeyedWorkflowResume(reference, deps.state),
4943
5600
  steer: (key, message, options, workflowSignal) => steerWorkflowChildByKey({ state: deps.state, workflowRunId: _id, key, message, options, signal: workflowSignal, resolveRunId: () => workflowChildRunIds.get(key) }),
4944
5601
  });
4945
- const receipt = terminalWorkflowReceipt(_id, "complete", workflow.children);
4946
- const traceLines = workflow.trace.map((entry) => `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.durationMs !== undefined ? ` in ${entry.durationMs}ms` : ""}${entry.error ? ` — ${entry.error}` : ""}`);
4947
- const sections = ["Workflow completed.", `Return:\n${formatWorkflowValue(workflow.value)}`];
5602
+ const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, workflow.trace, { settled: true });
5603
+ const finalPreflightTrace = annotateWorkflowPreflightTrace(workflow.trace, workflowPreflight);
5604
+ const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children });
5605
+ const receipt = terminalWorkflowReceipt(_id, "complete", workflow.children, workflowChildren, undefined, [...workflowHostSteps.values()], workflowResource?.provenance);
5606
+ 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}` : ""}`);
5607
+ const sections = [
5608
+ ...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []),
5609
+ "Workflow completed.",
5610
+ `Return:\n${formatWorkflowValue(workflow.value)}`,
5611
+ ];
4948
5612
  if (workflow.emits.length > 0) sections.push(`Emitted:\n${workflow.emits.map(formatWorkflowValue).join("\n")}`);
4949
5613
  if (workflow.console.length > 0) sections.push(`Console:\n${workflow.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
4950
5614
  if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
5615
+ if (finalPreflightWarnings.length > 0) sections.push(formatWorkflowPreflightWarnings(finalPreflightWarnings));
5616
+ const outputMappings = workflowOutputPathMappingSummary(workflow.children).trim();
5617
+ if (outputMappings) sections.push(outputMappings);
4951
5618
  const workflowText = sections.join("\n\n");
4952
5619
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText, producedChildOutputPaths);
4953
5620
  const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
4954
5621
  return attachWorkflowMission(withRunFanoutBudget({
4955
5622
  content: [{ type: "text", text: displayText }],
4956
- details: compactOptional<Details>({ mode: "workflow", runId: _id, results: workflow.children.flatMap((child) => (child.results ?? []) as SingleResult[]), totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { value: workflow.value, trace: workflow.trace, emits: workflow.emits, console: workflow.console, receipt }, chatProgress }),
5623
+ 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 }),
4957
5624
  }, workflowFanoutBudget));
4958
5625
  } catch (error) {
4959
5626
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
4960
- const text = error instanceof Error ? error.message : String(error);
4961
- const traceLines = partial.trace.map((entry) => `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.error ? ` — ${entry.error}` : ""}`);
4962
- const sections = [`Workflow failed: ${text}`];
5627
+ const text = workflowFailureMessage(error, _id, partial.children);
5628
+ const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, partial.trace, { settled: true });
5629
+ const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
5630
+ const traceLines = finalPreflightTrace.map((entry) => `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.warning ? ` — ${entry.warning}` : ""}${entry.error ? ` — ${entry.error}` : ""}`);
5631
+ const sections = [
5632
+ ...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []),
5633
+ `Workflow failed: ${text}`,
5634
+ ];
4963
5635
  if (partial.emits.length > 0) sections.push(`Emitted:\n${partial.emits.map(formatWorkflowValue).join("\n")}`);
4964
5636
  if (partial.console.length > 0) sections.push(`Console:\n${partial.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
4965
5637
  if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
5638
+ if (finalPreflightWarnings.length > 0) sections.push(formatWorkflowPreflightWarnings(finalPreflightWarnings));
5639
+ const outputMappings = workflowOutputPathMappingSummary(partial.children).trim();
5640
+ if (outputMappings) sections.push(outputMappings);
4966
5641
  const workflowText = sections.join("\n\n");
4967
5642
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText, producedChildOutputPaths);
4968
5643
  const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
4969
- const receipt = terminalWorkflowReceipt(_id, "failed", partial.children);
5644
+ const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "failed", inventoryComplete: true, trace: partial.trace, children: partial.children });
5645
+ const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
5646
+ const receipt = terminalWorkflowReceipt(_id, "failed", partial.children, workflowChildren, terminalOutcome, [...workflowHostSteps.values()], workflowResource?.provenance);
4970
5647
  return attachWorkflowMission(withRunFanoutBudget({
4971
5648
  content: [{ type: "text", text: displayText }],
4972
5649
  isError: true,
4973
- details: compactOptional<Details>({ mode: "workflow", runId: _id, results: partial.children.flatMap((child) => (child.results ?? []) as SingleResult[]), totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { trace: partial.trace, emits: partial.emits, console: partial.console, receipt }, chatProgress }),
5650
+ 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 }),
4974
5651
  }, workflowFanoutBudget));
4975
5652
  }
4976
5653
  }
4977
5654
  const directParams = requestParams;
5655
+ const requestedCwd = directParams.cwd;
4978
5656
  const requestCwd = resolveRequestedCwd(ctx.cwd, directParams.cwd);
4979
5657
  const paramsWithResolvedCwd = directParams.cwd === undefined ? directParams : { ...directParams, cwd: requestCwd };
4980
5658
  const action = paramsWithResolvedCwd.action;
@@ -4984,14 +5662,45 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4984
5662
  try {
4985
5663
  requestSessionId = resolveCurrentSessionId(ctx.sessionManager);
4986
5664
  requestPiSessionId = ctx.sessionManager.getSessionId() ?? undefined;
4987
- requestParentModel = preserveActiveSession
4988
- ? normalizeParentModel(ctx.model)
4989
- : rememberParentModel(deps.state, requestSessionId, ctx.model);
5665
+ requestParentModel = parentModelOverride !== undefined
5666
+ ? parentModelOverride ?? undefined
5667
+ : preserveActiveSession
5668
+ ? normalizeParentModel(ctx.model)
5669
+ : rememberParentModel(deps.state, requestSessionId, ctx.model);
4990
5670
  } catch (error) {
4991
5671
  if (action?.toLowerCase() !== "doctor" && action?.toLowerCase() !== "guide") throw error;
4992
5672
  requestParentModel = normalizeParentModel(ctx.model);
4993
5673
  }
4994
5674
  if (action) {
5675
+ if (action === "worktree.cleanup") {
5676
+ if (deps.allowMutatingManagementActions === false) {
5677
+ return { content: [{ type: "text", text: "Action 'worktree.cleanup' is not available from child-safe subagent fanout mode." }], isError: true, details: { mode: "management", results: [] } };
5678
+ }
5679
+ if (paramsWithResolvedCwd.mode !== "plan") {
5680
+ return { content: [{ type: "text", text: "worktree.cleanup currently supports mode='plan' only; apply/removal is not available yet." }], isError: true, details: { mode: "management", results: [] } };
5681
+ }
5682
+ if (paramsWithResolvedCwd.planId !== undefined) {
5683
+ return { content: [{ type: "text", text: "worktree.cleanup plan mode does not accept planId; apply is not available yet." }], isError: true, details: { mode: "management", results: [] } };
5684
+ }
5685
+ try {
5686
+ const created = createWorktreeCleanupPlan({
5687
+ repo: paramsWithResolvedCwd.repo?.trim()
5688
+ ? path.isAbsolute(paramsWithResolvedCwd.repo) ? paramsWithResolvedCwd.repo : path.resolve(requestCwd, paramsWithResolvedCwd.repo)
5689
+ : requestCwd,
5690
+ ...(paramsWithResolvedCwd.handoffPath ? { handoffPath: path.isAbsolute(paramsWithResolvedCwd.handoffPath) ? paramsWithResolvedCwd.handoffPath : path.resolve(requestCwd, paramsWithResolvedCwd.handoffPath) } : {}),
5691
+ ...(deps.config.worktreeBaseDir ? { worktreeBaseDir: deps.config.worktreeBaseDir } : {}),
5692
+ foregroundRunOwnership: (runId: string) => {
5693
+ if (deps.state.foregroundControls.has(runId)) return "active" as const;
5694
+ const remembered = deps.state.foregroundRuns?.get(runId);
5695
+ if (!remembered || remembered.children.length === 0 || remembered.children.some((child) => child.status === "detached")) return "unknown" as const;
5696
+ return "terminal" as const;
5697
+ },
5698
+ });
5699
+ return { content: [{ type: "text", text: formatWorktreeCleanupPlan(created) }], details: { mode: "management", results: [] } };
5700
+ } catch (error) {
5701
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
5702
+ }
5703
+ }
4995
5704
  if (action === "worktree.discard") {
4996
5705
  if (deps.allowMutatingManagementActions === false) {
4997
5706
  return { content: [{ type: "text", text: "Action 'worktree.discard' is not available from child-safe subagent fanout mode." }], isError: true, details: { mode: "management", results: [] } };
@@ -5019,6 +5728,30 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5019
5728
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
5020
5729
  }
5021
5730
  }
5731
+ if (action === "lane.status" || action === "lane.recordMerge" || action === "lane.recordSupersession") {
5732
+ if (action !== "lane.status" && deps.allowMutatingManagementActions === false) {
5733
+ return { content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }], isError: true, details: { mode: "management", results: [] } };
5734
+ }
5735
+ const laneId = paramsWithResolvedCwd.laneId?.trim();
5736
+ if (!laneId) return { content: [{ type: "text", text: `${action} requires laneId.` }], isError: true, details: { mode: "management", results: [] } };
5737
+ const handoffPath = paramsWithResolvedCwd.handoffPath?.trim();
5738
+ if (!handoffPath) return { content: [{ type: "text", text: `${action} requires handoffPath for the existing parallel handoff manifest.` }], isError: true, details: { mode: "management", results: [] } };
5739
+ const manifestPath = path.isAbsolute(handoffPath) ? handoffPath : path.resolve(requestCwd, handoffPath);
5740
+ try {
5741
+ if (action === "lane.status") {
5742
+ let manifest;
5743
+ try { manifest = readParallelHandoffManifest(manifestPath); } catch { manifest = undefined; }
5744
+ if (manifest && manifest.runId !== laneId) throw new Error(`Lane '${laneId}' does not match manifest run '${manifest.runId}'.`);
5745
+ return { content: [{ type: "text", text: formatStoredParallelHandoffCleanup(manifestPath, manifest) }], details: { mode: "management", results: [] } };
5746
+ }
5747
+ const recorded = action === "lane.recordMerge"
5748
+ ? recordParallelHandoffMerge({ manifestPath, laneId, merge: paramsWithResolvedCwd.merge })
5749
+ : recordParallelHandoffSupersession({ manifestPath, laneId, supersession: paramsWithResolvedCwd.supersession });
5750
+ return { content: [{ type: "text", text: recorded.text }], details: { mode: "management", results: [], parallelHandoff: recorded.reference } };
5751
+ } catch (error) {
5752
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
5753
+ }
5754
+ }
5022
5755
  if ((HERDR_PROJECT_PANE_ACTIONS as readonly string[]).includes(action)) {
5023
5756
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
5024
5757
  return { content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }], isError: true, details: { mode: "management", results: [] } };
@@ -5211,7 +5944,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5211
5944
  }
5212
5945
  const spawnBudget = getSpawnBudgetSnapshot(deps.state, deps.config, currentSessionId);
5213
5946
  const activeAsyncCapacity = currentSessionId
5214
- ? getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) })
5947
+ ? getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })
5215
5948
  : { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession) ?? 0 };
5216
5949
  deps.state.activeAsyncCapacity = activeAsyncCapacity;
5217
5950
  return {
@@ -5256,10 +5989,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5256
5989
  if (paramsWithResolvedCwd.view) {
5257
5990
  return withBudget({ content: [{ type: "text", text: "action='debug.run' does not support status views." }], isError: true, details: { mode: "management", results: [] } });
5258
5991
  }
5259
- return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots })));
5992
+ return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots, abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })));
5260
5993
  }
5261
5994
  if (paramsWithResolvedCwd.view === "fleet") {
5262
- return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots })));
5995
+ return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots, abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })));
5263
5996
  }
5264
5997
  if (targetRunId) {
5265
5998
  try {
@@ -5290,12 +6023,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5290
6023
  });
5291
6024
  }
5292
6025
  }
5293
- return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots })));
6026
+ return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots, abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })));
5294
6027
  }
5295
6028
  if (action === "resume") {
5296
6029
  return resumeAsyncRun(omitUndefinedProperties({ params: paramsWithResolvedCwd, requestCwd, ctx, deps, parentModel: requestParentModel, signal }));
5297
6030
  }
5298
6031
  if (action === "steer") {
6032
+ if (paramsWithResolvedCwd.mode !== undefined && resolveSteerDeliveryMode(paramsWithResolvedCwd.mode) === undefined) {
6033
+ return { content: [{ type: "text", text: "action='steer' mode must be 'steer', 'follow_up', or 'auto'." }], isError: true, details: { mode: "management", results: [] } };
6034
+ }
5299
6035
  deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
5300
6036
  const message = (paramsWithResolvedCwd.message ?? paramsWithResolvedCwd.task ?? "").trim();
5301
6037
  if (!message) return { content: [{ type: "text", text: "action='steer' requires message." }], isError: true, details: { mode: "management", results: [] } };
@@ -5308,7 +6044,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5308
6044
  if (directoryStatus?.mode === "workflow") {
5309
6045
  const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, workflowRunId: directoryStatus.runId || runId, asyncDirRoot: DIRS.async });
5310
6046
  if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
5311
- return steerWorkflowForegroundTarget({ target: route.target, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal });
6047
+ return steerWorkflowForegroundTarget({ target: route.target, message, mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode), index: paramsWithResolvedCwd.index });
5312
6048
  }
5313
6049
  if (location.asyncDir) {
5314
6050
  const unsupported = externalRunnerControlError(location.asyncDir, "steer");
@@ -5318,7 +6054,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5318
6054
  state: deps.state,
5319
6055
  runId,
5320
6056
  message,
5321
- mode: paramsWithResolvedCwd.mode,
6057
+ mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode),
5322
6058
  index: paramsWithResolvedCwd.index,
5323
6059
  kill: deps.kill,
5324
6060
  location,
@@ -5344,18 +6080,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5344
6080
  const text = error instanceof Error ? error.message : String(error);
5345
6081
  return { content: [{ type: "text", text }], isError: true, details: { mode: "management", results: [] } };
5346
6082
  }
5347
- if (resolved?.kind === "nested") return steerNestedRun(omitUndefinedProperties({ target: resolved, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal }));
6083
+ if (resolved?.kind === "nested") return steerNestedRun(omitUndefinedProperties({ target: resolved, message, mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode), index: paramsWithResolvedCwd.index, signal }));
5348
6084
  if (resolved?.kind === "foreground") {
5349
6085
  const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, childRunId: resolved.id, asyncDirRoot: DIRS.async });
5350
6086
  if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
5351
- return steerWorkflowForegroundTarget({ target: route.target, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal });
6087
+ return steerWorkflowForegroundTarget({ target: route.target, message, mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode), index: paramsWithResolvedCwd.index });
5352
6088
  }
5353
6089
  if (resolved?.kind !== "async") return { content: [{ type: "text", text: `No async run found for '${targetRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
5354
6090
  const resolvedStatus = resolved.location.asyncDir ? readStatus(resolved.location.asyncDir) : null;
5355
6091
  if (resolvedStatus?.mode === "workflow") {
5356
6092
  const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, workflowRunId: resolvedStatus.runId || resolved.id, asyncDirRoot: DIRS.async });
5357
6093
  if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
5358
- return steerWorkflowForegroundTarget({ target: route.target, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal });
6094
+ return steerWorkflowForegroundTarget({ target: route.target, message, mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode), index: paramsWithResolvedCwd.index });
5359
6095
  }
5360
6096
  if (resolved.location.asyncDir) {
5361
6097
  const unsupported = externalRunnerControlError(resolved.location.asyncDir, "steer");
@@ -5365,7 +6101,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5365
6101
  state: deps.state,
5366
6102
  runId: resolved.id,
5367
6103
  message,
5368
- mode: paramsWithResolvedCwd.mode,
6104
+ mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode),
5369
6105
  index: paramsWithResolvedCwd.index,
5370
6106
  kill: deps.kill,
5371
6107
  location: resolved.location,
@@ -5434,9 +6170,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5434
6170
  if (action === "stop") {
5435
6171
  const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
5436
6172
  const workflowController = targetRunId ? deps.state.workflowControllers?.get(targetRunId) : undefined;
5437
- if (workflowController) {
6173
+ if (workflowController && targetRunId) {
6174
+ const stopChild = deps.state.workflowChildStops?.get(targetRunId);
5438
6175
  if (paramsWithResolvedCwd.childId !== undefined) {
5439
- const workflowRunId = targetRunId!;
6176
+ const workflowRunId = targetRunId;
5440
6177
  const asyncJob = deps.state.asyncJobs.get(workflowRunId);
5441
6178
  if (!asyncJob?.asyncDir) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
5442
6179
  const status = readStatus(asyncJob.asyncDir);
@@ -5444,9 +6181,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5444
6181
  const resolution = resolveAsyncStatusChild(status, paramsWithResolvedCwd.childId);
5445
6182
  if (!resolution.ok) return { content: [{ type: "text", text: resolution.message }], isError: true, details: { mode: "management", results: [] } };
5446
6183
  if (!isStoppableAsyncStatusStep(resolution.child.step)) return { content: [{ type: "text", text: `Child '${paramsWithResolvedCwd.childId}' in async run '${targetRunId}' is ${resolution.child.step.status}; stop only supports pending or running children.` }], isError: true, details: { mode: "management", results: [] } };
5447
- const stopChild = deps.state.workflowChildStops?.get(targetRunId!);
5448
6184
  if (!stopChild) return { content: [{ type: "text", text: `Workflow ${targetRunId} child stop is unavailable in this extension runtime.` }], isError: true, details: { mode: "management", results: [] } };
5449
- if (!stopChild(resolution.child.id)) return { content: [{ type: "text", text: `Child '${paramsWithResolvedCwd.childId}' in workflow ${workflowRunId} is not available to stop.` }], isError: true, details: { mode: "management", results: [] } };
6185
+ if (!stopChild(resolution.child.id, `Workflow child '${resolution.child.id}' stopped.`)) return { content: [{ type: "text", text: `Child '${paramsWithResolvedCwd.childId}' in workflow ${workflowRunId} is not available to stop.` }], isError: true, details: { mode: "management", results: [] } };
5450
6186
  try {
5451
6187
  fs.appendFileSync(path.join(asyncJob.asyncDir, "events.jsonl"), `${JSON.stringify({
5452
6188
  type: "subagent.child-status",
@@ -5455,7 +6191,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5455
6191
  childId: resolution.child.id,
5456
6192
  status: "stopping",
5457
6193
  ts: Date.now(),
5458
- reason: "user",
6194
+ reason: "subagent-action",
5459
6195
  source: "async",
5460
6196
  stepIndex: resolution.child.index,
5461
6197
  agent: resolution.child.step.agent,
@@ -5469,17 +6205,16 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5469
6205
  }
5470
6206
  return { content: [{ type: "text", text: `Stop requested for child ${resolution.child.id} in async workflow ${workflowRunId}.` }], details: { mode: "management", results: [] } };
5471
6207
  }
5472
- workflowController.abort(new Error("Workflow stopped by user."));
6208
+ const asyncJob = deps.state.asyncJobs.get(targetRunId);
6209
+ const status = asyncJob?.asyncDir ? readStatus(asyncJob.asyncDir) : undefined;
6210
+ if (status) stopStoppableAsyncStatusChildren(status, stopChild, "Workflow stopped.");
6211
+ workflowController.abort(new Error("Workflow stopped."));
5473
6212
  return { content: [{ type: "text", text: `Stop requested for async workflow ${targetRunId}.` }], details: { mode: "management", results: [] } };
5474
6213
  }
5475
6214
  let resolved: ResolvedSubagentRunId | undefined;
5476
6215
  if (paramsWithResolvedCwd.dir) {
5477
6216
  try {
5478
6217
  const location = resolveAsyncRunLocation(paramsWithResolvedCwd, DIRS.async, DIRS.results);
5479
- const existingStatus = readStatus(location.asyncDir ?? "");
5480
- if (existingStatus?.mode === "workflow" && existingStatus.state === "running") {
5481
- return { content: [{ type: "text", text: `Workflow ${existingStatus.runId} is not controlled by this extension runtime; reload recovery cannot stop it safely.` }], isError: true, details: { mode: "management", results: [] } };
5482
- }
5483
6218
  const stopResult = stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location, paramsWithResolvedCwd.childId);
5484
6219
  return stopResult ?? { content: [{ type: "text", text: `No running or queued async run was found for '${targetRunId ?? paramsWithResolvedCwd.dir}'.` }], isError: true, details: { mode: "management", results: [] } };
5485
6220
  } catch (error) {
@@ -5496,12 +6231,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5496
6231
  }
5497
6232
  if (resolved?.kind === "nested") return { content: [{ type: "text", text: "action='stop' supports current-session top-level async runs only." }], isError: true, details: { mode: "management", results: [] } };
5498
6233
  if (resolved?.kind === "foreground") return { content: [{ type: "text", text: "action='stop' supports async runs only. Use action='interrupt' for foreground runs." }], isError: true, details: { mode: "management", results: [] } };
5499
- if (resolved?.kind === "async") {
5500
- const existingStatus = readStatus(resolved.location.asyncDir ?? "");
5501
- if (existingStatus?.mode === "workflow" && existingStatus.state === "running") {
5502
- return { content: [{ type: "text", text: `Workflow ${resolved.id} is not controlled by this extension runtime; reload recovery cannot stop it safely.` }], isError: true, details: { mode: "management", results: [] } };
5503
- }
5504
- }
5505
6234
  const stopResult = stopAsyncRun(
5506
6235
  deps.state,
5507
6236
  resolved?.kind === "async" ? resolved.id : targetRunId,
@@ -5574,7 +6303,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5574
6303
  });
5575
6304
  }
5576
6305
 
5577
- const { blocked, depth, maxDepth } = checkSubagentDepth(deps.config.maxSubagentDepth);
6306
+ const { blocked, depth, maxDepth } = checkSubagentDepth(deps.config.maxSubagentDepth, deps.childRuntime);
5578
6307
  if (blocked) {
5579
6308
  return {
5580
6309
  content: [
@@ -5614,15 +6343,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5614
6343
  const scope: AgentScope = resolveExecutionAgentScope(effectiveParams.agentScope);
5615
6344
  const effectiveCwd = effectiveParams.cwd ?? ctx.cwd;
5616
6345
  const parentSessionFile = ctx.sessionManager.getSessionFile() ?? null;
5617
- const discovered = deps.discoverAgents(effectiveCwd, scope);
6346
+ const discovered = deps.discoverAgents(effectiveCwd, scope, requestParentModel?.provider);
5618
6347
  const discoveredAgents = discovered.agents;
5619
- const canonicalParams = canonicalizeExecutionParams(effectiveParams, discoveredAgents, discovered.agentDiagnostics);
6348
+ const unknownAgentDiagnosticContext = diagnosticContextFromDiscovery(discovered, effectiveCwd, scope);
6349
+ const canonicalParams = canonicalizeExecutionParams(effectiveParams, discoveredAgents, discovered.agentDiagnostics, unknownAgentDiagnosticContext);
5620
6350
  if (canonicalParams.error) return buildRequestedModeError(effectiveParams, canonicalParams.error);
5621
6351
  effectiveParams = canonicalParams.params!;
6352
+ if (effectiveParams.worktree === undefined && deps.config.worktree !== undefined) {
6353
+ effectiveParams = { ...effectiveParams, worktree: deps.config.worktree };
6354
+ }
5622
6355
  const modelScope = discovered.modelScope;
5623
6356
  effectiveParams = applySingleAgentLaunchDefaults(effectiveParams, discoveredAgents);
5624
- const turnBudget = resolveTurnBudgetConfig(effectiveParams.turnBudget ?? deps.config.turnBudget);
5625
- if (turnBudget.error) return buildRequestedModeError(effectiveParams, turnBudget.error);
5626
6357
  // An agent-level defaultContext is a preference, unlike an explicit request.
5627
6358
  // Prefer fork only when the parent session is persisted and has a current leaf;
5628
6359
  // otherwise use fresh immediately instead of launching a guaranteed-to-fail fork.
@@ -5647,8 +6378,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5647
6378
  });
5648
6379
  const agents = applyScopedIntercomBridgeToAgents(discoveredAgents, intercomBridge, contextPolicy);
5649
6380
  const runId = randomUUID();
5650
- const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
5651
- const nestedParentAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
6381
+ const inheritedNestedRouteValue = inheritedNestedRoute(deps);
6382
+ const nestedParentAddress = inheritedNestedRouteValue ? inheritedNestedParentAddress(deps) : undefined;
5652
6383
  const shareEnabled = effectiveParams.share === true;
5653
6384
  const hasChain = (effectiveParams.chain?.length ?? 0) > 0;
5654
6385
  const hasTasks = (effectiveParams.tasks?.length ?? 0) > 0;
@@ -5665,6 +6396,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5665
6396
  hasTasks,
5666
6397
  hasSingle,
5667
6398
  allowClarifyTaskPrompt,
6399
+ unknownAgentDiagnosticContext,
5668
6400
  );
5669
6401
  if (validationError) return validationError;
5670
6402
 
@@ -5679,34 +6411,49 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5679
6411
  if (spawnPreflight.error) return spawnBudgetErrorResult(spawnPreflight.error, foregroundMode);
5680
6412
 
5681
6413
  let forkSessionFileForIndex: (idx?: number) => string | undefined = () => undefined;
6414
+ let prepareForkSessionForIndex: (idx?: number) => Promise<void> = async () => {};
5682
6415
  let forkThinkingOverrideForIndex: (idx?: number) => AgentConfig["thinking"] | undefined = () => undefined;
5683
- let prepareForkThinking = (_agentName: string, _index: number, _modelOverride?: string, _modelOverrideFromParent?: boolean): void => {};
6416
+ let prepareForkThinking = (_agentName: string, _index: number, _modelOverride?: string, _modelOverrideFromParent?: boolean, _modelOrigin?: ModelOrigin): void => {};
5684
6417
  const forkThinkingRequirements = new Map<number, boolean>();
5685
6418
  const forkThinkingDowngrades = new Map<number, string>();
5686
6419
  try {
5687
6420
  const forkAvailableModels = contextPolicy.usesFork ? ctx.modelRegistry.getAvailable().map(toModelInfo) : [];
5688
6421
  const parentModel = requestParentModel;
5689
- prepareForkThinking = (agentName, index, modelOverride, modelOverrideFromParent) => {
6422
+ prepareForkThinking = (agentName, index, modelOverride, modelOverrideFromParent, storedOrigin) => {
5690
6423
  const agentConfig = agents.find((agent) => agent.name === agentName);
5691
6424
  if (agentConfig?.runner?.type === "external-cli" || agentConfig?.runner?.type === "external-job") {
5692
6425
  forkThinkingRequirements.set(index, true);
5693
6426
  return;
5694
6427
  }
6428
+ const effectiveStoredOrigin = storedOrigin === "configured" && modelOverride === undefined && agentConfig?.model === undefined
6429
+ ? undefined
6430
+ : storedOrigin;
6431
+ const origin = resolveModelOrigin({
6432
+ fromParent: modelOverrideFromParent,
6433
+ storedOrigin: effectiveStoredOrigin,
6434
+ explicitModel: modelOverrideFromParent || effectiveStoredOrigin === "configured" ? undefined : modelOverride,
6435
+ agentModel: agentConfig?.model,
6436
+ parentModel,
6437
+ });
5695
6438
  const primaryModel = modelOverrideFromParent
5696
6439
  ? modelOverride
5697
6440
  : resolveEffectiveSubagentModel(
5698
- modelOverride,
6441
+ effectiveStoredOrigin === "configured" ? undefined : modelOverride,
5699
6442
  agentConfig?.model,
5700
6443
  parentModel,
5701
6444
  forkAvailableModels,
5702
6445
  agentConfig?.modelProvider ?? parentModel?.provider,
6446
+ { source: origin === "explicit" ? "explicit" : "inherited" },
5703
6447
  );
5704
6448
  const candidates = buildModelCandidates(
5705
6449
  primaryModel,
5706
6450
  agentConfig?.fallbackModels,
5707
6451
  forkAvailableModels,
5708
6452
  agentConfig?.modelProvider ?? parentModel?.provider,
5709
- { primaryModelFromParent: modelOverrideFromParent ?? inheritsParentModel(modelOverride, agentConfig?.model, parentModel) },
6453
+ {
6454
+ primaryModelFromParent: origin === "inherited",
6455
+ origin,
6456
+ },
5710
6457
  );
5711
6458
  forkThinkingRequirements.set(
5712
6459
  index,
@@ -5714,9 +6461,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5714
6461
  || candidates.some((candidate) => forkedChildRequiresThinkingOff(candidate, forkAvailableModels, parentModel?.provider)),
5715
6462
  );
5716
6463
  };
6464
+ const pruneSession = contextPolicy.usesFork && deps.config.forkContext?.mode === "pruned"
6465
+ ? await createPrunedForkSessionWriter(ctx, deps.config.forkContext, signal)
6466
+ : undefined;
5717
6467
  const forkContextResolver = createForkContextResolver(ctx.sessionManager, contextPolicy.usesFork ? "fork" : undefined, {
5718
6468
  forceThinkingOffForIndex: (index) => forkThinkingRequirements.get(index) ?? true,
6469
+ ...(pruneSession ? { pruneSession } : {}),
5719
6470
  });
6471
+ prepareForkSessionForIndex = forkContextResolver.prepareSessionForIndex;
5720
6472
  forkSessionFileForIndex = forkContextResolver.sessionFileForIndex;
5721
6473
  forkThinkingOverrideForIndex = forkContextResolver.thinkingOverrideForIndex;
5722
6474
  } catch (error) {
@@ -5748,7 +6500,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5748
6500
  const asyncRunId = requestedWorkflowChildAsyncId && path.basename(requestedWorkflowChildAsyncId) === requestedWorkflowChildAsyncId
5749
6501
  ? requestedWorkflowChildAsyncId
5750
6502
  : randomUUID();
5751
- const topLevelAsyncCapacityEligible = depth === 0 && !inheritedNestedRoute && !effectiveParams.workflowParentRunId;
6503
+ const topLevelAsyncCapacityEligible = depth === 0 && !inheritedNestedRouteValue && !effectiveParams.workflowParentRunId;
5752
6504
  const topLevelAsync = effectiveAsync && topLevelAsyncCapacityEligible;
5753
6505
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
5754
6506
  if (topLevelAsync) {
@@ -5760,8 +6512,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5760
6512
  runId: asyncRunId,
5761
6513
  kind: "runner",
5762
6514
  asyncDir: path.join(DIRS.async, asyncRunId),
5763
- }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) });
5764
- deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(requestSessionId, activeLimit, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) });
6515
+ }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) });
6516
+ deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(requestSessionId, activeLimit, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) });
5765
6517
  } catch (error) {
5766
6518
  if (error instanceof ActiveAsyncCapacityError) {
5767
6519
  deps.state.activeAsyncCapacity = error.snapshot;
@@ -5773,9 +6525,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5773
6525
 
5774
6526
  let runFanoutBudget: RunFanoutBudgetDescriptor;
5775
6527
  try {
5776
- const inheritedRunFanoutBudget = effectiveParams.runFanoutBudget ? undefined : decodeRunFanoutBudgetDescriptor(process.env[RUN_FANOUT_BUDGET_ENV]);
6528
+ const inheritedRunFanoutBudgetValue = effectiveParams.runFanoutBudget ? undefined : inheritedRunFanoutBudget(deps);
5777
6529
  runFanoutBudget = effectiveParams.runFanoutBudget
5778
- ?? (inheritedRunFanoutBudget ? { ...inheritedRunFanoutBudget, parentPath: `${inheritedRunFanoutBudget.parentPath ? `${inheritedRunFanoutBudget.parentPath}/` : ""}${runId}` } : undefined)
6530
+ ?? (inheritedRunFanoutBudgetValue ? { ...inheritedRunFanoutBudgetValue, parentPath: `${inheritedRunFanoutBudgetValue.parentPath ? `${inheritedRunFanoutBudgetValue.parentPath}/` : ""}${runId}` } : undefined)
5779
6531
  ?? createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun));
5780
6532
  if (!effectiveParams.runFanoutAdmitted) claimRunFanoutBatch(runFanoutBudget, staticRunFanoutPaths(effectiveParams));
5781
6533
  } catch (error) {
@@ -5783,7 +6535,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5783
6535
  if (error instanceof RunFanoutLimitError) return runFanoutErrorResult(error, foregroundMode);
5784
6536
  return buildRequestedModeError(effectiveParams, error instanceof Error ? error.message : String(error));
5785
6537
  }
5786
- const nestedRoute = inheritedNestedRoute ?? createNestedRoute(runId);
6538
+ const nestedRoute = inheritedNestedRouteValue ?? createNestedRoute(runId);
5787
6539
 
5788
6540
  const artifactConfig: ArtifactConfig = omitUndefinedProperties({
5789
6541
  ...DEFAULT_ARTIFACT_CONFIG,
@@ -5819,25 +6571,30 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5819
6571
  }
5820
6572
  const sessionDirForIndex = (idx?: number) =>
5821
6573
  path.join(sessionRoot, `run-${idx ?? 0}`);
5822
- const forkSessionFileForTask: ForkSessionFileForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent) => {
6574
+ const forkSessionFileForTask: ForkSessionFileForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent, modelOrigin) => {
5823
6575
  if (!shouldForkAgent(contextPolicy, agentName)) return undefined;
5824
- prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent);
6576
+ prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin);
5825
6577
  return forkSessionFileForIndex(idx);
5826
6578
  };
5827
- const forkThinkingOverrideForTask: ForkThinkingOverrideForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent) => {
6579
+ const prepareForkSessionForTask: PrepareForkSessionForTask = async (agentName, idx = 0, modelOverride, modelOverrideFromParent, modelOrigin) => {
6580
+ if (!shouldForkAgent(contextPolicy, agentName)) return;
6581
+ prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin);
6582
+ await prepareForkSessionForIndex(idx);
6583
+ };
6584
+ const forkThinkingOverrideForTask: ForkThinkingOverrideForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent, modelOrigin) => {
5828
6585
  if (!shouldForkAgent(contextPolicy, agentName)) return delegatedThinkingOverride;
5829
- prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent);
6586
+ prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin);
5830
6587
  const override = forkThinkingOverrideForIndex(idx);
5831
6588
  if (override === "off") forkThinkingDowngrades.set(idx, agentName);
5832
6589
  return override ?? delegatedThinkingOverride;
5833
6590
  };
5834
- const childSessionFileForTask: ForkSessionFileForTask = (agentName, idx, modelOverride, modelOverrideFromParent) =>
5835
- forkSessionFileForTask(agentName, idx, modelOverride, modelOverrideFromParent) ?? path.join(sessionDirForIndex(idx), "session.jsonl");
6591
+ const childSessionFileForTask: ForkSessionFileForTask = (agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin) =>
6592
+ forkSessionFileForTask(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin) ?? path.join(sessionDirForIndex(idx), "session.jsonl");
5836
6593
  const childSessionFileForIndex = (idx?: number) =>
5837
6594
  path.join(sessionDirForIndex(idx), "session.jsonl");
5838
6595
  try {
5839
- if (!(effectiveParams.clarify === true && ctx.hasUI)) {
5840
- preflightForkSessionsForStaticTasks(effectiveParams, contextPolicy, forkSessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems);
6596
+ if (!(effectiveParams.clarify === true && ctx.hasUI) || deps.config.forkContext?.mode === "pruned") {
6597
+ await preflightForkSessionsForStaticTasks(effectiveParams, contextPolicy, prepareForkSessionForTask, deps.config.chain?.dynamicFanout?.maxItems);
5841
6598
  }
5842
6599
  } catch (error) {
5843
6600
  activeAsyncCapacity?.rollback();
@@ -5906,10 +6663,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5906
6663
  const execData: ExecutionContextData = omitUndefinedProperties({
5907
6664
  params: effectiveParams,
5908
6665
  effectiveCwd,
6666
+ requestedCwd,
5909
6667
  ctx,
5910
6668
  signal,
5911
6669
  onUpdate: onUpdateWithContext,
5912
6670
  agents,
6671
+ unknownAgentDiagnosticContext,
5913
6672
  recoveryAgents: discoveredAgents,
5914
6673
  runId,
5915
6674
  shareEnabled,
@@ -5924,10 +6683,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5924
6683
  effectiveAsync,
5925
6684
  asyncRunId,
5926
6685
  controlConfig,
6686
+ ...(delegatedExecution ? { suppressUnchangedDelegationUpdates: true } : {}),
5927
6687
  intercomBridge,
5928
6688
  nestedRoute,
5929
6689
  timeoutMs: foregroundTimeout.timeoutMs,
5930
- turnBudget: turnBudget.turnBudget,
5931
6690
  toolBudget: runToolBudget.toolBudget,
5932
6691
  usageBudget: usageBudget.budget,
5933
6692
  allowZeroToolBudget,
@@ -5942,22 +6701,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5942
6701
  runFanoutBudget,
5943
6702
  topLevelAsyncCapacityEligible,
5944
6703
  activeAsyncCapacity,
6704
+ workflowChildPermitLaunch,
5945
6705
  });
5946
6706
 
5947
6707
  const foregroundDescription = selectedAgentNames.length === 1
5948
6708
  ? `${selectedAgentNames[0]} child`
5949
6709
  : `${selectedAgentNames.length} live children`;
5950
- const parentWorkflowStatus = effectiveParams.workflowParentRunId
5951
- ? readStatus(path.join(DIRS.async, effectiveParams.workflowParentRunId))
5952
- : null;
5953
- const workflowSteeringDir = effectiveParams.workflowParentRunId
5954
- && requestSessionId
5955
- && deps.state.workflowControllers?.has(effectiveParams.workflowParentRunId)
5956
- && parentWorkflowStatus?.mode === "workflow"
5957
- && (parentWorkflowStatus.state === "running" || parentWorkflowStatus.state === "queued")
5958
- && parentWorkflowStatus.sessionId === requestSessionId
5959
- ? workflowForegroundSteeringDir(DIRS.async, effectiveParams.workflowParentRunId, runId)
5960
- : undefined;
5961
6710
  const foregroundControl: ForegroundRunControl | undefined = effectiveAsync
5962
6711
  ? undefined
5963
6712
  : compactOptional<ForegroundRunControl>({
@@ -5966,7 +6715,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5966
6715
  mode: foregroundMode,
5967
6716
  ...(effectiveParams.workflowParentRunId ? { parentWorkflowRunId: effectiveParams.workflowParentRunId } : {}),
5968
6717
  ...(effectiveParams.workflowKey ? { workflowKey: effectiveParams.workflowKey } : {}),
5969
- workflowSteeringDir,
5970
6718
  startedAt: Date.now(),
5971
6719
  updatedAt: Date.now(),
5972
6720
  cwd: effectiveCwd,
@@ -6019,7 +6767,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6019
6767
  }
6020
6768
 
6021
6769
  const writeNestedForegroundEvent = (type: "subagent.nested.started" | "subagent.nested.completed", result?: AgentToolResult<Details>): void => {
6022
- if (!inheritedNestedRoute || !nestedParentAddress) return;
6770
+ if (!inheritedNestedRouteValue || !nestedParentAddress) return;
6023
6771
  const now = Date.now();
6024
6772
  const details = result?.details;
6025
6773
  const state = type === "subagent.nested.started"
@@ -6053,7 +6801,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6053
6801
  ? resolveSubagentIntercomTarget(runId, agentsForSummary[0], 0)
6054
6802
  : undefined;
6055
6803
  try {
6056
- writeNestedEvent(inheritedNestedRoute, compactOptional<Parameters<typeof writeNestedEvent>[1]>({
6804
+ writeNestedEvent(inheritedNestedRouteValue, compactOptional<Parameters<typeof writeNestedEvent>[1]>({
6057
6805
  type,
6058
6806
  ts: now,
6059
6807
  parentRunId: nestedParentAddress.parentRunId,
@@ -6064,13 +6812,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6064
6812
  parentStepIndex: nestedParentAddress.parentStepIndex,
6065
6813
  depth: nestedParentAddress.depth,
6066
6814
  path: nestedParentAddress.path,
6067
- ownerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,
6815
+ ownerIntercomTarget: deps.childRuntime?.intercomSessionName,
6068
6816
  leafIntercomTarget,
6069
6817
  intercomTarget: leafIntercomTarget,
6070
6818
  ownerState: state === "running" ? "live" : "gone",
6071
6819
  mode: foregroundMode,
6072
6820
  state,
6073
6821
  agent: agentsForSummary[0],
6822
+ ...(details?.results.length === 1 && details.results[0]?.sessionName ? { sessionName: details.results[0].sessionName } : {}),
6074
6823
  agents: agentsForSummary,
6075
6824
  ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.model : details?.results[0]?.model) ? { model: type === "subagent.nested.started" ? startedLaunches[0]?.model : details?.results[0]?.model } : {}),
6076
6825
  ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.thinking : details?.results[0]?.thinking) ? { thinking: type === "subagent.nested.started" ? startedLaunches[0]?.thinking : details?.results[0]?.thinking } : {}),
@@ -6089,6 +6838,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6089
6838
  : details?.results.length
6090
6839
  ? { steps: details.results.map((child) => ({
6091
6840
  agent: child.agent,
6841
+ ...(child.sessionName ? { sessionName: child.sessionName } : {}),
6092
6842
  status: child.interrupted || child.detached ? "paused" as const : child.exitCode === 0 ? "complete" as const : "failed" as const,
6093
6843
  ...(child.model ? { model: child.model } : {}),
6094
6844
  ...(child.thinking ? { thinking: child.thinking } : {}),
@@ -6112,10 +6862,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6112
6862
  }
6113
6863
  if (workflowLaunchObserver) {
6114
6864
  const singleTask = hasTasks && effectiveParams.tasks?.length === 1 ? effectiveParams.tasks[0] : undefined;
6865
+ const singleSessionName = hasSingle
6866
+ ? deriveChildSessionName({ agent: effectiveParams.agent!, task: effectiveParams.task })
6867
+ : singleTask
6868
+ ? deriveChildSessionName({ agent: singleTask.agent, task: singleTask.task })
6869
+ : undefined;
6115
6870
  const launch = hasSingle
6116
- ? { agent: effectiveParams.agent!, sessionFile: childSessionFileForTask(effectiveParams.agent!, 0, effectiveParams.model), async: effectiveAsync, ...(effectiveAsync ? { runId: asyncRunId } : {}) }
6871
+ ? { agent: effectiveParams.agent!, ...(singleSessionName ? { sessionName: singleSessionName } : {}), sessionFile: childSessionFileForTask(effectiveParams.agent!, 0, effectiveParams.model), async: effectiveAsync, runId: effectiveAsync ? asyncRunId : runId }
6117
6872
  : singleTask
6118
- ? { agent: singleTask.agent, sessionFile: childSessionFileForTask(singleTask.agent, 0, singleTask.model), async: effectiveAsync, ...(effectiveAsync ? { runId: asyncRunId } : {}) }
6873
+ ? { agent: singleTask.agent, ...(singleSessionName ? { sessionName: singleSessionName } : {}), sessionFile: childSessionFileForTask(singleTask.agent, 0, singleTask.model), async: effectiveAsync, runId: effectiveAsync ? asyncRunId : runId }
6119
6874
  : undefined;
6120
6875
  if (launch) {
6121
6876
  workflowLaunchObservers.delete(params);
@@ -6167,15 +6922,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6167
6922
  ): Promise<AgentToolResult<Details>> => {
6168
6923
  const normalizedAction = typeof params.action === "string" ? params.action.trim() : params.action;
6169
6924
  const requestParams = normalizedAction ? { ...params, action: normalizedAction } : params;
6170
- if (normalizedAction) return execute(id, requestParams, signal, onUpdate, ctx);
6171
- const { depth } = checkSubagentDepth(deps.config.maxSubagentDepth);
6925
+ if (normalizedAction) return execute(id, requestParams, signal, onUpdate, ctx).then(withAggregatedToolUsage);
6926
+ const { depth } = checkSubagentDepth(deps.config.maxSubagentDepth, deps.childRuntime);
6172
6927
  const dispatchParams = applyForceTopLevelAsyncOverride(requestParams, depth, deps.config.forceTopLevelAsync === true);
6173
6928
  const runsForeground = dispatchParams.clarify === true || (dispatchParams.async ?? deps.asyncByDefault) !== true;
6174
- if (!runsForeground) return execute(id, requestParams, signal, onUpdate, ctx);
6929
+ if (!runsForeground) return execute(id, requestParams, signal, onUpdate, ctx).then(withAggregatedToolUsage);
6175
6930
  if (deps.state.subagentInProgress === true) return duplicateSubagentCallResult(requestParams);
6176
6931
  deps.state.subagentInProgress = true;
6177
6932
  try {
6178
- return await execute(id, requestParams, signal, onUpdate, ctx);
6933
+ return withAggregatedToolUsage(await execute(id, requestParams, signal, onUpdate, ctx));
6179
6934
  } finally {
6180
6935
  deps.state.subagentInProgress = false;
6181
6936
  }
@@ -6188,11 +6943,24 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6188
6943
  onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
6189
6944
  ctx: ExtensionContext,
6190
6945
  ): Promise<AgentToolResult<Details>> => {
6191
- const normalized = normalizePublicSubagentExecution(params, { asyncByDefault: deps.asyncByDefault });
6946
+ const normalized = normalizePublicSubagentExecution(params);
6192
6947
  if (!normalized.ok) {
6193
6948
  return Promise.resolve({ content: [{ type: "text", text: normalized.error }], isError: true, details: { mode: normalized.mode, results: [] } });
6194
6949
  }
6195
- return executeWithSingleDispatchGuard(id, normalized.params, signal, onUpdate, ctx);
6950
+ let publicParams = normalized.params as SubagentParamsLike;
6951
+ if (publicParams.workflow !== undefined) {
6952
+ const resolved = resolveWorkflowResource(publicParams.workflow, publicParams.args);
6953
+ if (!resolved.ok) return Promise.resolve({ content: [{ type: "text", text: resolved.error }], isError: true, details: { mode: "workflow", results: [] } });
6954
+ const { workflow: _workflow, args: _args, ...withoutResourceInput } = publicParams;
6955
+ publicParams = { ...withoutResourceInput, workflowScript: resolved.resource.script };
6956
+ workflowResourcePermits.set(publicParams, resolved.resource.permit);
6957
+ }
6958
+ const loaded = loadWorkflowScriptPath(publicParams, ctx.cwd);
6959
+ if (loaded.error) {
6960
+ return Promise.resolve({ content: [{ type: "text", text: loaded.error }], isError: true, details: { mode: publicParams.action ? "management" : "workflow", results: [] } });
6961
+ }
6962
+ publicExecutions.add(loaded.params!);
6963
+ return executeWithSingleDispatchGuard(id, loaded.params!, signal, onUpdate, ctx);
6196
6964
  };
6197
6965
 
6198
6966
  const executeDelegated = async (
@@ -6206,15 +6974,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6206
6974
  const privateParams = delegatedParams as SubagentParamsLike & {
6207
6975
  delegatedThinkingOverride?: AgentConfig["thinking"];
6208
6976
  delegatedAllowZeroToolBudget?: true;
6977
+ delegatedWorkflowPermit?: WorkflowChildPermit;
6209
6978
  };
6210
6979
  const thinkingOverride = privateParams.delegatedThinkingOverride;
6211
6980
  const allowZeroToolBudget = privateParams.delegatedAllowZeroToolBudget === true;
6981
+ const workflowPermit = privateParams.delegatedWorkflowPermit;
6212
6982
  delete privateParams.delegatedThinkingOverride;
6213
6983
  delete privateParams.delegatedAllowZeroToolBudget;
6984
+ delete privateParams.delegatedWorkflowPermit;
6214
6985
  if (thinkingOverride !== undefined) delegatedThinkingOverrides.set(delegatedParams, thinkingOverride);
6215
6986
  if (allowZeroToolBudget) delegatedZeroToolBudgets.add(delegatedParams);
6987
+ if (workflowPermit) workflowPermitContexts.set(delegatedParams, { root: workflowPermit });
6216
6988
  delegatedExecutions.add(delegatedParams);
6217
- return execute(id, delegatedParams, signal, onUpdate, ctx);
6989
+ return withAggregatedToolUsage(await execute(id, delegatedParams, signal, onUpdate, ctx));
6218
6990
  };
6219
6991
 
6220
6992
  const executeScheduled = (
@@ -6232,7 +7004,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6232
7004
  });
6233
7005
  scheduledOwnerExecutors.set(ownerSessionId, ownerExecutor);
6234
7006
  }
6235
- return ownerExecutor.execute(id, params, signal, undefined, ctx);
7007
+ return ownerExecutor.executePublic(id, params, signal, undefined, ctx);
6236
7008
  };
6237
7009
 
6238
7010
  return { execute: executeWithSingleDispatchGuard, executePublic, executeDelegated, executeScheduled };