opencode-model-router 2.2.0 → 2.4.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 +214 -0
- package/README.md +90 -12
- package/package.json +4 -1
- package/src/commands/output.ts +24 -1
- package/src/compat/child-session.ts +43 -0
- package/src/compat/v2-client.ts +107 -7
- package/src/compat/v2-hooks.ts +1435 -44
- package/src/escalate/attempt-recorder.ts +263 -0
- package/src/escalate/ladder.ts +496 -10
- package/src/escalate/resume.ts +208 -0
- package/src/escalate/variants.ts +391 -0
- package/src/guard/enforce.ts +186 -22
- package/src/guard/guards.ts +132 -6
- package/src/guard/store.ts +5 -0
- package/src/index.ts +1193 -56
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1611 -19
- package/src/router/dispatch-header.ts +46 -4
- package/src/router/git-tools.ts +1152 -0
- package/src/router/guard-profile.ts +100 -0
- package/src/router/plugin-agents.ts +433 -0
- package/src/router/prompts.ts +26 -1
- package/src/router/protocol.ts +180 -0
- package/src/router/read-only.ts +149 -0
- package/src/router/role-agents.ts +409 -0
- package/src/router/roles-config.ts +429 -0
- package/src/router/roles.ts +600 -0
- package/src/router/run-tools.ts +913 -0
- package/src/router/sensitive-paths.ts +101 -0
- package/src/router/sessions.ts +533 -9
- package/src/router/subagents.ts +28 -1
- package/src/routing/advisor/findings.ts +898 -0
- package/src/routing/advisor/index.ts +614 -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 +594 -0
- package/src/routing/classify/route-line.ts +362 -0
- package/src/routing/classify/rules.ts +667 -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 +1310 -0
- package/src/routing/commands/annotate-plan.ts +652 -0
- package/src/routing/commands/stats.ts +134 -0
- package/src/routing/commands/v1-roles.ts +64 -0
- package/src/routing/engine/index.ts +32 -0
- package/src/routing/engine/kernel.ts +760 -0
- package/src/routing/engine/ladders.ts +802 -0
- package/src/routing/engine/plan.ts +404 -0
- package/src/routing/engine/protocol-line.ts +150 -0
- package/src/routing/engine/roles-taxonomy.ts +52 -0
- package/src/routing/engine/simulate.ts +167 -0
- package/src/routing/engine/types.ts +368 -0
- package/src/routing/file-lock.ts +53 -0
- package/src/routing/outcomes/beta.ts +147 -0
- package/src/routing/outcomes/cost.ts +313 -0
- package/src/routing/outcomes/index.ts +215 -0
- package/src/routing/outcomes/ingest.ts +960 -0
- package/src/routing/outcomes/persist.ts +1080 -0
- package/src/routing/outcomes/signals.ts +650 -0
- package/src/routing/outcomes/stats.ts +873 -0
- package/src/routing/outcomes/store.ts +673 -0
- package/src/routing/outcomes/types.ts +1093 -0
- package/src/routing/roles/authority.ts +495 -0
- package/src/routing/roles/binding.ts +543 -0
- package/src/routing/roles/policy.ts +416 -0
- package/src/routing/roles/work-root.ts +132 -0
- package/src/routing/wire/dispatch.ts +2088 -0
- package/src/routing/wire/hint.ts +222 -0
- package/src/routing/wire/host-info.ts +256 -0
- package/src/routing/wire/runtime.ts +348 -0
- package/src/v2.ts +40 -1
- package/src/verify/checker.ts +249 -7
- package/src/verify/deterministic.ts +10 -1
- package/src/verify/dispatch.ts +63 -6
- package/src/verify/dod.ts +127 -10
- package/src/verify/gate.ts +75 -7
- package/src/verify/types.ts +12 -0
- package/src/verify/wiring.ts +55 -10
- package/tiers.json +13 -5
package/src/router/config.ts
CHANGED
|
@@ -8,11 +8,29 @@ import {
|
|
|
8
8
|
writeFileSync,
|
|
9
9
|
} from "node:fs";
|
|
10
10
|
import { availableParallelism, homedir } from "node:os";
|
|
11
|
-
import { dirname, join, resolve as resolvePath } from "node:path";
|
|
11
|
+
import { dirname, isAbsolute, join, resolve as resolvePath } from "node:path";
|
|
12
12
|
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { formatRouterLine } from "./build-info";
|
|
13
14
|
import { parseJsonc } from "./jsonc";
|
|
14
15
|
import type { DelegateInstructionsPolicy } from "./instructions";
|
|
15
16
|
import type { PluginLogger } from "./logger";
|
|
17
|
+
import { sanitizePluginAgents, type PluginAgentConfig } from "./plugin-agents";
|
|
18
|
+
// Runtime cycle config <-> roles: both sides use the other only inside functions, never at module evaluation.
|
|
19
|
+
import { resolveRoleTable, type ExplorationConfig, type RunConfig } from "./roles";
|
|
20
|
+
import {
|
|
21
|
+
DEFAULT_RUN_COMMANDS,
|
|
22
|
+
DEFAULT_RUN_SCRIPTS,
|
|
23
|
+
DEFAULT_RUN_TIMEOUT_MS,
|
|
24
|
+
ROLES_V1_NOTICE,
|
|
25
|
+
collectRolesIssues,
|
|
26
|
+
sanitizeDelegation,
|
|
27
|
+
sanitizeExploration,
|
|
28
|
+
sanitizeRoleAgents,
|
|
29
|
+
sanitizeRun,
|
|
30
|
+
sanitizeWorkRoots,
|
|
31
|
+
type DelegationMode,
|
|
32
|
+
type RoleAgentCustomisation,
|
|
33
|
+
} from "./roles-config";
|
|
16
34
|
|
|
17
35
|
/**
|
|
18
36
|
* Filename of the optional user overrides file (global and project copies share
|
|
@@ -84,6 +102,8 @@ export const DEFAULT_STRONG_MODEL_PATTERNS = [
|
|
|
84
102
|
|
|
85
103
|
export interface TierConfig {
|
|
86
104
|
model: string;
|
|
105
|
+
/** Host-enforced read-only tools. Defaults to true for fast, false otherwise. */
|
|
106
|
+
readOnly?: boolean;
|
|
87
107
|
variant?: string;
|
|
88
108
|
/**
|
|
89
109
|
* Provider-agnostic effort. Loses to an explicit `thinking` budget on
|
|
@@ -106,6 +126,12 @@ export interface TierConfig {
|
|
|
106
126
|
promptStyle?: PromptStyle;
|
|
107
127
|
/** Optional use-case hints shown in `/tiers`. */
|
|
108
128
|
whenToUse?: string[];
|
|
129
|
+
/**
|
|
130
|
+
* Ordered `(model, variant, costRatio)` rungs the routing engine may use for
|
|
131
|
+
* this tier. Absent or empty = the tier's own single `(model, variant,
|
|
132
|
+
* costRatio)`. See {@link resolveCandidates}.
|
|
133
|
+
*/
|
|
134
|
+
candidates?: TierCandidate[];
|
|
109
135
|
}
|
|
110
136
|
|
|
111
137
|
export type Preset = Record<string, TierConfig>;
|
|
@@ -171,14 +197,140 @@ export interface EnforcementConfig {
|
|
|
171
197
|
failureRecheck?: boolean;
|
|
172
198
|
/** Budget for the reference re-run, in ms (integer >= 1). Default 60000. */
|
|
173
199
|
recheckTimeoutMs?: number };
|
|
174
|
-
escalate?:
|
|
175
|
-
/** Bump reasoning effort before escalating tiers. Default true. */
|
|
176
|
-
effortBump?: boolean;
|
|
177
|
-
/** Maximum reasoning effort for a bump. Default "xhigh". */
|
|
178
|
-
effortBumpMax?: EffortLevel };
|
|
200
|
+
escalate?: EscalateConfig;
|
|
179
201
|
proportional?: { trivialBypass?: boolean; trivialClassifier?: string };
|
|
180
202
|
}
|
|
181
203
|
|
|
204
|
+
export interface EscalateConfig {
|
|
205
|
+
floorTier?: string | null;
|
|
206
|
+
ladder?: string[];
|
|
207
|
+
maxAttemptsPerTier?: number;
|
|
208
|
+
maxTotalAttempts?: number;
|
|
209
|
+
costCeiling?: { base?: string; multiple?: number };
|
|
210
|
+
/** Bump reasoning effort before escalating tiers. Default true. */
|
|
211
|
+
effortBump?: boolean;
|
|
212
|
+
/** Maximum reasoning effort for a bump. Default "xhigh". */
|
|
213
|
+
effortBumpMax?: EffortLevel;
|
|
214
|
+
/**
|
|
215
|
+
* Retry on the same model's next variant before escalating the model (D10).
|
|
216
|
+
* OpenCode v2 only; ignored on v1. Default "auto".
|
|
217
|
+
*/
|
|
218
|
+
variantSteps?: VariantStepsMode;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ---------------------------------------------------------------------------
|
|
222
|
+
// Cost-aware routing (#74): the `routing` block, tier candidates, variant steps
|
|
223
|
+
// ---------------------------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
/** `static` = the shipped taxonomy only; the others add the engine of #74. */
|
|
226
|
+
export const ROUTING_ENGINES = ["static", "shadow", "advise", "enforce"] as const;
|
|
227
|
+
export type RoutingEngine = (typeof ROUTING_ENGINES)[number];
|
|
228
|
+
|
|
229
|
+
/** How much a wrong, undetected result is worth in the expected-cost formula (D8). */
|
|
230
|
+
export const ROUTING_PROFILES = ["frugal", "balanced", "safe"] as const;
|
|
231
|
+
export type RoutingProfile = (typeof ROUTING_PROFILES)[number];
|
|
232
|
+
|
|
233
|
+
export const CLASSIFIER_BACKENDS = ["rules", "host", "openai-compatible", "typesafe"] as const;
|
|
234
|
+
export type ClassifierBackend = (typeof CLASSIFIER_BACKENDS)[number];
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* The task classes `routing.roles` may name. The classifier (Phase 1.2) assigns
|
|
238
|
+
* one of these to every dispatch; `other` is the catch-all.
|
|
239
|
+
*/
|
|
240
|
+
export const ROUTING_TASK_CLASSES = [
|
|
241
|
+
"search",
|
|
242
|
+
"recon",
|
|
243
|
+
"mechanical",
|
|
244
|
+
"implement",
|
|
245
|
+
"debug",
|
|
246
|
+
"design",
|
|
247
|
+
"review",
|
|
248
|
+
"other",
|
|
249
|
+
] as const;
|
|
250
|
+
export type RoutingTaskClass = (typeof ROUTING_TASK_CLASSES)[number];
|
|
251
|
+
|
|
252
|
+
export const VARIANT_STEP_MODES = ["auto", "none"] as const;
|
|
253
|
+
export type VariantStepsMode = (typeof VARIANT_STEP_MODES)[number];
|
|
254
|
+
|
|
255
|
+
/** Which host runs the plugin; `v2` is OpenCode v2 (D1). */
|
|
256
|
+
export type RouterHost = "v1" | "v2";
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* One rung of a tier's ladder. `model` falls back to the tier's own model;
|
|
260
|
+
* `variant` is NOT inherited (omitted = the model's default variant); `costRatio`
|
|
261
|
+
* falls back to the tier's.
|
|
262
|
+
*/
|
|
263
|
+
export interface TierCandidate {
|
|
264
|
+
model?: string;
|
|
265
|
+
variant?: string;
|
|
266
|
+
costRatio?: number;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Verification-depth → probability that a wrong result is caught (D8). */
|
|
270
|
+
export interface DetectionConfig {
|
|
271
|
+
deterministic?: number;
|
|
272
|
+
grader?: number;
|
|
273
|
+
none?: number;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Per-preset override of the classifier's `backend` / `model`. */
|
|
277
|
+
export interface ClassifierPresetOverride {
|
|
278
|
+
backend?: ClassifierBackend;
|
|
279
|
+
model?: string | null;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export interface ClassifierConfig {
|
|
283
|
+
backend?: ClassifierBackend;
|
|
284
|
+
/** Catalog ref `provider/model[#variant]`; required when the effective backend is not `rules` (D3). */
|
|
285
|
+
model?: string | null;
|
|
286
|
+
/** `openai-compatible` / `typesafe` only. */
|
|
287
|
+
baseUrl?: string | null;
|
|
288
|
+
apiKeyEnv?: string | null;
|
|
289
|
+
timeoutMs?: number;
|
|
290
|
+
samples?: 1 | 3;
|
|
291
|
+
maxStateChars?: number;
|
|
292
|
+
presets?: Record<string, ClassifierPresetOverride>;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export interface OutcomesConfig {
|
|
296
|
+
path?: string | null;
|
|
297
|
+
halfLifeDays?: number;
|
|
298
|
+
maxEffectiveSamples?: number;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export interface SessionReuseConfig {
|
|
302
|
+
maxContextFraction?: number;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export interface AdvisorConfig {
|
|
306
|
+
enabled?: boolean;
|
|
307
|
+
noticeIntervalHours?: number;
|
|
308
|
+
/** `false` = the cost doctor never notifies (the `/router` section stays). Default `true`. */
|
|
309
|
+
notify?: boolean;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export interface RoutingConfig {
|
|
313
|
+
engine?: RoutingEngine;
|
|
314
|
+
profile?: RoutingProfile;
|
|
315
|
+
margin?: number;
|
|
316
|
+
minClassConfidence?: number;
|
|
317
|
+
detection?: DetectionConfig;
|
|
318
|
+
classifier?: ClassifierConfig;
|
|
319
|
+
/** Task class → ordered agent ids. Absent = host default (D12); `{}` = none. */
|
|
320
|
+
roles?: Record<string, string[]>;
|
|
321
|
+
outcomes?: OutcomesConfig;
|
|
322
|
+
sessionReuse?: SessionReuseConfig;
|
|
323
|
+
advisor?: AdvisorConfig;
|
|
324
|
+
/** `tiers` (default) or `roles`; global and project layers. Inert on v1. */
|
|
325
|
+
delegation?: DelegationMode;
|
|
326
|
+
/** Global only. `rate` 0..0.2, default 0; `requireDetection` is fixed. Inert on v1. */
|
|
327
|
+
exploration?: Partial<ExplorationConfig>;
|
|
328
|
+
/** Global only. `router_run` allow-list. Inert on v1. */
|
|
329
|
+
run?: Partial<RunConfig>;
|
|
330
|
+
/** Global only. Absolute globs with a static long-form prefix; default none. */
|
|
331
|
+
workRoots?: string[];
|
|
332
|
+
}
|
|
333
|
+
|
|
182
334
|
export interface RouterConfig {
|
|
183
335
|
/**
|
|
184
336
|
* Detect a delegate that hands a dispatch back having made zero tool calls
|
|
@@ -251,8 +403,24 @@ export interface RouterConfig {
|
|
|
251
403
|
* subagents; a primary agent is the orchestrator.
|
|
252
404
|
*/
|
|
253
405
|
subagentTiers?: Record<string, string>;
|
|
406
|
+
/**
|
|
407
|
+
* Subagents defined by the router config instead of opencode.json (#81):
|
|
408
|
+
* name → tier, description, optional prompt/steps and a router-published
|
|
409
|
+
* permission policy (`readOnly` and/or `permission`, plus `allowTools`).
|
|
410
|
+
* Only tiers.json and the global override may set it (A18). Validated per
|
|
411
|
+
* entry after merge: a bad entry is dropped with a config notice, never the
|
|
412
|
+
* layer. Absent ⇒ nothing is registered.
|
|
413
|
+
*/
|
|
414
|
+
agents?: Record<string, PluginAgentConfig>;
|
|
415
|
+
/**
|
|
416
|
+
* Narrowing-only customisation of the shipped role agents (agent name → partial spec).
|
|
417
|
+
* tiers.json and the global override only; validated per entry, never dropping the layer.
|
|
418
|
+
*/
|
|
419
|
+
roleAgents?: Record<string, RoleAgentCustomisation>;
|
|
254
420
|
/** Experimental, opt-in features. Off by default. */
|
|
255
421
|
experimental?: { verifiedDelegateTool?: boolean };
|
|
422
|
+
/** Cost-aware routing engine (#74). Absent = today's static routing, byte for byte. */
|
|
423
|
+
routing?: RoutingConfig;
|
|
256
424
|
}
|
|
257
425
|
|
|
258
426
|
export interface RouterState {
|
|
@@ -283,6 +451,8 @@ interface ConfigCacheEntry {
|
|
|
283
451
|
reloadError: string | null;
|
|
284
452
|
/** Fingerprint a reload-failure warning was last emitted for (warn once each). */
|
|
285
453
|
warnedFingerprint: string | null;
|
|
454
|
+
/** Non-fatal findings of the build that produced `config` (see {@link getConfigNotices}). */
|
|
455
|
+
notices: ConfigNotice[];
|
|
286
456
|
}
|
|
287
457
|
|
|
288
458
|
/** Keyed by {@link normalizeProjectDir}. */
|
|
@@ -299,6 +469,7 @@ function getCacheEntry(key: string): ConfigCacheEntry {
|
|
|
299
469
|
tolerated: new Set<string>(),
|
|
300
470
|
reloadError: null,
|
|
301
471
|
warnedFingerprint: null,
|
|
472
|
+
notices: [],
|
|
302
473
|
};
|
|
303
474
|
_configCaches.set(key, entry);
|
|
304
475
|
}
|
|
@@ -327,6 +498,24 @@ function normalizeProjectDir(dir?: string): string {
|
|
|
327
498
|
return realpathOrSelf(dir ? resolvePath(dir) : process.cwd());
|
|
328
499
|
}
|
|
329
500
|
|
|
501
|
+
/**
|
|
502
|
+
* A non-fatal finding of a config build: something was ignored or looks wrong,
|
|
503
|
+
* but the config still loaded. `source` is the file concerned, when one is.
|
|
504
|
+
*/
|
|
505
|
+
export interface ConfigNotice {
|
|
506
|
+
source?: string;
|
|
507
|
+
message: string;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* The notices of the config last built for `dir` (default: the working
|
|
512
|
+
* directory): keys dropped from the project layer, unknown `routing` keys, and
|
|
513
|
+
* the like. Empty when there are none. `/router` lists them.
|
|
514
|
+
*/
|
|
515
|
+
export function getConfigNotices(dir?: string): readonly ConfigNotice[] {
|
|
516
|
+
return _configCaches.get(normalizeProjectDir(dir))?.notices ?? [];
|
|
517
|
+
}
|
|
518
|
+
|
|
330
519
|
/**
|
|
331
520
|
* Why the last config rebuild failed for `dir` (default: the working
|
|
332
521
|
* directory), or null when it succeeded. When a source (tiers.json, an
|
|
@@ -572,6 +761,7 @@ function validatePresets(obj: Record<string, unknown>): Record<string, unknown>
|
|
|
572
761
|
throw new Error(`tiers.json: preset '${presetName}' must be an object`);
|
|
573
762
|
}
|
|
574
763
|
const tiers = preset as Record<string, unknown>;
|
|
764
|
+
const presetRungs: PresetRung[] = [];
|
|
575
765
|
for (const [tierName, tier] of Object.entries(tiers)) {
|
|
576
766
|
if (typeof tier !== "object" || tier === null) {
|
|
577
767
|
throw new Error(
|
|
@@ -579,6 +769,9 @@ function validatePresets(obj: Record<string, unknown>): Record<string, unknown>
|
|
|
579
769
|
);
|
|
580
770
|
}
|
|
581
771
|
const t = tier as Record<string, unknown>;
|
|
772
|
+
if (t.readOnly !== undefined && typeof t.readOnly !== "boolean") {
|
|
773
|
+
throw new Error(`tiers.json: '${presetName}.${tierName}.readOnly' must be a boolean`);
|
|
774
|
+
}
|
|
582
775
|
// `model` is the only required tier field — so an overrides file can define
|
|
583
776
|
// a new preset/tier with just `{ "model": "..." }`. The rest are optional
|
|
584
777
|
// and only type-checked when present.
|
|
@@ -630,7 +823,40 @@ function validatePresets(obj: Record<string, unknown>): Record<string, unknown>
|
|
|
630
823
|
`tiers.json: preset '${presetName}' tier '${tierName}': promptStyle must be one of ${PROMPT_STYLES.join("|")}`,
|
|
631
824
|
);
|
|
632
825
|
}
|
|
826
|
+
// The tier's own variant is what a candidates list is matched against.
|
|
827
|
+
if (t.variant !== undefined && (typeof t.variant !== "string" || !VARIANT_ID_PATTERN.test(t.variant))) {
|
|
828
|
+
throw new Error(
|
|
829
|
+
`tiers.json: '${presetName}.${tierName}.variant' must be a non-empty string without whitespace or '#' (got ${describeValue(t.variant)})`,
|
|
830
|
+
);
|
|
831
|
+
}
|
|
832
|
+
const candidates = validateTierCandidates(t, `${presetName}.${tierName}`, tierName);
|
|
833
|
+
const tierVariant = typeof t.variant === "string" ? t.variant : undefined;
|
|
834
|
+
const tierCostRatio = tierCostRatioOf(tierName, t.costRatio);
|
|
835
|
+
if (
|
|
836
|
+
candidates !== undefined &&
|
|
837
|
+
candidates.length > 0 &&
|
|
838
|
+
ownRungProblem(t.model, tierVariant, tierCostRatio, candidates) === undefined
|
|
839
|
+
) {
|
|
840
|
+
candidates.forEach((c, i) =>
|
|
841
|
+
presetRungs.push({
|
|
842
|
+
model: c.model ?? t.model as string,
|
|
843
|
+
variant: c.variant,
|
|
844
|
+
costRatio: c.costRatio ?? tierCostRatio,
|
|
845
|
+
source: `${tierName}.candidates[${i}]`,
|
|
846
|
+
explicit: true,
|
|
847
|
+
}),
|
|
848
|
+
);
|
|
849
|
+
} else {
|
|
850
|
+
presetRungs.push({
|
|
851
|
+
model: t.model,
|
|
852
|
+
variant: tierVariant,
|
|
853
|
+
costRatio: tierCostRatio,
|
|
854
|
+
source: `${tierName} (own rung)`,
|
|
855
|
+
explicit: false,
|
|
856
|
+
});
|
|
857
|
+
}
|
|
633
858
|
}
|
|
859
|
+
assertConsistentRungCosts(presetName, presetRungs);
|
|
634
860
|
}
|
|
635
861
|
|
|
636
862
|
return presets;
|
|
@@ -866,6 +1092,17 @@ function describeValue(value: unknown): string {
|
|
|
866
1092
|
return `${description.slice(0, end)}…`;
|
|
867
1093
|
}
|
|
868
1094
|
|
|
1095
|
+
/** Opt-in redaction for credential-capable paths, without changing legacy diagnostics. */
|
|
1096
|
+
function describeRoutingValue(value: unknown, path: string): string {
|
|
1097
|
+
const secretPath = /(?:^|\.)(?:classifier|typesafe|apiKey[^.]*|token|headers?)(?:\.|$)/i.test(path);
|
|
1098
|
+
// A malformed routing container can itself contain a nested classifier block.
|
|
1099
|
+
const routingContainer = path === "routing" && value !== null && typeof value === "object";
|
|
1100
|
+
if (!secretPath && !routingContainer) return describeValue(value);
|
|
1101
|
+
if (value === null) return "null";
|
|
1102
|
+
const kind = Array.isArray(value) ? "array" : typeof value;
|
|
1103
|
+
return `${kind}; value not shown`;
|
|
1104
|
+
}
|
|
1105
|
+
|
|
869
1106
|
/** Copy without invoking accessors again; include defined get-only Proxy values. */
|
|
870
1107
|
function withValidatedSnapshots<T extends object>(
|
|
871
1108
|
obj: T,
|
|
@@ -1086,7 +1323,13 @@ function validateEnforcement(value: unknown): Record<string, unknown> | undefine
|
|
|
1086
1323
|
`tiers.json: enforcement.escalate.effortBumpMax must be one of ${EFFORT_LEVELS.join("|")} (got ${describeValue(effortBumpMax)})`,
|
|
1087
1324
|
);
|
|
1088
1325
|
}
|
|
1089
|
-
|
|
1326
|
+
const variantSteps = escalate.variantSteps;
|
|
1327
|
+
if (variantSteps !== undefined && !pickEnum(VARIANT_STEP_MODES, variantSteps)) {
|
|
1328
|
+
throw new Error(
|
|
1329
|
+
`tiers.json: enforcement.escalate.variantSteps must be one of ${VARIANT_STEP_MODES.join("|")} (got ${describeValue(variantSteps)})`,
|
|
1330
|
+
);
|
|
1331
|
+
}
|
|
1332
|
+
snapshots.escalate = withValidatedSnapshots(escalate, { effortBump, effortBumpMax, variantSteps });
|
|
1090
1333
|
if (
|
|
1091
1334
|
escalate.costCeiling !== undefined &&
|
|
1092
1335
|
typeof escalate.costCeiling === "object" &&
|
|
@@ -1223,6 +1466,589 @@ function validateEnforcement(value: unknown): Record<string, unknown> | undefine
|
|
|
1223
1466
|
}
|
|
1224
1467
|
}
|
|
1225
1468
|
|
|
1469
|
+
// ---------------------------------------------------------------------------
|
|
1470
|
+
// Cost-aware routing validation (#74)
|
|
1471
|
+
//
|
|
1472
|
+
// Unknown keys inside `routing` are ignored, not rejected: that is the policy of
|
|
1473
|
+
// every other block in this file (see modelGenerations), so a config written for
|
|
1474
|
+
// a newer release still loads on an older one. The only keys refused are the
|
|
1475
|
+
// prototype-reparenting ones (rejectPrototypeKeys), as for `enforcement`.
|
|
1476
|
+
// Validators read every value exactly once and return a plain snapshot of what
|
|
1477
|
+
// they validated, so a config object cannot change between check and use.
|
|
1478
|
+
// ---------------------------------------------------------------------------
|
|
1479
|
+
|
|
1480
|
+
/**
|
|
1481
|
+
* Agent ids in `routing.roles`: host agent names, case-sensitive (an agent may be
|
|
1482
|
+
* called `ContextScout` or `team/helper`; QA-1.1-5). Nothing that could not be a
|
|
1483
|
+
* name: no empty id, no whitespace, no `#`.
|
|
1484
|
+
*/
|
|
1485
|
+
const AGENT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_./-]*$/;
|
|
1486
|
+
|
|
1487
|
+
/**
|
|
1488
|
+
* An agent id: {@link AGENT_ID_PATTERN}, and nothing path-like beyond a plain
|
|
1489
|
+
* `a/b`: no empty, `.` or `..` segment (`a//b`, `a/../b`, `a/./b`) and no
|
|
1490
|
+
* trailing `/` or `.` (QA-1.1-27).
|
|
1491
|
+
*/
|
|
1492
|
+
function isAgentId(id: string): boolean {
|
|
1493
|
+
return (
|
|
1494
|
+
AGENT_ID_PATTERN.test(id) &&
|
|
1495
|
+
!id.endsWith("/") &&
|
|
1496
|
+
!id.endsWith(".") &&
|
|
1497
|
+
!id.split("/").some((segment) => segment === "" || segment === "." || segment === "..")
|
|
1498
|
+
);
|
|
1499
|
+
}
|
|
1500
|
+
/** Environment variable names (`classifier.apiKeyEnv`). */
|
|
1501
|
+
const ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
1502
|
+
/** A variant id: non-empty, no whitespace, no `#` (the ref separator). */
|
|
1503
|
+
const VARIANT_ID_PATTERN = /^[^\s#]+$/;
|
|
1504
|
+
|
|
1505
|
+
/** `value` as a member of `allowed`, narrowed without a cast. */
|
|
1506
|
+
function pickEnum<T extends string>(allowed: readonly T[], value: unknown): T | undefined {
|
|
1507
|
+
return allowed.find((candidate) => candidate === value);
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
function readEnum<T extends string>(
|
|
1511
|
+
obj: Record<string, unknown>,
|
|
1512
|
+
key: string,
|
|
1513
|
+
path: string,
|
|
1514
|
+
allowed: readonly T[],
|
|
1515
|
+
): T | undefined {
|
|
1516
|
+
const value = obj[key];
|
|
1517
|
+
if (value === undefined) return undefined;
|
|
1518
|
+
const hit = pickEnum(allowed, value);
|
|
1519
|
+
if (hit === undefined) {
|
|
1520
|
+
throw new Error(
|
|
1521
|
+
`tiers.json: ${path}.${key} must be one of ${allowed.join("|")} (got ${describeRoutingValue(value, `${path}.${key}`)})`,
|
|
1522
|
+
);
|
|
1523
|
+
}
|
|
1524
|
+
return hit;
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
interface NumberRule {
|
|
1528
|
+
min: number;
|
|
1529
|
+
max: number;
|
|
1530
|
+
/** `min` itself is not allowed (an open lower bound). */
|
|
1531
|
+
minExclusive?: boolean;
|
|
1532
|
+
integer?: boolean;
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
function readNumber(
|
|
1536
|
+
obj: Record<string, unknown>,
|
|
1537
|
+
key: string,
|
|
1538
|
+
path: string,
|
|
1539
|
+
rule: NumberRule,
|
|
1540
|
+
): number | undefined {
|
|
1541
|
+
const value = obj[key];
|
|
1542
|
+
if (value === undefined) return undefined;
|
|
1543
|
+
const inRange =
|
|
1544
|
+
typeof value === "number" &&
|
|
1545
|
+
Number.isFinite(value) &&
|
|
1546
|
+
(!rule.integer || Number.isInteger(value)) &&
|
|
1547
|
+
(rule.minExclusive ? value > rule.min : value >= rule.min) &&
|
|
1548
|
+
value <= rule.max;
|
|
1549
|
+
if (typeof value !== "number" || !inRange) {
|
|
1550
|
+
const lower = rule.minExclusive ? `> ${rule.min}` : `>= ${rule.min}`;
|
|
1551
|
+
throw new Error(
|
|
1552
|
+
`tiers.json: ${path}.${key} must be ${rule.integer ? "an integer" : "a number"} ${lower} and <= ${rule.max} (got ${describeRoutingValue(value, `${path}.${key}`)})`,
|
|
1553
|
+
);
|
|
1554
|
+
}
|
|
1555
|
+
return value;
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
function readBoolean(
|
|
1559
|
+
obj: Record<string, unknown>,
|
|
1560
|
+
key: string,
|
|
1561
|
+
path: string,
|
|
1562
|
+
): boolean | undefined {
|
|
1563
|
+
const value = obj[key];
|
|
1564
|
+
if (value === undefined) return undefined;
|
|
1565
|
+
if (typeof value !== "boolean") {
|
|
1566
|
+
throw new Error(`tiers.json: ${path}.${key} must be a boolean (got ${describeRoutingValue(value, `${path}.${key}`)})`);
|
|
1567
|
+
}
|
|
1568
|
+
return value;
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
/** A nested object block; `null` and arrays are refused (an override `null` would erase a block). */
|
|
1572
|
+
function readBlock(
|
|
1573
|
+
parent: Record<string, unknown>,
|
|
1574
|
+
key: string,
|
|
1575
|
+
path: string,
|
|
1576
|
+
): Record<string, unknown> | undefined {
|
|
1577
|
+
const value = parent[key];
|
|
1578
|
+
if (value === undefined) return undefined;
|
|
1579
|
+
if (!isPlainObject(value)) {
|
|
1580
|
+
throw new Error(`tiers.json: ${path}.${key} must be an object (got ${describeRoutingValue(value, `${path}.${key}`)})`);
|
|
1581
|
+
}
|
|
1582
|
+
rejectPrototypeKeys(value, `${path}.${key}`);
|
|
1583
|
+
return value;
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
/**
|
|
1587
|
+
* An absolute path, or `~` / `~/…` / `~\...` (the home directory; expanded by
|
|
1588
|
+
* resolveRouting). On Windows "absolute" means a drive letter (`C:\x`, `C:/x`) or
|
|
1589
|
+
* a UNC path (`\\server\share`): a rooted path without a drive (`\x`, `/x`) is
|
|
1590
|
+
* relative to the current drive and so to wherever the process happens to run
|
|
1591
|
+
* (QA-1.1-27).
|
|
1592
|
+
*/
|
|
1593
|
+
function isAbsoluteOrHomePath(value: string): boolean {
|
|
1594
|
+
if (value === "~" || /^~[\\/]/.test(value)) return true;
|
|
1595
|
+
if (!isAbsolute(value)) return false;
|
|
1596
|
+
return process.platform !== "win32" || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/])/.test(value);
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
/** `provider/model` or `provider/model#variant` (a catalog reference). */
|
|
1600
|
+
function isCatalogRef(value: unknown): value is string {
|
|
1601
|
+
if (typeof value !== "string") return false;
|
|
1602
|
+
const hash = value.indexOf("#");
|
|
1603
|
+
if (hash === -1) return parseModelRef(value) !== undefined;
|
|
1604
|
+
return VARIANT_ID_PATTERN.test(value.slice(hash + 1)) && parseModelRef(value.slice(0, hash)) !== undefined;
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
/** `model` / `backend` pair read from a classifier block or a per-preset override. */
|
|
1608
|
+
function readClassifierModel(obj: Record<string, unknown>, path: string): string | null | undefined {
|
|
1609
|
+
const model = obj.model;
|
|
1610
|
+
if (model === undefined || model === null) return model;
|
|
1611
|
+
if (!isCatalogRef(model)) {
|
|
1612
|
+
throw new Error(
|
|
1613
|
+
`tiers.json: ${path}.model must be null or a 'provider/model[#variant]' string (got ${describeRoutingValue(model, `${path}.model`)})`,
|
|
1614
|
+
);
|
|
1615
|
+
}
|
|
1616
|
+
return model;
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
function isHttpUrl(value: string): boolean {
|
|
1620
|
+
try {
|
|
1621
|
+
const protocol = new URL(value).protocol;
|
|
1622
|
+
return protocol === "http:" || protocol === "https:";
|
|
1623
|
+
} catch {
|
|
1624
|
+
return false;
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
/** D3: a backend other than `rules` needs a model; the HTTP backends also need a URL. */
|
|
1629
|
+
function assertClassifierUsable(
|
|
1630
|
+
path: string,
|
|
1631
|
+
backend: ClassifierBackend,
|
|
1632
|
+
model: string | null | undefined,
|
|
1633
|
+
baseUrl: string | null | undefined,
|
|
1634
|
+
modelKeys: string,
|
|
1635
|
+
): void {
|
|
1636
|
+
if (backend === "rules") return;
|
|
1637
|
+
if (typeof model !== "string" || model === "") {
|
|
1638
|
+
throw new Error(
|
|
1639
|
+
`tiers.json: ${modelKeys} must be a non-empty 'provider/model[#variant]' string when ${path}.backend is "${backend}" (the classifier is never picked automatically)`,
|
|
1640
|
+
);
|
|
1641
|
+
}
|
|
1642
|
+
if ((backend === "openai-compatible" || backend === "typesafe") && !baseUrl) {
|
|
1643
|
+
throw new Error(
|
|
1644
|
+
`tiers.json: routing.classifier.baseUrl must be an http(s) URL when ${path}.backend is "${backend}"`,
|
|
1645
|
+
);
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
function validateClassifier(routing: Record<string, unknown>): ClassifierConfig | undefined {
|
|
1650
|
+
const c = readBlock(routing, "classifier", "routing");
|
|
1651
|
+
if (c === undefined) return undefined;
|
|
1652
|
+
const path = "routing.classifier";
|
|
1653
|
+
const out: ClassifierConfig = {};
|
|
1654
|
+
|
|
1655
|
+
const backend = readEnum(c, "backend", path, CLASSIFIER_BACKENDS);
|
|
1656
|
+
if (backend !== undefined) out.backend = backend;
|
|
1657
|
+
|
|
1658
|
+
const model = readClassifierModel(c, path);
|
|
1659
|
+
if (model !== undefined) out.model = model;
|
|
1660
|
+
|
|
1661
|
+
const baseUrl = c.baseUrl;
|
|
1662
|
+
if (baseUrl !== undefined && baseUrl !== null) {
|
|
1663
|
+
if (typeof baseUrl !== "string" || !isHttpUrl(baseUrl)) {
|
|
1664
|
+
throw new Error(
|
|
1665
|
+
`tiers.json: ${path}.baseUrl must be null or an http(s) URL (value not shown)`,
|
|
1666
|
+
);
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
if (baseUrl !== undefined) out.baseUrl = baseUrl;
|
|
1670
|
+
|
|
1671
|
+
const apiKeyEnv = c.apiKeyEnv;
|
|
1672
|
+
if (apiKeyEnv !== undefined && apiKeyEnv !== null) {
|
|
1673
|
+
if (typeof apiKeyEnv !== "string" || !ENV_NAME_PATTERN.test(apiKeyEnv)) {
|
|
1674
|
+
throw new Error(
|
|
1675
|
+
`tiers.json: ${path}.apiKeyEnv must be null or an environment variable name (value not shown)`,
|
|
1676
|
+
);
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
if (apiKeyEnv !== undefined) out.apiKeyEnv = apiKeyEnv;
|
|
1680
|
+
|
|
1681
|
+
const timeoutMs = readNumber(c, "timeoutMs", path, { min: 100, max: 30_000, integer: true });
|
|
1682
|
+
if (timeoutMs !== undefined) out.timeoutMs = timeoutMs;
|
|
1683
|
+
|
|
1684
|
+
const samples = c.samples;
|
|
1685
|
+
if (samples !== undefined) {
|
|
1686
|
+
if (samples !== 1 && samples !== 3) {
|
|
1687
|
+
throw new Error(`tiers.json: ${path}.samples must be 1 or 3 (got ${describeRoutingValue(samples, `${path}.samples`)})`);
|
|
1688
|
+
}
|
|
1689
|
+
out.samples = samples;
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
const maxStateChars = readNumber(c, "maxStateChars", path, { min: 200, max: 20_000, integer: true });
|
|
1693
|
+
if (maxStateChars !== undefined) out.maxStateChars = maxStateChars;
|
|
1694
|
+
|
|
1695
|
+
const presets = readBlock(c, "presets", path);
|
|
1696
|
+
if (presets !== undefined) {
|
|
1697
|
+
const snapshot: Record<string, ClassifierPresetOverride> = {};
|
|
1698
|
+
for (const [presetName, entry] of Object.entries(presets)) {
|
|
1699
|
+
const entryPath = `${path}.presets.'${presetName}'`;
|
|
1700
|
+
if (!isPlainObject(entry)) {
|
|
1701
|
+
throw new Error(`tiers.json: ${entryPath} must be an object (got ${describeRoutingValue(entry, entryPath)})`);
|
|
1702
|
+
}
|
|
1703
|
+
rejectPrototypeKeys(entry, entryPath);
|
|
1704
|
+
const override: ClassifierPresetOverride = {};
|
|
1705
|
+
const entryBackend = readEnum(entry, "backend", entryPath, CLASSIFIER_BACKENDS);
|
|
1706
|
+
if (entryBackend !== undefined) override.backend = entryBackend;
|
|
1707
|
+
const entryModel = readClassifierModel(entry, entryPath);
|
|
1708
|
+
if (entryModel !== undefined) override.model = entryModel;
|
|
1709
|
+
snapshot[presetName] = override;
|
|
1710
|
+
}
|
|
1711
|
+
out.presets = snapshot;
|
|
1712
|
+
}
|
|
1713
|
+
|
|
1714
|
+
// The top level and every per-preset override must each resolve to a usable
|
|
1715
|
+
// classifier, whichever layer supplied which key.
|
|
1716
|
+
const effectiveBackend = out.backend ?? "rules";
|
|
1717
|
+
assertClassifierUsable(path, effectiveBackend, out.model, out.baseUrl, `${path}.model`);
|
|
1718
|
+
for (const [presetName, override] of Object.entries(out.presets ?? {})) {
|
|
1719
|
+
const entryPath = `${path}.presets.'${presetName}'`;
|
|
1720
|
+
assertClassifierUsable(
|
|
1721
|
+
entryPath,
|
|
1722
|
+
override.backend ?? effectiveBackend,
|
|
1723
|
+
override.model !== undefined ? override.model : out.model,
|
|
1724
|
+
out.baseUrl,
|
|
1725
|
+
`${path}.model or ${entryPath}.model`,
|
|
1726
|
+
);
|
|
1727
|
+
}
|
|
1728
|
+
return out;
|
|
1729
|
+
}
|
|
1730
|
+
|
|
1731
|
+
function validateRoles(routing: Record<string, unknown>): Record<string, string[]> | undefined {
|
|
1732
|
+
const roles = readBlock(routing, "roles", "routing");
|
|
1733
|
+
if (roles === undefined) return undefined;
|
|
1734
|
+
const out: Record<string, string[]> = {};
|
|
1735
|
+
for (const [taskClass, agents] of Object.entries(roles)) {
|
|
1736
|
+
if (!pickEnum(ROUTING_TASK_CLASSES, taskClass)) {
|
|
1737
|
+
throw new Error(
|
|
1738
|
+
`tiers.json: routing.roles class '${taskClass}' must be one of ${ROUTING_TASK_CLASSES.join("|")}`,
|
|
1739
|
+
);
|
|
1740
|
+
}
|
|
1741
|
+
// An empty list is allowed: it means "no native candidates for this class"
|
|
1742
|
+
// (a deliberate deviation from "non-empty arrays", QA-1.1-7).
|
|
1743
|
+
if (!Array.isArray(agents)) {
|
|
1744
|
+
throw new Error(
|
|
1745
|
+
`tiers.json: routing.roles.'${taskClass}' must be an array of agent ids (got ${describeValue(agents)})`,
|
|
1746
|
+
);
|
|
1747
|
+
}
|
|
1748
|
+
const ids: string[] = [];
|
|
1749
|
+
for (const agent of agents as unknown[]) {
|
|
1750
|
+
if (typeof agent !== "string" || !isAgentId(agent)) {
|
|
1751
|
+
throw new Error(
|
|
1752
|
+
`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)})`,
|
|
1753
|
+
);
|
|
1754
|
+
}
|
|
1755
|
+
ids.push(agent);
|
|
1756
|
+
}
|
|
1757
|
+
out[taskClass] = ids;
|
|
1758
|
+
}
|
|
1759
|
+
return out;
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1762
|
+
/**
|
|
1763
|
+
* Validate `routing` and return a snapshot of the validated values (or
|
|
1764
|
+
* `undefined` when absent). Defaults are NOT applied here; see resolveRouting.
|
|
1765
|
+
*/
|
|
1766
|
+
function validateRouting(value: unknown): RoutingConfig | undefined {
|
|
1767
|
+
if (value === undefined) return undefined;
|
|
1768
|
+
if (!isPlainObject(value)) {
|
|
1769
|
+
throw new Error(`tiers.json: 'routing' must be an object (got ${describeRoutingValue(value, "routing")})`);
|
|
1770
|
+
}
|
|
1771
|
+
rejectPrototypeKeys(value, "routing");
|
|
1772
|
+
const routing = value;
|
|
1773
|
+
const out: RoutingConfig = {};
|
|
1774
|
+
|
|
1775
|
+
const engine = readEnum(routing, "engine", "routing", ROUTING_ENGINES);
|
|
1776
|
+
if (engine !== undefined) out.engine = engine;
|
|
1777
|
+
const profile = readEnum(routing, "profile", "routing", ROUTING_PROFILES);
|
|
1778
|
+
if (profile !== undefined) out.profile = profile;
|
|
1779
|
+
const margin = readNumber(routing, "margin", "routing", { min: 0, max: 0.9 });
|
|
1780
|
+
if (margin !== undefined) out.margin = margin;
|
|
1781
|
+
const minClassConfidence = readNumber(routing, "minClassConfidence", "routing", { min: 0, max: 1 });
|
|
1782
|
+
if (minClassConfidence !== undefined) out.minClassConfidence = minClassConfidence;
|
|
1783
|
+
|
|
1784
|
+
const detection = readBlock(routing, "detection", "routing");
|
|
1785
|
+
if (detection !== undefined) {
|
|
1786
|
+
const d: DetectionConfig = {};
|
|
1787
|
+
for (const key of ["deterministic", "grader", "none"] as const) {
|
|
1788
|
+
const v = readNumber(detection, key, "routing.detection", { min: 0, max: 1 });
|
|
1789
|
+
if (v !== undefined) d[key] = v;
|
|
1790
|
+
}
|
|
1791
|
+
// A deeper check cannot catch less than a shallower one (QA-1.1-13); compared
|
|
1792
|
+
// on the effective values, so one key can break the order against a default.
|
|
1793
|
+
const dd = ROUTING_DEFAULTS.detection;
|
|
1794
|
+
const effective = {
|
|
1795
|
+
deterministic: d.deterministic ?? dd.deterministic,
|
|
1796
|
+
grader: d.grader ?? dd.grader,
|
|
1797
|
+
none: d.none ?? dd.none,
|
|
1798
|
+
};
|
|
1799
|
+
if (!(effective.deterministic >= effective.grader && effective.grader >= effective.none)) {
|
|
1800
|
+
throw new Error(
|
|
1801
|
+
`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})`,
|
|
1802
|
+
);
|
|
1803
|
+
}
|
|
1804
|
+
out.detection = d;
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
const classifier = validateClassifier(routing);
|
|
1808
|
+
if (classifier !== undefined) out.classifier = classifier;
|
|
1809
|
+
const roles = validateRoles(routing);
|
|
1810
|
+
if (roles !== undefined) out.roles = roles;
|
|
1811
|
+
|
|
1812
|
+
// Roles keys (#84): tolerant per entry, never throw (see roles-config.ts).
|
|
1813
|
+
const delegation = sanitizeDelegation(routing.delegation).value;
|
|
1814
|
+
if (delegation !== undefined) out.delegation = delegation;
|
|
1815
|
+
const exploration = sanitizeExploration(routing.exploration).value;
|
|
1816
|
+
if (exploration !== undefined) out.exploration = exploration;
|
|
1817
|
+
const run = sanitizeRun(routing.run).value;
|
|
1818
|
+
if (run !== undefined) out.run = run;
|
|
1819
|
+
const workRoots = sanitizeWorkRoots(routing.workRoots).value;
|
|
1820
|
+
if (workRoots !== undefined) out.workRoots = workRoots;
|
|
1821
|
+
|
|
1822
|
+
const outcomes = readBlock(routing, "outcomes", "routing");
|
|
1823
|
+
if (outcomes !== undefined) {
|
|
1824
|
+
const o: OutcomesConfig = {};
|
|
1825
|
+
const path = outcomes.path;
|
|
1826
|
+
if (path !== undefined) {
|
|
1827
|
+
if (path !== null && (typeof path !== "string" || !isAbsoluteOrHomePath(path))) {
|
|
1828
|
+
throw new Error(
|
|
1829
|
+
`tiers.json: routing.outcomes.path must be null or an absolute path; a leading ~ means the home directory (got ${describeValue(path)})`,
|
|
1830
|
+
);
|
|
1831
|
+
}
|
|
1832
|
+
o.path = path;
|
|
1833
|
+
}
|
|
1834
|
+
const halfLifeDays = readNumber(outcomes, "halfLifeDays", "routing.outcomes", { min: 1, max: 365 });
|
|
1835
|
+
if (halfLifeDays !== undefined) o.halfLifeDays = halfLifeDays;
|
|
1836
|
+
const maxEffectiveSamples = readNumber(outcomes, "maxEffectiveSamples", "routing.outcomes", {
|
|
1837
|
+
min: 5,
|
|
1838
|
+
max: 1000,
|
|
1839
|
+
});
|
|
1840
|
+
if (maxEffectiveSamples !== undefined) o.maxEffectiveSamples = maxEffectiveSamples;
|
|
1841
|
+
out.outcomes = o;
|
|
1842
|
+
}
|
|
1843
|
+
|
|
1844
|
+
const sessionReuse = readBlock(routing, "sessionReuse", "routing");
|
|
1845
|
+
if (sessionReuse !== undefined) {
|
|
1846
|
+
const s: SessionReuseConfig = {};
|
|
1847
|
+
const maxContextFraction = readNumber(sessionReuse, "maxContextFraction", "routing.sessionReuse", {
|
|
1848
|
+
min: 0,
|
|
1849
|
+
max: 0.95,
|
|
1850
|
+
minExclusive: true,
|
|
1851
|
+
});
|
|
1852
|
+
if (maxContextFraction !== undefined) s.maxContextFraction = maxContextFraction;
|
|
1853
|
+
out.sessionReuse = s;
|
|
1854
|
+
}
|
|
1855
|
+
|
|
1856
|
+
const advisor = readBlock(routing, "advisor", "routing");
|
|
1857
|
+
if (advisor !== undefined) {
|
|
1858
|
+
const a: AdvisorConfig = {};
|
|
1859
|
+
const enabled = readBoolean(advisor, "enabled", "routing.advisor");
|
|
1860
|
+
if (enabled !== undefined) a.enabled = enabled;
|
|
1861
|
+
const notify = readBoolean(advisor, "notify", "routing.advisor");
|
|
1862
|
+
if (notify !== undefined) a.notify = notify;
|
|
1863
|
+
const noticeIntervalHours = readNumber(advisor, "noticeIntervalHours", "routing.advisor", {
|
|
1864
|
+
min: 1,
|
|
1865
|
+
max: 720,
|
|
1866
|
+
});
|
|
1867
|
+
if (noticeIntervalHours !== undefined) a.noticeIntervalHours = noticeIntervalHours;
|
|
1868
|
+
out.advisor = a;
|
|
1869
|
+
}
|
|
1870
|
+
|
|
1871
|
+
return out;
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
/** A `candidates` entry after validation (every key optional, see {@link TierCandidate}). */
|
|
1875
|
+
type CandidateSpec = TierCandidate;
|
|
1876
|
+
|
|
1877
|
+
/** The identity of a rung: its model and variant (an omitted variant is the default variant). */
|
|
1878
|
+
function rungKey(model: string, variant: string | undefined): string {
|
|
1879
|
+
return `${model}\u0000${variant ?? ""}`;
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
/** A tier's own costRatio: the one it states, else the conventional default of its name. */
|
|
1883
|
+
function tierCostRatioOf(tierName: string, costRatio: unknown): number {
|
|
1884
|
+
return typeof costRatio === "number" && Number.isFinite(costRatio) && costRatio > 0
|
|
1885
|
+
? costRatio
|
|
1886
|
+
: tierDefaultsFor(tierName).costRatio;
|
|
1887
|
+
}
|
|
1888
|
+
|
|
1889
|
+
/**
|
|
1890
|
+
* Why a non-empty `candidates` list cannot be used next to the tier's own rung,
|
|
1891
|
+
* or `undefined` when it can (QA-1.1-3, made non-fatal by QA-1.1-25):
|
|
1892
|
+
*
|
|
1893
|
+
* - it must contain the tier's own effective `(model, variant)`: the static choice
|
|
1894
|
+
* has to be one of the rungs, or the engine's degenerate case (D2) would have
|
|
1895
|
+
* nothing to start from;
|
|
1896
|
+
* - that rung's `costRatio` is the tier's own, so it must equal it or be omitted.
|
|
1897
|
+
*
|
|
1898
|
+
* It is a *problem*, not a validation error: a plugin update that changes a
|
|
1899
|
+
* bundled tier's variant would otherwise make a user's override file invalid and
|
|
1900
|
+
* drop the whole layer. The list is ignored instead (the ladder is the tier's own
|
|
1901
|
+
* rung) and the reason is noticed at load.
|
|
1902
|
+
*/
|
|
1903
|
+
function ownRungProblem(
|
|
1904
|
+
tierModel: string,
|
|
1905
|
+
tierVariant: string | undefined,
|
|
1906
|
+
tierCostRatio: number,
|
|
1907
|
+
candidates: readonly CandidateSpec[],
|
|
1908
|
+
): string | undefined {
|
|
1909
|
+
// `candidates` is non-empty: both callers check, an empty list means "none".
|
|
1910
|
+
const ownKey = rungKey(tierModel, tierVariant);
|
|
1911
|
+
const index = candidates.findIndex((c) => rungKey(c.model ?? tierModel, c.variant) === ownKey);
|
|
1912
|
+
if (index === -1) {
|
|
1913
|
+
return `it does not contain the tier's own rung (model ${tierModel}, variant ${tierVariant ?? "default"})`;
|
|
1914
|
+
}
|
|
1915
|
+
const declared = candidates[index]!.costRatio;
|
|
1916
|
+
if (declared !== undefined && declared !== tierCostRatio) {
|
|
1917
|
+
return `its own rung (candidates[${index}]) has costRatio ${declared}, not the tier's ${tierCostRatio}`;
|
|
1918
|
+
}
|
|
1919
|
+
return undefined;
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
/**
|
|
1923
|
+
* `tiers.<t>.candidates`: ordered rungs of a tier's ladder, in escalation order.
|
|
1924
|
+
* Throws for anything malformed; returns the validated entries.
|
|
1925
|
+
*
|
|
1926
|
+
* - `model` falls back to the tier's own; an omitted `variant` is the model's
|
|
1927
|
+
* default variant; an omitted `costRatio` is the tier's.
|
|
1928
|
+
* - No two rungs may name the same effective `(model, variant)`.
|
|
1929
|
+
* - Effective `costRatio` must not decrease along the list (QA-1.1-12): the list
|
|
1930
|
+
* is walked upward on failure, and a cheaper later rung is not an escalation.
|
|
1931
|
+
*
|
|
1932
|
+
* The own-rung rules are NOT enforced here: see {@link ownRungProblem}.
|
|
1933
|
+
*/
|
|
1934
|
+
function validateTierCandidates(
|
|
1935
|
+
tier: Record<string, unknown>,
|
|
1936
|
+
label: string,
|
|
1937
|
+
tierName: string,
|
|
1938
|
+
): CandidateSpec[] | undefined {
|
|
1939
|
+
const candidates = tier.candidates;
|
|
1940
|
+
if (candidates === undefined) return undefined;
|
|
1941
|
+
if (!Array.isArray(candidates)) {
|
|
1942
|
+
throw new Error(`tiers.json: '${label}.candidates' must be an array`);
|
|
1943
|
+
}
|
|
1944
|
+
const seen = new Map<string, number>();
|
|
1945
|
+
const tierCostRatio = tierCostRatioOf(tierName, tier.costRatio);
|
|
1946
|
+
const specs: CandidateSpec[] = [];
|
|
1947
|
+
const effectiveCosts: number[] = [];
|
|
1948
|
+
for (let i = 0; i < candidates.length; i++) {
|
|
1949
|
+
const entry: unknown = candidates[i];
|
|
1950
|
+
const where = `${label}.candidates[${i}]`;
|
|
1951
|
+
if (!isPlainObject(entry)) {
|
|
1952
|
+
throw new Error(`tiers.json: '${where}' must be an object`);
|
|
1953
|
+
}
|
|
1954
|
+
rejectPrototypeKeys(entry, `${label}.candidates[${i}]`);
|
|
1955
|
+
const model = entry.model;
|
|
1956
|
+
if (model !== undefined && (typeof model !== "string" || !parseModelRef(model))) {
|
|
1957
|
+
throw new Error(
|
|
1958
|
+
`tiers.json: '${where}.model' must be 'provider/model' (got ${describeValue(model)})`,
|
|
1959
|
+
);
|
|
1960
|
+
}
|
|
1961
|
+
const variant = entry.variant;
|
|
1962
|
+
if (variant !== undefined && (typeof variant !== "string" || !VARIANT_ID_PATTERN.test(variant))) {
|
|
1963
|
+
throw new Error(
|
|
1964
|
+
`tiers.json: '${where}.variant' must be a non-empty string without whitespace or '#' (got ${describeValue(variant)})`,
|
|
1965
|
+
);
|
|
1966
|
+
}
|
|
1967
|
+
const costRatio = entry.costRatio;
|
|
1968
|
+
if (
|
|
1969
|
+
costRatio !== undefined &&
|
|
1970
|
+
(typeof costRatio !== "number" || !Number.isFinite(costRatio) || costRatio <= 0)
|
|
1971
|
+
) {
|
|
1972
|
+
throw new Error(
|
|
1973
|
+
`tiers.json: '${where}.costRatio' must be a number > 0 (got ${describeValue(costRatio)})`,
|
|
1974
|
+
);
|
|
1975
|
+
}
|
|
1976
|
+
const effectiveModel = typeof model === "string" ? model : String(tier.model);
|
|
1977
|
+
const key = rungKey(effectiveModel, typeof variant === "string" ? variant : undefined);
|
|
1978
|
+
const first = seen.get(key);
|
|
1979
|
+
if (first !== undefined) {
|
|
1980
|
+
throw new Error(
|
|
1981
|
+
`tiers.json: '${where}' repeats (model, variant) = (${effectiveModel}, ${typeof variant === "string" ? variant : "default"}) of candidates[${first}]`,
|
|
1982
|
+
);
|
|
1983
|
+
}
|
|
1984
|
+
seen.set(key, i);
|
|
1985
|
+
const spec: CandidateSpec = {};
|
|
1986
|
+
if (typeof model === "string") spec.model = model;
|
|
1987
|
+
if (typeof variant === "string") spec.variant = variant;
|
|
1988
|
+
if (typeof costRatio === "number") spec.costRatio = costRatio;
|
|
1989
|
+
specs.push(spec);
|
|
1990
|
+
effectiveCosts.push(spec.costRatio ?? tierCostRatio);
|
|
1991
|
+
}
|
|
1992
|
+
for (let i = 1; i < effectiveCosts.length; i++) {
|
|
1993
|
+
if (effectiveCosts[i]! < effectiveCosts[i - 1]!) {
|
|
1994
|
+
throw new Error(
|
|
1995
|
+
`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`,
|
|
1996
|
+
);
|
|
1997
|
+
}
|
|
1998
|
+
}
|
|
1999
|
+
return specs;
|
|
2000
|
+
}
|
|
2001
|
+
|
|
2002
|
+
/** One rung of a tier as the validator sees it, for the per-preset costRatio check. */
|
|
2003
|
+
interface PresetRung {
|
|
2004
|
+
model: string;
|
|
2005
|
+
variant: string | undefined;
|
|
2006
|
+
costRatio: number;
|
|
2007
|
+
/** Where it was written, for the error message. */
|
|
2008
|
+
source: string;
|
|
2009
|
+
/** True for a rung of an explicit `candidates` list (the tier's own implicit rung is not). */
|
|
2010
|
+
explicit: boolean;
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
/**
|
|
2014
|
+
* Within one preset a `(model, variant)` has ONE costRatio (QA-1.1-26): the
|
|
2015
|
+
* engine prices a candidate by that pair, so two tiers (or a tier and a
|
|
2016
|
+
* candidate list) quoting different ratios for the same pair would make the
|
|
2017
|
+
* choice depend on which tier asked. Only pairs involving an explicit
|
|
2018
|
+
* `candidates` entry are checked: several bundled tiers legitimately share one
|
|
2019
|
+
* model at different effort levels and ratios, and say nothing about variants.
|
|
2020
|
+
*/
|
|
2021
|
+
function assertConsistentRungCosts(presetName: string, rungs: readonly PresetRung[]): void {
|
|
2022
|
+
const first = new Map<string, PresetRung>();
|
|
2023
|
+
for (const rung of rungs) {
|
|
2024
|
+
const key = rungKey(rung.model, rung.variant);
|
|
2025
|
+
const prior = first.get(key);
|
|
2026
|
+
if (prior === undefined) {
|
|
2027
|
+
first.set(key, rung);
|
|
2028
|
+
} else if (prior.costRatio !== rung.costRatio && (prior.explicit || rung.explicit)) {
|
|
2029
|
+
throw new Error(
|
|
2030
|
+
`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`,
|
|
2031
|
+
);
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
/** True when the tier lists at least one explicit candidate (an empty list counts as none). */
|
|
2036
|
+
export function hasExplicitCandidates(tier: TierConfig): boolean {
|
|
2037
|
+
return Array.isArray(tier.candidates) && tier.candidates.length > 0;
|
|
2038
|
+
}
|
|
2039
|
+
|
|
2040
|
+
/**
|
|
2041
|
+
* Why the tier's `candidates` are ignored (the ladder is then the tier's own
|
|
2042
|
+
* rung), or `undefined` when they are used or there are none (QA-1.1-25):
|
|
2043
|
+
* the list lacks the tier's own `(model, variant)`, or states another
|
|
2044
|
+
* `costRatio` for it. Loading reports it as a config notice.
|
|
2045
|
+
*/
|
|
2046
|
+
export function candidatesProblem(tierName: string, tier: TierConfig): string | undefined {
|
|
2047
|
+
const listed = tier.candidates;
|
|
2048
|
+
if (listed === undefined || listed.length === 0) return undefined;
|
|
2049
|
+
return ownRungProblem(tier.model, tier.variant, tierCostRatioOf(tierName, tier.costRatio), listed);
|
|
2050
|
+
}
|
|
2051
|
+
|
|
1226
2052
|
/**
|
|
1227
2053
|
* Validate a raw parsed config. Strict and throwing by design: the bundled
|
|
1228
2054
|
* tiers.json must be valid on its own, and loadConfig turns a throw from an
|
|
@@ -1261,9 +2087,12 @@ export function validateConfig(raw: unknown): RouterConfig {
|
|
|
1261
2087
|
validateDispatchHeader(obj);
|
|
1262
2088
|
validateTaskPromptRepair(obj);
|
|
1263
2089
|
validateFalseRefusalDetection(obj);
|
|
2090
|
+
const routing = validateRouting(obj.routing);
|
|
2091
|
+
// Never throws: a bad entry is dropped, and buildConfig reports it as a notice.
|
|
2092
|
+
const roleAgents = sanitizeRoleAgents(obj.roleAgents).value;
|
|
1264
2093
|
|
|
1265
2094
|
const cfg = raw as RouterConfig;
|
|
1266
|
-
return withValidatedSnapshots(cfg, { enforcement });
|
|
2095
|
+
return withValidatedSnapshots(cfg, { enforcement, routing, roleAgents });
|
|
1267
2096
|
}
|
|
1268
2097
|
|
|
1269
2098
|
/**
|
|
@@ -1360,21 +2189,158 @@ interface SourceFailure {
|
|
|
1360
2189
|
export interface OverrideLayer {
|
|
1361
2190
|
path: string;
|
|
1362
2191
|
data: Record<string, unknown>;
|
|
2192
|
+
project?: boolean;
|
|
2193
|
+
}
|
|
2194
|
+
|
|
2195
|
+
/**
|
|
2196
|
+
* `routing` keys that decide where task text is sent or where outcome data is
|
|
2197
|
+
* written. A repository-controlled file must not be able to set them (A18,
|
|
2198
|
+
* QA-1.1-2): cloning a project would otherwise let its author point the
|
|
2199
|
+
* classifier at their own server. Only the global override may.
|
|
2200
|
+
*/
|
|
2201
|
+
const GLOBAL_ONLY_ROUTING_KEYS: ReadonlyArray<readonly [block: string, key: string]> = [
|
|
2202
|
+
["classifier", "backend"],
|
|
2203
|
+
["classifier", "model"],
|
|
2204
|
+
["classifier", "baseUrl"],
|
|
2205
|
+
["classifier", "apiKeyEnv"],
|
|
2206
|
+
["classifier", "presets"],
|
|
2207
|
+
["outcomes", "path"],
|
|
2208
|
+
];
|
|
2209
|
+
|
|
2210
|
+
/** Roles keys (#84) a project layer must not carry; `routing.delegation` is allowed there. */
|
|
2211
|
+
const GLOBAL_ONLY_ROLES_ROUTING_KEYS = ["exploration", "run", "workRoots"] as const;
|
|
2212
|
+
|
|
2213
|
+
function stripGlobalOnlyRolesKeys(data: Record<string, unknown>): string[] {
|
|
2214
|
+
const dropped: string[] = [];
|
|
2215
|
+
if (Object.hasOwn(data, "roleAgents")) {
|
|
2216
|
+
delete data.roleAgents;
|
|
2217
|
+
dropped.push("roleAgents");
|
|
2218
|
+
}
|
|
2219
|
+
const routing = data.routing;
|
|
2220
|
+
if (isPlainObject(routing)) {
|
|
2221
|
+
for (const key of GLOBAL_ONLY_ROLES_ROUTING_KEYS) {
|
|
2222
|
+
if (Object.hasOwn(routing, key)) {
|
|
2223
|
+
delete routing[key];
|
|
2224
|
+
dropped.push(`routing.${key}`);
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
if (dropped.length > 0 && Object.keys(routing).length === 0) delete data.routing;
|
|
2228
|
+
}
|
|
2229
|
+
return dropped;
|
|
2230
|
+
}
|
|
2231
|
+
|
|
2232
|
+
/** Remove the global-only `routing` keys from a project layer; returns what was dropped. */
|
|
2233
|
+
function stripGlobalOnlyRoutingKeys(data: Record<string, unknown>): string[] {
|
|
2234
|
+
const routing = data.routing;
|
|
2235
|
+
if (!isPlainObject(routing)) return [];
|
|
2236
|
+
const dropped: string[] = [];
|
|
2237
|
+
const touched = new Set<string>();
|
|
2238
|
+
for (const [block, key] of GLOBAL_ONLY_ROUTING_KEYS) {
|
|
2239
|
+
const target = routing[block];
|
|
2240
|
+
if (isPlainObject(target) && Object.hasOwn(target, key)) {
|
|
2241
|
+
delete target[key];
|
|
2242
|
+
dropped.push(`routing.${block}.${key}`);
|
|
2243
|
+
touched.add(block);
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
// A block that stripping left empty goes too, and so does an emptied `routing`:
|
|
2247
|
+
// any `routing` block, however empty, changes behaviour (variantSteps defaults
|
|
2248
|
+
// to `auto` under one, A15), and the project file must not do that by accident.
|
|
2249
|
+
for (const block of touched) {
|
|
2250
|
+
const target = routing[block];
|
|
2251
|
+
if (isPlainObject(target) && Object.keys(target).length === 0) delete routing[block];
|
|
2252
|
+
}
|
|
2253
|
+
if (dropped.length > 0 && Object.keys(routing).length === 0) delete data.routing;
|
|
2254
|
+
return dropped;
|
|
1363
2255
|
}
|
|
1364
2256
|
|
|
1365
|
-
function collectOverrideLayers(
|
|
2257
|
+
function collectOverrideLayers(
|
|
2258
|
+
dir: string,
|
|
2259
|
+
failures?: SourceFailure[],
|
|
2260
|
+
notices?: ConfigNotice[],
|
|
2261
|
+
): OverrideLayer[] {
|
|
1366
2262
|
const layers: OverrideLayer[] = [];
|
|
1367
2263
|
// Lowest priority first: global, then project-local (found by upward search
|
|
1368
2264
|
// from the project directory).
|
|
1369
|
-
const
|
|
1370
|
-
|
|
2265
|
+
const sources = [
|
|
2266
|
+
{ path: overridePath(), project: false },
|
|
2267
|
+
{ path: walkForProjectOverride(dir), project: true },
|
|
2268
|
+
];
|
|
2269
|
+
for (const { path: p, project } of sources) {
|
|
1371
2270
|
if (!p) continue;
|
|
1372
2271
|
const data = readOverridesAt(p, failures);
|
|
1373
|
-
if (data)
|
|
2272
|
+
if (!data) continue;
|
|
2273
|
+
if (project) {
|
|
2274
|
+
const dropped = stripGlobalOnlyRoutingKeys(data);
|
|
2275
|
+
if (dropped.length > 0) {
|
|
2276
|
+
notices?.push({
|
|
2277
|
+
source: p,
|
|
2278
|
+
message: `ignoring ${dropped.join(", ")} from ${p}: only the global override may set it`,
|
|
2279
|
+
});
|
|
2280
|
+
}
|
|
2281
|
+
// #84: a repository may pick `routing.delegation`, but not customise role agents, grant
|
|
2282
|
+
// exploration, define `router_run` commands or widen the work roots.
|
|
2283
|
+
const rolesDropped = stripGlobalOnlyRolesKeys(data);
|
|
2284
|
+
if (rolesDropped.length > 0) {
|
|
2285
|
+
notices?.push({
|
|
2286
|
+
source: p,
|
|
2287
|
+
message: `ignoring ${rolesDropped.join(", ")} from ${p}: only tiers.json or the global override may set it`,
|
|
2288
|
+
});
|
|
2289
|
+
}
|
|
2290
|
+
// A18 (#81): a cloned repository must not register agents, let alone
|
|
2291
|
+
// ones with permissions. The rest of the project layer still applies.
|
|
2292
|
+
if (Object.hasOwn(data, "agents")) {
|
|
2293
|
+
delete data.agents;
|
|
2294
|
+
notices?.push({
|
|
2295
|
+
source: p,
|
|
2296
|
+
message: `ignoring agents from ${p}: only tiers.json or the global override may define agents (A18)`,
|
|
2297
|
+
});
|
|
2298
|
+
}
|
|
2299
|
+
}
|
|
2300
|
+
layers.push({ path: p, data, project });
|
|
1374
2301
|
}
|
|
1375
2302
|
return layers;
|
|
1376
2303
|
}
|
|
1377
2304
|
|
|
2305
|
+
/** The notices of the build that produced each config object (the cache hands the same object back until a reload). */
|
|
2306
|
+
const noticesByConfig = new WeakMap<RouterConfig, readonly ConfigNotice[]>();
|
|
2307
|
+
|
|
2308
|
+
/** Notice texts already logged in this process (bounded); see {@link warnConfigNotices}. */
|
|
2309
|
+
const loggedNoticeTexts = new Set<string>();
|
|
2310
|
+
|
|
2311
|
+
/**
|
|
2312
|
+
* Log, through the plugin logger, each notice of `cfg` whose text has not been
|
|
2313
|
+
* logged yet in this process (QA-1.1-23). `config.ts` itself never writes
|
|
2314
|
+
* notices to the console: `console.warn` from a plugin paints over the TUI, and
|
|
2315
|
+
* keying on the config fingerprint made a state-file write (`/preset`,
|
|
2316
|
+
* `/budget`) re-log a typo that had not changed. The dedupe key is the text,
|
|
2317
|
+
* which already names the file or the keys concerned.
|
|
2318
|
+
*/
|
|
2319
|
+
export function warnConfigNotices(
|
|
2320
|
+
cfg: RouterConfig | undefined,
|
|
2321
|
+
logger: Pick<PluginLogger, "warn">,
|
|
2322
|
+
): void {
|
|
2323
|
+
if (cfg === undefined) return;
|
|
2324
|
+
for (const notice of noticesByConfig.get(cfg) ?? []) {
|
|
2325
|
+
if (loggedNoticeTexts.has(notice.message)) continue;
|
|
2326
|
+
if (loggedNoticeTexts.size >= 256) loggedNoticeTexts.clear();
|
|
2327
|
+
loggedNoticeTexts.add(notice.message);
|
|
2328
|
+
logger.warn(notice.message, notice.source === undefined ? undefined : { source: notice.source });
|
|
2329
|
+
}
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2332
|
+
/**
|
|
2333
|
+
* What to log after every `loadConfig()`: the once-per-process deprecation
|
|
2334
|
+
* warning and any new config notices, both through the plugin logger.
|
|
2335
|
+
*/
|
|
2336
|
+
export function warnConfigIssues(
|
|
2337
|
+
cfg: RouterConfig | undefined,
|
|
2338
|
+
logger: PluginLogger,
|
|
2339
|
+
): void {
|
|
2340
|
+
warnDeprecatedVerifyKeys(cfg, logger);
|
|
2341
|
+
warnConfigNotices(cfg, logger);
|
|
2342
|
+
}
|
|
2343
|
+
|
|
1378
2344
|
/**
|
|
1379
2345
|
* Canonical per-tier defaults, keyed by the conventional tier names. These are
|
|
1380
2346
|
* the same values every bundled preset uses, so a preset defined in an overrides
|
|
@@ -1387,6 +2353,11 @@ const TIER_DEFAULTS: Record<string, { costRatio: number; steps: number }> = {
|
|
|
1387
2353
|
};
|
|
1388
2354
|
const FALLBACK_TIER_DEFAULTS = { costRatio: 1, steps: 50 };
|
|
1389
2355
|
|
|
2356
|
+
/** Defaults of a tier by name; own keys only, so `constructor` or `toString` are not tiers (QA-1.1-19). */
|
|
2357
|
+
function tierDefaultsFor(tierName: string): { costRatio: number; steps: number } {
|
|
2358
|
+
return Object.hasOwn(TIER_DEFAULTS, tierName) ? TIER_DEFAULTS[tierName]! : FALLBACK_TIER_DEFAULTS;
|
|
2359
|
+
}
|
|
2360
|
+
|
|
1390
2361
|
/**
|
|
1391
2362
|
* Fill in `costRatio`/`steps` for any tier that omits them, by tier name. Runs
|
|
1392
2363
|
* after merge so override-defined presets behave well without restating the
|
|
@@ -1396,7 +2367,7 @@ const FALLBACK_TIER_DEFAULTS = { costRatio: 1, steps: 50 };
|
|
|
1396
2367
|
function applyTierDefaults(cfg: RouterConfig): void {
|
|
1397
2368
|
for (const preset of Object.values(cfg.presets)) {
|
|
1398
2369
|
for (const [tierName, tier] of Object.entries(preset)) {
|
|
1399
|
-
const d =
|
|
2370
|
+
const d = tierDefaultsFor(tierName);
|
|
1400
2371
|
if (tier.costRatio === undefined) tier.costRatio = d.costRatio;
|
|
1401
2372
|
if (tier.steps === undefined) tier.steps = d.steps;
|
|
1402
2373
|
}
|
|
@@ -1458,9 +2429,10 @@ export function loadConfig(dir?: string): RouterConfig {
|
|
|
1458
2429
|
entry.config !== null && sourceKey === entry.sourceKey ? entry.config : null;
|
|
1459
2430
|
|
|
1460
2431
|
const failures: SourceFailure[] = [];
|
|
2432
|
+
const notices: ConfigNotice[] = [];
|
|
1461
2433
|
let cfg: RouterConfig;
|
|
1462
2434
|
try {
|
|
1463
|
-
cfg = buildConfig(projectDir, failures);
|
|
2435
|
+
cfg = buildConfig(projectDir, failures, notices);
|
|
1464
2436
|
} catch (err) {
|
|
1465
2437
|
// First load: unchanged behaviour — throw. Reload: keep the last good one.
|
|
1466
2438
|
if (!previous) throw err;
|
|
@@ -1494,6 +2466,8 @@ export function loadConfig(dir?: string): RouterConfig {
|
|
|
1494
2466
|
entry.dirty = false;
|
|
1495
2467
|
entry.reloadError = null;
|
|
1496
2468
|
entry.warnedFingerprint = null;
|
|
2469
|
+
entry.notices = notices;
|
|
2470
|
+
noticesByConfig.set(cfg, notices);
|
|
1497
2471
|
return cfg;
|
|
1498
2472
|
}
|
|
1499
2473
|
|
|
@@ -1521,25 +2495,184 @@ function keepLastValidConfig(
|
|
|
1521
2495
|
return previous;
|
|
1522
2496
|
}
|
|
1523
2497
|
|
|
2498
|
+
/** Keys each `routing` block understands; anything else is ignored (and noticed). */
|
|
2499
|
+
const ROUTING_KNOWN_KEYS: Readonly<Record<string, readonly string[]>> = {
|
|
2500
|
+
routing: [
|
|
2501
|
+
"engine",
|
|
2502
|
+
"profile",
|
|
2503
|
+
"margin",
|
|
2504
|
+
"minClassConfidence",
|
|
2505
|
+
"detection",
|
|
2506
|
+
"classifier",
|
|
2507
|
+
"roles",
|
|
2508
|
+
"outcomes",
|
|
2509
|
+
"sessionReuse",
|
|
2510
|
+
"advisor",
|
|
2511
|
+
"delegation",
|
|
2512
|
+
"exploration",
|
|
2513
|
+
"run",
|
|
2514
|
+
"workRoots",
|
|
2515
|
+
],
|
|
2516
|
+
detection: ["deterministic", "grader", "none"],
|
|
2517
|
+
classifier: ["backend", "model", "baseUrl", "apiKeyEnv", "timeoutMs", "samples", "maxStateChars", "presets"],
|
|
2518
|
+
preset: ["backend", "model"],
|
|
2519
|
+
outcomes: ["path", "halfLifeDays", "maxEffectiveSamples"],
|
|
2520
|
+
sessionReuse: ["maxContextFraction"],
|
|
2521
|
+
advisor: ["enabled", "noticeIntervalHours", "notify"],
|
|
2522
|
+
};
|
|
2523
|
+
|
|
2524
|
+
/**
|
|
2525
|
+
* Paths of the keys inside a raw `routing` block that nothing reads
|
|
2526
|
+
* (`routing.margn`, `routing.classifier.bakend`, …). Validation ignores them, as
|
|
2527
|
+
* it does everywhere in this file; this makes the typo visible (QA-1.1-10).
|
|
2528
|
+
*/
|
|
2529
|
+
export function findUnknownRoutingKeys(routing: unknown): string[] {
|
|
2530
|
+
if (!isPlainObject(routing)) return [];
|
|
2531
|
+
const unknown: string[] = [];
|
|
2532
|
+
const check = (obj: Record<string, unknown>, known: readonly string[], path: string): void => {
|
|
2533
|
+
for (const key of Object.keys(obj)) {
|
|
2534
|
+
if (!known.includes(key)) unknown.push(`${path}.${key}`);
|
|
2535
|
+
}
|
|
2536
|
+
};
|
|
2537
|
+
check(routing, ROUTING_KNOWN_KEYS.routing!, "routing");
|
|
2538
|
+
for (const block of ["detection", "classifier", "outcomes", "sessionReuse", "advisor"] as const) {
|
|
2539
|
+
const value = routing[block];
|
|
2540
|
+
if (isPlainObject(value)) check(value, ROUTING_KNOWN_KEYS[block]!, `routing.${block}`);
|
|
2541
|
+
}
|
|
2542
|
+
const classifier = routing.classifier;
|
|
2543
|
+
const presets = isPlainObject(classifier) ? classifier.presets : undefined;
|
|
2544
|
+
if (isPlainObject(presets)) {
|
|
2545
|
+
for (const [name, entry] of Object.entries(presets)) {
|
|
2546
|
+
if (isPlainObject(entry)) check(entry, ROUTING_KNOWN_KEYS.preset!, `routing.classifier.presets.${name}`);
|
|
2547
|
+
}
|
|
2548
|
+
}
|
|
2549
|
+
return unknown;
|
|
2550
|
+
}
|
|
2551
|
+
|
|
2552
|
+
/**
|
|
2553
|
+
* OpenCode's built-in primary and internal agents. None of them can be a
|
|
2554
|
+
* subagent candidate, so `routing.roles` naming one is useless (QA-1.1-18); it is
|
|
2555
|
+
* accepted (the host's agent set is not known at load) but noticed, and the
|
|
2556
|
+
* engine must skip it.
|
|
2557
|
+
*/
|
|
2558
|
+
export const ROUTING_RESERVED_AGENTS = ["build", "plan", "title", "summary", "compaction"] as const;
|
|
2559
|
+
|
|
2560
|
+
/**
|
|
2561
|
+
* Findings about a routing block that loaded fine but probably is not what the
|
|
2562
|
+
* author meant: unknown keys, `roles` naming reserved agents, per-preset
|
|
2563
|
+
* classifier overrides naming no preset. `rawRouting` is the merged block as
|
|
2564
|
+
* written (validation drops unknown keys from the snapshot); `cfg` is the
|
|
2565
|
+
* validated config.
|
|
2566
|
+
*/
|
|
2567
|
+
export function collectRoutingNotices(rawRouting: unknown, cfg: RouterConfig): string[] {
|
|
2568
|
+
const messages: string[] = [];
|
|
2569
|
+
const unknown = findUnknownRoutingKeys(rawRouting);
|
|
2570
|
+
if (unknown.length > 0) {
|
|
2571
|
+
messages.push(`ignoring unknown routing key${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}`);
|
|
2572
|
+
}
|
|
2573
|
+
for (const [taskClass, agents] of Object.entries(cfg.routing?.roles ?? {})) {
|
|
2574
|
+
for (const agent of agents) {
|
|
2575
|
+
if (ROUTING_RESERVED_AGENTS.some((reserved) => reserved === agent)) {
|
|
2576
|
+
messages.push(
|
|
2577
|
+
`routing.roles.'${taskClass}' names '${agent}', an OpenCode primary/internal agent that cannot be a subagent; it will be skipped`,
|
|
2578
|
+
);
|
|
2579
|
+
}
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
2582
|
+
for (const [presetName, preset] of Object.entries(cfg.presets)) {
|
|
2583
|
+
for (const [tierName, tier] of Object.entries(preset)) {
|
|
2584
|
+
const problem = candidatesProblem(tierName, tier);
|
|
2585
|
+
if (problem !== undefined) {
|
|
2586
|
+
messages.push(
|
|
2587
|
+
`presets.${presetName}.${tierName}.candidates are ignored, the tier's ladder is its own rung: ${problem}`,
|
|
2588
|
+
);
|
|
2589
|
+
}
|
|
2590
|
+
}
|
|
2591
|
+
}
|
|
2592
|
+
for (const name of Object.keys(cfg.routing?.classifier?.presets ?? {})) {
|
|
2593
|
+
if (resolvePresetName(cfg, name) === undefined) {
|
|
2594
|
+
messages.push(
|
|
2595
|
+
`routing.classifier.presets.'${name}' matches no preset (defined: ${Object.keys(cfg.presets).join(", ")}); the override is unused`,
|
|
2596
|
+
);
|
|
2597
|
+
}
|
|
2598
|
+
}
|
|
2599
|
+
return messages;
|
|
2600
|
+
}
|
|
2601
|
+
/**
|
|
2602
|
+
* `routing.roles` is replaced wholesale by the highest-priority layer that sets
|
|
2603
|
+
* it, not merged class by class (QA-1.1-7): the default is replaced as a whole
|
|
2604
|
+
* too, so a layer's `roles` is the complete list of what it wants, and a class
|
|
2605
|
+
* it leaves out cannot be re-enabled by a lower layer.
|
|
2606
|
+
*/
|
|
2607
|
+
function replaceRolesWholesale(merged: unknown, layers: readonly OverrideLayer[]): unknown {
|
|
2608
|
+
if (!isPlainObject(merged) || !isPlainObject(merged.routing)) return merged;
|
|
2609
|
+
for (let i = layers.length - 1; i >= 0; i--) {
|
|
2610
|
+
const routing = layers[i]!.data.routing;
|
|
2611
|
+
if (isPlainObject(routing) && Object.hasOwn(routing, "roles") && routing.roles !== undefined) {
|
|
2612
|
+
return { ...merged, routing: { ...merged.routing, roles: routing.roles } };
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
return merged;
|
|
2616
|
+
}
|
|
2617
|
+
|
|
2618
|
+
/** Merge an override while keeping project classifier budgets within the lower layers' bounds. */
|
|
2619
|
+
function mergeOverrideLayer(lower: unknown, layer: OverrideLayer, notices: ConfigNotice[]): unknown {
|
|
2620
|
+
const merged = deepMerge(lower, layer.data);
|
|
2621
|
+
if (!layer.project || !isPlainObject(merged) || !isPlainObject(merged.routing)) return merged;
|
|
2622
|
+
const classifier = merged.routing.classifier;
|
|
2623
|
+
const projectRouting = layer.data.routing;
|
|
2624
|
+
const projectClassifier = isPlainObject(projectRouting) ? projectRouting.classifier : undefined;
|
|
2625
|
+
if (!isPlainObject(classifier) || !isPlainObject(projectClassifier)) return merged;
|
|
2626
|
+
const lowerRouting = isPlainObject(lower) ? lower.routing : undefined;
|
|
2627
|
+
const lowerClassifier = isPlainObject(lowerRouting) ? lowerRouting.classifier : undefined;
|
|
2628
|
+
const bounded = { ...classifier };
|
|
2629
|
+
// A18 / A35: a repository may tighten the user's exposure/latency budgets, never widen them.
|
|
2630
|
+
for (const key of ["maxStateChars", "samples", "timeoutMs"] as const) {
|
|
2631
|
+
const requested = projectClassifier[key];
|
|
2632
|
+
const inherited = isPlainObject(lowerClassifier) ? lowerClassifier[key] : undefined;
|
|
2633
|
+
const validInherited = typeof inherited === "number" && Number.isInteger(inherited)
|
|
2634
|
+
&& (key === "samples" ? inherited === 1 || inherited === 3
|
|
2635
|
+
: key === "maxStateChars" ? inherited >= 200 && inherited <= 20_000
|
|
2636
|
+
: inherited >= 100 && inherited <= 30_000);
|
|
2637
|
+
const ceiling = validInherited ? inherited : ROUTING_DEFAULTS.classifier[key];
|
|
2638
|
+
if (typeof requested === "number" && Number.isFinite(requested) && typeof ceiling === "number" && requested > ceiling) {
|
|
2639
|
+
bounded[key] = ceiling;
|
|
2640
|
+
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)` });
|
|
2641
|
+
}
|
|
2642
|
+
}
|
|
2643
|
+
// deepMerge can share an override-only block: do not mutate a source layer used by fallback merges.
|
|
2644
|
+
return { ...merged, routing: { ...merged.routing, classifier: bounded } };
|
|
2645
|
+
}
|
|
2646
|
+
|
|
1524
2647
|
/**
|
|
1525
2648
|
* Build a fresh config from tiers.json + override layers + persisted state.
|
|
1526
2649
|
* Throws only when tiers.json itself is unreadable/invalid. Override and state
|
|
1527
2650
|
* problems are warned about, skipped, and appended to `failures`.
|
|
1528
2651
|
*/
|
|
1529
|
-
function buildConfig(
|
|
2652
|
+
function buildConfig(
|
|
2653
|
+
dir: string,
|
|
2654
|
+
failures: SourceFailure[],
|
|
2655
|
+
notices: ConfigNotice[],
|
|
2656
|
+
): RouterConfig {
|
|
1530
2657
|
const base = JSON.parse(readFileSync(configPath(), "utf-8"));
|
|
1531
|
-
const layers = collectOverrideLayers(dir, failures);
|
|
2658
|
+
const layers = collectOverrideLayers(dir, failures, notices);
|
|
1532
2659
|
|
|
1533
2660
|
// Bundled config must be valid on its own — throw otherwise (unchanged
|
|
1534
2661
|
// behaviour). Override layers are then applied on top.
|
|
1535
2662
|
let cfg = validateConfig(base);
|
|
2663
|
+
let rawUsed: unknown = base;
|
|
1536
2664
|
|
|
1537
2665
|
if (layers.length > 0) {
|
|
1538
2666
|
const merge = (ls: OverrideLayer[]): unknown =>
|
|
1539
|
-
|
|
2667
|
+
replaceRolesWholesale(
|
|
2668
|
+
ls.reduce<unknown>((acc, l) => mergeOverrideLayer(acc, l, notices), base),
|
|
2669
|
+
ls,
|
|
2670
|
+
);
|
|
1540
2671
|
|
|
1541
2672
|
try {
|
|
1542
|
-
|
|
2673
|
+
const merged = merge(layers);
|
|
2674
|
+
cfg = validateConfig(merged);
|
|
2675
|
+
rawUsed = merged;
|
|
1543
2676
|
} catch (err) {
|
|
1544
2677
|
// A bad override must never brick startup, and one broken file must not
|
|
1545
2678
|
// discard a good one. Fall back to the highest-priority layer that
|
|
@@ -1555,7 +2688,9 @@ function buildConfig(dir: string, failures: SourceFailure[]): RouterConfig {
|
|
|
1555
2688
|
});
|
|
1556
2689
|
for (let i = layers.length - 1; i >= 0; i--) {
|
|
1557
2690
|
try {
|
|
1558
|
-
|
|
2691
|
+
const single = merge([layers[i]!]);
|
|
2692
|
+
cfg = validateConfig(single);
|
|
2693
|
+
rawUsed = single;
|
|
1559
2694
|
for (let j = 0; j < layers.length; j++) {
|
|
1560
2695
|
if (j !== i) {
|
|
1561
2696
|
console.warn(`[model-router] dropped override layer ${layers[j]!.path}`);
|
|
@@ -1571,6 +2706,7 @@ function buildConfig(dir: string, failures: SourceFailure[]): RouterConfig {
|
|
|
1571
2706
|
message: `${layers[i]!.path}: ${(singleErr as Error).message}`,
|
|
1572
2707
|
});
|
|
1573
2708
|
cfg = validateConfig(base);
|
|
2709
|
+
rawUsed = base;
|
|
1574
2710
|
}
|
|
1575
2711
|
}
|
|
1576
2712
|
}
|
|
@@ -1610,9 +2746,94 @@ function buildConfig(dir: string, failures: SourceFailure[]): RouterConfig {
|
|
|
1610
2746
|
}
|
|
1611
2747
|
|
|
1612
2748
|
applyTierDefaults(cfg);
|
|
2749
|
+
const rawRouting = isPlainObject(rawUsed) ? rawUsed.routing : undefined;
|
|
2750
|
+
for (const message of collectRoutingNotices(rawRouting, cfg)) notices.push({ message });
|
|
2751
|
+
const rawRoleAgents = isPlainObject(rawUsed) ? rawUsed.roleAgents : undefined;
|
|
2752
|
+
for (const issue of collectRolesIssues(rawRouting, rawRoleAgents)) notices.push({ message: issue.message });
|
|
2753
|
+
dropIgnoredCandidates(cfg);
|
|
2754
|
+
applyPluginAgents(cfg, layers, notices);
|
|
2755
|
+
applyRoleNotices(cfg, notices);
|
|
1613
2756
|
return cfg;
|
|
1614
2757
|
}
|
|
1615
2758
|
|
|
2759
|
+
/** Prefix of every role-table notice: they describe roles mode, which only OpenCode v2 runs (QA-P11-2-1). */
|
|
2760
|
+
export const ROLE_NOTICE_PREFIX = "roles mode (OpenCode v2 only): ";
|
|
2761
|
+
|
|
2762
|
+
/** The role-table resolver used for notices; replaceable in tests only. */
|
|
2763
|
+
let roleTableResolver: typeof resolveRoleTable = resolveRoleTable;
|
|
2764
|
+
|
|
2765
|
+
/** Test-only: replace the resolver {@link applyRoleNotices} calls; no argument restores it. */
|
|
2766
|
+
export function setRoleTableResolverForTest(resolver?: typeof resolveRoleTable): void {
|
|
2767
|
+
roleTableResolver = resolver ?? resolveRoleTable;
|
|
2768
|
+
}
|
|
2769
|
+
|
|
2770
|
+
/**
|
|
2771
|
+
* Roles mode (#84): the notices of resolving the role table — unknown `roleAgents` names,
|
|
2772
|
+
* clamped budgets and ranges, disabled roles, #81 `agents` that replace or are dropped for a
|
|
2773
|
+
* role — so they reach `/router` with the other config notices. Pure; the host is not known
|
|
2774
|
+
* here, so the table is resolved as on v2 and every notice says it is about roles mode (on v1
|
|
2775
|
+
* the roles keys stay inert). It never throws: a failure is one notice, and the config loads
|
|
2776
|
+
* (QA-P11-2-2).
|
|
2777
|
+
*/
|
|
2778
|
+
function applyRoleNotices(cfg: RouterConfig, notices: ConfigNotice[]): void {
|
|
2779
|
+
if (cfg.routing?.delegation !== "roles") return;
|
|
2780
|
+
try {
|
|
2781
|
+
for (const issue of roleTableResolver(cfg, "v2").issues) notices.push({ message: `${ROLE_NOTICE_PREFIX}${issue.message}` });
|
|
2782
|
+
} catch (err) {
|
|
2783
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
2784
|
+
notices.push({ message: `roles: the role table could not be resolved (${reason}); no role agent will be registered` });
|
|
2785
|
+
}
|
|
2786
|
+
}
|
|
2787
|
+
|
|
2788
|
+
/**
|
|
2789
|
+
* Validate the merged `agents` block per entry against the active preset (#81).
|
|
2790
|
+
* Runs after the persisted preset is applied, so a `/preset` rebuild re-checks
|
|
2791
|
+
* every `tier`. A bad entry is removed with a notice naming its key path and
|
|
2792
|
+
* file; the other entries, the layer and `routing` are kept (#80).
|
|
2793
|
+
*/
|
|
2794
|
+
/**
|
|
2795
|
+
* The one preset resolver for plugin agents: validation, registration and the status lines all use it,
|
|
2796
|
+
* so they cannot disagree (QA-81-9). Case-insensitive like /preset; falls back to the first preset.
|
|
2797
|
+
*/
|
|
2798
|
+
export function resolveActiveTiers(cfg: RouterConfig): Preset {
|
|
2799
|
+
const name = resolvePresetName(cfg, cfg.activePreset);
|
|
2800
|
+
return (name !== undefined ? cfg.presets[name] : undefined) ?? Object.values(cfg.presets)[0] ?? {};
|
|
2801
|
+
}
|
|
2802
|
+
|
|
2803
|
+
function applyPluginAgents(cfg: RouterConfig, layers: readonly OverrideLayer[], notices: ConfigNotice[]): void {
|
|
2804
|
+
if (!Object.hasOwn(cfg, "agents")) return;
|
|
2805
|
+
const tiers = resolveActiveTiers(cfg);
|
|
2806
|
+
const { agents, issues } = sanitizePluginAgents(cfg.agents, { activePreset: cfg.activePreset, tiers });
|
|
2807
|
+
// Project layers never carry `agents` (stripped while collecting), so the
|
|
2808
|
+
// source is the global override when it names the entry, else tiers.json.
|
|
2809
|
+
const globalAgents = layers.find((layer) => !layer.project)?.data.agents;
|
|
2810
|
+
for (const issue of issues) {
|
|
2811
|
+
const name = issue.name;
|
|
2812
|
+
const source = isPlainObject(globalAgents) && (name === undefined || Object.hasOwn(globalAgents, name))
|
|
2813
|
+
? layers.find((layer) => !layer.project)!.path
|
|
2814
|
+
: configPath();
|
|
2815
|
+
notices.push({ source, message: `${issue.path}: ${issue.message} (${source})` });
|
|
2816
|
+
}
|
|
2817
|
+
if (agents === undefined) delete cfg.agents;
|
|
2818
|
+
else cfg.agents = agents;
|
|
2819
|
+
}
|
|
2820
|
+
|
|
2821
|
+
/**
|
|
2822
|
+
* Remove, from the built config, every `candidates` list that loading reports as
|
|
2823
|
+
* ignored ({@link candidatesProblem}), after the notice has been recorded
|
|
2824
|
+
* (QA-1.1-30). Leaving it on `tier.candidates` would make `hasExplicitCandidates`
|
|
2825
|
+
* and any code that reads the raw list disagree with `resolveCandidates`, which
|
|
2826
|
+
* already treats the tier as having only its own rung. Runs on the config this
|
|
2827
|
+
* build created, never on a caller's object.
|
|
2828
|
+
*/
|
|
2829
|
+
function dropIgnoredCandidates(cfg: RouterConfig): void {
|
|
2830
|
+
for (const preset of Object.values(cfg.presets)) {
|
|
2831
|
+
for (const [tierName, tier] of Object.entries(preset)) {
|
|
2832
|
+
if (candidatesProblem(tierName, tier) !== undefined) delete tier.candidates;
|
|
2833
|
+
}
|
|
2834
|
+
}
|
|
2835
|
+
}
|
|
2836
|
+
|
|
1616
2837
|
// ---------------------------------------------------------------------------
|
|
1617
2838
|
// State persistence helpers
|
|
1618
2839
|
// ---------------------------------------------------------------------------
|
|
@@ -1768,3 +2989,374 @@ export function resolveVerifyBudget(
|
|
|
1768
2989
|
gateBudgetMs: own<number>("gateBudgetMs") ?? 90_000,
|
|
1769
2990
|
};
|
|
1770
2991
|
}
|
|
2992
|
+
|
|
2993
|
+
// ---------------------------------------------------------------------------
|
|
2994
|
+
// Cost-aware routing helpers (#74)
|
|
2995
|
+
// ---------------------------------------------------------------------------
|
|
2996
|
+
|
|
2997
|
+
/** The single log line of D1; also the exact text tests pin. */
|
|
2998
|
+
export const ROUTING_ENGINE_IGNORED_ON_V1 = "routing.engine ignored on OpenCode v1";
|
|
2999
|
+
|
|
3000
|
+
/**
|
|
3001
|
+
* D12: the roles applied on OpenCode v2 when `routing.roles` is not set. On v1
|
|
3002
|
+
* the default is `{}` (D1). Setting `roles: {}` disables native candidates.
|
|
3003
|
+
*/
|
|
3004
|
+
export const DEFAULT_V2_ROLES: Readonly<Record<string, readonly string[]>> = Object.freeze({
|
|
3005
|
+
search: Object.freeze(["explore"]),
|
|
3006
|
+
implement: Object.freeze(["general"]),
|
|
3007
|
+
debug: Object.freeze(["general"]),
|
|
3008
|
+
review: Object.freeze(["general"]),
|
|
3009
|
+
});
|
|
3010
|
+
|
|
3011
|
+
/**
|
|
3012
|
+
* Every default of the `routing` block except `roles`, whose default depends on
|
|
3013
|
+
* the host. `docs/CONFIG_REFERENCE.md` documents exactly these values and a
|
|
3014
|
+
* test keeps the two in step.
|
|
3015
|
+
*/
|
|
3016
|
+
export const ROUTING_DEFAULTS = Object.freeze({
|
|
3017
|
+
engine: "static" as RoutingEngine,
|
|
3018
|
+
profile: "balanced" as RoutingProfile,
|
|
3019
|
+
margin: 0.2,
|
|
3020
|
+
minClassConfidence: 0.7,
|
|
3021
|
+
detection: Object.freeze({ deterministic: 0.95, grader: 0.7, none: 0.3 }),
|
|
3022
|
+
classifier: Object.freeze({
|
|
3023
|
+
backend: "rules" as ClassifierBackend,
|
|
3024
|
+
model: null,
|
|
3025
|
+
baseUrl: null,
|
|
3026
|
+
apiKeyEnv: null,
|
|
3027
|
+
timeoutMs: 1500,
|
|
3028
|
+
samples: 1 as 1 | 3,
|
|
3029
|
+
maxStateChars: 2000,
|
|
3030
|
+
}),
|
|
3031
|
+
outcomes: Object.freeze({ path: null, halfLifeDays: 14, maxEffectiveSamples: 50 }),
|
|
3032
|
+
sessionReuse: Object.freeze({ maxContextFraction: 0.6 }),
|
|
3033
|
+
advisor: Object.freeze({ enabled: true, noticeIntervalHours: 24, notify: true }),
|
|
3034
|
+
});
|
|
3035
|
+
|
|
3036
|
+
export interface ResolvedClassifier {
|
|
3037
|
+
readonly backend: ClassifierBackend;
|
|
3038
|
+
readonly model: string | null;
|
|
3039
|
+
readonly baseUrl: string | null;
|
|
3040
|
+
readonly apiKeyEnv: string | null;
|
|
3041
|
+
readonly timeoutMs: number;
|
|
3042
|
+
readonly samples: 1 | 3;
|
|
3043
|
+
readonly maxStateChars: number;
|
|
3044
|
+
readonly presets: Readonly<Record<string, Readonly<ClassifierPresetOverride>>>;
|
|
3045
|
+
}
|
|
3046
|
+
|
|
3047
|
+
/** What {@link resolveRouting} applied on top of the file, so `/router` can show it. */
|
|
3048
|
+
export interface RoutingApplied {
|
|
3049
|
+
readonly host: RouterHost;
|
|
3050
|
+
/** `routing.engine` as written (or the default), before the v1 coercion. */
|
|
3051
|
+
readonly requestedEngine: RoutingEngine;
|
|
3052
|
+
/** True when the engine was forced to `static` because the host is v1. */
|
|
3053
|
+
readonly engineCoerced: boolean;
|
|
3054
|
+
/** `configured`: `routing.roles` was set; `default`: the D12 v2 default; `none`: v1 without roles. */
|
|
3055
|
+
readonly rolesSource: "configured" | "default" | "none";
|
|
3056
|
+
}
|
|
3057
|
+
|
|
3058
|
+
/** A fully populated, deeply frozen view of `routing` for one host. */
|
|
3059
|
+
export interface ResolvedRouting {
|
|
3060
|
+
/** The effective engine: `static` on v1 whatever the file says (D1). */
|
|
3061
|
+
readonly engine: RoutingEngine;
|
|
3062
|
+
readonly profile: RoutingProfile;
|
|
3063
|
+
readonly margin: number;
|
|
3064
|
+
readonly minClassConfidence: number;
|
|
3065
|
+
readonly detection: Readonly<Required<DetectionConfig>>;
|
|
3066
|
+
readonly classifier: ResolvedClassifier;
|
|
3067
|
+
/** Class → ordered, de-duplicated agent ids. */
|
|
3068
|
+
readonly roles: Readonly<Record<string, readonly string[]>>;
|
|
3069
|
+
readonly outcomes: Readonly<{ path: string | null; halfLifeDays: number; maxEffectiveSamples: number }>;
|
|
3070
|
+
readonly sessionReuse: Readonly<Required<SessionReuseConfig>>;
|
|
3071
|
+
readonly advisor: Readonly<Required<AdvisorConfig>>;
|
|
3072
|
+
readonly applied: RoutingApplied;
|
|
3073
|
+
}
|
|
3074
|
+
|
|
3075
|
+
/** `~` and `~/x` become paths under the home directory; anything else is returned as is. */
|
|
3076
|
+
function expandHomePath(value: string | null): string | null {
|
|
3077
|
+
if (value === null) return null;
|
|
3078
|
+
if (value === "~") return homedir();
|
|
3079
|
+
return /^~[\\/]/.test(value) ? join(homedir(), value.slice(2)) : value;
|
|
3080
|
+
}
|
|
3081
|
+
|
|
3082
|
+
let warnedEngineIgnoredOnV1 = false;
|
|
3083
|
+
|
|
3084
|
+
/** Test-only: re-arm the once-per-process "engine ignored on v1" notice. */
|
|
3085
|
+
export function resetRoutingWarnings(): void {
|
|
3086
|
+
warnedEngineIgnoredOnV1 = false;
|
|
3087
|
+
loggedNoticeTexts.clear();
|
|
3088
|
+
}
|
|
3089
|
+
|
|
3090
|
+
/** Roles as fresh, de-duplicated, frozen arrays; never aliases the config. */
|
|
3091
|
+
function freezeRoles(
|
|
3092
|
+
roles: Readonly<Record<string, readonly string[]>>,
|
|
3093
|
+
): Readonly<Record<string, readonly string[]>> {
|
|
3094
|
+
const out: Record<string, readonly string[]> = {};
|
|
3095
|
+
for (const [taskClass, agents] of Object.entries(roles)) {
|
|
3096
|
+
out[taskClass] = Object.freeze([...new Set(agents)]);
|
|
3097
|
+
}
|
|
3098
|
+
return Object.freeze(out);
|
|
3099
|
+
}
|
|
3100
|
+
|
|
3101
|
+
/**
|
|
3102
|
+
* The single place the `routing` defaults are applied. Pure apart from the
|
|
3103
|
+
* once-per-process notice below, and never mutates `cfg`.
|
|
3104
|
+
*
|
|
3105
|
+
* - `host: "v2"` applies the D12 default for `roles` when the key is absent.
|
|
3106
|
+
* - `host: "v1"` forces `engine` to `static` (D1) and defaults `roles` to `{}`;
|
|
3107
|
+
* an explicit `routing.roles` is kept (the text-only v1 opt-in).
|
|
3108
|
+
*
|
|
3109
|
+
* The coercion is reported once per process through `logger` (its console
|
|
3110
|
+
* fallback adds the `[model-router]` prefix) or, without one, `console.warn`.
|
|
3111
|
+
*/
|
|
3112
|
+
export function resolveRouting(
|
|
3113
|
+
cfg: RouterConfig | undefined,
|
|
3114
|
+
host: RouterHost,
|
|
3115
|
+
logger?: Pick<PluginLogger, "warn">,
|
|
3116
|
+
): ResolvedRouting {
|
|
3117
|
+
const r: RoutingConfig = cfg?.routing ?? {};
|
|
3118
|
+
const d = ROUTING_DEFAULTS;
|
|
3119
|
+
const requestedEngine = r.engine ?? d.engine;
|
|
3120
|
+
const engineCoerced = host === "v1" && requestedEngine !== "static";
|
|
3121
|
+
if (engineCoerced && !warnedEngineIgnoredOnV1) {
|
|
3122
|
+
warnedEngineIgnoredOnV1 = true;
|
|
3123
|
+
if (logger) logger.warn(ROUTING_ENGINE_IGNORED_ON_V1);
|
|
3124
|
+
else console.warn(`[model-router] ${ROUTING_ENGINE_IGNORED_ON_V1}`);
|
|
3125
|
+
}
|
|
3126
|
+
|
|
3127
|
+
const c: ClassifierConfig = r.classifier ?? {};
|
|
3128
|
+
const presets: Record<string, Readonly<ClassifierPresetOverride>> = {};
|
|
3129
|
+
for (const [name, override] of Object.entries(c.presets ?? {})) {
|
|
3130
|
+
presets[name] = Object.freeze({ ...override });
|
|
3131
|
+
}
|
|
3132
|
+
|
|
3133
|
+
const rolesSource: RoutingApplied["rolesSource"] =
|
|
3134
|
+
r.roles !== undefined ? "configured" : host === "v2" ? "default" : "none";
|
|
3135
|
+
const roles = freezeRoles(r.roles ?? (host === "v2" ? DEFAULT_V2_ROLES : {}));
|
|
3136
|
+
|
|
3137
|
+
return Object.freeze({
|
|
3138
|
+
engine: host === "v1" ? "static" : requestedEngine,
|
|
3139
|
+
profile: r.profile ?? d.profile,
|
|
3140
|
+
margin: r.margin ?? d.margin,
|
|
3141
|
+
minClassConfidence: r.minClassConfidence ?? d.minClassConfidence,
|
|
3142
|
+
detection: Object.freeze({
|
|
3143
|
+
deterministic: r.detection?.deterministic ?? d.detection.deterministic,
|
|
3144
|
+
grader: r.detection?.grader ?? d.detection.grader,
|
|
3145
|
+
none: r.detection?.none ?? d.detection.none,
|
|
3146
|
+
}),
|
|
3147
|
+
classifier: Object.freeze({
|
|
3148
|
+
backend: c.backend ?? d.classifier.backend,
|
|
3149
|
+
model: c.model ?? d.classifier.model,
|
|
3150
|
+
baseUrl: c.baseUrl ?? d.classifier.baseUrl,
|
|
3151
|
+
apiKeyEnv: c.apiKeyEnv ?? d.classifier.apiKeyEnv,
|
|
3152
|
+
timeoutMs: c.timeoutMs ?? d.classifier.timeoutMs,
|
|
3153
|
+
samples: c.samples ?? d.classifier.samples,
|
|
3154
|
+
maxStateChars: c.maxStateChars ?? d.classifier.maxStateChars,
|
|
3155
|
+
presets: Object.freeze(presets),
|
|
3156
|
+
}),
|
|
3157
|
+
roles,
|
|
3158
|
+
outcomes: Object.freeze({
|
|
3159
|
+
path: expandHomePath(r.outcomes?.path ?? d.outcomes.path),
|
|
3160
|
+
halfLifeDays: r.outcomes?.halfLifeDays ?? d.outcomes.halfLifeDays,
|
|
3161
|
+
maxEffectiveSamples: r.outcomes?.maxEffectiveSamples ?? d.outcomes.maxEffectiveSamples,
|
|
3162
|
+
}),
|
|
3163
|
+
sessionReuse: Object.freeze({
|
|
3164
|
+
maxContextFraction: r.sessionReuse?.maxContextFraction ?? d.sessionReuse.maxContextFraction,
|
|
3165
|
+
}),
|
|
3166
|
+
advisor: Object.freeze({
|
|
3167
|
+
enabled: r.advisor?.enabled ?? d.advisor.enabled,
|
|
3168
|
+
noticeIntervalHours: r.advisor?.noticeIntervalHours ?? d.advisor.noticeIntervalHours,
|
|
3169
|
+
notify: r.advisor?.notify ?? d.advisor.notify,
|
|
3170
|
+
}),
|
|
3171
|
+
applied: Object.freeze({ host, requestedEngine, engineCoerced, rolesSource }),
|
|
3172
|
+
});
|
|
3173
|
+
}
|
|
3174
|
+
|
|
3175
|
+
/** The roles keys with their defaults applied, for one host (#84). Never mutates `cfg`. */
|
|
3176
|
+
export interface ResolvedRolesRouting {
|
|
3177
|
+
readonly delegation: DelegationMode;
|
|
3178
|
+
readonly exploration: Readonly<ExplorationConfig>;
|
|
3179
|
+
readonly run: Readonly<RunConfig>;
|
|
3180
|
+
readonly workRoots: readonly string[];
|
|
3181
|
+
/** True on v1 when roles keys were set: they are validated but have no effect. */
|
|
3182
|
+
readonly inert: boolean;
|
|
3183
|
+
}
|
|
3184
|
+
|
|
3185
|
+
let warnedRolesInertOnV1 = false;
|
|
3186
|
+
|
|
3187
|
+
/** Test-only: re-arm the once-per-process "roles delegation requires v2" notice. */
|
|
3188
|
+
export function resetRolesWarnings(): void {
|
|
3189
|
+
warnedRolesInertOnV1 = false;
|
|
3190
|
+
}
|
|
3191
|
+
|
|
3192
|
+
/**
|
|
3193
|
+
* Defaults for `routing.delegation`, `exploration`, `run` and `workRoots`. On v1 (`routerHost`
|
|
3194
|
+
* `v1`) delegation is always `tiers`, and one notice says so when any of delegation `roles`,
|
|
3195
|
+
* `roleAgents`, `exploration`, `run` or `workRoots` was set. Exploration is off (rate 0) unless
|
|
3196
|
+
* the effective delegation is `roles`. Switching `delegation` is only a config value here;
|
|
3197
|
+
* registration follows a hot reload elsewhere. The plugin logs the v1 notice at start-up by
|
|
3198
|
+
* calling this with its logger next to `resolveRouting` (wired with the roles runtime, #84 P2.1).
|
|
3199
|
+
*/
|
|
3200
|
+
export function resolveRolesRouting(
|
|
3201
|
+
cfg: RouterConfig | undefined,
|
|
3202
|
+
host: RouterHost,
|
|
3203
|
+
logger?: Pick<PluginLogger, "warn">,
|
|
3204
|
+
): ResolvedRolesRouting {
|
|
3205
|
+
const r: RoutingConfig = cfg?.routing ?? {};
|
|
3206
|
+
const requested = r.delegation ?? "tiers";
|
|
3207
|
+
const touched = requested === "roles" || cfg?.roleAgents !== undefined || r.exploration !== undefined
|
|
3208
|
+
|| r.run !== undefined || r.workRoots !== undefined;
|
|
3209
|
+
const inert = host === "v1" && touched;
|
|
3210
|
+
if (inert && !warnedRolesInertOnV1) {
|
|
3211
|
+
warnedRolesInertOnV1 = true;
|
|
3212
|
+
if (logger) logger.warn(ROLES_V1_NOTICE);
|
|
3213
|
+
else console.warn(`[model-router] ${ROLES_V1_NOTICE}`);
|
|
3214
|
+
}
|
|
3215
|
+
const delegation: DelegationMode = host === "v1" ? "tiers" : requested;
|
|
3216
|
+
return Object.freeze({
|
|
3217
|
+
delegation,
|
|
3218
|
+
exploration: Object.freeze({
|
|
3219
|
+
rate: delegation === "roles" ? (r.exploration?.rate ?? 0) : 0,
|
|
3220
|
+
requireDetection: "deterministic" as const,
|
|
3221
|
+
}),
|
|
3222
|
+
run: Object.freeze({
|
|
3223
|
+
scripts: Object.freeze([...(r.run?.scripts ?? DEFAULT_RUN_SCRIPTS)]),
|
|
3224
|
+
commands: Object.freeze({ ...(r.run?.commands ?? DEFAULT_RUN_COMMANDS) }),
|
|
3225
|
+
timeoutMs: r.run?.timeoutMs ?? DEFAULT_RUN_TIMEOUT_MS,
|
|
3226
|
+
}),
|
|
3227
|
+
workRoots: Object.freeze([...(r.workRoots ?? [])]),
|
|
3228
|
+
inert,
|
|
3229
|
+
});
|
|
3230
|
+
}
|
|
3231
|
+
|
|
3232
|
+
/**
|
|
3233
|
+
* The key of `presets` that names `presetName`: an exact match, else a
|
|
3234
|
+
* case-insensitive, trimmed one, like {@link resolvePresetName} (what `/preset`
|
|
3235
|
+
* uses), so `Anthropic` and `anthropic` are the same preset (QA-1.1-14).
|
|
3236
|
+
* Own keys only.
|
|
3237
|
+
*/
|
|
3238
|
+
function findPresetOverrideKey(
|
|
3239
|
+
presets: Readonly<Record<string, unknown>>,
|
|
3240
|
+
presetName: string,
|
|
3241
|
+
): string | undefined {
|
|
3242
|
+
if (Object.hasOwn(presets, presetName)) return presetName;
|
|
3243
|
+
const normalized = presetName.trim().toLowerCase();
|
|
3244
|
+
if (normalized === "") return undefined;
|
|
3245
|
+
return Object.keys(presets).find((key) => key.trim().toLowerCase() === normalized);
|
|
3246
|
+
}
|
|
3247
|
+
|
|
3248
|
+
/**
|
|
3249
|
+
* The classifier settings that apply while `presetName` is the active preset:
|
|
3250
|
+
* the top-level block with that preset's `backend` / `model` override on top.
|
|
3251
|
+
* The preset name is matched like `/preset` matches it (exact, then
|
|
3252
|
+
* case-insensitive); a `presets` key that matches no preset is noticed at load.
|
|
3253
|
+
*/
|
|
3254
|
+
export function resolveClassifierForPreset(
|
|
3255
|
+
classifier: ResolvedClassifier,
|
|
3256
|
+
presetName: string,
|
|
3257
|
+
): ResolvedClassifier {
|
|
3258
|
+
const key = findPresetOverrideKey(classifier.presets, presetName);
|
|
3259
|
+
const override = key === undefined ? undefined : classifier.presets[key];
|
|
3260
|
+
if (override === undefined) return classifier;
|
|
3261
|
+
return Object.freeze({
|
|
3262
|
+
...classifier,
|
|
3263
|
+
backend: override.backend ?? classifier.backend,
|
|
3264
|
+
model: override.model !== undefined ? override.model : classifier.model,
|
|
3265
|
+
});
|
|
3266
|
+
}
|
|
3267
|
+
|
|
3268
|
+
/**
|
|
3269
|
+
* `enforcement.escalate.variantSteps` for one host (A15, QA-1.1-4).
|
|
3270
|
+
*
|
|
3271
|
+
* - On v1 it is always `none`: variant steps do not exist there (D1), so even an
|
|
3272
|
+
* explicit value is ignored.
|
|
3273
|
+
* - On v2 an explicit value always wins. Absent, the default is `auto` when the
|
|
3274
|
+
* config has a `routing` block and `none` when it has not, so that a config
|
|
3275
|
+
* without `routing` keeps today's ladder byte for byte (D2).
|
|
3276
|
+
*/
|
|
3277
|
+
export function resolveVariantSteps(cfg: RouterConfig | undefined, host: RouterHost): VariantStepsMode {
|
|
3278
|
+
if (host === "v1") return "none";
|
|
3279
|
+
const explicit = cfg?.enforcement?.escalate?.variantSteps;
|
|
3280
|
+
if (explicit !== undefined) return explicit;
|
|
3281
|
+
return cfg?.routing !== undefined ? "auto" : "none";
|
|
3282
|
+
}
|
|
3283
|
+
|
|
3284
|
+
/** One rung of a tier's ladder, fully resolved. */
|
|
3285
|
+
export interface ResolvedCandidate {
|
|
3286
|
+
readonly model: string;
|
|
3287
|
+
/** Absent = the model's default variant. */
|
|
3288
|
+
readonly variant?: string;
|
|
3289
|
+
readonly costRatio: number;
|
|
3290
|
+
}
|
|
3291
|
+
|
|
3292
|
+
const NO_CANDIDATES: readonly ResolvedCandidate[] = Object.freeze([]);
|
|
3293
|
+
|
|
3294
|
+
/**
|
|
3295
|
+
* The ladder of rungs for `tierName` in the active preset (D10, D12).
|
|
3296
|
+
*
|
|
3297
|
+
* Without `candidates` (or with an empty list) it is exactly one rung: the
|
|
3298
|
+
* tier's own `(model, variant, costRatio)`. With `candidates` it is those
|
|
3299
|
+
* entries, in order, each completed from the tier: `model` and `costRatio`
|
|
3300
|
+
* are inherited when omitted, `variant` is not. An unknown tier yields an
|
|
3301
|
+
* empty ladder. Never throws.
|
|
3302
|
+
*/
|
|
3303
|
+
export function resolveCandidates(tierName: string, cfg: RouterConfig): readonly ResolvedCandidate[] {
|
|
3304
|
+
const presetName = resolvePresetName(cfg, cfg.activePreset);
|
|
3305
|
+
const preset = presetName !== undefined && Object.hasOwn(cfg.presets, presetName) ? cfg.presets[presetName] : undefined;
|
|
3306
|
+
const tier = preset !== undefined && Object.hasOwn(preset, tierName) ? preset[tierName] : undefined;
|
|
3307
|
+
if (tier === undefined) return NO_CANDIDATES;
|
|
3308
|
+
|
|
3309
|
+
const tierCostRatio = tier.costRatio ?? tierDefaultsFor(tierName).costRatio;
|
|
3310
|
+
const rung = (model: string, variant: string | undefined, costRatio: number): ResolvedCandidate =>
|
|
3311
|
+
Object.freeze(variant === undefined ? { model, costRatio } : { model, variant, costRatio });
|
|
3312
|
+
|
|
3313
|
+
const listed = tier.candidates;
|
|
3314
|
+
if (listed === undefined || candidatesProblem(tierName, tier) !== undefined || !hasExplicitCandidates(tier)) {
|
|
3315
|
+
return Object.freeze([rung(tier.model, tier.variant, tierCostRatio)]);
|
|
3316
|
+
}
|
|
3317
|
+
return Object.freeze(
|
|
3318
|
+
listed.map((c) => rung(c.model ?? tier.model, c.variant, c.costRatio ?? tierCostRatio)),
|
|
3319
|
+
);
|
|
3320
|
+
}
|
|
3321
|
+
/**
|
|
3322
|
+
* The extra lines of the bare `/router` status view: the marker
|
|
3323
|
+
* `router: engine=<mode> build=<version>+<sha7>` (the engine is the one
|
|
3324
|
+
* *applied* on `host`, so always `static` on v1) followed by one
|
|
3325
|
+
* `router: config notice: …` line per notice of the config last loaded for `dir`
|
|
3326
|
+
* (QA-1.1-10). Passing `logger` makes the once-per-process v1 notice go through
|
|
3327
|
+
* the plugin logger.
|
|
3328
|
+
*/
|
|
3329
|
+
export function routerStatusLines(
|
|
3330
|
+
cfg: RouterConfig,
|
|
3331
|
+
host: RouterHost,
|
|
3332
|
+
logger?: Pick<PluginLogger, "warn">,
|
|
3333
|
+
dir?: string,
|
|
3334
|
+
): string[] {
|
|
3335
|
+
return [
|
|
3336
|
+
formatRouterLine(resolveRouting(cfg, host, logger).engine),
|
|
3337
|
+
...pluginAgentLines(cfg),
|
|
3338
|
+
...getConfigNotices(dir).map((notice) => `router: config notice: ${notice.message}`),
|
|
3339
|
+
];
|
|
3340
|
+
}
|
|
3341
|
+
|
|
3342
|
+
/**
|
|
3343
|
+
* The `/router` "Plugin agents" listing (#81): one line per agent of the
|
|
3344
|
+
* `agents` block. Empty without the block, so `/router` output is unchanged.
|
|
3345
|
+
*/
|
|
3346
|
+
export function pluginAgentLines(cfg: RouterConfig): string[] {
|
|
3347
|
+
const agents = cfg.agents;
|
|
3348
|
+
if (agents === undefined) return [];
|
|
3349
|
+
const names = Object.keys(agents);
|
|
3350
|
+
if (names.length === 0) return [];
|
|
3351
|
+
const preset = resolveActiveTiers(cfg);
|
|
3352
|
+
return [
|
|
3353
|
+
"router: Plugin agents:",
|
|
3354
|
+
...names.map((name) => {
|
|
3355
|
+
const agent = agents[name];
|
|
3356
|
+
const tier = preset !== undefined && Object.hasOwn(preset, agent.tier) ? preset[agent.tier] : undefined;
|
|
3357
|
+
const policy = agent.readOnly === true ? "read-only" : "custom permission";
|
|
3358
|
+
const model = tier === undefined ? "?" : `${tier.model}${tier.variant ? `#${tier.variant}` : ""}`;
|
|
3359
|
+
return `router: ${name} → ${agent.tier} (${model}), ${policy}`;
|
|
3360
|
+
}),
|
|
3361
|
+
];
|
|
3362
|
+
}
|