opencode-model-router 1.15.0 → 2.0.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,64 @@ 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
+ ## [Unreleased]
9
+
10
+ ## [2.0.0] - 2026-10-04
11
+
12
+ The router now runs on OpenCode v2 through a separate server entrypoint. **OpenCode v1
13
+ remains supported**: the callable v1 entrypoint and every config key are unchanged. The
14
+ major version marks the new host support and the updated bundled preset defaults. See
15
+ [the compatibility notes](docs/OPENCODE_V2.md).
16
+
17
+ ### Added
18
+
19
+ - OpenCode v2 compatibility through a separate server entrypoint, fixing the
20
+ `Expected object at ["default"]` plugin validation error while preserving the
21
+ callable v1 entrypoint. The adapter translates agent registration, commands,
22
+ prompts, tool guards and verification to v2's domain APIs, and uses native
23
+ subagents for producer/grader sessions. A subagent's `background` request is
24
+ kept unless the router verifies that dispatch. Only router-added instructions
25
+ are translated to v2 tool names. V2 tier options reach requests through the
26
+ context hook, not unused agent settings. V2 ≥2.0.21 removes temporary children
27
+ after use; 2.0.20 retains their history. Anti-narration warnings appear as
28
+ synthetic transcript entries. Includes an opt-in provider-backed v2 e2e smoke
29
+ adapted from @ChronosWS (Cliff Hudson). See
30
+ [the compatibility notes](docs/OPENCODE_V2.md).
31
+ - **Behavior note:** on v2, graders send no temperature (the provider default
32
+ applies, not `graderTemperature`) unless the exact `provider/model` is listed in
33
+ `enforcement.verify.graderTemperatureModels` (reported by @ChronosWS).
34
+
35
+ ### Changed
36
+
37
+ - Bundled presets updated: `anthropic` fast → Sonnet 5.5 low, medium → Sonnet
38
+ 5.5 medium (was Opus 5.5 low); `openai` medium → `gpt-6.1-sol-fast` xhigh;
39
+ `hybrid` fast → Luna medium, medium → Astra high, heavy → Opus 5.5 xhigh
40
+ (was Fable 5.1 max). The orchestrator prompt grows by 11 characters:
41
+ 3,249 / 4,021 / 6,221 for base / Claude / Claude with enforcement.
42
+ - `hybrid` heavy now also sets `effort: "xhigh"`, like the `anthropic` preset's
43
+ heavy tier, so Opus 5.5 receives the effort and not only the variant. The
44
+ `github-copilot` heavy description names Fable 5.1, the model it runs.
45
+ - V1 graders no longer send `graderTemperature` to models whose capabilities
46
+ report `temperature: false`.
47
+
48
+ ### Fixed
49
+
50
+ - Setting `enforcement.verify.graderTemperature` to `null` removes any grader temperature,
51
+ including pre-existing values and v2 allowlisted models. Numeric values still respect
52
+ v1 model capabilities and the v2 allowlist. Grader response/API failures are reported as
53
+ SDK errors with metadata-only details before verdict parsing, rather than as parse failures.
54
+ - Native `task` acceptance checks could run in the router directory instead of the producer's worktree: `[acceptance]` now supports `cwd:` (a supplied tool cwd wins), and the deterministic gate returns unverifiable without running checks when all changed paths are absolute and outside its base.
55
+ - Windows e2e self-check waits for sampler snapshots instead of a fixed 2.5 s window (#61).
56
+ - Parallel deferred finishes now share their gate-time tree snapshot, as dispatch
57
+ starts already did. A run only serves finishes that asked before it started.
58
+ Unshared, 20 parallel deferred delegations on a 4-core Windows host ran 20
59
+ snapshots and 19 hit the 2 s finish bound, leaving their changes unattributed
60
+ (risk high). Measured with that affinity: finish p50 2.11 s → 0.96 s, 19 → 0 capped.
61
+
62
+ ### Documentation
63
+
64
+ - README updated for OpenCode v2 support, presets and requirements.
65
+
8
66
  ## [1.15.0] - 2026-09-28
9
67
 
10
68
  The acceptance gate no longer runs a test suite per delegation. `testsPass` now runs only
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  > **Use the cheapest model that can do the job. Automatically.**
6
6
 
7
- An [OpenCode](https://opencode.ai) plugin that routes every coding task to the right-priced AI tier — automatically, on every message, with 3,238–5,229 characters of system-prompt overhead depending on the orchestrator and enforcement mode.
7
+ An [OpenCode](https://opencode.ai) plugin that routes every coding task to the right-priced AI tier — automatically, on every message, with 3,249–6,357 characters of system-prompt overhead depending on the orchestrator and enforcement mode.
8
8
 
9
9
  ## Why it's different
10
10
 
@@ -14,7 +14,7 @@ Most AI coding tools give you one model for everything. You pay Opus prices to r
14
14
  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.
15
15
 
16
16
  **Inject a compressed, LLM-optimized routing protocol.**
17
- Instead of duplicated prose, the plugin injects a dense, machine-readable routing protocol. The protocol itself is 3,238 characters; a Claude orchestrator receives 4,010 characters after its authority prefix (roughly 1,000–1,115 tokens at 3.6–4.0 characters per token). Every message, every session.
17
+ Instead of duplicated prose, the plugin injects a dense, machine-readable routing protocol. The protocol itself is 3,249 characters; a Claude orchestrator receives 4,021 characters after its authority prefix (roughly 1,005–1,117 tokens at 3.6–4.0 characters per token). Every message, every session.
18
18
 
19
19
  **Match task to tier using a configurable taxonomy.**
20
20
  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.
@@ -67,7 +67,7 @@ opencode-model-router injects a **delegation protocol** into the system prompt t
67
67
  4. **Never over-qualify** — use the cheapest tier that can reliably handle the task
68
68
  5. **Fallback** across providers when one fails
69
69
 
70
- All of this adds 3,238 characters for a non-Claude orchestrator or 4,010 characters for a Claude orchestrator (roughly 810–1,115 tokens at 3.6–4.0 characters per token).
70
+ All of this adds 3,249 characters for a non-Claude orchestrator or 4,021 characters for a Claude orchestrator (roughly 812–1,117 tokens at 3.6–4.0 characters per token).
71
71
 
72
72
  ## Understanding how it works
73
73
 
@@ -168,13 +168,13 @@ Task distribution: 18 exploration (60%), 10 implementation (33%), 2 architecture
168
168
 
169
169
  ## How it works
170
170
 
171
- On every message, the plugin injects a 3,238-character routing protocol. A Claude orchestrator receives 4,010 characters after its authority prefix (roughly 1,000–1,115 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.
171
+ On every message, the plugin injects a 3,249-character routing protocol. A Claude orchestrator receives 4,021 characters after its authority prefix (roughly 1,005–1,117 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.
172
172
 
173
173
  What the orchestrator sees (Anthropic preset, normal mode):
174
174
 
175
175
  ```
176
176
  ## Model Delegation Protocol
177
- Preset: anthropic. Tiers: @fast=claude-sonnet-5(1x) @medium=claude-opus-5/high(5x) @heavy=claude-fable-5/max(20x). mode:normal
177
+ Preset: anthropic. Tiers: @fast=claude-sonnet-5-5/low(1x) @medium=claude-sonnet-5-5/medium(5x) @heavy=claude-opus-5-5/xhigh(20x). mode:normal
178
178
  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
179
179
  Multi-phase: prefer explore(@fast)→execute(@medium) when phases are separable. Cheapest-first when practical.
180
180
  1.[tier:X] tag in plan → delegate to X 2.plan:fast/cheap→@fast | plan:medium→@medium | plan:heavy→@heavy 3.default preference: read-only work → @fast; implementation → @medium 4.orchestrate=self, execute=subagent (info-gathering IS execution, not orchestration) 5.trivial (≤1 tool call, no expected follow-up) → direct, spent from the orchestrator read-only allowance 6.orchestrator read-only allowance (TARGET): dispatch is default; ≤2 direct read-only calls per turn; 3rd need → dispatch @fast (exceed only with 1-line reason) 7.dispatch caps baseline: @fast=CAP:8, @medium=CAP:5, @heavy=CAP:3 (omit directive = baseline; include CAP:N to override; CAP:none disables the cap only when the dispatch also carries a `reason:` line) 8.before dispatching @heavy: gather context first (usually via @fast); if context is already sufficient, dispatch directly 9.if self is opus: skip-@heavy (do locally); still prefer routing broader read-only exploration to @fast 10.min(cost, adequate-tier)
@@ -220,7 +220,7 @@ With router → split:
220
220
  | Cross-provider fallback | ✅ | ❌ | ❌ | ❌ | ❌ |
221
221
  | Cost ratio awareness | ✅ | ❌ | ❌ | ❌ | ❌ |
222
222
  | Plan annotation with tiers | ✅ | ❌ | ❌ | ❌ | ❌ |
223
- | Measured prompt overhead: 3,238–5,229 chars | ✅ | — | ❌ | ❌ | ❌ |
223
+ | Measured prompt overhead: 3,249–6,357 chars | ✅ | — | ❌ | ❌ | ❌ |
224
224
 
225
225
  **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.
226
226
 
@@ -250,6 +250,47 @@ Then install and configure model-router to handle the rest.
250
250
 
251
251
  ## Installation
252
252
 
253
+ ### OpenCode v2
254
+
255
+ The v2 adapter supports OpenCode hosts **2.0.20 or later** and typechecks against
256
+ `@opencode/plugin` **2.0.22**. Use the v2 `plugins` key:
257
+
258
+ ```json
259
+ {
260
+ "plugins": ["opencode-model-router"]
261
+ }
262
+ ```
263
+
264
+ For a local checkout, replace the package name with its absolute directory path.
265
+ V2 loads the package's `server.ts` definition; v1 continues to load the original
266
+ function from `src/index.ts`. Existing v1 configuration does not need to change.
267
+
268
+ Routing, tool guards and verification use the same engine on both versions. V2
269
+ uses its native `subagent` tool to create real child sessions, preserving the
270
+ host's permissions and cancellation. There are a few host differences:
271
+
272
+ - Delegations the router verifies run in the foreground so verification receives
273
+ a completed result; other `background` requests are kept. The router's own
274
+ deferred/background verification remains a separate setting.
275
+ - Temporary child sessions are removed after use on v2 ≥2.0.21; 2.0.20 can only
276
+ interrupt them, so their history is retained.
277
+ - Graders send no temperature unless the exact `provider/model` is listed in
278
+ `enforcement.verify.graderTemperatureModels`
279
+ ([details](docs/OPENCODE_V2.md#grader-temperature-on-v2)).
280
+ - Anti-narration warnings appear as separate synthetic transcript entries, because
281
+ completed v2 text events cannot be rewritten.
282
+ - Tier options (`effort`/`variant`/`reasoning_effort`, `budget_tokens`, etc.) are
283
+ applied per turn through the v2 `session` context hook, filling only keys not
284
+ already present, because v2 does not read `Agent.Info.request.settings`.
285
+
286
+ **Smoke tests:** Set `OPENCODE_V2_BIN` to the absolute path of an OpenCode v2
287
+ executable. `npm run smoke:v2` checks loading and registration without provider
288
+ credentials. `npm run smoke:v2:e2e` opts in to the end-to-end smoke (the script sets
289
+ `RUN_OC_SMOKE_V2_E2E=1`), driving `opencode run --standalone` against a local
290
+ deterministic OpenAI-compatible provider, also without provider credentials.
291
+
292
+ See [the v2 compatibility notes](docs/OPENCODE_V2.md) for the API mapping and validation.
293
+
253
294
  ### From npm (recommended)
254
295
  ```bash
255
296
  # In your opencode project or globally
@@ -378,23 +419,23 @@ The plugin ships with seven presets (switch with `/preset <name>`):
378
419
  **anthropic** (default):
379
420
  | Tier | Model | Cost ratio |
380
421
  |------|-------|-----------|
381
- | @fast | `anthropic/claude-sonnet-5` | 1x |
382
- | @medium | `anthropic/claude-opus-5` (high) | 5x |
383
- | @heavy | `anthropic/claude-fable-5` (max) | 20x |
422
+ | @fast | `anthropic/claude-sonnet-5-5` (variant/effort: low) | 1x |
423
+ | @medium | `anthropic/claude-sonnet-5-5` (variant/effort: medium) | 5x |
424
+ | @heavy | `anthropic/claude-opus-5-5` (variant/effort: xhigh) | 20x |
384
425
 
385
426
  **openai**:
386
427
  | Tier | Model | Cost ratio |
387
428
  |------|-------|-----------|
388
- | @fast | `openai/gpt-5.6-luna-fast` | 1x |
389
- | @medium | `openai/gpt-5.6-terra-fast` (high) | 5x |
390
- | @heavy | `openai/gpt-5.6-sol-fast` (xhigh) | 20x |
429
+ | @fast | `openai/gpt-6-luna-fast` | 1x |
430
+ | @medium | `openai/gpt-6.1-sol-fast` (xhigh) | 5x |
431
+ | @heavy | `openai/gpt-6-astra-fast` (max) | 20x |
391
432
 
392
433
  **github-copilot**:
393
434
  | Tier | Model | Cost ratio |
394
435
  |------|-------|-----------|
395
436
  | @fast | `github-copilot/claude-haiku-4.5` | 1x |
396
437
  | @medium | `github-copilot/claude-sonnet-5` | 5x |
397
- | @heavy | `github-copilot/claude-fable-5` | 20x |
438
+ | @heavy | `github-copilot/claude-fable-5-1` | 20x |
398
439
 
399
440
  **google**:
400
441
  | Tier | Model | Cost ratio |
@@ -403,19 +444,19 @@ The plugin ships with seven presets (switch with `/preset <name>`):
403
444
  | @medium | `google/gemini-3.7-flash` | 5x |
404
445
  | @heavy | `google/gemini-3.1-pro-preview` | 20x |
405
446
 
406
- **hybrid** — Anthropic for exploration and heavy analysis, OpenAI for implementation:
447
+ **hybrid** — OpenAI for exploration and implementation, Anthropic for heavy analysis:
407
448
  | Tier | Model | Cost ratio |
408
449
  |------|-------|-----------|
409
- | @fast | `anthropic/claude-haiku-4-5` | 1x |
410
- | @medium | `openai/gpt-5.6-terra-fast` (high) | 5x |
411
- | @heavy | `anthropic/claude-opus-5` (max) | 20x |
450
+ | @fast | `openai/gpt-6-luna-fast` (medium) | 1x |
451
+ | @medium | `openai/gpt-6-astra-fast` (high) | 5x |
452
+ | @heavy | `anthropic/claude-opus-5-5` (variant/effort: xhigh) | 20x |
412
453
 
413
454
  **fable-effort** — one model, three reasoning depths (see [per-tier `effort`](#per-tier-effort)):
414
455
  | Tier | Model | Effort | Cost ratio |
415
456
  |------|-------|--------|-----------|
416
- | @fast | `anthropic/claude-fable-5` | `low` | 1x |
417
- | @medium | `anthropic/claude-fable-5` | `high` | 3x |
418
- | @heavy | `anthropic/claude-fable-5` | `xhigh` | 6x |
457
+ | @fast | `anthropic/claude-fable-5-1` | `low` | 1x |
458
+ | @medium | `anthropic/claude-fable-5-1` | `high` | 3x |
459
+ | @heavy | `anthropic/claude-fable-5-1` | `xhigh` | 6x |
419
460
 
420
461
  Because the model string is identical across tiers, escalating a task keeps the prompt
421
462
  cache warm. The cost ratios are estimated token-spend multipliers, not price differences.
@@ -441,6 +482,9 @@ highest first:
441
482
 
442
483
  **Unset means unset**: no `effort` (and no `reasoning_effort`) key is registered at all.
443
484
 
485
+ Explicit fields are gated by model family: Claude drops `reasoning.effort`/`reasoning.summary`; adaptive-only Claude also ignores `thinking.budgetTokens`, leaving `effort` applicable.
486
+ Each drop warns once per tier; non-Claude explicit fields are unchanged. See the [provider gate](docs/CONFIG_REFERENCE.md#provider-gate-for-explicit-thinking-and-reasoning-fields).
487
+
444
488
  | Model family | Registered as | Caveats |
445
489
  |---|---|---|
446
490
  | 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. |
@@ -665,9 +709,9 @@ Each tier (`@fast`, `@medium`, `@heavy`) has a system prompt that describes its
665
709
  },
666
710
  "presets": {
667
711
  "anthropic": {
668
- "fast": { "model": "anthropic/claude-sonnet-5", ... },
669
- "medium": { "model": "anthropic/claude-opus-5", ... },
670
- "heavy": { "model": "anthropic/claude-fable-5", ... }
712
+ "fast": { "model": "anthropic/claude-sonnet-5-5", ... },
713
+ "medium": { "model": "anthropic/claude-sonnet-5-5", ... },
714
+ "heavy": { "model": "anthropic/claude-opus-5-5", ... }
671
715
  }
672
716
  }
673
717
  }
@@ -873,7 +917,9 @@ Defines provider fallback order when a delegated task fails:
873
917
 
874
918
  ## Delegation enforcement (advisory by default)
875
919
 
876
- The read-only cap banners described above are advisory: a well-behaved subagent will respect them, but nothing prevents a model from making one more read after the `[⚠ CAP REACHED]` banner. The **enforcement layer** turns delegation into a produce → verify → accept/escalate loop with independent acceptance and quality escalation. As of v1.3.0 it runs in **`advisory` mode by default**: non-trivial delegations are verified and any genuine failure surfaces a forcing-note, except that a DoD with `testsPass` is deferred by default and returns unverified with a `vrf_` handle until you call `router_verify`, use `VERIFY:required` or enable background verification; nothing is ever hard-blocked (the DoD/acceptance section adds 2,200 characters to the orchestrator system prompt, roughly 550–612 tokens at 3.6–4.0 characters per token, and subagents may receive non-blocking guard banners). Unavailable verification is accepted with explicit caveats by default; `enforcement.verify.strictUnverifiable: true` restores rejection without producer escalation. Set `"mode": "off"` — or run `/router enforce off` — to restore byte-for-byte-unchanged routing with zero added prompt tokens and zero new latency. Hard-blocks only activate in `"mode": "enforced"`.
920
+ The read-only cap banners described above are advisory: a well-behaved subagent will respect them, but nothing prevents a model from making one more read after the `[⚠ CAP REACHED]` banner. The **enforcement layer** turns delegation into a produce → verify → accept/escalate loop with independent acceptance and quality escalation. As of v1.3.0 it runs in **`advisory` mode by default**: non-trivial delegations are verified and any genuine failure surfaces a forcing-note, except that a DoD with `testsPass` is deferred by default and returns unverified with a `vrf_` handle until you call `router_verify`, use `VERIFY:required` or enable background verification; nothing is ever hard-blocked (the DoD/acceptance section adds 2,336 characters to the orchestrator system prompt, roughly 584–649 tokens at 3.6–4.0 characters per token, and subagents may receive non-blocking guard banners). Unavailable verification is accepted with explicit caveats by default; `enforcement.verify.strictUnverifiable: true` restores rejection without producer escalation. Set `"mode": "off"` — or run `/router enforce off` — to restore byte-for-byte-unchanged routing with zero added prompt tokens and zero new latency. Hard-blocks only activate in `"mode": "enforced"`.
921
+
922
+ That deferral is the v1.15.0 default (`enforcement.verify.defaultVerify: "deferred"`, `enforcement.verify.background: false`). It applies only to root-orchestrator dispatches whose DoD carries `testsPass`; see [deferred verification](docs/CONFIG_REFERENCE.md#deferred-verification) for the full conditions.
877
923
 
878
924
  ### The three enforcement layers
879
925
 
@@ -883,7 +929,7 @@ The read-only cap banners described above are advisory: a well-behaved subagent
883
929
 
884
930
  ### Two operating modes
885
931
 
886
- - **Mode A — on-the-fly.** The orchestrator delegates through the native `Task()` tool — observed and verified automatically by the enforcement pipeline, and rendered inline in the TUI. (An optional, independently-verified `delegate` tool can be enabled via `experimental.verifiedDelegateTool` in `tiers.json` or `MODEL_ROUTER_VERIFIED_DELEGATE=1`; it is hidden by default so delegation stays visible.)
932
+ - **Mode A — on-the-fly.** The orchestrator delegates through the native `Task()` tool — observed by the enforcement pipeline, verified according to the settings above, and rendered inline in the TUI. (An optional, independently-verified `delegate` tool can be enabled via `experimental.verifiedDelegateTool` in `tiers.json` or `MODEL_ROUTER_VERIFIED_DELEGATE=1`; it is hidden by default so delegation stays visible.)
887
933
  - **Mode B — plan-annotated.** `/annotate-plan` emits `[tier:X]` plus an `[acceptance]` block per task; the enforcement loop is wired up at execution time based on those annotations.
888
934
 
889
935
  ### Tuning enforcement
@@ -894,6 +940,12 @@ Advisory is the default. To change the level:
894
940
  2. Set `MODEL_ROUTER_ENFORCE=1` to force `enforced` for a session, or `MODEL_ROUTER_ENFORCE=0` to force `off`.
895
941
  3. Run `/router enforce <off|advisory|enforced>` from the chat to toggle at runtime.
896
942
 
943
+ `taskPromptRepair` (top-level, default `true`) fills an absent, null or blank `task` prompt from a non-empty trimmed description, or refuses the call readably if none is usable.
944
+ Set `taskPromptRepair: false` to restore the previous behaviour; see [configuration details](docs/CONFIG_REFERENCE.md#taskpromptrepair).
945
+
946
+ For work outside the router directory (e.g. a git worktree), add `cwd: <dir>` inside the task's `[acceptance]` block; a non-empty tool `args.cwd` takes precedence.
947
+ If every changed file is absolute and outside the verification base, deterministic checks return unverifiable instead of running in the wrong directory.
948
+
897
949
  **Modes:** `off` — no-op, byte-for-byte-unchanged routing (must now be set explicitly, since `advisory` is the default); `advisory` (default) — evaluates and surfaces guidance, never blocks; `enforced` — hard-blocks active, full produce → verify → accept/escalate pipeline.
898
950
 
899
951
  > Enforcement applies to subagent/delegate sessions only. The orchestrator session is never hard-blocked.
@@ -995,7 +1047,7 @@ After `/annotate-plan`:
995
1047
 
996
1048
  ## Token overhead
997
1049
 
998
- Measured with the bundled Anthropic preset in normal mode (the shipped `activePreset`/`activeMode` defaults), the routing protocol is 3,238 characters for a non-Claude orchestrator. A Claude orchestrator receives 4,010 characters after its authority prefix, or 6,210 characters when the 2,200-character DoD/enforcement section is enabled. That is roughly 810–1,725 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.
1050
+ Measured with the bundled Anthropic preset in normal mode (the shipped `activePreset`/`activeMode` defaults), the routing protocol is 3,249 characters for a non-Claude orchestrator. A Claude orchestrator receives 4,021 characters after its authority prefix, or 6,357 characters when the 2,336-character DoD/enforcement section is enabled. That is roughly 812–1,766 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.
999
1051
 
1000
1052
  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.
1001
1053
 
@@ -1007,7 +1059,7 @@ These are character counts of the prompts the shipped config actually produces,
1007
1059
 
1008
1060
  ## Requirements
1009
1061
 
1010
- - [OpenCode](https://opencode.ai) v1.0 or later
1062
+ - [OpenCode](https://opencode.ai) v1 (`>=1.0.0 <2.0.0`) or v2 **2.0.20+**
1011
1063
  - Node.js 20+
1012
1064
  - Provider API keys configured in OpenCode
1013
1065
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "1.15.0",
3
+ "version": "2.0.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",
@@ -10,6 +10,8 @@
10
10
  "test:coverage": "vitest run --coverage",
11
11
  "smoke": "cross-env RUN_OC_SMOKE=1 vitest run --config vitest.smoke.config.ts test/smoke",
12
12
  "smoke:keyless": "cross-env RUN_OC_SMOKE_KEYLESS=1 vitest run --config vitest.smoke.config.ts test/smoke/registration.smoke.test.ts test/smoke/subagent-tiers.smoke.test.ts test/smoke/deferred-catalog.smoke.test.ts",
13
+ "smoke:v2": "cross-env RUN_OC_SMOKE_V2=1 vitest run --config vitest.smoke.config.ts test/smoke/v2-registration.smoke.test.ts",
14
+ "smoke:v2:e2e": "cross-env RUN_OC_SMOKE_V2_E2E=1 vitest run --config vitest.smoke.config.ts test/smoke/v2-provider-e2e.smoke.test.ts",
13
15
  "typecheck": "tsc --noEmit"
14
16
  },
15
17
  "license": "GPL-3.0-only",
@@ -39,6 +41,7 @@
39
41
  "orchestration"
40
42
  ],
41
43
  "files": [
44
+ "server.ts",
42
45
  "src/",
43
46
  "tiers.json",
44
47
  "LICENSE",
@@ -49,11 +52,12 @@
49
52
  "@opencode-ai/plugin": ">=1.0.0 <2.0.0"
50
53
  },
51
54
  "devDependencies": {
55
+ "@opencode/plugin": "2.0.22",
52
56
  "@types/node": "^26.2.0",
53
- "@vitest/coverage-v8": "^4.1.8",
57
+ "@vitest/coverage-v8": "^5.0.3",
54
58
  "cross-env": "^10.1.0",
55
59
  "istanbul-lib-coverage": "^3.2.2",
56
60
  "typescript": "^7.0.2",
57
- "vitest": "^4.1.8"
61
+ "vitest": "^5.0.3"
58
62
  }
59
63
  }
package/server.ts ADDED
@@ -0,0 +1,3 @@
1
+ // OpenCode v2 resolves the /server entrypoint before the package main.
2
+ // Keep main callable for v1 loaders that invoke every module export.
3
+ export { default } from "./src/v2";
@@ -0,0 +1,27 @@
1
+ import type { PluginInput } from "@opencode-ai/plugin";
2
+
3
+ /** Marks the legacy tool.execute.before output bag when verification starts for
4
+ * that task call. V1 hosts read only output.args, so this symbol is invisible. */
5
+ export const TASK_VERIFICATION = Symbol.for("opencode-model-router.task-verification");
6
+
7
+ /** A host-owned child lifecycle, so v2 never fabricates REST sessions or IDs. */
8
+ export interface ChildSessionRequest {
9
+ parentSessionID?: string;
10
+ cwd?: string;
11
+ agent?: string;
12
+ model?: { providerID: string; modelID: string; variant?: string };
13
+ system?: string;
14
+ prompt: string;
15
+ signal?: AbortSignal;
16
+ /** Runs before the child can start its first model request. */
17
+ onCreated(sessionID: string): Promise<void>;
18
+ }
19
+
20
+ export interface ChildSessionRunner {
21
+ run(request: ChildSessionRequest): Promise<{ sessionID: string; text: string }>;
22
+ dispose(sessionID: string): Promise<void>;
23
+ }
24
+
25
+ export type RouterPluginInput = PluginInput & {
26
+ routerChildRunner?: ChildSessionRunner;
27
+ };
@@ -0,0 +1,183 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type { Plugin } from "@opencode/plugin";
3
+ import type { ToolContext } from "@opencode/plugin/promise/tool";
4
+ import type { SessionContext } from "@opencode/plugin/promise/session";
5
+ import type { ChildSessionRunner } from "./child-session";
6
+
7
+ export const V2_GRADER_AGENT = "model-router-grader";
8
+ const RETAINED_CONTEXT_LIMIT = 500;
9
+
10
+ /** The small v1 client surface still used by the shared hooks. */
11
+ export function createV2Runtime(ctx: Plugin.Context) {
12
+ type ToolScope = { context: ToolContext; active: boolean };
13
+ const currentTool = new AsyncLocalStorage<ToolScope>();
14
+ const retainedContexts = new Map<string, ToolScope>();
15
+ const lifetime = new AbortController();
16
+ const childSystems = new Map<string, string>();
17
+ const activeChildren = new Map<string, AbortController>();
18
+
19
+ const interrupt = async (sessionID: string, signal?: AbortSignal) => {
20
+ activeChildren.get(sessionID)?.abort();
21
+ return ctx.session.interrupt({ sessionID }, signal ? { signal } : undefined);
22
+ };
23
+
24
+ const client = {
25
+ session: {
26
+ async get(input: { path: { id: string }; signal?: AbortSignal }) {
27
+ return { data: await ctx.session.get({ sessionID: input.path.id }, input.signal ? { signal: input.signal } : undefined) };
28
+ },
29
+ async abort(input: { path: { id: string }; signal?: AbortSignal }) {
30
+ return { data: await interrupt(input.path.id, input.signal) };
31
+ },
32
+ },
33
+ config: {
34
+ async providers() {
35
+ const location = { directory: ctx.location.directory };
36
+ const [providers, models, defaultModel] = await Promise.all([
37
+ ctx.provider.list({ location }),
38
+ ctx.model.list({ location }),
39
+ ctx.model.default({ location }),
40
+ ]);
41
+ return {
42
+ data: {
43
+ providers: providers.data.map(provider => ({
44
+ id: provider.id,
45
+ name: provider.name,
46
+ models: Object.fromEntries(models.data
47
+ .filter(model => model.providerID === provider.id && model.enabled)
48
+ .map(model => [model.id, { id: model.id, status: model.status }])),
49
+ })),
50
+ default: defaultModel.data
51
+ ? { [defaultModel.data.providerID]: defaultModel.data.id }
52
+ : {},
53
+ },
54
+ };
55
+ },
56
+ },
57
+ // v2 has no app.log endpoint. createPluginLogger uses its console fallback.
58
+ };
59
+
60
+ const childRunner: ChildSessionRunner = {
61
+ async run(request) {
62
+ lifetime.signal.throwIfAborted();
63
+ const current = currentTool.getStore();
64
+ // A shared background worker can run in a different caller's async
65
+ // scope. Only a real context previously observed for the requested
66
+ // parent may authorize that dispatch; never manufacture call/message IDs.
67
+ const scope = request.parentSessionID && request.parentSessionID !== current?.context.sessionID
68
+ ? retainedContexts.get(request.parentSessionID)
69
+ : current;
70
+ if (!scope) throw new Error("[model-router] v2 child dispatch requires an active tool context or a retained context matching its parent");
71
+ const toolContext = scope.context;
72
+ // Retained-scope permission prompts remain attributed to the originating
73
+ // real call IDs, never fabricated replacements.
74
+ const native = (await ctx.tool.list()).find(tool => tool.id === "subagent");
75
+ if (!native) throw new Error("[model-router] OpenCode v2's native subagent tool is unavailable");
76
+ const controller = new AbortController();
77
+ // Deferred verification outlives its originating tool call. Its own
78
+ // deadline and plugin lifetime govern cancellation once that call ends.
79
+ const signal = AbortSignal.any([
80
+ lifetime.signal, controller.signal,
81
+ ...(scope.active ? [toolContext.signal] : []),
82
+ ...(request.signal ? [request.signal] : []),
83
+ ]);
84
+ signal.throwIfAborted();
85
+ let childID: string | undefined;
86
+ const model = request.model;
87
+ try {
88
+ const result = await native.execute({
89
+ agent: request.agent ?? V2_GRADER_AGENT,
90
+ description: request.agent ? `Router ${request.agent} delegation` : "Router result verification",
91
+ prompt: request.prompt,
92
+ ...(model ? { model: `${model.providerID}/${model.modelID}${model.variant ? `#${model.variant}` : ""}` } : {}),
93
+ background: false,
94
+ }, {
95
+ ...toolContext,
96
+ signal,
97
+ async progress(metadata) {
98
+ const sessionID = metadata.sessionID;
99
+ if (typeof sessionID === "string" && sessionID !== childID) {
100
+ if (childID) throw new Error("[model-router] native subagent changed its child session ID");
101
+ childID = sessionID;
102
+ activeChildren.set(sessionID, controller);
103
+ if (request.system) childSystems.set(sessionID, request.system);
104
+ // The native subagent awaits progress after creating its child and
105
+ // before prompting it. Register guards and scope graders here.
106
+ await request.onCreated(sessionID);
107
+ if (request.cwd) await ctx.session.move({ sessionID, directory: request.cwd }, { signal });
108
+ signal.throwIfAborted();
109
+ }
110
+ // V2 rejects progress outside a running call. Deferred/queued graders
111
+ // retain settled parent contexts; also tolerate settlement during progress.
112
+ if (scope.active) {
113
+ try { await toolContext.progress(metadata); }
114
+ catch (error) { if (scope.active) throw error; }
115
+ }
116
+ },
117
+ });
118
+ signal.throwIfAborted();
119
+ const output = result.output as { sessionID?: unknown; status?: unknown; output?: unknown } | undefined;
120
+ if (!childID || output?.sessionID !== childID || output.status !== "completed" || typeof output.output !== "string") {
121
+ throw new Error("[model-router] native subagent did not return a completed child result; verification cannot use a pending result");
122
+ }
123
+ return { sessionID: childID, text: output.output };
124
+ } catch (error) {
125
+ controller.abort();
126
+ if (childID) {
127
+ try { await ctx.session.interrupt({ sessionID: childID }); } catch { /* keep the original dispatch failure */ }
128
+ }
129
+ throw error;
130
+ } finally {
131
+ if (childID) {
132
+ childSystems.delete(childID);
133
+ activeChildren.delete(childID);
134
+ }
135
+ }
136
+ },
137
+ async dispose(sessionID) {
138
+ childSystems.delete(sessionID);
139
+ await interrupt(sessionID);
140
+ // Removal was added in 2.0.21; older hosts retain child history.
141
+ // disposeChildSession catches cleanup failures without masking the result.
142
+ if (typeof ctx.session.remove === "function") await ctx.session.remove({ sessionID });
143
+ },
144
+ };
145
+
146
+ return {
147
+ client,
148
+ childRunner,
149
+ async withToolContext<T>(context: ToolContext, operation: () => Promise<T>): Promise<T> {
150
+ lifetime.signal.throwIfAborted();
151
+ const scope = { context, active: true };
152
+ retainedContexts.delete(context.sessionID);
153
+ retainedContexts.set(context.sessionID, scope);
154
+ while (retainedContexts.size > RETAINED_CONTEXT_LIMIT) {
155
+ retainedContexts.delete(retainedContexts.keys().next().value!);
156
+ }
157
+ try {
158
+ return await currentTool.run(scope, operation);
159
+ } finally {
160
+ scope.active = false;
161
+ }
162
+ },
163
+ applyChildSystem(sessionID: string, system: SessionContext["system"]): void {
164
+ const text = childSystems.get(sessionID);
165
+ if (text && !system.some(part => part.text === text)) system.push({ type: "text", text });
166
+ },
167
+ forgetSession(sessionID: string): void {
168
+ retainedContexts.delete(sessionID);
169
+ childSystems.delete(sessionID);
170
+ activeChildren.get(sessionID)?.abort();
171
+ },
172
+ async dispose(): Promise<void> {
173
+ lifetime.abort();
174
+ const sessions = [...activeChildren.keys()];
175
+ retainedContexts.clear();
176
+ childSystems.clear();
177
+ await Promise.allSettled(sessions.map(sessionID => interrupt(sessionID)));
178
+ activeChildren.clear();
179
+ },
180
+ };
181
+ }
182
+
183
+ export type V2Runtime = ReturnType<typeof createV2Runtime>;