@xzzpig/pi-subagents 0.20.0 → 0.22.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 (144) hide show
  1. package/CHANGELOG.md +164 -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/fork-supervisor-routing.md +77 -0
  13. package/docs/missions.md +34 -17
  14. package/docs/models.md +1 -1
  15. package/docs/observability.md +10 -5
  16. package/docs/tool-reference.md +117 -84
  17. package/docs/watchdog.md +8 -6
  18. package/docs/workflows.md +16 -7
  19. package/index.ts +5 -0
  20. package/package.json +6 -3
  21. package/prompts/council.md +1 -1
  22. package/skills/pi-subagents/SKILL.md +1 -1
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  24. package/skills/pi-subagents/references/execution-controls.md +16 -16
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  26. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  27. package/src/agents/advertised-agent-prompt.ts +9 -1
  28. package/src/agents/agent-management.ts +4 -0
  29. package/src/agents/agent-memory.ts +3 -3
  30. package/src/agents/agent-scope.ts +4 -0
  31. package/src/agents/agent-serializer.ts +8 -1
  32. package/src/agents/agents.ts +191 -145
  33. package/src/api/preflight.ts +8 -4
  34. package/src/api/supervisor-routing.ts +196 -0
  35. package/src/extension/config.ts +21 -2
  36. package/src/extension/context-injection.ts +6 -1
  37. package/src/extension/control-notices.ts +1 -9
  38. package/src/extension/declaration-pinning.ts +164 -0
  39. package/src/extension/doctor.ts +7 -10
  40. package/src/extension/fanout-child.ts +7 -8
  41. package/src/extension/index.ts +143 -134
  42. package/src/extension/reply-workflow-script.ts +20 -11
  43. package/src/extension/rpc.ts +11 -6
  44. package/src/extension/schemas.ts +34 -30
  45. package/src/extension/subagent-guide.ts +86 -6
  46. package/src/extension/subagent-options.ts +47 -0
  47. package/src/extension/tool-activation.ts +3 -2
  48. package/src/extension/tool-description.ts +51 -68
  49. package/src/inspectors/actions.ts +37 -11
  50. package/src/inspectors/plugins.ts +3 -2
  51. package/src/inspectors/tmux/actions.ts +204 -0
  52. package/src/inspectors/tmux/client.ts +85 -0
  53. package/src/inspectors/tmux/plugin.ts +21 -0
  54. package/src/integrations/herdr-status.ts +18 -49
  55. package/src/integrations/program-status.ts +215 -0
  56. package/src/intercom/fork-supervisor-routing.ts +533 -0
  57. package/src/intercom/native-supervisor-channel.ts +152 -13
  58. package/src/intercom/result-intercom.ts +3 -2
  59. package/src/intercom/supervisor-ui.ts +2 -174
  60. package/src/missions/store.ts +25 -5
  61. package/src/profiles/profiles.ts +24 -21
  62. package/src/runs/background/active-async-capacity.ts +58 -8
  63. package/src/runs/background/async-execution.ts +143 -38
  64. package/src/runs/background/async-job-tracker.ts +11 -4
  65. package/src/runs/background/async-resume.ts +5 -2
  66. package/src/runs/background/await-async-run.ts +14 -9
  67. package/src/runs/background/binary-bootstrap.ts +2 -1
  68. package/src/runs/background/calendar-schedule.ts +90 -0
  69. package/src/runs/background/chain-root-attachment.ts +9 -5
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +16 -2
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-child-launch.ts +1 -0
  79. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  80. package/src/runs/background/scheduled-runs.ts +256 -61
  81. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  82. package/src/runs/background/subagent-runner.ts +32 -12
  83. package/src/runs/background/subagent-wait.ts +38 -19
  84. package/src/runs/background/terminal-run-index.ts +46 -1
  85. package/src/runs/background/wait-completions.ts +1 -0
  86. package/src/runs/background/wait-tool.ts +33 -23
  87. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  88. package/src/runs/foreground/async-stop-action.ts +48 -22
  89. package/src/runs/foreground/execution.ts +94 -52
  90. package/src/runs/foreground/foreground-history.ts +1 -0
  91. package/src/runs/foreground/subagent-executor.ts +232 -77
  92. package/src/runs/shared/child-commands.ts +2 -1
  93. package/src/runs/shared/child-hooks.ts +4 -3
  94. package/src/runs/shared/child-launch.ts +3 -0
  95. package/src/runs/shared/child-session.ts +41 -24
  96. package/src/runs/shared/child-tool-plan.ts +13 -26
  97. package/src/runs/shared/dynamic-fanout.ts +1 -1
  98. package/src/runs/shared/fork-command-result.ts +10 -0
  99. package/src/runs/shared/herdr-placed-run.ts +5 -4
  100. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  101. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  102. package/src/runs/shared/model-resolution.ts +30 -1
  103. package/src/runs/shared/nested-events.ts +5 -0
  104. package/src/runs/shared/parallel-handoff.ts +56 -8
  105. package/src/runs/shared/parallel-utils.ts +2 -0
  106. package/src/runs/shared/partial-output.ts +48 -0
  107. package/src/runs/shared/runner-launcher.ts +25 -0
  108. package/src/runs/shared/single-output.ts +53 -0
  109. package/src/runs/shared/structured-output.ts +14 -7
  110. package/src/runs/shared/subagent-control.ts +3 -3
  111. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  112. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  113. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  114. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  115. package/src/runs/shared/worktree-lock.ts +29 -0
  116. package/src/runs/shared/worktree.ts +12 -1
  117. package/src/shared/atomic-json.ts +4 -2
  118. package/src/shared/edit-distance.ts +33 -0
  119. package/src/shared/file-lease.ts +74 -0
  120. package/src/shared/formatters.ts +1 -5
  121. package/src/shared/model-info.ts +22 -0
  122. package/src/shared/package-version.ts +17 -0
  123. package/src/shared/parent-wake.ts +79 -0
  124. package/src/shared/pruned-fork.ts +7 -1
  125. package/src/shared/runtime-module-path.ts +19 -0
  126. package/src/shared/settings-file-lease.ts +36 -0
  127. package/src/shared/types.ts +36 -2
  128. package/src/shared/utils.ts +8 -6
  129. package/src/slash/prompt-template-bridge.ts +21 -20
  130. package/src/slash/slash-commands.ts +3 -3
  131. package/src/slash/subagents-admin.ts +2 -1
  132. package/src/tui/fleet-native-transcript.ts +2 -0
  133. package/src/tui/fleet-transcript.ts +12 -3
  134. package/src/tui/fleet.ts +11 -8
  135. package/src/tui/render.ts +27 -19
  136. package/src/tui/subagent-messages.ts +305 -0
  137. package/src/watchdog/diff-tool.ts +2 -2
  138. package/src/watchdog/register-main.ts +2 -22
  139. package/src/watchdog/render.ts +2 -24
  140. package/src/watchdog/runtime.ts +6 -4
  141. package/src/watchdog/settings.ts +18 -13
  142. package/src/watchdog/tool-actions.ts +2 -2
  143. package/src/workflows/scripted-workflow.ts +20 -6
  144. package/src/workflows/workflow-resources.ts +11 -0
@@ -3,7 +3,8 @@ 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 type { SupervisorLaunchHooks } from "../../intercom/fork-supervisor-routing.ts";
7
+ import { discoverAgents, discoverAgentsAll, findBlockingAgentDiagnostic, formatAvailableAgentLines, formatUnknownAgentError, resolveAgentName, suggestAgentName, unknownAgentDiagnosticContext, type AgentConfig, type AgentDiscoveryDiagnostic, type AgentScope, type UnknownAgentDiagnosticContext } from "../../agents/agents.ts";
7
8
  import { getArtifactsDir, getProjectArtifactPackagingWarning, getProjectSubagentsDir } from "../../shared/artifacts.ts";
8
9
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
9
10
  import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilient-json.ts";
@@ -18,7 +19,7 @@ import {
18
19
  } from "./foreground-control.ts";
19
20
  import { getLivePromptAudit, rewritePromptWithGuidance, updateLiveEffectivePrompt } from "./prompt-audit.ts";
20
21
  import { persistForegroundRunHistory, MAX_REMEMBERED_FOREGROUND_RUNS } from "./foreground-history.ts";
21
- import { resolveExecutionAgentScope } from "../../agents/agent-scope.ts";
22
+ import { projectScopeRequiresTrustMessage, resolveExecutionAgentScope } from "../../agents/agent-scope.ts";
22
23
  import { handleManagementAction } from "../../agents/agent-management.ts";
23
24
  import { handleRefinementAction } from "../../agents/agent-refinements.ts";
24
25
  import { buildDoctorReport } from "../../extension/doctor.ts";
@@ -77,10 +78,10 @@ import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeili
77
78
  import { isAgentContract } from "../shared/agent-contract.ts";
78
79
  import { normalizeExtensionBindings, type ExtensionBindings } from "../shared/extension-bindings.ts";
79
80
  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";
81
+ import { capInlineOutput, finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, outputPathMappingFromTask, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
81
82
  import { assertJsonSchemaObject, cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
82
83
  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";
84
+ import { discardPreservedWorktrees, formatParallelHandoffError, formatParallelHandoffReference, protectRetainedWorktreeForResume, formatStoredParallelHandoffCleanup, parallelHandoffPath, readParallelHandoffManifest, recordParallelHandoffMerge, recordParallelHandoffSupersession, writeParallelHandoffGroup, writeWorktreeSetupHandoff } from "../shared/parallel-handoff.ts";
84
85
  import { summarizeContextModes, type ContextMode, type ContextSummary } from "../shared/context-mode.ts";
85
86
  import {
86
87
  attachNestedChildrenToResultChildren,
@@ -105,8 +106,8 @@ import { promotePausedWorkflowIfSettled, reconcileDetachedWorkflowChildCompletio
105
106
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
106
107
  import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
107
108
  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";
109
+ import { fallbackResultPayloadPathForSessionRun, resultFilePath, retireResultSnapshot, writeAsyncResultFile } from "../background/result-files.ts";
110
+ 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
111
  import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
111
112
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
112
113
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
@@ -116,6 +117,7 @@ import { getExternalJobProvider } from "../../api/external-job-provider.ts";
116
117
  import { externalJobFollowUpRequestDigest, externalJobFollowUpRequestId, externalJobFollowUpRunId, externalJobPromptDigest, externalJobStableJson } from "../shared/external-job-runner.ts";
117
118
  import { externalCliReceiptMetadata, normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
118
119
  import { formatHerdrMachineRunnerUnsupported, resolveHerdrMachinePlacement } from "../shared/herdr-machine.ts";
120
+ import { lookupRunnerLauncher, resolveAgentRunnerLauncher } from "../shared/runner-launcher.ts";
119
121
  import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.ts";
120
122
  import { handleMissionAction, MISSION_ACTIONS } from "../../missions/actions.ts";
121
123
  import { attachMissionToLaunchResult, prepareMissionLaunch, writeMissionAsyncBinding, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
@@ -159,6 +161,7 @@ import {
159
161
  formatWorktreeDiffSummary,
160
162
  type WorktreeSetup,
161
163
  } from "../shared/worktree.ts";
164
+ import { applyReviewedCleanupPlan, formatCleanupReceipt, loadReviewedCleanupPlan } from "../shared/worktree-cleanup-apply.ts";
162
165
  import { createWorktreeCleanupPlan, formatWorktreeCleanupPlan } from "../shared/worktree-cleanup-plan.ts";
163
166
  import {
164
167
  type AgentProgress,
@@ -222,6 +225,7 @@ import {
222
225
  type SteeringTargetState,
223
226
  } from "../../shared/types.ts";
224
227
  import { deriveChildSessionName } from "../../shared/child-session-name.ts";
228
+ import { editDistance, hasSingleAdjacentTransposition } from "../../shared/edit-distance.ts";
225
229
 
226
230
  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
231
  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 +234,6 @@ function resolveSteerDeliveryMode(mode: SubagentParamsLike["mode"]): SteerDelive
230
234
  return mode === "steer" || mode === "follow_up" || mode === "auto" ? mode : undefined;
231
235
  }
232
236
 
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
237
  export function unknownSubagentActionMessage(action: string, disabled?: DisabledFeatureSurface): string {
259
238
  const requested = action.toLowerCase();
260
239
  const enabledActions = SUBAGENT_ACTIONS.filter((candidate) => !disabled?.actions.has(candidate));
@@ -435,7 +414,7 @@ export interface SubagentParamsLike {
435
414
  every?: string;
436
415
  sessionOnly?: boolean;
437
416
  quiet?: boolean;
438
- on?: string | number;
417
+ on?: string[];
439
418
  timezone?: string;
440
419
  overlap?: "skip";
441
420
  catchUp?: "none" | "latest";
@@ -461,6 +440,7 @@ function rememberParentModel(state: { currentSessionId?: string | null; lastPare
461
440
 
462
441
  interface ExecutorDeps {
463
442
  pi: ExtensionAPI;
443
+ parentWake?: Pick<ExtensionAPI, "sendMessage">;
464
444
  state: SubagentState;
465
445
  config: ExtensionConfig;
466
446
  asyncByDefault: boolean;
@@ -471,7 +451,7 @@ interface ExecutorDeps {
471
451
  tempArtifactsDir: string;
472
452
  getSubagentSessionRoot: (parentSessionFile: string | null) => string;
473
453
  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"] };
454
+ 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
455
  discoverAgentsAll?: typeof discoverAgentsAll;
476
456
  onAgentsChanged?: () => void;
477
457
  allowMutatingManagementActions?: boolean;
@@ -524,9 +504,12 @@ interface ExecutionContextData {
524
504
  backgroundRequestedWhileClarifying: boolean;
525
505
  effectiveAsync: boolean;
526
506
  asyncRunId: string;
507
+ toolCallId: string;
527
508
  controlConfig: ResolvedControlConfig;
528
509
  /** Structured delegation consumers do not need duration-only heartbeat snapshots. */
529
510
  suppressUnchangedDelegationUpdates?: boolean;
511
+ /** Internal delegated-launch binding hooks (never a model-facing parameter). */
512
+ supervisorLaunchHooks?: SupervisorLaunchHooks;
530
513
  intercomBridge: IntercomBridgeState;
531
514
  nestedRoute?: NestedRouteInfo;
532
515
  timeoutMs?: number;
@@ -685,6 +668,20 @@ function sessionProjectTrust(ctx: ExtensionContext): boolean | undefined {
685
668
  return typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : undefined;
686
669
  }
687
670
 
671
+ /** Agent and settings discovery follows the launching session's trust, like the child itself. */
672
+ function withSessionProjectTrust(deps: ExecutorDeps, ctx: ExtensionContext): ExecutorDeps {
673
+ if (sessionProjectTrust(ctx) !== false) return deps;
674
+ return { ...deps, discoverAgents: (cwd, scope, preferredModelProvider) => deps.discoverAgents(cwd, scope, preferredModelProvider, { projectTrusted: false }) };
675
+ }
676
+
677
+ function projectScopeTrustError(params: SubagentParamsLike, ctx: ExtensionContext): AgentToolResult<Details> | undefined {
678
+ if (sessionProjectTrust(ctx) !== false || resolveExecutionAgentScope(params.agentScope) !== "project") return undefined;
679
+ const action = typeof params.action === "string" ? params.action.trim() : undefined;
680
+ // These actions resolve agents in the requested scope; management actions are left to their own handlers.
681
+ if (action !== undefined && action !== "resume" && action !== "validate" && action !== "append-step") return undefined;
682
+ return buildRequestedModeError(params, projectScopeRequiresTrustMessage(resolveRequestedCwd(ctx.cwd, params.cwd)));
683
+ }
684
+
688
685
  function spawnBudgetErrorResult(message: string, mode: "single" | "parallel" | "chain"): AgentToolResult<Details> {
689
686
  return {
690
687
  content: [{ type: "text", text: message }],
@@ -851,6 +848,7 @@ function rememberForegroundRun(state: SubagentState, input: { modelResponseAlias
851
848
  ...(result.error ? { error: result.error } : {}),
852
849
  ...(result.finalOutput ? { finalOutput: result.finalOutput } : {}),
853
850
  ...(result.outputState ? { outputState: result.outputState } : {}),
851
+ ...(result.outputPartial ? { outputPartial: true } : {}),
854
852
  ...(result.outputMode ? { outputMode: result.outputMode } : {}),
855
853
  ...(result.savedOutputPath ? { savedOutputPath: result.savedOutputPath } : {}),
856
854
  ...(result.outputSaveError ? { outputSaveError: result.outputSaveError } : {}),
@@ -936,6 +934,7 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
936
934
  ...(input.result.error ? { error: input.result.error } : {}),
937
935
  ...(input.result.finalOutput ? { finalOutput: input.result.finalOutput } : {}),
938
936
  outputState: input.result.outputState,
937
+ outputPartial: input.result.outputPartial,
939
938
  outputMode: input.result.outputMode,
940
939
  savedOutputPath: input.result.savedOutputPath,
941
940
  outputSaveError: input.result.outputSaveError,
@@ -1237,7 +1236,7 @@ function interruptAsyncRun(
1237
1236
  kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean,
1238
1237
  location?: { asyncDir: string | null; resolvedId?: string },
1239
1238
  ): AgentToolResult<Details> | null {
1240
- const target = getAsyncInterruptTarget(state, runId, location);
1239
+ const target = getAsyncInterruptTarget(state, runId, location, { fallbackToNewest: runId === undefined });
1241
1240
  if (!target) return null;
1242
1241
  const status = reconcileAsyncRun(target.asyncDir, omitUndefinedProperties({ kill })).status;
1243
1242
  if (!status || status.state !== "running" || typeof status.pid !== "number") {
@@ -1432,6 +1431,7 @@ function appendStepToAsyncChain(input: {
1432
1431
  cwd: input.ctx.cwd,
1433
1432
  currentSessionId: resolveCurrentSessionId(input.ctx.sessionManager),
1434
1433
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1434
+ parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
1435
1435
  currentModelProvider: parentModel?.provider,
1436
1436
  currentModel: parentModel,
1437
1437
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
@@ -1443,6 +1443,17 @@ function appendStepToAsyncChain(input: {
1443
1443
  permissions: input.deps.config.permissions,
1444
1444
  childRuntime: input.deps.childRuntime,
1445
1445
  });
1446
+ // Appended steps run inside the already-running runner, so they must use its launcher (or none).
1447
+ // Checked before building, which can write progress files. A mix is refused by the builder.
1448
+ const appendedLaunchers = new Set(chain.flatMap(getStepAgents).map((name) => agents.find((agent) => agent.name === name)?.launcher));
1449
+ const appendedLauncher = [...appendedLaunchers][0];
1450
+ if (appendedLaunchers.size === 1 && appendedLauncher !== status.launcher?.name) {
1451
+ return {
1452
+ 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"}.` }],
1453
+ isError: true,
1454
+ details: { mode: "management", results: [] },
1455
+ };
1456
+ }
1446
1457
  const built = buildAsyncRunnerSteps(resolved.id, compactOptional<Parameters<typeof buildAsyncRunnerSteps>[1]>({
1447
1458
  chain: wrapChainTasksForFork(chain, contextPolicy),
1448
1459
  task: input.params.task,
@@ -1728,9 +1739,15 @@ async function interruptNestedRun(target: ResolvedSubagentRunId & { kind: "neste
1728
1739
  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
1740
  if (run.state === "paused") return { content: [{ type: "text", text: `Nested run ${run.id} is already paused.` }], isError: true, details: { mode: "management", results: [] } };
1730
1741
  const result = await sendNestedControlRequest(target, "interrupt");
1731
- if (result) return { content: [{ type: "text", text: result.message }], ...(result.ok ? {} : { isError: true }), details: { mode: "management", results: [] } };
1742
+ // The owner's foreground map cannot address a detached async child. Only
1743
+ // that missing-route response may use the existing authorized async inbox;
1744
+ // other owner refusals must remain authoritative.
1745
+ const missingForegroundRoute = result?.ok === false && result.message === nestedRunNotActiveMessage(run.id);
1746
+ if (result && !missingForegroundRoute) return { content: [{ type: "text", text: result.message }], ...(result.ok ? {} : { isError: true }), details: { mode: "management", results: [] } };
1732
1747
  const direct = directNestedAsyncInterrupt(target);
1733
1748
  if (direct) return direct;
1749
+ // No async inbox either: the owner's own answer is the accurate one.
1750
+ if (result) return { content: [{ type: "text", text: result.message }], isError: true, details: { mode: "management", results: [] } };
1734
1751
  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
1752
  }
1736
1753
 
@@ -1867,6 +1884,7 @@ async function resumeExternalJobFollowUp(input: {
1867
1884
  cwd: input.requestCwd,
1868
1885
  currentSessionId,
1869
1886
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1887
+ parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
1870
1888
  currentModelProvider: parentModel?.provider,
1871
1889
  currentModel: parentModel,
1872
1890
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
@@ -1993,7 +2011,7 @@ async function resumeAsyncRun(input: {
1993
2011
  type: "text",
1994
2012
  text: [
1995
2013
  `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: "..." }).`,
2014
+ `Send live input with subagent({ action: "steer", id: "${target.runId}", message: "...", options: { index: ${target.index} } }).`,
1997
2015
  ].join("\n"),
1998
2016
  }],
1999
2017
  isError: true,
@@ -2056,6 +2074,18 @@ async function resumeAsyncRun(input: {
2056
2074
  : "External runners do not persist Pi sessions and cannot be resumed.";
2057
2075
  return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
2058
2076
  }
2077
+ if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
2078
+ 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: [] } };
2079
+ }
2080
+ if (target.source === "async" && target.managedWorktree && target.asyncDir) {
2081
+ try {
2082
+ const protectedCwd = await protectRetainedWorktreeForResume(parallelHandoffPath(target.asyncDir), target.runId, target.index, input.signal);
2083
+ if (path.resolve(protectedCwd) !== path.resolve(effectiveCwd)) throw new Error("Retained worktree cwd changed during resume admission.");
2084
+ } catch (error) {
2085
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
2086
+ }
2087
+ }
2088
+
2059
2089
  if (target.source === "async" && target.runner?.type === "external-job") {
2060
2090
  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
2091
  const resumed = await resumeExternalJobFollowUp({
@@ -2119,7 +2149,7 @@ async function resumeAsyncRun(input: {
2119
2149
  const chain = wrapChainTasksForFork(attachChain, contextPolicy);
2120
2150
  const normalized = normalizeSkillInput(input.params.skill);
2121
2151
  const parentModel = input.parentModel;
2122
- const result = executeAsyncChain(runId, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
2152
+ const result = await executeAsyncChain(runId, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
2123
2153
  chain,
2124
2154
  task: workflowTask,
2125
2155
  goal,
@@ -2138,6 +2168,7 @@ async function resumeAsyncRun(input: {
2138
2168
  cwd: input.requestCwd,
2139
2169
  currentSessionId: input.deps.state.currentSessionId,
2140
2170
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
2171
+ parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
2141
2172
  currentModelProvider: parentModel?.provider,
2142
2173
  currentModel: parentModel,
2143
2174
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
@@ -2145,6 +2176,7 @@ async function resumeAsyncRun(input: {
2145
2176
  projectTrusted: currentProjectTrusted(input.ctx),
2146
2177
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2147
2178
  modelResponseAliases: input.deps.config.modelResponseAliases,
2179
+ runnerLaunchers: input.deps.config.runnerLaunchers,
2148
2180
  interactive: input.ctx.hasUI,
2149
2181
  permissions: input.deps.config.permissions,
2150
2182
  childRuntime: input.deps.childRuntime,
@@ -2202,16 +2234,14 @@ async function resumeAsyncRun(input: {
2202
2234
  if (!revivalSessionFile) {
2203
2235
  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
2236
  }
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
2237
  if (target.source === "async" && asyncReviveRequiresRecoveryDescriptor(target)) {
2209
2238
  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
2239
  }
2211
2240
  if (target.source === "nested" && !target.recoveryDescriptor) {
2212
2241
  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
2242
  }
2214
- const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
2243
+ // Runs without a recovery descriptor were never wrapped; a launcher added to the agent file later does not apply.
2244
+ const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : { ...baseAgentConfig, launcher: undefined };
2215
2245
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
2216
2246
  const foregroundContract = target.source === "foreground" ? target.resumeContract : undefined;
2217
2247
  const outputSchema = Object.hasOwn(input.params, "outputSchema")
@@ -2228,6 +2258,10 @@ async function resumeAsyncRun(input: {
2228
2258
  if (acceptanceErrors.length > 0) {
2229
2259
  return { content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }], isError: true, details: { mode: "management", results: [] } };
2230
2260
  }
2261
+ // Refuse before capacity moves so the retained run stays resumable once the config is fixed.
2262
+ if (agentConfig.launcher !== undefined && !lookupRunnerLauncher(input.deps.config.runnerLaunchers, agentConfig.launcher)) {
2263
+ 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: [] } };
2264
+ }
2231
2265
  const runId = randomUUID();
2232
2266
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
2233
2267
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
@@ -2269,6 +2303,7 @@ async function resumeAsyncRun(input: {
2269
2303
  cwd: input.requestCwd,
2270
2304
  currentSessionId: input.deps.state.currentSessionId,
2271
2305
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
2306
+ parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
2272
2307
  currentModelProvider: parentModel?.provider,
2273
2308
  currentModel: parentModel,
2274
2309
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
@@ -2277,6 +2312,7 @@ async function resumeAsyncRun(input: {
2277
2312
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2278
2313
  // Absence in the retained contract is meaningful; never acquire current aliases.
2279
2314
  modelResponseAliases: recoveryDescriptor ? recoveryDescriptor.modelResponseAliases : foregroundContract?.modelResponseAliases,
2315
+ runnerLaunchers: input.deps.config.runnerLaunchers,
2280
2316
  interactive: input.ctx.hasUI,
2281
2317
  permissions: input.deps.config.permissions,
2282
2318
  childRuntime: input.deps.childRuntime,
@@ -2423,10 +2459,12 @@ function formatFailedSingleRunOutput(result: SingleResult, displayOutput: string
2423
2459
  const error = result.error || "Failed";
2424
2460
  const output = displayOutput.trim();
2425
2461
  const lines = [error];
2462
+ let cappedOutput = output;
2426
2463
  if (output && output !== error.trim()) {
2427
- lines.push("", "Output:", output);
2464
+ cappedOutput = capInlineOutput(output, { artifactPath: result.artifactPaths?.outputPath, savedPath: result.savedOutputPath });
2465
+ lines.push("", "Output:", cappedOutput);
2428
2466
  }
2429
- if (result.artifactPaths?.outputPath && fs.existsSync(result.artifactPaths.outputPath)) {
2467
+ if (cappedOutput === output && result.artifactPaths?.outputPath && fs.existsSync(result.artifactPaths.outputPath)) {
2430
2468
  lines.push("", `Output artifact: ${result.artifactPaths.outputPath}`);
2431
2469
  }
2432
2470
  return lines.join("\n");
@@ -2500,6 +2538,7 @@ async function emitForegroundResultIntercom(input: {
2500
2538
  ...(result.sessionName ? { sessionName: result.sessionName } : {}),
2501
2539
  status: foregroundResultIntercomStatus(result),
2502
2540
  outputState: result.outputState ?? "unknown",
2541
+ ...(result.outputPartial ? { outputPartial: true } : {}),
2503
2542
  summary: resultSummaryForIntercom(result),
2504
2543
  index,
2505
2544
  artifactPath: result.artifactPaths?.outputPath,
@@ -2548,7 +2587,7 @@ async function maybeBuildForegroundIntercomReceipt(input: {
2548
2587
  }
2549
2588
 
2550
2589
  function diagnosticContextFromDiscovery(
2551
- discovered: { agents: AgentConfig[]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] },
2590
+ discovered: { agents: AgentConfig[]; disabledAgents?: string[]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] },
2552
2591
  cwd: string,
2553
2592
  scope: AgentScope,
2554
2593
  ): UnknownAgentDiagnosticContext {
@@ -2571,6 +2610,8 @@ function workflowValidationOptions(deps: ExecutorDeps, params: SubagentParamsLik
2571
2610
  const cwd = resolveRequestedCwd(runtimeCwd, params.cwd);
2572
2611
  const scope = resolveExecutionAgentScope(params.agentScope);
2573
2612
  let discovered: ReturnType<ExecutorDeps["discoverAgents"]> | undefined;
2613
+ // Validation reports every bad agent name; only the first one carries the agent list.
2614
+ let listedAgents = false;
2574
2615
  return {
2575
2616
  maxSubagentSpawnsPerRun: params.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
2576
2617
  agentNameError: (name) => {
@@ -2578,12 +2619,12 @@ function workflowValidationOptions(deps: ExecutorDeps, params: SubagentParamsLik
2578
2619
  const { agents } = discovered;
2579
2620
  const resolved = resolveAgentName(name, agents);
2580
2621
  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.`;
2622
+ const disabled = discovered.disabledAgents?.includes(name.trim()) === true;
2623
+ const suggestion = disabled ? undefined : suggestAgentName(name, agents);
2624
+ const problem = disabled ? `Agent '${name}' is disabled by a settings override.` : `Unknown agent '${name}'.${suggestion ? ` Did you mean '${suggestion}'?` : ""}`;
2625
+ if (listedAgents) return problem;
2626
+ listedAgents = true;
2627
+ return [`${problem} Available agents:`, ...formatAvailableAgentLines(agents)].join("\n");
2587
2628
  },
2588
2629
  };
2589
2630
  }
@@ -3390,11 +3431,11 @@ function importedAsyncRootUsage(completed: Awaited<ReturnType<typeof waitForImpo
3390
3431
 
3391
3432
  function removeWorkflowAwaitedResult(asyncDir: string, resultPath: string, runId: string, publication: NonNullable<Awaited<ReturnType<typeof waitForImportedAsyncRoot>>["importedPublication"]>): void {
3392
3433
  try {
3393
- fs.rmSync(resultPath, { force: true });
3394
- } catch {
3395
- // Payload cleanup must not replace an already imported delivery.
3434
+ retireResultSnapshot(workflowAwaitedAsyncResultPath(asyncDir), { ...publication, runId }, resultPath);
3435
+ } catch (error) {
3436
+ // Cleanup must not replace an already imported delivery.
3437
+ console.error(`Failed to remove imported workflow child result '${resultPath}'; leaving it in place:`, error);
3396
3438
  }
3397
- removeResultIndex(asyncDir, publication.sessionId, runId, publication.toolCallId);
3398
3439
  }
3399
3440
 
3400
3441
  function emitWorkflowAwaitedChildComplete(
@@ -3551,13 +3592,16 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3551
3592
  cwd: ctx.cwd,
3552
3593
  currentSessionId: data.parentSessionId!,
3553
3594
  parentSessionId: data.parentPiSessionId,
3595
+ parentSessionFile: ctx.sessionManager.getSessionFile() ?? undefined,
3554
3596
  currentModelProvider: parentModel?.provider,
3555
3597
  currentModel: parentModel,
3556
3598
  scopedModelIds: data.scopedModelIds,
3557
3599
  modelScope: data.modelScope,
3558
3600
  projectTrusted: currentProjectTrusted(ctx),
3559
3601
  ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3560
- modelResponseAliases: deps.config.modelResponseAliases, interactive: ctx.hasUI,
3602
+ modelResponseAliases: deps.config.modelResponseAliases,
3603
+ runnerLaunchers: deps.config.runnerLaunchers,
3604
+ interactive: ctx.hasUI,
3561
3605
  permissions: deps.config.permissions,
3562
3606
  childRuntime: deps.childRuntime,
3563
3607
  });
@@ -3618,6 +3662,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3618
3662
  const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: a.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
3619
3663
  if (launchRuleError) return toExecutionErrorResult(params, new Error(launchRuleError), data.contextPolicy.contextSummary);
3620
3664
  const asyncResult = await executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
3665
+ toolCallId: data.toolCallId,
3621
3666
  agent: params.agent!,
3622
3667
  task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(params.task ?? "") : (params.task ?? ""),
3623
3668
  goal: params.task ?? "",
@@ -3862,7 +3907,7 @@ function resolveWorkflowChildOutputPath(input: {
3862
3907
  state?: SubagentState;
3863
3908
  key: string;
3864
3909
  params: Record<string, unknown>;
3865
- }): { path?: string; inherited: boolean } {
3910
+ }): { path?: string; inherited: boolean; resumedOutput?: string } {
3866
3911
  const rawOutput = input.params.output;
3867
3912
  const hasExplicitOutput = typeof rawOutput === "string" || typeof rawOutput === "boolean";
3868
3913
  if (typeof input.params.resume === "string" && (!hasExplicitOutput || rawOutput === true || rawOutput === "true")) {
@@ -3872,7 +3917,11 @@ function resolveWorkflowChildOutputPath(input: {
3872
3917
  id: input.params.resume.trim(),
3873
3918
  ...(typeof index === "number" && Number.isInteger(index) ? { index } : {}),
3874
3919
  }, input.state);
3875
- return { path: "recoveryDescriptor" in target ? target.recoveryDescriptor?.outputPath : undefined, inherited: false };
3920
+ const recoveryOutput = "recoveryDescriptor" in target ? target.recoveryDescriptor?.outputPath : undefined;
3921
+ if (hasExplicitOutput) return { path: recoveryOutput, inherited: false };
3922
+ // An output-less foreground resume reuses its recorded output; only an absolute path is known before the new run id exists.
3923
+ const foregroundOutput = target.source === "foreground" ? target.resumeContract?.output : undefined;
3924
+ return { path: recoveryOutput, inherited: false, resumedOutput: recoveryOutput ?? (typeof foregroundOutput === "string" && path.isAbsolute(foregroundOutput) ? foregroundOutput : undefined) };
3876
3925
  }
3877
3926
  const childCwd = resolveWorkflowChildLocalCwd(input);
3878
3927
  let agentOutput: string | undefined;
@@ -3925,7 +3974,9 @@ function workflowChildOutputClaims(input: {
3925
3974
  }
3926
3975
  const overrides = new Map<string, string>();
3927
3976
  for (const entry of resolvedEntries) {
3928
- if (entry.inherited && entry.path && (paths.get(resolveWorkflowHostOutputClaimPath(entry.path)) ?? 0) > 1) {
3977
+ // An output-less resume keeps its retained path unless an earlier child of this workflow already owns it.
3978
+ const resumeCollides = entry.resumedOutput !== undefined && input.claimedOutputPaths.has(resolveWorkflowHostOutputClaimPath(entry.resumedOutput));
3979
+ if (resumeCollides || (entry.inherited && entry.path && (paths.get(resolveWorkflowHostOutputClaimPath(entry.path)) ?? 0) > 1)) {
3929
3980
  const output = workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.workflowRunId, entry.key);
3930
3981
  overrides.set(entry.key, output);
3931
3982
  entry.path = output;
@@ -3941,6 +3992,14 @@ function workflowChildOutputClaims(input: {
3941
3992
  claims.set(claimPath, key);
3942
3993
  childClaims.set(key, claimPath);
3943
3994
  }
3995
+ // Record a discovered output-less resume path for later admissions without adding same-batch duplicate errors.
3996
+ for (const { key, path: resolved, resumedOutput } of resolvedEntries) {
3997
+ if (resolved || !resumedOutput) continue;
3998
+ const claimPath = resolveWorkflowHostOutputClaimPath(resumedOutput);
3999
+ if (claims.has(claimPath)) continue;
4000
+ claims.set(claimPath, key);
4001
+ childClaims.set(key, claimPath);
4002
+ }
3944
4003
  return { claims, childClaims, overrides };
3945
4004
  }
3946
4005
 
@@ -3968,7 +4027,7 @@ function prepareWorkflowChildLaunchParams(input: {
3968
4027
  }): SubagentParamsLike {
3969
4028
  let childParams = input.childParams;
3970
4029
  const usesDefaultOutput = input.childParams.output === undefined && input.childParams.resume === undefined;
3971
- if (usesDefaultOutput && input.outputOverride !== undefined) {
4030
+ if (input.childParams.output === undefined && input.outputOverride !== undefined) {
3972
4031
  childParams = { ...input.childParams, output: input.outputOverride };
3973
4032
  } else if (usesDefaultOutput && input.aggregateOutputPath !== undefined) {
3974
4033
  childParams = { ...input.childParams, output: workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.parentWorkflowRunId, input.workflowKey) };
@@ -3982,7 +4041,7 @@ function prepareWorkflowChildLaunchParams(input: {
3982
4041
  const agent = typeof childParams.agent === "string"
3983
4042
  ? resolveAgentName(childParams.agent, discoveredAgents).agent ?? resolveAgentName(childParams.agent, input.agents).agent
3984
4043
  : undefined;
3985
- const externalAsyncRequired = agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job";
4044
+ const externalAsyncRequired = agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job" || agent?.launcher !== undefined;
3986
4045
  return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, { ...input.options, externalAsyncRequired, outputClaimPath: input.outputClaimPath });
3987
4046
  }
3988
4047
 
@@ -4108,6 +4167,22 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4108
4167
  details: { mode: "single", results: [] },
4109
4168
  };
4110
4169
  }
4170
+ // Internal delegated-launch binding: the real runId and canonical agent now
4171
+ // exist and no child prompt has been sent yet. A binding conflict or an
4172
+ // identity change must fail here, before any model call.
4173
+ if (data.supervisorLaunchHooks) {
4174
+ try {
4175
+ data.supervisorLaunchHooks.beforeNativeChildLaunch({
4176
+ runId,
4177
+ agent: agentConfig.name,
4178
+ childIndex: 0,
4179
+ ...(data.parentPiSessionId ? { parentSessionId: data.parentPiSessionId } : {}),
4180
+ bridgeActive: childBridgeActive,
4181
+ });
4182
+ } catch (error) {
4183
+ return toExecutionErrorResult(params, error instanceof Error ? error : new Error(String(error)), contextPolicy.contextSummary);
4184
+ }
4185
+ }
4111
4186
  let foregroundMachine: import("../../shared/types.ts").HerdrMachineReference | undefined;
4112
4187
  const requestedMachine = params.machine ?? agentConfig.machine;
4113
4188
  const requiredExtensions = data.requiredExtensions ?? deps.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(data.parentPiSessionId);
@@ -4258,6 +4333,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4258
4333
  const interruptController = new AbortController();
4259
4334
  let detachForeground: ((reason?: string) => boolean) | undefined;
4260
4335
  let childSessionControls: ForegroundChildSessionControls | undefined;
4336
+ let pendingRuntimeStop: string | undefined;
4261
4337
  const foregroundControl = deps.state.foregroundControls.get(runId);
4262
4338
  const syncHerdrForegroundChild = () => {
4263
4339
  if (!foregroundControl?.parentWorkflowRunId) return;
@@ -4326,6 +4402,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4326
4402
  ? new Promise<Awaited<ReturnType<typeof runSync>>>((resolve) => { resolveDetachedWorkflowChild = resolve; })
4327
4403
  : undefined;
4328
4404
  try {
4405
+ const childSessionFile = sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin);
4329
4406
  const launched = await runSync(ctx.cwd, agents, params.agent!, task, compactOptional<Parameters<typeof runSync>[4]>({
4330
4407
  machine: foregroundMachine,
4331
4408
  parentProviderRegistry: ctx.modelRegistry,
@@ -4335,9 +4412,13 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4335
4412
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
4336
4413
  projectTrusted: currentProjectTrusted(ctx),
4337
4414
  ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
4415
+ parentSessionFile: ctx.sessionManager.getSessionFile() ?? undefined,
4338
4416
  requiredExtensions,
4339
4417
  childRuntime: deps.childRuntime,
4340
- onChildSession: (controls) => { childSessionControls = controls; },
4418
+ onChildSession: (controls) => {
4419
+ childSessionControls = controls;
4420
+ if (pendingRuntimeStop) controls.stop(pendingRuntimeStop);
4421
+ },
4341
4422
  context: data.contextPolicy.contextForAgent(params.agent!),
4342
4423
  unknownAgentDiagnosticContext: data.unknownAgentDiagnosticContext,
4343
4424
  runFanoutBudget: params.runFanoutAdmitted ? data.runFanoutBudget : { ...data.runFanoutBudget, parentPath: `${data.runFanoutBudget.parentPath ? `${data.runFanoutBudget.parentPath}/` : ""}single` },
@@ -4350,7 +4431,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4350
4431
  intercomEvents: deps.pi.events,
4351
4432
  runId,
4352
4433
  sessionDir: sessionDirForIndex(0),
4353
- sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
4434
+ sessionFile: childSessionFile,
4354
4435
  share: shareEnabled,
4355
4436
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
4356
4437
  artifactConfig,
@@ -4391,6 +4472,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4391
4472
  detachForeground = detach;
4392
4473
  },
4393
4474
  onDetachedExit: async (result) => {
4475
+ if (foregroundControl) foregroundControl.stopForRuntimeReplacement = undefined;
4394
4476
  if (resolveDetachedWorkflowChild) {
4395
4477
  resolveDetachedWorkflowChild(result);
4396
4478
  return;
@@ -4437,6 +4519,18 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4437
4519
  capabilityCeiling: data.capabilityCeiling,
4438
4520
  allowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,
4439
4521
  }));
4522
+ if (launched.detached && foregroundControl) {
4523
+ // Record the stop before aborting so the next runtime's history restore finds it.
4524
+ foregroundControl.stopForRuntimeReplacement = () => {
4525
+ // The detach receipt predates the session file that resume needs.
4526
+ const sessionFile = childSessionFile && fs.existsSync(childSessionFile) ? childSessionFile : undefined;
4527
+ const stopped = { ...launched, detached: undefined, stopped: true, exitCode: 1, error: RUNTIME_REPLACED_STOP_ERROR, finalOutput: RUNTIME_REPLACED_STOP_ERROR, sessionFile };
4528
+ rememberForegroundRun(deps.state, { modelResponseAliases, runId, mode: "single", cwd: singleCwd, sessionId: data.parentSessionId, results: [stopped], params, effectiveOutput, effectiveOutputMode, extensionBindings: params.extensionBindings, requiredExtensions });
4529
+ // A child detached during creation has no controls yet; stop it as soon as they arrive.
4530
+ if (childSessionControls) childSessionControls.stop(RUNTIME_REPLACED_STOP_ERROR);
4531
+ else pendingRuntimeStop = RUNTIME_REPLACED_STOP_ERROR;
4532
+ };
4533
+ }
4440
4534
  r = launched.detached && detachedWorkflowChild ? await detachedWorkflowChild : launched;
4441
4535
  } catch (error) {
4442
4536
  await cleanupSingleWorktree();
@@ -4548,7 +4642,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4548
4642
  isError: true,
4549
4643
  };
4550
4644
  return {
4551
- content: [{ type: "text", text: `${finalizedOutput.displayOutput || "(no output)"}${worktreeSuffix}` }],
4645
+ content: [{ type: "text", text: `${capInlineOutput(finalizedOutput.displayOutput, { artifactPath: r.artifactPaths?.outputPath, savedPath: finalizedOutput.savedPath }) || "(no output)"}${worktreeSuffix}` }],
4552
4646
  details,
4553
4647
  };
4554
4648
  }
@@ -4766,7 +4860,7 @@ function workflowRunningChildrenSummary(children: WorkflowScriptChildResult[]):
4766
4860
  function workflowResultChildren(children: WorkflowScriptChildResult[], status: AsyncStatus, includeFailureFields: boolean) {
4767
4861
  return withWorkflowRevivals(DIRS.async, status.runId, children).map((child) => {
4768
4862
  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 } } : {}) };
4863
+ 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
4864
  });
4771
4865
  }
4772
4866
 
@@ -4803,6 +4897,7 @@ function workflowSteerReceipt(key: string, result: AgentToolResult<Details>): Wo
4803
4897
  }
4804
4898
 
4805
4899
  const CHILD_SESSION_NOT_RUNNING_YET = "Child session is not running yet.";
4900
+ const RUNTIME_REPLACED_STOP_ERROR = "Subagent stopped because the pi-subagents runtime that ran it was replaced (reload or session switch).";
4806
4901
  const MAX_WORKFLOW_RESUME_HINT_BYTES = 1024;
4807
4902
  const MAX_WORKFLOW_CHILD_RUN_ID_BYTES = 256;
4808
4903
  const WORKFLOW_RESUME_HINT_PARENT_STATES = new Set(["complete", "failed", "partial"]);
@@ -5336,6 +5431,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5336
5431
  signal: AbortSignal,
5337
5432
  onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
5338
5433
  ctx: ExtensionContext,
5434
+ supervisorLaunchHooks?: SupervisorLaunchHooks,
5339
5435
  ) => Promise<AgentToolResult<Details>>;
5340
5436
  /** Scheduled launches retain their owning context without replacing the live active session. */
5341
5437
  executeScheduled: (
@@ -5347,7 +5443,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5347
5443
  /** Scheduled state visible to the current runtime supervisor owner only. */
5348
5444
  getCurrentSupervisorOwnerStates: () => Iterable<SubagentState>;
5349
5445
  } {
5446
+ const executorDeps = deps;
5350
5447
  const delegatedThinkingOverrides = new WeakMap<object, AgentConfig["thinking"]>();
5448
+ const delegatedSupervisorLaunchHooks = new WeakMap<object, SupervisorLaunchHooks>();
5351
5449
  const delegatedZeroToolBudgets = new WeakSet<object>();
5352
5450
  const delegatedExecutions = new WeakSet<object>();
5353
5451
  const publicExecutions = new WeakSet<object>();
@@ -5376,10 +5474,14 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5376
5474
  preserveActiveSession = false,
5377
5475
  parentModelOverride?: ParentModel | null,
5378
5476
  ): Promise<AgentToolResult<Details>> => {
5477
+ const projectScopeError = projectScopeTrustError(params, ctx);
5478
+ if (projectScopeError) return projectScopeError;
5479
+ const deps = withSessionProjectTrust(executorDeps, ctx);
5379
5480
  const workflowLaunchObserver = workflowLaunchObservers.get(params);
5380
5481
  const inheritedUsageBudget = workflowOwnedUsageBudgets.get(params);
5381
5482
  const retainedRequiredExtensions = workflowRetainedRequiredExtensions.get(params);
5382
5483
  const delegatedThinkingOverride = delegatedThinkingOverrides.get(params);
5484
+ const supervisorLaunchHooks = delegatedSupervisorLaunchHooks.get(params);
5383
5485
  const allowZeroToolBudget = delegatedZeroToolBudgets.has(params);
5384
5486
  const delegatedExecution = delegatedExecutions.has(params);
5385
5487
  const publicExecution = publicExecutions.has(params);
@@ -5671,7 +5773,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5671
5773
  if (resultWriteFailureWakeDelivered) return false;
5672
5774
  if (deps.state.currentSessionId !== currentSessionId || deps.state.completionOwnerId !== completionOwnerId) return false;
5673
5775
  try {
5674
- deps.pi.sendMessage(
5776
+ (deps.parentWake ?? deps.pi).sendMessage(
5675
5777
  {
5676
5778
  customType: "subagent-workflow-result-write-failed",
5677
5779
  content: message,
@@ -6164,6 +6266,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6164
6266
  onChildSettled: (notification) => {
6165
6267
  const journalFingerprint = workflowJournalFingerprints.get(notification.childKey);
6166
6268
  if (journalFingerprint) appendWorkflowChildJournal(asyncDir, { type: "settle", key: notification.childKey, fingerprint: journalFingerprint, result: notification.result });
6269
+ // Fresh, journal-reused and re-attached children all settle here, so their rows take usage from the same result.
6270
+ const settledResults = notification.result.results ?? [];
6271
+ const settledStep = settledResults.length ? status.steps?.find((candidate) => candidate.workflowKey === notification.childKey) : undefined;
6272
+ if (settledStep) {
6273
+ const usage = sumResultsUsage(settledResults);
6274
+ settledStep.tokens = { input: usage.input, output: usage.output, total: usage.input + usage.output };
6275
+ if (usage.turns > 0) settledStep.turnCount = usage.turns;
6276
+ persist({ tolerateStatusWriteFailure: true });
6277
+ }
6167
6278
  appendWorkflowEvent({
6168
6279
  type: "subagent.workflow.child_settled",
6169
6280
  childKey: notification.childKey,
@@ -6172,11 +6283,13 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6172
6283
  workflowRunning: notification.workflowRunning,
6173
6284
  });
6174
6285
  try {
6175
- deps.pi.sendMessage(
6286
+ (deps.parentWake ?? deps.pi).sendMessage(
6176
6287
  {
6177
6288
  customType: "subagent-incremental-child-notify",
6178
6289
  content: formatIncrementalChildCompletion(notification),
6179
6290
  display: notification.outcome !== "completed",
6291
+ // Render-only: Pi does not send details to the model.
6292
+ details: { childKey: notification.childKey, outcome: notification.outcome },
6180
6293
  },
6181
6294
  { triggerTurn: incrementalChildCompletionTriggersTurn(notification, requestParams.scheduleOrigin) },
6182
6295
  );
@@ -6230,7 +6343,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6230
6343
  appendWorkflowChildJournal(asyncDir, { type: "start", key, fingerprint: journalFingerprint, runId: priorRunId });
6231
6344
  const stopListener = stopAwaitedAsyncChildOnAbort(workflowSignal, deps.state, priorRunId, priorAsyncDir, deps.kill);
6232
6345
  const reattached = await awaitExistingAsyncRun(priorAsyncDir, priorRunId, workflowSignal).finally(stopListener.remove);
6233
- const claimedPath = reattached.status === "settled" ? claimWorkflowAwaitedResult(priorAsyncDir, workflowRunId) : undefined;
6346
+ const claimedPath = reattached.status === "settled" ? claimWorkflowAwaitedResult(priorAsyncDir, workflowRunId, { ...reattached.result.importedPublication, runId: priorRunId }) : undefined;
6234
6347
  if (reattached.status === "settled" && claimedPath) {
6235
6348
  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
6349
  const reattachedResult = workflowChildResult(key, imported, childParams, deps.state);
@@ -6713,11 +6826,30 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6713
6826
  if (deps.allowMutatingManagementActions === false) {
6714
6827
  return { content: [{ type: "text", text: "Action 'worktree.cleanup' is not available from child-safe subagent fanout mode." }], isError: true, details: { mode: "management", results: [] } };
6715
6828
  }
6829
+ if (paramsWithResolvedCwd.mode === "apply") {
6830
+ try {
6831
+ if (!paramsWithResolvedCwd.repo?.trim() || !paramsWithResolvedCwd.planId?.trim() || paramsWithResolvedCwd.handoffPath !== undefined) throw new Error("worktree.cleanup apply requires explicit repo and planId, without handoffPath.");
6832
+ const repo = path.resolve(requestCwd, paramsWithResolvedCwd.repo);
6833
+ const plan = loadReviewedCleanupPlan(repo, paramsWithResolvedCwd.planId);
6834
+ const decision = resolveAuthorityDecision({ action: "discardWorktree", ...(deps.config.authorityPolicy === undefined ? {} : { policy: deps.config.authorityPolicy }) });
6835
+ if (decision === "forbid") throw new Error("Authority policy forbids worktree cleanup.");
6836
+ if (decision === "confirm") {
6837
+ if (!ctx.hasUI) throw new Error("Authority policy requires interactive confirmation for worktree cleanup.");
6838
+ 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: [] } };
6839
+ }
6840
+ const applied = await applyReviewedCleanupPlan({ repo: plan.repoRoot, planId: plan.planId, authorized: true, signal,
6841
+ 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",
6842
+ });
6843
+ return { content: [{ type: "text", text: formatCleanupReceipt(applied) }], details: { mode: "management", results: [] } };
6844
+ } catch (error) {
6845
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
6846
+ }
6847
+ }
6716
6848
  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: [] } };
6849
+ return { content: [{ type: "text", text: "worktree.cleanup requires mode='plan' or mode='apply'." }], isError: true, details: { mode: "management", results: [] } };
6718
6850
  }
6719
6851
  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: [] } };
6852
+ return { content: [{ type: "text", text: "worktree.cleanup plan mode does not accept planId." }], isError: true, details: { mode: "management", results: [] } };
6721
6853
  }
6722
6854
  try {
6723
6855
  const created = createWorktreeCleanupPlan({
@@ -6952,7 +7084,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6952
7084
  if (action === "guide") {
6953
7085
  try {
6954
7086
  const guide = readSubagentGuide(paramsWithResolvedCwd.topic);
6955
- const notice = paramsWithResolvedCwd.topic === "tool-reference" ? disabledFeatureNotice(disabledFeatures) : undefined;
7087
+ const [topic, section] = paramsWithResolvedCwd.topic?.split("/") ?? [];
7088
+ const fullNotice = topic === "tool-reference" ? disabledFeatureNotice(disabledFeatures) : undefined;
7089
+ // Sections are capped at 8,000 chars, so they get a one-line pointer instead of the full list.
7090
+ 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
7091
  return {
6957
7092
  content: [{ type: "text", text: notice ? `${notice}\n\n${guide}` : guide }],
6958
7093
  details: { mode: "management", results: [] },
@@ -6976,10 +7111,13 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6976
7111
  if (action === "doctor") {
6977
7112
  let currentSessionFile: string | null = null;
6978
7113
  let currentSessionId = deps.state.currentSessionId;
7114
+ let budgetSessionId = deps.state.currentSessionId;
6979
7115
  let sessionError: string | undefined;
6980
7116
  try {
6981
7117
  currentSessionFile = ctx.sessionManager.getSessionFile() ?? null;
6982
7118
  currentSessionId = ctx.sessionManager.getSessionId();
7119
+ // Launch admission's key (resolveCurrentSessionId) without its throw for an unbound session.
7120
+ budgetSessionId = currentSessionFile ?? currentSessionId;
6983
7121
  } catch (error) {
6984
7122
  sessionError = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
6985
7123
  }
@@ -6989,9 +7127,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6989
7127
  } catch (error) {
6990
7128
  if (!sessionError) sessionError = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
6991
7129
  }
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) })
7130
+ const spawnBudget = getSpawnBudgetSnapshot(deps.state, deps.config, budgetSessionId);
7131
+ const activeAsyncCapacity = budgetSessionId
7132
+ ? getActiveAsyncCapacitySnapshot(budgetSessionId, resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps.config.capacity?.abandonedSlotReleaseAfterMs) })
6995
7133
  : { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession) ?? 0 };
6996
7134
  deps.state.activeAsyncCapacity = activeAsyncCapacity;
6997
7135
  return {
@@ -7005,6 +7143,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7005
7143
  requestedSessionDir: paramsWithResolvedCwd.sessionDir,
7006
7144
  currentSessionFile,
7007
7145
  currentSessionId,
7146
+ spawnBudget,
7147
+ activeAsyncCapacity,
7008
7148
  orchestratorTarget,
7009
7149
  sessionError,
7010
7150
  expandTilde: deps.expandTilde,
@@ -7513,16 +7653,27 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7513
7653
  : hasTasks
7514
7654
  ? (effectiveParams.tasks ?? []).map((task) => task.agent)
7515
7655
  : (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;
7656
+ const selectedAgents = selectedAgentNames.map((name) => agents.find((agent) => agent.name === name));
7657
+ const externalAgent = selectedAgents.find((agent) => agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job");
7658
+ const launcherAgent = selectedAgents.find((agent) => agent?.launcher !== undefined);
7659
+ // A launcher agent goes to the background whenever the caller omitted async, even if the agent file defaults to foreground.
7660
+ const externalAsyncRequired = effectiveParams.foregroundOnly !== true && ((Boolean(externalAgent) && effectiveParams.async === undefined && effectiveParams.clarify !== true)
7661
+ || (Boolean(launcherAgent) && normalizedParams.async === undefined && normalizedParams.clarify !== true));
7520
7662
  const requestedAsync = externalAsyncRequired ? true : effectiveParams.async ?? deps.asyncByDefault;
7521
7663
  const backgroundRequestedWhileClarifying = (hasChain || hasTasks) && requestedAsync && effectiveParams.clarify === true;
7522
7664
  const effectiveAsync = requestedAsync && effectiveParams.clarify !== true;
7523
7665
  if (externalAgent && (!effectiveAsync || effectiveParams.foregroundOnly === true)) {
7524
7666
  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
7667
  }
7668
+ // forceTopLevelAsync rewrites async:false and clarify, so check what the caller asked for.
7669
+ if (launcherAgent && (!effectiveAsync || normalizedParams.async === false || normalizedParams.clarify === true || effectiveParams.foregroundOnly === true)) {
7670
+ 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.`);
7671
+ }
7672
+ // Refuse a launcher launch that cannot start before fan-out admission or a session directory exists.
7673
+ for (const agent of selectedAgents) {
7674
+ const launcherError = agent ? resolveAgentRunnerLauncher(agent, deps.config.runnerLaunchers, effectiveParams.machine ?? agent.machine).error : undefined;
7675
+ if (launcherError) return buildRequestedModeError(effectiveParams, launcherError);
7676
+ }
7526
7677
  if (effectiveAsync && hasSingle && effectiveParams.resume === undefined && effectiveParams.worktree === true) {
7527
7678
  try {
7528
7679
  await preflightWorktreeSource(effectiveCwd, { signal });
@@ -7725,8 +7876,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7725
7876
  backgroundRequestedWhileClarifying,
7726
7877
  effectiveAsync,
7727
7878
  asyncRunId,
7879
+ toolCallId: _id,
7728
7880
  controlConfig,
7729
7881
  ...(delegatedExecution ? { suppressUnchangedDelegationUpdates: true } : {}),
7882
+ ...(supervisorLaunchHooks ? { supervisorLaunchHooks } : {}),
7730
7883
  intercomBridge,
7731
7884
  nestedRoute,
7732
7885
  timeoutMs: foregroundTimeout.timeoutMs,
@@ -8042,6 +8195,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
8042
8195
  signal: AbortSignal,
8043
8196
  onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
8044
8197
  ctx: ExtensionContext,
8198
+ supervisorLaunchHooks?: SupervisorLaunchHooks,
8045
8199
  ): Promise<AgentToolResult<Details>> => {
8046
8200
  const disabledFeatureError = disabledFeatureResult(params);
8047
8201
  if (disabledFeatureError) return disabledFeatureError;
@@ -8058,6 +8212,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
8058
8212
  delete privateParams.delegatedAllowZeroToolBudget;
8059
8213
  delete privateParams.delegatedWorkflowPermit;
8060
8214
  if (thinkingOverride !== undefined) delegatedThinkingOverrides.set(delegatedParams, thinkingOverride);
8215
+ if (supervisorLaunchHooks) delegatedSupervisorLaunchHooks.set(delegatedParams, supervisorLaunchHooks);
8061
8216
  if (allowZeroToolBudget) delegatedZeroToolBudgets.add(delegatedParams);
8062
8217
  if (workflowPermit) workflowPermitContexts.set(delegatedParams, { root: workflowPermit });
8063
8218
  delegatedExecutions.add(delegatedParams);