@vicary/pi-subagents 0.84.0-1 → 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-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  5. package/bundle/{chunk-4MDR6V46.js → chunk-A7VJ5XXE.js} +190 -1177
  6. package/bundle/{chunk-LGLEH7B6.js → chunk-B3OOJJA6.js} +231 -182
  7. package/bundle/{chunk-4E7BKDTX.js → chunk-CS4O36CZ.js} +11 -156
  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-T44HVL5U.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/{chunk-F4AMYP5N.js → chunk-HS4WPO6B.js} +15 -6
  12. package/bundle/chunk-HXRB42AF.js +108 -0
  13. package/bundle/{chunk-4NIY3BE6.js → chunk-JHBQ7N2L.js} +2 -2
  14. package/bundle/{chunk-HKJLSMXV.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  16. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  17. package/bundle/{chunk-NENDSQUY.js → chunk-KZ34KQQH.js} +9 -6
  18. package/bundle/{chunk-AKOIVLA5.js → chunk-L2ENOFVZ.js} +76 -58
  19. package/bundle/{chunk-CGN2TVE7.js → chunk-LGMILZNE.js} +322 -18
  20. package/bundle/{chunk-L3WFKBEI.js → chunk-LTPH2DXH.js} +247 -153
  21. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  22. package/bundle/{chunk-PV63UFUR.js → chunk-O7CPL6H4.js} +183 -28
  23. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  24. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  25. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  26. package/bundle/{chunk-67ENPDDA.js → chunk-QZL2ZZPM.js} +22 -11
  27. package/bundle/{chunk-PALJGGYC.js → chunk-RV5OGHLO.js} +6 -3
  28. package/bundle/chunk-T5V5BRCL.js +1067 -0
  29. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  30. package/bundle/{chunk-TE4LHYHN.js → chunk-VEZMZDTW.js} +209 -93
  31. package/bundle/{chunk-X2MXCSA5.js → chunk-YZBCREP5.js} +310 -101
  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 +2 -2
  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
@@ -15,7 +15,9 @@ const MAX_PARSER_LINE_BYTES = 256 * 1024;
15
15
  const MAX_PARSER_STREAM_BYTES = 32 * 1024 * 1024;
16
16
  const MAX_PARSER_OUTPUT_BYTES = 1024 * 1024;
17
17
  const MAX_OVERSIZED_LINE_PREFIX_BYTES = 512;
18
- const MAX_SKIPPABLE_LINE_BYTES = 1024 * 1024;
18
+ // A skipped line keeps only its prefix in memory, and the stream limit still bounds the run.
19
+ // Claude Code puts a read image's base64 in its tool-result line twice.
20
+ const MAX_SKIPPABLE_LINE_BYTES = 8 * 1024 * 1024;
19
21
  const PARSER_PROGRESS_INTERVAL_MS = 100;
20
22
  export function buildExternalCliPrompt(systemInstructions, task) {
21
23
  return `<System instructions>\n${systemInstructions.trim()}\n\n<Task>\n${task}`;
@@ -196,6 +198,22 @@ export function runExternalCli(input) {
196
198
  let processTree;
197
199
  let processPid;
198
200
  let termination;
201
+ // A throwing onProcess fails the run only after the process is stopped and temp paths are removed.
202
+ let callbackFailed = false;
203
+ let callbackError;
204
+ const notifyProcess = (status) => {
205
+ try {
206
+ input.onProcess?.(status);
207
+ }
208
+ catch (error) {
209
+ if (callbackFailed)
210
+ return;
211
+ callbackFailed = true;
212
+ callbackError = error;
213
+ if (!settled && processTree && processPid !== undefined)
214
+ termination ??= terminateExternalProcessTree(processPid, processTree);
215
+ }
216
+ };
199
217
  const flushProgress = () => {
200
218
  if (!latestProgress)
201
219
  return;
@@ -217,7 +235,7 @@ export function runExternalCli(input) {
217
235
  progressTimer.unref?.();
218
236
  };
219
237
  const terminate = (reason) => {
220
- if (settled || timedOut || stopped || parserError)
238
+ if (settled || timedOut || stopped || parserError || callbackFailed)
221
239
  return;
222
240
  timedOut = reason === "timeout";
223
241
  stopped = reason === "stop";
@@ -323,7 +341,7 @@ export function runExternalCli(input) {
323
341
  stderrPath,
324
342
  ...(input.finalOutputPath ? { finalOutputPath: input.finalOutputPath } : {}),
325
343
  };
326
- input.onProcess?.(initialProcess);
344
+ notifyProcess(initialProcess);
327
345
  child.stdout.on("data", (chunk) => {
328
346
  parseChunk(chunk);
329
347
  writeBoundedLog(child.stdout, stdoutStream, chunk, stdoutLog, limits.stdoutLogBytes);
@@ -380,7 +398,7 @@ export function runExternalCli(input) {
380
398
  ...(stdoutLog.total > stdoutLog.bytes ? { stdoutTruncated: true } : {}),
381
399
  ...(stderrLog.total > stderrLog.bytes ? { stderrTruncated: true } : {}),
382
400
  };
383
- input.onProcess?.(externalProcess);
401
+ notifyProcess(externalProcess);
384
402
  const stderr = stderrTail.text().trim();
385
403
  const parserFailure = parserError?.message ?? (parserTerminal?.state === "failed" ? parserTerminal.error ?? "External CLI parser reported terminal failure." : undefined);
386
404
  const treeFailure = process.platform !== "win32" && treeProof?.state === "unknown"
@@ -415,11 +433,13 @@ export function runExternalCli(input) {
415
433
  reject(cleanupError);
416
434
  return;
417
435
  }
418
- if (streamFailure?.status === "rejected")
436
+ if (callbackFailed)
437
+ reject(callbackError);
438
+ else if (streamFailure?.status === "rejected")
419
439
  reject(streamFailure.reason);
420
440
  else
421
441
  resolve(result);
422
- })();
442
+ })().catch(reject);
423
443
  });
424
444
  });
425
445
  }
@@ -238,7 +238,8 @@ function openSshSockets(machine, options) {
238
238
  if (!path.posix.isAbsolute(remotePath))
239
239
  throw new Error("Remote socket path must be absolute.");
240
240
  const local = path.join(dir, `${name}.sock`);
241
- const child = spawn(options.sshBin ?? "ssh", [...herdrSshArgs(options.env), "-N", "-o", "StreamLocalBindUnlink=yes", "-L", `${local}:${remotePath}`, machine.target], { env: hardenedSshEnv(options.env), stdio: "ignore", windowsHide: true });
241
+ // Some sshd policies drop sessions that run no command (`ssh -N`). The remote command reads the open stdin pipe, so it ends on EOF when the connection closes; a non-tty `sleep` would outlive the forwarder.
242
+ const child = spawn(options.sshBin ?? "ssh", [...herdrSshArgs(options.env), "-o", "StreamLocalBindUnlink=yes", "-L", `${local}:${remotePath}`, machine.target, remoteShellCommand("exec cat >/dev/null")], { env: hardenedSshEnv(options.env), stdio: ["pipe", "ignore", "ignore"], windowsHide: true });
242
243
  children.add(child);
243
244
  const stop = async () => { await terminateChild(child); children.delete(child); try {
244
245
  fs.rmSync(local, { force: true });
@@ -2,7 +2,7 @@ import type { HerdrMachineReference, PlacementMachineReference } from "../../sha
2
2
  import { type HerdrForwardedConnection, type HerdrRpcClient } from "./herdr-connection.ts";
3
3
  import type { HerdrRunIdentity } from "./herdr-placed-run.ts";
4
4
  import { PlacedRunOwner, type PlacedBridgeManifest } from "./placed-run-owner.ts";
5
- import { type PlacementAgentKind, type PlacementBridgeIdentity, type PlacementEvidenceProof, type PlacementOwnedPane, type PlacementReconnectCheck, type PlacementRunState, type PlacementStartOptions } from "./placement-host.ts";
5
+ import { type PlacementAgentKind, type PlacementBridgeIdentity, type PlacementEvidenceProof, type PlacementOwnedPane, type PlacementPromptOptions, type PlacementReconnectCheck, type PlacementRunState, type PlacementStartOptions } from "./placement-host.ts";
6
6
  export interface HerdrPaneCandidate {
7
7
  endpoint: {
8
8
  session: string | null;
@@ -43,7 +43,7 @@ export declare const herdrPaneHost: {
43
43
  owned: PlacementOwnedPane;
44
44
  terminalId: string;
45
45
  }>;
46
- prompt(connection: HerdrForwardedConnection, identity: HerdrRunIdentity, text: string): Promise<void>;
46
+ prompt(connection: HerdrForwardedConnection, identity: HerdrRunIdentity, text: string, options?: PlacementPromptOptions): Promise<void>;
47
47
  subscribe(connection: HerdrForwardedConnection, paneId: string, listener: (event: unknown) => void, onDisconnect: (error: Error) => void): Promise<() => void>;
48
48
  paneEvent(event: unknown, fallback: PlacementRunState): {
49
49
  terminalId: unknown;
@@ -104,7 +104,23 @@ export const herdrPaneHost = {
104
104
  connect(machine) { return connectHerdrMachine(asHerdrMachine(machine)); },
105
105
  sessionOf(connection) { return connection.endpoint.session; },
106
106
  async launch(connection, machine, runId, runtimeDir, request, onPane, options) { const owned = await provisionHerdrOwnedPane(connection, asHerdrMachine(machine), runId, runtimeDir, request.environment); await onPane(owned); const { terminalId } = await startHerdrAgent(connection, owned, request.kind, request.name, request.args, options); return { owned, terminalId }; },
107
- async prompt(connection, identity, text) { await connection.client.call("agent.prompt", { target: identity.agentName, text }); },
107
+ async prompt(connection, identity, text, options = {}) {
108
+ // Herdr registers a started agent's name asynchronously, so a prompt right after start can be refused; a refused prompt was not delivered.
109
+ const clock = options.clock ?? { now: () => Date.now(), wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)) }, deadline = clock.now() + (options.timeoutMs ?? 5_000), pollMs = options.pollMs ?? 100;
110
+ for (;;) {
111
+ try {
112
+ await connection.client.call("agent.prompt", { target: identity.agentName, text });
113
+ return;
114
+ }
115
+ catch (error) {
116
+ if (!(error instanceof Error) || !error.message.includes("is not an active named agent") || clock.now() >= deadline)
117
+ throw error;
118
+ await clock.wait(Math.min(pollMs, deadline - clock.now()));
119
+ if (options.stopped?.())
120
+ throw new Error("Remote Pi prompt was not sent because the run was stopped.", { cause: error });
121
+ }
122
+ }
123
+ },
108
124
  subscribe(connection, paneId, listener, onDisconnect) { return connection.client.subscribe(herdrStatusSubscriptions(paneId), listener, onDisconnect); },
109
125
  paneEvent(event, fallback) { const data = event && typeof event === "object" ? event.data : undefined; return data ? { terminalId: data.terminal_id, paneId: data.pane_id, state: herdrRunState(data.agent_status, fallback) } : undefined; },
110
126
  async panes(connection) { return { endpoint: connection.endpoint, agents: snapshotAgents(parseHerdrSessionSnapshot(await connection.client.call("session.snapshot"))) }; },
@@ -7,6 +7,7 @@ import { herdrPaneHost, HerdrPlacedRunOwner } from "./herdr-pane-host.js";
7
7
  import { encodeHerdrPiFrame, HERDR_PI_MODE_ENV, HERDR_PI_PROTOCOL, HERDR_PI_RUN_ENV, HERDR_PI_RUNTIME_DIR_ENV, HerdrPiFrameDecoder, validateHerdrPiRunId } from "./herdr-pi-protocol.js";
8
8
  import { discoverPlacedBridgeManifest } from "./placed-run-owner.js";
9
9
  import { RexPlacedRunOwner } from "./rex-pane-host.js";
10
+ import { ensureSupervisorChannelDir } from "../../intercom/native-supervisor-channel.js";
10
11
  import { isRexLocalMachine } from "./rex-machine.js";
11
12
  import { PLACED_RESTORE_UNSUPPORTED } from "./herdr-machine.js";
12
13
  /** The pane half comes from the host; the bridge half (run, package, protocol, native session, evidence cursor) is host-neutral. */
@@ -136,21 +137,35 @@ export class HerdrPiSession {
136
137
  #reconnectFactory;
137
138
  #reconnectFailure;
138
139
  #replyTimer;
140
+ #repliesInFlight = new Set();
139
141
  supervisorDir;
140
142
  runtime;
141
143
  owner;
142
144
  constructor(owner, bridgeForward, bridge, requestedTools, model, runtime, initialGit) { this.owner = owner; this.bridgeForward = bridgeForward; this.bridge = bridge; this.requestedTools = requestedTools; this.model = model; this.runtime = runtime; this.supervisorDir = runtime.supervisorChannelDir; this.#initialGit = initialGit; bridge.adopt((frame) => this.#frame(frame)); if (this.supervisorDir) {
143
- this.#replyTimer = setInterval(() => { const replies = path.join(this.supervisorDir, "replies"); for (const name of fs.existsSync(replies) ? fs.readdirSync(replies) : []) {
144
- const file = path.join(replies, name);
145
- try {
146
- const value = JSON.parse(fs.readFileSync(file, "utf8"));
147
- if (typeof value.message === "string" && typeof value.requestId === "string")
148
- void this.#operation("supervisor-reply", value.message, value.requestId, typeof value.error === "string" ? value.error : undefined).then(() => fs.rmSync(file, { force: true }));
149
- }
150
- catch { }
151
- } }, 50);
145
+ this.#replyTimer = setInterval(() => this.#deliverSupervisorReplies(this.supervisorDir), 50);
152
146
  this.#replyTimer.unref?.();
153
147
  } }
148
+ // Runs on a timer, where a throw or an unhandled rejection exits Pi. A reply that can't be read or delivered stays
149
+ // on disk for the next tick, once its earlier delivery has settled; a lost transport reaches the session through the
150
+ // bridge failure.
151
+ #deliverSupervisorReplies(supervisorDir) { const replies = path.join(supervisorDir, "replies"); let names; try {
152
+ names = fs.existsSync(replies) ? fs.readdirSync(replies) : [];
153
+ }
154
+ catch {
155
+ return;
156
+ } for (const name of names) {
157
+ const file = path.join(replies, name);
158
+ if (this.#repliesInFlight.has(file))
159
+ continue;
160
+ try {
161
+ const value = JSON.parse(fs.readFileSync(file, "utf8"));
162
+ if (typeof value.message === "string" && typeof value.requestId === "string") {
163
+ this.#repliesInFlight.add(file);
164
+ void this.#operation("supervisor-reply", value.message, value.requestId, typeof value.error === "string" ? value.error : undefined).then(() => fs.rmSync(file, { force: true })).catch(() => { }).finally(() => this.#repliesInFlight.delete(file));
165
+ }
166
+ }
167
+ catch { }
168
+ } }
154
169
  get host() { return this.owner.host; }
155
170
  get identity() { return this.owner.identity; }
156
171
  set identity(value) { this.owner.identity = value; }
@@ -218,23 +233,34 @@ export class HerdrPiSession {
218
233
  for (const listener of this.#listeners)
219
234
  listener({ type: "agent_settled" });
220
235
  } }
221
- #relaySupervisor(frame) { if (!this.supervisorDir || typeof frame.requestId !== "string")
222
- return; const reason = frame.reason; if (reason !== "need_decision" && reason !== "interview_request" && reason !== "progress_update")
223
- return; const createdAt = Date.now(); const file = path.join(this.supervisorDir, "requests", `${path.basename(frame.requestId)}.json`); const request = { type: "subagent.supervisor.request", id: frame.requestId, createdAt, ...(reason !== "progress_update" ? { expiresAt: createdAt + 10 * 60_000 } : {}), reason, message: typeof frame.message === "string" ? frame.message : "", ...(frame.interview && typeof frame.interview === "object" ? { interview: frame.interview } : {}), expectsReply: reason !== "progress_update", runId: this.runtime.runId ?? this.identity.runId, agent: this.runtime.agent ?? "remote", childIndex: this.runtime.childIndex ?? 0, orchestratorSessionId: this.runtime.orchestratorSessionId }; try {
224
- fs.writeFileSync(file, JSON.stringify(request), { mode: 0o600, flag: "wx" });
236
+ #relaySupervisor(frame) {
237
+ if (!this.supervisorDir || typeof frame.requestId !== "string")
238
+ return;
239
+ const reason = frame.reason;
240
+ if (reason !== "need_decision" && reason !== "interview_request" && reason !== "progress_update")
241
+ return;
242
+ const createdAt = Date.now();
243
+ const file = path.join(this.supervisorDir, "requests", `${path.basename(frame.requestId)}.json`);
244
+ const request = { type: "subagent.supervisor.request", id: frame.requestId, createdAt, ...(reason !== "progress_update" ? { expiresAt: createdAt + 10 * 60_000 } : {}), reason, message: typeof frame.message === "string" ? frame.message : "", ...(frame.interview && typeof frame.interview === "object" ? { interview: frame.interview } : {}), expectsReply: reason !== "progress_update", runId: this.runtime.runId ?? this.identity.runId, agent: this.runtime.agent ?? "remote", childIndex: this.runtime.childIndex ?? 0, orchestratorSessionId: this.runtime.orchestratorSessionId };
245
+ // The parent's stale-channel cleanup removes an idle channel's empty directories after a minute.
246
+ ensureSupervisorChannelDir(this.supervisorDir);
247
+ try {
248
+ fs.writeFileSync(file, JSON.stringify(request), { mode: 0o600, flag: "wx" });
249
+ }
250
+ catch (error) {
251
+ if (error.code !== "EEXIST")
252
+ throw error;
253
+ const existing = JSON.parse(fs.readFileSync(file, "utf8"));
254
+ if (existing.id !== frame.requestId || existing.reason !== reason)
255
+ throw new Error("Supervisor relay identity changed during replay.");
256
+ }
257
+ if (reason === "progress_update")
258
+ this.bridge.supervisorDelivered(frame.requestId);
225
259
  }
226
- catch (error) {
227
- if (error.code !== "EEXIST")
228
- throw error;
229
- const existing = JSON.parse(fs.readFileSync(file, "utf8"));
230
- if (existing.id !== frame.requestId || existing.reason !== reason)
231
- throw new Error("Supervisor relay identity changed during replay.");
232
- } if (reason === "progress_update")
233
- this.bridge.supervisorDelivered(frame.requestId); }
234
260
  async #operation(operation, text, supervisorId, supervisorError) { const requestId = `${++this.#sequence}_${randomBytes(5).toString("hex")}`; let completion = Promise.resolve(); if (operation === "prompt")
235
261
  completion = new Promise((resolve, reject) => this.#operations.set(requestId, { resolve, reject, accepted: false, settled: false })); try {
236
262
  await Promise.race([this.bridge.prepare(requestId, operation, text, supervisorId, supervisorError), this.bridge.failure]);
237
- await this.host.prompt(this.connection, this.identity, `/pi-subagents-bridge ${requestId}`);
263
+ await this.host.prompt(this.connection, this.identity, `/pi-subagents-bridge ${requestId}`, operation === "abort" ? {} : { stopped: () => this.#aborted || this.#disposed });
238
264
  await completion;
239
265
  }
240
266
  catch (error) {
@@ -8,7 +8,6 @@ export declare const WORKFLOW_LANE_OUTPUT_PATHS_MAX = 10;
8
8
  export declare const WORKTREE_STATUS_PATH_MAX_BYTES = 4096;
9
9
  export declare const WORKTREE_STATUS_BRANCH_MAX_BYTES = 256;
10
10
  export declare const WORKTREE_STATUS_NAMING_LABEL_MAX_BYTES = 256;
11
- /** Normalize and validate launch-declared lane metadata. */
12
11
  export declare function normalizeWorkflowLaneMetadata(value: unknown, label?: string): WorkflowLaneMetadata | undefined;
13
12
  export declare function assertWorkflowLaneKey(lane: WorkflowLaneMetadata | undefined, workflowKey: string | undefined, label?: string): void;
14
13
  export interface WorktreeStatusReference {
@@ -43,7 +43,6 @@ function boundedStringArray(value, label, maxItems, maxBytes) {
43
43
  return boundedNonEmptyString(entry, `${label}[${index}]`, maxBytes);
44
44
  });
45
45
  }
46
- /** Normalize and validate launch-declared lane metadata. */
47
46
  export function normalizeWorkflowLaneMetadata(value, label = "lane") {
48
47
  if (value === undefined)
49
48
  return undefined;
@@ -1,6 +1,13 @@
1
1
  const BUILTIN_TOOL_NAMES = new Set(["read", "bash", "edit", "write", "grep", "find", "ls", "mcp"]);
2
2
  export function normalizeMcpDirectToolSelectors(selectors) {
3
- return [...new Set((selectors ?? []).map((selector) => selector.replace(/\/+$/, "")).filter(Boolean))];
3
+ return [...new Set((selectors ?? []).map(trimTrailingSlashes).filter(Boolean))];
4
+ }
5
+ /** A `/+$/` replace rescans the selector from every index when the string ends in anything else. */
6
+ function trimTrailingSlashes(selector) {
7
+ let end = selector.length;
8
+ while (end > 0 && selector[end - 1] === "/")
9
+ end -= 1;
10
+ return selector.slice(0, end);
4
11
  }
5
12
  export function parseMcpDirectToolSelectors(selectors) {
6
13
  const servers = new Set();
@@ -2,7 +2,6 @@ export interface ChildModelResolutionDiagnostic {
2
2
  agent?: string;
3
3
  model?: string;
4
4
  host?: "parent" | "runner";
5
- /** The launch's resolved capability ceiling, when one is active. */
6
5
  capabilityCeiling?: {
7
6
  denyExtensions: boolean;
8
7
  sources?: readonly string[];
@@ -12,7 +12,6 @@ export { splitThinkingSuffix };
12
12
  * to, so the virtual selection's provider/id is compared exactly with the launch candidate instead.
13
13
  */
14
14
  export declare function formatSubagentModelVerificationError(expectedModel: string, observedModel: string, availableModels: AvailableModelInfo[] | undefined, modelResponseAliases?: Record<string, string[]>, observedVirtualModel?: string): string | undefined;
15
- /** Sentinel model value requesting that a subagent inherit the parent session's model. */
16
15
  export declare const INHERIT_MODEL = "inherit";
17
16
  /** Minimal shape of the parent session's in-memory model (`ctx.model`). */
18
17
  export interface ParentModel {
@@ -56,6 +55,8 @@ export declare function fuzzyResolveModel(baseModel: string, availableModels: Av
56
55
  * query.
57
56
  */
58
57
  export declare function resolveModelCandidate(model: string | undefined, availableModels: AvailableModelInfo[] | undefined, preferredProvider?: string): string | undefined;
58
+ /** A configured pin that launch refuses because the registry cannot resolve it. An empty registry checks nothing. */
59
+ export declare function isUnavailableSubagentModel(model: string | undefined, availableModels: AvailableModelInfo[] | undefined, preferredProvider?: string): boolean;
59
60
  export interface ResolveSubagentModelOverrideOptions {
60
61
  /** When set with `enforce: true`, out-of-scope models are rejected. */
61
62
  scope?: ModelScopeCheckRule | ModelScopeCheckRule[];
@@ -90,7 +91,6 @@ export interface ResolveModelSelectionOptions {
90
91
  onWarn?: (violation: ModelScopeViolation) => void;
91
92
  /** The primary model came from the running parent session, not configuration. */
92
93
  primaryModelFromParent?: boolean;
93
- /** How the model was selected. */
94
94
  origin?: ModelOrigin;
95
95
  }
96
96
  export declare function resolveModelOrigin(input: {
@@ -31,7 +31,6 @@ export function formatSubagentModelVerificationError(expectedModel, observedMode
31
31
  }
32
32
  return `model_verification_failed: native Pi child reported a different model than the launch candidate. Expected '${expectedModel}' but observed '${observedModel}'. If you have independently verified this response ID identifies the requested model, declare the exact mapping in modelResponseAliases in ~/.pi/agent/extensions/subagent/config.json (see docs/configuration.md#modelresponsealiases). Use the resolved provider/model ID without its thinking suffix as the key. This leaves the outgoing request unchanged. Configuration changes affect new independent native runs; resumed native runs retain their launch-time declaration. External CLI adapters do not use this setting.`;
33
33
  }
34
- /** Sentinel model value requesting that a subagent inherit the parent session's model. */
35
34
  export const INHERIT_MODEL = "inherit";
36
35
  export function normalizeParentModel(model) {
37
36
  if (!model || typeof model !== "object")
@@ -257,6 +256,13 @@ function closestModelCandidates(model, availableModels) {
257
256
  .slice(0, MAX_MODEL_CANDIDATES)
258
257
  .map((entry) => `${entry.fullId}${thinkingSuffix}`);
259
258
  }
259
+ /** A configured pin that launch refuses because the registry cannot resolve it. An empty registry checks nothing. */
260
+ export function isUnavailableSubagentModel(model, availableModels, preferredProvider) {
261
+ const trimmed = model?.trim();
262
+ if (!trimmed || trimmed === INHERIT_MODEL || !availableModels?.length)
263
+ return false;
264
+ return resolveSubagentModelCandidate(trimmed, availableModels, preferredProvider) === undefined;
265
+ }
260
266
  function resolveRequiredSubagentModelCandidate(model, availableModels, preferredProvider) {
261
267
  const resolved = resolveSubagentModelCandidate(model, availableModels, preferredProvider);
262
268
  if (resolved)
@@ -8,9 +8,6 @@
8
8
  * inherited from agent frontmatter / `defaultModel` / the parent session only
9
9
  * emits a warning so existing configurations keep working. Optional strict
10
10
  * enforcement makes inherited models hard errors too.
11
- *
12
- * The decision logic ({@link checkModelScope}) is a pure function of its
13
- * inputs so it can be unit-tested without touching the filesystem or config.
14
11
  */
15
12
  export interface ModelScopeRule {
16
13
  enforce?: boolean;
@@ -60,8 +57,7 @@ export declare function resolveModelScopesForAgent(config: ModelScopeConfig | un
60
57
  } | undefined, scopedModelIds?: readonly string[]): ResolvedModelScope[];
61
58
  /**
62
59
  * Validate and normalize a raw `subagents.modelScope` value from settings.
63
- * Throws a descriptive error for malformed configs (matching the surrounding
64
- * settings-parsing style). Returns `undefined` when the field is absent.
60
+ * Throws a descriptive error for malformed configs. Returns `undefined` when the field is absent.
65
61
  */
66
62
  export declare function parseModelScopeConfig(value: unknown, meta: {
67
63
  filePath: string;
@@ -8,9 +8,6 @@
8
8
  * inherited from agent frontmatter / `defaultModel` / the parent session only
9
9
  * emits a warning so existing configurations keep working. Optional strict
10
10
  * enforcement makes inherited models hard errors too.
11
- *
12
- * The decision logic ({@link checkModelScope}) is a pure function of its
13
- * inputs so it can be unit-tested without touching the filesystem or config.
14
11
  */
15
12
  import { splitKnownThinkingSuffix } from "../../shared/model-info.js";
16
13
  export const SCOPED_PATTERN = "scoped";
@@ -140,8 +137,7 @@ export function resolveModelScopesForAgent(config, agentName, parentModel, scope
140
137
  }
141
138
  /**
142
139
  * Validate and normalize a raw `subagents.modelScope` value from settings.
143
- * Throws a descriptive error for malformed configs (matching the surrounding
144
- * settings-parsing style). Returns `undefined` when the field is absent.
140
+ * Throws a descriptive error for malformed configs. Returns `undefined` when the field is absent.
145
141
  */
146
142
  export function parseModelScopeConfig(value, meta) {
147
143
  if (value === undefined)
@@ -1,6 +1,6 @@
1
1
  import type { ArtifactPaths, TimeoutRecoveryProjection, TimeoutRecoverySummary, TrackedMutationEvidence, TrackedMutationSnapshot } from "../../shared/types.ts";
2
2
  export declare function snapshotTrackedMutations(cwd: string): TrackedMutationSnapshot;
3
- export declare function collectTrackedMutationEvidence(snapshot: TrackedMutationSnapshot, cwd?: string): TrackedMutationEvidence;
3
+ export declare function collectTrackedMutationEvidence(snapshot: TrackedMutationSnapshot, cwd?: string): Promise<TrackedMutationEvidence>;
4
4
  /** Keep status and completion details to bounded routing evidence, not raw output or effects. */
5
5
  export declare function projectTimeoutRecovery(value: unknown): TimeoutRecoveryProjection | undefined;
6
6
  /** Render only the bounded recovery route needed by a parent/operator. */
@@ -1,8 +1,9 @@
1
- import { execFileSync } from "node:child_process";
1
+ import { execFile, execFileSync } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
3
  import * as fs from "node:fs";
4
4
  import * as os from "node:os";
5
5
  import * as path from "node:path";
6
+ import { promisify } from "node:util";
6
7
  const MAX_TRACKED_PATHS = 500;
7
8
  const MAX_HASH_BYTES = 1024 * 1024;
8
9
  const MAX_TIMEOUT_FILES = 20;
@@ -13,6 +14,32 @@ function gitArguments(args) {
13
14
  function gitOutput(cwd, args, maxBuffer = MAX_HASH_BYTES) {
14
15
  return execFileSync("git", gitArguments(args), { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], maxBuffer, windowsHide: true });
15
16
  }
17
+ const execFileAsync = promisify(execFile);
18
+ /** The collection path runs while sibling children settle, so git runs off the event loop. */
19
+ async function gitOutputAsync(cwd, args) {
20
+ return (await execFileAsync("git", gitArguments(args), { cwd, encoding: "utf-8", maxBuffer: MAX_HASH_BYTES, windowsHide: true })).stdout;
21
+ }
22
+ /** Yields to the event loop every 2 MiB so hashing a large diff does not stall other work. */
23
+ async function hashFileAsync(diffPath) {
24
+ const hash = createHash("sha256");
25
+ const fd = fs.openSync(diffPath, "r");
26
+ try {
27
+ const buffer = Buffer.alloc(64 * 1024);
28
+ let chunks = 0;
29
+ for (;;) {
30
+ const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, null);
31
+ if (bytesRead === 0)
32
+ break;
33
+ hash.update(bytesRead === buffer.length ? buffer : buffer.subarray(0, bytesRead));
34
+ if (++chunks % 32 === 0)
35
+ await new Promise((resolve) => setImmediate(resolve));
36
+ }
37
+ }
38
+ finally {
39
+ fs.closeSync(fd);
40
+ }
41
+ return hash.digest("hex");
42
+ }
16
43
  function splitNul(output) {
17
44
  return output.split("\0").filter((part) => part.length > 0);
18
45
  }
@@ -41,8 +68,9 @@ function hashLargeDiff(cwd, relativePath) {
41
68
  fs.rmSync(tempDir, { recursive: true, force: true });
42
69
  }
43
70
  }
44
- function listChangedTrackedFiles(cwd) {
45
- const paths = splitNul(gitOutput(cwd, ["diff", "--no-ext-diff", "--name-only", "-z", "HEAD", "--"], MAX_HASH_BYTES));
71
+ const CHANGED_FILES_ARGS = ["diff", "--no-ext-diff", "--name-only", "-z", "HEAD", "--"];
72
+ function changedTrackedFiles(nameOnlyOutput) {
73
+ const paths = splitNul(nameOnlyOutput);
46
74
  return { paths: paths.slice(0, MAX_TRACKED_PATHS), truncated: paths.length > MAX_TRACKED_PATHS };
47
75
  }
48
76
  function fingerprintPath(cwd, relativePath) {
@@ -61,7 +89,7 @@ function sameFingerprint(left, right) {
61
89
  }
62
90
  export function snapshotTrackedMutations(cwd) {
63
91
  try {
64
- const changed = listChangedTrackedFiles(cwd);
92
+ const changed = changedTrackedFiles(gitOutput(cwd, CHANGED_FILES_ARGS));
65
93
  const fingerprints = {};
66
94
  for (const file of changed.paths)
67
95
  fingerprints[file] = fingerprintPath(cwd, file);
@@ -71,12 +99,29 @@ export function snapshotTrackedMutations(cwd) {
71
99
  return { source: "tracked-files", trackedOnly: true, cwd, dirtyFiles: [], fingerprints: {}, unavailable: error instanceof Error ? error.message : String(error) };
72
100
  }
73
101
  }
74
- export function collectTrackedMutationEvidence(snapshot, cwd = snapshot.cwd) {
102
+ async function fingerprintPathAsync(cwd, relativePath) {
103
+ try {
104
+ const diff = await gitOutputAsync(cwd, ["diff", "--no-ext-diff", "--binary", "HEAD", "--", relativePath]);
105
+ return { kind: "diff", digest: createHash("sha256").update(diff).digest("hex") };
106
+ }
107
+ catch {
108
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-mutation-evidence-"));
109
+ try {
110
+ const diffPath = path.join(tempDir, "diff.bin");
111
+ await gitOutputAsync(cwd, ["diff", "--no-ext-diff", "--binary", `--output=${diffPath}`, "HEAD", "--", relativePath]);
112
+ return { kind: "diff", digest: await hashFileAsync(diffPath) };
113
+ }
114
+ finally {
115
+ fs.rmSync(tempDir, { recursive: true, force: true });
116
+ }
117
+ }
118
+ }
119
+ export async function collectTrackedMutationEvidence(snapshot, cwd = snapshot.cwd) {
75
120
  if (snapshot.unavailable) {
76
121
  return { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: false, unavailable: snapshot.unavailable };
77
122
  }
78
123
  try {
79
- const current = listChangedTrackedFiles(cwd);
124
+ const current = changedTrackedFiles(await gitOutputAsync(cwd, CHANGED_FILES_ARGS));
80
125
  const startDirty = new Set(snapshot.dirtyFiles);
81
126
  const candidates = new Set([...snapshot.dirtyFiles, ...current.paths]);
82
127
  const changedFiles = [];
@@ -86,7 +131,7 @@ export function collectTrackedMutationEvidence(snapshot, cwd = snapshot.cwd) {
86
131
  changedFiles.push(file);
87
132
  continue;
88
133
  }
89
- if (!sameFingerprint(snapshot.fingerprints[file], fingerprintPath(cwd, file)))
134
+ if (!sameFingerprint(snapshot.fingerprints[file], await fingerprintPathAsync(cwd, file)))
90
135
  changedFiles.push(file);
91
136
  }
92
137
  changedFiles.sort();
@@ -87,6 +87,7 @@ export interface NestedRunResolutionScope {
87
87
  parentStepIndex?: number;
88
88
  };
89
89
  }
90
+ export declare function collectNestedRuns(children: NestedRunSummary[] | undefined, output?: NestedRunSummary[]): NestedRunSummary[];
90
91
  export declare function findNestedRunMatchesById(id: string, options?: {
91
92
  prefix?: boolean;
92
93
  scope?: NestedRunResolutionScope;
@@ -564,7 +564,7 @@ export function retainNestedLookupRoute(state, route, sessionId) {
564
564
  }
565
565
  state.retainedNestedLookupRoutes.routes.set(route.rootRunId, route);
566
566
  }
567
- function collectNestedRuns(children, output = []) {
567
+ export function collectNestedRuns(children, output = []) {
568
568
  for (const child of children ?? []) {
569
569
  output.push(child);
570
570
  collectNestedRuns(child.children, output);
@@ -22,7 +22,6 @@ export interface RunnerSubagentStep {
22
22
  requestId: string;
23
23
  requestDigest: string;
24
24
  };
25
- /** Resolved launch context for this child. */
26
25
  context?: "fresh" | "fork";
27
26
  importAsyncRoot?: {
28
27
  runId: string;
@@ -1,6 +1,8 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
- const INTERNAL_TOOLS = new Set(["contact_supervisor", "intercom", "bg_wait", "structured_output"]);
3
+ import { DEFAULT_WAIT_TOOL_NAME, waitToolName } from "../../shared/wait-tool-name.js";
4
+ const COORDINATION_TOOLS = new Set(["contact_supervisor", "intercom", "structured_output"]);
5
+ const isInternalTool = (tool) => COORDINATION_TOOLS.has(tool) || tool === waitToolName();
4
6
  const DECISIONS = new Set(["allow", "ask", "deny"]);
5
7
  const MAX_POLICY_BYTES = 16 * 1024;
6
8
  const MAX_PREVIEW_BYTES = 2048;
@@ -20,7 +22,7 @@ export function validatePermissionRules(value, label) {
20
22
  throw new Error(`${label} contains an empty tool name.`);
21
23
  if (tool === "bash")
22
24
  throw new Error(`${label}.bash is unsupported; pi-subagents leaves bash policy to pi-guard.`);
23
- if (INTERNAL_TOOLS.has(tool))
25
+ if (isInternalTool(tool) || tool === DEFAULT_WAIT_TOOL_NAME)
24
26
  throw new Error(`${label}.${tool} is reserved for child coordination and cannot be gated.`);
25
27
  if (!DECISIONS.has(decision))
26
28
  throw new Error(`${label}.${tool} must be allow, ask, or deny.`);
@@ -47,7 +49,7 @@ export function resolvePermissionRules(globalConfig, agentRules) {
47
49
  return Object.keys(merged).length ? merged : undefined;
48
50
  }
49
51
  export function permissionDecision(rules, toolName) {
50
- if (toolName === "bash" || INTERNAL_TOOLS.has(toolName))
52
+ if (toolName === "bash" || isInternalTool(toolName))
51
53
  return "allow";
52
54
  return rules?.[toolName] ?? "allow";
53
55
  }
@@ -39,6 +39,10 @@ export interface PlacementStartOptions {
39
39
  wait(ms: number): Promise<void>;
40
40
  };
41
41
  }
42
+ /** `stopped` ends a pending prompt retry once the run is aborted or disposed, so a refused prompt is never sent after that. */
43
+ export interface PlacementPromptOptions extends PlacementStartOptions {
44
+ stopped?: () => boolean;
45
+ }
42
46
  /** What to start in a new pane; the pane is created in the machine's cwd with this environment. */
43
47
  export interface PlacementLaunchRequest {
44
48
  kind: PlacementAgentKind;
@@ -81,7 +85,7 @@ export interface PlacementPaneHost<C extends PlacementSockets = PlacementSockets
81
85
  owned: PlacementOwnedPane;
82
86
  terminalId: string;
83
87
  }>;
84
- prompt(connection: C, identity: HerdrRunIdentity, text: string): Promise<void>;
88
+ prompt(connection: C, identity: HerdrRunIdentity, text: string, options?: PlacementPromptOptions): Promise<void>;
85
89
  subscribe(connection: C, paneId: string, listener: (event: unknown) => void, onDisconnect: (error: Error) => void): Promise<() => void>;
86
90
  paneEvent(event: unknown, fallback: PlacementRunState): {
87
91
  terminalId: unknown;
@@ -51,7 +51,6 @@ export declare const rexPaneHost: {
51
51
  reconcile: typeof reconcileRexPlacedRun;
52
52
  closeOwnedPane: typeof closeOwnedRexPane;
53
53
  };
54
- /** The placed-run owner bound to Rex and the pane machine's access. */
55
54
  export declare class RexPlacedRunOwner extends PlacedRunOwner<RexConnection, RexMachineReference> {
56
55
  private constructor();
57
56
  /** A Rex SSH owner's machine carries the resolved remote cwd, and its host reconnects only to the session recorded here. */
@@ -40,7 +40,6 @@ function requireRexSuccess(result, what) {
40
40
  if (result.status !== 0)
41
41
  throw new Error(`Rex ${what} exited with code ${result.status}: ${result.stderr.trim().slice(0, 512)}`);
42
42
  }
43
- /** Parses rex's JSON output against its schema; undefined when the shape does not match. */
44
43
  function parseRexJson(text, validator, what) {
45
44
  let value;
46
45
  try {
@@ -284,7 +283,6 @@ function removeRexRuntimeDir(access, runtimeDir) {
284
283
  throw error;
285
284
  }
286
285
  }
287
- /** The placed-run owner bound to Rex and the pane machine's access. */
288
286
  export class RexPlacedRunOwner extends PlacedRunOwner {
289
287
  constructor(machine, runId, runtimeDir, connection, access, host) { super(machine, runId, runtimeDir, connection, host, access, () => removeRexRuntimeDir(access, runtimeDir)); }
290
288
  /** A Rex SSH owner's machine carries the resolved remote cwd, and its host reconnects only to the session recorded here. */
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The parent-owned folder for a run's relaunch records: `async-subagent-launches/<id>/`, beside the
3
+ * runs root that holds the run folder. A runner launcher that isolates a run binds only the run's own
4
+ * folder, so the run cannot rewrite what a later resume starts or under which identity.
5
+ * Callers pass a runs root they know (never one derived from a requested path), because a run can
6
+ * build a runs-shaped tree inside its own folder.
7
+ * A nested run's records stay in its root run's folder (`nested-subagent-runs/<root>/.launches/<id>/`):
8
+ * the child runner that started it writes them, so they add no isolation, and a folder shared by every
9
+ * root run would only mix their records.
10
+ */
11
+ export declare function runLaunchDir(runsRoot: string, runId: string): string;
12
+ export declare function recoveryDescriptorPath(runsRoot: string, runId: string): string;
@@ -0,0 +1,21 @@
1
+ import * as path from "node:path";
2
+ /**
3
+ * The parent-owned folder for a run's relaunch records: `async-subagent-launches/<id>/`, beside the
4
+ * runs root that holds the run folder. A runner launcher that isolates a run binds only the run's own
5
+ * folder, so the run cannot rewrite what a later resume starts or under which identity.
6
+ * Callers pass a runs root they know (never one derived from a requested path), because a run can
7
+ * build a runs-shaped tree inside its own folder.
8
+ * A nested run's records stay in its root run's folder (`nested-subagent-runs/<root>/.launches/<id>/`):
9
+ * the child runner that started it writes them, so they add no isolation, and a folder shared by every
10
+ * root run would only mix their records.
11
+ */
12
+ export function runLaunchDir(runsRoot, runId) {
13
+ if (!runId || runId !== path.basename(runId) || runId === "." || runId === "..")
14
+ throw new Error(`Invalid run id for a launch folder: '${runId}'.`);
15
+ if (path.basename(path.dirname(runsRoot)) === "nested-subagent-runs")
16
+ return path.join(runsRoot, ".launches", runId);
17
+ return path.join(path.dirname(runsRoot), "async-subagent-launches", runId);
18
+ }
19
+ export function recoveryDescriptorPath(runsRoot, runId) {
20
+ return path.join(runLaunchDir(runsRoot, runId), "recovery-descriptor.json");
21
+ }