@xzzpig/pi-subagents 0.16.0 → 0.19.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 (166) hide show
  1. package/CHANGELOG.md +233 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +34 -21
  9. package/docs/configuration.md +82 -7
  10. package/docs/extension-api.md +75 -8
  11. package/docs/missions.md +13 -13
  12. package/docs/models.md +7 -5
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +5 -5
  15. package/docs/tool-reference.md +98 -100
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +214 -162
  18. package/inspector-runner.mjs +1 -1
  19. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  20. package/package.json +15 -9
  21. package/prompts/council.md +6 -3
  22. package/prompts/review-loop.md +1 -1
  23. package/runner-peer-loader.mjs +4 -7
  24. package/runner-peer-preload.mjs +5 -7
  25. package/skills/council-mode/SKILL.md +1 -1
  26. package/skills/pi-subagents/SKILL.md +13 -5
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
  28. package/skills/pi-subagents/references/execution-controls.md +72 -69
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
  32. package/src/agents/advertised-agent-prompt.ts +21 -41
  33. package/src/agents/agent-eject.ts +3 -3
  34. package/src/agents/agent-management.ts +63 -54
  35. package/src/agents/agent-memory.ts +90 -3
  36. package/src/agents/agent-serializer.ts +4 -4
  37. package/src/agents/agents.ts +132 -51
  38. package/src/agents/global-npm-root.ts +58 -0
  39. package/src/agents/proactive-skills.ts +4 -1
  40. package/src/agents/runtime-agent-registry.ts +14 -11
  41. package/src/agents/skills.ts +42 -9
  42. package/src/api/delegation.ts +15 -0
  43. package/src/api/inspectors.ts +27 -0
  44. package/src/api/preflight.ts +7 -2
  45. package/src/extension/config.ts +12 -4
  46. package/src/extension/control-notices.ts +3 -0
  47. package/src/extension/doctor.ts +10 -4
  48. package/src/extension/fanout-child.ts +20 -3
  49. package/src/extension/herdr-pi-bridge.ts +2 -0
  50. package/src/extension/index.ts +168 -206
  51. package/src/extension/public-execution.ts +69 -35
  52. package/src/extension/reply-workflow-script.ts +58 -0
  53. package/src/extension/rpc.ts +39 -11
  54. package/src/extension/schemas.ts +47 -138
  55. package/src/extension/subagent-guide.ts +12 -4
  56. package/src/extension/tool-activation.ts +146 -0
  57. package/src/extension/tool-description.ts +62 -27
  58. package/src/extension/upgrade-notice.ts +40 -0
  59. package/src/inspectors/ghostty/plugin.ts +13 -1
  60. package/src/inspectors/plugins.ts +70 -3
  61. package/src/integrations/herdr-status.ts +19 -3
  62. package/src/intercom/intercom-bridge.ts +2 -0
  63. package/src/intercom/native-supervisor-channel.ts +26 -16
  64. package/src/intercom/result-intercom.ts +4 -0
  65. package/src/runs/background/active-async-capacity.ts +3 -25
  66. package/src/runs/background/async-execution.ts +60 -95
  67. package/src/runs/background/async-job-tracker.ts +91 -56
  68. package/src/runs/background/async-resume.ts +16 -8
  69. package/src/runs/background/async-retention.ts +46 -16
  70. package/src/runs/background/async-status.ts +2 -0
  71. package/src/runs/background/await-async-run.ts +76 -0
  72. package/src/runs/background/binary-bootstrap.ts +34 -6
  73. package/src/runs/background/chain-root-attachment.ts +4 -4
  74. package/src/runs/background/control-channel.ts +18 -2
  75. package/src/runs/background/fleet-view.ts +51 -7
  76. package/src/runs/background/notify.ts +98 -7
  77. package/src/runs/background/pid-namespace.ts +18 -0
  78. package/src/runs/background/process-terminal-candidate.ts +98 -0
  79. package/src/runs/background/process-terminal.ts +17 -96
  80. package/src/runs/background/result-watcher.ts +1 -1
  81. package/src/runs/background/retained-children.ts +3 -2
  82. package/src/runs/background/run-child-session.ts +20 -6
  83. package/src/runs/background/run-id-resolver.ts +10 -5
  84. package/src/runs/background/run-status.ts +16 -4
  85. package/src/runs/background/runner-aliases.ts +54 -16
  86. package/src/runs/background/runner-child-launch.ts +4 -2
  87. package/src/runs/background/runner-startup-failure.ts +56 -0
  88. package/src/runs/background/scheduled-runs.ts +5 -5
  89. package/src/runs/background/stale-run-reconciler.ts +19 -3
  90. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  91. package/src/runs/background/subagent-runner.ts +111 -288
  92. package/src/runs/background/wait-tool.ts +2 -0
  93. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  94. package/src/runs/foreground/async-stop-action.ts +17 -3
  95. package/src/runs/foreground/execution.ts +111 -139
  96. package/src/runs/foreground/prompt-audit.ts +3 -9
  97. package/src/runs/foreground/subagent-executor.ts +715 -258
  98. package/src/runs/shared/acceptance.ts +167 -68
  99. package/src/runs/shared/async-status-projection.ts +5 -0
  100. package/src/runs/shared/capability-ceiling.ts +4 -1
  101. package/src/runs/shared/child-hooks.ts +1 -16
  102. package/src/runs/shared/child-launch.ts +37 -16
  103. package/src/runs/shared/child-runtime-config.ts +3 -0
  104. package/src/runs/shared/child-session.ts +144 -8
  105. package/src/runs/shared/child-tool-plan.ts +38 -116
  106. package/src/runs/shared/dynamic-fanout.ts +1 -1
  107. package/src/runs/shared/external-cli-runner.ts +3 -1
  108. package/src/runs/shared/external-job-bridge.ts +54 -0
  109. package/src/runs/shared/git-environment.ts +29 -0
  110. package/src/runs/shared/mcp-config-sources.ts +5 -1
  111. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
  112. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  113. package/src/runs/shared/model-resolution.ts +35 -10
  114. package/src/runs/shared/model-scope.ts +28 -9
  115. package/src/runs/shared/nested-events.ts +12 -0
  116. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  117. package/src/runs/shared/parallel-utils.ts +4 -1
  118. package/src/runs/shared/pi-spawn.ts +1 -3
  119. package/src/runs/shared/single-output.ts +11 -2
  120. package/src/runs/shared/structured-output.ts +227 -7
  121. package/src/runs/shared/subagent-control.ts +2 -16
  122. package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
  123. package/src/runs/shared/tool-availability.ts +2 -2
  124. package/src/runs/shared/tool-budget.ts +21 -0
  125. package/src/runs/shared/usage-reconciliation.ts +73 -0
  126. package/src/runs/shared/worktree.ts +36 -9
  127. package/src/shared/child-session-name.ts +4 -2
  128. package/src/shared/disabled-features.ts +123 -0
  129. package/src/shared/extension-context.ts +13 -0
  130. package/src/shared/fork-context.ts +11 -4
  131. package/src/shared/launch-contract.ts +1 -1
  132. package/src/shared/model-info.ts +9 -0
  133. package/src/shared/pruned-fork.ts +69 -56
  134. package/src/shared/settings.ts +1 -1
  135. package/src/shared/types.ts +73 -16
  136. package/src/slash/delegation-adapters.ts +25 -1
  137. package/src/slash/prompt-template-bridge.ts +18 -3
  138. package/src/slash/prompt-workflows.ts +12 -1
  139. package/src/slash/slash-commands.ts +17 -246
  140. package/src/slash/subagent-cost.ts +313 -0
  141. package/src/slash/subagents-admin.ts +4 -5
  142. package/src/tui/fleet-status.ts +38 -8
  143. package/src/tui/fleet.ts +21 -6
  144. package/src/tui/render.ts +166 -71
  145. package/src/tui/running-tone.ts +28 -0
  146. package/src/watchdog/diff-tool.ts +47 -12
  147. package/src/watchdog/permission-arbiter.ts +13 -15
  148. package/src/watchdog/register-child.ts +13 -5
  149. package/src/watchdog/register-main.ts +3 -3
  150. package/src/watchdog/review.ts +16 -16
  151. package/src/watchdog/runtime.ts +2 -1
  152. package/src/watchdog/turn-delta.ts +12 -6
  153. package/src/workflows/chat-progress.ts +2 -2
  154. package/src/workflows/scripted-workflow.ts +225 -59
  155. package/src/workflows/structured-workflow-scripts.ts +177 -0
  156. package/src/workflows/workflow-checklist.ts +6 -0
  157. package/src/workflows/workflow-child-summary.ts +4 -2
  158. package/src/workflows/workflow-receipt.ts +8 -2
  159. package/src/workflows/workflow-resources.ts +37 -12
  160. package/src/workflows/workflow-reuse.ts +120 -0
  161. package/src/workflows/workflow-revival.ts +123 -0
  162. package/src/workflows/workflow-settlement.ts +4 -1
  163. package/src/runs/shared/completion-evidence.ts +0 -89
  164. package/src/runs/shared/completion-guard.ts +0 -255
  165. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  166. package/src/runs/shared/task-intent.ts +0 -244
@@ -3,7 +3,7 @@ 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 { discoverAgents, findBlockingAgentDiagnostic, formatUnknownAgentError, resolveAgentName, unknownAgentDiagnosticContext, type AgentConfig, type AgentDiscoveryDiagnostic, type AgentScope, type UnknownAgentDiagnosticContext } from "../../agents/agents.ts";
6
+ import { discoverAgents, discoverAgentsAll, findBlockingAgentDiagnostic, formatUnknownAgentError, resolveAgentName, unknownAgentDiagnosticContext, type AgentConfig, type AgentDiscoveryDiagnostic, type AgentScope, type UnknownAgentDiagnosticContext } from "../../agents/agents.ts";
7
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";
@@ -23,13 +23,15 @@ import { handleManagementAction } from "../../agents/agent-management.ts";
23
23
  import { handleRefinementAction } from "../../agents/agent-refinements.ts";
24
24
  import { buildDoctorReport } from "../../extension/doctor.ts";
25
25
  import { readSubagentGuide } from "../../extension/subagent-guide.ts";
26
- import { normalizePublicSubagentExecution, validateWorkflowCapacityOverrides } from "../../extension/public-execution.ts";
26
+ import { isWorkflowScriptPath, normalizePublicSubagentExecution, validateWorkflowCapacityOverrides } from "../../extension/public-execution.ts";
27
+ import { readReplyWorkflowScript } from "../../extension/reply-workflow-script.ts";
28
+ import { disabledFeatureNotice, disabledFeatureUseError, resolveDisabledFeatureSurface, type DisabledFeatureSurface } from "../../shared/disabled-features.ts";
27
29
  import { runSync } from "./execution.ts";
28
30
  import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/tool-actions.ts";
29
31
  import type { MainWatchdogRuntime } from "../../watchdog/runtime.ts";
30
32
  import { applyWatchdogLaunchRules } from "../../watchdog/rules.ts";
31
33
  import { childWatchdogProgressForModel } from "../../watchdog/child-status.ts";
32
- import { normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, resolveModelSelection, type ModelOrigin, type ParentModel } from "../shared/model-resolution.ts";
34
+ import { normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, resolveModelSelection, scopedModelIdsFromContext, type ModelOrigin, type ParentModel } from "../shared/model-resolution.ts";
33
35
  import { getHostBuiltinToolNames } from "../shared/child-tool-plan.ts";
34
36
  import { projectScopedProfileTrustError } from "../shared/sandbox-profile-guard.ts";
35
37
  import { projectChainOutputSchemas, resolveEffectiveOutputSchema } from "../shared/child-launch-plan.ts";
@@ -56,26 +58,27 @@ import { isScheduledRunAction } from "../background/scheduled-runs.ts";
56
58
  import { encodeIndexSegment } from "../background/index-segment.ts";
57
59
  import { enqueueChainAppendRequest, readPendingChainAppendRequests, runnerStepOutputNames } from "../background/chain-append.ts";
58
60
  import { ChainOutputValidationError, validateChainOutputBindingsWithContext } from "../shared/chain-outputs.ts";
59
- import { normalizeGateAcceptance, resolveAcceptanceReportMode, validateAcceptanceInput, validateExecutionAcceptance, validateExecutionAcceptancePolicy } from "../shared/acceptance.ts";
61
+ import { acceptanceHasTypedVerify, normalizeGateAcceptance, resolveAcceptanceReportMode, TYPED_VERIFY_OUTPUT_SCHEMA_CONFLICT, validateAcceptanceInput, validateExecutionAcceptance, validateExecutionAcceptancePolicy } from "../shared/acceptance.ts";
60
62
  import { canPreferFork, createForkContextResolver, resolveSubagentLaunchContext } from "../../shared/fork-context.ts";
61
63
  import { createPrunedForkSessionWriter } from "../../shared/pruned-fork.ts";
62
64
  import { resolveCurrentSessionId } from "../../shared/session-identity.ts";
63
65
  import { currentCompletionOwnerId } from "../../shared/completion-owner.ts";
66
+ import { SUBAGENT_ASYNC_COMPLETE_EVENT } from "../../shared/types.ts";
64
67
  import { applyIntercomBridgeToAgent, INTERCOM_BRIDGE_MARKER, resolveIntercomBridge, resolveIntercomSessionTarget, resolveSubagentIntercomTarget, type IntercomBridgeState } from "../../intercom/intercom-bridge.ts";
65
68
  import { formatControlIntercomMessage, formatControlNoticeMessage, resolveControlConfig, shouldNotifyControlEvent } from "../shared/subagent-control.ts";
66
69
  import { formatSpawnBudget, getSpawnBudgetSnapshot, grantSpawnBudget, preflightSpawnBudget, preflightSpawnBudgetGrant, reserveSpawnBudget } from "../shared/spawn-budget.ts";
67
70
  import { claimRunFanoutBatch, claimRunFanoutBatchWithCommit, createRunFanoutBudget, formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor, RunFanoutLimitError, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
68
71
  import { retainLiveForegroundNestedRoute } from "../../integrations/pi-web-session-liveness.ts";
72
+ import { HERDR_FOREGROUND_CONTROL_CHANGED_EVENT } from "../../integrations/herdr-status.ts";
69
73
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
70
74
  import { usageBudgetExceededMessage, usageBudgetState, validateUsageBudgetConfig } from "../shared/usage-budget.ts";
71
- import { intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
75
+ import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
72
76
  import { isAgentContract } from "../shared/agent-contract.ts";
73
77
  import { normalizeExtensionBindings, type ExtensionBindings } from "../shared/extension-bindings.ts";
74
78
  import { resolveRequiredChildExtensions } from "../../shared/required-child-extensions.ts";
75
79
  import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, outputPathMappingFromTask, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
76
80
  import { assertJsonSchemaObject, cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
77
- import { compactForegroundDetails, getSingleResultOutput, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage, toAgentToolUsage } from "../../shared/utils.ts";
78
- import { createTaskMutationArbiter } from "../shared/llm-intent-arbiter.ts";
81
+ import { compactForegroundDetails, getSingleResultOutput, PROMPT_REDACTED, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage, toAgentToolUsage } from "../../shared/utils.ts";
79
82
  import { discardPreservedWorktrees, formatParallelHandoffError, formatParallelHandoffReference, formatStoredParallelHandoffCleanup, parallelHandoffPath, readParallelHandoffManifest, recordParallelHandoffMerge, recordParallelHandoffSupersession, writeParallelHandoffGroup, writeWorktreeSetupHandoff } from "../shared/parallel-handoff.ts";
80
83
  import { summarizeContextModes, type ContextMode, type ContextSummary } from "../shared/context-mode.ts";
81
84
  import {
@@ -100,12 +103,13 @@ import { dismissRecoveredWorkflow } from "./async-dismiss-action.ts";
100
103
  import { promotePausedWorkflowIfSettled, reconcileDetachedWorkflowChildCompletion } from "./workflow-detach-reconcile.ts";
101
104
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
102
105
  import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
106
+ import { awaitExistingAsyncRun, claimWorkflowAwaitedResult } from "../background/await-async-run.ts";
103
107
  import { fallbackResultPayloadPathForSessionRun, removeResultIndex, resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
104
- import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, inheritedNestedParentAddressOf, inheritedNestedRouteOf, resolveNestedAsyncDir, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedParentAddress, type NestedRoute, type NestedRunResolutionScope } from "../shared/nested-events.ts";
108
+ import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, inheritedNestedParentAddressOf, inheritedNestedRouteOf, nestedRunScope, resolveNestedAsyncDir, retainNestedLookupRoute, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedParentAddress, type NestedRoute, type NestedRunResolutionScope } from "../shared/nested-events.ts";
105
109
  import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
106
110
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
107
111
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
108
- import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, stopStoppableAsyncStatusChildren } from "../shared/child-identity.ts";
112
+ import { isStoppableAsyncStatusStep, resolveAsyncStatusChild } from "../shared/child-identity.ts";
109
113
  import { inspectSubagentStatus } from "../background/run-status.ts";
110
114
  import { getExternalJobProvider } from "../../api/external-job-provider.ts";
111
115
  import { externalJobFollowUpRequestDigest, externalJobFollowUpRequestId, externalJobFollowUpRunId, externalJobPromptDigest, externalJobStableJson } from "../shared/external-job-runner.ts";
@@ -119,12 +123,14 @@ import type { MissionWorkflowChildUpdate } from "../../missions/types.ts";
119
123
  import { createMissionWorkflowState } from "../../missions/workflow-state.ts";
120
124
  import { resolveAuthorityDecision } from "../../policy/authority.ts";
121
125
  import { handleInspectorAction, INSPECTOR_ACTIONS } from "../../inspectors/actions.ts";
122
- import { createBuiltinInspectorPlugins } from "../../inspectors/plugins.ts";
126
+ import { getInspectorPlugins } from "../../inspectors/plugins.ts";
123
127
  import { handleHerdrProjectPaneAction, HERDR_PROJECT_PANE_ACTIONS } from "../../inspectors/herdr/project-panes.ts";
124
128
  import { previewSimpleWorkflowRun, runWorkflowScript, validateWorkflowScript, WorkflowScriptError, type WorkflowChildSettledNotification, type WorkflowLanePlan, type WorkflowReceiptResumeReference, type WorkflowScriptChildResult, type WorkflowScriptTraceEntry, type WorkflowSteerOptions, type WorkflowSteerResult } from "../../workflows/scripted-workflow.ts";
125
129
  import { formatIncrementalChildCompletion, incrementalChildCompletionTriggersTurn } from "../background/notify.ts";
130
+ import { appendWorkflowChildJournal, findWorkflowReuseSource, matchWorkflowReuse, workflowChildFingerprint, workflowScriptDigest, workflowStopCause, WORKFLOW_RUNTIME_REPLACED_RELAUNCH_NOTICE } from "../../workflows/workflow-reuse.ts";
126
131
  import { executeWorkflowHostCommand, resolveWorkflowHostOutputClaimPath, type WorkflowHostCommandParams, type WorkflowHostCommandResult } from "../../workflows/host-command.ts";
127
132
  import { buildWorkflowReceipt, readWorkflowReceipt, workflowReceiptPath, resolveWorkflowReceiptResumeEntry, writeWorkflowReceipt, type WorkflowReceipt, type WorkflowReceiptState } from "../../workflows/workflow-receipt.ts";
133
+ import { formatWorkflowKeyRevival, recordWorkflowRevival, withWorkflowRevivals } from "../../workflows/workflow-revival.ts";
128
134
  import { upsertHostStep, validHostStepNodes } from "../shared/host-step-status.ts";
129
135
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
130
136
  import { parseWorkflowChildSummary, workflowChildProgress, workflowChildSummary } from "../../workflows/workflow-child-summary.ts";
@@ -140,7 +146,7 @@ import {
140
146
  type WorkflowResourceAuthority,
141
147
  type WorkflowResourcePermit,
142
148
  } from "../../shared/workflow-child-permit.ts";
143
- import { deepFreezeWorkflowArgs, normalizeWorkflowArgs, resolveWorkflowResource } from "../../workflows/workflow-resources.ts";
149
+ import { deepFreezeWorkflowArgs, normalizeWorkflowArgs, resolveStructuredWorkflowResource, resolveWorkflowResource } from "../../workflows/workflow-resources.ts";
144
150
  import { stableJsonDigest } from "../../shared/launch-contract.ts";
145
151
  import {
146
152
  cleanupWorktrees,
@@ -196,15 +202,20 @@ import {
196
202
  type SubagentState,
197
203
  DIRS,
198
204
  DEFAULT_ARTIFACT_CONFIG,
205
+ DEFAULT_MAX_OUTPUT,
199
206
  DEFAULT_FORK_PREAMBLE,
200
207
  SUBAGENT_ACTIONS,
208
+ SUBAGENT_ASYNC_STARTED_EVENT,
209
+ SUBAGENT_CHILD_STATUS_EVENT,
201
210
  SUBAGENT_CONTROL_EVENT,
202
211
  SUBAGENT_CONTROL_INTERCOM_EVENT,
203
212
  SUBAGENT_FOREGROUND_COMPLETE_EVENT,
213
+ SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
204
214
  checkSubagentDepth,
205
215
  resolveChildMaxSubagentDepth,
206
216
  resolveCurrentMaxSubagentDepth,
207
217
  resolveMaxSubagentSpawnsPerRun,
218
+ truncateOutput,
208
219
  wrapForkTask,
209
220
  type ScheduleOrigin,
210
221
  type SteeringTargetState,
@@ -243,16 +254,17 @@ function hasSingleAdjacentTransposition(left: string, right: string): boolean {
243
254
  && left.slice(mismatch + 2) === right.slice(mismatch + 2);
244
255
  }
245
256
 
246
- export function unknownSubagentActionMessage(action: string): string {
257
+ export function unknownSubagentActionMessage(action: string, disabled?: DisabledFeatureSurface): string {
247
258
  const requested = action.toLowerCase();
248
- const suggestion = SUBAGENT_ACTIONS.find((candidate) => {
259
+ const enabledActions = SUBAGENT_ACTIONS.filter((candidate) => !disabled?.actions.has(candidate));
260
+ const suggestion = enabledActions.find((candidate) => {
249
261
  const distance = editDistance(requested, candidate);
250
262
  const closeMatch = distance <= Math.max(1, Math.floor(candidate.length / 4)) || hasSingleAdjacentTransposition(requested, candidate);
251
263
  if (DESTRUCTIVE_MANAGEMENT_ACTIONS.has(candidate)) return distance === 1 && requested.length >= candidate.length - 1;
252
264
  return closeMatch;
253
265
  });
254
266
  const nextStep = 'Use subagent({ action: "status" }) to inspect runs or subagent({ action: "list" }) to inspect agents.';
255
- const validActions = `Valid: ${SUBAGENT_ACTIONS.join(", ")}.`;
267
+ const validActions = `Valid: ${enabledActions.join(", ")}.`;
256
268
  return suggestion
257
269
  ? `Unknown action: ${action}. Did you mean ${suggestion}? ${nextStep} ${validActions}`
258
270
  : `Unknown action: ${action}. ${nextStep} ${validActions}`;
@@ -337,8 +349,8 @@ export interface SubagentParamsLike {
337
349
  mode?: SteerDeliveryMode | "plan" | "apply";
338
350
  repo?: string;
339
351
  planId?: string;
352
+ /** Internal script carrier (slash, prompt-workflow, scheduled, RPC, named resources). The model-facing tool rejects it. */
340
353
  workflowScript?: string;
341
- workflowScriptPath?: string;
342
354
  globalConcurrencyLimit?: number;
343
355
  maxSubagentSpawnsPerRun?: number;
344
356
  preflight?: import("../../shared/types.ts").WorkflowPreflight;
@@ -364,7 +376,7 @@ export interface SubagentParamsLike {
364
376
  runFanoutAdmitted?: boolean;
365
377
  /** Internal inherited tool/agent ceiling for delegated child launches. */
366
378
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
367
- /** Internal durable-run compatibility fields. Public callers must use workflowScript. */
379
+ /** Internal durable-run compatibility fields. Public callers must use workflow. */
368
380
  chain?: ChainStep[];
369
381
  tasks?: TaskParam[];
370
382
  concurrency?: number;
@@ -400,8 +412,8 @@ export interface SubagentParamsLike {
400
412
  modelOrigin?: ModelOrigin;
401
413
  fast?: boolean;
402
414
  thinking?: string | false;
403
- /** Public named workflow resource. Resolved before entering the workflow sandbox. */
404
- workflow?: string;
415
+ /** true = the ```js workflow block in the calling reply; a string containing "/" or "\" = script path; otherwise a named workflow resource. */
416
+ workflow?: string | true;
405
417
  args?: Record<string, unknown>;
406
418
  scope?: string;
407
419
  target?: string;
@@ -458,6 +470,7 @@ interface ExecutorDeps {
458
470
  getSubagentSessionRoot: (parentSessionFile: string | null) => string;
459
471
  expandTilde: (p: string) => string;
460
472
  discoverAgents: (cwd: string, scope: AgentScope, preferredModelProvider?: string) => { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig; maxThinking?: AgentConfig["maxThinking"]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] };
473
+ discoverAgentsAll?: typeof discoverAgentsAll;
461
474
  onAgentsChanged?: () => void;
462
475
  allowMutatingManagementActions?: boolean;
463
476
  activateSupervisorTransport?: () => void;
@@ -527,6 +540,7 @@ interface ExecutionContextData {
527
540
  contextPolicy: AgentDefaultContextPolicy;
528
541
  modelScope?: ModelScopeConfig;
529
542
  parentModel?: ParentModel;
543
+ scopedModelIds?: string[];
530
544
  parentSessionId: string | null;
531
545
  parentPiSessionId?: string;
532
546
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
@@ -540,18 +554,16 @@ function resolveRequestedCwd(runtimeCwd: string, requestedCwd: string | undefine
540
554
  return requestedCwd ? path.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
541
555
  }
542
556
 
543
- function loadWorkflowScriptPath(params: SubagentParamsLike, runtimeCwd: string): { params?: SubagentParamsLike; error?: string } {
544
- if (params.workflowScriptPath === undefined) return { params };
545
- const scriptPath = path.resolve(resolveRequestedCwd(runtimeCwd, params.cwd), params.workflowScriptPath);
546
- let workflowScript: string;
557
+ function readWorkflowScriptFile(requestedPath: string, requestedCwd: string | undefined, runtimeCwd: string): { script: string } | { error: string } {
558
+ const scriptPath = path.resolve(resolveRequestedCwd(runtimeCwd, requestedCwd), requestedPath);
559
+ let script: string;
547
560
  try {
548
- workflowScript = fs.readFileSync(scriptPath, "utf8");
561
+ script = fs.readFileSync(scriptPath, "utf8");
549
562
  } catch (error) {
550
- return { error: `Failed to read workflowScriptPath '${scriptPath}': ${error instanceof Error ? error.message : String(error)}` };
563
+ return { error: `Failed to read workflow script '${scriptPath}': ${error instanceof Error ? error.message : String(error)}` };
551
564
  }
552
- if (!workflowScript.trim()) return { error: `workflowScriptPath file '${scriptPath}' is empty.` };
553
- const { workflowScriptPath: _workflowScriptPath, ...rest } = params;
554
- return { params: { ...rest, workflowScript } };
565
+ if (!script.trim()) return { error: `Workflow script file '${scriptPath}' is empty.` };
566
+ return { script };
555
567
  }
556
568
 
557
569
  function currentProjectTrusted(ctx: Pick<ExtensionContext, "isProjectTrusted">): boolean {
@@ -596,6 +608,7 @@ export function removeForegroundControlIfIdle(state: SubagentState, runId: strin
596
608
  console.error(`Failed to retain live nested descendants for foreground run '${runId}':`, error);
597
609
  }
598
610
  }
611
+ retainNestedLookupRoute(state, control?.nestedRoute, control?.sessionId);
599
612
  state.foregroundControls.delete(runId);
600
613
  if (state.lastForegroundControlId === runId) state.lastForegroundControlId = null;
601
614
  return true;
@@ -663,6 +676,11 @@ function trustedSessionRootsForStatus(ctx: ExtensionContext, deps: ExecutorDeps)
663
676
  return [...new Set(roots)];
664
677
  }
665
678
 
679
+ /** Children follow the launching session's trust; hosts older than Pi's trust concept keep Pi's default. */
680
+ function sessionProjectTrust(ctx: ExtensionContext): boolean | undefined {
681
+ return typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : undefined;
682
+ }
683
+
666
684
  function spawnBudgetErrorResult(message: string, mode: "single" | "parallel" | "chain"): AgentToolResult<Details> {
667
685
  return {
668
686
  content: [{ type: "text", text: message }],
@@ -1402,6 +1420,7 @@ function appendStepToAsyncChain(input: {
1402
1420
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1403
1421
  currentModelProvider: parentModel?.provider,
1404
1422
  currentModel: parentModel,
1423
+ scopedModelIds: scopedModelIdsFromContext(input.ctx),
1405
1424
  modelScope: discoveredForAppend.modelScope,
1406
1425
  projectTrusted: currentProjectTrusted(input.ctx),
1407
1426
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
@@ -1562,6 +1581,51 @@ function resolveNestedResumeTarget(match: ResolvedSubagentRunId & { kind: "neste
1562
1581
  });
1563
1582
  }
1564
1583
 
1584
+ function resolveNestedExternalJobResumeTarget(match: ResolvedSubagentRunId & { kind: "nested" }, params: SubagentParamsLike, deps: ExecutorDeps): AsyncResumeSourceTarget | undefined {
1585
+ const run = match.match.run;
1586
+ if (run.state === "stopped") return undefined;
1587
+ const asyncDir = resolveNestedAsyncDir(match.match.rootRunId, run);
1588
+ if (!asyncDir) return undefined;
1589
+ const status = readNestedRunStatus(asyncDir, run);
1590
+ const steps = status?.steps ?? [];
1591
+ const step = steps[params.index ?? 0];
1592
+ if (!step) {
1593
+ // An index outside an external-job run gets the async resolver's index error instead of a Pi revive.
1594
+ if (params.index === undefined || !steps.some((candidate) => candidate.runner?.type === "external-job")) return undefined;
1595
+ } else if (!step.runner) {
1596
+ // Pi steps record no runner, and neither does a launch status before the runner starts.
1597
+ // A session file means a Pi run; otherwise the agent definition says what the step runs.
1598
+ if (nestedRunSessionFile(run)) return undefined;
1599
+ const agent = deps.discoverAgents(status?.cwd ?? deps.state.baseCwd, resolveExecutionAgentScope(params.agentScope)).agents.find((candidate) => candidate.name === step.agent);
1600
+ if (agent?.runner?.type === "external-job") throw new Error(externalJobWithoutMetadataMessage(run.id));
1601
+ return undefined;
1602
+ } else if (step.runner.type !== "external-job") {
1603
+ return undefined;
1604
+ }
1605
+ // External-job runs have no Pi session, so resume them as a provider follow-up from their own run directory.
1606
+ const target = resolveAsyncResumeTarget(compactOptional<Parameters<typeof resolveAsyncResumeTarget>[0]>({ dir: asyncDir, index: params.index }), nestedRunScope(match.match.rootRunId), { requireSessionFile: false });
1607
+ if (target.kind === "live") throw new Error(externalJobStillRunningMessage(target.runId));
1608
+ return { source: "async", ...target };
1609
+ }
1610
+
1611
+ function readNestedRunStatus(asyncDir: string, run: NestedRunSummary): AsyncStatus | null {
1612
+ try {
1613
+ return readStatus(asyncDir);
1614
+ } catch (error) {
1615
+ // A nested Pi run revives from its session file, so its unreadable status file must not block it.
1616
+ if (nestedRunSessionFile(run)) return null;
1617
+ throw error;
1618
+ }
1619
+ }
1620
+
1621
+ function externalJobStillRunningMessage(runId: string): string {
1622
+ return `External-job run '${runId}' is still running. Wait for completion, then use subagent({ action: "resume", id: "${runId}", message: "..." }).`;
1623
+ }
1624
+
1625
+ function externalJobWithoutMetadataMessage(runId: string): string {
1626
+ return `External-job run '${runId}' has no persisted provider metadata. Cannot follow up without the parent provider job id.`;
1627
+ }
1628
+
1565
1629
  async function waitForNestedControlResult(target: ResolvedSubagentRunId & { kind: "nested" }, requestId: string, ignoredFiles: ReadonlySet<string>, timeoutMs = 1_000) {
1566
1630
  const deadline = Date.now() + timeoutMs;
1567
1631
  while (Date.now() < deadline) {
@@ -1724,12 +1788,12 @@ async function resumeExternalJobFollowUp(input: {
1724
1788
  absoluteDeadlineAt?: number;
1725
1789
  }): Promise<AgentToolResult<Details>> {
1726
1790
  if (input.target.kind === "live" || input.target.state === "running" || input.target.state === "queued") {
1727
- return { content: [{ type: "text", text: `External-job run '${input.target.runId}' is still running. Wait for completion, then use subagent({ action: "resume", id: "${input.target.runId}", message: "..." }).` }], isError: true, details: { mode: "management", results: [] } };
1791
+ return { content: [{ type: "text", text: externalJobStillRunningMessage(input.target.runId) }], isError: true, details: { mode: "management", results: [] } };
1728
1792
  }
1729
1793
  const runner = input.target.runner;
1730
1794
  const externalJob = input.target.externalJob;
1731
1795
  if (runner?.type !== "external-job") return { content: [{ type: "text", text: "Internal error: external-job follow-up was requested for a non-external-job runner." }], isError: true, details: { mode: "management", results: [] } };
1732
- if (!externalJob) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has no persisted provider metadata. Cannot follow up without the parent provider job id.` }], isError: true, details: { mode: "management", results: [] } };
1796
+ if (!externalJob) return { content: [{ type: "text", text: externalJobWithoutMetadataMessage(input.target.runId) }], isError: true, details: { mode: "management", results: [] } };
1733
1797
  if (externalJob.provider !== runner.provider) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has mismatched provider metadata. Refusing to follow up.` }], isError: true, details: { mode: "management", results: [] } };
1734
1798
  if (!externalJobOptionsEqual(externalJob.options, runner.options)) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has mismatched provider options. Refusing to follow up.` }], isError: true, details: { mode: "management", results: [] } };
1735
1799
  if (!externalJob.providerJobId) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has no parent provider job id. Cannot follow up without reopening or redispatching, so this fails closed.` }], isError: true, details: { mode: "management", results: [] } };
@@ -1741,10 +1805,13 @@ async function resumeExternalJobFollowUp(input: {
1741
1805
  const requestDigest = externalJobFollowUpRequestDigest({ provider: runner.provider, parentProviderJobId: externalJob.providerJobId, promptDigest, options: runner.options });
1742
1806
  const requestId = externalJobFollowUpRequestId(requestDigest);
1743
1807
  const runId = externalJobFollowUpRunId(requestDigest);
1744
- const asyncDir = path.join(DIRS.async, runId);
1808
+ // A child launches the follow-up under its nested route, so look for an earlier one where it would be.
1809
+ const nestedRoute = inheritedNestedRoute(input.deps);
1810
+ const runRoots = nestedRoute ? nestedRunScope(nestedRoute.rootRunId) : { asyncDirRoot: DIRS.async, resultsDir: DIRS.results };
1811
+ const asyncDir = path.join(runRoots.asyncDirRoot, runId);
1745
1812
  const currentSessionId = input.deps.state.currentSessionId;
1746
1813
  if (!currentSessionId) return { content: [{ type: "text", text: "External-job follow-up requires an active parent session." }], isError: true, details: { mode: "management", results: [] } };
1747
- if (fs.existsSync(asyncDir) || fs.existsSync(resultFilePath(DIRS.results, runId))) {
1814
+ if (fs.existsSync(asyncDir) || fs.existsSync(resultFilePath(runRoots.resultsDir, runId))) {
1748
1815
  return externalJobFollowUpStarted({ sourceRunId: input.target.runId, runId, asyncDir, duplicate: true, interactive: input.ctx.hasUI });
1749
1816
  }
1750
1817
 
@@ -1787,11 +1854,13 @@ async function resumeExternalJobFollowUp(input: {
1787
1854
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1788
1855
  currentModelProvider: parentModel?.provider,
1789
1856
  currentModel: parentModel,
1857
+ scopedModelIds: scopedModelIdsFromContext(input.ctx),
1790
1858
  modelScope: input.modelScope,
1791
1859
  modelResponseAliases: input.deps.config.modelResponseAliases,
1792
1860
  interactive: input.ctx.hasUI,
1793
1861
  permissions: input.deps.config.permissions,
1794
1862
  childRuntime: input.deps.childRuntime,
1863
+ projectTrusted: currentProjectTrusted(input.ctx),
1795
1864
  }),
1796
1865
  cwd: input.effectiveCwd,
1797
1866
  artifactsDir,
@@ -1837,6 +1906,8 @@ function resolveRequestedResumeTarget(params: SubagentParamsLike, deps: Executor
1837
1906
  if (resolved?.kind === "nested") {
1838
1907
  if (params.chain?.length) throw new Error("Attaching a running subagent as a chain root is currently available for top-level async runs only.");
1839
1908
  if (resolved.match.run.state === "running" || resolved.match.run.state === "queued") return { kind: "live-nested", target: resolved };
1909
+ const externalJobTarget = resolveNestedExternalJobResumeTarget(resolved, params, deps);
1910
+ if (externalJobTarget) return externalJobTarget;
1840
1911
  const trustedSessionRoots = [
1841
1912
  ...(deps.config.defaultSessionDir ? [path.resolve(deps.expandTilde(deps.config.defaultSessionDir))] : []),
1842
1913
  ...(parentSessionFile ? [deps.getSubagentSessionRoot(parentSessionFile)] : []),
@@ -1854,6 +1925,7 @@ async function resumeAsyncRun(input: {
1854
1925
  parentModel?: ParentModel;
1855
1926
  absoluteDeadlineAt?: number;
1856
1927
  signal?: AbortSignal;
1928
+ onLaunch?: (launch: { agent: string; sessionName?: string; sessionFile?: string; async: boolean; runId?: string }) => void;
1857
1929
  }): Promise<AgentToolResult<Details>> {
1858
1930
  const followUp = (input.params.message ?? input.params.task ?? "").trim();
1859
1931
  const attachChain = (input.params.chain?.length ?? 0) > 0 ? input.params.chain as ChainStep[] : undefined;
@@ -1864,6 +1936,14 @@ async function resumeAsyncRun(input: {
1864
1936
  details: { mode: "management", results: [] },
1865
1937
  };
1866
1938
  }
1939
+ const timeoutOverflowError = timerDelayOverflowError("timeoutMs", input.params.timeoutMs);
1940
+ if (timeoutOverflowError) {
1941
+ return {
1942
+ content: [{ type: "text", text: timeoutOverflowError }],
1943
+ isError: true,
1944
+ details: { mode: "management", results: [] },
1945
+ };
1946
+ }
1867
1947
  if (input.params.model !== undefined) {
1868
1948
  return {
1869
1949
  content: [{ type: "text", text: "action='resume' reuses the persisted child model and does not accept a model override." }],
@@ -1922,7 +2002,7 @@ async function resumeAsyncRun(input: {
1922
2002
  const discoveredAgents = discovered.agents;
1923
2003
  const unknownAgentDiagnosticContext = diagnosticContextFromDiscovery(discovered, effectiveCwd, scope);
1924
2004
  const modelScope = discovered.modelScope;
1925
- const sessionName = resolveIntercomSessionTarget(input.deps.pi.getSessionName(), input.ctx.sessionManager.getSessionId());
2005
+ const sessionName = resolveIntercomSessionTarget(input.deps.childRuntime?.intercomSessionName ?? input.deps.pi.getSessionName(), input.ctx.sessionManager.getSessionId());
1926
2006
  const recoveryDescriptor = "recoveryDescriptor" in target ? target.recoveryDescriptor : undefined;
1927
2007
  const recoveryContext = recoveryDescriptor?.context ?? (input.params.context === "profile" ? undefined : input.params.context);
1928
2008
  const intercomBridge = resolveIntercomBridge({
@@ -1963,7 +2043,7 @@ async function resumeAsyncRun(input: {
1963
2043
  }
1964
2044
  if (target.source === "async" && target.runner?.type === "external-job") {
1965
2045
  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: [] } };
1966
- return resumeExternalJobFollowUp({
2046
+ const resumed = await resumeExternalJobFollowUp({
1967
2047
  target,
1968
2048
  followUp,
1969
2049
  baseAgentConfig,
@@ -1977,6 +2057,9 @@ async function resumeAsyncRun(input: {
1977
2057
  parentSessionFile,
1978
2058
  absoluteDeadlineAt: input.absoluteDeadlineAt,
1979
2059
  });
2060
+ const resumedRunId = resumed.details.runId ?? resumed.details.asyncId;
2061
+ if (!resumed.isError && resumedRunId) input.onLaunch?.({ agent: target.agent, async: true, runId: resumedRunId });
2062
+ return resumed;
1980
2063
  }
1981
2064
 
1982
2065
  if (attachChain) {
@@ -2042,6 +2125,7 @@ async function resumeAsyncRun(input: {
2042
2125
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
2043
2126
  currentModelProvider: parentModel?.provider,
2044
2127
  currentModel: parentModel,
2128
+ scopedModelIds: scopedModelIdsFromContext(input.ctx),
2045
2129
  modelScope,
2046
2130
  projectTrusted: currentProjectTrusted(input.ctx),
2047
2131
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
@@ -2049,7 +2133,7 @@ async function resumeAsyncRun(input: {
2049
2133
  interactive: input.ctx.hasUI,
2050
2134
  permissions: input.deps.config.permissions,
2051
2135
  childRuntime: input.deps.childRuntime,
2052
- }),
2136
+ }),
2053
2137
  availableModels,
2054
2138
  cwd: effectiveCwd,
2055
2139
  maxOutput: input.params.maxOutput,
@@ -2085,6 +2169,7 @@ async function resumeAsyncRun(input: {
2085
2169
  return result;
2086
2170
  }
2087
2171
  const attachedId = result.details.asyncId ?? runId;
2172
+ input.onLaunch?.({ agent: target.agent, ...(target.sessionFile ? { sessionFile: target.sessionFile } : {}), async: true, runId: attachedId });
2088
2173
  const lines = [
2089
2174
  `Attached async subagent ${target.runId} as the first step of a new chain.`,
2090
2175
  `Chain run: ${attachedId}`,
@@ -2102,11 +2187,14 @@ async function resumeAsyncRun(input: {
2102
2187
  if (!revivalSessionFile) {
2103
2188
  return { content: [{ type: "text", text: `Async run '${target.runId}' child ${target.index} does not have a persisted session file to resume from.` }], isError: true, details: { mode: "management", results: [] } };
2104
2189
  }
2190
+ if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
2191
+ 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: [] } };
2192
+ }
2105
2193
  if (target.source === "async" && asyncReviveRequiresRecoveryDescriptor(target)) {
2106
2194
  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: [] } };
2107
2195
  }
2108
- if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
2109
- return { content: [{ type: "text", text: "Cannot resume with baseRef: retained managed-worktree children continue in their existing worktree. Start a new worktree run from that base ref instead." }], isError: true, details: { mode: "management", results: [] } };
2196
+ if (target.source === "nested" && !target.recoveryDescriptor) {
2197
+ return { content: [{ type: "text", text: `Nested child '${target.runId}' is missing its required recovery identity. Start a new run instead.` }], isError: true, details: { mode: "management", results: [] } };
2110
2198
  }
2111
2199
  const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
2112
2200
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
@@ -2168,6 +2256,7 @@ async function resumeAsyncRun(input: {
2168
2256
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
2169
2257
  currentModelProvider: parentModel?.provider,
2170
2258
  currentModel: parentModel,
2259
+ scopedModelIds: scopedModelIdsFromContext(input.ctx),
2171
2260
  modelScope,
2172
2261
  projectTrusted: currentProjectTrusted(input.ctx),
2173
2262
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
@@ -2229,15 +2318,19 @@ async function resumeAsyncRun(input: {
2229
2318
  ...(input.params.timeoutMs !== undefined ? { timeoutMs: input.params.timeoutMs } : {}),
2230
2319
  ...(input.absoluteDeadlineAt !== undefined ? { absoluteDeadlineAt: input.absoluteDeadlineAt } : {}),
2231
2320
  ...(input.params.toolBudget !== undefined ? { toolBudget: input.params.toolBudget } : {}),
2232
- capabilityCeiling: intersectSubagentCapabilityCeilings("capabilityCeiling" in target ? target.capabilityCeiling : undefined, recoveryDescriptor?.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId)),
2321
+ // Recovery descriptors, remembered foreground runs, and current workflow roots
2322
+ // preserve parent authority before the selected agent's descendant ceiling.
2323
+ capabilityCeiling: intersectSubagentCapabilityCeilings(recoveryDescriptor?.capabilityCeiling ?? (target.source === "foreground" || (target.source === "async" && target.mode === "workflow") ? target.capabilityCeiling : undefined), resolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId)),
2233
2324
  runFanoutBudget: input.params.runFanoutBudget ?? recoveryDescriptor?.runFanoutBudget ?? createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(input.deps.config.maxSubagentSpawnsPerRun)),
2234
2325
  parentWorkflowRunId: input.params.workflowParentRunId,
2235
2326
  workflowKey: input.params.workflowKey,
2236
2327
  activeAsyncCapacity,
2237
2328
  }));
2329
+ const notifyLaunch = (): void => input.onLaunch?.({ agent: target.agent, sessionFile: revivalSessionFile, async: true, runId });
2238
2330
  if (result.isError) {
2239
2331
  const startedStatus = readStatus(revivalAsyncDir);
2240
2332
  if (input.params.workflowParentRunId !== undefined && startedStatus?.runId === runId && startedStatus.processTerminal?.runnerProcessInstanceId) {
2333
+ notifyLaunch();
2241
2334
  return {
2242
2335
  ...result,
2243
2336
  details: {
@@ -2252,6 +2345,7 @@ async function resumeAsyncRun(input: {
2252
2345
  activeAsyncCapacity?.rollback();
2253
2346
  return result;
2254
2347
  }
2348
+ notifyLaunch();
2255
2349
  for (const brief of queuedBriefs) fs.rmSync(brief.path, { force: true });
2256
2350
  if (queuedBriefs.length > 0 && sourceAsyncDir) {
2257
2351
  const sourceStatus = readStatus(sourceAsyncDir);
@@ -2265,62 +2359,31 @@ async function resumeAsyncRun(input: {
2265
2359
  if (input.params.workflowParentRunId !== undefined && result.details.asyncDir) {
2266
2360
  const asyncDir = result.details.asyncDir;
2267
2361
  const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
2268
- const stopOnAbort = () => { stopAsyncRun(input.deps.state, revivedId, input.deps.kill, { asyncDir, resolvedId: revivedId }); };
2269
- if (input.signal?.aborted) stopOnAbort();
2270
- else input.signal?.addEventListener("abort", stopOnAbort, { once: true });
2271
- let completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>;
2272
- try {
2273
- completed = await waitForImportedAsyncRoot({ runId: revivedId, asyncDir, resultPath, index: 0 });
2274
- } finally {
2275
- input.signal?.removeEventListener("abort", stopOnAbort);
2276
- }
2277
- if (completed.importedPublication) removeWorkflowAwaitedResult(asyncDir, resultPath, revivedId, completed.importedPublication);
2278
- const usage = importedAsyncRootUsage(completed);
2279
- const childResult: SingleResult = {
2280
- index: 0,
2281
- agent: completed.agent,
2282
- ...(completed.sessionName ? { sessionName: completed.sessionName } : {}),
2283
- task: effectiveFollowUp,
2284
- exitCode: completed.exitCode,
2285
- usage,
2286
- finalOutput: completed.output,
2287
- outputState: completed.output.trim() ? "present" : "absent",
2288
- ...(completed.error ? { error: completed.error } : {}),
2289
- ...(completed.timedOut ? { timedOut: true } : {}),
2290
- ...(completed.stopped ? { stopped: true } : {}),
2291
- ...(completed.sessionFile ? { sessionFile: completed.sessionFile } : {}),
2292
- ...(completed.model ? { model: completed.model } : {}),
2293
- ...(completed.requestedModel ? { requestedModel: completed.requestedModel } : {}),
2294
- ...(completed.contextOverflow ? { contextOverflow: true } : {}),
2295
- ...(completed.structuredOutput !== undefined ? { structuredOutput: completed.structuredOutput } : {}),
2296
- ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
2297
- ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
2298
- ...(completed.acceptance ? { acceptance: completed.acceptance } : {}),
2299
- ...(completed.artifactPaths ? { artifactPaths: completed.artifactPaths } : {}),
2300
- ...(completed.savedOutputPath ? { savedOutputPath: completed.savedOutputPath } : {}),
2301
- ...(completed.outputSaveError ? { outputSaveError: completed.outputSaveError } : {}),
2302
- ...(completed.transcriptPath ? { transcriptPath: completed.transcriptPath } : {}),
2303
- ...(completed.transcriptError ? { transcriptError: completed.transcriptError } : {}),
2304
- };
2305
- return {
2306
- 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.` }],
2307
- ...(completed.success ? {} : { isError: true }),
2308
- details: {
2309
- ...result.details,
2310
- runId: revivedId,
2311
- results: [childResult],
2312
- ...(target.launchContractDigest ? { sourceLaunchContractDigest: target.launchContractDigest } : {}),
2313
- },
2314
- };
2362
+ const stopListener = stopAwaitedAsyncChildOnAbort(input.signal, input.deps.state, revivedId, asyncDir, input.deps.kill);
2363
+ const completed = await waitForImportedAsyncRoot({ runId: revivedId, asyncDir, resultPath, index: 0 }, {
2364
+ shouldAbort: () => input.signal?.aborted === true,
2365
+ timeoutMessage: "Workflow stopped before async child completed.",
2366
+ abortedAsStopped: true,
2367
+ }).finally(stopListener.remove);
2368
+ const details: Details = { ...result.details };
2369
+ if (target.launchContractDigest) details.sourceLaunchContractDigest = target.launchContractDigest;
2370
+ return importWorkflowAwaitedChildResult(completed, { runId: revivedId, asyncDir, resultPath, task: effectiveFollowUp, parentWorkflowRunId: input.params.workflowParentRunId, details, emptyOutputText: `Revived ${target.source} subagent ${revivedId} completed without output.`, state: input.deps.state, pi: input.deps.pi });
2315
2371
  }
2316
2372
  const revivedTarget = intercomBridge.active ? resolveSubagentIntercomTarget(revivedId, target.agent, 0) : undefined;
2317
2373
  const sourceLabel = target.source;
2374
+ let workflowRevivalWarning: string | undefined;
2375
+ try {
2376
+ if (target.source === "async") recordWorkflowRevival(DIRS.async, target.runId, revivedId);
2377
+ } catch (error) {
2378
+ workflowRevivalWarning = `Warning: workflow key link not recorded: ${error instanceof Error ? error.message : String(error)}`;
2379
+ }
2318
2380
  const lines = [
2319
2381
  `Revived ${sourceLabel} subagent from ${target.runId}.`,
2320
2382
  `Revived run: ${revivedId}`,
2321
2383
  `Agent: ${target.agent}`,
2322
2384
  `Session: ${target.sessionFile}`,
2323
2385
  result.details.asyncDir ? `Async dir: ${result.details.asyncDir}` : undefined,
2386
+ workflowRevivalWarning,
2324
2387
  revivedTarget ? `Intercom target: ${revivedTarget} (if registered)` : undefined,
2325
2388
  `Status if needed: subagent({ action: "status", id: "${revivedId}" })`,
2326
2389
  ].filter((line): line is string => Boolean(line));
@@ -2488,6 +2551,28 @@ function canonicalizeAgentName(name: string, agents: AgentConfig[], diagnostics:
2488
2551
  return { name: resolved.agent.name };
2489
2552
  }
2490
2553
 
2554
+ // Mirrors child launch: workflow children without their own cwd/agentScope discover agents at the workflow cwd and scope.
2555
+ function workflowValidationOptions(deps: ExecutorDeps, params: SubagentParamsLike, runtimeCwd: string, parentModelProvider: () => string | undefined): Parameters<typeof validateWorkflowScript>[1] {
2556
+ const cwd = resolveRequestedCwd(runtimeCwd, params.cwd);
2557
+ const scope = resolveExecutionAgentScope(params.agentScope);
2558
+ let discovered: ReturnType<ExecutorDeps["discoverAgents"]> | undefined;
2559
+ return {
2560
+ maxSubagentSpawnsPerRun: params.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
2561
+ agentNameError: (name) => {
2562
+ discovered ??= deps.discoverAgents(cwd, scope, parentModelProvider());
2563
+ const { agents } = discovered;
2564
+ const resolved = resolveAgentName(name, agents);
2565
+ if (resolved.agent || resolved.error) return canonicalizeAgentName(name, agents, discovered.agentDiagnostics, diagnosticContextFromDiscovery(discovered, cwd, scope)).error;
2566
+ const requested = name.trim().toLowerCase();
2567
+ const suggestion = [...new Set(agents.flatMap((agent) => [agent.name, ...(agent.localName ? [agent.localName] : []), ...(agent.aliases ?? [])]))]
2568
+ .map((candidate) => ({ candidate, distance: editDistance(requested, candidate.toLowerCase()) }))
2569
+ .filter(({ candidate, distance }) => distance <= Math.max(1, Math.floor(candidate.length / 4)) || hasSingleAdjacentTransposition(requested, candidate.toLowerCase()))
2570
+ .sort((left, right) => left.distance - right.distance || left.candidate.localeCompare(right.candidate))[0]?.candidate;
2571
+ return `Unknown agent '${name}'.${suggestion ? ` Did you mean '${suggestion}'?` : ""} Use subagent({ action: "list" }) to inspect agents.`;
2572
+ },
2573
+ };
2574
+ }
2575
+
2491
2576
  function canonicalizeExecutionParams(params: SubagentParamsLike, agents: AgentConfig[], diagnostics: AgentDiscoveryDiagnostic[] | undefined, context: UnknownAgentDiagnosticContext): { params?: SubagentParamsLike; error?: string } {
2492
2577
  const resolve = (name: string, location?: string): { name?: string; error?: string } => {
2493
2578
  const result = canonicalizeAgentName(name, agents, diagnostics, context);
@@ -2575,11 +2660,15 @@ function validateExecutionInput(
2575
2660
  context: UnknownAgentDiagnosticContext,
2576
2661
  ): AgentToolResult<Details> | null {
2577
2662
  if (Number(hasChain) + Number(hasTasks) + Number(hasSingle) !== 1) {
2663
+ const agentList = agents.map((a) => a.name).join(", ") || "none";
2664
+ const noMode = !hasChain && !hasTasks && !hasSingle;
2578
2665
  return {
2579
2666
  content: [
2580
2667
  {
2581
2668
  type: "text",
2582
- text: `Provide exactly one mode. Agents: ${agents.map((a) => a.name).join(", ") || "none"}`,
2669
+ text: noMode && typeof params.workflowKey === "string"
2670
+ ? `Workflow child '${params.workflowKey}' has no agent. Pass { key, agent, task }. Agents: ${agentList}`
2671
+ : `Provide exactly one mode. Agents: ${agentList}`,
2583
2672
  },
2584
2673
  ],
2585
2674
  isError: true,
@@ -2832,6 +2921,19 @@ function buildRequestedModeError(params: SubagentParamsLike, message: string): A
2832
2921
  );
2833
2922
  }
2834
2923
 
2924
+ function buildWorkflowValidationResult(
2925
+ validation: ReturnType<typeof validateWorkflowScript>,
2926
+ mode: "management" | "workflow",
2927
+ preflight?: import("../../shared/types.ts").WorkflowPreflight,
2928
+ ): AgentToolResult<Details> {
2929
+ const payload = preflight ? { ...validation, preflight } : validation;
2930
+ return {
2931
+ content: [{ type: "text", text: JSON.stringify(payload) }],
2932
+ ...(validation.ok ? {} : { isError: true }),
2933
+ details: { mode, results: [] },
2934
+ };
2935
+ }
2936
+
2835
2937
  function applySingleAgentLaunchDefaults(params: SubagentParamsLike, agents: AgentConfig[]): SubagentParamsLike {
2836
2938
  if ((params.chain?.length ?? 0) > 0 || (params.tasks?.length ?? 0) > 0 || !params.agent) return params;
2837
2939
  const agent = agents.find((candidate) => candidate.name === params.agent);
@@ -2893,6 +2995,12 @@ export { DEFAULT_ASYNC_TIMEOUT_MS };
2893
2995
  */
2894
2996
  const MAX_TIMER_DELAY_MS = 2_147_483_647;
2895
2997
 
2998
+ function timerDelayOverflowError(name: string, value: unknown): string | undefined {
2999
+ return typeof value === "number" && value > MAX_TIMER_DELAY_MS
3000
+ ? `${name} must be a positive integer no larger than ${MAX_TIMER_DELAY_MS}.`
3001
+ : undefined;
3002
+ }
3003
+
2896
3004
  /**
2897
3005
  * Resolve the optional global default runtime deadline from extension config
2898
3006
  * (`config.timeoutMs`). Returns undefined for unset or invalid values so callers
@@ -2916,6 +3024,8 @@ export function resolveForegroundTimeout(params: SubagentParamsLike, defaultTime
2916
3024
  if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
2917
3025
  return { error: `${name} must be a positive integer.` };
2918
3026
  }
3027
+ const overflowError = timerDelayOverflowError(name, value);
3028
+ if (overflowError) return { error: overflowError };
2919
3029
  }
2920
3030
  if (rawTimeout !== undefined && rawMaxRuntime !== undefined && rawTimeout !== rawMaxRuntime) {
2921
3031
  return { error: "timeoutMs and maxRuntimeMs are aliases; provide only one value or use the same value for both." };
@@ -3071,6 +3181,7 @@ function resolveStaticLaunchSummary(input: {
3071
3181
  explicitModel?: string;
3072
3182
  agents: AgentConfig[];
3073
3183
  parentModel?: ParentModel;
3184
+ scopedModelIds?: string[];
3074
3185
  availableModels: ModelInfo[];
3075
3186
  currentProvider?: string;
3076
3187
  modelScope?: ModelScopeConfig;
@@ -3078,7 +3189,7 @@ function resolveStaticLaunchSummary(input: {
3078
3189
  }): StaticLaunchSummary {
3079
3190
  const agentConfig = input.agents.find((agent) => agent.name === input.agent);
3080
3191
  const externalRunner = agentConfig?.runner?.type === "external-cli" || agentConfig?.runner?.type === "external-job";
3081
- const modelScopes = resolveModelScopesForAgent(input.modelScope, input.agent, input.parentModel);
3192
+ const modelScopes = resolveModelScopesForAgent(input.modelScope, input.agent, input.parentModel, input.scopedModelIds);
3082
3193
  const model = externalRunner
3083
3194
  ? undefined
3084
3195
  : resolveEffectiveSubagentModel(
@@ -3103,6 +3214,7 @@ function collectStaticLaunchSummaries(input: {
3103
3214
  params: SubagentParamsLike;
3104
3215
  agents: AgentConfig[];
3105
3216
  parentModel?: ParentModel;
3217
+ scopedModelIds?: string[];
3106
3218
  availableModels: ModelInfo[];
3107
3219
  currentProvider?: string;
3108
3220
  modelScope?: ModelScopeConfig;
@@ -3115,6 +3227,7 @@ function collectStaticLaunchSummaries(input: {
3115
3227
  explicitModel,
3116
3228
  agents: input.agents,
3117
3229
  parentModel: input.parentModel,
3230
+ scopedModelIds: input.scopedModelIds,
3118
3231
  availableModels: input.availableModels,
3119
3232
  currentProvider: input.currentProvider,
3120
3233
  modelScope: input.modelScope,
@@ -3269,27 +3382,44 @@ function removeWorkflowAwaitedResult(asyncDir: string, resultPath: string, runId
3269
3382
  removeResultIndex(asyncDir, publication.sessionId, runId, publication.toolCallId);
3270
3383
  }
3271
3384
 
3272
- async function waitForWorkflowAsyncSingleResult(
3273
- params: SubagentParamsLike,
3274
- launchResult: AgentToolResult<Details>,
3275
- options: { runId: string; task: string; signal?: AbortSignal; state: SubagentState; kill?: ExecutorDeps["kill"] },
3276
- ): Promise<AgentToolResult<Details>> {
3277
- if (params.workflowAwaitAsync !== true || !launchResult.details.asyncDir) return launchResult;
3278
- const asyncDir = launchResult.details.asyncDir;
3279
- const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
3280
- const stopOnAbort = () => { stopAsyncRun(options.state, options.runId, options.kill, { asyncDir, resolvedId: options.runId }); };
3281
- if (options.signal?.aborted) stopOnAbort();
3282
- else options.signal?.addEventListener("abort", stopOnAbort, { once: true });
3283
- let completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>;
3385
+ function emitWorkflowAwaitedChildComplete(
3386
+ pi: ExtensionAPI,
3387
+ state: SubagentState,
3388
+ runId: string,
3389
+ asyncDir: string,
3390
+ parentWorkflowRunId: string | undefined,
3391
+ completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>,
3392
+ ): void {
3393
+ let status: ReturnType<typeof readStatus> | undefined;
3284
3394
  try {
3285
- completed = await waitForImportedAsyncRoot({ runId: options.runId, asyncDir, resultPath, index: 0 }, omitUndefinedProperties({
3286
- shouldAbort: () => options.signal?.aborted === true,
3287
- timeoutMessage: "Workflow stopped before async child completed.",
3288
- }));
3289
- } finally {
3290
- options.signal?.removeEventListener("abort", stopOnAbort);
3395
+ status = readStatus(asyncDir);
3396
+ } catch (error) {
3397
+ console.error(`Failed to read awaited workflow child status for ${runId}; emitting completion with fallback metadata:`, error);
3291
3398
  }
3292
- if (completed.importedPublication) removeWorkflowAwaitedResult(asyncDir, resultPath, options.runId, completed.importedPublication);
3399
+ pi.events.emit(SUBAGENT_ASYNC_COMPLETE_EVENT, {
3400
+ id: runId,
3401
+ runId,
3402
+ sessionId: status?.sessionId ?? completed.importedPublication?.sessionId ?? state.currentSessionId,
3403
+ completionOwnerId: status?.completionOwnerId ?? state.completionOwnerId ?? currentCompletionOwnerId(),
3404
+ asyncDir,
3405
+ agent: completed.agent,
3406
+ mode: "single",
3407
+ state: completed.stopped ? "stopped" : completed.success ? "complete" : "failed",
3408
+ success: completed.success,
3409
+ timestamp: Date.now(),
3410
+ triggerTurn: false,
3411
+ awaitedByWorkflow: true,
3412
+ parentWorkflowRunId,
3413
+ });
3414
+ }
3415
+
3416
+ /** Consumes an awaited workflow child's published result: clears the payload, announces completion, and builds the tool result. */
3417
+ function importWorkflowAwaitedChildResult(
3418
+ completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>,
3419
+ options: { runId: string; asyncDir: string; resultPath: string; task: string; parentWorkflowRunId: string | undefined; details: Details; emptyOutputText?: string; state: SubagentState; pi: ExtensionAPI },
3420
+ ): AgentToolResult<Details> {
3421
+ if (completed.importedPublication) removeWorkflowAwaitedResult(options.asyncDir, options.resultPath, options.runId, completed.importedPublication);
3422
+ emitWorkflowAwaitedChildComplete(options.pi, options.state, options.runId, options.asyncDir, options.parentWorkflowRunId, completed);
3293
3423
  const usage = importedAsyncRootUsage(completed);
3294
3424
  const childResult: SingleResult = omitUndefinedProperties({
3295
3425
  index: 0,
@@ -3318,16 +3448,55 @@ async function waitForWorkflowAsyncSingleResult(
3318
3448
  ...(completed.transcriptError ? { transcriptError: completed.transcriptError } : {}),
3319
3449
  });
3320
3450
  return {
3321
- 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.` }],
3451
+ content: [{ type: "text", text: (completed.success ? completed.output || completed.error : completed.error || completed.output) || (options.emptyOutputText ?? `Async workflow child ${options.runId} completed without output.`) }],
3322
3452
  ...(completed.success ? {} : { isError: true }),
3323
3453
  details: {
3324
- ...launchResult.details,
3454
+ ...options.details,
3325
3455
  runId: options.runId,
3326
3456
  results: [childResult],
3327
3457
  },
3328
3458
  };
3329
3459
  }
3330
3460
 
3461
+ // A replaced runtime leaves the child running so a relaunch of the workflow can re-attach to it.
3462
+ function stopAwaitedAsyncChildOnAbort(signal: AbortSignal | undefined, state: SubagentState, runId: string, asyncDir: string, kill?: ExecutorDeps["kill"]): { remove: () => void } {
3463
+ const stopOnAbort = () => { if (!workflowStopCause(signal?.reason)) stopAsyncRun(state, runId, kill, { asyncDir, resolvedId: runId }); };
3464
+ if (signal?.aborted) stopOnAbort();
3465
+ else signal?.addEventListener("abort", stopOnAbort, { once: true });
3466
+ return { remove: () => signal?.removeEventListener("abort", stopOnAbort) };
3467
+ }
3468
+
3469
+ // Live workflow controls are keyed by the full run id; a stop id may be a prefix or the launch tool-call id.
3470
+ function resolveLiveWorkflowRunId(deps: ExecutorDeps, id: string): string | undefined {
3471
+ const controllers = deps.state.workflowControllers;
3472
+ if (!controllers?.size) return undefined;
3473
+ if (controllers.has(id)) return id;
3474
+ try {
3475
+ const resolved = resolveSubagentRunId(id, omitUndefinedProperties({ state: deps.state, nested: nestedResolutionScopeForExecutor(deps) }));
3476
+ return resolved?.kind === "async" && controllers.has(resolved.id) ? resolved.id : undefined;
3477
+ } catch {
3478
+ // The generic stop path resolves the id again and reports the error.
3479
+ return undefined;
3480
+ }
3481
+ }
3482
+
3483
+ async function waitForWorkflowAsyncSingleResult(
3484
+ params: SubagentParamsLike,
3485
+ launchResult: AgentToolResult<Details>,
3486
+ options: { runId: string; task: string; signal?: AbortSignal; state: SubagentState; pi: ExtensionAPI; kill?: ExecutorDeps["kill"] },
3487
+ ): Promise<AgentToolResult<Details>> {
3488
+ if (params.workflowAwaitAsync !== true || !launchResult.details.asyncDir) return launchResult;
3489
+ const asyncDir = launchResult.details.asyncDir;
3490
+ const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
3491
+ const stopListener = stopAwaitedAsyncChildOnAbort(options.signal, options.state, options.runId, asyncDir, options.kill);
3492
+ const completed = await waitForImportedAsyncRoot({ runId: options.runId, asyncDir, resultPath, index: 0 }, omitUndefinedProperties({
3493
+ shouldAbort: () => options.signal?.aborted === true,
3494
+ timeoutMessage: "Workflow stopped before async child completed.",
3495
+ abortedAsStopped: true,
3496
+ })).finally(stopListener.remove);
3497
+ return importWorkflowAwaitedChildResult(completed, { runId: options.runId, asyncDir, resultPath, task: options.task, parentWorkflowRunId: params.workflowParentRunId, details: launchResult.details, state: options.state, pi: options.pi });
3498
+ }
3499
+
3331
3500
  async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Promise<AgentToolResult<Details> | null> {
3332
3501
  const {
3333
3502
  params,
@@ -3369,6 +3538,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3369
3538
  parentSessionId: data.parentPiSessionId,
3370
3539
  currentModelProvider: parentModel?.provider,
3371
3540
  currentModel: parentModel,
3541
+ scopedModelIds: data.scopedModelIds,
3372
3542
  modelScope: data.modelScope,
3373
3543
  projectTrusted: currentProjectTrusted(ctx),
3374
3544
  ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
@@ -3416,7 +3586,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3416
3586
  if ((a.runner?.type === "external-cli" || a.runner?.type === "external-job") && (params.fast ?? a.fast) === true) {
3417
3587
  return buildRequestedModeError(params, `Agent '${a.name}' uses runner.type='${a.runner.type}' and does not support fast mode.`);
3418
3588
  }
3419
- const modelScopes = resolveModelScopesForAgent(data.modelScope, a.name, parentModel);
3589
+ const modelScopes = resolveModelScopesForAgent(data.modelScope, a.name, parentModel, data.scopedModelIds);
3420
3590
  const modelOrigin = resolveModelOrigin({
3421
3591
  storedOrigin: params.modelOrigin as ModelOrigin | undefined,
3422
3592
  explicitModel: params.model as string | undefined,
@@ -3497,7 +3667,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3497
3667
  lane: params.lane,
3498
3668
  workflowAwaitAsync: params.workflowAwaitAsync,
3499
3669
  }));
3500
- return waitForWorkflowAsyncSingleResult(params, asyncResult, { runId: id, task: params.task ?? "", signal: data.signal, state: deps.state, kill: deps.kill });
3670
+ return waitForWorkflowAsyncSingleResult(params, asyncResult, { runId: id, task: params.task ?? "", signal: data.signal, state: deps.state, pi: deps.pi, kill: deps.kill });
3501
3671
  }
3502
3672
 
3503
3673
  return null;
@@ -3607,6 +3777,45 @@ function appendWorkflowOutputWarning(text: string, warning: string | undefined):
3607
3777
  return warning ? `${text}\n\n${warning}` : text;
3608
3778
  }
3609
3779
 
3780
+ const WORKFLOW_TRACE_ERROR_MAX_CHARS = 500;
3781
+
3782
+ // Return, emits, console, and trace errors (which carry child text) have no size limit of their
3783
+ // own, so only they are cut; other host sections stay whole. The saved full result is uncut.
3784
+ function formatWorkflowResultText(input: {
3785
+ head: string[];
3786
+ script: string[];
3787
+ trace: Array<{ line: string; error?: string }>;
3788
+ tail: string[];
3789
+ maxOutput: MaxOutputConfig | undefined;
3790
+ aggregateOutputPath: string | undefined;
3791
+ fullResultPath: string;
3792
+ producedChildOutputPaths: ReadonlySet<string>;
3793
+ }): string {
3794
+ const traceSection = (error: (text: string) => string) => input.trace.length > 0
3795
+ ? [`Call trace:\n${input.trace.map((entry) => `${entry.line}${entry.error ? ` — ${error(entry.error)}` : ""}`).join("\n")}`]
3796
+ : [];
3797
+ const fullText = [...input.head, ...input.script, ...traceSection((error) => error), ...input.tail].join("\n\n");
3798
+ const outputWarning = writeWorkflowAggregateOutput(input.aggregateOutputPath, fullText, input.producedChildOutputPaths);
3799
+ const scriptText = input.script.join("\n\n");
3800
+ const config = { ...DEFAULT_MAX_OUTPUT, ...input.maxOutput };
3801
+ const scriptCut = truncateOutput(scriptText, config).truncated;
3802
+ const traceCut = input.trace.some((entry) => (entry.error?.length ?? 0) > WORKFLOW_TRACE_ERROR_MAX_CHARS);
3803
+ let shownScriptText = scriptText;
3804
+ let saveWarning: string | undefined;
3805
+ let savedPath: string | undefined;
3806
+ if (scriptCut || traceCut) {
3807
+ const aggregateHoldsFullText = input.aggregateOutputPath !== undefined && !outputWarning
3808
+ && !input.producedChildOutputPaths.has(resolveWorkflowHostOutputClaimPath(input.aggregateOutputPath));
3809
+ if (!aggregateHoldsFullText) saveWarning = writeWorkflowAggregateOutput(input.fullResultPath, fullText, new Set());
3810
+ savedPath = aggregateHoldsFullText ? input.aggregateOutputPath : saveWarning ? undefined : input.fullResultPath;
3811
+ if (scriptCut) shownScriptText = truncateOutput(scriptText, config, savedPath).text;
3812
+ }
3813
+ const shownTrace = traceSection((error) => error.length > WORKFLOW_TRACE_ERROR_MAX_CHARS ? `${error.slice(0, WORKFLOW_TRACE_ERROR_MAX_CHARS)}… (+${error.length - WORKFLOW_TRACE_ERROR_MAX_CHARS} chars)` : error);
3814
+ const traceNote = traceCut && !scriptCut && savedPath ? [`[TRUNCATED: trace errors shortened - full output at ${savedPath}]`] : [];
3815
+ const text = [...input.head, ...(shownScriptText ? [shownScriptText] : []), ...shownTrace, ...input.tail, ...traceNote].join("\n\n");
3816
+ return appendWorkflowOutputWarning(appendWorkflowOutputWarning(text, outputWarning), saveWarning);
3817
+ }
3818
+
3610
3819
  export function resolveWorkflowChildLocalCwd(input: {
3611
3820
  workflowCwd: string;
3612
3821
  discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
@@ -3895,7 +4104,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3895
4104
  const parentModel = data.parentModel;
3896
4105
  const currentProvider = parentModel?.provider;
3897
4106
  const availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);
3898
- const modelScopes = resolveModelScopesForAgent(data.modelScope, agentConfig.name, parentModel);
4107
+ const modelScopes = resolveModelScopesForAgent(data.modelScope, agentConfig.name, parentModel, data.scopedModelIds);
3899
4108
  let task = typeof params.task === "string" ? params.task : "";
3900
4109
  const modelOrigin = resolveModelOrigin({
3901
4110
  storedOrigin: params.modelOrigin as ModelOrigin | undefined,
@@ -4030,6 +4239,20 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4030
4239
  let detachForeground: ((reason?: string) => boolean) | undefined;
4031
4240
  let childSessionControls: ForegroundChildSessionControls | undefined;
4032
4241
  const foregroundControl = deps.state.foregroundControls.get(runId);
4242
+ const syncHerdrForegroundChild = () => {
4243
+ if (!foregroundControl?.parentWorkflowRunId) return;
4244
+ try {
4245
+ deps.pi.events.emit(HERDR_FOREGROUND_CONTROL_CHANGED_EVENT, { runId: foregroundControl.parentWorkflowRunId });
4246
+ } catch (error) {
4247
+ console.error("Failed to sync Herdr foreground child:", error);
4248
+ }
4249
+ };
4250
+ const finishTrackedForegroundChild = () => {
4251
+ if (!foregroundControl) return;
4252
+ const wasActive = foregroundControl.activeChildren?.has(0) === true;
4253
+ finishForegroundChild(foregroundControl, 0);
4254
+ if (wasActive) syncHerdrForegroundChild();
4255
+ };
4033
4256
  if (foregroundControl) {
4034
4257
  const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask());
4035
4258
  beginForegroundChild(foregroundControl, omitUndefinedProperties({
@@ -4065,6 +4288,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4065
4288
  }));
4066
4289
  // Capture the owned mailbox before a child can start and finish between polling ticks.
4067
4290
  if (deps.childRuntime?.fanoutChild) deps.activateSupervisorTransport?.();
4291
+ syncHerdrForegroundChild();
4068
4292
  }
4069
4293
 
4070
4294
  const modelResponseAliases = deps.config.modelResponseAliases === undefined ? undefined : structuredClone(deps.config.modelResponseAliases);
@@ -4089,12 +4313,10 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4089
4313
  remoteReads: foregroundMachine ? readsOverride : undefined,
4090
4314
  permissions: deps.config.permissions,
4091
4315
  runtimeSnapshotHost: deps.pi,
4092
- hostAvailableBuiltins: getHostBuiltinToolNames(deps.pi),
4093
4316
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
4094
4317
  projectTrusted: currentProjectTrusted(ctx),
4095
4318
  ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
4096
4319
  requiredExtensions,
4097
- llmIntentArbiter: createTaskMutationArbiter({ model: ctx.model, modelRegistry: ctx.modelRegistry, sessionId: ctx.sessionManager.getSessionId() }),
4098
4320
  childRuntime: deps.childRuntime,
4099
4321
  onChildSession: (controls) => { childSessionControls = controls; },
4100
4322
  context: data.contextPolicy.contextForAgent(params.agent!),
@@ -4103,6 +4325,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4103
4325
  cwd: singleCwd,
4104
4326
  requestedCwd: data.requestedCwd,
4105
4327
  signal,
4328
+ abortedAsStopped: params.workflowParentRunId !== undefined,
4106
4329
  interruptSignal: interruptController.signal,
4107
4330
  allowIntercomDetach: agentConfig.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,
4108
4331
  intercomEvents: deps.pi.events,
@@ -4178,7 +4401,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4178
4401
  if (!artifactConfig.enabled) cleanupStructuredOutputRuntime(structuredRuntime);
4179
4402
  } finally {
4180
4403
  try {
4181
- if (foregroundControl) finishForegroundChild(foregroundControl, 0);
4404
+ finishTrackedForegroundChild();
4182
4405
  } finally {
4183
4406
  removeForegroundControlIfIdle(deps.state, runId, deps.trackRetainedNestedRoute);
4184
4407
  }
@@ -4205,7 +4428,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4205
4428
  // authoritative completion remains live.
4206
4429
  if (!r?.detached) {
4207
4430
  if (!artifactConfig.enabled) cleanupStructuredOutputRuntime(structuredRuntime);
4208
- if (foregroundControl) finishForegroundChild(foregroundControl, 0);
4431
+ finishTrackedForegroundChild();
4209
4432
  }
4210
4433
  }
4211
4434
  if (!r.detached) {
@@ -4312,7 +4535,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4312
4535
  }
4313
4536
 
4314
4537
  function inferExecutionMode(params: SubagentParamsLike): Details["mode"] {
4315
- if (params.workflowScript !== undefined) return "workflow";
4538
+ if (params.workflowScript !== undefined || params.workflow !== undefined) return "workflow";
4316
4539
  if ((params.chain?.length ?? 0) > 0) return "chain";
4317
4540
  if ((params.tasks?.length ?? 0) > 0) return "parallel";
4318
4541
  return "single";
@@ -4390,12 +4613,13 @@ export function bindMissionWorkflowChildAsyncLaunch(
4390
4613
  binding: MissionLaunchBinding | undefined,
4391
4614
  asyncByDefault: boolean,
4392
4615
  asyncId: string = randomUUID(),
4616
+ nestedRootRunId?: string,
4393
4617
  ): SubagentParamsLike {
4394
4618
  const requestedAsync = params.async ?? asyncByDefault;
4395
4619
  if (!binding || !requestedAsync || params.clarify === true) return params;
4396
4620
  const id = asyncId.trim();
4397
4621
  if (!id || path.basename(id) !== id) throw new Error("workflow child async id must be a single path segment");
4398
- writeMissionAsyncBinding(path.join(DIRS.async, id), binding);
4622
+ writeMissionAsyncBinding(path.join(nestedRootRunId ? nestedRunScope(nestedRootRunId).asyncDirRoot : DIRS.async, id), binding);
4399
4623
  return { ...params, workflowChildAsyncId: id };
4400
4624
  }
4401
4625
 
@@ -4406,21 +4630,25 @@ function workflowChildResult(
4406
4630
  resumeState?: SubagentState,
4407
4631
  forcedTerminalOutcome?: WorkflowTerminalOutcome,
4408
4632
  ): WorkflowScriptChildResult {
4633
+ const running = missionWorkflowChildStatus(result) === "running";
4409
4634
  const receiptOutput = result.content.map((part) => part.type === "text" ? part.text : "").filter(Boolean).join("\n");
4410
- const output = result.details.results.length === 1 && result.details.results[0]?.finalOutput !== undefined
4635
+ const output = running ? "" : result.details.results.length === 1 && result.details.results[0]?.finalOutput !== undefined
4411
4636
  ? result.details.results[0].finalOutput
4412
4637
  : receiptOutput;
4413
4638
  const childError = result.details.results.map((child) => child.error).find((error): error is string => Boolean(error));
4414
- const failureErrorBase = childError && receiptOutput
4415
- ? receiptOutput.includes(childError) ? receiptOutput : `${childError}\n\n${receiptOutput}`
4416
- : childError || receiptOutput || output || "Child run failed.";
4639
+ const stopped = result.details.results.some((child) => child.stopped);
4640
+ // A stopped child's receipt text carries the run fan-out annotation; report the structured stop reason instead.
4641
+ const failureErrorBase = stopped && childError
4642
+ ? childError
4643
+ : childError && receiptOutput
4644
+ ? receiptOutput.includes(childError) ? receiptOutput : `${childError}\n\n${receiptOutput}`
4645
+ : childError || receiptOutput || output || "Child run failed.";
4417
4646
  const savedOutputEvidence = [...new Set(result.details.results.map((child) => child.savedOutputPath).filter((value): value is string => Boolean(value)))]
4418
4647
  .filter((savedOutputPath) => !failureErrorBase.includes(savedOutputPath))
4419
4648
  .map((savedOutputPath) => `Saved output: ${savedOutputPath}`);
4420
4649
  const failureError = [failureErrorBase, ...savedOutputEvidence].join("\n");
4421
4650
  const detached = result.details.results.some((child) => child.detached);
4422
4651
  const interrupted = result.details.results.some((child) => child.interrupted);
4423
- const stopped = result.details.results.some((child) => child.stopped);
4424
4652
  const terminalOutcome = forcedTerminalOutcome
4425
4653
  ?? (result.details.results.some((child) => child.timedOut)
4426
4654
  ? { state: "partial" as const, reason: "timeout" as const }
@@ -4428,7 +4656,7 @@ function workflowChildResult(
4428
4656
  ? { state: "partial" as const, reason: "budget_exhausted" as const }
4429
4657
  : undefined);
4430
4658
  const acceptanceRecovery = result.details.results.find((child) => child.acceptance?.recovery)?.acceptance?.recovery;
4431
- const ok = result.isError !== true && !detached && !interrupted && !stopped && acceptanceRecovery === undefined;
4659
+ const ok = result.isError !== true && !running && !detached && !interrupted && !stopped && acceptanceRecovery === undefined;
4432
4660
  const artifactPaths = new Set<string>();
4433
4661
  if (result.details.asyncDir) artifactPaths.add(result.details.asyncDir);
4434
4662
  if (result.details.parallelHandoff?.path) artifactPaths.add(result.details.parallelHandoff.path);
@@ -4458,6 +4686,8 @@ function workflowChildResult(
4458
4686
  const resolvedContext = result.details.context ?? (resolvedContexts.length === 1 ? resolvedContexts[0] : resolvedContexts.length > 1 ? "mixed" : undefined);
4459
4687
  const outputReference = result.details.results.find((child) => child.savedOutputPath)?.savedOutputPath
4460
4688
  ?? result.details.results.find((child) => child.outputReference?.path)?.outputReference?.path;
4689
+ const outputArtifactPath = running ? undefined : result.details.parallelHandoff?.path
4690
+ ?? result.details.results.find((child) => child.artifactPaths?.outputPath)?.artifactPaths?.outputPath;
4461
4691
  const outputPathMapping = typeof childParams.task === "string" ? outputPathMappingFromTask(childParams.task, outputReference) : undefined;
4462
4692
  const externalResult = result.details.results.length === 1 && result.details.results[0]?.runner?.type === "external-cli" ? result.details.results[0] : undefined;
4463
4693
  const externalStatus = result.details.asyncDir ? readStatus(result.details.asyncDir) : undefined;
@@ -4471,12 +4701,14 @@ function workflowChildResult(
4471
4701
  return {
4472
4702
  key,
4473
4703
  ok,
4704
+ ...(running ? { state: "running" as const } : {}),
4705
+ ...(result.details.asyncDir ? { asyncDir: result.details.asyncDir } : {}),
4474
4706
  ...(lane ? { lane } : {}),
4475
4707
  ...(terminalOutcome ? { terminalOutcome } : {}),
4476
4708
  ...(resolvedAgents.length === 1 ? { agent: resolvedAgents[0] } : {}),
4477
4709
  ...(runId ? { runId } : {}),
4478
4710
  output,
4479
- ...(!ok ? { error: failureError } : {}),
4711
+ ...(!ok && !running ? { error: failureError } : {}),
4480
4712
  ...(detached ? { detached: true } : {}),
4481
4713
  ...(interrupted ? { interrupted: true } : {}),
4482
4714
  ...(stopped ? { stopped: true } : {}),
@@ -4484,6 +4716,7 @@ function workflowChildResult(
4484
4716
  ...(requestedContext ? { requestedContext } : {}),
4485
4717
  ...(resolvedContext ? { resolvedContext } : {}),
4486
4718
  ...(outputReference ? { outputReference } : {}),
4719
+ ...(outputArtifactPath ? { outputArtifactPath } : {}),
4487
4720
  ...(acceptanceRecovery ? { recovery: acceptanceRecovery } : {}),
4488
4721
  ...(outputPathMapping ? { outputPathMapping } : {}),
4489
4722
  ...(externalAdapter ? { externalAdapter } : {}),
@@ -4505,6 +4738,18 @@ function workflowChildAccountingFields(child: WorkflowScriptChildResult): { usag
4505
4738
  };
4506
4739
  }
4507
4740
 
4741
+ function workflowRunningChildrenSummary(children: WorkflowScriptChildResult[]): string {
4742
+ const running = children.filter((child) => child.state === "running");
4743
+ return running.length ? `${running.length} child ${running.length === 1 ? "run remains" : "runs remain"} running or uncollected: ${running.map((child) => `${child.key}=${child.runId}`).join(", ")}. These launch receipts contain no final child results.` : "";
4744
+ }
4745
+
4746
+ function workflowResultChildren(children: WorkflowScriptChildResult[], status: AsyncStatus, includeFailureFields: boolean) {
4747
+ return withWorkflowRevivals(DIRS.async, status.runId, children).map((child) => {
4748
+ const sessionName = status.steps?.find((step) => step.workflowKey === child.key)?.sessionName;
4749
+ return { workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(child.revival ? { revival: formatWorkflowKeyRevival(child.revival) } : {}), ...(sessionName ? { sessionName } : {}), ...workflowChildAccountingFields(child), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, ...(child.state === "running" ? { state: "running" } : { success: child.ok }), ...(child.asyncDir ? { asyncDir: child.asyncDir } : {}), ...(child.outputReference ? { outputReference: child.outputReference } : {}), ...(includeFailureFields && child.terminalOutcome ? { terminalOutcome: child.terminalOutcome } : {}), ...(child.outputPathMapping ? { outputPathMapping: child.outputPathMapping } : {}), ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(includeFailureFields && child.detached && status.state !== "complete" ? { detached: true } : {}), ...(child.outputArtifactPath || child.outputReference ? { artifactPaths: { outputPath: child.outputArtifactPath ?? child.outputReference } } : {}) };
4750
+ });
4751
+ }
4752
+
4508
4753
  function workflowOutputPathMappingSummary(children: WorkflowScriptChildResult[]): string {
4509
4754
  const mappings = children.flatMap((child) => child.outputPathMapping
4510
4755
  ? [`'${child.key}': requested ${child.outputPathMapping.requestedPath} -> saved ${child.outputPathMapping.savedPath}`]
@@ -4658,7 +4903,7 @@ function terminalWorkflowReceipt(
4658
4903
  resource?: WorkflowReceipt["resource"],
4659
4904
  argsDigest?: string,
4660
4905
  ): WorkflowReceipt {
4661
- return buildWorkflowReceipt({ workflowRunId, state, children, workflowChildren, terminalOutcome, hostSteps, resource, ...(argsDigest ? { argsDigest } : {}) });
4906
+ return buildWorkflowReceipt({ workflowRunId, state, children: withWorkflowRevivals(DIRS.async, workflowRunId, children), workflowChildren, terminalOutcome, hostSteps, resource, ...(argsDigest ? { argsDigest } : {}) });
4662
4907
  }
4663
4908
 
4664
4909
  function workflowFailureTerminalOutcome(error: unknown, _children: WorkflowScriptChildResult[], usageBudget: ReturnType<typeof usageBudgetState>): WorkflowTerminalOutcome | undefined {
@@ -4672,7 +4917,7 @@ function workflowFailureMessage(error: unknown, workflowRunId: string, children:
4672
4917
  if (children.length === 0 && text.includes(validationPrefix)) {
4673
4918
  return `Workflow '${workflowRunId}' validation failed before child launch; no children launched.${text.slice(text.indexOf(validationPrefix) + validationPrefix.length)}`;
4674
4919
  }
4675
- return text;
4920
+ return [text, workflowRunningChildrenSummary(children)].filter(Boolean).join(" ");
4676
4921
  }
4677
4922
 
4678
4923
  export async function steerWorkflowChildByKey(input: {
@@ -4889,6 +5134,15 @@ function normalizeGateParams(params: SubagentParamsLike): GateParamsNormalizatio
4889
5134
  return { ok: true, params: { ...rest, ...(normalized.acceptance !== undefined ? { acceptance: normalized.acceptance } : {}) } };
4890
5135
  }
4891
5136
 
5137
+ function describeTypedVerifyOutputSchemaConflict(effective: SubagentParamsLike, requested: SubagentParamsLike): string | undefined {
5138
+ if (!acceptanceHasTypedVerify(effective.acceptance)) return undefined;
5139
+ if (effective.outputSchema === undefined || effective.outputSchema === false) return undefined;
5140
+ const agent = effective.agent ?? "?";
5141
+ const schemaSource = requested.outputSchema !== undefined && requested.outputSchema !== false ? "outputSchema" : `agent '${agent}' outputSchema`;
5142
+ const verifySource = requested.gate !== undefined ? "gate.output" : requested.acceptance !== undefined ? "acceptance.verify" : `agent '${agent}' defaultAcceptance`;
5143
+ return `${verifySource}: ${TYPED_VERIFY_OUTPUT_SCHEMA_CONFLICT.replace("with outputSchema", `with ${schemaSource}`)}`;
5144
+ }
5145
+
4892
5146
  function formatWorkflowValue(value: unknown): string {
4893
5147
  if (value === undefined) return "(undefined)";
4894
5148
  if (typeof value === "string") return value;
@@ -5077,6 +5331,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5077
5331
  const workflowPermitContexts = new WeakMap<object, { root: WorkflowChildPermit } | { child: WorkflowChildPermitContext }>();
5078
5332
  const warnedArtifactPackageDirs = new Set<string>();
5079
5333
  const scheduledOwnerExecutors = new Map<string | null, Map<string, { state: SubagentState; executor: ReturnType<typeof createSubagentExecutor> }>>();
5334
+ const disabledFeatures = resolveDisabledFeatureSurface(deps.config);
5335
+ const disabledFeatureResult = (params: SubagentParamsLike): AgentToolResult<Details> | undefined => {
5336
+ const error = disabledFeatureUseError(params, disabledFeatures);
5337
+ if (!error) return undefined;
5338
+ return { content: [{ type: "text", text: error }], isError: true, details: { mode: params.action === undefined ? inferExecutionMode(params) : "management", results: [] } };
5339
+ };
5340
+ const admitEnabledWorkflowChildren = (calls: Array<{ key: string; params: Record<string, unknown> }>): void => {
5341
+ for (const call of calls) {
5342
+ const error = disabledFeatureUseError(call.params, disabledFeatures, `workflow child '${call.key}'`);
5343
+ if (error) throw new Error(error);
5344
+ }
5345
+ };
5080
5346
  const execute = async (
5081
5347
  _id: string,
5082
5348
  params: SubagentParamsLike,
@@ -5106,18 +5372,25 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5106
5372
  const capacityOverrideError = validateWorkflowCapacityOverrides(requestParams);
5107
5373
  if (capacityOverrideError) return buildRequestedModeError(requestParams, capacityOverrideError);
5108
5374
  let workflowPreflight: import("../../shared/types.ts").WorkflowPreflight | undefined;
5375
+ // Only workflow requests read the session here; other actions (for example doctor) must not.
5376
+ const resolveWorkflowParentModel = () => parentModelOverride !== undefined
5377
+ ? parentModelOverride
5378
+ : (() => {
5379
+ const currentParentModel = normalizeParentModel(ctx.model);
5380
+ return (preserveActiveSession
5381
+ ? currentParentModel
5382
+ : rememberParentModel(deps.state, resolveCurrentSessionId(ctx.sessionManager), currentParentModel)) ?? null;
5383
+ })();
5109
5384
  try {
5110
- if (requestParams.preflight !== undefined && requestParams.workflowScript === undefined && requestParams.workflowScriptPath === undefined) {
5111
- throw new Error("preflight requires workflowScript or workflowScriptPath.");
5385
+ if (requestParams.preflight !== undefined && requestParams.workflowScript === undefined) {
5386
+ throw new Error("preflight requires workflow: true or a workflow script path.");
5112
5387
  }
5113
5388
  workflowPreflight = normalizeWorkflowPreflight(requestParams.preflight);
5114
5389
  if (workflowPreflight) requestParams = { ...requestParams, preflight: workflowPreflight };
5115
5390
  } catch (error) {
5116
5391
  const message = error instanceof Error ? error.message : String(error);
5117
5392
  if (requestParams.action?.trim() === "validate") {
5118
- const validation = validateWorkflowScript(requestParams.workflowScript ?? "", {
5119
- maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
5120
- });
5393
+ const validation = validateWorkflowScript(requestParams.workflowScript ?? "", workflowValidationOptions(deps, requestParams, ctx.cwd, () => resolveWorkflowParentModel()?.provider));
5121
5394
  const invalidValidation = { ...validation, ok: false, errors: [...validation.errors, { message }] };
5122
5395
  return {
5123
5396
  content: [{ type: "text", text: JSON.stringify(invalidValidation) }],
@@ -5128,15 +5401,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5128
5401
  return buildRequestedModeError(requestParams, message);
5129
5402
  }
5130
5403
  if (requestParams.action?.trim() === "validate") {
5131
- const validation = validateWorkflowScript(requestParams.workflowScript ?? "", {
5132
- maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
5133
- });
5134
- const payload = workflowPreflight ? { ...validation, preflight: workflowPreflight } : validation;
5135
- return {
5136
- content: [{ type: "text", text: JSON.stringify(payload) }],
5137
- ...(validation.ok ? {} : { isError: true }),
5138
- details: { mode: "management", results: [] },
5139
- };
5404
+ const validation = validateWorkflowScript(requestParams.workflowScript ?? "", workflowValidationOptions(deps, requestParams, ctx.cwd, () => resolveWorkflowParentModel()?.provider));
5405
+ return buildWorkflowValidationResult(validation, "management", workflowPreflight);
5140
5406
  }
5141
5407
  const normalizedAction = typeof requestParams.action === "string" ? requestParams.action.trim() : requestParams.action;
5142
5408
  if (normalizedAction === "resume" && requestParams.extensionBindings !== undefined) return buildRequestedModeError(requestParams, "extensionBindings is not supported with action='resume'; resume uses the original retained child binding.");
@@ -5151,14 +5417,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5151
5417
  const workflowArgsEvidence = requestParams.args === undefined ? undefined : { args: requestParams.args, argsDigest: stableJsonDigest(requestParams.args) };
5152
5418
  const workflowArgs = workflowArgsEvidence?.args;
5153
5419
  const workflowArgsDigest = workflowArgsEvidence?.argsDigest;
5154
- const spawnBudgetValidation = validateWorkflowScript(requestParams.workflowScript, {
5155
- maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
5156
- });
5157
- const spawnBudgetErrors = spawnBudgetValidation.errors.filter((error) => error.kind === "spawn-budget");
5158
- if (spawnBudgetErrors.length > 0) {
5159
- return buildRequestedModeError(requestParams, `workflowScript validation failed before child launch; no children launched. ${spawnBudgetErrors.map((error) => error.message).join(" ")}`);
5420
+ const workflowParentModel = resolveWorkflowParentModel();
5421
+ const workflowValidation = validateWorkflowScript(requestParams.workflowScript, workflowValidationOptions(deps, requestParams, ctx.cwd, () => workflowParentModel?.provider));
5422
+ if (!workflowValidation.ok && publicExecution) return buildWorkflowValidationResult(workflowValidation, "workflow", workflowPreflight);
5423
+ const launchBlockingErrors = workflowValidation.errors.filter((error) => error.kind === "spawn-budget" || error.kind === "agent");
5424
+ if (launchBlockingErrors.length > 0) {
5425
+ return buildRequestedModeError(requestParams, `Workflow '${_id}' validation failed before child launch; no children launched. ${launchBlockingErrors.map((error) => error.message).join(" ")}`);
5426
+ }
5427
+ // A package chain's per-step stop check defeats static launch counting; runtime fan-out enforcement still applies.
5428
+ const structuredResource = workflowResource?.provenance.name === "chain" || workflowResource?.provenance.name === "tasks";
5429
+ for (const warning of workflowValidation.warnings ?? []) {
5430
+ if (!(structuredResource && warning.kind === "dynamic-spawn-count")) console.warn(`[pi-subagents] ${warning.message}`);
5160
5431
  }
5161
- for (const warning of spawnBudgetValidation.warnings ?? []) console.warn(`[pi-subagents] ${warning.message}`);
5162
5432
  const acceptanceErrors = validateAcceptanceInput(requestParams.acceptance);
5163
5433
  if (acceptanceErrors.length > 0) return buildRequestedModeError(requestParams, acceptanceErrors.join(" "));
5164
5434
  const foregroundWorkflowRunId = encodeIndexSegment(_id);
@@ -5167,14 +5437,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5167
5437
  if (permitError) return buildRequestedModeError(requestParams, permitError);
5168
5438
  if (requestParams.async !== false) return buildRequestedModeError(requestParams, "Workflow child permit supports foreground workflow roots only; set async:false.");
5169
5439
  }
5170
- const workflowParentModel = parentModelOverride !== undefined
5171
- ? parentModelOverride
5172
- : (() => {
5173
- const currentParentModel = normalizeParentModel(ctx.model);
5174
- return (preserveActiveSession
5175
- ? currentParentModel
5176
- : rememberParentModel(deps.state, resolveCurrentSessionId(ctx.sessionManager), currentParentModel)) ?? null;
5177
- })();
5178
5440
  if (requestParams.extensionBindings !== undefined) {
5179
5441
  try {
5180
5442
  requestParams.extensionBindings = normalizeExtensionBindings(requestParams.extensionBindings)!.value;
@@ -5183,6 +5445,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5183
5445
  }
5184
5446
  }
5185
5447
  const parentCwd = ctx.cwd;
5448
+ for (const [name, value] of [["timeoutMs", requestParams.timeoutMs], ["maxRuntimeMs", requestParams.maxRuntimeMs]] as const) {
5449
+ if (value === undefined) continue;
5450
+ const overflowError = timerDelayOverflowError(name, value);
5451
+ if (overflowError) return buildRequestedModeError(requestParams, overflowError);
5452
+ }
5186
5453
  const timeout = requestParams.timeoutMs ?? requestParams.maxRuntimeMs ?? (requestParams.async === false ? resolveConfigDefaultTimeoutMs(deps.config.timeoutMs) ?? DEFAULT_FOREGROUND_TIMEOUT_MS : undefined);
5187
5454
  const workflowUsageBudget = validateUsageBudgetConfig(requestParams.usageBudget ?? deps.config.usageBudget, requestParams.usageBudget ? "usageBudget" : "config.usageBudget");
5188
5455
  if (workflowUsageBudget.error) return buildRequestedModeError(requestParams, workflowUsageBudget.error);
@@ -5288,6 +5555,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5288
5555
  const workflowCapabilityCeiling = intersectSubagentCapabilityCeilings(requestParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(currentSessionId));
5289
5556
  const completionOwnerId = deps.state.completionOwnerId ?? currentCompletionOwnerId();
5290
5557
  deps.state.completionOwnerId = completionOwnerId;
5558
+ const workflowScriptSourceDigest = workflowScriptDigest(requestParams.workflowScript);
5559
+ const workflowReuseSource = findWorkflowReuseSource(DIRS.async, currentSessionId, workflowScriptSourceDigest, workflowArgsDigest);
5560
+ const workflowRunEvidence: Pick<NonNullable<AsyncStatus["workflow"]>, "args" | "argsDigest" | "scriptDigest" | "reusedFrom" | "stopCause"> = { ...workflowArgsEvidence, scriptDigest: workflowScriptSourceDigest };
5561
+ if (workflowReuseSource) workflowRunEvidence.reusedFrom = workflowReuseSource.runId;
5562
+ const workflowJournalFingerprints = new Map<string, string>();
5291
5563
  try {
5292
5564
  fs.mkdirSync(asyncDir, { recursive: true });
5293
5565
  writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
@@ -5316,9 +5588,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5316
5588
  ...(workflowSessionRoot ? { sessionRoot: workflowSessionRoot } : {}),
5317
5589
  ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}),
5318
5590
  pid: process.pid,
5591
+ ...(workflowCapabilityCeiling ? { admissionCapabilityCeiling: workflowCapabilityCeiling } : {}),
5319
5592
  steps: [],
5320
5593
  ...(workflowPreflight ? { preflight: workflowPreflight } : {}),
5321
- workflow: { trace: [], emits: [], console: [], ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}) },
5594
+ workflow: { trace: [], emits: [], console: [], ...workflowRunEvidence, ...(workflowResource ? { resource: workflowResource.provenance } : {}) },
5322
5595
  workflowChildren: workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState: "running", inventoryComplete: false }),
5323
5596
  runFanoutBudget: getRunFanoutBudgetSnapshot(workflowFanoutBudget),
5324
5597
  };
@@ -5380,10 +5653,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5380
5653
  deps.refreshResultDelivery?.();
5381
5654
  return false;
5382
5655
  };
5656
+ const pendingWorkflowChildAnnouncements = new Map<string, NonNullable<AsyncStatus["steps"]>[number]>();
5657
+ let announcePersistedWorkflowChildren = (): void => {};
5383
5658
  const runPersistence = createCapacityResilientJsonWriter({
5384
5659
  keepAlive: true,
5385
5660
  onSuccess: (filePath, payload) => {
5386
- if (filePath === statusPath) queueActiveRunIndex(payload as AsyncStatus);
5661
+ if (filePath === statusPath) {
5662
+ announcePersistedWorkflowChildren();
5663
+ queueActiveRunIndex(payload as AsyncStatus);
5664
+ }
5387
5665
  if (filePath === resultPath) settleResultPublication?.(true);
5388
5666
  },
5389
5667
  onError: (error, filePath) => {
@@ -5404,7 +5682,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5404
5682
  // terminal writes stay fail-fast on purpose: no child work is at risk by then, and
5405
5683
  // silently dropping a terminal write would leave status.json and the active-run
5406
5684
  // index pinned at "running" after the result already says complete.
5407
- const persist = (options: { tolerateStatusWriteFailure?: boolean } = {}) => {
5685
+ const persist = (options: { tolerateStatusWriteFailure?: boolean } = {}): void => {
5408
5686
  if (persistClosed) return;
5409
5687
  const liveJob = deps.state.asyncJobs.get(workflowRunId);
5410
5688
  if (liveJob && (liveJob.status === "complete" || liveJob.status === "failed") && status.state !== "complete" && status.state !== "failed") return;
@@ -5418,7 +5696,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5418
5696
  } else if (options.tolerateStatusWriteFailure) {
5419
5697
  try {
5420
5698
  runPersistence.write(statusPath, { ...status });
5421
- statusPersistenceDegraded = false;
5699
+ if (runPersistence.pendingCount() === 0) statusPersistenceDegraded = false;
5422
5700
  } catch (error) {
5423
5701
  const message = `Failed to persist async workflow state ${statusPath}: ${error instanceof Error ? error.message : String(error)}`;
5424
5702
  console.error(message, error);
@@ -5507,6 +5785,24 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5507
5785
  return { content: [{ type: "text", text: `Failed to create async workflow storage: ${error instanceof Error ? error.message : String(error)}` }], isError: true, details: { mode: "workflow", results: [] } };
5508
5786
  }
5509
5787
  appendWorkflowEvent({ type: "subagent.workflow.started", ...(workflowArgsDigest ? { argsDigest: workflowArgsDigest } : {}) });
5788
+ try {
5789
+ deps.pi.events.emit(SUBAGENT_ASYNC_STARTED_EVENT, {
5790
+ lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
5791
+ id: workflowRunId,
5792
+ asyncDir,
5793
+ cwd: workflowCwd,
5794
+ ...(workflowSessionRoot ? { sessionRoot: workflowSessionRoot } : {}),
5795
+ pid: process.pid,
5796
+ sessionId: currentSessionId ?? undefined,
5797
+ completionOwnerId,
5798
+ mode: "workflow",
5799
+ agent: "workflow",
5800
+ goal: derivedObjective.trim() ? PROMPT_REDACTED : undefined,
5801
+ ...(timeout !== undefined ? { timeoutMs: timeout, deadlineAt: startedAt + timeout } : {}),
5802
+ });
5803
+ } catch (error) {
5804
+ console.error("Failed to emit async workflow start event:", error);
5805
+ }
5510
5806
  // The runner does not execute workflow scripts: this active owner must consume its own
5511
5807
  // durable steer inbox, deliver through in-process child controls, and persist receipts.
5512
5808
  const emitWorkflowSteerEvent = (type: string, requestId: string, index?: number, extra: Record<string, unknown> = {}): void => {
@@ -5662,6 +5958,41 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5662
5958
  const childOutputClaimPaths = new Map<string, string>();
5663
5959
  const producedChildOutputPaths = new Set<string>();
5664
5960
  const workflowSteps = new Map<string, NonNullable<AsyncStatus["steps"]>[number]>();
5961
+ const announcedWorkflowChildren = new Set<string>();
5962
+ const announceWorkflowChild = (key: string, step: NonNullable<AsyncStatus["steps"]>[number]): void => {
5963
+ if (announcedWorkflowChildren.has(key)) return;
5964
+ announcedWorkflowChildren.add(key);
5965
+ const stepIndex = status.steps?.indexOf(step);
5966
+ const childEvent: SubagentChildStatusEvent = {
5967
+ type: "subagent.child-status",
5968
+ version: 1,
5969
+ runId: workflowRunId,
5970
+ childId: key,
5971
+ status: "started",
5972
+ ts: Date.now(),
5973
+ source: "async",
5974
+ asyncDir,
5975
+ ...(stepIndex !== undefined ? { stepIndex } : {}),
5976
+ agent: step.agent,
5977
+ ...(step.runId ? { childRunId: step.runId } : {}),
5978
+ workflowKey: key,
5979
+ ...(step.phase ? { phase: step.phase } : {}),
5980
+ ...(step.label ? { label: step.label } : {}),
5981
+ };
5982
+ appendWorkflowEvent({ ...childEvent });
5983
+ try {
5984
+ deps.pi.events.emit(SUBAGENT_CHILD_STATUS_EVENT, childEvent);
5985
+ } catch (error) {
5986
+ console.error("Failed to emit workflow child status event:", error);
5987
+ }
5988
+ };
5989
+ announcePersistedWorkflowChildren = () => {
5990
+ for (const [key, step] of pendingWorkflowChildAnnouncements) {
5991
+ if (!step.runId) continue;
5992
+ announceWorkflowChild(key, step);
5993
+ pendingWorkflowChildAnnouncements.delete(key);
5994
+ }
5995
+ };
5665
5996
  const runHostCommand = workflowHostCommandRunner({
5666
5997
  workflowCwd,
5667
5998
  artifactsDir: workflowArtifactsDir,
@@ -5752,6 +6083,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5752
6083
  workflowSteps.set(entry.key, step);
5753
6084
  }
5754
6085
  const projectedStep = workflowSteps.get(entry.key);
6086
+ if (entry.reused && projectedStep) projectedStep.reused = true;
5755
6087
  if (entry.state === "stopped" && projectedStep) {
5756
6088
  appendWorkflowEvent({
5757
6089
  type: "subagent.child-status",
@@ -5785,7 +6117,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5785
6117
  timeoutMs: timeout,
5786
6118
  signal: controller.signal,
5787
6119
  continueAfterAbortWhenChildrenSettled: (abortError) => {
5788
- if (abortError.message !== "Workflow stopped because the extension session was replaced or reloaded.") return false;
6120
+ if (!workflowStopCause(abortError)) return false;
5789
6121
  const activeAsyncChild = [...(deps.state.asyncJobs?.values() ?? [])].some((job) => job.parentWorkflowRunId === workflowRunId && (job.status === "queued" || job.status === "running"));
5790
6122
  const activeForegroundChild = [...deps.state.foregroundControls.values()].some((control) => control.parentWorkflowRunId === workflowRunId && (control.activeChildren?.size ?? 0) > 0);
5791
6123
  return !activeAsyncChild && !activeForegroundChild;
@@ -5797,6 +6129,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5797
6129
  ...(workflowState ? { state: workflowState } : {}),
5798
6130
  onTrace: updateTrace,
5799
6131
  onChildSettled: (notification) => {
6132
+ const journalFingerprint = workflowJournalFingerprints.get(notification.childKey);
6133
+ if (journalFingerprint) appendWorkflowChildJournal(asyncDir, { type: "settle", key: notification.childKey, fingerprint: journalFingerprint, result: notification.result });
5800
6134
  appendWorkflowEvent({
5801
6135
  type: "subagent.workflow.child_settled",
5802
6136
  childKey: notification.childKey,
@@ -5831,6 +6165,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5831
6165
  } });
5832
6166
  },
5833
6167
  admit: async (calls, admissionSignal) => {
6168
+ admitEnabledWorkflowChildren(calls);
5834
6169
  await preflightWorkflowWorktrees({ workflowDefaults: workflowChildDefaults, defaultWorktree: deps.config.worktree, calls, ctxCwd: parentCwd, signal: admissionSignal, deadlineAt: workflowDeadlineAt });
5835
6170
  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 });
5836
6171
  if (outputClaims.error) throw new Error(outputClaims.error);
@@ -5847,6 +6182,32 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5847
6182
  appendWorkflowEvent({ type: "subagent.workflow.emit", value: emits.at(-1) });
5848
6183
  },
5849
6184
  launch: async (key, childParams, workflowSignal, admission) => {
6185
+ const journalFingerprint = workflowJournalFingerprints.get(key) ?? workflowChildFingerprint(childParams);
6186
+ workflowJournalFingerprints.set(key, journalFingerprint);
6187
+ const priorChild = workflowReuseSource ? matchWorkflowReuse(workflowReuseSource, key, journalFingerprint) : undefined;
6188
+ if (priorChild?.kind === "settled") {
6189
+ if (priorChild.result.runId) workflowChildRunIds.set(key, priorChild.result.runId);
6190
+ return { ...priorChild.result, reused: true };
6191
+ }
6192
+ if (priorChild?.kind === "started") {
6193
+ // The previous run's awaited async child may still be running: wait for that exact run
6194
+ // instead of launching again. Journal it first so another reload can re-attach too.
6195
+ const priorRunId = priorChild.runId;
6196
+ const priorAsyncDir = path.join(DIRS.async, priorRunId);
6197
+ appendWorkflowChildJournal(asyncDir, { type: "start", key, fingerprint: journalFingerprint, runId: priorRunId });
6198
+ const stopListener = stopAwaitedAsyncChildOnAbort(workflowSignal, deps.state, priorRunId, priorAsyncDir, deps.kill);
6199
+ const reattached = await awaitExistingAsyncRun(priorAsyncDir, priorRunId, workflowSignal).finally(stopListener.remove);
6200
+ const claimedPath = reattached.status === "settled" ? claimWorkflowAwaitedResult(priorAsyncDir, workflowRunId) : undefined;
6201
+ if (reattached.status === "settled" && claimedPath) {
6202
+ const imported = importWorkflowAwaitedChildResult(reattached.result, { runId: priorRunId, asyncDir: priorAsyncDir, resultPath: claimedPath, task: typeof childParams.task === "string" ? childParams.task : "", parentWorkflowRunId: workflowReuseSource?.runId, details: { mode: "single", asyncId: priorRunId, asyncDir: priorAsyncDir, results: [] }, state: deps.state, pi: deps.pi });
6203
+ const reattachedResult = workflowChildResult(key, imported, childParams, deps.state);
6204
+ // Like a settled journal match: only a successful child is reused; a failed or stopped one launches fresh.
6205
+ if (reattachedResult.ok) {
6206
+ workflowChildRunIds.set(key, priorRunId);
6207
+ return { ...reattachedResult, reused: true };
6208
+ }
6209
+ }
6210
+ }
5850
6211
  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);
5851
6212
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
5852
6213
  if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state, { state: "partial", reason: "budget_exhausted" });
@@ -5865,10 +6226,13 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5865
6226
  { ...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 },
5866
6227
  missionBinding,
5867
6228
  deps.asyncByDefault,
6229
+ undefined,
6230
+ inheritedNestedRoute(deps)?.rootRunId,
5868
6231
  );
5869
6232
  preparedChildParams = childRequest;
5870
6233
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
5871
6234
  workflowLaunchObservers.set(childRequest, (launch) => {
6235
+ if (launch.runId) appendWorkflowChildJournal(asyncDir, { type: "start", key, fingerprint: journalFingerprint, runId: launch.runId });
5872
6236
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
5873
6237
  if (step) {
5874
6238
  step.agent = launch.agent;
@@ -5877,6 +6241,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5877
6241
  step.async = launch.async;
5878
6242
  if (launch.runId) step.runId = launch.runId;
5879
6243
  if (childRequest.lane) step.lane = childRequest.lane;
6244
+ if (step.runId) pendingWorkflowChildAnnouncements.set(key, step);
5880
6245
  persist({ tolerateStatusWriteFailure: true });
5881
6246
  }
5882
6247
  recordMissionWorkflowChild(missionBinding, workflowRunId, key, { status: "running", agent: launch.agent, ...(launch.sessionFile ? { sessionPath: launch.sessionFile } : {}) });
@@ -5943,15 +6308,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5943
6308
  });
5944
6309
  const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, workflow.trace, { settled: true });
5945
6310
  const finalPreflightTrace = annotateWorkflowPreflightTrace(workflow.trace, workflowPreflight);
5946
- const returnPreview = formatWorkflowValue(workflow.value).slice(0, 1_000);
5947
- const emitPreview = workflow.emits.length > 0 ? ` Emitted: ${workflow.emits.map(formatWorkflowValue).join(", ").slice(0, 1_000)}` : "";
5948
- 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(" ")}` : ""}`;
6311
+ const returnText = formatWorkflowValue(workflow.value);
6312
+ const emitText = workflow.emits.map(formatWorkflowValue).join(", ");
6313
+ const returnPreview = returnText.length > 1_000 ? `${returnText.slice(0, 1_000)}…` : returnText;
6314
+ const emitPreview = workflow.emits.length > 0 ? ` Emitted: ${emitText.length > 1_000 ? `${emitText.slice(0, 1_000)}…` : emitText}` : "";
6315
+ const previewNote = returnText.length > 1_000 || emitText.length > 1_000 ? ` (truncated; full return value and emits: ${statusPath} (workflow.value, workflow.emits))` : "";
6316
+ const runningSummary = workflowRunningChildrenSummary(workflow.children);
6317
+ const summary = `${runningSummary ? `Workflow dispatch completed; ${runningSummary}` : `Workflow completed with ${workflow.children.length} child run(s).`} Return: ${returnPreview}${emitPreview}${previewNote} Trace: ${workflow.trace.length} event(s).${workflowOutputPathMappingSummary(workflow.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
5949
6318
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, summary, producedChildOutputPaths);
5950
6319
  const resultSummary = appendWorkflowOutputWarning(summary, outputWarning);
5951
6320
  const workflowUsage = sumResultsUsage(workflowResults);
5952
6321
  settleWorkflowSteerInbox("complete");
5953
6322
  const workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children, steps: status.steps });
5954
- status = { ...status, state: "complete", endedAt: Date.now(), workflow: { value: workflow.value, trace: finalPreflightTrace, emits: workflow.emits, console: workflow.console, ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}) }, workflowChildren, totalTokens: { input: workflowUsage.input, output: workflowUsage.output, total: workflowUsage.input + workflowUsage.output }, totalCost: sumResultsCost(workflowResults) };
6323
+ status = { ...status, state: "complete", endedAt: Date.now(), workflow: { value: workflow.value, trace: finalPreflightTrace, emits: workflow.emits, console: workflow.console, ...workflowRunEvidence, ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}) }, workflowChildren, totalTokens: { input: workflowUsage.input, output: workflowUsage.output, total: workflowUsage.input + workflowUsage.output }, totalCost: sumResultsCost(workflowResults) };
5955
6324
  const receipt = terminalWorkflowReceipt(workflowRunId, "complete", workflow.children, workflowChildren, undefined, validHostStepNodes(status.workflowGraph), workflowResource?.provenance, workflowArgsDigest);
5956
6325
  delete status.workflowReceiptPath;
5957
6326
  let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
@@ -5961,7 +6330,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5961
6330
  } catch (receiptError) {
5962
6331
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
5963
6332
  }
5964
- if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary: resultSummary, output: resultSummary, workflowChildren, results: workflow.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(status.steps?.find((step) => step.workflowKey === child.key)?.sessionName ? { sessionName: status.steps?.find((step) => step.workflowKey === child.key)?.sessionName } : {}), ...workflowChildAccountingFields(child), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.outputReference ? { outputReference: child.outputReference } : {}), ...(child.outputPathMapping ? { outputPathMapping: child.outputPathMapping } : {}), ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
6333
+ if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary: resultSummary, output: resultSummary, workflowChildren, results: workflowResultChildren(workflow.children, status, false), workflow: status.workflow, ...(workflowCapabilityCeiling ? { admissionCapabilityCeiling: workflowCapabilityCeiling } : {}), ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
5965
6334
  if (pendingResultPublication && !await pendingResultPublication) return;
5966
6335
  persist();
5967
6336
  deps.refreshResultDelivery?.();
@@ -5970,8 +6339,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5970
6339
  } catch (error) {
5971
6340
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
5972
6341
  const stopped = controller.signal.aborted;
6342
+ const stopCause = stopped ? workflowStopCause(controller.signal.reason) : undefined;
6343
+ if (stopCause) workflowRunEvidence.stopCause = stopCause;
5973
6344
  const detachedChildKeys = new Set(partial.children.filter((child) => child.detached).map((child) => child.key));
5974
- const hasRealFailedChild = partial.children.some((child) => !child.ok && !child.detached);
6345
+ const hasRealFailedChild = partial.children.some((child) => !child.ok && child.state !== "running" && !child.detached);
5975
6346
  const pauseForDetached = !stopped && error instanceof WorkflowScriptError && error.errorKind === "detached-child" && detachedChildKeys.size > 0 && !hasRealFailedChild;
5976
6347
  const state = stopped ? "stopped" : pauseForDetached ? "paused" : "failed";
5977
6348
  for (const step of status.steps ?? []) {
@@ -5990,14 +6361,16 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5990
6361
  const workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState, inventoryComplete: true, trace: partial.trace, children: partial.children, steps: status.steps });
5991
6362
  const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, partial.trace, { settled: true });
5992
6363
  const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
5993
- status = compactOptional<AsyncStatus>({ ...status, state, stopped: stopped || undefined, activityState: pauseForDetached || status.activityState === "needs_attention" ? "needs_attention" : undefined, error: workflowFailureMessage(error, workflowRunId, partial.children), endedAt: Date.now(), workflow: { trace: finalPreflightTrace, emits: partial.emits, console: partial.console, ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}) }, workflowChildren });
6364
+ status = compactOptional<AsyncStatus>({ ...status, state, stopped: stopped || undefined, activityState: pauseForDetached || status.activityState === "needs_attention" ? "needs_attention" : undefined, error: workflowFailureMessage(error, workflowRunId, partial.children), endedAt: Date.now(), workflow: { trace: finalPreflightTrace, emits: partial.emits, console: partial.console, ...(error instanceof WorkflowScriptError && error.errorKind ? { failureKind: error.errorKind } : {}), ...workflowRunEvidence, ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}) }, workflowChildren });
5994
6365
  if (pauseForDetached) {
5995
6366
  const promoted = promotePausedWorkflowIfSettled(status);
5996
6367
  if (promoted) status = promoted;
5997
6368
  }
6369
+ // A script can throw an error of any size; status.json keeps the full text.
6370
+ const errorPreview = status.error && status.error.length > 1_000 ? `${status.error.slice(0, 1_000)}… (truncated; full error: ${statusPath} (error))` : status.error;
5998
6371
  const terminalSummary = `${status.state === "complete"
5999
6372
  ? "Workflow completed after detached child finished."
6000
- : status.error ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.")}${workflowOutputPathMappingSummary(partial.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
6373
+ : errorPreview ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.")}${stopCause ? ` ${WORKFLOW_RUNTIME_REPLACED_RELAUNCH_NOTICE}` : ""}${workflowOutputPathMappingSummary(partial.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
6001
6374
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, terminalSummary, producedChildOutputPaths);
6002
6375
  const resultSummary = appendWorkflowOutputWarning(terminalSummary, outputWarning);
6003
6376
  const receiptState: WorkflowReceiptState = status.state === "complete" ? "complete" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "failed";
@@ -6011,7 +6384,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6011
6384
  } catch (receiptError) {
6012
6385
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
6013
6386
  }
6014
- if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: status.state === "complete", state: status.state, summary: resultSummary, error: status.state === "complete" ? undefined : status.error, stopped: status.stopped, activityState: status.activityState, workflowChildren, ...(terminalOutcome ? { terminalOutcome } : {}), results: partial.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(status.steps?.find((step) => step.workflowKey === child.key)?.sessionName ? { sessionName: status.steps?.find((step) => step.workflowKey === child.key)?.sessionName } : {}), ...workflowChildAccountingFields(child), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.outputReference ? { outputReference: child.outputReference } : {}), ...(child.terminalOutcome ? { terminalOutcome: child.terminalOutcome } : {}), ...(child.outputPathMapping ? { outputPathMapping: child.outputPathMapping } : {}), ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(child.detached && status.state !== "complete" ? { detached: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
6387
+ 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: workflowResultChildren(partial.children, status, true), workflow: status.workflow, ...(workflowCapabilityCeiling ? { admissionCapabilityCeiling: workflowCapabilityCeiling } : {}), ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
6015
6388
  if (pendingResultPublication && !await pendingResultPublication) return;
6016
6389
  persist();
6017
6390
  deps.refreshResultDelivery?.();
@@ -6040,6 +6413,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6040
6413
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
6041
6414
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
6042
6415
  const workflowAggregateOutputPath = resolveSingleOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, foregroundWorkflowRunId));
6416
+ // A top-level artifact file: outside outputs/, where children save their reports, and
6417
+ // within artifact retention, which only removes top-level files.
6418
+ const workflowFullResultPath = path.join(workflowArtifactsDir, `${sanitizeRunPathSegment(foregroundWorkflowRunId)}_workflow-result.md`);
6043
6419
  const claimedOutputPaths = new Map<string, string>();
6044
6420
  const childOutputOverrides = new Map<string, string>();
6045
6421
  const childOutputClaimPaths = new Map<string, string>();
@@ -6100,6 +6476,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6100
6476
  sendWorkflowProgress();
6101
6477
  },
6102
6478
  admit: async (calls, admissionSignal) => {
6479
+ admitEnabledWorkflowChildren(calls);
6103
6480
  await preflightWorkflowWorktrees({ workflowDefaults: workflowChildDefaults, defaultWorktree: deps.config.worktree, calls, ctxCwd: ctx.cwd, signal: admissionSignal, deadlineAt: workflowDeadlineAt });
6104
6481
  const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId: foregroundWorkflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
6105
6482
  if (outputClaims.error) throw new Error(outputClaims.error);
@@ -6134,6 +6511,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6134
6511
  { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams: delegatedWorkflowPermit ? { ...childParams, async: false } : childParams, parentWorkflowRunId: foregroundWorkflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
6135
6512
  missionBinding,
6136
6513
  deps.asyncByDefault,
6514
+ undefined,
6515
+ inheritedNestedRoute(deps)?.rootRunId,
6137
6516
  );
6138
6517
  preparedChildParams = childRequest;
6139
6518
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
@@ -6197,21 +6576,26 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6197
6576
  const finalPreflightTrace = annotateWorkflowPreflightTrace(workflow.trace, workflowPreflight);
6198
6577
  const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children });
6199
6578
  const receipt = terminalWorkflowReceipt(foregroundWorkflowRunId, "complete", workflow.children, workflowChildren, undefined, [...workflowHostSteps.values()], workflowResource?.provenance, workflowArgsDigest);
6200
- const traceLines = finalPreflightTrace.map((entry) => `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.durationMs !== undefined ? ` in ${entry.durationMs}ms` : ""}${entry.warning ? ` — ${entry.warning}` : ""}${entry.error ? ` — ${entry.error}` : ""}`);
6201
- const sections = [
6202
- ...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []),
6203
- "Workflow completed.",
6204
- `Return:\n${formatWorkflowValue(workflow.value)}`,
6205
- ];
6206
- if (workflow.emits.length > 0) sections.push(`Emitted:\n${workflow.emits.map(formatWorkflowValue).join("\n")}`);
6207
- if (workflow.console.length > 0) sections.push(`Console:\n${workflow.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
6208
- if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
6209
- if (finalPreflightWarnings.length > 0) sections.push(formatWorkflowPreflightWarnings(finalPreflightWarnings));
6579
+ const trace = finalPreflightTrace.map((entry) => ({ line: `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.durationMs !== undefined ? ` in ${entry.durationMs}ms` : ""}${entry.warning ? ` — ${entry.warning}` : ""}`, error: entry.error }));
6580
+ const runningSummary = workflowRunningChildrenSummary(workflow.children);
6210
6581
  const outputMappings = workflowOutputPathMappingSummary(workflow.children).trim();
6211
- if (outputMappings) sections.push(outputMappings);
6212
- const workflowText = sections.join("\n\n");
6213
- const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText, producedChildOutputPaths);
6214
- const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
6582
+ const displayText = formatWorkflowResultText({
6583
+ head: [...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []), runningSummary ? `Workflow dispatch completed; ${runningSummary}` : "Workflow completed."],
6584
+ script: [
6585
+ `Return:\n${formatWorkflowValue(workflow.value)}`,
6586
+ ...(workflow.emits.length > 0 ? [`Emitted:\n${workflow.emits.map(formatWorkflowValue).join("\n")}`] : []),
6587
+ ...(workflow.console.length > 0 ? [`Console:\n${workflow.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`] : []),
6588
+ ],
6589
+ trace,
6590
+ tail: [
6591
+ ...(finalPreflightWarnings.length > 0 ? [formatWorkflowPreflightWarnings(finalPreflightWarnings)] : []),
6592
+ ...(outputMappings ? [outputMappings] : []),
6593
+ ],
6594
+ maxOutput: requestParams.maxOutput,
6595
+ aggregateOutputPath: workflowAggregateOutputPath,
6596
+ fullResultPath: workflowFullResultPath,
6597
+ producedChildOutputPaths,
6598
+ });
6215
6599
  return attachWorkflowMission(withRunFanoutBudget({
6216
6600
  content: [{ type: "text", text: displayText }],
6217
6601
  details: compactOptional<Details>({ mode: "workflow", runId: foregroundWorkflowRunId, results: workflowDetailsResults(workflow.children), ...(workflowPreflight ? { preflight: workflowPreflight } : {}), workflowChildren, totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { value: workflow.value, trace: finalPreflightTrace, emits: workflow.emits, console: workflow.console, ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}), receipt }, chatProgress }),
@@ -6221,27 +6605,32 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6221
6605
  const text = workflowFailureMessage(error, foregroundWorkflowRunId, partial.children);
6222
6606
  const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, partial.trace, { settled: true });
6223
6607
  const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
6224
- const traceLines = finalPreflightTrace.map((entry) => `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.warning ? ` — ${entry.warning}` : ""}${entry.error ? ` — ${entry.error}` : ""}`);
6225
- const sections = [
6226
- ...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []),
6227
- `Workflow failed: ${text}`,
6228
- ];
6229
- if (partial.emits.length > 0) sections.push(`Emitted:\n${partial.emits.map(formatWorkflowValue).join("\n")}`);
6230
- if (partial.console.length > 0) sections.push(`Console:\n${partial.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
6231
- if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
6232
- if (finalPreflightWarnings.length > 0) sections.push(formatWorkflowPreflightWarnings(finalPreflightWarnings));
6608
+ const trace = finalPreflightTrace.map((entry) => ({ line: `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.warning ? ` — ${entry.warning}` : ""}`, error: entry.error }));
6233
6609
  const outputMappings = workflowOutputPathMappingSummary(partial.children).trim();
6234
- if (outputMappings) sections.push(outputMappings);
6235
- const workflowText = sections.join("\n\n");
6236
- const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText, producedChildOutputPaths);
6237
- const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
6610
+ const displayText = formatWorkflowResultText({
6611
+ head: workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : [],
6612
+ script: [
6613
+ `Workflow failed: ${text}`,
6614
+ ...(partial.emits.length > 0 ? [`Emitted:\n${partial.emits.map(formatWorkflowValue).join("\n")}`] : []),
6615
+ ...(partial.console.length > 0 ? [`Console:\n${partial.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`] : []),
6616
+ ],
6617
+ trace,
6618
+ tail: [
6619
+ ...(finalPreflightWarnings.length > 0 ? [formatWorkflowPreflightWarnings(finalPreflightWarnings)] : []),
6620
+ ...(outputMappings ? [outputMappings] : []),
6621
+ ],
6622
+ maxOutput: requestParams.maxOutput,
6623
+ aggregateOutputPath: workflowAggregateOutputPath,
6624
+ fullResultPath: workflowFullResultPath,
6625
+ producedChildOutputPaths,
6626
+ });
6238
6627
  const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "failed", inventoryComplete: true, trace: partial.trace, children: partial.children });
6239
6628
  const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
6240
6629
  const receipt = terminalWorkflowReceipt(foregroundWorkflowRunId, "failed", partial.children, workflowChildren, terminalOutcome, [...workflowHostSteps.values()], workflowResource?.provenance, workflowArgsDigest);
6241
6630
  return attachWorkflowMission(withRunFanoutBudget({
6242
6631
  content: [{ type: "text", text: displayText }],
6243
6632
  isError: true,
6244
- details: compactOptional<Details>({ mode: "workflow", runId: foregroundWorkflowRunId, results: workflowDetailsResults(partial.children), ...(workflowPreflight ? { preflight: workflowPreflight } : {}), workflowChildren, totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { trace: finalPreflightTrace, emits: partial.emits, console: partial.console, ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}), receipt }, chatProgress }),
6633
+ details: compactOptional<Details>({ mode: "workflow", runId: foregroundWorkflowRunId, results: workflowDetailsResults(partial.children), ...(workflowPreflight ? { preflight: workflowPreflight } : {}), workflowChildren, totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { trace: finalPreflightTrace, emits: partial.emits, console: partial.console, ...(error instanceof WorkflowScriptError && error.errorKind ? { failureKind: error.errorKind } : {}), ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}), receipt }, chatProgress }),
6245
6634
  }, workflowFanoutBudget));
6246
6635
  } finally {
6247
6636
  workflowProgressClosed = true;
@@ -6401,7 +6790,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6401
6790
  cwd: requestCwd,
6402
6791
  ...(deps.config.missions ? { missions: deps.config.missions } : {}),
6403
6792
  ...(deps.config.authorityPolicy ? { authorityPolicy: deps.config.authorityPolicy } : {}),
6404
- plugins: createBuiltinInspectorPlugins(),
6793
+ plugins: getInspectorPlugins(deps.pi),
6405
6794
  signal,
6406
6795
  });
6407
6796
  }
@@ -6527,8 +6916,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6527
6916
  }
6528
6917
  if (action === "guide") {
6529
6918
  try {
6919
+ const guide = readSubagentGuide(paramsWithResolvedCwd.topic);
6920
+ const notice = paramsWithResolvedCwd.topic === "tool-reference" ? disabledFeatureNotice(disabledFeatures) : undefined;
6530
6921
  return {
6531
- content: [{ type: "text", text: readSubagentGuide(paramsWithResolvedCwd.topic) }],
6922
+ content: [{ type: "text", text: notice ? `${notice}\n\n${guide}` : guide }],
6532
6923
  details: { mode: "management", results: [] },
6533
6924
  };
6534
6925
  } catch (error) {
@@ -6559,7 +6950,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6559
6950
  }
6560
6951
  let orchestratorTarget: string | undefined;
6561
6952
  try {
6562
- orchestratorTarget = resolveIntercomSessionTarget(deps.pi.getSessionName(), ctx.sessionManager.getSessionId());
6953
+ orchestratorTarget = resolveIntercomSessionTarget(deps.childRuntime?.intercomSessionName ?? deps.pi.getSessionName(), ctx.sessionManager.getSessionId());
6563
6954
  } catch (error) {
6564
6955
  if (!sessionError) sessionError = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
6565
6956
  }
@@ -6635,7 +7026,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6635
7026
  return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots, abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })));
6636
7027
  }
6637
7028
  if (action === "resume") {
6638
- return resumeAsyncRun(omitUndefinedProperties({ params: paramsWithResolvedCwd, requestCwd, ctx, deps, parentModel: requestParentModel, signal }));
7029
+ return resumeAsyncRun(omitUndefinedProperties({
7030
+ params: paramsWithResolvedCwd,
7031
+ requestCwd,
7032
+ ctx,
7033
+ deps,
7034
+ parentModel: requestParentModel,
7035
+ signal,
7036
+ ...(workflowLaunchObserver ? { onLaunch: (launch: Parameters<NonNullable<typeof workflowLaunchObserver>>[0]) => {
7037
+ workflowLaunchObservers.delete(params);
7038
+ workflowLaunchObserver(launch);
7039
+ } } : {}),
7040
+ }));
6639
7041
  }
6640
7042
  if (action === "steer") {
6641
7043
  if (paramsWithResolvedCwd.mode !== undefined && resolveSteerDeliveryMode(paramsWithResolvedCwd.mode) === undefined) {
@@ -6734,7 +7136,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6734
7136
  }
6735
7137
  if (action.startsWith("schedule.")) {
6736
7138
  if (!isScheduledRunAction(action)) {
6737
- return { content: [{ type: "text", text: unknownSubagentActionMessage(action) }], isError: true, details: { mode: "management", results: [] } };
7139
+ return { content: [{ type: "text", text: unknownSubagentActionMessage(action, disabledFeatures) }], isError: true, details: { mode: "management", results: [] } };
6738
7140
  }
6739
7141
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
6740
7142
  return {
@@ -6776,47 +7178,40 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6776
7178
  }
6777
7179
  if (action === "stop") {
6778
7180
  const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
6779
- const workflowController = targetRunId ? deps.state.workflowControllers?.get(targetRunId) : undefined;
6780
- if (workflowController && targetRunId) {
6781
- const stopChild = deps.state.workflowChildStops?.get(targetRunId);
6782
- if (paramsWithResolvedCwd.childId !== undefined) {
6783
- const workflowRunId = targetRunId;
6784
- const asyncJob = deps.state.asyncJobs.get(workflowRunId);
6785
- if (!asyncJob?.asyncDir) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
6786
- const status = readStatus(asyncJob.asyncDir);
6787
- if (!status) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
6788
- const resolution = resolveAsyncStatusChild(status, paramsWithResolvedCwd.childId);
6789
- if (!resolution.ok) return { content: [{ type: "text", text: resolution.message }], isError: true, details: { mode: "management", results: [] } };
6790
- 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: [] } };
6791
- if (!stopChild) return { content: [{ type: "text", text: `Workflow ${targetRunId} child stop is unavailable in this extension runtime.` }], isError: true, details: { mode: "management", results: [] } };
6792
- 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: [] } };
6793
- try {
6794
- fs.appendFileSync(path.join(asyncJob.asyncDir, "events.jsonl"), `${JSON.stringify({
6795
- type: "subagent.child-status",
6796
- version: 1,
6797
- runId: workflowRunId,
6798
- childId: resolution.child.id,
6799
- status: "stopping",
6800
- ts: Date.now(),
6801
- reason: "subagent-action",
6802
- source: "async",
6803
- stepIndex: resolution.child.index,
6804
- agent: resolution.child.step.agent,
6805
- ...(resolution.child.step.runId ? { childRunId: resolution.child.step.runId } : {}),
6806
- ...(resolution.child.step.workflowKey ? { workflowKey: resolution.child.step.workflowKey } : {}),
6807
- ...(resolution.child.step.phase ? { phase: resolution.child.step.phase } : {}),
6808
- ...(resolution.child.step.label ? { label: resolution.child.step.label } : {}),
6809
- } satisfies SubagentChildStatusEvent)}\n`, "utf-8");
6810
- } catch (error) {
6811
- console.error(`Failed to append child status event for workflow ${workflowRunId}:`, error);
6812
- }
6813
- return { content: [{ type: "text", text: `Stop requested for child ${resolution.child.id} in async workflow ${workflowRunId}.` }], details: { mode: "management", results: [] } };
7181
+ // Whole-workflow stops reach stopAsyncRun below, which stops a live workflow in-process.
7182
+ const workflowRunId = targetRunId && paramsWithResolvedCwd.childId !== undefined ? resolveLiveWorkflowRunId(deps, targetRunId) : undefined;
7183
+ if (workflowRunId && paramsWithResolvedCwd.childId !== undefined) {
7184
+ const stopChild = deps.state.workflowChildStops?.get(workflowRunId);
7185
+ const asyncJob = deps.state.asyncJobs.get(workflowRunId);
7186
+ if (!asyncJob?.asyncDir) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
7187
+ const status = readStatus(asyncJob.asyncDir);
7188
+ if (!status) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
7189
+ const resolution = resolveAsyncStatusChild(status, paramsWithResolvedCwd.childId);
7190
+ if (!resolution.ok) return { content: [{ type: "text", text: resolution.message }], isError: true, details: { mode: "management", results: [] } };
7191
+ if (!isStoppableAsyncStatusStep(resolution.child.step)) return { content: [{ type: "text", text: `Child '${paramsWithResolvedCwd.childId}' in async run '${workflowRunId}' is ${resolution.child.step.status}; stop only supports pending or running children.` }], isError: true, details: { mode: "management", results: [] } };
7192
+ if (!stopChild) return { content: [{ type: "text", text: `Workflow ${workflowRunId} child stop is unavailable in this extension runtime.` }], isError: true, details: { mode: "management", results: [] } };
7193
+ 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: [] } };
7194
+ try {
7195
+ fs.appendFileSync(path.join(asyncJob.asyncDir, "events.jsonl"), `${JSON.stringify({
7196
+ type: "subagent.child-status",
7197
+ version: 1,
7198
+ runId: workflowRunId,
7199
+ childId: resolution.child.id,
7200
+ status: "stopping",
7201
+ ts: Date.now(),
7202
+ reason: "subagent-action",
7203
+ source: "async",
7204
+ stepIndex: resolution.child.index,
7205
+ agent: resolution.child.step.agent,
7206
+ ...(resolution.child.step.runId ? { childRunId: resolution.child.step.runId } : {}),
7207
+ ...(resolution.child.step.workflowKey ? { workflowKey: resolution.child.step.workflowKey } : {}),
7208
+ ...(resolution.child.step.phase ? { phase: resolution.child.step.phase } : {}),
7209
+ ...(resolution.child.step.label ? { label: resolution.child.step.label } : {}),
7210
+ } satisfies SubagentChildStatusEvent)}\n`, "utf-8");
7211
+ } catch (error) {
7212
+ console.error(`Failed to append child status event for workflow ${workflowRunId}:`, error);
6814
7213
  }
6815
- const asyncJob = deps.state.asyncJobs.get(targetRunId);
6816
- const status = asyncJob?.asyncDir ? readStatus(asyncJob.asyncDir) : undefined;
6817
- if (status) stopStoppableAsyncStatusChildren(status, stopChild, "Workflow stopped.");
6818
- workflowController.abort(new Error("Workflow stopped."));
6819
- return { content: [{ type: "text", text: `Stop requested for async workflow ${targetRunId}.` }], details: { mode: "management", results: [] } };
7214
+ return { content: [{ type: "text", text: `Stop requested for child ${resolution.child.id} in async workflow ${workflowRunId}.` }], details: { mode: "management", results: [] } };
6820
7215
  }
6821
7216
  let resolved: ResolvedSubagentRunId | undefined;
6822
7217
  if (paramsWithResolvedCwd.dir) {
@@ -6896,7 +7291,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6896
7291
  }
6897
7292
  if (!(SUBAGENT_ACTIONS as readonly string[]).includes(action)) {
6898
7293
  return {
6899
- content: [{ type: "text", text: unknownSubagentActionMessage(action) }],
7294
+ content: [{ type: "text", text: unknownSubagentActionMessage(action, disabledFeatures) }],
6900
7295
  isError: true,
6901
7296
  details: { mode: "management" as const, results: [] },
6902
7297
  };
@@ -6906,6 +7301,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6906
7301
  cwd: requestCwd,
6907
7302
  config: deps.config,
6908
7303
  currentSessionId: deps.state.currentSessionId ?? ctx.sessionManager.getSessionId() ?? undefined,
7304
+ discoverAgentsAll: deps.discoverAgentsAll,
6909
7305
  runtimeAgentOwner: deps.pi,
6910
7306
  onAgentsChanged: deps.onAgentsChanged,
6911
7307
  });
@@ -6964,6 +7360,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6964
7360
  }
6965
7361
  const modelScope = discovered.modelScope;
6966
7362
  effectiveParams = applySingleAgentLaunchDefaults(effectiveParams, discoveredAgents);
7363
+ // The gate shorthand, an explicit acceptance.verify list, and an agent's
7364
+ // defaultAcceptance all normalize to verify commands, and the agent's
7365
+ // frontmatter outputSchema has been merged by now, so this one check keeps
7366
+ // a run to a single structured-output source regardless of spelling.
7367
+ const typedVerifyConflict = describeTypedVerifyOutputSchemaConflict(effectiveParams, params);
7368
+ if (typedVerifyConflict) return buildRequestedModeError(effectiveParams, typedVerifyConflict);
6967
7369
  // An agent-level defaultContext is a preference, unlike an explicit request.
6968
7370
  // Prefer fork only when the parent session is persisted and has a current leaf;
6969
7371
  // otherwise use fresh immediately instead of launching a guaranteed-to-fail fork.
@@ -6977,7 +7379,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6977
7379
  if ("error" in contextPolicyResult) return buildRequestedModeError(effectiveParams, contextPolicyResult.error);
6978
7380
  const contextPolicy = contextPolicyResult;
6979
7381
  effectiveParams = contextPolicy.params;
6980
- const sessionName = resolveIntercomSessionTarget(deps.pi.getSessionName(), ctx.sessionManager.getSessionId());
7382
+ const sessionName = resolveIntercomSessionTarget(deps.childRuntime?.intercomSessionName ?? deps.pi.getSessionName(), ctx.sessionManager.getSessionId());
6981
7383
  const intercomBridge = resolveIntercomBridge({
6982
7384
  config: deps.config.intercomBridge,
6983
7385
  override: effectiveParams.intercomBridge,
@@ -6987,7 +7389,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6987
7389
  orchestratorTarget: sessionName,
6988
7390
  });
6989
7391
  const agents = applyScopedIntercomBridgeToAgents(discoveredAgents, intercomBridge, contextPolicy);
6990
- const runId = randomUUID();
6991
7392
  const inheritedNestedRouteValue = inheritedNestedRoute(deps);
6992
7393
  const nestedParentAddress = inheritedNestedRouteValue ? inheritedNestedParentAddress(deps) : undefined;
6993
7394
  const shareEnabled = effectiveParams.share === true;
@@ -7022,10 +7423,30 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7022
7423
 
7023
7424
  let forkSessionFileForIndex: (idx?: number) => string | undefined = () => undefined;
7024
7425
  let prepareForkSessionForIndex: (idx?: number) => Promise<void> = async () => {};
7426
+ // Check before pruner/session preparation, then recheck immediately before each fork
7427
+ // because the session capability ceiling can tighten while preparation awaits.
7428
+ const launchCapabilityCeiling = () => intersectSubagentCapabilityCeilings(
7429
+ intersectSubagentCapabilityCeilings(effectiveParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(requestSessionId)),
7430
+ deps.childRuntime?.capabilityCeiling,
7431
+ );
7432
+ const assertLaunchableAgentsAllowedBeforeFork = (): void => {
7433
+ if (!contextPolicy.usesFork) return;
7434
+ const ceiling = launchCapabilityCeiling();
7435
+ const launchable = hasSingle
7436
+ ? [effectiveParams.agent!]
7437
+ : hasTasks
7438
+ ? (effectiveParams.tasks ?? []).map((task) => task.agent)
7439
+ : (effectiveParams.chain ?? []).flatMap((step) => isDynamicParallelStep(step)
7440
+ && (step.expand.maxItems ?? deps.config.chain?.dynamicFanout?.maxItems ?? 0) === 0
7441
+ ? []
7442
+ : getStepAgents(step));
7443
+ for (const agent of launchable) assertAgentAllowedByCapabilityCeiling(agent, ceiling);
7444
+ };
7025
7445
  // Forked children keep their requested thinking level. Signed Anthropic thinking
7026
7446
  // blocks are stripped from the inherited transcript by the resolver (they are bound
7027
7447
  // to the parent session), which is not a reason to disable the child's own reasoning.
7028
7448
  try {
7449
+ assertLaunchableAgentsAllowedBeforeFork();
7029
7450
  const pruneSession = contextPolicy.usesFork && deps.config.forkContext?.mode === "pruned"
7030
7451
  ? await createPrunedForkSessionWriter(ctx, deps.config.forkContext, signal)
7031
7452
  : undefined;
@@ -7054,6 +7475,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7054
7475
  if (externalAgent && (!effectiveAsync || effectiveParams.foregroundOnly === true)) {
7055
7476
  return buildRequestedModeError(effectiveParams, `Agent '${externalAgent.name}' uses runner.type='${externalAgent.runner?.type}', which currently supports async/background execution only. Omit async or pass async:true; clarify and foregroundOnly are unsupported.`);
7056
7477
  }
7478
+ if (effectiveAsync && hasSingle && effectiveParams.resume === undefined && effectiveParams.worktree === true) {
7479
+ try {
7480
+ await preflightWorktreeSource(effectiveCwd, { signal });
7481
+ } catch (error) {
7482
+ return toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);
7483
+ }
7484
+ }
7485
+ const runId = randomUUID();
7057
7486
  const foregroundTimeout = resolveSingleAgentLaunchTimeout(
7058
7487
  effectiveParams,
7059
7488
  effectiveAsync,
@@ -7152,8 +7581,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7152
7581
  const childSessionFileForIndex = (idx?: number) =>
7153
7582
  path.join(sessionDirForIndex(idx), "session.jsonl");
7154
7583
  try {
7584
+ // The ceiling can change while the pruned writer is built; clarify skips preflight but
7585
+ // still branches the parent session at launch.
7586
+ assertLaunchableAgentsAllowedBeforeFork();
7155
7587
  if (!(effectiveParams.clarify === true && ctx.hasUI) || deps.config.forkContext?.mode === "pruned") {
7156
- await preflightForkSessionsForStaticTasks(effectiveParams, contextPolicy, prepareForkSessionForTask, deps.config.chain?.dynamicFanout?.maxItems);
7588
+ const prepareAllowedForkSession: PrepareForkSessionForTask = async (agent, ...rest) => {
7589
+ assertAgentAllowedByCapabilityCeiling(agent, launchCapabilityCeiling());
7590
+ await prepareForkSessionForTask(agent, ...rest);
7591
+ };
7592
+ await preflightForkSessionsForStaticTasks(effectiveParams, contextPolicy, prepareAllowedForkSession, deps.config.chain?.dynamicFanout?.maxItems);
7157
7593
  }
7158
7594
  } catch (error) {
7159
7595
  activeAsyncCapacity?.rollback();
@@ -7255,6 +7691,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7255
7691
  contextPolicy,
7256
7692
  modelScope,
7257
7693
  parentModel: requestParentModel,
7694
+ scopedModelIds: scopedModelIdsFromContext(ctx),
7258
7695
  parentSessionId: requestSessionId,
7259
7696
  parentPiSessionId: requestPiSessionId,
7260
7697
  capabilityCeiling: intersectSubagentCapabilityCeilings(effectiveParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(requestSessionId)),
@@ -7346,6 +7783,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7346
7783
  params: effectiveParams,
7347
7784
  agents,
7348
7785
  parentModel: requestParentModel,
7786
+ scopedModelIds: scopedModelIdsFromContext(ctx),
7349
7787
  availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
7350
7788
  currentProvider: requestParentModel?.provider,
7351
7789
  modelScope,
@@ -7506,28 +7944,45 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7506
7944
  onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
7507
7945
  ctx: ExtensionContext,
7508
7946
  ): Promise<AgentToolResult<Details>> => {
7509
- const normalized = normalizePublicSubagentExecution(params);
7947
+ const disabledFeatureError = disabledFeatureResult(params);
7948
+ if (disabledFeatureError) return Promise.resolve(disabledFeatureError);
7949
+ const normalized = normalizePublicSubagentExecution(params, { structuredWorkflows: disabledFeatures.features.has("workflow-scripts") });
7510
7950
  if (!normalized.ok) {
7511
7951
  return Promise.resolve({ content: [{ type: "text", text: normalized.error }], isError: true, details: { mode: normalized.mode, results: [] } });
7512
7952
  }
7513
7953
  let publicParams = normalized.params as SubagentParamsLike;
7514
- if (publicParams.workflow !== undefined) {
7515
- const resolved = resolveWorkflowResource(publicParams.workflow, publicParams.args, ctx.sessionManager.getSessionId() ?? undefined);
7516
- if (!resolved.ok) return Promise.resolve({ content: [{ type: "text", text: resolved.error }], isError: true, details: { mode: "workflow", results: [] } });
7954
+ const workflow = publicParams.workflow;
7955
+ const errorResult = (text: string): Promise<AgentToolResult<Details>> => Promise.resolve({ content: [{ type: "text", text }], isError: true, details: { mode: publicParams.action ? "management" : "workflow", results: [] } });
7956
+ // Models tend to put script text in the workflow string; say how to pass it instead.
7957
+ const scriptTextHint = " A workflow string is a named workflow resource or a script file path. To run script text, write it in one ```js workflow block in the same reply and call subagent({ workflow: true }).";
7958
+ if (publicParams.tasks !== undefined || publicParams.chain !== undefined) {
7959
+ // Normalization admits chain/tasks only with workflow scripts disabled; the original input was checked above.
7960
+ const kind = publicParams.tasks !== undefined ? "tasks" : "chain";
7961
+ const resolved = resolveStructuredWorkflowResource({ kind, steps: publicParams[kind], task: publicParams.task });
7962
+ if (!resolved.ok) return errorResult(resolved.error);
7963
+ const { tasks: _tasks, chain: _chain, task: _task, ...withoutStructuredInput } = publicParams;
7964
+ publicParams = { ...withoutStructuredInput, workflowScript: resolved.resource.script };
7965
+ workflowResourcePermits.set(publicParams, resolved.resource.permit);
7966
+ } else if (typeof workflow === "string" && !isWorkflowScriptPath(workflow)) {
7967
+ const resolved = resolveWorkflowResource(workflow, publicParams.args, ctx.sessionManager.getSessionId() ?? undefined);
7968
+ if (!resolved.ok) return Promise.resolve({ content: [{ type: "text", text: resolved.error + scriptTextHint }], isError: true, details: { mode: "workflow", results: [] } });
7517
7969
  const { workflow: _workflow, args: _args, ...withoutResourceInput } = publicParams;
7518
7970
  publicParams = { ...withoutResourceInput, workflowScript: resolved.resource.script };
7519
7971
  workflowResourcePermits.set(publicParams, resolved.resource.permit);
7520
- } else if (publicParams.workflowScript !== undefined || publicParams.workflowScriptPath !== undefined) {
7972
+ } else if (workflow !== undefined || publicParams.workflowScript !== undefined) {
7521
7973
  const normalizedArgs = normalizeWorkflowArgs(publicParams.args);
7522
- if ("error" in normalizedArgs) return Promise.resolve({ content: [{ type: "text", text: normalizedArgs.error }], isError: true, details: { mode: publicParams.action ? "management" : "workflow", results: [] } });
7523
- publicParams = { ...publicParams, args: deepFreezeWorkflowArgs(normalizedArgs.args) };
7524
- }
7525
- const loaded = loadWorkflowScriptPath(publicParams, ctx.cwd);
7526
- if (loaded.error) {
7527
- return Promise.resolve({ content: [{ type: "text", text: loaded.error }], isError: true, details: { mode: publicParams.action ? "management" : "workflow", results: [] } });
7974
+ if ("error" in normalizedArgs) return errorResult(normalizedArgs.error);
7975
+ let workflowScript = publicParams.workflowScript;
7976
+ if (workflow !== undefined) {
7977
+ const source = workflow === true ? readReplyWorkflowScript(ctx.sessionManager, id) : readWorkflowScriptFile(workflow, publicParams.cwd, ctx.cwd);
7978
+ if ("error" in source) return errorResult(workflow === true ? source.error : source.error + scriptTextHint);
7979
+ workflowScript = source.script;
7980
+ }
7981
+ const { workflow: _workflow, ...withoutWorkflowSource } = publicParams;
7982
+ publicParams = { ...withoutWorkflowSource, workflowScript, args: deepFreezeWorkflowArgs(normalizedArgs.args) };
7528
7983
  }
7529
- publicExecutions.add(loaded.params!);
7530
- return executeWithSingleDispatchGuard(id, loaded.params!, signal, onUpdate, ctx);
7984
+ publicExecutions.add(publicParams);
7985
+ return executeWithSingleDispatchGuard(id, publicParams, signal, onUpdate, ctx);
7531
7986
  };
7532
7987
 
7533
7988
  const executeDelegated = async (
@@ -7537,6 +7992,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7537
7992
  onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
7538
7993
  ctx: ExtensionContext,
7539
7994
  ): Promise<AgentToolResult<Details>> => {
7995
+ const disabledFeatureError = disabledFeatureResult(params);
7996
+ if (disabledFeatureError) return disabledFeatureError;
7540
7997
  const delegatedParams = { ...params };
7541
7998
  const privateParams = delegatedParams as SubagentParamsLike & {
7542
7999
  delegatedThinkingOverride?: AgentConfig["thinking"];