brl-subagent 2.5.2 → 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 +14 -11
- package/README.md +30 -6
- package/package.json +8 -5
- package/src/concurrency.ts +156 -44
- package/src/dispatch-line.ts +144 -0
- package/src/history.ts +13 -1
- package/src/index.ts +642 -743
- package/src/loader.ts +178 -0
- package/src/mode-prologue.ts +169 -0
- package/src/model-availability.ts +13 -1
- package/src/params.ts +252 -67
- 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 +69 -51
- package/src/session-manager.ts +790 -91
- package/src/state.ts +29 -4
- 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-format.ts +382 -4
- package/src/tui.ts +997 -867
- package/src/types.ts +54 -25
- package/src/validate.ts +41 -0
package/src/params.ts
CHANGED
|
@@ -21,6 +21,8 @@ import type {
|
|
|
21
21
|
ApprovalMode,
|
|
22
22
|
SubagentToolOptions,
|
|
23
23
|
ResolvedParams,
|
|
24
|
+
SnapshotParams,
|
|
25
|
+
DelegateTaskParams,
|
|
24
26
|
} from "./types";
|
|
25
27
|
import { resolveThinkingLevel } from "./types";
|
|
26
28
|
import { getAllPresets, getPreset } from "./presets";
|
|
@@ -50,7 +52,7 @@ export const KNOWN_DELEGATE_KEYS = new Set([
|
|
|
50
52
|
"outputFile", "label", "model", "timeout", "cwd", "tools",
|
|
51
53
|
"excludeTools", "noBuiltinTools", "preset", "template", "params",
|
|
52
54
|
"retryRunId", "gitMode", "retryOnTimeout", "approvalMode", "background",
|
|
53
|
-
"priority", "chain", "tasks", "graph", "force",
|
|
55
|
+
"priority", "chain", "tasks", "graph", "force", "noJev",
|
|
54
56
|
] as const);
|
|
55
57
|
|
|
56
58
|
/**
|
|
@@ -82,25 +84,12 @@ export function findUnknownParams(
|
|
|
82
84
|
* resolveRetryParams rebuilds a fresh literal and a key missing here is both
|
|
83
85
|
* unrestored AND discarded when passed explicitly on a retry call. Records
|
|
84
86
|
* written before this change simply lack the keys (additive, undefined-safe).
|
|
87
|
+
*
|
|
88
|
+
* Issue #381 (audit D5): the 16-field shape is declared once, as
|
|
89
|
+
* `SnapshotParams` in types.ts, and shared with `SubagentRun["originalParams"]`;
|
|
90
|
+
* this signature previously carried its own copy of the literal.
|
|
85
91
|
*/
|
|
86
|
-
export function snapshotOriginalParams(params: {
|
|
87
|
-
systemPrompt?: string;
|
|
88
|
-
inheritSystemPrompt?: boolean;
|
|
89
|
-
model?: string;
|
|
90
|
-
thinkingLevel?: string;
|
|
91
|
-
priority?: string;
|
|
92
|
-
outputFile?: string;
|
|
93
|
-
timeout?: number;
|
|
94
|
-
cwd?: string;
|
|
95
|
-
tools?: string[];
|
|
96
|
-
excludeTools?: string[];
|
|
97
|
-
noBuiltinTools?: boolean;
|
|
98
|
-
preset?: string;
|
|
99
|
-
background?: boolean;
|
|
100
|
-
gitMode?: string;
|
|
101
|
-
approvalMode?: string;
|
|
102
|
-
force?: boolean;
|
|
103
|
-
}): Record<string, unknown> {
|
|
92
|
+
export function snapshotOriginalParams(params: SnapshotParams): Record<string, unknown> {
|
|
104
93
|
return {
|
|
105
94
|
systemPrompt: params.systemPrompt,
|
|
106
95
|
inheritSystemPrompt: params.inheritSystemPrompt,
|
|
@@ -121,30 +110,235 @@ export function snapshotOriginalParams(params: {
|
|
|
121
110
|
};
|
|
122
111
|
}
|
|
123
112
|
|
|
113
|
+
// ---------------------------------------------------------------------------
|
|
114
|
+
// Effective approval mode + the background default (issue #361)
|
|
115
|
+
// ---------------------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The approval mode that would actually apply to a child dispatched with these
|
|
119
|
+
* params: per-call param > configured default.
|
|
120
|
+
*
|
|
121
|
+
* Single source of truth (issue #361): `resolveSubagentParams` resolves the
|
|
122
|
+
* child's mode through this function, and the dispatch chokepoint uses it to
|
|
123
|
+
* pick the background default, so the mode that decides "can this run
|
|
124
|
+
* unattended?" is always the mode the child runs with. Presets declare no
|
|
125
|
+
* `approvalMode` field today (see SubagentPreset), so there is no preset tier;
|
|
126
|
+
* should one be added, it would slot in between the call param and the
|
|
127
|
+
* configured default.
|
|
128
|
+
*/
|
|
129
|
+
export function resolveEffectiveApprovalMode(
|
|
130
|
+
approvalMode: string | undefined,
|
|
131
|
+
state: Pick<SessionState, "config">,
|
|
132
|
+
): ApprovalMode {
|
|
133
|
+
return approvalMode === "auto" || approvalMode === "writes" || approvalMode === "always"
|
|
134
|
+
? approvalMode
|
|
135
|
+
: state.config.approvalMode;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Dispatch shapes that can select a `background` default. `parallel` is the
|
|
140
|
+
* `tasks` fan-out; `chain`/`graph` are batch modes that always block.
|
|
141
|
+
*/
|
|
142
|
+
export type DispatchShape = "single" | "parallel" | "chain" | "graph";
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Whether an EXPLICIT `background` value must be rejected for the dispatch
|
|
146
|
+
* shape. Only `chain`/`graph` reject, and only an explicit `true` — an omitted
|
|
147
|
+
* `background` (`undefined`) is not an explicit request and falls through to
|
|
148
|
+
* `defaultBackgroundFor`, while an explicit `false` is always honoured. Pure
|
|
149
|
+
* and separate from dispatch so the guard's strictness and its position ahead
|
|
150
|
+
* of default resolution can be pinned independently (issue #361 review).
|
|
151
|
+
*/
|
|
152
|
+
export function shouldRejectBackgroundForBatch(
|
|
153
|
+
shape: DispatchShape,
|
|
154
|
+
explicit: boolean | undefined,
|
|
155
|
+
): boolean {
|
|
156
|
+
return explicit === true && (shape === "chain" || shape === "graph");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Issue #361: the CONDITIONAL default for `background` when the caller omits
|
|
161
|
+
* it. Background wins only where it cannot weaken a gate:
|
|
162
|
+
*
|
|
163
|
+
* - `chain`/`graph` stay foreground — they block by definition and an
|
|
164
|
+
* explicit `background: true` is still rejected at dispatch.
|
|
165
|
+
* - an effective approval mode that needs the interactive dialog
|
|
166
|
+
* (`always`) or gates on writes (`writes`) stays foreground — a
|
|
167
|
+
* background run has no dialog, so defaulting there would either break
|
|
168
|
+
* the run or silently auto-approve diffs the user asked to review.
|
|
169
|
+
* - everything else (single task, `tasks` fan-out, effective `auto`) is
|
|
170
|
+
* background: the tool returns an agent id immediately and the conductor
|
|
171
|
+
* is woken on terminal state.
|
|
172
|
+
*
|
|
173
|
+
* Explicit `true`/`false` always wins — callers spread `params.background ??
|
|
174
|
+
* defaultBackgroundFor(...)`.
|
|
175
|
+
*/
|
|
176
|
+
export function defaultBackgroundFor(
|
|
177
|
+
shape: DispatchShape,
|
|
178
|
+
effectiveApprovalMode: ApprovalMode,
|
|
179
|
+
): boolean {
|
|
180
|
+
if (shape === "chain" || shape === "graph") return false;
|
|
181
|
+
return effectiveApprovalMode === "auto";
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// ---------------------------------------------------------------------------
|
|
185
|
+
// The thinking-level dispatch-shape pre-flight (issue #412, rule 2)
|
|
186
|
+
// ---------------------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The notice the dispatch emits when it auto-switches the shape. The text
|
|
190
|
+
* states the TRUE tool fact (why the shape matters), because that is the only
|
|
191
|
+
* thing that makes the switch acceptable to the conductor that asked for
|
|
192
|
+
* foreground: a foreground run has no transcript to resume, so a timeout there
|
|
193
|
+
* loses the work, while a background run keeps its session and is retried on a
|
|
194
|
+
* transport error.
|
|
195
|
+
*/
|
|
196
|
+
export const THINKING_SWITCH_NOTICE =
|
|
197
|
+
"Dispatch pre-flight (no deadline means the durable path): a high/xhigh-thinking run was dispatched FOREGROUND with an explicit timeout. " +
|
|
198
|
+
"The explicit timeout was dropped — foreground runs persist nothing, so a timeout there loses the run's whole context, while the 30-minute background deadline applies instead. " +
|
|
199
|
+
"The run is now background; the conductor is woken on terminal state. Pass force: true to keep it foreground (state the reason in the task text).";
|
|
200
|
+
|
|
201
|
+
/** The pre-flight's verdict for one dispatch. */
|
|
202
|
+
export type ThinkingDispatchSwitch = "switch" | "forced" | "none";
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Issue #412 (rule 2: "no deadline ⇒ durable path") — should the pre-flight
|
|
206
|
+
* change this dispatch's shape?
|
|
207
|
+
*
|
|
208
|
+
* The 2026-10-31 incident: a plan critique ran foreground under a 15-minute
|
|
209
|
+
* timeout, was killed at ~14 minutes ("almost done"), and lost everything —
|
|
210
|
+
* the background re-run then cost another 17 minutes. The decision was
|
|
211
|
+
* conductor discretion; this predicate makes the durable shape the only one
|
|
212
|
+
* for the runs where losing the context is expensive:
|
|
213
|
+
*
|
|
214
|
+
* processChecks (the project opted into OUR process — issue #415)
|
|
215
|
+
* + thinkingLevel high|xhigh
|
|
216
|
+
* + background EXPLICITLY false (the caller asked for foreground)
|
|
217
|
+
* + an explicit timeout (the deadline that would kill it)
|
|
218
|
+
* → switch to background and drop the timeout.
|
|
219
|
+
*
|
|
220
|
+
* Deliberately exempt:
|
|
221
|
+
* - `processChecks: false` — this is a CONDUCTOR decision rule, not product
|
|
222
|
+
* behavior. A user's explicit foreground timeout is usually a budget cap,
|
|
223
|
+
* so overriding it could triple time and cost against their instruction.
|
|
224
|
+
* The umbrella flag (ADR 0019) is what makes the switch opt-in; the
|
|
225
|
+
* predicate has no global mode.
|
|
226
|
+
* - `chain`/`graph` — they block by definition and `background: true` is
|
|
227
|
+
* rejected at dispatch; the decision cannot apply to them.
|
|
228
|
+
* - an omitted `background` — the #361 default already decided, and it knows
|
|
229
|
+
* about approval modes (a `writes`/`always` run must stay in front of the
|
|
230
|
+
* user); second-guessing it here would silently move a gated run into a
|
|
231
|
+
* context with no approval dialog.
|
|
232
|
+
* - no explicit timeout — there is no deadline to lose; the background
|
|
233
|
+
* default is a deadline too, so switching would not make the run safer.
|
|
234
|
+
* - `force: true` — the override, reported as `forced` (not `none`) so the
|
|
235
|
+
* caller can tell "kept foreground by request" from "never applied".
|
|
236
|
+
* `force` carries no reason field (ADR 0007): the dispatch text is the
|
|
237
|
+
* reason.
|
|
238
|
+
*
|
|
239
|
+
* `thinkingLevel` is the DECLARED level (per-call, else the named preset's),
|
|
240
|
+
* not the capped one: `maxThinkingLevel` defaults to `off` for an unconfigured
|
|
241
|
+
* session, so applying the cap here would disable the pre-flight exactly where
|
|
242
|
+
* nobody configured anything — the drift this rule exists to remove.
|
|
243
|
+
*/
|
|
244
|
+
export function resolveThinkingDispatchSwitch(input: {
|
|
245
|
+
processChecks: boolean;
|
|
246
|
+
thinkingLevel: ThinkingLevel | undefined;
|
|
247
|
+
explicitBackground: boolean | undefined;
|
|
248
|
+
timeout: number | undefined;
|
|
249
|
+
force: boolean | undefined;
|
|
250
|
+
shape: DispatchShape;
|
|
251
|
+
}): ThinkingDispatchSwitch {
|
|
252
|
+
if (!input.processChecks) return "none";
|
|
253
|
+
if (input.shape === "chain" || input.shape === "graph") return "none";
|
|
254
|
+
if (input.thinkingLevel !== "high" && input.thinkingLevel !== "xhigh") return "none";
|
|
255
|
+
if (input.explicitBackground !== false) return "none";
|
|
256
|
+
if (input.timeout === undefined) return "none";
|
|
257
|
+
return input.force === true ? "forced" : "switch";
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* The resolver's input: the dispatch-param fields resolution actually reads,
|
|
262
|
+
* derived from the registered schema (issue #379) instead of re-spelled here.
|
|
263
|
+
*
|
|
264
|
+
* `task` is OPTIONAL because the schema says so (`chain`/`tasks`/`graph`
|
|
265
|
+
* dispatches carry no mode-level task) — batch call sites therefore pass the
|
|
266
|
+
* registered params object through unchanged. The four `params as {…}`
|
|
267
|
+
* assertions this replaces existed only to claim a `task` the schema never
|
|
268
|
+
* required. `resolveSubagentParams` defaults it with `?? ""`, which every
|
|
269
|
+
* reader of the field treats like `undefined` (see the `task` line below).
|
|
270
|
+
*
|
|
271
|
+
* Compile-time coverage of this key list is ratcheted in index.ts
|
|
272
|
+
* (`_ResolveInputCoverage`) — a schema field the resolver forgets is silent at
|
|
273
|
+
* runtime, so only the compiler can catch it.
|
|
274
|
+
*/
|
|
275
|
+
export type ResolveInputParams = Pick<
|
|
276
|
+
DelegateTaskParams,
|
|
277
|
+
| "task"
|
|
278
|
+
| "label"
|
|
279
|
+
| "preset"
|
|
280
|
+
| "systemPrompt"
|
|
281
|
+
| "inheritSystemPrompt"
|
|
282
|
+
| "thinkingLevel"
|
|
283
|
+
| "outputFile"
|
|
284
|
+
| "timeout"
|
|
285
|
+
| "cwd"
|
|
286
|
+
| "tools"
|
|
287
|
+
| "excludeTools"
|
|
288
|
+
| "noBuiltinTools"
|
|
289
|
+
| "gitMode"
|
|
290
|
+
| "approvalMode"
|
|
291
|
+
| "template"
|
|
292
|
+
// Capability-block override: carried here so the validation call sites
|
|
293
|
+
// (which receive the resolved params) can forward it to validatePreTask.
|
|
294
|
+
// Resolution itself ignores it.
|
|
295
|
+
| "force"
|
|
296
|
+
>;
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Issue #412: resolve the preset a dispatch will actually run with, INCLUDING
|
|
300
|
+
* the auto-route decision. Extracted from `resolveSubagentParams` so the
|
|
301
|
+
* dispatch pre-flight can ask "what thinking level will this run have?"
|
|
302
|
+
* without re-spelling the routing condition — a second copy of that condition
|
|
303
|
+
* is exactly the silent drift `_ResolveInputCoverage` and the KNOWN_DELEGATE_KEYS
|
|
304
|
+
* ratchet exist to prevent.
|
|
305
|
+
*
|
|
306
|
+
* `name` is what the caller asked for (or the routed match); `preset` is the
|
|
307
|
+
* resolved record, `undefined` when neither exists. `autoRouted` distinguishes
|
|
308
|
+
* a routed match from an explicit request (the caller logs the evidence).
|
|
309
|
+
*/
|
|
310
|
+
export function resolveDispatchPreset(
|
|
311
|
+
params: Pick<
|
|
312
|
+
ResolveInputParams,
|
|
313
|
+
"preset" | "template" | "tools" | "excludeTools" | "noBuiltinTools" | "task"
|
|
314
|
+
>,
|
|
315
|
+
state: Pick<SessionState, "builtinPresets" | "customPresets">,
|
|
316
|
+
): { name?: string; preset?: SubagentPreset; autoRouted: boolean; keyword?: string } {
|
|
317
|
+
if (params.preset) {
|
|
318
|
+
return { name: params.preset, preset: getPreset(params.preset, state.builtinPresets, state.customPresets), autoRouted: false };
|
|
319
|
+
}
|
|
320
|
+
// E2: an explicit template or tool preference is intent that must win over
|
|
321
|
+
// keyword routing (issue #57) — unchanged from the resolver's rule.
|
|
322
|
+
const hasExplicitToolPreference =
|
|
323
|
+
params.tools !== undefined ||
|
|
324
|
+
params.excludeTools !== undefined ||
|
|
325
|
+
params.noBuiltinTools !== undefined;
|
|
326
|
+
if (params.template || hasExplicitToolPreference) return { autoRouted: false };
|
|
327
|
+
const matched = classifyTask(
|
|
328
|
+
params.task ?? "",
|
|
329
|
+
getAllPresets(state.builtinPresets, state.customPresets),
|
|
330
|
+
);
|
|
331
|
+
if (!matched) return { autoRouted: false };
|
|
332
|
+
return {
|
|
333
|
+
name: matched.preset,
|
|
334
|
+
preset: getPreset(matched.preset, state.builtinPresets, state.customPresets),
|
|
335
|
+
autoRouted: true,
|
|
336
|
+
keyword: matched.keyword,
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
124
340
|
export function resolveSubagentParams(
|
|
125
|
-
params:
|
|
126
|
-
task: string;
|
|
127
|
-
label?: string;
|
|
128
|
-
preset?: string;
|
|
129
|
-
systemPrompt?: string;
|
|
130
|
-
inheritSystemPrompt?: boolean;
|
|
131
|
-
thinkingLevel?: string;
|
|
132
|
-
outputFile?: string;
|
|
133
|
-
timeout?: number;
|
|
134
|
-
cwd?: string;
|
|
135
|
-
tools?: string[];
|
|
136
|
-
excludeTools?: string[];
|
|
137
|
-
noBuiltinTools?: boolean;
|
|
138
|
-
gitMode?: string;
|
|
139
|
-
approvalMode?: string;
|
|
140
|
-
template?: string;
|
|
141
|
-
/**
|
|
142
|
-
* Capability-block override: carried here so the validation call sites
|
|
143
|
-
* (which receive the resolved params) can forward it to validatePreTask.
|
|
144
|
-
* Resolution itself ignores it.
|
|
145
|
-
*/
|
|
146
|
-
force?: boolean;
|
|
147
|
-
},
|
|
341
|
+
params: ResolveInputParams,
|
|
148
342
|
state: SessionState,
|
|
149
343
|
ctx: ExtensionContext,
|
|
150
344
|
log: Logger,
|
|
@@ -158,25 +352,16 @@ export function resolveSubagentParams(
|
|
|
158
352
|
autoRouteKeyword?: string;
|
|
159
353
|
} {
|
|
160
354
|
// E2: Auto-route to best preset only when the conductor expressed NO
|
|
161
|
-
// explicit preference — an explicit preset, template, or tool
|
|
162
|
-
//
|
|
163
|
-
//
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
if (!resolvedPreset && !params.template && !hasExplicitToolPreference) {
|
|
172
|
-
const allPresets = getAllPresets(state.builtinPresets, state.customPresets);
|
|
173
|
-
const matched = classifyTask(params.task, allPresets);
|
|
174
|
-
if (matched) {
|
|
175
|
-
resolvedPreset = matched.preset;
|
|
176
|
-
wasAutoRouted = true;
|
|
177
|
-
routeKeyword = matched.keyword;
|
|
178
|
-
log.info("Auto-routed task to preset", { preset: matched.preset, keyword: matched.keyword });
|
|
179
|
-
}
|
|
355
|
+
// explicit preference — an explicit preset, template, or tool parameters
|
|
356
|
+
// (tools/excludeTools/noBuiltinTools) all count as intent that must win over
|
|
357
|
+
// keyword-based routing (issue #57). The rule lives in `resolveDispatchPreset`
|
|
358
|
+
// so the dispatch pre-flight (#412) resolves the SAME preset this merge does.
|
|
359
|
+
const routed = resolveDispatchPreset(params, state);
|
|
360
|
+
const resolvedPreset = routed.name;
|
|
361
|
+
const wasAutoRouted = routed.autoRouted;
|
|
362
|
+
const routeKeyword = routed.keyword;
|
|
363
|
+
if (wasAutoRouted) {
|
|
364
|
+
log.info("Auto-routed task to preset", { preset: resolvedPreset, keyword: routeKeyword });
|
|
180
365
|
}
|
|
181
366
|
|
|
182
367
|
const preset = resolvedPreset
|
|
@@ -212,11 +397,8 @@ export function resolveSubagentParams(
|
|
|
212
397
|
: state.config.gitMode;
|
|
213
398
|
|
|
214
399
|
// P4: Resolve approval mode: per-call param > state config > default "writes"
|
|
215
|
-
|
|
216
|
-
const resolvedApprovalMode
|
|
217
|
-
mergedApprovalMode === "auto" || mergedApprovalMode === "writes" || mergedApprovalMode === "always"
|
|
218
|
-
? mergedApprovalMode
|
|
219
|
-
: state.config.approvalMode;
|
|
400
|
+
// (shared with the dispatch chokepoint's background default, issue #361).
|
|
401
|
+
const resolvedApprovalMode = resolveEffectiveApprovalMode(params.approvalMode, state);
|
|
220
402
|
|
|
221
403
|
const thinkingLevel = resolveThinkingLevel(
|
|
222
404
|
mergedThinkingLevel,
|
|
@@ -233,7 +415,10 @@ export function resolveSubagentParams(
|
|
|
233
415
|
: undefined;
|
|
234
416
|
|
|
235
417
|
return {
|
|
236
|
-
|
|
418
|
+
// "" ≡ undefined at all three readers of the field: mergeSubTaskParams
|
|
419
|
+
// (`subTask.task || globalParams.task`), validatePreTask
|
|
420
|
+
// (`config.task || ''`) and classifyTask (`if (!task …)`).
|
|
421
|
+
task: params.task ?? "",
|
|
237
422
|
label: params.label?.trim() || undefined,
|
|
238
423
|
inheritSP: mergedInheritSP !== false,
|
|
239
424
|
customSP: mergedSystemPrompt,
|
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
|
+
}
|