@xzzpig/pi-subagents 0.19.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 (153) hide show
  1. package/CHANGELOG.md +214 -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 +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  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 +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -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 +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  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 +29 -8
  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-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -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";
@@ -27,6 +27,7 @@ import { isWorkflowScriptPath, normalizePublicSubagentExecution, validateWorkflo
27
27
  import { readReplyWorkflowScript } from "../../extension/reply-workflow-script.ts";
28
28
  import { disabledFeatureNotice, disabledFeatureUseError, resolveDisabledFeatureSurface, type DisabledFeatureSurface } from "../../shared/disabled-features.ts";
29
29
  import { runSync } from "./execution.ts";
30
+ import { commandAction } from "./command-action.ts";
30
31
  import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/tool-actions.ts";
31
32
  import type { MainWatchdogRuntime } from "../../watchdog/runtime.ts";
32
33
  import { applyWatchdogLaunchRules } from "../../watchdog/rules.ts";
@@ -75,11 +76,11 @@ import { usageBudgetExceededMessage, usageBudgetState, validateUsageBudgetConfig
75
76
  import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
76
77
  import { isAgentContract } from "../shared/agent-contract.ts";
77
78
  import { normalizeExtensionBindings, type ExtensionBindings } from "../shared/extension-bindings.ts";
78
- import { resolveRequiredChildExtensions } from "../../shared/required-child-extensions.ts";
79
- import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, outputPathMappingFromTask, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
79
+ import { assertRequiredChildExtensionsAdmitted, hasMandatoryRequiredChildExtensions, readRetainedRequiredChildExtensions, resolveRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
80
+ import { capInlineOutput, finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, outputPathMappingFromTask, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
80
81
  import { assertJsonSchemaObject, cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
81
82
  import { compactForegroundDetails, getSingleResultOutput, PROMPT_REDACTED, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage, toAgentToolUsage } from "../../shared/utils.ts";
82
- 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";
83
84
  import { summarizeContextModes, type ContextMode, type ContextSummary } from "../shared/context-mode.ts";
84
85
  import {
85
86
  attachNestedChildrenToResultChildren,
@@ -104,8 +105,8 @@ import { promotePausedWorkflowIfSettled, reconcileDetachedWorkflowChildCompletio
104
105
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
105
106
  import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
106
107
  import { awaitExistingAsyncRun, claimWorkflowAwaitedResult } from "../background/await-async-run.ts";
107
- import { fallbackResultPayloadPathForSessionRun, removeResultIndex, resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
108
- 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";
109
110
  import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
110
111
  import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
111
112
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
@@ -115,6 +116,7 @@ import { getExternalJobProvider } from "../../api/external-job-provider.ts";
115
116
  import { externalJobFollowUpRequestDigest, externalJobFollowUpRequestId, externalJobFollowUpRunId, externalJobPromptDigest, externalJobStableJson } from "../shared/external-job-runner.ts";
116
117
  import { externalCliReceiptMetadata, normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
117
118
  import { formatHerdrMachineRunnerUnsupported, resolveHerdrMachinePlacement } from "../shared/herdr-machine.ts";
119
+ import { lookupRunnerLauncher, resolveAgentRunnerLauncher } from "../shared/runner-launcher.ts";
118
120
  import { applyForceTopLevelAsyncOverride } from "../background/top-level-async.ts";
119
121
  import { handleMissionAction, MISSION_ACTIONS } from "../../missions/actions.ts";
120
122
  import { attachMissionToLaunchResult, prepareMissionLaunch, writeMissionAsyncBinding, type MissionLaunchBinding } from "../../missions/lifecycle.ts";
@@ -158,6 +160,7 @@ import {
158
160
  formatWorktreeDiffSummary,
159
161
  type WorktreeSetup,
160
162
  } from "../shared/worktree.ts";
163
+ import { applyReviewedCleanupPlan, formatCleanupReceipt, loadReviewedCleanupPlan } from "../shared/worktree-cleanup-apply.ts";
161
164
  import { createWorktreeCleanupPlan, formatWorktreeCleanupPlan } from "../shared/worktree-cleanup-plan.ts";
162
165
  import {
163
166
  type AgentProgress,
@@ -221,39 +224,15 @@ import {
221
224
  type SteeringTargetState,
222
225
  } from "../../shared/types.ts";
223
226
  import { deriveChildSessionName } from "../../shared/child-session-name.ts";
227
+ import { editDistance, hasSingleAdjacentTransposition } from "../../shared/edit-distance.ts";
224
228
 
225
- const MUTATING_MANAGEMENT_ACTIONS = new Set(["create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "worktree.cleanup", "lane.recordMerge", "lane.recordSupersession", "refine", "refine.rollback", "dismiss", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
226
- const DESTRUCTIVE_MANAGEMENT_ACTIONS = new Set(["delete", "eject", "disable", "reset", "mission.close", "worktree.discard", "refine.rollback", "inspector.close", "project.close", "stop", "interrupt", "schedule.delete"]);
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"]);
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"]);
227
231
 
228
232
  function resolveSteerDeliveryMode(mode: SubagentParamsLike["mode"]): SteerDeliveryMode | undefined {
229
233
  return mode === "steer" || mode === "follow_up" || mode === "auto" ? mode : undefined;
230
234
  }
231
235
 
232
- function editDistance(left: string, right: string): number {
233
- const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
234
- for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
235
- let diagonal = previous[0]!;
236
- previous[0] = leftIndex;
237
- for (let rightIndex = 1; rightIndex <= right.length; rightIndex += 1) {
238
- const above = previous[rightIndex]!;
239
- previous[rightIndex] = left[leftIndex - 1] === right[rightIndex - 1]
240
- ? diagonal
241
- : Math.min(diagonal, above, previous[rightIndex - 1]!) + 1;
242
- diagonal = above;
243
- }
244
- }
245
- return previous[right.length]!;
246
- }
247
-
248
- function hasSingleAdjacentTransposition(left: string, right: string): boolean {
249
- if (left.length !== right.length) return false;
250
- const mismatch = [...left].findIndex((character, index) => character !== right[index]);
251
- return mismatch >= 0
252
- && left[mismatch] === right[mismatch + 1]
253
- && left[mismatch + 1] === right[mismatch]
254
- && left.slice(mismatch + 2) === right.slice(mismatch + 2);
255
- }
256
-
257
236
  export function unknownSubagentActionMessage(action: string, disabled?: DisabledFeatureSurface): string {
258
237
  const requested = action.toLowerCase();
259
238
  const enabledActions = SUBAGENT_ACTIONS.filter((candidate) => !disabled?.actions.has(candidate));
@@ -330,6 +309,7 @@ export interface SubagentParamsLike {
330
309
  merge?: unknown;
331
310
  supersession?: unknown;
332
311
  index?: number;
312
+ toolCallId?: string;
333
313
  childId?: string;
334
314
  view?: "fleet" | "transcript";
335
315
  lines?: number;
@@ -433,7 +413,7 @@ export interface SubagentParamsLike {
433
413
  every?: string;
434
414
  sessionOnly?: boolean;
435
415
  quiet?: boolean;
436
- on?: string | number;
416
+ on?: string[];
437
417
  timezone?: string;
438
418
  overlap?: "skip";
439
419
  catchUp?: "none" | "latest";
@@ -459,6 +439,7 @@ function rememberParentModel(state: { currentSessionId?: string | null; lastPare
459
439
 
460
440
  interface ExecutorDeps {
461
441
  pi: ExtensionAPI;
442
+ parentWake?: Pick<ExtensionAPI, "sendMessage">;
462
443
  state: SubagentState;
463
444
  config: ExtensionConfig;
464
445
  asyncByDefault: boolean;
@@ -469,7 +450,7 @@ interface ExecutorDeps {
469
450
  tempArtifactsDir: string;
470
451
  getSubagentSessionRoot: (parentSessionFile: string | null) => string;
471
452
  expandTilde: (p: string) => string;
472
- 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"] };
473
454
  discoverAgentsAll?: typeof discoverAgentsAll;
474
455
  onAgentsChanged?: () => void;
475
456
  allowMutatingManagementActions?: boolean;
@@ -522,6 +503,7 @@ interface ExecutionContextData {
522
503
  backgroundRequestedWhileClarifying: boolean;
523
504
  effectiveAsync: boolean;
524
505
  asyncRunId: string;
506
+ toolCallId: string;
525
507
  controlConfig: ResolvedControlConfig;
526
508
  /** Structured delegation consumers do not need duration-only heartbeat snapshots. */
527
509
  suppressUnchangedDelegationUpdates?: boolean;
@@ -535,6 +517,8 @@ interface ExecutionContextData {
535
517
  usageBudget?: UsageBudgetConfig;
536
518
  /** Parent workflow owns this allowance; presence vetoes unverifiable child continuation. */
537
519
  inheritedUsageBudget?: UsageBudgetConfig;
520
+ /** Mandatory host extensions retained by a parent workflow; they outlive a later registration disposal. */
521
+ requiredExtensions?: RequiredChildExtensionSnapshot;
538
522
  allowZeroToolBudget?: boolean;
539
523
  configToolBudget?: ResolvedToolBudget;
540
524
  contextPolicy: AgentDefaultContextPolicy;
@@ -681,6 +665,20 @@ function sessionProjectTrust(ctx: ExtensionContext): boolean | undefined {
681
665
  return typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : undefined;
682
666
  }
683
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
+
684
682
  function spawnBudgetErrorResult(message: string, mode: "single" | "parallel" | "chain"): AgentToolResult<Details> {
685
683
  return {
686
684
  content: [{ type: "text", text: message }],
@@ -847,6 +845,7 @@ function rememberForegroundRun(state: SubagentState, input: { modelResponseAlias
847
845
  ...(result.error ? { error: result.error } : {}),
848
846
  ...(result.finalOutput ? { finalOutput: result.finalOutput } : {}),
849
847
  ...(result.outputState ? { outputState: result.outputState } : {}),
848
+ ...(result.outputPartial ? { outputPartial: true } : {}),
850
849
  ...(result.outputMode ? { outputMode: result.outputMode } : {}),
851
850
  ...(result.savedOutputPath ? { savedOutputPath: result.savedOutputPath } : {}),
852
851
  ...(result.outputSaveError ? { outputSaveError: result.outputSaveError } : {}),
@@ -932,6 +931,7 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
932
931
  ...(input.result.error ? { error: input.result.error } : {}),
933
932
  ...(input.result.finalOutput ? { finalOutput: input.result.finalOutput } : {}),
934
933
  outputState: input.result.outputState,
934
+ outputPartial: input.result.outputPartial,
935
935
  outputMode: input.result.outputMode,
936
936
  savedOutputPath: input.result.savedOutputPath,
937
937
  outputSaveError: input.result.outputSaveError,
@@ -1233,7 +1233,7 @@ function interruptAsyncRun(
1233
1233
  kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean,
1234
1234
  location?: { asyncDir: string | null; resolvedId?: string },
1235
1235
  ): AgentToolResult<Details> | null {
1236
- const target = getAsyncInterruptTarget(state, runId, location);
1236
+ const target = getAsyncInterruptTarget(state, runId, location, { fallbackToNewest: runId === undefined });
1237
1237
  if (!target) return null;
1238
1238
  const status = reconcileAsyncRun(target.asyncDir, omitUndefinedProperties({ kill })).status;
1239
1239
  if (!status || status.state !== "running" || typeof status.pid !== "number") {
@@ -1378,6 +1378,16 @@ function appendStepToAsyncChain(input: {
1378
1378
  };
1379
1379
  }
1380
1380
 
1381
+ let retainedRequiredExtensions: RequiredChildExtensionSnapshot | undefined;
1382
+ try {
1383
+ retainedRequiredExtensions = readRetainedRequiredChildExtensions(resolved.location.asyncDir);
1384
+ } catch (error) {
1385
+ return {
1386
+ content: [{ type: "text", text: `Cannot append step to run '${resolved.id}': ${error instanceof Error ? error.message : String(error)}` }],
1387
+ isError: true,
1388
+ details: { mode: "management", results: [] },
1389
+ };
1390
+ }
1381
1391
  const pendingAppendRequests = readPendingChainAppendRequests(resolved.location.asyncDir);
1382
1392
  const reservedOutputNames = new Set<string>([
1383
1393
  ...Object.keys(status.outputs ?? {}),
@@ -1418,6 +1428,7 @@ function appendStepToAsyncChain(input: {
1418
1428
  cwd: input.ctx.cwd,
1419
1429
  currentSessionId: resolveCurrentSessionId(input.ctx.sessionManager),
1420
1430
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1431
+ parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
1421
1432
  currentModelProvider: parentModel?.provider,
1422
1433
  currentModel: parentModel,
1423
1434
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
@@ -1429,6 +1440,17 @@ function appendStepToAsyncChain(input: {
1429
1440
  permissions: input.deps.config.permissions,
1430
1441
  childRuntime: input.deps.childRuntime,
1431
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
+ }
1432
1454
  const built = buildAsyncRunnerSteps(resolved.id, compactOptional<Parameters<typeof buildAsyncRunnerSteps>[1]>({
1433
1455
  chain: wrapChainTasksForFork(chain, contextPolicy),
1434
1456
  task: input.params.task,
@@ -1450,6 +1472,7 @@ function appendStepToAsyncChain(input: {
1450
1472
  asyncDir: resolved.location.asyncDir,
1451
1473
  validateOutputBindings: false,
1452
1474
  capabilityCeiling: intersectSubagentCapabilityCeilings(status.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(asyncCtx.currentSessionId)),
1475
+ requiredExtensions: retainedRequiredExtensions,
1453
1476
  }));
1454
1477
  if ("error" in built) {
1455
1478
  return {
@@ -1713,9 +1736,15 @@ async function interruptNestedRun(target: ResolvedSubagentRunId & { kind: "neste
1713
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: [] } };
1714
1737
  if (run.state === "paused") return { content: [{ type: "text", text: `Nested run ${run.id} is already paused.` }], isError: true, details: { mode: "management", results: [] } };
1715
1738
  const result = await sendNestedControlRequest(target, "interrupt");
1716
- 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: [] } };
1717
1744
  const direct = directNestedAsyncInterrupt(target);
1718
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: [] } };
1719
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: [] } };
1720
1749
  }
1721
1750
 
@@ -1852,6 +1881,7 @@ async function resumeExternalJobFollowUp(input: {
1852
1881
  cwd: input.requestCwd,
1853
1882
  currentSessionId,
1854
1883
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
1884
+ parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
1855
1885
  currentModelProvider: parentModel?.provider,
1856
1886
  currentModel: parentModel,
1857
1887
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
@@ -1978,7 +2008,7 @@ async function resumeAsyncRun(input: {
1978
2008
  type: "text",
1979
2009
  text: [
1980
2010
  `Async child '${target.runId}' index ${target.index} is still running. action='resume' only revives paused, completed, or failed children.`,
1981
- `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} } }).`,
1982
2012
  ].join("\n"),
1983
2013
  }],
1984
2014
  isError: true,
@@ -2041,6 +2071,18 @@ async function resumeAsyncRun(input: {
2041
2071
  : "External runners do not persist Pi sessions and cannot be resumed.";
2042
2072
  return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
2043
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
+
2044
2086
  if (target.source === "async" && target.runner?.type === "external-job") {
2045
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: [] } };
2046
2088
  const resumed = await resumeExternalJobFollowUp({
@@ -2104,7 +2146,7 @@ async function resumeAsyncRun(input: {
2104
2146
  const chain = wrapChainTasksForFork(attachChain, contextPolicy);
2105
2147
  const normalized = normalizeSkillInput(input.params.skill);
2106
2148
  const parentModel = input.parentModel;
2107
- const result = executeAsyncChain(runId, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
2149
+ const result = await executeAsyncChain(runId, compactOptional<Parameters<typeof executeAsyncChain>[1]>({
2108
2150
  chain,
2109
2151
  task: workflowTask,
2110
2152
  goal,
@@ -2123,6 +2165,7 @@ async function resumeAsyncRun(input: {
2123
2165
  cwd: input.requestCwd,
2124
2166
  currentSessionId: input.deps.state.currentSessionId,
2125
2167
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
2168
+ parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
2126
2169
  currentModelProvider: parentModel?.provider,
2127
2170
  currentModel: parentModel,
2128
2171
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
@@ -2130,6 +2173,7 @@ async function resumeAsyncRun(input: {
2130
2173
  projectTrusted: currentProjectTrusted(input.ctx),
2131
2174
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2132
2175
  modelResponseAliases: input.deps.config.modelResponseAliases,
2176
+ runnerLaunchers: input.deps.config.runnerLaunchers,
2133
2177
  interactive: input.ctx.hasUI,
2134
2178
  permissions: input.deps.config.permissions,
2135
2179
  childRuntime: input.deps.childRuntime,
@@ -2187,16 +2231,14 @@ async function resumeAsyncRun(input: {
2187
2231
  if (!revivalSessionFile) {
2188
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: [] } };
2189
2233
  }
2190
- if (input.params.baseRef !== undefined && "managedWorktree" in target && target.managedWorktree === true) {
2191
- 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: [] } };
2192
- }
2193
2234
  if (target.source === "async" && asyncReviveRequiresRecoveryDescriptor(target)) {
2194
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: [] } };
2195
2236
  }
2196
2237
  if (target.source === "nested" && !target.recoveryDescriptor) {
2197
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: [] } };
2198
2239
  }
2199
- 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 };
2200
2242
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
2201
2243
  const foregroundContract = target.source === "foreground" ? target.resumeContract : undefined;
2202
2244
  const outputSchema = Object.hasOwn(input.params, "outputSchema")
@@ -2213,6 +2255,10 @@ async function resumeAsyncRun(input: {
2213
2255
  if (acceptanceErrors.length > 0) {
2214
2256
  return { content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }], isError: true, details: { mode: "management", results: [] } };
2215
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
+ }
2216
2262
  const runId = randomUUID();
2217
2263
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
2218
2264
  let activeAsyncCapacity: ActiveAsyncCapacityHandle | undefined;
@@ -2254,6 +2300,7 @@ async function resumeAsyncRun(input: {
2254
2300
  cwd: input.requestCwd,
2255
2301
  currentSessionId: input.deps.state.currentSessionId,
2256
2302
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
2303
+ parentSessionFile: input.ctx.sessionManager.getSessionFile() ?? undefined,
2257
2304
  currentModelProvider: parentModel?.provider,
2258
2305
  currentModel: parentModel,
2259
2306
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
@@ -2262,6 +2309,7 @@ async function resumeAsyncRun(input: {
2262
2309
  ...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
2263
2310
  // Absence in the retained contract is meaningful; never acquire current aliases.
2264
2311
  modelResponseAliases: recoveryDescriptor ? recoveryDescriptor.modelResponseAliases : foregroundContract?.modelResponseAliases,
2312
+ runnerLaunchers: input.deps.config.runnerLaunchers,
2265
2313
  interactive: input.ctx.hasUI,
2266
2314
  permissions: input.deps.config.permissions,
2267
2315
  childRuntime: input.deps.childRuntime,
@@ -2408,10 +2456,12 @@ function formatFailedSingleRunOutput(result: SingleResult, displayOutput: string
2408
2456
  const error = result.error || "Failed";
2409
2457
  const output = displayOutput.trim();
2410
2458
  const lines = [error];
2459
+ let cappedOutput = output;
2411
2460
  if (output && output !== error.trim()) {
2412
- lines.push("", "Output:", output);
2461
+ cappedOutput = capInlineOutput(output, { artifactPath: result.artifactPaths?.outputPath, savedPath: result.savedOutputPath });
2462
+ lines.push("", "Output:", cappedOutput);
2413
2463
  }
2414
- if (result.artifactPaths?.outputPath && fs.existsSync(result.artifactPaths.outputPath)) {
2464
+ if (cappedOutput === output && result.artifactPaths?.outputPath && fs.existsSync(result.artifactPaths.outputPath)) {
2415
2465
  lines.push("", `Output artifact: ${result.artifactPaths.outputPath}`);
2416
2466
  }
2417
2467
  return lines.join("\n");
@@ -2485,6 +2535,7 @@ async function emitForegroundResultIntercom(input: {
2485
2535
  ...(result.sessionName ? { sessionName: result.sessionName } : {}),
2486
2536
  status: foregroundResultIntercomStatus(result),
2487
2537
  outputState: result.outputState ?? "unknown",
2538
+ ...(result.outputPartial ? { outputPartial: true } : {}),
2488
2539
  summary: resultSummaryForIntercom(result),
2489
2540
  index,
2490
2541
  artifactPath: result.artifactPaths?.outputPath,
@@ -2533,7 +2584,7 @@ async function maybeBuildForegroundIntercomReceipt(input: {
2533
2584
  }
2534
2585
 
2535
2586
  function diagnosticContextFromDiscovery(
2536
- discovered: { agents: AgentConfig[]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] },
2587
+ discovered: { agents: AgentConfig[]; disabledAgents?: string[]; cwd?: string; scope?: AgentScope; directories?: UnknownAgentDiagnosticContext["directories"] },
2537
2588
  cwd: string,
2538
2589
  scope: AgentScope,
2539
2590
  ): UnknownAgentDiagnosticContext {
@@ -2556,6 +2607,8 @@ function workflowValidationOptions(deps: ExecutorDeps, params: SubagentParamsLik
2556
2607
  const cwd = resolveRequestedCwd(runtimeCwd, params.cwd);
2557
2608
  const scope = resolveExecutionAgentScope(params.agentScope);
2558
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;
2559
2612
  return {
2560
2613
  maxSubagentSpawnsPerRun: params.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
2561
2614
  agentNameError: (name) => {
@@ -2563,12 +2616,12 @@ function workflowValidationOptions(deps: ExecutorDeps, params: SubagentParamsLik
2563
2616
  const { agents } = discovered;
2564
2617
  const resolved = resolveAgentName(name, agents);
2565
2618
  if (resolved.agent || resolved.error) return canonicalizeAgentName(name, agents, discovered.agentDiagnostics, diagnosticContextFromDiscovery(discovered, cwd, scope)).error;
2566
- const requested = name.trim().toLowerCase();
2567
- const suggestion = [...new Set(agents.flatMap((agent) => [agent.name, ...(agent.localName ? [agent.localName] : []), ...(agent.aliases ?? [])]))]
2568
- .map((candidate) => ({ candidate, distance: editDistance(requested, candidate.toLowerCase()) }))
2569
- .filter(({ candidate, distance }) => distance <= Math.max(1, Math.floor(candidate.length / 4)) || hasSingleAdjacentTransposition(requested, candidate.toLowerCase()))
2570
- .sort((left, right) => left.distance - right.distance || left.candidate.localeCompare(right.candidate))[0]?.candidate;
2571
- 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");
2572
2625
  },
2573
2626
  };
2574
2627
  }
@@ -3375,11 +3428,11 @@ function importedAsyncRootUsage(completed: Awaited<ReturnType<typeof waitForImpo
3375
3428
 
3376
3429
  function removeWorkflowAwaitedResult(asyncDir: string, resultPath: string, runId: string, publication: NonNullable<Awaited<ReturnType<typeof waitForImportedAsyncRoot>>["importedPublication"]>): void {
3377
3430
  try {
3378
- fs.rmSync(resultPath, { force: true });
3379
- } catch {
3380
- // 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);
3381
3435
  }
3382
- removeResultIndex(asyncDir, publication.sessionId, runId, publication.toolCallId);
3383
3436
  }
3384
3437
 
3385
3438
  function emitWorkflowAwaitedChildComplete(
@@ -3536,13 +3589,16 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3536
3589
  cwd: ctx.cwd,
3537
3590
  currentSessionId: data.parentSessionId!,
3538
3591
  parentSessionId: data.parentPiSessionId,
3592
+ parentSessionFile: ctx.sessionManager.getSessionFile() ?? undefined,
3539
3593
  currentModelProvider: parentModel?.provider,
3540
3594
  currentModel: parentModel,
3541
3595
  scopedModelIds: data.scopedModelIds,
3542
3596
  modelScope: data.modelScope,
3543
3597
  projectTrusted: currentProjectTrusted(ctx),
3544
3598
  ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
3545
- modelResponseAliases: deps.config.modelResponseAliases, interactive: ctx.hasUI,
3599
+ modelResponseAliases: deps.config.modelResponseAliases,
3600
+ runnerLaunchers: deps.config.runnerLaunchers,
3601
+ interactive: ctx.hasUI,
3546
3602
  permissions: deps.config.permissions,
3547
3603
  childRuntime: deps.childRuntime,
3548
3604
  });
@@ -3603,11 +3659,13 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3603
3659
  const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: a.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
3604
3660
  if (launchRuleError) return toExecutionErrorResult(params, new Error(launchRuleError), data.contextPolicy.contextSummary);
3605
3661
  const asyncResult = await executeAsyncSingle(id, compactOptional<Parameters<typeof executeAsyncSingle>[1]>({
3662
+ toolCallId: data.toolCallId,
3606
3663
  agent: params.agent!,
3607
3664
  task: shouldForkAgent(contextPolicy, params.agent!) ? wrapForkTask(params.task ?? "") : (params.task ?? ""),
3608
3665
  goal: params.task ?? "",
3609
3666
  agentConfig: a,
3610
3667
  recoveryAgentConfig: data.recoveryAgents.find((agent) => agent.name === params.agent),
3668
+ requiredExtensions: data.requiredExtensions,
3611
3669
  ctx: asyncCtx,
3612
3670
  availableModels,
3613
3671
  cwd: effectiveCwd,
@@ -3846,7 +3904,7 @@ function resolveWorkflowChildOutputPath(input: {
3846
3904
  state?: SubagentState;
3847
3905
  key: string;
3848
3906
  params: Record<string, unknown>;
3849
- }): { path?: string; inherited: boolean } {
3907
+ }): { path?: string; inherited: boolean; resumedOutput?: string } {
3850
3908
  const rawOutput = input.params.output;
3851
3909
  const hasExplicitOutput = typeof rawOutput === "string" || typeof rawOutput === "boolean";
3852
3910
  if (typeof input.params.resume === "string" && (!hasExplicitOutput || rawOutput === true || rawOutput === "true")) {
@@ -3856,7 +3914,11 @@ function resolveWorkflowChildOutputPath(input: {
3856
3914
  id: input.params.resume.trim(),
3857
3915
  ...(typeof index === "number" && Number.isInteger(index) ? { index } : {}),
3858
3916
  }, input.state);
3859
- 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) };
3860
3922
  }
3861
3923
  const childCwd = resolveWorkflowChildLocalCwd(input);
3862
3924
  let agentOutput: string | undefined;
@@ -3909,7 +3971,9 @@ function workflowChildOutputClaims(input: {
3909
3971
  }
3910
3972
  const overrides = new Map<string, string>();
3911
3973
  for (const entry of resolvedEntries) {
3912
- 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)) {
3913
3977
  const output = workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.workflowRunId, entry.key);
3914
3978
  overrides.set(entry.key, output);
3915
3979
  entry.path = output;
@@ -3925,6 +3989,14 @@ function workflowChildOutputClaims(input: {
3925
3989
  claims.set(claimPath, key);
3926
3990
  childClaims.set(key, claimPath);
3927
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
+ }
3928
4000
  return { claims, childClaims, overrides };
3929
4001
  }
3930
4002
 
@@ -3952,7 +4024,7 @@ function prepareWorkflowChildLaunchParams(input: {
3952
4024
  }): SubagentParamsLike {
3953
4025
  let childParams = input.childParams;
3954
4026
  const usesDefaultOutput = input.childParams.output === undefined && input.childParams.resume === undefined;
3955
- if (usesDefaultOutput && input.outputOverride !== undefined) {
4027
+ if (input.childParams.output === undefined && input.outputOverride !== undefined) {
3956
4028
  childParams = { ...input.childParams, output: input.outputOverride };
3957
4029
  } else if (usesDefaultOutput && input.aggregateOutputPath !== undefined) {
3958
4030
  childParams = { ...input.childParams, output: workflowChildDefaultOutput(input.aggregateOutputPath, input.artifactsDir, input.parentWorkflowRunId, input.workflowKey) };
@@ -3966,7 +4038,7 @@ function prepareWorkflowChildLaunchParams(input: {
3966
4038
  const agent = typeof childParams.agent === "string"
3967
4039
  ? resolveAgentName(childParams.agent, discoveredAgents).agent ?? resolveAgentName(childParams.agent, input.agents).agent
3968
4040
  : undefined;
3969
- 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;
3970
4042
  return prepareWorkflowLaunchParams(input.workflowDefaults, childParams, input.parentWorkflowRunId, input.workflowKey, { ...input.options, externalAsyncRequired, outputClaimPath: input.outputClaimPath });
3971
4043
  }
3972
4044
 
@@ -4094,8 +4166,12 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4094
4166
  }
4095
4167
  let foregroundMachine: import("../../shared/types.ts").HerdrMachineReference | undefined;
4096
4168
  const requestedMachine = params.machine ?? agentConfig.machine;
4169
+ const requiredExtensions = data.requiredExtensions ?? deps.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(data.parentPiSessionId);
4097
4170
  if (requestedMachine) {
4098
- try { foregroundMachine = resolveHerdrMachinePlacement({ machine: requestedMachine, cwd: ctx.cwd, stepCwd: params.machineCwd }).machine; }
4171
+ try {
4172
+ assertRequiredChildExtensionsAdmitted([requiredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
4173
+ foregroundMachine = resolveHerdrMachinePlacement({ machine: requestedMachine, cwd: ctx.cwd, stepCwd: params.machineCwd }).machine;
4174
+ }
4099
4175
  catch (error) { return toExecutionErrorResult(params, error instanceof Error ? error : new Error(String(error)), data.contextPolicy.contextSummary); }
4100
4176
  }
4101
4177
  const effectiveToolBudget = resolveEffectiveToolBudget(omitUndefinedProperties({ runBudget: data.toolBudget, agentBudget: agentConfig.toolBudget, configBudget: data.configToolBudget }));
@@ -4238,6 +4314,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4238
4314
  const interruptController = new AbortController();
4239
4315
  let detachForeground: ((reason?: string) => boolean) | undefined;
4240
4316
  let childSessionControls: ForegroundChildSessionControls | undefined;
4317
+ let pendingRuntimeStop: string | undefined;
4241
4318
  const foregroundControl = deps.state.foregroundControls.get(runId);
4242
4319
  const syncHerdrForegroundChild = () => {
4243
4320
  if (!foregroundControl?.parentWorkflowRunId) return;
@@ -4300,13 +4377,13 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4300
4377
  : undefined;
4301
4378
 
4302
4379
  const deadlineAt = data.deadlineAt ?? (data.timeoutMs !== undefined ? Date.now() + data.timeoutMs : undefined);
4303
- const requiredExtensions = deps.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(data.parentPiSessionId);
4304
4380
  let r: Awaited<ReturnType<typeof runSync>> | undefined;
4305
4381
  let resolveDetachedWorkflowChild: ((result: Awaited<ReturnType<typeof runSync>>) => void) | undefined;
4306
4382
  const detachedWorkflowChild = params.workflowAwaitDetached === true
4307
4383
  ? new Promise<Awaited<ReturnType<typeof runSync>>>((resolve) => { resolveDetachedWorkflowChild = resolve; })
4308
4384
  : undefined;
4309
4385
  try {
4386
+ const childSessionFile = sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin);
4310
4387
  const launched = await runSync(ctx.cwd, agents, params.agent!, task, compactOptional<Parameters<typeof runSync>[4]>({
4311
4388
  machine: foregroundMachine,
4312
4389
  parentProviderRegistry: ctx.modelRegistry,
@@ -4316,9 +4393,13 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4316
4393
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
4317
4394
  projectTrusted: currentProjectTrusted(ctx),
4318
4395
  ...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
4396
+ parentSessionFile: ctx.sessionManager.getSessionFile() ?? undefined,
4319
4397
  requiredExtensions,
4320
4398
  childRuntime: deps.childRuntime,
4321
- onChildSession: (controls) => { childSessionControls = controls; },
4399
+ onChildSession: (controls) => {
4400
+ childSessionControls = controls;
4401
+ if (pendingRuntimeStop) controls.stop(pendingRuntimeStop);
4402
+ },
4322
4403
  context: data.contextPolicy.contextForAgent(params.agent!),
4323
4404
  unknownAgentDiagnosticContext: data.unknownAgentDiagnosticContext,
4324
4405
  runFanoutBudget: params.runFanoutAdmitted ? data.runFanoutBudget : { ...data.runFanoutBudget, parentPath: `${data.runFanoutBudget.parentPath ? `${data.runFanoutBudget.parentPath}/` : ""}single` },
@@ -4331,7 +4412,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4331
4412
  intercomEvents: deps.pi.events,
4332
4413
  runId,
4333
4414
  sessionDir: sessionDirForIndex(0),
4334
- sessionFile: sessionFileForTask(params.agent!, 0, modelOverride, modelOverrideFromParent, modelOrigin),
4415
+ sessionFile: childSessionFile,
4335
4416
  share: shareEnabled,
4336
4417
  artifactsDir: artifactConfig.enabled ? artifactsDir : undefined,
4337
4418
  artifactConfig,
@@ -4372,6 +4453,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4372
4453
  detachForeground = detach;
4373
4454
  },
4374
4455
  onDetachedExit: async (result) => {
4456
+ if (foregroundControl) foregroundControl.stopForRuntimeReplacement = undefined;
4375
4457
  if (resolveDetachedWorkflowChild) {
4376
4458
  resolveDetachedWorkflowChild(result);
4377
4459
  return;
@@ -4418,6 +4500,18 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4418
4500
  capabilityCeiling: data.capabilityCeiling,
4419
4501
  allowZeroToolBudget: data.allowZeroToolBudget && effectiveToolBudget.toolBudget === data.toolBudget,
4420
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
+ }
4421
4515
  r = launched.detached && detachedWorkflowChild ? await detachedWorkflowChild : launched;
4422
4516
  } catch (error) {
4423
4517
  await cleanupSingleWorktree();
@@ -4529,7 +4623,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4529
4623
  isError: true,
4530
4624
  };
4531
4625
  return {
4532
- 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}` }],
4533
4627
  details,
4534
4628
  };
4535
4629
  }
@@ -4554,6 +4648,7 @@ function duplicateSubagentCallResult(params: SubagentParamsLike): AgentToolResul
4554
4648
 
4555
4649
  const workflowLaunchObservers = new WeakMap<object, (launch: { agent: string; sessionName?: string; sessionFile?: string; async: boolean; runId?: string }) => void>();
4556
4650
  const workflowOwnedUsageBudgets = new WeakMap<object, UsageBudgetConfig>();
4651
+ const workflowRetainedRequiredExtensions = new WeakMap<object, RequiredChildExtensionSnapshot>();
4557
4652
 
4558
4653
  /**
4559
4654
  * Terminal-mission retention can remove a mission while its children still
@@ -4746,7 +4841,7 @@ function workflowRunningChildrenSummary(children: WorkflowScriptChildResult[]):
4746
4841
  function workflowResultChildren(children: WorkflowScriptChildResult[], status: AsyncStatus, includeFailureFields: boolean) {
4747
4842
  return withWorkflowRevivals(DIRS.async, status.runId, children).map((child) => {
4748
4843
  const sessionName = status.steps?.find((step) => step.workflowKey === child.key)?.sessionName;
4749
- 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 } } : {}) };
4750
4845
  });
4751
4846
  }
4752
4847
 
@@ -4758,7 +4853,11 @@ function workflowOutputPathMappingSummary(children: WorkflowScriptChildResult[])
4758
4853
  }
4759
4854
 
4760
4855
  function workflowDetailsResults(children: WorkflowScriptChildResult[]): SingleResult[] {
4761
- return children.flatMap((child) => (child.results ?? []).map((result) => result.workflowKey ? result : { ...result, workflowKey: child.key }));
4856
+ return children.flatMap((child) => (child.results ?? []).map((result) => ({
4857
+ ...result,
4858
+ workflowKey: result.workflowKey ?? child.key,
4859
+ ...(child.runId && !result.runId ? { runId: child.runId } : {}),
4860
+ })));
4762
4861
  }
4763
4862
 
4764
4863
  function workflowSteerReceipt(key: string, result: AgentToolResult<Details>): WorkflowSteerResult {
@@ -4779,6 +4878,7 @@ function workflowSteerReceipt(key: string, result: AgentToolResult<Details>): Wo
4779
4878
  }
4780
4879
 
4781
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).";
4782
4882
  const MAX_WORKFLOW_RESUME_HINT_BYTES = 1024;
4783
4883
  const MAX_WORKFLOW_CHILD_RUN_ID_BYTES = 256;
4784
4884
  const WORKFLOW_RESUME_HINT_PARENT_STATES = new Set(["complete", "failed", "partial"]);
@@ -5323,6 +5423,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5323
5423
  /** Scheduled state visible to the current runtime supervisor owner only. */
5324
5424
  getCurrentSupervisorOwnerStates: () => Iterable<SubagentState>;
5325
5425
  } {
5426
+ const executorDeps = deps;
5326
5427
  const delegatedThinkingOverrides = new WeakMap<object, AgentConfig["thinking"]>();
5327
5428
  const delegatedZeroToolBudgets = new WeakSet<object>();
5328
5429
  const delegatedExecutions = new WeakSet<object>();
@@ -5352,8 +5453,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5352
5453
  preserveActiveSession = false,
5353
5454
  parentModelOverride?: ParentModel | null,
5354
5455
  ): Promise<AgentToolResult<Details>> => {
5456
+ const projectScopeError = projectScopeTrustError(params, ctx);
5457
+ if (projectScopeError) return projectScopeError;
5458
+ const deps = withSessionProjectTrust(executorDeps, ctx);
5355
5459
  const workflowLaunchObserver = workflowLaunchObservers.get(params);
5356
5460
  const inheritedUsageBudget = workflowOwnedUsageBudgets.get(params);
5461
+ const retainedRequiredExtensions = workflowRetainedRequiredExtensions.get(params);
5357
5462
  const delegatedThinkingOverride = delegatedThinkingOverrides.get(params);
5358
5463
  const allowZeroToolBudget = delegatedZeroToolBudgets.has(params);
5359
5464
  const delegatedExecution = delegatedExecutions.has(params);
@@ -5381,6 +5486,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5381
5486
  ? currentParentModel
5382
5487
  : rememberParentModel(deps.state, resolveCurrentSessionId(ctx.sessionManager), currentParentModel)) ?? null;
5383
5488
  })();
5489
+ // validate checks args with the same normalization launch uses, reported beside script errors.
5490
+ const validateWorkflowRequest = () => {
5491
+ const validation = validateWorkflowScript(requestParams.workflowScript ?? "", workflowValidationOptions(deps, requestParams, ctx.cwd, () => resolveWorkflowParentModel()?.provider));
5492
+ const normalizedArgs = normalizeWorkflowArgs(requestParams.args);
5493
+ return "error" in normalizedArgs ? { ...validation, ok: false, errors: [...validation.errors, { message: normalizedArgs.error }] } : validation;
5494
+ };
5384
5495
  try {
5385
5496
  if (requestParams.preflight !== undefined && requestParams.workflowScript === undefined) {
5386
5497
  throw new Error("preflight requires workflow: true or a workflow script path.");
@@ -5390,7 +5501,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5390
5501
  } catch (error) {
5391
5502
  const message = error instanceof Error ? error.message : String(error);
5392
5503
  if (requestParams.action?.trim() === "validate") {
5393
- const validation = validateWorkflowScript(requestParams.workflowScript ?? "", workflowValidationOptions(deps, requestParams, ctx.cwd, () => resolveWorkflowParentModel()?.provider));
5504
+ const validation = validateWorkflowRequest();
5394
5505
  const invalidValidation = { ...validation, ok: false, errors: [...validation.errors, { message }] };
5395
5506
  return {
5396
5507
  content: [{ type: "text", text: JSON.stringify(invalidValidation) }],
@@ -5401,8 +5512,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5401
5512
  return buildRequestedModeError(requestParams, message);
5402
5513
  }
5403
5514
  if (requestParams.action?.trim() === "validate") {
5404
- const validation = validateWorkflowScript(requestParams.workflowScript ?? "", workflowValidationOptions(deps, requestParams, ctx.cwd, () => resolveWorkflowParentModel()?.provider));
5405
- return buildWorkflowValidationResult(validation, "management", workflowPreflight);
5515
+ return buildWorkflowValidationResult(validateWorkflowRequest(), "management", workflowPreflight);
5406
5516
  }
5407
5517
  const normalizedAction = typeof requestParams.action === "string" ? requestParams.action.trim() : requestParams.action;
5408
5518
  if (normalizedAction === "resume" && requestParams.extensionBindings !== undefined) return buildRequestedModeError(requestParams, "extensionBindings is not supported with action='resume'; resume uses the original retained child binding.");
@@ -5431,6 +5541,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5431
5541
  }
5432
5542
  const acceptanceErrors = validateAcceptanceInput(requestParams.acceptance);
5433
5543
  if (acceptanceErrors.length > 0) return buildRequestedModeError(requestParams, acceptanceErrors.join(" "));
5544
+ // Capture mandatory host extensions at admission: script children may launch after the host disposes its registration.
5545
+ const admittedRequiredExtensions = retainedRequiredExtensions ?? deps.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(ctx.sessionManager.getSessionId() ?? undefined);
5546
+ const workflowRequiredExtensions = hasMandatoryRequiredChildExtensions(admittedRequiredExtensions) ? admittedRequiredExtensions : undefined;
5434
5547
  const foregroundWorkflowRunId = encodeIndexSegment(_id);
5435
5548
  if (delegatedWorkflowPermit) {
5436
5549
  const permitError = validateWorkflowChildPermitRoot(delegatedWorkflowPermit, foregroundWorkflowRunId);
@@ -5638,7 +5751,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5638
5751
  if (resultWriteFailureWakeDelivered) return false;
5639
5752
  if (deps.state.currentSessionId !== currentSessionId || deps.state.completionOwnerId !== completionOwnerId) return false;
5640
5753
  try {
5641
- deps.pi.sendMessage(
5754
+ (deps.parentWake ?? deps.pi).sendMessage(
5642
5755
  {
5643
5756
  customType: "subagent-workflow-result-write-failed",
5644
5757
  content: message,
@@ -6131,6 +6244,15 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6131
6244
  onChildSettled: (notification) => {
6132
6245
  const journalFingerprint = workflowJournalFingerprints.get(notification.childKey);
6133
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
+ }
6134
6256
  appendWorkflowEvent({
6135
6257
  type: "subagent.workflow.child_settled",
6136
6258
  childKey: notification.childKey,
@@ -6139,11 +6261,13 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6139
6261
  workflowRunning: notification.workflowRunning,
6140
6262
  });
6141
6263
  try {
6142
- deps.pi.sendMessage(
6264
+ (deps.parentWake ?? deps.pi).sendMessage(
6143
6265
  {
6144
6266
  customType: "subagent-incremental-child-notify",
6145
6267
  content: formatIncrementalChildCompletion(notification),
6146
6268
  display: notification.outcome !== "completed",
6269
+ // Render-only: Pi does not send details to the model.
6270
+ details: { childKey: notification.childKey, outcome: notification.outcome },
6147
6271
  },
6148
6272
  { triggerTurn: incrementalChildCompletionTriggersTurn(notification, requestParams.scheduleOrigin) },
6149
6273
  );
@@ -6197,7 +6321,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6197
6321
  appendWorkflowChildJournal(asyncDir, { type: "start", key, fingerprint: journalFingerprint, runId: priorRunId });
6198
6322
  const stopListener = stopAwaitedAsyncChildOnAbort(workflowSignal, deps.state, priorRunId, priorAsyncDir, deps.kill);
6199
6323
  const reattached = await awaitExistingAsyncRun(priorAsyncDir, priorRunId, workflowSignal).finally(stopListener.remove);
6200
- const claimedPath = reattached.status === "settled" ? claimWorkflowAwaitedResult(priorAsyncDir, workflowRunId) : undefined;
6324
+ const claimedPath = reattached.status === "settled" ? claimWorkflowAwaitedResult(priorAsyncDir, workflowRunId, { ...reattached.result.importedPublication, runId: priorRunId }) : undefined;
6201
6325
  if (reattached.status === "settled" && claimedPath) {
6202
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 });
6203
6327
  const reattachedResult = workflowChildResult(key, imported, childParams, deps.state);
@@ -6231,6 +6355,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6231
6355
  );
6232
6356
  preparedChildParams = childRequest;
6233
6357
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
6358
+ if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
6234
6359
  workflowLaunchObservers.set(childRequest, (launch) => {
6235
6360
  if (launch.runId) appendWorkflowChildJournal(asyncDir, { type: "start", key, fingerprint: journalFingerprint, runId: launch.runId });
6236
6361
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
@@ -6516,6 +6641,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6516
6641
  );
6517
6642
  preparedChildParams = childRequest;
6518
6643
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
6644
+ if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
6519
6645
  if (delegatedWorkflowPermit) {
6520
6646
  if (childRequest.async !== false) throw new Error("Workflow child permit supports one foreground child only.");
6521
6647
  const childCwd = resolveRequestedCwd(workflowCwd, childRequest.cwd);
@@ -6678,11 +6804,30 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6678
6804
  if (deps.allowMutatingManagementActions === false) {
6679
6805
  return { content: [{ type: "text", text: "Action 'worktree.cleanup' is not available from child-safe subagent fanout mode." }], isError: true, details: { mode: "management", results: [] } };
6680
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
+ }
6681
6826
  if (paramsWithResolvedCwd.mode !== "plan") {
6682
- 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: [] } };
6683
6828
  }
6684
6829
  if (paramsWithResolvedCwd.planId !== undefined) {
6685
- 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: [] } };
6686
6831
  }
6687
6832
  try {
6688
6833
  const created = createWorktreeCleanupPlan({
@@ -6755,7 +6900,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6755
6900
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
6756
6901
  }
6757
6902
  }
6758
- const policyAction = action === "stop" ? "stopRun" : action === "steer" ? "steerRun" : action === "schedule.create" ? "scheduleCreate" : action === "inspector.open" ? "inspectorOpen" : action === "project.open" ? "projectOpen" : undefined;
6903
+ const policyAction = action === "stop" || action === "command.cancel" ? "stopRun" : action === "steer" || action === "command.yield" ? "steerRun" : action === "schedule.create" ? "scheduleCreate" : action === "inspector.open" ? "inspectorOpen" : action === "project.open" ? "projectOpen" : undefined;
6759
6904
  if (policyAction) {
6760
6905
  // Child-safe mode is a hard capability boundary; the policy is an operator
6761
6906
  // preference. Refuse first, so the gate never prompts for an action that is
@@ -6917,7 +7062,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6917
7062
  if (action === "guide") {
6918
7063
  try {
6919
7064
  const guide = readSubagentGuide(paramsWithResolvedCwd.topic);
6920
- 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;
6921
7069
  return {
6922
7070
  content: [{ type: "text", text: notice ? `${notice}\n\n${guide}` : guide }],
6923
7071
  details: { mode: "management", results: [] },
@@ -6941,10 +7089,13 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6941
7089
  if (action === "doctor") {
6942
7090
  let currentSessionFile: string | null = null;
6943
7091
  let currentSessionId = deps.state.currentSessionId;
7092
+ let budgetSessionId = deps.state.currentSessionId;
6944
7093
  let sessionError: string | undefined;
6945
7094
  try {
6946
7095
  currentSessionFile = ctx.sessionManager.getSessionFile() ?? null;
6947
7096
  currentSessionId = ctx.sessionManager.getSessionId();
7097
+ // Launch admission's key (resolveCurrentSessionId) without its throw for an unbound session.
7098
+ budgetSessionId = currentSessionFile ?? currentSessionId;
6948
7099
  } catch (error) {
6949
7100
  sessionError = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
6950
7101
  }
@@ -6954,9 +7105,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6954
7105
  } catch (error) {
6955
7106
  if (!sessionError) sessionError = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
6956
7107
  }
6957
- const spawnBudget = getSpawnBudgetSnapshot(deps.state, deps.config, currentSessionId);
6958
- const activeAsyncCapacity = currentSessionId
6959
- ? 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) })
6960
7111
  : { used: 0, limit: resolveMaxActiveAsyncRunsPerSession(deps.config.maxActiveAsyncRunsPerSession) ?? 0 };
6961
7112
  deps.state.activeAsyncCapacity = activeAsyncCapacity;
6962
7113
  return {
@@ -6970,6 +7121,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6970
7121
  requestedSessionDir: paramsWithResolvedCwd.sessionDir,
6971
7122
  currentSessionFile,
6972
7123
  currentSessionId,
7124
+ spawnBudget,
7125
+ activeAsyncCapacity,
6973
7126
  orchestratorTarget,
6974
7127
  sessionError,
6975
7128
  expandTilde: deps.expandTilde,
@@ -6978,6 +7131,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6978
7131
  details: { mode: "management", results: [], spawnBudget, activeAsyncCapacity },
6979
7132
  };
6980
7133
  }
7134
+ if (["command.status", "command.yield", "command.cancel"].includes(action)) {
7135
+ try {
7136
+ if (deps.allowMutatingManagementActions === false && action !== "command.status") throw new Error(`Action '${action}' is not available from child-safe subagent fanout mode.`);
7137
+ const targetRunId = paramsWithResolvedCwd.id ?? paramsWithResolvedCwd.runId;
7138
+ if (!targetRunId || paramsWithResolvedCwd.dir) throw new Error(`${action} requires id or runId; directory targets are not supported.`);
7139
+ deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
7140
+ const target = resolveSubagentRunId(targetRunId, { state: deps.state, nested: nestedResolutionScopeForExecutor(deps) });
7141
+ if (!target) throw new Error(`No run found for '${targetRunId}'.`);
7142
+ return await commandAction({ state: deps.state, target, operation: action.slice("command.".length) as "status" | "yield" | "cancel", index: paramsWithResolvedCwd.index, toolCallId: paramsWithResolvedCwd.toolCallId, signal });
7143
+ } catch (error) {
7144
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
7145
+ }
7146
+ }
6981
7147
  if (action === "status" || action === "debug.run") {
6982
7148
  if (!preserveActiveSession) deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
6983
7149
  const targetRunId = paramsWithResolvedCwd.id ?? paramsWithResolvedCwd.runId;
@@ -7465,16 +7631,27 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7465
7631
  : hasTasks
7466
7632
  ? (effectiveParams.tasks ?? []).map((task) => task.agent)
7467
7633
  : (effectiveParams.chain ?? []).flatMap((step) => getStepAgents(step as ChainStep));
7468
- const externalAgent = selectedAgentNames
7469
- .map((name) => agents.find((agent) => agent.name === name))
7470
- .find((agent) => agent?.runner?.type === "external-cli" || agent?.runner?.type === "external-job");
7471
- 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));
7472
7640
  const requestedAsync = externalAsyncRequired ? true : effectiveParams.async ?? deps.asyncByDefault;
7473
7641
  const backgroundRequestedWhileClarifying = (hasChain || hasTasks) && requestedAsync && effectiveParams.clarify === true;
7474
7642
  const effectiveAsync = requestedAsync && effectiveParams.clarify !== true;
7475
7643
  if (externalAgent && (!effectiveAsync || effectiveParams.foregroundOnly === true)) {
7476
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.`);
7477
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
+ }
7478
7655
  if (effectiveAsync && hasSingle && effectiveParams.resume === undefined && effectiveParams.worktree === true) {
7479
7656
  try {
7480
7657
  await preflightWorktreeSource(effectiveCwd, { signal });
@@ -7677,6 +7854,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7677
7854
  backgroundRequestedWhileClarifying,
7678
7855
  effectiveAsync,
7679
7856
  asyncRunId,
7857
+ toolCallId: _id,
7680
7858
  controlConfig,
7681
7859
  ...(delegatedExecution ? { suppressUnchangedDelegationUpdates: true } : {}),
7682
7860
  intercomBridge,
@@ -7685,6 +7863,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7685
7863
  toolBudget: runToolBudget.toolBudget,
7686
7864
  usageBudget: usageBudget.budget,
7687
7865
  inheritedUsageBudget,
7866
+ requiredExtensions: retainedRequiredExtensions,
7688
7867
  allowZeroToolBudget,
7689
7868
  configToolBudget: configToolBudget.toolBudget,
7690
7869
  configToolTimeoutMs: deps.config.toolTimeoutMs,
@@ -7971,7 +8150,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7971
8150
  workflowResourcePermits.set(publicParams, resolved.resource.permit);
7972
8151
  } else if (workflow !== undefined || publicParams.workflowScript !== undefined) {
7973
8152
  const normalizedArgs = normalizeWorkflowArgs(publicParams.args);
7974
- if ("error" in normalizedArgs) return errorResult(normalizedArgs.error);
8153
+ // validate reports args errors with its script errors; launch rejects them here.
8154
+ const validateOnly = publicParams.action === "validate";
8155
+ if ("error" in normalizedArgs && !validateOnly) return errorResult(normalizedArgs.error);
7975
8156
  let workflowScript = publicParams.workflowScript;
7976
8157
  if (workflow !== undefined) {
7977
8158
  const source = workflow === true ? readReplyWorkflowScript(ctx.sessionManager, id) : readWorkflowScriptFile(workflow, publicParams.cwd, ctx.cwd);
@@ -7979,7 +8160,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7979
8160
  workflowScript = source.script;
7980
8161
  }
7981
8162
  const { workflow: _workflow, ...withoutWorkflowSource } = publicParams;
7982
- publicParams = { ...withoutWorkflowSource, workflowScript, args: deepFreezeWorkflowArgs(normalizedArgs.args) };
8163
+ publicParams = { ...withoutWorkflowSource, workflowScript, args: "error" in normalizedArgs ? publicParams.args : deepFreezeWorkflowArgs(normalizedArgs.args) };
7983
8164
  }
7984
8165
  publicExecutions.add(publicParams);
7985
8166
  return executeWithSingleDispatchGuard(id, publicParams, signal, onUpdate, ctx);