opencode-model-router 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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
 
@@ -298,6 +350,15 @@ Restart opencode after adding a new preset so its tier subagents get registered.
298
350
 
299
351
  > **`activePreset` / `activeMode` / `enforcement.mode` in an override file are _defaults_.** Runtime selections — `/preset`, `/budget`, `/router enforce` — are persisted to the state file (`~/.config/opencode/opencode-model-router.state.json`), which is applied **after** the override files and therefore wins. So the override's `activePreset` takes effect until you switch at runtime; if it ever "isn't taking", it's because a past `/preset` left a value in the state file — run `/preset <name>` again or delete that file. (The state file is machine-written, so the plugin never rewrites your hand-authored, commented override file.)
300
352
 
353
+ ### Keeping models current
354
+
355
+ You do not have to wait on a plugin release when providers ship new models. opencode already resolves a live model catalog (models.dev plus your configured and authenticated providers), and the plugin reads it directly. No external fetch, no hardcoded list.
356
+
357
+ - **`/router models [provider]`** lists the valid model ids for your configured providers, each annotated with the provider's default and any `deprecated`, `alpha` or `beta` status. Copy an id straight into an overrides file.
358
+ - **Validation.** Bare `/router` checks the active preset's tier models against the catalog and reports any that are missing or deprecated, with the closest valid suggestions. A stale id surfaces immediately instead of failing silently on every subagent dispatch. The same check is logged once per session to the plugin console.
359
+
360
+ This is report-only. The plugin never changes your models for you: it tells you what is available and what to change, and you set it in the overrides file.
361
+
301
362
  ### Advanced: edit the bundled `tiers.json` directly
302
363
 
303
364
  For an npm install, `tiers.json` is **inside the cached package directory**, not your `~/.config/opencode/` folder — typically:
@@ -310,35 +371,42 @@ For an npm install, `tiers.json` is **inside the cached package directory**, not
310
371
 
311
372
  ### Presets
312
373
 
313
- The plugin ships with four presets (switch with `/preset <name>`):
374
+ The plugin ships with six presets (switch with `/preset <name>`):
314
375
 
315
376
  **anthropic** (default):
316
377
  | Tier | Model | Cost ratio |
317
378
  |------|-------|-----------|
318
- | @fast | `anthropic/claude-haiku-4-5` | 1x |
319
- | @medium | `anthropic/claude-sonnet-4-5` (max) | 5x |
320
- | @heavy | `anthropic/claude-opus-4-6` (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 |
321
382
 
322
383
  **openai**:
323
384
  | Tier | Model | Cost ratio |
324
385
  |------|-------|-----------|
325
- | @fast | `openai/gpt-5.3-codex-spark` | 1x |
326
- | @medium | `openai/gpt-5.3-codex` | 5x |
327
- | @heavy | `openai/gpt-5.3-codex` (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 |
328
389
 
329
390
  **github-copilot**:
330
391
  | Tier | Model | Cost ratio |
331
392
  |------|-------|-----------|
332
- | @fast | `github-copilot/claude-haiku-4-5` | 1x |
333
- | @medium | `github-copilot/claude-sonnet-4-5` | 5x |
334
- | @heavy | `github-copilot/claude-opus-4-6` (thinking) | 20x |
393
+ | @fast | `github-copilot/claude-haiku-4.5` | 1x |
394
+ | @medium | `github-copilot/claude-sonnet-5` | 5x |
395
+ | @heavy | `github-copilot/claude-fable-5` | 20x |
335
396
 
336
397
  **google**:
337
398
  | Tier | Model | Cost ratio |
338
399
  |------|-------|-----------|
339
- | @fast | `google/gemini-2.5-flash` | 1x |
340
- | @medium | `google/gemini-2.5-pro` | 5x |
341
- | @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 |
403
+
404
+ **hybrid** — Anthropic for exploration and heavy analysis, OpenAI for implementation:
405
+ | Tier | Model | Cost ratio |
406
+ |------|-------|-----------|
407
+ | @fast | `anthropic/claude-haiku-4-5` | 1x |
408
+ | @medium | `openai/gpt-5.6-terra-fast` (high) | 5x |
409
+ | @heavy | `anthropic/claude-opus-5` (max) | 20x |
342
410
 
343
411
  **fable-effort** — one model, three reasoning depths (see [per-tier `effort`](#per-tier-effort)):
344
412
  | Tier | Model | Effort | Cost ratio |
@@ -365,7 +433,7 @@ highest first:
365
433
  |---|---|---|
366
434
  | Anthropic | `options.effort`, incl. `xhigh`/`max` | 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. |
367
435
  | OpenAI | `options.reasoning_effort` | Supports only `low`/`medium`/`high`; `xhigh` and `max` are downgraded to `high` with a warning. |
368
- | Other (Google, Copilot, …) | nothing | Dropped with a warning — no known mapping. |
436
+ | Other (Google, …) | nothing | Dropped with a warning — no known mapping. Detection is by model family, not provider prefix, so Copilot-proxied ids (`github-copilot/gpt-4o`, `github-copilot/claude-sonnet-4`) take their family's knob above. |
369
437
 
370
438
  An out-of-set value in `tiers.json` fails validation at load; one that arrives any other
371
439
  way is ignored with a single warning. Full detail in
@@ -493,6 +561,13 @@ A "resume" is a second `chat.message` to a session already tracked at the **same
493
561
 
494
562
  The ceiling follows the *current* cap, so a tighter resumed cap tightens the ceiling. `CAP:none` has no per-dispatch budget to derive from and therefore no cumulative ceiling. A **retry** (new session, e.g. an escalation to another tier) is not a resume: it gets fresh counters and an empty redundancy map. A session evicted by the idle-TTL sweep also comes back fresh.
495
563
 
564
+ The sweep exists so per-session bookkeeping does not grow without bound in a long-running
565
+ opencode process. A session is evicted once it has been idle for **1 hour**; every mutating
566
+ entry point refreshes its stamp, and a tool call refreshes at *start* so a single long call
567
+ cannot age out mid-flight. There are no timers: the sweep runs opportunistically off chat
568
+ activity, throttled to at most once every **5 minutes**, and covers the four session-keyed
569
+ stores (subagent sessions, guard state, trajectory telemetry, and changed-file tracking).
570
+
496
571
  The same accounting exists at the hard-guard layer: `guard.budget` resets per dispatch, with a cumulative ceiling of `guard.budget × 3` enforced as `cumulative_iteration_cap`.
497
572
 
498
573
  **If you never resume a subagent session, nothing changes** — a first dispatch's cumulative count equals its per-dispatch count, so the ceiling is unreachable and every banner is byte-identical to before.
@@ -578,9 +653,9 @@ Each tier (`@fast`, `@medium`, `@heavy`) has a system prompt that describes its
578
653
  },
579
654
  "presets": {
580
655
  "anthropic": {
581
- "fast": { "model": "anthropic/claude-haiku-4-5", ... },
582
- "medium": { "model": "anthropic/claude-sonnet-4-6", ... },
583
- "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", ... }
584
659
  }
585
660
  }
586
661
  }
@@ -594,6 +669,46 @@ Each tier (`@fast`, `@medium`, `@heavy`) has a system prompt that describes its
594
669
 
595
670
  Two wordings of every default prompt ship: the enumerated `tierPrompts` above, and a shorter goal-oriented set. Which one a tier gets is decided by `promptStyle`, which defaults to `auto` (goal-oriented for strong models). See [Prompt styles](docs/CONFIG_REFERENCE.md#prompt-styles-promptstyle) in the config reference — including which shipped presets are affected.
596
671
 
672
+ To replace a built-in goal-oriented prompt, set `tierPromptsGoalOriented` in the overrides
673
+ file. It is the goal-oriented twin of `tierPrompts`: an entry replaces the built-in default
674
+ for that tier name only, and tiers you do not list keep theirs.
675
+
676
+ ```jsonc
677
+ {
678
+ // Only affects tiers that resolve to the goal-oriented style.
679
+ "tierPromptsGoalOriented": {
680
+ "medium": "You are @medium. Ship the change described in the dispatch, match the surrounding code, and return the files you touched plus the verification you ran."
681
+ }
682
+ }
683
+ ```
684
+
685
+ #### `modelGenerations`
686
+
687
+ `modelGenerations` holds shared, case-insensitive substring patterns matched against a
688
+ tier's model ID. Two lists exist:
689
+
690
+ | List | Default | What it drives |
691
+ |------|---------|----------------|
692
+ | `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
+ 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
697
+ prompt prefixes and the anti-narration detector do **not** use these lists; they match the
698
+ model ID directly (`isClaudeModel` in `src/router/protocol.ts`).
699
+
700
+ ```jsonc
701
+ {
702
+ "modelGenerations": {
703
+ // Keep the shipped patterns and add a locally-hosted strong model.
704
+ "strong": ["claude-fable-5", "claude-mythos-5", "opus-4-8", "claude-opus-5", "my-org/big-coder"]
705
+ }
706
+ }
707
+ ```
708
+
709
+ See [Prompt styles](docs/CONFIG_REFERENCE.md#prompt-styles-promptstyle) in the config
710
+ reference for the full description.
711
+
597
712
  **When to customize:** if a specific provider/model in a preset needs different instructions (e.g. Gemini-specific tool format, tighter/looser caps for a weaker local model), add `"prompt": "..."` on that tier only. All other presets keep using the global.
598
713
 
599
714
  ```json
@@ -601,7 +716,7 @@ Two wordings of every default prompt ship: the enumerated `tierPrompts` above, a
601
716
  "presets": {
602
717
  "google": {
603
718
  "fast": {
604
- "model": "google/gemini-2.5-flash",
719
+ "model": "google/gemini-3.5-flash-lite",
605
720
  "prompt": "You are @fast (Gemini-tuned variant) — ...",
606
721
  ...
607
722
  }
@@ -688,12 +803,45 @@ When `antiNarration` is enabled, the detector runs for all models (not only Clau
688
803
  | `costRatio` | number | Relative cost (1 = cheapest). Shown in prompt. |
689
804
  | `thinking` | object | Anthropic thinking: `{ "budgetTokens": 10000 }` |
690
805
  | `reasoning` | object | OpenAI reasoning: `{ "effort": "high", "summary": "detailed" }` |
806
+ | `effort` | string | Provider-agnostic reasoning effort: `"low"`, `"medium"`, `"high"`, `"xhigh"`, `"max"`. See [Per-tier `effort`](#per-tier-effort). |
807
+ | `color` | string | Optional agent colour passed through to the opencode agent registration. |
691
808
  | `description` | string | Shown in `/tiers` output |
692
809
  | `steps` | number | Max agent turns |
693
810
  | `prompt` | string | Optional per-tier system prompt override. Falls back to the style-appropriate default when omitted. |
694
811
  | `promptStyle` | string | `"prescriptive"`, `"goal-oriented"` or `"auto"` (default). Picks which default prompt the tier gets; ignored when `prompt` is set. |
695
812
  | `whenToUse` | string[] | Use cases (shown in `/tiers`, not in system prompt) |
696
813
 
814
+ ### Routing your own subagents (`subagentTiers`, opt-in)
815
+
816
+ If you already have custom subagents (`.opencode/agents/**`), they do **not** get routed by default. An agent that declares no `model` inherits the model of whoever invoked it, usually your orchestrator, so a cheap read-only helper quietly runs at orchestrator prices.
817
+
818
+ `subagentTiers` maps your agent names to tiers, and the plugin repoints them at the active preset's models:
819
+
820
+ ```jsonc
821
+ {
822
+ "subagentTiers": {
823
+ "ContextScout": "fast",
824
+ "CodeReviewer": "medium",
825
+ "SecurityReviewer": "heavy"
826
+ }
827
+ }
828
+ ```
829
+
830
+ The point of doing this here rather than in `opencode.json` is that these agents then **follow `/preset`**. Switch to `openai` and `ContextScout` moves to that preset's fast model along with `@fast`. No model IDs live in your agent files, and a committed project overrides file gives the whole team the same routing.
831
+
832
+ **Getting the names right.** The key is opencode's agent name: the frontmatter `name:` field when the agent declares one, otherwise the file's path-derived name (`agents/team/helper.md` becomes `team/helper`). Frontmatter wins, so an agent in `subagents/core/contextscout.md` with `name: ContextScout` is keyed `ContextScout`. Matching is case-sensitive.
833
+
834
+ **Rules, all deliberate:**
835
+
836
+ - **Opt-in.** No map, or an empty one, and nothing is touched.
837
+ - **The map wins over the agent's own `model`.** This is the point, and it is what lets you delete hardcoded model IDs from agent files. If you want an agent to keep its pinned model, leave it out of the map.
838
+ - **List subagents only.** Primary agents are the orchestrator, so pinning one to a tier defeats the routing. Agents already registered with a non-`subagent` mode are skipped, but a *markdown* agent's mode is not visible when the map is applied, so a primary agent listed there would still be repointed.
839
+ - **Unknown tier names are skipped**, not fatal. A map written for a preset that defines a tier this one does not must never break startup.
840
+ - **Tier names are never overwritten.** An entry keyed `fast`/`medium`/`heavy` is ignored so it cannot clobber the plugin's own agents.
841
+ - **Variants are set explicitly.** If the target tier has no `variant`, any variant already on the agent is removed rather than inherited. An inherited variant from another provider fails at dispatch, not at load.
842
+
843
+ Anything not listed is left exactly as opencode built it.
844
+
697
845
  ### Fallback
698
846
 
699
847
  Defines provider fallback order when a delegated task fails:
@@ -736,6 +884,53 @@ Advisory is the default. To change the level:
736
884
 
737
885
  > Enforcement applies to subagent/delegate sessions only. The orchestrator session is never hard-blocked.
738
886
 
887
+ **Per-tier override.** `enforcement.perTier` maps a tier name to `off`, `advisory` or
888
+ `enforced` and wins over the global `mode` for delegations to that tier — useful to keep
889
+ `@fast` advisory while `@medium` and `@heavy` are enforced:
890
+
891
+ ```jsonc
892
+ {
893
+ "enforcement": {
894
+ "mode": "enforced",
895
+ "perTier": { "fast": "advisory" }
896
+ }
897
+ }
898
+ ```
899
+
900
+ #### Time-boxes
901
+
902
+ Three ceilings bound the verification pipeline so a stuck model cannot hang a delegation
903
+ forever. All are integers in milliseconds, live under `enforcement.verify`, and ship
904
+ explicitly in `tiers.json`:
905
+
906
+ | Key | Bundled default | Bounds |
907
+ |-----|-----------------|--------|
908
+ | `delegateTimeoutMs` | `600000` (10 min) | One producer turn. |
909
+ | `graderTimeoutMs` | `60000` (1 min) | One grader turn. |
910
+ | `gateBudgetMs` | `90000` (90 s) | The whole acceptance gate. |
911
+
912
+ Each budget is per **ladder attempt**, not per delegation: a fast → medium → heavy
913
+ escalation gives every attempt its own fresh clock. On expiry the child session is
914
+ cancelled for real via `session.abort` rather than left running, and the attempt is
915
+ recorded as failed so the ladder advances — an expired budget never yields a fabricated
916
+ pass, only an honest `status: unmet`.
917
+
918
+ Raise a ceiling rather than removing it; `0` and negative values are rejected by
919
+ `validateConfig`, not read as "no timeout".
920
+
921
+ ```jsonc
922
+ {
923
+ "enforcement": {
924
+ "verify": {
925
+ // A slow local model needs longer than the 10-minute default.
926
+ "delegateTimeoutMs": 1800000
927
+ }
928
+ }
929
+ }
930
+ ```
931
+
932
+ Full field notes are in [docs/CONFIG_REFERENCE.md](docs/CONFIG_REFERENCE.md).
933
+
739
934
  ### Deep-dive documentation
740
935
 
741
936
  - `docs/ENFORCEMENT.md` — architecture, hook wiring, session lifecycle
@@ -750,14 +945,16 @@ Advisory is the default. To change the level:
750
945
 
751
946
  | Command | Description |
752
947
  |---------|-------------|
753
- | `/tiers` | Show active tier configuration, models, and rules |
948
+ | `/tiers` | Show active tier configuration, models, rules, and each tier's resolved prompt style |
754
949
  | `/preset` | List available presets |
755
950
  | `/preset <name>` | Switch preset (e.g., `/preset openai`) |
756
951
  | `/budget` | Show available modes and which is active |
757
952
  | `/budget <mode>` | Switch routing mode (`normal`, `budget`, `quality`, `deep`) |
758
953
  | `/annotate-plan [path]` | Annotate a plan file with `[tier:X]` tags for each step |
759
954
  | `/router overrides` | Show the global + project override file paths and merge precedence |
955
+ | `/router models [provider]` | List valid model ids from your configured providers (with defaults and deprecated flags) |
760
956
  | `/router enforce <off\|advisory\|enforced>` | Set delegation-enforcement mode (persisted) |
957
+ | `/router` | With no subcommand — or an unrecognized one — prints the `/router` help and the current enforcement mode |
761
958
  | `/bypass [on\|off]` | Toggle the router off/on for the session |
762
959
 
763
960
  ## Plan annotation
@@ -784,7 +981,7 @@ After `/annotate-plan`:
784
981
 
785
982
  ## Token overhead
786
983
 
787
- 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.
984
+ 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.
788
985
 
789
986
  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.
790
987
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "1.6.0",
3
+ "version": "1.8.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",
@@ -41,7 +41,8 @@
41
41
  "src/",
42
42
  "tiers.json",
43
43
  "LICENSE",
44
- "README.md"
44
+ "README.md",
45
+ "CHANGELOG.md"
45
46
  ],
46
47
  "peerDependencies": {
47
48
  "@opencode-ai/plugin": ">=1.0.0"
@@ -11,32 +11,10 @@
11
11
  * what happened — which made the output impossible to test without a state
12
12
  * file on disk and a plugin instance to hang it off.
13
13
  */
14
- import type { RouterConfig, TierConfig, ModeConfig } from "../router/config";
14
+ import type { RouterConfig, ModeConfig } from "../router/config";
15
15
  import { getActiveTiers } from "../router/protocol";
16
-
17
- /** Provider-specific agent options (thinking / reasoning) for a tier. */
18
- export function buildAgentOptions(tier: TierConfig): Record<string, unknown> {
19
- const opts: Record<string, unknown> = {};
20
-
21
- // Anthropic thinking config
22
- if (tier.thinking) {
23
- if (tier.thinking.budgetTokens) {
24
- opts.budget_tokens = tier.thinking.budgetTokens;
25
- }
26
- }
27
-
28
- // OpenAI reasoning config
29
- if (tier.reasoning) {
30
- if (tier.reasoning.effort) {
31
- opts.reasoning_effort = tier.reasoning.effort;
32
- }
33
- if (tier.reasoning.summary) {
34
- opts.reasoning_summary = tier.reasoning.summary;
35
- }
36
- }
37
-
38
- return Object.keys(opts).length > 0 ? opts : {};
39
- }
16
+ import { resolvePromptStyle } from "../router/prompts";
17
+ import type { Catalog, ModelIssue } from "../router/catalog";
40
18
 
41
19
  /** `/tiers` */
42
20
  export function buildTiersOutput(cfg: RouterConfig): string {
@@ -52,7 +30,17 @@ export function buildTiersOutput(cfg: RouterConfig): string {
52
30
  : tier.reasoning
53
31
  ? ` | reasoning: effort=${tier.reasoning.effort}`
54
32
  : "";
55
- lines.push(`## @${name} -> \`${tier.model}\`${thinkingStr}`);
33
+ // The auto rule flips strong models to goal-oriented silently, so show the
34
+ // style the dispatch actually resolves to. An explicit `tier.prompt` wins
35
+ // outright (src/index.ts: `tier.prompt ?? selectTierPrompt(...)`).
36
+ const explicitStyle =
37
+ tier.promptStyle === "prescriptive" || tier.promptStyle === "goal-oriented";
38
+ const promptStr = tier.prompt
39
+ ? " | prompt: custom"
40
+ : ` | prompt: ${resolvePromptStyle(tier.promptStyle, tier.model, cfg)} (${
41
+ explicitStyle ? "explicit" : "auto"
42
+ })`;
43
+ lines.push(`## @${name} -> \`${tier.model}\`${thinkingStr}${promptStr}`);
56
44
  if (tier.description) lines.push(tier.description);
57
45
  lines.push(`Steps: ${tier.steps ?? "default"}`);
58
46
  const whenToUse = tier.whenToUse ?? [];
@@ -231,6 +219,124 @@ export function buildRouterHelp(current: string): string {
231
219
  "Commands:",
232
220
  "- `/router enforce <off|advisory|enforced>` — set hard-block enforcement (persisted)",
233
221
  "- `/router overrides` — show the global + project override file paths and precedence",
222
+ "- `/router models [provider]` — list valid model ids from your configured providers",
234
223
  "- `/tiers`, `/preset`, `/budget`, `/bypass`, `/annotate-plan`",
235
224
  ].join("\n");
236
225
  }
226
+
227
+ /**
228
+ * `/router models [provider]`. Takes the catalog the caller fetched, so a
229
+ * failed or unavailable fetch is a null here rather than an exception path.
230
+ */
231
+ export function buildModelsOutput(
232
+ catalog: Catalog | null,
233
+ filter: string,
234
+ orphanedStrongPatterns: string[] = [],
235
+ strongPatternNearMisses: Record<string, string[]> = {},
236
+ ): string {
237
+ // Orphan patterns are pure config analysis, so they are appended to EVERY
238
+ // return path — including the catalog-unavailable ones, where the warning is
239
+ // just as valid.
240
+ const suffix =
241
+ orphanedStrongPatterns.length > 0
242
+ ? "\n\n" +
243
+ formatOrphanedStrongPatterns(orphanedStrongPatterns, strongPatternNearMisses)
244
+ : "";
245
+ if (!catalog) {
246
+ return (
247
+ "Model catalog unavailable — could not query opencode's providers." + suffix
248
+ );
249
+ }
250
+ if (catalog.providers.length === 0) {
251
+ return "No providers are configured/authenticated in opencode." + suffix;
252
+ }
253
+ const f = filter.trim().toLowerCase();
254
+ const providers = f
255
+ ? catalog.providers.filter((p) => p.id.toLowerCase() === f)
256
+ : catalog.providers;
257
+ if (providers.length === 0) {
258
+ return (
259
+ `No configured provider matches \`${filter.trim()}\`. Available: ${catalog.providers
260
+ .map((p) => p.id)
261
+ .join(", ")}.` + suffix
262
+ );
263
+ }
264
+
265
+ const lines: string[] = ["# Model Router — available models", ""];
266
+ for (const p of providers) {
267
+ const name = p.name && p.name !== p.id ? ` (${p.name})` : "";
268
+ const def = p.defaultModel ? ` — default: \`${p.id}/${p.defaultModel}\`` : "";
269
+ lines.push(`## ${p.id}${name}${def}`);
270
+ const sorted = [...p.models].sort((a, b) => a.id.localeCompare(b.id));
271
+ if (sorted.length === 0) {
272
+ lines.push("- _(no models)_");
273
+ } else {
274
+ for (const m of sorted) {
275
+ const flag = m.status && m.status !== "active" ? ` _(${m.status})_` : "";
276
+ lines.push(`- \`${p.id}/${m.id}\`${flag}`);
277
+ }
278
+ }
279
+ lines.push("");
280
+ }
281
+ lines.push(
282
+ "Paste any id above into an overrides file (`/router overrides` shows where).",
283
+ );
284
+ return lines.join("\n") + suffix;
285
+ }
286
+
287
+ /**
288
+ * Render strong-model patterns that match no model in the active preset (see
289
+ * `findOrphanedStrongPatterns`). Report-only — the router never edits the
290
+ * user's pattern list.
291
+ */
292
+ export function formatOrphanedStrongPatterns(
293
+ patterns: string[],
294
+ nearMisses: Record<string, string[]> = {},
295
+ ): string {
296
+ return [
297
+ "⚠ **Strong-model patterns matching no model your providers serve:**",
298
+ ...patterns.map((p) => {
299
+ const near = nearMisses[p] ?? [];
300
+ if (near.length === 0) return `- \`${p}\``;
301
+ // Named separately from the generic rename hint below: when we can point
302
+ // at the served id, the user can fix it without going to look.
303
+ return `- \`${p}\` — served under a different separator: ${near
304
+ .slice(0, 3)
305
+ .map((r) => `\`${r}\``)
306
+ .join(", ")}`;
307
+ }),
308
+ "",
309
+ "This may silently change prompt-style resolution for tiers on `promptStyle: auto`. If a provider renamed a model, update `modelGenerations.strong` in your overrides file (`/router overrides`).",
310
+ ].join("\n");
311
+ }
312
+
313
+ /** Render model-validation issues for the active preset as a markdown block. */
314
+ export function formatModelIssues(issues: ModelIssue[]): string {
315
+ const lines: string[] = ["⚠ **Model issues in the active preset:**"];
316
+ for (const it of issues) {
317
+ const what =
318
+ it.kind === "provider-unknown" || it.kind === "fallback-provider-unknown"
319
+ ? `provider \`${it.providerId}\` is not configured/authenticated` +
320
+ (it.kind === "fallback-provider-unknown"
321
+ ? " — this fallback chain can never fire"
322
+ : "")
323
+ : it.kind === "fallback-preset-unknown"
324
+ ? `chain entry \`${it.chainTarget}\` is not a defined preset and is silently dropped`
325
+ : it.kind === "model-deprecated"
326
+ ? `\`${it.ref}\` is **deprecated**`
327
+ : `\`${it.ref}\` was not found`;
328
+ // Fallback issues are keyed by the chain's provider, not by a tier.
329
+ const where =
330
+ it.scope === "fallback" ? `${it.tier}[${it.providerId}]` : `@${it.tier}`;
331
+ let line = `- ${where}: ${what}.`;
332
+ if (it.suggestions.length > 0) {
333
+ line += ` Try: ${it.suggestions.map((s) => `\`${s}\``).join(", ")}.`;
334
+ }
335
+ lines.push(line);
336
+ }
337
+ lines.push(
338
+ "",
339
+ "Set a replacement in your overrides file (`/router overrides`), then re-run `/router`.",
340
+ );
341
+ return lines.join("\n");
342
+ }