opencode-model-router 2.2.0 → 2.3.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 +65 -0
- package/README.md +35 -3
- package/package.json +4 -1
- package/src/commands/output.ts +4 -1
- package/src/compat/child-session.ts +43 -0
- package/src/compat/v2-client.ts +107 -7
- package/src/compat/v2-hooks.ts +118 -31
- package/src/escalate/attempt-recorder.ts +263 -0
- package/src/escalate/ladder.ts +484 -10
- package/src/escalate/resume.ts +208 -0
- package/src/escalate/variants.ts +391 -0
- package/src/index.ts +486 -38
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1365 -19
- package/src/router/protocol.ts +47 -0
- package/src/router/sessions.ts +441 -9
- package/src/routing/advisor/findings.ts +706 -0
- package/src/routing/advisor/index.ts +606 -0
- package/src/routing/classify/backends/host.ts +163 -0
- package/src/routing/classify/backends/openai-compatible.ts +275 -0
- package/src/routing/classify/backends/shared.ts +741 -0
- package/src/routing/classify/backends/typesafe.ts +315 -0
- package/src/routing/classify/fences.ts +96 -0
- package/src/routing/classify/index.ts +576 -0
- package/src/routing/classify/route-line.ts +298 -0
- package/src/routing/classify/rules.ts +607 -0
- package/src/routing/classify/scrub.ts +214 -0
- package/src/routing/classify/state.ts +148 -0
- package/src/routing/classify/text.ts +20 -0
- package/src/routing/classify/types.ts +1280 -0
- package/src/routing/commands/annotate-plan.ts +652 -0
- package/src/routing/commands/stats.ts +131 -0
- package/src/routing/commands/v1-roles.ts +64 -0
- package/src/routing/engine/index.ts +32 -0
- package/src/routing/engine/kernel.ts +597 -0
- package/src/routing/engine/ladders.ts +561 -0
- package/src/routing/engine/plan.ts +404 -0
- package/src/routing/engine/protocol-line.ts +133 -0
- package/src/routing/engine/simulate.ts +167 -0
- package/src/routing/engine/types.ts +270 -0
- package/src/routing/file-lock.ts +53 -0
- package/src/routing/outcomes/beta.ts +141 -0
- package/src/routing/outcomes/cost.ts +313 -0
- package/src/routing/outcomes/index.ts +172 -0
- package/src/routing/outcomes/ingest.ts +812 -0
- package/src/routing/outcomes/persist.ts +1058 -0
- package/src/routing/outcomes/stats.ts +602 -0
- package/src/routing/outcomes/store.ts +653 -0
- package/src/routing/outcomes/types.ts +954 -0
- package/src/routing/wire/dispatch.ts +799 -0
- package/src/routing/wire/hint.ts +208 -0
- package/src/routing/wire/host-info.ts +256 -0
- package/src/routing/wire/runtime.ts +259 -0
- package/src/v2.ts +15 -1
|
@@ -0,0 +1,706 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cost doctor findings (M8, plan F4, Phase 2.4.1): what the router's own configuration and the host's catalog say
|
|
3
|
+
* about money and reliability that the user can fix.
|
|
4
|
+
*
|
|
5
|
+
* Pure: no I/O, no clock, no host calls. Every check reads only what it is handed (the merged router config, a view of
|
|
6
|
+
* the host's agents and the host model catalog) and answers with {@link Finding}s. A check that cannot know (no
|
|
7
|
+
* catalog, no agent list) says nothing instead of guessing, and a check that throws is skipped and logged by
|
|
8
|
+
* {@link runChecks}'s caller (`runAdvisor`), never raised into a session.
|
|
9
|
+
*
|
|
10
|
+
* Never invents a model: a suggested model always comes from the catalog it was given, is enabled, active and priced (A1/A2), and
|
|
11
|
+
* for the host's title agent it passes the host's own `Model.small` predicate (text in and out). A finding says where its fix goes:
|
|
12
|
+
* `target: "host"` = the user's `opencode.json`, `target: "router"` = `opencode-model-router.overrides.jsonc`; a snippet is JSON for that
|
|
13
|
+
* file, nothing else.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { readFileSync } from "node:fs";
|
|
17
|
+
import type { RouterConfig, TierConfig } from "../../router/config";
|
|
18
|
+
import { configPath, resolveCandidates, resolveClassifierForPreset, resolveRouting, resolveVariantSteps, validateConfig } from "../../router/config";
|
|
19
|
+
import { getActiveTiers } from "../../router/protocol";
|
|
20
|
+
import { buildEscalatePolicy } from "../../escalate/ladder";
|
|
21
|
+
import type { TierVariantInfo } from "../../escalate/ladder";
|
|
22
|
+
import { DEFAULT_VARIANT, catalogVariantIds, nextVariant, variantCovered, variantPosition, variantRank } from "../../escalate/variants";
|
|
23
|
+
import type { VariantLadder } from "../../escalate/variants";
|
|
24
|
+
import { CLASS_STATIC_TIER } from "../classify/types";
|
|
25
|
+
import { isUnpriced, selectPriceEntry } from "../outcomes/cost";
|
|
26
|
+
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
// Types
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
/** `warning`: a misconfiguration that costs reliability or silently disables something; `saving`: a concrete way to spend less; `info`: explains a number. */
|
|
32
|
+
export type FindingSeverity = "warning" | "saving" | "info";
|
|
33
|
+
|
|
34
|
+
export const FINDING_IDS = [
|
|
35
|
+
"title-model-unset",
|
|
36
|
+
"model-not-in-catalog",
|
|
37
|
+
"no-tool-support",
|
|
38
|
+
"variant-not-offered",
|
|
39
|
+
"effort-not-offered",
|
|
40
|
+
"variant-effort",
|
|
41
|
+
"effort-variant-mismatch",
|
|
42
|
+
"rejected-candidates",
|
|
43
|
+
"foreign-candidates",
|
|
44
|
+
"covered-tier",
|
|
45
|
+
"variant-ladder-budget",
|
|
46
|
+
"attempts-without-variants",
|
|
47
|
+
"unpriced-model",
|
|
48
|
+
"subscription-pricing",
|
|
49
|
+
"native-role-unmatched-rung",
|
|
50
|
+
"tier-agent-unavailable",
|
|
51
|
+
"classifier-model-missing",
|
|
52
|
+
] as const;
|
|
53
|
+
export type FindingId = (typeof FINDING_IDS)[number];
|
|
54
|
+
|
|
55
|
+
/** Whose configuration the fix belongs to: the host's own (`opencode.json`) or this plugin's (`opencode-model-router.overrides.jsonc`). */
|
|
56
|
+
export type FindingTarget = "host" | "router";
|
|
57
|
+
|
|
58
|
+
/** Only the title agent's model is the host's; everything else is this plugin's configuration. */
|
|
59
|
+
export const FINDING_TARGET: Readonly<Record<FindingId, FindingTarget>> = {
|
|
60
|
+
"title-model-unset": "host",
|
|
61
|
+
"model-not-in-catalog": "router",
|
|
62
|
+
"no-tool-support": "router",
|
|
63
|
+
"variant-not-offered": "router",
|
|
64
|
+
"effort-not-offered": "router",
|
|
65
|
+
"variant-effort": "router",
|
|
66
|
+
"effort-variant-mismatch": "router",
|
|
67
|
+
"rejected-candidates": "router",
|
|
68
|
+
"foreign-candidates": "router",
|
|
69
|
+
"covered-tier": "router",
|
|
70
|
+
"variant-ladder-budget": "router",
|
|
71
|
+
"attempts-without-variants": "router",
|
|
72
|
+
"unpriced-model": "router",
|
|
73
|
+
"subscription-pricing": "router",
|
|
74
|
+
"native-role-unmatched-rung": "router",
|
|
75
|
+
"tier-agent-unavailable": "router",
|
|
76
|
+
"classifier-model-missing": "router",
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export interface Finding {
|
|
80
|
+
readonly id: FindingId;
|
|
81
|
+
readonly severity: FindingSeverity;
|
|
82
|
+
/** Which file the fix is for. */
|
|
83
|
+
readonly target: FindingTarget;
|
|
84
|
+
/** The agent, tier or model the finding is about (`""` for a global finding). */
|
|
85
|
+
readonly subject: string;
|
|
86
|
+
/** What is wrong and what it costs, in one or two sentences. */
|
|
87
|
+
readonly message: string;
|
|
88
|
+
/** A JSON snippet for the `target` file that fixes it, or `null` when there is nothing safe to suggest. */
|
|
89
|
+
readonly snippet: string | null;
|
|
90
|
+
/** The OpenCode v1 spelling of a host-target snippet (`agent.title.model` / `small_model`), or `null`. */
|
|
91
|
+
readonly snippetV1: string | null;
|
|
92
|
+
/** The finding concerns a tier of a bundled preset that the user has not modified (QA-2.4-5): listed in `/router`, never in a notice. */
|
|
93
|
+
readonly bundledTier: boolean;
|
|
94
|
+
/** May appear in a notice: a warning or a saving that is not about an unmodified bundled tier. */
|
|
95
|
+
readonly notify: boolean;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** What a check produces: `runChecks` adds `target`, `snippetV1`, `bundledTier` and `notify`. */
|
|
99
|
+
type RawFinding = Omit<Finding, "target" | "snippetV1" | "bundledTier" | "notify"> & { readonly snippetV1?: string | null };
|
|
100
|
+
|
|
101
|
+
/** The slice of a host `Model.Info` the checks read (structural; extra fields are ignored). */
|
|
102
|
+
export interface AdvisorCatalogModel {
|
|
103
|
+
readonly providerID: string;
|
|
104
|
+
readonly id: string;
|
|
105
|
+
readonly enabled?: boolean;
|
|
106
|
+
readonly status?: string;
|
|
107
|
+
/** Model family (`claude-haiku`, `gpt-luna`, …): the host's small-model pick is by family. */
|
|
108
|
+
readonly family?: string;
|
|
109
|
+
readonly capabilities?: { readonly tools?: boolean; readonly input?: readonly string[]; readonly output?: readonly string[] } | null;
|
|
110
|
+
readonly variants?: ReadonlyArray<{ readonly id?: unknown } | null | undefined> | null;
|
|
111
|
+
readonly cost?: unknown;
|
|
112
|
+
readonly limit?: { readonly context?: unknown; readonly input?: unknown; readonly output?: unknown } | null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface HostAgentView {
|
|
116
|
+
readonly id: string;
|
|
117
|
+
/** `provider/model[#variant]`, or `null` when the agent has no model of its own. */
|
|
118
|
+
readonly model: string | null;
|
|
119
|
+
/** `subagent`, `primary` or `all` as the host reports it; `null` when the record carries none of those (a check then says nothing about the agent). */
|
|
120
|
+
readonly mode: "subagent" | "primary" | "all" | null;
|
|
121
|
+
readonly hidden: boolean;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** What the checks need to know of the host's own configuration: its agents (a missing `model` = unset) and the session's model. */
|
|
125
|
+
export interface HostConfigView {
|
|
126
|
+
readonly agents: readonly HostAgentView[];
|
|
127
|
+
/** The orchestrator's model (the host's "primary"); `null`/absent when not known yet. The host's title pick depends on its provider. */
|
|
128
|
+
readonly primary?: { readonly providerID: string; readonly modelID: string | null } | null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Providers whose catalog prices are relative weights, not what is billed (D6). */
|
|
132
|
+
export const SUBSCRIPTION_PROVIDERS: readonly string[] = ["opencode", "opencode-go", "github-copilot"];
|
|
133
|
+
|
|
134
|
+
const SEVERITY_ORDER: Readonly<Record<FindingSeverity, number>> = { warning: 0, saving: 1, info: 2 };
|
|
135
|
+
|
|
136
|
+
// ---------------------------------------------------------------------------
|
|
137
|
+
// Helpers
|
|
138
|
+
// ---------------------------------------------------------------------------
|
|
139
|
+
|
|
140
|
+
/** `provider/model#variant` → `{ model: "provider/model", variant }`. */
|
|
141
|
+
export function splitModelRef(ref: string): { model: string; variant: string | null } {
|
|
142
|
+
const at = ref.indexOf("#");
|
|
143
|
+
return at < 0 ? { model: ref, variant: null } : { model: ref.slice(0, at), variant: ref.slice(at + 1) === "" ? null : ref.slice(at + 1) };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function providerOf(model: string): string {
|
|
147
|
+
const slash = model.indexOf("/");
|
|
148
|
+
return slash < 0 ? "" : model.slice(0, slash);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function index(catalog: readonly AdvisorCatalogModel[]): Map<string, AdvisorCatalogModel> {
|
|
152
|
+
const map = new Map<string, AdvisorCatalogModel>();
|
|
153
|
+
for (const model of catalog) map.set(`${model.providerID}/${model.id}`, model);
|
|
154
|
+
return map;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function usable(model: AdvisorCatalogModel): boolean {
|
|
158
|
+
return model.enabled === true && model.status !== "deprecated";
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Catalog price of `model` as `input + output` USD per million tokens; `null` when unpriced (A1). */
|
|
162
|
+
function pricePerMillion(model: AdvisorCatalogModel): number | null {
|
|
163
|
+
if (isUnpriced(model.cost as Parameters<typeof isUnpriced>[0])) return null;
|
|
164
|
+
const entry = selectPriceEntry(model.cost as Parameters<typeof selectPriceEntry>[0], 0);
|
|
165
|
+
return entry === null ? null : entry.input + entry.output;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* The host's own candidate test for a title model (`Model.small` at v2.0.22, `core/src/model.ts`): enabled, `status: "active"`, and text
|
|
170
|
+
* in AND out. Tool calls are not needed (a title is one text generation), so they are not required here (QA-2.4-11).
|
|
171
|
+
*/
|
|
172
|
+
function titleEligible(model: AdvisorCatalogModel): boolean {
|
|
173
|
+
const input = model.capabilities?.input;
|
|
174
|
+
const output = model.capabilities?.output;
|
|
175
|
+
return (
|
|
176
|
+
model.enabled === true &&
|
|
177
|
+
model.status === "active" &&
|
|
178
|
+
Array.isArray(input) && input.some((item) => typeof item === "string" && item.startsWith("text")) &&
|
|
179
|
+
Array.isArray(output) && output.some((item) => typeof item === "string" && item.startsWith("text"))
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** The families the host's `Model.small` looks for, in its order of preference. */
|
|
184
|
+
export const HOST_SMALL_MODEL_FAMILIES: readonly string[] = ["gpt-luna", "gemini-flash-lite", "gemini-flash", "claude-haiku"];
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* What `Model.small(providerID)` would answer for this catalog: among the provider's eligible models, the first of
|
|
188
|
+
* {@link HOST_SMALL_MODEL_FAMILIES} that has one. `null` = the host finds none and a title is generated with the session's own model.
|
|
189
|
+
*/
|
|
190
|
+
export function hostSmallModel(catalog: readonly AdvisorCatalogModel[], providerID: string): AdvisorCatalogModel | null {
|
|
191
|
+
const models = catalog.filter((model) => model.providerID === providerID && titleEligible(model));
|
|
192
|
+
for (const family of HOST_SMALL_MODEL_FAMILIES) {
|
|
193
|
+
const hit = models.find((model) => model.family === family);
|
|
194
|
+
if (hit !== undefined) return hit;
|
|
195
|
+
}
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* A2: the cheapest priced model the host would accept for the title agent (`titleEligible`). Ties break on `provider/id`, so the
|
|
201
|
+
* answer is stable. `null` when the catalog has none.
|
|
202
|
+
*/
|
|
203
|
+
export function cheapestTitleModel(catalog: readonly AdvisorCatalogModel[]): { ref: string; model: AdvisorCatalogModel; price: number } | null {
|
|
204
|
+
let best: { ref: string; model: AdvisorCatalogModel; price: number } | null = null;
|
|
205
|
+
for (const model of catalog) {
|
|
206
|
+
if (!titleEligible(model)) continue;
|
|
207
|
+
const price = pricePerMillion(model);
|
|
208
|
+
if (price === null) continue;
|
|
209
|
+
const ref = `${model.providerID}/${model.id}`;
|
|
210
|
+
if (best === null || price < best.price || (price === best.price && ref < best.ref)) best = { ref, model, price };
|
|
211
|
+
}
|
|
212
|
+
return best;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function fmtPrice(model: AdvisorCatalogModel): string {
|
|
216
|
+
const entry = selectPriceEntry(model.cost as Parameters<typeof selectPriceEntry>[0], 0);
|
|
217
|
+
return entry === null ? "n/a" : `$${entry.input}/$${entry.output} per Mtok in/out`;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function json(value: unknown): string {
|
|
221
|
+
return JSON.stringify(value);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function isEffortConfigured(tier: TierConfig): boolean {
|
|
225
|
+
return tier.effort !== undefined || tier.thinking !== undefined || tier.reasoning !== undefined;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Every `(model, variant)` rung of every active tier, with the tier that owns it. */
|
|
229
|
+
function rungsOf(cfg: RouterConfig): Array<{ tier: string; model: string; variant: string | null; costRatio: number }> {
|
|
230
|
+
const rungs: Array<{ tier: string; model: string; variant: string | null; costRatio: number }> = [];
|
|
231
|
+
for (const name of Object.keys(getActiveTiers(cfg) ?? {})) {
|
|
232
|
+
for (const rung of resolveCandidates(name, cfg)) rungs.push({ tier: name, model: rung.model, variant: rung.variant ?? null, costRatio: rung.costRatio });
|
|
233
|
+
}
|
|
234
|
+
return rungs;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function activeTierEntries(cfg: RouterConfig): Array<[string, TierConfig]> {
|
|
238
|
+
return Object.entries(getActiveTiers(cfg) ?? {}).filter(([, tier]) => tier !== null && typeof tier === "object" && typeof tier.model === "string" && tier.model !== "");
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
interface CheckInput {
|
|
242
|
+
readonly cfg: RouterConfig;
|
|
243
|
+
readonly host: HostConfigView | null;
|
|
244
|
+
readonly catalog: readonly AdvisorCatalogModel[] | null;
|
|
245
|
+
/** Catalog by `provider/model`; `null` when the catalog is unknown or empty (a catalog check then says nothing). */
|
|
246
|
+
readonly byRef: ReadonlyMap<string, AdvisorCatalogModel> | null;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
type Check = (input: CheckInput) => RawFinding[];
|
|
250
|
+
|
|
251
|
+
// ---------------------------------------------------------------------------
|
|
252
|
+
// Checks
|
|
253
|
+
// ---------------------------------------------------------------------------
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* F4, QA-2.4-1: the host picks a session title's model as `agents.title.model`, else `Model.small(<session's provider>)` (a small model of
|
|
257
|
+
* the SAME provider: gpt-luna, gemini-flash-lite, gemini-flash or claude-haiku), else the session's own model (v2.0.22
|
|
258
|
+
* `core/src/session/context.ts` `selectTitle`). So the only case where leaving it unset costs anything is the last one: the provider has
|
|
259
|
+
* no such model in the catalog. Everything else is silent: with a small model present the host already picks a cheap one, and without
|
|
260
|
+
* knowing the session's provider (or the catalog) the pick cannot be predicted. No consumer of a `summary` model was found in the host,
|
|
261
|
+
* so none is reported.
|
|
262
|
+
*/
|
|
263
|
+
const titleModel: Check = ({ host, catalog }) => {
|
|
264
|
+
if (host === null || catalog === null) return [];
|
|
265
|
+
const title = host.agents.find((a) => a.id === "title");
|
|
266
|
+
if (title === undefined || title.model !== null) return [];
|
|
267
|
+
const primary = host.primary;
|
|
268
|
+
if (primary === null || primary === undefined) return [];
|
|
269
|
+
if (hostSmallModel(catalog, primary.providerID) !== null) return [];
|
|
270
|
+
// The host falls back to the primary itself, so that is the price to beat (never when the primary is unpriced: then no saving is claimed).
|
|
271
|
+
const cheapest = cheapestTitleModel(catalog);
|
|
272
|
+
if (cheapest === null) return [];
|
|
273
|
+
const primaryEntry = primary.modelID === null ? undefined : catalog.find((m) => m.providerID === primary.providerID && m.id === primary.modelID);
|
|
274
|
+
const primaryPrice = primaryEntry === undefined ? null : pricePerMillion(primaryEntry);
|
|
275
|
+
if (primaryPrice !== null && cheapest.price >= primaryPrice) return [];
|
|
276
|
+
const primaryRef = primary.modelID === null ? primary.providerID : `${primary.providerID}/${primary.modelID}`;
|
|
277
|
+
const subscription = SUBSCRIPTION_PROVIDERS.includes(cheapest.model.providerID);
|
|
278
|
+
return [{
|
|
279
|
+
id: "title-model-unset",
|
|
280
|
+
severity: "saving",
|
|
281
|
+
subject: "title",
|
|
282
|
+
message: `agents.title.model is unset and the host finds no small model of ${primary.providerID} in your catalog (it looks for ${HOST_SMALL_MODEL_FAMILIES.join(", ")} of the session's provider), so session titles are generated with the session's own model, ${primaryRef}${
|
|
283
|
+
primaryPrice === null ? "" : ` (${fmtPrice(primaryEntry as AdvisorCatalogModel)})`
|
|
284
|
+
}. The cheapest priced model the host accepts for it in your catalog is ${cheapest.ref} (${fmtPrice(cheapest.model)})${
|
|
285
|
+
subscription ? `; ${cheapest.model.providerID} is a subscription provider, so its catalog prices are relative weights, not billed amounts` : ""
|
|
286
|
+
}.`,
|
|
287
|
+
snippet: json({ agents: { title: { model: cheapest.ref } } }),
|
|
288
|
+
snippetV1: `${json({ agent: { title: { model: cheapest.ref } } })} or ${json({ small_model: cheapest.ref })}`,
|
|
289
|
+
}];
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
/** QA-1.1-9: every rung of every tier against the live catalog (existence, tool support, variant). */
|
|
293
|
+
const ladderCatalog: Check = ({ cfg, byRef }) => {
|
|
294
|
+
if (byRef === null) return [];
|
|
295
|
+
const findings: RawFinding[] = [];
|
|
296
|
+
const seen = new Set<string>();
|
|
297
|
+
for (const rung of rungsOf(cfg)) {
|
|
298
|
+
const entry = byRef.get(rung.model);
|
|
299
|
+
const key = `${rung.tier}|${rung.model}|${rung.variant ?? ""}`;
|
|
300
|
+
if (seen.has(key)) continue;
|
|
301
|
+
seen.add(key);
|
|
302
|
+
if (entry === undefined || !usable(entry)) {
|
|
303
|
+
findings.push({
|
|
304
|
+
id: "model-not-in-catalog",
|
|
305
|
+
severity: "warning",
|
|
306
|
+
subject: rung.tier,
|
|
307
|
+
message: `Tier ${rung.tier} uses ${rung.model}, which is ${entry === undefined ? "not in" : "not enabled or deprecated in"} the host's model catalog: a dispatch to it fails, and the engine cannot price or resume it.`,
|
|
308
|
+
snippet: null,
|
|
309
|
+
});
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
if (entry.capabilities?.tools === false) {
|
|
313
|
+
findings.push({
|
|
314
|
+
id: "no-tool-support",
|
|
315
|
+
severity: "warning",
|
|
316
|
+
subject: rung.tier,
|
|
317
|
+
message: `Tier ${rung.tier} uses ${rung.model}, which does not support tool calls; a subagent cannot read, edit or run anything on it.`,
|
|
318
|
+
snippet: null,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
const ids = catalogVariantIds(entry);
|
|
322
|
+
if (rung.variant !== null && ids !== null && !ids.includes(rung.variant)) {
|
|
323
|
+
findings.push({
|
|
324
|
+
id: "variant-not-offered",
|
|
325
|
+
severity: "warning",
|
|
326
|
+
subject: rung.tier,
|
|
327
|
+
message: `Tier ${rung.tier} asks for ${rung.model}#${rung.variant}, but the catalog offers ${ids.length === 0 ? "no variants" : `only ${ids.join(", ")}`} for it: the variant is dropped, the tier takes no variant steps and cannot be resumed.`,
|
|
328
|
+
snippet: null,
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
for (const [name, tier] of activeTierEntries(cfg)) {
|
|
333
|
+
if (tier.effort === undefined) continue;
|
|
334
|
+
const entry = byRef.get(tier.model);
|
|
335
|
+
const ids = entry === undefined ? null : catalogVariantIds(entry);
|
|
336
|
+
if (ids !== null && ids.length > 0 && !ids.includes(tier.effort)) {
|
|
337
|
+
findings.push({
|
|
338
|
+
id: "effort-not-offered",
|
|
339
|
+
severity: "info",
|
|
340
|
+
subject: name,
|
|
341
|
+
message: `Tier ${name} sets effort ${tier.effort}, which is not one of ${tier.model}'s catalog variants (${ids.join(", ")}); the host may map it provider-specifically or ignore it.`,
|
|
342
|
+
snippet: null,
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
return findings;
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
/** Ladders the runner will walk: needs variant steps on (v2, `auto`) and a catalog. */
|
|
350
|
+
function variantInfos(cfg: RouterConfig, byRef: ReadonlyMap<string, AdvisorCatalogModel> | null): { perTier: Readonly<Record<string, TierVariantInfo>>; maxTotalAttempts: number; ladder: readonly string[] } | null {
|
|
351
|
+
if (byRef === null || resolveVariantSteps(cfg, "v2") !== "auto") return null;
|
|
352
|
+
const policy = buildEscalatePolicy(cfg, {
|
|
353
|
+
host: "v2",
|
|
354
|
+
variantSteps: "auto",
|
|
355
|
+
maxContextFraction: resolveRouting(cfg, "v2").sessionReuse.maxContextFraction,
|
|
356
|
+
catalog: (model) => byRef.get(model) ?? null,
|
|
357
|
+
});
|
|
358
|
+
return { perTier: policy.variants?.perTier ?? {}, maxTotalAttempts: policy.maxTotalAttempts, ladder: policy.ladder };
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** A20 / QA-2.3-13: a tier that sets `variant` AND `effort`/`thinking`/`reasoning` has an empty variant ladder. */
|
|
362
|
+
const variantWithEffort: Check = ({ cfg, byRef }) => {
|
|
363
|
+
if (resolveVariantSteps(cfg, "v2") !== "auto") return [];
|
|
364
|
+
const findings: RawFinding[] = [];
|
|
365
|
+
for (const [name, tier] of activeTierEntries(cfg)) {
|
|
366
|
+
if (typeof tier.variant !== "string" || tier.variant === "" || !isEffortConfigured(tier)) continue;
|
|
367
|
+
const entry = byRef?.get(tier.model);
|
|
368
|
+
const ids = entry === undefined ? null : catalogVariantIds(entry);
|
|
369
|
+
const above = (ids ?? []).filter((id) => variantRank(id) > variantRank(tier.variant as string));
|
|
370
|
+
const own = resolveCandidates(name, cfg)[0];
|
|
371
|
+
const snippet = ids === null || above.length === 0 || own === undefined
|
|
372
|
+
? null
|
|
373
|
+
: json({ presets: { [cfg.activePreset]: { [name]: { candidates: [{ variant: tier.variant, costRatio: own.costRatio }, ...above.map((variant) => ({ variant }))] } } } });
|
|
374
|
+
findings.push({
|
|
375
|
+
id: "variant-effort",
|
|
376
|
+
severity: "warning",
|
|
377
|
+
subject: name,
|
|
378
|
+
message: `Tier ${name} sets variant ${tier.variant} together with ${[tier.effort !== undefined ? "effort" : null, tier.thinking !== undefined ? "thinking" : null, tier.reasoning !== undefined ? "reasoning" : null].filter((s) => s !== null).join("/")}: effort is delivered by the effort path only, so the tier has no variant steps, and an escalation across it starts a fresh session instead of resuming the child. Drop the effort setting from the tier and list its variants as \`candidates\`${
|
|
379
|
+
snippet === null ? "" : " (snippet: the variants the catalog offers above it; give each higher rung its own costRatio, it inherits the tier's otherwise, which understates it)"
|
|
380
|
+
}.`,
|
|
381
|
+
snippet,
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
return findings;
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* QA-3.2 (O-32-5, measured on the real OpenCode 2.0.22 host in Phase 3.2): a tier that sets `variant` AND a different `effort` runs the EFFORT
|
|
389
|
+
* on the wire (the agent's effort option wins over the stored variant: the child is stored `#medium` while the request carries `xhigh`), but
|
|
390
|
+
* the outcome keys, the decision rows and `routing:stats` name the VARIANT. The evidence is then filed under a rung that is not what ran.
|
|
391
|
+
Only while the engine records anything (`routing.engine` is not `static`).
|
|
392
|
+
* QA-3.2-R2-1: when variant steps are on (`auto`) `variant-effort` already fires for EVERY tier that sets `variant` together with an effort setting, and its fix
|
|
393
|
+
* (drop the effort setting, list the variants as candidates) removes this mismatch too; one warning per tier, not two, so this one only speaks while variant
|
|
394
|
+
* steps are off (`escalate.variantSteps: "none"`), where `variant-effort` is silent and the keys-versus-wire problem is all that is left.
|
|
395
|
+
* Measured on Anthropic Messages (the OpenAI Responses route was not measured for this).
|
|
396
|
+
*/
|
|
397
|
+
const effortVariantMismatch: Check = ({ cfg, byRef }) => {
|
|
398
|
+
if (resolveRouting(cfg, "v2").engine === "static") return [];
|
|
399
|
+
if (resolveVariantSteps(cfg, "v2") === "auto") return []; // `variant-effort` covers these tiers and says the same fix
|
|
400
|
+
const findings: RawFinding[] = [];
|
|
401
|
+
for (const [name, tier] of activeTierEntries(cfg)) {
|
|
402
|
+
if (typeof tier.variant !== "string" || tier.variant === "" || typeof tier.effort !== "string" || tier.effort === tier.variant) continue;
|
|
403
|
+
const entry = byRef?.get(tier.model);
|
|
404
|
+
const ids = entry === undefined ? null : catalogVariantIds(entry);
|
|
405
|
+
const offered = ids === null || ids.includes(tier.effort);
|
|
406
|
+
findings.push({
|
|
407
|
+
id: "effort-variant-mismatch",
|
|
408
|
+
severity: "warning",
|
|
409
|
+
subject: name,
|
|
410
|
+
message: `Tier ${name} sets variant ${tier.variant} but effort ${tier.effort}: the request runs effort ${tier.effort} (the agent's effort option wins over the stored variant; measured on Anthropic Messages), while the outcome keys, the decision rows and routing:stats name ${tier.model}#${tier.variant}, so what this tier learns is filed under a rung that is not what runs. Make them agree: ${
|
|
411
|
+
offered ? `set variant to ${tier.effort} (snippet), or ` : ""
|
|
412
|
+
}drop the effort setting.`,
|
|
413
|
+
snippet: offered ? json({ presets: { [cfg.activePreset]: { [name]: { variant: tier.effort } } } }) : null,
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
return findings;
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
/** The variant steps a tier takes from its base, in order (the ladder itself also lists the base and the rungs below it). */
|
|
420
|
+
function stepsFrom(ladder: VariantLadder, base: string): string[] {
|
|
421
|
+
const steps: string[] = [];
|
|
422
|
+
let current: string | null = base === DEFAULT_VARIANT ? null : base;
|
|
423
|
+
for (let i = 0; i < ladder.variants.length; i += 1) {
|
|
424
|
+
const next = nextVariant(ladder, current);
|
|
425
|
+
if (next === null) break;
|
|
426
|
+
steps.push(next);
|
|
427
|
+
current = next;
|
|
428
|
+
}
|
|
429
|
+
return steps;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** 1.5 handoff: rejected and foreign candidates, tiers a variant ladder covers, F5. */
|
|
433
|
+
const variantLadders: Check = ({ cfg, byRef }) => {
|
|
434
|
+
const infos = variantInfos(cfg, byRef);
|
|
435
|
+
if (infos === null) return [];
|
|
436
|
+
const findings: RawFinding[] = [];
|
|
437
|
+
for (const [name, info] of Object.entries(infos.perTier)) {
|
|
438
|
+
if (info.effortConfigured === true) continue; // reported by variantWithEffort
|
|
439
|
+
if (info.ladder.rejected.length > 0) {
|
|
440
|
+
findings.push({
|
|
441
|
+
id: "rejected-candidates",
|
|
442
|
+
severity: "warning",
|
|
443
|
+
subject: name,
|
|
444
|
+
message: `Tier ${name}: candidate variant${info.ladder.rejected.length > 1 ? "s" : ""} ${info.ladder.rejected.join(", ")} of ${info.model} ${info.ladder.rejected.length > 1 ? "are" : "is"} ignored (not offered by the catalog, unranked, or not above the previous rung). Variant steps walk ${info.ladder.variants.length === 0 ? "nothing" : info.ladder.variants.join(" → ")} (base ${info.base}).`,
|
|
445
|
+
snippet: null,
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
if (info.ladder.foreign.length > 0) {
|
|
449
|
+
findings.push({
|
|
450
|
+
id: "foreign-candidates",
|
|
451
|
+
severity: "info",
|
|
452
|
+
subject: name,
|
|
453
|
+
message: `Tier ${name}: candidate rung${info.ladder.foreign.length > 1 ? "s" : ""} on another model (${info.ladder.foreign.map((r) => `${r.model}${r.variant === null ? "" : `#${r.variant}`}`).join(", ")}) ${info.ladder.foreign.length > 1 ? "are" : "is"} never walked by variant steps (those stay on ${info.model}); the engine prices ${info.ladder.foreign.length > 1 ? "them" : "it"} as dispatch options only.`,
|
|
454
|
+
snippet: null,
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
const steps = stepsFrom(info.ladder, info.base);
|
|
458
|
+
if (steps.length >= infos.maxTotalAttempts - 1 && steps.length > 0) {
|
|
459
|
+
findings.push({
|
|
460
|
+
id: "variant-ladder-budget",
|
|
461
|
+
severity: "info",
|
|
462
|
+
subject: name,
|
|
463
|
+
message: `Tier ${name} has ${steps.length} variant steps (${[info.base, ...steps].join(" → ")}) and maxTotalAttempts is ${infos.maxTotalAttempts}: a failing delegation can spend its whole attempt budget on this tier's variants. The budget reserve still keeps an escalation reachable, but every variant of an unpriced model counts at the tier's costRatio unless you give it its own.`,
|
|
464
|
+
snippet: null,
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
// A tier skipped on escalation because an earlier tier on the same model already covers its base.
|
|
469
|
+
const order = infos.ladder.filter((name) => infos.perTier[name] !== undefined);
|
|
470
|
+
for (let i = 0; i < order.length; i += 1) {
|
|
471
|
+
const from = infos.perTier[order[i] as string] as TierVariantInfo;
|
|
472
|
+
if (from.effortConfigured === true) continue;
|
|
473
|
+
const fromSteps = stepsFrom(from.ladder, from.base);
|
|
474
|
+
const top = fromSteps.length === 0 ? from.base : (fromSteps[fromSteps.length - 1] as string);
|
|
475
|
+
const position = (variant: string): number => variantPosition(variant) ?? Number.POSITIVE_INFINITY;
|
|
476
|
+
for (let j = i + 1; j < order.length; j += 1) {
|
|
477
|
+
const to = infos.perTier[order[j] as string] as TierVariantInfo;
|
|
478
|
+
if (to.effortConfigured === true || to.model !== from.model) continue;
|
|
479
|
+
const toSteps = stepsFrom(to.ladder, to.base);
|
|
480
|
+
const toTop = toSteps.length === 0 ? to.base : (toSteps[toSteps.length - 1] as string);
|
|
481
|
+
if (variantCovered(to.base, top) && position(toTop) <= position(top)) {
|
|
482
|
+
findings.push({
|
|
483
|
+
id: "covered-tier",
|
|
484
|
+
severity: "info",
|
|
485
|
+
subject: order[j] as string,
|
|
486
|
+
message: `Tier ${order[j]} (${to.model}#${to.base}) is covered by tier ${order[i]}'s variant steps (up to #${top}): an escalation from ${order[i]} skips it and goes straight to the next tier that adds something.`,
|
|
487
|
+
snippet: null,
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
return findings;
|
|
493
|
+
};
|
|
494
|
+
|
|
495
|
+
/** F4: one attempt per tier and no variant steps = every failure pays for a bigger model. */
|
|
496
|
+
const attemptsWithoutVariants: Check = ({ cfg }) => {
|
|
497
|
+
const esc = cfg.enforcement?.escalate;
|
|
498
|
+
if (esc === undefined || esc === null) return [];
|
|
499
|
+
const perTier = esc.maxAttemptsPerTier ?? 1;
|
|
500
|
+
if (resolveVariantSteps(cfg, "v2") !== "none" || perTier !== 1) return [];
|
|
501
|
+
// QA-3.1-R2-5 (A20): variant steps exist only on tiers without effort/thinking/reasoning. When every ladder tier of the active preset
|
|
502
|
+
// sets one of those, turning variant steps on would change nothing, so the suggestion would be wrong.
|
|
503
|
+
const tiers = new Map(activeTierEntries(cfg));
|
|
504
|
+
const ladderTiers = buildEscalatePolicy(cfg).ladder.filter((name) => tiers.has(name)).map((name) => tiers.get(name) as TierConfig);
|
|
505
|
+
if (ladderTiers.length > 0 && ladderTiers.every(isEffortConfigured)) return [];
|
|
506
|
+
return [{
|
|
507
|
+
id: "attempts-without-variants",
|
|
508
|
+
severity: "info",
|
|
509
|
+
subject: "",
|
|
510
|
+
message: "enforcement.escalate.maxAttemptsPerTier is 1 and variantSteps is none: a failed verification re-runs the same rung once in a fresh child, then escalates to the next, more expensive tier; variant steps would retry a higher variant on the same session first, on tiers without effort/thinking/reasoning (a tier that sets one of those keeps the effort-bump path). Turn variant steps on (a `routing` block makes the default `auto`) or allow another attempt per tier.",
|
|
511
|
+
snippet: json({ enforcement: { escalate: { variantSteps: "auto" } } }),
|
|
512
|
+
}];
|
|
513
|
+
};
|
|
514
|
+
|
|
515
|
+
/** D5 / D6: unpriced ladder models and subscription providers. */
|
|
516
|
+
const pricing: Check = ({ cfg, byRef }) => {
|
|
517
|
+
if (byRef === null) return [];
|
|
518
|
+
const findings: RawFinding[] = [];
|
|
519
|
+
const models = [...new Set(rungsOf(cfg).map((r) => r.model))];
|
|
520
|
+
const unpriced = models.filter((m) => {
|
|
521
|
+
const entry = byRef.get(m);
|
|
522
|
+
return entry !== undefined && isUnpriced(entry.cost as Parameters<typeof isUnpriced>[0]);
|
|
523
|
+
});
|
|
524
|
+
if (unpriced.length > 0) {
|
|
525
|
+
findings.push({
|
|
526
|
+
id: "unpriced-model",
|
|
527
|
+
severity: "info",
|
|
528
|
+
subject: unpriced.join(", "),
|
|
529
|
+
message: `The catalog has no price for ${unpriced.join(", ")}: the engine compares candidates in costRatio units and reports no USD figure for them (a reported cost of 0 is treated as unknown). Token counts are still recorded.`,
|
|
530
|
+
snippet: null,
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
const subscription = [...new Set(models.map(providerOf))].filter((p) => SUBSCRIPTION_PROVIDERS.includes(p));
|
|
534
|
+
if (subscription.length > 0) {
|
|
535
|
+
findings.push({
|
|
536
|
+
id: "subscription-pricing",
|
|
537
|
+
severity: "info",
|
|
538
|
+
subject: subscription.join(", "),
|
|
539
|
+
message: `Provider${subscription.length > 1 ? "s" : ""} ${subscription.join(", ")} ${subscription.length > 1 ? "are" : "is a"} subscription provider${subscription.length > 1 ? "s" : ""}: catalog prices are not what is billed, so the engine uses them as relative weights only.`,
|
|
540
|
+
snippet: null,
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
return findings;
|
|
544
|
+
};
|
|
545
|
+
|
|
546
|
+
/** 1.4 handoff (E4): a role agent whose own model matches no rung of the preset is priced at its owning tier's first rung. */
|
|
547
|
+
const nativeRoles: Check = ({ cfg, host }) => {
|
|
548
|
+
if (host === null) return [];
|
|
549
|
+
const routing = resolveRouting(cfg, "v2");
|
|
550
|
+
if (routing.engine === "static") return [];
|
|
551
|
+
const rungKeys = new Set(rungsOf(cfg).map((r) => `${r.model}#${r.variant ?? DEFAULT_VARIANT}`));
|
|
552
|
+
const findings: RawFinding[] = [];
|
|
553
|
+
const reported = new Set<string>();
|
|
554
|
+
for (const [taskClass, agents] of Object.entries(routing.roles)) {
|
|
555
|
+
for (const id of agents) {
|
|
556
|
+
const agent = host.agents.find((a) => a.id === id);
|
|
557
|
+
if (agent === undefined || agent.model === null || agent.mode === null || agent.mode === "primary" || agent.hidden || reported.has(id)) continue;
|
|
558
|
+
const { model, variant } = splitModelRef(agent.model);
|
|
559
|
+
if (rungKeys.has(`${model}#${variant ?? DEFAULT_VARIANT}`)) continue;
|
|
560
|
+
reported.add(id);
|
|
561
|
+
const ownerName = CLASS_STATIC_TIER[taskClass as keyof typeof CLASS_STATIC_TIER] ?? cfg.defaultTier;
|
|
562
|
+
const owner = resolveCandidates(ownerName, cfg)[0];
|
|
563
|
+
findings.push({
|
|
564
|
+
id: "native-role-unmatched-rung",
|
|
565
|
+
severity: "info",
|
|
566
|
+
subject: id,
|
|
567
|
+
message: `Agent ${id} (role for ${taskClass}) runs ${agent.model}, which is not a rung of any tier, so the engine prices it at the first rung of tier ${ownerName}${owner === undefined ? "" : ` (${owner.costRatio}×)`}: an assumption, not its real cost. List it as a \`candidates\` rung with its own costRatio to price it properly.`,
|
|
568
|
+
snippet: null,
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
return findings;
|
|
573
|
+
};
|
|
574
|
+
|
|
575
|
+
/** 2.2 handoff: the engine routes to agents by id; a tier agent the host does not offer makes it inert for that tier. */
|
|
576
|
+
const tierAgents: Check = ({ cfg, host }) => {
|
|
577
|
+
if (host === null || host.agents.length === 0) return [];
|
|
578
|
+
const findings: RawFinding[] = [];
|
|
579
|
+
for (const [name] of activeTierEntries(cfg)) {
|
|
580
|
+
const agent = host.agents.find((a) => a.id === name);
|
|
581
|
+
if (agent !== undefined && (agent.mode === null || (agent.mode !== "primary" && !agent.hidden))) continue; // an unknown mode is not judged
|
|
582
|
+
findings.push({
|
|
583
|
+
id: "tier-agent-unavailable",
|
|
584
|
+
severity: "warning",
|
|
585
|
+
subject: name,
|
|
586
|
+
message: `The host offers no dispatchable subagent named ${name}${agent === undefined ? "" : agent.hidden ? " (it is hidden)" : " (it is a primary agent)"}: the engine cannot route a dispatch to this tier, and any \`ineligible: agent-unavailable\` reason in the decision log comes from this. Check that the plugin is registered and that no permission rule denies \`subagent:${name}\`.`,
|
|
587
|
+
snippet: null,
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
return findings;
|
|
591
|
+
};
|
|
592
|
+
|
|
593
|
+
/** QA-1.1-9: the `host` classifier backend names a catalog model. */
|
|
594
|
+
const classifierModel: Check = ({ cfg, byRef }) => {
|
|
595
|
+
if (byRef === null) return [];
|
|
596
|
+
const routing = resolveRouting(cfg, "v2");
|
|
597
|
+
const classifier = resolveClassifierForPreset(routing.classifier, cfg.activePreset);
|
|
598
|
+
if (classifier.backend !== "host" || classifier.model === null) return [];
|
|
599
|
+
const { model } = splitModelRef(classifier.model);
|
|
600
|
+
const entry = byRef.get(model);
|
|
601
|
+
if (entry !== undefined && usable(entry)) return [];
|
|
602
|
+
return [{
|
|
603
|
+
id: "classifier-model-missing",
|
|
604
|
+
severity: "warning",
|
|
605
|
+
subject: classifier.model,
|
|
606
|
+
message: `routing.classifier.model is ${classifier.model}, which is ${entry === undefined ? "not in" : "not enabled or deprecated in"} the host's model catalog: the classifier call fails and every dispatch falls back to the rules classifier.`,
|
|
607
|
+
snippet: null,
|
|
608
|
+
}];
|
|
609
|
+
};
|
|
610
|
+
|
|
611
|
+
const CHECKS: ReadonlyArray<readonly [string, Check]> = [
|
|
612
|
+
["title-model", titleModel],
|
|
613
|
+
["ladder-catalog", ladderCatalog],
|
|
614
|
+
["variant-effort", variantWithEffort],
|
|
615
|
+
["effort-variant", effortVariantMismatch],
|
|
616
|
+
["variant-ladders", variantLadders],
|
|
617
|
+
["attempts", attemptsWithoutVariants],
|
|
618
|
+
["pricing", pricing],
|
|
619
|
+
["native-roles", nativeRoles],
|
|
620
|
+
["tier-agents", tierAgents],
|
|
621
|
+
["classifier-model", classifierModel],
|
|
622
|
+
];
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* The findings about the SHAPE of a tier's configuration (`subject` is a tier name of the active preset): what the shipped `tiers.json`
|
|
626
|
+
* defines for that tier is not the user's doing, so while the tier is exactly as shipped these are listed in `/router` and never announced
|
|
627
|
+
* (QA-2.4-R2-7). The findings about the user's ENVIRONMENT (`model-not-in-catalog`, `no-tool-support`, `variant-not-offered`,
|
|
628
|
+
* `tier-agent-unavailable`: the model is not offered, has no tools, the agent is not there) are real whoever wrote the tier, so they
|
|
629
|
+
* always notify.
|
|
630
|
+
*/
|
|
631
|
+
const CONFIG_SHAPE: ReadonlySet<FindingId> = new Set<FindingId>([
|
|
632
|
+
"variant-effort",
|
|
633
|
+
"effort-variant-mismatch",
|
|
634
|
+
"rejected-candidates",
|
|
635
|
+
"foreign-candidates",
|
|
636
|
+
"covered-tier",
|
|
637
|
+
"variant-ladder-budget",
|
|
638
|
+
"effort-not-offered",
|
|
639
|
+
]);
|
|
640
|
+
|
|
641
|
+
function stable(value: unknown): string {
|
|
642
|
+
if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
|
|
643
|
+
if (typeof value === "object" && value !== null) {
|
|
644
|
+
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable((value as Record<string, unknown>)[key])}`).join(",")}}`;
|
|
645
|
+
}
|
|
646
|
+
return JSON.stringify(value) ?? "null";
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* The shipped `tiers.json`, validated like any config, read once per loaded config: the memo is keyed by the `RouterConfig` object, and
|
|
651
|
+
* `loadConfig` hands out a new object on every reload, so a `tiers.json` the plugin update replaced is read again (QA-2.4-R2-11) while
|
|
652
|
+
* a config in use is not re-read on every check. `null` = unreadable (a tier is then not "bundled").
|
|
653
|
+
*/
|
|
654
|
+
const bundledMemo = new WeakMap<RouterConfig, { readonly config: RouterConfig | null }>();
|
|
655
|
+
|
|
656
|
+
function bundledConfig(cfg: RouterConfig, onError: (check: string, error: unknown) => void): RouterConfig | null {
|
|
657
|
+
let memo = bundledMemo.get(cfg);
|
|
658
|
+
if (memo === undefined) {
|
|
659
|
+
try {
|
|
660
|
+
memo = { config: validateConfig(JSON.parse(readFileSync(configPath(), "utf-8"))) };
|
|
661
|
+
} catch (error) {
|
|
662
|
+
memo = { config: null };
|
|
663
|
+
onError("bundled-preset", error); // reported once per loaded config; every tier then counts as the user's own, so its findings still notify
|
|
664
|
+
}
|
|
665
|
+
bundledMemo.set(cfg, memo);
|
|
666
|
+
}
|
|
667
|
+
return memo.config;
|
|
668
|
+
}
|
|
669
|
+
/** The tier of the ACTIVE preset is exactly what the shipped `tiers.json` defines for that preset and tier (no override touched it). */
|
|
670
|
+
function isUnmodifiedBundledTier(cfg: RouterConfig, tierName: string, onError: (check: string, error: unknown) => void): boolean {
|
|
671
|
+
const live = cfg.presets[cfg.activePreset]?.[tierName];
|
|
672
|
+
const shipped = bundledConfig(cfg, onError)?.presets[cfg.activePreset]?.[tierName];
|
|
673
|
+
return live !== undefined && shipped !== undefined && stable(live) === stable(shipped);
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/**
|
|
677
|
+
* Run every check. A throwing check is reported to `onError` and skipped; the rest still run. Findings come back sorted by
|
|
678
|
+
* severity (warning, saving, info), then by check order, so the list is stable.
|
|
679
|
+
*/
|
|
680
|
+
export function runChecks(
|
|
681
|
+
cfg: RouterConfig,
|
|
682
|
+
host: HostConfigView | null,
|
|
683
|
+
catalog: readonly AdvisorCatalogModel[] | null,
|
|
684
|
+
onError: (check: string, error: unknown) => void,
|
|
685
|
+
): Finding[] {
|
|
686
|
+
const known = catalog !== null && catalog.length > 0 ? catalog : null;
|
|
687
|
+
const input: CheckInput = { cfg, host, catalog: known, byRef: known === null ? null : index(known) };
|
|
688
|
+
const out: Array<{ finding: Finding; order: number }> = [];
|
|
689
|
+
let order = 0;
|
|
690
|
+
for (const [name, check] of CHECKS) {
|
|
691
|
+
try {
|
|
692
|
+
for (const raw of check(input)) {
|
|
693
|
+
const bundledTier = CONFIG_SHAPE.has(raw.id) && isUnmodifiedBundledTier(cfg, raw.subject, onError);
|
|
694
|
+
out.push({
|
|
695
|
+
finding: { ...raw, target: FINDING_TARGET[raw.id], snippetV1: raw.snippetV1 ?? null, bundledTier, notify: raw.severity !== "info" && !bundledTier },
|
|
696
|
+
order: order++,
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
} catch (error) {
|
|
700
|
+
onError(name, error);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
return out
|
|
704
|
+
.sort((a, b) => SEVERITY_ORDER[a.finding.severity] - SEVERITY_ORDER[b.finding.severity] || a.order - b.order)
|
|
705
|
+
.map((entry) => entry.finding);
|
|
706
|
+
}
|