@xzzpig/pi-subagents 0.18.0 → 0.20.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 (108) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/README.md +1 -1
  3. package/docs/agents.md +32 -16
  4. package/docs/configuration.md +76 -9
  5. package/docs/extension-api.md +6 -5
  6. package/docs/missions.md +28 -14
  7. package/docs/models.md +8 -4
  8. package/docs/observability.md +10 -5
  9. package/docs/standalone-background.md +1 -1
  10. package/docs/tool-reference.md +90 -88
  11. package/docs/workflows.md +171 -173
  12. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  13. package/package.json +6 -6
  14. package/prompts/review-loop.md +1 -1
  15. package/skills/council-mode/SKILL.md +1 -1
  16. package/skills/pi-subagents/SKILL.md +12 -5
  17. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -3
  18. package/skills/pi-subagents/references/execution-controls.md +68 -67
  19. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  20. package/skills/pi-subagents/references/multi-lane-orchestration.md +1 -1
  21. package/skills/pi-subagents/references/prompting-and-roles.md +45 -48
  22. package/src/agents/advertised-agent-prompt.ts +21 -41
  23. package/src/agents/agent-management.ts +2 -2
  24. package/src/agents/agents.ts +66 -3
  25. package/src/api/preflight.ts +109 -63
  26. package/src/extension/config.ts +15 -4
  27. package/src/extension/control-notices.ts +3 -0
  28. package/src/extension/doctor.ts +1 -0
  29. package/src/extension/fanout-child.ts +12 -3
  30. package/src/extension/herdr-pi-bridge.ts +2 -0
  31. package/src/extension/index.ts +90 -174
  32. package/src/extension/public-execution.ts +72 -35
  33. package/src/extension/reply-workflow-script.ts +58 -0
  34. package/src/extension/rpc.ts +29 -10
  35. package/src/extension/schemas.ts +40 -135
  36. package/src/extension/tool-activation.ts +57 -108
  37. package/src/extension/tool-description.ts +62 -27
  38. package/src/extension/upgrade-notice.ts +40 -0
  39. package/src/integrations/herdr-status.ts +19 -3
  40. package/src/intercom/native-supervisor-channel.ts +4 -1
  41. package/src/missions/goal-driver.ts +44 -31
  42. package/src/missions/store.ts +10 -1
  43. package/src/profiles/profiles.ts +5 -2
  44. package/src/runs/background/async-execution.ts +146 -59
  45. package/src/runs/background/async-job-tracker.ts +66 -24
  46. package/src/runs/background/async-retention.ts +46 -16
  47. package/src/runs/background/await-async-run.ts +78 -0
  48. package/src/runs/background/chain-root-attachment.ts +4 -4
  49. package/src/runs/background/control-channel.ts +61 -2
  50. package/src/runs/background/notify.ts +5 -0
  51. package/src/runs/background/run-child-session.ts +17 -7
  52. package/src/runs/background/run-status.ts +6 -0
  53. package/src/runs/background/runner-aliases.ts +37 -6
  54. package/src/runs/background/runner-child-launch.ts +3 -0
  55. package/src/runs/background/scheduled-runs.ts +33 -18
  56. package/src/runs/background/stale-run-reconciler.ts +13 -2
  57. package/src/runs/background/subagent-runner.ts +58 -5
  58. package/src/runs/foreground/async-stop-action.ts +17 -3
  59. package/src/runs/foreground/command-action.ts +41 -0
  60. package/src/runs/foreground/execution.ts +145 -131
  61. package/src/runs/foreground/subagent-executor.ts +546 -296
  62. package/src/runs/shared/async-status-projection.ts +5 -0
  63. package/src/runs/shared/child-commands.ts +228 -0
  64. package/src/runs/shared/child-launch.ts +15 -2
  65. package/src/runs/shared/child-session.ts +184 -24
  66. package/src/runs/shared/child-tool-plan.ts +16 -4
  67. package/src/runs/shared/claude-code-adapter.ts +157 -2
  68. package/src/runs/shared/dynamic-fanout.ts +2 -2
  69. package/src/runs/shared/external-cli-preflight.ts +54 -6
  70. package/src/runs/shared/external-cli-runner.ts +5 -1
  71. package/src/runs/shared/mcp-config-sources.ts +2 -1
  72. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -11
  73. package/src/runs/shared/model-resolution.ts +38 -10
  74. package/src/runs/shared/model-scope.ts +28 -9
  75. package/src/runs/shared/nested-events.ts +55 -55
  76. package/src/runs/shared/parallel-utils.ts +4 -0
  77. package/src/runs/shared/pi-spawn.ts +7 -95
  78. package/src/runs/shared/run-history.ts +87 -0
  79. package/src/runs/shared/subagent-control.ts +32 -17
  80. package/src/runs/shared/subagent-prompt-runtime.ts +14 -6
  81. package/src/runs/shared/worktree.ts +1 -1
  82. package/src/shared/disabled-features.ts +123 -0
  83. package/src/shared/extension-context.ts +13 -0
  84. package/src/shared/model-info.ts +9 -0
  85. package/src/shared/required-child-extensions.ts +39 -5
  86. package/src/shared/settings.ts +1 -1
  87. package/src/shared/types.ts +27 -1
  88. package/src/slash/prompt-template-bridge.ts +2 -2
  89. package/src/slash/slash-commands.ts +10 -5
  90. package/src/slash/subagent-cost.ts +9 -5
  91. package/src/slash/subagents-admin.ts +24 -24
  92. package/src/tui/fleet-status.ts +14 -6
  93. package/src/tui/fleet.ts +14 -2
  94. package/src/tui/render.ts +117 -56
  95. package/src/tui/running-tone.ts +28 -0
  96. package/src/watchdog/diff-tool.ts +23 -9
  97. package/src/watchdog/register-child.ts +3 -3
  98. package/src/watchdog/register-main.ts +3 -3
  99. package/src/watchdog/review.ts +2 -2
  100. package/src/watchdog/turn-delta.ts +1 -1
  101. package/src/workflows/chat-progress.ts +2 -2
  102. package/src/workflows/scripted-workflow.ts +117 -37
  103. package/src/workflows/structured-workflow-scripts.ts +177 -0
  104. package/src/workflows/workflow-checklist.ts +6 -0
  105. package/src/workflows/workflow-receipt.ts +10 -4
  106. package/src/workflows/workflow-resources.ts +44 -16
  107. package/src/workflows/workflow-reuse.ts +120 -0
  108. package/src/workflows/workflow-revival.ts +123 -0
@@ -23,13 +23,16 @@ 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";
30
+ import { commandAction } from "./command-action.ts";
28
31
  import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/tool-actions.ts";
29
32
  import type { MainWatchdogRuntime } from "../../watchdog/runtime.ts";
30
33
  import { applyWatchdogLaunchRules } from "../../watchdog/rules.ts";
31
34
  import { childWatchdogProgressForModel } from "../../watchdog/child-status.ts";
32
- import { normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, resolveModelSelection, type ModelOrigin, type ParentModel } from "../shared/model-resolution.ts";
35
+ import { normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, resolveModelSelection, scopedModelIdsFromContext, type ModelOrigin, type ParentModel } from "../shared/model-resolution.ts";
33
36
  import { getHostBuiltinToolNames } from "../shared/child-tool-plan.ts";
34
37
  import { projectScopedProfileTrustError } from "../shared/sandbox-profile-guard.ts";
35
38
  import { projectChainOutputSchemas, resolveEffectiveOutputSchema } from "../shared/child-launch-plan.ts";
@@ -67,12 +70,13 @@ import { formatControlIntercomMessage, formatControlNoticeMessage, resolveContro
67
70
  import { formatSpawnBudget, getSpawnBudgetSnapshot, grantSpawnBudget, preflightSpawnBudget, preflightSpawnBudgetGrant, reserveSpawnBudget } from "../shared/spawn-budget.ts";
68
71
  import { claimRunFanoutBatch, claimRunFanoutBatchWithCommit, createRunFanoutBudget, formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor, RunFanoutLimitError, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
69
72
  import { retainLiveForegroundNestedRoute } from "../../integrations/pi-web-session-liveness.ts";
73
+ import { HERDR_FOREGROUND_CONTROL_CHANGED_EVENT } from "../../integrations/herdr-status.ts";
70
74
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
71
75
  import { usageBudgetExceededMessage, usageBudgetState, validateUsageBudgetConfig } from "../shared/usage-budget.ts";
72
76
  import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
73
77
  import { isAgentContract } from "../shared/agent-contract.ts";
74
78
  import { normalizeExtensionBindings, type ExtensionBindings } from "../shared/extension-bindings.ts";
75
- import { resolveRequiredChildExtensions } from "../../shared/required-child-extensions.ts";
79
+ import { assertRequiredChildExtensionsAdmitted, hasMandatoryRequiredChildExtensions, readRetainedRequiredChildExtensions, resolveRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
76
80
  import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, outputPathMappingFromTask, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
77
81
  import { assertJsonSchemaObject, cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
78
82
  import { compactForegroundDetails, getSingleResultOutput, PROMPT_REDACTED, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage, toAgentToolUsage } from "../../shared/utils.ts";
@@ -100,12 +104,13 @@ import { dismissRecoveredWorkflow } from "./async-dismiss-action.ts";
100
104
  import { promotePausedWorkflowIfSettled, reconcileDetachedWorkflowChildCompletion } from "./workflow-detach-reconcile.ts";
101
105
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
102
106
  import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
107
+ import { awaitExistingAsyncRun, claimWorkflowAwaitedResult } from "../background/await-async-run.ts";
103
108
  import { fallbackResultPayloadPathForSessionRun, removeResultIndex, resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
104
109
  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
110
  import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
106
111
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
107
112
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
108
- import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, stopStoppableAsyncStatusChildren } from "../shared/child-identity.ts";
113
+ import { isStoppableAsyncStatusStep, resolveAsyncStatusChild } from "../shared/child-identity.ts";
109
114
  import { inspectSubagentStatus } from "../background/run-status.ts";
110
115
  import { getExternalJobProvider } from "../../api/external-job-provider.ts";
111
116
  import { externalJobFollowUpRequestDigest, externalJobFollowUpRequestId, externalJobFollowUpRunId, externalJobPromptDigest, externalJobStableJson } from "../shared/external-job-runner.ts";
@@ -123,8 +128,10 @@ import { getInspectorPlugins } from "../../inspectors/plugins.ts";
123
128
  import { handleHerdrProjectPaneAction, HERDR_PROJECT_PANE_ACTIONS } from "../../inspectors/herdr/project-panes.ts";
124
129
  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
130
  import { formatIncrementalChildCompletion, incrementalChildCompletionTriggersTurn } from "../background/notify.ts";
131
+ import { appendWorkflowChildJournal, findWorkflowReuseSource, matchWorkflowReuse, workflowChildFingerprint, workflowScriptDigest, workflowStopCause, WORKFLOW_RUNTIME_REPLACED_RELAUNCH_NOTICE } from "../../workflows/workflow-reuse.ts";
126
132
  import { executeWorkflowHostCommand, resolveWorkflowHostOutputClaimPath, type WorkflowHostCommandParams, type WorkflowHostCommandResult } from "../../workflows/host-command.ts";
127
133
  import { buildWorkflowReceipt, readWorkflowReceipt, workflowReceiptPath, resolveWorkflowReceiptResumeEntry, writeWorkflowReceipt, type WorkflowReceipt, type WorkflowReceiptState } from "../../workflows/workflow-receipt.ts";
134
+ import { formatWorkflowKeyRevival, recordWorkflowRevival, withWorkflowRevivals } from "../../workflows/workflow-revival.ts";
128
135
  import { upsertHostStep, validHostStepNodes } from "../shared/host-step-status.ts";
129
136
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
130
137
  import { parseWorkflowChildSummary, workflowChildProgress, workflowChildSummary } from "../../workflows/workflow-child-summary.ts";
@@ -140,7 +147,7 @@ import {
140
147
  type WorkflowResourceAuthority,
141
148
  type WorkflowResourcePermit,
142
149
  } from "../../shared/workflow-child-permit.ts";
143
- import { deepFreezeWorkflowArgs, normalizeWorkflowArgs, resolveWorkflowResource } from "../../workflows/workflow-resources.ts";
150
+ import { deepFreezeWorkflowArgs, normalizeWorkflowArgs, resolveStructuredWorkflowResource, resolveWorkflowResource } from "../../workflows/workflow-resources.ts";
144
151
  import { stableJsonDigest } from "../../shared/launch-contract.ts";
145
152
  import {
146
153
  cleanupWorktrees,
@@ -196,6 +203,7 @@ import {
196
203
  type SubagentState,
197
204
  DIRS,
198
205
  DEFAULT_ARTIFACT_CONFIG,
206
+ DEFAULT_MAX_OUTPUT,
199
207
  DEFAULT_FORK_PREAMBLE,
200
208
  SUBAGENT_ACTIONS,
201
209
  SUBAGENT_ASYNC_STARTED_EVENT,
@@ -208,14 +216,15 @@ import {
208
216
  resolveChildMaxSubagentDepth,
209
217
  resolveCurrentMaxSubagentDepth,
210
218
  resolveMaxSubagentSpawnsPerRun,
219
+ truncateOutput,
211
220
  wrapForkTask,
212
221
  type ScheduleOrigin,
213
222
  type SteeringTargetState,
214
223
  } from "../../shared/types.ts";
215
224
  import { deriveChildSessionName } from "../../shared/child-session-name.ts";
216
225
 
217
- const MUTATING_MANAGEMENT_ACTIONS = new Set(["create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "worktree.cleanup", "lane.recordMerge", "lane.recordSupersession", "refine", "refine.rollback", "dismiss", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
218
- const DESTRUCTIVE_MANAGEMENT_ACTIONS = new Set(["delete", "eject", "disable", "reset", "mission.close", "worktree.discard", "refine.rollback", "inspector.close", "project.close", "stop", "interrupt", "schedule.delete"]);
226
+ const MUTATING_MANAGEMENT_ACTIONS = new Set(["command.yield", "command.cancel", "create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "worktree.cleanup", "lane.recordMerge", "lane.recordSupersession", "refine", "refine.rollback", "dismiss", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
227
+ const DESTRUCTIVE_MANAGEMENT_ACTIONS = new Set(["command.cancel", "delete", "eject", "disable", "reset", "mission.close", "worktree.discard", "refine.rollback", "inspector.close", "project.close", "stop", "interrupt", "schedule.delete"]);
219
228
 
220
229
  function resolveSteerDeliveryMode(mode: SubagentParamsLike["mode"]): SteerDeliveryMode | undefined {
221
230
  return mode === "steer" || mode === "follow_up" || mode === "auto" ? mode : undefined;
@@ -246,16 +255,17 @@ function hasSingleAdjacentTransposition(left: string, right: string): boolean {
246
255
  && left.slice(mismatch + 2) === right.slice(mismatch + 2);
247
256
  }
248
257
 
249
- export function unknownSubagentActionMessage(action: string): string {
258
+ export function unknownSubagentActionMessage(action: string, disabled?: DisabledFeatureSurface): string {
250
259
  const requested = action.toLowerCase();
251
- const suggestion = SUBAGENT_ACTIONS.find((candidate) => {
260
+ const enabledActions = SUBAGENT_ACTIONS.filter((candidate) => !disabled?.actions.has(candidate));
261
+ const suggestion = enabledActions.find((candidate) => {
252
262
  const distance = editDistance(requested, candidate);
253
263
  const closeMatch = distance <= Math.max(1, Math.floor(candidate.length / 4)) || hasSingleAdjacentTransposition(requested, candidate);
254
264
  if (DESTRUCTIVE_MANAGEMENT_ACTIONS.has(candidate)) return distance === 1 && requested.length >= candidate.length - 1;
255
265
  return closeMatch;
256
266
  });
257
267
  const nextStep = 'Use subagent({ action: "status" }) to inspect runs or subagent({ action: "list" }) to inspect agents.';
258
- const validActions = `Valid: ${SUBAGENT_ACTIONS.join(", ")}.`;
268
+ const validActions = `Valid: ${enabledActions.join(", ")}.`;
259
269
  return suggestion
260
270
  ? `Unknown action: ${action}. Did you mean ${suggestion}? ${nextStep} ${validActions}`
261
271
  : `Unknown action: ${action}. ${nextStep} ${validActions}`;
@@ -321,6 +331,7 @@ export interface SubagentParamsLike {
321
331
  merge?: unknown;
322
332
  supersession?: unknown;
323
333
  index?: number;
334
+ toolCallId?: string;
324
335
  childId?: string;
325
336
  view?: "fleet" | "transcript";
326
337
  lines?: number;
@@ -340,8 +351,8 @@ export interface SubagentParamsLike {
340
351
  mode?: SteerDeliveryMode | "plan" | "apply";
341
352
  repo?: string;
342
353
  planId?: string;
354
+ /** Internal script carrier (slash, prompt-workflow, scheduled, RPC, named resources). The model-facing tool rejects it. */
343
355
  workflowScript?: string;
344
- workflowScriptPath?: string;
345
356
  globalConcurrencyLimit?: number;
346
357
  maxSubagentSpawnsPerRun?: number;
347
358
  preflight?: import("../../shared/types.ts").WorkflowPreflight;
@@ -367,7 +378,7 @@ export interface SubagentParamsLike {
367
378
  runFanoutAdmitted?: boolean;
368
379
  /** Internal inherited tool/agent ceiling for delegated child launches. */
369
380
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
370
- /** Internal durable-run compatibility fields. Public callers must use workflowScript. */
381
+ /** Internal durable-run compatibility fields. Public callers must use workflow. */
371
382
  chain?: ChainStep[];
372
383
  tasks?: TaskParam[];
373
384
  concurrency?: number;
@@ -403,8 +414,8 @@ export interface SubagentParamsLike {
403
414
  modelOrigin?: ModelOrigin;
404
415
  fast?: boolean;
405
416
  thinking?: string | false;
406
- /** Public named workflow resource. Resolved before entering the workflow sandbox. */
407
- workflow?: string;
417
+ /** true = the ```js workflow block in the calling reply; a string containing "/" or "\" = script path; otherwise a named workflow resource. */
418
+ workflow?: string | true;
408
419
  args?: Record<string, unknown>;
409
420
  scope?: string;
410
421
  target?: string;
@@ -526,11 +537,14 @@ interface ExecutionContextData {
526
537
  usageBudget?: UsageBudgetConfig;
527
538
  /** Parent workflow owns this allowance; presence vetoes unverifiable child continuation. */
528
539
  inheritedUsageBudget?: UsageBudgetConfig;
540
+ /** Mandatory host extensions retained by a parent workflow; they outlive a later registration disposal. */
541
+ requiredExtensions?: RequiredChildExtensionSnapshot;
529
542
  allowZeroToolBudget?: boolean;
530
543
  configToolBudget?: ResolvedToolBudget;
531
544
  contextPolicy: AgentDefaultContextPolicy;
532
545
  modelScope?: ModelScopeConfig;
533
546
  parentModel?: ParentModel;
547
+ scopedModelIds?: string[];
534
548
  parentSessionId: string | null;
535
549
  parentPiSessionId?: string;
536
550
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
@@ -544,50 +558,48 @@ function resolveRequestedCwd(runtimeCwd: string, requestedCwd: string | undefine
544
558
  return requestedCwd ? path.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
545
559
  }
546
560
 
547
- function loadWorkflowScriptPath(params: SubagentParamsLike, runtimeCwd: string): { params?: SubagentParamsLike; error?: string } {
548
- if (params.workflowScriptPath === undefined) return { params };
549
- const scriptPath = path.resolve(resolveRequestedCwd(runtimeCwd, params.cwd), params.workflowScriptPath);
550
- let workflowScript: string;
561
+ function readWorkflowScriptFile(requestedPath: string, requestedCwd: string | undefined, runtimeCwd: string): { script: string } | { error: string } {
562
+ const scriptPath = path.resolve(resolveRequestedCwd(runtimeCwd, requestedCwd), requestedPath);
563
+ let script: string;
551
564
  try {
552
- workflowScript = fs.readFileSync(scriptPath, "utf8");
565
+ script = fs.readFileSync(scriptPath, "utf8");
553
566
  } catch (error) {
554
- return { error: `Failed to read workflowScriptPath '${scriptPath}': ${error instanceof Error ? error.message : String(error)}` };
567
+ return { error: `Failed to read workflow script '${scriptPath}': ${error instanceof Error ? error.message : String(error)}` };
555
568
  }
556
- if (!workflowScript.trim()) return { error: `workflowScriptPath file '${scriptPath}' is empty.` };
557
- const { workflowScriptPath: _workflowScriptPath, ...rest } = params;
558
- return { params: { ...rest, workflowScript } };
569
+ if (!script.trim()) return { error: `Workflow script file '${scriptPath}' is empty.` };
570
+ return { script };
559
571
  }
560
572
 
561
573
  function currentProjectTrusted(ctx: Pick<ExtensionContext, "isProjectTrusted">): boolean {
562
- return ctx.isProjectTrusted?.() === true;
574
+ return ctx.isProjectTrusted?.() === true;
563
575
  }
564
576
 
565
577
  function trustedProjectCwd(ctx: ExtensionContext): string | undefined {
566
- return currentProjectTrusted(ctx) ? path.resolve(ctx.cwd) : undefined;
578
+ return currentProjectTrusted(ctx) ? path.resolve(ctx.cwd) : undefined;
567
579
  }
568
580
 
569
581
  function sandboxProfileTrustError(agent: AgentConfig, ctx: ExtensionContext, childCwd: string): string | undefined {
570
- return projectScopedProfileTrustError({
571
- kind: "sandbox",
572
- agentName: agent.name,
573
- profileName: agent.sandbox ?? "",
574
- projectScoped: Boolean(agent.sandbox) && (agent.source === "project" || agent.override?.scope === "project"),
575
- trustedCwd: trustedProjectCwd(ctx),
576
- effectiveCwd: path.resolve(childCwd),
577
- messageStyle: "executor",
578
- });
582
+ return projectScopedProfileTrustError({
583
+ kind: "sandbox",
584
+ agentName: agent.name,
585
+ profileName: agent.sandbox ?? "",
586
+ projectScoped: Boolean(agent.sandbox) && (agent.source === "project" || agent.override?.scope === "project"),
587
+ trustedCwd: trustedProjectCwd(ctx),
588
+ effectiveCwd: path.resolve(childCwd),
589
+ messageStyle: "executor",
590
+ });
579
591
  }
580
592
 
581
593
  function permissionProfileTrustError(agent: AgentConfig, ctx: ExtensionContext, childCwd: string): string | undefined {
582
- return projectScopedProfileTrustError({
583
- kind: "permission",
584
- agentName: agent.name,
585
- profileName: agent.permissionProfile ?? "",
586
- projectScoped: Boolean(agent.permissionProfile) && (agent.source === "project" || agent.override?.scope === "project"),
587
- trustedCwd: trustedProjectCwd(ctx),
588
- effectiveCwd: path.resolve(childCwd),
589
- messageStyle: "executor",
590
- });
594
+ return projectScopedProfileTrustError({
595
+ kind: "permission",
596
+ agentName: agent.name,
597
+ profileName: agent.permissionProfile ?? "",
598
+ projectScoped: Boolean(agent.permissionProfile) && (agent.source === "project" || agent.override?.scope === "project"),
599
+ trustedCwd: trustedProjectCwd(ctx),
600
+ effectiveCwd: path.resolve(childCwd),
601
+ messageStyle: "executor",
602
+ });
591
603
  }
592
604
 
593
605
  export function removeForegroundControlIfIdle(state: SubagentState, runId: string, trackRetainedNestedRoute?: (rootRunId: string) => void): boolean {
@@ -668,6 +680,11 @@ function trustedSessionRootsForStatus(ctx: ExtensionContext, deps: ExecutorDeps)
668
680
  return [...new Set(roots)];
669
681
  }
670
682
 
683
+ /** Children follow the launching session's trust; hosts older than Pi's trust concept keep Pi's default. */
684
+ function sessionProjectTrust(ctx: ExtensionContext): boolean | undefined {
685
+ return typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : undefined;
686
+ }
687
+
671
688
  function spawnBudgetErrorResult(message: string, mode: "single" | "parallel" | "chain"): AgentToolResult<Details> {
672
689
  return {
673
690
  content: [{ type: "text", text: message }],
@@ -846,8 +863,8 @@ function rememberForegroundRun(state: SubagentState, input: { modelResponseAlias
846
863
  ...(result.detachedReason ? { detachedReason: result.detachedReason } : {}),
847
864
  ...(result.acceptance ? { acceptance: result.acceptance } : {}),
848
865
  ...(Object.keys(resumeContract).length ? { resumeContract } : {}),
849
- ...(result.sandbox ? { sandbox: result.sandbox } : {}),
850
- ...(result.permissionProfile ? { permissionProfile: result.permissionProfile } : {}),
866
+ ...(result.sandbox ? { sandbox: result.sandbox } : {}),
867
+ ...(result.permissionProfile ? { permissionProfile: result.permissionProfile } : {}),
851
868
  ...(result.launchContractDigest ? { launchContractDigest: result.launchContractDigest } : {}),
852
869
  ...(input.extensionBindings ? { extensionBindings: input.extensionBindings } : {}),
853
870
  ...(input.requiredExtensions?.length ? { requiredExtensions: input.requiredExtensions } : {}),
@@ -930,8 +947,8 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
930
947
  ...(input.result.transcriptError ? { transcriptError: input.result.transcriptError } : {}),
931
948
  ...(input.result.detachedReason ? { detachedReason: input.result.detachedReason } : {}),
932
949
  ...(input.result.acceptance ? { acceptance: input.result.acceptance } : {}),
933
- ...(input.result.sandbox ? { sandbox: input.result.sandbox } : {}),
934
- ...(input.result.permissionProfile ? { permissionProfile: input.result.permissionProfile } : {}),
950
+ ...(input.result.sandbox ? { sandbox: input.result.sandbox } : {}),
951
+ ...(input.result.permissionProfile ? { permissionProfile: input.result.permissionProfile } : {}),
935
952
  ...(input.result.launchContractDigest ? { launchContractDigest: input.result.launchContractDigest } : {}),
936
953
  ...(input.result.launchResolvedExtensions ? { launchResolvedExtensions: input.result.launchResolvedExtensions } : {}),
937
954
  ...(input.result.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: input.result.runtimeAcknowledgedExtensions } : {}),
@@ -1001,8 +1018,8 @@ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: Subage
1001
1018
  sessionFile,
1002
1019
  ...(child.model ? { model: child.model } : {}),
1003
1020
  ...(child.thinking ? { thinking: child.thinking } : {}),
1004
- ...(child.sandbox ? { sandbox: child.sandbox } : {}),
1005
- ...(child.permissionProfile ? { permissionProfile: child.permissionProfile } : {}),
1021
+ ...(child.sandbox ? { sandbox: child.sandbox } : {}),
1022
+ ...(child.permissionProfile ? { permissionProfile: child.permissionProfile } : {}),
1006
1023
  ...(child.launchContractDigest ? { launchContractDigest: child.launchContractDigest } : {}),
1007
1024
  ...(child.resumeContract ? { resumeContract: child.resumeContract } : {}),
1008
1025
  ...(child.extensionBindings ? { extensionBindings: normalizeExtensionBindings(child.extensionBindings)!.value } : {}),
@@ -1024,8 +1041,8 @@ type NestedResumeSourceTarget = {
1024
1041
  sessionFile: string;
1025
1042
  model?: string;
1026
1043
  thinking?: AgentConfig["thinking"];
1027
- sandbox?: string;
1028
- permissionProfile?: string;
1044
+ sandbox?: string;
1045
+ permissionProfile?: string;
1029
1046
  launchContractDigest?: string;
1030
1047
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
1031
1048
  recoveryDescriptor?: SteeringRecoveryDescriptor;
@@ -1365,6 +1382,16 @@ function appendStepToAsyncChain(input: {
1365
1382
  };
1366
1383
  }
1367
1384
 
1385
+ let retainedRequiredExtensions: RequiredChildExtensionSnapshot | undefined;
1386
+ try {
1387
+ retainedRequiredExtensions = readRetainedRequiredChildExtensions(resolved.location.asyncDir);
1388
+ } catch (error) {
1389
+ return {
1390
+ content: [{ type: "text", text: `Cannot append step to run '${resolved.id}': ${error instanceof Error ? error.message : String(error)}` }],
1391
+ isError: true,
1392
+ details: { mode: "management", results: [] },
1393
+ };
1394
+ }
1368
1395
  const pendingAppendRequests = readPendingChainAppendRequests(resolved.location.asyncDir);
1369
1396
  const reservedOutputNames = new Set<string>([
1370
1397
  ...Object.keys(status.outputs ?? {}),
@@ -1407,9 +1434,10 @@ function appendStepToAsyncChain(input: {
1407
1434
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1408
1435
  currentModelProvider: parentModel?.provider,
1409
1436
  currentModel: parentModel,
1437
+ scopedModelIds: scopedModelIdsFromContext(input.ctx),
1410
1438
  modelScope: discoveredForAppend.modelScope,
1411
- projectTrusted: currentProjectTrusted(input.ctx),
1412
- ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
1439
+ projectTrusted: currentProjectTrusted(input.ctx),
1440
+ ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
1413
1441
  modelResponseAliases: input.deps.config.modelResponseAliases,
1414
1442
  interactive: input.ctx.hasUI,
1415
1443
  permissions: input.deps.config.permissions,
@@ -1436,6 +1464,7 @@ projectTrusted: currentProjectTrusted(input.ctx),
1436
1464
  asyncDir: resolved.location.asyncDir,
1437
1465
  validateOutputBindings: false,
1438
1466
  capabilityCeiling: intersectSubagentCapabilityCeilings(status.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(asyncCtx.currentSessionId)),
1467
+ requiredExtensions: retainedRequiredExtensions,
1439
1468
  }));
1440
1469
  if ("error" in built) {
1441
1470
  return {
@@ -1561,7 +1590,7 @@ function resolveNestedResumeTarget(match: ResolvedSubagentRunId & { kind: "neste
1561
1590
  index: 0,
1562
1591
  cwd: asyncDir ? path.dirname(asyncDir) : undefined,
1563
1592
  sessionFile: validateNestedSessionFile(run, trustedSessionRoots),
1564
- ...(recoveryDescriptor?.sandbox ?? run.sandbox ? { sandbox: recoveryDescriptor?.sandbox ?? run.sandbox } : {}),
1593
+ ...(recoveryDescriptor?.sandbox ?? run.sandbox ? { sandbox: recoveryDescriptor?.sandbox ?? run.sandbox } : {}),
1565
1594
  ...(run.capabilityCeiling ? { capabilityCeiling: run.capabilityCeiling } : {}),
1566
1595
  ...(recoveryDescriptor ? { recoveryDescriptor } : {}),
1567
1596
  });
@@ -1840,11 +1869,13 @@ async function resumeExternalJobFollowUp(input: {
1840
1869
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1841
1870
  currentModelProvider: parentModel?.provider,
1842
1871
  currentModel: parentModel,
1872
+ scopedModelIds: scopedModelIdsFromContext(input.ctx),
1843
1873
  modelScope: input.modelScope,
1844
1874
  modelResponseAliases: input.deps.config.modelResponseAliases,
1845
1875
  interactive: input.ctx.hasUI,
1846
1876
  permissions: input.deps.config.permissions,
1847
1877
  childRuntime: input.deps.childRuntime,
1878
+ projectTrusted: currentProjectTrusted(input.ctx),
1848
1879
  }),
1849
1880
  cwd: input.effectiveCwd,
1850
1881
  artifactsDir,
@@ -1920,6 +1951,14 @@ async function resumeAsyncRun(input: {
1920
1951
  details: { mode: "management", results: [] },
1921
1952
  };
1922
1953
  }
1954
+ const timeoutOverflowError = timerDelayOverflowError("timeoutMs", input.params.timeoutMs);
1955
+ if (timeoutOverflowError) {
1956
+ return {
1957
+ content: [{ type: "text", text: timeoutOverflowError }],
1958
+ isError: true,
1959
+ details: { mode: "management", results: [] },
1960
+ };
1961
+ }
1923
1962
  if (input.params.model !== undefined) {
1924
1963
  return {
1925
1964
  content: [{ type: "text", text: "action='resume' reuses the persisted child model and does not accept a model override." }],
@@ -2101,12 +2140,13 @@ async function resumeAsyncRun(input: {
2101
2140
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
2102
2141
  currentModelProvider: parentModel?.provider,
2103
2142
  currentModel: parentModel,
2143
+ scopedModelIds: scopedModelIdsFromContext(input.ctx),
2104
2144
  modelScope,
2105
- projectTrusted: currentProjectTrusted(input.ctx),
2106
- ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2145
+ projectTrusted: currentProjectTrusted(input.ctx),
2146
+ ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2107
2147
  modelResponseAliases: input.deps.config.modelResponseAliases,
2108
2148
  interactive: input.ctx.hasUI,
2109
- permissions: input.deps.config.permissions,
2149
+ permissions: input.deps.config.permissions,
2110
2150
  childRuntime: input.deps.childRuntime,
2111
2151
  }),
2112
2152
  availableModels,
@@ -2223,7 +2263,7 @@ projectTrusted: currentProjectTrusted(input.ctx),
2223
2263
  goal: effectiveFollowUp,
2224
2264
  agentConfig,
2225
2265
  recoveryAgentConfig,
2226
- ...(recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) ? { sandbox: recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) } : {}),
2266
+ ...(recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) ? { sandbox: recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) } : {}),
2227
2267
  ctx: compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
2228
2268
  pi: input.deps.pi,
2229
2269
  cwd: input.requestCwd,
@@ -2231,9 +2271,10 @@ projectTrusted: currentProjectTrusted(input.ctx),
2231
2271
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
2232
2272
  currentModelProvider: parentModel?.provider,
2233
2273
  currentModel: parentModel,
2274
+ scopedModelIds: scopedModelIdsFromContext(input.ctx),
2234
2275
  modelScope,
2235
- projectTrusted: currentProjectTrusted(input.ctx),
2236
- ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2276
+ projectTrusted: currentProjectTrusted(input.ctx),
2277
+ ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2237
2278
  // Absence in the retained contract is meaningful; never acquire current aliases.
2238
2279
  modelResponseAliases: recoveryDescriptor ? recoveryDescriptor.modelResponseAliases : foregroundContract?.modelResponseAliases,
2239
2280
  interactive: input.ctx.hasUI,
@@ -2333,63 +2374,31 @@ projectTrusted: currentProjectTrusted(input.ctx),
2333
2374
  if (input.params.workflowParentRunId !== undefined && result.details.asyncDir) {
2334
2375
  const asyncDir = result.details.asyncDir;
2335
2376
  const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
2336
- const stopOnAbort = () => { stopAsyncRun(input.deps.state, revivedId, input.deps.kill, { asyncDir, resolvedId: revivedId }); };
2337
- if (input.signal?.aborted) stopOnAbort();
2338
- else input.signal?.addEventListener("abort", stopOnAbort, { once: true });
2339
- let completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>;
2340
- try {
2341
- completed = await waitForImportedAsyncRoot({ runId: revivedId, asyncDir, resultPath, index: 0 });
2342
- } finally {
2343
- input.signal?.removeEventListener("abort", stopOnAbort);
2344
- }
2345
- if (completed.importedPublication) removeWorkflowAwaitedResult(asyncDir, resultPath, revivedId, completed.importedPublication);
2346
- emitWorkflowAwaitedChildComplete(input.deps.pi, input.deps.state, revivedId, asyncDir, input.params.workflowParentRunId, completed);
2347
- const usage = importedAsyncRootUsage(completed);
2348
- const childResult: SingleResult = {
2349
- index: 0,
2350
- agent: completed.agent,
2351
- ...(completed.sessionName ? { sessionName: completed.sessionName } : {}),
2352
- task: effectiveFollowUp,
2353
- exitCode: completed.exitCode,
2354
- usage,
2355
- finalOutput: completed.output,
2356
- outputState: completed.output.trim() ? "present" : "absent",
2357
- ...(completed.error ? { error: completed.error } : {}),
2358
- ...(completed.timedOut ? { timedOut: true } : {}),
2359
- ...(completed.stopped ? { stopped: true } : {}),
2360
- ...(completed.sessionFile ? { sessionFile: completed.sessionFile } : {}),
2361
- ...(completed.model ? { model: completed.model } : {}),
2362
- ...(completed.requestedModel ? { requestedModel: completed.requestedModel } : {}),
2363
- ...(completed.contextOverflow ? { contextOverflow: true } : {}),
2364
- ...(completed.structuredOutput !== undefined ? { structuredOutput: completed.structuredOutput } : {}),
2365
- ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
2366
- ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
2367
- ...(completed.acceptance ? { acceptance: completed.acceptance } : {}),
2368
- ...(completed.artifactPaths ? { artifactPaths: completed.artifactPaths } : {}),
2369
- ...(completed.savedOutputPath ? { savedOutputPath: completed.savedOutputPath } : {}),
2370
- ...(completed.outputSaveError ? { outputSaveError: completed.outputSaveError } : {}),
2371
- ...(completed.transcriptPath ? { transcriptPath: completed.transcriptPath } : {}),
2372
- ...(completed.transcriptError ? { transcriptError: completed.transcriptError } : {}),
2373
- };
2374
- return {
2375
- 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.` }],
2376
- ...(completed.success ? {} : { isError: true }),
2377
- details: {
2378
- ...result.details,
2379
- runId: revivedId,
2380
- results: [childResult],
2381
- ...(target.launchContractDigest ? { sourceLaunchContractDigest: target.launchContractDigest } : {}),
2382
- },
2383
- };
2377
+ const stopListener = stopAwaitedAsyncChildOnAbort(input.signal, input.deps.state, revivedId, asyncDir, input.deps.kill);
2378
+ const completed = await waitForImportedAsyncRoot({ runId: revivedId, asyncDir, resultPath, index: 0 }, {
2379
+ shouldAbort: () => input.signal?.aborted === true,
2380
+ timeoutMessage: "Workflow stopped before async child completed.",
2381
+ abortedAsStopped: true,
2382
+ }).finally(stopListener.remove);
2383
+ const details: Details = { ...result.details };
2384
+ if (target.launchContractDigest) details.sourceLaunchContractDigest = target.launchContractDigest;
2385
+ 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 });
2384
2386
  }
2385
2387
  const revivedTarget = intercomBridge.active ? resolveSubagentIntercomTarget(revivedId, target.agent, 0) : undefined;
2386
2388
  const sourceLabel = target.source;
2389
+ let workflowRevivalWarning: string | undefined;
2390
+ try {
2391
+ if (target.source === "async") recordWorkflowRevival(DIRS.async, target.runId, revivedId);
2392
+ } catch (error) {
2393
+ workflowRevivalWarning = `Warning: workflow key link not recorded: ${error instanceof Error ? error.message : String(error)}`;
2394
+ }
2387
2395
  const lines = [
2388
2396
  `Revived ${sourceLabel} subagent from ${target.runId}.`,
2389
2397
  `Revived run: ${revivedId}`,
2390
2398
  `Agent: ${target.agent}`,
2391
2399
  `Session: ${target.sessionFile}`,
2392
2400
  result.details.asyncDir ? `Async dir: ${result.details.asyncDir}` : undefined,
2401
+ workflowRevivalWarning,
2393
2402
  revivedTarget ? `Intercom target: ${revivedTarget} (if registered)` : undefined,
2394
2403
  `Status if needed: subagent({ action: "status", id: "${revivedId}" })`,
2395
2404
  ].filter((line): line is string => Boolean(line));
@@ -2557,6 +2566,28 @@ function canonicalizeAgentName(name: string, agents: AgentConfig[], diagnostics:
2557
2566
  return { name: resolved.agent.name };
2558
2567
  }
2559
2568
 
2569
+ // Mirrors child launch: workflow children without their own cwd/agentScope discover agents at the workflow cwd and scope.
2570
+ function workflowValidationOptions(deps: ExecutorDeps, params: SubagentParamsLike, runtimeCwd: string, parentModelProvider: () => string | undefined): Parameters<typeof validateWorkflowScript>[1] {
2571
+ const cwd = resolveRequestedCwd(runtimeCwd, params.cwd);
2572
+ const scope = resolveExecutionAgentScope(params.agentScope);
2573
+ let discovered: ReturnType<ExecutorDeps["discoverAgents"]> | undefined;
2574
+ return {
2575
+ maxSubagentSpawnsPerRun: params.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
2576
+ agentNameError: (name) => {
2577
+ discovered ??= deps.discoverAgents(cwd, scope, parentModelProvider());
2578
+ const { agents } = discovered;
2579
+ const resolved = resolveAgentName(name, agents);
2580
+ if (resolved.agent || resolved.error) return canonicalizeAgentName(name, agents, discovered.agentDiagnostics, diagnosticContextFromDiscovery(discovered, cwd, scope)).error;
2581
+ const requested = name.trim().toLowerCase();
2582
+ const suggestion = [...new Set(agents.flatMap((agent) => [agent.name, ...(agent.localName ? [agent.localName] : []), ...(agent.aliases ?? [])]))]
2583
+ .map((candidate) => ({ candidate, distance: editDistance(requested, candidate.toLowerCase()) }))
2584
+ .filter(({ candidate, distance }) => distance <= Math.max(1, Math.floor(candidate.length / 4)) || hasSingleAdjacentTransposition(requested, candidate.toLowerCase()))
2585
+ .sort((left, right) => left.distance - right.distance || left.candidate.localeCompare(right.candidate))[0]?.candidate;
2586
+ return `Unknown agent '${name}'.${suggestion ? ` Did you mean '${suggestion}'?` : ""} Use subagent({ action: "list" }) to inspect agents.`;
2587
+ },
2588
+ };
2589
+ }
2590
+
2560
2591
  function canonicalizeExecutionParams(params: SubagentParamsLike, agents: AgentConfig[], diagnostics: AgentDiscoveryDiagnostic[] | undefined, context: UnknownAgentDiagnosticContext): { params?: SubagentParamsLike; error?: string } {
2561
2592
  const resolve = (name: string, location?: string): { name?: string; error?: string } => {
2562
2593
  const result = canonicalizeAgentName(name, agents, diagnostics, context);
@@ -2979,6 +3010,12 @@ export { DEFAULT_ASYNC_TIMEOUT_MS };
2979
3010
  */
2980
3011
  const MAX_TIMER_DELAY_MS = 2_147_483_647;
2981
3012
 
3013
+ function timerDelayOverflowError(name: string, value: unknown): string | undefined {
3014
+ return typeof value === "number" && value > MAX_TIMER_DELAY_MS
3015
+ ? `${name} must be a positive integer no larger than ${MAX_TIMER_DELAY_MS}.`
3016
+ : undefined;
3017
+ }
3018
+
2982
3019
  /**
2983
3020
  * Resolve the optional global default runtime deadline from extension config
2984
3021
  * (`config.timeoutMs`). Returns undefined for unset or invalid values so callers
@@ -3002,6 +3039,8 @@ export function resolveForegroundTimeout(params: SubagentParamsLike, defaultTime
3002
3039
  if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
3003
3040
  return { error: `${name} must be a positive integer.` };
3004
3041
  }
3042
+ const overflowError = timerDelayOverflowError(name, value);
3043
+ if (overflowError) return { error: overflowError };
3005
3044
  }
3006
3045
  if (rawTimeout !== undefined && rawMaxRuntime !== undefined && rawTimeout !== rawMaxRuntime) {
3007
3046
  return { error: "timeoutMs and maxRuntimeMs are aliases; provide only one value or use the same value for both." };
@@ -3157,6 +3196,7 @@ function resolveStaticLaunchSummary(input: {
3157
3196
  explicitModel?: string;
3158
3197
  agents: AgentConfig[];
3159
3198
  parentModel?: ParentModel;
3199
+ scopedModelIds?: string[];
3160
3200
  availableModels: ModelInfo[];
3161
3201
  currentProvider?: string;
3162
3202
  modelScope?: ModelScopeConfig;
@@ -3164,7 +3204,7 @@ function resolveStaticLaunchSummary(input: {
3164
3204
  }): StaticLaunchSummary {
3165
3205
  const agentConfig = input.agents.find((agent) => agent.name === input.agent);
3166
3206
  const externalRunner = agentConfig?.runner?.type === "external-cli" || agentConfig?.runner?.type === "external-job";
3167
- const modelScopes = resolveModelScopesForAgent(input.modelScope, input.agent, input.parentModel);
3207
+ const modelScopes = resolveModelScopesForAgent(input.modelScope, input.agent, input.parentModel, input.scopedModelIds);
3168
3208
  const model = externalRunner
3169
3209
  ? undefined
3170
3210
  : resolveEffectiveSubagentModel(
@@ -3181,7 +3221,7 @@ function resolveStaticLaunchSummary(input: {
3181
3221
  agent: input.agent,
3182
3222
  ...(model ? { model } : {}),
3183
3223
  ...(thinking ? { thinking } : {}),
3184
- ...(agentConfig?.sandbox ? { sandbox: agentConfig.sandbox } : {}),
3224
+ ...(agentConfig?.sandbox ? { sandbox: agentConfig.sandbox } : {}),
3185
3225
  };
3186
3226
  }
3187
3227
 
@@ -3189,6 +3229,7 @@ function collectStaticLaunchSummaries(input: {
3189
3229
  params: SubagentParamsLike;
3190
3230
  agents: AgentConfig[];
3191
3231
  parentModel?: ParentModel;
3232
+ scopedModelIds?: string[];
3192
3233
  availableModels: ModelInfo[];
3193
3234
  currentProvider?: string;
3194
3235
  modelScope?: ModelScopeConfig;
@@ -3201,6 +3242,7 @@ function collectStaticLaunchSummaries(input: {
3201
3242
  explicitModel,
3202
3243
  agents: input.agents,
3203
3244
  parentModel: input.parentModel,
3245
+ scopedModelIds: input.scopedModelIds,
3204
3246
  availableModels: input.availableModels,
3205
3247
  currentProvider: input.currentProvider,
3206
3248
  modelScope: input.modelScope,
@@ -3386,28 +3428,13 @@ function emitWorkflowAwaitedChildComplete(
3386
3428
  });
3387
3429
  }
3388
3430
 
3389
- async function waitForWorkflowAsyncSingleResult(
3390
- params: SubagentParamsLike,
3391
- launchResult: AgentToolResult<Details>,
3392
- options: { runId: string; task: string; signal?: AbortSignal; state: SubagentState; pi: ExtensionAPI; kill?: ExecutorDeps["kill"] },
3393
- ): Promise<AgentToolResult<Details>> {
3394
- if (params.workflowAwaitAsync !== true || !launchResult.details.asyncDir) return launchResult;
3395
- const asyncDir = launchResult.details.asyncDir;
3396
- const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
3397
- const stopOnAbort = () => { stopAsyncRun(options.state, options.runId, options.kill, { asyncDir, resolvedId: options.runId }); };
3398
- if (options.signal?.aborted) stopOnAbort();
3399
- else options.signal?.addEventListener("abort", stopOnAbort, { once: true });
3400
- let completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>;
3401
- try {
3402
- completed = await waitForImportedAsyncRoot({ runId: options.runId, asyncDir, resultPath, index: 0 }, omitUndefinedProperties({
3403
- shouldAbort: () => options.signal?.aborted === true,
3404
- timeoutMessage: "Workflow stopped before async child completed.",
3405
- }));
3406
- } finally {
3407
- options.signal?.removeEventListener("abort", stopOnAbort);
3408
- }
3409
- if (completed.importedPublication) removeWorkflowAwaitedResult(asyncDir, resultPath, options.runId, completed.importedPublication);
3410
- emitWorkflowAwaitedChildComplete(options.pi, options.state, options.runId, asyncDir, params.workflowParentRunId, completed);
3431
+ /** Consumes an awaited workflow child's published result: clears the payload, announces completion, and builds the tool result. */
3432
+ function importWorkflowAwaitedChildResult(
3433
+ completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>,
3434
+ options: { runId: string; asyncDir: string; resultPath: string; task: string; parentWorkflowRunId: string | undefined; details: Details; emptyOutputText?: string; state: SubagentState; pi: ExtensionAPI },
3435
+ ): AgentToolResult<Details> {
3436
+ if (completed.importedPublication) removeWorkflowAwaitedResult(options.asyncDir, options.resultPath, options.runId, completed.importedPublication);
3437
+ emitWorkflowAwaitedChildComplete(options.pi, options.state, options.runId, options.asyncDir, options.parentWorkflowRunId, completed);
3411
3438
  const usage = importedAsyncRootUsage(completed);
3412
3439
  const childResult: SingleResult = omitUndefinedProperties({
3413
3440
  index: 0,
@@ -3436,16 +3463,55 @@ async function waitForWorkflowAsyncSingleResult(
3436
3463
  ...(completed.transcriptError ? { transcriptError: completed.transcriptError } : {}),
3437
3464
  });
3438
3465
  return {
3439
- 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.` }],
3466
+ content: [{ type: "text", text: (completed.success ? completed.output || completed.error : completed.error || completed.output) || (options.emptyOutputText ?? `Async workflow child ${options.runId} completed without output.`) }],
3440
3467
  ...(completed.success ? {} : { isError: true }),
3441
3468
  details: {
3442
- ...launchResult.details,
3469
+ ...options.details,
3443
3470
  runId: options.runId,
3444
3471
  results: [childResult],
3445
3472
  },
3446
3473
  };
3447
3474
  }
3448
3475
 
3476
+ // A replaced runtime leaves the child running so a relaunch of the workflow can re-attach to it.
3477
+ function stopAwaitedAsyncChildOnAbort(signal: AbortSignal | undefined, state: SubagentState, runId: string, asyncDir: string, kill?: ExecutorDeps["kill"]): { remove: () => void } {
3478
+ const stopOnAbort = () => { if (!workflowStopCause(signal?.reason)) stopAsyncRun(state, runId, kill, { asyncDir, resolvedId: runId }); };
3479
+ if (signal?.aborted) stopOnAbort();
3480
+ else signal?.addEventListener("abort", stopOnAbort, { once: true });
3481
+ return { remove: () => signal?.removeEventListener("abort", stopOnAbort) };
3482
+ }
3483
+
3484
+ // Live workflow controls are keyed by the full run id; a stop id may be a prefix or the launch tool-call id.
3485
+ function resolveLiveWorkflowRunId(deps: ExecutorDeps, id: string): string | undefined {
3486
+ const controllers = deps.state.workflowControllers;
3487
+ if (!controllers?.size) return undefined;
3488
+ if (controllers.has(id)) return id;
3489
+ try {
3490
+ const resolved = resolveSubagentRunId(id, omitUndefinedProperties({ state: deps.state, nested: nestedResolutionScopeForExecutor(deps) }));
3491
+ return resolved?.kind === "async" && controllers.has(resolved.id) ? resolved.id : undefined;
3492
+ } catch {
3493
+ // The generic stop path resolves the id again and reports the error.
3494
+ return undefined;
3495
+ }
3496
+ }
3497
+
3498
+ async function waitForWorkflowAsyncSingleResult(
3499
+ params: SubagentParamsLike,
3500
+ launchResult: AgentToolResult<Details>,
3501
+ options: { runId: string; task: string; signal?: AbortSignal; state: SubagentState; pi: ExtensionAPI; kill?: ExecutorDeps["kill"] },
3502
+ ): Promise<AgentToolResult<Details>> {
3503
+ if (params.workflowAwaitAsync !== true || !launchResult.details.asyncDir) return launchResult;
3504
+ const asyncDir = launchResult.details.asyncDir;
3505
+ const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
3506
+ const stopListener = stopAwaitedAsyncChildOnAbort(options.signal, options.state, options.runId, asyncDir, options.kill);
3507
+ const completed = await waitForImportedAsyncRoot({ runId: options.runId, asyncDir, resultPath, index: 0 }, omitUndefinedProperties({
3508
+ shouldAbort: () => options.signal?.aborted === true,
3509
+ timeoutMessage: "Workflow stopped before async child completed.",
3510
+ abortedAsStopped: true,
3511
+ })).finally(stopListener.remove);
3512
+ return importWorkflowAwaitedChildResult(completed, { runId: options.runId, asyncDir, resultPath, task: options.task, parentWorkflowRunId: params.workflowParentRunId, details: launchResult.details, state: options.state, pi: options.pi });
3513
+ }
3514
+
3449
3515
  async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Promise<AgentToolResult<Details> | null> {
3450
3516
  const {
3451
3517
  params,
@@ -3487,10 +3553,11 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3487
3553
  parentSessionId: data.parentPiSessionId,
3488
3554
  currentModelProvider: parentModel?.provider,
3489
3555
  currentModel: parentModel,
3556
+ scopedModelIds: data.scopedModelIds,
3490
3557
  modelScope: data.modelScope,
3491
- projectTrusted: currentProjectTrusted(ctx),
3492
- ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3493
- modelResponseAliases: deps.config.modelResponseAliases, interactive: ctx.hasUI,
3558
+ projectTrusted: currentProjectTrusted(ctx),
3559
+ ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3560
+ modelResponseAliases: deps.config.modelResponseAliases, interactive: ctx.hasUI,
3494
3561
  permissions: deps.config.permissions,
3495
3562
  childRuntime: deps.childRuntime,
3496
3563
  });
@@ -3510,18 +3577,18 @@ modelResponseAliases: deps.config.modelResponseAliases, interactive: ctx.hasUI,
3510
3577
  details: { mode: "single" as const, results: [] },
3511
3578
  };
3512
3579
  }
3513
- const sandboxTrustError = params.worktree === true
3514
- ? sandboxProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
3515
- : sandboxProfileTrustError(a, ctx, effectiveCwd);
3516
- if (sandboxTrustError) {
3517
- return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single" as const, results: [] } };
3518
- }
3519
- const permissionProfileTrustErrorForAgent = params.worktree === true
3520
- ? permissionProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
3521
- : permissionProfileTrustError(a, ctx, effectiveCwd);
3522
- if (permissionProfileTrustErrorForAgent) {
3523
- return { content: [{ type: "text", text: permissionProfileTrustErrorForAgent }], isError: true, details: { mode: "single" as const, results: [] } };
3524
- }
3580
+ const sandboxTrustError = params.worktree === true
3581
+ ? sandboxProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
3582
+ : sandboxProfileTrustError(a, ctx, effectiveCwd);
3583
+ if (sandboxTrustError) {
3584
+ return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single" as const, results: [] } };
3585
+ }
3586
+ const permissionProfileTrustErrorForAgent = params.worktree === true
3587
+ ? permissionProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
3588
+ : permissionProfileTrustError(a, ctx, effectiveCwd);
3589
+ if (permissionProfileTrustErrorForAgent) {
3590
+ return { content: [{ type: "text", text: permissionProfileTrustErrorForAgent }], isError: true, details: { mode: "single" as const, results: [] } };
3591
+ }
3525
3592
  const rawOutput = params.output !== undefined ? params.output : a.output;
3526
3593
  const effectiveOutput = normalizeSingleOutputOverride(rawOutput, a.output);
3527
3594
  const effectiveOutputMode = params.outputMode ?? a.outputMode ?? "inline";
@@ -3534,7 +3601,7 @@ return { content: [{ type: "text", text: permissionProfileTrustErrorForAgent }],
3534
3601
  if ((a.runner?.type === "external-cli" || a.runner?.type === "external-job") && (params.fast ?? a.fast) === true) {
3535
3602
  return buildRequestedModeError(params, `Agent '${a.name}' uses runner.type='${a.runner.type}' and does not support fast mode.`);
3536
3603
  }
3537
- const modelScopes = resolveModelScopesForAgent(data.modelScope, a.name, parentModel);
3604
+ const modelScopes = resolveModelScopesForAgent(data.modelScope, a.name, parentModel, data.scopedModelIds);
3538
3605
  const modelOrigin = resolveModelOrigin({
3539
3606
  storedOrigin: params.modelOrigin as ModelOrigin | undefined,
3540
3607
  explicitModel: params.model as string | undefined,
@@ -3556,6 +3623,7 @@ return { content: [{ type: "text", text: permissionProfileTrustErrorForAgent }],
3556
3623
  goal: params.task ?? "",
3557
3624
  agentConfig: a,
3558
3625
  recoveryAgentConfig: data.recoveryAgents.find((agent) => agent.name === params.agent),
3626
+ requiredExtensions: data.requiredExtensions,
3559
3627
  ctx: asyncCtx,
3560
3628
  availableModels,
3561
3629
  cwd: effectiveCwd,
@@ -3725,6 +3793,45 @@ function appendWorkflowOutputWarning(text: string, warning: string | undefined):
3725
3793
  return warning ? `${text}\n\n${warning}` : text;
3726
3794
  }
3727
3795
 
3796
+ const WORKFLOW_TRACE_ERROR_MAX_CHARS = 500;
3797
+
3798
+ // Return, emits, console, and trace errors (which carry child text) have no size limit of their
3799
+ // own, so only they are cut; other host sections stay whole. The saved full result is uncut.
3800
+ function formatWorkflowResultText(input: {
3801
+ head: string[];
3802
+ script: string[];
3803
+ trace: Array<{ line: string; error?: string }>;
3804
+ tail: string[];
3805
+ maxOutput: MaxOutputConfig | undefined;
3806
+ aggregateOutputPath: string | undefined;
3807
+ fullResultPath: string;
3808
+ producedChildOutputPaths: ReadonlySet<string>;
3809
+ }): string {
3810
+ const traceSection = (error: (text: string) => string) => input.trace.length > 0
3811
+ ? [`Call trace:\n${input.trace.map((entry) => `${entry.line}${entry.error ? ` — ${error(entry.error)}` : ""}`).join("\n")}`]
3812
+ : [];
3813
+ const fullText = [...input.head, ...input.script, ...traceSection((error) => error), ...input.tail].join("\n\n");
3814
+ const outputWarning = writeWorkflowAggregateOutput(input.aggregateOutputPath, fullText, input.producedChildOutputPaths);
3815
+ const scriptText = input.script.join("\n\n");
3816
+ const config = { ...DEFAULT_MAX_OUTPUT, ...input.maxOutput };
3817
+ const scriptCut = truncateOutput(scriptText, config).truncated;
3818
+ const traceCut = input.trace.some((entry) => (entry.error?.length ?? 0) > WORKFLOW_TRACE_ERROR_MAX_CHARS);
3819
+ let shownScriptText = scriptText;
3820
+ let saveWarning: string | undefined;
3821
+ let savedPath: string | undefined;
3822
+ if (scriptCut || traceCut) {
3823
+ const aggregateHoldsFullText = input.aggregateOutputPath !== undefined && !outputWarning
3824
+ && !input.producedChildOutputPaths.has(resolveWorkflowHostOutputClaimPath(input.aggregateOutputPath));
3825
+ if (!aggregateHoldsFullText) saveWarning = writeWorkflowAggregateOutput(input.fullResultPath, fullText, new Set());
3826
+ savedPath = aggregateHoldsFullText ? input.aggregateOutputPath : saveWarning ? undefined : input.fullResultPath;
3827
+ if (scriptCut) shownScriptText = truncateOutput(scriptText, config, savedPath).text;
3828
+ }
3829
+ 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);
3830
+ const traceNote = traceCut && !scriptCut && savedPath ? [`[TRUNCATED: trace errors shortened - full output at ${savedPath}]`] : [];
3831
+ const text = [...input.head, ...(shownScriptText ? [shownScriptText] : []), ...shownTrace, ...input.tail, ...traceNote].join("\n\n");
3832
+ return appendWorkflowOutputWarning(appendWorkflowOutputWarning(text, outputWarning), saveWarning);
3833
+ }
3834
+
3728
3835
  export function resolveWorkflowChildLocalCwd(input: {
3729
3836
  workflowCwd: string;
3730
3837
  discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
@@ -4003,8 +4110,12 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4003
4110
  }
4004
4111
  let foregroundMachine: import("../../shared/types.ts").HerdrMachineReference | undefined;
4005
4112
  const requestedMachine = params.machine ?? agentConfig.machine;
4113
+ const requiredExtensions = data.requiredExtensions ?? deps.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(data.parentPiSessionId);
4006
4114
  if (requestedMachine) {
4007
- try { foregroundMachine = resolveHerdrMachinePlacement({ machine: requestedMachine, cwd: ctx.cwd, stepCwd: params.machineCwd }).machine; }
4115
+ try {
4116
+ assertRequiredChildExtensionsAdmitted([requiredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
4117
+ foregroundMachine = resolveHerdrMachinePlacement({ machine: requestedMachine, cwd: ctx.cwd, stepCwd: params.machineCwd }).machine;
4118
+ }
4008
4119
  catch (error) { return toExecutionErrorResult(params, error instanceof Error ? error : new Error(String(error)), data.contextPolicy.contextSummary); }
4009
4120
  }
4010
4121
  const effectiveToolBudget = resolveEffectiveToolBudget(omitUndefinedProperties({ runBudget: data.toolBudget, agentBudget: agentConfig.toolBudget, configBudget: data.configToolBudget }));
@@ -4013,7 +4124,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4013
4124
  const parentModel = data.parentModel;
4014
4125
  const currentProvider = parentModel?.provider;
4015
4126
  const availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);
4016
- const modelScopes = resolveModelScopesForAgent(data.modelScope, agentConfig.name, parentModel);
4127
+ const modelScopes = resolveModelScopesForAgent(data.modelScope, agentConfig.name, parentModel, data.scopedModelIds);
4017
4128
  let task = typeof params.task === "string" ? params.task : "";
4018
4129
  const modelOrigin = resolveModelOrigin({
4019
4130
  storedOrigin: params.modelOrigin as ModelOrigin | undefined,
@@ -4082,16 +4193,16 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4082
4193
  return worktreeSetupError;
4083
4194
  }
4084
4195
  const singleCwd = worktreeSetup?.worktrees[0]?.agentCwd ?? sourceCwd;
4085
- const sandboxTrustError = sandboxProfileTrustError(agentConfig, ctx, singleCwd);
4086
- if (sandboxTrustError) {
4087
- if (worktreeSetup) cleanupWorktrees(worktreeSetup);
4088
- return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single", results: [] } };
4089
- }
4090
- const permissionProfileTrustErrorForLaunch = permissionProfileTrustError(agentConfig, ctx, singleCwd);
4091
- if (permissionProfileTrustErrorForLaunch) {
4092
- if (worktreeSetup) cleanupWorktrees(worktreeSetup);
4093
- return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }], isError: true, details: { mode: "single", results: [] } };
4094
- }
4196
+ const sandboxTrustError = sandboxProfileTrustError(agentConfig, ctx, singleCwd);
4197
+ if (sandboxTrustError) {
4198
+ if (worktreeSetup) cleanupWorktrees(worktreeSetup);
4199
+ return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single", results: [] } };
4200
+ }
4201
+ const permissionProfileTrustErrorForLaunch = permissionProfileTrustError(agentConfig, ctx, singleCwd);
4202
+ if (permissionProfileTrustErrorForLaunch) {
4203
+ if (worktreeSetup) cleanupWorktrees(worktreeSetup);
4204
+ return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }], isError: true, details: { mode: "single", results: [] } };
4205
+ }
4095
4206
  const cleanupSingleWorktree = async () => {
4096
4207
  if (!worktreeSetup) return;
4097
4208
  let admitted = false;
@@ -4148,6 +4259,20 @@ return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }]
4148
4259
  let detachForeground: ((reason?: string) => boolean) | undefined;
4149
4260
  let childSessionControls: ForegroundChildSessionControls | undefined;
4150
4261
  const foregroundControl = deps.state.foregroundControls.get(runId);
4262
+ const syncHerdrForegroundChild = () => {
4263
+ if (!foregroundControl?.parentWorkflowRunId) return;
4264
+ try {
4265
+ deps.pi.events.emit(HERDR_FOREGROUND_CONTROL_CHANGED_EVENT, { runId: foregroundControl.parentWorkflowRunId });
4266
+ } catch (error) {
4267
+ console.error("Failed to sync Herdr foreground child:", error);
4268
+ }
4269
+ };
4270
+ const finishTrackedForegroundChild = () => {
4271
+ if (!foregroundControl) return;
4272
+ const wasActive = foregroundControl.activeChildren?.has(0) === true;
4273
+ finishForegroundChild(foregroundControl, 0);
4274
+ if (wasActive) syncHerdrForegroundChild();
4275
+ };
4151
4276
  if (foregroundControl) {
4152
4277
  const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask());
4153
4278
  beginForegroundChild(foregroundControl, omitUndefinedProperties({
@@ -4183,6 +4308,7 @@ return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }]
4183
4308
  }));
4184
4309
  // Capture the owned mailbox before a child can start and finish between polling ticks.
4185
4310
  if (deps.childRuntime?.fanoutChild) deps.activateSupervisorTransport?.();
4311
+ syncHerdrForegroundChild();
4186
4312
  }
4187
4313
 
4188
4314
  const modelResponseAliases = deps.config.modelResponseAliases === undefined ? undefined : structuredClone(deps.config.modelResponseAliases);
@@ -4194,7 +4320,6 @@ return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }]
4194
4320
  : undefined;
4195
4321
 
4196
4322
  const deadlineAt = data.deadlineAt ?? (data.timeoutMs !== undefined ? Date.now() + data.timeoutMs : undefined);
4197
- const requiredExtensions = deps.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(data.parentPiSessionId);
4198
4323
  let r: Awaited<ReturnType<typeof runSync>> | undefined;
4199
4324
  let resolveDetachedWorkflowChild: ((result: Awaited<ReturnType<typeof runSync>>) => void) | undefined;
4200
4325
  const detachedWorkflowChild = params.workflowAwaitDetached === true
@@ -4208,8 +4333,8 @@ return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }]
4208
4333
  permissions: deps.config.permissions,
4209
4334
  runtimeSnapshotHost: deps.pi,
4210
4335
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
4211
- projectTrusted: currentProjectTrusted(ctx),
4212
- ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
4336
+ projectTrusted: currentProjectTrusted(ctx),
4337
+ ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
4213
4338
  requiredExtensions,
4214
4339
  childRuntime: deps.childRuntime,
4215
4340
  onChildSession: (controls) => { childSessionControls = controls; },
@@ -4219,6 +4344,7 @@ projectTrusted: currentProjectTrusted(ctx),
4219
4344
  cwd: singleCwd,
4220
4345
  requestedCwd: data.requestedCwd,
4221
4346
  signal,
4347
+ abortedAsStopped: params.workflowParentRunId !== undefined,
4222
4348
  interruptSignal: interruptController.signal,
4223
4349
  allowIntercomDetach: agentConfig.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,
4224
4350
  intercomEvents: deps.pi.events,
@@ -4294,7 +4420,7 @@ projectTrusted: currentProjectTrusted(ctx),
4294
4420
  if (!artifactConfig.enabled) cleanupStructuredOutputRuntime(structuredRuntime);
4295
4421
  } finally {
4296
4422
  try {
4297
- if (foregroundControl) finishForegroundChild(foregroundControl, 0);
4423
+ finishTrackedForegroundChild();
4298
4424
  } finally {
4299
4425
  removeForegroundControlIfIdle(deps.state, runId, deps.trackRetainedNestedRoute);
4300
4426
  }
@@ -4321,7 +4447,7 @@ projectTrusted: currentProjectTrusted(ctx),
4321
4447
  // authoritative completion remains live.
4322
4448
  if (!r?.detached) {
4323
4449
  if (!artifactConfig.enabled) cleanupStructuredOutputRuntime(structuredRuntime);
4324
- if (foregroundControl) finishForegroundChild(foregroundControl, 0);
4450
+ finishTrackedForegroundChild();
4325
4451
  }
4326
4452
  }
4327
4453
  if (!r.detached) {
@@ -4428,7 +4554,7 @@ projectTrusted: currentProjectTrusted(ctx),
4428
4554
  }
4429
4555
 
4430
4556
  function inferExecutionMode(params: SubagentParamsLike): Details["mode"] {
4431
- if (params.workflowScript !== undefined) return "workflow";
4557
+ if (params.workflowScript !== undefined || params.workflow !== undefined) return "workflow";
4432
4558
  if ((params.chain?.length ?? 0) > 0) return "chain";
4433
4559
  if ((params.tasks?.length ?? 0) > 0) return "parallel";
4434
4560
  return "single";
@@ -4447,6 +4573,7 @@ function duplicateSubagentCallResult(params: SubagentParamsLike): AgentToolResul
4447
4573
 
4448
4574
  const workflowLaunchObservers = new WeakMap<object, (launch: { agent: string; sessionName?: string; sessionFile?: string; async: boolean; runId?: string }) => void>();
4449
4575
  const workflowOwnedUsageBudgets = new WeakMap<object, UsageBudgetConfig>();
4576
+ const workflowRetainedRequiredExtensions = new WeakMap<object, RequiredChildExtensionSnapshot>();
4450
4577
 
4451
4578
  /**
4452
4579
  * Terminal-mission retention can remove a mission while its children still
@@ -4529,16 +4656,19 @@ function workflowChildResult(
4529
4656
  ? result.details.results[0].finalOutput
4530
4657
  : receiptOutput;
4531
4658
  const childError = result.details.results.map((child) => child.error).find((error): error is string => Boolean(error));
4532
- const failureErrorBase = childError && receiptOutput
4533
- ? receiptOutput.includes(childError) ? receiptOutput : `${childError}\n\n${receiptOutput}`
4534
- : childError || receiptOutput || output || "Child run failed.";
4659
+ const stopped = result.details.results.some((child) => child.stopped);
4660
+ // A stopped child's receipt text carries the run fan-out annotation; report the structured stop reason instead.
4661
+ const failureErrorBase = stopped && childError
4662
+ ? childError
4663
+ : childError && receiptOutput
4664
+ ? receiptOutput.includes(childError) ? receiptOutput : `${childError}\n\n${receiptOutput}`
4665
+ : childError || receiptOutput || output || "Child run failed.";
4535
4666
  const savedOutputEvidence = [...new Set(result.details.results.map((child) => child.savedOutputPath).filter((value): value is string => Boolean(value)))]
4536
4667
  .filter((savedOutputPath) => !failureErrorBase.includes(savedOutputPath))
4537
4668
  .map((savedOutputPath) => `Saved output: ${savedOutputPath}`);
4538
4669
  const failureError = [failureErrorBase, ...savedOutputEvidence].join("\n");
4539
4670
  const detached = result.details.results.some((child) => child.detached);
4540
4671
  const interrupted = result.details.results.some((child) => child.interrupted);
4541
- const stopped = result.details.results.some((child) => child.stopped);
4542
4672
  const terminalOutcome = forcedTerminalOutcome
4543
4673
  ?? (result.details.results.some((child) => child.timedOut)
4544
4674
  ? { state: "partial" as const, reason: "timeout" as const }
@@ -4634,9 +4764,9 @@ function workflowRunningChildrenSummary(children: WorkflowScriptChildResult[]):
4634
4764
  }
4635
4765
 
4636
4766
  function workflowResultChildren(children: WorkflowScriptChildResult[], status: AsyncStatus, includeFailureFields: boolean) {
4637
- return children.map((child) => {
4767
+ return withWorkflowRevivals(DIRS.async, status.runId, children).map((child) => {
4638
4768
  const sessionName = status.steps?.find((step) => step.workflowKey === child.key)?.sessionName;
4639
- return { workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(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 } } : {}) };
4769
+ 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 } } : {}) };
4640
4770
  });
4641
4771
  }
4642
4772
 
@@ -4648,7 +4778,11 @@ function workflowOutputPathMappingSummary(children: WorkflowScriptChildResult[])
4648
4778
  }
4649
4779
 
4650
4780
  function workflowDetailsResults(children: WorkflowScriptChildResult[]): SingleResult[] {
4651
- return children.flatMap((child) => (child.results ?? []).map((result) => result.workflowKey ? result : { ...result, workflowKey: child.key }));
4781
+ return children.flatMap((child) => (child.results ?? []).map((result) => ({
4782
+ ...result,
4783
+ workflowKey: result.workflowKey ?? child.key,
4784
+ ...(child.runId && !result.runId ? { runId: child.runId } : {}),
4785
+ })));
4652
4786
  }
4653
4787
 
4654
4788
  function workflowSteerReceipt(key: string, result: AgentToolResult<Details>): WorkflowSteerResult {
@@ -4793,7 +4927,7 @@ function terminalWorkflowReceipt(
4793
4927
  resource?: WorkflowReceipt["resource"],
4794
4928
  argsDigest?: string,
4795
4929
  ): WorkflowReceipt {
4796
- return buildWorkflowReceipt({ workflowRunId, state, children, workflowChildren, terminalOutcome, hostSteps, resource, ...(argsDigest ? { argsDigest } : {}) });
4930
+ return buildWorkflowReceipt({ workflowRunId, state, children: withWorkflowRevivals(DIRS.async, workflowRunId, children), workflowChildren, terminalOutcome, hostSteps, resource, ...(argsDigest ? { argsDigest } : {}) });
4797
4931
  }
4798
4932
 
4799
4933
  function workflowFailureTerminalOutcome(error: unknown, _children: WorkflowScriptChildResult[], usageBudget: ReturnType<typeof usageBudgetState>): WorkflowTerminalOutcome | undefined {
@@ -5221,6 +5355,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5221
5355
  const workflowPermitContexts = new WeakMap<object, { root: WorkflowChildPermit } | { child: WorkflowChildPermitContext }>();
5222
5356
  const warnedArtifactPackageDirs = new Set<string>();
5223
5357
  const scheduledOwnerExecutors = new Map<string | null, Map<string, { state: SubagentState; executor: ReturnType<typeof createSubagentExecutor> }>>();
5358
+ const disabledFeatures = resolveDisabledFeatureSurface(deps.config);
5359
+ const disabledFeatureResult = (params: SubagentParamsLike): AgentToolResult<Details> | undefined => {
5360
+ const error = disabledFeatureUseError(params, disabledFeatures);
5361
+ if (!error) return undefined;
5362
+ return { content: [{ type: "text", text: error }], isError: true, details: { mode: params.action === undefined ? inferExecutionMode(params) : "management", results: [] } };
5363
+ };
5364
+ const admitEnabledWorkflowChildren = (calls: Array<{ key: string; params: Record<string, unknown> }>): void => {
5365
+ for (const call of calls) {
5366
+ const error = disabledFeatureUseError(call.params, disabledFeatures, `workflow child '${call.key}'`);
5367
+ if (error) throw new Error(error);
5368
+ }
5369
+ };
5224
5370
  const execute = async (
5225
5371
  _id: string,
5226
5372
  params: SubagentParamsLike,
@@ -5232,6 +5378,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5232
5378
  ): Promise<AgentToolResult<Details>> => {
5233
5379
  const workflowLaunchObserver = workflowLaunchObservers.get(params);
5234
5380
  const inheritedUsageBudget = workflowOwnedUsageBudgets.get(params);
5381
+ const retainedRequiredExtensions = workflowRetainedRequiredExtensions.get(params);
5235
5382
  const delegatedThinkingOverride = delegatedThinkingOverrides.get(params);
5236
5383
  const allowZeroToolBudget = delegatedZeroToolBudgets.has(params);
5237
5384
  const delegatedExecution = delegatedExecutions.has(params);
@@ -5250,18 +5397,31 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5250
5397
  const capacityOverrideError = validateWorkflowCapacityOverrides(requestParams);
5251
5398
  if (capacityOverrideError) return buildRequestedModeError(requestParams, capacityOverrideError);
5252
5399
  let workflowPreflight: import("../../shared/types.ts").WorkflowPreflight | undefined;
5400
+ // Only workflow requests read the session here; other actions (for example doctor) must not.
5401
+ const resolveWorkflowParentModel = () => parentModelOverride !== undefined
5402
+ ? parentModelOverride
5403
+ : (() => {
5404
+ const currentParentModel = normalizeParentModel(ctx.model);
5405
+ return (preserveActiveSession
5406
+ ? currentParentModel
5407
+ : rememberParentModel(deps.state, resolveCurrentSessionId(ctx.sessionManager), currentParentModel)) ?? null;
5408
+ })();
5409
+ // validate checks args with the same normalization launch uses, reported beside script errors.
5410
+ const validateWorkflowRequest = () => {
5411
+ const validation = validateWorkflowScript(requestParams.workflowScript ?? "", workflowValidationOptions(deps, requestParams, ctx.cwd, () => resolveWorkflowParentModel()?.provider));
5412
+ const normalizedArgs = normalizeWorkflowArgs(requestParams.args);
5413
+ return "error" in normalizedArgs ? { ...validation, ok: false, errors: [...validation.errors, { message: normalizedArgs.error }] } : validation;
5414
+ };
5253
5415
  try {
5254
- if (requestParams.preflight !== undefined && requestParams.workflowScript === undefined && requestParams.workflowScriptPath === undefined) {
5255
- throw new Error("preflight requires workflowScript or workflowScriptPath.");
5416
+ if (requestParams.preflight !== undefined && requestParams.workflowScript === undefined) {
5417
+ throw new Error("preflight requires workflow: true or a workflow script path.");
5256
5418
  }
5257
5419
  workflowPreflight = normalizeWorkflowPreflight(requestParams.preflight);
5258
5420
  if (workflowPreflight) requestParams = { ...requestParams, preflight: workflowPreflight };
5259
5421
  } catch (error) {
5260
5422
  const message = error instanceof Error ? error.message : String(error);
5261
5423
  if (requestParams.action?.trim() === "validate") {
5262
- const validation = validateWorkflowScript(requestParams.workflowScript ?? "", {
5263
- maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
5264
- });
5424
+ const validation = validateWorkflowRequest();
5265
5425
  const invalidValidation = { ...validation, ok: false, errors: [...validation.errors, { message }] };
5266
5426
  return {
5267
5427
  content: [{ type: "text", text: JSON.stringify(invalidValidation) }],
@@ -5272,10 +5432,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5272
5432
  return buildRequestedModeError(requestParams, message);
5273
5433
  }
5274
5434
  if (requestParams.action?.trim() === "validate") {
5275
- const validation = validateWorkflowScript(requestParams.workflowScript ?? "", {
5276
- maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
5277
- });
5278
- return buildWorkflowValidationResult(validation, "management", workflowPreflight);
5435
+ return buildWorkflowValidationResult(validateWorkflowRequest(), "management", workflowPreflight);
5279
5436
  }
5280
5437
  const normalizedAction = typeof requestParams.action === "string" ? requestParams.action.trim() : requestParams.action;
5281
5438
  if (normalizedAction === "resume" && requestParams.extensionBindings !== undefined) return buildRequestedModeError(requestParams, "extensionBindings is not supported with action='resume'; resume uses the original retained child binding.");
@@ -5290,31 +5447,29 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5290
5447
  const workflowArgsEvidence = requestParams.args === undefined ? undefined : { args: requestParams.args, argsDigest: stableJsonDigest(requestParams.args) };
5291
5448
  const workflowArgs = workflowArgsEvidence?.args;
5292
5449
  const workflowArgsDigest = workflowArgsEvidence?.argsDigest;
5293
- const workflowValidation = validateWorkflowScript(requestParams.workflowScript, {
5294
- maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
5295
- });
5450
+ const workflowParentModel = resolveWorkflowParentModel();
5451
+ const workflowValidation = validateWorkflowScript(requestParams.workflowScript, workflowValidationOptions(deps, requestParams, ctx.cwd, () => workflowParentModel?.provider));
5296
5452
  if (!workflowValidation.ok && publicExecution) return buildWorkflowValidationResult(workflowValidation, "workflow", workflowPreflight);
5297
- const spawnBudgetErrors = workflowValidation.errors.filter((error) => error.kind === "spawn-budget");
5298
- if (spawnBudgetErrors.length > 0) {
5299
- return buildRequestedModeError(requestParams, `Workflow '${_id}' validation failed before child launch; no children launched. ${spawnBudgetErrors.map((error) => error.message).join(" ")}`);
5453
+ const launchBlockingErrors = workflowValidation.errors.filter((error) => error.kind === "spawn-budget" || error.kind === "agent");
5454
+ if (launchBlockingErrors.length > 0) {
5455
+ return buildRequestedModeError(requestParams, `Workflow '${_id}' validation failed before child launch; no children launched. ${launchBlockingErrors.map((error) => error.message).join(" ")}`);
5456
+ }
5457
+ // A package chain's per-step stop check defeats static launch counting; runtime fan-out enforcement still applies.
5458
+ const structuredResource = workflowResource?.provenance.name === "chain" || workflowResource?.provenance.name === "tasks";
5459
+ for (const warning of workflowValidation.warnings ?? []) {
5460
+ if (!(structuredResource && warning.kind === "dynamic-spawn-count")) console.warn(`[pi-subagents] ${warning.message}`);
5300
5461
  }
5301
- for (const warning of workflowValidation.warnings ?? []) console.warn(`[pi-subagents] ${warning.message}`);
5302
5462
  const acceptanceErrors = validateAcceptanceInput(requestParams.acceptance);
5303
5463
  if (acceptanceErrors.length > 0) return buildRequestedModeError(requestParams, acceptanceErrors.join(" "));
5464
+ // Capture mandatory host extensions at admission: script children may launch after the host disposes its registration.
5465
+ const admittedRequiredExtensions = retainedRequiredExtensions ?? deps.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(ctx.sessionManager.getSessionId() ?? undefined);
5466
+ const workflowRequiredExtensions = hasMandatoryRequiredChildExtensions(admittedRequiredExtensions) ? admittedRequiredExtensions : undefined;
5304
5467
  const foregroundWorkflowRunId = encodeIndexSegment(_id);
5305
5468
  if (delegatedWorkflowPermit) {
5306
5469
  const permitError = validateWorkflowChildPermitRoot(delegatedWorkflowPermit, foregroundWorkflowRunId);
5307
5470
  if (permitError) return buildRequestedModeError(requestParams, permitError);
5308
5471
  if (requestParams.async !== false) return buildRequestedModeError(requestParams, "Workflow child permit supports foreground workflow roots only; set async:false.");
5309
5472
  }
5310
- const workflowParentModel = parentModelOverride !== undefined
5311
- ? parentModelOverride
5312
- : (() => {
5313
- const currentParentModel = normalizeParentModel(ctx.model);
5314
- return (preserveActiveSession
5315
- ? currentParentModel
5316
- : rememberParentModel(deps.state, resolveCurrentSessionId(ctx.sessionManager), currentParentModel)) ?? null;
5317
- })();
5318
5473
  if (requestParams.extensionBindings !== undefined) {
5319
5474
  try {
5320
5475
  requestParams.extensionBindings = normalizeExtensionBindings(requestParams.extensionBindings)!.value;
@@ -5323,6 +5478,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5323
5478
  }
5324
5479
  }
5325
5480
  const parentCwd = ctx.cwd;
5481
+ for (const [name, value] of [["timeoutMs", requestParams.timeoutMs], ["maxRuntimeMs", requestParams.maxRuntimeMs]] as const) {
5482
+ if (value === undefined) continue;
5483
+ const overflowError = timerDelayOverflowError(name, value);
5484
+ if (overflowError) return buildRequestedModeError(requestParams, overflowError);
5485
+ }
5326
5486
  const timeout = requestParams.timeoutMs ?? requestParams.maxRuntimeMs ?? (requestParams.async === false ? resolveConfigDefaultTimeoutMs(deps.config.timeoutMs) ?? DEFAULT_FOREGROUND_TIMEOUT_MS : undefined);
5327
5487
  const workflowUsageBudget = validateUsageBudgetConfig(requestParams.usageBudget ?? deps.config.usageBudget, requestParams.usageBudget ? "usageBudget" : "config.usageBudget");
5328
5488
  if (workflowUsageBudget.error) return buildRequestedModeError(requestParams, workflowUsageBudget.error);
@@ -5428,6 +5588,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5428
5588
  const workflowCapabilityCeiling = intersectSubagentCapabilityCeilings(requestParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(currentSessionId));
5429
5589
  const completionOwnerId = deps.state.completionOwnerId ?? currentCompletionOwnerId();
5430
5590
  deps.state.completionOwnerId = completionOwnerId;
5591
+ const workflowScriptSourceDigest = workflowScriptDigest(requestParams.workflowScript);
5592
+ const workflowReuseSource = findWorkflowReuseSource(DIRS.async, currentSessionId, workflowScriptSourceDigest, workflowArgsDigest);
5593
+ const workflowRunEvidence: Pick<NonNullable<AsyncStatus["workflow"]>, "args" | "argsDigest" | "scriptDigest" | "reusedFrom" | "stopCause"> = { ...workflowArgsEvidence, scriptDigest: workflowScriptSourceDigest };
5594
+ if (workflowReuseSource) workflowRunEvidence.reusedFrom = workflowReuseSource.runId;
5595
+ const workflowJournalFingerprints = new Map<string, string>();
5431
5596
  try {
5432
5597
  fs.mkdirSync(asyncDir, { recursive: true });
5433
5598
  writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
@@ -5459,7 +5624,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5459
5624
  ...(workflowCapabilityCeiling ? { admissionCapabilityCeiling: workflowCapabilityCeiling } : {}),
5460
5625
  steps: [],
5461
5626
  ...(workflowPreflight ? { preflight: workflowPreflight } : {}),
5462
- workflow: { trace: [], emits: [], console: [], ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}) },
5627
+ workflow: { trace: [], emits: [], console: [], ...workflowRunEvidence, ...(workflowResource ? { resource: workflowResource.provenance } : {}) },
5463
5628
  workflowChildren: workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState: "running", inventoryComplete: false }),
5464
5629
  runFanoutBudget: getRunFanoutBudgetSnapshot(workflowFanoutBudget),
5465
5630
  };
@@ -5951,6 +6116,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5951
6116
  workflowSteps.set(entry.key, step);
5952
6117
  }
5953
6118
  const projectedStep = workflowSteps.get(entry.key);
6119
+ if (entry.reused && projectedStep) projectedStep.reused = true;
5954
6120
  if (entry.state === "stopped" && projectedStep) {
5955
6121
  appendWorkflowEvent({
5956
6122
  type: "subagent.child-status",
@@ -5984,7 +6150,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5984
6150
  timeoutMs: timeout,
5985
6151
  signal: controller.signal,
5986
6152
  continueAfterAbortWhenChildrenSettled: (abortError) => {
5987
- if (abortError.message !== "Workflow stopped because the extension session was replaced or reloaded.") return false;
6153
+ if (!workflowStopCause(abortError)) return false;
5988
6154
  const activeAsyncChild = [...(deps.state.asyncJobs?.values() ?? [])].some((job) => job.parentWorkflowRunId === workflowRunId && (job.status === "queued" || job.status === "running"));
5989
6155
  const activeForegroundChild = [...deps.state.foregroundControls.values()].some((control) => control.parentWorkflowRunId === workflowRunId && (control.activeChildren?.size ?? 0) > 0);
5990
6156
  return !activeAsyncChild && !activeForegroundChild;
@@ -5996,6 +6162,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5996
6162
  ...(workflowState ? { state: workflowState } : {}),
5997
6163
  onTrace: updateTrace,
5998
6164
  onChildSettled: (notification) => {
6165
+ const journalFingerprint = workflowJournalFingerprints.get(notification.childKey);
6166
+ if (journalFingerprint) appendWorkflowChildJournal(asyncDir, { type: "settle", key: notification.childKey, fingerprint: journalFingerprint, result: notification.result });
5999
6167
  appendWorkflowEvent({
6000
6168
  type: "subagent.workflow.child_settled",
6001
6169
  childKey: notification.childKey,
@@ -6030,6 +6198,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6030
6198
  } });
6031
6199
  },
6032
6200
  admit: async (calls, admissionSignal) => {
6201
+ admitEnabledWorkflowChildren(calls);
6033
6202
  await preflightWorkflowWorktrees({ workflowDefaults: workflowChildDefaults, defaultWorktree: deps.config.worktree, calls, ctxCwd: parentCwd, signal: admissionSignal, deadlineAt: workflowDeadlineAt });
6034
6203
  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 });
6035
6204
  if (outputClaims.error) throw new Error(outputClaims.error);
@@ -6046,6 +6215,32 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6046
6215
  appendWorkflowEvent({ type: "subagent.workflow.emit", value: emits.at(-1) });
6047
6216
  },
6048
6217
  launch: async (key, childParams, workflowSignal, admission) => {
6218
+ const journalFingerprint = workflowJournalFingerprints.get(key) ?? workflowChildFingerprint(childParams);
6219
+ workflowJournalFingerprints.set(key, journalFingerprint);
6220
+ const priorChild = workflowReuseSource ? matchWorkflowReuse(workflowReuseSource, key, journalFingerprint) : undefined;
6221
+ if (priorChild?.kind === "settled") {
6222
+ if (priorChild.result.runId) workflowChildRunIds.set(key, priorChild.result.runId);
6223
+ return { ...priorChild.result, reused: true };
6224
+ }
6225
+ if (priorChild?.kind === "started") {
6226
+ // The previous run's awaited async child may still be running: wait for that exact run
6227
+ // instead of launching again. Journal it first so another reload can re-attach too.
6228
+ const priorRunId = priorChild.runId;
6229
+ const priorAsyncDir = path.join(DIRS.async, priorRunId);
6230
+ appendWorkflowChildJournal(asyncDir, { type: "start", key, fingerprint: journalFingerprint, runId: priorRunId });
6231
+ const stopListener = stopAwaitedAsyncChildOnAbort(workflowSignal, deps.state, priorRunId, priorAsyncDir, deps.kill);
6232
+ const reattached = await awaitExistingAsyncRun(priorAsyncDir, priorRunId, workflowSignal).finally(stopListener.remove);
6233
+ const claimedPath = reattached.status === "settled" ? claimWorkflowAwaitedResult(priorAsyncDir, workflowRunId) : undefined;
6234
+ if (reattached.status === "settled" && claimedPath) {
6235
+ 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 });
6236
+ const reattachedResult = workflowChildResult(key, imported, childParams, deps.state);
6237
+ // Like a settled journal match: only a successful child is reused; a failed or stopped one launches fresh.
6238
+ if (reattachedResult.ok) {
6239
+ workflowChildRunIds.set(key, priorRunId);
6240
+ return { ...reattachedResult, reused: true };
6241
+ }
6242
+ }
6243
+ }
6049
6244
  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);
6050
6245
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
6051
6246
  if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state, { state: "partial", reason: "budget_exhausted" });
@@ -6069,7 +6264,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6069
6264
  );
6070
6265
  preparedChildParams = childRequest;
6071
6266
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
6267
+ if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
6072
6268
  workflowLaunchObservers.set(childRequest, (launch) => {
6269
+ if (launch.runId) appendWorkflowChildJournal(asyncDir, { type: "start", key, fingerprint: journalFingerprint, runId: launch.runId });
6073
6270
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
6074
6271
  if (step) {
6075
6272
  step.agent = launch.agent;
@@ -6145,16 +6342,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6145
6342
  });
6146
6343
  const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, workflow.trace, { settled: true });
6147
6344
  const finalPreflightTrace = annotateWorkflowPreflightTrace(workflow.trace, workflowPreflight);
6148
- const returnPreview = formatWorkflowValue(workflow.value).slice(0, 1_000);
6149
- const emitPreview = workflow.emits.length > 0 ? ` Emitted: ${workflow.emits.map(formatWorkflowValue).join(", ").slice(0, 1_000)}` : "";
6345
+ const returnText = formatWorkflowValue(workflow.value);
6346
+ const emitText = workflow.emits.map(formatWorkflowValue).join(", ");
6347
+ const returnPreview = returnText.length > 1_000 ? `${returnText.slice(0, 1_000)}…` : returnText;
6348
+ const emitPreview = workflow.emits.length > 0 ? ` Emitted: ${emitText.length > 1_000 ? `${emitText.slice(0, 1_000)}…` : emitText}` : "";
6349
+ const previewNote = returnText.length > 1_000 || emitText.length > 1_000 ? ` (truncated; full return value and emits: ${statusPath} (workflow.value, workflow.emits))` : "";
6150
6350
  const runningSummary = workflowRunningChildrenSummary(workflow.children);
6151
- const summary = `${runningSummary ? `Workflow dispatch completed; ${runningSummary}` : `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(" ")}` : ""}`;
6351
+ 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(" ")}` : ""}`;
6152
6352
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, summary, producedChildOutputPaths);
6153
6353
  const resultSummary = appendWorkflowOutputWarning(summary, outputWarning);
6154
6354
  const workflowUsage = sumResultsUsage(workflowResults);
6155
6355
  settleWorkflowSteerInbox("complete");
6156
6356
  const workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children, steps: status.steps });
6157
- 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) };
6357
+ 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) };
6158
6358
  const receipt = terminalWorkflowReceipt(workflowRunId, "complete", workflow.children, workflowChildren, undefined, validHostStepNodes(status.workflowGraph), workflowResource?.provenance, workflowArgsDigest);
6159
6359
  delete status.workflowReceiptPath;
6160
6360
  let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
@@ -6173,6 +6373,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6173
6373
  } catch (error) {
6174
6374
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
6175
6375
  const stopped = controller.signal.aborted;
6376
+ const stopCause = stopped ? workflowStopCause(controller.signal.reason) : undefined;
6377
+ if (stopCause) workflowRunEvidence.stopCause = stopCause;
6176
6378
  const detachedChildKeys = new Set(partial.children.filter((child) => child.detached).map((child) => child.key));
6177
6379
  const hasRealFailedChild = partial.children.some((child) => !child.ok && child.state !== "running" && !child.detached);
6178
6380
  const pauseForDetached = !stopped && error instanceof WorkflowScriptError && error.errorKind === "detached-child" && detachedChildKeys.size > 0 && !hasRealFailedChild;
@@ -6193,14 +6395,16 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6193
6395
  const workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState, inventoryComplete: true, trace: partial.trace, children: partial.children, steps: status.steps });
6194
6396
  const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, partial.trace, { settled: true });
6195
6397
  const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
6196
- 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 });
6398
+ 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 });
6197
6399
  if (pauseForDetached) {
6198
6400
  const promoted = promotePausedWorkflowIfSettled(status);
6199
6401
  if (promoted) status = promoted;
6200
6402
  }
6403
+ // A script can throw an error of any size; status.json keeps the full text.
6404
+ const errorPreview = status.error && status.error.length > 1_000 ? `${status.error.slice(0, 1_000)}… (truncated; full error: ${statusPath} (error))` : status.error;
6201
6405
  const terminalSummary = `${status.state === "complete"
6202
6406
  ? "Workflow completed after detached child finished."
6203
- : status.error ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.")}${workflowOutputPathMappingSummary(partial.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
6407
+ : errorPreview ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.")}${stopCause ? ` ${WORKFLOW_RUNTIME_REPLACED_RELAUNCH_NOTICE}` : ""}${workflowOutputPathMappingSummary(partial.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
6204
6408
  const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, terminalSummary, producedChildOutputPaths);
6205
6409
  const resultSummary = appendWorkflowOutputWarning(terminalSummary, outputWarning);
6206
6410
  const receiptState: WorkflowReceiptState = status.state === "complete" ? "complete" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "failed";
@@ -6243,6 +6447,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6243
6447
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
6244
6448
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
6245
6449
  const workflowAggregateOutputPath = resolveSingleOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, foregroundWorkflowRunId));
6450
+ // A top-level artifact file: outside outputs/, where children save their reports, and
6451
+ // within artifact retention, which only removes top-level files.
6452
+ const workflowFullResultPath = path.join(workflowArtifactsDir, `${sanitizeRunPathSegment(foregroundWorkflowRunId)}_workflow-result.md`);
6246
6453
  const claimedOutputPaths = new Map<string, string>();
6247
6454
  const childOutputOverrides = new Map<string, string>();
6248
6455
  const childOutputClaimPaths = new Map<string, string>();
@@ -6303,6 +6510,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6303
6510
  sendWorkflowProgress();
6304
6511
  },
6305
6512
  admit: async (calls, admissionSignal) => {
6513
+ admitEnabledWorkflowChildren(calls);
6306
6514
  await preflightWorkflowWorktrees({ workflowDefaults: workflowChildDefaults, defaultWorktree: deps.config.worktree, calls, ctxCwd: ctx.cwd, signal: admissionSignal, deadlineAt: workflowDeadlineAt });
6307
6515
  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 });
6308
6516
  if (outputClaims.error) throw new Error(outputClaims.error);
@@ -6342,6 +6550,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6342
6550
  );
6343
6551
  preparedChildParams = childRequest;
6344
6552
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
6553
+ if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
6345
6554
  if (delegatedWorkflowPermit) {
6346
6555
  if (childRequest.async !== false) throw new Error("Workflow child permit supports one foreground child only.");
6347
6556
  const childCwd = resolveRequestedCwd(workflowCwd, childRequest.cwd);
@@ -6402,22 +6611,26 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6402
6611
  const finalPreflightTrace = annotateWorkflowPreflightTrace(workflow.trace, workflowPreflight);
6403
6612
  const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children });
6404
6613
  const receipt = terminalWorkflowReceipt(foregroundWorkflowRunId, "complete", workflow.children, workflowChildren, undefined, [...workflowHostSteps.values()], workflowResource?.provenance, workflowArgsDigest);
6405
- 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}` : ""}`);
6614
+ 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 }));
6406
6615
  const runningSummary = workflowRunningChildrenSummary(workflow.children);
6407
- const sections = [
6408
- ...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []),
6409
- runningSummary ? `Workflow dispatch completed; ${runningSummary}` : "Workflow completed.",
6410
- `Return:\n${formatWorkflowValue(workflow.value)}`,
6411
- ];
6412
- if (workflow.emits.length > 0) sections.push(`Emitted:\n${workflow.emits.map(formatWorkflowValue).join("\n")}`);
6413
- if (workflow.console.length > 0) sections.push(`Console:\n${workflow.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
6414
- if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
6415
- if (finalPreflightWarnings.length > 0) sections.push(formatWorkflowPreflightWarnings(finalPreflightWarnings));
6416
6616
  const outputMappings = workflowOutputPathMappingSummary(workflow.children).trim();
6417
- if (outputMappings) sections.push(outputMappings);
6418
- const workflowText = sections.join("\n\n");
6419
- const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText, producedChildOutputPaths);
6420
- const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
6617
+ const displayText = formatWorkflowResultText({
6618
+ head: [...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []), runningSummary ? `Workflow dispatch completed; ${runningSummary}` : "Workflow completed."],
6619
+ script: [
6620
+ `Return:\n${formatWorkflowValue(workflow.value)}`,
6621
+ ...(workflow.emits.length > 0 ? [`Emitted:\n${workflow.emits.map(formatWorkflowValue).join("\n")}`] : []),
6622
+ ...(workflow.console.length > 0 ? [`Console:\n${workflow.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`] : []),
6623
+ ],
6624
+ trace,
6625
+ tail: [
6626
+ ...(finalPreflightWarnings.length > 0 ? [formatWorkflowPreflightWarnings(finalPreflightWarnings)] : []),
6627
+ ...(outputMappings ? [outputMappings] : []),
6628
+ ],
6629
+ maxOutput: requestParams.maxOutput,
6630
+ aggregateOutputPath: workflowAggregateOutputPath,
6631
+ fullResultPath: workflowFullResultPath,
6632
+ producedChildOutputPaths,
6633
+ });
6421
6634
  return attachWorkflowMission(withRunFanoutBudget({
6422
6635
  content: [{ type: "text", text: displayText }],
6423
6636
  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 }),
@@ -6427,27 +6640,32 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6427
6640
  const text = workflowFailureMessage(error, foregroundWorkflowRunId, partial.children);
6428
6641
  const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, partial.trace, { settled: true });
6429
6642
  const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
6430
- const traceLines = finalPreflightTrace.map((entry) => `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.warning ? ` — ${entry.warning}` : ""}${entry.error ? ` — ${entry.error}` : ""}`);
6431
- const sections = [
6432
- ...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []),
6433
- `Workflow failed: ${text}`,
6434
- ];
6435
- if (partial.emits.length > 0) sections.push(`Emitted:\n${partial.emits.map(formatWorkflowValue).join("\n")}`);
6436
- if (partial.console.length > 0) sections.push(`Console:\n${partial.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
6437
- if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
6438
- if (finalPreflightWarnings.length > 0) sections.push(formatWorkflowPreflightWarnings(finalPreflightWarnings));
6643
+ const trace = finalPreflightTrace.map((entry) => ({ line: `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.warning ? ` — ${entry.warning}` : ""}`, error: entry.error }));
6439
6644
  const outputMappings = workflowOutputPathMappingSummary(partial.children).trim();
6440
- if (outputMappings) sections.push(outputMappings);
6441
- const workflowText = sections.join("\n\n");
6442
- const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText, producedChildOutputPaths);
6443
- const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
6645
+ const displayText = formatWorkflowResultText({
6646
+ head: workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : [],
6647
+ script: [
6648
+ `Workflow failed: ${text}`,
6649
+ ...(partial.emits.length > 0 ? [`Emitted:\n${partial.emits.map(formatWorkflowValue).join("\n")}`] : []),
6650
+ ...(partial.console.length > 0 ? [`Console:\n${partial.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`] : []),
6651
+ ],
6652
+ trace,
6653
+ tail: [
6654
+ ...(finalPreflightWarnings.length > 0 ? [formatWorkflowPreflightWarnings(finalPreflightWarnings)] : []),
6655
+ ...(outputMappings ? [outputMappings] : []),
6656
+ ],
6657
+ maxOutput: requestParams.maxOutput,
6658
+ aggregateOutputPath: workflowAggregateOutputPath,
6659
+ fullResultPath: workflowFullResultPath,
6660
+ producedChildOutputPaths,
6661
+ });
6444
6662
  const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "failed", inventoryComplete: true, trace: partial.trace, children: partial.children });
6445
6663
  const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
6446
6664
  const receipt = terminalWorkflowReceipt(foregroundWorkflowRunId, "failed", partial.children, workflowChildren, terminalOutcome, [...workflowHostSteps.values()], workflowResource?.provenance, workflowArgsDigest);
6447
6665
  return attachWorkflowMission(withRunFanoutBudget({
6448
6666
  content: [{ type: "text", text: displayText }],
6449
6667
  isError: true,
6450
- 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 }),
6668
+ 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 }),
6451
6669
  }, workflowFanoutBudget));
6452
6670
  } finally {
6453
6671
  workflowProgressClosed = true;
@@ -6572,7 +6790,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6572
6790
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
6573
6791
  }
6574
6792
  }
6575
- const policyAction = action === "stop" ? "stopRun" : action === "steer" ? "steerRun" : action === "schedule.create" ? "scheduleCreate" : action === "inspector.open" ? "inspectorOpen" : action === "project.open" ? "projectOpen" : undefined;
6793
+ const policyAction = action === "stop" || action === "command.cancel" ? "stopRun" : action === "steer" || action === "command.yield" ? "steerRun" : action === "schedule.create" ? "scheduleCreate" : action === "inspector.open" ? "inspectorOpen" : action === "project.open" ? "projectOpen" : undefined;
6576
6794
  if (policyAction) {
6577
6795
  // Child-safe mode is a hard capability boundary; the policy is an operator
6578
6796
  // preference. Refuse first, so the gate never prompts for an action that is
@@ -6733,8 +6951,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6733
6951
  }
6734
6952
  if (action === "guide") {
6735
6953
  try {
6954
+ const guide = readSubagentGuide(paramsWithResolvedCwd.topic);
6955
+ const notice = paramsWithResolvedCwd.topic === "tool-reference" ? disabledFeatureNotice(disabledFeatures) : undefined;
6736
6956
  return {
6737
- content: [{ type: "text", text: readSubagentGuide(paramsWithResolvedCwd.topic) }],
6957
+ content: [{ type: "text", text: notice ? `${notice}\n\n${guide}` : guide }],
6738
6958
  details: { mode: "management", results: [] },
6739
6959
  };
6740
6960
  } catch (error) {
@@ -6793,6 +7013,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6793
7013
  details: { mode: "management", results: [], spawnBudget, activeAsyncCapacity },
6794
7014
  };
6795
7015
  }
7016
+ if (["command.status", "command.yield", "command.cancel"].includes(action)) {
7017
+ try {
7018
+ if (deps.allowMutatingManagementActions === false && action !== "command.status") throw new Error(`Action '${action}' is not available from child-safe subagent fanout mode.`);
7019
+ const targetRunId = paramsWithResolvedCwd.id ?? paramsWithResolvedCwd.runId;
7020
+ if (!targetRunId || paramsWithResolvedCwd.dir) throw new Error(`${action} requires id or runId; directory targets are not supported.`);
7021
+ deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
7022
+ const target = resolveSubagentRunId(targetRunId, { state: deps.state, nested: nestedResolutionScopeForExecutor(deps) });
7023
+ if (!target) throw new Error(`No run found for '${targetRunId}'.`);
7024
+ return await commandAction({ state: deps.state, target, operation: action.slice("command.".length) as "status" | "yield" | "cancel", index: paramsWithResolvedCwd.index, toolCallId: paramsWithResolvedCwd.toolCallId, signal });
7025
+ } catch (error) {
7026
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
7027
+ }
7028
+ }
6796
7029
  if (action === "status" || action === "debug.run") {
6797
7030
  if (!preserveActiveSession) deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
6798
7031
  const targetRunId = paramsWithResolvedCwd.id ?? paramsWithResolvedCwd.runId;
@@ -6951,7 +7184,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6951
7184
  }
6952
7185
  if (action.startsWith("schedule.")) {
6953
7186
  if (!isScheduledRunAction(action)) {
6954
- return { content: [{ type: "text", text: unknownSubagentActionMessage(action) }], isError: true, details: { mode: "management", results: [] } };
7187
+ return { content: [{ type: "text", text: unknownSubagentActionMessage(action, disabledFeatures) }], isError: true, details: { mode: "management", results: [] } };
6955
7188
  }
6956
7189
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
6957
7190
  return {
@@ -6993,47 +7226,40 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6993
7226
  }
6994
7227
  if (action === "stop") {
6995
7228
  const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
6996
- const workflowController = targetRunId ? deps.state.workflowControllers?.get(targetRunId) : undefined;
6997
- if (workflowController && targetRunId) {
6998
- const stopChild = deps.state.workflowChildStops?.get(targetRunId);
6999
- if (paramsWithResolvedCwd.childId !== undefined) {
7000
- const workflowRunId = targetRunId;
7001
- const asyncJob = deps.state.asyncJobs.get(workflowRunId);
7002
- if (!asyncJob?.asyncDir) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
7003
- const status = readStatus(asyncJob.asyncDir);
7004
- if (!status) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
7005
- const resolution = resolveAsyncStatusChild(status, paramsWithResolvedCwd.childId);
7006
- if (!resolution.ok) return { content: [{ type: "text", text: resolution.message }], isError: true, details: { mode: "management", results: [] } };
7007
- 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: [] } };
7008
- if (!stopChild) return { content: [{ type: "text", text: `Workflow ${targetRunId} child stop is unavailable in this extension runtime.` }], isError: true, details: { mode: "management", results: [] } };
7009
- 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: [] } };
7010
- try {
7011
- fs.appendFileSync(path.join(asyncJob.asyncDir, "events.jsonl"), `${JSON.stringify({
7012
- type: "subagent.child-status",
7013
- version: 1,
7014
- runId: workflowRunId,
7015
- childId: resolution.child.id,
7016
- status: "stopping",
7017
- ts: Date.now(),
7018
- reason: "subagent-action",
7019
- source: "async",
7020
- stepIndex: resolution.child.index,
7021
- agent: resolution.child.step.agent,
7022
- ...(resolution.child.step.runId ? { childRunId: resolution.child.step.runId } : {}),
7023
- ...(resolution.child.step.workflowKey ? { workflowKey: resolution.child.step.workflowKey } : {}),
7024
- ...(resolution.child.step.phase ? { phase: resolution.child.step.phase } : {}),
7025
- ...(resolution.child.step.label ? { label: resolution.child.step.label } : {}),
7026
- } satisfies SubagentChildStatusEvent)}\n`, "utf-8");
7027
- } catch (error) {
7028
- console.error(`Failed to append child status event for workflow ${workflowRunId}:`, error);
7029
- }
7030
- return { content: [{ type: "text", text: `Stop requested for child ${resolution.child.id} in async workflow ${workflowRunId}.` }], details: { mode: "management", results: [] } };
7229
+ // Whole-workflow stops reach stopAsyncRun below, which stops a live workflow in-process.
7230
+ const workflowRunId = targetRunId && paramsWithResolvedCwd.childId !== undefined ? resolveLiveWorkflowRunId(deps, targetRunId) : undefined;
7231
+ if (workflowRunId && paramsWithResolvedCwd.childId !== undefined) {
7232
+ const stopChild = deps.state.workflowChildStops?.get(workflowRunId);
7233
+ const asyncJob = deps.state.asyncJobs.get(workflowRunId);
7234
+ if (!asyncJob?.asyncDir) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
7235
+ const status = readStatus(asyncJob.asyncDir);
7236
+ if (!status) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
7237
+ const resolution = resolveAsyncStatusChild(status, paramsWithResolvedCwd.childId);
7238
+ if (!resolution.ok) return { content: [{ type: "text", text: resolution.message }], isError: true, details: { mode: "management", results: [] } };
7239
+ 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: [] } };
7240
+ if (!stopChild) return { content: [{ type: "text", text: `Workflow ${workflowRunId} child stop is unavailable in this extension runtime.` }], isError: true, details: { mode: "management", results: [] } };
7241
+ 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: [] } };
7242
+ try {
7243
+ fs.appendFileSync(path.join(asyncJob.asyncDir, "events.jsonl"), `${JSON.stringify({
7244
+ type: "subagent.child-status",
7245
+ version: 1,
7246
+ runId: workflowRunId,
7247
+ childId: resolution.child.id,
7248
+ status: "stopping",
7249
+ ts: Date.now(),
7250
+ reason: "subagent-action",
7251
+ source: "async",
7252
+ stepIndex: resolution.child.index,
7253
+ agent: resolution.child.step.agent,
7254
+ ...(resolution.child.step.runId ? { childRunId: resolution.child.step.runId } : {}),
7255
+ ...(resolution.child.step.workflowKey ? { workflowKey: resolution.child.step.workflowKey } : {}),
7256
+ ...(resolution.child.step.phase ? { phase: resolution.child.step.phase } : {}),
7257
+ ...(resolution.child.step.label ? { label: resolution.child.step.label } : {}),
7258
+ } satisfies SubagentChildStatusEvent)}\n`, "utf-8");
7259
+ } catch (error) {
7260
+ console.error(`Failed to append child status event for workflow ${workflowRunId}:`, error);
7031
7261
  }
7032
- const asyncJob = deps.state.asyncJobs.get(targetRunId);
7033
- const status = asyncJob?.asyncDir ? readStatus(asyncJob.asyncDir) : undefined;
7034
- if (status) stopStoppableAsyncStatusChildren(status, stopChild, "Workflow stopped.");
7035
- workflowController.abort(new Error("Workflow stopped."));
7036
- return { content: [{ type: "text", text: `Stop requested for async workflow ${targetRunId}.` }], details: { mode: "management", results: [] } };
7262
+ return { content: [{ type: "text", text: `Stop requested for child ${resolution.child.id} in async workflow ${workflowRunId}.` }], details: { mode: "management", results: [] } };
7037
7263
  }
7038
7264
  let resolved: ResolvedSubagentRunId | undefined;
7039
7265
  if (paramsWithResolvedCwd.dir) {
@@ -7113,7 +7339,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7113
7339
  }
7114
7340
  if (!(SUBAGENT_ACTIONS as readonly string[]).includes(action)) {
7115
7341
  return {
7116
- content: [{ type: "text", text: unknownSubagentActionMessage(action) }],
7342
+ content: [{ type: "text", text: unknownSubagentActionMessage(action, disabledFeatures) }],
7117
7343
  isError: true,
7118
7344
  details: { mode: "management" as const, results: [] },
7119
7345
  };
@@ -7507,12 +7733,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7507
7733
  toolBudget: runToolBudget.toolBudget,
7508
7734
  usageBudget: usageBudget.budget,
7509
7735
  inheritedUsageBudget,
7736
+ requiredExtensions: retainedRequiredExtensions,
7510
7737
  allowZeroToolBudget,
7511
7738
  configToolBudget: configToolBudget.toolBudget,
7512
7739
  configToolTimeoutMs: deps.config.toolTimeoutMs,
7513
7740
  contextPolicy,
7514
7741
  modelScope,
7515
7742
  parentModel: requestParentModel,
7743
+ scopedModelIds: scopedModelIdsFromContext(ctx),
7516
7744
  parentSessionId: requestSessionId,
7517
7745
  parentPiSessionId: requestPiSessionId,
7518
7746
  capabilityCeiling: intersectSubagentCapabilityCeilings(effectiveParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(requestSessionId)),
@@ -7604,6 +7832,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7604
7832
  params: effectiveParams,
7605
7833
  agents,
7606
7834
  parentModel: requestParentModel,
7835
+ scopedModelIds: scopedModelIdsFromContext(ctx),
7607
7836
  availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
7608
7837
  currentProvider: requestParentModel?.provider,
7609
7838
  modelScope,
@@ -7641,7 +7870,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7641
7870
  agents: agentsForSummary,
7642
7871
  ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.model : details?.results[0]?.model) ? { model: type === "subagent.nested.started" ? startedLaunches[0]?.model : details?.results[0]?.model } : {}),
7643
7872
  ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.thinking : details?.results[0]?.thinking) ? { thinking: type === "subagent.nested.started" ? startedLaunches[0]?.thinking : details?.results[0]?.thinking } : {}),
7644
- ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox) ? { sandbox: type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox } : {}),
7873
+ ...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox) ? { sandbox: type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox } : {}),
7645
7874
  startedAt: foregroundControl?.startedAt ?? now,
7646
7875
  ...(state !== "running" ? { endedAt: now } : {}),
7647
7876
  lastUpdate: now,
@@ -7653,7 +7882,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7653
7882
  status: "running" as const,
7654
7883
  ...(launch.model ? { model: launch.model } : {}),
7655
7884
  ...(launch.thinking ? { thinking: launch.thinking } : {}),
7656
- ...(launch.sandbox ? { sandbox: launch.sandbox } : {}),
7885
+ ...(launch.sandbox ? { sandbox: launch.sandbox } : {}),
7657
7886
  })) }
7658
7887
  : details?.results.length
7659
7888
  ? { steps: details.results.map((child) => ({
@@ -7662,7 +7891,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7662
7891
  status: child.interrupted || child.detached ? "paused" as const : child.exitCode === 0 ? "complete" as const : "failed" as const,
7663
7892
  ...(child.model ? { model: child.model } : {}),
7664
7893
  ...(child.thinking ? { thinking: child.thinking } : {}),
7665
- ...(child.sandbox ? { sandbox: child.sandbox } : {}),
7894
+ ...(child.sandbox ? { sandbox: child.sandbox } : {}),
7666
7895
  ...(child.sessionFile ? { sessionFile: child.sessionFile } : {}),
7667
7896
  ...(child.error ? { error: child.error } : {}),
7668
7897
  })) }
@@ -7764,28 +7993,47 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7764
7993
  onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
7765
7994
  ctx: ExtensionContext,
7766
7995
  ): Promise<AgentToolResult<Details>> => {
7767
- const normalized = normalizePublicSubagentExecution(params);
7996
+ const disabledFeatureError = disabledFeatureResult(params);
7997
+ if (disabledFeatureError) return Promise.resolve(disabledFeatureError);
7998
+ const normalized = normalizePublicSubagentExecution(params, { structuredWorkflows: disabledFeatures.features.has("workflow-scripts") });
7768
7999
  if (!normalized.ok) {
7769
8000
  return Promise.resolve({ content: [{ type: "text", text: normalized.error }], isError: true, details: { mode: normalized.mode, results: [] } });
7770
8001
  }
7771
8002
  let publicParams = normalized.params as SubagentParamsLike;
7772
- if (publicParams.workflow !== undefined) {
7773
- const resolved = resolveWorkflowResource(publicParams.workflow, publicParams.args, ctx.sessionManager.getSessionId() ?? undefined);
7774
- if (!resolved.ok) return Promise.resolve({ content: [{ type: "text", text: resolved.error }], isError: true, details: { mode: "workflow", results: [] } });
8003
+ const workflow = publicParams.workflow;
8004
+ const errorResult = (text: string): Promise<AgentToolResult<Details>> => Promise.resolve({ content: [{ type: "text", text }], isError: true, details: { mode: publicParams.action ? "management" : "workflow", results: [] } });
8005
+ // Models tend to put script text in the workflow string; say how to pass it instead.
8006
+ 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 }).";
8007
+ if (publicParams.tasks !== undefined || publicParams.chain !== undefined) {
8008
+ // Normalization admits chain/tasks only with workflow scripts disabled; the original input was checked above.
8009
+ const kind = publicParams.tasks !== undefined ? "tasks" : "chain";
8010
+ const resolved = resolveStructuredWorkflowResource({ kind, steps: publicParams[kind], task: publicParams.task });
8011
+ if (!resolved.ok) return errorResult(resolved.error);
8012
+ const { tasks: _tasks, chain: _chain, task: _task, ...withoutStructuredInput } = publicParams;
8013
+ publicParams = { ...withoutStructuredInput, workflowScript: resolved.resource.script };
8014
+ workflowResourcePermits.set(publicParams, resolved.resource.permit);
8015
+ } else if (typeof workflow === "string" && !isWorkflowScriptPath(workflow)) {
8016
+ const resolved = resolveWorkflowResource(workflow, publicParams.args, ctx.sessionManager.getSessionId() ?? undefined);
8017
+ if (!resolved.ok) return Promise.resolve({ content: [{ type: "text", text: resolved.error + scriptTextHint }], isError: true, details: { mode: "workflow", results: [] } });
7775
8018
  const { workflow: _workflow, args: _args, ...withoutResourceInput } = publicParams;
7776
8019
  publicParams = { ...withoutResourceInput, workflowScript: resolved.resource.script };
7777
8020
  workflowResourcePermits.set(publicParams, resolved.resource.permit);
7778
- } else if (publicParams.workflowScript !== undefined || publicParams.workflowScriptPath !== undefined) {
8021
+ } else if (workflow !== undefined || publicParams.workflowScript !== undefined) {
7779
8022
  const normalizedArgs = normalizeWorkflowArgs(publicParams.args);
7780
- if ("error" in normalizedArgs) return Promise.resolve({ content: [{ type: "text", text: normalizedArgs.error }], isError: true, details: { mode: publicParams.action ? "management" : "workflow", results: [] } });
7781
- publicParams = { ...publicParams, args: deepFreezeWorkflowArgs(normalizedArgs.args) };
7782
- }
7783
- const loaded = loadWorkflowScriptPath(publicParams, ctx.cwd);
7784
- if (loaded.error) {
7785
- return Promise.resolve({ content: [{ type: "text", text: loaded.error }], isError: true, details: { mode: publicParams.action ? "management" : "workflow", results: [] } });
8023
+ // validate reports args errors with its script errors; launch rejects them here.
8024
+ const validateOnly = publicParams.action === "validate";
8025
+ if ("error" in normalizedArgs && !validateOnly) return errorResult(normalizedArgs.error);
8026
+ let workflowScript = publicParams.workflowScript;
8027
+ if (workflow !== undefined) {
8028
+ const source = workflow === true ? readReplyWorkflowScript(ctx.sessionManager, id) : readWorkflowScriptFile(workflow, publicParams.cwd, ctx.cwd);
8029
+ if ("error" in source) return errorResult(workflow === true ? source.error : source.error + scriptTextHint);
8030
+ workflowScript = source.script;
8031
+ }
8032
+ const { workflow: _workflow, ...withoutWorkflowSource } = publicParams;
8033
+ publicParams = { ...withoutWorkflowSource, workflowScript, args: "error" in normalizedArgs ? publicParams.args : deepFreezeWorkflowArgs(normalizedArgs.args) };
7786
8034
  }
7787
- publicExecutions.add(loaded.params!);
7788
- return executeWithSingleDispatchGuard(id, loaded.params!, signal, onUpdate, ctx);
8035
+ publicExecutions.add(publicParams);
8036
+ return executeWithSingleDispatchGuard(id, publicParams, signal, onUpdate, ctx);
7789
8037
  };
7790
8038
 
7791
8039
  const executeDelegated = async (
@@ -7795,6 +8043,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7795
8043
  onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
7796
8044
  ctx: ExtensionContext,
7797
8045
  ): Promise<AgentToolResult<Details>> => {
8046
+ const disabledFeatureError = disabledFeatureResult(params);
8047
+ if (disabledFeatureError) return disabledFeatureError;
7798
8048
  const delegatedParams = { ...params };
7799
8049
  const privateParams = delegatedParams as SubagentParamsLike & {
7800
8050
  delegatedThinkingOverride?: AgentConfig["thinking"];