@xzzpig/pi-subagents 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -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,61 +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
- import type { ModelScopeConfig } from "../shared/model-scope.ts";
34
- import { aggregateParallelOutputs } from "../shared/parallel-utils.ts";
33
+ import { resolveModelScopesForAgent, type ModelScopeConfig } from "../shared/model-scope.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
- import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
77
- import { cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
78
- import { compactForegroundDetails, getSingleResultOutput, mapConcurrent, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage } from "../../shared/utils.ts";
67
+ import { normalizeExtensionBindings, type ExtensionBindings } from "../shared/extension-bindings.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";
79
71
  import { createTaskMutationArbiter } from "../shared/llm-intent-arbiter.ts";
80
- import { DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore } from "../shared/parallel-utils.ts";
81
- 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";
82
73
  import { summarizeContextModes, type ContextMode, type ContextSummary } from "../shared/context-mode.ts";
83
74
  import {
84
75
  attachNestedChildrenToResultChildren,
@@ -88,16 +79,13 @@ import {
88
79
  resolveSubagentResultStatus,
89
80
  stripDetailsOutputsForIntercomReceipt,
90
81
  } from "../../intercom/result-intercom.ts";
91
- import { applySteeringRecoveryAgentConfig, asyncReviveRequiresRecoveryDescriptor, buildRevivedAsyncTask, resolveAsyncResumeTarget, resolveAsyncRunLocation } from "../background/async-resume.ts";
82
+ import { applySteeringRecoveryAgentConfig, asyncReviveRequiresRecoveryDescriptor, buildRevivedAsyncTask, readAsyncRecoveryDescriptor, resolveAsyncResumeTarget, resolveAsyncRunLocation } from "../background/async-resume.ts";
92
83
  import { deliverInterruptRequest, readRevivalBriefs, requestAsyncSteer, type SteerDeliveryMode } from "../background/control-channel.ts";
93
84
  import { updateSteeringTarget, waitForSteeringAction } from "../background/steering.ts";
94
85
  import { canQueueRetainedAsyncFollowUp, steerAsyncRun } from "./async-steering-action.ts";
95
86
  import {
96
- removeWorkflowForegroundSteeringRoute,
97
87
  resolveWorkflowForegroundSteeringTarget,
98
88
  steerWorkflowForegroundTarget,
99
- workflowForegroundSteeringDir,
100
- workflowForegroundSteeringLaunchOptions,
101
89
  } from "./workflow-foreground-steering.ts";
102
90
  import { stopAsyncRun } from "./async-stop-action.ts";
103
91
  import { dismissRecoveredWorkflow } from "./async-dismiss-action.ts";
@@ -105,10 +93,15 @@ import { promotePausedWorkflowIfSettled, reconcileDetachedWorkflowChildCompletio
105
93
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
106
94
  import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
107
95
  import { resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
108
- 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";
109
98
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
110
99
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
100
+ import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, stopStoppableAsyncStatusChildren } from "../shared/child-identity.ts";
111
101
  import { inspectSubagentStatus } from "../background/run-status.ts";
102
+ import { getExternalJobProvider } from "../../api/external-job-provider.ts";
103
+ import { externalJobFollowUpRequestDigest, externalJobFollowUpRequestId, externalJobFollowUpRunId, externalJobPromptDigest, externalJobStableJson } from "../shared/external-job-runner.ts";
104
+ import { externalCliReceiptMetadata, normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
112
105
  import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.ts";
113
106
  import { handleMissionAction, MISSION_ACTIONS } from "../../missions/actions.ts";
114
107
  import { attachMissionToLaunchResult, prepareMissionLaunch, writeMissionAsyncBinding, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
@@ -118,18 +111,33 @@ import { createMissionWorkflowState } from "../../missions/workflow-state.ts";
118
111
  import { resolveAuthorityDecision } from "../../policy/authority.ts";
119
112
  import { handleHerdrInspectorAction, HERDR_INSPECTOR_ACTIONS } from "../../inspectors/herdr/actions.ts";
120
113
  import { handleHerdrProjectPaneAction, HERDR_PROJECT_PANE_ACTIONS } from "../../inspectors/herdr/project-panes.ts";
121
- 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";
122
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";
123
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";
124
133
  import {
125
134
  cleanupWorktrees,
126
135
  createWorktrees,
127
136
  diffWorktrees,
128
- findWorktreeTaskCwdConflict,
129
137
  formatWorktreeDiffSummary,
130
- formatWorktreeTaskCwdConflict,
131
138
  type WorktreeSetup,
132
139
  } from "../shared/worktree.ts";
140
+ import { createWorktreeCleanupPlan, formatWorktreeCleanupPlan } from "../shared/worktree-cleanup-plan.ts";
133
141
  import {
134
142
  type AgentProgress,
135
143
  type AsyncJobState,
@@ -142,21 +150,33 @@ import {
142
150
  type ControlEvent,
143
151
  type Details,
144
152
  type ExtensionConfig,
153
+ type ForegroundResumeChild,
154
+ type ForegroundChildSessionControls,
155
+ type ForegroundSteerInput,
156
+ type ForegroundSteerOutcome,
145
157
  type ForegroundRunControl,
158
+ type HostStepNodeV1,
146
159
  type IntercomBridgeConfig,
147
160
  type IntercomEventBus,
148
161
  type JsonSchemaObject,
149
162
  type MaxOutputConfig,
150
163
  type NestedRouteInfo,
151
164
  type NestedRunSummary,
165
+ type OutputMode,
152
166
  type ResolvedControlConfig,
153
- type ResolvedTurnBudget,
154
167
  type ResolvedToolBudget,
155
168
  type RunFanoutBudgetDescriptor,
169
+ type SteeringRecoveryDescriptor,
156
170
  type SingleResult,
171
+ type SubagentChildStatusEvent,
157
172
  type ToolBudgetConfig,
158
- type TurnBudgetConfig,
173
+ type Usage,
159
174
  type UsageBudgetConfig,
175
+ type WorkflowResourceProvenanceV1,
176
+ type WorkflowGraphNode,
177
+ type WorkflowGraphSnapshot,
178
+ type WorkflowNodeStatus,
179
+ type WorkflowTerminalOutcome,
160
180
  type SubagentRunMode,
161
181
  type SubagentState,
162
182
  DIRS,
@@ -167,18 +187,21 @@ import {
167
187
  SUBAGENT_CONTROL_INTERCOM_EVENT,
168
188
  SUBAGENT_FOREGROUND_COMPLETE_EVENT,
169
189
  checkSubagentDepth,
170
- resolveTopLevelParallelConcurrency,
171
- resolveTopLevelParallelMaxTasks,
172
190
  resolveChildMaxSubagentDepth,
173
191
  resolveCurrentMaxSubagentDepth,
174
192
  resolveMaxSubagentSpawnsPerRun,
175
193
  wrapForkTask,
176
194
  type ScheduleOrigin,
177
195
  } from "../../shared/types.ts";
196
+ import { deriveChildSessionName } from "../../shared/child-session-name.ts";
178
197
 
179
- 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"]);
180
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"]);
181
200
 
201
+ function resolveSteerDeliveryMode(mode: SubagentParamsLike["mode"]): SteerDeliveryMode | undefined {
202
+ return mode === "steer" || mode === "follow_up" || mode === "auto" ? mode : undefined;
203
+ }
204
+
182
205
  function editDistance(left: string, right: string): number {
183
206
  const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
184
207
  for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
@@ -260,6 +283,7 @@ interface TaskParam {
260
283
  reads?: string[] | boolean;
261
284
  progress?: boolean;
262
285
  model?: string;
286
+ fast?: boolean;
263
287
  skill?: string | string[] | boolean;
264
288
  outputSchema?: JsonSchemaObject;
265
289
  acceptance?: AcceptanceInput;
@@ -273,7 +297,11 @@ export interface SubagentParamsLike {
273
297
  runId?: string;
274
298
  dir?: string;
275
299
  handoffPath?: string;
300
+ laneId?: string;
301
+ merge?: unknown;
302
+ supersession?: unknown;
276
303
  index?: number;
304
+ childId?: string;
277
305
  view?: "fleet" | "transcript";
278
306
  lines?: number;
279
307
  topic?: string;
@@ -283,32 +311,49 @@ export interface SubagentParamsLike {
283
311
  type?: string;
284
312
  agent?: string;
285
313
  task?: string;
314
+ capabilities?: boolean;
315
+ extensionBindings?: ExtensionBindings;
286
316
  /** Retained async child run id. Valid only on workflow runs.run items. */
287
317
  resume?: string;
288
318
  message?: string;
289
319
  steeringRecovery?: boolean;
290
- mode?: SteerDeliveryMode;
320
+ mode?: SteerDeliveryMode | "plan" | "apply";
321
+ repo?: string;
322
+ planId?: string;
291
323
  workflowScript?: string;
324
+ workflowScriptPath?: string;
325
+ globalConcurrencyLimit?: number;
326
+ maxSubagentSpawnsPerRun?: number;
327
+ preflight?: import("../../shared/types.ts").WorkflowPreflightV1;
292
328
  chatProgress?: "auto" | "off" | "live-card";
293
329
  isolation?: "none" | "worktree";
294
330
  step?: ChainStep;
295
331
  /** Internal workflow ownership metadata; not part of the public schema. */
296
332
  workflowParentRunId?: string;
297
333
  workflowKey?: string;
334
+ lane?: import("../../shared/types.ts").WorkflowLaneMetadata;
298
335
  /** Set by the scheduler so this run's completion can name the schedule that produced it. */
299
336
  scheduleOrigin?: ScheduleOrigin;
300
337
  workflowChildAsyncId?: string;
338
+ workflowAwaitAsync?: boolean;
339
+ /** Internal async-workflow bridge: keep the live VM await pending across supervisor detachment. */
340
+ workflowAwaitDetached?: boolean;
301
341
  workflowParentDeadlineAt?: number;
342
+ workflowOutputClaimPath?: string;
302
343
  suppressRoutineResultIntercom?: boolean;
303
344
  /** Internal inherited cumulative run-tree budget. */
304
345
  runFanoutBudget?: RunFanoutBudgetDescriptor;
305
346
  /** Internal workflow host admission proof. */
306
347
  runFanoutAdmitted?: boolean;
348
+ /** Internal inherited tool/agent ceiling for delegated child launches. */
349
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
307
350
  /** Internal durable-run compatibility fields. Public callers must use workflowScript. */
308
351
  chain?: ChainStep[];
309
352
  tasks?: TaskParam[];
310
353
  concurrency?: number;
311
354
  worktree?: boolean;
355
+ /** Git ref used as the managed worktree base. */
356
+ baseRef?: string;
312
357
  context?: "fresh" | "fork" | "profile";
313
358
  /** Per-run intercom bridge config. It replaces the global config for this launch only. */
314
359
  intercomBridge?: IntercomBridgeConfig;
@@ -318,9 +363,6 @@ export interface SubagentParamsLike {
318
363
  maxRuntimeMs?: number;
319
364
  /** Optional hard per-tool-call timeout (ms). Known-fast tools also have a default. */
320
365
  toolTimeoutMs?: number;
321
- turnBudget?: TurnBudgetConfig;
322
- /** Internal-only strict turn-boundary enforcement for versioned foreground delegation. */
323
- enforceHardTurnLimit?: boolean;
324
366
  toolBudget?: ToolBudgetConfig;
325
367
  usageBudget?: UsageBudgetConfig;
326
368
  clarify?: boolean;
@@ -332,7 +374,13 @@ export interface SubagentParamsLike {
332
374
  artifacts?: boolean;
333
375
  includeProgress?: boolean;
334
376
  model?: string;
377
+ /** Internal recovery provenance for a resolved model override. */
378
+ modelOrigin?: ModelOrigin;
379
+ fast?: boolean;
335
380
  thinking?: string | false;
381
+ /** Public named workflow resource. Resolved before entering the workflow sandbox. */
382
+ workflow?: string;
383
+ args?: Record<string, unknown>;
336
384
  scope?: string;
337
385
  target?: string;
338
386
  focus?: boolean;
@@ -349,6 +397,7 @@ export interface SubagentParamsLike {
349
397
  agentContract?: AgentContract;
350
398
  at?: string;
351
399
  every?: string;
400
+ sessionOnly?: boolean;
352
401
  on?: string | number;
353
402
  timezone?: string;
354
403
  overlap?: "skip";
@@ -379,28 +428,47 @@ interface ExecutorDeps {
379
428
  config: ExtensionConfig;
380
429
  asyncByDefault: boolean;
381
430
  waitToolEnabled?: boolean;
431
+ waitToolDefaultTimeoutMs?: number;
382
432
  handleScheduledRunAction?: (params: SubagentParamsLike, ctx: ExtensionContext) => Promise<AgentToolResult<Details>>;
383
433
  watchdog?: MainWatchdogRuntime;
384
434
  tempArtifactsDir: string;
385
435
  getSubagentSessionRoot: (parentSessionFile: string | null) => string;
386
436
  expandTilde: (p: string) => string;
387
- discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig };
437
+ discoverAgents: (cwd: string, scope: AgentScope, preferredModelProvider?: string) => { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig; maxThinking?: AgentConfig["maxThinking"]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] };
388
438
  allowMutatingManagementActions?: boolean;
389
439
  activateSupervisorTransport?: () => void;
390
440
  refreshResultDelivery?: () => void;
391
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;
392
444
  }
393
445
 
394
- type ForkSessionFileForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean) => string | undefined;
395
- type ForkThinkingOverrideForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean) => AgentConfig["thinking"] | undefined;
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);
452
+ }
453
+
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;
396
461
 
397
462
  interface ExecutionContextData {
398
463
  params: SubagentParamsLike;
399
464
  effectiveCwd: string;
465
+ requestedCwd?: string;
400
466
  ctx: ExtensionContext;
401
467
  signal: AbortSignal;
402
468
  onUpdate?: (r: AgentToolResult<Details>) => void;
403
469
  agents: AgentConfig[];
470
+ /** Exact filesystem discovery provenance retained through defensive execution backstops. */
471
+ unknownAgentDiagnosticContext: UnknownAgentDiagnosticContext;
404
472
  /** Discovered agent definitions before per-run bridge injection. */
405
473
  recoveryAgents: AgentConfig[];
406
474
  runId: string;
@@ -416,13 +484,14 @@ interface ExecutionContextData {
416
484
  effectiveAsync: boolean;
417
485
  asyncRunId: string;
418
486
  controlConfig: ResolvedControlConfig;
487
+ /** Structured delegation consumers do not need duration-only heartbeat snapshots. */
488
+ suppressUnchangedDelegationUpdates?: boolean;
419
489
  intercomBridge: IntercomBridgeState;
420
490
  nestedRoute?: NestedRouteInfo;
421
491
  timeoutMs?: number;
422
492
  deadlineAt?: number;
423
493
  /** Raw global config.toolTimeoutMs, for per-step resolution in async runners. */
424
494
  configToolTimeoutMs?: number;
425
- turnBudget?: ResolvedTurnBudget;
426
495
  toolBudget?: ResolvedToolBudget;
427
496
  usageBudget?: UsageBudgetConfig;
428
497
  allowZeroToolBudget?: boolean;
@@ -436,16 +505,30 @@ interface ExecutionContextData {
436
505
  runFanoutBudget: RunFanoutBudgetDescriptor;
437
506
  topLevelAsyncCapacityEligible: boolean;
438
507
  activeAsyncCapacity?: ActiveAsyncCapacityHandle;
508
+ workflowChildPermitLaunch?: WorkflowChildPermitContext;
439
509
  }
440
510
 
441
511
  function resolveRequestedCwd(runtimeCwd: string, requestedCwd: string | undefined): string {
442
512
  return requestedCwd ? path.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
443
513
  }
444
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
+
445
529
  function removeForegroundControlIfIdle(state: SubagentState, runId: string): boolean {
446
530
  const control = state.foregroundControls.get(runId);
447
531
  if (control && (!foregroundSchedulingSettled(control) || (control.activeChildren?.size ?? 0) > 0)) return false;
448
- if (control) removeWorkflowForegroundSteeringRoute(control);
449
532
  state.foregroundControls.delete(runId);
450
533
  if (state.lastForegroundControlId === runId) state.lastForegroundControlId = null;
451
534
  return true;
@@ -464,12 +547,13 @@ function getForegroundControl(state: SubagentState, runId: string | undefined) {
464
547
  return newest;
465
548
  }
466
549
 
467
- function promptAuditRedoParams(value: unknown, rewrittenTask: string): SubagentParamsLike {
550
+ export function promptAuditRedoParams(value: unknown, rewrittenTask: string): SubagentParamsLike {
468
551
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Prompt redo is missing a safe live launch contract.");
469
552
  const params = { ...(value as SubagentParamsLike), task: rewrittenTask, async: false };
470
553
  delete params.workflowParentRunId;
471
554
  delete params.workflowKey;
472
555
  delete params.workflowChildAsyncId;
556
+ delete params.workflowAwaitDetached;
473
557
  delete params.workflowParentDeadlineAt;
474
558
  delete params.suppressRoutineResultIntercom;
475
559
  if (params.worktree === true && Array.isArray(params.tasks)) delete params.cwd;
@@ -497,8 +581,8 @@ function formatForegroundActivity(control: SubagentState["foregroundControls"] e
497
581
 
498
582
  function nestedResolutionScopeForExecutor(deps: ExecutorDeps): NestedRunResolutionScope | undefined {
499
583
  if (deps.allowMutatingManagementActions !== false) return undefined;
500
- const route = resolveInheritedNestedRouteFromEnv();
501
- const address = route ? resolveNestedParentAddressFromEnv() : undefined;
584
+ const route = inheritedNestedRoute(deps);
585
+ const address = route ? inheritedNestedParentAddress(deps) : undefined;
502
586
  return {
503
587
  routes: route ? [route] : [],
504
588
  ...(address ? { descendantOf: { parentRunId: address.parentRunId, ...(address.parentStepIndex !== undefined ? { parentStepIndex: address.parentStepIndex } : {}) } } : {}),
@@ -530,6 +614,7 @@ function withSpawnBudgetStatus(
530
614
  const activeAsyncCapacity = sessionId
531
615
  ? getActiveAsyncCapacitySnapshot(sessionId, resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession), {
532
616
  liveWorkflowRunIds: new Set(state.workflowControllers?.keys() ?? []),
617
+ abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(config.capacity?.abandonedSlotReleaseAfterMs),
533
618
  })
534
619
  : { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession) ?? 0 };
535
620
  state.activeAsyncCapacity = activeAsyncCapacity;
@@ -632,11 +717,13 @@ function foregroundChildActivityFromProgress(progress: SingleResult["progress"]
632
717
  ...(progress?.currentPath ? { currentPath: progress.currentPath } : {}),
633
718
  ...(progress?.turnCount !== undefined ? { turnCount: progress.turnCount } : {}),
634
719
  ...(progress?.tokens !== undefined ? { tokens: progress.tokens } : {}),
720
+ ...(progress?.window !== undefined ? { window: progress.window } : {}),
721
+ ...(progress?.windowPeak !== undefined ? { windowPeak: progress.windowPeak } : {}),
635
722
  ...(progress?.toolCount !== undefined ? { toolCount: progress.toolCount } : {}),
636
723
  };
637
724
  }
638
725
 
639
- function rememberForegroundRun(state: SubagentState, input: { runId: string; mode: "single" | "parallel" | "chain"; cwd: string; sessionId: string | null; results: SingleResult[] }): 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 {
640
727
  state.foregroundRuns ??= new Map();
641
728
  const previous = state.foregroundRuns.get(input.runId);
642
729
  const updatedAt = Date.now();
@@ -647,9 +734,17 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
647
734
  ...(input.sessionId ? { sessionId: input.sessionId } : {}),
648
735
  updatedAt,
649
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
+ });
650
744
  const child = {
651
745
  agent: result.agent,
652
746
  index,
747
+ ...(result.sessionName ? { sessionName: result.sessionName } : {}),
653
748
  ...(result.context ? { context: result.context } : {}),
654
749
  status: resolveSubagentResultStatus(omitUndefinedProperties({
655
750
  exitCode: result.exitCode,
@@ -677,7 +772,9 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
677
772
  ...(result.transcriptError ? { transcriptError: result.transcriptError } : {}),
678
773
  ...(result.detachedReason ? { detachedReason: result.detachedReason } : {}),
679
774
  ...(result.acceptance ? { acceptance: result.acceptance } : {}),
775
+ ...(Object.keys(resumeContract).length ? { resumeContract } : {}),
680
776
  ...(result.launchContractDigest ? { launchContractDigest: result.launchContractDigest } : {}),
777
+ ...(input.extensionBindings ? { extensionBindings: input.extensionBindings } : {}),
681
778
  ...(result.launchResolvedExtensions ? { launchResolvedExtensions: result.launchResolvedExtensions } : {}),
682
779
  ...(result.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: result.runtimeAcknowledgedExtensions } : {}),
683
780
  ...(result.capabilityCeiling ? { capabilityCeiling: result.capabilityCeiling } : {}),
@@ -796,7 +893,7 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
796
893
  });
797
894
  }
798
895
 
799
- 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; 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 {
800
897
  const requested = (params.id ?? params.runId)?.trim();
801
898
  if (!requested || !state.foregroundRuns?.size || !state.currentSessionId) return undefined;
802
899
  const direct = state.foregroundRuns.get(requested);
@@ -806,7 +903,7 @@ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: Subage
806
903
  if (matches.length === 0) return undefined;
807
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.`);
808
905
  const run = matches[0]!;
809
- 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.`);
810
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.`);
811
908
  const index = params.index ?? 0;
812
909
  if (!Number.isInteger(index)) throw new Error(`Foreground run '${run.runId}' index must be an integer.`);
@@ -827,6 +924,8 @@ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: Subage
827
924
  ...(child.model ? { model: child.model } : {}),
828
925
  ...(child.thinking ? { thinking: child.thinking } : {}),
829
926
  ...(child.launchContractDigest ? { launchContractDigest: child.launchContractDigest } : {}),
927
+ ...(child.resumeContract ? { resumeContract: child.resumeContract } : {}),
928
+ ...(child.extensionBindings ? { extensionBindings: normalizeExtensionBindings(child.extensionBindings)!.value } : {}),
830
929
  ...(child.capabilityCeiling ? { capabilityCeiling: child.capabilityCeiling } : {}),
831
930
  };
832
931
  }
@@ -846,6 +945,7 @@ type NestedResumeSourceTarget = {
846
945
  thinking?: AgentConfig["thinking"];
847
946
  launchContractDigest?: string;
848
947
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
948
+ recoveryDescriptor?: SteeringRecoveryDescriptor;
849
949
  };
850
950
  type ResumeSourceTarget = AsyncResumeSourceTarget | ForegroundResumeSourceTarget | NestedResumeSourceTarget;
851
951
 
@@ -853,6 +953,10 @@ function isAsyncRunNotFound(error: unknown): boolean {
853
953
  return error instanceof Error && error.message.startsWith("Async run not found.");
854
954
  }
855
955
 
956
+ function isMissingExactAsyncStatusFile(error: unknown, requested: string): boolean {
957
+ return error instanceof Error && error.message === `Status file not found for async run '${requested}'.`;
958
+ }
959
+
856
960
  function isResumeAmbiguity(error: unknown): boolean {
857
961
  return error instanceof Error && /Ambiguous .*run id prefix/.test(error.message);
858
962
  }
@@ -906,7 +1010,7 @@ function resolveResumeTarget(params: SubagentParamsLike, state: SubagentState, o
906
1010
  throw new Error(`Resume id '${requested}' is ambiguous between foreground run '${foregroundTarget.runId}' and async run '${asyncTarget.runId}'. Provide a full run id.`);
907
1011
  }
908
1012
  if (foregroundTarget) {
909
- if (isExactResumeError(asyncError, "async", requested)) throw asyncError;
1013
+ if (isExactResumeError(asyncError, "async", requested) && !isMissingExactAsyncStatusFile(asyncError, requested)) throw asyncError;
910
1014
  if (isResumeAmbiguity(asyncError) && !resumeTargetExact(foregroundTarget, requested)) throw asyncError;
911
1015
  return foregroundTarget;
912
1016
  }
@@ -1195,7 +1299,7 @@ function appendStepToAsyncChain(input: {
1195
1299
  }
1196
1300
 
1197
1301
  const scope: AgentScope = resolveExecutionAgentScope(input.params.agentScope);
1198
- const discoveredForAppend = input.deps.discoverAgents(input.requestCwd, scope);
1302
+ const discoveredForAppend = input.deps.discoverAgents(input.requestCwd, scope, input.parentModel?.provider);
1199
1303
  const agents = discoveredForAppend.agents;
1200
1304
  const contextPolicy = resolveExplicitContextPolicy(input.params);
1201
1305
  const chainSkillInput = normalizeSkillInput(input.params.skill);
@@ -1211,6 +1315,7 @@ function appendStepToAsyncChain(input: {
1211
1315
  modelScope: discoveredForAppend.modelScope,
1212
1316
  interactive: input.ctx.hasUI,
1213
1317
  permissions: input.deps.config.permissions,
1318
+ childRuntime: input.deps.childRuntime,
1214
1319
  });
1215
1320
  const built = buildAsyncRunnerSteps(resolved.id, compactOptional<Parameters<typeof buildAsyncRunnerSteps>[1]>({
1216
1321
  chain: wrapChainTasksForFork(chain, contextPolicy),
@@ -1219,12 +1324,17 @@ function appendStepToAsyncChain(input: {
1219
1324
  agents,
1220
1325
  ctx: asyncCtx,
1221
1326
  availableModels: input.ctx.modelRegistry.getAvailable().map(toModelInfo),
1327
+ unknownAgentDiagnosticContext: diagnosticContextFromDiscovery(discoveredForAppend, input.requestCwd, scope),
1222
1328
  cwd: status.cwd ?? input.requestCwd,
1223
1329
  chainSkills,
1224
1330
  dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,
1225
- maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
1331
+ maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime),
1226
1332
  waitToolEnabled: input.deps.waitToolEnabled,
1333
+ waitToolDefaultTimeoutMs: input.deps.waitToolDefaultTimeoutMs,
1227
1334
  contextForAgent: contextPolicy.contextForAgent,
1335
+ worktreeBaseDir: input.deps.config.worktreeBaseDir,
1336
+ worktreeProvider: input.deps.config.worktreeProvider,
1337
+ worktreeBranchPrefix: input.deps.config.worktreeBranchPrefix,
1228
1338
  asyncDir: resolved.location.asyncDir,
1229
1339
  validateOutputBindings: false,
1230
1340
  capabilityCeiling: intersectSubagentCapabilityCeilings(status.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(asyncCtx.currentSessionId)),
@@ -1327,6 +1437,14 @@ function validateNestedSessionFile(run: NestedRunSummary, trustedSessionRoots: s
1327
1437
  return realSessionFile;
1328
1438
  }
1329
1439
 
1440
+ export function readNestedRecoveryDescriptor(asyncDir: string | undefined, runId: string, agent: string): SteeringRecoveryDescriptor | undefined {
1441
+ const recoveryDescriptor = readAsyncRecoveryDescriptor(asyncDir);
1442
+ if (!recoveryDescriptor) return undefined;
1443
+ if (recoveryDescriptor.sourceRunId !== runId) throw new Error(`Nested run '${runId}' has a recovery descriptor for a different source run.`);
1444
+ if (recoveryDescriptor.agent !== agent) throw new Error(`Nested run '${runId}' has a recovery descriptor for a different agent.`);
1445
+ return recoveryDescriptor;
1446
+ }
1447
+
1330
1448
  function resolveNestedResumeTarget(match: ResolvedSubagentRunId & { kind: "nested" }, trustedSessionRoots: string[]): NestedResumeSourceTarget {
1331
1449
  const run = match.match.run;
1332
1450
  if (run.state === "running" || run.state === "queued") throw new Error(`Nested run '${run.id}' is live; route the follow-up to the owner process instead.`);
@@ -1335,6 +1453,7 @@ function resolveNestedResumeTarget(match: ResolvedSubagentRunId & { kind: "neste
1335
1453
  if (!agent) throw new Error(`Could not determine child agent for nested run '${run.id}'.`);
1336
1454
  const state = run.state === "complete" || run.state === "failed" || run.state === "paused" ? run.state : "failed";
1337
1455
  const asyncDir = resolveNestedAsyncDir(match.match.rootRunId, run);
1456
+ const recoveryDescriptor = readNestedRecoveryDescriptor(asyncDir, run.id, agent);
1338
1457
  return compactOptional<NestedResumeSourceTarget>({
1339
1458
  kind: "revive",
1340
1459
  source: "nested",
@@ -1345,6 +1464,7 @@ function resolveNestedResumeTarget(match: ResolvedSubagentRunId & { kind: "neste
1345
1464
  cwd: asyncDir ? path.dirname(asyncDir) : undefined,
1346
1465
  sessionFile: validateNestedSessionFile(run, trustedSessionRoots),
1347
1466
  ...(run.capabilityCeiling ? { capabilityCeiling: run.capabilityCeiling } : {}),
1467
+ ...(recoveryDescriptor ? { recoveryDescriptor } : {}),
1348
1468
  });
1349
1469
  }
1350
1470
 
@@ -1456,15 +1576,159 @@ async function steerNestedRun(input: { target: ResolvedSubagentRunId & { kind: "
1456
1576
  return { content: [{ type: "text", text: `Nested run ${run.id} is not a live async Pi child session with a steering inbox. action='steer' cannot target foreground nested runs.` }], isError: true, details: { mode: "management", results: [] } };
1457
1577
  }
1458
1578
 
1579
+ function externalJobOptionsEqual(left: Record<string, unknown>, right: Record<string, unknown>): boolean {
1580
+ return externalJobStableJson(left) === externalJobStableJson(right);
1581
+ }
1582
+
1583
+ function providerFollowUpSupport(providerName: string): { ok: true } | { ok: false; message: string } {
1584
+ try {
1585
+ const provider = getExternalJobProvider(providerName);
1586
+ if (!provider) return { ok: false, message: `External-job provider '${providerName}' is not registered. Load the provider package, then retry action='resume'.` };
1587
+ if (typeof provider.followUp !== "function") return { ok: false, message: `External-job provider '${providerName}' does not support follow-up. Update or reload the provider package, then retry action='resume'.` };
1588
+ return { ok: true };
1589
+ } catch (error) {
1590
+ return { ok: false, message: `External-job provider registry unavailable: ${error instanceof Error ? error.message : String(error)}` };
1591
+ }
1592
+ }
1593
+
1594
+ function externalJobFollowUpStarted(input: { sourceRunId: string; runId: string; asyncDir: string; duplicate?: boolean; interactive: boolean }): AgentToolResult<Details> {
1595
+ const lines = [
1596
+ input.duplicate ? `External-job follow-up already exists for ${input.sourceRunId}.` : `Started external-job follow-up for ${input.sourceRunId}.`,
1597
+ `Follow-up run: ${input.runId}`,
1598
+ `Async dir: ${input.asyncDir}`,
1599
+ `Status if needed: subagent({ action: "status", id: "${input.runId}" })`,
1600
+ ];
1601
+ return { content: [{ type: "text", text: formatAsyncStartedMessage(lines.join("\n"), input.interactive) }], details: { mode: "single", results: [], asyncId: input.runId, asyncDir: input.asyncDir } };
1602
+ }
1603
+
1459
1604
  function externalRunnerControlError(asyncDir: string, action: "steer" | "resume"): AgentToolResult<Details> | undefined {
1460
1605
  const status = readStatus(asyncDir);
1461
1606
  if (!status?.steps?.length || !status.steps.every((step) => step.runner?.type === "external-cli" || step.runner?.type === "external-job")) return undefined;
1462
- const message = action === "steer"
1463
- ? "External runners do not accept live steer messages."
1464
- : "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.";
1465
1615
  return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
1466
1616
  }
1467
1617
 
1618
+ async function resumeExternalJobFollowUp(input: {
1619
+ target: AsyncResumeSourceTarget;
1620
+ followUp: string;
1621
+ baseAgentConfig: AgentConfig;
1622
+ effectiveCwd: string;
1623
+ requestCwd: string;
1624
+ ctx: ExtensionContext;
1625
+ deps: ExecutorDeps;
1626
+ parentModel?: ParentModel;
1627
+ modelScope?: ModelScopeConfig;
1628
+ intercomBridge: IntercomBridgeState;
1629
+ parentSessionFile: string | null;
1630
+ absoluteDeadlineAt?: number;
1631
+ }): Promise<AgentToolResult<Details>> {
1632
+ if (input.target.kind === "live" || input.target.state === "running" || input.target.state === "queued") {
1633
+ return { content: [{ type: "text", text: `External-job run '${input.target.runId}' is still running. Wait for completion, then use subagent({ action: "resume", id: "${input.target.runId}", message: "..." }).` }], isError: true, details: { mode: "management", results: [] } };
1634
+ }
1635
+ const runner = input.target.runner;
1636
+ const externalJob = input.target.externalJob;
1637
+ if (runner?.type !== "external-job") return { content: [{ type: "text", text: "Internal error: external-job follow-up was requested for a non-external-job runner." }], isError: true, details: { mode: "management", results: [] } };
1638
+ if (!externalJob) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has no persisted provider metadata. Cannot follow up without the parent provider job id.` }], isError: true, details: { mode: "management", results: [] } };
1639
+ if (externalJob.provider !== runner.provider) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has mismatched provider metadata. Refusing to follow up.` }], isError: true, details: { mode: "management", results: [] } };
1640
+ if (!externalJobOptionsEqual(externalJob.options, runner.options)) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has mismatched provider options. Refusing to follow up.` }], isError: true, details: { mode: "management", results: [] } };
1641
+ if (!externalJob.providerJobId) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has no parent provider job id. Cannot follow up without reopening or redispatching, so this fails closed.` }], isError: true, details: { mode: "management", results: [] } };
1642
+ if (externalJob.state !== "completed") return { content: [{ type: "text", text: `External-job run '${input.target.runId}' provider state is ${externalJob.state}. Wait for completion, then use action='resume'.` }], isError: true, details: { mode: "management", results: [] } };
1643
+ const support = providerFollowUpSupport(runner.provider);
1644
+ if (!support.ok) return { content: [{ type: "text", text: support.message }], isError: true, details: { mode: "management", results: [] } };
1645
+
1646
+ const promptDigest = externalJobPromptDigest(input.followUp);
1647
+ const requestDigest = externalJobFollowUpRequestDigest({ provider: runner.provider, parentProviderJobId: externalJob.providerJobId, promptDigest, options: runner.options });
1648
+ const requestId = externalJobFollowUpRequestId(requestDigest);
1649
+ const runId = externalJobFollowUpRunId(requestDigest);
1650
+ const asyncDir = path.join(DIRS.async, runId);
1651
+ const currentSessionId = input.deps.state.currentSessionId;
1652
+ if (!currentSessionId) return { content: [{ type: "text", text: "External-job follow-up requires an active parent session." }], isError: true, details: { mode: "management", results: [] } };
1653
+ if (fs.existsSync(asyncDir) || fs.existsSync(resultFilePath(DIRS.results, runId))) {
1654
+ return externalJobFollowUpStarted({ sourceRunId: input.target.runId, runId, asyncDir, duplicate: true, interactive: input.ctx.hasUI });
1655
+ }
1656
+
1657
+ const depthState = checkSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime);
1658
+ if (depthState.blocked) {
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: [] } };
1660
+ }
1661
+ const topLevelResume = depthState.depth === 0 && !inheritedNestedRoute(input.deps) && !input.deps.state.workflowControllers?.has(input.target.runId);
1662
+ let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1663
+ try {
1664
+ activeAsyncCapacity = topLevelResume ? acquireActiveAsyncCapacity({
1665
+ sessionId: currentSessionId,
1666
+ limit: resolveMaxActiveAsyncRunsPerSession(input.deps.config.maxActiveAsyncRunsPerSession),
1667
+ runId,
1668
+ kind: "runner",
1669
+ asyncDir,
1670
+ }, { liveWorkflowRunIds: new Set(input.deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(input.deps.config.capacity?.abandonedSlotReleaseAfterMs) }) : undefined;
1671
+ } catch (error) {
1672
+ if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "single", results: [], activeAsyncCapacity: error.snapshot } };
1673
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "single", results: [] } };
1674
+ }
1675
+
1676
+ const artifactConfig: ArtifactConfig = omitUndefinedProperties({ ...DEFAULT_ARTIFACT_CONFIG, enabled: true, dir: input.deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir });
1677
+ const artifactsDir = getArtifactsDir(input.parentSessionFile, input.effectiveCwd, artifactConfig.dir);
1678
+ const parentModel = input.parentModel;
1679
+ const agentConfig: AgentConfig = {
1680
+ ...input.baseAgentConfig,
1681
+ runner: { type: "external-job", provider: runner.provider, options: runner.options },
1682
+ };
1683
+ const result = executeAsyncSingle(runId, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
1684
+ agent: input.target.agent,
1685
+ task: input.followUp,
1686
+ goal: input.followUp,
1687
+ agentConfig,
1688
+ recoveryAgentConfig: agentConfig,
1689
+ ctx: compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
1690
+ pi: input.deps.pi,
1691
+ cwd: input.requestCwd,
1692
+ currentSessionId,
1693
+ parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1694
+ currentModelProvider: parentModel?.provider,
1695
+ currentModel: parentModel,
1696
+ modelScope: input.modelScope,
1697
+ interactive: input.ctx.hasUI,
1698
+ permissions: input.deps.config.permissions,
1699
+ childRuntime: input.deps.childRuntime,
1700
+ }),
1701
+ cwd: input.effectiveCwd,
1702
+ artifactsDir,
1703
+ artifactConfig,
1704
+ shareEnabled: false,
1705
+ ...(input.parentSessionFile ? { sessionRoot: input.deps.getSubagentSessionRoot(input.parentSessionFile) } : {}),
1706
+ maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime),
1707
+ waitToolEnabled: input.deps.waitToolEnabled,
1708
+ waitToolDefaultTimeoutMs: input.deps.waitToolDefaultTimeoutMs,
1709
+ worktreeSetupHook: input.deps.config.worktreeSetupHook,
1710
+ worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
1711
+ worktreeBaseDir: input.deps.config.worktreeBaseDir,
1712
+ worktreeProvider: input.deps.config.worktreeProvider,
1713
+ worktreeBranchPrefix: input.deps.config.worktreeBranchPrefix,
1714
+ controlConfig: resolveControlConfig(input.deps.config.control, undefined),
1715
+ controlIntercomTarget: input.intercomBridge.active ? input.intercomBridge.orchestratorTarget : undefined,
1716
+ childIntercomTarget: input.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : undefined,
1717
+ availableModels: input.ctx.modelRegistry.getAvailable().map(toModelInfo),
1718
+ outputBaseDir: resolveSingleRunOutputBaseDir(input.deps, artifactsDir, runId),
1719
+ ...(input.absoluteDeadlineAt !== undefined ? { absoluteDeadlineAt: input.absoluteDeadlineAt } : {}),
1720
+ capabilityCeiling: resolveCurrentSubagentCapabilityCeiling(currentSessionId),
1721
+ runFanoutBudget: createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(input.deps.config.maxSubagentSpawnsPerRun)),
1722
+ activeAsyncCapacity,
1723
+ externalJobFollowUp: { sourceRunId: input.target.runId, sourceStepIndex: input.target.index, parentProviderJobId: externalJob.providerJobId, requestId, requestDigest },
1724
+ }));
1725
+ if (result.isError) {
1726
+ activeAsyncCapacity?.rollback();
1727
+ return result;
1728
+ }
1729
+ return externalJobFollowUpStarted({ sourceRunId: input.target.runId, runId: result.details.asyncId ?? runId, asyncDir: result.details.asyncDir ?? asyncDir, interactive: input.ctx.hasUI });
1730
+ }
1731
+
1468
1732
  async function resumeAsyncRun(input: {
1469
1733
  params: SubagentParamsLike;
1470
1734
  requestCwd: string;
@@ -1529,11 +1793,7 @@ async function resumeAsyncRun(input: {
1529
1793
  ];
1530
1794
  target = resolveNestedResumeTarget(resolved, trustedSessionRoots);
1531
1795
  } else {
1532
- if (resolved?.kind === "async" && resolved.location.asyncDir) {
1533
- const unsupported = externalRunnerControlError(resolved.location.asyncDir, "resume");
1534
- if (unsupported) return unsupported;
1535
- }
1536
- target = resolveResumeTarget(input.params, input.deps.state, { asyncRequireSessionFile: !attachChain });
1796
+ target = resolveResumeTarget(input.params, input.deps.state, { asyncRequireSessionFile: false });
1537
1797
  }
1538
1798
  } catch (error) {
1539
1799
  const message = error instanceof Error ? error.message : String(error);
@@ -1554,7 +1814,7 @@ async function resumeAsyncRun(input: {
1554
1814
  };
1555
1815
  }
1556
1816
 
1557
- const { blocked, depth, maxDepth } = checkSubagentDepth(input.deps.config.maxSubagentDepth);
1817
+ const { blocked, depth, maxDepth } = checkSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime);
1558
1818
  if (blocked) {
1559
1819
  return {
1560
1820
  content: [{ type: "text", text: `Nested subagent resume blocked (depth=${depth}, max=${maxDepth}). Complete the follow-up directly instead.` }],
@@ -1566,8 +1826,9 @@ async function resumeAsyncRun(input: {
1566
1826
  input.deps.state.currentSessionId = resolveCurrentSessionId(input.ctx.sessionManager);
1567
1827
  const effectiveCwd = target.cwd ?? input.requestCwd;
1568
1828
  const scope: AgentScope = resolveExecutionAgentScope(input.params.agentScope);
1569
- const discovered = input.deps.discoverAgents(effectiveCwd, scope);
1829
+ const discovered = input.deps.discoverAgents(effectiveCwd, scope, input.parentModel?.provider);
1570
1830
  const discoveredAgents = discovered.agents;
1831
+ const unknownAgentDiagnosticContext = diagnosticContextFromDiscovery(discovered, effectiveCwd, scope);
1571
1832
  const modelScope = discovered.modelScope;
1572
1833
  const sessionName = resolveIntercomSessionTarget(input.deps.pi.getSessionName(), input.ctx.sessionManager.getSessionId());
1573
1834
  const recoveryDescriptor = "recoveryDescriptor" in target ? target.recoveryDescriptor : undefined;
@@ -1588,17 +1849,43 @@ async function resumeAsyncRun(input: {
1588
1849
  systemPrompt: "",
1589
1850
  systemPromptMode: recoveryDescriptor.systemPromptMode,
1590
1851
  inheritProjectContext: recoveryDescriptor.inheritProjectContext,
1852
+ inheritGlobalContext: recoveryDescriptor.inheritGlobalContext,
1591
1853
  inheritSkills: recoveryDescriptor.inheritSkills,
1592
1854
  source: "project",
1593
1855
  filePath: recoveryDescriptor.agentFilePath ?? path.join(getProjectSubagentsDir(recoveryDescriptor.cwd), "recovery-agent"),
1856
+ ...(discovered.maxThinking ? { maxThinking: discovered.maxThinking } : {}),
1594
1857
  } : undefined);
1595
1858
  if (!baseAgentConfig) {
1596
1859
  return {
1597
- content: [{ type: "text", text: `Unknown agent for resume: ${target.agent}` }],
1860
+ content: [{ type: "text", text: formatUnknownAgentError(target.agent, unknownAgentDiagnosticContext, "Unknown agent for resume") }],
1598
1861
  isError: true,
1599
1862
  details: { mode: "management", results: [] },
1600
1863
  };
1601
1864
  }
1865
+ if (target.source === "async" && target.runner?.type === "external-cli") {
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: [] } };
1871
+ }
1872
+ if (target.source === "async" && target.runner?.type === "external-job") {
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: [] } };
1874
+ return resumeExternalJobFollowUp({
1875
+ target,
1876
+ followUp,
1877
+ baseAgentConfig,
1878
+ effectiveCwd,
1879
+ requestCwd: input.requestCwd,
1880
+ ctx: input.ctx,
1881
+ deps: input.deps,
1882
+ parentModel: input.parentModel,
1883
+ modelScope,
1884
+ intercomBridge,
1885
+ parentSessionFile,
1886
+ absoluteDeadlineAt: input.absoluteDeadlineAt,
1887
+ });
1888
+ }
1602
1889
 
1603
1890
  if (attachChain) {
1604
1891
  if (target.source !== "async") {
@@ -1616,7 +1903,7 @@ async function resumeAsyncRun(input: {
1616
1903
  };
1617
1904
  }
1618
1905
  const runId = randomUUID();
1619
- const topLevelResume = depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.params.workflowParentRunId;
1906
+ const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
1620
1907
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1621
1908
  try {
1622
1909
  activeAsyncCapacity = topLevelResume ? acquireActiveAsyncCapacity({
@@ -1625,7 +1912,7 @@ async function resumeAsyncRun(input: {
1625
1912
  runId,
1626
1913
  kind: "runner",
1627
1914
  asyncDir: path.join(DIRS.async, runId),
1628
- }, { 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;
1629
1916
  } catch (error) {
1630
1917
  if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "chain", results: [], activeAsyncCapacity: error.snapshot } };
1631
1918
  throw error;
@@ -1651,6 +1938,7 @@ async function resumeAsyncRun(input: {
1651
1938
  label: `Attached ${target.runId}`,
1652
1939
  },
1653
1940
  agents,
1941
+ unknownAgentDiagnosticContext,
1654
1942
  ctx: compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
1655
1943
  pi: input.deps.pi,
1656
1944
  cwd: input.requestCwd,
@@ -1661,6 +1949,7 @@ async function resumeAsyncRun(input: {
1661
1949
  modelScope,
1662
1950
  interactive: input.ctx.hasUI,
1663
1951
  permissions: input.deps.config.permissions,
1952
+ childRuntime: input.deps.childRuntime,
1664
1953
  }),
1665
1954
  availableModels,
1666
1955
  cwd: effectiveCwd,
@@ -1671,18 +1960,24 @@ async function resumeAsyncRun(input: {
1671
1960
  sessionRoot: input.deps.getSubagentSessionRoot(parentSessionFile),
1672
1961
  chainSkills: normalized === false ? [] : (normalized ?? []),
1673
1962
  agentContract: input.params.agentContract,
1963
+ fast: input.params.fast,
1674
1964
  dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,
1675
- maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
1965
+ maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime),
1676
1966
  waitToolEnabled: input.deps.waitToolEnabled,
1967
+ waitToolDefaultTimeoutMs: input.deps.waitToolDefaultTimeoutMs,
1677
1968
  worktreeSetupHook: input.deps.config.worktreeSetupHook,
1678
1969
  worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
1679
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,
1680
1974
  controlConfig: resolveControlConfig(input.deps.config.control, input.params.control),
1681
1975
  controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : undefined,
1682
1976
  childIntercomTarget: intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : undefined,
1683
1977
  globalConcurrencyLimit: input.deps.config.globalConcurrencyLimit,
1684
1978
  runFanoutBudget: createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(input.deps.config.maxSubagentSpawnsPerRun)),
1685
1979
  capabilityCeiling: intersectSubagentCapabilityCeilings("capabilityCeiling" in target ? target.capabilityCeiling : undefined, resolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId)),
1980
+ thinkingCeiling: target.thinkingCeiling,
1686
1981
  activeAsyncCapacity,
1687
1982
  }));
1688
1983
  if (result.isError) {
@@ -1705,13 +2000,16 @@ async function resumeAsyncRun(input: {
1705
2000
  const effectiveFollowUp = [...queuedBriefs.map(({ request }) => request.message), followUp].filter(Boolean).join("\n\n");
1706
2001
  const revivalSessionFile = target.sessionFile;
1707
2002
  if (!revivalSessionFile) {
1708
- return { content: [{ type: "text", text: `Async child '${target.runId}' has no persisted session file to resume.` }], isError: true, details: { mode: "management", results: [] } };
2003
+ return { content: [{ type: "text", text: `Async run '${target.runId}' child ${target.index} does not have a persisted session file to resume from.` }], isError: true, details: { mode: "management", results: [] } };
1709
2004
  }
1710
2005
  if (target.source === "async" && asyncReviveRequiresRecoveryDescriptor(target)) {
1711
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: [] } };
1712
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
+ }
1713
2011
  const runId = randomUUID();
1714
- const topLevelResume = depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.params.workflowParentRunId;
2012
+ const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
1715
2013
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1716
2014
  try {
1717
2015
  activeAsyncCapacity = !topLevelResume ? undefined : target.source === "async"
@@ -1721,20 +2019,23 @@ async function resumeAsyncRun(input: {
1721
2019
  sourceRunId: target.runId,
1722
2020
  runId,
1723
2021
  asyncDir: path.join(DIRS.async, runId),
1724
- })
2022
+ }, { abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(input.deps.config.capacity?.abandonedSlotReleaseAfterMs) })
1725
2023
  : acquireActiveAsyncCapacity({
1726
2024
  sessionId: input.deps.state.currentSessionId!,
1727
2025
  limit: resolveMaxActiveAsyncRunsPerSession(input.deps.config.maxActiveAsyncRunsPerSession),
1728
2026
  runId,
1729
2027
  kind: "runner",
1730
2028
  asyncDir: path.join(DIRS.async, runId),
1731
- });
2029
+ }, { abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(input.deps.config.capacity?.abandonedSlotReleaseAfterMs) });
1732
2030
  } catch (error) {
1733
2031
  if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "single", results: [], activeAsyncCapacity: error.snapshot } };
1734
2032
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "single", results: [] } };
1735
2033
  }
1736
2034
  const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
1737
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;
1738
2039
  const artifactConfig: ArtifactConfig = recoveryDescriptor?.artifactConfig ?? omitUndefinedProperties({ ...DEFAULT_ARTIFACT_CONFIG, enabled: input.params.artifacts !== false, dir: input.deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir });
1739
2040
  const artifactsDir = recoveryDescriptor?.artifactsDir ?? getArtifactsDir(parentSessionFile, effectiveCwd, artifactConfig.dir);
1740
2041
  const availableModels = input.ctx.modelRegistry.getAvailable().map(toModelInfo);
@@ -1756,6 +2057,7 @@ async function resumeAsyncRun(input: {
1756
2057
  modelScope,
1757
2058
  interactive: input.ctx.hasUI,
1758
2059
  permissions: input.deps.config.permissions,
2060
+ childRuntime: input.deps.childRuntime,
1759
2061
  }),
1760
2062
  cwd: effectiveCwd,
1761
2063
  maxOutput: input.params.maxOutput ?? recoveryDescriptor?.maxOutput,
@@ -1773,29 +2075,39 @@ async function resumeAsyncRun(input: {
1773
2075
  },
1774
2076
  context: recoveryContext,
1775
2077
  modelOverride: recoveryDescriptor?.model ?? target.model,
2078
+ fast: recoveryDescriptor?.fast,
1776
2079
  modelOverrideFromParent: recoveryDescriptor?.modelOverrideFromParent,
2080
+ modelOrigin: recoveryDescriptor?.modelOrigin ?? (recoveryDescriptor?.modelOverrideFromParent ? "inherited" : undefined),
1777
2081
  thinkingOverride: recoveryDescriptor?.thinking ?? target.thinking,
2082
+ thinkingCeiling: recoveryDescriptor?.thinkingCeiling ?? ("thinkingCeiling" in target ? target.thinkingCeiling : undefined),
2083
+ extensionBindings: recoveryDescriptor?.extensionBindings ?? ("extensionBindings" in target ? target.extensionBindings : undefined),
1778
2084
  outputBaseDir: resolveSingleRunOutputBaseDir(input.deps, artifactsDir, runId),
1779
- maxSubagentDepth: recoveryDescriptor?.maxSubagentDepth ?? resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
2085
+ maxSubagentDepth: recoveryDescriptor?.maxSubagentDepth ?? resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime),
1780
2086
  waitToolEnabled: input.deps.waitToolEnabled,
2087
+ waitToolDefaultTimeoutMs: input.deps.waitToolDefaultTimeoutMs,
1781
2088
  worktreeSetupHook: input.deps.config.worktreeSetupHook,
1782
2089
  worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
1783
2090
  worktreeBaseDir: input.deps.config.worktreeBaseDir,
1784
- worktree: input.params.worktree === true,
1785
- 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 }),
1786
2099
  intercomBridge: input.params.intercomBridge ?? recoveryDescriptor?.intercomBridge,
1787
2100
  controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : undefined,
1788
2101
  childIntercomTarget: intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : undefined,
1789
2102
  availableModels,
1790
- output: typeof input.params.output === "string" ? input.params.output : recoveryDescriptor?.outputPath,
1791
- outputMode: input.params.outputMode ?? recoveryDescriptor?.outputMode,
1792
- ...(recoveryDescriptor?.agentContract ? { agentContract: recoveryDescriptor.agentContract } : {}),
1793
- ...(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 } : {}),
1794
2107
  ...(recoveryDescriptor?.skills ? { skills: [...recoveryDescriptor.skills] } : {}),
1795
- ...(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 } : {}),
1796
2109
  ...(input.params.timeoutMs !== undefined ? { timeoutMs: input.params.timeoutMs } : {}),
1797
2110
  ...(input.absoluteDeadlineAt !== undefined ? { absoluteDeadlineAt: input.absoluteDeadlineAt } : {}),
1798
- ...(input.params.turnBudget !== undefined ? { turnBudget: input.params.turnBudget } : {}),
1799
2111
  ...(input.params.toolBudget !== undefined ? { toolBudget: input.params.toolBudget } : {}),
1800
2112
  capabilityCeiling: intersectSubagentCapabilityCeilings("capabilityCeiling" in target ? target.capabilityCeiling : undefined, recoveryDescriptor?.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId)),
1801
2113
  runFanoutBudget: input.params.runFanoutBudget ?? recoveryDescriptor?.runFanoutBudget ?? createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(input.deps.config.maxSubagentSpawnsPerRun)),
@@ -1843,20 +2155,14 @@ async function resumeAsyncRun(input: {
1843
2155
  input.signal?.removeEventListener("abort", stopOnAbort);
1844
2156
  }
1845
2157
  fs.rmSync(resultPath, { force: true });
1846
- const totalCost = completed.totalCost;
2158
+ const usage = importedAsyncRootUsage(completed);
1847
2159
  const childResult: SingleResult = {
1848
2160
  index: 0,
1849
2161
  agent: completed.agent,
2162
+ ...(completed.sessionName ? { sessionName: completed.sessionName } : {}),
1850
2163
  task: effectiveFollowUp,
1851
2164
  exitCode: completed.exitCode,
1852
- usage: {
1853
- input: totalCost?.inputTokens ?? 0,
1854
- output: totalCost?.outputTokens ?? 0,
1855
- cacheRead: 0,
1856
- cacheWrite: 0,
1857
- cost: totalCost?.costUsd ?? 0,
1858
- turns: 0,
1859
- },
2165
+ usage,
1860
2166
  finalOutput: completed.output,
1861
2167
  outputState: completed.output.trim() ? "present" : "absent",
1862
2168
  ...(completed.error ? { error: completed.error } : {}),
@@ -1866,13 +2172,18 @@ async function resumeAsyncRun(input: {
1866
2172
  ...(completed.model ? { model: completed.model } : {}),
1867
2173
  ...(completed.attemptedModels ? { attemptedModels: completed.attemptedModels } : {}),
1868
2174
  ...(completed.modelAttempts ? { modelAttempts: completed.modelAttempts } : {}),
2175
+ ...(completed.contextOverflow ? { contextOverflow: true } : {}),
1869
2176
  ...(completed.structuredOutput !== undefined ? { structuredOutput: completed.structuredOutput } : {}),
1870
2177
  ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
1871
2178
  ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
1872
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 } : {}),
1873
2184
  };
1874
2185
  return {
1875
- 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.` }],
1876
2187
  ...(completed.success ? {} : { isError: true }),
1877
2188
  details: {
1878
2189
  ...result.details,
@@ -1988,6 +2299,7 @@ async function emitForegroundResultIntercom(input: {
1988
2299
  if (!input.intercomBridge.active || !input.intercomBridge.resultDelivery || !input.intercomBridge.orchestratorTarget) return null;
1989
2300
  const children = input.results.flatMap((result, index) => result.detached ? [] : [omitUndefinedProperties({
1990
2301
  agent: result.agent,
2302
+ ...(result.sessionName ? { sessionName: result.sessionName } : {}),
1991
2303
  status: foregroundResultIntercomStatus(result),
1992
2304
  outputState: result.outputState ?? "unknown",
1993
2305
  summary: resultSummaryForIntercom(result),
@@ -2037,25 +2349,43 @@ async function maybeBuildForegroundIntercomReceipt(input: {
2037
2349
  };
2038
2350
  }
2039
2351
 
2040
- 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 } {
2041
2362
  const resolved = resolveAgentName(name, agents);
2042
2363
  const candidates = resolved.error ? agents.filter((agent) => resolveAgentName(name, [agent]).agent) : resolved.agent;
2043
2364
  const diagnostic = findBlockingAgentDiagnostic(name, candidates, diagnostics);
2044
2365
  if (diagnostic) return { error: `Agent '${name}' has invalid configuration: ${diagnostic.error}` };
2045
2366
  if (resolved.error) return { error: resolved.error };
2046
- if (!resolved.agent) return { error: `Unknown agent: ${name}` };
2367
+ if (!resolved.agent) return { error: formatUnknownAgentError(name, context) };
2047
2368
  return { name: resolved.agent.name };
2048
2369
  }
2049
2370
 
2050
- 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 } {
2051
2372
  const resolve = (name: string, location?: string): { name?: string; error?: string } => {
2052
- const result = canonicalizeAgentName(name, agents, diagnostics);
2373
+ const result = canonicalizeAgentName(name, agents, diagnostics, context);
2053
2374
  return result.error && location ? { error: `${result.error} (${location})` } : result;
2054
2375
  };
2055
2376
  if (params.agent) {
2056
2377
  const result = resolve(params.agent);
2057
2378
  if (result.error) return { error: result.error };
2058
2379
  params = omitUndefinedProperties({ ...params, agent: result.name });
2380
+ const agent = agents.find((candidate) => candidate.name === result.name);
2381
+ if (params.extensionBindings !== undefined && (agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job")) return { error: `extensionBindings is not supported for runner.type='${agent.runner.type}'.` };
2382
+ }
2383
+ if (params.extensionBindings !== undefined) {
2384
+ try {
2385
+ params = { ...params, extensionBindings: normalizeExtensionBindings(params.extensionBindings)!.value };
2386
+ } catch (error) {
2387
+ return { error: error instanceof Error ? error.message : String(error) };
2388
+ }
2059
2389
  }
2060
2390
  if (params.tasks) {
2061
2391
  const tasks: TaskParam[] = [];
@@ -2108,6 +2438,7 @@ function validateExecutionInput(
2108
2438
  hasTasks: boolean,
2109
2439
  hasSingle: boolean,
2110
2440
  allowClarifyTaskPrompt: boolean,
2441
+ context: UnknownAgentDiagnosticContext,
2111
2442
  ): AgentToolResult<Details> | null {
2112
2443
  if (Number(hasChain) + Number(hasTasks) + Number(hasSingle) !== 1) {
2113
2444
  return {
@@ -2133,7 +2464,7 @@ function validateExecutionInput(
2133
2464
 
2134
2465
  if (hasSingle && params.agent && !agents.find((agent) => agent.name === params.agent)) {
2135
2466
  return {
2136
- content: [{ type: "text", text: `Unknown agent: ${params.agent}` }],
2467
+ content: [{ type: "text", text: formatUnknownAgentError(params.agent, context) }],
2137
2468
  isError: true,
2138
2469
  details: { mode: "single" as const, results: [] },
2139
2470
  };
@@ -2144,7 +2475,7 @@ function validateExecutionInput(
2144
2475
  const task = params.tasks[i]!;
2145
2476
  if (!agents.find((agent) => agent.name === task.agent)) {
2146
2477
  return {
2147
- content: [{ type: "text", text: `Unknown agent: ${task.agent} (task ${i + 1})` }],
2478
+ content: [{ type: "text", text: `${formatUnknownAgentError(task.agent, context)} (task ${i + 1})` }],
2148
2479
  isError: true,
2149
2480
  details: { mode: "parallel" as const, results: [] },
2150
2481
  };
@@ -2189,7 +2520,7 @@ function validateExecutionInput(
2189
2520
  for (const agentName of stepAgents) {
2190
2521
  if (!agents.find((a) => a.name === agentName)) {
2191
2522
  return {
2192
- content: [{ type: "text", text: `Unknown agent: ${agentName} (step ${i + 1})` }],
2523
+ content: [{ type: "text", text: `${formatUnknownAgentError(agentName, context)} (step ${i + 1})` }],
2193
2524
  isError: true,
2194
2525
  details: { mode: "chain" as const, results: [] },
2195
2526
  };
@@ -2381,9 +2712,6 @@ function applySingleAgentLaunchDefaults(params: SubagentParamsLike, agents: Agen
2381
2712
  ? { timeoutMs: agent.defaultTimeoutMs }
2382
2713
  : {}),
2383
2714
  ...(parentTimeoutMs !== undefined ? { timeoutMs: parentTimeoutMs } : {}),
2384
- ...(params.turnBudget === undefined && agent.defaultTurnBudget !== undefined
2385
- ? { turnBudget: agent.defaultTurnBudget }
2386
- : {}),
2387
2715
  ...(params.acceptance === undefined && agent.defaultAcceptance !== undefined
2388
2716
  ? { acceptance: agent.defaultAcceptance }
2389
2717
  : {}),
@@ -2552,6 +2880,14 @@ function withResolvedContext(
2552
2880
  };
2553
2881
  }
2554
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
+
2555
2891
  function withForkThinkingNotes(
2556
2892
  result: AgentToolResult<Details>,
2557
2893
  downgrades: Map<number, string>,
@@ -2577,66 +2913,6 @@ function toExecutionErrorResult(params: SubagentParamsLike, error: unknown, cont
2577
2913
  );
2578
2914
  }
2579
2915
 
2580
- function collectChainSessionFiles(
2581
- chain: ChainStep[],
2582
- sessionFileForTask: ForkSessionFileForTask,
2583
- dynamicFanoutMaxItems?: number,
2584
- ): (string | undefined)[] {
2585
- const sessionFiles: (string | undefined)[] = [];
2586
- let flatIndex = 0;
2587
- for (const step of chain) {
2588
- if (isParallelStep(step)) {
2589
- for (const task of step.parallel) {
2590
- sessionFiles.push(sessionFileForTask(task.agent, flatIndex, task.model));
2591
- flatIndex++;
2592
- }
2593
- continue;
2594
- }
2595
- if (isDynamicParallelStep(step)) {
2596
- const maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
2597
- for (let itemIndex = 0; itemIndex < maxItems; itemIndex++) {
2598
- sessionFiles.push(sessionFileForTask(step.parallel.agent, flatIndex, step.parallel.model));
2599
- flatIndex++;
2600
- }
2601
- continue;
2602
- }
2603
- const sequential = step as SequentialStep;
2604
- sessionFiles.push(sessionFileForTask(sequential.agent, flatIndex, sequential.model));
2605
- flatIndex++;
2606
- }
2607
- return sessionFiles;
2608
- }
2609
-
2610
- function collectChainThinkingOverrides(
2611
- chain: ChainStep[],
2612
- thinkingOverrideForTask: ForkThinkingOverrideForTask,
2613
- dynamicFanoutMaxItems?: number,
2614
- ): (AgentConfig["thinking"] | undefined)[] {
2615
- const thinkingOverrides: (AgentConfig["thinking"] | undefined)[] = [];
2616
- let flatIndex = 0;
2617
- for (const step of chain) {
2618
- if (isParallelStep(step)) {
2619
- for (const task of step.parallel) {
2620
- thinkingOverrides.push(thinkingOverrideForTask(task.agent, flatIndex, task.model));
2621
- flatIndex++;
2622
- }
2623
- continue;
2624
- }
2625
- if (isDynamicParallelStep(step)) {
2626
- const maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
2627
- for (let itemIndex = 0; itemIndex < maxItems; itemIndex++) {
2628
- thinkingOverrides.push(thinkingOverrideForTask(step.parallel.agent, flatIndex, step.parallel.model));
2629
- flatIndex++;
2630
- }
2631
- continue;
2632
- }
2633
- const sequential = step as SequentialStep;
2634
- thinkingOverrides.push(thinkingOverrideForTask(sequential.agent, flatIndex, sequential.model));
2635
- flatIndex++;
2636
- }
2637
- return thinkingOverrides;
2638
- }
2639
-
2640
2916
  type StaticLaunchSummary = { agent: string; model?: string; thinking?: string };
2641
2917
 
2642
2918
  function resolveStaticLaunchSummary(input: {
@@ -2652,6 +2928,7 @@ function resolveStaticLaunchSummary(input: {
2652
2928
  }): StaticLaunchSummary {
2653
2929
  const agentConfig = input.agents.find((agent) => agent.name === input.agent);
2654
2930
  const externalRunner = agentConfig?.runner?.type === "external-cli" || agentConfig?.runner?.type === "external-job";
2931
+ const modelScopes = resolveModelScopesForAgent(input.modelScope, input.agent, input.parentModel);
2655
2932
  const model = externalRunner
2656
2933
  ? undefined
2657
2934
  : resolveEffectiveSubagentModel(
@@ -2659,8 +2936,8 @@ function resolveStaticLaunchSummary(input: {
2659
2936
  agentConfig?.model,
2660
2937
  input.parentModel,
2661
2938
  input.availableModels,
2662
- input.currentProvider,
2663
- input.modelScope === undefined ? {} : { scope: input.modelScope },
2939
+ agentConfig?.modelProvider ?? input.currentProvider,
2940
+ modelScopes.length === 0 ? {} : { scope: modelScopes },
2664
2941
  );
2665
2942
  const thinkingOverride = externalRunner ? undefined : input.thinkingOverrideForTask(input.agent, input.index, model);
2666
2943
  const thinking = externalRunner ? undefined : resolveEffectiveThinking(model, thinkingOverride ?? agentConfig?.thinking);
@@ -2721,14 +2998,6 @@ function collectStaticLaunchSummaries(input: {
2721
2998
  return input.params.agent ? [summary(input.params.agent, 0, input.params.model as string | undefined)] : [];
2722
2999
  }
2723
3000
 
2724
- function firstChainAgent(chain: ChainStep[]): string | undefined {
2725
- const first = chain[0];
2726
- if (!first) return undefined;
2727
- if (isParallelStep(first)) return first.parallel[0]?.agent;
2728
- if (isDynamicParallelStep(first)) return first.parallel.agent;
2729
- return (first as SequentialStep).agent;
2730
- }
2731
-
2732
3001
  function firstRawChainTask(chain: ChainStep[]): string | undefined {
2733
3002
  const first = chain[0];
2734
3003
  if (!first) return undefined;
@@ -2779,21 +3048,29 @@ function wrapChainTasksForFork(chain: ChainStep[], contextPolicy: AgentDefaultCo
2779
3048
  });
2780
3049
  }
2781
3050
 
2782
- function preflightForkSessionsForStaticTasks(
3051
+ async function preflightForkSessionsForStaticTasks(
2783
3052
  params: SubagentParamsLike,
2784
3053
  contextPolicy: AgentDefaultContextPolicy,
2785
- sessionFileForTask: ForkSessionFileForTask,
3054
+ prepareSessionForTask: PrepareForkSessionForTask,
2786
3055
  dynamicFanoutMaxItems?: number,
2787
- ): void {
3056
+ ): Promise<void> {
2788
3057
  if (!contextPolicy.usesFork) return;
2789
3058
  if (params.agent) {
2790
- 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
+ }
2791
3068
  return;
2792
3069
  }
2793
3070
  if (params.tasks) {
2794
- params.tasks.forEach((task, index) => {
2795
- if (shouldForkAgent(contextPolicy, task.agent)) sessionFileForTask(task.agent, index, task.model);
2796
- });
3071
+ for (const [index, task] of params.tasks.entries()) {
3072
+ if (shouldForkAgent(contextPolicy, task.agent)) await prepareSessionForTask(task.agent, index, task.model);
3073
+ }
2797
3074
  return;
2798
3075
  }
2799
3076
  if (!params.chain?.length) return;
@@ -2801,7 +3078,7 @@ function preflightForkSessionsForStaticTasks(
2801
3078
  for (const step of params.chain) {
2802
3079
  if (isParallelStep(step)) {
2803
3080
  for (const task of step.parallel) {
2804
- if (shouldForkAgent(contextPolicy, task.agent)) sessionFileForTask(task.agent, flatIndex, task.model);
3081
+ if (shouldForkAgent(contextPolicy, task.agent)) await prepareSessionForTask(task.agent, flatIndex, task.model);
2805
3082
  flatIndex++;
2806
3083
  }
2807
3084
  continue;
@@ -2809,18 +3086,89 @@ function preflightForkSessionsForStaticTasks(
2809
3086
  if (isDynamicParallelStep(step)) {
2810
3087
  const maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
2811
3088
  if (shouldForkAgent(contextPolicy, step.parallel.agent)) {
2812
- 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);
2813
3090
  }
2814
3091
  flatIndex += maxItems;
2815
3092
  continue;
2816
3093
  }
2817
3094
  const sequential = step as SequentialStep;
2818
- if (shouldForkAgent(contextPolicy, sequential.agent)) sessionFileForTask(sequential.agent, flatIndex, sequential.model);
3095
+ if (shouldForkAgent(contextPolicy, sequential.agent)) await prepareSessionForTask(sequential.agent, flatIndex, sequential.model);
2819
3096
  flatIndex++;
2820
3097
  }
2821
3098
  }
2822
3099
 
2823
- function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentToolResult<Details> | null {
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
+
3112
+ async function waitForWorkflowAsyncSingleResult(
3113
+ params: SubagentParamsLike,
3114
+ launchResult: AgentToolResult<Details>,
3115
+ options: { runId: string; task: string; signal?: AbortSignal; state: SubagentState; kill?: ExecutorDeps["kill"] },
3116
+ ): Promise<AgentToolResult<Details>> {
3117
+ if (params.workflowAwaitAsync !== true || !launchResult.details.asyncDir) return launchResult;
3118
+ const asyncDir = launchResult.details.asyncDir;
3119
+ const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
3120
+ const stopOnAbort = () => { stopAsyncRun(options.state, options.runId, options.kill, { asyncDir, resolvedId: options.runId }); };
3121
+ if (options.signal?.aborted) stopOnAbort();
3122
+ else options.signal?.addEventListener("abort", stopOnAbort, { once: true });
3123
+ let completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>;
3124
+ try {
3125
+ completed = await waitForImportedAsyncRoot({ runId: options.runId, asyncDir, resultPath, index: 0 }, omitUndefinedProperties({
3126
+ shouldAbort: () => options.signal?.aborted === true,
3127
+ timeoutMessage: "Workflow stopped before async child completed.",
3128
+ }));
3129
+ } finally {
3130
+ options.signal?.removeEventListener("abort", stopOnAbort);
3131
+ }
3132
+ fs.rmSync(resultPath, { force: true });
3133
+ const usage = importedAsyncRootUsage(completed);
3134
+ const childResult: SingleResult = omitUndefinedProperties({
3135
+ index: 0,
3136
+ agent: completed.agent,
3137
+ ...(completed.sessionName ? { sessionName: completed.sessionName } : {}),
3138
+ task: options.task,
3139
+ exitCode: completed.exitCode,
3140
+ usage,
3141
+ finalOutput: completed.output,
3142
+ outputState: completed.output.trim() ? "present" as const : "absent" as const,
3143
+ ...(completed.error ? { error: completed.error } : {}),
3144
+ ...(completed.timedOut ? { timedOut: true } : {}),
3145
+ ...(completed.stopped ? { stopped: true } : {}),
3146
+ ...(completed.sessionFile ? { sessionFile: completed.sessionFile } : {}),
3147
+ ...(completed.model ? { model: completed.model } : {}),
3148
+ ...(completed.attemptedModels ? { attemptedModels: completed.attemptedModels } : {}),
3149
+ ...(completed.modelAttempts ? { modelAttempts: completed.modelAttempts } : {}),
3150
+ ...(completed.contextOverflow ? { contextOverflow: true } : {}),
3151
+ ...(completed.structuredOutput !== undefined ? { structuredOutput: completed.structuredOutput } : {}),
3152
+ ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
3153
+ ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
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 } : {}),
3159
+ });
3160
+ return {
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.` }],
3162
+ ...(completed.success ? {} : { isError: true }),
3163
+ details: {
3164
+ ...launchResult.details,
3165
+ runId: options.runId,
3166
+ results: [childResult],
3167
+ },
3168
+ };
3169
+ }
3170
+
3171
+ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Promise<AgentToolResult<Details> | null> {
2824
3172
  const {
2825
3173
  params,
2826
3174
  effectiveCwd,
@@ -2828,7 +3176,6 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2828
3176
  ctx,
2829
3177
  shareEnabled,
2830
3178
  sessionRoot,
2831
- sessionFileForIndex,
2832
3179
  sessionFileForTask,
2833
3180
  thinkingOverrideForTask,
2834
3181
  artifactConfig,
@@ -2838,6 +3185,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2838
3185
  intercomBridge,
2839
3186
  nestedRoute,
2840
3187
  contextPolicy,
3188
+ unknownAgentDiagnosticContext,
2841
3189
  } = data;
2842
3190
  const hasChain = (params.chain?.length ?? 0) > 0;
2843
3191
  const hasTasks = (params.tasks?.length ?? 0) > 0;
@@ -2864,9 +3212,10 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2864
3212
  modelScope: data.modelScope,
2865
3213
  interactive: ctx.hasUI,
2866
3214
  permissions: deps.config.permissions,
3215
+ childRuntime: deps.childRuntime,
2867
3216
  });
2868
3217
  const availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);
2869
- const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);
3218
+ const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth, deps.childRuntime);
2870
3219
  const currentProvider = parentModel?.provider;
2871
3220
  const controlIntercomTarget = resolveRunLevelIntercomTarget(intercomBridge, contextPolicy);
2872
3221
  const childIntercomTarget = resolveChildIntercomTargetFactory(intercomBridge, contextPolicy, id);
@@ -2876,7 +3225,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2876
3225
  const a = agents.find((x) => x.name === params.agent);
2877
3226
  if (!a) {
2878
3227
  return {
2879
- content: [{ type: "text", text: `Unknown agent: ${params.agent}` }],
3228
+ content: [{ type: "text", text: formatUnknownAgentError(params.agent!, unknownAgentDiagnosticContext) }],
2880
3229
  isError: true,
2881
3230
  details: { mode: "single" as const, results: [] },
2882
3231
  };
@@ -2890,11 +3239,26 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2890
3239
  const externalRunnerWithoutExplicitModel = (a.runner?.type === "external-cli" || a.runner?.type === "external-job")
2891
3240
  && params.model === undefined
2892
3241
  && (a.model === undefined || (a.modelSource?.type === "subagents.defaultModel" && a.model === a.modelSource.model));
3242
+ if ((a.runner?.type === "external-cli" || a.runner?.type === "external-job") && (params.fast ?? a.fast) === true) {
3243
+ return buildRequestedModeError(params, `Agent '${a.name}' uses runner.type='${a.runner.type}' and does not support fast mode.`);
3244
+ }
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
+ });
2893
3252
  const modelOverride = a.runner?.type === "external-cli" || a.runner?.type === "external-job"
2894
3253
  ? params.model ?? (externalRunnerWithoutExplicitModel ? undefined : a.model)
2895
- : resolveEffectiveSubagentModel(params.model as string | undefined, a.model, parentModel, availableModels, currentProvider, data.modelScope === undefined ? {} : { scope: data.modelScope });
2896
- const modelOverrideFromParent = inheritsParentModel(params.model as string | undefined, a.model, parentModel);
2897
- return executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
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);
3261
+ const asyncResult = executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
2898
3262
  agent: params.agent!,
2899
3263
  task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(params.task ?? "") : (params.task ?? ""),
2900
3264
  goal: params.task ?? "",
@@ -2903,28 +3267,37 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2903
3267
  ctx: asyncCtx,
2904
3268
  availableModels,
2905
3269
  cwd: effectiveCwd,
3270
+ requestedCwd: data.requestedCwd,
2906
3271
  maxOutput: params.maxOutput,
2907
3272
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
2908
3273
  artifactConfig,
2909
3274
  shareEnabled,
2910
3275
  activeAsyncCapacity: data.activeAsyncCapacity,
2911
3276
  sessionRoot,
2912
- sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
3277
+ sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
2913
3278
  context: contextPolicy.contextForAgent(params.agent!),
2914
3279
  skills,
2915
3280
  output: effectiveOutput,
2916
3281
  outputMode: effectiveOutputMode,
3282
+ outputClaimPath: params.workflowOutputClaimPath,
2917
3283
  ...(params.reads !== undefined ? { reads: params.reads } : {}),
2918
3284
  outputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),
2919
3285
  modelOverride,
3286
+ fast: params.fast,
2920
3287
  modelOverrideFromParent,
2921
- thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
3288
+ modelOrigin,
3289
+ thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
3290
+ thinkingCeiling: a.maxThinking,
2922
3291
  maxSubagentDepth,
2923
3292
  waitToolEnabled: deps.waitToolEnabled,
3293
+ waitToolDefaultTimeoutMs: deps.waitToolDefaultTimeoutMs,
2924
3294
  ...(params.worktree === true ? { worktree: true } : {}),
2925
3295
  worktreeSetupHook: deps.config.worktreeSetupHook,
2926
3296
  worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
2927
3297
  worktreeBaseDir: deps.config.worktreeBaseDir,
3298
+ baseRef: params.baseRef,
3299
+ worktreeProvider: deps.config.worktreeProvider,
3300
+ worktreeBranchPrefix: deps.config.worktreeBranchPrefix,
2928
3301
  controlConfig,
2929
3302
  intercomBridge: params.intercomBridge,
2930
3303
  controlIntercomTarget,
@@ -2932,9 +3305,9 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2932
3305
  nestedRoute,
2933
3306
  agentContract: params.agentContract,
2934
3307
  structuredOutputSchema: params.outputSchema,
3308
+ extensionBindings: params.extensionBindings,
2935
3309
  acceptance: params.acceptance,
2936
3310
  timeoutMs: data.timeoutMs,
2937
- turnBudget: data.turnBudget,
2938
3311
  toolBudget: data.toolBudget,
2939
3312
  usageBudget: data.usageBudget,
2940
3313
  configToolBudget: data.configToolBudget,
@@ -2944,7 +3317,10 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2944
3317
  runFanoutBudget: data.runFanoutBudget,
2945
3318
  parentWorkflowRunId: params.workflowParentRunId,
2946
3319
  workflowKey: params.workflowKey,
3320
+ lane: params.lane,
3321
+ workflowAwaitAsync: params.workflowAwaitAsync,
2947
3322
  }));
3323
+ return waitForWorkflowAsyncSingleResult(params, asyncResult, { runId: id, task: params.task ?? "", signal: data.signal, state: deps.state, kill: deps.kill });
2948
3324
  }
2949
3325
 
2950
3326
  return null;
@@ -2958,6 +3334,12 @@ function createSingleWorktreeSetup(
2958
3334
  setupHook: ExtensionConfig["worktreeSetupHook"],
2959
3335
  setupHookTimeoutMs: ExtensionConfig["worktreeSetupHookTimeoutMs"],
2960
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,
2961
3343
  ): { setup?: WorktreeSetup; errorResult?: AgentToolResult<Details> } {
2962
3344
  if (!enabled) return {};
2963
3345
  try {
@@ -2968,6 +3350,12 @@ function createSingleWorktreeSetup(
2968
3350
  ? { hookPath: setupHook, ...(setupHookTimeoutMs === undefined ? {} : { timeoutMs: setupHookTimeoutMs }) }
2969
3351
  : undefined,
2970
3352
  baseDir,
3353
+ baseRef,
3354
+ provider,
3355
+ branchPrefix,
3356
+ labels: [label],
3357
+ tasks: [task],
3358
+ beforeCreate,
2971
3359
  })),
2972
3360
  };
2973
3361
  } catch (error) {
@@ -2998,9 +3386,7 @@ function resolveWorkflowAggregateOutputPath(
2998
3386
  ctxCwd: string,
2999
3387
  workflowCwd: string,
3000
3388
  outputBaseDir: string,
3001
- configuredOutputBaseDir: string | undefined,
3002
3389
  ): string | undefined {
3003
- if (typeof output === "string" && output && !path.isAbsolute(output) && !configuredOutputBaseDir) return path.resolve(workflowCwd, output);
3004
3390
  return resolveSingleOutputPath(output, ctxCwd, workflowCwd, outputBaseDir);
3005
3391
  }
3006
3392
 
@@ -3012,10 +3398,33 @@ function workflowChildDefaultOutput(aggregateOutputPath: string | undefined, art
3012
3398
  return path.join(artifactsDir, "outputs", sanitizeRunPathSegment(workflowRunId), `${workflowKey}.md`);
3013
3399
  }
3014
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
+
3015
3424
  function writeWorkflowAggregateOutput(outputPath: string | undefined, text: string, producedChildOutputPaths: ReadonlySet<string>): string | undefined {
3016
3425
  if (!outputPath) return undefined;
3017
3426
  try {
3018
- if (producedChildOutputPaths.has(outputPath)) return undefined;
3427
+ if (producedChildOutputPaths.has(resolveWorkflowHostOutputClaimPath(outputPath))) return undefined;
3019
3428
  fs.mkdirSync(path.dirname(outputPath), { recursive: true });
3020
3429
  fs.writeFileSync(outputPath, text, "utf-8");
3021
3430
  return undefined;
@@ -3036,6 +3445,7 @@ function resolveWorkflowChildOutputPath(input: {
3036
3445
  aggregateOutputPath?: string;
3037
3446
  configuredOutputBaseDir?: string;
3038
3447
  discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3448
+ agents: AgentConfig[];
3039
3449
  workflowAgentScope?: unknown;
3040
3450
  state?: SubagentState;
3041
3451
  key: string;
@@ -3054,8 +3464,10 @@ function resolveWorkflowChildOutputPath(input: {
3054
3464
  const hasExplicitOutput = typeof rawOutput === "string" || typeof rawOutput === "boolean";
3055
3465
  const childCwd = typeof input.params.cwd === "string" ? resolveChildCwd(input.workflowCwd, input.params.cwd) : input.workflowCwd;
3056
3466
  const agentScope = resolveExecutionAgentScope(input.params.agentScope ?? input.workflowAgentScope);
3057
- const agents = input.discoverAgents(childCwd, agentScope).agents;
3058
- const agent = typeof input.params.agent === "string" ? resolveAgentName(input.params.agent, agents).agent : undefined;
3467
+ const discoveredAgents = input.discoverAgents(childCwd, agentScope).agents;
3468
+ const agent = typeof input.params.agent === "string"
3469
+ ? resolveAgentName(input.params.agent, discoveredAgents).agent ?? resolveAgentName(input.params.agent, input.agents).agent
3470
+ : undefined;
3059
3471
  const agentOutput = typeof agent?.output === "string" ? agent.output : undefined;
3060
3472
  const output = rawOutput === true || rawOutput === "true"
3061
3473
  ? agentOutput
@@ -3065,7 +3477,7 @@ function resolveWorkflowChildOutputPath(input: {
3065
3477
  ? workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.workflowRunId, input.key)
3066
3478
  : agentOutput;
3067
3479
  return {
3068
- path: resolveSingleOutputPath(output, input.ctxCwd, childCwd, input.configuredOutputBaseDir),
3480
+ path: resolveSingleOutputPath(output, input.ctxCwd, childCwd, input.configuredOutputBaseDir ?? path.join(input.artifactsDir, "outputs", sanitizeRunPathSegment(input.workflowRunId))),
3069
3481
  inherited: !hasExplicitOutput && !input.aggregateOutputPath && agentOutput !== undefined,
3070
3482
  };
3071
3483
  }
@@ -3078,11 +3490,12 @@ function workflowChildOutputClaims(input: {
3078
3490
  aggregateOutputPath?: string;
3079
3491
  configuredOutputBaseDir?: string;
3080
3492
  discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3493
+ agents: AgentConfig[];
3081
3494
  workflowAgentScope?: unknown;
3082
3495
  state: SubagentState;
3083
3496
  claimedOutputPaths: Map<string, string>;
3084
3497
  entries: Array<{ key: string; params: Record<string, unknown> }>;
3085
- }): { 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> } {
3086
3499
  const resolvedEntries = input.entries.map(({ key, params }) => ({
3087
3500
  key,
3088
3501
  ...resolveWorkflowChildOutputPath({ ...input, key, params }),
@@ -3090,24 +3503,30 @@ function workflowChildOutputClaims(input: {
3090
3503
  const paths = new Map<string, number>();
3091
3504
  for (const claimedPath of input.claimedOutputPaths.keys()) paths.set(claimedPath, 1);
3092
3505
  for (const { path: resolved } of resolvedEntries) {
3093
- 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
+ }
3094
3510
  }
3095
3511
  const overrides = new Map<string, string>();
3096
3512
  for (const entry of resolvedEntries) {
3097
- if (entry.inherited && entry.path && (paths.get(entry.path) ?? 0) > 1) {
3513
+ if (entry.inherited && entry.path && (paths.get(resolveWorkflowHostOutputClaimPath(entry.path)) ?? 0) > 1) {
3098
3514
  const output = workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.workflowRunId, entry.key);
3099
3515
  overrides.set(entry.key, output);
3100
3516
  entry.path = output;
3101
3517
  }
3102
3518
  }
3103
3519
  const claims = new Map(input.claimedOutputPaths);
3520
+ const childClaims = new Map<string, string>();
3104
3521
  for (const { key, path: resolved } of resolvedEntries) {
3105
3522
  if (!resolved) continue;
3106
- const previous = claims.get(resolved);
3523
+ const claimPath = resolveWorkflowHostOutputClaimPath(resolved);
3524
+ const previous = claims.get(claimPath);
3107
3525
  if (previous) return { error: `Workflow children '${previous}' and '${key}' resolve output to the same path: ${resolved}. Use distinct child output paths.` };
3108
- claims.set(resolved, key);
3526
+ claims.set(claimPath, key);
3527
+ childClaims.set(key, claimPath);
3109
3528
  }
3110
- return { claims, overrides };
3529
+ return { claims, childClaims, overrides };
3111
3530
  }
3112
3531
 
3113
3532
  function applyWorkflowChildOutputClaims(target: Map<string, string>, claims: Map<string, string>): void {
@@ -3126,20 +3545,30 @@ function prepareWorkflowChildLaunchParams(input: {
3126
3545
  aggregateOutputPath?: string;
3127
3546
  configuredOutputBaseDir?: string;
3128
3547
  discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3548
+ agents: AgentConfig[];
3129
3549
  workflowAgentScope?: unknown;
3130
3550
  outputOverride?: string;
3131
- options?: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number };
3551
+ outputClaimPath?: string;
3552
+ options?: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; awaitDetachedChild?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number; capabilityCeiling?: ResolvedSubagentCapabilityCeiling };
3132
3553
  }): SubagentParamsLike {
3133
3554
  let childParams = input.childParams;
3134
- 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) {
3135
3557
  childParams = { ...input.childParams, output: input.outputOverride };
3136
- } else if (input.childParams.output === undefined && input.childParams.resume === undefined && input.aggregateOutputPath !== undefined) {
3558
+ } else if (usesDefaultOutput && input.aggregateOutputPath !== undefined) {
3137
3559
  childParams = { ...input.childParams, output: workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.parentWorkflowRunId, input.workflowKey) };
3138
3560
  } else if (input.childParams.resume === undefined) {
3139
- const resolvedOutput = resolveWorkflowChildOutputPath({ ctxCwd: input.ctxCwd, workflowCwd: input.workflowCwd, artifactsDir: input.artifactsDir, workflowRunId: input.parentWorkflowRunId, aggregateOutputPath: input.aggregateOutputPath, configuredOutputBaseDir: input.configuredOutputBaseDir, discoverAgents: input.discoverAgents, workflowAgentScope: input.workflowAgentScope, key: input.workflowKey, params: input.childParams });
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 });
3140
3562
  if (resolvedOutput.path) childParams = { ...input.childParams, output: resolvedOutput.path };
3141
3563
  }
3142
- return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, input.options);
3564
+ const childCwd = typeof childParams.cwd === "string" ? resolveChildCwd(input.workflowCwd, childParams.cwd) : input.workflowCwd;
3565
+ const agentScope = resolveExecutionAgentScope(childParams.agentScope ?? input.workflowAgentScope);
3566
+ const discoveredAgents = input.discoverAgents(childCwd, agentScope).agents;
3567
+ const agent = typeof childParams.agent === "string"
3568
+ ? resolveAgentName(childParams.agent, discoveredAgents).agent ?? resolveAgentName(childParams.agent, input.agents).agent
3569
+ : undefined;
3570
+ const externalAsyncRequired = agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job";
3571
+ return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, { ...input.options, externalAsyncRequired, outputClaimPath: input.outputClaimPath });
3143
3572
  }
3144
3573
 
3145
3574
  function finalizeSingleWorktreeHandoff(input: {
@@ -3149,6 +3578,8 @@ function finalizeSingleWorktreeHandoff(input: {
3149
3578
  cwd: string;
3150
3579
  agent: string;
3151
3580
  result: SingleResult;
3581
+ workflowKey?: string;
3582
+ lane?: import("../../shared/types.ts").WorkflowLaneMetadata;
3152
3583
  }): { suffix: string; reference?: NonNullable<Details["parallelHandoff"]> } {
3153
3584
  const diffsDir = path.join(input.artifactsDir, "worktree-diffs", input.runId);
3154
3585
  const diffs = diffWorktrees(input.worktreeSetup, [input.agent], diffsDir);
@@ -3163,9 +3594,13 @@ function finalizeSingleWorktreeHandoff(input: {
3163
3594
  stepIndex: 0,
3164
3595
  flatStartIndex: 0,
3165
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,
3166
3598
  diffs,
3167
3599
  results: [{
3168
3600
  agent: input.result.agent,
3601
+ ...(input.workflowKey ? { workflowKey: input.workflowKey } : {}),
3602
+ ...(input.workflowKey ? { runId: input.runId } : {}),
3603
+ ...(input.lane ? { lane: input.lane } : {}),
3169
3604
  status: resolveSubagentResultStatus(omitUndefinedProperties({
3170
3605
  exitCode: input.result.exitCode,
3171
3606
  interrupted: input.result.interrupted,
@@ -3211,10 +3646,17 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3211
3646
  artifactConfig,
3212
3647
  artifactsDir,
3213
3648
  onUpdate,
3214
- sessionRoot,
3215
3649
  controlConfig,
3216
3650
  contextPolicy,
3651
+ suppressUnchangedDelegationUpdates,
3217
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
+ }
3218
3660
  const onControlEvent = createForegroundControlNotifier(data, deps);
3219
3661
  const childBridgeActive = intercomBridgeAppliesToAgent(data.intercomBridge, contextPolicy, params.agent!);
3220
3662
  const childIntercomTarget = childBridgeActive ? resolveSubagentIntercomTarget(runId, params.agent!, 0) : undefined;
@@ -3223,7 +3665,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3223
3665
  const agentConfig = agents.find((a) => a.name === params.agent);
3224
3666
  if (!agentConfig) {
3225
3667
  return {
3226
- content: [{ type: "text", text: `Unknown agent: ${params.agent}` }],
3668
+ content: [{ type: "text", text: formatUnknownAgentError(params.agent!, data.unknownAgentDiagnosticContext) }],
3227
3669
  isError: true,
3228
3670
  details: { mode: "single", results: [] },
3229
3671
  };
@@ -3234,26 +3676,39 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3234
3676
  const parentModel = data.parentModel;
3235
3677
  const currentProvider = parentModel?.provider;
3236
3678
  const availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);
3237
- let task = params.task ?? "";
3679
+ const modelScopes = resolveModelScopesForAgent(data.modelScope, agentConfig.name, parentModel);
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
+ });
3238
3687
  let modelOverride: string | undefined = resolveEffectiveSubagentModel(
3239
3688
  params.model as string | undefined,
3240
3689
  agentConfig.model,
3241
3690
  parentModel,
3242
3691
  availableModels,
3243
- currentProvider,
3244
- data.modelScope === undefined ? {} : { scope: data.modelScope },
3692
+ agentConfig.modelProvider ?? currentProvider,
3693
+ {
3694
+ ...(modelScopes.length === 0 ? {} : { scope: modelScopes }),
3695
+ source: modelOrigin === "explicit" ? "explicit" : "inherited",
3696
+ },
3245
3697
  );
3246
- 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);
3247
3701
  let skillOverride: string[] | false | undefined = normalizeSkillInput(params.skill);
3248
3702
  let readsOverride: string[] | false | undefined = params.reads;
3249
3703
  const rawOutput = params.output !== undefined ? params.output : agentConfig.output;
3250
3704
  let effectiveOutput = normalizeSingleOutputOverride(rawOutput, agentConfig.output);
3251
3705
  const effectiveOutputMode = params.outputMode ?? agentConfig.outputMode ?? "inline";
3252
- const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);
3706
+ const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth, deps.childRuntime);
3253
3707
  const maxSubagentDepth = resolveChildMaxSubagentDepth(currentMaxSubagentDepth, agentConfig.maxSubagentDepth);
3254
3708
 
3255
3709
 
3256
3710
  const sourceCwd = effectiveCwd;
3711
+ let pendingHandoff: Details["parallelHandoff"];
3257
3712
  const { setup: worktreeSetup, errorResult: worktreeSetupError } = createSingleWorktreeSetup(
3258
3713
  params.worktree,
3259
3714
  sourceCwd,
@@ -3262,12 +3717,12 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3262
3717
  deps.config.worktreeSetupHook,
3263
3718
  deps.config.worktreeSetupHookTimeoutMs,
3264
3719
  deps.config.worktreeBaseDir,
3265
- );
3266
- if (worktreeSetupError) return worktreeSetupError;
3267
- const singleCwd = worktreeSetup?.worktrees[0]?.agentCwd ?? sourceCwd;
3268
- let pendingHandoff: Details["parallelHandoff"];
3269
- if (worktreeSetup) {
3270
- try {
3720
+ params.baseRef,
3721
+ deps.config.worktreeProvider,
3722
+ deps.config.worktreeBranchPrefix,
3723
+ params.lane?.key ?? params.workflowKey,
3724
+ task,
3725
+ (plannedSetup) => {
3271
3726
  pendingHandoff = writePendingParallelHandoff({
3272
3727
  manifestPath: parallelHandoffPath(artifactsDir, runId),
3273
3728
  runId,
@@ -3276,13 +3731,13 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3276
3731
  cwd: sourceCwd,
3277
3732
  stepIndex: 0,
3278
3733
  flatStartIndex: 0,
3279
- setup: worktreeSetup,
3734
+ setup: plannedSetup,
3735
+ laneBindings: params.workflowKey || lane ? [{ index: 0, taskIndex: 0, ...(params.workflowKey ? { workflowKey: params.workflowKey, runId } : {}), ...(lane ? { lane } : {}) }] : undefined,
3280
3736
  });
3281
- } catch (error) {
3282
- cleanupWorktrees(worktreeSetup);
3283
- return { content: [{ type: "text", text: formatParallelHandoffError(error) }], isError: true, details: { mode: "single", results: [] } };
3284
- }
3285
- }
3737
+ },
3738
+ );
3739
+ if (worktreeSetupError) return worktreeSetupError;
3740
+ const singleCwd = worktreeSetup?.worktrees[0]?.agentCwd ?? sourceCwd;
3286
3741
 
3287
3742
  const authoredTask = task;
3288
3743
  if (shouldForkAgent(contextPolicy, params.agent!)) {
@@ -3296,7 +3751,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3296
3751
  return { content: [{ type: "text", text: validationError }], isError: true, details: { mode: "single", results: [] } };
3297
3752
  }
3298
3753
  const structuredRuntime = params.outputSchema
3299
- ? createStructuredOutputRuntime(params.outputSchema, artifactConfig.enabled ? path.join(artifactsDir, "structured-output", runId) : undefined)
3754
+ ? createStructuredOutputRuntime(params.outputSchema, artifactConfig.enabled ? path.join(artifactsDir, "structured-output", runId) : undefined, { acceptanceReport: resolveAcceptanceReportMode(params.acceptance) })
3300
3755
  : undefined;
3301
3756
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
3302
3757
  // absolute paths pass through; relative paths resolve against the child cwd.
@@ -3316,9 +3771,10 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3316
3771
  }
3317
3772
  const interruptController = new AbortController();
3318
3773
  let detachForeground: ((reason?: string) => boolean) | undefined;
3774
+ let childSessionControls: ForegroundChildSessionControls | undefined;
3319
3775
  const foregroundControl = deps.state.foregroundControls.get(runId);
3320
3776
  if (foregroundControl) {
3321
- const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent));
3777
+ const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin));
3322
3778
  beginForegroundChild(foregroundControl, omitUndefinedProperties({
3323
3779
  index: 0,
3324
3780
  agent: params.agent!,
@@ -3336,6 +3792,19 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3336
3792
  return true;
3337
3793
  },
3338
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
+ },
3339
3808
  }));
3340
3809
  }
3341
3810
 
@@ -3348,31 +3817,42 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3348
3817
 
3349
3818
  const deadlineAt = data.deadlineAt ?? (data.timeoutMs !== undefined ? Date.now() + data.timeoutMs : undefined);
3350
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;
3351
3824
  try {
3352
- 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]>({
3353
3826
  permissions: deps.config.permissions,
3827
+ runtimeSnapshotHost: deps.pi,
3354
3828
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
3355
3829
  llmIntentArbiter: createTaskMutationArbiter(ctx),
3356
- ...workflowForegroundSteeringLaunchOptions(foregroundControl, 0),
3830
+ childRuntime: deps.childRuntime,
3831
+ onChildSession: (controls) => { childSessionControls = controls; },
3357
3832
  context: data.contextPolicy.contextForAgent(params.agent!),
3833
+ unknownAgentDiagnosticContext: data.unknownAgentDiagnosticContext,
3358
3834
  runFanoutBudget: params.runFanoutAdmitted ? data.runFanoutBudget : { ...data.runFanoutBudget, parentPath: `${data.runFanoutBudget.parentPath ? `${data.runFanoutBudget.parentPath}/` : ""}single` },
3359
3835
  cwd: singleCwd,
3836
+ requestedCwd: data.requestedCwd,
3360
3837
  signal,
3361
3838
  interruptSignal: interruptController.signal,
3362
3839
  allowIntercomDetach: agentConfig.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,
3363
3840
  intercomEvents: deps.pi.events,
3364
3841
  runId,
3365
3842
  sessionDir: sessionDirForIndex(0),
3366
- sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
3843
+ sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
3367
3844
  share: shareEnabled,
3368
3845
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3369
3846
  artifactConfig,
3370
3847
  maxOutput: params.maxOutput,
3371
3848
  outputPath,
3849
+ outputClaimPath: params.workflowOutputClaimPath,
3372
3850
  outputMode: effectiveOutputMode,
3373
3851
  maxSubagentDepth,
3374
3852
  waitToolEnabled: deps.waitToolEnabled,
3853
+ waitToolDefaultTimeoutMs: deps.waitToolDefaultTimeoutMs,
3375
3854
  onUpdate: forwardSingleUpdate,
3855
+ suppressUnchangedDelegationUpdates,
3376
3856
  controlConfig,
3377
3857
  onControlEvent,
3378
3858
  intercomSessionName: childIntercomTarget,
@@ -3380,22 +3860,34 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3380
3860
  nestedRoute: foregroundControl?.nestedRoute,
3381
3861
  index: 0,
3382
3862
  modelOverride,
3863
+ fast: params.fast,
3383
3864
  modelOverrideFromParent,
3384
- thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
3865
+ modelOrigin,
3866
+ thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
3867
+ thinkingCeiling: agentConfig.maxThinking,
3868
+ extensionBindings: params.extensionBindings,
3385
3869
  availableModels,
3386
3870
  preferredModelProvider: currentProvider,
3387
- modelScope: data.modelScope,
3871
+ modelScope: modelScopes,
3388
3872
  skills: effectiveSkills,
3389
3873
  structuredOutput: structuredRuntime,
3390
3874
  agentContract: params.agentContract,
3391
3875
  acceptance: params.acceptance,
3392
3876
  acceptanceContext: { mode: "single" },
3877
+ workflowChildPermitLaunch: data.workflowChildPermitLaunch,
3393
3878
  onEffectivePrompt: foregroundControl ? (prompt) => updateLiveEffectivePrompt(foregroundControl, 0, prompt) : undefined,
3394
3879
  onDetachReady: (detach) => {
3395
3880
  detachForeground = detach;
3396
3881
  },
3397
3882
  onDetachedExit: (result) => {
3883
+ if (resolveDetachedWorkflowChild) {
3884
+ resolveDetachedWorkflowChild(result);
3885
+ return;
3886
+ }
3398
3887
  try {
3888
+ if (worktreeSetup) {
3889
+ finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result, workflowKey: params.workflowKey, lane });
3890
+ }
3399
3891
  try {
3400
3892
  updateRememberedForegroundChild(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, index: 0, result, events: deps.pi.events, notify: true });
3401
3893
  } catch {
@@ -3423,18 +3915,17 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3423
3915
  }
3424
3916
  }
3425
3917
  }
3426
- recordRun(params.agent!, cleanTask, result.exitCode, result.progressSummary?.durationMs ?? 0);
3918
+ recordRun(params.agent!, cleanTask, result.exitCode, result.progressSummary?.durationMs ?? 0, result);
3427
3919
  },
3428
3920
  timeoutMs: data.timeoutMs,
3429
3921
  deadlineAt,
3430
3922
  toolTimeoutMs: params.toolTimeoutMs,
3431
3923
  configToolTimeoutMs: data.configToolTimeoutMs,
3432
- turnBudget: data.turnBudget,
3433
- enforceHardTurnLimit: params.enforceHardTurnLimit,
3434
3924
  toolBudget: effectiveToolBudget.toolBudget,
3435
3925
  capabilityCeiling: data.capabilityCeiling,
3436
3926
  allowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,
3437
3927
  }));
3928
+ r = launched.detached && detachedWorkflowChild ? await detachedWorkflowChild : launched;
3438
3929
  } catch (error) {
3439
3930
  if (worktreeSetup) cleanupWorktrees(worktreeSetup);
3440
3931
  throw error;
@@ -3448,14 +3939,14 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3448
3939
  }
3449
3940
  }
3450
3941
  if (!r.detached) {
3451
- recordRun(params.agent!, cleanTask, r.exitCode, r.progressSummary?.durationMs ?? 0);
3942
+ recordRun(params.agent!, cleanTask, r.exitCode, r.progressSummary?.durationMs ?? 0, r);
3452
3943
  }
3453
3944
 
3454
3945
  let worktreeHandoff: ReturnType<typeof finalizeSingleWorktreeHandoff> | undefined;
3455
3946
  if (worktreeSetup) {
3456
3947
  worktreeHandoff = r.detached
3457
3948
  ? { suffix: pendingHandoff ? formatParallelHandoffReference(pendingHandoff) : "", reference: pendingHandoff }
3458
- : 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 });
3459
3950
  }
3460
3951
 
3461
3952
  if (r.progress) allProgress.push(r.progress);
@@ -3484,7 +3975,6 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3484
3975
  runId,
3485
3976
  timeoutMs: data.timeoutMs,
3486
3977
  results: [r],
3487
- ...(data.turnBudget ? { turnBudget: data.turnBudget } : {}),
3488
3978
  ...(effectiveToolBudget.toolBudget ? { toolBudget: effectiveToolBudget.toolBudget } : {}),
3489
3979
  progress: params.includeProgress ? allProgress : undefined,
3490
3980
  artifacts: allArtifactPaths.length ? { dir: artifactsDir, files: allArtifactPaths } : undefined,
@@ -3494,7 +3984,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3494
3984
  usageBudget: usageBudgetState(data.usageBudget, totalCost),
3495
3985
  ...(worktreeHandoff?.reference ? { parallelHandoff: worktreeHandoff.reference } : {}),
3496
3986
  }));
3497
- rememberForegroundRun(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: details.results });
3987
+ rememberForegroundRun(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: details.results, params, effectiveOutput, effectiveOutputMode, extensionBindings: params.extensionBindings });
3498
3988
 
3499
3989
  const suppressRoutineResultIntercom = shouldSuppressRoutineResultIntercom({ suppressRoutineResultIntercom: params.suppressRoutineResultIntercom, results: [r] });
3500
3990
  if (!r.detached && !r.interrupted && !suppressRoutineResultIntercom) {
@@ -3520,11 +4010,11 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3520
4010
  const worktreeSuffix = worktreeHandoff?.suffix ? `\n\n${worktreeHandoff.suffix}` : "";
3521
4011
  if (r.detached) {
3522
4012
  const statusRecovery = `subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
3523
- const blockingRecovery = `subagent_wait({ id: "${runId}" }). Use ${statusRecovery}`;
4013
+ const blockingRecovery = `bg_wait({ id: "${runId}" }). Use ${statusRecovery}`;
3524
4014
  const message = r.detachedReason === "intercom coordination"
3525
4015
  ? `Detached for intercom coordination: ${params.agent}. Reply to the supervisor request first, then wait with ${blockingRecovery}`
3526
4016
  : r.detachedReason === "user request"
3527
- ? `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}`
3528
4018
  : `Detached before task completion: ${params.agent}. Wait with ${blockingRecovery}`;
3529
4019
  return {
3530
4020
  content: [{ type: "text", text: `${message}${worktreeSuffix}` }],
@@ -3569,7 +4059,7 @@ function duplicateSubagentCallResult(params: SubagentParamsLike): AgentToolResul
3569
4059
  };
3570
4060
  }
3571
4061
 
3572
- 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>();
3573
4063
 
3574
4064
  /**
3575
4065
  * Terminal-mission retention can remove a mission while its children still
@@ -3641,15 +4131,29 @@ export function bindMissionWorkflowChildAsyncLaunch(
3641
4131
  function workflowChildResult(
3642
4132
  key: string,
3643
4133
  result: AgentToolResult<Details>,
3644
- childParams: Record<string, unknown> = {},
4134
+ childParams: SubagentParamsLike | Record<string, unknown> = {},
3645
4135
  resumeState?: SubagentState,
4136
+ forcedTerminalOutcome?: WorkflowTerminalOutcome,
3646
4137
  ): WorkflowScriptChildResult {
3647
4138
  const receiptOutput = result.content.map((part) => part.type === "text" ? part.text : "").filter(Boolean).join("\n");
3648
4139
  const output = result.details.results.length === 1 && result.details.results[0]?.finalOutput !== undefined
3649
4140
  ? result.details.results[0].finalOutput
3650
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.";
3651
4146
  const detached = result.details.results.some((child) => child.detached);
3652
- const ok = result.isError !== true && !detached;
4147
+ const interrupted = result.details.results.some((child) => child.interrupted);
4148
+ const stopped = result.details.results.some((child) => child.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;
3653
4157
  const artifactPaths = new Set<string>();
3654
4158
  if (result.details.asyncDir) artifactPaths.add(result.details.asyncDir);
3655
4159
  if (result.details.parallelHandoff?.path) artifactPaths.add(result.details.parallelHandoff.path);
@@ -3681,18 +4185,35 @@ function workflowChildResult(
3681
4185
  const continuationRunIds = [...new Set([resumeSourceRunId, runId].filter((value): value is string => Boolean(value)))];
3682
4186
  const outputReference = result.details.results.find((child) => child.savedOutputPath)?.savedOutputPath
3683
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`);
3684
4198
  return {
3685
4199
  key,
3686
4200
  ok,
4201
+ ...(lane ? { lane } : {}),
4202
+ ...(terminalOutcome ? { terminalOutcome } : {}),
3687
4203
  ...(resolvedAgents.length === 1 ? { agent: resolvedAgents[0] } : {}),
3688
4204
  ...(runId ? { runId } : {}),
3689
4205
  output,
3690
- ...(!ok ? { error: receiptOutput || output || "Child run failed." } : {}),
4206
+ ...(!ok ? { error: failureError } : {}),
3691
4207
  ...(detached ? { detached: true } : {}),
4208
+ ...(interrupted ? { interrupted: true } : {}),
4209
+ ...(stopped ? { stopped: true } : {}),
3692
4210
  ...(structured.length === 1 ? { structuredOutput: structured[0] } : structured.length > 1 ? { structuredOutput: structured } : {}),
3693
4211
  ...(requestedContext ? { requestedContext } : {}),
3694
4212
  ...(resolvedContext ? { resolvedContext } : {}),
3695
4213
  ...(outputReference ? { outputReference } : {}),
4214
+ ...(acceptanceRecovery ? { recovery: acceptanceRecovery } : {}),
4215
+ ...(outputPathMapping ? { outputPathMapping } : {}),
4216
+ ...(externalAdapter ? { externalAdapter } : {}),
3696
4217
  resumability,
3697
4218
  continuation: { runIds: continuationRunIds },
3698
4219
  artifactPaths: [...artifactPaths],
@@ -3700,6 +4221,28 @@ function workflowChildResult(
3700
4221
  };
3701
4222
  }
3702
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
+
3703
4246
  function workflowSteerReceipt(key: string, result: AgentToolResult<Details>): WorkflowSteerResult {
3704
4247
  const steering = result.details.steering;
3705
4248
  const error = result.content.map((part) => part.type === "text" ? part.text : "").filter(Boolean).join("\n") || undefined;
@@ -3717,29 +4260,124 @@ function workflowSteerReceipt(key: string, result: AgentToolResult<Details>): Wo
3717
4260
  };
3718
4261
  }
3719
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
+
3720
4331
  function resolveKeyedWorkflowResume(
3721
4332
  reference: WorkflowReceiptResumeReference,
3722
4333
  state: SubagentState,
3723
4334
  ): { runId: string; runIds: string[] } {
3724
- const entry = resolveWorkflowReceiptResumeEntry({
3725
- reference,
3726
- asyncDirRoot: DIRS.async,
3727
- assertResumable(runId) {
3728
- const target = resolveResumeTarget({ id: runId }, state, { asyncRequireSessionFile: true, exactOnly: true });
3729
- if (target.kind !== "revive") throw new Error(`Workflow receipt child '${reference.key}' latest run '${runId}' is still running.`);
3730
- },
3731
- });
3732
- const runId = entry.latestRunId;
3733
- if (!runId) throw new Error(`Workflow receipt child '${reference.key}' has no retained run id.`);
3734
- 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
+ }
3735
4355
  }
3736
4356
 
3737
4357
  function terminalWorkflowReceipt(
3738
4358
  workflowRunId: string,
3739
4359
  state: WorkflowReceiptState,
3740
4360
  children: WorkflowScriptChildResult[],
4361
+ workflowChildren?: WorkflowReceipt["workflowChildren"],
4362
+ terminalOutcome?: WorkflowTerminalOutcome,
4363
+ hostSteps?: WorkflowReceipt["hostSteps"],
4364
+ resource?: WorkflowReceipt["resource"],
3741
4365
  ): WorkflowReceipt {
3742
- 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;
3743
4381
  }
3744
4382
 
3745
4383
  export async function steerWorkflowChildByKey(input: {
@@ -3758,7 +4396,6 @@ export async function steerWorkflowChildByKey(input: {
3758
4396
  while (true) {
3759
4397
  const control = [...input.state.foregroundControls.values()].find((candidate) => candidate.parentWorkflowRunId === input.workflowRunId
3760
4398
  && candidate.workflowKey === input.key
3761
- && Boolean(candidate.workflowSteeringDir)
3762
4399
  && (candidate.activeChildren?.size ?? 0) > 0);
3763
4400
  if (control) {
3764
4401
  const result = await steerWorkflowForegroundTarget({
@@ -3766,10 +4403,9 @@ export async function steerWorkflowChildByKey(input: {
3766
4403
  message: input.message,
3767
4404
  mode: input.options.mode,
3768
4405
  index: input.options.index,
3769
- ackTimeoutMs: Math.max(1, deadline - Date.now()),
3770
- signal: input.signal,
3771
4406
  });
3772
- 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);
3773
4409
  }
3774
4410
 
3775
4411
  const workflowStatus = readStatus(path.join(asyncDirRoot, input.workflowRunId));
@@ -3782,6 +4418,8 @@ export async function steerWorkflowChildByKey(input: {
3782
4418
  return { key: input.key, state: "missed", error: `Workflow child '${input.key}' is ${childStatus.state}.` };
3783
4419
  }
3784
4420
  if (childStatus) {
4421
+ const unsupported = externalRunnerControlError(asyncDir, "steer");
4422
+ if (unsupported) return workflowSteerReceipt(input.key, unsupported);
3785
4423
  const result = await steerAsyncRun({
3786
4424
  state: input.state,
3787
4425
  runId: childRunId,
@@ -3813,8 +4451,15 @@ export function prepareWorkflowLaunchParams(
3813
4451
  childParams: Record<string, unknown>,
3814
4452
  parentWorkflowRunId: string,
3815
4453
  workflowKey: string,
3816
- options: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number } = {},
4454
+ options: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; awaitDetachedChild?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number; externalAsyncRequired?: boolean; capabilityCeiling?: ResolvedSubagentCapabilityCeiling; outputClaimPath?: string } = {},
3817
4455
  ): SubagentParamsLike {
4456
+ const { globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowDefaultsWithoutCapacity } = workflowDefaults;
4457
+ const { globalConcurrencyLimit: _childGlobalConcurrencyLimit, maxSubagentSpawnsPerRun: _childMaxSubagentSpawnsPerRun, ...childParamsWithoutCapacity } = childParams;
4458
+ workflowDefaults = workflowDefaultsWithoutCapacity;
4459
+ childParams = childParamsWithoutCapacity;
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`);
3818
4463
  const parentTimeoutMs = options.parentDeadlineAt === undefined
3819
4464
  || childParams.timeoutMs !== undefined
3820
4465
  || childParams.maxRuntimeMs !== undefined
@@ -3823,14 +4468,27 @@ export function prepareWorkflowLaunchParams(
3823
4468
  ? undefined
3824
4469
  : Math.max(1, options.parentDeadlineAt - Date.now());
3825
4470
  if (typeof childParams.resume === "string") {
4471
+ if (childParams.extensionBindings !== undefined || workflowDefaults.extensionBindings !== undefined) {
4472
+ throw new Error("extensionBindings is not supported with retained resume; resume uses the original retained child binding.");
4473
+ }
3826
4474
  if (childParams.gate !== undefined || workflowDefaults.gate !== undefined) {
3827
4475
  throw new Error("gate is not supported with retained resume; resume uses the retained child contract.");
3828
4476
  }
3829
4477
  const timeoutMs = childParams.timeoutMs ?? childParams.maxRuntimeMs ?? workflowDefaults.timeoutMs ?? workflowDefaults.maxRuntimeMs;
3830
- const turnBudget = childParams.turnBudget ?? workflowDefaults.turnBudget;
3831
4478
  const toolBudget = childParams.toolBudget ?? workflowDefaults.toolBudget;
3832
4479
  const intercomBridge = childParams.intercomBridge ?? workflowDefaults.intercomBridge;
3833
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);
3834
4492
  return {
3835
4493
  action: "resume",
3836
4494
  id: childParams.resume.trim(),
@@ -3838,31 +4496,58 @@ export function prepareWorkflowLaunchParams(
3838
4496
  message: typeof childParams.task === "string" ? childParams.task.trim() : "",
3839
4497
  workflowParentRunId: parentWorkflowRunId,
3840
4498
  workflowKey,
4499
+ ...(lane ? { lane } : {}),
3841
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 } : {}),
3842
4507
  ...(options.runFanoutBudget ? { runFanoutBudget: { ...options.runFanoutBudget, parentPath: `${options.runFanoutBudget.parentPath ? `${options.runFanoutBudget.parentPath}/` : ""}workflow[${workflowKey}]` } } : {}),
3843
4508
  ...(options.missionDetached ? { mission: false } : {}),
3844
4509
  ...(timeoutMs !== undefined ? { timeoutMs: timeoutMs as number } : {}),
3845
- ...(turnBudget !== undefined ? { turnBudget: turnBudget as TurnBudgetConfig } : {}),
3846
4510
  ...(toolBudget !== undefined ? { toolBudget: toolBudget as ToolBudgetConfig } : {}),
4511
+ ...(control !== undefined ? { control } : {}),
3847
4512
  ...(intercomBridge !== undefined ? { intercomBridge: intercomBridge as IntercomBridgeConfig } : {}),
4513
+ ...(capabilityCeiling ? { capabilityCeiling } : {}),
3848
4514
  };
3849
4515
  }
4516
+ const control = mergeWorkflowControlOverrides(workflowDefaults.control, childParams.control as ControlConfig | undefined);
3850
4517
  const launchParams = {
3851
4518
  ...workflowDefaults,
3852
- async: false,
4519
+ async: options.externalAsyncRequired === true && childParams.async === undefined && workflowDefaults.async === undefined ? true : false,
3853
4520
  ...childParams,
4521
+ ...(control !== undefined ? { control } : {}),
4522
+ ...(options.externalAsyncRequired === true && childParams.async === undefined && workflowDefaults.async === undefined ? { workflowAwaitAsync: true } : {}),
3854
4523
  ...(options.missionDetached ? { mission: false } : {}),
3855
4524
  workflowParentRunId: parentWorkflowRunId,
3856
4525
  workflowKey,
4526
+ ...(options.outputClaimPath ? { workflowOutputClaimPath: options.outputClaimPath } : {}),
4527
+ ...(options.awaitDetachedChild ? { workflowAwaitDetached: true } : {}),
4528
+ ...(lane ? { lane } : {}),
3857
4529
  ...(parentTimeoutMs !== undefined ? { workflowParentDeadlineAt: options.parentDeadlineAt } : {}),
3858
4530
  ...(options.runFanoutBudget ? { runFanoutBudget: { ...options.runFanoutBudget, parentPath: `${options.runFanoutBudget.parentPath ? `${options.runFanoutBudget.parentPath}/` : ""}workflow[${workflowKey}]` } } : {}),
3859
4531
  ...(options.suppressRoutineResultIntercom ? { suppressRoutineResultIntercom: true } : {}),
4532
+ ...(capabilityCeiling ? { capabilityCeiling } : {}),
3860
4533
  } as SubagentParamsLike;
4534
+ if (launchParams.extensionBindings !== undefined) launchParams.extensionBindings = normalizeExtensionBindings(launchParams.extensionBindings)!.value;
3861
4535
  const normalizedGate = normalizeGateParams(launchParams);
3862
4536
  if (!normalizedGate.ok) throw new Error(normalizedGate.error);
3863
4537
  return normalizedGate.params;
3864
4538
  }
3865
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
+
3866
4551
  type GateParamsNormalizationResult =
3867
4552
  | { ok: true; params: SubagentParamsLike }
3868
4553
  | { ok: false; error: string };
@@ -3888,15 +4573,101 @@ function formatWorkflowValue(value: unknown): string {
3888
4573
  }
3889
4574
  }
3890
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
+
3891
4660
  function workflowChatProgressUpdate(
3892
4661
  runId: string,
3893
4662
  chatProgress: WorkflowChatProgressProjection,
3894
4663
  workflow: NonNullable<Details["workflow"]>,
4664
+ workflowChildren?: Details["workflowChildren"],
4665
+ preflight?: import("../../shared/types.ts").WorkflowPreflightV1,
3895
4666
  ): AgentToolResult<Details> | undefined {
3896
4667
  if (chatProgress.mode !== "live-card") return undefined;
3897
4668
  return {
3898
4669
  content: [{ type: "text", text: "Workflow running." }],
3899
- details: { mode: "workflow", runId, results: [], workflow, chatProgress },
4670
+ details: { mode: "workflow", runId, results: [], workflow, ...(preflight ? { preflight } : {}), ...(workflowChildren ? { workflowChildren } : {}), chatProgress },
3900
4671
  };
3901
4672
  }
3902
4673
 
@@ -3907,13 +4678,16 @@ function createScheduledOwnerState(source: SubagentState, ownerSessionId: string
3907
4678
  grantHistory: [...(source.subagentSpawns.grantHistory ?? [])],
3908
4679
  }
3909
4680
  : undefined;
4681
+ const ownerParentModel = source.currentSessionId === ownerSessionId ? source.lastParentModel : undefined;
3910
4682
  return {
3911
4683
  ...source,
3912
4684
  baseCwd: ctx.cwd,
3913
4685
  currentSessionId: ownerSessionId,
4686
+ lastParentModel: ownerParentModel,
3914
4687
  parentSessionFile: ctx.sessionManager.getSessionFile() ?? null,
3915
4688
  subagentInProgress: false,
3916
4689
  ...(ownerSpawns ? { subagentSpawns: ownerSpawns } : { subagentSpawns: undefined }),
4690
+ herdrProjectPanes: new Map(),
3917
4691
  asyncJobs: new Map(),
3918
4692
  fleetJobs: new Map(),
3919
4693
  foregroundRuns: new Map(),
@@ -3927,6 +4701,7 @@ function createScheduledOwnerState(source: SubagentState, ownerSessionId: string
3927
4701
  watcherRestartTimer: null,
3928
4702
  waitSubscriptions: new Map(),
3929
4703
  workflowControllers: new Map(),
4704
+ workflowChildStops: new Map(),
3930
4705
  };
3931
4706
  }
3932
4707
 
@@ -3969,6 +4744,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
3969
4744
  const delegatedThinkingOverrides = new WeakMap<object, AgentConfig["thinking"]>();
3970
4745
  const delegatedZeroToolBudgets = new WeakSet<object>();
3971
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 }>();
3972
4750
  const warnedArtifactPackageDirs = new Set<string>();
3973
4751
  const scheduledOwnerExecutors = new Map<string, ReturnType<typeof createSubagentExecutor>>();
3974
4752
  const execute = async (
@@ -3978,25 +4756,92 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
3978
4756
  onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
3979
4757
  ctx: ExtensionContext,
3980
4758
  preserveActiveSession = false,
4759
+ parentModelOverride?: ParentModel | null,
3981
4760
  ): Promise<AgentToolResult<Details>> => {
3982
4761
  const workflowLaunchObserver = workflowLaunchObservers.get(params);
3983
4762
  const delegatedThinkingOverride = delegatedThinkingOverrides.get(params);
3984
4763
  const allowZeroToolBudget = delegatedZeroToolBudgets.has(params);
3985
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;
3986
4770
  if (!preserveActiveSession) deps.state.baseCwd = ctx.cwd;
3987
4771
  deps.state.foregroundRuns ??= new Map();
3988
4772
  deps.state.foregroundControls ??= new Map();
3989
4773
  deps.state.lastForegroundControlId ??= null;
3990
4774
  const normalizedGate = normalizeGateParams(params);
3991
4775
  if (!normalizedGate.ok) return buildRequestedModeError(params, normalizedGate.error);
3992
- 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
+ }
3993
4808
  const normalizedAction = typeof requestParams.action === "string" ? requestParams.action.trim() : requestParams.action;
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
+ }
3994
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
+ })();
4831
+ if (requestParams.extensionBindings !== undefined) {
4832
+ try {
4833
+ requestParams.extensionBindings = normalizeExtensionBindings(requestParams.extensionBindings)!.value;
4834
+ } catch (error) {
4835
+ return buildRequestedModeError(requestParams, error instanceof Error ? error.message : String(error));
4836
+ }
4837
+ }
3995
4838
  const parentCwd = ctx.cwd;
3996
4839
  const timeout = requestParams.timeoutMs ?? requestParams.maxRuntimeMs ?? (requestParams.async === false ? resolveConfigDefaultTimeoutMs(deps.config.timeoutMs) ?? DEFAULT_FOREGROUND_TIMEOUT_MS : undefined);
3997
4840
  const workflowUsageBudget = validateUsageBudgetConfig(requestParams.usageBudget ?? deps.config.usageBudget, requestParams.usageBudget ? "usageBudget" : "config.usageBudget");
3998
4841
  if (workflowUsageBudget.error) return buildRequestedModeError(requestParams, workflowUsageBudget.error);
3999
4842
  const workflowCwd = resolveRequestedCwd(parentCwd, requestParams.cwd);
4843
+ const discoverWorkflowAgents = (cwd: string, scope: AgentScope) => deps.discoverAgents(cwd, scope, workflowParentModel?.provider);
4844
+ const workflowAgents = discoverWorkflowAgents(workflowCwd, resolveExecutionAgentScope(requestParams.agentScope)).agents;
4000
4845
  const workflowArtifactConfig: ArtifactConfig = omitUndefinedProperties({
4001
4846
  ...DEFAULT_ARTIFACT_CONFIG,
4002
4847
  enabled: requestParams.artifacts !== false,
@@ -4018,11 +4863,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4018
4863
  const scriptFirstLine = requestParams.workflowScript.split(/\r?\n/).map((line) => line.trim()).find(Boolean) || "Workflow";
4019
4864
  const boundedScriptPreview = scriptFirstLine.length > 100 ? `${scriptFirstLine.slice(0, 97)}...` : scriptFirstLine;
4020
4865
  const derivedObjective = previewAgent ? `Workflow: ${previewAgent}` : boundedScriptPreview;
4021
- const workflowDepth = checkSubagentDepth(deps.config.maxSubagentDepth).depth;
4866
+ const workflowDepth = checkSubagentDepth(deps.config.maxSubagentDepth, deps.childRuntime).depth;
4022
4867
  const asyncWorkflow = requestParams.async !== false;
4023
4868
  const topLevelAsyncWorkflow = asyncWorkflow
4024
4869
  && workflowDepth === 0
4025
- && !resolveInheritedNestedRouteFromEnv()
4870
+ && !inheritedNestedRoute(deps)
4026
4871
  && !requestParams.workflowParentRunId;
4027
4872
  const workflowRunId = asyncWorkflow ? randomUUID() : undefined;
4028
4873
  let workflowCapacity: ActiveAsyncCapacityHandle | undefined;
@@ -4035,7 +4880,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4035
4880
  runId: workflowRunId,
4036
4881
  kind: "workflow",
4037
4882
  asyncDir: path.join(DIRS.async, workflowRunId),
4038
- }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) });
4883
+ }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) });
4039
4884
  } catch (error) {
4040
4885
  if (error instanceof ActiveAsyncCapacityError) {
4041
4886
  deps.state.activeAsyncCapacity = error.snapshot;
@@ -4047,8 +4892,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4047
4892
  let workflowFanoutBudget: RunFanoutBudgetDescriptor;
4048
4893
  try {
4049
4894
  workflowFanoutBudget = requestParams.runFanoutBudget
4050
- ?? decodeRunFanoutBudgetDescriptor(process.env[RUN_FANOUT_BUDGET_ENV])
4051
- ?? createRunFanoutBudget(_id, resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun));
4895
+ ?? inheritedRunFanoutBudget(deps)
4896
+ ?? createRunFanoutBudget(_id, requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun));
4052
4897
  } catch (error) {
4053
4898
  workflowCapacity?.rollback();
4054
4899
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "workflow", results: [] } };
@@ -4093,6 +4938,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4093
4938
  const eventsPath = path.join(asyncDir, "events.jsonl");
4094
4939
  const startedAt = Date.now();
4095
4940
  const currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
4941
+ const workflowCapabilityCeiling = intersectSubagentCapabilityCeilings(requestParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(currentSessionId));
4096
4942
  const completionOwnerId = deps.state.completionOwnerId ?? currentCompletionOwnerId();
4097
4943
  deps.state.completionOwnerId = completionOwnerId;
4098
4944
  try {
@@ -4105,9 +4951,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4105
4951
  }
4106
4952
  const controller = new AbortController();
4107
4953
  deps.state.workflowControllers ??= new Map();
4954
+ deps.state.workflowChildStops ??= new Map();
4108
4955
  deps.state.workflowControllers.set(workflowRunId, controller);
4109
4956
  workflowCapacity?.markWorkflowStarted();
4110
- 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) });
4111
4958
  let status: AsyncStatus = {
4112
4959
  runId: workflowRunId,
4113
4960
  toolCallId,
@@ -4123,7 +4970,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4123
4970
  ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}),
4124
4971
  pid: process.pid,
4125
4972
  steps: [],
4126
- 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 }),
4127
4976
  runFanoutBudget: getRunFanoutBudgetSnapshot(workflowFanoutBudget),
4128
4977
  };
4129
4978
  const appendWorkflowEvent = (event: Record<string, unknown>) => {
@@ -4172,6 +5021,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4172
5021
  if (persistClosed) return;
4173
5022
  const liveJob = deps.state.asyncJobs.get(workflowRunId);
4174
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 });
4175
5026
  status.lastUpdate = Date.now();
4176
5027
  if (!initialPersistenceComplete) {
4177
5028
  writeAtomicJson(statusPath, status);
@@ -4207,6 +5058,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4207
5058
  liveJob.turnCount = status.turnCount;
4208
5059
  liveJob.toolCount = status.toolCount;
4209
5060
  liveJob.currentStep = status.currentStep;
5061
+ liveJob.preflight = status.preflight;
5062
+ liveJob.workflowGraph = status.workflowGraph;
4210
5063
  if (status.steps) {
4211
5064
  liveJob.steps = status.steps.map((step, index) => ({ ...step, index }));
4212
5065
  liveJob.agents = status.steps.map((step) => step.agent);
@@ -4215,6 +5068,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4215
5068
  delete liveJob.agents;
4216
5069
  }
4217
5070
  liveJob.workflow = status.workflow;
5071
+ liveJob.workflowChildren = status.workflowChildren;
4218
5072
  }
4219
5073
  };
4220
5074
  const writeWorkflowResult = (payload: Record<string, unknown>): boolean => {
@@ -4249,7 +5103,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4249
5103
  status.toolCount = toolCounts.length > 0 ? toolCounts.reduce((total, count) => total + count, 0) : undefined;
4250
5104
  status.currentStep = runningSteps.length === 1 ? steps.indexOf(runningSteps[0]!) : undefined;
4251
5105
  };
4252
- 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 };
4253
5107
  deps.state.asyncJobs.set(workflowRunId, workflowJob);
4254
5108
  deps.state.fleetJobs ??= new Map();
4255
5109
  deps.state.fleetJobs.set(workflowRunId, workflowJob);
@@ -4269,18 +5123,37 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4269
5123
  const workflowDeadlineAt = timeout === undefined ? undefined : Date.now() + timeout;
4270
5124
  const workflowResults: SingleResult[] = [];
4271
5125
  const workflowChildRunIds = new Map<string, string>();
4272
- 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;
4273
5127
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
4274
5128
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
4275
- const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId), configuredOutputBaseDir);
5129
+ const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, parentCwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId));
4276
5130
  const claimedOutputPaths = new Map<string, string>();
4277
5131
  const childOutputOverrides = new Map<string, string>();
5132
+ const childOutputClaimPaths = new Map<string, string>();
4278
5133
  const producedChildOutputPaths = new Set<string>();
4279
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;
4280
5146
  let projectedTraceLength = 0;
4281
5147
  let projectedTraceTail: NonNullable<Details["workflow"]>["trace"][number] | undefined;
4282
5148
  const updateTrace = (trace: NonNullable<Details["workflow"]>["trace"]) => {
4283
- 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);
4284
5157
  const rebuild = trace.length < projectedTraceLength
4285
5158
  || (projectedTraceLength > 0 && trace[projectedTraceLength - 1] !== projectedTraceTail);
4286
5159
  if (rebuild) {
@@ -4293,8 +5166,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4293
5166
  for (let index = projectedTraceLength; index < trace.length; index += 1) {
4294
5167
  const entry = trace[index]!;
4295
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);
4296
5172
  const existing = workflowSteps.get(entry.key);
4297
- 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
+ }
4298
5180
  const mapped = entry.state === "started" || entry.state === "reused"
4299
5181
  ? "running"
4300
5182
  : entry.state === "completed"
@@ -4318,13 +5200,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4318
5200
  if (entry.durationMs === undefined) delete existing.durationMs;
4319
5201
  else existing.durationMs = entry.durationMs;
4320
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 });
4321
5207
  const step: NonNullable<AsyncStatus["steps"]>[number] = {
4322
5208
  agent: entry.agent ?? entry.key,
4323
- label: entry.key,
5209
+ ...(stepSessionName ? { sessionName: stepSessionName } : {}),
5210
+ label: entryLabel ?? entry.key,
4324
5211
  workflowKey: entry.key,
4325
5212
  parentWorkflowRunId: workflowRunId,
4326
5213
  status: mapped,
4327
5214
  startedAt: Date.now(),
5215
+ ...(entryPhase ? { phase: entryPhase } : {}),
4328
5216
  ...(entry.runId ? { runId: entry.runId } : {}),
4329
5217
  ...(entry.state === "failed" && !entry.runId ? { async: false } : {}),
4330
5218
  ...(entry.state === "detached" ? { activityState: "needs_attention" as const } : {}),
@@ -4333,6 +5221,23 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4333
5221
  status.steps?.push(step);
4334
5222
  workflowSteps.set(entry.key, step);
4335
5223
  }
5224
+ const projectedStep = workflowSteps.get(entry.key);
5225
+ if (entry.state === "stopped" && projectedStep) {
5226
+ appendWorkflowEvent({
5227
+ type: "subagent.child-status",
5228
+ version: 1,
5229
+ childId: entry.key,
5230
+ status: "stopped",
5231
+ reason: "subagent-action",
5232
+ source: "async",
5233
+ stepIndex: status.steps?.indexOf(projectedStep),
5234
+ agent: projectedStep.agent,
5235
+ ...(projectedStep.runId ? { childRunId: projectedStep.runId } : {}),
5236
+ workflowKey: entry.key,
5237
+ ...(projectedStep.phase ? { phase: projectedStep.phase } : {}),
5238
+ ...(projectedStep.label ? { label: projectedStep.label } : {}),
5239
+ });
5240
+ }
4336
5241
  }
4337
5242
  projectedTraceLength = trace.length;
4338
5243
  projectedTraceTail = trace.at(-1);
@@ -4343,15 +5248,39 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4343
5248
  try {
4344
5249
  const workflow = await runWorkflowScript({
4345
5250
  script: workflowScript,
5251
+ globalConcurrencyLimit: requestParams.globalConcurrencyLimit ?? deps.config.globalConcurrencyLimit,
4346
5252
  timeoutMs: timeout,
4347
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
+ },
5260
+ registerStopChild: (stop) => {
5261
+ if (stop) deps.state.workflowChildStops?.set(workflowRunId, stop);
5262
+ else deps.state.workflowChildStops?.delete(workflowRunId);
5263
+ },
4348
5264
  ...(workflowState ? { state: workflowState } : {}),
4349
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
+ },
4350
5278
  admit: (calls) => {
4351
- const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, 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 });
4352
5280
  if (outputClaims.error) throw new Error(outputClaims.error);
4353
5281
  status.runFanoutBudget = claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
4354
5282
  if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
5283
+ if (outputClaims.childClaims) for (const [key, claimPath] of outputClaims.childClaims) childOutputClaimPaths.set(key, claimPath);
4355
5284
  if (outputClaims.overrides) for (const [key, output] of outputClaims.overrides) childOutputOverrides.set(key, output);
4356
5285
  persist({ tolerateStatusWriteFailure: true });
4357
5286
  },
@@ -4364,7 +5293,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4364
5293
  launch: async (key, childParams, workflowSignal, admission) => {
4365
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);
4366
5295
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
4367
- 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" });
4368
5297
  const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
4369
5298
  const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
4370
5299
  recordMissionWorkflowChild(missionBinding, workflowRunId, key, {
@@ -4374,19 +5303,23 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4374
5303
  ...(childPhase ? { phase: childPhase } : {}),
4375
5304
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
4376
5305
  });
5306
+ let preparedChildParams: SubagentParamsLike | undefined;
4377
5307
  const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, () => {
4378
5308
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
4379
- { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), options: { missionDetached: detachWorkflowChildMissions, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt } }), 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 },
4380
5310
  missionBinding,
4381
5311
  deps.asyncByDefault,
4382
5312
  );
5313
+ preparedChildParams = childRequest;
4383
5314
  workflowLaunchObservers.set(childRequest, (launch) => {
4384
5315
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
4385
5316
  if (step) {
4386
5317
  step.agent = launch.agent;
5318
+ if (launch.sessionName) step.sessionName = launch.sessionName;
4387
5319
  step.sessionFile = launch.sessionFile;
4388
5320
  step.async = launch.async;
4389
5321
  if (launch.runId) step.runId = launch.runId;
5322
+ if (childRequest.lane) step.lane = childRequest.lane;
4390
5323
  persist({ tolerateStatusWriteFailure: true });
4391
5324
  }
4392
5325
  recordMissionWorkflowChild(missionBinding, workflowRunId, key, { status: "running", agent: launch.agent, ...(launch.sessionFile ? { sessionPath: launch.sessionFile } : {}) });
@@ -4408,6 +5341,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4408
5341
  step.toolCount = progress.toolCount;
4409
5342
  step.model = progress.model;
4410
5343
  step.thinking = progress.thinking;
5344
+ if (progress.sessionName) step.sessionName = progress.sessionName;
4411
5345
  step.error = progress.error;
4412
5346
  projectWorkflowActivity();
4413
5347
  persist({ tolerateStatusWriteFailure: true });
@@ -4415,18 +5349,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4415
5349
  status: step.status,
4416
5350
  heartbeat: { status: step.status, ...(childPhase ? { phase: childPhase } : {}) },
4417
5351
  });
4418
- }, ctx, preserveActiveSession);
5352
+ }, ctx, preserveActiveSession, workflowParentModel);
4419
5353
  });
4420
5354
  workflowResults.push(...result.details.results);
4421
5355
  for (const childResult of result.details.results) {
4422
- if (childResult.savedOutputPath) producedChildOutputPaths.add(childResult.savedOutputPath);
5356
+ if (childResult.savedOutputPath) producedChildOutputPaths.add(resolveWorkflowHostOutputClaimPath(childResult.savedOutputPath));
4423
5357
  }
4424
- const child = workflowChildResult(key, result, childParams, deps.state);
5358
+ const child = workflowChildResult(key, result, preparedChildParams ?? childParams, deps.state);
4425
5359
  if (child.runId) workflowChildRunIds.set(key, child.runId);
4426
5360
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
4427
5361
  if (step) {
4428
5362
  step.async = Boolean(result.details.asyncId || result.details.asyncDir);
4429
5363
  if (child.runId) step.runId = child.runId;
5364
+ if (child.lane) step.lane = child.lane;
4430
5365
  }
4431
5366
  if (result.details.asyncDir && missionBinding) writeMissionAsyncBinding(result.details.asyncDir, missionBinding);
4432
5367
  const childStatus = missionWorkflowChildStatus(result);
@@ -4445,26 +5380,30 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4445
5380
  }
4446
5381
  return child;
4447
5382
  },
4448
- 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)),
4449
5384
  resolveResume: (reference) => resolveKeyedWorkflowResume(reference, deps.state),
4450
5385
  steer: (key, message, options, workflowSignal) => steerWorkflowChildByKey({ state: deps.state, workflowRunId, key, message, options, signal: workflowSignal, resolveRunId: () => workflowChildRunIds.get(key) }),
4451
5386
  });
5387
+ const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, workflow.trace, { settled: true });
5388
+ const finalPreflightTrace = annotateWorkflowPreflightTrace(workflow.trace, workflowPreflight);
4452
5389
  const returnPreview = formatWorkflowValue(workflow.value).slice(0, 1_000);
4453
5390
  const emitPreview = workflow.emits.length > 0 ? ` Emitted: ${workflow.emits.map(formatWorkflowValue).join(", ").slice(0, 1_000)}` : "";
4454
- 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(" ")}` : ""}`;
4455
5392
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, summary, producedChildOutputPaths);
4456
5393
  const resultSummary = appendWorkflowOutputWarning(summary, outputWarning);
4457
5394
  const workflowUsage = sumResultsUsage(workflowResults);
4458
- 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) };
4459
- 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);
4460
5398
  let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
4461
5399
  try {
4462
5400
  workflowReceipt = { path: writeWorkflowReceipt(asyncDir, receipt), receipt };
4463
5401
  } catch (receiptError) {
4464
5402
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
4465
5403
  }
4466
- 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.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;
4467
5405
  persist();
5406
+ deps.refreshResultDelivery?.();
4468
5407
  persistClosed = true;
4469
5408
  appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(status.error ? { error: status.error } : {}) });
4470
5409
  } catch (error) {
@@ -4485,70 +5424,104 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4485
5424
  delete step.activityState;
4486
5425
  }
4487
5426
  }
4488
- 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 });
4489
5432
  if (pauseForDetached) {
4490
5433
  const promoted = promotePausedWorkflowIfSettled(status);
4491
5434
  if (promoted) status = promoted;
4492
5435
  }
4493
- const terminalSummary = status.state === "complete"
5436
+ const terminalSummary = `${status.state === "complete"
4494
5437
  ? "Workflow completed after detached child finished."
4495
- : status.error ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.");
5438
+ : status.error ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.")}${workflowOutputPathMappingSummary(partial.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
4496
5439
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, terminalSummary, producedChildOutputPaths);
4497
5440
  const resultSummary = appendWorkflowOutputWarning(terminalSummary, outputWarning);
4498
5441
  const receiptState: WorkflowReceiptState = status.state === "complete" ? "complete" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "failed";
4499
- 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);
4500
5444
  let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
4501
5445
  try {
4502
5446
  workflowReceipt = { path: writeWorkflowReceipt(asyncDir, receipt), receipt };
4503
5447
  } catch (receiptError) {
4504
5448
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
4505
5449
  }
4506
- 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.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;
4507
5451
  persist();
5452
+ deps.refreshResultDelivery?.();
4508
5453
  persistClosed = true;
4509
- 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 } : {}) });
4510
5455
  } finally {
4511
5456
  persistClosed = true;
4512
5457
  deps.state.workflowControllers?.delete(workflowRunId);
5458
+ deps.state.workflowChildStops?.delete(workflowRunId);
4513
5459
  deps.state.activeAsyncCapacity = workflowCapacity?.reconcile(new Set(deps.state.workflowControllers?.keys() ?? []))
4514
5460
  ?? deps.state.activeAsyncCapacity;
4515
5461
  }
4516
5462
  });
4517
5463
  return attachWorkflowMission(withRunFanoutBudget({
4518
- content: [{ type: "text", text: formatAsyncStartedMessage(`Async workflow [${workflowRunId}]`, ctx.hasUI === true) }],
4519
- 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 } : {}) },
4520
5466
  }, workflowFanoutBudget));
4521
5467
  }
4522
- 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;
4523
5469
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
4524
5470
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
4525
- const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, _id), configuredOutputBaseDir);
5471
+ const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, _id));
4526
5472
  const claimedOutputPaths = new Map<string, string>();
4527
5473
  const childOutputOverrides = new Map<string, string>();
5474
+ const childOutputClaimPaths = new Map<string, string>();
4528
5475
  const producedChildOutputPaths = new Set<string>();
4529
5476
  const workflowResults: SingleResult[] = [];
4530
5477
  const workflowChildRunIds = new Map<string, string>();
4531
- 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 });
4532
5494
  const workflowDeadlineAt = timeout === undefined ? undefined : Date.now() + timeout;
5495
+ const workflowCapabilityCeiling = intersectSubagentCapabilityCeilings(requestParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(resolveCurrentSessionId(ctx.sessionManager)));
4533
5496
  const sendWorkflowProgress = () => {
4534
- const update = workflowChatProgressUpdate(_id, chatProgress, liveWorkflow);
5497
+ const update = workflowChatProgressUpdate(_id, chatProgress, liveWorkflow, liveWorkflowChildren, workflowPreflight);
4535
5498
  if (update) onUpdate?.(update);
4536
5499
  };
4537
5500
  try {
4538
5501
  const workflow = await runWorkflowScript({
4539
5502
  script: requestParams.workflowScript,
5503
+ ...(delegatedWorkflowPermit ? { oneUsePermit: { claim: (key: string) => claimWorkflowChildPermit(delegatedWorkflowPermit, _id, key) } } : {}),
5504
+ globalConcurrencyLimit: requestParams.globalConcurrencyLimit ?? deps.config.globalConcurrencyLimit,
4540
5505
  timeoutMs: timeout,
4541
5506
  signal,
4542
5507
  ...(workflowState ? { state: workflowState } : {}),
5508
+ ...(workflowHost ? { host: workflowHost } : {}),
5509
+ onHostStep: (hostStep) => {
5510
+ workflowHostSteps.set(hostStep.id, { ...hostStep, ...(hostStep.freshness ? { freshness: { ...hostStep.freshness } } : {}) });
5511
+ },
4543
5512
  onTrace: (trace) => {
4544
- 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 });
4545
5517
  sendWorkflowProgress();
4546
5518
  },
4547
5519
  admit: (calls) => {
4548
- const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId: _id, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, 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 });
4549
5521
  if (outputClaims.error) throw new Error(outputClaims.error);
4550
5522
  claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
4551
5523
  if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
5524
+ if (outputClaims.childClaims) for (const [key, claimPath] of outputClaims.childClaims) childOutputClaimPaths.set(key, claimPath);
4552
5525
  if (outputClaims.overrides) for (const [key, output] of outputClaims.overrides) childOutputOverrides.set(key, output);
4553
5526
  },
4554
5527
  onEmit: (emits) => {
@@ -4556,9 +5529,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4556
5529
  sendWorkflowProgress();
4557
5530
  },
4558
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.");
4559
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);
4560
5536
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
4561
- 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" });
4562
5538
  const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
4563
5539
  const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
4564
5540
  recordMissionWorkflowChild(missionBinding, _id, key, {
@@ -4568,12 +5544,23 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4568
5544
  ...(childPhase ? { phase: childPhase } : {}),
4569
5545
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
4570
5546
  });
5547
+ let preparedChildParams: SubagentParamsLike | undefined;
4571
5548
  const result = await runMissionWorkflowChild(missionBinding, _id, key, childPhase, () => {
4572
5549
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
4573
- { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: _id, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt } }), 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 },
4574
5551
  missionBinding,
4575
5552
  deps.asyncByDefault,
4576
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
+ }
4577
5564
  workflowLaunchObservers.set(childRequest, (launch) => recordMissionWorkflowChild(missionBinding, _id, key, {
4578
5565
  status: "running",
4579
5566
  agent: launch.agent,
@@ -4587,14 +5574,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4587
5574
  status: progressStatus,
4588
5575
  heartbeat: { status: progressStatus, ...(childPhase ? { phase: childPhase } : {}) },
4589
5576
  });
4590
- }, ctx, preserveActiveSession);
5577
+ }, ctx, preserveActiveSession, workflowParentModel);
4591
5578
  });
4592
5579
  workflowResults.push(...result.details.results);
4593
5580
  for (const childResult of result.details.results) {
4594
- if (childResult.savedOutputPath) producedChildOutputPaths.add(childResult.savedOutputPath);
5581
+ if (childResult.savedOutputPath) producedChildOutputPaths.add(resolveWorkflowHostOutputClaimPath(childResult.savedOutputPath));
4595
5582
  }
4596
5583
  if (result.details.asyncDir && missionBinding) writeMissionAsyncBinding(result.details.asyncDir, missionBinding);
4597
- const child = workflowChildResult(key, result, childParams, deps.state);
5584
+ const child = workflowChildResult(key, result, preparedChildParams ?? childParams, deps.state);
4598
5585
  if (child.runId) workflowChildRunIds.set(key, child.runId);
4599
5586
  const childStatus = missionWorkflowChildStatus(result);
4600
5587
  recordMissionWorkflowChild(missionBinding, _id, key, {
@@ -4608,43 +5595,64 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4608
5595
  });
4609
5596
  return child;
4610
5597
  },
4611
- 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)),
4612
5599
  resolveResume: (reference) => resolveKeyedWorkflowResume(reference, deps.state),
4613
5600
  steer: (key, message, options, workflowSignal) => steerWorkflowChildByKey({ state: deps.state, workflowRunId: _id, key, message, options, signal: workflowSignal, resolveRunId: () => workflowChildRunIds.get(key) }),
4614
5601
  });
4615
- const receipt = terminalWorkflowReceipt(_id, "complete", workflow.children);
4616
- 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}` : ""}`);
4617
- 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
+ ];
4618
5612
  if (workflow.emits.length > 0) sections.push(`Emitted:\n${workflow.emits.map(formatWorkflowValue).join("\n")}`);
4619
5613
  if (workflow.console.length > 0) sections.push(`Console:\n${workflow.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
4620
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);
4621
5618
  const workflowText = sections.join("\n\n");
4622
5619
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText, producedChildOutputPaths);
4623
5620
  const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
4624
5621
  return attachWorkflowMission(withRunFanoutBudget({
4625
5622
  content: [{ type: "text", text: displayText }],
4626
- 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 }),
4627
5624
  }, workflowFanoutBudget));
4628
5625
  } catch (error) {
4629
5626
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
4630
- const text = error instanceof Error ? error.message : String(error);
4631
- const traceLines = partial.trace.map((entry) => `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.error ? ` — ${entry.error}` : ""}`);
4632
- 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
+ ];
4633
5635
  if (partial.emits.length > 0) sections.push(`Emitted:\n${partial.emits.map(formatWorkflowValue).join("\n")}`);
4634
5636
  if (partial.console.length > 0) sections.push(`Console:\n${partial.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
4635
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);
4636
5641
  const workflowText = sections.join("\n\n");
4637
5642
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText, producedChildOutputPaths);
4638
5643
  const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
4639
- 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);
4640
5647
  return attachWorkflowMission(withRunFanoutBudget({
4641
5648
  content: [{ type: "text", text: displayText }],
4642
5649
  isError: true,
4643
- 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 }),
4644
5651
  }, workflowFanoutBudget));
4645
5652
  }
4646
5653
  }
4647
5654
  const directParams = requestParams;
5655
+ const requestedCwd = directParams.cwd;
4648
5656
  const requestCwd = resolveRequestedCwd(ctx.cwd, directParams.cwd);
4649
5657
  const paramsWithResolvedCwd = directParams.cwd === undefined ? directParams : { ...directParams, cwd: requestCwd };
4650
5658
  const action = paramsWithResolvedCwd.action;
@@ -4654,14 +5662,45 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4654
5662
  try {
4655
5663
  requestSessionId = resolveCurrentSessionId(ctx.sessionManager);
4656
5664
  requestPiSessionId = ctx.sessionManager.getSessionId() ?? undefined;
4657
- requestParentModel = preserveActiveSession
4658
- ? normalizeParentModel(ctx.model)
4659
- : 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);
4660
5670
  } catch (error) {
4661
5671
  if (action?.toLowerCase() !== "doctor" && action?.toLowerCase() !== "guide") throw error;
4662
5672
  requestParentModel = normalizeParentModel(ctx.model);
4663
5673
  }
4664
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
+ }
4665
5704
  if (action === "worktree.discard") {
4666
5705
  if (deps.allowMutatingManagementActions === false) {
4667
5706
  return { content: [{ type: "text", text: "Action 'worktree.discard' is not available from child-safe subagent fanout mode." }], isError: true, details: { mode: "management", results: [] } };
@@ -4689,11 +5728,36 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4689
5728
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
4690
5729
  }
4691
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
+ }
4692
5755
  if ((HERDR_PROJECT_PANE_ACTIONS as readonly string[]).includes(action)) {
4693
5756
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
4694
5757
  return { content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }], isError: true, details: { mode: "management", results: [] } };
4695
5758
  }
4696
- return handleHerdrProjectPaneAction(action as (typeof HERDR_PROJECT_PANE_ACTIONS)[number], paramsWithResolvedCwd, { cwd: requestCwd, signal });
5759
+ deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
5760
+ return handleHerdrProjectPaneAction(action as (typeof HERDR_PROJECT_PANE_ACTIONS)[number], paramsWithResolvedCwd, { cwd: requestCwd, state: deps.state, signal });
4697
5761
  }
4698
5762
  if ((HERDR_INSPECTOR_ACTIONS as readonly string[]).includes(action)) {
4699
5763
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
@@ -4880,7 +5944,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4880
5944
  }
4881
5945
  const spawnBudget = getSpawnBudgetSnapshot(deps.state, deps.config, currentSessionId);
4882
5946
  const activeAsyncCapacity = currentSessionId
4883
- ? 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) })
4884
5948
  : { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession) ?? 0 };
4885
5949
  deps.state.activeAsyncCapacity = activeAsyncCapacity;
4886
5950
  return {
@@ -4925,10 +5989,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4925
5989
  if (paramsWithResolvedCwd.view) {
4926
5990
  return withBudget({ content: [{ type: "text", text: "action='debug.run' does not support status views." }], isError: true, details: { mode: "management", results: [] } });
4927
5991
  }
4928
- 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) })));
4929
5993
  }
4930
5994
  if (paramsWithResolvedCwd.view === "fleet") {
4931
- 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) })));
4932
5996
  }
4933
5997
  if (targetRunId) {
4934
5998
  try {
@@ -4959,12 +6023,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4959
6023
  });
4960
6024
  }
4961
6025
  }
4962
- 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) })));
4963
6027
  }
4964
6028
  if (action === "resume") {
4965
6029
  return resumeAsyncRun(omitUndefinedProperties({ params: paramsWithResolvedCwd, requestCwd, ctx, deps, parentModel: requestParentModel, signal }));
4966
6030
  }
4967
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
+ }
4968
6035
  deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
4969
6036
  const message = (paramsWithResolvedCwd.message ?? paramsWithResolvedCwd.task ?? "").trim();
4970
6037
  if (!message) return { content: [{ type: "text", text: "action='steer' requires message." }], isError: true, details: { mode: "management", results: [] } };
@@ -4977,7 +6044,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4977
6044
  if (directoryStatus?.mode === "workflow") {
4978
6045
  const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, workflowRunId: directoryStatus.runId || runId, asyncDirRoot: DIRS.async });
4979
6046
  if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
4980
- 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 });
4981
6048
  }
4982
6049
  if (location.asyncDir) {
4983
6050
  const unsupported = externalRunnerControlError(location.asyncDir, "steer");
@@ -4987,7 +6054,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4987
6054
  state: deps.state,
4988
6055
  runId,
4989
6056
  message,
4990
- mode: paramsWithResolvedCwd.mode,
6057
+ mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode),
4991
6058
  index: paramsWithResolvedCwd.index,
4992
6059
  kill: deps.kill,
4993
6060
  location,
@@ -5013,18 +6080,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5013
6080
  const text = error instanceof Error ? error.message : String(error);
5014
6081
  return { content: [{ type: "text", text }], isError: true, details: { mode: "management", results: [] } };
5015
6082
  }
5016
- 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 }));
5017
6084
  if (resolved?.kind === "foreground") {
5018
6085
  const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, childRunId: resolved.id, asyncDirRoot: DIRS.async });
5019
6086
  if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
5020
- 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 });
5021
6088
  }
5022
6089
  if (resolved?.kind !== "async") return { content: [{ type: "text", text: `No async run found for '${targetRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
5023
6090
  const resolvedStatus = resolved.location.asyncDir ? readStatus(resolved.location.asyncDir) : null;
5024
6091
  if (resolvedStatus?.mode === "workflow") {
5025
6092
  const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, workflowRunId: resolvedStatus.runId || resolved.id, asyncDirRoot: DIRS.async });
5026
6093
  if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
5027
- 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 });
5028
6095
  }
5029
6096
  if (resolved.location.asyncDir) {
5030
6097
  const unsupported = externalRunnerControlError(resolved.location.asyncDir, "steer");
@@ -5034,7 +6101,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5034
6101
  state: deps.state,
5035
6102
  runId: resolved.id,
5036
6103
  message,
5037
- mode: paramsWithResolvedCwd.mode,
6104
+ mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode),
5038
6105
  index: paramsWithResolvedCwd.index,
5039
6106
  kill: deps.kill,
5040
6107
  location: resolved.location,
@@ -5103,19 +6170,52 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5103
6170
  if (action === "stop") {
5104
6171
  const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
5105
6172
  const workflowController = targetRunId ? deps.state.workflowControllers?.get(targetRunId) : undefined;
5106
- if (workflowController) {
5107
- workflowController.abort(new Error("Workflow stopped by user."));
6173
+ if (workflowController && targetRunId) {
6174
+ const stopChild = deps.state.workflowChildStops?.get(targetRunId);
6175
+ if (paramsWithResolvedCwd.childId !== undefined) {
6176
+ const workflowRunId = targetRunId;
6177
+ const asyncJob = deps.state.asyncJobs.get(workflowRunId);
6178
+ if (!asyncJob?.asyncDir) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
6179
+ const status = readStatus(asyncJob.asyncDir);
6180
+ if (!status) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
6181
+ const resolution = resolveAsyncStatusChild(status, paramsWithResolvedCwd.childId);
6182
+ if (!resolution.ok) return { content: [{ type: "text", text: resolution.message }], isError: true, details: { mode: "management", results: [] } };
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: [] } };
6184
+ if (!stopChild) return { content: [{ type: "text", text: `Workflow ${targetRunId} child stop is unavailable in this extension runtime.` }], 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: [] } };
6186
+ try {
6187
+ fs.appendFileSync(path.join(asyncJob.asyncDir, "events.jsonl"), `${JSON.stringify({
6188
+ type: "subagent.child-status",
6189
+ version: 1,
6190
+ runId: workflowRunId,
6191
+ childId: resolution.child.id,
6192
+ status: "stopping",
6193
+ ts: Date.now(),
6194
+ reason: "subagent-action",
6195
+ source: "async",
6196
+ stepIndex: resolution.child.index,
6197
+ agent: resolution.child.step.agent,
6198
+ ...(resolution.child.step.runId ? { childRunId: resolution.child.step.runId } : {}),
6199
+ ...(resolution.child.step.workflowKey ? { workflowKey: resolution.child.step.workflowKey } : {}),
6200
+ ...(resolution.child.step.phase ? { phase: resolution.child.step.phase } : {}),
6201
+ ...(resolution.child.step.label ? { label: resolution.child.step.label } : {}),
6202
+ } satisfies SubagentChildStatusEvent)}\n`, "utf-8");
6203
+ } catch (error) {
6204
+ console.error(`Failed to append child status event for workflow ${workflowRunId}:`, error);
6205
+ }
6206
+ return { content: [{ type: "text", text: `Stop requested for child ${resolution.child.id} in async workflow ${workflowRunId}.` }], details: { mode: "management", results: [] } };
6207
+ }
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."));
5108
6212
  return { content: [{ type: "text", text: `Stop requested for async workflow ${targetRunId}.` }], details: { mode: "management", results: [] } };
5109
6213
  }
5110
6214
  let resolved: ResolvedSubagentRunId | undefined;
5111
6215
  if (paramsWithResolvedCwd.dir) {
5112
6216
  try {
5113
6217
  const location = resolveAsyncRunLocation(paramsWithResolvedCwd, DIRS.async, DIRS.results);
5114
- const existingStatus = readStatus(location.asyncDir ?? "");
5115
- if (existingStatus?.mode === "workflow" && existingStatus.state === "running") {
5116
- 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: [] } };
5117
- }
5118
- const stopResult = stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location);
6218
+ const stopResult = stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location, paramsWithResolvedCwd.childId);
5119
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: [] } };
5120
6220
  } catch (error) {
5121
6221
  const text = error instanceof Error ? error.message : String(error);
@@ -5131,17 +6231,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5131
6231
  }
5132
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: [] } };
5133
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: [] } };
5134
- if (resolved?.kind === "async") {
5135
- const existingStatus = readStatus(resolved.location.asyncDir ?? "");
5136
- if (existingStatus?.mode === "workflow" && existingStatus.state === "running") {
5137
- 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: [] } };
5138
- }
5139
- }
5140
6234
  const stopResult = stopAsyncRun(
5141
6235
  deps.state,
5142
6236
  resolved?.kind === "async" ? resolved.id : targetRunId,
5143
6237
  deps.kill,
5144
6238
  resolved?.kind === "async" ? resolved.location : undefined,
6239
+ paramsWithResolvedCwd.childId,
5145
6240
  );
5146
6241
  if (stopResult) return stopResult;
5147
6242
  return {
@@ -5208,7 +6303,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5208
6303
  });
5209
6304
  }
5210
6305
 
5211
- const { blocked, depth, maxDepth } = checkSubagentDepth(deps.config.maxSubagentDepth);
6306
+ const { blocked, depth, maxDepth } = checkSubagentDepth(deps.config.maxSubagentDepth, deps.childRuntime);
5212
6307
  if (blocked) {
5213
6308
  return {
5214
6309
  content: [
@@ -5248,15 +6343,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5248
6343
  const scope: AgentScope = resolveExecutionAgentScope(effectiveParams.agentScope);
5249
6344
  const effectiveCwd = effectiveParams.cwd ?? ctx.cwd;
5250
6345
  const parentSessionFile = ctx.sessionManager.getSessionFile() ?? null;
5251
- const discovered = deps.discoverAgents(effectiveCwd, scope);
6346
+ const discovered = deps.discoverAgents(effectiveCwd, scope, requestParentModel?.provider);
5252
6347
  const discoveredAgents = discovered.agents;
5253
- const canonicalParams = canonicalizeExecutionParams(effectiveParams, discoveredAgents, discovered.agentDiagnostics);
6348
+ const unknownAgentDiagnosticContext = diagnosticContextFromDiscovery(discovered, effectiveCwd, scope);
6349
+ const canonicalParams = canonicalizeExecutionParams(effectiveParams, discoveredAgents, discovered.agentDiagnostics, unknownAgentDiagnosticContext);
5254
6350
  if (canonicalParams.error) return buildRequestedModeError(effectiveParams, canonicalParams.error);
5255
6351
  effectiveParams = canonicalParams.params!;
6352
+ if (effectiveParams.worktree === undefined && deps.config.worktree !== undefined) {
6353
+ effectiveParams = { ...effectiveParams, worktree: deps.config.worktree };
6354
+ }
5256
6355
  const modelScope = discovered.modelScope;
5257
6356
  effectiveParams = applySingleAgentLaunchDefaults(effectiveParams, discoveredAgents);
5258
- const turnBudget = resolveTurnBudgetConfig(effectiveParams.turnBudget ?? deps.config.turnBudget);
5259
- if (turnBudget.error) return buildRequestedModeError(effectiveParams, turnBudget.error);
5260
6357
  // An agent-level defaultContext is a preference, unlike an explicit request.
5261
6358
  // Prefer fork only when the parent session is persisted and has a current leaf;
5262
6359
  // otherwise use fresh immediately instead of launching a guaranteed-to-fail fork.
@@ -5281,8 +6378,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5281
6378
  });
5282
6379
  const agents = applyScopedIntercomBridgeToAgents(discoveredAgents, intercomBridge, contextPolicy);
5283
6380
  const runId = randomUUID();
5284
- const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
5285
- const nestedParentAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
6381
+ const inheritedNestedRouteValue = inheritedNestedRoute(deps);
6382
+ const nestedParentAddress = inheritedNestedRouteValue ? inheritedNestedParentAddress(deps) : undefined;
5286
6383
  const shareEnabled = effectiveParams.share === true;
5287
6384
  const hasChain = (effectiveParams.chain?.length ?? 0) > 0;
5288
6385
  const hasTasks = (effectiveParams.tasks?.length ?? 0) > 0;
@@ -5299,6 +6396,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5299
6396
  hasTasks,
5300
6397
  hasSingle,
5301
6398
  allowClarifyTaskPrompt,
6399
+ unknownAgentDiagnosticContext,
5302
6400
  );
5303
6401
  if (validationError) return validationError;
5304
6402
 
@@ -5313,34 +6411,49 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5313
6411
  if (spawnPreflight.error) return spawnBudgetErrorResult(spawnPreflight.error, foregroundMode);
5314
6412
 
5315
6413
  let forkSessionFileForIndex: (idx?: number) => string | undefined = () => undefined;
6414
+ let prepareForkSessionForIndex: (idx?: number) => Promise<void> = async () => {};
5316
6415
  let forkThinkingOverrideForIndex: (idx?: number) => AgentConfig["thinking"] | undefined = () => undefined;
5317
- 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 => {};
5318
6417
  const forkThinkingRequirements = new Map<number, boolean>();
5319
6418
  const forkThinkingDowngrades = new Map<number, string>();
5320
6419
  try {
5321
6420
  const forkAvailableModels = contextPolicy.usesFork ? ctx.modelRegistry.getAvailable().map(toModelInfo) : [];
5322
6421
  const parentModel = requestParentModel;
5323
- prepareForkThinking = (agentName, index, modelOverride, modelOverrideFromParent) => {
6422
+ prepareForkThinking = (agentName, index, modelOverride, modelOverrideFromParent, storedOrigin) => {
5324
6423
  const agentConfig = agents.find((agent) => agent.name === agentName);
5325
6424
  if (agentConfig?.runner?.type === "external-cli" || agentConfig?.runner?.type === "external-job") {
5326
6425
  forkThinkingRequirements.set(index, true);
5327
6426
  return;
5328
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
+ });
5329
6438
  const primaryModel = modelOverrideFromParent
5330
6439
  ? modelOverride
5331
6440
  : resolveEffectiveSubagentModel(
5332
- modelOverride,
6441
+ effectiveStoredOrigin === "configured" ? undefined : modelOverride,
5333
6442
  agentConfig?.model,
5334
6443
  parentModel,
5335
6444
  forkAvailableModels,
5336
- parentModel?.provider,
6445
+ agentConfig?.modelProvider ?? parentModel?.provider,
6446
+ { source: origin === "explicit" ? "explicit" : "inherited" },
5337
6447
  );
5338
6448
  const candidates = buildModelCandidates(
5339
6449
  primaryModel,
5340
6450
  agentConfig?.fallbackModels,
5341
6451
  forkAvailableModels,
5342
- parentModel?.provider,
5343
- { primaryModelFromParent: modelOverrideFromParent ?? inheritsParentModel(modelOverride, agentConfig?.model, parentModel) },
6452
+ agentConfig?.modelProvider ?? parentModel?.provider,
6453
+ {
6454
+ primaryModelFromParent: origin === "inherited",
6455
+ origin,
6456
+ },
5344
6457
  );
5345
6458
  forkThinkingRequirements.set(
5346
6459
  index,
@@ -5348,17 +6461,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5348
6461
  || candidates.some((candidate) => forkedChildRequiresThinkingOff(candidate, forkAvailableModels, parentModel?.provider)),
5349
6462
  );
5350
6463
  };
6464
+ const pruneSession = contextPolicy.usesFork && deps.config.forkContext?.mode === "pruned"
6465
+ ? await createPrunedForkSessionWriter(ctx, deps.config.forkContext, signal)
6466
+ : undefined;
5351
6467
  const forkContextResolver = createForkContextResolver(ctx.sessionManager, contextPolicy.usesFork ? "fork" : undefined, {
5352
6468
  forceThinkingOffForIndex: (index) => forkThinkingRequirements.get(index) ?? true,
6469
+ ...(pruneSession ? { pruneSession } : {}),
5353
6470
  });
6471
+ prepareForkSessionForIndex = forkContextResolver.prepareSessionForIndex;
5354
6472
  forkSessionFileForIndex = forkContextResolver.sessionFileForIndex;
5355
6473
  forkThinkingOverrideForIndex = forkContextResolver.thinkingOverrideForIndex;
5356
6474
  } catch (error) {
5357
6475
  return toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);
5358
6476
  }
5359
- const requestedAsync = effectiveParams.async ?? deps.asyncByDefault;
5360
- const backgroundRequestedWhileClarifying = (hasChain || hasTasks) && requestedAsync && effectiveParams.clarify === true;
5361
- const effectiveAsync = requestedAsync && effectiveParams.clarify !== true;
5362
6477
  const selectedAgentNames = hasSingle
5363
6478
  ? [effectiveParams.agent!]
5364
6479
  : hasTasks
@@ -5367,6 +6482,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5367
6482
  const externalAgent = selectedAgentNames
5368
6483
  .map((name) => agents.find((agent) => agent.name === name))
5369
6484
  .find((agent) => agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job");
6485
+ const externalAsyncRequired = Boolean(externalAgent) && effectiveParams.async === undefined && effectiveParams.clarify !== true && effectiveParams.foregroundOnly !== true;
6486
+ const requestedAsync = externalAsyncRequired ? true : effectiveParams.async ?? deps.asyncByDefault;
6487
+ const backgroundRequestedWhileClarifying = (hasChain || hasTasks) && requestedAsync && effectiveParams.clarify === true;
6488
+ const effectiveAsync = requestedAsync && effectiveParams.clarify !== true;
5370
6489
  if (externalAgent && (!effectiveAsync || effectiveParams.foregroundOnly === true)) {
5371
6490
  return buildRequestedModeError(effectiveParams, `Agent '${externalAgent.name}' uses runner.type='${externalAgent.runner?.type}', which currently supports async/background execution only. Omit async or pass async:true; clarify and foregroundOnly are unsupported.`);
5372
6491
  }
@@ -5381,7 +6500,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5381
6500
  const asyncRunId = requestedWorkflowChildAsyncId && path.basename(requestedWorkflowChildAsyncId) === requestedWorkflowChildAsyncId
5382
6501
  ? requestedWorkflowChildAsyncId
5383
6502
  : randomUUID();
5384
- const topLevelAsyncCapacityEligible = depth === 0 && !inheritedNestedRoute && !effectiveParams.workflowParentRunId;
6503
+ const topLevelAsyncCapacityEligible = depth === 0 && !inheritedNestedRouteValue && !effectiveParams.workflowParentRunId;
5385
6504
  const topLevelAsync = effectiveAsync && topLevelAsyncCapacityEligible;
5386
6505
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
5387
6506
  if (topLevelAsync) {
@@ -5393,8 +6512,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5393
6512
  runId: asyncRunId,
5394
6513
  kind: "runner",
5395
6514
  asyncDir: path.join(DIRS.async, asyncRunId),
5396
- }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) });
5397
- 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) });
5398
6517
  } catch (error) {
5399
6518
  if (error instanceof ActiveAsyncCapacityError) {
5400
6519
  deps.state.activeAsyncCapacity = error.snapshot;
@@ -5406,9 +6525,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5406
6525
 
5407
6526
  let runFanoutBudget: RunFanoutBudgetDescriptor;
5408
6527
  try {
5409
- const inheritedRunFanoutBudget = effectiveParams.runFanoutBudget ? undefined : decodeRunFanoutBudgetDescriptor(process.env[RUN_FANOUT_BUDGET_ENV]);
6528
+ const inheritedRunFanoutBudgetValue = effectiveParams.runFanoutBudget ? undefined : inheritedRunFanoutBudget(deps);
5410
6529
  runFanoutBudget = effectiveParams.runFanoutBudget
5411
- ?? (inheritedRunFanoutBudget ? { ...inheritedRunFanoutBudget, parentPath: `${inheritedRunFanoutBudget.parentPath ? `${inheritedRunFanoutBudget.parentPath}/` : ""}${runId}` } : undefined)
6530
+ ?? (inheritedRunFanoutBudgetValue ? { ...inheritedRunFanoutBudgetValue, parentPath: `${inheritedRunFanoutBudgetValue.parentPath ? `${inheritedRunFanoutBudgetValue.parentPath}/` : ""}${runId}` } : undefined)
5412
6531
  ?? createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun));
5413
6532
  if (!effectiveParams.runFanoutAdmitted) claimRunFanoutBatch(runFanoutBudget, staticRunFanoutPaths(effectiveParams));
5414
6533
  } catch (error) {
@@ -5416,7 +6535,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5416
6535
  if (error instanceof RunFanoutLimitError) return runFanoutErrorResult(error, foregroundMode);
5417
6536
  return buildRequestedModeError(effectiveParams, error instanceof Error ? error.message : String(error));
5418
6537
  }
5419
- const nestedRoute = inheritedNestedRoute ?? createNestedRoute(runId);
6538
+ const nestedRoute = inheritedNestedRouteValue ?? createNestedRoute(runId);
5420
6539
 
5421
6540
  const artifactConfig: ArtifactConfig = omitUndefinedProperties({
5422
6541
  ...DEFAULT_ARTIFACT_CONFIG,
@@ -5452,25 +6571,30 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5452
6571
  }
5453
6572
  const sessionDirForIndex = (idx?: number) =>
5454
6573
  path.join(sessionRoot, `run-${idx ?? 0}`);
5455
- const forkSessionFileForTask: ForkSessionFileForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent) => {
6574
+ const forkSessionFileForTask: ForkSessionFileForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent, modelOrigin) => {
5456
6575
  if (!shouldForkAgent(contextPolicy, agentName)) return undefined;
5457
- prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent);
6576
+ prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin);
5458
6577
  return forkSessionFileForIndex(idx);
5459
6578
  };
5460
- 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) => {
5461
6585
  if (!shouldForkAgent(contextPolicy, agentName)) return delegatedThinkingOverride;
5462
- prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent);
6586
+ prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin);
5463
6587
  const override = forkThinkingOverrideForIndex(idx);
5464
6588
  if (override === "off") forkThinkingDowngrades.set(idx, agentName);
5465
6589
  return override ?? delegatedThinkingOverride;
5466
6590
  };
5467
- const childSessionFileForTask: ForkSessionFileForTask = (agentName, idx, modelOverride, modelOverrideFromParent) =>
5468
- 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");
5469
6593
  const childSessionFileForIndex = (idx?: number) =>
5470
6594
  path.join(sessionDirForIndex(idx), "session.jsonl");
5471
6595
  try {
5472
- if (!(effectiveParams.clarify === true && ctx.hasUI)) {
5473
- 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);
5474
6598
  }
5475
6599
  } catch (error) {
5476
6600
  activeAsyncCapacity?.rollback();
@@ -5539,10 +6663,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5539
6663
  const execData: ExecutionContextData = omitUndefinedProperties({
5540
6664
  params: effectiveParams,
5541
6665
  effectiveCwd,
6666
+ requestedCwd,
5542
6667
  ctx,
5543
6668
  signal,
5544
6669
  onUpdate: onUpdateWithContext,
5545
6670
  agents,
6671
+ unknownAgentDiagnosticContext,
5546
6672
  recoveryAgents: discoveredAgents,
5547
6673
  runId,
5548
6674
  shareEnabled,
@@ -5557,10 +6683,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5557
6683
  effectiveAsync,
5558
6684
  asyncRunId,
5559
6685
  controlConfig,
6686
+ ...(delegatedExecution ? { suppressUnchangedDelegationUpdates: true } : {}),
5560
6687
  intercomBridge,
5561
6688
  nestedRoute,
5562
6689
  timeoutMs: foregroundTimeout.timeoutMs,
5563
- turnBudget: turnBudget.turnBudget,
5564
6690
  toolBudget: runToolBudget.toolBudget,
5565
6691
  usageBudget: usageBudget.budget,
5566
6692
  allowZeroToolBudget,
@@ -5571,26 +6697,16 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5571
6697
  parentModel: requestParentModel,
5572
6698
  parentSessionId: requestSessionId,
5573
6699
  parentPiSessionId: requestPiSessionId,
5574
- capabilityCeiling: resolveCurrentSubagentCapabilityCeiling(requestSessionId),
6700
+ capabilityCeiling: intersectSubagentCapabilityCeilings(effectiveParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(requestSessionId)),
5575
6701
  runFanoutBudget,
5576
6702
  topLevelAsyncCapacityEligible,
5577
6703
  activeAsyncCapacity,
6704
+ workflowChildPermitLaunch,
5578
6705
  });
5579
6706
 
5580
6707
  const foregroundDescription = selectedAgentNames.length === 1
5581
6708
  ? `${selectedAgentNames[0]} child`
5582
6709
  : `${selectedAgentNames.length} live children`;
5583
- const parentWorkflowStatus = effectiveParams.workflowParentRunId
5584
- ? readStatus(path.join(DIRS.async, effectiveParams.workflowParentRunId))
5585
- : null;
5586
- const workflowSteeringDir = effectiveParams.workflowParentRunId
5587
- && requestSessionId
5588
- && deps.state.workflowControllers?.has(effectiveParams.workflowParentRunId)
5589
- && parentWorkflowStatus?.mode === "workflow"
5590
- && (parentWorkflowStatus.state === "running" || parentWorkflowStatus.state === "queued")
5591
- && parentWorkflowStatus.sessionId === requestSessionId
5592
- ? workflowForegroundSteeringDir(DIRS.async, effectiveParams.workflowParentRunId, runId)
5593
- : undefined;
5594
6710
  const foregroundControl: ForegroundRunControl | undefined = effectiveAsync
5595
6711
  ? undefined
5596
6712
  : compactOptional<ForegroundRunControl>({
@@ -5599,7 +6715,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5599
6715
  mode: foregroundMode,
5600
6716
  ...(effectiveParams.workflowParentRunId ? { parentWorkflowRunId: effectiveParams.workflowParentRunId } : {}),
5601
6717
  ...(effectiveParams.workflowKey ? { workflowKey: effectiveParams.workflowKey } : {}),
5602
- workflowSteeringDir,
5603
6718
  startedAt: Date.now(),
5604
6719
  updatedAt: Date.now(),
5605
6720
  cwd: effectiveCwd,
@@ -5652,7 +6767,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5652
6767
  }
5653
6768
 
5654
6769
  const writeNestedForegroundEvent = (type: "subagent.nested.started" | "subagent.nested.completed", result?: AgentToolResult<Details>): void => {
5655
- if (!inheritedNestedRoute || !nestedParentAddress) return;
6770
+ if (!inheritedNestedRouteValue || !nestedParentAddress) return;
5656
6771
  const now = Date.now();
5657
6772
  const details = result?.details;
5658
6773
  const state = type === "subagent.nested.started"
@@ -5686,7 +6801,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5686
6801
  ? resolveSubagentIntercomTarget(runId, agentsForSummary[0], 0)
5687
6802
  : undefined;
5688
6803
  try {
5689
- writeNestedEvent(inheritedNestedRoute, compactOptional<Parameters<typeof writeNestedEvent>[1]>({
6804
+ writeNestedEvent(inheritedNestedRouteValue, compactOptional<Parameters<typeof writeNestedEvent>[1]>({
5690
6805
  type,
5691
6806
  ts: now,
5692
6807
  parentRunId: nestedParentAddress.parentRunId,
@@ -5697,13 +6812,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5697
6812
  parentStepIndex: nestedParentAddress.parentStepIndex,
5698
6813
  depth: nestedParentAddress.depth,
5699
6814
  path: nestedParentAddress.path,
5700
- ownerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,
6815
+ ownerIntercomTarget: deps.childRuntime?.intercomSessionName,
5701
6816
  leafIntercomTarget,
5702
6817
  intercomTarget: leafIntercomTarget,
5703
6818
  ownerState: state === "running" ? "live" : "gone",
5704
6819
  mode: foregroundMode,
5705
6820
  state,
5706
6821
  agent: agentsForSummary[0],
6822
+ ...(details?.results.length === 1 && details.results[0]?.sessionName ? { sessionName: details.results[0].sessionName } : {}),
5707
6823
  agents: agentsForSummary,
5708
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 } : {}),
5709
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 } : {}),
@@ -5722,6 +6838,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5722
6838
  : details?.results.length
5723
6839
  ? { steps: details.results.map((child) => ({
5724
6840
  agent: child.agent,
6841
+ ...(child.sessionName ? { sessionName: child.sessionName } : {}),
5725
6842
  status: child.interrupted || child.detached ? "paused" as const : child.exitCode === 0 ? "complete" as const : "failed" as const,
5726
6843
  ...(child.model ? { model: child.model } : {}),
5727
6844
  ...(child.thinking ? { thinking: child.thinking } : {}),
@@ -5745,17 +6862,22 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5745
6862
  }
5746
6863
  if (workflowLaunchObserver) {
5747
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;
5748
6870
  const launch = hasSingle
5749
- ? { 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 }
5750
6872
  : singleTask
5751
- ? { 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 }
5752
6874
  : undefined;
5753
6875
  if (launch) {
5754
6876
  workflowLaunchObservers.delete(params);
5755
6877
  workflowLaunchObserver(launch);
5756
6878
  }
5757
6879
  }
5758
- const asyncResult = runAsyncPath(execData, deps);
6880
+ const asyncResult = await runAsyncPath(execData, deps);
5759
6881
  if (asyncResult) {
5760
6882
  asyncLaunchFailed = asyncResult.isError === true;
5761
6883
  return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(asyncResult, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget));
@@ -5800,15 +6922,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5800
6922
  ): Promise<AgentToolResult<Details>> => {
5801
6923
  const normalizedAction = typeof params.action === "string" ? params.action.trim() : params.action;
5802
6924
  const requestParams = normalizedAction ? { ...params, action: normalizedAction } : params;
5803
- if (normalizedAction) return execute(id, requestParams, signal, onUpdate, ctx);
5804
- 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);
5805
6927
  const dispatchParams = applyForceTopLevelAsyncOverride(requestParams, depth, deps.config.forceTopLevelAsync === true);
5806
6928
  const runsForeground = dispatchParams.clarify === true || (dispatchParams.async ?? deps.asyncByDefault) !== true;
5807
- if (!runsForeground) return execute(id, requestParams, signal, onUpdate, ctx);
6929
+ if (!runsForeground) return execute(id, requestParams, signal, onUpdate, ctx).then(withAggregatedToolUsage);
5808
6930
  if (deps.state.subagentInProgress === true) return duplicateSubagentCallResult(requestParams);
5809
6931
  deps.state.subagentInProgress = true;
5810
6932
  try {
5811
- return await execute(id, requestParams, signal, onUpdate, ctx);
6933
+ return withAggregatedToolUsage(await execute(id, requestParams, signal, onUpdate, ctx));
5812
6934
  } finally {
5813
6935
  deps.state.subagentInProgress = false;
5814
6936
  }
@@ -5821,11 +6943,24 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5821
6943
  onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
5822
6944
  ctx: ExtensionContext,
5823
6945
  ): Promise<AgentToolResult<Details>> => {
5824
- const normalized = normalizePublicSubagentExecution(params, { asyncByDefault: deps.asyncByDefault });
6946
+ const normalized = normalizePublicSubagentExecution(params);
5825
6947
  if (!normalized.ok) {
5826
6948
  return Promise.resolve({ content: [{ type: "text", text: normalized.error }], isError: true, details: { mode: normalized.mode, results: [] } });
5827
6949
  }
5828
- 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);
5829
6964
  };
5830
6965
 
5831
6966
  const executeDelegated = async (
@@ -5839,15 +6974,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5839
6974
  const privateParams = delegatedParams as SubagentParamsLike & {
5840
6975
  delegatedThinkingOverride?: AgentConfig["thinking"];
5841
6976
  delegatedAllowZeroToolBudget?: true;
6977
+ delegatedWorkflowPermit?: WorkflowChildPermit;
5842
6978
  };
5843
6979
  const thinkingOverride = privateParams.delegatedThinkingOverride;
5844
6980
  const allowZeroToolBudget = privateParams.delegatedAllowZeroToolBudget === true;
6981
+ const workflowPermit = privateParams.delegatedWorkflowPermit;
5845
6982
  delete privateParams.delegatedThinkingOverride;
5846
6983
  delete privateParams.delegatedAllowZeroToolBudget;
6984
+ delete privateParams.delegatedWorkflowPermit;
5847
6985
  if (thinkingOverride !== undefined) delegatedThinkingOverrides.set(delegatedParams, thinkingOverride);
5848
6986
  if (allowZeroToolBudget) delegatedZeroToolBudgets.add(delegatedParams);
6987
+ if (workflowPermit) workflowPermitContexts.set(delegatedParams, { root: workflowPermit });
5849
6988
  delegatedExecutions.add(delegatedParams);
5850
- return execute(id, delegatedParams, signal, onUpdate, ctx);
6989
+ return withAggregatedToolUsage(await execute(id, delegatedParams, signal, onUpdate, ctx));
5851
6990
  };
5852
6991
 
5853
6992
  const executeScheduled = (
@@ -5865,7 +7004,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5865
7004
  });
5866
7005
  scheduledOwnerExecutors.set(ownerSessionId, ownerExecutor);
5867
7006
  }
5868
- return ownerExecutor.execute(id, params, signal, undefined, ctx);
7007
+ return ownerExecutor.executePublic(id, params, signal, undefined, ctx);
5869
7008
  };
5870
7009
 
5871
7010
  return { execute: executeWithSingleDispatchGuard, executePublic, executeDelegated, executeScheduled };