opencode-model-router 2.2.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 (83) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +90 -12
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +24 -1
  5. package/src/compat/child-session.ts +43 -0
  6. package/src/compat/v2-client.ts +107 -7
  7. package/src/compat/v2-hooks.ts +1435 -44
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +496 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/guard/enforce.ts +186 -22
  13. package/src/guard/guards.ts +132 -6
  14. package/src/guard/store.ts +5 -0
  15. package/src/index.ts +1193 -56
  16. package/src/router/build-info.ts +151 -0
  17. package/src/router/config.ts +1611 -19
  18. package/src/router/dispatch-header.ts +46 -4
  19. package/src/router/git-tools.ts +1152 -0
  20. package/src/router/guard-profile.ts +100 -0
  21. package/src/router/plugin-agents.ts +433 -0
  22. package/src/router/prompts.ts +26 -1
  23. package/src/router/protocol.ts +180 -0
  24. package/src/router/read-only.ts +149 -0
  25. package/src/router/role-agents.ts +409 -0
  26. package/src/router/roles-config.ts +429 -0
  27. package/src/router/roles.ts +600 -0
  28. package/src/router/run-tools.ts +913 -0
  29. package/src/router/sensitive-paths.ts +101 -0
  30. package/src/router/sessions.ts +533 -9
  31. package/src/router/subagents.ts +28 -1
  32. package/src/routing/advisor/findings.ts +898 -0
  33. package/src/routing/advisor/index.ts +614 -0
  34. package/src/routing/classify/backends/host.ts +163 -0
  35. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  36. package/src/routing/classify/backends/shared.ts +741 -0
  37. package/src/routing/classify/backends/typesafe.ts +315 -0
  38. package/src/routing/classify/fences.ts +96 -0
  39. package/src/routing/classify/index.ts +594 -0
  40. package/src/routing/classify/route-line.ts +362 -0
  41. package/src/routing/classify/rules.ts +667 -0
  42. package/src/routing/classify/scrub.ts +214 -0
  43. package/src/routing/classify/state.ts +148 -0
  44. package/src/routing/classify/text.ts +20 -0
  45. package/src/routing/classify/types.ts +1310 -0
  46. package/src/routing/commands/annotate-plan.ts +652 -0
  47. package/src/routing/commands/stats.ts +134 -0
  48. package/src/routing/commands/v1-roles.ts +64 -0
  49. package/src/routing/engine/index.ts +32 -0
  50. package/src/routing/engine/kernel.ts +760 -0
  51. package/src/routing/engine/ladders.ts +802 -0
  52. package/src/routing/engine/plan.ts +404 -0
  53. package/src/routing/engine/protocol-line.ts +150 -0
  54. package/src/routing/engine/roles-taxonomy.ts +52 -0
  55. package/src/routing/engine/simulate.ts +167 -0
  56. package/src/routing/engine/types.ts +368 -0
  57. package/src/routing/file-lock.ts +53 -0
  58. package/src/routing/outcomes/beta.ts +147 -0
  59. package/src/routing/outcomes/cost.ts +313 -0
  60. package/src/routing/outcomes/index.ts +215 -0
  61. package/src/routing/outcomes/ingest.ts +960 -0
  62. package/src/routing/outcomes/persist.ts +1080 -0
  63. package/src/routing/outcomes/signals.ts +650 -0
  64. package/src/routing/outcomes/stats.ts +873 -0
  65. package/src/routing/outcomes/store.ts +673 -0
  66. package/src/routing/outcomes/types.ts +1093 -0
  67. package/src/routing/roles/authority.ts +495 -0
  68. package/src/routing/roles/binding.ts +543 -0
  69. package/src/routing/roles/policy.ts +416 -0
  70. package/src/routing/roles/work-root.ts +132 -0
  71. package/src/routing/wire/dispatch.ts +2088 -0
  72. package/src/routing/wire/hint.ts +222 -0
  73. package/src/routing/wire/host-info.ts +256 -0
  74. package/src/routing/wire/runtime.ts +348 -0
  75. package/src/v2.ts +40 -1
  76. package/src/verify/checker.ts +249 -7
  77. package/src/verify/deterministic.ts +10 -1
  78. package/src/verify/dispatch.ts +63 -6
  79. package/src/verify/dod.ts +127 -10
  80. package/src/verify/gate.ts +75 -7
  81. package/src/verify/types.ts +12 -0
  82. package/src/verify/wiring.ts +55 -10
  83. package/tiers.json +13 -5
package/CHANGELOG.md CHANGED
@@ -7,6 +7,220 @@ 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
+
159
+ ## [2.3.0] - 2026-10-07
160
+
161
+ ### Added
162
+
163
+ - **Cost-aware routing engine (#74), OpenCode v2, opt-in.** A `routing` block
164
+ turns on a decision engine that picks the `(agent, model#variant, retry path)`
165
+ of each dispatch from an expected-cost formula fed by typed task facts decided
166
+ in code and a scoreboard of verified outcomes per `(task class × agent ×
167
+ model#variant)`. With no `routing` block the plugin behaves exactly as 2.2.0.
168
+ Suggested in #73 by @javizuurc (giving custom agents and the context of the work
169
+ to a routing step that decides who does it); implemented from scratch with the
170
+ decision kept in code, and TypeSafe supported as an optional classifier backend.
171
+ - `routing.engine`: `static` (default), `shadow` (decide and record), `advise`
172
+ (generated `R:` line and a stable one-line `Route hint`, advise only) and `enforce` (no hint; reroute under
173
+ a strict margin, an evidence gate of 5 effective (decayed) outcomes on the
174
+ candidate's own key, permission and
175
+ floor rules, and the D9 never-down gate: high-risk work without detection
176
+ cannot run below the pick's capability rank or at lower effort on the same
177
+ model; detection uses the weaker route-line/acceptance claim. A dispatch
178
+ carrying `[route … pin]` is never rerouted).
179
+ - A task classifier (rules, an optional first-line `[route …]` directive, and
180
+ optional `host`, `openai-compatible` and `typesafe` backends; `host` is
181
+ experimental). Backends see a bounded, scrubbed excerpt only, never a task
182
+ that names a credential, and are configurable only from the global override.
183
+ - An outcome store and a decision log under the trajectory directory, with
184
+ cost units that never mix USD and `costRatio` and a zero cost for an unpriced
185
+ model treated as unknown.
186
+ - Same-session variant steps: a failed verification retries on the same
187
+ model's next variant, resuming the child session, before the ladder pays for
188
+ a bigger model (`enforcement.escalate.variantSteps`, `tiers.<t>.candidates`,
189
+ `routing.sessionReuse`).
190
+ - Native agents (`explore`, `general`) as default candidates on v2
191
+ (`routing.roles`; `roles: {}` disables them). The plugin never raises
192
+ `subagent_depth`.
193
+ - A cost doctor: findings in `/router` (title model, unpriced and missing
194
+ models, impossible variants, subscription pricing) and at most one notice,
195
+ delivered as a synthetic transcript entry, throttled per project.
196
+ `variant-effort` reports an empty variant ladder when a tier also sets effort
197
+ options; it fires on bundled `hybrid-2`/`anthropic` once a `routing` block
198
+ exists (unless variant steps are explicitly off). `effort-variant-mismatch`
199
+ reports different `variant` and `effort` values with a live engine and variant
200
+ steps off: the wire effort and learned outcome key would differ.
201
+ Throttle/pending state is stored as `advisor-notice.<hash>.json` with an
202
+ `advisor-notice.<hash>.lock` file in the outcomes directory, per project.
203
+ - `/router stats` and `npm run routing:stats` (the script needs Node 22.18 / 23.6 or
204
+ newer and is not part of the package); `/annotate-plan` emits `[route …]`
205
+ lines and pins `[tier:heavy]` steps when the engine is live; the bare
206
+ `/router` view prints `router: engine=<mode> build=<version>+<sha7>`.
207
+ It also prints `router: config notice:` lines for findings from the last
208
+ config load. A18: `routing.outcomes.path`, like classifier backend settings,
209
+ is accepted only from bundled config or the global override; project-local
210
+ values are dropped with a one-time warning.
211
+ - Documentation: `docs/ROUTING_ENGINE.md`, `docs/adr/0005-cost-aware-routing-engine.md`
212
+ and the `routing` section of `docs/CONFIG_REFERENCE.md`.
213
+
214
+ ### Changed
215
+
216
+ - With a `routing` block, `enforcement.escalate.variantSteps` defaults to `auto`
217
+ on OpenCode v2 (without one it stays `none`, so the 2.2.0 ladder is
218
+ unchanged); `enforcement.escalate.effortBumpMax` also caps the variant ladders
219
+ read from the model catalog.
220
+ - OpenCode v1: the `routing` block is validated and `routing.engine` is forced
221
+ to `static` with one log line; setting `routing.roles` explicitly adds a
222
+ prose-only destination suffix to the `R:` line.
223
+
10
224
  ## [2.2.0] - 2026-10-05
11
225
 
12
226
  ### 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
  }
@@ -1075,11 +1098,63 @@ Full field notes are in [docs/CONFIG_REFERENCE.md](docs/CONFIG_REFERENCE.md).
1075
1098
  - `docs/ENFORCEMENT.md` — architecture, hook wiring, session lifecycle
1076
1099
  - `docs/VERIFICATION.md` — DoD schema, deterministic checks, grader dispatch
1077
1100
  - `docs/ESCALATION.md` — escalation ladder configuration and cost ceilings
1078
- - `docs/CONFIG_REFERENCE.md` — full `enforcement` block schema
1101
+ - `docs/CONFIG_REFERENCE.md` — full `enforcement` and `routing` block schema
1079
1102
  - `docs/ENFORCEMENT_PRESETS.md` — ready-to-paste enforcement presets
1103
+ - `docs/ROUTING_ENGINE.md` — the cost-aware routing engine: modes, formula, classifier backends, session-aware ladder, cost doctor, privacy
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
1080
1107
 
1081
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.
1082
1109
 
1110
+ ## Cost-aware routing (opt-in, OpenCode v2)
1111
+
1112
+ By default the router picks a tier from the taxonomy in the protocol text and a fixed model per tier. The **routing engine** (issue #74, inspired by #73) can instead pick the `(agent, model#variant, retry path)` of each dispatch from an expected-cost formula fed by two things the plugin already produces: typed facts about the task, decided in code, and a scoreboard of **verified outcomes** (verification verdicts, false refusals, measured cost) per `(task class × agent × model#variant)`. It is off unless you add a `routing` block, and with no `routing` block the plugin behaves exactly as `2.2.0`.
1113
+
1114
+ | `routing.engine` | What happens |
1115
+ |---|---|
1116
+ | `static` (default) | Nothing is decided or recorded; the protocol text and `R:` line are unchanged. |
1117
+ | `shadow` | Every dispatch is decided and logged; nothing about it changes. |
1118
+ | `advise` | As `shadow`, and the orchestrator also receives the generated `R:` line and a one-line `Route hint`; it still decides. |
1119
+ | `enforce` | As `advise`, and the engine reroutes a dispatch when its expected cost is lower by more than `margin`, the class is trusted, the target has at least 5 effective outcomes (or ranks above the orchestrator's pick) and the permission and floor rules allow it. A dispatch carrying `[route … pin]` is never rerouted. |
1120
+
1121
+ Start in `shadow`, read `/router stats`, then raise the mode. A mode is a config-only change (hot reloaded); `static` is the instant kill switch. Put it in the global override file, `~/.config/opencode/opencode-model-router.overrides.jsonc`:
1122
+
1123
+ ```jsonc
1124
+ { "routing": { "engine": "shadow" } }
1125
+ ```
1126
+
1127
+ What else ships with it:
1128
+
1129
+ - **Same-session variant steps.** On OpenCode v2 a failed verification retries on the same model's next variant, resuming the child session (history kept), before paying for a bigger model.
1130
+ - **Native agents as candidates.** `explore` and `general` can be chosen for `search`, `implement`, `debug` and `review` work (`routing.roles`; `roles: {}` turns this off).
1131
+ - **A cost doctor.** `/router` reports waste outside the router (an unset title model on an expensive session model, unpriced models, variants the catalog does not offer) and sends at most one short notice.
1132
+ - **Observability.** A decision log and an outcome store under the trajectory directory, `/router stats`, and `npm run routing:stats` in a clone.
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.
1134
+
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).
1157
+
1083
1158
  ## Commands
1084
1159
 
1085
1160
  | Command | Description |
@@ -1089,11 +1164,12 @@ Full field notes are in [docs/CONFIG_REFERENCE.md](docs/CONFIG_REFERENCE.md).
1089
1164
  | `/preset <name>` | Switch preset (e.g., `/preset openai`) |
1090
1165
  | `/budget` | Show available modes and which is active |
1091
1166
  | `/budget <mode>` | Switch routing mode (`normal`, `budget`, `quality`, `deep`) |
1092
- | `/annotate-plan [path]` | Annotate a plan file with `[tier:X]` tags for each step |
1167
+ | `/annotate-plan [path]` | Annotate a plan file with `[tier:X]` tags for each step (and `[route …]` lines when the routing engine is live on v2) |
1093
1168
  | `/router overrides` | Show the global + project override file paths and merge precedence |
1094
1169
  | `/router models [provider]` | List valid model ids from your configured providers (with defaults and deprecated flags) |
1095
1170
  | `/router enforce <off\|advisory\|enforced>` | Set delegation-enforcement mode (persisted) |
1096
- | `/router` | With no subcommand — or an unrecognized one — prints the `/router` help and the current enforcement mode |
1171
+ | `/router stats [--since <ISO>] [--until <ISO>] [--json] [--dir <path>]` | Routing engine statistics for a time window (dispatches, agreement, switches, savings estimate, verdict and false-refusal rates per key); same table as `npm run routing:stats` in a clone. The script does not read config: pass `--dir <routing.outcomes.path>` when set. |
1172
+ | `/router` | With no subcommand — or an unrecognized one — prints the `/router` help and the current enforcement mode, plus the line `router: engine=<mode> build=<version>+<sha7>` (the engine in force and the build of the running code; on v1 it also prints, always as `engine=static`) and, on v2 with a `routing` block, the cost doctor's findings |
1097
1173
  | `/bypass [on\|off]` | Toggle the router off/on for the session |
1098
1174
 
1099
1175
  ## Plan annotation
@@ -1118,9 +1194,11 @@ After `/annotate-plan`:
1118
1194
  4. [tier:heavy] Design a token bucket algorithm for advanced rate limiting
1119
1195
  ```
1120
1196
 
1197
+ With the [routing engine](#cost-aware-routing-opt-in-opencode-v2) live on OpenCode v2, `/annotate-plan` also emits a `[route class=… risk=… d=…]` line per step, and pins (`pin`) every step whose final tag is `[tier:heavy]`, so the engine never reroutes it. A step that **starts with a code block** is skipped and reported (the command says which line and what to add by hand); the command never edits the file itself. Details: [`docs/ROUTING_ENGINE.md`](docs/ROUTING_ENGINE.md#annotate-plan).
1198
+
1121
1199
  ## Token overhead
1122
1200
 
1123
- 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.
1124
1202
 
1125
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.
1126
1204
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "2.2.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",
@@ -9,9 +9,12 @@
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:v1": "node scripts/smoke-v1-preflight.mjs && npm run smoke:keyless",
12
13
  "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
14
  "smoke:v2": "cross-env RUN_OC_SMOKE_V2=1 vitest run --config vitest.smoke.config.ts test/smoke/v2-registration.smoke.test.ts",
15
+ "smoke:routing": "cross-env RUN_OC_SMOKE_ROUTING=1 vitest run --config vitest.smoke.config.ts test/smoke/routing-engine.smoke.test.ts",
14
16
  "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",
17
+ "routing:stats": "node scripts/routing-stats.ts",
15
18
  "typecheck": "tsc --noEmit"
16
19
  },
17
20
  "license": "GPL-3.0-only",
@@ -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): 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}**`,
@@ -220,7 +239,11 @@ export function buildRouterHelp(current: string): string {
220
239
  "- `/router enforce <off|advisory|enforced>` — set hard-block enforcement (persisted)",
221
240
  "- `/router overrides` — show the global + project override file paths and precedence",
222
241
  "- `/router models [provider]` — list valid model ids from your configured providers",
242
+ ...(options.stats === true
243
+ ? ["- `/router stats [--since <ISO>]` — routing statistics from the decision log and outcome store (same table as `npm run routing:stats` (in a clone))"]
244
+ : []),
223
245
  "- `/tiers`, `/preset`, `/budget`, `/bypass`, `/annotate-plan`",
246
+ ...(roleLines.length > 0 ? ["", ...roleLines] : []),
224
247
  ].join("\n");
225
248
  }
226
249
 
@@ -1,4 +1,7 @@
1
1
  import type { PluginInput } from "@opencode-ai/plugin";
2
+ import type { RunnerCatalogModel } from "../escalate/resume";
3
+ import type { CatalogModel, Ingest } from "../routing/outcomes/ingest";
4
+ import type { HostGenerate } from "../routing/classify/types";
2
5
 
3
6
  /** Marks the legacy tool.execute.before output bag when verification starts for
4
7
  * that task call. V1 hosts read only output.args, so this symbol is invisible. */
@@ -16,8 +19,29 @@ export interface ChildSessionRequest {
16
19
  system?: string;
17
20
  prompt: string;
18
21
  signal?: AbortSignal;
22
+ /**
23
+ * Resume this existing child (the host `subagent` call's `sessionID`, D11) instead of creating one: the
24
+ * history is kept, `agent`/`model` switch it when they differ. The runner checks that it is a child of the
25
+ * calling session first and rejects with {@link ResumeRejectedError} otherwise, before anything is sent.
26
+ * `onCreated(resumeSessionID)` runs for a resumed child too (after that check, before the host runs it), so
27
+ * one callback registers every child the request runs on; `cwd` is not applied again.
28
+ */
29
+ resumeSessionID?: string;
19
30
  /** Runs before the child can start its first model request. */
20
31
  onCreated(sessionID: string): Promise<void>;
32
+ /** Runs once when progress or the completed result confirms which child the host actually ran. */
33
+ onConfirmed?(sessionID: string): Promise<void>;
34
+ }
35
+
36
+ /**
37
+ * A resume that was refused before the child ran: the session is gone, or it is not a child of the calling
38
+ * session. Nothing was sent, so the caller may start a fresh child for the same attempt (D11 fallback).
39
+ */
40
+ export class ResumeRejectedError extends Error {
41
+ constructor(readonly sessionID: string, reason: string) {
42
+ super(`[model-router] cannot resume child session ${sessionID}: ${reason}`);
43
+ this.name = "ResumeRejectedError";
44
+ }
21
45
  }
22
46
 
23
47
  export interface ChildSessionRunner {
@@ -29,4 +53,23 @@ export type RouterPluginInput = PluginInput & {
29
53
  routerChildRunner?: ChildSessionRunner;
30
54
  /** Set only by src/v2.ts; absent = v1 host (A3). */
31
55
  routerHost?: "v2";
56
+ /**
57
+ * Set only by src/v2.ts: the host model catalog (`ctx.model.list`): prices child steps (A1) and, with its `variants`
58
+ * and `limit`, lets the delegate ladder validate variants and size resumes (D10/D11, Phase 2.3).
59
+ */
60
+ routerCatalog?: () => Promise<readonly (CatalogModel & RunnerCatalogModel)[]>;
61
+ /**
62
+ * Set only by src/v2.ts: the host's agents (`ctx.agent.list().data`, Agent.Info records). The cost doctor (Phase 2.4) reads which
63
+ * agents have a model of their own (title, summary, the role agents) and which tier agents the host offers.
64
+ */
65
+ routerAgents?: () => Promise<readonly unknown[]>;
66
+ /**
67
+ * Set only by src/v2.ts: the host's synthetic transcript entry (`ctx.session.synthetic`, `resume: false`), the call the adapter already uses
68
+ * for its config-reload and narration notices. The cost doctor's notice goes through it, never into the user's message.
69
+ */
70
+ routerSynthetic?: (input: { sessionID: string; text: string; description: string }) => Promise<void>;
71
+ /** Set only by src/v2.ts: the host `generate` (the `host` classifier backend of `/annotate-plan`, A4); absent when the host has none. */
72
+ routerGenerate?: HostGenerate;
73
+ /** Set only by src/v2.ts: receives this plugin instance's telemetry ingest, whose step events the v2 adapter feeds (QA-2.1-7). */
74
+ routerOnIngest?: (ingest: Ingest) => void;
32
75
  };