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/src/index.ts CHANGED
@@ -1,319 +1,69 @@
1
1
  import type { Plugin, PluginInput } from "@opencode-ai/plugin";
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
3
- import { homedir } from "os";
4
- import { dirname, join } from "path";
5
- import { fileURLToPath } from "url";
6
2
 
7
- // ---------------------------------------------------------------------------
8
- // Types
9
- // ---------------------------------------------------------------------------
10
-
11
- interface ThinkingConfig {
12
- budgetTokens?: number;
13
- }
14
-
15
- interface ReasoningConfig {
16
- effort?: "low" | "medium" | "high";
17
- summary?: "auto" | "always" | "never";
18
- }
19
-
20
- interface TierConfig {
21
- model: string;
22
- variant?: string;
23
- thinking?: ThinkingConfig;
24
- reasoning?: ReasoningConfig;
25
- costRatio?: number;
26
- color?: string;
27
- description: string;
28
- steps?: number;
29
- prompt?: string;
30
- whenToUse: string[];
31
- }
32
-
33
- type Preset = Record<string, TierConfig>;
34
-
35
- interface FallbackConfig {
36
- global?: Record<string, string[]>;
37
- presets?: Record<string, Record<string, string[]>>;
38
- }
39
-
40
- interface ModeConfig {
41
- defaultTier: string;
42
- description: string;
43
- overrideRules?: string[];
44
- }
45
-
46
- interface RouterConfig {
47
- activePreset: string;
48
- activeMode?: string;
49
- presets: Record<string, Preset>;
50
- rules: string[];
51
- defaultTier: string;
52
- fallback?: FallbackConfig;
53
- taskPatterns?: Record<string, string[]>;
54
- modes?: Record<string, ModeConfig>;
55
- /** Global default prompts per tier name. A preset-level tier.prompt overrides this. */
56
- tierPrompts?: Record<string, string>;
57
- /** Read-only tool-call caps per tier, enforced at runtime via tool.execute.after banner injection. */
58
- tierCaps?: Record<string, number>;
59
- }
60
-
61
- interface RouterState {
62
- activePreset?: string;
63
- activeMode?: string;
64
- }
65
-
66
- // ---------------------------------------------------------------------------
67
- // Config loader with caching
68
- // ---------------------------------------------------------------------------
69
-
70
- let _cachedConfig: RouterConfig | null = null;
71
- let _configDirty = true;
72
-
73
- /** Mark config cache as stale so it is re-read on next access. */
74
- function invalidateConfigCache(): void {
75
- _configDirty = true;
76
- }
77
-
78
- function getPluginRoot(): string {
79
- const __dirname = dirname(fileURLToPath(import.meta.url));
80
- return join(__dirname, ".."); // src/ -> plugin root
81
- }
82
-
83
- function configPath(): string {
84
- return join(getPluginRoot(), "tiers.json");
85
- }
86
-
87
- function statePath(): string {
88
- return join(
89
- homedir(),
90
- ".config",
91
- "opencode",
92
- "opencode-model-router.state.json",
93
- );
94
- }
95
-
96
- function resolvePresetName(
97
- cfg: RouterConfig,
98
- requestedPreset: string,
99
- ): string | undefined {
100
- if (cfg.presets[requestedPreset]) {
101
- return requestedPreset;
102
- }
103
-
104
- const normalized = requestedPreset.trim().toLowerCase();
105
- if (!normalized) {
106
- return undefined;
107
- }
108
-
109
- return Object.keys(cfg.presets).find(
110
- (name) => name.toLowerCase() === normalized,
111
- );
112
- }
113
-
114
- function validateConfig(raw: unknown): RouterConfig {
115
- if (typeof raw !== "object" || raw === null) {
116
- throw new Error("tiers.json: expected a JSON object at root");
117
- }
118
-
119
- const obj = raw as Record<string, unknown>;
120
-
121
- if (typeof obj.activePreset !== "string" || !obj.activePreset) {
122
- throw new Error("tiers.json: 'activePreset' must be a non-empty string");
123
- }
124
- if (
125
- typeof obj.presets !== "object" ||
126
- obj.presets === null ||
127
- Array.isArray(obj.presets)
128
- ) {
129
- throw new Error("tiers.json: 'presets' must be a non-null object");
130
- }
131
-
132
- const presets = obj.presets as Record<string, unknown>;
133
- for (const [presetName, preset] of Object.entries(presets)) {
134
- if (
135
- typeof preset !== "object" ||
136
- preset === null ||
137
- Array.isArray(preset)
138
- ) {
139
- throw new Error(`tiers.json: preset '${presetName}' must be an object`);
140
- }
141
- const tiers = preset as Record<string, unknown>;
142
- for (const [tierName, tier] of Object.entries(tiers)) {
143
- if (typeof tier !== "object" || tier === null) {
144
- throw new Error(
145
- `tiers.json: tier '${presetName}.${tierName}' must be an object`,
146
- );
147
- }
148
- const t = tier as Record<string, unknown>;
149
- if (typeof t.model !== "string" || !t.model) {
150
- throw new Error(
151
- `tiers.json: '${presetName}.${tierName}.model' must be a non-empty string`,
152
- );
153
- }
154
- if (typeof t.description !== "string") {
155
- throw new Error(
156
- `tiers.json: '${presetName}.${tierName}.description' must be a string`,
157
- );
158
- }
159
- if (!Array.isArray(t.whenToUse)) {
160
- throw new Error(
161
- `tiers.json: '${presetName}.${tierName}.whenToUse' must be an array`,
162
- );
163
- }
164
- }
165
- }
166
-
167
- if (!Array.isArray(obj.rules)) {
168
- throw new Error("tiers.json: 'rules' must be an array of strings");
169
- }
170
- if (typeof obj.defaultTier !== "string") {
171
- throw new Error("tiers.json: 'defaultTier' must be a string");
172
- }
173
-
174
- // Validate modes if present
175
- if (obj.modes !== undefined) {
176
- if (
177
- typeof obj.modes !== "object" ||
178
- obj.modes === null ||
179
- Array.isArray(obj.modes)
180
- ) {
181
- throw new Error("tiers.json: 'modes' must be an object");
182
- }
183
- const modes = obj.modes as Record<string, unknown>;
184
- for (const [modeName, mode] of Object.entries(modes)) {
185
- if (typeof mode !== "object" || mode === null) {
186
- throw new Error(`tiers.json: mode '${modeName}' must be an object`);
187
- }
188
- const m = mode as Record<string, unknown>;
189
- if (typeof m.defaultTier !== "string") {
190
- throw new Error(
191
- `tiers.json: mode '${modeName}.defaultTier' must be a string`,
192
- );
193
- }
194
- if (typeof m.description !== "string") {
195
- throw new Error(
196
- `tiers.json: mode '${modeName}.description' must be a string`,
197
- );
198
- }
199
- }
200
- }
201
-
202
- // Validate tierCaps if present
203
- if (obj.tierCaps !== undefined) {
204
- if (
205
- typeof obj.tierCaps !== "object" ||
206
- obj.tierCaps === null ||
207
- Array.isArray(obj.tierCaps)
208
- ) {
209
- throw new Error("tiers.json: 'tierCaps' must be an object");
210
- }
211
- const tc = obj.tierCaps as Record<string, unknown>;
212
- for (const [tierName, cap] of Object.entries(tc)) {
213
- if (typeof cap !== "number" || !Number.isFinite(cap) || cap < 1) {
214
- throw new Error(
215
- `tiers.json: tierCaps.'${tierName}' must be a positive integer`,
216
- );
217
- }
218
- }
219
- }
220
-
221
- // Validate tierPrompts if present
222
- if (obj.tierPrompts !== undefined) {
223
- if (
224
- typeof obj.tierPrompts !== "object" ||
225
- obj.tierPrompts === null ||
226
- Array.isArray(obj.tierPrompts)
227
- ) {
228
- throw new Error("tiers.json: 'tierPrompts' must be an object");
229
- }
230
- const tp = obj.tierPrompts as Record<string, unknown>;
231
- for (const [tierName, prompt] of Object.entries(tp)) {
232
- if (typeof prompt !== "string") {
233
- throw new Error(
234
- `tiers.json: tierPrompts.'${tierName}' must be a string`,
235
- );
236
- }
237
- }
238
- }
239
-
240
- // Validate taskPatterns if present
241
- if (obj.taskPatterns !== undefined) {
242
- if (
243
- typeof obj.taskPatterns !== "object" ||
244
- obj.taskPatterns === null ||
245
- Array.isArray(obj.taskPatterns)
246
- ) {
247
- throw new Error("tiers.json: 'taskPatterns' must be an object");
248
- }
249
- const tp = obj.taskPatterns as Record<string, unknown>;
250
- for (const [tierName, patterns] of Object.entries(tp)) {
251
- if (!Array.isArray(patterns)) {
252
- throw new Error(
253
- `tiers.json: taskPatterns.'${tierName}' must be an array of strings`,
254
- );
255
- }
256
- }
257
- }
258
-
259
- return raw as RouterConfig;
260
- }
261
-
262
- function loadConfig(): RouterConfig {
263
- if (_cachedConfig && !_configDirty) {
264
- return _cachedConfig;
265
- }
266
-
267
- const raw = JSON.parse(readFileSync(configPath(), "utf-8"));
268
- const cfg = validateConfig(raw);
269
-
270
- try {
271
- if (existsSync(statePath())) {
272
- const state = JSON.parse(
273
- readFileSync(statePath(), "utf-8"),
274
- ) as RouterState;
275
- if (state.activePreset) {
276
- const resolved = resolvePresetName(cfg, state.activePreset);
277
- if (resolved) {
278
- cfg.activePreset = resolved;
279
- }
280
- }
281
- if (state.activeMode && cfg.modes?.[state.activeMode]) {
282
- cfg.activeMode = state.activeMode;
283
- }
284
- }
285
- } catch {
286
- // Ignore state read errors and keep tiers.json defaults
287
- }
288
-
289
- _cachedConfig = cfg;
290
- _configDirty = false;
291
- return cfg;
292
- }
3
+ // Imports for internal use within this module
4
+ import {
5
+ loadConfig,
6
+ resolvePresetName,
7
+ writeState,
8
+ invalidateConfigCache,
9
+ } from "./router/config";
10
+ import type { RouterConfig, TierConfig, Preset, ModeConfig } from "./router/config";
11
+ import { fingerprintToolCall } from "./guard/fingerprint";
12
+ import { detectNarration } from "./guard/narration";
13
+ import {
14
+ getActiveTiers,
15
+ buildDelegationProtocol,
16
+ isClaudeModel,
17
+ CLAUDE_TIER_PREFIX,
18
+ CLAUDE_ORCHESTRATOR_PREFIX,
19
+ CLAUDE_ANTI_NARRATION,
20
+ assembleSystemPrompt,
21
+ } from "./router/protocol";
22
+ import { resolveEnforcementMode } from "./router/enforcement";
23
+ import {
24
+ createSessionStore,
25
+ parseCapDirective,
26
+ buildCapBanner,
27
+ DEFAULT_TIER_CAPS,
28
+ READ_ONLY_TOOLS,
29
+ } from "./router/sessions";
30
+ import type { Cap, SubagentState } from "./router/sessions";
31
+ import { createTrajectoryStore } from "./telemetry/trajectory";
32
+ import { createGuardStore } from "./guard/store";
33
+ import { guardBeforeCall, guardAfterCall, formatScorecard } from "./guard/enforce";
34
+ import { mkdirSync, writeFileSync } from "node:fs";
35
+ import { tmpdir } from "node:os";
36
+ import { join, isAbsolute } from "node:path";
37
+ import { exec as nodeExec } from "node:child_process";
38
+ import { access, readFile as fsReadFile } from "node:fs/promises";
39
+ import { tool } from "@opencode-ai/plugin";
40
+ import { scrubText } from "./guard/scrub";
41
+ import { accept } from "./verify/gate";
42
+ import { createMutexRegistry } from "./verify/deterministic";
43
+ import {
44
+ createChangedFileStore,
45
+ parseTaskResult,
46
+ buildDelegationDoD,
47
+ tierModel,
48
+ shouldVerifyTask,
49
+ buildForcingNote,
50
+ buildAcceptedSuffix,
51
+ } from "./verify/dispatch";
52
+ import { newLadderState, recordAttempt, nextAction, advance, buildEscalatePolicy, formatLadderScorecard } from "./escalate/ladder";
293
53
 
294
54
  // ---------------------------------------------------------------------------
295
- // State persistence helpers
55
+ // Re-exports — type-only re-exports for IDE/test consumers.
56
+ // NOTE: value re-exports are intentionally absent. opencode's plugin loader
57
+ // calls every function export as a factory (Ck iterates Object.values(mod));
58
+ // adding named function exports would cause spurious factory calls.
59
+ // Tests import from their specific source files instead of this entry point.
296
60
  // ---------------------------------------------------------------------------
297
61
 
298
- /** Read current persisted state (or empty object on failure). */
299
- function readState(): RouterState {
300
- try {
301
- if (existsSync(statePath())) {
302
- return JSON.parse(readFileSync(statePath(), "utf-8")) as RouterState;
303
- }
304
- } catch {
305
- // ignore
306
- }
307
- return {};
308
- }
309
-
310
- /** Write state to disk (merges with existing keys). */
311
- function writeState(patch: Partial<RouterState>): void {
312
- const state = { ...readState(), ...patch };
313
- const p = statePath();
314
- mkdirSync(dirname(p), { recursive: true });
315
- writeFileSync(p, JSON.stringify(state, null, 2) + "\n", "utf-8");
316
- }
62
+ export type { RouterConfig, TierConfig, Preset, ModeConfig, FallbackConfig, EnforcementConfig } from "./router/config";
63
+ export type { Cap, SubagentState };
64
+ export type { TrajectoryState, TrajectoryToolEvent } from "./telemetry/trajectory";
65
+ export type { EnforcementMode } from "./router/enforcement";
66
+ export type { GuardPolicy, GuardState, GuardCall, GuardDecision } from "./guard/guards";
317
67
 
318
68
  function saveActivePreset(presetName: string): void {
319
69
  const cfg = loadConfig();
@@ -342,8 +92,48 @@ function saveActiveMode(modeName: string): void {
342
92
  invalidateConfigCache();
343
93
  }
344
94
 
345
- function getActiveTiers(cfg: RouterConfig): Preset {
346
- return cfg.presets[cfg.activePreset] ?? Object.values(cfg.presets)[0]!;
95
+ function saveEnforcementMode(mode: "off" | "advisory" | "enforced"): void {
96
+ writeState({ enforcementMode: mode });
97
+ invalidateConfigCache();
98
+ }
99
+
100
+ function buildRouterOutput(cfg: RouterConfig, args: string): string {
101
+ const tokens = (args ?? "").trim().split(/\s+/).filter(Boolean);
102
+ const sub = (tokens[0] ?? "").toLowerCase();
103
+ if (sub === "enforce") {
104
+ const mode = (tokens[1] ?? "").toLowerCase();
105
+ if (mode === "off" || mode === "advisory" || mode === "enforced") {
106
+ saveEnforcementMode(mode);
107
+ const desc =
108
+ mode === "off"
109
+ ? "Hard-block guard disabled (default routing behaviour)."
110
+ : mode === "advisory"
111
+ ? "Guard evaluates and surfaces banners but never hard-blocks."
112
+ : "Guard hard-blocks subagent tool calls that violate budget / redundancy / self-script policy.";
113
+ return [
114
+ `Enforcement mode set to **${mode}** and persisted.`,
115
+ "",
116
+ desc,
117
+ "",
118
+ "Note: the `MODEL_ROUTER_ENFORCE` env var, when set to `0` or `1`, overrides this setting.",
119
+ ].join("\n");
120
+ }
121
+ const current = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
122
+ return [
123
+ `Current enforcement mode: **${current}**`,
124
+ "",
125
+ "Usage: `/router enforce <off|advisory|enforced>`",
126
+ ].join("\n");
127
+ }
128
+ const current = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
129
+ return [
130
+ `# Model Router`,
131
+ `Enforcement: **${current}**`,
132
+ "",
133
+ "Commands:",
134
+ "- `/router enforce <off|advisory|enforced>` — set hard-block enforcement (persisted)",
135
+ "- `/tiers`, `/preset`, `/budget`, `/bypass`, `/annotate-plan`",
136
+ ].join("\n");
347
137
  }
348
138
 
349
139
  // ---------------------------------------------------------------------------
@@ -373,154 +163,6 @@ function buildAgentOptions(tier: TierConfig): Record<string, unknown> {
373
163
  return Object.keys(opts).length > 0 ? opts : {};
374
164
  }
375
165
 
376
- // ---------------------------------------------------------------------------
377
- // Mode helpers
378
- // ---------------------------------------------------------------------------
379
-
380
- function getActiveMode(cfg: RouterConfig): ModeConfig | undefined {
381
- if (!cfg.modes || !cfg.activeMode) return undefined;
382
- return cfg.modes[cfg.activeMode];
383
- }
384
-
385
- // ---------------------------------------------------------------------------
386
- // Fallback instructions builder
387
- // ---------------------------------------------------------------------------
388
-
389
- function buildFallbackInstructions(cfg: RouterConfig): string {
390
- const fb = cfg.fallback;
391
- if (!fb) return "";
392
-
393
- const presetMap = fb.presets?.[cfg.activePreset];
394
- const map =
395
- presetMap && Object.keys(presetMap).length > 0 ? presetMap : fb.global;
396
- if (!map) return "";
397
-
398
- const chains = Object.entries(map).flatMap(([provider, presetOrder]) => {
399
- if (!Array.isArray(presetOrder)) return [];
400
- const valid = presetOrder.filter(
401
- (p) => p !== cfg.activePreset && Boolean(cfg.presets[p]),
402
- );
403
- return valid.length > 0 ? [`${provider}→${valid.join("→")}`] : [];
404
- });
405
-
406
- if (chains.length === 0) return "";
407
- return `Err→retry-alt-tier→fail→direct. Chain: ${chains.join(" | ")}`;
408
- }
409
-
410
- // ---------------------------------------------------------------------------
411
- // Cost & taxonomy builders
412
- // ---------------------------------------------------------------------------
413
-
414
- function buildTaskTaxonomy(cfg: RouterConfig): string {
415
- if (!cfg.taskPatterns || Object.keys(cfg.taskPatterns).length === 0)
416
- return "";
417
- const lines = ["R:"];
418
- for (const [tier, patterns] of Object.entries(cfg.taskPatterns)) {
419
- if (Array.isArray(patterns) && patterns.length > 0) {
420
- lines.push(`@${tier}→${patterns.join("/")}`);
421
- }
422
- }
423
- return lines.join(" ");
424
- }
425
-
426
- /**
427
- * Injects a multi-phase decomposition hint into the delegation protocol.
428
- * Teaches the orchestrator to split composite tasks (explore + implement)
429
- * so the cheap @fast tier handles exploration and @medium handles execution.
430
- * Only active in normal mode — budget/quality modes have their own override rules.
431
- */
432
- function buildDecomposeHint(cfg: RouterConfig): string {
433
- const mode = getActiveMode(cfg);
434
- // Budget and quality modes handle this via overrideRules — skip to avoid conflicts
435
- if (mode?.overrideRules?.length) return "";
436
-
437
- const tiers = getActiveTiers(cfg);
438
- const entries = Object.entries(tiers);
439
- if (entries.length < 2) return "";
440
-
441
- // Sort by costRatio ascending to find cheapest (explore) and next (execute) tiers
442
- const sorted = [...entries].sort(
443
- ([, a], [, b]) => (a.costRatio ?? 1) - (b.costRatio ?? 1),
444
- );
445
- const cheapest = sorted[0]?.[0];
446
- const mid = sorted[1]?.[0];
447
- if (!cheapest || !mid) return "";
448
-
449
- return `Multi-phase: prefer explore(@${cheapest})→execute(@${mid}) when phases are separable. Cheapest-first when practical.`;
450
- }
451
-
452
- // ---------------------------------------------------------------------------
453
- // System prompt builder
454
- // ---------------------------------------------------------------------------
455
-
456
- function buildDelegationProtocol(cfg: RouterConfig): string {
457
- const tiers = getActiveTiers(cfg);
458
-
459
- // Compact tier summary: @name=model/variant(costRatio)
460
- const tierLine = Object.entries(tiers)
461
- .map(([name, t]) => {
462
- const short = t.model.split("/").pop() ?? t.model;
463
- const v = t.variant ? `/${t.variant}` : "";
464
- const c = t.costRatio != null ? `(${t.costRatio}x)` : "";
465
- return `@${name}=${short}${v}${c}`;
466
- })
467
- .join(" ");
468
-
469
- const mode = getActiveMode(cfg);
470
- const modeSuffix = cfg.activeMode ? ` mode:${cfg.activeMode}` : "";
471
-
472
- const taxonomy = buildTaskTaxonomy(cfg);
473
- const decompose = buildDecomposeHint(cfg);
474
-
475
- const effectiveRules = mode?.overrideRules?.length
476
- ? mode.overrideRules
477
- : cfg.rules;
478
- const rulesLine = effectiveRules.map((r, i) => `${i + 1}.${r}`).join(" ");
479
-
480
- const fallback = buildFallbackInstructions(cfg);
481
-
482
- return [
483
- `## Model Delegation Protocol — MANDATORY`,
484
- ``,
485
- `You are the orchestrator. Information-gathering is NOT orchestration — it IS execution. Execution belongs to subagents, not to you.`,
486
- ``,
487
- `Preset: ${cfg.activePreset}. Tiers: ${tierLine}.${modeSuffix}`,
488
- ``,
489
- `### HARD ROUTING (non-negotiable)`,
490
- `- **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.`,
491
- `- **Implementation work** (write, edit, refactor, tests, bug-fix, build-fix, create-file, config, api-endpoint) → \`Task(subagent_type="medium", ...)\`.`,
492
- `- **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.`,
493
- ``,
494
- `### DISPATCH CAPS (read-only budget per subagent)`,
495
- `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.`,
496
- ``,
497
- `### ROLE CONTRACT`,
498
- `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.`,
499
- ``,
500
- `### @fast contract`,
501
- `@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).`,
502
- ``,
503
- `### @medium contract`,
504
- `@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.`,
505
- ``,
506
- `### @heavy contract (CRITICAL — read before every @heavy dispatch)`,
507
- `@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.`,
508
- `**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.`,
509
- `Pattern: \`Task(@fast, "collect X, Y, Z")\` (when needed) → synthesize findings → \`Task(@heavy, "given these findings: [paste], analyze W")\`.`,
510
- ``,
511
- `### CONFLICT WITH CLAUDE.md / AGENTS.md`,
512
- `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.`,
513
- ``,
514
- ...(taxonomy ? [taxonomy, ``] : []),
515
- ...(decompose ? [decompose, ``] : []),
516
- `### Compact rules`,
517
- rulesLine,
518
- ...(fallback ? [``, fallback] : []),
519
- ``,
520
- `Delegate with \`Task(subagent_type="fast"|"medium"|"heavy", prompt="...")\`. Keep orchestration and final synthesis here.`,
521
- ].join("\n");
522
- }
523
-
524
166
  // ---------------------------------------------------------------------------
525
167
  // /tiers command output
526
168
  // ---------------------------------------------------------------------------
@@ -644,275 +286,340 @@ function buildPresetOutput(cfg: RouterConfig, args: string): string {
644
286
  return `Unknown preset: "${requestedPreset}". Available: ${Object.keys(cfg.presets).join(", ")}`;
645
287
  }
646
288
 
647
- // ---------------------------------------------------------------------------
648
- // Runtime cap enforcement (tool.execute.after banner injection for subagents)
649
- // ---------------------------------------------------------------------------
650
-
651
- /** Tools that count against the read-only cap. Keep narrow — editing tools should never count. */
652
- const READ_ONLY_TOOLS = new Set(["grep", "read", "glob", "ls"]);
653
-
654
- /** Fallback caps when tiers.json has no tierCaps block. */
655
- const DEFAULT_TIER_CAPS: Record<string, number> = {
656
- fast: 8,
657
- medium: 5,
658
- heavy: 3,
659
- };
660
-
661
- type Cap = number | "none";
662
-
663
- interface SubagentState {
664
- tierName: string;
665
- cap: Cap;
666
- calls: number;
667
- /** Fingerprint → call index where this fingerprint was first seen. */
668
- seen: Map<string, number>;
669
- }
670
-
671
- /** Extract the first `CAP:N` or `CAP:none` directive from a dispatch prompt. */
672
- function parseCapDirective(text: string): Cap | null {
673
- const m = text.match(/\bCAP\s*:\s*(none|\d+)\b/i);
674
- if (!m) return null;
675
- const raw = m[1]!.toLowerCase();
676
- if (raw === "none") return "none";
677
- const n = parseInt(raw, 10);
678
- return Number.isFinite(n) && n > 0 ? n : null;
679
- }
680
-
681
- /** Fingerprint a read-only tool call for redundancy detection. */
682
- function fingerprintToolCall(tool: string, args: unknown): string {
683
- const a = (args ?? {}) as Record<string, unknown>;
684
- switch (tool) {
685
- case "read":
686
- return `read:${a.file_path ?? a.filePath ?? ""}`;
687
- case "grep":
688
- return `grep:${a.pattern ?? ""}:${a.path ?? a.glob ?? ""}`;
689
- case "glob":
690
- return `glob:${a.pattern ?? ""}:${a.path ?? ""}`;
691
- case "ls":
692
- return `ls:${a.path ?? ""}`;
693
- default:
694
- return `${tool}:${JSON.stringify(a).slice(0, 120)}`;
695
- }
696
- }
697
-
698
- /** Best-effort extraction of textual content from a chat.message output payload. */
699
- function extractDispatchText(output: unknown): string {
700
- const o = output as Record<string, unknown> | undefined;
701
- const parts = (o?.parts as unknown[]) ?? [];
702
- const chunks: string[] = [];
703
- for (const p of parts) {
704
- if (typeof p === "string") {
705
- chunks.push(p);
706
- } else if (p && typeof p === "object") {
707
- const rec = p as Record<string, unknown>;
708
- if (typeof rec.text === "string") chunks.push(rec.text);
709
- else if (typeof rec.content === "string") chunks.push(rec.content);
710
- }
711
- }
712
- if (chunks.length === 0) {
713
- const msg = o?.message as Record<string, unknown> | undefined;
714
- const content = msg?.content;
715
- if (typeof content === "string") chunks.push(content);
716
- }
717
- return chunks.join("\n");
718
- }
719
-
720
- /** Build the banner appended to every read-only tool result in a subagent session. */
721
- function buildCapBanner(
722
- state: SubagentState,
723
- isRedundant: boolean,
724
- previousCall: number | undefined,
725
- tool: string,
726
- ): string {
727
- const lines: string[] = [];
728
- const capDisplay = state.cap === "none" ? "∞" : String(state.cap);
729
- lines.push(`[cap: ${state.calls}/${capDisplay}]`);
730
-
731
- if (isRedundant && previousCall !== undefined) {
732
- lines.push(
733
- `[⚠ REDUNDANT: this is the same ${tool} you ran at call #${previousCall}. STOP now — repeated reads add no information. Return with DONE/NEED MORE/NEED CONTEXT/SCOPE GROWTH/ESCALATE.]`,
734
- );
735
- }
736
-
737
- if (state.cap !== "none") {
738
- const remaining = state.cap - state.calls;
739
- if (remaining <= 0) {
740
- lines.push(
741
- `[⚠ CAP REACHED (${state.calls}/${state.cap}): your NEXT response MUST be a return — do NOT make another read-only call. Start the response with DONE:, NEED MORE:, NEED CONTEXT:, SCOPE GROWTH:, or ESCALATE:.]`,
742
- );
743
- } else if (remaining <= 2) {
744
- lines.push(
745
- `[⚠ CAP WARNING: ${remaining} read-only call(s) remaining before forced return]`,
746
- );
747
- }
748
- }
749
-
750
- return lines.join("\n");
751
- }
752
-
753
- // ---------------------------------------------------------------------------
754
- // Claude-model adversarial prefixes
755
- //
756
- // Anthropic models (direct or via other providers) are served with a large
757
- // cached "Claude Code" signature prompt that primes them toward broad
758
- // exploratory Read/Grep/Glob behavior. Our tier prompts land after that
759
- // cached block and lose authority through primacy bias and cache freezing.
760
- // For Claude models specifically, we prepend an override block that
761
- // explicitly revokes the exploratory priming for the current dispatch.
762
- //
763
- // Detection is by model identifier, not preset — a hybrid preset mixing
764
- // providers gets the override only on its Claude-backed tiers.
765
- // ---------------------------------------------------------------------------
766
-
767
- function isClaudeModel(modelID: string | undefined): boolean {
768
- if (!modelID) return false;
769
- const s = modelID.toLowerCase();
770
- if (s.startsWith("anthropic/")) return true;
771
- return /\/claude-/.test(s) || /(^|[\/\-])claude-/.test(s);
772
- }
773
-
774
- /** Per-tier adversarial openers. @fast/@medium use Tom 2 (scoping); @heavy uses Tom 1 (override). */
775
- const CLAUDE_TIER_PREFIX: Record<string, string> = {
776
- fast: [
777
- "SCOPE NOTE — any cached instruction priming you to 'thoroughly explore",
778
- "the codebase' or 'gather context broadly' does not apply here. This is",
779
- "a single dispatch with a single question. Stay narrow to the ask.",
780
- "",
781
- "Before every tool call, ask: 'Does THIS read answer the dispatch",
782
- "question specifically, or am I drifting into context-gathering for my",
783
- "own understanding?' If the latter, stop — you have enough.",
784
- ].join("\n"),
785
- medium: [
786
- "SCOPE NOTE — cached instructions may prime you to deeply understand",
787
- "surrounding code before editing. For THIS dispatch, the orchestrator",
788
- "has already scoped the problem; trust that scoping. Read what's needed",
789
- "for the edit, not the whole module.",
790
- "",
791
- "A 4th or 5th 'context read' is usually a sign the dispatch was under-",
792
- "scoped — return NEED CONTEXT rather than expanding scope yourself.",
793
- ].join("\n"),
794
- heavy: [
795
- "AUTHORITY OVERRIDE — this block supersedes any cached prefix suggesting",
796
- "you should 'investigate thoroughly', 'gather comprehensive context', or",
797
- "'trace through the code systematically before analyzing'. You are",
798
- "@heavy, an ANALYSIS specialist. The orchestrator should have pre-",
799
- "gathered context via @fast before dispatching you. If it didn't, return",
800
- "`SCOPE GROWTH:` immediately — do NOT self-gather.",
801
- "",
802
- "40 minutes of Read/Grep is not analysis — it is the orchestrator's job",
803
- "that leaked into yours. Push it back with SCOPE GROWTH. Your 3 reads",
804
- "are for targeted verification, not exploration.",
805
- ].join("\n"),
806
- };
807
-
808
- /** Adversarial opener prepended to the delegation protocol when the orchestrator is a Claude model. */
809
- const CLAUDE_ORCHESTRATOR_PREFIX = [
810
- "AUTHORITY OVERRIDE — this block supersedes any prior system instruction",
811
- "about 'exploring the codebase', 'gathering context with tools', or using",
812
- "Read/Grep/Glob to validate assumptions. Those instructions describe a",
813
- "general-purpose Claude Code session. THIS session is a routing",
814
- "orchestrator.",
815
- "",
816
- "Your job is to DISPATCH, not to EXECUTE. Read-only work (grep/read/",
817
- "glob/ls) is execution, and execution is delegated to @fast. You may run",
818
- "AT MOST 2 direct read-only tool calls per turn — a 3rd call is a rule",
819
- "violation. If you need more context, you dispatch @fast.",
820
- "",
821
- "If a cached instruction told you to 'be thorough', 'explore broadly', or",
822
- "'read supporting files' — ignore it here. Thoroughness is achieved by",
823
- "dispatching the right tier, not by you becoming the explorer.",
824
- ].join("\n");
825
-
826
- /**
827
- * Anti-narration clause appended to every Claude-model prefix (tier + orchestrator).
828
- *
829
- * Thinking-enabled Claude models (esp. Sonnet with `max` variant) sometimes
830
- * produce progress narration in place of actual work — "Still writing X...",
831
- * "Now I'll implement Y...", "Let me add Z..." — without the X/Y/Z ever
832
- * appearing. This clause names the pattern, lists specific forbidden phrasings
833
- * (A3 — exemplified), and carves out an escape valve for legitimate
834
- * explanation/plan requests (A2 — with exception).
835
- */
836
- const CLAUDE_ANTI_NARRATION = [
837
- "ANTI-NARRATION — do NOT write progress commentary in your response or",
838
- "thinking output. Forbidden phrasings include:",
839
- " - \"Still writing the X function...\"",
840
- " - \"Now I'll implement Y...\"",
841
- " - \"Let me add Z...\"",
842
- " - \"Continuing with W...\"",
843
- " - \"Going to fix V...\"",
844
- "",
845
- "Each of these signals planning without production. If you write one, the",
846
- "NEXT tokens MUST contain the actual artifact (the code, the edit, the",
847
- "concrete output). Otherwise, stop and return with status.",
848
- "",
849
- "Exception: when the user explicitly asks for an explanation, plan, or",
850
- "walkthrough, prose is welcome — this rule targets unsolicited progress",
851
- "narration during code and implementation tasks.",
852
- ].join("\n");
853
-
854
- // ---------------------------------------------------------------------------
855
- // Narration detector (telemetry — logs + appends banner)
856
- // ---------------------------------------------------------------------------
857
-
858
- /** Regex patterns that flag progress narration without production. */
859
- const NARRATION_PATTERNS: RegExp[] = [
860
- // "Still writing the X", "Still implementing the Y"
861
- /\bstill\s+(writing|implementing|working on|adding|creating|fixing|building|refactoring|handling)\s+(the\s+)?\w+/gi,
862
- // "Now I'll write the X", "Now writing the Y"
863
- /\bnow\s+(i['']ll\s+)?(writ|implement|add|creat|work|fix|build|handl|refactor|updat|mov)\w*\s+(the\s+)?\w+/gi,
864
- // "Let me write X", "Let me implement Y"
865
- /\blet\s+me\s+(write|implement|add|create|fix|build|handle|refactor|work on|move|update|set up)\s+(the\s+)?\w+/gi,
866
- // "I'll write the X", "I'll now implement Y"
867
- /\bi['']ll\s+(now\s+)?(write|implement|add|create|fix|build|handle|refactor|set up|work on|move|update)\s+(the\s+)?\w+/gi,
868
- // "Going to fix the X"
869
- /\bgoing\s+to\s+(write|implement|add|create|fix|build|handle|refactor|set up|work on|move|update)\s+(the\s+)?\w+/gi,
870
- // "Continuing with X", "Continuing by adding Y"
871
- /\bcontinuing\s+(with|by\s+\w+ing)\s+(the\s+)?\w+/gi,
872
- ];
873
-
874
- /** Returns matched narration phrases, deduped and capped. Empty array = no narration detected. */
875
- function detectNarration(text: string): string[] {
876
- if (text.length < 20) return [];
877
- const seen = new Set<string>();
878
- const out: string[] = [];
879
- for (const pattern of NARRATION_PATTERNS) {
880
- const matches = text.match(pattern);
881
- if (!matches) continue;
882
- for (const m of matches) {
883
- const trimmed = m.trim().toLowerCase();
884
- if (seen.has(trimmed)) continue;
885
- seen.add(trimmed);
886
- out.push(m.trim());
887
- if (out.length >= 5) return out;
888
- }
889
- }
890
- return out;
891
- }
892
-
893
289
  // ---------------------------------------------------------------------------
894
290
  // Plugin
895
291
  // ---------------------------------------------------------------------------
896
292
 
897
- const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
293
+ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
898
294
  let cfg = loadConfig();
899
295
  const activeTiers = getActiveTiers(cfg);
900
296
 
901
- // Track subagent sessions so we can skip delegation protocol injection.
902
- // Populated by chat.params (which has the agent name) before system.transform fires.
903
- const subagentSessionIDs = new Set<string>();
297
+ // Per-plugin-instance session store: owns subagentSessionIDs and subagentCapState.
298
+ const sessionStore = createSessionStore();
299
+
300
+ // Per-plugin-instance trajectory store (Phase 0.3 scaffolding — RECORD-ONLY).
301
+ // Observes subagent tool activity to build a per-session scorecard. It emits
302
+ // NOTHING into any model-visible output; the only externally observable effect
303
+ // is an opt-in debug dump gated behind MODEL_ROUTER_TRAJECTORY_DEBUG=1.
304
+ const trajectoryStore = createTrajectoryStore();
305
+
306
+ // Per-plugin-instance guard state (Layer 1 hard-block). Only engaged for
307
+ // subagent sessions when enforcement mode is advisory/enforced; in "off"
308
+ // mode no guard state is ever created, so behaviour stays byte-identical.
309
+ const guardStore = createGuardStore();
310
+
311
+ const changedFileStore = createChangedFileStore();
312
+ const graderSessions = new Set<string>();
313
+
314
+ // Layer-2 real adapters (live-only; every call site is fail-closed).
315
+ const execSeam = (
316
+ command: string,
317
+ opts?: { cwd?: string; timeoutMs?: number },
318
+ ): Promise<{ code: number; stdout: string; stderr: string; timedOut: boolean }> =>
319
+ new Promise((resolve) => {
320
+ try {
321
+ nodeExec(
322
+ command,
323
+ {
324
+ cwd: opts?.cwd ?? ctx.directory,
325
+ timeout: opts?.timeoutMs ?? 120000,
326
+ maxBuffer: 10 * 1024 * 1024,
327
+ windowsHide: true,
328
+ },
329
+ (err: any, stdout: any, stderr: any) => {
330
+ const timedOut = !!(err && err.killed && err.signal === "SIGTERM");
331
+ const code =
332
+ err && typeof err.code === "number" ? err.code : err ? 1 : 0;
333
+ resolve({
334
+ code,
335
+ stdout: String(stdout ?? ""),
336
+ stderr: String(stderr ?? ""),
337
+ timedOut,
338
+ });
339
+ },
340
+ );
341
+ } catch {
342
+ resolve({ code: 1, stdout: "", stderr: "exec failed", timedOut: false });
343
+ }
344
+ });
345
+ const fsSeam = {
346
+ async fileExists(p: string): Promise<boolean> {
347
+ try {
348
+ await access(isAbsolute(p) ? p : join(ctx.directory, p));
349
+ return true;
350
+ } catch {
351
+ return false;
352
+ }
353
+ },
354
+ async readFile(p: string): Promise<string> {
355
+ return await fsReadFile(isAbsolute(p) ? p : join(ctx.directory, p), "utf-8");
356
+ },
357
+ };
358
+ const verifyMutex = createMutexRegistry();
359
+ const dispatchGrader = async (req: {
360
+ tier: string;
361
+ system: string;
362
+ prompt: string;
363
+ }): Promise<{ sessionID: string; text: string }> => {
364
+ const created: any = await ctx.client.session.create({});
365
+ const sid: string | undefined = created?.data?.id;
366
+ if (!sid) return { sessionID: "", text: "" };
367
+ graderSessions.add(sid);
368
+ try {
369
+ const model = tierModel(cfg, req.tier) ?? undefined;
370
+ const res: any = await ctx.client.session.prompt({
371
+ path: { id: sid },
372
+ body: {
373
+ ...(model ? { model } : {}),
374
+ system: req.system,
375
+ parts: [{ type: "text", text: req.prompt }],
376
+ },
377
+ });
378
+ const parts: any[] = res?.data?.parts ?? [];
379
+ const text = parts
380
+ .filter((p) => p?.type === "text" && typeof p.text === "string")
381
+ .map((p) => p.text)
382
+ .join("\n");
383
+ return { sessionID: sid, text };
384
+ } finally {
385
+ graderSessions.delete(sid);
386
+ }
387
+ };
388
+ const buildGateDeps = () => ({
389
+ deterministic: {
390
+ exec: execSeam,
391
+ fs: fsSeam,
392
+ cwd: ctx.directory,
393
+ mutex: verifyMutex,
394
+ },
395
+ checker: {
396
+ dispatchGrader,
397
+ ladder: ["fast", "medium", "heavy"],
398
+ minGraderTier: cfg.enforcement?.verify?.minGraderTier ?? null,
399
+ },
400
+ require: cfg.enforcement?.verify?.require,
401
+ });
904
402
 
905
- // Per-subagent-session cap state for runtime enforcement. Populated on chat.message,
906
- // read/updated by tool.execute.after. Keyed by sessionID. Orchestrator sessions are
907
- // intentionally NOT tracked here (per user decision: enforce on subagents only).
908
- const subagentCapState = new Map<string, SubagentState>();
403
+ // Best-effort, secret-free delegate scorecard dump (counts only).
404
+ const dumpDelegateScorecard = (
405
+ sid: string,
406
+ st: Parameters<typeof formatLadderScorecard>[0],
407
+ accepted: boolean,
408
+ method: string,
409
+ ): void => {
410
+ try {
411
+ const line = formatLadderScorecard(st, accepted, method);
412
+ const dir = join(tmpdir(), "opencode-model-router-trajectory");
413
+ mkdirSync(dir, { recursive: true });
414
+ writeFileSync(join(dir, `${sid}.delegate.log`), line + "\n", { flag: "a" });
415
+ } catch {
416
+ // best-effort only
417
+ }
418
+ };
909
419
 
910
420
  // Bypass mode: when true, the router skips all system prompt injection,
911
421
  // subagent tracking, cap enforcement, and narration detection for the
912
422
  // current plugin lifetime (i.e., until OpenCode is restarted).
913
423
  let bypassed = false;
914
424
 
425
+ const enableDelegateTool =
426
+ cfg.experimental?.verifiedDelegateTool === true ||
427
+ process.env.MODEL_ROUTER_VERIFIED_DELEGATE === "1";
428
+
915
429
  return {
430
+ tool: {
431
+ ...(enableDelegateTool ? { delegate: tool({
432
+ description:
433
+ "Delegate a task to a tier subagent (fast | medium | heavy). The subagent's result is INDEPENDENTLY VERIFIED (deterministic checks, or an independent grader at >= the producer tier in a fresh session) before it is returned. Returns an accepted result on PASS, or an honest 'unmet' status on FAIL — never a self-reported completion. Optionally pass an [acceptance]...[/acceptance] block to define the Definition of Done.",
434
+ args: {
435
+ task: tool.schema
436
+ .string()
437
+ .describe("The task for the subagent to perform."),
438
+ tier: tool.schema
439
+ .string()
440
+ .optional()
441
+ .describe("fast | medium | heavy. Defaults to the router default tier."),
442
+ acceptance: tool.schema
443
+ .string()
444
+ .optional()
445
+ .describe(
446
+ "Optional [acceptance]...[/acceptance] block defining the Definition of Done (check: / criteria: / deliverable: directives).",
447
+ ),
448
+ },
449
+ async execute(args: {
450
+ task: string;
451
+ tier?: string;
452
+ acceptance?: string;
453
+ }): Promise<string> {
454
+ try {
455
+ let activeCfg = cfg;
456
+ try {
457
+ activeCfg = loadConfig();
458
+ } catch {
459
+ activeCfg = cfg;
460
+ }
461
+ const initialTier =
462
+ typeof args.tier === "string" && args.tier.trim()
463
+ ? args.tier.trim()
464
+ : activeCfg.defaultTier || "medium";
465
+ const dod = buildDelegationDoD({
466
+ prompt: args.task,
467
+ acceptance: args.acceptance,
468
+ });
469
+
470
+ const policy = buildEscalatePolicy(activeCfg);
471
+ let state = newLadderState(initialTier, policy);
472
+ const tiersForCost: any = getActiveTiers(activeCfg);
473
+
474
+ // Independent safety net: even a policy bug cannot loop unbounded.
475
+ const safetyMax =
476
+ Math.max(
477
+ policy.maxTotalAttempts,
478
+ policy.ladder.length * (policy.maxAttemptsPerTier + 1),
479
+ ) + 2;
480
+ let safety = 0;
481
+
482
+ let producerText = "";
483
+ let forcing: string | null = null;
484
+
485
+ while (true) {
486
+ if (safety++ > safetyMax) {
487
+ return (
488
+ `[router status: unmet] delegation stopped by the safety net after ` +
489
+ `${state.totalAttempts} attempt(s).\n\n${scrubText(producerText)}`
490
+ );
491
+ }
492
+ const tier = state.currentTier;
493
+ const taskText = forcing
494
+ ? `${scrubText(forcing)}\n\n${args.task}`
495
+ : args.task;
496
+
497
+ const created: any = await ctx.client.session.create({});
498
+ const producerSid: string | undefined = created?.data?.id;
499
+ if (!producerSid) {
500
+ return "[router] delegate failed: could not create a producer session.";
501
+ }
502
+ // Compose with Layer 1: guard the plugin-created producer session.
503
+ try {
504
+ sessionStore.registerProducerSession(producerSid, tier, activeCfg);
505
+ } catch {
506
+ // non-fatal
507
+ }
508
+
509
+ const model = tierModel(activeCfg, tier) ?? undefined;
510
+ producerText = "";
511
+ // Provider-failover vs quality-escalation precedence (Phase 3.3):
512
+ // Provider-failover is advisory only — a text chain injected into the orchestrator
513
+ // system prompt (buildFallbackInstructions). It is orthogonal to this runtime ladder.
514
+ // A transport/API error here is caught, yields an empty artefact, and is treated as
515
+ // exactly ONE failed attempt by the quality-escalation ladder (no provider swap, no
516
+ // double-counted attempt). API error => (advisory) provider failover; verification
517
+ // FAIL => (runtime) quality escalation.
518
+ try {
519
+ const res: any = await ctx.client.session.prompt({
520
+ path: { id: producerSid },
521
+ body: {
522
+ ...(model ? { model } : {}),
523
+ ...(tier ? { agent: tier } : {}),
524
+ parts: [{ type: "text", text: taskText }],
525
+ },
526
+ });
527
+ const parts: any[] = res?.data?.parts ?? [];
528
+ producerText = parts
529
+ .filter((p) => p?.type === "text" && typeof p.text === "string")
530
+ .map((p) => p.text)
531
+ .join("\n");
532
+ } catch {
533
+ producerText = "";
534
+ }
535
+
536
+ const artefact = {
537
+ changedFiles: changedFileStore.get(producerSid),
538
+ finalReturnText: producerText,
539
+ declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
540
+ producerSessionID: producerSid,
541
+ producerTier: tier,
542
+ };
543
+
544
+ let gateRes;
545
+ try {
546
+ gateRes = await accept(
547
+ { dod, trivial: false, mode: "modeA" },
548
+ artefact,
549
+ buildGateDeps(),
550
+ );
551
+ } catch {
552
+ gateRes = {
553
+ accepted: false,
554
+ verdict: {
555
+ pass: false,
556
+ method: "none" as const,
557
+ reasons: ["verification failed (fail-closed)"],
558
+ },
559
+ dodSource: dod.source,
560
+ };
561
+ }
562
+
563
+ // Per-attempt cleanup (drop producer session tracking + state).
564
+ changedFileStore.clear(producerSid);
565
+ try {
566
+ sessionStore.unregister(producerSid);
567
+ } catch {
568
+ // non-fatal
569
+ }
570
+ try {
571
+ guardStore.clear(producerSid);
572
+ } catch {
573
+ // non-fatal
574
+ }
575
+
576
+ const costRatio =
577
+ typeof tiersForCost?.[tier]?.costRatio === "number"
578
+ ? tiersForCost[tier].costRatio
579
+ : 1;
580
+ state = recordAttempt(state, costRatio);
581
+
582
+ const action = nextAction(
583
+ state,
584
+ { pass: gateRes.accepted, reasons: gateRes.verdict.reasons },
585
+ policy,
586
+ );
587
+
588
+ if (action.action === "accept") {
589
+ dumpDelegateScorecard(
590
+ producerSid,
591
+ state,
592
+ true,
593
+ gateRes.verdict.method,
594
+ );
595
+ return producerText + buildAcceptedSuffix(gateRes.verdict.method);
596
+ }
597
+ if (action.action === "give_up") {
598
+ dumpDelegateScorecard(
599
+ producerSid,
600
+ state,
601
+ false,
602
+ gateRes.verdict.method,
603
+ );
604
+ const note = scrubText(buildForcingNote(gateRes.verdict.reasons));
605
+ return (
606
+ `[router status: unmet] The delegated result was not accepted after ` +
607
+ `${state.totalAttempts} attempt(s) across ${state.escalations} escalation(s) ` +
608
+ `(final tier ${state.currentTier}; ${action.reason ?? "verification failed"}).\n\n` +
609
+ `${scrubText(producerText)}\n\n${note}`
610
+ );
611
+ }
612
+ // retry or escalate
613
+ forcing = action.forcingMessage ?? null;
614
+ state = advance(state, action);
615
+ }
616
+ } catch {
617
+ return "[router] delegate failed (fail-closed): the delegation or verification could not complete.";
618
+ }
619
+ },
620
+ }) } : {}),
621
+ },
622
+
916
623
  // -----------------------------------------------------------------------
917
624
  // Detect subagent calls via chat.message. When the agent name matches a
918
625
  // registered tier, record the sessionID so system.transform can skip
@@ -931,6 +638,16 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
931
638
  // loop -> LLM.stream path, so by the time system.transform runs the Set
932
639
  // is fully populated and await-safe (yield* on the plugin trigger).
933
640
  // -----------------------------------------------------------------------
641
+ "chat.params": async (input: any, output: any) => {
642
+ try {
643
+ if (input?.sessionID && graderSessions.has(input.sessionID)) {
644
+ output.temperature = cfg.enforcement?.verify?.graderTemperature ?? 0;
645
+ }
646
+ } catch {
647
+ // best-effort: never crash a real session
648
+ }
649
+ },
650
+
934
651
  "chat.message": async (input: any, output: any) => {
935
652
  if (bypassed) return;
936
653
  // Re-read cfg so /preset switches take effect without restart
@@ -938,23 +655,50 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
938
655
  cfg = loadConfig();
939
656
  } catch {}
940
657
  const tierNames = Object.keys(getActiveTiers(cfg));
941
- if (input.agent && tierNames.includes(input.agent)) {
942
- subagentSessionIDs.add(input.sessionID);
943
-
944
- // Initialize cap state on first dispatch; reset on subsequent rounds to the same
945
- // subagent session (rare but supported — treats each round as a fresh budget).
946
- const tierName = input.agent as string;
947
- const dispatchText = extractDispatchText(output);
948
- const override = parseCapDirective(dispatchText);
949
- const baseline =
950
- cfg.tierCaps?.[tierName] ?? DEFAULT_TIER_CAPS[tierName] ?? 5;
951
- const cap: Cap = override ?? baseline;
952
- subagentCapState.set(input.sessionID, {
953
- tierName,
954
- cap,
955
- calls: 0,
956
- seen: new Map(),
658
+ sessionStore.registerFromChatMessage(input, output, cfg, tierNames);
659
+
660
+ // Record-only: initialise a trajectory scorecard for tracked subagents.
661
+ const sid = input?.sessionID;
662
+ if (sid && sessionStore.isSubagent(sid)) {
663
+ trajectoryStore.ensure(sid, input?.agent ?? null);
664
+ }
665
+ },
666
+
667
+ // -----------------------------------------------------------------------
668
+ // Hard-block enforcement (Layer 1). Fires before tool execution; only
669
+ // engaged for subagent sessions when enforcement mode is advisory/enforced.
670
+ // Throws to abort the tool call when a guard fires; never throws for
671
+ // non-subagent sessions or when enforcement is off (GA-1 preserved).
672
+ // -----------------------------------------------------------------------
673
+ "tool.execute.before": async (input: any, output: any) => {
674
+ if (bypassed) return;
675
+ const sid = input?.sessionID;
676
+ if (!sid || !sessionStore.isSubagent(sid) || typeof input?.tool !== "string") {
677
+ return;
678
+ }
679
+ let res;
680
+ try {
681
+ res = guardBeforeCall({
682
+ cfg,
683
+ tier: sessionStore.getTier(sid),
684
+ trivial: sessionStore.isTrivial(sid),
685
+ sessionID: sid,
686
+ tool: input.tool,
687
+ toolArgs: output?.args,
688
+ store: guardStore,
689
+ env: process.env,
957
690
  });
691
+ } catch {
692
+ return; // never break a real session on a guard-internal error
693
+ }
694
+ if (res.block) {
695
+ trajectoryStore.recordToolEvent(sid, {
696
+ tool: input.tool,
697
+ readOnly: READ_ONLY_TOOLS.has(input.tool),
698
+ blocked: true,
699
+ selfScript: res.guard === "anti_self_script",
700
+ });
701
+ throw new Error(res.message);
958
702
  }
959
703
  },
960
704
 
@@ -967,24 +711,92 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
967
711
  // -----------------------------------------------------------------------
968
712
  "tool.execute.after": async (input: any, output: any) => {
969
713
  if (bypassed) return;
970
- const state = subagentCapState.get(input.sessionID);
971
- if (!state) return; // not a tracked subagent session
972
- if (!READ_ONLY_TOOLS.has(input.tool)) return;
714
+ sessionStore.recordToolCall(input, output);
973
715
 
974
- const fp = fingerprintToolCall(input.tool, input.args);
975
- const previousCall = state.seen.get(fp);
976
- const isRedundant = previousCall !== undefined;
716
+ // Record-only trajectory observation (mutates internal maps only; never
717
+ // touches output, so emitted banners/observations stay byte-identical).
718
+ const sid = input?.sessionID;
977
719
 
978
- state.calls += 1;
979
- if (!isRedundant) {
980
- state.seen.set(fp, state.calls);
720
+ // Attribute changed files to whichever session made the edit (any session).
721
+ if (sid && typeof input?.tool === "string") {
722
+ changedFileStore.record(sid, input.tool, input?.args);
981
723
  }
982
724
 
983
- const banner = buildCapBanner(state, isRedundant, previousCall, input.tool);
725
+ if (sid && sessionStore.isSubagent(sid) && typeof input?.tool === "string") {
726
+ trajectoryStore.recordToolEvent(sid, {
727
+ tool: input.tool,
728
+ readOnly: READ_ONLY_TOOLS.has(input.tool),
729
+ });
730
+ try {
731
+ guardAfterCall({
732
+ cfg,
733
+ tier: sessionStore.getTier(sid),
734
+ sessionID: sid,
735
+ tool: input.tool,
736
+ toolArgs: input?.args,
737
+ output,
738
+ store: guardStore,
739
+ });
740
+ } catch {
741
+ // best-effort: enforcement must never crash a real session
742
+ }
743
+ }
984
744
 
985
- const existing =
986
- typeof output.output === "string" ? output.output : "";
987
- output.output = existing ? `${existing}\n\n${banner}` : banner;
745
+ // Option (i): verify-dispatch around the built-in `task` tool (advisory-grade —
746
+ // we observe the finished task result and append a forcing note if it is not
747
+ // accepted; we cannot retry a task call that already finished).
748
+ if (typeof input?.tool === "string") {
749
+ let mode = "off";
750
+ try {
751
+ mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
752
+ } catch {
753
+ // fall through with mode "off"
754
+ }
755
+ const requireMode = cfg.enforcement?.verify?.require;
756
+ if (shouldVerifyTask(input.tool, mode, requireMode)) {
757
+ try {
758
+ const { finalReturnText, childSessionID } = parseTaskResult(output);
759
+ const producerTier =
760
+ typeof input?.args?.subagent_type === "string"
761
+ ? input.args.subagent_type
762
+ : "";
763
+ const dod = buildDelegationDoD({
764
+ prompt: input?.args?.prompt,
765
+ description: input?.args?.description,
766
+ });
767
+ const artefact = {
768
+ changedFiles: childSessionID
769
+ ? changedFileStore.get(childSessionID)
770
+ : [],
771
+ finalReturnText,
772
+ declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
773
+ producerSessionID: childSessionID ?? "",
774
+ producerTier,
775
+ };
776
+ const trivial = childSessionID
777
+ ? sessionStore.isTrivial(childSessionID)
778
+ : false;
779
+ const res = await accept(
780
+ { dod, trivial, mode: "modeA" },
781
+ artefact,
782
+ buildGateDeps(),
783
+ );
784
+ if (!res.accepted && !res.verdict.skipped) {
785
+ const ladder = cfg.enforcement?.escalate?.ladder ?? ["fast", "medium", "heavy"];
786
+ const li = ladder.indexOf(producerTier);
787
+ const nextTier = li >= 0 && li < ladder.length - 1 ? ladder[li + 1] : null;
788
+ const note = scrubText(buildForcingNote(res.verdict.reasons, { producerTier, nextTier }));
789
+ output.output =
790
+ typeof output.output === "string"
791
+ ? output.output + "\n\n" + note
792
+ : note;
793
+ }
794
+ if (childSessionID) changedFileStore.clear(childSessionID);
795
+ } catch {
796
+ // fail-closed: a verification error must NEVER throw out of the after-hook
797
+ }
798
+ }
799
+ }
988
800
  },
989
801
 
990
802
  // -----------------------------------------------------------------------
@@ -1010,6 +822,44 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
1010
822
  output.text = `${text}\n\n[⚠ narration detected: ${quoted}]`;
1011
823
  },
1012
824
 
825
+ // -----------------------------------------------------------------------
826
+ // Gated trajectory debug dump (Phase 0.3, T0.3.3) — RECORD-ONLY, OPT-IN.
827
+ // No-op unless MODEL_ROUTER_TRAJECTORY_DEBUG=1. On session.idle, writes the
828
+ // session's trajectory scorecard to a throwaway file under the OS temp dir
829
+ // for manual inspection. Best-effort; never throws into the session.
830
+ // Emits nothing model-visible, so GA-1 (no-regression) is preserved.
831
+ // -----------------------------------------------------------------------
832
+ event: async ({ event }: any) => {
833
+ if (event?.type !== "session.idle") return;
834
+ const sid = event?.properties?.sessionID;
835
+ if (typeof sid !== "string") return;
836
+
837
+ // Per-delegation scorecard: only when enforcement was active (guard state exists).
838
+ try {
839
+ const gstate = guardStore.get(sid);
840
+ if (gstate) {
841
+ const line = formatScorecard(gstate, sessionStore.getTier(sid));
842
+ const dir = join(tmpdir(), "opencode-model-router-trajectory");
843
+ mkdirSync(dir, { recursive: true });
844
+ writeFileSync(join(dir, `${sid}.scorecard.log`), line + "\n", { flag: "a" });
845
+ }
846
+ } catch {
847
+ // best-effort: a scorecard must never crash a real session
848
+ }
849
+
850
+ // Opt-in full trajectory dump (unchanged gating).
851
+ if (process.env.MODEL_ROUTER_TRAJECTORY_DEBUG !== "1") return;
852
+ const dump = trajectoryStore.dump(sid);
853
+ if (!dump) return;
854
+ try {
855
+ const dir = join(tmpdir(), "opencode-model-router-trajectory");
856
+ mkdirSync(dir, { recursive: true });
857
+ writeFileSync(join(dir, `${sid}.log`), dump + "\n", { flag: "a" });
858
+ } catch {
859
+ // best-effort
860
+ }
861
+ },
862
+
1013
863
  // -----------------------------------------------------------------------
1014
864
  // Register tier agents + commands at load time
1015
865
  // -----------------------------------------------------------------------
@@ -1099,10 +949,23 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
1099
949
  "",
1100
950
  "## Output",
1101
951
  "Rewrite the entire plan in the file with the tags. Do not change the substance — only add tags, and split mixed steps when useful for clearer delegation.",
952
+ "",
953
+ "## Acceptance blocks (for enforcement)",
954
+ "For each NON-TRIVIAL task, append an acceptance block immediately after the step so the router can verify the work:",
955
+ "[acceptance]",
956
+ "check: <testsPass | buildPasses | lintClean | fileExists path=... | run command=\"...\" expect=...>",
957
+ "criteria: <plain-language success condition, when no deterministic check applies>",
958
+ "deliverable: <path or short description>",
959
+ "[/acceptance]",
960
+ "Prefer deterministic checks (testsPass/buildPasses/fileExists). Use a criteria line for design/explanatory tasks. Trivial read-only steps need no acceptance block.",
1102
961
  ].join("\n"),
1103
962
  description:
1104
963
  "Annotate a plan with [tier:fast/medium/heavy] delegation tags",
1105
964
  };
965
+ opencodeConfig.command["router"] = {
966
+ template: "$ARGUMENTS",
967
+ description: "Model-router controls (e.g., /router enforce off|advisory|enforced)",
968
+ };
1106
969
  },
1107
970
 
1108
971
  // -----------------------------------------------------------------------
@@ -1122,7 +985,7 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
1122
985
  // Skip injection for child (subagent) sessions.
1123
986
  // Child sessions are detected via session.created events with a parentID.
1124
987
  const sessionID = _input?.sessionID;
1125
- if (sessionID && subagentSessionIDs.has(sessionID)) return;
988
+ if (sessionID && sessionStore.isSubagent(sessionID)) return;
1126
989
 
1127
990
  // For Claude-backed orchestrators, prepend an adversarial opener that
1128
991
  // revokes the cached "Claude Code explorer" priming for the routing
@@ -1130,12 +993,10 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
1130
993
  const providerID = _input?.model?.providerID ?? "";
1131
994
  const modelID = _input?.model?.modelID ?? "";
1132
995
  const orchestratorModel = providerID && modelID ? `${providerID}/${modelID}` : modelID;
1133
- const delegationProtocol = buildDelegationProtocol(cfg);
1134
- const finalProtocol = isClaudeModel(orchestratorModel)
1135
- ? `${CLAUDE_ORCHESTRATOR_PREFIX}\n\n${CLAUDE_ANTI_NARRATION}\n\n---\n\n${delegationProtocol}`
1136
- : delegationProtocol;
1137
996
 
1138
- output.system.push(finalProtocol);
997
+ let enfOn = false;
998
+ try { enfOn = resolveEnforcementMode({ config: cfg, env: process.env }).mode !== "off"; } catch {}
999
+ output.system.push(assembleSystemPrompt(cfg, orchestratorModel, enfOn));
1139
1000
  },
1140
1001
 
1141
1002
  // -----------------------------------------------------------------------
@@ -1190,6 +1051,16 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
1190
1051
  text: buildBudgetOutput(cfg, input.arguments ?? ""),
1191
1052
  });
1192
1053
  }
1054
+
1055
+ if (input.command === "router") {
1056
+ try {
1057
+ cfg = loadConfig();
1058
+ } catch {}
1059
+ output.parts.push({
1060
+ type: "text" as const,
1061
+ text: buildRouterOutput(cfg, input.arguments ?? ""),
1062
+ });
1063
+ }
1193
1064
  },
1194
1065
  };
1195
1066
  };