brl-subagent 2.8.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.
- package/AGENT.md +1 -1
- 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 +313 -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 +1 -1
- 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 +2 -3
- package/src/reports.ts +1 -7
- package/src/run-registry.ts +2 -3
- 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/scratch-root.ts +909 -0
- package/src/scratch-spawn.ts +256 -0
- package/src/session-manager.ts +75 -7
- 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 +42 -32
- package/src/types.ts +29 -3
- package/src/unit-params.ts +113 -0
- package/src/unit-run.ts +35 -15
- package/src/validate.ts +2 -3
- package/src/worktree-report.ts +142 -0
package/src/notify-completion.ts
CHANGED
|
@@ -18,17 +18,17 @@
|
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
20
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
21
|
-
import type {
|
|
22
|
-
BackgroundAgent,
|
|
23
|
-
BackgroundAgentIdentity,
|
|
24
|
-
SubagentRun,
|
|
25
|
-
CompletionNotifyMode,
|
|
26
|
-
AgentStatus,
|
|
27
|
-
} from "./types";
|
|
28
21
|
import { truncateTail } from "./transcript-tail";
|
|
29
22
|
import { formatRunDuration } from "./history";
|
|
30
23
|
import { formatBudgetDuration } from "./tui-format";
|
|
31
|
-
import {
|
|
24
|
+
import {
|
|
25
|
+
classifyTerminalOutcome,
|
|
26
|
+
type BackgroundAgent,
|
|
27
|
+
type BackgroundAgentIdentity,
|
|
28
|
+
type SubagentRun,
|
|
29
|
+
type CompletionNotifyMode,
|
|
30
|
+
type AgentStatus,
|
|
31
|
+
} from "./types";
|
|
32
32
|
import { resolveTerminalRunEntry } from "./state";
|
|
33
33
|
|
|
34
34
|
/** Terminal statuses the completion message can carry. */
|
|
@@ -246,6 +246,33 @@ export function buildCompletionMessage(
|
|
|
246
246
|
return { customType: "subagent-completion", content, display: true, details };
|
|
247
247
|
}
|
|
248
248
|
|
|
249
|
+
/**
|
|
250
|
+
* Issue #474: insert the worktree-state block into a settled-failure wake, as
|
|
251
|
+
* its own part and BEFORE the closing directive.
|
|
252
|
+
*
|
|
253
|
+
* PURE — it takes the already-rendered block and never probes git: the builder's
|
|
254
|
+
* contract is "no side effects", and the probe is a subprocess. The caller
|
|
255
|
+
* renders the block (`describeWorktreeState`) and gates on the CLASSIFIED
|
|
256
|
+
* status.
|
|
257
|
+
*
|
|
258
|
+
* The directive is matched at the END (`endsWith`), never as the first
|
|
259
|
+
* occurrence: an agent's own tail can quote the directive text, and splitting
|
|
260
|
+
* there would drop everything after the quote. A shape that does not end with
|
|
261
|
+
* the directive keeps the block by appending it — a missing report is the one
|
|
262
|
+
* outcome this function must not produce.
|
|
263
|
+
*/
|
|
264
|
+
export function withWorktreeState(
|
|
265
|
+
message: CompletionMessagePayload,
|
|
266
|
+
worktreeState: string,
|
|
267
|
+
): CompletionMessagePayload {
|
|
268
|
+
if (!worktreeState) return message;
|
|
269
|
+
const suffix = `\n\n${COMPLETION_DIRECTIVE}`;
|
|
270
|
+
const content = message.content.endsWith(suffix)
|
|
271
|
+
? `${message.content.slice(0, -suffix.length)}\n\n${worktreeState}${suffix}`
|
|
272
|
+
: `${message.content}\n\n${worktreeState}`;
|
|
273
|
+
return { ...message, content };
|
|
274
|
+
}
|
|
275
|
+
|
|
249
276
|
/**
|
|
250
277
|
* D1 + D2 matrix — the only knob-dependent logic. Delivery is always-on
|
|
251
278
|
* (minimum `nextTurn`); the knob controls the WAKE (triggerTurn).
|
package/src/params.ts
CHANGED
|
@@ -12,24 +12,25 @@
|
|
|
12
12
|
* drive the REAL function (no more silent test drift).
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
+
import type { Logger } from "./logging";
|
|
16
|
+
import type { SessionState } from "./state";
|
|
15
17
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
18
|
+
import {
|
|
19
|
+
approvalBlocksBackground,
|
|
20
|
+
declaredThinkingLevel,
|
|
21
|
+
resolveThinkingLevel,
|
|
22
|
+
type ThinkingLevel,
|
|
23
|
+
type SubagentPreset,
|
|
24
|
+
type GitMode,
|
|
25
|
+
type ApprovalMode,
|
|
26
|
+
type SubagentToolOptions,
|
|
27
|
+
type ResolvedParams,
|
|
28
|
+
type SnapshotParams,
|
|
29
|
+
type DelegateTaskParams,
|
|
26
30
|
} from "./types";
|
|
27
|
-
import { approvalBlocksBackground, declaredThinkingLevel, resolveThinkingLevel } from "./types";
|
|
28
31
|
import { getAllPresets, getPreset } from "./presets";
|
|
29
32
|
import { classifyTask } from "./router";
|
|
30
33
|
import { normalizeTimeout } from "./validate";
|
|
31
|
-
import type { SessionState } from "./state";
|
|
32
|
-
import type { Logger } from "./logging";
|
|
33
34
|
|
|
34
35
|
// ---------------------------------------------------------------------------
|
|
35
36
|
// delegate_task known keys (issue #99)
|
package/src/preflight.ts
CHANGED
|
@@ -1,16 +1,34 @@
|
|
|
1
|
-
// Purpose: Pre-spawn environment checks: pi binary,
|
|
1
|
+
// Purpose: Pre-spawn environment checks: pi binary, scratch-root writability, cwd readability.
|
|
2
2
|
/**
|
|
3
3
|
* brl-subagent — Pre-flight Checks (R3)
|
|
4
4
|
*
|
|
5
5
|
* Validates the execution environment before spawning a subagent.
|
|
6
|
-
* Checks: pi binary availability,
|
|
7
|
-
* and project cwd
|
|
6
|
+
* Checks: pi binary availability, **shipped scratch-root** writability (issue
|
|
7
|
+
* #511, U4 — the last probe of a system-temp path), and project cwd
|
|
8
|
+
* readability.
|
|
9
|
+
*
|
|
10
|
+
* THE THIRD CHECK IS AN EARLY WARNING, NOT THE AUTHORITY. It resolves the same
|
|
11
|
+
* root the spawn uses and proves a file can be created where the root lives or
|
|
12
|
+
* would be created; `prepareRunScratch` then re-resolves, re-validates the chain
|
|
13
|
+
* and creates `<root>/runs/<id>` at 0700 on every spawn. This check exists so a
|
|
14
|
+
* human learns before the dispatch does — never as the only place a bad root is
|
|
15
|
+
* caught.
|
|
16
|
+
*
|
|
17
|
+
* LIMITS, stated rather than implied: the probe CREATES nothing durable — a
|
|
18
|
+
* missing root stays missing (the spawn creates it), so a probe that passes on
|
|
19
|
+
* a writable ancestor says "the root can be created here", not "the root is
|
|
20
|
+
* sound"; a process killed between the write and the unlink leaves one 0600
|
|
21
|
+
* `.brl-preflight-probe-<pid>-<n>` file in the root or its nearest existing
|
|
22
|
+
* ancestor, recognisable and inert (nothing reads it, and no validation looks
|
|
23
|
+
* at it); and no system-temp
|
|
24
|
+
* path is probed, used as a fallback, or advised in a message any more
|
|
25
|
+
* (`src/__tests__/no-temp-paths` is the guard).
|
|
8
26
|
*/
|
|
9
27
|
|
|
10
28
|
import * as fs from "node:fs";
|
|
11
|
-
import * as os from "node:os";
|
|
12
29
|
import * as path from "node:path";
|
|
13
30
|
import { getPiInvocation } from "./runner";
|
|
31
|
+
import { FILE_MODE, resolveRoot, type RootOptions } from "./scratch-root";
|
|
14
32
|
|
|
15
33
|
// ---------------------------------------------------------------------------
|
|
16
34
|
// Types
|
|
@@ -18,6 +36,16 @@ import { getPiInvocation } from "./runner";
|
|
|
18
36
|
|
|
19
37
|
export type PreflightResult = { ok: true } | { ok: false; error: string };
|
|
20
38
|
|
|
39
|
+
/** What a caller may inject. Production passes nothing. */
|
|
40
|
+
export interface PreflightOptions {
|
|
41
|
+
/**
|
|
42
|
+
* Root-resolution inputs (U1's seam), injected by tests only — `home` is the
|
|
43
|
+
* one that moves the layout. Production lets `resolveRoot` read the real
|
|
44
|
+
* environment.
|
|
45
|
+
*/
|
|
46
|
+
root?: RootOptions;
|
|
47
|
+
}
|
|
48
|
+
|
|
21
49
|
// ---------------------------------------------------------------------------
|
|
22
50
|
// Checks
|
|
23
51
|
// ---------------------------------------------------------------------------
|
|
@@ -117,24 +145,103 @@ function checkCwdReadable(cwd: string): PreflightResult {
|
|
|
117
145
|
return { ok: true };
|
|
118
146
|
}
|
|
119
147
|
|
|
148
|
+
/** The probe's one name, so a leftover from a killed process is recognisable as ours. */
|
|
149
|
+
const PROBE_PREFIX = ".brl-preflight-probe";
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* A per-process sequence, appended to the probe's name.
|
|
153
|
+
*
|
|
154
|
+
* The pid alone is not enough: `preflightCheck` runs BEFORE the concurrency slot
|
|
155
|
+
* is taken, so two overlapping dispatches in one process can probe at the same
|
|
156
|
+
* moment — and both would then write and unlink the SAME path, letting one
|
|
157
|
+
* call's unlink make the other report "not writable" for a directory that is
|
|
158
|
+
* perfectly writable. A distinct name per call removes the race without a lock.
|
|
159
|
+
*/
|
|
160
|
+
let probeSequence = 0;
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The probe's filename for THIS call: prefix, pid and a per-call sequence.
|
|
164
|
+
* Exported so a test can pin the part that matters — two calls must not share a
|
|
165
|
+
* name, because a pid-only name is exactly the race above.
|
|
166
|
+
*/
|
|
167
|
+
export function nextProbeName(): string {
|
|
168
|
+
probeSequence += 1;
|
|
169
|
+
return `${PROBE_PREFIX}-${process.pid}-${probeSequence}`;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* The nearest ancestor of `target` that exists — the directory a root that is
|
|
174
|
+
* not there yet would be CREATED in, and therefore the one that must be
|
|
175
|
+
* writable.
|
|
176
|
+
*
|
|
177
|
+
* `access` rather than `existsSync`: a directory we may not even look at is not
|
|
178
|
+
* a directory we can create in, and treating it as "missing" would walk past it
|
|
179
|
+
* and blame the wrong path. `dirname` is separator-agnostic and terminates at
|
|
180
|
+
* the filesystem root, which is returned as-is when nothing above exists.
|
|
181
|
+
*/
|
|
182
|
+
function nearestExistingAncestor(target: string): string {
|
|
183
|
+
let current = target;
|
|
184
|
+
for (;;) {
|
|
185
|
+
try {
|
|
186
|
+
fs.accessSync(current, fs.constants.F_OK);
|
|
187
|
+
return current;
|
|
188
|
+
} catch {
|
|
189
|
+
const parent = path.dirname(current);
|
|
190
|
+
if (parent === current) return current;
|
|
191
|
+
current = parent;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
120
196
|
/**
|
|
121
|
-
* Verify the
|
|
122
|
-
*
|
|
197
|
+
* Verify the shipped scratch root is writable, by creating and removing a
|
|
198
|
+
* 0600 probe file (issue #511, U4 — the replacement for the `os.tmpdir()`
|
|
199
|
+
* probe).
|
|
200
|
+
*
|
|
201
|
+
* WHERE it lands: inside the root when the root exists, otherwise in its
|
|
202
|
+
* nearest existing ancestor, because that is where the root would be created.
|
|
203
|
+
* A missing root is NOT a failure — the spawn creates it at 0700.
|
|
204
|
+
*
|
|
205
|
+
* WHERE the root comes from: `resolveRoot` (U1) with this module's injected
|
|
206
|
+
* inputs. PRODUCTION passes none, so the resolver reads the real environment;
|
|
207
|
+
* TESTS inject `{ home }`, the one input that moves the layout, which is why no
|
|
208
|
+
* test here reads or writes the developer's real cache root. There is
|
|
209
|
+
* deliberately NO module-level test redirect (the pattern `scratch-spawn.ts`
|
|
210
|
+
* uses): a global setup file that imported this module would load it BEFORE a
|
|
211
|
+
* suite registers `vi.mock("../runner")`, leaving this module bound to the real
|
|
212
|
+
* runner and silently defeating every suite whose preflight is supposed to see a
|
|
213
|
+
* mocked binary. The injected seam has no such ordering hazard.
|
|
214
|
+
*
|
|
215
|
+
* A refusal names the RESOLVED root, not the probe directory alone, so the line
|
|
216
|
+
* a human reads is the path the spawn would use. There is no "set TMPDIR"
|
|
217
|
+
* advice here: that advice belonged to the temp-dir probe this replaces, and the
|
|
218
|
+
* root is not configurable by an environment variable.
|
|
123
219
|
*/
|
|
124
|
-
function
|
|
125
|
-
const
|
|
126
|
-
|
|
220
|
+
function checkScratchRootWritable(options: PreflightOptions): PreflightResult {
|
|
221
|
+
const resolved = resolveRoot(options.root);
|
|
222
|
+
if (!resolved.ok) {
|
|
223
|
+
// A resolver refusal (no home, a root that is a symlink, a foreign owner, a
|
|
224
|
+
// writable ancestor, a mode that is not 0700) IS a preflight failure, and
|
|
225
|
+
// the resolver's code travels with it: one taxonomy, no re-wording.
|
|
226
|
+
return {
|
|
227
|
+
ok: false,
|
|
228
|
+
error: `Scratch root could not be resolved (${resolved.code}): ${resolved.message}`,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const probeDir = nearestExistingAncestor(resolved.root);
|
|
233
|
+
const probeFile = path.join(probeDir, nextProbeName());
|
|
127
234
|
|
|
128
235
|
try {
|
|
129
|
-
fs.writeFileSync(
|
|
130
|
-
fs.unlinkSync(
|
|
236
|
+
fs.writeFileSync(probeFile, "ok", { encoding: "utf-8", mode: FILE_MODE });
|
|
237
|
+
fs.unlinkSync(probeFile);
|
|
131
238
|
return { ok: true };
|
|
132
239
|
} catch (err) {
|
|
133
240
|
const message = err instanceof Error ? err.message : String(err);
|
|
134
241
|
return {
|
|
135
242
|
ok: false,
|
|
136
|
-
error: `
|
|
137
|
-
|
|
243
|
+
error: `Scratch root (${resolved.root}) is not writable: ${message}. ` +
|
|
244
|
+
`brl-subagent banks each run's progress under this root, so ${probeDir} must be writable by you.`,
|
|
138
245
|
};
|
|
139
246
|
}
|
|
140
247
|
}
|
|
@@ -152,15 +259,15 @@ function checkTempWritable(): PreflightResult {
|
|
|
152
259
|
* Call this BEFORE acquiring a concurrency slot to avoid wasting
|
|
153
260
|
* resources on a doomed spawn.
|
|
154
261
|
*/
|
|
155
|
-
export function preflightCheck(cwd: string): PreflightResult {
|
|
262
|
+
export function preflightCheck(cwd: string, options: PreflightOptions = {}): PreflightResult {
|
|
156
263
|
const piResult = checkPiBinary();
|
|
157
264
|
if (!piResult.ok) return piResult;
|
|
158
265
|
|
|
159
266
|
const cwdResult = checkCwdReadable(cwd);
|
|
160
267
|
if (!cwdResult.ok) return cwdResult;
|
|
161
268
|
|
|
162
|
-
const
|
|
163
|
-
if (!
|
|
269
|
+
const scratchResult = checkScratchRootWritable(options);
|
|
270
|
+
if (!scratchResult.ok) return scratchResult;
|
|
164
271
|
|
|
165
272
|
return { ok: true };
|
|
166
273
|
}
|
package/src/prelude.ts
CHANGED
|
@@ -45,11 +45,20 @@
|
|
|
45
45
|
* extra log fields.
|
|
46
46
|
*/
|
|
47
47
|
|
|
48
|
-
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
49
|
-
import type { ApprovalMode, GitMode, SubagentPreset, SubagentToolOptions, ThinkingLevel, ToolResult } from "./types";
|
|
50
|
-
import { approvalBlocksBackground, isThinkingLevel, THINKING_LEVELS } from "./types";
|
|
51
|
-
import type { SessionState } from "./state";
|
|
52
48
|
import type { Logger } from "./logging";
|
|
49
|
+
import type { SessionState } from "./state";
|
|
50
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
51
|
+
import {
|
|
52
|
+
approvalBlocksBackground,
|
|
53
|
+
isThinkingLevel,
|
|
54
|
+
THINKING_LEVELS,
|
|
55
|
+
type ApprovalMode,
|
|
56
|
+
type GitMode,
|
|
57
|
+
type SubagentPreset,
|
|
58
|
+
type SubagentToolOptions,
|
|
59
|
+
type ThinkingLevel,
|
|
60
|
+
type ToolResult,
|
|
61
|
+
} from "./types";
|
|
53
62
|
import { validateCwd, validateOutputFile } from "./sanitize";
|
|
54
63
|
import { validatePreTask, type ValidateConfig } from "./validate";
|
|
55
64
|
import { modelIsAvailable, parseModelString } from "./model-availability";
|
|
@@ -308,7 +317,7 @@ export function runPreTaskValidation(input: {
|
|
|
308
317
|
|
|
309
318
|
/**
|
|
310
319
|
* A merged per-unit source, structurally (mergeSubTaskParams lives in
|
|
311
|
-
*
|
|
320
|
+
* unit-params.ts and is passed in by the handler). These are the fields the
|
|
312
321
|
* pre-pass reads; the handler's own type is preserved through the generic
|
|
313
322
|
* `M` so it can build its mode-specific unit records from the result.
|
|
314
323
|
*/
|
package/src/presets.ts
CHANGED
|
@@ -7,13 +7,11 @@
|
|
|
7
7
|
* Custom presets are stored in session state.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
+
import type { Logger } from "./logging";
|
|
10
11
|
import * as fs from "node:fs";
|
|
11
12
|
import * as path from "node:path";
|
|
12
|
-
import type
|
|
13
|
-
import {
|
|
14
|
-
import type { Logger } from "./logging";
|
|
15
|
-
import { applyFrontmatterMappers, loadMarkdownRecords } from "./loader";
|
|
16
|
-
import type { FrontmatterFieldMapper, FrontmatterMapContext } from "./loader";
|
|
13
|
+
import { THINKING_LEVELS, type SubagentPreset, type ThinkingLevel } from "./types";
|
|
14
|
+
import { applyFrontmatterMappers, loadMarkdownRecords, type FrontmatterFieldMapper, type FrontmatterMapContext } from "./loader";
|
|
17
15
|
|
|
18
16
|
// `parseFrontmatter` moved to loader.ts when the four loader copies collapsed
|
|
19
17
|
// into one walk (issue #380). Re-exported so the existing import sites keep
|
package/src/proc.ts
CHANGED
|
@@ -18,12 +18,11 @@
|
|
|
18
18
|
* that platform guard without mocking `node:fs` module-wide.
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
|
+
import type { RecoveryDeps } from "./recovery-engine";
|
|
21
22
|
import * as fs from "node:fs";
|
|
22
23
|
import * as path from "node:path";
|
|
23
|
-
import type
|
|
24
|
-
import { SIGKILL_GRACE_MS, SIGKILL_POLL_MS } from "./types";
|
|
24
|
+
import { SIGKILL_GRACE_MS, SIGKILL_POLL_MS, type ProcessOwner } from "./types";
|
|
25
25
|
import { CHILD_MARKER_ENV_KEY } from "./sanitize";
|
|
26
|
-
import type { RecoveryDeps } from "./recovery-engine";
|
|
27
26
|
import { supportsProcessGroupKill } from "./kill-escalation";
|
|
28
27
|
|
|
29
28
|
const PROC_ROOT = "/proc";
|
package/src/recovery-engine.ts
CHANGED
|
@@ -23,10 +23,10 @@
|
|
|
23
23
|
* every pid, wait one grace window, SIGKILL any survivor.
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
|
+
import type { Logger } from "./logging";
|
|
26
27
|
import type { ProcessOwner, SubagentRun } from "./types";
|
|
27
28
|
import { resolveTerminalRunEntry } from "./state";
|
|
28
29
|
import { escalateKill, processTarget, type SignalGuard, type SignalPhase } from "./kill-escalation";
|
|
29
|
-
import type { Logger } from "./logging";
|
|
30
30
|
|
|
31
31
|
// ---------------------------------------------------------------------------
|
|
32
32
|
// Dependency injection surface
|
package/src/recovery-surface.ts
CHANGED
|
@@ -28,8 +28,7 @@
|
|
|
28
28
|
*/
|
|
29
29
|
|
|
30
30
|
import { listInflightRuns, type InflightRun, type InflightRunKind } from "./run-registry";
|
|
31
|
-
import type
|
|
32
|
-
import { isInterruptedRun, runRecoveryPosture, type RecoveryMode } from "./types";
|
|
31
|
+
import { isInterruptedRun, runRecoveryPosture, type RecoveryMode, type SubagentRun } from "./types";
|
|
33
32
|
import { resolveTerminalRunEntry } from "./state";
|
|
34
33
|
import { sortNewestFirst } from "./history";
|
|
35
34
|
import { claimTerminalNotice, type DeliveryResolution } from "./notify-completion";
|
package/src/recovery.ts
CHANGED
|
@@ -31,13 +31,12 @@
|
|
|
31
31
|
* ownership cannot be verified.
|
|
32
32
|
*/
|
|
33
33
|
|
|
34
|
+
import type { Logger } from "./logging";
|
|
34
35
|
import { listInflightRuns, type InflightRun } from "./run-registry";
|
|
35
36
|
import { assertSafeAgentId } from "./sanitize";
|
|
36
37
|
import { isProcAvailable, defaultRecoveryDeps } from "./proc";
|
|
37
38
|
import { decideRecovery, classifyOwner, reapPids, type RecoveryDeps, type RecoveryRecord } from "./recovery-engine";
|
|
38
|
-
import type
|
|
39
|
-
import type { SubagentRun } from "./types";
|
|
40
|
-
import { PROMPT_NEVER_ISSUED_MESSAGE } from "./types";
|
|
39
|
+
import { PROMPT_NEVER_ISSUED_MESSAGE, type SubagentRun } from "./types";
|
|
41
40
|
|
|
42
41
|
// Re-export the pure engine and the production wiring so existing importers
|
|
43
42
|
// (`index.ts`, the recovery/registry suites) keep their single entry point.
|
package/src/reports.ts
CHANGED
|
@@ -6,13 +6,7 @@
|
|
|
6
6
|
* and what secrets may have been accessed.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import type {
|
|
10
|
-
SubagentRun,
|
|
11
|
-
FileAccessReport,
|
|
12
|
-
SecretsExposureEntry,
|
|
13
|
-
SecretsExposureReport,
|
|
14
|
-
ComplianceSummary,
|
|
15
|
-
} from "./types";
|
|
9
|
+
import type { SubagentRun, FileAccessReport, SecretsExposureEntry, SecretsExposureReport, ComplianceSummary } from "./types";
|
|
16
10
|
import { computeSLAMetrics } from "./metrics";
|
|
17
11
|
|
|
18
12
|
// ---------------------------------------------------------------------------
|
package/src/run-registry.ts
CHANGED
|
@@ -29,11 +29,10 @@
|
|
|
29
29
|
* agent store's F6 discipline.
|
|
30
30
|
*/
|
|
31
31
|
|
|
32
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
32
33
|
import * as fs from "node:fs";
|
|
33
34
|
import * as path from "node:path";
|
|
34
|
-
import type
|
|
35
|
-
import type { ProcessOwner, RecoveryMode, SubagentRun } from "./types";
|
|
36
|
-
import { CUSTOM_ENTRY_TYPES, RECOVERY_MODES } from "./types";
|
|
35
|
+
import { CUSTOM_ENTRY_TYPES, RECOVERY_MODES, type ProcessOwner, type RecoveryMode, type SubagentRun } from "./types";
|
|
37
36
|
import { assertSafeAgentId } from "./sanitize";
|
|
38
37
|
import { ensureOwnerOnlyDir } from "./store-permissions";
|
|
39
38
|
|
package/src/runner.ts
CHANGED
|
@@ -10,19 +10,13 @@
|
|
|
10
10
|
* - Temp file management
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
import {
|
|
14
|
-
import type {
|
|
13
|
+
import type { TranscriptMessage, TranscriptContentBlock, TranscriptToolCallBlock } from "./transcript-tail";
|
|
14
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
15
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
15
16
|
import * as fs from "node:fs";
|
|
16
17
|
import * as path from "node:path";
|
|
17
|
-
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
18
18
|
import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
19
19
|
import { wrapTask } from "./prompt";
|
|
20
|
-
import type {
|
|
21
|
-
SubagentResult,
|
|
22
|
-
SubagentToolOptions,
|
|
23
|
-
UsageStats,
|
|
24
|
-
ThinkingLevel,
|
|
25
|
-
} from "./types";
|
|
26
20
|
import {
|
|
27
21
|
EMPTY_USAGE,
|
|
28
22
|
SIGKILL_GRACE_MS,
|
|
@@ -33,6 +27,10 @@ import {
|
|
|
33
27
|
classifyError,
|
|
34
28
|
SUBAGENT_ABORTED_MESSAGE,
|
|
35
29
|
SUBAGENT_SIGNAL_KILLED_MESSAGE,
|
|
30
|
+
type SubagentResult,
|
|
31
|
+
type SubagentToolOptions,
|
|
32
|
+
type UsageStats,
|
|
33
|
+
type ThinkingLevel,
|
|
36
34
|
} from "./types";
|
|
37
35
|
import {
|
|
38
36
|
escalateKill,
|
|
@@ -45,16 +43,10 @@ import {
|
|
|
45
43
|
} from "./kill-escalation";
|
|
46
44
|
import { findByMarker, pidAlive, pidHasMarker, pidGone, groupHasMembers, killProcessGroup } from "./proc";
|
|
47
45
|
import { getSafeEnv, DEPTH_ENV_KEY, CHILD_MARKER_ENV_KEY, sanitizeErrorMessage } from "./sanitize";
|
|
48
|
-
import { createLogger } from "./logging";
|
|
49
|
-
import type { Logger } from "./logging";
|
|
46
|
+
import { createLogger, type Logger } from "./logging";
|
|
50
47
|
import { buildEngineeringBarSection } from "./engineering-bar";
|
|
51
|
-
import
|
|
52
|
-
import { extractMessages, formatPendingMessages } from "./messaging";
|
|
53
|
-
import type {
|
|
54
|
-
TranscriptMessage,
|
|
55
|
-
TranscriptContentBlock,
|
|
56
|
-
TranscriptToolCallBlock,
|
|
57
|
-
} from "./transcript-tail";
|
|
48
|
+
import { SCRATCH_ENV_KEY, prepareRunScratch } from "./scratch-spawn";
|
|
49
|
+
import { extractMessages, formatPendingMessages, type Intercom } from "./messaging";
|
|
58
50
|
|
|
59
51
|
/**
|
|
60
52
|
* The logger for diagnostics a CALLER did not instrument. `runSubagent`'s `log`
|
|
@@ -1084,7 +1076,39 @@ export async function runSubagent(
|
|
|
1084
1076
|
intercom?: Intercom,
|
|
1085
1077
|
subagentId?: string,
|
|
1086
1078
|
childMarker?: string,
|
|
1079
|
+
/**
|
|
1080
|
+
* Issue #511 (U2): this run's id — the record id the caller already persisted
|
|
1081
|
+
* (`run.id`), and the name of its scratch directory (`<root>/runs/<id>`).
|
|
1082
|
+
*
|
|
1083
|
+
* Supplied by every DISPATCH call site (single, chain, parallel, graph — and
|
|
1084
|
+
* the timeout retry re-enters this function with the same id). It is optional
|
|
1085
|
+
* only so the non-dispatch callers and the unit tests need not own a scratch
|
|
1086
|
+
* root: absent means "no scratch directory for this spawn", which is a hole
|
|
1087
|
+
* `scratch-spawn.test.ts` closes by asserting each dispatch site passes one.
|
|
1088
|
+
*/
|
|
1089
|
+
runId?: string,
|
|
1087
1090
|
): Promise<SubagentResult> {
|
|
1091
|
+
// Issue #511 (U2): resolve the scratch root, create this run's directory and
|
|
1092
|
+
// admit `BRL_SCRATCH` into the child's environment — HERE, at the one
|
|
1093
|
+
// foreground spawn seam every caller shares, BEFORE any side effect of the
|
|
1094
|
+
// spawn (no temp system-prompt file, no process). A refusal is named and
|
|
1095
|
+
// pre-spawn: the caller's ordinary failure path reports it and no child
|
|
1096
|
+
// starts.
|
|
1097
|
+
const scratch = runId === undefined ? undefined : prepareRunScratch(runId, { log });
|
|
1098
|
+
if (scratch !== undefined && !scratch.ok) {
|
|
1099
|
+
return {
|
|
1100
|
+
messages: [],
|
|
1101
|
+
usage: { ...EMPTY_USAGE },
|
|
1102
|
+
exitCode: 1,
|
|
1103
|
+
stderr: scratch.message,
|
|
1104
|
+
errorMessage: `scratch root unavailable (${scratch.code}): ${scratch.message}`,
|
|
1105
|
+
// An environment refusal is not a provider or tool failure; "crash" is
|
|
1106
|
+
// the closed taxonomy's bucket for "the child never got to run" (the
|
|
1107
|
+
// named code in the message is the actionable half).
|
|
1108
|
+
errorCategory: "crash",
|
|
1109
|
+
};
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1088
1112
|
// E10: Inject pending intercom messages into the task prompt
|
|
1089
1113
|
if (intercom && subagentId && intercom.hasMessages(subagentId)) {
|
|
1090
1114
|
const pending = intercom.receiveAndClear(subagentId);
|
|
@@ -1148,6 +1172,11 @@ ${msgBlock}`;
|
|
|
1148
1172
|
// Option B U1: stamp the per-run marker so boot recovery can discover
|
|
1149
1173
|
// this child by scanning /proc/*/environ after a conductor crash.
|
|
1150
1174
|
if (childMarker) envOverrides[CHILD_MARKER_ENV_KEY] = childMarker;
|
|
1175
|
+
// Issue #511 (U2): the run's scratch directory, as an OVERRIDE (applied
|
|
1176
|
+
// last by `getSafeEnv`) and never as an allowlisted key: a `BRL_SCRATCH`
|
|
1177
|
+
// inherited from the parent process must be replaced, and a grandchild
|
|
1178
|
+
// must resolve its own run rather than inherit this one.
|
|
1179
|
+
if (scratch) envOverrides[SCRATCH_ENV_KEY] = scratch.runDir;
|
|
1151
1180
|
const hasEnvOverrides = Object.keys(envOverrides).length > 0;
|
|
1152
1181
|
const proc = spawn(invocation.command, invocation.args, {
|
|
1153
1182
|
cwd,
|
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Purpose: The per-invocation runtime context (pi, log, state) the composition root builds once and hands to the mode runners.
|
|
2
|
+
/**
|
|
3
|
+
* brl-subagent — the runtime context (cycle S2, ADR 0027 D1/D3)
|
|
4
|
+
*
|
|
5
|
+
* ADR 0027 D1 splits the composition root from the code it composes. The mode
|
|
6
|
+
* runners (S2) are the first consumers that need the three long-lived bindings
|
|
7
|
+
* `src/index.ts`'s `default` export used to own as closures: `pi` (the extension
|
|
8
|
+
* API), `log` (the session logger) and `state` (the session-bound store).
|
|
9
|
+
*
|
|
10
|
+
* `RuntimeContext` names those three, and `createRuntime` builds them with the
|
|
11
|
+
* exact order and arguments `index.ts` used inline — `createLogger` first
|
|
12
|
+
* because `createSessionState` takes the logger. D1 is why this is a value, not
|
|
13
|
+
* a module-level singleton: one context per `initExtension` invocation, so two
|
|
14
|
+
* loaded sessions in one process share no state.
|
|
15
|
+
*
|
|
16
|
+
* Deliberately NOT part of the context (D3): `sessionCtx`,
|
|
17
|
+
* `recoveryNoticeDelivered` and the other `default`-export closures. The runners
|
|
18
|
+
* never read them (recon at 46b427e: zero references across the moved range);
|
|
19
|
+
* adding one here without a consumer would be a binding the split does not
|
|
20
|
+
* need. ADR 0027 F1: if a runner ever needs a fourth field, the split is wrong —
|
|
21
|
+
* report it rather than widening this interface.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
25
|
+
import { createLogger, type Logger } from "./logging";
|
|
26
|
+
import { createSessionState, type SessionState } from "./state";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The three bindings the mode runners read, captured once per extension
|
|
30
|
+
* invocation. `readonly` because the split's contract is "handed in, never
|
|
31
|
+
* rebound": `createRuntime` produces it, `createModeRunners` destructures it,
|
|
32
|
+
* and nothing downstream reassigns a field (a rebind would be a second owner).
|
|
33
|
+
*/
|
|
34
|
+
export interface RuntimeContext {
|
|
35
|
+
readonly pi: ExtensionAPI;
|
|
36
|
+
readonly log: Logger;
|
|
37
|
+
readonly state: SessionState;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Build the runtime context for one extension invocation — the same two calls
|
|
42
|
+
* `index.ts` made inline (log → state, in that order). The only reason this is a
|
|
43
|
+
* function rather than three lines at the call site: the S2 boundary test drives
|
|
44
|
+
* two contexts and asserts they are independent (ADR 0027 D1).
|
|
45
|
+
*/
|
|
46
|
+
export function createRuntime(pi: ExtensionAPI): RuntimeContext {
|
|
47
|
+
const log = createLogger("brl-subagent");
|
|
48
|
+
const state = createSessionState(log);
|
|
49
|
+
return { pi, log, state };
|
|
50
|
+
}
|
package/src/sanitize.ts
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
import * as path from "node:path";
|
|
10
10
|
import * as fs from "node:fs";
|
|
11
11
|
import { EMPTY_USAGE, DEFAULT_OUTPUT_CAP_BYTES } from "./types";
|
|
12
|
+
import { appendWorktreeState } from "./worktree-report";
|
|
12
13
|
|
|
13
14
|
// ---------------------------------------------------------------------------
|
|
14
15
|
// F1: Input sanitization
|
|
@@ -152,6 +153,14 @@ export function assertSafeAgentId(id: string): void {
|
|
|
152
153
|
const SAFE_ENV_KEYS = new Set([
|
|
153
154
|
"PATH",
|
|
154
155
|
"HOME",
|
|
156
|
+
// Issue #511 (U2): the Windows halves of the same question. The shipped
|
|
157
|
+
// scratch root is `%LOCALAPPDATA%\brl-subagent` there, and `USERPROFILE` is
|
|
158
|
+
// what a nested child needs to find its own home at all — `HOME` alone leaves
|
|
159
|
+
// a Windows grandchild with no root to resolve. Symmetric with `HOME`, and
|
|
160
|
+
// deliberately NOT a place for `BRL_SCRATCH`: that value is per-run, so it is
|
|
161
|
+
// overridden at the spawn seam and stripped from anything inherited.
|
|
162
|
+
"USERPROFILE",
|
|
163
|
+
"LOCALAPPDATA",
|
|
155
164
|
"USER",
|
|
156
165
|
"LANG",
|
|
157
166
|
"LC_ALL",
|
|
@@ -316,7 +325,7 @@ function neutralizePathPrefix(text: string, prefix: string, replacement: string)
|
|
|
316
325
|
* 4. Caps length at 2000 chars with an ellipsis marker.
|
|
317
326
|
*
|
|
318
327
|
* Remaining-absolute-path policy: paths OUTSIDE the project root and its
|
|
319
|
-
* parent are left as-is (e.g. `/etc/passwd`, `/usr/bin/node`, `/
|
|
328
|
+
* parent are left as-is (e.g. `/etc/passwd`, `/usr/bin/node`, `/var/log/x.log`).
|
|
320
329
|
* Issue #30 is specifically about CWD/home disclosure; system paths carry no
|
|
321
330
|
* personal structure and keeping them preserves debugging value. Messages
|
|
322
331
|
* that are short and clean (no ANSI, no cwd/parent prefixes) pass through
|
|
@@ -357,6 +366,13 @@ export function sanitizeErrorMessage(msg: string, cwd?: string): string {
|
|
|
357
366
|
* serializes `content` into the LLM context, while the raw text persists to
|
|
358
367
|
* the session file for post-mortems (issue #68 framing: extraction is DRY,
|
|
359
368
|
* not a stderr-content change).
|
|
369
|
+
*
|
|
370
|
+
* Issue #474: this is the ONE crash seam (single, chain, graph and the per-unit
|
|
371
|
+
* finalizer all build their envelope here), so the worktree-state block is
|
|
372
|
+
* appended here rather than at seven call sites. `err` may carry the crashing
|
|
373
|
+
* UNIT's own block (`finalizeUnitRunCrash` attaches it) and that wins over
|
|
374
|
+
* `cwd`, which a mode-level caller only knows as the dispatch cwd. The block is
|
|
375
|
+
* appended, never spliced: the cause reads first, the residue after.
|
|
360
376
|
*/
|
|
361
377
|
export function buildCrashResult(mode: string, err: unknown, cwd: string): {
|
|
362
378
|
content: Array<{ type: "text"; text: string }>;
|
|
@@ -374,7 +390,9 @@ export function buildCrashResult(mode: string, err: unknown, cwd: string): {
|
|
|
374
390
|
cwd,
|
|
375
391
|
);
|
|
376
392
|
return {
|
|
377
|
-
content: [
|
|
393
|
+
content: [
|
|
394
|
+
{ type: "text", text: appendWorktreeState(`${mode} crashed: ${errorMessage}`, cwd, err) },
|
|
395
|
+
],
|
|
378
396
|
details: {
|
|
379
397
|
messages: [],
|
|
380
398
|
usage: { ...EMPTY_USAGE },
|
package/src/scheduler.ts
CHANGED
|
@@ -6,8 +6,7 @@
|
|
|
6
6
|
* and graph validation for P10 dependency graph mode.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import type
|
|
10
|
-
import { MAX_GRAPH_TASKS } from "./types";
|
|
9
|
+
import { MAX_GRAPH_TASKS, type GraphTask } from "./types";
|
|
11
10
|
|
|
12
11
|
// ---------------------------------------------------------------------------
|
|
13
12
|
// Cycle detection — three-color DFS
|