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
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure presentation layer for the slash commands.
|
|
3
|
+
*
|
|
4
|
+
* Every function here is config/data in, markdown string out. No fs, no env,
|
|
5
|
+
* no state writes, no mutation of the config it is handed. The
|
|
6
|
+
* `command.execute.before` handlers in `src/index.ts` do the deciding and the
|
|
7
|
+
* persisting, then call these to render the result.
|
|
8
|
+
*
|
|
9
|
+
* The split exists because the command bodies used to interleave three
|
|
10
|
+
* different jobs — work out what the user asked for, persist it, and describe
|
|
11
|
+
* what happened — which made the output impossible to test without a state
|
|
12
|
+
* file on disk and a plugin instance to hang it off.
|
|
13
|
+
*/
|
|
14
|
+
import type { RouterConfig, ModeConfig } from "../router/config";
|
|
15
|
+
import { getActiveTiers } from "../router/protocol";
|
|
16
|
+
import { resolvePromptStyle } from "../router/prompts";
|
|
17
|
+
import type { Catalog, ModelIssue } from "../router/catalog";
|
|
18
|
+
|
|
19
|
+
/** `/tiers` */
|
|
20
|
+
export function buildTiersOutput(cfg: RouterConfig): string {
|
|
21
|
+
const tiers = getActiveTiers(cfg);
|
|
22
|
+
const lines: string[] = [
|
|
23
|
+
`# Model Delegation Tiers`,
|
|
24
|
+
`Active preset: **${cfg.activePreset}**\n`,
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
for (const [name, tier] of Object.entries(tiers)) {
|
|
28
|
+
const thinkingStr = tier.thinking
|
|
29
|
+
? ` | thinking: ${tier.thinking.budgetTokens} tokens`
|
|
30
|
+
: tier.reasoning
|
|
31
|
+
? ` | reasoning: effort=${tier.reasoning.effort}`
|
|
32
|
+
: "";
|
|
33
|
+
// The auto rule flips strong models to goal-oriented silently, so show the
|
|
34
|
+
// style the dispatch actually resolves to. An explicit `tier.prompt` wins
|
|
35
|
+
// outright (src/index.ts: `tier.prompt ?? selectTierPrompt(...)`).
|
|
36
|
+
const explicitStyle =
|
|
37
|
+
tier.promptStyle === "prescriptive" || tier.promptStyle === "goal-oriented";
|
|
38
|
+
const promptStr = tier.prompt
|
|
39
|
+
? " | prompt: custom"
|
|
40
|
+
: ` | prompt: ${resolvePromptStyle(tier.promptStyle, tier.model, cfg)} (${
|
|
41
|
+
explicitStyle ? "explicit" : "auto"
|
|
42
|
+
})`;
|
|
43
|
+
lines.push(`## @${name} -> \`${tier.model}\`${thinkingStr}${promptStr}`);
|
|
44
|
+
if (tier.description) lines.push(tier.description);
|
|
45
|
+
lines.push(`Steps: ${tier.steps ?? "default"}`);
|
|
46
|
+
const whenToUse = tier.whenToUse ?? [];
|
|
47
|
+
lines.push(whenToUse.length ? `Use when: ${whenToUse.join(", ")}\n` : "");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
lines.push("## Delegation Rules");
|
|
51
|
+
cfg.rules.forEach((r) => lines.push(`- ${r}`));
|
|
52
|
+
lines.push(`\nDefault tier: @${cfg.defaultTier}`);
|
|
53
|
+
lines.push(`\nAvailable presets: ${Object.keys(cfg.presets).join(", ")}`);
|
|
54
|
+
lines.push(`Switch with: \`/preset <name>\``);
|
|
55
|
+
lines.push(`Edit \`tiers.json\` to customize.`);
|
|
56
|
+
|
|
57
|
+
return lines.join("\n");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** `/preset` with no argument. */
|
|
61
|
+
export function buildPresetList(cfg: RouterConfig): string {
|
|
62
|
+
const lines = ["# Available Presets\n"];
|
|
63
|
+
for (const [name, tiers] of Object.entries(cfg.presets)) {
|
|
64
|
+
const active = name === cfg.activePreset ? " <- active" : "";
|
|
65
|
+
const models = Object.entries(tiers)
|
|
66
|
+
.map(([tier, t]) => `${tier}: ${t.model.split("/").pop()}`)
|
|
67
|
+
.join(", ");
|
|
68
|
+
lines.push(`- **${name}**${active}: ${models}`);
|
|
69
|
+
}
|
|
70
|
+
lines.push(`\nSwitch with: \`/preset <name>\``);
|
|
71
|
+
return lines.join("\n");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* `/preset <name>` after the switch has been persisted. Takes the resolved
|
|
76
|
+
* name, so the caller owns resolution and this only describes the outcome.
|
|
77
|
+
*/
|
|
78
|
+
export function buildPresetSwitched(cfg: RouterConfig, name: string): string {
|
|
79
|
+
const tiers = cfg.presets[name]!;
|
|
80
|
+
const models = Object.entries(tiers)
|
|
81
|
+
.map(([tier, t]) => ` @${tier} -> ${t.model}`)
|
|
82
|
+
.join("\n");
|
|
83
|
+
return [
|
|
84
|
+
`Preset switched to **${name}**.`,
|
|
85
|
+
"",
|
|
86
|
+
models,
|
|
87
|
+
"",
|
|
88
|
+
"Selection is now persisted in ~/.config/opencode/opencode-model-router.state.json.",
|
|
89
|
+
"Restart OpenCode for subagent model registration to take effect.",
|
|
90
|
+
"System prompt delegation rules update immediately.",
|
|
91
|
+
].join("\n");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** `/preset <name>` where the name resolves to nothing. */
|
|
95
|
+
export function buildUnknownPreset(cfg: RouterConfig, requested: string): string {
|
|
96
|
+
return `Unknown preset: "${requested}". Available: ${Object.keys(cfg.presets).join(", ")}`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** `/budget` when tiers.json defines no modes at all. */
|
|
100
|
+
export function buildNoModes(): string {
|
|
101
|
+
return 'No modes configured in tiers.json. Add a "modes" section to enable budget mode.';
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** `/budget` with no argument. */
|
|
105
|
+
export function buildBudgetList(cfg: RouterConfig): string {
|
|
106
|
+
const modes = cfg.modes ?? {};
|
|
107
|
+
const currentMode = cfg.activeMode || "normal";
|
|
108
|
+
const lines = ["# Routing Modes\n"];
|
|
109
|
+
for (const [name, mode] of Object.entries(modes)) {
|
|
110
|
+
const active = name === currentMode ? " <- active" : "";
|
|
111
|
+
lines.push(
|
|
112
|
+
`- **${name}**${active}: ${mode.description} (default tier: @${mode.defaultTier})`,
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
lines.push(`\nSwitch with: \`/budget <mode>\``);
|
|
116
|
+
return lines.join("\n");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** `/budget <mode>` after the switch has been persisted. */
|
|
120
|
+
export function buildBudgetSwitched(mode: ModeConfig, name: string): string {
|
|
121
|
+
return [
|
|
122
|
+
`Routing mode switched to **${name}**.`,
|
|
123
|
+
"",
|
|
124
|
+
mode.description,
|
|
125
|
+
`Default tier: @${mode.defaultTier}`,
|
|
126
|
+
...(mode.overrideRules?.length
|
|
127
|
+
? ["", "Active rules:", ...mode.overrideRules.map((r) => `- ${r}`)]
|
|
128
|
+
: []),
|
|
129
|
+
"",
|
|
130
|
+
"Mode change takes effect immediately on the next message.",
|
|
131
|
+
].join("\n");
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** `/budget <mode>` where the mode is not configured. */
|
|
135
|
+
export function buildUnknownMode(
|
|
136
|
+
modes: Record<string, ModeConfig>,
|
|
137
|
+
requested: string,
|
|
138
|
+
): string {
|
|
139
|
+
return `Unknown mode: "${requested}". Available: ${Object.keys(modes).join(", ")}`;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** `/bypass`, rendered from the resulting state rather than the argument. */
|
|
143
|
+
export function buildBypassMessage(bypassed: boolean): string {
|
|
144
|
+
const status = bypassed ? "ON" : "OFF";
|
|
145
|
+
const desc = bypassed
|
|
146
|
+
? "Model-router is **bypassed**. Delegation protocol, cap enforcement, and narration detection are disabled. The model will run without routing rules until you run `/bypass off` or restart OpenCode."
|
|
147
|
+
: "Model-router is **active**. Delegation protocol and all enforcement rules are in effect.";
|
|
148
|
+
return `# Bypass: ${status}\n\n${desc}`;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** `/router enforce <mode>` after the mode has been persisted. */
|
|
152
|
+
export function buildEnforceSet(mode: "off" | "advisory" | "enforced"): string {
|
|
153
|
+
const desc =
|
|
154
|
+
mode === "off"
|
|
155
|
+
? "Hard-block guard disabled (default routing behaviour)."
|
|
156
|
+
: mode === "advisory"
|
|
157
|
+
? "Guard evaluates and surfaces banners but never hard-blocks."
|
|
158
|
+
: "Guard hard-blocks subagent tool calls that violate budget / redundancy / self-script policy.";
|
|
159
|
+
return [
|
|
160
|
+
`Enforcement mode set to **${mode}** and persisted.`,
|
|
161
|
+
"",
|
|
162
|
+
desc,
|
|
163
|
+
"",
|
|
164
|
+
"Note: the `MODEL_ROUTER_ENFORCE` env var, when set to `0` or `1`, overrides this setting.",
|
|
165
|
+
].join("\n");
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** `/router enforce` with a missing or unrecognized mode. */
|
|
169
|
+
export function buildEnforceStatus(current: string): string {
|
|
170
|
+
return [
|
|
171
|
+
`Current enforcement mode: **${current}**`,
|
|
172
|
+
"",
|
|
173
|
+
"Usage: `/router enforce <off|advisory|enforced>`",
|
|
174
|
+
].join("\n");
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Everything `/router overrides` needs to know about the filesystem, resolved
|
|
179
|
+
* by the caller so this stays pure.
|
|
180
|
+
*/
|
|
181
|
+
export interface OverridesView {
|
|
182
|
+
globalPath: string;
|
|
183
|
+
globalPresent: boolean;
|
|
184
|
+
/** The project file that was found, or the default create-location. */
|
|
185
|
+
localPath: string;
|
|
186
|
+
localPresent: boolean;
|
|
187
|
+
/** False when localPath is a suggestion rather than a file that was found. */
|
|
188
|
+
localFound: boolean;
|
|
189
|
+
activePreset: string;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** `/router overrides` */
|
|
193
|
+
export function buildOverridesOutput(v: OverridesView): string {
|
|
194
|
+
const mark = (present: boolean) => (present ? "present" : "absent");
|
|
195
|
+
const localNote = v.localFound
|
|
196
|
+
? ""
|
|
197
|
+
: ` _(create at \`${v.localPath}\`; the project file is searched upward from the working dir to the repo root)_`;
|
|
198
|
+
return [
|
|
199
|
+
`# Model Router — config overrides`,
|
|
200
|
+
"",
|
|
201
|
+
"Config is loaded lowest→highest priority; each layer deep-merges over the previous one:",
|
|
202
|
+
"",
|
|
203
|
+
"1. bundled `tiers.json` (defaults)",
|
|
204
|
+
`2. global — \`${v.globalPath}\` _(${mark(v.globalPresent)})_`,
|
|
205
|
+
`3. project — \`${v.localPath}\` _(${mark(v.localPresent)})_${localNote}`,
|
|
206
|
+
"",
|
|
207
|
+
`Active preset: **${v.activePreset}**. Run \`/tiers\` to see the effective models after merging.`,
|
|
208
|
+
"",
|
|
209
|
+
"Create either file to customize models/tiers/presets without editing the cached `tiers.json`. Objects merge recursively; arrays and scalars are replaced.",
|
|
210
|
+
].join("\n");
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Bare `/router`. */
|
|
214
|
+
export function buildRouterHelp(current: string): string {
|
|
215
|
+
return [
|
|
216
|
+
`# Model Router`,
|
|
217
|
+
`Enforcement: **${current}**`,
|
|
218
|
+
"",
|
|
219
|
+
"Commands:",
|
|
220
|
+
"- `/router enforce <off|advisory|enforced>` — set hard-block enforcement (persisted)",
|
|
221
|
+
"- `/router overrides` — show the global + project override file paths and precedence",
|
|
222
|
+
"- `/router models [provider]` — list valid model ids from your configured providers",
|
|
223
|
+
"- `/tiers`, `/preset`, `/budget`, `/bypass`, `/annotate-plan`",
|
|
224
|
+
].join("\n");
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* `/router models [provider]`. Takes the catalog the caller fetched, so a
|
|
229
|
+
* failed or unavailable fetch is a null here rather than an exception path.
|
|
230
|
+
*/
|
|
231
|
+
export function buildModelsOutput(
|
|
232
|
+
catalog: Catalog | null,
|
|
233
|
+
filter: string,
|
|
234
|
+
orphanedStrongPatterns: string[] = [],
|
|
235
|
+
strongPatternNearMisses: Record<string, string[]> = {},
|
|
236
|
+
): string {
|
|
237
|
+
// Orphan patterns are pure config analysis, so they are appended to EVERY
|
|
238
|
+
// return path — including the catalog-unavailable ones, where the warning is
|
|
239
|
+
// just as valid.
|
|
240
|
+
const suffix =
|
|
241
|
+
orphanedStrongPatterns.length > 0
|
|
242
|
+
? "\n\n" +
|
|
243
|
+
formatOrphanedStrongPatterns(orphanedStrongPatterns, strongPatternNearMisses)
|
|
244
|
+
: "";
|
|
245
|
+
if (!catalog) {
|
|
246
|
+
return (
|
|
247
|
+
"Model catalog unavailable — could not query opencode's providers." + suffix
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
if (catalog.providers.length === 0) {
|
|
251
|
+
return "No providers are configured/authenticated in opencode." + suffix;
|
|
252
|
+
}
|
|
253
|
+
const f = filter.trim().toLowerCase();
|
|
254
|
+
const providers = f
|
|
255
|
+
? catalog.providers.filter((p) => p.id.toLowerCase() === f)
|
|
256
|
+
: catalog.providers;
|
|
257
|
+
if (providers.length === 0) {
|
|
258
|
+
return (
|
|
259
|
+
`No configured provider matches \`${filter.trim()}\`. Available: ${catalog.providers
|
|
260
|
+
.map((p) => p.id)
|
|
261
|
+
.join(", ")}.` + suffix
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const lines: string[] = ["# Model Router — available models", ""];
|
|
266
|
+
for (const p of providers) {
|
|
267
|
+
const name = p.name && p.name !== p.id ? ` (${p.name})` : "";
|
|
268
|
+
const def = p.defaultModel ? ` — default: \`${p.id}/${p.defaultModel}\`` : "";
|
|
269
|
+
lines.push(`## ${p.id}${name}${def}`);
|
|
270
|
+
const sorted = [...p.models].sort((a, b) => a.id.localeCompare(b.id));
|
|
271
|
+
if (sorted.length === 0) {
|
|
272
|
+
lines.push("- _(no models)_");
|
|
273
|
+
} else {
|
|
274
|
+
for (const m of sorted) {
|
|
275
|
+
const flag = m.status && m.status !== "active" ? ` _(${m.status})_` : "";
|
|
276
|
+
lines.push(`- \`${p.id}/${m.id}\`${flag}`);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
lines.push("");
|
|
280
|
+
}
|
|
281
|
+
lines.push(
|
|
282
|
+
"Paste any id above into an overrides file (`/router overrides` shows where).",
|
|
283
|
+
);
|
|
284
|
+
return lines.join("\n") + suffix;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Render strong-model patterns that match no model in the active preset (see
|
|
289
|
+
* `findOrphanedStrongPatterns`). Report-only — the router never edits the
|
|
290
|
+
* user's pattern list.
|
|
291
|
+
*/
|
|
292
|
+
export function formatOrphanedStrongPatterns(
|
|
293
|
+
patterns: string[],
|
|
294
|
+
nearMisses: Record<string, string[]> = {},
|
|
295
|
+
): string {
|
|
296
|
+
return [
|
|
297
|
+
"⚠ **Strong-model patterns matching no model your providers serve:**",
|
|
298
|
+
...patterns.map((p) => {
|
|
299
|
+
const near = nearMisses[p] ?? [];
|
|
300
|
+
if (near.length === 0) return `- \`${p}\``;
|
|
301
|
+
// Named separately from the generic rename hint below: when we can point
|
|
302
|
+
// at the served id, the user can fix it without going to look.
|
|
303
|
+
return `- \`${p}\` — served under a different separator: ${near
|
|
304
|
+
.slice(0, 3)
|
|
305
|
+
.map((r) => `\`${r}\``)
|
|
306
|
+
.join(", ")}`;
|
|
307
|
+
}),
|
|
308
|
+
"",
|
|
309
|
+
"This may silently change prompt-style resolution for tiers on `promptStyle: auto`. If a provider renamed a model, update `modelGenerations.strong` in your overrides file (`/router overrides`).",
|
|
310
|
+
].join("\n");
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Render model-validation issues for the active preset as a markdown block. */
|
|
314
|
+
export function formatModelIssues(issues: ModelIssue[]): string {
|
|
315
|
+
const lines: string[] = ["⚠ **Model issues in the active preset:**"];
|
|
316
|
+
for (const it of issues) {
|
|
317
|
+
const what =
|
|
318
|
+
it.kind === "provider-unknown" || it.kind === "fallback-provider-unknown"
|
|
319
|
+
? `provider \`${it.providerId}\` is not configured/authenticated` +
|
|
320
|
+
(it.kind === "fallback-provider-unknown"
|
|
321
|
+
? " — this fallback chain can never fire"
|
|
322
|
+
: "")
|
|
323
|
+
: it.kind === "fallback-preset-unknown"
|
|
324
|
+
? `chain entry \`${it.chainTarget}\` is not a defined preset and is silently dropped`
|
|
325
|
+
: it.kind === "model-deprecated"
|
|
326
|
+
? `\`${it.ref}\` is **deprecated**`
|
|
327
|
+
: `\`${it.ref}\` was not found`;
|
|
328
|
+
// Fallback issues are keyed by the chain's provider, not by a tier.
|
|
329
|
+
const where =
|
|
330
|
+
it.scope === "fallback" ? `${it.tier}[${it.providerId}]` : `@${it.tier}`;
|
|
331
|
+
let line = `- ${where}: ${what}.`;
|
|
332
|
+
if (it.suggestions.length > 0) {
|
|
333
|
+
line += ` Try: ${it.suggestions.map((s) => `\`${s}\``).join(", ")}.`;
|
|
334
|
+
}
|
|
335
|
+
lines.push(line);
|
|
336
|
+
}
|
|
337
|
+
lines.push(
|
|
338
|
+
"",
|
|
339
|
+
"Set a replacement in your overrides file (`/router overrides`), then re-run `/router`.",
|
|
340
|
+
);
|
|
341
|
+
return lines.join("\n");
|
|
342
|
+
}
|
package/src/guard/enforce.ts
CHANGED
|
@@ -19,6 +19,17 @@ import type { RouterConfig } from "../router/config";
|
|
|
19
19
|
*/
|
|
20
20
|
export const DEFAULT_GUARD_BUDGET = 25;
|
|
21
21
|
|
|
22
|
+
/**
|
|
23
|
+
* The cumulative ceiling spans resumed dispatches: it is this multiple of the
|
|
24
|
+
* effective per-dispatch budget (configured or default), giving resumed
|
|
25
|
+
* subagents bounded room without unbounded same-session loops.
|
|
26
|
+
*/
|
|
27
|
+
export const CUMULATIVE_BUDGET_MULTIPLIER = 3;
|
|
28
|
+
|
|
29
|
+
/** Default-case cumulative budget, retained for imports/tests. */
|
|
30
|
+
export const CUMULATIVE_GUARD_BUDGET =
|
|
31
|
+
DEFAULT_GUARD_BUDGET * CUMULATIVE_BUDGET_MULTIPLIER;
|
|
32
|
+
|
|
22
33
|
export interface GuardStoreLike {
|
|
23
34
|
ensure(sessionID: string, policy: GuardPolicy): GuardState;
|
|
24
35
|
get(sessionID: string): GuardState | undefined;
|
|
@@ -31,8 +42,10 @@ export interface GuardStoreLike {
|
|
|
31
42
|
* the deliverable-first clause — the honest common case (M5). */
|
|
32
43
|
export function buildGuardPolicy(cfg: RouterConfig, tier: string | null): GuardPolicy {
|
|
33
44
|
const g = cfg.enforcement?.guard ?? {};
|
|
45
|
+
const budget = g.budget ?? DEFAULT_GUARD_BUDGET;
|
|
34
46
|
return {
|
|
35
|
-
budget
|
|
47
|
+
budget,
|
|
48
|
+
cumulativeBudget: budget * CUMULATIVE_BUDGET_MULTIPLIER,
|
|
36
49
|
readDraftCap: g.readDraftCap ?? 3,
|
|
37
50
|
sameOpRetryCap: g.sameOpRetryCap ?? 1,
|
|
38
51
|
blockSelfScript: g.blockSelfScript ?? true,
|
package/src/guard/guards.ts
CHANGED
|
@@ -7,6 +7,8 @@ import { READ_ONLY_TOOLS } from "../router/sessions";
|
|
|
7
7
|
|
|
8
8
|
export interface GuardPolicy {
|
|
9
9
|
budget: number;
|
|
10
|
+
/** Cumulative tool-call ceiling across resumed dispatches. Unset = no ceiling. */
|
|
11
|
+
cumulativeBudget?: number;
|
|
10
12
|
readDraftCap: number;
|
|
11
13
|
sameOpRetryCap: number;
|
|
12
14
|
blockSelfScript: boolean;
|
|
@@ -33,7 +35,12 @@ export interface GuardDecision {
|
|
|
33
35
|
|
|
34
36
|
export interface GuardState {
|
|
35
37
|
budget: number;
|
|
38
|
+
/** Tool calls in the CURRENT dispatch (reset by guardStore.beginDispatch). */
|
|
36
39
|
toolCallCount: number;
|
|
40
|
+
/** Tool calls across all dispatches of this session (never reset). */
|
|
41
|
+
totalToolCallCount: number;
|
|
42
|
+
/** Dispatch rounds seen for this session (1 on first dispatch). */
|
|
43
|
+
dispatches: number;
|
|
37
44
|
readCount: number;
|
|
38
45
|
execCount: number;
|
|
39
46
|
selfScriptCount: number;
|
|
@@ -71,6 +78,8 @@ export function newGuardState(policy: GuardPolicy): GuardState {
|
|
|
71
78
|
return {
|
|
72
79
|
budget: policy.budget,
|
|
73
80
|
toolCallCount: 0,
|
|
81
|
+
totalToolCallCount: 0,
|
|
82
|
+
dispatches: 1,
|
|
74
83
|
readCount: 0,
|
|
75
84
|
execCount: 0,
|
|
76
85
|
selfScriptCount: 0,
|
|
@@ -178,6 +187,20 @@ export function evaluateGuards(
|
|
|
178
187
|
};
|
|
179
188
|
}
|
|
180
189
|
|
|
190
|
+
// CLAUSE 3b: cumulative budget across resumed dispatches. Without this, a
|
|
191
|
+
// session that keeps getting resumed gets a fresh per-dispatch budget every
|
|
192
|
+
// round — an unbounded loop that CLAUSE 3 alone cannot see.
|
|
193
|
+
if (
|
|
194
|
+
policy.cumulativeBudget !== undefined &&
|
|
195
|
+
state.totalToolCallCount >= policy.cumulativeBudget
|
|
196
|
+
) {
|
|
197
|
+
return {
|
|
198
|
+
allow: false,
|
|
199
|
+
guard: "cumulative_iteration_cap",
|
|
200
|
+
observation: `DENIED: cumulative tool-call budget ${policy.cumulativeBudget} exhausted across ${state.dispatches} dispatches. Stop now and emit your final answer with what you have.`,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
181
204
|
// CLAUSE 4: redundancy
|
|
182
205
|
if (kind === "read" && (state.seen.get(fp) ?? 0) >= policy.sameOpRetryCap) {
|
|
183
206
|
return {
|
|
@@ -230,6 +253,7 @@ export function updateState(
|
|
|
230
253
|
if (kind === "finish") return state;
|
|
231
254
|
|
|
232
255
|
state.toolCallCount += 1;
|
|
256
|
+
state.totalToolCallCount += 1;
|
|
233
257
|
|
|
234
258
|
const fp = fingerprintToolCall(call.tool, call.args);
|
|
235
259
|
|
|
@@ -306,6 +330,8 @@ export function trajectoryMetrics(state: GuardState): Record<string, unknown> {
|
|
|
306
330
|
state.execCount === 0 ? state.readCount : state.readCount / state.execCount,
|
|
307
331
|
self_script_count: state.selfScriptCount,
|
|
308
332
|
tool_call_count: state.toolCallCount,
|
|
333
|
+
total_tool_call_count: state.totalToolCallCount,
|
|
334
|
+
dispatches: state.dispatches,
|
|
309
335
|
deliverable_executed: state.deliverableExecuted,
|
|
310
336
|
blocked_count: state.blockedCount,
|
|
311
337
|
redundant_count: state.redundantCount,
|
package/src/guard/store.ts
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import { newGuardState } from "./guards";
|
|
2
2
|
import type { GuardState, GuardPolicy } from "./guards";
|
|
3
|
+
import { DEFAULT_IDLE_TTL_MS } from "../router/idle-sweep";
|
|
4
|
+
|
|
5
|
+
export interface GuardStoreOptions {
|
|
6
|
+
/** Injectable clock (tests). Defaults to Date.now. */
|
|
7
|
+
now?: () => number;
|
|
8
|
+
}
|
|
3
9
|
|
|
4
10
|
/**
|
|
5
11
|
* Per-plugin-instance store of guard state, keyed by sessionID. Mirrors the
|
|
@@ -7,12 +13,29 @@ import type { GuardState, GuardPolicy } from "./guards";
|
|
|
7
13
|
* singletons, so concurrent subagent sessions never share mutable state (M7).
|
|
8
14
|
* Also holds a per-session "pending note" used by advisory mode to defer a
|
|
9
15
|
* banner from the before-hook to the after-hook (where output is mutable).
|
|
16
|
+
*
|
|
17
|
+
* Idle-TTL: every mutating entry point refreshes a per-session lastTouch stamp;
|
|
18
|
+
* `sweep()` evicts sessions idle for at least ttlMs. No timers.
|
|
10
19
|
*/
|
|
11
|
-
export function createGuardStore() {
|
|
20
|
+
export function createGuardStore(options: GuardStoreOptions = {}) {
|
|
21
|
+
const now = options.now ?? Date.now;
|
|
12
22
|
const states = new Map<string, GuardState>();
|
|
13
23
|
const pendingNotes = new Map<string, string>();
|
|
24
|
+
const lastTouch = new Map<string, number>();
|
|
25
|
+
|
|
26
|
+
function touch(sessionID: string): void {
|
|
27
|
+
lastTouch.set(sessionID, now());
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function evict(sessionID: string): void {
|
|
31
|
+
states.delete(sessionID);
|
|
32
|
+
pendingNotes.delete(sessionID);
|
|
33
|
+
lastTouch.delete(sessionID);
|
|
34
|
+
}
|
|
35
|
+
|
|
14
36
|
return {
|
|
15
37
|
ensure(sessionID: string, policy: GuardPolicy): GuardState {
|
|
38
|
+
touch(sessionID);
|
|
16
39
|
let s = states.get(sessionID);
|
|
17
40
|
if (!s) {
|
|
18
41
|
s = newGuardState(policy);
|
|
@@ -24,16 +47,36 @@ export function createGuardStore() {
|
|
|
24
47
|
return states.get(sessionID);
|
|
25
48
|
},
|
|
26
49
|
setPendingNote(sessionID: string, note: string): void {
|
|
50
|
+
touch(sessionID);
|
|
27
51
|
pendingNotes.set(sessionID, note);
|
|
28
52
|
},
|
|
29
53
|
takePendingNote(sessionID: string): string | undefined {
|
|
54
|
+
touch(sessionID);
|
|
30
55
|
const n = pendingNotes.get(sessionID);
|
|
31
56
|
if (n !== undefined) pendingNotes.delete(sessionID);
|
|
32
57
|
return n;
|
|
33
58
|
},
|
|
59
|
+
/**
|
|
60
|
+
* Start a new dispatch round for an existing session: reset the
|
|
61
|
+
* per-dispatch tool-call count while preserving cumulative totals,
|
|
62
|
+
* redundancy fingerprints and deliverable state. No-op for sessions
|
|
63
|
+
* that were never guarded (nothing to reset).
|
|
64
|
+
*/
|
|
65
|
+
beginDispatch(sessionID: string): void {
|
|
66
|
+
const s = states.get(sessionID);
|
|
67
|
+
if (!s) return;
|
|
68
|
+
s.toolCallCount = 0;
|
|
69
|
+
s.dispatches += 1;
|
|
70
|
+
touch(sessionID);
|
|
71
|
+
},
|
|
34
72
|
clear(sessionID: string): void {
|
|
35
|
-
|
|
36
|
-
|
|
73
|
+
evict(sessionID);
|
|
74
|
+
},
|
|
75
|
+
/** Evict every session idle for >= ttlMs. Future stamps are never evicted. */
|
|
76
|
+
sweep(nowMs: number = now(), ttlMs: number = DEFAULT_IDLE_TTL_MS): void {
|
|
77
|
+
for (const [sessionID, stamp] of [...lastTouch.entries()]) {
|
|
78
|
+
if (nowMs - stamp >= ttlMs) evict(sessionID);
|
|
79
|
+
}
|
|
37
80
|
},
|
|
38
81
|
};
|
|
39
82
|
}
|