opencode-model-router 1.4.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 +134 -12
- 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 +272 -321
- package/src/router/agent-options.ts +118 -0
- package/src/router/config.ts +555 -46
- package/src/router/idle-sweep.ts +35 -0
- package/src/router/jsonc.ts +92 -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
package/src/router/config.ts
CHANGED
|
@@ -2,6 +2,14 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "
|
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { parseJsonc } from "./jsonc";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Filename of the optional user overrides file (global and project copies share
|
|
9
|
+
* it). `.jsonc` so comments and trailing commas are allowed; mirrors the
|
|
10
|
+
* `opencode-model-router.*` prefix of the state file.
|
|
11
|
+
*/
|
|
12
|
+
export const OVERRIDE_FILENAME = "opencode-model-router.overrides.jsonc";
|
|
5
13
|
|
|
6
14
|
// ---------------------------------------------------------------------------
|
|
7
15
|
// Types
|
|
@@ -16,17 +24,66 @@ export interface ReasoningConfig {
|
|
|
16
24
|
summary?: "auto" | "always" | "never";
|
|
17
25
|
}
|
|
18
26
|
|
|
27
|
+
/**
|
|
28
|
+
* Provider-agnostic reasoning effort for a tier.
|
|
29
|
+
*
|
|
30
|
+
* `xhigh` and `max` exist because Anthropic's adaptive models accept them;
|
|
31
|
+
* OpenAI's `reasoning_effort` stops at `high`, so the registration path
|
|
32
|
+
* downgrades those two with a warning (see `src/router/agent-options.ts`).
|
|
33
|
+
*/
|
|
34
|
+
export const EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"] as const;
|
|
35
|
+
|
|
36
|
+
export type EffortLevel = (typeof EFFORT_LEVELS)[number];
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Wording style of the default system prompt handed to a tier agent.
|
|
40
|
+
*
|
|
41
|
+
* `prescriptive` uses the enumerated `tierPrompts` from tiers.json; `goal-oriented`
|
|
42
|
+
* uses the goal + constraints defaults in `src/router/prompts.ts`; `auto` (the
|
|
43
|
+
* default when unset) picks goal-oriented for strong models and prescriptive for
|
|
44
|
+
* the rest.
|
|
45
|
+
*/
|
|
46
|
+
export const PROMPT_STYLES = ["prescriptive", "goal-oriented", "auto"] as const;
|
|
47
|
+
|
|
48
|
+
export type PromptStyle = (typeof PROMPT_STYLES)[number];
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Shared model-generation pattern lists, matched case-insensitively as substrings
|
|
52
|
+
* of a tier's model ID.
|
|
53
|
+
*/
|
|
54
|
+
export interface ModelGenerationsConfig {
|
|
55
|
+
claude5x?: string[];
|
|
56
|
+
strong?: string[];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export const DEFAULT_CLAUDE5X_PATTERNS = ["claude-fable-5", "claude-mythos-5"];
|
|
60
|
+
// NOTE: strong is a superset of claude5x by construction — editing DEFAULT_CLAUDE5X_PATTERNS also widens strong. Deliberate: every Claude 5.x model is a strong model.
|
|
61
|
+
export const DEFAULT_STRONG_MODEL_PATTERNS = [...DEFAULT_CLAUDE5X_PATTERNS, "opus-4-8"];
|
|
62
|
+
|
|
19
63
|
export interface TierConfig {
|
|
20
64
|
model: string;
|
|
21
65
|
variant?: string;
|
|
66
|
+
/**
|
|
67
|
+
* Provider-agnostic effort. Loses to an explicit `thinking` budget on
|
|
68
|
+
* Anthropic and to an explicit `reasoning.effort` on OpenAI. When unset, no
|
|
69
|
+
* effort key is registered at all.
|
|
70
|
+
*/
|
|
71
|
+
effort?: EffortLevel;
|
|
22
72
|
thinking?: ThinkingConfig;
|
|
23
73
|
reasoning?: ReasoningConfig;
|
|
24
74
|
costRatio?: number;
|
|
25
75
|
color?: string;
|
|
26
|
-
|
|
76
|
+
/** Optional human-readable blurb shown in `/tiers` and the agent registration. */
|
|
77
|
+
description?: string;
|
|
27
78
|
steps?: number;
|
|
28
79
|
prompt?: string;
|
|
29
|
-
|
|
80
|
+
/**
|
|
81
|
+
* Wording style of the default prompt for this tier. Ignored when `prompt` is
|
|
82
|
+
* set — an explicit per-tier prompt always wins. Defaults to `auto`.
|
|
83
|
+
*/
|
|
84
|
+
promptStyle?: PromptStyle;
|
|
85
|
+
/** Optional use-case hints shown in `/tiers`. */
|
|
86
|
+
whenToUse?: string[];
|
|
30
87
|
}
|
|
31
88
|
|
|
32
89
|
export type Preset = Record<string, TierConfig>;
|
|
@@ -47,7 +104,13 @@ export interface EnforcementConfig {
|
|
|
47
104
|
envGate?: string;
|
|
48
105
|
perTier?: Record<string, "off" | "advisory" | "enforced">;
|
|
49
106
|
guard?: { readDraftCap?: number; sameOpRetryCap?: number; blockSelfScript?: boolean; deliverableFirst?: boolean; budget?: number; blockScriptWrites?: boolean };
|
|
50
|
-
verify?: { require?: "never" | "whenDoDPresent" | "always"; requireExplicitDoD?: boolean; preferDeterministic?: boolean; graderPolicy?: "atLeastProducerTier"; graderTemperature?: number; minGraderTier?: string
|
|
107
|
+
verify?: { require?: "never" | "whenDoDPresent" | "always"; requireExplicitDoD?: boolean; preferDeterministic?: boolean; graderPolicy?: "atLeastProducerTier"; graderTemperature?: number; minGraderTier?: string | null;
|
|
108
|
+
/** Ceiling for one producer `session.prompt` turn, in ms. Default 600000. */
|
|
109
|
+
delegateTimeoutMs?: number;
|
|
110
|
+
/** Ceiling for one grader `session.prompt` turn, in ms. Default 60000. */
|
|
111
|
+
graderTimeoutMs?: number;
|
|
112
|
+
/** Ceiling for the whole acceptance gate, in ms. Default 90000. */
|
|
113
|
+
gateBudgetMs?: number };
|
|
51
114
|
escalate?: { floorTier?: string | null; ladder?: string[]; maxAttemptsPerTier?: number; maxTotalAttempts?: number; costCeiling?: { base?: string; multiple?: number } };
|
|
52
115
|
proportional?: { trivialBypass?: boolean; trivialClassifier?: string };
|
|
53
116
|
}
|
|
@@ -63,6 +126,14 @@ export interface RouterConfig {
|
|
|
63
126
|
modes?: Record<string, ModeConfig>;
|
|
64
127
|
/** Global default prompts per tier name. A preset-level tier.prompt overrides this. */
|
|
65
128
|
tierPrompts?: Record<string, string>;
|
|
129
|
+
/**
|
|
130
|
+
* Optional user overrides for the goal-oriented tier prompts. The defaults ship
|
|
131
|
+
* in code (`src/router/prompts.ts`); an entry here replaces the built-in for
|
|
132
|
+
* that tier name.
|
|
133
|
+
*/
|
|
134
|
+
tierPromptsGoalOriented?: Record<string, string>;
|
|
135
|
+
/** Shared model-generation pattern lists; see {@link ModelGenerationsConfig}. */
|
|
136
|
+
modelGenerations?: ModelGenerationsConfig;
|
|
66
137
|
/** Read-only tool-call caps per tier, enforced at runtime via tool.execute.after banner injection. */
|
|
67
138
|
tierCaps?: Record<string, number>;
|
|
68
139
|
enforcement?: EnforcementConfig;
|
|
@@ -105,6 +176,92 @@ export function configPath(): string {
|
|
|
105
176
|
return join(getPluginRoot(), "tiers.json");
|
|
106
177
|
}
|
|
107
178
|
|
|
179
|
+
/**
|
|
180
|
+
* Path to the global user overrides file. Lives in the stable opencode config
|
|
181
|
+
* dir (next to the state file) so it survives plugin updates — unlike the
|
|
182
|
+
* bundled tiers.json, which sits in the cache dir and is overwritten on every
|
|
183
|
+
* update. Anything here is deep-merged over the bundled config.
|
|
184
|
+
*/
|
|
185
|
+
export function overridePath(): string {
|
|
186
|
+
return join(homedir(), ".config", "opencode", OVERRIDE_FILENAME);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Default location of the project-local overrides file
|
|
191
|
+
* (`.opencode/opencode-model-router.overrides.jsonc` in the current working
|
|
192
|
+
* directory). This is the path to *create* the file at; the actual lookup walks
|
|
193
|
+
* upward — see {@link findProjectOverride}. Used for display when no project
|
|
194
|
+
* file is found.
|
|
195
|
+
*
|
|
196
|
+
* The project file is deep-merged *after* (and therefore wins over) the global
|
|
197
|
+
* overrides file, so a team can commit a shared file that unifies routing for
|
|
198
|
+
* the project on top of each member's personal global file.
|
|
199
|
+
*/
|
|
200
|
+
export function localOverridePath(): string {
|
|
201
|
+
return join(process.cwd(), ".opencode", OVERRIDE_FILENAME);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Repo-root markers. Each is one-per-repository, so finding one means the
|
|
206
|
+
* ancestor is a project root. `package.json` is deliberately NOT a marker: in a
|
|
207
|
+
* monorepo, `<repo>/packages/app/package.json` would stop the walk before it
|
|
208
|
+
* ever reached `<repo>/.opencode/`.
|
|
209
|
+
*/
|
|
210
|
+
const REPO_MARKERS = [".git", ".hg", ".svn"] as const;
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Hard ceiling on how many levels the walk may climb above the starting
|
|
214
|
+
* directory. Deep working directories in a monorepo
|
|
215
|
+
* (`<repo>/packages/<pkg>/src/<area>/<sub>/…`) sit roughly 8 levels below the
|
|
216
|
+
* root, so 16 leaves generous headroom while keeping the walk bounded on trees
|
|
217
|
+
* that contain no repo marker at all.
|
|
218
|
+
*/
|
|
219
|
+
const MAX_WALK_DEPTH = 16;
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Locate the project-local overrides file by walking upward from the current
|
|
223
|
+
* working directory, so the project config is found even when opencode is
|
|
224
|
+
* launched from a subdirectory.
|
|
225
|
+
*
|
|
226
|
+
* The walk stops at the first of these, whichever comes first:
|
|
227
|
+
* - an ancestor containing a repo marker (`.git`, `.hg`, `.svn`), after
|
|
228
|
+
* checking that ancestor;
|
|
229
|
+
* - `MAX_WALK_DEPTH` levels above the starting directory;
|
|
230
|
+
* - the user's home directory, which is never treated as a project directory
|
|
231
|
+
* unless it is itself a repo root;
|
|
232
|
+
* - the filesystem root.
|
|
233
|
+
*
|
|
234
|
+
* The depth ceiling and the home-directory boundary matter because a directory
|
|
235
|
+
* tree with no repo marker anywhere would otherwise be walked all the way to the
|
|
236
|
+
* filesystem root, silently adopting an unrelated ancestor's override file.
|
|
237
|
+
* Returns the resolved path, or undefined when no file applies.
|
|
238
|
+
*/
|
|
239
|
+
export function findProjectOverride(): string | undefined {
|
|
240
|
+
let dir = process.cwd();
|
|
241
|
+
const home = homedir();
|
|
242
|
+
let depth = 0;
|
|
243
|
+
|
|
244
|
+
for (;;) {
|
|
245
|
+
const hasMarker = REPO_MARKERS.some((m) => existsSync(join(dir, m)));
|
|
246
|
+
|
|
247
|
+
// $HOME is not a project directory. Only look inside it when it is itself a
|
|
248
|
+
// repo root (a dotfiles repo), otherwise `~/.opencode/…` would be picked up
|
|
249
|
+
// by any unrelated scratch directory below it.
|
|
250
|
+
if (dir === home && !hasMarker) return undefined;
|
|
251
|
+
|
|
252
|
+
const candidate = join(dir, ".opencode", OVERRIDE_FILENAME);
|
|
253
|
+
if (existsSync(candidate)) return candidate;
|
|
254
|
+
|
|
255
|
+
if (hasMarker) return undefined; // reached the project root, no file
|
|
256
|
+
if (dir === home) return undefined; // home was a repo root; never go above it
|
|
257
|
+
if (++depth >= MAX_WALK_DEPTH) return undefined;
|
|
258
|
+
|
|
259
|
+
const parent = dirname(dir);
|
|
260
|
+
if (parent === dir) return undefined; // filesystem root
|
|
261
|
+
dir = parent;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
108
265
|
export function statePath(): string {
|
|
109
266
|
return join(
|
|
110
267
|
homedir(),
|
|
@@ -132,21 +289,17 @@ export function resolvePresetName(
|
|
|
132
289
|
);
|
|
133
290
|
}
|
|
134
291
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
const obj = raw as Record<string, unknown>;
|
|
292
|
+
/** True for a non-null, non-array object literal. */
|
|
293
|
+
function isPlainObject(v: unknown): v is Record<string, unknown> {
|
|
294
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
295
|
+
}
|
|
141
296
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
Array.isArray(obj.presets)
|
|
149
|
-
) {
|
|
297
|
+
/**
|
|
298
|
+
* Shape of every preset and every tier within it. Returns the presets map so
|
|
299
|
+
* the caller can hand it to validateActivePreset without re-narrowing.
|
|
300
|
+
*/
|
|
301
|
+
function validatePresets(obj: Record<string, unknown>): Record<string, unknown> {
|
|
302
|
+
if (!isPlainObject(obj.presets)) {
|
|
150
303
|
throw new Error("tiers.json: 'presets' must be a non-null object");
|
|
151
304
|
}
|
|
152
305
|
|
|
@@ -167,24 +320,77 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
167
320
|
);
|
|
168
321
|
}
|
|
169
322
|
const t = tier as Record<string, unknown>;
|
|
323
|
+
// `model` is the only required tier field — so an overrides file can define
|
|
324
|
+
// a new preset/tier with just `{ "model": "..." }`. The rest are optional
|
|
325
|
+
// and only type-checked when present.
|
|
170
326
|
if (typeof t.model !== "string" || !t.model) {
|
|
171
327
|
throw new Error(
|
|
172
328
|
`tiers.json: '${presetName}.${tierName}.model' must be a non-empty string`,
|
|
173
329
|
);
|
|
174
330
|
}
|
|
175
|
-
if (typeof t.description !== "string") {
|
|
331
|
+
if (t.description !== undefined && typeof t.description !== "string") {
|
|
176
332
|
throw new Error(
|
|
177
333
|
`tiers.json: '${presetName}.${tierName}.description' must be a string`,
|
|
178
334
|
);
|
|
179
335
|
}
|
|
180
|
-
if (!Array.isArray(t.whenToUse)) {
|
|
336
|
+
if (t.whenToUse !== undefined && !Array.isArray(t.whenToUse)) {
|
|
181
337
|
throw new Error(
|
|
182
338
|
`tiers.json: '${presetName}.${tierName}.whenToUse' must be an array`,
|
|
183
339
|
);
|
|
184
340
|
}
|
|
341
|
+
// A typo'd effort would otherwise load clean and be silently dropped at
|
|
342
|
+
// registration time, leaving a tier running at the provider default with
|
|
343
|
+
// only a warning nobody reads.
|
|
344
|
+
if (
|
|
345
|
+
t.effort !== undefined &&
|
|
346
|
+
!EFFORT_LEVELS.some((level) => level === t.effort)
|
|
347
|
+
) {
|
|
348
|
+
throw new Error(
|
|
349
|
+
`tiers.json: preset '${presetName}' tier '${tierName}': effort must be one of ${EFFORT_LEVELS.join(", ")}`,
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
// Same reasoning as effort: a typo'd style would otherwise load clean and
|
|
353
|
+
// silently fall back to the prescriptive prompt with nothing said.
|
|
354
|
+
if (
|
|
355
|
+
t.promptStyle !== undefined &&
|
|
356
|
+
!PROMPT_STYLES.some((style) => style === t.promptStyle)
|
|
357
|
+
) {
|
|
358
|
+
throw new Error(
|
|
359
|
+
`tiers.json: preset '${presetName}' tier '${tierName}': promptStyle must be one of ${PROMPT_STYLES.join("|")}`,
|
|
360
|
+
);
|
|
361
|
+
}
|
|
185
362
|
}
|
|
186
363
|
}
|
|
187
364
|
|
|
365
|
+
return presets;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** `activePreset` names a preset that exists. */
|
|
369
|
+
function validateActivePreset(
|
|
370
|
+
obj: Record<string, unknown>,
|
|
371
|
+
presets: Record<string, unknown>,
|
|
372
|
+
): void {
|
|
373
|
+
// `activePreset` has to name a preset that actually exists. It is the key most
|
|
374
|
+
// likely to be typo'd in a hand-edited override file, and without this the bad
|
|
375
|
+
// name loads clean and routing quietly runs on whatever the state file or the
|
|
376
|
+
// bundled default left behind, with nothing said. Matching is case-insensitive
|
|
377
|
+
// to agree with resolvePresetName, which is what `/preset` uses.
|
|
378
|
+
const activePresetName = obj.activePreset as string;
|
|
379
|
+
const presetNames = Object.keys(presets);
|
|
380
|
+
const activeExists =
|
|
381
|
+
Object.prototype.hasOwnProperty.call(presets, activePresetName) ||
|
|
382
|
+
presetNames.some(
|
|
383
|
+
(n) => n.toLowerCase() === activePresetName.trim().toLowerCase(),
|
|
384
|
+
);
|
|
385
|
+
if (!activeExists) {
|
|
386
|
+
throw new Error(
|
|
387
|
+
`tiers.json: 'activePreset' is '${activePresetName}', which is not a defined preset (defined: ${presetNames.join(", ")})`,
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** Top-level keys that are required, or optional with a fixed type. */
|
|
393
|
+
function validateCoreKeys(obj: Record<string, unknown>): void {
|
|
188
394
|
if (!Array.isArray(obj.rules)) {
|
|
189
395
|
throw new Error("tiers.json: 'rules' must be an array of strings");
|
|
190
396
|
}
|
|
@@ -194,14 +400,12 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
194
400
|
if (obj.antiNarration !== undefined && typeof obj.antiNarration !== "boolean") {
|
|
195
401
|
throw new Error("tiers.json: 'antiNarration' must be a boolean");
|
|
196
402
|
}
|
|
403
|
+
}
|
|
197
404
|
|
|
405
|
+
function validateModes(obj: Record<string, unknown>): void {
|
|
198
406
|
// Validate modes if present
|
|
199
407
|
if (obj.modes !== undefined) {
|
|
200
|
-
if (
|
|
201
|
-
typeof obj.modes !== "object" ||
|
|
202
|
-
obj.modes === null ||
|
|
203
|
-
Array.isArray(obj.modes)
|
|
204
|
-
) {
|
|
408
|
+
if (!isPlainObject(obj.modes)) {
|
|
205
409
|
throw new Error("tiers.json: 'modes' must be an object");
|
|
206
410
|
}
|
|
207
411
|
const modes = obj.modes as Record<string, unknown>;
|
|
@@ -222,14 +426,12 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
222
426
|
}
|
|
223
427
|
}
|
|
224
428
|
}
|
|
429
|
+
}
|
|
225
430
|
|
|
431
|
+
function validateTierCaps(obj: Record<string, unknown>): void {
|
|
226
432
|
// Validate tierCaps if present
|
|
227
433
|
if (obj.tierCaps !== undefined) {
|
|
228
|
-
if (
|
|
229
|
-
typeof obj.tierCaps !== "object" ||
|
|
230
|
-
obj.tierCaps === null ||
|
|
231
|
-
Array.isArray(obj.tierCaps)
|
|
232
|
-
) {
|
|
434
|
+
if (!isPlainObject(obj.tierCaps)) {
|
|
233
435
|
throw new Error("tiers.json: 'tierCaps' must be an object");
|
|
234
436
|
}
|
|
235
437
|
const tc = obj.tierCaps as Record<string, unknown>;
|
|
@@ -241,14 +443,12 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
241
443
|
}
|
|
242
444
|
}
|
|
243
445
|
}
|
|
446
|
+
}
|
|
244
447
|
|
|
448
|
+
function validateTierPrompts(obj: Record<string, unknown>): void {
|
|
245
449
|
// Validate tierPrompts if present
|
|
246
450
|
if (obj.tierPrompts !== undefined) {
|
|
247
|
-
if (
|
|
248
|
-
typeof obj.tierPrompts !== "object" ||
|
|
249
|
-
obj.tierPrompts === null ||
|
|
250
|
-
Array.isArray(obj.tierPrompts)
|
|
251
|
-
) {
|
|
451
|
+
if (!isPlainObject(obj.tierPrompts)) {
|
|
252
452
|
throw new Error("tiers.json: 'tierPrompts' must be an object");
|
|
253
453
|
}
|
|
254
454
|
const tp = obj.tierPrompts as Record<string, unknown>;
|
|
@@ -260,14 +460,49 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
260
460
|
}
|
|
261
461
|
}
|
|
262
462
|
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function validateTierPromptsGoalOriented(obj: Record<string, unknown>): void {
|
|
466
|
+
// Validate tierPromptsGoalOriented if present
|
|
467
|
+
if (obj.tierPromptsGoalOriented !== undefined) {
|
|
468
|
+
if (!isPlainObject(obj.tierPromptsGoalOriented)) {
|
|
469
|
+
throw new Error("tiers.json: 'tierPromptsGoalOriented' must be an object");
|
|
470
|
+
}
|
|
471
|
+
const tp = obj.tierPromptsGoalOriented as Record<string, unknown>;
|
|
472
|
+
for (const [tierName, prompt] of Object.entries(tp)) {
|
|
473
|
+
if (typeof prompt !== "string") {
|
|
474
|
+
throw new Error(
|
|
475
|
+
`tiers.json: tierPromptsGoalOriented.'${tierName}' must be a string`,
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
263
481
|
|
|
482
|
+
function validateModelGenerations(obj: Record<string, unknown>): void {
|
|
483
|
+
// Validate modelGenerations if present. Element-level non-strings are tolerated
|
|
484
|
+
// and filtered at match time rather than rejected here, so one bad entry in an
|
|
485
|
+
// override file cannot drop the whole layer.
|
|
486
|
+
if (obj.modelGenerations !== undefined) {
|
|
487
|
+
if (!isPlainObject(obj.modelGenerations)) {
|
|
488
|
+
throw new Error("tiers.json: modelGenerations must be an object");
|
|
489
|
+
}
|
|
490
|
+
const modelGenerations = obj.modelGenerations as Record<string, unknown>;
|
|
491
|
+
for (const key of ["claude5x", "strong"] as const) {
|
|
492
|
+
if (
|
|
493
|
+
modelGenerations[key] !== undefined &&
|
|
494
|
+
!Array.isArray(modelGenerations[key])
|
|
495
|
+
) {
|
|
496
|
+
throw new Error(`tiers.json: modelGenerations.${key} must be an array`);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function validateTaskPatterns(obj: Record<string, unknown>): void {
|
|
264
503
|
// Validate taskPatterns if present
|
|
265
504
|
if (obj.taskPatterns !== undefined) {
|
|
266
|
-
if (
|
|
267
|
-
typeof obj.taskPatterns !== "object" ||
|
|
268
|
-
obj.taskPatterns === null ||
|
|
269
|
-
Array.isArray(obj.taskPatterns)
|
|
270
|
-
) {
|
|
505
|
+
if (!isPlainObject(obj.taskPatterns)) {
|
|
271
506
|
throw new Error("tiers.json: 'taskPatterns' must be an object");
|
|
272
507
|
}
|
|
273
508
|
const tp = obj.taskPatterns as Record<string, unknown>;
|
|
@@ -279,14 +514,12 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
279
514
|
}
|
|
280
515
|
}
|
|
281
516
|
}
|
|
517
|
+
}
|
|
282
518
|
|
|
519
|
+
function validateEnforcement(obj: Record<string, unknown>): void {
|
|
283
520
|
// Validate enforcement if present (optional — absent means no enforcement)
|
|
284
521
|
if (obj.enforcement !== undefined) {
|
|
285
|
-
if (
|
|
286
|
-
typeof obj.enforcement !== "object" ||
|
|
287
|
-
obj.enforcement === null ||
|
|
288
|
-
Array.isArray(obj.enforcement)
|
|
289
|
-
) {
|
|
522
|
+
if (!isPlainObject(obj.enforcement)) {
|
|
290
523
|
throw new Error("tiers.json: enforcement must be an object");
|
|
291
524
|
}
|
|
292
525
|
const enforcement = obj.enforcement as Record<string, unknown>;
|
|
@@ -297,6 +530,13 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
297
530
|
);
|
|
298
531
|
}
|
|
299
532
|
}
|
|
533
|
+
if (enforcement.envGate !== undefined) {
|
|
534
|
+
if (typeof enforcement.envGate !== "string" || !enforcement.envGate) {
|
|
535
|
+
throw new Error(
|
|
536
|
+
"tiers.json: enforcement.envGate must be a non-empty string",
|
|
537
|
+
);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
300
540
|
if (
|
|
301
541
|
enforcement.verify !== undefined &&
|
|
302
542
|
typeof enforcement.verify === "object" &&
|
|
@@ -311,6 +551,53 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
311
551
|
'tiers.json: enforcement.verify.graderPolicy must be "atLeastProducerTier"',
|
|
312
552
|
);
|
|
313
553
|
}
|
|
554
|
+
// `null` is the shipped default and means "no floor" — same as absent.
|
|
555
|
+
if (
|
|
556
|
+
verify.minGraderTier !== undefined &&
|
|
557
|
+
verify.minGraderTier !== null &&
|
|
558
|
+
typeof verify.minGraderTier !== "string"
|
|
559
|
+
) {
|
|
560
|
+
throw new Error(
|
|
561
|
+
"tiers.json: enforcement.verify.minGraderTier must be a string or null",
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
if (verify.graderTemperature !== undefined) {
|
|
565
|
+
if (
|
|
566
|
+
typeof verify.graderTemperature !== "number" ||
|
|
567
|
+
!Number.isFinite(verify.graderTemperature) ||
|
|
568
|
+
verify.graderTemperature < 0
|
|
569
|
+
) {
|
|
570
|
+
throw new Error(
|
|
571
|
+
"tiers.json: enforcement.verify.graderTemperature must be a number >= 0",
|
|
572
|
+
);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
// Time-box ceilings. `>= 1` and not `>= 0`: a 0 or negative budget is
|
|
576
|
+
// almost always meant as "no timeout", and silently reading it as an
|
|
577
|
+
// immediately-expiring one would make every delegation fail. Reject it
|
|
578
|
+
// at the config boundary and say so, rather than guessing.
|
|
579
|
+
for (const key of [
|
|
580
|
+
"delegateTimeoutMs",
|
|
581
|
+
"graderTimeoutMs",
|
|
582
|
+
"gateBudgetMs",
|
|
583
|
+
] as const) {
|
|
584
|
+
const value = verify[key];
|
|
585
|
+
if (value !== undefined) {
|
|
586
|
+
if (!Number.isInteger(value) || (value as number) < 1) {
|
|
587
|
+
throw new Error(
|
|
588
|
+
`tiers.json: enforcement.verify.${key} must be an integer >= 1 (milliseconds)`,
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
if (
|
|
594
|
+
verify.requireExplicitDoD !== undefined &&
|
|
595
|
+
typeof verify.requireExplicitDoD !== "boolean"
|
|
596
|
+
) {
|
|
597
|
+
throw new Error(
|
|
598
|
+
"tiers.json: enforcement.verify.requireExplicitDoD must be a boolean",
|
|
599
|
+
);
|
|
600
|
+
}
|
|
314
601
|
}
|
|
315
602
|
if (
|
|
316
603
|
enforcement.escalate !== undefined &&
|
|
@@ -412,19 +699,239 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
412
699
|
throw new Error("enforcement.guard.blockScriptWrites must be a boolean");
|
|
413
700
|
}
|
|
414
701
|
}
|
|
702
|
+
for (const key of ["readDraftCap", "sameOpRetryCap"] as const) {
|
|
703
|
+
if (guard[key] !== undefined) {
|
|
704
|
+
if (
|
|
705
|
+
typeof guard[key] !== "number" ||
|
|
706
|
+
!Number.isInteger(guard[key]) ||
|
|
707
|
+
(guard[key] as number) < 0
|
|
708
|
+
) {
|
|
709
|
+
throw new Error(
|
|
710
|
+
`tiers.json: enforcement.guard.${key} must be an integer >= 0`,
|
|
711
|
+
);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
for (const key of ["blockSelfScript", "deliverableFirst"] as const) {
|
|
716
|
+
if (guard[key] !== undefined && typeof guard[key] !== "boolean") {
|
|
717
|
+
throw new Error(
|
|
718
|
+
`tiers.json: enforcement.guard.${key} must be a boolean`,
|
|
719
|
+
);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
if (
|
|
724
|
+
enforcement.proportional !== undefined &&
|
|
725
|
+
typeof enforcement.proportional === "object" &&
|
|
726
|
+
enforcement.proportional !== null
|
|
727
|
+
) {
|
|
728
|
+
const proportional = enforcement.proportional as Record<string, unknown>;
|
|
729
|
+
if (
|
|
730
|
+
proportional.trivialBypass !== undefined &&
|
|
731
|
+
typeof proportional.trivialBypass !== "boolean"
|
|
732
|
+
) {
|
|
733
|
+
throw new Error(
|
|
734
|
+
"tiers.json: enforcement.proportional.trivialBypass must be a boolean",
|
|
735
|
+
);
|
|
736
|
+
}
|
|
415
737
|
}
|
|
416
738
|
}
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/**
|
|
742
|
+
* Validate a raw parsed config. Strict and throwing by design: the bundled
|
|
743
|
+
* tiers.json must be valid on its own, and loadConfig turns a throw from an
|
|
744
|
+
* override layer into a warning plus a fallback rather than a crash.
|
|
745
|
+
*
|
|
746
|
+
* Section order matters and is preserved from when this was one function: a
|
|
747
|
+
* config with several problems reports the same first error it always did.
|
|
748
|
+
*/
|
|
749
|
+
export function validateConfig(raw: unknown): RouterConfig {
|
|
750
|
+
if (typeof raw !== "object" || raw === null) {
|
|
751
|
+
throw new Error("tiers.json: expected a JSON object at root");
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
const obj = raw as Record<string, unknown>;
|
|
756
|
+
|
|
757
|
+
if (typeof obj.activePreset !== "string" || !obj.activePreset) {
|
|
758
|
+
throw new Error("tiers.json: 'activePreset' must be a non-empty string");
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
const presets = validatePresets(obj);
|
|
762
|
+
validateActivePreset(obj, presets);
|
|
763
|
+
validateCoreKeys(obj);
|
|
764
|
+
validateModes(obj);
|
|
765
|
+
validateTierCaps(obj);
|
|
766
|
+
validateTierPrompts(obj);
|
|
767
|
+
validateTierPromptsGoalOriented(obj);
|
|
768
|
+
validateModelGenerations(obj);
|
|
769
|
+
validateTaskPatterns(obj);
|
|
770
|
+
validateEnforcement(obj);
|
|
417
771
|
|
|
418
772
|
return raw as RouterConfig;
|
|
419
773
|
}
|
|
420
774
|
|
|
775
|
+
/**
|
|
776
|
+
* Recursively merge `override` onto `base`. Plain objects merge key-by-key;
|
|
777
|
+
* arrays and scalars are replaced wholesale (so e.g. an overridden `rules` or
|
|
778
|
+
* `whenToUse` list replaces rather than appends). `undefined` values in the
|
|
779
|
+
* override are skipped so they never blow away a base value.
|
|
780
|
+
*/
|
|
781
|
+
export function deepMerge(base: unknown, override: unknown): unknown {
|
|
782
|
+
if (!isPlainObject(base) || !isPlainObject(override)) {
|
|
783
|
+
return override;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
const result: Record<string, unknown> = { ...base };
|
|
787
|
+
for (const [key, value] of Object.entries(override)) {
|
|
788
|
+
if (value === undefined) continue;
|
|
789
|
+
// `__proto__` from a parsed override would replace the merged object's own
|
|
790
|
+
// prototype rather than becoming a key. Whoever writes the config file can
|
|
791
|
+
// already do worse, so this is tidiness rather than a boundary, but a merge
|
|
792
|
+
// helper should not be the thing that reparents an object.
|
|
793
|
+
if (key === "__proto__" || key === "constructor") continue;
|
|
794
|
+
result[key] =
|
|
795
|
+
key in result && isPlainObject(result[key]) && isPlainObject(value)
|
|
796
|
+
? deepMerge(result[key], value)
|
|
797
|
+
: value;
|
|
798
|
+
}
|
|
799
|
+
return result;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/**
|
|
803
|
+
* Read and parse the optional user overrides file. Returns the parsed object,
|
|
804
|
+
* or undefined when the file is absent/unreadable/invalid. Parse and shape
|
|
805
|
+
* errors are surfaced via console.warn (never thrown) so a typo in the
|
|
806
|
+
* overrides file can never brick opencode startup — but the user still gets a
|
|
807
|
+
* visible reason why their override was ignored.
|
|
808
|
+
*/
|
|
809
|
+
function readOverridesAt(op: string): Record<string, unknown> | undefined {
|
|
810
|
+
let text: string;
|
|
811
|
+
try {
|
|
812
|
+
if (!existsSync(op)) return undefined;
|
|
813
|
+
text = readFileSync(op, "utf-8");
|
|
814
|
+
} catch (err) {
|
|
815
|
+
// The file is there but unreadable (permissions, a dangling symlink, a
|
|
816
|
+
// race with a delete). Every other failure below says so; staying silent
|
|
817
|
+
// here makes an unreadable override look exactly like an absent one.
|
|
818
|
+
console.warn(
|
|
819
|
+
`[model-router] ignoring ${op}: cannot read it — ${(err as Error).message}`,
|
|
820
|
+
);
|
|
821
|
+
return undefined;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
try {
|
|
825
|
+
const parsed = parseJsonc(text) as unknown;
|
|
826
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
827
|
+
console.warn(
|
|
828
|
+
`[model-router] ignoring ${op}: expected a JSON object at root`,
|
|
829
|
+
);
|
|
830
|
+
return undefined;
|
|
831
|
+
}
|
|
832
|
+
return parsed as Record<string, unknown>;
|
|
833
|
+
} catch (err) {
|
|
834
|
+
console.warn(
|
|
835
|
+
`[model-router] ignoring ${op}: invalid JSONC — ${(err as Error).message}`,
|
|
836
|
+
);
|
|
837
|
+
return undefined;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
/**
|
|
842
|
+
* The ordered override layers (lowest priority first): global, then
|
|
843
|
+
* project-local. Each present, well-formed file becomes a layer that is
|
|
844
|
+
* deep-merged over the ones before it.
|
|
845
|
+
*/
|
|
846
|
+
export interface OverrideLayer {
|
|
847
|
+
path: string;
|
|
848
|
+
data: Record<string, unknown>;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
function collectOverrideLayers(): OverrideLayer[] {
|
|
852
|
+
const layers: OverrideLayer[] = [];
|
|
853
|
+
// Lowest priority first: global, then project-local (found by upward search).
|
|
854
|
+
const paths = [overridePath(), findProjectOverride()];
|
|
855
|
+
for (const p of paths) {
|
|
856
|
+
if (!p) continue;
|
|
857
|
+
const data = readOverridesAt(p);
|
|
858
|
+
if (data) layers.push({ path: p, data });
|
|
859
|
+
}
|
|
860
|
+
return layers;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* Canonical per-tier defaults, keyed by the conventional tier names. These are
|
|
865
|
+
* the same values every bundled preset uses, so a preset defined in an overrides
|
|
866
|
+
* file with only `model` per tier gets a sensible cost ladder and turn budgets.
|
|
867
|
+
*/
|
|
868
|
+
const TIER_DEFAULTS: Record<string, { costRatio: number; steps: number }> = {
|
|
869
|
+
fast: { costRatio: 1, steps: 30 },
|
|
870
|
+
medium: { costRatio: 5, steps: 50 },
|
|
871
|
+
heavy: { costRatio: 20, steps: 120 },
|
|
872
|
+
};
|
|
873
|
+
const FALLBACK_TIER_DEFAULTS = { costRatio: 1, steps: 50 };
|
|
874
|
+
|
|
875
|
+
/**
|
|
876
|
+
* Fill in `costRatio`/`steps` for any tier that omits them, by tier name. Runs
|
|
877
|
+
* after merge so override-defined presets behave well without restating the
|
|
878
|
+
* conventional values; the effective numbers then show up in `/tiers` and the
|
|
879
|
+
* injected protocol. Bundled presets already set both, so this is a no-op there.
|
|
880
|
+
*/
|
|
881
|
+
function applyTierDefaults(cfg: RouterConfig): void {
|
|
882
|
+
for (const preset of Object.values(cfg.presets)) {
|
|
883
|
+
for (const [tierName, tier] of Object.entries(preset)) {
|
|
884
|
+
const d = TIER_DEFAULTS[tierName] ?? FALLBACK_TIER_DEFAULTS;
|
|
885
|
+
if (tier.costRatio === undefined) tier.costRatio = d.costRatio;
|
|
886
|
+
if (tier.steps === undefined) tier.steps = d.steps;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
|
|
421
891
|
export function loadConfig(): RouterConfig {
|
|
422
892
|
if (_cachedConfig && !_configDirty) {
|
|
423
893
|
return _cachedConfig;
|
|
424
894
|
}
|
|
425
895
|
|
|
426
|
-
const
|
|
427
|
-
const
|
|
896
|
+
const base = JSON.parse(readFileSync(configPath(), "utf-8"));
|
|
897
|
+
const layers = collectOverrideLayers();
|
|
898
|
+
|
|
899
|
+
// Bundled config must be valid on its own — throw otherwise (unchanged
|
|
900
|
+
// behaviour). Override layers are then applied on top.
|
|
901
|
+
let cfg = validateConfig(base);
|
|
902
|
+
|
|
903
|
+
if (layers.length > 0) {
|
|
904
|
+
const merge = (ls: OverrideLayer[]): unknown =>
|
|
905
|
+
ls.reduce<unknown>((acc, l) => deepMerge(acc, l.data), base);
|
|
906
|
+
|
|
907
|
+
try {
|
|
908
|
+
cfg = validateConfig(merge(layers));
|
|
909
|
+
} catch (err) {
|
|
910
|
+
// A bad override must never brick startup, and one broken file must not
|
|
911
|
+
// discard a good one. Fall back to the highest-priority layer that
|
|
912
|
+
// validates on its own (so a broken personal/global file still lets a
|
|
913
|
+
// shared project file apply), else the bundled defaults.
|
|
914
|
+
console.warn(
|
|
915
|
+
`[model-router] combined overrides are invalid (${(err as Error).message}); dropping conflicting layer(s)`,
|
|
916
|
+
);
|
|
917
|
+
for (let i = layers.length - 1; i >= 0; i--) {
|
|
918
|
+
try {
|
|
919
|
+
cfg = validateConfig(merge([layers[i]!]));
|
|
920
|
+
for (let j = 0; j < layers.length; j++) {
|
|
921
|
+
if (j !== i) {
|
|
922
|
+
console.warn(`[model-router] dropped override layer ${layers[j]!.path}`);
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
break;
|
|
926
|
+
} catch (singleErr) {
|
|
927
|
+
console.warn(
|
|
928
|
+
`[model-router] ignoring ${layers[i]!.path}: ${(singleErr as Error).message}`,
|
|
929
|
+
);
|
|
930
|
+
cfg = validateConfig(base);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
}
|
|
428
935
|
|
|
429
936
|
try {
|
|
430
937
|
if (existsSync(statePath())) {
|
|
@@ -448,6 +955,8 @@ export function loadConfig(): RouterConfig {
|
|
|
448
955
|
// Ignore state read errors and keep tiers.json defaults
|
|
449
956
|
}
|
|
450
957
|
|
|
958
|
+
applyTierDefaults(cfg);
|
|
959
|
+
|
|
451
960
|
_cachedConfig = cfg;
|
|
452
961
|
_configDirty = false;
|
|
453
962
|
return cfg;
|