brl-subagent 2.6.0 → 2.8.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/src/prelude.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Purpose: Shared guard/validation prelude opening every delegation mode (cost gate, approval, H1 validation, dispatch guards).
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,16 @@
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";
50
+ import { approvalBlocksBackground, isThinkingLevel, THINKING_LEVELS } from "./types";
37
51
  import type { SessionState } from "./state";
38
52
  import type { Logger } from "./logging";
39
53
  import { validateCwd, validateOutputFile } from "./sanitize";
40
54
  import { validatePreTask, type ValidateConfig } from "./validate";
55
+ import { modelIsAvailable, parseModelString } from "./model-availability";
41
56
 
42
57
  /** The standard rejection result shape shared by these gates. */
43
- function rejection(text: string): ToolResult<undefined> {
58
+ export function rejection(text: string): ToolResult<undefined> {
44
59
  return {
45
60
  content: [{ type: "text" as const, text }],
46
61
  details: undefined,
@@ -48,6 +63,89 @@ function rejection(text: string): ToolResult<undefined> {
48
63
  };
49
64
  }
50
65
 
66
+ // ── Shared rejection messages (one wording, every dispatch path) ────────
67
+
68
+ /**
69
+ * The recursion-depth rejection (IN3). The gate itself lives per family (the
70
+ * batch prologue and the single foreground path), but the wording must not
71
+ * drift between them — the #375 prose guard treats a second copy as a build
72
+ * failure.
73
+ */
74
+ export function depthLimitRejection(currentDepth: number, maxDepth: number): ToolResult<undefined> {
75
+ return rejection(
76
+ `Cannot delegate further: subagent recursion depth limit reached ` +
77
+ `(depth ${currentDepth}/${maxDepth}). ` +
78
+ `Subagents can delegate up to ${maxDepth} levels deep (configurable via /brl-subagent depth). Complete the remaining work directly.`,
79
+ );
80
+ }
81
+
82
+ /**
83
+ * The empty-`provider/id` rejection (IN11): a model resolved to nothing usable.
84
+ * Shared by the batch tail (`resolveModeModel`) and the single foreground path.
85
+ */
86
+ export function modelNotConfiguredRejection(): ToolResult<undefined> {
87
+ return rejection(
88
+ "Subagent model is not configured. " +
89
+ "Use /brl-subagent to set a model, or ensure your current session has a valid model.",
90
+ );
91
+ }
92
+
93
+ // ── Gate 0: a DECLARED thinking level (issue #443) ──────────────────────
94
+
95
+ /**
96
+ * Render a declared value for the rejection text. A string is quoted as JSON so
97
+ * an empty/whitespace value is VISIBLE (`""` vs `" high"`); anything else
98
+ * arrives only from a programmatic caller (the schema declares a string), so it
99
+ * is rendered as JSON and falls back to `String` for the values JSON rejects
100
+ * (a `BigInt` throws, a symbol stringifies to `undefined`).
101
+ */
102
+ function renderDeclaredThinkingLevel(value: unknown): string {
103
+ try {
104
+ return JSON.stringify(value) ?? String(value);
105
+ } catch {
106
+ return String(value);
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Reject an unsupported DECLARED thinking level before it reaches resolution
112
+ * (issue #443). Returns `undefined` when the value is usable.
113
+ *
114
+ * This is the runtime guard; the schema's `enum` is only the first line of
115
+ * defence, because pi validates raw TOOL ARGUMENTS. Every other route to a
116
+ * launch — a preset object injected in memory (the file tier has its own
117
+ * validator, `getPreset` does not re-check), a value restored by `retryRunId`,
118
+ * the transport auto-retry's rebuilt params, a per-unit declaration — reaches
119
+ * `resolveSubagentParams` without passing through the schema at all.
120
+ *
121
+ * The guard must run before resolution: `resolveThinkingLevel` erases an
122
+ * unknown value to `undefined`, which then survives every later check
123
+ * (`resolveSubagentParams` returns a level, it cannot report a failure) and
124
+ * reaches the child as `--thinking undefined`, where pi warns and runs at its
125
+ * own default — the configured cap silently bypassed.
126
+ *
127
+ * Deliberately NOT rejected: `undefined`/`null` (omitted) and `""`. Both are
128
+ * existing, meaningful declarations — top level `""` means "use the configured
129
+ * maximum", per unit `""` means "inherit the global level" — so the empty
130
+ * string keeps its meaning rather than becoming an error.
131
+ *
132
+ * `prefix` names the unit a per-unit declaration came from, matching the other
133
+ * unit-prefixed rejections (`Task 2 ("two"): …`).
134
+ */
135
+ export function invalidThinkingLevelRejection(
136
+ declared: unknown,
137
+ prefix?: string,
138
+ ): ToolResult<undefined> | undefined {
139
+ // Omitted, or the preserved empty-string declaration: not a level to judge.
140
+ if (declared === undefined || declared === null || declared === "") return undefined;
141
+ if (isThinkingLevel(declared)) return undefined;
142
+ return rejection(
143
+ `${prefix ? `${prefix}: ` : ""}Invalid thinkingLevel ${renderDeclaredThinkingLevel(declared)}. ` +
144
+ `Valid levels: ${THINKING_LEVELS.join(", ")} — matched exactly, so "High" and " high" are rejected too. ` +
145
+ `Omit thinkingLevel, or pass "", to use the configured maximum.`,
146
+ );
147
+ }
148
+
51
149
  // ── Gate 1: session cost ────────────────────────────────────────────────
52
150
 
53
151
  /**
@@ -101,7 +199,7 @@ export function gateSessionCost(input: {
101
199
  export function rejectApprovalAlwaysInBackground(
102
200
  approvalMode: ApprovalMode,
103
201
  ): ToolResult<undefined> | undefined {
104
- if (approvalMode !== "always") return undefined;
202
+ if (!approvalBlocksBackground(approvalMode)) return undefined;
105
203
  return rejection(
106
204
  `Cannot spawn background agent with approvalMode 'always': background agents run unattended ` +
107
205
  `and cannot present the approval dialog. Use approvalMode 'auto' (default) or 'writes'.`,
@@ -205,3 +303,257 @@ export function runPreTaskValidation(input: {
205
303
  }
206
304
  return { warnings: validation.warnings };
207
305
  }
306
+
307
+ // ── Gate 4: per-unit pre-pass (merge → targets → H1) ────────────────────
308
+
309
+ /**
310
+ * A merged per-unit source, structurally (mergeSubTaskParams lives in
311
+ * index.ts and is passed in by the handler). These are the fields the
312
+ * pre-pass reads; the handler's own type is preserved through the generic
313
+ * `M` so it can build its mode-specific unit records from the result.
314
+ */
315
+ export interface UnitPrePassSource {
316
+ task: string;
317
+ label?: string;
318
+ effectiveCwd: string;
319
+ outputFile?: string;
320
+ thinkingLevel: ThinkingLevel;
321
+ toolOptions?: SubagentToolOptions;
322
+ }
323
+
324
+ /** One validated unit: the handler's unit and merged source, plus the
325
+ * resolved cwd/outputFile that unit must spawn in. */
326
+ export interface ValidatedUnit<U, M extends UnitPrePassSource> {
327
+ unit: U;
328
+ merged: M;
329
+ cwd: string;
330
+ outputFile: string | undefined;
331
+ }
332
+
333
+ export interface UnitPrePassInput<U, M extends UnitPrePassSource> {
334
+ units: readonly U[];
335
+ /** The handler's mergeSubTaskParams, bound to its globalParams. */
336
+ merge: (unit: U, index: number) => M;
337
+ /**
338
+ * Per-unit display data the handler already computes — no formatting
339
+ * policy lives in this helper. Called after `merge` and before target
340
+ * validation, so the unit is described exactly once, in unit order.
341
+ */
342
+ describe: (
343
+ unit: U,
344
+ merged: M,
345
+ index: number,
346
+ ) => {
347
+ /** Unit prefix, e.g. `Step 1 ("one")` / `Node "n1"`. */
348
+ prefix: string;
349
+ /** Extra structured fields merged into the H1 warn entries. */
350
+ logContext: Record<string, unknown>;
351
+ /** Text H1 validates (defaults to `merged.task`); the graph
352
+ * pre-pass passes its placeholder-stripped declared text. */
353
+ task?: string;
354
+ };
355
+ /** H1 site label, e.g. "Chain" / "Parallel" / "Graph". */
356
+ label: string;
357
+ /** Mode-level resolved git mode applied to every unit's H1. */
358
+ gitMode: GitMode;
359
+ ctx: ExtensionContext;
360
+ log: Logger;
361
+ /** Per-unit force flag (IN10): mode entry never carries it. */
362
+ force?: boolean;
363
+ /**
364
+ * The call-level `noJev` bypass (issue #412), forwarded to every unit's H1.
365
+ * Mode entry never carries it either: the mode-level pre-task check has no
366
+ * task text of its own to bypass, and a per-unit bypass would let a caller
367
+ * silence the check for a batch while appearing to pass it for the call.
368
+ */
369
+ noJev?: string;
370
+ /**
371
+ * The unit's DECLARED thinkingLevel, read from the unit itself (issue #443).
372
+ * Required, so a new caller cannot silently skip the check: the merged value
373
+ * cannot be judged — `merge` has already resolved it, and an unknown
374
+ * declaration comes back as `undefined` (the erasure this guard exists for).
375
+ * `""` and an omitted declaration are NOT rejected here: they mean "inherit
376
+ * the global level", which `merge` applies.
377
+ */
378
+ declaredThinkingLevel: (unit: U) => unknown;
379
+ }
380
+
381
+ export type UnitPrePassOutcome<U, M extends UnitPrePassSource> =
382
+ | { ok: false; error: ToolResult<undefined> }
383
+ | { ok: true; units: Array<ValidatedUnit<U, M>>; warnings: string[] };
384
+
385
+ /**
386
+ * The per-unit pre-pass shared by chain, parallel and graph: for EVERY unit,
387
+ * declared-level guard → merge → validate cwd/outputFile → H1 → collect
388
+ * `${prefix}: ${warning}`.
389
+ *
390
+ * This is a helper each handler CALLS at its own position; it is deliberately
391
+ * not a hook the mode prologue invokes — the three modes run it at different
392
+ * points (chain/parallel before model resolution, graph after the circuit
393
+ * check and the topological sort), and the position is part of the contract
394
+ * (design note #379 IN8). All units are validated before any spawn; the first
395
+ * rejection wins, so nothing starts on a bad unit. Warnings come back in unit
396
+ * order for the caller to surface after the result payload (IN9).
397
+ */
398
+ export function validateUnitPrePass<U, M extends UnitPrePassSource>(
399
+ input: UnitPrePassInput<U, M>,
400
+ ): UnitPrePassOutcome<U, M> {
401
+ const { units, merge, describe, label, gitMode, ctx, log, force, noJev, declaredThinkingLevel } = input;
402
+ const validated: Array<ValidatedUnit<U, M>> = [];
403
+ const warnings: string[] = [];
404
+
405
+ for (let i = 0; i < units.length; i++) {
406
+ const unit = units[i];
407
+ const merged = merge(unit, i);
408
+ const display = describe(unit, merged, i);
409
+
410
+ // Issue #443: the DECLARED per-unit level, before `merged.thinkingLevel`
411
+ // (already resolved, so an unknown value is indistinguishable from
412
+ // omitted) could hide it.
413
+ const thinkingError = invalidThinkingLevelRejection(
414
+ declaredThinkingLevel(unit),
415
+ display.prefix,
416
+ );
417
+ if (thinkingError) return { ok: false, error: thinkingError };
418
+
419
+ const targets = validateDelegationTargets({
420
+ ctx,
421
+ effectiveCwd: merged.effectiveCwd,
422
+ outputFile: merged.outputFile,
423
+ prefix: display.prefix,
424
+ });
425
+ if (!targets.ok) return { ok: false, error: targets.error };
426
+ validated.push({ unit, merged, cwd: targets.cwd, outputFile: targets.outputFile });
427
+
428
+ const validation = runPreTaskValidation({
429
+ log,
430
+ label,
431
+ prefix: display.prefix,
432
+ logContext: display.logContext,
433
+ preTask: {
434
+ task: display.task ?? merged.task,
435
+ toolOptions: merged.toolOptions,
436
+ thinkingLevel: merged.thinkingLevel,
437
+ gitMode,
438
+ outputFile: merged.outputFile,
439
+ force,
440
+ cwd: targets.cwd,
441
+ noJev,
442
+ },
443
+ });
444
+ if (validation.error) return { ok: false, error: validation.error };
445
+ for (const w of validation.warnings) warnings.push(`${display.prefix}: ${w}`);
446
+ }
447
+
448
+ return { ok: true, units: validated, warnings };
449
+ }
450
+
451
+ // ── Batch tail: model resolution + empty-model + circuit (IN11) ──────────
452
+
453
+ export type SubagentModelResolution =
454
+ | { ok: true; model: { provider: string; id: string } }
455
+ | { ok: false; error: ToolResult<undefined> };
456
+
457
+ /**
458
+ * Resolve WHICH model a dispatch runs on: per-call override > preset.model >
459
+ * configured model > conductor model. The preset handed in is the mode-level
460
+ * `resolvedPreset` — already carrying the auto-route decision when routing
461
+ * chose it — so this one chain serves the batch tail and the single/background
462
+ * paths alike (the fallbacks log, they never throw).
463
+ */
464
+ export function resolveSubagentModelPrecedence(input: {
465
+ state: SessionState;
466
+ ctx: ExtensionContext;
467
+ log: Logger;
468
+ preset: SubagentPreset | undefined;
469
+ /** Top-level delegate_task model override (issue #96) — beats the preset. */
470
+ perCallModel?: string;
471
+ }): SubagentModelResolution {
472
+ const { state, ctx, log, preset, perCallModel } = input;
473
+ let subagentModel: { provider: string; id: string } | undefined;
474
+
475
+ if (perCallModel) {
476
+ const parsed = parseModelString(perCallModel);
477
+ if (!parsed) {
478
+ log.warn("Model override is not a valid provider/model-id, falling back", { model: perCallModel });
479
+ } else if (modelIsAvailable(ctx.modelRegistry, parsed)) {
480
+ log.info("Using per-call model override", { model: perCallModel });
481
+ return { ok: true, model: parsed };
482
+ } else {
483
+ log.warn("Model override unavailable, falling back", { model: perCallModel });
484
+ }
485
+ }
486
+
487
+ if (preset?.model) {
488
+ const parsed = parseModelString(preset.model);
489
+ if (parsed && modelIsAvailable(ctx.modelRegistry, parsed)) {
490
+ subagentModel = parsed;
491
+ log.info("Using preset model", { preset: preset.name, model: preset.model });
492
+ } else {
493
+ // Fallback: preset model unavailable → configured model
494
+ log.warn("Preset model unavailable, falling back to configured model", {
495
+ preset: preset.name,
496
+ model: preset.model,
497
+ });
498
+ }
499
+ }
500
+
501
+ if (!subagentModel) {
502
+ subagentModel =
503
+ state.config.model ||
504
+ (ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : undefined);
505
+ }
506
+
507
+ if (!subagentModel) {
508
+ return {
509
+ ok: false,
510
+ error: rejection(
511
+ "No model available. Configure API keys first, then use /brl-subagent to set a model.",
512
+ ),
513
+ };
514
+ }
515
+
516
+ return { ok: true, model: subagentModel };
517
+ }
518
+
519
+ export type ModeModelOutcome =
520
+ | { ok: true; model: { provider: string; id: string }; modelStr: string }
521
+ | { ok: false; error: ToolResult<undefined> };
522
+
523
+ /**
524
+ * The batch modes' shared tail (IN11): resolve the model (preset + per-call
525
+ * override), reject an empty `provider/id` resolution, then apply the circuit
526
+ * breaker. Handlers CALL it at their own position — chain/parallel after the
527
+ * per-unit pass, graph before its topological sort and per-node pass — because
528
+ * that position is pinned (IN8/IN11).
529
+ */
530
+ export function resolveModeModel(input: {
531
+ state: SessionState;
532
+ ctx: ExtensionContext;
533
+ log: Logger;
534
+ preset: SubagentPreset | undefined;
535
+ perCallModel?: string;
536
+ }): ModeModelOutcome {
537
+ const { state, ctx, log, preset, perCallModel } = input;
538
+
539
+ const resolution = resolveSubagentModelPrecedence({ state, ctx, log, preset, perCallModel });
540
+ if (!resolution.ok) return { ok: false, error: resolution.error };
541
+ const subagentModel = resolution.model;
542
+
543
+ const modelStr = `${subagentModel.provider}/${subagentModel.id}`.trim();
544
+ if (!modelStr || modelStr === "/") {
545
+ log.warn("Model string is empty after resolution", { model: subagentModel });
546
+ return {
547
+ ok: false,
548
+ error: modelNotConfiguredRejection(),
549
+ };
550
+ }
551
+
552
+ // R1: Circuit breaker check — after model resolution (IN11).
553
+ const circuitCheck = state.checkCircuit();
554
+ if (circuitCheck.isOpen) {
555
+ return { ok: false, error: rejection(circuitCheck.message!) };
556
+ }
557
+
558
+ return { ok: true, model: subagentModel, modelStr };
559
+ }