opencode-model-router 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -11,6 +11,23 @@ import {
11
11
  findProjectOverride,
12
12
  } from "./router/config";
13
13
  import type { RouterConfig, TierConfig, Preset, ModeConfig } from "./router/config";
14
+ import { buildAgentOptions, warnAgentOptionsEffortOnce } from "./router/agent-options";
15
+ import { selectTierPrompt } from "./router/prompts";
16
+ import {
17
+ buildTiersOutput,
18
+ buildPresetList,
19
+ buildPresetSwitched,
20
+ buildUnknownPreset,
21
+ buildNoModes,
22
+ buildBudgetList,
23
+ buildBudgetSwitched,
24
+ buildUnknownMode,
25
+ buildBypassMessage,
26
+ buildEnforceSet,
27
+ buildEnforceStatus,
28
+ buildOverridesOutput,
29
+ buildRouterHelp,
30
+ } from "./commands/output";
14
31
  import { fingerprintToolCall } from "./guard/fingerprint";
15
32
  import { detectNarration } from "./guard/narration";
16
33
  import {
@@ -33,6 +50,7 @@ import {
33
50
  import type { Cap, SubagentState } from "./router/sessions";
34
51
  import { createTrajectoryStore } from "./telemetry/trajectory";
35
52
  import { createGuardStore } from "./guard/store";
53
+ import { createIdleTtlSweeper } from "./router/idle-sweep";
36
54
  import { guardBeforeCall, guardAfterCall, formatScorecard } from "./guard/enforce";
37
55
  import { mkdirSync, writeFileSync, existsSync } from "node:fs";
38
56
  import { tmpdir } from "node:os";
@@ -42,7 +60,14 @@ import { access, readFile as fsReadFile } from "node:fs/promises";
42
60
  import { tool } from "@opencode-ai/plugin";
43
61
  import { scrubText } from "./guard/scrub";
44
62
  import { accept } from "./verify/gate";
45
- import { createMutexRegistry } from "./verify/deterministic";
63
+ import { createVerificationWiring, extractAssistantText } from "./verify/wiring";
64
+ import {
65
+ DEFAULT_DELEGATE_PROMPT_TIMEOUT_MS,
66
+ DEFAULT_GATE_BUDGET_MS,
67
+ RouterTimeoutError,
68
+ timeoutMs,
69
+ withTimeout,
70
+ } from "./verify/timeout";
46
71
  import {
47
72
  createChangedFileStore,
48
73
  parseTaskResult,
@@ -100,223 +125,76 @@ function saveEnforcementMode(mode: "off" | "advisory" | "enforced"): void {
100
125
  invalidateConfigCache();
101
126
  }
102
127
 
128
+ /**
129
+ * `/router` dispatch. Decides and persists here; rendering lives in
130
+ * src/commands/output.ts.
131
+ */
103
132
  function buildRouterOutput(cfg: RouterConfig, args: string): string {
104
133
  const tokens = (args ?? "").trim().split(/\s+/).filter(Boolean);
105
134
  const sub = (tokens[0] ?? "").toLowerCase();
135
+
106
136
  if (sub === "enforce") {
107
137
  const mode = (tokens[1] ?? "").toLowerCase();
108
138
  if (mode === "off" || mode === "advisory" || mode === "enforced") {
109
139
  saveEnforcementMode(mode);
110
- const desc =
111
- mode === "off"
112
- ? "Hard-block guard disabled (default routing behaviour)."
113
- : mode === "advisory"
114
- ? "Guard evaluates and surfaces banners but never hard-blocks."
115
- : "Guard hard-blocks subagent tool calls that violate budget / redundancy / self-script policy.";
116
- return [
117
- `Enforcement mode set to **${mode}** and persisted.`,
118
- "",
119
- desc,
120
- "",
121
- "Note: the `MODEL_ROUTER_ENFORCE` env var, when set to `0` or `1`, overrides this setting.",
122
- ].join("\n");
140
+ return buildEnforceSet(mode);
123
141
  }
124
- const current = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
125
- return [
126
- `Current enforcement mode: **${current}**`,
127
- "",
128
- "Usage: `/router enforce <off|advisory|enforced>`",
129
- ].join("\n");
142
+ return buildEnforceStatus(
143
+ resolveEnforcementMode({ config: cfg, env: process.env }).mode,
144
+ );
130
145
  }
146
+
131
147
  if (sub === "overrides") {
132
- const globalP = overridePath();
148
+ const globalPath = overridePath();
133
149
  const foundLocal = findProjectOverride();
134
- const localP = foundLocal ?? localOverridePath();
135
- const mark = (p: string) => (existsSync(p) ? "present" : "absent");
136
- const localNote = foundLocal
137
- ? ""
138
- : ` _(create at \`${localP}\`; the project file is searched upward from the working dir to the repo root)_`;
139
- return [
140
- `# Model Router — config overrides`,
141
- "",
142
- "Config is loaded lowest→highest priority; each layer deep-merges over the previous one:",
143
- "",
144
- "1. bundled `tiers.json` (defaults)",
145
- `2. global — \`${globalP}\` _(${mark(globalP)})_`,
146
- `3. project — \`${localP}\` _(${mark(localP)})_${localNote}`,
147
- "",
148
- `Active preset: **${cfg.activePreset}**. Run \`/tiers\` to see the effective models after merging.`,
149
- "",
150
- "Create either file to customize models/tiers/presets without editing the cached `tiers.json`. Objects merge recursively; arrays and scalars are replaced.",
151
- ].join("\n");
152
- }
153
- const current = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
154
- return [
155
- `# Model Router`,
156
- `Enforcement: **${current}**`,
157
- "",
158
- "Commands:",
159
- "- `/router enforce <off|advisory|enforced>` — set hard-block enforcement (persisted)",
160
- "- `/router overrides` — show the global + project override file paths and precedence",
161
- "- `/tiers`, `/preset`, `/budget`, `/bypass`, `/annotate-plan`",
162
- ].join("\n");
163
- }
164
-
165
- // ---------------------------------------------------------------------------
166
- // Build agent options from tier config
167
- // ---------------------------------------------------------------------------
168
-
169
- function buildAgentOptions(tier: TierConfig): Record<string, unknown> {
170
- const opts: Record<string, unknown> = {};
171
-
172
- // Anthropic thinking config
173
- if (tier.thinking) {
174
- if (tier.thinking.budgetTokens) {
175
- opts.budget_tokens = tier.thinking.budgetTokens;
176
- }
177
- }
178
-
179
- // OpenAI reasoning config
180
- if (tier.reasoning) {
181
- if (tier.reasoning.effort) {
182
- opts.reasoning_effort = tier.reasoning.effort;
183
- }
184
- if (tier.reasoning.summary) {
185
- opts.reasoning_summary = tier.reasoning.summary;
186
- }
187
- }
188
-
189
- return Object.keys(opts).length > 0 ? opts : {};
190
- }
191
-
192
- // ---------------------------------------------------------------------------
193
- // /tiers command output
194
- // ---------------------------------------------------------------------------
195
-
196
- function buildTiersOutput(cfg: RouterConfig): string {
197
- const tiers = getActiveTiers(cfg);
198
- const lines: string[] = [
199
- `# Model Delegation Tiers`,
200
- `Active preset: **${cfg.activePreset}**\n`,
201
- ];
202
-
203
- for (const [name, tier] of Object.entries(tiers)) {
204
- const thinkingStr = tier.thinking
205
- ? ` | thinking: ${tier.thinking.budgetTokens} tokens`
206
- : tier.reasoning
207
- ? ` | reasoning: effort=${tier.reasoning.effort}`
208
- : "";
209
- lines.push(`## @${name} -> \`${tier.model}\`${thinkingStr}`);
210
- if (tier.description) lines.push(tier.description);
211
- lines.push(`Steps: ${tier.steps ?? "default"}`);
212
- const whenToUse = tier.whenToUse ?? [];
213
- lines.push(whenToUse.length ? `Use when: ${whenToUse.join(", ")}\n` : "");
150
+ const localPath = foundLocal ?? localOverridePath();
151
+ return buildOverridesOutput({
152
+ globalPath,
153
+ globalPresent: existsSync(globalPath),
154
+ localPath,
155
+ localPresent: existsSync(localPath),
156
+ localFound: foundLocal !== undefined,
157
+ activePreset: cfg.activePreset,
158
+ });
214
159
  }
215
160
 
216
- lines.push("## Delegation Rules");
217
- cfg.rules.forEach((r) => lines.push(`- ${r}`));
218
- lines.push(`\nDefault tier: @${cfg.defaultTier}`);
219
- lines.push(`\nAvailable presets: ${Object.keys(cfg.presets).join(", ")}`);
220
- lines.push(`Switch with: \`/preset <name>\``);
221
- lines.push(`Edit \`tiers.json\` to customize.`);
222
-
223
- return lines.join("\n");
161
+ return buildRouterHelp(
162
+ resolveEnforcementMode({ config: cfg, env: process.env }).mode,
163
+ );
224
164
  }
225
165
 
226
- // ---------------------------------------------------------------------------
227
- // /budget command output
228
- // ---------------------------------------------------------------------------
229
-
166
+ /** `/budget` dispatch. Persists the switch, then renders. */
230
167
  function buildBudgetOutput(cfg: RouterConfig, args: string): string {
231
168
  const modes = cfg.modes;
232
- if (!modes || Object.keys(modes).length === 0) {
233
- return 'No modes configured in tiers.json. Add a "modes" section to enable budget mode.';
234
- }
169
+ if (!modes || Object.keys(modes).length === 0) return buildNoModes();
235
170
 
236
171
  const requested = args.trim().toLowerCase();
237
- const currentMode = cfg.activeMode || "normal";
238
-
239
- // No args: show current mode and available modes
240
- if (!requested) {
241
- const lines = ["# Routing Modes\n"];
242
- for (const [name, mode] of Object.entries(modes)) {
243
- const active = name === currentMode ? " <- active" : "";
244
- lines.push(
245
- `- **${name}**${active}: ${mode.description} (default tier: @${mode.defaultTier})`,
246
- );
247
- }
248
- lines.push(`\nSwitch with: \`/budget <mode>\``);
249
- return lines.join("\n");
250
- }
172
+ if (!requested) return buildBudgetList(cfg);
251
173
 
252
- // Switch mode
253
- if (modes[requested]) {
174
+ const mode = modes[requested];
175
+ if (mode) {
254
176
  saveActiveMode(requested);
255
- const mode = modes[requested];
256
- return [
257
- `Routing mode switched to **${requested}**.`,
258
- "",
259
- mode.description,
260
- `Default tier: @${mode.defaultTier}`,
261
- ...(mode.overrideRules?.length
262
- ? ["", "Active rules:", ...mode.overrideRules.map((r) => `- ${r}`)]
263
- : []),
264
- "",
265
- "Mode change takes effect immediately on the next message.",
266
- ].join("\n");
177
+ return buildBudgetSwitched(mode, requested);
267
178
  }
268
179
 
269
- return `Unknown mode: "${requested}". Available: ${Object.keys(modes).join(", ")}`;
180
+ return buildUnknownMode(modes, requested);
270
181
  }
271
182
 
272
- // ---------------------------------------------------------------------------
273
- // /preset command output
274
- // ---------------------------------------------------------------------------
275
-
183
+ /** `/preset` dispatch. Persists the switch, then renders. */
276
184
  function buildPresetOutput(cfg: RouterConfig, args: string): string {
277
185
  const requestedPreset = args.trim();
186
+ if (!requestedPreset) return buildPresetList(cfg);
278
187
 
279
- // No args: show available presets
280
- if (!requestedPreset) {
281
- const lines = ["# Available Presets\n"];
282
- for (const [name, tiers] of Object.entries(cfg.presets)) {
283
- const active = name === cfg.activePreset ? " <- active" : "";
284
- const models = Object.entries(tiers)
285
- .map(([tier, t]) => `${tier}: ${t.model.split("/").pop()}`)
286
- .join(", ");
287
- lines.push(`- **${name}**${active}: ${models}`);
288
- }
289
- lines.push(`\nSwitch with: \`/preset <name>\``);
290
- return lines.join("\n");
291
- }
292
-
293
- // Switch preset
294
188
  const resolvedPreset = resolvePresetName(cfg, requestedPreset);
295
189
  if (resolvedPreset) {
296
190
  saveActivePreset(resolvedPreset);
297
191
  cfg.activePreset = resolvedPreset;
298
- const tiers = cfg.presets[resolvedPreset]!;
299
- const models = Object.entries(tiers)
300
- .map(([tier, t]) => ` @${tier} -> ${t.model}`)
301
- .join("\n");
302
- return [
303
- `Preset switched to **${resolvedPreset}**.`,
304
- "",
305
- models,
306
- "",
307
- "Selection is now persisted in ~/.config/opencode/opencode-model-router.state.json.",
308
- "Restart OpenCode for subagent model registration to take effect.",
309
- "System prompt delegation rules update immediately.",
310
- ].join("\n");
192
+ return buildPresetSwitched(cfg, resolvedPreset);
311
193
  }
312
194
 
313
- return `Unknown preset: "${requestedPreset}". Available: ${Object.keys(cfg.presets).join(", ")}`;
195
+ return buildUnknownPreset(cfg, requestedPreset);
314
196
  }
315
197
 
316
- // ---------------------------------------------------------------------------
317
- // Plugin
318
- // ---------------------------------------------------------------------------
319
-
320
198
  const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
321
199
  let cfg = loadConfig();
322
200
  const activeTiers = getActiveTiers(cfg);
@@ -336,120 +214,27 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
336
214
  const guardStore = createGuardStore();
337
215
 
338
216
  const changedFileStore = createChangedFileStore();
339
- const graderSessions = new Set<string>();
340
-
341
- // Layer-2 real adapters (live-only; every call site is fail-closed).
342
- const execSeam = (
343
- command: string,
344
- opts?: { cwd?: string; timeoutMs?: number },
345
- ): Promise<{ code: number; stdout: string; stderr: string; timedOut: boolean }> =>
346
- new Promise((resolve) => {
347
- try {
348
- nodeExec(
349
- command,
350
- {
351
- cwd: opts?.cwd ?? ctx.directory,
352
- timeout: opts?.timeoutMs ?? 120000,
353
- maxBuffer: 10 * 1024 * 1024,
354
- windowsHide: true,
355
- },
356
- (err: any, stdout: any, stderr: any) => {
357
- const timedOut = !!(err && err.killed && err.signal === "SIGTERM");
358
- const code =
359
- err && typeof err.code === "number" ? err.code : err ? 1 : 0;
360
- resolve({
361
- code,
362
- stdout: String(stdout ?? ""),
363
- stderr: String(stderr ?? ""),
364
- timedOut,
365
- });
366
- },
367
- );
368
- } catch {
369
- resolve({ code: 1, stdout: "", stderr: "exec failed", timedOut: false });
370
- }
371
- });
372
- const fsSeam = {
373
- async fileExists(p: string): Promise<boolean> {
374
- try {
375
- await access(isAbsolute(p) ? p : join(ctx.directory, p));
376
- return true;
377
- } catch {
378
- return false;
379
- }
380
- },
381
- async readFile(p: string): Promise<string> {
382
- return await fsReadFile(isAbsolute(p) ? p : join(ctx.directory, p), "utf-8");
383
- },
384
- };
385
- const verifyMutex = createMutexRegistry();
386
- // Best-effort disposal of a plugin-created child session: abort any in-flight
387
- // work, then delete it so it does not linger forever as a top-level session in
388
- // the TUI. Fail-soft by contract — never throws, so it is safe to call from a
389
- // finally without masking the original error.
390
- const disposeChildSession = async (sid: string): Promise<void> => {
391
- try {
392
- await ctx.client.session.abort({ path: { id: sid } });
393
- } catch {
394
- // best-effort: the session may already have completed or been removed
395
- }
396
- try {
397
- await ctx.client.session.delete({ path: { id: sid } });
398
- } catch {
399
- // best-effort: cleanup must never break the run
400
- }
401
- };
402
217
 
403
- const dispatchGrader = async (
404
- req: {
405
- tier: string;
406
- system: string;
407
- prompt: string;
408
- },
409
- parentSessionID?: string,
410
- ): Promise<{ sessionID: string; text: string }> => {
411
- const created: any = await ctx.client.session.create({
412
- body: { ...(parentSessionID ? { parentID: parentSessionID } : {}) },
218
+ // Idle-TTL maintenance for the four per-instance stores. No timer is
219
+ // scheduled: the sweeper is invoked opportunistically from chat.message and
220
+ // self-throttles, so a long-lived plugin instance cannot accumulate state for
221
+ // sessions that went away without a teardown hook.
222
+ const sweepIdleStores = createIdleTtlSweeper([
223
+ () => sessionStore.sweep(),
224
+ () => guardStore.sweep(),
225
+ () => trajectoryStore.sweep(),
226
+ () => changedFileStore.sweep(),
227
+ ]);
228
+
229
+ // Layer-2's impure corner: exec, fs, and the opencode client, built once and
230
+ // read back through getConfig so a reloaded cfg (from /preset, /budget or
231
+ // /router enforce) applies to graded work too.
232
+ const { graderSessions, dispatchGrader, buildGateDeps, disposeChildSession } =
233
+ createVerificationWiring({
234
+ client: ctx.client,
235
+ directory: ctx.directory,
236
+ getConfig: () => cfg,
413
237
  });
414
- const sid: string | undefined = created?.data?.id;
415
- if (!sid) return { sessionID: "", text: "" };
416
- graderSessions.add(sid);
417
- try {
418
- const model = tierModel(cfg, req.tier) ?? undefined;
419
- const res: any = await ctx.client.session.prompt({
420
- path: { id: sid },
421
- body: {
422
- ...(model ? { model } : {}),
423
- system: req.system,
424
- parts: [{ type: "text", text: req.prompt }],
425
- },
426
- });
427
- const parts: any[] = res?.data?.parts ?? [];
428
- const text = parts
429
- .filter((p) => p?.type === "text" && typeof p.text === "string")
430
- .map((p) => p.text)
431
- .join("\n");
432
- return { sessionID: sid, text };
433
- } finally {
434
- graderSessions.delete(sid);
435
- await disposeChildSession(sid);
436
- }
437
- };
438
- const buildGateDeps = (parentSessionID?: string) => ({
439
- deterministic: {
440
- exec: execSeam,
441
- fs: fsSeam,
442
- cwd: ctx.directory,
443
- mutex: verifyMutex,
444
- },
445
- checker: {
446
- dispatchGrader: (req: { tier: string; system: string; prompt: string }) =>
447
- dispatchGrader(req, parentSessionID),
448
- ladder: ["fast", "medium", "heavy"],
449
- minGraderTier: cfg.enforcement?.verify?.minGraderTier ?? null,
450
- },
451
- require: cfg.enforcement?.verify?.require,
452
- });
453
238
 
454
239
  // Best-effort, secret-free delegate scorecard dump (counts only).
455
240
  const dumpDelegateScorecard = (
@@ -496,12 +281,19 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
496
281
  .describe(
497
282
  "Optional [acceptance]...[/acceptance] block defining the Definition of Done (check: / criteria: / deliverable: directives).",
498
283
  ),
284
+ cwd: tool.schema
285
+ .string()
286
+ .optional()
287
+ .describe(
288
+ "Optional working directory used to VERIFY the result: relative check paths resolve against it and the grader session runs in it. It does NOT scope the producer subagent, so the task text must still tell the producer where to work.",
289
+ ),
499
290
  },
500
291
  async execute(
501
292
  args: {
502
293
  task: string;
503
294
  tier?: string;
504
295
  acceptance?: string;
296
+ cwd?: string;
505
297
  },
506
298
  toolCtx?: { sessionID?: string },
507
299
  ): Promise<string> {
@@ -540,16 +332,26 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
540
332
  let producerText = "";
541
333
  let forcing: string | null = null;
542
334
 
543
- while (true) {
544
- if (safety++ > safetyMax) {
545
- return (
546
- `[router status: unmet] delegation stopped by the safety net after ` +
547
- `${state.totalAttempts} attempt(s).\n\n${scrubText(producerText)}`
548
- );
549
- }
550
- const tier = state.currentTier;
551
- const taskText = forcing
552
- ? `${scrubText(forcing)}\n\n${args.task}`
335
+ /**
336
+ * One turn of the escalation ladder: create a producer session, run
337
+ * the task on it, put the result through the acceptance gate, then
338
+ * tear the session down. Returns null when the backend refused to
339
+ * create a session, the one failure the caller cannot retry.
340
+ *
341
+ * Split out because the loop is about when to *stop* — safety net,
342
+ * attempt accounting, tier advancement — and a ninety-line attempt
343
+ * in the middle of it obscured both halves.
344
+ */
345
+ const runProducerAttempt = async (
346
+ tier: string,
347
+ forcingNote: string | null,
348
+ ): Promise<{
349
+ sessionID: string;
350
+ text: string;
351
+ gateRes: Awaited<ReturnType<typeof accept>>;
352
+ } | null> => {
353
+ const taskText = forcingNote
354
+ ? `${scrubText(forcingNote)}\n\n${args.task}`
553
355
  : args.task;
554
356
 
555
357
  const created: any = await ctx.client.session.create({
@@ -558,9 +360,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
558
360
  },
559
361
  });
560
362
  const producerSid: string | undefined = created?.data?.id;
561
- if (!producerSid) {
562
- return "[router] delegate failed: could not create a producer session.";
563
- }
363
+ if (!producerSid) return null;
564
364
  producerSessions.push(producerSid);
565
365
  // Compose with Layer 1: guard the plugin-created producer session.
566
366
  try {
@@ -570,29 +370,40 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
570
370
  }
571
371
 
572
372
  const model = tierModel(activeCfg, tier) ?? undefined;
573
- producerText = "";
373
+ let producerText = "";
574
374
  // Provider-failover vs quality-escalation precedence (Phase 3.3):
575
375
  // Provider-failover is advisory only — a text chain injected into the orchestrator
576
376
  // system prompt (buildFallbackInstructions). It is orthogonal to this runtime ladder.
577
- // A transport/API error here is caught, yields an empty artefact, and is treated as
377
+ // A transport/API error here becomes an explicit failed attempt and is treated as
578
378
  // exactly ONE failed attempt by the quality-escalation ladder (no provider swap, no
579
379
  // double-counted attempt). API error => (advisory) provider failover; verification
580
380
  // FAIL => (runtime) quality escalation.
381
+ //
382
+ // The prompt is time-boxed: a model that never answers would
383
+ // otherwise hang the delegate forever. A timeout is folded into
384
+ // the same failed-attempt path as any other producer error — it
385
+ // is never an empty artefact that a lenient DoD could pass.
386
+ let producerError: string | null = null;
581
387
  try {
582
- const res: any = await ctx.client.session.prompt({
583
- path: { id: producerSid },
584
- body: {
585
- ...(model ? { model } : {}),
586
- ...(tier ? { agent: tier } : {}),
587
- parts: [{ type: "text", text: taskText }],
588
- },
589
- });
590
- const parts: any[] = res?.data?.parts ?? [];
591
- producerText = parts
592
- .filter((p) => p?.type === "text" && typeof p.text === "string")
593
- .map((p) => p.text)
594
- .join("\n");
595
- } catch {
388
+ const res: any = await withTimeout(
389
+ ctx.client.session.prompt({
390
+ path: { id: producerSid },
391
+ body: {
392
+ ...(model ? { model } : {}),
393
+ ...(tier ? { agent: tier } : {}),
394
+ parts: [{ type: "text", text: taskText }],
395
+ },
396
+ }),
397
+ timeoutMs(
398
+ activeCfg.enforcement?.verify?.delegateTimeoutMs,
399
+ DEFAULT_DELEGATE_PROMPT_TIMEOUT_MS,
400
+ ),
401
+ "delegate producer prompt",
402
+ );
403
+ producerText = extractAssistantText(res);
404
+ } catch (error) {
405
+ producerError =
406
+ error instanceof Error ? error.message : String(error);
596
407
  producerText = "";
597
408
  }
598
409
 
@@ -604,20 +415,69 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
604
415
  producerTier: tier,
605
416
  };
606
417
 
418
+ const gateBudgetMs = timeoutMs(
419
+ activeCfg.enforcement?.verify?.gateBudgetMs,
420
+ DEFAULT_GATE_BUDGET_MS,
421
+ );
422
+ // Grader sessions opened by THIS accept() call, and only those.
423
+ const gateGraderSessions = new Set<string>();
607
424
  let gateRes;
608
425
  try {
609
- gateRes = await accept(
610
- { dod, trivial: false, mode: "modeA" },
611
- artefact,
612
- buildGateDeps(toolCtx?.sessionID),
613
- );
614
- } catch {
426
+ gateRes = producerError
427
+ ? {
428
+ accepted: false,
429
+ verdict: {
430
+ pass: false,
431
+ method: "none" as const,
432
+ reasons: [`producer failed: ${producerError}`],
433
+ },
434
+ dodSource: dod.source,
435
+ }
436
+ : await withTimeout(
437
+ accept(
438
+ {
439
+ dod,
440
+ trivial: false,
441
+ mode: "modeA",
442
+ ...(args.cwd ? { cwd: args.cwd } : {}),
443
+ },
444
+ artefact,
445
+ buildGateDeps(toolCtx?.sessionID, gateGraderSessions),
446
+ ),
447
+ gateBudgetMs,
448
+ "verification gate",
449
+ );
450
+ } catch (error) {
451
+ // A gate that ran out of budget is UNMET, never accepted: the
452
+ // one thing worse than a slow verifier is a fast fabricated
453
+ // pass. Abort any grader still in flight so the ceiling is a
454
+ // real cancellation and not just a stopped wait.
455
+ //
456
+ // Scoped to THIS gate invocation's graders. The wiring-global
457
+ // graderSessions set is shared by every concurrent delegation,
458
+ // so aborting it here would kill a healthy grader belonging to
459
+ // someone else's delegation — reachable with the shipped
460
+ // config, where a deterministic check may run a command for up
461
+ // to 120s against a 90s gate budget.
462
+ if (error instanceof RouterTimeoutError) {
463
+ for (const gsid of gateGraderSessions) {
464
+ try {
465
+ await ctx.client.session.abort({ path: { id: gsid } });
466
+ } catch {
467
+ // best-effort: the gate result stands either way
468
+ }
469
+ }
470
+ }
615
471
  gateRes = {
616
472
  accepted: false,
617
473
  verdict: {
618
474
  pass: false,
619
475
  method: "none" as const,
620
- reasons: ["verification failed (fail-closed)"],
476
+ reasons: [
477
+ error instanceof RouterTimeoutError
478
+ ? `verification gate timed out after ${gateBudgetMs}ms`
479
+ : "verification failed (fail-closed)",
480
+ ],
621
481
  },
622
482
  dodSource: dod.source,
623
483
  };
@@ -639,6 +499,25 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
639
499
  // so a long ladder never accumulates live sessions.
640
500
  await disposeChildSession(producerSid);
641
501
 
502
+ return { sessionID: producerSid, text: producerText, gateRes };
503
+ };
504
+
505
+ while (true) {
506
+ if (safety++ > safetyMax) {
507
+ return (
508
+ `[router status: unmet] delegation stopped by the safety net after ` +
509
+ `${state.totalAttempts} attempt(s).\n\n${scrubText(producerText)}`
510
+ );
511
+ }
512
+ const tier = state.currentTier;
513
+ const attempt = await runProducerAttempt(tier, forcing);
514
+ if (!attempt) {
515
+ return "[router] delegate failed: could not create a producer session.";
516
+ }
517
+ producerText = attempt.text;
518
+ const producerSid = attempt.sessionID;
519
+ const gateRes = attempt.gateRes;
520
+
642
521
  const costRatio =
643
522
  typeof tiersForCost?.[tier]?.costRatio === "number"
644
523
  ? tiersForCost[tier].costRatio
@@ -728,11 +607,39 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
728
607
  try {
729
608
  cfg = loadConfig();
730
609
  } catch {}
610
+ try {
611
+ sweepIdleStores();
612
+ } catch {
613
+ // best-effort maintenance: never break a real turn
614
+ }
731
615
  const tierNames = Object.keys(getActiveTiers(cfg));
732
- sessionStore.registerFromChatMessage(input, output, cfg, tierNames);
616
+ const sid = input?.sessionID;
617
+ try {
618
+ const registration = sessionStore.registerFromChatMessage(
619
+ input,
620
+ output,
621
+ cfg,
622
+ tierNames,
623
+ );
624
+ // A same-session same-tier re-registration is a resumed dispatch
625
+ // (how an opencode task_id resume reaches this hook): start a new
626
+ // per-dispatch guard round and count it in telemetry.
627
+ if (registration.resumed === true && typeof sid === "string") {
628
+ guardStore.beginDispatch(sid);
629
+ trajectoryStore.recordResume(sid, input?.agent ?? null);
630
+ }
631
+ // KNOWN RESIDUAL: a fresh registration over an EXISTING session (same
632
+ // sessionID, different tier) resets session cap state but leaves guard
633
+ // state alone, so the guard keeps counting from the old dispatch. The
634
+ // desync can only make the guard stricter, never laxer, and opencode
635
+ // assigns one agent per subagent session — so this is documented in
636
+ // docs/CONFIG_REFERENCE.md rather than fixed by clearing guard state,
637
+ // which would also drop deliverable and fingerprint history.
638
+ } catch {
639
+ // best-effort: never crash a real session during registration
640
+ }
733
641
 
734
642
  // Record-only: initialise a trajectory scorecard for tracked subagents.
735
- const sid = input?.sessionID;
736
643
  if (sid && sessionStore.isSubagent(sid)) {
737
644
  trajectoryStore.ensure(sid, input?.agent ?? null);
738
645
  }
@@ -750,6 +657,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
750
657
  if (!sid || !sessionStore.isSubagent(sid) || typeof input?.tool !== "string") {
751
658
  return;
752
659
  }
660
+ // Start-of-call refresh: the idle TTL must cover the tool's runtime, not
661
+ // just the moment it finished.
662
+ sessionStore.touchIfTracked(sid);
753
663
  let res;
754
664
  try {
755
665
  res = guardBeforeCall({
@@ -868,7 +778,17 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
868
778
  }
869
779
 
870
780
  const res = await accept(
871
- { dod, trivial, mode: "modeA" },
781
+ {
782
+ dod,
783
+ trivial,
784
+ mode: "modeA",
785
+ // The built-in task tool declares no cwd of its own, but if a
786
+ // caller supplies one it scopes verification the same way the
787
+ // delegate tool's does.
788
+ ...(typeof input?.args?.cwd === "string" && input.args.cwd
789
+ ? { cwd: input.args.cwd }
790
+ : {}),
791
+ },
872
792
  artefact,
873
793
  buildGateDeps(),
874
794
  );
@@ -958,8 +878,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
958
878
  opencodeConfig.agent ??= {};
959
879
 
960
880
  for (const [name, tier] of Object.entries(activeTiers)) {
961
- // Resolve prompt: per-tier override wins; otherwise fall back to global tierPrompts[name].
962
- const resolvedPrompt = tier.prompt ?? cfg.tierPrompts?.[name];
881
+ // Resolve prompt: per-tier override wins; otherwise fall back to the
882
+ // style-appropriate default (goal-oriented or global tierPrompts[name]).
883
+ const resolvedPrompt = tier.prompt ?? selectTierPrompt(name, tier, cfg);
963
884
 
964
885
  // For Claude-backed tiers, prepend an adversarial opener that revokes
965
886
  // the cached "Claude Code exploratory agent" priming for this dispatch.
@@ -990,10 +911,16 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
990
911
  }
991
912
 
992
913
  // Apply provider-specific options
993
- const opts = buildAgentOptions(tier);
914
+ const opts = buildAgentOptions(tier, name);
994
915
  if (Object.keys(opts).length > 0) {
995
916
  agentDef.options = opts;
996
917
  }
918
+ if (typeof opts.effort === "string") {
919
+ warnAgentOptionsEffortOnce(
920
+ "anthropic-effort-dependency",
921
+ "effort on Anthropic models requires the opencode-anthropic-fix plugin (commit 307aea9+ for fable/mythos); non-adaptive Claude models (e.g. haiku) silently strip effort at the API layer, and without the plugin a top-level effort can break Claude-Code billing fingerprinting",
922
+ );
923
+ }
997
924
 
998
925
  opencodeConfig.agent[name] = agentDef;
999
926
  }
@@ -1126,13 +1053,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1126
1053
  } else {
1127
1054
  bypassed = !bypassed;
1128
1055
  }
1129
- const status = bypassed ? "ON" : "OFF";
1130
- const desc = bypassed
1131
- ? "Model-router is **bypassed**. Delegation protocol, cap enforcement, and narration detection are disabled. The model will run without routing rules until you run `/bypass off` or restart OpenCode."
1132
- : "Model-router is **active**. Delegation protocol and all enforcement rules are in effect.";
1133
1056
  output.parts.push({
1134
1057
  type: "text" as const,
1135
- text: `# Bypass: ${status}\n\n${desc}`,
1058
+ text: buildBypassMessage(bypassed),
1136
1059
  });
1137
1060
  }
1138
1061