@vicary/pi-subagents 0.88.0 → 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 (106) hide show
  1. package/CHANGELOG.md +54 -1
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +3 -3
  4. package/bundle/{chunk-6EUQPQY7.js → chunk-443LPCRI.js} +5 -5
  5. package/bundle/{chunk-4QFZZV3O.js → chunk-4AL6LDBY.js} +3 -1
  6. package/bundle/{chunk-CKLZ5FGU.js → chunk-4ALRHKGE.js} +1 -1
  7. package/bundle/{chunk-SVIXQDIV.js → chunk-6JD4XCA4.js} +77 -19
  8. package/bundle/{chunk-XZXYPZUT.js → chunk-7JLNWAMO.js} +54 -36
  9. package/bundle/{chunk-RHYVKQQL.js → chunk-7W2IQFP4.js} +4 -4
  10. package/bundle/{chunk-W6HIYD2Z.js → chunk-A3INCQ6Z.js} +1 -1
  11. package/bundle/{chunk-JYHTDTOZ.js → chunk-CFIYO2IV.js} +5 -5
  12. package/bundle/{chunk-CYKNHFXB.js → chunk-EPMRDKQT.js} +1 -1
  13. package/bundle/{chunk-6PR44R7E.js → chunk-ETDE2VYK.js} +2 -2
  14. package/bundle/{chunk-4MVDMA5C.js → chunk-GHJ6BH5U.js} +13 -7
  15. package/bundle/{chunk-IZEKQEY4.js → chunk-HSHLPYCQ.js} +27 -10
  16. package/bundle/{chunk-3MFYKBKI.js → chunk-HZDLR73C.js} +4 -4
  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-TDJKY2NE.js → chunk-LEPIY76E.js} +34 -5
  21. package/bundle/{chunk-BW5JLKIU.js → chunk-MJHQIUU7.js} +68 -41
  22. package/bundle/{chunk-47ZN7NKR.js → chunk-NONHDYXE.js} +1 -1
  23. package/bundle/{chunk-PJSOS2Q4.js → chunk-NQ26PJSQ.js} +96 -96
  24. package/bundle/{chunk-AOSILI5R.js → chunk-OVBUEVOT.js} +95 -49
  25. package/bundle/{chunk-NVGQE2H2.js → chunk-PFZZMVD5.js} +75 -32
  26. package/bundle/{chunk-YDZ7BZD5.js → chunk-S77ZKDLS.js} +1 -1
  27. package/bundle/{chunk-3DT5X2QC.js → chunk-SLLZJ5EC.js} +50 -18
  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-YZPVALSQ.js → chunk-WW6GQBBS.js} +4 -4
  31. package/bundle/{chunk-CTPAE36Y.js → chunk-YARY7JWU.js} +22 -0
  32. package/bundle/{chunk-GDR2ILWY.js → chunk-ZSCIHMUI.js} +50 -22
  33. package/bundle/control-channel.js +2 -2
  34. package/bundle/index.js +2 -2
  35. package/bundle/intercom-bridge.js +2 -2
  36. package/bundle/preflight.js +9 -9
  37. package/bundle/project-panes.js +3 -3
  38. package/bundle/required-child-extensions.js +1 -1
  39. package/docs/agents.md +14 -6
  40. package/docs/configuration.md +2 -0
  41. package/docs/extension-api.md +1 -1
  42. package/docs/tool-reference.md +1 -1
  43. package/docs/workflows.md +8 -4
  44. package/package.json +2 -2
  45. package/src/extension/herdr-pi-bridge.js +78 -22
  46. package/src/extension/index.d.ts +1 -1
  47. package/src/extension/index.js +43 -20
  48. package/src/extension/schemas.js +1 -1
  49. package/src/extension/subagent-launch-tool.d.ts +6 -2
  50. package/src/extension/subagent-launch-tool.js +13 -9
  51. package/src/extension/subagent-options.js +5 -0
  52. package/src/intercom/result-intercom.js +3 -2
  53. package/src/runs/background/notify.d.ts +3 -0
  54. package/src/runs/background/notify.js +7 -2
  55. package/src/runs/background/run-status.js +3 -2
  56. package/src/runs/background/runner-child-launch.js +1 -0
  57. package/src/runs/background/stale-run-reconciler.js +17 -8
  58. package/src/runs/background/subagent-runner.js +11 -8
  59. package/src/runs/foreground/execution.js +8 -7
  60. package/src/runs/foreground/subagent-executor.js +42 -11
  61. package/src/runs/shared/child-launch.d.ts +2 -0
  62. package/src/runs/shared/child-launch.js +7 -4
  63. package/src/runs/shared/child-session.d.ts +3 -2
  64. package/src/runs/shared/child-session.js +3 -27
  65. package/src/runs/shared/herdr-connection.d.ts +6 -0
  66. package/src/runs/shared/herdr-connection.js +11 -1
  67. package/src/runs/shared/herdr-machine.d.ts +2 -2
  68. package/src/runs/shared/herdr-machine.js +47 -22
  69. package/src/runs/shared/herdr-pane-host.d.ts +7 -19
  70. package/src/runs/shared/herdr-pane-host.js +48 -33
  71. package/src/runs/shared/herdr-pi-protocol.d.ts +1 -0
  72. package/src/runs/shared/herdr-pi-protocol.js +3 -2
  73. package/src/runs/shared/herdr-placed-run.d.ts +2 -12
  74. package/src/runs/shared/herdr-placed-run.js +10 -8
  75. package/src/runs/shared/kept-branch-text.d.ts +8 -0
  76. package/src/runs/shared/kept-branch-text.js +24 -0
  77. package/src/runs/shared/local-machine-access.d.ts +4 -1
  78. package/src/runs/shared/local-machine-access.js +6 -3
  79. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +5 -3
  80. package/src/runs/shared/mcp-direct-tool-allowlist.js +5 -4
  81. package/src/runs/shared/mutation-evidence.d.ts +7 -1
  82. package/src/runs/shared/mutation-evidence.js +18 -2
  83. package/src/runs/shared/parallel-handoff.js +19 -7
  84. package/src/runs/shared/placed-run-owner.d.ts +4 -2
  85. package/src/runs/shared/placed-run-owner.js +15 -7
  86. package/src/runs/shared/rex-machine.d.ts +7 -3
  87. package/src/runs/shared/rex-machine.js +12 -9
  88. package/src/runs/shared/rex-pane-host.js +7 -27
  89. package/src/runs/shared/single-output.js +2 -2
  90. package/src/runs/shared/subagent-prompt-runtime.js +33 -0
  91. package/src/runs/shared/tool-availability.d.ts +4 -0
  92. package/src/runs/shared/tool-availability.js +7 -0
  93. package/src/runs/shared/worktree-cleanup-plan.js +2 -2
  94. package/src/runs/shared/worktree.d.ts +4 -14
  95. package/src/runs/shared/worktree.js +38 -8
  96. package/src/shared/compaction-interruption.d.ts +9 -0
  97. package/src/shared/compaction-interruption.js +47 -0
  98. package/src/shared/parent-wake.d.ts +3 -2
  99. package/src/shared/parent-wake.js +14 -3
  100. package/src/shared/required-child-extensions.d.ts +2 -0
  101. package/src/shared/required-child-extensions.js +27 -0
  102. package/src/shared/types.d.ts +26 -2
  103. package/src/tui/fleet.d.ts +7 -2
  104. package/src/tui/fleet.js +22 -0
  105. package/src/workflows/workflow-child-summary.d.ts +2 -1
  106. package/src/workflows/workflow-child-summary.js +14 -6
package/docs/workflows.md CHANGED
@@ -149,7 +149,9 @@ The host resolves the name and validates bounded plain-JSON `args` before starti
149
149
 
150
150
  ### Approving workflow children in permission extensions
151
151
 
152
- Before a workflow starts a child, pi-subagents makes a nested `subagent_launch` tool call, so permission extensions see it in their `tool_call` handler like any other tool call. This covers reply-block, file and named workflows, and `chain` and `tasks`. The call's input is `{ workflowRunId, key, agent?, task?, cwd?, model?, async?, worktree?, resume?, commands?, output? }`. `cwd` is the absolute directory the child starts in. It is left out for a resumed child, which keeps its earlier directory, and for a child placed on another machine. `commands` lists, in run order, the shell commands the child's `gate`, `acceptance.verify` or agent `acceptance` will run on this machine after the child finishes, each `{ command, cwd?, env? }`. A command's `cwd` is absolute and is left out when the child's is; for a `worktree: true` child it names the source directory, because the worktree does not exist yet. `env` lists only the variables the command sets on top of the parent's environment. `output` is the absolute path of the file the child's `output` writes. The other optional fields appear when the child request sets them. A blocked or failed call stops that child, so its commands never run and its output file is never written; it fails with `Workflow child '<key>' was not started: …` and the block reason. Allowed calls do nothing else. The tool is not declared to the model.
152
+ Before a workflow starts a child, pi-subagents makes a nested `subagent_launch` tool call, so permission extensions see it in their `tool_call` handler like any other tool call. This covers reply-block, file and named workflows, and `chain` and `tasks`. The call's input is `{ workflowRunId, key, agent?, task?, cwd?, model?, async?, worktree?, resume?, commands?, output? }`. `cwd` is the absolute directory the child starts in. It is left out for a resumed child, which keeps its earlier directory, and for a child placed on another machine. `commands` lists, in run order, the shell commands the child's `gate`, `acceptance.verify` or agent `acceptance` will run on this machine after the child finishes, each `{ command, cwd?, env? }`. A command's `cwd` is absolute and is left out when the child's is; for a `worktree: true` child it names the source directory, because the worktree does not exist yet. `env` lists only the variables the command sets on top of the parent's environment. `output` is the absolute path of the file the child's `output` writes. The other optional fields appear when the child request sets them. A blocked or failed call stops that child, so its commands never run and its output file is never written; it fails with `Workflow child '<key>' was not started: …` and the block reason. The tool is not declared to the model.
153
+
154
+ A handler may also change `task` in place (`event.input.task = …`). A freshly launched child then receives the changed text, after `{previous}` is filled in and before any fork preamble is added. Changes to any other field, and to a resumed child's message, are ignored. Handlers run in registration order, so one registered earlier sees the original text.
153
155
 
154
156
  Extensions that ask about tools they have no rule for ask once per workflow child until you allow `subagent_launch`. Ones that deny unknown tools without a UI, as in `pi -p`, refuse every workflow child until you allow it.
155
157
 
@@ -475,9 +477,11 @@ known, or for explicit emergency hotfix lanes.
475
477
 
476
478
  For watched same-repo workflows, pass `async:false` only when the parent must block until completion. That blocking mode also shows the live in-chat workflow card. `chatProgress` can force `off` or `live-card` when the automatic policy is not what you want. Blocking and async workflows have no implicit runtime deadline; explicitly configured deadlines still apply. See the [tool reference](tool-reference.md) for the full parameter list.
477
479
 
478
- Synchronous workflows publish trace and `emit(...)` updates through the tool update callback regardless of `chatProgress`, including RPC/headless and cross-repository runs. These updates include `details.workflow` and `details.workflowChildren`; `chatProgress: "off"` disables the live card, not transport progress. Once a child launches, its running row carries its `agent` and `runId`; for a child running in the background, that `runId` is the id of its run node in the `subagent-async` snapshot. Running foreground child rows additionally expose bounded `activity` (current tool, timing, and counters), plus resolved model/thinking when available, keyed by `childId`. Activity-only updates coalesce over 100 ms; lifecycle updates remain immediate. Activity clears when children settle, and is not persisted for async workflows. Tool names are limited to 256 UTF-8 bytes and each activity object is below 2 KiB (including JSON escaping); arguments and transcripts are not forwarded.
480
+ Synchronous workflows publish trace and `emit(...)` updates through the tool update callback regardless of `chatProgress`, including RPC/headless and cross-repository runs. These updates include `details.workflow` and `details.workflowChildren`; `chatProgress: "off"` disables the live card, not transport progress. Once a child launches, its running row carries its `agent` and `runId`; for a child running in the background, that `runId` is the id of its run node in the `subagent-async` snapshot. Rows also carry the child's `sessionFile` once its launch resolves one, so a host can follow the child's transcript while it runs; the file may appear only once the child writes its first entry. Running foreground child rows additionally expose bounded `activity` (current tool, timing, and counters), plus resolved model/thinking when available, keyed by `childId`. Activity-only updates coalesce over 100 ms; lifecycle updates remain immediate. Activity clears when children settle, and is not persisted for async workflows. Tool names are limited to 256 UTF-8 bytes and each activity object is below 2 KiB (including JSON escaping); arguments and transcripts are not forwarded.
481
+
482
+ The workflow result text keeps the Return, Emitted, and Console sections, and a failed workflow's error, under 200 KB and 5000 lines, or under `maxOutput` when set. Each call-trace error is cut to 500 characters. A cut adds a `[TRUNCATED: ... - full output at <path>]` line. The full text goes to the workflow `output` file when one is set and the workflow completed, otherwise to `<run>_workflow-result.md` in the run's artifacts directory, outside the `outputs/` tree where children save their reports. That file has the same retention as the other run artifacts: age-based cleanup removes it from temp and session artifact directories, and `artifactDir: "project"` files are kept. The status line, the rest of each trace line, warnings, and output-path mappings are never cut. Async completion notices and `action: "status"` show short previews; a cut preview or async error ends in `…` and names the run's `status.json`, which holds the full `workflow.value`, `workflow.emits`, and `error`.
479
483
 
480
- The workflow result text keeps the Return, Emitted, and Console sections, and a failed workflow's error, under 200 KB and 5000 lines, or under `maxOutput` when set. Each call-trace error is cut to 500 characters. A cut adds a `[TRUNCATED: ... - full output at <path>]` line. The full text goes to the workflow `output` file when one is set, otherwise to `<run>_workflow-result.md` in the run's artifacts directory, outside the `outputs/` tree where children save their reports. That file has the same retention as the other run artifacts: age-based cleanup removes it from temp and session artifact directories, and `artifactDir: "project"` files are kept. The status line, the rest of each trace line, warnings, and output-path mappings are never cut. Async completion notices and `action: "status"` show short previews; a cut preview or async error ends in `…` and names the run's `status.json`, which holds the full `workflow.value`, `workflow.emits`, and `error`.
484
+ A workflow removes any earlier file at its `output` path when it starts, and writes the file only when it completes. A failed, stopped, or paused workflow leaves the path alone, so the file is missing or holds a report written during the run, never this run's error. A relaunch of an interrupted workflow never removes the file, since a child of the interrupted run may have saved its report there, so a file found after a relaunch may be stale. The error is in the tool result, the completion notice, and `status.json`.
481
485
 
482
486
  The legacy `/chain`, `/parallel`, and `/run-chain` commands are not registered.
483
487
 
@@ -497,7 +501,7 @@ const [api, ui] = await runs.all([
497
501
  return { api: api.artifactPaths, ui: ui.artifactPaths };
498
502
  ```
499
503
 
500
- Each child uses the existing worktree lifecycle: it branches from clean HEAD, journals ownership before launch, captures a patch and handoff manifest, then removes cleanly captured temporary worktrees and branches. The handoff manifest path remains available in the child's `artifactPaths`; return or emit it when the orchestrator needs to apply or inspect the patches. `worktree.cleanup` scans only the repository's project artifacts, so a workflow child's worktree is reported as unknown until you pass that manifest as `options.handoffPath`; worktrees of retained, resumable children are then kept rather than removed. `runs.ref` stays concise and intentionally omits full paths.
504
+ Each child uses the existing worktree lifecycle: it branches from clean HEAD, journals ownership before launch, captures a patch and handoff manifest, then removes cleanly captured temporary worktrees and branches. A branch holding commits that no other branch, remote branch, or tag contains is kept and recorded as `keptBranchTip` on its cleanup task in the handoff manifest (the child's result does not mention it); delete it yourself once those commits have landed. The handoff manifest path remains available in the child's `artifactPaths`; return or emit it when the orchestrator needs to apply or inspect the patches. `worktree.cleanup` scans only the repository's project artifacts, so a workflow child's worktree is reported as unknown until you pass that manifest as `options.handoffPath`; worktrees of retained, resumable children are then kept rather than removed. `runs.ref` stays concise and intentionally omits full paths.
501
505
 
502
506
  A top-level `{ workflow: true, worktree: true }` makes isolation the default for every workflow child. An individual child can override that default with `worktree: false`. Keep one writer when parallel writes are not intentionally isolated.
503
507
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@vicary/pi-subagents",
4
- "version": "0.88.0",
4
+ "version": "0.89.0",
5
5
  "description": "Pi extension for single-agent delegation and scripted multi-agent workflows",
6
6
  "author": "Nico Bailon",
7
7
  "license": "MIT",
@@ -135,5 +135,5 @@
135
135
  "./prompts"
136
136
  ]
137
137
  },
138
- "gitHead": "dc58b0272437b63b167428647c94a09df31675fe"
138
+ "gitHead": "0551e1ca035818cefc5493b2a00ca7f7c7e1ec51"
139
139
  }
@@ -4,7 +4,7 @@ import * as net from "node:net";
4
4
  import * as path from "node:path";
5
5
  import { Type } from "typebox";
6
6
  import packageJson from "../../package.json" with { type: "json" };
7
- import { encodeHerdrPiFrame, HERDR_PI_MAX_FRAME_BYTES, HERDR_PI_PROTOCOL, HERDR_PI_RUN_ENV, HERDR_PI_RUNTIME_DIR_ENV, HerdrPiFrameDecoder, validateHerdrPiRunId } from "../runs/shared/herdr-pi-protocol.js";
7
+ import { encodeHerdrPiFrame, HERDR_PI_MAX_ACCEPTANCE_PROMPT_BYTES, HERDR_PI_MAX_FRAME_BYTES, HERDR_PI_PROTOCOL, HERDR_PI_RUN_ENV, HERDR_PI_RUNTIME_DIR_ENV, HerdrPiFrameDecoder, validateHerdrPiRunId } from "../runs/shared/herdr-pi-protocol.js";
8
8
  import { discoverAgents } from "../agents/agents.js";
9
9
  import { buildSkillInjection, resolveSkills } from "../agents/skills.js";
10
10
  import { buildAgentMemoryInjection } from "../agents/agent-memory.js";
@@ -24,6 +24,40 @@ function gitEvidence(cwd) {
24
24
  const dirty = run(["status", "--porcelain"]);
25
25
  return { ...(head.status === 0 ? { head: head.stdout.trim() } : {}), ...(branch.status === 0 ? { branch: branch.stdout.trim() } : {}), dirty: Boolean(dirty.stdout.trim()) };
26
26
  }
27
+ const TOOL_ARGS_FRAME_BUDGET = 64 * 1024;
28
+ // A frame over HERDR_PI_MAX_FRAME_BYTES throws on write and on every journal replay, so oversized args (a whole file
29
+ // for write) keep only short top-level scalars: the path, command and supervisor reason are what the parent reads.
30
+ function boundedToolArgs(args) {
31
+ if (!args || typeof args !== "object" || Array.isArray(args) || Buffer.byteLength(JSON.stringify(args)) <= TOOL_ARGS_FRAME_BUDGET)
32
+ return args;
33
+ const shortened = Object.fromEntries(Object.entries(args).flatMap(([key, value]) => typeof value === "string" ? [[key, value.slice(0, 4096)]] : typeof value === "number" || typeof value === "boolean" ? [[key, value]] : []));
34
+ return Buffer.byteLength(JSON.stringify(shortened)) <= TOOL_ARGS_FRAME_BUDGET ? shortened : {};
35
+ }
36
+ // Leaves room under HERDR_PI_MAX_FRAME_BYTES for the frame around the message. A read image alone can be 4.5 MB of base64.
37
+ const MESSAGE_FRAME_BUDGET = HERDR_PI_MAX_FRAME_BYTES - 64 * 1024;
38
+ const fitsMessageBudget = (value) => Buffer.byteLength(JSON.stringify(value)) <= MESSAGE_FRAME_BUDGET;
39
+ const omittedText = (what, bytes) => `[${what} omitted by the pi-subagents bridge: ${bytes} bytes did not fit in one bridge frame]`;
40
+ function boundedMessage(message) {
41
+ if (fitsMessageBudget(message))
42
+ return message;
43
+ const record = message;
44
+ const content = Array.isArray(record.content) ? record.content.map((block) => {
45
+ if (block.type === "image")
46
+ return { type: "text", text: omittedText(`Image (${String(block.mimeType)})`, Buffer.byteLength(String(block.data))) };
47
+ if (block.type === "text" && typeof block.text === "string" && block.text.length > 65_536)
48
+ return { type: "text", text: `${block.text.slice(0, 65_536)}\n${omittedText("The rest of this text", Buffer.byteLength(block.text.slice(65_536)))}` };
49
+ if (block.type === "thinking" && typeof block.thinking === "string")
50
+ return { type: "thinking", thinking: block.thinking.length > 4096 ? `${block.thinking.slice(0, 4096)}\n${omittedText("The rest of this thinking", Buffer.byteLength(block.thinking.slice(4096)))}` : block.thinking };
51
+ if (block.type === "toolCall")
52
+ return { ...block, arguments: boundedToolArgs(block.arguments) };
53
+ return block;
54
+ }) : record.content;
55
+ const shrunk = { ...record, content, details: undefined };
56
+ if (fitsMessageBudget(shrunk))
57
+ return shrunk;
58
+ const kept = Object.fromEntries(["role", "toolCallId", "toolName", "isError", "api", "provider", "model", "usage", "stopReason", "timestamp"].filter((key) => key in record).map((key) => [key, record[key]]));
59
+ return { ...kept, ...(typeof record.errorMessage === "string" ? { errorMessage: record.errorMessage.slice(0, 4096) } : {}), content: [{ type: "text", text: omittedText("This message", Buffer.byteLength(JSON.stringify(message))) }] };
60
+ }
27
61
  export function resolveRemoteHerdrResources(cwd, resources, remoteDefaultTools = []) {
28
62
  if (!/^[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 && (!Array.isArray(resources.reads) || resources.reads.some((name) => typeof name !== "string"))))
29
63
  throw new Error("Remote logical resource names are invalid.");
@@ -51,21 +85,12 @@ export default function registerHerdrPiBridge(pi) {
51
85
  const runDir = process.env[HERDR_PI_RUNTIME_DIR_ENV];
52
86
  if (!runDir || !path.isAbsolute(runDir) || fs.lstatSync(runDir).isSymbolicLink())
53
87
  throw new Error("Herdr bridge runtime directory was not authoritatively provisioned.");
54
- fs.chmodSync(runDir, 0o700);
55
88
  const socketPath = path.join(runDir, "bridge.sock");
56
89
  const manifestPath = path.join(runDir, "manifest.json");
57
- for (const candidate of [socketPath, manifestPath]) {
58
- try {
59
- const stat = fs.lstatSync(candidate);
60
- if (stat.isSymbolicLink())
61
- throw new Error(`Refusing symlink at '${candidate}'.`);
62
- fs.rmSync(candidate, { force: true });
63
- }
64
- catch (error) {
65
- if (error.code !== "ENOENT")
66
- throw error;
67
- }
68
- }
90
+ // An in-process SDK session (createAgentSession without a resourceLoader) runs this factory again in the same child and may
91
+ // start its own session, so the factory touches no files: the first session to start claims the runtime directory for the process.
92
+ const claims = (globalThis[Symbol.for("pi-subagents.herdr-bridge-claims")] ??= new Set());
93
+ let claimed = false;
69
94
  let client;
70
95
  let context;
71
96
  let nativeSessionId;
@@ -80,8 +105,12 @@ export default function registerHerdrPiBridge(pi) {
80
105
  let journalBytes = 0;
81
106
  const journal = [];
82
107
  const send = (frame) => {
83
- const record = { protocol: HERDR_PI_PROTOCOL, runId, ...frame, cursor: ++evidenceCursor };
108
+ // Checked before journaling: the journal replays on every reconnect, where an unencodable record would end this Pi.
109
+ const record = { protocol: HERDR_PI_PROTOCOL, runId, ...frame, cursor: evidenceCursor + 1 };
84
110
  const size = Buffer.byteLength(JSON.stringify(record));
111
+ if (size >= HERDR_PI_MAX_FRAME_BYTES)
112
+ throw new Error(`pi-subagents bridge frame '${frame.type}' is ${size} bytes, over the ${HERDR_PI_MAX_FRAME_BYTES}-byte limit.`);
113
+ evidenceCursor++;
85
114
  journal.push(record);
86
115
  journalBytes += size;
87
116
  while (journal.length > 512 || journalBytes > 8 * 1024 * 1024) {
@@ -93,6 +122,7 @@ export default function registerHerdrPiBridge(pi) {
93
122
  return;
94
123
  client.write(encodeHerdrPiFrame(record));
95
124
  };
125
+ const sendReady = (ctx) => send({ type: "ready", packageVersion: packageJson.version, nativeSessionId, sessionFile: ctx.sessionManager?.getSessionFile?.(), cwd: process.cwd(), tools: pi.getActiveTools(), model: ctx.model?.provider && ctx.model.id ? `${ctx.model.provider}/${ctx.model.id}` : undefined, configured, activeRequestId, evidenceCursor, evidenceFloor: journal[0]?.cursor ?? evidenceCursor + 1, initialGit: gitEvidence(process.cwd()) });
96
126
  const sessionId = (ctx) => ctx.sessionManager?.getSessionId?.();
97
127
  pi.registerTool({
98
128
  name: "contact_supervisor",
@@ -165,22 +195,45 @@ export default function registerHerdrPiBridge(pi) {
165
195
  return resolvedSystemPrompt && resolvedContextPolicy ? { systemPrompt: `${rewriteSubagentPrompt(typeof event.systemPrompt === "string" ? event.systemPrompt : "", { inheritProjectContext: resolvedContextPolicy.inheritProjectContext, inheritGlobalContext: resolvedContextPolicy.inheritGlobalContext, inheritSkills: resolvedContextPolicy.inheritSkills })}\n\n<active_agent name=${JSON.stringify(resolvedContextPolicy.agent)}/>\n\n${resolvedSystemPrompt}` } : undefined;
166
196
  });
167
197
  on("session_start", (_event, ctx) => {
198
+ if (claims.has(runDir))
199
+ return;
168
200
  context = ctx;
169
201
  nativeSessionId = sessionId(ctx);
170
202
  if (!nativeSessionId)
171
203
  throw new Error("Pane-native Pi bridge requires a persisted native session identity.");
204
+ claims.add(runDir);
205
+ claimed = true;
206
+ fs.chmodSync(runDir, 0o700);
207
+ for (const candidate of [socketPath, manifestPath]) {
208
+ try {
209
+ const stat = fs.lstatSync(candidate);
210
+ if (stat.isSymbolicLink())
211
+ throw new Error(`Refusing symlink at '${candidate}'.`);
212
+ fs.rmSync(candidate, { force: true });
213
+ }
214
+ catch (error) {
215
+ if (error.code !== "ENOENT")
216
+ throw error;
217
+ }
218
+ }
219
+ server.listen(socketPath, () => { fs.chmodSync(socketPath, 0o600); });
172
220
  fs.writeFileSync(manifestPath, JSON.stringify({ protocol: HERDR_PI_PROTOCOL, packageVersion: packageJson.version, runId, socketPath, nativeSessionId, pid: process.pid }), { mode: 0o600, flag: "wx" });
173
- send({ type: "ready", packageVersion: packageJson.version, nativeSessionId, sessionFile: ctx.sessionManager?.getSessionFile?.(), cwd: process.cwd(), tools: pi.getActiveTools(), model: ctx.model?.provider && ctx.model.id ? `${ctx.model.provider}/${ctx.model.id}` : undefined, configured, activeRequestId, evidenceCursor, evidenceFloor: journal[0]?.cursor ?? evidenceCursor + 1, initialGit: gitEvidence(process.cwd()) });
221
+ sendReady(ctx);
174
222
  });
175
223
  on("message_end", (event) => {
176
- const message = event.message;
177
- if (message?.role === "assistant")
224
+ const message = boundedMessage(event.message);
225
+ if (message.role === "assistant")
178
226
  finalAssistant = message;
179
227
  send({ type: "event", requestId: activeRequestId, event: { ...event, message }, nativeSessionId });
180
228
  });
229
+ // The parent counts tools, arms per-tool timeouts and pauses its run timeout on a supervisor wait from these events.
230
+ // The result itself arrives as the toolResult message_end, so the end event carries no result.
231
+ on("tool_execution_start", (event) => send({ type: "event", requestId: activeRequestId, event: { type: "tool_execution_start", toolCallId: event.toolCallId, toolName: event.toolName, args: boundedToolArgs(event.args) }, nativeSessionId }));
232
+ on("tool_execution_end", (event) => send({ type: "event", requestId: activeRequestId, event: { type: "tool_execution_end", toolCallId: event.toolCallId, toolName: event.toolName, isError: event.isError }, nativeSessionId }));
181
233
  on("agent_settled", (_event, ctx) => { const requestId = activeRequestId; send({ type: "settled", requestId, nativeSessionId, idle: ctx.isIdle(), pending: ctx.hasPendingMessages(), finalAssistant, finalGit: gitEvidence(process.cwd()) }); if (ctx.isIdle() && !ctx.hasPendingMessages())
182
234
  activeRequestId = undefined; });
183
- on("session_shutdown", () => { server.close(); client?.destroy(); try {
235
+ on("session_shutdown", () => { if (!claimed)
236
+ return; claimed = false; claims.delete(runDir); server.close(); client?.destroy(); try {
184
237
  fs.rmSync(runDir, { recursive: true, force: true });
185
238
  }
186
239
  catch { } });
@@ -220,9 +273,13 @@ export default function registerHerdrPiBridge(pi) {
220
273
  const invalidReads = resources.reads !== undefined && resources.reads !== false && (!Array.isArray(resources.reads) || resources.reads.some((name) => typeof name !== "string"));
221
274
  if (typeof resources.agent !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(resources.agent) || invalidSkills || invalidReads)
222
275
  throw new Error("Remote logical resource names are invalid.");
276
+ const acceptancePrompt = resources.acceptancePrompt;
277
+ if (acceptancePrompt !== undefined && (typeof acceptancePrompt !== "string" || Buffer.byteLength(acceptancePrompt) > HERDR_PI_MAX_ACCEPTANCE_PROMPT_BYTES))
278
+ throw new Error("Bridge acceptance instructions are invalid or too large.");
223
279
  const resolved = resolveRemoteHerdrResources(process.cwd(), { agent: resources.agent, ...(resources.skills ? { skills: resources.skills } : {}), ...(resources.toolCeiling ? { toolCeiling: resources.toolCeiling } : {}), ...(resources.reads !== undefined ? { reads: resources.reads } : {}) }, context ? pi.getActiveTools() : []);
224
- resolvedSystemPrompt = resolved.systemPrompt;
225
280
  resolvedContextPolicy = resolved;
281
+ // Appended after the remote agent's own prompt, as a local child's system prompt carries it.
282
+ resolvedSystemPrompt = acceptancePrompt ? `${resolved.systemPrompt}\n${acceptancePrompt}` : resolved.systemPrompt;
226
283
  // A local child gets watchdog_diff from the prompt runtime, which a placed child never loads.
227
284
  if (resolved.tools.includes(WATCHDOG_DIFF_TOOL_NAME) && !pi.getAllTools().some((tool) => tool.name === WATCHDOG_DIFF_TOOL_NAME))
228
285
  pi.registerTool(createWatchdogDiffTool(captureWatchdogDiffBaseline(process.cwd()), { workingTreeAtLaunch: true }));
@@ -260,7 +317,6 @@ export default function registerHerdrPiBridge(pi) {
260
317
  socket.on("close", () => { if (client === socket)
261
318
  client = undefined; });
262
319
  if (context && nativeSessionId)
263
- send({ type: "ready", packageVersion: packageJson.version, nativeSessionId, sessionFile: context.sessionManager?.getSessionFile?.(), cwd: process.cwd(), tools: pi.getActiveTools(), model: context.model?.provider && context.model.id ? `${context.model.provider}/${context.model.id}` : undefined, configured, activeRequestId, evidenceCursor, evidenceFloor: journal[0]?.cursor ?? evidenceCursor + 1, initialGit: gitEvidence(process.cwd()) });
320
+ sendReady(context);
264
321
  });
265
- server.listen(socketPath, () => { fs.chmodSync(socketPath, 0o600); });
266
322
  }
@@ -1,4 +1,4 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { type HerdrStatusRun } from "../integrations/herdr-status.ts";
3
3
  import { type SubagentState } from "../shared/types.ts";
4
4
  export declare function projectActiveHerdrRuns(state: SubagentState): HerdrStatusRun[];
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
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
+ import { AgentSession } from "@earendil-works/pi-coding-agent";
5
6
  import { Box, Container, Spacer, Text } from "@earendil-works/pi-tui";
6
7
  import { clearAgentDiscoveryCache, discoverAgentSnapshot, discoverAgents, discoverAgentsAll } from "../agents/agents.js";
7
8
  import { resolveGlobalNpmRoot } from "../agents/global-npm-root.js";
@@ -13,6 +14,7 @@ import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "..
13
14
  import { resolveCurrentSessionId } from "../shared/session-identity.js";
14
15
  import { recordSessionReplacement, recordSessionStart } from "../shared/session-succession.js";
15
16
  import { createSessionSwitchGuard } from "./session-switch.js";
17
+ import { compactionInProgress, compactionInterruptedRun, installCompactionInterruptionCapture, takeCompactionAbort } from "../shared/compaction-interruption.js";
16
18
  import { reportSessionWarning } from "../shared/session-warnings.js";
17
19
  import { getAgentDir } from "../shared/utils.js";
18
20
  import { isStaleExtensionContextError, MODEL_ONLY_TOOL, withCachedUiContext } from "../shared/extension-context.js";
@@ -215,6 +217,7 @@ export default function registerSubagentExtension(pi) {
215
217
  if (process.env[SUBAGENT_CHILD_ENV] === "1") {
216
218
  return;
217
219
  }
220
+ installCompactionInterruptionCapture(AgentSession);
218
221
  const runtimeRegistry = getRuntimeRegistry();
219
222
  setMainThinkingLevelSource(() => readMainThinkingLevel(() => pi.getThinkingLevel()));
220
223
  DIRS.results = ensureAccessibleDir(DIRS.results);
@@ -747,7 +750,7 @@ export default function registerSubagentExtension(pi) {
747
750
  try {
748
751
  // The run is still active here, so its signal tells a user stop (Esc) apart from a finished or failed run.
749
752
  // Pi skips agent_before_settle after an abort. Background runs keep going, but they must not restart the parent.
750
- if (ctx.hasUI && ctx.signal?.aborted) {
753
+ if (ctx.hasUI && ctx.signal?.aborted && !takeCompactionAbort(ctx.sessionManager)) {
751
754
  parentWake.userAborted();
752
755
  const active = activeAsyncJobCount();
753
756
  if (active > 0)
@@ -1110,7 +1113,12 @@ export default function registerSubagentExtension(pi) {
1110
1113
  }
1111
1114
  };
1112
1115
  let compactionResumeTimer;
1113
- const cancelCompactionResume = () => { clearTimeout(compactionResumeTimer); compactionResumeTimer = undefined; };
1116
+ let compactionInterruptedParent = false;
1117
+ const cancelCompactionResume = () => {
1118
+ clearTimeout(compactionResumeTimer);
1119
+ compactionResumeTimer = undefined;
1120
+ compactionInterruptedParent = false;
1121
+ };
1114
1122
  pi.on("agent_start", () => {
1115
1123
  cancelCompactionResume();
1116
1124
  parentWake.agentStarted();
@@ -1132,38 +1140,53 @@ export default function registerSubagentExtension(pi) {
1132
1140
  if (event.reason !== "manual")
1133
1141
  suspendWidgetsForCompaction();
1134
1142
  });
1135
- // Pi emits session_compact before it clears its compaction state. sendMessage's run path has no
1136
- // compaction guard (only prompt() refuses), so wait for the parent to go idle before the resume notice
1137
- // starts a run. A run that starts first cancels the pending resume.
1138
- pi.on("session_compact", (event) => {
1143
+ // parentWake only appends wakes during a manual compaction. Once every overlapping compaction has ended, wake
1144
+ // the parent once if a wake was deferred, or if a successful compaction cut off a working parent with
1145
+ // background work (Pi never continues that run). Pi emits session_compact before it clears its compaction
1146
+ // state, so wait until the session is idle and compact() has returned. A run that starts first cancels it.
1147
+ const wakeAfterCompaction = (completed) => (event, ctx) => {
1139
1148
  if (event.reason !== "manual")
1140
1149
  return;
1141
- if (activeAsyncJobCount() === 0 || !withLastUiContext(() => true))
1150
+ const sessionManager = ctx.sessionManager;
1151
+ if (completed && compactionInterruptedRun(sessionManager))
1152
+ compactionInterruptedParent = true;
1153
+ if (compactionResumeTimer)
1142
1154
  return;
1143
- cancelCompactionResume();
1144
1155
  const sessionId = state.currentSessionId;
1145
1156
  const deadline = Date.now() + COMPACTION_RESUME_DEADLINE_MS;
1146
- const resumeWhenIdle = () => {
1147
- if (state.currentSessionId !== sessionId || activeAsyncJobCount() === 0)
1157
+ const wakeWhenIdle = () => {
1158
+ compactionResumeTimer = undefined;
1159
+ if (state.currentSessionId !== sessionId)
1148
1160
  return;
1149
- const idle = withLastUiContext((ctx) => ctx.isIdle());
1150
- if (idle === undefined)
1151
- return;
1152
- if (!idle) {
1161
+ let idle;
1162
+ try {
1163
+ idle = ctx.isIdle();
1164
+ }
1165
+ catch {
1166
+ return; // Replaced or reloaded: the new session's runtime owns its notices.
1167
+ }
1168
+ // Past the deadline the next compaction event polls again.
1169
+ if (!idle || compactionInProgress(sessionManager)) {
1153
1170
  if (Date.now() < deadline)
1154
- compactionResumeTimer = setTimeout(resumeWhenIdle, COMPACTION_RESUME_POLL_MS);
1171
+ compactionResumeTimer = setTimeout(wakeWhenIdle, COMPACTION_RESUME_POLL_MS);
1155
1172
  return;
1156
1173
  }
1157
- // Pi's compact() aborts a live run first, which set the user-abort hold; this resume is deliberate.
1158
- parentWake.releaseHold();
1174
+ const interrupted = compactionInterruptedParent && activeAsyncJobCount() > 0 && withLastUiContext(() => true) === true;
1175
+ compactionInterruptedParent = false;
1176
+ if (!parentWake.takeDeferredWake() && !interrupted)
1177
+ return;
1159
1178
  parentWake.sendMessage({
1160
1179
  customType: "subagent-compaction-resume",
1161
- content: "Compaction is complete. Resume the parent task now; background subagent results will arrive separately when ready.",
1180
+ content: interrupted
1181
+ ? "Compaction is complete. Resume the parent task now; background subagent results will arrive separately when ready."
1182
+ : "Compaction is complete. Act on the background subagent notices above.",
1162
1183
  display: false,
1163
1184
  }, { triggerTurn: true });
1164
1185
  };
1165
- compactionResumeTimer = setTimeout(resumeWhenIdle, COMPACTION_RESUME_POLL_MS);
1166
- });
1186
+ compactionResumeTimer = setTimeout(wakeWhenIdle, COMPACTION_RESUME_POLL_MS);
1187
+ };
1188
+ pi.on("session_compact", wakeAfterCompaction(true));
1189
+ pi.on("session_compact_failed", wakeAfterCompaction(false));
1167
1190
  pi.on("session_start", (event, ctx) => {
1168
1191
  parentWake.bindSession(ctx);
1169
1192
  completionNotifier.bindSession(ctx.sessionManager);
@@ -227,7 +227,7 @@ const SubagentParamProperties = {
227
227
  usageBudget: Type.Optional(UsageBudgetOverride),
228
228
  agentScope: Type.Optional(Type.String({ description: "user/project/both (default); project wins collisions." })),
229
229
  cwd: Type.Optional(Type.String({ description: "Execution/project-pane directory." })),
230
- machine: Type.Optional(Type.String({ minLength: 1, maxLength: 128, description: "Herdr saved machine id or label (runs an external CLI agent), a Rex host named in settings (runs a Pi child), or \"local\" (a Pi child in a Rex pane here). On another machine, cwd is a directory there." })),
230
+ machine: Type.Optional(Type.String({ minLength: 1, maxLength: 128, description: "Herdr saved machine id or label (runs an external CLI agent), a Rex host named in settings (runs a Pi child), or \"local\" (a Pi child in a new tab of the Herdr or Rex session this Pi runs in). On another machine, cwd is a directory there." })),
231
231
  requireLauncher: Type.Optional(Type.Object({
232
232
  name: Type.String({ pattern: RUNNER_LAUNCHER_NAME_PATTERN.source }),
233
233
  definitionDigest: Type.String({ pattern: "^[0-9a-f]{64}$" }),
@@ -20,6 +20,10 @@ declare const parameters: Type.TObject<{
20
20
  export type SubagentLaunchArgs = Static<typeof parameters>;
21
21
  /** Not declared to the model, so the system prompt and tool list stay unchanged. */
22
22
  export declare function registerSubagentLaunchTool(pi: ExtensionAPI): void;
23
- /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, if any. */
24
- export declare function approveWorkflowChildLaunch(ctx: ExtensionContext, describe: () => SubagentLaunchArgs, signal: AbortSignal): Promise<string | undefined>;
23
+ /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, or the task the handlers left. */
24
+ export declare function approveWorkflowChildLaunch(ctx: ExtensionContext, describe: () => SubagentLaunchArgs, signal: AbortSignal): Promise<{
25
+ refusal: string;
26
+ } | {
27
+ task?: string;
28
+ }>;
25
29
  export {};
@@ -22,27 +22,31 @@ export function registerSubagentLaunchTool(pi) {
22
22
  pi.registerTool({
23
23
  name: SUBAGENT_LAUNCH_TOOL,
24
24
  label: "Subagent launch",
25
- description: "A workflow is about to start this subagent. Blocking this call stops that child from starting.",
25
+ description: "A workflow is about to start this subagent. Blocking this call stops that child from starting; changing its task changes what the child is told.",
26
26
  parameters,
27
27
  exposure: "deferred",
28
- async execute() {
29
- return { content: [{ type: "text", text: "Records approval for a workflow child launch; it starts nothing itself." }], details: {} };
28
+ // Pi hands execute the input after every tool_call handler ran, so a handler's change to task arrives here.
29
+ async execute(_toolCallId, params) {
30
+ return { content: [{ type: "text", text: "Records approval for a workflow child launch; it starts nothing itself." }], details: { task: params.task } };
30
31
  },
31
32
  });
32
33
  }
33
- /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, if any. */
34
+ /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, or the task the handlers left. */
34
35
  export async function approveWorkflowChildLaunch(ctx, describe, signal) {
35
36
  // Starts with no tool call behind them (schedule ticks, auto-resume, RPC) have no executeTool, and a tool
36
37
  // allowlist that leaves the tool out unregisters it: no handler could see the call in either case.
37
38
  if (!("executeTool" in ctx))
38
- return undefined;
39
+ return {};
39
40
  const toolCtx = ctx;
40
41
  if (!toolCtx.tools.some((tool) => tool.name === SUBAGENT_LAUNCH_TOOL))
41
- return undefined;
42
+ return {};
42
43
  const args = describe();
43
44
  const outcome = await toolCtx.executeTool(SUBAGENT_LAUNCH_TOOL, args, { signal });
44
- if (!outcome.isError)
45
- return undefined;
45
+ if (!outcome.isError) {
46
+ // Pi doesn't validate the input again after a handler changes it.
47
+ const task = outcome.result.details?.task;
48
+ return { task: typeof task === "string" ? task : undefined };
49
+ }
46
50
  const reason = outcome.result.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n").trim();
47
- return `Workflow child '${args.key}' was not started: the ${SUBAGENT_LAUNCH_TOOL} call was refused${reason ? `: ${reason}` : "."}`;
51
+ return { refusal: `Workflow child '${args.key}' was not started: the ${SUBAGENT_LAUNCH_TOOL} call was refused${reason ? `: ${reason}` : "."}` };
48
52
  }
@@ -12,6 +12,11 @@ const optionsValidator = Compile(SubagentOptionParams);
12
12
  * Management fields given at the top level keep working, as in the flat shape older sessions declared.
13
13
  */
14
14
  export function flattenSubagentToolOptions(params, disabled) {
15
+ // Some models fill every unset optional parameter with the string "null", and the workflow union with "false" (#3285).
16
+ params = Object.fromEntries(Object.entries(params).filter(([key, value]) => value !== "null" && !(key === "workflow" && value === "false")));
17
+ if (params.options && typeof params.options === "object" && !Array.isArray(params.options)) {
18
+ params.options = Object.fromEntries(Object.entries(params.options).filter(([, value]) => value !== "null"));
19
+ }
15
20
  const removedTopLevel = removedModelWorkflowFieldError(params);
16
21
  if (removedTopLevel)
17
22
  throw new Error(removedTopLevel);
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import { isUnexplainedProcessSignal } from "../runs/shared/process-signal.js";
4
+ import { formatParallelHandoffLines } from "../runs/shared/kept-branch-text.js";
4
5
  import { SUBAGENT_RESULT_INTERCOM_DELIVERY_EVENT, SUBAGENT_RESULT_INTERCOM_EVENT, } from "../shared/types.js";
5
6
  export function resolveSubagentResultStatus(input) {
6
7
  if (input.detached)
@@ -223,7 +224,7 @@ function formatSubagentResultIntercomMessage(input) {
223
224
  if (input.asyncDir)
224
225
  lines.push(`Async dir: ${input.asyncDir}`);
225
226
  if (input.parallelHandoff)
226
- lines.push(`Parallel handoff: ${input.parallelHandoff.path}`);
227
+ lines.push(...formatParallelHandoffLines(input.parallelHandoff.path, input.parallelHandoff.keptBranches));
227
228
  const resumeGuidance = asyncResumeGuidance(input);
228
229
  if (resumeGuidance)
229
230
  lines.push(resumeGuidance);
@@ -345,7 +346,7 @@ export function formatSubagentResultReceipt(input) {
345
346
  `Children: ${formatStatusCounts(counts)}`,
346
347
  ];
347
348
  if (input.payload.parallelHandoff)
348
- lines.push(`Parallel handoff: ${input.payload.parallelHandoff.path}`);
349
+ lines.push(...formatParallelHandoffLines(input.payload.parallelHandoff.path, input.payload.parallelHandoff.keptBranches));
349
350
  const artifacts = input.payload.children.filter((child) => typeof child.artifactPath === "string");
350
351
  if (artifacts.length > 0) {
351
352
  lines.push("Artifacts:");
@@ -8,6 +8,7 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
8
8
  import { type CompletionBatchConfig } from "./completion-batcher.ts";
9
9
  import { type ChildWatchdogProgress, type ChildWatchdogWarningSummary, type ParallelHandoffReference, type ScheduleOrigin, type SubagentState } from "../../shared/types.ts";
10
10
  import { type ParentWake } from "../../shared/parent-wake.ts";
11
+ import { type KeptBranch } from "../shared/kept-branch-text.ts";
11
12
  import type { ResultDeliveryOwnership } from "./result-delivery-ownership.ts";
12
13
  export interface SubagentNotifyChildOutput {
13
14
  workflowKey?: string;
@@ -54,6 +55,8 @@ export interface SubagentNotifyDetails {
54
55
  sessionLabel?: string;
55
56
  sessionValue?: string;
56
57
  handoffPath?: string;
58
+ /** Branches worktree cleanup kept because their commits are on no other ref. */
59
+ keptBranches?: KeptBranch[];
57
60
  /** Present when a durable schedule launched the run. */
58
61
  scheduleOrigin?: ScheduleOrigin;
59
62
  watchdogBlockers?: SubagentNotifyWatchdogBlocker[];
@@ -13,6 +13,7 @@ import { COMPLETION_ACTION } from "../../shared/parent-wake.js";
13
13
  import { resolveSubagentResultStatus } from "../../intercom/result-intercom.js";
14
14
  import { isUnexplainedProcessSignal } from "../shared/process-signal.js";
15
15
  import { capSummaryOutputs } from "../shared/single-output.js";
16
+ import { formatParallelHandoffLines, parseKeptBranchLines, readKeptBranches } from "../shared/kept-branch-text.js";
16
17
  import { describeWorkflowResume } from "../../workflows/workflow-resume-claim.js";
17
18
  import { isReusableWorkflowStopCause } from "../../workflows/workflow-stop-cause.js";
18
19
  const CHILD_OUTPUT_PREVIEW_MAX_BYTES = 2_000;
@@ -228,7 +229,7 @@ export function formatSingleCompletion(details) {
228
229
  formatResultPreview(details),
229
230
  ...(watchdogLines.length ? ["", ...watchdogLines] : []),
230
231
  details.handoffPath ? "" : undefined,
231
- details.handoffPath ? `Parallel handoff: ${details.handoffPath}` : undefined,
232
+ ...(details.handoffPath ? formatParallelHandoffLines(details.handoffPath, details.keptBranches) : []),
232
233
  correlationLines.length && !details.handoffPath ? "" : undefined,
233
234
  ...correlationLines,
234
235
  sessionLine ? "" : undefined,
@@ -308,6 +309,7 @@ export function parseSubagentNotifyContent(content) {
308
309
  const resultEnd = firstMetadataIndex > 0 && body[firstMetadataIndex - 1]?.trim() === "" ? firstMetadataIndex - 1 : firstMetadataIndex;
309
310
  const resultPreview = body.slice(0, resultEnd).join("\n").trim() || "(no output)";
310
311
  const handoffPath = handoffIndex >= 0 ? body[handoffIndex].slice("Parallel handoff: ".length).trim() : undefined;
312
+ const keptBranches = handoffIndex >= 0 ? parseKeptBranchLines(body.slice(handoffIndex + 1)) : [];
311
313
  const workflowRunId = workflowRunIndex >= 0 ? body[workflowRunIndex].slice("Workflow run: ".length).trim() : undefined;
312
314
  const childRuns = childRunsIndex >= 0
313
315
  ? body[childRunsIndex].slice("Child runs: ".length).split(", ").map((part) => {
@@ -337,6 +339,7 @@ export function parseSubagentNotifyContent(content) {
337
339
  ...(workflowReceiptPath ? { workflowReceiptPath } : {}),
338
340
  resultPreview,
339
341
  ...(handoffPath ? { handoffPath } : {}),
342
+ ...(keptBranches.length ? { keptBranches } : {}),
340
343
  ...(workflowRunId ? { workflowRunId } : {}),
341
344
  ...(resumeNotice ? { resumeNotice } : {}),
342
345
  ...(childRuns?.length ? { childRuns } : {}),
@@ -359,7 +362,7 @@ export function formatGroupedCompletion(details) {
359
362
  blocks.push(formatResultPreview(detail));
360
363
  blocks.push(...formatWatchdogBlockerLines(detail));
361
364
  if (detail.handoffPath)
362
- blocks.push(`Parallel handoff: ${detail.handoffPath}`);
365
+ blocks.push(...formatParallelHandoffLines(detail.handoffPath, detail.keptBranches));
363
366
  blocks.push(...formatCorrelationLines(detail));
364
367
  if (sessionLine)
365
368
  blocks.push(sessionLine);
@@ -542,6 +545,7 @@ export function buildCompletionDetails(result) {
542
545
  ? result.parallelHandoff
543
546
  : undefined;
544
547
  const handoffPath = typeof parallelHandoff?.path === "string" ? parallelHandoff.path : undefined;
548
+ const keptBranches = readKeptBranches(parallelHandoff?.keptBranches);
545
549
  const receipt = result.workflowReceipt;
546
550
  const receiptPath = receipt && typeof receipt === "object" && !Array.isArray(receipt)
547
551
  ? receipt.path : undefined;
@@ -661,6 +665,7 @@ export function buildCompletionDetails(result) {
661
665
  resultPreview: watchdogConcerns.length ? `${resultPreview}\n\nHigh-importance watchdog concerns:\n${watchdogConcerns.map((warning) => `- ${warning}`).join("\n")}` : resultPreview,
662
666
  ...(typeof result.durationMs === "number" ? { durationMs: result.durationMs } : {}),
663
667
  ...(handoffPath ? { handoffPath } : {}),
668
+ ...(handoffPath && keptBranches.length ? { keptBranches } : {}),
664
669
  ...(rawRunId ? { runId: rawRunId } : {}),
665
670
  ...(workflowRunId ? { workflowRunId } : {}),
666
671
  ...(resumeNotice ? { resumeNotice } : {}),
@@ -35,6 +35,7 @@ import { validHostStepNodes } from "../shared/host-step-status.js";
35
35
  import { workflowAsyncChildSteeringGuidance } from "../shared/workflow-async-child-guidance.js";
36
36
  import { formatWorkflowKeyRevival, projectWorkflowKeyRevival } from "../../workflows/workflow-revival.js";
37
37
  import { capSummaryOutputs } from "../shared/single-output.js";
38
+ import { formatParallelHandoffLines } from "../shared/kept-branch-text.js";
38
39
  import { ownsRun } from "../shared/run-ownership.js";
39
40
  import { foregroundChildStateLabel } from "../foreground/foreground-history.js";
40
41
  import { waitToolName } from "../../shared/wait-tool-name.js";
@@ -632,7 +633,7 @@ export function inspectSubagentStatus(params, deps = {}) {
632
633
  status.turnBudget ? `Turn budget: ${status.turnBudget.turnCount}/${status.turnBudget.maxTurns}+${status.turnBudget.graceTurns} (${status.turnBudget.outcome})` : undefined,
633
634
  `Dir: ${asyncDir}`,
634
635
  outputPath ? `Output: ${outputPath}` : undefined,
635
- status.parallelHandoff ? `Parallel handoff: ${status.parallelHandoff.path}` : undefined,
636
+ ...(status.parallelHandoff ? formatParallelHandoffLines(status.parallelHandoff.path, status.parallelHandoff.keptBranches) : []),
636
637
  reconciliation.message ? `Diagnosis: ${reconciliation.message}` : undefined,
637
638
  reconciliation.resultPath && fs.existsSync(reconciliation.resultPath) ? `Result: ${reconciliation.resultPath}` : undefined,
638
639
  ].filter((line) => Boolean(line));
@@ -807,7 +808,7 @@ export function inspectSubagentStatus(params, deps = {}) {
807
808
  const runId = data.runId ?? data.id ?? resolvedId;
808
809
  const lines = [`Run: ${runId}`, data.toolCallId ? `Tool call: ${data.toolCallId}` : undefined, `State: ${status}`, `Result: ${resultPath}`].filter((line) => Boolean(line));
809
810
  if (data.parallelHandoff?.path)
810
- lines.push(`Parallel handoff: ${data.parallelHandoff.path}`);
811
+ lines.push(...formatParallelHandoffLines(data.parallelHandoff.path, data.parallelHandoff.keptBranches));
811
812
  const receipt = data.workflowReceipt;
812
813
  const receiptPath = receipt && typeof receipt === "object" && !Array.isArray(receipt)
813
814
  ? receipt.path : undefined;
@@ -14,6 +14,7 @@ export function buildRunnerChildLaunch(step, ctx, attempt) {
14
14
  machine: step.machine,
15
15
  remoteSkillNames: step.skills,
16
16
  remoteReads: step.remoteReads,
17
+ acceptancePrompt,
17
18
  parentSessionId: step.parentSessionId,
18
19
  parentSessionFile: step.parentSessionFile,
19
20
  forkCacheKey: step.context === "fork" ? deriveForkPromptCacheKey(step.parentSessionId) : undefined,