opencode-model-router 1.1.16 → 1.2.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,268 +286,136 @@ 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
@@ -913,6 +423,199 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
913
423
  let bypassed = false;
914
424
 
915
425
  return {
426
+ tool: {
427
+ delegate: tool({
428
+ description:
429
+ "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.",
430
+ args: {
431
+ task: tool.schema
432
+ .string()
433
+ .describe("The task for the subagent to perform."),
434
+ tier: tool.schema
435
+ .string()
436
+ .optional()
437
+ .describe("fast | medium | heavy. Defaults to the router default tier."),
438
+ acceptance: tool.schema
439
+ .string()
440
+ .optional()
441
+ .describe(
442
+ "Optional [acceptance]...[/acceptance] block defining the Definition of Done (check: / criteria: / deliverable: directives).",
443
+ ),
444
+ },
445
+ async execute(args: {
446
+ task: string;
447
+ tier?: string;
448
+ acceptance?: string;
449
+ }): Promise<string> {
450
+ try {
451
+ let activeCfg = cfg;
452
+ try {
453
+ activeCfg = loadConfig();
454
+ } catch {
455
+ activeCfg = cfg;
456
+ }
457
+ const initialTier =
458
+ typeof args.tier === "string" && args.tier.trim()
459
+ ? args.tier.trim()
460
+ : activeCfg.defaultTier || "medium";
461
+ const dod = buildDelegationDoD({
462
+ prompt: args.task,
463
+ acceptance: args.acceptance,
464
+ });
465
+
466
+ const policy = buildEscalatePolicy(activeCfg);
467
+ let state = newLadderState(initialTier, policy);
468
+ const tiersForCost: any = getActiveTiers(activeCfg);
469
+
470
+ // Independent safety net: even a policy bug cannot loop unbounded.
471
+ const safetyMax =
472
+ Math.max(
473
+ policy.maxTotalAttempts,
474
+ policy.ladder.length * (policy.maxAttemptsPerTier + 1),
475
+ ) + 2;
476
+ let safety = 0;
477
+
478
+ let producerText = "";
479
+ let forcing: string | null = null;
480
+
481
+ while (true) {
482
+ if (safety++ > safetyMax) {
483
+ return (
484
+ `[router status: unmet] delegation stopped by the safety net after ` +
485
+ `${state.totalAttempts} attempt(s).\n\n${scrubText(producerText)}`
486
+ );
487
+ }
488
+ const tier = state.currentTier;
489
+ const taskText = forcing
490
+ ? `${scrubText(forcing)}\n\n${args.task}`
491
+ : args.task;
492
+
493
+ const created: any = await ctx.client.session.create({});
494
+ const producerSid: string | undefined = created?.data?.id;
495
+ if (!producerSid) {
496
+ return "[router] delegate failed: could not create a producer session.";
497
+ }
498
+ // Compose with Layer 1: guard the plugin-created producer session.
499
+ try {
500
+ sessionStore.registerProducerSession(producerSid, tier, activeCfg);
501
+ } catch {
502
+ // non-fatal
503
+ }
504
+
505
+ const model = tierModel(activeCfg, tier) ?? undefined;
506
+ producerText = "";
507
+ // Provider-failover vs quality-escalation precedence (Phase 3.3):
508
+ // Provider-failover is advisory only — a text chain injected into the orchestrator
509
+ // system prompt (buildFallbackInstructions). It is orthogonal to this runtime ladder.
510
+ // A transport/API error here is caught, yields an empty artefact, and is treated as
511
+ // exactly ONE failed attempt by the quality-escalation ladder (no provider swap, no
512
+ // double-counted attempt). API error => (advisory) provider failover; verification
513
+ // FAIL => (runtime) quality escalation.
514
+ try {
515
+ const res: any = await ctx.client.session.prompt({
516
+ path: { id: producerSid },
517
+ body: {
518
+ ...(model ? { model } : {}),
519
+ ...(tier ? { agent: tier } : {}),
520
+ parts: [{ type: "text", text: taskText }],
521
+ },
522
+ });
523
+ const parts: any[] = res?.data?.parts ?? [];
524
+ producerText = parts
525
+ .filter((p) => p?.type === "text" && typeof p.text === "string")
526
+ .map((p) => p.text)
527
+ .join("\n");
528
+ } catch {
529
+ producerText = "";
530
+ }
531
+
532
+ const artefact = {
533
+ changedFiles: changedFileStore.get(producerSid),
534
+ finalReturnText: producerText,
535
+ declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
536
+ producerSessionID: producerSid,
537
+ producerTier: tier,
538
+ };
539
+
540
+ let gateRes;
541
+ try {
542
+ gateRes = await accept(
543
+ { dod, trivial: false, mode: "modeA" },
544
+ artefact,
545
+ buildGateDeps(),
546
+ );
547
+ } catch {
548
+ gateRes = {
549
+ accepted: false,
550
+ verdict: {
551
+ pass: false,
552
+ method: "none" as const,
553
+ reasons: ["verification failed (fail-closed)"],
554
+ },
555
+ dodSource: dod.source,
556
+ };
557
+ }
558
+
559
+ // Per-attempt cleanup (drop producer session tracking + state).
560
+ changedFileStore.clear(producerSid);
561
+ try {
562
+ sessionStore.unregister(producerSid);
563
+ } catch {
564
+ // non-fatal
565
+ }
566
+ try {
567
+ guardStore.clear(producerSid);
568
+ } catch {
569
+ // non-fatal
570
+ }
571
+
572
+ const costRatio =
573
+ typeof tiersForCost?.[tier]?.costRatio === "number"
574
+ ? tiersForCost[tier].costRatio
575
+ : 1;
576
+ state = recordAttempt(state, costRatio);
577
+
578
+ const action = nextAction(
579
+ state,
580
+ { pass: gateRes.accepted, reasons: gateRes.verdict.reasons },
581
+ policy,
582
+ );
583
+
584
+ if (action.action === "accept") {
585
+ dumpDelegateScorecard(
586
+ producerSid,
587
+ state,
588
+ true,
589
+ gateRes.verdict.method,
590
+ );
591
+ return producerText + buildAcceptedSuffix(gateRes.verdict.method);
592
+ }
593
+ if (action.action === "give_up") {
594
+ dumpDelegateScorecard(
595
+ producerSid,
596
+ state,
597
+ false,
598
+ gateRes.verdict.method,
599
+ );
600
+ const note = scrubText(buildForcingNote(gateRes.verdict.reasons));
601
+ return (
602
+ `[router status: unmet] The delegated result was not accepted after ` +
603
+ `${state.totalAttempts} attempt(s) across ${state.escalations} escalation(s) ` +
604
+ `(final tier ${state.currentTier}; ${action.reason ?? "verification failed"}).\n\n` +
605
+ `${scrubText(producerText)}\n\n${note}`
606
+ );
607
+ }
608
+ // retry or escalate
609
+ forcing = action.forcingMessage ?? null;
610
+ state = advance(state, action);
611
+ }
612
+ } catch {
613
+ return "[router] delegate failed (fail-closed): the delegation or verification could not complete.";
614
+ }
615
+ },
616
+ }),
617
+ },
618
+
916
619
  // -----------------------------------------------------------------------
917
620
  // Detect subagent calls via chat.message. When the agent name matches a
918
621
  // registered tier, record the sessionID so system.transform can skip
@@ -931,6 +634,16 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
931
634
  // loop -> LLM.stream path, so by the time system.transform runs the Set
932
635
  // is fully populated and await-safe (yield* on the plugin trigger).
933
636
  // -----------------------------------------------------------------------
637
+ "chat.params": async (input: any, output: any) => {
638
+ try {
639
+ if (input?.sessionID && graderSessions.has(input.sessionID)) {
640
+ output.temperature = cfg.enforcement?.verify?.graderTemperature ?? 0;
641
+ }
642
+ } catch {
643
+ // best-effort: never crash a real session
644
+ }
645
+ },
646
+
934
647
  "chat.message": async (input: any, output: any) => {
935
648
  if (bypassed) return;
936
649
  // Re-read cfg so /preset switches take effect without restart
@@ -938,23 +651,50 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
938
651
  cfg = loadConfig();
939
652
  } catch {}
940
653
  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(),
654
+ sessionStore.registerFromChatMessage(input, output, cfg, tierNames);
655
+
656
+ // Record-only: initialise a trajectory scorecard for tracked subagents.
657
+ const sid = input?.sessionID;
658
+ if (sid && sessionStore.isSubagent(sid)) {
659
+ trajectoryStore.ensure(sid, input?.agent ?? null);
660
+ }
661
+ },
662
+
663
+ // -----------------------------------------------------------------------
664
+ // Hard-block enforcement (Layer 1). Fires before tool execution; only
665
+ // engaged for subagent sessions when enforcement mode is advisory/enforced.
666
+ // Throws to abort the tool call when a guard fires; never throws for
667
+ // non-subagent sessions or when enforcement is off (GA-1 preserved).
668
+ // -----------------------------------------------------------------------
669
+ "tool.execute.before": async (input: any, output: any) => {
670
+ if (bypassed) return;
671
+ const sid = input?.sessionID;
672
+ if (!sid || !sessionStore.isSubagent(sid) || typeof input?.tool !== "string") {
673
+ return;
674
+ }
675
+ let res;
676
+ try {
677
+ res = guardBeforeCall({
678
+ cfg,
679
+ tier: sessionStore.getTier(sid),
680
+ trivial: sessionStore.isTrivial(sid),
681
+ sessionID: sid,
682
+ tool: input.tool,
683
+ toolArgs: output?.args,
684
+ store: guardStore,
685
+ env: process.env,
686
+ });
687
+ } catch {
688
+ return; // never break a real session on a guard-internal error
689
+ }
690
+ if (res.block) {
691
+ trajectoryStore.recordToolEvent(sid, {
692
+ tool: input.tool,
693
+ readOnly: READ_ONLY_TOOLS.has(input.tool),
694
+ blocked: true,
695
+ selfScript: res.guard === "anti_self_script",
957
696
  });
697
+ throw new Error(res.message);
958
698
  }
959
699
  },
960
700
 
@@ -967,24 +707,89 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
967
707
  // -----------------------------------------------------------------------
968
708
  "tool.execute.after": async (input: any, output: any) => {
969
709
  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;
710
+ sessionStore.recordToolCall(input, output);
973
711
 
974
- const fp = fingerprintToolCall(input.tool, input.args);
975
- const previousCall = state.seen.get(fp);
976
- const isRedundant = previousCall !== undefined;
712
+ // Record-only trajectory observation (mutates internal maps only; never
713
+ // touches output, so emitted banners/observations stay byte-identical).
714
+ const sid = input?.sessionID;
977
715
 
978
- state.calls += 1;
979
- if (!isRedundant) {
980
- state.seen.set(fp, state.calls);
716
+ // Attribute changed files to whichever session made the edit (any session).
717
+ if (sid && typeof input?.tool === "string") {
718
+ changedFileStore.record(sid, input.tool, input?.args);
981
719
  }
982
720
 
983
- const banner = buildCapBanner(state, isRedundant, previousCall, input.tool);
721
+ if (sid && sessionStore.isSubagent(sid) && typeof input?.tool === "string") {
722
+ trajectoryStore.recordToolEvent(sid, {
723
+ tool: input.tool,
724
+ readOnly: READ_ONLY_TOOLS.has(input.tool),
725
+ });
726
+ try {
727
+ guardAfterCall({
728
+ cfg,
729
+ tier: sessionStore.getTier(sid),
730
+ sessionID: sid,
731
+ tool: input.tool,
732
+ toolArgs: input?.args,
733
+ output,
734
+ store: guardStore,
735
+ });
736
+ } catch {
737
+ // best-effort: enforcement must never crash a real session
738
+ }
739
+ }
984
740
 
985
- const existing =
986
- typeof output.output === "string" ? output.output : "";
987
- output.output = existing ? `${existing}\n\n${banner}` : banner;
741
+ // Option (i): verify-dispatch around the built-in `task` tool (advisory-grade —
742
+ // we observe the finished task result and append a forcing note if it is not
743
+ // accepted; we cannot retry a task call that already finished).
744
+ if (typeof input?.tool === "string") {
745
+ let mode = "off";
746
+ try {
747
+ mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
748
+ } catch {
749
+ // fall through with mode "off"
750
+ }
751
+ const requireMode = cfg.enforcement?.verify?.require;
752
+ if (shouldVerifyTask(input.tool, mode, requireMode)) {
753
+ try {
754
+ const { finalReturnText, childSessionID } = parseTaskResult(output);
755
+ const producerTier =
756
+ typeof input?.args?.subagent_type === "string"
757
+ ? input.args.subagent_type
758
+ : "";
759
+ const dod = buildDelegationDoD({
760
+ prompt: input?.args?.prompt,
761
+ description: input?.args?.description,
762
+ });
763
+ const artefact = {
764
+ changedFiles: childSessionID
765
+ ? changedFileStore.get(childSessionID)
766
+ : [],
767
+ finalReturnText,
768
+ declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
769
+ producerSessionID: childSessionID ?? "",
770
+ producerTier,
771
+ };
772
+ const trivial = childSessionID
773
+ ? sessionStore.isTrivial(childSessionID)
774
+ : false;
775
+ const res = await accept(
776
+ { dod, trivial, mode: "modeA" },
777
+ artefact,
778
+ buildGateDeps(),
779
+ );
780
+ if (!res.accepted && !res.verdict.skipped) {
781
+ const note = scrubText(buildForcingNote(res.verdict.reasons));
782
+ output.output =
783
+ typeof output.output === "string"
784
+ ? output.output + "\n\n" + note
785
+ : note;
786
+ }
787
+ if (childSessionID) changedFileStore.clear(childSessionID);
788
+ } catch {
789
+ // fail-closed: a verification error must NEVER throw out of the after-hook
790
+ }
791
+ }
792
+ }
988
793
  },
989
794
 
990
795
  // -----------------------------------------------------------------------
@@ -1010,6 +815,44 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
1010
815
  output.text = `${text}\n\n[⚠ narration detected: ${quoted}]`;
1011
816
  },
1012
817
 
818
+ // -----------------------------------------------------------------------
819
+ // Gated trajectory debug dump (Phase 0.3, T0.3.3) — RECORD-ONLY, OPT-IN.
820
+ // No-op unless MODEL_ROUTER_TRAJECTORY_DEBUG=1. On session.idle, writes the
821
+ // session's trajectory scorecard to a throwaway file under the OS temp dir
822
+ // for manual inspection. Best-effort; never throws into the session.
823
+ // Emits nothing model-visible, so GA-1 (no-regression) is preserved.
824
+ // -----------------------------------------------------------------------
825
+ event: async ({ event }: any) => {
826
+ if (event?.type !== "session.idle") return;
827
+ const sid = event?.properties?.sessionID;
828
+ if (typeof sid !== "string") return;
829
+
830
+ // Per-delegation scorecard: only when enforcement was active (guard state exists).
831
+ try {
832
+ const gstate = guardStore.get(sid);
833
+ if (gstate) {
834
+ const line = formatScorecard(gstate, sessionStore.getTier(sid));
835
+ const dir = join(tmpdir(), "opencode-model-router-trajectory");
836
+ mkdirSync(dir, { recursive: true });
837
+ writeFileSync(join(dir, `${sid}.scorecard.log`), line + "\n", { flag: "a" });
838
+ }
839
+ } catch {
840
+ // best-effort: a scorecard must never crash a real session
841
+ }
842
+
843
+ // Opt-in full trajectory dump (unchanged gating).
844
+ if (process.env.MODEL_ROUTER_TRAJECTORY_DEBUG !== "1") return;
845
+ const dump = trajectoryStore.dump(sid);
846
+ if (!dump) return;
847
+ try {
848
+ const dir = join(tmpdir(), "opencode-model-router-trajectory");
849
+ mkdirSync(dir, { recursive: true });
850
+ writeFileSync(join(dir, `${sid}.log`), dump + "\n", { flag: "a" });
851
+ } catch {
852
+ // best-effort
853
+ }
854
+ },
855
+
1013
856
  // -----------------------------------------------------------------------
1014
857
  // Register tier agents + commands at load time
1015
858
  // -----------------------------------------------------------------------
@@ -1099,10 +942,23 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
1099
942
  "",
1100
943
  "## Output",
1101
944
  "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.",
945
+ "",
946
+ "## Acceptance blocks (for enforcement)",
947
+ "For each NON-TRIVIAL task, append an acceptance block immediately after the step so the router can verify the work:",
948
+ "[acceptance]",
949
+ "check: <testsPass | buildPasses | lintClean | fileExists path=... | run command=\"...\" expect=...>",
950
+ "criteria: <plain-language success condition, when no deterministic check applies>",
951
+ "deliverable: <path or short description>",
952
+ "[/acceptance]",
953
+ "Prefer deterministic checks (testsPass/buildPasses/fileExists). Use a criteria line for design/explanatory tasks. Trivial read-only steps need no acceptance block.",
1102
954
  ].join("\n"),
1103
955
  description:
1104
956
  "Annotate a plan with [tier:fast/medium/heavy] delegation tags",
1105
957
  };
958
+ opencodeConfig.command["router"] = {
959
+ template: "$ARGUMENTS",
960
+ description: "Model-router controls (e.g., /router enforce off|advisory|enforced)",
961
+ };
1106
962
  },
1107
963
 
1108
964
  // -----------------------------------------------------------------------
@@ -1122,7 +978,7 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
1122
978
  // Skip injection for child (subagent) sessions.
1123
979
  // Child sessions are detected via session.created events with a parentID.
1124
980
  const sessionID = _input?.sessionID;
1125
- if (sessionID && subagentSessionIDs.has(sessionID)) return;
981
+ if (sessionID && sessionStore.isSubagent(sessionID)) return;
1126
982
 
1127
983
  // For Claude-backed orchestrators, prepend an adversarial opener that
1128
984
  // revokes the cached "Claude Code explorer" priming for the routing
@@ -1130,12 +986,10 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
1130
986
  const providerID = _input?.model?.providerID ?? "";
1131
987
  const modelID = _input?.model?.modelID ?? "";
1132
988
  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
989
 
1138
- output.system.push(finalProtocol);
990
+ let enfOn = false;
991
+ try { enfOn = resolveEnforcementMode({ config: cfg, env: process.env }).mode !== "off"; } catch {}
992
+ output.system.push(assembleSystemPrompt(cfg, orchestratorModel, enfOn));
1139
993
  },
1140
994
 
1141
995
  // -----------------------------------------------------------------------
@@ -1190,6 +1044,16 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
1190
1044
  text: buildBudgetOutput(cfg, input.arguments ?? ""),
1191
1045
  });
1192
1046
  }
1047
+
1048
+ if (input.command === "router") {
1049
+ try {
1050
+ cfg = loadConfig();
1051
+ } catch {}
1052
+ output.parts.push({
1053
+ type: "text" as const,
1054
+ text: buildRouterOutput(cfg, input.arguments ?? ""),
1055
+ });
1056
+ }
1193
1057
  },
1194
1058
  };
1195
1059
  };