opencode-model-router 1.3.1 → 1.5.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 +91 -20
- package/package.json +7 -4
- package/src/index.ts +116 -22
- package/src/router/config.ts +292 -6
- package/src/router/jsonc.ts +91 -0
- package/src/router/protocol.ts +17 -32
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 2,970–4,540 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
|
|
15
|
+
Instead of duplicated prose, the plugin injects a dense, machine-readable routing protocol. The protocol itself is 2,970 characters; a Claude orchestrator receives 3,742 characters after its authority prefix (roughly 935–1,040 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 2,970 characters for a non-Claude orchestrator or 3,742 characters for a Claude orchestrator (roughly 740–1,040 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
|
|
117
|
+
On every message, the plugin injects a 2,970-character routing protocol. A Claude orchestrator receives 3,742 characters after its authority prefix (roughly 935–1,040 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
|
-
|
|
|
169
|
+
| Measured prompt overhead: 2,970–4,540 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
|
|
|
@@ -526,11 +589,17 @@ Detection is by model string, not preset. A `hybrid` preset that mixes providers
|
|
|
526
589
|
|
|
527
590
|
No configuration is needed — the prefixes are always applied for Claude-backed tiers. If you want to disable them, override the tier's `prompt` field (per-tier overrides replace the whole prompt, including the prefix).
|
|
528
591
|
|
|
529
|
-
### Anti-narration guardrail (Claude models)
|
|
592
|
+
### Anti-narration guardrail (Claude models, opt-in)
|
|
593
|
+
|
|
594
|
+
Some Claude models (historically, thinking-enabled Sonnet with the `max` variant) can produce progress narration instead of actual work, phrasings like *"Still writing the X function..."*, *"Now I'll implement Y..."*, *"Let me add Z..."*, without the X/Y/Z ever appearing.
|
|
530
595
|
|
|
531
|
-
|
|
596
|
+
This guardrail is **off by default**. On the Claude orchestrator path, enabling it adds 650 characters per message (roughly 160–180 tokens at 3.6–4.0 characters per token), and its detector false-positives on normal productive phrasing like "Now I'll add the test" when the test does follow, so it is opt-in. Enable it only if you actually observe narration-without-production on your models:
|
|
597
|
+
|
|
598
|
+
```jsonc
|
|
599
|
+
{ "antiNarration": true }
|
|
600
|
+
```
|
|
532
601
|
|
|
533
|
-
|
|
602
|
+
When enabled, it works on two layers:
|
|
534
603
|
|
|
535
604
|
**1. Prompt-level clause (prevention).** A dedicated `ANTI-NARRATION` block is appended to every Claude-backed tier prompt and to the Claude-backed orchestrator delegation protocol. It names the forbidden phrasings explicitly and requires concrete output to follow any such phrase. A carve-out preserves legitimate explanation/plan requests from the user.
|
|
536
605
|
|
|
@@ -556,7 +625,7 @@ Detected patterns (conservative set to minimize false positives):
|
|
|
556
625
|
- `Going to (write|implement|...) the X`
|
|
557
626
|
- `Continuing (with|by ...ing) (the )? X`
|
|
558
627
|
|
|
559
|
-
|
|
628
|
+
When `antiNarration` is enabled, the detector runs for all models (not only Claude), while the prompt-level clause is Claude-only, so non-Claude models get detector-only. With the default (`antiNarration` off), neither layer runs.
|
|
560
629
|
|
|
561
630
|
### Tier fields reference
|
|
562
631
|
|
|
@@ -589,12 +658,12 @@ Defines provider fallback order when a delegated task fails:
|
|
|
589
658
|
|
|
590
659
|
## Delegation enforcement (advisory by default)
|
|
591
660
|
|
|
592
|
-
The read-only cap banners described above are advisory: a well-behaved subagent will respect them, but nothing prevents a model from making one more read after the `[⚠ CAP REACHED]` banner. The **enforcement layer** turns delegation into a produce → verify → accept/escalate loop with independent acceptance and quality escalation. As of v1.3.0 it runs in **`advisory` mode by default**: every non-trivial delegation is verified and any miss surfaces a forcing-note, but nothing is ever hard-blocked (the orchestrator system prompt
|
|
661
|
+
The read-only cap banners described above are advisory: a well-behaved subagent will respect them, but nothing prevents a model from making one more read after the `[⚠ CAP REACHED]` banner. The **enforcement layer** turns delegation into a produce → verify → accept/escalate loop with independent acceptance and quality escalation. As of v1.3.0 it runs in **`advisory` mode by default**: every non-trivial delegation is verified and any miss surfaces a forcing-note, but nothing is ever hard-blocked (the DoD/acceptance section adds 798 characters to the orchestrator system prompt, roughly 200–220 tokens at 3.6–4.0 characters per token, and subagents may receive non-blocking guard banners). Set `"mode": "off"` — or run `/router enforce off` — to restore byte-for-byte-unchanged routing with zero added prompt tokens and zero new latency. Hard-blocks only activate in `"mode": "enforced"`.
|
|
593
662
|
|
|
594
663
|
### The three enforcement layers
|
|
595
664
|
|
|
596
665
|
- **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.
|
|
597
|
-
- **Layer 2 — independent acceptance gate.**
|
|
666
|
+
- **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).
|
|
598
667
|
- **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.
|
|
599
668
|
|
|
600
669
|
### Two operating modes
|
|
@@ -634,6 +703,9 @@ Advisory is the default. To change the level:
|
|
|
634
703
|
| `/budget` | Show available modes and which is active |
|
|
635
704
|
| `/budget <mode>` | Switch routing mode (`normal`, `budget`, `quality`, `deep`) |
|
|
636
705
|
| `/annotate-plan [path]` | Annotate a plan file with `[tier:X]` tags for each step |
|
|
706
|
+
| `/router overrides` | Show the global + project override file paths and merge precedence |
|
|
707
|
+
| `/router enforce <off\|advisory\|enforced>` | Set delegation-enforcement mode (persisted) |
|
|
708
|
+
| `/bypass [on\|off]` | Toggle the router off/on for the session |
|
|
637
709
|
|
|
638
710
|
## Plan annotation
|
|
639
711
|
|
|
@@ -659,18 +731,17 @@ After `/annotate-plan`:
|
|
|
659
731
|
|
|
660
732
|
## Token overhead
|
|
661
733
|
|
|
662
|
-
|
|
734
|
+
Measured with the bundled Anthropic preset in normal mode, the routing protocol is 2,970 characters for a non-Claude orchestrator. A Claude orchestrator receives 3,742 characters after its authority prefix, or 4,540 characters when the 798-character DoD/enforcement section is enabled. That is roughly 740–1,260 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.
|
|
663
735
|
|
|
664
|
-
| Version |
|
|
665
|
-
|
|
666
|
-
| v1.0
|
|
667
|
-
| v1.
|
|
668
|
-
| v1.1.1+ | ~210 | All features, compressed format |
|
|
736
|
+
| Version | Measured overhead | Features |
|
|
737
|
+
|---------|-------------------|----------|
|
|
738
|
+
| Before v1.4.0 | Earlier README token estimates were not measured and were inaccurate | Routing, caps, and enforcement evolved across releases |
|
|
739
|
+
| 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 |
|
|
669
740
|
|
|
670
741
|
## Requirements
|
|
671
742
|
|
|
672
743
|
- [OpenCode](https://opencode.ai) v1.0 or later
|
|
673
|
-
- Node.js
|
|
744
|
+
- Node.js 20+
|
|
674
745
|
- Provider API keys configured in OpenCode
|
|
675
746
|
|
|
676
747
|
## License
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-model-router",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.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",
|
|
@@ -12,6 +12,9 @@
|
|
|
12
12
|
"typecheck": "tsc --noEmit"
|
|
13
13
|
},
|
|
14
14
|
"license": "GPL-3.0-only",
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=20"
|
|
17
|
+
},
|
|
15
18
|
"repository": {
|
|
16
19
|
"type": "git",
|
|
17
20
|
"url": "git+https://github.com/marco-jardim/opencode-model-router.git"
|
|
@@ -44,10 +47,10 @@
|
|
|
44
47
|
"@opencode-ai/plugin": ">=1.0.0"
|
|
45
48
|
},
|
|
46
49
|
"devDependencies": {
|
|
47
|
-
"@types/node": "^
|
|
50
|
+
"@types/node": "^26.2.0",
|
|
48
51
|
"@vitest/coverage-v8": "^4.1.8",
|
|
49
|
-
"cross-env": "^
|
|
50
|
-
"typescript": "^
|
|
52
|
+
"cross-env": "^10.1.0",
|
|
53
|
+
"typescript": "^7.0.2",
|
|
51
54
|
"vitest": "^4.1.8"
|
|
52
55
|
}
|
|
53
56
|
}
|
package/src/index.ts
CHANGED
|
@@ -6,6 +6,9 @@ import {
|
|
|
6
6
|
resolvePresetName,
|
|
7
7
|
writeState,
|
|
8
8
|
invalidateConfigCache,
|
|
9
|
+
overridePath,
|
|
10
|
+
localOverridePath,
|
|
11
|
+
findProjectOverride,
|
|
9
12
|
} from "./router/config";
|
|
10
13
|
import type { RouterConfig, TierConfig, Preset, ModeConfig } from "./router/config";
|
|
11
14
|
import { fingerprintToolCall } from "./guard/fingerprint";
|
|
@@ -31,7 +34,7 @@ import type { Cap, SubagentState } from "./router/sessions";
|
|
|
31
34
|
import { createTrajectoryStore } from "./telemetry/trajectory";
|
|
32
35
|
import { createGuardStore } from "./guard/store";
|
|
33
36
|
import { guardBeforeCall, guardAfterCall, formatScorecard } from "./guard/enforce";
|
|
34
|
-
import { mkdirSync, writeFileSync } from "node:fs";
|
|
37
|
+
import { mkdirSync, writeFileSync, existsSync } from "node:fs";
|
|
35
38
|
import { tmpdir } from "node:os";
|
|
36
39
|
import { join, isAbsolute } from "node:path";
|
|
37
40
|
import { exec as nodeExec } from "node:child_process";
|
|
@@ -125,6 +128,28 @@ function buildRouterOutput(cfg: RouterConfig, args: string): string {
|
|
|
125
128
|
"Usage: `/router enforce <off|advisory|enforced>`",
|
|
126
129
|
].join("\n");
|
|
127
130
|
}
|
|
131
|
+
if (sub === "overrides") {
|
|
132
|
+
const globalP = overridePath();
|
|
133
|
+
const foundLocal = findProjectOverride();
|
|
134
|
+
const localP = foundLocal ?? localOverridePath();
|
|
135
|
+
const mark = (p: string) => (existsSync(p) ? "present" : "absent");
|
|
136
|
+
const localNote = foundLocal
|
|
137
|
+
? ""
|
|
138
|
+
: ` _(create at \`${localP}\`; the project file is searched upward from the working dir to the repo root)_`;
|
|
139
|
+
return [
|
|
140
|
+
`# Model Router — config overrides`,
|
|
141
|
+
"",
|
|
142
|
+
"Config is loaded lowest→highest priority; each layer deep-merges over the previous one:",
|
|
143
|
+
"",
|
|
144
|
+
"1. bundled `tiers.json` (defaults)",
|
|
145
|
+
`2. global — \`${globalP}\` _(${mark(globalP)})_`,
|
|
146
|
+
`3. project — \`${localP}\` _(${mark(localP)})_${localNote}`,
|
|
147
|
+
"",
|
|
148
|
+
`Active preset: **${cfg.activePreset}**. Run \`/tiers\` to see the effective models after merging.`,
|
|
149
|
+
"",
|
|
150
|
+
"Create either file to customize models/tiers/presets without editing the cached `tiers.json`. Objects merge recursively; arrays and scalars are replaced.",
|
|
151
|
+
].join("\n");
|
|
152
|
+
}
|
|
128
153
|
const current = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
|
|
129
154
|
return [
|
|
130
155
|
`# Model Router`,
|
|
@@ -132,6 +157,7 @@ function buildRouterOutput(cfg: RouterConfig, args: string): string {
|
|
|
132
157
|
"",
|
|
133
158
|
"Commands:",
|
|
134
159
|
"- `/router enforce <off|advisory|enforced>` — set hard-block enforcement (persisted)",
|
|
160
|
+
"- `/router overrides` — show the global + project override file paths and precedence",
|
|
135
161
|
"- `/tiers`, `/preset`, `/budget`, `/bypass`, `/annotate-plan`",
|
|
136
162
|
].join("\n");
|
|
137
163
|
}
|
|
@@ -181,9 +207,10 @@ function buildTiersOutput(cfg: RouterConfig): string {
|
|
|
181
207
|
? ` | reasoning: effort=${tier.reasoning.effort}`
|
|
182
208
|
: "";
|
|
183
209
|
lines.push(`## @${name} -> \`${tier.model}\`${thinkingStr}`);
|
|
184
|
-
lines.push(tier.description);
|
|
210
|
+
if (tier.description) lines.push(tier.description);
|
|
185
211
|
lines.push(`Steps: ${tier.steps ?? "default"}`);
|
|
186
|
-
|
|
212
|
+
const whenToUse = tier.whenToUse ?? [];
|
|
213
|
+
lines.push(whenToUse.length ? `Use when: ${whenToUse.join(", ")}\n` : "");
|
|
187
214
|
}
|
|
188
215
|
|
|
189
216
|
lines.push("## Delegation Rules");
|
|
@@ -356,12 +383,34 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
356
383
|
},
|
|
357
384
|
};
|
|
358
385
|
const verifyMutex = createMutexRegistry();
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
386
|
+
// Best-effort disposal of a plugin-created child session: abort any in-flight
|
|
387
|
+
// work, then delete it so it does not linger forever as a top-level session in
|
|
388
|
+
// the TUI. Fail-soft by contract — never throws, so it is safe to call from a
|
|
389
|
+
// finally without masking the original error.
|
|
390
|
+
const disposeChildSession = async (sid: string): Promise<void> => {
|
|
391
|
+
try {
|
|
392
|
+
await ctx.client.session.abort({ path: { id: sid } });
|
|
393
|
+
} catch {
|
|
394
|
+
// best-effort: the session may already have completed or been removed
|
|
395
|
+
}
|
|
396
|
+
try {
|
|
397
|
+
await ctx.client.session.delete({ path: { id: sid } });
|
|
398
|
+
} catch {
|
|
399
|
+
// best-effort: cleanup must never break the run
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
const dispatchGrader = async (
|
|
404
|
+
req: {
|
|
405
|
+
tier: string;
|
|
406
|
+
system: string;
|
|
407
|
+
prompt: string;
|
|
408
|
+
},
|
|
409
|
+
parentSessionID?: string,
|
|
410
|
+
): Promise<{ sessionID: string; text: string }> => {
|
|
411
|
+
const created: any = await ctx.client.session.create({
|
|
412
|
+
body: { ...(parentSessionID ? { parentID: parentSessionID } : {}) },
|
|
413
|
+
});
|
|
365
414
|
const sid: string | undefined = created?.data?.id;
|
|
366
415
|
if (!sid) return { sessionID: "", text: "" };
|
|
367
416
|
graderSessions.add(sid);
|
|
@@ -383,9 +432,10 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
383
432
|
return { sessionID: sid, text };
|
|
384
433
|
} finally {
|
|
385
434
|
graderSessions.delete(sid);
|
|
435
|
+
await disposeChildSession(sid);
|
|
386
436
|
}
|
|
387
437
|
};
|
|
388
|
-
const buildGateDeps = () => ({
|
|
438
|
+
const buildGateDeps = (parentSessionID?: string) => ({
|
|
389
439
|
deterministic: {
|
|
390
440
|
exec: execSeam,
|
|
391
441
|
fs: fsSeam,
|
|
@@ -393,7 +443,8 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
393
443
|
mutex: verifyMutex,
|
|
394
444
|
},
|
|
395
445
|
checker: {
|
|
396
|
-
dispatchGrader
|
|
446
|
+
dispatchGrader: (req: { tier: string; system: string; prompt: string }) =>
|
|
447
|
+
dispatchGrader(req, parentSessionID),
|
|
397
448
|
ladder: ["fast", "medium", "heavy"],
|
|
398
449
|
minGraderTier: cfg.enforcement?.verify?.minGraderTier ?? null,
|
|
399
450
|
},
|
|
@@ -446,11 +497,18 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
446
497
|
"Optional [acceptance]...[/acceptance] block defining the Definition of Done (check: / criteria: / deliverable: directives).",
|
|
447
498
|
),
|
|
448
499
|
},
|
|
449
|
-
async execute(
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
500
|
+
async execute(
|
|
501
|
+
args: {
|
|
502
|
+
task: string;
|
|
503
|
+
tier?: string;
|
|
504
|
+
acceptance?: string;
|
|
505
|
+
},
|
|
506
|
+
toolCtx?: { sessionID?: string },
|
|
507
|
+
): Promise<string> {
|
|
508
|
+
// Every ladder iteration creates its own producer session. Tracked out
|
|
509
|
+
// here (not inside the try) so the finally below can dispose any that an
|
|
510
|
+
// early return or a throw skipped — otherwise each retry leaks another.
|
|
511
|
+
const producerSessions: string[] = [];
|
|
454
512
|
try {
|
|
455
513
|
let activeCfg = cfg;
|
|
456
514
|
try {
|
|
@@ -494,11 +552,16 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
494
552
|
? `${scrubText(forcing)}\n\n${args.task}`
|
|
495
553
|
: args.task;
|
|
496
554
|
|
|
497
|
-
const created: any = await ctx.client.session.create({
|
|
555
|
+
const created: any = await ctx.client.session.create({
|
|
556
|
+
body: {
|
|
557
|
+
...(toolCtx?.sessionID ? { parentID: toolCtx.sessionID } : {}),
|
|
558
|
+
},
|
|
559
|
+
});
|
|
498
560
|
const producerSid: string | undefined = created?.data?.id;
|
|
499
561
|
if (!producerSid) {
|
|
500
562
|
return "[router] delegate failed: could not create a producer session.";
|
|
501
563
|
}
|
|
564
|
+
producerSessions.push(producerSid);
|
|
502
565
|
// Compose with Layer 1: guard the plugin-created producer session.
|
|
503
566
|
try {
|
|
504
567
|
sessionStore.registerProducerSession(producerSid, tier, activeCfg);
|
|
@@ -546,7 +609,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
546
609
|
gateRes = await accept(
|
|
547
610
|
{ dod, trivial: false, mode: "modeA" },
|
|
548
611
|
artefact,
|
|
549
|
-
buildGateDeps(),
|
|
612
|
+
buildGateDeps(toolCtx?.sessionID),
|
|
550
613
|
);
|
|
551
614
|
} catch {
|
|
552
615
|
gateRes = {
|
|
@@ -572,6 +635,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
572
635
|
} catch {
|
|
573
636
|
// non-fatal
|
|
574
637
|
}
|
|
638
|
+
// Dispose this attempt's backend session before the next iteration
|
|
639
|
+
// so a long ladder never accumulates live sessions.
|
|
640
|
+
await disposeChildSession(producerSid);
|
|
575
641
|
|
|
576
642
|
const costRatio =
|
|
577
643
|
typeof tiersForCost?.[tier]?.costRatio === "number"
|
|
@@ -615,6 +681,14 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
615
681
|
}
|
|
616
682
|
} catch {
|
|
617
683
|
return "[router] delegate failed (fail-closed): the delegation or verification could not complete.";
|
|
684
|
+
} finally {
|
|
685
|
+
// Safety net for every exit path an end-of-iteration dispose cannot
|
|
686
|
+
// reach: accept/give-up returns, the safety-net return, and throws.
|
|
687
|
+
// disposeChildSession is fail-soft, so re-disposing an already
|
|
688
|
+
// disposed session is harmless.
|
|
689
|
+
for (const sid of producerSessions) {
|
|
690
|
+
await disposeChildSession(sid);
|
|
691
|
+
}
|
|
618
692
|
}
|
|
619
693
|
},
|
|
620
694
|
}) } : {}),
|
|
@@ -776,6 +850,23 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
776
850
|
const trivial = childSessionID
|
|
777
851
|
? sessionStore.isTrivial(childSessionID)
|
|
778
852
|
: false;
|
|
853
|
+
|
|
854
|
+
// Read-only / research delegation: an auto-inferred, criteria-only DoD on a
|
|
855
|
+
// native Task() that changed no files is exploration, not implementation.
|
|
856
|
+
// There is nothing concrete to verify, so skip rather than grade the
|
|
857
|
+
// findings against the task's own summary, which otherwise appends false
|
|
858
|
+
// "not accepted" notes to legitimate read-only research delegations.
|
|
859
|
+
// Explicit [acceptance] blocks (source != "inferred") and inferred
|
|
860
|
+
// deterministic checks (dod.kind === "deterministic") still verify normally.
|
|
861
|
+
if (
|
|
862
|
+
dod.source === "inferred" &&
|
|
863
|
+
dod.kind === "checker" &&
|
|
864
|
+
artefact.changedFiles.length === 0
|
|
865
|
+
) {
|
|
866
|
+
if (childSessionID) changedFileStore.clear(childSessionID);
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
|
|
779
870
|
const res = await accept(
|
|
780
871
|
{ dod, trivial, mode: "modeA" },
|
|
781
872
|
artefact,
|
|
@@ -809,7 +900,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
809
900
|
// post-hoc signal.
|
|
810
901
|
// -----------------------------------------------------------------------
|
|
811
902
|
"experimental.text.complete": async (input: any, output: any) => {
|
|
812
|
-
if (bypassed) return;
|
|
903
|
+
if (bypassed || !cfg.antiNarration) return;
|
|
813
904
|
const text = output?.text;
|
|
814
905
|
if (typeof text !== "string" || text.length < 20) return;
|
|
815
906
|
|
|
@@ -875,7 +966,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
875
966
|
// Detection is by model string, so hybrid presets get the override
|
|
876
967
|
// only on their Claude-backed tiers.
|
|
877
968
|
const claudePrefix = isClaudeModel(tier.model)
|
|
878
|
-
?
|
|
969
|
+
? cfg.antiNarration
|
|
970
|
+
? `${CLAUDE_TIER_PREFIX[name]}\n\n${CLAUDE_ANTI_NARRATION}`
|
|
971
|
+
: CLAUDE_TIER_PREFIX[name]
|
|
879
972
|
: undefined;
|
|
880
973
|
const finalPrompt =
|
|
881
974
|
claudePrefix && resolvedPrompt
|
|
@@ -885,7 +978,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
885
978
|
const agentDef: Record<string, unknown> = {
|
|
886
979
|
model: tier.model,
|
|
887
980
|
mode: "subagent",
|
|
888
|
-
description: tier.description
|
|
981
|
+
description: tier.description ?? `@${name} tier (${tier.model})`,
|
|
889
982
|
maxSteps: tier.steps,
|
|
890
983
|
prompt: finalPrompt,
|
|
891
984
|
color: tier.color,
|
|
@@ -964,7 +1057,8 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
964
1057
|
};
|
|
965
1058
|
opencodeConfig.command["router"] = {
|
|
966
1059
|
template: "$ARGUMENTS",
|
|
967
|
-
description:
|
|
1060
|
+
description:
|
|
1061
|
+
"Model-router controls (e.g., /router enforce off|advisory|enforced, /router overrides)",
|
|
968
1062
|
};
|
|
969
1063
|
},
|
|
970
1064
|
|
package/src/router/config.ts
CHANGED
|
@@ -2,6 +2,14 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "
|
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { parseJsonc } from "./jsonc";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Filename of the optional user overrides file (global and project copies share
|
|
9
|
+
* it). `.jsonc` so comments and trailing commas are allowed; mirrors the
|
|
10
|
+
* `opencode-model-router.*` prefix of the state file.
|
|
11
|
+
*/
|
|
12
|
+
export const OVERRIDE_FILENAME = "opencode-model-router.overrides.jsonc";
|
|
5
13
|
|
|
6
14
|
// ---------------------------------------------------------------------------
|
|
7
15
|
// Types
|
|
@@ -23,10 +31,12 @@ export interface TierConfig {
|
|
|
23
31
|
reasoning?: ReasoningConfig;
|
|
24
32
|
costRatio?: number;
|
|
25
33
|
color?: string;
|
|
26
|
-
|
|
34
|
+
/** Optional human-readable blurb shown in `/tiers` and the agent registration. */
|
|
35
|
+
description?: string;
|
|
27
36
|
steps?: number;
|
|
28
37
|
prompt?: string;
|
|
29
|
-
|
|
38
|
+
/** Optional use-case hints shown in `/tiers`. */
|
|
39
|
+
whenToUse?: string[];
|
|
30
40
|
}
|
|
31
41
|
|
|
32
42
|
export type Preset = Record<string, TierConfig>;
|
|
@@ -66,6 +76,14 @@ export interface RouterConfig {
|
|
|
66
76
|
/** Read-only tool-call caps per tier, enforced at runtime via tool.execute.after banner injection. */
|
|
67
77
|
tierCaps?: Record<string, number>;
|
|
68
78
|
enforcement?: EnforcementConfig;
|
|
79
|
+
/**
|
|
80
|
+
* Claude-model anti-narration guardrail. When true, appends the anti-narration
|
|
81
|
+
* clause to Claude orchestrator/tier prompts and runs the post-hoc narration
|
|
82
|
+
* detector. Off by default: the clause costs ~162 tokens per Claude dispatch
|
|
83
|
+
* and the detector is non-blocking telemetry that false-positives on normal
|
|
84
|
+
* "Now I'll add X" phrasing.
|
|
85
|
+
*/
|
|
86
|
+
antiNarration?: boolean;
|
|
69
87
|
/** Experimental, opt-in features. Off by default. */
|
|
70
88
|
experimental?: { verifiedDelegateTool?: boolean };
|
|
71
89
|
}
|
|
@@ -97,6 +115,92 @@ export function configPath(): string {
|
|
|
97
115
|
return join(getPluginRoot(), "tiers.json");
|
|
98
116
|
}
|
|
99
117
|
|
|
118
|
+
/**
|
|
119
|
+
* Path to the global user overrides file. Lives in the stable opencode config
|
|
120
|
+
* dir (next to the state file) so it survives plugin updates — unlike the
|
|
121
|
+
* bundled tiers.json, which sits in the cache dir and is overwritten on every
|
|
122
|
+
* update. Anything here is deep-merged over the bundled config.
|
|
123
|
+
*/
|
|
124
|
+
export function overridePath(): string {
|
|
125
|
+
return join(homedir(), ".config", "opencode", OVERRIDE_FILENAME);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Default location of the project-local overrides file
|
|
130
|
+
* (`.opencode/opencode-model-router.overrides.jsonc` in the current working
|
|
131
|
+
* directory). This is the path to *create* the file at; the actual lookup walks
|
|
132
|
+
* upward — see {@link findProjectOverride}. Used for display when no project
|
|
133
|
+
* file is found.
|
|
134
|
+
*
|
|
135
|
+
* The project file is deep-merged *after* (and therefore wins over) the global
|
|
136
|
+
* overrides file, so a team can commit a shared file that unifies routing for
|
|
137
|
+
* the project on top of each member's personal global file.
|
|
138
|
+
*/
|
|
139
|
+
export function localOverridePath(): string {
|
|
140
|
+
return join(process.cwd(), ".opencode", OVERRIDE_FILENAME);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Repo-root markers. Each is one-per-repository, so finding one means the
|
|
145
|
+
* ancestor is a project root. `package.json` is deliberately NOT a marker: in a
|
|
146
|
+
* monorepo, `<repo>/packages/app/package.json` would stop the walk before it
|
|
147
|
+
* ever reached `<repo>/.opencode/`.
|
|
148
|
+
*/
|
|
149
|
+
const REPO_MARKERS = [".git", ".hg", ".svn"] as const;
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Hard ceiling on how many levels the walk may climb above the starting
|
|
153
|
+
* directory. Deep working directories in a monorepo
|
|
154
|
+
* (`<repo>/packages/<pkg>/src/<area>/<sub>/…`) sit roughly 8 levels below the
|
|
155
|
+
* root, so 16 leaves generous headroom while keeping the walk bounded on trees
|
|
156
|
+
* that contain no repo marker at all.
|
|
157
|
+
*/
|
|
158
|
+
const MAX_WALK_DEPTH = 16;
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Locate the project-local overrides file by walking upward from the current
|
|
162
|
+
* working directory, so the project config is found even when opencode is
|
|
163
|
+
* launched from a subdirectory.
|
|
164
|
+
*
|
|
165
|
+
* The walk stops at the first of these, whichever comes first:
|
|
166
|
+
* - an ancestor containing a repo marker (`.git`, `.hg`, `.svn`), after
|
|
167
|
+
* checking that ancestor;
|
|
168
|
+
* - `MAX_WALK_DEPTH` levels above the starting directory;
|
|
169
|
+
* - the user's home directory, which is never treated as a project directory
|
|
170
|
+
* unless it is itself a repo root;
|
|
171
|
+
* - the filesystem root.
|
|
172
|
+
*
|
|
173
|
+
* The depth ceiling and the home-directory boundary matter because a directory
|
|
174
|
+
* tree with no repo marker anywhere would otherwise be walked all the way to the
|
|
175
|
+
* filesystem root, silently adopting an unrelated ancestor's override file.
|
|
176
|
+
* Returns the resolved path, or undefined when no file applies.
|
|
177
|
+
*/
|
|
178
|
+
export function findProjectOverride(): string | undefined {
|
|
179
|
+
let dir = process.cwd();
|
|
180
|
+
const home = homedir();
|
|
181
|
+
let depth = 0;
|
|
182
|
+
|
|
183
|
+
for (;;) {
|
|
184
|
+
const hasMarker = REPO_MARKERS.some((m) => existsSync(join(dir, m)));
|
|
185
|
+
|
|
186
|
+
// $HOME is not a project directory. Only look inside it when it is itself a
|
|
187
|
+
// repo root (a dotfiles repo), otherwise `~/.opencode/…` would be picked up
|
|
188
|
+
// by any unrelated scratch directory below it.
|
|
189
|
+
if (dir === home && !hasMarker) return undefined;
|
|
190
|
+
|
|
191
|
+
const candidate = join(dir, ".opencode", OVERRIDE_FILENAME);
|
|
192
|
+
if (existsSync(candidate)) return candidate;
|
|
193
|
+
|
|
194
|
+
if (hasMarker) return undefined; // reached the project root, no file
|
|
195
|
+
if (dir === home) return undefined; // home was a repo root; never go above it
|
|
196
|
+
if (++depth >= MAX_WALK_DEPTH) return undefined;
|
|
197
|
+
|
|
198
|
+
const parent = dirname(dir);
|
|
199
|
+
if (parent === dir) return undefined; // filesystem root
|
|
200
|
+
dir = parent;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
100
204
|
export function statePath(): string {
|
|
101
205
|
return join(
|
|
102
206
|
homedir(),
|
|
@@ -159,17 +263,20 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
159
263
|
);
|
|
160
264
|
}
|
|
161
265
|
const t = tier as Record<string, unknown>;
|
|
266
|
+
// `model` is the only required tier field — so an overrides file can define
|
|
267
|
+
// a new preset/tier with just `{ "model": "..." }`. The rest are optional
|
|
268
|
+
// and only type-checked when present.
|
|
162
269
|
if (typeof t.model !== "string" || !t.model) {
|
|
163
270
|
throw new Error(
|
|
164
271
|
`tiers.json: '${presetName}.${tierName}.model' must be a non-empty string`,
|
|
165
272
|
);
|
|
166
273
|
}
|
|
167
|
-
if (typeof t.description !== "string") {
|
|
274
|
+
if (t.description !== undefined && typeof t.description !== "string") {
|
|
168
275
|
throw new Error(
|
|
169
276
|
`tiers.json: '${presetName}.${tierName}.description' must be a string`,
|
|
170
277
|
);
|
|
171
278
|
}
|
|
172
|
-
if (!Array.isArray(t.whenToUse)) {
|
|
279
|
+
if (t.whenToUse !== undefined && !Array.isArray(t.whenToUse)) {
|
|
173
280
|
throw new Error(
|
|
174
281
|
`tiers.json: '${presetName}.${tierName}.whenToUse' must be an array`,
|
|
175
282
|
);
|
|
@@ -177,12 +284,33 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
177
284
|
}
|
|
178
285
|
}
|
|
179
286
|
|
|
287
|
+
// `activePreset` has to name a preset that actually exists. It is the key most
|
|
288
|
+
// likely to be typo'd in a hand-edited override file, and without this the bad
|
|
289
|
+
// name loads clean and routing quietly runs on whatever the state file or the
|
|
290
|
+
// bundled default left behind, with nothing said. Matching is case-insensitive
|
|
291
|
+
// to agree with resolvePresetName, which is what `/preset` uses.
|
|
292
|
+
const activePresetName = obj.activePreset as string;
|
|
293
|
+
const presetNames = Object.keys(presets);
|
|
294
|
+
const activeExists =
|
|
295
|
+
Object.prototype.hasOwnProperty.call(presets, activePresetName) ||
|
|
296
|
+
presetNames.some(
|
|
297
|
+
(n) => n.toLowerCase() === activePresetName.trim().toLowerCase(),
|
|
298
|
+
);
|
|
299
|
+
if (!activeExists) {
|
|
300
|
+
throw new Error(
|
|
301
|
+
`tiers.json: 'activePreset' is '${activePresetName}', which is not a defined preset (defined: ${presetNames.join(", ")})`,
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
|
|
180
305
|
if (!Array.isArray(obj.rules)) {
|
|
181
306
|
throw new Error("tiers.json: 'rules' must be an array of strings");
|
|
182
307
|
}
|
|
183
308
|
if (typeof obj.defaultTier !== "string") {
|
|
184
309
|
throw new Error("tiers.json: 'defaultTier' must be a string");
|
|
185
310
|
}
|
|
311
|
+
if (obj.antiNarration !== undefined && typeof obj.antiNarration !== "boolean") {
|
|
312
|
+
throw new Error("tiers.json: 'antiNarration' must be a boolean");
|
|
313
|
+
}
|
|
186
314
|
|
|
187
315
|
// Validate modes if present
|
|
188
316
|
if (obj.modes !== undefined) {
|
|
@@ -407,13 +535,169 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
407
535
|
return raw as RouterConfig;
|
|
408
536
|
}
|
|
409
537
|
|
|
538
|
+
/**
|
|
539
|
+
* Recursively merge `override` onto `base`. Plain objects merge key-by-key;
|
|
540
|
+
* arrays and scalars are replaced wholesale (so e.g. an overridden `rules` or
|
|
541
|
+
* `whenToUse` list replaces rather than appends). `undefined` values in the
|
|
542
|
+
* override are skipped so they never blow away a base value.
|
|
543
|
+
*/
|
|
544
|
+
export function deepMerge(base: unknown, override: unknown): unknown {
|
|
545
|
+
const isPlainObject = (v: unknown): v is Record<string, unknown> =>
|
|
546
|
+
typeof v === "object" && v !== null && !Array.isArray(v);
|
|
547
|
+
|
|
548
|
+
if (!isPlainObject(base) || !isPlainObject(override)) {
|
|
549
|
+
return override;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
const result: Record<string, unknown> = { ...base };
|
|
553
|
+
for (const [key, value] of Object.entries(override)) {
|
|
554
|
+
if (value === undefined) continue;
|
|
555
|
+
// `__proto__` from a parsed override would replace the merged object's own
|
|
556
|
+
// prototype rather than becoming a key. Whoever writes the config file can
|
|
557
|
+
// already do worse, so this is tidiness rather than a boundary, but a merge
|
|
558
|
+
// helper should not be the thing that reparents an object.
|
|
559
|
+
if (key === "__proto__" || key === "constructor") continue;
|
|
560
|
+
result[key] =
|
|
561
|
+
key in result && isPlainObject(result[key]) && isPlainObject(value)
|
|
562
|
+
? deepMerge(result[key], value)
|
|
563
|
+
: value;
|
|
564
|
+
}
|
|
565
|
+
return result;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* Read and parse the optional user overrides file. Returns the parsed object,
|
|
570
|
+
* or undefined when the file is absent/unreadable/invalid. Parse and shape
|
|
571
|
+
* errors are surfaced via console.warn (never thrown) so a typo in the
|
|
572
|
+
* overrides file can never brick opencode startup — but the user still gets a
|
|
573
|
+
* visible reason why their override was ignored.
|
|
574
|
+
*/
|
|
575
|
+
function readOverridesAt(op: string): Record<string, unknown> | undefined {
|
|
576
|
+
let text: string;
|
|
577
|
+
try {
|
|
578
|
+
if (!existsSync(op)) return undefined;
|
|
579
|
+
text = readFileSync(op, "utf-8");
|
|
580
|
+
} catch (err) {
|
|
581
|
+
// The file is there but unreadable (permissions, a dangling symlink, a
|
|
582
|
+
// race with a delete). Every other failure below says so; staying silent
|
|
583
|
+
// here makes an unreadable override look exactly like an absent one.
|
|
584
|
+
console.warn(
|
|
585
|
+
`[model-router] ignoring ${op}: cannot read it — ${(err as Error).message}`,
|
|
586
|
+
);
|
|
587
|
+
return undefined;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
try {
|
|
591
|
+
const parsed = parseJsonc(text) as unknown;
|
|
592
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
593
|
+
console.warn(
|
|
594
|
+
`[model-router] ignoring ${op}: expected a JSON object at root`,
|
|
595
|
+
);
|
|
596
|
+
return undefined;
|
|
597
|
+
}
|
|
598
|
+
return parsed as Record<string, unknown>;
|
|
599
|
+
} catch (err) {
|
|
600
|
+
console.warn(
|
|
601
|
+
`[model-router] ignoring ${op}: invalid JSONC — ${(err as Error).message}`,
|
|
602
|
+
);
|
|
603
|
+
return undefined;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/**
|
|
608
|
+
* The ordered override layers (lowest priority first): global, then
|
|
609
|
+
* project-local. Each present, well-formed file becomes a layer that is
|
|
610
|
+
* deep-merged over the ones before it.
|
|
611
|
+
*/
|
|
612
|
+
export interface OverrideLayer {
|
|
613
|
+
path: string;
|
|
614
|
+
data: Record<string, unknown>;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
function collectOverrideLayers(): OverrideLayer[] {
|
|
618
|
+
const layers: OverrideLayer[] = [];
|
|
619
|
+
// Lowest priority first: global, then project-local (found by upward search).
|
|
620
|
+
const paths = [overridePath(), findProjectOverride()];
|
|
621
|
+
for (const p of paths) {
|
|
622
|
+
if (!p) continue;
|
|
623
|
+
const data = readOverridesAt(p);
|
|
624
|
+
if (data) layers.push({ path: p, data });
|
|
625
|
+
}
|
|
626
|
+
return layers;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* Canonical per-tier defaults, keyed by the conventional tier names. These are
|
|
631
|
+
* the same values every bundled preset uses, so a preset defined in an overrides
|
|
632
|
+
* file with only `model` per tier gets a sensible cost ladder and turn budgets.
|
|
633
|
+
*/
|
|
634
|
+
const TIER_DEFAULTS: Record<string, { costRatio: number; steps: number }> = {
|
|
635
|
+
fast: { costRatio: 1, steps: 30 },
|
|
636
|
+
medium: { costRatio: 5, steps: 50 },
|
|
637
|
+
heavy: { costRatio: 20, steps: 120 },
|
|
638
|
+
};
|
|
639
|
+
const FALLBACK_TIER_DEFAULTS = { costRatio: 1, steps: 50 };
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* Fill in `costRatio`/`steps` for any tier that omits them, by tier name. Runs
|
|
643
|
+
* after merge so override-defined presets behave well without restating the
|
|
644
|
+
* conventional values; the effective numbers then show up in `/tiers` and the
|
|
645
|
+
* injected protocol. Bundled presets already set both, so this is a no-op there.
|
|
646
|
+
*/
|
|
647
|
+
function applyTierDefaults(cfg: RouterConfig): void {
|
|
648
|
+
for (const preset of Object.values(cfg.presets)) {
|
|
649
|
+
for (const [tierName, tier] of Object.entries(preset)) {
|
|
650
|
+
const d = TIER_DEFAULTS[tierName] ?? FALLBACK_TIER_DEFAULTS;
|
|
651
|
+
if (tier.costRatio === undefined) tier.costRatio = d.costRatio;
|
|
652
|
+
if (tier.steps === undefined) tier.steps = d.steps;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
410
657
|
export function loadConfig(): RouterConfig {
|
|
411
658
|
if (_cachedConfig && !_configDirty) {
|
|
412
659
|
return _cachedConfig;
|
|
413
660
|
}
|
|
414
661
|
|
|
415
|
-
const
|
|
416
|
-
const
|
|
662
|
+
const base = JSON.parse(readFileSync(configPath(), "utf-8"));
|
|
663
|
+
const layers = collectOverrideLayers();
|
|
664
|
+
|
|
665
|
+
// Bundled config must be valid on its own — throw otherwise (unchanged
|
|
666
|
+
// behaviour). Override layers are then applied on top.
|
|
667
|
+
let cfg = validateConfig(base);
|
|
668
|
+
|
|
669
|
+
if (layers.length > 0) {
|
|
670
|
+
const merge = (ls: OverrideLayer[]): unknown =>
|
|
671
|
+
ls.reduce<unknown>((acc, l) => deepMerge(acc, l.data), base);
|
|
672
|
+
|
|
673
|
+
try {
|
|
674
|
+
cfg = validateConfig(merge(layers));
|
|
675
|
+
} catch (err) {
|
|
676
|
+
// A bad override must never brick startup, and one broken file must not
|
|
677
|
+
// discard a good one. Fall back to the highest-priority layer that
|
|
678
|
+
// validates on its own (so a broken personal/global file still lets a
|
|
679
|
+
// shared project file apply), else the bundled defaults.
|
|
680
|
+
console.warn(
|
|
681
|
+
`[model-router] combined overrides are invalid (${(err as Error).message}); dropping conflicting layer(s)`,
|
|
682
|
+
);
|
|
683
|
+
for (let i = layers.length - 1; i >= 0; i--) {
|
|
684
|
+
try {
|
|
685
|
+
cfg = validateConfig(merge([layers[i]!]));
|
|
686
|
+
for (let j = 0; j < layers.length; j++) {
|
|
687
|
+
if (j !== i) {
|
|
688
|
+
console.warn(`[model-router] dropped override layer ${layers[j]!.path}`);
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
break;
|
|
692
|
+
} catch (singleErr) {
|
|
693
|
+
console.warn(
|
|
694
|
+
`[model-router] ignoring ${layers[i]!.path}: ${(singleErr as Error).message}`,
|
|
695
|
+
);
|
|
696
|
+
cfg = validateConfig(base);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
417
701
|
|
|
418
702
|
try {
|
|
419
703
|
if (existsSync(statePath())) {
|
|
@@ -437,6 +721,8 @@ export function loadConfig(): RouterConfig {
|
|
|
437
721
|
// Ignore state read errors and keep tiers.json defaults
|
|
438
722
|
}
|
|
439
723
|
|
|
724
|
+
applyTierDefaults(cfg);
|
|
725
|
+
|
|
440
726
|
_cachedConfig = cfg;
|
|
441
727
|
_configDirty = false;
|
|
442
728
|
return cfg;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// src/router/jsonc.ts — minimal JSONC support (comments + trailing commas).
|
|
3
|
+
//
|
|
4
|
+
// PURE, zero-dependency. `stripJsonc` removes `//` line comments, `/* */` block
|
|
5
|
+
// comments, and trailing commas before `}`/`]` — all string-aware, so a `//`,
|
|
6
|
+
// `/*`, or `,` inside a string value is preserved. `parseJsonc` then hands the
|
|
7
|
+
// cleaned text to JSON.parse. JSON is a subset of JSONC, so plain-JSON input
|
|
8
|
+
// passes through unchanged.
|
|
9
|
+
// ---------------------------------------------------------------------------
|
|
10
|
+
|
|
11
|
+
/** Remove comments and trailing commas from JSONC text (string-aware). */
|
|
12
|
+
export function stripJsonc(input: string): string {
|
|
13
|
+
let out = "";
|
|
14
|
+
let i = 0;
|
|
15
|
+
const n = input.length;
|
|
16
|
+
let inString = false;
|
|
17
|
+
|
|
18
|
+
while (i < n) {
|
|
19
|
+
const c = input[i]!;
|
|
20
|
+
|
|
21
|
+
if (inString) {
|
|
22
|
+
if (c === "\\" && i + 1 < n) {
|
|
23
|
+
out += c + input[i + 1]; // copy the escape pair verbatim
|
|
24
|
+
i += 2;
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
out += c;
|
|
28
|
+
if (c === '"') inString = false;
|
|
29
|
+
i++;
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (c === '"') {
|
|
34
|
+
inString = true;
|
|
35
|
+
out += c;
|
|
36
|
+
i++;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (c === "/" && input[i + 1] === "/") {
|
|
41
|
+
i += 2;
|
|
42
|
+
while (i < n && input[i] !== "\n") i++; // keep the newline
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (c === "/" && input[i + 1] === "*") {
|
|
47
|
+
i += 2;
|
|
48
|
+
while (i < n && !(input[i] === "*" && input[i + 1] === "/")) i++;
|
|
49
|
+
i += 2; // skip the closing */
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (c === ",") {
|
|
54
|
+
// Drop the comma if the next significant token (skipping whitespace and
|
|
55
|
+
// comments) closes an object or array.
|
|
56
|
+
let j = i + 1;
|
|
57
|
+
while (j < n) {
|
|
58
|
+
const d = input[j]!;
|
|
59
|
+
if (d === " " || d === "\t" || d === "\n" || d === "\r") {
|
|
60
|
+
j++;
|
|
61
|
+
} else if (d === "/" && input[j + 1] === "/") {
|
|
62
|
+
j += 2;
|
|
63
|
+
while (j < n && input[j] !== "\n") j++;
|
|
64
|
+
} else if (d === "/" && input[j + 1] === "*") {
|
|
65
|
+
j += 2;
|
|
66
|
+
while (j < n && !(input[j] === "*" && input[j + 1] === "/")) j++;
|
|
67
|
+
j += 2;
|
|
68
|
+
} else {
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (j < n && (input[j] === "}" || input[j] === "]")) {
|
|
73
|
+
i++; // trailing comma — skip it
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
out += c;
|
|
77
|
+
i++;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
out += c;
|
|
82
|
+
i++;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Parse JSONC text (comments + trailing commas tolerated) into a value. */
|
|
89
|
+
export function parseJsonc(text: string): unknown {
|
|
90
|
+
return JSON.parse(stripJsonc(text));
|
|
91
|
+
}
|
package/src/router/protocol.ts
CHANGED
|
@@ -111,44 +111,24 @@ export function buildDelegationProtocol(cfg: RouterConfig): string {
|
|
|
111
111
|
const fallback = buildFallbackInstructions(cfg);
|
|
112
112
|
|
|
113
113
|
return [
|
|
114
|
-
`## Model Delegation Protocol
|
|
114
|
+
`## Model Delegation Protocol (MANDATORY)`,
|
|
115
115
|
``,
|
|
116
|
-
`You are the orchestrator
|
|
116
|
+
`You are the orchestrator: route each task to the right tier and delegate it with \`Task(subagent_type="fast"|"medium"|"heavy", prompt="...")\`. Information-gathering (grep, read, glob, ls) is execution, so dispatch it to @fast rather than running it yourself; cap yourself at about 2 direct read-only calls per turn and dispatch @fast on the 3rd. Synthesize the subagents' results and answer the user yourself.`,
|
|
117
117
|
``,
|
|
118
118
|
`Preset: ${cfg.activePreset}. Tiers: ${tierLine}.${modeSuffix}`,
|
|
119
119
|
``,
|
|
120
|
-
|
|
121
|
-
`- **Read-only work** (grep, glob, read, ls, lookup, count, git-info, doc-lookup, type-check, exists-check) → default to \`Task(subagent_type="fast", ...)\`. Self-cap (TARGET): ≤2 direct read-only calls per user turn; on the 3rd read-only need, dispatch @fast instead. You may exceed with a 1-line \`reason:\` note when dispatching feels clearly wrong. Rationale: every tool-result token is billed at your tier rate — a grep via @fast costs ~20x less than the same grep here.`,
|
|
122
|
-
`- **Implementation work** (write, edit, refactor, tests, bug-fix, build-fix, create-file, config, api-endpoint) → \`Task(subagent_type="medium", ...)\`.`,
|
|
123
|
-
`- **Architecture / security / perf / debugging after ≥2 failures / multi-system tradeoffs / RCA** → \`Task(subagent_type="heavy", ...)\`, UNLESS you ARE @heavy (opus); then handle locally and never self-call @heavy.`,
|
|
124
|
-
``,
|
|
125
|
-
`### DISPATCH CAPS (read-only budget per subagent)`,
|
|
126
|
-
`Subagents carry a TARGET cap on their own read-only tool calls (baseline: @fast=8, @medium=5, @heavy=3). Include \`CAP:N\` in the dispatch prompt to override (e.g., \`CAP:3\` for a tight lookup, \`CAP:none\` to disable). Mode adjustments apply automatically via rules below. Subagents also run a redundancy check every call: if they detect repeated reads/greps of the same area, they STOP and return partial findings with \`DONE: ...\`, \`NEED MORE: ...\`, or \`ESCALATE: ...\` — you decide the next step from their return.`,
|
|
127
|
-
``,
|
|
128
|
-
`### ROLE CONTRACT`,
|
|
129
|
-
`The primary agent's job: decompose the user's request, dispatch subagents, synthesize their results, and answer the user. Keep orchestration-first posture: prefer dispatching read-only exploration to @fast rather than running repeated Grep/Read/Glob/Bash calls yourself. Self-cap applies (see HARD ROUTING above): ≤2 direct read-only calls per turn as a target; beyond that, dispatch @fast.`,
|
|
130
|
-
``,
|
|
131
|
-
`### @fast contract`,
|
|
132
|
-
`@fast is a read-only explorer. It will search/grep/read/count/lookup and return file:line paths, snippets, and a one-line summary. It will refuse edits. Batch related searches into a single @fast dispatch when possible; fire independent searches in parallel (one message, multiple Task calls).`,
|
|
133
|
-
``,
|
|
134
|
-
`### @medium contract`,
|
|
135
|
-
`@medium is the implementer. It writes, edits, refactors, adds tests, fixes bugs, applies build-fixes. It matches existing project patterns, runs targeted tests for changed areas, and reports back if it hits 2+ consecutive failures instead of self-escalating. Give it context: file paths, patterns to match, what verification to run.`,
|
|
136
|
-
``,
|
|
137
|
-
`### @heavy contract (CRITICAL — read before every @heavy dispatch)`,
|
|
138
|
-
`@heavy has **no Task tool** — it cannot self-explore, cannot grep, cannot delegate. Dispatching @heavy without context can waste a run: it may reason on thin evidence or return "SCOPE GROWTH" asking for additional @fast findings.`,
|
|
139
|
-
`**Before @heavy, gather context first — usually via @fast.** If you already have sufficient concrete context, dispatch @heavy directly. If @heavy still needs more evidence, collect it with @fast and re-invoke.`,
|
|
140
|
-
`Pattern: \`Task(@fast, "collect X, Y, Z")\` (when needed) → synthesize findings → \`Task(@heavy, "given these findings: [paste], analyze W")\`.`,
|
|
141
|
-
``,
|
|
142
|
-
`### CONFLICT WITH CLAUDE.md / AGENTS.md`,
|
|
143
|
-
`If CLAUDE.md or AGENTS.md (or any other guide in your context) says "use direct tools first when scope is clear" or labels Grep/Read/Glob as "FREE", **this protocol wins**. Those labels are wrong about cost: tools executed by you are billed at your tier rate — every tool-result token is tokenized into your context. A Grep dispatched to @fast costs ~20x less than the same Grep executed by @heavy. Treat yourself as expensive and delegate reads by default.`,
|
|
120
|
+
`If you ARE @heavy, handle heavy-tier work yourself: never self-call @heavy.`,
|
|
144
121
|
``,
|
|
145
122
|
...(taxonomy ? [taxonomy, ``] : []),
|
|
146
123
|
...(decompose ? [decompose, ``] : []),
|
|
147
|
-
|
|
148
|
-
rulesLine,
|
|
124
|
+
`Rules: ${rulesLine}`,
|
|
149
125
|
...(fallback ? [``, fallback] : []),
|
|
150
126
|
``,
|
|
151
|
-
`
|
|
127
|
+
`When dispatching: batch related @fast searches into one call and run independent ones in parallel (several Task calls in one message); give @medium concrete context (paths, patterns, how to verify).`,
|
|
128
|
+
``,
|
|
129
|
+
`Per dispatch you may add \`CAP:N\` (or \`CAP:none\`) to change a subagent's read-only budget (baseline @fast=8, @medium=5, @heavy=3). Subagents return \`DONE:\`, \`NEED MORE:\`, or \`ESCALATE:\` for you to act on. @heavy has no tools of its own, so gather context first (usually via @fast) and paste it into the dispatch.`,
|
|
130
|
+
``,
|
|
131
|
+
`This protocol overrides any project guide (CLAUDE.md, AGENTS.md, etc.) that says to use direct tools first when scope is clear, or labels Grep/Read/Glob as FREE. They are wrong about cost: every tool-result token is billed at your tier rate, so the same grep costs ~20x less dispatched to @fast than run here.`,
|
|
152
132
|
].join("\n");
|
|
153
133
|
}
|
|
154
134
|
|
|
@@ -300,7 +280,12 @@ export function assembleSystemPrompt(
|
|
|
300
280
|
): string {
|
|
301
281
|
const delegationProtocol = buildDelegationProtocol(cfg);
|
|
302
282
|
const dodSection = enforcementOn ? `\n\n---\n\n${buildDoDProtocolSection(cfg)}` : "";
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
283
|
+
if (!isClaudeModel(orchestratorModel)) {
|
|
284
|
+
return `${delegationProtocol}${dodSection}`;
|
|
285
|
+
}
|
|
286
|
+
// anti-narration clause is opt-in (cfg.antiNarration); off by default.
|
|
287
|
+
const claudePrefix = cfg.antiNarration
|
|
288
|
+
? `${CLAUDE_ORCHESTRATOR_PREFIX}\n\n${CLAUDE_ANTI_NARRATION}`
|
|
289
|
+
: CLAUDE_ORCHESTRATOR_PREFIX;
|
|
290
|
+
return `${claudePrefix}\n\n---\n\n${delegationProtocol}${dodSection}`;
|
|
306
291
|
}
|