opencode-model-router 1.15.0 → 2.1.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,132 @@ 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.1.0] - 2026-10-05
11
+
12
+ Observations by @MetalbolicX in opencode-smart-router (#17); implementation written from scratch.
13
+
14
+ ### Added
15
+
16
+ - Delegation depth guard (#66), configured by `enforcement.maxDelegationDepth`
17
+ (default `1`; `null` disables it).
18
+ - Effort bump before escalation (#67), configured by
19
+ `enforcement.escalate.effortBump` (default `true`) and
20
+ `enforcement.escalate.effortBumpMax` (default `"xhigh"`, further capped per model).
21
+
22
+ ### Changed
23
+
24
+ - The automatic ladder's existing same-tier retry now runs one effort level higher
25
+ by default on eligible tiers: explicit valid `effort`, no `variant`, a recognised
26
+ Claude or OpenAI model family, no winning explicit provider setting, and room
27
+ below the effective ceiling. This adds no attempt and
28
+ still respects attempt and cost ceilings. It applies only to the optional
29
+ `delegate` tool's automatic ladder, not native `task`/`subagent` or manual retries.
30
+ Only `fable-effort` fast/medium are eligible among bundled presets; at the default
31
+ cost ceiling, a run starting at fast stops before medium's bump. Set
32
+ `enforcement.escalate.effortBump: false` to restore the previous retry behaviour.
33
+ - Dispatches past `enforcement.maxDelegationDepth` (default `1`) are warned in
34
+ `advisory` mode (the bundled default) with `[⚠ GUARD:delegation_depth]` and refused
35
+ in `enforced` mode. Set `enforcement.mode: "enforced"` to enforce it unless the
36
+ caller tier's `enforcement.perTier` entry overrides `mode`; `MODEL_ROUTER_ENFORCE=1`
37
+ overrides both and forces enforcement. Set `enforcement.maxDelegationDepth: null`
38
+ to opt out of the guard. Enforcement mode `off`, a caller-tier `perTier: "off"`
39
+ (unless the environment gate forces enforcement), and `/bypass on` also disable
40
+ the check. OpenCode 2's own
41
+ `experimental.subagent_depth` cap remains independent.
42
+ - On OpenCode 2, router-modified `subagent` results now keep the host's
43
+ `<subagent sessionID=…>` envelope part and append the router's text as a separate
44
+ part, preserving the resume handle instead of replacing the envelope with plain
45
+ text. This applies when host text exists and the router output starts with the
46
+ child's text after trimming trailing whitespace. Missing host text or a
47
+ non-suffix rewrite uses the full router output as one text part instead, retaining
48
+ non-text attachments without losing or duplicating the child's text. Structured
49
+ output and metadata handling are unchanged.
50
+
51
+ ### Fixed
52
+
53
+ - **OpenCode v1 behaviour change:** tier `effort` (for OpenAI-family models),
54
+ `reasoning.*` and `thinking.budgetTokens` settings that v1 silently dropped now
55
+ reach requests through provider-native registered keys: `reasoningEffort`,
56
+ `reasoningSummary` and `thinking: { type: "enabled", budgetTokens }`. User config
57
+ keys and provider-specific precedence/gates are unchanged; Claude `effort` was
58
+ already registered with its native key.
59
+ - OpenAI-family detection is regex-based: Copilot/OpenRouter/Azure `gpt-*`,
60
+ `gpt-oss` through Ollama/Groq, and non-reasoning GPT models with configured
61
+ `effort` or explicit `reasoning.effort` now receive `reasoningEffort` (and
62
+ configured summaries use `reasoningSummary`). IDs containing `o1`/`o3`/`o4`
63
+ delimited by `/`, `-` or `_` (or the start/end of the ID), including bare IDs
64
+ and false positives such as `mistral/magistral-o1`, are also treated as OpenAI.
65
+ OpenAI-family tiers with a truthy `thinking.budgetTokens` now also send
66
+ `thinking: { type: "enabled", budgetTokens }`; non-Claude budgets are not gated.
67
+ Whether the SDK strips unsupported options for non-reasoning models is unverified.
68
+ - Claude tiers with an applicable `thinking.budgetTokens` now send `thinking`;
69
+ adaptive-only Claude still drops manual budgets. Unknown-family tiers (such
70
+ as Bedrock Claude or Gemini) with explicit `thinking.budgetTokens` or
71
+ `reasoning.*` also receive the native keys; their provider effect is unverified.
72
+ - Latency/cost may rise, or a provider may reject newly delivered settings.
73
+ To restore the previous behaviour, remove `effort`, `reasoning.*` or `thinking`
74
+ from the affected tier. **Bundled presets are unaffected by this registration
75
+ fix:** none sets `reasoning` or `thinking`, and their explicit `effort` settings
76
+ are Claude's already-native key.
77
+
78
+ ## [2.0.0] - 2026-10-04
79
+
80
+ The router now runs on OpenCode v2 through a separate server entrypoint. **OpenCode v1
81
+ remains supported**: the callable v1 entrypoint and every config key are unchanged. The
82
+ major version marks the new host support and the updated bundled preset defaults. See
83
+ [the compatibility notes](docs/OPENCODE_V2.md).
84
+
85
+ ### Added
86
+
87
+ - OpenCode v2 compatibility through a separate server entrypoint, fixing the
88
+ `Expected object at ["default"]` plugin validation error while preserving the
89
+ callable v1 entrypoint. The adapter translates agent registration, commands,
90
+ prompts, tool guards and verification to v2's domain APIs, and uses native
91
+ subagents for producer/grader sessions. A subagent's `background` request is
92
+ kept unless the router verifies that dispatch. Only router-added instructions
93
+ are translated to v2 tool names. V2 tier options reach requests through the
94
+ context hook, not unused agent settings. V2 ≥2.0.21 removes temporary children
95
+ after use; 2.0.20 retains their history. Anti-narration warnings appear as
96
+ synthetic transcript entries. Includes an opt-in provider-backed v2 e2e smoke
97
+ adapted from @ChronosWS (Cliff Hudson). See
98
+ [the compatibility notes](docs/OPENCODE_V2.md).
99
+ - **Behavior note:** on v2, graders send no temperature (the provider default
100
+ applies, not `graderTemperature`) unless the exact `provider/model` is listed in
101
+ `enforcement.verify.graderTemperatureModels` (reported by @ChronosWS).
102
+
103
+ ### Changed
104
+
105
+ - Bundled presets updated: `anthropic` fast → Sonnet 5.5 low, medium → Sonnet
106
+ 5.5 medium (was Opus 5.5 low); `openai` medium → `gpt-6.1-sol-fast` xhigh;
107
+ `hybrid` fast → Luna medium, medium → Astra high, heavy → Opus 5.5 xhigh
108
+ (was Fable 5.1 max). The orchestrator prompt grows by 11 characters:
109
+ 3,249 / 4,021 / 6,221 for base / Claude / Claude with enforcement.
110
+ - `hybrid` heavy now also sets `effort: "xhigh"`, like the `anthropic` preset's
111
+ heavy tier, so Opus 5.5 receives the effort and not only the variant. The
112
+ `github-copilot` heavy description names Fable 5.1, the model it runs.
113
+ - V1 graders no longer send `graderTemperature` to models whose capabilities
114
+ report `temperature: false`.
115
+
116
+ ### Fixed
117
+
118
+ - Setting `enforcement.verify.graderTemperature` to `null` removes any grader temperature,
119
+ including pre-existing values and v2 allowlisted models. Numeric values still respect
120
+ v1 model capabilities and the v2 allowlist. Grader response/API failures are reported as
121
+ SDK errors with metadata-only details before verdict parsing, rather than as parse failures.
122
+ - 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.
123
+ - Windows e2e self-check waits for sampler snapshots instead of a fixed 2.5 s window (#61).
124
+ - Parallel deferred finishes now share their gate-time tree snapshot, as dispatch
125
+ starts already did. A run only serves finishes that asked before it started.
126
+ Unshared, 20 parallel deferred delegations on a 4-core Windows host ran 20
127
+ snapshots and 19 hit the 2 s finish bound, leaving their changes unattributed
128
+ (risk high). Measured with that affinity: finish p50 2.11 s → 0.96 s, 19 → 0 capped.
129
+
130
+ ### Documentation
131
+
132
+ - README updated for OpenCode v2 support, presets and requirements.
133
+
8
134
  ## [1.15.0] - 2026-09-28
9
135
 
10
136
  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,48 @@ 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`/`reasoningEffort`/`reasoningSummary`/`thinking`) 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
+ A tier's `variant` is applied through its agent model reference at registration.
286
+
287
+ **Smoke tests:** Set `OPENCODE_V2_BIN` to the absolute path of an OpenCode v2
288
+ executable. `npm run smoke:v2` checks loading and registration without provider
289
+ credentials. `npm run smoke:v2:e2e` opts in to the end-to-end smoke (the script sets
290
+ `RUN_OC_SMOKE_V2_E2E=1`), driving `opencode run --standalone` against a local
291
+ deterministic OpenAI-compatible provider, also without provider credentials.
292
+
293
+ See [the v2 compatibility notes](docs/OPENCODE_V2.md) for the API mapping and validation.
294
+
253
295
  ### From npm (recommended)
254
296
  ```bash
255
297
  # In your opencode project or globally
@@ -378,23 +420,23 @@ The plugin ships with seven presets (switch with `/preset <name>`):
378
420
  **anthropic** (default):
379
421
  | Tier | Model | Cost ratio |
380
422
  |------|-------|-----------|
381
- | @fast | `anthropic/claude-sonnet-5` | 1x |
382
- | @medium | `anthropic/claude-opus-5` (high) | 5x |
383
- | @heavy | `anthropic/claude-fable-5` (max) | 20x |
423
+ | @fast | `anthropic/claude-sonnet-5-5` (variant/effort: low) | 1x |
424
+ | @medium | `anthropic/claude-sonnet-5-5` (variant/effort: medium) | 5x |
425
+ | @heavy | `anthropic/claude-opus-5-5` (variant/effort: xhigh) | 20x |
384
426
 
385
427
  **openai**:
386
428
  | Tier | Model | Cost ratio |
387
429
  |------|-------|-----------|
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 |
430
+ | @fast | `openai/gpt-6-luna-fast` | 1x |
431
+ | @medium | `openai/gpt-6.1-sol-fast` (xhigh) | 5x |
432
+ | @heavy | `openai/gpt-6-astra-fast` (max) | 20x |
391
433
 
392
434
  **github-copilot**:
393
435
  | Tier | Model | Cost ratio |
394
436
  |------|-------|-----------|
395
437
  | @fast | `github-copilot/claude-haiku-4.5` | 1x |
396
438
  | @medium | `github-copilot/claude-sonnet-5` | 5x |
397
- | @heavy | `github-copilot/claude-fable-5` | 20x |
439
+ | @heavy | `github-copilot/claude-fable-5-1` | 20x |
398
440
 
399
441
  **google**:
400
442
  | Tier | Model | Cost ratio |
@@ -403,19 +445,19 @@ The plugin ships with seven presets (switch with `/preset <name>`):
403
445
  | @medium | `google/gemini-3.7-flash` | 5x |
404
446
  | @heavy | `google/gemini-3.1-pro-preview` | 20x |
405
447
 
406
- **hybrid** — Anthropic for exploration and heavy analysis, OpenAI for implementation:
448
+ **hybrid** — OpenAI for exploration and implementation, Anthropic for heavy analysis:
407
449
  | Tier | Model | Cost ratio |
408
450
  |------|-------|-----------|
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 |
451
+ | @fast | `openai/gpt-6-luna-fast` (medium) | 1x |
452
+ | @medium | `openai/gpt-6-astra-fast` (high) | 5x |
453
+ | @heavy | `anthropic/claude-opus-5-5` (variant/effort: xhigh) | 20x |
412
454
 
413
455
  **fable-effort** — one model, three reasoning depths (see [per-tier `effort`](#per-tier-effort)):
414
456
  | Tier | Model | Effort | Cost ratio |
415
457
  |------|-------|--------|-----------|
416
- | @fast | `anthropic/claude-fable-5` | `low` | 1x |
417
- | @medium | `anthropic/claude-fable-5` | `high` | 3x |
418
- | @heavy | `anthropic/claude-fable-5` | `xhigh` | 6x |
458
+ | @fast | `anthropic/claude-fable-5-1` | `low` | 1x |
459
+ | @medium | `anthropic/claude-fable-5-1` | `high` | 3x |
460
+ | @heavy | `anthropic/claude-fable-5-1` | `xhigh` | 6x |
419
461
 
420
462
  Because the model string is identical across tiers, escalating a task keeps the prompt
421
463
  cache warm. The cost ratios are estimated token-spend multipliers, not price differences.
@@ -439,12 +481,19 @@ highest first:
439
481
  provider-specific setting always wins, and a one-time warning names the tier.
440
482
  2. `effort`.
441
483
 
442
- **Unset means unset**: no `effort` (and no `reasoning_effort`) key is registered at all.
484
+ **Unset means unset**: without `effort` or an explicit `reasoning.effort`, neither
485
+ `effort` nor `reasoningEffort` is registered. User config keys remain
486
+ `reasoning.effort`, `reasoning.summary` and `thinking.budgetTokens`; registered
487
+ provider options use `reasoningEffort`, `reasoningSummary` and
488
+ `thinking: { type: "enabled", budgetTokens }` respectively.
489
+
490
+ Explicit fields are gated by model family: Claude drops `reasoning.effort`/`reasoning.summary`; adaptive-only Claude also ignores `thinking.budgetTokens`, leaving `effort` applicable.
491
+ 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).
443
492
 
444
493
  | Model family | Registered as | Caveats |
445
494
  |---|---|---|
446
495
  | 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. |
447
- | OpenAI | `options.reasoning_effort` | Supports only `low`/`medium`/`high`; `xhigh` and `max` are downgraded to `high` with a warning. |
496
+ | OpenAI | `options.reasoningEffort` | Supports only `low`/`medium`/`high`; `xhigh` and `max` are downgraded to `high` with a warning. |
448
497
  | 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. |
449
498
 
450
499
  An out-of-set value in `tiers.json` fails validation at load; one that arrives any other
@@ -665,9 +714,9 @@ Each tier (`@fast`, `@medium`, `@heavy`) has a system prompt that describes its
665
714
  },
666
715
  "presets": {
667
716
  "anthropic": {
668
- "fast": { "model": "anthropic/claude-sonnet-5", ... },
669
- "medium": { "model": "anthropic/claude-opus-5", ... },
670
- "heavy": { "model": "anthropic/claude-fable-5", ... }
717
+ "fast": { "model": "anthropic/claude-sonnet-5-5", ... },
718
+ "medium": { "model": "anthropic/claude-sonnet-5-5", ... },
719
+ "heavy": { "model": "anthropic/claude-opus-5-5", ... }
671
720
  }
672
721
  }
673
722
  }
@@ -873,7 +922,9 @@ Defines provider fallback order when a delegated task fails:
873
922
 
874
923
  ## Delegation enforcement (advisory by default)
875
924
 
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"`.
925
+ 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"`.
926
+
927
+ 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
928
 
878
929
  ### The three enforcement layers
879
930
 
@@ -883,9 +934,70 @@ The read-only cap banners described above are advisory: a well-behaved subagent
883
934
 
884
935
  ### Two operating modes
885
936
 
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.)
937
+ - **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
938
  - **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
939
 
940
+ ### Delegation depth guard
941
+
942
+ The guard checks model-initiated dispatches through native `task` (OpenCode v1),
943
+ `subagent` (OpenCode 2), and the router's optional `delegate` tool, including resumes.
944
+ `enforcement.maxDelegationDepth` defaults to `1`: the root orchestrator is depth 0,
945
+ so it may delegate, but its depth-1 children would exceed the limit by delegating again.
946
+
947
+ - **`advisory` (bundled default):** allows the dispatch and warns with
948
+ `[⚠ GUARD:delegation_depth]` in its result; it does not refuse it.
949
+ - **`enforced`:** refuses a dispatch past the limit before another subagent runs.
950
+ Set `enforcement.mode: "enforced"` or `MODEL_ROUTER_ENFORCE=1` to enforce it.
951
+ The caller tier's `enforcement.perTier` override applies unless the environment
952
+ gate overrides it.
953
+ - **`off`:** skips the check. Set `enforcement.maxDelegationDepth: null` to disable
954
+ just this guard, or use an integer from 1 to 32 to change the depth limit.
955
+
956
+ This is not a sandbox: shell-launched `opencode run` and other plugins' session
957
+ tools are outside its scope. `/bypass on` also disables the depth guard. If the
958
+ caller depth cannot be resolved, the guard fails open with a logged warning.
959
+ OpenCode 2 has its own independent `experimental.subagent_depth` cap (default 1):
960
+ raising or disabling the router limit does not lift that host cap. With both caps
961
+ enforced, the lower one wins. V2's `general` agent also needs explicit `subagent`
962
+ permission to dispatch. The Phase 2.3 host proof on OpenCode v1 1.18.19 likewise encountered
963
+ a host cap and used top-level `subagent_depth: 4` to lift it; its default and upstream
964
+ documentation are unverified. Raising only the router limit does not lift a host cap.
965
+ These are observations from the [host-proof fixtures](docs/qa/depth-and-effort/phase-2.3.md#handoffs),
966
+ not a documented cross-version default for v1.
967
+
968
+ See the [configuration reference](docs/CONFIG_REFERENCE.md) and
969
+ [design decisions and scope limits](docs/adr/0004-delegation-depth-and-effort-bump.md).
970
+
971
+ ### Effort bump before escalation
972
+
973
+ The automatic escalation ladder uses its existing same-tier retry to try **one
974
+ effort level higher** before moving to a more expensive tier. It adds no attempt.
975
+ `enforcement.escalate.effortBump` defaults to `true`, and `effortBumpMax` defaults
976
+ to `"xhigh"`, further capped by model family (OpenAI: `high`; Claude: `max`). Set
977
+ `enforcement.escalate.effortBump: false` to restore the previous ladder behaviour.
978
+
979
+ An eligible tier must set an explicit valid `effort`, have no `variant`, belong to
980
+ a recognised Claude or OpenAI model family, and have room below the effective ceiling.
981
+ A winning explicit provider setting
982
+ (`reasoning.effort` or an applicable `thinking.budgetTokens`) prevents the bump.
983
+ It changes only that retry producer's options, not the preset, titles or graders.
984
+ The bump applies to the optional `delegate` tool's automatic ladder, not native
985
+ `task`/`subagent` calls or manual retries; deferred verification does not retry.
986
+ `/bypass` leaves the ladder and effort bump active; use `effortBump: false` to disable
987
+ the bump.
988
+
989
+ Among bundled presets, **only `fable-effort` fast and medium are eligible**
990
+ (`low → medium` and `high → xhigh`). Its heavy tier is already at the default
991
+ ceiling; all other presets either set a variant or omit `effort`. In particular,
992
+ the default `anthropic` preset has no bumpable tier. Attempt and cost ceilings
993
+ still apply: starting at fast with the default cost multiple of 4, `fable-effort`
994
+ runs `fast@low → fast@medium → medium@high`, then stops on cost; medium's bump
995
+ is not reached. Raise `enforcement.escalate.costCeiling.multiple` to allow it.
996
+
997
+ See the [configuration reference](docs/CONFIG_REFERENCE.md) for eligibility and
998
+ cost settings, and the [ADR](docs/adr/0004-delegation-depth-and-effort-bump.md) for
999
+ trade-offs and host evidence (real-provider acceptance of bumped values is unverified).
1000
+
889
1001
  ### Tuning enforcement
890
1002
 
891
1003
  Advisory is the default. To change the level:
@@ -894,7 +1006,13 @@ Advisory is the default. To change the level:
894
1006
  2. Set `MODEL_ROUTER_ENFORCE=1` to force `enforced` for a session, or `MODEL_ROUTER_ENFORCE=0` to force `off`.
895
1007
  3. Run `/router enforce <off|advisory|enforced>` from the chat to toggle at runtime.
896
1008
 
897
- **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.
1009
+ `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.
1010
+ Set `taskPromptRepair: false` to restore the previous behaviour; see [configuration details](docs/CONFIG_REFERENCE.md#taskpromptrepair).
1011
+
1012
+ 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.
1013
+ If every changed file is absolute and outside the verification base, deterministic checks return unverifiable instead of running in the wrong directory.
1014
+
1015
+ **Modes:** `off` — disables enforcement guards and skips native `task`/`subagent` verification (must be set explicitly, since `advisory` is the default); `advisory` (default) — warns on guard violations without blocking; `enforced` — blocks guard violations. Native-task verification annotates completed results in both advisory and enforced modes, subject to verification policy. Whenever the opt-in `delegate` tool is enabled, its produce → verify → accept/escalate pipeline runs in **every mode**, including retries and eligible effort bumps, subject to its verification policy and attempt/cost limits.
898
1016
 
899
1017
  > Enforcement applies to subagent/delegate sessions only. The orchestrator session is never hard-blocked.
900
1018
 
@@ -995,7 +1113,7 @@ After `/annotate-plan`:
995
1113
 
996
1114
  ## Token overhead
997
1115
 
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.
1116
+ 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
1117
 
1000
1118
  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
1119
 
@@ -1007,7 +1125,7 @@ These are character counts of the prompts the shipped config actually produces,
1007
1125
 
1008
1126
  ## Requirements
1009
1127
 
1010
- - [OpenCode](https://opencode.ai) v1.0 or later
1128
+ - [OpenCode](https://opencode.ai) v1 (`>=1.0.0 <2.0.0`) or v2 **2.0.20+**
1011
1129
  - Node.js 20+
1012
1130
  - Provider API keys configured in OpenCode
1013
1131
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "1.15.0",
3
+ "version": "2.1.0",
4
4
  "description": "OpenCode plugin that routes tasks to tiered subagents (fast/medium/heavy) based on complexity",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -9,7 +9,9 @@
9
9
  "test:watch": "vitest",
10
10
  "test:coverage": "vitest run --coverage",
11
11
  "smoke": "cross-env RUN_OC_SMOKE=1 vitest run --config vitest.smoke.config.ts test/smoke",
12
- "smoke:keyless": "cross-env RUN_OC_SMOKE_KEYLESS=1 vitest run --config vitest.smoke.config.ts test/smoke/registration.smoke.test.ts test/smoke/subagent-tiers.smoke.test.ts test/smoke/deferred-catalog.smoke.test.ts",
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 test/smoke/depth-effort.smoke.test.ts test/smoke/helpers/scripted-provider.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,32 @@
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
+ /** An advisory depth banner for this call; the v2 bridge delivers it. */
8
+ export const DEPTH_BANNER = Symbol.for("opencode-model-router.depth-banner");
9
+
10
+ /** A host-owned child lifecycle, so v2 never fabricates REST sessions or IDs. */
11
+ export interface ChildSessionRequest {
12
+ parentSessionID?: string;
13
+ cwd?: string;
14
+ agent?: string;
15
+ model?: { providerID: string; modelID: string; variant?: string };
16
+ system?: string;
17
+ prompt: string;
18
+ signal?: AbortSignal;
19
+ /** Runs before the child can start its first model request. */
20
+ onCreated(sessionID: string): Promise<void>;
21
+ }
22
+
23
+ export interface ChildSessionRunner {
24
+ run(request: ChildSessionRequest): Promise<{ sessionID: string; text: string }>;
25
+ dispose(sessionID: string): Promise<void>;
26
+ }
27
+
28
+ export type RouterPluginInput = PluginInput & {
29
+ routerChildRunner?: ChildSessionRunner;
30
+ /** Set only by src/v2.ts; absent = v1 host (A3). */
31
+ routerHost?: "v2";
32
+ };