@vicary/pi-subagents 0.88.1 → 0.89.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 (88) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-7OX6O7DQ.js → chunk-443LPCRI.js} +5 -5
  5. package/bundle/{chunk-4QFZZV3O.js → chunk-4AL6LDBY.js} +3 -1
  6. package/bundle/{chunk-6CG2VAG4.js → chunk-4ALRHKGE.js} +1 -1
  7. package/bundle/{chunk-4ZQBZDF3.js → chunk-6JD4XCA4.js} +76 -18
  8. package/bundle/{chunk-CGWNA6EJ.js → chunk-7JLNWAMO.js} +21 -21
  9. package/bundle/{chunk-LV3CPYXJ.js → chunk-7W2IQFP4.js} +4 -4
  10. package/bundle/{chunk-W6HIYD2Z.js → chunk-A3INCQ6Z.js} +1 -1
  11. package/bundle/{chunk-IYT7X46U.js → chunk-CFIYO2IV.js} +5 -5
  12. package/bundle/{chunk-CYKNHFXB.js → chunk-EPMRDKQT.js} +1 -1
  13. package/bundle/{chunk-RMZAAXIR.js → chunk-ETDE2VYK.js} +2 -2
  14. package/bundle/{chunk-4MVDMA5C.js → chunk-GHJ6BH5U.js} +13 -7
  15. package/bundle/{chunk-PYKBTBY6.js → chunk-HSHLPYCQ.js} +9 -9
  16. package/bundle/{chunk-D32H53HM.js → chunk-HZDLR73C.js} +1 -1
  17. package/bundle/{chunk-2DIEL4WG.js → chunk-JFACGAJT.js} +2 -2
  18. package/bundle/{chunk-L4YY2TOE.js → chunk-JRO2CU4D.js} +1 -1
  19. package/bundle/{chunk-KXW62VBU.js → chunk-KOLLMZ2X.js} +1 -1
  20. package/bundle/{chunk-AZPP3G4N.js → chunk-LEPIY76E.js} +34 -5
  21. package/bundle/{chunk-BKISQ5CJ.js → chunk-MJHQIUU7.js} +56 -34
  22. package/bundle/{chunk-47ZN7NKR.js → chunk-NONHDYXE.js} +1 -1
  23. package/bundle/{chunk-DSHQWGHO.js → chunk-NQ26PJSQ.js} +96 -96
  24. package/bundle/{chunk-2HKPEANZ.js → chunk-OVBUEVOT.js} +26 -15
  25. package/bundle/{chunk-JQTHG2ID.js → chunk-PFZZMVD5.js} +74 -31
  26. package/bundle/{chunk-YDZ7BZD5.js → chunk-S77ZKDLS.js} +1 -1
  27. package/bundle/{chunk-CPSUJHZE.js → chunk-SLLZJ5EC.js} +39 -10
  28. package/bundle/{chunk-V7SZMS6W.js → chunk-SWL2EITY.js} +2 -2
  29. package/bundle/{chunk-XIA5GSEU.js → chunk-UQT2EQ4U.js} +2 -2
  30. package/bundle/{chunk-5EMPFFO4.js → chunk-WW6GQBBS.js} +4 -4
  31. package/bundle/{chunk-GDR2ILWY.js → chunk-ZSCIHMUI.js} +50 -22
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +2 -2
  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 +10 -4
  38. package/docs/configuration.md +2 -0
  39. package/docs/extension-api.md +1 -1
  40. package/docs/tool-reference.md +1 -1
  41. package/docs/workflows.md +5 -3
  42. package/package.json +2 -2
  43. package/src/extension/herdr-pi-bridge.js +78 -22
  44. package/src/extension/schemas.js +1 -1
  45. package/src/extension/subagent-options.js +5 -0
  46. package/src/intercom/result-intercom.js +3 -2
  47. package/src/runs/background/notify.d.ts +3 -0
  48. package/src/runs/background/notify.js +7 -2
  49. package/src/runs/background/run-status.js +3 -2
  50. package/src/runs/background/runner-child-launch.js +1 -0
  51. package/src/runs/background/subagent-runner.js +11 -8
  52. package/src/runs/foreground/execution.js +8 -7
  53. package/src/runs/foreground/subagent-executor.js +31 -5
  54. package/src/runs/shared/child-launch.d.ts +2 -0
  55. package/src/runs/shared/child-launch.js +1 -1
  56. package/src/runs/shared/child-session.d.ts +2 -1
  57. package/src/runs/shared/herdr-connection.d.ts +6 -0
  58. package/src/runs/shared/herdr-connection.js +11 -1
  59. package/src/runs/shared/herdr-machine.d.ts +2 -2
  60. package/src/runs/shared/herdr-machine.js +47 -22
  61. package/src/runs/shared/herdr-pane-host.d.ts +7 -19
  62. package/src/runs/shared/herdr-pane-host.js +48 -33
  63. package/src/runs/shared/herdr-pi-protocol.d.ts +1 -0
  64. package/src/runs/shared/herdr-pi-protocol.js +3 -2
  65. package/src/runs/shared/herdr-placed-run.d.ts +2 -12
  66. package/src/runs/shared/herdr-placed-run.js +10 -8
  67. package/src/runs/shared/kept-branch-text.d.ts +8 -0
  68. package/src/runs/shared/kept-branch-text.js +24 -0
  69. package/src/runs/shared/local-machine-access.d.ts +4 -1
  70. package/src/runs/shared/local-machine-access.js +6 -3
  71. package/src/runs/shared/mutation-evidence.d.ts +7 -1
  72. package/src/runs/shared/mutation-evidence.js +18 -2
  73. package/src/runs/shared/parallel-handoff.js +19 -7
  74. package/src/runs/shared/placed-run-owner.d.ts +4 -2
  75. package/src/runs/shared/placed-run-owner.js +15 -7
  76. package/src/runs/shared/rex-machine.d.ts +7 -3
  77. package/src/runs/shared/rex-machine.js +12 -9
  78. package/src/runs/shared/rex-pane-host.js +7 -27
  79. package/src/runs/shared/single-output.js +2 -2
  80. package/src/runs/shared/subagent-prompt-runtime.js +33 -0
  81. package/src/runs/shared/tool-availability.d.ts +4 -0
  82. package/src/runs/shared/tool-availability.js +7 -0
  83. package/src/runs/shared/worktree-cleanup-plan.js +2 -2
  84. package/src/runs/shared/worktree.d.ts +4 -14
  85. package/src/runs/shared/worktree.js +38 -8
  86. package/src/shared/types.d.ts +26 -2
  87. package/src/workflows/workflow-child-summary.d.ts +2 -1
  88. package/src/workflows/workflow-child-summary.js +14 -6
@@ -4,11 +4,11 @@ import * as net from "node:net";
4
4
  import * as path from "node:path";
5
5
  import packageJson from "../../../package.json" with { type: "json" };
6
6
  import { herdrPaneHost, HerdrPlacedRunOwner } from "./herdr-pane-host.js";
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";
7
+ import { encodeHerdrPiFrame, HERDR_PI_MAX_ACCEPTANCE_PROMPT_BYTES, 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
10
  import { ensureSupervisorChannelDir } from "../../intercom/native-supervisor-channel.js";
11
- import { isRexLocalMachine } from "./rex-machine.js";
11
+ import { editsLocalDisk } from "./rex-machine.js";
12
12
  import { PLACED_RESTORE_UNSUPPORTED } from "./herdr-machine.js";
13
13
  /** The pane half comes from the host; the bridge half (run, package, protocol, native session, evidence cursor) is host-neutral. */
14
14
  export function reconcileHerdrReconnect(identity, candidate, lastEvidenceCursor, host = herdrPaneHost) {
@@ -47,11 +47,13 @@ export function serializeHerdrPiLaunch(launch) {
47
47
  throw new Error("Pane-native remote Pi cannot transfer local bindings, MCP selections, or process environment.");
48
48
  if (launch.runtime.nestedRoute || launch.runtime.fanoutChild || launch.runtime.depth > 1)
49
49
  throw new Error("Nested delegation from a pane-native remote Pi is not supported.");
50
- if (launch.excludeTools?.length || launch.runtime.permissions || launch.runtime.toolBudget || launch.runtime.requiredExtensions || launch.runtime.mcpDirectTools?.length)
51
- throw new Error("Pane-native remote Pi cannot yet represent exclusions, permission rules, tool budgets, MCP direct tools, or required-extension contracts; remove machine placement.");
50
+ if (launch.excludeTools?.length || launch.runtime.permissions || launch.runtime.toolBudget || launch.runtime.requiredExtensions || launch.runtime.mcpDirectTools?.length || launch.runtime.structuredOutput)
51
+ throw new Error("Pane-native remote Pi cannot yet represent exclusions, permission rules, tool budgets, MCP direct tools, required-extension contracts, or outputSchema; remove machine placement.");
52
52
  const resources = launch.remoteResources;
53
53
  if (!resources || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(resources.agent) || resources.skills?.some((name) => !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(name)) || resources.toolCeiling?.some((name) => !/^[A-Za-z0-9_-]{1,64}$/u.test(name)) || (resources.reads !== undefined && resources.reads !== false && resources.reads.some((read) => typeof read !== "string" || Buffer.byteLength(read) > 4096)))
54
54
  throw new Error("Pane-native remote resources require bounded logical agent, skill, tool, and read names.");
55
+ if (resources.acceptancePrompt !== undefined && Buffer.byteLength(resources.acceptancePrompt) > HERDR_PI_MAX_ACCEPTANCE_PROMPT_BYTES)
56
+ throw new Error(`A placed Pi child's acceptance instructions exceed ${HERDR_PI_MAX_ACCEPTANCE_PROMPT_BYTES} bytes; shorten the acceptance criteria or remove machine placement.`);
55
57
  const args = [];
56
58
  if (launch.noSkills)
57
59
  args.push("--no-skills", "--no-prompt-templates");
@@ -59,7 +61,7 @@ export function serializeHerdrPiLaunch(launch) {
59
61
  args.push("--no-context-files");
60
62
  if (launch.model)
61
63
  args.push("--model", launch.model);
62
- return { args, resources: { agent: resources.agent, ...(resources.skills ? { skills: [...resources.skills] } : {}), ...(resources.toolCeiling ? { toolCeiling: [...resources.toolCeiling] } : {}), ...(resources.reads !== undefined ? { reads: resources.reads === false ? false : [...resources.reads] } : {}) } };
64
+ return { args, resources: { agent: resources.agent, ...(resources.skills ? { skills: [...resources.skills] } : {}), ...(resources.toolCeiling ? { toolCeiling: [...resources.toolCeiling] } : {}), ...(resources.reads !== undefined ? { reads: resources.reads === false ? false : [...resources.reads] } : {}), ...(resources.acceptancePrompt ? { acceptancePrompt: resources.acceptancePrompt } : {}) } };
63
65
  }
64
66
  export class BridgeChannel {
65
67
  socket;
@@ -345,9 +347,9 @@ export async function reconnectHerdrPiSession(session, launch, dependencies = {}
345
347
  }
346
348
  export async function createHerdrPiSession(launch) {
347
349
  if (!launch.machine)
348
- throw new Error("Pane-native Pi launch requires a saved machine.");
350
+ throw new Error("Pane-native Pi launch requires a machine.");
349
351
  if (launch.machine.provider !== "herdr")
350
- throw new Error("Herdr pane-native Pi launch requires a Herdr saved machine.");
352
+ throw new Error("Herdr pane-native Pi launch requires a Herdr machine.");
351
353
  const policy = serializeHerdrPiLaunch(launch);
352
354
  const runId = safeRunId(launch.runtime.runId);
353
355
  return startPlacedPiSession(launch, await HerdrPlacedRunOwner.create(launch.machine, runId), policy);
@@ -385,7 +387,7 @@ async function startPlacedPiSession(launch, owner, policy) {
385
387
  throw new Error(`Remote Pi agent '${policy.resources.agent}' did not activate required tools: ${missingRequired.join(", ")}.`);
386
388
  if (launch.model && configured.model !== launch.model.split(":")[0])
387
389
  throw new Error(`Remote Pi model '${launch.model}' did not resolve to the requested provider/model.`);
388
- const identity = { runId, machineId: machine.id, target: isRexLocalMachine(machine) ? machine.id : machine.target, session: owner.host.sessionOf(connection), workspaceId: owned.workspaceId, tabId: owned.tabId, paneId: owned.paneId, terminalId, agentName, nativeSessionId: manifest.nativeSessionId, cwd: machine.cwd, runtimeDir };
390
+ const identity = { runId, machineId: machine.id, target: editsLocalDisk(machine) ? machine.id : machine.target, session: owner.host.sessionOf(connection), workspaceId: owned.workspaceId, tabId: owned.tabId, paneId: owned.paneId, terminalId, agentName, nativeSessionId: manifest.nativeSessionId, cwd: machine.cwd, runtimeDir };
389
391
  owner.journal(identity);
390
392
  const session = new HerdrPiSession(owner, bridgeForward, bridge, configured.tools, typeof ready.model === "string" ? ready.model : undefined, launch.runtime, ready.initialGit);
391
393
  reconnectSession = session;
@@ -0,0 +1,8 @@
1
+ import type { ParallelHandoffReference } from "../../shared/types.ts";
2
+ export type KeptBranch = NonNullable<ParallelHandoffReference["keptBranches"]>[number];
3
+ /** Kept branches from a saved handoff reference, which is read back from disk. */
4
+ export declare function readKeptBranches(value: unknown): KeptBranch[];
5
+ export declare function formatKeptBranchLines(keptBranches: readonly KeptBranch[]): string[];
6
+ /** The kept-branch lines follow the handoff line directly: `parseKeptBranchLines` reads them back from there. */
7
+ export declare function formatParallelHandoffLines(handoffPath: string, keptBranches: unknown): string[];
8
+ export declare function parseKeptBranchLines(lines: string[]): KeptBranch[];
@@ -0,0 +1,24 @@
1
+ const KEPT_BRANCH_LINE = /^Kept branch (\S+) at ([0-9a-f]+): its commits are on no other branch\.$/;
2
+ /** Kept branches from a saved handoff reference, which is read back from disk. */
3
+ export function readKeptBranches(value) {
4
+ if (!Array.isArray(value))
5
+ return [];
6
+ return value.filter((entry) => typeof entry?.branch === "string" && typeof entry?.tip === "string");
7
+ }
8
+ export function formatKeptBranchLines(keptBranches) {
9
+ return keptBranches.map(({ branch, tip }) => `Kept branch ${branch} at ${tip.slice(0, 12)}: its commits are on no other branch.`);
10
+ }
11
+ /** The kept-branch lines follow the handoff line directly: `parseKeptBranchLines` reads them back from there. */
12
+ export function formatParallelHandoffLines(handoffPath, keptBranches) {
13
+ return [`Parallel handoff: ${handoffPath}`, ...formatKeptBranchLines(readKeptBranches(keptBranches))];
14
+ }
15
+ export function parseKeptBranchLines(lines) {
16
+ const kept = [];
17
+ for (const line of lines) {
18
+ const match = line.match(KEPT_BRANCH_LINE);
19
+ if (!match)
20
+ break;
21
+ kept.push({ branch: match[1], tip: match[2] });
22
+ }
23
+ return kept;
24
+ }
@@ -1,5 +1,8 @@
1
1
  import type { PlacementMachineAccess } from "./placement-host.ts";
2
- /** Machine access for the parent's own machine: the same quoted `sh -c` scripts the SSH access sends, run directly through /bin/sh. */
2
+ /**
3
+ * Machine access for the parent's own machine: the same quoted `sh -c` scripts the SSH access sends, run directly through /bin/sh.
4
+ * They keep this process's PATH instead of the fixed remote one, which lacks coreutils on hosts such as NixOS.
5
+ */
3
6
  export declare function localMachineAccess(options?: {
4
7
  env?: NodeJS.ProcessEnv;
5
8
  }): PlacementMachineAccess;
@@ -1,6 +1,6 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import * as path from "node:path";
3
- import { remoteShellCommand, runBoundedCommand } from "./herdr-connection.js";
3
+ import { runBoundedCommand, shellScriptCommand } from "./herdr-connection.js";
4
4
  const DEFAULT_TIMEOUT_MS = 15_000, DEFAULT_MAX_BUFFER = 256 * 1024;
5
5
  /** Sockets on this machine are already reachable: forwarding returns the path unchanged and closing is a no-op. */
6
6
  function localSockets() {
@@ -10,11 +10,14 @@ function localSockets() {
10
10
  async close() { },
11
11
  };
12
12
  }
13
- /** Machine access for the parent's own machine: the same quoted `sh -c` scripts the SSH access sends, run directly through /bin/sh. */
13
+ /**
14
+ * Machine access for the parent's own machine: the same quoted `sh -c` scripts the SSH access sends, run directly through /bin/sh.
15
+ * They keep this process's PATH instead of the fixed remote one, which lacks coreutils on hosts such as NixOS.
16
+ */
14
17
  export function localMachineAccess(options = {}) {
15
18
  const env = options.env ?? process.env;
16
19
  return {
17
- shellCommand: remoteShellCommand,
20
+ shellCommand: shellScriptCommand,
18
21
  run(command, limits = {}) {
19
22
  const spawned = spawnSync("/bin/sh", ["-c", command], { encoding: "utf8", env, timeout: limits.timeout ?? DEFAULT_TIMEOUT_MS, maxBuffer: limits.maxBuffer ?? DEFAULT_MAX_BUFFER, windowsHide: true });
20
23
  const result = { status: spawned.status, stdout: spawned.stdout ?? "", stderr: spawned.stderr ?? "" };
@@ -1,5 +1,11 @@
1
- import type { ArtifactPaths, TimeoutRecoveryProjection, TimeoutRecoverySummary, TrackedMutationEvidence, TrackedMutationSnapshot } from "../../shared/types.ts";
1
+ import type { ArtifactPaths, HerdrRemoteGitStatus, TimeoutRecoveryProjection, TimeoutRecoverySummary, TrackedMutationEvidence, TrackedMutationSnapshot } from "../../shared/types.ts";
2
2
  export declare function snapshotTrackedMutations(cwd: string): TrackedMutationSnapshot;
3
+ /** A placed child on another machine edits that machine's disk, so local Git evidence stands in only as a marked placeholder. */
4
+ export declare function remoteMutationSnapshot(cwd: string): TrackedMutationSnapshot;
5
+ export declare function remoteMutationEvidence(machine: {
6
+ initialGit?: HerdrRemoteGitStatus;
7
+ finalGit?: HerdrRemoteGitStatus;
8
+ }): TrackedMutationEvidence;
3
9
  export declare function collectTrackedMutationEvidence(snapshot: TrackedMutationSnapshot, cwd?: string): Promise<TrackedMutationEvidence>;
4
10
  /** Keep status and completion details to bounded routing evidence, not raw output or effects. */
5
11
  export declare function projectTimeoutRecovery(value: unknown): TimeoutRecoveryProjection | undefined;
@@ -43,6 +43,14 @@ async function hashFileAsync(diffPath) {
43
43
  function splitNul(output) {
44
44
  return output.split("\0").filter((part) => part.length > 0);
45
45
  }
46
+ /** Git prints its whole option reference after the error, which must not reach recovery summaries. */
47
+ function gitFailureReason(error) {
48
+ const stderr = error && typeof error === "object" && "stderr" in error ? String(error.stderr ?? "") : "";
49
+ if (/not a git repository/i.test(stderr))
50
+ return "not a Git work tree";
51
+ const firstLine = (stderr || (error instanceof Error ? error.message : String(error))).split("\n").find((line) => line.trim().length > 0);
52
+ return firstLine?.trim() ?? "git failed";
53
+ }
46
54
  function hashLargeDiff(cwd, relativePath) {
47
55
  const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagents-tracked-diff-"));
48
56
  const diffPath = path.join(tempDir, "diff.patch");
@@ -96,7 +104,7 @@ export function snapshotTrackedMutations(cwd) {
96
104
  return { source: "tracked-files", trackedOnly: true, cwd, dirtyFiles: changed.paths, fingerprints, truncated: changed.truncated };
97
105
  }
98
106
  catch (error) {
99
- return { source: "tracked-files", trackedOnly: true, cwd, dirtyFiles: [], fingerprints: {}, unavailable: error instanceof Error ? error.message : String(error) };
107
+ return { source: "tracked-files", trackedOnly: true, cwd, dirtyFiles: [], fingerprints: {}, unavailable: gitFailureReason(error) };
100
108
  }
101
109
  }
102
110
  async function fingerprintPathAsync(cwd, relativePath) {
@@ -116,6 +124,14 @@ async function fingerprintPathAsync(cwd, relativePath) {
116
124
  }
117
125
  }
118
126
  }
127
+ /** A placed child on another machine edits that machine's disk, so local Git evidence stands in only as a marked placeholder. */
128
+ export function remoteMutationSnapshot(cwd) {
129
+ return { source: "tracked-files", trackedOnly: true, cwd, dirtyFiles: [], fingerprints: {}, unavailable: "Local Git evidence is not authoritative for a pane-native remote run." };
130
+ }
131
+ export function remoteMutationEvidence(machine) {
132
+ const changed = machine.initialGit && machine.finalGit ? machine.initialGit.head !== machine.finalGit.head || machine.initialGit.dirty !== machine.finalGit.dirty : undefined;
133
+ return { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: changed === true, ...(changed === undefined ? { unavailable: "Remote Git before/after evidence was incomplete." } : {}) };
134
+ }
119
135
  export async function collectTrackedMutationEvidence(snapshot, cwd = snapshot.cwd) {
120
136
  if (snapshot.unavailable) {
121
137
  return { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: false, unavailable: snapshot.unavailable };
@@ -144,7 +160,7 @@ export async function collectTrackedMutationEvidence(snapshot, cwd = snapshot.cw
144
160
  };
145
161
  }
146
162
  catch (error) {
147
- return { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: false, unavailable: error instanceof Error ? error.message : String(error) };
163
+ return { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: false, unavailable: gitFailureReason(error) };
148
164
  }
149
165
  }
150
166
  function formatPathList(paths) {
@@ -3,8 +3,9 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import { writeAtomicJson } from "../../shared/atomic-json.js";
5
5
  import { stableJsonDigest } from "../../shared/launch-contract.js";
6
- import { cleanupWorktrees, withWorktreeTransaction } from "./worktree.js";
6
+ import { cleanupWorktrees, isWorktreeCleanupTaskDone, withWorktreeTransaction } from "./worktree.js";
7
7
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "./lane-metadata.js";
8
+ import { formatKeptBranchLines } from "./kept-branch-text.js";
8
9
  function optionalIdentity(value, label) {
9
10
  if (value === undefined)
10
11
  return undefined;
@@ -209,6 +210,7 @@ export function resolveRetainedWorktreeCwd(manifestPath, runId, childIndex, reco
209
210
  }
210
211
  function referenceFor(manifestPath, manifest) {
211
212
  const children = manifest.groups.flatMap((group) => group.children);
213
+ const keptBranches = manifest.groups.flatMap((group) => group.cleanup.tasks.flatMap((task) => task.keptBranchTip ? [{ branch: task.branch, tip: task.keptBranchTip }] : []));
212
214
  return {
213
215
  version: 1,
214
216
  path: manifestPath,
@@ -216,6 +218,7 @@ function referenceFor(manifestPath, manifest) {
216
218
  childCount: children.length,
217
219
  changedPatches: children.filter((child) => child.patch.changed).length,
218
220
  cleanupState: manifest.groups.every((group) => group.cleanup.state === "complete") ? "complete" : "partial",
221
+ ...(keptBranches.length ? { keptBranches } : {}),
219
222
  ...(Object.prototype.hasOwnProperty.call(manifest, "cleanupEligibility")
220
223
  ? { cleanupEligibility: trustedStoredCleanupEligibility(manifest) }
221
224
  : {}),
@@ -627,6 +630,8 @@ function writeParallelHandoffGroupUnlocked(input) {
627
630
  task.worktreeRemoved = true;
628
631
  if (previous?.branchRemoved)
629
632
  task.branchRemoved = true;
633
+ if (previous?.keptBranchTip)
634
+ task.keptBranchTip = previous.keptBranchTip;
630
635
  if (!task.worktreeRemoved && previous?.reason?.includes("retained child resume")) {
631
636
  task.preserved = true;
632
637
  task.reason = previous.reason;
@@ -719,10 +724,17 @@ export function writeWorktreeSetupHandoff(input) {
719
724
  });
720
725
  }
721
726
  export function formatParallelHandoffReference(reference) {
722
- return `Worktree handoff: ${reference.path} (${reference.childCount} children, ${reference.changedPatches} changed patches, cleanup ${reference.cleanupState})`;
727
+ // After cleanup a patch is the only copy of the work, and nothing applies it to the parent's checkout.
728
+ const patches = reference.changedPatches > 0 ? "; the work is in groups[].children[].patch, not applied to this checkout" : "";
729
+ const kept = reference.cleanupState === "complete" ? "" : "; groups[].cleanup.tasks[] (reason, errors) says what stayed behind";
730
+ return [
731
+ `Worktree handoff: ${reference.path} (${reference.childCount} children, ${reference.changedPatches} changed patches, cleanup ${reference.cleanupState})${patches}${kept}`,
732
+ ...formatKeptBranchLines(reference.keptBranches ?? []),
733
+ ].join("\n");
723
734
  }
724
735
  export function formatParallelHandoffError(error) {
725
- return `Worktree handoff unavailable: ${error instanceof Error ? error.message : String(error)}`;
736
+ // This can fire before, during, or after cleanup, so it cannot say whether the worktrees still exist.
737
+ return `Worktree handoff unavailable: ${error instanceof Error ? error.message : String(error)}; check \`git worktree list\` for worktrees left behind`;
726
738
  }
727
739
  export function discardPreservedWorktrees(...args) {
728
740
  return withHandoffWriteLock(args[0], () => discardPreservedWorktreesUnlocked(...args));
@@ -734,7 +746,7 @@ function discardPreservedWorktreesUnlocked(manifestPath, authorization) {
734
746
  throw new Error(`Parallel handoff manifest not found: ${resolvedPath}`);
735
747
  let attempted = 0;
736
748
  for (const group of manifest.groups) {
737
- const pending = group.cleanup.tasks.filter((task) => task.preserved && (!task.worktreeRemoved || !task.branchRemoved));
749
+ const pending = group.cleanup.tasks.filter((task) => task.preserved && !isWorktreeCleanupTaskDone(task));
738
750
  if (pending.length === 0)
739
751
  continue;
740
752
  attempted += pending.length;
@@ -753,13 +765,13 @@ function discardPreservedWorktreesUnlocked(manifestPath, authorization) {
753
765
  syntheticPaths: [],
754
766
  })),
755
767
  }, { kind: "discard", authorization });
756
- const updates = new Map(report.tasks.map((task) => [task.index, task.worktreeRemoved && task.branchRemoved
768
+ const updates = new Map(report.tasks.map((task) => [task.index, isWorktreeCleanupTaskDone(task)
757
769
  ? task
758
770
  : { ...task, preserved: true, reason: task.reason ?? "discard cleanup remains incomplete" }]));
759
771
  group.cleanup = {
760
772
  state: group.cleanup.tasks.every((task) => {
761
773
  const next = updates.get(task.index) ?? task;
762
- return next.worktreeRemoved && next.branchRemoved;
774
+ return isWorktreeCleanupTaskDone(next);
763
775
  }) && report.pruned ? "complete" : "partial",
764
776
  tasks: group.cleanup.tasks.map((task) => updates.get(task.index) ?? task),
765
777
  pruned: report.pruned,
@@ -769,7 +781,7 @@ function discardPreservedWorktreesUnlocked(manifestPath, authorization) {
769
781
  manifest.updatedAt = Date.now();
770
782
  writeAtomicJson(resolvedPath, manifest);
771
783
  const remaining = manifest.groups.flatMap((group) => group.cleanup.tasks.map((task) => ({ group, task })))
772
- .filter(({ task }) => task.preserved && (!task.worktreeRemoved || !task.branchRemoved));
784
+ .filter(({ task }) => task.preserved && !isWorktreeCleanupTaskDone(task));
773
785
  const lines = attempted === 0
774
786
  ? [`No preserved worktrees remain in ${resolvedPath}.`]
775
787
  : [`Discard processed ${attempted} preserved worktree${attempted === 1 ? "" : "s"}.`, `Manifest: ${resolvedPath}`];
@@ -9,7 +9,9 @@ export interface PlacedBridgeManifest {
9
9
  }
10
10
  /** Prints `$1/manifest.json` when it is a regular file, never through a symlink. */
11
11
  export declare const PLACED_MANIFEST_READ_SCRIPT = "p=\"$1/manifest.json\"; test -f \"$p\" && test ! -L \"$p\" && cat \"$p\"";
12
- export declare function discoverPlacedBridgeManifest(access: PlacementMachineAccess, runId: string, runtimeDir: string, missing?: string): Promise<PlacedBridgeManifest>;
12
+ export declare function discoverPlacedBridgeManifest(access: PlacementMachineAccess, runId: string, runtimeDir: string, missing?: string, deadlineMs?: number): Promise<PlacedBridgeManifest>;
13
+ /** A short hash names a runtime directory under /tmp, so /tmp/pi-subagents-herdr-<hash>-XXXXXXXX/bridge.sock (57 bytes) fits the 103-byte macOS socket path limit for any run id. */
14
+ export declare function hashedRuntimeDirName(runId: string): string;
13
15
  export declare function createPlacedRuntimeDir(access: PlacementMachineAccess, runId: string): Promise<string>;
14
16
  export declare function removePlacedRuntimeDir(access: PlacementMachineAccess, runtimeDir: string): void;
15
17
  /** The single private owner for allocation shared by every pane-native backend projection. */
@@ -26,7 +28,7 @@ export declare class PlacedRunOwner<C extends PlacementSockets, M extends Placem
26
28
  agentName?: string;
27
29
  startedArgv?: string[];
28
30
  identity?: HerdrRunIdentity;
29
- protected constructor(machine: M, runId: string, runtimeDir: string, connection: C, host: PlacementPaneHost<C>, access: PlacementMachineAccess, removeRuntime?: () => void);
31
+ protected constructor(machine: M, runId: string, runtimeDir: string, connection: C, host: PlacementPaneHost<C>, access: PlacementMachineAccess);
30
32
  observeEvent(event: unknown): void;
31
33
  markConnectionUnknown(observed: C): boolean;
32
34
  subscribe(listener: (event: unknown) => void, disconnected: (error: Error) => void): Promise<void>;
@@ -1,10 +1,14 @@
1
+ import { createHash } from "node:crypto";
1
2
  import * as fs from "node:fs";
2
3
  import * as path from "node:path";
3
4
  import { getAgentDir } from "../../shared/utils.js";
4
5
  /** Prints `$1/manifest.json` when it is a regular file, never through a symlink. */
5
6
  export const PLACED_MANIFEST_READ_SCRIPT = 'p="$1/manifest.json"; test -f "$p" && test ! -L "$p" && cat "$p"';
6
- export async function discoverPlacedBridgeManifest(access, runId, runtimeDir, missing = "The placed Pi's pi-subagents bridge manifest is not in its runtime directory; the Pi may have exited.") {
7
- for (let attempt = 0; attempt < 100; attempt++) {
7
+ /** A child with many extensions took about 12 s to write its manifest; a child stuck on a startup prompt holds its pane until this deadline. */
8
+ const PLACED_MANIFEST_DEADLINE_MS = 30_000;
9
+ export async function discoverPlacedBridgeManifest(access, runId, runtimeDir, missing = "The placed Pi's pi-subagents bridge manifest is not in its runtime directory; the Pi may have exited.", deadlineMs = PLACED_MANIFEST_DEADLINE_MS) {
10
+ const deadline = Date.now() + deadlineMs;
11
+ for (;;) {
8
12
  const result = await access.runAsync(access.shellCommand(PLACED_MANIFEST_READ_SCRIPT, [runtimeDir]), { timeout: 5_000, maxBuffer: 64 * 1024 });
9
13
  if (result.error)
10
14
  throw new Error(`Remote bridge manifest discovery failed: ${result.error.message}`, { cause: result.error });
@@ -21,14 +25,19 @@ export async function discoverPlacedBridgeManifest(access, runId, runtimeDir, mi
21
25
  throw new Error("Remote bridge manifest identity is incomplete or outside its owned runtime directory.");
22
26
  return { socketPath: p.socketPath, nativeSessionId: p.nativeSessionId, packageVersion: p.packageVersion, protocol: p.protocol };
23
27
  }
28
+ if (Date.now() >= deadline)
29
+ throw new Error(missing);
24
30
  await new Promise((resolve) => setTimeout(resolve, 50));
25
31
  }
26
- throw new Error(missing);
27
32
  }
33
+ /** A short hash names a runtime directory under /tmp, so /tmp/pi-subagents-herdr-<hash>-XXXXXXXX/bridge.sock (57 bytes) fits the 103-byte macOS socket path limit for any run id. */
34
+ export function hashedRuntimeDirName(runId) { return createHash("sha256").update(runId).digest("hex").slice(0, 12); }
28
35
  export async function createPlacedRuntimeDir(access, runId) { const result = await access.runAsync(access.shellCommand("umask 077; mktemp -d \"${TMPDIR:-/tmp}/pi-subagents-herdr-$1-XXXXXXXX\"", [runId]), { timeout: 10_000, maxBuffer: 4096 }); if (result.error)
29
36
  throw new Error(`Could not provision a run-private remote bridge runtime directory: ${result.error.message}`, { cause: result.error }); const value = result.stdout.trim(); if (result.status !== 0 || !path.posix.isAbsolute(value) || value.includes("\n"))
30
37
  throw new Error("Could not provision a run-private remote bridge runtime directory."); return value; }
31
- export function removePlacedRuntimeDir(access, runtimeDir) { const result = access.run(access.shellCommand("p=$1; case \"${p##*/}\" in pi-subagents-herdr-*) test -d \"$p\" && test ! -L \"$p\" && rm -rf -- \"$p\";; *) exit 64;; esac", [runtimeDir]), { timeout: 10_000, maxBuffer: 4096 }); if (result.status !== 0 || result.stdout)
38
+ // Already-gone counts as removed: the placed child deletes its own runtime directory on session
39
+ // shutdown (herdr-pi-bridge), so the parent's cleanup races it and must tolerate losing.
40
+ export function removePlacedRuntimeDir(access, runtimeDir) { const result = access.run(access.shellCommand("p=$1; case \"${p##*/}\" in pi-subagents-herdr-*) if test -d \"$p\" && test ! -L \"$p\"; then rm -rf -- \"$p\"; fi; test ! -e \"$p\" && test ! -L \"$p\";; *) exit 64;; esac", [runtimeDir]), { timeout: 10_000, maxBuffer: 4096 }); if (result.status !== 0 || result.stdout)
32
41
  throw new Error(`Could not remove the exact owned remote runtime directory: ${String(result.stderr).slice(0, 512)}`); }
33
42
  /** The single private owner for allocation shared by every pane-native backend projection. */
34
43
  export class PlacedRunOwner {
@@ -46,8 +55,7 @@ export class PlacedRunOwner {
46
55
  #unsubscribe = () => { };
47
56
  #snapshot = { connection: "connected", state: "ready", revision: 0 };
48
57
  #cleanupPromise;
49
- #removeRuntime;
50
- constructor(machine, runId, runtimeDir, connection, host, access, removeRuntime = () => removePlacedRuntimeDir(access, runtimeDir)) { this.machine = machine; this.runId = runId; this.runtimeDir = runtimeDir; this.connection = connection; this.#removeRuntime = removeRuntime; this.host = host; this.access = access; }
58
+ constructor(machine, runId, runtimeDir, connection, host, access) { this.machine = machine; this.runId = runId; this.runtimeDir = runtimeDir; this.connection = connection; this.host = host; this.access = access; }
51
59
  observeEvent(event) { const data = this.host.paneEvent(event, this.#snapshot.state); if (data && (!this.terminalId || data.terminalId === this.terminalId || data.paneId === this.owned?.paneId))
52
60
  this.#snapshot = { ...this.#snapshot, revision: this.#snapshot.revision + 1, state: data.state }; }
53
61
  markConnectionUnknown(observed) { if (this.connection !== observed)
@@ -84,7 +92,7 @@ export class PlacedRunOwner {
84
92
  } try {
85
93
  this.#unsubscribe();
86
94
  await this.connection.close();
87
- this.#removeRuntime();
95
+ removePlacedRuntimeDir(this.access, this.runtimeDir);
88
96
  }
89
97
  catch (error) {
90
98
  failure ??= error;
@@ -1,10 +1,12 @@
1
- import type { PlacementMachineReference, RexLocalMachineReference } from "../../shared/types.ts";
2
- /** `machine: "local"` is reserved: this machine, in a Rex pane of the parent's own Rex session. It never consults the Herdr catalog. */
1
+ import type { HerdrLocalMachineReference, PlacementMachineReference, RexLocalMachineReference } from "../../shared/types.ts";
2
+ /** `machine: "local"` is reserved: this machine, in a new tab of the Herdr or Rex session this Pi runs in. It never consults the Herdr catalog. */
3
3
  export declare const REX_LOCAL_MACHINE = "local";
4
4
  /** Rex CLI exit codes: 3 means the target is gone, 4 means the server is unreachable (state unknown, never "gone"). */
5
5
  export declare const REX_EXIT_GONE = 3, REX_EXIT_UNREACHABLE = 4;
6
- /** A `local` child edits this machine's disk; every other placed child edits the remote one. */
6
+ /** A Rex pane in the parent's own Rex session; the other Rex reference is an SSH machine. */
7
7
  export declare function isRexLocalMachine(machine: PlacementMachineReference | undefined): machine is RexLocalMachineReference;
8
+ /** A placed child without an SSH `target` (Rex or Herdr `local`) edits this machine's disk; every other placed child edits the remote one. */
9
+ export declare function editsLocalDisk(machine: PlacementMachineReference | undefined): machine is RexLocalMachineReference | HerdrLocalMachineReference;
8
10
  /** The Rex server bundle's CLI, relative to the home directory. */
9
11
  export declare const REX_BUNDLE_BIN = "Library/Application Support/com.superlogical.rex/RexServer/Versions/Current/Rex Server.app/Contents/MacOS/rex";
10
12
  export declare const REX_CALL_TIMEOUT_MS = 15000, REX_MAX_OUTPUT: number;
@@ -23,3 +25,5 @@ export declare function resolveRexLocalPlacement(input: {
23
25
  stepCwd?: string;
24
26
  env?: NodeJS.ProcessEnv;
25
27
  }): RexLocalMachineReference;
28
+ /** The real launch directory of a `local` child: `stepCwd` is absolute, `~`, or relative to the parent's launch directory `cwd`. */
29
+ export declare function resolveLocalLaunchCwd(parentCwd: string, stepCwd: string | undefined): string;
@@ -2,12 +2,14 @@ import { spawnSync } from "node:child_process";
2
2
  import * as fs from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
- /** `machine: "local"` is reserved: this machine, in a Rex pane of the parent's own Rex session. It never consults the Herdr catalog. */
5
+ /** `machine: "local"` is reserved: this machine, in a new tab of the Herdr or Rex session this Pi runs in. It never consults the Herdr catalog. */
6
6
  export const REX_LOCAL_MACHINE = "local";
7
7
  /** Rex CLI exit codes: 3 means the target is gone, 4 means the server is unreachable (state unknown, never "gone"). */
8
8
  export const REX_EXIT_GONE = 3, REX_EXIT_UNREACHABLE = 4;
9
- /** A `local` child edits this machine's disk; every other placed child edits the remote one. */
9
+ /** A Rex pane in the parent's own Rex session; the other Rex reference is an SSH machine. */
10
10
  export function isRexLocalMachine(machine) { return machine?.provider === "rex" && !("target" in machine); }
11
+ /** A placed child without an SSH `target` (Rex or Herdr `local`) edits this machine's disk; every other placed child edits the remote one. */
12
+ export function editsLocalDisk(machine) { return machine !== undefined && !("target" in machine); }
11
13
  /** The Rex server bundle's CLI, relative to the home directory. */
12
14
  export const REX_BUNDLE_BIN = "Library/Application Support/com.superlogical.rex/RexServer/Versions/Current/Rex Server.app/Contents/MacOS/rex";
13
15
  export const REX_CALL_TIMEOUT_MS = 15_000, REX_MAX_OUTPUT = 1024 * 1024;
@@ -64,9 +66,13 @@ export function resolveRexLocalPlacement(input) {
64
66
  throw new Error(`rex session inspect exited with code ${result.status}: ${(result.stderr || result.stdout).trim().slice(0, 512)}`);
65
67
  if (!sessionConfirmed(result.stdout, session))
66
68
  throw new Error(`The Rex server did not confirm session ${session}.`);
67
- const stepCwd = input.stepCwd?.trim();
68
- const home = stepCwd === "~" || stepCwd?.startsWith("~/") ? path.join(os.homedir(), stepCwd.slice(1)) : undefined;
69
- const requested = home ?? (stepCwd ? path.resolve(input.cwd, stepCwd) : input.cwd);
69
+ return { provider: "rex", id: REX_LOCAL_MACHINE, session, cwd: resolveLocalLaunchCwd(input.cwd, input.stepCwd), ...(server ? { server } : {}) };
70
+ }
71
+ /** The real launch directory of a `local` child: `stepCwd` is absolute, `~`, or relative to the parent's launch directory `cwd`. */
72
+ export function resolveLocalLaunchCwd(parentCwd, stepCwd) {
73
+ const step = stepCwd?.trim();
74
+ const home = step === "~" || step?.startsWith("~/") ? path.join(os.homedir(), step.slice(1)) : undefined;
75
+ const requested = home ?? (step ? path.resolve(parentCwd, step) : parentCwd);
70
76
  let cwd;
71
77
  try {
72
78
  cwd = fs.realpathSync(requested);
@@ -76,8 +82,5 @@ export function resolveRexLocalPlacement(input) {
76
82
  }
77
83
  if (!fs.statSync(cwd).isDirectory())
78
84
  throw new Error(`Machine 'local' cwd is not a directory: ${requested}.`);
79
- const machine = { provider: "rex", id: REX_LOCAL_MACHINE, session, cwd };
80
- if (server)
81
- machine.server = server;
82
- return machine;
85
+ return cwd;
83
86
  }
@@ -1,11 +1,10 @@
1
- import { createHash } from "node:crypto";
2
1
  import * as path from "node:path";
3
2
  import { Type } from "typebox";
4
3
  import { Compile } from "typebox/compile";
5
- import { remoteShellCommand, sshMachineAccess } from "./herdr-connection.js";
4
+ import { sshMachineAccess } from "./herdr-connection.js";
6
5
  import { localMachineAccess } from "./local-machine-access.js";
7
6
  import { getPiSpawnCommand } from "./pi-spawn.js";
8
- import { createPlacedRuntimeDir, PLACED_MANIFEST_READ_SCRIPT, PlacedRunOwner, removePlacedRuntimeDir } from "./placed-run-owner.js";
7
+ import { createPlacedRuntimeDir, hashedRuntimeDirName, PLACED_MANIFEST_READ_SCRIPT, PlacedRunOwner, removePlacedRuntimeDir } from "./placed-run-owner.js";
9
8
  import { withHerdrPaneAllocationLock } from "./placement-host.js";
10
9
  import { isRexLocalMachine, REX_BUNDLE_BIN, REX_CALL_TIMEOUT_MS, REX_EXIT_GONE, REX_EXIT_UNREACHABLE, REX_MAX_OUTPUT, resolveRexBinary, rexCommandEnv, rexGlobalArgs } from "./rex-machine.js";
11
10
  const REX_CLOSE_POLLS = 20, REX_CLOSE_POLL_MS = 50;
@@ -20,7 +19,7 @@ const bridgeManifestPid = Compile(Type.Object({ pid: Type.Integer() }));
20
19
  /** Rex runtime directories go under /tmp: the bridge socket path inside a macOS TMPDIR exceeds the unix socket path limit. */
21
20
  function rexAccess() { return localMachineAccess({ env: { ...rexCommandEnv(), TMPDIR: "/tmp" } }); }
22
21
  /** The same /tmp rule on the remote, whatever TMPDIR its SSH session has. */
23
- function rexSshAccess(machine, access = sshMachineAccess(machine)) { return { ...access, shellCommand: (script, args) => remoteShellCommand(`TMPDIR=/tmp; export TMPDIR; ${script}`, args) }; }
22
+ function rexSshAccess(machine, access = sshMachineAccess(machine)) { return { ...access, shellCommand: (script, args) => access.shellCommand(`TMPDIR=/tmp; export TMPDIR; ${script}`, args) }; }
24
23
  function asRexMachine(machine) { if (machine.provider !== "rex")
25
24
  throw new Error("The Rex pane host only places runs on Rex machines."); return machine; }
26
25
  /** Runs one rex command on the pane machine with --autostart=false, the recorded server, and no inherited Rex selectors; exit 4 always throws. */
@@ -265,30 +264,11 @@ export const rexPaneHost = {
265
264
  reconcile: reconcileRexPlacedRun,
266
265
  closeOwnedPane: closeOwnedRexPane,
267
266
  };
268
- function runtimeDirPresent(access, runtimeDir) {
269
- const result = access.run(access.shellCommand('test -e "$1" || test -L "$1"', [runtimeDir]), { timeout: 10_000, maxBuffer: 4096 });
270
- if (result.error)
271
- throw new Error(`Could not check the owned runtime directory: ${result.error.message}`, { cause: result.error });
272
- return result.status === 0;
273
- }
274
- /** A closed local Pi removes its own runtime directory on shutdown, so already-removed counts as removed. */
275
- function removeRexRuntimeDir(access, runtimeDir) {
276
- if (!runtimeDirPresent(access, runtimeDir))
277
- return;
278
- try {
279
- removePlacedRuntimeDir(access, runtimeDir);
280
- }
281
- catch (error) {
282
- if (runtimeDirPresent(access, runtimeDir))
283
- throw error;
284
- }
285
- }
286
267
  export class RexPlacedRunOwner extends PlacedRunOwner {
287
- constructor(machine, runId, runtimeDir, connection, access, host) { super(machine, runId, runtimeDir, connection, host, access, () => removeRexRuntimeDir(access, runtimeDir)); }
268
+ constructor(machine, runId, runtimeDir, connection, access, host) { super(machine, runId, runtimeDir, connection, host, access); }
288
269
  /** A Rex SSH owner's machine carries the resolved remote cwd, and its host reconnects only to the session recorded here. */
289
270
  static async create(machine, runId, options = {}) {
290
- // A short hash names the directory, so /tmp/pi-subagents-herdr-<hash>-XXXXXXXX/bridge.sock (57 bytes) fits the 103-byte macOS socket path limit for any run id.
291
- const hash = createHash("sha256").update(runId).digest("hex").slice(0, 12);
271
+ const hash = hashedRuntimeDirName(runId);
292
272
  if (isRexLocalMachine(machine)) {
293
273
  const access = rexAccess(), runtimeDir = await createPlacedRuntimeDir(access, hash);
294
274
  try {
@@ -296,7 +276,7 @@ export class RexPlacedRunOwner extends PlacedRunOwner {
296
276
  }
297
277
  catch (error) {
298
278
  try {
299
- removeRexRuntimeDir(access, runtimeDir);
279
+ removePlacedRuntimeDir(access, runtimeDir);
300
280
  }
301
281
  catch (cleanupError) {
302
282
  throw new AggregateError([error, cleanupError], "Rex owner creation failed and runtime cleanup also failed.", { cause: error });
@@ -314,7 +294,7 @@ export class RexPlacedRunOwner extends PlacedRunOwner {
314
294
  }
315
295
  catch (error) {
316
296
  try {
317
- removeRexRuntimeDir(access, runtimeDir);
297
+ removePlacedRuntimeDir(access, runtimeDir);
318
298
  }
319
299
  catch (cleanupError) {
320
300
  throw new AggregateError([error, cleanupError], "Rex owner creation failed and runtime cleanup also failed.", { cause: error });
@@ -1,6 +1,6 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
- import { isRexLocalMachine } from "./rex-machine.js";
3
+ import { editsLocalDisk } from "./rex-machine.js";
4
4
  const READ_ONLY_OUTPUT_TOOLS = new Set([
5
5
  "read", "grep", "find", "ls", "web_search", "fetch_content", "get_search_content",
6
6
  "source_check", "intercom", "contact_supervisor", "structured_output", "watchdog_diff",
@@ -103,7 +103,7 @@ export function outputPathMappingFromTask(task, savedPath) {
103
103
  export function injectSingleOutputInstruction(task, outputPath, capabilities, machine) {
104
104
  if (!outputPath)
105
105
  return task;
106
- const remote = machine !== undefined && !isRexLocalMachine(machine);
106
+ const remote = machine !== undefined && !editsLocalDisk(machine);
107
107
  const delivery = !remote && (!capabilities || hasOutputWriteCapability(capabilities.tools, capabilities.mcpDirectTools))
108
108
  ? `Write your findings to exactly this path: ${outputPath}`
109
109
  : [
@@ -229,8 +229,41 @@ function filterChildPromptOptions(options, inherited) {
229
229
  function rewritesChildPrompt(config) {
230
230
  return config.inheritProjectContext !== undefined || config.inheritGlobalContext !== undefined || config.inheritSkills !== undefined || Boolean(config.fanoutChild);
231
231
  }
232
+ /**
233
+ * An extension can replace the tools a request declares (pi-fabric's code mode sends only its own
234
+ * `fabric_exec`), and Pi only reports a throw from a request hook. This hook runs after every other
235
+ * extension's, so a child whose registered allowlisted tools were left out records why and stops
236
+ * before the provider gets the request. A request that declares them all passes through unchanged.
237
+ */
238
+ function registerDeclaredToolCheck(pi, config, required) {
239
+ pi.on("context_with_system", (event, ctx) => {
240
+ const declared = new Set(getCurrentTools(event.messages).map((tool) => tool.name));
241
+ if (required.every((name) => declared.has(name)))
242
+ return undefined;
243
+ const registered = new Set(pi.getAllTools().map((tool) => tool.name));
244
+ // A required tool that never registered is the agent_start diagnostic's case.
245
+ const undeclared = required.filter((name) => registered.has(name) && !declared.has(name));
246
+ if (undeclared.length === 0)
247
+ return undefined;
248
+ const active = new Set(pi.getActiveTools());
249
+ // A fork declares its parent's tools on purpose, to reuse the parent's prompt cache.
250
+ const uncallable = config.forkCacheKey ? [] : [...declared].filter((name) => !active.has(name));
251
+ config.toolDiagnostic?.({
252
+ ...(config.agent ? { agent: config.agent } : {}),
253
+ required: [...required],
254
+ available: [...registered],
255
+ missing: [],
256
+ undeclared,
257
+ ...(uncallable.length > 0 ? { uncallable } : {}),
258
+ });
259
+ ctx.abort();
260
+ return undefined;
261
+ });
262
+ }
232
263
  /** Installed after every other extension: a returned prompt freezes out sections added after it. */
233
264
  export function registerSubagentPromptBoundary(pi, config) {
265
+ if (config.requiredTools)
266
+ registerDeclaredToolCheck(pi, config, config.requiredTools);
234
267
  if (!rewritesChildPrompt(config))
235
268
  return;
236
269
  // A returned prompt replaces the whole system prompt of every request. A fork must send its
@@ -4,6 +4,10 @@ export interface ChildToolDiagnostic {
4
4
  available: string[];
5
5
  missing: string[];
6
6
  missingMcpDirectTools?: string[];
7
+ /** Registered allowlisted tools an extension left out of the tools sent to the model. */
8
+ undeclared?: string[];
9
+ /** Tools sent to the model that this child cannot call. */
10
+ uncallable?: string[];
7
11
  }
8
12
  /**
9
13
  * Explain missing child tools. Foreground children run inside the parent
@@ -6,6 +6,13 @@
6
6
  */
7
7
  export function formatChildToolDiagnostic(diagnostic, options = {}) {
8
8
  const subject = diagnostic.agent ? `Agent '${diagnostic.agent}'` : "Subagent";
9
+ if (diagnostic.undeclared?.length) {
10
+ const uncallable = diagnostic.uncallable?.length ? ` and added ${diagnostic.uncallable.join(", ")}, which this child cannot call` : "";
11
+ return [
12
+ `${subject} declares tools: ${diagnostic.required.join(", ")}, but an extension loaded in this child replaced the tools sent to the model: it left out ${diagnostic.undeclared.join(", ")}${uncallable}.`,
13
+ "The `tools` field is a strict allowlist. Set `extensions: []` or list only the extensions this child needs, or omit `tools` to use that extension's tool surface.",
14
+ ].join("\n");
15
+ }
9
16
  if (options.host === "parent") {
10
17
  return [
11
18
  `${subject} ran as a foreground child, which never loads the parent's ambient extensions, and these child tools were unavailable: ${diagnostic.missing.join(", ")}.`,
@@ -8,7 +8,7 @@ import { PROJECT_SUBAGENTS_RELATIVE_DIR } from "../../shared/artifacts.js";
8
8
  import { DEFAULT_STALE_TERMINAL_ACTIVE_MARKER_MS, activeRunMarkerAgeMs } from "../background/active-run-index.js";
9
9
  import { getAgentDir } from "../../shared/utils.js";
10
10
  import { isTerminalParallelHandoffChildStatus, readParallelHandoffManifest } from "./parallel-handoff.js";
11
- import { MACHINE_DIFF_OPTIONS, validateWorktreePatchRepresentsCurrentWorktree } from "./worktree.js";
11
+ import { MACHINE_DIFF_OPTIONS, isWorktreeCleanupTaskDone, validateWorktreePatchRepresentsCurrentWorktree } from "./worktree.js";
12
12
  export const WORKTREE_CLEANUP_PLAN_VERSION = 1;
13
13
  export const WORKTREE_CLEANUP_PLAN_TTL_MS = 30 * 60 * 1000;
14
14
  const MAX_DISCOVERED_HANDOFFS = 256;
@@ -650,7 +650,7 @@ function buildUnknownGitEntry(input) {
650
650
  return blockedEntry(entry, "unknown", "unknown", "no matching extension-owned handoff metadata was found");
651
651
  }
652
652
  function buildMissingMetadataEntry(input) {
653
- if (input.record.task.worktreeRemoved && input.record.task.branchRemoved)
653
+ if (isWorktreeCleanupTaskDone(input.record.task))
654
654
  return undefined;
655
655
  const pathValue = metadataRecordPath(input.record);
656
656
  const entry = buildEntryBase({ path: pathValue, branch: input.record.task.branch, source: "metadata", metadata: input.record, targetHead: input.targetHead });