@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
package/docs/agents.md CHANGED
@@ -269,6 +269,8 @@ A custom agent file that shadows a bundled agent replaces the bundled definition
269
269
 
270
270
  Native Pi and the six code-owned Claude Code, Codex, and Cursor profiles can run on a Herdr machine (`herdr machine add <target> --label <name>`). Herdr owns each visible agent process in a fresh no-focus pane; SSH is used only as bounded transport for Herdr RPC and ownership checks. Herdr's catalog is the host allowlist; raw ssh targets are rejected.
271
271
 
272
+ For a pane on this machine you don't need a saved machine: run Pi inside Herdr and use `machine: "local"`.
273
+
272
274
  `machine` is a top-level frontmatter key, a settings override (`subagents.agentOverrides.<agent>.machine`, project beats user, `false` clears a pin), and a launch option on the `subagent` tool, workflow `runs.run`, chain, parallel, and dynamic-fanout steps. The launch option wins. Placement survives `subagent({ action: "disable" })`, `reset`, and model profile switches.
273
275
 
274
276
  `cwd` means the directory on that machine when a machine is set. An absolute path or `~/...` is used as given; a relative path joins the repo's configured machine root; with no cwd the root is used; with no root the launch fails closed naming the setting:
@@ -288,13 +290,15 @@ Placed external profiles are one-shot and stop-only: they cannot steer, resume,
288
290
 
289
291
  pi-subagents never clones, pulls, or checks out on the machine. Generic `external-cli` commands and managed worktrees are rejected before launch; saved-machine placement accepts native Pi and only the six code-owned external profiles.
290
292
 
291
- ## Running a Pi child in a Rex pane on this machine
293
+ ## Running a Pi child in a new tab on this machine (Rex or Herdr)
294
+
295
+ `machine: "local"` runs a native Pi child as a visible Pi in a new background tab of the terminal this Pi runs in, labeled `subagent-<run id tail>`. Inside Rex, that is a tab in your Rex session. Inside a Herdr pane (`HERDR_ENV=1` and `HERDR_PANE_ID` set), it is a tab in your own Herdr session, reached over the local Herdr socket with no saved machine and no SSH. When both are set (Herdr running inside a Rex tab), Herdr wins, because the Herdr pane is where Pi is drawn. Outside both, or when the Rex or Herdr server does not confirm this Pi's session or pane, the launch fails before anything starts. `local` is reserved and never looks in the Herdr catalog. It works wherever `machine` works: frontmatter, settings overrides, the `subagent` tool, workflow `runs.run`, chain, parallel, and dynamic-fanout steps.
292
296
 
293
- `machine: "local"` runs a native Pi child as a visible Pi in a new background tab of your own Rex session, labeled `subagent-<run id tail>`. It works wherever `machine` works: frontmatter, settings overrides, the `subagent` tool, workflow `runs.run`, chain, parallel, and dynamic-fanout steps. `local` is reserved and never looks in the Herdr catalog. The parent Pi must run inside Rex: with no `REX_SESSION`, or a session the Rex server does not confirm, the launch fails before anything starts.
297
+ The parent drives the child through the same bridge as a Herdr-placed Pi: prompt, steer, follow-up, abort, `contact_supervisor`, and results. The child Pi loads pi-subagents from its own extensions, so it must be installed at the same version. `cwd` is a directory on this machine; a relative path joins the launch directory. In Herdr, the tab opens in the `pi-subagents-…` workspace pi-subagents made for that directory if there is one, else in the one workspace with a pane in that directory, else in a new no-focus `pi-subagents-…` workspace. In Rex, pi-subagents finds `rex` in `$REX_BIN_DIR`, then on `PATH`, then in the Rex server app; in Herdr, it runs `herdr` from `$HERDR_BIN` or `PATH`.
294
298
 
295
- The parent drives the child through the same bridge as a Herdr-placed Pi: prompt, steer, follow-up, abort, `contact_supervisor`, and results. The child Pi loads pi-subagents from its own extensions, so it must be installed at the same version. `cwd` is a directory on this machine; a relative path joins the launch directory. pi-subagents finds `rex` in `$REX_BIN_DIR`, then on `PATH`, then in the Rex server app.
299
+ A finished child keeps its tab open, with the idle Pi, until you close it; an aborted or stopped child's tab is closed. Limits: native Pi only (Claude Code, Codex, Cursor, and generic `external-cli` agents are rejected), fresh context only, and the same restrictions as a Herdr-placed Pi (no local extension paths, process environment, nested delegation, permission rules, tool budgets, or `outputSchema`).
296
300
 
297
- A finished child keeps its tab open, with the idle Pi, until you close it; an aborted or stopped child's tab is closed. Limits: native Pi only (Claude Code, Codex, Cursor, and generic `external-cli` agents are rejected), fresh context only, and the same restrictions as a Herdr-placed Pi (no local extension paths, process environment, nested delegation, permission rules, or tool budgets).
301
+ A `local` child edits this machine's disk, so in either terminal it gets the same local cwd check, Git evidence and output-file handling as a child without `machine`.
298
302
 
299
303
  ## Running a Pi child in a Rex pane on another Mac
300
304
 
@@ -571,6 +575,8 @@ How `tools` behaves:
571
575
 
572
576
  An allowlisted name does not load the extension that registers it. Load that provider through `extensions`, `subagentOnlyExtensions`, a path-like `tools` entry, or (background children only) normal Pi extension discovery. Pi's built-in `codemode` is the exception: native children register the host SDK's official factory when codemode is permitted, without enabling it in the main session. On older Pi hosts without that factory, a child that requests codemode still reports it as unavailable; a capability ceiling that denies extensions prevents its registration.
573
577
 
578
+ An extension loaded in the child can also replace the tools sent to the model, as pi-fabric's code mode does when it offers only `fabric_exec`. A child with a `tools` allowlist then fails before its first model request, and the error names the allowlisted tools the request left out. Set `extensions: []` or list only the extensions the child needs, or omit `tools` to use that extension's tool surface.
579
+
574
580
  Ambient extensions depend on where the child runs. Local foreground children are sessions inside the parent Pi process and never load the parent's ambient extensions; otherwise the parent would start a second copy of each ambient extension, including this one. Background children are sessions inside the detached runner process and load the ambient extensions unless the agent sets `extensions` or the capability ceiling denies extensions. Local foreground children do inherit the providers the parent's extensions registered (`pi.registerProvider`), so their models resolve without loading those extensions again. The child gets the provider but not the registering extension's session hooks, so a provider that relies on its own hooks (for example to record each session's system prompt) can fail the child's first request; the foreground error then says so. Use `async: true` or list that extension in the agent's `subagentOnlyExtensions` or `extensions`. Pane-native remote foreground children instead use the remote machine's provider discovery and configuration. Agents that need MCP tools from an ambient adapter such as pi-mcp-adapter (including `mcp:` entries the adapter resolves) must therefore run as background children (`async: true`). A foreground launch of such an agent fails with a diagnostic that says exactly that.
575
581
 
576
582
  More rules:
@@ -668,6 +668,8 @@ Set `worktree` to `true` to make managed worktree isolation the default for laun
668
668
 
669
669
  The hook runs once per created worktree. Paths must be absolute, `~/...`, or repo-relative; bare command names are rejected.
670
670
 
671
+ Before the hook runs, a new worktree gets a `node_modules` link to the main checkout's `node_modules` when one exists, so a worktree that installs nothing can still load its dependencies. A hook that installs dependencies must remove that link first, for example with `fs.rmSync(path.join(worktreePath, "node_modules"), { force: true })`. Otherwise the install writes through the link into the main checkout's `node_modules`.
672
+
671
673
  Setup command waits are nonblocking and cancellable through existing run controls. Existing run deadlines and the hook timeout still apply; there is no new setup timeout or configuration.
672
674
 
673
675
  Setup commands, including Git hooks, must be finite and await all descendants before reporting success; do not start background services. Exit zero, natural pipe closure, complete bounded output, and valid JSON/path metadata are trusted completion for launch and cleanup—not observed process-tree proof. Violations are unsupported: protection against deleting a worktree with an undisclosed live descendant is not guaranteed. No additional Windows containment guarantee is provided.
@@ -152,7 +152,7 @@ A host that shows background subagent activity (an editor panel, a footer, a sta
152
152
 
153
153
  `subagent:jobs-changed` carries only `{ version: 1 }`. It fires whenever the parent's background job view changes: a run starts, moves to another step (no other event reports a chain or parallel run's step changes), reports new activity (a tool, a turn, tokens, or output), finishes, or is cleared from the widget. While a child streams output this can be about once per second per run. Starts and finishes fire right away; step and activity changes fire when the parent next reads the run's status file, which on macOS is a check every 5 seconds. It fires only in sessions with a UI, which covers interactive and RPC mode; print mode (`pi -p`) and SDK embeddings without a UI do not get it. It fires even when the async widget is turned off.
154
154
 
155
- Foreground children are not background jobs. Their progress arrives as updates to the parent's `subagent` tool call (Pi's `tool_execution_update` events), with the `details.results[]` rows described above.
155
+ Foreground children are not background jobs. Their progress arrives as updates to the parent's `subagent` tool call (Pi's `tool_execution_update` events), with the `details.results[]` rows described above. Each `details.progress[]` row names the child's `sessionFile` from launch when the child has one, so a host can follow the child's transcript while it runs instead of waiting for the final result; the file may appear only once the child writes its first entry.
156
156
 
157
157
  To rebuild what ran in a session after a reload, read the records the session file already holds: the `subagent` tool result's `details.results[]` for foreground runs and the `subagent-notify` message's `details.runs[]` for background runs (see [Host session lifetime and completion wakes](#host-session-lifetime-and-completion-wakes)). The `cost` method returns per-child rows built from the same records.
158
158
 
@@ -114,7 +114,7 @@ The `subagent` tool schema lists `agent`, `task`, `workflow`, `args`, `async`, `
114
114
  | `options.extensionBindings` | object | none | Child-only plain JSON keyed by namespaces like `package.name/1` (positive version): at most 16 namespaces, nesting depth 16, 256 total object properties, and 16 KiB of canonical UTF-8 JSON. Native Pi launches only; external runners and retained resumes reject it. A child's extensions read it as canonical JSON from `PI_SUBAGENT_EXTENSION_BINDINGS` in their factory or `session_start`; a foreground child sees it only until its session has started, after which the parent's environment is restored. |
115
115
  | `options.preflight` | object | none | Advisory lane hints for raw scripts (`workflow: true` or a script path) only; not accepted with named workflows or direct children. See [bounded workflows](workflows.md#opt-in-bounded-workflows). |
116
116
  | `cwd` | string | runtime cwd | Override working directory. With `machine`, the directory on that machine. |
117
- | `options.machine` | string | - | Herdr saved machine (label or profile id) for external-cli agents; see [agents.md](agents.md#running-external-cli-agents-on-a-herdr-saved-machine). |
117
+ | `options.machine` | string | - | Herdr saved machine (label or profile id), a Rex host from settings, or `"local"` (a new tab in the Herdr or Rex session this Pi runs in); see [agents.md](agents.md#running-a-pi-child-in-a-new-tab-on-this-machine-rex-or-herdr). |
118
118
  | `options.maxOutput` | object | none | Final output truncation limits `{ bytes?, lines? }`. For child runs it is only applied when set; there is no default cap on the inline path, so use `outputMode: "file-only"` for large outputs. For workflow script results, the Return, Emitted, and Console sections are always capped, at 200 KB / 5000 lines unless `maxOutput` sets other limits. |
119
119
  | `options.artifacts` | boolean | true | Write debug artifacts. |
120
120
  | `options.includeProgress` | boolean | false | Include full progress in result. |
package/docs/workflows.md CHANGED
@@ -477,9 +477,11 @@ known, or for explicit emergency hotfix lanes.
477
477
 
478
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.
479
479
 
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. 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
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, 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`.
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`.
483
+
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`.
483
485
 
484
486
  The legacy `/chain`, `/parallel`, and `/run-chain` commands are not registered.
485
487
 
@@ -499,7 +501,7 @@ const [api, ui] = await runs.all([
499
501
  return { api: api.artifactPaths, ui: ui.artifactPaths };
500
502
  ```
501
503
 
502
- 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.
503
505
 
504
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.
505
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.1",
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": "5091dc4108789ed257c421b927e7c7b960af5f4b"
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
  }
@@ -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}$" }),
@@ -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,
@@ -44,7 +44,7 @@ import { outputEntryFromAsyncResult, resolveOutputReferences } from "../shared/c
44
44
  import { clearStructuredOutputCaptures, createStructuredOutputFileCapture, createStructuredOutputRuntime, formatStructuredOutputRejectionError, MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput, readStructuredOutputAcceptanceReport } from "../shared/structured-output.js";
45
45
  import { formatMidToolExitError, isOrdinaryToolForMidToolExit, isUnexplainedProcessSignal } from "../shared/process-signal.js";
46
46
  import { formatChildToolDiagnostic } from "../shared/tool-availability.js";
47
- import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.js";
47
+ import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, remoteMutationEvidence, remoteMutationSnapshot, snapshotTrackedMutations } from "../shared/mutation-evidence.js";
48
48
  import { collectDynamicResults, DynamicFanoutError, materializeDynamicParallelStep, validateDynamicCollection } from "../shared/dynamic-fanout.js";
49
49
  import { claimRunFanoutBatch, getRunFanoutBudgetSnapshot } from "../shared/run-fanout-budget.js";
50
50
  import { nestedSummaryFromAsyncStatus, projectNestedEvents, resolveNestedAsyncDir, writeNestedEvent } from "../shared/nested-events.js";
@@ -79,7 +79,7 @@ import { resolveCodexExecLaunch } from "../shared/codex-exec-adapter.js";
79
79
  import { resolveCursorAgentLaunch } from "../shared/cursor-agent-adapter.js";
80
80
  import { resolveExternalCliRunnerStatus } from "../shared/external-cli-contract.js";
81
81
  import { formatHerdrMachineHint, prepareHerdrMachineExternalCliRun } from "../shared/herdr-machine.js";
82
- import { isRexLocalMachine } from "../shared/rex-machine.js";
82
+ import { editsLocalDisk } from "../shared/rex-machine.js";
83
83
  import { HerdrExternalNeedsAttentionError, createHerdrExternalAdapter, prepareInternalHerdrExternalAdapter } from "../shared/herdr-external-adapters.js";
84
84
  import { runExternalJob } from "../shared/external-job-runner.js";
85
85
  import { createOrcaProgressTab } from "../shared/orca-progress-tabs.js";
@@ -606,6 +606,8 @@ export async function runSingleStepInner(step, ctx) {
606
606
  if (step.machine) {
607
607
  if (step.machine.provider !== "herdr")
608
608
  throw new Error("Rex supports native Pi children only.");
609
+ if (!("target" in step.machine))
610
+ throw new Error("Machine 'local' runs native Pi children only.");
609
611
  const runner = resolveExternalCliRunnerStatus({ ...step.runner, machine: step.machine });
610
612
  const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
611
613
  const placedRunId = `${ctx.id}-${ctx.flatIndex}`;
@@ -762,7 +764,7 @@ export async function runSingleStepInner(step, ctx) {
762
764
  }
763
765
  const effectiveCwd = step.cwd ?? ctx.cwd;
764
766
  // A placed child's cwd is a directory on its machine; only machine 'local' shares this disk.
765
- const cwdError = step.machine && !isRexLocalMachine(step.machine) ? undefined : preflightLaunchCwd(step.requestedCwd ?? effectiveCwd, effectiveCwd);
767
+ const cwdError = step.machine && !editsLocalDisk(step.machine) ? undefined : preflightLaunchCwd(step.requestedCwd ?? effectiveCwd, effectiveCwd);
766
768
  if (cwdError)
767
769
  return { agent: step.agent, output: cwdError, error: cwdError, exitCode: 1, context: step.context };
768
770
  if (step.context === "fork" && step.sessionFile && fs.existsSync(step.sessionFile)) {
@@ -781,7 +783,7 @@ export async function runSingleStepInner(step, ctx) {
781
783
  let toolBudgetBlocked = false;
782
784
  let actualLaunchContractDigest = step.launchContractDigest;
783
785
  // A machine 'local' child edits this disk, so its local Git evidence is authoritative, as for an unplaced run.
784
- const mutationSnapshot = step.machine && !isRexLocalMachine(step.machine) ? { source: "tracked-files", trackedOnly: true, cwd: step.cwd ?? ctx.cwd, dirtyFiles: [], fingerprints: {}, unavailable: "Local Git evidence is not authoritative for a pane-native remote run." } : snapshotTrackedMutations(step.cwd ?? ctx.cwd);
786
+ const mutationSnapshot = step.machine && !editsLocalDisk(step.machine) ? remoteMutationSnapshot(step.cwd ?? ctx.cwd) : snapshotTrackedMutations(step.cwd ?? ctx.cwd);
785
787
  let finalMutationEvidence = await collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
786
788
  let contextOverflow = false;
787
789
  let launchWarningsEmitted = false;
@@ -944,7 +946,9 @@ export async function runSingleStepInner(step, ctx) {
944
946
  // A parked run still owes output diagnostics when it actually finishes.
945
947
  // Stopped/timedOut runs already have terminal failures, so terminal output diagnostics are deferred.
946
948
  const terminalDiagnosticsEligible = !run.interrupted && !run.stopped && !run.timedOut;
947
- const toolDiagnostic = run.exitCode === 0 && !run.error ? launch.capture.toolDiagnostic() : undefined;
949
+ const recordedToolDiagnostic = launch.capture.toolDiagnostic();
950
+ // An undeclared allowlisted tool aborts the child itself, so its diagnostic explains that abort's error.
951
+ const toolDiagnostic = (run.exitCode === 0 && !run.error) || recordedToolDiagnostic?.undeclared ? recordedToolDiagnostic : undefined;
948
952
  const toolAvailabilityError = toolDiagnostic ? formatChildToolDiagnostic(toolDiagnostic) : undefined;
949
953
  const runtimeAcknowledgedExtensions = launch.capture.runtimeAcknowledgedExtensions();
950
954
  const midToolExitError = run.currentTool
@@ -1007,8 +1011,7 @@ export async function runSingleStepInner(step, ctx) {
1007
1011
  const truncatedResponseError = hiddenError && !hiddenError.hasError && !validatedStructuredOutput && getTerminalAssistantStopReason(run.messages) === "length"
1008
1012
  ? TRUNCATED_RESPONSE_ERROR
1009
1013
  : undefined;
1010
- const remoteGitChanged = run.nativeMachine?.initialGit && run.nativeMachine.finalGit ? run.nativeMachine.initialGit.head !== run.nativeMachine.finalGit.head || run.nativeMachine.initialGit.dirty !== run.nativeMachine.finalGit.dirty : undefined;
1011
- const mutationEvidence = run.nativeMachine && !isRexLocalMachine(step.machine) ? { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: remoteGitChanged === true, ...(remoteGitChanged === undefined ? { unavailable: "Remote Git before/after evidence was incomplete." } : {}) } : await collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
1014
+ const mutationEvidence = run.nativeMachine && !editsLocalDisk(step.machine) ? remoteMutationEvidence(run.nativeMachine) : await collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
1012
1015
  finalMutationEvidence = mutationEvidence;
1013
1016
  const mutationAttemptObserved = run.observedMutationAttempt === true || mutationEvidence.attemptedMutation === true;
1014
1017
  // Validated structured output is persistable file content even when the final text is only
@@ -1289,7 +1292,7 @@ async function runSingleStep(step, ctx) {
1289
1292
  }
1290
1293
  function externalRunnerStatus(runner, machine) {
1291
1294
  if (runner?.type === "external-cli") {
1292
- return resolveExternalCliRunnerStatus(machine?.provider === "herdr" ? { ...runner, machine } : runner);
1295
+ return resolveExternalCliRunnerStatus(machine?.provider === "herdr" && "target" in machine ? { ...runner, machine } : runner);
1293
1296
  }
1294
1297
  if (runner?.type === "external-job") {
1295
1298
  return {