@xzzpig/pi-subagents 0.7.0 → 0.8.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 (86) hide show
  1. package/CHANGELOG.md +13 -4
  2. package/README.md +1 -1
  3. package/agents/reviewer.md +12 -2
  4. package/docs/agents.md +4 -4
  5. package/docs/configuration.md +6 -6
  6. package/docs/extension-api.md +14 -4
  7. package/docs/models.md +47 -6
  8. package/docs/observability.md +14 -3
  9. package/docs/tool-reference.md +21 -6
  10. package/docs/workflows.md +7 -1
  11. package/index.ts +10 -1
  12. package/package.json +3 -3
  13. package/prompts/council.md +19 -7
  14. package/prompts/parallel-review.md +5 -1
  15. package/prompts/review-loop.md +9 -5
  16. package/skills/council-mode/SKILL.md +50 -26
  17. package/skills/pi-subagents/SKILL.md +5 -1
  18. package/skills/pi-subagents/references/constraints-and-recipes.md +16 -1
  19. package/skills/pi-subagents/references/execution-controls.md +13 -4
  20. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -3
  21. package/skills/pi-subagents/references/prompting-and-roles.md +14 -7
  22. package/src/agents/agent-management.ts +115 -14
  23. package/src/agents/agent-serializer.ts +4 -2
  24. package/src/agents/agents.ts +226 -48
  25. package/src/api/external-job-provider.ts +10 -1
  26. package/src/api/preflight.ts +52 -19
  27. package/src/api/project-panes.ts +2 -0
  28. package/src/extension/doctor.ts +10 -0
  29. package/src/extension/fanout-child.ts +3 -2
  30. package/src/extension/index.ts +24 -4
  31. package/src/extension/public-execution.ts +12 -9
  32. package/src/extension/rpc.ts +77 -3
  33. package/src/extension/schemas.ts +7 -1
  34. package/src/extension/tool-description.ts +9 -6
  35. package/src/extension/tool-result.ts +19 -0
  36. package/src/inspectors/herdr/client.ts +3 -3
  37. package/src/inspectors/herdr/focus.ts +55 -0
  38. package/src/inspectors/herdr/project-panes.ts +228 -44
  39. package/src/integrations/herdr-status.ts +26 -4
  40. package/src/runs/background/async-execution.ts +146 -17
  41. package/src/runs/background/async-job-tracker.ts +33 -14
  42. package/src/runs/background/async-resume.ts +23 -2
  43. package/src/runs/background/async-retention.ts +1 -1
  44. package/src/runs/background/async-status.ts +10 -0
  45. package/src/runs/background/chain-root-attachment.ts +5 -0
  46. package/src/runs/background/control-channel.ts +98 -10
  47. package/src/runs/background/notify.ts +62 -1
  48. package/src/runs/background/result-watcher.ts +4 -3
  49. package/src/runs/background/run-status.ts +15 -1
  50. package/src/runs/background/stale-run-reconciler.ts +3 -0
  51. package/src/runs/background/subagent-runner.ts +333 -48
  52. package/src/runs/background/wait-completions.ts +2 -0
  53. package/src/runs/background/wait-tool.ts +4 -3
  54. package/src/runs/foreground/async-stop-action.ts +23 -2
  55. package/src/runs/foreground/execution.ts +148 -13
  56. package/src/runs/foreground/foreground-history.ts +3 -2
  57. package/src/runs/foreground/subagent-executor.ts +417 -50
  58. package/src/runs/foreground/workflow-detach-reconcile.ts +18 -6
  59. package/src/runs/shared/acceptance.ts +11 -5
  60. package/src/runs/shared/agent-contract.ts +1 -1
  61. package/src/runs/shared/child-identity.ts +36 -0
  62. package/src/runs/shared/completion-guard.ts +52 -2
  63. package/src/runs/shared/dynamic-fanout.ts +1 -1
  64. package/src/runs/shared/extension-bindings.ts +78 -0
  65. package/src/runs/shared/external-cli-runner.ts +2 -0
  66. package/src/runs/shared/external-job-bridge.ts +53 -37
  67. package/src/runs/shared/external-job-runner.ts +126 -23
  68. package/src/runs/shared/fast-mode-extension.ts +10 -0
  69. package/src/runs/shared/model-exclusions.ts +2 -1
  70. package/src/runs/shared/model-fallback.ts +48 -22
  71. package/src/runs/shared/model-scope.ts +106 -39
  72. package/src/runs/shared/mutation-evidence.ts +145 -0
  73. package/src/runs/shared/orca-progress-tabs.ts +71 -9
  74. package/src/runs/shared/parallel-utils.ts +15 -0
  75. package/src/runs/shared/pi-args.ts +78 -1
  76. package/src/runs/shared/structured-output.ts +18 -4
  77. package/src/runs/shared/subagent-prompt-runtime.ts +48 -15
  78. package/src/runs/shared/tool-availability.ts +1 -3
  79. package/src/shared/launch-contract.ts +12 -5
  80. package/src/shared/settings.ts +6 -1
  81. package/src/shared/thinking-ceiling.ts +52 -0
  82. package/src/shared/types.ts +120 -5
  83. package/src/tui/fleet-status.ts +66 -13
  84. package/src/tui/render.ts +5 -4
  85. package/src/watchdog/permission-arbiter.ts +59 -52
  86. package/src/workflows/scripted-workflow.ts +156 -12
@@ -30,7 +30,7 @@ import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/
30
30
  import type { MainWatchdogRuntime } from "../../watchdog/runtime.ts";
31
31
  import { buildModelCandidates, inheritsParentModel, normalizeParentModel, resolveEffectiveSubagentModel, resolveModelCandidate, type ParentModel } from "../shared/model-fallback.ts";
32
32
  import { formatRetainedChildren, listRetainedChildren } from "../background/retained-children.ts";
33
- import type { ModelScopeConfig } from "../shared/model-scope.ts";
33
+ import { resolveModelScopesForAgent, type ModelScopeConfig } from "../shared/model-scope.ts";
34
34
  import { aggregateParallelOutputs } from "../shared/parallel-utils.ts";
35
35
  import { recordRun } from "../shared/run-history.ts";
36
36
  import {
@@ -73,6 +73,7 @@ import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
73
73
  import { usageBudgetExceededMessage, usageBudgetState, validateUsageBudgetConfig } from "../shared/usage-budget.ts";
74
74
  import { intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
75
75
  import { isAgentContractV1 } from "../shared/agent-contract.ts";
76
+ import { normalizeExtensionBindings, type ExtensionBindings } from "../shared/extension-bindings.ts";
76
77
  import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
77
78
  import { cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
78
79
  import { compactForegroundDetails, getSingleResultOutput, mapConcurrent, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage } from "../../shared/utils.ts";
@@ -88,7 +89,7 @@ import {
88
89
  resolveSubagentResultStatus,
89
90
  stripDetailsOutputsForIntercomReceipt,
90
91
  } from "../../intercom/result-intercom.ts";
91
- import { applySteeringRecoveryAgentConfig, asyncReviveRequiresRecoveryDescriptor, buildRevivedAsyncTask, resolveAsyncResumeTarget, resolveAsyncRunLocation } from "../background/async-resume.ts";
92
+ import { applySteeringRecoveryAgentConfig, asyncReviveRequiresRecoveryDescriptor, buildRevivedAsyncTask, readAsyncRecoveryDescriptor, resolveAsyncResumeTarget, resolveAsyncRunLocation } from "../background/async-resume.ts";
92
93
  import { deliverInterruptRequest, readRevivalBriefs, requestAsyncSteer, type SteerDeliveryMode } from "../background/control-channel.ts";
93
94
  import { updateSteeringTarget, waitForSteeringAction } from "../background/steering.ts";
94
95
  import { canQueueRetainedAsyncFollowUp, steerAsyncRun } from "./async-steering-action.ts";
@@ -108,7 +109,10 @@ import { resultFilePath, writeAsyncResultFile } from "../background/result-files
108
109
  import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, resolveInheritedNestedRouteFromEnv, resolveNestedAsyncDir, resolveNestedParentAddressFromEnv, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedRunResolutionScope } from "../shared/nested-events.ts";
109
110
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
110
111
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
112
+ import { isStoppableAsyncStatusStep, resolveAsyncStatusChild } from "../shared/child-identity.ts";
111
113
  import { inspectSubagentStatus } from "../background/run-status.ts";
114
+ import { getExternalJobProvider } from "../../api/external-job-provider.ts";
115
+ import { externalJobFollowUpRequestDigest, externalJobFollowUpRequestId, externalJobFollowUpRunId, externalJobPromptDigest, externalJobStableJson } from "../shared/external-job-runner.ts";
112
116
  import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.ts";
113
117
  import { handleMissionAction, MISSION_ACTIONS } from "../../missions/actions.ts";
114
118
  import { attachMissionToLaunchResult, prepareMissionLaunch, writeMissionAsyncBinding, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
@@ -153,7 +157,9 @@ import {
153
157
  type ResolvedTurnBudget,
154
158
  type ResolvedToolBudget,
155
159
  type RunFanoutBudgetDescriptor,
160
+ type SteeringRecoveryDescriptor,
156
161
  type SingleResult,
162
+ type SubagentChildStatusEvent,
157
163
  type ToolBudgetConfig,
158
164
  type TurnBudgetConfig,
159
165
  type UsageBudgetConfig,
@@ -260,6 +266,7 @@ interface TaskParam {
260
266
  reads?: string[] | boolean;
261
267
  progress?: boolean;
262
268
  model?: string;
269
+ fast?: boolean;
263
270
  skill?: string | string[] | boolean;
264
271
  outputSchema?: JsonSchemaObject;
265
272
  acceptance?: AcceptanceInput;
@@ -274,6 +281,7 @@ export interface SubagentParamsLike {
274
281
  dir?: string;
275
282
  handoffPath?: string;
276
283
  index?: number;
284
+ childId?: string;
277
285
  view?: "fleet" | "transcript";
278
286
  lines?: number;
279
287
  topic?: string;
@@ -283,6 +291,7 @@ export interface SubagentParamsLike {
283
291
  type?: string;
284
292
  agent?: string;
285
293
  task?: string;
294
+ extensionBindings?: ExtensionBindings;
286
295
  /** Retained async child run id. Valid only on workflow runs.run items. */
287
296
  resume?: string;
288
297
  message?: string;
@@ -298,12 +307,15 @@ export interface SubagentParamsLike {
298
307
  /** Set by the scheduler so this run's completion can name the schedule that produced it. */
299
308
  scheduleOrigin?: ScheduleOrigin;
300
309
  workflowChildAsyncId?: string;
310
+ workflowAwaitAsync?: boolean;
301
311
  workflowParentDeadlineAt?: number;
302
312
  suppressRoutineResultIntercom?: boolean;
303
313
  /** Internal inherited cumulative run-tree budget. */
304
314
  runFanoutBudget?: RunFanoutBudgetDescriptor;
305
315
  /** Internal workflow host admission proof. */
306
316
  runFanoutAdmitted?: boolean;
317
+ /** Internal inherited tool/agent ceiling for delegated child launches. */
318
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
307
319
  /** Internal durable-run compatibility fields. Public callers must use workflowScript. */
308
320
  chain?: ChainStep[];
309
321
  tasks?: TaskParam[];
@@ -332,6 +344,7 @@ export interface SubagentParamsLike {
332
344
  artifacts?: boolean;
333
345
  includeProgress?: boolean;
334
346
  model?: string;
347
+ fast?: boolean;
335
348
  thinking?: string | false;
336
349
  scope?: string;
337
350
  target?: string;
@@ -384,7 +397,7 @@ interface ExecutorDeps {
384
397
  tempArtifactsDir: string;
385
398
  getSubagentSessionRoot: (parentSessionFile: string | null) => string;
386
399
  expandTilde: (p: string) => string;
387
- discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig };
400
+ discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig; maxThinking?: AgentConfig["maxThinking"] };
388
401
  allowMutatingManagementActions?: boolean;
389
402
  activateSupervisorTransport?: () => void;
390
403
  refreshResultDelivery?: () => void;
@@ -636,7 +649,7 @@ function foregroundChildActivityFromProgress(progress: SingleResult["progress"]
636
649
  };
637
650
  }
638
651
 
639
- function rememberForegroundRun(state: SubagentState, input: { runId: string; mode: "single" | "parallel" | "chain"; cwd: string; sessionId: string | null; results: SingleResult[] }): void {
652
+ function rememberForegroundRun(state: SubagentState, input: { runId: string; mode: "single" | "parallel" | "chain"; cwd: string; sessionId: string | null; results: SingleResult[]; extensionBindings?: ExtensionBindings }): void {
640
653
  state.foregroundRuns ??= new Map();
641
654
  const previous = state.foregroundRuns.get(input.runId);
642
655
  const updatedAt = Date.now();
@@ -678,6 +691,7 @@ function rememberForegroundRun(state: SubagentState, input: { runId: string; mod
678
691
  ...(result.detachedReason ? { detachedReason: result.detachedReason } : {}),
679
692
  ...(result.acceptance ? { acceptance: result.acceptance } : {}),
680
693
  ...(result.launchContractDigest ? { launchContractDigest: result.launchContractDigest } : {}),
694
+ ...(input.extensionBindings ? { extensionBindings: input.extensionBindings } : {}),
681
695
  ...(result.launchResolvedExtensions ? { launchResolvedExtensions: result.launchResolvedExtensions } : {}),
682
696
  ...(result.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: result.runtimeAcknowledgedExtensions } : {}),
683
697
  ...(result.capabilityCeiling ? { capabilityCeiling: result.capabilityCeiling } : {}),
@@ -796,7 +810,7 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
796
810
  });
797
811
  }
798
812
 
799
- function resolveForegroundResumeTarget(params: SubagentParamsLike, state: SubagentState, options: { exactOnly?: boolean } = {}): { runId: string; mode: SubagentRunMode; state: "complete"; agent: string; index: number; cwd: string; sessionFile: string; model?: string; thinking?: string; launchContractDigest?: string; capabilityCeiling?: ResolvedSubagentCapabilityCeiling } | undefined {
813
+ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: SubagentState, options: { exactOnly?: boolean } = {}): { runId: string; mode: SubagentRunMode; state: "complete"; agent: string; index: number; cwd: string; sessionFile: string; model?: string; thinking?: string; launchContractDigest?: string; extensionBindings?: ExtensionBindings; capabilityCeiling?: ResolvedSubagentCapabilityCeiling } | undefined {
800
814
  const requested = (params.id ?? params.runId)?.trim();
801
815
  if (!requested || !state.foregroundRuns?.size || !state.currentSessionId) return undefined;
802
816
  const direct = state.foregroundRuns.get(requested);
@@ -827,6 +841,7 @@ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: Subage
827
841
  ...(child.model ? { model: child.model } : {}),
828
842
  ...(child.thinking ? { thinking: child.thinking } : {}),
829
843
  ...(child.launchContractDigest ? { launchContractDigest: child.launchContractDigest } : {}),
844
+ ...(child.extensionBindings ? { extensionBindings: normalizeExtensionBindings(child.extensionBindings)!.value } : {}),
830
845
  ...(child.capabilityCeiling ? { capabilityCeiling: child.capabilityCeiling } : {}),
831
846
  };
832
847
  }
@@ -846,6 +861,7 @@ type NestedResumeSourceTarget = {
846
861
  thinking?: AgentConfig["thinking"];
847
862
  launchContractDigest?: string;
848
863
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
864
+ recoveryDescriptor?: SteeringRecoveryDescriptor;
849
865
  };
850
866
  type ResumeSourceTarget = AsyncResumeSourceTarget | ForegroundResumeSourceTarget | NestedResumeSourceTarget;
851
867
 
@@ -853,6 +869,10 @@ function isAsyncRunNotFound(error: unknown): boolean {
853
869
  return error instanceof Error && error.message.startsWith("Async run not found.");
854
870
  }
855
871
 
872
+ function isMissingExactAsyncStatusFile(error: unknown, requested: string): boolean {
873
+ return error instanceof Error && error.message === `Status file not found for async run '${requested}'.`;
874
+ }
875
+
856
876
  function isResumeAmbiguity(error: unknown): boolean {
857
877
  return error instanceof Error && /Ambiguous .*run id prefix/.test(error.message);
858
878
  }
@@ -906,7 +926,7 @@ function resolveResumeTarget(params: SubagentParamsLike, state: SubagentState, o
906
926
  throw new Error(`Resume id '${requested}' is ambiguous between foreground run '${foregroundTarget.runId}' and async run '${asyncTarget.runId}'. Provide a full run id.`);
907
927
  }
908
928
  if (foregroundTarget) {
909
- if (isExactResumeError(asyncError, "async", requested)) throw asyncError;
929
+ if (isExactResumeError(asyncError, "async", requested) && !isMissingExactAsyncStatusFile(asyncError, requested)) throw asyncError;
910
930
  if (isResumeAmbiguity(asyncError) && !resumeTargetExact(foregroundTarget, requested)) throw asyncError;
911
931
  return foregroundTarget;
912
932
  }
@@ -1327,6 +1347,14 @@ function validateNestedSessionFile(run: NestedRunSummary, trustedSessionRoots: s
1327
1347
  return realSessionFile;
1328
1348
  }
1329
1349
 
1350
+ export function readNestedRecoveryDescriptor(asyncDir: string | undefined, runId: string, agent: string): SteeringRecoveryDescriptor | undefined {
1351
+ const recoveryDescriptor = readAsyncRecoveryDescriptor(asyncDir);
1352
+ if (!recoveryDescriptor) return undefined;
1353
+ if (recoveryDescriptor.sourceRunId !== runId) throw new Error(`Nested run '${runId}' has a recovery descriptor for a different source run.`);
1354
+ if (recoveryDescriptor.agent !== agent) throw new Error(`Nested run '${runId}' has a recovery descriptor for a different agent.`);
1355
+ return recoveryDescriptor;
1356
+ }
1357
+
1330
1358
  function resolveNestedResumeTarget(match: ResolvedSubagentRunId & { kind: "nested" }, trustedSessionRoots: string[]): NestedResumeSourceTarget {
1331
1359
  const run = match.match.run;
1332
1360
  if (run.state === "running" || run.state === "queued") throw new Error(`Nested run '${run.id}' is live; route the follow-up to the owner process instead.`);
@@ -1335,6 +1363,7 @@ function resolveNestedResumeTarget(match: ResolvedSubagentRunId & { kind: "neste
1335
1363
  if (!agent) throw new Error(`Could not determine child agent for nested run '${run.id}'.`);
1336
1364
  const state = run.state === "complete" || run.state === "failed" || run.state === "paused" ? run.state : "failed";
1337
1365
  const asyncDir = resolveNestedAsyncDir(match.match.rootRunId, run);
1366
+ const recoveryDescriptor = readNestedRecoveryDescriptor(asyncDir, run.id, agent);
1338
1367
  return compactOptional<NestedResumeSourceTarget>({
1339
1368
  kind: "revive",
1340
1369
  source: "nested",
@@ -1345,6 +1374,7 @@ function resolveNestedResumeTarget(match: ResolvedSubagentRunId & { kind: "neste
1345
1374
  cwd: asyncDir ? path.dirname(asyncDir) : undefined,
1346
1375
  sessionFile: validateNestedSessionFile(run, trustedSessionRoots),
1347
1376
  ...(run.capabilityCeiling ? { capabilityCeiling: run.capabilityCeiling } : {}),
1377
+ ...(recoveryDescriptor ? { recoveryDescriptor } : {}),
1348
1378
  });
1349
1379
  }
1350
1380
 
@@ -1456,6 +1486,31 @@ async function steerNestedRun(input: { target: ResolvedSubagentRunId & { kind: "
1456
1486
  return { content: [{ type: "text", text: `Nested run ${run.id} is not a live async Pi child session with a steering inbox. action='steer' cannot target foreground nested runs.` }], isError: true, details: { mode: "management", results: [] } };
1457
1487
  }
1458
1488
 
1489
+ function externalJobOptionsEqual(left: Record<string, unknown>, right: Record<string, unknown>): boolean {
1490
+ return externalJobStableJson(left) === externalJobStableJson(right);
1491
+ }
1492
+
1493
+ function providerFollowUpSupport(providerName: string): { ok: true } | { ok: false; message: string } {
1494
+ try {
1495
+ const provider = getExternalJobProvider(providerName);
1496
+ if (!provider) return { ok: false, message: `External-job provider '${providerName}' is not registered. Load the provider package, then retry action='resume'.` };
1497
+ if (typeof provider.followUp !== "function") return { ok: false, message: `External-job provider '${providerName}' does not support follow-up. Update or reload the provider package, then retry action='resume'.` };
1498
+ return { ok: true };
1499
+ } catch (error) {
1500
+ return { ok: false, message: `External-job provider registry unavailable: ${error instanceof Error ? error.message : String(error)}` };
1501
+ }
1502
+ }
1503
+
1504
+ function externalJobFollowUpStarted(input: { sourceRunId: string; runId: string; asyncDir: string; duplicate?: boolean; interactive: boolean }): AgentToolResult<Details> {
1505
+ const lines = [
1506
+ input.duplicate ? `External-job follow-up already exists for ${input.sourceRunId}.` : `Started external-job follow-up for ${input.sourceRunId}.`,
1507
+ `Follow-up run: ${input.runId}`,
1508
+ `Async dir: ${input.asyncDir}`,
1509
+ `Status if needed: subagent({ action: "status", id: "${input.runId}" })`,
1510
+ ];
1511
+ return { content: [{ type: "text", text: formatAsyncStartedMessage(lines.join("\n"), input.interactive) }], details: { mode: "single", results: [], asyncId: input.runId, asyncDir: input.asyncDir } };
1512
+ }
1513
+
1459
1514
  function externalRunnerControlError(asyncDir: string, action: "steer" | "resume"): AgentToolResult<Details> | undefined {
1460
1515
  const status = readStatus(asyncDir);
1461
1516
  if (!status?.steps?.length || !status.steps.every((step) => step.runner?.type === "external-cli" || step.runner?.type === "external-job")) return undefined;
@@ -1465,6 +1520,116 @@ function externalRunnerControlError(asyncDir: string, action: "steer" | "resume"
1465
1520
  return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
1466
1521
  }
1467
1522
 
1523
+ async function resumeExternalJobFollowUp(input: {
1524
+ target: AsyncResumeSourceTarget;
1525
+ followUp: string;
1526
+ baseAgentConfig: AgentConfig;
1527
+ effectiveCwd: string;
1528
+ requestCwd: string;
1529
+ ctx: ExtensionContext;
1530
+ deps: ExecutorDeps;
1531
+ parentModel?: ParentModel;
1532
+ modelScope?: ModelScopeConfig;
1533
+ intercomBridge: IntercomBridgeState;
1534
+ parentSessionFile: string | null;
1535
+ absoluteDeadlineAt?: number;
1536
+ }): Promise<AgentToolResult<Details>> {
1537
+ if (input.target.kind === "live" || input.target.state === "running" || input.target.state === "queued") {
1538
+ return { content: [{ type: "text", text: `External-job run '${input.target.runId}' is still running. Wait for completion, then use subagent({ action: "resume", id: "${input.target.runId}", message: "..." }).` }], isError: true, details: { mode: "management", results: [] } };
1539
+ }
1540
+ const runner = input.target.runner;
1541
+ const externalJob = input.target.externalJob;
1542
+ if (runner?.type !== "external-job") return { content: [{ type: "text", text: "Internal error: external-job follow-up was requested for a non-external-job runner." }], isError: true, details: { mode: "management", results: [] } };
1543
+ if (!externalJob) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has no persisted provider metadata. Cannot follow up without the parent provider job id.` }], isError: true, details: { mode: "management", results: [] } };
1544
+ if (externalJob.provider !== runner.provider) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has mismatched provider metadata. Refusing to follow up.` }], isError: true, details: { mode: "management", results: [] } };
1545
+ if (!externalJobOptionsEqual(externalJob.options, runner.options)) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has mismatched provider options. Refusing to follow up.` }], isError: true, details: { mode: "management", results: [] } };
1546
+ if (!externalJob.providerJobId) return { content: [{ type: "text", text: `External-job run '${input.target.runId}' has no parent provider job id. Cannot follow up without reopening or redispatching, so this fails closed.` }], isError: true, details: { mode: "management", results: [] } };
1547
+ if (externalJob.state !== "completed") return { content: [{ type: "text", text: `External-job run '${input.target.runId}' provider state is ${externalJob.state}. Wait for completion, then use action='resume'.` }], isError: true, details: { mode: "management", results: [] } };
1548
+ const support = providerFollowUpSupport(runner.provider);
1549
+ if (!support.ok) return { content: [{ type: "text", text: support.message }], isError: true, details: { mode: "management", results: [] } };
1550
+
1551
+ const promptDigest = externalJobPromptDigest(input.followUp);
1552
+ const requestDigest = externalJobFollowUpRequestDigest({ provider: runner.provider, parentProviderJobId: externalJob.providerJobId, promptDigest, options: runner.options });
1553
+ const requestId = externalJobFollowUpRequestId(requestDigest);
1554
+ const runId = externalJobFollowUpRunId(requestDigest);
1555
+ const asyncDir = path.join(DIRS.async, runId);
1556
+ const currentSessionId = input.deps.state.currentSessionId;
1557
+ if (!currentSessionId) return { content: [{ type: "text", text: "External-job follow-up requires an active parent session." }], isError: true, details: { mode: "management", results: [] } };
1558
+ if (fs.existsSync(asyncDir) || fs.existsSync(resultFilePath(DIRS.results, runId))) {
1559
+ return externalJobFollowUpStarted({ sourceRunId: input.target.runId, runId, asyncDir, duplicate: true, interactive: input.ctx.hasUI });
1560
+ }
1561
+
1562
+ const depthState = checkSubagentDepth(input.deps.config.maxSubagentDepth);
1563
+ if (depthState.blocked) {
1564
+ return { content: [{ type: "text", text: `Nested subagent resume blocked (depth=${depthState.depth}, max=${depthState.maxDepth}). Complete the follow-up directly instead.` }], isError: true, details: { mode: "management", results: [] } };
1565
+ }
1566
+ const topLevelResume = depthState.depth === 0 && !resolveInheritedNestedRouteFromEnv() && !input.deps.state.workflowControllers?.has(input.target.runId);
1567
+ let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
1568
+ try {
1569
+ activeAsyncCapacity = topLevelResume ? acquireActiveAsyncCapacity({
1570
+ sessionId: currentSessionId,
1571
+ limit: resolveMaxActiveAsyncRunsPerSession(input.deps.config.maxActiveAsyncRunsPerSession),
1572
+ runId,
1573
+ kind: "runner",
1574
+ asyncDir,
1575
+ }, { liveWorkflowRunIds: new Set(input.deps.state.workflowControllers?.keys() ?? []) }) : undefined;
1576
+ } catch (error) {
1577
+ if (error instanceof ActiveAsyncCapacityError) return { content: [{ type: "text", text: error.message }], isError: true, details: { mode: "single", results: [], activeAsyncCapacity: error.snapshot } };
1578
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "single", results: [] } };
1579
+ }
1580
+
1581
+ const artifactConfig: ArtifactConfig = omitUndefinedProperties({ ...DEFAULT_ARTIFACT_CONFIG, enabled: true, dir: input.deps.config.artifactDir ?? DEFAULT_ARTIFACT_CONFIG.dir });
1582
+ const artifactsDir = getArtifactsDir(input.parentSessionFile, input.effectiveCwd, artifactConfig.dir);
1583
+ const parentModel = input.parentModel;
1584
+ const agentConfig: AgentConfig = {
1585
+ ...input.baseAgentConfig,
1586
+ runner: { type: "external-job", provider: runner.provider, options: runner.options },
1587
+ };
1588
+ const result = executeAsyncSingle(runId, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
1589
+ agent: input.target.agent,
1590
+ task: input.followUp,
1591
+ goal: input.followUp,
1592
+ agentConfig,
1593
+ recoveryAgentConfig: agentConfig,
1594
+ ctx: compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
1595
+ pi: input.deps.pi,
1596
+ cwd: input.requestCwd,
1597
+ currentSessionId,
1598
+ parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1599
+ currentModelProvider: parentModel?.provider,
1600
+ currentModel: parentModel,
1601
+ modelScope: input.modelScope,
1602
+ interactive: input.ctx.hasUI,
1603
+ permissions: input.deps.config.permissions,
1604
+ }),
1605
+ cwd: input.effectiveCwd,
1606
+ artifactsDir,
1607
+ artifactConfig,
1608
+ shareEnabled: false,
1609
+ ...(input.parentSessionFile ? { sessionRoot: input.deps.getSubagentSessionRoot(input.parentSessionFile) } : {}),
1610
+ maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
1611
+ waitToolEnabled: input.deps.waitToolEnabled,
1612
+ worktreeSetupHook: input.deps.config.worktreeSetupHook,
1613
+ worktreeSetupHookTimeoutMs: input.deps.config.worktreeSetupHookTimeoutMs,
1614
+ worktreeBaseDir: input.deps.config.worktreeBaseDir,
1615
+ controlConfig: resolveControlConfig(input.deps.config.control, undefined),
1616
+ controlIntercomTarget: input.intercomBridge.active ? input.intercomBridge.orchestratorTarget : undefined,
1617
+ childIntercomTarget: input.intercomBridge.active ? (agent, index) => resolveSubagentIntercomTarget(runId, agent, index) : undefined,
1618
+ availableModels: input.ctx.modelRegistry.getAvailable().map(toModelInfo),
1619
+ outputBaseDir: resolveSingleRunOutputBaseDir(input.deps, artifactsDir, runId),
1620
+ ...(input.absoluteDeadlineAt !== undefined ? { absoluteDeadlineAt: input.absoluteDeadlineAt } : {}),
1621
+ capabilityCeiling: resolveCurrentSubagentCapabilityCeiling(currentSessionId),
1622
+ runFanoutBudget: createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(input.deps.config.maxSubagentSpawnsPerRun)),
1623
+ activeAsyncCapacity,
1624
+ externalJobFollowUp: { sourceRunId: input.target.runId, sourceStepIndex: input.target.index, parentProviderJobId: externalJob.providerJobId, requestId, requestDigest },
1625
+ }));
1626
+ if (result.isError) {
1627
+ activeAsyncCapacity?.rollback();
1628
+ return result;
1629
+ }
1630
+ return externalJobFollowUpStarted({ sourceRunId: input.target.runId, runId: result.details.asyncId ?? runId, asyncDir: result.details.asyncDir ?? asyncDir, interactive: input.ctx.hasUI });
1631
+ }
1632
+
1468
1633
  async function resumeAsyncRun(input: {
1469
1634
  params: SubagentParamsLike;
1470
1635
  requestCwd: string;
@@ -1529,11 +1694,7 @@ async function resumeAsyncRun(input: {
1529
1694
  ];
1530
1695
  target = resolveNestedResumeTarget(resolved, trustedSessionRoots);
1531
1696
  } else {
1532
- if (resolved?.kind === "async" && resolved.location.asyncDir) {
1533
- const unsupported = externalRunnerControlError(resolved.location.asyncDir, "resume");
1534
- if (unsupported) return unsupported;
1535
- }
1536
- target = resolveResumeTarget(input.params, input.deps.state, { asyncRequireSessionFile: !attachChain });
1697
+ target = resolveResumeTarget(input.params, input.deps.state, { asyncRequireSessionFile: false });
1537
1698
  }
1538
1699
  } catch (error) {
1539
1700
  const message = error instanceof Error ? error.message : String(error);
@@ -1591,6 +1752,7 @@ async function resumeAsyncRun(input: {
1591
1752
  inheritSkills: recoveryDescriptor.inheritSkills,
1592
1753
  source: "project",
1593
1754
  filePath: recoveryDescriptor.agentFilePath ?? path.join(getProjectSubagentsDir(recoveryDescriptor.cwd), "recovery-agent"),
1755
+ ...(discovered.maxThinking ? { maxThinking: discovered.maxThinking } : {}),
1594
1756
  } : undefined);
1595
1757
  if (!baseAgentConfig) {
1596
1758
  return {
@@ -1599,6 +1761,26 @@ async function resumeAsyncRun(input: {
1599
1761
  details: { mode: "management", results: [] },
1600
1762
  };
1601
1763
  }
1764
+ if (target.source === "async" && target.runner?.type === "external-cli") {
1765
+ return { content: [{ type: "text", text: "External runners do not persist Pi sessions and cannot be resumed." }], isError: true, details: { mode: "management", results: [] } };
1766
+ }
1767
+ if (target.source === "async" && target.runner?.type === "external-job") {
1768
+ if (attachChain) return { content: [{ type: "text", text: "External-job follow-up does not support chain attachment. Use action='resume' with message instead." }], isError: true, details: { mode: "management", results: [] } };
1769
+ return resumeExternalJobFollowUp({
1770
+ target,
1771
+ followUp,
1772
+ baseAgentConfig,
1773
+ effectiveCwd,
1774
+ requestCwd: input.requestCwd,
1775
+ ctx: input.ctx,
1776
+ deps: input.deps,
1777
+ parentModel: input.parentModel,
1778
+ modelScope,
1779
+ intercomBridge,
1780
+ parentSessionFile,
1781
+ absoluteDeadlineAt: input.absoluteDeadlineAt,
1782
+ });
1783
+ }
1602
1784
 
1603
1785
  if (attachChain) {
1604
1786
  if (target.source !== "async") {
@@ -1671,6 +1853,7 @@ async function resumeAsyncRun(input: {
1671
1853
  sessionRoot: input.deps.getSubagentSessionRoot(parentSessionFile),
1672
1854
  chainSkills: normalized === false ? [] : (normalized ?? []),
1673
1855
  agentContract: input.params.agentContract,
1856
+ fast: input.params.fast,
1674
1857
  dynamicFanoutMaxItems: input.deps.config.chain?.dynamicFanout?.maxItems,
1675
1858
  maxSubagentDepth: resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
1676
1859
  waitToolEnabled: input.deps.waitToolEnabled,
@@ -1683,6 +1866,7 @@ async function resumeAsyncRun(input: {
1683
1866
  globalConcurrencyLimit: input.deps.config.globalConcurrencyLimit,
1684
1867
  runFanoutBudget: createRunFanoutBudget(runId, resolveMaxSubagentSpawnsPerRun(input.deps.config.maxSubagentSpawnsPerRun)),
1685
1868
  capabilityCeiling: intersectSubagentCapabilityCeilings("capabilityCeiling" in target ? target.capabilityCeiling : undefined, resolveCurrentSubagentCapabilityCeiling(input.deps.state.currentSessionId)),
1869
+ thinkingCeiling: target.thinkingCeiling,
1686
1870
  activeAsyncCapacity,
1687
1871
  }));
1688
1872
  if (result.isError) {
@@ -1705,7 +1889,7 @@ async function resumeAsyncRun(input: {
1705
1889
  const effectiveFollowUp = [...queuedBriefs.map(({ request }) => request.message), followUp].filter(Boolean).join("\n\n");
1706
1890
  const revivalSessionFile = target.sessionFile;
1707
1891
  if (!revivalSessionFile) {
1708
- return { content: [{ type: "text", text: `Async child '${target.runId}' has no persisted session file to resume.` }], isError: true, details: { mode: "management", results: [] } };
1892
+ return { content: [{ type: "text", text: `Async run '${target.runId}' child ${target.index} does not have a persisted session file to resume from.` }], isError: true, details: { mode: "management", results: [] } };
1709
1893
  }
1710
1894
  if (target.source === "async" && asyncReviveRequiresRecoveryDescriptor(target)) {
1711
1895
  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: [] } };
@@ -1773,8 +1957,11 @@ async function resumeAsyncRun(input: {
1773
1957
  },
1774
1958
  context: recoveryContext,
1775
1959
  modelOverride: recoveryDescriptor?.model ?? target.model,
1960
+ fast: recoveryDescriptor?.fast,
1776
1961
  modelOverrideFromParent: recoveryDescriptor?.modelOverrideFromParent,
1777
1962
  thinkingOverride: recoveryDescriptor?.thinking ?? target.thinking,
1963
+ thinkingCeiling: recoveryDescriptor?.thinkingCeiling ?? ("thinkingCeiling" in target ? target.thinkingCeiling : undefined),
1964
+ extensionBindings: recoveryDescriptor?.extensionBindings ?? ("extensionBindings" in target ? target.extensionBindings : undefined),
1778
1965
  outputBaseDir: resolveSingleRunOutputBaseDir(input.deps, artifactsDir, runId),
1779
1966
  maxSubagentDepth: recoveryDescriptor?.maxSubagentDepth ?? resolveCurrentMaxSubagentDepth(input.deps.config.maxSubagentDepth),
1780
1967
  waitToolEnabled: input.deps.waitToolEnabled,
@@ -1866,6 +2053,7 @@ async function resumeAsyncRun(input: {
1866
2053
  ...(completed.model ? { model: completed.model } : {}),
1867
2054
  ...(completed.attemptedModels ? { attemptedModels: completed.attemptedModels } : {}),
1868
2055
  ...(completed.modelAttempts ? { modelAttempts: completed.modelAttempts } : {}),
2056
+ ...(completed.contextOverflow ? { contextOverflow: true } : {}),
1869
2057
  ...(completed.structuredOutput !== undefined ? { structuredOutput: completed.structuredOutput } : {}),
1870
2058
  ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
1871
2059
  ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
@@ -2056,6 +2244,15 @@ function canonicalizeExecutionParams(params: SubagentParamsLike, agents: AgentCo
2056
2244
  const result = resolve(params.agent);
2057
2245
  if (result.error) return { error: result.error };
2058
2246
  params = omitUndefinedProperties({ ...params, agent: result.name });
2247
+ const agent = agents.find((candidate) => candidate.name === result.name);
2248
+ if (params.extensionBindings !== undefined && (agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job")) return { error: `extensionBindings is not supported for runner.type='${agent.runner.type}'.` };
2249
+ }
2250
+ if (params.extensionBindings !== undefined) {
2251
+ try {
2252
+ params = { ...params, extensionBindings: normalizeExtensionBindings(params.extensionBindings)!.value };
2253
+ } catch (error) {
2254
+ return { error: error instanceof Error ? error.message : String(error) };
2255
+ }
2059
2256
  }
2060
2257
  if (params.tasks) {
2061
2258
  const tasks: TaskParam[] = [];
@@ -2652,6 +2849,7 @@ function resolveStaticLaunchSummary(input: {
2652
2849
  }): StaticLaunchSummary {
2653
2850
  const agentConfig = input.agents.find((agent) => agent.name === input.agent);
2654
2851
  const externalRunner = agentConfig?.runner?.type === "external-cli" || agentConfig?.runner?.type === "external-job";
2852
+ const modelScopes = resolveModelScopesForAgent(input.modelScope, input.agent, input.parentModel);
2655
2853
  const model = externalRunner
2656
2854
  ? undefined
2657
2855
  : resolveEffectiveSubagentModel(
@@ -2659,8 +2857,8 @@ function resolveStaticLaunchSummary(input: {
2659
2857
  agentConfig?.model,
2660
2858
  input.parentModel,
2661
2859
  input.availableModels,
2662
- input.currentProvider,
2663
- input.modelScope === undefined ? {} : { scope: input.modelScope },
2860
+ agentConfig?.modelProvider ?? input.currentProvider,
2861
+ modelScopes.length === 0 ? {} : { scope: modelScopes },
2664
2862
  );
2665
2863
  const thinkingOverride = externalRunner ? undefined : input.thinkingOverrideForTask(input.agent, input.index, model);
2666
2864
  const thinking = externalRunner ? undefined : resolveEffectiveThinking(model, thinkingOverride ?? agentConfig?.thinking);
@@ -2820,7 +3018,68 @@ function preflightForkSessionsForStaticTasks(
2820
3018
  }
2821
3019
  }
2822
3020
 
2823
- function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentToolResult<Details> | null {
3021
+ async function waitForWorkflowAsyncSingleResult(
3022
+ params: SubagentParamsLike,
3023
+ launchResult: AgentToolResult<Details>,
3024
+ options: { runId: string; task: string; signal?: AbortSignal; state: SubagentState; kill?: ExecutorDeps["kill"] },
3025
+ ): Promise<AgentToolResult<Details>> {
3026
+ if (params.workflowAwaitAsync !== true || !launchResult.details.asyncDir) return launchResult;
3027
+ const asyncDir = launchResult.details.asyncDir;
3028
+ const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
3029
+ const stopOnAbort = () => { stopAsyncRun(options.state, options.runId, options.kill, { asyncDir, resolvedId: options.runId }); };
3030
+ if (options.signal?.aborted) stopOnAbort();
3031
+ else options.signal?.addEventListener("abort", stopOnAbort, { once: true });
3032
+ let completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>;
3033
+ try {
3034
+ completed = await waitForImportedAsyncRoot({ runId: options.runId, asyncDir, resultPath, index: 0 }, omitUndefinedProperties({
3035
+ shouldAbort: () => options.signal?.aborted === true,
3036
+ timeoutMessage: "Workflow stopped before async child completed.",
3037
+ }));
3038
+ } finally {
3039
+ options.signal?.removeEventListener("abort", stopOnAbort);
3040
+ }
3041
+ fs.rmSync(resultPath, { force: true });
3042
+ const totalCost = completed.totalCost;
3043
+ const childResult: SingleResult = omitUndefinedProperties({
3044
+ index: 0,
3045
+ agent: completed.agent,
3046
+ task: options.task,
3047
+ exitCode: completed.exitCode,
3048
+ usage: {
3049
+ input: totalCost?.inputTokens ?? 0,
3050
+ output: totalCost?.outputTokens ?? 0,
3051
+ cacheRead: 0,
3052
+ cacheWrite: 0,
3053
+ cost: totalCost?.costUsd ?? 0,
3054
+ turns: 0,
3055
+ },
3056
+ finalOutput: completed.output,
3057
+ outputState: completed.output.trim() ? "present" as const : "absent" as const,
3058
+ ...(completed.error ? { error: completed.error } : {}),
3059
+ ...(completed.timedOut ? { timedOut: true } : {}),
3060
+ ...(completed.stopped ? { stopped: true } : {}),
3061
+ ...(completed.sessionFile ? { sessionFile: completed.sessionFile } : {}),
3062
+ ...(completed.model ? { model: completed.model } : {}),
3063
+ ...(completed.attemptedModels ? { attemptedModels: completed.attemptedModels } : {}),
3064
+ ...(completed.modelAttempts ? { modelAttempts: completed.modelAttempts } : {}),
3065
+ ...(completed.contextOverflow ? { contextOverflow: true } : {}),
3066
+ ...(completed.structuredOutput !== undefined ? { structuredOutput: completed.structuredOutput } : {}),
3067
+ ...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
3068
+ ...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
3069
+ ...(completed.acceptance ? { acceptance: completed.acceptance } : {}),
3070
+ });
3071
+ return {
3072
+ content: [{ type: "text", text: completed.output || completed.error || `Async workflow child ${options.runId} completed without output.` }],
3073
+ ...(completed.success ? {} : { isError: true }),
3074
+ details: {
3075
+ ...launchResult.details,
3076
+ runId: options.runId,
3077
+ results: [childResult],
3078
+ },
3079
+ };
3080
+ }
3081
+
3082
+ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Promise<AgentToolResult<Details> | null> {
2824
3083
  const {
2825
3084
  params,
2826
3085
  effectiveCwd,
@@ -2890,11 +3149,15 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2890
3149
  const externalRunnerWithoutExplicitModel = (a.runner?.type === "external-cli" || a.runner?.type === "external-job")
2891
3150
  && params.model === undefined
2892
3151
  && (a.model === undefined || (a.modelSource?.type === "subagents.defaultModel" && a.model === a.modelSource.model));
3152
+ if ((a.runner?.type === "external-cli" || a.runner?.type === "external-job") && (params.fast ?? a.fast) === true) {
3153
+ return buildRequestedModeError(params, `Agent '${a.name}' uses runner.type='${a.runner.type}' and does not support fast mode.`);
3154
+ }
3155
+ const modelScopes = resolveModelScopesForAgent(data.modelScope, a.name, parentModel);
2893
3156
  const modelOverride = a.runner?.type === "external-cli" || a.runner?.type === "external-job"
2894
3157
  ? params.model ?? (externalRunnerWithoutExplicitModel ? undefined : a.model)
2895
- : resolveEffectiveSubagentModel(params.model as string | undefined, a.model, parentModel, availableModels, currentProvider, data.modelScope === undefined ? {} : { scope: data.modelScope });
3158
+ : resolveEffectiveSubagentModel(params.model as string | undefined, a.model, parentModel, availableModels, a.modelProvider ?? currentProvider, modelScopes.length === 0 ? {} : { scope: modelScopes });
2896
3159
  const modelOverrideFromParent = inheritsParentModel(params.model as string | undefined, a.model, parentModel);
2897
- return executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
3160
+ const asyncResult = executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
2898
3161
  agent: params.agent!,
2899
3162
  task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(params.task ?? "") : (params.task ?? ""),
2900
3163
  goal: params.task ?? "",
@@ -2917,8 +3180,10 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2917
3180
  ...(params.reads !== undefined ? { reads: params.reads } : {}),
2918
3181
  outputBaseDir: resolveSingleRunOutputBaseDir(deps, artifactsDir, id),
2919
3182
  modelOverride,
3183
+ fast: params.fast,
2920
3184
  modelOverrideFromParent,
2921
3185
  thinkingOverride: externalRunnerWithoutExplicitModel ? undefined : thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
3186
+ thinkingCeiling: a.maxThinking,
2922
3187
  maxSubagentDepth,
2923
3188
  waitToolEnabled: deps.waitToolEnabled,
2924
3189
  ...(params.worktree === true ? { worktree: true } : {}),
@@ -2932,6 +3197,7 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2932
3197
  nestedRoute,
2933
3198
  agentContract: params.agentContract,
2934
3199
  structuredOutputSchema: params.outputSchema,
3200
+ extensionBindings: params.extensionBindings,
2935
3201
  acceptance: params.acceptance,
2936
3202
  timeoutMs: data.timeoutMs,
2937
3203
  turnBudget: data.turnBudget,
@@ -2944,7 +3210,9 @@ function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): AgentTool
2944
3210
  runFanoutBudget: data.runFanoutBudget,
2945
3211
  parentWorkflowRunId: params.workflowParentRunId,
2946
3212
  workflowKey: params.workflowKey,
3213
+ workflowAwaitAsync: params.workflowAwaitAsync,
2947
3214
  }));
3215
+ return waitForWorkflowAsyncSingleResult(params, asyncResult, { runId: id, task: params.task ?? "", signal: data.signal, state: deps.state, kill: deps.kill });
2948
3216
  }
2949
3217
 
2950
3218
  return null;
@@ -2998,9 +3266,7 @@ function resolveWorkflowAggregateOutputPath(
2998
3266
  ctxCwd: string,
2999
3267
  workflowCwd: string,
3000
3268
  outputBaseDir: string,
3001
- configuredOutputBaseDir: string | undefined,
3002
3269
  ): string | undefined {
3003
- if (typeof output === "string" && output && !path.isAbsolute(output) && !configuredOutputBaseDir) return path.resolve(workflowCwd, output);
3004
3270
  return resolveSingleOutputPath(output, ctxCwd, workflowCwd, outputBaseDir);
3005
3271
  }
3006
3272
 
@@ -3036,6 +3302,7 @@ function resolveWorkflowChildOutputPath(input: {
3036
3302
  aggregateOutputPath?: string;
3037
3303
  configuredOutputBaseDir?: string;
3038
3304
  discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3305
+ agents: AgentConfig[];
3039
3306
  workflowAgentScope?: unknown;
3040
3307
  state?: SubagentState;
3041
3308
  key: string;
@@ -3054,8 +3321,10 @@ function resolveWorkflowChildOutputPath(input: {
3054
3321
  const hasExplicitOutput = typeof rawOutput === "string" || typeof rawOutput === "boolean";
3055
3322
  const childCwd = typeof input.params.cwd === "string" ? resolveChildCwd(input.workflowCwd, input.params.cwd) : input.workflowCwd;
3056
3323
  const agentScope = resolveExecutionAgentScope(input.params.agentScope ?? input.workflowAgentScope);
3057
- const agents = input.discoverAgents(childCwd, agentScope).agents;
3058
- const agent = typeof input.params.agent === "string" ? resolveAgentName(input.params.agent, agents).agent : undefined;
3324
+ const discoveredAgents = input.discoverAgents(childCwd, agentScope).agents;
3325
+ const agent = typeof input.params.agent === "string"
3326
+ ? resolveAgentName(input.params.agent, discoveredAgents).agent ?? resolveAgentName(input.params.agent, input.agents).agent
3327
+ : undefined;
3059
3328
  const agentOutput = typeof agent?.output === "string" ? agent.output : undefined;
3060
3329
  const output = rawOutput === true || rawOutput === "true"
3061
3330
  ? agentOutput
@@ -3065,7 +3334,7 @@ function resolveWorkflowChildOutputPath(input: {
3065
3334
  ? workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.workflowRunId, input.key)
3066
3335
  : agentOutput;
3067
3336
  return {
3068
- path: resolveSingleOutputPath(output, input.ctxCwd, childCwd, input.configuredOutputBaseDir),
3337
+ path: resolveSingleOutputPath(output, input.ctxCwd, childCwd, input.configuredOutputBaseDir ?? path.join(input.artifactsDir, "outputs", sanitizeRunPathSegment(input.workflowRunId))),
3069
3338
  inherited: !hasExplicitOutput && !input.aggregateOutputPath && agentOutput !== undefined,
3070
3339
  };
3071
3340
  }
@@ -3078,6 +3347,7 @@ function workflowChildOutputClaims(input: {
3078
3347
  aggregateOutputPath?: string;
3079
3348
  configuredOutputBaseDir?: string;
3080
3349
  discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3350
+ agents: AgentConfig[];
3081
3351
  workflowAgentScope?: unknown;
3082
3352
  state: SubagentState;
3083
3353
  claimedOutputPaths: Map<string, string>;
@@ -3126,9 +3396,10 @@ function prepareWorkflowChildLaunchParams(input: {
3126
3396
  aggregateOutputPath?: string;
3127
3397
  configuredOutputBaseDir?: string;
3128
3398
  discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
3399
+ agents: AgentConfig[];
3129
3400
  workflowAgentScope?: unknown;
3130
3401
  outputOverride?: string;
3131
- options?: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number };
3402
+ options?: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number; capabilityCeiling?: ResolvedSubagentCapabilityCeiling };
3132
3403
  }): SubagentParamsLike {
3133
3404
  let childParams = input.childParams;
3134
3405
  if (input.childParams.output === undefined && input.childParams.resume === undefined && input.outputOverride !== undefined) {
@@ -3136,10 +3407,17 @@ function prepareWorkflowChildLaunchParams(input: {
3136
3407
  } else if (input.childParams.output === undefined && input.childParams.resume === undefined && input.aggregateOutputPath !== undefined) {
3137
3408
  childParams = { ...input.childParams, output: workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.parentWorkflowRunId, input.workflowKey) };
3138
3409
  } else if (input.childParams.resume === undefined) {
3139
- 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 });
3410
+ const resolvedOutput = resolveWorkflowChildOutputPath({ ctxCwd: input.ctxCwd, workflowCwd: input.workflowCwd, artifactsDir: input.artifactsDir, workflowRunId: input.parentWorkflowRunId, aggregateOutputPath: input.aggregateOutputPath, configuredOutputBaseDir: input.configuredOutputBaseDir, discoverAgents: input.discoverAgents, agents: input.agents, workflowAgentScope: input.workflowAgentScope, key: input.workflowKey, params: input.childParams });
3140
3411
  if (resolvedOutput.path) childParams = { ...input.childParams, output: resolvedOutput.path };
3141
3412
  }
3142
- return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, input.options);
3413
+ const childCwd = typeof childParams.cwd === "string" ? resolveChildCwd(input.workflowCwd, childParams.cwd) : input.workflowCwd;
3414
+ const agentScope = resolveExecutionAgentScope(childParams.agentScope ?? input.workflowAgentScope);
3415
+ const discoveredAgents = input.discoverAgents(childCwd, agentScope).agents;
3416
+ const agent = typeof childParams.agent === "string"
3417
+ ? resolveAgentName(childParams.agent, discoveredAgents).agent ?? resolveAgentName(childParams.agent, input.agents).agent
3418
+ : undefined;
3419
+ const externalAsyncRequired = agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job";
3420
+ return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, { ...input.options, externalAsyncRequired });
3143
3421
  }
3144
3422
 
3145
3423
  function finalizeSingleWorktreeHandoff(input: {
@@ -3234,14 +3512,15 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3234
3512
  const parentModel = data.parentModel;
3235
3513
  const currentProvider = parentModel?.provider;
3236
3514
  const availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);
3515
+ const modelScopes = resolveModelScopesForAgent(data.modelScope, agentConfig.name, parentModel);
3237
3516
  let task = params.task ?? "";
3238
3517
  let modelOverride: string | undefined = resolveEffectiveSubagentModel(
3239
3518
  params.model as string | undefined,
3240
3519
  agentConfig.model,
3241
3520
  parentModel,
3242
3521
  availableModels,
3243
- currentProvider,
3244
- data.modelScope === undefined ? {} : { scope: data.modelScope },
3522
+ agentConfig.modelProvider ?? currentProvider,
3523
+ modelScopes.length === 0 ? {} : { scope: modelScopes },
3245
3524
  );
3246
3525
  const modelOverrideFromParent = inheritsParentModel(params.model as string | undefined, agentConfig.model, parentModel);
3247
3526
  let skillOverride: string[] | false | undefined = normalizeSkillInput(params.skill);
@@ -3296,7 +3575,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3296
3575
  return { content: [{ type: "text", text: validationError }], isError: true, details: { mode: "single", results: [] } };
3297
3576
  }
3298
3577
  const structuredRuntime = params.outputSchema
3299
- ? createStructuredOutputRuntime(params.outputSchema, artifactConfig.enabled ? path.join(artifactsDir, "structured-output", runId) : undefined)
3578
+ ? createStructuredOutputRuntime(params.outputSchema, artifactConfig.enabled ? path.join(artifactsDir, "structured-output", runId) : undefined, { captureAcceptanceReport: params.acceptance !== false })
3300
3579
  : undefined;
3301
3580
  // Reads: caller override > agent defaultReads > none. `~`/`~/` expand to home;
3302
3581
  // absolute paths pass through; relative paths resolve against the child cwd.
@@ -3380,11 +3659,14 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3380
3659
  nestedRoute: foregroundControl?.nestedRoute,
3381
3660
  index: 0,
3382
3661
  modelOverride,
3662
+ fast: params.fast,
3383
3663
  modelOverrideFromParent,
3384
3664
  thinkingOverride: thinkingOverrideForTask(params.agent!, 0, modelOverride, modelOverrideFromParent),
3665
+ thinkingCeiling: agentConfig.maxThinking,
3666
+ extensionBindings: params.extensionBindings,
3385
3667
  availableModels,
3386
3668
  preferredModelProvider: currentProvider,
3387
- modelScope: data.modelScope,
3669
+ modelScope: modelScopes,
3388
3670
  skills: effectiveSkills,
3389
3671
  structuredOutput: structuredRuntime,
3390
3672
  agentContract: params.agentContract,
@@ -3494,7 +3776,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
3494
3776
  usageBudget: usageBudgetState(data.usageBudget, totalCost),
3495
3777
  ...(worktreeHandoff?.reference ? { parallelHandoff: worktreeHandoff.reference } : {}),
3496
3778
  }));
3497
- rememberForegroundRun(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: details.results });
3779
+ rememberForegroundRun(deps.state, { runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: details.results, extensionBindings: params.extensionBindings });
3498
3780
 
3499
3781
  const suppressRoutineResultIntercom = shouldSuppressRoutineResultIntercom({ suppressRoutineResultIntercom: params.suppressRoutineResultIntercom, results: [r] });
3500
3782
  if (!r.detached && !r.interrupted && !suppressRoutineResultIntercom) {
@@ -3649,7 +3931,9 @@ function workflowChildResult(
3649
3931
  ? result.details.results[0].finalOutput
3650
3932
  : receiptOutput;
3651
3933
  const detached = result.details.results.some((child) => child.detached);
3652
- const ok = result.isError !== true && !detached;
3934
+ const interrupted = result.details.results.some((child) => child.interrupted);
3935
+ const stopped = result.details.results.some((child) => child.stopped);
3936
+ const ok = result.isError !== true && !detached && !interrupted && !stopped;
3653
3937
  const artifactPaths = new Set<string>();
3654
3938
  if (result.details.asyncDir) artifactPaths.add(result.details.asyncDir);
3655
3939
  if (result.details.parallelHandoff?.path) artifactPaths.add(result.details.parallelHandoff.path);
@@ -3689,6 +3973,8 @@ function workflowChildResult(
3689
3973
  output,
3690
3974
  ...(!ok ? { error: receiptOutput || output || "Child run failed." } : {}),
3691
3975
  ...(detached ? { detached: true } : {}),
3976
+ ...(interrupted ? { interrupted: true } : {}),
3977
+ ...(stopped ? { stopped: true } : {}),
3692
3978
  ...(structured.length === 1 ? { structuredOutput: structured[0] } : structured.length > 1 ? { structuredOutput: structured } : {}),
3693
3979
  ...(requestedContext ? { requestedContext } : {}),
3694
3980
  ...(resolvedContext ? { resolvedContext } : {}),
@@ -3813,8 +4099,9 @@ export function prepareWorkflowLaunchParams(
3813
4099
  childParams: Record<string, unknown>,
3814
4100
  parentWorkflowRunId: string,
3815
4101
  workflowKey: string,
3816
- options: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number } = {},
4102
+ options: { missionDetached?: boolean; suppressRoutineResultIntercom?: boolean; runFanoutBudget?: RunFanoutBudgetDescriptor; parentDeadlineAt?: number; externalAsyncRequired?: boolean; capabilityCeiling?: ResolvedSubagentCapabilityCeiling } = {},
3817
4103
  ): SubagentParamsLike {
4104
+ const capabilityCeiling = intersectSubagentCapabilityCeilings(workflowDefaults.capabilityCeiling, options.capabilityCeiling);
3818
4105
  const parentTimeoutMs = options.parentDeadlineAt === undefined
3819
4106
  || childParams.timeoutMs !== undefined
3820
4107
  || childParams.maxRuntimeMs !== undefined
@@ -3823,6 +4110,9 @@ export function prepareWorkflowLaunchParams(
3823
4110
  ? undefined
3824
4111
  : Math.max(1, options.parentDeadlineAt - Date.now());
3825
4112
  if (typeof childParams.resume === "string") {
4113
+ if (childParams.extensionBindings !== undefined || workflowDefaults.extensionBindings !== undefined) {
4114
+ throw new Error("extensionBindings is not supported with retained resume; resume uses the original retained child binding.");
4115
+ }
3826
4116
  if (childParams.gate !== undefined || workflowDefaults.gate !== undefined) {
3827
4117
  throw new Error("gate is not supported with retained resume; resume uses the retained child contract.");
3828
4118
  }
@@ -3845,19 +4135,23 @@ export function prepareWorkflowLaunchParams(
3845
4135
  ...(turnBudget !== undefined ? { turnBudget: turnBudget as TurnBudgetConfig } : {}),
3846
4136
  ...(toolBudget !== undefined ? { toolBudget: toolBudget as ToolBudgetConfig } : {}),
3847
4137
  ...(intercomBridge !== undefined ? { intercomBridge: intercomBridge as IntercomBridgeConfig } : {}),
4138
+ ...(capabilityCeiling ? { capabilityCeiling } : {}),
3848
4139
  };
3849
4140
  }
3850
4141
  const launchParams = {
3851
4142
  ...workflowDefaults,
3852
- async: false,
4143
+ async: options.externalAsyncRequired === true && childParams.async === undefined && workflowDefaults.async === undefined ? true : false,
3853
4144
  ...childParams,
4145
+ ...(options.externalAsyncRequired === true && childParams.async === undefined && workflowDefaults.async === undefined ? { workflowAwaitAsync: true } : {}),
3854
4146
  ...(options.missionDetached ? { mission: false } : {}),
3855
4147
  workflowParentRunId: parentWorkflowRunId,
3856
4148
  workflowKey,
3857
4149
  ...(parentTimeoutMs !== undefined ? { workflowParentDeadlineAt: options.parentDeadlineAt } : {}),
3858
4150
  ...(options.runFanoutBudget ? { runFanoutBudget: { ...options.runFanoutBudget, parentPath: `${options.runFanoutBudget.parentPath ? `${options.runFanoutBudget.parentPath}/` : ""}workflow[${workflowKey}]` } } : {}),
3859
4151
  ...(options.suppressRoutineResultIntercom ? { suppressRoutineResultIntercom: true } : {}),
4152
+ ...(capabilityCeiling ? { capabilityCeiling } : {}),
3860
4153
  } as SubagentParamsLike;
4154
+ if (launchParams.extensionBindings !== undefined) launchParams.extensionBindings = normalizeExtensionBindings(launchParams.extensionBindings)!.value;
3861
4155
  const normalizedGate = normalizeGateParams(launchParams);
3862
4156
  if (!normalizedGate.ok) throw new Error(normalizedGate.error);
3863
4157
  return normalizedGate.params;
@@ -3914,6 +4208,7 @@ function createScheduledOwnerState(source: SubagentState, ownerSessionId: string
3914
4208
  parentSessionFile: ctx.sessionManager.getSessionFile() ?? null,
3915
4209
  subagentInProgress: false,
3916
4210
  ...(ownerSpawns ? { subagentSpawns: ownerSpawns } : { subagentSpawns: undefined }),
4211
+ herdrProjectPanes: new Map(),
3917
4212
  asyncJobs: new Map(),
3918
4213
  fleetJobs: new Map(),
3919
4214
  foregroundRuns: new Map(),
@@ -3927,6 +4222,7 @@ function createScheduledOwnerState(source: SubagentState, ownerSessionId: string
3927
4222
  watcherRestartTimer: null,
3928
4223
  waitSubscriptions: new Map(),
3929
4224
  workflowControllers: new Map(),
4225
+ workflowChildStops: new Map(),
3930
4226
  };
3931
4227
  }
3932
4228
 
@@ -3991,12 +4287,21 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
3991
4287
  if (!normalizedGate.ok) return buildRequestedModeError(params, normalizedGate.error);
3992
4288
  const requestParams = normalizedGate.params;
3993
4289
  const normalizedAction = typeof requestParams.action === "string" ? requestParams.action.trim() : requestParams.action;
4290
+ if (normalizedAction === "resume" && requestParams.extensionBindings !== undefined) return buildRequestedModeError(requestParams, "extensionBindings is not supported with action='resume'; resume uses the original retained child binding.");
3994
4291
  if (requestParams.workflowScript !== undefined && normalizedAction === undefined) {
4292
+ if (requestParams.extensionBindings !== undefined) {
4293
+ try {
4294
+ requestParams.extensionBindings = normalizeExtensionBindings(requestParams.extensionBindings)!.value;
4295
+ } catch (error) {
4296
+ return buildRequestedModeError(requestParams, error instanceof Error ? error.message : String(error));
4297
+ }
4298
+ }
3995
4299
  const parentCwd = ctx.cwd;
3996
4300
  const timeout = requestParams.timeoutMs ?? requestParams.maxRuntimeMs ?? (requestParams.async === false ? resolveConfigDefaultTimeoutMs(deps.config.timeoutMs) ?? DEFAULT_FOREGROUND_TIMEOUT_MS : undefined);
3997
4301
  const workflowUsageBudget = validateUsageBudgetConfig(requestParams.usageBudget ?? deps.config.usageBudget, requestParams.usageBudget ? "usageBudget" : "config.usageBudget");
3998
4302
  if (workflowUsageBudget.error) return buildRequestedModeError(requestParams, workflowUsageBudget.error);
3999
4303
  const workflowCwd = resolveRequestedCwd(parentCwd, requestParams.cwd);
4304
+ const workflowAgents = deps.discoverAgents(workflowCwd, resolveExecutionAgentScope(requestParams.agentScope)).agents;
4000
4305
  const workflowArtifactConfig: ArtifactConfig = omitUndefinedProperties({
4001
4306
  ...DEFAULT_ARTIFACT_CONFIG,
4002
4307
  enabled: requestParams.artifacts !== false,
@@ -4093,6 +4398,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4093
4398
  const eventsPath = path.join(asyncDir, "events.jsonl");
4094
4399
  const startedAt = Date.now();
4095
4400
  const currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
4401
+ const workflowCapabilityCeiling = intersectSubagentCapabilityCeilings(requestParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(currentSessionId));
4096
4402
  const completionOwnerId = deps.state.completionOwnerId ?? currentCompletionOwnerId();
4097
4403
  deps.state.completionOwnerId = completionOwnerId;
4098
4404
  try {
@@ -4105,6 +4411,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4105
4411
  }
4106
4412
  const controller = new AbortController();
4107
4413
  deps.state.workflowControllers ??= new Map();
4414
+ deps.state.workflowChildStops ??= new Map();
4108
4415
  deps.state.workflowControllers.set(workflowRunId, controller);
4109
4416
  workflowCapacity?.markWorkflowStarted();
4110
4417
  if (workflowCapacity) deps.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers.keys()) });
@@ -4272,7 +4579,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4272
4579
  const { action: _action, agent: _agent, task: _task, resume: _resume, tasks: _tasks, chain: _chain, concurrency: _concurrency, foregroundOnly: _foregroundOnly, clarify: _clarify, timeoutMs: _timeoutMs, maxRuntimeMs: _maxRuntimeMs, usageBudget: _usageBudget, missionId: _missionId, mission: _mission, ...workflowChildDefaults } = workflowRequest;
4273
4580
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
4274
4581
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
4275
- const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId), configuredOutputBaseDir);
4582
+ const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, workflowRunId));
4276
4583
  const claimedOutputPaths = new Map<string, string>();
4277
4584
  const childOutputOverrides = new Map<string, string>();
4278
4585
  const producedChildOutputPaths = new Set<string>();
@@ -4333,6 +4640,23 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4333
4640
  status.steps?.push(step);
4334
4641
  workflowSteps.set(entry.key, step);
4335
4642
  }
4643
+ const projectedStep = workflowSteps.get(entry.key);
4644
+ if (entry.state === "stopped" && projectedStep) {
4645
+ appendWorkflowEvent({
4646
+ type: "subagent.child-status",
4647
+ version: 1,
4648
+ childId: entry.key,
4649
+ status: "stopped",
4650
+ reason: "user",
4651
+ source: "async",
4652
+ stepIndex: status.steps?.indexOf(projectedStep),
4653
+ agent: projectedStep.agent,
4654
+ ...(projectedStep.runId ? { childRunId: projectedStep.runId } : {}),
4655
+ workflowKey: entry.key,
4656
+ ...(projectedStep.phase ? { phase: projectedStep.phase } : {}),
4657
+ ...(projectedStep.label ? { label: projectedStep.label } : {}),
4658
+ });
4659
+ }
4336
4660
  }
4337
4661
  projectedTraceLength = trace.length;
4338
4662
  projectedTraceTail = trace.at(-1);
@@ -4345,10 +4669,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4345
4669
  script: workflowScript,
4346
4670
  timeoutMs: timeout,
4347
4671
  signal: controller.signal,
4672
+ registerStopChild: (stop) => {
4673
+ if (stop) deps.state.workflowChildStops?.set(workflowRunId, stop);
4674
+ else deps.state.workflowChildStops?.delete(workflowRunId);
4675
+ },
4348
4676
  ...(workflowState ? { state: workflowState } : {}),
4349
4677
  onTrace: updateTrace,
4350
4678
  admit: (calls) => {
4351
- const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
4679
+ const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
4352
4680
  if (outputClaims.error) throw new Error(outputClaims.error);
4353
4681
  status.runFanoutBudget = claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
4354
4682
  if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
@@ -4376,7 +4704,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4376
4704
  });
4377
4705
  const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, () => {
4378
4706
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
4379
- { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), options: { missionDetached: detachWorkflowChildMissions, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt } }), runFanoutAdmitted: admission.admitted },
4707
+ { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), options: { missionDetached: detachWorkflowChildMissions, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
4380
4708
  missionBinding,
4381
4709
  deps.asyncByDefault,
4382
4710
  );
@@ -4463,7 +4791,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4463
4791
  } catch (receiptError) {
4464
4792
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
4465
4793
  }
4466
- 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, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
4794
+ if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: true, state: "complete", summary: resultSummary, output: resultSummary, results: workflow.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
4467
4795
  persist();
4468
4796
  persistClosed = true;
4469
4797
  appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(status.error ? { error: status.error } : {}) });
@@ -4503,13 +4831,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4503
4831
  } catch (receiptError) {
4504
4832
  appendWorkflowEvent({ type: "subagent.workflow.receipt_write_failed", error: `Failed to persist async workflow receipt: ${receiptError instanceof Error ? receiptError.message : String(receiptError)}` });
4505
4833
  }
4506
- if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: status.state === "complete", state: status.state, summary: resultSummary, error: status.state === "complete" ? undefined : status.error, stopped: status.stopped, activityState: status.activityState, results: partial.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.detached && status.state !== "complete" ? { detached: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
4834
+ if (!writeWorkflowResult({ id: workflowRunId, runId: workflowRunId, toolCallId, agent: "workflow", mode: "workflow", success: status.state === "complete", state: status.state, summary: resultSummary, error: status.state === "complete" ? undefined : status.error, stopped: status.stopped, activityState: status.activityState, results: partial.children.map((child) => ({ workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, success: child.ok, ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(child.detached && status.state !== "complete" ? { detached: true } : {}), ...(child.artifactPaths[0] ? { artifactPaths: { outputPath: child.artifactPaths[0] } } : {}) })), workflow: status.workflow, ...(workflowReceipt ? { workflowReceipt } : {}), asyncDir, cwd: workflowCwd, sessionId: currentSessionId, completionOwnerId, ...(requestParams.scheduleOrigin ? { scheduleOrigin: requestParams.scheduleOrigin } : {}), timestamp: Date.now(), durationMs: Date.now() - startedAt })) return;
4507
4835
  persist();
4508
4836
  persistClosed = true;
4509
4837
  appendWorkflowEvent({ type: "subagent.workflow.completed", state: status.state, ...(status.error ? { error: status.error } : {}), ...(status.activityState ? { activityState: status.activityState } : {}) });
4510
4838
  } finally {
4511
4839
  persistClosed = true;
4512
4840
  deps.state.workflowControllers?.delete(workflowRunId);
4841
+ deps.state.workflowChildStops?.delete(workflowRunId);
4513
4842
  deps.state.activeAsyncCapacity = workflowCapacity?.reconcile(new Set(deps.state.workflowControllers?.keys() ?? []))
4514
4843
  ?? deps.state.activeAsyncCapacity;
4515
4844
  }
@@ -4522,7 +4851,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4522
4851
  const { workflowScript: _workflowScript, action: _action, agent: _agent, task: _task, resume: _resume, tasks: _tasks, chain: _chain, concurrency: _concurrency, async: _async, foregroundOnly: _foregroundOnly, clarify: _clarify, timeoutMs: _timeoutMs, maxRuntimeMs: _maxRuntimeMs, usageBudget: _usageBudget, chatProgress: _chatProgress, missionId: _missionId, mission: _mission, ...workflowChildDefaults } = requestParams;
4523
4852
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
4524
4853
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
4525
- const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, _id), configuredOutputBaseDir);
4854
+ const workflowAggregateOutputPath = resolveWorkflowAggregateOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, _id));
4526
4855
  const claimedOutputPaths = new Map<string, string>();
4527
4856
  const childOutputOverrides = new Map<string, string>();
4528
4857
  const producedChildOutputPaths = new Set<string>();
@@ -4530,6 +4859,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4530
4859
  const workflowChildRunIds = new Map<string, string>();
4531
4860
  let liveWorkflow: NonNullable<Details["workflow"]> = { trace: [], emits: [], console: [] };
4532
4861
  const workflowDeadlineAt = timeout === undefined ? undefined : Date.now() + timeout;
4862
+ const workflowCapabilityCeiling = intersectSubagentCapabilityCeilings(requestParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(resolveCurrentSessionId(ctx.sessionManager)));
4533
4863
  const sendWorkflowProgress = () => {
4534
4864
  const update = workflowChatProgressUpdate(_id, chatProgress, liveWorkflow);
4535
4865
  if (update) onUpdate?.(update);
@@ -4545,7 +4875,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4545
4875
  sendWorkflowProgress();
4546
4876
  },
4547
4877
  admit: (calls) => {
4548
- const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId: _id, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
4878
+ const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId: _id, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
4549
4879
  if (outputClaims.error) throw new Error(outputClaims.error);
4550
4880
  claimRunFanoutBatch(workflowFanoutBudget, calls.map(({ key }) => `workflow[${key}]`));
4551
4881
  if (outputClaims.claims) applyWorkflowChildOutputClaims(claimedOutputPaths, outputClaims.claims);
@@ -4570,7 +4900,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4570
4900
  });
4571
4901
  const result = await runMissionWorkflowChild(missionBinding, _id, key, childPhase, () => {
4572
4902
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
4573
- { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: _id, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt } }), runFanoutAdmitted: admission.admitted },
4903
+ { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: _id, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: deps.discoverAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
4574
4904
  missionBinding,
4575
4905
  deps.asyncByDefault,
4576
4906
  );
@@ -4693,7 +5023,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
4693
5023
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
4694
5024
  return { content: [{ type: "text", text: `Action '${action}' is not available from child-safe subagent fanout mode.` }], isError: true, details: { mode: "management", results: [] } };
4695
5025
  }
4696
- return handleHerdrProjectPaneAction(action as (typeof HERDR_PROJECT_PANE_ACTIONS)[number], paramsWithResolvedCwd, { cwd: requestCwd, signal });
5026
+ deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
5027
+ return handleHerdrProjectPaneAction(action as (typeof HERDR_PROJECT_PANE_ACTIONS)[number], paramsWithResolvedCwd, { cwd: requestCwd, state: deps.state, signal });
4697
5028
  }
4698
5029
  if ((HERDR_INSPECTOR_ACTIONS as readonly string[]).includes(action)) {
4699
5030
  if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
@@ -5104,6 +5435,40 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5104
5435
  const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
5105
5436
  const workflowController = targetRunId ? deps.state.workflowControllers?.get(targetRunId) : undefined;
5106
5437
  if (workflowController) {
5438
+ if (paramsWithResolvedCwd.childId !== undefined) {
5439
+ const workflowRunId = targetRunId!;
5440
+ const asyncJob = deps.state.asyncJobs.get(workflowRunId);
5441
+ if (!asyncJob?.asyncDir) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
5442
+ const status = readStatus(asyncJob.asyncDir);
5443
+ if (!status) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
5444
+ const resolution = resolveAsyncStatusChild(status, paramsWithResolvedCwd.childId);
5445
+ if (!resolution.ok) return { content: [{ type: "text", text: resolution.message }], isError: true, details: { mode: "management", results: [] } };
5446
+ if (!isStoppableAsyncStatusStep(resolution.child.step)) return { content: [{ type: "text", text: `Child '${paramsWithResolvedCwd.childId}' in async run '${targetRunId}' is ${resolution.child.step.status}; stop only supports pending or running children.` }], isError: true, details: { mode: "management", results: [] } };
5447
+ const stopChild = deps.state.workflowChildStops?.get(targetRunId!);
5448
+ if (!stopChild) return { content: [{ type: "text", text: `Workflow ${targetRunId} child stop is unavailable in this extension runtime.` }], isError: true, details: { mode: "management", results: [] } };
5449
+ if (!stopChild(resolution.child.id)) return { content: [{ type: "text", text: `Child '${paramsWithResolvedCwd.childId}' in workflow ${workflowRunId} is not available to stop.` }], isError: true, details: { mode: "management", results: [] } };
5450
+ try {
5451
+ fs.appendFileSync(path.join(asyncJob.asyncDir, "events.jsonl"), `${JSON.stringify({
5452
+ type: "subagent.child-status",
5453
+ version: 1,
5454
+ runId: workflowRunId,
5455
+ childId: resolution.child.id,
5456
+ status: "stopping",
5457
+ ts: Date.now(),
5458
+ reason: "user",
5459
+ source: "async",
5460
+ stepIndex: resolution.child.index,
5461
+ agent: resolution.child.step.agent,
5462
+ ...(resolution.child.step.runId ? { childRunId: resolution.child.step.runId } : {}),
5463
+ ...(resolution.child.step.workflowKey ? { workflowKey: resolution.child.step.workflowKey } : {}),
5464
+ ...(resolution.child.step.phase ? { phase: resolution.child.step.phase } : {}),
5465
+ ...(resolution.child.step.label ? { label: resolution.child.step.label } : {}),
5466
+ } satisfies SubagentChildStatusEvent)}\n`, "utf-8");
5467
+ } catch (error) {
5468
+ console.error(`Failed to append child status event for workflow ${workflowRunId}:`, error);
5469
+ }
5470
+ return { content: [{ type: "text", text: `Stop requested for child ${resolution.child.id} in async workflow ${workflowRunId}.` }], details: { mode: "management", results: [] } };
5471
+ }
5107
5472
  workflowController.abort(new Error("Workflow stopped by user."));
5108
5473
  return { content: [{ type: "text", text: `Stop requested for async workflow ${targetRunId}.` }], details: { mode: "management", results: [] } };
5109
5474
  }
@@ -5115,7 +5480,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5115
5480
  if (existingStatus?.mode === "workflow" && existingStatus.state === "running") {
5116
5481
  return { content: [{ type: "text", text: `Workflow ${existingStatus.runId} is not controlled by this extension runtime; reload recovery cannot stop it safely.` }], isError: true, details: { mode: "management", results: [] } };
5117
5482
  }
5118
- const stopResult = stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location);
5483
+ const stopResult = stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location, paramsWithResolvedCwd.childId);
5119
5484
  return stopResult ?? { content: [{ type: "text", text: `No running or queued async run was found for '${targetRunId ?? paramsWithResolvedCwd.dir}'.` }], isError: true, details: { mode: "management", results: [] } };
5120
5485
  } catch (error) {
5121
5486
  const text = error instanceof Error ? error.message : String(error);
@@ -5142,6 +5507,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5142
5507
  resolved?.kind === "async" ? resolved.id : targetRunId,
5143
5508
  deps.kill,
5144
5509
  resolved?.kind === "async" ? resolved.location : undefined,
5510
+ paramsWithResolvedCwd.childId,
5145
5511
  );
5146
5512
  if (stopResult) return stopResult;
5147
5513
  return {
@@ -5333,13 +5699,13 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5333
5699
  agentConfig?.model,
5334
5700
  parentModel,
5335
5701
  forkAvailableModels,
5336
- parentModel?.provider,
5702
+ agentConfig?.modelProvider ?? parentModel?.provider,
5337
5703
  );
5338
5704
  const candidates = buildModelCandidates(
5339
5705
  primaryModel,
5340
5706
  agentConfig?.fallbackModels,
5341
5707
  forkAvailableModels,
5342
- parentModel?.provider,
5708
+ agentConfig?.modelProvider ?? parentModel?.provider,
5343
5709
  { primaryModelFromParent: modelOverrideFromParent ?? inheritsParentModel(modelOverride, agentConfig?.model, parentModel) },
5344
5710
  );
5345
5711
  forkThinkingRequirements.set(
@@ -5356,9 +5722,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5356
5722
  } catch (error) {
5357
5723
  return toExecutionErrorResult(effectiveParams, error, contextPolicy.contextSummary);
5358
5724
  }
5359
- const requestedAsync = effectiveParams.async ?? deps.asyncByDefault;
5360
- const backgroundRequestedWhileClarifying = (hasChain || hasTasks) && requestedAsync && effectiveParams.clarify === true;
5361
- const effectiveAsync = requestedAsync && effectiveParams.clarify !== true;
5362
5725
  const selectedAgentNames = hasSingle
5363
5726
  ? [effectiveParams.agent!]
5364
5727
  : hasTasks
@@ -5367,6 +5730,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5367
5730
  const externalAgent = selectedAgentNames
5368
5731
  .map((name) => agents.find((agent) => agent.name === name))
5369
5732
  .find((agent) => agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job");
5733
+ const externalAsyncRequired = Boolean(externalAgent) && effectiveParams.async === undefined && effectiveParams.clarify !== true && effectiveParams.foregroundOnly !== true;
5734
+ const requestedAsync = externalAsyncRequired ? true : effectiveParams.async ?? deps.asyncByDefault;
5735
+ const backgroundRequestedWhileClarifying = (hasChain || hasTasks) && requestedAsync && effectiveParams.clarify === true;
5736
+ const effectiveAsync = requestedAsync && effectiveParams.clarify !== true;
5370
5737
  if (externalAgent && (!effectiveAsync || effectiveParams.foregroundOnly === true)) {
5371
5738
  return buildRequestedModeError(effectiveParams, `Agent '${externalAgent.name}' uses runner.type='${externalAgent.runner?.type}', which currently supports async/background execution only. Omit async or pass async:true; clarify and foregroundOnly are unsupported.`);
5372
5739
  }
@@ -5571,7 +5938,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5571
5938
  parentModel: requestParentModel,
5572
5939
  parentSessionId: requestSessionId,
5573
5940
  parentPiSessionId: requestPiSessionId,
5574
- capabilityCeiling: resolveCurrentSubagentCapabilityCeiling(requestSessionId),
5941
+ capabilityCeiling: intersectSubagentCapabilityCeilings(effectiveParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(requestSessionId)),
5575
5942
  runFanoutBudget,
5576
5943
  topLevelAsyncCapacityEligible,
5577
5944
  activeAsyncCapacity,
@@ -5755,7 +6122,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5755
6122
  workflowLaunchObserver(launch);
5756
6123
  }
5757
6124
  }
5758
- const asyncResult = runAsyncPath(execData, deps);
6125
+ const asyncResult = await runAsyncPath(execData, deps);
5759
6126
  if (asyncResult) {
5760
6127
  asyncLaunchFailed = asyncResult.isError === true;
5761
6128
  return attachMission(withRunFanoutBudget(withResolvedContext(withForkThinkingNotes(asyncResult, forkThinkingDowngrades), contextPolicy.contextSummary), runFanoutBudget));