opencode-model-router 2.1.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 +86 -0
- package/README.md +44 -5
- 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 +174 -47
- 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 +557 -61
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1691 -67
- 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/tiers.json +43 -0
package/src/router/config.ts
CHANGED
|
@@ -4,11 +4,13 @@ import {
|
|
|
4
4
|
readFileSync,
|
|
5
5
|
realpathSync,
|
|
6
6
|
renameSync,
|
|
7
|
+
statSync,
|
|
7
8
|
writeFileSync,
|
|
8
9
|
} from "node:fs";
|
|
9
10
|
import { availableParallelism, homedir } from "node:os";
|
|
10
|
-
import { dirname, join } from "node:path";
|
|
11
|
+
import { dirname, isAbsolute, join, resolve as resolvePath } from "node:path";
|
|
11
12
|
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { formatRouterLine } from "./build-info";
|
|
12
14
|
import { parseJsonc } from "./jsonc";
|
|
13
15
|
import type { DelegateInstructionsPolicy } from "./instructions";
|
|
14
16
|
import type { PluginLogger } from "./logger";
|
|
@@ -105,6 +107,12 @@ export interface TierConfig {
|
|
|
105
107
|
promptStyle?: PromptStyle;
|
|
106
108
|
/** Optional use-case hints shown in `/tiers`. */
|
|
107
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[];
|
|
108
116
|
}
|
|
109
117
|
|
|
110
118
|
export type Preset = Record<string, TierConfig>;
|
|
@@ -170,14 +178,132 @@ export interface EnforcementConfig {
|
|
|
170
178
|
failureRecheck?: boolean;
|
|
171
179
|
/** Budget for the reference re-run, in ms (integer >= 1). Default 60000. */
|
|
172
180
|
recheckTimeoutMs?: number };
|
|
173
|
-
escalate?:
|
|
174
|
-
/** Bump reasoning effort before escalating tiers. Default true. */
|
|
175
|
-
effortBump?: boolean;
|
|
176
|
-
/** Maximum reasoning effort for a bump. Default "xhigh". */
|
|
177
|
-
effortBumpMax?: EffortLevel };
|
|
181
|
+
escalate?: EscalateConfig;
|
|
178
182
|
proportional?: { trivialBypass?: boolean; trivialClassifier?: string };
|
|
179
183
|
}
|
|
180
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
|
+
|
|
181
307
|
export interface RouterConfig {
|
|
182
308
|
/**
|
|
183
309
|
* Detect a delegate that hands a dispatch back having made zero tool calls
|
|
@@ -252,6 +378,8 @@ export interface RouterConfig {
|
|
|
252
378
|
subagentTiers?: Record<string, string>;
|
|
253
379
|
/** Experimental, opt-in features. Off by default. */
|
|
254
380
|
experimental?: { verifiedDelegateTool?: boolean };
|
|
381
|
+
/** Cost-aware routing engine (#74). Absent = today's static routing, byte for byte. */
|
|
382
|
+
routing?: RoutingConfig;
|
|
255
383
|
}
|
|
256
384
|
|
|
257
385
|
export interface RouterState {
|
|
@@ -264,12 +392,103 @@ export interface RouterState {
|
|
|
264
392
|
// Config loader with caching
|
|
265
393
|
// ---------------------------------------------------------------------------
|
|
266
394
|
|
|
267
|
-
|
|
268
|
-
|
|
395
|
+
/**
|
|
396
|
+
* Cache state for one project directory. Hosts such as OpenCode v2 run one
|
|
397
|
+
* plugin instance per project directory inside a single process, so the cache
|
|
398
|
+
* cannot be a single module-level slot: each directory has its own project
|
|
399
|
+
* override file and therefore its own config, fingerprint and last-good state.
|
|
400
|
+
*/
|
|
401
|
+
interface ConfigCacheEntry {
|
|
402
|
+
config: RouterConfig | null;
|
|
403
|
+
dirty: boolean;
|
|
404
|
+
fingerprint: string;
|
|
405
|
+
/** Source locations (paths only, no mtimes) that produced `config`. */
|
|
406
|
+
sourceKey: string;
|
|
407
|
+
/** Sources that were already failing when `config` was built (tolerated). */
|
|
408
|
+
tolerated: Set<string>;
|
|
409
|
+
/** Last hot-reload failure (null when the most recent rebuild succeeded). */
|
|
410
|
+
reloadError: string | null;
|
|
411
|
+
/** Fingerprint a reload-failure warning was last emitted for (warn once each). */
|
|
412
|
+
warnedFingerprint: string | null;
|
|
413
|
+
/** Non-fatal findings of the build that produced `config` (see {@link getConfigNotices}). */
|
|
414
|
+
notices: ConfigNotice[];
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Keyed by {@link normalizeProjectDir}. */
|
|
418
|
+
const _configCaches = new Map<string, ConfigCacheEntry>();
|
|
419
|
+
|
|
420
|
+
function getCacheEntry(key: string): ConfigCacheEntry {
|
|
421
|
+
let entry = _configCaches.get(key);
|
|
422
|
+
if (!entry) {
|
|
423
|
+
entry = {
|
|
424
|
+
config: null,
|
|
425
|
+
dirty: true,
|
|
426
|
+
fingerprint: "",
|
|
427
|
+
sourceKey: "",
|
|
428
|
+
tolerated: new Set<string>(),
|
|
429
|
+
reloadError: null,
|
|
430
|
+
warnedFingerprint: null,
|
|
431
|
+
notices: [],
|
|
432
|
+
};
|
|
433
|
+
_configCaches.set(key, entry);
|
|
434
|
+
}
|
|
435
|
+
return entry;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* `realpathSync` that fails soft: an unresolvable path is used as-is, which is
|
|
440
|
+
* no worse than not resolving at all.
|
|
441
|
+
*/
|
|
442
|
+
function realpathOrSelf(p: string): string {
|
|
443
|
+
try {
|
|
444
|
+
return realpathSync(p);
|
|
445
|
+
} catch {
|
|
446
|
+
return p;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Canonical form of a project directory: absolute and symlink-resolved, so the
|
|
452
|
+
* same directory reached through different spellings shares one cache entry
|
|
453
|
+
* and compares equal to the (resolved) home directory. A missing or empty `dir`
|
|
454
|
+
* means "the process working directory at call time".
|
|
455
|
+
*/
|
|
456
|
+
function normalizeProjectDir(dir?: string): string {
|
|
457
|
+
return realpathOrSelf(dir ? resolvePath(dir) : process.cwd());
|
|
458
|
+
}
|
|
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
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Why the last config rebuild failed for `dir` (default: the working
|
|
480
|
+
* directory), or null when it succeeded. When a source (tiers.json, an
|
|
481
|
+
* overrides file, or the state file) becomes invalid after a successful load,
|
|
482
|
+
* loadConfig() keeps serving the last valid config and records the reason here
|
|
483
|
+
* instead of throwing or silently dropping layers.
|
|
484
|
+
*/
|
|
485
|
+
export function getConfigReloadError(dir?: string): string | null {
|
|
486
|
+
return _configCaches.get(normalizeProjectDir(dir))?.reloadError ?? null;
|
|
487
|
+
}
|
|
269
488
|
|
|
270
|
-
/** Mark config cache as stale so it is re-read on next access. */
|
|
489
|
+
/** Mark every directory's config cache as stale so it is re-read on next access. */
|
|
271
490
|
export function invalidateConfigCache(): void {
|
|
272
|
-
|
|
491
|
+
for (const entry of _configCaches.values()) entry.dirty = true;
|
|
273
492
|
}
|
|
274
493
|
|
|
275
494
|
function getPluginRoot(): string {
|
|
@@ -293,17 +512,17 @@ export function overridePath(): string {
|
|
|
293
512
|
|
|
294
513
|
/**
|
|
295
514
|
* Default location of the project-local overrides file
|
|
296
|
-
* (`.opencode/opencode-model-router.overrides.jsonc` in the
|
|
297
|
-
*
|
|
298
|
-
*
|
|
299
|
-
* file is found.
|
|
515
|
+
* (`.opencode/opencode-model-router.overrides.jsonc` in the project directory,
|
|
516
|
+
* or in the current working directory when `dir` is omitted). This is the path
|
|
517
|
+
* to *create* the file at; the actual lookup walks upward — see
|
|
518
|
+
* {@link findProjectOverride}. Used for display when no project file is found.
|
|
300
519
|
*
|
|
301
520
|
* The project file is deep-merged *after* (and therefore wins over) the global
|
|
302
521
|
* overrides file, so a team can commit a shared file that unifies routing for
|
|
303
522
|
* the project on top of each member's personal global file.
|
|
304
523
|
*/
|
|
305
|
-
export function localOverridePath(): string {
|
|
306
|
-
return join(process.cwd(), ".opencode", OVERRIDE_FILENAME);
|
|
524
|
+
export function localOverridePath(dir?: string): string {
|
|
525
|
+
return join(dir ? resolvePath(dir) : process.cwd(), ".opencode", OVERRIDE_FILENAME);
|
|
307
526
|
}
|
|
308
527
|
|
|
309
528
|
/**
|
|
@@ -323,10 +542,54 @@ const REPO_MARKERS = [".git", ".hg", ".svn"] as const;
|
|
|
323
542
|
*/
|
|
324
543
|
const MAX_WALK_DEPTH = 16;
|
|
325
544
|
|
|
545
|
+
/** errno code of a thrown fs error, or "UNKNOWN" when it carries none. */
|
|
546
|
+
function errnoCode(err: unknown): string {
|
|
547
|
+
const code = (err as NodeJS.ErrnoException | undefined)?.code;
|
|
548
|
+
return typeof code === "string" ? code : "UNKNOWN";
|
|
549
|
+
}
|
|
550
|
+
|
|
326
551
|
/**
|
|
327
|
-
*
|
|
328
|
-
*
|
|
329
|
-
*
|
|
552
|
+
* ENOENT (nothing there) and ENOTDIR (a path component is a file) both mean the
|
|
553
|
+
* path is gone. Every other errno (EACCES, EIO, ELOOP, …) means "cannot tell",
|
|
554
|
+
* which is NOT the same as "removed".
|
|
555
|
+
*/
|
|
556
|
+
function isGoneError(err: unknown): boolean {
|
|
557
|
+
const code = errnoCode(err);
|
|
558
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** A stat that failed for a reason other than the path being gone. */
|
|
562
|
+
interface StatFailure {
|
|
563
|
+
code: string;
|
|
564
|
+
message: string;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* Outcome of looking at a config source: it is there, it is definitely gone, or
|
|
569
|
+
* it could not be inspected. Unlike `existsSync` — which folds every error into
|
|
570
|
+
* `false` — this keeps "removed" and "unreachable" apart, so a transient I/O
|
|
571
|
+
* error or a directory that lost search permission is never mistaken for the
|
|
572
|
+
* user deleting the file.
|
|
573
|
+
*/
|
|
574
|
+
type StatKind = "present" | "missing" | StatFailure;
|
|
575
|
+
|
|
576
|
+
function statKind(p: string): StatKind {
|
|
577
|
+
try {
|
|
578
|
+
statSync(p);
|
|
579
|
+
return "present";
|
|
580
|
+
} catch (err) {
|
|
581
|
+
if (isGoneError(err)) return "missing";
|
|
582
|
+
return { code: errnoCode(err), message: (err as Error).message };
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Locate the project-local overrides file by walking upward from `dir` (the
|
|
588
|
+
* host-provided project directory), so the project config is found even when
|
|
589
|
+
* opencode is launched from a subdirectory. When `dir` is omitted the walk
|
|
590
|
+
* starts at the process working directory; hosts that change the working
|
|
591
|
+
* directory away from the project (OpenCode v2 server mode chdirs to $HOME)
|
|
592
|
+
* must pass the project directory explicitly.
|
|
330
593
|
*
|
|
331
594
|
* The walk stops at the first of these, whichever comes first:
|
|
332
595
|
* - an ancestor containing a repo marker (`.git`, `.hg`, `.svn`), after
|
|
@@ -340,28 +603,34 @@ const MAX_WALK_DEPTH = 16;
|
|
|
340
603
|
* tree with no repo marker anywhere would otherwise be walked all the way to the
|
|
341
604
|
* filesystem root, silently adopting an unrelated ancestor's override file.
|
|
342
605
|
* Returns the resolved path, or undefined when no file applies.
|
|
606
|
+
*
|
|
607
|
+
* Only ENOENT/ENOTDIR count as "no file here". A candidate that cannot be
|
|
608
|
+
* inspected for any other reason (EACCES on a parent directory, a transient
|
|
609
|
+
* I/O error) is still returned and ends the walk — the nearest override wins,
|
|
610
|
+
* so it must not be skipped in favour of an ancestor's file — and the later
|
|
611
|
+
* read reports it as a failure instead of the source silently vanishing. A
|
|
612
|
+
* repo marker that cannot be inspected is likewise treated as present, so the
|
|
613
|
+
* walk never climbs past a project root it merely failed to stat.
|
|
343
614
|
*/
|
|
344
|
-
export function findProjectOverride(): string | undefined {
|
|
615
|
+
export function findProjectOverride(dir?: string): string | undefined {
|
|
616
|
+
return walkForProjectOverride(normalizeProjectDir(dir));
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** `startDir` must already be normalized (see {@link normalizeProjectDir}). */
|
|
620
|
+
function walkForProjectOverride(startDir: string): string | undefined {
|
|
345
621
|
// Both sides of the $HOME comparison below have to be resolved the same way.
|
|
346
622
|
// process.cwd() returns a realpath, while homedir() returns $HOME verbatim, so
|
|
347
623
|
// on any system where $HOME contains a symlinked component (macOS temp dirs,
|
|
348
624
|
// containers, some NFS homes) a raw string compare never matches and the home
|
|
349
|
-
// boundary silently stops applying.
|
|
350
|
-
//
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
} catch {
|
|
355
|
-
return p;
|
|
356
|
-
}
|
|
357
|
-
};
|
|
358
|
-
|
|
359
|
-
let dir = resolve(process.cwd());
|
|
360
|
-
const home = resolve(homedir());
|
|
625
|
+
// boundary silently stops applying. A host-provided project directory gets
|
|
626
|
+
// the same treatment (normalizeProjectDir). Fail soft: an unresolvable path
|
|
627
|
+
// is used as-is, which is no worse than not comparing at all.
|
|
628
|
+
let dir = startDir;
|
|
629
|
+
const home = realpathOrSelf(homedir());
|
|
361
630
|
let depth = 0;
|
|
362
631
|
|
|
363
632
|
for (;;) {
|
|
364
|
-
const hasMarker = REPO_MARKERS.some((m) =>
|
|
633
|
+
const hasMarker = REPO_MARKERS.some((m) => statKind(join(dir, m)) !== "missing");
|
|
365
634
|
|
|
366
635
|
// $HOME is not a project directory. Only look inside it when it is itself a
|
|
367
636
|
// repo root (a dotfiles repo), otherwise `~/.opencode/…` would be picked up
|
|
@@ -369,7 +638,7 @@ export function findProjectOverride(): string | undefined {
|
|
|
369
638
|
if (dir === home && !hasMarker) return undefined;
|
|
370
639
|
|
|
371
640
|
const candidate = join(dir, ".opencode", OVERRIDE_FILENAME);
|
|
372
|
-
if (
|
|
641
|
+
if (statKind(candidate) !== "missing") return candidate;
|
|
373
642
|
|
|
374
643
|
if (hasMarker) return undefined; // reached the project root, no file
|
|
375
644
|
if (dir === home) return undefined; // home was a repo root; never go above it
|
|
@@ -451,6 +720,7 @@ function validatePresets(obj: Record<string, unknown>): Record<string, unknown>
|
|
|
451
720
|
throw new Error(`tiers.json: preset '${presetName}' must be an object`);
|
|
452
721
|
}
|
|
453
722
|
const tiers = preset as Record<string, unknown>;
|
|
723
|
+
const presetRungs: PresetRung[] = [];
|
|
454
724
|
for (const [tierName, tier] of Object.entries(tiers)) {
|
|
455
725
|
if (typeof tier !== "object" || tier === null) {
|
|
456
726
|
throw new Error(
|
|
@@ -509,7 +779,40 @@ function validatePresets(obj: Record<string, unknown>): Record<string, unknown>
|
|
|
509
779
|
`tiers.json: preset '${presetName}' tier '${tierName}': promptStyle must be one of ${PROMPT_STYLES.join("|")}`,
|
|
510
780
|
);
|
|
511
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
|
+
}
|
|
512
814
|
}
|
|
815
|
+
assertConsistentRungCosts(presetName, presetRungs);
|
|
513
816
|
}
|
|
514
817
|
|
|
515
818
|
return presets;
|
|
@@ -745,6 +1048,17 @@ function describeValue(value: unknown): string {
|
|
|
745
1048
|
return `${description.slice(0, end)}…`;
|
|
746
1049
|
}
|
|
747
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
|
+
|
|
748
1062
|
/** Copy without invoking accessors again; include defined get-only Proxy values. */
|
|
749
1063
|
function withValidatedSnapshots<T extends object>(
|
|
750
1064
|
obj: T,
|
|
@@ -965,7 +1279,13 @@ function validateEnforcement(value: unknown): Record<string, unknown> | undefine
|
|
|
965
1279
|
`tiers.json: enforcement.escalate.effortBumpMax must be one of ${EFFORT_LEVELS.join("|")} (got ${describeValue(effortBumpMax)})`,
|
|
966
1280
|
);
|
|
967
1281
|
}
|
|
968
|
-
|
|
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 });
|
|
969
1289
|
if (
|
|
970
1290
|
escalate.costCeiling !== undefined &&
|
|
971
1291
|
typeof escalate.costCeiling === "object" &&
|
|
@@ -1102,6 +1422,579 @@ function validateEnforcement(value: unknown): Record<string, unknown> | undefine
|
|
|
1102
1422
|
}
|
|
1103
1423
|
}
|
|
1104
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
|
+
|
|
1105
1998
|
/**
|
|
1106
1999
|
* Validate a raw parsed config. Strict and throwing by design: the bundled
|
|
1107
2000
|
* tiers.json must be valid on its own, and loadConfig turns a throw from an
|
|
@@ -1140,9 +2033,10 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
1140
2033
|
validateDispatchHeader(obj);
|
|
1141
2034
|
validateTaskPromptRepair(obj);
|
|
1142
2035
|
validateFalseRefusalDetection(obj);
|
|
2036
|
+
const routing = validateRouting(obj.routing);
|
|
1143
2037
|
|
|
1144
2038
|
const cfg = raw as RouterConfig;
|
|
1145
|
-
return withValidatedSnapshots(cfg, { enforcement });
|
|
2039
|
+
return withValidatedSnapshots(cfg, { enforcement, routing });
|
|
1146
2040
|
}
|
|
1147
2041
|
|
|
1148
2042
|
/**
|
|
@@ -1179,38 +2073,58 @@ export function deepMerge(base: unknown, override: unknown): unknown {
|
|
|
1179
2073
|
* overrides file can never brick opencode startup — but the user still gets a
|
|
1180
2074
|
* visible reason why their override was ignored.
|
|
1181
2075
|
*/
|
|
1182
|
-
function readOverridesAt(
|
|
2076
|
+
function readOverridesAt(
|
|
2077
|
+
op: string,
|
|
2078
|
+
failures?: SourceFailure[],
|
|
2079
|
+
): Record<string, unknown> | undefined {
|
|
2080
|
+
// Only ENOENT/ENOTDIR mean the file is absent. Any other stat error (EACCES on
|
|
2081
|
+
// a parent directory, a transient I/O error) is a failure, never a removal —
|
|
2082
|
+
// otherwise a reload would swap the last valid config for lower-priority
|
|
2083
|
+
// defaults.
|
|
2084
|
+
const kind = statKind(op);
|
|
2085
|
+
if (kind === "missing") return undefined;
|
|
2086
|
+
|
|
1183
2087
|
let text: string;
|
|
1184
2088
|
try {
|
|
1185
|
-
if (
|
|
2089
|
+
if (kind !== "present") throw new Error(kind.message);
|
|
1186
2090
|
text = readFileSync(op, "utf-8");
|
|
1187
2091
|
} catch (err) {
|
|
1188
2092
|
// The file is there but unreadable (permissions, a dangling symlink, a
|
|
1189
2093
|
// race with a delete). Every other failure below says so; staying silent
|
|
1190
2094
|
// here makes an unreadable override look exactly like an absent one.
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
);
|
|
2095
|
+
const reason = `cannot read it — ${(err as Error).message}`;
|
|
2096
|
+
console.warn(`[model-router] ignoring ${op}: ${reason}`);
|
|
2097
|
+
failures?.push({ source: op, message: `${op}: ${reason}` });
|
|
1194
2098
|
return undefined;
|
|
1195
2099
|
}
|
|
1196
2100
|
|
|
1197
2101
|
try {
|
|
1198
2102
|
const parsed = parseJsonc(text) as unknown;
|
|
1199
2103
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
);
|
|
2104
|
+
const reason = "expected a JSON object at root";
|
|
2105
|
+
console.warn(`[model-router] ignoring ${op}: ${reason}`);
|
|
2106
|
+
failures?.push({ source: op, message: `${op}: ${reason}` });
|
|
1203
2107
|
return undefined;
|
|
1204
2108
|
}
|
|
1205
2109
|
return parsed as Record<string, unknown>;
|
|
1206
2110
|
} catch (err) {
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
);
|
|
2111
|
+
const reason = `invalid JSONC — ${(err as Error).message}`;
|
|
2112
|
+
console.warn(`[model-router] ignoring ${op}: ${reason}`);
|
|
2113
|
+
failures?.push({ source: op, message: `${op}: ${reason}` });
|
|
1210
2114
|
return undefined;
|
|
1211
2115
|
}
|
|
1212
2116
|
}
|
|
1213
2117
|
|
|
2118
|
+
/**
|
|
2119
|
+
* A source that exists on disk but could not be used while building the
|
|
2120
|
+
* config. `source` is a stable key (a file path, or the joined layer paths for
|
|
2121
|
+
* a combined-merge failure); `message` is the user-facing reason.
|
|
2122
|
+
*/
|
|
2123
|
+
interface SourceFailure {
|
|
2124
|
+
source: string;
|
|
2125
|
+
message: string;
|
|
2126
|
+
}
|
|
2127
|
+
|
|
1214
2128
|
/**
|
|
1215
2129
|
* The ordered override layers (lowest priority first): global, then
|
|
1216
2130
|
* project-local. Each present, well-formed file becomes a layer that is
|
|
@@ -1219,20 +2133,118 @@ function readOverridesAt(op: string): Record<string, unknown> | undefined {
|
|
|
1219
2133
|
export interface OverrideLayer {
|
|
1220
2134
|
path: string;
|
|
1221
2135
|
data: Record<string, unknown>;
|
|
2136
|
+
project?: boolean;
|
|
1222
2137
|
}
|
|
1223
2138
|
|
|
1224
|
-
|
|
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[] {
|
|
1225
2184
|
const layers: OverrideLayer[] = [];
|
|
1226
|
-
// Lowest priority first: global, then project-local (found by upward search
|
|
1227
|
-
|
|
1228
|
-
|
|
2185
|
+
// Lowest priority first: global, then project-local (found by upward search
|
|
2186
|
+
// from the project directory).
|
|
2187
|
+
const sources = [
|
|
2188
|
+
{ path: overridePath(), project: false },
|
|
2189
|
+
{ path: walkForProjectOverride(dir), project: true },
|
|
2190
|
+
];
|
|
2191
|
+
for (const { path: p, project } of sources) {
|
|
1229
2192
|
if (!p) continue;
|
|
1230
|
-
const data = readOverridesAt(p);
|
|
1231
|
-
if (data)
|
|
2193
|
+
const data = readOverridesAt(p, failures);
|
|
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 });
|
|
1232
2205
|
}
|
|
1233
2206
|
return layers;
|
|
1234
2207
|
}
|
|
1235
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
|
+
|
|
1236
2248
|
/**
|
|
1237
2249
|
* Canonical per-tier defaults, keyed by the conventional tier names. These are
|
|
1238
2250
|
* the same values every bundled preset uses, so a preset defined in an overrides
|
|
@@ -1245,6 +2257,11 @@ const TIER_DEFAULTS: Record<string, { costRatio: number; steps: number }> = {
|
|
|
1245
2257
|
};
|
|
1246
2258
|
const FALLBACK_TIER_DEFAULTS = { costRatio: 1, steps: 50 };
|
|
1247
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
|
+
|
|
1248
2265
|
/**
|
|
1249
2266
|
* Fill in `costRatio`/`steps` for any tier that omits them, by tier name. Runs
|
|
1250
2267
|
* after merge so override-defined presets behave well without restating the
|
|
@@ -1254,31 +2271,308 @@ const FALLBACK_TIER_DEFAULTS = { costRatio: 1, steps: 50 };
|
|
|
1254
2271
|
function applyTierDefaults(cfg: RouterConfig): void {
|
|
1255
2272
|
for (const preset of Object.values(cfg.presets)) {
|
|
1256
2273
|
for (const [tierName, tier] of Object.entries(preset)) {
|
|
1257
|
-
const d =
|
|
2274
|
+
const d = tierDefaultsFor(tierName);
|
|
1258
2275
|
if (tier.costRatio === undefined) tier.costRatio = d.costRatio;
|
|
1259
2276
|
if (tier.steps === undefined) tier.steps = d.steps;
|
|
1260
2277
|
}
|
|
1261
2278
|
}
|
|
1262
2279
|
}
|
|
1263
2280
|
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
2281
|
+
/**
|
|
2282
|
+
* Every file location that feeds loadConfig() for the (normalized) project
|
|
2283
|
+
* directory `dir` (undefined = none applicable).
|
|
2284
|
+
*/
|
|
2285
|
+
function sourcePaths(dir: string): Array<string | undefined> {
|
|
2286
|
+
return [configPath(), overridePath(), walkForProjectOverride(dir), statePath()];
|
|
2287
|
+
}
|
|
2288
|
+
|
|
2289
|
+
/**
|
|
2290
|
+
* mtime/ctime/size fingerprint of every file that feeds loadConfig(). ctime is
|
|
2291
|
+
* included because restoring access to a previously unreadable file (chmod)
|
|
2292
|
+
* changes ctime but not mtime/size, and that must trigger a retry. Only
|
|
2293
|
+
* ENOENT/ENOTDIR map to `missing` (removal); any other stat error maps to
|
|
2294
|
+
* `error:<code>`, a distinct marker, so losing access to a file is never
|
|
2295
|
+
* fingerprinted — or reloaded — as if it had been deleted.
|
|
2296
|
+
*/
|
|
2297
|
+
function sourceFingerprint(paths: Array<string | undefined>): string {
|
|
2298
|
+
return paths
|
|
2299
|
+
.map((p) => {
|
|
2300
|
+
if (!p) return "none";
|
|
2301
|
+
try {
|
|
2302
|
+
const st = statSync(p);
|
|
2303
|
+
return `${p}:${st.mtimeMs}:${st.ctimeMs}:${st.size}`;
|
|
2304
|
+
} catch (err) {
|
|
2305
|
+
return isGoneError(err) ? `${p}:missing` : `${p}:error:${errnoCode(err)}`;
|
|
2306
|
+
}
|
|
2307
|
+
})
|
|
2308
|
+
.join("|");
|
|
2309
|
+
}
|
|
2310
|
+
|
|
2311
|
+
/**
|
|
2312
|
+
* Load the effective config for the project directory `dir` (the host-provided
|
|
2313
|
+
* project dir; defaults to the process working directory). Each directory has
|
|
2314
|
+
* its own cache entry, so several project instances sharing one process never
|
|
2315
|
+
* see or overwrite each other's config.
|
|
2316
|
+
*/
|
|
2317
|
+
export function loadConfig(dir?: string): RouterConfig {
|
|
2318
|
+
const projectDir = normalizeProjectDir(dir);
|
|
2319
|
+
const entry = getCacheEntry(projectDir);
|
|
2320
|
+
const paths = sourcePaths(projectDir);
|
|
2321
|
+
const fingerprint = sourceFingerprint(paths);
|
|
2322
|
+
if (entry.config && !entry.dirty && fingerprint === entry.fingerprint) {
|
|
2323
|
+
return entry.config;
|
|
2324
|
+
}
|
|
2325
|
+
|
|
2326
|
+
// A previous config is only a valid fallback when it was built for the same
|
|
2327
|
+
// project identity: HOME + the normalized project dir (the cache key) + the
|
|
2328
|
+
// state path. Deliberately NOT the resolved override file paths: a project
|
|
2329
|
+
// override created after startup must not turn a broken file into a
|
|
2330
|
+
// tolerated "first load".
|
|
2331
|
+
const sourceKey = [homedir(), projectDir, statePath()].join("|");
|
|
2332
|
+
const previous =
|
|
2333
|
+
entry.config !== null && sourceKey === entry.sourceKey ? entry.config : null;
|
|
2334
|
+
|
|
2335
|
+
const failures: SourceFailure[] = [];
|
|
2336
|
+
const notices: ConfigNotice[] = [];
|
|
2337
|
+
let cfg: RouterConfig;
|
|
2338
|
+
try {
|
|
2339
|
+
cfg = buildConfig(projectDir, failures, notices);
|
|
2340
|
+
} catch (err) {
|
|
2341
|
+
// First load: unchanged behaviour — throw. Reload: keep the last good one.
|
|
2342
|
+
if (!previous) throw err;
|
|
2343
|
+
return keepLastValidConfig(
|
|
2344
|
+
entry,
|
|
2345
|
+
previous,
|
|
2346
|
+
fingerprint,
|
|
2347
|
+
`${configPath()}: ${(err as Error).message}`,
|
|
2348
|
+
);
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
if (previous) {
|
|
2352
|
+
// Sources that were already failing when `previous` was built are an
|
|
2353
|
+
// accepted state (e.g. a broken override at startup); only a source that
|
|
2354
|
+
// newly broke counts as a failed reload.
|
|
2355
|
+
const regressions = failures.filter((f) => !entry.tolerated.has(f.source));
|
|
2356
|
+
if (regressions.length > 0) {
|
|
2357
|
+
return keepLastValidConfig(
|
|
2358
|
+
entry,
|
|
2359
|
+
previous,
|
|
2360
|
+
fingerprint,
|
|
2361
|
+
regressions.map((f) => f.message).join("\n"),
|
|
2362
|
+
);
|
|
2363
|
+
}
|
|
2364
|
+
}
|
|
2365
|
+
|
|
2366
|
+
entry.config = cfg;
|
|
2367
|
+
entry.fingerprint = fingerprint;
|
|
2368
|
+
entry.sourceKey = sourceKey;
|
|
2369
|
+
entry.tolerated = new Set(failures.map((f) => f.source));
|
|
2370
|
+
entry.dirty = false;
|
|
2371
|
+
entry.reloadError = null;
|
|
2372
|
+
entry.warnedFingerprint = null;
|
|
2373
|
+
entry.notices = notices;
|
|
2374
|
+
noticesByConfig.set(cfg, notices);
|
|
2375
|
+
return cfg;
|
|
2376
|
+
}
|
|
2377
|
+
|
|
2378
|
+
/**
|
|
2379
|
+
* Reload failed: keep serving `previous` (same object reference), remember the
|
|
2380
|
+
* fingerprint so we do not retry on every message until a file changes (or
|
|
2381
|
+
* invalidateConfigCache() is called), record the reason, and warn once per
|
|
2382
|
+
* failed fingerprint. All state lives on the directory's own cache `entry`.
|
|
2383
|
+
*/
|
|
2384
|
+
function keepLastValidConfig(
|
|
2385
|
+
entry: ConfigCacheEntry,
|
|
2386
|
+
previous: RouterConfig,
|
|
2387
|
+
fingerprint: string,
|
|
2388
|
+
message: string,
|
|
2389
|
+
): RouterConfig {
|
|
2390
|
+
entry.fingerprint = fingerprint;
|
|
2391
|
+
entry.dirty = false;
|
|
2392
|
+
entry.reloadError = message;
|
|
2393
|
+
if (entry.warnedFingerprint !== fingerprint) {
|
|
2394
|
+
entry.warnedFingerprint = fingerprint;
|
|
2395
|
+
console.warn(
|
|
2396
|
+
`[model-router] config reload failed — keeping last valid config: ${message}`,
|
|
2397
|
+
);
|
|
2398
|
+
}
|
|
2399
|
+
return previous;
|
|
2400
|
+
}
|
|
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
|
+
}
|
|
1267
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
|
+
}
|
|
1268
2546
|
|
|
2547
|
+
/**
|
|
2548
|
+
* Build a fresh config from tiers.json + override layers + persisted state.
|
|
2549
|
+
* Throws only when tiers.json itself is unreadable/invalid. Override and state
|
|
2550
|
+
* problems are warned about, skipped, and appended to `failures`.
|
|
2551
|
+
*/
|
|
2552
|
+
function buildConfig(
|
|
2553
|
+
dir: string,
|
|
2554
|
+
failures: SourceFailure[],
|
|
2555
|
+
notices: ConfigNotice[],
|
|
2556
|
+
): RouterConfig {
|
|
1269
2557
|
const base = JSON.parse(readFileSync(configPath(), "utf-8"));
|
|
1270
|
-
const layers = collectOverrideLayers();
|
|
2558
|
+
const layers = collectOverrideLayers(dir, failures, notices);
|
|
1271
2559
|
|
|
1272
2560
|
// Bundled config must be valid on its own — throw otherwise (unchanged
|
|
1273
2561
|
// behaviour). Override layers are then applied on top.
|
|
1274
2562
|
let cfg = validateConfig(base);
|
|
2563
|
+
let rawUsed: unknown = base;
|
|
1275
2564
|
|
|
1276
2565
|
if (layers.length > 0) {
|
|
1277
2566
|
const merge = (ls: OverrideLayer[]): unknown =>
|
|
1278
|
-
|
|
2567
|
+
replaceRolesWholesale(
|
|
2568
|
+
ls.reduce<unknown>((acc, l) => mergeOverrideLayer(acc, l, notices), base),
|
|
2569
|
+
ls,
|
|
2570
|
+
);
|
|
1279
2571
|
|
|
1280
2572
|
try {
|
|
1281
|
-
|
|
2573
|
+
const merged = merge(layers);
|
|
2574
|
+
cfg = validateConfig(merged);
|
|
2575
|
+
rawUsed = merged;
|
|
1282
2576
|
} catch (err) {
|
|
1283
2577
|
// A bad override must never brick startup, and one broken file must not
|
|
1284
2578
|
// discard a good one. Fall back to the highest-priority layer that
|
|
@@ -1287,9 +2581,16 @@ export function loadConfig(): RouterConfig {
|
|
|
1287
2581
|
console.warn(
|
|
1288
2582
|
`[model-router] combined overrides are invalid (${(err as Error).message}); dropping conflicting layer(s)`,
|
|
1289
2583
|
);
|
|
2584
|
+
const layerPaths = layers.map((l) => l.path).join(" + ");
|
|
2585
|
+
failures.push({
|
|
2586
|
+
source: layerPaths,
|
|
2587
|
+
message: `${layerPaths}: combined overrides are invalid — ${(err as Error).message}`,
|
|
2588
|
+
});
|
|
1290
2589
|
for (let i = layers.length - 1; i >= 0; i--) {
|
|
1291
2590
|
try {
|
|
1292
|
-
|
|
2591
|
+
const single = merge([layers[i]!]);
|
|
2592
|
+
cfg = validateConfig(single);
|
|
2593
|
+
rawUsed = single;
|
|
1293
2594
|
for (let j = 0; j < layers.length; j++) {
|
|
1294
2595
|
if (j !== i) {
|
|
1295
2596
|
console.warn(`[model-router] dropped override layer ${layers[j]!.path}`);
|
|
@@ -1300,14 +2601,24 @@ export function loadConfig(): RouterConfig {
|
|
|
1300
2601
|
console.warn(
|
|
1301
2602
|
`[model-router] ignoring ${layers[i]!.path}: ${(singleErr as Error).message}`,
|
|
1302
2603
|
);
|
|
2604
|
+
failures.push({
|
|
2605
|
+
source: layers[i]!.path,
|
|
2606
|
+
message: `${layers[i]!.path}: ${(singleErr as Error).message}`,
|
|
2607
|
+
});
|
|
1303
2608
|
cfg = validateConfig(base);
|
|
2609
|
+
rawUsed = base;
|
|
1304
2610
|
}
|
|
1305
2611
|
}
|
|
1306
2612
|
}
|
|
1307
2613
|
}
|
|
1308
2614
|
|
|
1309
2615
|
try {
|
|
1310
|
-
|
|
2616
|
+
const stateKind = statKind(statePath());
|
|
2617
|
+
if (stateKind !== "missing") {
|
|
2618
|
+
// Present-but-uninspectable (EACCES, EIO, …) is a failure, not an absent
|
|
2619
|
+
// state file: reverting the persisted preset on a transient error would
|
|
2620
|
+
// be silent data loss.
|
|
2621
|
+
if (stateKind !== "present") throw new Error(`cannot read it — ${stateKind.message}`);
|
|
1311
2622
|
const state = JSON.parse(
|
|
1312
2623
|
readFileSync(statePath(), "utf-8"),
|
|
1313
2624
|
) as RouterState;
|
|
@@ -1324,17 +2635,39 @@ export function loadConfig(): RouterConfig {
|
|
|
1324
2635
|
cfg.enforcement = { ...(cfg.enforcement ?? {}), mode: state.enforcementMode };
|
|
1325
2636
|
}
|
|
1326
2637
|
}
|
|
1327
|
-
} catch {
|
|
1328
|
-
//
|
|
2638
|
+
} catch (err) {
|
|
2639
|
+
// State read errors never block startup: keep tiers.json defaults. They are
|
|
2640
|
+
// recorded so a state file that breaks on a later reload is reported (and
|
|
2641
|
+
// the last valid config kept) rather than silently reverting the preset.
|
|
2642
|
+
failures.push({
|
|
2643
|
+
source: statePath(),
|
|
2644
|
+
message: `${statePath()}: ${(err as Error).message}`,
|
|
2645
|
+
});
|
|
1329
2646
|
}
|
|
1330
2647
|
|
|
1331
2648
|
applyTierDefaults(cfg);
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
2649
|
+
const rawRouting = isPlainObject(rawUsed) ? rawUsed.routing : undefined;
|
|
2650
|
+
for (const message of collectRoutingNotices(rawRouting, cfg)) notices.push({ message });
|
|
2651
|
+
dropIgnoredCandidates(cfg);
|
|
1335
2652
|
return cfg;
|
|
1336
2653
|
}
|
|
1337
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
|
+
|
|
1338
2671
|
// ---------------------------------------------------------------------------
|
|
1339
2672
|
// State persistence helpers
|
|
1340
2673
|
// ---------------------------------------------------------------------------
|
|
@@ -1490,3 +2823,294 @@ export function resolveVerifyBudget(
|
|
|
1490
2823
|
gateBudgetMs: own<number>("gateBudgetMs") ?? 90_000,
|
|
1491
2824
|
};
|
|
1492
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
|
+
}
|