opencode-model-router 1.6.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.
@@ -11,32 +11,10 @@
11
11
  * what happened — which made the output impossible to test without a state
12
12
  * file on disk and a plugin instance to hang it off.
13
13
  */
14
- import type { RouterConfig, TierConfig, ModeConfig } from "../router/config";
14
+ import type { RouterConfig, ModeConfig } from "../router/config";
15
15
  import { getActiveTiers } from "../router/protocol";
16
-
17
- /** Provider-specific agent options (thinking / reasoning) for a tier. */
18
- export function buildAgentOptions(tier: TierConfig): Record<string, unknown> {
19
- const opts: Record<string, unknown> = {};
20
-
21
- // Anthropic thinking config
22
- if (tier.thinking) {
23
- if (tier.thinking.budgetTokens) {
24
- opts.budget_tokens = tier.thinking.budgetTokens;
25
- }
26
- }
27
-
28
- // OpenAI reasoning config
29
- if (tier.reasoning) {
30
- if (tier.reasoning.effort) {
31
- opts.reasoning_effort = tier.reasoning.effort;
32
- }
33
- if (tier.reasoning.summary) {
34
- opts.reasoning_summary = tier.reasoning.summary;
35
- }
36
- }
37
-
38
- return Object.keys(opts).length > 0 ? opts : {};
39
- }
16
+ import { resolvePromptStyle } from "../router/prompts";
17
+ import type { Catalog, ModelIssue } from "../router/catalog";
40
18
 
41
19
  /** `/tiers` */
42
20
  export function buildTiersOutput(cfg: RouterConfig): string {
@@ -52,7 +30,17 @@ export function buildTiersOutput(cfg: RouterConfig): string {
52
30
  : tier.reasoning
53
31
  ? ` | reasoning: effort=${tier.reasoning.effort}`
54
32
  : "";
55
- lines.push(`## @${name} -> \`${tier.model}\`${thinkingStr}`);
33
+ // The auto rule flips strong models to goal-oriented silently, so show the
34
+ // style the dispatch actually resolves to. An explicit `tier.prompt` wins
35
+ // outright (src/index.ts: `tier.prompt ?? selectTierPrompt(...)`).
36
+ const explicitStyle =
37
+ tier.promptStyle === "prescriptive" || tier.promptStyle === "goal-oriented";
38
+ const promptStr = tier.prompt
39
+ ? " | prompt: custom"
40
+ : ` | prompt: ${resolvePromptStyle(tier.promptStyle, tier.model, cfg)} (${
41
+ explicitStyle ? "explicit" : "auto"
42
+ })`;
43
+ lines.push(`## @${name} -> \`${tier.model}\`${thinkingStr}${promptStr}`);
56
44
  if (tier.description) lines.push(tier.description);
57
45
  lines.push(`Steps: ${tier.steps ?? "default"}`);
58
46
  const whenToUse = tier.whenToUse ?? [];
@@ -231,6 +219,124 @@ export function buildRouterHelp(current: string): string {
231
219
  "Commands:",
232
220
  "- `/router enforce <off|advisory|enforced>` — set hard-block enforcement (persisted)",
233
221
  "- `/router overrides` — show the global + project override file paths and precedence",
222
+ "- `/router models [provider]` — list valid model ids from your configured providers",
234
223
  "- `/tiers`, `/preset`, `/budget`, `/bypass`, `/annotate-plan`",
235
224
  ].join("\n");
236
225
  }
226
+
227
+ /**
228
+ * `/router models [provider]`. Takes the catalog the caller fetched, so a
229
+ * failed or unavailable fetch is a null here rather than an exception path.
230
+ */
231
+ export function buildModelsOutput(
232
+ catalog: Catalog | null,
233
+ filter: string,
234
+ orphanedStrongPatterns: string[] = [],
235
+ strongPatternNearMisses: Record<string, string[]> = {},
236
+ ): string {
237
+ // Orphan patterns are pure config analysis, so they are appended to EVERY
238
+ // return path — including the catalog-unavailable ones, where the warning is
239
+ // just as valid.
240
+ const suffix =
241
+ orphanedStrongPatterns.length > 0
242
+ ? "\n\n" +
243
+ formatOrphanedStrongPatterns(orphanedStrongPatterns, strongPatternNearMisses)
244
+ : "";
245
+ if (!catalog) {
246
+ return (
247
+ "Model catalog unavailable — could not query opencode's providers." + suffix
248
+ );
249
+ }
250
+ if (catalog.providers.length === 0) {
251
+ return "No providers are configured/authenticated in opencode." + suffix;
252
+ }
253
+ const f = filter.trim().toLowerCase();
254
+ const providers = f
255
+ ? catalog.providers.filter((p) => p.id.toLowerCase() === f)
256
+ : catalog.providers;
257
+ if (providers.length === 0) {
258
+ return (
259
+ `No configured provider matches \`${filter.trim()}\`. Available: ${catalog.providers
260
+ .map((p) => p.id)
261
+ .join(", ")}.` + suffix
262
+ );
263
+ }
264
+
265
+ const lines: string[] = ["# Model Router — available models", ""];
266
+ for (const p of providers) {
267
+ const name = p.name && p.name !== p.id ? ` (${p.name})` : "";
268
+ const def = p.defaultModel ? ` — default: \`${p.id}/${p.defaultModel}\`` : "";
269
+ lines.push(`## ${p.id}${name}${def}`);
270
+ const sorted = [...p.models].sort((a, b) => a.id.localeCompare(b.id));
271
+ if (sorted.length === 0) {
272
+ lines.push("- _(no models)_");
273
+ } else {
274
+ for (const m of sorted) {
275
+ const flag = m.status && m.status !== "active" ? ` _(${m.status})_` : "";
276
+ lines.push(`- \`${p.id}/${m.id}\`${flag}`);
277
+ }
278
+ }
279
+ lines.push("");
280
+ }
281
+ lines.push(
282
+ "Paste any id above into an overrides file (`/router overrides` shows where).",
283
+ );
284
+ return lines.join("\n") + suffix;
285
+ }
286
+
287
+ /**
288
+ * Render strong-model patterns that match no model in the active preset (see
289
+ * `findOrphanedStrongPatterns`). Report-only — the router never edits the
290
+ * user's pattern list.
291
+ */
292
+ export function formatOrphanedStrongPatterns(
293
+ patterns: string[],
294
+ nearMisses: Record<string, string[]> = {},
295
+ ): string {
296
+ return [
297
+ "⚠ **Strong-model patterns matching no model your providers serve:**",
298
+ ...patterns.map((p) => {
299
+ const near = nearMisses[p] ?? [];
300
+ if (near.length === 0) return `- \`${p}\``;
301
+ // Named separately from the generic rename hint below: when we can point
302
+ // at the served id, the user can fix it without going to look.
303
+ return `- \`${p}\` — served under a different separator: ${near
304
+ .slice(0, 3)
305
+ .map((r) => `\`${r}\``)
306
+ .join(", ")}`;
307
+ }),
308
+ "",
309
+ "This may silently change prompt-style resolution for tiers on `promptStyle: auto`. If a provider renamed a model, update `modelGenerations.strong` in your overrides file (`/router overrides`).",
310
+ ].join("\n");
311
+ }
312
+
313
+ /** Render model-validation issues for the active preset as a markdown block. */
314
+ export function formatModelIssues(issues: ModelIssue[]): string {
315
+ const lines: string[] = ["⚠ **Model issues in the active preset:**"];
316
+ for (const it of issues) {
317
+ const what =
318
+ it.kind === "provider-unknown" || it.kind === "fallback-provider-unknown"
319
+ ? `provider \`${it.providerId}\` is not configured/authenticated` +
320
+ (it.kind === "fallback-provider-unknown"
321
+ ? " — this fallback chain can never fire"
322
+ : "")
323
+ : it.kind === "fallback-preset-unknown"
324
+ ? `chain entry \`${it.chainTarget}\` is not a defined preset and is silently dropped`
325
+ : it.kind === "model-deprecated"
326
+ ? `\`${it.ref}\` is **deprecated**`
327
+ : `\`${it.ref}\` was not found`;
328
+ // Fallback issues are keyed by the chain's provider, not by a tier.
329
+ const where =
330
+ it.scope === "fallback" ? `${it.tier}[${it.providerId}]` : `@${it.tier}`;
331
+ let line = `- ${where}: ${what}.`;
332
+ if (it.suggestions.length > 0) {
333
+ line += ` Try: ${it.suggestions.map((s) => `\`${s}\``).join(", ")}.`;
334
+ }
335
+ lines.push(line);
336
+ }
337
+ lines.push(
338
+ "",
339
+ "Set a replacement in your overrides file (`/router overrides`), then re-run `/router`.",
340
+ );
341
+ return lines.join("\n");
342
+ }
package/src/index.ts CHANGED
@@ -27,7 +27,13 @@ import {
27
27
  buildEnforceStatus,
28
28
  buildOverridesOutput,
29
29
  buildRouterHelp,
30
+ buildModelsOutput,
31
+ formatModelIssues,
30
32
  } from "./commands/output";
33
+ import {
34
+ resolveSubagentOverrides,
35
+ mergeSubagentOverride,
36
+ } from "./router/subagents";
31
37
  import { fingerprintToolCall } from "./guard/fingerprint";
32
38
  import { detectNarration } from "./guard/narration";
33
39
  import {
@@ -40,6 +46,13 @@ import {
40
46
  assembleSystemPrompt,
41
47
  } from "./router/protocol";
42
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";
43
56
  import {
44
57
  createSessionStore,
45
58
  parseCapDirective,
@@ -258,6 +271,51 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
258
271
  // current plugin lifetime (i.e., until OpenCode is restarted).
259
272
  let bypassed = false;
260
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
+
261
319
  const enableDelegateTool =
262
320
  cfg.experimental?.verifiedDelegateTool === true ||
263
321
  process.env.MODEL_ROUTER_VERIFIED_DELEGATE === "1";
@@ -594,7 +652,10 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
594
652
  "chat.params": async (input: any, output: any) => {
595
653
  try {
596
654
  if (input?.sessionID && graderSessions.has(input.sessionID)) {
597
- output.temperature = cfg.enforcement?.verify?.graderTemperature ?? 0;
655
+ const graderTemperature = cfg.enforcement?.verify?.graderTemperature;
656
+ if (graderTemperature !== undefined) {
657
+ output.temperature = graderTemperature;
658
+ }
598
659
  }
599
660
  } catch {
600
661
  // best-effort: never crash a real session
@@ -643,6 +704,59 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
643
704
  if (sid && sessionStore.isSubagent(sid)) {
644
705
  trajectoryStore.ensure(sid, input?.agent ?? null);
645
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
+ }
646
760
  },
647
761
 
648
762
  // -----------------------------------------------------------------------
@@ -925,6 +1039,22 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
925
1039
  opencodeConfig.agent[name] = agentDef;
926
1040
  }
927
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
+
928
1058
  // Register commands
929
1059
  opencodeConfig.command ??= {};
930
1060
  opencodeConfig.command["tiers"] = {
@@ -985,7 +1115,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
985
1115
  opencodeConfig.command["router"] = {
986
1116
  template: "$ARGUMENTS",
987
1117
  description:
988
- "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)",
989
1119
  };
990
1120
  },
991
1121
 
@@ -1073,10 +1203,39 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1073
1203
  try {
1074
1204
  cfg = loadConfig();
1075
1205
  } catch {}
1076
- output.parts.push({
1077
- type: "text" as const,
1078
- text: buildRouterOutput(cfg, input.arguments ?? ""),
1079
- });
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 });
1080
1239
  }
1081
1240
  },
1082
1241
  };
@@ -47,19 +47,28 @@ function isOpenAIModel(model: string): boolean {
47
47
  /**
48
48
  * Provider-specific agent options for a tier, as registered with opencode.
49
49
  *
50
- * Precedence, highest first: explicit `thinking` (Anthropic) or explicit
51
- * `reasoning.effort` (OpenAI), then the provider-agnostic `effort`. A key is
50
+ * Precedence, highest first: explicit `thinking` with a truthy `budgetTokens`
51
+ * (Anthropic) or explicit `reasoning.effort` (OpenAI), then the
52
+ * provider-agnostic `effort`. A `budgetTokens` of 0 asks for nothing and so
53
+ * loses to `effort`, with a one-time notice per tier. A key is
52
54
  * only ever present when something asked for it — an unset `effort` leaves no
53
55
  * trace in the returned object.
54
56
  */
55
57
  export function buildAgentOptions(tier: TierConfig, tierName = tier.model): Record<string, unknown> {
56
58
  const opts: Record<string, unknown> = {};
57
59
 
58
- // Anthropic thinking config
59
- if (tier.thinking?.budgetTokens != null) {
60
- if (tier.thinking.budgetTokens) {
61
- opts.budget_tokens = tier.thinking.budgetTokens;
62
- }
60
+ // Anthropic thinking config. A zero budget asks for no extended thinking at
61
+ // all, so it is neither emitted nor treated as an explicit thinking config
62
+ // below — `hasThinkingBudget` is the single notion of "thinking was asked
63
+ // for", shared by the emission and the effort precedence check.
64
+ const hasThinkingBudget = Boolean(tier.thinking?.budgetTokens);
65
+ if (hasThinkingBudget) {
66
+ opts.budget_tokens = tier.thinking?.budgetTokens;
67
+ } else if (tier.thinking?.budgetTokens === 0) {
68
+ warnAgentOptionsEffortOnce(
69
+ `thinking-zero:${tierName}`,
70
+ `tier ${tierName}: thinking.budgetTokens: 0 is ignored`,
71
+ );
63
72
  }
64
73
 
65
74
  // OpenAI reasoning config
@@ -83,7 +92,7 @@ export function buildAgentOptions(tier: TierConfig, tierName = tier.model): Reco
83
92
  `tier ${tierName}: invalid effort '${String(effort)}' ignored`,
84
93
  );
85
94
  } else if (isClaudeModel(tier.model)) {
86
- if (tier.thinking?.budgetTokens != null) {
95
+ if (hasThinkingBudget) {
87
96
  warnAgentOptionsEffortOnce(
88
97
  `anthropic-conflict:${tierName}`,
89
98
  `tier ${tierName}: both thinking and effort set; explicit thinking wins`,