tuxevil-rotator 4.2.2 → 4.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.
Files changed (84) hide show
  1. package/CHANGELOG.md +48 -1
  2. package/README.md +11 -4
  3. package/package.json +2 -1
  4. package/plugins/opencode-discovery/capabilities.d.mts +7 -0
  5. package/plugins/opencode-discovery/capabilities.mjs +54 -0
  6. package/plugins/opencode-discovery/index.d.mts +2 -1
  7. package/plugins/opencode-discovery/index.mjs +6 -1
  8. package/plugins/opencode-discovery/package.json +3 -1
  9. package/src/access-evidence.ts +153 -0
  10. package/src/access-probe.ts +85 -0
  11. package/src/admin-auth.ts +4 -1
  12. package/src/audio-transcription.ts +32 -6
  13. package/src/auto-access-shadow.ts +11 -0
  14. package/src/auto-model-access.ts +185 -0
  15. package/src/auto-output-health.ts +12 -0
  16. package/src/auto-routing-evaluation.ts +80 -0
  17. package/src/auto-routing-quality.ts +308 -0
  18. package/src/auto-routing.ts +403 -26
  19. package/src/cli.ts +3 -3
  20. package/src/compat/model-specs.ts +4 -0
  21. package/src/compat.ts +253 -37
  22. package/src/compression/index.ts +6 -6
  23. package/src/compression/lite.ts +3 -9
  24. package/src/compression/rtk/index.ts +0 -3
  25. package/src/config-defaults.ts +7 -0
  26. package/src/dashboard-app.ts +1 -0
  27. package/src/dashboard.ts +5 -0
  28. package/src/db-store.ts +10 -0
  29. package/src/index.ts +2 -0
  30. package/src/install-agent.ts +211 -129
  31. package/src/install-opencode.ts +80 -18
  32. package/src/model-access-api.ts +74 -0
  33. package/src/model-access.ts +56 -0
  34. package/src/ollama-output-gate.ts +18 -0
  35. package/src/onboarding.ts +1 -1
  36. package/src/provider-catalog-evidence.ts +26 -0
  37. package/src/providers/google-antigravity/catalog.ts +14 -6
  38. package/src/providers/google-antigravity/dynamic-catalog.ts +87 -3
  39. package/src/providers/google-antigravity/forward.ts +4 -2
  40. package/src/providers/google-antigravity/quota.ts +7 -0
  41. package/src/providers/ollama/context-window.ts +13 -0
  42. package/src/providers/ollama/forward.ts +10 -0
  43. package/src/providers/ollama/quota.ts +4 -0
  44. package/src/providers/ollama/translators.ts +19 -2
  45. package/src/providers/openai-codex/catalog.ts +157 -18
  46. package/src/providers/openai-codex/compat.ts +5 -1
  47. package/src/providers/openai-codex/credentials.ts +22 -6
  48. package/src/providers/openai-codex/index.ts +9 -1
  49. package/src/providers/openai-codex/quota.ts +19 -6
  50. package/src/providers/opencode-zen/forward.ts +1 -1
  51. package/src/providers/opencode-zen/quota.ts +2 -0
  52. package/src/proxy.ts +113 -5
  53. package/src/quota-observation.ts +26 -0
  54. package/src/quota-pools.ts +322 -0
  55. package/src/rotator.ts +167 -40
  56. package/src/settings-repository.ts +1 -0
  57. package/src/types.ts +106 -29
  58. package/src/usage-limits-auth.ts +24 -0
  59. package/src/usage-limits.ts +148 -0
  60. package/src/validators.ts +26 -0
  61. package/src/web/app.tsx +4 -0
  62. package/src/web/components/icons.tsx +15 -0
  63. package/src/web/components/overlays.tsx +4 -0
  64. package/src/web/components/ui.tsx +9 -9
  65. package/src/web/lib/audio-recorder.ts +159 -0
  66. package/src/web/lib/colors.ts +4 -0
  67. package/src/web/lib/playground-storage.ts +261 -0
  68. package/src/web/lib/playground.ts +483 -0
  69. package/src/web/lib/pool-navigation.ts +4 -0
  70. package/src/web/lib/pools.ts +2 -243
  71. package/src/web/nav.ts +1 -0
  72. package/src/web/pages/AccountDetail.tsx +2 -1
  73. package/src/web/pages/ModelAccess.tsx +88 -0
  74. package/src/web/pages/Models.tsx +2 -0
  75. package/src/web/pages/Overview.tsx +26 -9
  76. package/src/web/pages/Playground.tsx +1692 -0
  77. package/src/web/pages/Transcription.tsx +562 -0
  78. package/src/web/state/api.ts +6 -0
  79. package/src/web/state/playground-client.ts +136 -0
  80. package/src/web/state/playground.ts +69 -0
  81. package/src/web/state/router.ts +2 -2
  82. package/src/web/state/transcription-client.ts +93 -0
  83. package/src/web/styles/app.css +501 -0
  84. package/tools/telemetry-receiver/receiver.js +59 -46
@@ -4,6 +4,7 @@ import https from "node:https";
4
4
  import cp from "node:child_process";
5
5
  import crypto from "node:crypto";
6
6
  import fs from "node:fs";
7
+ import { requireAdmin, isSameOriginRequest } from "./admin-auth.js";
7
8
  import { readLimitedBody } from "./body-limit.js";
8
9
  import { authenticateVirtualKey, sendAuthErrorResponse, type KeyAuthResult } from "./key-auth.js";
9
10
  import { logger } from "./logger.js";
@@ -103,7 +104,7 @@ export function resolveMimeType(fileName: string, mimeType?: string): string {
103
104
  if (lower.endsWith(".mp3")) return "audio/mp3";
104
105
  if (lower.endsWith(".m4a")) return "audio/m4a";
105
106
  if (lower.endsWith(".webm")) return "audio/webm;codecs=opus";
106
- if (lower.endsWith(".ogg")) return "audio/ogg";
107
+ if (lower.endsWith(".ogg") || lower.endsWith(".oga")) return "audio/ogg";
107
108
  if (lower.endsWith(".flac")) return "audio/flac";
108
109
  if (lower.endsWith(".pcm")) return "audio/pcm;rate=16000";
109
110
  return "audio/wav";
@@ -819,16 +820,41 @@ export function getAudioDurationSeconds(audioBuffer: Buffer, mimeType: string):
819
820
  return undefined;
820
821
  }
821
822
 
822
- /**
823
- * Handles standard OpenAI-compatible POST /v1/audio/transcriptions
824
- */
823
+ /** Browser-only admin inference; public audio routes still require virtual keys. */
824
+ export async function handlePlaygroundAudioTranscriptions(
825
+ req: IncomingMessage,
826
+ res: ServerResponse,
827
+ rotator: AccountRotator,
828
+ ): Promise<void> {
829
+ if (!requireAdmin(req, res)) return;
830
+ if (!isSameOriginRequest(req)) {
831
+ res.writeHead(403, { "Content-Type": "application/json" });
832
+ res.end(JSON.stringify({ error: { message: "Transcription requests must come from the dashboard's own origin" } }));
833
+ return;
834
+ }
835
+ res.setHeader("Cache-Control", "no-store");
836
+ await handleAudioTranscriptions(req, res, rotator, true);
837
+ }
838
+
839
+ /** Handles standard OpenAI-compatible POST /v1/audio/transcriptions. */
825
840
  export async function handleOpenAIAudioTranscriptions(
826
841
  req: IncomingMessage,
827
842
  res: ServerResponse,
828
843
  rotator?: AccountRotator,
844
+ ): Promise<void> {
845
+ await handleAudioTranscriptions(req, res, rotator, false);
846
+ }
847
+
848
+ async function handleAudioTranscriptions(
849
+ req: IncomingMessage,
850
+ res: ServerResponse,
851
+ rotator: AccountRotator | undefined,
852
+ dashboardAdmin: boolean,
829
853
  ): Promise<void> {
830
854
  const requestStartedAt = Date.now();
831
- const initialAuth = await authenticateVirtualKey(req);
855
+ const initialAuth: KeyAuthResult = dashboardAdmin
856
+ ? { authenticated: true, key: null }
857
+ : await authenticateVirtualKey(req);
832
858
  if (!initialAuth.authenticated) {
833
859
  sendAuthErrorResponse(res, initialAuth);
834
860
  return;
@@ -933,7 +959,7 @@ export async function handleOpenAIAudioTranscriptions(
933
959
  ? resolveAudioTranscriptionModel(requestedModel ?? "whisper-1")
934
960
  : applyModelAlias(requestedModel ?? "whisper-1");
935
961
  spendModel = requestedModel ?? "whisper-1";
936
- const modelAuth = await authorizeAudioModel(req, executedModel, requestedModel);
962
+ const modelAuth = dashboardAdmin ? initialAuth : await authorizeAudioModel(req, executedModel, requestedModel);
937
963
  if (!modelAuth.authenticated) {
938
964
  logRequest("failure");
939
965
  sendAuthErrorResponse(res, modelAuth);
@@ -0,0 +1,11 @@
1
+ import type { AccountConfig } from "./types.js";
2
+ import { accessEvidenceStore, type AccessEvidenceStore } from "./access-evidence.js";
3
+ /** Inputs are operationally eligible accounts. One account's denial never excludes its siblings. */
4
+ export function summarizeAutoAccess(accounts: AccountConfig[], provider: string, model: string, store: AccessEvidenceStore = accessEvidenceStore(), now = Date.now()) {
5
+ let rejectedAccounts=0;
6
+ for(const account of accounts){
7
+ const latest=store.forAccount(account,now).observations.filter(o=>o.provider===provider&&o.model===model&&o.client==='unknown').sort((a,b)=>b.observedAt-a.observedAt)[0];
8
+ if(latest&&['model-unavailable','entitlement'].includes(latest.kind))rejectedAccounts++;
9
+ }
10
+ return {eligibleAccounts:accounts.length,rejectedAccounts,wouldExclude:accounts.length>0&&rejectedAccounts===accounts.length};
11
+ }
@@ -0,0 +1,185 @@
1
+ import { accessEvidenceStore, type AccessEvidenceStore } from "./access-evidence.js";
2
+ import { evaluateModelAccess, MODEL_ACCESS_RULES } from "./model-access.js";
3
+ import type { AccountConfig } from "./types.js";
4
+
5
+ export interface AutoModelAccessDecision {
6
+ eligible: boolean;
7
+ plan: string;
8
+ planSource:
9
+ | "provider-declaration"
10
+ | "operator-provider-default"
11
+ | "account-tier"
12
+ | "unknown";
13
+ reason: string;
14
+ }
15
+
16
+ export interface AutoAccountScope {
17
+ providerId: string;
18
+ modelId: string;
19
+ }
20
+
21
+ function matchesRule(rule: (typeof MODEL_ACCESS_RULES)[number], model: string): boolean {
22
+ if (rule.modelPrefix === "*-free") return model.endsWith("-free");
23
+ return rule.exact
24
+ ? rule.modelPrefix === model
25
+ : model === rule.modelPrefix || model.startsWith(`${rule.modelPrefix}-`);
26
+ }
27
+
28
+ function providersForAccount(account: AccountConfig): string[] {
29
+ const providers = account.credentials?.map((credential) => credential.provider) ?? [];
30
+ if (providers.length) return [...new Set(providers)];
31
+ return [
32
+ account.provider === "google"
33
+ ? "google-antigravity"
34
+ : account.provider ?? "google-antigravity",
35
+ ];
36
+ }
37
+
38
+ function accountTierPlan(account: AccountConfig, provider: string): string | undefined {
39
+ const tier = account.tier ?? account.type;
40
+ if (tier && ["free", "plus", "ultra", "team"].includes(tier)) return tier;
41
+ // The operator has confirmed that the configured Antigravity Pro accounts
42
+ // are paid. This inference applies only to their primary Google provider.
43
+ if (provider === "google-antigravity" && tier === "pro") return "pro-paid";
44
+ return undefined;
45
+ }
46
+
47
+ function isModelAccessRejection(kind: string): boolean {
48
+ return ["payment-or-plan", "entitlement", "model-unavailable"].includes(kind);
49
+ }
50
+
51
+ export function evaluateAutoModelAccess(
52
+ account: AccountConfig,
53
+ provider: string,
54
+ model: string,
55
+ store: AccessEvidenceStore = accessEvidenceStore(),
56
+ now = Date.now(),
57
+ ): AutoModelAccessDecision {
58
+ const evidence = store.forAccount(account, now);
59
+ const declared = evidence.plans
60
+ .filter((entry) => entry.provider === provider)
61
+ .sort((a, b) => b.observedAt - a.observedAt)[0];
62
+ let plan = declared?.plan ?? "unknown";
63
+ let planSource: AutoModelAccessDecision["planSource"] = declared
64
+ ? "provider-declaration"
65
+ : "unknown";
66
+
67
+ if (!declared && provider === "ollama") {
68
+ // The operator confirmed that all linked Ollama accounts are Free.
69
+ plan = "free";
70
+ planSource = "operator-provider-default";
71
+ } else if (!declared) {
72
+ const providers = providersForAccount(account);
73
+ const isPrimaryGoogle =
74
+ provider === "google-antigravity" &&
75
+ (account.provider === undefined ||
76
+ account.provider === "google" ||
77
+ account.provider === "google-antigravity");
78
+ if (isPrimaryGoogle || providers.length === 1) {
79
+ const inferred = accountTierPlan(account, provider);
80
+ if (inferred) {
81
+ plan = inferred;
82
+ planSource = "account-tier";
83
+ }
84
+ }
85
+ }
86
+
87
+ const latestObservation = evidence.observations
88
+ .filter(
89
+ (entry) =>
90
+ entry.provider === provider &&
91
+ entry.model === model &&
92
+ ["success", "payment-or-plan", "entitlement", "model-unavailable"].includes(
93
+ entry.kind,
94
+ ),
95
+ )
96
+ .sort(
97
+ (a, b) =>
98
+ b.observedAt - a.observedAt ||
99
+ Number(isModelAccessRejection(b.kind)) - Number(isModelAccessRejection(a.kind)),
100
+ )[0];
101
+ if (
102
+ latestObservation &&
103
+ isModelAccessRejection(latestObservation.kind)
104
+ ) {
105
+ return {
106
+ eligible: false,
107
+ plan,
108
+ planSource,
109
+ reason: `recent ${latestObservation.kind} rejection for this account and model`,
110
+ };
111
+ }
112
+
113
+ if (plan === "unknown") {
114
+ const hasPlanSpecificRule = MODEL_ACCESS_RULES.some((rule) =>
115
+ rule.provider === provider && matchesRule(rule, model),
116
+ );
117
+ if (provider === "openai-codex" || hasPlanSpecificRule) {
118
+ return {
119
+ eligible: false,
120
+ plan,
121
+ planSource,
122
+ reason: "provider plan is unknown for this model's access policy",
123
+ };
124
+ }
125
+ return {
126
+ eligible: true,
127
+ plan,
128
+ planSource,
129
+ reason: "no confirmed plan restriction for this model",
130
+ };
131
+ }
132
+
133
+ const matchingRules = MODEL_ACCESS_RULES.filter((rule) =>
134
+ rule.provider === provider &&
135
+ (rule.plans.includes(plan) || rule.plans.includes("*")) &&
136
+ matchesRule(rule, model),
137
+ );
138
+
139
+ const decision = evaluateModelAccess({
140
+ provider,
141
+ model,
142
+ plan,
143
+ at: new Date(now).toISOString(),
144
+ });
145
+
146
+ // Free accounts have a complete, operator-confirmed catalog for these
147
+ // providers. Unknown or stale entries must not silently inherit free access.
148
+ if ((provider === "ollama" || provider === "openai-codex") && plan === "free") {
149
+ const confirmedAllow = matchingRules.some((rule) =>
150
+ rule.state === "allowed" && rule.evidence === "operator-confirmed",
151
+ );
152
+ if (!confirmedAllow || decision.state === "unknown") {
153
+ return {
154
+ eligible: false,
155
+ plan,
156
+ planSource,
157
+ reason: confirmedAllow
158
+ ? "Free-plan model policy needs re-verification"
159
+ : "model is outside the confirmed Free-plan auto-routing list",
160
+ };
161
+ }
162
+ }
163
+ if (provider === "google-antigravity" && ["free", "plus"].includes(plan)) {
164
+ // The operator confirmed Free/Plus access is limited to the listed model
165
+ // families. Do not treat an unlisted dynamic-catalog entry as permission.
166
+ const listedAllow = matchingRules.some((rule) => rule.state === "allowed");
167
+ if (!listedAllow) {
168
+ return {
169
+ eligible: false,
170
+ plan,
171
+ planSource,
172
+ reason: decision.state === "blocked"
173
+ ? decision.reason
174
+ : "model is outside the confirmed Antigravity Free/Plus auto-routing list",
175
+ };
176
+ }
177
+ if (decision.state !== "allowed") {
178
+ return { eligible: false, plan, planSource, reason: decision.reason };
179
+ }
180
+ }
181
+ if (decision.state === "blocked" || decision.state === "conditional") {
182
+ return { eligible: false, plan, planSource, reason: decision.reason };
183
+ }
184
+ return { eligible: true, plan, planSource, reason: decision.reason };
185
+ }
@@ -0,0 +1,12 @@
1
+ /** Transient output-quality circuit, separate from account entitlement evidence. */
2
+ const failures=new Map<string,number>();
3
+ const key=(provider:string,model:string)=>JSON.stringify([provider,model]);
4
+ export function markEmptyAutoOutput(provider:string,model:string,now=Date.now()):void {
5
+ for(const [k,expiry] of failures)if(expiry<=now)failures.delete(k);
6
+ if(failures.size>=256)failures.delete(failures.keys().next().value!);
7
+ failures.set(key(provider,model),now+300000);
8
+ }
9
+ export function isAutoOutputCooling(provider:string,model:string,now=Date.now()):boolean {
10
+ const k=key(provider,model),expiry=failures.get(k);if(expiry===undefined)return false;
11
+ if(expiry<=now){failures.delete(k);return false;}return true;
12
+ }
@@ -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
+ }