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
package/src/router/config.ts
CHANGED
|
@@ -8,8 +8,9 @@ import {
|
|
|
8
8
|
writeFileSync,
|
|
9
9
|
} from "node:fs";
|
|
10
10
|
import { availableParallelism, homedir } from "node:os";
|
|
11
|
-
import { dirname, join, resolve as resolvePath } from "node:path";
|
|
11
|
+
import { dirname, isAbsolute, join, resolve as resolvePath } from "node:path";
|
|
12
12
|
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { formatRouterLine } from "./build-info";
|
|
13
14
|
import { parseJsonc } from "./jsonc";
|
|
14
15
|
import type { DelegateInstructionsPolicy } from "./instructions";
|
|
15
16
|
import type { PluginLogger } from "./logger";
|
|
@@ -106,6 +107,12 @@ export interface TierConfig {
|
|
|
106
107
|
promptStyle?: PromptStyle;
|
|
107
108
|
/** Optional use-case hints shown in `/tiers`. */
|
|
108
109
|
whenToUse?: string[];
|
|
110
|
+
/**
|
|
111
|
+
* Ordered `(model, variant, costRatio)` rungs the routing engine may use for
|
|
112
|
+
* this tier. Absent or empty = the tier's own single `(model, variant,
|
|
113
|
+
* costRatio)`. See {@link resolveCandidates}.
|
|
114
|
+
*/
|
|
115
|
+
candidates?: TierCandidate[];
|
|
109
116
|
}
|
|
110
117
|
|
|
111
118
|
export type Preset = Record<string, TierConfig>;
|
|
@@ -171,14 +178,132 @@ export interface EnforcementConfig {
|
|
|
171
178
|
failureRecheck?: boolean;
|
|
172
179
|
/** Budget for the reference re-run, in ms (integer >= 1). Default 60000. */
|
|
173
180
|
recheckTimeoutMs?: number };
|
|
174
|
-
escalate?:
|
|
175
|
-
/** Bump reasoning effort before escalating tiers. Default true. */
|
|
176
|
-
effortBump?: boolean;
|
|
177
|
-
/** Maximum reasoning effort for a bump. Default "xhigh". */
|
|
178
|
-
effortBumpMax?: EffortLevel };
|
|
181
|
+
escalate?: EscalateConfig;
|
|
179
182
|
proportional?: { trivialBypass?: boolean; trivialClassifier?: string };
|
|
180
183
|
}
|
|
181
184
|
|
|
185
|
+
export interface EscalateConfig {
|
|
186
|
+
floorTier?: string | null;
|
|
187
|
+
ladder?: string[];
|
|
188
|
+
maxAttemptsPerTier?: number;
|
|
189
|
+
maxTotalAttempts?: number;
|
|
190
|
+
costCeiling?: { base?: string; multiple?: number };
|
|
191
|
+
/** Bump reasoning effort before escalating tiers. Default true. */
|
|
192
|
+
effortBump?: boolean;
|
|
193
|
+
/** Maximum reasoning effort for a bump. Default "xhigh". */
|
|
194
|
+
effortBumpMax?: EffortLevel;
|
|
195
|
+
/**
|
|
196
|
+
* Retry on the same model's next variant before escalating the model (D10).
|
|
197
|
+
* OpenCode v2 only; ignored on v1. Default "auto".
|
|
198
|
+
*/
|
|
199
|
+
variantSteps?: VariantStepsMode;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ---------------------------------------------------------------------------
|
|
203
|
+
// Cost-aware routing (#74): the `routing` block, tier candidates, variant steps
|
|
204
|
+
// ---------------------------------------------------------------------------
|
|
205
|
+
|
|
206
|
+
/** `static` = the shipped taxonomy only; the others add the engine of #74. */
|
|
207
|
+
export const ROUTING_ENGINES = ["static", "shadow", "advise", "enforce"] as const;
|
|
208
|
+
export type RoutingEngine = (typeof ROUTING_ENGINES)[number];
|
|
209
|
+
|
|
210
|
+
/** How much a wrong, undetected result is worth in the expected-cost formula (D8). */
|
|
211
|
+
export const ROUTING_PROFILES = ["frugal", "balanced", "safe"] as const;
|
|
212
|
+
export type RoutingProfile = (typeof ROUTING_PROFILES)[number];
|
|
213
|
+
|
|
214
|
+
export const CLASSIFIER_BACKENDS = ["rules", "host", "openai-compatible", "typesafe"] as const;
|
|
215
|
+
export type ClassifierBackend = (typeof CLASSIFIER_BACKENDS)[number];
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* The task classes `routing.roles` may name. The classifier (Phase 1.2) assigns
|
|
219
|
+
* one of these to every dispatch; `other` is the catch-all.
|
|
220
|
+
*/
|
|
221
|
+
export const ROUTING_TASK_CLASSES = [
|
|
222
|
+
"search",
|
|
223
|
+
"recon",
|
|
224
|
+
"mechanical",
|
|
225
|
+
"implement",
|
|
226
|
+
"debug",
|
|
227
|
+
"design",
|
|
228
|
+
"review",
|
|
229
|
+
"other",
|
|
230
|
+
] as const;
|
|
231
|
+
export type RoutingTaskClass = (typeof ROUTING_TASK_CLASSES)[number];
|
|
232
|
+
|
|
233
|
+
export const VARIANT_STEP_MODES = ["auto", "none"] as const;
|
|
234
|
+
export type VariantStepsMode = (typeof VARIANT_STEP_MODES)[number];
|
|
235
|
+
|
|
236
|
+
/** Which host runs the plugin; `v2` is OpenCode v2 (D1). */
|
|
237
|
+
export type RouterHost = "v1" | "v2";
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* One rung of a tier's ladder. `model` falls back to the tier's own model;
|
|
241
|
+
* `variant` is NOT inherited (omitted = the model's default variant); `costRatio`
|
|
242
|
+
* falls back to the tier's.
|
|
243
|
+
*/
|
|
244
|
+
export interface TierCandidate {
|
|
245
|
+
model?: string;
|
|
246
|
+
variant?: string;
|
|
247
|
+
costRatio?: number;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Verification-depth → probability that a wrong result is caught (D8). */
|
|
251
|
+
export interface DetectionConfig {
|
|
252
|
+
deterministic?: number;
|
|
253
|
+
grader?: number;
|
|
254
|
+
none?: number;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Per-preset override of the classifier's `backend` / `model`. */
|
|
258
|
+
export interface ClassifierPresetOverride {
|
|
259
|
+
backend?: ClassifierBackend;
|
|
260
|
+
model?: string | null;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export interface ClassifierConfig {
|
|
264
|
+
backend?: ClassifierBackend;
|
|
265
|
+
/** Catalog ref `provider/model[#variant]`; required when the effective backend is not `rules` (D3). */
|
|
266
|
+
model?: string | null;
|
|
267
|
+
/** `openai-compatible` / `typesafe` only. */
|
|
268
|
+
baseUrl?: string | null;
|
|
269
|
+
apiKeyEnv?: string | null;
|
|
270
|
+
timeoutMs?: number;
|
|
271
|
+
samples?: 1 | 3;
|
|
272
|
+
maxStateChars?: number;
|
|
273
|
+
presets?: Record<string, ClassifierPresetOverride>;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export interface OutcomesConfig {
|
|
277
|
+
path?: string | null;
|
|
278
|
+
halfLifeDays?: number;
|
|
279
|
+
maxEffectiveSamples?: number;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export interface SessionReuseConfig {
|
|
283
|
+
maxContextFraction?: number;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export interface AdvisorConfig {
|
|
287
|
+
enabled?: boolean;
|
|
288
|
+
noticeIntervalHours?: number;
|
|
289
|
+
/** `false` = the cost doctor never notifies (the `/router` section stays). Default `true`. */
|
|
290
|
+
notify?: boolean;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export interface RoutingConfig {
|
|
294
|
+
engine?: RoutingEngine;
|
|
295
|
+
profile?: RoutingProfile;
|
|
296
|
+
margin?: number;
|
|
297
|
+
minClassConfidence?: number;
|
|
298
|
+
detection?: DetectionConfig;
|
|
299
|
+
classifier?: ClassifierConfig;
|
|
300
|
+
/** Task class → ordered agent ids. Absent = host default (D12); `{}` = none. */
|
|
301
|
+
roles?: Record<string, string[]>;
|
|
302
|
+
outcomes?: OutcomesConfig;
|
|
303
|
+
sessionReuse?: SessionReuseConfig;
|
|
304
|
+
advisor?: AdvisorConfig;
|
|
305
|
+
}
|
|
306
|
+
|
|
182
307
|
export interface RouterConfig {
|
|
183
308
|
/**
|
|
184
309
|
* Detect a delegate that hands a dispatch back having made zero tool calls
|
|
@@ -253,6 +378,8 @@ export interface RouterConfig {
|
|
|
253
378
|
subagentTiers?: Record<string, string>;
|
|
254
379
|
/** Experimental, opt-in features. Off by default. */
|
|
255
380
|
experimental?: { verifiedDelegateTool?: boolean };
|
|
381
|
+
/** Cost-aware routing engine (#74). Absent = today's static routing, byte for byte. */
|
|
382
|
+
routing?: RoutingConfig;
|
|
256
383
|
}
|
|
257
384
|
|
|
258
385
|
export interface RouterState {
|
|
@@ -283,6 +410,8 @@ interface ConfigCacheEntry {
|
|
|
283
410
|
reloadError: string | null;
|
|
284
411
|
/** Fingerprint a reload-failure warning was last emitted for (warn once each). */
|
|
285
412
|
warnedFingerprint: string | null;
|
|
413
|
+
/** Non-fatal findings of the build that produced `config` (see {@link getConfigNotices}). */
|
|
414
|
+
notices: ConfigNotice[];
|
|
286
415
|
}
|
|
287
416
|
|
|
288
417
|
/** Keyed by {@link normalizeProjectDir}. */
|
|
@@ -299,6 +428,7 @@ function getCacheEntry(key: string): ConfigCacheEntry {
|
|
|
299
428
|
tolerated: new Set<string>(),
|
|
300
429
|
reloadError: null,
|
|
301
430
|
warnedFingerprint: null,
|
|
431
|
+
notices: [],
|
|
302
432
|
};
|
|
303
433
|
_configCaches.set(key, entry);
|
|
304
434
|
}
|
|
@@ -327,6 +457,24 @@ function normalizeProjectDir(dir?: string): string {
|
|
|
327
457
|
return realpathOrSelf(dir ? resolvePath(dir) : process.cwd());
|
|
328
458
|
}
|
|
329
459
|
|
|
460
|
+
/**
|
|
461
|
+
* A non-fatal finding of a config build: something was ignored or looks wrong,
|
|
462
|
+
* but the config still loaded. `source` is the file concerned, when one is.
|
|
463
|
+
*/
|
|
464
|
+
export interface ConfigNotice {
|
|
465
|
+
source?: string;
|
|
466
|
+
message: string;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* The notices of the config last built for `dir` (default: the working
|
|
471
|
+
* directory): keys dropped from the project layer, unknown `routing` keys, and
|
|
472
|
+
* the like. Empty when there are none. `/router` lists them.
|
|
473
|
+
*/
|
|
474
|
+
export function getConfigNotices(dir?: string): readonly ConfigNotice[] {
|
|
475
|
+
return _configCaches.get(normalizeProjectDir(dir))?.notices ?? [];
|
|
476
|
+
}
|
|
477
|
+
|
|
330
478
|
/**
|
|
331
479
|
* Why the last config rebuild failed for `dir` (default: the working
|
|
332
480
|
* directory), or null when it succeeded. When a source (tiers.json, an
|
|
@@ -572,6 +720,7 @@ function validatePresets(obj: Record<string, unknown>): Record<string, unknown>
|
|
|
572
720
|
throw new Error(`tiers.json: preset '${presetName}' must be an object`);
|
|
573
721
|
}
|
|
574
722
|
const tiers = preset as Record<string, unknown>;
|
|
723
|
+
const presetRungs: PresetRung[] = [];
|
|
575
724
|
for (const [tierName, tier] of Object.entries(tiers)) {
|
|
576
725
|
if (typeof tier !== "object" || tier === null) {
|
|
577
726
|
throw new Error(
|
|
@@ -630,7 +779,40 @@ function validatePresets(obj: Record<string, unknown>): Record<string, unknown>
|
|
|
630
779
|
`tiers.json: preset '${presetName}' tier '${tierName}': promptStyle must be one of ${PROMPT_STYLES.join("|")}`,
|
|
631
780
|
);
|
|
632
781
|
}
|
|
782
|
+
// The tier's own variant is what a candidates list is matched against.
|
|
783
|
+
if (t.variant !== undefined && (typeof t.variant !== "string" || !VARIANT_ID_PATTERN.test(t.variant))) {
|
|
784
|
+
throw new Error(
|
|
785
|
+
`tiers.json: '${presetName}.${tierName}.variant' must be a non-empty string without whitespace or '#' (got ${describeValue(t.variant)})`,
|
|
786
|
+
);
|
|
787
|
+
}
|
|
788
|
+
const candidates = validateTierCandidates(t, `${presetName}.${tierName}`, tierName);
|
|
789
|
+
const tierVariant = typeof t.variant === "string" ? t.variant : undefined;
|
|
790
|
+
const tierCostRatio = tierCostRatioOf(tierName, t.costRatio);
|
|
791
|
+
if (
|
|
792
|
+
candidates !== undefined &&
|
|
793
|
+
candidates.length > 0 &&
|
|
794
|
+
ownRungProblem(t.model, tierVariant, tierCostRatio, candidates) === undefined
|
|
795
|
+
) {
|
|
796
|
+
candidates.forEach((c, i) =>
|
|
797
|
+
presetRungs.push({
|
|
798
|
+
model: c.model ?? t.model as string,
|
|
799
|
+
variant: c.variant,
|
|
800
|
+
costRatio: c.costRatio ?? tierCostRatio,
|
|
801
|
+
source: `${tierName}.candidates[${i}]`,
|
|
802
|
+
explicit: true,
|
|
803
|
+
}),
|
|
804
|
+
);
|
|
805
|
+
} else {
|
|
806
|
+
presetRungs.push({
|
|
807
|
+
model: t.model,
|
|
808
|
+
variant: tierVariant,
|
|
809
|
+
costRatio: tierCostRatio,
|
|
810
|
+
source: `${tierName} (own rung)`,
|
|
811
|
+
explicit: false,
|
|
812
|
+
});
|
|
813
|
+
}
|
|
633
814
|
}
|
|
815
|
+
assertConsistentRungCosts(presetName, presetRungs);
|
|
634
816
|
}
|
|
635
817
|
|
|
636
818
|
return presets;
|
|
@@ -866,6 +1048,17 @@ function describeValue(value: unknown): string {
|
|
|
866
1048
|
return `${description.slice(0, end)}…`;
|
|
867
1049
|
}
|
|
868
1050
|
|
|
1051
|
+
/** Opt-in redaction for credential-capable paths, without changing legacy diagnostics. */
|
|
1052
|
+
function describeRoutingValue(value: unknown, path: string): string {
|
|
1053
|
+
const secretPath = /(?:^|\.)(?:classifier|typesafe|apiKey[^.]*|token|headers?)(?:\.|$)/i.test(path);
|
|
1054
|
+
// A malformed routing container can itself contain a nested classifier block.
|
|
1055
|
+
const routingContainer = path === "routing" && value !== null && typeof value === "object";
|
|
1056
|
+
if (!secretPath && !routingContainer) return describeValue(value);
|
|
1057
|
+
if (value === null) return "null";
|
|
1058
|
+
const kind = Array.isArray(value) ? "array" : typeof value;
|
|
1059
|
+
return `${kind}; value not shown`;
|
|
1060
|
+
}
|
|
1061
|
+
|
|
869
1062
|
/** Copy without invoking accessors again; include defined get-only Proxy values. */
|
|
870
1063
|
function withValidatedSnapshots<T extends object>(
|
|
871
1064
|
obj: T,
|
|
@@ -1086,7 +1279,13 @@ function validateEnforcement(value: unknown): Record<string, unknown> | undefine
|
|
|
1086
1279
|
`tiers.json: enforcement.escalate.effortBumpMax must be one of ${EFFORT_LEVELS.join("|")} (got ${describeValue(effortBumpMax)})`,
|
|
1087
1280
|
);
|
|
1088
1281
|
}
|
|
1089
|
-
|
|
1282
|
+
const variantSteps = escalate.variantSteps;
|
|
1283
|
+
if (variantSteps !== undefined && !pickEnum(VARIANT_STEP_MODES, variantSteps)) {
|
|
1284
|
+
throw new Error(
|
|
1285
|
+
`tiers.json: enforcement.escalate.variantSteps must be one of ${VARIANT_STEP_MODES.join("|")} (got ${describeValue(variantSteps)})`,
|
|
1286
|
+
);
|
|
1287
|
+
}
|
|
1288
|
+
snapshots.escalate = withValidatedSnapshots(escalate, { effortBump, effortBumpMax, variantSteps });
|
|
1090
1289
|
if (
|
|
1091
1290
|
escalate.costCeiling !== undefined &&
|
|
1092
1291
|
typeof escalate.costCeiling === "object" &&
|
|
@@ -1223,6 +1422,579 @@ function validateEnforcement(value: unknown): Record<string, unknown> | undefine
|
|
|
1223
1422
|
}
|
|
1224
1423
|
}
|
|
1225
1424
|
|
|
1425
|
+
// ---------------------------------------------------------------------------
|
|
1426
|
+
// Cost-aware routing validation (#74)
|
|
1427
|
+
//
|
|
1428
|
+
// Unknown keys inside `routing` are ignored, not rejected: that is the policy of
|
|
1429
|
+
// every other block in this file (see modelGenerations), so a config written for
|
|
1430
|
+
// a newer release still loads on an older one. The only keys refused are the
|
|
1431
|
+
// prototype-reparenting ones (rejectPrototypeKeys), as for `enforcement`.
|
|
1432
|
+
// Validators read every value exactly once and return a plain snapshot of what
|
|
1433
|
+
// they validated, so a config object cannot change between check and use.
|
|
1434
|
+
// ---------------------------------------------------------------------------
|
|
1435
|
+
|
|
1436
|
+
/**
|
|
1437
|
+
* Agent ids in `routing.roles`: host agent names, case-sensitive (an agent may be
|
|
1438
|
+
* called `ContextScout` or `team/helper`; QA-1.1-5). Nothing that could not be a
|
|
1439
|
+
* name: no empty id, no whitespace, no `#`.
|
|
1440
|
+
*/
|
|
1441
|
+
const AGENT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_./-]*$/;
|
|
1442
|
+
|
|
1443
|
+
/**
|
|
1444
|
+
* An agent id: {@link AGENT_ID_PATTERN}, and nothing path-like beyond a plain
|
|
1445
|
+
* `a/b`: no empty, `.` or `..` segment (`a//b`, `a/../b`, `a/./b`) and no
|
|
1446
|
+
* trailing `/` or `.` (QA-1.1-27).
|
|
1447
|
+
*/
|
|
1448
|
+
function isAgentId(id: string): boolean {
|
|
1449
|
+
return (
|
|
1450
|
+
AGENT_ID_PATTERN.test(id) &&
|
|
1451
|
+
!id.endsWith("/") &&
|
|
1452
|
+
!id.endsWith(".") &&
|
|
1453
|
+
!id.split("/").some((segment) => segment === "" || segment === "." || segment === "..")
|
|
1454
|
+
);
|
|
1455
|
+
}
|
|
1456
|
+
/** Environment variable names (`classifier.apiKeyEnv`). */
|
|
1457
|
+
const ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
1458
|
+
/** A variant id: non-empty, no whitespace, no `#` (the ref separator). */
|
|
1459
|
+
const VARIANT_ID_PATTERN = /^[^\s#]+$/;
|
|
1460
|
+
|
|
1461
|
+
/** `value` as a member of `allowed`, narrowed without a cast. */
|
|
1462
|
+
function pickEnum<T extends string>(allowed: readonly T[], value: unknown): T | undefined {
|
|
1463
|
+
return allowed.find((candidate) => candidate === value);
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
function readEnum<T extends string>(
|
|
1467
|
+
obj: Record<string, unknown>,
|
|
1468
|
+
key: string,
|
|
1469
|
+
path: string,
|
|
1470
|
+
allowed: readonly T[],
|
|
1471
|
+
): T | undefined {
|
|
1472
|
+
const value = obj[key];
|
|
1473
|
+
if (value === undefined) return undefined;
|
|
1474
|
+
const hit = pickEnum(allowed, value);
|
|
1475
|
+
if (hit === undefined) {
|
|
1476
|
+
throw new Error(
|
|
1477
|
+
`tiers.json: ${path}.${key} must be one of ${allowed.join("|")} (got ${describeRoutingValue(value, `${path}.${key}`)})`,
|
|
1478
|
+
);
|
|
1479
|
+
}
|
|
1480
|
+
return hit;
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
interface NumberRule {
|
|
1484
|
+
min: number;
|
|
1485
|
+
max: number;
|
|
1486
|
+
/** `min` itself is not allowed (an open lower bound). */
|
|
1487
|
+
minExclusive?: boolean;
|
|
1488
|
+
integer?: boolean;
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
function readNumber(
|
|
1492
|
+
obj: Record<string, unknown>,
|
|
1493
|
+
key: string,
|
|
1494
|
+
path: string,
|
|
1495
|
+
rule: NumberRule,
|
|
1496
|
+
): number | undefined {
|
|
1497
|
+
const value = obj[key];
|
|
1498
|
+
if (value === undefined) return undefined;
|
|
1499
|
+
const inRange =
|
|
1500
|
+
typeof value === "number" &&
|
|
1501
|
+
Number.isFinite(value) &&
|
|
1502
|
+
(!rule.integer || Number.isInteger(value)) &&
|
|
1503
|
+
(rule.minExclusive ? value > rule.min : value >= rule.min) &&
|
|
1504
|
+
value <= rule.max;
|
|
1505
|
+
if (typeof value !== "number" || !inRange) {
|
|
1506
|
+
const lower = rule.minExclusive ? `> ${rule.min}` : `>= ${rule.min}`;
|
|
1507
|
+
throw new Error(
|
|
1508
|
+
`tiers.json: ${path}.${key} must be ${rule.integer ? "an integer" : "a number"} ${lower} and <= ${rule.max} (got ${describeRoutingValue(value, `${path}.${key}`)})`,
|
|
1509
|
+
);
|
|
1510
|
+
}
|
|
1511
|
+
return value;
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
function readBoolean(
|
|
1515
|
+
obj: Record<string, unknown>,
|
|
1516
|
+
key: string,
|
|
1517
|
+
path: string,
|
|
1518
|
+
): boolean | undefined {
|
|
1519
|
+
const value = obj[key];
|
|
1520
|
+
if (value === undefined) return undefined;
|
|
1521
|
+
if (typeof value !== "boolean") {
|
|
1522
|
+
throw new Error(`tiers.json: ${path}.${key} must be a boolean (got ${describeRoutingValue(value, `${path}.${key}`)})`);
|
|
1523
|
+
}
|
|
1524
|
+
return value;
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
/** A nested object block; `null` and arrays are refused (an override `null` would erase a block). */
|
|
1528
|
+
function readBlock(
|
|
1529
|
+
parent: Record<string, unknown>,
|
|
1530
|
+
key: string,
|
|
1531
|
+
path: string,
|
|
1532
|
+
): Record<string, unknown> | undefined {
|
|
1533
|
+
const value = parent[key];
|
|
1534
|
+
if (value === undefined) return undefined;
|
|
1535
|
+
if (!isPlainObject(value)) {
|
|
1536
|
+
throw new Error(`tiers.json: ${path}.${key} must be an object (got ${describeRoutingValue(value, `${path}.${key}`)})`);
|
|
1537
|
+
}
|
|
1538
|
+
rejectPrototypeKeys(value, `${path}.${key}`);
|
|
1539
|
+
return value;
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
/**
|
|
1543
|
+
* An absolute path, or `~` / `~/…` / `~\...` (the home directory; expanded by
|
|
1544
|
+
* resolveRouting). On Windows "absolute" means a drive letter (`C:\x`, `C:/x`) or
|
|
1545
|
+
* a UNC path (`\\server\share`): a rooted path without a drive (`\x`, `/x`) is
|
|
1546
|
+
* relative to the current drive and so to wherever the process happens to run
|
|
1547
|
+
* (QA-1.1-27).
|
|
1548
|
+
*/
|
|
1549
|
+
function isAbsoluteOrHomePath(value: string): boolean {
|
|
1550
|
+
if (value === "~" || /^~[\\/]/.test(value)) return true;
|
|
1551
|
+
if (!isAbsolute(value)) return false;
|
|
1552
|
+
return process.platform !== "win32" || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/])/.test(value);
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
/** `provider/model` or `provider/model#variant` (a catalog reference). */
|
|
1556
|
+
function isCatalogRef(value: unknown): value is string {
|
|
1557
|
+
if (typeof value !== "string") return false;
|
|
1558
|
+
const hash = value.indexOf("#");
|
|
1559
|
+
if (hash === -1) return parseModelRef(value) !== undefined;
|
|
1560
|
+
return VARIANT_ID_PATTERN.test(value.slice(hash + 1)) && parseModelRef(value.slice(0, hash)) !== undefined;
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
/** `model` / `backend` pair read from a classifier block or a per-preset override. */
|
|
1564
|
+
function readClassifierModel(obj: Record<string, unknown>, path: string): string | null | undefined {
|
|
1565
|
+
const model = obj.model;
|
|
1566
|
+
if (model === undefined || model === null) return model;
|
|
1567
|
+
if (!isCatalogRef(model)) {
|
|
1568
|
+
throw new Error(
|
|
1569
|
+
`tiers.json: ${path}.model must be null or a 'provider/model[#variant]' string (got ${describeRoutingValue(model, `${path}.model`)})`,
|
|
1570
|
+
);
|
|
1571
|
+
}
|
|
1572
|
+
return model;
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
function isHttpUrl(value: string): boolean {
|
|
1576
|
+
try {
|
|
1577
|
+
const protocol = new URL(value).protocol;
|
|
1578
|
+
return protocol === "http:" || protocol === "https:";
|
|
1579
|
+
} catch {
|
|
1580
|
+
return false;
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
/** D3: a backend other than `rules` needs a model; the HTTP backends also need a URL. */
|
|
1585
|
+
function assertClassifierUsable(
|
|
1586
|
+
path: string,
|
|
1587
|
+
backend: ClassifierBackend,
|
|
1588
|
+
model: string | null | undefined,
|
|
1589
|
+
baseUrl: string | null | undefined,
|
|
1590
|
+
modelKeys: string,
|
|
1591
|
+
): void {
|
|
1592
|
+
if (backend === "rules") return;
|
|
1593
|
+
if (typeof model !== "string" || model === "") {
|
|
1594
|
+
throw new Error(
|
|
1595
|
+
`tiers.json: ${modelKeys} must be a non-empty 'provider/model[#variant]' string when ${path}.backend is "${backend}" (the classifier is never picked automatically)`,
|
|
1596
|
+
);
|
|
1597
|
+
}
|
|
1598
|
+
if ((backend === "openai-compatible" || backend === "typesafe") && !baseUrl) {
|
|
1599
|
+
throw new Error(
|
|
1600
|
+
`tiers.json: routing.classifier.baseUrl must be an http(s) URL when ${path}.backend is "${backend}"`,
|
|
1601
|
+
);
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
function validateClassifier(routing: Record<string, unknown>): ClassifierConfig | undefined {
|
|
1606
|
+
const c = readBlock(routing, "classifier", "routing");
|
|
1607
|
+
if (c === undefined) return undefined;
|
|
1608
|
+
const path = "routing.classifier";
|
|
1609
|
+
const out: ClassifierConfig = {};
|
|
1610
|
+
|
|
1611
|
+
const backend = readEnum(c, "backend", path, CLASSIFIER_BACKENDS);
|
|
1612
|
+
if (backend !== undefined) out.backend = backend;
|
|
1613
|
+
|
|
1614
|
+
const model = readClassifierModel(c, path);
|
|
1615
|
+
if (model !== undefined) out.model = model;
|
|
1616
|
+
|
|
1617
|
+
const baseUrl = c.baseUrl;
|
|
1618
|
+
if (baseUrl !== undefined && baseUrl !== null) {
|
|
1619
|
+
if (typeof baseUrl !== "string" || !isHttpUrl(baseUrl)) {
|
|
1620
|
+
throw new Error(
|
|
1621
|
+
`tiers.json: ${path}.baseUrl must be null or an http(s) URL (value not shown)`,
|
|
1622
|
+
);
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
if (baseUrl !== undefined) out.baseUrl = baseUrl;
|
|
1626
|
+
|
|
1627
|
+
const apiKeyEnv = c.apiKeyEnv;
|
|
1628
|
+
if (apiKeyEnv !== undefined && apiKeyEnv !== null) {
|
|
1629
|
+
if (typeof apiKeyEnv !== "string" || !ENV_NAME_PATTERN.test(apiKeyEnv)) {
|
|
1630
|
+
throw new Error(
|
|
1631
|
+
`tiers.json: ${path}.apiKeyEnv must be null or an environment variable name (value not shown)`,
|
|
1632
|
+
);
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
if (apiKeyEnv !== undefined) out.apiKeyEnv = apiKeyEnv;
|
|
1636
|
+
|
|
1637
|
+
const timeoutMs = readNumber(c, "timeoutMs", path, { min: 100, max: 30_000, integer: true });
|
|
1638
|
+
if (timeoutMs !== undefined) out.timeoutMs = timeoutMs;
|
|
1639
|
+
|
|
1640
|
+
const samples = c.samples;
|
|
1641
|
+
if (samples !== undefined) {
|
|
1642
|
+
if (samples !== 1 && samples !== 3) {
|
|
1643
|
+
throw new Error(`tiers.json: ${path}.samples must be 1 or 3 (got ${describeRoutingValue(samples, `${path}.samples`)})`);
|
|
1644
|
+
}
|
|
1645
|
+
out.samples = samples;
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
const maxStateChars = readNumber(c, "maxStateChars", path, { min: 200, max: 20_000, integer: true });
|
|
1649
|
+
if (maxStateChars !== undefined) out.maxStateChars = maxStateChars;
|
|
1650
|
+
|
|
1651
|
+
const presets = readBlock(c, "presets", path);
|
|
1652
|
+
if (presets !== undefined) {
|
|
1653
|
+
const snapshot: Record<string, ClassifierPresetOverride> = {};
|
|
1654
|
+
for (const [presetName, entry] of Object.entries(presets)) {
|
|
1655
|
+
const entryPath = `${path}.presets.'${presetName}'`;
|
|
1656
|
+
if (!isPlainObject(entry)) {
|
|
1657
|
+
throw new Error(`tiers.json: ${entryPath} must be an object (got ${describeRoutingValue(entry, entryPath)})`);
|
|
1658
|
+
}
|
|
1659
|
+
rejectPrototypeKeys(entry, entryPath);
|
|
1660
|
+
const override: ClassifierPresetOverride = {};
|
|
1661
|
+
const entryBackend = readEnum(entry, "backend", entryPath, CLASSIFIER_BACKENDS);
|
|
1662
|
+
if (entryBackend !== undefined) override.backend = entryBackend;
|
|
1663
|
+
const entryModel = readClassifierModel(entry, entryPath);
|
|
1664
|
+
if (entryModel !== undefined) override.model = entryModel;
|
|
1665
|
+
snapshot[presetName] = override;
|
|
1666
|
+
}
|
|
1667
|
+
out.presets = snapshot;
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
// The top level and every per-preset override must each resolve to a usable
|
|
1671
|
+
// classifier, whichever layer supplied which key.
|
|
1672
|
+
const effectiveBackend = out.backend ?? "rules";
|
|
1673
|
+
assertClassifierUsable(path, effectiveBackend, out.model, out.baseUrl, `${path}.model`);
|
|
1674
|
+
for (const [presetName, override] of Object.entries(out.presets ?? {})) {
|
|
1675
|
+
const entryPath = `${path}.presets.'${presetName}'`;
|
|
1676
|
+
assertClassifierUsable(
|
|
1677
|
+
entryPath,
|
|
1678
|
+
override.backend ?? effectiveBackend,
|
|
1679
|
+
override.model !== undefined ? override.model : out.model,
|
|
1680
|
+
out.baseUrl,
|
|
1681
|
+
`${path}.model or ${entryPath}.model`,
|
|
1682
|
+
);
|
|
1683
|
+
}
|
|
1684
|
+
return out;
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
function validateRoles(routing: Record<string, unknown>): Record<string, string[]> | undefined {
|
|
1688
|
+
const roles = readBlock(routing, "roles", "routing");
|
|
1689
|
+
if (roles === undefined) return undefined;
|
|
1690
|
+
const out: Record<string, string[]> = {};
|
|
1691
|
+
for (const [taskClass, agents] of Object.entries(roles)) {
|
|
1692
|
+
if (!pickEnum(ROUTING_TASK_CLASSES, taskClass)) {
|
|
1693
|
+
throw new Error(
|
|
1694
|
+
`tiers.json: routing.roles class '${taskClass}' must be one of ${ROUTING_TASK_CLASSES.join("|")}`,
|
|
1695
|
+
);
|
|
1696
|
+
}
|
|
1697
|
+
// An empty list is allowed: it means "no native candidates for this class"
|
|
1698
|
+
// (a deliberate deviation from "non-empty arrays", QA-1.1-7).
|
|
1699
|
+
if (!Array.isArray(agents)) {
|
|
1700
|
+
throw new Error(
|
|
1701
|
+
`tiers.json: routing.roles.'${taskClass}' must be an array of agent ids (got ${describeValue(agents)})`,
|
|
1702
|
+
);
|
|
1703
|
+
}
|
|
1704
|
+
const ids: string[] = [];
|
|
1705
|
+
for (const agent of agents as unknown[]) {
|
|
1706
|
+
if (typeof agent !== "string" || !isAgentId(agent)) {
|
|
1707
|
+
throw new Error(
|
|
1708
|
+
`tiers.json: routing.roles.'${taskClass}' entries must be agent ids matching ${AGENT_ID_PATTERN.source}, without '.' or '..' segments and not ending in '/' or '.' (got ${describeValue(agent)})`,
|
|
1709
|
+
);
|
|
1710
|
+
}
|
|
1711
|
+
ids.push(agent);
|
|
1712
|
+
}
|
|
1713
|
+
out[taskClass] = ids;
|
|
1714
|
+
}
|
|
1715
|
+
return out;
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
/**
|
|
1719
|
+
* Validate `routing` and return a snapshot of the validated values (or
|
|
1720
|
+
* `undefined` when absent). Defaults are NOT applied here; see resolveRouting.
|
|
1721
|
+
*/
|
|
1722
|
+
function validateRouting(value: unknown): RoutingConfig | undefined {
|
|
1723
|
+
if (value === undefined) return undefined;
|
|
1724
|
+
if (!isPlainObject(value)) {
|
|
1725
|
+
throw new Error(`tiers.json: 'routing' must be an object (got ${describeRoutingValue(value, "routing")})`);
|
|
1726
|
+
}
|
|
1727
|
+
rejectPrototypeKeys(value, "routing");
|
|
1728
|
+
const routing = value;
|
|
1729
|
+
const out: RoutingConfig = {};
|
|
1730
|
+
|
|
1731
|
+
const engine = readEnum(routing, "engine", "routing", ROUTING_ENGINES);
|
|
1732
|
+
if (engine !== undefined) out.engine = engine;
|
|
1733
|
+
const profile = readEnum(routing, "profile", "routing", ROUTING_PROFILES);
|
|
1734
|
+
if (profile !== undefined) out.profile = profile;
|
|
1735
|
+
const margin = readNumber(routing, "margin", "routing", { min: 0, max: 0.9 });
|
|
1736
|
+
if (margin !== undefined) out.margin = margin;
|
|
1737
|
+
const minClassConfidence = readNumber(routing, "minClassConfidence", "routing", { min: 0, max: 1 });
|
|
1738
|
+
if (minClassConfidence !== undefined) out.minClassConfidence = minClassConfidence;
|
|
1739
|
+
|
|
1740
|
+
const detection = readBlock(routing, "detection", "routing");
|
|
1741
|
+
if (detection !== undefined) {
|
|
1742
|
+
const d: DetectionConfig = {};
|
|
1743
|
+
for (const key of ["deterministic", "grader", "none"] as const) {
|
|
1744
|
+
const v = readNumber(detection, key, "routing.detection", { min: 0, max: 1 });
|
|
1745
|
+
if (v !== undefined) d[key] = v;
|
|
1746
|
+
}
|
|
1747
|
+
// A deeper check cannot catch less than a shallower one (QA-1.1-13); compared
|
|
1748
|
+
// on the effective values, so one key can break the order against a default.
|
|
1749
|
+
const dd = ROUTING_DEFAULTS.detection;
|
|
1750
|
+
const effective = {
|
|
1751
|
+
deterministic: d.deterministic ?? dd.deterministic,
|
|
1752
|
+
grader: d.grader ?? dd.grader,
|
|
1753
|
+
none: d.none ?? dd.none,
|
|
1754
|
+
};
|
|
1755
|
+
if (!(effective.deterministic >= effective.grader && effective.grader >= effective.none)) {
|
|
1756
|
+
throw new Error(
|
|
1757
|
+
`tiers.json: routing.detection must satisfy deterministic >= grader >= none, because a deeper check cannot catch less than a shallower one (got deterministic ${effective.deterministic}, grader ${effective.grader}, none ${effective.none})`,
|
|
1758
|
+
);
|
|
1759
|
+
}
|
|
1760
|
+
out.detection = d;
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
const classifier = validateClassifier(routing);
|
|
1764
|
+
if (classifier !== undefined) out.classifier = classifier;
|
|
1765
|
+
const roles = validateRoles(routing);
|
|
1766
|
+
if (roles !== undefined) out.roles = roles;
|
|
1767
|
+
|
|
1768
|
+
const outcomes = readBlock(routing, "outcomes", "routing");
|
|
1769
|
+
if (outcomes !== undefined) {
|
|
1770
|
+
const o: OutcomesConfig = {};
|
|
1771
|
+
const path = outcomes.path;
|
|
1772
|
+
if (path !== undefined) {
|
|
1773
|
+
if (path !== null && (typeof path !== "string" || !isAbsoluteOrHomePath(path))) {
|
|
1774
|
+
throw new Error(
|
|
1775
|
+
`tiers.json: routing.outcomes.path must be null or an absolute path; a leading ~ means the home directory (got ${describeValue(path)})`,
|
|
1776
|
+
);
|
|
1777
|
+
}
|
|
1778
|
+
o.path = path;
|
|
1779
|
+
}
|
|
1780
|
+
const halfLifeDays = readNumber(outcomes, "halfLifeDays", "routing.outcomes", { min: 1, max: 365 });
|
|
1781
|
+
if (halfLifeDays !== undefined) o.halfLifeDays = halfLifeDays;
|
|
1782
|
+
const maxEffectiveSamples = readNumber(outcomes, "maxEffectiveSamples", "routing.outcomes", {
|
|
1783
|
+
min: 5,
|
|
1784
|
+
max: 1000,
|
|
1785
|
+
});
|
|
1786
|
+
if (maxEffectiveSamples !== undefined) o.maxEffectiveSamples = maxEffectiveSamples;
|
|
1787
|
+
out.outcomes = o;
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
const sessionReuse = readBlock(routing, "sessionReuse", "routing");
|
|
1791
|
+
if (sessionReuse !== undefined) {
|
|
1792
|
+
const s: SessionReuseConfig = {};
|
|
1793
|
+
const maxContextFraction = readNumber(sessionReuse, "maxContextFraction", "routing.sessionReuse", {
|
|
1794
|
+
min: 0,
|
|
1795
|
+
max: 0.95,
|
|
1796
|
+
minExclusive: true,
|
|
1797
|
+
});
|
|
1798
|
+
if (maxContextFraction !== undefined) s.maxContextFraction = maxContextFraction;
|
|
1799
|
+
out.sessionReuse = s;
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
const advisor = readBlock(routing, "advisor", "routing");
|
|
1803
|
+
if (advisor !== undefined) {
|
|
1804
|
+
const a: AdvisorConfig = {};
|
|
1805
|
+
const enabled = readBoolean(advisor, "enabled", "routing.advisor");
|
|
1806
|
+
if (enabled !== undefined) a.enabled = enabled;
|
|
1807
|
+
const notify = readBoolean(advisor, "notify", "routing.advisor");
|
|
1808
|
+
if (notify !== undefined) a.notify = notify;
|
|
1809
|
+
const noticeIntervalHours = readNumber(advisor, "noticeIntervalHours", "routing.advisor", {
|
|
1810
|
+
min: 1,
|
|
1811
|
+
max: 720,
|
|
1812
|
+
});
|
|
1813
|
+
if (noticeIntervalHours !== undefined) a.noticeIntervalHours = noticeIntervalHours;
|
|
1814
|
+
out.advisor = a;
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
return out;
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
/** A `candidates` entry after validation (every key optional, see {@link TierCandidate}). */
|
|
1821
|
+
type CandidateSpec = TierCandidate;
|
|
1822
|
+
|
|
1823
|
+
/** The identity of a rung: its model and variant (an omitted variant is the default variant). */
|
|
1824
|
+
function rungKey(model: string, variant: string | undefined): string {
|
|
1825
|
+
return `${model}\u0000${variant ?? ""}`;
|
|
1826
|
+
}
|
|
1827
|
+
|
|
1828
|
+
/** A tier's own costRatio: the one it states, else the conventional default of its name. */
|
|
1829
|
+
function tierCostRatioOf(tierName: string, costRatio: unknown): number {
|
|
1830
|
+
return typeof costRatio === "number" && Number.isFinite(costRatio) && costRatio > 0
|
|
1831
|
+
? costRatio
|
|
1832
|
+
: tierDefaultsFor(tierName).costRatio;
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
/**
|
|
1836
|
+
* Why a non-empty `candidates` list cannot be used next to the tier's own rung,
|
|
1837
|
+
* or `undefined` when it can (QA-1.1-3, made non-fatal by QA-1.1-25):
|
|
1838
|
+
*
|
|
1839
|
+
* - it must contain the tier's own effective `(model, variant)`: the static choice
|
|
1840
|
+
* has to be one of the rungs, or the engine's degenerate case (D2) would have
|
|
1841
|
+
* nothing to start from;
|
|
1842
|
+
* - that rung's `costRatio` is the tier's own, so it must equal it or be omitted.
|
|
1843
|
+
*
|
|
1844
|
+
* It is a *problem*, not a validation error: a plugin update that changes a
|
|
1845
|
+
* bundled tier's variant would otherwise make a user's override file invalid and
|
|
1846
|
+
* drop the whole layer. The list is ignored instead (the ladder is the tier's own
|
|
1847
|
+
* rung) and the reason is noticed at load.
|
|
1848
|
+
*/
|
|
1849
|
+
function ownRungProblem(
|
|
1850
|
+
tierModel: string,
|
|
1851
|
+
tierVariant: string | undefined,
|
|
1852
|
+
tierCostRatio: number,
|
|
1853
|
+
candidates: readonly CandidateSpec[],
|
|
1854
|
+
): string | undefined {
|
|
1855
|
+
// `candidates` is non-empty: both callers check, an empty list means "none".
|
|
1856
|
+
const ownKey = rungKey(tierModel, tierVariant);
|
|
1857
|
+
const index = candidates.findIndex((c) => rungKey(c.model ?? tierModel, c.variant) === ownKey);
|
|
1858
|
+
if (index === -1) {
|
|
1859
|
+
return `it does not contain the tier's own rung (model ${tierModel}, variant ${tierVariant ?? "default"})`;
|
|
1860
|
+
}
|
|
1861
|
+
const declared = candidates[index]!.costRatio;
|
|
1862
|
+
if (declared !== undefined && declared !== tierCostRatio) {
|
|
1863
|
+
return `its own rung (candidates[${index}]) has costRatio ${declared}, not the tier's ${tierCostRatio}`;
|
|
1864
|
+
}
|
|
1865
|
+
return undefined;
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1868
|
+
/**
|
|
1869
|
+
* `tiers.<t>.candidates`: ordered rungs of a tier's ladder, in escalation order.
|
|
1870
|
+
* Throws for anything malformed; returns the validated entries.
|
|
1871
|
+
*
|
|
1872
|
+
* - `model` falls back to the tier's own; an omitted `variant` is the model's
|
|
1873
|
+
* default variant; an omitted `costRatio` is the tier's.
|
|
1874
|
+
* - No two rungs may name the same effective `(model, variant)`.
|
|
1875
|
+
* - Effective `costRatio` must not decrease along the list (QA-1.1-12): the list
|
|
1876
|
+
* is walked upward on failure, and a cheaper later rung is not an escalation.
|
|
1877
|
+
*
|
|
1878
|
+
* The own-rung rules are NOT enforced here: see {@link ownRungProblem}.
|
|
1879
|
+
*/
|
|
1880
|
+
function validateTierCandidates(
|
|
1881
|
+
tier: Record<string, unknown>,
|
|
1882
|
+
label: string,
|
|
1883
|
+
tierName: string,
|
|
1884
|
+
): CandidateSpec[] | undefined {
|
|
1885
|
+
const candidates = tier.candidates;
|
|
1886
|
+
if (candidates === undefined) return undefined;
|
|
1887
|
+
if (!Array.isArray(candidates)) {
|
|
1888
|
+
throw new Error(`tiers.json: '${label}.candidates' must be an array`);
|
|
1889
|
+
}
|
|
1890
|
+
const seen = new Map<string, number>();
|
|
1891
|
+
const tierCostRatio = tierCostRatioOf(tierName, tier.costRatio);
|
|
1892
|
+
const specs: CandidateSpec[] = [];
|
|
1893
|
+
const effectiveCosts: number[] = [];
|
|
1894
|
+
for (let i = 0; i < candidates.length; i++) {
|
|
1895
|
+
const entry: unknown = candidates[i];
|
|
1896
|
+
const where = `${label}.candidates[${i}]`;
|
|
1897
|
+
if (!isPlainObject(entry)) {
|
|
1898
|
+
throw new Error(`tiers.json: '${where}' must be an object`);
|
|
1899
|
+
}
|
|
1900
|
+
rejectPrototypeKeys(entry, `${label}.candidates[${i}]`);
|
|
1901
|
+
const model = entry.model;
|
|
1902
|
+
if (model !== undefined && (typeof model !== "string" || !parseModelRef(model))) {
|
|
1903
|
+
throw new Error(
|
|
1904
|
+
`tiers.json: '${where}.model' must be 'provider/model' (got ${describeValue(model)})`,
|
|
1905
|
+
);
|
|
1906
|
+
}
|
|
1907
|
+
const variant = entry.variant;
|
|
1908
|
+
if (variant !== undefined && (typeof variant !== "string" || !VARIANT_ID_PATTERN.test(variant))) {
|
|
1909
|
+
throw new Error(
|
|
1910
|
+
`tiers.json: '${where}.variant' must be a non-empty string without whitespace or '#' (got ${describeValue(variant)})`,
|
|
1911
|
+
);
|
|
1912
|
+
}
|
|
1913
|
+
const costRatio = entry.costRatio;
|
|
1914
|
+
if (
|
|
1915
|
+
costRatio !== undefined &&
|
|
1916
|
+
(typeof costRatio !== "number" || !Number.isFinite(costRatio) || costRatio <= 0)
|
|
1917
|
+
) {
|
|
1918
|
+
throw new Error(
|
|
1919
|
+
`tiers.json: '${where}.costRatio' must be a number > 0 (got ${describeValue(costRatio)})`,
|
|
1920
|
+
);
|
|
1921
|
+
}
|
|
1922
|
+
const effectiveModel = typeof model === "string" ? model : String(tier.model);
|
|
1923
|
+
const key = rungKey(effectiveModel, typeof variant === "string" ? variant : undefined);
|
|
1924
|
+
const first = seen.get(key);
|
|
1925
|
+
if (first !== undefined) {
|
|
1926
|
+
throw new Error(
|
|
1927
|
+
`tiers.json: '${where}' repeats (model, variant) = (${effectiveModel}, ${typeof variant === "string" ? variant : "default"}) of candidates[${first}]`,
|
|
1928
|
+
);
|
|
1929
|
+
}
|
|
1930
|
+
seen.set(key, i);
|
|
1931
|
+
const spec: CandidateSpec = {};
|
|
1932
|
+
if (typeof model === "string") spec.model = model;
|
|
1933
|
+
if (typeof variant === "string") spec.variant = variant;
|
|
1934
|
+
if (typeof costRatio === "number") spec.costRatio = costRatio;
|
|
1935
|
+
specs.push(spec);
|
|
1936
|
+
effectiveCosts.push(spec.costRatio ?? tierCostRatio);
|
|
1937
|
+
}
|
|
1938
|
+
for (let i = 1; i < effectiveCosts.length; i++) {
|
|
1939
|
+
if (effectiveCosts[i]! < effectiveCosts[i - 1]!) {
|
|
1940
|
+
throw new Error(
|
|
1941
|
+
`tiers.json: '${label}.candidates[${i}]' has costRatio ${effectiveCosts[i]}, lower than candidates[${i - 1}] (${effectiveCosts[i - 1]}): candidates are listed in escalation order, so costRatio must not decrease`,
|
|
1942
|
+
);
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
return specs;
|
|
1946
|
+
}
|
|
1947
|
+
|
|
1948
|
+
/** One rung of a tier as the validator sees it, for the per-preset costRatio check. */
|
|
1949
|
+
interface PresetRung {
|
|
1950
|
+
model: string;
|
|
1951
|
+
variant: string | undefined;
|
|
1952
|
+
costRatio: number;
|
|
1953
|
+
/** Where it was written, for the error message. */
|
|
1954
|
+
source: string;
|
|
1955
|
+
/** True for a rung of an explicit `candidates` list (the tier's own implicit rung is not). */
|
|
1956
|
+
explicit: boolean;
|
|
1957
|
+
}
|
|
1958
|
+
|
|
1959
|
+
/**
|
|
1960
|
+
* Within one preset a `(model, variant)` has ONE costRatio (QA-1.1-26): the
|
|
1961
|
+
* engine prices a candidate by that pair, so two tiers (or a tier and a
|
|
1962
|
+
* candidate list) quoting different ratios for the same pair would make the
|
|
1963
|
+
* choice depend on which tier asked. Only pairs involving an explicit
|
|
1964
|
+
* `candidates` entry are checked: several bundled tiers legitimately share one
|
|
1965
|
+
* model at different effort levels and ratios, and say nothing about variants.
|
|
1966
|
+
*/
|
|
1967
|
+
function assertConsistentRungCosts(presetName: string, rungs: readonly PresetRung[]): void {
|
|
1968
|
+
const first = new Map<string, PresetRung>();
|
|
1969
|
+
for (const rung of rungs) {
|
|
1970
|
+
const key = rungKey(rung.model, rung.variant);
|
|
1971
|
+
const prior = first.get(key);
|
|
1972
|
+
if (prior === undefined) {
|
|
1973
|
+
first.set(key, rung);
|
|
1974
|
+
} else if (prior.costRatio !== rung.costRatio && (prior.explicit || rung.explicit)) {
|
|
1975
|
+
throw new Error(
|
|
1976
|
+
`tiers.json: preset '${presetName}': (model, variant) = (${rung.model}, ${rung.variant ?? "default"}) has costRatio ${rung.costRatio} in '${rung.source}' but ${prior.costRatio} in '${prior.source}'; within a preset one (model, variant) has one costRatio`,
|
|
1977
|
+
);
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
/** True when the tier lists at least one explicit candidate (an empty list counts as none). */
|
|
1982
|
+
export function hasExplicitCandidates(tier: TierConfig): boolean {
|
|
1983
|
+
return Array.isArray(tier.candidates) && tier.candidates.length > 0;
|
|
1984
|
+
}
|
|
1985
|
+
|
|
1986
|
+
/**
|
|
1987
|
+
* Why the tier's `candidates` are ignored (the ladder is then the tier's own
|
|
1988
|
+
* rung), or `undefined` when they are used or there are none (QA-1.1-25):
|
|
1989
|
+
* the list lacks the tier's own `(model, variant)`, or states another
|
|
1990
|
+
* `costRatio` for it. Loading reports it as a config notice.
|
|
1991
|
+
*/
|
|
1992
|
+
export function candidatesProblem(tierName: string, tier: TierConfig): string | undefined {
|
|
1993
|
+
const listed = tier.candidates;
|
|
1994
|
+
if (listed === undefined || listed.length === 0) return undefined;
|
|
1995
|
+
return ownRungProblem(tier.model, tier.variant, tierCostRatioOf(tierName, tier.costRatio), listed);
|
|
1996
|
+
}
|
|
1997
|
+
|
|
1226
1998
|
/**
|
|
1227
1999
|
* Validate a raw parsed config. Strict and throwing by design: the bundled
|
|
1228
2000
|
* tiers.json must be valid on its own, and loadConfig turns a throw from an
|
|
@@ -1261,9 +2033,10 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
1261
2033
|
validateDispatchHeader(obj);
|
|
1262
2034
|
validateTaskPromptRepair(obj);
|
|
1263
2035
|
validateFalseRefusalDetection(obj);
|
|
2036
|
+
const routing = validateRouting(obj.routing);
|
|
1264
2037
|
|
|
1265
2038
|
const cfg = raw as RouterConfig;
|
|
1266
|
-
return withValidatedSnapshots(cfg, { enforcement });
|
|
2039
|
+
return withValidatedSnapshots(cfg, { enforcement, routing });
|
|
1267
2040
|
}
|
|
1268
2041
|
|
|
1269
2042
|
/**
|
|
@@ -1360,21 +2133,118 @@ interface SourceFailure {
|
|
|
1360
2133
|
export interface OverrideLayer {
|
|
1361
2134
|
path: string;
|
|
1362
2135
|
data: Record<string, unknown>;
|
|
2136
|
+
project?: boolean;
|
|
1363
2137
|
}
|
|
1364
2138
|
|
|
1365
|
-
|
|
2139
|
+
/**
|
|
2140
|
+
* `routing` keys that decide where task text is sent or where outcome data is
|
|
2141
|
+
* written. A repository-controlled file must not be able to set them (A18,
|
|
2142
|
+
* QA-1.1-2): cloning a project would otherwise let its author point the
|
|
2143
|
+
* classifier at their own server. Only the global override may.
|
|
2144
|
+
*/
|
|
2145
|
+
const GLOBAL_ONLY_ROUTING_KEYS: ReadonlyArray<readonly [block: string, key: string]> = [
|
|
2146
|
+
["classifier", "backend"],
|
|
2147
|
+
["classifier", "model"],
|
|
2148
|
+
["classifier", "baseUrl"],
|
|
2149
|
+
["classifier", "apiKeyEnv"],
|
|
2150
|
+
["classifier", "presets"],
|
|
2151
|
+
["outcomes", "path"],
|
|
2152
|
+
];
|
|
2153
|
+
|
|
2154
|
+
/** Remove the global-only `routing` keys from a project layer; returns what was dropped. */
|
|
2155
|
+
function stripGlobalOnlyRoutingKeys(data: Record<string, unknown>): string[] {
|
|
2156
|
+
const routing = data.routing;
|
|
2157
|
+
if (!isPlainObject(routing)) return [];
|
|
2158
|
+
const dropped: string[] = [];
|
|
2159
|
+
const touched = new Set<string>();
|
|
2160
|
+
for (const [block, key] of GLOBAL_ONLY_ROUTING_KEYS) {
|
|
2161
|
+
const target = routing[block];
|
|
2162
|
+
if (isPlainObject(target) && Object.hasOwn(target, key)) {
|
|
2163
|
+
delete target[key];
|
|
2164
|
+
dropped.push(`routing.${block}.${key}`);
|
|
2165
|
+
touched.add(block);
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
// A block that stripping left empty goes too, and so does an emptied `routing`:
|
|
2169
|
+
// any `routing` block, however empty, changes behaviour (variantSteps defaults
|
|
2170
|
+
// to `auto` under one, A15), and the project file must not do that by accident.
|
|
2171
|
+
for (const block of touched) {
|
|
2172
|
+
const target = routing[block];
|
|
2173
|
+
if (isPlainObject(target) && Object.keys(target).length === 0) delete routing[block];
|
|
2174
|
+
}
|
|
2175
|
+
if (dropped.length > 0 && Object.keys(routing).length === 0) delete data.routing;
|
|
2176
|
+
return dropped;
|
|
2177
|
+
}
|
|
2178
|
+
|
|
2179
|
+
function collectOverrideLayers(
|
|
2180
|
+
dir: string,
|
|
2181
|
+
failures?: SourceFailure[],
|
|
2182
|
+
notices?: ConfigNotice[],
|
|
2183
|
+
): OverrideLayer[] {
|
|
1366
2184
|
const layers: OverrideLayer[] = [];
|
|
1367
2185
|
// Lowest priority first: global, then project-local (found by upward search
|
|
1368
2186
|
// from the project directory).
|
|
1369
|
-
const
|
|
1370
|
-
|
|
2187
|
+
const sources = [
|
|
2188
|
+
{ path: overridePath(), project: false },
|
|
2189
|
+
{ path: walkForProjectOverride(dir), project: true },
|
|
2190
|
+
];
|
|
2191
|
+
for (const { path: p, project } of sources) {
|
|
1371
2192
|
if (!p) continue;
|
|
1372
2193
|
const data = readOverridesAt(p, failures);
|
|
1373
|
-
if (data)
|
|
2194
|
+
if (!data) continue;
|
|
2195
|
+
if (project) {
|
|
2196
|
+
const dropped = stripGlobalOnlyRoutingKeys(data);
|
|
2197
|
+
if (dropped.length > 0) {
|
|
2198
|
+
notices?.push({
|
|
2199
|
+
source: p,
|
|
2200
|
+
message: `ignoring ${dropped.join(", ")} from ${p}: only the global override may set it`,
|
|
2201
|
+
});
|
|
2202
|
+
}
|
|
2203
|
+
}
|
|
2204
|
+
layers.push({ path: p, data, project });
|
|
1374
2205
|
}
|
|
1375
2206
|
return layers;
|
|
1376
2207
|
}
|
|
1377
2208
|
|
|
2209
|
+
/** The notices of the build that produced each config object (the cache hands the same object back until a reload). */
|
|
2210
|
+
const noticesByConfig = new WeakMap<RouterConfig, readonly ConfigNotice[]>();
|
|
2211
|
+
|
|
2212
|
+
/** Notice texts already logged in this process (bounded); see {@link warnConfigNotices}. */
|
|
2213
|
+
const loggedNoticeTexts = new Set<string>();
|
|
2214
|
+
|
|
2215
|
+
/**
|
|
2216
|
+
* Log, through the plugin logger, each notice of `cfg` whose text has not been
|
|
2217
|
+
* logged yet in this process (QA-1.1-23). `config.ts` itself never writes
|
|
2218
|
+
* notices to the console: `console.warn` from a plugin paints over the TUI, and
|
|
2219
|
+
* keying on the config fingerprint made a state-file write (`/preset`,
|
|
2220
|
+
* `/budget`) re-log a typo that had not changed. The dedupe key is the text,
|
|
2221
|
+
* which already names the file or the keys concerned.
|
|
2222
|
+
*/
|
|
2223
|
+
export function warnConfigNotices(
|
|
2224
|
+
cfg: RouterConfig | undefined,
|
|
2225
|
+
logger: Pick<PluginLogger, "warn">,
|
|
2226
|
+
): void {
|
|
2227
|
+
if (cfg === undefined) return;
|
|
2228
|
+
for (const notice of noticesByConfig.get(cfg) ?? []) {
|
|
2229
|
+
if (loggedNoticeTexts.has(notice.message)) continue;
|
|
2230
|
+
if (loggedNoticeTexts.size >= 256) loggedNoticeTexts.clear();
|
|
2231
|
+
loggedNoticeTexts.add(notice.message);
|
|
2232
|
+
logger.warn(notice.message, notice.source === undefined ? undefined : { source: notice.source });
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
|
|
2236
|
+
/**
|
|
2237
|
+
* What to log after every `loadConfig()`: the once-per-process deprecation
|
|
2238
|
+
* warning and any new config notices, both through the plugin logger.
|
|
2239
|
+
*/
|
|
2240
|
+
export function warnConfigIssues(
|
|
2241
|
+
cfg: RouterConfig | undefined,
|
|
2242
|
+
logger: PluginLogger,
|
|
2243
|
+
): void {
|
|
2244
|
+
warnDeprecatedVerifyKeys(cfg, logger);
|
|
2245
|
+
warnConfigNotices(cfg, logger);
|
|
2246
|
+
}
|
|
2247
|
+
|
|
1378
2248
|
/**
|
|
1379
2249
|
* Canonical per-tier defaults, keyed by the conventional tier names. These are
|
|
1380
2250
|
* the same values every bundled preset uses, so a preset defined in an overrides
|
|
@@ -1387,6 +2257,11 @@ const TIER_DEFAULTS: Record<string, { costRatio: number; steps: number }> = {
|
|
|
1387
2257
|
};
|
|
1388
2258
|
const FALLBACK_TIER_DEFAULTS = { costRatio: 1, steps: 50 };
|
|
1389
2259
|
|
|
2260
|
+
/** Defaults of a tier by name; own keys only, so `constructor` or `toString` are not tiers (QA-1.1-19). */
|
|
2261
|
+
function tierDefaultsFor(tierName: string): { costRatio: number; steps: number } {
|
|
2262
|
+
return Object.hasOwn(TIER_DEFAULTS, tierName) ? TIER_DEFAULTS[tierName]! : FALLBACK_TIER_DEFAULTS;
|
|
2263
|
+
}
|
|
2264
|
+
|
|
1390
2265
|
/**
|
|
1391
2266
|
* Fill in `costRatio`/`steps` for any tier that omits them, by tier name. Runs
|
|
1392
2267
|
* after merge so override-defined presets behave well without restating the
|
|
@@ -1396,7 +2271,7 @@ const FALLBACK_TIER_DEFAULTS = { costRatio: 1, steps: 50 };
|
|
|
1396
2271
|
function applyTierDefaults(cfg: RouterConfig): void {
|
|
1397
2272
|
for (const preset of Object.values(cfg.presets)) {
|
|
1398
2273
|
for (const [tierName, tier] of Object.entries(preset)) {
|
|
1399
|
-
const d =
|
|
2274
|
+
const d = tierDefaultsFor(tierName);
|
|
1400
2275
|
if (tier.costRatio === undefined) tier.costRatio = d.costRatio;
|
|
1401
2276
|
if (tier.steps === undefined) tier.steps = d.steps;
|
|
1402
2277
|
}
|
|
@@ -1458,9 +2333,10 @@ export function loadConfig(dir?: string): RouterConfig {
|
|
|
1458
2333
|
entry.config !== null && sourceKey === entry.sourceKey ? entry.config : null;
|
|
1459
2334
|
|
|
1460
2335
|
const failures: SourceFailure[] = [];
|
|
2336
|
+
const notices: ConfigNotice[] = [];
|
|
1461
2337
|
let cfg: RouterConfig;
|
|
1462
2338
|
try {
|
|
1463
|
-
cfg = buildConfig(projectDir, failures);
|
|
2339
|
+
cfg = buildConfig(projectDir, failures, notices);
|
|
1464
2340
|
} catch (err) {
|
|
1465
2341
|
// First load: unchanged behaviour — throw. Reload: keep the last good one.
|
|
1466
2342
|
if (!previous) throw err;
|
|
@@ -1494,6 +2370,8 @@ export function loadConfig(dir?: string): RouterConfig {
|
|
|
1494
2370
|
entry.dirty = false;
|
|
1495
2371
|
entry.reloadError = null;
|
|
1496
2372
|
entry.warnedFingerprint = null;
|
|
2373
|
+
entry.notices = notices;
|
|
2374
|
+
noticesByConfig.set(cfg, notices);
|
|
1497
2375
|
return cfg;
|
|
1498
2376
|
}
|
|
1499
2377
|
|
|
@@ -1521,25 +2399,180 @@ function keepLastValidConfig(
|
|
|
1521
2399
|
return previous;
|
|
1522
2400
|
}
|
|
1523
2401
|
|
|
2402
|
+
/** Keys each `routing` block understands; anything else is ignored (and noticed). */
|
|
2403
|
+
const ROUTING_KNOWN_KEYS: Readonly<Record<string, readonly string[]>> = {
|
|
2404
|
+
routing: [
|
|
2405
|
+
"engine",
|
|
2406
|
+
"profile",
|
|
2407
|
+
"margin",
|
|
2408
|
+
"minClassConfidence",
|
|
2409
|
+
"detection",
|
|
2410
|
+
"classifier",
|
|
2411
|
+
"roles",
|
|
2412
|
+
"outcomes",
|
|
2413
|
+
"sessionReuse",
|
|
2414
|
+
"advisor",
|
|
2415
|
+
],
|
|
2416
|
+
detection: ["deterministic", "grader", "none"],
|
|
2417
|
+
classifier: ["backend", "model", "baseUrl", "apiKeyEnv", "timeoutMs", "samples", "maxStateChars", "presets"],
|
|
2418
|
+
preset: ["backend", "model"],
|
|
2419
|
+
outcomes: ["path", "halfLifeDays", "maxEffectiveSamples"],
|
|
2420
|
+
sessionReuse: ["maxContextFraction"],
|
|
2421
|
+
advisor: ["enabled", "noticeIntervalHours", "notify"],
|
|
2422
|
+
};
|
|
2423
|
+
|
|
2424
|
+
/**
|
|
2425
|
+
* Paths of the keys inside a raw `routing` block that nothing reads
|
|
2426
|
+
* (`routing.margn`, `routing.classifier.bakend`, …). Validation ignores them, as
|
|
2427
|
+
* it does everywhere in this file; this makes the typo visible (QA-1.1-10).
|
|
2428
|
+
*/
|
|
2429
|
+
export function findUnknownRoutingKeys(routing: unknown): string[] {
|
|
2430
|
+
if (!isPlainObject(routing)) return [];
|
|
2431
|
+
const unknown: string[] = [];
|
|
2432
|
+
const check = (obj: Record<string, unknown>, known: readonly string[], path: string): void => {
|
|
2433
|
+
for (const key of Object.keys(obj)) {
|
|
2434
|
+
if (!known.includes(key)) unknown.push(`${path}.${key}`);
|
|
2435
|
+
}
|
|
2436
|
+
};
|
|
2437
|
+
check(routing, ROUTING_KNOWN_KEYS.routing!, "routing");
|
|
2438
|
+
for (const block of ["detection", "classifier", "outcomes", "sessionReuse", "advisor"] as const) {
|
|
2439
|
+
const value = routing[block];
|
|
2440
|
+
if (isPlainObject(value)) check(value, ROUTING_KNOWN_KEYS[block]!, `routing.${block}`);
|
|
2441
|
+
}
|
|
2442
|
+
const classifier = routing.classifier;
|
|
2443
|
+
const presets = isPlainObject(classifier) ? classifier.presets : undefined;
|
|
2444
|
+
if (isPlainObject(presets)) {
|
|
2445
|
+
for (const [name, entry] of Object.entries(presets)) {
|
|
2446
|
+
if (isPlainObject(entry)) check(entry, ROUTING_KNOWN_KEYS.preset!, `routing.classifier.presets.${name}`);
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
return unknown;
|
|
2450
|
+
}
|
|
2451
|
+
|
|
2452
|
+
/**
|
|
2453
|
+
* OpenCode's built-in primary and internal agents. None of them can be a
|
|
2454
|
+
* subagent candidate, so `routing.roles` naming one is useless (QA-1.1-18); it is
|
|
2455
|
+
* accepted (the host's agent set is not known at load) but noticed, and the
|
|
2456
|
+
* engine must skip it.
|
|
2457
|
+
*/
|
|
2458
|
+
export const ROUTING_RESERVED_AGENTS = ["build", "plan", "title", "summary", "compaction"] as const;
|
|
2459
|
+
|
|
2460
|
+
/**
|
|
2461
|
+
* Findings about a routing block that loaded fine but probably is not what the
|
|
2462
|
+
* author meant: unknown keys, `roles` naming reserved agents, per-preset
|
|
2463
|
+
* classifier overrides naming no preset. `rawRouting` is the merged block as
|
|
2464
|
+
* written (validation drops unknown keys from the snapshot); `cfg` is the
|
|
2465
|
+
* validated config.
|
|
2466
|
+
*/
|
|
2467
|
+
export function collectRoutingNotices(rawRouting: unknown, cfg: RouterConfig): string[] {
|
|
2468
|
+
const messages: string[] = [];
|
|
2469
|
+
const unknown = findUnknownRoutingKeys(rawRouting);
|
|
2470
|
+
if (unknown.length > 0) {
|
|
2471
|
+
messages.push(`ignoring unknown routing key${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}`);
|
|
2472
|
+
}
|
|
2473
|
+
for (const [taskClass, agents] of Object.entries(cfg.routing?.roles ?? {})) {
|
|
2474
|
+
for (const agent of agents) {
|
|
2475
|
+
if (ROUTING_RESERVED_AGENTS.some((reserved) => reserved === agent)) {
|
|
2476
|
+
messages.push(
|
|
2477
|
+
`routing.roles.'${taskClass}' names '${agent}', an OpenCode primary/internal agent that cannot be a subagent; it will be skipped`,
|
|
2478
|
+
);
|
|
2479
|
+
}
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
for (const [presetName, preset] of Object.entries(cfg.presets)) {
|
|
2483
|
+
for (const [tierName, tier] of Object.entries(preset)) {
|
|
2484
|
+
const problem = candidatesProblem(tierName, tier);
|
|
2485
|
+
if (problem !== undefined) {
|
|
2486
|
+
messages.push(
|
|
2487
|
+
`presets.${presetName}.${tierName}.candidates are ignored, the tier's ladder is its own rung: ${problem}`,
|
|
2488
|
+
);
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
}
|
|
2492
|
+
for (const name of Object.keys(cfg.routing?.classifier?.presets ?? {})) {
|
|
2493
|
+
if (resolvePresetName(cfg, name) === undefined) {
|
|
2494
|
+
messages.push(
|
|
2495
|
+
`routing.classifier.presets.'${name}' matches no preset (defined: ${Object.keys(cfg.presets).join(", ")}); the override is unused`,
|
|
2496
|
+
);
|
|
2497
|
+
}
|
|
2498
|
+
}
|
|
2499
|
+
return messages;
|
|
2500
|
+
}
|
|
2501
|
+
/**
|
|
2502
|
+
* `routing.roles` is replaced wholesale by the highest-priority layer that sets
|
|
2503
|
+
* it, not merged class by class (QA-1.1-7): the default is replaced as a whole
|
|
2504
|
+
* too, so a layer's `roles` is the complete list of what it wants, and a class
|
|
2505
|
+
* it leaves out cannot be re-enabled by a lower layer.
|
|
2506
|
+
*/
|
|
2507
|
+
function replaceRolesWholesale(merged: unknown, layers: readonly OverrideLayer[]): unknown {
|
|
2508
|
+
if (!isPlainObject(merged) || !isPlainObject(merged.routing)) return merged;
|
|
2509
|
+
for (let i = layers.length - 1; i >= 0; i--) {
|
|
2510
|
+
const routing = layers[i]!.data.routing;
|
|
2511
|
+
if (isPlainObject(routing) && Object.hasOwn(routing, "roles") && routing.roles !== undefined) {
|
|
2512
|
+
return { ...merged, routing: { ...merged.routing, roles: routing.roles } };
|
|
2513
|
+
}
|
|
2514
|
+
}
|
|
2515
|
+
return merged;
|
|
2516
|
+
}
|
|
2517
|
+
|
|
2518
|
+
/** Merge an override while keeping project classifier budgets within the lower layers' bounds. */
|
|
2519
|
+
function mergeOverrideLayer(lower: unknown, layer: OverrideLayer, notices: ConfigNotice[]): unknown {
|
|
2520
|
+
const merged = deepMerge(lower, layer.data);
|
|
2521
|
+
if (!layer.project || !isPlainObject(merged) || !isPlainObject(merged.routing)) return merged;
|
|
2522
|
+
const classifier = merged.routing.classifier;
|
|
2523
|
+
const projectRouting = layer.data.routing;
|
|
2524
|
+
const projectClassifier = isPlainObject(projectRouting) ? projectRouting.classifier : undefined;
|
|
2525
|
+
if (!isPlainObject(classifier) || !isPlainObject(projectClassifier)) return merged;
|
|
2526
|
+
const lowerRouting = isPlainObject(lower) ? lower.routing : undefined;
|
|
2527
|
+
const lowerClassifier = isPlainObject(lowerRouting) ? lowerRouting.classifier : undefined;
|
|
2528
|
+
const bounded = { ...classifier };
|
|
2529
|
+
// A18 / A35: a repository may tighten the user's exposure/latency budgets, never widen them.
|
|
2530
|
+
for (const key of ["maxStateChars", "samples", "timeoutMs"] as const) {
|
|
2531
|
+
const requested = projectClassifier[key];
|
|
2532
|
+
const inherited = isPlainObject(lowerClassifier) ? lowerClassifier[key] : undefined;
|
|
2533
|
+
const validInherited = typeof inherited === "number" && Number.isInteger(inherited)
|
|
2534
|
+
&& (key === "samples" ? inherited === 1 || inherited === 3
|
|
2535
|
+
: key === "maxStateChars" ? inherited >= 200 && inherited <= 20_000
|
|
2536
|
+
: inherited >= 100 && inherited <= 30_000);
|
|
2537
|
+
const ceiling = validInherited ? inherited : ROUTING_DEFAULTS.classifier[key];
|
|
2538
|
+
if (typeof requested === "number" && Number.isFinite(requested) && typeof ceiling === "number" && requested > ceiling) {
|
|
2539
|
+
bounded[key] = ceiling;
|
|
2540
|
+
notices.push({ source: layer.path, message: `A18: clamping routing.classifier.${key} from ${layer.path} to ${ceiling}: project overrides may only tighten the lower-layer value (A35)` });
|
|
2541
|
+
}
|
|
2542
|
+
}
|
|
2543
|
+
// deepMerge can share an override-only block: do not mutate a source layer used by fallback merges.
|
|
2544
|
+
return { ...merged, routing: { ...merged.routing, classifier: bounded } };
|
|
2545
|
+
}
|
|
2546
|
+
|
|
1524
2547
|
/**
|
|
1525
2548
|
* Build a fresh config from tiers.json + override layers + persisted state.
|
|
1526
2549
|
* Throws only when tiers.json itself is unreadable/invalid. Override and state
|
|
1527
2550
|
* problems are warned about, skipped, and appended to `failures`.
|
|
1528
2551
|
*/
|
|
1529
|
-
function buildConfig(
|
|
2552
|
+
function buildConfig(
|
|
2553
|
+
dir: string,
|
|
2554
|
+
failures: SourceFailure[],
|
|
2555
|
+
notices: ConfigNotice[],
|
|
2556
|
+
): RouterConfig {
|
|
1530
2557
|
const base = JSON.parse(readFileSync(configPath(), "utf-8"));
|
|
1531
|
-
const layers = collectOverrideLayers(dir, failures);
|
|
2558
|
+
const layers = collectOverrideLayers(dir, failures, notices);
|
|
1532
2559
|
|
|
1533
2560
|
// Bundled config must be valid on its own — throw otherwise (unchanged
|
|
1534
2561
|
// behaviour). Override layers are then applied on top.
|
|
1535
2562
|
let cfg = validateConfig(base);
|
|
2563
|
+
let rawUsed: unknown = base;
|
|
1536
2564
|
|
|
1537
2565
|
if (layers.length > 0) {
|
|
1538
2566
|
const merge = (ls: OverrideLayer[]): unknown =>
|
|
1539
|
-
|
|
2567
|
+
replaceRolesWholesale(
|
|
2568
|
+
ls.reduce<unknown>((acc, l) => mergeOverrideLayer(acc, l, notices), base),
|
|
2569
|
+
ls,
|
|
2570
|
+
);
|
|
1540
2571
|
|
|
1541
2572
|
try {
|
|
1542
|
-
|
|
2573
|
+
const merged = merge(layers);
|
|
2574
|
+
cfg = validateConfig(merged);
|
|
2575
|
+
rawUsed = merged;
|
|
1543
2576
|
} catch (err) {
|
|
1544
2577
|
// A bad override must never brick startup, and one broken file must not
|
|
1545
2578
|
// discard a good one. Fall back to the highest-priority layer that
|
|
@@ -1555,7 +2588,9 @@ function buildConfig(dir: string, failures: SourceFailure[]): RouterConfig {
|
|
|
1555
2588
|
});
|
|
1556
2589
|
for (let i = layers.length - 1; i >= 0; i--) {
|
|
1557
2590
|
try {
|
|
1558
|
-
|
|
2591
|
+
const single = merge([layers[i]!]);
|
|
2592
|
+
cfg = validateConfig(single);
|
|
2593
|
+
rawUsed = single;
|
|
1559
2594
|
for (let j = 0; j < layers.length; j++) {
|
|
1560
2595
|
if (j !== i) {
|
|
1561
2596
|
console.warn(`[model-router] dropped override layer ${layers[j]!.path}`);
|
|
@@ -1571,6 +2606,7 @@ function buildConfig(dir: string, failures: SourceFailure[]): RouterConfig {
|
|
|
1571
2606
|
message: `${layers[i]!.path}: ${(singleErr as Error).message}`,
|
|
1572
2607
|
});
|
|
1573
2608
|
cfg = validateConfig(base);
|
|
2609
|
+
rawUsed = base;
|
|
1574
2610
|
}
|
|
1575
2611
|
}
|
|
1576
2612
|
}
|
|
@@ -1610,9 +2646,28 @@ function buildConfig(dir: string, failures: SourceFailure[]): RouterConfig {
|
|
|
1610
2646
|
}
|
|
1611
2647
|
|
|
1612
2648
|
applyTierDefaults(cfg);
|
|
2649
|
+
const rawRouting = isPlainObject(rawUsed) ? rawUsed.routing : undefined;
|
|
2650
|
+
for (const message of collectRoutingNotices(rawRouting, cfg)) notices.push({ message });
|
|
2651
|
+
dropIgnoredCandidates(cfg);
|
|
1613
2652
|
return cfg;
|
|
1614
2653
|
}
|
|
1615
2654
|
|
|
2655
|
+
/**
|
|
2656
|
+
* Remove, from the built config, every `candidates` list that loading reports as
|
|
2657
|
+
* ignored ({@link candidatesProblem}), after the notice has been recorded
|
|
2658
|
+
* (QA-1.1-30). Leaving it on `tier.candidates` would make `hasExplicitCandidates`
|
|
2659
|
+
* and any code that reads the raw list disagree with `resolveCandidates`, which
|
|
2660
|
+
* already treats the tier as having only its own rung. Runs on the config this
|
|
2661
|
+
* build created, never on a caller's object.
|
|
2662
|
+
*/
|
|
2663
|
+
function dropIgnoredCandidates(cfg: RouterConfig): void {
|
|
2664
|
+
for (const preset of Object.values(cfg.presets)) {
|
|
2665
|
+
for (const [tierName, tier] of Object.entries(preset)) {
|
|
2666
|
+
if (candidatesProblem(tierName, tier) !== undefined) delete tier.candidates;
|
|
2667
|
+
}
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
|
|
1616
2671
|
// ---------------------------------------------------------------------------
|
|
1617
2672
|
// State persistence helpers
|
|
1618
2673
|
// ---------------------------------------------------------------------------
|
|
@@ -1768,3 +2823,294 @@ export function resolveVerifyBudget(
|
|
|
1768
2823
|
gateBudgetMs: own<number>("gateBudgetMs") ?? 90_000,
|
|
1769
2824
|
};
|
|
1770
2825
|
}
|
|
2826
|
+
|
|
2827
|
+
// ---------------------------------------------------------------------------
|
|
2828
|
+
// Cost-aware routing helpers (#74)
|
|
2829
|
+
// ---------------------------------------------------------------------------
|
|
2830
|
+
|
|
2831
|
+
/** The single log line of D1; also the exact text tests pin. */
|
|
2832
|
+
export const ROUTING_ENGINE_IGNORED_ON_V1 = "routing.engine ignored on OpenCode v1";
|
|
2833
|
+
|
|
2834
|
+
/**
|
|
2835
|
+
* D12: the roles applied on OpenCode v2 when `routing.roles` is not set. On v1
|
|
2836
|
+
* the default is `{}` (D1). Setting `roles: {}` disables native candidates.
|
|
2837
|
+
*/
|
|
2838
|
+
export const DEFAULT_V2_ROLES: Readonly<Record<string, readonly string[]>> = Object.freeze({
|
|
2839
|
+
search: Object.freeze(["explore"]),
|
|
2840
|
+
implement: Object.freeze(["general"]),
|
|
2841
|
+
debug: Object.freeze(["general"]),
|
|
2842
|
+
review: Object.freeze(["general"]),
|
|
2843
|
+
});
|
|
2844
|
+
|
|
2845
|
+
/**
|
|
2846
|
+
* Every default of the `routing` block except `roles`, whose default depends on
|
|
2847
|
+
* the host. `docs/CONFIG_REFERENCE.md` documents exactly these values and a
|
|
2848
|
+
* test keeps the two in step.
|
|
2849
|
+
*/
|
|
2850
|
+
export const ROUTING_DEFAULTS = Object.freeze({
|
|
2851
|
+
engine: "static" as RoutingEngine,
|
|
2852
|
+
profile: "balanced" as RoutingProfile,
|
|
2853
|
+
margin: 0.2,
|
|
2854
|
+
minClassConfidence: 0.7,
|
|
2855
|
+
detection: Object.freeze({ deterministic: 0.95, grader: 0.7, none: 0.3 }),
|
|
2856
|
+
classifier: Object.freeze({
|
|
2857
|
+
backend: "rules" as ClassifierBackend,
|
|
2858
|
+
model: null,
|
|
2859
|
+
baseUrl: null,
|
|
2860
|
+
apiKeyEnv: null,
|
|
2861
|
+
timeoutMs: 1500,
|
|
2862
|
+
samples: 1 as 1 | 3,
|
|
2863
|
+
maxStateChars: 2000,
|
|
2864
|
+
}),
|
|
2865
|
+
outcomes: Object.freeze({ path: null, halfLifeDays: 14, maxEffectiveSamples: 50 }),
|
|
2866
|
+
sessionReuse: Object.freeze({ maxContextFraction: 0.6 }),
|
|
2867
|
+
advisor: Object.freeze({ enabled: true, noticeIntervalHours: 24, notify: true }),
|
|
2868
|
+
});
|
|
2869
|
+
|
|
2870
|
+
export interface ResolvedClassifier {
|
|
2871
|
+
readonly backend: ClassifierBackend;
|
|
2872
|
+
readonly model: string | null;
|
|
2873
|
+
readonly baseUrl: string | null;
|
|
2874
|
+
readonly apiKeyEnv: string | null;
|
|
2875
|
+
readonly timeoutMs: number;
|
|
2876
|
+
readonly samples: 1 | 3;
|
|
2877
|
+
readonly maxStateChars: number;
|
|
2878
|
+
readonly presets: Readonly<Record<string, Readonly<ClassifierPresetOverride>>>;
|
|
2879
|
+
}
|
|
2880
|
+
|
|
2881
|
+
/** What {@link resolveRouting} applied on top of the file, so `/router` can show it. */
|
|
2882
|
+
export interface RoutingApplied {
|
|
2883
|
+
readonly host: RouterHost;
|
|
2884
|
+
/** `routing.engine` as written (or the default), before the v1 coercion. */
|
|
2885
|
+
readonly requestedEngine: RoutingEngine;
|
|
2886
|
+
/** True when the engine was forced to `static` because the host is v1. */
|
|
2887
|
+
readonly engineCoerced: boolean;
|
|
2888
|
+
/** `configured`: `routing.roles` was set; `default`: the D12 v2 default; `none`: v1 without roles. */
|
|
2889
|
+
readonly rolesSource: "configured" | "default" | "none";
|
|
2890
|
+
}
|
|
2891
|
+
|
|
2892
|
+
/** A fully populated, deeply frozen view of `routing` for one host. */
|
|
2893
|
+
export interface ResolvedRouting {
|
|
2894
|
+
/** The effective engine: `static` on v1 whatever the file says (D1). */
|
|
2895
|
+
readonly engine: RoutingEngine;
|
|
2896
|
+
readonly profile: RoutingProfile;
|
|
2897
|
+
readonly margin: number;
|
|
2898
|
+
readonly minClassConfidence: number;
|
|
2899
|
+
readonly detection: Readonly<Required<DetectionConfig>>;
|
|
2900
|
+
readonly classifier: ResolvedClassifier;
|
|
2901
|
+
/** Class → ordered, de-duplicated agent ids. */
|
|
2902
|
+
readonly roles: Readonly<Record<string, readonly string[]>>;
|
|
2903
|
+
readonly outcomes: Readonly<{ path: string | null; halfLifeDays: number; maxEffectiveSamples: number }>;
|
|
2904
|
+
readonly sessionReuse: Readonly<Required<SessionReuseConfig>>;
|
|
2905
|
+
readonly advisor: Readonly<Required<AdvisorConfig>>;
|
|
2906
|
+
readonly applied: RoutingApplied;
|
|
2907
|
+
}
|
|
2908
|
+
|
|
2909
|
+
/** `~` and `~/x` become paths under the home directory; anything else is returned as is. */
|
|
2910
|
+
function expandHomePath(value: string | null): string | null {
|
|
2911
|
+
if (value === null) return null;
|
|
2912
|
+
if (value === "~") return homedir();
|
|
2913
|
+
return /^~[\\/]/.test(value) ? join(homedir(), value.slice(2)) : value;
|
|
2914
|
+
}
|
|
2915
|
+
|
|
2916
|
+
let warnedEngineIgnoredOnV1 = false;
|
|
2917
|
+
|
|
2918
|
+
/** Test-only: re-arm the once-per-process "engine ignored on v1" notice. */
|
|
2919
|
+
export function resetRoutingWarnings(): void {
|
|
2920
|
+
warnedEngineIgnoredOnV1 = false;
|
|
2921
|
+
loggedNoticeTexts.clear();
|
|
2922
|
+
}
|
|
2923
|
+
|
|
2924
|
+
/** Roles as fresh, de-duplicated, frozen arrays; never aliases the config. */
|
|
2925
|
+
function freezeRoles(
|
|
2926
|
+
roles: Readonly<Record<string, readonly string[]>>,
|
|
2927
|
+
): Readonly<Record<string, readonly string[]>> {
|
|
2928
|
+
const out: Record<string, readonly string[]> = {};
|
|
2929
|
+
for (const [taskClass, agents] of Object.entries(roles)) {
|
|
2930
|
+
out[taskClass] = Object.freeze([...new Set(agents)]);
|
|
2931
|
+
}
|
|
2932
|
+
return Object.freeze(out);
|
|
2933
|
+
}
|
|
2934
|
+
|
|
2935
|
+
/**
|
|
2936
|
+
* The single place the `routing` defaults are applied. Pure apart from the
|
|
2937
|
+
* once-per-process notice below, and never mutates `cfg`.
|
|
2938
|
+
*
|
|
2939
|
+
* - `host: "v2"` applies the D12 default for `roles` when the key is absent.
|
|
2940
|
+
* - `host: "v1"` forces `engine` to `static` (D1) and defaults `roles` to `{}`;
|
|
2941
|
+
* an explicit `routing.roles` is kept (the text-only v1 opt-in).
|
|
2942
|
+
*
|
|
2943
|
+
* The coercion is reported once per process through `logger` (its console
|
|
2944
|
+
* fallback adds the `[model-router]` prefix) or, without one, `console.warn`.
|
|
2945
|
+
*/
|
|
2946
|
+
export function resolveRouting(
|
|
2947
|
+
cfg: RouterConfig | undefined,
|
|
2948
|
+
host: RouterHost,
|
|
2949
|
+
logger?: Pick<PluginLogger, "warn">,
|
|
2950
|
+
): ResolvedRouting {
|
|
2951
|
+
const r: RoutingConfig = cfg?.routing ?? {};
|
|
2952
|
+
const d = ROUTING_DEFAULTS;
|
|
2953
|
+
const requestedEngine = r.engine ?? d.engine;
|
|
2954
|
+
const engineCoerced = host === "v1" && requestedEngine !== "static";
|
|
2955
|
+
if (engineCoerced && !warnedEngineIgnoredOnV1) {
|
|
2956
|
+
warnedEngineIgnoredOnV1 = true;
|
|
2957
|
+
if (logger) logger.warn(ROUTING_ENGINE_IGNORED_ON_V1);
|
|
2958
|
+
else console.warn(`[model-router] ${ROUTING_ENGINE_IGNORED_ON_V1}`);
|
|
2959
|
+
}
|
|
2960
|
+
|
|
2961
|
+
const c: ClassifierConfig = r.classifier ?? {};
|
|
2962
|
+
const presets: Record<string, Readonly<ClassifierPresetOverride>> = {};
|
|
2963
|
+
for (const [name, override] of Object.entries(c.presets ?? {})) {
|
|
2964
|
+
presets[name] = Object.freeze({ ...override });
|
|
2965
|
+
}
|
|
2966
|
+
|
|
2967
|
+
const rolesSource: RoutingApplied["rolesSource"] =
|
|
2968
|
+
r.roles !== undefined ? "configured" : host === "v2" ? "default" : "none";
|
|
2969
|
+
const roles = freezeRoles(r.roles ?? (host === "v2" ? DEFAULT_V2_ROLES : {}));
|
|
2970
|
+
|
|
2971
|
+
return Object.freeze({
|
|
2972
|
+
engine: host === "v1" ? "static" : requestedEngine,
|
|
2973
|
+
profile: r.profile ?? d.profile,
|
|
2974
|
+
margin: r.margin ?? d.margin,
|
|
2975
|
+
minClassConfidence: r.minClassConfidence ?? d.minClassConfidence,
|
|
2976
|
+
detection: Object.freeze({
|
|
2977
|
+
deterministic: r.detection?.deterministic ?? d.detection.deterministic,
|
|
2978
|
+
grader: r.detection?.grader ?? d.detection.grader,
|
|
2979
|
+
none: r.detection?.none ?? d.detection.none,
|
|
2980
|
+
}),
|
|
2981
|
+
classifier: Object.freeze({
|
|
2982
|
+
backend: c.backend ?? d.classifier.backend,
|
|
2983
|
+
model: c.model ?? d.classifier.model,
|
|
2984
|
+
baseUrl: c.baseUrl ?? d.classifier.baseUrl,
|
|
2985
|
+
apiKeyEnv: c.apiKeyEnv ?? d.classifier.apiKeyEnv,
|
|
2986
|
+
timeoutMs: c.timeoutMs ?? d.classifier.timeoutMs,
|
|
2987
|
+
samples: c.samples ?? d.classifier.samples,
|
|
2988
|
+
maxStateChars: c.maxStateChars ?? d.classifier.maxStateChars,
|
|
2989
|
+
presets: Object.freeze(presets),
|
|
2990
|
+
}),
|
|
2991
|
+
roles,
|
|
2992
|
+
outcomes: Object.freeze({
|
|
2993
|
+
path: expandHomePath(r.outcomes?.path ?? d.outcomes.path),
|
|
2994
|
+
halfLifeDays: r.outcomes?.halfLifeDays ?? d.outcomes.halfLifeDays,
|
|
2995
|
+
maxEffectiveSamples: r.outcomes?.maxEffectiveSamples ?? d.outcomes.maxEffectiveSamples,
|
|
2996
|
+
}),
|
|
2997
|
+
sessionReuse: Object.freeze({
|
|
2998
|
+
maxContextFraction: r.sessionReuse?.maxContextFraction ?? d.sessionReuse.maxContextFraction,
|
|
2999
|
+
}),
|
|
3000
|
+
advisor: Object.freeze({
|
|
3001
|
+
enabled: r.advisor?.enabled ?? d.advisor.enabled,
|
|
3002
|
+
noticeIntervalHours: r.advisor?.noticeIntervalHours ?? d.advisor.noticeIntervalHours,
|
|
3003
|
+
notify: r.advisor?.notify ?? d.advisor.notify,
|
|
3004
|
+
}),
|
|
3005
|
+
applied: Object.freeze({ host, requestedEngine, engineCoerced, rolesSource }),
|
|
3006
|
+
});
|
|
3007
|
+
}
|
|
3008
|
+
|
|
3009
|
+
/**
|
|
3010
|
+
* The key of `presets` that names `presetName`: an exact match, else a
|
|
3011
|
+
* case-insensitive, trimmed one, like {@link resolvePresetName} (what `/preset`
|
|
3012
|
+
* uses), so `Anthropic` and `anthropic` are the same preset (QA-1.1-14).
|
|
3013
|
+
* Own keys only.
|
|
3014
|
+
*/
|
|
3015
|
+
function findPresetOverrideKey(
|
|
3016
|
+
presets: Readonly<Record<string, unknown>>,
|
|
3017
|
+
presetName: string,
|
|
3018
|
+
): string | undefined {
|
|
3019
|
+
if (Object.hasOwn(presets, presetName)) return presetName;
|
|
3020
|
+
const normalized = presetName.trim().toLowerCase();
|
|
3021
|
+
if (normalized === "") return undefined;
|
|
3022
|
+
return Object.keys(presets).find((key) => key.trim().toLowerCase() === normalized);
|
|
3023
|
+
}
|
|
3024
|
+
|
|
3025
|
+
/**
|
|
3026
|
+
* The classifier settings that apply while `presetName` is the active preset:
|
|
3027
|
+
* the top-level block with that preset's `backend` / `model` override on top.
|
|
3028
|
+
* The preset name is matched like `/preset` matches it (exact, then
|
|
3029
|
+
* case-insensitive); a `presets` key that matches no preset is noticed at load.
|
|
3030
|
+
*/
|
|
3031
|
+
export function resolveClassifierForPreset(
|
|
3032
|
+
classifier: ResolvedClassifier,
|
|
3033
|
+
presetName: string,
|
|
3034
|
+
): ResolvedClassifier {
|
|
3035
|
+
const key = findPresetOverrideKey(classifier.presets, presetName);
|
|
3036
|
+
const override = key === undefined ? undefined : classifier.presets[key];
|
|
3037
|
+
if (override === undefined) return classifier;
|
|
3038
|
+
return Object.freeze({
|
|
3039
|
+
...classifier,
|
|
3040
|
+
backend: override.backend ?? classifier.backend,
|
|
3041
|
+
model: override.model !== undefined ? override.model : classifier.model,
|
|
3042
|
+
});
|
|
3043
|
+
}
|
|
3044
|
+
|
|
3045
|
+
/**
|
|
3046
|
+
* `enforcement.escalate.variantSteps` for one host (A15, QA-1.1-4).
|
|
3047
|
+
*
|
|
3048
|
+
* - On v1 it is always `none`: variant steps do not exist there (D1), so even an
|
|
3049
|
+
* explicit value is ignored.
|
|
3050
|
+
* - On v2 an explicit value always wins. Absent, the default is `auto` when the
|
|
3051
|
+
* config has a `routing` block and `none` when it has not, so that a config
|
|
3052
|
+
* without `routing` keeps today's ladder byte for byte (D2).
|
|
3053
|
+
*/
|
|
3054
|
+
export function resolveVariantSteps(cfg: RouterConfig | undefined, host: RouterHost): VariantStepsMode {
|
|
3055
|
+
if (host === "v1") return "none";
|
|
3056
|
+
const explicit = cfg?.enforcement?.escalate?.variantSteps;
|
|
3057
|
+
if (explicit !== undefined) return explicit;
|
|
3058
|
+
return cfg?.routing !== undefined ? "auto" : "none";
|
|
3059
|
+
}
|
|
3060
|
+
|
|
3061
|
+
/** One rung of a tier's ladder, fully resolved. */
|
|
3062
|
+
export interface ResolvedCandidate {
|
|
3063
|
+
readonly model: string;
|
|
3064
|
+
/** Absent = the model's default variant. */
|
|
3065
|
+
readonly variant?: string;
|
|
3066
|
+
readonly costRatio: number;
|
|
3067
|
+
}
|
|
3068
|
+
|
|
3069
|
+
const NO_CANDIDATES: readonly ResolvedCandidate[] = Object.freeze([]);
|
|
3070
|
+
|
|
3071
|
+
/**
|
|
3072
|
+
* The ladder of rungs for `tierName` in the active preset (D10, D12).
|
|
3073
|
+
*
|
|
3074
|
+
* Without `candidates` (or with an empty list) it is exactly one rung: the
|
|
3075
|
+
* tier's own `(model, variant, costRatio)`. With `candidates` it is those
|
|
3076
|
+
* entries, in order, each completed from the tier: `model` and `costRatio`
|
|
3077
|
+
* are inherited when omitted, `variant` is not. An unknown tier yields an
|
|
3078
|
+
* empty ladder. Never throws.
|
|
3079
|
+
*/
|
|
3080
|
+
export function resolveCandidates(tierName: string, cfg: RouterConfig): readonly ResolvedCandidate[] {
|
|
3081
|
+
const presetName = resolvePresetName(cfg, cfg.activePreset);
|
|
3082
|
+
const preset = presetName !== undefined && Object.hasOwn(cfg.presets, presetName) ? cfg.presets[presetName] : undefined;
|
|
3083
|
+
const tier = preset !== undefined && Object.hasOwn(preset, tierName) ? preset[tierName] : undefined;
|
|
3084
|
+
if (tier === undefined) return NO_CANDIDATES;
|
|
3085
|
+
|
|
3086
|
+
const tierCostRatio = tier.costRatio ?? tierDefaultsFor(tierName).costRatio;
|
|
3087
|
+
const rung = (model: string, variant: string | undefined, costRatio: number): ResolvedCandidate =>
|
|
3088
|
+
Object.freeze(variant === undefined ? { model, costRatio } : { model, variant, costRatio });
|
|
3089
|
+
|
|
3090
|
+
const listed = tier.candidates;
|
|
3091
|
+
if (listed === undefined || candidatesProblem(tierName, tier) !== undefined || !hasExplicitCandidates(tier)) {
|
|
3092
|
+
return Object.freeze([rung(tier.model, tier.variant, tierCostRatio)]);
|
|
3093
|
+
}
|
|
3094
|
+
return Object.freeze(
|
|
3095
|
+
listed.map((c) => rung(c.model ?? tier.model, c.variant, c.costRatio ?? tierCostRatio)),
|
|
3096
|
+
);
|
|
3097
|
+
}
|
|
3098
|
+
/**
|
|
3099
|
+
* The extra lines of the bare `/router` status view: the marker
|
|
3100
|
+
* `router: engine=<mode> build=<version>+<sha7>` (the engine is the one
|
|
3101
|
+
* *applied* on `host`, so always `static` on v1) followed by one
|
|
3102
|
+
* `router: config notice: …` line per notice of the config last loaded for `dir`
|
|
3103
|
+
* (QA-1.1-10). Passing `logger` makes the once-per-process v1 notice go through
|
|
3104
|
+
* the plugin logger.
|
|
3105
|
+
*/
|
|
3106
|
+
export function routerStatusLines(
|
|
3107
|
+
cfg: RouterConfig,
|
|
3108
|
+
host: RouterHost,
|
|
3109
|
+
logger?: Pick<PluginLogger, "warn">,
|
|
3110
|
+
dir?: string,
|
|
3111
|
+
): string[] {
|
|
3112
|
+
return [
|
|
3113
|
+
formatRouterLine(resolveRouting(cfg, host, logger).engine),
|
|
3114
|
+
...getConfigNotices(dir).map((notice) => `router: config notice: ${notice.message}`),
|
|
3115
|
+
];
|
|
3116
|
+
}
|