opencode-model-router 2.3.0 → 2.4.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.
Files changed (61) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/README.md +56 -10
  3. package/package.json +1 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1322 -18
  6. package/src/escalate/ladder.ts +12 -0
  7. package/src/guard/enforce.ts +186 -22
  8. package/src/guard/guards.ts +132 -6
  9. package/src/guard/store.ts +5 -0
  10. package/src/index.ts +718 -29
  11. package/src/router/config.ts +247 -1
  12. package/src/router/dispatch-header.ts +46 -4
  13. package/src/router/git-tools.ts +1152 -0
  14. package/src/router/guard-profile.ts +100 -0
  15. package/src/router/plugin-agents.ts +433 -0
  16. package/src/router/prompts.ts +26 -1
  17. package/src/router/protocol.ts +133 -0
  18. package/src/router/read-only.ts +149 -0
  19. package/src/router/role-agents.ts +409 -0
  20. package/src/router/roles-config.ts +429 -0
  21. package/src/router/roles.ts +600 -0
  22. package/src/router/run-tools.ts +913 -0
  23. package/src/router/sensitive-paths.ts +101 -0
  24. package/src/router/sessions.ts +92 -0
  25. package/src/router/subagents.ts +28 -1
  26. package/src/routing/advisor/findings.ts +193 -1
  27. package/src/routing/advisor/index.ts +13 -5
  28. package/src/routing/classify/index.ts +23 -5
  29. package/src/routing/classify/route-line.ts +67 -3
  30. package/src/routing/classify/rules.ts +80 -20
  31. package/src/routing/classify/types.ts +34 -4
  32. package/src/routing/commands/stats.ts +3 -0
  33. package/src/routing/engine/kernel.ts +163 -0
  34. package/src/routing/engine/ladders.ts +242 -1
  35. package/src/routing/engine/protocol-line.ts +17 -0
  36. package/src/routing/engine/roles-taxonomy.ts +52 -0
  37. package/src/routing/engine/types.ts +99 -1
  38. package/src/routing/outcomes/beta.ts +10 -4
  39. package/src/routing/outcomes/index.ts +44 -1
  40. package/src/routing/outcomes/ingest.ts +163 -15
  41. package/src/routing/outcomes/persist.ts +23 -1
  42. package/src/routing/outcomes/signals.ts +650 -0
  43. package/src/routing/outcomes/stats.ts +273 -2
  44. package/src/routing/outcomes/store.ts +25 -5
  45. package/src/routing/outcomes/types.ts +145 -6
  46. package/src/routing/roles/authority.ts +495 -0
  47. package/src/routing/roles/binding.ts +543 -0
  48. package/src/routing/roles/policy.ts +416 -0
  49. package/src/routing/roles/work-root.ts +132 -0
  50. package/src/routing/wire/dispatch.ts +1306 -17
  51. package/src/routing/wire/hint.ts +14 -0
  52. package/src/routing/wire/runtime.ts +117 -28
  53. package/src/v2.ts +26 -1
  54. package/src/verify/checker.ts +249 -7
  55. package/src/verify/deterministic.ts +10 -1
  56. package/src/verify/dispatch.ts +63 -6
  57. package/src/verify/dod.ts +127 -10
  58. package/src/verify/gate.ts +75 -7
  59. package/src/verify/types.ts +12 -0
  60. package/src/verify/wiring.ts +55 -10
  61. package/tiers.json +13 -5
package/CHANGELOG.md CHANGED
@@ -7,6 +7,155 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.4.0] - 2026-10-09
11
+
12
+ Role × tier × assurance delegation (#84), opt-in on OpenCode v2: role agents, tier floors from authority × detection,
13
+ validated work roots, `router_run` and work-root-scoped `router_git_*`, and outcome signals from external verification
14
+ only. OpenCode v1 is unchanged apart from the changes listed below; the roles keys are validated and inert there. See
15
+ [Roles mode](docs/ROLES.md) and [ADR 0006](docs/adr/0006-role-tier-assurance-delegation.md).
16
+
17
+ **Upgrade notes.** Read these entries under [Changed](#changed) before upgrading:
18
+
19
+ - **Breaking (behaviour): `fast` is now host-enforced read-only on v1 and v2 (#77).**
20
+ - The #84 behaviour change: guard and verification fixes for every host and mode, OpenCode v1 included.
21
+ - Its **Downgrades** item: downgrading past this version is unsupported.
22
+
23
+ ### Added
24
+
25
+ - **Roles mode: role × tier × assurance delegation (#84), OpenCode v2, opt-in.** With `routing.delegation: "roles"`
26
+ the orchestrator dispatches seven role agents — `explorer`, `researcher`, `runner`, `implementer`, `reviewer`,
27
+ `architect`, `general` — and the router picks the tier and the per-call model of every dispatch. Decided at plugin
28
+ start: restart OpenCode after switching. See [Roles mode](docs/ROLES.md) and
29
+ [ADR 0006](docs/adr/0006-role-tier-assurance-delegation.md).
30
+ - Role contracts in code (`SHIPPED_ROLE_SPECS`): maximum authority, tier range, a descriptive default assurance,
31
+ guard profile, call budget per tier; `roleAgents.<name>` (global only) can only narrow them. A role whose tier
32
+ range the active preset's `costRatio` orders against the tier names is disabled with a notice.
33
+ - Least privilege with capability separation: no grant mixes local, exec or write actions with egress; Code Mode
34
+ `execute`, shell and delegation are denied to every role; `researcher` is web and docs only.
35
+ - Tier floor from authority × effective detection (`authorityFloor`): edits reach `fast` only behind the router's
36
+ own deterministic checks on a low-risk single-file change; edit + run never below `medium`. After a verification
37
+ FAIL of a role child the router raises its tier on the next resume itself; the orchestrator never sets `tier=`
38
+ or `model`.
39
+ - Dynamic authority for `implementer` and `general`, with nonce-exact binding and a resume-based ladder
40
+ (`router_request_authority` → `ESCALATE: authority` → resume the same session; widening only for exact bindings).
41
+ - Work roots: `root=` on the route line (a git worktree of the repository) and `routing.workRoots` globs; the router
42
+ narrows each session to its own root. A role dispatch's acceptance checks run in its work root; a `cwd:` outside
43
+ it is refused. Role `edit` needs a validated work root (on the authority ladder too) and never falls back to the
44
+ session or plugin directory; it never writes `.git` or anything below it, through any host edit tool.
45
+ `router_git_*` are limited to the work root (a pathspec for a work root below the repository's top level) and are
46
+ refused for a repository other than the dispatch's or a `.git` pointer to a network or device path. The
47
+ `git worktree list` runs that validate work roots inherit the user's `safe.directory` values.
48
+ - `router_run`: `package.json` scripts listed by exact name and `routing.run.commands` with fixed argv, argument
49
+ patterns, pinned npm script shell and config files, refused `.npmrc` keys and a credential-stripped environment;
50
+ single-dash arguments carrying `/`, `\` or `..` are refused. A network or device `cwd` is refused before any
51
+ filesystem call. Credential-like variables (`PGPASSWORD`, `MYSQL_PWD` included; `PWD` and `OLDPWD` kept) are
52
+ always stripped: `routing.run` has no passthrough option.
53
+ - Role budgets (`budget=` up to 2×; a resume without `budget=` keeps the previous one), `NEED MORE: budget` with a
54
+ `[router budget]` resume note, never a tier penalty. Role agents' host `steps` = 2 × max(the top role budget, 25)
55
+ + `REFUSAL_CAP` (10) + 5. A dispatch that a floor lifts above its role's ceiling, on a tier the role has no budget
56
+ for, gets max(the role's budget for its ceiling tier, 25). The cumulative ceiling is 3 × the largest round budget
57
+ the child had. A role dispatch has a read-only call cap only when it carries `CAP:N` or `CAP:none`. A
58
+ `subagentTiers` entry for a role name gives that role's children the mapped tier's default read-only cap (and, for
59
+ `fast`, the trivial-dispatch bypass): remove such entries in roles mode.
60
+ - Refused calls of a role child — role-authority refusals and structured host permission denials — count toward
61
+ `denied_cap` in `advisory` mode too (`advisory` still never stops). In `advisory` mode a child out of budget that
62
+ returns `NEED MORE: budget` records a `budget` signal and the parent's result gets the `[router budget]` note.
63
+ - Resumes of a role child keep the dispatch's class and needs (risk and scope: the max of both), its `[acceptance]`
64
+ block, `VERIFY:` lines and `d=` claim; a new block replaces them. Carried checks run at the resume's return (never
65
+ deferred) on the child's cumulative changes, and are unverifiable when the attempt that introduced them was never
66
+ gated. An authority request widens the grant only when the resuming session is the dispatch's parent, never on a
67
+ delegate's resume.
68
+ - A role dispatch's detection is `none` when no verification will run (enforcement `off`, `/bypass`,
69
+ `verify.require: "never"`, a `cwd` outside the root the gate verifies in).
70
+ - Dynamic roles: a route-line `needs=` replaces the needs the text implies (the listed needs plus the route class's
71
+ implied needs, always inside the role max), and `class=` without `needs=` keeps the text's needs plus that class's
72
+ implied needs, dropping those of the class it replaced; a role dispatch is classified in its work root. Decision rows carry
73
+ `trace.needTerms` (vocabulary labels, `term-<n>`, `url`, `path`, never free task text).
74
+ - In a role dispatch's result, child lines starting with `[router` are defanged to `(router`, so only the router's
75
+ notes start with `[router`.
76
+ - Outcome signals from external verification only (deterministic/run 1, independent grader 0.5, incomplete 0.5,
77
+ re-dispatch 0.5, `DONE` alone 0; the `run` signal matches npm-script-form checks only and counts only the current
78
+ attempt's runs). Only verdicts (deterministic, and independent graders at 0.5) move the outcome store the kernel
79
+ reads; `run`, `incomplete` and `redispatch` rows are routing statistics only. An LLM grader's verdict of
80
+ a role dispatch moves the outcome store by 0.5 with a `grader` signal row only when the grader is independent
81
+ (tier ≥ the producer's, another model); any other grader records nothing (no store change, no verdict row), so
82
+ `routing:stats` shows fewer verdict rows for role dispatches. Role × tier statistics and the advisor findings
83
+ `role-separation`,
84
+ `roles-on-legacy-host`, `role-budget-low`, `role-range-clamped`, `role-binding-unknown`,
85
+ `native-explore-aliased`, `roles-none-enabled`, `role-usage-share`.
86
+ - Exploration of cheaper rungs (`routing.exploration.rate`, off by default, at most 0.2, `enforce` and deterministic
87
+ detection only).
88
+ - New keys: `routing.delegation`, `roleAgents`, `routing.exploration`, `routing.run`, `routing.workRoots`. On
89
+ OpenCode v1 they are validated and inert, with one notice.
90
+ - **`agents` block: subagents defined by the router (#81).** `tiers.json` and the global override can define
91
+ subagents that run on a tier of the active preset (following `/preset`), with `readOnly`/`allowTools` or an
92
+ explicit `permission`, on v1 and v2 with fail-closed permissions. Project overrides cannot define `agents`
93
+ (A18). `/router` lists them under "Plugin agents". On OpenCode v2 a `permission` key naming `write`, `patch`,
94
+ `multiedit` or `apply_patch` only narrows that tool and `edit` decides; a key that allows or asks for what the
95
+ agent's `edit` rules deny gets a config notice.
96
+ - Six shell-free `router_git_*` inspection tools: status, log, diff, show, blame,
97
+ ls_files. Fixed hardened argv, strict paths/refs, bounded output, timeout/tree
98
+ cancellation, and remote-URL userinfo redaction; no write commands or arbitrary
99
+ options. Read-only tiers can also use configured Context7 docs lookups.
100
+ See [Read-only tiers](docs/READ_ONLY_TIERS.md) for policy, overrides and limits
101
+ (not an OS sandbox).
102
+
103
+ ### Fixed
104
+
105
+ - **Plugin agents round-1 fixes (#81).** `allowTools` can no longer grant edit, delegation, Code Mode `execute` or shell, rejects leading wildcards and never reaches the legacy `tools` booleans; grep output is redacted for every plugin agent on v1 and v2; v1 `subagentTiers` still maps host built-ins such as `explore`; stale plugin agents are removed on reload; one preset resolver; v2 skips colliding non-subagent host agents. See `docs/qa/plugin-agents.md`.
106
+ - `subagentTiers` no longer creates phantom primary, allow-all agents for names that no agent defines; such
107
+ names are skipped with a notice. On v2 the router re-checks at the first prompt, so `opencode.json` agents
108
+ registered after startup still get the tier model.
109
+
110
+ ### Changed
111
+
112
+ - **Behaviour change (#84): guard and verification fixes for every host and mode** (v1, v2 tiers mode and roles mode;
113
+ each ships with a before/after golden):
114
+ - **Reader guard profile.** The read-only `fast` tier, dispatches routed `class=review|recon|search` (OpenCode v2
115
+ with a routing engine other than `static`; never on v1), dispatches with `CAP:none` + `reason:` and reader roles are no longer denied or warned for "consecutive non-producing" reads;
116
+ readers are told to emit their final answer instead of to take a producing action.
117
+ - **Uncharged denials.** A refused call is no longer charged to the call budget nor recorded as executed by the
118
+ repeat check; a round is stopped for refusals only when it has min(budget, 10) of them and its executed plus refused
119
+ calls reach the budget.
120
+ - **Whole criteria.** Verification never cuts a criterion: the inferred criterion is the first task line whole (or
121
+ its leading whole sentences within 4000 code points), and grader criteria are kept whole within 4000 code points.
122
+ **Explicit `[acceptance]` lists over 4000 code points are no longer graded in full:** the overflow is named
123
+ ("n criteria omitted") and not graded, and a pass on the rest is unverifiable.
124
+ - **Header strip.** The router's dispatch header (through its first `---` separator) and router directives
125
+ (`CAP:`, `VERIFY:`, `VERIFY_WAIT:`, `reason:`, `[route …]`, `[router]`) are no longer gradable criteria.
126
+ - **Progress notes are incomplete.** A contract follower's progress note, and a `NEED MORE: budget` return backed
127
+ by the guard's state, is an `incomplete` verdict (`[router ⚠ INCOMPLETE]`): never accepted, no next tier, no
128
+ evidence, resume the same session. The budget claim is read from the return prefix; a progress summary written
129
+ before a line-start `NEED MORE: budget` still counts.
130
+ - **`root=` in the header.** The dispatch header's `Working directory:` names the route line's `root=` when present
131
+ (byte-identical otherwise).
132
+ - **Verification reasons, in tiers mode too.** Verification reasons are rendered one per line with line breaks
133
+ joined, at most 20 items plus a count of the rest; an LLM grader's text is cut at 500 characters. A list of at
134
+ most 20 one-line reasons renders as before.
135
+ - **Downgrades.** Outcome signals are written as annotation rows of the decision log, which earlier versions drop
136
+ only through their decision-id dedupe: downgrading past this version is unsupported.
137
+ - `anthropic` preset: `fast` tier now uses Claude Haiku 5.5 (low) instead of Sonnet 5.5 (low).
138
+ - **Breaking (behaviour): `fast` is now host-enforced read-only on v1 and v2 (#77).** Shell, edits,
139
+ Code Mode, delegation and unspecified MCP tools are denied, including inherited
140
+ ask grants outside the permitted actions, even
141
+ for existing configs without the new optional tier `readOnly` boolean.
142
+ Opt out by setting `presets.<preset>.fast.readOnly: false` in a router override
143
+ file. V2 inherited session grants no longer override the agent's own denies or
144
+ asks, but remain intact for children resumed as medium/heavy. Drifted host
145
+ defaults fail closed. Agent-specific resource overrides on
146
+ permitted actions remain supported; other tiers are unchanged. Legacy v1
147
+ hosts that honour only tool booleans cannot enforce sensitive-read approval.
148
+ `rename` moves from the fast taxonomy to medium. Fast prompts distinguish
149
+ direct tools from the separate Code Mode catalog.
150
+ One shared sensitive-file policy now drives read asks, read-only grep output
151
+ filtering, and Git patch exclusions/refusals. Git show accepts commits only
152
+ (no blob ids or `rev:path`); log includes filtered patches. The list includes
153
+ `*.env`/`*.env.*` and additional credential stores; exact SSH public-key `.pub`
154
+ names and `*.env.example` are intentionally readable. Saved project-wide
155
+ “always allow” approvals are applied after host deny checks (QA-77-P8), but the
156
+ v2 router hook now restores the protected agent's ask. Auto-answer modes may
157
+ still approve that ask; denies remain denied.
158
+
10
159
  ## [2.3.0] - 2026-10-07
11
160
 
12
161
  ### Added
package/README.md CHANGED
@@ -4,17 +4,27 @@
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,249–6,357 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,248–6,356 characters of system-prompt overhead depending on the orchestrator and enforcement mode.
8
8
 
9
9
  ## Why it's different
10
10
 
11
+ **`fast` is now host-enforced read-only (behaviour change, #77).** It can use
12
+ `read`, `glob`, `grep`, the six shell-free `router_git_*` inspection tools, and
13
+ configured Context7 documentation lookups—not shell, edits, Code Mode, or child
14
+ agents. `rename` belongs to `medium`. This applies even to older configs without
15
+ the new field. To opt out for a preset, layer
16
+ `{ "presets": { "anthropic": { "fast": { "readOnly": false } } } }` in your
17
+ router override file (substitute your preset). Other tiers are unchanged.
18
+ See [Read-only tiers](docs/READ_ONLY_TIERS.md) for permission precedence,
19
+ configurable external-directory access, Git limits, and why this is **not an OS sandbox**.
20
+
11
21
  Most AI coding tools give you one model for everything. You pay Opus prices to run `grep`. opencode-model-router changes that with a stack of interlocking ideas:
12
22
 
13
23
  **Use a mid-tier model as orchestrator.**
14
24
  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
25
 
16
26
  **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,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.
27
+ Instead of duplicated prose, the plugin injects a dense, machine-readable routing protocol. The protocol itself is 3,248 characters; a Claude orchestrator receives 4,020 characters after its authority prefix (roughly 1,005–1,117 tokens at 3.6–4.0 characters per token). Every message, every session.
18
28
 
19
29
  **Match task to tier using a configurable taxonomy.**
20
30
  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 +77,7 @@ opencode-model-router injects a **delegation protocol** into the system prompt t
67
77
  4. **Never over-qualify** — use the cheapest tier that can reliably handle the task
68
78
  5. **Fallback** across providers when one fails
69
79
 
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).
80
+ All of this adds 3,248 characters for a non-Claude orchestrator or 4,020 characters for a Claude orchestrator (roughly 812–1,117 tokens at 3.6–4.0 characters per token).
71
81
 
72
82
  ## Understanding how it works
73
83
 
@@ -168,13 +178,13 @@ Task distribution: 18 exploration (60%), 10 implementation (33%), 2 architecture
168
178
 
169
179
  ## How it works
170
180
 
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.
181
+ On every message, the plugin injects a 3,248-character routing protocol. A Claude orchestrator receives 4,020 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
182
 
173
183
  What the orchestrator sees (Anthropic preset, normal mode):
174
184
 
175
185
  ```
176
186
  ## Model Delegation Protocol
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
187
+ Preset: anthropic. Tiers: @fast=claude-haiku-5-5/low(1x) @medium=claude-sonnet-5-5/medium(5x) @heavy=claude-opus-5-5/xhigh(20x). mode:normal
178
188
  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
189
  Multi-phase: prefer explore(@fast)→execute(@medium) when phases are separable. Cheapest-first when practical.
180
190
  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 +230,7 @@ With router → split:
220
230
  | Cross-provider fallback | ✅ | ❌ | ❌ | ❌ | ❌ |
221
231
  | Cost ratio awareness | ✅ | ❌ | ❌ | ❌ | ❌ |
222
232
  | Plan annotation with tiers | ✅ | ❌ | ❌ | ❌ | ❌ |
223
- | Measured prompt overhead: 3,249–6,357 chars | ✅ | — | ❌ | ❌ | ❌ |
233
+ | Measured prompt overhead: 3,248–6,356 chars | ✅ | — | ❌ | ❌ | ❌ |
224
234
 
225
235
  **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
236
 
@@ -420,7 +430,7 @@ The plugin ships with eight presets (switch with `/preset <name>`):
420
430
  **anthropic** (default):
421
431
  | Tier | Model | Cost ratio |
422
432
  |------|-------|-----------|
423
- | @fast | `anthropic/claude-sonnet-5-5` (variant/effort: low) | 1x |
433
+ | @fast | `anthropic/claude-haiku-5-5` (variant/effort: low) | 1x |
424
434
  | @medium | `anthropic/claude-sonnet-5-5` (variant/effort: medium) | 5x |
425
435
  | @heavy | `anthropic/claude-opus-5-5` (variant/effort: xhigh) | 20x |
426
436
 
@@ -596,6 +606,19 @@ The `rules` array is injected verbatim (in compact form) into the system prompt.
596
606
 
597
607
  Rules in `modes[x].overrideRules` replace this array entirely for that mode.
598
608
 
609
+ ### Router-defined subagents (`agents`)
610
+
611
+ Define extra subagents in `tiers.json` or the global override instead of `opencode.json` (#81). Each runs on a
612
+ tier of the active preset (so it follows `/preset`), is always a subagent, and gets router-published
613
+ permissions: `readOnly: true` reuses the read-only policy, or give an explicit `permission`.
614
+
615
+ ```jsonc
616
+ { "agents": { "reviewer": { "tier": "heavy", "description": "Reviews diffs", "readOnly": true, "allowTools": ["router_git_*"] } } }
617
+ ```
618
+
619
+ Project overrides cannot define `agents`. `opencode.json` wins for the fields it sets when it defines the same
620
+ name. `subagentTiers` no longer creates agents that do not exist (host built-ins such as `explore` still map). `allowTools` never grants edit, delegation, Code Mode or shell. See
621
+ [CONFIG_REFERENCE.md](docs/CONFIG_REFERENCE.md#agents--router-defined-subagents-81).
599
622
  ### Read-only call caps
600
623
 
601
624
  Subagents carry a cap on their own read-only tool calls (grep/read/glob/ls) per dispatch. Enforcement is **two-layered**: prompt-level stop rules + runtime banners injected into tool results. Baselines (configurable via `tierCaps` — see below):
@@ -721,7 +744,7 @@ Each tier (`@fast`, `@medium`, `@heavy`) has a system prompt that describes its
721
744
  },
722
745
  "presets": {
723
746
  "anthropic": {
724
- "fast": { "model": "anthropic/claude-sonnet-5-5", ... },
747
+ "fast": { "model": "anthropic/claude-haiku-5-5", ... },
725
748
  "medium": { "model": "anthropic/claude-sonnet-5-5", ... },
726
749
  "heavy": { "model": "anthropic/claude-opus-5-5", ... }
727
750
  }
@@ -1079,6 +1102,8 @@ Full field notes are in [docs/CONFIG_REFERENCE.md](docs/CONFIG_REFERENCE.md).
1079
1102
  - `docs/ENFORCEMENT_PRESETS.md` — ready-to-paste enforcement presets
1080
1103
  - `docs/ROUTING_ENGINE.md` — the cost-aware routing engine: modes, formula, classifier backends, session-aware ladder, cost doctor, privacy
1081
1104
  - `docs/adr/0005-cost-aware-routing-engine.md` — the decisions behind the routing engine
1105
+ - `docs/ROLES.md` — roles mode: role agents, authority and separation, tier floor, budgets, `router_run`, migration
1106
+ - `docs/adr/0006-role-tier-assurance-delegation.md` — the decisions behind roles mode
1082
1107
 
1083
1108
  > These files are not included in the npm tarball. This section is the self-contained summary; the docs are available in the repository for contributors and advanced users.
1084
1109
 
@@ -1107,7 +1132,28 @@ What else ships with it:
1107
1132
  - **Observability.** A decision log and an outcome store under the trajectory directory, `/router stats`, and `npm run routing:stats` in a clone.
1108
1133
  - **Classifier backends** for uncertain task classes: `rules` (default, local), `openai-compatible` (Ollama, any OpenAI-style server), `typesafe`, and `host` (**experimental**). Backends receive at most a bounded, scrubbed excerpt of the task, are only configurable from the global override, and never block a dispatch.
1109
1134
 
1110
- OpenCode v1 is unchanged: the `routing` block is validated and `engine` is forced to `static`; the only effect is an opt-in prose line when you set `routing.roles`. Every key and default is in [`docs/CONFIG_REFERENCE.md`](docs/CONFIG_REFERENCE.md#routing--cost-aware-routing-engine-74); the full guide is [`docs/ROUTING_ENGINE.md`](docs/ROUTING_ENGINE.md) and the decision record is [`docs/adr/0005-cost-aware-routing-engine.md`](docs/adr/0005-cost-aware-routing-engine.md).
1135
+ On OpenCode v1 the routing engine does not run: the `routing` block is validated and `engine` is forced to `static`; setting `routing.roles` adds an opt-in prose line. Roles mode is inert on v1 too: when `routing.delegation: "roles"`, `roleAgents`, `routing.exploration`, `routing.run` or `routing.workRoots` is set, the plugin logs one notice per process, `roles delegation requires OpenCode v2; using tiers`, and with `routing.delegation: "roles"` `/router` also reports the advisor info `roles-on-legacy-host`. v1 is not entirely unchanged by this release: the #84 guard and verification fixes apply on every host (see the [behaviour change entry](CHANGELOG.md#changed) of the changelog). Every key and default is in [`docs/CONFIG_REFERENCE.md`](docs/CONFIG_REFERENCE.md#routing--cost-aware-routing-engine-74); the full guide is [`docs/ROUTING_ENGINE.md`](docs/ROUTING_ENGINE.md) and the decision record is [`docs/adr/0005-cost-aware-routing-engine.md`](docs/adr/0005-cost-aware-routing-engine.md).
1136
+
1137
+ ## Roles mode (opt-in, OpenCode v2)
1138
+
1139
+ With `routing.delegation: "roles"` the orchestrator stops picking tiers: it dispatches **role agents** by intent, and the router picks the tier and model of every dispatch (issue #84).
1140
+
1141
+ | Role | For | Tiers |
1142
+ |---|---|---|
1143
+ | `explorer` | read-only codebase lookups | fast–medium |
1144
+ | `researcher` | web and library docs, no local files | fast–medium |
1145
+ | `runner` | tests, typecheck, lint, build through `router_run` | fast–medium |
1146
+ | `implementer` | scoped edits, checks when needed | fast–heavy |
1147
+ | `reviewer` | read-only senior review | heavy |
1148
+ | `architect` | read-only design analysis | medium–heavy |
1149
+ | `general` | anything else; authority follows the task's needs | fast–heavy |
1150
+
1151
+ - **Least privilege.** Each role has a fixed maximum authority, and no role holds the web together with reads, runs or edits. Commands run through `router_run` (allowlisted scripts and commands, fixed argv, no shell controlled by the caller; npm script bodies still run in npm's pinned script shell); raw shell stays with the tier agents.
1152
+ - **Authority sets the floor.** Reading may use the cheapest tier; an edit goes below `medium` only when the router itself runs the acceptance checks on a low-risk, single-file change, and edit + run never goes below `medium` (`heavy` without those checks).
1153
+ - **Budgets per role.** A role that runs out of calls returns `NEED MORE: budget` and is resumed in the same session; that is never counted as a failure.
1154
+ - **Evidence from verification only.** Only verdicts move the routing evidence: the router's deterministic checks, and an independent LLM grader at half weight. Router-observed runs, incomplete returns and re-dispatches are recorded as routing statistics; a bare `DONE` counts for nothing.
1155
+
1156
+ Put `{ "routing": { "delegation": "roles" } }` in the global override file and **restart OpenCode** (roles mode is decided at plugin start); restore the previous file and restart to go back. OpenCode v1 keeps the tier model. Guide: [`docs/ROLES.md`](docs/ROLES.md); decision record: [`docs/adr/0006-role-tier-assurance-delegation.md`](docs/adr/0006-role-tier-assurance-delegation.md).
1111
1157
 
1112
1158
  ## Commands
1113
1159
 
@@ -1152,7 +1198,7 @@ With the [routing engine](#cost-aware-routing-opt-in-opencode-v2) live on OpenCo
1152
1198
 
1153
1199
  ## Token overhead
1154
1200
 
1155
- 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.
1201
+ Measured with the bundled Anthropic preset in normal mode (the shipped `activePreset`/`activeMode` defaults), the routing protocol is 3,248 characters for a non-Claude orchestrator. A Claude orchestrator receives 4,020 characters after its authority prefix, or 6,356 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.
1156
1202
 
1157
1203
  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.
1158
1204
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "2.3.0",
3
+ "version": "2.4.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",
@@ -15,6 +15,7 @@ import type { RouterConfig, ModeConfig } from "../router/config";
15
15
  import { getActiveTiers } from "../router/protocol";
16
16
  import { resolvePromptStyle } from "../router/prompts";
17
17
  import type { Catalog, ModelIssue } from "../router/catalog";
18
+ import type { RoleSpec } from "../router/roles";
18
19
 
19
20
  /** `/tiers` */
20
21
  export function buildTiersOutput(cfg: RouterConfig): string {
@@ -210,8 +211,26 @@ export function buildOverridesOutput(v: OverridesView): string {
210
211
  ].join("\n");
211
212
  }
212
213
 
214
+ /**
215
+ * Role lines of `/router` in roles mode: one per enabled role, `name (kind): floor..ceiling | authority`. Authority is the
216
+ * mode and the allowed actions, with the denied ones when any. Empty without roles (tiers mode, v1): nothing is added.
217
+ */
218
+ export function buildRoleLines(roles: Iterable<RoleSpec>): string[] {
219
+ const lines: string[] = [];
220
+ for (const role of roles) {
221
+ if (!role.enabled) continue;
222
+ const { mode, allow, deny } = role.authority;
223
+ const denied = deny.length > 0 ? `; denied: ${deny.join(", ")}` : "";
224
+ lines.push(
225
+ `- \`${role.agent}\` (${role.kind}): tiers ${role.tierRange.floor}..${role.tierRange.ceiling} | authority ${mode}: ${allow.join(", ") || "none"}${denied}`,
226
+ );
227
+ }
228
+ return lines.length === 0 ? [] : ["Roles:", ...lines];
229
+ }
230
+
213
231
  /** Bare `/router`. */
214
- export function buildRouterHelp(current: string, options: { stats?: boolean } = {}): string {
232
+ export function buildRouterHelp(current: string, options: { stats?: boolean; roles?: Iterable<RoleSpec> } = {}): string {
233
+ const roleLines = options.roles === undefined ? [] : buildRoleLines(options.roles);
215
234
  return [
216
235
  `# Model Router`,
217
236
  `Enforcement: **${current}**`,
@@ -224,6 +243,7 @@ export function buildRouterHelp(current: string, options: { stats?: boolean } =
224
243
  ? ["- `/router stats [--since <ISO>]` — routing statistics from the decision log and outcome store (same table as `npm run routing:stats` (in a clone))"]
225
244
  : []),
226
245
  "- `/tiers`, `/preset`, `/budget`, `/bypass`, `/annotate-plan`",
246
+ ...(roleLines.length > 0 ? ["", ...roleLines] : []),
227
247
  ].join("\n");
228
248
  }
229
249