Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add OpenRouter and Epoch AI comparison sync (#8072)

[._.]/ Adam Eivyf4566653a82f
diff --git a/docs/MODEL-COMPARISON.md b/docs/MODEL-COMPARISON.md
index 7e984e881a..660c055631 100644
--- a/docs/MODEL-COMPARISON.md
+++ b/docs/MODEL-COMPARISON.md
@@ -7,6 +7,9 @@ The catalog contains comprehensive public configurations across major providers
## Sources and interpretation
- [Artificial Analysis](https://artificialanalysis.ai/) supplies independent quality, benchmark cost and performance measurements. Its [API documentation](https://artificialanalysis.ai/api-reference) describes key-based access and attribution. Research can use public model/provider pages without a key. Do not copy documentation example values into the catalog as current observations.
+- [OpenRouter's public model API](https://openrouter.ai/api/v1/models) supplies OpenRouter-routed per-token prices. These prices describe OpenRouter's routed charge, not the creator's first-party price. The `:free` routes are promotional and remain subject to upstream limits and data-use terms; this source publishes no quality score.
+- [OpenRouter's model endpoint API](https://openrouter.ai/docs/api/api-reference/endpoints/list-all-endpoints-for-a-model) supplies per-serving-provider p50 latency and throughput for its rolling 30-minute window. Each row keeps the routed model, serving provider, endpoint tag, quantization and context limits in its configuration. Missing measurements remain null, and endpoint performance is never transferred to another provider.
+- [Epoch AI's Capabilities & Benchmarking data](https://epoch.ai/benchmarks/use-this-data) supplies named benchmark scores from its on-demand CSV bundle. The adapter records the benchmark release or version and each row's model/run configuration. Epoch AI's data is attributed under CC BY 4.0; benchmark questions and answers remain their creators' property, and external-run rows retain their original source licensing.
- Official provider pricing documents govern the exact endpoint, region, token classes, batch/cache/context tier and billing date. Public benchmark pricing is an attributed reference, not an account-specific invoice.
- Official local model cards identify revisions and quantizations. Hosted quality is only transferable when the evaluated configuration is verified equivalent. Hosted speed and cost never describe local hardware.
- Subscription quota stays unknown unless a primary source defines per-task units for the exact workload and plan. No dollar-to-quota conversion, generic effort multiplier, or assumption that local inference is free.
@@ -45,7 +48,7 @@ Endpoints (relative to the configured PortOS API origin):
- `POST /api/providers/comparison/discover` with `{ "providerId": "example-provider" }` → current `{ providerId, models: [{ model, efforts }] }`. Explicit discovery only; failures remain visible.
- `POST /api/providers/comparison/import` accepts `{ schemaVersion: 1, observations: [...] }`. GET's `inventory` field is not an import field. The UI also accepts this JSON as a file.
- `POST /api/providers/comparison/sync-aa` with optional `{ "apiKey": "..." }` → fetches model metadata directly from the Artificial Analysis API, normalizes observations, and imports them. The API-reported `intelligence_index_version` determines observation IDs, benchmark labels and metric methodology. Missing/invalid versions, malformed/empty pages, or a version change during pagination fail before import; new benchmark versions never overwrite older-version evidence. Back-compat alias for the generalized source sync below.
-- `POST /api/providers/comparison/sync/:source` with an optional `{ "apiKey": "..." }` (used only by `artificial-analysis`) → the same import contract for any declared source. `GET` reports the selectable list as `syncSources: [{ id, label, requiresKey }]`. Built-in sources: `artificial-analysis`, `swebench`, and `livecodebench` — see "Benchmark source sync" below.
+- `POST /api/providers/comparison/sync/:source` with an optional `{ "apiKey": "..." }` (used only by `artificial-analysis`) → the same import contract for any declared source. `GET` reports the selectable list as `syncSources: [{ id, label, requiresKey }]`. Built-in sources: `artificial-analysis`, `openrouter`, `openrouter-endpoints`, `epoch-ai`, `swebench`, and `livecodebench` — see "Benchmark source sync" below.
Use the actual configured origin, optional authentication and trusted local HTTP mirror described in `PORTS.md`; do not hardcode an install address. Never put credentials in a catalog, command argument, source URL, output report or repository file. Existing authenticated PortOS tooling can perform the POST. Direct local file replacement bypasses import preservation checks and is not the research workflow.
@@ -64,7 +67,7 @@ The exact schema is `modelComparisonImportSchema` in `server/lib/validation.js`.
| `quota` | `null` or `{ unitsPerTask, unit, source }`; unit must identify its plan/workload |
| `notes` | Source limitations, scope and interpretation |
-Each non-null metric is `{ "value": 12.3, "source": { "url": "https://example.com/benchmark", "retrievedAt": "2026-09-05T00:00:00Z", "methodology": "Example benchmark v1, exact workload and measurement scope" } }`. This is invented schema illustration, not benchmark data. All nullable fields must be present. At least one sourced metric is required. Sources must be HTTPS and dates cannot be in the future. Imports contain 1–2,000 unique observation IDs; the merged catalog is capped at 2,000.
+Each non-null metric is `{ "value": 12.3, "source": { "url": "https://example.com/benchmark", "retrievedAt": "2026-09-05T00:00:00Z", "methodology": "Example benchmark v1, exact workload and measurement scope" } }`. This is invented schema illustration, not benchmark data. All nullable fields must be present. At least one sourced metric is required. Sources must be HTTPS and dates cannot be in the future. Imports contain 1–12,000 unique observation IDs; the merged catalog is capped at 12,000 to fit the complete Epoch AI benchmark snapshot in one validated, atomic merge.
Validate a candidate locally from the PortOS root, without writing anything:
@@ -80,6 +83,9 @@ Partial source refreshes cannot erase old evidence. To retract incorrect data, a
Artificial Analysis is not the only source the page can pull: **Models → Comparison → Sync benchmark data** offers every source `GET /api/providers/comparison` lists as `syncSources`. Each sync is an explicit user action (or an explicitly scheduled task run) — never a boot-time or background call. All sources share the import contract above: server-side fetch, schema validation, and per-metric merge keyed by stable observation ID. No seed ships for any synced source — the fetch happens on demand into this install's catalog, so nothing is bundled or redistributed by PortOS itself; the source's own publication terms govern the data it serves.
+- **OpenRouter routed pricing** (`openrouter`) — reads the public model list and maps `pricing.prompt`, `pricing.completion`, and a published `pricing.internal_reasoning` to uncached input, output and reasoning USD per million tokens. Every row identifies the exact routed model in its configuration. Each mapped minimum-prompt-token or UTC-window override becomes a separate identity using the published tier rates, without interpolation; unmodified token classes retain their base rate. Audio/cache-only charges are not represented by this schema. Zero-price `:free` offers stay zero. The source URL and methodology describe OpenRouter's routing price, not a model creator's first-party rate. No key required.
+- **OpenRouter endpoint performance** (`openrouter-endpoints`) — reads each model's endpoint list and records p50 `latency_last_30m` and `throughput_last_30m` as separate per-serving-endpoint observations. Endpoint tag, provider name and model ID, quantization and context limits remain in configuration and in the stable identity; no model-level or cross-provider speed is inferred. Missing p50 values stay null. No key required.
+- **Epoch AI benchmarks** (`epoch-ai`) — downloads the CSV bundle on demand and imports each available benchmark/model/run-configuration score as its own quality observation. The benchmark name includes the published version or release date, while reasoning effort, model version, harness and other run details remain in the configuration and identity. Notes attribute the Capabilities & Benchmarking dataset under CC BY 4.0 and state that external-run rows retain their original licensing. No seed ships and no key is required.
- **SWE-bench** (`swebench`) — fetches [swebench.com](https://www.swebench.com/) and reads the `leaderboard-data` JSON the site renders from. Each scored-track submission becomes one observation: benchmark `SWE-bench <track> (pass@1, <agent>)` — the scaffold is part of the name, and several submissions one model+agent pair carries stay distinct — with the resolved-task percentage as quality and the mean USD cost per instance as `costPerTask`. The observation ID keys on the submission folder, so leaderboard row order never changes an identity and a re-submission under the same folder refreshes in place. The site's `Test` tab (a system-test playground, not a scored leaderboard) and rows without an attributable model identity (`Undisclosed`, `Multi`-vendor lineups) stay absent rather than becoming a fake series. No key required.
- **LiveCodeBench** (`livecodebench`) — fetches LiveCodeBench's published `performances_generation.json` and aggregates pass@1 per model across the full date window. The window span is part of the benchmark name — `LiveCodeBench (generation, pass@1, <start> to <end>)` — so a sync that picks up newly added problems starts a new series instead of mixing different windows. The serving family (`model_style`) names the provider where it is unambiguous; unrecognized families stay `Unknown` with the style in notes. Costs, throughput and quota are not published by this source. No key required.
diff --git a/server/lib/validation.js b/server/lib/validation.js
index de9fb5a0bf..2bcce70091 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -2245,7 +2245,9 @@ export const modelComparisonObservationSchema = z.object({
}).strict();
export const modelComparisonImportSchema = z.object({
schemaVersion: z.literal(1),
- observations: z.array(modelComparisonObservationSchema).min(1).max(2000),
+ // The on-demand Epoch AI sync imports several thousand independently
+ // attributed model/benchmark/configuration rows in one atomic catalog merge.
+ observations: z.array(modelComparisonObservationSchema).min(1).max(12000),
}).strict().superRefine((value, ctx) => {
const ids = new Set();
value.observations.forEach((row, index) => {
diff --git a/server/routes/modelComparison.js b/server/routes/modelComparison.js
index 4d22e55eba..b0b9502df6 100644
--- a/server/routes/modelComparison.js
+++ b/server/routes/modelComparison.js
@@ -3,6 +3,8 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest, modelComparisonImportSchema, modelComparisonDiscoverySchema, modelComparisonSyncSchema } from '../lib/validation.js';
import { getModelComparison, importModelComparison } from '../services/modelComparison.js';
import { hasArtificialAnalysisKey, syncArtificialAnalysisCatalog } from '../services/artificialAnalysis.js';
+import { syncOpenRouterCatalog, syncOpenRouterEndpointCatalog } from '../services/openrouterBenchmarks.js';
+import { syncEpochAiCatalog } from '../services/epochAiBenchmarks.js';
import { syncSwebenchCatalog } from '../services/swebenchBenchmarks.js';
import { syncLiveCodeBenchCatalog } from '../services/livecodebenchBenchmarks.js';
import { canRefreshModels } from '../lib/aiToolkit/internal/modelFetchers.js';
@@ -14,6 +16,9 @@ import { applyModelAccess } from '../lib/aiToolkit/internal/modelAccess.js';
// presence travels separately on GET — never the key itself.
const BENCHMARK_SYNC_SOURCES = Object.freeze({
'artificial-analysis': { label: 'Artificial Analysis', requiresKey: true, sync: syncArtificialAnalysisCatalog },
+ openrouter: { label: 'OpenRouter routed pricing', requiresKey: false, sync: () => syncOpenRouterCatalog() },
+ 'openrouter-endpoints': { label: 'OpenRouter serving endpoints', requiresKey: false, sync: () => syncOpenRouterEndpointCatalog() },
+ 'epoch-ai': { label: 'Epoch AI benchmarks', requiresKey: false, sync: () => syncEpochAiCatalog() },
swebench: { label: 'SWE-bench leaderboards', requiresKey: false, sync: () => syncSwebenchCatalog() },
livecodebench: { label: 'LiveCodeBench', requiresKey: false, sync: () => syncLiveCodeBenchCatalog() },
});
diff --git a/server/routes/modelComparison.test.js b/server/routes/modelComparison.test.js
index f734478f30..a0c593f6b4 100644
--- a/server/routes/modelComparison.test.js
+++ b/server/routes/modelComparison.test.js
@@ -192,6 +192,9 @@ it('exposes the sync sources and syncs each keyless source without a key', async
const listed = (await request(app).get('/comparison')).body.syncSources;
expect(listed).toEqual([
{ id: 'artificial-analysis', label: 'Artificial Analysis', requiresKey: true },
+ { id: 'openrouter', label: 'OpenRouter routed pricing', requiresKey: false },
+ { id: 'openrouter-endpoints', label: 'OpenRouter serving endpoints', requiresKey: false },
+ { id: 'epoch-ai', label: 'Epoch AI benchmarks', requiresKey: false },
{ id: 'swebench', label: 'SWE-bench leaderboards', requiresKey: false },
{ id: 'livecodebench', label: 'LiveCodeBench', requiresKey: false },
]);
diff --git a/server/services/epochAiBenchmarks.js b/server/services/epochAiBenchmarks.js
new file mode 100644
index 0000000000..5535e9a0d7
--- /dev/null
+++ b/server/services/epochAiBenchmarks.js
@@ -0,0 +1,392 @@
+/** On-demand Epoch AI benchmark CSV sync for the model comparison catalog. */
+import { createHash } from 'crypto';
+import { Readable } from 'stream';
+import { ServerError } from '../lib/errorHandler.js';
+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+import { collectZipEntry, parseZip } from '../lib/zipStream.js';
+import { modelComparisonImportSchema } from '../lib/validation.js';
+import { importModelComparison } from './modelComparison.js';
+import { KNOWN_EFFORTS, parseModelNameAndEffort, slugify } from './artificialAnalysis.js';
+
+const EPOCH_AI_ARCHIVE_URL = 'https://epoch.ai/data/benchmark_data.zip';
+const EPOCH_AI_CITATION_URL = 'https://epoch.ai/benchmarks/use-this-data';
+const EPOCH_AI_REQUEST_TIMEOUT_MS = 30_000;
+const MAX_EPOCH_ARCHIVE_BYTES = 15 * 1024 * 1024;
+const MAX_EPOCH_CSV_MEMBER_BYTES = 1024 * 1024;
+const MAX_EPOCH_CSV_TOTAL_BYTES = 20 * 1024 * 1024;
+const MAX_EPOCH_ARCHIVE_ENTRIES = 200;
+
+const identityHash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 32);
+const cleanCell = value => String(value ?? '').replace(/\s+/g, ' ').trim();
+const normalizedName = value => String(value || '').toLowerCase().replace(/\.0(?=$|[^0-9])/g, '').replace(/[^a-z0-9]/g, '');
+
+// Epoch's benchmark CSVs use different columns for run setup, so retain the
+// source-specific fields broadly and exclude only model metadata, row IDs,
+// provenance text, and the selected score itself.
+const NON_CONFIGURATION_COLUMNS = new Set([
+ 'Model version', 'Release date', 'Organization', 'Country',
+ 'Training compute (FLOP)', 'Training compute notes', 'id', 'UUID',
+ 'Source', 'Source link', 'Source Link', 'Source link (site from table)',
+ 'Notes', 'Notes (details)', 'Log viewer', 'Logs',
+]);
+
+const BENCHMARK_VERSION_COLUMNS = [
+ 'Benchmark version', 'Benchmark variant', 'METR version', 'LiveBench Version',
+];
+
+function invalidArchive() {
+ return new ServerError('Epoch AI returned an invalid or incomplete benchmark archive; retry sync', { status: 502 });
+}
+
+async function readBoundedResponse(response) {
+ const contentLength = Number(response.headers?.get?.('content-length'));
+ if (Number.isFinite(contentLength) && contentLength > MAX_EPOCH_ARCHIVE_BYTES) {
+ throw new ServerError('Epoch AI benchmark archive exceeds the supported size; retry sync later', { status: 502 });
+ }
+ const reader = response.body?.getReader?.();
+ if (!reader) throw invalidArchive();
+ const chunks = [];
+ let size = 0;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ if (size > MAX_EPOCH_ARCHIVE_BYTES) {
+ await reader.cancel().catch(() => {});
+ throw new ServerError('Epoch AI benchmark archive exceeds the supported size; retry sync later', { status: 502 });
+ }
+ chunks.push(Buffer.from(value));
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ if (size === 0) throw invalidArchive();
+ return Buffer.concat(chunks, size);
+}
+
+function collectCsvMembers(archive) {
+ const source = Readable.from([archive]);
+ const parser = parseZip();
+ const reads = [];
+ const files = new Map();
+ let entryCount = 0;
+ let totalBytes = 0;
+
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ const settle = (fn, value) => {
+ if (settled) return;
+ settled = true;
+ if (fn === reject) {
+ source.destroy();
+ parser.destroy();
+ }
+ fn(value);
+ };
+ const fail = error => settle(reject, error instanceof ServerError ? error : invalidArchive());
+
+ source.on('error', fail);
+ const stream = source.pipe(parser);
+ stream.on('error', fail);
+ stream.on('entry', entry => {
+ entryCount += 1;
+ if (entryCount > MAX_EPOCH_ARCHIVE_ENTRIES) {
+ entry.autodrain();
+ fail(invalidArchive());
+ return;
+ }
+ const name = String(entry.path || '');
+ if (name.includes('/') || !name.toLowerCase().endsWith('.csv')) {
+ entry.autodrain();
+ return;
+ }
+ const read = collectZipEntry(entry, MAX_EPOCH_CSV_MEMBER_BYTES)
+ .then(buffer => {
+ totalBytes += buffer.length;
+ if (totalBytes > MAX_EPOCH_CSV_TOTAL_BYTES || files.has(name)) throw invalidArchive();
+ files.set(name, buffer.toString('utf8'));
+ })
+ .catch(error => fail(error));
+ reads.push(read);
+ });
+ stream.on('close', () => {
+ Promise.all(reads).then(() => settle(resolve, files)).catch(fail);
+ });
+ });
+}
+
+export function parseEpochCsv(text, label = 'benchmark CSV') {
+ if (typeof text !== 'string' || !text.length) throw invalidArchive();
+ const rows = [];
+ let row = [];
+ let field = '';
+ let quoted = false;
+
+ const pushRow = () => {
+ row.push(field);
+ if (row.some(cell => cell.trim())) rows.push(row);
+ row = [];
+ field = '';
+ };
+
+ for (let index = 0; index < text.length; index += 1) {
+ const character = text[index];
+ if (quoted) {
+ if (character === '"' && text[index + 1] === '"') {
+ field += '"';
+ index += 1;
+ } else if (character === '"') {
+ quoted = false;
+ } else {
+ field += character;
+ }
+ } else if (character === ',' ) {
+ row.push(field);
+ field = '';
+ } else if (character === '\n' || character === '\r') {
+ if (character === '\r' && text[index + 1] === '\n') index += 1;
+ pushRow();
+ } else if (character === '"' && field.length === 0) {
+ quoted = true;
+ } else if (character === '"') {
+ throw new ServerError('Epoch AI ' + label + ' contains malformed CSV; retry sync', { status: 502 });
+ } else {
+ field += character;
+ }
+ }
+ if (quoted) throw new ServerError('Epoch AI ' + label + ' contains an unterminated CSV field; retry sync', { status: 502 });
+ if (field.length || row.length) pushRow();
+ if (rows.length < 2) throw new ServerError('Epoch AI ' + label + ' contains no data rows; retry sync', { status: 502 });
+
+ const headers = rows[0].map((header, index) => (index === 0 ? header.replace(/^\uFEFF/, '') : header).trim());
+ if (headers.some(header => !header) || new Set(headers).size !== headers.length) {
+ throw new ServerError('Epoch AI ' + label + ' contains invalid CSV headers; retry sync', { status: 502 });
+ }
+ return rows.slice(1).map(cells => {
+ if (cells.length > headers.length) {
+ throw new ServerError('Epoch AI ' + label + ' contains a malformed CSV row; retry sync', { status: 502 });
+ }
+ return Object.fromEntries(headers.map((header, index) => [header, cells[index] ?? '']));
+ });
+}
+
+function resolveBenchmarkFile(benchmark, filesByStem) {
+ const sourceFile = cleanCell(benchmark.source_file);
+ if (sourceFile) return sourceFile;
+ const direct = filesByStem.get(normalizedName(benchmark.benchmark)) || [];
+ if (direct.length === 1) return direct[0];
+ if (direct.length > 1) throw invalidArchive();
+ if (normalizedName(benchmark.benchmark) === 'csqa2') return 'common_sense_qa_2_external.csv';
+ return '';
+}
+
+export async function parseEpochAiBenchmarkArchive(archive) {
+ if (!Buffer.isBuffer(archive) || archive.length === 0 || archive.length > MAX_EPOCH_ARCHIVE_BYTES) {
+ throw invalidArchive();
+ }
+ let members;
+ try {
+ members = await collectCsvMembers(archive);
+ } catch (error) {
+ if (error instanceof ServerError) throw error;
+ throw invalidArchive();
+ }
+
+ const benchmarkText = members.get('benchmark_metadata.csv');
+ const modelText = members.get('model_metadata.csv');
+ if (!benchmarkText || !modelText) throw invalidArchive();
+ const benchmarkMetadata = parseEpochCsv(benchmarkText, 'benchmark metadata');
+ const modelMetadata = parseEpochCsv(modelText, 'model metadata');
+ const fileNames = [...members.keys()].filter(name => name !== 'benchmark_metadata.csv' && name !== 'model_metadata.csv');
+ const filesByStem = new Map();
+ for (const fileName of fileNames) {
+ const stem = fileName.replace(/\.csv$/i, '').replace(/_external$/i, '');
+ const key = normalizedName(stem);
+ filesByStem.set(key, [...(filesByStem.get(key) || []), fileName]);
+ }
+
+ const selectedNames = new Set();
+ for (const benchmark of benchmarkMetadata) {
+ if (!cleanCell(benchmark.benchmark)) throw invalidArchive();
+ const fileName = resolveBenchmarkFile(benchmark, filesByStem);
+ if (!fileName) continue;
+ if (!members.has(fileName)) throw invalidArchive();
+ selectedNames.add(fileName);
+ }
+ if (selectedNames.size === 0) throw invalidArchive();
+ const datasets = new Map([...selectedNames].map(fileName => [fileName, parseEpochCsv(members.get(fileName), fileName)]));
+ return { benchmarkMetadata, modelMetadata, datasets };
+}
+
+export async function fetchEpochAiBenchmarkData() {
+ let response;
+ let archive;
+ try {
+ response = await fetchWithTimeout(EPOCH_AI_ARCHIVE_URL, { headers: { Accept: 'application/zip' } }, EPOCH_AI_REQUEST_TIMEOUT_MS);
+ if (!response.ok) {
+ throw new ServerError('Epoch AI benchmark download failed (' + response.status + ')', { status: 502 });
+ }
+ archive = await readBoundedResponse(response);
+ } catch (error) {
+ if (error instanceof ServerError) throw error;
+ if (error?.name === 'AbortError') throw new ServerError('Epoch AI benchmark download timed out; retry sync', { status: 502 });
+ throw error;
+ }
+ return parseEpochAiBenchmarkArchive(archive);
+}
+
+function numericScore(value) {
+ if (value === null || value === undefined || cleanCell(value) === '') return null;
+ const raw = cleanCell(value);
+ if (/^(?:n\/a|na|not available|—|-|null)$/i.test(raw)) return null;
+ const numeric = Number(raw.replace(/%$/, ''));
+ if (!Number.isFinite(numeric) || numeric < 0) {
+ throw new ServerError('Epoch AI returned a malformed benchmark score; retry sync', { status: 502 });
+ }
+ return numeric;
+}
+
+function normalizeEffort(value) {
+ const effort = cleanCell(value).toLowerCase().replace(/\s+/g, '-');
+ if (!effort || ['unknown', 'n/a', 'na', 'none', 'unspecified'].includes(effort)) return 'unspecified';
+ if (effort === 'very_high') return 'xhigh';
+ return effort.slice(0, 80);
+}
+
+function resolveModel(row, modelMetadataByVersion) {
+ const modelVersion = cleanCell(row['Model version']);
+ if (!modelVersion) return null;
+ const metadata = modelMetadataByVersion.get(modelVersion) || {};
+ const displayName = cleanCell(metadata.display_name || row.Name || modelVersion);
+ const parsedName = parseModelNameAndEffort(displayName);
+ const model = slugify(parsedName.baseName || displayName);
+ if (!model) return null;
+ const versionEffort = modelVersion.match(/_([a-z][a-z0-9-]*)$/i)?.[1];
+ const explicitEffort = row['Reasoning effort'] || row['Reasoning level'] || row.Reasoning;
+ const effort = normalizeEffort(explicitEffort || (KNOWN_EFFORTS.includes(String(versionEffort || '').toLowerCase()) ? versionEffort : parsedName.effort));
+ const provider = cleanCell(row.Organization || metadata.organization || row.Provider || 'Unknown').slice(0, 160) || 'Unknown';
+ return { modelVersion, model, effort, provider };
+}
+
+function rowConfiguration(row, modelVersion, scoreColumn) {
+ const parts = ['model version=' + modelVersion];
+ const entries = Object.entries(row)
+ .filter(([field, value]) => field !== scoreColumn && !NON_CONFIGURATION_COLUMNS.has(field) && cleanCell(value))
+ .sort(([left], [right]) => left.localeCompare(right));
+ for (const [field, value] of entries) {
+ parts.push(field.toLowerCase() + '=' + cleanCell(value));
+ }
+ return parts;
+}
+
+function benchmarkVersionName(metadata, row) {
+ const name = cleanCell(metadata.benchmark);
+ const rowVersions = BENCHMARK_VERSION_COLUMNS
+ .map(field => cleanCell(row[field]))
+ .filter(Boolean);
+ const distinctVersions = [...new Set(rowVersions)];
+ const releaseDate = cleanCell(metadata.release_date);
+ const qualifiers = [
+ ...distinctVersions,
+ ...(releaseDate && !name.includes(releaseDate) ? ['released ' + releaseDate] : []),
+ ...(cleanCell(metadata.score_column) ? ['score column: ' + cleanCell(metadata.score_column)] : []),
+ ];
+ const suffix = qualifiers.length ? ' (' + qualifiers.join('; ') + ')' : '';
+ return ('Epoch AI: ' + name + suffix).slice(0, 160);
+}
+
+function benchmarkScore(row, metadata) {
+ const scoreColumn = cleanCell(metadata.score_column);
+ if (!scoreColumn) return null;
+ if (!Object.prototype.hasOwnProperty.call(row, scoreColumn)) throw invalidArchive();
+ return numericScore(row[scoreColumn]);
+}
+
+export function transformEpochBenchmarkData(data, { retrievedAt = new Date().toISOString() } = {}) {
+ if (!data || !Array.isArray(data.benchmarkMetadata) || !Array.isArray(data.modelMetadata) || !(data.datasets instanceof Map)) {
+ throw invalidArchive();
+ }
+ const filesByStem = new Map();
+ for (const file of data.datasets.keys()) {
+ const stem = file.replace(/\.csv$/i, '').replace(/_external$/i, '');
+ const key = normalizedName(stem);
+ filesByStem.set(key, [...(filesByStem.get(key) || []), file]);
+ }
+ const modelMetadataByVersion = new Map(data.modelMetadata
+ .filter(row => cleanCell(row.model_version))
+ .map(row => [cleanCell(row.model_version), row]));
+ const observations = [];
+ const seenIds = new Set();
+
+ for (const benchmark of data.benchmarkMetadata) {
+ const fileName = resolveBenchmarkFile(benchmark, filesByStem);
+ const rows = data.datasets.get(fileName);
+ if (!rows) continue;
+ for (const row of rows) {
+ if (!row || typeof row !== 'object') throw invalidArchive();
+ const resolved = resolveModel(row, modelMetadataByVersion);
+ if (!resolved) continue;
+ const qualityValue = benchmarkScore(row, benchmark);
+ if (qualityValue === null) continue;
+
+ const benchmarkName = benchmarkVersionName(benchmark, row);
+ const scoreColumn = cleanCell(benchmark.score_column);
+ let configParts = rowConfiguration(row, resolved.modelVersion, scoreColumn);
+ let identity = [benchmarkName, scoreColumn, resolved.modelVersion, resolved.effort, configParts];
+ let id = 'epoch-ai-' + identityHash(identity);
+ if (seenIds.has(id)) {
+ const sourceRowId = cleanCell(row.id);
+ if (!sourceRowId) throw invalidArchive();
+ configParts = [...configParts, 'source record id=' + sourceRowId];
+ identity = [benchmarkName, scoreColumn, resolved.modelVersion, resolved.effort, configParts];
+ id = 'epoch-ai-' + identityHash(identity);
+ }
+ if (seenIds.has(id)) throw invalidArchive();
+ seenIds.add(id);
+
+ const scale = cleanCell(benchmark.scale) || 'source-reported scale';
+ const release = cleanCell(benchmark.release_date);
+ const external = /_external\.csv$/i.test(fileName);
+ const methodology = 'Epoch AI ' + cleanCell(benchmark.benchmark)
+ + (release ? ' (benchmark release ' + release + ')' : '')
+ + '; published score column "' + cleanCell(benchmark.score_column) + '" on the ' + scale + ' scale'
+ + '; run configuration is recorded per observation. No score rescaling is applied.';
+ observations.push({
+ id,
+ provider: resolved.provider,
+ model: resolved.model,
+ effort: resolved.effort,
+ configuration: ('Epoch AI run; ' + configParts.join('; ')).slice(0, 500),
+ billing: 'unknown',
+ benchmark: benchmarkName,
+ quality: {
+ value: qualityValue,
+ source: { url: EPOCH_AI_ARCHIVE_URL, retrievedAt, methodology },
+ },
+ costPerTask: null,
+ inputPerMillion: null,
+ outputPerMillion: null,
+ reasoningPerMillion: null,
+ responseSeconds: null,
+ tokensPerSecond: null,
+ quota: null,
+ notes: 'Epoch AI, Capabilities & Benchmarking CSV archive (' + EPOCH_AI_CITATION_URL + '); attributed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Benchmark questions and answers remain their creators’ property.'
+ + (external ? ' This is an external-run row; Epoch AI states that external rows retain their original source licensing.' : ''),
+ });
+ }
+ }
+ if (observations.length === 0) {
+ throw new ServerError('Epoch AI returned no usable benchmark observations; retry sync', { status: 502 });
+ }
+ return observations;
+}
+
+export async function syncEpochAiCatalog() {
+ const data = await fetchEpochAiBenchmarkData();
+ const observations = transformEpochBenchmarkData(data);
+ const validated = modelComparisonImportSchema.parse({ schemaVersion: 1, observations });
+ const updated = await importModelComparison(validated);
+ const fetched = [...data.datasets.values()].reduce((total, rows) => total + rows.length, 0);
+ return { success: true, fetched, observations: observations.length, total: updated.observations.length, catalog: updated };
+}
diff --git a/server/services/epochAiBenchmarks.test.js b/server/services/epochAiBenchmarks.test.js
new file mode 100644
index 0000000000..b770010ca4
--- /dev/null
+++ b/server/services/epochAiBenchmarks.test.js
@@ -0,0 +1,92 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { modelComparisonImportSchema } from '../lib/validation.js';
+
+vi.mock('./modelComparison.js', () => ({
+ importModelComparison: vi.fn(async value => value),
+}));
+
+const { importModelComparison } = await import('./modelComparison.js');
+const {
+ parseEpochAiBenchmarkArchive,
+ syncEpochAiCatalog,
+ transformEpochBenchmarkData,
+} = await import('./epochAiBenchmarks.js');
+
+const retrievedAt = '2026-09-23T00:00:00.000Z';
+
+function storedZip(entries) {
+ const localEntries = entries.map(([name, text]) => {
+ const nameBytes = Buffer.from(name);
+ const content = Buffer.from(text);
+ const header = Buffer.alloc(30);
+ header.writeUInt32LE(0x04034b50, 0);
+ header.writeUInt16LE(20, 4);
+ header.writeUInt16LE(0, 6);
+ header.writeUInt16LE(0, 8);
+ header.writeUInt32LE(content.length, 18);
+ header.writeUInt32LE(content.length, 22);
+ header.writeUInt16LE(nameBytes.length, 26);
+ header.writeUInt16LE(0, 28);
+ return Buffer.concat([header, nameBytes, content]);
+ });
+ const centralDirectoryStart = Buffer.alloc(4);
+ centralDirectoryStart.writeUInt32LE(0x02014b50, 0);
+ return Buffer.concat([...localEntries, centralDirectoryStart]);
+}
+
+function fixtureData(releaseDate = '2025-06-01') {
+ const archive = storedZip([
+ ['benchmark_metadata.csv', `benchmark,release_date,score_column,scale,source_file\nGPQA Diamond,${releaseDate},score,percent,gpqa_diamond.csv\n`],
+ ['model_metadata.csv', 'model_version,display_name,organization\nexample-model-v2,Example Model,Example Labs\n'],
+ ['gpqa_diamond.csv', 'Model version,Agent,Reasoning effort,Run date,Shots,score\nexample-model-v2,Example Harness,high,2026-05-01,5,72.5\n'],
+ ]);
+ return parseEpochAiBenchmarkArchive(archive);
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ importModelComparison.mockClear();
+});
+
+it('imports versioned benchmark scores with their run configuration and CC BY attribution', async () => {
+ const data = await fixtureData();
+ const observations = transformEpochBenchmarkData(data, { retrievedAt });
+
+ expect(observations).toHaveLength(1);
+ expect(observations[0]).toMatchObject({
+ provider: 'Example Labs',
+ model: 'example-model',
+ effort: 'high',
+ benchmark: 'Epoch AI: GPQA Diamond (released 2025-06-01; score column: score)',
+ quality: {
+ value: 72.5,
+ source: { url: 'https://epoch.ai/data/benchmark_data.zip', retrievedAt },
+ },
+ });
+ expect(observations[0].configuration).toContain('agent=Example Harness');
+ expect(observations[0].configuration).toContain('reasoning effort=high');
+ expect(observations[0].configuration).toContain('shots=5');
+ expect(observations[0].notes).toContain('CC BY 4.0');
+ expect(observations[0].notes).toContain('https://creativecommons.org/licenses/by/4.0/');
+ expect(modelComparisonImportSchema.parse({ schemaVersion: 1, observations }).observations).toHaveLength(1);
+
+ const nextVersion = transformEpochBenchmarkData(await fixtureData('2025-08-15'), { retrievedAt });
+ expect(nextVersion[0].benchmark).not.toBe(observations[0].benchmark);
+ expect(nextVersion[0].id).not.toBe(observations[0].id);
+
+ const reordered = {
+ ...data,
+ datasets: new Map([...data.datasets].map(([name, rows]) => [
+ name,
+ rows.map(row => Object.fromEntries(Object.entries(row).reverse())),
+ ])),
+ };
+ expect(transformEpochBenchmarkData(reordered, { retrievedAt })[0].id).toBe(observations[0].id);
+});
+
+it('rejects an invalid archive before importing any existing evidence', async () => {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(Buffer.from('not a zip'), { status: 200 }));
+
+ await expect(syncEpochAiCatalog()).rejects.toMatchObject({ status: 502 });
+ expect(importModelComparison).not.toHaveBeenCalled();
+});
diff --git a/server/services/openrouterBenchmarks.js b/server/services/openrouterBenchmarks.js
new file mode 100644
index 0000000000..9636c8b066
--- /dev/null
+++ b/server/services/openrouterBenchmarks.js
@@ -0,0 +1,394 @@
+/** OpenRouter routed price and per-serving-endpoint performance sync. */
+import { createHash } from 'crypto';
+import { ServerError } from '../lib/errorHandler.js';
+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+import { modelComparisonImportSchema } from '../lib/validation.js';
+import { catalogSlugForProviderModel } from '../lib/comparisonModelScope.js';
+import { importModelComparison } from './modelComparison.js';
+import { parseModelNameAndEffort, slugify } from './artificialAnalysis.js';
+
+const OPENROUTER_MODELS_URL = 'https://openrouter.ai/api/v1/models';
+const OPENROUTER_ENDPOINTS_URL = 'https://openrouter.ai/api/v1/models';
+const OPENROUTER_REQUEST_TIMEOUT_MS = 15_000;
+const OPENROUTER_ENDPOINT_CONCURRENCY = 8;
+const ENDPOINT_WINDOW = '30m-p50';
+
+const identityHash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 24);
+const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
+
+function validRoutedModelId(value) {
+ return typeof value === 'string' && value.length > 0 && value.length <= 300
+ && value.includes('/') && !/[\u0000-\u001f\u007f]/.test(value)
+ && value.indexOf('/') === value.lastIndexOf('/');
+}
+
+function parseRate(value) {
+ if (value === null || value === undefined) return null;
+ if ((typeof value !== 'string' && typeof value !== 'number') || (typeof value === 'string' && !value.trim())) {
+ throw new ServerError('OpenRouter returned malformed pricing data; retry sync', { status: 502 });
+ }
+ const rate = Number(value);
+ // OpenRouter's router/meta-model entries use -1 for an unpublished price.
+ // It is an absent metric, not a negative charge or a zero-price offer.
+ if (rate === -1) return null;
+ if (!Number.isFinite(rate) || rate < 0) {
+ throw new ServerError('OpenRouter returned malformed pricing data; retry sync', { status: 502 });
+ }
+ const perMillion = rate * 1_000_000;
+ if (!Number.isFinite(perMillion)) {
+ throw new ServerError('OpenRouter returned malformed pricing data; retry sync', { status: 502 });
+ }
+ return perMillion;
+}
+
+function parseThreshold(value) {
+ if ((typeof value !== 'string' && typeof value !== 'number') || (typeof value === 'string' && !value.trim())) {
+ throw new ServerError('OpenRouter returned an invalid long-context pricing tier; retry sync', { status: 502 });
+ }
+ const threshold = Number(value);
+ if (!Number.isSafeInteger(threshold) || threshold < 0) {
+ throw new ServerError('OpenRouter returned an invalid long-context pricing tier; retry sync', { status: 502 });
+ }
+ return threshold;
+}
+
+function parseUtcTime(value) {
+ if ((typeof value !== 'string' && typeof value !== 'number') || (typeof value === 'string' && !value.trim())) {
+ throw new ServerError('OpenRouter returned an invalid UTC pricing window; retry sync', { status: 502 });
+ }
+ const time = Number(value);
+ const hour = Math.floor(time / 100);
+ const minute = time % 100;
+ if (!Number.isSafeInteger(time) || time < 0 || time > 2359 || hour > 23 || minute > 59) {
+ throw new ServerError('OpenRouter returned an invalid UTC pricing window; retry sync', { status: 502 });
+ }
+ return time;
+}
+
+function formatUtcTime(value) {
+ const hour = String(Math.floor(value / 100)).padStart(2, '0');
+ const minute = String(value % 100).padStart(2, '0');
+ return hour + ':' + minute;
+}
+
+function overrideCondition(override) {
+ const parts = [];
+ const identity = {};
+ if (hasOwn(override, 'min_prompt_tokens')) {
+ identity.minPromptTokens = parseThreshold(override.min_prompt_tokens);
+ parts.push('minimum ' + identity.minPromptTokens + ' prompt tokens');
+ }
+
+ const hasDays = hasOwn(override, 'utc_days');
+ const hasStart = hasOwn(override, 'utc_start');
+ const hasEnd = hasOwn(override, 'utc_end');
+ if (hasDays || hasStart || hasEnd) {
+ if (hasDays && (!Array.isArray(override.utc_days) || !override.utc_days.length
+ || override.utc_days.some(day => typeof day !== 'string' || !/^(monday|tuesday|wednesday|thursday|friday|saturday|sunday)$/i.test(day)))) {
+ throw new ServerError('OpenRouter returned invalid UTC pricing days; retry sync', { status: 502 });
+ }
+ if (hasStart !== hasEnd) {
+ throw new ServerError('OpenRouter returned an incomplete UTC pricing window; retry sync', { status: 502 });
+ }
+ const days = hasDays ? [...new Set(override.utc_days.map(day => day.toLowerCase()))].sort() : [];
+ identity.utcDays = days;
+ if (hasStart) {
+ identity.utcStart = parseUtcTime(override.utc_start);
+ identity.utcEnd = parseUtcTime(override.utc_end);
+ }
+ const dayLabel = days.length ? days.join(', ') : 'every UTC day';
+ parts.push(dayLabel + (hasStart ? ' ' + formatUtcTime(identity.utcStart) + '–' + formatUtcTime(identity.utcEnd) : ''));
+ }
+
+ return parts.length ? { key: JSON.stringify(identity), label: parts.join('; ') } : null;
+}
+
+function sourceMetric(value, url, retrievedAt, methodology) {
+ return value === null ? null : { value, source: { url, retrievedAt, methodology } };
+}
+
+function routedModel(model) {
+ const modelId = model.id;
+ const comparableId = modelId.replace(/:(?:free|batch)$/i, '');
+ const modelSlug = catalogSlugForProviderModel(comparableId)
+ || slugify((model.name || comparableId.slice(comparableId.lastIndexOf('/') + 1)).replace(/\s*\((?:free|batch)\)$/i, ''));
+ const parsedName = parseModelNameAndEffort(model.name || comparableId);
+ return {
+ id: modelId,
+ model: modelSlug || slugify(comparableId),
+ effort: parsedName.effort || 'unspecified',
+ };
+}
+
+function validateModels(payload) {
+ if (!payload || !Array.isArray(payload.data) || payload.data.length === 0) {
+ throw new ServerError('OpenRouter returned no model data; retry sync', { status: 502 });
+ }
+ const ids = new Set();
+ for (const model of payload.data) {
+ if (!model || !validRoutedModelId(model.id) || ids.has(model.id)) {
+ throw new ServerError('OpenRouter returned malformed or duplicate model data; retry sync', { status: 502 });
+ }
+ ids.add(model.id);
+ }
+ return payload.data;
+}
+
+async function fetchJson(url, label) {
+ let response;
+ try {
+ response = await fetchWithTimeout(url, { headers: { Accept: 'application/json' } }, OPENROUTER_REQUEST_TIMEOUT_MS);
+ } catch (error) {
+ if (error?.name === 'AbortError') throw new ServerError(label + ' request timed out; retry sync', { status: 502 });
+ throw error;
+ }
+ if (!response.ok) {
+ throw new ServerError(label + ' request failed (' + response.status + ')', { status: 502 });
+ }
+ try {
+ return await response.json();
+ } catch {
+ throw new ServerError(label + ' returned malformed JSON; retry sync', { status: 502 });
+ }
+}
+
+export async function fetchOpenRouterModels() {
+ return validateModels(await fetchJson(OPENROUTER_MODELS_URL, 'OpenRouter models'));
+}
+
+export function transformOpenRouterModelsToObservations(models, { retrievedAt = new Date().toISOString() } = {}) {
+ if (!Array.isArray(models) || models.length === 0) {
+ throw new ServerError('OpenRouter returned no model data; retry sync', { status: 502 });
+ }
+
+ const observations = [];
+ for (const model of models) {
+ if (!model || !validRoutedModelId(model.id)) {
+ throw new ServerError('OpenRouter returned malformed model data; retry sync', { status: 502 });
+ }
+ if (model.pricing === null || model.pricing === undefined) continue;
+ if (typeof model.pricing !== 'object' || Array.isArray(model.pricing)) {
+ throw new ServerError('OpenRouter returned malformed pricing data; retry sync', { status: 502 });
+ }
+
+ const route = routedModel(model);
+ const overrides = model.pricing.overrides;
+ if (overrides !== undefined && !Array.isArray(overrides)) {
+ throw new ServerError('OpenRouter returned malformed pricing tiers; retry sync', { status: 502 });
+ }
+ const baseInputRate = parseRate(model.pricing.prompt);
+ const baseOutputRate = parseRate(model.pricing.completion);
+ const baseReasoningRate = parseRate(model.pricing.internal_reasoning);
+ const tiers = [{ key: 'standard', label: 'standard', isLongContext: false, prices: model.pricing }];
+ const seenTierKeys = new Set();
+ for (const override of overrides || []) {
+ if (!override || typeof override !== 'object' || Array.isArray(override)) {
+ throw new ServerError('OpenRouter returned malformed pricing tiers; retry sync', { status: 502 });
+ }
+ const condition = overrideCondition(override);
+ // Some OpenRouter overrides describe audio/cache-only rates or publish
+ // no scope. Those classes have no matching comparison metric or safe
+ // identity in this schema, so leave them out rather than inventing one.
+ const hasComparablePrice = ['prompt', 'completion', 'internal_reasoning'].some(key => hasOwn(override, key));
+ if (!condition || !hasComparablePrice) continue;
+ if (seenTierKeys.has(condition.key)) {
+ throw new ServerError('OpenRouter returned duplicate pricing tiers; retry sync', { status: 502 });
+ }
+ seenTierKeys.add(condition.key);
+ tiers.push({
+ key: condition.key,
+ label: condition.label,
+ // An override changes only the fields it publishes; other token classes
+ // retain the base rate, with no interpolation between published tiers.
+ prices: { ...model.pricing, ...override },
+ });
+ }
+
+ for (const tier of tiers) {
+ const inputRate = parseRate(tier.prices.prompt);
+ const outputRate = parseRate(tier.prices.completion);
+ const reasoningRate = parseRate(tier.prices.internal_reasoning);
+ if (inputRate === null && outputRate === null && reasoningRate === null) continue;
+ if (tier.key !== 'standard'
+ && inputRate === baseInputRate && outputRate === baseOutputRate && reasoningRate === baseReasoningRate) continue;
+
+ const tierLabel = tier.label;
+ const configuration = ('OpenRouter routed model ' + route.id + '; ' + tierLabel + ' pricing tier').slice(0, 500);
+ const methodologyBase = 'OpenRouter published routed price for ' + route.id + '; ' + tierLabel + '. Rates are USD per million tokens.';
+ observations.push({
+ id: 'openrouter-price-' + identityHash([route.id, tier.key]),
+ provider: 'OpenRouter',
+ model: route.model,
+ effort: route.effort,
+ configuration,
+ billing: 'api',
+ benchmark: 'OpenRouter routed API pricing',
+ quality: null,
+ costPerTask: null,
+ inputPerMillion: sourceMetric(inputRate, OPENROUTER_MODELS_URL, retrievedAt, methodologyBase + ' Prompt price is the uncached-input rate.'),
+ outputPerMillion: sourceMetric(outputRate, OPENROUTER_MODELS_URL, retrievedAt, methodologyBase + ' Completion price is the output rate.'),
+ reasoningPerMillion: sourceMetric(reasoningRate, OPENROUTER_MODELS_URL, retrievedAt, methodologyBase + ' Internal reasoning price is recorded only when OpenRouter publishes it.'),
+ responseSeconds: null,
+ tokensPerSecond: null,
+ quota: null,
+ notes: 'OpenRouter routed price, not the model creator first-party price. Cached-token, audio and per-request charges are not represented by this schema; free routes remain subject to upstream limits and terms.',
+ });
+ }
+ }
+
+ if (observations.length === 0) {
+ throw new ServerError('OpenRouter returned no usable pricing observations; retry sync', { status: 502 });
+ }
+ return observations;
+}
+
+export async function syncOpenRouterCatalog() {
+ const models = await fetchOpenRouterModels();
+ const observations = transformOpenRouterModelsToObservations(models);
+ const validated = modelComparisonImportSchema.parse({ schemaVersion: 1, observations });
+ const updated = await importModelComparison(validated);
+ return { success: true, fetched: models.length, observations: observations.length, total: updated.observations.length, catalog: updated };
+}
+
+function endpointRequestUrl(modelId) {
+ const parts = modelId.split('/');
+ return OPENROUTER_ENDPOINTS_URL + '/' + encodeURIComponent(parts[0]) + '/' + encodeURIComponent(parts[1]) + '/endpoints';
+}
+
+async function fetchOpenRouterModelEndpoints(model) {
+ const url = endpointRequestUrl(model.id);
+ let response;
+ try {
+ response = await fetchWithTimeout(url, { headers: { Accept: 'application/json' } }, OPENROUTER_REQUEST_TIMEOUT_MS);
+ } catch (error) {
+ if (error?.name === 'AbortError') throw new ServerError('OpenRouter endpoints request timed out; retry sync', { status: 502 });
+ throw error;
+ }
+ if (response.status === 404) return { model, endpoints: [] };
+ if (!response.ok) {
+ throw new ServerError('OpenRouter endpoints request failed (' + response.status + ')', { status: 502 });
+ }
+
+ let payload;
+ try {
+ payload = await response.json();
+ } catch {
+ throw new ServerError('OpenRouter endpoints returned malformed JSON; retry sync', { status: 502 });
+ }
+ if (!payload?.data || payload.data.id !== model.id || !Array.isArray(payload.data.endpoints)) {
+ throw new ServerError('OpenRouter endpoints returned malformed model data; retry sync', { status: 502 });
+ }
+ return { model, endpoints: payload.data.endpoints };
+}
+
+async function mapWithConcurrency(items, limit, mapper) {
+ const results = new Array(items.length);
+ let cursor = 0;
+ let failure = null;
+ const worker = async () => {
+ while (!failure) {
+ const index = cursor++;
+ if (index >= items.length) return;
+ try {
+ results[index] = await mapper(items[index]);
+ } catch (error) {
+ failure = error;
+ }
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
+ if (failure) throw failure;
+ return results;
+}
+
+function percentileValue(windowData) {
+ if (windowData === null || windowData === undefined) return null;
+ if (typeof windowData !== 'object' || Array.isArray(windowData)) {
+ throw new ServerError('OpenRouter returned malformed endpoint performance data; retry sync', { status: 502 });
+ }
+ if (!hasOwn(windowData, 'p50') || windowData.p50 === null || windowData.p50 === undefined) return null;
+ if (typeof windowData.p50 !== 'number' || !Number.isFinite(windowData.p50) || windowData.p50 < 0) {
+ throw new ServerError('OpenRouter returned malformed endpoint performance data; retry sync', { status: 502 });
+ }
+ return windowData.p50;
+}
+
+export function transformOpenRouterEndpointsToObservations(modelEndpoints, { retrievedAt = new Date().toISOString() } = {}) {
+ if (!Array.isArray(modelEndpoints) || modelEndpoints.length === 0) {
+ throw new ServerError('OpenRouter returned no serving endpoint data; retry sync', { status: 502 });
+ }
+ const observations = [];
+ for (const item of modelEndpoints) {
+ if (!item || !item.model || !validRoutedModelId(item.model.id) || !Array.isArray(item.endpoints)) {
+ throw new ServerError('OpenRouter returned malformed serving endpoint data; retry sync', { status: 502 });
+ }
+ const route = routedModel(item.model);
+ for (const endpoint of item.endpoints) {
+ if (!endpoint || typeof endpoint !== 'object' || Array.isArray(endpoint)) {
+ throw new ServerError('OpenRouter returned malformed serving endpoint data; retry sync', { status: 502 });
+ }
+ const providerName = typeof endpoint.provider_name === 'string' ? endpoint.provider_name.trim() : '';
+ const tag = typeof endpoint.tag === 'string' ? endpoint.tag.trim() : '';
+ const name = typeof endpoint.name === 'string' ? endpoint.name.trim() : '';
+ const providerModelId = typeof endpoint.model_id === 'string' ? endpoint.model_id.trim() : '';
+ if (!providerName && !tag && !name && !providerModelId) {
+ throw new ServerError('OpenRouter returned an endpoint without an identity; retry sync', { status: 502 });
+ }
+ const latency = percentileValue(endpoint.latency_last_30m);
+ const throughput = percentileValue(endpoint.throughput_last_30m);
+ if (latency === null && throughput === null) continue;
+
+ const identity = [
+ route.id, providerName, tag, name, providerModelId,
+ endpoint.quantization ?? null,
+ endpoint.context_length ?? null,
+ endpoint.max_prompt_tokens ?? null,
+ endpoint.max_completion_tokens ?? null,
+ ENDPOINT_WINDOW,
+ ];
+ const endpointLabel = name || tag || providerName;
+ const details = [
+ 'OpenRouter routed model ' + route.id,
+ 'serving provider ' + (providerName || 'unspecified'),
+ 'endpoint ' + endpointLabel,
+ 'provider model ' + (providerModelId || 'unspecified'),
+ 'quantization ' + (endpoint.quantization || 'unspecified'),
+ 'context ' + (endpoint.context_length ?? 'unspecified'),
+ 'maximum prompt ' + (endpoint.max_prompt_tokens ?? 'unspecified'),
+ 'maximum completion ' + (endpoint.max_completion_tokens ?? 'unspecified'),
+ ].join('; ');
+ const sourceUrl = OPENROUTER_ENDPOINTS_URL + '/' + encodeURIComponent(route.id.split('/')[0]) + '/' + encodeURIComponent(route.id.split('/')[1]) + '/endpoints';
+ observations.push({
+ id: 'openrouter-endpoint-' + identityHash(identity),
+ provider: 'OpenRouter',
+ model: route.model,
+ effort: route.effort,
+ configuration: details.slice(0, 500),
+ billing: 'api',
+ benchmark: 'OpenRouter serving endpoint performance (30m p50)',
+ quality: null,
+ costPerTask: null,
+ inputPerMillion: null,
+ outputPerMillion: null,
+ reasoningPerMillion: null,
+ responseSeconds: sourceMetric(latency, sourceUrl, retrievedAt, 'OpenRouter per-serving-endpoint latency_last_30m p50, in seconds.'),
+ tokensPerSecond: sourceMetric(throughput, sourceUrl, retrievedAt, 'OpenRouter per-serving-endpoint throughput_last_30m p50, in output tokens per second.'),
+ quota: null,
+ notes: 'Performance belongs to this OpenRouter serving endpoint and its 30-minute measurement window; no price or quality is transferred from another endpoint.',
+ });
+ }
+ }
+ if (observations.length === 0) {
+ throw new ServerError('OpenRouter returned no usable serving endpoint observations; retry sync', { status: 502 });
+ }
+ return observations;
+}
+
+export async function syncOpenRouterEndpointCatalog() {
+ const models = await fetchOpenRouterModels();
+ const endpoints = await mapWithConcurrency(models, OPENROUTER_ENDPOINT_CONCURRENCY, fetchOpenRouterModelEndpoints);
+ const observations = transformOpenRouterEndpointsToObservations(endpoints);
+ const validated = modelComparisonImportSchema.parse({ schemaVersion: 1, observations });
+ const updated = await importModelComparison(validated);
+ return { success: true, fetched: models.length, observations: observations.length, total: updated.observations.length, catalog: updated };
+}
diff --git a/server/services/openrouterBenchmarks.test.js b/server/services/openrouterBenchmarks.test.js
new file mode 100644
index 0000000000..16be31040c
--- /dev/null
+++ b/server/services/openrouterBenchmarks.test.js
@@ -0,0 +1,129 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { modelComparisonImportSchema } from '../lib/validation.js';
+
+vi.mock('./modelComparison.js', () => ({
+ importModelComparison: vi.fn(async value => value),
+}));
+
+const {
+ importModelComparison,
+} = await import('./modelComparison.js');
+const {
+ syncOpenRouterCatalog,
+ transformOpenRouterEndpointsToObservations,
+ transformOpenRouterModelsToObservations,
+} = await import('./openrouterBenchmarks.js');
+
+const retrievedAt = '2026-09-23T00:00:00.000Z';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ importModelComparison.mockClear();
+});
+
+it('keeps routed pricing separate from first-party pricing and creates a distinct long-context identity', () => {
+ const observations = transformOpenRouterModelsToObservations([{
+ id: 'example/model-x',
+ name: 'Model X',
+ pricing: {
+ prompt: '0.000001',
+ completion: '0.000002',
+ internal_reasoning: '0.000003',
+ overrides: [{ min_prompt_tokens: 128, prompt: '0.000004' }],
+ },
+ }], { retrievedAt });
+
+ expect(observations).toHaveLength(2);
+ const standard = observations.find(row => row.configuration.includes('standard pricing tier'));
+ const longContext = observations.find(row => row.configuration.includes('minimum 128 prompt tokens'));
+ expect(standard).toMatchObject({
+ provider: 'OpenRouter',
+ benchmark: 'OpenRouter routed API pricing',
+ inputPerMillion: { value: 1, source: { url: 'https://openrouter.ai/api/v1/models', retrievedAt } },
+ outputPerMillion: { value: 2 },
+ reasoningPerMillion: { value: 3 },
+ });
+ expect(longContext).toMatchObject({
+ provider: 'OpenRouter',
+ inputPerMillion: { value: 4 },
+ outputPerMillion: { value: 2 },
+ reasoningPerMillion: { value: 3 },
+ });
+ expect(longContext.id).not.toBe(standard.id);
+ expect(standard.configuration).toContain('example/model-x');
+ expect(standard.notes).toContain('not the model creator first-party price');
+ expect(modelComparisonImportSchema.parse({ schemaVersion: 1, observations }).observations).toHaveLength(2);
+});
+
+it('preserves free-route zero prices and separates UTC-window tiers when published', () => {
+ const observations = transformOpenRouterModelsToObservations([{
+ id: 'example/model-x:free',
+ name: 'Model X (free)',
+ pricing: {
+ prompt: '0',
+ completion: '0',
+ overrides: [{ utc_days: ['Saturday', 'Sunday'], prompt: '0.000001' }],
+ },
+ }], { retrievedAt });
+
+ expect(observations).toHaveLength(2);
+ expect(observations[0].inputPerMillion.value).toBe(0);
+ expect(observations[0].outputPerMillion.value).toBe(0);
+ expect(observations[1].inputPerMillion.value).toBe(1);
+ expect(observations[1].configuration).toContain('saturday, sunday');
+ expect(new Set(observations.map(row => row.id)).size).toBe(2);
+});
+
+it('skips OpenRouter meta-models whose documented price sentinel means unavailable', () => {
+ const observations = transformOpenRouterModelsToObservations([
+ { id: 'example/model-x', name: 'Model X', pricing: { prompt: '0.000001', completion: '0.000002' } },
+ { id: 'openrouter/auto', name: 'Auto Router', pricing: { prompt: '-1', completion: '-1' } },
+ ], { retrievedAt });
+
+ expect(observations).toHaveLength(1);
+ expect(observations[0].provider).toBe('OpenRouter');
+ expect(observations[0].inputPerMillion.value).toBe(1);
+});
+
+it('keeps speed metrics on the serving endpoint that reported them and preserves nulls', () => {
+ const observations = transformOpenRouterEndpointsToObservations([{
+ model: { id: 'example/model-x', name: 'Model X' },
+ endpoints: [
+ {
+ provider_name: 'Example Hosting', tag: 'fast', name: 'Model X Fast', model_id: 'example/model-x-fast', quantization: 'fp8',
+ context_length: 64000, max_completion_tokens: 8192,
+ latency_last_30m: { p50: 0.8 }, throughput_last_30m: { p50: null },
+ },
+ {
+ provider_name: 'Other Hosting', tag: 'standard', name: 'Model X Standard', model_id: 'example/model-x-standard', quantization: 'int8',
+ context_length: 32000, max_completion_tokens: 4096,
+ latency_last_30m: { p50: null }, throughput_last_30m: { p50: 42 },
+ },
+ ],
+ }], { retrievedAt });
+
+ expect(observations).toHaveLength(2);
+ expect(observations[0]).toMatchObject({
+ responseSeconds: { value: 0.8, source: { retrievedAt, url: 'https://openrouter.ai/api/v1/models/example/model-x/endpoints' } },
+ tokensPerSecond: null,
+ inputPerMillion: null,
+ outputPerMillion: null,
+ });
+ expect(observations[1]).toMatchObject({ responseSeconds: null, tokensPerSecond: { value: 42 } });
+ expect(observations[0].configuration).toContain('Example Hosting');
+ expect(observations[0].configuration).toContain('example/model-x-fast');
+ expect(observations[0].configuration).toContain('fp8');
+ expect(observations[1].configuration).toContain('Other Hosting');
+ expect(new Set(observations.map(row => row.id)).size).toBe(2);
+ expect(modelComparisonImportSchema.parse({ schemaVersion: 1, observations }).observations).toHaveLength(2);
+});
+
+it('rejects an empty upstream catalog before importing any evidence', async () => {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ json: async () => ({ data: [] }),
+ });
+
+ await expect(syncOpenRouterCatalog()).rejects.toMatchObject({ status: 502 });
+ expect(importModelComparison).not.toHaveBeenCalled();
+});