opencode-model-router 1.4.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +134 -12
- package/package.json +1 -1
- package/src/commands/output.ts +236 -0
- package/src/guard/enforce.ts +14 -1
- package/src/guard/guards.ts +26 -0
- package/src/guard/store.ts +46 -3
- package/src/index.ts +272 -321
- package/src/router/agent-options.ts +118 -0
- package/src/router/config.ts +555 -46
- package/src/router/idle-sweep.ts +35 -0
- package/src/router/jsonc.ts +92 -0
- package/src/router/prompts.ts +72 -0
- package/src/router/protocol.ts +1 -1
- package/src/router/sessions.ts +159 -22
- package/src/telemetry/trajectory.ts +48 -1
- package/src/verify/checker.ts +47 -1
- package/src/verify/deterministic.ts +13 -5
- package/src/verify/dispatch.ts +27 -2
- package/src/verify/gate.ts +25 -1
- package/src/verify/paths.ts +29 -0
- package/src/verify/timeout.ts +93 -0
- package/src/verify/wiring.ts +267 -0
- package/tiers.json +79 -6
package/src/index.ts
CHANGED
|
@@ -6,8 +6,28 @@ import {
|
|
|
6
6
|
resolvePresetName,
|
|
7
7
|
writeState,
|
|
8
8
|
invalidateConfigCache,
|
|
9
|
+
overridePath,
|
|
10
|
+
localOverridePath,
|
|
11
|
+
findProjectOverride,
|
|
9
12
|
} from "./router/config";
|
|
10
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";
|
|
11
31
|
import { fingerprintToolCall } from "./guard/fingerprint";
|
|
12
32
|
import { detectNarration } from "./guard/narration";
|
|
13
33
|
import {
|
|
@@ -30,8 +50,9 @@ import {
|
|
|
30
50
|
import type { Cap, SubagentState } from "./router/sessions";
|
|
31
51
|
import { createTrajectoryStore } from "./telemetry/trajectory";
|
|
32
52
|
import { createGuardStore } from "./guard/store";
|
|
53
|
+
import { createIdleTtlSweeper } from "./router/idle-sweep";
|
|
33
54
|
import { guardBeforeCall, guardAfterCall, formatScorecard } from "./guard/enforce";
|
|
34
|
-
import { mkdirSync, writeFileSync } from "node:fs";
|
|
55
|
+
import { mkdirSync, writeFileSync, existsSync } from "node:fs";
|
|
35
56
|
import { tmpdir } from "node:os";
|
|
36
57
|
import { join, isAbsolute } from "node:path";
|
|
37
58
|
import { exec as nodeExec } from "node:child_process";
|
|
@@ -39,7 +60,14 @@ import { access, readFile as fsReadFile } from "node:fs/promises";
|
|
|
39
60
|
import { tool } from "@opencode-ai/plugin";
|
|
40
61
|
import { scrubText } from "./guard/scrub";
|
|
41
62
|
import { accept } from "./verify/gate";
|
|
42
|
-
import {
|
|
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";
|
|
43
71
|
import {
|
|
44
72
|
createChangedFileStore,
|
|
45
73
|
parseTaskResult,
|
|
@@ -97,199 +125,76 @@ function saveEnforcementMode(mode: "off" | "advisory" | "enforced"): void {
|
|
|
97
125
|
invalidateConfigCache();
|
|
98
126
|
}
|
|
99
127
|
|
|
128
|
+
/**
|
|
129
|
+
* `/router` dispatch. Decides and persists here; rendering lives in
|
|
130
|
+
* src/commands/output.ts.
|
|
131
|
+
*/
|
|
100
132
|
function buildRouterOutput(cfg: RouterConfig, args: string): string {
|
|
101
133
|
const tokens = (args ?? "").trim().split(/\s+/).filter(Boolean);
|
|
102
134
|
const sub = (tokens[0] ?? "").toLowerCase();
|
|
135
|
+
|
|
103
136
|
if (sub === "enforce") {
|
|
104
137
|
const mode = (tokens[1] ?? "").toLowerCase();
|
|
105
138
|
if (mode === "off" || mode === "advisory" || mode === "enforced") {
|
|
106
139
|
saveEnforcementMode(mode);
|
|
107
|
-
|
|
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");
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
// ---------------------------------------------------------------------------
|
|
140
|
-
// Build agent options from tier config
|
|
141
|
-
// ---------------------------------------------------------------------------
|
|
142
|
-
|
|
143
|
-
function buildAgentOptions(tier: TierConfig): Record<string, unknown> {
|
|
144
|
-
const opts: Record<string, unknown> = {};
|
|
145
|
-
|
|
146
|
-
// Anthropic thinking config
|
|
147
|
-
if (tier.thinking) {
|
|
148
|
-
if (tier.thinking.budgetTokens) {
|
|
149
|
-
opts.budget_tokens = tier.thinking.budgetTokens;
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
// OpenAI reasoning config
|
|
154
|
-
if (tier.reasoning) {
|
|
155
|
-
if (tier.reasoning.effort) {
|
|
156
|
-
opts.reasoning_effort = tier.reasoning.effort;
|
|
157
|
-
}
|
|
158
|
-
if (tier.reasoning.summary) {
|
|
159
|
-
opts.reasoning_summary = tier.reasoning.summary;
|
|
140
|
+
return buildEnforceSet(mode);
|
|
160
141
|
}
|
|
142
|
+
return buildEnforceStatus(
|
|
143
|
+
resolveEnforcementMode({ config: cfg, env: process.env }).mode,
|
|
144
|
+
);
|
|
161
145
|
}
|
|
162
146
|
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
];
|
|
176
|
-
|
|
177
|
-
for (const [name, tier] of Object.entries(tiers)) {
|
|
178
|
-
const thinkingStr = tier.thinking
|
|
179
|
-
? ` | thinking: ${tier.thinking.budgetTokens} tokens`
|
|
180
|
-
: tier.reasoning
|
|
181
|
-
? ` | reasoning: effort=${tier.reasoning.effort}`
|
|
182
|
-
: "";
|
|
183
|
-
lines.push(`## @${name} -> \`${tier.model}\`${thinkingStr}`);
|
|
184
|
-
lines.push(tier.description);
|
|
185
|
-
lines.push(`Steps: ${tier.steps ?? "default"}`);
|
|
186
|
-
lines.push(`Use when: ${tier.whenToUse.join(", ")}\n`);
|
|
147
|
+
if (sub === "overrides") {
|
|
148
|
+
const globalPath = overridePath();
|
|
149
|
+
const foundLocal = findProjectOverride();
|
|
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
|
+
});
|
|
187
159
|
}
|
|
188
160
|
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
lines.push(`\nAvailable presets: ${Object.keys(cfg.presets).join(", ")}`);
|
|
193
|
-
lines.push(`Switch with: \`/preset <name>\``);
|
|
194
|
-
lines.push(`Edit \`tiers.json\` to customize.`);
|
|
195
|
-
|
|
196
|
-
return lines.join("\n");
|
|
161
|
+
return buildRouterHelp(
|
|
162
|
+
resolveEnforcementMode({ config: cfg, env: process.env }).mode,
|
|
163
|
+
);
|
|
197
164
|
}
|
|
198
165
|
|
|
199
|
-
|
|
200
|
-
// /budget command output
|
|
201
|
-
// ---------------------------------------------------------------------------
|
|
202
|
-
|
|
166
|
+
/** `/budget` dispatch. Persists the switch, then renders. */
|
|
203
167
|
function buildBudgetOutput(cfg: RouterConfig, args: string): string {
|
|
204
168
|
const modes = cfg.modes;
|
|
205
|
-
if (!modes || Object.keys(modes).length === 0)
|
|
206
|
-
return 'No modes configured in tiers.json. Add a "modes" section to enable budget mode.';
|
|
207
|
-
}
|
|
169
|
+
if (!modes || Object.keys(modes).length === 0) return buildNoModes();
|
|
208
170
|
|
|
209
171
|
const requested = args.trim().toLowerCase();
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
// No args: show current mode and available modes
|
|
213
|
-
if (!requested) {
|
|
214
|
-
const lines = ["# Routing Modes\n"];
|
|
215
|
-
for (const [name, mode] of Object.entries(modes)) {
|
|
216
|
-
const active = name === currentMode ? " <- active" : "";
|
|
217
|
-
lines.push(
|
|
218
|
-
`- **${name}**${active}: ${mode.description} (default tier: @${mode.defaultTier})`,
|
|
219
|
-
);
|
|
220
|
-
}
|
|
221
|
-
lines.push(`\nSwitch with: \`/budget <mode>\``);
|
|
222
|
-
return lines.join("\n");
|
|
223
|
-
}
|
|
172
|
+
if (!requested) return buildBudgetList(cfg);
|
|
224
173
|
|
|
225
|
-
|
|
226
|
-
if (
|
|
174
|
+
const mode = modes[requested];
|
|
175
|
+
if (mode) {
|
|
227
176
|
saveActiveMode(requested);
|
|
228
|
-
|
|
229
|
-
return [
|
|
230
|
-
`Routing mode switched to **${requested}**.`,
|
|
231
|
-
"",
|
|
232
|
-
mode.description,
|
|
233
|
-
`Default tier: @${mode.defaultTier}`,
|
|
234
|
-
...(mode.overrideRules?.length
|
|
235
|
-
? ["", "Active rules:", ...mode.overrideRules.map((r) => `- ${r}`)]
|
|
236
|
-
: []),
|
|
237
|
-
"",
|
|
238
|
-
"Mode change takes effect immediately on the next message.",
|
|
239
|
-
].join("\n");
|
|
177
|
+
return buildBudgetSwitched(mode, requested);
|
|
240
178
|
}
|
|
241
179
|
|
|
242
|
-
return
|
|
180
|
+
return buildUnknownMode(modes, requested);
|
|
243
181
|
}
|
|
244
182
|
|
|
245
|
-
|
|
246
|
-
// /preset command output
|
|
247
|
-
// ---------------------------------------------------------------------------
|
|
248
|
-
|
|
183
|
+
/** `/preset` dispatch. Persists the switch, then renders. */
|
|
249
184
|
function buildPresetOutput(cfg: RouterConfig, args: string): string {
|
|
250
185
|
const requestedPreset = args.trim();
|
|
186
|
+
if (!requestedPreset) return buildPresetList(cfg);
|
|
251
187
|
|
|
252
|
-
// No args: show available presets
|
|
253
|
-
if (!requestedPreset) {
|
|
254
|
-
const lines = ["# Available Presets\n"];
|
|
255
|
-
for (const [name, tiers] of Object.entries(cfg.presets)) {
|
|
256
|
-
const active = name === cfg.activePreset ? " <- active" : "";
|
|
257
|
-
const models = Object.entries(tiers)
|
|
258
|
-
.map(([tier, t]) => `${tier}: ${t.model.split("/").pop()}`)
|
|
259
|
-
.join(", ");
|
|
260
|
-
lines.push(`- **${name}**${active}: ${models}`);
|
|
261
|
-
}
|
|
262
|
-
lines.push(`\nSwitch with: \`/preset <name>\``);
|
|
263
|
-
return lines.join("\n");
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
// Switch preset
|
|
267
188
|
const resolvedPreset = resolvePresetName(cfg, requestedPreset);
|
|
268
189
|
if (resolvedPreset) {
|
|
269
190
|
saveActivePreset(resolvedPreset);
|
|
270
191
|
cfg.activePreset = resolvedPreset;
|
|
271
|
-
|
|
272
|
-
const models = Object.entries(tiers)
|
|
273
|
-
.map(([tier, t]) => ` @${tier} -> ${t.model}`)
|
|
274
|
-
.join("\n");
|
|
275
|
-
return [
|
|
276
|
-
`Preset switched to **${resolvedPreset}**.`,
|
|
277
|
-
"",
|
|
278
|
-
models,
|
|
279
|
-
"",
|
|
280
|
-
"Selection is now persisted in ~/.config/opencode/opencode-model-router.state.json.",
|
|
281
|
-
"Restart OpenCode for subagent model registration to take effect.",
|
|
282
|
-
"System prompt delegation rules update immediately.",
|
|
283
|
-
].join("\n");
|
|
192
|
+
return buildPresetSwitched(cfg, resolvedPreset);
|
|
284
193
|
}
|
|
285
194
|
|
|
286
|
-
return
|
|
195
|
+
return buildUnknownPreset(cfg, requestedPreset);
|
|
287
196
|
}
|
|
288
197
|
|
|
289
|
-
// ---------------------------------------------------------------------------
|
|
290
|
-
// Plugin
|
|
291
|
-
// ---------------------------------------------------------------------------
|
|
292
|
-
|
|
293
198
|
const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
294
199
|
let cfg = loadConfig();
|
|
295
200
|
const activeTiers = getActiveTiers(cfg);
|
|
@@ -309,120 +214,27 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
309
214
|
const guardStore = createGuardStore();
|
|
310
215
|
|
|
311
216
|
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
|
-
// Best-effort disposal of a plugin-created child session: abort any in-flight
|
|
360
|
-
// work, then delete it so it does not linger forever as a top-level session in
|
|
361
|
-
// the TUI. Fail-soft by contract — never throws, so it is safe to call from a
|
|
362
|
-
// finally without masking the original error.
|
|
363
|
-
const disposeChildSession = async (sid: string): Promise<void> => {
|
|
364
|
-
try {
|
|
365
|
-
await ctx.client.session.abort({ path: { id: sid } });
|
|
366
|
-
} catch {
|
|
367
|
-
// best-effort: the session may already have completed or been removed
|
|
368
|
-
}
|
|
369
|
-
try {
|
|
370
|
-
await ctx.client.session.delete({ path: { id: sid } });
|
|
371
|
-
} catch {
|
|
372
|
-
// best-effort: cleanup must never break the run
|
|
373
|
-
}
|
|
374
|
-
};
|
|
375
217
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
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,
|
|
386
237
|
});
|
|
387
|
-
const sid: string | undefined = created?.data?.id;
|
|
388
|
-
if (!sid) return { sessionID: "", text: "" };
|
|
389
|
-
graderSessions.add(sid);
|
|
390
|
-
try {
|
|
391
|
-
const model = tierModel(cfg, req.tier) ?? undefined;
|
|
392
|
-
const res: any = await ctx.client.session.prompt({
|
|
393
|
-
path: { id: sid },
|
|
394
|
-
body: {
|
|
395
|
-
...(model ? { model } : {}),
|
|
396
|
-
system: req.system,
|
|
397
|
-
parts: [{ type: "text", text: req.prompt }],
|
|
398
|
-
},
|
|
399
|
-
});
|
|
400
|
-
const parts: any[] = res?.data?.parts ?? [];
|
|
401
|
-
const text = parts
|
|
402
|
-
.filter((p) => p?.type === "text" && typeof p.text === "string")
|
|
403
|
-
.map((p) => p.text)
|
|
404
|
-
.join("\n");
|
|
405
|
-
return { sessionID: sid, text };
|
|
406
|
-
} finally {
|
|
407
|
-
graderSessions.delete(sid);
|
|
408
|
-
await disposeChildSession(sid);
|
|
409
|
-
}
|
|
410
|
-
};
|
|
411
|
-
const buildGateDeps = (parentSessionID?: string) => ({
|
|
412
|
-
deterministic: {
|
|
413
|
-
exec: execSeam,
|
|
414
|
-
fs: fsSeam,
|
|
415
|
-
cwd: ctx.directory,
|
|
416
|
-
mutex: verifyMutex,
|
|
417
|
-
},
|
|
418
|
-
checker: {
|
|
419
|
-
dispatchGrader: (req: { tier: string; system: string; prompt: string }) =>
|
|
420
|
-
dispatchGrader(req, parentSessionID),
|
|
421
|
-
ladder: ["fast", "medium", "heavy"],
|
|
422
|
-
minGraderTier: cfg.enforcement?.verify?.minGraderTier ?? null,
|
|
423
|
-
},
|
|
424
|
-
require: cfg.enforcement?.verify?.require,
|
|
425
|
-
});
|
|
426
238
|
|
|
427
239
|
// Best-effort, secret-free delegate scorecard dump (counts only).
|
|
428
240
|
const dumpDelegateScorecard = (
|
|
@@ -469,12 +281,19 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
469
281
|
.describe(
|
|
470
282
|
"Optional [acceptance]...[/acceptance] block defining the Definition of Done (check: / criteria: / deliverable: directives).",
|
|
471
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
|
+
),
|
|
472
290
|
},
|
|
473
291
|
async execute(
|
|
474
292
|
args: {
|
|
475
293
|
task: string;
|
|
476
294
|
tier?: string;
|
|
477
295
|
acceptance?: string;
|
|
296
|
+
cwd?: string;
|
|
478
297
|
},
|
|
479
298
|
toolCtx?: { sessionID?: string },
|
|
480
299
|
): Promise<string> {
|
|
@@ -513,16 +332,26 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
513
332
|
let producerText = "";
|
|
514
333
|
let forcing: string | null = null;
|
|
515
334
|
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
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}`
|
|
526
355
|
: args.task;
|
|
527
356
|
|
|
528
357
|
const created: any = await ctx.client.session.create({
|
|
@@ -531,9 +360,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
531
360
|
},
|
|
532
361
|
});
|
|
533
362
|
const producerSid: string | undefined = created?.data?.id;
|
|
534
|
-
if (!producerSid)
|
|
535
|
-
return "[router] delegate failed: could not create a producer session.";
|
|
536
|
-
}
|
|
363
|
+
if (!producerSid) return null;
|
|
537
364
|
producerSessions.push(producerSid);
|
|
538
365
|
// Compose with Layer 1: guard the plugin-created producer session.
|
|
539
366
|
try {
|
|
@@ -543,29 +370,40 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
543
370
|
}
|
|
544
371
|
|
|
545
372
|
const model = tierModel(activeCfg, tier) ?? undefined;
|
|
546
|
-
producerText = "";
|
|
373
|
+
let producerText = "";
|
|
547
374
|
// Provider-failover vs quality-escalation precedence (Phase 3.3):
|
|
548
375
|
// Provider-failover is advisory only — a text chain injected into the orchestrator
|
|
549
376
|
// system prompt (buildFallbackInstructions). It is orthogonal to this runtime ladder.
|
|
550
|
-
// A transport/API error here
|
|
377
|
+
// A transport/API error here becomes an explicit failed attempt and is treated as
|
|
551
378
|
// exactly ONE failed attempt by the quality-escalation ladder (no provider swap, no
|
|
552
379
|
// double-counted attempt). API error => (advisory) provider failover; verification
|
|
553
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;
|
|
554
387
|
try {
|
|
555
|
-
const res: any = await
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
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);
|
|
569
407
|
producerText = "";
|
|
570
408
|
}
|
|
571
409
|
|
|
@@ -577,20 +415,69 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
577
415
|
producerTier: tier,
|
|
578
416
|
};
|
|
579
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>();
|
|
580
424
|
let gateRes;
|
|
581
425
|
try {
|
|
582
|
-
gateRes =
|
|
583
|
-
{
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
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
|
+
}
|
|
588
471
|
gateRes = {
|
|
589
472
|
accepted: false,
|
|
590
473
|
verdict: {
|
|
591
474
|
pass: false,
|
|
592
475
|
method: "none" as const,
|
|
593
|
-
reasons: [
|
|
476
|
+
reasons: [
|
|
477
|
+
error instanceof RouterTimeoutError
|
|
478
|
+
? `verification gate timed out after ${gateBudgetMs}ms`
|
|
479
|
+
: "verification failed (fail-closed)",
|
|
480
|
+
],
|
|
594
481
|
},
|
|
595
482
|
dodSource: dod.source,
|
|
596
483
|
};
|
|
@@ -612,6 +499,25 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
612
499
|
// so a long ladder never accumulates live sessions.
|
|
613
500
|
await disposeChildSession(producerSid);
|
|
614
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
|
+
|
|
615
521
|
const costRatio =
|
|
616
522
|
typeof tiersForCost?.[tier]?.costRatio === "number"
|
|
617
523
|
? tiersForCost[tier].costRatio
|
|
@@ -701,11 +607,39 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
701
607
|
try {
|
|
702
608
|
cfg = loadConfig();
|
|
703
609
|
} catch {}
|
|
610
|
+
try {
|
|
611
|
+
sweepIdleStores();
|
|
612
|
+
} catch {
|
|
613
|
+
// best-effort maintenance: never break a real turn
|
|
614
|
+
}
|
|
704
615
|
const tierNames = Object.keys(getActiveTiers(cfg));
|
|
705
|
-
|
|
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
|
+
}
|
|
706
641
|
|
|
707
642
|
// Record-only: initialise a trajectory scorecard for tracked subagents.
|
|
708
|
-
const sid = input?.sessionID;
|
|
709
643
|
if (sid && sessionStore.isSubagent(sid)) {
|
|
710
644
|
trajectoryStore.ensure(sid, input?.agent ?? null);
|
|
711
645
|
}
|
|
@@ -723,6 +657,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
723
657
|
if (!sid || !sessionStore.isSubagent(sid) || typeof input?.tool !== "string") {
|
|
724
658
|
return;
|
|
725
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);
|
|
726
663
|
let res;
|
|
727
664
|
try {
|
|
728
665
|
res = guardBeforeCall({
|
|
@@ -841,7 +778,17 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
841
778
|
}
|
|
842
779
|
|
|
843
780
|
const res = await accept(
|
|
844
|
-
{
|
|
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
|
+
},
|
|
845
792
|
artefact,
|
|
846
793
|
buildGateDeps(),
|
|
847
794
|
);
|
|
@@ -931,8 +878,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
931
878
|
opencodeConfig.agent ??= {};
|
|
932
879
|
|
|
933
880
|
for (const [name, tier] of Object.entries(activeTiers)) {
|
|
934
|
-
// Resolve prompt: per-tier override wins; otherwise fall back to
|
|
935
|
-
|
|
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);
|
|
936
884
|
|
|
937
885
|
// For Claude-backed tiers, prepend an adversarial opener that revokes
|
|
938
886
|
// the cached "Claude Code exploratory agent" priming for this dispatch.
|
|
@@ -951,7 +899,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
951
899
|
const agentDef: Record<string, unknown> = {
|
|
952
900
|
model: tier.model,
|
|
953
901
|
mode: "subagent",
|
|
954
|
-
description: tier.description
|
|
902
|
+
description: tier.description ?? `@${name} tier (${tier.model})`,
|
|
955
903
|
maxSteps: tier.steps,
|
|
956
904
|
prompt: finalPrompt,
|
|
957
905
|
color: tier.color,
|
|
@@ -963,10 +911,16 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
963
911
|
}
|
|
964
912
|
|
|
965
913
|
// Apply provider-specific options
|
|
966
|
-
const opts = buildAgentOptions(tier);
|
|
914
|
+
const opts = buildAgentOptions(tier, name);
|
|
967
915
|
if (Object.keys(opts).length > 0) {
|
|
968
916
|
agentDef.options = opts;
|
|
969
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
|
+
}
|
|
970
924
|
|
|
971
925
|
opencodeConfig.agent[name] = agentDef;
|
|
972
926
|
}
|
|
@@ -1030,7 +984,8 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
1030
984
|
};
|
|
1031
985
|
opencodeConfig.command["router"] = {
|
|
1032
986
|
template: "$ARGUMENTS",
|
|
1033
|
-
description:
|
|
987
|
+
description:
|
|
988
|
+
"Model-router controls (e.g., /router enforce off|advisory|enforced, /router overrides)",
|
|
1034
989
|
};
|
|
1035
990
|
},
|
|
1036
991
|
|
|
@@ -1098,13 +1053,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
1098
1053
|
} else {
|
|
1099
1054
|
bypassed = !bypassed;
|
|
1100
1055
|
}
|
|
1101
|
-
const status = bypassed ? "ON" : "OFF";
|
|
1102
|
-
const desc = bypassed
|
|
1103
|
-
? "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."
|
|
1104
|
-
: "Model-router is **active**. Delegation protocol and all enforcement rules are in effect.";
|
|
1105
1056
|
output.parts.push({
|
|
1106
1057
|
type: "text" as const,
|
|
1107
|
-
text:
|
|
1058
|
+
text: buildBypassMessage(bypassed),
|
|
1108
1059
|
});
|
|
1109
1060
|
}
|
|
1110
1061
|
|