@vicary/pi-subagents 0.88.1 → 0.89.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +51 -1
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-4QFZZV3O.js → chunk-4AL6LDBY.js} +3 -1
  5. package/bundle/{chunk-5EMPFFO4.js → chunk-4FFKVLBG.js} +4 -4
  6. package/bundle/{chunk-L4YY2TOE.js → chunk-5TXWZB73.js} +1 -1
  7. package/bundle/{chunk-YDZ7BZD5.js → chunk-77VQEATI.js} +1 -1
  8. package/bundle/{chunk-7OX6O7DQ.js → chunk-BERAWSQQ.js} +5 -5
  9. package/bundle/{chunk-LV3CPYXJ.js → chunk-C22YEYFZ.js} +4 -4
  10. package/bundle/{chunk-AZPP3G4N.js → chunk-DVOXHOTY.js} +34 -5
  11. package/bundle/{chunk-2HKPEANZ.js → chunk-JLZFSOEL.js} +26 -15
  12. package/bundle/{chunk-CPSUJHZE.js → chunk-KCDPTXHT.js} +39 -10
  13. package/bundle/{chunk-4MVDMA5C.js → chunk-LWH7IGI3.js} +21 -7
  14. package/bundle/{chunk-DSHQWGHO.js → chunk-MIX3MCIF.js} +96 -96
  15. package/bundle/{chunk-BKISQ5CJ.js → chunk-NLDROUCR.js} +56 -34
  16. package/bundle/{chunk-2DIEL4WG.js → chunk-OUM6SEVD.js} +2 -2
  17. package/bundle/{chunk-XIA5GSEU.js → chunk-Q4VH72JI.js} +2 -2
  18. package/bundle/{chunk-D32H53HM.js → chunk-R3NH5XAL.js} +1 -1
  19. package/bundle/{chunk-CGWNA6EJ.js → chunk-R5XS4CVE.js} +98 -29
  20. package/bundle/{chunk-V7SZMS6W.js → chunk-RHMU7SXN.js} +2 -2
  21. package/bundle/{chunk-4ZQBZDF3.js → chunk-SG3NCWZW.js} +86 -20
  22. package/bundle/{chunk-KXW62VBU.js → chunk-SWGB2P5J.js} +1 -1
  23. package/bundle/{chunk-6CG2VAG4.js → chunk-TRN65L4F.js} +1 -1
  24. package/bundle/{chunk-GDR2ILWY.js → chunk-TXC7WIPL.js} +51 -22
  25. package/bundle/{chunk-IYT7X46U.js → chunk-UNLGCAC4.js} +5 -5
  26. package/bundle/{chunk-PYKBTBY6.js → chunk-URKQZHVH.js} +9 -9
  27. package/bundle/{chunk-W6HIYD2Z.js → chunk-UUW7P6KJ.js} +1 -1
  28. package/bundle/{chunk-CYKNHFXB.js → chunk-VEEUXJDO.js} +1 -1
  29. package/bundle/{chunk-JQTHG2ID.js → chunk-WMGQNIP7.js} +75 -32
  30. package/bundle/{chunk-47ZN7NKR.js → chunk-YJIU5WF4.js} +1 -1
  31. package/bundle/{chunk-RMZAAXIR.js → chunk-YLU5JFW2.js} +2 -2
  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 +79 -23
  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/async-job-tracker.js +85 -9
  48. package/src/runs/background/async-status.d.ts +2 -0
  49. package/src/runs/background/async-status.js +8 -3
  50. package/src/runs/background/notify.d.ts +3 -0
  51. package/src/runs/background/notify.js +7 -2
  52. package/src/runs/background/run-status.js +3 -2
  53. package/src/runs/background/runner-child-launch.js +1 -0
  54. package/src/runs/background/subagent-runner.js +11 -8
  55. package/src/runs/foreground/execution.js +8 -7
  56. package/src/runs/foreground/subagent-executor.js +31 -5
  57. package/src/runs/shared/child-launch.d.ts +2 -0
  58. package/src/runs/shared/child-launch.js +1 -1
  59. package/src/runs/shared/child-session.d.ts +2 -1
  60. package/src/runs/shared/herdr-connection.d.ts +6 -0
  61. package/src/runs/shared/herdr-connection.js +11 -1
  62. package/src/runs/shared/herdr-machine.d.ts +2 -2
  63. package/src/runs/shared/herdr-machine.js +49 -22
  64. package/src/runs/shared/herdr-pane-host.d.ts +7 -19
  65. package/src/runs/shared/herdr-pane-host.js +48 -33
  66. package/src/runs/shared/herdr-pi-protocol.d.ts +1 -0
  67. package/src/runs/shared/herdr-pi-protocol.js +3 -2
  68. package/src/runs/shared/herdr-placed-run.d.ts +2 -12
  69. package/src/runs/shared/herdr-placed-run.js +10 -8
  70. package/src/runs/shared/kept-branch-text.d.ts +8 -0
  71. package/src/runs/shared/kept-branch-text.js +24 -0
  72. package/src/runs/shared/local-machine-access.d.ts +4 -1
  73. package/src/runs/shared/local-machine-access.js +6 -3
  74. package/src/runs/shared/mutation-evidence.d.ts +7 -1
  75. package/src/runs/shared/mutation-evidence.js +18 -2
  76. package/src/runs/shared/parallel-handoff.js +19 -7
  77. package/src/runs/shared/placed-run-owner.d.ts +4 -2
  78. package/src/runs/shared/placed-run-owner.js +15 -7
  79. package/src/runs/shared/rex-machine.d.ts +7 -3
  80. package/src/runs/shared/rex-machine.js +12 -9
  81. package/src/runs/shared/rex-pane-host.js +7 -27
  82. package/src/runs/shared/single-output.js +2 -2
  83. package/src/runs/shared/subagent-prompt-runtime.js +34 -0
  84. package/src/runs/shared/tool-availability.d.ts +4 -0
  85. package/src/runs/shared/tool-availability.js +7 -0
  86. package/src/runs/shared/worktree-cleanup-plan.js +2 -2
  87. package/src/runs/shared/worktree.d.ts +4 -14
  88. package/src/runs/shared/worktree.js +38 -8
  89. package/src/shared/types.d.ts +26 -2
  90. package/src/shared/utils.d.ts +2 -0
  91. package/src/shared/utils.js +9 -0
  92. package/src/workflows/workflow-child-summary.d.ts +2 -1
  93. package/src/workflows/workflow-child-summary.js +14 -6
@@ -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,42 @@ 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 active 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 active = new Set(pi.getActiveTools());
244
+ // Only an active tool must be declared: an extension may leave a registered tool inactive on
245
+ // purpose (pi-web-access's `web_enable`), and one that never registered is agent_start's case.
246
+ const undeclared = required.filter((name) => active.has(name) && !declared.has(name));
247
+ if (undeclared.length === 0)
248
+ return undefined;
249
+ const registered = new Set(pi.getAllTools().map((tool) => tool.name));
250
+ // A fork declares its parent's tools on purpose, to reuse the parent's prompt cache.
251
+ const uncallable = config.forkCacheKey ? [] : [...declared].filter((name) => !active.has(name));
252
+ config.toolDiagnostic?.({
253
+ ...(config.agent ? { agent: config.agent } : {}),
254
+ required: [...required],
255
+ available: [...registered],
256
+ missing: [],
257
+ undeclared,
258
+ ...(uncallable.length > 0 ? { uncallable } : {}),
259
+ });
260
+ ctx.abort();
261
+ return undefined;
262
+ });
263
+ }
232
264
  /** Installed after every other extension: a returned prompt freezes out sections added after it. */
233
265
  export function registerSubagentPromptBoundary(pi, config) {
266
+ if (config.requiredTools)
267
+ registerDeclaredToolCheck(pi, config, config.requiredTools);
234
268
  if (!rewritesChildPrompt(config))
235
269
  return;
236
270
  // 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 });
@@ -1,6 +1,6 @@
1
1
  import { type SetupCommandOptions, type SetupCommandResult } from "./worktree-setup-command.ts";
2
2
  import { type AuthorityPolicyConfig } from "../../policy/authority.ts";
3
- import type { ManagedWorktreeProvider, WorktreeNaming, WorktreeProvider } from "../../shared/types.ts";
3
+ import type { ManagedWorktreeProvider, ParallelHandoffCleanupTask, WorktreeNaming, WorktreeProvider } from "../../shared/types.ts";
4
4
  export declare const DEFAULT_WORKTREE_PROVIDER: WorktreeProvider;
5
5
  export declare const DEFAULT_WORKTREE_BASE_REF = "HEAD";
6
6
  export declare const DEFAULT_WORKTREE_BRANCH_PREFIX = "pi-subagents/";
@@ -59,19 +59,7 @@ export interface WorktreeDiff {
59
59
  patchPath: string;
60
60
  error?: string;
61
61
  }
62
- export interface WorktreeCleanupTask {
63
- recordedBaseDir?: string;
64
- index: number;
65
- path: string;
66
- branch: string;
67
- provider?: ManagedWorktreeProvider;
68
- naming?: WorktreeNaming;
69
- worktreeRemoved: boolean;
70
- branchRemoved: boolean;
71
- preserved?: boolean;
72
- reason?: string;
73
- errors?: string[];
74
- }
62
+ export type WorktreeCleanupTask = ParallelHandoffCleanupTask;
75
63
  export type WorktreeCleanupIntent = {
76
64
  kind: "preserve";
77
65
  capturedDiffs?: WorktreeDiff[];
@@ -179,6 +167,8 @@ export declare function shouldDeferWorktreeCwd(requested: WorktreeProvider | und
179
167
  export declare function resolveExpectedWorktreeAgentCwd(cwd: string, runId: string, index: number, baseDir?: string): string;
180
168
  export declare function createWorktrees(cwd: string, runId: string, count: number, options?: CreateWorktreesOptions): Promise<WorktreeSetup>;
181
169
  export declare function diffWorktrees(setup: WorktreeSetup, agents: string[], diffsDir: string): WorktreeDiff[];
170
+ /** A branch kept for its commits is a finished cleanup, the same as a removed one. */
171
+ export declare function isWorktreeCleanupTaskDone(task: Pick<WorktreeCleanupTask, "worktreeRemoved" | "branchRemoved" | "keptBranchTip">): boolean;
182
172
  export declare function cleanupWorktrees(setup: WorktreeSetup, intent?: WorktreeCleanupIntent): WorktreeCleanupReport;
183
173
  export declare function formatWorktreeDiffSummary(diffs: WorktreeDiff[]): string;
184
174
  export {};
@@ -220,8 +220,12 @@ async function probeWorktreeSource(tx, cwd) {
220
220
  // pi-subagents writes durable runtime state under .pi/subagents/ by default;
221
221
  // that state must not make managed isolation unusable for later runs.
222
222
  const status = await tx.gitChecked(toplevel, ["status", "--porcelain", "--", `:!${PROJECT_SUBAGENTS_RELATIVE_DIR}`]);
223
- if (status.trim().length > 0) {
224
- throw new Error("worktree isolation requires a clean git working tree. Commit or stash changes first.");
223
+ const changes = status.split("\n").filter((line) => line.trim().length > 0);
224
+ if (changes.length > 0) {
225
+ const shown = changes.slice(0, 10).map((line) => ` ${line}`);
226
+ if (changes.length > shown.length)
227
+ shown.push(` … and ${changes.length - shown.length} more`);
228
+ throw new Error(`worktree isolation requires a clean git working tree: ${toplevel} has ${changes.length} uncommitted change(s):\n${shown.join("\n")}\nCommit or stash them first.`);
225
229
  }
226
230
  return toplevel;
227
231
  }
@@ -1014,6 +1018,7 @@ function cleanupSingleWorktree(setup, worktree, intent) {
1014
1018
  const errors = [];
1015
1019
  let worktreeRemoved = false;
1016
1020
  let branchRemoved = false;
1021
+ let keptBranchTip;
1017
1022
  if (intent.kind === "preserve" && intent.cleanupBlocker) {
1018
1023
  return {
1019
1024
  index: worktree.index,
@@ -1124,12 +1129,32 @@ function cleanupSingleWorktree(setup, worktree, intent) {
1124
1129
  errors.push(`worktree removal failed: ${error instanceof Error ? error.message : String(error)}`);
1125
1130
  }
1126
1131
  if (worktreeRemoved) {
1127
- try {
1128
- runGitChecked(setup.cwd, ["branch", "-D", worktree.branch]);
1129
- branchRemoved = true;
1132
+ let deleteBranch = true;
1133
+ if (intent.kind === "preserve") {
1134
+ // The handoff patch keeps the child's content but not its commits, so a branch holding the only copy of them stays.
1135
+ try {
1136
+ const tip = runGitChecked(setup.cwd, ["rev-parse", "--verify", `refs/heads/${worktree.branch}^{commit}`]).trim();
1137
+ if (tip !== setup.baseCommit) {
1138
+ const containing = runGitChecked(setup.cwd, ["for-each-ref", "--contains", tip, "--format=%(refname)", "refs/heads", "refs/remotes", "refs/tags"]);
1139
+ if (!containing.split("\n").some((ref) => ref && ref !== `refs/heads/${worktree.branch}`)) {
1140
+ keptBranchTip = tip;
1141
+ deleteBranch = false;
1142
+ }
1143
+ }
1144
+ }
1145
+ catch (error) {
1146
+ deleteBranch = false;
1147
+ errors.push(`branch check failed: ${error instanceof Error ? error.message : String(error)}`);
1148
+ }
1130
1149
  }
1131
- catch (error) {
1132
- errors.push(`branch removal failed: ${error instanceof Error ? error.message : String(error)}`);
1150
+ if (deleteBranch) {
1151
+ try {
1152
+ runGitChecked(setup.cwd, ["branch", "-D", worktree.branch]);
1153
+ branchRemoved = true;
1154
+ }
1155
+ catch (error) {
1156
+ errors.push(`branch removal failed: ${error instanceof Error ? error.message : String(error)}`);
1157
+ }
1133
1158
  }
1134
1159
  }
1135
1160
  return {
@@ -1141,6 +1166,7 @@ function cleanupSingleWorktree(setup, worktree, intent) {
1141
1166
  ...(worktree.recordedBaseDir ? { recordedBaseDir: worktree.recordedBaseDir } : {}),
1142
1167
  worktreeRemoved,
1143
1168
  branchRemoved,
1169
+ ...(keptBranchTip ? { keptBranchTip } : {}),
1144
1170
  ...(errors.length ? { errors } : {}),
1145
1171
  };
1146
1172
  }
@@ -1324,6 +1350,10 @@ export function diffWorktrees(setup, agents, diffsDir) {
1324
1350
  setup.capturedDiffs = diffs;
1325
1351
  return diffs;
1326
1352
  }
1353
+ /** A branch kept for its commits is a finished cleanup, the same as a removed one. */
1354
+ export function isWorktreeCleanupTaskDone(task) {
1355
+ return task.worktreeRemoved && (task.branchRemoved || task.keptBranchTip !== undefined);
1356
+ }
1327
1357
  export function cleanupWorktrees(setup, intent = { kind: "preserve", ...(setup.capturedDiffs ? { capturedDiffs: setup.capturedDiffs } : {}) }) {
1328
1358
  assertWorktreeMutationAllowed();
1329
1359
  const tasks = [];
@@ -1340,7 +1370,7 @@ export function cleanupWorktrees(setup, intent = { kind: "preserve", ...(setup.c
1340
1370
  catch (error) {
1341
1371
  errors.push(`worktree prune failed: ${error instanceof Error ? error.message : String(error)}`);
1342
1372
  }
1343
- const state = tasks.every((task) => task.worktreeRemoved && task.branchRemoved) && pruned ? "complete" : "partial";
1373
+ const state = tasks.every(isWorktreeCleanupTaskDone) && pruned ? "complete" : "partial";
1344
1374
  return {
1345
1375
  state,
1346
1376
  tasks,
@@ -178,6 +178,11 @@ export interface WorkflowChildSummary {
178
178
  agent?: string;
179
179
  /** Human-readable display name for the child session, when derived at launch. */
180
180
  sessionName?: string;
181
+ /**
182
+ * The child's session file, once its launch resolved one. The file may not exist until the
183
+ * child writes its first entry; a host can follow it to show the child's transcript live.
184
+ */
185
+ sessionFile?: string;
181
186
  model?: string;
182
187
  thinking?: string;
183
188
  /** Present only while a synchronous foreground child is running. */
@@ -430,6 +435,8 @@ export interface ParallelHandoffCleanupTask {
430
435
  naming?: WorktreeNaming;
431
436
  worktreeRemoved: boolean;
432
437
  branchRemoved: boolean;
438
+ /** Tip of a branch cleanup kept because no other branch, remote branch, or tag holds its commits. */
439
+ keptBranchTip?: string;
433
440
  preserved?: boolean;
434
441
  reason?: string;
435
442
  errors?: string[];
@@ -496,6 +503,10 @@ export interface ParallelHandoffReference {
496
503
  childCount: number;
497
504
  changedPatches: number;
498
505
  cleanupState: "complete" | "partial";
506
+ keptBranches?: Array<{
507
+ branch: string;
508
+ tip: string;
509
+ }>;
499
510
  cleanupEligibility?: CleanupEligibility;
500
511
  }
501
512
  export interface AgentContract {
@@ -889,6 +900,11 @@ export interface AgentProgress {
889
900
  agent: string;
890
901
  /** Human-readable display name for the child's session, when derived at launch. */
891
902
  sessionName?: string;
903
+ /**
904
+ * The child's session file, from launch, when it has one. The file may not exist until the
905
+ * child writes its first entry; a host can follow it to show the child's transcript live.
906
+ */
907
+ sessionFile?: string;
892
908
  status: "pending" | "running" | "completed" | "failed" | "detached";
893
909
  progressText?: string;
894
910
  progressUpdatedAt?: number;
@@ -1720,8 +1736,16 @@ export interface RexSshMachineReference {
1720
1736
  cwd: string;
1721
1737
  }
1722
1738
  export type RexMachineReference = RexLocalMachineReference | RexSshMachineReference;
1723
- /** Where a placed native Pi child runs. */
1724
- export type PlacementMachineReference = HerdrMachineReference | RexMachineReference;
1739
+ /** `machine: "local"` inside a Herdr pane: a tab in the parent's own Herdr session on this machine, reached over its local socket. `socket` and `session` are recorded in the parent at resolution time; `cwd` is the real local launch directory. */
1740
+ export interface HerdrLocalMachineReference {
1741
+ provider: "herdr";
1742
+ id: "local";
1743
+ socket: string;
1744
+ session?: string;
1745
+ cwd: string;
1746
+ }
1747
+ /** Where a placed native Pi child runs. A reference without `target` is on this machine. */
1748
+ export type PlacementMachineReference = HerdrMachineReference | HerdrLocalMachineReference | RexMachineReference;
1725
1749
  export interface ExternalCliMachineStatus extends HerdrMachineReference {
1726
1750
  remoteGit?: HerdrRemoteGitStatus;
1727
1751
  }
@@ -11,6 +11,8 @@ export declare function getProjectConfigDir(projectRoot: string): string;
11
11
  export declare function getAgentDir(): string;
12
12
  export declare function pruneStatusCacheForAsyncRoot(asyncDirRoot: string, runIds: Iterable<string>): number;
13
13
  export declare function resolveChildCwd(baseCwd: string, childCwd: string | undefined): string;
14
+ /** A `readStatus(asyncDir)` error caused by permissions on that run's own status file, which says nothing about whether its runner is alive. */
15
+ export declare function isStatusAccessError(error: unknown, asyncDir: string): boolean;
14
16
  export declare function readStatus(asyncDir: string): AsyncStatus | null;
15
17
  export declare function getLastActivity(outputFile: string | undefined): string;
16
18
  export declare function findLatestSessionFile(sessionDir: string): string | null;
@@ -119,6 +119,15 @@ function isNotFoundError(error) {
119
119
  && "code" in error
120
120
  && error.code === "ENOENT";
121
121
  }
122
+ /** A `readStatus(asyncDir)` error caused by permissions on that run's own status file, which says nothing about whether its runner is alive. */
123
+ export function isStatusAccessError(error, asyncDir) {
124
+ const code = error?.cause?.code;
125
+ if (code !== "EACCES" && code !== "EPERM")
126
+ return false;
127
+ const message = error instanceof Error ? error.message : "";
128
+ const quotedPath = `'${path.join(asyncDir, "status.json")}':`;
129
+ return message.startsWith(`Failed to inspect async status file ${quotedPath}`) || message.startsWith(`Failed to read async status file ${quotedPath}`);
130
+ }
122
131
  export function readStatus(asyncDir) {
123
132
  if (Buffer.byteLength(path.basename(asyncDir), "utf-8") > 255) {
124
133
  return null;
@@ -14,10 +14,11 @@ export declare function workflowChildSummary(input: {
14
14
  steps?: NonNullable<AsyncStatus["steps"]>;
15
15
  /** In-memory snapshots from synchronous child callbacks, keyed by workflow key. */
16
16
  progress?: ReadonlyMap<string, WorkflowChildLiveProgress>;
17
- /** Agent and run id each child launched with, keyed by workflow key; known before an async child settles. */
17
+ /** Agent, run id and session file each child launched with, keyed by workflow key; known before an async child settles. */
18
18
  launches?: ReadonlyMap<string, {
19
19
  agent: string;
20
20
  runId?: string;
21
+ sessionFile?: string;
21
22
  }>;
22
23
  }): WorkflowChildSummary;
23
24
  export declare function parseWorkflowChildSummary(value: unknown): WorkflowChildSummary | undefined;
@@ -2,6 +2,8 @@ import { hashedSegment } from "../runs/background/index-segment.js";
2
2
  const KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
3
3
  const TERMINAL_STATES = new Set(["completed", "failed", "paused", "stopped", "rejected", "detached"]);
4
4
  const MAX_REQUIRED_ID_BYTES = 4_096;
5
+ /** Linux PATH_MAX: a longer session path cannot be opened anyway. */
6
+ const MAX_SESSION_FILE_BYTES = 4_096;
5
7
  const ACTIVITY_COUNTERS = ["currentToolStartedAt", "lastActivityAt", "durationMs", "toolCount", "turnCount", "tokens", "inputTokens", "outputTokens"];
6
8
  export function workflowChildProgress(progress) {
7
9
  return {
@@ -71,6 +73,7 @@ export function workflowChildSummary(input) {
71
73
  ...(bounded(entry.runId, 256) ? { runId: bounded(entry.runId, 256) } : {}),
72
74
  ...(previous?.agent ? { agent: previous.agent } : {}),
73
75
  ...(previous?.sessionName ? { sessionName: previous.sessionName } : {}),
76
+ ...(previous?.sessionFile ? { sessionFile: previous.sessionFile } : {}),
74
77
  ...(previous?.model ? { model: previous.model } : {}),
75
78
  ...(previous?.thinking ? { thinking: previous.thinking } : {}),
76
79
  });
@@ -94,6 +97,7 @@ export function workflowChildSummary(input) {
94
97
  ...(bounded(step.runId, 256) ? { runId: bounded(step.runId, 256) } : {}),
95
98
  ...(launchResolved && bounded(step.agent, 256) ? { agent: bounded(step.agent, 256) } : {}),
96
99
  ...(bounded(step.sessionName, 256) ? { sessionName: bounded(step.sessionName, 256) } : {}),
100
+ ...(bounded(step.sessionFile, MAX_SESSION_FILE_BYTES) ? { sessionFile: step.sessionFile } : {}),
97
101
  ...(bounded(step.model, 256) ? { model: bounded(step.model, 256) } : {}),
98
102
  ...(bounded(step.thinking, 32) ? { thinking: bounded(step.thinking, 32) } : {}),
99
103
  });
@@ -109,6 +113,7 @@ export function workflowChildSummary(input) {
109
113
  ...(bounded(child.runId, 256) ? { runId: bounded(child.runId, 256) } : {}),
110
114
  ...(bounded(child.agent, 256) ? { agent: bounded(child.agent, 256) } : {}),
111
115
  ...(bounded(result?.sessionName, 256) ? { sessionName: bounded(result?.sessionName, 256) } : {}),
116
+ ...(bounded(result?.sessionFile, MAX_SESSION_FILE_BYTES) ? { sessionFile: result?.sessionFile } : {}),
112
117
  ...(bounded(result?.model, 256) ? { model: bounded(result?.model, 256) } : {}),
113
118
  ...(bounded(result?.thinking, 32) ? { thinking: bounded(result?.thinking, 32) } : {}),
114
119
  });
@@ -121,12 +126,15 @@ export function workflowChildSummary(input) {
121
126
  }
122
127
  for (const [key, launch] of input.launches ?? []) {
123
128
  const row = rows.get(key);
124
- if (!row || row.state !== "running")
129
+ if (!row)
125
130
  continue;
131
+ const running = row.state === "running";
126
132
  rows.set(key, {
127
133
  ...row,
128
- ...(!row.runId && bounded(launch.runId, 256) ? { runId: launch.runId } : {}),
129
- ...(!row.agent && bounded(launch.agent, 256) ? { agent: launch.agent } : {}),
134
+ ...(running && !row.runId && bounded(launch.runId, 256) ? { runId: launch.runId } : {}),
135
+ ...(running && !row.agent && bounded(launch.agent, 256) ? { agent: launch.agent } : {}),
136
+ // Finished rows keep it too: live updates carry no child results, so this is a settled child's only transcript link until the workflow returns.
137
+ ...(!row.sessionFile && bounded(launch.sessionFile, MAX_SESSION_FILE_BYTES) ? { sessionFile: launch.sessionFile } : {}),
130
138
  });
131
139
  }
132
140
  for (const [key, progress] of input.progress ?? []) {
@@ -169,21 +177,21 @@ export function parseWorkflowChildSummary(value) {
169
177
  if (!row || typeof row !== "object" || Array.isArray(row))
170
178
  throw new Error("workflowChildren child row is invalid.");
171
179
  const child = row;
172
- if (Object.keys(child).some((key) => !["childId", "runId", "agent", "sessionName", "model", "thinking", "state", "activity"].includes(key)))
180
+ if (Object.keys(child).some((key) => !["childId", "runId", "agent", "sessionName", "sessionFile", "model", "thinking", "state", "activity"].includes(key)))
173
181
  throw new Error("workflowChildren child row has unsupported fields.");
174
182
  if (typeof child.childId !== "string" || !KEY_PATTERN.test(child.childId))
175
183
  throw new Error("workflowChildren childId is invalid.");
176
184
  const state = child.state;
177
185
  if (state !== "pending" && state !== "running" && state !== "completed" && state !== "failed" && state !== "paused" && state !== "stopped" && state !== "rejected" && state !== "detached")
178
186
  throw new Error("workflowChildren child state is invalid.");
179
- for (const [field, maxBytes] of [["runId", 256], ["agent", 256], ["sessionName", 256], ["model", 256], ["thinking", 32]]) {
187
+ for (const [field, maxBytes] of [["runId", 256], ["agent", 256], ["sessionName", 256], ["sessionFile", MAX_SESSION_FILE_BYTES], ["model", 256], ["thinking", 32]]) {
180
188
  if (child[field] !== undefined && bounded(child[field], maxBytes) === undefined)
181
189
  throw new Error(`workflowChildren child ${field} is invalid.`);
182
190
  }
183
191
  const activity = parseActivity(child.activity);
184
192
  if (activity && state !== "running")
185
193
  throw new Error("workflowChildren child activity requires running state.");
186
- return { childId: child.childId, state, ...(activity ? { activity } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(child.agent ? { agent: child.agent } : {}), ...(child.sessionName ? { sessionName: child.sessionName } : {}), ...(child.model ? { model: child.model } : {}), ...(child.thinking ? { thinking: child.thinking } : {}) };
194
+ return { childId: child.childId, state, ...(activity ? { activity } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(child.agent ? { agent: child.agent } : {}), ...(child.sessionName ? { sessionName: child.sessionName } : {}), ...(child.sessionFile ? { sessionFile: child.sessionFile } : {}), ...(child.model ? { model: child.model } : {}), ...(child.thinking ? { thinking: child.thinking } : {}) };
187
195
  });
188
196
  if (new Set(children.map((child) => child.childId)).size !== children.length)
189
197
  throw new Error("workflowChildren has duplicate childId values.");