opencode-model-router 1.7.0 → 1.9.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,90 @@ 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.9.0] - 2026-08-20
9
+
10
+ Minor release. One real bug — prompt-style resolution broke when a provider renamed a
11
+ model across separators — plus the diagnostics that were compensating for it, which are
12
+ gone now that the cause is fixed.
13
+
14
+ ### Fixed
15
+
16
+ - **`promptStyle: "auto"` survives a provider renaming a model across separators.**
17
+ `isStrongModel` matched patterns case-insensitively but not separator-insensitively, so
18
+ the moment a provider shipped `claude-opus-4.8` where the pattern said `opus-4-8`, the
19
+ tier silently stopped resolving as strong and dropped from `goal-oriented` to
20
+ `prescriptive` — a different system prompt, with nothing said. Matching now normalizes
21
+ case and `.`, `-`, `_` on both sides. The provider boundary is preserved: `/` is not
22
+ normalized, so a pattern cannot match across it. A pattern consisting only of
23
+ separators now matches nothing instead of everything.
24
+
25
+ This is not hypothetical drift. Our own `tiers.json` carries the same model as
26
+ `anthropic/claude-haiku-4-5` and `github-copilot/claude-haiku-4.5`, because each
27
+ provider spells it its own way.
28
+
29
+ - **Passive warnings go to opencode's log instead of the terminal.** `console.warn`
30
+ from a plugin lands on the server's stderr, which the TUI does not own, so a warning
31
+ painted over whatever the terminal was drawing. Stale-model, orphaned-pattern and
32
+ agent-option warnings now post to `POST /log` via `client.app.log` with a
33
+ `model-router` service tag and structured `extra`. Fire-and-forget and fail-soft: a
34
+ server without the endpoint, a rejected post, a post that resolves reporting an error,
35
+ and a synchronous throw all fall back to `console.warn`, so a diagnostic is never
36
+ silently dropped.
37
+
38
+ Config-parse warnings deliberately still use `console.warn`. They are emitted from
39
+ `loadConfig`, which runs before a client exists, and they only fire on a malformed
40
+ override file — a case where being loud is the point.
41
+
42
+ ### Removed
43
+
44
+ - **`modelGenerations.claude5x`.** The field was declared, type-validated on load and
45
+ documented in three places, and never read by anything. `isStrongModel` reads
46
+ `strong`, and the default `strong` list was a module-level constant computed once
47
+ from the built-in array, so a user's `claude5x` could not reach it. Setting it did
48
+ nothing, and passing validation implied otherwise. An existing config carrying the key
49
+ still loads — unknown keys under `modelGenerations` are ignored, not rejected.
50
+
51
+ The note that `strong` was "a superset of `claude5x` by construction — every Claude 5.x
52
+ model is a strong model" is gone with it. It had stopped being true in both directions:
53
+ `claude-opus-5` was strong without being in `claude5x`, and `claude-sonnet-5` ships on
54
+ two tiers as a Claude 5 model that is deliberately not strong. `strong` is curated per
55
+ model, and the docs now say so.
56
+
57
+ - **Near-miss detection for orphaned strong-model patterns.** It existed to spot exactly
58
+ the rename the matcher now absorbs, so under the fixed matcher a near miss *is* a match
59
+ and can no longer be an orphan — the code was unreachable. The `/router models` output
60
+ and the passive warning both drop the "served under a different separator" hint. What
61
+ remains is narrower and honest: a pattern **you** wrote in `modelGenerations.strong`
62
+ that matches nothing your providers serve is still reported, because that is a claim
63
+ about your environment that turned out to be wrong. Shipped defaults are never
64
+ reported — most of a cross-provider union is unserved on any given install, and saying
65
+ so is noise you cannot act on.
66
+
67
+ ### Changed
68
+
69
+ - **`@opencode-ai/plugin` peer range is now `>=1.0.0 <2.0.0`.** The open-ended `>=1.0.0`
70
+ claimed compatibility with a major version that does not exist yet and whose plugin API
71
+ is by definition unknown.
72
+
73
+ ## [1.8.0] - 2026-08-19
74
+
75
+ Minor release: every vendor preset is refreshed to the current generation of models.
76
+ No routing logic changed — the tier structure, patterns and enforcement behavior are
77
+ the same, only the model ids (and the reasoning effort attached to them) move forward.
78
+
79
+ ### Changed
80
+
81
+ - **`anthropic` preset** now routes `fast` → `sonnet-5`, `medium` → `opus-5` at `high`
82
+ effort, and `heavy` → `fable-5` at `max`.
83
+ - **`openai` preset** now routes `fast` → `gpt-5.6-luna-fast`, `medium` →
84
+ `gpt-5.6-terra-fast` at `high` effort, and `heavy` → `gpt-5.6-sol-fast` at `xhigh`.
85
+ - **`google` preset** now routes `fast` → `gemini-3.5-flash-lite`, `medium` →
86
+ `gemini-3.7-flash`, and `heavy` → `gemini-3.1-pro-preview`.
87
+ - **`github-copilot` preset** now routes `medium` → `claude-sonnet-5` and `heavy` →
88
+ `claude-fable-5`.
89
+ - **`hybrid` preset** now routes `medium` → `gpt-5.6-terra-fast` and `heavy` →
90
+ `claude-opus-5` at `max` effort.
91
+
8
92
  ## [1.7.0] - 2026-08-19
9
93
 
10
94
  Minor release: live model-catalog discovery and validation — `/router models`, stale-model
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > **Use the cheapest model that can do the job. Automatically.**
4
4
 
5
- An [OpenCode](https://opencode.ai) plugin that routes every coding task to the right-priced AI tier — automatically, on every message, with 3,089–4,659 characters of system-prompt overhead depending on the orchestrator and enforcement mode.
5
+ An [OpenCode](https://opencode.ai) plugin that routes every coding task to the right-priced AI tier — automatically, on every message, with 3,084–4,654 characters of system-prompt overhead depending on the orchestrator and enforcement mode.
6
6
 
7
7
  ## Why it's different
8
8
 
@@ -12,7 +12,7 @@ Most AI coding tools give you one model for everything. You pay Opus prices to r
12
12
  The orchestrator runs on *every* message. Put Sonnet there, not Opus. Sonnet reads a routing protocol and delegates just as well as Opus — at 4x lower cost. Reserve Opus for when it genuinely matters.
13
13
 
14
14
  **Inject a compressed, LLM-optimized routing protocol.**
15
- Instead of duplicated prose, the plugin injects a dense, machine-readable routing protocol. The protocol itself is 3,089 characters; a Claude orchestrator receives 3,861 characters after its authority prefix (roughly 965–1,075 tokens at 3.6–4.0 characters per token). Every message, every session.
15
+ Instead of duplicated prose, the plugin injects a dense, machine-readable routing protocol. The protocol itself is 3,084 characters; a Claude orchestrator receives 3,856 characters after its authority prefix (roughly 965–1,075 tokens at 3.6–4.0 characters per token). Every message, every session.
16
16
 
17
17
  **Match task to tier using a configurable taxonomy.**
18
18
  A keyword routing guide (`@fast→search/grep/read`, `@medium→impl/refactor/test`, `@heavy→arch/debug/security`) tells the orchestrator exactly which tier fits each task type. Fully customizable. No ambiguity.
@@ -65,7 +65,59 @@ opencode-model-router injects a **delegation protocol** into the system prompt t
65
65
  4. **Never over-qualify** — use the cheapest tier that can reliably handle the task
66
66
  5. **Fallback** across providers when one fails
67
67
 
68
- All of this adds 3,089 characters for a non-Claude orchestrator or 3,861 characters for a Claude orchestrator (roughly 770–1,075 tokens at 3.6–4.0 characters per token).
68
+ All of this adds 3,084 characters for a non-Claude orchestrator or 3,856 characters for a Claude orchestrator (roughly 770–1,075 tokens at 3.6–4.0 characters per token).
69
+
70
+ ## Understanding how it works
71
+
72
+ > This intuition-first walkthrough was written by [Lucas Húngaro](https://github.com/lucashungaro) for [his fork](https://github.com/lucashungaro/opencode-model-router), and is included here with his permission.
73
+
74
+ There are a lot of moving parts, so let's use an analogy to explain how the plugin works.
75
+
76
+ ### Picking who does the work
77
+
78
+ Think of your main orchestrator model as a head chef in a restaurant. You give it an order, and instead of cooking everything itself, it hands tasks to line cooks of different skill and price: a fast, cheap cook for simple tasks, a mid-level cook for everyday work, and an expensive expert for the hard problems.
79
+
80
+ The chef assigns each task by what the task is, not by who is the "fanciest" cook. Reading a file, searching the codebase, or looking something up goes to the cheap cook. Writing and editing code goes to the mid-level cook. Gnarly architecture, security work, or debugging that has already failed a couple of times goes to the expert. Trivial one-off lookups the chef just handles itself, since delegating those would cost more than it saves.
81
+
82
+ That is the routing in a nutshell. You pay expert prices only when a task genuinely needs an expert, which is exactly the point.
83
+
84
+ ### Making sure the work actually got done
85
+
86
+ The enforcement layer is the kitchen's quality control. It exists because a cook saying "all done" is not the same as the dish being good.
87
+
88
+ It works in two parts. First, a recipe card travels with each order, so the chef and the cook agree up front on what "done" means (say, the tests pass, or a specific file exists). Second, when the work comes back, someone other than the cook who made it tastes it, and that taster is at least as senior as the cook who executed it. They check it against the recipe card, and if it falls short, a note goes back to the chef suggesting a redo, maybe by a more capable cook.
89
+
90
+ How strict all of this is comes down to one setting:
91
+
92
+ - **Off:** no checking. A cook says done and it goes out.
93
+ - **Advisory (the default):** everything still gets tasted and notes still get left, but nothing is ever held back. Gentle nudges only.
94
+ - **Enforced:** a dish that fails its check is held back and redone, or handed to a better cook, before it can leave the kitchen.
95
+
96
+ You can disable the enforcement layer entirely to save some tokens in the system prompt, at the cost of possible re-work if a subagent fails to meet the agreed-upon definition of "done." This is the enforcement feature.
97
+
98
+ ### The standing rule: limited trips to the pantry
99
+
100
+ Separate from that optional quality control, the kitchen has one rule that is always in force, no matter which setting above you pick: a cook only gets so many trips to the pantry on a given task before they have to either start cooking or hand back what they have so far. And if a cook keeps checking the same shelf over and over, they get a sticky note telling them to stop. This is not about whether the dish is any good, it just keeps anyone from vanishing into the walk-in for an hour of "research" instead of producing something. It applies even with enforcement layer turned off.
101
+
102
+ This is the read-only call cap feature. It prevents runaway "exploration" loops and redundant tool calls, which are a common source of wasted time and money.
103
+
104
+ ### Planning a big job up front
105
+
106
+ For a large, multi-step job you do not have to let the chef work out each step on the fly. You can write the plan down and have the kitchen label every step on the ticket ahead of time with the cook who should handle it. Think of prepping a banquet where each course is pre-assigned to a station, so nobody is deciding in the middle of service.
107
+
108
+ This is the plan annotation feature. You can invoke it with `/annotate-plan`. More details in [Plan annotation](#plan-annotation).
109
+
110
+ ### Keeping certain cooks on task
111
+
112
+ Some cooks arrive with strong habits from their previous job. Left alone they tend to wander the whole pantry "just to be thorough," or they announce what they are about to do ("now I'll dice the onions") instead of actually doing it.
113
+
114
+ For those cooks the plugin clips a short note to the top of their instructions: in this kitchen your job is the dish in front of you, not a tour of the pantry. It keeps them from burning time and money on busywork. This is the adversarial prefix. There is also an optional, off-by-default add-on (the anti-narration guardrail) that tells them to cook rather than describe cooking; turn it on only if a model keeps announcing it will do work but never really does it (this can be common on small/older models).
115
+
116
+ ### Setting the kitchen's priorities
117
+
118
+ You can also tell the kitchen how to lean. One setting keeps things balanced, one pushes hard for savings and sends almost everything to the cheap cook (with the obvious quality trade-offs), one spends more freely when you want quality, and one goes expert-first for long, hard jobs. You also choose which suppliers the cooks come from (Anthropic, OpenAI, Google, GitHub Copilot, or a mix), and if a supplier is unavailable the kitchen falls back to another automatically. These are the budget modes, presets, and fallback chain features.
119
+
120
+ In summary, the chef decides who cooks, the quality control decides whether the finished plate is good enough to serve, and the remaining knobs let you set the kitchen's budget, priorities, and suppliers.
69
121
 
70
122
  ## Cost simulation
71
123
 
@@ -114,13 +166,13 @@ Task distribution: 18 exploration (60%), 10 implementation (33%), 2 architecture
114
166
 
115
167
  ## How it works
116
168
 
117
- On every message, the plugin injects a 3,089-character routing protocol. A Claude orchestrator receives 3,861 characters after its authority prefix (roughly 965–1,075 tokens at 3.6–4.0 characters per token). The notation is intentionally dense and compressed — it's **optimized for LLM comprehension, not human readability**. An agent reads it as a precise routing grammar; a human might squint at it.
169
+ On every message, the plugin injects a 3,084-character routing protocol. A Claude orchestrator receives 3,856 characters after its authority prefix (roughly 965–1,075 tokens at 3.6–4.0 characters per token). The notation is intentionally dense and compressed — it's **optimized for LLM comprehension, not human readability**. An agent reads it as a precise routing grammar; a human might squint at it.
118
170
 
119
171
  What the orchestrator sees (Anthropic preset, normal mode):
120
172
 
121
173
  ```
122
174
  ## Model Delegation Protocol
123
- Preset: anthropic. Tiers: @fast=claude-haiku-4-5(1x) @medium=claude-sonnet-4-5/max(5x) @heavy=claude-opus-4-6/max(20x). mode:normal
175
+ Preset: anthropic. Tiers: @fast=claude-sonnet-5(1x) @medium=claude-opus-5/high(5x) @heavy=claude-fable-5/max(20x). mode:normal
124
176
  R: @fast→search/grep/read/git-info/ls/lookup-docs/types/count/exists-check/rename @medium→impl-feature/refactor/write-tests/bugfix(≤2)/edit-logic/code-review/build-fix/create-file/db-migrate/api-endpoint/config-update @heavy→arch-design/debug(≥3fail)/sec-audit/perf-opt/migrate-strategy/multi-system-integration/tradeoff-analysis/rca
125
177
  Multi-phase: prefer explore(@fast)→execute(@medium) when phases are separable. Cheapest-first when practical.
126
178
  1.[tier:X] tag in plan→delegate X 2.plan:fast/cheap→@fast | plan:medium→@medium | plan:heavy→@heavy 3.default preference: read-only→@fast | implementation→@medium 4.orchestrate=self,execute=subagent 5.trivial(≤1 tool call,no expected follow-up)→direct,skip-delegate 6.before @heavy: gather context first(usually via @fast); if already sufficient, dispatch directly 7.if self is opus: skip-@heavy(do locally), still route broader read-only exploration to @fast 8.min(cost,adequate-tier)
@@ -166,7 +218,7 @@ With router → split:
166
218
  | Cross-provider fallback | ✅ | ❌ | ❌ | ❌ | ❌ |
167
219
  | Cost ratio awareness | ✅ | ❌ | ❌ | ❌ | ❌ |
168
220
  | Plan annotation with tiers | ✅ | ❌ | ❌ | ❌ | ❌ |
169
- | Measured prompt overhead: 3,089–4,659 chars | ✅ | — | ❌ | ❌ | ❌ |
221
+ | Measured prompt overhead: 3,084–4,654 chars | ✅ | — | ❌ | ❌ | ❌ |
170
222
 
171
223
  **Claude native**: single model for everything, no cost routing. If you're using claude.ai or OpenCode without plugins, you're paying the same price for `grep` as for architecture design.
172
224
 
@@ -324,37 +376,37 @@ The plugin ships with six presets (switch with `/preset <name>`):
324
376
  **anthropic** (default):
325
377
  | Tier | Model | Cost ratio |
326
378
  |------|-------|-----------|
327
- | @fast | `anthropic/claude-haiku-4-5` | 1x |
328
- | @medium | `anthropic/claude-sonnet-4-6` (max) | 5x |
329
- | @heavy | `anthropic/claude-opus-4-8` (max) | 20x |
379
+ | @fast | `anthropic/claude-sonnet-5` | 1x |
380
+ | @medium | `anthropic/claude-opus-5` (high) | 5x |
381
+ | @heavy | `anthropic/claude-fable-5` (max) | 20x |
330
382
 
331
383
  **openai**:
332
384
  | Tier | Model | Cost ratio |
333
385
  |------|-------|-----------|
334
- | @fast | `openai/gpt-5.4-mini-fast` | 1x |
335
- | @medium | `openai/gpt-5.5-fast` (high) | 5x |
336
- | @heavy | `openai/gpt-5.5-fast` (xhigh) | 20x |
386
+ | @fast | `openai/gpt-5.6-luna-fast` | 1x |
387
+ | @medium | `openai/gpt-5.6-terra-fast` (high) | 5x |
388
+ | @heavy | `openai/gpt-5.6-sol-fast` (xhigh) | 20x |
337
389
 
338
390
  **github-copilot**:
339
391
  | Tier | Model | Cost ratio |
340
392
  |------|-------|-----------|
341
393
  | @fast | `github-copilot/claude-haiku-4.5` | 1x |
342
- | @medium | `github-copilot/claude-sonnet-4.6` | 5x |
343
- | @heavy | `github-copilot/claude-opus-4.6` | 20x |
394
+ | @medium | `github-copilot/claude-sonnet-5` | 5x |
395
+ | @heavy | `github-copilot/claude-fable-5` | 20x |
344
396
 
345
397
  **google**:
346
398
  | Tier | Model | Cost ratio |
347
399
  |------|-------|-----------|
348
- | @fast | `google/gemini-2.5-flash` | 1x |
349
- | @medium | `google/gemini-2.5-pro` | 5x |
350
- | @heavy | `google/gemini-3-pro-preview` | 20x |
400
+ | @fast | `google/gemini-3.5-flash-lite` | 1x |
401
+ | @medium | `google/gemini-3.7-flash` | 5x |
402
+ | @heavy | `google/gemini-3.1-pro-preview` | 20x |
351
403
 
352
404
  **hybrid** — Anthropic for exploration and heavy analysis, OpenAI for implementation:
353
405
  | Tier | Model | Cost ratio |
354
406
  |------|-------|-----------|
355
407
  | @fast | `anthropic/claude-haiku-4-5` | 1x |
356
- | @medium | `openai/gpt-5.5-fast` (high) | 5x |
357
- | @heavy | `anthropic/claude-opus-4-8` (max) | 20x |
408
+ | @medium | `openai/gpt-5.6-terra-fast` (high) | 5x |
409
+ | @heavy | `anthropic/claude-opus-5` (max) | 20x |
358
410
 
359
411
  **fable-effort** — one model, three reasoning depths (see [per-tier `effort`](#per-tier-effort)):
360
412
  | Tier | Model | Effort | Cost ratio |
@@ -601,9 +653,9 @@ Each tier (`@fast`, `@medium`, `@heavy`) has a system prompt that describes its
601
653
  },
602
654
  "presets": {
603
655
  "anthropic": {
604
- "fast": { "model": "anthropic/claude-haiku-4-5", ... },
605
- "medium": { "model": "anthropic/claude-sonnet-4-6", ... },
606
- "heavy": { "model": "anthropic/claude-opus-4-7", ... }
656
+ "fast": { "model": "anthropic/claude-sonnet-5", ... },
657
+ "medium": { "model": "anthropic/claude-opus-5", ... },
658
+ "heavy": { "model": "anthropic/claude-fable-5", ... }
607
659
  }
608
660
  }
609
661
  }
@@ -632,16 +684,18 @@ for that tier name only, and tiers you do not list keep theirs.
632
684
 
633
685
  #### `modelGenerations`
634
686
 
635
- `modelGenerations` holds shared, case-insensitive substring patterns matched against a
636
- 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:
637
691
 
638
692
  | List | Default | What it drives |
639
693
  |------|---------|----------------|
640
- | `strong` | `["claude-fable-5", "claude-mythos-5", "opus-4-8"]` | `promptStyle: "auto"` resolution — a match resolves to `goal-oriented`, everything else to `prescriptive` (`isStrongModel` in `src/router/prompts.ts`). |
641
- | `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
+ | `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`). |
642
695
 
643
- Only `strong` is read at match time, and setting it replaces the default list outright
644
- 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
645
699
  prompt prefixes and the anti-narration detector do **not** use these lists; they match the
646
700
  model ID directly (`isClaudeModel` in `src/router/protocol.ts`).
647
701
 
@@ -649,7 +703,7 @@ model ID directly (`isClaudeModel` in `src/router/protocol.ts`).
649
703
  {
650
704
  "modelGenerations": {
651
705
  // Keep the shipped patterns and add a locally-hosted strong model.
652
- "strong": ["claude-fable-5", "claude-mythos-5", "opus-4-8", "my-org/big-coder"]
706
+ "strong": ["claude-fable-5", "claude-mythos-5", "opus-4-8", "claude-opus-5", "my-org/big-coder"]
653
707
  }
654
708
  }
655
709
  ```
@@ -664,7 +718,7 @@ reference for the full description.
664
718
  "presets": {
665
719
  "google": {
666
720
  "fast": {
667
- "model": "google/gemini-2.5-flash",
721
+ "model": "google/gemini-3.5-flash-lite",
668
722
  "prompt": "You are @fast (Gemini-tuned variant) — ...",
669
723
  ...
670
724
  }
@@ -929,7 +983,7 @@ After `/annotate-plan`:
929
983
 
930
984
  ## Token overhead
931
985
 
932
- Measured with the bundled Anthropic preset in normal mode (the shipped `activePreset`/`activeMode` defaults), the routing protocol is 3,089 characters for a non-Claude orchestrator. A Claude orchestrator receives 3,861 characters after its authority prefix, or 4,659 characters when the 798-character DoD/enforcement section is enabled. That is roughly 770–1,295 tokens across the three paths at 3.6–4.0 characters per token. The optional anti-narration clause adds another 650 characters to the Claude path.
986
+ Measured with the bundled Anthropic preset in normal mode (the shipped `activePreset`/`activeMode` defaults), the routing protocol is 3,084 characters for a non-Claude orchestrator. A Claude orchestrator receives 3,856 characters after its authority prefix, or 4,654 characters when the 798-character DoD/enforcement section is enabled. That is roughly 770–1,295 tokens across the three paths at 3.6–4.0 characters per token. The optional anti-narration clause adds another 650 characters to the Claude path.
933
987
 
934
988
  These are character counts of the prompts the shipped config actually produces, so they move whenever the protocol text does. `test/unit/docs-drift.test.ts` recomputes all three from `tiers.json` on every run and fails unless this section still quotes them, so a change that grows the protocol cannot land without updating these numbers.
935
989
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "1.7.0",
3
+ "version": "1.9.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",
@@ -45,7 +45,7 @@
45
45
  "CHANGELOG.md"
46
46
  ],
47
47
  "peerDependencies": {
48
- "@opencode-ai/plugin": ">=1.0.0"
48
+ "@opencode-ai/plugin": ">=1.0.0 <2.0.0"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@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 (
@@ -289,22 +288,10 @@ export function buildModelsOutput(
289
288
  * `findOrphanedStrongPatterns`). Report-only — the router never edits the
290
289
  * user's pattern list.
291
290
  */
292
- export function formatOrphanedStrongPatterns(
293
- patterns: string[],
294
- nearMisses: Record<string, string[]> = {},
295
- ): string {
291
+ export function formatOrphanedStrongPatterns(patterns: string[]): string {
296
292
  return [
297
293
  "⚠ **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
- }),
294
+ ...patterns.map((p) => `- \`${p}\``),
308
295
  "",
309
296
  "This may silently change prompt-style resolution for tiers on `promptStyle: auto`. If a provider renamed a model, update `modelGenerations.strong` in your overrides file (`/router overrides`).",
310
297
  ].join("\n");
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.
@@ -727,14 +732,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
727
732
  // tiers on auto. Catalog-dependent, so it rides the same deferred
728
733
  // path — it is NOT emitted on turn 1.
729
734
  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}`,
735
+ logger.warn(
736
+ `strong-model pattern '${p}' matches no model your providers serve — may silently change prompt-style resolution for tiers on auto`,
737
+ { pattern: p },
738
738
  );
739
739
  }
740
740
  for (const it of validateModels(cfg, catalog)) {
@@ -747,9 +747,12 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
747
747
  it.scope === "fallback"
748
748
  ? `${it.tier}[${it.providerId}]`
749
749
  : `@${it.tier}`;
750
- console.warn(
751
- `[model-router] ${where} ${it.ref}: ${it.kind}${hint}`,
752
- );
750
+ logger.warn(`${where} ${it.ref}: ${it.kind}${hint}`, {
751
+ tier: it.tier,
752
+ ref: it.ref,
753
+ kind: it.kind,
754
+ suggestions: it.suggestions,
755
+ });
753
756
  }
754
757
  }
755
758
  }
@@ -1025,7 +1028,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1025
1028
  }
1026
1029
 
1027
1030
  // Apply provider-specific options
1028
- const opts = buildAgentOptions(tier, name);
1031
+ const opts = buildAgentOptions(tier, name, logger);
1029
1032
  if (Object.keys(opts).length > 0) {
1030
1033
  agentDef.options = opts;
1031
1034
  }
@@ -1210,18 +1213,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1210
1213
  if (sub === "models") {
1211
1214
  const catalog = await fetchCatalog();
1212
1215
  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
- );
1216
+ text = buildModelsOutput(catalog, parts.slice(1).join(" "), orphans);
1225
1217
  } else {
1226
1218
  text = buildRouterOutput(cfg, args);
1227
1219
  // 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
  }
@@ -6,6 +6,7 @@
6
6
  // ---------------------------------------------------------------------------
7
7
 
8
8
  import { DEFAULT_STRONG_MODEL_PATTERNS, type RouterConfig } from "./config";
9
+ import { flattenModelID } from "./prompts";
9
10
  import { getActiveTiers } from "./protocol";
10
11
 
11
12
  export interface CatalogModel {
@@ -145,19 +146,24 @@ export function suggestModels(
145
146
  * {@link DEFAULT_STRONG_MODEL_PATTERNS}) that match NO model in the live
146
147
  * catalog. Report-only: the router never rewrites the user's pattern list.
147
148
  *
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.
149
+ * Why this exists: prompt-style resolution matches patterns against tier model
150
+ * ids (`isStrongModel` in ./prompts). A pattern that matches nothing any
151
+ * configured provider serves decides nothing, so it is dead weight the user
152
+ * probably meant to be doing something.
153
+ *
154
+ * Matching is IDENTICAL to `isStrongModel`: case- and separator-insensitive via
155
+ * the shared {@link flattenModelID}. That equivalence is the contract of this
156
+ * function — "orphaned" means precisely "isStrongModel would never match this
157
+ * against anything served". Historically the two used different rules, which is
158
+ * what made the old near-miss machinery necessary; see the note on `reportable`
159
+ * below.
153
160
  *
154
161
  * Comparison base: the CATALOG, not the active preset. The default pattern list
155
162
  * is a cross-preset union by construction (see DEFAULT_STRONG_MODEL_PATTERNS in
156
163
  * ./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.
164
+ * the active preset would warn on every clean install. Refs are compared as
165
+ * `provider/model`, mirroring `isStrongModel`, which is fed the full
166
+ * provider-prefixed tier model.
161
167
  *
162
168
  * Never cries wolf: an empty catalog (fetch failed) or a catalog with no models
163
169
  * returns `[]`, like `validateModels`.
@@ -165,6 +171,15 @@ export function suggestModels(
165
171
  * Gate: reported only when at least one active tier resolves its style by `auto`
166
172
  * (`promptStyle` absent or `"auto"`). With every tier pinned to an explicit
167
173
  * style the pattern list decides nothing, so an orphan there is harmless noise.
174
+ *
175
+ * SCOPE BOUNDARY, DELIBERATE: `usesAuto` reads the ACTIVE preset only
176
+ * (`getActiveTiers` in ./protocol returns `cfg.presets[cfg.activePreset]`). A
177
+ * preset reachable only by failing over through `cfg.fallback` is not consulted,
178
+ * so a pattern that matters solely to such a preset is out of scope here. This
179
+ * is a choice, not an oversight: fallback presets are conditional futures, and
180
+ * warning about prompt-style resolution in a preset the session may never enter
181
+ * trades a real signal for speculative noise. The tier the user is actually
182
+ * running is what this check speaks about.
168
183
  */
169
184
  export function findOrphanedStrongPatterns(
170
185
  cfg: RouterConfig,
@@ -180,7 +195,7 @@ export function findOrphanedStrongPatterns(
180
195
 
181
196
  const refs: string[] = [];
182
197
  for (const p of catalog.providers) {
183
- for (const m of p.models) refs.push(`${p.id}/${m.id}`.toLowerCase());
198
+ for (const m of p.models) refs.push(flattenModelID(`${p.id}/${m.id}`));
184
199
  }
185
200
  if (refs.length === 0) return [];
186
201
 
@@ -189,55 +204,39 @@ export function findOrphanedStrongPatterns(
189
204
  const patterns = raw.filter(
190
205
  (p): p is string => typeof p === "string" && p.length > 0,
191
206
  );
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;
207
+ // Exactly isStrongModel()'s rule, via the shared normalizer: case- and
208
+ // separator-insensitive substring match. A pattern that flattens to nothing
209
+ // (e.g. "---") matches nothing there, so it is an orphan here too.
210
+ const orphans = patterns.filter((p) => {
211
+ const needle = flattenModelID(p);
212
+ return needle.length === 0 || !refs.some((r) => r.includes(needle));
213
+ });
214
+
215
+ // Defaults are never reported; user-authored patterns are reported when dead.
216
+ //
217
+ // This used to be an evidence gate: a default pattern was reported only if it
218
+ // had a separator "near miss" AND named a model the active preset used. That
219
+ // gate was correct for the matcher of the time — `isStrongModel` compared
220
+ // separators literally, so `opus-4-8` genuinely failed against a served
221
+ // `claude-opus-4.8`, and a provider re-spelling a model could silently
222
+ // downgrade a tier from `goal-oriented` to `prescriptive`. The gate existed to
223
+ // catch that silence without drowning every install in noise from a default
224
+ // list that is a cross-provider union.
225
+ //
226
+ // `isStrongModel` now normalizes separators itself, so that failure mode is
227
+ // gone at the source: a "near miss" IS a match, and a default pattern can no
228
+ // longer be simultaneously orphaned and about a real served model. The gate
229
+ // became unreachable rather than wrong, and carrying unreachable code that
230
+ // implies a live hazard is worse than deleting it.
231
+ //
232
+ // What remains actionable is narrow and genuine: a user wrote a
233
+ // `modelGenerations.strong` entry that matches nothing their providers serve.
234
+ // That is a claim about THIS environment which is false, so we say so. The
235
+ // shipped defaults make no such claim and stay silent.
236
+ const reportable = configured === undefined ? [] : orphans;
208
237
  return [...new Set(reportable)];
209
238
  }
210
239
 
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
240
  export type ModelIssueKind =
242
241
  | "provider-unknown"
243
242
  | "model-missing"
@@ -328,6 +327,13 @@ function validateFallbackChains(
328
327
  // an unknown provider for a chain that could never fire anyway.
329
328
  if (!Array.isArray(chain)) continue;
330
329
 
330
+ // KEPT DELIBERATELY, THOUGH CURRENTLY UNREACHABLE via validateModels: the
331
+ // tier pass already reports every unknown provider a tier routes to, and it
332
+ // seeds knownBadProviders with exactly those ids — the same set
333
+ // usedProviders admits here. So the two guards below can never both hold on
334
+ // that path. This stays as a safety net in case the usedProviders gating
335
+ // changes (or a caller drives validateFallbackChains directly).
336
+ // Full analysis: https://github.com/marco-jardim/opencode-model-router/issues/30#issuecomment-5343553727
331
337
  if (
332
338
  !isCatalogEmpty(catalog) &&
333
339
  usedProviders.has(providerId) &&
@@ -55,17 +55,28 @@ 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.
68
- export const DEFAULT_STRONG_MODEL_PATTERNS = [...DEFAULT_CLAUDE5X_PATTERNS, "opus-4-8"];
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.
74
+ export const DEFAULT_STRONG_MODEL_PATTERNS = [
75
+ "claude-fable-5",
76
+ "claude-mythos-5",
77
+ "opus-4-8",
78
+ "claude-opus-5",
79
+ ];
69
80
 
70
81
  export interface TierConfig {
71
82
  model: string;
@@ -521,13 +532,14 @@ function validateModelGenerations(obj: Record<string, unknown>): void {
521
532
  throw new Error("tiers.json: modelGenerations must be an object");
522
533
  }
523
534
  const modelGenerations = obj.modelGenerations as Record<string, unknown>;
524
- for (const key of ["claude5x", "strong"] as const) {
525
- if (
526
- modelGenerations[key] !== undefined &&
527
- !Array.isArray(modelGenerations[key])
528
- ) {
529
- throw new Error(`tiers.json: modelGenerations.${key} must be an array`);
530
- }
535
+ // Only `strong` is validated because only `strong` is read. Unknown keys —
536
+ // including the removed `claude5x` — are ignored rather than rejected, so an
537
+ // existing tiers.json carrying one still loads.
538
+ if (
539
+ modelGenerations.strong !== undefined &&
540
+ !Array.isArray(modelGenerations.strong)
541
+ ) {
542
+ throw new Error("tiers.json: modelGenerations.strong must be an array");
531
543
  }
532
544
  }
533
545
  }
@@ -0,0 +1,122 @@
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
+ */
30
+
31
+ export interface PluginLogger {
32
+ warn(message: string, extra?: Record<string, unknown>): void;
33
+ }
34
+
35
+ /** The service tag on every entry, so entries are greppable by origin. */
36
+ export const LOG_SERVICE = "model-router";
37
+
38
+ /** Prefix used only on the console fallback, where there is no service field. */
39
+ const CONSOLE_PREFIX = `[${LOG_SERVICE}]`;
40
+
41
+ type LogRequest = {
42
+ body: {
43
+ service: string;
44
+ level: "debug" | "info" | "error" | "warn";
45
+ message: string;
46
+ extra?: Record<string, unknown>;
47
+ };
48
+ };
49
+
50
+ /**
51
+ * Structural view of the one method we use. Deliberately narrow: the plugin
52
+ * must keep working against a bare stub (every unit test hands it one) and
53
+ * against an older server with no `/log` at all, so the capability is probed at
54
+ * runtime rather than demanded by the type.
55
+ */
56
+ type LogCapableClient = {
57
+ app?: {
58
+ log?: (req: LogRequest) => unknown;
59
+ };
60
+ };
61
+
62
+ /**
63
+ * The SDK resolves rather than rejects on an HTTP failure, reporting it as a
64
+ * populated `error` field on the settled value. Treat that as a failed post.
65
+ */
66
+ function isErrorResult(value: unknown): boolean {
67
+ return (
68
+ typeof value === "object" &&
69
+ value !== null &&
70
+ "error" in value &&
71
+ (value as { error?: unknown }).error !== undefined
72
+ );
73
+ }
74
+
75
+ /**
76
+ * Build a logger over an opencode client. Falls back to the console when the
77
+ * client cannot log, which covers older servers and every unit test that hands
78
+ * the plugin a stub.
79
+ */
80
+ export function createPluginLogger(client?: unknown): PluginLogger {
81
+ const app = (client as LogCapableClient | undefined)?.app;
82
+ const log = app?.log;
83
+
84
+ if (!app || typeof log !== "function") {
85
+ return {
86
+ warn(message) {
87
+ console.warn(`${CONSOLE_PREFIX} ${message}`);
88
+ },
89
+ };
90
+ }
91
+
92
+ return {
93
+ warn(message, extra) {
94
+ const toConsole = () => console.warn(`${CONSOLE_PREFIX} ${message}`);
95
+ let result: unknown;
96
+ try {
97
+ // Bound to `app` on purpose — see (1) in the module comment. Calling
98
+ // the detached reference would throw on every real client.
99
+ result = log.call(app, {
100
+ body: {
101
+ service: LOG_SERVICE,
102
+ level: "warn",
103
+ message,
104
+ ...(extra ? { extra } : {}),
105
+ },
106
+ });
107
+ } catch {
108
+ // A synchronous throw means the transport is unusable; say it somewhere.
109
+ toConsole();
110
+ return;
111
+ }
112
+ // Fire-and-forget: never await, but never leave a rejection unhandled
113
+ // either, and do not lose the diagnostic when the post fails — whether it
114
+ // fails by rejecting or by resolving with an error. See (2) above.
115
+ void Promise.resolve(result)
116
+ .then((settled) => {
117
+ if (isErrorResult(settled)) toConsole();
118
+ })
119
+ .catch(toConsole);
120
+ },
121
+ };
122
+ }
@@ -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. */
package/tiers.json CHANGED
@@ -46,9 +46,9 @@
46
46
  "presets": {
47
47
  "anthropic": {
48
48
  "fast": {
49
- "model": "anthropic/claude-haiku-4-5",
49
+ "model": "anthropic/claude-sonnet-5",
50
50
  "costRatio": 1,
51
- "description": "Haiku 4.5 for exploration, search, and simple reads",
51
+ "description": "Sonnet 5 for exploration, search, and simple reads",
52
52
  "steps": 30,
53
53
  "whenToUse": [
54
54
  "Codebase exploration and search",
@@ -58,10 +58,11 @@
58
58
  ]
59
59
  },
60
60
  "medium": {
61
- "model": "anthropic/claude-sonnet-4-6",
62
- "variant": "max",
61
+ "model": "anthropic/claude-opus-5",
62
+ "variant": "high",
63
+ "effort": "high",
63
64
  "costRatio": 5,
64
- "description": "Sonnet 4.6 max for implementation, refactoring, and tests",
65
+ "description": "Opus 5 high for implementation, refactoring, and tests",
65
66
  "steps": 50,
66
67
  "whenToUse": [
67
68
  "Feature implementation",
@@ -72,10 +73,10 @@
72
73
  ]
73
74
  },
74
75
  "heavy": {
75
- "model": "anthropic/claude-opus-4-8",
76
+ "model": "anthropic/claude-fable-5",
76
77
  "variant": "max",
77
78
  "costRatio": 20,
78
- "description": "Opus 4.8 max for architecture, complex debugging, and security",
79
+ "description": "Fable 5 max for architecture, complex debugging, and security",
79
80
  "steps": 120,
80
81
  "whenToUse": [
81
82
  "Architecture decisions",
@@ -87,9 +88,9 @@
87
88
  },
88
89
  "openai": {
89
90
  "fast": {
90
- "model": "openai/gpt-5.4-mini-fast",
91
+ "model": "openai/gpt-5.6-luna-fast",
91
92
  "costRatio": 1,
92
- "description": "GPT-5.4 Mini Fast for fast exploration and simple tasks",
93
+ "description": "GPT-5.6 Luna Fast for fast exploration and simple tasks",
93
94
  "steps": 30,
94
95
  "whenToUse": [
95
96
  "Codebase exploration and search",
@@ -98,10 +99,10 @@
98
99
  ]
99
100
  },
100
101
  "medium": {
101
- "model": "openai/gpt-5.5-fast",
102
+ "model": "openai/gpt-5.6-terra-fast",
102
103
  "variant": "high",
103
104
  "costRatio": 5,
104
- "description": "GPT-5.5 fast default settings for implementation and standard coding",
105
+ "description": "GPT-5.6 Terra Fast (high) for implementation and standard coding",
105
106
  "steps": 50,
106
107
  "whenToUse": [
107
108
  "Feature implementation",
@@ -111,10 +112,10 @@
111
112
  ]
112
113
  },
113
114
  "heavy": {
114
- "model": "openai/gpt-5.5-fast",
115
+ "model": "openai/gpt-5.6-sol-fast",
115
116
  "variant": "xhigh",
116
117
  "costRatio": 20,
117
- "description": "GPT-5.4 xhigh for architecture and complex tasks",
118
+ "description": "GPT-5.6 Sol Fast (xhigh) for architecture and complex tasks",
118
119
  "steps": 120,
119
120
  "whenToUse": [
120
121
  "Architecture decisions",
@@ -138,9 +139,9 @@
138
139
  ]
139
140
  },
140
141
  "medium": {
141
- "model": "github-copilot/claude-sonnet-4.6",
142
+ "model": "github-copilot/claude-sonnet-5",
142
143
  "costRatio": 5,
143
- "description": "Claude Sonnet 4.6 via GitHub Copilot for implementation, refactoring, and tests",
144
+ "description": "Claude Sonnet 5 via GitHub Copilot for implementation, refactoring, and tests",
144
145
  "steps": 50,
145
146
  "whenToUse": [
146
147
  "Feature implementation",
@@ -151,9 +152,9 @@
151
152
  ]
152
153
  },
153
154
  "heavy": {
154
- "model": "github-copilot/claude-opus-4.6",
155
+ "model": "github-copilot/claude-fable-5",
155
156
  "costRatio": 20,
156
- "description": "Claude Opus 4.6 via GitHub Copilot for architecture, complex debugging, and security",
157
+ "description": "Claude Fable 5 via GitHub Copilot for architecture, complex debugging, and security",
157
158
  "steps": 120,
158
159
  "whenToUse": [
159
160
  "Architecture decisions",
@@ -165,9 +166,9 @@
165
166
  },
166
167
  "google": {
167
168
  "fast": {
168
- "model": "google/gemini-2.5-flash",
169
+ "model": "google/gemini-3.5-flash-lite",
169
170
  "costRatio": 1,
170
- "description": "Gemini 2.5 Flash for fast exploration and simple tasks",
171
+ "description": "Gemini 3.5 Flash Lite for fast exploration and simple tasks",
171
172
  "steps": 30,
172
173
  "whenToUse": [
173
174
  "Codebase exploration and search",
@@ -177,9 +178,9 @@
177
178
  ]
178
179
  },
179
180
  "medium": {
180
- "model": "google/gemini-2.5-pro",
181
+ "model": "google/gemini-3.7-flash",
181
182
  "costRatio": 5,
182
- "description": "Gemini 2.5 Pro for implementation, refactoring, and tests",
183
+ "description": "Gemini 3.7 Flash for implementation, refactoring, and tests",
183
184
  "steps": 50,
184
185
  "whenToUse": [
185
186
  "Feature implementation",
@@ -190,9 +191,9 @@
190
191
  ]
191
192
  },
192
193
  "heavy": {
193
- "model": "google/gemini-3-pro-preview",
194
+ "model": "google/gemini-3.1-pro-preview",
194
195
  "costRatio": 20,
195
- "description": "Gemini 3 Pro Preview for architecture, complex debugging, and security",
196
+ "description": "Gemini 3.1 Pro Preview for architecture, complex debugging, and security",
196
197
  "steps": 120,
197
198
  "whenToUse": [
198
199
  "Architecture decisions",
@@ -216,10 +217,10 @@
216
217
  ]
217
218
  },
218
219
  "medium": {
219
- "model": "openai/gpt-5.5-fast",
220
+ "model": "openai/gpt-5.6-terra-fast",
220
221
  "variant": "high",
221
222
  "costRatio": 5,
222
- "description": "GPT-5.5 fast default settings for implementation and standard coding",
223
+ "description": "GPT-5.6 Terra Fast (high) for implementation and standard coding",
223
224
  "steps": 50,
224
225
  "whenToUse": [
225
226
  "Feature implementation",
@@ -229,10 +230,10 @@
229
230
  ]
230
231
  },
231
232
  "heavy": {
232
- "model": "anthropic/claude-opus-4-8",
233
+ "model": "anthropic/claude-opus-5",
233
234
  "variant": "max",
234
235
  "costRatio": 20,
235
- "description": "Claude Opus 4.8 max for architecture, complex debugging, and security",
236
+ "description": "Claude Opus 5 max for architecture, complex debugging, and security",
236
237
  "steps": 120,
237
238
  "whenToUse": [
238
239
  "Architecture decisions",