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.
@@ -0,0 +1,457 @@
1
+ // ---------------------------------------------------------------------------
2
+ // src/router/catalog.ts — model catalog normalization, validation, and
3
+ // suggestions. PURE module: no fs/network/SDK/process.env. The async fetch of
4
+ // opencode's live catalog (client.config.providers()) happens in index.ts; the
5
+ // raw payload is handed here for normalization and analysis.
6
+ // ---------------------------------------------------------------------------
7
+
8
+ import { DEFAULT_STRONG_MODEL_PATTERNS, type RouterConfig } from "./config";
9
+ import { getActiveTiers } from "./protocol";
10
+
11
+ export interface CatalogModel {
12
+ id: string;
13
+ /** "active" | "alpha" | "beta" | "deprecated" when known. */
14
+ status?: string;
15
+ }
16
+
17
+ export interface CatalogProvider {
18
+ id: string;
19
+ name?: string;
20
+ /** opencode's default model id for this provider, when known. */
21
+ defaultModel?: string;
22
+ models: CatalogModel[];
23
+ }
24
+
25
+ export interface Catalog {
26
+ providers: CatalogProvider[];
27
+ }
28
+
29
+ /**
30
+ * Normalize the raw `client.config.providers()` payload
31
+ * (`{ providers: Provider[], default: { [providerId]: modelId } }`) into the
32
+ * minimal shape this module needs. Defensive against missing/oddly-typed fields
33
+ * so a catalog-shape change never throws.
34
+ */
35
+ export function normalizeCatalog(raw: unknown): Catalog {
36
+ const providers: CatalogProvider[] = [];
37
+ if (raw && typeof raw === "object") {
38
+ const r = raw as Record<string, unknown>;
39
+ const defaults =
40
+ r.default && typeof r.default === "object"
41
+ ? (r.default as Record<string, unknown>)
42
+ : {};
43
+ const list = Array.isArray(r.providers) ? r.providers : [];
44
+ for (const p of list) {
45
+ if (!p || typeof p !== "object") continue;
46
+ const prov = p as Record<string, unknown>;
47
+ if (typeof prov.id !== "string") continue;
48
+ const modelsObj =
49
+ prov.models && typeof prov.models === "object"
50
+ ? (prov.models as Record<string, unknown>)
51
+ : {};
52
+ const models: CatalogModel[] = Object.entries(modelsObj).map(
53
+ ([key, m]) => {
54
+ const mm = (m && typeof m === "object" ? m : {}) as Record<
55
+ string,
56
+ unknown
57
+ >;
58
+ return {
59
+ id: typeof mm.id === "string" ? mm.id : key,
60
+ status: typeof mm.status === "string" ? mm.status : undefined,
61
+ };
62
+ },
63
+ );
64
+ const def = defaults[prov.id];
65
+ providers.push({
66
+ id: prov.id,
67
+ name: typeof prov.name === "string" ? prov.name : undefined,
68
+ defaultModel: typeof def === "string" ? def : undefined,
69
+ models,
70
+ });
71
+ }
72
+ }
73
+ return { providers };
74
+ }
75
+
76
+ /** True when the catalog carries no usable provider data (fetch failed/empty). */
77
+ export function isCatalogEmpty(catalog: Catalog): boolean {
78
+ return catalog.providers.length === 0;
79
+ }
80
+
81
+ /**
82
+ * Split a tier model reference (`"provider/model"`) into its parts. Splits on
83
+ * the FIRST slash only, so multi-segment model ids (e.g.
84
+ * `openrouter/deepseek/deepseek-v3.2`) keep their full model id.
85
+ */
86
+ export function parseModelRef(
87
+ ref: string,
88
+ ): { providerId: string; modelId: string } | undefined {
89
+ const i = ref.indexOf("/");
90
+ if (i <= 0 || i === ref.length - 1) return undefined;
91
+ return { providerId: ref.slice(0, i), modelId: ref.slice(i + 1) };
92
+ }
93
+
94
+ function findProvider(
95
+ catalog: Catalog,
96
+ providerId: string,
97
+ ): CatalogProvider | undefined {
98
+ return catalog.providers.find((p) => p.id === providerId);
99
+ }
100
+
101
+ /** Levenshtein edit distance (iterative, two-row). */
102
+ export function editDistance(a: string, b: string): number {
103
+ if (a === b) return 0;
104
+ if (a.length === 0) return b.length;
105
+ if (b.length === 0) return a.length;
106
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
107
+ let curr = new Array<number>(b.length + 1);
108
+ for (let i = 1; i <= a.length; i++) {
109
+ curr[0] = i;
110
+ for (let j = 1; j <= b.length; j++) {
111
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
112
+ curr[j] = Math.min(
113
+ prev[j]! + 1, // deletion
114
+ curr[j - 1]! + 1, // insertion
115
+ prev[j - 1]! + cost, // substitution
116
+ );
117
+ }
118
+ [prev, curr] = [curr, prev];
119
+ }
120
+ return prev[b.length]!;
121
+ }
122
+
123
+ /**
124
+ * Rank a provider's model ids by closeness to `target`, preferring non-deprecated
125
+ * models. Returns up to `limit` model ids.
126
+ */
127
+ export function suggestModels(
128
+ target: string,
129
+ models: CatalogModel[],
130
+ limit = 3,
131
+ ): string[] {
132
+ return models
133
+ .map((m) => ({
134
+ id: m.id,
135
+ deprecated: m.status === "deprecated" ? 1 : 0,
136
+ dist: editDistance(target, m.id),
137
+ }))
138
+ .sort((a, b) => a.deprecated - b.deprecated || a.dist - b.dist || a.id.localeCompare(b.id))
139
+ .slice(0, limit)
140
+ .map((m) => m.id);
141
+ }
142
+
143
+ /**
144
+ * Strong-model patterns (`cfg.modelGenerations.strong`, else
145
+ * {@link DEFAULT_STRONG_MODEL_PATTERNS}) that match NO model in the live
146
+ * catalog. Report-only: the router never rewrites the user's pattern list.
147
+ *
148
+ * Why this exists: prompt-style resolution is a case-insensitive substring match
149
+ * (`isStrongModel` in ./prompts). When a provider renames a model
150
+ * (`claude-opus-4-8` -> `opus-4.8`), every pattern that used to match silently
151
+ * stops matching, the tier drops back to the prescriptive prompt, and nothing
152
+ * anywhere errors. This surfaces that silence.
153
+ *
154
+ * Comparison base: the CATALOG, not the active preset. The default pattern list
155
+ * is a cross-preset union by construction (see DEFAULT_STRONG_MODEL_PATTERNS in
156
+ * ./config), so any single preset leaves most of it unmatched — checking against
157
+ * the active preset would warn on every clean install. A pattern matching no
158
+ * model any configured provider serves is dead in THIS environment, which is
159
+ * exactly the rename signal we want. Refs are compared as `provider/model`,
160
+ * mirroring `isStrongModel`, which is fed the full provider-prefixed tier model.
161
+ *
162
+ * Never cries wolf: an empty catalog (fetch failed) or a catalog with no models
163
+ * returns `[]`, like `validateModels`.
164
+ *
165
+ * Gate: reported only when at least one active tier resolves its style by `auto`
166
+ * (`promptStyle` absent or `"auto"`). With every tier pinned to an explicit
167
+ * style the pattern list decides nothing, so an orphan there is harmless noise.
168
+ */
169
+ export function findOrphanedStrongPatterns(
170
+ cfg: RouterConfig,
171
+ catalog: Catalog,
172
+ ): string[] {
173
+ if (isCatalogEmpty(catalog)) return [];
174
+
175
+ const tiers = Object.values(getActiveTiers(cfg) ?? {});
176
+ const usesAuto = tiers.some(
177
+ (t) => t?.promptStyle === undefined || t.promptStyle === "auto",
178
+ );
179
+ if (!usesAuto) return [];
180
+
181
+ const refs: string[] = [];
182
+ for (const p of catalog.providers) {
183
+ for (const m of p.models) refs.push(`${p.id}/${m.id}`.toLowerCase());
184
+ }
185
+ if (refs.length === 0) return [];
186
+
187
+ const configured = cfg.modelGenerations?.strong;
188
+ const raw = configured ?? DEFAULT_STRONG_MODEL_PATTERNS;
189
+ const patterns = raw.filter(
190
+ (p): p is string => typeof p === "string" && p.length > 0,
191
+ );
192
+ // Same semantics as isStrongModel(): case-insensitive substring match.
193
+ const orphans = patterns.filter(
194
+ (p) => !refs.some((r) => r.includes(p.toLowerCase())),
195
+ );
196
+
197
+ // Evidence gate for the defaults. A user-authored list is a claim about THIS
198
+ // environment, so a dead entry in it is actionable on its own. The default
199
+ // list is not a claim about anything — it is a cross-provider union we ship,
200
+ // so most of it is unserved on any given install and saying so is noise the
201
+ // user cannot act on. A default pattern is only worth reporting when a
202
+ // near-miss proves the model is there under a drifted separator
203
+ // (`opus-4-8` vs `opus-4.8`), which is the rename this check exists to catch.
204
+ const reportable =
205
+ configured === undefined
206
+ ? orphans.filter((p) => findStrongPatternNearMisses(p, catalog).length > 0)
207
+ : orphans;
208
+ return [...new Set(reportable)];
209
+ }
210
+
211
+ /**
212
+ * For an orphaned pattern, the served refs it would match if separators were
213
+ * ignored.
214
+ *
215
+ * `findOrphanedStrongPatterns` says a pattern is dead; this says why. The
216
+ * failure this exists for is separator drift, not a wrong name: `anthropic`
217
+ * ships `claude-opus-4-8` while the copilot preset uses `claude-opus-4.6`, so a
218
+ * provider moving between the two un-matches a pattern that is otherwise still
219
+ * describing the right model. Normalizing `.`, `-` and `_` away turns "this
220
+ * matches nothing" into "this matches nothing, but here is the model it almost
221
+ * certainly means", which is the difference between a warning and a fix.
222
+ *
223
+ * Returns empty when nothing plausibly matches, i.e. the pattern is simply
224
+ * wrong or the model is genuinely gone.
225
+ */
226
+ export function findStrongPatternNearMisses(
227
+ pattern: string,
228
+ catalog: Catalog,
229
+ ): string[] {
230
+ const flatten = (v: string) => v.toLowerCase().replace(/[.\-_]/g, "");
231
+ const needle = flatten(pattern);
232
+ if (!needle) return [];
233
+
234
+ const refs: string[] = [];
235
+ for (const p of catalog.providers) {
236
+ for (const m of p.models) refs.push(`${p.id}/${m.id}`);
237
+ }
238
+ return refs.filter((r) => flatten(r).includes(needle));
239
+ }
240
+
241
+ export type ModelIssueKind =
242
+ | "provider-unknown"
243
+ | "model-missing"
244
+ | "model-deprecated"
245
+ | "fallback-provider-unknown"
246
+ | "fallback-preset-unknown";
247
+
248
+ export interface ModelIssue {
249
+ /** Tier name for `scope: "tier"`; the fallback map key for `scope: "fallback"`. */
250
+ tier: string;
251
+ /** Where the reference came from: an active-preset tier, or a fallback chain. */
252
+ scope: "tier" | "fallback";
253
+ /** Full `provider/model` reference for tier issues; the offending chain entry for fallback issues. */
254
+ ref: string;
255
+ providerId: string;
256
+ modelId: string;
257
+ kind: ModelIssueKind;
258
+ /** Preset a fallback chain entry points at (`fallback-preset-unknown` only). */
259
+ chainTarget?: string;
260
+ /** Suggested replacements, closest first: `provider/model` refs for tier issues, preset names for fallback ones. */
261
+ suggestions: string[];
262
+ }
263
+
264
+ /**
265
+ * The fallback map that actually applies to the active preset, using the same
266
+ * precedence as `buildFallbackInstructions` in ./protocol: a non-empty
267
+ * preset-specific map wins over `fallback.global`.
268
+ */
269
+ function activeFallbackMap(
270
+ cfg: RouterConfig,
271
+ ): { source: string; map: Record<string, unknown> } | undefined {
272
+ const fb = cfg.fallback;
273
+ if (!fb) return undefined;
274
+ const presetMap = fb.presets?.[cfg.activePreset];
275
+ if (presetMap && typeof presetMap === "object" && Object.keys(presetMap).length > 0) {
276
+ return { source: `presets.${cfg.activePreset}`, map: presetMap as Record<string, unknown> };
277
+ }
278
+ if (fb.global && typeof fb.global === "object" && Object.keys(fb.global).length > 0) {
279
+ return { source: "global", map: fb.global as Record<string, unknown> };
280
+ }
281
+ return undefined;
282
+ }
283
+
284
+ /**
285
+ * Validate the fallback chains that apply to the active preset. Report-only.
286
+ *
287
+ * NOTE ON SHAPE: a fallback chain is `providerId -> [presetName, ...]` (see
288
+ * FallbackConfig in ./config and `buildFallbackInstructions` in ./protocol) —
289
+ * it holds provider ids and PRESET names, not `provider/model` refs. So the two
290
+ * things that can silently rot are:
291
+ * - a chain keyed by a provider opencode does not know about (catalog check:
292
+ * the chain can never fire), and
293
+ * - a chain entry naming a preset that does not exist, which ./protocol drops
294
+ * from the rendered chain without a word (config check, no catalog needed).
295
+ *
296
+ * Dedupe: a provider already reported unknown from a tier model is not reported
297
+ * a second time from a fallback key — `knownBadProviders` carries those ids.
298
+ */
299
+ function validateFallbackChains(
300
+ cfg: RouterConfig,
301
+ catalog: Catalog,
302
+ knownBadProviders: Set<string>,
303
+ ): ModelIssue[] {
304
+ const active = activeFallbackMap(cfg);
305
+ if (!active) return [];
306
+
307
+ const issues: ModelIssue[] = [];
308
+ const presetNames = Object.keys(cfg.presets ?? {});
309
+ const label = `fallback.${active.source}`;
310
+
311
+ // Providers the active preset actually routes to. The shipped tiers.json
312
+ // chains every provider to every other one, so on a single-provider install
313
+ // most chains are dormant BY DESIGN — warning that a provider you never use
314
+ // is unconfigured is noise. A chain only matters once a tier can fail over
315
+ // from it.
316
+ const usedProviders = new Set<string>();
317
+ for (const tierCfg of Object.values(getActiveTiers(cfg) ?? {})) {
318
+ const ref = tierCfg?.model;
319
+ if (typeof ref !== "string") continue;
320
+ const parsed = parseModelRef(ref);
321
+ if (parsed) usedProviders.add(parsed.providerId);
322
+ }
323
+
324
+ for (const [providerId, chain] of Object.entries(active.map)) {
325
+ if (!providerId) continue;
326
+ // ./protocol ignores a non-array chain wholesale, so there is nothing left
327
+ // to warn about for this key — skip it the same way rather than reporting
328
+ // an unknown provider for a chain that could never fire anyway.
329
+ if (!Array.isArray(chain)) continue;
330
+
331
+ if (
332
+ !isCatalogEmpty(catalog) &&
333
+ usedProviders.has(providerId) &&
334
+ !findProvider(catalog, providerId) &&
335
+ !knownBadProviders.has(providerId)
336
+ ) {
337
+ knownBadProviders.add(providerId);
338
+ issues.push({
339
+ tier: label,
340
+ scope: "fallback",
341
+ ref: providerId,
342
+ providerId,
343
+ modelId: "",
344
+ kind: "fallback-provider-unknown",
345
+ suggestions: [],
346
+ });
347
+ }
348
+
349
+ for (const target of chain) {
350
+ if (typeof target !== "string" || target.length === 0) continue;
351
+ // ./protocol also drops a self-reference to the active preset, but that
352
+ // is a no-op by design rather than a typo, so it is not reported.
353
+ if (target === cfg.activePreset) continue;
354
+ // Truthiness, for parity with ./protocol's `Boolean(cfg.presets[p])`.
355
+ if (cfg.presets?.[target]) continue;
356
+ issues.push({
357
+ tier: label,
358
+ scope: "fallback",
359
+ ref: `${providerId} → ${target}`,
360
+ providerId,
361
+ modelId: "",
362
+ kind: "fallback-preset-unknown",
363
+ chainTarget: target,
364
+ suggestions: presetNames
365
+ .map((n) => ({ n, d: editDistance(target, n) }))
366
+ .sort((a, b) => a.d - b.d || a.n.localeCompare(b.n))
367
+ .slice(0, 3)
368
+ .map((x) => x.n),
369
+ });
370
+ }
371
+ }
372
+
373
+ return issues;
374
+ }
375
+
376
+ /**
377
+ * Validate the active preset's tier models — and the fallback chains that apply
378
+ * to it — against the live catalog. Catalog-dependent checks are skipped when
379
+ * the catalog is empty (fetch failed): we never cry wolf about missing models
380
+ * when we couldn't see the catalog at all. The fallback preset-name check is
381
+ * pure config analysis, so it still runs in that case.
382
+ */
383
+ export function validateModels(cfg: RouterConfig, catalog: Catalog): ModelIssue[] {
384
+ const issues: ModelIssue[] = [];
385
+ const badProviders = new Set<string>();
386
+ if (!isCatalogEmpty(catalog)) {
387
+ issues.push(...validateTierModels(cfg, catalog, badProviders));
388
+ }
389
+ issues.push(...validateFallbackChains(cfg, catalog, badProviders));
390
+ return issues;
391
+ }
392
+
393
+ function validateTierModels(
394
+ cfg: RouterConfig,
395
+ catalog: Catalog,
396
+ badProviders: Set<string>,
397
+ ): ModelIssue[] {
398
+ const issues: ModelIssue[] = [];
399
+ const preset = getActiveTiers(cfg);
400
+
401
+ for (const [tier, tierCfg] of Object.entries(preset)) {
402
+ const ref = tierCfg?.model;
403
+ if (typeof ref !== "string") continue;
404
+ const parsed = parseModelRef(ref);
405
+ if (!parsed) continue;
406
+
407
+ const provider = findProvider(catalog, parsed.providerId);
408
+ if (!provider) {
409
+ badProviders.add(parsed.providerId);
410
+ issues.push({
411
+ tier,
412
+ scope: "tier",
413
+ ref,
414
+ providerId: parsed.providerId,
415
+ modelId: parsed.modelId,
416
+ kind: "provider-unknown",
417
+ suggestions: [],
418
+ });
419
+ continue;
420
+ }
421
+
422
+ const model = provider.models.find((m) => m.id === parsed.modelId);
423
+ if (!model) {
424
+ issues.push({
425
+ tier,
426
+ ref,
427
+ providerId: parsed.providerId,
428
+ modelId: parsed.modelId,
429
+ kind: "model-missing",
430
+ scope: "tier",
431
+ suggestions: suggestModels(parsed.modelId, provider.models).map(
432
+ (id) => `${parsed.providerId}/${id}`,
433
+ ),
434
+ });
435
+ continue;
436
+ }
437
+
438
+ if (model.status === "deprecated") {
439
+ const alternatives = provider.models.filter(
440
+ (m) => m.status !== "deprecated",
441
+ );
442
+ issues.push({
443
+ tier,
444
+ ref,
445
+ providerId: parsed.providerId,
446
+ modelId: parsed.modelId,
447
+ kind: "model-deprecated",
448
+ scope: "tier",
449
+ suggestions: suggestModels(parsed.modelId, alternatives).map(
450
+ (id) => `${parsed.providerId}/${id}`,
451
+ ),
452
+ });
453
+ }
454
+ }
455
+
456
+ return issues;
457
+ }
@@ -1,4 +1,11 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
1
+ import {
2
+ existsSync,
3
+ mkdirSync,
4
+ readFileSync,
5
+ realpathSync,
6
+ renameSync,
7
+ writeFileSync,
8
+ } from "node:fs";
2
9
  import { homedir } from "node:os";
3
10
  import { dirname, join } from "node:path";
4
11
  import { fileURLToPath } from "node:url";
@@ -145,6 +152,18 @@ export interface RouterConfig {
145
152
  * "Now I'll add X" phrasing.
146
153
  */
147
154
  antiNarration?: boolean;
155
+ /**
156
+ * Opt-in map of pre-existing agent name → tier name, e.g.
157
+ * `{ "ContextScout": "fast" }`. Listed agents are repointed at the active
158
+ * preset's model for that tier, so they follow `/preset` instead of pinning
159
+ * a model id in their own definition. Absent or empty ⇒ feature is off and
160
+ * no agent is touched.
161
+ *
162
+ * Keys are opencode agent names — the frontmatter `name:` field when a
163
+ * markdown agent declares one, otherwise its path-derived name. List only
164
+ * subagents; a primary agent is the orchestrator.
165
+ */
166
+ subagentTiers?: Record<string, string>;
148
167
  /** Experimental, opt-in features. Off by default. */
149
168
  experimental?: { verifiedDelegateTool?: boolean };
150
169
  }
@@ -237,8 +256,22 @@ const MAX_WALK_DEPTH = 16;
237
256
  * Returns the resolved path, or undefined when no file applies.
238
257
  */
239
258
  export function findProjectOverride(): string | undefined {
240
- let dir = process.cwd();
241
- const home = homedir();
259
+ // Both sides of the $HOME comparison below have to be resolved the same way.
260
+ // process.cwd() returns a realpath, while homedir() returns $HOME verbatim, so
261
+ // on any system where $HOME contains a symlinked component (macOS temp dirs,
262
+ // containers, some NFS homes) a raw string compare never matches and the home
263
+ // boundary silently stops applying. Fail soft: an unresolvable path is used
264
+ // as-is, which is no worse than not comparing at all.
265
+ const resolve = (p: string): string => {
266
+ try {
267
+ return realpathSync(p);
268
+ } catch {
269
+ return p;
270
+ }
271
+ };
272
+
273
+ let dir = resolve(process.cwd());
274
+ const home = resolve(homedir());
242
275
  let depth = 0;
243
276
 
244
277
  for (;;) {
@@ -499,6 +532,23 @@ function validateModelGenerations(obj: Record<string, unknown>): void {
499
532
  }
500
533
  }
501
534
 
535
+ function validateSubagentTiers(obj: Record<string, unknown>): void {
536
+ if (obj.subagentTiers === undefined) return;
537
+ if (!isPlainObject(obj.subagentTiers)) {
538
+ throw new Error("tiers.json: 'subagentTiers' must be an object");
539
+ }
540
+ for (const [agentName, tierName] of Object.entries(obj.subagentTiers)) {
541
+ if (typeof tierName !== "string" || tierName === "") {
542
+ throw new Error(
543
+ `tiers.json: subagentTiers.'${agentName}' must be a non-empty tier name`,
544
+ );
545
+ }
546
+ }
547
+ // Deliberately not checking that the tier exists: a map may name a tier that
548
+ // only some presets define, and switching preset must never brick startup.
549
+ // Unknown tiers are skipped at resolve time (see resolveSubagentOverrides).
550
+ }
551
+
502
552
  function validateTaskPatterns(obj: Record<string, unknown>): void {
503
553
  // Validate taskPatterns if present
504
554
  if (obj.taskPatterns !== undefined) {
@@ -691,12 +741,14 @@ function validateEnforcement(obj: Record<string, unknown>): void {
691
741
  !Number.isFinite(guard.budget) ||
692
742
  guard.budget < 1
693
743
  ) {
694
- throw new Error("enforcement.guard.budget must be a number >= 1");
744
+ throw new Error("tiers.json: enforcement.guard.budget must be a number >= 1");
695
745
  }
696
746
  }
697
747
  if (guard.blockScriptWrites !== undefined) {
698
748
  if (typeof guard.blockScriptWrites !== "boolean") {
699
- throw new Error("enforcement.guard.blockScriptWrites must be a boolean");
749
+ throw new Error(
750
+ "tiers.json: enforcement.guard.blockScriptWrites must be a boolean",
751
+ );
700
752
  }
701
753
  }
702
754
  for (const key of ["readDraftCap", "sameOpRetryCap"] as const) {
@@ -767,6 +819,7 @@ export function validateConfig(raw: unknown): RouterConfig {
767
819
  validateTierPromptsGoalOriented(obj);
768
820
  validateModelGenerations(obj);
769
821
  validateTaskPatterns(obj);
822
+ validateSubagentTiers(obj);
770
823
  validateEnforcement(obj);
771
824
 
772
825
  return raw as RouterConfig;