opencode-model-router 1.8.0 → 1.10.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 CHANGED
@@ -5,6 +5,131 @@ All notable changes to this project are documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.10.0] - 2026-08-20
9
+
10
+ Minor release. Config errors are caught at load instead of drifting to a later turn,
11
+ the logging path 1.9.0 introduced is finished — it was losing messages entirely in
12
+ short-lived processes, and one warning had never been routed through it at all — and
13
+ there is now a smoke lane that needs no credential and therefore actually runs.
14
+
15
+ ### Added
16
+
17
+ - **A credential-free smoke lane, running on every push.** `opencode debug agent`
18
+ loads the plugin, runs the `config` hook, resolves overrides and registers agents
19
+ with no API key and no model call, so an end-to-end check of registration costs
20
+ ~20s. The existing smoke lane is gated on secrets, which made it a green no-op on
21
+ forks — and meant the only test covering the `config` hook had been asserting the
22
+ pre-1.8.0 anthropic preset for a whole release without anyone finding out. Those
23
+ pins are repaired, and the new lane asserts that **stderr is empty**, which is
24
+ coverage unit tests structurally cannot provide: they hand the plugin a stub client,
25
+ so they have neither a real SDK receiver nor a real process's stderr to check.
26
+
27
+ - **A malformed tier `model` is rejected when the config loads, not on some later
28
+ turn.** `"model": "claude-sonnet-5"` — a ref missing its provider — used to validate
29
+ clean and only surface as a catalog issue on a turn that happened to have the catalog
30
+ in hand, or never, if the fetch failed. The `provider/model` shape needs no network,
31
+ so it is now decided at load, alongside the existing `effort` and `promptStyle`
32
+ checks. `parseModelRef` moved to `config.ts` (re-exported from `catalog.ts`) so load
33
+ validation and catalog lookup share one definition of well-formed: passing the first
34
+ now guarantees parsing in the second. Observed by @MetalbolicX in
35
+ [#17](https://github.com/marco-jardim/opencode-model-router/issues/17); implementation
36
+ is independent of the fork's.
37
+
38
+ Behaviour change for an existing malformed config: an overrides file carrying a bad
39
+ ref is now dropped with a warning naming the offending value, and the bundled
40
+ defaults stand. Startup is never blocked — the layer-drop path already guaranteed
41
+ that, and there is now a test pinning it for this case specifically.
42
+
43
+ ### Fixed
44
+
45
+ - **The orphaned-pattern warning no longer suggests a fix that cannot apply.** It still
46
+ told the user a provider rename was the likely cause and to update
47
+ `modelGenerations.strong` to match. Since 1.9.0 normalizes separators, a rename is
48
+ matched rather than orphaned, so the only way to reach the warning is a user-authored
49
+ pattern naming something genuinely absent. The copy now says that and forecloses the
50
+ separator fix explicitly.
51
+
52
+ - **Passive warnings are no longer lost in short-lived processes.** 1.9.0 sent them to
53
+ opencode's log fire-and-forget, which is right for a hook — a warning must never
54
+ block one — but in `opencode run` or `opencode debug` the post never settled before
55
+ the process exited, and the console fallback never fired because nothing had failed.
56
+ The warning reached neither the log nor the terminal. The plugin API has
57
+ `dispose?: () => Promise<void>`, and opencode calls *and awaits* it even on a
58
+ two-second run, so the logger now tracks in-flight posts and `dispose` drains them.
59
+ The tracked promise is the already-`catch`-wrapped one, so a failing post can never
60
+ reject out of teardown. ([#36](https://github.com/marco-jardim/opencode-model-router/issues/36))
61
+
62
+ - **The `opencode-anthropic-fix` dependency notice reaches the log instead of the
63
+ terminal.** 1.9.0 routed five of the six `warnAgentOptionsEffortOnce` call sites
64
+ through the logger and missed the one in `index.ts`, so that warning kept writing to
65
+ stderr — the exact symptom the change existed to remove. Found by running a real
66
+ process, not by a test; there is now a test.
67
+
68
+ ## [1.9.0] - 2026-08-20
69
+
70
+ Minor release. One real bug — prompt-style resolution broke when a provider renamed a
71
+ model across separators — plus the diagnostics that were compensating for it, which are
72
+ gone now that the cause is fixed.
73
+
74
+ ### Fixed
75
+
76
+ - **`promptStyle: "auto"` survives a provider renaming a model across separators.**
77
+ `isStrongModel` matched patterns case-insensitively but not separator-insensitively, so
78
+ the moment a provider shipped `claude-opus-4.8` where the pattern said `opus-4-8`, the
79
+ tier silently stopped resolving as strong and dropped from `goal-oriented` to
80
+ `prescriptive` — a different system prompt, with nothing said. Matching now normalizes
81
+ case and `.`, `-`, `_` on both sides. The provider boundary is preserved: `/` is not
82
+ normalized, so a pattern cannot match across it. A pattern consisting only of
83
+ separators now matches nothing instead of everything.
84
+
85
+ This is not hypothetical drift. Our own `tiers.json` carries the same model as
86
+ `anthropic/claude-haiku-4-5` and `github-copilot/claude-haiku-4.5`, because each
87
+ provider spells it its own way.
88
+
89
+ - **Passive warnings go to opencode's log instead of the terminal.** `console.warn`
90
+ from a plugin lands on the server's stderr, which the TUI does not own, so a warning
91
+ painted over whatever the terminal was drawing. Stale-model, orphaned-pattern and
92
+ agent-option warnings now post to `POST /log` via `client.app.log` with a
93
+ `model-router` service tag and structured `extra`. Fire-and-forget and fail-soft: a
94
+ server without the endpoint, a rejected post, a post that resolves reporting an error,
95
+ and a synchronous throw all fall back to `console.warn`, so a diagnostic is never
96
+ silently dropped.
97
+
98
+ Config-parse warnings deliberately still use `console.warn`. They are emitted from
99
+ `loadConfig`, which runs before a client exists, and they only fire on a malformed
100
+ override file — a case where being loud is the point.
101
+
102
+ ### Removed
103
+
104
+ - **`modelGenerations.claude5x`.** The field was declared, type-validated on load and
105
+ documented in three places, and never read by anything. `isStrongModel` reads
106
+ `strong`, and the default `strong` list was a module-level constant computed once
107
+ from the built-in array, so a user's `claude5x` could not reach it. Setting it did
108
+ nothing, and passing validation implied otherwise. An existing config carrying the key
109
+ still loads — unknown keys under `modelGenerations` are ignored, not rejected.
110
+
111
+ The note that `strong` was "a superset of `claude5x` by construction — every Claude 5.x
112
+ model is a strong model" is gone with it. It had stopped being true in both directions:
113
+ `claude-opus-5` was strong without being in `claude5x`, and `claude-sonnet-5` ships on
114
+ two tiers as a Claude 5 model that is deliberately not strong. `strong` is curated per
115
+ model, and the docs now say so.
116
+
117
+ - **Near-miss detection for orphaned strong-model patterns.** It existed to spot exactly
118
+ the rename the matcher now absorbs, so under the fixed matcher a near miss *is* a match
119
+ and can no longer be an orphan — the code was unreachable. The `/router models` output
120
+ and the passive warning both drop the "served under a different separator" hint. What
121
+ remains is narrower and honest: a pattern **you** wrote in `modelGenerations.strong`
122
+ that matches nothing your providers serve is still reported, because that is a claim
123
+ about your environment that turned out to be wrong. Shipped defaults are never
124
+ reported — most of a cross-provider union is unserved on any given install, and saying
125
+ so is noise you cannot act on.
126
+
127
+ ### Changed
128
+
129
+ - **`@opencode-ai/plugin` peer range is now `>=1.0.0 <2.0.0`.** The open-ended `>=1.0.0`
130
+ claimed compatibility with a major version that does not exist yet and whose plugin API
131
+ is by definition unknown.
132
+
8
133
  ## [1.8.0] - 2026-08-19
9
134
 
10
135
  Minor release: every vendor preset is refreshed to the current generation of models.
package/README.md CHANGED
@@ -684,16 +684,18 @@ for that tier name only, and tiers you do not list keep theirs.
684
684
 
685
685
  #### `modelGenerations`
686
686
 
687
- `modelGenerations` holds shared, case-insensitive substring patterns matched against a
688
- tier's model ID. Two lists exist:
687
+ `modelGenerations` holds substring patterns matched against a tier's model ID, with case
688
+ and separators (`.`, `-`, `_`) normalized on both sides — so `opus-4-8` matches
689
+ `opus-4.8`, and a provider renaming a model across separators cannot silently change how
690
+ it resolves. One list exists:
689
691
 
690
692
  | List | Default | What it drives |
691
693
  |------|---------|----------------|
692
694
  | `strong` | `["claude-fable-5", "claude-mythos-5", "opus-4-8", "claude-opus-5"]` | `promptStyle: "auto"` resolution — a match resolves to `goal-oriented`, everything else to `prescriptive` (`isStrongModel` in `src/router/prompts.ts`). |
693
- | `claude5x` | `["claude-fable-5", "claude-mythos-5"]` | The Claude 5.x generation list. In code it seeds the default `strong` list (`DEFAULT_STRONG_MODEL_PATTERNS` in `src/router/config.ts`), so `strong` is a superset of it by construction. |
694
695
 
695
- Only `strong` is read at match time, and setting it replaces the default list outright
696
- rather than extending it — include the built-in patterns you still want. Claude-specific
696
+ Setting `strong` replaces the default list outright rather than extending it — include the
697
+ built-in patterns you still want. The list is curated per model, not by generation:
698
+ `claude-sonnet-5` is a Claude 5 model that is deliberately not in it. Claude-specific
697
699
  prompt prefixes and the anti-narration detector do **not** use these lists; they match the
698
700
  model ID directly (`isClaudeModel` in `src/router/protocol.ts`).
699
701
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "1.8.0",
3
+ "version": "1.10.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",
@@ -9,6 +9,7 @@
9
9
  "test:watch": "vitest",
10
10
  "test:coverage": "vitest run --coverage",
11
11
  "smoke": "cross-env RUN_OC_SMOKE=1 vitest run --config vitest.smoke.config.ts test/smoke",
12
+ "smoke:keyless": "cross-env RUN_OC_SMOKE_KEYLESS=1 vitest run --config vitest.smoke.config.ts test/smoke/registration.smoke.test.ts test/smoke/subagent-tiers.smoke.test.ts",
12
13
  "typecheck": "tsc --noEmit"
13
14
  },
14
15
  "license": "GPL-3.0-only",
@@ -45,7 +46,7 @@
45
46
  "CHANGELOG.md"
46
47
  ],
47
48
  "peerDependencies": {
48
- "@opencode-ai/plugin": ">=1.0.0"
49
+ "@opencode-ai/plugin": ">=1.0.0 <2.0.0"
49
50
  },
50
51
  "devDependencies": {
51
52
  "@types/node": "^26.2.0",
@@ -232,7 +232,6 @@ export function buildModelsOutput(
232
232
  catalog: Catalog | null,
233
233
  filter: string,
234
234
  orphanedStrongPatterns: string[] = [],
235
- strongPatternNearMisses: Record<string, string[]> = {},
236
235
  ): string {
237
236
  // Orphan patterns are pure config analysis, so they are appended to EVERY
238
237
  // return path — including the catalog-unavailable ones, where the warning is
@@ -240,7 +239,7 @@ export function buildModelsOutput(
240
239
  const suffix =
241
240
  orphanedStrongPatterns.length > 0
242
241
  ? "\n\n" +
243
- formatOrphanedStrongPatterns(orphanedStrongPatterns, strongPatternNearMisses)
242
+ formatOrphanedStrongPatterns(orphanedStrongPatterns)
244
243
  : "";
245
244
  if (!catalog) {
246
245
  return (
@@ -285,28 +284,17 @@ export function buildModelsOutput(
285
284
  }
286
285
 
287
286
  /**
288
- * Render strong-model patterns that match no model in the active preset (see
289
- * `findOrphanedStrongPatterns`). Report-only — the router never edits the
287
+ * Render strong-model patterns that match no model the configured providers
288
+ * serve (see `findOrphanedStrongPatterns`). Only ever user-authored patterns:
289
+ * shipped defaults are not reported. Report-only — the router never edits the
290
290
  * user's pattern list.
291
291
  */
292
- export function formatOrphanedStrongPatterns(
293
- patterns: string[],
294
- nearMisses: Record<string, string[]> = {},
295
- ): string {
292
+ export function formatOrphanedStrongPatterns(patterns: string[]): string {
296
293
  return [
297
294
  "⚠ **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
- }),
295
+ ...patterns.map((p) => `- \`${p}\``),
308
296
  "",
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`).",
297
+ "You set these in `modelGenerations.strong`, so they decide nothing here and tiers on `promptStyle: auto` resolve without them. Matching already ignores case and separator style, so `opus-4-8` finds `opus-4.8` — a pattern listed above is absent, not merely spelled differently. Fix or drop it in your overrides file (`/router overrides`).",
310
298
  ].join("\n");
311
299
  }
312
300
 
package/src/index.ts CHANGED
@@ -46,9 +46,9 @@ import {
46
46
  assembleSystemPrompt,
47
47
  } from "./router/protocol";
48
48
  import { resolveEnforcementMode } from "./router/enforcement";
49
+ import { createPluginLogger } from "./router/logger";
49
50
  import {
50
51
  findOrphanedStrongPatterns,
51
- findStrongPatternNearMisses,
52
52
  normalizeCatalog,
53
53
  validateModels,
54
54
  } from "./router/catalog";
@@ -271,6 +271,11 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
271
271
  // current plugin lifetime (i.e., until OpenCode is restarted).
272
272
  let bypassed = false;
273
273
 
274
+ // Passive warnings go to opencode's log rather than stderr: console output
275
+ // from a plugin paints over the TUI. Falls back to console when the server
276
+ // has no /log endpoint. See src/router/logger.ts.
277
+ const logger = createPluginLogger(ctx.client);
278
+
274
279
  // Fetch and normalize opencode's live provider/model catalog. Best-effort:
275
280
  // returns null when the client call fails, e.g. the server is not ready yet.
276
281
  // The pure analysis (validateModels) lives in src/router/catalog.ts.
@@ -321,6 +326,13 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
321
326
  process.env.MODEL_ROUTER_VERIFIED_DELEGATE === "1";
322
327
 
323
328
  return {
329
+ // Warnings post to /log fire-and-forget, which loses the message when the
330
+ // process is about to exit — `opencode run` and `opencode debug` are short
331
+ // enough for that to be the normal case. Verified against opencode 1.18.16
332
+ // that dispose is both called and awaited, so flushing here is enough.
333
+ dispose: async () => {
334
+ await logger.flush();
335
+ },
324
336
  tool: {
325
337
  ...(enableDelegateTool ? { delegate: tool({
326
338
  description:
@@ -722,19 +734,16 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
722
734
  catalogWarned = true;
723
735
  const catalog = deferredCatalog;
724
736
  if (catalog) {
725
- // Strong-model patterns matching nothing any configured provider
726
- // serves, which can silently flip prompt-style resolution for
727
- // tiers on auto. Catalog-dependent, so it rides the same deferred
728
- // path — it is NOT emitted on turn 1.
737
+ // User-authored strong-model patterns matching nothing any
738
+ // configured provider serves. Shipped defaults are never reported
739
+ // (see findOrphanedStrongPatterns), so reaching here means the
740
+ // user wrote a claim about this environment that is false.
741
+ // Catalog-dependent, so it rides the same deferred path — it is
742
+ // NOT emitted on turn 1.
729
743
  for (const p of findOrphanedStrongPatterns(cfg, catalog)) {
730
- // Naming the served id turns "something is wrong" into a fix.
731
- const near = findStrongPatternNearMisses(p, catalog);
732
- const hint =
733
- near.length > 0
734
- ? ` — served under a different separator: ${near.slice(0, 3).join(", ")}`
735
- : "";
736
- console.warn(
737
- `[model-router] strong-model pattern '${p}' matches no model your providers serve — may silently change prompt-style resolution for tiers on auto${hint}`,
744
+ logger.warn(
745
+ `strong-model pattern '${p}' from your modelGenerations.strong matches no model your providers serve, so it decides nothing — separator style is already ignored when matching`,
746
+ { pattern: p },
738
747
  );
739
748
  }
740
749
  for (const it of validateModels(cfg, catalog)) {
@@ -747,9 +756,12 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
747
756
  it.scope === "fallback"
748
757
  ? `${it.tier}[${it.providerId}]`
749
758
  : `@${it.tier}`;
750
- console.warn(
751
- `[model-router] ${where} ${it.ref}: ${it.kind}${hint}`,
752
- );
759
+ logger.warn(`${where} ${it.ref}: ${it.kind}${hint}`, {
760
+ tier: it.tier,
761
+ ref: it.ref,
762
+ kind: it.kind,
763
+ suggestions: it.suggestions,
764
+ });
753
765
  }
754
766
  }
755
767
  }
@@ -1025,7 +1037,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1025
1037
  }
1026
1038
 
1027
1039
  // Apply provider-specific options
1028
- const opts = buildAgentOptions(tier, name);
1040
+ const opts = buildAgentOptions(tier, name, logger);
1029
1041
  if (Object.keys(opts).length > 0) {
1030
1042
  agentDef.options = opts;
1031
1043
  }
@@ -1033,6 +1045,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1033
1045
  warnAgentOptionsEffortOnce(
1034
1046
  "anthropic-effort-dependency",
1035
1047
  "effort on Anthropic models requires the opencode-anthropic-fix plugin (commit 307aea9+ for fable/mythos); non-adaptive Claude models (e.g. haiku) silently strip effort at the API layer, and without the plugin a top-level effort can break Claude-Code billing fingerprinting",
1048
+ logger,
1036
1049
  );
1037
1050
  }
1038
1051
 
@@ -1210,18 +1223,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1210
1223
  if (sub === "models") {
1211
1224
  const catalog = await fetchCatalog();
1212
1225
  const orphans = catalog ? findOrphanedStrongPatterns(cfg, catalog) : [];
1213
- const nearMisses: Record<string, string[]> = {};
1214
- if (catalog) {
1215
- for (const p of orphans) {
1216
- nearMisses[p] = findStrongPatternNearMisses(p, catalog);
1217
- }
1218
- }
1219
- text = buildModelsOutput(
1220
- catalog,
1221
- parts.slice(1).join(" "),
1222
- orphans,
1223
- nearMisses,
1224
- );
1226
+ text = buildModelsOutput(catalog, parts.slice(1).join(" "), orphans);
1225
1227
  } else {
1226
1228
  text = buildRouterOutput(cfg, args);
1227
1229
  // On the bare status view, surface stale or missing models inline.
@@ -1,3 +1,4 @@
1
+ import type { PluginLogger } from "./logger";
1
2
  /**
2
3
  * Registration-path agent options.
3
4
  *
@@ -25,9 +26,19 @@ import { isClaudeModel } from "./protocol";
25
26
  // two different mistakes are still two different warnings.
26
27
  const warnedAgentOptionsEffort = new Set<string>();
27
28
 
28
- export function warnAgentOptionsEffortOnce(key: string, message: string): void {
29
+ export function warnAgentOptionsEffortOnce(
30
+ key: string,
31
+ message: string,
32
+ logger?: PluginLogger,
33
+ ): void {
29
34
  if (warnedAgentOptionsEffort.has(key)) return;
30
35
  warnedAgentOptionsEffort.add(key);
36
+ // Optional so this module keeps working for callers that have no client
37
+ // (unit tests, and buildAgentOptions being called directly).
38
+ if (logger) {
39
+ logger.warn(message, { key });
40
+ return;
41
+ }
31
42
  console.warn(`[model-router] ${message}`);
32
43
  }
33
44
 
@@ -54,7 +65,11 @@ function isOpenAIModel(model: string): boolean {
54
65
  * only ever present when something asked for it — an unset `effort` leaves no
55
66
  * trace in the returned object.
56
67
  */
57
- export function buildAgentOptions(tier: TierConfig, tierName = tier.model): Record<string, unknown> {
68
+ export function buildAgentOptions(
69
+ tier: TierConfig,
70
+ tierName = tier.model,
71
+ logger?: PluginLogger,
72
+ ): Record<string, unknown> {
58
73
  const opts: Record<string, unknown> = {};
59
74
 
60
75
  // Anthropic thinking config. A zero budget asks for no extended thinking at
@@ -68,6 +83,7 @@ export function buildAgentOptions(tier: TierConfig, tierName = tier.model): Reco
68
83
  warnAgentOptionsEffortOnce(
69
84
  `thinking-zero:${tierName}`,
70
85
  `tier ${tierName}: thinking.budgetTokens: 0 is ignored`,
86
+ logger,
71
87
  );
72
88
  }
73
89
 
@@ -96,6 +112,7 @@ export function buildAgentOptions(tier: TierConfig, tierName = tier.model): Reco
96
112
  warnAgentOptionsEffortOnce(
97
113
  `anthropic-conflict:${tierName}`,
98
114
  `tier ${tierName}: both thinking and effort set; explicit thinking wins`,
115
+ logger,
99
116
  );
100
117
  } else {
101
118
  opts.effort = effort;
@@ -105,11 +122,13 @@ export function buildAgentOptions(tier: TierConfig, tierName = tier.model): Reco
105
122
  warnAgentOptionsEffortOnce(
106
123
  `openai-conflict:${tierName}`,
107
124
  `tier ${tierName}: both reasoning.effort and effort set; explicit reasoning wins`,
125
+ logger,
108
126
  );
109
127
  } else if (effort === "xhigh" || effort === "max") {
110
128
  warnAgentOptionsEffortOnce(
111
129
  `openai-downgrade:${tierName}:${effort}`,
112
130
  `tier ${tierName}: downgrading effort '${effort}' to 'high' because OpenAI reasoning_effort only supports low, medium, or high`,
131
+ logger,
113
132
  );
114
133
  opts.reasoning_effort = "high";
115
134
  } else {
@@ -119,6 +138,7 @@ export function buildAgentOptions(tier: TierConfig, tierName = tier.model): Reco
119
138
  warnAgentOptionsEffortOnce(
120
139
  `unknown-provider:${tierName}`,
121
140
  `tier ${tierName}: effort ignored for unknown provider family '${tier.model}'`,
141
+ logger,
122
142
  );
123
143
  }
124
144
  }
@@ -5,7 +5,12 @@
5
5
  // raw payload is handed here for normalization and analysis.
6
6
  // ---------------------------------------------------------------------------
7
7
 
8
- import { DEFAULT_STRONG_MODEL_PATTERNS, type RouterConfig } from "./config";
8
+ import {
9
+ DEFAULT_STRONG_MODEL_PATTERNS,
10
+ parseModelRef,
11
+ type RouterConfig,
12
+ } from "./config";
13
+ import { flattenModelID } from "./prompts";
9
14
  import { getActiveTiers } from "./protocol";
10
15
 
11
16
  export interface CatalogModel {
@@ -79,17 +84,12 @@ export function isCatalogEmpty(catalog: Catalog): boolean {
79
84
  }
80
85
 
81
86
  /**
82
- * Split a tier model reference (`"provider/model"`) into its parts. Splits on
83
- * the FIRST slash only, so multi-segment model ids (e.g.
84
- * `openrouter/deepseek/deepseek-v3.2`) keep their full model id.
87
+ * Re-exported from config.ts, where it lives because the `provider/model` shape
88
+ * is a property of the config format rather than of the catalog. Config load
89
+ * rejects a ref this cannot parse, so by the time a ref reaches the lookups
90
+ * below it has already been through the same function.
85
91
  */
86
- export function parseModelRef(
87
- ref: string,
88
- ): { providerId: string; modelId: string } | undefined {
89
- const i = ref.indexOf("/");
90
- if (i <= 0 || i === ref.length - 1) return undefined;
91
- return { providerId: ref.slice(0, i), modelId: ref.slice(i + 1) };
92
- }
92
+ export { parseModelRef };
93
93
 
94
94
  function findProvider(
95
95
  catalog: Catalog,
@@ -145,19 +145,24 @@ export function suggestModels(
145
145
  * {@link DEFAULT_STRONG_MODEL_PATTERNS}) that match NO model in the live
146
146
  * catalog. Report-only: the router never rewrites the user's pattern list.
147
147
  *
148
- * Why this exists: prompt-style resolution is a case-insensitive substring match
149
- * (`isStrongModel` in ./prompts). When a provider renames a model
150
- * (`claude-opus-4-8` -> `opus-4.8`), every pattern that used to match silently
151
- * stops matching, the tier drops back to the prescriptive prompt, and nothing
152
- * anywhere errors. This surfaces that silence.
148
+ * Why this exists: prompt-style resolution matches patterns against tier model
149
+ * ids (`isStrongModel` in ./prompts). A pattern that matches nothing any
150
+ * configured provider serves decides nothing, so it is dead weight the user
151
+ * probably meant to be doing something.
152
+ *
153
+ * Matching is IDENTICAL to `isStrongModel`: case- and separator-insensitive via
154
+ * the shared {@link flattenModelID}. That equivalence is the contract of this
155
+ * function — "orphaned" means precisely "isStrongModel would never match this
156
+ * against anything served". Historically the two used different rules, which is
157
+ * what made the old near-miss machinery necessary; see the note on `reportable`
158
+ * below.
153
159
  *
154
160
  * Comparison base: the CATALOG, not the active preset. The default pattern list
155
161
  * is a cross-preset union by construction (see DEFAULT_STRONG_MODEL_PATTERNS in
156
162
  * ./config), so any single preset leaves most of it unmatched — checking against
157
- * the active preset would warn on every clean install. A pattern matching no
158
- * model any configured provider serves is dead in THIS environment, which is
159
- * exactly the rename signal we want. Refs are compared as `provider/model`,
160
- * mirroring `isStrongModel`, which is fed the full provider-prefixed tier model.
163
+ * the active preset would warn on every clean install. Refs are compared as
164
+ * `provider/model`, mirroring `isStrongModel`, which is fed the full
165
+ * provider-prefixed tier model.
161
166
  *
162
167
  * Never cries wolf: an empty catalog (fetch failed) or a catalog with no models
163
168
  * returns `[]`, like `validateModels`.
@@ -165,6 +170,15 @@ export function suggestModels(
165
170
  * Gate: reported only when at least one active tier resolves its style by `auto`
166
171
  * (`promptStyle` absent or `"auto"`). With every tier pinned to an explicit
167
172
  * style the pattern list decides nothing, so an orphan there is harmless noise.
173
+ *
174
+ * SCOPE BOUNDARY, DELIBERATE: `usesAuto` reads the ACTIVE preset only
175
+ * (`getActiveTiers` in ./protocol returns `cfg.presets[cfg.activePreset]`). A
176
+ * preset reachable only by failing over through `cfg.fallback` is not consulted,
177
+ * so a pattern that matters solely to such a preset is out of scope here. This
178
+ * is a choice, not an oversight: fallback presets are conditional futures, and
179
+ * warning about prompt-style resolution in a preset the session may never enter
180
+ * trades a real signal for speculative noise. The tier the user is actually
181
+ * running is what this check speaks about.
168
182
  */
169
183
  export function findOrphanedStrongPatterns(
170
184
  cfg: RouterConfig,
@@ -180,7 +194,7 @@ export function findOrphanedStrongPatterns(
180
194
 
181
195
  const refs: string[] = [];
182
196
  for (const p of catalog.providers) {
183
- for (const m of p.models) refs.push(`${p.id}/${m.id}`.toLowerCase());
197
+ for (const m of p.models) refs.push(flattenModelID(`${p.id}/${m.id}`));
184
198
  }
185
199
  if (refs.length === 0) return [];
186
200
 
@@ -189,55 +203,39 @@ export function findOrphanedStrongPatterns(
189
203
  const patterns = raw.filter(
190
204
  (p): p is string => typeof p === "string" && p.length > 0,
191
205
  );
192
- // Same semantics as isStrongModel(): case-insensitive substring match.
193
- const orphans = patterns.filter(
194
- (p) => !refs.some((r) => r.includes(p.toLowerCase())),
195
- );
196
-
197
- // Evidence gate for the defaults. A user-authored list is a claim about THIS
198
- // environment, so a dead entry in it is actionable on its own. The default
199
- // list is not a claim about anything — it is a cross-provider union we ship,
200
- // so most of it is unserved on any given install and saying so is noise the
201
- // user cannot act on. A default pattern is only worth reporting when a
202
- // near-miss proves the model is there under a drifted separator
203
- // (`opus-4-8` vs `opus-4.8`), which is the rename this check exists to catch.
204
- const reportable =
205
- configured === undefined
206
- ? orphans.filter((p) => findStrongPatternNearMisses(p, catalog).length > 0)
207
- : orphans;
206
+ // Exactly isStrongModel()'s rule, via the shared normalizer: case- and
207
+ // separator-insensitive substring match. A pattern that flattens to nothing
208
+ // (e.g. "---") matches nothing there, so it is an orphan here too.
209
+ const orphans = patterns.filter((p) => {
210
+ const needle = flattenModelID(p);
211
+ return needle.length === 0 || !refs.some((r) => r.includes(needle));
212
+ });
213
+
214
+ // Defaults are never reported; user-authored patterns are reported when dead.
215
+ //
216
+ // This used to be an evidence gate: a default pattern was reported only if it
217
+ // had a separator "near miss" AND named a model the active preset used. That
218
+ // gate was correct for the matcher of the time — `isStrongModel` compared
219
+ // separators literally, so `opus-4-8` genuinely failed against a served
220
+ // `claude-opus-4.8`, and a provider re-spelling a model could silently
221
+ // downgrade a tier from `goal-oriented` to `prescriptive`. The gate existed to
222
+ // catch that silence without drowning every install in noise from a default
223
+ // list that is a cross-provider union.
224
+ //
225
+ // `isStrongModel` now normalizes separators itself, so that failure mode is
226
+ // gone at the source: a "near miss" IS a match, and a default pattern can no
227
+ // longer be simultaneously orphaned and about a real served model. The gate
228
+ // became unreachable rather than wrong, and carrying unreachable code that
229
+ // implies a live hazard is worse than deleting it.
230
+ //
231
+ // What remains actionable is narrow and genuine: a user wrote a
232
+ // `modelGenerations.strong` entry that matches nothing their providers serve.
233
+ // That is a claim about THIS environment which is false, so we say so. The
234
+ // shipped defaults make no such claim and stay silent.
235
+ const reportable = configured === undefined ? [] : orphans;
208
236
  return [...new Set(reportable)];
209
237
  }
210
238
 
211
- /**
212
- * For an orphaned pattern, the served refs it would match if separators were
213
- * ignored.
214
- *
215
- * `findOrphanedStrongPatterns` says a pattern is dead; this says why. The
216
- * failure this exists for is separator drift, not a wrong name: `anthropic`
217
- * ships `claude-opus-4-8` while the copilot preset uses `claude-opus-4.6`, so a
218
- * provider moving between the two un-matches a pattern that is otherwise still
219
- * describing the right model. Normalizing `.`, `-` and `_` away turns "this
220
- * matches nothing" into "this matches nothing, but here is the model it almost
221
- * certainly means", which is the difference between a warning and a fix.
222
- *
223
- * Returns empty when nothing plausibly matches, i.e. the pattern is simply
224
- * wrong or the model is genuinely gone.
225
- */
226
- export function findStrongPatternNearMisses(
227
- pattern: string,
228
- catalog: Catalog,
229
- ): string[] {
230
- const flatten = (v: string) => v.toLowerCase().replace(/[.\-_]/g, "");
231
- const needle = flatten(pattern);
232
- if (!needle) return [];
233
-
234
- const refs: string[] = [];
235
- for (const p of catalog.providers) {
236
- for (const m of p.models) refs.push(`${p.id}/${m.id}`);
237
- }
238
- return refs.filter((r) => flatten(r).includes(needle));
239
- }
240
-
241
239
  export type ModelIssueKind =
242
240
  | "provider-unknown"
243
241
  | "model-missing"
@@ -55,18 +55,25 @@ export const PROMPT_STYLES = ["prescriptive", "goal-oriented", "auto"] as const;
55
55
  export type PromptStyle = (typeof PROMPT_STYLES)[number];
56
56
 
57
57
  /**
58
- * Shared model-generation pattern lists, matched case-insensitively as substrings
59
- * of a tier's model ID.
58
+ * Model-ID patterns, matched as substrings of a tier's model ID with case and
59
+ * separators normalized (see flattenModelID in ./prompts).
60
60
  */
61
61
  export interface ModelGenerationsConfig {
62
- claude5x?: string[];
63
62
  strong?: string[];
64
63
  }
65
64
 
66
- export const DEFAULT_CLAUDE5X_PATTERNS = ["claude-fable-5", "claude-mythos-5"];
67
- // 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.
65
+ // Curated per model, NOT by generation. There used to be a `claude5x` list that
66
+ // this one spread, with a note claiming "strong is a superset of claude5x by
67
+ // construction — every Claude 5.x model is a strong model". Both halves stopped
68
+ // being true: `claude-opus-5` was added here without being added there, and
69
+ // `claude-sonnet-5` ships on two tiers as a Claude 5.x model that is
70
+ // deliberately not strong. Worse, the `claude5x` config field was validated and
71
+ // documented but never read — the spread happened once at module load from the
72
+ // default array, so a user override could not reach it. Generation is not the
73
+ // criterion; whether goal-oriented prompting suits the model is.
68
74
  export const DEFAULT_STRONG_MODEL_PATTERNS = [
69
- ...DEFAULT_CLAUDE5X_PATTERNS,
75
+ "claude-fable-5",
76
+ "claude-mythos-5",
70
77
  "opus-4-8",
71
78
  "claude-opus-5",
72
79
  ];
@@ -331,6 +338,25 @@ function isPlainObject(v: unknown): v is Record<string, unknown> {
331
338
  return typeof v === "object" && v !== null && !Array.isArray(v);
332
339
  }
333
340
 
341
+ /**
342
+ * Split a tier model reference (`"provider/model"`) into its parts. Splits on
343
+ * the FIRST slash only, so multi-segment model ids (e.g.
344
+ * `openrouter/deepseek/deepseek-v3.2`) keep their full model id.
345
+ *
346
+ * Lives here rather than in catalog.ts because the `provider/model` shape is a
347
+ * property of the config format, not of the catalog. Config load and catalog
348
+ * lookup have to agree on what a well-formed ref is; sharing one function is
349
+ * what makes "it validated at load" mean "it will parse later". catalog.ts
350
+ * re-exports it so the reference is still reachable from where it is used.
351
+ */
352
+ export function parseModelRef(
353
+ ref: string,
354
+ ): { providerId: string; modelId: string } | undefined {
355
+ const i = ref.indexOf("/");
356
+ if (i <= 0 || i === ref.length - 1) return undefined;
357
+ return { providerId: ref.slice(0, i), modelId: ref.slice(i + 1) };
358
+ }
359
+
334
360
  /**
335
361
  * Shape of every preset and every tier within it. Returns the presets map so
336
362
  * the caller can hand it to validateActivePreset without re-narrowing.
@@ -365,6 +391,18 @@ function validatePresets(obj: Record<string, unknown>): Record<string, unknown>
365
391
  `tiers.json: '${presetName}.${tierName}.model' must be a non-empty string`,
366
392
  );
367
393
  }
394
+ // Same reasoning as effort and promptStyle below, one step earlier: a ref
395
+ // missing its provider (`claude-sonnet-5`) or missing its model
396
+ // (`anthropic/`) used to load clean and only surface much later, as a
397
+ // catalog issue on a turn that happened to fetch the catalog — or never,
398
+ // if the fetch failed. The shape is knowable without the network, so it
399
+ // is decided here. parseModelRef is the same function the catalog lookup
400
+ // uses, so passing this guarantees the ref parses there too.
401
+ if (!parseModelRef(t.model)) {
402
+ throw new Error(
403
+ `tiers.json: '${presetName}.${tierName}.model' must be 'provider/model' (got '${t.model}')`,
404
+ );
405
+ }
368
406
  if (t.description !== undefined && typeof t.description !== "string") {
369
407
  throw new Error(
370
408
  `tiers.json: '${presetName}.${tierName}.description' must be a string`,
@@ -525,13 +563,14 @@ function validateModelGenerations(obj: Record<string, unknown>): void {
525
563
  throw new Error("tiers.json: modelGenerations must be an object");
526
564
  }
527
565
  const modelGenerations = obj.modelGenerations as Record<string, unknown>;
528
- for (const key of ["claude5x", "strong"] as const) {
529
- if (
530
- modelGenerations[key] !== undefined &&
531
- !Array.isArray(modelGenerations[key])
532
- ) {
533
- throw new Error(`tiers.json: modelGenerations.${key} must be an array`);
534
- }
566
+ // Only `strong` is validated because only `strong` is read. Unknown keys —
567
+ // including the removed `claude5x` — are ignored rather than rejected, so an
568
+ // existing tiers.json carrying one still loads.
569
+ if (
570
+ modelGenerations.strong !== undefined &&
571
+ !Array.isArray(modelGenerations.strong)
572
+ ) {
573
+ throw new Error("tiers.json: modelGenerations.strong must be an array");
535
574
  }
536
575
  }
537
576
  }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Where the plugin's passive warnings go.
3
+ *
4
+ * `console.warn` from a plugin lands on the server process's stderr, which the
5
+ * TUI does not own, so anything written there paints over whatever the terminal
6
+ * was drawing. A user reported exactly that: a preset switch smeared a
7
+ * ~230-character warning across two lines of UI.
8
+ *
9
+ * opencode exposes `POST /log` for this, reachable as `client.app.log`. Entries
10
+ * go to opencode's own log with a service tag instead of into the terminal.
11
+ *
12
+ * Fail-soft by contract. The call is fire-and-forget: a warning is never worth
13
+ * blocking a hook on, and a logging failure must never surface as a plugin
14
+ * error. When the endpoint is unavailable, when the post rejects, and when it
15
+ * resolves reporting an error, the message falls back to console.warn so a
16
+ * diagnostic is never silently dropped.
17
+ *
18
+ * Two properties of the real SDK client shape this file, and getting either
19
+ * wrong degrades the feature silently rather than loudly:
20
+ *
21
+ * 1. `client.app` is a class instance (`App extends _HeyApiClient`) whose
22
+ * methods read `this._client`. Detaching the method — `const log =
23
+ * client.app.log` — leaves `this` undefined under ESM strict mode, so every
24
+ * call throws and every warning quietly takes the console fallback. The
25
+ * method is therefore always invoked with its receiver bound.
26
+ * 2. `App.log` defaults to `ThrowOnError = false`, so an HTTP failure RESOLVES
27
+ * as `{ data: undefined, error }` instead of rejecting. A bare `.catch()`
28
+ * sees nothing on a 400, so the settled value is inspected as well.
29
+ * 3. Fire-and-forget loses the message outright when the process is about to
30
+ * exit: the post never settles, and the fallback never runs because nothing
31
+ * failed. A long-lived server never notices; `opencode run` and `opencode
32
+ * debug` are short-lived and would go silent, which is strictly worse than
33
+ * the stderr write this file exists to avoid. Hence `flush()`, awaited from
34
+ * the plugin's `dispose` hook. Verified against a live opencode 1.18.16:
35
+ * `dispose` is both called and awaited on `opencode debug agent`.
36
+ *
37
+ * One thing to know before debugging this: the `service` tag is a namespace,
38
+ * not a rendered field. Entries land as
39
+ * `timestamp=... level=WARN run=... message="..." <extra keys>` with no
40
+ * `service=` anywhere, so grepping opencode's log for `service=model-router`
41
+ * finds nothing even when the entry is there. Match on the message text.
42
+ */
43
+
44
+ export interface PluginLogger {
45
+ warn(message: string, extra?: Record<string, unknown>): void;
46
+ /**
47
+ * Await every post still in flight, so a shutting-down process does not drop
48
+ * warnings it already decided to emit. Never rejects: a failing flush must
49
+ * not be the thing that breaks teardown.
50
+ */
51
+ flush(): Promise<void>;
52
+ }
53
+
54
+ /** The service tag on every entry, so entries are greppable by origin. */
55
+ export const LOG_SERVICE = "model-router";
56
+
57
+ /** Prefix used only on the console fallback, where there is no service field. */
58
+ const CONSOLE_PREFIX = `[${LOG_SERVICE}]`;
59
+
60
+ type LogRequest = {
61
+ body: {
62
+ service: string;
63
+ level: "debug" | "info" | "error" | "warn";
64
+ message: string;
65
+ extra?: Record<string, unknown>;
66
+ };
67
+ };
68
+
69
+ /**
70
+ * Structural view of the one method we use. Deliberately narrow: the plugin
71
+ * must keep working against a bare stub (every unit test hands it one) and
72
+ * against an older server with no `/log` at all, so the capability is probed at
73
+ * runtime rather than demanded by the type.
74
+ */
75
+ type LogCapableClient = {
76
+ app?: {
77
+ log?: (req: LogRequest) => unknown;
78
+ };
79
+ };
80
+
81
+ /**
82
+ * The SDK resolves rather than rejects on an HTTP failure, reporting it as a
83
+ * populated `error` field on the settled value. Treat that as a failed post.
84
+ */
85
+ function isErrorResult(value: unknown): boolean {
86
+ return (
87
+ typeof value === "object" &&
88
+ value !== null &&
89
+ "error" in value &&
90
+ (value as { error?: unknown }).error !== undefined
91
+ );
92
+ }
93
+
94
+ /**
95
+ * Build a logger over an opencode client. Falls back to the console when the
96
+ * client cannot log, which covers older servers and every unit test that hands
97
+ * the plugin a stub.
98
+ */
99
+ export function createPluginLogger(client?: unknown): PluginLogger {
100
+ const app = (client as LogCapableClient | undefined)?.app;
101
+ const log = app?.log;
102
+
103
+ if (!app || typeof log !== "function") {
104
+ return {
105
+ warn(message) {
106
+ console.warn(`${CONSOLE_PREFIX} ${message}`);
107
+ },
108
+ // console.warn is synchronous, so there is never anything to wait for.
109
+ flush: () => Promise.resolve(),
110
+ };
111
+ }
112
+
113
+ // Posts still in flight. Entries remove themselves once settled, so this
114
+ // stays bounded on a long-lived server rather than growing for its lifetime.
115
+ const inFlight = new Set<Promise<void>>();
116
+
117
+ return {
118
+ warn(message, extra) {
119
+ const toConsole = () => console.warn(`${CONSOLE_PREFIX} ${message}`);
120
+ let result: unknown;
121
+ try {
122
+ // Bound to `app` on purpose — see (1) in the module comment. Calling
123
+ // the detached reference would throw on every real client.
124
+ result = log.call(app, {
125
+ body: {
126
+ service: LOG_SERVICE,
127
+ level: "warn",
128
+ message,
129
+ ...(extra ? { extra } : {}),
130
+ },
131
+ });
132
+ } catch {
133
+ // A synchronous throw means the transport is unusable; say it somewhere.
134
+ toConsole();
135
+ return;
136
+ }
137
+ // Fire-and-forget: never await, but never leave a rejection unhandled
138
+ // either, and do not lose the diagnostic when the post fails — whether it
139
+ // fails by rejecting or by resolving with an error. See (2) above.
140
+ const settled: Promise<void> = Promise.resolve(result)
141
+ .then((value) => {
142
+ if (isErrorResult(value)) toConsole();
143
+ })
144
+ .catch(toConsole);
145
+ // Tracked so `flush` can wait for it. `settled` already absorbs its own
146
+ // failures, so nothing here can reject. See (3) above.
147
+ inFlight.add(settled);
148
+ void settled.finally(() => {
149
+ inFlight.delete(settled);
150
+ });
151
+ },
152
+ async flush() {
153
+ await Promise.allSettled([...inFlight]);
154
+ },
155
+ };
156
+ }
@@ -47,13 +47,46 @@ Ground every claim in a tool result or the context you were given; flag anything
47
47
  Begin your response with exactly one of \`DONE:\` (structured analysis), \`SCOPE GROWTH:\` (prefer @fast pre-exploration of [specific files/patterns/areas] before I continue), or \`ESCALATE:\`.`,
48
48
  };
49
49
 
50
- /** Case-insensitive substring match against the strong-model pattern list. */
50
+ /**
51
+ * Fold away case and separator style (`.`, `-`, `_`) so two spellings of the
52
+ * same model id compare equal. `/` is deliberately preserved: it separates the
53
+ * provider prefix from the model id, and collapsing it would let a pattern
54
+ * match across that boundary.
55
+ *
56
+ * Exported because `findOrphanedStrongPatterns` in ./catalog must ask exactly
57
+ * the question `isStrongModel` answers — "would this pattern match anything?" —
58
+ * and a second, drifting copy of this rule would reintroduce the mismatch it
59
+ * exists to remove.
60
+ */
61
+ export const flattenModelID = (v: string): string =>
62
+ v.toLowerCase().replace(/[.\-_]/g, "");
63
+
64
+ /**
65
+ * Substring match against the strong-model pattern list, ignoring case AND
66
+ * separator style: `.`, `-` and `_` are normalized away on both sides, so the
67
+ * pattern `opus-4-8` matches the served id `claude-opus-4.8`, and
68
+ * `claude-haiku-4-5` matches `claude-haiku-4.5`.
69
+ *
70
+ * Why separator-insensitive: providers spell the same model differently and
71
+ * change their minds. Our own shipped tiers.json carries
72
+ * `anthropic/claude-haiku-4-5` and `github-copilot/claude-haiku-4.5` for one
73
+ * model. Under a plain substring match, that drift silently un-matched the
74
+ * pattern list and quietly downgraded a tier's prompt style from
75
+ * `goal-oriented` to `prescriptive` — no error, no log, just a weaker prompt.
76
+ * Normalizing separators here removes that failure mode at the source.
77
+ *
78
+ * The provider prefix still participates in the match (see
79
+ * {@link flattenModelID}), so a pattern may target `provider/model` refs.
80
+ */
51
81
  export function isStrongModel(modelID: string | undefined, cfg: RouterConfig): boolean {
52
82
  if (typeof modelID !== "string" || modelID.length === 0) return false;
53
83
  const raw = cfg.modelGenerations?.strong ?? DEFAULT_STRONG_MODEL_PATTERNS;
54
84
  const patterns = raw.filter((p): p is string => typeof p === "string" && p.length > 0);
55
- const id = modelID.toLowerCase();
56
- return patterns.some((p) => id.includes(p.toLowerCase()));
85
+ const id = flattenModelID(modelID);
86
+ return patterns.some((p) => {
87
+ const needle = flattenModelID(p);
88
+ return needle.length > 0 && id.includes(needle);
89
+ });
57
90
  }
58
91
 
59
92
  /** Resolve "auto" (or absent) to a concrete style. Fail-safe: unknown/empty model -> prescriptive. */