opencode-model-router 1.4.0 → 1.5.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 CHANGED
@@ -241,9 +241,72 @@ In `~/.config/opencode/opencode.json`:
241
241
 
242
242
  ## Configuration
243
243
 
244
- All configuration lives in `tiers.json` at the plugin root, which is located inside the cached package directory in your home folder (e.g. `~/.cache/opencode/packages/opencode-model-router@latest/node_modules/opencode-model-router/tiers.json`).
244
+ The full default configuration lives in `tiers.json` at the plugin root. There are two ways to customize it.
245
245
 
246
- > ⚠️ **IMPORTANT**: You **must** edit this cached version of `tiers.json` for opencode to respect your changes and custom model configurations.
246
+ ### Recommended: overrides files (survive updates)
247
+
248
+ Anything in an overrides file is **deep-merged** over the bundled `tiers.json` on load — you only specify the keys you want to change; everything else falls back to the defaults. These files live outside the cache dir, so they are **not** wiped when the plugin updates. They're `.jsonc`, so `//` and `/* */` comments and trailing commas are allowed.
249
+
250
+ There are two layers, applied lowest→highest priority:
251
+
252
+ | Layer | Path | Scope |
253
+ |-------|------|-------|
254
+ | **Global** | `~/.config/opencode/opencode-model-router.overrides.jsonc` | Your personal defaults across all projects |
255
+ | **Project** | `<project>/.opencode/opencode-model-router.overrides.jsonc` | Per-project; commit it to share one routing config with your team |
256
+
257
+ The project file deep-merges over (and wins against) the global file, which in turn merges over the bundled defaults. So you can keep personal preferences globally while a committed project file unifies routing for everyone on the repo. The project file is found by searching upward from the working directory to the repo root (the nearest ancestor containing `.git`), so it is picked up even when you launch opencode from a subdirectory.
258
+
259
+ ```json
260
+ {
261
+ "presets": {
262
+ "github-copilot": {
263
+ "heavy": { "model": "github-copilot/claude-opus-4.8", "variant": "high" }
264
+ }
265
+ }
266
+ }
267
+ ```
268
+
269
+ The example above changes only the `@heavy` model/variant for the `github-copilot` preset; every other tier, preset, and setting keeps its bundled value. You can also override `costRatio`, `tierCaps`, `rules`, `modes`, `enforcement`, add an entirely new preset, etc. — any top-level key from `tiers.json`.
270
+
271
+ Run `/router overrides` to see both file paths, whether each exists, and the precedence order.
272
+
273
+ Merge semantics: objects merge recursively; arrays and scalars are replaced wholesale (so an overridden `rules`/`whenToUse` list *replaces* the default, it does not append). If a file is missing, malformed, or produces an invalid config, the plugin logs a `[model-router]` warning and drops just that layer (keeping the others) — a typo in one file can never break startup or discard a valid file.
274
+
275
+ #### Defining a whole new preset
276
+
277
+ An overrides file can add a brand-new preset, not just tweak the bundled ones. `model` is the only required field per tier. `costRatio` and `steps` are optional — when omitted they fall back to the conventional **`1` / `5` / `20`** and **`30` / `50` / `120`** (by tier name, the same values the bundled presets use); `description`/`whenToUse` are display-only.
278
+
279
+ ```jsonc
280
+ {
281
+ "presets": {
282
+ "openrouter": {
283
+ "fast": { "model": "openrouter/deepseek/deepseek-v3.2" },
284
+ "medium": { "model": "openrouter/qwen/qwen3-coder", "costRatio": 3, "steps": 60 },
285
+ "heavy": { "model": "openrouter/google/gemini-3-pro", "costRatio": 9, "steps": 140 },
286
+ },
287
+ },
288
+ // make it the active preset (or switch at runtime with `/preset openrouter`)
289
+ "activePreset": "openrouter",
290
+ }
291
+ ```
292
+
293
+ `@fast` omits `costRatio`/`steps`, so it gets the defaults (`1` / `30`); `@medium` and `@heavy` set their own to match their real economics. **Set `costRatio` whenever your models' relative costs differ from the default ladder** — it's the price signal the orchestrator uses to pick the cheapest adequate tier. (Routing by *task type* — `@fast`=read-only, `@medium`=implementation, `@heavy`=architecture — comes from the shared `taskPatterns`/`rules`, so it works for any preset automatically.)
294
+
295
+ The effective values, including any defaults, are shown by `/tiers`.
296
+
297
+ Restart opencode after adding a new preset so its tier subagents get registered. (Each model's provider must itself be configured in your `opencode.json`.)
298
+
299
+ > **`activePreset` / `activeMode` / `enforcement.mode` in an override file are _defaults_.** Runtime selections — `/preset`, `/budget`, `/router enforce` — are persisted to the state file (`~/.config/opencode/opencode-model-router.state.json`), which is applied **after** the override files and therefore wins. So the override's `activePreset` takes effect until you switch at runtime; if it ever "isn't taking", it's because a past `/preset` left a value in the state file — run `/preset <name>` again or delete that file. (The state file is machine-written, so the plugin never rewrites your hand-authored, commented override file.)
300
+
301
+ ### Advanced: edit the bundled `tiers.json` directly
302
+
303
+ For an npm install, `tiers.json` is **inside the cached package directory**, not your `~/.config/opencode/` folder — typically:
304
+
305
+ ```
306
+ ~/.cache/opencode/packages/opencode-model-router@latest/node_modules/opencode-model-router/tiers.json
307
+ ```
308
+
309
+ > ⚠️ Editing a copy elsewhere (e.g. under your global `npm` `node_modules`) has no effect, and this cached file is **overwritten on each plugin update**. Prefer the overrides file above unless you are developing the plugin from a local clone.
247
310
 
248
311
  ### Presets
249
312
 
@@ -600,7 +663,7 @@ The read-only cap banners described above are advisory: a well-behaved subagent
600
663
  ### The three enforcement layers
601
664
 
602
665
  - **Layer 1 — hard-block guard.** A `tool.execute.before` hook throws before a disallowed tool call executes, stopping budget overruns, redundant reads, and throwaway-script sidesteps in subagent sessions.
603
- - **Layer 2 — independent acceptance gate.** Every non-trivial delegation carries a Definition-of-Done (DoD) that is checked — deterministically or by an independent grader at ≥ the producer's tier — before the result is trusted. The producer never grades its own output.
666
+ - **Layer 2 — independent acceptance gate.** A non-trivial delegation carries a Definition-of-Done (DoD) that is checked — deterministically or by an independent grader at ≥ the producer's tier — before the result is trusted. The producer never grades its own output. Two cases are skipped rather than checked: a trivial dispatch carrying only an inferred DoD, and a dispatch whose inferred DoD has no deterministic checks and which changed no files. An explicit `[acceptance]` block is always verified. See [docs/VERIFICATION.md](docs/VERIFICATION.md).
604
667
  - **Layer 3 — quality-escalation ladder.** On a failed check: retry once, then escalate fast → medium → heavy, bounded by attempt and cost ceilings. The loop ends in an honest `status: unmet` rather than a fabricated pass.
605
668
 
606
669
  ### Two operating modes
@@ -640,6 +703,9 @@ Advisory is the default. To change the level:
640
703
  | `/budget` | Show available modes and which is active |
641
704
  | `/budget <mode>` | Switch routing mode (`normal`, `budget`, `quality`, `deep`) |
642
705
  | `/annotate-plan [path]` | Annotate a plan file with `[tier:X]` tags for each step |
706
+ | `/router overrides` | Show the global + project override file paths and merge precedence |
707
+ | `/router enforce <off\|advisory\|enforced>` | Set delegation-enforcement mode (persisted) |
708
+ | `/bypass [on\|off]` | Toggle the router off/on for the session |
643
709
 
644
710
  ## Plan annotation
645
711
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "OpenCode plugin that routes tasks to tiered subagents (fast/medium/heavy) based on complexity",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
package/src/index.ts CHANGED
@@ -6,6 +6,9 @@ import {
6
6
  resolvePresetName,
7
7
  writeState,
8
8
  invalidateConfigCache,
9
+ overridePath,
10
+ localOverridePath,
11
+ findProjectOverride,
9
12
  } from "./router/config";
10
13
  import type { RouterConfig, TierConfig, Preset, ModeConfig } from "./router/config";
11
14
  import { fingerprintToolCall } from "./guard/fingerprint";
@@ -31,7 +34,7 @@ import type { Cap, SubagentState } from "./router/sessions";
31
34
  import { createTrajectoryStore } from "./telemetry/trajectory";
32
35
  import { createGuardStore } from "./guard/store";
33
36
  import { guardBeforeCall, guardAfterCall, formatScorecard } from "./guard/enforce";
34
- import { mkdirSync, writeFileSync } from "node:fs";
37
+ import { mkdirSync, writeFileSync, existsSync } from "node:fs";
35
38
  import { tmpdir } from "node:os";
36
39
  import { join, isAbsolute } from "node:path";
37
40
  import { exec as nodeExec } from "node:child_process";
@@ -125,6 +128,28 @@ function buildRouterOutput(cfg: RouterConfig, args: string): string {
125
128
  "Usage: `/router enforce <off|advisory|enforced>`",
126
129
  ].join("\n");
127
130
  }
131
+ if (sub === "overrides") {
132
+ const globalP = overridePath();
133
+ const foundLocal = findProjectOverride();
134
+ const localP = foundLocal ?? localOverridePath();
135
+ const mark = (p: string) => (existsSync(p) ? "present" : "absent");
136
+ const localNote = foundLocal
137
+ ? ""
138
+ : ` _(create at \`${localP}\`; the project file is searched upward from the working dir to the repo root)_`;
139
+ return [
140
+ `# Model Router — config overrides`,
141
+ "",
142
+ "Config is loaded lowest→highest priority; each layer deep-merges over the previous one:",
143
+ "",
144
+ "1. bundled `tiers.json` (defaults)",
145
+ `2. global — \`${globalP}\` _(${mark(globalP)})_`,
146
+ `3. project — \`${localP}\` _(${mark(localP)})_${localNote}`,
147
+ "",
148
+ `Active preset: **${cfg.activePreset}**. Run \`/tiers\` to see the effective models after merging.`,
149
+ "",
150
+ "Create either file to customize models/tiers/presets without editing the cached `tiers.json`. Objects merge recursively; arrays and scalars are replaced.",
151
+ ].join("\n");
152
+ }
128
153
  const current = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
129
154
  return [
130
155
  `# Model Router`,
@@ -132,6 +157,7 @@ function buildRouterOutput(cfg: RouterConfig, args: string): string {
132
157
  "",
133
158
  "Commands:",
134
159
  "- `/router enforce <off|advisory|enforced>` — set hard-block enforcement (persisted)",
160
+ "- `/router overrides` — show the global + project override file paths and precedence",
135
161
  "- `/tiers`, `/preset`, `/budget`, `/bypass`, `/annotate-plan`",
136
162
  ].join("\n");
137
163
  }
@@ -181,9 +207,10 @@ function buildTiersOutput(cfg: RouterConfig): string {
181
207
  ? ` | reasoning: effort=${tier.reasoning.effort}`
182
208
  : "";
183
209
  lines.push(`## @${name} -> \`${tier.model}\`${thinkingStr}`);
184
- lines.push(tier.description);
210
+ if (tier.description) lines.push(tier.description);
185
211
  lines.push(`Steps: ${tier.steps ?? "default"}`);
186
- lines.push(`Use when: ${tier.whenToUse.join(", ")}\n`);
212
+ const whenToUse = tier.whenToUse ?? [];
213
+ lines.push(whenToUse.length ? `Use when: ${whenToUse.join(", ")}\n` : "");
187
214
  }
188
215
 
189
216
  lines.push("## Delegation Rules");
@@ -951,7 +978,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
951
978
  const agentDef: Record<string, unknown> = {
952
979
  model: tier.model,
953
980
  mode: "subagent",
954
- description: tier.description,
981
+ description: tier.description ?? `@${name} tier (${tier.model})`,
955
982
  maxSteps: tier.steps,
956
983
  prompt: finalPrompt,
957
984
  color: tier.color,
@@ -1030,7 +1057,8 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1030
1057
  };
1031
1058
  opencodeConfig.command["router"] = {
1032
1059
  template: "$ARGUMENTS",
1033
- description: "Model-router controls (e.g., /router enforce off|advisory|enforced)",
1060
+ description:
1061
+ "Model-router controls (e.g., /router enforce off|advisory|enforced, /router overrides)",
1034
1062
  };
1035
1063
  },
1036
1064
 
@@ -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
@@ -23,10 +31,12 @@ export interface TierConfig {
23
31
  reasoning?: ReasoningConfig;
24
32
  costRatio?: number;
25
33
  color?: string;
26
- description: string;
34
+ /** Optional human-readable blurb shown in `/tiers` and the agent registration. */
35
+ description?: string;
27
36
  steps?: number;
28
37
  prompt?: string;
29
- whenToUse: string[];
38
+ /** Optional use-case hints shown in `/tiers`. */
39
+ whenToUse?: string[];
30
40
  }
31
41
 
32
42
  export type Preset = Record<string, TierConfig>;
@@ -105,6 +115,92 @@ export function configPath(): string {
105
115
  return join(getPluginRoot(), "tiers.json");
106
116
  }
107
117
 
118
+ /**
119
+ * Path to the global user overrides file. Lives in the stable opencode config
120
+ * dir (next to the state file) so it survives plugin updates — unlike the
121
+ * bundled tiers.json, which sits in the cache dir and is overwritten on every
122
+ * update. Anything here is deep-merged over the bundled config.
123
+ */
124
+ export function overridePath(): string {
125
+ return join(homedir(), ".config", "opencode", OVERRIDE_FILENAME);
126
+ }
127
+
128
+ /**
129
+ * Default location of the project-local overrides file
130
+ * (`.opencode/opencode-model-router.overrides.jsonc` in the current working
131
+ * directory). This is the path to *create* the file at; the actual lookup walks
132
+ * upward — see {@link findProjectOverride}. Used for display when no project
133
+ * file is found.
134
+ *
135
+ * The project file is deep-merged *after* (and therefore wins over) the global
136
+ * overrides file, so a team can commit a shared file that unifies routing for
137
+ * the project on top of each member's personal global file.
138
+ */
139
+ export function localOverridePath(): string {
140
+ return join(process.cwd(), ".opencode", OVERRIDE_FILENAME);
141
+ }
142
+
143
+ /**
144
+ * Repo-root markers. Each is one-per-repository, so finding one means the
145
+ * ancestor is a project root. `package.json` is deliberately NOT a marker: in a
146
+ * monorepo, `<repo>/packages/app/package.json` would stop the walk before it
147
+ * ever reached `<repo>/.opencode/`.
148
+ */
149
+ const REPO_MARKERS = [".git", ".hg", ".svn"] as const;
150
+
151
+ /**
152
+ * Hard ceiling on how many levels the walk may climb above the starting
153
+ * directory. Deep working directories in a monorepo
154
+ * (`<repo>/packages/<pkg>/src/<area>/<sub>/…`) sit roughly 8 levels below the
155
+ * root, so 16 leaves generous headroom while keeping the walk bounded on trees
156
+ * that contain no repo marker at all.
157
+ */
158
+ const MAX_WALK_DEPTH = 16;
159
+
160
+ /**
161
+ * Locate the project-local overrides file by walking upward from the current
162
+ * working directory, so the project config is found even when opencode is
163
+ * launched from a subdirectory.
164
+ *
165
+ * The walk stops at the first of these, whichever comes first:
166
+ * - an ancestor containing a repo marker (`.git`, `.hg`, `.svn`), after
167
+ * checking that ancestor;
168
+ * - `MAX_WALK_DEPTH` levels above the starting directory;
169
+ * - the user's home directory, which is never treated as a project directory
170
+ * unless it is itself a repo root;
171
+ * - the filesystem root.
172
+ *
173
+ * The depth ceiling and the home-directory boundary matter because a directory
174
+ * tree with no repo marker anywhere would otherwise be walked all the way to the
175
+ * filesystem root, silently adopting an unrelated ancestor's override file.
176
+ * Returns the resolved path, or undefined when no file applies.
177
+ */
178
+ export function findProjectOverride(): string | undefined {
179
+ let dir = process.cwd();
180
+ const home = homedir();
181
+ let depth = 0;
182
+
183
+ for (;;) {
184
+ const hasMarker = REPO_MARKERS.some((m) => existsSync(join(dir, m)));
185
+
186
+ // $HOME is not a project directory. Only look inside it when it is itself a
187
+ // repo root (a dotfiles repo), otherwise `~/.opencode/…` would be picked up
188
+ // by any unrelated scratch directory below it.
189
+ if (dir === home && !hasMarker) return undefined;
190
+
191
+ const candidate = join(dir, ".opencode", OVERRIDE_FILENAME);
192
+ if (existsSync(candidate)) return candidate;
193
+
194
+ if (hasMarker) return undefined; // reached the project root, no file
195
+ if (dir === home) return undefined; // home was a repo root; never go above it
196
+ if (++depth >= MAX_WALK_DEPTH) return undefined;
197
+
198
+ const parent = dirname(dir);
199
+ if (parent === dir) return undefined; // filesystem root
200
+ dir = parent;
201
+ }
202
+ }
203
+
108
204
  export function statePath(): string {
109
205
  return join(
110
206
  homedir(),
@@ -167,17 +263,20 @@ export function validateConfig(raw: unknown): RouterConfig {
167
263
  );
168
264
  }
169
265
  const t = tier as Record<string, unknown>;
266
+ // `model` is the only required tier field — so an overrides file can define
267
+ // a new preset/tier with just `{ "model": "..." }`. The rest are optional
268
+ // and only type-checked when present.
170
269
  if (typeof t.model !== "string" || !t.model) {
171
270
  throw new Error(
172
271
  `tiers.json: '${presetName}.${tierName}.model' must be a non-empty string`,
173
272
  );
174
273
  }
175
- if (typeof t.description !== "string") {
274
+ if (t.description !== undefined && typeof t.description !== "string") {
176
275
  throw new Error(
177
276
  `tiers.json: '${presetName}.${tierName}.description' must be a string`,
178
277
  );
179
278
  }
180
- if (!Array.isArray(t.whenToUse)) {
279
+ if (t.whenToUse !== undefined && !Array.isArray(t.whenToUse)) {
181
280
  throw new Error(
182
281
  `tiers.json: '${presetName}.${tierName}.whenToUse' must be an array`,
183
282
  );
@@ -185,6 +284,24 @@ export function validateConfig(raw: unknown): RouterConfig {
185
284
  }
186
285
  }
187
286
 
287
+ // `activePreset` has to name a preset that actually exists. It is the key most
288
+ // likely to be typo'd in a hand-edited override file, and without this the bad
289
+ // name loads clean and routing quietly runs on whatever the state file or the
290
+ // bundled default left behind, with nothing said. Matching is case-insensitive
291
+ // to agree with resolvePresetName, which is what `/preset` uses.
292
+ const activePresetName = obj.activePreset as string;
293
+ const presetNames = Object.keys(presets);
294
+ const activeExists =
295
+ Object.prototype.hasOwnProperty.call(presets, activePresetName) ||
296
+ presetNames.some(
297
+ (n) => n.toLowerCase() === activePresetName.trim().toLowerCase(),
298
+ );
299
+ if (!activeExists) {
300
+ throw new Error(
301
+ `tiers.json: 'activePreset' is '${activePresetName}', which is not a defined preset (defined: ${presetNames.join(", ")})`,
302
+ );
303
+ }
304
+
188
305
  if (!Array.isArray(obj.rules)) {
189
306
  throw new Error("tiers.json: 'rules' must be an array of strings");
190
307
  }
@@ -418,13 +535,169 @@ export function validateConfig(raw: unknown): RouterConfig {
418
535
  return raw as RouterConfig;
419
536
  }
420
537
 
538
+ /**
539
+ * Recursively merge `override` onto `base`. Plain objects merge key-by-key;
540
+ * arrays and scalars are replaced wholesale (so e.g. an overridden `rules` or
541
+ * `whenToUse` list replaces rather than appends). `undefined` values in the
542
+ * override are skipped so they never blow away a base value.
543
+ */
544
+ export function deepMerge(base: unknown, override: unknown): unknown {
545
+ const isPlainObject = (v: unknown): v is Record<string, unknown> =>
546
+ typeof v === "object" && v !== null && !Array.isArray(v);
547
+
548
+ if (!isPlainObject(base) || !isPlainObject(override)) {
549
+ return override;
550
+ }
551
+
552
+ const result: Record<string, unknown> = { ...base };
553
+ for (const [key, value] of Object.entries(override)) {
554
+ if (value === undefined) continue;
555
+ // `__proto__` from a parsed override would replace the merged object's own
556
+ // prototype rather than becoming a key. Whoever writes the config file can
557
+ // already do worse, so this is tidiness rather than a boundary, but a merge
558
+ // helper should not be the thing that reparents an object.
559
+ if (key === "__proto__" || key === "constructor") continue;
560
+ result[key] =
561
+ key in result && isPlainObject(result[key]) && isPlainObject(value)
562
+ ? deepMerge(result[key], value)
563
+ : value;
564
+ }
565
+ return result;
566
+ }
567
+
568
+ /**
569
+ * Read and parse the optional user overrides file. Returns the parsed object,
570
+ * or undefined when the file is absent/unreadable/invalid. Parse and shape
571
+ * errors are surfaced via console.warn (never thrown) so a typo in the
572
+ * overrides file can never brick opencode startup — but the user still gets a
573
+ * visible reason why their override was ignored.
574
+ */
575
+ function readOverridesAt(op: string): Record<string, unknown> | undefined {
576
+ let text: string;
577
+ try {
578
+ if (!existsSync(op)) return undefined;
579
+ text = readFileSync(op, "utf-8");
580
+ } catch (err) {
581
+ // The file is there but unreadable (permissions, a dangling symlink, a
582
+ // race with a delete). Every other failure below says so; staying silent
583
+ // here makes an unreadable override look exactly like an absent one.
584
+ console.warn(
585
+ `[model-router] ignoring ${op}: cannot read it — ${(err as Error).message}`,
586
+ );
587
+ return undefined;
588
+ }
589
+
590
+ try {
591
+ const parsed = parseJsonc(text) as unknown;
592
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
593
+ console.warn(
594
+ `[model-router] ignoring ${op}: expected a JSON object at root`,
595
+ );
596
+ return undefined;
597
+ }
598
+ return parsed as Record<string, unknown>;
599
+ } catch (err) {
600
+ console.warn(
601
+ `[model-router] ignoring ${op}: invalid JSONC — ${(err as Error).message}`,
602
+ );
603
+ return undefined;
604
+ }
605
+ }
606
+
607
+ /**
608
+ * The ordered override layers (lowest priority first): global, then
609
+ * project-local. Each present, well-formed file becomes a layer that is
610
+ * deep-merged over the ones before it.
611
+ */
612
+ export interface OverrideLayer {
613
+ path: string;
614
+ data: Record<string, unknown>;
615
+ }
616
+
617
+ function collectOverrideLayers(): OverrideLayer[] {
618
+ const layers: OverrideLayer[] = [];
619
+ // Lowest priority first: global, then project-local (found by upward search).
620
+ const paths = [overridePath(), findProjectOverride()];
621
+ for (const p of paths) {
622
+ if (!p) continue;
623
+ const data = readOverridesAt(p);
624
+ if (data) layers.push({ path: p, data });
625
+ }
626
+ return layers;
627
+ }
628
+
629
+ /**
630
+ * Canonical per-tier defaults, keyed by the conventional tier names. These are
631
+ * the same values every bundled preset uses, so a preset defined in an overrides
632
+ * file with only `model` per tier gets a sensible cost ladder and turn budgets.
633
+ */
634
+ const TIER_DEFAULTS: Record<string, { costRatio: number; steps: number }> = {
635
+ fast: { costRatio: 1, steps: 30 },
636
+ medium: { costRatio: 5, steps: 50 },
637
+ heavy: { costRatio: 20, steps: 120 },
638
+ };
639
+ const FALLBACK_TIER_DEFAULTS = { costRatio: 1, steps: 50 };
640
+
641
+ /**
642
+ * Fill in `costRatio`/`steps` for any tier that omits them, by tier name. Runs
643
+ * after merge so override-defined presets behave well without restating the
644
+ * conventional values; the effective numbers then show up in `/tiers` and the
645
+ * injected protocol. Bundled presets already set both, so this is a no-op there.
646
+ */
647
+ function applyTierDefaults(cfg: RouterConfig): void {
648
+ for (const preset of Object.values(cfg.presets)) {
649
+ for (const [tierName, tier] of Object.entries(preset)) {
650
+ const d = TIER_DEFAULTS[tierName] ?? FALLBACK_TIER_DEFAULTS;
651
+ if (tier.costRatio === undefined) tier.costRatio = d.costRatio;
652
+ if (tier.steps === undefined) tier.steps = d.steps;
653
+ }
654
+ }
655
+ }
656
+
421
657
  export function loadConfig(): RouterConfig {
422
658
  if (_cachedConfig && !_configDirty) {
423
659
  return _cachedConfig;
424
660
  }
425
661
 
426
- const raw = JSON.parse(readFileSync(configPath(), "utf-8"));
427
- const cfg = validateConfig(raw);
662
+ const base = JSON.parse(readFileSync(configPath(), "utf-8"));
663
+ const layers = collectOverrideLayers();
664
+
665
+ // Bundled config must be valid on its own — throw otherwise (unchanged
666
+ // behaviour). Override layers are then applied on top.
667
+ let cfg = validateConfig(base);
668
+
669
+ if (layers.length > 0) {
670
+ const merge = (ls: OverrideLayer[]): unknown =>
671
+ ls.reduce<unknown>((acc, l) => deepMerge(acc, l.data), base);
672
+
673
+ try {
674
+ cfg = validateConfig(merge(layers));
675
+ } catch (err) {
676
+ // A bad override must never brick startup, and one broken file must not
677
+ // discard a good one. Fall back to the highest-priority layer that
678
+ // validates on its own (so a broken personal/global file still lets a
679
+ // shared project file apply), else the bundled defaults.
680
+ console.warn(
681
+ `[model-router] combined overrides are invalid (${(err as Error).message}); dropping conflicting layer(s)`,
682
+ );
683
+ for (let i = layers.length - 1; i >= 0; i--) {
684
+ try {
685
+ cfg = validateConfig(merge([layers[i]!]));
686
+ for (let j = 0; j < layers.length; j++) {
687
+ if (j !== i) {
688
+ console.warn(`[model-router] dropped override layer ${layers[j]!.path}`);
689
+ }
690
+ }
691
+ break;
692
+ } catch (singleErr) {
693
+ console.warn(
694
+ `[model-router] ignoring ${layers[i]!.path}: ${(singleErr as Error).message}`,
695
+ );
696
+ cfg = validateConfig(base);
697
+ }
698
+ }
699
+ }
700
+ }
428
701
 
429
702
  try {
430
703
  if (existsSync(statePath())) {
@@ -448,6 +721,8 @@ export function loadConfig(): RouterConfig {
448
721
  // Ignore state read errors and keep tiers.json defaults
449
722
  }
450
723
 
724
+ applyTierDefaults(cfg);
725
+
451
726
  _cachedConfig = cfg;
452
727
  _configDirty = false;
453
728
  return cfg;
@@ -0,0 +1,91 @@
1
+ // ---------------------------------------------------------------------------
2
+ // src/router/jsonc.ts — minimal JSONC support (comments + trailing commas).
3
+ //
4
+ // PURE, zero-dependency. `stripJsonc` removes `//` line comments, `/* */` block
5
+ // comments, and trailing commas before `}`/`]` — all string-aware, so a `//`,
6
+ // `/*`, or `,` inside a string value is preserved. `parseJsonc` then hands the
7
+ // cleaned text to JSON.parse. JSON is a subset of JSONC, so plain-JSON input
8
+ // passes through unchanged.
9
+ // ---------------------------------------------------------------------------
10
+
11
+ /** Remove comments and trailing commas from JSONC text (string-aware). */
12
+ export function stripJsonc(input: string): string {
13
+ let out = "";
14
+ let i = 0;
15
+ const n = input.length;
16
+ let inString = false;
17
+
18
+ while (i < n) {
19
+ const c = input[i]!;
20
+
21
+ if (inString) {
22
+ if (c === "\\" && i + 1 < n) {
23
+ out += c + input[i + 1]; // copy the escape pair verbatim
24
+ i += 2;
25
+ continue;
26
+ }
27
+ out += c;
28
+ if (c === '"') inString = false;
29
+ i++;
30
+ continue;
31
+ }
32
+
33
+ if (c === '"') {
34
+ inString = true;
35
+ out += c;
36
+ i++;
37
+ continue;
38
+ }
39
+
40
+ if (c === "/" && input[i + 1] === "/") {
41
+ i += 2;
42
+ while (i < n && input[i] !== "\n") i++; // keep the newline
43
+ continue;
44
+ }
45
+
46
+ if (c === "/" && input[i + 1] === "*") {
47
+ i += 2;
48
+ while (i < n && !(input[i] === "*" && input[i + 1] === "/")) i++;
49
+ i += 2; // skip the closing */
50
+ continue;
51
+ }
52
+
53
+ if (c === ",") {
54
+ // Drop the comma if the next significant token (skipping whitespace and
55
+ // comments) closes an object or array.
56
+ let j = i + 1;
57
+ while (j < n) {
58
+ const d = input[j]!;
59
+ if (d === " " || d === "\t" || d === "\n" || d === "\r") {
60
+ j++;
61
+ } else if (d === "/" && input[j + 1] === "/") {
62
+ j += 2;
63
+ while (j < n && input[j] !== "\n") j++;
64
+ } else if (d === "/" && input[j + 1] === "*") {
65
+ j += 2;
66
+ while (j < n && !(input[j] === "*" && input[j + 1] === "/")) j++;
67
+ j += 2;
68
+ } else {
69
+ break;
70
+ }
71
+ }
72
+ if (j < n && (input[j] === "}" || input[j] === "]")) {
73
+ i++; // trailing comma — skip it
74
+ continue;
75
+ }
76
+ out += c;
77
+ i++;
78
+ continue;
79
+ }
80
+
81
+ out += c;
82
+ i++;
83
+ }
84
+
85
+ return out;
86
+ }
87
+
88
+ /** Parse JSONC text (comments + trailing commas tolerated) into a value. */
89
+ export function parseJsonc(text: string): unknown {
90
+ return JSON.parse(stripJsonc(text));
91
+ }