@xzzpig/pi-subagents 0.14.0 → 0.15.1

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 (206) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/README.md +7 -6
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +55 -136
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -74
  9. package/docs/fork-extensions.md +184 -0
  10. package/docs/missions.md +10 -2
  11. package/docs/models.md +11 -22
  12. package/docs/observability.md +63 -11
  13. package/docs/standalone-background.md +59 -0
  14. package/docs/tool-reference.md +42 -23
  15. package/docs/watchdog.md +39 -10
  16. package/docs/workflows.md +58 -19
  17. package/index.ts +5 -2
  18. package/inspector-runner.mjs +2 -2
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  21. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  22. package/package.json +9 -4
  23. package/prompts/parallel-review.md +1 -1
  24. package/runner-peer-loader.mjs +24 -0
  25. package/runner-peer-preload.mjs +36 -0
  26. package/skills/pi-subagents/SKILL.md +34 -22
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  28. package/skills/pi-subagents/references/execution-controls.md +27 -8
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  32. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  33. package/src/agents/advertised-agent-prompt.ts +94 -0
  34. package/src/agents/agent-eject.ts +339 -0
  35. package/src/agents/agent-management.ts +79 -387
  36. package/src/agents/agent-serializer.ts +6 -3
  37. package/src/agents/agents.ts +198 -72
  38. package/src/agents/builtin-names.ts +1 -0
  39. package/src/agents/chain-serializer.ts +5 -0
  40. package/src/agents/runtime-agent-registry.ts +7 -6
  41. package/src/api/agent-management.ts +2 -2
  42. package/src/api/delegation.ts +4 -0
  43. package/src/api/preflight.ts +131 -86
  44. package/src/api/required-child-extensions.ts +6 -0
  45. package/src/api/shared-types.ts +3 -1
  46. package/src/api/workflow-resources.ts +6 -0
  47. package/src/extension/config.ts +14 -37
  48. package/src/extension/fanout-child.ts +68 -5
  49. package/src/extension/herdr-pi-bridge.ts +164 -0
  50. package/src/extension/index.ts +141 -51
  51. package/src/extension/public-execution.ts +7 -6
  52. package/src/extension/rpc.ts +8 -21
  53. package/src/extension/schemas.ts +86 -84
  54. package/src/extension/tool-description.ts +32 -79
  55. package/src/inspectors/actions.ts +148 -0
  56. package/src/inspectors/ghostty/actions.ts +74 -0
  57. package/src/inspectors/ghostty/plugin.ts +17 -0
  58. package/src/inspectors/herdr/actions.ts +99 -179
  59. package/src/inspectors/herdr/plugin.ts +20 -0
  60. package/src/inspectors/herdr/project-panes.ts +4 -1
  61. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  62. package/src/inspectors/plugins.ts +8 -0
  63. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  64. package/src/inspectors/types.ts +51 -0
  65. package/src/integrations/pi-web-session-liveness.ts +73 -0
  66. package/src/intercom/intercom-bridge.ts +50 -8
  67. package/src/intercom/native-supervisor-channel.ts +142 -115
  68. package/src/intercom/supervisor-ui.ts +3 -2
  69. package/src/missions/workflow-state.ts +37 -16
  70. package/src/policy/authority.ts +4 -0
  71. package/src/profiles/profiles.ts +12 -6
  72. package/src/runs/background/active-async-capacity.ts +22 -18
  73. package/src/runs/background/active-run-index.ts +17 -1
  74. package/src/runs/background/async-execution.ts +359 -176
  75. package/src/runs/background/async-job-tracker.ts +41 -7
  76. package/src/runs/background/async-resume.ts +19 -12
  77. package/src/runs/background/async-retention.ts +20 -0
  78. package/src/runs/background/async-status-snapshot.ts +10 -12
  79. package/src/runs/background/async-status.ts +38 -35
  80. package/src/runs/background/auto-drain.ts +59 -35
  81. package/src/runs/background/binary-bootstrap.ts +38 -0
  82. package/src/runs/background/chain-append.ts +1 -1
  83. package/src/runs/background/chain-root-attachment.ts +22 -33
  84. package/src/runs/background/control-channel.ts +78 -44
  85. package/src/runs/background/fleet-view.ts +30 -2
  86. package/src/runs/background/notify.ts +193 -19
  87. package/src/runs/background/owned-process-tree.ts +35 -8
  88. package/src/runs/background/process-terminal.ts +23 -23
  89. package/src/runs/background/result-files.ts +8 -4
  90. package/src/runs/background/result-watcher.ts +19 -2
  91. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  92. package/src/runs/background/run-child-session.ts +118 -41
  93. package/src/runs/background/run-status.ts +78 -5
  94. package/src/runs/background/runner-aliases.ts +22 -5
  95. package/src/runs/background/runner-child-launch.ts +93 -0
  96. package/src/runs/background/runner-child-sessions.ts +5 -4
  97. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  98. package/src/runs/background/scheduled-runs.ts +51 -18
  99. package/src/runs/background/stale-run-reconciler.ts +38 -12
  100. package/src/runs/background/steering.ts +20 -2
  101. package/src/runs/background/subagent-runner.ts +770 -444
  102. package/src/runs/background/subagent-wait.ts +179 -28
  103. package/src/runs/background/wait-completions.ts +79 -27
  104. package/src/runs/background/wait-subscriptions.ts +9 -3
  105. package/src/runs/background/wait-tool.ts +5 -3
  106. package/src/runs/foreground/async-steering-action.ts +37 -7
  107. package/src/runs/foreground/async-stop-action.ts +93 -3
  108. package/src/runs/foreground/execution.ts +174 -194
  109. package/src/runs/foreground/foreground-history.ts +5 -2
  110. package/src/runs/foreground/prompt-audit.ts +12 -6
  111. package/src/runs/foreground/subagent-executor.ts +915 -411
  112. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  113. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  114. package/src/runs/shared/acceptance.ts +54 -14
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +172 -78
  117. package/src/runs/shared/capability-ceiling.ts +2 -0
  118. package/src/runs/shared/child-hooks.ts +167 -3
  119. package/src/runs/shared/child-launch-plan.ts +15 -3
  120. package/src/runs/shared/child-launch.ts +49 -85
  121. package/src/runs/shared/child-lifecycle.ts +6 -3
  122. package/src/runs/shared/child-runtime-config.ts +8 -1
  123. package/src/runs/shared/child-session.ts +130 -24
  124. package/src/runs/shared/child-tool-plan.ts +149 -112
  125. package/src/runs/shared/completion-evidence.ts +2 -2
  126. package/src/runs/shared/completion-guard.ts +6 -3
  127. package/src/runs/shared/dynamic-fanout.ts +2 -2
  128. package/src/runs/shared/effective-system-prompt.ts +33 -0
  129. package/src/runs/shared/external-cli-contract.ts +11 -1
  130. package/src/runs/shared/external-cli-preflight.ts +6 -2
  131. package/src/runs/shared/external-cli-runner.ts +9 -7
  132. package/src/runs/shared/herdr-connection.ts +134 -0
  133. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  134. package/src/runs/shared/herdr-machine.ts +279 -0
  135. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  136. package/src/runs/shared/herdr-placed-run.ts +263 -0
  137. package/src/runs/shared/host-step-status.ts +11 -11
  138. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  139. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  140. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  141. package/src/runs/shared/model-scope.ts +1 -1
  142. package/src/runs/shared/nested-events.ts +27 -34
  143. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  144. package/src/runs/shared/parallel-handoff.ts +57 -12
  145. package/src/runs/shared/parallel-utils.ts +10 -4
  146. package/src/runs/shared/pi-spawn.ts +10 -0
  147. package/src/runs/shared/profile-extensions.ts +134 -0
  148. package/src/runs/shared/profile-launch-env.ts +113 -0
  149. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  150. package/src/runs/shared/run-fanout-budget.ts +8 -8
  151. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  152. package/src/runs/shared/sandbox-profile-guard.ts +34 -0
  153. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  154. package/src/runs/shared/task-intent.ts +46 -13
  155. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  156. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  157. package/src/runs/shared/worktree-setup-command.ts +213 -0
  158. package/src/runs/shared/worktree.ts +437 -214
  159. package/src/shared/child-cache-retention.ts +43 -0
  160. package/src/shared/fork-context.ts +15 -72
  161. package/src/shared/launch-contract.ts +70 -8
  162. package/src/shared/model-response-aliases.ts +13 -0
  163. package/src/shared/opencode-session-headers.ts +30 -0
  164. package/src/shared/permission-profile.ts +14 -0
  165. package/src/shared/pruned-fork.ts +1 -1
  166. package/src/shared/required-child-extensions.ts +81 -0
  167. package/src/shared/sandbox-profile.ts +14 -0
  168. package/src/shared/settings.ts +5 -2
  169. package/src/shared/shortcuts.ts +0 -4
  170. package/src/shared/types.ts +163 -90
  171. package/src/shared/utils.ts +10 -2
  172. package/src/shared/watch-strategy.ts +2 -0
  173. package/src/shared/workflow-child-permit.ts +18 -13
  174. package/src/slash/delegation-adapters.ts +3 -1
  175. package/src/slash/delegation-request.ts +14 -0
  176. package/src/slash/slash-commands.ts +2 -7
  177. package/src/slash/subagents-admin.ts +31 -14
  178. package/src/tui/fleet-status.ts +165 -20
  179. package/src/tui/fleet.ts +30 -19
  180. package/src/tui/render.ts +210 -50
  181. package/src/watchdog/child-status.ts +28 -28
  182. package/src/watchdog/lsp-diagnostics.ts +1 -1
  183. package/src/watchdog/model-selection.ts +21 -1
  184. package/src/watchdog/permission-arbiter.ts +5 -2
  185. package/src/watchdog/register-child.ts +10 -2
  186. package/src/watchdog/register-main.ts +39 -35
  187. package/src/watchdog/render.ts +1 -1
  188. package/src/watchdog/review.ts +122 -74
  189. package/src/watchdog/rules.ts +1 -1
  190. package/src/watchdog/runtime.ts +100 -27
  191. package/src/watchdog/scope.ts +1 -1
  192. package/src/watchdog/settings.ts +3 -0
  193. package/src/watchdog/tool-actions.ts +13 -12
  194. package/src/watchdog/turn-delta.ts +23 -0
  195. package/src/watchdog/types.ts +5 -3
  196. package/src/watchdog/warning-format.ts +1 -1
  197. package/src/workflows/chat-progress.ts +3 -3
  198. package/src/workflows/scripted-workflow.ts +349 -26
  199. package/src/workflows/workflow-checklist.ts +17 -20
  200. package/src/workflows/workflow-child-summary.ts +57 -8
  201. package/src/workflows/workflow-preflight.ts +19 -19
  202. package/src/workflows/workflow-receipt.ts +24 -6
  203. package/src/workflows/workflow-resources.ts +108 -22
  204. package/src/workflows/workflow-settlement.ts +3 -0
  205. package/src/runs/shared/model-exclusions.ts +0 -373
  206. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -17,6 +17,7 @@ import type {
17
17
  WorktreeCleanupReport,
18
18
  WorktreeDiff,
19
19
  WorktreeSetup,
20
+ WorktreeSetupProgress,
20
21
  WorktreeCleanupIntent,
21
22
  } from "./worktree.ts";
22
23
  import { cleanupWorktrees } from "./worktree.ts";
@@ -614,18 +615,62 @@ export function parallelHandoffPath(baseDir: string, runId?: string): string {
614
615
  return runId ? path.join(baseDir, "handoffs", `${runId}.json`) : path.join(baseDir, "handoff.json");
615
616
  }
616
617
 
617
- export function writePendingParallelHandoff(input: {
618
- manifestPath: string;
619
- runId: string;
620
- mode: "single" | "parallel" | "chain";
621
- source: "foreground" | "async";
622
- cwd: string;
623
- stepIndex: number;
624
- flatStartIndex: number;
625
- setup: WorktreeSetup;
626
- laneBindings?: ParallelHandoffLaneBinding[];
627
- }): ParallelHandoffReference {
628
- return writeParallelHandoffGroup({ ...input, diffs: [], results: [] });
618
+ /** Synchronous onProgress projection shared by setup owners; snapshots are cumulative. */
619
+ export function writeWorktreeSetupHandoff(input: Omit<Parameters<typeof writeParallelHandoffGroup>[0], "setup" | "diffs" | "results" | "cleanup" | "now"> & {
620
+ progress: WorktreeSetupProgress;
621
+ }): ParallelHandoffReference | undefined {
622
+ const { progress, ...handoff } = input;
623
+ const { setup, attempts, cleanup } = progress;
624
+ // Preflight has no allocation identity yet. Its original error belongs to the caller.
625
+ if (attempts.length === 0 && setup.worktrees.length === 0) return undefined;
626
+ if (!setup.cwd || !setup.baseCommit) throw new Error("Cannot publish worktree allocation evidence without repository and base commit.");
627
+ const diagnostic = (text: string): string => text.slice(0, 512);
628
+ // Never copy argv, environment, Error objects or captured stdout/stderr into artifacts.
629
+ const commandEvidence = (command: WorktreeSetupProgress["command"]) => command && ({
630
+ pid: command.pid,
631
+ processGroupId: command.processGroupId,
632
+ ...(command.result ? {
633
+ status: command.result.status,
634
+ signal: command.result.signal,
635
+ failed: Boolean(command.result.error),
636
+ outputIncomplete: command.result.outputIncomplete,
637
+ processTree: command.result.processTree?.state,
638
+ } : {}),
639
+ });
640
+ const errors = [
641
+ `Worktree setup ${JSON.stringify({ runId: input.runId, stepIndex: input.stepIndex, phase: progress.phase,
642
+ unknown: Boolean(progress.unknown), command: commandEvidence(progress.command) })}`,
643
+ ...attempts.map((attempt) => {
644
+ const task = cleanup?.tasks.find((candidate) => candidate.index === attempt.index);
645
+ return `Allocation attempt ${JSON.stringify({ index: attempt.index, branch: attempt.branch,
646
+ path: attempt.path ?? null, validated: attempt.validated,
647
+ command: commandEvidence(attempt.command), hookCommand: commandEvidence(attempt.hookCommand),
648
+ ...(task ? { worktreeRemoved: task.worktreeRemoved, branchRemoved: task.branchRemoved,
649
+ preserved: task.preserved, reason: task.reason && diagnostic(task.reason), errors: task.errors?.map(diagnostic) } : {}),
650
+ })}`;
651
+ }),
652
+ ...(cleanup?.errors?.map(diagnostic) ?? []),
653
+ ...(progress.unknown ? ["Setup settlement unknown; manual reconciliation required."] : []),
654
+ ];
655
+ return writeParallelHandoffGroup({
656
+ ...handoff, setup, diffs: [], results: [],
657
+ laneBindings: input.laneBindings?.filter((binding) => setup.worktrees.some((worktree) => worktree.index === binding.taskIndex)),
658
+ cleanup: {
659
+ state: cleanup?.state ?? "partial",
660
+ pruned: cleanup?.pruned ?? false,
661
+ errors,
662
+ // An attempted native path is not a validated recovery task, even during rollback.
663
+ tasks: setup.worktrees.map((worktree) => {
664
+ const task = cleanup?.tasks.find((candidate) => candidate.index === worktree.index);
665
+ return task ? { ...task, reason: task.reason && diagnostic(task.reason), errors: task.errors?.map(diagnostic) } : {
666
+ index: worktree.index, path: worktree.path, branch: worktree.branch,
667
+ provider: worktree.provider, naming: worktree.naming,
668
+ worktreeRemoved: false, branchRemoved: false, preserved: true,
669
+ reason: "setup pending durable handoff capture",
670
+ };
671
+ }),
672
+ },
673
+ });
629
674
  }
630
675
 
631
676
  export function formatParallelHandoffReference(reference: ParallelHandoffReference): string {
@@ -14,6 +14,10 @@ export interface RunnerSubagentStep {
14
14
  sessionName?: string;
15
15
  task: string;
16
16
  runner?: ResolvedRunnerConfig;
17
+ /** Herdr saved machine this external-cli step runs on; `cwd` is then the directory on that machine. */
18
+ machine?: import("../../shared/types.ts").HerdrMachineReference;
19
+ remoteReads?: string[] | false;
20
+ machineEnv?: Record<string, string>;
17
21
  externalJobFollowUp?: {
18
22
  sourceRunId: string;
19
23
  sourceStepIndex: number;
@@ -41,15 +45,18 @@ export interface RunnerSubagentStep {
41
45
  fast?: boolean;
42
46
  thinking?: string;
43
47
  thinkingCeiling?: import("../../shared/model-info.ts").ThinkingLevel;
44
- modelCandidates?: string[];
48
+ requestedModel?: string;
45
49
  /** The primary model is inherited from the parent session and should not be verified against the child-reported active registry model. */
46
50
  skipPrimaryModelVerification?: boolean;
47
51
  modelVerificationRegistry?: Array<{ provider: string; id: string; fullId: string; contextWindow?: number }>;
52
+ modelResponseAliases?: Record<string, string[]>;
48
53
  tools?: string[];
49
54
  excludeTools?: string[];
50
55
  allowNestedSubagents?: boolean;
51
56
  extensions?: string[];
52
57
  subagentOnlyExtensions?: string[];
58
+ /** Private immutable host policy snapshot serialized to the native runner. */
59
+ requiredExtensions?: import("../../shared/required-child-extensions.ts").RequiredChildExtensionSnapshot;
53
60
  mcpDirectTools?: string[];
54
61
  mutationTools?: string[];
55
62
  completionGuard?: boolean;
@@ -80,8 +87,8 @@ export interface RunnerSubagentStep {
80
87
  launchBindingTask?: string;
81
88
  launchContractDigest?: string;
82
89
  extensionBindings?: import("./extension-bindings.ts").ExtensionBindings;
83
- launchResolvedExtensions?: import("../../shared/types.ts").LaunchResolvedChildExtensionsV1;
84
- runtimeAcknowledgedExtensions?: import("../../shared/types.ts").RuntimeAcknowledgedChildExtensionsV1;
90
+ launchResolvedExtensions?: import("../../shared/types.ts").LaunchResolvedChildExtensions;
91
+ runtimeAcknowledgedExtensions?: import("../../shared/types.ts").RuntimeAcknowledgedChildExtensions;
85
92
  effectiveAcceptance?: import("../../shared/types.ts").ResolvedAcceptanceConfig;
86
93
  acceptanceInput?: import("../../shared/types.ts").AcceptanceInput;
87
94
  acceptanceRole?: import("../../shared/types.ts").AcceptanceRole;
@@ -242,7 +249,6 @@ export interface ParallelTaskResult {
242
249
  error?: string;
243
250
  timedOut?: boolean;
244
251
  model?: string;
245
- attemptedModels?: string[];
246
252
  outputTargetPath?: string;
247
253
  outputTargetExists?: boolean;
248
254
  }
@@ -49,6 +49,7 @@ export interface PiSpawnDeps {
49
49
  platform?: NodeJS.Platform;
50
50
  execPath?: string;
51
51
  argv1?: string;
52
+ bunVersion?: string;
52
53
  existsSync?: (filePath: string) => boolean;
53
54
  realpathSync?: (filePath: string) => string;
54
55
  readFileSync?: (filePath: string, encoding: "utf-8") => string;
@@ -58,6 +59,15 @@ export interface PiSpawnDeps {
58
59
  env?: NodeJS.ProcessEnv;
59
60
  }
60
61
 
62
+ /** Compiled Pi's entrypoint is virtual; execPath is the real (possibly renamed) image. */
63
+ export function resolveBunPiExecutable(deps: PiSpawnDeps = {}): string | undefined {
64
+ const bunVersion = deps.bunVersion ?? process.versions.bun;
65
+ const entry = deps.argv1 ?? process.argv[1];
66
+ if (!bunVersion || !entry || !/^(?:\/\$bunfs\/|B:[\\/]~BUN[\\/])/.test(entry)) return undefined;
67
+ const env = deps.env ?? process.env;
68
+ return env[PI_SUBAGENT_PI_BINARY_ENV]?.trim() || (deps.execPath ?? process.execPath);
69
+ }
70
+
61
71
  interface PiSpawnCommand {
62
72
  command: string;
63
73
  args: string[];
@@ -0,0 +1,134 @@
1
+ /**
2
+ * [fork] Sandbox/permission-profile child-extension resolution. Split out of
3
+ * child-tool-plan.ts so the shared tool planner keeps only the call site: the
4
+ * profile validation, the sandbox extension lookup, and the permission-system
5
+ * fallback for profile-only agents live here.
6
+ */
7
+ import * as fs from "node:fs";
8
+ import * as path from "node:path";
9
+ import { getAgentDir } from "../../shared/utils.ts";
10
+ import { validateSandboxProfileName } from "../../shared/sandbox-profile.ts";
11
+ import { validatePermissionProfileName } from "../../shared/permission-profile.ts";
12
+ import type { ResolvedSubagentCapabilityCeiling } from "./capability-ceiling.ts";
13
+ import { resolvePermissionSystemExtension } from "./child-tool-plan.ts";
14
+
15
+ export function resolveSandboxExtensionForProfile(profileName: string): string {
16
+ validateSandboxProfileName(profileName, "sandbox profile");
17
+ return resolveSandboxExtension();
18
+ }
19
+
20
+ function resolveSandboxExtension(): string {
21
+ const agentDir = getAgentDir();
22
+ const candidates = [
23
+ path.join(agentDir, "npm", "node_modules", "@xzzpig", "pi-sandbox"),
24
+ path.join(agentDir, "npm", "node_modules", "pi-sandbox"),
25
+ path.join(agentDir, "extensions", "pi-sandbox"),
26
+ ];
27
+ const errors: Error[] = [];
28
+ let foundPackage = false;
29
+ for (const extDir of candidates) {
30
+ if (!fs.existsSync(extDir)) continue;
31
+ foundPackage = true;
32
+ const pkgPath = path.join(extDir, "package.json");
33
+ if (!fs.existsSync(pkgPath)) {
34
+ errors.push(new Error(`Sandbox package manifest is missing at ${pkgPath}.`));
35
+ continue;
36
+ }
37
+ try {
38
+ const parsed: unknown = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
39
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
40
+ throw new Error("manifest root must be an object");
41
+ }
42
+ const manifest = parsed as { name?: unknown; pi?: { extensions?: unknown } };
43
+ if (manifest.name !== "@xzzpig/pi-sandbox" && manifest.name !== "pi-sandbox") {
44
+ throw new Error(`Sandbox package manifest at ${pkgPath} must declare name '@xzzpig/pi-sandbox' or 'pi-sandbox'.`);
45
+ }
46
+ const extensions = manifest.pi?.extensions;
47
+ const entry = Array.isArray(extensions) ? extensions[0] : undefined;
48
+ if (typeof entry !== "string" || !entry.trim()) {
49
+ throw new Error(`Sandbox package manifest at ${pkgPath} must declare pi.extensions[0] as a non-empty string.`);
50
+ }
51
+ if (path.isAbsolute(entry)) {
52
+ throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} must be relative to the package directory.`);
53
+ }
54
+ const resolved = path.resolve(extDir, entry);
55
+ const relative = path.relative(extDir, resolved);
56
+ if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
57
+ throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} must remain inside ${extDir}.`);
58
+ }
59
+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
60
+ throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} does not resolve to a file at ${resolved}.`);
61
+ }
62
+ const realPackageRoot = fs.realpathSync(extDir);
63
+ const realEntry = fs.realpathSync(resolved);
64
+ const realRelative = path.relative(realPackageRoot, realEntry);
65
+ if (!realRelative || realRelative === ".." || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) {
66
+ throw new Error(`Sandbox extension entry ${JSON.stringify(entry)} in ${pkgPath} resolves outside ${extDir}.`);
67
+ }
68
+ return resolved;
69
+ } catch (error) {
70
+ const message = error instanceof Error ? error.message : String(error);
71
+ errors.push(message.startsWith("Sandbox") ? new Error(message) : new Error(`Cannot read sandbox package manifest at ${pkgPath}: ${message}`));
72
+ }
73
+ }
74
+ if (errors.length > 0) throw errors[0]!;
75
+ if (!foundPackage) {
76
+ throw new Error(`pi-sandbox is not installed; cannot launch a child with sandbox profile.`);
77
+ }
78
+ throw new Error(`No usable pi-sandbox extension manifest was found under '${agentDir}'.`);
79
+ }
80
+
81
+ export interface ResolvedProfileExtensions {
82
+ /** Absolute path of the resolved pi-sandbox child extension when a sandbox profile is selected. */
83
+ sandboxExtension?: string;
84
+ /** The permission-system child extension a launch must load: rules-driven or profile-driven. */
85
+ effectivePermSystemExt?: string;
86
+ }
87
+
88
+ /**
89
+ * Validate the selected sandbox/permission profiles and resolve the child
90
+ * extensions they require. `permSystemExt` is the rules-driven permission-system
91
+ * resolution the tool plan already computed; when only a permission profile is
92
+ * selected the extension is resolved eagerly here and a missing package fails
93
+ * the launch instead of silently degrading to no policy at all.
94
+ */
95
+ export function resolveProfileExtensions(input: {
96
+ sandbox?: string;
97
+ permissionProfile?: string;
98
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
99
+ permSystemExt?: string;
100
+ }): ResolvedProfileExtensions {
101
+ const { capabilityCeiling, permSystemExt } = input;
102
+ const sandboxProfile = input.sandbox === undefined
103
+ ? undefined
104
+ : validateSandboxProfileName(input.sandbox, "sandbox profile");
105
+ if (sandboxProfile && capabilityCeiling?.denyExtensions) {
106
+ throw new Error(`Sandbox profile '${sandboxProfile}' requires the pi-sandbox child extension, but this launch denies child extensions.`);
107
+ }
108
+ const permissionProfile = input.permissionProfile === undefined
109
+ ? undefined
110
+ : validatePermissionProfileName(input.permissionProfile, "permission profile");
111
+ if (permissionProfile && capabilityCeiling?.denyExtensions) {
112
+ throw new Error(`Permission profile '${permissionProfile}' requires the pi-permission-system child extension, but this launch denies child extensions.`);
113
+ }
114
+ const permSystemExtForProfile = permissionProfile !== undefined && permSystemExt === undefined
115
+ ? resolvePermissionSystemExtension()
116
+ : undefined;
117
+ if (permissionProfile !== undefined && permSystemExt === undefined && permSystemExtForProfile === undefined) {
118
+ throw new Error(`Permission profile '${permissionProfile}' cannot be enabled: pi-permission-system is not installed; cannot launch a child with a permission profile.`);
119
+ }
120
+ const effectivePermSystemExt = permSystemExt ?? permSystemExtForProfile;
121
+ let sandboxExtension: string | undefined;
122
+ if (sandboxProfile) {
123
+ try {
124
+ sandboxExtension = resolveSandboxExtensionForProfile(sandboxProfile);
125
+ } catch (error) {
126
+ const message = error instanceof Error ? error.message : String(error);
127
+ throw new Error(`Sandbox profile '${sandboxProfile}' cannot be enabled: ${message}`);
128
+ }
129
+ }
130
+ return {
131
+ ...(sandboxExtension ? { sandboxExtension } : {}),
132
+ ...(effectivePermSystemExt ? { effectivePermSystemExt } : {}),
133
+ };
134
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * [fork] Launch-environment construction for sandbox/permission-profile child
3
+ * launches: the transient env keys the child reads, the pinned permission
4
+ * profile, and the startup-diagnostics channel. Split out of child-launch.ts
5
+ * so the shared launcher keeps only the call site and the final processEnv
6
+ * assembly.
7
+ */
8
+ import * as fs from "node:fs";
9
+ import * as path from "node:path";
10
+ import { randomUUID } from "node:crypto";
11
+ import { TEMP_ROOT_DIR } from "../../shared/types.ts";
12
+ import { SUBAGENT_SANDBOX_PROFILE_ENV, SUBAGENT_SANDBOX_PROJECT_TRUST_ENV } from "../../shared/sandbox-profile.ts";
13
+ import { SUBAGENT_PERMISSION_PROFILE_ENV, SUBAGENT_PERMISSION_PROFILE_PINNED_ENV } from "../../shared/permission-profile.ts";
14
+ import { SANDBOX_DIAGNOSTICS_PATH_ENV } from "./sandbox-startup-diagnostics.ts";
15
+ import type { PiLaunchToolPlan } from "./child-tool-plan.ts";
16
+
17
+ const SANDBOX_STARTUP_ACK_PATH_ENV = "PI_SUBAGENT_SANDBOX_STARTUP_ACK_PATH";
18
+ const SANDBOX_STARTUP_ACK_TOKEN_ENV = "PI_SUBAGENT_SANDBOX_STARTUP_ACK_TOKEN";
19
+ // Marks an in-process child so child extensions never mutate the host process
20
+ // state (for example a profile-failure exit code) that a separate child process
21
+ // would legitimately own.
22
+ const IN_PROCESS_CHILD_ENV = "PI_SUBAGENT_SANDBOX_IN_PROCESS_CHILD";
23
+
24
+ /** Structural subset of the child-launch input the profile env needs. */
25
+ export interface ProfileLaunchEnvInput {
26
+ cwd: string;
27
+ /** A validated global pi-sandbox profile selected by the agent definition. */
28
+ sandbox?: string;
29
+ /** A validated global pi-permission-system profile selected by the agent definition. */
30
+ permissionProfile?: string;
31
+ /** Parent-authoritative trust state for profile-aware project config merging. */
32
+ projectTrusted?: boolean;
33
+ /** Exact trusted parent cwd; profile project config applies only when the child cwd matches it. */
34
+ trustedProjectCwd?: string;
35
+ host: "parent" | "runner";
36
+ }
37
+
38
+ export interface ProfileLaunchEnv {
39
+ /** Transient env keys the child reads; only a runner-hosted child applies them. */
40
+ childEnv: Record<string, string | undefined> | undefined;
41
+ /** Pinned permission-profile selection; applied to every child launch. */
42
+ profilePin: Record<string, string | undefined>;
43
+ /** Host process env keys to restore once the child session exists. */
44
+ transientProcessEnv: string[];
45
+ /** Path a blocked child extension writes its startup failure to. */
46
+ sandboxDiagnosticsPath?: string;
47
+ }
48
+
49
+ function hasTrustedProfileProjectCwd(input: Pick<ProfileLaunchEnvInput, "cwd" | "projectTrusted" | "trustedProjectCwd">): boolean {
50
+ if (input.projectTrusted !== true || !input.cwd || !input.trustedProjectCwd) return false;
51
+ return path.resolve(input.cwd) === path.resolve(input.trustedProjectCwd);
52
+ }
53
+
54
+ export function buildProfileLaunchEnv(input: ProfileLaunchEnvInput, toolPlan: Pick<PiLaunchToolPlan, "sandboxExtension">): ProfileLaunchEnv {
55
+ // A selected profile is validated by resolvePiLaunchToolPlan; the child
56
+ // receives only the profile identity, trust snapshot, and startup ack
57
+ // channel through its environment. Transient keys are restored after the
58
+ // session is created so the host process never keeps them.
59
+ const sandboxAckPath = toolPlan.sandboxExtension && input.sandbox !== undefined
60
+ ? path.join(TEMP_ROOT_DIR, "sandbox-profile-acks", `${randomUUID()}.json`)
61
+ : undefined;
62
+ const sandboxDiagnosticsPath = sandboxAckPath
63
+ ? path.join(TEMP_ROOT_DIR, "sandbox-profile-diagnostics", `${randomUUID()}.json`)
64
+ : undefined;
65
+ const sandboxEnv: Record<string, string | undefined> | undefined = sandboxAckPath
66
+ ? {
67
+ [SUBAGENT_SANDBOX_PROFILE_ENV]: input.sandbox,
68
+ [SUBAGENT_SANDBOX_PROJECT_TRUST_ENV]: hasTrustedProfileProjectCwd(input) ? "1" : "0",
69
+ [SANDBOX_STARTUP_ACK_PATH_ENV]: sandboxAckPath,
70
+ [SANDBOX_STARTUP_ACK_TOKEN_ENV]: randomUUID(),
71
+ [SANDBOX_DIAGNOSTICS_PATH_ENV]: sandboxDiagnosticsPath,
72
+ ...(input.host === "parent" ? { [IN_PROCESS_CHILD_ENV]: "1" } : {}),
73
+ }
74
+ : undefined;
75
+ if (sandboxAckPath) fs.mkdirSync(path.dirname(sandboxAckPath), { recursive: true, mode: 0o700 });
76
+
77
+ // A selected permission profile travels as a bare validated name (the rules
78
+ // live in the child's global pi-permission-system config). The key is
79
+ // transient like the sandbox keys: restored on the host once the child
80
+ // session exists.
81
+ const permissionProfileEnv: Record<string, string | undefined> | undefined =
82
+ input.permissionProfile !== undefined
83
+ ? { [SUBAGENT_PERMISSION_PROFILE_ENV]: input.permissionProfile }
84
+ : undefined;
85
+ const childEnv: Record<string, string | undefined> | undefined =
86
+ sandboxEnv !== undefined || permissionProfileEnv !== undefined
87
+ ? { ...(sandboxEnv ?? {}), ...(permissionProfileEnv ?? {}) }
88
+ : undefined;
89
+ // The profile key is pinned for every launch, `undefined` included: a child
90
+ // that declares no profile must not inherit the host session's role
91
+ // selection, and one that declares a profile must not be overridden by it
92
+ // (the launcher env wins inside pi-permission-system). It is kept out of
93
+ // `childEnv` so a plain in-process child does not also start receiving the
94
+ // binding and MCP values that only a runner-hosted child used to get.
95
+ const profilePin: Record<string, string | undefined> = {
96
+ [SUBAGENT_PERMISSION_PROFILE_ENV]: input.permissionProfile,
97
+ // Present for every child launch: it is what tells pi-permission-system
98
+ // this selection is authoritative for the child (see the constant).
99
+ [SUBAGENT_PERMISSION_PROFILE_PINNED_ENV]: "1",
100
+ };
101
+ const transientProcessEnv = [
102
+ ...new Set([
103
+ ...(childEnv ? Object.keys(childEnv) : []),
104
+ ...Object.keys(profilePin),
105
+ ]),
106
+ ];
107
+ return {
108
+ childEnv,
109
+ profilePin,
110
+ transientProcessEnv,
111
+ ...(sandboxDiagnosticsPath ? { sandboxDiagnosticsPath } : {}),
112
+ };
113
+ }
@@ -0,0 +1,42 @@
1
+ const knownStates = new Set(["queued", "running", "complete", "failed", "partial", "paused", "stopped", "rejected"]);
2
+
3
+ /**
4
+ * Private, installation-owned evidence. Never changes drain/query behavior or retains statuses.
5
+ * Observes the ordinary indexed drain, not historical ownership or outside work appearing later.
6
+ */
7
+ export class ReadonlyDrainObservation {
8
+ private state: "pending" | "empty" | "denied" = "pending";
9
+ private started = false;
10
+ private first = false;
11
+ private readonly file: string;
12
+ private readonly guard: () => boolean;
13
+ constructor(file: string, guard: () => boolean) { this.file = file; this.guard = guard; }
14
+ deny(): void { this.state = "denied"; }
15
+ check(): boolean {
16
+ try { if (!this.guard()) this.deny(); } catch { this.deny(); }
17
+ return this.state !== "denied";
18
+ }
19
+ begin(file: string | null, native: boolean): void {
20
+ if (this.started || file !== this.file || !native) this.deny();
21
+ this.started = true;
22
+ this.check();
23
+ }
24
+ /** Called at the existing initial read, before reconciliation or filtering. */
25
+ readonly status: RawDrainStatusObserver = (status) => {
26
+ if (!status || typeof status.sessionId !== "string" || !status.sessionId
27
+ || !knownStates.has(status.state as string)) this.deny();
28
+ else if (status.sessionId === this.file && (status.state === "queued" || status.state === "running")) this.deny();
29
+ };
30
+ predicate(hasWork: boolean): void {
31
+ if (this.first) return;
32
+ this.first = true;
33
+ if (hasWork) this.deny();
34
+ }
35
+ complete(): void {
36
+ if (this.started && this.first && this.check()) this.state = "empty";
37
+ }
38
+ settled(): boolean { return this.check() && this.state === "empty"; }
39
+ }
40
+
41
+ /** Internal synchronous sink; null means an existing query encountered uncertainty. */
42
+ export type RawDrainStatusObserver = (status: { sessionId?: unknown; state?: unknown } | null) => void;
@@ -11,14 +11,14 @@ import {
11
11
 
12
12
  const RUN_FANOUT_ROOT = path.join(TEMP_ROOT_DIR, "run-fanout-budgets");
13
13
 
14
- interface ManifestV1 {
14
+ interface FanoutBudgetManifest {
15
15
  version: 1;
16
16
  rootRunId: string;
17
17
  limit: number;
18
18
  createdAt: number;
19
19
  }
20
20
 
21
- interface ClaimV1 {
21
+ interface FanoutBudgetClaim {
22
22
  version: 1;
23
23
  claimId: string;
24
24
  path: string;
@@ -41,16 +41,16 @@ function safeRootRunId(rootRunId: string): string {
41
41
  return rootRunId.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 120) || randomUUID();
42
42
  }
43
43
 
44
- function parseManifest(value: unknown): ManifestV1 | undefined {
44
+ function parseManifest(value: unknown): FanoutBudgetManifest | undefined {
45
45
  if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
46
- const manifest = value as Partial<ManifestV1>;
46
+ const manifest = value as Partial<FanoutBudgetManifest>;
47
47
  if (manifest.version !== 1 || typeof manifest.rootRunId !== "string" || !manifest.rootRunId
48
48
  || !Number.isInteger(manifest.limit) || (manifest.limit ?? 0) <= 0
49
49
  || typeof manifest.createdAt !== "number" || !Number.isFinite(manifest.createdAt)) return undefined;
50
- return manifest as ManifestV1;
50
+ return manifest as FanoutBudgetManifest;
51
51
  }
52
52
 
53
- function readManifest(directory: string): ManifestV1 {
53
+ function readManifest(directory: string): FanoutBudgetManifest {
54
54
  let parsed: unknown;
55
55
  try {
56
56
  parsed = JSON.parse(fs.readFileSync(path.join(directory, "manifest.json"), "utf-8"));
@@ -84,7 +84,7 @@ export function createRunFanoutBudget(rootRunId: string, limit: number): RunFano
84
84
  do directory = path.join(RUN_FANOUT_ROOT, `${safeRootRunId(rootRunId)}-${randomUUID()}`);
85
85
  while (fs.existsSync(directory));
86
86
  fs.mkdirSync(path.join(directory, "claims"), { recursive: true, mode: 0o700 });
87
- const manifest: ManifestV1 = { version: 1, rootRunId, limit, createdAt: Date.now() };
87
+ const manifest: FanoutBudgetManifest = { version: 1, rootRunId, limit, createdAt: Date.now() };
88
88
  fs.writeFileSync(path.join(directory, "manifest.json"), `${JSON.stringify(manifest)}\n`, { mode: 0o600, flag: "wx" });
89
89
  return { version: 1, rootRunId, directory, limit };
90
90
  }
@@ -230,7 +230,7 @@ function commitRunFanoutBatch<T>(descriptor: RunFanoutBudgetDescriptor, paths: s
230
230
  const fd = fs.openSync(slotPath, "wx", 0o600);
231
231
  created.push(slotPath);
232
232
  try {
233
- const claim: ClaimV1 = { version: 1, claimId: randomUUID(), path: claimPath, claimedAt: Date.now() };
233
+ const claim: FanoutBudgetClaim = { version: 1, claimId: randomUUID(), path: claimPath, claimedAt: Date.now() };
234
234
  fs.writeFileSync(fd, `${JSON.stringify(claim)}\n`, "utf-8");
235
235
  } finally { fs.closeSync(fd); }
236
236
  break;
@@ -1,4 +1,4 @@
1
- import type { RuntimeAcknowledgedChildExtensionsV1 } from "../../shared/types.ts";
1
+ import type { RuntimeAcknowledgedChildExtensions } from "../../shared/types.ts";
2
2
 
3
3
  export const RUNTIME_EXTENSION_ACK_EVENT = "subagent:acknowledge-extension";
4
4
  export const MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_IDS = 32;
@@ -14,7 +14,7 @@ export function isRuntimeAcknowledgedExtensionId(value: unknown): value is strin
14
14
  && !value.includes("\\");
15
15
  }
16
16
 
17
- export function projectRuntimeAcknowledgedExtensions(ids: Iterable<unknown>): RuntimeAcknowledgedChildExtensionsV1 | undefined {
17
+ export function projectRuntimeAcknowledgedExtensions(ids: Iterable<unknown>): RuntimeAcknowledgedChildExtensions | undefined {
18
18
  const unique: string[] = [];
19
19
  const seen = new Set<string>();
20
20
  for (const id of ids) {
@@ -31,7 +31,7 @@ export function projectRuntimeAcknowledgedExtensions(ids: Iterable<unknown>): Ru
31
31
  };
32
32
  }
33
33
 
34
- export function sanitizeRuntimeAcknowledgedExtensions(value: unknown): RuntimeAcknowledgedChildExtensionsV1 | undefined {
34
+ export function sanitizeRuntimeAcknowledgedExtensions(value: unknown): RuntimeAcknowledgedChildExtensions | undefined {
35
35
  if (!value || typeof value !== "object") return undefined;
36
36
  const raw = value as Record<string, unknown>;
37
37
  if (raw.version !== 1 || raw.source !== "child-runtime" || !Array.isArray(raw.ids)) return undefined;
@@ -83,3 +83,37 @@ export default function registerSandboxProfileGuard(pi: ExtensionAPI): void {
83
83
  return undefined;
84
84
  });
85
85
  }
86
+
87
+ export type ProjectScopedProfileKind = "sandbox" | "permission";
88
+
89
+ /**
90
+ * [fork] Shared project-trust gate for project-scoped sandbox/permission
91
+ * profile selections. Returns the error message to surface when the selection
92
+ * is not permitted under the current project-trust state, or undefined when
93
+ * the launch may proceed. The messages are byte-identical to the original
94
+ * preflight and executor copies that this helper replaces.
95
+ */
96
+ export function projectScopedProfileTrustError(options: {
97
+ kind: ProjectScopedProfileKind;
98
+ agentName: string;
99
+ profileName: string;
100
+ /** True when the selection is project-scoped (agent source or override scope). */
101
+ projectScoped: boolean;
102
+ /** Resolved trusted project cwd, or undefined when the project is not trusted. */
103
+ trustedCwd: string | undefined;
104
+ /** cwd that must match the trusted project cwd, already in comparison form. */
105
+ effectiveCwd: string;
106
+ /** "preflight" compares raw cwds; "executor" resolves the child cwd and says "child cwd". */
107
+ messageStyle: "preflight" | "executor";
108
+ }): string | undefined {
109
+ if (!options.projectScoped) return undefined;
110
+ const label = options.kind === "sandbox" ? "sandbox profile" : "permission profile";
111
+ if (options.trustedCwd === undefined) {
112
+ return `Agent '${options.agentName}' selects ${label} '${options.profileName}' from project scope, but the project is not trusted. Trust the project and retry.`;
113
+ }
114
+ if (options.trustedCwd === options.effectiveCwd) return undefined;
115
+ if (options.messageStyle === "executor") {
116
+ return `Agent '${options.agentName}' selects ${label} '${options.profileName}' from project scope, but child cwd '${options.effectiveCwd}' does not match the trusted project cwd '${options.trustedCwd}'. Launch from the trusted project cwd and retry.`;
117
+ }
118
+ return `Agent '${options.agentName}' selects ${label} '${options.profileName}' from project scope, but cwd '${options.effectiveCwd}' does not match trusted project cwd '${options.trustedCwd}'. Launch from the trusted project cwd and retry.`;
119
+ }
@@ -17,6 +17,7 @@ import { registerChildWatchdog } from "../../watchdog/register-child.ts";
17
17
  import type { ChildWatchdogConfig } from "../../watchdog/child-status.ts";
18
18
  import { requestWatchdogPermission, type WatchdogPermissionRequest, type WatchdogPermissionResult } from "../../watchdog/permission-arbiter.ts";
19
19
  import { SUBAGENT_WATCHDOG_WARNING_TYPE } from "../../watchdog/types.ts";
20
+ import { inheritedNestedRouteOf } from "./nested-events.ts";
20
21
  import { registerWaitTool } from "../background/wait-tool.ts";
21
22
  import { drainOutstandingWork } from "../background/auto-drain.ts";
22
23
  import {
@@ -441,15 +442,21 @@ function registerStructuredOutputTool(pi: ExtensionAPI, structured: NonNullable<
441
442
  }
442
443
 
443
444
  /** Register every child-side hook the prompt runtime owns for one child session. */
444
- export default function registerSubagentPromptRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
445
+ export default function registerSubagentPromptRuntime(pi: ExtensionAPI, config?: ChildRuntimeConfig, drainObservation?: import("./readonly-drain-observation.ts").ReadonlyDrainObservation): void {
446
+ // A path-based load has no ChildRuntimeConfig. This can happen if an
447
+ // ambient-extension discovery path finds the runtime module in addition to
448
+ // the configured inline factory. It must be inert rather than crashing the
449
+ // child before startup; the inline factory remains the real registration path.
450
+ if (!config) return;
445
451
  registerRuntimeExtensionAcknowledgements(pi, config.runtimeAcknowledgements);
446
452
  registerPermissionGate(pi, config.permissions, config.childWatchdog);
447
453
  registerToolBudget(pi, config.toolBudget);
448
454
  registerChildWatchdog(pi, config.childWatchdog, config.watchdogStatus);
449
- const waitState = {
455
+ const waitState = config.runtimeState ?? {
450
456
  baseCwd: "",
451
457
  currentSessionId: null,
452
458
  asyncJobs: new Map(),
459
+ foregroundRuns: new Map(),
453
460
  foregroundControls: new Map(),
454
461
  lastForegroundControlId: null,
455
462
  cleanupTimers: new Map(),
@@ -460,7 +467,8 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI, config:
460
467
  watcherRestartTimer: null,
461
468
  resultFileCoalescer: { schedule: () => false, clear: () => {} },
462
469
  } as unknown as SubagentState;
463
- if (typeof pi.registerTool === "function") registerWaitTool(pi, waitState, config.waitTool.enabled, undefined, config.waitTool.defaultTimeoutMs);
470
+ const nestedRootRunId = inheritedNestedRouteOf(config)?.rootRunId;
471
+ if (typeof pi.registerTool === "function") registerWaitTool(pi, waitState, config.waitTool.enabled, undefined, config.waitTool.defaultTimeoutMs, { nestedRootRunId });
464
472
  const supervisorMetadata = childSupervisorMetadata(config);
465
473
  let nativeSupervisorClientRegistered = false;
466
474
  const registerNativeSupervisorClientOnce = (): void => {
@@ -481,8 +489,18 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI, config:
481
489
  if (diagnostic) throw new Error(formatChildToolDiagnostic(diagnostic));
482
490
  });
483
491
  onRuntimeEvent("agent_end", async (_event: unknown, ctx: unknown) => {
484
- if ((ctx as { hasUI?: boolean } | undefined)?.hasUI === true) return;
485
- await drainOutstandingWork({ state: waitState, events: pi.events });
492
+ if ((ctx as { hasUI?: boolean } | undefined)?.hasUI === true) drainObservation?.deny();
493
+ if (drainObservation) {
494
+ try {
495
+ if ((ctx as ExtensionContext)?.sessionManager?.getSessionFile() !== waitState.currentSessionId) drainObservation.deny();
496
+ } catch { drainObservation.deny(); }
497
+ }
498
+ config.holdFinalDrain?.(true);
499
+ try {
500
+ await drainOutstandingWork({ state: waitState, events: pi.events, nestedRootRunId, hasPendingSupervisorRequest: config.hasPendingSupervisorRequest }, drainObservation);
501
+ } finally {
502
+ config.holdFinalDrain?.(false);
503
+ }
486
504
  });
487
505
  if (config.structuredOutput) registerStructuredOutputTool(pi, config.structuredOutput);
488
506