opencode-model-router 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -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`,