brl-subagent 2.7.0 → 2.9.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 (51) hide show
  1. package/AGENT.md +3 -3
  2. package/README.md +18 -10
  3. package/package.json +6 -5
  4. package/src/agent-tools.ts +332 -0
  5. package/src/background-pipeline.ts +1025 -0
  6. package/src/boot-recovery.ts +313 -0
  7. package/src/commands.ts +137 -0
  8. package/src/concurrency.ts +26 -5
  9. package/src/delegate-handler.ts +2261 -0
  10. package/src/engineering-bar.ts +69 -0
  11. package/src/event-bus.ts +10 -0
  12. package/src/git.ts +274 -5
  13. package/src/headstate.ts +471 -0
  14. package/src/history.ts +21 -3
  15. package/src/index.ts +127 -3943
  16. package/src/kill-escalation.ts +87 -7
  17. package/src/loader.ts +47 -1
  18. package/src/logging.ts +1 -1
  19. package/src/mode-prologue.ts +4 -10
  20. package/src/mode-runners.ts +1575 -0
  21. package/src/notify-completion.ts +180 -12
  22. package/src/params.ts +211 -37
  23. package/src/preflight.ts +123 -16
  24. package/src/prelude.ts +92 -7
  25. package/src/presets.ts +85 -18
  26. package/src/proc.ts +2 -3
  27. package/src/project-flags.ts +3 -3
  28. package/src/recovery-engine.ts +11 -1
  29. package/src/recovery-surface.ts +1 -2
  30. package/src/recovery.ts +155 -20
  31. package/src/reports.ts +1 -7
  32. package/src/run-registry.ts +22 -3
  33. package/src/runner.ts +80 -21
  34. package/src/runtime.ts +50 -0
  35. package/src/sanitize.ts +20 -2
  36. package/src/scheduler.ts +1 -2
  37. package/src/schema.ts +37 -7
  38. package/src/scratch-root.ts +909 -0
  39. package/src/scratch-spawn.ts +256 -0
  40. package/src/session-manager.ts +854 -200
  41. package/src/state.ts +130 -30
  42. package/src/templates.ts +42 -17
  43. package/src/terminal-notifier.ts +405 -0
  44. package/src/transcript.ts +1 -1
  45. package/src/tui-format.ts +177 -7
  46. package/src/tui.ts +115 -57
  47. package/src/types.ts +206 -5
  48. package/src/unit-params.ts +113 -0
  49. package/src/unit-run.ts +45 -16
  50. package/src/validate.ts +89 -11
  51. package/src/worktree-report.ts +142 -0
package/AGENT.md CHANGED
@@ -41,7 +41,7 @@ delegation-heavy work.
41
41
  - Delivery mode by status holds at knob `"all"`: `failed`/`stopped` → steering you to act; `completed` → follow-up. The `completionNotify` knob changes both the delivery mode and the wake: under `"failed"` a `completed` run is delivered as a passive `nextTurn` (no wake) while `failed`/`stopped` still steer; under `"off"` everything is a passive `nextTurn` and nothing wakes you. (The knob controls whether an idle conductor is triggered — see below.)
42
42
  - Knob dependency: polling is correct only when wakes are disabled (`completionNotify: "off"`). The wake is per-terminal-status and knob-scoped: under `"all"` a terminal run always wakes you; under `"failed"` only a `failed` or `stopped` run wakes you — a `completed` run stays a passive `nextTurn` (no wake); under `"off"` nothing wakes you. So repeated polling is wrong; a single status check as a stall check is legitimate, and a status check is needed only when the knob will not wake you for that outcome (`"off"`, or a `completed` run under `"failed"`).
43
43
  - One message per run — the extension deduplicates on the first terminal event for a run id, so don't expect multiple messages for a single run. A fan-out wakes you once per agent — still one message per run (each agent is its own run), never coalesced.
44
- - **Transport failures auto-retry once.** A background run whose conductor-side transport dropped (`exit_error` with a connection/network signature — `Connection error.`, `ECONNRESET`, `socket hang up`, `fetch failed`, `ETIMEDOUT`, …) is re-dispatched **once** with its recorded task and params, recorded as `attempt: 2` (`resumeOf` the source). The retry's **system prompt** carries a short `<resume-context>` resume block — inspect `git status --short`, the recent history, the `/tmp/brl-<label>-bank.md` progress bank, and the previous attempt's retained session directory when it exists — so it continues from what survived a drop instead of redoing it. The settle path keeps that directory for exactly this class of failure (marked `.transport-retained`, bounded to 5 dirs / 50 MB / 14 days by a sweep at the same choke point), so the retry can read the conversation attempt 1 lost. The block is system-prompt-only (outside the `<task>` fence): routing, thinking, model and the capability pre-flight still see the recorded original task, which stays byte-identical to the original — the spawn result's `Task:` line therefore no longer shows the resume marker (`attempt`/`resumeOf` carry that lineage). The source run's completion message is suppressed and replaced by a warning toast, so the retry's own settle is the wake you get — do not re-dispatch it yourself. A second transport failure surfaces as an ordinary failure; non-transport failures, foreground runs, and fan-out units are never auto-retried (`retryRunId` stays your call for those).
44
+ - **Transport failures auto-retry once.** A background run whose conductor-side transport dropped (`exit_error` with a connection/network signature — `Connection error.`, `ECONNRESET`, `socket hang up`, `fetch failed`, `ETIMEDOUT`, …) is re-dispatched **once** with its recorded task and params, recorded as `attempt: 2` (`resumeOf` the source). The retry's **system prompt** carries a short `<resume-context>` resume block — inspect `git status --short`, the recent history, the run's own progress bank under the validated cache root (`<root>/runs/<runId>/bank.md`; named only when that directory exists), and the previous attempt's retained session directory when it exists — so it continues from what survived a drop instead of redoing it. The settle path keeps that directory for exactly this class of failure (marked `.transport-retained`, bounded to 5 dirs / 50 MB / 14 days by a sweep at the same choke point), so the retry can read the conversation attempt 1 lost. The block is system-prompt-only (outside the `<task>` fence): routing, thinking, model and the capability pre-flight still see the recorded original task, which stays byte-identical to the original — the spawn result's `Task:` line therefore no longer shows the resume marker (`attempt`/`resumeOf` carry that lineage). The source run's completion message is suppressed and replaced by a warning toast, so the retry's own settle is the wake you get — do not re-dispatch it yourself. A second transport failure surfaces as an ordinary failure; non-transport failures, foreground runs, and fan-out units are never auto-retried (`retryRunId` stays your call for those).
45
45
  - Honest records: trust the message's `errorCategory`/abort source over your own guess. The provider/abort origin is authoritative on why the run stopped.
46
46
  - Steering is not an abort. Being steered to act on a terminal run is not terminating it. A real `stop` is an abort — and a stopped run still wakes you.
47
47
 
@@ -78,8 +78,8 @@ delegation-heavy work.
78
78
 
79
79
  ## Deadlines and retries
80
80
 
81
- - `timeout` (ms) is a **deadline, not a ceiling** — an explicit value is honored as given; 30 minutes is only the default for a background run that passes none (a foreground run is not capped). Background expiry aborts the session (the run ends `stopped`); foreground expiry kills the process. Because background is now the default under `auto`, remember the 30-minute deadline: pass an explicit `timeout` for anything expected to run longer.
82
- - `retryOnTimeout` applies to **foreground runs only**. A timed-out background run is not auto-retried on the deadline: re-dispatch it with `retryRunId` if that is the right call. The one automatic retry is the **transport-class** one above — a background run that died on a dropped connection is replayed once. The same applies to an interrupted run — recovery is always an explicit `retryRunId` call, never automatic (auto mode is not yet accepted).
81
+ - `timeout` (ms) is a **deadline, not a ceiling** — an explicit value is honored as given; 30 minutes is only the default for a background run that passes none (a foreground run is not capped). Background expiry aborts the session (the agent ends `stopped`, the run record is `failed`/`timeout`); foreground expiry kills the process. Because background is now the default under `auto`, remember the 30-minute deadline: pass an explicit `timeout` for anything expected to run longer.
82
+ - `retryOnTimeout` applies to **foreground runs only**. A timed-out background run is not auto-retried on the deadline: re-dispatch it with `retryRunId` if that is the right call. The one automatic retry is the **transport-class** one above — a background run that died on a dropped connection is replayed once. The same applies to an interrupted run — recovery is always an explicit `retryRunId` call, never automatic (auto mode is not yet accepted). A run recorded before its prompt was ever issued is settled as **failed**, so the retry menu never lists it as interrupted.
83
83
 
84
84
  ## Mechanics pointer
85
85
 
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > Multi-agent orchestration for [pi](https://github.com/earendil-works/pi) — chain, parallel, and dependency-graph delegation to isolated subagents with per-step model routing, preset-driven tool scoping, thinking-level control, and background execution with live monitoring, real abort, and per-agent timeouts.
4
4
 
5
- **Version:** 2.7.0 · **Author:** Azmeen Afandi / [Beeroo Labs](https://beeroolabs.com) · **License:** MIT
5
+ **Version:** 2.9.0 · **Author:** Azmeen Afandi / [Beeroo Labs](https://beeroolabs.com) · **License:** MIT
6
6
 
7
7
  ---
8
8
 
@@ -14,7 +14,7 @@
14
14
  - **True background execution** — live monitor, real abort (`stop_subagent`), per-agent timeouts, and a 30-minute default deadline for runs that don't set one. Nothing orphans; nothing leaks.
15
15
  - **Preset-driven tool scoping** — every subagent runs with exactly the tools its job needs, restricted by preset or per-call `tools`/`excludeTools`, with auto-route that picks the right preset when you don't.
16
16
  - **Templates with slots** — saved, file-backed task templates with `${param}` placeholders for workflows you run again and again.
17
- - **Safety by default** — task-fence injection protection, sanitized error paths, owner-only persistence (`0o700` stores, `0o600` files; the directory mode is repaired on every write and is the confidentiality boundary), and a 1900+ test suite pinning every contract against the real pi SDK.
17
+ - **Safety by default** — task-fence injection protection, sanitized error paths, owner-only persistence (`0o700` stores, `0o600` files; the directory mode is repaired on every write and is the confidentiality boundary), and a 3000+ test suite pinning every contract against the real pi SDK.
18
18
 
19
19
  ---
20
20
 
@@ -88,13 +88,13 @@ All settings persist across sessions.
88
88
  | `params` | object | — | Values for `${param}` slots in the template. All slots must be filled; missing ones error. |
89
89
  | `systemPrompt` | string | — | Extra instructions or a different persona for the subagent. |
90
90
  | `inheritSystemPrompt` | boolean | `true` | Whether to inherit the main agent's system prompt. Set `false` to save tokens. |
91
- | `thinkingLevel` | string | — | `off` / `minimal` / `low` / `medium` / `high` / `xhigh`. Capped at user's configured max. |
91
+ | `thinkingLevel` | string | — | `off` / `minimal` / `low` / `medium` / `high` / `xhigh`. Capped at user's configured max. Matched **exactly** (case and whitespace matter): an unknown value is rejected before anything launches — including pi's own `max`, which is not a delegated level. `""` or an omitted field uses the configured max. |
92
92
  | `outputFile` | string | — | Path for the subagent to write full findings. Returns only a summary. |
93
- | `timeout` | number | — | Max milliseconds. Foreground: exceeded → SIGTERM (5s grace) → SIGKILL. Background: the session is aborted and the run ends `stopped` with the timeout reason. A background run with no explicit `timeout` gets the 30-minute default deadline — an explicit timeout is honored as given (a default, not a ceiling). A raw value `≥ 2^31-1` normalizes to no timeout (for a background run, the 30-minute default then applies). |
93
+ | `timeout` | number | — | Max milliseconds. Foreground: exceeded → SIGTERM (5s grace) → SIGKILL. Background: the session is aborted, the agent ends `stopped`, and the run record is finalized `failed` with `errorCategory: "timeout"`; a settle that arrives later amends that record's cost/tokens/output instead of rewriting its classification. One owner arms it — `spawnBackgroundSession`, before the prompt, with the budget anchored at the run record's creation. A background run with no explicit `timeout` gets the 30-minute default deadline — an explicit timeout is honored as given (a default, not a ceiling). A raw value `≥ 2^31-1` normalizes to no timeout (for a background run, the 30-minute default then applies). |
94
94
  | `cwd` | string | — | Working directory. Defaults to conductor's cwd. |
95
95
  | `background` | boolean | conditional | Spawn as an independent background session; returns an ID immediately. **Omitted**, a single task or a `tasks` fan-out runs in the background when the *effective* `approvalMode` is `auto` (call param, else config), and stays foreground under `writes`/`always` or for `chain`/`graph` — see [Background execution](#background-execution). With `tasks` it fans out (one background agent per task, one ID per task), and the conductor is woken once per agent as each finishes. Pass `false` for a quick probe whose answer the next step needs inline. |
96
96
  | `priority` | string | — | Concurrency priority: `critical` / `high` / `normal` / `low`. Defaults to `normal`; higher-priority delegations queue ahead. `tasks[]` / `graph[]` steps can set `priority` per unit (see below). |
97
- | `tools` | array | — | Explicit tool allowlist for the subagent. |
97
+ | `tools` | array | — | Explicit tool allowlist for the subagent. **An empty array (`tools: []`) requests zero child tools** — it maps to pi's `--no-tools`, which also wins over `noBuiltinTools`. Omit the field to keep pi's defaults. |
98
98
  | `excludeTools` | array | — | Tool names to disable for the subagent. |
99
99
  | `noBuiltinTools` | boolean | — | Disable all pi built-in tools for the subagent. |
100
100
 
@@ -110,9 +110,13 @@ All settings persist across sessions.
110
110
 
111
111
  **Capability pre-flight:** before spawning, the extension checks that the resolved toolset can actually do the task — a run/execute/test/compile/benchmark task with no `bash`, or an exploration task (search/grep/find/list/locate/glob) with none of `find`/`ls`/`grep`/`bash`. Such a dispatch is **rejected** by default; `force: true` downgrades the rejection to a **warning**. `force` never suppresses an `outputFile`-without-write conflict — that stays a hard error. Warnings are surfaced in the returned result in every mode.
112
112
 
113
+ **An empty tool list means no tools (`tools: []`):** `tools: []` is an explicit *restriction*, not an absent value. A foreground child is spawned with pi's `--no-tools`, so all built-in, extension, custom and MCP tools are inactive for that run, and it wins over `noBuiltinTools` (`[]` can never widen into "built-ins off, extension tools on"). A background run passes the same empty list to the SDK session, so it starts with zero active tools. When the resolved tool allowlist is omitted, Pi's normal selection applies unless `noBuiltinTools` or `excludeTools` restrict it; a preset may still supply an allowlist. Before this fix, a resolved empty allowlist alone incorrectly fell back to that selection in foreground runs. `[]` combined with `excludeTools` still has no tools; `excludeTools` can only disable.
114
+
115
+ This is a **tool-access setting, not a security sandbox.** In the foreground, configured extensions and MCP servers still load and connect at child startup, because users deliberately rely on that startup (and on extension *hooks* such as permission gates) — `[]` denies the model their tools, it does not prevent the code from running, and it is no defence against an extension that reactivates tools on purpose. Background runs are unchanged: they never load extensions or skills (`noExtensions`/`noSkills`) and start no MCP servers at all, with or without `tools`. A dispatch that needs zero capabilities therefore still costs the child its extension initialisation time; if an `outputFile` is requested alongside `tools: []`, the dispatch is rejected before launch, because no write tool exists to write that file.
116
+
113
117
  **Retries (`retryRunId`):** a retry rebuilds the parameter object from a fixed set of fields, falling back to the original run's recorded values, with explicit values on the retry call winning: `task`, `label`, `model`, `preset`, `systemPrompt`, `inheritSystemPrompt`, `thinkingLevel`, `priority`, `outputFile`, `timeout`, `cwd`, `tools`, `excludeTools`, `noBuiltinTools`, plus the four **execution-shape** fields `background`, `gitMode`, `approvalMode` and `force`.
114
118
 
115
- **Interrupted runs:** a run whose conductor died mid-run is marked interrupted (it keeps its persisted session file) and is surfaced as **Interrupted** in `/brl-subagent history` and in `/brl-subagent retry` — including after a crash + fresh boot, when it is reconstructed from the durable per-run registry (plus the background agent record). Recover one with `retryRunId: <run-id>`, or abandon it from the retry menu — abandon finalizes it as stopped, prunes its session file, and sends no completion wake. A **foreground** run's task is not persisted, so its crashed row shows no task and a retry needs the task supplied explicitly; a background run keeps its task in its agent record. The recovery posture (`/brl-subagent recovery`, default `offer`) controls whether a boot announces interrupted runs with one turn-boundary notice; `off` silences it. Recovery is never automatic — there is no `auto` mode.
119
+ **Interrupted runs:** a run whose conductor died mid-run is marked interrupted (it keeps its persisted session file) and is surfaced as **Interrupted** in `/brl-subagent history` and in `/brl-subagent retry` — including after a crash + fresh boot, when it is reconstructed from the durable per-run registry (plus the background agent record). Recover one with `retryRunId: <run-id>`, or abandon it from the retry menu — abandon finalizes it as stopped, prunes its session file, and sends no completion wake. A **foreground** run's task is not persisted, so its crashed row shows no task and a retry needs the task supplied explicitly; a background run keeps its task in its agent record. The recovery posture (`/brl-subagent recovery`, default `offer`) controls whether a boot announces interrupted runs with one turn-boundary notice; `off` silences it. Recovery is never automatic — there is no `auto` mode. A dispatch that died **before its prompt was issued** is not an interrupted run: it is finalized failed and never offered for retry.
116
120
 
117
121
  **The execution-shape fields are restored, so a retry keeps the original's shape:** retrying a background run re-runs it in the background (with its completion wake), a `gitMode: 'branch'` retry keeps its work branch, an `approvalMode`-constrained retry keeps that gating, and a retry that was capability-blocked keeps its `force`. Passing any of them explicitly on the retry call overrides the recorded value. One qualification on `gitMode`: when neither the record nor the call carries one, the **configured** default still applies — so a user with a global `gitMode: 'branch'` gets a work branch on every retry, and one with the default `'none'` gets none. Do not assume "no work branch" without checking the effective `gitMode`.
118
122
 
@@ -128,7 +132,7 @@ A **background** run that settles `failed` with `errorCategory: 'exit_error'` an
128
132
 
129
133
  The retry is a normal dispatch of the existing `retryRunId` shape: the recorded task, model, thinking level, tools, `cwd`, `timeout` and preset are restored, the record continues the logical dispatch (`resumeOf` the source run, `attempt: 2`), and every gate (session cost, approval, capability pre-flight) runs again. The source run's completion message is **suppressed** — replaced by a warning toast (`Transport failure — auto-retrying once (attempt 2/2)`), so the retry's own terminal settle is the wake. If the retry also fails, that failure is surfaced as an ordinary one: **one retry per logical dispatch, never a chain**.
130
134
 
131
- A drop costs the child its context, not its files, so the retry is a **resume**: its **system prompt** carries a bounded `<resume-context>` block (outside the `<task>` fence) naming the previous attempt's id, the fact that the directory may already hold uncommitted edits, `git status --short` / `git log --oneline -8`, the `/tmp/brl-<label>-bank.md` progress bank (`<label>` is the source run's label, sanitized for a filename), and — when the settle path retained it — the previous attempt's session directory as an **absolute** path, with the instruction to read the newest `.jsonl` inside. It closes with "continue from what exists; do NOT redo committed, written, or banked work". The block rides the **system prompt** only — never inside the `<task>` fence — and the recorded task stays byte-identical to the original: that is what resolution, auto-routing, thinking level and the H1 capability checks see, and it is kept on the retry's own record so a further retry cannot stack preambles. Manual `retryRunId` dispatches do not get a resume block.
135
+ A drop costs the child its context, not its files, so the retry is a **resume**: its **system prompt** carries a bounded `<resume-context>` block (outside the `<task>` fence) naming the previous attempt's id, the fact that the directory may already hold uncommitted edits, `git status --short` / `git log --oneline -8`, the run's own progress bank at `<cache>/runs/<runId>/bank.md` (the cache root is `~/.cache/brl-subagent` on Linux, `~/Library/Caches/brl-subagent` on macOS, `%LOCALAPPDATA%\brl-subagent` on Windows; a foreground child sees the same directory as `$BRL_SCRATCH`), and — when the settle path retained it — the previous attempt's session directory as an **absolute** path, with the instruction to read the newest `.jsonl` inside. It closes with "continue from what exists; do NOT redo committed, written, or banked work". The block rides the **system prompt** only — never inside the `<task>` fence — and the recorded task stays byte-identical to the original: that is what resolution, auto-routing, thinking level and the H1 capability checks see, and it is kept on the retry's own record so a further retry cannot stack preambles. Manual `retryRunId` dispatches do not get a resume block.
132
136
 
133
137
  Out of scope by construction: non-transport failures, foreground runs (a synchronous failure is already visible, and `retryOnTimeout` covers the timeout case), fan-out units (their records carry no `originalParams`), and chain/graph. Recovery from an interrupted run stays an explicit `retryRunId` call.
134
138
 
@@ -184,10 +188,14 @@ model: anthropic/claude-opus-4-6
184
188
  tools:
185
189
  - read
186
190
  - bash
191
+ # optional — capture the run's findings to this path; needs the write tool
192
+ outputFile: findings.md
187
193
  thinkingLevel: high
188
194
  ---
189
195
  ```
190
196
 
197
+ A preset `outputFile` is validated at dispatch exactly like the `outputFile` parameter — it requires the `write` tool, so a preset that excludes `write` is a hard conflict. `timeout` is deliberately **not** a preset field: the deadline belongs to the call/template tier, not the persona (ADR 0022 §6).
198
+
191
199
  Custom presets override built-ins with the same name and survive `pi install` updates.
192
200
 
193
201
  Refer to a preset via the `preset` parameter of `delegate_task` (see above). Parameters on `delegate_task` override preset values.
@@ -234,7 +242,7 @@ Supported frontmatter fields:
234
242
  | `thinkingLevel` | string | `off` / `minimal` / `low` / `medium` / `high` / `xhigh` |
235
243
  | `outputFile` | string | Output file path (may contain `${param}` slots) |
236
244
  | `timeout` | number | Max milliseconds for the delegated run |
237
- | `tools` | list | Tool allowlist |
245
+ | `tools` | list | Tool allowlist (empty = no tools) |
238
246
  | `excludeTools` | list | Tools to exclude |
239
247
  | `noBuiltinTools` | `"true"` / `"false"` | Disable all pi built-in tools |
240
248
  | `inheritSystemPrompt` | `"true"` / `"false"` | Override system-prompt inheritance (default `true`) |
@@ -314,7 +322,7 @@ The approval-aware fallback is the safety property: background runs have no appr
314
322
 
315
323
  **Background safety controls (issue #28):** background agents honor the same safety controls as foreground runs — no more unattended sessions that bypass approval, git isolation, deadlines, or cost:
316
324
 
317
- - **Per-agent timeout** — the deadline is armed immediately after the prompt is issued, so in-prompt preflight (auth, model resolution) counts toward it. A background run with no explicit `timeout` gets a 30-minute default deadline (the issue #28 orphan protection); an explicit timeout is honored as given — 30 minutes is the default, not a ceiling. On expiry the session is aborted and the agent ends with status `stopped` and the timeout reason. Timeout values are normalized (`0`/negative/`NaN`/`Infinity`/`≥ 2^31` → no timeout, which for a background run means the 30-minute default) and a double-fire guard prevents the timer from acting on an already-settled agent.
325
+ - **Per-agent timeout** — exactly one deadline is armed per run, by the session that owns it, before the prompt is issued; the budget is anchored at the run record's creation, so the setup and the in-prompt preflight (auth, model resolution) both count toward it. A background run with no explicit `timeout` gets a 30-minute default deadline (the issue #28 orphan protection); an explicit timeout is honored as given — 30 minutes is the default, not a ceiling. On expiry the session is aborted, the agent ends with status `stopped` and the timeout reason, and the run record becomes `failed` / `timeout` — written at the deadline and amended (never re-classified) if the prompt settles later. The abort is cooperative: a prompt that ignores it keeps running, and that run keeps its session directory and its branch lock (and has no registry entry). Timeout values are normalized (`0`/negative/`NaN`/`Infinity`/`≥ 2^31` → no timeout, which for a background run means the 30-minute default) and a double-fire guard prevents the timer from acting on an already-settled agent.
318
326
  - **Session cost limit (R5)** — the cost check runs before the background spawn, so a session at its limit cannot bypass it by delegating to background. For a background fan-out the whole batch is checked up front as per-task estimate × N.
319
327
  - **Approval mode** — `approvalMode: 'always'` is rejected for background agents (there is no interactive dialog to approve a diff while running unattended); `'writes'` silently auto-approves with a warning logged. For a fan-out, `'always'` rejects the whole batch before any spawn and `'writes'` warns once for the batch.
320
328
  - **Transport auto-retry** — a run that dies on a dropped connection is replayed once with its recorded params (see [Transport auto-retry](#transport-auto-retry)), carrying a `<resume-context>` block on the system-prompt side that names the surviving files and the progress bank; the source notice is replaced by a toast so a lost connection doesn't read as a lost run. A second failure surfaces normally.
@@ -324,7 +332,7 @@ The approval-aware fallback is the safety property: background runs have no appr
324
332
 
325
333
  `background: true` with `tasks: [...]` fans out: every task starts as its own background agent, the call returns immediately with **one ID per task** in task order, and the conductor is woken with **one completion message per agent** as each finishes — no coalescing, no batch wake. `chain` and `graph` cannot be combined with `background: true` (rejected loudly): sequential dependencies and dependency waves do not survive fan-out.
326
334
 
327
- Fan-out validates the entire batch before spawning anything. Any invalid task — `cwd`, `outputFile`, or a pre-task check — rejects the whole batch before a single spawn starts, and the error names the task (`Task N ("label")`). Per-task overrides are honoured: `model`, `thinkingLevel`, `tools` / `excludeTools` / `noBuiltinTools`, `systemPrompt` / `inheritSystemPrompt`, `outputFile`, `timeout`, `cwd`, `priority`, `label`.
335
+ Fan-out validates the entire batch before spawning anything. Any invalid task — `cwd`, `outputFile`, an unsupported `thinkingLevel`, or a pre-task check — rejects the whole batch before a single spawn starts, and the error names the task (`Task N ("label")`). Per-task overrides are honoured: `model`, `thinkingLevel`, `tools` / `excludeTools` / `noBuiltinTools`, `systemPrompt` / `inheritSystemPrompt`, `outputFile`, `timeout`, `cwd`, `priority`, `label`.
328
336
 
329
337
  Three checks reject the fan-out up front, before any spawn: `approvalMode: 'always'`; `gitMode: 'branch'` for the batch (the git lock is awaited inside the first spawn and held until that agent settles, so branch-mode spawns targeting the same repository would serialize and block the call — the rule is blanket because the lock is keyed by the resolved repository root, so any two units of the same repo contend); and the session cost limit, checked as per-task estimate × N.
330
338
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brl-subagent",
3
- "version": "2.7.0",
3
+ "version": "2.9.0",
4
4
  "description": "Subagent delegation for pi — blocking or background runs, chain/parallel/graph modes, presets and task templates, live monitor, and dispatch capability guards.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -29,6 +29,7 @@
29
29
  },
30
30
  "scripts": {
31
31
  "typecheck": "tsc --noEmit",
32
+ "check:imports": "node scripts/check-imports.mjs",
32
33
  "docs:arch": "node scripts/docs-arch.mjs --write",
33
34
  "docs:decisions": "node scripts/docs-decisions.mjs --write"
34
35
  },
@@ -40,10 +41,10 @@
40
41
  "typebox": "*"
41
42
  },
42
43
  "devDependencies": {
43
- "@earendil-works/pi-agent-core": "^1.4.0",
44
- "@earendil-works/pi-ai": "^1.4.0",
45
- "@earendil-works/pi-coding-agent": "^1.4.0",
46
- "@earendil-works/pi-tui": "^1.4.0",
44
+ "@earendil-works/pi-agent-core": "^1.5.2",
45
+ "@earendil-works/pi-ai": "^1.5.2",
46
+ "@earendil-works/pi-coding-agent": "^1.5.2",
47
+ "@earendil-works/pi-tui": "^1.5.2",
47
48
  "jiti": "^2.7.0",
48
49
  "typebox": "1.3.27",
49
50
  "typescript": "7.0.2",
@@ -0,0 +1,332 @@
1
+ // Purpose: The three agent-lifecycle tools (get_subagent_result, steer_subagent, stop_subagent) as definitions, returned to the composition root to register.
2
+ /**
3
+ * brl-subagent — the agent tools (ADR 0027 S5, issue #483)
4
+ *
5
+ * The three `pi.registerTool({ … })` literals that let the conductor act on a
6
+ * BACKGROUND run — read its result, steer it, stop it — move here. The
7
+ * registrations do not (D7): `index.ts` iterates what this factory returns and
8
+ * calls `pi.registerTool` on each, so `index.ts` remains the one place where the
9
+ * tool surface is registered.
10
+ *
11
+ * **No context parameter.** Unlike `createCommands` and `createDelegateHandler`,
12
+ * these three tools read nothing from the runtime: the session manager and the
13
+ * transcript store are reached by dynamic `import(...)` inside each `execute`
14
+ * (the timing that keeps session-manager's lifecycle mutators lazy), and the
15
+ * status formatting comes from `notify-completion.ts` / `transcript-path.ts`.
16
+ * An unused `rt` parameter would be a binding with no consumer — the rule
17
+ * ADR 0027 F1 states for the runtime context, applied to the deps seam.
18
+ *
19
+ * Each definition goes through the module-local `defineTool` identity helper
20
+ * rather than being annotated `ToolDefinition`: the annotation's `TParams`
21
+ * defaults to `TSchema`, which widens `params` inside `execute` to `unknown` and
22
+ * takes the `agent_id`/`message` access with it. The helper does what pi's
23
+ * exported `defineTool` does — infer `TParams` from the inline `Type.Object` and
24
+ * hand the definition back — but it is LOCAL because pi's is a RUNTIME import
25
+ * from `@earendil-works/pi-coding-agent`, and this repo's suites stub that
26
+ * package to the two symbols their renderer path needs. A runtime import of a
27
+ * third symbol would make every one of those suites fail to collect. A
28
+ * type-level annotation needs no import at all; a value-level identity function
29
+ * needs one call site fewer than rewriting the schemas into named consts.
30
+ */
31
+
32
+ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
33
+ import { Type, type TSchema } from "typebox";
34
+ import { formatBudgetLine, normalizeCompletionStatus } from "./notify-completion";
35
+ import { sanitizeErrorMessage } from "./sanitize";
36
+ import { transcriptDisplayPath } from "./transcript-path";
37
+
38
+ /**
39
+ * Identity helper over `ToolDefinition` that PRESERVES the schema's inference:
40
+ * `TParams` comes from the `parameters` property, so `execute` keeps the params
41
+ * object its inline `Type.Object` describes. See the header for why this is
42
+ * local rather than pi's exported `defineTool`.
43
+ */
44
+ function defineTool<TParams extends TSchema, TDetails = unknown>(
45
+ tool: ToolDefinition<TParams, TDetails>,
46
+ ): ToolDefinition<TParams, TDetails> {
47
+ return tool;
48
+ }
49
+
50
+ /**
51
+ * `ToolDefinition<any, any, any>` is pi's own `AnyToolDefinition` alias (not
52
+ * exported from the package): the element type of a heterogeneous MANY-tool
53
+ * list. Naming the three schema/details pairs instead would make the array
54
+ * invariant per member — `renderCall`'s `Static<TParams>` is contravariant — so
55
+ * the three definitions could not share one return type at all.
56
+ */
57
+ /**
58
+ * Build the three agent-tool definitions. Stateless and cheap: the factory is a
59
+ * definition assembler, so it may be called per invocation without consequence
60
+ * (the cost of the old inline literals, and nothing more).
61
+ */
62
+ export function createAgentTools(): ToolDefinition<any, any, any>[] {
63
+ const getSubagentResultTool = defineTool({
64
+ name: "get_subagent_result",
65
+ label: "Get Subagent Result",
66
+ description: [
67
+ "Check the status of a background agent and retrieve its result.",
68
+ "The conductor is woken with a completion message when the agent finishes; use this for post-wake retrieval, stall checks, and detail access — not for polling.",
69
+ "Accepts a full agent id or a unique 8-character id prefix.",
70
+ "When the id belongs to a retried run, the answer names the latest attempt; a finished run that was superseded also reports its successor.",
71
+ "Returns the agent's status, result (if completed), and transcript path.",
72
+ ].join(" "),
73
+ parameters: Type.Object({
74
+ agent_id: Type.String({
75
+ description: "The agent ID returned by delegate_task when background=true",
76
+ }),
77
+ verbose: Type.Optional(
78
+ Type.Boolean({
79
+ description: "If true, include the full conversation log. Default: false.",
80
+ }),
81
+ ),
82
+ }),
83
+ execute: async (toolCallId, params) => {
84
+ const { getAgent, resolveAgentId, findRetryLineage, isTerminalAgentStatus, RETRY_SCAN_WINDOW_MS, RETRY_SCAN_WINDOW_DAYS } = await import('./session-manager');
85
+ const { getTranscript } = await import('./transcript');
86
+
87
+ // The notices render the first 8 hex characters of an id; resolve a
88
+ // unique prefix before both the record read and the lineage lookup.
89
+ // Ambiguity fails closed — a guess here could report the wrong run.
90
+ const resolution = resolveAgentId(params.agent_id);
91
+ if (resolution.kind === 'ambiguous') {
92
+ return {
93
+ content: [{
94
+ type: "text" as const,
95
+ text: `Agent id prefix "${params.agent_id}" is ambiguous — matches: ${resolution.matches.join(', ')}`,
96
+ }],
97
+ details: undefined,
98
+ isError: true,
99
+ };
100
+ }
101
+ // Anything that is not a full id or a matching 8-hex prefix keeps
102
+ // today's message — there is no id to resolve against the stores.
103
+ if (resolution.kind === 'unresolved') {
104
+ return {
105
+ content: [{ type: "text" as const, text: `Agent ${params.agent_id} not found` }],
106
+ details: undefined,
107
+ isError: true,
108
+ };
109
+ }
110
+ const agentId = resolution.id;
111
+
112
+ const agent = getAgent(agentId);
113
+
114
+ if (!agent) {
115
+ const lineage = findRetryLineage(agentId);
116
+ if (lineage.latest && lineage.latest.id !== agentId) {
117
+ const latest = lineage.latest;
118
+ return {
119
+ content: [{
120
+ type: "text" as const,
121
+ text: `Agent ${params.agent_id} not found — run ${params.agent_id} was retried as ${latest.id} (attempt ${latest.attempt}, ${latest.status}, started ${new Date(latest.startedAt).toISOString()}).`,
122
+ }],
123
+ details: undefined,
124
+ isError: true,
125
+ };
126
+ }
127
+
128
+ const registryRun = lineage.inflight.find((run) => run.id === agentId);
129
+ const registryStarted = registryRun
130
+ ? (Number.isFinite(Date.parse(registryRun.startedAt))
131
+ ? new Date(registryRun.startedAt).toISOString()
132
+ : registryRun.startedAt)
133
+ : undefined;
134
+ const registryText = registryRun
135
+ ? `no recent retry lineage recorded, but the registry still lists run ${registryRun.id} (attempt ${registryRun.attempt ?? 1}, started ${registryStarted}).`
136
+ : `no recent retry lineage recorded (scanned the last ${RETRY_SCAN_WINDOW_DAYS} days), and no registry record either.`;
137
+ return {
138
+ content: [{
139
+ type: "text" as const,
140
+ text: `Agent ${params.agent_id} not found — ${registryText}`,
141
+ }],
142
+ details: undefined,
143
+ isError: true,
144
+ };
145
+ }
146
+
147
+ let resultText = `Agent: ${agent.description}\n`;
148
+ resultText += `Status: ${agent.status}\n`;
149
+ resultText += `Started: ${new Date(agent.startedAt).toISOString()}\n`;
150
+
151
+ if (agent.completedAt) {
152
+ resultText += `Completed: ${new Date(agent.completedAt).toISOString()}\n`;
153
+ resultText += `Duration: ${agent.completedAt - agent.startedAt}ms\n`;
154
+ }
155
+
156
+ // Issue #423: the budget the run actually ran under — from the PERSISTED
157
+ // record, so it survives the closure that armed the timer. The result
158
+ // path has no run entry to consult, so the timeout evidence is the
159
+ // agent's own error stamp (one shared predicate owns both paths).
160
+ const budgetLine = formatBudgetLine(
161
+ agent,
162
+ normalizeCompletionStatus(agent.status),
163
+ undefined,
164
+ );
165
+ if (budgetLine) resultText += `${budgetLine}\n`;
166
+
167
+ if (agent.error) {
168
+ resultText += `Error: ${agent.error}\n`;
169
+ }
170
+
171
+ // A terminal source can be the WRONG run to act on: the retry that
172
+ // actually finished is a later attempt of the same dispatch. Name it
173
+ // so a terminal status is not read as the final word.
174
+ if (isTerminalAgentStatus(agent.status)) {
175
+ const lineage = findRetryLineage(agentId, agent);
176
+ if (lineage.latest && lineage.latest.id !== agentId) {
177
+ const latest = lineage.latest;
178
+ resultText += `Superseded by ${latest.id} (attempt ${latest.attempt}, ${latest.status}, started ${new Date(latest.startedAt).toISOString()})\n`;
179
+ } else if (agent.startedAt < Date.now() - RETRY_SCAN_WINDOW_MS) {
180
+ // The lineage scan is windowed: an older run cannot be shown a
181
+ // later attempt that fell outside it. Say so instead of implying
182
+ // there is none.
183
+ resultText += `Retry lineage not checked: this run started more than ${RETRY_SCAN_WINDOW_DAYS} days ago.\n`;
184
+ }
185
+ }
186
+
187
+ if (agent.result) {
188
+ resultText += `\nResult:\n`;
189
+ if (agent.result.messages && agent.result.messages.length > 0) {
190
+ resultText += agent.result.messages.join('\n');
191
+ }
192
+ // W4: surface the background agent's git work-branch diff so the
193
+ // captured changes are reviewable (the branch itself is discarded).
194
+ if (agent.result.gitBranch) {
195
+ resultText += `\nGit branch: ${agent.result.gitBranch}\n`;
196
+ }
197
+ if (agent.result.gitDiff) {
198
+ const diff = agent.result.gitDiff;
199
+ const truncated = diff.length > 8000 ? diff.slice(0, 8000) + "\n…[diff truncated]" : diff;
200
+ resultText += `\nGit diff (branch ${agent.result.gitBranch ?? 'work'}):\n${truncated}\n`;
201
+ }
202
+ }
203
+
204
+ if (agent.finalOutput) {
205
+ const full = agent.finalOutput;
206
+ const truncated = full.length > 8000 ? full.slice(0, 8000) + "\n…[truncated — full output in transcript]" : full;
207
+ resultText += `\n\nFinal output:\n${truncated}`;
208
+ }
209
+
210
+ // Include transcript if verbose
211
+ if (params.verbose) {
212
+ const transcript = getTranscript(agentId);
213
+ if (transcript.length > 0) {
214
+ resultText += `\n\nTranscript (${transcript.length} entries):\n`;
215
+ for (const entry of transcript.slice(-10)) { // Last 10 entries
216
+ resultText += `[${new Date(entry.timestamp).toISOString()}] ${entry.type}: ${entry.content.slice(0, 100)}\n`;
217
+ }
218
+ }
219
+ }
220
+
221
+ // Include transcript path
222
+ resultText += `\nTranscript: ${transcriptDisplayPath(agentId)}`;
223
+
224
+ return {
225
+ content: [{ type: "text" as const, text: resultText }],
226
+ details: undefined,
227
+ };
228
+ },
229
+ });
230
+
231
+ const steerSubagentTool = defineTool({
232
+ name: "steer_subagent",
233
+ label: "Steer Subagent",
234
+ description: [
235
+ "Send a steering message to a running background agent.",
236
+ "The message is delivered after the agent's current tool call finishes, before its next model call.",
237
+ "Use this to redirect an agent's work without restarting it.",
238
+ ].join(" "),
239
+ parameters: Type.Object({
240
+ agent_id: Type.String({
241
+ description: "The agent ID to steer",
242
+ }),
243
+ message: Type.String({
244
+ description: "The message to inject into the agent's conversation",
245
+ }),
246
+ }),
247
+ execute: async (toolCallId, params, _signal, _onUpdate, ctx) => {
248
+ const { steerAgent } = await import('./session-manager');
249
+
250
+ try {
251
+ const agent = await steerAgent(params.agent_id, params.message);
252
+
253
+ if (!agent) {
254
+ return {
255
+ content: [{ type: "text" as const, text: `Agent ${params.agent_id} not found` }],
256
+ details: undefined,
257
+ isError: true,
258
+ };
259
+ }
260
+
261
+ return {
262
+ content: [{
263
+ type: "text" as const,
264
+ text: `Steered agent ${params.agent_id}: "${params.message.slice(0, 50)}${params.message.length > 50 ? '...' : ''}"`,
265
+ }],
266
+ details: undefined,
267
+ };
268
+ } catch (err) {
269
+ // F7 (issue #65): sanitize BEFORE the message reaches the main
270
+ // agent's context. pi passes ctx as the 5th arg to tool execute,
271
+ // so ctx.cwd is in scope — sibling-project paths are properly
272
+ // masked (defensive process.cwd() fallback if ctx is undefined).
273
+ const message = sanitizeErrorMessage(err instanceof Error ? err.message : String(err), ctx?.cwd);
274
+ return {
275
+ content: [{ type: "text" as const, text: `Failed to steer agent: ${message}` }],
276
+ details: undefined,
277
+ isError: true,
278
+ };
279
+ }
280
+ },
281
+ });
282
+
283
+ const stopSubagentTool = defineTool({
284
+ name: "stop_subagent",
285
+ label: "Stop Subagent",
286
+ description: [
287
+ "Stop a running background agent by aborting its session.",
288
+ "The agent's current operation is aborted and the session is marked stopped.",
289
+ "Use this to halt a background agent that is no longer needed.",
290
+ ].join(" "),
291
+ parameters: Type.Object({
292
+ agent_id: Type.String({
293
+ description: "The agent ID to stop",
294
+ }),
295
+ }),
296
+ execute: async (toolCallId, params, _signal, _onUpdate, ctx) => {
297
+ const { stopAgent } = await import('./session-manager');
298
+
299
+ try {
300
+ const agent = await stopAgent(params.agent_id);
301
+
302
+ if (!agent) {
303
+ return {
304
+ content: [{ type: "text" as const, text: `Agent ${params.agent_id} not found` }],
305
+ details: undefined,
306
+ isError: true,
307
+ };
308
+ }
309
+
310
+ return {
311
+ content: [{
312
+ type: "text" as const,
313
+ text: `Stopped agent ${params.agent_id} (${agent.description}).`,
314
+ }],
315
+ details: undefined,
316
+ };
317
+ } catch (err) {
318
+ // F7 (issue #65): sanitize BEFORE the message reaches the main
319
+ // agent's context. pi passes ctx as the 5th arg to tool execute,
320
+ // so ctx.cwd is in scope — sibling-project paths are properly
321
+ // masked (defensive process.cwd() fallback if ctx is undefined).
322
+ const message = sanitizeErrorMessage(err instanceof Error ? err.message : String(err), ctx?.cwd);
323
+ return {
324
+ content: [{ type: "text" as const, text: `Failed to stop agent: ${message}` }],
325
+ details: undefined,
326
+ isError: true,
327
+ };
328
+ }
329
+ },
330
+ });
331
+ return [getSubagentResultTool, steerSubagentTool, stopSubagentTool];
332
+ }