opencode-model-router 1.1.16 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -579,6 +579,43 @@ Defines provider fallback order when a delegated task fails:
579
579
  }
580
580
  ```
581
581
 
582
+ ## Delegation enforcement (advisory by default)
583
+
584
+ 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 grows by ~200 tokens for the DoD/acceptance section, 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"`.
585
+
586
+ ### The three enforcement layers
587
+
588
+ - **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.
589
+ - **Layer 2 — independent acceptance gate.** Every 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.
590
+ - **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.
591
+
592
+ ### Two operating modes
593
+
594
+ - **Mode A — on-the-fly.** The orchestrator delegates through the native `Task()` tool — observed and verified automatically by the enforcement pipeline, and rendered inline in the TUI. (An optional, independently-verified `delegate` tool can be enabled via `experimental.verifiedDelegateTool` in `tiers.json` or `MODEL_ROUTER_VERIFIED_DELEGATE=1`; it is hidden by default so delegation stays visible.)
595
+ - **Mode B — plan-annotated.** `/annotate-plan` emits `[tier:X]` plus an `[acceptance]` block per task; the enforcement loop is wired up at execution time based on those annotations.
596
+
597
+ ### Tuning enforcement
598
+
599
+ Advisory is the default. To change the level:
600
+
601
+ 1. Add or edit the `enforcement` block in `tiers.json` — `"mode": "off"`, `"advisory"`, or `"enforced"` (see `docs/CONFIG_REFERENCE.md`).
602
+ 2. Set `MODEL_ROUTER_ENFORCE=1` to force `enforced` for a session, or `MODEL_ROUTER_ENFORCE=0` to force `off`.
603
+ 3. Run `/router enforce <off|advisory|enforced>` from the chat to toggle at runtime.
604
+
605
+ **Modes:** `off` — no-op, byte-for-byte-unchanged routing (must now be set explicitly, since `advisory` is the default); `advisory` (default) — evaluates and surfaces guidance, never blocks; `enforced` — hard-blocks active, full produce → verify → accept/escalate pipeline.
606
+
607
+ > Enforcement applies to subagent/delegate sessions only. The orchestrator session is never hard-blocked.
608
+
609
+ ### Deep-dive documentation
610
+
611
+ - `docs/ENFORCEMENT.md` — architecture, hook wiring, session lifecycle
612
+ - `docs/VERIFICATION.md` — DoD schema, deterministic checks, grader dispatch
613
+ - `docs/ESCALATION.md` — escalation ladder configuration and cost ceilings
614
+ - `docs/CONFIG_REFERENCE.md` — full `enforcement` block schema
615
+ - `docs/ENFORCEMENT_PRESETS.md` — ready-to-paste enforcement presets
616
+
617
+ > These files are not included in the npm tarball. This section is the self-contained summary; the docs are available in the repository for contributors and advanced users.
618
+
582
619
  ## Commands
583
620
 
584
621
  | Command | Description |
package/package.json CHANGED
@@ -1,9 +1,16 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "1.1.16",
3
+ "version": "1.3.0",
4
4
  "description": "OpenCode plugin that routes tasks to tiered subagents (fast/medium/heavy) based on complexity",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
7
+ "scripts": {
8
+ "test": "vitest run",
9
+ "test:watch": "vitest",
10
+ "test:coverage": "vitest run --coverage",
11
+ "smoke": "cross-env RUN_OC_SMOKE=1 vitest run --config vitest.smoke.config.ts test/smoke",
12
+ "typecheck": "tsc --noEmit"
13
+ },
7
14
  "license": "GPL-3.0-only",
8
15
  "repository": {
9
16
  "type": "git",
@@ -38,6 +45,9 @@
38
45
  },
39
46
  "devDependencies": {
40
47
  "@types/node": "^25.2.3",
41
- "typescript": "^5.9.3"
48
+ "@vitest/coverage-v8": "^3.2.4",
49
+ "cross-env": "^7.0.3",
50
+ "typescript": "^5.9.3",
51
+ "vitest": "^3.2.4"
42
52
  }
43
53
  }
@@ -0,0 +1,201 @@
1
+ import type { RouterConfig } from "../router/config";
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Types
5
+ // ---------------------------------------------------------------------------
6
+
7
+ export interface EscalatePolicy {
8
+ ladder: string[];
9
+ floorTier?: string | null;
10
+ maxAttemptsPerTier: number;
11
+ maxTotalAttempts: number;
12
+ costMultiple?: number | null;
13
+ }
14
+
15
+ export interface LadderState {
16
+ currentTier: string;
17
+ attemptsThisTier: number;
18
+ totalAttempts: number;
19
+ escalations: number;
20
+ firstAttemptCost: number | null;
21
+ cumulativeCost: number;
22
+ }
23
+
24
+ export type LadderActionKind = "accept" | "retry" | "escalate" | "give_up";
25
+
26
+ export interface LadderAction {
27
+ action: LadderActionKind;
28
+ tier?: string;
29
+ forcingMessage?: string;
30
+ reason?: string;
31
+ }
32
+
33
+ export interface LadderVerdict {
34
+ pass: boolean;
35
+ reasons?: string[];
36
+ }
37
+
38
+ // ---------------------------------------------------------------------------
39
+ // Helpers
40
+ // ---------------------------------------------------------------------------
41
+
42
+ export function tierRank(tier: string, ladder: string[]): number {
43
+ return ladder.indexOf(tier);
44
+ }
45
+
46
+ export function resolveStartTier(
47
+ producerTier: string,
48
+ policy: EscalatePolicy,
49
+ ): string {
50
+ const pi = tierRank(producerTier, policy.ladder);
51
+ const fi =
52
+ policy.floorTier != null ? tierRank(policy.floorTier, policy.ladder) : -1;
53
+ const startIdx = Math.max(pi >= 0 ? pi : 0, fi >= 0 ? fi : 0);
54
+ return policy.ladder[startIdx] ?? producerTier;
55
+ }
56
+
57
+ export function newLadderState(
58
+ producerTier: string,
59
+ policy: EscalatePolicy,
60
+ ): LadderState {
61
+ return {
62
+ currentTier: resolveStartTier(producerTier, policy),
63
+ attemptsThisTier: 0,
64
+ totalAttempts: 0,
65
+ escalations: 0,
66
+ firstAttemptCost: null,
67
+ cumulativeCost: 0,
68
+ };
69
+ }
70
+
71
+ export function recordAttempt(
72
+ state: LadderState,
73
+ costUnits = 0,
74
+ ): LadderState {
75
+ return {
76
+ ...state,
77
+ totalAttempts: state.totalAttempts + 1,
78
+ cumulativeCost: state.cumulativeCost + costUnits,
79
+ firstAttemptCost:
80
+ state.firstAttemptCost == null ? costUnits : state.firstAttemptCost,
81
+ };
82
+ }
83
+
84
+ export function nextTierAfter(
85
+ currentTier: string,
86
+ policy: EscalatePolicy,
87
+ ): string | null {
88
+ const ci = tierRank(currentTier, policy.ladder);
89
+ if (ci >= 0 && ci + 1 <= policy.ladder.length - 1) {
90
+ return policy.ladder[ci + 1]!;
91
+ }
92
+ return null;
93
+ }
94
+
95
+ export function buildLadderForcingMessage(reasons: string[]): string {
96
+ const list =
97
+ reasons.length === 0
98
+ ? "- (no reasons provided)"
99
+ : reasons.map((r) => `- ${r}`).join("\n");
100
+ return (
101
+ `[router escalation] previous attempt did not pass verification:\n` +
102
+ list +
103
+ `\nNEXT: retry with these failures addressed.`
104
+ );
105
+ }
106
+
107
+ export function nextAction(
108
+ state: LadderState,
109
+ verdict: LadderVerdict | null | undefined,
110
+ policy: EscalatePolicy,
111
+ ): LadderAction {
112
+ // (1) pass
113
+ if (verdict?.pass === true) {
114
+ return { action: "accept" };
115
+ }
116
+
117
+ // (2) cost check
118
+ const costExceeded =
119
+ policy.costMultiple != null &&
120
+ state.firstAttemptCost != null &&
121
+ state.cumulativeCost > state.firstAttemptCost * policy.costMultiple;
122
+
123
+ // (3) max total attempts
124
+ if (state.totalAttempts >= policy.maxTotalAttempts) {
125
+ return {
126
+ action: "give_up",
127
+ reason: `max total attempts (${policy.maxTotalAttempts}) reached`,
128
+ };
129
+ }
130
+
131
+ // (4) cost ceiling
132
+ if (costExceeded) {
133
+ return { action: "give_up", reason: "cost ceiling exceeded" };
134
+ }
135
+
136
+ // (5) retry within tier
137
+ if (state.attemptsThisTier < policy.maxAttemptsPerTier) {
138
+ return {
139
+ action: "retry",
140
+ tier: state.currentTier,
141
+ forcingMessage: buildLadderForcingMessage(verdict?.reasons ?? []),
142
+ };
143
+ }
144
+
145
+ // (6) escalate or give_up
146
+ const next = nextTierAfter(state.currentTier, policy);
147
+ if (next == null) {
148
+ return {
149
+ action: "give_up",
150
+ reason: "no higher tier (already at top of ladder)",
151
+ };
152
+ }
153
+ return {
154
+ action: "escalate",
155
+ tier: next,
156
+ forcingMessage: buildLadderForcingMessage(verdict?.reasons ?? []),
157
+ };
158
+ }
159
+
160
+ export function advance(state: LadderState, action: LadderAction): LadderState {
161
+ if (action.action === "retry") {
162
+ return { ...state, attemptsThisTier: state.attemptsThisTier + 1 };
163
+ }
164
+ if (action.action === "escalate") {
165
+ return {
166
+ ...state,
167
+ currentTier: action.tier!,
168
+ attemptsThisTier: 0,
169
+ escalations: state.escalations + 1,
170
+ };
171
+ }
172
+ // accept / give_up — terminal, return unchanged
173
+ return state;
174
+ }
175
+
176
+ export function buildEscalatePolicy(cfg: RouterConfig): EscalatePolicy {
177
+ const esc = cfg.enforcement?.escalate;
178
+ return {
179
+ ladder: esc?.ladder ?? ["fast", "medium", "heavy"],
180
+ floorTier: esc?.floorTier ?? null,
181
+ maxAttemptsPerTier: esc?.maxAttemptsPerTier ?? 1,
182
+ maxTotalAttempts: esc?.maxTotalAttempts ?? 4,
183
+ costMultiple: esc?.costCeiling?.multiple ?? 4,
184
+ };
185
+ }
186
+
187
+ /**
188
+ * One-line, secret-free scorecard for a finished delegation (counts only).
189
+ */
190
+ export function formatLadderScorecard(
191
+ state: LadderState,
192
+ accepted: boolean,
193
+ method: string,
194
+ ): string {
195
+ return (
196
+ `[router delegate scorecard | final_tier=${state.currentTier} | ` +
197
+ `attempts=${state.totalAttempts} | escalations=${state.escalations} | ` +
198
+ `cost=${state.cumulativeCost} | verdict=${accepted ? "PASS" : "UNMET"} | ` +
199
+ `method=${method}]`
200
+ );
201
+ }
@@ -0,0 +1,135 @@
1
+ import {
2
+ evaluateGuards,
3
+ updateState,
4
+ recordBlock,
5
+ forcingMessage,
6
+ observationOk,
7
+ } from "./guards";
8
+ import type { GuardPolicy, GuardCall, GuardState } from "./guards";
9
+ import { scrubText } from "./scrub";
10
+ import { resolveEnforcementMode } from "../router/enforcement";
11
+ import type { EnforcementMode } from "../router/enforcement";
12
+ import type { RouterConfig } from "../router/config";
13
+
14
+ /**
15
+ * Default total tool-call ceiling for an enforced subagent delegation. This is a
16
+ * hard budget (all tool calls), distinct from the read-only cap in tiers.json.
17
+ * Deliberately generous so enforced mode never false-stops ordinary work;
18
+ * tuned with field data in Phase 4.3 (preliminary).
19
+ */
20
+ export const DEFAULT_GUARD_BUDGET = 25;
21
+
22
+ export interface GuardStoreLike {
23
+ ensure(sessionID: string, policy: GuardPolicy): GuardState;
24
+ get(sessionID: string): GuardState | undefined;
25
+ setPendingNote(sessionID: string, note: string): void;
26
+ takePendingNote(sessionID: string): string | undefined;
27
+ }
28
+
29
+ /** Build a GuardPolicy from config for a given subagent tier. deliverableSignal
30
+ * is null in Wave 1 (Mode A/B signal wiring lands in Wave 2/4), which disables
31
+ * the deliverable-first clause — the honest common case (M5). */
32
+ export function buildGuardPolicy(cfg: RouterConfig, tier: string | null): GuardPolicy {
33
+ const g = cfg.enforcement?.guard ?? {};
34
+ return {
35
+ budget: g.budget ?? DEFAULT_GUARD_BUDGET,
36
+ readDraftCap: g.readDraftCap ?? 3,
37
+ sameOpRetryCap: g.sameOpRetryCap ?? 1,
38
+ blockSelfScript: g.blockSelfScript ?? true,
39
+ deliverableFirst: g.deliverableFirst ?? true,
40
+ blockScriptWrites: g.blockScriptWrites ?? false,
41
+ deliverableSignal: null,
42
+ };
43
+ }
44
+
45
+ export interface BeforeResult {
46
+ block: boolean;
47
+ message?: string;
48
+ mode: EnforcementMode;
49
+ guard?: string | null;
50
+ }
51
+
52
+ /** Compact per-delegation scorecard, emitted only when enforcement was active. */
53
+ export function formatScorecard(state: GuardState, tier: string | null): string {
54
+ const ttfa = state.ttfa == null ? "n/a" : String(state.ttfa);
55
+ return `[router scorecard | tier=${tier ?? "?"} | ttfa=${ttfa} | read:exec=${state.readCount}:${state.execCount} | self_scripts=${state.selfScriptCount} | tool_calls=${state.toolCallCount} | blocks=${state.blockedCount} | stop=${state.lastBlock ?? "none"}]`;
56
+ }
57
+
58
+ /**
59
+ * Decide whether a subagent tool call must be hard-blocked. The caller (the
60
+ * tool.execute.before hook) throws with `message` when block===true. In "off"
61
+ * mode this returns immediately WITHOUT creating guard state, so the after-hook
62
+ * stays a no-op and behaviour is byte-identical (GA-1).
63
+ */
64
+ export function guardBeforeCall(params: {
65
+ cfg: RouterConfig;
66
+ tier: string | null;
67
+ sessionID: string;
68
+ tool: string;
69
+ toolArgs: unknown;
70
+ store: GuardStoreLike;
71
+ env: Record<string, string | undefined>;
72
+ trivial?: boolean;
73
+ }): BeforeResult {
74
+ const { cfg, tier, sessionID, tool, toolArgs, store, env, trivial } = params;
75
+ let mode = resolveEnforcementMode({ config: cfg, tier: tier ?? undefined, env }).mode;
76
+ if (
77
+ mode === "enforced" &&
78
+ trivial === true &&
79
+ cfg.enforcement?.proportional?.trivialBypass !== false
80
+ ) {
81
+ mode = "advisory";
82
+ }
83
+ if (mode === "off") return { block: false, mode };
84
+
85
+ const policy = buildGuardPolicy(cfg, tier);
86
+ const state = store.ensure(sessionID, policy);
87
+ const call: GuardCall = { tool, args: (toolArgs ?? {}) as Record<string, unknown> };
88
+ const decision = evaluateGuards(state, call, policy);
89
+
90
+ if (decision.allow) return { block: false, mode, guard: null };
91
+
92
+ if (mode === "enforced") {
93
+ // Count the refused attempt so the budget cannot be spun, then signal a block.
94
+ updateState(state, call, { ok: false }, policy);
95
+ recordBlock(state, decision);
96
+ const message = scrubText(`${decision.observation}\n${forcingMessage(state, policy)}`);
97
+ return { block: true, mode, message, guard: decision.guard };
98
+ }
99
+
100
+ // advisory: never block; record the would-block and stash a banner the
101
+ // after-hook will append to this call's output.
102
+ recordBlock(state, decision);
103
+ store.setPendingNote(
104
+ sessionID,
105
+ scrubText(`[\u26a0 GUARD:${decision.guard}] ${forcingMessage(state, policy)}`),
106
+ );
107
+ return { block: false, mode, guard: decision.guard };
108
+ }
109
+
110
+ /**
111
+ * Update guard state after an ALLOWED call has executed (we now know ok), and
112
+ * surface any pending advisory banner by appending it to the tool output.
113
+ * No-op when guard state was never created (off mode) => GA-1 preserved.
114
+ */
115
+ export function guardAfterCall(params: {
116
+ cfg: RouterConfig;
117
+ tier: string | null;
118
+ sessionID: string;
119
+ tool: string;
120
+ toolArgs: unknown;
121
+ output: { output?: unknown };
122
+ store: GuardStoreLike;
123
+ }): void {
124
+ const { cfg, tier, sessionID, tool, toolArgs, output, store } = params;
125
+ const state = store.get(sessionID);
126
+ if (!state) return;
127
+ const policy = buildGuardPolicy(cfg, tier);
128
+ const call: GuardCall = { tool, args: (toolArgs ?? {}) as Record<string, unknown> };
129
+ updateState(state, call, { ok: observationOk(output?.output) }, policy);
130
+ const note = store.takePendingNote(sessionID);
131
+ if (note) {
132
+ const existing = typeof output.output === "string" ? output.output : "";
133
+ output.output = existing ? `${existing}\n\n${note}` : note;
134
+ }
135
+ }
@@ -0,0 +1,16 @@
1
+ /** Fingerprint a read-only tool call for redundancy detection. */
2
+ export function fingerprintToolCall(tool: string, args: unknown): string {
3
+ const a = (args ?? {}) as Record<string, unknown>;
4
+ switch (tool) {
5
+ case "read":
6
+ return `read:${a.file_path ?? a.filePath ?? ""}`;
7
+ case "grep":
8
+ return `grep:${a.pattern ?? ""}:${a.path ?? a.glob ?? ""}`;
9
+ case "glob":
10
+ return `glob:${a.pattern ?? ""}:${a.path ?? ""}`;
11
+ case "ls":
12
+ return `ls:${a.path ?? ""}`;
13
+ default:
14
+ return `${tool}:${JSON.stringify(a).slice(0, 120)}`;
15
+ }
16
+ }