@xzzpig/pi-subagents 0.1.0 → 0.3.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 +135 -0
  2. package/README.md +4 -0
  3. package/agents/reviewer.md +3 -4
  4. package/docs/agents.md +343 -0
  5. package/docs/configuration.md +395 -0
  6. package/docs/extension-api.md +308 -0
  7. package/docs/missions.md +121 -0
  8. package/docs/models.md +192 -0
  9. package/docs/observability.md +198 -0
  10. package/docs/tool-reference.md +343 -0
  11. package/docs/watchdog.md +176 -0
  12. package/docs/workflows.md +163 -0
  13. package/package.json +13 -11
  14. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  15. package/skills/pi-subagents/references/execution-controls.md +7 -7
  16. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
  17. package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
  18. package/src/agents/agents.ts +53 -23
  19. package/src/agents/frontmatter.ts +7 -3
  20. package/src/agents/skills.ts +2 -9
  21. package/src/api/preflight.ts +1 -1
  22. package/src/api/project-panes.ts +30 -0
  23. package/src/extension/config.ts +54 -1
  24. package/src/extension/doctor.ts +40 -0
  25. package/src/extension/fanout-child.ts +5 -4
  26. package/src/extension/index.ts +114 -38
  27. package/src/extension/public-execution.ts +35 -4
  28. package/src/extension/rpc.ts +10 -15
  29. package/src/extension/schemas.ts +33 -11
  30. package/src/extension/subagent-guide.ts +39 -0
  31. package/src/extension/tool-description.ts +38 -18
  32. package/src/inspectors/herdr/actions.ts +11 -2
  33. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  34. package/src/inspectors/herdr/project-panes.ts +459 -63
  35. package/src/intercom/intercom-bridge.ts +7 -2
  36. package/src/intercom/native-supervisor-channel.ts +102 -4
  37. package/src/missions/actions.ts +25 -2
  38. package/src/missions/lifecycle.ts +25 -9
  39. package/src/missions/store.ts +89 -7
  40. package/src/missions/types.ts +33 -0
  41. package/src/missions/workflow-state.ts +25 -15
  42. package/src/runs/background/active-async-capacity.ts +431 -0
  43. package/src/runs/background/active-run-index.ts +46 -0
  44. package/src/runs/background/async-execution.ts +158 -71
  45. package/src/runs/background/async-job-tracker.ts +297 -133
  46. package/src/runs/background/async-resume.ts +37 -5
  47. package/src/runs/background/async-status.ts +39 -5
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/completion-replay.ts +267 -0
  50. package/src/runs/background/control-channel.ts +95 -54
  51. package/src/runs/background/fleet-view.ts +18 -5
  52. package/src/runs/background/owned-process-tree.ts +104 -0
  53. package/src/runs/background/process-terminal.ts +17 -3
  54. package/src/runs/background/result-watcher.ts +113 -10
  55. package/src/runs/background/resume-guidance.ts +53 -0
  56. package/src/runs/background/retained-children.ts +14 -6
  57. package/src/runs/background/run-status.ts +119 -5
  58. package/src/runs/background/scheduled-runs.ts +25 -1
  59. package/src/runs/background/stale-run-reconciler.ts +12 -24
  60. package/src/runs/background/subagent-runner.ts +127 -41
  61. package/src/runs/background/subagent-wait.ts +5 -2
  62. package/src/runs/background/wait-completions.ts +39 -5
  63. package/src/runs/background/wait-subscriptions.ts +21 -5
  64. package/src/runs/foreground/async-dismiss-action.ts +85 -0
  65. package/src/runs/foreground/async-steering-action.ts +7 -8
  66. package/src/runs/foreground/chain-execution.ts +40 -2
  67. package/src/runs/foreground/execution.ts +97 -19
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/foreground-history.ts +137 -0
  70. package/src/runs/foreground/prompt-audit.ts +172 -0
  71. package/src/runs/foreground/subagent-executor.ts +1274 -243
  72. package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
  73. package/src/runs/shared/acceptance.ts +13 -4
  74. package/src/runs/shared/completion-guard.ts +17 -1
  75. package/src/runs/shared/dynamic-fanout.ts +1 -1
  76. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  77. package/src/runs/shared/model-fallback.ts +8 -4
  78. package/src/runs/shared/model-scope.ts +12 -2
  79. package/src/runs/shared/parallel-utils.ts +3 -0
  80. package/src/runs/shared/pi-args.ts +44 -1
  81. package/src/runs/shared/run-fanout-budget.ts +280 -0
  82. package/src/runs/shared/single-output.ts +4 -2
  83. package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
  84. package/src/runs/shared/task-intent.ts +19 -3
  85. package/src/runs/shared/worktree.ts +20 -7
  86. package/src/shared/agent-stream-options.ts +5 -0
  87. package/src/shared/artifacts.ts +17 -21
  88. package/src/shared/display-text.ts +150 -0
  89. package/src/shared/file-coalescer.ts +9 -0
  90. package/src/shared/fork-context.ts +13 -0
  91. package/src/shared/formatters.ts +4 -6
  92. package/src/shared/node-executable.ts +21 -0
  93. package/src/shared/prompt-resources.ts +51 -0
  94. package/src/shared/settings.ts +15 -2
  95. package/src/shared/types.ts +158 -4
  96. package/src/shared/utf8.ts +11 -0
  97. package/src/shared/utils.ts +46 -34
  98. package/src/slash/prompt-workflows.ts +2 -15
  99. package/src/slash/slash-commands.ts +22 -2
  100. package/src/tui/fleet-status.ts +29 -17
  101. package/src/tui/fleet-transcript.ts +1 -48
  102. package/src/tui/fleet.ts +362 -37
  103. package/src/tui/render.ts +235 -71
  104. package/src/watchdog/change-signature.ts +4 -3
  105. package/src/watchdog/permission-arbiter.ts +2 -1
  106. package/src/watchdog/review.ts +4 -3
  107. package/src/workflows/chat-progress.ts +8 -2
  108. package/src/workflows/scripted-workflow.ts +273 -20
@@ -4,7 +4,7 @@ import * as path from "node:path";
4
4
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
5
5
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
6
6
  import { resolveAgentName, type AgentConfig, type AgentScope } from "../../agents/agents.ts";
7
- import { getArtifactsDir, getChainRunsDir, getProjectArtifactPackagingWarning } from "../../shared/artifacts.ts";
7
+ import { getArtifactsDir, getChainRunsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir } from "../../shared/artifacts.ts";
8
8
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
9
9
  import { ChainClarifyComponent, type ChainClarifyResult } from "./chain-clarify.ts";
10
10
  import { resolveEffectiveThinking, toModelInfo, type ModelInfo } from "../../shared/model-info.ts";
@@ -17,10 +17,13 @@ import {
17
17
  settleForegroundSchedulingOwner,
18
18
  updateForegroundChild,
19
19
  } from "./foreground-control.ts";
20
+ import { getLivePromptAudit, rewritePromptWithGuidance, updateLiveEffectivePrompt } from "./prompt-audit.ts";
21
+ import { persistForegroundRunHistory, MAX_REMEMBERED_FOREGROUND_RUNS } from "./foreground-history.ts";
20
22
  import { resolveExecutionAgentScope } from "../../agents/agent-scope.ts";
21
23
  import { handleManagementAction } from "../../agents/agent-management.ts";
22
24
  import { handleRefinementAction } from "../../agents/agent-refinements.ts";
23
25
  import { buildDoctorReport } from "../../extension/doctor.ts";
26
+ import { readSubagentGuide } from "../../extension/subagent-guide.ts";
24
27
  import { normalizePublicSubagentExecution } from "../../extension/public-execution.ts";
25
28
  import { runSync } from "./execution.ts";
26
29
  import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/tool-actions.ts";
@@ -37,6 +40,7 @@ import {
37
40
  isParallelStep,
38
41
  isDynamicParallelStep,
39
42
  resolveChainPath,
43
+ resolveExistingReadPaths,
40
44
  resolveStepBehavior,
41
45
  suppressProgressForReadOnlyTask,
42
46
  taskDisallowsFileUpdates,
@@ -49,8 +53,10 @@ import {
49
53
  type StepOverrides,
50
54
  } from "../../shared/settings.ts";
51
55
  import { discoverAvailableSkills, normalizeSkillInput } from "../../agents/skills.ts";
52
- import { buildAsyncRunnerSteps, executeAsyncChain, executeAsyncSingle, formatAsyncStartedMessage, isAsyncAvailable } from "../background/async-execution.ts";
53
- import type { ScheduledRunAction } from "../background/scheduled-runs.ts";
56
+ import { buildAsyncRunnerSteps, DEFAULT_ASYNC_TIMEOUT_MS, executeAsyncChain, executeAsyncSingle, formatAsyncStartedMessage, isAsyncAvailable, workflowAwaitedAsyncResultPath } from "../background/async-execution.ts";
57
+ import { updateActiveRunIndex } from "../background/active-run-index.ts";
58
+ import { acquireActiveAsyncCapacity, ActiveAsyncCapacityError, getActiveAsyncCapacitySnapshot, resolveMaxActiveAsyncRunsPerSession, transferActiveAsyncCapacity, type ActiveAsyncCapacityHandle } from "../background/active-async-capacity.ts";
59
+ import { isScheduledRunAction, type ScheduledRunAction } from "../background/scheduled-runs.ts";
54
60
  import { enqueueChainAppendRequest, readPendingChainAppendRequests, runnerStepOutputNames } from "../background/chain-append.ts";
55
61
  import { ChainOutputValidationError, validateChainOutputBindingsWithContext } from "../shared/chain-outputs.ts";
56
62
  import { normalizeGateAcceptance, validateExecutionAcceptance } from "../shared/acceptance.ts";
@@ -60,6 +66,7 @@ import { applyIntercomBridgeToAgent, INTERCOM_BRIDGE_MARKER, resolveIntercomBrid
60
66
  import { formatControlIntercomMessage, formatControlNoticeMessage, resolveControlConfig, shouldNotifyControlEvent } from "../shared/subagent-control.ts";
61
67
  import { resolveTurnBudgetConfig } from "../shared/turn-budget.ts";
62
68
  import { formatSpawnBudget, getSpawnBudgetSnapshot, grantSpawnBudget, preflightSpawnBudget, preflightSpawnBudgetGrant, reserveSpawnBudget } from "../shared/spawn-budget.ts";
69
+ import { claimRunFanoutBatch, claimRunFanoutBatchWithCommit, createRunFanoutBudget, decodeRunFanoutBudgetDescriptor, formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor, RunFanoutLimitError, RUN_FANOUT_BUDGET_ENV, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
63
70
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
64
71
  import { usageBudgetExceededMessage, usageBudgetState, validateUsageBudgetConfig } from "../shared/usage-budget.ts";
65
72
  import { intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
@@ -67,6 +74,7 @@ import { isAgentContractV1 } from "../shared/agent-contract.ts";
67
74
  import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
68
75
  import { cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
69
76
  import { compactForegroundDetails, getSingleResultOutput, mapConcurrent, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage } from "../../shared/utils.ts";
77
+ import { createTaskMutationArbiter } from "../shared/llm-intent-arbiter.ts";
70
78
  import { DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore } from "../shared/parallel-utils.ts";
71
79
  import { discardPreservedWorktrees, formatParallelHandoffError, formatParallelHandoffReference, parallelHandoffPath, writeParallelHandoffGroup, writePendingParallelHandoff } from "../shared/parallel-handoff.ts";
72
80
  import { summarizeContextModes, type ContextMode, type ContextSummary } from "../shared/context-mode.ts";
@@ -82,22 +90,32 @@ import { applySteeringRecoveryAgentConfig, buildRevivedAsyncTask, resolveAsyncRe
82
90
  import { deliverCheckpointDecisionRequest, deliverInterruptRequest, readRevivalBriefs, requestAsyncSteer, type SteerDeliveryMode } from "../background/control-channel.ts";
83
91
  import { updateSteeringTarget, waitForSteeringAction } from "../background/steering.ts";
84
92
  import { steerAsyncRun } from "./async-steering-action.ts";
93
+ import {
94
+ removeWorkflowForegroundSteeringRoute,
95
+ resolveWorkflowForegroundSteeringTarget,
96
+ steerWorkflowForegroundTarget,
97
+ workflowForegroundSteeringDir,
98
+ workflowForegroundSteeringLaunchOptions,
99
+ } from "./workflow-foreground-steering.ts";
85
100
  import { stopAsyncRun } from "./async-stop-action.ts";
101
+ import { dismissRecoveredWorkflow } from "./async-dismiss-action.ts";
86
102
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
87
- import { resolveAsyncRootResultPath } from "../background/chain-root-attachment.ts";
103
+ import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
88
104
  import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, resolveInheritedNestedRouteFromEnv, resolveNestedAsyncDir, resolveNestedParentAddressFromEnv, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedRunResolutionScope } from "../shared/nested-events.ts";
89
105
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
90
106
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
91
107
  import { inspectSubagentStatus } from "../background/run-status.ts";
92
108
  import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.ts";
93
109
  import { handleMissionAction, MISSION_ACTIONS } from "../../missions/actions.ts";
94
- import { attachMissionToLaunchResult, prepareMissionLaunch, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
110
+ import { attachMissionToLaunchResult, prepareMissionLaunch, writeMissionAsyncBinding, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
95
111
  import { updateMission } from "../../missions/store.ts";
112
+ import type { MissionWorkflowChildUpdate } from "../../missions/types.ts";
96
113
  import { createMissionWorkflowState } from "../../missions/workflow-state.ts";
97
114
  import { resolveAuthorityDecision } from "../../policy/authority.ts";
98
115
  import { handleHerdrInspectorAction, HERDR_INSPECTOR_ACTIONS } from "../../inspectors/herdr/actions.ts";
99
116
  import { handleHerdrProjectPaneAction, HERDR_PROJECT_PANE_ACTIONS } from "../../inspectors/herdr/project-panes.ts";
100
117
  import { previewSimpleWorkflowRun, runWorkflowScript, WorkflowScriptError, type WorkflowScriptChildResult } from "../../workflows/scripted-workflow.ts";
118
+ import { renderWorkflowPrompt } from "../../shared/prompt-resources.ts";
101
119
  import { resolveWorkflowChatProgress, type WorkflowChatProgressProjection } from "../../workflows/chat-progress.ts";
102
120
  import {
103
121
  cleanupWorktrees,
@@ -121,6 +139,7 @@ import {
121
139
  type Details,
122
140
  type ExtensionConfig,
123
141
  type ForegroundRunControl,
142
+ type IntercomBridgeConfig,
124
143
  type IntercomEventBus,
125
144
  type JsonSchemaObject,
126
145
  type MaxOutputConfig,
@@ -129,6 +148,7 @@ import {
129
148
  type ResolvedControlConfig,
130
149
  type ResolvedTurnBudget,
131
150
  type ResolvedToolBudget,
151
+ type RunFanoutBudgetDescriptor,
132
152
  type SingleResult,
133
153
  type ToolBudgetConfig,
134
154
  type TurnBudgetConfig,
@@ -147,10 +167,52 @@ import {
147
167
  resolveTopLevelParallelMaxTasks,
148
168
  resolveChildMaxSubagentDepth,
149
169
  resolveCurrentMaxSubagentDepth,
170
+ resolveMaxSubagentSpawnsPerRun,
150
171
  wrapForkTask,
151
172
  } from "../../shared/types.ts";
152
173
 
153
- const MUTATING_MANAGEMENT_ACTIONS = new Set(["create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "refine", "refine.rollback", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
174
+ const MUTATING_MANAGEMENT_ACTIONS = new Set(["create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "refine", "refine.rollback", "dismiss", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
175
+ const DESTRUCTIVE_MANAGEMENT_ACTIONS = new Set(["delete", "eject", "disable", "reset", "mission.close", "worktree.discard", "refine.rollback", "inspector.close", "project.close", "stop", "interrupt", "reject-checkpoint", "schedule.delete"]);
176
+
177
+ function editDistance(left: string, right: string): number {
178
+ const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
179
+ for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
180
+ let diagonal = previous[0]!;
181
+ previous[0] = leftIndex;
182
+ for (let rightIndex = 1; rightIndex <= right.length; rightIndex += 1) {
183
+ const above = previous[rightIndex]!;
184
+ previous[rightIndex] = left[leftIndex - 1] === right[rightIndex - 1]
185
+ ? diagonal
186
+ : Math.min(diagonal, above, previous[rightIndex - 1]!) + 1;
187
+ diagonal = above;
188
+ }
189
+ }
190
+ return previous[right.length]!;
191
+ }
192
+
193
+ function hasSingleAdjacentTransposition(left: string, right: string): boolean {
194
+ if (left.length !== right.length) return false;
195
+ const mismatch = [...left].findIndex((character, index) => character !== right[index]);
196
+ return mismatch >= 0
197
+ && left[mismatch] === right[mismatch + 1]
198
+ && left[mismatch + 1] === right[mismatch]
199
+ && left.slice(mismatch + 2) === right.slice(mismatch + 2);
200
+ }
201
+
202
+ export function unknownSubagentActionMessage(action: string): string {
203
+ const requested = action.toLowerCase();
204
+ const suggestion = SUBAGENT_ACTIONS.find((candidate) => {
205
+ const distance = editDistance(requested, candidate);
206
+ const closeMatch = distance <= Math.max(1, Math.floor(candidate.length / 4)) || hasSingleAdjacentTransposition(requested, candidate);
207
+ if (DESTRUCTIVE_MANAGEMENT_ACTIONS.has(candidate)) return distance === 1 && requested.length >= candidate.length - 1;
208
+ return closeMatch;
209
+ });
210
+ const nextStep = 'Use subagent({ action: "status" }) to inspect runs or subagent({ action: "list" }) to inspect agents.';
211
+ const validActions = `Valid: ${SUBAGENT_ACTIONS.join(", ")}.`;
212
+ return suggestion
213
+ ? `Unknown action: ${action}. Did you mean ${suggestion}? ${nextStep} ${validActions}`
214
+ : `Unknown action: ${action}. ${nextStep} ${validActions}`;
215
+ }
154
216
 
155
217
  type UndefinedOmitted<T extends object> = {
156
218
  [K in keyof T as undefined extends T[K] ? never : K]: T[K];
@@ -209,6 +271,7 @@ export interface SubagentParamsLike {
209
271
  index?: number;
210
272
  view?: "fleet" | "transcript";
211
273
  lines?: number;
274
+ topic?: string;
212
275
  chainName?: string;
213
276
  config?: unknown;
214
277
  name?: string;
@@ -226,13 +289,20 @@ export interface SubagentParamsLike {
226
289
  /** Internal workflow ownership metadata; not part of the public schema. */
227
290
  workflowParentRunId?: string;
228
291
  workflowKey?: string;
292
+ workflowChildAsyncId?: string;
229
293
  suppressRoutineResultIntercom?: boolean;
294
+ /** Internal inherited cumulative run-tree budget. */
295
+ runFanoutBudget?: RunFanoutBudgetDescriptor;
296
+ /** Internal workflow host admission proof. */
297
+ runFanoutAdmitted?: boolean;
230
298
  /** Internal durable-run compatibility fields. Public callers must use workflowScript. */
231
299
  chain?: ChainStep[];
232
300
  tasks?: TaskParam[];
233
301
  concurrency?: number;
234
302
  worktree?: boolean;
235
303
  context?: "fresh" | "fork";
304
+ /** Per-run intercom bridge config. It replaces the global config for this launch only. */
305
+ intercomBridge?: IntercomBridgeConfig;
236
306
  async?: boolean;
237
307
  foregroundOnly?: boolean;
238
308
  timeoutMs?: number;
@@ -320,6 +390,8 @@ interface ExecutionContextData {
320
390
  signal: AbortSignal;
321
391
  onUpdate?: (r: AgentToolResult<Details>) => void;
322
392
  agents: AgentConfig[];
393
+ /** Discovered agent definitions before per-run bridge injection. */
394
+ recoveryAgents: AgentConfig[];
323
395
  runId: string;
324
396
  shareEnabled: boolean;
325
397
  sessionRoot: string;
@@ -331,6 +403,7 @@ interface ExecutionContextData {
331
403
  artifactsDir: string;
332
404
  backgroundRequestedWhileClarifying: boolean;
333
405
  effectiveAsync: boolean;
406
+ asyncRunId: string;
334
407
  controlConfig: ResolvedControlConfig;
335
408
  intercomBridge: IntercomBridgeState;
336
409
  nestedRoute?: NestedRouteInfo;
@@ -347,6 +420,9 @@ interface ExecutionContextData {
347
420
  parentSessionId: string | null;
348
421
  parentPiSessionId?: string;
349
422
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
423
+ runFanoutBudget: RunFanoutBudgetDescriptor;
424
+ topLevelAsyncCapacityEligible: boolean;
425
+ activeAsyncCapacity?: ActiveAsyncCapacityHandle;
350
426
  }
351
427
 
352
428
  function resolveRequestedCwd(runtimeCwd: string, requestedCwd: string | undefined): string {
@@ -356,6 +432,7 @@ function resolveRequestedCwd(runtimeCwd: string, requestedCwd: string | undefine
356
432
  function removeForegroundControlIfIdle(state: SubagentState, runId: string): boolean {
357
433
  const control = state.foregroundControls.get(runId);
358
434
  if (control && (!foregroundSchedulingSettled(control) || (control.activeChildren?.size ?? 0) > 0)) return false;
435
+ if (control) removeWorkflowForegroundSteeringRoute(control);
359
436
  state.foregroundControls.delete(runId);
360
437
  if (state.lastForegroundControlId === runId) state.lastForegroundControlId = null;
361
438
  return true;
@@ -374,6 +451,17 @@ function getForegroundControl(state: SubagentState, runId: string | undefined) {
374
451
  return newest;
375
452
  }
376
453
 
454
+ function promptAuditRedoParams(value: unknown, rewrittenTask: string): SubagentParamsLike {
455
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Prompt redo is missing a safe live launch contract.");
456
+ const params = { ...(value as SubagentParamsLike), task: rewrittenTask, async: false };
457
+ delete params.workflowParentRunId;
458
+ delete params.workflowKey;
459
+ delete params.workflowChildAsyncId;
460
+ delete params.suppressRoutineResultIntercom;
461
+ if (params.worktree === true && Array.isArray(params.tasks)) delete params.cwd;
462
+ return params;
463
+ }
464
+
377
465
  function formatForegroundActivity(control: SubagentState["foregroundControls"] extends Map<string, infer T> ? T : never): string | undefined {
378
466
  const facts: string[] = [];
379
467
  if (control.currentTool && control.currentToolStartedAt) facts.push(`tool ${control.currentTool} for ${Math.floor(Math.max(0, Date.now() - control.currentToolStartedAt) / 1000)}s`);
@@ -425,12 +513,18 @@ function withSpawnBudgetStatus(
425
513
  sessionId: string | null,
426
514
  ): AgentToolResult<Details> {
427
515
  const spawnBudget = getSpawnBudgetSnapshot(state, config, sessionId);
516
+ const activeAsyncCapacity = sessionId
517
+ ? getActiveAsyncCapacitySnapshot(sessionId, resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession), {
518
+ liveWorkflowRunIds: new Set(state.workflowControllers?.keys() ?? []),
519
+ })
520
+ : { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession) ?? 0 };
521
+ state.activeAsyncCapacity = activeAsyncCapacity;
428
522
  return {
429
523
  ...result,
430
524
  content: result.content.map((item, index) => index === 0 && item.type === "text"
431
- ? { ...item, text: `${formatSpawnBudget(spawnBudget)}\n${item.text}` }
525
+ ? { ...item, text: `${formatSpawnBudget(spawnBudget)}\nActive async capacity: ${activeAsyncCapacity.used}/${activeAsyncCapacity.limit || "unlimited"} used\n${item.text}` }
432
526
  : item),
433
- details: { ...result.details, spawnBudget },
527
+ details: { ...result.details, spawnBudget, activeAsyncCapacity },
434
528
  };
435
529
  }
436
530
 
@@ -451,6 +545,31 @@ function countRequestedSubagentSpawns(params: SubagentParamsLike, config: Extens
451
545
  return params.agent ? 1 : 0;
452
546
  }
453
547
 
548
+ function staticRunFanoutPaths(params: SubagentParamsLike): string[] {
549
+ if (params.tasks) return params.tasks.map((_, index) => `tasks[${index}]`);
550
+ if (params.chain) return params.chain.flatMap((step, stepIndex) => {
551
+ if (isDynamicParallelStep(step) || "checkpoint" in step) return [];
552
+ if (isParallelStep(step)) return step.parallel.map((_, itemIndex) => `chain[${stepIndex}].parallel[${itemIndex}]`);
553
+ return [`chain[${stepIndex}]`];
554
+ });
555
+ return params.agent ? ["single"] : [];
556
+ }
557
+
558
+ function runFanoutErrorResult(error: RunFanoutLimitError, mode: "single" | "parallel" | "chain"): AgentToolResult<Details> {
559
+ return { content: [{ type: "text", text: error.message }], isError: true, details: { mode, results: [], runFanoutBudget: error.snapshot, runFanoutRejection: error.rejection } };
560
+ }
561
+
562
+ function withRunFanoutBudget(result: AgentToolResult<Details>, descriptor: RunFanoutBudgetDescriptor, options: { annotateContent?: boolean } = {}): AgentToolResult<Details> {
563
+ const runFanoutBudget = getRunFanoutBudgetSnapshot(descriptor);
564
+ return {
565
+ ...result,
566
+ content: options.annotateContent === false
567
+ ? result.content
568
+ : result.content.map((item, index) => index === 0 && item.type === "text" ? { ...item, text: `${formatRunFanoutBudget(runFanoutBudget)}\n${item.text}` } : item),
569
+ details: { ...result.details, runFanoutBudget },
570
+ };
571
+ }
572
+
454
573
  function foregroundStatusResult(control: SubagentState["foregroundControls"] extends Map<string, infer T> ? T : never): AgentToolResult<Details> {
455
574
  let nestedWarning: string | undefined;
456
575
  try {
@@ -473,7 +592,7 @@ function foregroundStatusResult(control: SubagentState["foregroundControls"] ext
473
592
 
474
593
  function trimRememberedForegroundRuns(state: SubagentState): void {
475
594
  if (!state.foregroundRuns) return;
476
- while (state.foregroundRuns.size > 50) {
595
+ while (state.foregroundRuns.size > MAX_REMEMBERED_FOREGROUND_RUNS) {
477
596
  const oldestTerminal = [...state.foregroundRuns.values()]
478
597
  .filter((run) => !run.children.some((child) => child.status === "detached"))
479
598
  .sort((left, right) => left.updatedAt - right.updatedAt)[0];
@@ -482,6 +601,14 @@ function trimRememberedForegroundRuns(state: SubagentState): void {
482
601
  }
483
602
  }
484
603
 
604
+ function persistRememberedForegroundRuns(state: SubagentState): void {
605
+ try {
606
+ persistForegroundRunHistory(state);
607
+ } catch (error) {
608
+ console.error("Failed to persist foreground run history:", error);
609
+ }
610
+ }
611
+
485
612
  function foregroundChildActivityFromProgress(progress: SingleResult["progress"] | undefined) {
486
613
  return {
487
614
  ...(progress?.activityState ? { activityState: progress.activityState } : {}),
@@ -548,6 +675,7 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
548
675
  }),
549
676
  });
550
677
  trimRememberedForegroundRuns(state);
678
+ persistRememberedForegroundRuns(state);
551
679
  }
552
680
 
553
681
  function applyControlEventToRememberedForegroundRun(state: SubagentState, event: ControlEvent): void {
@@ -623,6 +751,7 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
623
751
  ...(input.result.capabilityAudit ? { capabilityAudit: input.result.capabilityAudit } : {}),
624
752
  });
625
753
  trimRememberedForegroundRuns(state);
754
+ persistRememberedForegroundRuns(state);
626
755
  const output = getSingleResultOutput(input.result).trim();
627
756
  const success = terminalStatus === "completed";
628
757
  const summary = !success && input.result.error
@@ -868,8 +997,15 @@ function interruptAsyncRun(
868
997
  details: { mode: "management", results: [] },
869
998
  };
870
999
  }
1000
+ if (status.mode === "workflow") {
1001
+ return {
1002
+ content: [{ type: "text", text: `Interrupt is unsupported for async workflow ${target.asyncId}; use stop instead.` }],
1003
+ isError: true,
1004
+ details: { mode: "management", results: [] },
1005
+ };
1006
+ }
871
1007
  try {
872
- deliverInterruptRequest(omitUndefinedProperties({ asyncDir: target.asyncDir, pid: status.pid, kill, source: "interrupt-action" }));
1008
+ deliverInterruptRequest({ asyncDir: target.asyncDir, source: "interrupt-action" });
873
1009
  const tracked = state.asyncJobs.get(target.asyncId);
874
1010
  if (tracked) {
875
1011
  delete tracked.activityState;
@@ -1066,18 +1202,30 @@ function appendStepToAsyncChain(input: {
1066
1202
  }
1067
1203
 
1068
1204
  try {
1205
+ const asyncDir = resolved.location.asyncDir;
1206
+ if (!asyncDir) throw new Error(`Run '${resolved.id}' is missing its async directory.`);
1207
+ const runFanoutBudget = readRunFanoutBudgetDescriptor(asyncDir);
1208
+ if (!runFanoutBudget) throw new Error(`Run '${resolved.id}' is missing its run fan-out budget identity.`);
1209
+ const startIndex = (status.chainStepCount ?? status.steps?.length ?? 0) + pendingAppendRequests.reduce((total, request) => total + request.steps.length, 0);
1210
+ const appendPaths = chain.flatMap((step, localIndex) => {
1211
+ const absoluteIndex = startIndex + localIndex;
1212
+ if (isDynamicParallelStep(step) || "checkpoint" in step) return [];
1213
+ if (isParallelStep(step)) return step.parallel.map((_, itemIndex) => `chain[${absoluteIndex}].parallel[${itemIndex}]`);
1214
+ return [`chain[${absoluteIndex}]`];
1215
+ });
1069
1216
  const result = enqueueChainAppendRequest({
1070
- asyncDir: resolved.location.asyncDir,
1217
+ asyncDir,
1071
1218
  runId: resolved.id,
1072
1219
  steps: built.steps,
1220
+ admit: (persist) => claimRunFanoutBatchWithCommit(runFanoutBudget, appendPaths, persist),
1073
1221
  });
1074
1222
  const stepText = built.steps.length === 1 ? "step" : "steps";
1075
1223
  return {
1076
1224
  content: [{
1077
1225
  type: "text",
1078
- text: `Append queued for chain run ${resolved.id}: ${built.steps.length} ${stepText}. It becomes eligible after the chain's already-queued steps finish. Pending appends: ${result.pendingCount}.`,
1226
+ text: `Append queued for chain run ${resolved.id}: ${built.steps.length} ${stepText}. It becomes eligible after the chain's already-queued steps finish. Pending appends: ${result.pendingCount}.${result.bookkeepingError ? ` Bookkeeping warning: ${result.bookkeepingError}` : ""}`,
1079
1227
  }],
1080
- details: { mode: "management", results: [], asyncId: resolved.id, asyncDir: resolved.location.asyncDir },
1228
+ details: { mode: "management", results: [], asyncId: resolved.id, asyncDir },
1081
1229
  };
1082
1230
  } catch (error) {
1083
1231
  const message = error instanceof Error ? error.message : String(error);
@@ -1178,7 +1326,7 @@ function directNestedAsyncInterrupt(target: ResolvedSubagentRunId & { kind: "nes
1178
1326
  const pid = typeof status?.pid === "number" && status.pid > 0 ? status.pid : run.pid;
1179
1327
  if (!status || status.state !== "running" || typeof pid !== "number" || pid <= 0) return undefined;
1180
1328
  try {
1181
- deliverInterruptRequest({ asyncDir, pid, source: "nested-interrupt" });
1329
+ deliverInterruptRequest({ asyncDir, source: "nested-interrupt" });
1182
1330
  return { content: [{ type: "text", text: `Interrupt requested for nested async run ${run.id}.` }], details: { mode: "management", results: [] } };
1183
1331
  } catch (error) {
1184
1332
  const message = error instanceof Error ? error.message : String(error);
@@ -1270,6 +1418,7 @@ async function resumeAsyncRun(input: {
1270
1418
  deps: ExecutorDeps;
1271
1419
  parentModel?: ParentModel;
1272
1420
  absoluteDeadlineAt?: number;
1421
+ signal?: AbortSignal;
1273
1422
  }): Promise<AgentToolResult<Details>> {
1274
1423
  const followUp = (input.params.message ?? input.params.task ?? "").trim();
1275
1424
  const attachChain = (input.params.chain?.length ?? 0) > 0 ? input.params.chain as ChainStep[] : undefined;
@@ -1367,17 +1516,18 @@ async function resumeAsyncRun(input: {
1367
1516
  const discoveredAgents = discovered.agents;
1368
1517
  const modelScope = discovered.modelScope;
1369
1518
  const sessionName = resolveIntercomSessionTarget(input.deps.pi.getSessionName(), input.ctx.sessionManager.getSessionId());
1519
+ const recoveryDescriptor = "recoveryDescriptor" in target ? target.recoveryDescriptor : undefined;
1370
1520
  const intercomBridge = resolveIntercomBridge({
1371
1521
  config: input.deps.config.intercomBridge,
1522
+ override: input.params.intercomBridge ?? recoveryDescriptor?.intercomBridge,
1372
1523
  context: input.params.context,
1373
1524
  orchestratorTarget: sessionName,
1374
1525
  });
1375
1526
  const agents = intercomBridge.active
1376
1527
  ? discoveredAgents.map((agent) => applyIntercomBridgeToAgent(agent, intercomBridge))
1377
1528
  : discoveredAgents;
1378
- const recoveryDescriptor = "recoveryDescriptor" in target ? target.recoveryDescriptor : undefined;
1379
- const discoveredAgentConfig = agents.find((agent) => agent.name === target.agent);
1380
- const agentConfig: AgentConfig | undefined = discoveredAgentConfig ?? (recoveryDescriptor ? {
1529
+ const discoveredAgentConfig = discoveredAgents.find((agent) => agent.name === target.agent);
1530
+ const baseAgentConfig: AgentConfig | undefined = discoveredAgentConfig ?? (recoveryDescriptor ? {
1381
1531
  name: recoveryDescriptor.agent,
1382
1532
  description: "Persisted async recovery contract",
1383
1533
  systemPrompt: "",
@@ -1385,9 +1535,9 @@ async function resumeAsyncRun(input: {
1385
1535
  inheritProjectContext: recoveryDescriptor.inheritProjectContext,
1386
1536
  inheritSkills: recoveryDescriptor.inheritSkills,
1387
1537
  source: "project",
1388
- filePath: recoveryDescriptor.agentFilePath ?? path.join(recoveryDescriptor.cwd, ".pi-subagents-recovery-agent"),
1538
+ filePath: recoveryDescriptor.agentFilePath ?? path.join(getProjectSubagentsDir(recoveryDescriptor.cwd), "recovery-agent"),
1389
1539
  } : undefined);
1390
- if (!agentConfig) {
1540
+ if (!baseAgentConfig) {
1391
1541
  return {
1392
1542
  content: [{ type: "text", text: `Unknown agent for resume: ${target.agent}` }],
1393
1543
  isError: true,
@@ -1411,6 +1561,20 @@ async function resumeAsyncRun(input: {
1411
1561
  };
1412
1562
  }
1413
1563
  const runId = randomUUID().slice(0, 8);
1564
+ const topLevelResume = depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.params.workflowParentRunId;
1565
+ let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1566
+ try {
1567
+ activeAsyncCapacity = topLevelResume ? acquireActiveAsyncCapacity({
1568
+ sessionId: input.deps.state.currentSessionId!,
1569
+ limit: resolveMaxActiveAsyncRunsPerSession(input.deps.config.maxActiveAsyncRunsPerSession),
1570
+ runId,
1571
+ kind: "runner",
1572
+ asyncDir: path.join(DIRS.async, runId),
1573
+ }, { liveWorkflowRunIds: new Set(input.deps.state.workflowControllers?.keys() ?? []) }) : undefined;
1574
+ } catch (error) {
1575
+ if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "chain", results: [], activeAsyncCapacity: error.snapshot } };
1576
+ throw error;
1577
+ }
1414
1578
  const artifactConfig: ArtifactConfig = omitUndefinedProperties({ ...DEFAULT_ARTIFACT_CONFIG, enabled: input.params.artifacts !== false, dir: input.deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir });
1415
1579
  const availableModels = input.ctx.modelRegistry.getAvailable().map(toModelInfo);
1416
1580
  const contextPolicy = resolveExplicitContextPolicy(input.params);
@@ -1462,9 +1626,14 @@ async function resumeAsyncRun(input: {
1462
1626
  controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : undefined,
1463
1627
  childIntercomTarget: intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : undefined,
1464
1628
  globalConcurrencyLimit: input.deps.config.globalConcurrencyLimit,
1629
+ runFanoutBudget: createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(input.deps.config.maxSubagentSpawnsPerRun)),
1465
1630
  capabilityCeiling: intersectSubagentCapabilityCeilings("capabilityCeiling" in target ? target.capabilityCeiling : undefined, resolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId)),
1631
+ activeAsyncCapacity,
1466
1632
  }));
1467
- if (result.isError) return result;
1633
+ if (result.isError) {
1634
+ activeAsyncCapacity?.rollback();
1635
+ return result;
1636
+ }
1468
1637
  const attachedId = result.details.asyncId ?? runId;
1469
1638
  const lines = [
1470
1639
  `Attached async subagent ${target.runId} as the first step of a new chain.`,
@@ -1483,17 +1652,45 @@ async function resumeAsyncRun(input: {
1483
1652
  if (!revivalSessionFile) {
1484
1653
  return { content: [{ type: "text", text: `Async child '${target.runId}' has no persisted session file to resume.` }], isError: true, details: { mode: "management", results: [] } };
1485
1654
  }
1655
+ if (target.source === "async" && !recoveryDescriptor) {
1656
+ return { content: [{ type: "text", text: `Async child '${target.runId}' is missing its required run fan-out recovery identity. Start a new run instead.` }], isError: true, details: { mode: "management", results: [] } };
1657
+ }
1486
1658
  const runId = randomUUID().slice(0, 8);
1487
- const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(agentConfig, recoveryDescriptor) : agentConfig;
1659
+ const topLevelResume = depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.params.workflowParentRunId;
1660
+ let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1661
+ try {
1662
+ activeAsyncCapacity = !topLevelResume ? undefined : target.source === "async"
1663
+ ? transferActiveAsyncCapacity({
1664
+ sessionId: input.deps.state.currentSessionId!,
1665
+ limit: resolveMaxActiveAsyncRunsPerSession(input.deps.config.maxActiveAsyncRunsPerSession),
1666
+ sourceRunId: target.runId,
1667
+ runId,
1668
+ asyncDir: path.join(DIRS.async, runId),
1669
+ })
1670
+ : acquireActiveAsyncCapacity({
1671
+ sessionId: input.deps.state.currentSessionId!,
1672
+ limit: resolveMaxActiveAsyncRunsPerSession(input.deps.config.maxActiveAsyncRunsPerSession),
1673
+ runId,
1674
+ kind: "runner",
1675
+ asyncDir: path.join(DIRS.async, runId),
1676
+ });
1677
+ } catch (error) {
1678
+ if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "single", results: [], activeAsyncCapacity: error.snapshot } };
1679
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "single", results: [] } };
1680
+ }
1681
+ const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
1682
+ const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
1488
1683
  const artifactConfig: ArtifactConfig = recoveryDescriptor?.artifactConfig ?? omitUndefinedProperties({ ...DEFAULT_ARTIFACT_CONFIG, enabled: input.params.artifacts !== false, dir: input.deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir });
1489
1684
  const artifactsDir = recoveryDescriptor?.artifactsDir ?? getArtifactsDir(parentSessionFile, effectiveCwd, artifactConfig.dir);
1490
1685
  const availableModels = input.ctx.modelRegistry.getAvailable().map(toModelInfo);
1491
1686
  const parentModel = input.parentModel;
1687
+ const revivalAsyncDir = path.join(DIRS.async, runId);
1492
1688
  const result = executeAsyncSingle(runId, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
1493
1689
  agent: target.agent,
1494
1690
  task: buildRevivedAsyncTask(target as Parameters<typeof buildRevivedAsyncTask>[0], effectiveFollowUp),
1495
1691
  goal: effectiveFollowUp,
1496
- agentConfig: recoveryAgentConfig,
1692
+ agentConfig,
1693
+ recoveryAgentConfig,
1497
1694
  ctx: compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
1498
1695
  pi: input.deps.pi,
1499
1696
  cwd: input.requestCwd,
@@ -1528,6 +1725,7 @@ async function resumeAsyncRun(input: {
1528
1725
  worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
1529
1726
  worktreeBaseDir: input.deps.config.worktreeBaseDir,
1530
1727
  controlConfig: recoveryDescriptor?.controlConfig ?? resolveControlConfig(input.deps.config.control, input.params.control),
1728
+ intercomBridge: input.params.intercomBridge ?? recoveryDescriptor?.intercomBridge,
1531
1729
  controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : undefined,
1532
1730
  childIntercomTarget: intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : undefined,
1533
1731
  availableModels,
@@ -1542,10 +1740,28 @@ async function resumeAsyncRun(input: {
1542
1740
  ...(input.params.turnBudget !== undefined ? { turnBudget: input.params.turnBudget } : {}),
1543
1741
  ...(input.params.toolBudget !== undefined ? { toolBudget: input.params.toolBudget } : {}),
1544
1742
  capabilityCeiling: intersectSubagentCapabilityCeilings("capabilityCeiling" in target ? target.capabilityCeiling : undefined, recoveryDescriptor?.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId)),
1743
+ runFanoutBudget: input.params.runFanoutBudget ?? recoveryDescriptor?.runFanoutBudget ?? createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(input.deps.config.maxSubagentSpawnsPerRun)),
1545
1744
  parentWorkflowRunId: input.params.workflowParentRunId,
1546
1745
  workflowKey: input.params.workflowKey,
1746
+ activeAsyncCapacity,
1547
1747
  }));
1548
- if (result.isError) return result;
1748
+ if (result.isError) {
1749
+ const startedStatus = readStatus(revivalAsyncDir);
1750
+ if (input.params.workflowParentRunId !== undefined && startedStatus?.runId === runId && startedStatus.processTerminal?.runnerProcessInstanceId) {
1751
+ return {
1752
+ ...result,
1753
+ details: {
1754
+ ...result.details,
1755
+ runId,
1756
+ asyncId: runId,
1757
+ asyncDir: revivalAsyncDir,
1758
+ ...(target.launchContractDigest ? { sourceLaunchContractDigest: target.launchContractDigest } : {}),
1759
+ },
1760
+ };
1761
+ }
1762
+ activeAsyncCapacity?.rollback();
1763
+ return result;
1764
+ }
1549
1765
  for (const brief of queuedBriefs) fs.rmSync(brief.path, { force: true });
1550
1766
  if (queuedBriefs.length > 0 && sourceAsyncDir) {
1551
1767
  const sourceStatus = readStatus(sourceAsyncDir);
@@ -1556,6 +1772,58 @@ async function resumeAsyncRun(input: {
1556
1772
  }
1557
1773
 
1558
1774
  const revivedId = result.details.asyncId ?? runId;
1775
+ if (input.params.workflowParentRunId !== undefined && result.details.asyncDir) {
1776
+ const asyncDir = result.details.asyncDir;
1777
+ const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
1778
+ const stopOnAbort = () => { stopAsyncRun(input.deps.state, revivedId, input.deps.kill, { asyncDir, resolvedId: revivedId }); };
1779
+ if (input.signal?.aborted) stopOnAbort();
1780
+ else input.signal?.addEventListener("abort", stopOnAbort, { once: true });
1781
+ let completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>;
1782
+ try {
1783
+ completed = await waitForImportedAsyncRoot({ runId: revivedId, asyncDir, resultPath, index: 0 });
1784
+ } finally {
1785
+ input.signal?.removeEventListener("abort", stopOnAbort);
1786
+ }
1787
+ fs.rmSync(resultPath, { force: true });
1788
+ const totalCost = completed.totalCost;
1789
+ const childResult: SingleResult = {
1790
+ index: 0,
1791
+ agent: completed.agent,
1792
+ task: effectiveFollowUp,
1793
+ exitCode: completed.exitCode,
1794
+ usage: {
1795
+ input: totalCost?.inputTokens ?? 0,
1796
+ output: totalCost?.outputTokens ?? 0,
1797
+ cacheRead: 0,
1798
+ cacheWrite: 0,
1799
+ cost: totalCost?.costUsd ?? 0,
1800
+ turns: 0,
1801
+ },
1802
+ finalOutput: completed.output,
1803
+ outputState: completed.output.trim() ? "present" : "absent",
1804
+ ...(completed.error ? { error: completed.error } : {}),
1805
+ ...(completed.timedOut ? { timedOut: true } : {}),
1806
+ ...(completed.stopped ? { stopped: true } : {}),
1807
+ ...(completed.sessionFile ? { sessionFile: completed.sessionFile } : {}),
1808
+ ...(completed.model ? { model: completed.model } : {}),
1809
+ ...(completed.attemptedModels ? { attemptedModels: completed.attemptedModels } : {}),
1810
+ ...(completed.modelAttempts ? { modelAttempts: completed.modelAttempts } : {}),
1811
+ ...(completed.structuredOutput !== undefined ? { structuredOutput: completed.structuredOutput } : {}),
1812
+ ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
1813
+ ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
1814
+ ...(completed.acceptance ? { acceptance: completed.acceptance } : {}),
1815
+ };
1816
+ return {
1817
+ content: [{ type: "text", text: completed.output || completed.error || `Revived ${target.source} subagent ${revivedId} completed without output.` }],
1818
+ ...(completed.success ? {} : { isError: true }),
1819
+ details: {
1820
+ ...result.details,
1821
+ runId: revivedId,
1822
+ results: [childResult],
1823
+ ...(target.launchContractDigest ? { sourceLaunchContractDigest: target.launchContractDigest } : {}),
1824
+ },
1825
+ };
1826
+ }
1559
1827
  const revivedTarget = intercomBridge.active ? resolveSubagentIntercomTarget(revivedId, target.agent, 0) : undefined;
1560
1828
  const sourceLabel = target.source;
1561
1829
  const lines = [
@@ -1979,7 +2247,38 @@ function applySingleAgentLaunchDefaults(params: SubagentParamsLike, agents: Agen
1979
2247
 
1980
2248
  export const DEFAULT_FOREGROUND_TIMEOUT_MS = 30 * 60 * 1000;
1981
2249
 
1982
- function resolveForegroundTimeout(params: SubagentParamsLike, defaultTimeoutMs?: number): { timeoutMs?: number; error?: string } {
2250
+ // Async single-agent runs also need a wall-clock backstop: a child whose bash
2251
+ // tool blocks forever (e.g. a background process inheriting the terminal with
2252
+ // no bash `timeout` arg) would otherwise hang the parent indefinitely with
2253
+ // zero signal. Same generous default as foreground; explicit timeoutMs/
2254
+ // maxRuntimeMs and agent-level defaultTimeoutMs remain authoritative.
2255
+ //
2256
+ // Deliberately NOT applied at the workflow level: async scripted workflows
2257
+ // stay unbounded as a whole, while each runner child has its own deadline.
2258
+ export { DEFAULT_ASYNC_TIMEOUT_MS };
2259
+
2260
+ /**
2261
+ * Maximum delay a Node.js timer accepts. Values above the 32-bit signed integer
2262
+ * ceiling overflow `setTimeout`, which silently clamps the delay to ~1ms and
2263
+ * fires almost immediately — so a run configured with a larger deadline would
2264
+ * terminate right away while reporting the long duration. Any timeout destined
2265
+ * for a timer must stay within this bound.
2266
+ */
2267
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
2268
+
2269
+ /**
2270
+ * Resolve the optional global default runtime deadline from extension config
2271
+ * (`config.timeoutMs`). Returns undefined for unset or invalid values so callers
2272
+ * fall back to the built-in defaults. "Invalid" covers non-positive-integer
2273
+ * values and values above `MAX_TIMER_DELAY_MS`; the latter would overflow the
2274
+ * Node.js timer and expire the run almost immediately instead of running long.
2275
+ */
2276
+ export function resolveConfigDefaultTimeoutMs(raw: unknown): number | undefined {
2277
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw <= 0 || raw > MAX_TIMER_DELAY_MS) return undefined;
2278
+ return raw;
2279
+ }
2280
+
2281
+ export function resolveForegroundTimeout(params: SubagentParamsLike, defaultTimeoutMs?: number): { timeoutMs?: number; error?: string } {
1983
2282
  const rawTimeout = params.timeoutMs;
1984
2283
  const rawMaxRuntime = params.maxRuntimeMs;
1985
2284
  if (rawTimeout === undefined && rawMaxRuntime === undefined) {
@@ -1998,6 +2297,25 @@ function resolveForegroundTimeout(params: SubagentParamsLike, defaultTimeoutMs?:
1998
2297
  return timeoutMs === undefined ? {} : { timeoutMs };
1999
2298
  }
2000
2299
 
2300
+ /**
2301
+ * Resolve the effective launch timeout for a single-agent run, applying the
2302
+ * async/foreground default when neither the caller nor the agent set one.
2303
+ *
2304
+ * A global config default (`config.timeoutMs`, passed as `configDefaultTimeoutMs`)
2305
+ * replaces the built-in 30-minute backstop wherever a concrete default is applied.
2306
+ * The async default is deliberately applied only to plain single-agent launches.
2307
+ * Composite launches keep their top-level execution unbounded when no timeout is
2308
+ * set — even with a config default — while their runner children resolve separate
2309
+ * deadlines. Exported so the executor wiring is directly testable.
2310
+ */
2311
+ export function resolveSingleAgentLaunchTimeout(params: SubagentParamsLike, async: boolean, configDefaultTimeoutMs?: number): { timeoutMs?: number; error?: string } {
2312
+ const isComposite = (params.chain?.length ?? 0) > 0 || (params.tasks?.length ?? 0) > 0 || params.workflowScript !== undefined;
2313
+ const foregroundDefault = configDefaultTimeoutMs ?? DEFAULT_FOREGROUND_TIMEOUT_MS;
2314
+ const asyncSingleDefault = configDefaultTimeoutMs ?? DEFAULT_ASYNC_TIMEOUT_MS;
2315
+ const defaultTimeoutMs = !async ? foregroundDefault : isComposite ? undefined : asyncSingleDefault;
2316
+ return resolveForegroundTimeout(params, defaultTimeoutMs);
2317
+ }
2318
+
2001
2319
  function resolveToolBudget(
2002
2320
  raw: unknown,
2003
2321
  label = "toolBudget",
@@ -2407,7 +2725,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2407
2725
  details: { mode: "single" as const, results: [] },
2408
2726
  };
2409
2727
  }
2410
- const id = randomUUID();
2728
+ const id = data.asyncRunId;
2411
2729
  const parentModel = data.parentModel;
2412
2730
  const asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
2413
2731
  pi: deps.pi,
@@ -2461,6 +2779,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2461
2779
  shareEnabled,
2462
2780
  sessionRoot,
2463
2781
  chainSkills: [],
2782
+ activeAsyncCapacity: data.activeAsyncCapacity,
2464
2783
  sessionFilesByFlatIndex: params.tasks.map((task, index) => sessionFileForTask(task.agent, index, task.model)),
2465
2784
  thinkingOverridesByFlatIndex: params.tasks.map((task, index) => thinkingOverrideForTask(task.agent, index, task.model)),
2466
2785
  contextForAgent: contextPolicy.contextForAgent,
@@ -2480,6 +2799,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2480
2799
  usageBudget: data.usageBudget,
2481
2800
  configToolBudget: data.configToolBudget,
2482
2801
  capabilityCeiling: data.capabilityCeiling,
2802
+ runFanoutBudget: data.runFanoutBudget,
2483
2803
  globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
2484
2804
  parentWorkflowRunId: params.workflowParentRunId,
2485
2805
  workflowKey: params.workflowKey,
@@ -2505,6 +2825,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2505
2825
  shareEnabled,
2506
2826
  sessionRoot,
2507
2827
  chainSkills,
2828
+ activeAsyncCapacity: data.activeAsyncCapacity,
2508
2829
  sessionFilesByFlatIndex: collectChainSessionFiles(chain, sessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems),
2509
2830
  thinkingOverridesByFlatIndex: collectChainThinkingOverrides(chain, thinkingOverrideForTask, deps.config.chain?.dynamicFanout?.maxItems),
2510
2831
  contextForAgent: contextPolicy.contextForAgent,
@@ -2525,6 +2846,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2525
2846
  usageBudget: data.usageBudget,
2526
2847
  configToolBudget: data.configToolBudget,
2527
2848
  capabilityCeiling: data.capabilityCeiling,
2849
+ runFanoutBudget: data.runFanoutBudget,
2528
2850
  globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
2529
2851
  parentWorkflowRunId: params.workflowParentRunId,
2530
2852
  workflowKey: params.workflowKey,
@@ -2546,12 +2868,18 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2546
2868
  const normalizedSkills = normalizeSkillInput(params.skill);
2547
2869
  const skills = normalizedSkills === false ? [] : normalizedSkills;
2548
2870
  const maxSubagentDepth = resolveChildMaxSubagentDepth(currentMaxSubagentDepth, a.maxSubagentDepth);
2549
- const modelOverride = resolveEffectiveSubagentModel(params.model as string | undefined, a.model, parentModel, availableModels, currentProvider, data.modelScope === undefined ? {} : { scope: data.modelScope });
2871
+ const externalRunnerWithoutExplicitModel = a.runner?.type === "external-cli"
2872
+ && params.model === undefined
2873
+ && (a.model === undefined || (a.modelSource?.type === "subagents.defaultModel" && a.model === a.modelSource.model));
2874
+ const modelOverride = externalRunnerWithoutExplicitModel
2875
+ ? undefined
2876
+ : resolveEffectiveSubagentModel(params.model as string | undefined, a.model, parentModel, availableModels, currentProvider, data.modelScope === undefined ? {} : { scope: data.modelScope });
2550
2877
  return executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
2551
2878
  agent: params.agent!,
2552
2879
  task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(params.task ?? "") : (params.task ?? ""),
2553
2880
  goal: params.task ?? "",
2554
2881
  agentConfig: a,
2882
+ recoveryAgentConfig: data.recoveryAgents.find((agent) => agent.name === params.agent),
2555
2883
  ctx: asyncCtx,
2556
2884
  availableModels,
2557
2885
  cwd: effectiveCwd,
@@ -2559,6 +2887,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2559
2887
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
2560
2888
  artifactConfig,
2561
2889
  shareEnabled,
2890
+ activeAsyncCapacity: data.activeAsyncCapacity,
2562
2891
  sessionRoot,
2563
2892
  sessionFile: sessionFileForTask(params.agent!, 0, modelOverride),
2564
2893
  context: contextPolicy.contextForAgent(params.agent!),
@@ -2568,13 +2897,14 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2568
2897
  ...(params.reads !== undefined ? { reads: params.reads } : {}),
2569
2898
  outputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),
2570
2899
  modelOverride,
2571
- thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride),
2900
+ thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(params.agent!, 0, modelOverride),
2572
2901
  maxSubagentDepth,
2573
2902
  waitToolEnabled: deps.waitToolEnabled,
2574
2903
  worktreeSetupHook: deps.config.worktreeSetupHook,
2575
2904
  worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
2576
2905
  worktreeBaseDir: deps.config.worktreeBaseDir,
2577
2906
  controlConfig,
2907
+ intercomBridge: params.intercomBridge,
2578
2908
  controlIntercomTarget,
2579
2909
  childIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(agent, index) : undefined,
2580
2910
  nestedRoute,
@@ -2587,6 +2917,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2587
2917
  usageBudget: data.usageBudget,
2588
2918
  configToolBudget: data.configToolBudget,
2589
2919
  capabilityCeiling: data.capabilityCeiling,
2920
+ runFanoutBudget: data.runFanoutBudget,
2590
2921
  parentWorkflowRunId: params.workflowParentRunId,
2591
2922
  workflowKey: params.workflowKey,
2592
2923
  }));
@@ -2677,6 +3008,7 @@ async function runChainPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
2677
3008
  permissions: deps.config.permissions,
2678
3009
  globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
2679
3010
  capabilityCeiling: data.capabilityCeiling,
3011
+ runFanoutBudget: data.runFanoutBudget,
2680
3012
  }));
2681
3013
 
2682
3014
  if (chainResult.requestedAsync) {
@@ -2687,7 +3019,9 @@ async function runChainPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
2687
3019
  details: { mode: "chain" as const, results: [] },
2688
3020
  };
2689
3021
  }
2690
- const id = randomUUID();
3022
+ const id = data.asyncRunId;
3023
+ const capacity = acquireClarifiedBackgroundCapacity(data, deps, "chain", id);
3024
+ if (capacity.errorResult) return capacity.errorResult;
2691
3025
  const parentModel = data.parentModel;
2692
3026
  const asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
2693
3027
  pi: deps.pi,
@@ -2703,42 +3037,48 @@ async function runChainPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
2703
3037
  const rawAsyncChain = chainResult.requestedAsync.chain;
2704
3038
  const asyncChain = wrapChainTasksForFork(rawAsyncChain, contextPolicy);
2705
3039
  const firstAgent = firstChainAgent(rawAsyncChain);
2706
- return executeAsyncChain(id, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
2707
- chain: asyncChain,
2708
- task: params.task,
2709
- goal: resolveAsyncEventGoal(params.task, rawAsyncChain, firstAgent ? shouldForkAgent(contextPolicy, firstAgent) : false),
2710
- agents,
2711
- ctx: asyncCtx,
2712
- availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
2713
- cwd: effectiveCwd,
2714
- maxOutput: params.maxOutput,
2715
- artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
2716
- artifactConfig,
2717
- shareEnabled,
2718
- sessionRoot,
2719
- chainSkills: chainResult.requestedAsync.chainSkills,
2720
- sessionFilesByFlatIndex: collectChainSessionFiles(asyncChain, sessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems),
2721
- thinkingOverridesByFlatIndex: collectChainThinkingOverrides(asyncChain, thinkingOverrideForTask, deps.config.chain?.dynamicFanout?.maxItems),
2722
- contextForAgent: contextPolicy.contextForAgent,
2723
- dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
2724
- maxSubagentDepth: currentMaxSubagentDepth,
2725
- waitToolEnabled: deps.waitToolEnabled,
2726
- worktreeSetupHook: deps.config.worktreeSetupHook,
2727
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
2728
- worktreeBaseDir: deps.config.worktreeBaseDir,
2729
- controlConfig,
2730
- agentContract: params.agentContract,
2731
- controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
2732
- childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
2733
- nestedRoute: data.nestedRoute,
2734
- timeoutMs: data.timeoutMs,
2735
- turnBudget: data.turnBudget,
2736
- toolBudget: data.toolBudget,
2737
- usageBudget: data.usageBudget,
2738
- configToolBudget: data.configToolBudget,
2739
- capabilityCeiling: data.capabilityCeiling,
2740
- globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
2741
- }));
3040
+ try {
3041
+ return executeAsyncChain(id, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
3042
+ chain: asyncChain,
3043
+ task: params.task,
3044
+ goal: resolveAsyncEventGoal(params.task, rawAsyncChain, firstAgent ? shouldForkAgent(contextPolicy, firstAgent) : false),
3045
+ agents,
3046
+ ctx: asyncCtx,
3047
+ availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
3048
+ cwd: effectiveCwd,
3049
+ maxOutput: params.maxOutput,
3050
+ artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3051
+ artifactConfig,
3052
+ shareEnabled,
3053
+ sessionRoot,
3054
+ chainSkills: chainResult.requestedAsync.chainSkills,
3055
+ activeAsyncCapacity: capacity.activeAsyncCapacity,
3056
+ sessionFilesByFlatIndex: collectChainSessionFiles(asyncChain, sessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems),
3057
+ thinkingOverridesByFlatIndex: collectChainThinkingOverrides(asyncChain, thinkingOverrideForTask, deps.config.chain?.dynamicFanout?.maxItems),
3058
+ contextForAgent: contextPolicy.contextForAgent,
3059
+ dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
3060
+ maxSubagentDepth: currentMaxSubagentDepth,
3061
+ waitToolEnabled: deps.waitToolEnabled,
3062
+ worktreeSetupHook: deps.config.worktreeSetupHook,
3063
+ worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
3064
+ worktreeBaseDir: deps.config.worktreeBaseDir,
3065
+ controlConfig,
3066
+ agentContract: params.agentContract,
3067
+ controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
3068
+ childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
3069
+ nestedRoute: data.nestedRoute,
3070
+ timeoutMs: data.timeoutMs,
3071
+ turnBudget: data.turnBudget,
3072
+ toolBudget: data.toolBudget,
3073
+ usageBudget: data.usageBudget,
3074
+ configToolBudget: data.configToolBudget,
3075
+ capabilityCeiling: data.capabilityCeiling,
3076
+ runFanoutBudget: data.runFanoutBudget,
3077
+ globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
3078
+ }));
3079
+ } finally {
3080
+ finalizeClarifiedBackgroundCapacity(data, deps, capacity.activeAsyncCapacity);
3081
+ }
2742
3082
  }
2743
3083
 
2744
3084
  const rawChainDetails = chainResult.details ? compactOptional<Details>({ ...chainResult.details, runId, timeoutMs: data.timeoutMs }) : undefined;
@@ -2783,6 +3123,7 @@ interface ForegroundParallelRunInput {
2783
3123
  intercomEvents: IntercomEventBus;
2784
3124
  parentSessionId: string | null;
2785
3125
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
3126
+ runFanoutBudget: RunFanoutBudgetDescriptor;
2786
3127
  signal: AbortSignal;
2787
3128
  runId: string;
2788
3129
  sessionDirForIndex: (idx?: number) => string | undefined;
@@ -2832,6 +3173,48 @@ function buildParallelModeError(message: string): AgentToolResult<Details> {
2832
3173
  };
2833
3174
  }
2834
3175
 
3176
+ function acquireClarifiedBackgroundCapacity(
3177
+ data: ExecutionContextData,
3178
+ deps: ExecutorDeps,
3179
+ mode: "single" | "parallel" | "chain",
3180
+ asyncRunId: string,
3181
+ ): { activeAsyncCapacity?: ActiveAsyncCapacityHandle; errorResult?: AgentToolResult<Details> } {
3182
+ if (!data.topLevelAsyncCapacityEligible || !data.parentSessionId) return {};
3183
+ const liveWorkflowRunIds = new Set(deps.state.workflowControllers?.keys() ?? []);
3184
+ const activeLimit = resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession);
3185
+ try {
3186
+ const activeAsyncCapacity = acquireActiveAsyncCapacity({
3187
+ sessionId: data.parentSessionId,
3188
+ limit: activeLimit,
3189
+ runId: asyncRunId,
3190
+ kind: "runner",
3191
+ asyncDir: path.join(DIRS.async, asyncRunId),
3192
+ }, { liveWorkflowRunIds });
3193
+ deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(data.parentSessionId, activeLimit, { liveWorkflowRunIds });
3194
+ return { activeAsyncCapacity };
3195
+ } catch (error) {
3196
+ if (error instanceof ActiveAsyncCapacityError) {
3197
+ deps.state.activeAsyncCapacity = error.snapshot;
3198
+ return { errorResult: { content: [{ type: "text", text: error.message }], isError: true, details: { mode, results: [], activeAsyncCapacity: error.snapshot } } };
3199
+ }
3200
+ throw error;
3201
+ }
3202
+ }
3203
+
3204
+ function finalizeClarifiedBackgroundCapacity(
3205
+ data: ExecutionContextData,
3206
+ deps: ExecutorDeps,
3207
+ activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined,
3208
+ ): void {
3209
+ if (!activeAsyncCapacity || !data.parentSessionId) return;
3210
+ if (!activeAsyncCapacity.owner.runnerStartedAt) activeAsyncCapacity.rollback();
3211
+ deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(
3212
+ data.parentSessionId,
3213
+ resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession),
3214
+ { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) },
3215
+ );
3216
+ }
3217
+
2835
3218
  function createParallelWorktreeSetup(
2836
3219
  enabled: boolean | undefined,
2837
3220
  cwd: string,
@@ -2867,10 +3250,128 @@ function buildParallelWorktreeTaskCwdError(
2867
3250
  return formatWorktreeTaskCwdConflict(conflict, sharedCwd);
2868
3251
  }
2869
3252
 
2870
- function resolveSingleRunOutputBaseDir(deps: ExecutorDeps, artifactsDir: string, runId: string): string {
3253
+ function resolveConfiguredSingleRunOutputBaseDir(deps: ExecutorDeps): string | undefined {
2871
3254
  return deps.config.singleRunOutputBaseDir
2872
3255
  ? path.resolve(deps.expandTilde(deps.config.singleRunOutputBaseDir))
2873
- : path.join(artifactsDir, "outputs", runId);
3256
+ : undefined;
3257
+ }
3258
+
3259
+ function resolveSingleRunOutputBaseDir(deps: ExecutorDeps, artifactsDir: string, runId: string): string {
3260
+ return resolveConfiguredSingleRunOutputBaseDir(deps) ?? path.join(artifactsDir, "outputs", runId);
3261
+ }
3262
+
3263
+ function resolveWorkflowAggregateOutputPath(
3264
+ output: string | boolean | undefined,
3265
+ ctxCwd: string,
3266
+ workflowCwd: string,
3267
+ outputBaseDir: string,
3268
+ configuredOutputBaseDir: string | undefined,
3269
+ ): string | undefined {
3270
+ if (typeof output === "string" && output && !path.isAbsolute(output) && !configuredOutputBaseDir) return path.resolve(workflowCwd, output);
3271
+ return resolveSingleOutputPath(output, ctxCwd, workflowCwd, outputBaseDir);
3272
+ }
3273
+
3274
+ function workflowChildDefaultOutput(aggregateOutputPath: string | undefined, artifactsDir: string, workflowRunId: string, workflowKey: string): string {
3275
+ if (aggregateOutputPath) {
3276
+ const parsed = path.parse(aggregateOutputPath);
3277
+ return path.join(parsed.dir, `${parsed.name}.${workflowKey}${parsed.ext || ".md"}`);
3278
+ }
3279
+ return path.join(artifactsDir, "outputs", workflowRunId, `${workflowKey}.md`);
3280
+ }
3281
+
3282
+ function writeWorkflowAggregateOutput(outputPath: string | undefined, text: string): string | undefined {
3283
+ if (!outputPath) return undefined;
3284
+ try {
3285
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
3286
+ fs.writeFileSync(outputPath, text, "utf-8");
3287
+ return undefined;
3288
+ } catch (error) {
3289
+ return `Output file error: ${outputPath}\n${error instanceof Error ? error.message : String(error)}`;
3290
+ }
3291
+ }
3292
+
3293
+ function appendWorkflowOutputWarning(text: string, warning: string | undefined): string {
3294
+ return warning ? `${text}\n\n${warning}` : text;
3295
+ }
3296
+
3297
+ function resolveWorkflowChildOutputPath(input: {
3298
+ ctxCwd: string;
3299
+ workflowCwd: string;
3300
+ artifactsDir: string;
3301
+ workflowRunId: string;
3302
+ aggregateOutputPath?: string;
3303
+ configuredOutputBaseDir?: string;
3304
+ discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3305
+ workflowAgentScope?: unknown;
3306
+ key: string;
3307
+ params: Record<string, unknown>;
3308
+ }): string | undefined {
3309
+ const rawOutput = input.params.output;
3310
+ const hasExplicitOutput = typeof rawOutput === "string" || typeof rawOutput === "boolean";
3311
+ const childCwd = typeof input.params.cwd === "string" ? resolveChildCwd(input.workflowCwd, input.params.cwd) : input.workflowCwd;
3312
+ const agentScope = resolveExecutionAgentScope(input.params.agentScope ?? input.workflowAgentScope);
3313
+ const agents = input.discoverAgents(childCwd, agentScope).agents;
3314
+ const agent = typeof input.params.agent === "string" ? resolveAgentName(input.params.agent, agents).agent : undefined;
3315
+ const agentOutput = typeof agent?.output === "string" ? agent.output : undefined;
3316
+ const output = rawOutput === true || rawOutput === "true"
3317
+ ? agentOutput
3318
+ : hasExplicitOutput
3319
+ ? rawOutput
3320
+ : workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.workflowRunId, input.key);
3321
+ return resolveSingleOutputPath(output, input.ctxCwd, childCwd, input.configuredOutputBaseDir);
3322
+ }
3323
+
3324
+ function workflowChildOutputClaims(input: {
3325
+ ctxCwd: string;
3326
+ workflowCwd: string;
3327
+ artifactsDir: string;
3328
+ workflowRunId: string;
3329
+ aggregateOutputPath?: string;
3330
+ configuredOutputBaseDir?: string;
3331
+ discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3332
+ workflowAgentScope?: unknown;
3333
+ claimedOutputPaths: Map<string, string>;
3334
+ entries: Array<{ key: string; params: Record<string, unknown> }>;
3335
+ }): { error?: string; claims?: Map<string, string> } {
3336
+ const claims = new Map(input.claimedOutputPaths);
3337
+ for (const { key, params } of input.entries) {
3338
+ const resolved = resolveWorkflowChildOutputPath({ ...input, key, params });
3339
+ if (!resolved) continue;
3340
+ if (input.aggregateOutputPath && resolved === input.aggregateOutputPath) return { error: `Workflow child '${key}' output resolves to the workflow aggregate output path: ${resolved}. Use a distinct child output path.` };
3341
+ const previous = claims.get(resolved);
3342
+ if (previous) return { error: `Workflow children '${previous}' and '${key}' resolve output to the same path: ${resolved}. Use distinct child output paths.` };
3343
+ claims.set(resolved, key);
3344
+ }
3345
+ return { claims };
3346
+ }
3347
+
3348
+ function applyWorkflowChildOutputClaims(target: Map<string, string>, claims: Map<string, string>): void {
3349
+ target.clear();
3350
+ for (const [resolved, key] of claims) target.set(resolved, key);
3351
+ }
3352
+
3353
+ function prepareWorkflowChildLaunchParams(input: {
3354
+ workflowDefaults: SubagentParamsLike;
3355
+ childParams: Record<string, unknown>;
3356
+ parentWorkflowRunId: string;
3357
+ workflowKey: string;
3358
+ ctxCwd: string;
3359
+ workflowCwd: string;
3360
+ artifactsDir: string;
3361
+ aggregateOutputPath?: string;
3362
+ configuredOutputBaseDir?: string;
3363
+ discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3364
+ workflowAgentScope?: unknown;
3365
+ options?: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor };
3366
+ }): SubagentParamsLike {
3367
+ let childParams = input.childParams;
3368
+ if (input.childParams.output === undefined && input.childParams.resume === undefined) {
3369
+ childParams = { ...input.childParams, output: workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.parentWorkflowRunId, input.workflowKey) };
3370
+ } else if (input.childParams.resume === undefined) {
3371
+ const resolvedOutput = resolveWorkflowChildOutputPath({ ctxCwd: input.ctxCwd, workflowCwd: input.workflowCwd, artifactsDir: input.artifactsDir, workflowRunId: input.parentWorkflowRunId, aggregateOutputPath: input.aggregateOutputPath, configuredOutputBaseDir: input.configuredOutputBaseDir, discoverAgents: input.discoverAgents, workflowAgentScope: input.workflowAgentScope, key: input.workflowKey, params: input.childParams });
3372
+ if (resolvedOutput) childParams = { ...input.childParams, output: resolvedOutput };
3373
+ }
3374
+ return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, input.options);
2874
3375
  }
2875
3376
 
2876
3377
  function buildChainWorktreeTaskCwdError(chain: ChainStep[], sharedCwd: string): string | undefined {
@@ -3020,7 +3521,33 @@ async function runForegroundParallelTasks(input: ForegroundParallelRunInput): Pr
3020
3521
  beginForegroundChild(input.foregroundControl, {
3021
3522
  index,
3022
3523
  agent: task.agent,
3023
- ...(input.taskDescriptions[index] === undefined ? {} : { description: input.taskDescriptions[index] }),
3524
+ authoredTask: input.taskDescriptions[index] ?? "",
3525
+ effectivePrompt: taskText,
3526
+ cwd: taskCwd,
3527
+ ...(outputPath ? { outputPath } : {}),
3528
+ rerun: { params: compactOptional<Record<string, unknown>>({
3529
+ agent: task.agent,
3530
+ task: input.taskDescriptions[index] ?? "",
3531
+ async: false,
3532
+ cwd: input.worktreeSetup ? undefined : taskCwd,
3533
+ worktree: input.worktreeSetup ? true : false,
3534
+ context: input.contextPolicy.contextForAgent(task.agent),
3535
+ share: input.shareEnabled || undefined,
3536
+ maxOutput: input.maxOutput,
3537
+ timeoutMs: input.timeoutMs,
3538
+ turnBudget: input.turnBudget,
3539
+ ...(model ? { model } : {}),
3540
+ ...(effectiveSkills !== undefined ? { skill: effectiveSkills } : {}),
3541
+ ...(outputPath ? { output: outputPath } : {}),
3542
+ ...(behavior?.outputMode !== undefined ? { outputMode: behavior.outputMode } : {}),
3543
+ ...(behavior?.reads !== undefined ? { reads: behavior.reads } : {}),
3544
+ ...(behavior?.progress !== undefined ? { progress: behavior.progress } : {}),
3545
+ ...(task.toolBudget !== undefined ? { toolBudget: task.toolBudget } : {}),
3546
+ ...(task.outputSchema !== undefined ? { outputSchema: task.outputSchema } : {}),
3547
+ ...(task.acceptance !== undefined ? { acceptance: task.acceptance } : {}),
3548
+ ...(task.agentContract !== undefined || input.agentContract !== undefined ? { agentContract: task.agentContract ?? input.agentContract } : {}),
3549
+ }) },
3550
+ description: `${task.agent} child`,
3024
3551
  ...(model ? { model } : {}),
3025
3552
  ...(thinking ? { thinking } : {}),
3026
3553
  interrupt: () => {
@@ -3037,7 +3564,10 @@ async function runForegroundParallelTasks(input: ForegroundParallelRunInput): Pr
3037
3564
  const result = await runSync(input.ctx.cwd, input.agents, task.agent, taskText, compactOptional<Parameters<typeof runSync>[4]>({
3038
3565
  permissions: input.permissions,
3039
3566
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
3567
+ llmIntentArbiter: createTaskMutationArbiter(input.ctx),
3568
+ ...workflowForegroundSteeringLaunchOptions(input.foregroundControl, index),
3040
3569
  context: input.contextPolicy.contextForAgent(task.agent),
3570
+ runFanoutBudget: { ...input.runFanoutBudget, parentPath: `${input.runFanoutBudget.parentPath ? `${input.runFanoutBudget.parentPath}/` : ""}tasks[${index}]` },
3041
3571
  cwd: taskCwd,
3042
3572
  signal: input.signal,
3043
3573
  interruptSignal: interruptController.signal,
@@ -3082,6 +3612,7 @@ async function runForegroundParallelTasks(input: ForegroundParallelRunInput): Pr
3082
3612
  agentContract: task.agentContract ?? input.agentContract,
3083
3613
  acceptance: task.acceptance,
3084
3614
  acceptanceContext: { mode: "parallel" },
3615
+ onEffectivePrompt: input.foregroundControl ? (prompt) => updateLiveEffectivePrompt(input.foregroundControl!, index, prompt) : undefined,
3085
3616
  timeoutMs: input.timeoutMs,
3086
3617
  deadlineAt: input.deadlineAt,
3087
3618
  turnBudget: input.turnBudget,
@@ -3265,7 +3796,9 @@ async function runParallelPath(data: ExecutionContextData, deps: ExecutorDeps):
3265
3796
  details: { mode: "parallel" as const, results: [] },
3266
3797
  };
3267
3798
  }
3268
- const id = randomUUID();
3799
+ const id = data.asyncRunId;
3800
+ const capacity = acquireClarifiedBackgroundCapacity(data, deps, "parallel", id);
3801
+ if (capacity.errorResult) return capacity.errorResult;
3269
3802
  const asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
3270
3803
  pi: deps.pi,
3271
3804
  cwd: ctx.cwd,
@@ -3296,40 +3829,46 @@ async function runParallelPath(data: ExecutionContextData, deps: ExecutorDeps):
3296
3829
  ...(t.agentContract !== undefined ? { agentContract: t.agentContract } : {}),
3297
3830
  });
3298
3831
  });
3299
- return executeAsyncChain(id, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
3300
- chain: [compactOptional<ParallelStep>({ parallel: parallelTasks, concurrency: parallelConcurrency, worktree: params.worktree })],
3301
- resultMode: "parallel",
3302
- goal: taskTexts[0] ?? "",
3303
- agents,
3304
- ctx: asyncCtx,
3305
- availableModels,
3306
- cwd: effectiveCwd,
3307
- maxOutput: params.maxOutput,
3308
- artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3309
- artifactConfig,
3310
- shareEnabled,
3311
- sessionRoot,
3312
- chainSkills: [],
3313
- sessionFilesByFlatIndex: tasks.map((task, index) => sessionFileForTask(task.agent, index, modelOverrides[index])),
3314
- thinkingOverridesByFlatIndex: tasks.map((task, index) => thinkingOverrideForTask(task.agent, index, modelOverrides[index])),
3315
- contextForAgent: contextPolicy.contextForAgent,
3316
- maxSubagentDepth: currentMaxSubagentDepth,
3317
- waitToolEnabled: deps.waitToolEnabled,
3318
- worktreeSetupHook: deps.config.worktreeSetupHook,
3319
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
3320
- worktreeBaseDir: deps.config.worktreeBaseDir,
3321
- controlConfig,
3322
- agentContract: params.agentContract,
3323
- controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
3324
- childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
3325
- nestedRoute: data.nestedRoute,
3326
- timeoutMs: data.timeoutMs,
3327
- turnBudget: data.turnBudget,
3328
- usageBudget: data.usageBudget,
3329
- toolBudget: data.toolBudget,
3330
- configToolBudget: data.configToolBudget,
3331
- globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
3332
- }));
3832
+ try {
3833
+ return executeAsyncChain(id, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
3834
+ chain: [compactOptional<ParallelStep>({ parallel: parallelTasks, concurrency: parallelConcurrency, worktree: params.worktree })],
3835
+ resultMode: "parallel",
3836
+ goal: taskTexts[0] ?? "",
3837
+ agents,
3838
+ ctx: asyncCtx,
3839
+ availableModels,
3840
+ cwd: effectiveCwd,
3841
+ maxOutput: params.maxOutput,
3842
+ artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3843
+ artifactConfig,
3844
+ shareEnabled,
3845
+ sessionRoot,
3846
+ chainSkills: [],
3847
+ activeAsyncCapacity: capacity.activeAsyncCapacity,
3848
+ sessionFilesByFlatIndex: tasks.map((task, index) => sessionFileForTask(task.agent, index, modelOverrides[index])),
3849
+ thinkingOverridesByFlatIndex: tasks.map((task, index) => thinkingOverrideForTask(task.agent, index, modelOverrides[index])),
3850
+ contextForAgent: contextPolicy.contextForAgent,
3851
+ maxSubagentDepth: currentMaxSubagentDepth,
3852
+ waitToolEnabled: deps.waitToolEnabled,
3853
+ worktreeSetupHook: deps.config.worktreeSetupHook,
3854
+ worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
3855
+ worktreeBaseDir: deps.config.worktreeBaseDir,
3856
+ controlConfig,
3857
+ agentContract: params.agentContract,
3858
+ controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
3859
+ childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
3860
+ nestedRoute: data.nestedRoute,
3861
+ timeoutMs: data.timeoutMs,
3862
+ turnBudget: data.turnBudget,
3863
+ usageBudget: data.usageBudget,
3864
+ toolBudget: data.toolBudget,
3865
+ configToolBudget: data.configToolBudget,
3866
+ globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
3867
+ runFanoutBudget: data.runFanoutBudget,
3868
+ }));
3869
+ } finally {
3870
+ finalizeClarifiedBackgroundCapacity(data, deps, capacity.activeAsyncCapacity);
3871
+ }
3333
3872
  }
3334
3873
  }
3335
3874
 
@@ -3408,6 +3947,7 @@ async function runParallelPath(data: ExecutionContextData, deps: ExecutorDeps):
3408
3947
  intercomEvents: deps.pi.events,
3409
3948
  parentSessionId: data.parentSessionId,
3410
3949
  capabilityCeiling: data.capabilityCeiling,
3950
+ runFanoutBudget: data.runFanoutBudget,
3411
3951
  signal,
3412
3952
  runId,
3413
3953
  sessionDirForIndex,
@@ -3642,7 +4182,9 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3642
4182
  details: { mode: "single" as const, results: [] },
3643
4183
  };
3644
4184
  }
3645
- const id = randomUUID();
4185
+ const id = data.asyncRunId;
4186
+ const capacity = acquireClarifiedBackgroundCapacity(data, deps, "single", id);
4187
+ if (capacity.errorResult) return capacity.errorResult;
3646
4188
  const asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
3647
4189
  pi: deps.pi,
3648
4190
  cwd: ctx.cwd,
@@ -3654,49 +4196,58 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3654
4196
  interactive: ctx.hasUI,
3655
4197
  permissions: deps.config.permissions,
3656
4198
  });
3657
- return executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
3658
- agent: params.agent!,
3659
- task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(task) : task,
3660
- goal: task,
3661
- agentConfig,
3662
- ctx: asyncCtx,
3663
- availableModels,
3664
- cwd: effectiveCwd,
3665
- maxOutput: params.maxOutput,
3666
- artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3667
- artifactConfig,
3668
- shareEnabled,
3669
- sessionRoot,
3670
- sessionFile: sessionFileForTask(params.agent!, 0, modelOverride),
3671
- context: contextPolicy.contextForAgent(params.agent!),
3672
- skills: skillOverride === false ? [] : skillOverride,
3673
- output: effectiveOutput,
3674
- outputMode: effectiveOutputMode,
3675
- ...(readsOverride !== undefined ? { reads: readsOverride } : {}),
3676
- outputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),
3677
- modelOverride,
3678
- thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride),
3679
- maxSubagentDepth,
3680
- waitToolEnabled: deps.waitToolEnabled,
3681
- worktreeSetupHook: deps.config.worktreeSetupHook,
3682
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
3683
- worktreeBaseDir: deps.config.worktreeBaseDir,
3684
- controlConfig,
3685
- controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
3686
- childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
3687
- nestedRoute: data.nestedRoute,
3688
- agentContract: params.agentContract,
3689
- structuredOutputSchema: params.outputSchema,
3690
- acceptance: params.acceptance,
3691
- timeoutMs: data.timeoutMs,
3692
- turnBudget: data.turnBudget,
3693
- toolBudget: effectiveToolBudget.toolBudget,
3694
- usageBudget: data.usageBudget,
3695
- allowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,
3696
- }));
4199
+ try {
4200
+ return executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
4201
+ agent: params.agent!,
4202
+ task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(task) : task,
4203
+ goal: task,
4204
+ agentConfig,
4205
+ recoveryAgentConfig: data.recoveryAgents.find((agent) => agent.name === params.agent),
4206
+ ctx: asyncCtx,
4207
+ availableModels,
4208
+ cwd: effectiveCwd,
4209
+ maxOutput: params.maxOutput,
4210
+ artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
4211
+ artifactConfig,
4212
+ shareEnabled,
4213
+ activeAsyncCapacity: capacity.activeAsyncCapacity,
4214
+ sessionRoot,
4215
+ sessionFile: sessionFileForTask(params.agent!, 0, modelOverride),
4216
+ context: contextPolicy.contextForAgent(params.agent!),
4217
+ skills: skillOverride === false ? [] : skillOverride,
4218
+ output: effectiveOutput,
4219
+ outputMode: effectiveOutputMode,
4220
+ ...(readsOverride !== undefined ? { reads: readsOverride } : {}),
4221
+ outputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),
4222
+ modelOverride,
4223
+ thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride),
4224
+ maxSubagentDepth,
4225
+ waitToolEnabled: deps.waitToolEnabled,
4226
+ worktreeSetupHook: deps.config.worktreeSetupHook,
4227
+ worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
4228
+ worktreeBaseDir: deps.config.worktreeBaseDir,
4229
+ controlConfig,
4230
+ intercomBridge: params.intercomBridge,
4231
+ controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
4232
+ childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
4233
+ nestedRoute: data.nestedRoute,
4234
+ agentContract: params.agentContract,
4235
+ structuredOutputSchema: params.outputSchema,
4236
+ acceptance: params.acceptance,
4237
+ timeoutMs: data.timeoutMs,
4238
+ turnBudget: data.turnBudget,
4239
+ toolBudget: effectiveToolBudget.toolBudget,
4240
+ usageBudget: data.usageBudget,
4241
+ allowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,
4242
+ runFanoutBudget: data.runFanoutBudget,
4243
+ }));
4244
+ } finally {
4245
+ finalizeClarifiedBackgroundCapacity(data, deps, capacity.activeAsyncCapacity);
4246
+ }
3697
4247
  }
3698
4248
  }
3699
4249
 
4250
+ const authoredTask = task;
3700
4251
  if (shouldForkAgent(contextPolicy, params.agent!)) {
3701
4252
  task = wrapForkTask(task);
3702
4253
  }
@@ -3712,8 +4263,9 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3712
4263
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
3713
4264
  // absolute paths pass through; relative paths resolve against the child cwd.
3714
4265
  const reads = readsOverride !== undefined ? readsOverride : agentConfig.defaultReads ?? false;
3715
- const readsInstruction = Array.isArray(reads) && reads.length > 0
3716
- ? `[Read from: ${reads.map((f) => resolveChainPath(f, effectiveCwd)).join(", ")}]\n\n`
4266
+ const readPaths = Array.isArray(reads) ? resolveExistingReadPaths(reads, effectiveCwd) : [];
4267
+ const readsInstruction = readPaths.length > 0
4268
+ ? `[Read from: ${readPaths.join(", ")}]\n\n`
3717
4269
  : "";
3718
4270
  task = readsInstruction + task;
3719
4271
  task = injectSingleOutputInstruction(task, outputPath, agentConfig);
@@ -3732,6 +4284,11 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3732
4284
  beginForegroundChild(foregroundControl, omitUndefinedProperties({
3733
4285
  index: 0,
3734
4286
  agent: params.agent!,
4287
+ authoredTask,
4288
+ effectivePrompt: task,
4289
+ cwd: effectiveCwd,
4290
+ outputPath,
4291
+ rerun: { params: { ...params, task: authoredTask, async: params.async ?? false } },
3735
4292
  description: foregroundControl.description,
3736
4293
  ...(modelOverride ? { model: modelOverride } : {}),
3737
4294
  ...(thinking ? { thinking } : {}),
@@ -3757,7 +4314,10 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3757
4314
  r = await runSync(ctx.cwd, agents, params.agent!, task, compactOptional<Parameters<typeof runSync>[4]>({
3758
4315
  permissions: deps.config.permissions,
3759
4316
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
4317
+ llmIntentArbiter: createTaskMutationArbiter(ctx),
4318
+ ...workflowForegroundSteeringLaunchOptions(foregroundControl, 0),
3760
4319
  context: data.contextPolicy.contextForAgent(params.agent!),
4320
+ runFanoutBudget: params.runFanoutAdmitted ? data.runFanoutBudget : { ...data.runFanoutBudget, parentPath: `${data.runFanoutBudget.parentPath ? `${data.runFanoutBudget.parentPath}/` : ""}single` },
3761
4321
  cwd: effectiveCwd,
3762
4322
  signal,
3763
4323
  interruptSignal: interruptController.signal,
@@ -3791,6 +4351,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3791
4351
  agentContract: params.agentContract,
3792
4352
  acceptance: params.acceptance,
3793
4353
  acceptanceContext: { mode: "single" },
4354
+ onEffectivePrompt: foregroundControl ? (prompt) => updateLiveEffectivePrompt(foregroundControl, 0, prompt) : undefined,
3794
4355
  onDetachReady: (detach) => {
3795
4356
  detachForeground = detach;
3796
4357
  },
@@ -3839,12 +4400,14 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3839
4400
  if (r.artifactPaths) allArtifactPaths.push(r.artifactPaths);
3840
4401
 
3841
4402
  const fullOutput = getSingleResultOutput(r);
4403
+ const preserveRejectedSavedOutput = r.acceptance?.explicit && r.acceptance.status === "rejected" && r.savedOutputPath !== undefined;
3842
4404
  const finalizedOutput = finalizeSingleOutput(omitUndefinedProperties({
3843
4405
  fullOutput,
3844
4406
  truncatedOutput: r.truncation?.text,
3845
4407
  outputPath,
3846
4408
  outputMode: r.outputMode,
3847
4409
  exitCode: r.exitCode,
4410
+ preserveSavedOutput: preserveRejectedSavedOutput,
3848
4411
  savedPath: r.savedOutputPath,
3849
4412
  outputReference: r.outputReference,
3850
4413
  saveError: r.outputSaveError,
@@ -3935,6 +4498,64 @@ function duplicateSubagentCallResult(params: SubagentParamsLike): AgentToolResul
3935
4498
  };
3936
4499
  }
3937
4500
 
4501
+ const workflowLaunchObservers = new WeakMap<object, (launch: { agent: string; sessionFile?: string; async: boolean; runId?: string }) => void>();
4502
+
4503
+ function recordMissionWorkflowChild(
4504
+ binding: MissionLaunchBinding | undefined,
4505
+ workflowRunId: string,
4506
+ key: string,
4507
+ update: Omit<MissionWorkflowChildUpdate, "workflowRunId" | "key">,
4508
+ ): void {
4509
+ if (!binding) return;
4510
+ const { task: _task, ...durableUpdate } = update;
4511
+ try {
4512
+ updateMission(binding.location, binding.missionId, { upsertWorkflowChildren: [{ workflowRunId, key, ...durableUpdate }] });
4513
+ } catch (error) {
4514
+ console.warn(`[pi-subagents] Failed to record mission workflow child '${key}': ${error instanceof Error ? error.message : String(error)}`);
4515
+ }
4516
+ }
4517
+
4518
+ export function missionWorkflowChildStatus(result: AgentToolResult<Details>): string {
4519
+ const childResults = result.details.results;
4520
+ if (childResults.some((child) => child.detached || child.interrupted)) return "paused";
4521
+ if (result.isError === true || childResults.some((child) => child.exitCode !== 0)) return "failed";
4522
+ if (childResults.length === 0 && (result.details.asyncId || result.details.asyncDir)) return "running";
4523
+ return "completed";
4524
+ }
4525
+
4526
+ export async function runMissionWorkflowChild(
4527
+ binding: MissionLaunchBinding | undefined,
4528
+ workflowRunId: string,
4529
+ key: string,
4530
+ phase: string | undefined,
4531
+ run: () => Promise<AgentToolResult<Details>>,
4532
+ ): Promise<AgentToolResult<Details>> {
4533
+ try {
4534
+ return await run();
4535
+ } catch (error) {
4536
+ recordMissionWorkflowChild(binding, workflowRunId, key, {
4537
+ status: "failed",
4538
+ completedAt: new Date().toISOString(),
4539
+ heartbeat: { status: "failed", ...(phase ? { phase } : {}), message: error instanceof Error ? error.message : String(error) },
4540
+ });
4541
+ throw error;
4542
+ }
4543
+ }
4544
+
4545
+ export function bindMissionWorkflowChildAsyncLaunch(
4546
+ params: SubagentParamsLike,
4547
+ binding: MissionLaunchBinding | undefined,
4548
+ asyncByDefault: boolean,
4549
+ asyncId: string = randomUUID(),
4550
+ ): SubagentParamsLike {
4551
+ const requestedAsync = params.async ?? asyncByDefault;
4552
+ if (!binding || !requestedAsync || params.clarify === true) return params;
4553
+ const id = asyncId.trim();
4554
+ if (!id || path.basename(id) !== id) throw new Error("workflow child async id must be a single path segment");
4555
+ writeMissionAsyncBinding(path.join(DIRS.async, id), binding);
4556
+ return { ...params, workflowChildAsyncId: id };
4557
+ }
4558
+
3938
4559
  function workflowChildResult(key: string, result: AgentToolResult<Details>): WorkflowScriptChildResult {
3939
4560
  const receiptOutput = result.content.map((part) => part.type === "text" ? part.text : "").filter(Boolean).join("\n");
3940
4561
  const output = result.details.results.length === 1 && result.details.results[0]?.finalOutput !== undefined
@@ -3951,9 +4572,11 @@ function workflowChildResult(key: string, result: AgentToolResult<Details>): Wor
3951
4572
  if (child.sessionFile) artifactPaths.add(child.sessionFile);
3952
4573
  }
3953
4574
  const structured = result.details.results.map((child) => child.structuredOutput).filter((value) => value !== undefined);
4575
+ const resolvedAgents = [...new Set(result.details.results.map((child) => child.agent).filter((agent): agent is string => Boolean(agent)))];
3954
4576
  return {
3955
4577
  key,
3956
4578
  ok,
4579
+ ...(resolvedAgents.length === 1 ? { agent: resolvedAgents[0] } : {}),
3957
4580
  ...(result.details.runId || result.details.asyncId ? { runId: result.details.runId ?? result.details.asyncId } : {}),
3958
4581
  output,
3959
4582
  ...(!ok ? { error: receiptOutput || output || "Child run failed." } : {}),
@@ -3968,7 +4591,7 @@ export function prepareWorkflowLaunchParams(
3968
4591
  childParams: Record<string, unknown>,
3969
4592
  parentWorkflowRunId: string,
3970
4593
  workflowKey: string,
3971
- options: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean } = {},
4594
+ options: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor } = {},
3972
4595
  ): SubagentParamsLike {
3973
4596
  if (typeof childParams.resume === "string") {
3974
4597
  if (childParams.gate !== undefined || workflowDefaults.gate !== undefined) {
@@ -3977,24 +4600,29 @@ export function prepareWorkflowLaunchParams(
3977
4600
  const timeoutMs = childParams.timeoutMs ?? childParams.maxRuntimeMs ?? workflowDefaults.timeoutMs ?? workflowDefaults.maxRuntimeMs;
3978
4601
  const turnBudget = childParams.turnBudget ?? workflowDefaults.turnBudget;
3979
4602
  const toolBudget = childParams.toolBudget ?? workflowDefaults.toolBudget;
4603
+ const intercomBridge = childParams.intercomBridge ?? workflowDefaults.intercomBridge;
3980
4604
  return {
3981
4605
  action: "resume",
3982
4606
  id: childParams.resume.trim(),
3983
4607
  message: typeof childParams.task === "string" ? childParams.task.trim() : "",
3984
4608
  workflowParentRunId: parentWorkflowRunId,
3985
4609
  workflowKey,
4610
+ ...(options.runFanoutBudget ? { runFanoutBudget: { ...options.runFanoutBudget, parentPath: `${options.runFanoutBudget.parentPath ? `${options.runFanoutBudget.parentPath}/` : ""}workflow[${workflowKey}]` } } : {}),
3986
4611
  ...(options.missionDetached ? { mission: false } : {}),
3987
4612
  ...(timeoutMs !== undefined ? { timeoutMs: timeoutMs as number } : {}),
3988
4613
  ...(turnBudget !== undefined ? { turnBudget: turnBudget as TurnBudgetConfig } : {}),
3989
4614
  ...(toolBudget !== undefined ? { toolBudget: toolBudget as ToolBudgetConfig } : {}),
4615
+ ...(intercomBridge !== undefined ? { intercomBridge: intercomBridge as IntercomBridgeConfig } : {}),
3990
4616
  };
3991
4617
  }
3992
4618
  const launchParams = {
3993
4619
  ...workflowDefaults,
4620
+ async: false,
3994
4621
  ...childParams,
3995
4622
  ...(options.missionDetached ? { mission: false } : {}),
3996
4623
  workflowParentRunId: parentWorkflowRunId,
3997
4624
  workflowKey,
4625
+ ...(options.runFanoutBudget ? { runFanoutBudget: { ...options.runFanoutBudget, parentPath: `${options.runFanoutBudget.parentPath ? `${options.runFanoutBudget.parentPath}/` : ""}workflow[${workflowKey}]` } } : {}),
3998
4626
  ...(options.suppressRoutineResultIntercom ? { suppressRoutineResultIntercom: true } : {}),
3999
4627
  } as SubagentParamsLike;
4000
4628
  const normalizedGate = normalizeGateParams(launchParams);
@@ -4142,6 +4770,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4142
4770
  } {
4143
4771
  const delegatedThinkingOverrides = new WeakMap<object, AgentConfig["thinking"]>();
4144
4772
  const delegatedZeroToolBudgets = new WeakSet<object>();
4773
+ const delegatedExecutions = new WeakSet<object>();
4145
4774
  const warnedArtifactPackageDirs = new Set<string>();
4146
4775
  const scheduledOwnerExecutors = new Map<string, ReturnType<typeof createSubagentExecutor>>();
4147
4776
  const execute = async (
@@ -4152,8 +4781,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4152
4781
  ctx: ExtensionContext,
4153
4782
  preserveActiveSession = false,
4154
4783
  ): Promise<AgentToolResult<Details>> => {
4784
+ const workflowLaunchObserver = workflowLaunchObservers.get(params);
4155
4785
  const delegatedThinkingOverride = delegatedThinkingOverrides.get(params);
4156
4786
  const allowZeroToolBudget = delegatedZeroToolBudgets.has(params);
4787
+ const delegatedExecution = delegatedExecutions.has(params);
4157
4788
  if (!preserveActiveSession) deps.state.baseCwd = ctx.cwd;
4158
4789
  deps.state.foregroundRuns ??= new Map();
4159
4790
  deps.state.foregroundControls ??= new Map();
@@ -4164,21 +4795,67 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4164
4795
  const normalizedAction = typeof requestParams.action === "string" ? requestParams.action.trim() : requestParams.action;
4165
4796
  if (requestParams.workflowScript !== undefined && normalizedAction === undefined) {
4166
4797
  const parentCwd = ctx.cwd;
4167
- const timeout = requestParams.timeoutMs ?? requestParams.maxRuntimeMs ?? (requestParams.async === false ? DEFAULT_FOREGROUND_TIMEOUT_MS : undefined);
4798
+ const timeout = requestParams.timeoutMs ?? requestParams.maxRuntimeMs ?? (requestParams.async === false ? resolveConfigDefaultTimeoutMs(deps.config.timeoutMs) ?? DEFAULT_FOREGROUND_TIMEOUT_MS : undefined);
4168
4799
  const workflowUsageBudget = validateUsageBudgetConfig(requestParams.usageBudget ?? deps.config.usageBudget, requestParams.usageBudget ? "usageBudget" : "config.usageBudget");
4169
4800
  if (workflowUsageBudget.error) return buildRequestedModeError(requestParams, workflowUsageBudget.error);
4170
4801
  const workflowCwd = resolveRequestedCwd(parentCwd, requestParams.cwd);
4802
+ const workflowArtifactConfig: ArtifactConfig = omitUndefinedProperties({
4803
+ ...DEFAULT_ARTIFACT_CONFIG,
4804
+ enabled: requestParams.artifacts !== false,
4805
+ dir: deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir,
4806
+ });
4807
+ const workflowArtifactsDir = getArtifactsDir(ctx.sessionManager.getSessionFile() ?? null, workflowCwd, workflowArtifactConfig.dir);
4808
+ if (workflowArtifactConfig.dir === "project" && !warnedArtifactPackageDirs.has(workflowCwd)) {
4809
+ warnedArtifactPackageDirs.add(workflowCwd);
4810
+ const warning = getProjectArtifactPackagingWarning(workflowCwd);
4811
+ if (warning) console.warn(`[pi-subagents] ${warning}`);
4812
+ }
4813
+ const workflowPrompts = { render: (ref: string, vars?: unknown) => renderWorkflowPrompt(ref, vars, workflowCwd) };
4171
4814
  const chatProgressResult = resolveWorkflowChatProgress({ requested: requestParams.chatProgress, parentCwd, workflowCwd, background: requestParams.async !== false });
4172
4815
  if (chatProgressResult.error) return { content: [{ type: "text", text: chatProgressResult.error }], isError: true, details: { mode: "workflow", results: [] } };
4173
4816
  const chatProgress = chatProgressResult.projection!;
4174
4817
  const explicitMission = requestParams.missionId !== undefined || requestParams.mission !== undefined;
4175
4818
  const autoMission = !explicitMission;
4176
4819
  const workflowPreview = autoMission ? previewSimpleWorkflowRun(requestParams.workflowScript) : undefined;
4177
- const previewTask = workflowPreview?.task?.trim() || undefined;
4178
4820
  const previewAgent = workflowPreview?.agent?.trim() || undefined;
4179
4821
  const scriptFirstLine = requestParams.workflowScript.split(/\r?\n/).map((line) => line.trim()).find(Boolean) || "Workflow";
4180
4822
  const boundedScriptPreview = scriptFirstLine.length > 100 ? `${scriptFirstLine.slice(0, 97)}...` : scriptFirstLine;
4181
- const derivedObjective = previewTask || (previewAgent ? `Workflow: ${previewAgent}` : boundedScriptPreview);
4823
+ const derivedObjective = previewAgent ? `Workflow: ${previewAgent}` : boundedScriptPreview;
4824
+ const workflowDepth = checkSubagentDepth(deps.config.maxSubagentDepth).depth;
4825
+ const asyncWorkflow = requestParams.async !== false;
4826
+ const topLevelAsyncWorkflow = asyncWorkflow
4827
+ && workflowDepth === 0
4828
+ && !resolveInheritedNestedRouteFromEnv()
4829
+ && !requestParams.workflowParentRunId;
4830
+ const workflowRunId = asyncWorkflow ? randomUUID() : undefined;
4831
+ let workflowCapacity: ActiveAsyncCapacityHandle | undefined;
4832
+ if (workflowRunId && topLevelAsyncWorkflow) {
4833
+ const currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
4834
+ try {
4835
+ workflowCapacity = acquireActiveAsyncCapacity({
4836
+ sessionId: currentSessionId,
4837
+ limit: resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession),
4838
+ runId: workflowRunId,
4839
+ kind: "workflow",
4840
+ asyncDir: path.join(DIRS.async, workflowRunId),
4841
+ }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) });
4842
+ } catch (error) {
4843
+ if (error instanceof ActiveAsyncCapacityError) {
4844
+ deps.state.activeAsyncCapacity = error.snapshot;
4845
+ return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "workflow", results: [], activeAsyncCapacity: error.snapshot } };
4846
+ }
4847
+ throw error;
4848
+ }
4849
+ }
4850
+ let workflowFanoutBudget: RunFanoutBudgetDescriptor;
4851
+ try {
4852
+ workflowFanoutBudget = requestParams.runFanoutBudget
4853
+ ?? decodeRunFanoutBudgetDescriptor(process.env[RUN_FANOUT_BUDGET_ENV])
4854
+ ?? createRunFanoutBudget(_id, resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun));
4855
+ } catch (error) {
4856
+ workflowCapacity?.rollback();
4857
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "workflow", results: [] } };
4858
+ }
4182
4859
  let missionBinding: MissionLaunchBinding | undefined;
4183
4860
  let missionWarning: string | undefined;
4184
4861
  try {
@@ -4189,22 +4866,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4189
4866
  ownerSessionId: resolveCurrentSessionId(ctx.sessionManager),
4190
4867
  });
4191
4868
  } catch (error) {
4192
- if (explicitMission) return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "workflow", results: [] } };
4869
+ if (explicitMission) {
4870
+ workflowCapacity?.rollback();
4871
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "workflow", results: [] } };
4872
+ }
4193
4873
  missionWarning = `Mission tracking unavailable: ${error instanceof Error ? error.message : String(error)}`;
4194
4874
  }
4195
- let shouldPatchMissionObjective = autoMission && previewTask === undefined && missionBinding !== undefined;
4196
- const patchMissionObjective = (task: unknown): void => {
4197
- if (!shouldPatchMissionObjective || !missionBinding || typeof task !== "string" || !task.trim()) return;
4198
- shouldPatchMissionObjective = false;
4199
- const objective = task.trim();
4200
- const firstLine = objective.split(/\r?\n/, 1)[0]?.trim() || objective;
4201
- const title = firstLine.length > 100 ? `${firstLine.slice(0, 97)}...` : firstLine;
4202
- try {
4203
- updateMission(missionBinding.location, missionBinding.missionId, { title, objective });
4204
- } catch (error) {
4205
- console.warn(`[pi-subagents] Failed to update automatic mission objective: ${error instanceof Error ? error.message : String(error)}`);
4206
- }
4207
- };
4208
4875
  const detachWorkflowChildMissions = autoMission || missionBinding !== undefined || requestParams.mission === false;
4209
4876
  const workflowState = missionBinding ? createMissionWorkflowState(missionBinding.location, missionBinding.missionId) : undefined;
4210
4877
  const attachWorkflowMission = (result: AgentToolResult<Details>): AgentToolResult<Details> => {
@@ -4218,20 +4885,27 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4218
4885
  : { ...result, details: { ...result.details, missionWarning: warning } };
4219
4886
  }
4220
4887
  };
4221
- if (requestParams.async !== false) {
4888
+ if (workflowRunId) {
4222
4889
  const toolCallId = _id;
4223
- const workflowRunId = randomUUID();
4224
4890
  const asyncDir = path.join(DIRS.async, workflowRunId);
4225
4891
  const resultPath = path.join(DIRS.results, `${workflowRunId}.json`);
4226
4892
  const statusPath = path.join(asyncDir, "status.json");
4227
4893
  const eventsPath = path.join(asyncDir, "events.jsonl");
4228
4894
  const startedAt = Date.now();
4229
4895
  const currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
4230
- fs.mkdirSync(asyncDir, { recursive: true });
4231
- fs.mkdirSync(DIRS.results, { recursive: true });
4896
+ try {
4897
+ fs.mkdirSync(asyncDir, { recursive: true });
4898
+ writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
4899
+ fs.mkdirSync(DIRS.results, { recursive: true });
4900
+ } catch (error) {
4901
+ workflowCapacity?.rollback();
4902
+ return { content: [{ type: "text", text: `Failed to create async workflow storage: ${error instanceof Error ? error.message : String(error)}` }], isError: true, details: { mode: "workflow", results: [] } };
4903
+ }
4232
4904
  const controller = new AbortController();
4233
4905
  deps.state.workflowControllers ??= new Map();
4234
4906
  deps.state.workflowControllers.set(workflowRunId, controller);
4907
+ workflowCapacity?.markWorkflowStarted();
4908
+ if (workflowCapacity) deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers.keys()) });
4235
4909
  let status: AsyncStatus = {
4236
4910
  runId: workflowRunId,
4237
4911
  toolCallId,
@@ -4245,11 +4919,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4245
4919
  pid: process.pid,
4246
4920
  steps: [],
4247
4921
  workflow: { trace: [], emits: [], console: [] },
4922
+ runFanoutBudget: getRunFanoutBudgetSnapshot(workflowFanoutBudget),
4248
4923
  };
4249
4924
  const appendWorkflowEvent = (event: Record<string, unknown>) => fs.appendFileSync(eventsPath, `${JSON.stringify({ ts: Date.now(), runId: workflowRunId, ...event })}\n`, "utf-8");
4925
+ let indexedState: AsyncStatus["state"] | undefined;
4250
4926
  const persist = () => {
4251
4927
  status.lastUpdate = Date.now();
4252
4928
  writeAtomicJson(statusPath, status);
4929
+ if (indexedState !== status.state) {
4930
+ updateActiveRunIndex(asyncDir, status.state);
4931
+ indexedState = status.state;
4932
+ }
4253
4933
  const job = deps.state.asyncJobs.get(workflowRunId);
4254
4934
  if (job) {
4255
4935
  job.status = status.state;
@@ -4273,7 +4953,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4273
4953
  }
4274
4954
  };
4275
4955
  const projectWorkflowActivity = () => {
4276
- const runningSteps = (status.steps ?? []).filter((step) => step.status === "running");
4956
+ const steps = status.steps ?? [];
4957
+ const runningSteps = steps.filter((step) => step.status === "running");
4277
4958
  const lastActivityAt = runningSteps.reduce<number | undefined>((latest, step) => step.lastActivityAt === undefined ? latest : Math.max(latest ?? step.lastActivityAt, step.lastActivityAt), undefined);
4278
4959
  const activeToolStep = runningSteps
4279
4960
  .filter((step) => step.currentTool)
@@ -4286,11 +4967,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4286
4967
  status.currentTool = activeToolStep?.currentTool;
4287
4968
  status.currentToolStartedAt = activeToolStep?.currentToolStartedAt;
4288
4969
  status.currentPath = activeToolStep?.currentPath;
4289
- const turnCounts = (status.steps ?? []).flatMap((step) => step.turnCount === undefined ? [] : [step.turnCount]);
4290
- const toolCounts = (status.steps ?? []).flatMap((step) => step.toolCount === undefined ? [] : [step.toolCount]);
4970
+ const turnCounts = steps.flatMap((step) => step.turnCount === undefined ? [] : [step.turnCount]);
4971
+ const toolCounts = steps.flatMap((step) => step.toolCount === undefined ? [] : [step.toolCount]);
4291
4972
  status.turnCount = turnCounts.length > 0 ? turnCounts.reduce((total, count) => total + count, 0) : undefined;
4292
4973
  status.toolCount = toolCounts.length > 0 ? toolCounts.reduce((total, count) => total + count, 0) : undefined;
4293
- status.currentStep = runningSteps.length === 1 ? status.steps?.indexOf(runningSteps[0]!) : undefined;
4974
+ status.currentStep = runningSteps.length === 1 ? steps.indexOf(runningSteps[0]!) : undefined;
4294
4975
  };
4295
4976
  const workflowJob: AsyncJobState = { asyncId: workflowRunId, asyncDir, cwd: workflowCwd, status: "running", sessionId: currentSessionId ?? undefined, mode: "workflow", agents: [], steps: [], startedAt, updatedAt: startedAt, ...(timeout !== undefined ? { timeoutMs: timeout, deadlineAt: startedAt + timeout } : {}), workflow: status.workflow };
4296
4977
  deps.state.asyncJobs.set(workflowRunId, workflowJob);
@@ -4302,22 +4983,65 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4302
4983
  void Promise.resolve().then(async () => {
4303
4984
  const workflowResults: SingleResult[] = [];
4304
4985
  const { action: _action, agent: _agent, task: _task, resume: _resume, tasks: _tasks, chain: _chain, concurrency: _concurrency, foregroundOnly: _foregroundOnly, clarify: _clarify, timeoutMs: _timeoutMs, maxRuntimeMs: _maxRuntimeMs, usageBudget: _usageBudget, missionId: _missionId, mission: _mission, ...workflowChildDefaults } = workflowRequest;
4986
+ const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
4987
+ const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
4988
+ const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId), configuredOutputBaseDir);
4989
+ const claimedOutputPaths = new Map<string, string>();
4990
+ const workflowSteps = new Map<string, NonNullable<AsyncStatus["steps"]>[number]>();
4991
+ let projectedTraceLength = 0;
4992
+ let projectedTraceTail: NonNullable<Details["workflow"]>["trace"][number] | undefined;
4305
4993
  const updateTrace = (trace: NonNullable<Details["workflow"]>["trace"]) => {
4306
4994
  status.workflow = { ...(status.workflow ?? { emits: [], console: [] }), trace };
4307
- for (const entry of trace.filter((candidate) => candidate.operation === "run")) {
4308
- const existing = status.steps?.find((step) => step.workflowKey === entry.key);
4995
+ const rebuild = trace.length < projectedTraceLength
4996
+ || (projectedTraceLength > 0 && trace[projectedTraceLength - 1] !== projectedTraceTail);
4997
+ if (rebuild) {
4998
+ workflowSteps.clear();
4999
+ for (const step of status.steps ?? []) {
5000
+ if (step.workflowKey) workflowSteps.set(step.workflowKey, step);
5001
+ }
5002
+ projectedTraceLength = 0;
5003
+ }
5004
+ for (let index = projectedTraceLength; index < trace.length; index += 1) {
5005
+ const entry = trace[index]!;
5006
+ if (entry.operation !== "run") continue;
5007
+ const existing = workflowSteps.get(entry.key);
4309
5008
  if (entry.state === "reused" && existing) continue;
4310
- const mapped = entry.state === "started" || entry.state === "reused" ? "running" : entry.state === "completed" ? "completed" : "failed";
5009
+ const mapped = entry.state === "started" || entry.state === "reused"
5010
+ ? "running"
5011
+ : entry.state === "completed"
5012
+ ? "completed"
5013
+ : entry.state === "stopped"
5014
+ ? "stopped"
5015
+ : "failed";
4311
5016
  if (existing) {
4312
5017
  existing.status = mapped;
5018
+ if (entry.agent) existing.agent = entry.agent;
5019
+ if (entry.runId) existing.runId = entry.runId;
5020
+ if (entry.state === "failed" && !entry.runId && existing.async === undefined) existing.async = false;
5021
+ if (entry.state === "stopped") existing.stopped = true;
5022
+ else delete existing.stopped;
4313
5023
  if (entry.error === undefined) delete existing.error;
4314
5024
  else existing.error = entry.error;
4315
5025
  if (entry.durationMs === undefined) delete existing.durationMs;
4316
5026
  else existing.durationMs = entry.durationMs;
4317
5027
  } else {
4318
- status.steps?.push({ agent: entry.key, label: entry.key, workflowKey: entry.key, parentWorkflowRunId: workflowRunId, status: mapped, startedAt: Date.now() });
5028
+ const step: NonNullable<AsyncStatus["steps"]>[number] = {
5029
+ agent: entry.agent ?? entry.key,
5030
+ label: entry.key,
5031
+ workflowKey: entry.key,
5032
+ parentWorkflowRunId: workflowRunId,
5033
+ status: mapped,
5034
+ startedAt: Date.now(),
5035
+ ...(entry.runId ? { runId: entry.runId } : {}),
5036
+ ...(entry.state === "failed" && !entry.runId ? { async: false } : {}),
5037
+ ...(entry.state === "stopped" ? { stopped: true } : {}),
5038
+ };
5039
+ status.steps?.push(step);
5040
+ workflowSteps.set(entry.key, step);
4319
5041
  }
4320
5042
  }
5043
+ projectedTraceLength = trace.length;
5044
+ projectedTraceTail = trace.at(-1);
4321
5045
  projectWorkflowActivity();
4322
5046
  persist();
4323
5047
  appendWorkflowEvent({ type: "subagent.workflow.trace", trace });
@@ -4327,43 +5051,96 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4327
5051
  script: workflowScript,
4328
5052
  timeoutMs: timeout,
4329
5053
  signal: controller.signal,
5054
+ prompts: workflowPrompts,
4330
5055
  ...(workflowState ? { state: workflowState } : {}),
4331
5056
  onTrace: updateTrace,
5057
+ admit: (calls) => {
5058
+ const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, claimedOutputPaths, entries: calls });
5059
+ if (outputClaims.error) throw new Error(outputClaims.error);
5060
+ status.runFanoutBudget = claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
5061
+ if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
5062
+ persist();
5063
+ },
4332
5064
  onEmit: (emits) => {
4333
5065
  // Each emit is validated at the host boundary in runWorkflowScript before onEmit fires.
4334
5066
  status.workflow = { ...(status.workflow ?? { trace: [], console: [] }), emits };
4335
5067
  persist();
4336
5068
  appendWorkflowEvent({ type: "subagent.workflow.emit", value: emits.at(-1) });
4337
5069
  },
4338
- launch: async (key, childParams, workflowSignal) => {
5070
+ launch: async (key, childParams, workflowSignal, admission) => {
4339
5071
  if (workflowUsageBudget.budget && childParams.async === true) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, "workflow usageBudget does not support async runs.run launches."));
4340
5072
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
4341
5073
  if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)));
4342
- patchMissionObjective(childParams.task);
4343
- const childRequest = prepareWorkflowLaunchParams(workflowChildDefaults, childParams, workflowRunId, key, { missionDetached: detachWorkflowChildMissions });
4344
- const result = await execute(randomUUID(), childRequest, workflowSignal, (update) => {
4345
- const progress = update.details.progress?.[0];
4346
- const step = status.steps?.find((candidate) => candidate.workflowKey === key);
4347
- if (!progress || !step) return;
4348
- step.status = progress.status === "completed" ? "completed" : progress.status === "failed" ? "failed" : "running";
4349
- step.activityState = progress.activityState;
4350
- step.lastActivityAt = progress.lastActivityAt;
4351
- step.currentTool = progress.currentTool;
4352
- step.currentToolArgs = progress.currentToolArgs;
4353
- step.currentToolStartedAt = progress.currentToolStartedAt;
4354
- step.currentPath = progress.currentPath;
4355
- step.recentTools = progress.recentTools.map((tool) => ({ ...tool }));
4356
- step.recentOutput = [...progress.recentOutput];
4357
- step.turnCount = progress.turnCount;
4358
- step.toolCount = progress.toolCount;
4359
- step.model = progress.model;
4360
- step.thinking = progress.thinking;
4361
- step.error = progress.error;
4362
- projectWorkflowActivity();
4363
- persist();
4364
- }, ctx, preserveActiveSession);
5074
+ const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
5075
+ const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
5076
+ recordMissionWorkflowChild(missionBinding, workflowRunId, key, {
5077
+ status: "running",
5078
+ ...(typeof childParams.agent === "string" && childParams.agent.trim() ? { agent: childParams.agent.trim() } : {}),
5079
+ ...(childLabel ? { label: childLabel } : {}),
5080
+ ...(childPhase ? { phase: childPhase } : {}),
5081
+ heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
5082
+ });
5083
+ const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, () => {
5084
+ const childRequest = bindMissionWorkflowChildAsyncLaunch(
5085
+ { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, options: { missionDetached: detachWorkflowChildMissions, runFanoutBudget: workflowFanoutBudget } }), runFanoutAdmitted: admission.admitted },
5086
+ missionBinding,
5087
+ deps.asyncByDefault,
5088
+ );
5089
+ workflowLaunchObservers.set(childRequest, (launch) => {
5090
+ const step = status.steps?.find((candidate) => candidate.workflowKey === key);
5091
+ if (step) {
5092
+ step.agent = launch.agent;
5093
+ step.sessionFile = launch.sessionFile;
5094
+ step.async = launch.async;
5095
+ if (launch.runId) step.runId = launch.runId;
5096
+ persist();
5097
+ }
5098
+ recordMissionWorkflowChild(missionBinding, workflowRunId, key, { status: "running", agent: launch.agent, ...(launch.sessionFile ? { sessionPath: launch.sessionFile } : {}) });
5099
+ });
5100
+ return execute(randomUUID(), childRequest, workflowSignal, (update) => {
5101
+ const progress = update.details.progress?.[0];
5102
+ const step = status.steps?.find((candidate) => candidate.workflowKey === key);
5103
+ if (!progress || !step || step.stopped) return;
5104
+ step.status = progress.status === "completed" ? "completed" : progress.status === "failed" ? "failed" : "running";
5105
+ step.activityState = progress.activityState;
5106
+ step.lastActivityAt = progress.lastActivityAt;
5107
+ step.currentTool = progress.currentTool;
5108
+ step.currentToolArgs = progress.currentToolArgs;
5109
+ step.currentToolStartedAt = progress.currentToolStartedAt;
5110
+ step.currentPath = progress.currentPath;
5111
+ step.recentTools = progress.recentTools.map((tool) => ({ ...tool }));
5112
+ step.recentOutput = [...progress.recentOutput];
5113
+ step.turnCount = progress.turnCount;
5114
+ step.toolCount = progress.toolCount;
5115
+ step.model = progress.model;
5116
+ step.thinking = progress.thinking;
5117
+ step.error = progress.error;
5118
+ projectWorkflowActivity();
5119
+ persist();
5120
+ recordMissionWorkflowChild(missionBinding, workflowRunId, key, {
5121
+ status: step.status,
5122
+ heartbeat: { status: step.status, ...(childPhase ? { phase: childPhase } : {}) },
5123
+ });
5124
+ }, ctx, preserveActiveSession);
5125
+ });
4365
5126
  workflowResults.push(...result.details.results);
4366
5127
  const child = workflowChildResult(key, result);
5128
+ const step = status.steps?.find((candidate) => candidate.workflowKey === key);
5129
+ if (step) {
5130
+ step.async = Boolean(result.details.asyncId || result.details.asyncDir);
5131
+ if (child.runId) step.runId = child.runId;
5132
+ }
5133
+ if (result.details.asyncDir && missionBinding) writeMissionAsyncBinding(result.details.asyncDir, missionBinding);
5134
+ const childStatus = missionWorkflowChildStatus(result);
5135
+ recordMissionWorkflowChild(missionBinding, workflowRunId, key, {
5136
+ status: childStatus,
5137
+ ...(child.runId ? { runId: child.runId } : {}),
5138
+ ...(result.details.results[0]?.agent ? { agent: result.details.results[0].agent } : {}),
5139
+ ...(result.details.results[0]?.sessionFile ? { sessionPath: result.details.results[0].sessionFile } : {}),
5140
+ artifactPaths: child.artifactPaths,
5141
+ ...(["completed", "failed"].includes(childStatus) ? { completedAt: new Date().toISOString() } : {}),
5142
+ heartbeat: { status: childStatus, ...(childPhase ? { phase: childPhase } : {}) },
5143
+ });
4367
5144
  if (result.details.asyncId) {
4368
5145
  const childJob = deps.state.asyncJobs.get(result.details.asyncId);
4369
5146
  if (childJob) { childJob.parentWorkflowRunId = workflowRunId; childJob.workflowKey = key; }
@@ -4375,28 +5152,38 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4375
5152
  const returnPreview = formatWorkflowValue(workflow.value).slice(0, 1_000);
4376
5153
  const emitPreview = workflow.emits.length > 0 ? ` Emitted: ${workflow.emits.map(formatWorkflowValue).join(", ").slice(0, 1_000)}` : "";
4377
5154
  const summary = `Workflow completed with ${workflow.children.length} child run(s). Return: ${returnPreview}${emitPreview} Trace: ${workflow.trace.length} event(s).`;
5155
+ const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, summary);
5156
+ const resultSummary = appendWorkflowOutputWarning(summary, outputWarning);
4378
5157
  const workflowUsage = sumResultsUsage(workflowResults);
4379
5158
  status = { ...status, state: "complete", endedAt: Date.now(), workflow: { value: workflow.value, trace: workflow.trace, emits: workflow.emits, console: workflow.console }, totalTokens: { input: workflowUsage.input, output: workflowUsage.output, total: workflowUsage.input + workflowUsage.output }, totalCost: sumResultsCost(workflowResults) };
4380
- writeAtomicJson(resultPath, { id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary, output: summary, results: workflow.children.map((child) => ({ agent: child.key, ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, asyncDir, cwd: workflowCwd, sessionId: currentSessionId, timestamp: Date.now(), durationMs: Date.now() - startedAt });
5159
+ writeAtomicJson(resultPath, { id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary: resultSummary, output: resultSummary, results: workflow.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, asyncDir, cwd: workflowCwd, sessionId: currentSessionId, timestamp: Date.now(), durationMs: Date.now() - startedAt });
4381
5160
  persist();
4382
5161
  appendWorkflowEvent({ type: "subagent.workflow.completed", state: "complete" });
4383
5162
  } catch (error) {
4384
5163
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
4385
5164
  const stopped = controller.signal.aborted;
4386
5165
  status = compactOptional<AsyncStatus>({ ...status, state: stopped ? "stopped" : "failed", stopped: stopped || undefined, error: error instanceof Error ? error.message : String(error), endedAt: Date.now(), workflow: { trace: partial.trace, emits: partial.emits, console: partial.console } });
4387
- writeAtomicJson(resultPath, { id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: false, state: status.state, summary: status.error, error: status.error, stopped: status.stopped, results: partial.children.map((child) => ({ agent: child.key, ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, asyncDir, cwd: workflowCwd, sessionId: currentSessionId, timestamp: Date.now(), durationMs: Date.now() - startedAt });
5166
+ const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, status.error ?? "Workflow failed.");
5167
+ const resultSummary = appendWorkflowOutputWarning(status.error ?? "Workflow failed.", outputWarning);
5168
+ writeAtomicJson(resultPath, { id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: false, state: status.state, summary: resultSummary, error: status.error, stopped: status.stopped, results: partial.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, asyncDir, cwd: workflowCwd, sessionId: currentSessionId, timestamp: Date.now(), durationMs: Date.now() - startedAt });
4388
5169
  persist();
4389
5170
  appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, error: status.error });
4390
5171
  } finally {
4391
5172
  deps.state.workflowControllers?.delete(workflowRunId);
5173
+ deps.state.activeAsyncCapacity = workflowCapacity?.reconcile(new Set(deps.state.workflowControllers?.keys() ?? []))
5174
+ ?? deps.state.activeAsyncCapacity;
4392
5175
  }
4393
5176
  });
4394
- return attachWorkflowMission({
5177
+ return attachWorkflowMission(withRunFanoutBudget({
4395
5178
  content: [{ type: "text", text: formatAsyncStartedMessage(`Async workflow [${workflowRunId}]`, ctx.hasUI === true) }],
4396
- details: { mode: "workflow", runId: workflowRunId, toolCallId, asyncId: workflowRunId, asyncDir, results: [], chatProgress },
4397
- });
5179
+ details: { mode: "workflow", runId: workflowRunId, toolCallId, asyncId: workflowRunId, asyncDir, results: [], chatProgress, ...(deps.state.activeAsyncCapacity ? { activeAsyncCapacity: deps.state.activeAsyncCapacity } : {}) },
5180
+ }, workflowFanoutBudget));
4398
5181
  }
4399
5182
  const { workflowScript: _workflowScript, action: _action, agent: _agent, task: _task, resume: _resume, tasks: _tasks, chain: _chain, concurrency: _concurrency, async: _async, foregroundOnly: _foregroundOnly, clarify: _clarify, timeoutMs: _timeoutMs, maxRuntimeMs: _maxRuntimeMs, usageBudget: _usageBudget, chatProgress: _chatProgress, missionId: _missionId, mission: _mission, ...workflowChildDefaults } = requestParams;
5183
+ const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
5184
+ const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
5185
+ const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, _id), configuredOutputBaseDir);
5186
+ const claimedOutputPaths = new Map<string, string>();
4400
5187
  const workflowResults: SingleResult[] = [];
4401
5188
  let liveWorkflow: NonNullable<Details["workflow"]> = { trace: [], emits: [], console: [] };
4402
5189
  const sendWorkflowProgress = () => {
@@ -4408,24 +5195,70 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4408
5195
  script: requestParams.workflowScript,
4409
5196
  timeoutMs: timeout,
4410
5197
  signal,
5198
+ prompts: workflowPrompts,
4411
5199
  ...(workflowState ? { state: workflowState } : {}),
4412
5200
  onTrace: (trace) => {
4413
5201
  liveWorkflow = { ...liveWorkflow, trace };
4414
5202
  sendWorkflowProgress();
4415
5203
  },
5204
+ admit: (calls) => {
5205
+ const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId: _id, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, claimedOutputPaths, entries: calls });
5206
+ if (outputClaims.error) throw new Error(outputClaims.error);
5207
+ claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
5208
+ if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
5209
+ },
4416
5210
  onEmit: (emits) => {
4417
5211
  liveWorkflow = { ...liveWorkflow, emits };
4418
5212
  sendWorkflowProgress();
4419
5213
  },
4420
- launch: async (key, childParams, workflowSignal) => {
5214
+ launch: async (key, childParams, workflowSignal, admission) => {
4421
5215
  if (workflowUsageBudget.budget && childParams.async === true) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, "workflow usageBudget does not support async runs.run launches."));
4422
5216
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
4423
5217
  if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)));
4424
- patchMissionObjective(childParams.task);
4425
- const childRequest = prepareWorkflowLaunchParams(workflowChildDefaults, childParams, _id, key, { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card" });
4426
- const result = await execute(randomUUID(), childRequest, workflowSignal, undefined, ctx, preserveActiveSession);
5218
+ const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
5219
+ const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
5220
+ recordMissionWorkflowChild(missionBinding, _id, key, {
5221
+ status: "running",
5222
+ ...(typeof childParams.agent === "string" && childParams.agent.trim() ? { agent: childParams.agent.trim() } : {}),
5223
+ ...(childLabel ? { label: childLabel } : {}),
5224
+ ...(childPhase ? { phase: childPhase } : {}),
5225
+ heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
5226
+ });
5227
+ const result = await runMissionWorkflowChild(missionBinding, _id, key, childPhase, () => {
5228
+ const childRequest = bindMissionWorkflowChildAsyncLaunch(
5229
+ { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: _id, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget } }), runFanoutAdmitted: admission.admitted },
5230
+ missionBinding,
5231
+ deps.asyncByDefault,
5232
+ );
5233
+ workflowLaunchObservers.set(childRequest, (launch) => recordMissionWorkflowChild(missionBinding, _id, key, {
5234
+ status: "running",
5235
+ agent: launch.agent,
5236
+ ...(launch.sessionFile ? { sessionPath: launch.sessionFile } : {}),
5237
+ }));
5238
+ return execute(randomUUID(), childRequest, workflowSignal, (update) => {
5239
+ const progress = update.details.progress?.[0];
5240
+ if (!progress) return;
5241
+ const progressStatus = progress.status === "completed" ? "completed" : progress.status === "failed" ? "failed" : "running";
5242
+ recordMissionWorkflowChild(missionBinding, _id, key, {
5243
+ status: progressStatus,
5244
+ heartbeat: { status: progressStatus, ...(childPhase ? { phase: childPhase } : {}) },
5245
+ });
5246
+ }, ctx, preserveActiveSession);
5247
+ });
4427
5248
  workflowResults.push(...result.details.results);
4428
- return workflowChildResult(key, result);
5249
+ if (result.details.asyncDir && missionBinding) writeMissionAsyncBinding(result.details.asyncDir, missionBinding);
5250
+ const child = workflowChildResult(key, result);
5251
+ const childStatus = missionWorkflowChildStatus(result);
5252
+ recordMissionWorkflowChild(missionBinding, _id, key, {
5253
+ status: childStatus,
5254
+ ...(child.runId ? { runId: child.runId } : {}),
5255
+ ...(result.details.results[0]?.agent ? { agent: result.details.results[0].agent } : {}),
5256
+ ...(result.details.results[0]?.sessionFile ? { sessionPath: result.details.results[0].sessionFile } : {}),
5257
+ artifactPaths: child.artifactPaths,
5258
+ ...(["completed", "failed"].includes(childStatus) ? { completedAt: new Date().toISOString() } : {}),
5259
+ heartbeat: { status: childStatus, ...(childPhase ? { phase: childPhase } : {}) },
5260
+ });
5261
+ return child;
4429
5262
  },
4430
5263
  status: async (keyOrRunId, workflowSignal) => workflowChildResult(keyOrRunId, await execute(randomUUID(), { action: "status", id: keyOrRunId }, workflowSignal, undefined, ctx, preserveActiveSession)),
4431
5264
  });
@@ -4434,10 +5267,13 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4434
5267
  if (workflow.emits.length > 0) sections.push(`Emitted:\n${workflow.emits.map(formatWorkflowValue).join("\n")}`);
4435
5268
  if (workflow.console.length > 0) sections.push(`Console:\n${workflow.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
4436
5269
  if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
4437
- return attachWorkflowMission({
4438
- content: [{ type: "text", text: sections.join("\n\n") }],
5270
+ const workflowText = sections.join("\n\n");
5271
+ const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText);
5272
+ const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
5273
+ return attachWorkflowMission(withRunFanoutBudget({
5274
+ content: [{ type: "text", text: displayText }],
4439
5275
  details: compactOptional<Details>({ mode: "workflow", runId: _id, results: workflow.children.flatMap((child) => (child.results ?? []) as SingleResult[]), totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { value: workflow.value, trace: workflow.trace, emits: workflow.emits, console: workflow.console }, chatProgress }),
4440
- });
5276
+ }, workflowFanoutBudget));
4441
5277
  } catch (error) {
4442
5278
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
4443
5279
  const text = error instanceof Error ? error.message : String(error);
@@ -4446,11 +5282,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4446
5282
  if (partial.emits.length > 0) sections.push(`Emitted:\n${partial.emits.map(formatWorkflowValue).join("\n")}`);
4447
5283
  if (partial.console.length > 0) sections.push(`Console:\n${partial.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
4448
5284
  if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
4449
- return attachWorkflowMission({
4450
- content: [{ type: "text", text: sections.join("\n\n") }],
5285
+ const workflowText = sections.join("\n\n");
5286
+ const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText);
5287
+ const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
5288
+ return attachWorkflowMission(withRunFanoutBudget({
5289
+ content: [{ type: "text", text: displayText }],
4451
5290
  isError: true,
4452
5291
  details: compactOptional<Details>({ mode: "workflow", runId: _id, results: partial.children.flatMap((child) => (child.results ?? []) as SingleResult[]), totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { trace: partial.trace, emits: partial.emits, console: partial.console }, chatProgress }),
4453
- });
5292
+ }, workflowFanoutBudget));
4454
5293
  }
4455
5294
  }
4456
5295
  const directParams = prepareWorkflowChildParams(requestParams);
@@ -4467,7 +5306,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4467
5306
  ? normalizeParentModel(ctx.model)
4468
5307
  : rememberParentModel(deps.state, requestSessionId, ctx.model);
4469
5308
  } catch (error) {
4470
- if (action?.toLowerCase() !== "doctor") throw error;
5309
+ if (action?.toLowerCase() !== "doctor" && action?.toLowerCase() !== "guide") throw error;
4471
5310
  requestParentModel = normalizeParentModel(ctx.model);
4472
5311
  }
4473
5312
  if (action) {
@@ -4649,6 +5488,20 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4649
5488
  details: { mode: "management", results: [], spawnBudget: granted.snapshot },
4650
5489
  };
4651
5490
  }
5491
+ if (action === "guide") {
5492
+ try {
5493
+ return {
5494
+ content: [{ type: "text", text: readSubagentGuide(paramsWithResolvedCwd.topic) }],
5495
+ details: { mode: "management", results: [] },
5496
+ };
5497
+ } catch (error) {
5498
+ return {
5499
+ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
5500
+ isError: true,
5501
+ details: { mode: "management", results: [] },
5502
+ };
5503
+ }
5504
+ }
4652
5505
  if (action === "children.list") {
4653
5506
  deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
4654
5507
  const children = listRetainedChildren(DIRS.async, deps.state.currentSessionId);
@@ -4674,6 +5527,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4674
5527
  if (!sessionError) sessionError = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
4675
5528
  }
4676
5529
  const spawnBudget = getSpawnBudgetSnapshot(deps.state, deps.config, currentSessionId);
5530
+ const activeAsyncCapacity = currentSessionId
5531
+ ? getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) })
5532
+ : { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession) ?? 0 };
5533
+ deps.state.activeAsyncCapacity = activeAsyncCapacity;
4677
5534
  return {
4678
5535
  content: [{
4679
5536
  type: "text",
@@ -4690,14 +5547,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4690
5547
  expandTilde: deps.expandTilde,
4691
5548
  })),
4692
5549
  }],
4693
- details: { mode: "management", results: [], spawnBudget },
5550
+ details: { mode: "management", results: [], spawnBudget, activeAsyncCapacity },
4694
5551
  };
4695
5552
  }
4696
- if (action === "status") {
5553
+ if (action === "status" || action === "debug.run") {
4697
5554
  if (!preserveActiveSession) deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
4698
5555
  const targetRunId = paramsWithResolvedCwd.id ?? paramsWithResolvedCwd.runId;
4699
5556
  const hasDirectoryTarget = Boolean(paramsWithResolvedCwd.dir);
4700
- const targetLabel = formatStatusTargetLabel(paramsWithResolvedCwd, targetRunId);
5557
+ const targetLabel = action === "debug.run" ? "Debug run" : formatStatusTargetLabel(paramsWithResolvedCwd, targetRunId);
4701
5558
  const withBudget = (result: AgentToolResult<Details>) => {
4702
5559
  const budgeted = withSpawnBudgetStatus(result, deps.state, deps.config, deps.state.currentSessionId);
4703
5560
  return {
@@ -4709,6 +5566,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4709
5566
  };
4710
5567
  const nestedScope = nestedResolutionScopeForExecutor(deps);
4711
5568
  const sessionRoots = trustedSessionRootsForStatus(ctx, deps);
5569
+ if (action === "debug.run") {
5570
+ if (!targetRunId && !hasDirectoryTarget) {
5571
+ return withBudget({ content: [{ type: "text", text: "action='debug.run' requires id, runId, or dir." }], isError: true, details: { mode: "management", results: [] } });
5572
+ }
5573
+ if (paramsWithResolvedCwd.view) {
5574
+ return withBudget({ content: [{ type: "text", text: "action='debug.run' does not support status views." }], isError: true, details: { mode: "management", results: [] } });
5575
+ }
5576
+ return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots })));
5577
+ }
4712
5578
  if (paramsWithResolvedCwd.view === "fleet") {
4713
5579
  return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots })));
4714
5580
  }
@@ -4799,7 +5665,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4799
5665
  }
4800
5666
  }
4801
5667
  if (action === "resume") {
4802
- return resumeAsyncRun(omitUndefinedProperties({ params: paramsWithResolvedCwd, requestCwd, ctx, deps, parentModel: requestParentModel }));
5668
+ return resumeAsyncRun(omitUndefinedProperties({ params: paramsWithResolvedCwd, requestCwd, ctx, deps, parentModel: requestParentModel, signal }));
4803
5669
  }
4804
5670
  if (action === "steer") {
4805
5671
  deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
@@ -4810,6 +5676,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4810
5676
  try {
4811
5677
  const location = resolveAsyncRunLocation(paramsWithResolvedCwd, DIRS.async, DIRS.results);
4812
5678
  const runId = location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir);
5679
+ const directoryStatus = location.asyncDir ? readStatus(location.asyncDir) : null;
5680
+ if (directoryStatus?.mode === "workflow") {
5681
+ const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, workflowRunId: directoryStatus.runId || runId, asyncDirRoot: DIRS.async });
5682
+ if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
5683
+ return steerWorkflowForegroundTarget({ target: route.target, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal });
5684
+ }
4813
5685
  if (location.asyncDir) {
4814
5686
  const unsupported = externalRunnerControlError(location.asyncDir, "steer");
4815
5687
  if (unsupported) return unsupported;
@@ -4845,8 +5717,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4845
5717
  return { content: [{ type: "text", text }], isError: true, details: { mode: "management", results: [] } };
4846
5718
  }
4847
5719
  if (resolved?.kind === "nested") return steerNestedRun(omitUndefinedProperties({ target: resolved, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal }));
4848
- if (resolved?.kind === "foreground") return { content: [{ type: "text", text: "action='steer' currently supports live async Pi child sessions only; use action='interrupt' or action='resume' for foreground runs." }], isError: true, details: { mode: "management", results: [] } };
5720
+ if (resolved?.kind === "foreground") {
5721
+ const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, childRunId: resolved.id, asyncDirRoot: DIRS.async });
5722
+ if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
5723
+ return steerWorkflowForegroundTarget({ target: route.target, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal });
5724
+ }
4849
5725
  if (resolved?.kind !== "async") return { content: [{ type: "text", text: `No async run found for '${targetRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
5726
+ const resolvedStatus = resolved.location.asyncDir ? readStatus(resolved.location.asyncDir) : null;
5727
+ if (resolvedStatus?.mode === "workflow") {
5728
+ const route = resolveWorkflowForegroundSteeringTarget({ state: deps.state, workflowRunId: resolvedStatus.runId || resolved.id, asyncDirRoot: DIRS.async });
5729
+ if (!route.ok) return { content: [{ type: "text", text: route.message }], isError: true, details: { mode: "management", results: [] } };
5730
+ return steerWorkflowForegroundTarget({ target: route.target, message, mode: paramsWithResolvedCwd.mode, index: paramsWithResolvedCwd.index, signal });
5731
+ }
4850
5732
  if (resolved.location.asyncDir) {
4851
5733
  const unsupported = externalRunnerControlError(resolved.location.asyncDir, "steer");
4852
5734
  if (unsupported) return unsupported;
@@ -4880,6 +5762,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4880
5762
  return appendStepToAsyncChain(omitUndefinedProperties({ params: paramsWithResolvedCwd, requestCwd, ctx, deps, parentModel: requestParentModel }));
4881
5763
  }
4882
5764
  if (action.startsWith("schedule.")) {
5765
+ if (!isScheduledRunAction(action)) {
5766
+ return { content: [{ type: "text", text: unknownSubagentActionMessage(action) }], isError: true, details: { mode: "management", results: [] } };
5767
+ }
4883
5768
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
4884
5769
  return {
4885
5770
  content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }],
@@ -4896,6 +5781,28 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4896
5781
  }
4897
5782
  return deps.handleScheduledRunAction(paramsWithResolvedCwd, ctx);
4898
5783
  }
5784
+ if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
5785
+ return {
5786
+ content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }],
5787
+ isError: true,
5788
+ details: { mode: "management" as const, results: [] },
5789
+ };
5790
+ }
5791
+ if (action === "dismiss") {
5792
+ const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
5793
+ if (!targetRunId) return { content: [{ type: "text", text: "action='dismiss' requires id." }], isError: true, details: { mode: "management", results: [] } };
5794
+ let resolved: ResolvedSubagentRunId | undefined;
5795
+ try {
5796
+ resolved = resolveSubagentRunId(targetRunId, omitUndefinedProperties({ state: deps.state, nested: nestedResolutionScopeForExecutor(deps) }));
5797
+ } catch (error) {
5798
+ const message = error instanceof Error ? error.message : String(error);
5799
+ return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
5800
+ }
5801
+ if (resolved?.kind !== "async") {
5802
+ return { content: [{ type: "text", text: `Run '${targetRunId}' is not a recovered workflow.` }], isError: true, details: { mode: "management", results: [] } };
5803
+ }
5804
+ return dismissRecoveredWorkflow(deps.state, resolved.location);
5805
+ }
4899
5806
  if (action === "stop") {
4900
5807
  const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
4901
5808
  const workflowController = targetRunId ? deps.state.workflowControllers?.get(targetRunId) : undefined;
@@ -4907,6 +5814,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4907
5814
  if (paramsWithResolvedCwd.dir) {
4908
5815
  try {
4909
5816
  const location = resolveAsyncRunLocation(paramsWithResolvedCwd, DIRS.async, DIRS.results);
5817
+ const existingStatus = readStatus(location.asyncDir ?? "");
5818
+ if (existingStatus?.mode === "workflow" && existingStatus.state === "running") {
5819
+ return { content: [{ type: "text", text: `Workflow ${existingStatus.runId} is not controlled by this extension runtime; reload recovery cannot stop it safely.` }], isError: true, details: { mode: "management", results: [] } };
5820
+ }
4910
5821
  const stopResult = stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location);
4911
5822
  return stopResult ?? { content: [{ type: "text", text: `No running or queued async run was found for '${targetRunId ?? paramsWithResolvedCwd.dir}'.` }], isError: true, details: { mode: "management", results: [] } };
4912
5823
  } catch (error) {
@@ -4986,14 +5897,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4986
5897
  }
4987
5898
  if (!(SUBAGENT_ACTIONS as readonly string[]).includes(action)) {
4988
5899
  return {
4989
- content: [{ type: "text", text: `Unknown action: ${action}. Valid: ${SUBAGENT_ACTIONS.join(", ")}` }],
4990
- isError: true,
4991
- details: { mode: "management" as const, results: [] },
4992
- };
4993
- }
4994
- if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
4995
- return {
4996
- content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }],
5900
+ content: [{ type: "text", text: unknownSubagentActionMessage(action) }],
4997
5901
  isError: true,
4998
5902
  details: { mode: "management" as const, results: [] },
4999
5903
  };
@@ -5060,6 +5964,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5060
5964
  const sessionName = resolveIntercomSessionTarget(deps.pi.getSessionName(), ctx.sessionManager.getSessionId());
5061
5965
  const intercomBridge = resolveIntercomBridge({
5062
5966
  config: deps.config.intercomBridge,
5967
+ override: effectiveParams.intercomBridge,
5063
5968
  context: effectiveParams.context ?? (contextPolicy.usesFork ? "fork" : undefined),
5064
5969
  orchestratorTarget: sessionName,
5065
5970
  });
@@ -5069,7 +5974,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5069
5974
  const runId = randomUUID().slice(0, 8);
5070
5975
  const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
5071
5976
  const nestedParentAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
5072
- const nestedRoute = inheritedNestedRoute ?? createNestedRoute(runId);
5073
5977
  const shareEnabled = effectiveParams.share === true;
5074
5978
  const hasChain = (effectiveParams.chain?.length ?? 0) > 0;
5075
5979
  const hasTasks = (effectiveParams.tasks?.length ?? 0) > 0;
@@ -5150,12 +6054,53 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5150
6054
  if (externalAgent && (!effectiveAsync || effectiveParams.foregroundOnly === true)) {
5151
6055
  return buildRequestedModeError(effectiveParams, `Agent '${externalAgent.name}' uses runner.type='external-cli', which currently supports async/background execution only. Omit async or pass async:true; clarify and foregroundOnly are unsupported.`);
5152
6056
  }
5153
- const foregroundTimeout = resolveForegroundTimeout(
6057
+ const foregroundTimeout = resolveSingleAgentLaunchTimeout(
5154
6058
  effectiveParams,
5155
- effectiveAsync ? undefined : DEFAULT_FOREGROUND_TIMEOUT_MS,
6059
+ effectiveAsync,
6060
+ resolveConfigDefaultTimeoutMs(deps.config.timeoutMs),
5156
6061
  );
5157
6062
  if (foregroundTimeout.error) return buildRequestedModeError(effectiveParams, foregroundTimeout.error);
5158
6063
  const controlConfig = resolveControlConfig(deps.config.control, effectiveParams.control);
6064
+ const requestedWorkflowChildAsyncId = typeof effectiveParams.workflowChildAsyncId === "string" ? effectiveParams.workflowChildAsyncId.trim() : "";
6065
+ const asyncRunId = requestedWorkflowChildAsyncId && path.basename(requestedWorkflowChildAsyncId) === requestedWorkflowChildAsyncId
6066
+ ? requestedWorkflowChildAsyncId
6067
+ : randomUUID();
6068
+ const topLevelAsyncCapacityEligible = depth === 0 && !inheritedNestedRoute && !effectiveParams.workflowParentRunId;
6069
+ const topLevelAsync = effectiveAsync && topLevelAsyncCapacityEligible;
6070
+ let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
6071
+ if (topLevelAsync) {
6072
+ try {
6073
+ const activeLimit = resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession);
6074
+ activeAsyncCapacity = acquireActiveAsyncCapacity({
6075
+ sessionId: requestSessionId,
6076
+ limit: activeLimit,
6077
+ runId: asyncRunId,
6078
+ kind: "runner",
6079
+ asyncDir: path.join(DIRS.async, asyncRunId),
6080
+ }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) });
6081
+ deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(requestSessionId, activeLimit, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) });
6082
+ } catch (error) {
6083
+ if (error instanceof ActiveAsyncCapacityError) {
6084
+ deps.state.activeAsyncCapacity = error.snapshot;
6085
+ return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: foregroundMode, results: [], activeAsyncCapacity: error.snapshot } };
6086
+ }
6087
+ throw error;
6088
+ }
6089
+ }
6090
+
6091
+ let runFanoutBudget: RunFanoutBudgetDescriptor;
6092
+ try {
6093
+ const inheritedRunFanoutBudget = effectiveParams.runFanoutBudget ? undefined : decodeRunFanoutBudgetDescriptor(process.env[RUN_FANOUT_BUDGET_ENV]);
6094
+ runFanoutBudget = effectiveParams.runFanoutBudget
6095
+ ?? (inheritedRunFanoutBudget ? { ...inheritedRunFanoutBudget, parentPath: `${inheritedRunFanoutBudget.parentPath ? `${inheritedRunFanoutBudget.parentPath}/` : ""}${runId}` } : undefined)
6096
+ ?? createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun));
6097
+ if (!effectiveParams.runFanoutAdmitted) claimRunFanoutBatch(runFanoutBudget, staticRunFanoutPaths(effectiveParams));
6098
+ } catch (error) {
6099
+ activeAsyncCapacity?.rollback();
6100
+ if (error instanceof RunFanoutLimitError) return runFanoutErrorResult(error, foregroundMode);
6101
+ return buildRequestedModeError(effectiveParams, error instanceof Error ? error.message : String(error));
6102
+ }
6103
+ const nestedRoute = inheritedNestedRoute ?? createNestedRoute(runId);
5159
6104
 
5160
6105
  const artifactConfig: ArtifactConfig = omitUndefinedProperties({
5161
6106
  ...DEFAULT_ARTIFACT_CONFIG,
@@ -5181,6 +6126,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5181
6126
  try {
5182
6127
  fs.mkdirSync(sessionRoot, { recursive: true });
5183
6128
  } catch (error) {
6129
+ activeAsyncCapacity?.rollback();
5184
6130
  const message = error instanceof Error ? error.message : String(error);
5185
6131
  return toExecutionErrorResult(
5186
6132
  effectiveParams,
@@ -5211,10 +6157,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5211
6157
  preflightForkSessionsForStaticTasks(effectiveParams, contextPolicy, forkSessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems);
5212
6158
  }
5213
6159
  } catch (error) {
6160
+ activeAsyncCapacity?.rollback();
5214
6161
  return toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);
5215
6162
  }
5216
6163
  const chainBindingsError = validateExecutionChainBindings(effectiveParams, deps.config.chain?.dynamicFanout?.maxItems);
5217
- if (chainBindingsError) return withResolvedContext(chainBindingsError, contextPolicy.contextSummary);
6164
+ if (chainBindingsError) {
6165
+ activeAsyncCapacity?.rollback();
6166
+ return withResolvedContext(chainBindingsError, contextPolicy.contextSummary);
6167
+ }
5218
6168
 
5219
6169
  const onUpdateWithContext = onUpdate
5220
6170
  ? (r: AgentToolResult<Details>) => onUpdate(withResolvedContext({
@@ -5234,14 +6184,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5234
6184
  ownerSessionId: requestSessionId,
5235
6185
  });
5236
6186
  } catch (error) {
5237
- if (explicitMission) return toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);
6187
+ if (explicitMission) {
6188
+ activeAsyncCapacity?.rollback();
6189
+ return toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);
6190
+ }
5238
6191
  missionWarning = `Mission tracking unavailable: ${error instanceof Error ? error.message : String(error)}`;
5239
6192
  }
5240
6193
 
5241
6194
  const attachMission = (result: AgentToolResult<Details>): AgentToolResult<Details> => {
5242
6195
  if (!missionBinding) return missionWarning ? { ...result, details: { ...result.details, missionWarning } } : result;
5243
6196
  try {
5244
- return attachMissionToLaunchResult({ binding: missionBinding, result });
6197
+ return attachMissionToLaunchResult({ binding: delegatedExecution ? { ...missionBinding, announceInContent: false } : missionBinding, result });
5245
6198
  } catch (error) {
5246
6199
  const warning = `Mission tracking unavailable after launch: ${error instanceof Error ? error.message : String(error)}`;
5247
6200
  if (explicitMission) {
@@ -5262,7 +6215,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5262
6215
  requestSessionId,
5263
6216
  requestedSpawns,
5264
6217
  );
5265
- if (reservation.error) return attachMission(spawnBudgetErrorResult(reservation.error, foregroundMode));
6218
+ if (reservation.error) {
6219
+ activeAsyncCapacity?.rollback();
6220
+ return attachMission(spawnBudgetErrorResult(reservation.error, foregroundMode));
6221
+ }
5266
6222
 
5267
6223
  const execData: ExecutionContextData = omitUndefinedProperties({
5268
6224
  params: effectiveParams,
@@ -5271,6 +6227,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5271
6227
  signal,
5272
6228
  onUpdate: onUpdateWithContext,
5273
6229
  agents,
6230
+ recoveryAgents: discoveredAgents,
5274
6231
  runId,
5275
6232
  shareEnabled,
5276
6233
  sessionRoot,
@@ -5282,6 +6239,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5282
6239
  artifactsDir,
5283
6240
  backgroundRequestedWhileClarifying,
5284
6241
  effectiveAsync,
6242
+ asyncRunId,
5285
6243
  controlConfig,
5286
6244
  intercomBridge,
5287
6245
  nestedRoute,
@@ -5297,17 +6255,34 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5297
6255
  parentSessionId: requestSessionId,
5298
6256
  parentPiSessionId: requestPiSessionId,
5299
6257
  capabilityCeiling: resolveCurrentSubagentCapabilityCeiling(requestSessionId),
6258
+ runFanoutBudget,
6259
+ topLevelAsyncCapacityEligible,
6260
+ activeAsyncCapacity,
5300
6261
  });
5301
6262
 
5302
- const foregroundDescription = effectiveParams.task?.trim()
5303
- || effectiveParams.tasks?.[0]?.task?.trim()
5304
- || (effectiveParams.chain ? firstRawChainTask(effectiveParams.chain)?.trim() : undefined);
6263
+ const foregroundDescription = selectedAgentNames.length === 1
6264
+ ? `${selectedAgentNames[0]} child`
6265
+ : `${selectedAgentNames.length} live children`;
6266
+ const parentWorkflowStatus = effectiveParams.workflowParentRunId
6267
+ ? readStatus(path.join(DIRS.async, effectiveParams.workflowParentRunId))
6268
+ : null;
6269
+ const workflowSteeringDir = effectiveParams.workflowParentRunId
6270
+ && requestSessionId
6271
+ && deps.state.workflowControllers?.has(effectiveParams.workflowParentRunId)
6272
+ && parentWorkflowStatus?.mode === "workflow"
6273
+ && (parentWorkflowStatus.state === "running" || parentWorkflowStatus.state === "queued")
6274
+ && parentWorkflowStatus.sessionId === requestSessionId
6275
+ ? workflowForegroundSteeringDir(DIRS.async, effectiveParams.workflowParentRunId, runId)
6276
+ : undefined;
5305
6277
  const foregroundControl: ForegroundRunControl | undefined = effectiveAsync
5306
6278
  ? undefined
5307
6279
  : compactOptional<ForegroundRunControl>({
5308
6280
  runId,
5309
6281
  sessionId: requestSessionId,
5310
6282
  mode: foregroundMode,
6283
+ ...(effectiveParams.workflowParentRunId ? { parentWorkflowRunId: effectiveParams.workflowParentRunId } : {}),
6284
+ ...(effectiveParams.workflowKey ? { workflowKey: effectiveParams.workflowKey } : {}),
6285
+ workflowSteeringDir,
5311
6286
  startedAt: Date.now(),
5312
6287
  updatedAt: Date.now(),
5313
6288
  cwd: effectiveCwd,
@@ -5322,6 +6297,37 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5322
6297
  interrupt: undefined,
5323
6298
  });
5324
6299
  if (foregroundControl) {
6300
+ foregroundControl.promptAuditRedo = async (index, guidance) => {
6301
+ const audit = getLivePromptAudit(foregroundControl, index);
6302
+ if (!audit?.rerun) return { text: "Redo is not safe for this prompt in this slice.", isError: true };
6303
+ const rewrittenTask = await rewritePromptWithGuidance({
6304
+ ctx,
6305
+ authoredTask: audit.authoredTask,
6306
+ runtimeAdditions: audit.runtimeAdditions,
6307
+ finalEffectivePrompt: audit.finalEffectivePrompt,
6308
+ guidance,
6309
+ signal,
6310
+ });
6311
+ const redoParams = promptAuditRedoParams(audit.rerun.params, rewrittenTask);
6312
+ const previousForegroundId = deps.state.lastForegroundControlId;
6313
+ const launch = execute(randomUUID(), redoParams, signal, undefined, ctx, true);
6314
+ const newRunId = deps.state.lastForegroundControlId && deps.state.lastForegroundControlId !== previousForegroundId
6315
+ ? deps.state.lastForegroundControlId
6316
+ : undefined;
6317
+ if (!newRunId) {
6318
+ const result = await launch;
6319
+ return { text: result.content.find((item) => item.type === "text")?.text ?? "Prompt redo could not start.", isError: true };
6320
+ }
6321
+ foregroundControl.supersededByRunId = newRunId;
6322
+ const replacement = deps.state.foregroundControls.get(newRunId);
6323
+ if (replacement) replacement.sourceRunId = foregroundControl.runId;
6324
+ void launch.then((result) => {
6325
+ if (result.isError) console.warn(`[pi-subagents] Prompt redo ${newRunId} failed: ${result.content.find((item) => item.type === "text")?.text ?? "unknown error"}`);
6326
+ }).catch((error) => {
6327
+ console.warn(`[pi-subagents] Prompt redo ${newRunId} failed: ${error instanceof Error ? error.message : String(error)}`);
6328
+ });
6329
+ return { text: `Prompt redo started ${newRunId}.` };
6330
+ };
5325
6331
  deps.state.foregroundControls.set(runId, foregroundControl);
5326
6332
  deps.state.lastForegroundControlId = runId;
5327
6333
  }
@@ -5412,33 +6418,57 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5412
6418
  };
5413
6419
 
5414
6420
  let nestedForegroundStarted = false;
6421
+ let asyncLaunchFailed = false;
5415
6422
  try {
6423
+ if (effectiveAsync) {
6424
+ deps.state.liveAsyncSessionRoots ??= new Map();
6425
+ deps.state.liveAsyncSessionRoots.set(asyncRunId, sessionRoot);
6426
+ }
6427
+ if (workflowLaunchObserver) {
6428
+ const singleTask = hasTasks && effectiveParams.tasks?.length === 1 ? effectiveParams.tasks[0] : undefined;
6429
+ const launch = hasSingle
6430
+ ? { agent: effectiveParams.agent!, sessionFile: childSessionFileForTask(effectiveParams.agent!, 0, effectiveParams.model), async: effectiveAsync, ...(effectiveAsync ? { runId: asyncRunId } : {}) }
6431
+ : singleTask
6432
+ ? { agent: singleTask.agent, sessionFile: childSessionFileForTask(singleTask.agent, 0, singleTask.model), async: effectiveAsync, ...(effectiveAsync ? { runId: asyncRunId } : {}) }
6433
+ : undefined;
6434
+ if (launch) {
6435
+ workflowLaunchObservers.delete(params);
6436
+ workflowLaunchObserver(launch);
6437
+ }
6438
+ }
5416
6439
  const asyncResult = runAsyncPath(execData, deps);
5417
- if (asyncResult) return attachMission(withResolvedContext(withForkThinkingNotes(asyncResult, forkThinkingDowngrades), contextPolicy.contextSummary));
6440
+ if (asyncResult) {
6441
+ asyncLaunchFailed = asyncResult.isError === true;
6442
+ return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(asyncResult, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget));
6443
+ }
5418
6444
  if (foregroundControl) {
5419
6445
  writeNestedForegroundEvent("subagent.nested.started");
5420
6446
  nestedForegroundStarted = true;
5421
6447
  }
6448
+ const runFanoutAnnotateContent = !delegatedExecution;
5422
6449
  if (hasChain && effectiveParams.chain) {
5423
6450
  const result = await runChainPath(execData, deps);
5424
6451
  writeNestedForegroundEvent("subagent.nested.completed", result);
5425
- return attachMission(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary));
6452
+ return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget, { annotateContent: runFanoutAnnotateContent }));
5426
6453
  }
5427
6454
  if (hasTasks && effectiveParams.tasks) {
5428
6455
  const result = await runParallelPath(execData, deps);
5429
6456
  writeNestedForegroundEvent("subagent.nested.completed", result);
5430
- return attachMission(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary));
6457
+ return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget, { annotateContent: runFanoutAnnotateContent }));
5431
6458
  }
5432
6459
  if (hasSingle) {
5433
6460
  const result = await runSinglePath(execData, deps);
5434
6461
  writeNestedForegroundEvent("subagent.nested.completed", result);
5435
- return attachMission(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary));
6462
+ return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget, { annotateContent: runFanoutAnnotateContent }));
5436
6463
  }
5437
6464
  } catch (error) {
6465
+ asyncLaunchFailed = effectiveAsync;
5438
6466
  const errorResult = withForkThinkingNotes(toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary), forkThinkingDowngrades);
5439
6467
  if (nestedForegroundStarted) writeNestedForegroundEvent("subagent.nested.completed", errorResult);
5440
6468
  return attachMission(errorResult);
5441
6469
  } finally {
6470
+ if (effectiveAsync && (asyncLaunchFailed || (activeAsyncCapacity && !activeAsyncCapacity.owner.runnerStartedAt))) deps.state.liveAsyncSessionRoots?.delete(asyncRunId);
6471
+ if (activeAsyncCapacity && !activeAsyncCapacity.owner.runnerStartedAt) activeAsyncCapacity.rollback();
5442
6472
  if (foregroundControl) {
5443
6473
  settleForegroundSchedulingOwner(foregroundControl);
5444
6474
  removeForegroundControlIfIdle(deps.state, runId);
@@ -5507,6 +6537,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5507
6537
  delete privateParams.delegatedAllowZeroToolBudget;
5508
6538
  if (thinkingOverride !== undefined) delegatedThinkingOverrides.set(delegatedParams, thinkingOverride);
5509
6539
  if (allowZeroToolBudget) delegatedZeroToolBudgets.add(delegatedParams);
6540
+ delegatedExecutions.add(delegatedParams);
5510
6541
  return execute(id, delegatedParams, signal, onUpdate, ctx);
5511
6542
  };
5512
6543