@xzzpig/pi-subagents 0.2.0 → 0.4.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 (103) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +2 -0
  3. package/agents/oracle.md +7 -5
  4. package/agents/researcher.md +1 -1
  5. package/agents/reviewer.md +2 -2
  6. package/agents/scout.md +1 -1
  7. package/agents/worker.md +1 -1
  8. package/docs/agents.md +3 -0
  9. package/docs/configuration.md +121 -10
  10. package/docs/extension-api.md +36 -0
  11. package/docs/missions.md +5 -3
  12. package/docs/observability.md +43 -3
  13. package/docs/tool-reference.md +20 -3
  14. package/docs/workflows.md +2 -2
  15. package/package.json +4 -4
  16. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  17. package/skills/pi-subagents/references/execution-controls.md +5 -4
  18. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  19. package/skills/pi-subagents/references/prompting-and-roles.md +31 -15
  20. package/src/agents/agent-serializer.ts +2 -0
  21. package/src/agents/agents.ts +46 -15
  22. package/src/api/external-runs.ts +174 -84
  23. package/src/api/preflight.ts +13 -7
  24. package/src/extension/config.ts +59 -0
  25. package/src/extension/doctor.ts +40 -0
  26. package/src/extension/index.ts +83 -9
  27. package/src/extension/public-execution.ts +37 -4
  28. package/src/extension/rpc.ts +8 -10
  29. package/src/extension/schemas.ts +12 -10
  30. package/src/extension/tool-description.ts +13 -9
  31. package/src/inspectors/herdr/actions.ts +13 -8
  32. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  33. package/src/inspectors/herdr/project-panes.ts +2 -6
  34. package/src/inspectors/herdr/shell-command.ts +16 -0
  35. package/src/intercom/intercom-bridge.ts +9 -5
  36. package/src/intercom/native-supervisor-channel.ts +19 -42
  37. package/src/missions/goal-driver.ts +3 -1
  38. package/src/missions/lifecycle.ts +4 -7
  39. package/src/missions/store.ts +12 -7
  40. package/src/missions/workflow-state.ts +6 -2
  41. package/src/runs/background/active-async-capacity.ts +431 -0
  42. package/src/runs/background/active-run-index.ts +77 -3
  43. package/src/runs/background/async-execution.ts +190 -72
  44. package/src/runs/background/async-job-tracker.ts +5 -0
  45. package/src/runs/background/async-resume.ts +21 -7
  46. package/src/runs/background/async-status-snapshot.ts +277 -0
  47. package/src/runs/background/async-status.ts +17 -6
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/chain-root-attachment.ts +2 -2
  50. package/src/runs/background/completion-replay.ts +11 -1
  51. package/src/runs/background/fleet-view.ts +21 -6
  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-files.ts +437 -0
  55. package/src/runs/background/result-watcher.ts +188 -41
  56. package/src/runs/background/resume-guidance.ts +27 -7
  57. package/src/runs/background/retained-children.ts +75 -18
  58. package/src/runs/background/run-id-resolver.ts +30 -24
  59. package/src/runs/background/run-status.ts +106 -5
  60. package/src/runs/background/scheduled-runs.ts +54 -28
  61. package/src/runs/background/stale-run-reconciler.ts +30 -16
  62. package/src/runs/background/subagent-runner.ts +352 -62
  63. package/src/runs/background/subagent-wait.ts +2 -0
  64. package/src/runs/background/wait-completions.ts +5 -2
  65. package/src/runs/foreground/async-dismiss-action.ts +2 -1
  66. package/src/runs/foreground/chain-execution.ts +53 -2
  67. package/src/runs/foreground/execution.ts +309 -34
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/prompt-audit.ts +172 -0
  70. package/src/runs/foreground/subagent-executor.ts +936 -224
  71. package/src/runs/shared/acceptance.ts +13 -4
  72. package/src/runs/shared/completion-guard.ts +107 -1
  73. package/src/runs/shared/external-cli-runner.ts +4 -0
  74. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  75. package/src/runs/shared/model-fallback.ts +16 -2
  76. package/src/runs/shared/nested-events.ts +66 -62
  77. package/src/runs/shared/orca-progress-tabs.ts +375 -0
  78. package/src/runs/shared/parallel-utils.ts +4 -0
  79. package/src/runs/shared/pi-args.ts +44 -1
  80. package/src/runs/shared/run-fanout-budget.ts +280 -0
  81. package/src/runs/shared/single-output.ts +4 -2
  82. package/src/runs/shared/subagent-control.ts +15 -0
  83. package/src/runs/shared/subagent-prompt-runtime.ts +1 -9
  84. package/src/runs/shared/subagent-startup-retry.ts +12 -0
  85. package/src/runs/shared/task-intent.ts +19 -3
  86. package/src/runs/shared/tool-timeout.ts +93 -0
  87. package/src/runs/shared/worktree.ts +17 -5
  88. package/src/shared/agent-stream-options.ts +5 -0
  89. package/src/shared/artifacts.ts +2 -6
  90. package/src/shared/display-text.ts +50 -0
  91. package/src/shared/node-executable.ts +21 -0
  92. package/src/shared/types.ts +143 -5
  93. package/src/shared/utils.ts +3 -1
  94. package/src/slash/slash-commands.ts +34 -25
  95. package/src/slash/slash-live-state.ts +3 -0
  96. package/src/tui/fleet-status.ts +164 -47
  97. package/src/tui/fleet-transcript.ts +1 -48
  98. package/src/tui/fleet.ts +352 -27
  99. package/src/tui/render.ts +122 -44
  100. package/src/watchdog/permission-arbiter.ts +2 -1
  101. package/src/watchdog/review.ts +4 -3
  102. package/src/workflows/chat-progress.ts +10 -2
  103. package/src/workflows/scripted-workflow.ts +292 -79
@@ -17,6 +17,7 @@ import {
17
17
  settleForegroundSchedulingOwner,
18
18
  updateForegroundChild,
19
19
  } from "./foreground-control.ts";
20
+ import { getLivePromptAudit, rewritePromptWithGuidance, updateLiveEffectivePrompt } from "./prompt-audit.ts";
20
21
  import { persistForegroundRunHistory, MAX_REMEMBERED_FOREGROUND_RUNS } from "./foreground-history.ts";
21
22
  import { resolveExecutionAgentScope } from "../../agents/agent-scope.ts";
22
23
  import { handleManagementAction } from "../../agents/agent-management.ts";
@@ -54,6 +55,7 @@ import {
54
55
  import { discoverAvailableSkills, normalizeSkillInput } from "../../agents/skills.ts";
55
56
  import { buildAsyncRunnerSteps, DEFAULT_ASYNC_TIMEOUT_MS, executeAsyncChain, executeAsyncSingle, formatAsyncStartedMessage, isAsyncAvailable, workflowAwaitedAsyncResultPath } from "../background/async-execution.ts";
56
57
  import { updateActiveRunIndex } from "../background/active-run-index.ts";
58
+ import { acquireActiveAsyncCapacity, ActiveAsyncCapacityError, getActiveAsyncCapacitySnapshot, resolveMaxActiveAsyncRunsPerSession, transferActiveAsyncCapacity, type ActiveAsyncCapacityHandle } from "../background/active-async-capacity.ts";
57
59
  import { isScheduledRunAction, type ScheduledRunAction } from "../background/scheduled-runs.ts";
58
60
  import { enqueueChainAppendRequest, readPendingChainAppendRequests, runnerStepOutputNames } from "../background/chain-append.ts";
59
61
  import { ChainOutputValidationError, validateChainOutputBindingsWithContext } from "../shared/chain-outputs.ts";
@@ -64,6 +66,7 @@ import { applyIntercomBridgeToAgent, INTERCOM_BRIDGE_MARKER, resolveIntercomBrid
64
66
  import { formatControlIntercomMessage, formatControlNoticeMessage, resolveControlConfig, shouldNotifyControlEvent } from "../shared/subagent-control.ts";
65
67
  import { resolveTurnBudgetConfig } from "../shared/turn-budget.ts";
66
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";
67
70
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
68
71
  import { usageBudgetExceededMessage, usageBudgetState, validateUsageBudgetConfig } from "../shared/usage-budget.ts";
69
72
  import { intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
@@ -71,6 +74,7 @@ import { isAgentContractV1 } from "../shared/agent-contract.ts";
71
74
  import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
72
75
  import { cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
73
76
  import { compactForegroundDetails, getSingleResultOutput, mapConcurrent, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage } from "../../shared/utils.ts";
77
+ import { createTaskMutationArbiter } from "../shared/llm-intent-arbiter.ts";
74
78
  import { DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore } from "../shared/parallel-utils.ts";
75
79
  import { discardPreservedWorktrees, formatParallelHandoffError, formatParallelHandoffReference, parallelHandoffPath, writeParallelHandoffGroup, writePendingParallelHandoff } from "../shared/parallel-handoff.ts";
76
80
  import { summarizeContextModes, type ContextMode, type ContextSummary } from "../shared/context-mode.ts";
@@ -97,6 +101,7 @@ import { stopAsyncRun } from "./async-stop-action.ts";
97
101
  import { dismissRecoveredWorkflow } from "./async-dismiss-action.ts";
98
102
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
99
103
  import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
104
+ import { resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
100
105
  import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, resolveInheritedNestedRouteFromEnv, resolveNestedAsyncDir, resolveNestedParentAddressFromEnv, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedRunResolutionScope } from "../shared/nested-events.ts";
101
106
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
102
107
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
@@ -104,7 +109,7 @@ import { inspectSubagentStatus } from "../background/run-status.ts";
104
109
  import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.ts";
105
110
  import { handleMissionAction, MISSION_ACTIONS } from "../../missions/actions.ts";
106
111
  import { attachMissionToLaunchResult, prepareMissionLaunch, writeMissionAsyncBinding, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
107
- import { updateMission } from "../../missions/store.ts";
112
+ import { MissionNotFoundError, updateMission } from "../../missions/store.ts";
108
113
  import type { MissionWorkflowChildUpdate } from "../../missions/types.ts";
109
114
  import { createMissionWorkflowState } from "../../missions/workflow-state.ts";
110
115
  import { resolveAuthorityDecision } from "../../policy/authority.ts";
@@ -135,6 +140,7 @@ import {
135
140
  type Details,
136
141
  type ExtensionConfig,
137
142
  type ForegroundRunControl,
143
+ type IntercomBridgeConfig,
138
144
  type IntercomEventBus,
139
145
  type JsonSchemaObject,
140
146
  type MaxOutputConfig,
@@ -143,6 +149,7 @@ import {
143
149
  type ResolvedControlConfig,
144
150
  type ResolvedTurnBudget,
145
151
  type ResolvedToolBudget,
152
+ type RunFanoutBudgetDescriptor,
146
153
  type SingleResult,
147
154
  type ToolBudgetConfig,
148
155
  type TurnBudgetConfig,
@@ -161,6 +168,7 @@ import {
161
168
  resolveTopLevelParallelMaxTasks,
162
169
  resolveChildMaxSubagentDepth,
163
170
  resolveCurrentMaxSubagentDepth,
171
+ resolveMaxSubagentSpawnsPerRun,
164
172
  wrapForkTask,
165
173
  } from "../../shared/types.ts";
166
174
 
@@ -284,16 +292,24 @@ export interface SubagentParamsLike {
284
292
  workflowKey?: string;
285
293
  workflowChildAsyncId?: string;
286
294
  suppressRoutineResultIntercom?: boolean;
295
+ /** Internal inherited cumulative run-tree budget. */
296
+ runFanoutBudget?: RunFanoutBudgetDescriptor;
297
+ /** Internal workflow host admission proof. */
298
+ runFanoutAdmitted?: boolean;
287
299
  /** Internal durable-run compatibility fields. Public callers must use workflowScript. */
288
300
  chain?: ChainStep[];
289
301
  tasks?: TaskParam[];
290
302
  concurrency?: number;
291
303
  worktree?: boolean;
292
304
  context?: "fresh" | "fork";
305
+ /** Per-run intercom bridge config. It replaces the global config for this launch only. */
306
+ intercomBridge?: IntercomBridgeConfig;
293
307
  async?: boolean;
294
308
  foregroundOnly?: boolean;
295
309
  timeoutMs?: number;
296
310
  maxRuntimeMs?: number;
311
+ /** Optional hard per-tool-call timeout (ms). Known-fast tools also have a default. */
312
+ toolTimeoutMs?: number;
297
313
  turnBudget?: TurnBudgetConfig;
298
314
  /** Internal-only strict turn-boundary enforcement for versioned foreground delegation. */
299
315
  enforceHardTurnLimit?: boolean;
@@ -377,6 +393,8 @@ interface ExecutionContextData {
377
393
  signal: AbortSignal;
378
394
  onUpdate?: (r: AgentToolResult<Details>) => void;
379
395
  agents: AgentConfig[];
396
+ /** Discovered agent definitions before per-run bridge injection. */
397
+ recoveryAgents: AgentConfig[];
380
398
  runId: string;
381
399
  shareEnabled: boolean;
382
400
  sessionRoot: string;
@@ -388,11 +406,14 @@ interface ExecutionContextData {
388
406
  artifactsDir: string;
389
407
  backgroundRequestedWhileClarifying: boolean;
390
408
  effectiveAsync: boolean;
409
+ asyncRunId: string;
391
410
  controlConfig: ResolvedControlConfig;
392
411
  intercomBridge: IntercomBridgeState;
393
412
  nestedRoute?: NestedRouteInfo;
394
413
  timeoutMs?: number;
395
414
  deadlineAt?: number;
415
+ /** Raw global config.toolTimeoutMs, for per-step resolution in async runners. */
416
+ configToolTimeoutMs?: number;
396
417
  turnBudget?: ResolvedTurnBudget;
397
418
  toolBudget?: ResolvedToolBudget;
398
419
  usageBudget?: UsageBudgetConfig;
@@ -404,6 +425,9 @@ interface ExecutionContextData {
404
425
  parentSessionId: string | null;
405
426
  parentPiSessionId?: string;
406
427
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
428
+ runFanoutBudget: RunFanoutBudgetDescriptor;
429
+ topLevelAsyncCapacityEligible: boolean;
430
+ activeAsyncCapacity?: ActiveAsyncCapacityHandle;
407
431
  }
408
432
 
409
433
  function resolveRequestedCwd(runtimeCwd: string, requestedCwd: string | undefined): string {
@@ -432,6 +456,17 @@ function getForegroundControl(state: SubagentState, runId: string | undefined) {
432
456
  return newest;
433
457
  }
434
458
 
459
+ function promptAuditRedoParams(value: unknown, rewrittenTask: string): SubagentParamsLike {
460
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Prompt redo is missing a safe live launch contract.");
461
+ const params = { ...(value as SubagentParamsLike), task: rewrittenTask, async: false };
462
+ delete params.workflowParentRunId;
463
+ delete params.workflowKey;
464
+ delete params.workflowChildAsyncId;
465
+ delete params.suppressRoutineResultIntercom;
466
+ if (params.worktree === true && Array.isArray(params.tasks)) delete params.cwd;
467
+ return params;
468
+ }
469
+
435
470
  function formatForegroundActivity(control: SubagentState["foregroundControls"] extends Map<string, infer T> ? T : never): string | undefined {
436
471
  const facts: string[] = [];
437
472
  if (control.currentTool && control.currentToolStartedAt) facts.push(`tool ${control.currentTool} for ${Math.floor(Math.max(0, Date.now() - control.currentToolStartedAt) / 1000)}s`);
@@ -483,12 +518,18 @@ function withSpawnBudgetStatus(
483
518
  sessionId: string | null,
484
519
  ): AgentToolResult<Details> {
485
520
  const spawnBudget = getSpawnBudgetSnapshot(state, config, sessionId);
521
+ const activeAsyncCapacity = sessionId
522
+ ? getActiveAsyncCapacitySnapshot(sessionId, resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession), {
523
+ liveWorkflowRunIds: new Set(state.workflowControllers?.keys() ?? []),
524
+ })
525
+ : { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession) ?? 0 };
526
+ state.activeAsyncCapacity = activeAsyncCapacity;
486
527
  return {
487
528
  ...result,
488
529
  content: result.content.map((item, index) => index === 0 && item.type === "text"
489
- ? { ...item, text: `${formatSpawnBudget(spawnBudget)}\n${item.text}` }
530
+ ? { ...item, text: `${formatSpawnBudget(spawnBudget)}\nActive async capacity: ${activeAsyncCapacity.used}/${activeAsyncCapacity.limit || "unlimited"} used\n${item.text}` }
490
531
  : item),
491
- details: { ...result.details, spawnBudget },
532
+ details: { ...result.details, spawnBudget, activeAsyncCapacity },
492
533
  };
493
534
  }
494
535
 
@@ -509,6 +550,31 @@ function countRequestedSubagentSpawns(params: SubagentParamsLike, config: Extens
509
550
  return params.agent ? 1 : 0;
510
551
  }
511
552
 
553
+ function staticRunFanoutPaths(params: SubagentParamsLike): string[] {
554
+ if (params.tasks) return params.tasks.map((_, index) => `tasks[${index}]`);
555
+ if (params.chain) return params.chain.flatMap((step, stepIndex) => {
556
+ if (isDynamicParallelStep(step) || "checkpoint" in step) return [];
557
+ if (isParallelStep(step)) return step.parallel.map((_, itemIndex) => `chain[${stepIndex}].parallel[${itemIndex}]`);
558
+ return [`chain[${stepIndex}]`];
559
+ });
560
+ return params.agent ? ["single"] : [];
561
+ }
562
+
563
+ function runFanoutErrorResult(error: RunFanoutLimitError, mode: "single" | "parallel" | "chain"): AgentToolResult<Details> {
564
+ return { content: [{ type: "text", text: error.message }], isError: true, details: { mode, results: [], runFanoutBudget: error.snapshot, runFanoutRejection: error.rejection } };
565
+ }
566
+
567
+ function withRunFanoutBudget(result: AgentToolResult<Details>, descriptor: RunFanoutBudgetDescriptor, options: { annotateContent?: boolean } = {}): AgentToolResult<Details> {
568
+ const runFanoutBudget = getRunFanoutBudgetSnapshot(descriptor);
569
+ return {
570
+ ...result,
571
+ content: options.annotateContent === false
572
+ ? result.content
573
+ : result.content.map((item, index) => index === 0 && item.type === "text" ? { ...item, text: `${formatRunFanoutBudget(runFanoutBudget)}\n${item.text}` } : item),
574
+ details: { ...result.details, runFanoutBudget },
575
+ };
576
+ }
577
+
512
578
  function foregroundStatusResult(control: SubagentState["foregroundControls"] extends Map<string, infer T> ? T : never): AgentToolResult<Details> {
513
579
  let nestedWarning: string | undefined;
514
580
  try {
@@ -1141,18 +1207,30 @@ function appendStepToAsyncChain(input: {
1141
1207
  }
1142
1208
 
1143
1209
  try {
1210
+ const asyncDir = resolved.location.asyncDir;
1211
+ if (!asyncDir) throw new Error(`Run '${resolved.id}' is missing its async directory.`);
1212
+ const runFanoutBudget = readRunFanoutBudgetDescriptor(asyncDir);
1213
+ if (!runFanoutBudget) throw new Error(`Run '${resolved.id}' is missing its run fan-out budget identity.`);
1214
+ const startIndex = (status.chainStepCount ?? status.steps?.length ?? 0) + pendingAppendRequests.reduce((total, request) => total + request.steps.length, 0);
1215
+ const appendPaths = chain.flatMap((step, localIndex) => {
1216
+ const absoluteIndex = startIndex + localIndex;
1217
+ if (isDynamicParallelStep(step) || "checkpoint" in step) return [];
1218
+ if (isParallelStep(step)) return step.parallel.map((_, itemIndex) => `chain[${absoluteIndex}].parallel[${itemIndex}]`);
1219
+ return [`chain[${absoluteIndex}]`];
1220
+ });
1144
1221
  const result = enqueueChainAppendRequest({
1145
- asyncDir: resolved.location.asyncDir,
1222
+ asyncDir,
1146
1223
  runId: resolved.id,
1147
1224
  steps: built.steps,
1225
+ admit: (persist) => claimRunFanoutBatchWithCommit(runFanoutBudget, appendPaths, persist),
1148
1226
  });
1149
1227
  const stepText = built.steps.length === 1 ? "step" : "steps";
1150
1228
  return {
1151
1229
  content: [{
1152
1230
  type: "text",
1153
- 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}.`,
1231
+ 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}` : ""}`,
1154
1232
  }],
1155
- details: { mode: "management", results: [], asyncId: resolved.id, asyncDir: resolved.location.asyncDir },
1233
+ details: { mode: "management", results: [], asyncId: resolved.id, asyncDir },
1156
1234
  };
1157
1235
  } catch (error) {
1158
1236
  const message = error instanceof Error ? error.message : String(error);
@@ -1443,17 +1521,18 @@ async function resumeAsyncRun(input: {
1443
1521
  const discoveredAgents = discovered.agents;
1444
1522
  const modelScope = discovered.modelScope;
1445
1523
  const sessionName = resolveIntercomSessionTarget(input.deps.pi.getSessionName(), input.ctx.sessionManager.getSessionId());
1524
+ const recoveryDescriptor = "recoveryDescriptor" in target ? target.recoveryDescriptor : undefined;
1446
1525
  const intercomBridge = resolveIntercomBridge({
1447
1526
  config: input.deps.config.intercomBridge,
1527
+ override: input.params.intercomBridge ?? recoveryDescriptor?.intercomBridge,
1448
1528
  context: input.params.context,
1449
1529
  orchestratorTarget: sessionName,
1450
1530
  });
1451
1531
  const agents = intercomBridge.active
1452
1532
  ? discoveredAgents.map((agent) => applyIntercomBridgeToAgent(agent, intercomBridge))
1453
1533
  : discoveredAgents;
1454
- const recoveryDescriptor = "recoveryDescriptor" in target ? target.recoveryDescriptor : undefined;
1455
- const discoveredAgentConfig = agents.find((agent) => agent.name === target.agent);
1456
- const agentConfig: AgentConfig | undefined = discoveredAgentConfig ?? (recoveryDescriptor ? {
1534
+ const discoveredAgentConfig = discoveredAgents.find((agent) => agent.name === target.agent);
1535
+ const baseAgentConfig: AgentConfig | undefined = discoveredAgentConfig ?? (recoveryDescriptor ? {
1457
1536
  name: recoveryDescriptor.agent,
1458
1537
  description: "Persisted async recovery contract",
1459
1538
  systemPrompt: "",
@@ -1463,7 +1542,7 @@ async function resumeAsyncRun(input: {
1463
1542
  source: "project",
1464
1543
  filePath: recoveryDescriptor.agentFilePath ?? path.join(getProjectSubagentsDir(recoveryDescriptor.cwd), "recovery-agent"),
1465
1544
  } : undefined);
1466
- if (!agentConfig) {
1545
+ if (!baseAgentConfig) {
1467
1546
  return {
1468
1547
  content: [{ type: "text", text: `Unknown agent for resume: ${target.agent}` }],
1469
1548
  isError: true,
@@ -1487,6 +1566,20 @@ async function resumeAsyncRun(input: {
1487
1566
  };
1488
1567
  }
1489
1568
  const runId = randomUUID().slice(0, 8);
1569
+ const topLevelResume = depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.params.workflowParentRunId;
1570
+ let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1571
+ try {
1572
+ activeAsyncCapacity = topLevelResume ? acquireActiveAsyncCapacity({
1573
+ sessionId: input.deps.state.currentSessionId!,
1574
+ limit: resolveMaxActiveAsyncRunsPerSession(input.deps.config.maxActiveAsyncRunsPerSession),
1575
+ runId,
1576
+ kind: "runner",
1577
+ asyncDir: path.join(DIRS.async, runId),
1578
+ }, { liveWorkflowRunIds: new Set(input.deps.state.workflowControllers?.keys() ?? []) }) : undefined;
1579
+ } catch (error) {
1580
+ if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "chain", results: [], activeAsyncCapacity: error.snapshot } };
1581
+ throw error;
1582
+ }
1490
1583
  const artifactConfig: ArtifactConfig = omitUndefinedProperties({ ...DEFAULT_ARTIFACT_CONFIG, enabled: input.params.artifacts !== false, dir: input.deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir });
1491
1584
  const availableModels = input.ctx.modelRegistry.getAvailable().map(toModelInfo);
1492
1585
  const contextPolicy = resolveExplicitContextPolicy(input.params);
@@ -1538,9 +1631,14 @@ async function resumeAsyncRun(input: {
1538
1631
  controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : undefined,
1539
1632
  childIntercomTarget: intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : undefined,
1540
1633
  globalConcurrencyLimit: input.deps.config.globalConcurrencyLimit,
1634
+ runFanoutBudget: createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(input.deps.config.maxSubagentSpawnsPerRun)),
1541
1635
  capabilityCeiling: intersectSubagentCapabilityCeilings("capabilityCeiling" in target ? target.capabilityCeiling : undefined, resolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId)),
1636
+ activeAsyncCapacity,
1542
1637
  }));
1543
- if (result.isError) return result;
1638
+ if (result.isError) {
1639
+ activeAsyncCapacity?.rollback();
1640
+ return result;
1641
+ }
1544
1642
  const attachedId = result.details.asyncId ?? runId;
1545
1643
  const lines = [
1546
1644
  `Attached async subagent ${target.runId} as the first step of a new chain.`,
@@ -1559,17 +1657,45 @@ async function resumeAsyncRun(input: {
1559
1657
  if (!revivalSessionFile) {
1560
1658
  return { content: [{ type: "text", text: `Async child '${target.runId}' has no persisted session file to resume.` }], isError: true, details: { mode: "management", results: [] } };
1561
1659
  }
1660
+ if (target.source === "async" && !recoveryDescriptor) {
1661
+ 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: [] } };
1662
+ }
1562
1663
  const runId = randomUUID().slice(0, 8);
1563
- const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(agentConfig, recoveryDescriptor) : agentConfig;
1664
+ const topLevelResume = depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.params.workflowParentRunId;
1665
+ let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1666
+ try {
1667
+ activeAsyncCapacity = !topLevelResume ? undefined : target.source === "async"
1668
+ ? transferActiveAsyncCapacity({
1669
+ sessionId: input.deps.state.currentSessionId!,
1670
+ limit: resolveMaxActiveAsyncRunsPerSession(input.deps.config.maxActiveAsyncRunsPerSession),
1671
+ sourceRunId: target.runId,
1672
+ runId,
1673
+ asyncDir: path.join(DIRS.async, runId),
1674
+ })
1675
+ : acquireActiveAsyncCapacity({
1676
+ sessionId: input.deps.state.currentSessionId!,
1677
+ limit: resolveMaxActiveAsyncRunsPerSession(input.deps.config.maxActiveAsyncRunsPerSession),
1678
+ runId,
1679
+ kind: "runner",
1680
+ asyncDir: path.join(DIRS.async, runId),
1681
+ });
1682
+ } catch (error) {
1683
+ if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "single", results: [], activeAsyncCapacity: error.snapshot } };
1684
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "single", results: [] } };
1685
+ }
1686
+ const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
1687
+ const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
1564
1688
  const artifactConfig: ArtifactConfig = recoveryDescriptor?.artifactConfig ?? omitUndefinedProperties({ ...DEFAULT_ARTIFACT_CONFIG, enabled: input.params.artifacts !== false, dir: input.deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir });
1565
1689
  const artifactsDir = recoveryDescriptor?.artifactsDir ?? getArtifactsDir(parentSessionFile, effectiveCwd, artifactConfig.dir);
1566
1690
  const availableModels = input.ctx.modelRegistry.getAvailable().map(toModelInfo);
1567
1691
  const parentModel = input.parentModel;
1692
+ const revivalAsyncDir = path.join(DIRS.async, runId);
1568
1693
  const result = executeAsyncSingle(runId, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
1569
1694
  agent: target.agent,
1570
1695
  task: buildRevivedAsyncTask(target as Parameters<typeof buildRevivedAsyncTask>[0], effectiveFollowUp),
1571
1696
  goal: effectiveFollowUp,
1572
- agentConfig: recoveryAgentConfig,
1697
+ agentConfig,
1698
+ recoveryAgentConfig,
1573
1699
  ctx: compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
1574
1700
  pi: input.deps.pi,
1575
1701
  cwd: input.requestCwd,
@@ -1604,6 +1730,7 @@ async function resumeAsyncRun(input: {
1604
1730
  worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
1605
1731
  worktreeBaseDir: input.deps.config.worktreeBaseDir,
1606
1732
  controlConfig: recoveryDescriptor?.controlConfig ?? resolveControlConfig(input.deps.config.control, input.params.control),
1733
+ intercomBridge: input.params.intercomBridge ?? recoveryDescriptor?.intercomBridge,
1607
1734
  controlIntercomTarget: intercomBridge.active ? intercomBridge.orchestratorTarget : undefined,
1608
1735
  childIntercomTarget: intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : undefined,
1609
1736
  availableModels,
@@ -1618,10 +1745,28 @@ async function resumeAsyncRun(input: {
1618
1745
  ...(input.params.turnBudget !== undefined ? { turnBudget: input.params.turnBudget } : {}),
1619
1746
  ...(input.params.toolBudget !== undefined ? { toolBudget: input.params.toolBudget } : {}),
1620
1747
  capabilityCeiling: intersectSubagentCapabilityCeilings("capabilityCeiling" in target ? target.capabilityCeiling : undefined, recoveryDescriptor?.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId)),
1748
+ runFanoutBudget: input.params.runFanoutBudget ?? recoveryDescriptor?.runFanoutBudget ?? createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(input.deps.config.maxSubagentSpawnsPerRun)),
1621
1749
  parentWorkflowRunId: input.params.workflowParentRunId,
1622
1750
  workflowKey: input.params.workflowKey,
1751
+ activeAsyncCapacity,
1623
1752
  }));
1624
- if (result.isError) return result;
1753
+ if (result.isError) {
1754
+ const startedStatus = readStatus(revivalAsyncDir);
1755
+ if (input.params.workflowParentRunId !== undefined && startedStatus?.runId === runId && startedStatus.processTerminal?.runnerProcessInstanceId) {
1756
+ return {
1757
+ ...result,
1758
+ details: {
1759
+ ...result.details,
1760
+ runId,
1761
+ asyncId: runId,
1762
+ asyncDir: revivalAsyncDir,
1763
+ ...(target.launchContractDigest ? { sourceLaunchContractDigest: target.launchContractDigest } : {}),
1764
+ },
1765
+ };
1766
+ }
1767
+ activeAsyncCapacity?.rollback();
1768
+ return result;
1769
+ }
1625
1770
  for (const brief of queuedBriefs) fs.rmSync(brief.path, { force: true });
1626
1771
  if (queuedBriefs.length > 0 && sourceAsyncDir) {
1627
1772
  const sourceStatus = readStatus(sourceAsyncDir);
@@ -2117,6 +2262,27 @@ export const DEFAULT_FOREGROUND_TIMEOUT_MS = 30 * 60 * 1000;
2117
2262
  // stay unbounded as a whole, while each runner child has its own deadline.
2118
2263
  export { DEFAULT_ASYNC_TIMEOUT_MS };
2119
2264
 
2265
+ /**
2266
+ * Maximum delay a Node.js timer accepts. Values above the 32-bit signed integer
2267
+ * ceiling overflow `setTimeout`, which silently clamps the delay to ~1ms and
2268
+ * fires almost immediately — so a run configured with a larger deadline would
2269
+ * terminate right away while reporting the long duration. Any timeout destined
2270
+ * for a timer must stay within this bound.
2271
+ */
2272
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
2273
+
2274
+ /**
2275
+ * Resolve the optional global default runtime deadline from extension config
2276
+ * (`config.timeoutMs`). Returns undefined for unset or invalid values so callers
2277
+ * fall back to the built-in defaults. "Invalid" covers non-positive-integer
2278
+ * values and values above `MAX_TIMER_DELAY_MS`; the latter would overflow the
2279
+ * Node.js timer and expire the run almost immediately instead of running long.
2280
+ */
2281
+ export function resolveConfigDefaultTimeoutMs(raw: unknown): number | undefined {
2282
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw <= 0 || raw > MAX_TIMER_DELAY_MS) return undefined;
2283
+ return raw;
2284
+ }
2285
+
2120
2286
  export function resolveForegroundTimeout(params: SubagentParamsLike, defaultTimeoutMs?: number): { timeoutMs?: number; error?: string } {
2121
2287
  const rawTimeout = params.timeoutMs;
2122
2288
  const rawMaxRuntime = params.maxRuntimeMs;
@@ -2140,14 +2306,18 @@ export function resolveForegroundTimeout(params: SubagentParamsLike, defaultTime
2140
2306
  * Resolve the effective launch timeout for a single-agent run, applying the
2141
2307
  * async/foreground default when neither the caller nor the agent set one.
2142
2308
  *
2143
- * The async default is deliberately applied only to plain single-agent
2144
- * launches. Composite launches keep their top-level execution unbounded when
2145
- * no timeout is set; their runner children resolve separate deadlines.
2146
- * Exported so the executor wiring is directly testable.
2309
+ * A global config default (`config.timeoutMs`, passed as `configDefaultTimeoutMs`)
2310
+ * replaces the built-in 30-minute backstop wherever a concrete default is applied.
2311
+ * The async default is deliberately applied only to plain single-agent launches.
2312
+ * Composite launches keep their top-level execution unbounded when no timeout is
2313
+ * set — even with a config default — while their runner children resolve separate
2314
+ * deadlines. Exported so the executor wiring is directly testable.
2147
2315
  */
2148
- export function resolveSingleAgentLaunchTimeout(params: SubagentParamsLike, async: boolean): { timeoutMs?: number; error?: string } {
2316
+ export function resolveSingleAgentLaunchTimeout(params: SubagentParamsLike, async: boolean, configDefaultTimeoutMs?: number): { timeoutMs?: number; error?: string } {
2149
2317
  const isComposite = (params.chain?.length ?? 0) > 0 || (params.tasks?.length ?? 0) > 0 || params.workflowScript !== undefined;
2150
- const defaultTimeoutMs = !async ? DEFAULT_FOREGROUND_TIMEOUT_MS : isComposite ? undefined : DEFAULT_ASYNC_TIMEOUT_MS;
2318
+ const foregroundDefault = configDefaultTimeoutMs ?? DEFAULT_FOREGROUND_TIMEOUT_MS;
2319
+ const asyncSingleDefault = configDefaultTimeoutMs ?? DEFAULT_ASYNC_TIMEOUT_MS;
2320
+ const defaultTimeoutMs = !async ? foregroundDefault : isComposite ? undefined : asyncSingleDefault;
2151
2321
  return resolveForegroundTimeout(params, defaultTimeoutMs);
2152
2322
  }
2153
2323
 
@@ -2341,16 +2511,19 @@ function resolveStaticLaunchSummary(input: {
2341
2511
  thinkingOverrideForTask: ForkThinkingOverrideForTask;
2342
2512
  }): StaticLaunchSummary {
2343
2513
  const agentConfig = input.agents.find((agent) => agent.name === input.agent);
2344
- const model = resolveEffectiveSubagentModel(
2345
- input.explicitModel,
2346
- agentConfig?.model,
2347
- input.parentModel,
2348
- input.availableModels,
2349
- input.currentProvider,
2350
- input.modelScope === undefined ? {} : { scope: input.modelScope },
2351
- );
2352
- const thinkingOverride = input.thinkingOverrideForTask(input.agent, input.index, model);
2353
- const thinking = resolveEffectiveThinking(model, thinkingOverride ?? agentConfig?.thinking);
2514
+ const externalRunner = agentConfig?.runner?.type === "external-cli";
2515
+ const model = externalRunner
2516
+ ? undefined
2517
+ : resolveEffectiveSubagentModel(
2518
+ input.explicitModel,
2519
+ agentConfig?.model,
2520
+ input.parentModel,
2521
+ input.availableModels,
2522
+ input.currentProvider,
2523
+ input.modelScope === undefined ? {} : { scope: input.modelScope },
2524
+ );
2525
+ const thinkingOverride = externalRunner ? undefined : input.thinkingOverrideForTask(input.agent, input.index, model);
2526
+ const thinking = externalRunner ? undefined : resolveEffectiveThinking(model, thinkingOverride ?? agentConfig?.thinking);
2354
2527
  return {
2355
2528
  agent: input.agent,
2356
2529
  ...(model ? { model } : {}),
@@ -2560,8 +2733,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2560
2733
  details: { mode: "single" as const, results: [] },
2561
2734
  };
2562
2735
  }
2563
- const requestedWorkflowChildAsyncId = typeof params.workflowChildAsyncId === "string" ? params.workflowChildAsyncId.trim() : "";
2564
- const id = requestedWorkflowChildAsyncId && path.basename(requestedWorkflowChildAsyncId) === requestedWorkflowChildAsyncId ? requestedWorkflowChildAsyncId : randomUUID();
2736
+ const id = data.asyncRunId;
2565
2737
  const parentModel = data.parentModel;
2566
2738
  const asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
2567
2739
  pi: deps.pi,
@@ -2615,6 +2787,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2615
2787
  shareEnabled,
2616
2788
  sessionRoot,
2617
2789
  chainSkills: [],
2790
+ activeAsyncCapacity: data.activeAsyncCapacity,
2618
2791
  sessionFilesByFlatIndex: params.tasks.map((task, index) => sessionFileForTask(task.agent, index, task.model)),
2619
2792
  thinkingOverridesByFlatIndex: params.tasks.map((task, index) => thinkingOverrideForTask(task.agent, index, task.model)),
2620
2793
  contextForAgent: contextPolicy.contextForAgent,
@@ -2633,7 +2806,10 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2633
2806
  toolBudget: data.toolBudget,
2634
2807
  usageBudget: data.usageBudget,
2635
2808
  configToolBudget: data.configToolBudget,
2809
+ callToolTimeoutMs: data.params?.toolTimeoutMs,
2810
+ configToolTimeoutMs: data.configToolTimeoutMs,
2636
2811
  capabilityCeiling: data.capabilityCeiling,
2812
+ runFanoutBudget: data.runFanoutBudget,
2637
2813
  globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
2638
2814
  parentWorkflowRunId: params.workflowParentRunId,
2639
2815
  workflowKey: params.workflowKey,
@@ -2659,6 +2835,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2659
2835
  shareEnabled,
2660
2836
  sessionRoot,
2661
2837
  chainSkills,
2838
+ activeAsyncCapacity: data.activeAsyncCapacity,
2662
2839
  sessionFilesByFlatIndex: collectChainSessionFiles(chain, sessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems),
2663
2840
  thinkingOverridesByFlatIndex: collectChainThinkingOverrides(chain, thinkingOverrideForTask, deps.config.chain?.dynamicFanout?.maxItems),
2664
2841
  contextForAgent: contextPolicy.contextForAgent,
@@ -2678,7 +2855,10 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2678
2855
  toolBudget: data.toolBudget,
2679
2856
  usageBudget: data.usageBudget,
2680
2857
  configToolBudget: data.configToolBudget,
2858
+ callToolTimeoutMs: data.params?.toolTimeoutMs,
2859
+ configToolTimeoutMs: data.configToolTimeoutMs,
2681
2860
  capabilityCeiling: data.capabilityCeiling,
2861
+ runFanoutBudget: data.runFanoutBudget,
2682
2862
  globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
2683
2863
  parentWorkflowRunId: params.workflowParentRunId,
2684
2864
  workflowKey: params.workflowKey,
@@ -2700,12 +2880,18 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2700
2880
  const normalizedSkills = normalizeSkillInput(params.skill);
2701
2881
  const skills = normalizedSkills === false ? [] : normalizedSkills;
2702
2882
  const maxSubagentDepth = resolveChildMaxSubagentDepth(currentMaxSubagentDepth, a.maxSubagentDepth);
2703
- const modelOverride = resolveEffectiveSubagentModel(params.model as string | undefined, a.model, parentModel, availableModels, currentProvider, data.modelScope === undefined ? {} : { scope: data.modelScope });
2883
+ const externalRunnerWithoutExplicitModel = a.runner?.type === "external-cli"
2884
+ && params.model === undefined
2885
+ && (a.model === undefined || (a.modelSource?.type === "subagents.defaultModel" && a.model === a.modelSource.model));
2886
+ const modelOverride = a.runner?.type === "external-cli"
2887
+ ? params.model ?? (externalRunnerWithoutExplicitModel ? undefined : a.model)
2888
+ : resolveEffectiveSubagentModel(params.model as string | undefined, a.model, parentModel, availableModels, currentProvider, data.modelScope === undefined ? {} : { scope: data.modelScope });
2704
2889
  return executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
2705
2890
  agent: params.agent!,
2706
2891
  task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(params.task ?? "") : (params.task ?? ""),
2707
2892
  goal: params.task ?? "",
2708
2893
  agentConfig: a,
2894
+ recoveryAgentConfig: data.recoveryAgents.find((agent) => agent.name === params.agent),
2709
2895
  ctx: asyncCtx,
2710
2896
  availableModels,
2711
2897
  cwd: effectiveCwd,
@@ -2713,6 +2899,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2713
2899
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
2714
2900
  artifactConfig,
2715
2901
  shareEnabled,
2902
+ activeAsyncCapacity: data.activeAsyncCapacity,
2716
2903
  sessionRoot,
2717
2904
  sessionFile: sessionFileForTask(params.agent!, 0, modelOverride),
2718
2905
  context: contextPolicy.contextForAgent(params.agent!),
@@ -2722,13 +2909,14 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2722
2909
  ...(params.reads !== undefined ? { reads: params.reads } : {}),
2723
2910
  outputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),
2724
2911
  modelOverride,
2725
- thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride),
2912
+ thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(params.agent!, 0, modelOverride),
2726
2913
  maxSubagentDepth,
2727
2914
  waitToolEnabled: deps.waitToolEnabled,
2728
2915
  worktreeSetupHook: deps.config.worktreeSetupHook,
2729
2916
  worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
2730
2917
  worktreeBaseDir: deps.config.worktreeBaseDir,
2731
2918
  controlConfig,
2919
+ intercomBridge: params.intercomBridge,
2732
2920
  controlIntercomTarget,
2733
2921
  childIntercomTarget: childIntercomTarget ? (agent, index) => childIntercomTarget(agent, index) : undefined,
2734
2922
  nestedRoute,
@@ -2740,7 +2928,10 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2740
2928
  toolBudget: data.toolBudget,
2741
2929
  usageBudget: data.usageBudget,
2742
2930
  configToolBudget: data.configToolBudget,
2931
+ toolTimeoutMs: data.params?.toolTimeoutMs,
2932
+ configToolTimeoutMs: data.configToolTimeoutMs,
2743
2933
  capabilityCeiling: data.capabilityCeiling,
2934
+ runFanoutBudget: data.runFanoutBudget,
2744
2935
  parentWorkflowRunId: params.workflowParentRunId,
2745
2936
  workflowKey: params.workflowKey,
2746
2937
  }));
@@ -2828,9 +3019,12 @@ async function runChainPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
2828
3019
  toolBudget: data.toolBudget,
2829
3020
  usageBudget: data.usageBudget,
2830
3021
  configToolBudget: data.configToolBudget,
3022
+ callToolTimeoutMs: data.params?.toolTimeoutMs,
3023
+ configToolTimeoutMs: data.configToolTimeoutMs,
2831
3024
  permissions: deps.config.permissions,
2832
3025
  globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
2833
3026
  capabilityCeiling: data.capabilityCeiling,
3027
+ runFanoutBudget: data.runFanoutBudget,
2834
3028
  }));
2835
3029
 
2836
3030
  if (chainResult.requestedAsync) {
@@ -2841,7 +3035,9 @@ async function runChainPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
2841
3035
  details: { mode: "chain" as const, results: [] },
2842
3036
  };
2843
3037
  }
2844
- const id = randomUUID();
3038
+ const id = data.asyncRunId;
3039
+ const capacity = acquireClarifiedBackgroundCapacity(data, deps, "chain", id);
3040
+ if (capacity.errorResult) return capacity.errorResult;
2845
3041
  const parentModel = data.parentModel;
2846
3042
  const asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
2847
3043
  pi: deps.pi,
@@ -2857,42 +3053,50 @@ async function runChainPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
2857
3053
  const rawAsyncChain = chainResult.requestedAsync.chain;
2858
3054
  const asyncChain = wrapChainTasksForFork(rawAsyncChain, contextPolicy);
2859
3055
  const firstAgent = firstChainAgent(rawAsyncChain);
2860
- return executeAsyncChain(id, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
2861
- chain: asyncChain,
2862
- task: params.task,
2863
- goal: resolveAsyncEventGoal(params.task, rawAsyncChain, firstAgent ? shouldForkAgent(contextPolicy, firstAgent) : false),
2864
- agents,
2865
- ctx: asyncCtx,
2866
- availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
2867
- cwd: effectiveCwd,
2868
- maxOutput: params.maxOutput,
2869
- artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
2870
- artifactConfig,
2871
- shareEnabled,
2872
- sessionRoot,
2873
- chainSkills: chainResult.requestedAsync.chainSkills,
2874
- sessionFilesByFlatIndex: collectChainSessionFiles(asyncChain, sessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems),
2875
- thinkingOverridesByFlatIndex: collectChainThinkingOverrides(asyncChain, thinkingOverrideForTask, deps.config.chain?.dynamicFanout?.maxItems),
2876
- contextForAgent: contextPolicy.contextForAgent,
2877
- dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
2878
- maxSubagentDepth: currentMaxSubagentDepth,
2879
- waitToolEnabled: deps.waitToolEnabled,
2880
- worktreeSetupHook: deps.config.worktreeSetupHook,
2881
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
2882
- worktreeBaseDir: deps.config.worktreeBaseDir,
2883
- controlConfig,
2884
- agentContract: params.agentContract,
2885
- controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
2886
- childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
2887
- nestedRoute: data.nestedRoute,
2888
- timeoutMs: data.timeoutMs,
2889
- turnBudget: data.turnBudget,
2890
- toolBudget: data.toolBudget,
2891
- usageBudget: data.usageBudget,
2892
- configToolBudget: data.configToolBudget,
2893
- capabilityCeiling: data.capabilityCeiling,
2894
- globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
2895
- }));
3056
+ try {
3057
+ return executeAsyncChain(id, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
3058
+ chain: asyncChain,
3059
+ task: params.task,
3060
+ goal: resolveAsyncEventGoal(params.task, rawAsyncChain, firstAgent ? shouldForkAgent(contextPolicy, firstAgent) : false),
3061
+ agents,
3062
+ ctx: asyncCtx,
3063
+ availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
3064
+ cwd: effectiveCwd,
3065
+ maxOutput: params.maxOutput,
3066
+ artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3067
+ artifactConfig,
3068
+ shareEnabled,
3069
+ sessionRoot,
3070
+ chainSkills: chainResult.requestedAsync.chainSkills,
3071
+ activeAsyncCapacity: capacity.activeAsyncCapacity,
3072
+ sessionFilesByFlatIndex: collectChainSessionFiles(asyncChain, sessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems),
3073
+ thinkingOverridesByFlatIndex: collectChainThinkingOverrides(asyncChain, thinkingOverrideForTask, deps.config.chain?.dynamicFanout?.maxItems),
3074
+ contextForAgent: contextPolicy.contextForAgent,
3075
+ dynamicFanoutMaxItems: deps.config.chain?.dynamicFanout?.maxItems,
3076
+ maxSubagentDepth: currentMaxSubagentDepth,
3077
+ waitToolEnabled: deps.waitToolEnabled,
3078
+ worktreeSetupHook: deps.config.worktreeSetupHook,
3079
+ worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
3080
+ worktreeBaseDir: deps.config.worktreeBaseDir,
3081
+ controlConfig,
3082
+ agentContract: params.agentContract,
3083
+ controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
3084
+ childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
3085
+ nestedRoute: data.nestedRoute,
3086
+ timeoutMs: data.timeoutMs,
3087
+ turnBudget: data.turnBudget,
3088
+ toolBudget: data.toolBudget,
3089
+ usageBudget: data.usageBudget,
3090
+ configToolBudget: data.configToolBudget,
3091
+ callToolTimeoutMs: data.params?.toolTimeoutMs,
3092
+ configToolTimeoutMs: data.configToolTimeoutMs,
3093
+ capabilityCeiling: data.capabilityCeiling,
3094
+ runFanoutBudget: data.runFanoutBudget,
3095
+ globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
3096
+ }));
3097
+ } finally {
3098
+ finalizeClarifiedBackgroundCapacity(data, deps, capacity.activeAsyncCapacity);
3099
+ }
2896
3100
  }
2897
3101
 
2898
3102
  const rawChainDetails = chainResult.details ? compactOptional<Details>({ ...chainResult.details, runId, timeoutMs: data.timeoutMs }) : undefined;
@@ -2937,6 +3141,7 @@ interface ForegroundParallelRunInput {
2937
3141
  intercomEvents: IntercomEventBus;
2938
3142
  parentSessionId: string | null;
2939
3143
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
3144
+ runFanoutBudget: RunFanoutBudgetDescriptor;
2940
3145
  signal: AbortSignal;
2941
3146
  runId: string;
2942
3147
  sessionDirForIndex: (idx?: number) => string | undefined;
@@ -2972,6 +3177,10 @@ interface ForegroundParallelRunInput {
2972
3177
  worktreeSetup?: WorktreeSetup;
2973
3178
  timeoutMs?: number;
2974
3179
  deadlineAt?: number;
3180
+ /** Per-call per-tool timeout, resolved separately for each task's agent. */
3181
+ toolTimeoutMs?: number;
3182
+ /** Raw global config.toolTimeoutMs, used by each task's resolver. */
3183
+ configToolTimeoutMs?: number;
2975
3184
  turnBudget?: ResolvedTurnBudget;
2976
3185
  usageBudget?: UsageBudgetConfig;
2977
3186
  toolBudgets: (ResolvedToolBudget | undefined)[];
@@ -2986,6 +3195,48 @@ function buildParallelModeError(message: string): AgentToolResult<Details> {
2986
3195
  };
2987
3196
  }
2988
3197
 
3198
+ function acquireClarifiedBackgroundCapacity(
3199
+ data: ExecutionContextData,
3200
+ deps: ExecutorDeps,
3201
+ mode: "single" | "parallel" | "chain",
3202
+ asyncRunId: string,
3203
+ ): { activeAsyncCapacity?: ActiveAsyncCapacityHandle; errorResult?: AgentToolResult<Details> } {
3204
+ if (!data.topLevelAsyncCapacityEligible || !data.parentSessionId) return {};
3205
+ const liveWorkflowRunIds = new Set(deps.state.workflowControllers?.keys() ?? []);
3206
+ const activeLimit = resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession);
3207
+ try {
3208
+ const activeAsyncCapacity = acquireActiveAsyncCapacity({
3209
+ sessionId: data.parentSessionId,
3210
+ limit: activeLimit,
3211
+ runId: asyncRunId,
3212
+ kind: "runner",
3213
+ asyncDir: path.join(DIRS.async, asyncRunId),
3214
+ }, { liveWorkflowRunIds });
3215
+ deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(data.parentSessionId, activeLimit, { liveWorkflowRunIds });
3216
+ return { activeAsyncCapacity };
3217
+ } catch (error) {
3218
+ if (error instanceof ActiveAsyncCapacityError) {
3219
+ deps.state.activeAsyncCapacity = error.snapshot;
3220
+ return { errorResult: { content: [{ type: "text", text: error.message }], isError: true, details: { mode, results: [], activeAsyncCapacity: error.snapshot } } };
3221
+ }
3222
+ throw error;
3223
+ }
3224
+ }
3225
+
3226
+ function finalizeClarifiedBackgroundCapacity(
3227
+ data: ExecutionContextData,
3228
+ deps: ExecutorDeps,
3229
+ activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined,
3230
+ ): void {
3231
+ if (!activeAsyncCapacity || !data.parentSessionId) return;
3232
+ if (!activeAsyncCapacity.owner.runnerStartedAt) activeAsyncCapacity.rollback();
3233
+ deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(
3234
+ data.parentSessionId,
3235
+ resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession),
3236
+ { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) },
3237
+ );
3238
+ }
3239
+
2989
3240
  function createParallelWorktreeSetup(
2990
3241
  enabled: boolean | undefined,
2991
3242
  cwd: string,
@@ -3021,10 +3272,128 @@ function buildParallelWorktreeTaskCwdError(
3021
3272
  return formatWorktreeTaskCwdConflict(conflict, sharedCwd);
3022
3273
  }
3023
3274
 
3024
- function resolveSingleRunOutputBaseDir(deps: ExecutorDeps, artifactsDir: string, runId: string): string {
3275
+ function resolveConfiguredSingleRunOutputBaseDir(deps: ExecutorDeps): string | undefined {
3025
3276
  return deps.config.singleRunOutputBaseDir
3026
3277
  ? path.resolve(deps.expandTilde(deps.config.singleRunOutputBaseDir))
3027
- : path.join(artifactsDir, "outputs", runId);
3278
+ : undefined;
3279
+ }
3280
+
3281
+ function resolveSingleRunOutputBaseDir(deps: ExecutorDeps, artifactsDir: string, runId: string): string {
3282
+ return resolveConfiguredSingleRunOutputBaseDir(deps) ?? path.join(artifactsDir, "outputs", runId);
3283
+ }
3284
+
3285
+ function resolveWorkflowAggregateOutputPath(
3286
+ output: string | boolean | undefined,
3287
+ ctxCwd: string,
3288
+ workflowCwd: string,
3289
+ outputBaseDir: string,
3290
+ configuredOutputBaseDir: string | undefined,
3291
+ ): string | undefined {
3292
+ if (typeof output === "string" && output && !path.isAbsolute(output) && !configuredOutputBaseDir) return path.resolve(workflowCwd, output);
3293
+ return resolveSingleOutputPath(output, ctxCwd, workflowCwd, outputBaseDir);
3294
+ }
3295
+
3296
+ function workflowChildDefaultOutput(aggregateOutputPath: string | undefined, artifactsDir: string, workflowRunId: string, workflowKey: string): string {
3297
+ if (aggregateOutputPath) {
3298
+ const parsed = path.parse(aggregateOutputPath);
3299
+ return path.join(parsed.dir, `${parsed.name}.${workflowKey}${parsed.ext || ".md"}`);
3300
+ }
3301
+ return path.join(artifactsDir, "outputs", workflowRunId, `${workflowKey}.md`);
3302
+ }
3303
+
3304
+ function writeWorkflowAggregateOutput(outputPath: string | undefined, text: string): string | undefined {
3305
+ if (!outputPath) return undefined;
3306
+ try {
3307
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
3308
+ fs.writeFileSync(outputPath, text, "utf-8");
3309
+ return undefined;
3310
+ } catch (error) {
3311
+ return `Output file error: ${outputPath}\n${error instanceof Error ? error.message : String(error)}`;
3312
+ }
3313
+ }
3314
+
3315
+ function appendWorkflowOutputWarning(text: string, warning: string | undefined): string {
3316
+ return warning ? `${text}\n\n${warning}` : text;
3317
+ }
3318
+
3319
+ function resolveWorkflowChildOutputPath(input: {
3320
+ ctxCwd: string;
3321
+ workflowCwd: string;
3322
+ artifactsDir: string;
3323
+ workflowRunId: string;
3324
+ aggregateOutputPath?: string;
3325
+ configuredOutputBaseDir?: string;
3326
+ discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3327
+ workflowAgentScope?: unknown;
3328
+ key: string;
3329
+ params: Record<string, unknown>;
3330
+ }): string | undefined {
3331
+ const rawOutput = input.params.output;
3332
+ const hasExplicitOutput = typeof rawOutput === "string" || typeof rawOutput === "boolean";
3333
+ const childCwd = typeof input.params.cwd === "string" ? resolveChildCwd(input.workflowCwd, input.params.cwd) : input.workflowCwd;
3334
+ const agentScope = resolveExecutionAgentScope(input.params.agentScope ?? input.workflowAgentScope);
3335
+ const agents = input.discoverAgents(childCwd, agentScope).agents;
3336
+ const agent = typeof input.params.agent === "string" ? resolveAgentName(input.params.agent, agents).agent : undefined;
3337
+ const agentOutput = typeof agent?.output === "string" ? agent.output : undefined;
3338
+ const output = rawOutput === true || rawOutput === "true"
3339
+ ? agentOutput
3340
+ : hasExplicitOutput
3341
+ ? rawOutput
3342
+ : workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.workflowRunId, input.key);
3343
+ return resolveSingleOutputPath(output, input.ctxCwd, childCwd, input.configuredOutputBaseDir);
3344
+ }
3345
+
3346
+ function workflowChildOutputClaims(input: {
3347
+ ctxCwd: string;
3348
+ workflowCwd: string;
3349
+ artifactsDir: string;
3350
+ workflowRunId: string;
3351
+ aggregateOutputPath?: string;
3352
+ configuredOutputBaseDir?: string;
3353
+ discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3354
+ workflowAgentScope?: unknown;
3355
+ claimedOutputPaths: Map<string, string>;
3356
+ entries: Array<{ key: string; params: Record<string, unknown> }>;
3357
+ }): { error?: string; claims?: Map<string, string> } {
3358
+ const claims = new Map(input.claimedOutputPaths);
3359
+ for (const { key, params } of input.entries) {
3360
+ const resolved = resolveWorkflowChildOutputPath({ ...input, key, params });
3361
+ if (!resolved) continue;
3362
+ 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.` };
3363
+ const previous = claims.get(resolved);
3364
+ if (previous) return { error: `Workflow children '${previous}' and '${key}' resolve output to the same path: ${resolved}. Use distinct child output paths.` };
3365
+ claims.set(resolved, key);
3366
+ }
3367
+ return { claims };
3368
+ }
3369
+
3370
+ function applyWorkflowChildOutputClaims(target: Map<string, string>, claims: Map<string, string>): void {
3371
+ target.clear();
3372
+ for (const [resolved, key] of claims) target.set(resolved, key);
3373
+ }
3374
+
3375
+ function prepareWorkflowChildLaunchParams(input: {
3376
+ workflowDefaults: SubagentParamsLike;
3377
+ childParams: Record<string, unknown>;
3378
+ parentWorkflowRunId: string;
3379
+ workflowKey: string;
3380
+ ctxCwd: string;
3381
+ workflowCwd: string;
3382
+ artifactsDir: string;
3383
+ aggregateOutputPath?: string;
3384
+ configuredOutputBaseDir?: string;
3385
+ discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3386
+ workflowAgentScope?: unknown;
3387
+ options?: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor };
3388
+ }): SubagentParamsLike {
3389
+ let childParams = input.childParams;
3390
+ if (input.childParams.output === undefined && input.childParams.resume === undefined) {
3391
+ childParams = { ...input.childParams, output: workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.parentWorkflowRunId, input.workflowKey) };
3392
+ } else if (input.childParams.resume === undefined) {
3393
+ 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 });
3394
+ if (resolvedOutput) childParams = { ...input.childParams, output: resolvedOutput };
3395
+ }
3396
+ return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, input.options);
3028
3397
  }
3029
3398
 
3030
3399
  function buildChainWorktreeTaskCwdError(chain: ChainStep[], sharedCwd: string): string | undefined {
@@ -3174,7 +3543,35 @@ async function runForegroundParallelTasks(input: ForegroundParallelRunInput): Pr
3174
3543
  beginForegroundChild(input.foregroundControl, {
3175
3544
  index,
3176
3545
  agent: task.agent,
3177
- ...(input.taskDescriptions[index] === undefined ? {} : { description: input.taskDescriptions[index] }),
3546
+ authoredTask: input.taskDescriptions[index] ?? "",
3547
+ effectivePrompt: taskText,
3548
+ cwd: taskCwd,
3549
+ ...(outputPath ? { outputPath } : {}),
3550
+ rerun: { params: compactOptional<Record<string, unknown>>({
3551
+ agent: task.agent,
3552
+ task: input.taskDescriptions[index] ?? "",
3553
+ async: false,
3554
+ cwd: input.worktreeSetup ? undefined : taskCwd,
3555
+ worktree: input.worktreeSetup ? true : false,
3556
+ context: input.contextPolicy.contextForAgent(task.agent),
3557
+ share: input.shareEnabled || undefined,
3558
+ maxOutput: input.maxOutput,
3559
+ timeoutMs: input.timeoutMs,
3560
+ toolTimeoutMs: input.toolTimeoutMs,
3561
+ configToolTimeoutMs: input.configToolTimeoutMs,
3562
+ turnBudget: input.turnBudget,
3563
+ ...(model ? { model } : {}),
3564
+ ...(effectiveSkills !== undefined ? { skill: effectiveSkills } : {}),
3565
+ ...(outputPath ? { output: outputPath } : {}),
3566
+ ...(behavior?.outputMode !== undefined ? { outputMode: behavior.outputMode } : {}),
3567
+ ...(behavior?.reads !== undefined ? { reads: behavior.reads } : {}),
3568
+ ...(behavior?.progress !== undefined ? { progress: behavior.progress } : {}),
3569
+ ...(task.toolBudget !== undefined ? { toolBudget: task.toolBudget } : {}),
3570
+ ...(task.outputSchema !== undefined ? { outputSchema: task.outputSchema } : {}),
3571
+ ...(task.acceptance !== undefined ? { acceptance: task.acceptance } : {}),
3572
+ ...(task.agentContract !== undefined || input.agentContract !== undefined ? { agentContract: task.agentContract ?? input.agentContract } : {}),
3573
+ }) },
3574
+ description: `${task.agent} child`,
3178
3575
  ...(model ? { model } : {}),
3179
3576
  ...(thinking ? { thinking } : {}),
3180
3577
  interrupt: () => {
@@ -3191,8 +3588,10 @@ async function runForegroundParallelTasks(input: ForegroundParallelRunInput): Pr
3191
3588
  const result = await runSync(input.ctx.cwd, input.agents, task.agent, taskText, compactOptional<Parameters<typeof runSync>[4]>({
3192
3589
  permissions: input.permissions,
3193
3590
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
3591
+ llmIntentArbiter: createTaskMutationArbiter(input.ctx),
3194
3592
  ...workflowForegroundSteeringLaunchOptions(input.foregroundControl, index),
3195
3593
  context: input.contextPolicy.contextForAgent(task.agent),
3594
+ runFanoutBudget: { ...input.runFanoutBudget, parentPath: `${input.runFanoutBudget.parentPath ? `${input.runFanoutBudget.parentPath}/` : ""}tasks[${index}]` },
3196
3595
  cwd: taskCwd,
3197
3596
  signal: input.signal,
3198
3597
  interruptSignal: interruptController.signal,
@@ -3237,7 +3636,10 @@ async function runForegroundParallelTasks(input: ForegroundParallelRunInput): Pr
3237
3636
  agentContract: task.agentContract ?? input.agentContract,
3238
3637
  acceptance: task.acceptance,
3239
3638
  acceptanceContext: { mode: "parallel" },
3639
+ onEffectivePrompt: input.foregroundControl ? (prompt) => updateLiveEffectivePrompt(input.foregroundControl!, index, prompt) : undefined,
3240
3640
  timeoutMs: input.timeoutMs,
3641
+ toolTimeoutMs: input.toolTimeoutMs,
3642
+ configToolTimeoutMs: input.configToolTimeoutMs,
3241
3643
  deadlineAt: input.deadlineAt,
3242
3644
  turnBudget: input.turnBudget,
3243
3645
  toolBudget: input.toolBudgets[index],
@@ -3365,7 +3767,9 @@ async function runParallelPath(data: ExecutionContextData, deps: ExecutorDeps):
3365
3767
  ...(task.model !== undefined ? { model: task.model } : {}),
3366
3768
  }));
3367
3769
  const modelOverrides: (string | undefined)[] = tasks.map((_, i) =>
3368
- resolveEffectiveSubagentModel(behaviorOverrides[i]?.model, agentConfigs[i]?.model, parentModel, availableModels, currentProvider, data.modelScope === undefined ? {} : { scope: data.modelScope }),
3770
+ agentConfigs[i]?.runner?.type === "external-cli"
3771
+ ? undefined
3772
+ : resolveEffectiveSubagentModel(behaviorOverrides[i]?.model, agentConfigs[i]?.model, parentModel, availableModels, currentProvider, data.modelScope === undefined ? {} : { scope: data.modelScope }),
3369
3773
  );
3370
3774
 
3371
3775
  if (params.clarify === true && ctx.hasUI) {
@@ -3400,7 +3804,9 @@ async function runParallelPath(data: ExecutionContextData, deps: ExecutorDeps):
3400
3804
  for (let i = 0; i < result.behaviorOverrides.length; i++) {
3401
3805
  const override = result.behaviorOverrides[i];
3402
3806
  if (override?.model !== undefined) {
3403
- modelOverrides[i] = resolveEffectiveSubagentModel(override.model, agentConfigs[i]?.model, parentModel, availableModels, currentProvider, data.modelScope === undefined ? {} : { scope: data.modelScope });
3807
+ modelOverrides[i] = agentConfigs[i]?.runner?.type === "external-cli"
3808
+ ? undefined
3809
+ : resolveEffectiveSubagentModel(override.model, agentConfigs[i]?.model, parentModel, availableModels, currentProvider, data.modelScope === undefined ? {} : { scope: data.modelScope });
3404
3810
  behaviorOverrides[i]!.model = override.model;
3405
3811
  }
3406
3812
  if (override?.output !== undefined) behaviorOverrides[i]!.output = override.output;
@@ -3420,7 +3826,9 @@ async function runParallelPath(data: ExecutionContextData, deps: ExecutorDeps):
3420
3826
  details: { mode: "parallel" as const, results: [] },
3421
3827
  };
3422
3828
  }
3423
- const id = randomUUID();
3829
+ const id = data.asyncRunId;
3830
+ const capacity = acquireClarifiedBackgroundCapacity(data, deps, "parallel", id);
3831
+ if (capacity.errorResult) return capacity.errorResult;
3424
3832
  const asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
3425
3833
  pi: deps.pi,
3426
3834
  cwd: ctx.cwd,
@@ -3451,40 +3859,48 @@ async function runParallelPath(data: ExecutionContextData, deps: ExecutorDeps):
3451
3859
  ...(t.agentContract !== undefined ? { agentContract: t.agentContract } : {}),
3452
3860
  });
3453
3861
  });
3454
- return executeAsyncChain(id, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
3455
- chain: [compactOptional<ParallelStep>({ parallel: parallelTasks, concurrency: parallelConcurrency, worktree: params.worktree })],
3456
- resultMode: "parallel",
3457
- goal: taskTexts[0] ?? "",
3458
- agents,
3459
- ctx: asyncCtx,
3460
- availableModels,
3461
- cwd: effectiveCwd,
3462
- maxOutput: params.maxOutput,
3463
- artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3464
- artifactConfig,
3465
- shareEnabled,
3466
- sessionRoot,
3467
- chainSkills: [],
3468
- sessionFilesByFlatIndex: tasks.map((task, index) => sessionFileForTask(task.agent, index, modelOverrides[index])),
3469
- thinkingOverridesByFlatIndex: tasks.map((task, index) => thinkingOverrideForTask(task.agent, index, modelOverrides[index])),
3470
- contextForAgent: contextPolicy.contextForAgent,
3471
- maxSubagentDepth: currentMaxSubagentDepth,
3472
- waitToolEnabled: deps.waitToolEnabled,
3473
- worktreeSetupHook: deps.config.worktreeSetupHook,
3474
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
3475
- worktreeBaseDir: deps.config.worktreeBaseDir,
3476
- controlConfig,
3477
- agentContract: params.agentContract,
3478
- controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
3479
- childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
3480
- nestedRoute: data.nestedRoute,
3481
- timeoutMs: data.timeoutMs,
3482
- turnBudget: data.turnBudget,
3483
- usageBudget: data.usageBudget,
3484
- toolBudget: data.toolBudget,
3485
- configToolBudget: data.configToolBudget,
3486
- globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
3487
- }));
3862
+ try {
3863
+ return executeAsyncChain(id, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
3864
+ chain: [compactOptional<ParallelStep>({ parallel: parallelTasks, concurrency: parallelConcurrency, worktree: params.worktree })],
3865
+ resultMode: "parallel",
3866
+ goal: taskTexts[0] ?? "",
3867
+ agents,
3868
+ ctx: asyncCtx,
3869
+ availableModels,
3870
+ cwd: effectiveCwd,
3871
+ maxOutput: params.maxOutput,
3872
+ artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3873
+ artifactConfig,
3874
+ shareEnabled,
3875
+ sessionRoot,
3876
+ chainSkills: [],
3877
+ activeAsyncCapacity: capacity.activeAsyncCapacity,
3878
+ sessionFilesByFlatIndex: tasks.map((task, index) => sessionFileForTask(task.agent, index, modelOverrides[index])),
3879
+ thinkingOverridesByFlatIndex: tasks.map((task, index) => thinkingOverrideForTask(task.agent, index, modelOverrides[index])),
3880
+ contextForAgent: contextPolicy.contextForAgent,
3881
+ maxSubagentDepth: currentMaxSubagentDepth,
3882
+ waitToolEnabled: deps.waitToolEnabled,
3883
+ worktreeSetupHook: deps.config.worktreeSetupHook,
3884
+ worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
3885
+ worktreeBaseDir: deps.config.worktreeBaseDir,
3886
+ controlConfig,
3887
+ agentContract: params.agentContract,
3888
+ controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
3889
+ childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
3890
+ nestedRoute: data.nestedRoute,
3891
+ timeoutMs: data.timeoutMs,
3892
+ turnBudget: data.turnBudget,
3893
+ usageBudget: data.usageBudget,
3894
+ toolBudget: data.toolBudget,
3895
+ configToolBudget: data.configToolBudget,
3896
+ callToolTimeoutMs: data.params?.toolTimeoutMs,
3897
+ configToolTimeoutMs: data.configToolTimeoutMs,
3898
+ globalConcurrencyLimit: deps.config.globalConcurrencyLimit,
3899
+ runFanoutBudget: data.runFanoutBudget,
3900
+ }));
3901
+ } finally {
3902
+ finalizeClarifiedBackgroundCapacity(data, deps, capacity.activeAsyncCapacity);
3903
+ }
3488
3904
  }
3489
3905
  }
3490
3906
 
@@ -3563,6 +3979,7 @@ async function runParallelPath(data: ExecutionContextData, deps: ExecutorDeps):
3563
3979
  intercomEvents: deps.pi.events,
3564
3980
  parentSessionId: data.parentSessionId,
3565
3981
  capabilityCeiling: data.capabilityCeiling,
3982
+ runFanoutBudget: data.runFanoutBudget,
3566
3983
  signal,
3567
3984
  runId,
3568
3985
  sessionDirForIndex,
@@ -3598,6 +4015,8 @@ async function runParallelPath(data: ExecutionContextData, deps: ExecutorDeps):
3598
4015
  worktreeSetup,
3599
4016
  timeoutMs: data.timeoutMs,
3600
4017
  deadlineAt,
4018
+ toolTimeoutMs: data.params?.toolTimeoutMs,
4019
+ configToolTimeoutMs: data.configToolTimeoutMs,
3601
4020
  turnBudget: data.turnBudget,
3602
4021
  usageBudget: data.usageBudget,
3603
4022
  toolBudgets,
@@ -3797,7 +4216,9 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3797
4216
  details: { mode: "single" as const, results: [] },
3798
4217
  };
3799
4218
  }
3800
- const id = randomUUID();
4219
+ const id = data.asyncRunId;
4220
+ const capacity = acquireClarifiedBackgroundCapacity(data, deps, "single", id);
4221
+ if (capacity.errorResult) return capacity.errorResult;
3801
4222
  const asyncCtx = compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
3802
4223
  pi: deps.pi,
3803
4224
  cwd: ctx.cwd,
@@ -3809,49 +4230,58 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3809
4230
  interactive: ctx.hasUI,
3810
4231
  permissions: deps.config.permissions,
3811
4232
  });
3812
- return executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
3813
- agent: params.agent!,
3814
- task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(task) : task,
3815
- goal: task,
3816
- agentConfig,
3817
- ctx: asyncCtx,
3818
- availableModels,
3819
- cwd: effectiveCwd,
3820
- maxOutput: params.maxOutput,
3821
- artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
3822
- artifactConfig,
3823
- shareEnabled,
3824
- sessionRoot,
3825
- sessionFile: sessionFileForTask(params.agent!, 0, modelOverride),
3826
- context: contextPolicy.contextForAgent(params.agent!),
3827
- skills: skillOverride === false ? [] : skillOverride,
3828
- output: effectiveOutput,
3829
- outputMode: effectiveOutputMode,
3830
- ...(readsOverride !== undefined ? { reads: readsOverride } : {}),
3831
- outputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),
3832
- modelOverride,
3833
- thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride),
3834
- maxSubagentDepth,
3835
- waitToolEnabled: deps.waitToolEnabled,
3836
- worktreeSetupHook: deps.config.worktreeSetupHook,
3837
- worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
3838
- worktreeBaseDir: deps.config.worktreeBaseDir,
3839
- controlConfig,
3840
- controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
3841
- childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
3842
- nestedRoute: data.nestedRoute,
3843
- agentContract: params.agentContract,
3844
- structuredOutputSchema: params.outputSchema,
3845
- acceptance: params.acceptance,
3846
- timeoutMs: data.timeoutMs,
3847
- turnBudget: data.turnBudget,
3848
- toolBudget: effectiveToolBudget.toolBudget,
3849
- usageBudget: data.usageBudget,
3850
- allowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,
3851
- }));
4233
+ try {
4234
+ return executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
4235
+ agent: params.agent!,
4236
+ task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(task) : task,
4237
+ goal: task,
4238
+ agentConfig,
4239
+ recoveryAgentConfig: data.recoveryAgents.find((agent) => agent.name === params.agent),
4240
+ ctx: asyncCtx,
4241
+ availableModels,
4242
+ cwd: effectiveCwd,
4243
+ maxOutput: params.maxOutput,
4244
+ artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
4245
+ artifactConfig,
4246
+ shareEnabled,
4247
+ activeAsyncCapacity: capacity.activeAsyncCapacity,
4248
+ sessionRoot,
4249
+ sessionFile: sessionFileForTask(params.agent!, 0, modelOverride),
4250
+ context: contextPolicy.contextForAgent(params.agent!),
4251
+ skills: skillOverride === false ? [] : skillOverride,
4252
+ output: effectiveOutput,
4253
+ outputMode: effectiveOutputMode,
4254
+ ...(readsOverride !== undefined ? { reads: readsOverride } : {}),
4255
+ outputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),
4256
+ modelOverride,
4257
+ thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride),
4258
+ maxSubagentDepth,
4259
+ waitToolEnabled: deps.waitToolEnabled,
4260
+ worktreeSetupHook: deps.config.worktreeSetupHook,
4261
+ worktreeSetupHookTimeoutMs: deps.config.worktreeSetupHookTimeoutMs,
4262
+ worktreeBaseDir: deps.config.worktreeBaseDir,
4263
+ controlConfig,
4264
+ intercomBridge: params.intercomBridge,
4265
+ controlIntercomTarget: data.intercomBridge.active ? data.intercomBridge.orchestratorTarget : undefined,
4266
+ childIntercomTarget: data.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(id, agent, index) : undefined,
4267
+ nestedRoute: data.nestedRoute,
4268
+ agentContract: params.agentContract,
4269
+ structuredOutputSchema: params.outputSchema,
4270
+ acceptance: params.acceptance,
4271
+ timeoutMs: data.timeoutMs,
4272
+ turnBudget: data.turnBudget,
4273
+ toolBudget: effectiveToolBudget.toolBudget,
4274
+ usageBudget: data.usageBudget,
4275
+ allowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,
4276
+ runFanoutBudget: data.runFanoutBudget,
4277
+ }));
4278
+ } finally {
4279
+ finalizeClarifiedBackgroundCapacity(data, deps, capacity.activeAsyncCapacity);
4280
+ }
3852
4281
  }
3853
4282
  }
3854
4283
 
4284
+ const authoredTask = task;
3855
4285
  if (shouldForkAgent(contextPolicy, params.agent!)) {
3856
4286
  task = wrapForkTask(task);
3857
4287
  }
@@ -3888,6 +4318,11 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3888
4318
  beginForegroundChild(foregroundControl, omitUndefinedProperties({
3889
4319
  index: 0,
3890
4320
  agent: params.agent!,
4321
+ authoredTask,
4322
+ effectivePrompt: task,
4323
+ cwd: effectiveCwd,
4324
+ outputPath,
4325
+ rerun: { params: { ...params, task: authoredTask, async: params.async ?? false } },
3891
4326
  description: foregroundControl.description,
3892
4327
  ...(modelOverride ? { model: modelOverride } : {}),
3893
4328
  ...(thinking ? { thinking } : {}),
@@ -3913,8 +4348,10 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3913
4348
  r = await runSync(ctx.cwd, agents, params.agent!, task, compactOptional<Parameters<typeof runSync>[4]>({
3914
4349
  permissions: deps.config.permissions,
3915
4350
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
4351
+ llmIntentArbiter: createTaskMutationArbiter(ctx),
3916
4352
  ...workflowForegroundSteeringLaunchOptions(foregroundControl, 0),
3917
4353
  context: data.contextPolicy.contextForAgent(params.agent!),
4354
+ runFanoutBudget: params.runFanoutAdmitted ? data.runFanoutBudget : { ...data.runFanoutBudget, parentPath: `${data.runFanoutBudget.parentPath ? `${data.runFanoutBudget.parentPath}/` : ""}single` },
3918
4355
  cwd: effectiveCwd,
3919
4356
  signal,
3920
4357
  interruptSignal: interruptController.signal,
@@ -3948,6 +4385,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3948
4385
  agentContract: params.agentContract,
3949
4386
  acceptance: params.acceptance,
3950
4387
  acceptanceContext: { mode: "single" },
4388
+ onEffectivePrompt: foregroundControl ? (prompt) => updateLiveEffectivePrompt(foregroundControl, 0, prompt) : undefined,
3951
4389
  onDetachReady: (detach) => {
3952
4390
  detachForeground = detach;
3953
4391
  },
@@ -3973,6 +4411,8 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3973
4411
  },
3974
4412
  timeoutMs: data.timeoutMs,
3975
4413
  deadlineAt,
4414
+ toolTimeoutMs: params.toolTimeoutMs,
4415
+ configToolTimeoutMs: data.configToolTimeoutMs,
3976
4416
  turnBudget: data.turnBudget,
3977
4417
  enforceHardTurnLimit: params.enforceHardTurnLimit,
3978
4418
  toolBudget: effectiveToolBudget.toolBudget,
@@ -3996,12 +4436,14 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3996
4436
  if (r.artifactPaths) allArtifactPaths.push(r.artifactPaths);
3997
4437
 
3998
4438
  const fullOutput = getSingleResultOutput(r);
4439
+ const preserveRejectedSavedOutput = r.acceptance?.explicit && r.acceptance.status === "rejected" && r.savedOutputPath !== undefined;
3999
4440
  const finalizedOutput = finalizeSingleOutput(omitUndefinedProperties({
4000
4441
  fullOutput,
4001
4442
  truncatedOutput: r.truncation?.text,
4002
4443
  outputPath,
4003
4444
  outputMode: r.outputMode,
4004
4445
  exitCode: r.exitCode,
4446
+ preserveSavedOutput: preserveRejectedSavedOutput,
4005
4447
  savedPath: r.savedOutputPath,
4006
4448
  outputReference: r.outputReference,
4007
4449
  saveError: r.outputSaveError,
@@ -4049,8 +4491,15 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4049
4491
  }
4050
4492
 
4051
4493
  if (r.detached) {
4494
+ const statusRecovery = `subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
4495
+ const blockingRecovery = `subagent_wait({ id: "${runId}" }). Use ${statusRecovery}`;
4496
+ const message = r.detachedReason === "intercom coordination"
4497
+ ? `Detached for intercom coordination: ${params.agent}. Reply to the supervisor request first, then wait with ${blockingRecovery}`
4498
+ : r.detachedReason === "user request"
4499
+ ? `Detached at user request: ${params.agent}. The child continues independently. Register a completion wake-up with subagent_wait({ id: "${runId}", nonBlocking: true }), or use ${statusRecovery}`
4500
+ : `Detached before task completion: ${params.agent}. Wait with ${blockingRecovery}`;
4052
4501
  return {
4053
- content: [{ type: "text", text: `Detached for intercom coordination: ${params.agent}. Reply to the supervisor request first, then wait with subagent_wait({ id: "${runId}" }). Use subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.` }],
4502
+ content: [{ type: "text", text: message }],
4054
4503
  details,
4055
4504
  };
4056
4505
  }
@@ -4092,7 +4541,13 @@ function duplicateSubagentCallResult(params: SubagentParamsLike): AgentToolResul
4092
4541
  };
4093
4542
  }
4094
4543
 
4095
- const workflowLaunchObservers = new WeakMap<object, (launch: { agent: string; sessionFile?: string }) => void>();
4544
+ const workflowLaunchObservers = new WeakMap<object, (launch: { agent: string; sessionFile?: string; async: boolean; runId?: string }) => void>();
4545
+
4546
+ /**
4547
+ * Terminal-mission retention can remove a mission while its children still
4548
+ * report. Remember it to prevent later heartbeats from warning repeatedly.
4549
+ */
4550
+ const missionsMissingFromStore = new Set<string>();
4096
4551
 
4097
4552
  function recordMissionWorkflowChild(
4098
4553
  binding: MissionLaunchBinding | undefined,
@@ -4100,10 +4555,16 @@ function recordMissionWorkflowChild(
4100
4555
  key: string,
4101
4556
  update: Omit<MissionWorkflowChildUpdate, "workflowRunId" | "key">,
4102
4557
  ): void {
4103
- if (!binding) return;
4558
+ if (!binding || missionsMissingFromStore.has(binding.missionId)) return;
4559
+ const { task: _task, ...durableUpdate } = update;
4104
4560
  try {
4105
- updateMission(binding.location, binding.missionId, { upsertWorkflowChildren: [{ workflowRunId, key, ...update }] });
4561
+ updateMission(binding.location, binding.missionId, { upsertWorkflowChildren: [{ workflowRunId, key, ...durableUpdate }] });
4106
4562
  } catch (error) {
4563
+ if (error instanceof MissionNotFoundError) {
4564
+ missionsMissingFromStore.add(binding.missionId);
4565
+ console.warn(`[pi-subagents] Mission '${binding.missionId}' is no longer in the mission store; stopped recording its workflow children. Terminal-mission retention can prune a mission while its run is still active.`);
4566
+ return;
4567
+ }
4107
4568
  console.warn(`[pi-subagents] Failed to record mission workflow child '${key}': ${error instanceof Error ? error.message : String(error)}`);
4108
4569
  }
4109
4570
  }
@@ -4173,6 +4634,7 @@ function workflowChildResult(key: string, result: AgentToolResult<Details>): Wor
4173
4634
  ...(result.details.runId || result.details.asyncId ? { runId: result.details.runId ?? result.details.asyncId } : {}),
4174
4635
  output,
4175
4636
  ...(!ok ? { error: receiptOutput || output || "Child run failed." } : {}),
4637
+ ...(detached ? { detached: true } : {}),
4176
4638
  ...(structured.length === 1 ? { structuredOutput: structured[0] } : structured.length > 1 ? { structuredOutput: structured } : {}),
4177
4639
  artifactPaths: [...artifactPaths],
4178
4640
  results: result.details.results,
@@ -4184,7 +4646,7 @@ export function prepareWorkflowLaunchParams(
4184
4646
  childParams: Record<string, unknown>,
4185
4647
  parentWorkflowRunId: string,
4186
4648
  workflowKey: string,
4187
- options: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean } = {},
4649
+ options: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor } = {},
4188
4650
  ): SubagentParamsLike {
4189
4651
  if (typeof childParams.resume === "string") {
4190
4652
  if (childParams.gate !== undefined || workflowDefaults.gate !== undefined) {
@@ -4193,16 +4655,19 @@ export function prepareWorkflowLaunchParams(
4193
4655
  const timeoutMs = childParams.timeoutMs ?? childParams.maxRuntimeMs ?? workflowDefaults.timeoutMs ?? workflowDefaults.maxRuntimeMs;
4194
4656
  const turnBudget = childParams.turnBudget ?? workflowDefaults.turnBudget;
4195
4657
  const toolBudget = childParams.toolBudget ?? workflowDefaults.toolBudget;
4658
+ const intercomBridge = childParams.intercomBridge ?? workflowDefaults.intercomBridge;
4196
4659
  return {
4197
4660
  action: "resume",
4198
4661
  id: childParams.resume.trim(),
4199
4662
  message: typeof childParams.task === "string" ? childParams.task.trim() : "",
4200
4663
  workflowParentRunId: parentWorkflowRunId,
4201
4664
  workflowKey,
4665
+ ...(options.runFanoutBudget ? { runFanoutBudget: { ...options.runFanoutBudget, parentPath: `${options.runFanoutBudget.parentPath ? `${options.runFanoutBudget.parentPath}/` : ""}workflow[${workflowKey}]` } } : {}),
4202
4666
  ...(options.missionDetached ? { mission: false } : {}),
4203
4667
  ...(timeoutMs !== undefined ? { timeoutMs: timeoutMs as number } : {}),
4204
4668
  ...(turnBudget !== undefined ? { turnBudget: turnBudget as TurnBudgetConfig } : {}),
4205
4669
  ...(toolBudget !== undefined ? { toolBudget: toolBudget as ToolBudgetConfig } : {}),
4670
+ ...(intercomBridge !== undefined ? { intercomBridge: intercomBridge as IntercomBridgeConfig } : {}),
4206
4671
  };
4207
4672
  }
4208
4673
  const launchParams = {
@@ -4212,6 +4677,7 @@ export function prepareWorkflowLaunchParams(
4212
4677
  ...(options.missionDetached ? { mission: false } : {}),
4213
4678
  workflowParentRunId: parentWorkflowRunId,
4214
4679
  workflowKey,
4680
+ ...(options.runFanoutBudget ? { runFanoutBudget: { ...options.runFanoutBudget, parentPath: `${options.runFanoutBudget.parentPath ? `${options.runFanoutBudget.parentPath}/` : ""}workflow[${workflowKey}]` } } : {}),
4215
4681
  ...(options.suppressRoutineResultIntercom ? { suppressRoutineResultIntercom: true } : {}),
4216
4682
  } as SubagentParamsLike;
4217
4683
  const normalizedGate = normalizeGateParams(launchParams);
@@ -4359,6 +4825,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4359
4825
  } {
4360
4826
  const delegatedThinkingOverrides = new WeakMap<object, AgentConfig["thinking"]>();
4361
4827
  const delegatedZeroToolBudgets = new WeakSet<object>();
4828
+ const delegatedExecutions = new WeakSet<object>();
4362
4829
  const warnedArtifactPackageDirs = new Set<string>();
4363
4830
  const scheduledOwnerExecutors = new Map<string, ReturnType<typeof createSubagentExecutor>>();
4364
4831
  const execute = async (
@@ -4372,6 +4839,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4372
4839
  const workflowLaunchObserver = workflowLaunchObservers.get(params);
4373
4840
  const delegatedThinkingOverride = delegatedThinkingOverrides.get(params);
4374
4841
  const allowZeroToolBudget = delegatedZeroToolBudgets.has(params);
4842
+ const delegatedExecution = delegatedExecutions.has(params);
4375
4843
  if (!preserveActiveSession) deps.state.baseCwd = ctx.cwd;
4376
4844
  deps.state.foregroundRuns ??= new Map();
4377
4845
  deps.state.foregroundControls ??= new Map();
@@ -4382,10 +4850,21 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4382
4850
  const normalizedAction = typeof requestParams.action === "string" ? requestParams.action.trim() : requestParams.action;
4383
4851
  if (requestParams.workflowScript !== undefined && normalizedAction === undefined) {
4384
4852
  const parentCwd = ctx.cwd;
4385
- const timeout = requestParams.timeoutMs ?? requestParams.maxRuntimeMs ?? (requestParams.async === false ? DEFAULT_FOREGROUND_TIMEOUT_MS : undefined);
4853
+ const timeout = requestParams.timeoutMs ?? requestParams.maxRuntimeMs ?? (requestParams.async === false ? resolveConfigDefaultTimeoutMs(deps.config.timeoutMs) ?? DEFAULT_FOREGROUND_TIMEOUT_MS : undefined);
4386
4854
  const workflowUsageBudget = validateUsageBudgetConfig(requestParams.usageBudget ?? deps.config.usageBudget, requestParams.usageBudget ? "usageBudget" : "config.usageBudget");
4387
4855
  if (workflowUsageBudget.error) return buildRequestedModeError(requestParams, workflowUsageBudget.error);
4388
4856
  const workflowCwd = resolveRequestedCwd(parentCwd, requestParams.cwd);
4857
+ const workflowArtifactConfig: ArtifactConfig = omitUndefinedProperties({
4858
+ ...DEFAULT_ARTIFACT_CONFIG,
4859
+ enabled: requestParams.artifacts !== false,
4860
+ dir: deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir,
4861
+ });
4862
+ const workflowArtifactsDir = getArtifactsDir(ctx.sessionManager.getSessionFile() ?? null, workflowCwd, workflowArtifactConfig.dir);
4863
+ if (workflowArtifactConfig.dir === "project" && !warnedArtifactPackageDirs.has(workflowCwd)) {
4864
+ warnedArtifactPackageDirs.add(workflowCwd);
4865
+ const warning = getProjectArtifactPackagingWarning(workflowCwd);
4866
+ if (warning) console.warn(`[pi-subagents] ${warning}`);
4867
+ }
4389
4868
  const workflowPrompts = { render: (ref: string, vars?: unknown) => renderWorkflowPrompt(ref, vars, workflowCwd) };
4390
4869
  const chatProgressResult = resolveWorkflowChatProgress({ requested: requestParams.chatProgress, parentCwd, workflowCwd, background: requestParams.async !== false });
4391
4870
  if (chatProgressResult.error) return { content: [{ type: "text", text: chatProgressResult.error }], isError: true, details: { mode: "workflow", results: [] } };
@@ -4393,11 +4872,45 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4393
4872
  const explicitMission = requestParams.missionId !== undefined || requestParams.mission !== undefined;
4394
4873
  const autoMission = !explicitMission;
4395
4874
  const workflowPreview = autoMission ? previewSimpleWorkflowRun(requestParams.workflowScript) : undefined;
4396
- const previewTask = workflowPreview?.task?.trim() || undefined;
4397
4875
  const previewAgent = workflowPreview?.agent?.trim() || undefined;
4398
4876
  const scriptFirstLine = requestParams.workflowScript.split(/\r?\n/).map((line) => line.trim()).find(Boolean) || "Workflow";
4399
4877
  const boundedScriptPreview = scriptFirstLine.length > 100 ? `${scriptFirstLine.slice(0, 97)}...` : scriptFirstLine;
4400
- const derivedObjective = previewTask || (previewAgent ? `Workflow: ${previewAgent}` : boundedScriptPreview);
4878
+ const derivedObjective = previewAgent ? `Workflow: ${previewAgent}` : boundedScriptPreview;
4879
+ const workflowDepth = checkSubagentDepth(deps.config.maxSubagentDepth).depth;
4880
+ const asyncWorkflow = requestParams.async !== false;
4881
+ const topLevelAsyncWorkflow = asyncWorkflow
4882
+ && workflowDepth === 0
4883
+ && !resolveInheritedNestedRouteFromEnv()
4884
+ && !requestParams.workflowParentRunId;
4885
+ const workflowRunId = asyncWorkflow ? randomUUID() : undefined;
4886
+ let workflowCapacity: ActiveAsyncCapacityHandle | undefined;
4887
+ if (workflowRunId && topLevelAsyncWorkflow) {
4888
+ const currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
4889
+ try {
4890
+ workflowCapacity = acquireActiveAsyncCapacity({
4891
+ sessionId: currentSessionId,
4892
+ limit: resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession),
4893
+ runId: workflowRunId,
4894
+ kind: "workflow",
4895
+ asyncDir: path.join(DIRS.async, workflowRunId),
4896
+ }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) });
4897
+ } catch (error) {
4898
+ if (error instanceof ActiveAsyncCapacityError) {
4899
+ deps.state.activeAsyncCapacity = error.snapshot;
4900
+ return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "workflow", results: [], activeAsyncCapacity: error.snapshot } };
4901
+ }
4902
+ throw error;
4903
+ }
4904
+ }
4905
+ let workflowFanoutBudget: RunFanoutBudgetDescriptor;
4906
+ try {
4907
+ workflowFanoutBudget = requestParams.runFanoutBudget
4908
+ ?? decodeRunFanoutBudgetDescriptor(process.env[RUN_FANOUT_BUDGET_ENV])
4909
+ ?? createRunFanoutBudget(_id, resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun));
4910
+ } catch (error) {
4911
+ workflowCapacity?.rollback();
4912
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "workflow", results: [] } };
4913
+ }
4401
4914
  let missionBinding: MissionLaunchBinding | undefined;
4402
4915
  let missionWarning: string | undefined;
4403
4916
  try {
@@ -4408,22 +4921,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4408
4921
  ownerSessionId: resolveCurrentSessionId(ctx.sessionManager),
4409
4922
  });
4410
4923
  } catch (error) {
4411
- if (explicitMission) return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "workflow", results: [] } };
4924
+ if (explicitMission) {
4925
+ workflowCapacity?.rollback();
4926
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "workflow", results: [] } };
4927
+ }
4412
4928
  missionWarning = `Mission tracking unavailable: ${error instanceof Error ? error.message : String(error)}`;
4413
4929
  }
4414
- let shouldPatchMissionObjective = autoMission && previewTask === undefined && missionBinding !== undefined;
4415
- const patchMissionObjective = (task: unknown): void => {
4416
- if (!shouldPatchMissionObjective || !missionBinding || typeof task !== "string" || !task.trim()) return;
4417
- shouldPatchMissionObjective = false;
4418
- const objective = task.trim();
4419
- const firstLine = objective.split(/\r?\n/, 1)[0]?.trim() || objective;
4420
- const title = firstLine.length > 100 ? `${firstLine.slice(0, 97)}...` : firstLine;
4421
- try {
4422
- updateMission(missionBinding.location, missionBinding.missionId, { title, objective });
4423
- } catch (error) {
4424
- console.warn(`[pi-subagents] Failed to update automatic mission objective: ${error instanceof Error ? error.message : String(error)}`);
4425
- }
4426
- };
4427
4930
  const detachWorkflowChildMissions = autoMission || missionBinding !== undefined || requestParams.mission === false;
4428
4931
  const workflowState = missionBinding ? createMissionWorkflowState(missionBinding.location, missionBinding.missionId) : undefined;
4429
4932
  const attachWorkflowMission = (result: AgentToolResult<Details>): AgentToolResult<Details> => {
@@ -4437,20 +4940,27 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4437
4940
  : { ...result, details: { ...result.details, missionWarning: warning } };
4438
4941
  }
4439
4942
  };
4440
- if (requestParams.async !== false) {
4943
+ if (workflowRunId) {
4441
4944
  const toolCallId = _id;
4442
- const workflowRunId = randomUUID();
4443
4945
  const asyncDir = path.join(DIRS.async, workflowRunId);
4444
- const resultPath = path.join(DIRS.results, `${workflowRunId}.json`);
4946
+ const resultPath = resultFilePath(DIRS.results, workflowRunId);
4445
4947
  const statusPath = path.join(asyncDir, "status.json");
4446
4948
  const eventsPath = path.join(asyncDir, "events.jsonl");
4447
4949
  const startedAt = Date.now();
4448
4950
  const currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
4449
- fs.mkdirSync(asyncDir, { recursive: true });
4450
- fs.mkdirSync(DIRS.results, { recursive: true });
4951
+ try {
4952
+ fs.mkdirSync(asyncDir, { recursive: true });
4953
+ writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
4954
+ fs.mkdirSync(DIRS.results, { recursive: true });
4955
+ } catch (error) {
4956
+ workflowCapacity?.rollback();
4957
+ return { content: [{ type: "text", text: `Failed to create async workflow storage: ${error instanceof Error ? error.message : String(error)}` }], isError: true, details: { mode: "workflow", results: [] } };
4958
+ }
4451
4959
  const controller = new AbortController();
4452
4960
  deps.state.workflowControllers ??= new Map();
4453
4961
  deps.state.workflowControllers.set(workflowRunId, controller);
4962
+ workflowCapacity?.markWorkflowStarted();
4963
+ if (workflowCapacity) deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers.keys()) });
4454
4964
  let status: AsyncStatus = {
4455
4965
  runId: workflowRunId,
4456
4966
  toolCallId,
@@ -4464,6 +4974,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4464
4974
  pid: process.pid,
4465
4975
  steps: [],
4466
4976
  workflow: { trace: [], emits: [], console: [] },
4977
+ runFanoutBudget: getRunFanoutBudgetSnapshot(workflowFanoutBudget),
4467
4978
  };
4468
4979
  const appendWorkflowEvent = (event: Record<string, unknown>) => fs.appendFileSync(eventsPath, `${JSON.stringify({ ts: Date.now(), runId: workflowRunId, ...event })}\n`, "utf-8");
4469
4980
  let indexedState: AsyncStatus["state"] | undefined;
@@ -4471,7 +4982,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4471
4982
  status.lastUpdate = Date.now();
4472
4983
  writeAtomicJson(statusPath, status);
4473
4984
  if (indexedState !== status.state) {
4474
- updateActiveRunIndex(asyncDir, status.state);
4985
+ updateActiveRunIndex(asyncDir, status.state, status.toolCallId);
4475
4986
  indexedState = status.state;
4476
4987
  }
4477
4988
  const job = deps.state.asyncJobs.get(workflowRunId);
@@ -4496,6 +5007,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4496
5007
  job.workflow = status.workflow;
4497
5008
  }
4498
5009
  };
5010
+ const writeWorkflowResult = (payload: Record<string, unknown>): boolean => {
5011
+ try {
5012
+ writeAsyncResultFile(resultPath, payload);
5013
+ return true;
5014
+ } catch (error) {
5015
+ const message = `Failed to write async workflow result ${resultPath}: ${error instanceof Error ? error.message : String(error)}`;
5016
+ console.error(message, error);
5017
+ appendWorkflowEvent({ type: "subagent.workflow.result_write_failed", error: message });
5018
+ return false;
5019
+ }
5020
+ };
4499
5021
  const projectWorkflowActivity = () => {
4500
5022
  const steps = status.steps ?? [];
4501
5023
  const runningSteps = steps.filter((step) => step.status === "running");
@@ -4517,7 +5039,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4517
5039
  status.toolCount = toolCounts.length > 0 ? toolCounts.reduce((total, count) => total + count, 0) : undefined;
4518
5040
  status.currentStep = runningSteps.length === 1 ? steps.indexOf(runningSteps[0]!) : undefined;
4519
5041
  };
4520
- 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 };
5042
+ const workflowJob: AsyncJobState = { asyncId: workflowRunId, asyncDir, toolCallId, cwd: workflowCwd, status: "running", sessionId: currentSessionId ?? undefined, mode: "workflow", agents: [], steps: [], startedAt, updatedAt: startedAt, ...(timeout !== undefined ? { timeoutMs: timeout, deadlineAt: startedAt + timeout } : {}), workflow: status.workflow };
4521
5043
  deps.state.asyncJobs.set(workflowRunId, workflowJob);
4522
5044
  deps.state.fleetJobs ??= new Map();
4523
5045
  deps.state.fleetJobs.set(workflowRunId, workflowJob);
@@ -4527,6 +5049,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4527
5049
  void Promise.resolve().then(async () => {
4528
5050
  const workflowResults: SingleResult[] = [];
4529
5051
  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;
5052
+ const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
5053
+ const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
5054
+ const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId), configuredOutputBaseDir);
5055
+ const claimedOutputPaths = new Map<string, string>();
4530
5056
  const workflowSteps = new Map<string, NonNullable<AsyncStatus["steps"]>[number]>();
4531
5057
  let projectedTraceLength = 0;
4532
5058
  let projectedTraceTail: NonNullable<Details["workflow"]>["trace"][number] | undefined;
@@ -4546,16 +5072,41 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4546
5072
  if (entry.operation !== "run") continue;
4547
5073
  const existing = workflowSteps.get(entry.key);
4548
5074
  if (entry.state === "reused" && existing) continue;
4549
- const mapped = entry.state === "started" || entry.state === "reused" ? "running" : entry.state === "completed" ? "completed" : "failed";
5075
+ const mapped = entry.state === "started" || entry.state === "reused"
5076
+ ? "running"
5077
+ : entry.state === "completed"
5078
+ ? "completed"
5079
+ : entry.state === "stopped"
5080
+ ? "stopped"
5081
+ : entry.state === "detached"
5082
+ ? "paused"
5083
+ : "failed";
4550
5084
  if (existing) {
4551
5085
  existing.status = mapped;
4552
5086
  if (entry.agent) existing.agent = entry.agent;
5087
+ if (entry.runId) existing.runId = entry.runId;
5088
+ if (entry.state === "failed" && !entry.runId && existing.async === undefined) existing.async = false;
5089
+ if (entry.state === "detached") existing.activityState = "needs_attention";
5090
+ else if (existing.status !== "running") delete existing.activityState;
5091
+ if (entry.state === "stopped") existing.stopped = true;
5092
+ else delete existing.stopped;
4553
5093
  if (entry.error === undefined) delete existing.error;
4554
5094
  else existing.error = entry.error;
4555
5095
  if (entry.durationMs === undefined) delete existing.durationMs;
4556
5096
  else existing.durationMs = entry.durationMs;
4557
5097
  } else {
4558
- const step: NonNullable<AsyncStatus["steps"]>[number] = { agent: entry.agent ?? entry.key, label: entry.key, workflowKey: entry.key, parentWorkflowRunId: workflowRunId, status: mapped, startedAt: Date.now() };
5098
+ const step: NonNullable<AsyncStatus["steps"]>[number] = {
5099
+ agent: entry.agent ?? entry.key,
5100
+ label: entry.key,
5101
+ workflowKey: entry.key,
5102
+ parentWorkflowRunId: workflowRunId,
5103
+ status: mapped,
5104
+ startedAt: Date.now(),
5105
+ ...(entry.runId ? { runId: entry.runId } : {}),
5106
+ ...(entry.state === "failed" && !entry.runId ? { async: false } : {}),
5107
+ ...(entry.state === "detached" ? { activityState: "needs_attention" as const } : {}),
5108
+ ...(entry.state === "stopped" ? { stopped: true } : {}),
5109
+ };
4559
5110
  status.steps?.push(step);
4560
5111
  workflowSteps.set(entry.key, step);
4561
5112
  }
@@ -4574,30 +5125,35 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4574
5125
  prompts: workflowPrompts,
4575
5126
  ...(workflowState ? { state: workflowState } : {}),
4576
5127
  onTrace: updateTrace,
5128
+ admit: (calls) => {
5129
+ const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, claimedOutputPaths, entries: calls });
5130
+ if (outputClaims.error) throw new Error(outputClaims.error);
5131
+ status.runFanoutBudget = claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
5132
+ if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
5133
+ persist();
5134
+ },
4577
5135
  onEmit: (emits) => {
4578
5136
  // Each emit is validated at the host boundary in runWorkflowScript before onEmit fires.
4579
5137
  status.workflow = { ...(status.workflow ?? { trace: [], console: [] }), emits };
4580
5138
  persist();
4581
5139
  appendWorkflowEvent({ type: "subagent.workflow.emit", value: emits.at(-1) });
4582
5140
  },
4583
- launch: async (key, childParams, workflowSignal) => {
5141
+ launch: async (key, childParams, workflowSignal, admission) => {
4584
5142
  if (workflowUsageBudget.budget && childParams.async === true) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, "workflow usageBudget does not support async runs.run launches."));
4585
5143
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
4586
5144
  if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)));
4587
- patchMissionObjective(childParams.task);
4588
5145
  const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
4589
5146
  const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
4590
5147
  recordMissionWorkflowChild(missionBinding, workflowRunId, key, {
4591
5148
  status: "running",
4592
5149
  ...(typeof childParams.agent === "string" && childParams.agent.trim() ? { agent: childParams.agent.trim() } : {}),
4593
- ...(typeof childParams.task === "string" && childParams.task.trim() ? { task: childParams.task.trim() } : {}),
4594
5150
  ...(childLabel ? { label: childLabel } : {}),
4595
5151
  ...(childPhase ? { phase: childPhase } : {}),
4596
5152
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
4597
5153
  });
4598
5154
  const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, () => {
4599
5155
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
4600
- prepareWorkflowLaunchParams(workflowChildDefaults, childParams, workflowRunId, key, { missionDetached: detachWorkflowChildMissions }),
5156
+ { ...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 },
4601
5157
  missionBinding,
4602
5158
  deps.asyncByDefault,
4603
5159
  );
@@ -4606,6 +5162,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4606
5162
  if (step) {
4607
5163
  step.agent = launch.agent;
4608
5164
  step.sessionFile = launch.sessionFile;
5165
+ step.async = launch.async;
5166
+ if (launch.runId) step.runId = launch.runId;
4609
5167
  persist();
4610
5168
  }
4611
5169
  recordMissionWorkflowChild(missionBinding, workflowRunId, key, { status: "running", agent: launch.agent, ...(launch.sessionFile ? { sessionPath: launch.sessionFile } : {}) });
@@ -4613,7 +5171,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4613
5171
  return execute(randomUUID(), childRequest, workflowSignal, (update) => {
4614
5172
  const progress = update.details.progress?.[0];
4615
5173
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
4616
- if (!progress || !step) return;
5174
+ if (!progress || !step || step.stopped) return;
4617
5175
  step.status = progress.status === "completed" ? "completed" : progress.status === "failed" ? "failed" : "running";
4618
5176
  step.activityState = progress.activityState;
4619
5177
  step.lastActivityAt = progress.lastActivityAt;
@@ -4637,8 +5195,13 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4637
5195
  }, ctx, preserveActiveSession);
4638
5196
  });
4639
5197
  workflowResults.push(...result.details.results);
4640
- if (result.details.asyncDir && missionBinding) writeMissionAsyncBinding(result.details.asyncDir, missionBinding);
4641
5198
  const child = workflowChildResult(key, result);
5199
+ const step = status.steps?.find((candidate) => candidate.workflowKey === key);
5200
+ if (step) {
5201
+ step.async = Boolean(result.details.asyncId || result.details.asyncDir);
5202
+ if (child.runId) step.runId = child.runId;
5203
+ }
5204
+ if (result.details.asyncDir && missionBinding) writeMissionAsyncBinding(result.details.asyncDir, missionBinding);
4642
5205
  const childStatus = missionWorkflowChildStatus(result);
4643
5206
  recordMissionWorkflowChild(missionBinding, workflowRunId, key, {
4644
5207
  status: childStatus,
@@ -4660,28 +5223,48 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4660
5223
  const returnPreview = formatWorkflowValue(workflow.value).slice(0, 1_000);
4661
5224
  const emitPreview = workflow.emits.length > 0 ? ` Emitted: ${workflow.emits.map(formatWorkflowValue).join(", ").slice(0, 1_000)}` : "";
4662
5225
  const summary = `Workflow completed with ${workflow.children.length} child run(s). Return: ${returnPreview}${emitPreview} Trace: ${workflow.trace.length} event(s).`;
5226
+ const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, summary);
5227
+ const resultSummary = appendWorkflowOutputWarning(summary, outputWarning);
4663
5228
  const workflowUsage = sumResultsUsage(workflowResults);
4664
5229
  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) };
4665
- writeAtomicJson(resultPath, { id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary, output: summary, 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 });
5230
+ if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary: resultSummary, output: resultSummary, results: workflow.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, asyncDir, cwd: workflowCwd, sessionId: currentSessionId, timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
4666
5231
  persist();
4667
- appendWorkflowEvent({ type: "subagent.workflow.completed", state: "complete" });
5232
+ appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(status.error ? { error: status.error } : {}) });
4668
5233
  } catch (error) {
4669
5234
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
4670
5235
  const stopped = controller.signal.aborted;
4671
- 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 } });
4672
- 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) => ({ 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 });
5236
+ const detachedChildKeys = new Set(partial.children.filter((child) => child.detached).map((child) => child.key));
5237
+ const hasRealFailedChild = partial.children.some((child) => !child.ok && !child.detached);
5238
+ const pauseForDetached = !stopped && error instanceof WorkflowScriptError && error.errorKind === "detached-child" && detachedChildKeys.size > 0 && !hasRealFailedChild;
5239
+ const state = stopped ? "stopped" : pauseForDetached ? "paused" : "failed";
5240
+ for (const step of status.steps ?? []) {
5241
+ if (step.workflowKey && detachedChildKeys.has(step.workflowKey)) {
5242
+ step.status = "paused";
5243
+ step.activityState = "needs_attention";
5244
+ }
5245
+ }
5246
+ status = compactOptional<AsyncStatus>({ ...status, state, stopped: stopped || undefined, activityState: pauseForDetached ? "needs_attention" : undefined, error: error instanceof Error ? error.message : String(error), endedAt: Date.now(), workflow: { trace: partial.trace, emits: partial.emits, console: partial.console } });
5247
+ const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, status.error ?? (pauseForDetached ? "Workflow paused." : "Workflow failed."));
5248
+ const resultSummary = appendWorkflowOutputWarning(status.error ?? (pauseForDetached ? "Workflow paused." : "Workflow failed."), outputWarning);
5249
+ if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: false, state: status.state, summary: resultSummary, error: status.error, stopped: status.stopped, activityState: status.activityState, results: partial.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.detached ? { detached: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, asyncDir, cwd: workflowCwd, sessionId: currentSessionId, timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
4673
5250
  persist();
4674
- appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, error: status.error });
5251
+ appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, error: status.error, ...(status.activityState ? { activityState: status.activityState } : {}) });
4675
5252
  } finally {
4676
5253
  deps.state.workflowControllers?.delete(workflowRunId);
5254
+ deps.state.activeAsyncCapacity = workflowCapacity?.reconcile(new Set(deps.state.workflowControllers?.keys() ?? []))
5255
+ ?? deps.state.activeAsyncCapacity;
4677
5256
  }
4678
5257
  });
4679
- return attachWorkflowMission({
5258
+ return attachWorkflowMission(withRunFanoutBudget({
4680
5259
  content: [{ type: "text", text: formatAsyncStartedMessage(`Async workflow [${workflowRunId}]`, ctx.hasUI === true) }],
4681
- details: { mode: "workflow", runId: workflowRunId, toolCallId, asyncId: workflowRunId, asyncDir, results: [], chatProgress },
4682
- });
5260
+ details: { mode: "workflow", runId: workflowRunId, toolCallId, asyncId: workflowRunId, asyncDir, results: [], chatProgress, ...(deps.state.activeAsyncCapacity ? { activeAsyncCapacity: deps.state.activeAsyncCapacity } : {}) },
5261
+ }, workflowFanoutBudget));
4683
5262
  }
4684
5263
  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;
5264
+ const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
5265
+ const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
5266
+ const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, _id), configuredOutputBaseDir);
5267
+ const claimedOutputPaths = new Map<string, string>();
4685
5268
  const workflowResults: SingleResult[] = [];
4686
5269
  let liveWorkflow: NonNullable<Details["workflow"]> = { trace: [], emits: [], console: [] };
4687
5270
  const sendWorkflowProgress = () => {
@@ -4699,28 +5282,32 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4699
5282
  liveWorkflow = { ...liveWorkflow, trace };
4700
5283
  sendWorkflowProgress();
4701
5284
  },
5285
+ admit: (calls) => {
5286
+ const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId: _id, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, claimedOutputPaths, entries: calls });
5287
+ if (outputClaims.error) throw new Error(outputClaims.error);
5288
+ claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
5289
+ if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
5290
+ },
4702
5291
  onEmit: (emits) => {
4703
5292
  liveWorkflow = { ...liveWorkflow, emits };
4704
5293
  sendWorkflowProgress();
4705
5294
  },
4706
- launch: async (key, childParams, workflowSignal) => {
5295
+ launch: async (key, childParams, workflowSignal, admission) => {
4707
5296
  if (workflowUsageBudget.budget && childParams.async === true) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, "workflow usageBudget does not support async runs.run launches."));
4708
5297
  const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
4709
5298
  if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)));
4710
- patchMissionObjective(childParams.task);
4711
5299
  const childPhase = typeof childParams.phase === "string" && childParams.phase.trim() ? childParams.phase.trim() : undefined;
4712
5300
  const childLabel = typeof childParams.label === "string" && childParams.label.trim() ? childParams.label.trim() : undefined;
4713
5301
  recordMissionWorkflowChild(missionBinding, _id, key, {
4714
5302
  status: "running",
4715
5303
  ...(typeof childParams.agent === "string" && childParams.agent.trim() ? { agent: childParams.agent.trim() } : {}),
4716
- ...(typeof childParams.task === "string" && childParams.task.trim() ? { task: childParams.task.trim() } : {}),
4717
5304
  ...(childLabel ? { label: childLabel } : {}),
4718
5305
  ...(childPhase ? { phase: childPhase } : {}),
4719
5306
  heartbeat: { status: "running", ...(childPhase ? { phase: childPhase } : {}) },
4720
5307
  });
4721
5308
  const result = await runMissionWorkflowChild(missionBinding, _id, key, childPhase, () => {
4722
5309
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
4723
- prepareWorkflowLaunchParams(workflowChildDefaults, childParams, _id, key, { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card" }),
5310
+ { ...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 },
4724
5311
  missionBinding,
4725
5312
  deps.asyncByDefault,
4726
5313
  );
@@ -4761,10 +5348,13 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4761
5348
  if (workflow.emits.length > 0) sections.push(`Emitted:\n${workflow.emits.map(formatWorkflowValue).join("\n")}`);
4762
5349
  if (workflow.console.length > 0) sections.push(`Console:\n${workflow.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
4763
5350
  if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
4764
- return attachWorkflowMission({
4765
- content: [{ type: "text", text: sections.join("\n\n") }],
5351
+ const workflowText = sections.join("\n\n");
5352
+ const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText);
5353
+ const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
5354
+ return attachWorkflowMission(withRunFanoutBudget({
5355
+ content: [{ type: "text", text: displayText }],
4766
5356
  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 }),
4767
- });
5357
+ }, workflowFanoutBudget));
4768
5358
  } catch (error) {
4769
5359
  const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
4770
5360
  const text = error instanceof Error ? error.message : String(error);
@@ -4773,11 +5363,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4773
5363
  if (partial.emits.length > 0) sections.push(`Emitted:\n${partial.emits.map(formatWorkflowValue).join("\n")}`);
4774
5364
  if (partial.console.length > 0) sections.push(`Console:\n${partial.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
4775
5365
  if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
4776
- return attachWorkflowMission({
4777
- content: [{ type: "text", text: sections.join("\n\n") }],
5366
+ const workflowText = sections.join("\n\n");
5367
+ const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, workflowText);
5368
+ const displayText = appendWorkflowOutputWarning(workflowText, outputWarning);
5369
+ return attachWorkflowMission(withRunFanoutBudget({
5370
+ content: [{ type: "text", text: displayText }],
4778
5371
  isError: true,
4779
5372
  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 }),
4780
- });
5373
+ }, workflowFanoutBudget));
4781
5374
  }
4782
5375
  }
4783
5376
  const directParams = prepareWorkflowChildParams(requestParams);
@@ -5015,6 +5608,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5015
5608
  if (!sessionError) sessionError = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
5016
5609
  }
5017
5610
  const spawnBudget = getSpawnBudgetSnapshot(deps.state, deps.config, currentSessionId);
5611
+ const activeAsyncCapacity = currentSessionId
5612
+ ? getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) })
5613
+ : { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession) ?? 0 };
5614
+ deps.state.activeAsyncCapacity = activeAsyncCapacity;
5018
5615
  return {
5019
5616
  content: [{
5020
5617
  type: "text",
@@ -5031,14 +5628,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5031
5628
  expandTilde: deps.expandTilde,
5032
5629
  })),
5033
5630
  }],
5034
- details: { mode: "management", results: [], spawnBudget },
5631
+ details: { mode: "management", results: [], spawnBudget, activeAsyncCapacity },
5035
5632
  };
5036
5633
  }
5037
- if (action === "status") {
5634
+ if (action === "status" || action === "debug.run") {
5038
5635
  if (!preserveActiveSession) deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
5039
5636
  const targetRunId = paramsWithResolvedCwd.id ?? paramsWithResolvedCwd.runId;
5040
5637
  const hasDirectoryTarget = Boolean(paramsWithResolvedCwd.dir);
5041
- const targetLabel = formatStatusTargetLabel(paramsWithResolvedCwd, targetRunId);
5638
+ const targetLabel = action === "debug.run" ? "Debug run" : formatStatusTargetLabel(paramsWithResolvedCwd, targetRunId);
5042
5639
  const withBudget = (result: AgentToolResult<Details>) => {
5043
5640
  const budgeted = withSpawnBudgetStatus(result, deps.state, deps.config, deps.state.currentSessionId);
5044
5641
  return {
@@ -5050,6 +5647,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5050
5647
  };
5051
5648
  const nestedScope = nestedResolutionScopeForExecutor(deps);
5052
5649
  const sessionRoots = trustedSessionRootsForStatus(ctx, deps);
5650
+ if (action === "debug.run") {
5651
+ if (!targetRunId && !hasDirectoryTarget) {
5652
+ return withBudget({ content: [{ type: "text", text: "action='debug.run' requires id, runId, or dir." }], isError: true, details: { mode: "management", results: [] } });
5653
+ }
5654
+ if (paramsWithResolvedCwd.view) {
5655
+ return withBudget({ content: [{ type: "text", text: "action='debug.run' does not support status views." }], isError: true, details: { mode: "management", results: [] } });
5656
+ }
5657
+ return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots })));
5658
+ }
5053
5659
  if (paramsWithResolvedCwd.view === "fleet") {
5054
5660
  return withBudget(inspectSubagentStatus(paramsWithResolvedCwd, omitUndefinedProperties({ state: deps.state, nested: nestedScope, sessionRoots })));
5055
5661
  }
@@ -5439,6 +6045,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5439
6045
  const sessionName = resolveIntercomSessionTarget(deps.pi.getSessionName(), ctx.sessionManager.getSessionId());
5440
6046
  const intercomBridge = resolveIntercomBridge({
5441
6047
  config: deps.config.intercomBridge,
6048
+ override: effectiveParams.intercomBridge,
5442
6049
  context: effectiveParams.context ?? (contextPolicy.usesFork ? "fork" : undefined),
5443
6050
  orchestratorTarget: sessionName,
5444
6051
  });
@@ -5448,7 +6055,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5448
6055
  const runId = randomUUID().slice(0, 8);
5449
6056
  const inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();
5450
6057
  const nestedParentAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;
5451
- const nestedRoute = inheritedNestedRoute ?? createNestedRoute(runId);
5452
6058
  const shareEnabled = effectiveParams.share === true;
5453
6059
  const hasChain = (effectiveParams.chain?.length ?? 0) > 0;
5454
6060
  const hasTasks = (effectiveParams.tasks?.length ?? 0) > 0;
@@ -5488,6 +6094,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5488
6094
  const parentModel = requestParentModel;
5489
6095
  prepareForkThinking = (agentName, index, modelOverride) => {
5490
6096
  const agentConfig = agents.find((agent) => agent.name === agentName);
6097
+ if (agentConfig?.runner?.type === "external-cli") {
6098
+ forkThinkingRequirements.set(index, true);
6099
+ return;
6100
+ }
5491
6101
  const primaryModel = resolveEffectiveSubagentModel(
5492
6102
  modelOverride,
5493
6103
  agentConfig?.model,
@@ -5532,9 +6142,50 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5532
6142
  const foregroundTimeout = resolveSingleAgentLaunchTimeout(
5533
6143
  effectiveParams,
5534
6144
  effectiveAsync,
6145
+ resolveConfigDefaultTimeoutMs(deps.config.timeoutMs),
5535
6146
  );
5536
6147
  if (foregroundTimeout.error) return buildRequestedModeError(effectiveParams, foregroundTimeout.error);
5537
6148
  const controlConfig = resolveControlConfig(deps.config.control, effectiveParams.control);
6149
+ const requestedWorkflowChildAsyncId = typeof effectiveParams.workflowChildAsyncId === "string" ? effectiveParams.workflowChildAsyncId.trim() : "";
6150
+ const asyncRunId = requestedWorkflowChildAsyncId && path.basename(requestedWorkflowChildAsyncId) === requestedWorkflowChildAsyncId
6151
+ ? requestedWorkflowChildAsyncId
6152
+ : randomUUID();
6153
+ const topLevelAsyncCapacityEligible = depth === 0 && !inheritedNestedRoute && !effectiveParams.workflowParentRunId;
6154
+ const topLevelAsync = effectiveAsync && topLevelAsyncCapacityEligible;
6155
+ let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
6156
+ if (topLevelAsync) {
6157
+ try {
6158
+ const activeLimit = resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession);
6159
+ activeAsyncCapacity = acquireActiveAsyncCapacity({
6160
+ sessionId: requestSessionId,
6161
+ limit: activeLimit,
6162
+ runId: asyncRunId,
6163
+ kind: "runner",
6164
+ asyncDir: path.join(DIRS.async, asyncRunId),
6165
+ }, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) });
6166
+ deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(requestSessionId, activeLimit, { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []) });
6167
+ } catch (error) {
6168
+ if (error instanceof ActiveAsyncCapacityError) {
6169
+ deps.state.activeAsyncCapacity = error.snapshot;
6170
+ return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: foregroundMode, results: [], activeAsyncCapacity: error.snapshot } };
6171
+ }
6172
+ throw error;
6173
+ }
6174
+ }
6175
+
6176
+ let runFanoutBudget: RunFanoutBudgetDescriptor;
6177
+ try {
6178
+ const inheritedRunFanoutBudget = effectiveParams.runFanoutBudget ? undefined : decodeRunFanoutBudgetDescriptor(process.env[RUN_FANOUT_BUDGET_ENV]);
6179
+ runFanoutBudget = effectiveParams.runFanoutBudget
6180
+ ?? (inheritedRunFanoutBudget ? { ...inheritedRunFanoutBudget, parentPath: `${inheritedRunFanoutBudget.parentPath ? `${inheritedRunFanoutBudget.parentPath}/` : ""}${runId}` } : undefined)
6181
+ ?? createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun));
6182
+ if (!effectiveParams.runFanoutAdmitted) claimRunFanoutBatch(runFanoutBudget, staticRunFanoutPaths(effectiveParams));
6183
+ } catch (error) {
6184
+ activeAsyncCapacity?.rollback();
6185
+ if (error instanceof RunFanoutLimitError) return runFanoutErrorResult(error, foregroundMode);
6186
+ return buildRequestedModeError(effectiveParams, error instanceof Error ? error.message : String(error));
6187
+ }
6188
+ const nestedRoute = inheritedNestedRoute ?? createNestedRoute(runId);
5538
6189
 
5539
6190
  const artifactConfig: ArtifactConfig = omitUndefinedProperties({
5540
6191
  ...DEFAULT_ARTIFACT_CONFIG,
@@ -5560,6 +6211,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5560
6211
  try {
5561
6212
  fs.mkdirSync(sessionRoot, { recursive: true });
5562
6213
  } catch (error) {
6214
+ activeAsyncCapacity?.rollback();
5563
6215
  const message = error instanceof Error ? error.message : String(error);
5564
6216
  return toExecutionErrorResult(
5565
6217
  effectiveParams,
@@ -5590,10 +6242,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5590
6242
  preflightForkSessionsForStaticTasks(effectiveParams, contextPolicy, forkSessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems);
5591
6243
  }
5592
6244
  } catch (error) {
6245
+ activeAsyncCapacity?.rollback();
5593
6246
  return toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);
5594
6247
  }
5595
6248
  const chainBindingsError = validateExecutionChainBindings(effectiveParams, deps.config.chain?.dynamicFanout?.maxItems);
5596
- if (chainBindingsError) return withResolvedContext(chainBindingsError, contextPolicy.contextSummary);
6249
+ if (chainBindingsError) {
6250
+ activeAsyncCapacity?.rollback();
6251
+ return withResolvedContext(chainBindingsError, contextPolicy.contextSummary);
6252
+ }
5597
6253
 
5598
6254
  const onUpdateWithContext = onUpdate
5599
6255
  ? (r: AgentToolResult<Details>) => onUpdate(withResolvedContext({
@@ -5613,14 +6269,17 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5613
6269
  ownerSessionId: requestSessionId,
5614
6270
  });
5615
6271
  } catch (error) {
5616
- if (explicitMission) return toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);
6272
+ if (explicitMission) {
6273
+ activeAsyncCapacity?.rollback();
6274
+ return toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);
6275
+ }
5617
6276
  missionWarning = `Mission tracking unavailable: ${error instanceof Error ? error.message : String(error)}`;
5618
6277
  }
5619
6278
 
5620
6279
  const attachMission = (result: AgentToolResult<Details>): AgentToolResult<Details> => {
5621
6280
  if (!missionBinding) return missionWarning ? { ...result, details: { ...result.details, missionWarning } } : result;
5622
6281
  try {
5623
- return attachMissionToLaunchResult({ binding: missionBinding, result });
6282
+ return attachMissionToLaunchResult({ binding: delegatedExecution ? { ...missionBinding, announceInContent: false } : missionBinding, result });
5624
6283
  } catch (error) {
5625
6284
  const warning = `Mission tracking unavailable after launch: ${error instanceof Error ? error.message : String(error)}`;
5626
6285
  if (explicitMission) {
@@ -5641,7 +6300,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5641
6300
  requestSessionId,
5642
6301
  requestedSpawns,
5643
6302
  );
5644
- if (reservation.error) return attachMission(spawnBudgetErrorResult(reservation.error, foregroundMode));
6303
+ if (reservation.error) {
6304
+ activeAsyncCapacity?.rollback();
6305
+ return attachMission(spawnBudgetErrorResult(reservation.error, foregroundMode));
6306
+ }
5645
6307
 
5646
6308
  const execData: ExecutionContextData = omitUndefinedProperties({
5647
6309
  params: effectiveParams,
@@ -5650,6 +6312,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5650
6312
  signal,
5651
6313
  onUpdate: onUpdateWithContext,
5652
6314
  agents,
6315
+ recoveryAgents: discoveredAgents,
5653
6316
  runId,
5654
6317
  shareEnabled,
5655
6318
  sessionRoot,
@@ -5661,6 +6324,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5661
6324
  artifactsDir,
5662
6325
  backgroundRequestedWhileClarifying,
5663
6326
  effectiveAsync,
6327
+ asyncRunId,
5664
6328
  controlConfig,
5665
6329
  intercomBridge,
5666
6330
  nestedRoute,
@@ -5670,17 +6334,21 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5670
6334
  usageBudget: usageBudget.budget,
5671
6335
  allowZeroToolBudget,
5672
6336
  configToolBudget: configToolBudget.toolBudget,
6337
+ configToolTimeoutMs: deps.config.toolTimeoutMs,
5673
6338
  contextPolicy,
5674
6339
  modelScope,
5675
6340
  parentModel: requestParentModel,
5676
6341
  parentSessionId: requestSessionId,
5677
6342
  parentPiSessionId: requestPiSessionId,
5678
6343
  capabilityCeiling: resolveCurrentSubagentCapabilityCeiling(requestSessionId),
6344
+ runFanoutBudget,
6345
+ topLevelAsyncCapacityEligible,
6346
+ activeAsyncCapacity,
5679
6347
  });
5680
6348
 
5681
- const foregroundDescription = effectiveParams.task?.trim()
5682
- || effectiveParams.tasks?.[0]?.task?.trim()
5683
- || (effectiveParams.chain ? firstRawChainTask(effectiveParams.chain)?.trim() : undefined);
6349
+ const foregroundDescription = selectedAgentNames.length === 1
6350
+ ? `${selectedAgentNames[0]} child`
6351
+ : `${selectedAgentNames.length} live children`;
5684
6352
  const parentWorkflowStatus = effectiveParams.workflowParentRunId
5685
6353
  ? readStatus(path.join(DIRS.async, effectiveParams.workflowParentRunId))
5686
6354
  : null;
@@ -5715,6 +6383,37 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5715
6383
  interrupt: undefined,
5716
6384
  });
5717
6385
  if (foregroundControl) {
6386
+ foregroundControl.promptAuditRedo = async (index, guidance) => {
6387
+ const audit = getLivePromptAudit(foregroundControl, index);
6388
+ if (!audit?.rerun) return { text: "Redo is not safe for this prompt in this slice.", isError: true };
6389
+ const rewrittenTask = await rewritePromptWithGuidance({
6390
+ ctx,
6391
+ authoredTask: audit.authoredTask,
6392
+ runtimeAdditions: audit.runtimeAdditions,
6393
+ finalEffectivePrompt: audit.finalEffectivePrompt,
6394
+ guidance,
6395
+ signal,
6396
+ });
6397
+ const redoParams = promptAuditRedoParams(audit.rerun.params, rewrittenTask);
6398
+ const previousForegroundId = deps.state.lastForegroundControlId;
6399
+ const launch = execute(randomUUID(), redoParams, signal, undefined, ctx, true);
6400
+ const newRunId = deps.state.lastForegroundControlId && deps.state.lastForegroundControlId !== previousForegroundId
6401
+ ? deps.state.lastForegroundControlId
6402
+ : undefined;
6403
+ if (!newRunId) {
6404
+ const result = await launch;
6405
+ return { text: result.content.find((item) => item.type === "text")?.text ?? "Prompt redo could not start.", isError: true };
6406
+ }
6407
+ foregroundControl.supersededByRunId = newRunId;
6408
+ const replacement = deps.state.foregroundControls.get(newRunId);
6409
+ if (replacement) replacement.sourceRunId = foregroundControl.runId;
6410
+ void launch.then((result) => {
6411
+ if (result.isError) console.warn(`[pi-subagents] Prompt redo ${newRunId} failed: ${result.content.find((item) => item.type === "text")?.text ?? "unknown error"}`);
6412
+ }).catch((error) => {
6413
+ console.warn(`[pi-subagents] Prompt redo ${newRunId} failed: ${error instanceof Error ? error.message : String(error)}`);
6414
+ });
6415
+ return { text: `Prompt redo started ${newRunId}.` };
6416
+ };
5718
6417
  deps.state.foregroundControls.set(runId, foregroundControl);
5719
6418
  deps.state.lastForegroundControlId = runId;
5720
6419
  }
@@ -5805,13 +6504,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5805
6504
  };
5806
6505
 
5807
6506
  let nestedForegroundStarted = false;
6507
+ let asyncLaunchFailed = false;
5808
6508
  try {
6509
+ if (effectiveAsync) {
6510
+ deps.state.liveAsyncSessionRoots ??= new Map();
6511
+ deps.state.liveAsyncSessionRoots.set(asyncRunId, sessionRoot);
6512
+ }
5809
6513
  if (workflowLaunchObserver) {
5810
6514
  const singleTask = hasTasks && effectiveParams.tasks?.length === 1 ? effectiveParams.tasks[0] : undefined;
5811
6515
  const launch = hasSingle
5812
- ? { agent: effectiveParams.agent!, sessionFile: childSessionFileForTask(effectiveParams.agent!, 0, effectiveParams.model) }
6516
+ ? { agent: effectiveParams.agent!, sessionFile: childSessionFileForTask(effectiveParams.agent!, 0, effectiveParams.model), async: effectiveAsync, ...(effectiveAsync ? { runId: asyncRunId } : {}) }
5813
6517
  : singleTask
5814
- ? { agent: singleTask.agent, sessionFile: childSessionFileForTask(singleTask.agent, 0, singleTask.model) }
6518
+ ? { agent: singleTask.agent, sessionFile: childSessionFileForTask(singleTask.agent, 0, singleTask.model), async: effectiveAsync, ...(effectiveAsync ? { runId: asyncRunId } : {}) }
5815
6519
  : undefined;
5816
6520
  if (launch) {
5817
6521
  workflowLaunchObservers.delete(params);
@@ -5819,31 +6523,38 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5819
6523
  }
5820
6524
  }
5821
6525
  const asyncResult = runAsyncPath(execData, deps);
5822
- if (asyncResult) return attachMission(withResolvedContext(withForkThinkingNotes(asyncResult, forkThinkingDowngrades), contextPolicy.contextSummary));
6526
+ if (asyncResult) {
6527
+ asyncLaunchFailed = asyncResult.isError === true;
6528
+ return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(asyncResult, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget));
6529
+ }
5823
6530
  if (foregroundControl) {
5824
6531
  writeNestedForegroundEvent("subagent.nested.started");
5825
6532
  nestedForegroundStarted = true;
5826
6533
  }
6534
+ const runFanoutAnnotateContent = !delegatedExecution;
5827
6535
  if (hasChain && effectiveParams.chain) {
5828
6536
  const result = await runChainPath(execData, deps);
5829
6537
  writeNestedForegroundEvent("subagent.nested.completed", result);
5830
- return attachMission(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary));
6538
+ return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget, { annotateContent: runFanoutAnnotateContent }));
5831
6539
  }
5832
6540
  if (hasTasks && effectiveParams.tasks) {
5833
6541
  const result = await runParallelPath(execData, deps);
5834
6542
  writeNestedForegroundEvent("subagent.nested.completed", result);
5835
- return attachMission(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary));
6543
+ return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget, { annotateContent: runFanoutAnnotateContent }));
5836
6544
  }
5837
6545
  if (hasSingle) {
5838
6546
  const result = await runSinglePath(execData, deps);
5839
6547
  writeNestedForegroundEvent("subagent.nested.completed", result);
5840
- return attachMission(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary));
6548
+ return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(result, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget, { annotateContent: runFanoutAnnotateContent }));
5841
6549
  }
5842
6550
  } catch (error) {
6551
+ asyncLaunchFailed = effectiveAsync;
5843
6552
  const errorResult = withForkThinkingNotes(toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary), forkThinkingDowngrades);
5844
6553
  if (nestedForegroundStarted) writeNestedForegroundEvent("subagent.nested.completed", errorResult);
5845
6554
  return attachMission(errorResult);
5846
6555
  } finally {
6556
+ if (effectiveAsync && (asyncLaunchFailed || (activeAsyncCapacity && !activeAsyncCapacity.owner.runnerStartedAt))) deps.state.liveAsyncSessionRoots?.delete(asyncRunId);
6557
+ if (activeAsyncCapacity && !activeAsyncCapacity.owner.runnerStartedAt) activeAsyncCapacity.rollback();
5847
6558
  if (foregroundControl) {
5848
6559
  settleForegroundSchedulingOwner(foregroundControl);
5849
6560
  removeForegroundControlIfIdle(deps.state, runId);
@@ -5912,6 +6623,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5912
6623
  delete privateParams.delegatedAllowZeroToolBudget;
5913
6624
  if (thinkingOverride !== undefined) delegatedThinkingOverrides.set(delegatedParams, thinkingOverride);
5914
6625
  if (allowZeroToolBudget) delegatedZeroToolBudgets.add(delegatedParams);
6626
+ delegatedExecutions.add(delegatedParams);
5915
6627
  return execute(id, delegatedParams, signal, onUpdate, ctx);
5916
6628
  };
5917
6629