opencode-model-router 1.5.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 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 2,970–4,540 characters of system-prompt overhead depending on the orchestrator and enforcement mode.
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 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.
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 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).
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 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.
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: 2,970–4,540 chars | ✅ | — | ❌ | ❌ | ❌ |
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
 
@@ -340,6 +340,37 @@ The plugin ships with four presets (switch with `/preset <name>`):
340
340
  | @medium | `google/gemini-2.5-pro` | 5x |
341
341
  | @heavy | `google/gemini-3-pro-preview` | 20x |
342
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
+
343
374
  ### Routing modes
344
375
 
345
376
  Switch with `/budget <mode>`. Mode is persisted across restarts.
@@ -443,10 +474,29 @@ Subagents carry a cap on their own read-only tool calls (grep/read/glob/ls) per
443
474
  The orchestrator can override any subagent's cap per dispatch by including a directive in the `Task` prompt:
444
475
 
445
476
  - `CAP:N` — tighten or loosen to N calls (e.g., `CAP:3` for a focused lookup).
446
- - `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.
447
478
 
448
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).
449
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
+
450
500
  #### Runtime enforcement (subagents only)
451
501
 
452
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.
@@ -539,9 +589,11 @@ Each tier (`@fast`, `@medium`, `@heavy`) has a system prompt that describes its
539
589
  **Resolution order per tier:**
540
590
 
541
591
  1. If the preset's tier defines `"prompt": "..."` inline → use it (per-tier override).
542
- 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>]`.
543
593
  3. If neither is set → the tier registers without a system prompt.
544
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
+
545
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.
546
598
 
547
599
  ```json
@@ -638,7 +690,8 @@ When `antiNarration` is enabled, the detector runs for all models (not only Clau
638
690
  | `reasoning` | object | OpenAI reasoning: `{ "effort": "high", "summary": "detailed" }` |
639
691
  | `description` | string | Shown in `/tiers` output |
640
692
  | `steps` | number | Max agent turns |
641
- | `prompt` | string | Optional per-tier system prompt override. Falls back to top-level `tierPrompts[<tierName>]` when omitted. |
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. |
642
695
  | `whenToUse` | string[] | Use cases (shown in `/tiers`, not in system prompt) |
643
696
 
644
697
  ### Fallback
@@ -731,12 +784,15 @@ After `/annotate-plan`:
731
784
 
732
785
  ## Token overhead
733
786
 
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.
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.
735
790
 
736
791
  | Version | Measured overhead | Features |
737
792
  |---------|-------------------|----------|
738
793
  | Before v1.4.0 | Earlier README token estimates were not measured and were inaccurate | Routing, caps, and enforcement evolved across releases |
739
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) |
740
796
 
741
797
  ## Requirements
742
798
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "1.5.0",
3
+ "version": "1.6.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",
@@ -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
+ }
@@ -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: g.budget ?? DEFAULT_GUARD_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,
@@ -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,
@@ -1,5 +1,11 @@
1
1
  import { newGuardState } from "./guards";
2
2
  import type { GuardState, GuardPolicy } from "./guards";
3
+ import { DEFAULT_IDLE_TTL_MS } from "../router/idle-sweep";
4
+
5
+ export interface GuardStoreOptions {
6
+ /** Injectable clock (tests). Defaults to Date.now. */
7
+ now?: () => number;
8
+ }
3
9
 
4
10
  /**
5
11
  * Per-plugin-instance store of guard state, keyed by sessionID. Mirrors the
@@ -7,12 +13,29 @@ import type { GuardState, GuardPolicy } from "./guards";
7
13
  * singletons, so concurrent subagent sessions never share mutable state (M7).
8
14
  * Also holds a per-session "pending note" used by advisory mode to defer a
9
15
  * banner from the before-hook to the after-hook (where output is mutable).
16
+ *
17
+ * Idle-TTL: every mutating entry point refreshes a per-session lastTouch stamp;
18
+ * `sweep()` evicts sessions idle for at least ttlMs. No timers.
10
19
  */
11
- export function createGuardStore() {
20
+ export function createGuardStore(options: GuardStoreOptions = {}) {
21
+ const now = options.now ?? Date.now;
12
22
  const states = new Map<string, GuardState>();
13
23
  const pendingNotes = new Map<string, string>();
24
+ const lastTouch = new Map<string, number>();
25
+
26
+ function touch(sessionID: string): void {
27
+ lastTouch.set(sessionID, now());
28
+ }
29
+
30
+ function evict(sessionID: string): void {
31
+ states.delete(sessionID);
32
+ pendingNotes.delete(sessionID);
33
+ lastTouch.delete(sessionID);
34
+ }
35
+
14
36
  return {
15
37
  ensure(sessionID: string, policy: GuardPolicy): GuardState {
38
+ touch(sessionID);
16
39
  let s = states.get(sessionID);
17
40
  if (!s) {
18
41
  s = newGuardState(policy);
@@ -24,16 +47,36 @@ export function createGuardStore() {
24
47
  return states.get(sessionID);
25
48
  },
26
49
  setPendingNote(sessionID: string, note: string): void {
50
+ touch(sessionID);
27
51
  pendingNotes.set(sessionID, note);
28
52
  },
29
53
  takePendingNote(sessionID: string): string | undefined {
54
+ touch(sessionID);
30
55
  const n = pendingNotes.get(sessionID);
31
56
  if (n !== undefined) pendingNotes.delete(sessionID);
32
57
  return n;
33
58
  },
59
+ /**
60
+ * Start a new dispatch round for an existing session: reset the
61
+ * per-dispatch tool-call count while preserving cumulative totals,
62
+ * redundancy fingerprints and deliverable state. No-op for sessions
63
+ * that were never guarded (nothing to reset).
64
+ */
65
+ beginDispatch(sessionID: string): void {
66
+ const s = states.get(sessionID);
67
+ if (!s) return;
68
+ s.toolCallCount = 0;
69
+ s.dispatches += 1;
70
+ touch(sessionID);
71
+ },
34
72
  clear(sessionID: string): void {
35
- states.delete(sessionID);
36
- pendingNotes.delete(sessionID);
73
+ evict(sessionID);
74
+ },
75
+ /** Evict every session idle for >= ttlMs. Future stamps are never evicted. */
76
+ sweep(nowMs: number = now(), ttlMs: number = DEFAULT_IDLE_TTL_MS): void {
77
+ for (const [sessionID, stamp] of [...lastTouch.entries()]) {
78
+ if (nowMs - stamp >= ttlMs) evict(sessionID);
79
+ }
37
80
  },
38
81
  };
39
82
  }