@vicary/pi-subagents 0.88.1 → 0.89.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +51 -1
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-4QFZZV3O.js → chunk-4AL6LDBY.js} +3 -1
  5. package/bundle/{chunk-5EMPFFO4.js → chunk-4FFKVLBG.js} +4 -4
  6. package/bundle/{chunk-L4YY2TOE.js → chunk-5TXWZB73.js} +1 -1
  7. package/bundle/{chunk-YDZ7BZD5.js → chunk-77VQEATI.js} +1 -1
  8. package/bundle/{chunk-7OX6O7DQ.js → chunk-BERAWSQQ.js} +5 -5
  9. package/bundle/{chunk-LV3CPYXJ.js → chunk-C22YEYFZ.js} +4 -4
  10. package/bundle/{chunk-AZPP3G4N.js → chunk-DVOXHOTY.js} +34 -5
  11. package/bundle/{chunk-2HKPEANZ.js → chunk-JLZFSOEL.js} +26 -15
  12. package/bundle/{chunk-CPSUJHZE.js → chunk-KCDPTXHT.js} +39 -10
  13. package/bundle/{chunk-4MVDMA5C.js → chunk-LWH7IGI3.js} +21 -7
  14. package/bundle/{chunk-DSHQWGHO.js → chunk-MIX3MCIF.js} +96 -96
  15. package/bundle/{chunk-BKISQ5CJ.js → chunk-NLDROUCR.js} +56 -34
  16. package/bundle/{chunk-2DIEL4WG.js → chunk-OUM6SEVD.js} +2 -2
  17. package/bundle/{chunk-XIA5GSEU.js → chunk-Q4VH72JI.js} +2 -2
  18. package/bundle/{chunk-D32H53HM.js → chunk-R3NH5XAL.js} +1 -1
  19. package/bundle/{chunk-CGWNA6EJ.js → chunk-R5XS4CVE.js} +98 -29
  20. package/bundle/{chunk-V7SZMS6W.js → chunk-RHMU7SXN.js} +2 -2
  21. package/bundle/{chunk-4ZQBZDF3.js → chunk-SG3NCWZW.js} +86 -20
  22. package/bundle/{chunk-KXW62VBU.js → chunk-SWGB2P5J.js} +1 -1
  23. package/bundle/{chunk-6CG2VAG4.js → chunk-TRN65L4F.js} +1 -1
  24. package/bundle/{chunk-GDR2ILWY.js → chunk-TXC7WIPL.js} +51 -22
  25. package/bundle/{chunk-IYT7X46U.js → chunk-UNLGCAC4.js} +5 -5
  26. package/bundle/{chunk-PYKBTBY6.js → chunk-URKQZHVH.js} +9 -9
  27. package/bundle/{chunk-W6HIYD2Z.js → chunk-UUW7P6KJ.js} +1 -1
  28. package/bundle/{chunk-CYKNHFXB.js → chunk-VEEUXJDO.js} +1 -1
  29. package/bundle/{chunk-JQTHG2ID.js → chunk-WMGQNIP7.js} +75 -32
  30. package/bundle/{chunk-47ZN7NKR.js → chunk-YJIU5WF4.js} +1 -1
  31. package/bundle/{chunk-RMZAAXIR.js → chunk-YLU5JFW2.js} +2 -2
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +2 -2
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +10 -4
  38. package/docs/configuration.md +2 -0
  39. package/docs/extension-api.md +1 -1
  40. package/docs/tool-reference.md +1 -1
  41. package/docs/workflows.md +5 -3
  42. package/package.json +2 -2
  43. package/src/extension/herdr-pi-bridge.js +79 -23
  44. package/src/extension/schemas.js +1 -1
  45. package/src/extension/subagent-options.js +5 -0
  46. package/src/intercom/result-intercom.js +3 -2
  47. package/src/runs/background/async-job-tracker.js +85 -9
  48. package/src/runs/background/async-status.d.ts +2 -0
  49. package/src/runs/background/async-status.js +8 -3
  50. package/src/runs/background/notify.d.ts +3 -0
  51. package/src/runs/background/notify.js +7 -2
  52. package/src/runs/background/run-status.js +3 -2
  53. package/src/runs/background/runner-child-launch.js +1 -0
  54. package/src/runs/background/subagent-runner.js +11 -8
  55. package/src/runs/foreground/execution.js +8 -7
  56. package/src/runs/foreground/subagent-executor.js +31 -5
  57. package/src/runs/shared/child-launch.d.ts +2 -0
  58. package/src/runs/shared/child-launch.js +1 -1
  59. package/src/runs/shared/child-session.d.ts +2 -1
  60. package/src/runs/shared/herdr-connection.d.ts +6 -0
  61. package/src/runs/shared/herdr-connection.js +11 -1
  62. package/src/runs/shared/herdr-machine.d.ts +2 -2
  63. package/src/runs/shared/herdr-machine.js +49 -22
  64. package/src/runs/shared/herdr-pane-host.d.ts +7 -19
  65. package/src/runs/shared/herdr-pane-host.js +48 -33
  66. package/src/runs/shared/herdr-pi-protocol.d.ts +1 -0
  67. package/src/runs/shared/herdr-pi-protocol.js +3 -2
  68. package/src/runs/shared/herdr-placed-run.d.ts +2 -12
  69. package/src/runs/shared/herdr-placed-run.js +10 -8
  70. package/src/runs/shared/kept-branch-text.d.ts +8 -0
  71. package/src/runs/shared/kept-branch-text.js +24 -0
  72. package/src/runs/shared/local-machine-access.d.ts +4 -1
  73. package/src/runs/shared/local-machine-access.js +6 -3
  74. package/src/runs/shared/mutation-evidence.d.ts +7 -1
  75. package/src/runs/shared/mutation-evidence.js +18 -2
  76. package/src/runs/shared/parallel-handoff.js +19 -7
  77. package/src/runs/shared/placed-run-owner.d.ts +4 -2
  78. package/src/runs/shared/placed-run-owner.js +15 -7
  79. package/src/runs/shared/rex-machine.d.ts +7 -3
  80. package/src/runs/shared/rex-machine.js +12 -9
  81. package/src/runs/shared/rex-pane-host.js +7 -27
  82. package/src/runs/shared/single-output.js +2 -2
  83. package/src/runs/shared/subagent-prompt-runtime.js +34 -0
  84. package/src/runs/shared/tool-availability.d.ts +4 -0
  85. package/src/runs/shared/tool-availability.js +7 -0
  86. package/src/runs/shared/worktree-cleanup-plan.js +2 -2
  87. package/src/runs/shared/worktree.d.ts +4 -14
  88. package/src/runs/shared/worktree.js +38 -8
  89. package/src/shared/types.d.ts +26 -2
  90. package/src/shared/utils.d.ts +2 -0
  91. package/src/shared/utils.js +9 -0
  92. package/src/workflows/workflow-child-summary.d.ts +2 -1
  93. package/src/workflows/workflow-child-summary.js +14 -6
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"`. This means the herdr terminal multiplexer; terminals of Herdr Core (`hc`, the Herdr app's terminal server) are not supported.
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 active 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. An allowlisted tool that an extension keeps inactive, such as pi-web-access's `web_enable` loader, can be left out of a request without failing the child.
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.1",
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": "f466f3b427dcef136202f4fb9b129b6e0ca760d2"
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",
@@ -141,7 +171,7 @@ export default function registerHerdrPiBridge(pi) {
141
171
  else if (request.operation === "follow-up")
142
172
  api.sendUserMessage(request.text ?? "", { deliverAs: "followUp" });
143
173
  else if (request.operation === "abort")
144
- api.abort();
174
+ ctx.abort();
145
175
  else {
146
176
  const entry = request.supervisorId ? supervisor.get(request.supervisorId) : undefined;
147
177
  if (!entry)
@@ -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:");
@@ -3,11 +3,11 @@ import * as path from "node:path";
3
3
  import { renderWidget, widgetRenderKey } from "../../tui/render.js";
4
4
  import { formatControlNoticeMessage } from "../shared/subagent-control.js";
5
5
  import { DIRS, SUBAGENT_CHILD_STATUS_EVENT, SUBAGENT_CONTROL_EVENT, SUBAGENT_CONTROL_INTERCOM_EVENT, SUBAGENT_JOBS_CHANGED_EVENT, SUBAGENT_STEERING_NOTICE_EVENT, WIDGET_ANIMATION_INTERVAL_MS, } from "../../shared/types.js";
6
- import { readStatus, resolveWatchPath } from "../../shared/utils.js";
6
+ import { isStatusAccessError, readStatus, resolveWatchPath } from "../../shared/utils.js";
7
7
  import { normalizeParallelGroups } from "./parallel-groups.js";
8
8
  import { reconcileAsyncRun, reconcileNestedAsyncDescendants } from "./stale-run-reconciler.js";
9
9
  import { findNestedRouteForRootId, hasLiveNestedDescendants, retainNestedLookupRoute, updateAsyncJobNestedProjection } from "../shared/nested-events.js";
10
- import { listAsyncRuns } from "./async-status.js";
10
+ import { listAsyncRuns, summarizeAsyncStatus } from "./async-status.js";
11
11
  import { EXTERNAL_JOB_BRIDGE_REQUEST_DIR, externalJobBridgeEligibility, serviceExternalJobBridgeRequests } from "../shared/external-job-bridge.js";
12
12
  import { shouldUseNativeFsWatch } from "../../shared/watch-strategy.js";
13
13
  import { parseWorkflowChildSummary } from "../../workflows/workflow-child-summary.js";
@@ -49,6 +49,12 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
49
49
  // Early native failure is visible before its publisher finishes. Retain only
50
50
  // that scoped observation, using the existing liveness sweep to renew delivery.
51
51
  const terminalPublications = new Map();
52
+ // Runs whose status.json this process may not read. An unreadable file says nothing about the
53
+ // runner, so the job keeps its last known state rather than reading as finished (#3295).
54
+ const unreadableStatusRuns = new Set();
55
+ // Restored runs whose status.json was unreadable, so their owner is unknown. Each is counted as
56
+ // this session's until a read shows otherwise; nothing writes to it before then.
57
+ const unverifiedRuns = new Set();
52
58
  const supervisorNoticeTimers = new Map();
53
59
  let rootWatcher;
54
60
  let nextLivenessAt = Date.now() + livenessIntervalMs;
@@ -424,9 +430,53 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
424
430
  runningJobIds.delete(asyncId);
425
431
  externalJobBridgeRuns.delete(asyncId);
426
432
  terminalPublications.delete(asyncId);
433
+ unreadableStatusRuns.delete(asyncId);
434
+ unverifiedRuns.delete(asyncId);
427
435
  clearSupervisorNotices(asyncId);
428
436
  };
437
+ const forgetJob = (asyncId) => {
438
+ cancelCleanup(asyncId);
439
+ closeJobWatcher(asyncId);
440
+ state.asyncJobs.delete(asyncId);
441
+ state.fleetJobs?.delete(asyncId);
442
+ options.onJobCleanup?.(asyncId);
443
+ };
429
444
  const refreshJob = (job) => {
445
+ if (unverifiedRuns.has(job.asyncId)) {
446
+ let stored = null;
447
+ let summary;
448
+ try {
449
+ stored = readStatus(job.asyncDir);
450
+ if (stored)
451
+ summary = summarizeAsyncStatus(job.asyncDir, stored);
452
+ }
453
+ catch (error) {
454
+ if (isStatusAccessError(error, job.asyncDir))
455
+ return false;
456
+ console.error(`[pi-subagents] Dropping restored async run '${job.asyncId}' at '${path.join(job.asyncDir, "status.json")}': ${error instanceof Error ? error.message : String(error)}.`);
457
+ }
458
+ const owners = state.currentSessionId ? ownerSessionIds(state.currentSessionId) : undefined;
459
+ if (!stored || !summary || (owners && !owners.has(stored.sessionId))) {
460
+ forgetJob(job.asyncId);
461
+ return true;
462
+ }
463
+ let restored;
464
+ try {
465
+ restored = summaryToJob(summary);
466
+ }
467
+ catch (error) {
468
+ if (!unreadableStatusRuns.has(job.asyncId)) {
469
+ unreadableStatusRuns.add(job.asyncId);
470
+ console.error(`Cannot read async control events for '${job.asyncDir}'; keeping it as running until they are readable:`, error);
471
+ }
472
+ return false;
473
+ }
474
+ // Become the job a normal restore would have made, but keep the placeholder's state so the
475
+ // refresh below sees any transition, and its cursor when restore could read events.jsonl.
476
+ Object.assign(job, restored, { status: job.status, controlEventCursor: job.controlEventCursor ?? restored.controlEventCursor });
477
+ rememberFleetJob(state, job);
478
+ unverifiedRuns.delete(job.asyncId);
479
+ }
430
480
  const widgetExpanded = withLastUiContext((ctx) => ctx.ui.getToolsExpanded?.() ?? false) ?? false;
431
481
  const widgetStateBefore = widgetRenderKey(job, widgetExpanded);
432
482
  let nestedRefreshFailed = false;
@@ -475,6 +525,7 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
475
525
  },
476
526
  });
477
527
  const status = reconciliation.status ?? readStatus(job.asyncDir);
528
+ unreadableStatusRuns.delete(job.asyncId);
478
529
  if (!bridgeAlreadyRequired) {
479
530
  const bridgeEligibility = externalJobBridgeEligibility(status?.steps);
480
531
  if (bridgeEligibility === "required")
@@ -612,6 +663,13 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
612
663
  console.error(`Failed to service external job bridge for '${job.asyncDir}':`, bridgeError);
613
664
  }
614
665
  }
666
+ if (isStatusAccessError(error, job.asyncDir)) {
667
+ if (!unreadableStatusRuns.has(job.asyncId)) {
668
+ unreadableStatusRuns.add(job.asyncId);
669
+ console.error(`Cannot read async status for '${job.asyncDir}'; keeping its last known state until it is readable:`, error);
670
+ }
671
+ return widgetRenderKey(job, widgetExpanded) !== widgetStateBefore;
672
+ }
615
673
  if (job.status !== "failed") {
616
674
  console.error(`Failed to read async status for '${job.asyncDir}':`, error);
617
675
  job.status = "failed";
@@ -751,11 +809,7 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
751
809
  const owners = state.currentSessionId ? ownerSessionIds(state.currentSessionId) : undefined;
752
810
  for (const job of state.asyncJobs.values()) {
753
811
  if (owners && job.sessionId !== undefined && !owners.has(job.sessionId)) {
754
- cancelCleanup(job.asyncId);
755
- closeJobWatcher(job.asyncId);
756
- state.asyncJobs.delete(job.asyncId);
757
- state.fleetJobs?.delete(job.asyncId);
758
- options.onJobCleanup?.(job.asyncId);
812
+ forgetJob(job.asyncId);
759
813
  widgetChanged = true;
760
814
  continue;
761
815
  }
@@ -881,6 +935,8 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
881
935
  runningJobIds.clear();
882
936
  externalJobBridgeRuns.clear();
883
937
  terminalPublications.clear();
938
+ unreadableStatusRuns.clear();
939
+ unverifiedRuns.clear();
884
940
  clearSupervisorNotices();
885
941
  };
886
942
  const resetJobs = (ctx) => {
@@ -907,9 +963,13 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
907
963
  if (!state.currentSessionId)
908
964
  return;
909
965
  let runs;
966
+ const unreadable = [];
910
967
  try {
911
968
  // A workflow whose Pi exited is repaired here, in the session that owns it, which then delivers its notice.
912
- runs = listAsyncRuns(asyncDirRoot, { states: ["queued", "running"], sessionId: state.currentSessionId, resultsDir, kill: options.kill, now: options.now, adoptCompletionOwnerId: state.completionOwnerId }, observeStatus);
969
+ runs = listAsyncRuns(asyncDirRoot, {
970
+ states: ["queued", "running"], sessionId: state.currentSessionId, resultsDir, kill: options.kill, now: options.now, adoptCompletionOwnerId: state.completionOwnerId,
971
+ onUnreadableActiveRun: (runId, asyncDir) => unreadable.push({ runId, asyncDir }),
972
+ }, observeStatus);
913
973
  }
914
974
  catch (error) {
915
975
  console.error(`Failed to restore active async jobs from '${asyncDirRoot}':`, error);
@@ -923,8 +983,24 @@ export function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
923
983
  rememberFleetJob(state, job);
924
984
  watchJob(job);
925
985
  }
986
+ // An unreadable run may still be working: idle must not be reported until a read settles it.
987
+ for (const { runId, asyncDir } of unreadable) {
988
+ if (state.asyncJobs.has(runId))
989
+ continue;
990
+ const job = { asyncId: runId, asyncDir, status: "running", sessionId: state.currentSessionId, updatedAt: Date.now() };
991
+ try {
992
+ job.controlEventCursor = restoredControlEventCursor(asyncDir);
993
+ }
994
+ catch {
995
+ // An unsearchable run directory: refreshJob reads the cursor once the run is verified.
996
+ }
997
+ state.asyncJobs.set(runId, job);
998
+ runningJobIds.add(runId);
999
+ unverifiedRuns.add(runId);
1000
+ watchJob(job);
1001
+ }
926
1002
  state.statusProjectionSessionId = state.currentSessionId;
927
- if (runs.length === 0)
1003
+ if (runs.length === 0 && unreadable.length === 0)
928
1004
  return;
929
1005
  ensurePoller();
930
1006
  rerenderLastWidget();
@@ -148,6 +148,8 @@ interface AsyncRunListOptions {
148
148
  adoptCompletionOwnerId?: string;
149
149
  /** Receives the warning for a skipped corrupt terminal status, so an open TUI can show it as a notice instead of console output. */
150
150
  onCorruptStatus?: (warning: string) => void;
151
+ /** Receives an active run kept in the index whose status.json this process may not read. */
152
+ onUnreadableActiveRun?: (runId: string, asyncDir: string) => void;
151
153
  }
152
154
  type TargetedAsyncRunResolution = {
153
155
  kind: "exact";
@@ -3,7 +3,7 @@ import * as path from "node:path";
3
3
  import { formatDuration, formatModelThinking, formatTokens, shortenPath } from "../../shared/formatters.js";
4
4
  import { previewDisplayText } from "../../shared/display-text.js";
5
5
  import { formatActivityLabel, formatParallelOutcome } from "../../shared/status-format.js";
6
- import { readStatus } from "../../shared/utils.js";
6
+ import { isStatusAccessError, readStatus } from "../../shared/utils.js";
7
7
  import { attachRootChildrenToSteps, buildNestedRouteIndex, findNestedRouteForRootId, projectNestedEvents } from "../shared/nested-events.js";
8
8
  import { formatNestedRunStatusLines } from "../shared/nested-render.js";
9
9
  import { formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.js";
@@ -40,6 +40,7 @@ function isAsyncStatusIsolationError(asyncDir, error) {
40
40
  // Status path -> last logged signature. A corrupt run is re-scanned on every
41
41
  // status poll, so the line repeats only when the file or the outcome changes.
42
42
  const reportedCorruptStatus = new Map();
43
+ /** Returns whether the active-run marker is still in place. */
43
44
  function isolateCorruptActiveRun(asyncDir, runId, error, now) {
44
45
  const statusPath = path.join(asyncDir, "status.json");
45
46
  const processTerminal = readProcessTerminal(asyncDir, { runId });
@@ -53,9 +54,11 @@ function isolateCorruptActiveRun(asyncDir, runId, error, now) {
53
54
  const markerCanBeReleased = processTerminal?.state === "observed"
54
55
  || (markerAge !== undefined && markerAge > DEFAULT_STALE_TERMINAL_ACTIVE_MARKER_MS);
55
56
  let markerAction = "active marker retained because runner liveness is unknown";
57
+ let retained = true;
56
58
  if (markerCanBeReleased) {
57
59
  try {
58
60
  releaseActiveRunIndex(asyncDir);
61
+ retained = false;
59
62
  markerAction = processTerminal?.state === "observed"
60
63
  ? "active marker released after observed process-terminal proof"
61
64
  : "stale active marker released";
@@ -75,9 +78,10 @@ function isolateCorruptActiveRun(asyncDir, runId, error, now) {
75
78
  }
76
79
  const signature = `${fileSignature}\n${line}`;
77
80
  if (reportedCorruptStatus.get(statusPath) === signature)
78
- return;
81
+ return retained;
79
82
  reportedCorruptStatus.set(statusPath, signature);
80
83
  console.error(line);
84
+ return retained;
81
85
  }
82
86
  function isNotFoundError(error) {
83
87
  return typeof error === "object"
@@ -464,7 +468,8 @@ export function listAsyncRuns(asyncDirRoot, options = {}, observeStatus) {
464
468
  observeStatus?.(null);
465
469
  if (!activeEntries.has(entry) || !isAsyncStatusIsolationError(asyncDir, error))
466
470
  throw error;
467
- isolateCorruptActiveRun(asyncDir, entry, error, options.now);
471
+ if (isolateCorruptActiveRun(asyncDir, entry, error, options.now) && isStatusAccessError(error, asyncDir))
472
+ options.onUnreadableActiveRun?.(entry, asyncDir);
468
473
  continue;
469
474
  }
470
475
  if (!status) {
@@ -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[];