opencode-model-router 1.4.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +134 -12
- package/package.json +1 -1
- package/src/commands/output.ts +236 -0
- package/src/guard/enforce.ts +14 -1
- package/src/guard/guards.ts +26 -0
- package/src/guard/store.ts +46 -3
- package/src/index.ts +272 -321
- package/src/router/agent-options.ts +118 -0
- package/src/router/config.ts +555 -46
- package/src/router/idle-sweep.ts +35 -0
- package/src/router/jsonc.ts +92 -0
- package/src/router/prompts.ts +72 -0
- package/src/router/protocol.ts +1 -1
- package/src/router/sessions.ts +159 -22
- package/src/telemetry/trajectory.ts +48 -1
- package/src/verify/checker.ts +47 -1
- package/src/verify/deterministic.ts +13 -5
- package/src/verify/dispatch.ts +27 -2
- package/src/verify/gate.ts +25 -1
- package/src/verify/paths.ts +29 -0
- package/src/verify/timeout.ts +93 -0
- package/src/verify/wiring.ts +267 -0
- package/tiers.json +79 -6
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> **Use the cheapest model that can do the job. Automatically.**
|
|
4
4
|
|
|
5
|
-
An [OpenCode](https://opencode.ai) plugin that routes every coding task to the right-priced AI tier — automatically, on every message, with
|
|
5
|
+
An [OpenCode](https://opencode.ai) plugin that routes every coding task to the right-priced AI tier — automatically, on every message, with 3,089–4,659 characters of system-prompt overhead depending on the orchestrator and enforcement mode.
|
|
6
6
|
|
|
7
7
|
## Why it's different
|
|
8
8
|
|
|
@@ -12,7 +12,7 @@ Most AI coding tools give you one model for everything. You pay Opus prices to r
|
|
|
12
12
|
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.
|
|
13
13
|
|
|
14
14
|
**Inject a compressed, LLM-optimized routing protocol.**
|
|
15
|
-
Instead of duplicated prose, the plugin injects a dense, machine-readable routing protocol. The protocol itself is
|
|
15
|
+
Instead of duplicated prose, the plugin injects a dense, machine-readable routing protocol. The protocol itself is 3,089 characters; a Claude orchestrator receives 3,861 characters after its authority prefix (roughly 965–1,075 tokens at 3.6–4.0 characters per token). Every message, every session.
|
|
16
16
|
|
|
17
17
|
**Match task to tier using a configurable taxonomy.**
|
|
18
18
|
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.
|
|
@@ -65,7 +65,7 @@ opencode-model-router injects a **delegation protocol** into the system prompt t
|
|
|
65
65
|
4. **Never over-qualify** — use the cheapest tier that can reliably handle the task
|
|
66
66
|
5. **Fallback** across providers when one fails
|
|
67
67
|
|
|
68
|
-
All of this adds
|
|
68
|
+
All of this adds 3,089 characters for a non-Claude orchestrator or 3,861 characters for a Claude orchestrator (roughly 770–1,075 tokens at 3.6–4.0 characters per token).
|
|
69
69
|
|
|
70
70
|
## Cost simulation
|
|
71
71
|
|
|
@@ -114,7 +114,7 @@ Task distribution: 18 exploration (60%), 10 implementation (33%), 2 architecture
|
|
|
114
114
|
|
|
115
115
|
## How it works
|
|
116
116
|
|
|
117
|
-
On every message, the plugin injects a
|
|
117
|
+
On every message, the plugin injects a 3,089-character routing protocol. A Claude orchestrator receives 3,861 characters after its authority prefix (roughly 965–1,075 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.
|
|
118
118
|
|
|
119
119
|
What the orchestrator sees (Anthropic preset, normal mode):
|
|
120
120
|
|
|
@@ -166,7 +166,7 @@ With router → split:
|
|
|
166
166
|
| Cross-provider fallback | ✅ | ❌ | ❌ | ❌ | ❌ |
|
|
167
167
|
| Cost ratio awareness | ✅ | ❌ | ❌ | ❌ | ❌ |
|
|
168
168
|
| Plan annotation with tiers | ✅ | ❌ | ❌ | ❌ | ❌ |
|
|
169
|
-
| Measured prompt overhead:
|
|
169
|
+
| Measured prompt overhead: 3,089–4,659 chars | ✅ | — | ❌ | ❌ | ❌ |
|
|
170
170
|
|
|
171
171
|
**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.
|
|
172
172
|
|
|
@@ -241,9 +241,72 @@ In `~/.config/opencode/opencode.json`:
|
|
|
241
241
|
|
|
242
242
|
## Configuration
|
|
243
243
|
|
|
244
|
-
|
|
244
|
+
The full default configuration lives in `tiers.json` at the plugin root. There are two ways to customize it.
|
|
245
245
|
|
|
246
|
-
|
|
246
|
+
### Recommended: overrides files (survive updates)
|
|
247
|
+
|
|
248
|
+
Anything in an overrides file is **deep-merged** over the bundled `tiers.json` on load — you only specify the keys you want to change; everything else falls back to the defaults. These files live outside the cache dir, so they are **not** wiped when the plugin updates. They're `.jsonc`, so `//` and `/* */` comments and trailing commas are allowed.
|
|
249
|
+
|
|
250
|
+
There are two layers, applied lowest→highest priority:
|
|
251
|
+
|
|
252
|
+
| Layer | Path | Scope |
|
|
253
|
+
|-------|------|-------|
|
|
254
|
+
| **Global** | `~/.config/opencode/opencode-model-router.overrides.jsonc` | Your personal defaults across all projects |
|
|
255
|
+
| **Project** | `<project>/.opencode/opencode-model-router.overrides.jsonc` | Per-project; commit it to share one routing config with your team |
|
|
256
|
+
|
|
257
|
+
The project file deep-merges over (and wins against) the global file, which in turn merges over the bundled defaults. So you can keep personal preferences globally while a committed project file unifies routing for everyone on the repo. The project file is found by searching upward from the working directory to the repo root (the nearest ancestor containing `.git`), so it is picked up even when you launch opencode from a subdirectory.
|
|
258
|
+
|
|
259
|
+
```json
|
|
260
|
+
{
|
|
261
|
+
"presets": {
|
|
262
|
+
"github-copilot": {
|
|
263
|
+
"heavy": { "model": "github-copilot/claude-opus-4.8", "variant": "high" }
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
The example above changes only the `@heavy` model/variant for the `github-copilot` preset; every other tier, preset, and setting keeps its bundled value. You can also override `costRatio`, `tierCaps`, `rules`, `modes`, `enforcement`, add an entirely new preset, etc. — any top-level key from `tiers.json`.
|
|
270
|
+
|
|
271
|
+
Run `/router overrides` to see both file paths, whether each exists, and the precedence order.
|
|
272
|
+
|
|
273
|
+
Merge semantics: objects merge recursively; arrays and scalars are replaced wholesale (so an overridden `rules`/`whenToUse` list *replaces* the default, it does not append). If a file is missing, malformed, or produces an invalid config, the plugin logs a `[model-router]` warning and drops just that layer (keeping the others) — a typo in one file can never break startup or discard a valid file.
|
|
274
|
+
|
|
275
|
+
#### Defining a whole new preset
|
|
276
|
+
|
|
277
|
+
An overrides file can add a brand-new preset, not just tweak the bundled ones. `model` is the only required field per tier. `costRatio` and `steps` are optional — when omitted they fall back to the conventional **`1` / `5` / `20`** and **`30` / `50` / `120`** (by tier name, the same values the bundled presets use); `description`/`whenToUse` are display-only.
|
|
278
|
+
|
|
279
|
+
```jsonc
|
|
280
|
+
{
|
|
281
|
+
"presets": {
|
|
282
|
+
"openrouter": {
|
|
283
|
+
"fast": { "model": "openrouter/deepseek/deepseek-v3.2" },
|
|
284
|
+
"medium": { "model": "openrouter/qwen/qwen3-coder", "costRatio": 3, "steps": 60 },
|
|
285
|
+
"heavy": { "model": "openrouter/google/gemini-3-pro", "costRatio": 9, "steps": 140 },
|
|
286
|
+
},
|
|
287
|
+
},
|
|
288
|
+
// make it the active preset (or switch at runtime with `/preset openrouter`)
|
|
289
|
+
"activePreset": "openrouter",
|
|
290
|
+
}
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
`@fast` omits `costRatio`/`steps`, so it gets the defaults (`1` / `30`); `@medium` and `@heavy` set their own to match their real economics. **Set `costRatio` whenever your models' relative costs differ from the default ladder** — it's the price signal the orchestrator uses to pick the cheapest adequate tier. (Routing by *task type* — `@fast`=read-only, `@medium`=implementation, `@heavy`=architecture — comes from the shared `taskPatterns`/`rules`, so it works for any preset automatically.)
|
|
294
|
+
|
|
295
|
+
The effective values, including any defaults, are shown by `/tiers`.
|
|
296
|
+
|
|
297
|
+
Restart opencode after adding a new preset so its tier subagents get registered. (Each model's provider must itself be configured in your `opencode.json`.)
|
|
298
|
+
|
|
299
|
+
> **`activePreset` / `activeMode` / `enforcement.mode` in an override file are _defaults_.** Runtime selections — `/preset`, `/budget`, `/router enforce` — are persisted to the state file (`~/.config/opencode/opencode-model-router.state.json`), which is applied **after** the override files and therefore wins. So the override's `activePreset` takes effect until you switch at runtime; if it ever "isn't taking", it's because a past `/preset` left a value in the state file — run `/preset <name>` again or delete that file. (The state file is machine-written, so the plugin never rewrites your hand-authored, commented override file.)
|
|
300
|
+
|
|
301
|
+
### Advanced: edit the bundled `tiers.json` directly
|
|
302
|
+
|
|
303
|
+
For an npm install, `tiers.json` is **inside the cached package directory**, not your `~/.config/opencode/` folder — typically:
|
|
304
|
+
|
|
305
|
+
```
|
|
306
|
+
~/.cache/opencode/packages/opencode-model-router@latest/node_modules/opencode-model-router/tiers.json
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
> ⚠️ Editing a copy elsewhere (e.g. under your global `npm` `node_modules`) has no effect, and this cached file is **overwritten on each plugin update**. Prefer the overrides file above unless you are developing the plugin from a local clone.
|
|
247
310
|
|
|
248
311
|
### Presets
|
|
249
312
|
|
|
@@ -277,6 +340,37 @@ The plugin ships with four presets (switch with `/preset <name>`):
|
|
|
277
340
|
| @medium | `google/gemini-2.5-pro` | 5x |
|
|
278
341
|
| @heavy | `google/gemini-3-pro-preview` | 20x |
|
|
279
342
|
|
|
343
|
+
**fable-effort** — one model, three reasoning depths (see [per-tier `effort`](#per-tier-effort)):
|
|
344
|
+
| Tier | Model | Effort | Cost ratio |
|
|
345
|
+
|------|-------|--------|-----------|
|
|
346
|
+
| @fast | `anthropic/claude-fable-5` | `low` | 1x |
|
|
347
|
+
| @medium | `anthropic/claude-fable-5` | `high` | 3x |
|
|
348
|
+
| @heavy | `anthropic/claude-fable-5` | `xhigh` | 6x |
|
|
349
|
+
|
|
350
|
+
Because the model string is identical across tiers, escalating a task keeps the prompt
|
|
351
|
+
cache warm. The cost ratios are estimated token-spend multipliers, not price differences.
|
|
352
|
+
|
|
353
|
+
### Per-tier `effort`
|
|
354
|
+
|
|
355
|
+
Any tier may set `effort`: `low`, `medium`, `high`, `xhigh`, or `max`. Precedence,
|
|
356
|
+
highest first:
|
|
357
|
+
|
|
358
|
+
1. `thinking.budgetTokens` (Anthropic) / `reasoning.effort` (OpenAI) — the explicit,
|
|
359
|
+
provider-specific setting always wins, and a one-time warning names the tier.
|
|
360
|
+
2. `effort`.
|
|
361
|
+
|
|
362
|
+
**Unset means unset**: no `effort` (and no `reasoning_effort`) key is registered at all.
|
|
363
|
+
|
|
364
|
+
| Model family | Registered as | Caveats |
|
|
365
|
+
|---|---|---|
|
|
366
|
+
| Anthropic | `options.effort`, incl. `xhigh`/`max` | Requires the `opencode-anthropic-fix` plugin (commit `307aea9`+ for fable/mythos). Non-adaptive Claude models (e.g. haiku) silently strip `effort` at the API layer, and without the plugin a top-level `effort` can break Claude-Code billing fingerprinting. |
|
|
367
|
+
| OpenAI | `options.reasoning_effort` | Supports only `low`/`medium`/`high`; `xhigh` and `max` are downgraded to `high` with a warning. |
|
|
368
|
+
| Other (Google, Copilot, …) | nothing | Dropped with a warning — no known mapping. |
|
|
369
|
+
|
|
370
|
+
An out-of-set value in `tiers.json` fails validation at load; one that arrives any other
|
|
371
|
+
way is ignored with a single warning. Full detail in
|
|
372
|
+
[docs/CONFIG_REFERENCE.md](docs/CONFIG_REFERENCE.md#per-tier-effort).
|
|
373
|
+
|
|
280
374
|
### Routing modes
|
|
281
375
|
|
|
282
376
|
Switch with `/budget <mode>`. Mode is persisted across restarts.
|
|
@@ -380,10 +474,29 @@ Subagents carry a cap on their own read-only tool calls (grep/read/glob/ls) per
|
|
|
380
474
|
The orchestrator can override any subagent's cap per dispatch by including a directive in the `Task` prompt:
|
|
381
475
|
|
|
382
476
|
- `CAP:N` — tighten or loosen to N calls (e.g., `CAP:3` for a focused lookup).
|
|
383
|
-
- `CAP:none` — disable the numeric cap entirely (used in `quality` mode and for `@heavy` in `deep` mode).
|
|
477
|
+
- `CAP:none` — disable the numeric cap entirely (used in `quality` mode and for `@heavy` in `deep` mode). **`CAP:none` is honored only when the dispatch prompt also contains a `reason:` line.** An unjustified `CAP:none` silently falls back to the tier baseline — uncapped work must be justified in the dispatch, not just requested. `CAP:N` is unaffected.
|
|
384
478
|
|
|
385
479
|
Omitting the directive falls back to the tier baseline. Subagents may **exceed** their cap with a 1-line `reason:` in the return (target, not hard block).
|
|
386
480
|
|
|
481
|
+
#### Resumed dispatches
|
|
482
|
+
|
|
483
|
+
A "resume" is a second `chat.message` to a session already tracked at the **same tier** — how an opencode `task_id` resume (re-prompting an existing subagent session instead of spawning a new one) reaches the plugin. On resume:
|
|
484
|
+
|
|
485
|
+
- the **per-dispatch cap resets** (`[cap: 1/8]` again) — the resumed round gets a full budget, and re-reads the `CAP:` directive from the new dispatch text, gate included;
|
|
486
|
+
- the **redundancy map persists** — re-reading a file you already read in the previous round still emits `[⚠ REDUNDANT: … call #1]`;
|
|
487
|
+
- **cumulative usage persists** and is bounded by a ceiling of `cap × 3` (the current dispatch's cap). Exceeding it appends:
|
|
488
|
+
|
|
489
|
+
```
|
|
490
|
+
[cap: 2/3]
|
|
491
|
+
[⚠ CUMULATIVE BUDGET EXCEEDED: 10/9 across 4 dispatches — return now]
|
|
492
|
+
```
|
|
493
|
+
|
|
494
|
+
The ceiling follows the *current* cap, so a tighter resumed cap tightens the ceiling. `CAP:none` has no per-dispatch budget to derive from and therefore no cumulative ceiling. A **retry** (new session, e.g. an escalation to another tier) is not a resume: it gets fresh counters and an empty redundancy map. A session evicted by the idle-TTL sweep also comes back fresh.
|
|
495
|
+
|
|
496
|
+
The same accounting exists at the hard-guard layer: `guard.budget` resets per dispatch, with a cumulative ceiling of `guard.budget × 3` enforced as `cumulative_iteration_cap`.
|
|
497
|
+
|
|
498
|
+
**If you never resume a subagent session, nothing changes** — a first dispatch's cumulative count equals its per-dispatch count, so the ceiling is unreachable and every banner is byte-identical to before.
|
|
499
|
+
|
|
387
500
|
#### Runtime enforcement (subagents only)
|
|
388
501
|
|
|
389
502
|
Prompt-level rules alone are unreliable: many models (including strong ones like Opus 4.7) ignore "please stop at N reads" and loop on reconnaissance for tens of minutes. To address this, the plugin tracks read-only tool calls per subagent session and **appends a banner to every read-only tool result** via the `tool.execute.after` hook. The subagent sees this banner inside the tool's own response text — not as advisory system prompt noise — which makes it very hard to ignore.
|
|
@@ -476,9 +589,11 @@ Each tier (`@fast`, `@medium`, `@heavy`) has a system prompt that describes its
|
|
|
476
589
|
**Resolution order per tier:**
|
|
477
590
|
|
|
478
591
|
1. If the preset's tier defines `"prompt": "..."` inline → use it (per-tier override).
|
|
479
|
-
2. Otherwise → fall back to `tierPrompts[<tierName>]`.
|
|
592
|
+
2. Otherwise → fall back to the default for the tier's **prompt style**: `tierPromptsGoalOriented[<tierName>]` (or the built-in goal-oriented default) when the tier resolves to `goal-oriented`, else `tierPrompts[<tierName>]`.
|
|
480
593
|
3. If neither is set → the tier registers without a system prompt.
|
|
481
594
|
|
|
595
|
+
Two wordings of every default prompt ship: the enumerated `tierPrompts` above, and a shorter goal-oriented set. Which one a tier gets is decided by `promptStyle`, which defaults to `auto` (goal-oriented for strong models). See [Prompt styles](docs/CONFIG_REFERENCE.md#prompt-styles-promptstyle) in the config reference — including which shipped presets are affected.
|
|
596
|
+
|
|
482
597
|
**When to customize:** if a specific provider/model in a preset needs different instructions (e.g. Gemini-specific tool format, tighter/looser caps for a weaker local model), add `"prompt": "..."` on that tier only. All other presets keep using the global.
|
|
483
598
|
|
|
484
599
|
```json
|
|
@@ -575,7 +690,8 @@ When `antiNarration` is enabled, the detector runs for all models (not only Clau
|
|
|
575
690
|
| `reasoning` | object | OpenAI reasoning: `{ "effort": "high", "summary": "detailed" }` |
|
|
576
691
|
| `description` | string | Shown in `/tiers` output |
|
|
577
692
|
| `steps` | number | Max agent turns |
|
|
578
|
-
| `prompt` | string | Optional per-tier system prompt override. Falls back to
|
|
693
|
+
| `prompt` | string | Optional per-tier system prompt override. Falls back to the style-appropriate default when omitted. |
|
|
694
|
+
| `promptStyle` | string | `"prescriptive"`, `"goal-oriented"` or `"auto"` (default). Picks which default prompt the tier gets; ignored when `prompt` is set. |
|
|
579
695
|
| `whenToUse` | string[] | Use cases (shown in `/tiers`, not in system prompt) |
|
|
580
696
|
|
|
581
697
|
### Fallback
|
|
@@ -600,7 +716,7 @@ The read-only cap banners described above are advisory: a well-behaved subagent
|
|
|
600
716
|
### The three enforcement layers
|
|
601
717
|
|
|
602
718
|
- **Layer 1 — hard-block guard.** A `tool.execute.before` hook throws before a disallowed tool call executes, stopping budget overruns, redundant reads, and throwaway-script sidesteps in subagent sessions.
|
|
603
|
-
- **Layer 2 — independent acceptance gate.**
|
|
719
|
+
- **Layer 2 — independent acceptance gate.** A non-trivial delegation carries a Definition-of-Done (DoD) that is checked — deterministically or by an independent grader at ≥ the producer's tier — before the result is trusted. The producer never grades its own output. Two cases are skipped rather than checked: a trivial dispatch carrying only an inferred DoD, and a dispatch whose inferred DoD has no deterministic checks and which changed no files. An explicit `[acceptance]` block is always verified. See [docs/VERIFICATION.md](docs/VERIFICATION.md).
|
|
604
720
|
- **Layer 3 — quality-escalation ladder.** On a failed check: retry once, then escalate fast → medium → heavy, bounded by attempt and cost ceilings. The loop ends in an honest `status: unmet` rather than a fabricated pass.
|
|
605
721
|
|
|
606
722
|
### Two operating modes
|
|
@@ -640,6 +756,9 @@ Advisory is the default. To change the level:
|
|
|
640
756
|
| `/budget` | Show available modes and which is active |
|
|
641
757
|
| `/budget <mode>` | Switch routing mode (`normal`, `budget`, `quality`, `deep`) |
|
|
642
758
|
| `/annotate-plan [path]` | Annotate a plan file with `[tier:X]` tags for each step |
|
|
759
|
+
| `/router overrides` | Show the global + project override file paths and merge precedence |
|
|
760
|
+
| `/router enforce <off\|advisory\|enforced>` | Set delegation-enforcement mode (persisted) |
|
|
761
|
+
| `/bypass [on\|off]` | Toggle the router off/on for the session |
|
|
643
762
|
|
|
644
763
|
## Plan annotation
|
|
645
764
|
|
|
@@ -665,12 +784,15 @@ After `/annotate-plan`:
|
|
|
665
784
|
|
|
666
785
|
## Token overhead
|
|
667
786
|
|
|
668
|
-
Measured with the bundled Anthropic preset in normal mode, the routing protocol is
|
|
787
|
+
Measured with the bundled Anthropic preset in normal mode (the shipped `activePreset`/`activeMode` defaults), the routing protocol is 3,089 characters for a non-Claude orchestrator. A Claude orchestrator receives 3,861 characters after its authority prefix, or 4,659 characters when the 798-character DoD/enforcement section is enabled. That is roughly 770–1,295 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.
|
|
788
|
+
|
|
789
|
+
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.
|
|
669
790
|
|
|
670
791
|
| Version | Measured overhead | Features |
|
|
671
792
|
|---------|-------------------|----------|
|
|
672
793
|
| Before v1.4.0 | Earlier README token estimates were not measured and were inaccurate | Routing, caps, and enforcement evolved across releases |
|
|
673
794
|
| v1.4.0 | 2,970–4,540 chars (~740–1,260 tokens at 3.6–4.0 chars/token) | Trimmed protocol; path-dependent Claude and enforcement prefixes |
|
|
795
|
+
| v1.6.0 | 3,089–4,659 chars (~770–1,295 tokens at 3.6–4.0 chars/token) | +119 chars on every path: `CAP:none` now has to be justified by a `reason:` line, and the protocol says so twice (rule 7 and the per-dispatch paragraph) |
|
|
674
796
|
|
|
675
797
|
## Requirements
|
|
676
798
|
|
package/package.json
CHANGED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure presentation layer for the slash commands.
|
|
3
|
+
*
|
|
4
|
+
* Every function here is config/data in, markdown string out. No fs, no env,
|
|
5
|
+
* no state writes, no mutation of the config it is handed. The
|
|
6
|
+
* `command.execute.before` handlers in `src/index.ts` do the deciding and the
|
|
7
|
+
* persisting, then call these to render the result.
|
|
8
|
+
*
|
|
9
|
+
* The split exists because the command bodies used to interleave three
|
|
10
|
+
* different jobs — work out what the user asked for, persist it, and describe
|
|
11
|
+
* what happened — which made the output impossible to test without a state
|
|
12
|
+
* file on disk and a plugin instance to hang it off.
|
|
13
|
+
*/
|
|
14
|
+
import type { RouterConfig, TierConfig, ModeConfig } from "../router/config";
|
|
15
|
+
import { getActiveTiers } from "../router/protocol";
|
|
16
|
+
|
|
17
|
+
/** Provider-specific agent options (thinking / reasoning) for a tier. */
|
|
18
|
+
export function buildAgentOptions(tier: TierConfig): Record<string, unknown> {
|
|
19
|
+
const opts: Record<string, unknown> = {};
|
|
20
|
+
|
|
21
|
+
// Anthropic thinking config
|
|
22
|
+
if (tier.thinking) {
|
|
23
|
+
if (tier.thinking.budgetTokens) {
|
|
24
|
+
opts.budget_tokens = tier.thinking.budgetTokens;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// OpenAI reasoning config
|
|
29
|
+
if (tier.reasoning) {
|
|
30
|
+
if (tier.reasoning.effort) {
|
|
31
|
+
opts.reasoning_effort = tier.reasoning.effort;
|
|
32
|
+
}
|
|
33
|
+
if (tier.reasoning.summary) {
|
|
34
|
+
opts.reasoning_summary = tier.reasoning.summary;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return Object.keys(opts).length > 0 ? opts : {};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** `/tiers` */
|
|
42
|
+
export function buildTiersOutput(cfg: RouterConfig): string {
|
|
43
|
+
const tiers = getActiveTiers(cfg);
|
|
44
|
+
const lines: string[] = [
|
|
45
|
+
`# Model Delegation Tiers`,
|
|
46
|
+
`Active preset: **${cfg.activePreset}**\n`,
|
|
47
|
+
];
|
|
48
|
+
|
|
49
|
+
for (const [name, tier] of Object.entries(tiers)) {
|
|
50
|
+
const thinkingStr = tier.thinking
|
|
51
|
+
? ` | thinking: ${tier.thinking.budgetTokens} tokens`
|
|
52
|
+
: tier.reasoning
|
|
53
|
+
? ` | reasoning: effort=${tier.reasoning.effort}`
|
|
54
|
+
: "";
|
|
55
|
+
lines.push(`## @${name} -> \`${tier.model}\`${thinkingStr}`);
|
|
56
|
+
if (tier.description) lines.push(tier.description);
|
|
57
|
+
lines.push(`Steps: ${tier.steps ?? "default"}`);
|
|
58
|
+
const whenToUse = tier.whenToUse ?? [];
|
|
59
|
+
lines.push(whenToUse.length ? `Use when: ${whenToUse.join(", ")}\n` : "");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
lines.push("## Delegation Rules");
|
|
63
|
+
cfg.rules.forEach((r) => lines.push(`- ${r}`));
|
|
64
|
+
lines.push(`\nDefault tier: @${cfg.defaultTier}`);
|
|
65
|
+
lines.push(`\nAvailable presets: ${Object.keys(cfg.presets).join(", ")}`);
|
|
66
|
+
lines.push(`Switch with: \`/preset <name>\``);
|
|
67
|
+
lines.push(`Edit \`tiers.json\` to customize.`);
|
|
68
|
+
|
|
69
|
+
return lines.join("\n");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** `/preset` with no argument. */
|
|
73
|
+
export function buildPresetList(cfg: RouterConfig): string {
|
|
74
|
+
const lines = ["# Available Presets\n"];
|
|
75
|
+
for (const [name, tiers] of Object.entries(cfg.presets)) {
|
|
76
|
+
const active = name === cfg.activePreset ? " <- active" : "";
|
|
77
|
+
const models = Object.entries(tiers)
|
|
78
|
+
.map(([tier, t]) => `${tier}: ${t.model.split("/").pop()}`)
|
|
79
|
+
.join(", ");
|
|
80
|
+
lines.push(`- **${name}**${active}: ${models}`);
|
|
81
|
+
}
|
|
82
|
+
lines.push(`\nSwitch with: \`/preset <name>\``);
|
|
83
|
+
return lines.join("\n");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* `/preset <name>` after the switch has been persisted. Takes the resolved
|
|
88
|
+
* name, so the caller owns resolution and this only describes the outcome.
|
|
89
|
+
*/
|
|
90
|
+
export function buildPresetSwitched(cfg: RouterConfig, name: string): string {
|
|
91
|
+
const tiers = cfg.presets[name]!;
|
|
92
|
+
const models = Object.entries(tiers)
|
|
93
|
+
.map(([tier, t]) => ` @${tier} -> ${t.model}`)
|
|
94
|
+
.join("\n");
|
|
95
|
+
return [
|
|
96
|
+
`Preset switched to **${name}**.`,
|
|
97
|
+
"",
|
|
98
|
+
models,
|
|
99
|
+
"",
|
|
100
|
+
"Selection is now persisted in ~/.config/opencode/opencode-model-router.state.json.",
|
|
101
|
+
"Restart OpenCode for subagent model registration to take effect.",
|
|
102
|
+
"System prompt delegation rules update immediately.",
|
|
103
|
+
].join("\n");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** `/preset <name>` where the name resolves to nothing. */
|
|
107
|
+
export function buildUnknownPreset(cfg: RouterConfig, requested: string): string {
|
|
108
|
+
return `Unknown preset: "${requested}". Available: ${Object.keys(cfg.presets).join(", ")}`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** `/budget` when tiers.json defines no modes at all. */
|
|
112
|
+
export function buildNoModes(): string {
|
|
113
|
+
return 'No modes configured in tiers.json. Add a "modes" section to enable budget mode.';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** `/budget` with no argument. */
|
|
117
|
+
export function buildBudgetList(cfg: RouterConfig): string {
|
|
118
|
+
const modes = cfg.modes ?? {};
|
|
119
|
+
const currentMode = cfg.activeMode || "normal";
|
|
120
|
+
const lines = ["# Routing Modes\n"];
|
|
121
|
+
for (const [name, mode] of Object.entries(modes)) {
|
|
122
|
+
const active = name === currentMode ? " <- active" : "";
|
|
123
|
+
lines.push(
|
|
124
|
+
`- **${name}**${active}: ${mode.description} (default tier: @${mode.defaultTier})`,
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
lines.push(`\nSwitch with: \`/budget <mode>\``);
|
|
128
|
+
return lines.join("\n");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** `/budget <mode>` after the switch has been persisted. */
|
|
132
|
+
export function buildBudgetSwitched(mode: ModeConfig, name: string): string {
|
|
133
|
+
return [
|
|
134
|
+
`Routing mode switched to **${name}**.`,
|
|
135
|
+
"",
|
|
136
|
+
mode.description,
|
|
137
|
+
`Default tier: @${mode.defaultTier}`,
|
|
138
|
+
...(mode.overrideRules?.length
|
|
139
|
+
? ["", "Active rules:", ...mode.overrideRules.map((r) => `- ${r}`)]
|
|
140
|
+
: []),
|
|
141
|
+
"",
|
|
142
|
+
"Mode change takes effect immediately on the next message.",
|
|
143
|
+
].join("\n");
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** `/budget <mode>` where the mode is not configured. */
|
|
147
|
+
export function buildUnknownMode(
|
|
148
|
+
modes: Record<string, ModeConfig>,
|
|
149
|
+
requested: string,
|
|
150
|
+
): string {
|
|
151
|
+
return `Unknown mode: "${requested}". Available: ${Object.keys(modes).join(", ")}`;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** `/bypass`, rendered from the resulting state rather than the argument. */
|
|
155
|
+
export function buildBypassMessage(bypassed: boolean): string {
|
|
156
|
+
const status = bypassed ? "ON" : "OFF";
|
|
157
|
+
const desc = bypassed
|
|
158
|
+
? "Model-router is **bypassed**. Delegation protocol, cap enforcement, and narration detection are disabled. The model will run without routing rules until you run `/bypass off` or restart OpenCode."
|
|
159
|
+
: "Model-router is **active**. Delegation protocol and all enforcement rules are in effect.";
|
|
160
|
+
return `# Bypass: ${status}\n\n${desc}`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** `/router enforce <mode>` after the mode has been persisted. */
|
|
164
|
+
export function buildEnforceSet(mode: "off" | "advisory" | "enforced"): string {
|
|
165
|
+
const desc =
|
|
166
|
+
mode === "off"
|
|
167
|
+
? "Hard-block guard disabled (default routing behaviour)."
|
|
168
|
+
: mode === "advisory"
|
|
169
|
+
? "Guard evaluates and surfaces banners but never hard-blocks."
|
|
170
|
+
: "Guard hard-blocks subagent tool calls that violate budget / redundancy / self-script policy.";
|
|
171
|
+
return [
|
|
172
|
+
`Enforcement mode set to **${mode}** and persisted.`,
|
|
173
|
+
"",
|
|
174
|
+
desc,
|
|
175
|
+
"",
|
|
176
|
+
"Note: the `MODEL_ROUTER_ENFORCE` env var, when set to `0` or `1`, overrides this setting.",
|
|
177
|
+
].join("\n");
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** `/router enforce` with a missing or unrecognized mode. */
|
|
181
|
+
export function buildEnforceStatus(current: string): string {
|
|
182
|
+
return [
|
|
183
|
+
`Current enforcement mode: **${current}**`,
|
|
184
|
+
"",
|
|
185
|
+
"Usage: `/router enforce <off|advisory|enforced>`",
|
|
186
|
+
].join("\n");
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Everything `/router overrides` needs to know about the filesystem, resolved
|
|
191
|
+
* by the caller so this stays pure.
|
|
192
|
+
*/
|
|
193
|
+
export interface OverridesView {
|
|
194
|
+
globalPath: string;
|
|
195
|
+
globalPresent: boolean;
|
|
196
|
+
/** The project file that was found, or the default create-location. */
|
|
197
|
+
localPath: string;
|
|
198
|
+
localPresent: boolean;
|
|
199
|
+
/** False when localPath is a suggestion rather than a file that was found. */
|
|
200
|
+
localFound: boolean;
|
|
201
|
+
activePreset: string;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** `/router overrides` */
|
|
205
|
+
export function buildOverridesOutput(v: OverridesView): string {
|
|
206
|
+
const mark = (present: boolean) => (present ? "present" : "absent");
|
|
207
|
+
const localNote = v.localFound
|
|
208
|
+
? ""
|
|
209
|
+
: ` _(create at \`${v.localPath}\`; the project file is searched upward from the working dir to the repo root)_`;
|
|
210
|
+
return [
|
|
211
|
+
`# Model Router — config overrides`,
|
|
212
|
+
"",
|
|
213
|
+
"Config is loaded lowest→highest priority; each layer deep-merges over the previous one:",
|
|
214
|
+
"",
|
|
215
|
+
"1. bundled `tiers.json` (defaults)",
|
|
216
|
+
`2. global — \`${v.globalPath}\` _(${mark(v.globalPresent)})_`,
|
|
217
|
+
`3. project — \`${v.localPath}\` _(${mark(v.localPresent)})_${localNote}`,
|
|
218
|
+
"",
|
|
219
|
+
`Active preset: **${v.activePreset}**. Run \`/tiers\` to see the effective models after merging.`,
|
|
220
|
+
"",
|
|
221
|
+
"Create either file to customize models/tiers/presets without editing the cached `tiers.json`. Objects merge recursively; arrays and scalars are replaced.",
|
|
222
|
+
].join("\n");
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Bare `/router`. */
|
|
226
|
+
export function buildRouterHelp(current: string): string {
|
|
227
|
+
return [
|
|
228
|
+
`# Model Router`,
|
|
229
|
+
`Enforcement: **${current}**`,
|
|
230
|
+
"",
|
|
231
|
+
"Commands:",
|
|
232
|
+
"- `/router enforce <off|advisory|enforced>` — set hard-block enforcement (persisted)",
|
|
233
|
+
"- `/router overrides` — show the global + project override file paths and precedence",
|
|
234
|
+
"- `/tiers`, `/preset`, `/budget`, `/bypass`, `/annotate-plan`",
|
|
235
|
+
].join("\n");
|
|
236
|
+
}
|
package/src/guard/enforce.ts
CHANGED
|
@@ -19,6 +19,17 @@ import type { RouterConfig } from "../router/config";
|
|
|
19
19
|
*/
|
|
20
20
|
export const DEFAULT_GUARD_BUDGET = 25;
|
|
21
21
|
|
|
22
|
+
/**
|
|
23
|
+
* The cumulative ceiling spans resumed dispatches: it is this multiple of the
|
|
24
|
+
* effective per-dispatch budget (configured or default), giving resumed
|
|
25
|
+
* subagents bounded room without unbounded same-session loops.
|
|
26
|
+
*/
|
|
27
|
+
export const CUMULATIVE_BUDGET_MULTIPLIER = 3;
|
|
28
|
+
|
|
29
|
+
/** Default-case cumulative budget, retained for imports/tests. */
|
|
30
|
+
export const CUMULATIVE_GUARD_BUDGET =
|
|
31
|
+
DEFAULT_GUARD_BUDGET * CUMULATIVE_BUDGET_MULTIPLIER;
|
|
32
|
+
|
|
22
33
|
export interface GuardStoreLike {
|
|
23
34
|
ensure(sessionID: string, policy: GuardPolicy): GuardState;
|
|
24
35
|
get(sessionID: string): GuardState | undefined;
|
|
@@ -31,8 +42,10 @@ export interface GuardStoreLike {
|
|
|
31
42
|
* the deliverable-first clause — the honest common case (M5). */
|
|
32
43
|
export function buildGuardPolicy(cfg: RouterConfig, tier: string | null): GuardPolicy {
|
|
33
44
|
const g = cfg.enforcement?.guard ?? {};
|
|
45
|
+
const budget = g.budget ?? DEFAULT_GUARD_BUDGET;
|
|
34
46
|
return {
|
|
35
|
-
budget
|
|
47
|
+
budget,
|
|
48
|
+
cumulativeBudget: budget * CUMULATIVE_BUDGET_MULTIPLIER,
|
|
36
49
|
readDraftCap: g.readDraftCap ?? 3,
|
|
37
50
|
sameOpRetryCap: g.sameOpRetryCap ?? 1,
|
|
38
51
|
blockSelfScript: g.blockSelfScript ?? true,
|
package/src/guard/guards.ts
CHANGED
|
@@ -7,6 +7,8 @@ import { READ_ONLY_TOOLS } from "../router/sessions";
|
|
|
7
7
|
|
|
8
8
|
export interface GuardPolicy {
|
|
9
9
|
budget: number;
|
|
10
|
+
/** Cumulative tool-call ceiling across resumed dispatches. Unset = no ceiling. */
|
|
11
|
+
cumulativeBudget?: number;
|
|
10
12
|
readDraftCap: number;
|
|
11
13
|
sameOpRetryCap: number;
|
|
12
14
|
blockSelfScript: boolean;
|
|
@@ -33,7 +35,12 @@ export interface GuardDecision {
|
|
|
33
35
|
|
|
34
36
|
export interface GuardState {
|
|
35
37
|
budget: number;
|
|
38
|
+
/** Tool calls in the CURRENT dispatch (reset by guardStore.beginDispatch). */
|
|
36
39
|
toolCallCount: number;
|
|
40
|
+
/** Tool calls across all dispatches of this session (never reset). */
|
|
41
|
+
totalToolCallCount: number;
|
|
42
|
+
/** Dispatch rounds seen for this session (1 on first dispatch). */
|
|
43
|
+
dispatches: number;
|
|
37
44
|
readCount: number;
|
|
38
45
|
execCount: number;
|
|
39
46
|
selfScriptCount: number;
|
|
@@ -71,6 +78,8 @@ export function newGuardState(policy: GuardPolicy): GuardState {
|
|
|
71
78
|
return {
|
|
72
79
|
budget: policy.budget,
|
|
73
80
|
toolCallCount: 0,
|
|
81
|
+
totalToolCallCount: 0,
|
|
82
|
+
dispatches: 1,
|
|
74
83
|
readCount: 0,
|
|
75
84
|
execCount: 0,
|
|
76
85
|
selfScriptCount: 0,
|
|
@@ -178,6 +187,20 @@ export function evaluateGuards(
|
|
|
178
187
|
};
|
|
179
188
|
}
|
|
180
189
|
|
|
190
|
+
// CLAUSE 3b: cumulative budget across resumed dispatches. Without this, a
|
|
191
|
+
// session that keeps getting resumed gets a fresh per-dispatch budget every
|
|
192
|
+
// round — an unbounded loop that CLAUSE 3 alone cannot see.
|
|
193
|
+
if (
|
|
194
|
+
policy.cumulativeBudget !== undefined &&
|
|
195
|
+
state.totalToolCallCount >= policy.cumulativeBudget
|
|
196
|
+
) {
|
|
197
|
+
return {
|
|
198
|
+
allow: false,
|
|
199
|
+
guard: "cumulative_iteration_cap",
|
|
200
|
+
observation: `DENIED: cumulative tool-call budget ${policy.cumulativeBudget} exhausted across ${state.dispatches} dispatches. Stop now and emit your final answer with what you have.`,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
181
204
|
// CLAUSE 4: redundancy
|
|
182
205
|
if (kind === "read" && (state.seen.get(fp) ?? 0) >= policy.sameOpRetryCap) {
|
|
183
206
|
return {
|
|
@@ -230,6 +253,7 @@ export function updateState(
|
|
|
230
253
|
if (kind === "finish") return state;
|
|
231
254
|
|
|
232
255
|
state.toolCallCount += 1;
|
|
256
|
+
state.totalToolCallCount += 1;
|
|
233
257
|
|
|
234
258
|
const fp = fingerprintToolCall(call.tool, call.args);
|
|
235
259
|
|
|
@@ -306,6 +330,8 @@ export function trajectoryMetrics(state: GuardState): Record<string, unknown> {
|
|
|
306
330
|
state.execCount === 0 ? state.readCount : state.readCount / state.execCount,
|
|
307
331
|
self_script_count: state.selfScriptCount,
|
|
308
332
|
tool_call_count: state.toolCallCount,
|
|
333
|
+
total_tool_call_count: state.totalToolCallCount,
|
|
334
|
+
dispatches: state.dispatches,
|
|
309
335
|
deliverable_executed: state.deliverableExecuted,
|
|
310
336
|
blocked_count: state.blockedCount,
|
|
311
337
|
redundant_count: state.redundantCount,
|