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/AGENT.md +3 -2
- package/README.md +31 -10
- package/package.json +8 -5
- package/src/concurrency.ts +25 -2
- package/src/dispatch-line.ts +144 -0
- package/src/engineering-bar.ts +69 -0
- package/src/event-bus.ts +10 -0
- package/src/git.ts +58 -1
- package/src/headstate.ts +471 -0
- package/src/history.ts +13 -1
- package/src/index.ts +1328 -947
- package/src/kill-escalation.ts +87 -7
- package/src/loader.ts +224 -0
- package/src/mode-prologue.ts +169 -0
- package/src/model-availability.ts +13 -1
- package/src/notify-completion.ts +146 -5
- package/src/params.ts +356 -66
- package/src/prelude.ts +356 -4
- package/src/presets.ts +127 -150
- package/src/project-flags.ts +58 -0
- package/src/recovery-engine.ts +10 -0
- package/src/recovery.ts +155 -19
- package/src/run-registry.ts +24 -1
- package/src/runner.ts +34 -4
- package/src/schema.ts +101 -55
- package/src/session-manager.ts +1549 -264
- package/src/state.ts +118 -16
- package/src/store-permissions.ts +98 -0
- package/src/templates.ts +92 -121
- package/src/transcript.ts +5 -2
- package/src/transport-retry.ts +90 -0
- package/src/tui-format.ts +174 -6
- package/src/tui.ts +284 -377
- package/src/types.ts +219 -25
- package/src/unit-run.ts +10 -1
- package/src/validate.ts +120 -0
package/src/kill-escalation.ts
CHANGED
|
@@ -329,6 +329,17 @@ export function processTarget(
|
|
|
329
329
|
: pidTarget(pid, kill, pidAlive, guard);
|
|
330
330
|
}
|
|
331
331
|
|
|
332
|
+
/**
|
|
333
|
+
* #455: the default post-SIGKILL confirmation window. SIGKILL delivery is
|
|
334
|
+
* ASYNCHRONOUS — sampling death in the same pass that signalled reads `R`
|
|
335
|
+
* (signal pending) or `Z` (awaiting reap) and calls a dying process a survivor.
|
|
336
|
+
* 100 ms is a bounded confirmation window, not a wait for a kill to work.
|
|
337
|
+
*/
|
|
338
|
+
const DEFAULT_DRAIN_MS = 100;
|
|
339
|
+
|
|
340
|
+
/** #455: drain poll interval when the caller set no `pollMs`. */
|
|
341
|
+
const DEFAULT_DRAIN_POLL_MS = 10;
|
|
342
|
+
|
|
332
343
|
export interface EscalationOptions {
|
|
333
344
|
/** Grace window between SIGTERM and SIGKILL (ms). */
|
|
334
345
|
graceMs: number;
|
|
@@ -337,11 +348,51 @@ export interface EscalationOptions {
|
|
|
337
348
|
/**
|
|
338
349
|
* Poll interval for the early-exit wait (B4). When > 0 the helper returns as
|
|
339
350
|
* soon as every target verifies dead, bounded by `graceMs`; when omitted the
|
|
340
|
-
* helper waits the full `graceMs` once.
|
|
351
|
+
* helper waits the full `graceMs` once. Also used as the #455 drain interval.
|
|
341
352
|
*/
|
|
342
353
|
pollMs?: number;
|
|
343
354
|
/** Injectable clock for the deadline (defaults to Date.now). */
|
|
344
355
|
now?(): number;
|
|
356
|
+
/**
|
|
357
|
+
* #455: bounded post-SIGKILL confirmation window (ms) — how long the helper
|
|
358
|
+
* re-samples `verifyDeath()` for the targets it just force-killed before it
|
|
359
|
+
* classifies survivors. Defaults to {@link DEFAULT_DRAIN_MS}; `0` (any
|
|
360
|
+
* non-positive value) disables it and restores the legacy single-sample
|
|
361
|
+
* classification (the documented escape). Ignored when no `forceKill` was issued: a target that died during
|
|
362
|
+
* the grace window has no signal in flight to confirm.
|
|
363
|
+
*/
|
|
364
|
+
drainMs?: number;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* #455 phase B: re-sample `verifyDeath()` for the targets that were force-killed
|
|
369
|
+
* until every one confirms dead or the drain deadline passes. SIGKILL delivery
|
|
370
|
+
* and reaping are asynchronous, so the classification below must not be decided
|
|
371
|
+
* by the sample taken in the same instant as the signal.
|
|
372
|
+
*
|
|
373
|
+
* Bounded by `now() + drainMs` (never "poll until dead") and cheap when nothing
|
|
374
|
+
* is in flight: zero force-killed targets ⇒ no sleep, no clock read.
|
|
375
|
+
*/
|
|
376
|
+
async function drainForceKilled(
|
|
377
|
+
forceKilled: EscalationTarget[],
|
|
378
|
+
options: EscalationOptions,
|
|
379
|
+
): Promise<void> {
|
|
380
|
+
const drainMs = options.drainMs ?? DEFAULT_DRAIN_MS;
|
|
381
|
+
if (forceKilled.length === 0 || drainMs <= 0) return;
|
|
382
|
+
const pollMs = options.pollMs && options.pollMs > 0 ? options.pollMs : DEFAULT_DRAIN_POLL_MS;
|
|
383
|
+
const now = options.now ?? Date.now;
|
|
384
|
+
const deadline = now() + drainMs;
|
|
385
|
+
// TWO bounds, deliberately. The clock bound is the contract ("100 ms"); the
|
|
386
|
+
// iteration bound is what keeps a sleep that does not actually advance time
|
|
387
|
+
// (a no-op injected sleep) from turning the drain into a hot spin — measured
|
|
388
|
+
// at 61k samples inside one 100 ms window before this bound existed.
|
|
389
|
+
const maxPolls = Math.max(1, Math.ceil(drainMs / pollMs));
|
|
390
|
+
for (let poll = 0; poll < maxPolls; poll++) {
|
|
391
|
+
if (forceKilled.every((target) => target.verifyDeath())) return;
|
|
392
|
+
const remaining = deadline - now();
|
|
393
|
+
if (remaining <= 0) return;
|
|
394
|
+
await options.sleep(Math.min(pollMs, remaining));
|
|
395
|
+
}
|
|
345
396
|
}
|
|
346
397
|
|
|
347
398
|
/**
|
|
@@ -361,6 +412,15 @@ export interface EscalationOptions {
|
|
|
361
412
|
* whose final group signal was REFUSED while its group still had live members is
|
|
362
413
|
* appended to the survivors (`refusedForceKillGroup`), so a refined guard
|
|
363
414
|
* decision can never report a clean result over a live group we targeted.
|
|
415
|
+
*
|
|
416
|
+
* #455: the SIGKILL pass is three phases — (A) dispatch `forceKill` to every
|
|
417
|
+
* target still verifying alive, (B) a BOUNDED post-SIGKILL drain of
|
|
418
|
+
* `verifyDeath` for exactly those targets, (C) classify survivors. Phases A and
|
|
419
|
+
* C were one pass before, which decided the survivor list from a sample taken
|
|
420
|
+
* in the same instant as the signal: SIGKILL is asynchronous, so a dying process
|
|
421
|
+
* (state `R`, or `Z` awaiting reap) read as a survivor every time. The refused
|
|
422
|
+
* group rule and the unconditional final group SIGKILL stay AFTER phase C — a
|
|
423
|
+
* refusal is a decision, not a timing window.
|
|
364
424
|
*/
|
|
365
425
|
export async function escalateKill(
|
|
366
426
|
targets: EscalationTarget[],
|
|
@@ -379,7 +439,13 @@ export async function escalateKill(
|
|
|
379
439
|
if (pollMs > 0) {
|
|
380
440
|
const now = options.now ?? Date.now;
|
|
381
441
|
const deadline = now() + options.graceMs;
|
|
382
|
-
|
|
442
|
+
// #455 review: the SAME two-bound rule as the drain below — a sleep that
|
|
443
|
+
// does not advance an injected clock must not turn this into a hot spin.
|
|
444
|
+
// With a real clock the iteration cap is exactly the number of polls the
|
|
445
|
+
// window can hold, so it never truncates a legitimate wait.
|
|
446
|
+
const maxPolls = Math.max(1, Math.ceil(options.graceMs / pollMs));
|
|
447
|
+
for (let poll = 0; poll < maxPolls; poll++) {
|
|
448
|
+
if (now() >= deadline || targets.every((target) => target.verifyDeath())) break;
|
|
383
449
|
const remaining = Math.max(deadline - now(), 1);
|
|
384
450
|
await options.sleep(Math.min(pollMs, remaining));
|
|
385
451
|
}
|
|
@@ -388,19 +454,33 @@ export async function escalateKill(
|
|
|
388
454
|
}
|
|
389
455
|
}
|
|
390
456
|
|
|
391
|
-
|
|
457
|
+
// Phase A — force-kill pass. Only force-kill the DIRECT process while it is
|
|
458
|
+
// still alive; a group whose leader already exited is ended by the
|
|
459
|
+
// unconditional group SIGKILL below.
|
|
460
|
+
const forceKilled: EscalationTarget[] = [];
|
|
392
461
|
for (const target of targets) {
|
|
393
462
|
if (target.verifyDeath()) continue;
|
|
394
|
-
// Only force-kill the DIRECT process while it is still alive; a group whose
|
|
395
|
-
// leader already exited is ended by the unconditional group SIGKILL below.
|
|
396
463
|
if (target.verifyProcessAlive?.() ?? true) {
|
|
397
464
|
try {
|
|
398
465
|
target.forceKill();
|
|
466
|
+
forceKilled.push(target);
|
|
399
467
|
} catch {
|
|
400
|
-
// Exited between the liveness check and the signal.
|
|
468
|
+
// Exited between the liveness check and the signal: nothing in flight.
|
|
401
469
|
}
|
|
402
470
|
}
|
|
403
|
-
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// Phase B — bounded drain (#455): let the SIGKILLs that were just dispatched
|
|
474
|
+
// land and be reaped before anything is classified as a survivor.
|
|
475
|
+
await drainForceKilled(forceKilled, options);
|
|
476
|
+
|
|
477
|
+
// Phase C — classify. A survivor is a target that is still not dead AND still
|
|
478
|
+
// process-alive, exactly as before — only now the sample is not taken in the
|
|
479
|
+
// same instant as the signal.
|
|
480
|
+
const survivors: EscalationTarget[] = [];
|
|
481
|
+
for (const target of targets) {
|
|
482
|
+
if (target.verifyDeath()) continue;
|
|
483
|
+
if (target.verifyProcessAlive?.() ?? true) survivors.push(target);
|
|
404
484
|
}
|
|
405
485
|
|
|
406
486
|
// D5 (option b): the final GROUP SIGKILL is UNCONDITIONAL. `verifyDeath` is
|
package/src/loader.ts
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// Purpose: Shared markdown-tier loader — scan dirs for `.md`, parse frontmatter, validate, map to a typed record.
|
|
2
|
+
/**
|
|
3
|
+
* brl-subagent — Markdown tier loader
|
|
4
|
+
*
|
|
5
|
+
* Presets and task templates are both FILE-BACKED tiers: a directory of `.md`
|
|
6
|
+
* files with YAML frontmatter is listed, filtered to `.md`, read, parsed,
|
|
7
|
+
* validated, and normalised into a family-specific record. Before issue #380
|
|
8
|
+
* that pipeline was written four times (builtin presets, custom presets,
|
|
9
|
+
* custom templates, builtin templates) with only the record shape, the
|
|
10
|
+
* validator, and the log wording differing (D6 in the smell audit).
|
|
11
|
+
*
|
|
12
|
+
* This module owns the common steps once. The two families keep their own
|
|
13
|
+
* record types and mappers — `loadMarkdownRecords` is generic over the record
|
|
14
|
+
* and takes the family-specific mapping as `spec.map`, so presets stay presets
|
|
15
|
+
* and templates stay templates while the walk is single-source.
|
|
16
|
+
*
|
|
17
|
+
* Behaviour preserved from the four copies:
|
|
18
|
+
* - non-`.md` entries are ignored; a directory named `*.md` surfaces as a
|
|
19
|
+
* read failure (warn) instead of aborting the scan;
|
|
20
|
+
* - an unreadable directory is skipped (`onMissingDir` lets the builtin tiers
|
|
21
|
+
* log the info line, custom tiers stay silent);
|
|
22
|
+
* - a validation error warns once per error and skips the file;
|
|
23
|
+
* - a per-file read/parse/map throw warns and continues;
|
|
24
|
+
* - dedupe by name is opt-in (`dedupeByName`) and first-occurrence-wins,
|
|
25
|
+
* which is how PROJECT > USER precedence is enforced.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import * as fs from "node:fs";
|
|
29
|
+
import * as path from "node:path";
|
|
30
|
+
import type { Logger } from "./logging";
|
|
31
|
+
|
|
32
|
+
// ---------------------------------------------------------------------------
|
|
33
|
+
// Frontmatter parsing
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Parse YAML frontmatter from a markdown file.
|
|
38
|
+
* Returns metadata key-value pairs and the body content.
|
|
39
|
+
*/
|
|
40
|
+
export function parseFrontmatter(content: string): { meta: Record<string, unknown>; body: string } {
|
|
41
|
+
const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
|
|
42
|
+
if (!match) return { meta: {}, body: content };
|
|
43
|
+
|
|
44
|
+
const meta: Record<string, unknown> = {};
|
|
45
|
+
const lines = match[1].split("\n");
|
|
46
|
+
let currentKey = "";
|
|
47
|
+
let currentArray: string[] | null = null;
|
|
48
|
+
|
|
49
|
+
for (const line of lines) {
|
|
50
|
+
// Array item: starts with "- "
|
|
51
|
+
if (line.match(/^\s+-\s+/)) {
|
|
52
|
+
if (currentArray !== null) {
|
|
53
|
+
currentArray.push(line.replace(/^\s+-\s+/, "").trim());
|
|
54
|
+
}
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// End of array if we were in one
|
|
59
|
+
if (currentArray !== null) {
|
|
60
|
+
meta[currentKey] = currentArray;
|
|
61
|
+
currentArray = null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Key-value pair
|
|
65
|
+
const kvMatch = line.match(/^(\w+):\s*(.*)$/);
|
|
66
|
+
if (kvMatch) {
|
|
67
|
+
const key = kvMatch[1];
|
|
68
|
+
const value = kvMatch[2].trim();
|
|
69
|
+
// Check if next line starts an array
|
|
70
|
+
if (value === "") {
|
|
71
|
+
currentKey = key;
|
|
72
|
+
currentArray = [];
|
|
73
|
+
} else {
|
|
74
|
+
// Strip quotes if present
|
|
75
|
+
meta[key] = value.replace(/^["']|["']$/g, "");
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// Close any pending array
|
|
80
|
+
if (currentArray !== null) {
|
|
81
|
+
meta[currentKey] = currentArray;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return { meta, body: match[2].trim() };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ---------------------------------------------------------------------------
|
|
88
|
+
// Field-mapper tables
|
|
89
|
+
// ---------------------------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The non-frontmatter inputs a field mapper may read: the resolved name (which
|
|
93
|
+
* comes from the file/validator, not always from `meta`) and the markdown body.
|
|
94
|
+
* Shared by both tiers' tables — presets read `name`/`body`, templates too.
|
|
95
|
+
*/
|
|
96
|
+
export interface FrontmatterMapContext {
|
|
97
|
+
name: string;
|
|
98
|
+
body: string;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* One row of a tier's field-mapper table: frontmatter plus context in, ONE
|
|
103
|
+
* record field out. `R` is the field's declared type, so a table declared as
|
|
104
|
+
* `{[K in keyof T]: FrontmatterFieldMapper<T[K]>}` makes a mapper that returns
|
|
105
|
+
* the wrong type a compile error at the row, not a silent cast at the assembly.
|
|
106
|
+
*/
|
|
107
|
+
export type FrontmatterFieldMapper<R> = (
|
|
108
|
+
meta: Record<string, unknown>,
|
|
109
|
+
ctx: FrontmatterMapContext,
|
|
110
|
+
) => R;
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Build a record from a field-mapper table and one parsed frontmatter pair.
|
|
114
|
+
* Single-source for both tiers (`presetFromFrontmatter`, `templateFromFrontmatter`),
|
|
115
|
+
* which had byte-identical assemblies.
|
|
116
|
+
*
|
|
117
|
+
* The `as unknown as R` bridge is the compensating cast: `Object.fromEntries`
|
|
118
|
+
* hands back `{ [k: string]: unknown }`, and the record types are interfaces
|
|
119
|
+
* (no implicit index signature), so no narrower assertion compiles. Its safety
|
|
120
|
+
* is the table it is handed: `satisfies { [K in keyof T]: … }` pins the key set
|
|
121
|
+
* to exactly the record's fields, and the per-key return type pins each value.
|
|
122
|
+
*/
|
|
123
|
+
export function applyFrontmatterMappers<R>(
|
|
124
|
+
mappers: Record<string, FrontmatterFieldMapper<unknown>>,
|
|
125
|
+
meta: Record<string, unknown>,
|
|
126
|
+
ctx: FrontmatterMapContext,
|
|
127
|
+
): R {
|
|
128
|
+
return Object.fromEntries(
|
|
129
|
+
Object.entries(mappers).map(([field, mapper]) => [field, mapper(meta, ctx)]),
|
|
130
|
+
) as unknown as R;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
// Tier loading
|
|
135
|
+
// ---------------------------------------------------------------------------
|
|
136
|
+
|
|
137
|
+
/** Log wording for one tier — the only part of the walk that is family-specific. */
|
|
138
|
+
export interface LoaderMessages {
|
|
139
|
+
/** Warn message for a file skipped by `validate` or `bodyError`. */
|
|
140
|
+
invalid: string;
|
|
141
|
+
/** Warn message for a file that threw while being read, parsed, or mapped. */
|
|
142
|
+
readFailed: string;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Everything one tier needs: where to scan, how to validate, how to build the record. */
|
|
146
|
+
export interface MarkdownTierSpec<T> {
|
|
147
|
+
/** Directories to scan, in precedence order (first occurrence of a name wins). */
|
|
148
|
+
dirs: readonly string[];
|
|
149
|
+
/** Frontmatter validator; a non-empty result skips the file (one warn per error). */
|
|
150
|
+
validate: (meta: Record<string, unknown>, fileName: string) => string[];
|
|
151
|
+
/** Family-specific record construction from validated frontmatter, body, and name. */
|
|
152
|
+
map: (meta: Record<string, unknown>, body: string, name: string) => T;
|
|
153
|
+
/** Log wording for this tier. */
|
|
154
|
+
messages: LoaderMessages;
|
|
155
|
+
/** Logger for the warn/info lines; omitted → silent. */
|
|
156
|
+
log?: Logger;
|
|
157
|
+
/** Skip a second occurrence of an already-seen name (PROJECT > USER precedence). */
|
|
158
|
+
dedupeByName?: boolean;
|
|
159
|
+
/** Extra skip check after `validate`; a returned error string warns and skips. */
|
|
160
|
+
bodyError?: (meta: Record<string, unknown>, body: string) => string | null;
|
|
161
|
+
/** Called when a directory cannot be read (missing dir). Custom tiers stay silent. */
|
|
162
|
+
onMissingDir?: (dir: string) => void;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Load every record of one markdown tier: walk `spec.dirs` in order, and for
|
|
167
|
+
* each `.md` file parse frontmatter, validate, check the optional body guard,
|
|
168
|
+
* dedupe by name when asked, then map into the family-specific record.
|
|
169
|
+
*
|
|
170
|
+
* Never throws for a bad file or a missing directory — those are warnings (or
|
|
171
|
+
* silence), matching the four hand-written loaders this replaces.
|
|
172
|
+
*/
|
|
173
|
+
export function loadMarkdownRecords<T>(spec: MarkdownTierSpec<T>): T[] {
|
|
174
|
+
const records: T[] = [];
|
|
175
|
+
const seenNames = new Set<string>();
|
|
176
|
+
|
|
177
|
+
for (const dir of spec.dirs) {
|
|
178
|
+
let files: string[];
|
|
179
|
+
try {
|
|
180
|
+
files = fs.readdirSync(dir);
|
|
181
|
+
} catch {
|
|
182
|
+
// Directory doesn't exist or can't be read — no records from this tier.
|
|
183
|
+
spec.onMissingDir?.(dir);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
for (const file of files) {
|
|
188
|
+
if (!file.endsWith(".md")) continue;
|
|
189
|
+
|
|
190
|
+
try {
|
|
191
|
+
const content = fs.readFileSync(path.join(dir, file), "utf-8");
|
|
192
|
+
const { meta, body } = parseFrontmatter(content);
|
|
193
|
+
|
|
194
|
+
const errors = spec.validate(meta, file);
|
|
195
|
+
if (errors.length > 0) {
|
|
196
|
+
for (const err of errors) {
|
|
197
|
+
spec.log?.warn(spec.messages.invalid, { file, error: err });
|
|
198
|
+
}
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const bodyError = spec.bodyError?.(meta, body) ?? null;
|
|
203
|
+
if (bodyError !== null) {
|
|
204
|
+
spec.log?.warn(spec.messages.invalid, { file, error: bodyError });
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Both validators reject a missing/non-string name, so it is a string here.
|
|
209
|
+
const name = meta.name as string;
|
|
210
|
+
if (spec.dedupeByName) {
|
|
211
|
+
// First occurrence (highest-precedence dir) wins; later ones are skipped.
|
|
212
|
+
if (seenNames.has(name)) continue;
|
|
213
|
+
seenNames.add(name);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
records.push(spec.map(meta, body, name));
|
|
217
|
+
} catch (err) {
|
|
218
|
+
spec.log?.warn(spec.messages.readFailed, { file, error: (err as Error).message });
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
return records;
|
|
224
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// Purpose: The batch-mode prologue (cost → depth → resolve → targets → preflight → H1), one call per foreground batch handler.
|
|
2
|
+
/**
|
|
3
|
+
* Batch-mode prologue (issue #379, the D1 cluster).
|
|
4
|
+
*
|
|
5
|
+
* `runChainMode`, `runParallelMode` and `runGraphMode` open with the SAME six
|
|
6
|
+
* gates in the SAME order:
|
|
7
|
+
*
|
|
8
|
+
* [graph only: DAG validation] → cost → depth → resolve params
|
|
9
|
+
* → mode-level target validation → pre-flight → H1
|
|
10
|
+
*
|
|
11
|
+
* That sequence used to be copied into each handler (~110 lines × 3). This
|
|
12
|
+
* module owns it once. The per-mode differences are parameters, not forks:
|
|
13
|
+
*
|
|
14
|
+
* - `label` — the warning/log lead: "Chain" → "Chain delegation" (cost
|
|
15
|
+
* and depth logs), "Chain pre-flight check failed", "Chain
|
|
16
|
+
* pre-task validation warnings/failed";
|
|
17
|
+
* - `units` — the cost estimate's multiplier (IN2: the declared unit
|
|
18
|
+
* count for chain/parallel/graph — never a wave count);
|
|
19
|
+
* - `beforeCost` — graph's DAG validation, the ONE hook that must run before
|
|
20
|
+
* the cost gate (IN1 boundary: a malformed graph is rejected
|
|
21
|
+
* before the session spends anything).
|
|
22
|
+
*
|
|
23
|
+
* Deliberately NOT here:
|
|
24
|
+
*
|
|
25
|
+
* - the per-unit pre-pass (`validateUnitPrePass`, prelude.ts) — each handler
|
|
26
|
+
* CALLS it at its own position, because that position is part of the
|
|
27
|
+
* contract (IN8: chain/parallel before model resolution, graph after the
|
|
28
|
+
* circuit check and the topological sort);
|
|
29
|
+
* - the model tail (`resolveModeModel`, prelude.ts) — same reason: graph
|
|
30
|
+
* resolves the model before its per-node pass, chain/parallel after;
|
|
31
|
+
* - the single foreground path and the two background paths — they are a
|
|
32
|
+
* different gate sequence (design note §2.1; IN1/IN3/IN6), so forcing
|
|
33
|
+
* them through this skeleton would normalise their order.
|
|
34
|
+
*
|
|
35
|
+
* The gate functions are imported from `prelude.ts` (not re-implemented), so
|
|
36
|
+
* the existing suite's call-through wrappers still observe each gate at the
|
|
37
|
+
* same point in the sequence.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
41
|
+
import type { ToolResult } from "./types";
|
|
42
|
+
import type { SessionState } from "./state";
|
|
43
|
+
import type { Logger } from "./logging";
|
|
44
|
+
import { resolveSubagentParams, type ResolveInputParams } from "./params";
|
|
45
|
+
import { getCurrentDepth } from "./sanitize";
|
|
46
|
+
import { preflightCheck } from "./preflight";
|
|
47
|
+
import {
|
|
48
|
+
depthLimitRejection,
|
|
49
|
+
gateSessionCost,
|
|
50
|
+
rejection,
|
|
51
|
+
runPreTaskValidation,
|
|
52
|
+
validateDelegationTargets,
|
|
53
|
+
} from "./prelude";
|
|
54
|
+
|
|
55
|
+
/** The params object the shared resolver consumes (`ResolveInputParams`,
|
|
56
|
+
* params.ts) — the same type the background and single paths pass. */
|
|
57
|
+
export interface ModePrologueInput {
|
|
58
|
+
/**
|
|
59
|
+
* `noJev` is carried alongside the resolution inputs rather than inside
|
|
60
|
+
* `ResolveInputParams`: resolution never reads it, but the mode-level H1
|
|
61
|
+
* gate forwards it as the call's stated bypass (issue #412).
|
|
62
|
+
*/
|
|
63
|
+
params: ResolveInputParams & { noJev?: string };
|
|
64
|
+
state: SessionState;
|
|
65
|
+
ctx: ExtensionContext;
|
|
66
|
+
log: Logger;
|
|
67
|
+
/** Mode name, used as the warning/log lead: "Chain" | "Parallel" | "Graph". */
|
|
68
|
+
label: string;
|
|
69
|
+
/** Units this dispatch would spawn — the cost estimate's multiplier (IN2). */
|
|
70
|
+
units: number;
|
|
71
|
+
/**
|
|
72
|
+
* Mode-specific validation that MUST run before the cost gate. Graph uses
|
|
73
|
+
* it for `validateGraph`; chain/parallel pass nothing. Returns the
|
|
74
|
+
* rejection to surface, or `undefined` when the mode's precondition holds.
|
|
75
|
+
*/
|
|
76
|
+
beforeCost?: () => ToolResult<undefined> | undefined;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The resolved dispatch the handlers build on (IN4: resolved exactly once). */
|
|
80
|
+
export type ModeGlobalParams = ReturnType<typeof resolveSubagentParams>;
|
|
81
|
+
|
|
82
|
+
export type ModePrologueOutcome =
|
|
83
|
+
| { ok: false; error: ToolResult<undefined> }
|
|
84
|
+
| {
|
|
85
|
+
ok: true;
|
|
86
|
+
globalParams: ModeGlobalParams;
|
|
87
|
+
resolvedCwd: string;
|
|
88
|
+
/** The depth the depth gate measured — every unit spawns at `+ 1`. */
|
|
89
|
+
currentDepth: number;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Run the batch-mode prologue. Returns the resolved params + validated cwd on
|
|
94
|
+
* success, or the first gate's rejection in the verbatim wording the suites
|
|
95
|
+
* pin. Gate order is the invariant (IN1/IN3/IN4/IN5/IN6/IN7): `beforeCost` →
|
|
96
|
+
* cost → depth → resolve → targets → preflight → H1.
|
|
97
|
+
*/
|
|
98
|
+
export function runModePrologue(input: ModePrologueInput): ModePrologueOutcome {
|
|
99
|
+
const { params, state, ctx, log, label, units, beforeCost } = input;
|
|
100
|
+
|
|
101
|
+
// 0. Mode precondition (graph: DAG validation) — before the cost gate.
|
|
102
|
+
const preCost = beforeCost?.();
|
|
103
|
+
if (preCost) return { ok: false, error: preCost };
|
|
104
|
+
|
|
105
|
+
// 1. Session cost gate (R5) — the first gate of every batch mode.
|
|
106
|
+
const costError = gateSessionCost({
|
|
107
|
+
state,
|
|
108
|
+
ctx,
|
|
109
|
+
log,
|
|
110
|
+
units,
|
|
111
|
+
label: `${label} delegation`,
|
|
112
|
+
});
|
|
113
|
+
if (costError) return { ok: false, error: costError };
|
|
114
|
+
|
|
115
|
+
// 2. Recursion depth gate (IN3) — absent from the background paths by
|
|
116
|
+
// design (they spawn in-process SDK sessions, which do not stamp the
|
|
117
|
+
// depth env key); pinning the asymmetry, not "fixing" it here.
|
|
118
|
+
const currentDepth = getCurrentDepth();
|
|
119
|
+
if (currentDepth >= state.config.maxSubagentDepth) {
|
|
120
|
+
log.warn(`${label} delegation rejected: max depth reached`, {
|
|
121
|
+
currentDepth,
|
|
122
|
+
maxDepth: state.config.maxSubagentDepth,
|
|
123
|
+
});
|
|
124
|
+
return {
|
|
125
|
+
ok: false,
|
|
126
|
+
error: depthLimitRejection(currentDepth, state.config.maxSubagentDepth),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// 3. Resolve the global params exactly once (IN4).
|
|
131
|
+
const globalParams = resolveSubagentParams(params, state, ctx, log);
|
|
132
|
+
|
|
133
|
+
// 4. Mode-level target validation — cwd only. Every unit's own outputFile
|
|
134
|
+
// is validated by the per-unit pre-pass (IN5); the message bytes are
|
|
135
|
+
// identical to the inline spelling this replaced.
|
|
136
|
+
const targets = validateDelegationTargets({ ctx, effectiveCwd: globalParams.effectiveCwd });
|
|
137
|
+
if (!targets.ok) return { ok: false, error: targets.error };
|
|
138
|
+
|
|
139
|
+
// 5. Pre-flight checks — fail fast before consuming resources (IN6).
|
|
140
|
+
const pfResult = preflightCheck(targets.cwd);
|
|
141
|
+
if (!pfResult.ok) {
|
|
142
|
+
log.warn(`${label} pre-flight check failed`, { error: pfResult.error });
|
|
143
|
+
return { ok: false, error: rejection(`Pre-flight check failed: ${pfResult.error}`) };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// 6. H1 at mode entry — mode-level params only, never prefixed and never
|
|
147
|
+
// carrying `force` (IN7). Warnings are logged, not surfaced: the result
|
|
148
|
+
// warnings come from the per-unit passes.
|
|
149
|
+
const preTask = runPreTaskValidation({
|
|
150
|
+
log,
|
|
151
|
+
label,
|
|
152
|
+
preTask: {
|
|
153
|
+
task: globalParams.task,
|
|
154
|
+
toolOptions: globalParams.toolOptions,
|
|
155
|
+
thinkingLevel: globalParams.thinkingLevel,
|
|
156
|
+
gitMode: globalParams.resolvedGitMode,
|
|
157
|
+
outputFile: globalParams.outputFile,
|
|
158
|
+
// Issue #412: the project-local Jev-line check keys on the DISPATCH
|
|
159
|
+
// cwd (the project whose manifest opts in), and `noJev` is the
|
|
160
|
+
// call-level stated bypass — the mode-level task text is the caller's
|
|
161
|
+
// own, so it is checked and bypassable exactly like a single task.
|
|
162
|
+
cwd: targets.cwd,
|
|
163
|
+
noJev: params.noJev,
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
if (preTask.error) return { ok: false, error: preTask.error };
|
|
167
|
+
|
|
168
|
+
return { ok: true, globalParams, resolvedCwd: targets.cwd, currentDepth };
|
|
169
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Purpose:
|
|
1
|
+
// Purpose: Model identity + auth-aware availability: parse a provider/model-id string and check catalog presence plus configured provider auth.
|
|
2
2
|
/**
|
|
3
3
|
* Auth-aware model availability check (issue #4).
|
|
4
4
|
*
|
|
@@ -23,6 +23,18 @@ export interface ModelLike {
|
|
|
23
23
|
id: string;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
+
/**
|
|
27
|
+
* Parse a `provider/model-id` string. Returns null on anything that is not
|
|
28
|
+
* exactly one non-empty provider and one non-empty id (no provider-only or
|
|
29
|
+
* trailing-slash values).
|
|
30
|
+
*/
|
|
31
|
+
export function parseModelString(s: string): { provider: string; id: string } | null {
|
|
32
|
+
const trimmed = s.trim();
|
|
33
|
+
const idx = trimmed.indexOf("/");
|
|
34
|
+
if (idx <= 0 || idx === trimmed.length - 1) return null;
|
|
35
|
+
return { provider: trimmed.slice(0, idx), id: trimmed.slice(idx + 1) };
|
|
36
|
+
}
|
|
37
|
+
|
|
26
38
|
export interface ProviderAuthStatusLike {
|
|
27
39
|
configured?: boolean;
|
|
28
40
|
source?: string;
|