opencode-model-router 1.5.0 → 1.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/CHANGELOG.md +357 -0
- package/README.md +220 -19
- package/package.json +3 -2
- package/src/commands/output.ts +342 -0
- package/src/guard/enforce.ts +14 -1
- package/src/guard/guards.ts +26 -0
- package/src/guard/store.ts +46 -3
- package/src/index.ts +429 -347
- package/src/router/agent-options.ts +127 -0
- package/src/router/catalog.ts +457 -0
- package/src/router/config.ts +335 -48
- package/src/router/idle-sweep.ts +35 -0
- package/src/router/jsonc.ts +1 -0
- package/src/router/prompts.ts +72 -0
- package/src/router/protocol.ts +1 -1
- package/src/router/sessions.ts +299 -27
- package/src/router/subagents.ts +85 -0
- package/src/telemetry/trajectory.ts +48 -1
- package/src/verify/checker.ts +47 -1
- package/src/verify/deterministic.ts +13 -5
- package/src/verify/dispatch.ts +27 -2
- package/src/verify/gate.ts +25 -1
- package/src/verify/paths.ts +29 -0
- package/src/verify/timeout.ts +93 -0
- package/src/verify/wiring.ts +267 -0
- package/tiers.json +79 -6
package/src/router/sessions.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { RouterConfig } from "./config";
|
|
2
2
|
import { fingerprintToolCall } from "../guard/fingerprint";
|
|
3
|
+
import { DEFAULT_IDLE_TTL_MS } from "./idle-sweep";
|
|
3
4
|
|
|
4
5
|
// ---------------------------------------------------------------------------
|
|
5
6
|
// Types
|
|
@@ -10,12 +11,25 @@ export type Cap = number | "none";
|
|
|
10
11
|
export interface SubagentState {
|
|
11
12
|
tierName: string;
|
|
12
13
|
cap: Cap;
|
|
14
|
+
/** Read-only tool calls in the CURRENT dispatch round (reset on resume). */
|
|
13
15
|
calls: number;
|
|
16
|
+
/** Number of dispatch rounds registered for this session (1 on first dispatch). */
|
|
17
|
+
dispatches: number;
|
|
18
|
+
/** Cumulative read-only tool calls across all dispatch rounds (never reset). */
|
|
19
|
+
totalCalls: number;
|
|
14
20
|
/** Fingerprint → call index where this fingerprint was first seen. */
|
|
15
21
|
seen: Map<string, number>;
|
|
16
22
|
trivial: boolean;
|
|
17
23
|
}
|
|
18
24
|
|
|
25
|
+
/** Outcome of a chat.message registration attempt. */
|
|
26
|
+
export interface RegisterResult {
|
|
27
|
+
/** True when the message was directed at a tracked tier agent. */
|
|
28
|
+
registered: boolean;
|
|
29
|
+
/** True when this was a same-session, same-tier re-registration (a resume). */
|
|
30
|
+
resumed: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
19
33
|
// ---------------------------------------------------------------------------
|
|
20
34
|
// Fallback caps when tiers.json has no tierCaps block.
|
|
21
35
|
// ---------------------------------------------------------------------------
|
|
@@ -27,6 +41,16 @@ export const DEFAULT_TIER_CAPS: Record<string, number> = {
|
|
|
27
41
|
heavy: 3,
|
|
28
42
|
};
|
|
29
43
|
|
|
44
|
+
/**
|
|
45
|
+
* Cumulative read-only ceiling across resumed dispatches, expressed as a
|
|
46
|
+
* multiple of the CURRENT dispatch cap. A subagent that keeps getting resumed
|
|
47
|
+
* gets a fresh per-dispatch budget every round; without a ceiling derived from
|
|
48
|
+
* the configured budget, repeated resumes are an unbounded read loop.
|
|
49
|
+
* A `CAP:none` dispatch has no per-dispatch budget to derive from, so it has
|
|
50
|
+
* no cumulative ceiling either.
|
|
51
|
+
*/
|
|
52
|
+
export const CUMULATIVE_CAP_MULTIPLIER = 3;
|
|
53
|
+
|
|
30
54
|
// ---------------------------------------------------------------------------
|
|
31
55
|
// Cap directive parser
|
|
32
56
|
// ---------------------------------------------------------------------------
|
|
@@ -99,6 +123,26 @@ export function buildCapBanner(
|
|
|
99
123
|
`[⚠ CAP WARNING: ${remaining} read-only call(s) remaining before forced return]`,
|
|
100
124
|
);
|
|
101
125
|
}
|
|
126
|
+
|
|
127
|
+
// Cumulative ceiling across resumed dispatches. Intentionally follows the
|
|
128
|
+
// CURRENT dispatch cap: a tighter resumed cap makes the ceiling stricter,
|
|
129
|
+
// so a resume can never buy more total budget than it declares.
|
|
130
|
+
//
|
|
131
|
+
// Gated on dispatches > 1: this ceiling exists to bound RESUMES. A single
|
|
132
|
+
// dispatch that blows past 3x its cap is already covered by CAP REACHED
|
|
133
|
+
// above, and firing here would both contradict "never-resumed sessions see
|
|
134
|
+
// no new banner text" and read absurdly ("across 1 dispatches").
|
|
135
|
+
//
|
|
136
|
+
// Threshold asymmetry with the guard layer is deliberate: this runs AFTER
|
|
137
|
+
// the call was counted (post-increment, so `>` = "the call that overran"),
|
|
138
|
+
// while guards.ts CLAUSE 3b runs BEFORE a call executes (pre-increment,
|
|
139
|
+
// so `>=` = "this call would overrun").
|
|
140
|
+
const cumulativeCeiling = state.cap * CUMULATIVE_CAP_MULTIPLIER;
|
|
141
|
+
if (state.dispatches > 1 && state.totalCalls > cumulativeCeiling) {
|
|
142
|
+
lines.push(
|
|
143
|
+
`[⚠ CUMULATIVE BUDGET EXCEEDED: ${state.totalCalls}/${cumulativeCeiling} across ${state.dispatches} dispatches — return now]`,
|
|
144
|
+
);
|
|
145
|
+
}
|
|
102
146
|
}
|
|
103
147
|
|
|
104
148
|
return lines.join("\n");
|
|
@@ -120,12 +164,124 @@ function normTaskKw(kw: string): string {
|
|
|
120
164
|
return kw.toLowerCase().split("(")[0]!.split("/")[0]!.trim();
|
|
121
165
|
}
|
|
122
166
|
|
|
167
|
+
/**
|
|
168
|
+
* A dispatch is "multi-step" when its text describes a sequence rather than one
|
|
169
|
+
* lookup: an ordered/bulleted/step list item, an explicit sequencing or
|
|
170
|
+
* distributive word, or shell-style command chaining (`;`, `&&`). These are the
|
|
171
|
+
* cheapest reliable signals that the subagent is expected to make several tool
|
|
172
|
+
* calls, which is exactly the case proportional bypass must NOT exempt from
|
|
173
|
+
* enforcement.
|
|
174
|
+
*
|
|
175
|
+
* List markers accept `1.`, `1)` and `1:` because "Step 1: ... Step 2: ..." is a
|
|
176
|
+
* common phrasing; `step N` is also matched inline, since it frequently appears
|
|
177
|
+
* mid-line rather than at the start of one.
|
|
178
|
+
*/
|
|
179
|
+
const MULTI_STEP_RE =
|
|
180
|
+
/(?:^\s*(?:[-*+]|\d+[.):])\s)|\bstep\s*\d+\s*[.):]|\bthen\b|\bone at a time\b|\bone-at-a-time\b|\bsequentially\b|\bin order\b|\bin this exact order\b|\beach\b|\bafter that\b|\bfor every\b|;|&&/im;
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* An enumeration of three or more named subjects ("router, guard and verify")
|
|
184
|
+
* describes breadth even when no file is named and no sequencing word appears.
|
|
185
|
+
* Two items are deliberately NOT enough: "read a.json, b.json" is already caught
|
|
186
|
+
* by the path count, and a two-item phrase is common in single-shot requests.
|
|
187
|
+
*/
|
|
188
|
+
const ENUMERATION_RE =
|
|
189
|
+
/[\w./-]+\s*,\s*[\w./-]+\s*(?:,\s*[\w./-]+|\b(?:and|or)\s+[\w./-]+)/i;
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Bare distributive phrasing — "summarize every config file", "list all guard
|
|
193
|
+
* modules" — describes breadth over a whole class of targets with none of the
|
|
194
|
+
* other breadth signals: no comma enumeration, no connector, no second
|
|
195
|
+
* imperative line, no named path, and well under the length backstop. It is
|
|
196
|
+
* still a fan-out, so it must not be trivial.
|
|
197
|
+
*
|
|
198
|
+
* `each` and `for every` are handled by `MULTI_STEP_RE`; this gate covers the
|
|
199
|
+
* remaining bare `every`/`all` forms. The quantifier only counts when it scopes
|
|
200
|
+
* a plural or collective TARGET class ("all guard modules", "every config
|
|
201
|
+
* file"), which is what keeps depth phrasing over ONE file trivial: in "read
|
|
202
|
+
* every line of package.json" and "read all of src/index.ts" the quantifier is
|
|
203
|
+
* partitive, so the intervening-word class refuses to cross `of`, and the head
|
|
204
|
+
* noun may not be followed by a file extension — otherwise `package` in
|
|
205
|
+
* `package.json` reads as a collective, since `.` is a word boundary. The
|
|
206
|
+
* generic plural branch carries a stop-list because English has many singular
|
|
207
|
+
* words ending in `s` — "what does all this mean in tiers.json" must stay a
|
|
208
|
+
* single-file lookup.
|
|
209
|
+
*/
|
|
210
|
+
const DISTRIBUTIVE_RE =
|
|
211
|
+
/\b(?:every|all)\s+(?:(?:the|these|those|other|remaining)\s+)?(?:(?!of\b)[a-z][a-z-]*\s+){0,2}(?:files?|modules?|tests?|configs?|dirs?|directory|directories|components?|routes?|stores?|handlers?|guards?|helpers?|scripts?|packages?|classes?|functions?|endpoints?|entries?|(?!(?:this|its|his|hers|thus|was|has|does|less|plus|yes|gas|bus|css|js|status|focus|process|access|address|business|class|success)\b)[a-z][a-z-]{2,}s)\b(?!\.[a-z])/i;
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Lines that open with an imperative verb. Two or more of them is a task list
|
|
215
|
+
* written as prose. Matched per line so the `Working directory:` / `Platform:` /
|
|
216
|
+
* `Shell:` footer described below cannot inflate the count.
|
|
217
|
+
*/
|
|
218
|
+
const IMPERATIVE_LINE_RE =
|
|
219
|
+
/^\s*(?:read|search|grep|list|find|check|report|summari[sz]e|open|inspect|show|tell|explain|analy[sz]e|compare|verify|count|locate|trace)\b/i;
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* File-path-like tokens, counted to detect multi-file recon. Deliberately
|
|
223
|
+
* requires a known file EXTENSION rather than accepting any slashed path.
|
|
224
|
+
*
|
|
225
|
+
* Dispatch prompts commonly arrive with a `Working directory: <cwd>` footer.
|
|
226
|
+
* That footer is NOT emitted by this plugin — nothing in this repo writes it; it
|
|
227
|
+
* comes from the host/orchestrator's own prompt conventions. Requiring an
|
|
228
|
+
* extension is what keeps a POSIX cwd (`/home/u/proj`) from being miscounted as
|
|
229
|
+
* a target file.
|
|
230
|
+
*/
|
|
231
|
+
const PATH_TOKEN_RE =
|
|
232
|
+
/[\w./\\-]*[\w-]\.(?:ts|tsx|js|jsx|mjs|cjs|json|jsonc|md|ya?ml|toml|txt|css|scss|html|py|rs|go|rb|java|sh|ps1|sql|lock)\b/gi;
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Well-known extensionless files, which `PATH_TOKEN_RE` cannot see. Matched
|
|
236
|
+
* case-SENSITIVELY against the raw text so the conventional capitalisation is
|
|
237
|
+
* required: "read Makefile and LICENSE" names two files, while "read the license
|
|
238
|
+
* field in package.json" names one. The lookahead prevents double-counting
|
|
239
|
+
* `README.md`, which `PATH_TOKEN_RE` already matches.
|
|
240
|
+
*/
|
|
241
|
+
const BARE_FILENAME_RE =
|
|
242
|
+
/\b(?:Makefile|Dockerfile|LICENSE|README|CHANGELOG|Gemfile|Rakefile|Procfile|NOTICE|CODEOWNERS)\b(?!\.\w)/g;
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* At most this many distinct target files still counts as a single-shot lookup.
|
|
246
|
+
*
|
|
247
|
+
* Zero paths is deliberately still eligible: "search the codebase for X" and
|
|
248
|
+
* "grep for the handler" name no file yet are the canonical cheap lookups, and
|
|
249
|
+
* requiring exactly one path would reclassify them. Breadth that names no file
|
|
250
|
+
* is caught by `ENUMERATION_RE` and `IMPERATIVE_LINE_RE` instead.
|
|
251
|
+
*/
|
|
252
|
+
const MAX_TRIVIAL_PATHS = 1;
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Backstop for multi-step dispatches that use none of the marker words above:
|
|
256
|
+
* a genuine single-shot lookup is short. Sized well above the real single-shot
|
|
257
|
+
* prompts ("read package.json and tell me the version") and well below a real
|
|
258
|
+
* recon brief, and measured AFTER the cwd/platform footer so that footer can
|
|
259
|
+
* never by itself push a dispatch over the line.
|
|
260
|
+
*/
|
|
261
|
+
const MAX_TRIVIAL_CHARS = 240;
|
|
262
|
+
|
|
123
263
|
/**
|
|
124
264
|
* Classify a dispatch as "trivial" AT DISPATCH TIME (m2): conservative,
|
|
125
|
-
* tier-gated.
|
|
126
|
-
*
|
|
127
|
-
*
|
|
128
|
-
*
|
|
265
|
+
* tier-gated. Trivial means the GA-6 proportionality case — a SINGLE-SHOT
|
|
266
|
+
* lookup — not merely "read-only". A dispatch is trivial only when ALL hold:
|
|
267
|
+
*
|
|
268
|
+
* 1. tier is `fast` (medium/heavy is never trivial), and
|
|
269
|
+
* 2. the text is non-empty, and
|
|
270
|
+
* 3. it carries NO medium/heavy taskPattern signal, and
|
|
271
|
+
* 4. it matches a fast taskPattern stem, and
|
|
272
|
+
* 5. it names at most `MAX_TRIVIAL_PATHS` distinct file paths, counting both
|
|
273
|
+
* extensioned paths and well-known extensionless files, and
|
|
274
|
+
* 6. it carries no multi-step marker (`MULTI_STEP_RE`), no 3+ item
|
|
275
|
+
* enumeration (`ENUMERATION_RE`), no distributive breadth quantifier
|
|
276
|
+
* (`DISTRIBUTIVE_RE`), and no second imperative line, and
|
|
277
|
+
* 7. it is at most `MAX_TRIVIAL_CHARS` long.
|
|
278
|
+
*
|
|
279
|
+
* Clauses 5-7 are the narrowing. Without them ANY `fast` dispatch containing a
|
|
280
|
+
* stem like "read" or "search" was trivial, which silently exempted multi-file
|
|
281
|
+
* recon from enforced-mode hard blocks — the read_budget guard could therefore
|
|
282
|
+
* never fire on a `@fast` subagent, defeating the guard it exists to apply.
|
|
283
|
+
* Real work is still NEVER trivial, so bypass still cannot disable enforcement
|
|
284
|
+
* on implementation.
|
|
129
285
|
*/
|
|
130
286
|
export function classifyTrivial(
|
|
131
287
|
dispatchText: string,
|
|
@@ -133,7 +289,8 @@ export function classifyTrivial(
|
|
|
133
289
|
cfg: RouterConfig,
|
|
134
290
|
): boolean {
|
|
135
291
|
if (tier !== "fast") return false;
|
|
136
|
-
const
|
|
292
|
+
const raw = dispatchText || "";
|
|
293
|
+
const text = raw.toLowerCase();
|
|
137
294
|
if (!text.trim()) return false;
|
|
138
295
|
const disqualifiers = [
|
|
139
296
|
...(cfg.taskPatterns?.medium ?? []),
|
|
@@ -143,6 +300,28 @@ export function classifyTrivial(
|
|
|
143
300
|
const n = normTaskKw(kw);
|
|
144
301
|
if (n.length >= 3 && text.includes(n)) return false;
|
|
145
302
|
}
|
|
303
|
+
|
|
304
|
+
// Shape gates: a single-shot lookup is short, names at most one file, and
|
|
305
|
+
// does not enumerate steps or subjects. Checked before the fast-stem match so
|
|
306
|
+
// that a multi-file recon prompt can never be rescued by containing "read".
|
|
307
|
+
if (raw.length > MAX_TRIVIAL_CHARS) return false;
|
|
308
|
+
if (MULTI_STEP_RE.test(raw)) return false;
|
|
309
|
+
if (ENUMERATION_RE.test(raw)) return false;
|
|
310
|
+
if (DISTRIBUTIVE_RE.test(raw)) return false;
|
|
311
|
+
|
|
312
|
+
const imperativeLines = raw
|
|
313
|
+
.split(/\r?\n/)
|
|
314
|
+
.filter((line) => IMPERATIVE_LINE_RE.test(line)).length;
|
|
315
|
+
if (imperativeLines > 1) return false;
|
|
316
|
+
|
|
317
|
+
const paths = new Set<string>(
|
|
318
|
+
(text.match(PATH_TOKEN_RE) ?? []).map((p) => p.trim()),
|
|
319
|
+
);
|
|
320
|
+
for (const bare of raw.match(BARE_FILENAME_RE) ?? []) {
|
|
321
|
+
paths.add(bare.toLowerCase());
|
|
322
|
+
}
|
|
323
|
+
if (paths.size > MAX_TRIVIAL_PATHS) return false;
|
|
324
|
+
|
|
146
325
|
const fast = cfg.taskPatterns?.fast ?? [];
|
|
147
326
|
for (const kw of fast) {
|
|
148
327
|
const n = normTaskKw(kw);
|
|
@@ -155,14 +334,34 @@ export function classifyTrivial(
|
|
|
155
334
|
// Session store factory
|
|
156
335
|
// ---------------------------------------------------------------------------
|
|
157
336
|
|
|
337
|
+
export interface SessionStoreOptions {
|
|
338
|
+
/** Injectable clock (tests). Defaults to Date.now. */
|
|
339
|
+
now?: () => number;
|
|
340
|
+
}
|
|
341
|
+
|
|
158
342
|
/**
|
|
159
343
|
* Creates a per-plugin-instance session store that owns the subagent tracking
|
|
160
344
|
* state (session IDs + cap state). Returns methods the hooks delegate to.
|
|
161
345
|
* Concurrency: Set/Map are per-store-instance, NOT module-level singletons.
|
|
346
|
+
*
|
|
347
|
+
* Idle-TTL: registration and tool-call activity refresh a per-session lastTouch
|
|
348
|
+
* stamp; `sweep()` evicts sessions idle for at least ttlMs. No timers.
|
|
162
349
|
*/
|
|
163
|
-
export function createSessionStore() {
|
|
350
|
+
export function createSessionStore(options: SessionStoreOptions = {}) {
|
|
351
|
+
const now = options.now ?? Date.now;
|
|
164
352
|
const subagentSessionIDs = new Set<string>();
|
|
165
353
|
const subagentCapState = new Map<string, SubagentState>();
|
|
354
|
+
const lastTouch = new Map<string, number>();
|
|
355
|
+
|
|
356
|
+
function touch(sessionID: string): void {
|
|
357
|
+
lastTouch.set(sessionID, now());
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function evict(sessionID: string): void {
|
|
361
|
+
subagentSessionIDs.delete(sessionID);
|
|
362
|
+
subagentCapState.delete(sessionID);
|
|
363
|
+
lastTouch.delete(sessionID);
|
|
364
|
+
}
|
|
166
365
|
|
|
167
366
|
return {
|
|
168
367
|
/** Returns true when sessionID belongs to a tracked subagent session. */
|
|
@@ -192,15 +391,40 @@ export function createSessionStore() {
|
|
|
192
391
|
tierName: tier,
|
|
193
392
|
cap: baseline,
|
|
194
393
|
calls: 0,
|
|
394
|
+
dispatches: 1,
|
|
395
|
+
totalCalls: 0,
|
|
195
396
|
seen: new Map(),
|
|
196
397
|
trivial: false,
|
|
197
398
|
});
|
|
399
|
+
touch(sessionID);
|
|
198
400
|
},
|
|
199
401
|
|
|
200
402
|
/** Remove a session from tracking (used to clean up delegate producer sessions). */
|
|
201
403
|
unregister(sessionID: string): void {
|
|
202
|
-
|
|
203
|
-
|
|
404
|
+
evict(sessionID);
|
|
405
|
+
},
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Refresh a tracked session's idle stamp. Called when a tool call STARTS,
|
|
409
|
+
* so that a session whose single tool call outlives the TTL is not evicted
|
|
410
|
+
* mid-call by some other session's sweep — an eviction that would silently
|
|
411
|
+
* drop cap enforcement for the rest of that session, because recordToolCall
|
|
412
|
+
* returns early when the state is gone.
|
|
413
|
+
*
|
|
414
|
+
* Only touches sessions that are actually tracked. Touching unconditionally
|
|
415
|
+
* is what created orphan lastTouch entries in the first place.
|
|
416
|
+
*/
|
|
417
|
+
touchIfTracked(sessionID: string): boolean {
|
|
418
|
+
if (!subagentCapState.has(sessionID)) return false;
|
|
419
|
+
touch(sessionID);
|
|
420
|
+
return true;
|
|
421
|
+
},
|
|
422
|
+
|
|
423
|
+
/** Evict every session idle for >= ttlMs. Future stamps are never evicted. */
|
|
424
|
+
sweep(nowMs: number = now(), ttlMs: number = DEFAULT_IDLE_TTL_MS): void {
|
|
425
|
+
for (const [sessionID, stamp] of [...lastTouch.entries()]) {
|
|
426
|
+
if (nowMs - stamp >= ttlMs) evict(sessionID);
|
|
427
|
+
}
|
|
204
428
|
},
|
|
205
429
|
|
|
206
430
|
/**
|
|
@@ -208,32 +432,74 @@ export function createSessionStore() {
|
|
|
208
432
|
* at a registered tier agent, records the session and initialises its cap state.
|
|
209
433
|
* Accepts `tierNames` (from getActiveTiers) so this module doesn't need to
|
|
210
434
|
* import protocol.ts.
|
|
435
|
+
*
|
|
436
|
+
* Resume detection: a re-registration of a session already tracked at the
|
|
437
|
+
* SAME tier is a resumed dispatch (this is how an opencode task_id resume
|
|
438
|
+
* manifests at the chat.message hook). A resume resets the per-dispatch
|
|
439
|
+
* budget but preserves cumulative usage and read fingerprints.
|
|
211
440
|
*/
|
|
212
441
|
registerFromChatMessage(
|
|
213
442
|
input: { agent?: string; sessionID: string },
|
|
214
443
|
output: unknown,
|
|
215
444
|
cfg: RouterConfig,
|
|
216
445
|
tierNames: string[],
|
|
217
|
-
):
|
|
218
|
-
if (input.agent
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
446
|
+
): RegisterResult {
|
|
447
|
+
if (!input.agent || !tierNames.includes(input.agent)) {
|
|
448
|
+
return { registered: false, resumed: false };
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
subagentSessionIDs.add(input.sessionID);
|
|
452
|
+
|
|
453
|
+
const tierName = input.agent;
|
|
454
|
+
const dispatchText = extractDispatchText(output);
|
|
455
|
+
// CAP:none is honored only when the dispatch carries a justification
|
|
456
|
+
// (a `reason:` line). An unjustified CAP:none falls back to the tier
|
|
457
|
+
// baseline — prompt rules alone are advisory; this is the deterministic
|
|
458
|
+
// enforcer of "uncapped requires a stated reason". Numeric CAP:N is
|
|
459
|
+
// unaffected.
|
|
460
|
+
//
|
|
461
|
+
// The regex matches `reason:` ANYWHERE in the dispatch text, not only on
|
|
462
|
+
// its own line. That is deliberate: this is a deterministic but
|
|
463
|
+
// advisory-grade gate whose job is to make an unjustified CAP:none the
|
|
464
|
+
// inconvenient path, not to adjudicate the quality of a justification.
|
|
465
|
+
// An orchestrator that wants to defeat it can, and that is fine — the
|
|
466
|
+
// config-derived guard budget, which never reads dispatch text, is the
|
|
467
|
+
// real backstop.
|
|
468
|
+
const parsed = parseCapDirective(dispatchText);
|
|
469
|
+
const override =
|
|
470
|
+
parsed === "none" && !/\breason:/i.test(dispatchText) ? null : parsed;
|
|
471
|
+
const baseline =
|
|
472
|
+
cfg.tierCaps?.[tierName] ?? DEFAULT_TIER_CAPS[tierName] ?? 5;
|
|
473
|
+
const cap: Cap = override ?? baseline;
|
|
474
|
+
const trivial = classifyTrivial(dispatchText, tierName, cfg);
|
|
475
|
+
const existing = subagentCapState.get(input.sessionID);
|
|
476
|
+
|
|
477
|
+
// Same-tier re-registration = resumed dispatch. Reset only the
|
|
478
|
+
// per-dispatch budget; `seen` is PRESERVED so redundancy detection
|
|
479
|
+
// carries across dispatches, and totalCalls keeps feeding the
|
|
480
|
+
// cumulative ceiling.
|
|
481
|
+
if (existing?.tierName === tierName) {
|
|
482
|
+
existing.cap = cap;
|
|
483
|
+
existing.calls = 0;
|
|
484
|
+
existing.dispatches += 1;
|
|
485
|
+
existing.trivial = trivial;
|
|
486
|
+
touch(input.sessionID);
|
|
487
|
+
return { registered: true, resumed: true };
|
|
236
488
|
}
|
|
489
|
+
|
|
490
|
+
// No prior state (first dispatch, or an idle-TTL sweep evicted it) or a
|
|
491
|
+
// different tier on the same sessionID: fresh session, fresh counters.
|
|
492
|
+
subagentCapState.set(input.sessionID, {
|
|
493
|
+
tierName,
|
|
494
|
+
cap,
|
|
495
|
+
calls: 0,
|
|
496
|
+
dispatches: 1,
|
|
497
|
+
totalCalls: 0,
|
|
498
|
+
seen: new Map(),
|
|
499
|
+
trivial,
|
|
500
|
+
});
|
|
501
|
+
touch(input.sessionID);
|
|
502
|
+
return { registered: true, resumed: false };
|
|
237
503
|
},
|
|
238
504
|
|
|
239
505
|
/**
|
|
@@ -247,6 +513,11 @@ export function createSessionStore() {
|
|
|
247
513
|
): void {
|
|
248
514
|
const state = subagentCapState.get(input.sessionID);
|
|
249
515
|
if (!state) return; // not a tracked subagent session
|
|
516
|
+
// Touch AFTER the early return: touching first created a lastTouch entry
|
|
517
|
+
// for every untracked session that ever ran a tool, and nothing else ever
|
|
518
|
+
// removed it. Tracked sessions still refresh here, because the read-only
|
|
519
|
+
// filter below runs later.
|
|
520
|
+
touch(input.sessionID);
|
|
250
521
|
if (!READ_ONLY_TOOLS.has(input.tool)) return;
|
|
251
522
|
|
|
252
523
|
const fp = fingerprintToolCall(input.tool, input.args);
|
|
@@ -254,6 +525,7 @@ export function createSessionStore() {
|
|
|
254
525
|
const isRedundant = previousCall !== undefined;
|
|
255
526
|
|
|
256
527
|
state.calls += 1;
|
|
528
|
+
state.totalCalls += 1;
|
|
257
529
|
if (!isRedundant) {
|
|
258
530
|
state.seen.set(fp, state.calls);
|
|
259
531
|
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { Preset } from "./config";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Model override to apply to a pre-existing subagent. `variant` is always
|
|
5
|
+
* present in the result (possibly `undefined`) so callers can distinguish
|
|
6
|
+
* "this tier has no variant" from "leave whatever was there" — an inherited
|
|
7
|
+
* variant from another provider is a silent dispatch-time failure.
|
|
8
|
+
*/
|
|
9
|
+
export interface SubagentOverride {
|
|
10
|
+
model: string;
|
|
11
|
+
variant: string | undefined;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function isPlainObject(v: unknown): v is Record<string, unknown> {
|
|
15
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Resolves `subagentTiers` (agent name → tier name) into concrete per-agent
|
|
20
|
+
* model overrides, using the models of the *active* preset. This is what lets
|
|
21
|
+
* a pre-existing agent follow `/preset` instead of pinning a model id in its
|
|
22
|
+
* own definition.
|
|
23
|
+
*
|
|
24
|
+
* Pure. Entries are skipped — never throw — when:
|
|
25
|
+
* - the named tier does not exist in the active preset (e.g. a map written
|
|
26
|
+
* for a preset that defines a tier this one doesn't),
|
|
27
|
+
* - the agent name collides with a tier name, which would clobber the
|
|
28
|
+
* plugin's own `@fast`/`@medium`/`@heavy` agents,
|
|
29
|
+
* - the agent is already registered with a `mode` other than "subagent";
|
|
30
|
+
* primary agents are the orchestrator, and pinning one to a tier model
|
|
31
|
+
* would defeat the routing design.
|
|
32
|
+
*
|
|
33
|
+
* Note this can only see agents already present in the opencode config —
|
|
34
|
+
* markdown-defined agents are loaded separately, so their `mode` is not
|
|
35
|
+
* visible here. Listing a primary agent defined in markdown is not caught.
|
|
36
|
+
*/
|
|
37
|
+
export function resolveSubagentOverrides(input: {
|
|
38
|
+
subagentTiers?: Record<string, string>;
|
|
39
|
+
tiers: Preset;
|
|
40
|
+
/** The opencode config's `agent` record, when already populated. */
|
|
41
|
+
existingAgents?: Record<string, unknown>;
|
|
42
|
+
}): Record<string, SubagentOverride> {
|
|
43
|
+
const { subagentTiers, tiers, existingAgents } = input;
|
|
44
|
+
if (!isPlainObject(subagentTiers)) return {};
|
|
45
|
+
|
|
46
|
+
const out: Record<string, SubagentOverride> = {};
|
|
47
|
+
|
|
48
|
+
for (const [agentName, tierName] of Object.entries(subagentTiers)) {
|
|
49
|
+
if (typeof tierName !== "string" || tierName === "") continue;
|
|
50
|
+
if (agentName === "") continue;
|
|
51
|
+
|
|
52
|
+
// Never rewrite the plugin's own tier agents.
|
|
53
|
+
if (Object.prototype.hasOwnProperty.call(tiers, agentName)) continue;
|
|
54
|
+
|
|
55
|
+
const tier = tiers[tierName];
|
|
56
|
+
if (!tier || typeof tier.model !== "string" || tier.model === "") continue;
|
|
57
|
+
|
|
58
|
+
const existing = existingAgents?.[agentName];
|
|
59
|
+
if (isPlainObject(existing) && typeof existing.mode === "string") {
|
|
60
|
+
if (existing.mode !== "subagent") continue;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
out[agentName] = { model: tier.model, variant: tier.variant };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Merges a resolved override onto an agent's existing config entry.
|
|
71
|
+
*
|
|
72
|
+
* `variant` is set or removed explicitly rather than spread, so a tier without
|
|
73
|
+
* a variant clears one left behind by a previous preset instead of inheriting
|
|
74
|
+
* it. Every other field on the entry is preserved.
|
|
75
|
+
*/
|
|
76
|
+
export function mergeSubagentOverride(
|
|
77
|
+
existing: unknown,
|
|
78
|
+
override: SubagentOverride,
|
|
79
|
+
): Record<string, unknown> {
|
|
80
|
+
const base = isPlainObject(existing) ? { ...existing } : {};
|
|
81
|
+
base.model = override.model;
|
|
82
|
+
if (override.variant) base.variant = override.variant;
|
|
83
|
+
else delete base.variant;
|
|
84
|
+
return base;
|
|
85
|
+
}
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
// Trajectory scorecard — pure module, no fs/network/SDK/process.env
|
|
3
3
|
// ---------------------------------------------------------------------------
|
|
4
4
|
|
|
5
|
+
import { DEFAULT_IDLE_TTL_MS } from "../router/idle-sweep";
|
|
6
|
+
|
|
5
7
|
export interface TrajectoryToolEvent {
|
|
6
8
|
tool: string;
|
|
7
9
|
readOnly: boolean;
|
|
@@ -34,6 +36,8 @@ export interface TrajectoryState {
|
|
|
34
36
|
escalations: number;
|
|
35
37
|
finalTier: string | null;
|
|
36
38
|
costUnits: number;
|
|
39
|
+
/** Dispatch rounds seen for this session (1 on first dispatch). */
|
|
40
|
+
dispatches: number;
|
|
37
41
|
}
|
|
38
42
|
|
|
39
43
|
export function createTrajectory(
|
|
@@ -60,6 +64,7 @@ export function createTrajectory(
|
|
|
60
64
|
escalations: 0,
|
|
61
65
|
finalTier: null,
|
|
62
66
|
costUnits: 0,
|
|
67
|
+
dispatches: 1,
|
|
63
68
|
};
|
|
64
69
|
}
|
|
65
70
|
|
|
@@ -128,6 +133,7 @@ export function trajectoryMetrics(
|
|
|
128
133
|
escalations: state.escalations,
|
|
129
134
|
final_tier: state.finalTier,
|
|
130
135
|
cost_units: state.costUnits,
|
|
136
|
+
dispatches: state.dispatches,
|
|
131
137
|
};
|
|
132
138
|
}
|
|
133
139
|
|
|
@@ -139,10 +145,27 @@ export function dumpTrajectory(state: TrajectoryState): string {
|
|
|
139
145
|
// Per-instance store factory — mirrors src/router/sessions.ts pattern
|
|
140
146
|
// ---------------------------------------------------------------------------
|
|
141
147
|
|
|
142
|
-
export
|
|
148
|
+
export interface TrajectoryStoreOptions {
|
|
149
|
+
/** Injectable clock (tests). Defaults to Date.now. */
|
|
150
|
+
now?: () => number;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function createTrajectoryStore(options: TrajectoryStoreOptions = {}) {
|
|
154
|
+
const now = options.now ?? Date.now;
|
|
143
155
|
const store = new Map<string, TrajectoryState>();
|
|
156
|
+
const lastTouch = new Map<string, number>();
|
|
157
|
+
|
|
158
|
+
function touch(sessionID: string): void {
|
|
159
|
+
lastTouch.set(sessionID, now());
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function evictState(sessionID: string): void {
|
|
163
|
+
store.delete(sessionID);
|
|
164
|
+
lastTouch.delete(sessionID);
|
|
165
|
+
}
|
|
144
166
|
|
|
145
167
|
function ensureState(sessionID: string, tier?: string | null): TrajectoryState {
|
|
168
|
+
touch(sessionID);
|
|
146
169
|
let s = store.get(sessionID);
|
|
147
170
|
if (!s) {
|
|
148
171
|
s = createTrajectory(sessionID, tier);
|
|
@@ -165,7 +188,19 @@ export function createTrajectoryStore() {
|
|
|
165
188
|
recordToolEvent(s, event);
|
|
166
189
|
},
|
|
167
190
|
|
|
191
|
+
/**
|
|
192
|
+
* Record a resumed dispatch into an existing session. Creates state when
|
|
193
|
+
* absent so a resume that outlived an idle-TTL sweep still reports a
|
|
194
|
+
* dispatch count rather than throwing.
|
|
195
|
+
*/
|
|
196
|
+
recordResume(sessionID: string, tier?: string | null): void {
|
|
197
|
+
const s = ensureState(sessionID, tier);
|
|
198
|
+
s.dispatches += 1;
|
|
199
|
+
touch(sessionID);
|
|
200
|
+
},
|
|
201
|
+
|
|
168
202
|
setStopReason(sessionID: string, reason: string): void {
|
|
203
|
+
touch(sessionID);
|
|
169
204
|
const s = store.get(sessionID);
|
|
170
205
|
if (!s) return;
|
|
171
206
|
setStopReason(s, reason);
|
|
@@ -176,5 +211,17 @@ export function createTrajectoryStore() {
|
|
|
176
211
|
if (!s) return null;
|
|
177
212
|
return dumpTrajectory(s);
|
|
178
213
|
},
|
|
214
|
+
|
|
215
|
+
/** Drop a session's trajectory state. */
|
|
216
|
+
evict(sessionID: string): void {
|
|
217
|
+
evictState(sessionID);
|
|
218
|
+
},
|
|
219
|
+
|
|
220
|
+
/** Evict every session idle for >= ttlMs. Future stamps are never evicted. */
|
|
221
|
+
sweep(nowMs: number = now(), ttlMs: number = DEFAULT_IDLE_TTL_MS): void {
|
|
222
|
+
for (const [sessionID, stamp] of [...lastTouch.entries()]) {
|
|
223
|
+
if (nowMs - stamp >= ttlMs) evictState(sessionID);
|
|
224
|
+
}
|
|
225
|
+
},
|
|
179
226
|
};
|
|
180
227
|
}
|