opencode-model-router 1.5.0 → 1.7.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/CHANGELOG.md +357 -0
- package/README.md +220 -19
- package/package.json +3 -2
- package/src/commands/output.ts +342 -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 +429 -347
- package/src/router/agent-options.ts +127 -0
- package/src/router/catalog.ts +457 -0
- package/src/router/config.ts +335 -48
- package/src/router/idle-sweep.ts +35 -0
- package/src/router/jsonc.ts +1 -0
- package/src/router/prompts.ts +72 -0
- package/src/router/protocol.ts +1 -1
- package/src/router/sessions.ts +299 -27
- package/src/router/subagents.ts +85 -0
- 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
|
@@ -11,6 +11,29 @@ 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
|
+
buildModelsOutput,
|
|
31
|
+
formatModelIssues,
|
|
32
|
+
} from "./commands/output";
|
|
33
|
+
import {
|
|
34
|
+
resolveSubagentOverrides,
|
|
35
|
+
mergeSubagentOverride,
|
|
36
|
+
} from "./router/subagents";
|
|
14
37
|
import { fingerprintToolCall } from "./guard/fingerprint";
|
|
15
38
|
import { detectNarration } from "./guard/narration";
|
|
16
39
|
import {
|
|
@@ -23,6 +46,13 @@ import {
|
|
|
23
46
|
assembleSystemPrompt,
|
|
24
47
|
} from "./router/protocol";
|
|
25
48
|
import { resolveEnforcementMode } from "./router/enforcement";
|
|
49
|
+
import {
|
|
50
|
+
findOrphanedStrongPatterns,
|
|
51
|
+
findStrongPatternNearMisses,
|
|
52
|
+
normalizeCatalog,
|
|
53
|
+
validateModels,
|
|
54
|
+
} from "./router/catalog";
|
|
55
|
+
import type { Catalog } from "./router/catalog";
|
|
26
56
|
import {
|
|
27
57
|
createSessionStore,
|
|
28
58
|
parseCapDirective,
|
|
@@ -33,6 +63,7 @@ import {
|
|
|
33
63
|
import type { Cap, SubagentState } from "./router/sessions";
|
|
34
64
|
import { createTrajectoryStore } from "./telemetry/trajectory";
|
|
35
65
|
import { createGuardStore } from "./guard/store";
|
|
66
|
+
import { createIdleTtlSweeper } from "./router/idle-sweep";
|
|
36
67
|
import { guardBeforeCall, guardAfterCall, formatScorecard } from "./guard/enforce";
|
|
37
68
|
import { mkdirSync, writeFileSync, existsSync } from "node:fs";
|
|
38
69
|
import { tmpdir } from "node:os";
|
|
@@ -42,7 +73,14 @@ import { access, readFile as fsReadFile } from "node:fs/promises";
|
|
|
42
73
|
import { tool } from "@opencode-ai/plugin";
|
|
43
74
|
import { scrubText } from "./guard/scrub";
|
|
44
75
|
import { accept } from "./verify/gate";
|
|
45
|
-
import {
|
|
76
|
+
import { createVerificationWiring, extractAssistantText } from "./verify/wiring";
|
|
77
|
+
import {
|
|
78
|
+
DEFAULT_DELEGATE_PROMPT_TIMEOUT_MS,
|
|
79
|
+
DEFAULT_GATE_BUDGET_MS,
|
|
80
|
+
RouterTimeoutError,
|
|
81
|
+
timeoutMs,
|
|
82
|
+
withTimeout,
|
|
83
|
+
} from "./verify/timeout";
|
|
46
84
|
import {
|
|
47
85
|
createChangedFileStore,
|
|
48
86
|
parseTaskResult,
|
|
@@ -100,223 +138,76 @@ function saveEnforcementMode(mode: "off" | "advisory" | "enforced"): void {
|
|
|
100
138
|
invalidateConfigCache();
|
|
101
139
|
}
|
|
102
140
|
|
|
141
|
+
/**
|
|
142
|
+
* `/router` dispatch. Decides and persists here; rendering lives in
|
|
143
|
+
* src/commands/output.ts.
|
|
144
|
+
*/
|
|
103
145
|
function buildRouterOutput(cfg: RouterConfig, args: string): string {
|
|
104
146
|
const tokens = (args ?? "").trim().split(/\s+/).filter(Boolean);
|
|
105
147
|
const sub = (tokens[0] ?? "").toLowerCase();
|
|
148
|
+
|
|
106
149
|
if (sub === "enforce") {
|
|
107
150
|
const mode = (tokens[1] ?? "").toLowerCase();
|
|
108
151
|
if (mode === "off" || mode === "advisory" || mode === "enforced") {
|
|
109
152
|
saveEnforcementMode(mode);
|
|
110
|
-
|
|
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");
|
|
153
|
+
return buildEnforceSet(mode);
|
|
123
154
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
"",
|
|
128
|
-
"Usage: `/router enforce <off|advisory|enforced>`",
|
|
129
|
-
].join("\n");
|
|
155
|
+
return buildEnforceStatus(
|
|
156
|
+
resolveEnforcementMode({ config: cfg, env: process.env }).mode,
|
|
157
|
+
);
|
|
130
158
|
}
|
|
159
|
+
|
|
131
160
|
if (sub === "overrides") {
|
|
132
|
-
const
|
|
161
|
+
const globalPath = overridePath();
|
|
133
162
|
const foundLocal = findProjectOverride();
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
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` : "");
|
|
163
|
+
const localPath = foundLocal ?? localOverridePath();
|
|
164
|
+
return buildOverridesOutput({
|
|
165
|
+
globalPath,
|
|
166
|
+
globalPresent: existsSync(globalPath),
|
|
167
|
+
localPath,
|
|
168
|
+
localPresent: existsSync(localPath),
|
|
169
|
+
localFound: foundLocal !== undefined,
|
|
170
|
+
activePreset: cfg.activePreset,
|
|
171
|
+
});
|
|
214
172
|
}
|
|
215
173
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
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");
|
|
174
|
+
return buildRouterHelp(
|
|
175
|
+
resolveEnforcementMode({ config: cfg, env: process.env }).mode,
|
|
176
|
+
);
|
|
224
177
|
}
|
|
225
178
|
|
|
226
|
-
|
|
227
|
-
// /budget command output
|
|
228
|
-
// ---------------------------------------------------------------------------
|
|
229
|
-
|
|
179
|
+
/** `/budget` dispatch. Persists the switch, then renders. */
|
|
230
180
|
function buildBudgetOutput(cfg: RouterConfig, args: string): string {
|
|
231
181
|
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
|
-
}
|
|
182
|
+
if (!modes || Object.keys(modes).length === 0) return buildNoModes();
|
|
235
183
|
|
|
236
184
|
const requested = args.trim().toLowerCase();
|
|
237
|
-
|
|
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
|
-
}
|
|
185
|
+
if (!requested) return buildBudgetList(cfg);
|
|
251
186
|
|
|
252
|
-
|
|
253
|
-
if (
|
|
187
|
+
const mode = modes[requested];
|
|
188
|
+
if (mode) {
|
|
254
189
|
saveActiveMode(requested);
|
|
255
|
-
|
|
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");
|
|
190
|
+
return buildBudgetSwitched(mode, requested);
|
|
267
191
|
}
|
|
268
192
|
|
|
269
|
-
return
|
|
193
|
+
return buildUnknownMode(modes, requested);
|
|
270
194
|
}
|
|
271
195
|
|
|
272
|
-
|
|
273
|
-
// /preset command output
|
|
274
|
-
// ---------------------------------------------------------------------------
|
|
275
|
-
|
|
196
|
+
/** `/preset` dispatch. Persists the switch, then renders. */
|
|
276
197
|
function buildPresetOutput(cfg: RouterConfig, args: string): string {
|
|
277
198
|
const requestedPreset = args.trim();
|
|
199
|
+
if (!requestedPreset) return buildPresetList(cfg);
|
|
278
200
|
|
|
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
201
|
const resolvedPreset = resolvePresetName(cfg, requestedPreset);
|
|
295
202
|
if (resolvedPreset) {
|
|
296
203
|
saveActivePreset(resolvedPreset);
|
|
297
204
|
cfg.activePreset = resolvedPreset;
|
|
298
|
-
|
|
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");
|
|
205
|
+
return buildPresetSwitched(cfg, resolvedPreset);
|
|
311
206
|
}
|
|
312
207
|
|
|
313
|
-
return
|
|
208
|
+
return buildUnknownPreset(cfg, requestedPreset);
|
|
314
209
|
}
|
|
315
210
|
|
|
316
|
-
// ---------------------------------------------------------------------------
|
|
317
|
-
// Plugin
|
|
318
|
-
// ---------------------------------------------------------------------------
|
|
319
|
-
|
|
320
211
|
const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
321
212
|
let cfg = loadConfig();
|
|
322
213
|
const activeTiers = getActiveTiers(cfg);
|
|
@@ -336,120 +227,27 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
336
227
|
const guardStore = createGuardStore();
|
|
337
228
|
|
|
338
229
|
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
230
|
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
231
|
+
// Idle-TTL maintenance for the four per-instance stores. No timer is
|
|
232
|
+
// scheduled: the sweeper is invoked opportunistically from chat.message and
|
|
233
|
+
// self-throttles, so a long-lived plugin instance cannot accumulate state for
|
|
234
|
+
// sessions that went away without a teardown hook.
|
|
235
|
+
const sweepIdleStores = createIdleTtlSweeper([
|
|
236
|
+
() => sessionStore.sweep(),
|
|
237
|
+
() => guardStore.sweep(),
|
|
238
|
+
() => trajectoryStore.sweep(),
|
|
239
|
+
() => changedFileStore.sweep(),
|
|
240
|
+
]);
|
|
241
|
+
|
|
242
|
+
// Layer-2's impure corner: exec, fs, and the opencode client, built once and
|
|
243
|
+
// read back through getConfig so a reloaded cfg (from /preset, /budget or
|
|
244
|
+
// /router enforce) applies to graded work too.
|
|
245
|
+
const { graderSessions, dispatchGrader, buildGateDeps, disposeChildSession } =
|
|
246
|
+
createVerificationWiring({
|
|
247
|
+
client: ctx.client,
|
|
248
|
+
directory: ctx.directory,
|
|
249
|
+
getConfig: () => cfg,
|
|
413
250
|
});
|
|
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
251
|
|
|
454
252
|
// Best-effort, secret-free delegate scorecard dump (counts only).
|
|
455
253
|
const dumpDelegateScorecard = (
|
|
@@ -473,6 +271,51 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
473
271
|
// current plugin lifetime (i.e., until OpenCode is restarted).
|
|
474
272
|
let bypassed = false;
|
|
475
273
|
|
|
274
|
+
// Fetch and normalize opencode's live provider/model catalog. Best-effort:
|
|
275
|
+
// returns null when the client call fails, e.g. the server is not ready yet.
|
|
276
|
+
// The pure analysis (validateModels) lives in src/router/catalog.ts.
|
|
277
|
+
const fetchCatalog = async (): Promise<Catalog | null> => {
|
|
278
|
+
try {
|
|
279
|
+
const res: any = await ctx.client.config.providers();
|
|
280
|
+
return normalizeCatalog(res?.data);
|
|
281
|
+
} catch {
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
// Deferred passive catalog check. The first orchestrator turn only STARTS the
|
|
287
|
+
// fetch (fire-and-forget, never awaited on the chat.message hot path) and
|
|
288
|
+
// parks the result in a local; the warning is emitted on the first LATER turn
|
|
289
|
+
// that finds the promise already settled — normally turn 2. Deliberate
|
|
290
|
+
// tradeoff: a report-only diagnostic showing up one turn late costs nothing,
|
|
291
|
+
// while awaiting a network round-trip in front of every session's first
|
|
292
|
+
// message costs every user every session. No timers (banned in src/), and the
|
|
293
|
+
// continuation writes to a local variable only — it never touches an
|
|
294
|
+
// output.parts of a message the hook has already returned.
|
|
295
|
+
//
|
|
296
|
+
// Command handlers deliberately keep their own fresh fetchCatalog() call, so a
|
|
297
|
+
// turn-1 failure (server not ready yet) is never cached into `/router models`.
|
|
298
|
+
let catalogFetchStarted = false;
|
|
299
|
+
/** undefined = not started or still in flight; null = the fetch failed. */
|
|
300
|
+
let deferredCatalog: Catalog | null | undefined;
|
|
301
|
+
// One-shot guard so the passive warnings run at most once per plugin
|
|
302
|
+
// lifetime; re-validate on demand with /router.
|
|
303
|
+
let catalogWarned = false;
|
|
304
|
+
|
|
305
|
+
const startCatalogFetch = (): void => {
|
|
306
|
+
if (catalogFetchStarted) return;
|
|
307
|
+
catalogFetchStarted = true;
|
|
308
|
+
// fetchCatalog already swallows its own errors; the .catch is belt-and-
|
|
309
|
+
// braces so this fire-and-forget promise can never reject unhandled.
|
|
310
|
+
void fetchCatalog()
|
|
311
|
+
.then((c) => {
|
|
312
|
+
deferredCatalog = c;
|
|
313
|
+
})
|
|
314
|
+
.catch(() => {
|
|
315
|
+
deferredCatalog = null;
|
|
316
|
+
});
|
|
317
|
+
};
|
|
318
|
+
|
|
476
319
|
const enableDelegateTool =
|
|
477
320
|
cfg.experimental?.verifiedDelegateTool === true ||
|
|
478
321
|
process.env.MODEL_ROUTER_VERIFIED_DELEGATE === "1";
|
|
@@ -496,12 +339,19 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
496
339
|
.describe(
|
|
497
340
|
"Optional [acceptance]...[/acceptance] block defining the Definition of Done (check: / criteria: / deliverable: directives).",
|
|
498
341
|
),
|
|
342
|
+
cwd: tool.schema
|
|
343
|
+
.string()
|
|
344
|
+
.optional()
|
|
345
|
+
.describe(
|
|
346
|
+
"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.",
|
|
347
|
+
),
|
|
499
348
|
},
|
|
500
349
|
async execute(
|
|
501
350
|
args: {
|
|
502
351
|
task: string;
|
|
503
352
|
tier?: string;
|
|
504
353
|
acceptance?: string;
|
|
354
|
+
cwd?: string;
|
|
505
355
|
},
|
|
506
356
|
toolCtx?: { sessionID?: string },
|
|
507
357
|
): Promise<string> {
|
|
@@ -540,16 +390,26 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
540
390
|
let producerText = "";
|
|
541
391
|
let forcing: string | null = null;
|
|
542
392
|
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
393
|
+
/**
|
|
394
|
+
* One turn of the escalation ladder: create a producer session, run
|
|
395
|
+
* the task on it, put the result through the acceptance gate, then
|
|
396
|
+
* tear the session down. Returns null when the backend refused to
|
|
397
|
+
* create a session, the one failure the caller cannot retry.
|
|
398
|
+
*
|
|
399
|
+
* Split out because the loop is about when to *stop* — safety net,
|
|
400
|
+
* attempt accounting, tier advancement — and a ninety-line attempt
|
|
401
|
+
* in the middle of it obscured both halves.
|
|
402
|
+
*/
|
|
403
|
+
const runProducerAttempt = async (
|
|
404
|
+
tier: string,
|
|
405
|
+
forcingNote: string | null,
|
|
406
|
+
): Promise<{
|
|
407
|
+
sessionID: string;
|
|
408
|
+
text: string;
|
|
409
|
+
gateRes: Awaited<ReturnType<typeof accept>>;
|
|
410
|
+
} | null> => {
|
|
411
|
+
const taskText = forcingNote
|
|
412
|
+
? `${scrubText(forcingNote)}\n\n${args.task}`
|
|
553
413
|
: args.task;
|
|
554
414
|
|
|
555
415
|
const created: any = await ctx.client.session.create({
|
|
@@ -558,9 +418,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
558
418
|
},
|
|
559
419
|
});
|
|
560
420
|
const producerSid: string | undefined = created?.data?.id;
|
|
561
|
-
if (!producerSid)
|
|
562
|
-
return "[router] delegate failed: could not create a producer session.";
|
|
563
|
-
}
|
|
421
|
+
if (!producerSid) return null;
|
|
564
422
|
producerSessions.push(producerSid);
|
|
565
423
|
// Compose with Layer 1: guard the plugin-created producer session.
|
|
566
424
|
try {
|
|
@@ -570,29 +428,40 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
570
428
|
}
|
|
571
429
|
|
|
572
430
|
const model = tierModel(activeCfg, tier) ?? undefined;
|
|
573
|
-
producerText = "";
|
|
431
|
+
let producerText = "";
|
|
574
432
|
// Provider-failover vs quality-escalation precedence (Phase 3.3):
|
|
575
433
|
// Provider-failover is advisory only — a text chain injected into the orchestrator
|
|
576
434
|
// system prompt (buildFallbackInstructions). It is orthogonal to this runtime ladder.
|
|
577
|
-
// A transport/API error here
|
|
435
|
+
// A transport/API error here becomes an explicit failed attempt and is treated as
|
|
578
436
|
// exactly ONE failed attempt by the quality-escalation ladder (no provider swap, no
|
|
579
437
|
// double-counted attempt). API error => (advisory) provider failover; verification
|
|
580
438
|
// FAIL => (runtime) quality escalation.
|
|
439
|
+
//
|
|
440
|
+
// The prompt is time-boxed: a model that never answers would
|
|
441
|
+
// otherwise hang the delegate forever. A timeout is folded into
|
|
442
|
+
// the same failed-attempt path as any other producer error — it
|
|
443
|
+
// is never an empty artefact that a lenient DoD could pass.
|
|
444
|
+
let producerError: string | null = null;
|
|
581
445
|
try {
|
|
582
|
-
const res: any = await
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
446
|
+
const res: any = await withTimeout(
|
|
447
|
+
ctx.client.session.prompt({
|
|
448
|
+
path: { id: producerSid },
|
|
449
|
+
body: {
|
|
450
|
+
...(model ? { model } : {}),
|
|
451
|
+
...(tier ? { agent: tier } : {}),
|
|
452
|
+
parts: [{ type: "text", text: taskText }],
|
|
453
|
+
},
|
|
454
|
+
}),
|
|
455
|
+
timeoutMs(
|
|
456
|
+
activeCfg.enforcement?.verify?.delegateTimeoutMs,
|
|
457
|
+
DEFAULT_DELEGATE_PROMPT_TIMEOUT_MS,
|
|
458
|
+
),
|
|
459
|
+
"delegate producer prompt",
|
|
460
|
+
);
|
|
461
|
+
producerText = extractAssistantText(res);
|
|
462
|
+
} catch (error) {
|
|
463
|
+
producerError =
|
|
464
|
+
error instanceof Error ? error.message : String(error);
|
|
596
465
|
producerText = "";
|
|
597
466
|
}
|
|
598
467
|
|
|
@@ -604,20 +473,69 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
604
473
|
producerTier: tier,
|
|
605
474
|
};
|
|
606
475
|
|
|
476
|
+
const gateBudgetMs = timeoutMs(
|
|
477
|
+
activeCfg.enforcement?.verify?.gateBudgetMs,
|
|
478
|
+
DEFAULT_GATE_BUDGET_MS,
|
|
479
|
+
);
|
|
480
|
+
// Grader sessions opened by THIS accept() call, and only those.
|
|
481
|
+
const gateGraderSessions = new Set<string>();
|
|
607
482
|
let gateRes;
|
|
608
483
|
try {
|
|
609
|
-
gateRes =
|
|
610
|
-
{
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
484
|
+
gateRes = producerError
|
|
485
|
+
? {
|
|
486
|
+
accepted: false,
|
|
487
|
+
verdict: {
|
|
488
|
+
pass: false,
|
|
489
|
+
method: "none" as const,
|
|
490
|
+
reasons: [`producer failed: ${producerError}`],
|
|
491
|
+
},
|
|
492
|
+
dodSource: dod.source,
|
|
493
|
+
}
|
|
494
|
+
: await withTimeout(
|
|
495
|
+
accept(
|
|
496
|
+
{
|
|
497
|
+
dod,
|
|
498
|
+
trivial: false,
|
|
499
|
+
mode: "modeA",
|
|
500
|
+
...(args.cwd ? { cwd: args.cwd } : {}),
|
|
501
|
+
},
|
|
502
|
+
artefact,
|
|
503
|
+
buildGateDeps(toolCtx?.sessionID, gateGraderSessions),
|
|
504
|
+
),
|
|
505
|
+
gateBudgetMs,
|
|
506
|
+
"verification gate",
|
|
507
|
+
);
|
|
508
|
+
} catch (error) {
|
|
509
|
+
// A gate that ran out of budget is UNMET, never accepted: the
|
|
510
|
+
// one thing worse than a slow verifier is a fast fabricated
|
|
511
|
+
// pass. Abort any grader still in flight so the ceiling is a
|
|
512
|
+
// real cancellation and not just a stopped wait.
|
|
513
|
+
//
|
|
514
|
+
// Scoped to THIS gate invocation's graders. The wiring-global
|
|
515
|
+
// graderSessions set is shared by every concurrent delegation,
|
|
516
|
+
// so aborting it here would kill a healthy grader belonging to
|
|
517
|
+
// someone else's delegation — reachable with the shipped
|
|
518
|
+
// config, where a deterministic check may run a command for up
|
|
519
|
+
// to 120s against a 90s gate budget.
|
|
520
|
+
if (error instanceof RouterTimeoutError) {
|
|
521
|
+
for (const gsid of gateGraderSessions) {
|
|
522
|
+
try {
|
|
523
|
+
await ctx.client.session.abort({ path: { id: gsid } });
|
|
524
|
+
} catch {
|
|
525
|
+
// best-effort: the gate result stands either way
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
615
529
|
gateRes = {
|
|
616
530
|
accepted: false,
|
|
617
531
|
verdict: {
|
|
618
532
|
pass: false,
|
|
619
533
|
method: "none" as const,
|
|
620
|
-
reasons: [
|
|
534
|
+
reasons: [
|
|
535
|
+
error instanceof RouterTimeoutError
|
|
536
|
+
? `verification gate timed out after ${gateBudgetMs}ms`
|
|
537
|
+
: "verification failed (fail-closed)",
|
|
538
|
+
],
|
|
621
539
|
},
|
|
622
540
|
dodSource: dod.source,
|
|
623
541
|
};
|
|
@@ -639,6 +557,25 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
639
557
|
// so a long ladder never accumulates live sessions.
|
|
640
558
|
await disposeChildSession(producerSid);
|
|
641
559
|
|
|
560
|
+
return { sessionID: producerSid, text: producerText, gateRes };
|
|
561
|
+
};
|
|
562
|
+
|
|
563
|
+
while (true) {
|
|
564
|
+
if (safety++ > safetyMax) {
|
|
565
|
+
return (
|
|
566
|
+
`[router status: unmet] delegation stopped by the safety net after ` +
|
|
567
|
+
`${state.totalAttempts} attempt(s).\n\n${scrubText(producerText)}`
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
const tier = state.currentTier;
|
|
571
|
+
const attempt = await runProducerAttempt(tier, forcing);
|
|
572
|
+
if (!attempt) {
|
|
573
|
+
return "[router] delegate failed: could not create a producer session.";
|
|
574
|
+
}
|
|
575
|
+
producerText = attempt.text;
|
|
576
|
+
const producerSid = attempt.sessionID;
|
|
577
|
+
const gateRes = attempt.gateRes;
|
|
578
|
+
|
|
642
579
|
const costRatio =
|
|
643
580
|
typeof tiersForCost?.[tier]?.costRatio === "number"
|
|
644
581
|
? tiersForCost[tier].costRatio
|
|
@@ -715,7 +652,10 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
715
652
|
"chat.params": async (input: any, output: any) => {
|
|
716
653
|
try {
|
|
717
654
|
if (input?.sessionID && graderSessions.has(input.sessionID)) {
|
|
718
|
-
|
|
655
|
+
const graderTemperature = cfg.enforcement?.verify?.graderTemperature;
|
|
656
|
+
if (graderTemperature !== undefined) {
|
|
657
|
+
output.temperature = graderTemperature;
|
|
658
|
+
}
|
|
719
659
|
}
|
|
720
660
|
} catch {
|
|
721
661
|
// best-effort: never crash a real session
|
|
@@ -728,14 +668,95 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
728
668
|
try {
|
|
729
669
|
cfg = loadConfig();
|
|
730
670
|
} catch {}
|
|
671
|
+
try {
|
|
672
|
+
sweepIdleStores();
|
|
673
|
+
} catch {
|
|
674
|
+
// best-effort maintenance: never break a real turn
|
|
675
|
+
}
|
|
731
676
|
const tierNames = Object.keys(getActiveTiers(cfg));
|
|
732
|
-
|
|
677
|
+
const sid = input?.sessionID;
|
|
678
|
+
try {
|
|
679
|
+
const registration = sessionStore.registerFromChatMessage(
|
|
680
|
+
input,
|
|
681
|
+
output,
|
|
682
|
+
cfg,
|
|
683
|
+
tierNames,
|
|
684
|
+
);
|
|
685
|
+
// A same-session same-tier re-registration is a resumed dispatch
|
|
686
|
+
// (how an opencode task_id resume reaches this hook): start a new
|
|
687
|
+
// per-dispatch guard round and count it in telemetry.
|
|
688
|
+
if (registration.resumed === true && typeof sid === "string") {
|
|
689
|
+
guardStore.beginDispatch(sid);
|
|
690
|
+
trajectoryStore.recordResume(sid, input?.agent ?? null);
|
|
691
|
+
}
|
|
692
|
+
// KNOWN RESIDUAL: a fresh registration over an EXISTING session (same
|
|
693
|
+
// sessionID, different tier) resets session cap state but leaves guard
|
|
694
|
+
// state alone, so the guard keeps counting from the old dispatch. The
|
|
695
|
+
// desync can only make the guard stricter, never laxer, and opencode
|
|
696
|
+
// assigns one agent per subagent session — so this is documented in
|
|
697
|
+
// docs/CONFIG_REFERENCE.md rather than fixed by clearing guard state,
|
|
698
|
+
// which would also drop deliverable and fingerprint history.
|
|
699
|
+
} catch {
|
|
700
|
+
// best-effort: never crash a real session during registration
|
|
701
|
+
}
|
|
733
702
|
|
|
734
703
|
// Record-only: initialise a trajectory scorecard for tracked subagents.
|
|
735
|
-
const sid = input?.sessionID;
|
|
736
704
|
if (sid && sessionStore.isSubagent(sid)) {
|
|
737
705
|
trajectoryStore.ensure(sid, input?.agent ?? null);
|
|
738
706
|
}
|
|
707
|
+
|
|
708
|
+
// Once per lifetime, warn in the plugin log when the active preset points
|
|
709
|
+
// at models opencode's catalog says are missing or deprecated, or when a
|
|
710
|
+
// strong-model pattern matches nothing the configured providers serve.
|
|
711
|
+
// This is the whole point of the catalog: both failures are otherwise
|
|
712
|
+
// silent on every subagent dispatch. Orchestrator sessions only, never
|
|
713
|
+
// throws, and deferred (see startCatalogFetch): turn 1 starts the fetch,
|
|
714
|
+
// a later turn reports what it found.
|
|
715
|
+
if (sid && !sessionStore.isSubagent(sid)) {
|
|
716
|
+
try {
|
|
717
|
+
if (!catalogFetchStarted) {
|
|
718
|
+
// Turn 1: kick the fetch off and move on. NO await here.
|
|
719
|
+
startCatalogFetch();
|
|
720
|
+
} else if (!catalogWarned && deferredCatalog !== undefined) {
|
|
721
|
+
// A later turn found the turn-1 fetch already settled: report now.
|
|
722
|
+
catalogWarned = true;
|
|
723
|
+
const catalog = deferredCatalog;
|
|
724
|
+
if (catalog) {
|
|
725
|
+
// Strong-model patterns matching nothing any configured provider
|
|
726
|
+
// serves, which can silently flip prompt-style resolution for
|
|
727
|
+
// tiers on auto. Catalog-dependent, so it rides the same deferred
|
|
728
|
+
// path — it is NOT emitted on turn 1.
|
|
729
|
+
for (const p of findOrphanedStrongPatterns(cfg, catalog)) {
|
|
730
|
+
// Naming the served id turns "something is wrong" into a fix.
|
|
731
|
+
const near = findStrongPatternNearMisses(p, catalog);
|
|
732
|
+
const hint =
|
|
733
|
+
near.length > 0
|
|
734
|
+
? ` — served under a different separator: ${near.slice(0, 3).join(", ")}`
|
|
735
|
+
: "";
|
|
736
|
+
console.warn(
|
|
737
|
+
`[model-router] strong-model pattern '${p}' matches no model your providers serve — may silently change prompt-style resolution for tiers on auto${hint}`,
|
|
738
|
+
);
|
|
739
|
+
}
|
|
740
|
+
for (const it of validateModels(cfg, catalog)) {
|
|
741
|
+
const hint =
|
|
742
|
+
it.suggestions.length > 0
|
|
743
|
+
? ` — try ${it.suggestions.join(", ")}`
|
|
744
|
+
: "";
|
|
745
|
+
// Fallback issues are keyed by the chain's provider, not a tier.
|
|
746
|
+
const where =
|
|
747
|
+
it.scope === "fallback"
|
|
748
|
+
? `${it.tier}[${it.providerId}]`
|
|
749
|
+
: `@${it.tier}`;
|
|
750
|
+
console.warn(
|
|
751
|
+
`[model-router] ${where} ${it.ref}: ${it.kind}${hint}`,
|
|
752
|
+
);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
} catch {
|
|
757
|
+
// best-effort: never disrupt a real session
|
|
758
|
+
}
|
|
759
|
+
}
|
|
739
760
|
},
|
|
740
761
|
|
|
741
762
|
// -----------------------------------------------------------------------
|
|
@@ -750,6 +771,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
750
771
|
if (!sid || !sessionStore.isSubagent(sid) || typeof input?.tool !== "string") {
|
|
751
772
|
return;
|
|
752
773
|
}
|
|
774
|
+
// Start-of-call refresh: the idle TTL must cover the tool's runtime, not
|
|
775
|
+
// just the moment it finished.
|
|
776
|
+
sessionStore.touchIfTracked(sid);
|
|
753
777
|
let res;
|
|
754
778
|
try {
|
|
755
779
|
res = guardBeforeCall({
|
|
@@ -868,7 +892,17 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
868
892
|
}
|
|
869
893
|
|
|
870
894
|
const res = await accept(
|
|
871
|
-
{
|
|
895
|
+
{
|
|
896
|
+
dod,
|
|
897
|
+
trivial,
|
|
898
|
+
mode: "modeA",
|
|
899
|
+
// The built-in task tool declares no cwd of its own, but if a
|
|
900
|
+
// caller supplies one it scopes verification the same way the
|
|
901
|
+
// delegate tool's does.
|
|
902
|
+
...(typeof input?.args?.cwd === "string" && input.args.cwd
|
|
903
|
+
? { cwd: input.args.cwd }
|
|
904
|
+
: {}),
|
|
905
|
+
},
|
|
872
906
|
artefact,
|
|
873
907
|
buildGateDeps(),
|
|
874
908
|
);
|
|
@@ -958,8 +992,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
958
992
|
opencodeConfig.agent ??= {};
|
|
959
993
|
|
|
960
994
|
for (const [name, tier] of Object.entries(activeTiers)) {
|
|
961
|
-
// Resolve prompt: per-tier override wins; otherwise fall back to
|
|
962
|
-
|
|
995
|
+
// Resolve prompt: per-tier override wins; otherwise fall back to the
|
|
996
|
+
// style-appropriate default (goal-oriented or global tierPrompts[name]).
|
|
997
|
+
const resolvedPrompt = tier.prompt ?? selectTierPrompt(name, tier, cfg);
|
|
963
998
|
|
|
964
999
|
// For Claude-backed tiers, prepend an adversarial opener that revokes
|
|
965
1000
|
// the cached "Claude Code exploratory agent" priming for this dispatch.
|
|
@@ -990,14 +1025,36 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
990
1025
|
}
|
|
991
1026
|
|
|
992
1027
|
// Apply provider-specific options
|
|
993
|
-
const opts = buildAgentOptions(tier);
|
|
1028
|
+
const opts = buildAgentOptions(tier, name);
|
|
994
1029
|
if (Object.keys(opts).length > 0) {
|
|
995
1030
|
agentDef.options = opts;
|
|
996
1031
|
}
|
|
1032
|
+
if (typeof opts.effort === "string") {
|
|
1033
|
+
warnAgentOptionsEffortOnce(
|
|
1034
|
+
"anthropic-effort-dependency",
|
|
1035
|
+
"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",
|
|
1036
|
+
);
|
|
1037
|
+
}
|
|
997
1038
|
|
|
998
1039
|
opencodeConfig.agent[name] = agentDef;
|
|
999
1040
|
}
|
|
1000
1041
|
|
|
1042
|
+
// Repoint pre-existing subagents listed in `subagentTiers` at the active
|
|
1043
|
+
// preset's models. Opt-in: with no map, nothing here runs and the agent
|
|
1044
|
+
// record is left exactly as opencode built it. Runs after tier
|
|
1045
|
+
// registration so the tier-name collision guard sees the real tiers.
|
|
1046
|
+
const subagentOverrides = resolveSubagentOverrides({
|
|
1047
|
+
subagentTiers: cfg.subagentTiers,
|
|
1048
|
+
tiers: activeTiers,
|
|
1049
|
+
existingAgents: opencodeConfig.agent,
|
|
1050
|
+
});
|
|
1051
|
+
for (const [agentName, override] of Object.entries(subagentOverrides)) {
|
|
1052
|
+
opencodeConfig.agent[agentName] = mergeSubagentOverride(
|
|
1053
|
+
opencodeConfig.agent[agentName],
|
|
1054
|
+
override,
|
|
1055
|
+
);
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1001
1058
|
// Register commands
|
|
1002
1059
|
opencodeConfig.command ??= {};
|
|
1003
1060
|
opencodeConfig.command["tiers"] = {
|
|
@@ -1058,7 +1115,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
1058
1115
|
opencodeConfig.command["router"] = {
|
|
1059
1116
|
template: "$ARGUMENTS",
|
|
1060
1117
|
description:
|
|
1061
|
-
"Model-router controls (e.g., /router enforce off|advisory|enforced, /router overrides)",
|
|
1118
|
+
"Model-router controls (e.g., /router enforce off|advisory|enforced, /router overrides, /router models)",
|
|
1062
1119
|
};
|
|
1063
1120
|
},
|
|
1064
1121
|
|
|
@@ -1126,13 +1183,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
1126
1183
|
} else {
|
|
1127
1184
|
bypassed = !bypassed;
|
|
1128
1185
|
}
|
|
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
1186
|
output.parts.push({
|
|
1134
1187
|
type: "text" as const,
|
|
1135
|
-
text:
|
|
1188
|
+
text: buildBypassMessage(bypassed),
|
|
1136
1189
|
});
|
|
1137
1190
|
}
|
|
1138
1191
|
|
|
@@ -1150,10 +1203,39 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
|
|
|
1150
1203
|
try {
|
|
1151
1204
|
cfg = loadConfig();
|
|
1152
1205
|
} catch {}
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1206
|
+
const args = (input.arguments ?? "").trim();
|
|
1207
|
+
const parts = args.split(/\s+/).filter(Boolean);
|
|
1208
|
+
const sub = (parts[0] ?? "").toLowerCase();
|
|
1209
|
+
let text: string;
|
|
1210
|
+
if (sub === "models") {
|
|
1211
|
+
const catalog = await fetchCatalog();
|
|
1212
|
+
const orphans = catalog ? findOrphanedStrongPatterns(cfg, catalog) : [];
|
|
1213
|
+
const nearMisses: Record<string, string[]> = {};
|
|
1214
|
+
if (catalog) {
|
|
1215
|
+
for (const p of orphans) {
|
|
1216
|
+
nearMisses[p] = findStrongPatternNearMisses(p, catalog);
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
text = buildModelsOutput(
|
|
1220
|
+
catalog,
|
|
1221
|
+
parts.slice(1).join(" "),
|
|
1222
|
+
orphans,
|
|
1223
|
+
nearMisses,
|
|
1224
|
+
);
|
|
1225
|
+
} else {
|
|
1226
|
+
text = buildRouterOutput(cfg, args);
|
|
1227
|
+
// On the bare status view, surface stale or missing models inline.
|
|
1228
|
+
if (sub === "") {
|
|
1229
|
+
const catalog = await fetchCatalog();
|
|
1230
|
+
if (catalog) {
|
|
1231
|
+
const issues = validateModels(cfg, catalog);
|
|
1232
|
+
if (issues.length > 0) {
|
|
1233
|
+
text += "\n\n" + formatModelIssues(issues);
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
output.parts.push({ type: "text" as const, text });
|
|
1157
1239
|
}
|
|
1158
1240
|
},
|
|
1159
1241
|
};
|