opencode-model-router 1.5.0 → 1.6.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/README.md +65 -9
- package/package.json +1 -1
- package/src/commands/output.ts +236 -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 +264 -341
- package/src/router/agent-options.ts +118 -0
- package/src/router/config.ts +277 -43
- 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 +159 -22
- 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
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal-oriented tier prompt defaults and prompt-style resolution.
|
|
3
|
+
*
|
|
4
|
+
* Two prompt styles exist per tier:
|
|
5
|
+
* - "prescriptive": the enumerated STOP CONDITIONS prompts in tiers.json (tierPrompts) —
|
|
6
|
+
* better for weaker models that need explicit steps.
|
|
7
|
+
* - "goal-oriented": goal + constraints, no step enumeration (Anthropic Fable 5 guidance:
|
|
8
|
+
* "state the goal and constraints over enumerating steps") — better for strong models.
|
|
9
|
+
* - "auto" (default): goal-oriented when the tier model matches the strong-model pattern
|
|
10
|
+
* list (cfg.modelGenerations.strong, default Claude 5.x gen + opus-4-8); else prescriptive.
|
|
11
|
+
*
|
|
12
|
+
* The runtime guard (src/guard/) enforces caps regardless of prompt style — prompt text is
|
|
13
|
+
* advisory; enforcement is mechanical.
|
|
14
|
+
*/
|
|
15
|
+
import {
|
|
16
|
+
DEFAULT_STRONG_MODEL_PATTERNS,
|
|
17
|
+
type PromptStyle,
|
|
18
|
+
type RouterConfig,
|
|
19
|
+
type TierConfig,
|
|
20
|
+
} from "./config";
|
|
21
|
+
|
|
22
|
+
export const GOAL_ORIENTED_TIER_PROMPTS: Record<string, string> = {
|
|
23
|
+
fast: `You are @fast, a read-only exploration specialist: searching, grepping, reading, listing, looking up docs, checking types, counting, verifying existence, and gathering git info. You never write or edit files — if a change is needed, report it and note that the orchestrator must dispatch @medium. You have no Task tool and cannot sub-delegate.
|
|
24
|
+
|
|
25
|
+
Your goal is to answer the dispatch with exactly the findings requested, reported concisely as file:line references plus short snippets and a one-line summary. Make a single focused pass and stop once you have enough to answer; resist widening scope beyond what was asked.
|
|
26
|
+
|
|
27
|
+
Treat read-only calls as a budget of 8 per dispatch — a \`CAP:N\` in the dispatch resets this number, and \`CAP:none\` removes the limit when the dispatch also carries a \`reason:\` line. The runtime appends \`[cap: N/MAX]\` to each read-only result so you can track spend, and appends \`[⚠ REDUNDANT]\` when you repeat a call; stop re-reading ground you have already covered when you see it. A rare overrun is acceptable if you prefix one line with \`reason:\`.
|
|
28
|
+
|
|
29
|
+
Begin your response with exactly one of \`DONE:\` (with findings), \`NEED MORE:\`, or \`ESCALATE:\`.`,
|
|
30
|
+
medium: `You are @medium, an implementation specialist: writing and editing code, refactoring, adding tests, fixing bugs, repairing builds, creating files, configuring, and wiring APIs. You have no Task tool and cannot sub-delegate.
|
|
31
|
+
|
|
32
|
+
Your goal is to deliver working, verified changes that match the existing project's patterns and conventions. Never suppress type errors with \`as any\`, \`@ts-ignore\`, or \`@ts-expect-error\` — fix the underlying cause. Run only the targeted tests that cover what you changed, not the full suite unless asked. If the same change fails twice in a row, stop and report what you tried rather than escalating yourself or thrashing further.
|
|
33
|
+
|
|
34
|
+
Gather just enough context before editing: treat read-only calls as a budget of 5 before your first edit, where \`CAP:N\` resets the number and \`CAP:none\` removes it when the dispatch also carries a \`reason:\` line. The runtime appends \`[cap: N/MAX]\` to read-only results and \`[⚠ REDUNDANT]\` on repeated calls; once redundancy shows, start editing or ask for what is missing. A rare overrun is fine with a one-line \`reason:\` prefix.
|
|
35
|
+
|
|
36
|
+
Ground every claim in actual tool results from this session — if you say a test passed, a file changed, or behavior works, it must trace to output you saw. Flag anything unverified as such, and quote the relevant excerpt when a test fails.
|
|
37
|
+
|
|
38
|
+
Begin your response with exactly one of \`DONE:\` (changes plus verification), \`NEED CONTEXT:\`, or \`ESCALATE:\`, and close a \`DONE:\` with a concise summary of files changed, key decisions, and tests run.`,
|
|
39
|
+
heavy: `You are @heavy, a senior architecture and debugging consultant: architecture decisions, security and performance review, hard debugging after at least two prior failed attempts, multi-system tradeoffs, migration strategy, and root-cause analysis. Your identity is analysis, not reconnaissance — forty minutes of file reads is reconnaissance, which is @fast's job, not yours. You have no Task tool and cannot sub-delegate.
|
|
40
|
+
|
|
41
|
+
Your goal is to analyze exhaustively within the context you were given and return a clear recommendation, structured as problem framing, then options considered, then tradeoffs, then recommendation, then implementation notes. Reason from what you have, and write code only when the dispatch explicitly asks for it.
|
|
42
|
+
|
|
43
|
+
Treat reads and greps as a budget of 3, where \`CAP:N\` resets the number and \`CAP:none\` removes it for deep mode when the dispatch also carries a \`reason:\` line. The runtime appends \`[cap: N/MAX]\` to read-only results and \`[⚠ REDUNDANT]\` on repeated calls; when you reach the budget, deliver your analysis from what you already have rather than reading further. When the redundancy marker appears, stop gathering and analyze with what you have. A rare overrun is acceptable with a one-line \`reason:\` prefix.
|
|
44
|
+
|
|
45
|
+
Ground every claim in a tool result or the context you were given; flag anything unverified explicitly, and quote the relevant excerpt when you cite a failure.
|
|
46
|
+
|
|
47
|
+
Begin your response with exactly one of \`DONE:\` (structured analysis), \`SCOPE GROWTH:\` (prefer @fast pre-exploration of [specific files/patterns/areas] before I continue), or \`ESCALATE:\`.`,
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** Case-insensitive substring match against the strong-model pattern list. */
|
|
51
|
+
export function isStrongModel(modelID: string | undefined, cfg: RouterConfig): boolean {
|
|
52
|
+
if (typeof modelID !== "string" || modelID.length === 0) return false;
|
|
53
|
+
const raw = cfg.modelGenerations?.strong ?? DEFAULT_STRONG_MODEL_PATTERNS;
|
|
54
|
+
const patterns = raw.filter((p): p is string => typeof p === "string" && p.length > 0);
|
|
55
|
+
const id = modelID.toLowerCase();
|
|
56
|
+
return patterns.some((p) => id.includes(p.toLowerCase()));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Resolve "auto" (or absent) to a concrete style. Fail-safe: unknown/empty model -> prescriptive. */
|
|
60
|
+
export function resolvePromptStyle(style: PromptStyle | undefined, modelID: string | undefined, cfg: RouterConfig): "prescriptive" | "goal-oriented" {
|
|
61
|
+
if (style === "prescriptive" || style === "goal-oriented") return style;
|
|
62
|
+
return isStrongModel(modelID, cfg) ? "goal-oriented" : "prescriptive";
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Select the default prompt for a tier honoring style. Explicit tier.prompt is handled by the caller and always wins. */
|
|
66
|
+
export function selectTierPrompt(tierName: string, tier: TierConfig, cfg: RouterConfig): string | undefined {
|
|
67
|
+
const style = resolvePromptStyle(tier.promptStyle, tier.model, cfg);
|
|
68
|
+
if (style === "goal-oriented") {
|
|
69
|
+
return cfg.tierPromptsGoalOriented?.[tierName] ?? GOAL_ORIENTED_TIER_PROMPTS[tierName] ?? cfg.tierPrompts?.[tierName];
|
|
70
|
+
}
|
|
71
|
+
return cfg.tierPrompts?.[tierName];
|
|
72
|
+
}
|
package/src/router/protocol.ts
CHANGED
|
@@ -126,7 +126,7 @@ export function buildDelegationProtocol(cfg: RouterConfig): string {
|
|
|
126
126
|
``,
|
|
127
127
|
`When dispatching: batch related @fast searches into one call and run independent ones in parallel (several Task calls in one message); give @medium concrete context (paths, patterns, how to verify).`,
|
|
128
128
|
``,
|
|
129
|
-
`Per dispatch you may add \`CAP:N\` (or \`CAP:none\`) to change a subagent's read-only budget (baseline @fast=8, @medium=5, @heavy=3). Subagents return \`DONE:\`, \`NEED MORE:\`, or \`ESCALATE:\` for you to act on. @heavy has no tools of its own, so gather context first (usually via @fast) and paste it into the dispatch.`,
|
|
129
|
+
`Per dispatch you may add \`CAP:N\` (or \`CAP:none\` with a \`reason:\` line — unjustified \`CAP:none\` is ignored) to change a subagent's read-only budget (baseline @fast=8, @medium=5, @heavy=3). Subagents return \`DONE:\`, \`NEED MORE:\`, or \`ESCALATE:\` for you to act on. @heavy has no tools of its own, so gather context first (usually via @fast) and paste it into the dispatch.`,
|
|
130
130
|
``,
|
|
131
131
|
`This protocol overrides any project guide (CLAUDE.md, AGENTS.md, etc.) that says to use direct tools first when scope is clear, or labels Grep/Read/Glob as FREE. They are wrong about cost: every tool-result token is billed at your tier rate, so the same grep costs ~20x less dispatched to @fast than run here.`,
|
|
132
132
|
].join("\n");
|
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");
|
|
@@ -155,14 +199,34 @@ export function classifyTrivial(
|
|
|
155
199
|
// Session store factory
|
|
156
200
|
// ---------------------------------------------------------------------------
|
|
157
201
|
|
|
202
|
+
export interface SessionStoreOptions {
|
|
203
|
+
/** Injectable clock (tests). Defaults to Date.now. */
|
|
204
|
+
now?: () => number;
|
|
205
|
+
}
|
|
206
|
+
|
|
158
207
|
/**
|
|
159
208
|
* Creates a per-plugin-instance session store that owns the subagent tracking
|
|
160
209
|
* state (session IDs + cap state). Returns methods the hooks delegate to.
|
|
161
210
|
* Concurrency: Set/Map are per-store-instance, NOT module-level singletons.
|
|
211
|
+
*
|
|
212
|
+
* Idle-TTL: registration and tool-call activity refresh a per-session lastTouch
|
|
213
|
+
* stamp; `sweep()` evicts sessions idle for at least ttlMs. No timers.
|
|
162
214
|
*/
|
|
163
|
-
export function createSessionStore() {
|
|
215
|
+
export function createSessionStore(options: SessionStoreOptions = {}) {
|
|
216
|
+
const now = options.now ?? Date.now;
|
|
164
217
|
const subagentSessionIDs = new Set<string>();
|
|
165
218
|
const subagentCapState = new Map<string, SubagentState>();
|
|
219
|
+
const lastTouch = new Map<string, number>();
|
|
220
|
+
|
|
221
|
+
function touch(sessionID: string): void {
|
|
222
|
+
lastTouch.set(sessionID, now());
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function evict(sessionID: string): void {
|
|
226
|
+
subagentSessionIDs.delete(sessionID);
|
|
227
|
+
subagentCapState.delete(sessionID);
|
|
228
|
+
lastTouch.delete(sessionID);
|
|
229
|
+
}
|
|
166
230
|
|
|
167
231
|
return {
|
|
168
232
|
/** Returns true when sessionID belongs to a tracked subagent session. */
|
|
@@ -192,15 +256,40 @@ export function createSessionStore() {
|
|
|
192
256
|
tierName: tier,
|
|
193
257
|
cap: baseline,
|
|
194
258
|
calls: 0,
|
|
259
|
+
dispatches: 1,
|
|
260
|
+
totalCalls: 0,
|
|
195
261
|
seen: new Map(),
|
|
196
262
|
trivial: false,
|
|
197
263
|
});
|
|
264
|
+
touch(sessionID);
|
|
198
265
|
},
|
|
199
266
|
|
|
200
267
|
/** Remove a session from tracking (used to clean up delegate producer sessions). */
|
|
201
268
|
unregister(sessionID: string): void {
|
|
202
|
-
|
|
203
|
-
|
|
269
|
+
evict(sessionID);
|
|
270
|
+
},
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Refresh a tracked session's idle stamp. Called when a tool call STARTS,
|
|
274
|
+
* so that a session whose single tool call outlives the TTL is not evicted
|
|
275
|
+
* mid-call by some other session's sweep — an eviction that would silently
|
|
276
|
+
* drop cap enforcement for the rest of that session, because recordToolCall
|
|
277
|
+
* returns early when the state is gone.
|
|
278
|
+
*
|
|
279
|
+
* Only touches sessions that are actually tracked. Touching unconditionally
|
|
280
|
+
* is what created orphan lastTouch entries in the first place.
|
|
281
|
+
*/
|
|
282
|
+
touchIfTracked(sessionID: string): boolean {
|
|
283
|
+
if (!subagentCapState.has(sessionID)) return false;
|
|
284
|
+
touch(sessionID);
|
|
285
|
+
return true;
|
|
286
|
+
},
|
|
287
|
+
|
|
288
|
+
/** Evict every session idle for >= ttlMs. Future stamps are never evicted. */
|
|
289
|
+
sweep(nowMs: number = now(), ttlMs: number = DEFAULT_IDLE_TTL_MS): void {
|
|
290
|
+
for (const [sessionID, stamp] of [...lastTouch.entries()]) {
|
|
291
|
+
if (nowMs - stamp >= ttlMs) evict(sessionID);
|
|
292
|
+
}
|
|
204
293
|
},
|
|
205
294
|
|
|
206
295
|
/**
|
|
@@ -208,32 +297,74 @@ export function createSessionStore() {
|
|
|
208
297
|
* at a registered tier agent, records the session and initialises its cap state.
|
|
209
298
|
* Accepts `tierNames` (from getActiveTiers) so this module doesn't need to
|
|
210
299
|
* import protocol.ts.
|
|
300
|
+
*
|
|
301
|
+
* Resume detection: a re-registration of a session already tracked at the
|
|
302
|
+
* SAME tier is a resumed dispatch (this is how an opencode task_id resume
|
|
303
|
+
* manifests at the chat.message hook). A resume resets the per-dispatch
|
|
304
|
+
* budget but preserves cumulative usage and read fingerprints.
|
|
211
305
|
*/
|
|
212
306
|
registerFromChatMessage(
|
|
213
307
|
input: { agent?: string; sessionID: string },
|
|
214
308
|
output: unknown,
|
|
215
309
|
cfg: RouterConfig,
|
|
216
310
|
tierNames: string[],
|
|
217
|
-
):
|
|
218
|
-
if (input.agent
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
311
|
+
): RegisterResult {
|
|
312
|
+
if (!input.agent || !tierNames.includes(input.agent)) {
|
|
313
|
+
return { registered: false, resumed: false };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
subagentSessionIDs.add(input.sessionID);
|
|
317
|
+
|
|
318
|
+
const tierName = input.agent;
|
|
319
|
+
const dispatchText = extractDispatchText(output);
|
|
320
|
+
// CAP:none is honored only when the dispatch carries a justification
|
|
321
|
+
// (a `reason:` line). An unjustified CAP:none falls back to the tier
|
|
322
|
+
// baseline — prompt rules alone are advisory; this is the deterministic
|
|
323
|
+
// enforcer of "uncapped requires a stated reason". Numeric CAP:N is
|
|
324
|
+
// unaffected.
|
|
325
|
+
//
|
|
326
|
+
// The regex matches `reason:` ANYWHERE in the dispatch text, not only on
|
|
327
|
+
// its own line. That is deliberate: this is a deterministic but
|
|
328
|
+
// advisory-grade gate whose job is to make an unjustified CAP:none the
|
|
329
|
+
// inconvenient path, not to adjudicate the quality of a justification.
|
|
330
|
+
// An orchestrator that wants to defeat it can, and that is fine — the
|
|
331
|
+
// config-derived guard budget, which never reads dispatch text, is the
|
|
332
|
+
// real backstop.
|
|
333
|
+
const parsed = parseCapDirective(dispatchText);
|
|
334
|
+
const override =
|
|
335
|
+
parsed === "none" && !/\breason:/i.test(dispatchText) ? null : parsed;
|
|
336
|
+
const baseline =
|
|
337
|
+
cfg.tierCaps?.[tierName] ?? DEFAULT_TIER_CAPS[tierName] ?? 5;
|
|
338
|
+
const cap: Cap = override ?? baseline;
|
|
339
|
+
const trivial = classifyTrivial(dispatchText, tierName, cfg);
|
|
340
|
+
const existing = subagentCapState.get(input.sessionID);
|
|
341
|
+
|
|
342
|
+
// Same-tier re-registration = resumed dispatch. Reset only the
|
|
343
|
+
// per-dispatch budget; `seen` is PRESERVED so redundancy detection
|
|
344
|
+
// carries across dispatches, and totalCalls keeps feeding the
|
|
345
|
+
// cumulative ceiling.
|
|
346
|
+
if (existing?.tierName === tierName) {
|
|
347
|
+
existing.cap = cap;
|
|
348
|
+
existing.calls = 0;
|
|
349
|
+
existing.dispatches += 1;
|
|
350
|
+
existing.trivial = trivial;
|
|
351
|
+
touch(input.sessionID);
|
|
352
|
+
return { registered: true, resumed: true };
|
|
236
353
|
}
|
|
354
|
+
|
|
355
|
+
// No prior state (first dispatch, or an idle-TTL sweep evicted it) or a
|
|
356
|
+
// different tier on the same sessionID: fresh session, fresh counters.
|
|
357
|
+
subagentCapState.set(input.sessionID, {
|
|
358
|
+
tierName,
|
|
359
|
+
cap,
|
|
360
|
+
calls: 0,
|
|
361
|
+
dispatches: 1,
|
|
362
|
+
totalCalls: 0,
|
|
363
|
+
seen: new Map(),
|
|
364
|
+
trivial,
|
|
365
|
+
});
|
|
366
|
+
touch(input.sessionID);
|
|
367
|
+
return { registered: true, resumed: false };
|
|
237
368
|
},
|
|
238
369
|
|
|
239
370
|
/**
|
|
@@ -247,6 +378,11 @@ export function createSessionStore() {
|
|
|
247
378
|
): void {
|
|
248
379
|
const state = subagentCapState.get(input.sessionID);
|
|
249
380
|
if (!state) return; // not a tracked subagent session
|
|
381
|
+
// Touch AFTER the early return: touching first created a lastTouch entry
|
|
382
|
+
// for every untracked session that ever ran a tool, and nothing else ever
|
|
383
|
+
// removed it. Tracked sessions still refresh here, because the read-only
|
|
384
|
+
// filter below runs later.
|
|
385
|
+
touch(input.sessionID);
|
|
250
386
|
if (!READ_ONLY_TOOLS.has(input.tool)) return;
|
|
251
387
|
|
|
252
388
|
const fp = fingerprintToolCall(input.tool, input.args);
|
|
@@ -254,6 +390,7 @@ export function createSessionStore() {
|
|
|
254
390
|
const isRedundant = previousCall !== undefined;
|
|
255
391
|
|
|
256
392
|
state.calls += 1;
|
|
393
|
+
state.totalCalls += 1;
|
|
257
394
|
if (!isRedundant) {
|
|
258
395
|
state.seen.set(fp, state.calls);
|
|
259
396
|
}
|
|
@@ -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
|
}
|
package/src/verify/checker.ts
CHANGED
|
@@ -22,6 +22,12 @@ export interface GraderRequest {
|
|
|
22
22
|
tier: string;
|
|
23
23
|
system: string;
|
|
24
24
|
prompt: string;
|
|
25
|
+
/**
|
|
26
|
+
* Producer working directory. When present, the grader session MUST be scoped
|
|
27
|
+
* to this directory so any file-existence / command claims the grader verifies
|
|
28
|
+
* are checked against the producer's cwd, not the grader's own session cwd.
|
|
29
|
+
*/
|
|
30
|
+
cwd?: string;
|
|
25
31
|
}
|
|
26
32
|
|
|
27
33
|
export interface GraderResult {
|
|
@@ -45,6 +51,8 @@ export interface CheckerInput {
|
|
|
45
51
|
artefact: ArtefactView;
|
|
46
52
|
producerTier: string;
|
|
47
53
|
producerSessionID: string;
|
|
54
|
+
/** Effective producer working directory; scopes the grader + informs its prompt. */
|
|
55
|
+
workingDir?: string;
|
|
48
56
|
}
|
|
49
57
|
|
|
50
58
|
// ---------------------------------------------------------------------------
|
|
@@ -76,9 +84,42 @@ export function atLeastProducerTier(
|
|
|
76
84
|
const GRADER_SYSTEM =
|
|
77
85
|
'You are an independent, skeptical verification grader. You did NOT produce this work and have no stake in it. Evaluate ONLY whether the artefact satisfies EACH acceptance criterion below. For every criterion, cite concrete evidence from the artefact. If the evidence is missing, ambiguous, partial, or you are uncertain for ANY reason, you MUST fail that criterion. Default to FAIL. Do not give the benefit of the doubt. Output ONLY a single JSON object on one line: {"pass": boolean, "reasons": string[]}. Set pass=true ONLY if every criterion is satisfied with cited evidence; otherwise pass=false with a reason per failed criterion.';
|
|
78
86
|
|
|
87
|
+
/** Upper bound on the working-directory string interpolated into the prompt. */
|
|
88
|
+
const MAX_WORKING_DIR_CHARS = 512;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Make an attacker-influenced value safe to interpolate into a single prompt
|
|
92
|
+
* line. The working directory reaches us from a delegate tool argument, i.e.
|
|
93
|
+
* from model output, so it is untrusted text: scrubText strips secrets, and
|
|
94
|
+
* collapsing newlines and control characters stops a crafted path from ending
|
|
95
|
+
* the line and forging further instructions to the grader.
|
|
96
|
+
*/
|
|
97
|
+
function sanitizeOneLine(value: string): string {
|
|
98
|
+
const cleaned = scrubText(value)
|
|
99
|
+
// C0 controls, DEL, the C1 block, and the Unicode LINE/PARAGRAPH
|
|
100
|
+
// SEPARATORS. U+2028 and U+2029 matter as much as \n here: plenty of
|
|
101
|
+
// renderers and tokenizers treat them as line breaks, so leaving them in
|
|
102
|
+
// would reopen the forged-instruction hole that stripping \n closes.
|
|
103
|
+
// eslint-disable-next-line no-control-regex
|
|
104
|
+
.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ")
|
|
105
|
+
.trim();
|
|
106
|
+
// A path has no legitimate reason to be long, and an unbounded one lets a
|
|
107
|
+
// caller push the real criteria out of the grader's attention.
|
|
108
|
+
return cleaned.length > MAX_WORKING_DIR_CHARS
|
|
109
|
+
? cleaned.slice(0, MAX_WORKING_DIR_CHARS) + "…(truncated)"
|
|
110
|
+
: cleaned;
|
|
111
|
+
}
|
|
112
|
+
|
|
79
113
|
export function buildGradingPrompt(input: CheckerInput): { system: string; prompt: string } {
|
|
80
114
|
const lines: string[] = [];
|
|
81
115
|
|
|
116
|
+
if (input.workingDir) {
|
|
117
|
+
lines.push(
|
|
118
|
+
`Producer working directory: ${sanitizeOneLine(input.workingDir)}. Any file-existence or command claims MUST be verified against THIS directory, not your own session directory.`,
|
|
119
|
+
);
|
|
120
|
+
lines.push("");
|
|
121
|
+
}
|
|
122
|
+
|
|
82
123
|
lines.push("## Acceptance criteria (ALL must be satisfied)");
|
|
83
124
|
for (let i = 0; i < input.criteria.length; i++) {
|
|
84
125
|
lines.push(`${i + 1}. ${input.criteria[i]}`);
|
|
@@ -181,7 +222,12 @@ export async function runChecker(input: CheckerInput, deps: CheckerDeps): Promis
|
|
|
181
222
|
// 4. Dispatch grader
|
|
182
223
|
let res: GraderResult;
|
|
183
224
|
try {
|
|
184
|
-
res = await deps.dispatchGrader({
|
|
225
|
+
res = await deps.dispatchGrader({
|
|
226
|
+
tier: graderTier,
|
|
227
|
+
system,
|
|
228
|
+
prompt,
|
|
229
|
+
...(input.workingDir ? { cwd: input.workingDir } : {}),
|
|
230
|
+
});
|
|
185
231
|
} catch (err) {
|
|
186
232
|
return {
|
|
187
233
|
pass: false,
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
// src/verify/deterministic.ts
|
|
2
2
|
// Deterministic verifier: runs DoD checks using injected seams (no real fs/exec imports).
|
|
3
|
-
// PURE: no Node built-ins; all I/O goes through DeterministicDeps
|
|
3
|
+
// PURE: no I/O-capable Node built-ins; all I/O goes through DeterministicDeps
|
|
4
|
+
// seams. ./paths is pure path math (node:path only) and keeps that contract.
|
|
4
5
|
|
|
5
6
|
import type { Check, DoD } from "./dod";
|
|
6
7
|
import type { Verdict, DeterministicDeps, MutexRegistry, ExecResult } from "./types";
|
|
7
8
|
import { scrubText } from "../guard/scrub";
|
|
9
|
+
import { resolveAgainst } from "./paths";
|
|
10
|
+
import { isAbsolute } from "node:path";
|
|
8
11
|
|
|
9
12
|
// ---------------------------------------------------------------------------
|
|
10
13
|
// MutexRegistry — per-key serialization via promise-chaining
|
|
@@ -113,9 +116,14 @@ interface CheckResult {
|
|
|
113
116
|
async function runFileExists(check: Check, deps: DeterministicDeps): Promise<CheckResult> {
|
|
114
117
|
try {
|
|
115
118
|
if (!check.path) return { ok: false, reason: "fileExists check missing 'path'" };
|
|
116
|
-
const
|
|
119
|
+
const resolved = resolveAgainst(deps.cwd, check.path);
|
|
120
|
+
const ok = await deps.fs.fileExists(resolved);
|
|
117
121
|
if (ok) return { ok: true, evidence: `exists: ${check.path}` };
|
|
118
|
-
|
|
122
|
+
// An absolute check path ignores deps.cwd entirely, so claiming the file
|
|
123
|
+
// was missing "in <cwd>" would name a directory the check never looked in.
|
|
124
|
+
return isAbsolute(check.path)
|
|
125
|
+
? { ok: false, reason: `file not found: ${resolved}` }
|
|
126
|
+
: { ok: false, reason: `file not found in ${deps.cwd}: ${check.path}` };
|
|
119
127
|
} catch (err) {
|
|
120
128
|
return { ok: false, reason: `fileExists check errored: ${scrubText(String(err))}` };
|
|
121
129
|
}
|
|
@@ -214,7 +222,7 @@ async function runSchemaMatch(check: Check, deps: DeterministicDeps): Promise<Ch
|
|
|
214
222
|
return { ok: false, reason: "schemaMatch requires 'path' and 'schema'" };
|
|
215
223
|
}
|
|
216
224
|
|
|
217
|
-
const targetRaw = await deps.fs.readFile(check.path);
|
|
225
|
+
const targetRaw = await deps.fs.readFile(resolveAgainst(deps.cwd, check.path));
|
|
218
226
|
let targetVal: unknown;
|
|
219
227
|
try {
|
|
220
228
|
targetVal = JSON.parse(targetRaw);
|
|
@@ -230,7 +238,7 @@ async function runSchemaMatch(check: Check, deps: DeterministicDeps): Promise<Ch
|
|
|
230
238
|
return { ok: false, reason: "schema is not valid JSON" };
|
|
231
239
|
}
|
|
232
240
|
} else {
|
|
233
|
-
const schemaRaw = await deps.fs.readFile(check.schema);
|
|
241
|
+
const schemaRaw = await deps.fs.readFile(resolveAgainst(deps.cwd, check.schema));
|
|
234
242
|
try {
|
|
235
243
|
schemaVal = JSON.parse(schemaRaw);
|
|
236
244
|
} catch {
|
package/src/verify/dispatch.ts
CHANGED
|
@@ -8,6 +8,12 @@ import type { RouterConfig } from "../router/config";
|
|
|
8
8
|
import { getActiveTiers } from "../router/protocol";
|
|
9
9
|
import { parseDoDFromDispatch, inferDoD } from "./dod";
|
|
10
10
|
import type { DoD, InferHints } from "./dod";
|
|
11
|
+
import { DEFAULT_IDLE_TTL_MS } from "../router/idle-sweep";
|
|
12
|
+
|
|
13
|
+
export interface ChangedFileStoreOptions {
|
|
14
|
+
/** Injectable clock (tests). Defaults to Date.now. */
|
|
15
|
+
now?: () => number;
|
|
16
|
+
}
|
|
11
17
|
|
|
12
18
|
/** Tools that mutate the workspace (mirrors the guard taxonomy). */
|
|
13
19
|
const WRITE_TOOLS = new Set(["write", "edit", "patch", "multiedit"]);
|
|
@@ -39,10 +45,23 @@ export function extractChangedFile(tool: string, args: unknown): ChangedFile | n
|
|
|
39
45
|
* by observing that session's own edit/write tool calls (ADR 0002 D3 — NOT a
|
|
40
46
|
* global git diff), which is concurrency-safe under interleaved subagents.
|
|
41
47
|
*/
|
|
42
|
-
export function createChangedFileStore() {
|
|
48
|
+
export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
|
|
49
|
+
const now = options.now ?? Date.now;
|
|
43
50
|
const bySession = new Map<string, Map<string, string>>();
|
|
51
|
+
const lastTouch = new Map<string, number>();
|
|
52
|
+
|
|
53
|
+
function touch(sessionID: string): void {
|
|
54
|
+
lastTouch.set(sessionID, now());
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function evict(sessionID: string): void {
|
|
58
|
+
bySession.delete(sessionID);
|
|
59
|
+
lastTouch.delete(sessionID);
|
|
60
|
+
}
|
|
61
|
+
|
|
44
62
|
return {
|
|
45
63
|
record(sessionID: string, tool: string, args: unknown): void {
|
|
64
|
+
touch(sessionID);
|
|
46
65
|
const cf = extractChangedFile(tool, args);
|
|
47
66
|
if (!cf) return;
|
|
48
67
|
let m = bySession.get(sessionID);
|
|
@@ -60,7 +79,13 @@ export function createChangedFileStore() {
|
|
|
60
79
|
return [...m.entries()].map(([path, status]) => ({ path, status }));
|
|
61
80
|
},
|
|
62
81
|
clear(sessionID: string): void {
|
|
63
|
-
|
|
82
|
+
evict(sessionID);
|
|
83
|
+
},
|
|
84
|
+
/** Evict every session idle for >= ttlMs. Future stamps are never evicted. */
|
|
85
|
+
sweep(nowMs: number = now(), ttlMs: number = DEFAULT_IDLE_TTL_MS): void {
|
|
86
|
+
for (const [sessionID, stamp] of [...lastTouch.entries()]) {
|
|
87
|
+
if (nowMs - stamp >= ttlMs) evict(sessionID);
|
|
88
|
+
}
|
|
64
89
|
},
|
|
65
90
|
};
|
|
66
91
|
}
|