brl-subagent 2.8.0 → 2.9.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.
- package/AGENT.md +17 -2
- package/README.md +3 -3
- package/package.json +6 -5
- package/src/agent-tools.ts +332 -0
- package/src/background-pipeline.ts +1025 -0
- package/src/boot-recovery.ts +360 -0
- package/src/commands.ts +137 -0
- package/src/concurrency.ts +3 -5
- package/src/delegate-handler.ts +2261 -0
- package/src/engineering-bar.ts +1 -1
- package/src/git.ts +220 -8
- package/src/headstate.ts +3 -3
- package/src/history.ts +21 -3
- package/src/index.ts +109 -4473
- package/src/loader.ts +1 -1
- package/src/logging.ts +67 -4
- package/src/mode-prologue.ts +4 -10
- package/src/mode-runners.ts +1575 -0
- package/src/notify-completion.ts +35 -8
- package/src/params.ts +14 -13
- package/src/preflight.ts +123 -16
- package/src/prelude.ts +14 -5
- package/src/presets.ts +3 -5
- package/src/proc.ts +2 -3
- package/src/recovery-engine.ts +1 -1
- package/src/recovery-surface.ts +1 -2
- package/src/recovery.ts +238 -10
- package/src/reports.ts +1 -7
- package/src/run-registry.ts +133 -10
- package/src/runner.ts +47 -18
- package/src/runtime.ts +50 -0
- package/src/sanitize.ts +20 -2
- package/src/scheduler.ts +1 -2
- package/src/schema.ts +4 -2
- package/src/scratch-root.ts +909 -0
- package/src/scratch-spawn.ts +256 -0
- package/src/session-manager.ts +587 -81
- package/src/state.ts +12 -14
- package/src/templates.ts +3 -5
- package/src/terminal-notifier.ts +405 -0
- package/src/transcript.ts +1 -1
- package/src/tui-format.ts +3 -1
- package/src/tui.ts +46 -36
- package/src/types.ts +29 -3
- package/src/unit-params.ts +113 -0
- package/src/unit-run.ts +35 -15
- package/src/validate.ts +28 -9
- 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
|
|
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,7 +78,22 @@ 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 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.
|
|
81
|
+
- `timeout` (ms) is a **deadline, not a ceiling** — an explicit positive 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. The exceptions to "honored as given": a raw value `≥ 2³¹−1` ms **or a nonpositive value** normalizes to no timeout (a background run then gets the 30m default, a foreground run has none), and the opt-in `processChecks` high/xhigh **foreground** switch may drop an explicit timeout.
|
|
82
|
+
|
|
83
|
+
**Reference priors (2026-11-18 snapshot).** The table uses minutes; the `timeout` parameter itself is milliseconds. Reference workload: this repo, 2026-11-04T14:37Z → 2026-11-18T13:45Z; 217 settled background runs; the model cohorts are descriptive (each includes whatever tasks that model ran); the completed-only stats are the cap basis. Your mileage will vary: use your own run history when you have it; the 2h fallback is for an unknown shape, not a guarantee; a slow/local model needs more — pass a larger explicit timeout (a valid positive value is honored unless the opt-in high/xhigh foreground switch drops it; the only removals are that switch and the normalization of raw ≥2³¹−1/nonpositive values: a background run then gets the 30m default, a foreground run has none). The reference cap is not a runtime ceiling.
|
|
84
|
+
|
|
85
|
+
| model cohort (descriptive) | n (done/failed) | completed p50 | p90 | p99 | max | reference cap |
|
|
86
|
+
|---|---|---|---|---|---|---|
|
|
87
|
+
| deepseek-flash (implementation + probes + 24 failures: 23 transport + 1 abort) | 106 (82/24) | 9.1m | 19.8m | 26.9m | 28.4m | 60m |
|
|
88
|
+
| muse-spark / muse-ember (review) | 70 (60/10) | 4.8m | 8.2m | 16.0m | 16.3m | 20–30m |
|
|
89
|
+
| gpt-6.1-terra (critique) | 39 (37/2) | 1.6m | 6.1m | 10.0m | 10.6m | 30m |
|
|
90
|
+
| qwen3.8-max (critique; n=2) | 2 (2/0) | 29.7m | — | — | 35.1m | 60m (caveat) |
|
|
91
|
+
| all background | 217 (181/36) | 5.2m | 15.7m | 26.9m | 35.1m | 2h fallback |
|
|
92
|
+
|
|
93
|
+
- The cap is a **reference ceiling above the observed tail** for that model cohort's completed work, not a runtime ceiling or a target. A run that hits it is aborted (background) or killed (foreground); pass a larger explicit timeout if you know the task/model needs it (a valid positive value is honored unless the opt-in high/xhigh foreground switch drops it; raw ≥2³¹−1/nonpositive values normalize to no timeout, background then 30m, foreground none).
|
|
94
|
+
- The 30-minute **background** default applies when no valid timeout remains after normalization; a **foreground** run has no default. It is a default, not an enforced floor.
|
|
95
|
+
- Quick probes are not a separate validated cohort; the 4-run sample is descriptive only. Use the 30-minute **background** default for a **background** probe unless your own history supports a shorter cap; a **foreground/inline** probe (`background: false`) has no default — pass an explicit `timeout` if it needs a cap. The opt-in high/xhigh foreground switch may drop an explicit timeout.
|
|
96
|
+
- The qwen row is n=2 — a caveat, not a rule; the 60m cap covers it, and the 2h fallback is for an unknown shape.
|
|
82
97
|
- `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
98
|
|
|
84
99
|
## Mechanics pointer
|
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.
|
|
5
|
+
**Version:** 2.9.1 · **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
|
|
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 3100+ test suite pinning every contract against the real pi SDK.
|
|
18
18
|
|
|
19
19
|
---
|
|
20
20
|
|
|
@@ -132,7 +132,7 @@ A **background** run that settles `failed` with `errorCategory: 'exit_error'` an
|
|
|
132
132
|
|
|
133
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**.
|
|
134
134
|
|
|
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
|
|
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.
|
|
136
136
|
|
|
137
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.
|
|
138
138
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "brl-subagent",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.9.1",
|
|
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.
|
|
44
|
-
"@earendil-works/pi-ai": "^1.
|
|
45
|
-
"@earendil-works/pi-coding-agent": "^1.
|
|
46
|
-
"@earendil-works/pi-tui": "^1.
|
|
44
|
+
"@earendil-works/pi-agent-core": "^1.6.0",
|
|
45
|
+
"@earendil-works/pi-ai": "^1.6.0",
|
|
46
|
+
"@earendil-works/pi-coding-agent": "^1.6.0",
|
|
47
|
+
"@earendil-works/pi-tui": "^1.6.0",
|
|
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
|
+
}
|