brl-subagent 2.6.0 → 2.7.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 +2 -1
- package/README.md +16 -3
- package/package.json +4 -1
- package/src/dispatch-line.ts +144 -0
- package/src/history.ts +13 -1
- package/src/index.ts +542 -709
- package/src/loader.ts +178 -0
- package/src/mode-prologue.ts +169 -0
- package/src/model-availability.ts +13 -1
- package/src/params.ts +179 -62
- package/src/prelude.ts +279 -3
- package/src/presets.ts +56 -148
- package/src/project-flags.ts +58 -0
- package/src/run-registry.ts +4 -1
- package/src/schema.ts +67 -51
- package/src/session-manager.ts +790 -91
- package/src/store-permissions.ts +98 -0
- package/src/templates.ts +65 -121
- package/src/transcript.ts +5 -2
- package/src/transport-retry.ts +90 -0
- package/src/tui.ts +210 -351
- package/src/types.ts +42 -23
- package/src/validate.ts +41 -0
package/src/prelude.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Purpose: Shared guard/validation prelude
|
|
1
|
+
// Purpose: Shared guard/validation prelude for delegation modes: the individual gates (cost, approval, targets, H1), the per-unit pre-pass, and the batch modes' model tail.
|
|
2
2
|
/**
|
|
3
3
|
* Shared guard/validation prelude for delegation modes (issue #201).
|
|
4
4
|
*
|
|
@@ -26,6 +26,19 @@
|
|
|
26
26
|
* const pre = runPreTaskValidation({ … });
|
|
27
27
|
* if (pre.error) return pre.error;
|
|
28
28
|
*
|
|
29
|
+
* The per-unit pre-pass (merge → targets → H1 → warnings, repeated per unit)
|
|
30
|
+
* is validateUnitPrePass. Handlers CALL it at their own position; the gate
|
|
31
|
+
* order around it stays visible per mode.
|
|
32
|
+
*
|
|
33
|
+
* The batch modes' tail — model resolution, the empty-model rejection and the
|
|
34
|
+
* circuit check (IN11) — is resolveModeModel, built on
|
|
35
|
+
* resolveSubagentModelPrecedence, the one precedence chain the single and
|
|
36
|
+
* background paths resolve through too.
|
|
37
|
+
*
|
|
38
|
+
* The three foreground batch handlers compose the cost, target, preflight and
|
|
39
|
+
* H1 gates through `mode-prologue.ts` (`runModePrologue`), so their sequence
|
|
40
|
+
* is defined in one place; this module keeps the individual gates.
|
|
41
|
+
*
|
|
29
42
|
* Messages are byte-identical to the pre-extraction copies (the suites pin
|
|
30
43
|
* them); the parameters absorb only the real differences between sites — the
|
|
31
44
|
* cost-gate log label and unit count, and the H1 log label / unit prefix /
|
|
@@ -33,14 +46,15 @@
|
|
|
33
46
|
*/
|
|
34
47
|
|
|
35
48
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
36
|
-
import type { ApprovalMode, ToolResult } from "./types";
|
|
49
|
+
import type { ApprovalMode, GitMode, SubagentPreset, SubagentToolOptions, ThinkingLevel, ToolResult } from "./types";
|
|
37
50
|
import type { SessionState } from "./state";
|
|
38
51
|
import type { Logger } from "./logging";
|
|
39
52
|
import { validateCwd, validateOutputFile } from "./sanitize";
|
|
40
53
|
import { validatePreTask, type ValidateConfig } from "./validate";
|
|
54
|
+
import { modelIsAvailable, parseModelString } from "./model-availability";
|
|
41
55
|
|
|
42
56
|
/** The standard rejection result shape shared by these gates. */
|
|
43
|
-
function rejection(text: string): ToolResult<undefined> {
|
|
57
|
+
export function rejection(text: string): ToolResult<undefined> {
|
|
44
58
|
return {
|
|
45
59
|
content: [{ type: "text" as const, text }],
|
|
46
60
|
details: undefined,
|
|
@@ -48,6 +62,33 @@ function rejection(text: string): ToolResult<undefined> {
|
|
|
48
62
|
};
|
|
49
63
|
}
|
|
50
64
|
|
|
65
|
+
// ── Shared rejection messages (one wording, every dispatch path) ────────
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The recursion-depth rejection (IN3). The gate itself lives per family (the
|
|
69
|
+
* batch prologue and the single foreground path), but the wording must not
|
|
70
|
+
* drift between them — the #375 prose guard treats a second copy as a build
|
|
71
|
+
* failure.
|
|
72
|
+
*/
|
|
73
|
+
export function depthLimitRejection(currentDepth: number, maxDepth: number): ToolResult<undefined> {
|
|
74
|
+
return rejection(
|
|
75
|
+
`Cannot delegate further: subagent recursion depth limit reached ` +
|
|
76
|
+
`(depth ${currentDepth}/${maxDepth}). ` +
|
|
77
|
+
`Subagents can delegate up to ${maxDepth} levels deep (configurable via /brl-subagent depth). Complete the remaining work directly.`,
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The empty-`provider/id` rejection (IN11): a model resolved to nothing usable.
|
|
83
|
+
* Shared by the batch tail (`resolveModeModel`) and the single foreground path.
|
|
84
|
+
*/
|
|
85
|
+
export function modelNotConfiguredRejection(): ToolResult<undefined> {
|
|
86
|
+
return rejection(
|
|
87
|
+
"Subagent model is not configured. " +
|
|
88
|
+
"Use /brl-subagent to set a model, or ensure your current session has a valid model.",
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
51
92
|
// ── Gate 1: session cost ────────────────────────────────────────────────
|
|
52
93
|
|
|
53
94
|
/**
|
|
@@ -205,3 +246,238 @@ export function runPreTaskValidation(input: {
|
|
|
205
246
|
}
|
|
206
247
|
return { warnings: validation.warnings };
|
|
207
248
|
}
|
|
249
|
+
|
|
250
|
+
// ── Gate 4: per-unit pre-pass (merge → targets → H1) ────────────────────
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* A merged per-unit source, structurally (mergeSubTaskParams lives in
|
|
254
|
+
* index.ts and is passed in by the handler). These are the fields the
|
|
255
|
+
* pre-pass reads; the handler's own type is preserved through the generic
|
|
256
|
+
* `M` so it can build its mode-specific unit records from the result.
|
|
257
|
+
*/
|
|
258
|
+
export interface UnitPrePassSource {
|
|
259
|
+
task: string;
|
|
260
|
+
label?: string;
|
|
261
|
+
effectiveCwd: string;
|
|
262
|
+
outputFile?: string;
|
|
263
|
+
thinkingLevel: ThinkingLevel;
|
|
264
|
+
toolOptions?: SubagentToolOptions;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** One validated unit: the handler's unit and merged source, plus the
|
|
268
|
+
* resolved cwd/outputFile that unit must spawn in. */
|
|
269
|
+
export interface ValidatedUnit<U, M extends UnitPrePassSource> {
|
|
270
|
+
unit: U;
|
|
271
|
+
merged: M;
|
|
272
|
+
cwd: string;
|
|
273
|
+
outputFile: string | undefined;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export interface UnitPrePassInput<U, M extends UnitPrePassSource> {
|
|
277
|
+
units: readonly U[];
|
|
278
|
+
/** The handler's mergeSubTaskParams, bound to its globalParams. */
|
|
279
|
+
merge: (unit: U, index: number) => M;
|
|
280
|
+
/**
|
|
281
|
+
* Per-unit display data the handler already computes — no formatting
|
|
282
|
+
* policy lives in this helper. Called after `merge` and before target
|
|
283
|
+
* validation, so the unit is described exactly once, in unit order.
|
|
284
|
+
*/
|
|
285
|
+
describe: (
|
|
286
|
+
unit: U,
|
|
287
|
+
merged: M,
|
|
288
|
+
index: number,
|
|
289
|
+
) => {
|
|
290
|
+
/** Unit prefix, e.g. `Step 1 ("one")` / `Node "n1"`. */
|
|
291
|
+
prefix: string;
|
|
292
|
+
/** Extra structured fields merged into the H1 warn entries. */
|
|
293
|
+
logContext: Record<string, unknown>;
|
|
294
|
+
/** Text H1 validates (defaults to `merged.task`); the graph
|
|
295
|
+
* pre-pass passes its placeholder-stripped declared text. */
|
|
296
|
+
task?: string;
|
|
297
|
+
};
|
|
298
|
+
/** H1 site label, e.g. "Chain" / "Parallel" / "Graph". */
|
|
299
|
+
label: string;
|
|
300
|
+
/** Mode-level resolved git mode applied to every unit's H1. */
|
|
301
|
+
gitMode: GitMode;
|
|
302
|
+
ctx: ExtensionContext;
|
|
303
|
+
log: Logger;
|
|
304
|
+
/** Per-unit force flag (IN10): mode entry never carries it. */
|
|
305
|
+
force?: boolean;
|
|
306
|
+
/**
|
|
307
|
+
* The call-level `noJev` bypass (issue #412), forwarded to every unit's H1.
|
|
308
|
+
* Mode entry never carries it either: the mode-level pre-task check has no
|
|
309
|
+
* task text of its own to bypass, and a per-unit bypass would let a caller
|
|
310
|
+
* silence the check for a batch while appearing to pass it for the call.
|
|
311
|
+
*/
|
|
312
|
+
noJev?: string;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export type UnitPrePassOutcome<U, M extends UnitPrePassSource> =
|
|
316
|
+
| { ok: false; error: ToolResult<undefined> }
|
|
317
|
+
| { ok: true; units: Array<ValidatedUnit<U, M>>; warnings: string[] };
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* The per-unit pre-pass shared by chain, parallel and graph: for EVERY unit,
|
|
321
|
+
* merge → validate cwd/outputFile → H1 → collect `${prefix}: ${warning}`.
|
|
322
|
+
*
|
|
323
|
+
* This is a helper each handler CALLS at its own position; it is deliberately
|
|
324
|
+
* not a hook the mode prologue invokes — the three modes run it at different
|
|
325
|
+
* points (chain/parallel before model resolution, graph after the circuit
|
|
326
|
+
* check and the topological sort), and the position is part of the contract
|
|
327
|
+
* (design note #379 IN8). All units are validated before any spawn; the first
|
|
328
|
+
* rejection wins, so nothing starts on a bad unit. Warnings come back in unit
|
|
329
|
+
* order for the caller to surface after the result payload (IN9).
|
|
330
|
+
*/
|
|
331
|
+
export function validateUnitPrePass<U, M extends UnitPrePassSource>(
|
|
332
|
+
input: UnitPrePassInput<U, M>,
|
|
333
|
+
): UnitPrePassOutcome<U, M> {
|
|
334
|
+
const { units, merge, describe, label, gitMode, ctx, log, force, noJev } = input;
|
|
335
|
+
const validated: Array<ValidatedUnit<U, M>> = [];
|
|
336
|
+
const warnings: string[] = [];
|
|
337
|
+
|
|
338
|
+
for (let i = 0; i < units.length; i++) {
|
|
339
|
+
const unit = units[i];
|
|
340
|
+
const merged = merge(unit, i);
|
|
341
|
+
const display = describe(unit, merged, i);
|
|
342
|
+
|
|
343
|
+
const targets = validateDelegationTargets({
|
|
344
|
+
ctx,
|
|
345
|
+
effectiveCwd: merged.effectiveCwd,
|
|
346
|
+
outputFile: merged.outputFile,
|
|
347
|
+
prefix: display.prefix,
|
|
348
|
+
});
|
|
349
|
+
if (!targets.ok) return { ok: false, error: targets.error };
|
|
350
|
+
validated.push({ unit, merged, cwd: targets.cwd, outputFile: targets.outputFile });
|
|
351
|
+
|
|
352
|
+
const validation = runPreTaskValidation({
|
|
353
|
+
log,
|
|
354
|
+
label,
|
|
355
|
+
prefix: display.prefix,
|
|
356
|
+
logContext: display.logContext,
|
|
357
|
+
preTask: {
|
|
358
|
+
task: display.task ?? merged.task,
|
|
359
|
+
toolOptions: merged.toolOptions,
|
|
360
|
+
thinkingLevel: merged.thinkingLevel,
|
|
361
|
+
gitMode,
|
|
362
|
+
outputFile: merged.outputFile,
|
|
363
|
+
force,
|
|
364
|
+
cwd: targets.cwd,
|
|
365
|
+
noJev,
|
|
366
|
+
},
|
|
367
|
+
});
|
|
368
|
+
if (validation.error) return { ok: false, error: validation.error };
|
|
369
|
+
for (const w of validation.warnings) warnings.push(`${display.prefix}: ${w}`);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
return { ok: true, units: validated, warnings };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// ── Batch tail: model resolution + empty-model + circuit (IN11) ──────────
|
|
376
|
+
|
|
377
|
+
export type SubagentModelResolution =
|
|
378
|
+
| { ok: true; model: { provider: string; id: string } }
|
|
379
|
+
| { ok: false; error: ToolResult<undefined> };
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Resolve WHICH model a dispatch runs on: per-call override > preset.model >
|
|
383
|
+
* configured model > conductor model. The preset handed in is the mode-level
|
|
384
|
+
* `resolvedPreset` — already carrying the auto-route decision when routing
|
|
385
|
+
* chose it — so this one chain serves the batch tail and the single/background
|
|
386
|
+
* paths alike (the fallbacks log, they never throw).
|
|
387
|
+
*/
|
|
388
|
+
export function resolveSubagentModelPrecedence(input: {
|
|
389
|
+
state: SessionState;
|
|
390
|
+
ctx: ExtensionContext;
|
|
391
|
+
log: Logger;
|
|
392
|
+
preset: SubagentPreset | undefined;
|
|
393
|
+
/** Top-level delegate_task model override (issue #96) — beats the preset. */
|
|
394
|
+
perCallModel?: string;
|
|
395
|
+
}): SubagentModelResolution {
|
|
396
|
+
const { state, ctx, log, preset, perCallModel } = input;
|
|
397
|
+
let subagentModel: { provider: string; id: string } | undefined;
|
|
398
|
+
|
|
399
|
+
if (perCallModel) {
|
|
400
|
+
const parsed = parseModelString(perCallModel);
|
|
401
|
+
if (!parsed) {
|
|
402
|
+
log.warn("Model override is not a valid provider/model-id, falling back", { model: perCallModel });
|
|
403
|
+
} else if (modelIsAvailable(ctx.modelRegistry, parsed)) {
|
|
404
|
+
log.info("Using per-call model override", { model: perCallModel });
|
|
405
|
+
return { ok: true, model: parsed };
|
|
406
|
+
} else {
|
|
407
|
+
log.warn("Model override unavailable, falling back", { model: perCallModel });
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
if (preset?.model) {
|
|
412
|
+
const parsed = parseModelString(preset.model);
|
|
413
|
+
if (parsed && modelIsAvailable(ctx.modelRegistry, parsed)) {
|
|
414
|
+
subagentModel = parsed;
|
|
415
|
+
log.info("Using preset model", { preset: preset.name, model: preset.model });
|
|
416
|
+
} else {
|
|
417
|
+
// Fallback: preset model unavailable → configured model
|
|
418
|
+
log.warn("Preset model unavailable, falling back to configured model", {
|
|
419
|
+
preset: preset.name,
|
|
420
|
+
model: preset.model,
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
if (!subagentModel) {
|
|
426
|
+
subagentModel =
|
|
427
|
+
state.config.model ||
|
|
428
|
+
(ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : undefined);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
if (!subagentModel) {
|
|
432
|
+
return {
|
|
433
|
+
ok: false,
|
|
434
|
+
error: rejection(
|
|
435
|
+
"No model available. Configure API keys first, then use /brl-subagent to set a model.",
|
|
436
|
+
),
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
return { ok: true, model: subagentModel };
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
export type ModeModelOutcome =
|
|
444
|
+
| { ok: true; model: { provider: string; id: string }; modelStr: string }
|
|
445
|
+
| { ok: false; error: ToolResult<undefined> };
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* The batch modes' shared tail (IN11): resolve the model (preset + per-call
|
|
449
|
+
* override), reject an empty `provider/id` resolution, then apply the circuit
|
|
450
|
+
* breaker. Handlers CALL it at their own position — chain/parallel after the
|
|
451
|
+
* per-unit pass, graph before its topological sort and per-node pass — because
|
|
452
|
+
* that position is pinned (IN8/IN11).
|
|
453
|
+
*/
|
|
454
|
+
export function resolveModeModel(input: {
|
|
455
|
+
state: SessionState;
|
|
456
|
+
ctx: ExtensionContext;
|
|
457
|
+
log: Logger;
|
|
458
|
+
preset: SubagentPreset | undefined;
|
|
459
|
+
perCallModel?: string;
|
|
460
|
+
}): ModeModelOutcome {
|
|
461
|
+
const { state, ctx, log, preset, perCallModel } = input;
|
|
462
|
+
|
|
463
|
+
const resolution = resolveSubagentModelPrecedence({ state, ctx, log, preset, perCallModel });
|
|
464
|
+
if (!resolution.ok) return { ok: false, error: resolution.error };
|
|
465
|
+
const subagentModel = resolution.model;
|
|
466
|
+
|
|
467
|
+
const modelStr = `${subagentModel.provider}/${subagentModel.id}`.trim();
|
|
468
|
+
if (!modelStr || modelStr === "/") {
|
|
469
|
+
log.warn("Model string is empty after resolution", { model: subagentModel });
|
|
470
|
+
return {
|
|
471
|
+
ok: false,
|
|
472
|
+
error: modelNotConfiguredRejection(),
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// R1: Circuit breaker check — after model resolution (IN11).
|
|
477
|
+
const circuitCheck = state.checkCircuit();
|
|
478
|
+
if (circuitCheck.isOpen) {
|
|
479
|
+
return { ok: false, error: rejection(circuitCheck.message!) };
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
return { ok: true, model: subagentModel, modelStr };
|
|
483
|
+
}
|
package/src/presets.ts
CHANGED
|
@@ -12,61 +12,12 @@ import * as path from "node:path";
|
|
|
12
12
|
import type { SubagentPreset, ThinkingLevel } from "./types";
|
|
13
13
|
import { THINKING_LEVELS } from "./types";
|
|
14
14
|
import type { Logger } from "./logging";
|
|
15
|
+
import { loadMarkdownRecords } from "./loader";
|
|
15
16
|
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Parse YAML frontmatter from a markdown file.
|
|
22
|
-
* Returns metadata key-value pairs and the body content.
|
|
23
|
-
*/
|
|
24
|
-
export function parseFrontmatter(content: string): { meta: Record<string, unknown>; body: string } {
|
|
25
|
-
const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
|
|
26
|
-
if (!match) return { meta: {}, body: content };
|
|
27
|
-
|
|
28
|
-
const meta: Record<string, unknown> = {};
|
|
29
|
-
const lines = match[1].split("\n");
|
|
30
|
-
let currentKey = "";
|
|
31
|
-
let currentArray: string[] | null = null;
|
|
32
|
-
|
|
33
|
-
for (const line of lines) {
|
|
34
|
-
// Array item: starts with "- "
|
|
35
|
-
if (line.match(/^\s+-\s+/)) {
|
|
36
|
-
if (currentArray !== null) {
|
|
37
|
-
currentArray.push(line.replace(/^\s+-\s+/, "").trim());
|
|
38
|
-
}
|
|
39
|
-
continue;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// End of array if we were in one
|
|
43
|
-
if (currentArray !== null) {
|
|
44
|
-
meta[currentKey] = currentArray;
|
|
45
|
-
currentArray = null;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
// Key-value pair
|
|
49
|
-
const kvMatch = line.match(/^(\w+):\s*(.*)$/);
|
|
50
|
-
if (kvMatch) {
|
|
51
|
-
const key = kvMatch[1];
|
|
52
|
-
const value = kvMatch[2].trim();
|
|
53
|
-
// Check if next line starts an array
|
|
54
|
-
if (value === "") {
|
|
55
|
-
currentKey = key;
|
|
56
|
-
currentArray = [];
|
|
57
|
-
} else {
|
|
58
|
-
// Strip quotes if present
|
|
59
|
-
meta[key] = value.replace(/^["']|["']$/g, "");
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
// Close any pending array
|
|
64
|
-
if (currentArray !== null) {
|
|
65
|
-
meta[currentKey] = currentArray;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
return { meta, body: match[2].trim() };
|
|
69
|
-
}
|
|
17
|
+
// `parseFrontmatter` moved to loader.ts when the four loader copies collapsed
|
|
18
|
+
// into one walk (issue #380). Re-exported so the existing import sites keep
|
|
19
|
+
// working unchanged.
|
|
20
|
+
export { parseFrontmatter } from "./loader";
|
|
70
21
|
|
|
71
22
|
// ---------------------------------------------------------------------------
|
|
72
23
|
// Preset validation
|
|
@@ -120,54 +71,47 @@ export function validatePreset(meta: Record<string, unknown>, fileName: string):
|
|
|
120
71
|
// Loading
|
|
121
72
|
// ---------------------------------------------------------------------------
|
|
122
73
|
|
|
74
|
+
/**
|
|
75
|
+
* Normalise validated preset frontmatter into a SubagentPreset. Shared by both
|
|
76
|
+
* preset tiers — the file walk and validation live in loadMarkdownRecords.
|
|
77
|
+
*/
|
|
78
|
+
function presetFromFrontmatter(
|
|
79
|
+
meta: Record<string, unknown>,
|
|
80
|
+
body: string,
|
|
81
|
+
name: string,
|
|
82
|
+
): SubagentPreset {
|
|
83
|
+
return {
|
|
84
|
+
name,
|
|
85
|
+
description: (meta.description as string) || undefined,
|
|
86
|
+
systemPrompt: body || undefined,
|
|
87
|
+
thinkingLevel: (meta.thinkingLevel as string) || undefined,
|
|
88
|
+
model: (meta.model as string) || undefined,
|
|
89
|
+
inheritSystemPrompt: meta.inheritSystemPrompt === "false" ? false : undefined,
|
|
90
|
+
tools: Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined,
|
|
91
|
+
excludeTools: Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
|
|
92
|
+
noBuiltinTools: meta.noBuiltinTools === "true" ? true : undefined,
|
|
93
|
+
promptGuideline: (meta.promptGuideline as string) || undefined,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
123
97
|
/**
|
|
124
98
|
* Load built-in presets from a directory of markdown files.
|
|
125
99
|
* Files must have YAML frontmatter with at least a `name` field.
|
|
126
100
|
* Invalid files are skipped with log warnings.
|
|
127
101
|
*/
|
|
128
102
|
export function loadBuiltinPresets(presetsDir: string, log?: Logger): SubagentPreset[] {
|
|
129
|
-
const presets
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
const errors = validatePreset(meta, file);
|
|
142
|
-
if (errors.length > 0) {
|
|
143
|
-
for (const err of errors) {
|
|
144
|
-
log?.warn("Preset validation failed", { file, error: err });
|
|
145
|
-
}
|
|
146
|
-
continue;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
const name = meta.name as string;
|
|
150
|
-
|
|
151
|
-
presets.push({
|
|
152
|
-
name,
|
|
153
|
-
description: (meta.description as string) || undefined,
|
|
154
|
-
systemPrompt: body || undefined,
|
|
155
|
-
thinkingLevel: (meta.thinkingLevel as string) || undefined,
|
|
156
|
-
model: (meta.model as string) || undefined,
|
|
157
|
-
inheritSystemPrompt: meta.inheritSystemPrompt === "false" ? false : undefined,
|
|
158
|
-
tools: Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined,
|
|
159
|
-
excludeTools: Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
|
|
160
|
-
noBuiltinTools: meta.noBuiltinTools === "true" ? true : undefined,
|
|
161
|
-
promptGuideline: (meta.promptGuideline as string) || undefined,
|
|
162
|
-
});
|
|
163
|
-
} catch (err) {
|
|
164
|
-
log?.warn("Failed to load preset file", { file, error: (err as Error).message });
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
} catch {
|
|
168
|
-
// Presets directory doesn't exist or can't be read — no built-in presets
|
|
169
|
-
log?.info("No built-in presets directory found", { dir: presetsDir });
|
|
170
|
-
}
|
|
103
|
+
const presets = loadMarkdownRecords<SubagentPreset>({
|
|
104
|
+
dirs: [presetsDir],
|
|
105
|
+
validate: validatePreset,
|
|
106
|
+
map: presetFromFrontmatter,
|
|
107
|
+
log,
|
|
108
|
+
messages: {
|
|
109
|
+
invalid: "Preset validation failed",
|
|
110
|
+
readFailed: "Failed to load preset file",
|
|
111
|
+
},
|
|
112
|
+
// Built-in presets directory doesn't exist or can't be read — no built-in presets
|
|
113
|
+
onMissingDir: (dir) => log?.info("No built-in presets directory found", { dir }),
|
|
114
|
+
});
|
|
171
115
|
|
|
172
116
|
// Validate all loaded presets
|
|
173
117
|
const validationErrors = validateAllPresets(presets);
|
|
@@ -195,60 +139,24 @@ export function loadBuiltinPresets(presetsDir: string, log?: Logger): SubagentPr
|
|
|
195
139
|
* 2. ~/.pi/agent/brl-subagent/presets/ (global)
|
|
196
140
|
*/
|
|
197
141
|
export function loadCustomPresets(cwd: string, log?: Logger): SubagentPreset[] {
|
|
198
|
-
const presets: SubagentPreset[] = [];
|
|
199
|
-
const seenNames = new Set<string>();
|
|
200
142
|
const homedir = process.env.HOME || process.env.USERPROFILE || "";
|
|
201
143
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
if (errors.length > 0) {
|
|
219
|
-
for (const err of errors) {
|
|
220
|
-
log?.warn("Custom preset validation failed", { file, error: err });
|
|
221
|
-
}
|
|
222
|
-
continue;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
const name = meta.name as string;
|
|
226
|
-
// Dedup by name: the first occurrence (project-local, scanned
|
|
227
|
-
// first) wins; user-global duplicates are skipped.
|
|
228
|
-
if (seenNames.has(name)) continue;
|
|
229
|
-
seenNames.add(name);
|
|
230
|
-
presets.push({
|
|
231
|
-
name,
|
|
232
|
-
description: (meta.description as string) || undefined,
|
|
233
|
-
systemPrompt: body || undefined,
|
|
234
|
-
thinkingLevel: (meta.thinkingLevel as string) || undefined,
|
|
235
|
-
model: (meta.model as string) || undefined,
|
|
236
|
-
inheritSystemPrompt: meta.inheritSystemPrompt === "false" ? false : undefined,
|
|
237
|
-
tools: Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined,
|
|
238
|
-
excludeTools: Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
|
|
239
|
-
noBuiltinTools: meta.noBuiltinTools === "true" ? true : undefined,
|
|
240
|
-
promptGuideline: (meta.promptGuideline as string) || undefined,
|
|
241
|
-
});
|
|
242
|
-
} catch (err) {
|
|
243
|
-
log?.warn("Failed to load custom preset file", { file, error: (err as Error).message });
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
} catch {
|
|
247
|
-
// Directory doesn't exist — that's fine, no custom presets
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
return presets;
|
|
144
|
+
return loadMarkdownRecords<SubagentPreset>({
|
|
145
|
+
dirs: [
|
|
146
|
+
path.join(cwd, ".pi", "brl-subagent", "presets"),
|
|
147
|
+
path.join(homedir, ".pi", "agent", "brl-subagent", "presets"),
|
|
148
|
+
],
|
|
149
|
+
validate: validatePreset,
|
|
150
|
+
map: presetFromFrontmatter,
|
|
151
|
+
// Dedup by name: the first occurrence (project-local, scanned first) wins.
|
|
152
|
+
dedupeByName: true,
|
|
153
|
+
log,
|
|
154
|
+
messages: {
|
|
155
|
+
invalid: "Custom preset validation failed",
|
|
156
|
+
readFailed: "Failed to load custom preset file",
|
|
157
|
+
},
|
|
158
|
+
// A missing directory is fine — no custom presets in that tier.
|
|
159
|
+
});
|
|
252
160
|
}
|
|
253
161
|
|
|
254
162
|
// ---------------------------------------------------------------------------
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Purpose: The single reader for the project-local `brl-subagent` umbrella flags (issue #415).
|
|
2
|
+
/**
|
|
3
|
+
* The umbrella project-local flag: `{"brl-subagent": {"processChecks": true}}`.
|
|
4
|
+
*
|
|
5
|
+
* `processChecks` gates OUR process mechanisms — the Jev dispatch-line check
|
|
6
|
+
* (#407/#412) and rule 2's durable-shape auto-switch (#412). It replaces the
|
|
7
|
+
* merged-but-unreleased `requireJevLine`: one flag, one reader, no per-rule
|
|
8
|
+
* fields.
|
|
9
|
+
*
|
|
10
|
+
* Why one reader (issue #415): the shape rule shipped GLOBAL, so a user's
|
|
11
|
+
* explicit `background: false` + timeout was overridden by our conductor
|
|
12
|
+
* decision rule. A conductor rule is not product behavior. Scoping both
|
|
13
|
+
* mechanisms behind one project-local opt-in keeps a user's dispatch exactly as
|
|
14
|
+
* they asked for it, and this module is the only place the manifest field is
|
|
15
|
+
* read (the ratchet in `project-flags.test.ts` fails a second reader).
|
|
16
|
+
*
|
|
17
|
+
* FAIL-OPEN is the product contract: a missing, unreadable or malformed
|
|
18
|
+
* `package.json` means `false`. A project's packaging mistake must never reject
|
|
19
|
+
* a user's dispatch or reshape it.
|
|
20
|
+
*
|
|
21
|
+
* The manifest read is the project's OWN `package.json` — tracked, so it exists
|
|
22
|
+
* in every worktree (worktrees share the repo's manifest), unlike a gitignored
|
|
23
|
+
* marker under `.pi/`.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { readFileSync } from "node:fs";
|
|
27
|
+
import { join } from "node:path";
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The fields this module is allowed to read from the `brl-subagent` section.
|
|
31
|
+
* A third field is a new mechanism, and a new mechanism needs its own ADR and
|
|
32
|
+
* its own line in this whitelist (the ratchet enforces both directions).
|
|
33
|
+
*/
|
|
34
|
+
export const PROCESS_CHECK_KEYS = ["processChecks"] as const;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Whether the project at `cwd` opted into our process checks. Fail-open in
|
|
38
|
+
* every failure mode: no cwd, no manifest, unreadable manifest, malformed JSON,
|
|
39
|
+
* a non-object section, or a non-boolean field all read as `false`.
|
|
40
|
+
*/
|
|
41
|
+
export function readProcessChecks(cwd: string | undefined): boolean {
|
|
42
|
+
if (cwd === undefined || cwd === "") return false;
|
|
43
|
+
try {
|
|
44
|
+
const manifest = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8")) as {
|
|
45
|
+
"brl-subagent"?: { processChecks?: unknown };
|
|
46
|
+
};
|
|
47
|
+
return manifest?.["brl-subagent"]?.processChecks === true;
|
|
48
|
+
} catch {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The validation seam's name for the same read (`validatePreTask` asks "is the
|
|
55
|
+
* check enabled for this project?"). One implementation: this is an alias, not
|
|
56
|
+
* a second reader.
|
|
57
|
+
*/
|
|
58
|
+
export const isProcessChecksEnabled = readProcessChecks;
|
package/src/run-registry.ts
CHANGED
|
@@ -35,6 +35,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
|
35
35
|
import type { ProcessOwner, RecoveryMode, SubagentRun } from "./types";
|
|
36
36
|
import { CUSTOM_ENTRY_TYPES, RECOVERY_MODES } from "./types";
|
|
37
37
|
import { assertSafeAgentId } from "./sanitize";
|
|
38
|
+
import { ensureOwnerOnlyDir } from "./store-permissions";
|
|
38
39
|
|
|
39
40
|
/** Which execution path owns an in-flight run (drives the boot scan's mark). */
|
|
40
41
|
export type InflightRunKind = "foreground" | "unit" | "background";
|
|
@@ -126,7 +127,9 @@ function resolvePath(id: string): string | null {
|
|
|
126
127
|
}
|
|
127
128
|
|
|
128
129
|
function ensureDir(): void {
|
|
129
|
-
|
|
130
|
+
// Issue #408: `mode` only applies on CREATE — repair a pre-existing registry
|
|
131
|
+
// dir on every write so the entries stay untraversable by other local users.
|
|
132
|
+
ensureOwnerOnlyDir(REGISTRY_DIR);
|
|
130
133
|
}
|
|
131
134
|
|
|
132
135
|
/** True when `value` looks like a registry entry (id + kind + startedAt). */
|