tuxevil-rotator 4.3.0 → 4.4.1

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +5 -2
  3. package/package.json +5 -1
  4. package/src/access-evidence.ts +153 -0
  5. package/src/access-probe.ts +85 -0
  6. package/src/admin-auth.ts +4 -1
  7. package/src/auto-access-shadow.ts +11 -0
  8. package/src/auto-model-access.ts +185 -0
  9. package/src/auto-output-health.ts +12 -0
  10. package/src/auto-routing-evaluation.ts +80 -0
  11. package/src/auto-routing-quality.ts +308 -0
  12. package/src/auto-routing.ts +403 -26
  13. package/src/compat.ts +223 -36
  14. package/src/compression/index.ts +6 -6
  15. package/src/compression/lite.ts +3 -9
  16. package/src/compression/rtk/index.ts +0 -3
  17. package/src/config-defaults.ts +7 -0
  18. package/src/dashboard.ts +5 -0
  19. package/src/db-store.ts +10 -0
  20. package/src/index.ts +2 -0
  21. package/src/model-access-api.ts +74 -0
  22. package/src/model-access.ts +56 -0
  23. package/src/ollama-output-gate.ts +18 -0
  24. package/src/onboarding.ts +1 -1
  25. package/src/provider-catalog-evidence.ts +26 -0
  26. package/src/providers/google-antigravity/dynamic-catalog.ts +8 -0
  27. package/src/providers/google-antigravity/quota.ts +3 -0
  28. package/src/providers/ollama/context-window.ts +13 -0
  29. package/src/providers/ollama/quota.ts +4 -0
  30. package/src/providers/ollama/translators.ts +19 -2
  31. package/src/providers/openai-codex/compat.ts +5 -1
  32. package/src/providers/openai-codex/credentials.ts +22 -6
  33. package/src/providers/openai-codex/index.ts +9 -1
  34. package/src/providers/openai-codex/quota.ts +19 -6
  35. package/src/providers/opencode-zen/forward.ts +1 -1
  36. package/src/providers/opencode-zen/quota.ts +2 -0
  37. package/src/proxy.ts +78 -3
  38. package/src/quota-observation.ts +26 -0
  39. package/src/quota-pools.ts +322 -0
  40. package/src/rotator.ts +151 -38
  41. package/src/settings-repository.ts +1 -0
  42. package/src/telemetry.ts +3 -1
  43. package/src/types.ts +28 -0
  44. package/src/usage-limits-auth.ts +24 -0
  45. package/src/usage-limits.ts +148 -0
  46. package/src/validators.ts +26 -0
  47. package/src/web/components/icons.tsx +15 -0
  48. package/src/web/components/overlays.tsx +4 -0
  49. package/src/web/components/ui.tsx +9 -9
  50. package/src/web/lib/playground.ts +35 -0
  51. package/src/web/lib/pool-navigation.ts +4 -0
  52. package/src/web/lib/pools.ts +2 -243
  53. package/src/web/pages/AccountDetail.tsx +2 -1
  54. package/src/web/pages/ModelAccess.tsx +88 -0
  55. package/src/web/pages/Models.tsx +2 -0
  56. package/src/web/pages/Overview.tsx +26 -9
  57. package/src/web/pages/Playground.tsx +1132 -551
  58. package/src/web/pages/Transcription.tsx +304 -170
  59. package/src/web/state/api.ts +3 -0
  60. package/src/web/styles/app.css +501 -45
@@ -0,0 +1,80 @@
1
+ /** Small deterministic checks for bounded tasks; not a substitute for human review. */
2
+ export interface RoutingEvalCase {
3
+ id: string;
4
+ prompt: string;
5
+ expected: string;
6
+ }
7
+ export interface RoutingEvalResult {
8
+ caseId: string;
9
+ requestedModel: string;
10
+ servedModel: string | null;
11
+ passed: boolean;
12
+ latencyMs: number;
13
+ inputTokens: number | null;
14
+ outputTokens: number | null;
15
+ answerChars?: number;
16
+ finishReason?: string | null;
17
+ error?: string;
18
+ }
19
+
20
+ export function parseRoutingEvalCases(input: unknown): RoutingEvalCase[] {
21
+ if (!Array.isArray(input) || !input.length || input.length > 100) throw new Error("Expected 1–100 evaluation cases");
22
+ const ids = new Set<string>();
23
+ return input.map(value => {
24
+ if (!value || typeof value !== "object") throw new Error("Invalid evaluation case");
25
+ const item = value as Record<string, unknown>;
26
+ for (const field of ["id", "prompt", "expected"]) {
27
+ if (typeof item[field] !== "string" || !(item[field] as string).trim()) throw new Error(`Missing ${field}`);
28
+ }
29
+ if (ids.has(item.id as string)) throw new Error("Duplicate case ID");
30
+ ids.add(item.id as string);
31
+ return { id: item.id as string, prompt: item.prompt as string, expected: item.expected as string };
32
+ });
33
+ }
34
+
35
+ export async function evaluateRouting(
36
+ cases: RoutingEvalCase[],
37
+ models: string[],
38
+ complete: (model: string, prompt: string) => Promise<unknown>,
39
+ options: { maxFailuresPerModel?: number; onResult?: (row: RoutingEvalResult) => Promise<void> } = {},
40
+ ): Promise<RoutingEvalResult[]> {
41
+ const results: RoutingEvalResult[] = [];
42
+ const failures = new Map<string, number>();
43
+ const tokens = (value: unknown): number | null => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
44
+ for (const [index, task] of cases.entries()) {
45
+ // Alternate order to reduce consistent warmup/order bias.
46
+ for (const model of index % 2 ? [...models].reverse() : models) {
47
+ const started = performance.now();
48
+ const row: RoutingEvalResult = { caseId: task.id, requestedModel: model, servedModel: null, passed: false, latencyMs: 0, inputTokens: null, outputTokens: null };
49
+ if ((failures.get(model) ?? 0) >= (options.maxFailuresPerModel ?? Infinity)) {
50
+ row.error = "model-skipped-after-failure";
51
+ results.push(row);
52
+ await options.onResult?.(row);
53
+ continue;
54
+ }
55
+ try {
56
+ const response = await complete(model, task.prompt) as { model?: unknown; choices?: { message?: { content?: unknown }; finish_reason?: unknown }[]; usage?: { prompt_tokens?: unknown; completion_tokens?: unknown } };
57
+ const content = response?.choices?.[0]?.message?.content;
58
+ if (typeof content !== "string") throw new Error("Missing text completion");
59
+ row.answerChars = content.length;
60
+ const finish = response.choices?.[0]?.finish_reason;
61
+ row.finishReason = typeof finish === "string" && ["stop", "length", "tool_calls", "content_filter"].includes(finish) ? finish : null;
62
+ if (!content.trim()) throw Object.assign(new Error("Empty completion"), { evalError: "empty-completion" });
63
+ row.passed = content.trim() === task.expected.trim();
64
+ row.servedModel = typeof response.model === "string" ? response.model : null;
65
+ row.inputTokens = tokens(response.usage?.prompt_tokens);
66
+ row.outputTokens = tokens(response.usage?.completion_tokens);
67
+ } catch (error) {
68
+ // Do not copy provider errors that could contain request text or secrets.
69
+ const status = (error as { status?: unknown } | null)?.status;
70
+ row.error = (error as { evalError?: unknown } | null)?.evalError === "empty-completion" ? "empty-completion" : typeof status === "number" && Number.isInteger(status) && status >= 400 && status <= 599
71
+ ? `http-${status}` : "completion-failed";
72
+ failures.set(model, (failures.get(model) ?? 0) + 1);
73
+ }
74
+ row.latencyMs = Math.round((performance.now() - started) * 100) / 100;
75
+ results.push(row);
76
+ await options.onResult?.(row);
77
+ }
78
+ }
79
+ return results;
80
+ }
@@ -0,0 +1,308 @@
1
+ /**
2
+ * Dated Artificial Analysis Intelligence Index snapshot used only to assess
3
+ * routing decisions. It is deliberately separate from selection policy:
4
+ * benchmark evidence must never grant access or change a selected model.
5
+ */
6
+ export type AAScoreVersion = "v5.0" | "v4.3.2";
7
+ export type AAScoreAlignment = "model-effort-exact" | "effort-proxy" | "base-model-proxy" | "estimated" | "conflicted";
8
+
9
+ interface AAScoreRecord {
10
+ name: string;
11
+ effort: string | null;
12
+ scores: Partial<Record<AAScoreVersion, number>>;
13
+ source: string;
14
+ note?: string;
15
+ }
16
+
17
+ interface AARouterAlias {
18
+ scoreId: string;
19
+ alignment: AAScoreAlignment;
20
+ }
21
+
22
+ export interface AARoutingCandidate {
23
+ providerId: string;
24
+ modelId: string;
25
+ }
26
+
27
+ export interface AARoutingAssessment {
28
+ status: "ranked" | "insufficient-comparison" | "unscored" | "conflicted";
29
+ metric: "artificial-analysis-intelligence-index";
30
+ snapshot: string;
31
+ scoreVersion?: AAScoreVersion;
32
+ selectedModel: string;
33
+ selectedScore?: number;
34
+ benchmarkModel?: string;
35
+ benchmarkEffort?: string | null;
36
+ benchmarkSource?: string;
37
+ benchmarkNote?: string;
38
+ servingMatch?: "not-verified";
39
+ alignment?: AAScoreAlignment;
40
+ rank?: number;
41
+ comparableCandidates: number;
42
+ scoredCandidates: number;
43
+ unscoredCandidates: number;
44
+ estimatedCandidates: number;
45
+ bestCandidate?: { providerId: string; modelId: string; score: number };
46
+ gapToBest?: number;
47
+ relativeToBest?: number;
48
+ }
49
+
50
+ export const AA_ROUTING_SCORE_SNAPSHOT = "2026-10-31";
51
+
52
+ const SCORE_RECORDS: Record<string, AAScoreRecord> = {
53
+ "gemini-3.8-flash-high": {
54
+ name: "Gemini 3.8 Flash", effort: "High", scores: { "v4.3.2": 41, "v5.0": 31 },
55
+ source: "https://artificialanalysis.ai/models/comparisons/gemini-4-argon-vs-gemini-3-8-flash",
56
+ },
57
+ "gemini-4-argon-high": {
58
+ name: "Gemini 4 Argon", effort: "High", scores: { "v4.3.2": 53, "v5.0": 50 },
59
+ source: "https://artificialanalysis.ai/models/comparisons/gemini-4-argon-vs-gemini-3-8-flash",
60
+ },
61
+ "claude-sonnet-5-5-max": {
62
+ name: "Claude Sonnet 5.5", effort: "Max", scores: { "v4.3.2": 56, "v5.0": 54 },
63
+ source: "https://artificialanalysis.ai/models/comparisons/claude-opus-5-5-vs-claude-sonnet-5-5",
64
+ },
65
+ "claude-opus-5-5-max": {
66
+ name: "Claude Opus 5.5", effort: "Max", scores: { "v4.3.2": 58, "v5.0": 58 },
67
+ source: "https://artificialanalysis.ai/models/comparisons/claude-opus-5-5-vs-claude-sonnet-5-5",
68
+ },
69
+ "gpt-6-luna-max": {
70
+ name: "GPT-6 Luna", effort: "Max", scores: { "v4.3.2": 38, "v5.0": 28 },
71
+ source: "https://artificialanalysis.ai/models/releases/comparisons/gpt-6-1-terra-vs-gpt-6-luna",
72
+ },
73
+ beam: {
74
+ name: "Beam", effort: null, scores: { "v4.3.2": 30, "v5.0": 18 },
75
+ source: "https://artificialanalysis.ai/models/comparisons/reflection-beam-vs-step-5",
76
+ },
77
+ "gpt-6-astra-max": {
78
+ name: "GPT-6 Astra", effort: "Max", scores: { "v4.3.2": 53, "v5.0": 57 },
79
+ source: "https://artificialanalysis.ai/models/gpt-6-astra/",
80
+ },
81
+ "gpt-6-sol-max": {
82
+ name: "GPT-6 Sol", effort: "Max", scores: { "v4.3.2": 48 },
83
+ source: "https://artificialanalysis.ai/models/gpt-6-sol/",
84
+ },
85
+ "gpt-5.6-sol-max": {
86
+ name: "GPT-5.6 Sol", effort: "Max", scores: { "v4.3.2": 47 },
87
+ source: "https://artificialanalysis.ai/models/gpt-5-6-sol",
88
+ },
89
+ "gpt-5.6-terra-max": {
90
+ name: "GPT-5.6 Terra", effort: "Max", scores: { "v4.3.2": 42 },
91
+ source: "https://artificialanalysis.ai/models/gpt-5-6-terra",
92
+ },
93
+ "gpt-5.6-luna-max": {
94
+ name: "GPT-5.6 Luna", effort: "Max", scores: { "v4.3.2": 37 },
95
+ source: "https://artificialanalysis.ai/models/gpt-5-6-luna",
96
+ },
97
+ "gpt-6.1-terra-max": {
98
+ name: "GPT-6.1 Terra", effort: "Max", scores: { "v5.0": 51 },
99
+ source: "https://artificialanalysis.ai/models/gpt-6-1-terra",
100
+ },
101
+ "claude-sonnet-4-6-max": {
102
+ name: "Claude Sonnet 4.6", effort: "Max", scores: { "v4.3.2": 30 },
103
+ source: "https://artificialanalysis.ai/models/releases/claude-sonnet-4-6",
104
+ note: "La ficha actual también expone una variante no-reasoning con otro resultado.",
105
+ },
106
+ "claude-opus-4-6-max": {
107
+ name: "Claude Opus 4.6", effort: "Max", scores: { "v4.3.2": 32 },
108
+ source: "https://artificialanalysis.ai/models/claude-opus-4-6-adaptive/",
109
+ note: "Artificial Analysis marca esta observación como estimada.",
110
+ },
111
+ "gemma-4-31b-reasoning": {
112
+ name: "Gemma 4 31B", effort: "Reasoning", scores: { "v4.3.2": 15 },
113
+ source: "https://artificialanalysis.ai/models/gemma-4-31b/",
114
+ },
115
+ "gpt-oss-20b-high": {
116
+ name: "gpt-oss-20b", effort: "High", scores: { "v4.3.2": 9 },
117
+ source: "https://artificialanalysis.ai/models/gpt-oss-20b",
118
+ note: "La variante Low figura con 10*; la ruta del router no fija ese esfuerzo.",
119
+ },
120
+ "gpt-oss-120b-high": {
121
+ name: "gpt-oss-120b", effort: "High", scores: { "v4.3.2": 12 },
122
+ source: "https://artificialanalysis.ai/models/gpt-oss-120b",
123
+ note: "La variante Low figura con 10*; la ruta del router no fija ese esfuerzo.",
124
+ },
125
+ "nemotron-3-nano-30b-reasoning": {
126
+ name: "Nemotron 3 Nano 30B A3B", effort: "Reasoning", scores: { "v4.3.2": 9 },
127
+ source: "https://artificialanalysis.ai/models/nvidia-nemotron-3-nano-30b-a3b",
128
+ note: "La variante no-reasoning figura con 7.",
129
+ },
130
+ "nemotron-3-super-reasoning": {
131
+ name: "Nemotron 3 Super", effort: "Reasoning", scores: { "v4.3.2": 13 },
132
+ source: "https://artificialanalysis.ai/models/nvidia-nemotron-3-super-120b-a12b",
133
+ },
134
+ "nemotron-3-ultra-reasoning": {
135
+ name: "Nemotron 3 Ultra", effort: "Reasoning", scores: { "v4.3.2": 23, "v5.0": 12 },
136
+ source: "https://artificialanalysis.ai/models/nvidia-nemotron-3-ultra-550b-a55b",
137
+ },
138
+ "nemotron-3.5-lightning-conflicted": {
139
+ name: "Nemotron 3.5 Lightning", effort: "Reasoning", scores: {},
140
+ source: "https://artificialanalysis.ai/models/comparisons/nemotron-3-5-lightning-vs-mimo-v2-5-0424",
141
+ note: "Se excluye del ranking: comparaciones actuales muestran 13 y el artículo de lanzamiento 24.",
142
+ },
143
+ "mimo-v2.5": {
144
+ name: "MiMo-V2.5", effort: "Reasoning", scores: { "v4.3.2": 22 },
145
+ source: "https://artificialanalysis.ai/models/mimo-v2-5-0424",
146
+ note: "El endpoint Zen es un alias gratuito; no se confirmó que sirva la misma configuración.",
147
+ },
148
+ "ling-3.0-flash-fin": {
149
+ name: "Ling-3.0-flash-Fin", effort: "Reasoning", scores: { "v4.3.2": 23 },
150
+ source: "https://artificialanalysis.ai/models/ling-3-0-flash-fin",
151
+ note: "El endpoint Zen puede diferir de la configuración evaluada por Artificial Analysis.",
152
+ },
153
+ "muse-spark-1.3-max": {
154
+ name: "Muse Spark 1.3", effort: "Max", scores: { "v4.3.2": 48, "v5.0": 36 },
155
+ source: "https://artificialanalysis.ai/models/muse-spark-1-3",
156
+ note: "El endpoint Zen Contributor puede diferir de la variante Max medida.",
157
+ },
158
+ };
159
+
160
+ /** Exact provider/model allowlist; unknown dynamic catalog entries remain unscored. */
161
+ const ROUTER_ALIASES: Record<string, AARouterAlias> = {
162
+ "google-antigravity/gemini-3.8-flash-low": { scoreId: "gemini-3.8-flash-high", alignment: "effort-proxy" },
163
+ "google-antigravity/gemini-3.8-flash-medium": { scoreId: "gemini-3.8-flash-high", alignment: "effort-proxy" },
164
+ "google-antigravity/gemini-3.8-flash-high": { scoreId: "gemini-3.8-flash-high", alignment: "model-effort-exact" },
165
+ "google-antigravity/gemini-4-argon-medium": { scoreId: "gemini-4-argon-high", alignment: "effort-proxy" },
166
+ "google-antigravity/gemini-4-argon-high": { scoreId: "gemini-4-argon-high", alignment: "model-effort-exact" },
167
+ "google-antigravity/gemini-4-argon": { scoreId: "gemini-4-argon-high", alignment: "effort-proxy" },
168
+ "google-antigravity/claude-sonnet-5-5": { scoreId: "claude-sonnet-5-5-max", alignment: "effort-proxy" },
169
+ "google-antigravity/claude-sonnet-5-5-medium": { scoreId: "claude-sonnet-5-5-max", alignment: "effort-proxy" },
170
+ "google-antigravity/claude-sonnet-5-5-high": { scoreId: "claude-sonnet-5-5-max", alignment: "effort-proxy" },
171
+ "google-antigravity/claude-opus-5-5": { scoreId: "claude-opus-5-5-max", alignment: "effort-proxy" },
172
+ "google-antigravity/claude-opus-5-5-high": { scoreId: "claude-opus-5-5-max", alignment: "effort-proxy" },
173
+ "google-antigravity/claude-sonnet-4-6": { scoreId: "claude-sonnet-4-6-max", alignment: "effort-proxy" },
174
+ "google-antigravity/claude-sonnet-4-6-thinking": { scoreId: "claude-sonnet-4-6-max", alignment: "effort-proxy" },
175
+ "google-antigravity/claude-opus-4-6": { scoreId: "claude-opus-4-6-max", alignment: "estimated" },
176
+ "google-antigravity/claude-opus-4-6-thinking": { scoreId: "claude-opus-4-6-max", alignment: "estimated" },
177
+ "google-antigravity/claude-sonnet-4-6-high": { scoreId: "claude-sonnet-4-6-max", alignment: "effort-proxy" },
178
+ "google-antigravity/claude-opus-4-6-high": { scoreId: "claude-opus-4-6-max", alignment: "estimated" },
179
+ "openai-codex/gpt-6-astra": { scoreId: "gpt-6-astra-max", alignment: "effort-proxy" },
180
+ "openai-codex/gpt-6-sol": { scoreId: "gpt-6-sol-max", alignment: "effort-proxy" },
181
+ "openai-codex/gpt-6-luna": { scoreId: "gpt-6-luna-max", alignment: "effort-proxy" },
182
+ "openai-codex/gpt-5.6-sol": { scoreId: "gpt-5.6-sol-max", alignment: "effort-proxy" },
183
+ "openai-codex/gpt-5.6-terra": { scoreId: "gpt-5.6-terra-max", alignment: "effort-proxy" },
184
+ "openai-codex/gpt-5.6-luna": { scoreId: "gpt-5.6-luna-max", alignment: "effort-proxy" },
185
+ "openai-codex/gpt-6.1-terra": { scoreId: "gpt-6.1-terra-max", alignment: "effort-proxy" },
186
+ "ollama/beam": { scoreId: "beam", alignment: "base-model-proxy" },
187
+ "ollama/gemma4:31b": { scoreId: "gemma-4-31b-reasoning", alignment: "base-model-proxy" },
188
+ "ollama/gpt-oss:20b": { scoreId: "gpt-oss-20b-high", alignment: "base-model-proxy" },
189
+ "ollama/gpt-oss:120b": { scoreId: "gpt-oss-120b-high", alignment: "base-model-proxy" },
190
+ "ollama/nemotron-3-nano:30b": { scoreId: "nemotron-3-nano-30b-reasoning", alignment: "base-model-proxy" },
191
+ "ollama/nemotron-3-super": { scoreId: "nemotron-3-super-reasoning", alignment: "base-model-proxy" },
192
+ "ollama/nemotron-3-ultra": { scoreId: "nemotron-3-ultra-reasoning", alignment: "base-model-proxy" },
193
+ "opencode-zen/mimo-v2.5-free": { scoreId: "mimo-v2.5", alignment: "base-model-proxy" },
194
+ "opencode-zen/ling-3.0-flash-fin-free": { scoreId: "ling-3.0-flash-fin", alignment: "base-model-proxy" },
195
+ "opencode-zen/nemotron-3-ultra-free": { scoreId: "nemotron-3-ultra-reasoning", alignment: "base-model-proxy" },
196
+ "opencode-zen/nemotron-3.5-lightning-free": { scoreId: "nemotron-3.5-lightning-conflicted", alignment: "conflicted" },
197
+ "opencode-zen/muse-spark-1.3-contributor-free": { scoreId: "muse-spark-1.3-max", alignment: "base-model-proxy" },
198
+ };
199
+
200
+ function indexValue(record: AAScoreRecord, version: AAScoreVersion): number | undefined {
201
+ const value = record.scores[version];
202
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
203
+ }
204
+
205
+ function resolveCandidate(candidate: AARoutingCandidate): { record: AAScoreRecord; alignment: AAScoreAlignment } | null {
206
+ const alias = ROUTER_ALIASES[`${candidate.providerId}/${candidate.modelId}`];
207
+ if (!alias) return null;
208
+ const record = SCORE_RECORDS[alias.scoreId];
209
+ return record ? { record, alignment: alias.alignment } : null;
210
+ }
211
+
212
+ /**
213
+ * Rank a selected route against only the candidates available in that decision.
214
+ * Version choice is based on coverage, with V5 preferred on ties; V4 and V5
215
+ * scores are never compared numerically or converted into one another.
216
+ */
217
+ export function assessAARoutingSelection(
218
+ selected: AARoutingCandidate,
219
+ candidates: AARoutingCandidate[],
220
+ ): AARoutingAssessment {
221
+ const selectedResolved = resolveCandidate(selected);
222
+ const base: AARoutingAssessment = {
223
+ status: "unscored",
224
+ metric: "artificial-analysis-intelligence-index",
225
+ snapshot: AA_ROUTING_SCORE_SNAPSHOT,
226
+ selectedModel: `${selected.providerId}/${selected.modelId}`,
227
+ comparableCandidates: candidates.length,
228
+ scoredCandidates: 0,
229
+ unscoredCandidates: candidates.length,
230
+ estimatedCandidates: 0,
231
+ };
232
+ if (!selectedResolved) return base;
233
+ if (selectedResolved.alignment === "conflicted") return {
234
+ ...base,
235
+ status: "conflicted",
236
+ alignment: "conflicted",
237
+ benchmarkModel: selectedResolved.record.name,
238
+ benchmarkEffort: selectedResolved.record.effort,
239
+ benchmarkSource: selectedResolved.record.source,
240
+ servingMatch: "not-verified",
241
+ ...(selectedResolved.record.note ? { benchmarkNote: selectedResolved.record.note } : {}),
242
+ };
243
+
244
+ const selectedVersions = (["v5.0", "v4.3.2"] as const)
245
+ .filter(version => indexValue(selectedResolved.record, version) !== undefined);
246
+ if (!selectedVersions.length) return { ...base, status: "conflicted", alignment: selectedResolved.alignment };
247
+
248
+ const resolved = candidates.map(candidate => ({
249
+ candidate,
250
+ model: resolveCandidate(candidate),
251
+ }));
252
+ const versions = selectedVersions
253
+ .map(version => ({
254
+ version,
255
+ coverage: resolved.filter(item => item.model && indexValue(item.model.record, version) !== undefined).length,
256
+ priority: version === "v5.0" ? 1 : 0,
257
+ }))
258
+ .sort((a, b) => b.coverage - a.coverage || b.priority - a.priority);
259
+ const scoreVersion = versions[0]?.version;
260
+ if (!scoreVersion) return { ...base, status: "conflicted", alignment: selectedResolved.alignment };
261
+
262
+ const selectedScore = indexValue(selectedResolved.record, scoreVersion);
263
+ if (selectedScore === undefined) return { ...base, status: "conflicted", alignment: selectedResolved.alignment };
264
+ const scored = resolved.flatMap(item => {
265
+ if (!item.model) return [];
266
+ const score = indexValue(item.model.record, scoreVersion);
267
+ if (score === undefined) return [];
268
+ return [{
269
+ providerId: item.candidate.providerId,
270
+ modelId: item.candidate.modelId,
271
+ score,
272
+ alignment: item.model.alignment,
273
+ }];
274
+ });
275
+ const selectedId = `${selected.providerId}/${selected.modelId}`;
276
+ const selectedComparable = scored.find(item => `${item.providerId}/${item.modelId}` === selectedId);
277
+ if (!selectedComparable) return { ...base, status: "conflicted", alignment: selectedResolved.alignment };
278
+ const best = [...scored].sort((a, b) => b.score - a.score || a.providerId.localeCompare(b.providerId) || a.modelId.localeCompare(b.modelId))[0];
279
+ const greater = scored.filter(item => item.score > selectedScore).length;
280
+ const estimatedCandidates = scored.filter(item => item.alignment === "estimated").length;
281
+ const unscoredCandidates = Math.max(0, candidates.length - scored.length);
282
+ return {
283
+ ...base,
284
+ status: scored.length >= 2 ? "ranked" : "insufficient-comparison",
285
+ scoreVersion,
286
+ selectedScore,
287
+ benchmarkModel: selectedResolved.record.name,
288
+ benchmarkEffort: selectedResolved.record.effort,
289
+ benchmarkSource: selectedResolved.record.source,
290
+ servingMatch: "not-verified",
291
+ ...(selectedResolved.record.note ? { benchmarkNote: selectedResolved.record.note } : {}),
292
+ alignment: selectedResolved.alignment,
293
+ rank: greater + 1,
294
+ comparableCandidates: scored.length,
295
+ scoredCandidates: scored.length,
296
+ unscoredCandidates,
297
+ estimatedCandidates,
298
+ bestCandidate: best ? { providerId: best.providerId, modelId: best.modelId, score: best.score } : undefined,
299
+ gapToBest: best ? Number((best.score - selectedScore).toFixed(2)) : undefined,
300
+ relativeToBest: best && best.score > 0 ? Number((selectedScore / best.score).toFixed(4)) : undefined,
301
+ };
302
+ }
303
+
304
+ /** Resolve a public AA source and note for support tools and offline reports. */
305
+ export function getAAScoreSource(candidate: AARoutingCandidate): { name: string; source: string; note?: string } | null {
306
+ const resolved = resolveCandidate(candidate);
307
+ return resolved ? { name: resolved.record.name, source: resolved.record.source, ...(resolved.record.note ? { note: resolved.record.note } : {}) } : null;
308
+ }