@xzzpig/pi-subagents 0.20.0 → 0.21.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 (140) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +34 -17
  13. package/docs/models.md +1 -1
  14. package/docs/observability.md +10 -5
  15. package/docs/tool-reference.md +117 -84
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +16 -7
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +191 -145
  32. package/src/api/preflight.ts +8 -4
  33. package/src/extension/config.ts +21 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +114 -132
  40. package/src/extension/reply-workflow-script.ts +20 -11
  41. package/src/extension/rpc.ts +11 -6
  42. package/src/extension/schemas.ts +34 -30
  43. package/src/extension/subagent-guide.ts +86 -6
  44. package/src/extension/subagent-options.ts +47 -0
  45. package/src/extension/tool-activation.ts +3 -2
  46. package/src/extension/tool-description.ts +51 -68
  47. package/src/inspectors/actions.ts +37 -11
  48. package/src/inspectors/plugins.ts +3 -2
  49. package/src/inspectors/tmux/actions.ts +204 -0
  50. package/src/inspectors/tmux/client.ts +85 -0
  51. package/src/inspectors/tmux/plugin.ts +21 -0
  52. package/src/integrations/herdr-status.ts +18 -49
  53. package/src/integrations/program-status.ts +215 -0
  54. package/src/intercom/native-supervisor-channel.ts +77 -4
  55. package/src/intercom/result-intercom.ts +3 -2
  56. package/src/intercom/supervisor-ui.ts +2 -174
  57. package/src/missions/store.ts +25 -5
  58. package/src/profiles/profiles.ts +24 -21
  59. package/src/runs/background/active-async-capacity.ts +58 -8
  60. package/src/runs/background/async-execution.ts +143 -38
  61. package/src/runs/background/async-job-tracker.ts +11 -4
  62. package/src/runs/background/async-resume.ts +5 -2
  63. package/src/runs/background/await-async-run.ts +14 -9
  64. package/src/runs/background/binary-bootstrap.ts +2 -1
  65. package/src/runs/background/calendar-schedule.ts +90 -0
  66. package/src/runs/background/chain-root-attachment.ts +9 -5
  67. package/src/runs/background/fleet-view.ts +5 -5
  68. package/src/runs/background/notify.ts +185 -12
  69. package/src/runs/background/result-files.ts +116 -5
  70. package/src/runs/background/result-watcher.ts +99 -66
  71. package/src/runs/background/resume-guidance.ts +2 -2
  72. package/src/runs/background/run-child-session.ts +16 -2
  73. package/src/runs/background/run-id-resolver.ts +8 -5
  74. package/src/runs/background/run-status.ts +21 -16
  75. package/src/runs/background/runner-child-launch.ts +1 -0
  76. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  77. package/src/runs/background/scheduled-runs.ts +256 -61
  78. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  79. package/src/runs/background/subagent-runner.ts +32 -12
  80. package/src/runs/background/subagent-wait.ts +38 -19
  81. package/src/runs/background/terminal-run-index.ts +46 -1
  82. package/src/runs/background/wait-completions.ts +1 -0
  83. package/src/runs/background/wait-tool.ts +33 -23
  84. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  85. package/src/runs/foreground/async-stop-action.ts +48 -22
  86. package/src/runs/foreground/execution.ts +94 -52
  87. package/src/runs/foreground/foreground-history.ts +1 -0
  88. package/src/runs/foreground/subagent-executor.ts +207 -77
  89. package/src/runs/shared/child-commands.ts +2 -1
  90. package/src/runs/shared/child-hooks.ts +4 -3
  91. package/src/runs/shared/child-launch.ts +3 -0
  92. package/src/runs/shared/child-session.ts +41 -24
  93. package/src/runs/shared/child-tool-plan.ts +13 -26
  94. package/src/runs/shared/dynamic-fanout.ts +1 -1
  95. package/src/runs/shared/fork-command-result.ts +10 -0
  96. package/src/runs/shared/herdr-placed-run.ts +5 -4
  97. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  98. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  99. package/src/runs/shared/model-resolution.ts +30 -1
  100. package/src/runs/shared/nested-events.ts +5 -0
  101. package/src/runs/shared/parallel-handoff.ts +56 -8
  102. package/src/runs/shared/parallel-utils.ts +2 -0
  103. package/src/runs/shared/partial-output.ts +48 -0
  104. package/src/runs/shared/runner-launcher.ts +25 -0
  105. package/src/runs/shared/single-output.ts +53 -0
  106. package/src/runs/shared/structured-output.ts +14 -7
  107. package/src/runs/shared/subagent-control.ts +3 -3
  108. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  109. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  110. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  111. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  112. package/src/runs/shared/worktree-lock.ts +29 -0
  113. package/src/runs/shared/worktree.ts +12 -1
  114. package/src/shared/atomic-json.ts +4 -2
  115. package/src/shared/edit-distance.ts +33 -0
  116. package/src/shared/file-lease.ts +74 -0
  117. package/src/shared/formatters.ts +1 -5
  118. package/src/shared/model-info.ts +22 -0
  119. package/src/shared/package-version.ts +17 -0
  120. package/src/shared/parent-wake.ts +79 -0
  121. package/src/shared/pruned-fork.ts +7 -1
  122. package/src/shared/runtime-module-path.ts +19 -0
  123. package/src/shared/settings-file-lease.ts +36 -0
  124. package/src/shared/types.ts +36 -2
  125. package/src/shared/utils.ts +8 -6
  126. package/src/slash/slash-commands.ts +3 -3
  127. package/src/slash/subagents-admin.ts +2 -1
  128. package/src/tui/fleet-native-transcript.ts +2 -0
  129. package/src/tui/fleet-transcript.ts +12 -3
  130. package/src/tui/fleet.ts +11 -8
  131. package/src/tui/render.ts +27 -19
  132. package/src/tui/subagent-messages.ts +305 -0
  133. package/src/watchdog/diff-tool.ts +2 -2
  134. package/src/watchdog/register-main.ts +2 -22
  135. package/src/watchdog/render.ts +2 -24
  136. package/src/watchdog/runtime.ts +6 -4
  137. package/src/watchdog/settings.ts +18 -13
  138. package/src/watchdog/tool-actions.ts +2 -2
  139. package/src/workflows/scripted-workflow.ts +20 -6
  140. package/src/workflows/workflow-resources.ts +11 -0
@@ -3,7 +3,7 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
5
5
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
6
- import { discoverAgents, discoverAgentsAll, findBlockingAgentDiagnostic, formatUnknownAgentError, resolveAgentName, unknownAgentDiagnosticContext, type AgentConfig, type AgentDiscoveryDiagnostic, type AgentScope, type UnknownAgentDiagnosticContext } from "../../agents/agents.ts";
6
+ import { discoverAgents, discoverAgentsAll, findBlockingAgentDiagnostic, formatAvailableAgentLines, formatUnknownAgentError, resolveAgentName, suggestAgentName, unknownAgentDiagnosticContext, type AgentConfig, type AgentDiscoveryDiagnostic, type AgentScope, type UnknownAgentDiagnosticContext } from "../../agents/agents.ts";
7
7
  import { getArtifactsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir } from "../../shared/artifacts.ts";
8
8
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
9
9
  import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilient-json.ts";
@@ -18,7 +18,7 @@ import {
18
18
  } from "./foreground-control.ts";
19
19
  import { getLivePromptAudit, rewritePromptWithGuidance, updateLiveEffectivePrompt } from "./prompt-audit.ts";
20
20
  import { persistForegroundRunHistory, MAX_REMEMBERED_FOREGROUND_RUNS } from "./foreground-history.ts";
21
- import { resolveExecutionAgentScope } from "../../agents/agent-scope.ts";
21
+ import { projectScopeRequiresTrustMessage, resolveExecutionAgentScope } from "../../agents/agent-scope.ts";
22
22
  import { handleManagementAction } from "../../agents/agent-management.ts";
23
23
  import { handleRefinementAction } from "../../agents/agent-refinements.ts";
24
24
  import { buildDoctorReport } from "../../extension/doctor.ts";
@@ -77,10 +77,10 @@ import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeili
77
77
  import { isAgentContract } from "../shared/agent-contract.ts";
78
78
  import { normalizeExtensionBindings, type ExtensionBindings } from "../shared/extension-bindings.ts";
79
79
  import { assertRequiredChildExtensionsAdmitted, hasMandatoryRequiredChildExtensions, readRetainedRequiredChildExtensions, resolveRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
80
- import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, outputPathMappingFromTask, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
80
+ import { capInlineOutput, finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, outputPathMappingFromTask, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
81
81
  import { assertJsonSchemaObject, cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
82
82
  import { compactForegroundDetails, getSingleResultOutput, PROMPT_REDACTED, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage, toAgentToolUsage } from "../../shared/utils.ts";
83
- import { discardPreservedWorktrees, formatParallelHandoffError, formatParallelHandoffReference, formatStoredParallelHandoffCleanup, parallelHandoffPath, readParallelHandoffManifest, recordParallelHandoffMerge, recordParallelHandoffSupersession, writeParallelHandoffGroup, writeWorktreeSetupHandoff } from "../shared/parallel-handoff.ts";
83
+ import { discardPreservedWorktrees, formatParallelHandoffError, formatParallelHandoffReference, protectRetainedWorktreeForResume, formatStoredParallelHandoffCleanup, parallelHandoffPath, readParallelHandoffManifest, recordParallelHandoffMerge, recordParallelHandoffSupersession, writeParallelHandoffGroup, writeWorktreeSetupHandoff } from "../shared/parallel-handoff.ts";
84
84
  import { summarizeContextModes, type ContextMode, type ContextSummary } from "../shared/context-mode.ts";
85
85
  import {
86
86
  attachNestedChildrenToResultChildren,
@@ -105,8 +105,8 @@ import { promotePausedWorkflowIfSettled, reconcileDetachedWorkflowChildCompletio
105
105
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
106
106
  import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
107
107
  import { awaitExistingAsyncRun, claimWorkflowAwaitedResult } from "../background/await-async-run.ts";
108
- import { fallbackResultPayloadPathForSessionRun, removeResultIndex, resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
109
- import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, inheritedNestedParentAddressOf, inheritedNestedRouteOf, nestedRunScope, resolveNestedAsyncDir, retainNestedLookupRoute, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedParentAddress, type NestedRoute, type NestedRunResolutionScope } from "../shared/nested-events.ts";
108
+ import { fallbackResultPayloadPathForSessionRun, resultFilePath, retireResultSnapshot, writeAsyncResultFile } from "../background/result-files.ts";
109
+ import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, inheritedNestedParentAddressOf, inheritedNestedRouteOf, nestedRunNotActiveMessage, nestedRunScope, resolveNestedAsyncDir, retainNestedLookupRoute, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedParentAddress, type NestedRoute, type NestedRunResolutionScope } from "../shared/nested-events.ts";
110
110
  import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
111
111
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
112
112
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
@@ -116,6 +116,7 @@ import { getExternalJobProvider } from "../../api/external-job-provider.ts";
116
116
  import { externalJobFollowUpRequestDigest, externalJobFollowUpRequestId, externalJobFollowUpRunId, externalJobPromptDigest, externalJobStableJson } from "../shared/external-job-runner.ts";
117
117
  import { externalCliReceiptMetadata, normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
118
118
  import { formatHerdrMachineRunnerUnsupported, resolveHerdrMachinePlacement } from "../shared/herdr-machine.ts";
119
+ import { lookupRunnerLauncher, resolveAgentRunnerLauncher } from "../shared/runner-launcher.ts";
119
120
  import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.ts";
120
121
  import { handleMissionAction, MISSION_ACTIONS } from "../../missions/actions.ts";
121
122
  import { attachMissionToLaunchResult, prepareMissionLaunch, writeMissionAsyncBinding, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
@@ -159,6 +160,7 @@ import {
159
160
  formatWorktreeDiffSummary,
160
161
  type WorktreeSetup,
161
162
  } from "../shared/worktree.ts";
163
+ import { applyReviewedCleanupPlan, formatCleanupReceipt, loadReviewedCleanupPlan } from "../shared/worktree-cleanup-apply.ts";
162
164
  import { createWorktreeCleanupPlan, formatWorktreeCleanupPlan } from "../shared/worktree-cleanup-plan.ts";
163
165
  import {
164
166
  type AgentProgress,
@@ -222,6 +224,7 @@ import {
222
224
  type SteeringTargetState,
223
225
  } from "../../shared/types.ts";
224
226
  import { deriveChildSessionName } from "../../shared/child-session-name.ts";
227
+ import { editDistance, hasSingleAdjacentTransposition } from "../../shared/edit-distance.ts";
225
228
 
226
229
  const MUTATING_MANAGEMENT_ACTIONS = new Set(["command.yield", "command.cancel", "create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "worktree.cleanup", "lane.recordMerge", "lane.recordSupersession", "refine", "refine.rollback", "dismiss", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
227
230
  const DESTRUCTIVE_MANAGEMENT_ACTIONS = new Set(["command.cancel", "delete", "eject", "disable", "reset", "mission.close", "worktree.discard", "refine.rollback", "inspector.close", "project.close", "stop", "interrupt", "schedule.delete"]);
@@ -230,31 +233,6 @@ function resolveSteerDeliveryMode(mode: SubagentParamsLike["mode"]): SteerDelive
230
233
  return mode === "steer" || mode === "follow_up" || mode === "auto" ? mode : undefined;
231
234
  }
232
235
 
233
- function editDistance(left: string, right: string): number {
234
- const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
235
- for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
236
- let diagonal = previous[0]!;
237
- previous[0] = leftIndex;
238
- for (let rightIndex = 1; rightIndex <= right.length; rightIndex += 1) {
239
- const above = previous[rightIndex]!;
240
- previous[rightIndex] = left[leftIndex - 1] === right[rightIndex - 1]
241
- ? diagonal
242
- : Math.min(diagonal, above, previous[rightIndex - 1]!) + 1;
243
- diagonal = above;
244
- }
245
- }
246
- return previous[right.length]!;
247
- }
248
-
249
- function hasSingleAdjacentTransposition(left: string, right: string): boolean {
250
- if (left.length !== right.length) return false;
251
- const mismatch = [...left].findIndex((character, index) => character !== right[index]);
252
- return mismatch >= 0
253
- && left[mismatch] === right[mismatch + 1]
254
- && left[mismatch + 1] === right[mismatch]
255
- && left.slice(mismatch + 2) === right.slice(mismatch + 2);
256
- }
257
-
258
236
  export function unknownSubagentActionMessage(action: string, disabled?: DisabledFeatureSurface): string {
259
237
  const requested = action.toLowerCase();
260
238
  const enabledActions = SUBAGENT_ACTIONS.filter((candidate) => !disabled?.actions.has(candidate));
@@ -435,7 +413,7 @@ export interface SubagentParamsLike {
435
413
  every?: string;
436
414
  sessionOnly?: boolean;
437
415
  quiet?: boolean;
438
- on?: string | number;
416
+ on?: string[];
439
417
  timezone?: string;
440
418
  overlap?: "skip";
441
419
  catchUp?: "none" | "latest";
@@ -461,6 +439,7 @@ function rememberParentModel(state: { currentSessionId?: string | null; lastPare
461
439
 
462
440
  interface ExecutorDeps {
463
441
  pi: ExtensionAPI;
442
+ parentWake?: Pick<ExtensionAPI, "sendMessage">;
464
443
  state: SubagentState;
465
444
  config: ExtensionConfig;
466
445
  asyncByDefault: boolean;
@@ -471,7 +450,7 @@ interface ExecutorDeps {
471
450
  tempArtifactsDir: string;
472
451
  getSubagentSessionRoot: (parentSessionFile: string | null) => string;
473
452
  expandTilde: (p: string) => string;
474
- discoverAgents: (cwd: string, scope: AgentScope, preferredModelProvider?: string) => { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig; maxThinking?: AgentConfig["maxThinking"]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] };
453
+ discoverAgents: (cwd: string, scope: AgentScope, preferredModelProvider?: string, options?: { projectTrusted?: boolean }) => { agents: AgentConfig[]; disabledAgents?: string[]; agentDiagnostics?: AgentDiscoveryDiagnostic[]; modelScope?: ModelScopeConfig; maxThinking?: AgentConfig["maxThinking"]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] };
475
454
  discoverAgentsAll?: typeof discoverAgentsAll;
476
455
  onAgentsChanged?: () => void;
477
456
  allowMutatingManagementActions?: boolean;
@@ -524,6 +503,7 @@ interface ExecutionContextData {
524
503
  backgroundRequestedWhileClarifying: boolean;
525
504
  effectiveAsync: boolean;
526
505
  asyncRunId: string;
506
+ toolCallId: string;
527
507
  controlConfig: ResolvedControlConfig;
528
508
  /** Structured delegation consumers do not need duration-only heartbeat snapshots. */
529
509
  suppressUnchangedDelegationUpdates?: boolean;
@@ -685,6 +665,20 @@ function sessionProjectTrust(ctx: ExtensionContext): boolean | undefined {
685
665
  return typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : undefined;
686
666
  }
687
667
 
668
+ /** Agent and settings discovery follows the launching session's trust, like the child itself. */
669
+ function withSessionProjectTrust(deps: ExecutorDeps, ctx: ExtensionContext): ExecutorDeps {
670
+ if (sessionProjectTrust(ctx) !== false) return deps;
671
+ return { ...deps, discoverAgents: (cwd, scope, preferredModelProvider) => deps.discoverAgents(cwd, scope, preferredModelProvider, { projectTrusted: false }) };
672
+ }
673
+
674
+ function projectScopeTrustError(params: SubagentParamsLike, ctx: ExtensionContext): AgentToolResult<Details> | undefined {
675
+ if (sessionProjectTrust(ctx) !== false || resolveExecutionAgentScope(params.agentScope) !== "project") return undefined;
676
+ const action = typeof params.action === "string" ? params.action.trim() : undefined;
677
+ // These actions resolve agents in the requested scope; management actions are left to their own handlers.
678
+ if (action !== undefined && action !== "resume" && action !== "validate" && action !== "append-step") return undefined;
679
+ return buildRequestedModeError(params, projectScopeRequiresTrustMessage(resolveRequestedCwd(ctx.cwd, params.cwd)));
680
+ }
681
+
688
682
  function spawnBudgetErrorResult(message: string, mode: "single" | "parallel" | "chain"): AgentToolResult<Details> {
689
683
  return {
690
684
  content: [{ type: "text", text: message }],
@@ -851,6 +845,7 @@ function rememberForegroundRun(state: SubagentState, input: { modelResponseAlias
851
845
  ...(result.error ? { error: result.error } : {}),
852
846
  ...(result.finalOutput ? { finalOutput: result.finalOutput } : {}),
853
847
  ...(result.outputState ? { outputState: result.outputState } : {}),
848
+ ...(result.outputPartial ? { outputPartial: true } : {}),
854
849
  ...(result.outputMode ? { outputMode: result.outputMode } : {}),
855
850
  ...(result.savedOutputPath ? { savedOutputPath: result.savedOutputPath } : {}),
856
851
  ...(result.outputSaveError ? { outputSaveError: result.outputSaveError } : {}),
@@ -936,6 +931,7 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
936
931
  ...(input.result.error ? { error: input.result.error } : {}),
937
932
  ...(input.result.finalOutput ? { finalOutput: input.result.finalOutput } : {}),
938
933
  outputState: input.result.outputState,
934
+ outputPartial: input.result.outputPartial,
939
935
  outputMode: input.result.outputMode,
940
936
  savedOutputPath: input.result.savedOutputPath,
941
937
  outputSaveError: input.result.outputSaveError,
@@ -1237,7 +1233,7 @@ function interruptAsyncRun(
1237
1233
  kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean,
1238
1234
  location?: { asyncDir: string | null; resolvedId?: string },
1239
1235
  ): AgentToolResult<Details> | null {
1240
- const target = getAsyncInterruptTarget(state, runId, location);
1236
+ const target = getAsyncInterruptTarget(state, runId, location, { fallbackToNewest: runId === undefined });
1241
1237
  if (!target) return null;
1242
1238
  const status = reconcileAsyncRun(target.asyncDir, omitUndefinedProperties({ kill })).status;
1243
1239
  if (!status || status.state !== "running" || typeof status.pid !== "number") {
@@ -1432,6 +1428,7 @@ function appendStepToAsyncChain(input: {
1432
1428
  cwd: input.ctx.cwd,
1433
1429
  currentSessionId: resolveCurrentSessionId(input.ctx.sessionManager),
1434
1430
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1431
+ parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
1435
1432
  currentModelProvider: parentModel?.provider,
1436
1433
  currentModel: parentModel,
1437
1434
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
@@ -1443,6 +1440,17 @@ function appendStepToAsyncChain(input: {
1443
1440
  permissions: input.deps.config.permissions,
1444
1441
  childRuntime: input.deps.childRuntime,
1445
1442
  });
1443
+ // Appended steps run inside the already-running runner, so they must use its launcher (or none).
1444
+ // Checked before building, which can write progress files. A mix is refused by the builder.
1445
+ const appendedLaunchers = new Set(chain.flatMap(getStepAgents).map((name) => agents.find((agent) => agent.name === name)?.launcher));
1446
+ const appendedLauncher = [...appendedLaunchers][0];
1447
+ if (appendedLaunchers.size === 1 && appendedLauncher !== status.launcher?.name) {
1448
+ return {
1449
+ content: [{ type: "text", text: `Cannot append step to run '${resolved.id}': its runner uses ${status.launcher ? `launcher '${status.launcher.name}'` : "no launcher"}, but the appended agents use ${appendedLauncher ? `launcher '${appendedLauncher}'` : "no launcher"}.` }],
1450
+ isError: true,
1451
+ details: { mode: "management", results: [] },
1452
+ };
1453
+ }
1446
1454
  const built = buildAsyncRunnerSteps(resolved.id, compactOptional<Parameters<typeof buildAsyncRunnerSteps>[1]>({
1447
1455
  chain: wrapChainTasksForFork(chain, contextPolicy),
1448
1456
  task: input.params.task,
@@ -1728,9 +1736,15 @@ async function interruptNestedRun(target: ResolvedSubagentRunId & { kind: "neste
1728
1736
  if (run.state === "failed") return { content: [{ type: "text", text: `Nested run ${run.id} has failed and cannot be interrupted.` }], isError: true, details: { mode: "management", results: [] } };
1729
1737
  if (run.state === "paused") return { content: [{ type: "text", text: `Nested run ${run.id} is already paused.` }], isError: true, details: { mode: "management", results: [] } };
1730
1738
  const result = await sendNestedControlRequest(target, "interrupt");
1731
- if (result) return { content: [{ type: "text", text: result.message }], ...(result.ok ? {} : { isError: true }), details: { mode: "management", results: [] } };
1739
+ // The owner's foreground map cannot address a detached async child. Only
1740
+ // that missing-route response may use the existing authorized async inbox;
1741
+ // other owner refusals must remain authoritative.
1742
+ const missingForegroundRoute = result?.ok === false && result.message === nestedRunNotActiveMessage(run.id);
1743
+ if (result && !missingForegroundRoute) return { content: [{ type: "text", text: result.message }], ...(result.ok ? {} : { isError: true }), details: { mode: "management", results: [] } };
1732
1744
  const direct = directNestedAsyncInterrupt(target);
1733
1745
  if (direct) return direct;
1746
+ // No async inbox either: the owner's own answer is the accurate one.
1747
+ if (result) return { content: [{ type: "text", text: result.message }], isError: true, details: { mode: "management", results: [] } };
1734
1748
  return { content: [{ type: "text", text: `Nested run ${run.id} owner is not reachable and no safe direct async interrupt fallback is available.` }], isError: true, details: { mode: "management", results: [] } };
1735
1749
  }
1736
1750
 
@@ -1867,6 +1881,7 @@ async function resumeExternalJobFollowUp(input: {
1867
1881
  cwd: input.requestCwd,
1868
1882
  currentSessionId,
1869
1883
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1884
+ parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
1870
1885
  currentModelProvider: parentModel?.provider,
1871
1886
  currentModel: parentModel,
1872
1887
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
@@ -1993,7 +2008,7 @@ async function resumeAsyncRun(input: {
1993
2008
  type: "text",
1994
2009
  text: [
1995
2010
  `Async child '${target.runId}' index ${target.index} is still running. action='resume' only revives paused, completed, or failed children.`,
1996
- `Send live input with subagent({ action: "steer", id: "${target.runId}", index: ${target.index}, message: "..." }).`,
2011
+ `Send live input with subagent({ action: "steer", id: "${target.runId}", message: "...", options: { index: ${target.index} } }).`,
1997
2012
  ].join("\n"),
1998
2013
  }],
1999
2014
  isError: true,
@@ -2056,6 +2071,18 @@ async function resumeAsyncRun(input: {
2056
2071
  : "External runners do not persist Pi sessions and cannot be resumed.";
2057
2072
  return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
2058
2073
  }
2074
+ if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
2075
+ return { content: [{ type: "text", text: "Cannot resume with baseRef: retained managed-worktree children continue in their existing worktree. Start a new worktree run from that base ref instead." }], isError: true, details: { mode: "management", results: [] } };
2076
+ }
2077
+ if (target.source === "async" && target.managedWorktree && target.asyncDir) {
2078
+ try {
2079
+ const protectedCwd = await protectRetainedWorktreeForResume(parallelHandoffPath(target.asyncDir), target.runId, target.index, input.signal);
2080
+ if (path.resolve(protectedCwd) !== path.resolve(effectiveCwd)) throw new Error("Retained worktree cwd changed during resume admission.");
2081
+ } catch (error) {
2082
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
2083
+ }
2084
+ }
2085
+
2059
2086
  if (target.source === "async" && target.runner?.type === "external-job") {
2060
2087
  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: [] } };
2061
2088
  const resumed = await resumeExternalJobFollowUp({
@@ -2119,7 +2146,7 @@ async function resumeAsyncRun(input: {
2119
2146
  const chain = wrapChainTasksForFork(attachChain, contextPolicy);
2120
2147
  const normalized = normalizeSkillInput(input.params.skill);
2121
2148
  const parentModel = input.parentModel;
2122
- const result = executeAsyncChain(runId, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
2149
+ const result = await executeAsyncChain(runId, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
2123
2150
  chain,
2124
2151
  task: workflowTask,
2125
2152
  goal,
@@ -2138,6 +2165,7 @@ async function resumeAsyncRun(input: {
2138
2165
  cwd: input.requestCwd,
2139
2166
  currentSessionId: input.deps.state.currentSessionId,
2140
2167
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
2168
+ parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
2141
2169
  currentModelProvider: parentModel?.provider,
2142
2170
  currentModel: parentModel,
2143
2171
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
@@ -2145,6 +2173,7 @@ async function resumeAsyncRun(input: {
2145
2173
  projectTrusted: currentProjectTrusted(input.ctx),
2146
2174
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2147
2175
  modelResponseAliases: input.deps.config.modelResponseAliases,
2176
+ runnerLaunchers: input.deps.config.runnerLaunchers,
2148
2177
  interactive: input.ctx.hasUI,
2149
2178
  permissions: input.deps.config.permissions,
2150
2179
  childRuntime: input.deps.childRuntime,
@@ -2202,16 +2231,14 @@ async function resumeAsyncRun(input: {
2202
2231
  if (!revivalSessionFile) {
2203
2232
  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: [] } };
2204
2233
  }
2205
- if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
2206
- return { content: [{ type: "text", text: "Cannot resume with baseRef: retained managed-worktree children continue in their existing worktree. Start a new worktree run from that base ref instead." }], isError: true, details: { mode: "management", results: [] } };
2207
- }
2208
2234
  if (target.source === "async" && asyncReviveRequiresRecoveryDescriptor(target)) {
2209
2235
  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: [] } };
2210
2236
  }
2211
2237
  if (target.source === "nested" && !target.recoveryDescriptor) {
2212
2238
  return { content: [{ type: "text", text: `Nested child '${target.runId}' is missing its required recovery identity. Start a new run instead.` }], isError: true, details: { mode: "management", results: [] } };
2213
2239
  }
2214
- const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
2240
+ // Runs without a recovery descriptor were never wrapped; a launcher added to the agent file later does not apply.
2241
+ const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : { ...baseAgentConfig, launcher: undefined };
2215
2242
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
2216
2243
  const foregroundContract = target.source === "foreground" ? target.resumeContract : undefined;
2217
2244
  const outputSchema = Object.hasOwn(input.params, "outputSchema")
@@ -2228,6 +2255,10 @@ async function resumeAsyncRun(input: {
2228
2255
  if (acceptanceErrors.length > 0) {
2229
2256
  return { content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }], isError: true, details: { mode: "management", results: [] } };
2230
2257
  }
2258
+ // Refuse before capacity moves so the retained run stays resumable once the config is fixed.
2259
+ if (agentConfig.launcher !== undefined && !lookupRunnerLauncher(input.deps.config.runnerLaunchers, agentConfig.launcher)) {
2260
+ return { content: [{ type: "text", text: `Cannot resume: run '${target.runId}' was launched with launcher '${agentConfig.launcher}', which is no longer defined in runnerLaunchers in the user subagent config.` }], isError: true, details: { mode: "management", results: [] } };
2261
+ }
2231
2262
  const runId = randomUUID();
2232
2263
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
2233
2264
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
@@ -2269,6 +2300,7 @@ async function resumeAsyncRun(input: {
2269
2300
  cwd: input.requestCwd,
2270
2301
  currentSessionId: input.deps.state.currentSessionId,
2271
2302
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
2303
+ parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
2272
2304
  currentModelProvider: parentModel?.provider,
2273
2305
  currentModel: parentModel,
2274
2306
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
@@ -2277,6 +2309,7 @@ async function resumeAsyncRun(input: {
2277
2309
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2278
2310
  // Absence in the retained contract is meaningful; never acquire current aliases.
2279
2311
  modelResponseAliases: recoveryDescriptor ? recoveryDescriptor.modelResponseAliases : foregroundContract?.modelResponseAliases,
2312
+ runnerLaunchers: input.deps.config.runnerLaunchers,
2280
2313
  interactive: input.ctx.hasUI,
2281
2314
  permissions: input.deps.config.permissions,
2282
2315
  childRuntime: input.deps.childRuntime,
@@ -2423,10 +2456,12 @@ function formatFailedSingleRunOutput(result: SingleResult, displayOutput: string
2423
2456
  const error = result.error || "Failed";
2424
2457
  const output = displayOutput.trim();
2425
2458
  const lines = [error];
2459
+ let cappedOutput = output;
2426
2460
  if (output && output !== error.trim()) {
2427
- lines.push("", "Output:", output);
2461
+ cappedOutput = capInlineOutput(output, { artifactPath: result.artifactPaths?.outputPath, savedPath: result.savedOutputPath });
2462
+ lines.push("", "Output:", cappedOutput);
2428
2463
  }
2429
- if (result.artifactPaths?.outputPath && fs.existsSync(result.artifactPaths.outputPath)) {
2464
+ if (cappedOutput === output && result.artifactPaths?.outputPath && fs.existsSync(result.artifactPaths.outputPath)) {
2430
2465
  lines.push("", `Output artifact: ${result.artifactPaths.outputPath}`);
2431
2466
  }
2432
2467
  return lines.join("\n");
@@ -2500,6 +2535,7 @@ async function emitForegroundResultIntercom(input: {
2500
2535
  ...(result.sessionName ? { sessionName: result.sessionName } : {}),
2501
2536
  status: foregroundResultIntercomStatus(result),
2502
2537
  outputState: result.outputState ?? "unknown",
2538
+ ...(result.outputPartial ? { outputPartial: true } : {}),
2503
2539
  summary: resultSummaryForIntercom(result),
2504
2540
  index,
2505
2541
  artifactPath: result.artifactPaths?.outputPath,
@@ -2548,7 +2584,7 @@ async function maybeBuildForegroundIntercomReceipt(input: {
2548
2584
  }
2549
2585
 
2550
2586
  function diagnosticContextFromDiscovery(
2551
- discovered: { agents: AgentConfig[]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] },
2587
+ discovered: { agents: AgentConfig[]; disabledAgents?: string[]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] },
2552
2588
  cwd: string,
2553
2589
  scope: AgentScope,
2554
2590
  ): UnknownAgentDiagnosticContext {
@@ -2571,6 +2607,8 @@ function workflowValidationOptions(deps: ExecutorDeps, params: SubagentParamsLik
2571
2607
  const cwd = resolveRequestedCwd(runtimeCwd, params.cwd);
2572
2608
  const scope = resolveExecutionAgentScope(params.agentScope);
2573
2609
  let discovered: ReturnType<ExecutorDeps["discoverAgents"]> | undefined;
2610
+ // Validation reports every bad agent name; only the first one carries the agent list.
2611
+ let listedAgents = false;
2574
2612
  return {
2575
2613
  maxSubagentSpawnsPerRun: params.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
2576
2614
  agentNameError: (name) => {
@@ -2578,12 +2616,12 @@ function workflowValidationOptions(deps: ExecutorDeps, params: SubagentParamsLik
2578
2616
  const { agents } = discovered;
2579
2617
  const resolved = resolveAgentName(name, agents);
2580
2618
  if (resolved.agent || resolved.error) return canonicalizeAgentName(name, agents, discovered.agentDiagnostics, diagnosticContextFromDiscovery(discovered, cwd, scope)).error;
2581
- const requested = name.trim().toLowerCase();
2582
- const suggestion = [...new Set(agents.flatMap((agent) => [agent.name, ...(agent.localName ? [agent.localName] : []), ...(agent.aliases ?? [])]))]
2583
- .map((candidate) => ({ candidate, distance: editDistance(requested, candidate.toLowerCase()) }))
2584
- .filter(({ candidate, distance }) => distance <= Math.max(1, Math.floor(candidate.length / 4)) || hasSingleAdjacentTransposition(requested, candidate.toLowerCase()))
2585
- .sort((left, right) => left.distance - right.distance || left.candidate.localeCompare(right.candidate))[0]?.candidate;
2586
- return `Unknown agent '${name}'.${suggestion ? ` Did you mean '${suggestion}'?` : ""} Use subagent({ action: "list" }) to inspect agents.`;
2619
+ const disabled = discovered.disabledAgents?.includes(name.trim()) === true;
2620
+ const suggestion = disabled ? undefined : suggestAgentName(name, agents);
2621
+ const problem = disabled ? `Agent '${name}' is disabled by a settings override.` : `Unknown agent '${name}'.${suggestion ? ` Did you mean '${suggestion}'?` : ""}`;
2622
+ if (listedAgents) return problem;
2623
+ listedAgents = true;
2624
+ return [`${problem} Available agents:`, ...formatAvailableAgentLines(agents)].join("\n");
2587
2625
  },
2588
2626
  };
2589
2627
  }
@@ -3390,11 +3428,11 @@ function importedAsyncRootUsage(completed: Awaited<ReturnType<typeof waitForImpo
3390
3428
 
3391
3429
  function removeWorkflowAwaitedResult(asyncDir: string, resultPath: string, runId: string, publication: NonNullable<Awaited<ReturnType<typeof waitForImportedAsyncRoot>>["importedPublication"]>): void {
3392
3430
  try {
3393
- fs.rmSync(resultPath, { force: true });
3394
- } catch {
3395
- // Payload cleanup must not replace an already imported delivery.
3431
+ retireResultSnapshot(workflowAwaitedAsyncResultPath(asyncDir), { ...publication, runId }, resultPath);
3432
+ } catch (error) {
3433
+ // Cleanup must not replace an already imported delivery.
3434
+ console.error(`Failed to remove imported workflow child result '${resultPath}'; leaving it in place:`, error);
3396
3435
  }
3397
- removeResultIndex(asyncDir, publication.sessionId, runId, publication.toolCallId);
3398
3436
  }
3399
3437
 
3400
3438
  function emitWorkflowAwaitedChildComplete(
@@ -3551,13 +3589,16 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3551
3589
  cwd: ctx.cwd,
3552
3590
  currentSessionId: data.parentSessionId!,
3553
3591
  parentSessionId: data.parentPiSessionId,
3592
+ parentSessionFile: ctx.sessionManager.getSessionFile() ?? undefined,
3554
3593
  currentModelProvider: parentModel?.provider,
3555
3594
  currentModel: parentModel,
3556
3595
  scopedModelIds: data.scopedModelIds,
3557
3596
  modelScope: data.modelScope,
3558
3597
  projectTrusted: currentProjectTrusted(ctx),
3559
3598
  ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3560
- modelResponseAliases: deps.config.modelResponseAliases, interactive: ctx.hasUI,
3599
+ modelResponseAliases: deps.config.modelResponseAliases,
3600
+ runnerLaunchers: deps.config.runnerLaunchers,
3601
+ interactive: ctx.hasUI,
3561
3602
  permissions: deps.config.permissions,
3562
3603
  childRuntime: deps.childRuntime,
3563
3604
  });
@@ -3618,6 +3659,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3618
3659
  const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: a.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
3619
3660
  if (launchRuleError) return toExecutionErrorResult(params, new Error(launchRuleError), data.contextPolicy.contextSummary);
3620
3661
  const asyncResult = await executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
3662
+ toolCallId: data.toolCallId,
3621
3663
  agent: params.agent!,
3622
3664
  task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(params.task ?? "") : (params.task ?? ""),
3623
3665
  goal: params.task ?? "",
@@ -3862,7 +3904,7 @@ function resolveWorkflowChildOutputPath(input: {
3862
3904
  state?: SubagentState;
3863
3905
  key: string;
3864
3906
  params: Record<string, unknown>;
3865
- }): { path?: string; inherited: boolean } {
3907
+ }): { path?: string; inherited: boolean; resumedOutput?: string } {
3866
3908
  const rawOutput = input.params.output;
3867
3909
  const hasExplicitOutput = typeof rawOutput === "string" || typeof rawOutput === "boolean";
3868
3910
  if (typeof input.params.resume === "string" && (!hasExplicitOutput || rawOutput === true || rawOutput === "true")) {
@@ -3872,7 +3914,11 @@ function resolveWorkflowChildOutputPath(input: {
3872
3914
  id: input.params.resume.trim(),
3873
3915
  ...(typeof index === "number" && Number.isInteger(index) ? { index } : {}),
3874
3916
  }, input.state);
3875
- return { path: "recoveryDescriptor" in target ? target.recoveryDescriptor?.outputPath : undefined, inherited: false };
3917
+ const recoveryOutput = "recoveryDescriptor" in target ? target.recoveryDescriptor?.outputPath : undefined;
3918
+ if (hasExplicitOutput) return { path: recoveryOutput, inherited: false };
3919
+ // An output-less foreground resume reuses its recorded output; only an absolute path is known before the new run id exists.
3920
+ const foregroundOutput = target.source === "foreground" ? target.resumeContract?.output : undefined;
3921
+ return { path: recoveryOutput, inherited: false, resumedOutput: recoveryOutput ?? (typeof foregroundOutput === "string" && path.isAbsolute(foregroundOutput) ? foregroundOutput : undefined) };
3876
3922
  }
3877
3923
  const childCwd = resolveWorkflowChildLocalCwd(input);
3878
3924
  let agentOutput: string | undefined;
@@ -3925,7 +3971,9 @@ function workflowChildOutputClaims(input: {
3925
3971
  }
3926
3972
  const overrides = new Map<string, string>();
3927
3973
  for (const entry of resolvedEntries) {
3928
- if (entry.inherited && entry.path && (paths.get(resolveWorkflowHostOutputClaimPath(entry.path)) ?? 0) > 1) {
3974
+ // An output-less resume keeps its retained path unless an earlier child of this workflow already owns it.
3975
+ const resumeCollides = entry.resumedOutput !== undefined && input.claimedOutputPaths.has(resolveWorkflowHostOutputClaimPath(entry.resumedOutput));
3976
+ if (resumeCollides || (entry.inherited && entry.path && (paths.get(resolveWorkflowHostOutputClaimPath(entry.path)) ?? 0) > 1)) {
3929
3977
  const output = workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.workflowRunId, entry.key);
3930
3978
  overrides.set(entry.key, output);
3931
3979
  entry.path = output;
@@ -3941,6 +3989,14 @@ function workflowChildOutputClaims(input: {
3941
3989
  claims.set(claimPath, key);
3942
3990
  childClaims.set(key, claimPath);
3943
3991
  }
3992
+ // Record a discovered output-less resume path for later admissions without adding same-batch duplicate errors.
3993
+ for (const { key, path: resolved, resumedOutput } of resolvedEntries) {
3994
+ if (resolved || !resumedOutput) continue;
3995
+ const claimPath = resolveWorkflowHostOutputClaimPath(resumedOutput);
3996
+ if (claims.has(claimPath)) continue;
3997
+ claims.set(claimPath, key);
3998
+ childClaims.set(key, claimPath);
3999
+ }
3944
4000
  return { claims, childClaims, overrides };
3945
4001
  }
3946
4002
 
@@ -3968,7 +4024,7 @@ function prepareWorkflowChildLaunchParams(input: {
3968
4024
  }): SubagentParamsLike {
3969
4025
  let childParams = input.childParams;
3970
4026
  const usesDefaultOutput = input.childParams.output === undefined && input.childParams.resume === undefined;
3971
- if (usesDefaultOutput && input.outputOverride !== undefined) {
4027
+ if (input.childParams.output === undefined && input.outputOverride !== undefined) {
3972
4028
  childParams = { ...input.childParams, output: input.outputOverride };
3973
4029
  } else if (usesDefaultOutput && input.aggregateOutputPath !== undefined) {
3974
4030
  childParams = { ...input.childParams, output: workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.parentWorkflowRunId, input.workflowKey) };
@@ -3982,7 +4038,7 @@ function prepareWorkflowChildLaunchParams(input: {
3982
4038
  const agent = typeof childParams.agent === "string"
3983
4039
  ? resolveAgentName(childParams.agent, discoveredAgents).agent ?? resolveAgentName(childParams.agent, input.agents).agent
3984
4040
  : undefined;
3985
- const externalAsyncRequired = agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job";
4041
+ const externalAsyncRequired = agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job" || agent?.launcher !== undefined;
3986
4042
  return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, { ...input.options, externalAsyncRequired, outputClaimPath: input.outputClaimPath });
3987
4043
  }
3988
4044
 
@@ -4258,6 +4314,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4258
4314
  const interruptController = new AbortController();
4259
4315
  let detachForeground: ((reason?: string) => boolean) | undefined;
4260
4316
  let childSessionControls: ForegroundChildSessionControls | undefined;
4317
+ let pendingRuntimeStop: string | undefined;
4261
4318
  const foregroundControl = deps.state.foregroundControls.get(runId);
4262
4319
  const syncHerdrForegroundChild = () => {
4263
4320
  if (!foregroundControl?.parentWorkflowRunId) return;
@@ -4326,6 +4383,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4326
4383
  ? new Promise<Awaited<ReturnType<typeof runSync>>>((resolve) => { resolveDetachedWorkflowChild = resolve; })
4327
4384
  : undefined;
4328
4385
  try {
4386
+ const childSessionFile = sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin);
4329
4387
  const launched = await runSync(ctx.cwd, agents, params.agent!, task, compactOptional<Parameters<typeof runSync>[4]>({
4330
4388
  machine: foregroundMachine,
4331
4389
  parentProviderRegistry: ctx.modelRegistry,
@@ -4335,9 +4393,13 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4335
4393
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
4336
4394
  projectTrusted: currentProjectTrusted(ctx),
4337
4395
  ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
4396
+ parentSessionFile: ctx.sessionManager.getSessionFile() ?? undefined,
4338
4397
  requiredExtensions,
4339
4398
  childRuntime: deps.childRuntime,
4340
- onChildSession: (controls) => { childSessionControls = controls; },
4399
+ onChildSession: (controls) => {
4400
+ childSessionControls = controls;
4401
+ if (pendingRuntimeStop) controls.stop(pendingRuntimeStop);
4402
+ },
4341
4403
  context: data.contextPolicy.contextForAgent(params.agent!),
4342
4404
  unknownAgentDiagnosticContext: data.unknownAgentDiagnosticContext,
4343
4405
  runFanoutBudget: params.runFanoutAdmitted ? data.runFanoutBudget : { ...data.runFanoutBudget, parentPath: `${data.runFanoutBudget.parentPath ? `${data.runFanoutBudget.parentPath}/` : ""}single` },
@@ -4350,7 +4412,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4350
4412
  intercomEvents: deps.pi.events,
4351
4413
  runId,
4352
4414
  sessionDir: sessionDirForIndex(0),
4353
- sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
4415
+ sessionFile: childSessionFile,
4354
4416
  share: shareEnabled,
4355
4417
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
4356
4418
  artifactConfig,
@@ -4391,6 +4453,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4391
4453
  detachForeground = detach;
4392
4454
  },
4393
4455
  onDetachedExit: async (result) => {
4456
+ if (foregroundControl) foregroundControl.stopForRuntimeReplacement = undefined;
4394
4457
  if (resolveDetachedWorkflowChild) {
4395
4458
  resolveDetachedWorkflowChild(result);
4396
4459
  return;
@@ -4437,6 +4500,18 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4437
4500
  capabilityCeiling: data.capabilityCeiling,
4438
4501
  allowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,
4439
4502
  }));
4503
+ if (launched.detached && foregroundControl) {
4504
+ // Record the stop before aborting so the next runtime's history restore finds it.
4505
+ foregroundControl.stopForRuntimeReplacement = () => {
4506
+ // The detach receipt predates the session file that resume needs.
4507
+ const sessionFile = childSessionFile && fs.existsSync(childSessionFile) ? childSessionFile : undefined;
4508
+ const stopped = { ...launched, detached: undefined, stopped: true, exitCode: 1, error: RUNTIME_REPLACED_STOP_ERROR, finalOutput: RUNTIME_REPLACED_STOP_ERROR, sessionFile };
4509
+ rememberForegroundRun(deps.state, { modelResponseAliases, runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: [stopped], params, effectiveOutput, effectiveOutputMode, extensionBindings: params.extensionBindings, requiredExtensions });
4510
+ // A child detached during creation has no controls yet; stop it as soon as they arrive.
4511
+ if (childSessionControls) childSessionControls.stop(RUNTIME_REPLACED_STOP_ERROR);
4512
+ else pendingRuntimeStop = RUNTIME_REPLACED_STOP_ERROR;
4513
+ };
4514
+ }
4440
4515
  r = launched.detached && detachedWorkflowChild ? await detachedWorkflowChild : launched;
4441
4516
  } catch (error) {
4442
4517
  await cleanupSingleWorktree();
@@ -4548,7 +4623,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4548
4623
  isError: true,
4549
4624
  };
4550
4625
  return {
4551
- content: [{ type: "text", text: `${finalizedOutput.displayOutput || "(no output)"}${worktreeSuffix}` }],
4626
+ content: [{ type: "text", text: `${capInlineOutput(finalizedOutput.displayOutput, { artifactPath: r.artifactPaths?.outputPath, savedPath: finalizedOutput.savedPath }) || "(no output)"}${worktreeSuffix}` }],
4552
4627
  details,
4553
4628
  };
4554
4629
  }
@@ -4766,7 +4841,7 @@ function workflowRunningChildrenSummary(children: WorkflowScriptChildResult[]):
4766
4841
  function workflowResultChildren(children: WorkflowScriptChildResult[], status: AsyncStatus, includeFailureFields: boolean) {
4767
4842
  return withWorkflowRevivals(DIRS.async, status.runId, children).map((child) => {
4768
4843
  const sessionName = status.steps?.find((step) => step.workflowKey === child.key)?.sessionName;
4769
- return { workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(child.revival ? { revival: formatWorkflowKeyRevival(child.revival) } : {}), ...(sessionName ? { sessionName } : {}), ...workflowChildAccountingFields(child), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, ...(child.state === "running" ? { state: "running" } : { success: child.ok }), ...(child.asyncDir ? { asyncDir: child.asyncDir } : {}), ...(child.outputReference ? { outputReference: child.outputReference } : {}), ...(includeFailureFields && child.terminalOutcome ? { terminalOutcome: child.terminalOutcome } : {}), ...(child.outputPathMapping ? { outputPathMapping: child.outputPathMapping } : {}), ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(includeFailureFields && child.detached && status.state !== "complete" ? { detached: true } : {}), ...(child.outputArtifactPath || child.outputReference ? { artifactPaths: { outputPath: child.outputArtifactPath ?? child.outputReference } } : {}) };
4844
+ return { workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(child.revival ? { revival: formatWorkflowKeyRevival(child.revival) } : {}), ...(sessionName ? { sessionName } : {}), ...workflowChildAccountingFields(child), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, ...(child.state === "running" ? { state: "running" } : { success: child.ok }), ...(!child.ok && child.error ? { error: child.error } : {}), ...(child.asyncDir ? { asyncDir: child.asyncDir } : {}), ...(child.outputReference ? { outputReference: child.outputReference } : {}), ...(includeFailureFields && child.terminalOutcome ? { terminalOutcome: child.terminalOutcome } : {}), ...(child.outputPathMapping ? { outputPathMapping: child.outputPathMapping } : {}), ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(includeFailureFields && child.detached && status.state !== "complete" ? { detached: true } : {}), ...(child.outputArtifactPath || child.outputReference ? { artifactPaths: { outputPath: child.outputArtifactPath ?? child.outputReference } } : {}) };
4770
4845
  });
4771
4846
  }
4772
4847
 
@@ -4803,6 +4878,7 @@ function workflowSteerReceipt(key: string, result: AgentToolResult<Details>): Wo
4803
4878
  }
4804
4879
 
4805
4880
  const CHILD_SESSION_NOT_RUNNING_YET = "Child session is not running yet.";
4881
+ const RUNTIME_REPLACED_STOP_ERROR = "Subagent stopped because the pi-subagents runtime that ran it was replaced (reload or session switch).";
4806
4882
  const MAX_WORKFLOW_RESUME_HINT_BYTES = 1024;
4807
4883
  const MAX_WORKFLOW_CHILD_RUN_ID_BYTES = 256;
4808
4884
  const WORKFLOW_RESUME_HINT_PARENT_STATES = new Set(["complete", "failed", "partial"]);
@@ -5347,6 +5423,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5347
5423
  /** Scheduled state visible to the current runtime supervisor owner only. */
5348
5424
  getCurrentSupervisorOwnerStates: () => Iterable<SubagentState>;
5349
5425
  } {
5426
+ const executorDeps = deps;
5350
5427
  const delegatedThinkingOverrides = new WeakMap<object, AgentConfig["thinking"]>();
5351
5428
  const delegatedZeroToolBudgets = new WeakSet<object>();
5352
5429
  const delegatedExecutions = new WeakSet<object>();
@@ -5376,6 +5453,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5376
5453
  preserveActiveSession = false,
5377
5454
  parentModelOverride?: ParentModel | null,
5378
5455
  ): Promise<AgentToolResult<Details>> => {
5456
+ const projectScopeError = projectScopeTrustError(params, ctx);
5457
+ if (projectScopeError) return projectScopeError;
5458
+ const deps = withSessionProjectTrust(executorDeps, ctx);
5379
5459
  const workflowLaunchObserver = workflowLaunchObservers.get(params);
5380
5460
  const inheritedUsageBudget = workflowOwnedUsageBudgets.get(params);
5381
5461
  const retainedRequiredExtensions = workflowRetainedRequiredExtensions.get(params);
@@ -5671,7 +5751,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5671
5751
  if (resultWriteFailureWakeDelivered) return false;
5672
5752
  if (deps.state.currentSessionId !== currentSessionId || deps.state.completionOwnerId !== completionOwnerId) return false;
5673
5753
  try {
5674
- deps.pi.sendMessage(
5754
+ (deps.parentWake ?? deps.pi).sendMessage(
5675
5755
  {
5676
5756
  customType: "subagent-workflow-result-write-failed",
5677
5757
  content: message,
@@ -6164,6 +6244,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6164
6244
  onChildSettled: (notification) => {
6165
6245
  const journalFingerprint = workflowJournalFingerprints.get(notification.childKey);
6166
6246
  if (journalFingerprint) appendWorkflowChildJournal(asyncDir, { type: "settle", key: notification.childKey, fingerprint: journalFingerprint, result: notification.result });
6247
+ // Fresh, journal-reused and re-attached children all settle here, so their rows take usage from the same result.
6248
+ const settledResults = notification.result.results ?? [];
6249
+ const settledStep = settledResults.length ? status.steps?.find((candidate) => candidate.workflowKey === notification.childKey) : undefined;
6250
+ if (settledStep) {
6251
+ const usage = sumResultsUsage(settledResults);
6252
+ settledStep.tokens = { input: usage.input, output: usage.output, total: usage.input + usage.output };
6253
+ if (usage.turns > 0) settledStep.turnCount = usage.turns;
6254
+ persist({ tolerateStatusWriteFailure: true });
6255
+ }
6167
6256
  appendWorkflowEvent({
6168
6257
  type: "subagent.workflow.child_settled",
6169
6258
  childKey: notification.childKey,
@@ -6172,11 +6261,13 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6172
6261
  workflowRunning: notification.workflowRunning,
6173
6262
  });
6174
6263
  try {
6175
- deps.pi.sendMessage(
6264
+ (deps.parentWake ?? deps.pi).sendMessage(
6176
6265
  {
6177
6266
  customType: "subagent-incremental-child-notify",
6178
6267
  content: formatIncrementalChildCompletion(notification),
6179
6268
  display: notification.outcome !== "completed",
6269
+ // Render-only: Pi does not send details to the model.
6270
+ details: { childKey: notification.childKey, outcome: notification.outcome },
6180
6271
  },
6181
6272
  { triggerTurn: incrementalChildCompletionTriggersTurn(notification, requestParams.scheduleOrigin) },
6182
6273
  );
@@ -6230,7 +6321,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6230
6321
  appendWorkflowChildJournal(asyncDir, { type: "start", key, fingerprint: journalFingerprint, runId: priorRunId });
6231
6322
  const stopListener = stopAwaitedAsyncChildOnAbort(workflowSignal, deps.state, priorRunId, priorAsyncDir, deps.kill);
6232
6323
  const reattached = await awaitExistingAsyncRun(priorAsyncDir, priorRunId, workflowSignal).finally(stopListener.remove);
6233
- const claimedPath = reattached.status === "settled" ? claimWorkflowAwaitedResult(priorAsyncDir, workflowRunId) : undefined;
6324
+ const claimedPath = reattached.status === "settled" ? claimWorkflowAwaitedResult(priorAsyncDir, workflowRunId, { ...reattached.result.importedPublication, runId: priorRunId }) : undefined;
6234
6325
  if (reattached.status === "settled" && claimedPath) {
6235
6326
  const imported = importWorkflowAwaitedChildResult(reattached.result, { runId: priorRunId, asyncDir: priorAsyncDir, resultPath: claimedPath, task: typeof childParams.task === "string" ? childParams.task : "", parentWorkflowRunId: workflowReuseSource?.runId, details: { mode: "single", asyncId: priorRunId, asyncDir: priorAsyncDir, results: [] }, state: deps.state, pi: deps.pi });
6236
6327
  const reattachedResult = workflowChildResult(key, imported, childParams, deps.state);
@@ -6713,11 +6804,30 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6713
6804
  if (deps.allowMutatingManagementActions === false) {
6714
6805
  return { content: [{ type: "text", text: "Action 'worktree.cleanup' is not available from child-safe subagent fanout mode." }], isError: true, details: { mode: "management", results: [] } };
6715
6806
  }
6807
+ if (paramsWithResolvedCwd.mode === "apply") {
6808
+ try {
6809
+ if (!paramsWithResolvedCwd.repo?.trim() || !paramsWithResolvedCwd.planId?.trim() || paramsWithResolvedCwd.handoffPath !== undefined) throw new Error("worktree.cleanup apply requires explicit repo and planId, without handoffPath.");
6810
+ const repo = path.resolve(requestCwd, paramsWithResolvedCwd.repo);
6811
+ const plan = loadReviewedCleanupPlan(repo, paramsWithResolvedCwd.planId);
6812
+ const decision = resolveAuthorityDecision({ action: "discardWorktree", ...(deps.config.authorityPolicy === undefined ? {} : { policy: deps.config.authorityPolicy }) });
6813
+ if (decision === "forbid") throw new Error("Authority policy forbids worktree cleanup.");
6814
+ if (decision === "confirm") {
6815
+ if (!ctx.hasUI) throw new Error("Authority policy requires interactive confirmation for worktree cleanup.");
6816
+ if (!await ctx.ui.confirm("Apply reviewed worktree cleanup?", `Repository: ${plan.repoRoot}\nPlan: ${plan.planId}\nRemove up to ${plan.entries.filter((entry) => entry.decision === "remove").length} eligible worktrees. All local branches are retained.`)) return { content: [{ type: "text", text: "Worktree cleanup canceled." }], details: { mode: "management", results: [] } };
6817
+ }
6818
+ const applied = await applyReviewedCleanupPlan({ repo: plan.repoRoot, planId: plan.planId, authorized: true, signal,
6819
+ foregroundRunOwnership: (runId) => deps.state.foregroundControls.has(runId) ? "active" : (deps.state.foregroundRuns?.get(runId)?.children.length && deps.state.foregroundRuns.get(runId)!.children.every((child) => child.status !== "detached")) ? "terminal" : "unknown",
6820
+ });
6821
+ return { content: [{ type: "text", text: formatCleanupReceipt(applied) }], details: { mode: "management", results: [] } };
6822
+ } catch (error) {
6823
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
6824
+ }
6825
+ }
6716
6826
  if (paramsWithResolvedCwd.mode !== "plan") {
6717
- return { content: [{ type: "text", text: "worktree.cleanup currently supports mode='plan' only; apply/removal is not available yet." }], isError: true, details: { mode: "management", results: [] } };
6827
+ return { content: [{ type: "text", text: "worktree.cleanup requires mode='plan' or mode='apply'." }], isError: true, details: { mode: "management", results: [] } };
6718
6828
  }
6719
6829
  if (paramsWithResolvedCwd.planId !== undefined) {
6720
- return { content: [{ type: "text", text: "worktree.cleanup plan mode does not accept planId; apply is not available yet." }], isError: true, details: { mode: "management", results: [] } };
6830
+ return { content: [{ type: "text", text: "worktree.cleanup plan mode does not accept planId." }], isError: true, details: { mode: "management", results: [] } };
6721
6831
  }
6722
6832
  try {
6723
6833
  const created = createWorktreeCleanupPlan({
@@ -6952,7 +7062,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6952
7062
  if (action === "guide") {
6953
7063
  try {
6954
7064
  const guide = readSubagentGuide(paramsWithResolvedCwd.topic);
6955
- const notice = paramsWithResolvedCwd.topic === "tool-reference" ? disabledFeatureNotice(disabledFeatures) : undefined;
7065
+ const [topic, section] = paramsWithResolvedCwd.topic?.split("/") ?? [];
7066
+ const fullNotice = topic === "tool-reference" ? disabledFeatureNotice(disabledFeatures) : undefined;
7067
+ // Sections are capped at 8,000 chars, so they get a one-line pointer instead of the full list.
7068
+ const notice = fullNotice && section !== undefined ? "Some options and actions documented here are disabled by config in this session; guide topic tool-reference lists them." : fullNotice;
6956
7069
  return {
6957
7070
  content: [{ type: "text", text: notice ? `${notice}\n\n${guide}` : guide }],
6958
7071
  details: { mode: "management", results: [] },
@@ -6976,10 +7089,13 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6976
7089
  if (action === "doctor") {
6977
7090
  let currentSessionFile: string | null = null;
6978
7091
  let currentSessionId = deps.state.currentSessionId;
7092
+ let budgetSessionId = deps.state.currentSessionId;
6979
7093
  let sessionError: string | undefined;
6980
7094
  try {
6981
7095
  currentSessionFile = ctx.sessionManager.getSessionFile() ?? null;
6982
7096
  currentSessionId = ctx.sessionManager.getSessionId();
7097
+ // Launch admission's key (resolveCurrentSessionId) without its throw for an unbound session.
7098
+ budgetSessionId = currentSessionFile ?? currentSessionId;
6983
7099
  } catch (error) {
6984
7100
  sessionError = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
6985
7101
  }
@@ -6989,9 +7105,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6989
7105
  } catch (error) {
6990
7106
  if (!sessionError) sessionError = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
6991
7107
  }
6992
- const spawnBudget = getSpawnBudgetSnapshot(deps.state, deps.config, currentSessionId);
6993
- const activeAsyncCapacity = currentSessionId
6994
- ? getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })
7108
+ const spawnBudget = getSpawnBudgetSnapshot(deps.state, deps.config, budgetSessionId);
7109
+ const activeAsyncCapacity = budgetSessionId
7110
+ ? getActiveAsyncCapacitySnapshot(budgetSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })
6995
7111
  : { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession) ?? 0 };
6996
7112
  deps.state.activeAsyncCapacity = activeAsyncCapacity;
6997
7113
  return {
@@ -7005,6 +7121,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7005
7121
  requestedSessionDir: paramsWithResolvedCwd.sessionDir,
7006
7122
  currentSessionFile,
7007
7123
  currentSessionId,
7124
+ spawnBudget,
7125
+ activeAsyncCapacity,
7008
7126
  orchestratorTarget,
7009
7127
  sessionError,
7010
7128
  expandTilde: deps.expandTilde,
@@ -7513,16 +7631,27 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7513
7631
  : hasTasks
7514
7632
  ? (effectiveParams.tasks ?? []).map((task) => task.agent)
7515
7633
  : (effectiveParams.chain ?? []).flatMap((step) => getStepAgents(step as ChainStep));
7516
- const externalAgent = selectedAgentNames
7517
- .map((name) => agents.find((agent) => agent.name === name))
7518
- .find((agent) => agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job");
7519
- const externalAsyncRequired = Boolean(externalAgent) && effectiveParams.async === undefined && effectiveParams.clarify !== true && effectiveParams.foregroundOnly !== true;
7634
+ const selectedAgents = selectedAgentNames.map((name) => agents.find((agent) => agent.name === name));
7635
+ const externalAgent = selectedAgents.find((agent) => agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job");
7636
+ const launcherAgent = selectedAgents.find((agent) => agent?.launcher !== undefined);
7637
+ // A launcher agent goes to the background whenever the caller omitted async, even if the agent file defaults to foreground.
7638
+ const externalAsyncRequired = effectiveParams.foregroundOnly !== true && ((Boolean(externalAgent) && effectiveParams.async === undefined && effectiveParams.clarify !== true)
7639
+ || (Boolean(launcherAgent) && normalizedParams.async === undefined && normalizedParams.clarify !== true));
7520
7640
  const requestedAsync = externalAsyncRequired ? true : effectiveParams.async ?? deps.asyncByDefault;
7521
7641
  const backgroundRequestedWhileClarifying = (hasChain || hasTasks) && requestedAsync && effectiveParams.clarify === true;
7522
7642
  const effectiveAsync = requestedAsync && effectiveParams.clarify !== true;
7523
7643
  if (externalAgent && (!effectiveAsync || effectiveParams.foregroundOnly === true)) {
7524
7644
  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.`);
7525
7645
  }
7646
+ // forceTopLevelAsync rewrites async:false and clarify, so check what the caller asked for.
7647
+ if (launcherAgent && (!effectiveAsync || normalizedParams.async === false || normalizedParams.clarify === true || effectiveParams.foregroundOnly === true)) {
7648
+ return buildRequestedModeError(effectiveParams, `Agent '${launcherAgent.name}' uses launcher '${launcherAgent.launcher}', which wraps the background runner only. Foreground children run inside the parent process, so a launcher cannot wrap them. Omit async or pass async:true; clarify and foregroundOnly are unsupported.`);
7649
+ }
7650
+ // Refuse a launcher launch that cannot start before fan-out admission or a session directory exists.
7651
+ for (const agent of selectedAgents) {
7652
+ const launcherError = agent ? resolveAgentRunnerLauncher(agent, deps.config.runnerLaunchers, effectiveParams.machine ?? agent.machine).error : undefined;
7653
+ if (launcherError) return buildRequestedModeError(effectiveParams, launcherError);
7654
+ }
7526
7655
  if (effectiveAsync && hasSingle && effectiveParams.resume === undefined && effectiveParams.worktree === true) {
7527
7656
  try {
7528
7657
  await preflightWorktreeSource(effectiveCwd, { signal });
@@ -7725,6 +7854,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7725
7854
  backgroundRequestedWhileClarifying,
7726
7855
  effectiveAsync,
7727
7856
  asyncRunId,
7857
+ toolCallId: _id,
7728
7858
  controlConfig,
7729
7859
  ...(delegatedExecution ? { suppressUnchangedDelegationUpdates: true } : {}),
7730
7860
  intercomBridge,