pi-subagents 0.84.0 → 0.85.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 (204) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-235AWJUQ.js → chunk-3UZ5FVVJ.js} +310 -101
  5. package/bundle/{chunk-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  6. package/bundle/{chunk-4E7BKDTX.js → chunk-CS4O36CZ.js} +11 -156
  7. package/bundle/{chunk-VQVVHSY6.js → chunk-DV2NCNPR.js} +22 -11
  8. package/bundle/{chunk-G2Z6ZH26.js → chunk-GCSLVFCX.js} +1 -1
  9. package/bundle/{chunk-2S4K53MV.js → chunk-H2NLFTC5.js} +1 -1
  10. package/bundle/{chunk-NKQ6JNAS.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/chunk-HXRB42AF.js +108 -0
  12. package/bundle/{chunk-7BWGNDNK.js → chunk-IQIWF2VX.js} +190 -1177
  13. package/bundle/{chunk-XDQORLZ5.js → chunk-JNXT3MPI.js} +15 -6
  14. package/bundle/{chunk-J5YL7LYR.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-JG4QKI5M.js → chunk-JWYG26RE.js} +209 -93
  16. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  17. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  18. package/bundle/{chunk-NENDSQUY.js → chunk-KZ34KQQH.js} +9 -6
  19. package/bundle/{chunk-AKOIVLA5.js → chunk-L2ENOFVZ.js} +76 -58
  20. package/bundle/{chunk-CGN2TVE7.js → chunk-LGMILZNE.js} +322 -18
  21. package/bundle/{chunk-L3WFKBEI.js → chunk-LTPH2DXH.js} +247 -153
  22. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  23. package/bundle/{chunk-PV63UFUR.js → chunk-O7CPL6H4.js} +183 -28
  24. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  25. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  26. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  27. package/bundle/{chunk-SSG7IEP5.js → chunk-RQAUNAWG.js} +2 -2
  28. package/bundle/{chunk-PALJGGYC.js → chunk-RV5OGHLO.js} +6 -3
  29. package/bundle/chunk-T5V5BRCL.js +1067 -0
  30. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  31. package/bundle/{chunk-DZDETGRJ.js → chunk-WOVMHDES.js} +231 -182
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +17 -2
  38. package/docs/configuration.md +2 -2
  39. package/docs/extension-api.md +16 -1
  40. package/docs/workflows.md +30 -2
  41. package/package.json +1 -1
  42. package/src/agents/agent-management.js +27 -11
  43. package/src/agents/agent-memory.d.ts +1 -4
  44. package/src/agents/agent-memory.js +1 -4
  45. package/src/agents/agents.d.ts +1 -3
  46. package/src/agents/agents.js +7 -6
  47. package/src/agents/frontmatter.js +1 -8
  48. package/src/agents/global-npm-root.d.ts +1 -0
  49. package/src/agents/global-npm-root.js +11 -3
  50. package/src/agents/skills.d.ts +0 -3
  51. package/src/agents/skills.js +0 -3
  52. package/src/extension/config.js +7 -1
  53. package/src/extension/herdr-pi-bridge.js +10 -2
  54. package/src/extension/index.d.ts +0 -13
  55. package/src/extension/index.js +43 -32
  56. package/src/extension/public-execution.d.ts +1 -0
  57. package/src/extension/public-execution.js +4 -0
  58. package/src/extension/reply-workflow-script.js +24 -4
  59. package/src/extension/schemas.d.ts +8 -3
  60. package/src/extension/schemas.js +5 -3
  61. package/src/extension/session-switch.d.ts +25 -0
  62. package/src/extension/session-switch.js +138 -0
  63. package/src/extension/subagent-guide.d.ts +1 -1
  64. package/src/extension/subagent-guide.js +1 -1
  65. package/src/extension/subagent-launch-tool.d.ts +25 -0
  66. package/src/extension/subagent-launch-tool.js +48 -0
  67. package/src/extension/tool-activation.js +25 -11
  68. package/src/extension/tool-description.js +6 -0
  69. package/src/inspectors/herdr/actions.d.ts +0 -1
  70. package/src/inspectors/herdr/actions.js +0 -1
  71. package/src/inspectors/session-roots-codec.d.ts +0 -1
  72. package/src/inspectors/session-roots-codec.js +0 -1
  73. package/src/inspectors/tmux/actions.d.ts +0 -1
  74. package/src/inspectors/tmux/actions.js +0 -1
  75. package/src/integrations/herdr-status.js +3 -8
  76. package/src/intercom/native-supervisor-channel.js +65 -9
  77. package/src/runs/background/async-execution.d.ts +5 -9
  78. package/src/runs/background/async-execution.js +62 -27
  79. package/src/runs/background/async-job-tracker.js +12 -0
  80. package/src/runs/background/async-resume.d.ts +2 -1
  81. package/src/runs/background/async-resume.js +112 -39
  82. package/src/runs/background/async-retention.js +6 -1
  83. package/src/runs/background/auto-drain.js +2 -1
  84. package/src/runs/background/boot-id.d.ts +1 -3
  85. package/src/runs/background/boot-id.js +1 -3
  86. package/src/runs/background/completion-batcher.d.ts +3 -4
  87. package/src/runs/background/completion-batcher.js +2 -3
  88. package/src/runs/background/control-channel.d.ts +0 -6
  89. package/src/runs/background/control-channel.js +0 -6
  90. package/src/runs/background/fleet-view.js +2 -3
  91. package/src/runs/background/notify.d.ts +0 -2
  92. package/src/runs/background/notify.js +0 -2
  93. package/src/runs/background/result-watcher.d.ts +1 -0
  94. package/src/runs/background/result-watcher.js +59 -29
  95. package/src/runs/background/resume-guidance.js +4 -2
  96. package/src/runs/background/retained-children.js +2 -1
  97. package/src/runs/background/run-child-session.d.ts +0 -1
  98. package/src/runs/background/run-child-session.js +1 -1
  99. package/src/runs/background/run-status.js +4 -3
  100. package/src/runs/background/scheduled-runs.d.ts +3 -1
  101. package/src/runs/background/scheduled-runs.js +13 -16
  102. package/src/runs/background/subagent-runner.d.ts +2 -4
  103. package/src/runs/background/subagent-runner.js +9 -6
  104. package/src/runs/background/subagent-wait.js +12 -15
  105. package/src/runs/background/wait-config.d.ts +2 -0
  106. package/src/runs/background/wait-config.js +17 -3
  107. package/src/runs/background/wait-tool.js +4 -2
  108. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  109. package/src/runs/background/workflow-terminal-proof.js +0 -1
  110. package/src/runs/foreground/execution.d.ts +0 -3
  111. package/src/runs/foreground/execution.js +17 -9
  112. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  113. package/src/runs/foreground/subagent-executor.js +107 -26
  114. package/src/runs/shared/child-commands.js +15 -2
  115. package/src/runs/shared/child-hooks.d.ts +1 -7
  116. package/src/runs/shared/child-hooks.js +13 -5
  117. package/src/runs/shared/child-launch.js +6 -2
  118. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  119. package/src/runs/shared/child-session.d.ts +1 -1
  120. package/src/runs/shared/child-session.js +21 -2
  121. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  122. package/src/runs/shared/child-tool-plan.js +0 -1
  123. package/src/runs/shared/claude-code-adapter.js +11 -0
  124. package/src/runs/shared/external-cli-runner.js +26 -6
  125. package/src/runs/shared/herdr-connection.js +2 -1
  126. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  127. package/src/runs/shared/herdr-pane-host.js +17 -1
  128. package/src/runs/shared/herdr-placed-run.js +48 -22
  129. package/src/runs/shared/lane-metadata.d.ts +0 -1
  130. package/src/runs/shared/lane-metadata.js +0 -1
  131. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  132. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  133. package/src/runs/shared/model-resolution.d.ts +2 -2
  134. package/src/runs/shared/model-resolution.js +7 -1
  135. package/src/runs/shared/model-scope.d.ts +1 -5
  136. package/src/runs/shared/model-scope.js +1 -5
  137. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  138. package/src/runs/shared/mutation-evidence.js +52 -7
  139. package/src/runs/shared/nested-events.d.ts +1 -0
  140. package/src/runs/shared/nested-events.js +1 -1
  141. package/src/runs/shared/parallel-utils.d.ts +0 -1
  142. package/src/runs/shared/permissions.js +5 -3
  143. package/src/runs/shared/placement-host.d.ts +5 -1
  144. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  145. package/src/runs/shared/rex-pane-host.js +0 -2
  146. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  147. package/src/runs/shared/run-launch-folder.js +21 -0
  148. package/src/runs/shared/runner-launcher.d.ts +12 -1
  149. package/src/runs/shared/runner-launcher.js +16 -0
  150. package/src/runs/shared/single-output.d.ts +3 -3
  151. package/src/runs/shared/single-output.js +5 -3
  152. package/src/runs/shared/structured-output.d.ts +8 -0
  153. package/src/runs/shared/structured-output.js +30 -2
  154. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  155. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  156. package/src/runs/shared/tool-timeout.js +2 -1
  157. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  158. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  159. package/src/runs/shared/worktree.d.ts +3 -0
  160. package/src/runs/shared/worktree.js +20 -0
  161. package/src/shared/capacity-resilient-json.d.ts +1 -1
  162. package/src/shared/child-cache-retention.d.ts +1 -2
  163. package/src/shared/child-cache-retention.js +1 -2
  164. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  165. package/src/shared/fleet-transcript-reader.js +333 -0
  166. package/src/shared/formatters.d.ts +0 -18
  167. package/src/shared/formatters.js +0 -18
  168. package/src/shared/session-succession.d.ts +16 -1
  169. package/src/shared/session-succession.js +41 -2
  170. package/src/shared/session-warnings.d.ts +7 -0
  171. package/src/shared/session-warnings.js +26 -0
  172. package/src/shared/settings.d.ts +0 -23
  173. package/src/shared/settings.js +3 -35
  174. package/src/shared/types.d.ts +28 -11
  175. package/src/shared/types.js +0 -12
  176. package/src/shared/utils.d.ts +0 -14
  177. package/src/shared/utils.js +0 -22
  178. package/src/shared/wait-tool-name.d.ts +8 -0
  179. package/src/shared/wait-tool-name.js +13 -0
  180. package/src/slash/slash-commands.js +2 -1
  181. package/src/slash/subagent-cost.d.ts +3 -2
  182. package/src/slash/subagent-cost.js +22 -3
  183. package/src/slash/subagents-admin.js +0 -1
  184. package/src/tui/fleet-status.d.ts +0 -5
  185. package/src/tui/fleet-status.js +4 -24
  186. package/src/tui/fleet-transcript.d.ts +1 -44
  187. package/src/tui/fleet-transcript.js +1 -327
  188. package/src/tui/fleet.js +6 -4
  189. package/src/tui/render.d.ts +0 -9
  190. package/src/tui/render.js +81 -47
  191. package/src/tui/subagent-messages.js +3 -2
  192. package/src/watchdog/register-child.d.ts +2 -3
  193. package/src/watchdog/register-child.js +2 -3
  194. package/src/watchdog/turn-delta.js +2 -1
  195. package/src/workflows/scripted-workflow.js +241 -20
  196. package/src/workflows/workflow-launch-record.d.ts +15 -6
  197. package/src/workflows/workflow-launch-record.js +30 -12
  198. package/src/workflows/workflow-resume-claim.js +2 -2
  199. package/src/workflows/workflow-resume.d.ts +1 -1
  200. package/src/workflows/workflow-resume.js +11 -8
  201. package/src/workflows/workflow-script-worker.d.ts +13 -0
  202. package/src/workflows/workflow-script-worker.js +79 -0
  203. package/workflow-script-process.cjs +36 -0
  204. package/workflow-script-worker.cjs +4 -1
@@ -3,6 +3,9 @@ import { promises as fs } from "node:fs";
3
3
  import path from "node:path";
4
4
  /** Optional global package discovery; a failure never prevents local discovery. */
5
5
  export async function resolveGlobalNpmRoot(options = {}) {
6
+ const signal = options.signal;
7
+ if (signal?.aborted)
8
+ return null;
6
9
  const env = options.env ?? process.env;
7
10
  const offline = env.PI_OFFLINE?.toLowerCase();
8
11
  if (offline === "1" || offline === "true" || offline === "yes")
@@ -17,6 +20,8 @@ export async function resolveGlobalNpmRoot(options = {}) {
17
20
  // Invalid APPDATA roots fall back to npm (including disappearing directories).
18
21
  }
19
22
  }
23
+ if (signal?.aborted)
24
+ return null;
20
25
  const timeoutMs = options.timeoutMs ?? 5000;
21
26
  const output = await new Promise((resolve) => {
22
27
  let settled = false;
@@ -25,6 +30,7 @@ export async function resolveGlobalNpmRoot(options = {}) {
25
30
  return;
26
31
  settled = true;
27
32
  clearTimeout(timer);
33
+ signal?.removeEventListener("abort", cancel);
28
34
  resolve(value);
29
35
  };
30
36
  const commandOptions = {
@@ -40,11 +46,13 @@ export async function resolveGlobalNpmRoot(options = {}) {
40
46
  const child = (options.platform ?? process.platform) === "win32"
41
47
  ? exec("npm root -g", commandOptions, callback)
42
48
  : execFile("npm", ["root", "-g"], commandOptions, callback);
43
- // Resolve at the deadline even if inherited pipes hold the callback open.
44
- const timer = setTimeout(() => {
49
+ const cancel = () => {
45
50
  child.kill();
46
51
  finish(null);
47
- }, timeoutMs);
52
+ };
53
+ // Resolve at the deadline even if inherited pipes hold the callback open.
54
+ const timer = setTimeout(cancel, timeoutMs);
55
+ signal?.addEventListener("abort", cancel, { once: true });
48
56
  });
49
57
  if (!output)
50
58
  return null;
@@ -1,6 +1,3 @@
1
- /**
2
- * Skill resolution and caching for subagent extension
3
- */
4
1
  export type SkillSource = "project" | "user" | "project-package" | "user-package" | "project-settings" | "user-settings" | "extension" | "builtin" | "unknown";
5
2
  interface ResolvedSkill {
6
3
  name: string;
@@ -1,6 +1,3 @@
1
- /**
2
- * Skill resolution and caching for subagent extension
3
- */
4
1
  import { execSync } from "node:child_process";
5
2
  import * as fs from "node:fs";
6
3
  import * as os from "node:os";
@@ -13,7 +13,7 @@ import { validateModelResponseAliases } from "../shared/model-response-aliases.j
13
13
  import { validateDisabledFeatures } from "../shared/disabled-features.js";
14
14
  // Explicit route identity, worktree, checkpoint, and tool-surface policies must not be silently
15
15
  // discarded and replaced by the built-in defaults after validation fails.
16
- const FAIL_CLOSED_CONFIG_KEYS = ["worktreeProvider", "worktreeBranchPrefix", "modelResponseAliases", "modelExclusions", "checkpointBeforeDeadlineMs", "disabledFeatures", "scheduledRuns", "toolActivation", "authorityPolicy", "permissions", "toolBudget", "runnerLaunchers"];
16
+ const FAIL_CLOSED_CONFIG_KEYS = ["worktreeProvider", "worktreeBranchPrefix", "modelResponseAliases", "modelExclusions", "checkpointBeforeDeadlineMs", "disabledFeatures", "scheduledRuns", "toolActivation", "authorityPolicy", "permissions", "toolBudget", "runnerLaunchers", "globalConcurrencyLimit"];
17
17
  const ARTIFACT_DIR_PREFERENCES = new Set(["project", "session", "temp"]);
18
18
  const FLEET_KEYBINDING_ACTION_SET = new Set(FLEET_KEYBINDING_ACTIONS);
19
19
  const KEY_MODIFIERS = new Set(["ctrl", "shift", "alt", "super"]);
@@ -196,6 +196,12 @@ function validateConfig(config) {
196
196
  || config.maxActiveAsyncRunsPerSession < 0)) {
197
197
  throw new Error("config.maxActiveAsyncRunsPerSession must be a non-negative integer");
198
198
  }
199
+ if (config.globalConcurrencyLimit !== undefined
200
+ && (typeof config.globalConcurrencyLimit !== "number"
201
+ || !Number.isInteger(config.globalConcurrencyLimit)
202
+ || config.globalConcurrencyLimit < 1)) {
203
+ throw new Error("config.globalConcurrencyLimit must be a positive integer");
204
+ }
199
205
  if (config.resultScanLogging !== undefined && config.resultScanLogging !== "all" && config.resultScanLogging !== "activity" && config.resultScanLogging !== "off") {
200
206
  throw new Error('config.resultScanLogging must be "all", "activity", or "off"');
201
207
  }
@@ -13,6 +13,7 @@ import { rewriteSubagentPrompt } from "../runs/shared/subagent-prompt-runtime.js
13
13
  import { assertNoToolModifierEntries } from "../runs/shared/child-tool-plan.js";
14
14
  import { resolveExistingReadPaths } from "../shared/settings.js";
15
15
  import { MODEL_ONLY_TOOL } from "../shared/extension-context.js";
16
+ import { captureWatchdogDiffBaseline, createWatchdogDiffTool, WATCHDOG_DIFF_TOOL_NAME } from "../watchdog/diff-tool.js";
16
17
  function gitEvidence(cwd) {
17
18
  const run = (args) => spawnSync("git", args, { cwd, encoding: "utf8", timeout: 5_000, maxBuffer: 128 * 1024 });
18
19
  const inside = run(["rev-parse", "--is-inside-work-tree"]);
@@ -222,10 +223,14 @@ export default function registerHerdrPiBridge(pi) {
222
223
  const resolved = resolveRemoteHerdrResources(process.cwd(), { agent: resources.agent, ...(resources.skills ? { skills: resources.skills } : {}), ...(resources.toolCeiling ? { toolCeiling: resources.toolCeiling } : {}), ...(resources.reads !== undefined ? { reads: resources.reads } : {}) }, context ? pi.getActiveTools() : []);
223
224
  resolvedSystemPrompt = resolved.systemPrompt;
224
225
  resolvedContextPolicy = resolved;
226
+ // A local child gets watchdog_diff from the prompt runtime, which a placed child never loads.
227
+ if (resolved.tools.includes(WATCHDOG_DIFF_TOOL_NAME) && !pi.getAllTools().some((tool) => tool.name === WATCHDOG_DIFF_TOOL_NAME))
228
+ pi.registerTool(createWatchdogDiffTool(captureWatchdogDiffBaseline(process.cwd()), { workingTreeAtLaunch: true }));
225
229
  pi.setActiveTools(resolved.tools);
226
230
  const acknowledged = context ? pi.getActiveTools() : [];
227
- if (acknowledged.some((tool) => !resolved.tools.includes(tool)) || resolved.tools.some((tool) => !acknowledged.includes(tool)))
228
- throw new Error("Remote Pi did not apply the resolved active-tool set exactly.");
231
+ const missing = resolved.tools.filter((tool) => !acknowledged.includes(tool)), extra = acknowledged.filter((tool) => !resolved.tools.includes(tool));
232
+ if (missing.length || extra.length)
233
+ throw new Error(`Remote Pi did not apply the resolved active-tool set exactly (${[...(missing.length ? [`not available: ${missing.join(", ")}`] : []), ...(extra.length ? [`unexpected: ${extra.join(", ")}`] : [])].join("; ")}).`);
229
234
  configured = true;
230
235
  send({ type: "configured", requestId: frame.requestId, nativeSessionId, agent: resolved.agent, skills: resolved.skills, model: context?.model?.provider && context.model.id ? `${context.model.provider}/${context.model.id}` : undefined, tools: acknowledged });
231
236
  continue;
@@ -246,9 +251,12 @@ export default function registerHerdrPiBridge(pi) {
246
251
  }
247
252
  }
248
253
  catch (error) {
254
+ context?.ui?.notify(`pi-subagents bridge: ${error.message}`, "error");
249
255
  socket.destroy(error);
250
256
  }
251
257
  });
258
+ // Without a listener, a protocol error or peer reset is an uncaught exception that ends the child Pi.
259
+ socket.on("error", () => { });
252
260
  socket.on("close", () => { if (client === socket)
253
261
  client = undefined; });
254
262
  if (context && nativeSessionId)
@@ -1,16 +1,3 @@
1
- /**
2
- * Subagent Tool
3
- *
4
- * Full-featured subagent with sync and async modes.
5
- * - Sync (default): Streams output, renders markdown, tracks usage
6
- * - Async: Background execution, emits events when done
7
- *
8
- * Public execution mode: workflow (workflow: true reply block, script path, or named resource)
9
- * Toggle: async parameter (default: true; set asyncByDefault:false in config.json to opt out)
10
- *
11
- * Config file: ~/.pi/agent/extensions/subagent/config.json
12
- * { "asyncByDefault": true, "defaultSubagentContext": "fork", "forkContext": { "mode": "pruned", "model": "provider/model" }, "forceTopLevelAsync": true, "maxSubagentDepth": 1, "intercomBridge": { "mode": "always", "instructionFile": "./intercom-bridge.md" }, "worktreeSetupHook": "./scripts/setup-worktree.mjs" }
13
- */
14
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
15
2
  import { type HerdrStatusRun } from "../integrations/herdr-status.ts";
16
3
  import { type SubagentState } from "../shared/types.ts";
@@ -1,16 +1,3 @@
1
- /**
2
- * Subagent Tool
3
- *
4
- * Full-featured subagent with sync and async modes.
5
- * - Sync (default): Streams output, renders markdown, tracks usage
6
- * - Async: Background execution, emits events when done
7
- *
8
- * Public execution mode: workflow (workflow: true reply block, script path, or named resource)
9
- * Toggle: async parameter (default: true; set asyncByDefault:false in config.json to opt out)
10
- *
11
- * Config file: ~/.pi/agent/extensions/subagent/config.json
12
- * { "asyncByDefault": true, "defaultSubagentContext": "fork", "forkContext": { "mode": "pruned", "model": "provider/model" }, "forceTopLevelAsync": true, "maxSubagentDepth": 1, "intercomBridge": { "mode": "always", "instructionFile": "./intercom-bridge.md" }, "worktreeSetupHook": "./scripts/setup-worktree.mjs" }
13
- */
14
1
  import { randomUUID } from "node:crypto";
15
2
  import * as fs from "node:fs";
16
3
  import * as os from "node:os";
@@ -24,7 +11,9 @@ import { registerRuntimeAgentEventListener } from "../agents/runtime-agent-event
24
11
  import { ensureAccessibleDir } from "../shared/accessible-dir.js";
25
12
  import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "../shared/artifacts.js";
26
13
  import { resolveCurrentSessionId } from "../shared/session-identity.js";
27
- import { recordSessionReplacement } from "../shared/session-succession.js";
14
+ import { recordSessionReplacement, recordSessionStart } from "../shared/session-succession.js";
15
+ import { createSessionSwitchGuard } from "./session-switch.js";
16
+ import { reportSessionWarning } from "../shared/session-warnings.js";
28
17
  import { getAgentDir } from "../shared/utils.js";
29
18
  import { isStaleExtensionContextError, MODEL_ONLY_TOOL, withCachedUiContext } from "../shared/extension-context.js";
30
19
  import { currentCompletionOwnerId } from "../shared/completion-owner.js";
@@ -57,6 +46,7 @@ import { listHerdrProjectPaneRoots, restoreHerdrProjectPaneSnapshots } from "../
57
46
  import { registerSubagentRpcBridge } from "./rpc.js";
58
47
  import { clearSlashSnapshots, getSlashRenderableSnapshot, resolveSlashMessageDetails, restoreSlashFinalSnapshots } from "../slash/slash-live-state.js";
59
48
  import { resolveWaitToolConfig } from "../runs/background/subagent-wait.js";
49
+ import { DEFAULT_WAIT_TOOL_NAME, setWaitToolName } from "../shared/wait-tool-name.js";
60
50
  import { registerWaitTool } from "../runs/background/wait-tool.js";
61
51
  import { registerSubagentToolActivation } from "./tool-activation.js";
62
52
  import { recordedPromptSection, registerPinnedTool, setDeclarationPinning } from "./declaration-pinning.js";
@@ -86,6 +76,7 @@ import { listRetainedChildren } from "../runs/background/retained-children.js";
86
76
  import { DIRS, DEFAULT_ARTIFACT_CONFIG, SLASH_RESULT_TYPE, SLASH_TEXT_RESULT_TYPE, SUBAGENT_ASYNC_COMPLETE_EVENT, SUBAGENT_ASYNC_STARTED_EVENT, SUBAGENT_PROCESS_TERMINAL_EVENT, SUBAGENT_CONTROL_EVENT, SUBAGENT_STEERING_NOTICE_EVENT, WIDGET_KEY, resolveMaxSubagentSpawnsPerSession, } from "../shared/types.js";
87
77
  import { handleSubagentControlNotice, } from "./control-notices.js";
88
78
  import { showUpgradeNotice } from "./upgrade-notice.js";
79
+ import { registerSubagentLaunchTool } from "./subagent-launch-tool.js";
89
80
  const SLOW_RELOAD_PHASE_MS = 250;
90
81
  // Long enough for Pi to finish starting; loading the executor blocks the event loop for tens of ms.
91
82
  const MODULE_PRELOAD_DELAY_MS = 1_000;
@@ -109,10 +100,10 @@ function getRuntimeRegistry() {
109
100
  globalStore[RUNTIME_REGISTRY_STORE_KEY] = registry;
110
101
  return registry;
111
102
  }
112
- function logSlowPhase(label, startedAt) {
103
+ function logSlowPhase(state, label, startedAt) {
113
104
  const elapsed = Date.now() - startedAt;
114
105
  if (elapsed >= SLOW_RELOAD_PHASE_MS)
115
- console.error(`Subagent reload phase '${label}' took ${elapsed}ms.`);
106
+ reportSessionWarning(state, `Subagent reload phase '${label}' took ${elapsed}ms.`, `slow-reload-phase:${label}`);
116
107
  }
117
108
  function formatWorkflowPreflightCall(input) {
118
109
  if (input === undefined)
@@ -125,7 +116,6 @@ function formatWorkflowPreflightCall(input) {
125
116
  }
126
117
  }
127
118
  /**
128
- * Derive subagent session base directory from parent session file.
129
119
  * If parent session is ~/.pi/agent/sessions/abc123.jsonl,
130
120
  * returns ~/.pi/agent/sessions/abc123/ as the base.
131
121
  * Callers add runId to create the actual session root: abc123/{runId}/
@@ -233,6 +223,7 @@ export default function registerSubagentExtension(pi) {
233
223
  const config = loadConfig();
234
224
  setDeclarationPinning(pi, config.pinToolDeclarations !== false);
235
225
  const waitToolConfig = resolveWaitToolConfig(config.waitTool);
226
+ setWaitToolName(waitToolConfig.name ?? DEFAULT_WAIT_TOOL_NAME);
236
227
  const asyncByDefault = resolveAsyncByDefault(config);
237
228
  const fleetViewEnabled = config.fleetView !== false;
238
229
  const slashCommandsEnabled = config.enableSlashCommands !== false;
@@ -344,11 +335,13 @@ export default function registerSubagentExtension(pi) {
344
335
  return (await getExecutor()).executeScheduled(randomUUID(), params, signal, ctx);
345
336
  },
346
337
  resolveCapabilityCeiling: (sessionId) => resolveCurrentSubagentCapabilityCeiling(sessionId),
338
+ reportWarning: (message, key) => reportSessionWarning(state, message, key),
347
339
  });
348
340
  let refreshResultDelivery = () => { };
349
341
  let advertisedAgents = [];
350
342
  let advertisedContext;
351
343
  let advertisementGeneration = 0;
344
+ let advertisementLookup;
352
345
  let globalRoot = null;
353
346
  let advertisementReady = Promise.resolve();
354
347
  let notifySessionChange = () => { };
@@ -372,12 +365,14 @@ export default function registerSubagentExtension(pi) {
372
365
  };
373
366
  const beginAdvertisement = (ctx) => {
374
367
  const generation = ++advertisementGeneration;
368
+ advertisementLookup?.abort();
369
+ advertisementLookup = new AbortController();
375
370
  notifySessionChange();
376
371
  sessionChanged = new Promise((resolve) => { notifySessionChange = resolve; });
377
372
  advertisedAgents = [];
378
373
  advertisedContext = { cwd: ctx.cwd, model: ctx.model, projectTrusted: typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : undefined };
379
374
  globalRoot = null;
380
- advertisementReady = resolveGlobalNpmRoot().then((root) => {
375
+ advertisementReady = resolveGlobalNpmRoot({ signal: advertisementLookup.signal }).then((root) => {
381
376
  if (generation !== advertisementGeneration)
382
377
  return;
383
378
  globalRoot = root;
@@ -457,6 +452,13 @@ export default function registerSubagentExtension(pi) {
457
452
  resultScanLogging: config.resultScanLogging,
458
453
  });
459
454
  const { startResultWatcher, transitionResultDelivery, primeExistingResults, stopResultWatcher } = resultWatcher;
455
+ const sessionSwitchGuard = createSessionSwitchGuard({
456
+ state, asyncDirRoot: DIRS.async, resultsDir: DIRS.results,
457
+ hasPendingResults: () => owedResultRunIds.size > 0 || completionNotifier.hasPendingDelivery() || resultWatcher.hasPendingResults(),
458
+ hasPendingSupervisorRequest: supervisorChannel.hasPendingRequests,
459
+ });
460
+ pi.on("session_before_switch", (event, ctx) => sessionSwitchGuard.beforeSwitch(event.reason, ctx));
461
+ pi.on("session_before_fork", (_event, ctx) => sessionSwitchGuard.beforeSwitch("fork", ctx));
460
462
  refreshResultDelivery = resultWatcher.refreshResultDelivery;
461
463
  const asyncRetentionAbort = new AbortController();
462
464
  let asyncRetentionTimer;
@@ -723,6 +725,7 @@ export default function registerSubagentExtension(pi) {
723
725
  registerPinnedTool(pi, tool);
724
726
  // Declared with the same definition children use, so a fork's tool list equals this session's.
725
727
  registerPinnedTool(pi, topLevelSupervisorTool());
728
+ registerSubagentLaunchTool(pi);
726
729
  pi.on("before_agent_start", async (event, ctx) => {
727
730
  await waitForAdvertisement();
728
731
  const sessionId = state.currentSessionId ?? resolveCurrentSessionId(ctx.sessionManager);
@@ -887,11 +890,12 @@ export default function registerSubagentExtension(pi) {
887
890
  }
888
891
  state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(state.currentSessionId, resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(config.capacity?.abandonedSlotReleaseAfterMs) });
889
892
  };
890
- const resetSessionState = (ctx, recovering, previousSessionFile) => {
893
+ const resetSessionState = (ctx, recovering, startup, previousSessionFile) => {
891
894
  state.widgetsSuspended = false;
892
895
  state.baseCwd = ctx.cwd;
893
896
  goalTurnId = 0;
894
897
  state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
898
+ recordSessionStart(state.currentSessionId, startup);
895
899
  // Pi passes previousSessionFile only for new/resume/fork, after tearing that session down in this process.
896
900
  if (previousSessionFile)
897
901
  recordSessionReplacement(state.currentSessionId, previousSessionFile);
@@ -922,10 +926,10 @@ export default function registerSubagentExtension(pi) {
922
926
  state.lastUiContext = ctx;
923
927
  let phaseStartedAt = Date.now();
924
928
  refreshActiveAsyncCapacity();
925
- logSlowPhase("active-capacity", phaseStartedAt);
929
+ logSlowPhase(state, "active-capacity", phaseStartedAt);
926
930
  phaseStartedAt = Date.now();
927
931
  cleanupSessionArtifacts(ctx);
928
- logSlowPhase("session-artifact-cleanup", phaseStartedAt);
932
+ logSlowPhase(state, "session-artifact-cleanup", phaseStartedAt);
929
933
  state.foregroundControls.clear();
930
934
  retainedNestedRouteTracker?.clear();
931
935
  retainedNestedRouteTracker = undefined;
@@ -933,21 +937,21 @@ export default function registerSubagentExtension(pi) {
933
937
  state.lastForegroundControlId = null;
934
938
  phaseStartedAt = Date.now();
935
939
  resetJobs(ctx);
936
- logSlowPhase("reset-jobs", phaseStartedAt);
940
+ logSlowPhase(state, "reset-jobs", phaseStartedAt);
937
941
  phaseStartedAt = Date.now();
938
942
  // Runs other sessions in this folder left when their Pi died, from what this restore reads anyway.
939
943
  const interruptedElsewhere = ctx.hasUI ? createInterruptedElsewhereCollector({ currentSessionId: state.currentSessionId, cwd: ctx.cwd, now: Date.now() }) : undefined;
940
944
  restoreForegroundRunHistory(state, { resultsDir: DIRS.results, observeForeign: interruptedElsewhere?.observeForegroundRun });
941
- logSlowPhase("foreground-history", phaseStartedAt);
945
+ logSlowPhase(state, "foreground-history", phaseStartedAt);
942
946
  phaseStartedAt = Date.now();
943
947
  restoreActiveJobs(ctx, interruptedElsewhere?.observeStatus);
944
- logSlowPhase("active-job-restore", phaseStartedAt);
948
+ logSlowPhase(state, "active-job-restore", phaseStartedAt);
945
949
  phaseStartedAt = Date.now();
946
950
  // Read-only and UI-only: never sent to the model, so prompts and history are unchanged.
947
951
  if (interruptedElsewhere)
948
952
  for (const line of interruptedElsewhere.lines())
949
953
  ctx.ui.notify(line, "info");
950
- logSlowPhase("cross-session-notice", phaseStartedAt);
954
+ logSlowPhase(state, "cross-session-notice", phaseStartedAt);
951
955
  // Before any stored result is delivered, so the interrupted run's notice can name its resume.
952
956
  phaseStartedAt = Date.now();
953
957
  // Launches an earlier session start of this runtime planned and has not started belong to that session.
@@ -958,22 +962,22 @@ export default function registerSubagentExtension(pi) {
958
962
  void launchWorkflowAutoResume(entry, ctx);
959
963
  }
960
964
  }
961
- logSlowPhase("workflow-auto-resume", phaseStartedAt);
965
+ logSlowPhase(state, "workflow-auto-resume", phaseStartedAt);
962
966
  phaseStartedAt = Date.now();
963
967
  scheduledRunManager.bindSession(ctx);
964
- logSlowPhase("scheduled-runs", phaseStartedAt);
968
+ logSlowPhase(state, "scheduled-runs", phaseStartedAt);
965
969
  phaseStartedAt = Date.now();
966
970
  restoreSlashFinalSnapshots(ctx.sessionManager.getEntries());
967
- logSlowPhase("slash-snapshots", phaseStartedAt);
971
+ logSlowPhase(state, "slash-snapshots", phaseStartedAt);
968
972
  phaseStartedAt = Date.now();
969
973
  waitSubscriptionManager.restore();
970
- logSlowPhase("wait-subscriptions", phaseStartedAt);
974
+ logSlowPhase(state, "wait-subscriptions", phaseStartedAt);
971
975
  phaseStartedAt = Date.now();
972
976
  startResultWatcher();
973
- logSlowPhase("result-watcher-start", phaseStartedAt);
977
+ logSlowPhase(state, "result-watcher-start", phaseStartedAt);
974
978
  phaseStartedAt = Date.now();
975
979
  primeExistingResults({ triggerTurn: !recovering });
976
- logSlowPhase("result-prime", phaseStartedAt);
980
+ logSlowPhase(state, "result-prime", phaseStartedAt);
977
981
  fleetStatus?.setContext(ctx);
978
982
  };
979
983
  let runtimeCleaned = false;
@@ -984,6 +988,12 @@ export default function registerSubagentExtension(pi) {
984
988
  if (runtimeCleaned)
985
989
  return;
986
990
  runtimeCleaned = true;
991
+ sessionSwitchGuard.dispose();
992
+ ++advertisementGeneration;
993
+ advertisementLookup?.abort();
994
+ advertisedAgents = [];
995
+ advertisedContext = undefined;
996
+ notifySessionChange();
987
997
  // Synchronously, so a reload's new runtime finds these runs unclaimed when it scans.
988
998
  cancelPendingWorkflowAutoResumes((entry) => entry.owner === autoResumeOwner);
989
999
  programStatus.dispose(shutdownReason);
@@ -1160,7 +1170,7 @@ export default function registerSubagentExtension(pi) {
1160
1170
  startSessionMaintenance();
1161
1171
  scheduleModulePreload();
1162
1172
  const recovering = event.reason === "startup" || event.reason === "reload" || event.reason === "resume";
1163
- resetSessionState(ctx, recovering, event.previousSessionFile);
1173
+ resetSessionState(ctx, recovering, event.reason === "startup", event.previousSessionFile);
1164
1174
  releaseHostSessionLiveness();
1165
1175
  const sessionId = ctx.sessionManager.getSessionId();
1166
1176
  const sessionFile = ctx.sessionManager.getSessionFile();
@@ -1186,6 +1196,7 @@ export default function registerSubagentExtension(pi) {
1186
1196
  supervisorChannel.activateTransport();
1187
1197
  });
1188
1198
  pi.on("session_shutdown", async (event) => {
1199
+ sessionSwitchGuard.sessionShutdown(event);
1189
1200
  cancelCompactionResume();
1190
1201
  completionNotifier.sessionShutdown(event?.reason);
1191
1202
  parentWake.sessionShutdown(event?.reason);
@@ -44,6 +44,7 @@ export interface PublicSubagentExecutionParams {
44
44
  suppressRoutineResultIntercom?: unknown;
45
45
  runFanoutBudget?: unknown;
46
46
  runFanoutAdmitted?: unknown;
47
+ requireLauncher?: unknown;
47
48
  }
48
49
  export type PublicSubagentExecutionMode = "workflow" | "management";
49
50
  export type PublicSubagentExecutionNormalization<T> = {
@@ -1,4 +1,5 @@
1
1
  import { normalizeWorktreeBaseRef } from "../runs/shared/worktree.js";
2
+ import { REQUIRE_LAUNCHER_SHAPE_ERROR } from "../runs/shared/runner-launcher.js";
2
3
  const RAW_SCRIPT_FORMS = "workflow: true or a workflow script path";
3
4
  const REMOVED_WORKFLOW_SCRIPT = "workflowScript was removed; write the script in one ```js workflow block in this reply and call subagent({ workflow: true }), or pass a script file as workflow: \"./path/to/script.js\".";
4
5
  const REMOVED_WORKFLOW_SCRIPT_PATH = "workflowScriptPath was removed; pass the script file as workflow: \"./path/to/script.js\" (a workflow value containing '/' is a path).";
@@ -108,6 +109,9 @@ export function normalizePublicSubagentExecution(params, options = {}) {
108
109
  return { ok: false, error: "action must be a non-empty management/control action, or omit action and use workflow.", mode: "management" };
109
110
  }
110
111
  const normalizedAction = typeof action === "string" ? action.trim() : undefined;
112
+ if (params.requireLauncher !== undefined && (normalizedAction !== undefined || hasWorkflowInput || params.tasks !== undefined || params.chain !== undefined || params.parallel !== undefined || params.resume !== undefined)) {
113
+ return { ok: false, error: REQUIRE_LAUNCHER_SHAPE_ERROR, mode: normalizedAction !== undefined ? "management" : "workflow" };
114
+ }
111
115
  if (params.baseRef !== undefined && normalizedAction !== undefined && normalizedAction !== "resume" && normalizedAction !== "schedule.create") {
112
116
  return { ok: false, error: "baseRef is only supported for child execution, resume, and schedule.create.", mode: "management" };
113
117
  }
@@ -20,17 +20,37 @@ export function readReplyWorkflowScript(sessionManager, toolCallId) {
20
20
  continue;
21
21
  if (!message.content.some((block) => block.type === "toolCall" && block.id === toolCallId))
22
22
  continue;
23
- return scriptFromReply(message.content);
23
+ return scriptFromReply(message.content, () => earlierTurnHasJsBlock(branch, index));
24
24
  }
25
25
  return { error: "workflow: true only works from a model subagent tool call whose assistant message contains the ```js workflow block; other callers must pass a script path such as workflow: \"./script.js\"." };
26
26
  }
27
- function scriptFromReply(content) {
27
+ /** Whether an assistant message earlier in this turn (after the last user message) holds a js block. */
28
+ function earlierTurnHasJsBlock(branch, callIndex) {
29
+ for (let index = callIndex - 1; index >= 0; index--) {
30
+ const entry = branch[index];
31
+ if (entry.type !== "message")
32
+ continue;
33
+ if (entry.message?.role === "user")
34
+ return false;
35
+ if (entry.message?.role !== "assistant" || !Array.isArray(entry.message.content))
36
+ continue;
37
+ const text = entry.message.content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
38
+ const { tagged, plain } = workflowBlocks(text);
39
+ if (tagged.length > 0 || plain.length > 0)
40
+ return true;
41
+ }
42
+ return false;
43
+ }
44
+ function scriptFromReply(content, earlierBlock) {
28
45
  const replyCalls = content.filter((block) => block.type === "toolCall" && block.name === "subagent"
29
46
  && (block.arguments?.workflow === true || block.arguments?.workflow === "true")).length;
30
47
  if (replyCalls > 1)
31
48
  return { error: `This reply has ${replyCalls} subagent calls with workflow: true; a reply can carry only one. Pass other scripts as workflow file paths.` };
32
- if (!content.some((block) => block.type === "text"))
33
- return { error: `The assistant message that issued this call has no text in the session, so the reply's visible text, including any \`\`\`js workflow block, never reached it. ${SUMMARY_NOTE}` };
49
+ if (!content.some((block) => block.type === "text")) {
50
+ if (earlierBlock())
51
+ return { error: "The assistant message that issued this call has no text. A ```js block is in an earlier message of this turn, but workflow: true reads only the message that issues the call. Pass that script's source as options: { script: \"...\" } in place of workflow: true, with the call's other fields unchanged, or write the block and the call in one message." };
52
+ return { error: `The assistant message that issued this call has no text in the session, so no \`\`\`js workflow block reached it. ${SUMMARY_NOTE}` };
53
+ }
34
54
  const text = content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
35
55
  const { tagged, plain, unclosed } = workflowBlocks(text);
36
56
  if (unclosed)
@@ -1,6 +1,3 @@
1
- /**
2
- * TypeBox schemas for subagent tool parameters
3
- */
4
1
  import { Type } from "typebox";
5
2
  import type { DisabledFeatureSurface } from "../shared/disabled-features.ts";
6
3
  /** Full flat parameter shape accepted by RPC, slash, scheduled and workflow callers. */
@@ -104,6 +101,10 @@ export declare const SubagentFlatParams: Type.TObject<{
104
101
  agentScope: Type.TOptional<Type.TString>;
105
102
  cwd: Type.TOptional<Type.TString>;
106
103
  machine: Type.TOptional<Type.TString>;
104
+ requireLauncher: Type.TOptional<Type.TObject<{
105
+ name: Type.TString;
106
+ definitionDigest: Type.TString;
107
+ }>>;
107
108
  artifacts: Type.TOptional<Type.TBoolean>;
108
109
  includeProgress: Type.TOptional<Type.TBoolean>;
109
110
  share: Type.TOptional<Type.TBoolean>;
@@ -223,6 +224,10 @@ export declare const SubagentOptionParams: Type.TObject<{
223
224
  }>>;
224
225
  agentScope: Type.TOptional<Type.TString>;
225
226
  machine: Type.TOptional<Type.TString>;
227
+ requireLauncher: Type.TOptional<Type.TObject<{
228
+ name: Type.TString;
229
+ definitionDigest: Type.TString;
230
+ }>>;
226
231
  artifacts: Type.TOptional<Type.TBoolean>;
227
232
  includeProgress: Type.TOptional<Type.TBoolean>;
228
233
  share: Type.TOptional<Type.TBoolean>;
@@ -1,7 +1,5 @@
1
- /**
2
- * TypeBox schemas for subagent tool parameters
3
- */
4
1
  import { Type } from "typebox";
2
+ import { RUNNER_LAUNCHER_NAME_PATTERN } from "../shared/types.js";
5
3
  import { MAX_ARGS_BYTES, MAX_ARGS_DEPTH, MAX_ARGS_FIELDS, MAX_ARGS_ITEMS } from "../workflows/workflow-resources.js";
6
4
  function keepTopLevelParameterDescriptions(schema) {
7
5
  return pruneNestedDescriptions(schema, []);
@@ -228,6 +226,10 @@ const SubagentParamProperties = {
228
226
  agentScope: Type.Optional(Type.String({ description: "user/project/both (default); project wins collisions." })),
229
227
  cwd: Type.Optional(Type.String({ description: "Execution/project-pane directory." })),
230
228
  machine: Type.Optional(Type.String({ minLength: 1, maxLength: 128, description: "Herdr saved machine id or label (runs an external CLI agent), a Rex host named in settings (runs a Pi child), or \"local\" (a Pi child in a Rex pane here). On another machine, cwd is a directory there." })),
229
+ requireLauncher: Type.Optional(Type.Object({
230
+ name: Type.String({ pattern: RUNNER_LAUNCHER_NAME_PATTERN.source }),
231
+ definitionDigest: Type.String({ pattern: "^[0-9a-f]{64}$" }),
232
+ }, { additionalProperties: false, description: "Top-level single async launch only: refuse unless the agent runs under this launcher with this definition digest (preflight agent.definitionDigest)." })),
231
233
  artifacts: Type.Optional(Type.Boolean({ description: "Debug artifacts; default true." })),
232
234
  includeProgress: Type.Optional(Type.Boolean({ description: "Full result progress; default false." })),
233
235
  share: Type.Optional(Type.Boolean({ description: "Upload session to GitHub Gist; default false." })),
@@ -0,0 +1,25 @@
1
+ import type { ExtensionContext, SessionShutdownEvent } from "@earendil-works/pi-coding-agent";
2
+ import type { SubagentState } from "../shared/types.ts";
3
+ type SwitchReason = "new" | "resume" | "fork";
4
+ export type SessionSwitchContext = Pick<ExtensionContext, "mode" | "hasUI"> & {
5
+ ui: Pick<ExtensionContext["ui"], "select" | "notify">;
6
+ };
7
+ interface SessionSwitchDeps {
8
+ state: SubagentState;
9
+ asyncDirRoot: string;
10
+ resultsDir: string;
11
+ hasPendingResults(): boolean;
12
+ hasPendingSupervisorRequest(): boolean;
13
+ }
14
+ /**
15
+ * Asks what happens to this session's outstanding background work when a UI session switches away. Without a UI or
16
+ * outstanding work the switch proceeds and the next session inherits the work. The prompt never enters model history.
17
+ */
18
+ export declare function createSessionSwitchGuard(deps: SessionSwitchDeps): {
19
+ beforeSwitch(reason: SwitchReason, ctx: SessionSwitchContext): Promise<{
20
+ cancel: true;
21
+ } | undefined>;
22
+ sessionShutdown(event: SessionShutdownEvent): void;
23
+ dispose(): void;
24
+ };
25
+ export {};