opencode-model-router 2.1.0 → 2.3.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 (55) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +44 -5
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +4 -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 +174 -47
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +484 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/index.ts +557 -61
  13. package/src/router/build-info.ts +151 -0
  14. package/src/router/config.ts +1691 -67
  15. package/src/router/protocol.ts +47 -0
  16. package/src/router/sessions.ts +441 -9
  17. package/src/routing/advisor/findings.ts +706 -0
  18. package/src/routing/advisor/index.ts +606 -0
  19. package/src/routing/classify/backends/host.ts +163 -0
  20. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  21. package/src/routing/classify/backends/shared.ts +741 -0
  22. package/src/routing/classify/backends/typesafe.ts +315 -0
  23. package/src/routing/classify/fences.ts +96 -0
  24. package/src/routing/classify/index.ts +576 -0
  25. package/src/routing/classify/route-line.ts +298 -0
  26. package/src/routing/classify/rules.ts +607 -0
  27. package/src/routing/classify/scrub.ts +214 -0
  28. package/src/routing/classify/state.ts +148 -0
  29. package/src/routing/classify/text.ts +20 -0
  30. package/src/routing/classify/types.ts +1280 -0
  31. package/src/routing/commands/annotate-plan.ts +652 -0
  32. package/src/routing/commands/stats.ts +131 -0
  33. package/src/routing/commands/v1-roles.ts +64 -0
  34. package/src/routing/engine/index.ts +32 -0
  35. package/src/routing/engine/kernel.ts +597 -0
  36. package/src/routing/engine/ladders.ts +561 -0
  37. package/src/routing/engine/plan.ts +404 -0
  38. package/src/routing/engine/protocol-line.ts +133 -0
  39. package/src/routing/engine/simulate.ts +167 -0
  40. package/src/routing/engine/types.ts +270 -0
  41. package/src/routing/file-lock.ts +53 -0
  42. package/src/routing/outcomes/beta.ts +141 -0
  43. package/src/routing/outcomes/cost.ts +313 -0
  44. package/src/routing/outcomes/index.ts +172 -0
  45. package/src/routing/outcomes/ingest.ts +812 -0
  46. package/src/routing/outcomes/persist.ts +1058 -0
  47. package/src/routing/outcomes/stats.ts +602 -0
  48. package/src/routing/outcomes/store.ts +653 -0
  49. package/src/routing/outcomes/types.ts +954 -0
  50. package/src/routing/wire/dispatch.ts +799 -0
  51. package/src/routing/wire/hint.ts +208 -0
  52. package/src/routing/wire/host-info.ts +256 -0
  53. package/src/routing/wire/runtime.ts +259 -0
  54. package/src/v2.ts +15 -1
  55. package/tiers.json +43 -0
package/CHANGELOG.md CHANGED
@@ -7,6 +7,92 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.3.0] - 2026-10-07
11
+
12
+ ### Added
13
+
14
+ - **Cost-aware routing engine (#74), OpenCode v2, opt-in.** A `routing` block
15
+ turns on a decision engine that picks the `(agent, model#variant, retry path)`
16
+ of each dispatch from an expected-cost formula fed by typed task facts decided
17
+ in code and a scoreboard of verified outcomes per `(task class × agent ×
18
+ model#variant)`. With no `routing` block the plugin behaves exactly as 2.2.0.
19
+ Suggested in #73 by @javizuurc (giving custom agents and the context of the work
20
+ to a routing step that decides who does it); implemented from scratch with the
21
+ decision kept in code, and TypeSafe supported as an optional classifier backend.
22
+ - `routing.engine`: `static` (default), `shadow` (decide and record), `advise`
23
+ (generated `R:` line and a stable one-line `Route hint`, advise only) and `enforce` (no hint; reroute under
24
+ a strict margin, an evidence gate of 5 effective (decayed) outcomes on the
25
+ candidate's own key, permission and
26
+ floor rules, and the D9 never-down gate: high-risk work without detection
27
+ cannot run below the pick's capability rank or at lower effort on the same
28
+ model; detection uses the weaker route-line/acceptance claim. A dispatch
29
+ carrying `[route … pin]` is never rerouted).
30
+ - A task classifier (rules, an optional first-line `[route …]` directive, and
31
+ optional `host`, `openai-compatible` and `typesafe` backends; `host` is
32
+ experimental). Backends see a bounded, scrubbed excerpt only, never a task
33
+ that names a credential, and are configurable only from the global override.
34
+ - An outcome store and a decision log under the trajectory directory, with
35
+ cost units that never mix USD and `costRatio` and a zero cost for an unpriced
36
+ model treated as unknown.
37
+ - Same-session variant steps: a failed verification retries on the same
38
+ model's next variant, resuming the child session, before the ladder pays for
39
+ a bigger model (`enforcement.escalate.variantSteps`, `tiers.<t>.candidates`,
40
+ `routing.sessionReuse`).
41
+ - Native agents (`explore`, `general`) as default candidates on v2
42
+ (`routing.roles`; `roles: {}` disables them). The plugin never raises
43
+ `subagent_depth`.
44
+ - A cost doctor: findings in `/router` (title model, unpriced and missing
45
+ models, impossible variants, subscription pricing) and at most one notice,
46
+ delivered as a synthetic transcript entry, throttled per project.
47
+ `variant-effort` reports an empty variant ladder when a tier also sets effort
48
+ options; it fires on bundled `hybrid-2`/`anthropic` once a `routing` block
49
+ exists (unless variant steps are explicitly off). `effort-variant-mismatch`
50
+ reports different `variant` and `effort` values with a live engine and variant
51
+ steps off: the wire effort and learned outcome key would differ.
52
+ Throttle/pending state is stored as `advisor-notice.<hash>.json` with an
53
+ `advisor-notice.<hash>.lock` file in the outcomes directory, per project.
54
+ - `/router stats` and `npm run routing:stats` (the script needs Node 22.18 / 23.6 or
55
+ newer and is not part of the package); `/annotate-plan` emits `[route …]`
56
+ lines and pins `[tier:heavy]` steps when the engine is live; the bare
57
+ `/router` view prints `router: engine=<mode> build=<version>+<sha7>`.
58
+ It also prints `router: config notice:` lines for findings from the last
59
+ config load. A18: `routing.outcomes.path`, like classifier backend settings,
60
+ is accepted only from bundled config or the global override; project-local
61
+ values are dropped with a one-time warning.
62
+ - Documentation: `docs/ROUTING_ENGINE.md`, `docs/adr/0005-cost-aware-routing-engine.md`
63
+ and the `routing` section of `docs/CONFIG_REFERENCE.md`.
64
+
65
+ ### Changed
66
+
67
+ - With a `routing` block, `enforcement.escalate.variantSteps` defaults to `auto`
68
+ on OpenCode v2 (without one it stays `none`, so the 2.2.0 ladder is
69
+ unchanged); `enforcement.escalate.effortBumpMax` also caps the variant ladders
70
+ read from the model catalog.
71
+ - OpenCode v1: the `routing` block is validated and `routing.engine` is forced
72
+ to `static` with one log line; setting `routing.roles` explicitly adds a
73
+ prose-only destination suffix to the `R:` line.
74
+
75
+ ## [2.2.0] - 2026-10-05
76
+
77
+ ### Added
78
+
79
+ - Config hot reload: the router re-reads `tiers.json`, the global and project
80
+ overrides files and the state file when their mtime/ctime/size fingerprint changes,
81
+ with no restart. A source that turns invalid or unreachable keeps the last valid
82
+ config (the reason is surfaced by `getConfigReloadError()`); only ENOENT/ENOTDIR
83
+ count as a removed file. `/router-reload` forces a reload, and on OpenCode 2 the
84
+ agent and command registry is refreshed on reload and after `/preset`.
85
+ - `hybrid-2` preset: `@fast` → `openai/gpt-6-luna-fast` (medium), `@medium` →
86
+ `anthropic/claude-sonnet-5-5` (xhigh), `@heavy` → `anthropic/claude-opus-5-5`
87
+ (xhigh).
88
+
89
+ ### Fixed
90
+
91
+ - Project overrides are found again on opencode v2 service mode (#70): the override
92
+ lookup and the config cache are now keyed by the host-provided project directory
93
+ instead of `process.cwd()` (which the v2 server moves to `$HOME`), so several
94
+ projects in one process each keep their own config, reload state and error.
95
+
10
96
  ## [2.1.0] - 2026-10-05
11
97
 
12
98
  Observations by @MetalbolicX in opencode-smart-router (#17); implementation written from scratch.
package/README.md CHANGED
@@ -35,7 +35,7 @@ Every tier carries its `costRatio` (fast=1x, medium=5x, heavy=20x) injected into
35
35
  If the orchestrator is already running on Opus, the rule `self∈opus→never→@heavy` fires — it does the heavy work itself rather than delegating to another Opus instance.
36
36
 
37
37
  **Multi-provider support with automatic fallback.**
38
- Seven presets out of the box: Anthropic, OpenAI, GitHub Copilot, Google, hybrid, fable-effort, and Zai (GLM). Switch with `/preset`. If a provider fails, the fallback chain tries the next one automatically.
38
+ Eight presets out of the box: Anthropic, OpenAI, GitHub Copilot, Google, hybrid, hybrid-2, fable-effort, and Zai (GLM). Switch with `/preset`. If a provider fails, the fallback chain tries the next one automatically.
39
39
 
40
40
  **Plan annotation for long tasks.**
41
41
  `/annotate-plan` reads a markdown plan and tags each step with `[tier:fast]`, `[tier:medium]`, or `[tier:heavy]` — removing all routing ambiguity from multi-step workflows.
@@ -415,7 +415,7 @@ For an npm install, `tiers.json` is **inside the cached package directory**, not
415
415
 
416
416
  ### Presets
417
417
 
418
- The plugin ships with seven presets (switch with `/preset <name>`):
418
+ The plugin ships with eight presets (switch with `/preset <name>`):
419
419
 
420
420
  **anthropic** (default):
421
421
  | Tier | Model | Cost ratio |
@@ -452,6 +452,13 @@ The plugin ships with seven presets (switch with `/preset <name>`):
452
452
  | @medium | `openai/gpt-6-astra-fast` (high) | 5x |
453
453
  | @heavy | `anthropic/claude-opus-5-5` (variant/effort: xhigh) | 20x |
454
454
 
455
+ **hybrid-2** — OpenAI for exploration, Anthropic for implementation and heavy analysis:
456
+ | Tier | Model | Cost ratio |
457
+ |------|-------|-----------|
458
+ | @fast | `openai/gpt-6-luna-fast` (medium) | 1x |
459
+ | @medium | `anthropic/claude-sonnet-5-5` (variant/effort: xhigh) | 5x |
460
+ | @heavy | `anthropic/claude-opus-5-5` (variant/effort: xhigh) | 20x |
461
+
455
462
  **fable-effort** — one model, three reasoning depths (see [per-tier `effort`](#per-tier-effort)):
456
463
  | Tier | Model | Effort | Cost ratio |
457
464
  |------|-------|--------|-----------|
@@ -1068,11 +1075,40 @@ Full field notes are in [docs/CONFIG_REFERENCE.md](docs/CONFIG_REFERENCE.md).
1068
1075
  - `docs/ENFORCEMENT.md` — architecture, hook wiring, session lifecycle
1069
1076
  - `docs/VERIFICATION.md` — DoD schema, deterministic checks, grader dispatch
1070
1077
  - `docs/ESCALATION.md` — escalation ladder configuration and cost ceilings
1071
- - `docs/CONFIG_REFERENCE.md` — full `enforcement` block schema
1078
+ - `docs/CONFIG_REFERENCE.md` — full `enforcement` and `routing` block schema
1072
1079
  - `docs/ENFORCEMENT_PRESETS.md` — ready-to-paste enforcement presets
1080
+ - `docs/ROUTING_ENGINE.md` — the cost-aware routing engine: modes, formula, classifier backends, session-aware ladder, cost doctor, privacy
1081
+ - `docs/adr/0005-cost-aware-routing-engine.md` — the decisions behind the routing engine
1073
1082
 
1074
1083
  > 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.
1075
1084
 
1085
+ ## Cost-aware routing (opt-in, OpenCode v2)
1086
+
1087
+ 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`.
1088
+
1089
+ | `routing.engine` | What happens |
1090
+ |---|---|
1091
+ | `static` (default) | Nothing is decided or recorded; the protocol text and `R:` line are unchanged. |
1092
+ | `shadow` | Every dispatch is decided and logged; nothing about it changes. |
1093
+ | `advise` | As `shadow`, and the orchestrator also receives the generated `R:` line and a one-line `Route hint`; it still decides. |
1094
+ | `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. |
1095
+
1096
+ 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`:
1097
+
1098
+ ```jsonc
1099
+ { "routing": { "engine": "shadow" } }
1100
+ ```
1101
+
1102
+ What else ships with it:
1103
+
1104
+ - **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.
1105
+ - **Native agents as candidates.** `explore` and `general` can be chosen for `search`, `implement`, `debug` and `review` work (`routing.roles`; `roles: {}` turns this off).
1106
+ - **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.
1107
+ - **Observability.** A decision log and an outcome store under the trajectory directory, `/router stats`, and `npm run routing:stats` in a clone.
1108
+ - **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
+
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).
1111
+
1076
1112
  ## Commands
1077
1113
 
1078
1114
  | Command | Description |
@@ -1082,11 +1118,12 @@ Full field notes are in [docs/CONFIG_REFERENCE.md](docs/CONFIG_REFERENCE.md).
1082
1118
  | `/preset <name>` | Switch preset (e.g., `/preset openai`) |
1083
1119
  | `/budget` | Show available modes and which is active |
1084
1120
  | `/budget <mode>` | Switch routing mode (`normal`, `budget`, `quality`, `deep`) |
1085
- | `/annotate-plan [path]` | Annotate a plan file with `[tier:X]` tags for each step |
1121
+ | `/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) |
1086
1122
  | `/router overrides` | Show the global + project override file paths and merge precedence |
1087
1123
  | `/router models [provider]` | List valid model ids from your configured providers (with defaults and deprecated flags) |
1088
1124
  | `/router enforce <off\|advisory\|enforced>` | Set delegation-enforcement mode (persisted) |
1089
- | `/router` | With no subcommand — or an unrecognized one — prints the `/router` help and the current enforcement mode |
1125
+ | `/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. |
1126
+ | `/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 |
1090
1127
  | `/bypass [on\|off]` | Toggle the router off/on for the session |
1091
1128
 
1092
1129
  ## Plan annotation
@@ -1111,6 +1148,8 @@ After `/annotate-plan`:
1111
1148
  4. [tier:heavy] Design a token bucket algorithm for advanced rate limiting
1112
1149
  ```
1113
1150
 
1151
+ 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).
1152
+
1114
1153
  ## Token overhead
1115
1154
 
1116
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "2.1.0",
3
+ "version": "2.3.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",
@@ -211,7 +211,7 @@ export function buildOverridesOutput(v: OverridesView): string {
211
211
  }
212
212
 
213
213
  /** Bare `/router`. */
214
- export function buildRouterHelp(current: string): string {
214
+ export function buildRouterHelp(current: string, options: { stats?: boolean } = {}): string {
215
215
  return [
216
216
  `# Model Router`,
217
217
  `Enforcement: **${current}**`,
@@ -220,6 +220,9 @@ export function buildRouterHelp(current: string): string {
220
220
  "- `/router enforce <off|advisory|enforced>` — set hard-block enforcement (persisted)",
221
221
  "- `/router overrides` — show the global + project override file paths and precedence",
222
222
  "- `/router models [provider]` — list valid model ids from your configured providers",
223
+ ...(options.stats === true
224
+ ? ["- `/router stats [--since <ISO>]` — routing statistics from the decision log and outcome store (same table as `npm run routing:stats` (in a clone))"]
225
+ : []),
223
226
  "- `/tiers`, `/preset`, `/budget`, `/bypass`, `/annotate-plan`",
224
227
  ].join("\n");
225
228
  }
@@ -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
  };
@@ -2,10 +2,13 @@ import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import type { Plugin } from "@opencode/plugin";
3
3
  import type { ToolContext } from "@opencode/plugin/promise/tool";
4
4
  import type { SessionContext } from "@opencode/plugin/promise/session";
5
- import type { ChildSessionRunner } from "./child-session";
5
+ import { ResumeRejectedError, type ChildSessionRunner } from "./child-session";
6
+ import { markRunnerDispatch, runnerDescription } from "../router/sessions";
6
7
 
7
8
  export const V2_GRADER_AGENT = "model-router-grader";
8
9
  const RETAINED_CONTEXT_LIMIT = 500;
10
+ /** How long a delegation waits for the host to remove a child it started by mistake before it reports the error. */
11
+ export const STRAY_CLEANUP_TIMEOUT_MS = 2_000;
9
12
 
10
13
  /** The small v1 client surface still used by the shared hooks. */
11
14
  export function createV2Runtime(ctx: Plugin.Context) {
@@ -45,7 +48,18 @@ export function createV2Runtime(ctx: Plugin.Context) {
45
48
  name: provider.name,
46
49
  models: Object.fromEntries(models.data
47
50
  .filter(model => model.providerID === provider.id && model.enabled)
48
- .map(model => [model.id, { id: model.id, status: model.status }])),
51
+ // `id` and `status` are what the v1 shape had; the rest lets the cost doctor (Phase 2.4) read the SAME call instead of a second
52
+ // `model.list` (QA-2.4-3). v1 consumers (`normalizeCatalog`) ignore the extra fields.
53
+ .map(model => [model.id, {
54
+ id: model.id,
55
+ status: model.status,
56
+ enabled: model.enabled,
57
+ family: model.family,
58
+ capabilities: model.capabilities,
59
+ cost: model.cost,
60
+ variants: model.variants,
61
+ limit: model.limit,
62
+ }])),
49
63
  })),
50
64
  default: defaultModel.data
51
65
  ? { [defaultModel.data.providerID]: defaultModel.data.id }
@@ -57,6 +71,28 @@ export function createV2Runtime(ctx: Plugin.Context) {
57
71
  // v2 has no app.log endpoint. createPluginLogger uses its console fallback.
58
72
  };
59
73
 
74
+ /**
75
+ * Stop and remove a child the host started that no caller knows (QA-2.3-5). Bounded (QA-2.3-R2-3): resolves with ""
76
+ * when it is gone, otherwise with a sentence for the error (a failure, or a removal still running after
77
+ * STRAY_CLEANUP_TIMEOUT_MS, which then finishes or fails in the background without anyone waiting for it). Never rejects.
78
+ */
79
+ const removeStray = async (sessionID: string): Promise<string> => {
80
+ const removal = childRunner.dispose(sessionID).then(
81
+ () => "",
82
+ (error: unknown) => `; removing it failed (${error instanceof Error ? error.message : String(error)})`,
83
+ );
84
+ let timer: ReturnType<typeof setTimeout> | undefined;
85
+ const timeout = new Promise<string>((resolve) => {
86
+ timer = setTimeout(() => resolve(`; removing it did not finish within ${STRAY_CLEANUP_TIMEOUT_MS} ms and may still be running`), STRAY_CLEANUP_TIMEOUT_MS);
87
+ if (typeof timer === "object" && typeof timer.unref === "function") timer.unref();
88
+ });
89
+ try {
90
+ return await Promise.race([removal, timeout]);
91
+ } finally {
92
+ clearTimeout(timer);
93
+ }
94
+ };
95
+
60
96
  const childRunner: ChildSessionRunner = {
61
97
  async run(request) {
62
98
  lifetime.signal.throwIfAborted();
@@ -82,14 +118,54 @@ export function createV2Runtime(ctx: Plugin.Context) {
82
118
  ...(request.signal ? [request.signal] : []),
83
119
  ]);
84
120
  signal.throwIfAborted();
85
- let childID: string | undefined;
121
+ const resumeID = request.resumeSessionID;
122
+ if (resumeID !== undefined) {
123
+ // The host resumes any session id it is given, so ours checks that the child exists and belongs to the
124
+ // calling session before anything is sent. Whatever the lookup says other than "my child", the caller
125
+ // falls back to a fresh child.
126
+ const parent = scope.context.sessionID;
127
+ let info: { parentID?: unknown } | undefined;
128
+ try {
129
+ info = await ctx.session.get({ sessionID: resumeID }, { signal });
130
+ } catch (error) {
131
+ signal.throwIfAborted();
132
+ throw new ResumeRejectedError(resumeID, `session lookup failed (${error instanceof Error ? error.message : String(error)})`);
133
+ }
134
+ if (info?.parentID !== parent) throw new ResumeRejectedError(resumeID, `it is not a child of session ${parent}`);
135
+ }
136
+ // A resumed child is known up front: the host does not create one, and a progress event for another id is an error.
137
+ let childID: string | undefined = resumeID;
138
+ let confirmed = false;
139
+ const confirmChild = async (sessionID: string): Promise<void> => {
140
+ if (confirmed) return;
141
+ confirmed = true;
142
+ await request.onConfirmed?.(sessionID);
143
+ };
144
+ /** Set when the host answered a resume with another child; thrown from `run` whatever the host made of the progress error. */
145
+ let strayResume: ResumeRejectedError | undefined;
146
+ if (resumeID !== undefined) {
147
+ activeChildren.set(resumeID, controller);
148
+ if (request.system) childSystems.set(resumeID, request.system);
149
+ }
86
150
  const model = request.model;
151
+ // 2.2 / 2.3 single writer (QA-2.2-1): announce the native call to the 2.2 dispatch router, which must leave it alone
152
+ // (this runner has chosen the agent and model#variant, writes the attempt's row and registers the child itself). Measured on 2.0.22
153
+ // (Phase 3.2, H4): the host runs no plugin tool hook for a call made through `ctx.tool.list()`, so the router never sees it and the
154
+ // mark is withdrawn below unconsumed; it is defensive, for a host that does hook such calls.
155
+ let withdrawMark: (() => void) | undefined;
87
156
  try {
157
+ // A resumed child is registered here, before the host can run it, exactly like a created one is in `progress`.
158
+ if (resumeID !== undefined) {
159
+ await request.onCreated(resumeID);
160
+ signal.throwIfAborted();
161
+ }
162
+ withdrawMark = markRunnerDispatch({ parentSessionID: toolContext.sessionID, agent: request.agent ?? V2_GRADER_AGENT, prompt: request.prompt });
88
163
  const result = await native.execute({
89
164
  agent: request.agent ?? V2_GRADER_AGENT,
90
- description: request.agent ? `Router ${request.agent} delegation` : "Router result verification",
165
+ description: runnerDescription(request.agent),
91
166
  prompt: request.prompt,
92
167
  ...(model ? { model: `${model.providerID}/${model.modelID}${model.variant ? `#${model.variant}` : ""}` } : {}),
168
+ ...(resumeID !== undefined ? { sessionID: resumeID } : {}),
93
169
  background: false,
94
170
  }, {
95
171
  ...toolContext,
@@ -97,7 +173,22 @@ export function createV2Runtime(ctx: Plugin.Context) {
97
173
  async progress(metadata) {
98
174
  const sessionID = metadata.sessionID;
99
175
  if (typeof sessionID === "string" && sessionID !== childID) {
100
- if (childID) throw new Error("[model-router] native subagent changed its child session ID");
176
+ if (childID) {
177
+ // The host started another child than the one this call is about (a resume that did not resume, or a
178
+ // second child): no caller knows its id, so it is stopped and removed here before the error, or it
179
+ // would live until the host is restarted (QA-2.3-5). The original child is interrupted below.
180
+ // The removal is bounded (QA-2.3-R2-3): a host that hangs on it must not hang the delegation, and the error
181
+ // says so instead of hiding it.
182
+ const cleanup = await removeStray(sessionID);
183
+ if (resumeID !== undefined && childID === resumeID) {
184
+ // A resume that did not resume: the caller starts a fresh child for the same attempt (D11 fallback)
185
+ // instead of counting a failed attempt. Kept aside so the host's own wrapping of a progress error
186
+ // cannot hide the type.
187
+ strayResume = new ResumeRejectedError(resumeID, `the host started another child (${sessionID}) instead${cleanup}`);
188
+ throw strayResume;
189
+ }
190
+ throw new Error(`[model-router] native subagent changed its child session ID (${childID} -> ${sessionID}${cleanup})`);
191
+ }
101
192
  childID = sessionID;
102
193
  activeChildren.set(sessionID, controller);
103
194
  if (request.system) childSystems.set(sessionID, request.system);
@@ -107,6 +198,7 @@ export function createV2Runtime(ctx: Plugin.Context) {
107
198
  if (request.cwd) await ctx.session.move({ sessionID, directory: request.cwd }, { signal });
108
199
  signal.throwIfAborted();
109
200
  }
201
+ if (typeof sessionID === "string" && sessionID === childID) await confirmChild(sessionID);
110
202
  // V2 rejects progress outside a running call. Deferred/queued graders
111
203
  // retain settled parent contexts; also tolerate settlement during progress.
112
204
  if (scope.active) {
@@ -115,19 +207,27 @@ export function createV2Runtime(ctx: Plugin.Context) {
115
207
  }
116
208
  },
117
209
  });
118
- signal.throwIfAborted();
119
210
  const output = result.output as { sessionID?: unknown; status?: unknown; output?: unknown } | undefined;
211
+ // A named child confirms an attempted resume even when its result failed or was aborted.
212
+ if (childID && output?.sessionID === childID) await confirmChild(childID);
213
+ signal.throwIfAborted();
214
+ if (resumeID !== undefined && typeof output?.sessionID === "string" && output.sessionID !== resumeID) {
215
+ const cleanup = await removeStray(output.sessionID);
216
+ throw new ResumeRejectedError(resumeID, `the host started another child (${output.sessionID}) instead${cleanup}`);
217
+ }
120
218
  if (!childID || output?.sessionID !== childID || output.status !== "completed" || typeof output.output !== "string") {
121
219
  throw new Error("[model-router] native subagent did not return a completed child result; verification cannot use a pending result");
122
220
  }
221
+ await confirmChild(childID);
123
222
  return { sessionID: childID, text: output.output };
124
223
  } catch (error) {
125
224
  controller.abort();
126
225
  if (childID) {
127
226
  try { await ctx.session.interrupt({ sessionID: childID }); } catch { /* keep the original dispatch failure */ }
128
227
  }
129
- throw error;
228
+ throw strayResume ?? error;
130
229
  } finally {
230
+ withdrawMark?.(); // a hook that never fired must not leave a mark behind
131
231
  if (childID) {
132
232
  childSystems.delete(childID);
133
233
  activeChildren.delete(childID);