@xzzpig/pi-subagents 0.8.0 → 0.10.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 (221) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +195 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +7 -6
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +42 -21
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +77 -21
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +65 -29
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +7 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +204 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +718 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +489 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1223 -402
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +364 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +20 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -3,8 +3,8 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
5
5
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
6
- import { findBlockingAgentDiagnostic, resolveAgentName, type AgentConfig, type AgentDiscoveryDiagnostic, type AgentScope } from "../../agents/agents.ts";
7
- import { getArtifactsDir, getChainRunsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir } from "../../shared/artifacts.ts";
6
+ import { discoverAgents, findBlockingAgentDiagnostic, formatUnknownAgentError, resolveAgentName, unknownAgentDiagnosticContext, type AgentConfig, type AgentDiscoveryDiagnostic, type AgentScope, type UnknownAgentDiagnosticContext } from "../../agents/agents.ts";
7
+ import { getArtifactsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir } from "../../shared/artifacts.ts";
8
8
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
9
9
  import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilient-json.ts";
10
10
  import { isStorageCapacityError } from "../../shared/file-system-retry.ts";
@@ -13,7 +13,6 @@ import {
13
13
  beginForegroundChild,
14
14
  finishForegroundChild,
15
15
  foregroundSchedulingSettled,
16
- retainForegroundSchedulingOwner,
17
16
  settleForegroundSchedulingOwner,
18
17
  updateForegroundChild,
19
18
  } from "./foreground-control.ts";
@@ -24,62 +23,53 @@ import { handleManagementAction } from "../../agents/agent-management.ts";
24
23
  import { handleRefinementAction } from "../../agents/agent-refinements.ts";
25
24
  import { buildDoctorReport } from "../../extension/doctor.ts";
26
25
  import { readSubagentGuide } from "../../extension/subagent-guide.ts";
27
- import { normalizePublicSubagentExecution } from "../../extension/public-execution.ts";
26
+ import { normalizePublicSubagentExecution, validateWorkflowCapacityOverrides } from "../../extension/public-execution.ts";
28
27
  import { runSync } from "./execution.ts";
29
28
  import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/tool-actions.ts";
30
29
  import type { MainWatchdogRuntime } from "../../watchdog/runtime.ts";
31
- import { buildModelCandidates, inheritsParentModel, normalizeParentModel, resolveEffectiveSubagentModel, resolveModelCandidate, type ParentModel } from "../shared/model-fallback.ts";
30
+ import { applyWatchdogLaunchRules } from "../../watchdog/rules.ts";
31
+ import { buildModelCandidates, normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, type ModelOrigin, type ParentModel } from "../shared/model-fallback.ts";
32
32
  import { formatRetainedChildren, listRetainedChildren } from "../background/retained-children.ts";
33
33
  import { resolveModelScopesForAgent, type ModelScopeConfig } from "../shared/model-scope.ts";
34
- import { aggregateParallelOutputs } from "../shared/parallel-utils.ts";
35
34
  import { recordRun } from "../shared/run-history.ts";
36
35
  import {
37
- buildChainInstructions,
38
- writeInitialProgressFile,
39
36
  getStepAgents,
40
37
  isParallelStep,
41
38
  isDynamicParallelStep,
42
- resolveChainPath,
43
39
  resolveExistingReadPaths,
44
- resolveStepBehavior,
45
- suppressProgressForReadOnlyTask,
46
- taskDisallowsFileUpdates,
47
40
  type ChainStep,
48
41
  type DynamicParallelStep,
49
42
  type ParallelStep,
50
43
  type ParallelTaskItem,
51
- type ResolvedStepBehavior,
52
44
  type SequentialStep,
53
- type StepOverrides,
54
45
  } from "../../shared/settings.ts";
55
- import { discoverAvailableSkills, normalizeSkillInput } from "../../agents/skills.ts";
46
+ import { normalizeSkillInput } from "../../agents/skills.ts";
56
47
  import { buildAsyncRunnerSteps, DEFAULT_ASYNC_TIMEOUT_MS, executeAsyncChain, executeAsyncSingle, formatAsyncStartedMessage, isAsyncAvailable, workflowAwaitedAsyncResultPath } from "../background/async-execution.ts";
57
48
  import { updateActiveRunIndex } from "../background/active-run-index.ts";
58
49
  import { steeringReceipt } from "../background/steering.ts";
59
- import { acquireActiveAsyncCapacity, ActiveAsyncCapacityError, getActiveAsyncCapacitySnapshot, resolveMaxActiveAsyncRunsPerSession, transferActiveAsyncCapacity, type ActiveAsyncCapacityHandle } from "../background/active-async-capacity.ts";
60
- import { isScheduledRunAction, type ScheduledRunAction } from "../background/scheduled-runs.ts";
50
+ import { acquireActiveAsyncCapacity, ActiveAsyncCapacityError, getActiveAsyncCapacitySnapshot, resolveAbandonedSlotReleaseAfterMs, resolveMaxActiveAsyncRunsPerSession, transferActiveAsyncCapacity, type ActiveAsyncCapacityHandle } from "../background/active-async-capacity.ts";
51
+ import { isScheduledRunAction } from "../background/scheduled-runs.ts";
61
52
  import { enqueueChainAppendRequest, readPendingChainAppendRequests, runnerStepOutputNames } from "../background/chain-append.ts";
62
53
  import { ChainOutputValidationError, validateChainOutputBindingsWithContext } from "../shared/chain-outputs.ts";
63
- import { normalizeGateAcceptance, validateExecutionAcceptance } from "../shared/acceptance.ts";
54
+ import { normalizeGateAcceptance, resolveAcceptanceReportMode, validateExecutionAcceptance } from "../shared/acceptance.ts";
64
55
  import { canPreferFork, createForkContextResolver, forkedChildRequiresThinkingOff, resolveSubagentLaunchContext } from "../../shared/fork-context.ts";
56
+ import { createPrunedForkSessionWriter } from "../../shared/pruned-fork.ts";
65
57
  import { resolveCurrentSessionId } from "../../shared/session-identity.ts";
66
58
  import { currentCompletionOwnerId } from "../../shared/completion-owner.ts";
67
59
  import { applyIntercomBridgeToAgent, INTERCOM_BRIDGE_MARKER, resolveIntercomBridge, resolveIntercomSessionTarget, resolveSubagentIntercomTarget, type IntercomBridgeState } from "../../intercom/intercom-bridge.ts";
68
60
  import { formatControlIntercomMessage, formatControlNoticeMessage, resolveControlConfig, shouldNotifyControlEvent } from "../shared/subagent-control.ts";
69
- import { resolveTurnBudgetConfig } from "../shared/turn-budget.ts";
70
61
  import { formatSpawnBudget, getSpawnBudgetSnapshot, grantSpawnBudget, preflightSpawnBudget, preflightSpawnBudgetGrant, reserveSpawnBudget } from "../shared/spawn-budget.ts";
71
- import { claimRunFanoutBatch, claimRunFanoutBatchWithCommit, createRunFanoutBudget, decodeRunFanoutBudgetDescriptor, formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor, RunFanoutLimitError, RUN_FANOUT_BUDGET_ENV, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
62
+ import { claimRunFanoutBatch, claimRunFanoutBatchWithCommit, createRunFanoutBudget, formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor, RunFanoutLimitError, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
72
63
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
73
64
  import { usageBudgetExceededMessage, usageBudgetState, validateUsageBudgetConfig } from "../shared/usage-budget.ts";
74
65
  import { intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
75
66
  import { isAgentContractV1 } from "../shared/agent-contract.ts";
76
67
  import { normalizeExtensionBindings, type ExtensionBindings } from "../shared/extension-bindings.ts";
77
- import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
78
- import { cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
79
- import { compactForegroundDetails, getSingleResultOutput, mapConcurrent, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage } from "../../shared/utils.ts";
68
+ import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, outputPathMappingFromTask, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
69
+ import { assertJsonSchemaObject, cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
70
+ import { compactForegroundDetails, getSingleResultOutput, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage, toAgentToolUsage } from "../../shared/utils.ts";
80
71
  import { createTaskMutationArbiter } from "../shared/llm-intent-arbiter.ts";
81
- import { DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore } from "../shared/parallel-utils.ts";
82
- import { discardPreservedWorktrees, formatParallelHandoffError, formatParallelHandoffReference, parallelHandoffPath, writeParallelHandoffGroup, writePendingParallelHandoff } from "../shared/parallel-handoff.ts";
72
+ import { discardPreservedWorktrees, formatParallelHandoffError, formatParallelHandoffReference, formatStoredParallelHandoffCleanup, parallelHandoffPath, readParallelHandoffManifest, recordParallelHandoffMerge, recordParallelHandoffSupersession, writeParallelHandoffGroup, writePendingParallelHandoff } from "../shared/parallel-handoff.ts";
83
73
  import { summarizeContextModes, type ContextMode, type ContextSummary } from "../shared/context-mode.ts";
84
74
  import {
85
75
  attachNestedChildrenToResultChildren,
@@ -94,11 +84,8 @@ import { deliverInterruptRequest, readRevivalBriefs, requestAsyncSteer, type Ste
94
84
  import { updateSteeringTarget, waitForSteeringAction } from "../background/steering.ts";
95
85
  import { canQueueRetainedAsyncFollowUp, steerAsyncRun } from "./async-steering-action.ts";
96
86
  import {
97
- removeWorkflowForegroundSteeringRoute,
98
87
  resolveWorkflowForegroundSteeringTarget,
99
88
  steerWorkflowForegroundTarget,
100
- workflowForegroundSteeringDir,
101
- workflowForegroundSteeringLaunchOptions,
102
89
  } from "./workflow-foreground-steering.ts";
103
90
  import { stopAsyncRun } from "./async-stop-action.ts";
104
91
  import { dismissRecoveredWorkflow } from "./async-dismiss-action.ts";
@@ -106,13 +93,15 @@ import { promotePausedWorkflowIfSettled, reconcileDetachedWorkflowChildCompletio
106
93
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
107
94
  import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
108
95
  import { resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
109
- import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, resolveInheritedNestedRouteFromEnv, resolveNestedAsyncDir, resolveNestedParentAddressFromEnv, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedRunResolutionScope } from "../shared/nested-events.ts";
96
+ import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, inheritedNestedParentAddressOf, inheritedNestedRouteOf, resolveNestedAsyncDir, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedParentAddress, type NestedRoute, type NestedRunResolutionScope } from "../shared/nested-events.ts";
97
+ import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
110
98
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
111
99
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
112
- import { isStoppableAsyncStatusStep, resolveAsyncStatusChild } from "../shared/child-identity.ts";
100
+ import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, stopStoppableAsyncStatusChildren } from "../shared/child-identity.ts";
113
101
  import { inspectSubagentStatus } from "../background/run-status.ts";
114
102
  import { getExternalJobProvider } from "../../api/external-job-provider.ts";
115
103
  import { externalJobFollowUpRequestDigest, externalJobFollowUpRequestId, externalJobFollowUpRunId, externalJobPromptDigest, externalJobStableJson } from "../shared/external-job-runner.ts";
104
+ import { externalCliReceiptMetadata, normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
116
105
  import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.ts";
117
106
  import { handleMissionAction, MISSION_ACTIONS } from "../../missions/actions.ts";
118
107
  import { attachMissionToLaunchResult, prepareMissionLaunch, writeMissionAsyncBinding, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
@@ -122,18 +111,33 @@ import { createMissionWorkflowState } from "../../missions/workflow-state.ts";
122
111
  import { resolveAuthorityDecision } from "../../policy/authority.ts";
123
112
  import { handleHerdrInspectorAction, HERDR_INSPECTOR_ACTIONS } from "../../inspectors/herdr/actions.ts";
124
113
  import { handleHerdrProjectPaneAction, HERDR_PROJECT_PANE_ACTIONS } from "../../inspectors/herdr/project-panes.ts";
125
- import { previewSimpleWorkflowRun, runWorkflowScript, WorkflowScriptError, type WorkflowReceiptResumeReference, type WorkflowScriptChildResult, type WorkflowSteerOptions, type WorkflowSteerResult } from "../../workflows/scripted-workflow.ts";
114
+ import { previewSimpleWorkflowRun, runWorkflowScript, validateWorkflowScript, WorkflowScriptError, type WorkflowLanePlan, type WorkflowReceiptResumeReference, type WorkflowScriptChildResult, type WorkflowScriptTraceEntry, type WorkflowSteerOptions, type WorkflowSteerResult } from "../../workflows/scripted-workflow.ts";
115
+ import { executeWorkflowHostCommand, resolveWorkflowHostOutputClaimPath, type WorkflowHostCommandParams, type WorkflowHostCommandResult } from "../../workflows/host-command.ts";
126
116
  import { buildWorkflowReceipt, resolveWorkflowReceiptResumeEntry, writeWorkflowReceipt, type WorkflowReceipt, type WorkflowReceiptState } from "../../workflows/workflow-receipt.ts";
117
+ import { upsertHostStep, validHostStepNodes } from "../shared/host-step-status.ts";
118
+ import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
119
+ import { parseWorkflowChildSummary, workflowChildSummary } from "../../workflows/workflow-child-summary.ts";
127
120
  import { resolveWorkflowChatProgress, type WorkflowChatProgressProjection } from "../../workflows/chat-progress.ts";
121
+ import { annotateWorkflowPreflightTrace, formatWorkflowPreflight, formatWorkflowPreflightWarnings, normalizeWorkflowPreflight, workflowPreflightWarnings } from "../../workflows/workflow-preflight.ts";
122
+ import {
123
+ authorizeWorkflowResourceHost,
124
+ claimWorkflowChildPermit,
125
+ consumeWorkflowResourcePermit,
126
+ validateWorkflowChildPermitRoot,
127
+ type WorkflowChildPermit,
128
+ type WorkflowChildPermitContext,
129
+ type WorkflowResourceAuthority,
130
+ type WorkflowResourcePermit,
131
+ } from "../../shared/workflow-child-permit.ts";
132
+ import { resolveWorkflowResource } from "../../workflows/workflow-resources.ts";
128
133
  import {
129
134
  cleanupWorktrees,
130
135
  createWorktrees,
131
136
  diffWorktrees,
132
- findWorktreeTaskCwdConflict,
133
137
  formatWorktreeDiffSummary,
134
- formatWorktreeTaskCwdConflict,
135
138
  type WorktreeSetup,
136
139
  } from "../shared/worktree.ts";
140
+ import { createWorktreeCleanupPlan, formatWorktreeCleanupPlan } from "../shared/worktree-cleanup-plan.ts";
137
141
  import {
138
142
  type AgentProgress,
139
143
  type AsyncJobState,
@@ -146,23 +150,33 @@ import {
146
150
  type ControlEvent,
147
151
  type Details,
148
152
  type ExtensionConfig,
153
+ type ForegroundResumeChild,
154
+ type ForegroundChildSessionControls,
155
+ type ForegroundSteerInput,
156
+ type ForegroundSteerOutcome,
149
157
  type ForegroundRunControl,
158
+ type HostStepNodeV1,
150
159
  type IntercomBridgeConfig,
151
160
  type IntercomEventBus,
152
161
  type JsonSchemaObject,
153
162
  type MaxOutputConfig,
154
163
  type NestedRouteInfo,
155
164
  type NestedRunSummary,
165
+ type OutputMode,
156
166
  type ResolvedControlConfig,
157
- type ResolvedTurnBudget,
158
167
  type ResolvedToolBudget,
159
168
  type RunFanoutBudgetDescriptor,
160
169
  type SteeringRecoveryDescriptor,
161
170
  type SingleResult,
162
171
  type SubagentChildStatusEvent,
163
172
  type ToolBudgetConfig,
164
- type TurnBudgetConfig,
173
+ type Usage,
165
174
  type UsageBudgetConfig,
175
+ type WorkflowResourceProvenanceV1,
176
+ type WorkflowGraphNode,
177
+ type WorkflowGraphSnapshot,
178
+ type WorkflowNodeStatus,
179
+ type WorkflowTerminalOutcome,
166
180
  type SubagentRunMode,
167
181
  type SubagentState,
168
182
  DIRS,
@@ -173,18 +187,21 @@ import {
173
187
  SUBAGENT_CONTROL_INTERCOM_EVENT,
174
188
  SUBAGENT_FOREGROUND_COMPLETE_EVENT,
175
189
  checkSubagentDepth,
176
- resolveTopLevelParallelConcurrency,
177
- resolveTopLevelParallelMaxTasks,
178
190
  resolveChildMaxSubagentDepth,
179
191
  resolveCurrentMaxSubagentDepth,
180
192
  resolveMaxSubagentSpawnsPerRun,
181
193
  wrapForkTask,
182
194
  type ScheduleOrigin,
183
195
  } from "../../shared/types.ts";
196
+ import { deriveChildSessionName } from "../../shared/child-session-name.ts";
184
197
 
185
- const MUTATING_MANAGEMENT_ACTIONS = new Set(["create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "refine", "refine.rollback", "dismiss", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
198
+ const MUTATING_MANAGEMENT_ACTIONS = new Set(["create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "worktree.cleanup", "lane.recordMerge", "lane.recordSupersession", "refine", "refine.rollback", "dismiss", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
186
199
  const DESTRUCTIVE_MANAGEMENT_ACTIONS = new Set(["delete", "eject", "disable", "reset", "mission.close", "worktree.discard", "refine.rollback", "inspector.close", "project.close", "stop", "interrupt", "schedule.delete"]);
187
200
 
201
+ function resolveSteerDeliveryMode(mode: SubagentParamsLike["mode"]): SteerDeliveryMode | undefined {
202
+ return mode === "steer" || mode === "follow_up" || mode === "auto" ? mode : undefined;
203
+ }
204
+
188
205
  function editDistance(left: string, right: string): number {
189
206
  const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
190
207
  for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
@@ -280,6 +297,9 @@ export interface SubagentParamsLike {
280
297
  runId?: string;
281
298
  dir?: string;
282
299
  handoffPath?: string;
300
+ laneId?: string;
301
+ merge?: unknown;
302
+ supersession?: unknown;
283
303
  index?: number;
284
304
  childId?: string;
285
305
  view?: "fleet" | "transcript";
@@ -291,24 +311,35 @@ export interface SubagentParamsLike {
291
311
  type?: string;
292
312
  agent?: string;
293
313
  task?: string;
314
+ capabilities?: boolean;
294
315
  extensionBindings?: ExtensionBindings;
295
316
  /** Retained async child run id. Valid only on workflow runs.run items. */
296
317
  resume?: string;
297
318
  message?: string;
298
319
  steeringRecovery?: boolean;
299
- mode?: SteerDeliveryMode;
320
+ mode?: SteerDeliveryMode | "plan" | "apply";
321
+ repo?: string;
322
+ planId?: string;
300
323
  workflowScript?: string;
324
+ workflowScriptPath?: string;
325
+ globalConcurrencyLimit?: number;
326
+ maxSubagentSpawnsPerRun?: number;
327
+ preflight?: import("../../shared/types.ts").WorkflowPreflightV1;
301
328
  chatProgress?: "auto" | "off" | "live-card";
302
329
  isolation?: "none" | "worktree";
303
330
  step?: ChainStep;
304
331
  /** Internal workflow ownership metadata; not part of the public schema. */
305
332
  workflowParentRunId?: string;
306
333
  workflowKey?: string;
334
+ lane?: import("../../shared/types.ts").WorkflowLaneMetadata;
307
335
  /** Set by the scheduler so this run's completion can name the schedule that produced it. */
308
336
  scheduleOrigin?: ScheduleOrigin;
309
337
  workflowChildAsyncId?: string;
310
338
  workflowAwaitAsync?: boolean;
339
+ /** Internal async-workflow bridge: keep the live VM await pending across supervisor detachment. */
340
+ workflowAwaitDetached?: boolean;
311
341
  workflowParentDeadlineAt?: number;
342
+ workflowOutputClaimPath?: string;
312
343
  suppressRoutineResultIntercom?: boolean;
313
344
  /** Internal inherited cumulative run-tree budget. */
314
345
  runFanoutBudget?: RunFanoutBudgetDescriptor;
@@ -321,6 +352,8 @@ export interface SubagentParamsLike {
321
352
  tasks?: TaskParam[];
322
353
  concurrency?: number;
323
354
  worktree?: boolean;
355
+ /** Git ref used as the managed worktree base. */
356
+ baseRef?: string;
324
357
  context?: "fresh" | "fork" | "profile";
325
358
  /** Per-run intercom bridge config. It replaces the global config for this launch only. */
326
359
  intercomBridge?: IntercomBridgeConfig;
@@ -330,9 +363,6 @@ export interface SubagentParamsLike {
330
363
  maxRuntimeMs?: number;
331
364
  /** Optional hard per-tool-call timeout (ms). Known-fast tools also have a default. */
332
365
  toolTimeoutMs?: number;
333
- turnBudget?: TurnBudgetConfig;
334
- /** Internal-only strict turn-boundary enforcement for versioned foreground delegation. */
335
- enforceHardTurnLimit?: boolean;
336
366
  toolBudget?: ToolBudgetConfig;
337
367
  usageBudget?: UsageBudgetConfig;
338
368
  clarify?: boolean;
@@ -344,8 +374,13 @@ export interface SubagentParamsLike {
344
374
  artifacts?: boolean;
345
375
  includeProgress?: boolean;
346
376
  model?: string;
377
+ /** Internal recovery provenance for a resolved model override. */
378
+ modelOrigin?: ModelOrigin;
347
379
  fast?: boolean;
348
380
  thinking?: string | false;
381
+ /** Public named workflow resource. Resolved before entering the workflow sandbox. */
382
+ workflow?: string;
383
+ args?: Record<string, unknown>;
349
384
  scope?: string;
350
385
  target?: string;
351
386
  focus?: boolean;
@@ -362,6 +397,7 @@ export interface SubagentParamsLike {
362
397
  agentContract?: AgentContract;
363
398
  at?: string;
364
399
  every?: string;
400
+ sessionOnly?: boolean;
365
401
  on?: string | number;
366
402
  timezone?: string;
367
403
  overlap?: "skip";
@@ -392,28 +428,47 @@ interface ExecutorDeps {
392
428
  config: ExtensionConfig;
393
429
  asyncByDefault: boolean;
394
430
  waitToolEnabled?: boolean;
431
+ waitToolDefaultTimeoutMs?: number;
395
432
  handleScheduledRunAction?: (params: SubagentParamsLike, ctx: ExtensionContext) => Promise<AgentToolResult<Details>>;
396
433
  watchdog?: MainWatchdogRuntime;
397
434
  tempArtifactsDir: string;
398
435
  getSubagentSessionRoot: (parentSessionFile: string | null) => string;
399
436
  expandTilde: (p: string) => string;
400
- discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig; maxThinking?: AgentConfig["maxThinking"] };
437
+ discoverAgents: (cwd: string, scope: AgentScope, preferredModelProvider?: string) => { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig; maxThinking?: AgentConfig["maxThinking"]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] };
401
438
  allowMutatingManagementActions?: boolean;
402
439
  activateSupervisorTransport?: () => void;
403
440
  refreshResultDelivery?: () => void;
404
441
  kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
442
+ /** Set when this executor runs inside a child session; carries the runtime settings the host passes instead of environment variables. */
443
+ childRuntime?: ChildRuntimeConfig;
444
+ }
445
+
446
+ function inheritedNestedRoute(deps: Pick<ExecutorDeps, "childRuntime">): NestedRoute | undefined {
447
+ return inheritedNestedRouteOf(deps.childRuntime);
448
+ }
449
+
450
+ function inheritedNestedParentAddress(deps: Pick<ExecutorDeps, "childRuntime">): NestedParentAddress | undefined {
451
+ return inheritedNestedParentAddressOf(deps.childRuntime);
405
452
  }
406
453
 
407
- type ForkSessionFileForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean) => string | undefined;
408
- type ForkThinkingOverrideForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean) => AgentConfig["thinking"] | undefined;
454
+ function inheritedRunFanoutBudget(deps: Pick<ExecutorDeps, "childRuntime">): RunFanoutBudgetDescriptor | undefined {
455
+ return deps.childRuntime?.runFanoutBudget;
456
+ }
457
+
458
+ type ForkSessionFileForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean, modelOrigin?: ModelOrigin) => string | undefined;
459
+ type PrepareForkSessionForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean, modelOrigin?: ModelOrigin) => Promise<void>;
460
+ type ForkThinkingOverrideForTask = (agentName: string, idx?: number, modelOverride?: string, modelOverrideFromParent?: boolean, modelOrigin?: ModelOrigin) => AgentConfig["thinking"] | undefined;
409
461
 
410
462
  interface ExecutionContextData {
411
463
  params: SubagentParamsLike;
412
464
  effectiveCwd: string;
465
+ requestedCwd?: string;
413
466
  ctx: ExtensionContext;
414
467
  signal: AbortSignal;
415
468
  onUpdate?: (r: AgentToolResult<Details>) => void;
416
469
  agents: AgentConfig[];
470
+ /** Exact filesystem discovery provenance retained through defensive execution backstops. */
471
+ unknownAgentDiagnosticContext: UnknownAgentDiagnosticContext;
417
472
  /** Discovered agent definitions before per-run bridge injection. */
418
473
  recoveryAgents: AgentConfig[];
419
474
  runId: string;
@@ -429,13 +484,14 @@ interface ExecutionContextData {
429
484
  effectiveAsync: boolean;
430
485
  asyncRunId: string;
431
486
  controlConfig: ResolvedControlConfig;
487
+ /** Structured delegation consumers do not need duration-only heartbeat snapshots. */
488
+ suppressUnchangedDelegationUpdates?: boolean;
432
489
  intercomBridge: IntercomBridgeState;
433
490
  nestedRoute?: NestedRouteInfo;
434
491
  timeoutMs?: number;
435
492
  deadlineAt?: number;
436
493
  /** Raw global config.toolTimeoutMs, for per-step resolution in async runners. */
437
494
  configToolTimeoutMs?: number;
438
- turnBudget?: ResolvedTurnBudget;
439
495
  toolBudget?: ResolvedToolBudget;
440
496
  usageBudget?: UsageBudgetConfig;
441
497
  allowZeroToolBudget?: boolean;
@@ -449,16 +505,48 @@ interface ExecutionContextData {
449
505
  runFanoutBudget: RunFanoutBudgetDescriptor;
450
506
  topLevelAsyncCapacityEligible: boolean;
451
507
  activeAsyncCapacity?: ActiveAsyncCapacityHandle;
508
+ workflowChildPermitLaunch?: WorkflowChildPermitContext;
452
509
  }
453
510
 
454
511
  function resolveRequestedCwd(runtimeCwd: string, requestedCwd: string | undefined): string {
455
512
  return requestedCwd ? path.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
456
513
  }
457
514
 
515
+ function loadWorkflowScriptPath(params: SubagentParamsLike, runtimeCwd: string): { params?: SubagentParamsLike; error?: string } {
516
+ if (params.workflowScriptPath === undefined) return { params };
517
+ const scriptPath = path.resolve(resolveRequestedCwd(runtimeCwd, params.cwd), params.workflowScriptPath);
518
+ let workflowScript: string;
519
+ try {
520
+ workflowScript = fs.readFileSync(scriptPath, "utf8");
521
+ } catch (error) {
522
+ return { error: `Failed to read workflowScriptPath '${scriptPath}': ${error instanceof Error ? error.message : String(error)}` };
523
+ }
524
+ if (!workflowScript.trim()) return { error: `workflowScriptPath file '${scriptPath}' is empty.` };
525
+ const { workflowScriptPath: _workflowScriptPath, ...rest } = params;
526
+ return { params: { ...rest, workflowScript } };
527
+ }
528
+
529
+ function currentProjectTrusted(ctx: Pick<ExtensionContext, "isProjectTrusted">): boolean {
530
+ return ctx.isProjectTrusted?.() === true;
531
+ }
532
+
533
+ function trustedProjectCwd(ctx: ExtensionContext): string | undefined {
534
+ return currentProjectTrusted(ctx) ? path.resolve(ctx.cwd) : undefined;
535
+ }
536
+
537
+ function sandboxProfileTrustError(agent: AgentConfig, ctx: ExtensionContext, childCwd: string): string | undefined {
538
+ if (!agent.sandbox || (agent.source !== "project" && agent.override?.scope !== "project")) return undefined;
539
+ const trustedCwd = trustedProjectCwd(ctx);
540
+ if (trustedCwd && trustedCwd === path.resolve(childCwd)) return undefined;
541
+ if (!trustedCwd) {
542
+ return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the project is not trusted. Trust the project and retry.`;
543
+ }
544
+ return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but child cwd '${path.resolve(childCwd)}' does not match the trusted project cwd '${trustedCwd}'. Launch from the trusted project cwd and retry.`;
545
+ }
546
+
458
547
  function removeForegroundControlIfIdle(state: SubagentState, runId: string): boolean {
459
548
  const control = state.foregroundControls.get(runId);
460
549
  if (control && (!foregroundSchedulingSettled(control) || (control.activeChildren?.size ?? 0) > 0)) return false;
461
- if (control) removeWorkflowForegroundSteeringRoute(control);
462
550
  state.foregroundControls.delete(runId);
463
551
  if (state.lastForegroundControlId === runId) state.lastForegroundControlId = null;
464
552
  return true;
@@ -477,12 +565,13 @@ function getForegroundControl(state: SubagentState, runId: string | undefined) {
477
565
  return newest;
478
566
  }
479
567
 
480
- function promptAuditRedoParams(value: unknown, rewrittenTask: string): SubagentParamsLike {
568
+ export function promptAuditRedoParams(value: unknown, rewrittenTask: string): SubagentParamsLike {
481
569
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Prompt redo is missing a safe live launch contract.");
482
570
  const params = { ...(value as SubagentParamsLike), task: rewrittenTask, async: false };
483
571
  delete params.workflowParentRunId;
484
572
  delete params.workflowKey;
485
573
  delete params.workflowChildAsyncId;
574
+ delete params.workflowAwaitDetached;
486
575
  delete params.workflowParentDeadlineAt;
487
576
  delete params.suppressRoutineResultIntercom;
488
577
  if (params.worktree === true && Array.isArray(params.tasks)) delete params.cwd;
@@ -510,8 +599,8 @@ function formatForegroundActivity(control: SubagentState["foregroundControls"] e
510
599
 
511
600
  function nestedResolutionScopeForExecutor(deps: ExecutorDeps): NestedRunResolutionScope | undefined {
512
601
  if (deps.allowMutatingManagementActions !== false) return undefined;
513
- const route = resolveInheritedNestedRouteFromEnv();
514
- const address = route ? resolveNestedParentAddressFromEnv() : undefined;
602
+ const route = inheritedNestedRoute(deps);
603
+ const address = route ? inheritedNestedParentAddress(deps) : undefined;
515
604
  return {
516
605
  routes: route ? [route] : [],
517
606
  ...(address ? { descendantOf: { parentRunId: address.parentRunId, ...(address.parentStepIndex !== undefined ? { parentStepIndex: address.parentStepIndex } : {}) } } : {}),
@@ -543,6 +632,7 @@ function withSpawnBudgetStatus(
543
632
  const activeAsyncCapacity = sessionId
544
633
  ? getActiveAsyncCapacitySnapshot(sessionId, resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession), {
545
634
  liveWorkflowRunIds: new Set(state.workflowControllers?.keys() ?? []),
635
+ abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(config.capacity?.abandonedSlotReleaseAfterMs),
546
636
  })
547
637
  : { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession) ?? 0 };
548
638
  state.activeAsyncCapacity = activeAsyncCapacity;
@@ -645,11 +735,13 @@ function foregroundChildActivityFromProgress(progress: SingleResult["progress"]
645
735
  ...(progress?.currentPath ? { currentPath: progress.currentPath } : {}),
646
736
  ...(progress?.turnCount !== undefined ? { turnCount: progress.turnCount } : {}),
647
737
  ...(progress?.tokens !== undefined ? { tokens: progress.tokens } : {}),
738
+ ...(progress?.window !== undefined ? { window: progress.window } : {}),
739
+ ...(progress?.windowPeak !== undefined ? { windowPeak: progress.windowPeak } : {}),
648
740
  ...(progress?.toolCount !== undefined ? { toolCount: progress.toolCount } : {}),
649
741
  };
650
742
  }
651
743
 
652
- function rememberForegroundRun(state: SubagentState, input: { runId: string; mode: "single" | "parallel" | "chain"; cwd: string; sessionId: string | null; results: SingleResult[]; extensionBindings?: ExtensionBindings }): void {
744
+ function rememberForegroundRun(state: SubagentState, input: { runId: string; mode: "single" | "parallel" | "chain"; cwd: string; sessionId: string | null; results: SingleResult[]; params: SubagentParamsLike; effectiveOutput?: string | boolean; effectiveOutputMode: OutputMode; extensionBindings?: ExtensionBindings }): void {
653
745
  state.foregroundRuns ??= new Map();
654
746
  const previous = state.foregroundRuns.get(input.runId);
655
747
  const updatedAt = Date.now();
@@ -660,9 +752,17 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
660
752
  ...(input.sessionId ? { sessionId: input.sessionId } : {}),
661
753
  updatedAt,
662
754
  children: input.results.map((result, index) => {
755
+ const resumeContract = omitUndefinedProperties({
756
+ outputSchema: input.params.outputSchema,
757
+ agentContract: input.params.agentContract,
758
+ acceptance: input.params.acceptance,
759
+ output: input.effectiveOutput,
760
+ outputMode: input.effectiveOutputMode,
761
+ });
663
762
  const child = {
664
763
  agent: result.agent,
665
764
  index,
765
+ ...(result.sessionName ? { sessionName: result.sessionName } : {}),
666
766
  ...(result.context ? { context: result.context } : {}),
667
767
  status: resolveSubagentResultStatus(omitUndefinedProperties({
668
768
  exitCode: result.exitCode,
@@ -690,6 +790,8 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
690
790
  ...(result.transcriptError ? { transcriptError: result.transcriptError } : {}),
691
791
  ...(result.detachedReason ? { detachedReason: result.detachedReason } : {}),
692
792
  ...(result.acceptance ? { acceptance: result.acceptance } : {}),
793
+ ...(Object.keys(resumeContract).length ? { resumeContract } : {}),
794
+ ...(result.sandbox ? { sandbox: result.sandbox } : {}),
693
795
  ...(result.launchContractDigest ? { launchContractDigest: result.launchContractDigest } : {}),
694
796
  ...(input.extensionBindings ? { extensionBindings: input.extensionBindings } : {}),
695
797
  ...(result.launchResolvedExtensions ? { launchResolvedExtensions: result.launchResolvedExtensions } : {}),
@@ -771,6 +873,7 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
771
873
  ...(input.result.transcriptError ? { transcriptError: input.result.transcriptError } : {}),
772
874
  ...(input.result.detachedReason ? { detachedReason: input.result.detachedReason } : {}),
773
875
  ...(input.result.acceptance ? { acceptance: input.result.acceptance } : {}),
876
+ ...(input.result.sandbox ? { sandbox: input.result.sandbox } : {}),
774
877
  ...(input.result.launchContractDigest ? { launchContractDigest: input.result.launchContractDigest } : {}),
775
878
  ...(input.result.launchResolvedExtensions ? { launchResolvedExtensions: input.result.launchResolvedExtensions } : {}),
776
879
  ...(input.result.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: input.result.runtimeAcknowledgedExtensions } : {}),
@@ -810,7 +913,7 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
810
913
  });
811
914
  }
812
915
 
813
- function resolveForegroundResumeTarget(params: SubagentParamsLike, state: SubagentState, options: { exactOnly?: boolean } = {}): { runId: string; mode: SubagentRunMode; state: "complete"; agent: string; index: number; cwd: string; sessionFile: string; model?: string; thinking?: string; launchContractDigest?: string; extensionBindings?: ExtensionBindings; capabilityCeiling?: ResolvedSubagentCapabilityCeiling } | undefined {
916
+ 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; sandbox?: string; launchContractDigest?: string; resumeContract?: ForegroundResumeChild["resumeContract"]; extensionBindings?: ExtensionBindings; capabilityCeiling?: ResolvedSubagentCapabilityCeiling } | undefined {
814
917
  const requested = (params.id ?? params.runId)?.trim();
815
918
  if (!requested || !state.foregroundRuns?.size || !state.currentSessionId) return undefined;
816
919
  const direct = state.foregroundRuns.get(requested);
@@ -820,7 +923,7 @@ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: Subage
820
923
  if (matches.length === 0) return undefined;
821
924
  if (matches.length > 1) throw new Error(`Ambiguous foreground run id prefix '${requested}' matched: ${matches.map((run) => run.runId).join(", ")}. Provide a longer id.`);
822
925
  const run = matches[0]!;
823
- if (run.children.some((child) => child.status === "detached")) throw new Error(`Foreground run '${run.runId}' is detached for intercom coordination and cannot be revived safely while any child may still be live. Reply to the supervisor request first, then wait with subagent_wait({ id: "${run.runId}" }); use status to recover the result and do not launch a replacement while it remains detached.`);
926
+ if (run.children.some((child) => child.status === "detached")) throw new Error(`Foreground run '${run.runId}' is detached for intercom coordination and cannot be revived safely while any child may still be live. Reply to the supervisor request first, then wait with bg_wait({ id: "${run.runId}" }); use status to recover the result and do not launch a replacement while it remains detached.`);
824
927
  if (run.children.length > 1 && params.index === undefined) throw new Error(`Foreground run '${run.runId}' has ${run.children.length} children. Provide index to choose one.`);
825
928
  const index = params.index ?? 0;
826
929
  if (!Number.isInteger(index)) throw new Error(`Foreground run '${run.runId}' index must be an integer.`);
@@ -840,7 +943,9 @@ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: Subage
840
943
  sessionFile,
841
944
  ...(child.model ? { model: child.model } : {}),
842
945
  ...(child.thinking ? { thinking: child.thinking } : {}),
946
+ ...(child.sandbox ? { sandbox: child.sandbox } : {}),
843
947
  ...(child.launchContractDigest ? { launchContractDigest: child.launchContractDigest } : {}),
948
+ ...(child.resumeContract ? { resumeContract: child.resumeContract } : {}),
844
949
  ...(child.extensionBindings ? { extensionBindings: normalizeExtensionBindings(child.extensionBindings)!.value } : {}),
845
950
  ...(child.capabilityCeiling ? { capabilityCeiling: child.capabilityCeiling } : {}),
846
951
  };
@@ -859,6 +964,7 @@ type NestedResumeSourceTarget = {
859
964
  sessionFile: string;
860
965
  model?: string;
861
966
  thinking?: AgentConfig["thinking"];
967
+ sandbox?: string;
862
968
  launchContractDigest?: string;
863
969
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
864
970
  recoveryDescriptor?: SteeringRecoveryDescriptor;
@@ -1215,7 +1321,7 @@ function appendStepToAsyncChain(input: {
1215
1321
  }
1216
1322
 
1217
1323
  const scope: AgentScope = resolveExecutionAgentScope(input.params.agentScope);
1218
- const discoveredForAppend = input.deps.discoverAgents(input.requestCwd, scope);
1324
+ const discoveredForAppend = input.deps.discoverAgents(input.requestCwd, scope, input.parentModel?.provider);
1219
1325
  const agents = discoveredForAppend.agents;
1220
1326
  const contextPolicy = resolveExplicitContextPolicy(input.params);
1221
1327
  const chainSkillInput = normalizeSkillInput(input.params.skill);
@@ -1229,8 +1335,11 @@ function appendStepToAsyncChain(input: {
1229
1335
  currentModelProvider: parentModel?.provider,
1230
1336
  currentModel: parentModel,
1231
1337
  modelScope: discoveredForAppend.modelScope,
1338
+ projectTrusted: currentProjectTrusted(input.ctx),
1339
+ ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
1232
1340
  interactive: input.ctx.hasUI,
1233
1341
  permissions: input.deps.config.permissions,
1342
+ childRuntime: input.deps.childRuntime,
1234
1343
  });
1235
1344
  const built = buildAsyncRunnerSteps(resolved.id, compactOptional<Parameters<typeof buildAsyncRunnerSteps>[1]>({
1236
1345
  chain: wrapChainTasksForFork(chain, contextPolicy),
@@ -1239,12 +1348,17 @@ function appendStepToAsyncChain(input: {
1239
1348
  agents,
1240
1349
  ctx: asyncCtx,
1241
1350
  availableModels: input.ctx.modelRegistry.getAvailable().map(toModelInfo),
1351
+ unknownAgentDiagnosticContext: diagnosticContextFromDiscovery(discoveredForAppend, input.requestCwd, scope),
1242
1352
  cwd: status.cwd ?? input.requestCwd,
1243
1353
  chainSkills,
1244
1354
  dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,
1245
- maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
1355
+ maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime),
1246
1356
  waitToolEnabled: input.deps.waitToolEnabled,
1357
+ waitToolDefaultTimeoutMs: input.deps.waitToolDefaultTimeoutMs,
1247
1358
  contextForAgent: contextPolicy.contextForAgent,
1359
+ worktreeBaseDir: input.deps.config.worktreeBaseDir,
1360
+ worktreeProvider: input.deps.config.worktreeProvider,
1361
+ worktreeBranchPrefix: input.deps.config.worktreeBranchPrefix,
1248
1362
  asyncDir: resolved.location.asyncDir,
1249
1363
  validateOutputBindings: false,
1250
1364
  capabilityCeiling: intersectSubagentCapabilityCeilings(status.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(asyncCtx.currentSessionId)),
@@ -1373,6 +1487,7 @@ function resolveNestedResumeTarget(match: ResolvedSubagentRunId & { kind: "neste
1373
1487
  index: 0,
1374
1488
  cwd: asyncDir ? path.dirname(asyncDir) : undefined,
1375
1489
  sessionFile: validateNestedSessionFile(run, trustedSessionRoots),
1490
+ ...(recoveryDescriptor?.sandbox ?? run.sandbox ? { sandbox: recoveryDescriptor?.sandbox ?? run.sandbox } : {}),
1376
1491
  ...(run.capabilityCeiling ? { capabilityCeiling: run.capabilityCeiling } : {}),
1377
1492
  ...(recoveryDescriptor ? { recoveryDescriptor } : {}),
1378
1493
  });
@@ -1514,9 +1629,14 @@ function externalJobFollowUpStarted(input: { sourceRunId: string; runId: string;
1514
1629
  function externalRunnerControlError(asyncDir: string, action: "steer" | "resume"): AgentToolResult<Details> | undefined {
1515
1630
  const status = readStatus(asyncDir);
1516
1631
  if (!status?.steps?.length || !status.steps.every((step) => step.runner?.type === "external-cli" || step.runner?.type === "external-job")) return undefined;
1517
- const message = action === "steer"
1518
- ? "External runners do not accept live steer messages."
1519
- : "External runners do not persist Pi sessions and cannot be resumed.";
1632
+ const externalCli = normalizeExternalCliRunnerStatus(status.steps.find((step) => step.runner?.type === "external-cli")?.runner);
1633
+ const message = externalCli
1634
+ ? action === "steer"
1635
+ ? `External adapter '${externalCli.adapter.id}' does not support runs.steer: ${externalCli.unsupportedReasons.steer}`
1636
+ : `External adapter '${externalCli.adapter.id}' cannot resume: ${externalCli.nonResumableReason}`
1637
+ : action === "steer"
1638
+ ? "External runners do not accept live steer messages."
1639
+ : "External runners do not persist Pi sessions and cannot be resumed.";
1520
1640
  return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
1521
1641
  }
1522
1642
 
@@ -1559,11 +1679,11 @@ async function resumeExternalJobFollowUp(input: {
1559
1679
  return externalJobFollowUpStarted({ sourceRunId: input.target.runId, runId, asyncDir, duplicate: true, interactive: input.ctx.hasUI });
1560
1680
  }
1561
1681
 
1562
- const depthState = checkSubagentDepth(input.deps.config.maxSubagentDepth);
1682
+ const depthState = checkSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime);
1563
1683
  if (depthState.blocked) {
1564
1684
  return { content: [{ type: "text", text: `Nested subagent resume blocked (depth=${depthState.depth}, max=${depthState.maxDepth}). Complete the follow-up directly instead.` }], isError: true, details: { mode: "management", results: [] } };
1565
1685
  }
1566
- const topLevelResume = depthState.depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.deps.state.workflowControllers?.has(input.target.runId);
1686
+ const topLevelResume = depthState.depth === 0 && !inheritedNestedRoute(input.deps) && !input.deps.state.workflowControllers?.has(input.target.runId);
1567
1687
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1568
1688
  try {
1569
1689
  activeAsyncCapacity = topLevelResume ? acquireActiveAsyncCapacity({
@@ -1572,7 +1692,7 @@ async function resumeExternalJobFollowUp(input: {
1572
1692
  runId,
1573
1693
  kind: "runner",
1574
1694
  asyncDir,
1575
- }, { liveWorkflowRunIds: new Set(input.deps.state.workflowControllers?.keys() ?? []) }) : undefined;
1695
+ }, { liveWorkflowRunIds: new Set(input.deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(input.deps.config.capacity?.abandonedSlotReleaseAfterMs) }) : undefined;
1576
1696
  } catch (error) {
1577
1697
  if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "single", results: [], activeAsyncCapacity: error.snapshot } };
1578
1698
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "single", results: [] } };
@@ -1601,17 +1721,21 @@ async function resumeExternalJobFollowUp(input: {
1601
1721
  modelScope: input.modelScope,
1602
1722
  interactive: input.ctx.hasUI,
1603
1723
  permissions: input.deps.config.permissions,
1724
+ childRuntime: input.deps.childRuntime,
1604
1725
  }),
1605
1726
  cwd: input.effectiveCwd,
1606
1727
  artifactsDir,
1607
1728
  artifactConfig,
1608
1729
  shareEnabled: false,
1609
1730
  ...(input.parentSessionFile ? { sessionRoot: input.deps.getSubagentSessionRoot(input.parentSessionFile) } : {}),
1610
- maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
1731
+ maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime),
1611
1732
  waitToolEnabled: input.deps.waitToolEnabled,
1733
+ waitToolDefaultTimeoutMs: input.deps.waitToolDefaultTimeoutMs,
1612
1734
  worktreeSetupHook: input.deps.config.worktreeSetupHook,
1613
1735
  worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
1614
1736
  worktreeBaseDir: input.deps.config.worktreeBaseDir,
1737
+ worktreeProvider: input.deps.config.worktreeProvider,
1738
+ worktreeBranchPrefix: input.deps.config.worktreeBranchPrefix,
1615
1739
  controlConfig: resolveControlConfig(input.deps.config.control, undefined),
1616
1740
  controlIntercomTarget: input.intercomBridge.active ? input.intercomBridge.orchestratorTarget : undefined,
1617
1741
  childIntercomTarget: input.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : undefined,
@@ -1715,7 +1839,7 @@ async function resumeAsyncRun(input: {
1715
1839
  };
1716
1840
  }
1717
1841
 
1718
- const { blocked, depth, maxDepth } = checkSubagentDepth(input.deps.config.maxSubagentDepth);
1842
+ const { blocked, depth, maxDepth } = checkSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime);
1719
1843
  if (blocked) {
1720
1844
  return {
1721
1845
  content: [{ type: "text", text: `Nested subagent resume blocked (depth=${depth}, max=${maxDepth}). Complete the follow-up directly instead.` }],
@@ -1727,8 +1851,9 @@ async function resumeAsyncRun(input: {
1727
1851
  input.deps.state.currentSessionId = resolveCurrentSessionId(input.ctx.sessionManager);
1728
1852
  const effectiveCwd = target.cwd ?? input.requestCwd;
1729
1853
  const scope: AgentScope = resolveExecutionAgentScope(input.params.agentScope);
1730
- const discovered = input.deps.discoverAgents(effectiveCwd, scope);
1854
+ const discovered = input.deps.discoverAgents(effectiveCwd, scope, input.parentModel?.provider);
1731
1855
  const discoveredAgents = discovered.agents;
1856
+ const unknownAgentDiagnosticContext = diagnosticContextFromDiscovery(discovered, effectiveCwd, scope);
1732
1857
  const modelScope = discovered.modelScope;
1733
1858
  const sessionName = resolveIntercomSessionTarget(input.deps.pi.getSessionName(), input.ctx.sessionManager.getSessionId());
1734
1859
  const recoveryDescriptor = "recoveryDescriptor" in target ? target.recoveryDescriptor : undefined;
@@ -1749,6 +1874,7 @@ async function resumeAsyncRun(input: {
1749
1874
  systemPrompt: "",
1750
1875
  systemPromptMode: recoveryDescriptor.systemPromptMode,
1751
1876
  inheritProjectContext: recoveryDescriptor.inheritProjectContext,
1877
+ inheritGlobalContext: recoveryDescriptor.inheritGlobalContext,
1752
1878
  inheritSkills: recoveryDescriptor.inheritSkills,
1753
1879
  source: "project",
1754
1880
  filePath: recoveryDescriptor.agentFilePath ?? path.join(getProjectSubagentsDir(recoveryDescriptor.cwd), "recovery-agent"),
@@ -1756,13 +1882,17 @@ async function resumeAsyncRun(input: {
1756
1882
  } : undefined);
1757
1883
  if (!baseAgentConfig) {
1758
1884
  return {
1759
- content: [{ type: "text", text: `Unknown agent for resume: ${target.agent}` }],
1885
+ content: [{ type: "text", text: formatUnknownAgentError(target.agent, unknownAgentDiagnosticContext, "Unknown agent for resume") }],
1760
1886
  isError: true,
1761
1887
  details: { mode: "management", results: [] },
1762
1888
  };
1763
1889
  }
1764
1890
  if (target.source === "async" && target.runner?.type === "external-cli") {
1765
- return { content: [{ type: "text", text: "External runners do not persist Pi sessions and cannot be resumed." }], isError: true, details: { mode: "management", results: [] } };
1891
+ const runner = normalizeExternalCliRunnerStatus(target.runner);
1892
+ const message = runner
1893
+ ? `External adapter '${runner.adapter.id}' cannot resume: ${runner.nonResumableReason}`
1894
+ : "External runners do not persist Pi sessions and cannot be resumed.";
1895
+ return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
1766
1896
  }
1767
1897
  if (target.source === "async" && target.runner?.type === "external-job") {
1768
1898
  if (attachChain) return { content: [{ type: "text", text: "External-job follow-up does not support chain attachment. Use action='resume' with message instead." }], isError: true, details: { mode: "management", results: [] } };
@@ -1798,7 +1928,7 @@ async function resumeAsyncRun(input: {
1798
1928
  };
1799
1929
  }
1800
1930
  const runId = randomUUID();
1801
- const topLevelResume = depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.params.workflowParentRunId;
1931
+ const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
1802
1932
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1803
1933
  try {
1804
1934
  activeAsyncCapacity = topLevelResume ? acquireActiveAsyncCapacity({
@@ -1807,7 +1937,7 @@ async function resumeAsyncRun(input: {
1807
1937
  runId,
1808
1938
  kind: "runner",
1809
1939
  asyncDir: path.join(DIRS.async, runId),
1810
- }, { liveWorkflowRunIds: new Set(input.deps.state.workflowControllers?.keys() ?? []) }) : undefined;
1940
+ }, { liveWorkflowRunIds: new Set(input.deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(input.deps.config.capacity?.abandonedSlotReleaseAfterMs) }) : undefined;
1811
1941
  } catch (error) {
1812
1942
  if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "chain", results: [], activeAsyncCapacity: error.snapshot } };
1813
1943
  throw error;
@@ -1833,6 +1963,7 @@ async function resumeAsyncRun(input: {
1833
1963
  label: `Attached ${target.runId}`,
1834
1964
  },
1835
1965
  agents,
1966
+ unknownAgentDiagnosticContext,
1836
1967
  ctx: compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
1837
1968
  pi: input.deps.pi,
1838
1969
  cwd: input.requestCwd,
@@ -1841,9 +1972,12 @@ async function resumeAsyncRun(input: {
1841
1972
  currentModelProvider: parentModel?.provider,
1842
1973
  currentModel: parentModel,
1843
1974
  modelScope,
1844
- interactive: input.ctx.hasUI,
1975
+ projectTrusted: currentProjectTrusted(input.ctx),
1976
+ ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
1977
+ interactive: input.ctx.hasUI,
1845
1978
  permissions: input.deps.config.permissions,
1846
- }),
1979
+ childRuntime: input.deps.childRuntime,
1980
+ }),
1847
1981
  availableModels,
1848
1982
  cwd: effectiveCwd,
1849
1983
  maxOutput: input.params.maxOutput,
@@ -1855,11 +1989,15 @@ async function resumeAsyncRun(input: {
1855
1989
  agentContract: input.params.agentContract,
1856
1990
  fast: input.params.fast,
1857
1991
  dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,
1858
- maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
1992
+ maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime),
1859
1993
  waitToolEnabled: input.deps.waitToolEnabled,
1994
+ waitToolDefaultTimeoutMs: input.deps.waitToolDefaultTimeoutMs,
1860
1995
  worktreeSetupHook: input.deps.config.worktreeSetupHook,
1861
1996
  worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
1862
1997
  worktreeBaseDir: input.deps.config.worktreeBaseDir,
1998
+ baseRef: input.params.baseRef ?? target.recoveryDescriptor?.baseRef,
1999
+ worktreeProvider: input.deps.config.worktreeProvider,
2000
+ worktreeBranchPrefix: input.deps.config.worktreeBranchPrefix,
1863
2001
  controlConfig: resolveControlConfig(input.deps.config.control, input.params.control),
1864
2002
  controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : undefined,
1865
2003
  childIntercomTarget: intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : undefined,
@@ -1894,8 +2032,11 @@ async function resumeAsyncRun(input: {
1894
2032
  if (target.source === "async" && asyncReviveRequiresRecoveryDescriptor(target)) {
1895
2033
  return { content: [{ type: "text", text: `Async child '${target.runId}' is missing its required run fan-out recovery identity. Start a new run instead.` }], isError: true, details: { mode: "management", results: [] } };
1896
2034
  }
2035
+ if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
2036
+ 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: [] } };
2037
+ }
1897
2038
  const runId = randomUUID();
1898
- const topLevelResume = depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.params.workflowParentRunId;
2039
+ const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
1899
2040
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1900
2041
  try {
1901
2042
  activeAsyncCapacity = !topLevelResume ? undefined : target.source === "async"
@@ -1905,20 +2046,23 @@ async function resumeAsyncRun(input: {
1905
2046
  sourceRunId: target.runId,
1906
2047
  runId,
1907
2048
  asyncDir: path.join(DIRS.async, runId),
1908
- })
2049
+ }, { abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(input.deps.config.capacity?.abandonedSlotReleaseAfterMs) })
1909
2050
  : acquireActiveAsyncCapacity({
1910
2051
  sessionId: input.deps.state.currentSessionId!,
1911
2052
  limit: resolveMaxActiveAsyncRunsPerSession(input.deps.config.maxActiveAsyncRunsPerSession),
1912
2053
  runId,
1913
2054
  kind: "runner",
1914
2055
  asyncDir: path.join(DIRS.async, runId),
1915
- });
2056
+ }, { abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(input.deps.config.capacity?.abandonedSlotReleaseAfterMs) });
1916
2057
  } catch (error) {
1917
2058
  if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "single", results: [], activeAsyncCapacity: error.snapshot } };
1918
2059
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "single", results: [] } };
1919
2060
  }
1920
2061
  const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
1921
2062
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
2063
+ const foregroundContract = target.source === "foreground" ? target.resumeContract : undefined;
2064
+ const outputSchema = input.params.outputSchema ?? foregroundContract?.outputSchema ?? recoveryDescriptor?.structuredOutputSchema;
2065
+ const agentContract = input.params.agentContract ?? foregroundContract?.agentContract ?? recoveryDescriptor?.agentContract;
1922
2066
  const artifactConfig: ArtifactConfig = recoveryDescriptor?.artifactConfig ?? omitUndefinedProperties({ ...DEFAULT_ARTIFACT_CONFIG, enabled: input.params.artifacts !== false, dir: input.deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir });
1923
2067
  const artifactsDir = recoveryDescriptor?.artifactsDir ?? getArtifactsDir(parentSessionFile, effectiveCwd, artifactConfig.dir);
1924
2068
  const availableModels = input.ctx.modelRegistry.getAvailable().map(toModelInfo);
@@ -1930,6 +2074,7 @@ async function resumeAsyncRun(input: {
1930
2074
  goal: effectiveFollowUp,
1931
2075
  agentConfig,
1932
2076
  recoveryAgentConfig,
2077
+ ...(recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) ? { sandbox: recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) } : {}),
1933
2078
  ctx: compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
1934
2079
  pi: input.deps.pi,
1935
2080
  cwd: input.requestCwd,
@@ -1938,8 +2083,11 @@ async function resumeAsyncRun(input: {
1938
2083
  currentModelProvider: parentModel?.provider,
1939
2084
  currentModel: parentModel,
1940
2085
  modelScope,
2086
+ projectTrusted: currentProjectTrusted(input.ctx),
2087
+ ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
1941
2088
  interactive: input.ctx.hasUI,
1942
2089
  permissions: input.deps.config.permissions,
2090
+ childRuntime: input.deps.childRuntime,
1943
2091
  }),
1944
2092
  cwd: effectiveCwd,
1945
2093
  maxOutput: input.params.maxOutput ?? recoveryDescriptor?.maxOutput,
@@ -1959,30 +2107,37 @@ async function resumeAsyncRun(input: {
1959
2107
  modelOverride: recoveryDescriptor?.model ?? target.model,
1960
2108
  fast: recoveryDescriptor?.fast,
1961
2109
  modelOverrideFromParent: recoveryDescriptor?.modelOverrideFromParent,
2110
+ modelOrigin: recoveryDescriptor?.modelOrigin ?? (recoveryDescriptor?.modelOverrideFromParent ? "inherited" : undefined),
1962
2111
  thinkingOverride: recoveryDescriptor?.thinking ?? target.thinking,
1963
2112
  thinkingCeiling: recoveryDescriptor?.thinkingCeiling ?? ("thinkingCeiling" in target ? target.thinkingCeiling : undefined),
1964
2113
  extensionBindings: recoveryDescriptor?.extensionBindings ?? ("extensionBindings" in target ? target.extensionBindings : undefined),
1965
2114
  outputBaseDir: resolveSingleRunOutputBaseDir(input.deps, artifactsDir, runId),
1966
- maxSubagentDepth: recoveryDescriptor?.maxSubagentDepth ?? resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
2115
+ maxSubagentDepth: recoveryDescriptor?.maxSubagentDepth ?? resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth, input.deps.childRuntime),
1967
2116
  waitToolEnabled: input.deps.waitToolEnabled,
2117
+ waitToolDefaultTimeoutMs: input.deps.waitToolDefaultTimeoutMs,
1968
2118
  worktreeSetupHook: input.deps.config.worktreeSetupHook,
1969
2119
  worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
1970
2120
  worktreeBaseDir: input.deps.config.worktreeBaseDir,
1971
- worktree: input.params.worktree === true,
1972
- controlConfig: recoveryDescriptor?.controlConfig ?? resolveControlConfig(input.deps.config.control, input.params.control),
2121
+ baseRef: input.params.baseRef ?? recoveryDescriptor?.baseRef,
2122
+ worktreeProvider: input.deps.config.worktreeProvider,
2123
+ worktreeBranchPrefix: input.deps.config.worktreeBranchPrefix,
2124
+ // A retained async child already owns the recorded worktree. Resume it in
2125
+ // place rather than allocating a second provider worktree around it.
2126
+ worktree: input.params.worktree === true && !("managedWorktree" in target && target.managedWorktree === true),
2127
+ lane: input.params.lane ?? recoveryDescriptor?.lane,
2128
+ controlConfig: resolveRevivalControlConfig({ globalConfig: input.deps.config.control, requestedControl: input.params.control, recoveryControlConfig: recoveryDescriptor?.controlConfig }),
1973
2129
  intercomBridge: input.params.intercomBridge ?? recoveryDescriptor?.intercomBridge,
1974
2130
  controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : undefined,
1975
2131
  childIntercomTarget: intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : undefined,
1976
2132
  availableModels,
1977
- output: typeof input.params.output === "string" ? input.params.output : recoveryDescriptor?.outputPath,
1978
- outputMode: input.params.outputMode ?? recoveryDescriptor?.outputMode,
1979
- ...(recoveryDescriptor?.agentContract ? { agentContract: recoveryDescriptor.agentContract } : {}),
1980
- ...(recoveryDescriptor?.structuredOutputSchema ? { structuredOutputSchema: recoveryDescriptor.structuredOutputSchema } : {}),
2133
+ output: input.params.output !== undefined ? input.params.output : foregroundContract?.output ?? recoveryDescriptor?.outputPath,
2134
+ outputMode: input.params.outputMode ?? foregroundContract?.outputMode ?? recoveryDescriptor?.outputMode,
2135
+ ...(agentContract ? { agentContract } : {}),
2136
+ ...(outputSchema ? { structuredOutputSchema: outputSchema } : {}),
1981
2137
  ...(recoveryDescriptor?.skills ? { skills: [...recoveryDescriptor.skills] } : {}),
1982
- ...(recoveryDescriptor?.acceptance !== undefined && input.params.acceptance === undefined ? { acceptance: recoveryDescriptor.acceptance } : {}),
2138
+ ...(input.params.acceptance !== undefined ? { acceptance: input.params.acceptance } : foregroundContract?.acceptance !== undefined ? { acceptance: foregroundContract.acceptance } : recoveryDescriptor?.acceptance !== undefined ? { acceptance: recoveryDescriptor.acceptance } : {}),
1983
2139
  ...(input.params.timeoutMs !== undefined ? { timeoutMs: input.params.timeoutMs } : {}),
1984
2140
  ...(input.absoluteDeadlineAt !== undefined ? { absoluteDeadlineAt: input.absoluteDeadlineAt } : {}),
1985
- ...(input.params.turnBudget !== undefined ? { turnBudget: input.params.turnBudget } : {}),
1986
2141
  ...(input.params.toolBudget !== undefined ? { toolBudget: input.params.toolBudget } : {}),
1987
2142
  capabilityCeiling: intersectSubagentCapabilityCeilings("capabilityCeiling" in target ? target.capabilityCeiling : undefined, recoveryDescriptor?.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId)),
1988
2143
  runFanoutBudget: input.params.runFanoutBudget ?? recoveryDescriptor?.runFanoutBudget ?? createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(input.deps.config.maxSubagentSpawnsPerRun)),
@@ -2030,20 +2185,14 @@ async function resumeAsyncRun(input: {
2030
2185
  input.signal?.removeEventListener("abort", stopOnAbort);
2031
2186
  }
2032
2187
  fs.rmSync(resultPath, { force: true });
2033
- const totalCost = completed.totalCost;
2188
+ const usage = importedAsyncRootUsage(completed);
2034
2189
  const childResult: SingleResult = {
2035
2190
  index: 0,
2036
2191
  agent: completed.agent,
2192
+ ...(completed.sessionName ? { sessionName: completed.sessionName } : {}),
2037
2193
  task: effectiveFollowUp,
2038
2194
  exitCode: completed.exitCode,
2039
- usage: {
2040
- input: totalCost?.inputTokens ?? 0,
2041
- output: totalCost?.outputTokens ?? 0,
2042
- cacheRead: 0,
2043
- cacheWrite: 0,
2044
- cost: totalCost?.costUsd ?? 0,
2045
- turns: 0,
2046
- },
2195
+ usage,
2047
2196
  finalOutput: completed.output,
2048
2197
  outputState: completed.output.trim() ? "present" : "absent",
2049
2198
  ...(completed.error ? { error: completed.error } : {}),
@@ -2058,9 +2207,13 @@ async function resumeAsyncRun(input: {
2058
2207
  ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
2059
2208
  ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
2060
2209
  ...(completed.acceptance ? { acceptance: completed.acceptance } : {}),
2210
+ ...(completed.artifactPaths ? { artifactPaths: completed.artifactPaths } : {}),
2211
+ ...(completed.outputSaveError ? { outputSaveError: completed.outputSaveError } : {}),
2212
+ ...(completed.transcriptPath ? { transcriptPath: completed.transcriptPath } : {}),
2213
+ ...(completed.transcriptError ? { transcriptError: completed.transcriptError } : {}),
2061
2214
  };
2062
2215
  return {
2063
- content: [{ type: "text", text: completed.output || completed.error || `Revived ${target.source} subagent ${revivedId} completed without output.` }],
2216
+ content: [{ type: "text", text: completed.success ? completed.output || completed.error || `Revived ${target.source} subagent ${revivedId} completed without output.` : completed.error || completed.output || `Revived ${target.source} subagent ${revivedId} completed without output.` }],
2064
2217
  ...(completed.success ? {} : { isError: true }),
2065
2218
  details: {
2066
2219
  ...result.details,
@@ -2176,6 +2329,7 @@ async function emitForegroundResultIntercom(input: {
2176
2329
  if (!input.intercomBridge.active || !input.intercomBridge.resultDelivery || !input.intercomBridge.orchestratorTarget) return null;
2177
2330
  const children = input.results.flatMap((result, index) => result.detached ? [] : [omitUndefinedProperties({
2178
2331
  agent: result.agent,
2332
+ ...(result.sessionName ? { sessionName: result.sessionName } : {}),
2179
2333
  status: foregroundResultIntercomStatus(result),
2180
2334
  outputState: result.outputState ?? "unknown",
2181
2335
  summary: resultSummaryForIntercom(result),
@@ -2225,19 +2379,28 @@ async function maybeBuildForegroundIntercomReceipt(input: {
2225
2379
  };
2226
2380
  }
2227
2381
 
2228
- function canonicalizeAgentName(name: string, agents: AgentConfig[], diagnostics?: AgentDiscoveryDiagnostic[]): { name?: string; error?: string } {
2382
+ function diagnosticContextFromDiscovery(
2383
+ discovered: { agents: AgentConfig[]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] },
2384
+ cwd: string,
2385
+ scope: AgentScope,
2386
+ ): UnknownAgentDiagnosticContext {
2387
+ if (discovered.cwd && discovered.scope && discovered.directories) return unknownAgentDiagnosticContext({ ...discovered, cwd: discovered.cwd, scope: discovered.scope, directories: discovered.directories });
2388
+ return unknownAgentDiagnosticContext(discoverAgents(path.resolve(cwd), scope));
2389
+ }
2390
+
2391
+ function canonicalizeAgentName(name: string, agents: AgentConfig[], diagnostics: AgentDiscoveryDiagnostic[] | undefined, context: UnknownAgentDiagnosticContext): { name?: string; error?: string } {
2229
2392
  const resolved = resolveAgentName(name, agents);
2230
2393
  const candidates = resolved.error ? agents.filter((agent) => resolveAgentName(name, [agent]).agent) : resolved.agent;
2231
2394
  const diagnostic = findBlockingAgentDiagnostic(name, candidates, diagnostics);
2232
2395
  if (diagnostic) return { error: `Agent '${name}' has invalid configuration: ${diagnostic.error}` };
2233
2396
  if (resolved.error) return { error: resolved.error };
2234
- if (!resolved.agent) return { error: `Unknown agent: ${name}` };
2397
+ if (!resolved.agent) return { error: formatUnknownAgentError(name, context) };
2235
2398
  return { name: resolved.agent.name };
2236
2399
  }
2237
2400
 
2238
- function canonicalizeExecutionParams(params: SubagentParamsLike, agents: AgentConfig[], diagnostics?: AgentDiscoveryDiagnostic[]): { params?: SubagentParamsLike; error?: string } {
2401
+ function canonicalizeExecutionParams(params: SubagentParamsLike, agents: AgentConfig[], diagnostics: AgentDiscoveryDiagnostic[] | undefined, context: UnknownAgentDiagnosticContext): { params?: SubagentParamsLike; error?: string } {
2239
2402
  const resolve = (name: string, location?: string): { name?: string; error?: string } => {
2240
- const result = canonicalizeAgentName(name, agents, diagnostics);
2403
+ const result = canonicalizeAgentName(name, agents, diagnostics, context);
2241
2404
  return result.error && location ? { error: `${result.error} (${location})` } : result;
2242
2405
  };
2243
2406
  if (params.agent) {
@@ -2305,6 +2468,7 @@ function validateExecutionInput(
2305
2468
  hasTasks: boolean,
2306
2469
  hasSingle: boolean,
2307
2470
  allowClarifyTaskPrompt: boolean,
2471
+ context: UnknownAgentDiagnosticContext,
2308
2472
  ): AgentToolResult<Details> | null {
2309
2473
  if (Number(hasChain) + Number(hasTasks) + Number(hasSingle) !== 1) {
2310
2474
  return {
@@ -2330,7 +2494,7 @@ function validateExecutionInput(
2330
2494
 
2331
2495
  if (hasSingle && params.agent && !agents.find((agent) => agent.name === params.agent)) {
2332
2496
  return {
2333
- content: [{ type: "text", text: `Unknown agent: ${params.agent}` }],
2497
+ content: [{ type: "text", text: formatUnknownAgentError(params.agent, context) }],
2334
2498
  isError: true,
2335
2499
  details: { mode: "single" as const, results: [] },
2336
2500
  };
@@ -2341,7 +2505,7 @@ function validateExecutionInput(
2341
2505
  const task = params.tasks[i]!;
2342
2506
  if (!agents.find((agent) => agent.name === task.agent)) {
2343
2507
  return {
2344
- content: [{ type: "text", text: `Unknown agent: ${task.agent} (task ${i + 1})` }],
2508
+ content: [{ type: "text", text: `${formatUnknownAgentError(task.agent, context)} (task ${i + 1})` }],
2345
2509
  isError: true,
2346
2510
  details: { mode: "parallel" as const, results: [] },
2347
2511
  };
@@ -2386,7 +2550,7 @@ function validateExecutionInput(
2386
2550
  for (const agentName of stepAgents) {
2387
2551
  if (!agents.find((a) => a.name === agentName)) {
2388
2552
  return {
2389
- content: [{ type: "text", text: `Unknown agent: ${agentName} (step ${i + 1})` }],
2553
+ content: [{ type: "text", text: `${formatUnknownAgentError(agentName, context)} (step ${i + 1})` }],
2390
2554
  isError: true,
2391
2555
  details: { mode: "chain" as const, results: [] },
2392
2556
  };
@@ -2578,9 +2742,6 @@ function applySingleAgentLaunchDefaults(params: SubagentParamsLike, agents: Agen
2578
2742
  ? { timeoutMs: agent.defaultTimeoutMs }
2579
2743
  : {}),
2580
2744
  ...(parentTimeoutMs !== undefined ? { timeoutMs: parentTimeoutMs } : {}),
2581
- ...(params.turnBudget === undefined && agent.defaultTurnBudget !== undefined
2582
- ? { turnBudget: agent.defaultTurnBudget }
2583
- : {}),
2584
2745
  ...(params.acceptance === undefined && agent.defaultAcceptance !== undefined
2585
2746
  ? { acceptance: agent.defaultAcceptance }
2586
2747
  : {}),
@@ -2749,6 +2910,14 @@ function withResolvedContext(
2749
2910
  };
2750
2911
  }
2751
2912
 
2913
+ function withAggregatedToolUsage(result: AgentToolResult<Details>): AgentToolResult<Details> {
2914
+ if (result.details.results.length === 0) return result;
2915
+ const usage = sumResultsUsage(result.details.results);
2916
+ return usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0
2917
+ ? { ...result, usage: toAgentToolUsage(usage) }
2918
+ : result;
2919
+ }
2920
+
2752
2921
  function withForkThinkingNotes(
2753
2922
  result: AgentToolResult<Details>,
2754
2923
  downgrades: Map<number, string>,
@@ -2774,67 +2943,7 @@ function toExecutionErrorResult(params: SubagentParamsLike, error: unknown, cont
2774
2943
  );
2775
2944
  }
2776
2945
 
2777
- function collectChainSessionFiles(
2778
- chain: ChainStep[],
2779
- sessionFileForTask: ForkSessionFileForTask,
2780
- dynamicFanoutMaxItems?: number,
2781
- ): (string | undefined)[] {
2782
- const sessionFiles: (string | undefined)[] = [];
2783
- let flatIndex = 0;
2784
- for (const step of chain) {
2785
- if (isParallelStep(step)) {
2786
- for (const task of step.parallel) {
2787
- sessionFiles.push(sessionFileForTask(task.agent, flatIndex, task.model));
2788
- flatIndex++;
2789
- }
2790
- continue;
2791
- }
2792
- if (isDynamicParallelStep(step)) {
2793
- const maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
2794
- for (let itemIndex = 0; itemIndex < maxItems; itemIndex++) {
2795
- sessionFiles.push(sessionFileForTask(step.parallel.agent, flatIndex, step.parallel.model));
2796
- flatIndex++;
2797
- }
2798
- continue;
2799
- }
2800
- const sequential = step as SequentialStep;
2801
- sessionFiles.push(sessionFileForTask(sequential.agent, flatIndex, sequential.model));
2802
- flatIndex++;
2803
- }
2804
- return sessionFiles;
2805
- }
2806
-
2807
- function collectChainThinkingOverrides(
2808
- chain: ChainStep[],
2809
- thinkingOverrideForTask: ForkThinkingOverrideForTask,
2810
- dynamicFanoutMaxItems?: number,
2811
- ): (AgentConfig["thinking"] | undefined)[] {
2812
- const thinkingOverrides: (AgentConfig["thinking"] | undefined)[] = [];
2813
- let flatIndex = 0;
2814
- for (const step of chain) {
2815
- if (isParallelStep(step)) {
2816
- for (const task of step.parallel) {
2817
- thinkingOverrides.push(thinkingOverrideForTask(task.agent, flatIndex, task.model));
2818
- flatIndex++;
2819
- }
2820
- continue;
2821
- }
2822
- if (isDynamicParallelStep(step)) {
2823
- const maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
2824
- for (let itemIndex = 0; itemIndex < maxItems; itemIndex++) {
2825
- thinkingOverrides.push(thinkingOverrideForTask(step.parallel.agent, flatIndex, step.parallel.model));
2826
- flatIndex++;
2827
- }
2828
- continue;
2829
- }
2830
- const sequential = step as SequentialStep;
2831
- thinkingOverrides.push(thinkingOverrideForTask(sequential.agent, flatIndex, sequential.model));
2832
- flatIndex++;
2833
- }
2834
- return thinkingOverrides;
2835
- }
2836
-
2837
- type StaticLaunchSummary = { agent: string; model?: string; thinking?: string };
2946
+ type StaticLaunchSummary = { agent: string; model?: string; thinking?: string; sandbox?: string };
2838
2947
 
2839
2948
  function resolveStaticLaunchSummary(input: {
2840
2949
  agent: string;
@@ -2866,6 +2975,7 @@ function resolveStaticLaunchSummary(input: {
2866
2975
  agent: input.agent,
2867
2976
  ...(model ? { model } : {}),
2868
2977
  ...(thinking ? { thinking } : {}),
2978
+ ...(agentConfig?.sandbox ? { sandbox: agentConfig.sandbox } : {}),
2869
2979
  };
2870
2980
  }
2871
2981
 
@@ -2919,14 +3029,6 @@ function collectStaticLaunchSummaries(input: {
2919
3029
  return input.params.agent ? [summary(input.params.agent, 0, input.params.model as string | undefined)] : [];
2920
3030
  }
2921
3031
 
2922
- function firstChainAgent(chain: ChainStep[]): string | undefined {
2923
- const first = chain[0];
2924
- if (!first) return undefined;
2925
- if (isParallelStep(first)) return first.parallel[0]?.agent;
2926
- if (isDynamicParallelStep(first)) return first.parallel.agent;
2927
- return (first as SequentialStep).agent;
2928
- }
2929
-
2930
3032
  function firstRawChainTask(chain: ChainStep[]): string | undefined {
2931
3033
  const first = chain[0];
2932
3034
  if (!first) return undefined;
@@ -2977,21 +3079,29 @@ function wrapChainTasksForFork(chain: ChainStep[], contextPolicy: AgentDefaultCo
2977
3079
  });
2978
3080
  }
2979
3081
 
2980
- function preflightForkSessionsForStaticTasks(
3082
+ async function preflightForkSessionsForStaticTasks(
2981
3083
  params: SubagentParamsLike,
2982
3084
  contextPolicy: AgentDefaultContextPolicy,
2983
- sessionFileForTask: ForkSessionFileForTask,
3085
+ prepareSessionForTask: PrepareForkSessionForTask,
2984
3086
  dynamicFanoutMaxItems?: number,
2985
- ): void {
3087
+ ): Promise<void> {
2986
3088
  if (!contextPolicy.usesFork) return;
2987
3089
  if (params.agent) {
2988
- if (shouldForkAgent(contextPolicy, params.agent)) sessionFileForTask(params.agent, 0, params.model);
3090
+ if (shouldForkAgent(contextPolicy, params.agent)) {
3091
+ await prepareSessionForTask(
3092
+ params.agent,
3093
+ 0,
3094
+ params.model,
3095
+ params.modelOrigin === "inherited",
3096
+ params.modelOrigin,
3097
+ );
3098
+ }
2989
3099
  return;
2990
3100
  }
2991
3101
  if (params.tasks) {
2992
- params.tasks.forEach((task, index) => {
2993
- if (shouldForkAgent(contextPolicy, task.agent)) sessionFileForTask(task.agent, index, task.model);
2994
- });
3102
+ for (const [index, task] of params.tasks.entries()) {
3103
+ if (shouldForkAgent(contextPolicy, task.agent)) await prepareSessionForTask(task.agent, index, task.model);
3104
+ }
2995
3105
  return;
2996
3106
  }
2997
3107
  if (!params.chain?.length) return;
@@ -2999,7 +3109,7 @@ function preflightForkSessionsForStaticTasks(
2999
3109
  for (const step of params.chain) {
3000
3110
  if (isParallelStep(step)) {
3001
3111
  for (const task of step.parallel) {
3002
- if (shouldForkAgent(contextPolicy, task.agent)) sessionFileForTask(task.agent, flatIndex, task.model);
3112
+ if (shouldForkAgent(contextPolicy, task.agent)) await prepareSessionForTask(task.agent, flatIndex, task.model);
3003
3113
  flatIndex++;
3004
3114
  }
3005
3115
  continue;
@@ -3007,17 +3117,29 @@ function preflightForkSessionsForStaticTasks(
3007
3117
  if (isDynamicParallelStep(step)) {
3008
3118
  const maxItems = step.expand.maxItems ?? dynamicFanoutMaxItems ?? 0;
3009
3119
  if (shouldForkAgent(contextPolicy, step.parallel.agent)) {
3010
- for (let itemIndex = 0; itemIndex < maxItems; itemIndex++) sessionFileForTask(step.parallel.agent, flatIndex + itemIndex, step.parallel.model);
3120
+ for (let itemIndex = 0; itemIndex < maxItems; itemIndex++) await prepareSessionForTask(step.parallel.agent, flatIndex + itemIndex, step.parallel.model);
3011
3121
  }
3012
3122
  flatIndex += maxItems;
3013
3123
  continue;
3014
3124
  }
3015
3125
  const sequential = step as SequentialStep;
3016
- if (shouldForkAgent(contextPolicy, sequential.agent)) sessionFileForTask(sequential.agent, flatIndex, sequential.model);
3126
+ if (shouldForkAgent(contextPolicy, sequential.agent)) await prepareSessionForTask(sequential.agent, flatIndex, sequential.model);
3017
3127
  flatIndex++;
3018
3128
  }
3019
3129
  }
3020
3130
 
3131
+ function importedAsyncRootUsage(completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>): Usage {
3132
+ const totalCost = completed.totalCost;
3133
+ return completed.usage ?? {
3134
+ input: totalCost?.inputTokens ?? 0,
3135
+ output: totalCost?.outputTokens ?? 0,
3136
+ cacheRead: 0,
3137
+ cacheWrite: 0,
3138
+ cost: totalCost?.costUsd ?? 0,
3139
+ turns: 0,
3140
+ };
3141
+ }
3142
+
3021
3143
  async function waitForWorkflowAsyncSingleResult(
3022
3144
  params: SubagentParamsLike,
3023
3145
  launchResult: AgentToolResult<Details>,
@@ -3039,20 +3161,14 @@ async function waitForWorkflowAsyncSingleResult(
3039
3161
  options.signal?.removeEventListener("abort", stopOnAbort);
3040
3162
  }
3041
3163
  fs.rmSync(resultPath, { force: true });
3042
- const totalCost = completed.totalCost;
3164
+ const usage = importedAsyncRootUsage(completed);
3043
3165
  const childResult: SingleResult = omitUndefinedProperties({
3044
3166
  index: 0,
3045
3167
  agent: completed.agent,
3168
+ ...(completed.sessionName ? { sessionName: completed.sessionName } : {}),
3046
3169
  task: options.task,
3047
3170
  exitCode: completed.exitCode,
3048
- usage: {
3049
- input: totalCost?.inputTokens ?? 0,
3050
- output: totalCost?.outputTokens ?? 0,
3051
- cacheRead: 0,
3052
- cacheWrite: 0,
3053
- cost: totalCost?.costUsd ?? 0,
3054
- turns: 0,
3055
- },
3171
+ usage,
3056
3172
  finalOutput: completed.output,
3057
3173
  outputState: completed.output.trim() ? "present" as const : "absent" as const,
3058
3174
  ...(completed.error ? { error: completed.error } : {}),
@@ -3067,9 +3183,13 @@ async function waitForWorkflowAsyncSingleResult(
3067
3183
  ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
3068
3184
  ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
3069
3185
  ...(completed.acceptance ? { acceptance: completed.acceptance } : {}),
3186
+ ...(completed.artifactPaths ? { artifactPaths: completed.artifactPaths } : {}),
3187
+ ...(completed.outputSaveError ? { outputSaveError: completed.outputSaveError } : {}),
3188
+ ...(completed.transcriptPath ? { transcriptPath: completed.transcriptPath } : {}),
3189
+ ...(completed.transcriptError ? { transcriptError: completed.transcriptError } : {}),
3070
3190
  });
3071
3191
  return {
3072
- content: [{ type: "text", text: completed.output || completed.error || `Async workflow child ${options.runId} completed without output.` }],
3192
+ content: [{ type: "text", text: completed.success ? completed.output || completed.error || `Async workflow child ${options.runId} completed without output.` : completed.error || completed.output || `Async workflow child ${options.runId} completed without output.` }],
3073
3193
  ...(completed.success ? {} : { isError: true }),
3074
3194
  details: {
3075
3195
  ...launchResult.details,
@@ -3087,7 +3207,6 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3087
3207
  ctx,
3088
3208
  shareEnabled,
3089
3209
  sessionRoot,
3090
- sessionFileForIndex,
3091
3210
  sessionFileForTask,
3092
3211
  thinkingOverrideForTask,
3093
3212
  artifactConfig,
@@ -3097,6 +3216,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3097
3216
  intercomBridge,
3098
3217
  nestedRoute,
3099
3218
  contextPolicy,
3219
+ unknownAgentDiagnosticContext,
3100
3220
  } = data;
3101
3221
  const hasChain = (params.chain?.length ?? 0) > 0;
3102
3222
  const hasTasks = (params.tasks?.length ?? 0) > 0;
@@ -3121,11 +3241,14 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3121
3241
  currentModelProvider: parentModel?.provider,
3122
3242
  currentModel: parentModel,
3123
3243
  modelScope: data.modelScope,
3244
+ projectTrusted: currentProjectTrusted(ctx),
3245
+ ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3124
3246
  interactive: ctx.hasUI,
3125
3247
  permissions: deps.config.permissions,
3248
+ childRuntime: deps.childRuntime,
3126
3249
  });
3127
3250
  const availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);
3128
- const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);
3251
+ const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth, deps.childRuntime);
3129
3252
  const currentProvider = parentModel?.provider;
3130
3253
  const controlIntercomTarget = resolveRunLevelIntercomTarget(intercomBridge, contextPolicy);
3131
3254
  const childIntercomTarget = resolveChildIntercomTargetFactory(intercomBridge, contextPolicy, id);
@@ -3135,11 +3258,17 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3135
3258
  const a = agents.find((x) => x.name === params.agent);
3136
3259
  if (!a) {
3137
3260
  return {
3138
- content: [{ type: "text", text: `Unknown agent: ${params.agent}` }],
3261
+ content: [{ type: "text", text: formatUnknownAgentError(params.agent!, unknownAgentDiagnosticContext) }],
3139
3262
  isError: true,
3140
3263
  details: { mode: "single" as const, results: [] },
3141
3264
  };
3142
3265
  }
3266
+ const sandboxTrustError = params.worktree === true
3267
+ ? sandboxProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
3268
+ : sandboxProfileTrustError(a, ctx, effectiveCwd);
3269
+ if (sandboxTrustError) {
3270
+ return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single" as const, results: [] } };
3271
+ }
3143
3272
  const rawOutput = params.output !== undefined ? params.output : a.output;
3144
3273
  const effectiveOutput = normalizeSingleOutputOverride(rawOutput, a.output);
3145
3274
  const effectiveOutputMode = params.outputMode ?? a.outputMode ?? "inline";
@@ -3153,10 +3282,21 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3153
3282
  return buildRequestedModeError(params, `Agent '${a.name}' uses runner.type='${a.runner.type}' and does not support fast mode.`);
3154
3283
  }
3155
3284
  const modelScopes = resolveModelScopesForAgent(data.modelScope, a.name, parentModel);
3285
+ const modelOrigin = resolveModelOrigin({
3286
+ storedOrigin: params.modelOrigin as ModelOrigin | undefined,
3287
+ explicitModel: params.model as string | undefined,
3288
+ agentModel: a.model,
3289
+ parentModel,
3290
+ });
3156
3291
  const modelOverride = a.runner?.type === "external-cli" || a.runner?.type === "external-job"
3157
3292
  ? params.model ?? (externalRunnerWithoutExplicitModel ? undefined : a.model)
3158
- : resolveEffectiveSubagentModel(params.model as string | undefined, a.model, parentModel, availableModels, a.modelProvider ?? currentProvider, modelScopes.length === 0 ? {} : { scope: modelScopes });
3159
- const modelOverrideFromParent = inheritsParentModel(params.model as string | undefined, a.model, parentModel);
3293
+ : resolveEffectiveSubagentModel(params.model as string | undefined, a.model, parentModel, availableModels, a.modelProvider ?? currentProvider, {
3294
+ ...(modelScopes.length === 0 ? {} : { scope: modelScopes }),
3295
+ source: modelOrigin === "explicit" ? "explicit" : "inherited",
3296
+ });
3297
+ const modelOverrideFromParent = modelOrigin === "inherited";
3298
+ const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: a.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
3299
+ if (launchRuleError) return toExecutionErrorResult(params, new Error(launchRuleError), data.contextPolicy.contextSummary);
3160
3300
  const asyncResult = executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
3161
3301
  agent: params.agent!,
3162
3302
  task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(params.task ?? "") : (params.task ?? ""),
@@ -3166,30 +3306,37 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3166
3306
  ctx: asyncCtx,
3167
3307
  availableModels,
3168
3308
  cwd: effectiveCwd,
3309
+ requestedCwd: data.requestedCwd,
3169
3310
  maxOutput: params.maxOutput,
3170
3311
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3171
3312
  artifactConfig,
3172
3313
  shareEnabled,
3173
3314
  activeAsyncCapacity: data.activeAsyncCapacity,
3174
3315
  sessionRoot,
3175
- sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
3316
+ sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
3176
3317
  context: contextPolicy.contextForAgent(params.agent!),
3177
3318
  skills,
3178
3319
  output: effectiveOutput,
3179
3320
  outputMode: effectiveOutputMode,
3321
+ outputClaimPath: params.workflowOutputClaimPath,
3180
3322
  ...(params.reads !== undefined ? { reads: params.reads } : {}),
3181
3323
  outputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),
3182
3324
  modelOverride,
3183
3325
  fast: params.fast,
3184
3326
  modelOverrideFromParent,
3185
- thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
3327
+ modelOrigin,
3328
+ thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
3186
3329
  thinkingCeiling: a.maxThinking,
3187
3330
  maxSubagentDepth,
3188
3331
  waitToolEnabled: deps.waitToolEnabled,
3332
+ waitToolDefaultTimeoutMs: deps.waitToolDefaultTimeoutMs,
3189
3333
  ...(params.worktree === true ? { worktree: true } : {}),
3190
3334
  worktreeSetupHook: deps.config.worktreeSetupHook,
3191
3335
  worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
3192
3336
  worktreeBaseDir: deps.config.worktreeBaseDir,
3337
+ baseRef: params.baseRef,
3338
+ worktreeProvider: deps.config.worktreeProvider,
3339
+ worktreeBranchPrefix: deps.config.worktreeBranchPrefix,
3193
3340
  controlConfig,
3194
3341
  intercomBridge: params.intercomBridge,
3195
3342
  controlIntercomTarget,
@@ -3200,7 +3347,6 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3200
3347
  extensionBindings: params.extensionBindings,
3201
3348
  acceptance: params.acceptance,
3202
3349
  timeoutMs: data.timeoutMs,
3203
- turnBudget: data.turnBudget,
3204
3350
  toolBudget: data.toolBudget,
3205
3351
  usageBudget: data.usageBudget,
3206
3352
  configToolBudget: data.configToolBudget,
@@ -3210,6 +3356,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3210
3356
  runFanoutBudget: data.runFanoutBudget,
3211
3357
  parentWorkflowRunId: params.workflowParentRunId,
3212
3358
  workflowKey: params.workflowKey,
3359
+ lane: params.lane,
3213
3360
  workflowAwaitAsync: params.workflowAwaitAsync,
3214
3361
  }));
3215
3362
  return waitForWorkflowAsyncSingleResult(params, asyncResult, { runId: id, task: params.task ?? "", signal: data.signal, state: deps.state, kill: deps.kill });
@@ -3226,6 +3373,12 @@ function createSingleWorktreeSetup(
3226
3373
  setupHook: ExtensionConfig["worktreeSetupHook"],
3227
3374
  setupHookTimeoutMs: ExtensionConfig["worktreeSetupHookTimeoutMs"],
3228
3375
  baseDir: ExtensionConfig["worktreeBaseDir"],
3376
+ baseRef: string | undefined,
3377
+ provider: ExtensionConfig["worktreeProvider"],
3378
+ branchPrefix: ExtensionConfig["worktreeBranchPrefix"],
3379
+ label?: string,
3380
+ task?: string,
3381
+ beforeCreate?: (setup: WorktreeSetup) => void,
3229
3382
  ): { setup?: WorktreeSetup; errorResult?: AgentToolResult<Details> } {
3230
3383
  if (!enabled) return {};
3231
3384
  try {
@@ -3236,6 +3389,12 @@ function createSingleWorktreeSetup(
3236
3389
  ? { hookPath: setupHook, ...(setupHookTimeoutMs === undefined ? {} : { timeoutMs: setupHookTimeoutMs }) }
3237
3390
  : undefined,
3238
3391
  baseDir,
3392
+ baseRef,
3393
+ provider,
3394
+ branchPrefix,
3395
+ labels: [label],
3396
+ tasks: [task],
3397
+ beforeCreate,
3239
3398
  })),
3240
3399
  };
3241
3400
  } catch (error) {
@@ -3278,10 +3437,33 @@ function workflowChildDefaultOutput(aggregateOutputPath: string | undefined, art
3278
3437
  return path.join(artifactsDir, "outputs", sanitizeRunPathSegment(workflowRunId), `${workflowKey}.md`);
3279
3438
  }
3280
3439
 
3440
+ function workflowHostCommandRunner(input: {
3441
+ workflowCwd: string;
3442
+ artifactsDir: string;
3443
+ workflowRunId: string;
3444
+ claimedOutputPaths: Map<string, string>;
3445
+ producedOutputPaths: Set<string>;
3446
+ authorize?: (key: string, params: WorkflowHostCommandParams) => string | undefined;
3447
+ }) {
3448
+ return async (key: string, params: WorkflowHostCommandParams, signal: AbortSignal): Promise<WorkflowHostCommandResult> => {
3449
+ const authorizationError = input.authorize?.(key, params);
3450
+ if (authorizationError) throw new Error(authorizationError);
3451
+ const defaultOutputPath = path.join(input.artifactsDir, "outputs", sanitizeRunPathSegment(input.workflowRunId), "host", `${sanitizeRunPathSegment(key)}.log`);
3452
+ const outputPath = params.output ? path.resolve(input.workflowCwd, params.output) : defaultOutputPath;
3453
+ const claimPath = resolveWorkflowHostOutputClaimPath(outputPath);
3454
+ const previous = input.claimedOutputPaths.get(claimPath);
3455
+ if (previous) throw new Error(`runs.host('${key}') output path is already claimed by '${previous}': ${outputPath}.`);
3456
+ input.claimedOutputPaths.set(claimPath, `host:${key}`);
3457
+ const result = await executeWorkflowHostCommand({ key, params, cwd: input.workflowCwd, defaultOutputPath, claimedOutputPath: claimPath, signal });
3458
+ input.producedOutputPaths.add(resolveWorkflowHostOutputClaimPath(result.outputPath));
3459
+ return result;
3460
+ };
3461
+ }
3462
+
3281
3463
  function writeWorkflowAggregateOutput(outputPath: string | undefined, text: string, producedChildOutputPaths: ReadonlySet<string>): string | undefined {
3282
3464
  if (!outputPath) return undefined;
3283
3465
  try {
3284
- if (producedChildOutputPaths.has(outputPath)) return undefined;
3466
+ if (producedChildOutputPaths.has(resolveWorkflowHostOutputClaimPath(outputPath))) return undefined;
3285
3467
  fs.mkdirSync(path.dirname(outputPath), { recursive: true });
3286
3468
  fs.writeFileSync(outputPath, text, "utf-8");
3287
3469
  return undefined;
@@ -3352,7 +3534,7 @@ function workflowChildOutputClaims(input: {
3352
3534
  state: SubagentState;
3353
3535
  claimedOutputPaths: Map<string, string>;
3354
3536
  entries: Array<{ key: string; params: Record<string, unknown> }>;
3355
- }): { error?: string; claims?: Map<string, string>; overrides?: Map<string, string> } {
3537
+ }): { error?: string; claims?: Map<string, string>; childClaims?: Map<string, string>; overrides?: Map<string, string> } {
3356
3538
  const resolvedEntries = input.entries.map(({ key, params }) => ({
3357
3539
  key,
3358
3540
  ...resolveWorkflowChildOutputPath({ ...input, key, params }),
@@ -3360,24 +3542,30 @@ function workflowChildOutputClaims(input: {
3360
3542
  const paths = new Map<string, number>();
3361
3543
  for (const claimedPath of input.claimedOutputPaths.keys()) paths.set(claimedPath, 1);
3362
3544
  for (const { path: resolved } of resolvedEntries) {
3363
- if (resolved) paths.set(resolved, (paths.get(resolved) ?? 0) + 1);
3545
+ if (resolved) {
3546
+ const claimPath = resolveWorkflowHostOutputClaimPath(resolved);
3547
+ paths.set(claimPath, (paths.get(claimPath) ?? 0) + 1);
3548
+ }
3364
3549
  }
3365
3550
  const overrides = new Map<string, string>();
3366
3551
  for (const entry of resolvedEntries) {
3367
- if (entry.inherited && entry.path && (paths.get(entry.path) ?? 0) > 1) {
3552
+ if (entry.inherited && entry.path && (paths.get(resolveWorkflowHostOutputClaimPath(entry.path)) ?? 0) > 1) {
3368
3553
  const output = workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.workflowRunId, entry.key);
3369
3554
  overrides.set(entry.key, output);
3370
3555
  entry.path = output;
3371
3556
  }
3372
3557
  }
3373
3558
  const claims = new Map(input.claimedOutputPaths);
3559
+ const childClaims = new Map<string, string>();
3374
3560
  for (const { key, path: resolved } of resolvedEntries) {
3375
3561
  if (!resolved) continue;
3376
- const previous = claims.get(resolved);
3562
+ const claimPath = resolveWorkflowHostOutputClaimPath(resolved);
3563
+ const previous = claims.get(claimPath);
3377
3564
  if (previous) return { error: `Workflow children '${previous}' and '${key}' resolve output to the same path: ${resolved}. Use distinct child output paths.` };
3378
- claims.set(resolved, key);
3565
+ claims.set(claimPath, key);
3566
+ childClaims.set(key, claimPath);
3379
3567
  }
3380
- return { claims, overrides };
3568
+ return { claims, childClaims, overrides };
3381
3569
  }
3382
3570
 
3383
3571
  function applyWorkflowChildOutputClaims(target: Map<string, string>, claims: Map<string, string>): void {
@@ -3399,12 +3587,14 @@ function prepareWorkflowChildLaunchParams(input: {
3399
3587
  agents: AgentConfig[];
3400
3588
  workflowAgentScope?: unknown;
3401
3589
  outputOverride?: string;
3402
- options?: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number; capabilityCeiling?: ResolvedSubagentCapabilityCeiling };
3590
+ outputClaimPath?: string;
3591
+ options?: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; awaitDetachedChild?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number; capabilityCeiling?: ResolvedSubagentCapabilityCeiling };
3403
3592
  }): SubagentParamsLike {
3404
3593
  let childParams = input.childParams;
3405
- if (input.childParams.output === undefined && input.childParams.resume === undefined && input.outputOverride !== undefined) {
3594
+ const usesDefaultOutput = input.childParams.output === undefined && input.childParams.resume === undefined;
3595
+ if (usesDefaultOutput && input.outputOverride !== undefined) {
3406
3596
  childParams = { ...input.childParams, output: input.outputOverride };
3407
- } else if (input.childParams.output === undefined && input.childParams.resume === undefined && input.aggregateOutputPath !== undefined) {
3597
+ } else if (usesDefaultOutput && input.aggregateOutputPath !== undefined) {
3408
3598
  childParams = { ...input.childParams, output: workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.parentWorkflowRunId, input.workflowKey) };
3409
3599
  } else if (input.childParams.resume === undefined) {
3410
3600
  const resolvedOutput = resolveWorkflowChildOutputPath({ ctxCwd: input.ctxCwd, workflowCwd: input.workflowCwd, artifactsDir: input.artifactsDir, workflowRunId: input.parentWorkflowRunId, aggregateOutputPath: input.aggregateOutputPath, configuredOutputBaseDir: input.configuredOutputBaseDir, discoverAgents: input.discoverAgents, agents: input.agents, workflowAgentScope: input.workflowAgentScope, key: input.workflowKey, params: input.childParams });
@@ -3417,7 +3607,7 @@ function prepareWorkflowChildLaunchParams(input: {
3417
3607
  ? resolveAgentName(childParams.agent, discoveredAgents).agent ?? resolveAgentName(childParams.agent, input.agents).agent
3418
3608
  : undefined;
3419
3609
  const externalAsyncRequired = agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job";
3420
- return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, { ...input.options, externalAsyncRequired });
3610
+ return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, { ...input.options, externalAsyncRequired, outputClaimPath: input.outputClaimPath });
3421
3611
  }
3422
3612
 
3423
3613
  function finalizeSingleWorktreeHandoff(input: {
@@ -3427,6 +3617,8 @@ function finalizeSingleWorktreeHandoff(input: {
3427
3617
  cwd: string;
3428
3618
  agent: string;
3429
3619
  result: SingleResult;
3620
+ workflowKey?: string;
3621
+ lane?: import("../../shared/types.ts").WorkflowLaneMetadata;
3430
3622
  }): { suffix: string; reference?: NonNullable<Details["parallelHandoff"]> } {
3431
3623
  const diffsDir = path.join(input.artifactsDir, "worktree-diffs", input.runId);
3432
3624
  const diffs = diffWorktrees(input.worktreeSetup, [input.agent], diffsDir);
@@ -3441,9 +3633,13 @@ function finalizeSingleWorktreeHandoff(input: {
3441
3633
  stepIndex: 0,
3442
3634
  flatStartIndex: 0,
3443
3635
  setup: input.worktreeSetup,
3636
+ laneBindings: input.workflowKey || input.lane ? [{ index: 0, taskIndex: 0, ...(input.workflowKey ? { workflowKey: input.workflowKey } : {}), runId: input.workflowKey ? input.runId : undefined, ...(input.lane ? { lane: input.lane } : {}) }] : undefined,
3444
3637
  diffs,
3445
3638
  results: [{
3446
3639
  agent: input.result.agent,
3640
+ ...(input.workflowKey ? { workflowKey: input.workflowKey } : {}),
3641
+ ...(input.workflowKey ? { runId: input.runId } : {}),
3642
+ ...(input.lane ? { lane: input.lane } : {}),
3447
3643
  status: resolveSubagentResultStatus(omitUndefinedProperties({
3448
3644
  exitCode: input.result.exitCode,
3449
3645
  interrupted: input.result.interrupted,
@@ -3489,10 +3685,17 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3489
3685
  artifactConfig,
3490
3686
  artifactsDir,
3491
3687
  onUpdate,
3492
- sessionRoot,
3493
3688
  controlConfig,
3494
3689
  contextPolicy,
3690
+ suppressUnchangedDelegationUpdates,
3495
3691
  } = data;
3692
+ let lane: import("../../shared/types.ts").WorkflowLaneMetadata | undefined;
3693
+ try {
3694
+ lane = normalizeWorkflowLaneMetadata(params.lane, "lane");
3695
+ assertWorkflowLaneKey(lane, params.workflowKey, "lane");
3696
+ } catch (error) {
3697
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "single", results: [] } };
3698
+ }
3496
3699
  const onControlEvent = createForegroundControlNotifier(data, deps);
3497
3700
  const childBridgeActive = intercomBridgeAppliesToAgent(data.intercomBridge, contextPolicy, params.agent!);
3498
3701
  const childIntercomTarget = childBridgeActive ? resolveSubagentIntercomTarget(runId, params.agent!, 0) : undefined;
@@ -3501,7 +3704,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3501
3704
  const agentConfig = agents.find((a) => a.name === params.agent);
3502
3705
  if (!agentConfig) {
3503
3706
  return {
3504
- content: [{ type: "text", text: `Unknown agent: ${params.agent}` }],
3707
+ content: [{ type: "text", text: formatUnknownAgentError(params.agent!, data.unknownAgentDiagnosticContext) }],
3505
3708
  isError: true,
3506
3709
  details: { mode: "single", results: [] },
3507
3710
  };
@@ -3513,26 +3716,38 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3513
3716
  const currentProvider = parentModel?.provider;
3514
3717
  const availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);
3515
3718
  const modelScopes = resolveModelScopesForAgent(data.modelScope, agentConfig.name, parentModel);
3516
- let task = params.task ?? "";
3719
+ let task = typeof params.task === "string" ? params.task : "";
3720
+ const modelOrigin = resolveModelOrigin({
3721
+ storedOrigin: params.modelOrigin as ModelOrigin | undefined,
3722
+ explicitModel: params.model as string | undefined,
3723
+ agentModel: agentConfig.model,
3724
+ parentModel,
3725
+ });
3517
3726
  let modelOverride: string | undefined = resolveEffectiveSubagentModel(
3518
3727
  params.model as string | undefined,
3519
3728
  agentConfig.model,
3520
3729
  parentModel,
3521
3730
  availableModels,
3522
3731
  agentConfig.modelProvider ?? currentProvider,
3523
- modelScopes.length === 0 ? {} : { scope: modelScopes },
3732
+ {
3733
+ ...(modelScopes.length === 0 ? {} : { scope: modelScopes }),
3734
+ source: modelOrigin === "explicit" ? "explicit" : "inherited",
3735
+ },
3524
3736
  );
3525
- const modelOverrideFromParent = inheritsParentModel(params.model as string | undefined, agentConfig.model, parentModel);
3737
+ const modelOverrideFromParent = modelOrigin === "inherited";
3738
+ const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: agentConfig.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
3739
+ if (launchRuleError) return toExecutionErrorResult(params, new Error(launchRuleError), data.contextPolicy.contextSummary);
3526
3740
  let skillOverride: string[] | false | undefined = normalizeSkillInput(params.skill);
3527
3741
  let readsOverride: string[] | false | undefined = params.reads;
3528
3742
  const rawOutput = params.output !== undefined ? params.output : agentConfig.output;
3529
3743
  let effectiveOutput = normalizeSingleOutputOverride(rawOutput, agentConfig.output);
3530
3744
  const effectiveOutputMode = params.outputMode ?? agentConfig.outputMode ?? "inline";
3531
- const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth);
3745
+ const currentMaxSubagentDepth = resolveCurrentMaxSubagentDepth(deps.config.maxSubagentDepth, deps.childRuntime);
3532
3746
  const maxSubagentDepth = resolveChildMaxSubagentDepth(currentMaxSubagentDepth, agentConfig.maxSubagentDepth);
3533
3747
 
3534
3748
 
3535
3749
  const sourceCwd = effectiveCwd;
3750
+ let pendingHandoff: Details["parallelHandoff"];
3536
3751
  const { setup: worktreeSetup, errorResult: worktreeSetupError } = createSingleWorktreeSetup(
3537
3752
  params.worktree,
3538
3753
  sourceCwd,
@@ -3541,12 +3756,12 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3541
3756
  deps.config.worktreeSetupHook,
3542
3757
  deps.config.worktreeSetupHookTimeoutMs,
3543
3758
  deps.config.worktreeBaseDir,
3544
- );
3545
- if (worktreeSetupError) return worktreeSetupError;
3546
- const singleCwd = worktreeSetup?.worktrees[0]?.agentCwd ?? sourceCwd;
3547
- let pendingHandoff: Details["parallelHandoff"];
3548
- if (worktreeSetup) {
3549
- try {
3759
+ params.baseRef,
3760
+ deps.config.worktreeProvider,
3761
+ deps.config.worktreeBranchPrefix,
3762
+ params.lane?.key ?? params.workflowKey,
3763
+ task,
3764
+ (plannedSetup) => {
3550
3765
  pendingHandoff = writePendingParallelHandoff({
3551
3766
  manifestPath: parallelHandoffPath(artifactsDir, runId),
3552
3767
  runId,
@@ -3555,12 +3770,17 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3555
3770
  cwd: sourceCwd,
3556
3771
  stepIndex: 0,
3557
3772
  flatStartIndex: 0,
3558
- setup: worktreeSetup,
3773
+ setup: plannedSetup,
3774
+ laneBindings: params.workflowKey || lane ? [{ index: 0, taskIndex: 0, ...(params.workflowKey ? { workflowKey: params.workflowKey, runId } : {}), ...(lane ? { lane } : {}) }] : undefined,
3559
3775
  });
3560
- } catch (error) {
3561
- cleanupWorktrees(worktreeSetup);
3562
- return { content: [{ type: "text", text: formatParallelHandoffError(error) }], isError: true, details: { mode: "single", results: [] } };
3563
- }
3776
+ },
3777
+ );
3778
+ if (worktreeSetupError) return worktreeSetupError;
3779
+ const singleCwd = worktreeSetup?.worktrees[0]?.agentCwd ?? sourceCwd;
3780
+ const sandboxTrustError = sandboxProfileTrustError(agentConfig, ctx, singleCwd);
3781
+ if (sandboxTrustError) {
3782
+ if (worktreeSetup) cleanupWorktrees(worktreeSetup);
3783
+ return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single", results: [] } };
3564
3784
  }
3565
3785
 
3566
3786
  const authoredTask = task;
@@ -3575,7 +3795,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3575
3795
  return { content: [{ type: "text", text: validationError }], isError: true, details: { mode: "single", results: [] } };
3576
3796
  }
3577
3797
  const structuredRuntime = params.outputSchema
3578
- ? createStructuredOutputRuntime(params.outputSchema, artifactConfig.enabled ? path.join(artifactsDir, "structured-output", runId) : undefined, { captureAcceptanceReport: params.acceptance !== false })
3798
+ ? createStructuredOutputRuntime(params.outputSchema, artifactConfig.enabled ? path.join(artifactsDir, "structured-output", runId) : undefined, { acceptanceReport: resolveAcceptanceReportMode(params.acceptance) })
3579
3799
  : undefined;
3580
3800
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
3581
3801
  // absolute paths pass through; relative paths resolve against the child cwd.
@@ -3595,9 +3815,10 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3595
3815
  }
3596
3816
  const interruptController = new AbortController();
3597
3817
  let detachForeground: ((reason?: string) => boolean) | undefined;
3818
+ let childSessionControls: ForegroundChildSessionControls | undefined;
3598
3819
  const foregroundControl = deps.state.foregroundControls.get(runId);
3599
3820
  if (foregroundControl) {
3600
- const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent));
3821
+ const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin));
3601
3822
  beginForegroundChild(foregroundControl, omitUndefinedProperties({
3602
3823
  index: 0,
3603
3824
  agent: params.agent!,
@@ -3615,6 +3836,19 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3615
3836
  return true;
3616
3837
  },
3617
3838
  detach: () => detachForeground?.("user request") === true,
3839
+ steer: async (input: ForegroundSteerInput): Promise<ForegroundSteerOutcome> => {
3840
+ if (!childSessionControls) return { state: "failed", reason: CHILD_SESSION_NOT_RUNNING_YET };
3841
+ try {
3842
+ if (input.mode === "follow_up") {
3843
+ await childSessionControls.followUp(input.message);
3844
+ return { state: "queued" };
3845
+ }
3846
+ await childSessionControls.steer(input.message);
3847
+ return { state: "delivered" };
3848
+ } catch (error) {
3849
+ return { state: "failed", reason: error instanceof Error ? error.message : String(error) };
3850
+ }
3851
+ },
3618
3852
  }));
3619
3853
  }
3620
3854
 
@@ -3627,31 +3861,44 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3627
3861
 
3628
3862
  const deadlineAt = data.deadlineAt ?? (data.timeoutMs !== undefined ? Date.now() + data.timeoutMs : undefined);
3629
3863
  let r: Awaited<ReturnType<typeof runSync>> | undefined;
3864
+ let resolveDetachedWorkflowChild: ((result: Awaited<ReturnType<typeof runSync>>) => void) | undefined;
3865
+ const detachedWorkflowChild = params.workflowAwaitDetached === true
3866
+ ? new Promise<Awaited<ReturnType<typeof runSync>>>((resolve) => { resolveDetachedWorkflowChild = resolve; })
3867
+ : undefined;
3630
3868
  try {
3631
- r = await runSync(ctx.cwd, agents, params.agent!, task, compactOptional<Parameters<typeof runSync>[4]>({
3869
+ const launched = await runSync(ctx.cwd, agents, params.agent!, task, compactOptional<Parameters<typeof runSync>[4]>({
3632
3870
  permissions: deps.config.permissions,
3871
+ runtimeSnapshotHost: deps.pi,
3633
3872
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
3873
+ projectTrusted: currentProjectTrusted(ctx),
3874
+ ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3634
3875
  llmIntentArbiter: createTaskMutationArbiter(ctx),
3635
- ...workflowForegroundSteeringLaunchOptions(foregroundControl, 0),
3876
+ childRuntime: deps.childRuntime,
3877
+ onChildSession: (controls) => { childSessionControls = controls; },
3636
3878
  context: data.contextPolicy.contextForAgent(params.agent!),
3879
+ unknownAgentDiagnosticContext: data.unknownAgentDiagnosticContext,
3637
3880
  runFanoutBudget: params.runFanoutAdmitted ? data.runFanoutBudget : { ...data.runFanoutBudget, parentPath: `${data.runFanoutBudget.parentPath ? `${data.runFanoutBudget.parentPath}/` : ""}single` },
3638
3881
  cwd: singleCwd,
3882
+ requestedCwd: data.requestedCwd,
3639
3883
  signal,
3640
3884
  interruptSignal: interruptController.signal,
3641
3885
  allowIntercomDetach: agentConfig.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,
3642
3886
  intercomEvents: deps.pi.events,
3643
3887
  runId,
3644
3888
  sessionDir: sessionDirForIndex(0),
3645
- sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
3889
+ sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
3646
3890
  share: shareEnabled,
3647
3891
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3648
3892
  artifactConfig,
3649
3893
  maxOutput: params.maxOutput,
3650
3894
  outputPath,
3895
+ outputClaimPath: params.workflowOutputClaimPath,
3651
3896
  outputMode: effectiveOutputMode,
3652
3897
  maxSubagentDepth,
3653
3898
  waitToolEnabled: deps.waitToolEnabled,
3899
+ waitToolDefaultTimeoutMs: deps.waitToolDefaultTimeoutMs,
3654
3900
  onUpdate: forwardSingleUpdate,
3901
+ suppressUnchangedDelegationUpdates,
3655
3902
  controlConfig,
3656
3903
  onControlEvent,
3657
3904
  intercomSessionName: childIntercomTarget,
@@ -3661,7 +3908,8 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3661
3908
  modelOverride,
3662
3909
  fast: params.fast,
3663
3910
  modelOverrideFromParent,
3664
- thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
3911
+ modelOrigin,
3912
+ thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
3665
3913
  thinkingCeiling: agentConfig.maxThinking,
3666
3914
  extensionBindings: params.extensionBindings,
3667
3915
  availableModels,
@@ -3672,12 +3920,20 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3672
3920
  agentContract: params.agentContract,
3673
3921
  acceptance: params.acceptance,
3674
3922
  acceptanceContext: { mode: "single" },
3923
+ workflowChildPermitLaunch: data.workflowChildPermitLaunch,
3675
3924
  onEffectivePrompt: foregroundControl ? (prompt) => updateLiveEffectivePrompt(foregroundControl, 0, prompt) : undefined,
3676
3925
  onDetachReady: (detach) => {
3677
3926
  detachForeground = detach;
3678
3927
  },
3679
3928
  onDetachedExit: (result) => {
3929
+ if (resolveDetachedWorkflowChild) {
3930
+ resolveDetachedWorkflowChild(result);
3931
+ return;
3932
+ }
3680
3933
  try {
3934
+ if (worktreeSetup) {
3935
+ finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result, workflowKey: params.workflowKey, lane });
3936
+ }
3681
3937
  try {
3682
3938
  updateRememberedForegroundChild(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, index: 0, result, events: deps.pi.events, notify: true });
3683
3939
  } catch {
@@ -3705,18 +3961,17 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3705
3961
  }
3706
3962
  }
3707
3963
  }
3708
- recordRun(params.agent!, cleanTask, result.exitCode, result.progressSummary?.durationMs ?? 0);
3964
+ recordRun(params.agent!, cleanTask, result.exitCode, result.progressSummary?.durationMs ?? 0, result);
3709
3965
  },
3710
3966
  timeoutMs: data.timeoutMs,
3711
3967
  deadlineAt,
3712
3968
  toolTimeoutMs: params.toolTimeoutMs,
3713
3969
  configToolTimeoutMs: data.configToolTimeoutMs,
3714
- turnBudget: data.turnBudget,
3715
- enforceHardTurnLimit: params.enforceHardTurnLimit,
3716
3970
  toolBudget: effectiveToolBudget.toolBudget,
3717
3971
  capabilityCeiling: data.capabilityCeiling,
3718
3972
  allowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,
3719
3973
  }));
3974
+ r = launched.detached && detachedWorkflowChild ? await detachedWorkflowChild : launched;
3720
3975
  } catch (error) {
3721
3976
  if (worktreeSetup) cleanupWorktrees(worktreeSetup);
3722
3977
  throw error;
@@ -3730,14 +3985,14 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3730
3985
  }
3731
3986
  }
3732
3987
  if (!r.detached) {
3733
- recordRun(params.agent!, cleanTask, r.exitCode, r.progressSummary?.durationMs ?? 0);
3988
+ recordRun(params.agent!, cleanTask, r.exitCode, r.progressSummary?.durationMs ?? 0, r);
3734
3989
  }
3735
3990
 
3736
3991
  let worktreeHandoff: ReturnType<typeof finalizeSingleWorktreeHandoff> | undefined;
3737
3992
  if (worktreeSetup) {
3738
3993
  worktreeHandoff = r.detached
3739
3994
  ? { suffix: pendingHandoff ? formatParallelHandoffReference(pendingHandoff) : "", reference: pendingHandoff }
3740
- : finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result: r });
3995
+ : finalizeSingleWorktreeHandoff({ worktreeSetup, artifactsDir, runId, cwd: sourceCwd, agent: params.agent!, result: r, workflowKey: params.workflowKey, lane });
3741
3996
  }
3742
3997
 
3743
3998
  if (r.progress) allProgress.push(r.progress);
@@ -3766,7 +4021,6 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3766
4021
  runId,
3767
4022
  timeoutMs: data.timeoutMs,
3768
4023
  results: [r],
3769
- ...(data.turnBudget ? { turnBudget: data.turnBudget } : {}),
3770
4024
  ...(effectiveToolBudget.toolBudget ? { toolBudget: effectiveToolBudget.toolBudget } : {}),
3771
4025
  progress: params.includeProgress ? allProgress : undefined,
3772
4026
  artifacts: allArtifactPaths.length ? { dir: artifactsDir, files: allArtifactPaths } : undefined,
@@ -3776,7 +4030,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3776
4030
  usageBudget: usageBudgetState(data.usageBudget, totalCost),
3777
4031
  ...(worktreeHandoff?.reference ? { parallelHandoff: worktreeHandoff.reference } : {}),
3778
4032
  }));
3779
- rememberForegroundRun(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: details.results, extensionBindings: params.extensionBindings });
4033
+ rememberForegroundRun(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: details.results, params, effectiveOutput, effectiveOutputMode, extensionBindings: params.extensionBindings });
3780
4034
 
3781
4035
  const suppressRoutineResultIntercom = shouldSuppressRoutineResultIntercom({ suppressRoutineResultIntercom: params.suppressRoutineResultIntercom, results: [r] });
3782
4036
  if (!r.detached && !r.interrupted && !suppressRoutineResultIntercom) {
@@ -3802,11 +4056,11 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3802
4056
  const worktreeSuffix = worktreeHandoff?.suffix ? `\n\n${worktreeHandoff.suffix}` : "";
3803
4057
  if (r.detached) {
3804
4058
  const statusRecovery = `subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
3805
- const blockingRecovery = `subagent_wait({ id: "${runId}" }). Use ${statusRecovery}`;
4059
+ const blockingRecovery = `bg_wait({ id: "${runId}" }). Use ${statusRecovery}`;
3806
4060
  const message = r.detachedReason === "intercom coordination"
3807
4061
  ? `Detached for intercom coordination: ${params.agent}. Reply to the supervisor request first, then wait with ${blockingRecovery}`
3808
4062
  : r.detachedReason === "user request"
3809
- ? `Detached at user request: ${params.agent}. The child continues independently. Register a completion wake-up with subagent_wait({ id: "${runId}", nonBlocking: true }), or use ${statusRecovery}`
4063
+ ? `Detached at user request: ${params.agent}. The child continues independently. Register a completion wake-up with bg_wait({ id: "${runId}", nonBlocking: true }), or use ${statusRecovery}`
3810
4064
  : `Detached before task completion: ${params.agent}. Wait with ${blockingRecovery}`;
3811
4065
  return {
3812
4066
  content: [{ type: "text", text: `${message}${worktreeSuffix}` }],
@@ -3851,7 +4105,7 @@ function duplicateSubagentCallResult(params: SubagentParamsLike): AgentToolResul
3851
4105
  };
3852
4106
  }
3853
4107
 
3854
- const workflowLaunchObservers = new WeakMap<object, (launch: { agent: string; sessionFile?: string; async: boolean; runId?: string }) => void>();
4108
+ const workflowLaunchObservers = new WeakMap<object, (launch: { agent: string; sessionName?: string; sessionFile?: string; async: boolean; runId?: string }) => void>();
3855
4109
 
3856
4110
  /**
3857
4111
  * Terminal-mission retention can remove a mission while its children still
@@ -3923,17 +4177,29 @@ export function bindMissionWorkflowChildAsyncLaunch(
3923
4177
  function workflowChildResult(
3924
4178
  key: string,
3925
4179
  result: AgentToolResult<Details>,
3926
- childParams: Record<string, unknown> = {},
4180
+ childParams: SubagentParamsLike | Record<string, unknown> = {},
3927
4181
  resumeState?: SubagentState,
4182
+ forcedTerminalOutcome?: WorkflowTerminalOutcome,
3928
4183
  ): WorkflowScriptChildResult {
3929
4184
  const receiptOutput = result.content.map((part) => part.type === "text" ? part.text : "").filter(Boolean).join("\n");
3930
4185
  const output = result.details.results.length === 1 && result.details.results[0]?.finalOutput !== undefined
3931
4186
  ? result.details.results[0].finalOutput
3932
4187
  : receiptOutput;
4188
+ const childError = result.details.results.map((child) => child.error).find((error): error is string => Boolean(error));
4189
+ const failureError = childError && receiptOutput && receiptOutput !== childError
4190
+ ? `${childError}\n\n${receiptOutput}`
4191
+ : childError || receiptOutput || output || "Child run failed.";
3933
4192
  const detached = result.details.results.some((child) => child.detached);
3934
4193
  const interrupted = result.details.results.some((child) => child.interrupted);
3935
4194
  const stopped = result.details.results.some((child) => child.stopped);
3936
- const ok = result.isError !== true && !detached && !interrupted && !stopped;
4195
+ const terminalOutcome = forcedTerminalOutcome
4196
+ ?? (result.details.results.some((child) => child.timedOut)
4197
+ ? { state: "partial" as const, reason: "timeout" as const }
4198
+ : result.details.usageBudget?.exhausted || result.details.results.some((child) => child.turnBudgetExceeded || child.toolBudgetBlocked)
4199
+ ? { state: "partial" as const, reason: "budget_exhausted" as const }
4200
+ : undefined);
4201
+ const acceptanceRecovery = result.details.results.find((child) => child.acceptance?.recovery)?.acceptance?.recovery;
4202
+ const ok = result.isError !== true && !detached && !interrupted && !stopped && acceptanceRecovery === undefined;
3937
4203
  const artifactPaths = new Set<string>();
3938
4204
  if (result.details.asyncDir) artifactPaths.add(result.details.asyncDir);
3939
4205
  if (result.details.parallelHandoff?.path) artifactPaths.add(result.details.parallelHandoff.path);
@@ -3965,13 +4231,25 @@ function workflowChildResult(
3965
4231
  const continuationRunIds = [...new Set([resumeSourceRunId, runId].filter((value): value is string => Boolean(value)))];
3966
4232
  const outputReference = result.details.results.find((child) => child.savedOutputPath)?.savedOutputPath
3967
4233
  ?? result.details.results.find((child) => child.outputReference?.path)?.outputReference?.path;
4234
+ const outputPathMapping = typeof childParams.task === "string" ? outputPathMappingFromTask(childParams.task, outputReference) : undefined;
4235
+ const externalResult = result.details.results.length === 1 && result.details.results[0]?.runner?.type === "external-cli" ? result.details.results[0] : undefined;
4236
+ const externalStatus = result.details.asyncDir ? readStatus(result.details.asyncDir) : undefined;
4237
+ const externalStatusStep = externalStatus?.steps?.length === 1 && externalStatus.steps[0]?.runner?.type === "external-cli" ? externalStatus.steps[0] : undefined;
4238
+ const externalRunner = normalizeExternalCliRunnerStatus(externalResult?.runner ?? externalStatusStep?.runner);
4239
+ const externalProcess = externalResult?.externalProcess ?? externalStatusStep?.externalProcess;
4240
+ const externalAdapter = externalRunner ? externalCliReceiptMetadata({ runner: externalRunner, externalProcess, outputReference }) : undefined;
4241
+ if (externalAdapter) resumability = { state: "not-resumable", reason: externalAdapter.nonResumableReason };
4242
+ const lane = normalizeWorkflowLaneMetadata(childParams.lane, `workflow child '${key}'.lane`);
4243
+ assertWorkflowLaneKey(lane, key, `workflow child '${key}'.lane`);
3968
4244
  return {
3969
4245
  key,
3970
4246
  ok,
4247
+ ...(lane ? { lane } : {}),
4248
+ ...(terminalOutcome ? { terminalOutcome } : {}),
3971
4249
  ...(resolvedAgents.length === 1 ? { agent: resolvedAgents[0] } : {}),
3972
4250
  ...(runId ? { runId } : {}),
3973
4251
  output,
3974
- ...(!ok ? { error: receiptOutput || output || "Child run failed." } : {}),
4252
+ ...(!ok ? { error: failureError } : {}),
3975
4253
  ...(detached ? { detached: true } : {}),
3976
4254
  ...(interrupted ? { interrupted: true } : {}),
3977
4255
  ...(stopped ? { stopped: true } : {}),
@@ -3979,6 +4257,9 @@ function workflowChildResult(
3979
4257
  ...(requestedContext ? { requestedContext } : {}),
3980
4258
  ...(resolvedContext ? { resolvedContext } : {}),
3981
4259
  ...(outputReference ? { outputReference } : {}),
4260
+ ...(acceptanceRecovery ? { recovery: acceptanceRecovery } : {}),
4261
+ ...(outputPathMapping ? { outputPathMapping } : {}),
4262
+ ...(externalAdapter ? { externalAdapter } : {}),
3982
4263
  resumability,
3983
4264
  continuation: { runIds: continuationRunIds },
3984
4265
  artifactPaths: [...artifactPaths],
@@ -3986,6 +4267,28 @@ function workflowChildResult(
3986
4267
  };
3987
4268
  }
3988
4269
 
4270
+ function workflowChildAccountingFields(child: WorkflowScriptChildResult): { usage?: Usage; sessionFile?: string; recovery?: import("../../shared/types.ts").AcceptanceRecoveryMetadata } {
4271
+ if (!child.results?.length) return {};
4272
+ const usage = sumResultsUsage(child.results);
4273
+ const sessionFile = child.results.find((result) => result.sessionFile)?.sessionFile;
4274
+ return {
4275
+ ...(usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0 ? { usage } : {}),
4276
+ ...(sessionFile ? { sessionFile } : {}),
4277
+ ...(child.recovery ? { recovery: child.recovery } : {}),
4278
+ };
4279
+ }
4280
+
4281
+ function workflowOutputPathMappingSummary(children: WorkflowScriptChildResult[]): string {
4282
+ const mappings = children.flatMap((child) => child.outputPathMapping
4283
+ ? [`'${child.key}': requested ${child.outputPathMapping.requestedPath} -> saved ${child.outputPathMapping.savedPath}`]
4284
+ : []);
4285
+ return mappings.length > 0 ? ` Output path mappings: ${mappings.join("; ")}.` : "";
4286
+ }
4287
+
4288
+ function workflowDetailsResults(children: WorkflowScriptChildResult[]): SingleResult[] {
4289
+ return children.flatMap((child) => (child.results ?? []).map((result) => result.workflowKey ? result : { ...result, workflowKey: child.key }));
4290
+ }
4291
+
3989
4292
  function workflowSteerReceipt(key: string, result: AgentToolResult<Details>): WorkflowSteerResult {
3990
4293
  const steering = result.details.steering;
3991
4294
  const error = result.content.map((part) => part.type === "text" ? part.text : "").filter(Boolean).join("\n") || undefined;
@@ -4003,29 +4306,124 @@ function workflowSteerReceipt(key: string, result: AgentToolResult<Details>): Wo
4003
4306
  };
4004
4307
  }
4005
4308
 
4309
+ const CHILD_SESSION_NOT_RUNNING_YET = "Child session is not running yet.";
4310
+ const MAX_WORKFLOW_RESUME_HINT_BYTES = 1024;
4311
+ const MAX_WORKFLOW_CHILD_RUN_ID_BYTES = 256;
4312
+ const WORKFLOW_RESUME_HINT_PARENT_STATES = new Set(["complete", "failed", "partial"]);
4313
+ const WORKFLOW_STEP_STATES = new Set(["pending", "running", "complete", "completed", "failed", "partial", "paused", "stopped", "rejected"]);
4314
+
4315
+ function isSafeWorkflowChildRunId(value: unknown): value is string {
4316
+ if (typeof value !== "string") return false;
4317
+ const runId = value.trim();
4318
+ return value === runId
4319
+ && Boolean(runId)
4320
+ && Buffer.byteLength(runId, "utf8") <= MAX_WORKFLOW_CHILD_RUN_ID_BYTES
4321
+ && path.basename(runId) === runId
4322
+ && path.win32.basename(runId) === runId
4323
+ && !/[\\/]/.test(runId)
4324
+ && !runId.includes("..")
4325
+ && !/[\u0000-\u001f\u007f]/.test(runId);
4326
+ }
4327
+
4328
+ function isMissingWorkflowReceiptDiagnostic(error: unknown, workflowRunId: string): error is Error {
4329
+ return error instanceof Error
4330
+ && error.message.startsWith(`Workflow receipt '${workflowRunId}' is not available because the workflow may still be active or terminal receipt writing failed.`);
4331
+ }
4332
+
4333
+ function missingWorkflowReceiptResumeHint(reference: WorkflowReceiptResumeReference, state: SubagentState): string | undefined {
4334
+ try {
4335
+ if (!state.currentSessionId) return undefined;
4336
+ const workflowRunId = reference.workflowRunId.trim();
4337
+ const workflowStatus = readStatus(path.join(DIRS.async, workflowRunId));
4338
+ if (!workflowStatus
4339
+ || workflowStatus.runId !== workflowRunId
4340
+ || workflowStatus.mode !== "workflow"
4341
+ || workflowStatus.sessionId !== state.currentSessionId
4342
+ || typeof workflowStatus.startedAt !== "number"
4343
+ || !Number.isFinite(workflowStatus.startedAt)
4344
+ || !WORKFLOW_RESUME_HINT_PARENT_STATES.has(workflowStatus.state)
4345
+ || !Array.isArray(workflowStatus.steps)
4346
+ || workflowStatus.steps.some((step) => {
4347
+ if (!step || typeof step !== "object" || Array.isArray(step)) return true;
4348
+ const record = step as Record<string, unknown>;
4349
+ return typeof record.agent !== "string"
4350
+ || typeof record.status !== "string"
4351
+ || !WORKFLOW_STEP_STATES.has(record.status)
4352
+ || (record.workflowKey !== undefined && typeof record.workflowKey !== "string")
4353
+ || (record.runId !== undefined && typeof record.runId !== "string");
4354
+ })) return undefined;
4355
+ const matchingSteps = workflowStatus.steps.filter((step) => step.workflowKey === reference.key);
4356
+ if (matchingSteps.length !== 1) return undefined;
4357
+ const childRunId = matchingSteps[0]?.runId;
4358
+ if (!isSafeWorkflowChildRunId(childRunId)) return undefined;
4359
+
4360
+ const workflowChildren = parseWorkflowChildSummary(workflowStatus.workflowChildren);
4361
+ if (workflowChildren) {
4362
+ if (workflowChildren.workflowRunId !== workflowRunId) return undefined;
4363
+ const matchingChildren = workflowChildren.children.filter((child) => child.childId === reference.key);
4364
+ if (matchingChildren.length > 1 || (workflowChildren.inventoryComplete && matchingChildren.length !== 1)) return undefined;
4365
+ if (matchingChildren.length === 1 && matchingChildren[0]?.runId !== childRunId) return undefined;
4366
+ }
4367
+
4368
+ const target = resolveResumeTarget({ id: childRunId }, state, { asyncRequireSessionFile: true, exactOnly: true });
4369
+ if (target.kind !== "revive") return undefined;
4370
+ const hint = `Direct resumable child for workflow key '${reference.key}': subagent({ action: "resume", id: ${JSON.stringify(childRunId)}, message: "..." })`;
4371
+ return Buffer.byteLength(hint, "utf8") <= MAX_WORKFLOW_RESUME_HINT_BYTES ? hint : undefined;
4372
+ } catch {
4373
+ return undefined;
4374
+ }
4375
+ }
4376
+
4006
4377
  function resolveKeyedWorkflowResume(
4007
4378
  reference: WorkflowReceiptResumeReference,
4008
4379
  state: SubagentState,
4009
4380
  ): { runId: string; runIds: string[] } {
4010
- const entry = resolveWorkflowReceiptResumeEntry({
4011
- reference,
4012
- asyncDirRoot: DIRS.async,
4013
- assertResumable(runId) {
4014
- const target = resolveResumeTarget({ id: runId }, state, { asyncRequireSessionFile: true, exactOnly: true });
4015
- if (target.kind !== "revive") throw new Error(`Workflow receipt child '${reference.key}' latest run '${runId}' is still running.`);
4016
- },
4017
- });
4018
- const runId = entry.latestRunId;
4019
- if (!runId) throw new Error(`Workflow receipt child '${reference.key}' has no retained run id.`);
4020
- return { runId, runIds: entry.continuation.runIds };
4381
+ try {
4382
+ const entry = resolveWorkflowReceiptResumeEntry({
4383
+ reference,
4384
+ asyncDirRoot: DIRS.async,
4385
+ assertResumable(runId) {
4386
+ const target = resolveResumeTarget({ id: runId }, state, { asyncRequireSessionFile: true, exactOnly: true });
4387
+ if (target.kind !== "revive") throw new Error(`Workflow receipt child '${reference.key}' latest run '${runId}' is still running.`);
4388
+ },
4389
+ });
4390
+ const runId = entry.latestRunId;
4391
+ if (!runId) throw new Error(`Workflow receipt child '${reference.key}' has no retained run id.`);
4392
+ return { runId, runIds: entry.continuation.runIds };
4393
+ } catch (error) {
4394
+ const workflowRunId = reference.workflowRunId.trim();
4395
+ if (isMissingWorkflowReceiptDiagnostic(error, workflowRunId)) {
4396
+ const hint = missingWorkflowReceiptResumeHint(reference, state);
4397
+ if (hint) throw new Error(`${error.message} ${hint}`, { cause: error });
4398
+ }
4399
+ throw error;
4400
+ }
4021
4401
  }
4022
4402
 
4023
4403
  function terminalWorkflowReceipt(
4024
4404
  workflowRunId: string,
4025
4405
  state: WorkflowReceiptState,
4026
4406
  children: WorkflowScriptChildResult[],
4407
+ workflowChildren?: WorkflowReceipt["workflowChildren"],
4408
+ terminalOutcome?: WorkflowTerminalOutcome,
4409
+ hostSteps?: WorkflowReceipt["hostSteps"],
4410
+ resource?: WorkflowReceipt["resource"],
4027
4411
  ): WorkflowReceipt {
4028
- return buildWorkflowReceipt({ workflowRunId, state, children });
4412
+ return buildWorkflowReceipt({ workflowRunId, state, children, workflowChildren, terminalOutcome, hostSteps, resource });
4413
+ }
4414
+
4415
+ function workflowFailureTerminalOutcome(error: unknown, _children: WorkflowScriptChildResult[], usageBudget: ReturnType<typeof usageBudgetState>): WorkflowTerminalOutcome | undefined {
4416
+ if (usageBudget?.exhausted) return { state: "partial", reason: "budget_exhausted" };
4417
+ return error instanceof WorkflowScriptError && error.errorKind === "timeout" ? { state: "partial", reason: "timeout" } : undefined;
4418
+ }
4419
+
4420
+ function workflowFailureMessage(error: unknown, workflowRunId: string, children: WorkflowScriptChildResult[]): string {
4421
+ const text = error instanceof Error ? error.message : String(error);
4422
+ const validationPrefix = "workflowScript validation failed before child launch; no children launched.";
4423
+ if (children.length === 0 && text.includes(validationPrefix)) {
4424
+ return `Workflow '${workflowRunId}' validation failed before child launch; no children launched.${text.slice(text.indexOf(validationPrefix) + validationPrefix.length)}`;
4425
+ }
4426
+ return text;
4029
4427
  }
4030
4428
 
4031
4429
  export async function steerWorkflowChildByKey(input: {
@@ -4044,7 +4442,6 @@ export async function steerWorkflowChildByKey(input: {
4044
4442
  while (true) {
4045
4443
  const control = [...input.state.foregroundControls.values()].find((candidate) => candidate.parentWorkflowRunId === input.workflowRunId
4046
4444
  && candidate.workflowKey === input.key
4047
- && Boolean(candidate.workflowSteeringDir)
4048
4445
  && (candidate.activeChildren?.size ?? 0) > 0);
4049
4446
  if (control) {
4050
4447
  const result = await steerWorkflowForegroundTarget({
@@ -4052,10 +4449,9 @@ export async function steerWorkflowChildByKey(input: {
4052
4449
  message: input.message,
4053
4450
  mode: input.options.mode,
4054
4451
  index: input.options.index,
4055
- ackTimeoutMs: Math.max(1, deadline - Date.now()),
4056
- signal: input.signal,
4057
4452
  });
4058
- return workflowSteerReceipt(input.key, result);
4453
+ // The control registers before its child session exists; keep polling until the steer can route.
4454
+ if (!result.details.steering?.targets.some((target) => target.reason === CHILD_SESSION_NOT_RUNNING_YET) || Date.now() >= deadline) return workflowSteerReceipt(input.key, result);
4059
4455
  }
4060
4456
 
4061
4457
  const workflowStatus = readStatus(path.join(asyncDirRoot, input.workflowRunId));
@@ -4068,6 +4464,8 @@ export async function steerWorkflowChildByKey(input: {
4068
4464
  return { key: input.key, state: "missed", error: `Workflow child '${input.key}' is ${childStatus.state}.` };
4069
4465
  }
4070
4466
  if (childStatus) {
4467
+ const unsupported = externalRunnerControlError(asyncDir, "steer");
4468
+ if (unsupported) return workflowSteerReceipt(input.key, unsupported);
4071
4469
  const result = await steerAsyncRun({
4072
4470
  state: input.state,
4073
4471
  runId: childRunId,
@@ -4099,9 +4497,15 @@ export function prepareWorkflowLaunchParams(
4099
4497
  childParams: Record<string, unknown>,
4100
4498
  parentWorkflowRunId: string,
4101
4499
  workflowKey: string,
4102
- options: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number; externalAsyncRequired?: boolean; capabilityCeiling?: ResolvedSubagentCapabilityCeiling } = {},
4500
+ options: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; awaitDetachedChild?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number; externalAsyncRequired?: boolean; capabilityCeiling?: ResolvedSubagentCapabilityCeiling; outputClaimPath?: string } = {},
4103
4501
  ): SubagentParamsLike {
4502
+ const { globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowDefaultsWithoutCapacity } = workflowDefaults;
4503
+ const { globalConcurrencyLimit: _childGlobalConcurrencyLimit, maxSubagentSpawnsPerRun: _childMaxSubagentSpawnsPerRun, ...childParamsWithoutCapacity } = childParams;
4504
+ workflowDefaults = workflowDefaultsWithoutCapacity;
4505
+ childParams = childParamsWithoutCapacity;
4104
4506
  const capabilityCeiling = intersectSubagentCapabilityCeilings(workflowDefaults.capabilityCeiling, options.capabilityCeiling);
4507
+ const lane = normalizeWorkflowLaneMetadata(Object.hasOwn(childParams, "lane") ? childParams.lane : workflowDefaults.lane, `workflow child '${workflowKey}'.lane`);
4508
+ assertWorkflowLaneKey(lane, workflowKey, `workflow child '${workflowKey}'.lane`);
4105
4509
  const parentTimeoutMs = options.parentDeadlineAt === undefined
4106
4510
  || childParams.timeoutMs !== undefined
4107
4511
  || childParams.maxRuntimeMs !== undefined
@@ -4117,10 +4521,20 @@ export function prepareWorkflowLaunchParams(
4117
4521
  throw new Error("gate is not supported with retained resume; resume uses the retained child contract.");
4118
4522
  }
4119
4523
  const timeoutMs = childParams.timeoutMs ?? childParams.maxRuntimeMs ?? workflowDefaults.timeoutMs ?? workflowDefaults.maxRuntimeMs;
4120
- const turnBudget = childParams.turnBudget ?? workflowDefaults.turnBudget;
4121
4524
  const toolBudget = childParams.toolBudget ?? workflowDefaults.toolBudget;
4122
4525
  const intercomBridge = childParams.intercomBridge ?? workflowDefaults.intercomBridge;
4123
4526
  const worktree = childParams.worktree ?? workflowDefaults.worktree;
4527
+ const baseRef = Object.hasOwn(childParams, "baseRef") ? childParams.baseRef : undefined;
4528
+ const outputSchema = Object.hasOwn(childParams, "outputSchema") ? childParams.outputSchema : workflowDefaults.outputSchema;
4529
+ if (outputSchema !== undefined) assertJsonSchemaObject(outputSchema, "outputSchema");
4530
+ const agentContract = Object.hasOwn(childParams, "agentContract") ? childParams.agentContract : workflowDefaults.agentContract;
4531
+ if (agentContract !== undefined && !isAgentContractV1(agentContract as AgentContract)) throw new Error("agentContract must be { version: 1 }.");
4532
+ const acceptance = Object.hasOwn(childParams, "acceptance") ? childParams.acceptance : workflowDefaults.acceptance;
4533
+ const output = Object.hasOwn(childParams, "output") ? childParams.output : workflowDefaults.output;
4534
+ if (output !== undefined && typeof output !== "string" && typeof output !== "boolean") throw new Error("output must be a path string or boolean.");
4535
+ const outputMode = Object.hasOwn(childParams, "outputMode") ? childParams.outputMode : workflowDefaults.outputMode;
4536
+ if (outputMode !== undefined && outputMode !== "inline" && outputMode !== "file-only") throw new Error("outputMode must be 'inline' or 'file-only'.");
4537
+ const control = mergeWorkflowControlOverrides(workflowDefaults.control, childParams.control as ControlConfig | undefined);
4124
4538
  return {
4125
4539
  action: "resume",
4126
4540
  id: childParams.resume.trim(),
@@ -4128,24 +4542,36 @@ export function prepareWorkflowLaunchParams(
4128
4542
  message: typeof childParams.task === "string" ? childParams.task.trim() : "",
4129
4543
  workflowParentRunId: parentWorkflowRunId,
4130
4544
  workflowKey,
4545
+ ...(lane ? { lane } : {}),
4131
4546
  ...(worktree !== undefined ? { worktree: worktree as boolean } : {}),
4547
+ ...(baseRef !== undefined ? { baseRef: baseRef as string } : {}),
4548
+ ...(outputSchema !== undefined ? { outputSchema: outputSchema as JsonSchemaObject } : {}),
4549
+ ...(agentContract !== undefined ? { agentContract: agentContract as AgentContract } : {}),
4550
+ ...(acceptance !== undefined ? { acceptance: acceptance as AcceptanceInput } : {}),
4551
+ ...(output !== undefined ? { output: output as string | boolean } : {}),
4552
+ ...(outputMode !== undefined ? { outputMode: outputMode as OutputMode } : {}),
4132
4553
  ...(options.runFanoutBudget ? { runFanoutBudget: { ...options.runFanoutBudget, parentPath: `${options.runFanoutBudget.parentPath ? `${options.runFanoutBudget.parentPath}/` : ""}workflow[${workflowKey}]` } } : {}),
4133
4554
  ...(options.missionDetached ? { mission: false } : {}),
4134
4555
  ...(timeoutMs !== undefined ? { timeoutMs: timeoutMs as number } : {}),
4135
- ...(turnBudget !== undefined ? { turnBudget: turnBudget as TurnBudgetConfig } : {}),
4136
4556
  ...(toolBudget !== undefined ? { toolBudget: toolBudget as ToolBudgetConfig } : {}),
4557
+ ...(control !== undefined ? { control } : {}),
4137
4558
  ...(intercomBridge !== undefined ? { intercomBridge: intercomBridge as IntercomBridgeConfig } : {}),
4138
4559
  ...(capabilityCeiling ? { capabilityCeiling } : {}),
4139
4560
  };
4140
4561
  }
4562
+ const control = mergeWorkflowControlOverrides(workflowDefaults.control, childParams.control as ControlConfig | undefined);
4141
4563
  const launchParams = {
4142
4564
  ...workflowDefaults,
4143
4565
  async: options.externalAsyncRequired === true && childParams.async === undefined && workflowDefaults.async === undefined ? true : false,
4144
4566
  ...childParams,
4567
+ ...(control !== undefined ? { control } : {}),
4145
4568
  ...(options.externalAsyncRequired === true && childParams.async === undefined && workflowDefaults.async === undefined ? { workflowAwaitAsync: true } : {}),
4146
4569
  ...(options.missionDetached ? { mission: false } : {}),
4147
4570
  workflowParentRunId: parentWorkflowRunId,
4148
4571
  workflowKey,
4572
+ ...(options.outputClaimPath ? { workflowOutputClaimPath: options.outputClaimPath } : {}),
4573
+ ...(options.awaitDetachedChild ? { workflowAwaitDetached: true } : {}),
4574
+ ...(lane ? { lane } : {}),
4149
4575
  ...(parentTimeoutMs !== undefined ? { workflowParentDeadlineAt: options.parentDeadlineAt } : {}),
4150
4576
  ...(options.runFanoutBudget ? { runFanoutBudget: { ...options.runFanoutBudget, parentPath: `${options.runFanoutBudget.parentPath ? `${options.runFanoutBudget.parentPath}/` : ""}workflow[${workflowKey}]` } } : {}),
4151
4577
  ...(options.suppressRoutineResultIntercom ? { suppressRoutineResultIntercom: true } : {}),
@@ -4157,6 +4583,17 @@ export function prepareWorkflowLaunchParams(
4157
4583
  return normalizedGate.params;
4158
4584
  }
4159
4585
 
4586
+ function mergeWorkflowControlOverrides(workflowControl: ControlConfig | undefined, childControl: ControlConfig | undefined): ControlConfig | undefined {
4587
+ if (childControl === undefined) return workflowControl;
4588
+ if (workflowControl === undefined) return childControl;
4589
+ return { ...workflowControl, ...childControl };
4590
+ }
4591
+
4592
+ export function resolveRevivalControlConfig(input: { globalConfig?: ControlConfig; requestedControl?: ControlConfig; recoveryControlConfig?: ResolvedControlConfig }): ResolvedControlConfig {
4593
+ if (input.requestedControl === undefined) return input.recoveryControlConfig ?? resolveControlConfig(input.globalConfig, undefined);
4594
+ return resolveControlConfig(input.recoveryControlConfig ?? input.globalConfig, input.requestedControl);
4595
+ }
4596
+
4160
4597
  type GateParamsNormalizationResult =
4161
4598
  | { ok: true; params: SubagentParamsLike }
4162
4599
  | { ok: false; error: string };
@@ -4182,15 +4619,101 @@ function formatWorkflowValue(value: unknown): string {
4182
4619
  }
4183
4620
  }
4184
4621
 
4622
+ function buildWorkflowLaneGraph(runId: string, lanes: WorkflowLanePlan[], existing?: WorkflowGraphSnapshot): WorkflowGraphSnapshot {
4623
+ const plannedIds = new Set(lanes.flatMap((lane) => lane.stages.map((stage) => stage.generatedKey)));
4624
+ const previousById = new Map((existing?.nodes ?? []).map((node) => [node.id, node]));
4625
+ const nodes: WorkflowGraphNode[] = [];
4626
+ const phases: WorkflowGraphSnapshot["phases"] = [];
4627
+ let flatIndex = 0;
4628
+ for (const lane of lanes) {
4629
+ const nodeIds: string[] = [];
4630
+ for (const [stageIndex, stage] of lane.stages.entries()) {
4631
+ const previous = previousById.get(stage.generatedKey);
4632
+ const outputName = stage.outputName || previous?.outputName;
4633
+ const structured = stage.structured ?? previous?.structured;
4634
+ const node: WorkflowGraphNode = {
4635
+ id: stage.generatedKey,
4636
+ kind: "step",
4637
+ agent: stage.agent ?? previous?.agent,
4638
+ phase: stage.phase ?? previous?.phase,
4639
+ label: stage.label ?? stage.key,
4640
+ status: previous?.status ?? (stageIndex === 0 ? "running" : "pending"),
4641
+ flatIndex,
4642
+ stepIndex: flatIndex,
4643
+ ...(outputName ? { outputName } : {}),
4644
+ ...(structured !== undefined ? { structured } : {}),
4645
+ ...(previous?.acceptanceStatus ? { acceptanceStatus: previous.acceptanceStatus } : {}),
4646
+ ...(previous?.error ? { error: previous.error } : {}),
4647
+ };
4648
+ nodes.push(node);
4649
+ nodeIds.push(node.id);
4650
+ flatIndex++;
4651
+ }
4652
+ if (nodeIds.length > 0) phases.push({ title: lane.key, nodeIds });
4653
+ }
4654
+ for (const node of existing?.nodes ?? []) {
4655
+ if (!plannedIds.has(node.id)) nodes.push(node);
4656
+ }
4657
+ for (const phase of existing?.phases ?? []) {
4658
+ const retainedNodeIds = phase.nodeIds.filter((nodeId) => !plannedIds.has(nodeId));
4659
+ if (retainedNodeIds.length === 0) continue;
4660
+ const currentPhase = phases.find((candidate) => candidate.title === phase.title);
4661
+ if (currentPhase) currentPhase.nodeIds.push(...retainedNodeIds);
4662
+ else phases.push({ title: phase.title, nodeIds: retainedNodeIds });
4663
+ }
4664
+ const currentNodeId = nodes.find((node) => node.status === "running")?.id ?? existing?.currentNodeId;
4665
+ return { runId, mode: "workflow", phases, nodes, ...(currentNodeId ? { currentNodeId } : {}) };
4666
+ }
4667
+
4668
+ function workflowLaneTraceStatus(state: WorkflowScriptTraceEntry["state"]): WorkflowNodeStatus | undefined {
4669
+ switch (state) {
4670
+ case "started":
4671
+ return "running";
4672
+ case "reused":
4673
+ return undefined;
4674
+ case "completed":
4675
+ return "completed";
4676
+ case "failed":
4677
+ return "failed";
4678
+ case "detached":
4679
+ return "detached";
4680
+ case "stopped":
4681
+ return "stopped";
4682
+ default:
4683
+ return undefined;
4684
+ }
4685
+ }
4686
+
4687
+ function applyWorkflowLaneTrace(graph: WorkflowGraphSnapshot, trace: WorkflowScriptTraceEntry[]): void {
4688
+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
4689
+ for (const entry of trace) {
4690
+ if (entry.operation !== "run") continue;
4691
+ const node = nodesById.get(entry.key);
4692
+ if (!node) continue;
4693
+ const status = workflowLaneTraceStatus(entry.state);
4694
+ if (status) node.status = status;
4695
+ if (entry.agent) node.agent = entry.agent;
4696
+ if (entry.phase && (entry.phase !== "auto-resume" || node.phase === undefined)) node.phase = entry.phase;
4697
+ if (entry.label) node.label = entry.label;
4698
+ if (entry.error) node.error = entry.error;
4699
+ else if (status === "completed" || status === "running") delete node.error;
4700
+ }
4701
+ const currentNodeId = graph.nodes.find((node) => node.status === "running")?.id;
4702
+ if (currentNodeId) graph.currentNodeId = currentNodeId;
4703
+ else delete graph.currentNodeId;
4704
+ }
4705
+
4185
4706
  function workflowChatProgressUpdate(
4186
4707
  runId: string,
4187
4708
  chatProgress: WorkflowChatProgressProjection,
4188
4709
  workflow: NonNullable<Details["workflow"]>,
4710
+ workflowChildren?: Details["workflowChildren"],
4711
+ preflight?: import("../../shared/types.ts").WorkflowPreflightV1,
4189
4712
  ): AgentToolResult<Details> | undefined {
4190
4713
  if (chatProgress.mode !== "live-card") return undefined;
4191
4714
  return {
4192
4715
  content: [{ type: "text", text: "Workflow running." }],
4193
- details: { mode: "workflow", runId, results: [], workflow, chatProgress },
4716
+ details: { mode: "workflow", runId, results: [], workflow, ...(preflight ? { preflight } : {}), ...(workflowChildren ? { workflowChildren } : {}), chatProgress },
4194
4717
  };
4195
4718
  }
4196
4719
 
@@ -4201,10 +4724,12 @@ function createScheduledOwnerState(source: SubagentState, ownerSessionId: string
4201
4724
  grantHistory: [...(source.subagentSpawns.grantHistory ?? [])],
4202
4725
  }
4203
4726
  : undefined;
4727
+ const ownerParentModel = source.currentSessionId === ownerSessionId ? source.lastParentModel : undefined;
4204
4728
  return {
4205
4729
  ...source,
4206
4730
  baseCwd: ctx.cwd,
4207
4731
  currentSessionId: ownerSessionId,
4732
+ lastParentModel: ownerParentModel,
4208
4733
  parentSessionFile: ctx.sessionManager.getSessionFile() ?? null,
4209
4734
  subagentInProgress: false,
4210
4735
  ...(ownerSpawns ? { subagentSpawns: ownerSpawns } : { subagentSpawns: undefined }),
@@ -4265,6 +4790,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4265
4790
  const delegatedThinkingOverrides = new WeakMap<object, AgentConfig["thinking"]>();
4266
4791
  const delegatedZeroToolBudgets = new WeakSet<object>();
4267
4792
  const delegatedExecutions = new WeakSet<object>();
4793
+ const publicExecutions = new WeakSet<object>();
4794
+ const workflowResourcePermits = new WeakMap<object, WorkflowResourcePermit>();
4795
+ const workflowPermitContexts = new WeakMap<object, { root: WorkflowChildPermit } | { child: WorkflowChildPermitContext }>();
4268
4796
  const warnedArtifactPackageDirs = new Set<string>();
4269
4797
  const scheduledOwnerExecutors = new Map<string, ReturnType<typeof createSubagentExecutor>>();
4270
4798
  const execute = async (
@@ -4274,21 +4802,78 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4274
4802
  onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
4275
4803
  ctx: ExtensionContext,
4276
4804
  preserveActiveSession = false,
4805
+ parentModelOverride?: ParentModel | null,
4277
4806
  ): Promise<AgentToolResult<Details>> => {
4278
4807
  const workflowLaunchObserver = workflowLaunchObservers.get(params);
4279
4808
  const delegatedThinkingOverride = delegatedThinkingOverrides.get(params);
4280
4809
  const allowZeroToolBudget = delegatedZeroToolBudgets.has(params);
4281
4810
  const delegatedExecution = delegatedExecutions.has(params);
4811
+ const publicExecution = publicExecutions.has(params);
4812
+ const workflowResourcePermit = workflowResourcePermits.get(params);
4813
+ const workflowPermitContext = workflowPermitContexts.get(params);
4814
+ const delegatedWorkflowPermit = workflowPermitContext && "root" in workflowPermitContext ? workflowPermitContext.root : undefined;
4815
+ const workflowChildPermitLaunch = workflowPermitContext && "child" in workflowPermitContext ? workflowPermitContext.child : undefined;
4282
4816
  if (!preserveActiveSession) deps.state.baseCwd = ctx.cwd;
4283
4817
  deps.state.foregroundRuns ??= new Map();
4284
4818
  deps.state.foregroundControls ??= new Map();
4285
4819
  deps.state.lastForegroundControlId ??= null;
4286
4820
  const normalizedGate = normalizeGateParams(params);
4287
4821
  if (!normalizedGate.ok) return buildRequestedModeError(params, normalizedGate.error);
4288
- const requestParams = normalizedGate.params;
4822
+ let requestParams = normalizedGate.params;
4823
+ const capacityOverrideError = validateWorkflowCapacityOverrides(requestParams);
4824
+ if (capacityOverrideError) return buildRequestedModeError(requestParams, capacityOverrideError);
4825
+ let workflowPreflight: import("../../shared/types.ts").WorkflowPreflightV1 | undefined;
4826
+ try {
4827
+ if (requestParams.preflight !== undefined && requestParams.workflowScript === undefined && requestParams.workflowScriptPath === undefined) {
4828
+ throw new Error("preflight requires workflowScript or workflowScriptPath.");
4829
+ }
4830
+ workflowPreflight = normalizeWorkflowPreflight(requestParams.preflight);
4831
+ if (workflowPreflight) requestParams = { ...requestParams, preflight: workflowPreflight };
4832
+ } catch (error) {
4833
+ const message = error instanceof Error ? error.message : String(error);
4834
+ if (requestParams.action?.trim() === "validate") {
4835
+ const validation = validateWorkflowScript(requestParams.workflowScript ?? "");
4836
+ const invalidValidation = { ...validation, ok: false, errors: [...validation.errors, { message }] };
4837
+ return {
4838
+ content: [{ type: "text", text: JSON.stringify(invalidValidation) }],
4839
+ isError: true,
4840
+ details: { mode: "management", results: [] },
4841
+ };
4842
+ }
4843
+ return buildRequestedModeError(requestParams, message);
4844
+ }
4845
+ if (requestParams.action?.trim() === "validate") {
4846
+ const validation = validateWorkflowScript(requestParams.workflowScript ?? "");
4847
+ const payload = workflowPreflight ? { ...validation, preflight: workflowPreflight } : validation;
4848
+ return {
4849
+ content: [{ type: "text", text: JSON.stringify(payload) }],
4850
+ ...(validation.ok ? {} : { isError: true }),
4851
+ details: { mode: "management", results: [] },
4852
+ };
4853
+ }
4289
4854
  const normalizedAction = typeof requestParams.action === "string" ? requestParams.action.trim() : requestParams.action;
4290
4855
  if (normalizedAction === "resume" && requestParams.extensionBindings !== undefined) return buildRequestedModeError(requestParams, "extensionBindings is not supported with action='resume'; resume uses the original retained child binding.");
4856
+ let workflowResource: { permit: WorkflowResourcePermit; provenance: WorkflowResourceProvenanceV1; authority: WorkflowResourceAuthority } | undefined;
4857
+ if (workflowResourcePermit) {
4858
+ if (typeof requestParams.workflowScript !== "string") return buildRequestedModeError(requestParams, "Resolved workflow resource is missing its workflow script.");
4859
+ const consumed = consumeWorkflowResourcePermit(workflowResourcePermit, requestParams.workflowScript);
4860
+ if (typeof consumed === "string") return buildRequestedModeError(requestParams, consumed);
4861
+ workflowResource = { permit: workflowResourcePermit, ...consumed };
4862
+ }
4291
4863
  if (requestParams.workflowScript !== undefined && normalizedAction === undefined) {
4864
+ if (delegatedWorkflowPermit) {
4865
+ const permitError = validateWorkflowChildPermitRoot(delegatedWorkflowPermit, _id);
4866
+ if (permitError) return buildRequestedModeError(requestParams, permitError);
4867
+ if (requestParams.async !== false) return buildRequestedModeError(requestParams, "Workflow child permit supports foreground workflow roots only; set async:false.");
4868
+ }
4869
+ const workflowParentModel = parentModelOverride !== undefined
4870
+ ? parentModelOverride
4871
+ : (() => {
4872
+ const currentParentModel = normalizeParentModel(ctx.model);
4873
+ return (preserveActiveSession
4874
+ ? currentParentModel
4875
+ : rememberParentModel(deps.state, resolveCurrentSessionId(ctx.sessionManager), currentParentModel)) ?? null;
4876
+ })();
4292
4877
  if (requestParams.extensionBindings !== undefined) {
4293
4878
  try {
4294
4879
  requestParams.extensionBindings = normalizeExtensionBindings(requestParams.extensionBindings)!.value;
@@ -4301,7 +4886,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4301
4886
  const workflowUsageBudget = validateUsageBudgetConfig(requestParams.usageBudget ?? deps.config.usageBudget, requestParams.usageBudget ? "usageBudget" : "config.usageBudget");
4302
4887
  if (workflowUsageBudget.error) return buildRequestedModeError(requestParams, workflowUsageBudget.error);
4303
4888
  const workflowCwd = resolveRequestedCwd(parentCwd, requestParams.cwd);
4304
- const workflowAgents = deps.discoverAgents(workflowCwd, resolveExecutionAgentScope(requestParams.agentScope)).agents;
4889
+ const discoverWorkflowAgents = (cwd: string, scope: AgentScope) => deps.discoverAgents(cwd, scope, workflowParentModel?.provider);
4890
+ const workflowAgents = discoverWorkflowAgents(workflowCwd, resolveExecutionAgentScope(requestParams.agentScope)).agents;
4305
4891
  const workflowArtifactConfig: ArtifactConfig = omitUndefinedProperties({
4306
4892
  ...DEFAULT_ARTIFACT_CONFIG,
4307
4893
  enabled: requestParams.artifacts !== false,
@@ -4323,11 +4909,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4323
4909
  const scriptFirstLine = requestParams.workflowScript.split(/\r?\n/).map((line) => line.trim()).find(Boolean) || "Workflow";
4324
4910
  const boundedScriptPreview = scriptFirstLine.length > 100 ? `${scriptFirstLine.slice(0, 97)}...` : scriptFirstLine;
4325
4911
  const derivedObjective = previewAgent ? `Workflow: ${previewAgent}` : boundedScriptPreview;
4326
- const workflowDepth = checkSubagentDepth(deps.config.maxSubagentDepth).depth;
4912
+ const workflowDepth = checkSubagentDepth(deps.config.maxSubagentDepth, deps.childRuntime).depth;
4327
4913
  const asyncWorkflow = requestParams.async !== false;
4328
4914
  const topLevelAsyncWorkflow = asyncWorkflow
4329
4915
  && workflowDepth === 0
4330
- && !resolveInheritedNestedRouteFromEnv()
4916
+ && !inheritedNestedRoute(deps)
4331
4917
  && !requestParams.workflowParentRunId;
4332
4918
  const workflowRunId = asyncWorkflow ? randomUUID() : undefined;
4333
4919
  let workflowCapacity: ActiveAsyncCapacityHandle | undefined;
@@ -4340,7 +4926,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4340
4926
  runId: workflowRunId,
4341
4927
  kind: "workflow",
4342
4928
  asyncDir: path.join(DIRS.async, workflowRunId),
4343
- }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) });
4929
+ }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) });
4344
4930
  } catch (error) {
4345
4931
  if (error instanceof ActiveAsyncCapacityError) {
4346
4932
  deps.state.activeAsyncCapacity = error.snapshot;
@@ -4352,8 +4938,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4352
4938
  let workflowFanoutBudget: RunFanoutBudgetDescriptor;
4353
4939
  try {
4354
4940
  workflowFanoutBudget = requestParams.runFanoutBudget
4355
- ?? decodeRunFanoutBudgetDescriptor(process.env[RUN_FANOUT_BUDGET_ENV])
4356
- ?? createRunFanoutBudget(_id, resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun));
4941
+ ?? inheritedRunFanoutBudget(deps)
4942
+ ?? createRunFanoutBudget(_id, requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun));
4357
4943
  } catch (error) {
4358
4944
  workflowCapacity?.rollback();
4359
4945
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "workflow", results: [] } };
@@ -4414,7 +5000,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4414
5000
  deps.state.workflowChildStops ??= new Map();
4415
5001
  deps.state.workflowControllers.set(workflowRunId, controller);
4416
5002
  workflowCapacity?.markWorkflowStarted();
4417
- if (workflowCapacity) deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers.keys()) });
5003
+ if (workflowCapacity) deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers.keys()), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) });
4418
5004
  let status: AsyncStatus = {
4419
5005
  runId: workflowRunId,
4420
5006
  toolCallId,
@@ -4430,7 +5016,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4430
5016
  ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}),
4431
5017
  pid: process.pid,
4432
5018
  steps: [],
4433
- workflow: { trace: [], emits: [], console: [] },
5019
+ ...(workflowPreflight ? { preflight: workflowPreflight } : {}),
5020
+ workflow: { trace: [], emits: [], console: [], ...(workflowResource ? { resource: workflowResource.provenance } : {}) },
5021
+ workflowChildren: workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState: "running", inventoryComplete: false }),
4434
5022
  runFanoutBudget: getRunFanoutBudgetSnapshot(workflowFanoutBudget),
4435
5023
  };
4436
5024
  const appendWorkflowEvent = (event: Record<string, unknown>) => {
@@ -4479,6 +5067,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4479
5067
  if (persistClosed) return;
4480
5068
  const liveJob = deps.state.asyncJobs.get(workflowRunId);
4481
5069
  if (liveJob && (liveJob.status === "complete" || liveJob.status === "failed") && status.state !== "complete" && status.state !== "failed") return;
5070
+ const workflowState = status.state === "complete" ? "completed" : status.state === "failed" || status.state === "rejected" ? "failed" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "running";
5071
+ status.workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState, inventoryComplete: workflowState !== "running", trace: status.workflow?.trace, steps: status.steps });
4482
5072
  status.lastUpdate = Date.now();
4483
5073
  if (!initialPersistenceComplete) {
4484
5074
  writeAtomicJson(statusPath, status);
@@ -4514,6 +5104,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4514
5104
  liveJob.turnCount = status.turnCount;
4515
5105
  liveJob.toolCount = status.toolCount;
4516
5106
  liveJob.currentStep = status.currentStep;
5107
+ liveJob.preflight = status.preflight;
5108
+ liveJob.workflowGraph = status.workflowGraph;
4517
5109
  if (status.steps) {
4518
5110
  liveJob.steps = status.steps.map((step, index) => ({ ...step, index }));
4519
5111
  liveJob.agents = status.steps.map((step) => step.agent);
@@ -4522,6 +5114,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4522
5114
  delete liveJob.agents;
4523
5115
  }
4524
5116
  liveJob.workflow = status.workflow;
5117
+ liveJob.workflowChildren = status.workflowChildren;
4525
5118
  }
4526
5119
  };
4527
5120
  const writeWorkflowResult = (payload: Record<string, unknown>): boolean => {
@@ -4556,7 +5149,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4556
5149
  status.toolCount = toolCounts.length > 0 ? toolCounts.reduce((total, count) => total + count, 0) : undefined;
4557
5150
  status.currentStep = runningSteps.length === 1 ? steps.indexOf(runningSteps[0]!) : undefined;
4558
5151
  };
4559
- const workflowJob: AsyncJobState = { asyncId: workflowRunId, asyncDir, toolCallId, cwd: workflowCwd, ...(workflowSessionRoot ? { sessionRoot: workflowSessionRoot } : {}), status: "running", sessionId: currentSessionId ?? undefined, mode: "workflow", agents: [], steps: [], startedAt, updatedAt: startedAt, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), ...(timeout !== undefined ? { timeoutMs: timeout, deadlineAt: startedAt + timeout } : {}), workflow: status.workflow };
5152
+ const workflowJob: AsyncJobState = { asyncId: workflowRunId, asyncDir, toolCallId, cwd: workflowCwd, ...(workflowSessionRoot ? { sessionRoot: workflowSessionRoot } : {}), status: "running", sessionId: currentSessionId ?? undefined, mode: "workflow", agents: [], steps: [], ...(workflowPreflight ? { preflight: workflowPreflight } : {}), startedAt, updatedAt: startedAt, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), ...(timeout !== undefined ? { timeoutMs: timeout, deadlineAt: startedAt + timeout } : {}), workflow: status.workflow, workflowChildren: status.workflowChildren };
4560
5153
  deps.state.asyncJobs.set(workflowRunId, workflowJob);
4561
5154
  deps.state.fleetJobs ??= new Map();
4562
5155
  deps.state.fleetJobs.set(workflowRunId, workflowJob);
@@ -4576,18 +5169,37 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4576
5169
  const workflowDeadlineAt = timeout === undefined ? undefined : Date.now() + timeout;
4577
5170
  const workflowResults: SingleResult[] = [];
4578
5171
  const workflowChildRunIds = new Map<string, string>();
4579
- const { action: _action, agent: _agent, task: _task, resume: _resume, tasks: _tasks, chain: _chain, concurrency: _concurrency, foregroundOnly: _foregroundOnly, clarify: _clarify, timeoutMs: _timeoutMs, maxRuntimeMs: _maxRuntimeMs, usageBudget: _usageBudget, missionId: _missionId, mission: _mission, ...workflowChildDefaults } = workflowRequest;
5172
+ const { action: _action, agent: _agent, task: _task, resume: _resume, tasks: _tasks, chain: _chain, concurrency: _concurrency, foregroundOnly: _foregroundOnly, clarify: _clarify, timeoutMs: _timeoutMs, maxRuntimeMs: _maxRuntimeMs, usageBudget: _usageBudget, missionId: _missionId, mission: _mission, preflight: _preflight, globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowChildDefaults } = workflowRequest;
4580
5173
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
4581
5174
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
4582
- const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId));
5175
+ const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, parentCwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId));
4583
5176
  const claimedOutputPaths = new Map<string, string>();
4584
5177
  const childOutputOverrides = new Map<string, string>();
5178
+ const childOutputClaimPaths = new Map<string, string>();
4585
5179
  const producedChildOutputPaths = new Set<string>();
4586
5180
  const workflowSteps = new Map<string, NonNullable<AsyncStatus["steps"]>[number]>();
5181
+ const runHostCommand = workflowHostCommandRunner({
5182
+ workflowCwd,
5183
+ artifactsDir: workflowArtifactsDir,
5184
+ workflowRunId,
5185
+ claimedOutputPaths,
5186
+ producedOutputPaths: producedChildOutputPaths,
5187
+ ...(workflowResource ? { authorize: (key, params) => authorizeWorkflowResourceHost(workflowResource!.permit, key, params.command) } : {}),
5188
+ });
5189
+ const workflowHost = workflowResource
5190
+ ? workflowResource.authority.host ? runHostCommand : undefined
5191
+ : publicExecution ? undefined : runHostCommand;
4587
5192
  let projectedTraceLength = 0;
4588
5193
  let projectedTraceTail: NonNullable<Details["workflow"]>["trace"][number] | undefined;
4589
5194
  const updateTrace = (trace: NonNullable<Details["workflow"]>["trace"]) => {
4590
- status.workflow = { ...(status.workflow ?? { emits: [], console: [] }), trace };
5195
+ const projectedTrace = annotateWorkflowPreflightTrace(trace, workflowPreflight);
5196
+ const preflightWarnings = workflowPreflightWarnings(workflowPreflight, trace);
5197
+ status.workflow = {
5198
+ ...(status.workflow ?? { emits: [], console: [] }),
5199
+ trace: projectedTrace,
5200
+ ...(preflightWarnings.length ? { preflightWarnings } : {}),
5201
+ };
5202
+ if (status.workflowGraph) applyWorkflowLaneTrace(status.workflowGraph, trace);
4591
5203
  const rebuild = trace.length < projectedTraceLength
4592
5204
  || (projectedTraceLength > 0 && trace[projectedTraceLength - 1] !== projectedTraceTail);
4593
5205
  if (rebuild) {
@@ -4600,8 +5212,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4600
5212
  for (let index = projectedTraceLength; index < trace.length; index += 1) {
4601
5213
  const entry = trace[index]!;
4602
5214
  if (entry.operation !== "run") continue;
5215
+ const entryLabel = entry.label?.trim() || undefined;
5216
+ const entryPhase = entry.phase?.trim() || undefined;
5217
+ const shouldProjectPhase = entryPhase !== undefined && (entryPhase !== "auto-resume" || workflowSteps.get(entry.key)?.phase === undefined);
4603
5218
  const existing = workflowSteps.get(entry.key);
4604
- if (entry.state === "reused" && existing) continue;
5219
+ if (existing) {
5220
+ if (entryLabel) existing.label = entryLabel;
5221
+ if (shouldProjectPhase) existing.phase = entryPhase;
5222
+ }
5223
+ if (entry.state === "reused" && existing) {
5224
+ continue;
5225
+ }
4605
5226
  const mapped = entry.state === "started" || entry.state === "reused"
4606
5227
  ? "running"
4607
5228
  : entry.state === "completed"
@@ -4625,13 +5246,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4625
5246
  if (entry.durationMs === undefined) delete existing.durationMs;
4626
5247
  else existing.durationMs = entry.durationMs;
4627
5248
  } else {
5249
+ // Naming uses the explicit label only — never the workflow key — so the
5250
+ // placeholder cannot diverge from the task-derived name the child
5251
+ // session actually gets (launch/progress updates overwrite this).
5252
+ const stepSessionName = deriveChildSessionName({ agent: entry.agent ?? entry.key, label: entryLabel });
4628
5253
  const step: NonNullable<AsyncStatus["steps"]>[number] = {
4629
5254
  agent: entry.agent ?? entry.key,
4630
- label: entry.key,
5255
+ ...(stepSessionName ? { sessionName: stepSessionName } : {}),
5256
+ label: entryLabel ?? entry.key,
4631
5257
  workflowKey: entry.key,
4632
5258
  parentWorkflowRunId: workflowRunId,
4633
5259
  status: mapped,
4634
5260
  startedAt: Date.now(),
5261
+ ...(entryPhase ? { phase: entryPhase } : {}),
4635
5262
  ...(entry.runId ? { runId: entry.runId } : {}),
4636
5263
  ...(entry.state === "failed" && !entry.runId ? { async: false } : {}),
4637
5264
  ...(entry.state === "detached" ? { activityState: "needs_attention" as const } : {}),
@@ -4647,7 +5274,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4647
5274
  version: 1,
4648
5275
  childId: entry.key,
4649
5276
  status: "stopped",
4650
- reason: "user",
5277
+ reason: "subagent-action",
4651
5278
  source: "async",
4652
5279
  stepIndex: status.steps?.indexOf(projectedStep),
4653
5280
  agent: projectedStep.agent,
@@ -4667,19 +5294,39 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4667
5294
  try {
4668
5295
  const workflow = await runWorkflowScript({
4669
5296
  script: workflowScript,
5297
+ globalConcurrencyLimit: requestParams.globalConcurrencyLimit ?? deps.config.globalConcurrencyLimit,
4670
5298
  timeoutMs: timeout,
4671
5299
  signal: controller.signal,
5300
+ continueAfterAbortWhenChildrenSettled: (abortError) => {
5301
+ if (abortError.message !== "Workflow stopped because the extension session was replaced or reloaded.") return false;
5302
+ const activeAsyncChild = [...(deps.state.asyncJobs?.values() ?? [])].some((job) => job.parentWorkflowRunId === workflowRunId && (job.status === "queued" || job.status === "running"));
5303
+ const activeForegroundChild = [...deps.state.foregroundControls.values()].some((control) => control.parentWorkflowRunId === workflowRunId && (control.activeChildren?.size ?? 0) > 0);
5304
+ return !activeAsyncChild && !activeForegroundChild;
5305
+ },
4672
5306
  registerStopChild: (stop) => {
4673
5307
  if (stop) deps.state.workflowChildStops?.set(workflowRunId, stop);
4674
5308
  else deps.state.workflowChildStops?.delete(workflowRunId);
4675
5309
  },
4676
5310
  ...(workflowState ? { state: workflowState } : {}),
4677
5311
  onTrace: updateTrace,
5312
+ onLanePlan: (lanes) => {
5313
+ status.workflowGraph = buildWorkflowLaneGraph(workflowRunId, lanes, status.workflowGraph);
5314
+ applyWorkflowLaneTrace(status.workflowGraph, status.workflow?.trace ?? []);
5315
+ persist({ tolerateStatusWriteFailure: true });
5316
+ },
5317
+ ...(workflowHost ? { host: workflowHost } : {}),
5318
+ onHostStep: (hostStep) => {
5319
+ status = upsertHostStep({ status, hostStep, persist: (nextStatus) => {
5320
+ status = nextStatus;
5321
+ persist({ tolerateStatusWriteFailure: true });
5322
+ } });
5323
+ },
4678
5324
  admit: (calls) => {
4679
- const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
5325
+ const outputClaims = workflowChildOutputClaims({ ctxCwd: parentCwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
4680
5326
  if (outputClaims.error) throw new Error(outputClaims.error);
4681
5327
  status.runFanoutBudget = claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
4682
5328
  if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
5329
+ if (outputClaims.childClaims) for (const [key, claimPath] of outputClaims.childClaims) childOutputClaimPaths.set(key, claimPath);
4683
5330
  if (outputClaims.overrides) for (const [key, output] of outputClaims.overrides) childOutputOverrides.set(key, output);
4684
5331
  persist({ tolerateStatusWriteFailure: true });
4685
5332
  },
@@ -4692,7 +5339,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4692
5339
  launch: async (key, childParams, workflowSignal, admission) => {
4693
5340
  if (workflowUsageBudget.budget && childParams.async === true) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, "workflow usageBudget does not support async runs.run launches."), childParams, deps.state);
4694
5341
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
4695
- if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state);
5342
+ if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state, { state: "partial", reason: "budget_exhausted" });
4696
5343
  const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
4697
5344
  const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
4698
5345
  recordMissionWorkflowChild(missionBinding, workflowRunId, key, {
@@ -4702,19 +5349,23 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4702
5349
  ...(childPhase ? { phase: childPhase } : {}),
4703
5350
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
4704
5351
  });
5352
+ let preparedChildParams: SubagentParamsLike | undefined;
4705
5353
  const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, () => {
4706
5354
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
4707
- { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), options: { missionDetached: detachWorkflowChildMissions, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
5355
+ { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: parentCwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, awaitDetachedChild: true, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
4708
5356
  missionBinding,
4709
5357
  deps.asyncByDefault,
4710
5358
  );
5359
+ preparedChildParams = childRequest;
4711
5360
  workflowLaunchObservers.set(childRequest, (launch) => {
4712
5361
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
4713
5362
  if (step) {
4714
5363
  step.agent = launch.agent;
5364
+ if (launch.sessionName) step.sessionName = launch.sessionName;
4715
5365
  step.sessionFile = launch.sessionFile;
4716
5366
  step.async = launch.async;
4717
5367
  if (launch.runId) step.runId = launch.runId;
5368
+ if (childRequest.lane) step.lane = childRequest.lane;
4718
5369
  persist({ tolerateStatusWriteFailure: true });
4719
5370
  }
4720
5371
  recordMissionWorkflowChild(missionBinding, workflowRunId, key, { status: "running", agent: launch.agent, ...(launch.sessionFile ? { sessionPath: launch.sessionFile } : {}) });
@@ -4736,6 +5387,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4736
5387
  step.toolCount = progress.toolCount;
4737
5388
  step.model = progress.model;
4738
5389
  step.thinking = progress.thinking;
5390
+ if (progress.sessionName) step.sessionName = progress.sessionName;
4739
5391
  step.error = progress.error;
4740
5392
  projectWorkflowActivity();
4741
5393
  persist({ tolerateStatusWriteFailure: true });
@@ -4743,18 +5395,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4743
5395
  status: step.status,
4744
5396
  heartbeat: { status: step.status, ...(childPhase ? { phase: childPhase } : {}) },
4745
5397
  });
4746
- }, ctx, preserveActiveSession);
5398
+ }, ctx, preserveActiveSession, workflowParentModel);
4747
5399
  });
4748
5400
  workflowResults.push(...result.details.results);
4749
5401
  for (const childResult of result.details.results) {
4750
- if (childResult.savedOutputPath) producedChildOutputPaths.add(childResult.savedOutputPath);
5402
+ if (childResult.savedOutputPath) producedChildOutputPaths.add(resolveWorkflowHostOutputClaimPath(childResult.savedOutputPath));
4751
5403
  }
4752
- const child = workflowChildResult(key, result, childParams, deps.state);
5404
+ const child = workflowChildResult(key, result, preparedChildParams ?? childParams, deps.state);
4753
5405
  if (child.runId) workflowChildRunIds.set(key, child.runId);
4754
5406
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
4755
5407
  if (step) {
4756
5408
  step.async = Boolean(result.details.asyncId || result.details.asyncDir);
4757
5409
  if (child.runId) step.runId = child.runId;
5410
+ if (child.lane) step.lane = child.lane;
4758
5411
  }
4759
5412
  if (result.details.asyncDir && missionBinding) writeMissionAsyncBinding(result.details.asyncDir, missionBinding);
4760
5413
  const childStatus = missionWorkflowChildStatus(result);
@@ -4773,26 +5426,30 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4773
5426
  }
4774
5427
  return child;
4775
5428
  },
4776
- status: async (keyOrRunId, workflowSignal) => workflowChildResult(keyOrRunId, await execute(randomUUID(), { action: "status", id: keyOrRunId }, workflowSignal, undefined, ctx, preserveActiveSession)),
5429
+ status: async (keyOrRunId, workflowSignal) => workflowChildResult(keyOrRunId, await execute(randomUUID(), { action: "status", id: keyOrRunId }, workflowSignal, undefined, ctx, preserveActiveSession, workflowParentModel)),
4777
5430
  resolveResume: (reference) => resolveKeyedWorkflowResume(reference, deps.state),
4778
5431
  steer: (key, message, options, workflowSignal) => steerWorkflowChildByKey({ state: deps.state, workflowRunId, key, message, options, signal: workflowSignal, resolveRunId: () => workflowChildRunIds.get(key) }),
4779
5432
  });
5433
+ const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, workflow.trace, { settled: true });
5434
+ const finalPreflightTrace = annotateWorkflowPreflightTrace(workflow.trace, workflowPreflight);
4780
5435
  const returnPreview = formatWorkflowValue(workflow.value).slice(0, 1_000);
4781
5436
  const emitPreview = workflow.emits.length > 0 ? ` Emitted: ${workflow.emits.map(formatWorkflowValue).join(", ").slice(0, 1_000)}` : "";
4782
- const summary = `Workflow completed with ${workflow.children.length} child run(s). Return: ${returnPreview}${emitPreview} Trace: ${workflow.trace.length} event(s).`;
5437
+ const summary = `Workflow completed with ${workflow.children.length} child run(s). Return: ${returnPreview}${emitPreview} Trace: ${workflow.trace.length} event(s).${workflowOutputPathMappingSummary(workflow.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
4783
5438
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, summary, producedChildOutputPaths);
4784
5439
  const resultSummary = appendWorkflowOutputWarning(summary, outputWarning);
4785
5440
  const workflowUsage = sumResultsUsage(workflowResults);
4786
- status = { ...status, state: "complete", endedAt: Date.now(), workflow: { value: workflow.value, trace: workflow.trace, emits: workflow.emits, console: workflow.console }, totalTokens: { input: workflowUsage.input, output: workflowUsage.output, total: workflowUsage.input + workflowUsage.output }, totalCost: sumResultsCost(workflowResults) };
4787
- const receipt = terminalWorkflowReceipt(workflowRunId, "complete", workflow.children);
5441
+ const workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children, steps: status.steps });
5442
+ 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) };
5443
+ const receipt = terminalWorkflowReceipt(workflowRunId, "complete", workflow.children, workflowChildren, undefined, validHostStepNodes(status.workflowGraph), workflowResource?.provenance);
4788
5444
  let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
4789
5445
  try {
4790
5446
  workflowReceipt = { path: writeWorkflowReceipt(asyncDir, receipt), receipt };
4791
5447
  } catch (receiptError) {
4792
5448
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
4793
5449
  }
4794
- if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary: resultSummary, output: resultSummary, results: workflow.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
5450
+ if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary: resultSummary, output: resultSummary, workflowChildren, results: workflow.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(status.steps?.find((step) => step.workflowKey === child.key)?.sessionName ? { sessionName: status.steps?.find((step) => step.workflowKey === child.key)?.sessionName } : {}), ...workflowChildAccountingFields(child), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.outputReference ? { outputReference: child.outputReference } : {}), ...(child.outputPathMapping ? { outputPathMapping: child.outputPathMapping } : {}), ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
4795
5451
  persist();
5452
+ deps.refreshResultDelivery?.();
4796
5453
  persistClosed = true;
4797
5454
  appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(status.error ? { error: status.error } : {}) });
4798
5455
  } catch (error) {
@@ -4813,28 +5470,34 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4813
5470
  delete step.activityState;
4814
5471
  }
4815
5472
  }
4816
- status = compactOptional<AsyncStatus>({ ...status, state, stopped: stopped || undefined, activityState: pauseForDetached ? "needs_attention" : undefined, error: error instanceof Error ? error.message : String(error), endedAt: Date.now(), workflow: { trace: partial.trace, emits: partial.emits, console: partial.console } });
5473
+ const workflowState = state === "paused" ? "paused" : state === "stopped" ? "stopped" : "failed";
5474
+ const workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState, inventoryComplete: true, trace: partial.trace, children: partial.children, steps: status.steps });
5475
+ const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, partial.trace, { settled: true });
5476
+ const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
5477
+ status = compactOptional<AsyncStatus>({ ...status, state, stopped: stopped || undefined, activityState: pauseForDetached ? "needs_attention" : undefined, error: workflowFailureMessage(error, workflowRunId, partial.children), endedAt: Date.now(), workflow: { trace: finalPreflightTrace, emits: partial.emits, console: partial.console, ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}) }, workflowChildren });
4817
5478
  if (pauseForDetached) {
4818
5479
  const promoted = promotePausedWorkflowIfSettled(status);
4819
5480
  if (promoted) status = promoted;
4820
5481
  }
4821
- const terminalSummary = status.state === "complete"
5482
+ const terminalSummary = `${status.state === "complete"
4822
5483
  ? "Workflow completed after detached child finished."
4823
- : status.error ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.");
5484
+ : status.error ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.")}${workflowOutputPathMappingSummary(partial.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
4824
5485
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, terminalSummary, producedChildOutputPaths);
4825
5486
  const resultSummary = appendWorkflowOutputWarning(terminalSummary, outputWarning);
4826
5487
  const receiptState: WorkflowReceiptState = status.state === "complete" ? "complete" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "failed";
4827
- const receipt = terminalWorkflowReceipt(workflowRunId, receiptState, partial.children);
5488
+ const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
5489
+ const receipt = terminalWorkflowReceipt(workflowRunId, receiptState, partial.children, workflowChildren, terminalOutcome, validHostStepNodes(status.workflowGraph), workflowResource?.provenance);
4828
5490
  let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
4829
5491
  try {
4830
5492
  workflowReceipt = { path: writeWorkflowReceipt(asyncDir, receipt), receipt };
4831
5493
  } catch (receiptError) {
4832
5494
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
4833
5495
  }
4834
- if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: status.state === "complete", state: status.state, summary: resultSummary, error: status.state === "complete" ? undefined : status.error, stopped: status.stopped, activityState: status.activityState, results: partial.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(child.detached && status.state !== "complete" ? { detached: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
5496
+ if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: status.state === "complete", state: status.state, summary: resultSummary, error: status.state === "complete" ? undefined : status.error, stopped: status.stopped, activityState: status.activityState, workflowChildren, ...(terminalOutcome ? { terminalOutcome } : {}), results: partial.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(status.steps?.find((step) => step.workflowKey === child.key)?.sessionName ? { sessionName: status.steps?.find((step) => step.workflowKey === child.key)?.sessionName } : {}), ...workflowChildAccountingFields(child), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.outputReference ? { outputReference: child.outputReference } : {}), ...(child.terminalOutcome ? { terminalOutcome: child.terminalOutcome } : {}), ...(child.outputPathMapping ? { outputPathMapping: child.outputPathMapping } : {}), ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(child.detached && status.state !== "complete" ? { detached: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
4835
5497
  persist();
5498
+ deps.refreshResultDelivery?.();
4836
5499
  persistClosed = true;
4837
- appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(status.error ? { error: status.error } : {}), ...(status.activityState ? { activityState: status.activityState } : {}) });
5500
+ appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(terminalOutcome ? { terminalOutcome } : {}), ...(status.error ? { error: status.error } : {}), ...(status.activityState ? { activityState: status.activityState } : {}) });
4838
5501
  } finally {
4839
5502
  persistClosed = true;
4840
5503
  deps.state.workflowControllers?.delete(workflowRunId);
@@ -4844,41 +5507,67 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4844
5507
  }
4845
5508
  });
4846
5509
  return attachWorkflowMission(withRunFanoutBudget({
4847
- content: [{ type: "text", text: formatAsyncStartedMessage(`Async workflow [${workflowRunId}]`, ctx.hasUI === true) }],
4848
- details: { mode: "workflow", runId: workflowRunId, toolCallId, asyncId: workflowRunId, asyncDir, results: [], chatProgress, ...(deps.state.activeAsyncCapacity ? { activeAsyncCapacity: deps.state.activeAsyncCapacity } : {}) },
5510
+ content: [{ type: "text", text: `${workflowPreflight ? `${formatWorkflowPreflight(workflowPreflight)}\n\n` : ""}${formatAsyncStartedMessage(`Async workflow [${workflowRunId}]`, ctx.hasUI === true)}` }],
5511
+ details: { mode: "workflow", runId: workflowRunId, toolCallId, asyncId: workflowRunId, asyncDir, results: [], ...(workflowPreflight ? { preflight: workflowPreflight } : {}), workflow: status.workflow, workflowChildren: status.workflowChildren, chatProgress, ...(deps.state.activeAsyncCapacity ? { activeAsyncCapacity: deps.state.activeAsyncCapacity } : {}) },
4849
5512
  }, workflowFanoutBudget));
4850
5513
  }
4851
- const { workflowScript: _workflowScript, action: _action, agent: _agent, task: _task, resume: _resume, tasks: _tasks, chain: _chain, concurrency: _concurrency, async: _async, foregroundOnly: _foregroundOnly, clarify: _clarify, timeoutMs: _timeoutMs, maxRuntimeMs: _maxRuntimeMs, usageBudget: _usageBudget, chatProgress: _chatProgress, missionId: _missionId, mission: _mission, ...workflowChildDefaults } = requestParams;
5514
+ const { workflowScript: _workflowScript, action: _action, agent: _agent, task: _task, resume: _resume, tasks: _tasks, chain: _chain, concurrency: _concurrency, async: _async, foregroundOnly: _foregroundOnly, clarify: _clarify, timeoutMs: _timeoutMs, maxRuntimeMs: _maxRuntimeMs, usageBudget: _usageBudget, chatProgress: _chatProgress, missionId: _missionId, mission: _mission, preflight: _preflight, globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowChildDefaults } = requestParams;
4852
5515
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
4853
5516
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
4854
5517
  const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, _id));
4855
5518
  const claimedOutputPaths = new Map<string, string>();
4856
5519
  const childOutputOverrides = new Map<string, string>();
5520
+ const childOutputClaimPaths = new Map<string, string>();
4857
5521
  const producedChildOutputPaths = new Set<string>();
4858
5522
  const workflowResults: SingleResult[] = [];
4859
5523
  const workflowChildRunIds = new Map<string, string>();
4860
- let liveWorkflow: NonNullable<Details["workflow"]> = { trace: [], emits: [], console: [] };
5524
+ const runHostCommand = workflowHostCommandRunner({
5525
+ workflowCwd,
5526
+ artifactsDir: workflowArtifactsDir,
5527
+ workflowRunId: _id,
5528
+ claimedOutputPaths,
5529
+ producedOutputPaths: producedChildOutputPaths,
5530
+ ...(workflowResource ? { authorize: (key, params) => authorizeWorkflowResourceHost(workflowResource!.permit, key, params.command) } : {}),
5531
+ });
5532
+ const workflowHost = delegatedWorkflowPermit
5533
+ ? undefined
5534
+ : workflowResource
5535
+ ? workflowResource.authority.host ? runHostCommand : undefined
5536
+ : publicExecution ? undefined : runHostCommand;
5537
+ const workflowHostSteps = new Map<string, HostStepNodeV1>();
5538
+ let liveWorkflow: NonNullable<Details["workflow"]> = { trace: [], emits: [], console: [], ...(workflowResource ? { resource: workflowResource.provenance } : {}) };
5539
+ let liveWorkflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "running", inventoryComplete: false });
4861
5540
  const workflowDeadlineAt = timeout === undefined ? undefined : Date.now() + timeout;
4862
5541
  const workflowCapabilityCeiling = intersectSubagentCapabilityCeilings(requestParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(resolveCurrentSessionId(ctx.sessionManager)));
4863
5542
  const sendWorkflowProgress = () => {
4864
- const update = workflowChatProgressUpdate(_id, chatProgress, liveWorkflow);
5543
+ const update = workflowChatProgressUpdate(_id, chatProgress, liveWorkflow, liveWorkflowChildren, workflowPreflight);
4865
5544
  if (update) onUpdate?.(update);
4866
5545
  };
4867
5546
  try {
4868
5547
  const workflow = await runWorkflowScript({
4869
5548
  script: requestParams.workflowScript,
5549
+ ...(delegatedWorkflowPermit ? { oneUsePermit: { claim: (key: string) => claimWorkflowChildPermit(delegatedWorkflowPermit, _id, key) } } : {}),
5550
+ globalConcurrencyLimit: requestParams.globalConcurrencyLimit ?? deps.config.globalConcurrencyLimit,
4870
5551
  timeoutMs: timeout,
4871
5552
  signal,
4872
5553
  ...(workflowState ? { state: workflowState } : {}),
5554
+ ...(workflowHost ? { host: workflowHost } : {}),
5555
+ onHostStep: (hostStep) => {
5556
+ workflowHostSteps.set(hostStep.id, { ...hostStep, ...(hostStep.freshness ? { freshness: { ...hostStep.freshness } } : {}) });
5557
+ },
4873
5558
  onTrace: (trace) => {
4874
- liveWorkflow = { ...liveWorkflow, trace };
5559
+ const projectedTrace = annotateWorkflowPreflightTrace(trace, workflowPreflight);
5560
+ const preflightWarnings = workflowPreflightWarnings(workflowPreflight, trace);
5561
+ liveWorkflow = { ...liveWorkflow, trace: projectedTrace, ...(preflightWarnings.length ? { preflightWarnings } : {}) };
5562
+ liveWorkflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "running", inventoryComplete: false, trace });
4875
5563
  sendWorkflowProgress();
4876
5564
  },
4877
5565
  admit: (calls) => {
4878
- const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId: _id, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
5566
+ const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId: _id, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
4879
5567
  if (outputClaims.error) throw new Error(outputClaims.error);
4880
5568
  claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
4881
5569
  if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
5570
+ if (outputClaims.childClaims) for (const [key, claimPath] of outputClaims.childClaims) childOutputClaimPaths.set(key, claimPath);
4882
5571
  if (outputClaims.overrides) for (const [key, output] of outputClaims.overrides) childOutputOverrides.set(key, output);
4883
5572
  },
4884
5573
  onEmit: (emits) => {
@@ -4886,9 +5575,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4886
5575
  sendWorkflowProgress();
4887
5576
  },
4888
5577
  launch: async (key, childParams, workflowSignal, admission) => {
5578
+ if (delegatedWorkflowPermit && admission.batch) throw new Error("Workflow child permit does not support runs.all.");
5579
+ if (delegatedWorkflowPermit && childParams.resume !== undefined) throw new Error("Workflow child permit does not support retained resume.");
5580
+ if (delegatedWorkflowPermit && childParams.async === true) throw new Error("Workflow child permit supports one foreground child only.");
4889
5581
  if (workflowUsageBudget.budget && childParams.async === true) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, "workflow usageBudget does not support async runs.run launches."), childParams, deps.state);
4890
5582
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
4891
- if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state);
5583
+ if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state, { state: "partial", reason: "budget_exhausted" });
4892
5584
  const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
4893
5585
  const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
4894
5586
  recordMissionWorkflowChild(missionBinding, _id, key, {
@@ -4898,12 +5590,23 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4898
5590
  ...(childPhase ? { phase: childPhase } : {}),
4899
5591
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
4900
5592
  });
5593
+ let preparedChildParams: SubagentParamsLike | undefined;
4901
5594
  const result = await runMissionWorkflowChild(missionBinding, _id, key, childPhase, () => {
4902
5595
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
4903
- { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: _id, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
5596
+ { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: _id, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
4904
5597
  missionBinding,
4905
5598
  deps.asyncByDefault,
4906
5599
  );
5600
+ preparedChildParams = childRequest;
5601
+ if (delegatedWorkflowPermit) {
5602
+ if (childRequest.async !== false) throw new Error("Workflow child permit supports one foreground child only.");
5603
+ const childCwd = resolveRequestedCwd(workflowCwd, childRequest.cwd);
5604
+ const childAgent = typeof childRequest.agent === "string"
5605
+ ? resolveAgentName(childRequest.agent, discoverWorkflowAgents(childCwd, resolveExecutionAgentScope(childRequest.agentScope)).agents).agent
5606
+ : undefined;
5607
+ if (childAgent?.runner?.type === "external-cli" || childAgent?.runner?.type === "external-job") throw new Error("Workflow child permit supports native Pi children only.");
5608
+ workflowPermitContexts.set(childRequest, { child: { permit: delegatedWorkflowPermit, workflowRunId: _id, childKey: key } });
5609
+ }
4907
5610
  workflowLaunchObservers.set(childRequest, (launch) => recordMissionWorkflowChild(missionBinding, _id, key, {
4908
5611
  status: "running",
4909
5612
  agent: launch.agent,
@@ -4917,14 +5620,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4917
5620
  status: progressStatus,
4918
5621
  heartbeat: { status: progressStatus, ...(childPhase ? { phase: childPhase } : {}) },
4919
5622
  });
4920
- }, ctx, preserveActiveSession);
5623
+ }, ctx, preserveActiveSession, workflowParentModel);
4921
5624
  });
4922
5625
  workflowResults.push(...result.details.results);
4923
5626
  for (const childResult of result.details.results) {
4924
- if (childResult.savedOutputPath) producedChildOutputPaths.add(childResult.savedOutputPath);
5627
+ if (childResult.savedOutputPath) producedChildOutputPaths.add(resolveWorkflowHostOutputClaimPath(childResult.savedOutputPath));
4925
5628
  }
4926
5629
  if (result.details.asyncDir && missionBinding) writeMissionAsyncBinding(result.details.asyncDir, missionBinding);
4927
- const child = workflowChildResult(key, result, childParams, deps.state);
5630
+ const child = workflowChildResult(key, result, preparedChildParams ?? childParams, deps.state);
4928
5631
  if (child.runId) workflowChildRunIds.set(key, child.runId);
4929
5632
  const childStatus = missionWorkflowChildStatus(result);
4930
5633
  recordMissionWorkflowChild(missionBinding, _id, key, {
@@ -4938,43 +5641,64 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4938
5641
  });
4939
5642
  return child;
4940
5643
  },
4941
- status: async (keyOrRunId, workflowSignal) => workflowChildResult(keyOrRunId, await execute(randomUUID(), { action: "status", id: keyOrRunId }, workflowSignal, undefined, ctx, preserveActiveSession)),
5644
+ status: async (keyOrRunId, workflowSignal) => workflowChildResult(keyOrRunId, await execute(randomUUID(), { action: "status", id: keyOrRunId }, workflowSignal, undefined, ctx, preserveActiveSession, workflowParentModel)),
4942
5645
  resolveResume: (reference) => resolveKeyedWorkflowResume(reference, deps.state),
4943
5646
  steer: (key, message, options, workflowSignal) => steerWorkflowChildByKey({ state: deps.state, workflowRunId: _id, key, message, options, signal: workflowSignal, resolveRunId: () => workflowChildRunIds.get(key) }),
4944
5647
  });
4945
- const receipt = terminalWorkflowReceipt(_id, "complete", workflow.children);
4946
- const traceLines = workflow.trace.map((entry) => `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.durationMs !== undefined ? ` in ${entry.durationMs}ms` : ""}${entry.error ? ` — ${entry.error}` : ""}`);
4947
- const sections = ["Workflow completed.", `Return:\n${formatWorkflowValue(workflow.value)}`];
5648
+ const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, workflow.trace, { settled: true });
5649
+ const finalPreflightTrace = annotateWorkflowPreflightTrace(workflow.trace, workflowPreflight);
5650
+ const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children });
5651
+ const receipt = terminalWorkflowReceipt(_id, "complete", workflow.children, workflowChildren, undefined, [...workflowHostSteps.values()], workflowResource?.provenance);
5652
+ 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}` : ""}`);
5653
+ const sections = [
5654
+ ...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []),
5655
+ "Workflow completed.",
5656
+ `Return:\n${formatWorkflowValue(workflow.value)}`,
5657
+ ];
4948
5658
  if (workflow.emits.length > 0) sections.push(`Emitted:\n${workflow.emits.map(formatWorkflowValue).join("\n")}`);
4949
5659
  if (workflow.console.length > 0) sections.push(`Console:\n${workflow.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
4950
5660
  if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
5661
+ if (finalPreflightWarnings.length > 0) sections.push(formatWorkflowPreflightWarnings(finalPreflightWarnings));
5662
+ const outputMappings = workflowOutputPathMappingSummary(workflow.children).trim();
5663
+ if (outputMappings) sections.push(outputMappings);
4951
5664
  const workflowText = sections.join("\n\n");
4952
5665
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText, producedChildOutputPaths);
4953
5666
  const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
4954
5667
  return attachWorkflowMission(withRunFanoutBudget({
4955
5668
  content: [{ type: "text", text: displayText }],
4956
- details: compactOptional<Details>({ mode: "workflow", runId: _id, results: workflow.children.flatMap((child) => (child.results ?? []) as SingleResult[]), totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { value: workflow.value, trace: workflow.trace, emits: workflow.emits, console: workflow.console, receipt }, chatProgress }),
5669
+ details: compactOptional<Details>({ mode: "workflow", runId: _id, results: workflowDetailsResults(workflow.children), ...(workflowPreflight ? { preflight: workflowPreflight } : {}), workflowChildren, totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { value: workflow.value, trace: finalPreflightTrace, emits: workflow.emits, console: workflow.console, ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}), receipt }, chatProgress }),
4957
5670
  }, workflowFanoutBudget));
4958
5671
  } catch (error) {
4959
5672
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
4960
- const text = error instanceof Error ? error.message : String(error);
4961
- const traceLines = partial.trace.map((entry) => `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.error ? ` — ${entry.error}` : ""}`);
4962
- const sections = [`Workflow failed: ${text}`];
5673
+ const text = workflowFailureMessage(error, _id, partial.children);
5674
+ const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, partial.trace, { settled: true });
5675
+ const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
5676
+ const traceLines = finalPreflightTrace.map((entry) => `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.warning ? ` — ${entry.warning}` : ""}${entry.error ? ` — ${entry.error}` : ""}`);
5677
+ const sections = [
5678
+ ...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []),
5679
+ `Workflow failed: ${text}`,
5680
+ ];
4963
5681
  if (partial.emits.length > 0) sections.push(`Emitted:\n${partial.emits.map(formatWorkflowValue).join("\n")}`);
4964
5682
  if (partial.console.length > 0) sections.push(`Console:\n${partial.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
4965
5683
  if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
5684
+ if (finalPreflightWarnings.length > 0) sections.push(formatWorkflowPreflightWarnings(finalPreflightWarnings));
5685
+ const outputMappings = workflowOutputPathMappingSummary(partial.children).trim();
5686
+ if (outputMappings) sections.push(outputMappings);
4966
5687
  const workflowText = sections.join("\n\n");
4967
5688
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText, producedChildOutputPaths);
4968
5689
  const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
4969
- const receipt = terminalWorkflowReceipt(_id, "failed", partial.children);
5690
+ const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: _id, workflowState: "failed", inventoryComplete: true, trace: partial.trace, children: partial.children });
5691
+ const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
5692
+ const receipt = terminalWorkflowReceipt(_id, "failed", partial.children, workflowChildren, terminalOutcome, [...workflowHostSteps.values()], workflowResource?.provenance);
4970
5693
  return attachWorkflowMission(withRunFanoutBudget({
4971
5694
  content: [{ type: "text", text: displayText }],
4972
5695
  isError: true,
4973
- details: compactOptional<Details>({ mode: "workflow", runId: _id, results: partial.children.flatMap((child) => (child.results ?? []) as SingleResult[]), totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { trace: partial.trace, emits: partial.emits, console: partial.console, receipt }, chatProgress }),
5696
+ details: compactOptional<Details>({ mode: "workflow", runId: _id, results: workflowDetailsResults(partial.children), ...(workflowPreflight ? { preflight: workflowPreflight } : {}), workflowChildren, totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { trace: finalPreflightTrace, emits: partial.emits, console: partial.console, ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}), receipt }, chatProgress }),
4974
5697
  }, workflowFanoutBudget));
4975
5698
  }
4976
5699
  }
4977
5700
  const directParams = requestParams;
5701
+ const requestedCwd = directParams.cwd;
4978
5702
  const requestCwd = resolveRequestedCwd(ctx.cwd, directParams.cwd);
4979
5703
  const paramsWithResolvedCwd = directParams.cwd === undefined ? directParams : { ...directParams, cwd: requestCwd };
4980
5704
  const action = paramsWithResolvedCwd.action;
@@ -4984,14 +5708,45 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4984
5708
  try {
4985
5709
  requestSessionId = resolveCurrentSessionId(ctx.sessionManager);
4986
5710
  requestPiSessionId = ctx.sessionManager.getSessionId() ?? undefined;
4987
- requestParentModel = preserveActiveSession
4988
- ? normalizeParentModel(ctx.model)
4989
- : rememberParentModel(deps.state, requestSessionId, ctx.model);
5711
+ requestParentModel = parentModelOverride !== undefined
5712
+ ? parentModelOverride ?? undefined
5713
+ : preserveActiveSession
5714
+ ? normalizeParentModel(ctx.model)
5715
+ : rememberParentModel(deps.state, requestSessionId, ctx.model);
4990
5716
  } catch (error) {
4991
5717
  if (action?.toLowerCase() !== "doctor" && action?.toLowerCase() !== "guide") throw error;
4992
5718
  requestParentModel = normalizeParentModel(ctx.model);
4993
5719
  }
4994
5720
  if (action) {
5721
+ if (action === "worktree.cleanup") {
5722
+ if (deps.allowMutatingManagementActions === false) {
5723
+ return { content: [{ type: "text", text: "Action 'worktree.cleanup' is not available from child-safe subagent fanout mode." }], isError: true, details: { mode: "management", results: [] } };
5724
+ }
5725
+ if (paramsWithResolvedCwd.mode !== "plan") {
5726
+ return { content: [{ type: "text", text: "worktree.cleanup currently supports mode='plan' only; apply/removal is not available yet." }], isError: true, details: { mode: "management", results: [] } };
5727
+ }
5728
+ if (paramsWithResolvedCwd.planId !== undefined) {
5729
+ return { content: [{ type: "text", text: "worktree.cleanup plan mode does not accept planId; apply is not available yet." }], isError: true, details: { mode: "management", results: [] } };
5730
+ }
5731
+ try {
5732
+ const created = createWorktreeCleanupPlan({
5733
+ repo: paramsWithResolvedCwd.repo?.trim()
5734
+ ? path.isAbsolute(paramsWithResolvedCwd.repo) ? paramsWithResolvedCwd.repo : path.resolve(requestCwd, paramsWithResolvedCwd.repo)
5735
+ : requestCwd,
5736
+ ...(paramsWithResolvedCwd.handoffPath ? { handoffPath: path.isAbsolute(paramsWithResolvedCwd.handoffPath) ? paramsWithResolvedCwd.handoffPath : path.resolve(requestCwd, paramsWithResolvedCwd.handoffPath) } : {}),
5737
+ ...(deps.config.worktreeBaseDir ? { worktreeBaseDir: deps.config.worktreeBaseDir } : {}),
5738
+ foregroundRunOwnership: (runId: string) => {
5739
+ if (deps.state.foregroundControls.has(runId)) return "active" as const;
5740
+ const remembered = deps.state.foregroundRuns?.get(runId);
5741
+ if (!remembered || remembered.children.length === 0 || remembered.children.some((child) => child.status === "detached")) return "unknown" as const;
5742
+ return "terminal" as const;
5743
+ },
5744
+ });
5745
+ return { content: [{ type: "text", text: formatWorktreeCleanupPlan(created) }], details: { mode: "management", results: [] } };
5746
+ } catch (error) {
5747
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
5748
+ }
5749
+ }
4995
5750
  if (action === "worktree.discard") {
4996
5751
  if (deps.allowMutatingManagementActions === false) {
4997
5752
  return { content: [{ type: "text", text: "Action 'worktree.discard' is not available from child-safe subagent fanout mode." }], isError: true, details: { mode: "management", results: [] } };
@@ -5019,6 +5774,30 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5019
5774
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
5020
5775
  }
5021
5776
  }
5777
+ if (action === "lane.status" || action === "lane.recordMerge" || action === "lane.recordSupersession") {
5778
+ if (action !== "lane.status" && deps.allowMutatingManagementActions === false) {
5779
+ return { content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }], isError: true, details: { mode: "management", results: [] } };
5780
+ }
5781
+ const laneId = paramsWithResolvedCwd.laneId?.trim();
5782
+ if (!laneId) return { content: [{ type: "text", text: `${action} requires laneId.` }], isError: true, details: { mode: "management", results: [] } };
5783
+ const handoffPath = paramsWithResolvedCwd.handoffPath?.trim();
5784
+ if (!handoffPath) return { content: [{ type: "text", text: `${action} requires handoffPath for the existing parallel handoff manifest.` }], isError: true, details: { mode: "management", results: [] } };
5785
+ const manifestPath = path.isAbsolute(handoffPath) ? handoffPath : path.resolve(requestCwd, handoffPath);
5786
+ try {
5787
+ if (action === "lane.status") {
5788
+ let manifest;
5789
+ try { manifest = readParallelHandoffManifest(manifestPath); } catch { manifest = undefined; }
5790
+ if (manifest && manifest.runId !== laneId) throw new Error(`Lane '${laneId}' does not match manifest run '${manifest.runId}'.`);
5791
+ return { content: [{ type: "text", text: formatStoredParallelHandoffCleanup(manifestPath, manifest) }], details: { mode: "management", results: [] } };
5792
+ }
5793
+ const recorded = action === "lane.recordMerge"
5794
+ ? recordParallelHandoffMerge({ manifestPath, laneId, merge: paramsWithResolvedCwd.merge })
5795
+ : recordParallelHandoffSupersession({ manifestPath, laneId, supersession: paramsWithResolvedCwd.supersession });
5796
+ return { content: [{ type: "text", text: recorded.text }], details: { mode: "management", results: [], parallelHandoff: recorded.reference } };
5797
+ } catch (error) {
5798
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
5799
+ }
5800
+ }
5022
5801
  if ((HERDR_PROJECT_PANE_ACTIONS as readonly string[]).includes(action)) {
5023
5802
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
5024
5803
  return { content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }], isError: true, details: { mode: "management", results: [] } };
@@ -5211,7 +5990,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5211
5990
  }
5212
5991
  const spawnBudget = getSpawnBudgetSnapshot(deps.state, deps.config, currentSessionId);
5213
5992
  const activeAsyncCapacity = currentSessionId
5214
- ? getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) })
5993
+ ? getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })
5215
5994
  : { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession) ?? 0 };
5216
5995
  deps.state.activeAsyncCapacity = activeAsyncCapacity;
5217
5996
  return {
@@ -5256,10 +6035,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5256
6035
  if (paramsWithResolvedCwd.view) {
5257
6036
  return withBudget({ content: [{ type: "text", text: "action='debug.run' does not support status views." }], isError: true, details: { mode: "management", results: [] } });
5258
6037
  }
5259
- return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots })));
6038
+ return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots, abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })));
5260
6039
  }
5261
6040
  if (paramsWithResolvedCwd.view === "fleet") {
5262
- return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots })));
6041
+ return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots, abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })));
5263
6042
  }
5264
6043
  if (targetRunId) {
5265
6044
  try {
@@ -5290,12 +6069,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5290
6069
  });
5291
6070
  }
5292
6071
  }
5293
- return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots })));
6072
+ return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots, abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })));
5294
6073
  }
5295
6074
  if (action === "resume") {
5296
6075
  return resumeAsyncRun(omitUndefinedProperties({ params: paramsWithResolvedCwd, requestCwd, ctx, deps, parentModel: requestParentModel, signal }));
5297
6076
  }
5298
6077
  if (action === "steer") {
6078
+ if (paramsWithResolvedCwd.mode !== undefined && resolveSteerDeliveryMode(paramsWithResolvedCwd.mode) === undefined) {
6079
+ return { content: [{ type: "text", text: "action='steer' mode must be 'steer', 'follow_up', or 'auto'." }], isError: true, details: { mode: "management", results: [] } };
6080
+ }
5299
6081
  deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
5300
6082
  const message = (paramsWithResolvedCwd.message ?? paramsWithResolvedCwd.task ?? "").trim();
5301
6083
  if (!message) return { content: [{ type: "text", text: "action='steer' requires message." }], isError: true, details: { mode: "management", results: [] } };
@@ -5308,7 +6090,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5308
6090
  if (directoryStatus?.mode === "workflow") {
5309
6091
  const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, workflowRunId: directoryStatus.runId || runId, asyncDirRoot: DIRS.async });
5310
6092
  if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
5311
- return steerWorkflowForegroundTarget({ target: route.target, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal });
6093
+ return steerWorkflowForegroundTarget({ target: route.target, message, mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode), index: paramsWithResolvedCwd.index });
5312
6094
  }
5313
6095
  if (location.asyncDir) {
5314
6096
  const unsupported = externalRunnerControlError(location.asyncDir, "steer");
@@ -5318,7 +6100,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5318
6100
  state: deps.state,
5319
6101
  runId,
5320
6102
  message,
5321
- mode: paramsWithResolvedCwd.mode,
6103
+ mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode),
5322
6104
  index: paramsWithResolvedCwd.index,
5323
6105
  kill: deps.kill,
5324
6106
  location,
@@ -5344,18 +6126,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5344
6126
  const text = error instanceof Error ? error.message : String(error);
5345
6127
  return { content: [{ type: "text", text }], isError: true, details: { mode: "management", results: [] } };
5346
6128
  }
5347
- if (resolved?.kind === "nested") return steerNestedRun(omitUndefinedProperties({ target: resolved, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal }));
6129
+ if (resolved?.kind === "nested") return steerNestedRun(omitUndefinedProperties({ target: resolved, message, mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode), index: paramsWithResolvedCwd.index, signal }));
5348
6130
  if (resolved?.kind === "foreground") {
5349
6131
  const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, childRunId: resolved.id, asyncDirRoot: DIRS.async });
5350
6132
  if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
5351
- return steerWorkflowForegroundTarget({ target: route.target, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal });
6133
+ return steerWorkflowForegroundTarget({ target: route.target, message, mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode), index: paramsWithResolvedCwd.index });
5352
6134
  }
5353
6135
  if (resolved?.kind !== "async") return { content: [{ type: "text", text: `No async run found for '${targetRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
5354
6136
  const resolvedStatus = resolved.location.asyncDir ? readStatus(resolved.location.asyncDir) : null;
5355
6137
  if (resolvedStatus?.mode === "workflow") {
5356
6138
  const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, workflowRunId: resolvedStatus.runId || resolved.id, asyncDirRoot: DIRS.async });
5357
6139
  if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
5358
- return steerWorkflowForegroundTarget({ target: route.target, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal });
6140
+ return steerWorkflowForegroundTarget({ target: route.target, message, mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode), index: paramsWithResolvedCwd.index });
5359
6141
  }
5360
6142
  if (resolved.location.asyncDir) {
5361
6143
  const unsupported = externalRunnerControlError(resolved.location.asyncDir, "steer");
@@ -5365,7 +6147,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5365
6147
  state: deps.state,
5366
6148
  runId: resolved.id,
5367
6149
  message,
5368
- mode: paramsWithResolvedCwd.mode,
6150
+ mode: resolveSteerDeliveryMode(paramsWithResolvedCwd.mode),
5369
6151
  index: paramsWithResolvedCwd.index,
5370
6152
  kill: deps.kill,
5371
6153
  location: resolved.location,
@@ -5434,9 +6216,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5434
6216
  if (action === "stop") {
5435
6217
  const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
5436
6218
  const workflowController = targetRunId ? deps.state.workflowControllers?.get(targetRunId) : undefined;
5437
- if (workflowController) {
6219
+ if (workflowController && targetRunId) {
6220
+ const stopChild = deps.state.workflowChildStops?.get(targetRunId);
5438
6221
  if (paramsWithResolvedCwd.childId !== undefined) {
5439
- const workflowRunId = targetRunId!;
6222
+ const workflowRunId = targetRunId;
5440
6223
  const asyncJob = deps.state.asyncJobs.get(workflowRunId);
5441
6224
  if (!asyncJob?.asyncDir) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
5442
6225
  const status = readStatus(asyncJob.asyncDir);
@@ -5444,9 +6227,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5444
6227
  const resolution = resolveAsyncStatusChild(status, paramsWithResolvedCwd.childId);
5445
6228
  if (!resolution.ok) return { content: [{ type: "text", text: resolution.message }], isError: true, details: { mode: "management", results: [] } };
5446
6229
  if (!isStoppableAsyncStatusStep(resolution.child.step)) return { content: [{ type: "text", text: `Child '${paramsWithResolvedCwd.childId}' in async run '${targetRunId}' is ${resolution.child.step.status}; stop only supports pending or running children.` }], isError: true, details: { mode: "management", results: [] } };
5447
- const stopChild = deps.state.workflowChildStops?.get(targetRunId!);
5448
6230
  if (!stopChild) return { content: [{ type: "text", text: `Workflow ${targetRunId} child stop is unavailable in this extension runtime.` }], isError: true, details: { mode: "management", results: [] } };
5449
- if (!stopChild(resolution.child.id)) return { content: [{ type: "text", text: `Child '${paramsWithResolvedCwd.childId}' in workflow ${workflowRunId} is not available to stop.` }], isError: true, details: { mode: "management", results: [] } };
6231
+ if (!stopChild(resolution.child.id, `Workflow child '${resolution.child.id}' stopped.`)) return { content: [{ type: "text", text: `Child '${paramsWithResolvedCwd.childId}' in workflow ${workflowRunId} is not available to stop.` }], isError: true, details: { mode: "management", results: [] } };
5450
6232
  try {
5451
6233
  fs.appendFileSync(path.join(asyncJob.asyncDir, "events.jsonl"), `${JSON.stringify({
5452
6234
  type: "subagent.child-status",
@@ -5455,7 +6237,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5455
6237
  childId: resolution.child.id,
5456
6238
  status: "stopping",
5457
6239
  ts: Date.now(),
5458
- reason: "user",
6240
+ reason: "subagent-action",
5459
6241
  source: "async",
5460
6242
  stepIndex: resolution.child.index,
5461
6243
  agent: resolution.child.step.agent,
@@ -5469,17 +6251,16 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5469
6251
  }
5470
6252
  return { content: [{ type: "text", text: `Stop requested for child ${resolution.child.id} in async workflow ${workflowRunId}.` }], details: { mode: "management", results: [] } };
5471
6253
  }
5472
- workflowController.abort(new Error("Workflow stopped by user."));
6254
+ const asyncJob = deps.state.asyncJobs.get(targetRunId);
6255
+ const status = asyncJob?.asyncDir ? readStatus(asyncJob.asyncDir) : undefined;
6256
+ if (status) stopStoppableAsyncStatusChildren(status, stopChild, "Workflow stopped.");
6257
+ workflowController.abort(new Error("Workflow stopped."));
5473
6258
  return { content: [{ type: "text", text: `Stop requested for async workflow ${targetRunId}.` }], details: { mode: "management", results: [] } };
5474
6259
  }
5475
6260
  let resolved: ResolvedSubagentRunId | undefined;
5476
6261
  if (paramsWithResolvedCwd.dir) {
5477
6262
  try {
5478
6263
  const location = resolveAsyncRunLocation(paramsWithResolvedCwd, DIRS.async, DIRS.results);
5479
- const existingStatus = readStatus(location.asyncDir ?? "");
5480
- if (existingStatus?.mode === "workflow" && existingStatus.state === "running") {
5481
- return { content: [{ type: "text", text: `Workflow ${existingStatus.runId} is not controlled by this extension runtime; reload recovery cannot stop it safely.` }], isError: true, details: { mode: "management", results: [] } };
5482
- }
5483
6264
  const stopResult = stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location, paramsWithResolvedCwd.childId);
5484
6265
  return stopResult ?? { content: [{ type: "text", text: `No running or queued async run was found for '${targetRunId ?? paramsWithResolvedCwd.dir}'.` }], isError: true, details: { mode: "management", results: [] } };
5485
6266
  } catch (error) {
@@ -5496,12 +6277,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5496
6277
  }
5497
6278
  if (resolved?.kind === "nested") return { content: [{ type: "text", text: "action='stop' supports current-session top-level async runs only." }], isError: true, details: { mode: "management", results: [] } };
5498
6279
  if (resolved?.kind === "foreground") return { content: [{ type: "text", text: "action='stop' supports async runs only. Use action='interrupt' for foreground runs." }], isError: true, details: { mode: "management", results: [] } };
5499
- if (resolved?.kind === "async") {
5500
- const existingStatus = readStatus(resolved.location.asyncDir ?? "");
5501
- if (existingStatus?.mode === "workflow" && existingStatus.state === "running") {
5502
- return { content: [{ type: "text", text: `Workflow ${resolved.id} is not controlled by this extension runtime; reload recovery cannot stop it safely.` }], isError: true, details: { mode: "management", results: [] } };
5503
- }
5504
- }
5505
6280
  const stopResult = stopAsyncRun(
5506
6281
  deps.state,
5507
6282
  resolved?.kind === "async" ? resolved.id : targetRunId,
@@ -5574,7 +6349,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5574
6349
  });
5575
6350
  }
5576
6351
 
5577
- const { blocked, depth, maxDepth } = checkSubagentDepth(deps.config.maxSubagentDepth);
6352
+ const { blocked, depth, maxDepth } = checkSubagentDepth(deps.config.maxSubagentDepth, deps.childRuntime);
5578
6353
  if (blocked) {
5579
6354
  return {
5580
6355
  content: [
@@ -5614,15 +6389,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5614
6389
  const scope: AgentScope = resolveExecutionAgentScope(effectiveParams.agentScope);
5615
6390
  const effectiveCwd = effectiveParams.cwd ?? ctx.cwd;
5616
6391
  const parentSessionFile = ctx.sessionManager.getSessionFile() ?? null;
5617
- const discovered = deps.discoverAgents(effectiveCwd, scope);
6392
+ const discovered = deps.discoverAgents(effectiveCwd, scope, requestParentModel?.provider);
5618
6393
  const discoveredAgents = discovered.agents;
5619
- const canonicalParams = canonicalizeExecutionParams(effectiveParams, discoveredAgents, discovered.agentDiagnostics);
6394
+ const unknownAgentDiagnosticContext = diagnosticContextFromDiscovery(discovered, effectiveCwd, scope);
6395
+ const canonicalParams = canonicalizeExecutionParams(effectiveParams, discoveredAgents, discovered.agentDiagnostics, unknownAgentDiagnosticContext);
5620
6396
  if (canonicalParams.error) return buildRequestedModeError(effectiveParams, canonicalParams.error);
5621
6397
  effectiveParams = canonicalParams.params!;
6398
+ if (effectiveParams.worktree === undefined && deps.config.worktree !== undefined) {
6399
+ effectiveParams = { ...effectiveParams, worktree: deps.config.worktree };
6400
+ }
5622
6401
  const modelScope = discovered.modelScope;
5623
6402
  effectiveParams = applySingleAgentLaunchDefaults(effectiveParams, discoveredAgents);
5624
- const turnBudget = resolveTurnBudgetConfig(effectiveParams.turnBudget ?? deps.config.turnBudget);
5625
- if (turnBudget.error) return buildRequestedModeError(effectiveParams, turnBudget.error);
5626
6403
  // An agent-level defaultContext is a preference, unlike an explicit request.
5627
6404
  // Prefer fork only when the parent session is persisted and has a current leaf;
5628
6405
  // otherwise use fresh immediately instead of launching a guaranteed-to-fail fork.
@@ -5647,8 +6424,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5647
6424
  });
5648
6425
  const agents = applyScopedIntercomBridgeToAgents(discoveredAgents, intercomBridge, contextPolicy);
5649
6426
  const runId = randomUUID();
5650
- const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
5651
- const nestedParentAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
6427
+ const inheritedNestedRouteValue = inheritedNestedRoute(deps);
6428
+ const nestedParentAddress = inheritedNestedRouteValue ? inheritedNestedParentAddress(deps) : undefined;
5652
6429
  const shareEnabled = effectiveParams.share === true;
5653
6430
  const hasChain = (effectiveParams.chain?.length ?? 0) > 0;
5654
6431
  const hasTasks = (effectiveParams.tasks?.length ?? 0) > 0;
@@ -5665,6 +6442,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5665
6442
  hasTasks,
5666
6443
  hasSingle,
5667
6444
  allowClarifyTaskPrompt,
6445
+ unknownAgentDiagnosticContext,
5668
6446
  );
5669
6447
  if (validationError) return validationError;
5670
6448
 
@@ -5679,34 +6457,49 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5679
6457
  if (spawnPreflight.error) return spawnBudgetErrorResult(spawnPreflight.error, foregroundMode);
5680
6458
 
5681
6459
  let forkSessionFileForIndex: (idx?: number) => string | undefined = () => undefined;
6460
+ let prepareForkSessionForIndex: (idx?: number) => Promise<void> = async () => {};
5682
6461
  let forkThinkingOverrideForIndex: (idx?: number) => AgentConfig["thinking"] | undefined = () => undefined;
5683
- let prepareForkThinking = (_agentName: string, _index: number, _modelOverride?: string, _modelOverrideFromParent?: boolean): void => {};
6462
+ let prepareForkThinking = (_agentName: string, _index: number, _modelOverride?: string, _modelOverrideFromParent?: boolean, _modelOrigin?: ModelOrigin): void => {};
5684
6463
  const forkThinkingRequirements = new Map<number, boolean>();
5685
6464
  const forkThinkingDowngrades = new Map<number, string>();
5686
6465
  try {
5687
6466
  const forkAvailableModels = contextPolicy.usesFork ? ctx.modelRegistry.getAvailable().map(toModelInfo) : [];
5688
6467
  const parentModel = requestParentModel;
5689
- prepareForkThinking = (agentName, index, modelOverride, modelOverrideFromParent) => {
6468
+ prepareForkThinking = (agentName, index, modelOverride, modelOverrideFromParent, storedOrigin) => {
5690
6469
  const agentConfig = agents.find((agent) => agent.name === agentName);
5691
6470
  if (agentConfig?.runner?.type === "external-cli" || agentConfig?.runner?.type === "external-job") {
5692
6471
  forkThinkingRequirements.set(index, true);
5693
6472
  return;
5694
6473
  }
6474
+ const effectiveStoredOrigin = storedOrigin === "configured" && modelOverride === undefined && agentConfig?.model === undefined
6475
+ ? undefined
6476
+ : storedOrigin;
6477
+ const origin = resolveModelOrigin({
6478
+ fromParent: modelOverrideFromParent,
6479
+ storedOrigin: effectiveStoredOrigin,
6480
+ explicitModel: modelOverrideFromParent || effectiveStoredOrigin === "configured" ? undefined : modelOverride,
6481
+ agentModel: agentConfig?.model,
6482
+ parentModel,
6483
+ });
5695
6484
  const primaryModel = modelOverrideFromParent
5696
6485
  ? modelOverride
5697
6486
  : resolveEffectiveSubagentModel(
5698
- modelOverride,
6487
+ effectiveStoredOrigin === "configured" ? undefined : modelOverride,
5699
6488
  agentConfig?.model,
5700
6489
  parentModel,
5701
6490
  forkAvailableModels,
5702
6491
  agentConfig?.modelProvider ?? parentModel?.provider,
6492
+ { source: origin === "explicit" ? "explicit" : "inherited" },
5703
6493
  );
5704
6494
  const candidates = buildModelCandidates(
5705
6495
  primaryModel,
5706
6496
  agentConfig?.fallbackModels,
5707
6497
  forkAvailableModels,
5708
6498
  agentConfig?.modelProvider ?? parentModel?.provider,
5709
- { primaryModelFromParent: modelOverrideFromParent ?? inheritsParentModel(modelOverride, agentConfig?.model, parentModel) },
6499
+ {
6500
+ primaryModelFromParent: origin === "inherited",
6501
+ origin,
6502
+ },
5710
6503
  );
5711
6504
  forkThinkingRequirements.set(
5712
6505
  index,
@@ -5714,9 +6507,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5714
6507
  || candidates.some((candidate) => forkedChildRequiresThinkingOff(candidate, forkAvailableModels, parentModel?.provider)),
5715
6508
  );
5716
6509
  };
6510
+ const pruneSession = contextPolicy.usesFork && deps.config.forkContext?.mode === "pruned"
6511
+ ? await createPrunedForkSessionWriter(ctx, deps.config.forkContext, signal)
6512
+ : undefined;
5717
6513
  const forkContextResolver = createForkContextResolver(ctx.sessionManager, contextPolicy.usesFork ? "fork" : undefined, {
5718
6514
  forceThinkingOffForIndex: (index) => forkThinkingRequirements.get(index) ?? true,
6515
+ ...(pruneSession ? { pruneSession } : {}),
5719
6516
  });
6517
+ prepareForkSessionForIndex = forkContextResolver.prepareSessionForIndex;
5720
6518
  forkSessionFileForIndex = forkContextResolver.sessionFileForIndex;
5721
6519
  forkThinkingOverrideForIndex = forkContextResolver.thinkingOverrideForIndex;
5722
6520
  } catch (error) {
@@ -5748,7 +6546,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5748
6546
  const asyncRunId = requestedWorkflowChildAsyncId && path.basename(requestedWorkflowChildAsyncId) === requestedWorkflowChildAsyncId
5749
6547
  ? requestedWorkflowChildAsyncId
5750
6548
  : randomUUID();
5751
- const topLevelAsyncCapacityEligible = depth === 0 && !inheritedNestedRoute && !effectiveParams.workflowParentRunId;
6549
+ const topLevelAsyncCapacityEligible = depth === 0 && !inheritedNestedRouteValue && !effectiveParams.workflowParentRunId;
5752
6550
  const topLevelAsync = effectiveAsync && topLevelAsyncCapacityEligible;
5753
6551
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
5754
6552
  if (topLevelAsync) {
@@ -5760,8 +6558,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5760
6558
  runId: asyncRunId,
5761
6559
  kind: "runner",
5762
6560
  asyncDir: path.join(DIRS.async, asyncRunId),
5763
- }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) });
5764
- deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(requestSessionId, activeLimit, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) });
6561
+ }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) });
6562
+ deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(requestSessionId, activeLimit, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) });
5765
6563
  } catch (error) {
5766
6564
  if (error instanceof ActiveAsyncCapacityError) {
5767
6565
  deps.state.activeAsyncCapacity = error.snapshot;
@@ -5773,9 +6571,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5773
6571
 
5774
6572
  let runFanoutBudget: RunFanoutBudgetDescriptor;
5775
6573
  try {
5776
- const inheritedRunFanoutBudget = effectiveParams.runFanoutBudget ? undefined : decodeRunFanoutBudgetDescriptor(process.env[RUN_FANOUT_BUDGET_ENV]);
6574
+ const inheritedRunFanoutBudgetValue = effectiveParams.runFanoutBudget ? undefined : inheritedRunFanoutBudget(deps);
5777
6575
  runFanoutBudget = effectiveParams.runFanoutBudget
5778
- ?? (inheritedRunFanoutBudget ? { ...inheritedRunFanoutBudget, parentPath: `${inheritedRunFanoutBudget.parentPath ? `${inheritedRunFanoutBudget.parentPath}/` : ""}${runId}` } : undefined)
6576
+ ?? (inheritedRunFanoutBudgetValue ? { ...inheritedRunFanoutBudgetValue, parentPath: `${inheritedRunFanoutBudgetValue.parentPath ? `${inheritedRunFanoutBudgetValue.parentPath}/` : ""}${runId}` } : undefined)
5779
6577
  ?? createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun));
5780
6578
  if (!effectiveParams.runFanoutAdmitted) claimRunFanoutBatch(runFanoutBudget, staticRunFanoutPaths(effectiveParams));
5781
6579
  } catch (error) {
@@ -5783,7 +6581,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5783
6581
  if (error instanceof RunFanoutLimitError) return runFanoutErrorResult(error, foregroundMode);
5784
6582
  return buildRequestedModeError(effectiveParams, error instanceof Error ? error.message : String(error));
5785
6583
  }
5786
- const nestedRoute = inheritedNestedRoute ?? createNestedRoute(runId);
6584
+ const nestedRoute = inheritedNestedRouteValue ?? createNestedRoute(runId);
5787
6585
 
5788
6586
  const artifactConfig: ArtifactConfig = omitUndefinedProperties({
5789
6587
  ...DEFAULT_ARTIFACT_CONFIG,
@@ -5819,25 +6617,30 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5819
6617
  }
5820
6618
  const sessionDirForIndex = (idx?: number) =>
5821
6619
  path.join(sessionRoot, `run-${idx ?? 0}`);
5822
- const forkSessionFileForTask: ForkSessionFileForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent) => {
6620
+ const forkSessionFileForTask: ForkSessionFileForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent, modelOrigin) => {
5823
6621
  if (!shouldForkAgent(contextPolicy, agentName)) return undefined;
5824
- prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent);
6622
+ prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin);
5825
6623
  return forkSessionFileForIndex(idx);
5826
6624
  };
5827
- const forkThinkingOverrideForTask: ForkThinkingOverrideForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent) => {
6625
+ const prepareForkSessionForTask: PrepareForkSessionForTask = async (agentName, idx = 0, modelOverride, modelOverrideFromParent, modelOrigin) => {
6626
+ if (!shouldForkAgent(contextPolicy, agentName)) return;
6627
+ prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin);
6628
+ await prepareForkSessionForIndex(idx);
6629
+ };
6630
+ const forkThinkingOverrideForTask: ForkThinkingOverrideForTask = (agentName, idx = 0, modelOverride, modelOverrideFromParent, modelOrigin) => {
5828
6631
  if (!shouldForkAgent(contextPolicy, agentName)) return delegatedThinkingOverride;
5829
- prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent);
6632
+ prepareForkThinking(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin);
5830
6633
  const override = forkThinkingOverrideForIndex(idx);
5831
6634
  if (override === "off") forkThinkingDowngrades.set(idx, agentName);
5832
6635
  return override ?? delegatedThinkingOverride;
5833
6636
  };
5834
- const childSessionFileForTask: ForkSessionFileForTask = (agentName, idx, modelOverride, modelOverrideFromParent) =>
5835
- forkSessionFileForTask(agentName, idx, modelOverride, modelOverrideFromParent) ?? path.join(sessionDirForIndex(idx), "session.jsonl");
6637
+ const childSessionFileForTask: ForkSessionFileForTask = (agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin) =>
6638
+ forkSessionFileForTask(agentName, idx, modelOverride, modelOverrideFromParent, modelOrigin) ?? path.join(sessionDirForIndex(idx), "session.jsonl");
5836
6639
  const childSessionFileForIndex = (idx?: number) =>
5837
6640
  path.join(sessionDirForIndex(idx), "session.jsonl");
5838
6641
  try {
5839
- if (!(effectiveParams.clarify === true && ctx.hasUI)) {
5840
- preflightForkSessionsForStaticTasks(effectiveParams, contextPolicy, forkSessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems);
6642
+ if (!(effectiveParams.clarify === true && ctx.hasUI) || deps.config.forkContext?.mode === "pruned") {
6643
+ await preflightForkSessionsForStaticTasks(effectiveParams, contextPolicy, prepareForkSessionForTask, deps.config.chain?.dynamicFanout?.maxItems);
5841
6644
  }
5842
6645
  } catch (error) {
5843
6646
  activeAsyncCapacity?.rollback();
@@ -5906,10 +6709,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5906
6709
  const execData: ExecutionContextData = omitUndefinedProperties({
5907
6710
  params: effectiveParams,
5908
6711
  effectiveCwd,
6712
+ requestedCwd,
5909
6713
  ctx,
5910
6714
  signal,
5911
6715
  onUpdate: onUpdateWithContext,
5912
6716
  agents,
6717
+ unknownAgentDiagnosticContext,
5913
6718
  recoveryAgents: discoveredAgents,
5914
6719
  runId,
5915
6720
  shareEnabled,
@@ -5924,10 +6729,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5924
6729
  effectiveAsync,
5925
6730
  asyncRunId,
5926
6731
  controlConfig,
6732
+ ...(delegatedExecution ? { suppressUnchangedDelegationUpdates: true } : {}),
5927
6733
  intercomBridge,
5928
6734
  nestedRoute,
5929
6735
  timeoutMs: foregroundTimeout.timeoutMs,
5930
- turnBudget: turnBudget.turnBudget,
5931
6736
  toolBudget: runToolBudget.toolBudget,
5932
6737
  usageBudget: usageBudget.budget,
5933
6738
  allowZeroToolBudget,
@@ -5942,22 +6747,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5942
6747
  runFanoutBudget,
5943
6748
  topLevelAsyncCapacityEligible,
5944
6749
  activeAsyncCapacity,
6750
+ workflowChildPermitLaunch,
5945
6751
  });
5946
6752
 
5947
6753
  const foregroundDescription = selectedAgentNames.length === 1
5948
6754
  ? `${selectedAgentNames[0]} child`
5949
6755
  : `${selectedAgentNames.length} live children`;
5950
- const parentWorkflowStatus = effectiveParams.workflowParentRunId
5951
- ? readStatus(path.join(DIRS.async, effectiveParams.workflowParentRunId))
5952
- : null;
5953
- const workflowSteeringDir = effectiveParams.workflowParentRunId
5954
- && requestSessionId
5955
- && deps.state.workflowControllers?.has(effectiveParams.workflowParentRunId)
5956
- && parentWorkflowStatus?.mode === "workflow"
5957
- && (parentWorkflowStatus.state === "running" || parentWorkflowStatus.state === "queued")
5958
- && parentWorkflowStatus.sessionId === requestSessionId
5959
- ? workflowForegroundSteeringDir(DIRS.async, effectiveParams.workflowParentRunId, runId)
5960
- : undefined;
5961
6756
  const foregroundControl: ForegroundRunControl | undefined = effectiveAsync
5962
6757
  ? undefined
5963
6758
  : compactOptional<ForegroundRunControl>({
@@ -5966,7 +6761,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5966
6761
  mode: foregroundMode,
5967
6762
  ...(effectiveParams.workflowParentRunId ? { parentWorkflowRunId: effectiveParams.workflowParentRunId } : {}),
5968
6763
  ...(effectiveParams.workflowKey ? { workflowKey: effectiveParams.workflowKey } : {}),
5969
- workflowSteeringDir,
5970
6764
  startedAt: Date.now(),
5971
6765
  updatedAt: Date.now(),
5972
6766
  cwd: effectiveCwd,
@@ -6019,7 +6813,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6019
6813
  }
6020
6814
 
6021
6815
  const writeNestedForegroundEvent = (type: "subagent.nested.started" | "subagent.nested.completed", result?: AgentToolResult<Details>): void => {
6022
- if (!inheritedNestedRoute || !nestedParentAddress) return;
6816
+ if (!inheritedNestedRouteValue || !nestedParentAddress) return;
6023
6817
  const now = Date.now();
6024
6818
  const details = result?.details;
6025
6819
  const state = type === "subagent.nested.started"
@@ -6053,7 +6847,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6053
6847
  ? resolveSubagentIntercomTarget(runId, agentsForSummary[0], 0)
6054
6848
  : undefined;
6055
6849
  try {
6056
- writeNestedEvent(inheritedNestedRoute, compactOptional<Parameters<typeof writeNestedEvent>[1]>({
6850
+ writeNestedEvent(inheritedNestedRouteValue, compactOptional<Parameters<typeof writeNestedEvent>[1]>({
6057
6851
  type,
6058
6852
  ts: now,
6059
6853
  parentRunId: nestedParentAddress.parentRunId,
@@ -6064,16 +6858,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6064
6858
  parentStepIndex: nestedParentAddress.parentStepIndex,
6065
6859
  depth: nestedParentAddress.depth,
6066
6860
  path: nestedParentAddress.path,
6067
- ownerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,
6861
+ ownerIntercomTarget: deps.childRuntime?.intercomSessionName,
6068
6862
  leafIntercomTarget,
6069
6863
  intercomTarget: leafIntercomTarget,
6070
6864
  ownerState: state === "running" ? "live" : "gone",
6071
6865
  mode: foregroundMode,
6072
6866
  state,
6073
6867
  agent: agentsForSummary[0],
6868
+ ...(details?.results.length === 1 && details.results[0]?.sessionName ? { sessionName: details.results[0].sessionName } : {}),
6074
6869
  agents: agentsForSummary,
6075
6870
  ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.model : details?.results[0]?.model) ? { model: type === "subagent.nested.started" ? startedLaunches[0]?.model : details?.results[0]?.model } : {}),
6076
6871
  ...(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 } : {}),
6872
+ ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox) ? { sandbox: type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox } : {}),
6077
6873
  startedAt: foregroundControl?.startedAt ?? now,
6078
6874
  ...(state !== "running" ? { endedAt: now } : {}),
6079
6875
  lastUpdate: now,
@@ -6085,13 +6881,16 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6085
6881
  status: "running" as const,
6086
6882
  ...(launch.model ? { model: launch.model } : {}),
6087
6883
  ...(launch.thinking ? { thinking: launch.thinking } : {}),
6884
+ ...(launch.sandbox ? { sandbox: launch.sandbox } : {}),
6088
6885
  })) }
6089
6886
  : details?.results.length
6090
6887
  ? { steps: details.results.map((child) => ({
6091
6888
  agent: child.agent,
6889
+ ...(child.sessionName ? { sessionName: child.sessionName } : {}),
6092
6890
  status: child.interrupted || child.detached ? "paused" as const : child.exitCode === 0 ? "complete" as const : "failed" as const,
6093
6891
  ...(child.model ? { model: child.model } : {}),
6094
6892
  ...(child.thinking ? { thinking: child.thinking } : {}),
6893
+ ...(child.sandbox ? { sandbox: child.sandbox } : {}),
6095
6894
  ...(child.sessionFile ? { sessionFile: child.sessionFile } : {}),
6096
6895
  ...(child.error ? { error: child.error } : {}),
6097
6896
  })) }
@@ -6112,10 +6911,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6112
6911
  }
6113
6912
  if (workflowLaunchObserver) {
6114
6913
  const singleTask = hasTasks && effectiveParams.tasks?.length === 1 ? effectiveParams.tasks[0] : undefined;
6914
+ const singleSessionName = hasSingle
6915
+ ? deriveChildSessionName({ agent: effectiveParams.agent!, task: effectiveParams.task })
6916
+ : singleTask
6917
+ ? deriveChildSessionName({ agent: singleTask.agent, task: singleTask.task })
6918
+ : undefined;
6115
6919
  const launch = hasSingle
6116
- ? { agent: effectiveParams.agent!, sessionFile: childSessionFileForTask(effectiveParams.agent!, 0, effectiveParams.model), async: effectiveAsync, ...(effectiveAsync ? { runId: asyncRunId } : {}) }
6920
+ ? { agent: effectiveParams.agent!, ...(singleSessionName ? { sessionName: singleSessionName } : {}), sessionFile: childSessionFileForTask(effectiveParams.agent!, 0, effectiveParams.model), async: effectiveAsync, runId: effectiveAsync ? asyncRunId : runId }
6117
6921
  : singleTask
6118
- ? { agent: singleTask.agent, sessionFile: childSessionFileForTask(singleTask.agent, 0, singleTask.model), async: effectiveAsync, ...(effectiveAsync ? { runId: asyncRunId } : {}) }
6922
+ ? { agent: singleTask.agent, ...(singleSessionName ? { sessionName: singleSessionName } : {}), sessionFile: childSessionFileForTask(singleTask.agent, 0, singleTask.model), async: effectiveAsync, runId: effectiveAsync ? asyncRunId : runId }
6119
6923
  : undefined;
6120
6924
  if (launch) {
6121
6925
  workflowLaunchObservers.delete(params);
@@ -6167,15 +6971,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6167
6971
  ): Promise<AgentToolResult<Details>> => {
6168
6972
  const normalizedAction = typeof params.action === "string" ? params.action.trim() : params.action;
6169
6973
  const requestParams = normalizedAction ? { ...params, action: normalizedAction } : params;
6170
- if (normalizedAction) return execute(id, requestParams, signal, onUpdate, ctx);
6171
- const { depth } = checkSubagentDepth(deps.config.maxSubagentDepth);
6974
+ if (normalizedAction) return execute(id, requestParams, signal, onUpdate, ctx).then(withAggregatedToolUsage);
6975
+ const { depth } = checkSubagentDepth(deps.config.maxSubagentDepth, deps.childRuntime);
6172
6976
  const dispatchParams = applyForceTopLevelAsyncOverride(requestParams, depth, deps.config.forceTopLevelAsync === true);
6173
6977
  const runsForeground = dispatchParams.clarify === true || (dispatchParams.async ?? deps.asyncByDefault) !== true;
6174
- if (!runsForeground) return execute(id, requestParams, signal, onUpdate, ctx);
6978
+ if (!runsForeground) return execute(id, requestParams, signal, onUpdate, ctx).then(withAggregatedToolUsage);
6175
6979
  if (deps.state.subagentInProgress === true) return duplicateSubagentCallResult(requestParams);
6176
6980
  deps.state.subagentInProgress = true;
6177
6981
  try {
6178
- return await execute(id, requestParams, signal, onUpdate, ctx);
6982
+ return withAggregatedToolUsage(await execute(id, requestParams, signal, onUpdate, ctx));
6179
6983
  } finally {
6180
6984
  deps.state.subagentInProgress = false;
6181
6985
  }
@@ -6188,11 +6992,24 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6188
6992
  onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
6189
6993
  ctx: ExtensionContext,
6190
6994
  ): Promise<AgentToolResult<Details>> => {
6191
- const normalized = normalizePublicSubagentExecution(params, { asyncByDefault: deps.asyncByDefault });
6995
+ const normalized = normalizePublicSubagentExecution(params);
6192
6996
  if (!normalized.ok) {
6193
6997
  return Promise.resolve({ content: [{ type: "text", text: normalized.error }], isError: true, details: { mode: normalized.mode, results: [] } });
6194
6998
  }
6195
- return executeWithSingleDispatchGuard(id, normalized.params, signal, onUpdate, ctx);
6999
+ let publicParams = normalized.params as SubagentParamsLike;
7000
+ if (publicParams.workflow !== undefined) {
7001
+ const resolved = resolveWorkflowResource(publicParams.workflow, publicParams.args);
7002
+ if (!resolved.ok) return Promise.resolve({ content: [{ type: "text", text: resolved.error }], isError: true, details: { mode: "workflow", results: [] } });
7003
+ const { workflow: _workflow, args: _args, ...withoutResourceInput } = publicParams;
7004
+ publicParams = { ...withoutResourceInput, workflowScript: resolved.resource.script };
7005
+ workflowResourcePermits.set(publicParams, resolved.resource.permit);
7006
+ }
7007
+ const loaded = loadWorkflowScriptPath(publicParams, ctx.cwd);
7008
+ if (loaded.error) {
7009
+ return Promise.resolve({ content: [{ type: "text", text: loaded.error }], isError: true, details: { mode: publicParams.action ? "management" : "workflow", results: [] } });
7010
+ }
7011
+ publicExecutions.add(loaded.params!);
7012
+ return executeWithSingleDispatchGuard(id, loaded.params!, signal, onUpdate, ctx);
6196
7013
  };
6197
7014
 
6198
7015
  const executeDelegated = async (
@@ -6206,15 +7023,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6206
7023
  const privateParams = delegatedParams as SubagentParamsLike & {
6207
7024
  delegatedThinkingOverride?: AgentConfig["thinking"];
6208
7025
  delegatedAllowZeroToolBudget?: true;
7026
+ delegatedWorkflowPermit?: WorkflowChildPermit;
6209
7027
  };
6210
7028
  const thinkingOverride = privateParams.delegatedThinkingOverride;
6211
7029
  const allowZeroToolBudget = privateParams.delegatedAllowZeroToolBudget === true;
7030
+ const workflowPermit = privateParams.delegatedWorkflowPermit;
6212
7031
  delete privateParams.delegatedThinkingOverride;
6213
7032
  delete privateParams.delegatedAllowZeroToolBudget;
7033
+ delete privateParams.delegatedWorkflowPermit;
6214
7034
  if (thinkingOverride !== undefined) delegatedThinkingOverrides.set(delegatedParams, thinkingOverride);
6215
7035
  if (allowZeroToolBudget) delegatedZeroToolBudgets.add(delegatedParams);
7036
+ if (workflowPermit) workflowPermitContexts.set(delegatedParams, { root: workflowPermit });
6216
7037
  delegatedExecutions.add(delegatedParams);
6217
- return execute(id, delegatedParams, signal, onUpdate, ctx);
7038
+ return withAggregatedToolUsage(await execute(id, delegatedParams, signal, onUpdate, ctx));
6218
7039
  };
6219
7040
 
6220
7041
  const executeScheduled = (
@@ -6232,7 +7053,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6232
7053
  });
6233
7054
  scheduledOwnerExecutors.set(ownerSessionId, ownerExecutor);
6234
7055
  }
6235
- return ownerExecutor.execute(id, params, signal, undefined, ctx);
7056
+ return ownerExecutor.executePublic(id, params, signal, undefined, ctx);
6236
7057
  };
6237
7058
 
6238
7059
  return { execute: executeWithSingleDispatchGuard, executePublic, executeDelegated, executeScheduled };