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
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Registration-path agent options.
|
|
3
|
+
*
|
|
4
|
+
* `src/index.ts` turns each tier of the active preset into an opencode agent
|
|
5
|
+
* definition; this module owns the `options` bag on that definition. It is the
|
|
6
|
+
* only place that knows how a tier's provider-agnostic `effort` maps onto the
|
|
7
|
+
* provider-specific knob (`effort` for Anthropic, `reasoning_effort` for
|
|
8
|
+
* OpenAI) and what to do when a tier asks for something the provider cannot do.
|
|
9
|
+
*
|
|
10
|
+
* The display-path builder in `src/commands/output.ts` renders what a tier is
|
|
11
|
+
* configured with; this one decides what is actually sent. They are kept apart
|
|
12
|
+
* on purpose: `/tiers` should not warn, downgrade or drop keys.
|
|
13
|
+
*/
|
|
14
|
+
import type { TierConfig } from "./config";
|
|
15
|
+
import { EFFORT_LEVELS } from "./config";
|
|
16
|
+
import { isClaudeModel } from "./protocol";
|
|
17
|
+
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
// Warn-once
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
|
|
22
|
+
// Agent registration runs on every `config` hook, so an unqualified
|
|
23
|
+
// console.warn would repeat the same line for the life of the session. Keys are
|
|
24
|
+
// deliberately tight (tier name + offending value where the value matters), so
|
|
25
|
+
// two different mistakes are still two different warnings.
|
|
26
|
+
const warnedAgentOptionsEffort = new Set<string>();
|
|
27
|
+
|
|
28
|
+
export function warnAgentOptionsEffortOnce(key: string, message: string): void {
|
|
29
|
+
if (warnedAgentOptionsEffort.has(key)) return;
|
|
30
|
+
warnedAgentOptionsEffort.add(key);
|
|
31
|
+
console.warn(`[model-router] ${message}`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function resetAgentOptionsEffortWarnings(): void {
|
|
35
|
+
warnedAgentOptionsEffort.clear();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function isEffortLevel(value: unknown): value is (typeof EFFORT_LEVELS)[number] {
|
|
39
|
+
return typeof value === "string" && EFFORT_LEVELS.some((level) => level === value);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function isOpenAIModel(model: string): boolean {
|
|
43
|
+
const s = model.toLowerCase();
|
|
44
|
+
return s.startsWith("openai/") || /\bgpt-/.test(s) || /(^|[/\-_])o[134]([/\-_]|$)/.test(s);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Provider-specific agent options for a tier, as registered with opencode.
|
|
49
|
+
*
|
|
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
|
|
54
|
+
* only ever present when something asked for it — an unset `effort` leaves no
|
|
55
|
+
* trace in the returned object.
|
|
56
|
+
*/
|
|
57
|
+
export function buildAgentOptions(tier: TierConfig, tierName = tier.model): Record<string, unknown> {
|
|
58
|
+
const opts: Record<string, unknown> = {};
|
|
59
|
+
|
|
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
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// OpenAI reasoning config
|
|
75
|
+
if (tier.reasoning) {
|
|
76
|
+
if (tier.reasoning.effort) {
|
|
77
|
+
opts.reasoning_effort = tier.reasoning.effort;
|
|
78
|
+
}
|
|
79
|
+
if (tier.reasoning.summary) {
|
|
80
|
+
opts.reasoning_summary = tier.reasoning.summary;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const effort: unknown = tier.effort;
|
|
85
|
+
if (effort !== undefined) {
|
|
86
|
+
if (!isEffortLevel(effort)) {
|
|
87
|
+
// Loading tiers.json rejects this, but an override layer or a
|
|
88
|
+
// programmatic caller can still hand us junk. Ignore it rather than
|
|
89
|
+
// failing registration for the whole preset.
|
|
90
|
+
warnAgentOptionsEffortOnce(
|
|
91
|
+
`invalid:${tierName}:${String(effort)}`,
|
|
92
|
+
`tier ${tierName}: invalid effort '${String(effort)}' ignored`,
|
|
93
|
+
);
|
|
94
|
+
} else if (isClaudeModel(tier.model)) {
|
|
95
|
+
if (hasThinkingBudget) {
|
|
96
|
+
warnAgentOptionsEffortOnce(
|
|
97
|
+
`anthropic-conflict:${tierName}`,
|
|
98
|
+
`tier ${tierName}: both thinking and effort set; explicit thinking wins`,
|
|
99
|
+
);
|
|
100
|
+
} else {
|
|
101
|
+
opts.effort = effort;
|
|
102
|
+
}
|
|
103
|
+
} else if (isOpenAIModel(tier.model)) {
|
|
104
|
+
if (tier.reasoning?.effort) {
|
|
105
|
+
warnAgentOptionsEffortOnce(
|
|
106
|
+
`openai-conflict:${tierName}`,
|
|
107
|
+
`tier ${tierName}: both reasoning.effort and effort set; explicit reasoning wins`,
|
|
108
|
+
);
|
|
109
|
+
} else if (effort === "xhigh" || effort === "max") {
|
|
110
|
+
warnAgentOptionsEffortOnce(
|
|
111
|
+
`openai-downgrade:${tierName}:${effort}`,
|
|
112
|
+
`tier ${tierName}: downgrading effort '${effort}' to 'high' because OpenAI reasoning_effort only supports low, medium, or high`,
|
|
113
|
+
);
|
|
114
|
+
opts.reasoning_effort = "high";
|
|
115
|
+
} else {
|
|
116
|
+
opts.reasoning_effort = effort;
|
|
117
|
+
}
|
|
118
|
+
} else {
|
|
119
|
+
warnAgentOptionsEffortOnce(
|
|
120
|
+
`unknown-provider:${tierName}`,
|
|
121
|
+
`tier ${tierName}: effort ignored for unknown provider family '${tier.model}'`,
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return opts;
|
|
127
|
+
}
|
|
@@ -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
|
+
}
|