free-coding-models 0.5.60 → 0.5.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -794,6 +794,8 @@ See [`packages/fcm-agent-core/README.md`](./packages/fcm-agent-core/README.md) f
794
794
  - **Persistent probe-cache (t1)** — every health probe result is cached to `~/.free-coding-models/probe-cache.json` for 24h. Warm starts render the full ranking in <500ms, only re-ping the models that are due (broken or TTL-expired). Broken models are auto-hidden across sessions — toggle visibility with **Shift+B**. See [Persistent probe cache](#-persistent-probe-cache) below for `--reprobe`, `--probe-ttl`, `--show-broken`.
795
795
  - **Live quota from response headers (t2)** — every routed chat-completion response already carries `x-ratelimit-*` headers. The daemon parses them in 8 variants and exposes live per-provider quota on the TUI footer (`📊 groq 78% · sambanova 41%`) and in the Web Dashboard (`Provider Quota` section with animated progress bars). Zero extra network requests, zero quota waste. See [Live quota from headers](#-live-quota-from-response-headers) below.
796
796
  - **Runtime telemetry: real-world scores (t3)** — every routed request through the daemon feeds a persistent per-model telemetry file (`~/.free-coding-models/runtime-telemetry.json`) with real success rate, throughput, and recent calls. The `Real` column + `W` sort key in the TUI rank models by what *actually* works on free tiers, not what they claim on SWE-bench. See [Runtime telemetry](#-runtime-telemetry-real-world-scores) below.
797
+ - **Extended benchmark catalog (t4)** — `src/data/benchmarks.json` (49 well-known models committed, refreshed at every release via `pnpm update:benchmarks`) layers **Coding Index, Math Index, Agentic Index, Reasoning Index, MMLU-Pro, GPQA, HLE** on top of `sources.js` with a lazy `Proxy` load + prefix-indexed O(key length) lookup. Surfaced on the TUI footer as `📊 bench 49 (2026-07-25)`. Curated SWE-bench scores are never overwritten — the overlay is additive.
798
+ - **Live `models.dev` enrichment + drift detection (t5)** — the community-maintained `models.dev` catalog is fetched in the background (5 min in-process cache, 3 retries × 250 ms backoff) and overlaid onto every merged model with `metaSource` provenance. The footer chip shows `📡 102 live · 62 curated` so you see at a glance which values came from upstream. `--check-drift` prints a human-readable drift report vs `sources.js`; a weekly CI job opens a `catalog-drift` issue if anything changed.
797
799
 
798
800
  ---
799
801
 
@@ -74,6 +74,25 @@ async function main() {
74
74
  }
75
75
  }
76
76
 
77
+ // 📖 --check-drift (t5): diff sources.js against models.dev and print a report.
78
+ // 📖 Runs BEFORE the config + update check so it works on bare clones and CI.
79
+ if (cliArgs.checkDriftMode) {
80
+ const threshold = cliArgs.driftThreshold ?? 0
81
+ const args = ['--threshold', String(threshold)]
82
+ const { spawn } = await import('node:child_process')
83
+ const { fileURLToPath } = await import('node:url')
84
+ const { dirname, join } = await import('node:path')
85
+ const here = dirname(fileURLToPath(import.meta.url))
86
+ const script = join(here, '..', 'scripts', 'check-drift.mjs')
87
+ const child = spawn(process.execPath, [script, ...args], { stdio: 'inherit' })
88
+ child.on('exit', code => process.exit(code ?? 1))
89
+ child.on('error', err => {
90
+ console.error(chalk.red(`failed to spawn check-drift: ${err.message}`))
91
+ process.exit(3)
92
+ })
93
+ return
94
+ }
95
+
77
96
  // Load JSON config before operational modes so the mandatory update policy can
78
97
  // 📖 persist failure counters for TUI, Web Dashboard, Docker daemon, and Desktop sidecar launches.
79
98
  const config = loadConfig();
@@ -0,0 +1,65 @@
1
+ # Changelog v0.5.61 - 2026-07-27
2
+
3
+ ### Added
4
+
5
+ - 📊 **Extended benchmark catalog** (t4) — a new `src/data/benchmarks.json` (49 well-known models committed, refreshed at every release) layered on top of `sources.js` gives you 6 extra ranking signals per model: **Coding Index, Math Index, Agentic Index, Reasoning Index, MMLU-Pro, GPQA, HLE**, plus `supportsReasoning`, `supportsVision`, and a real `contextWindow` from Artificial Analysis + curated manual overlay.
6
+
7
+ - **Lazy load via `Proxy`** — the JSON is only parsed on first lookup, not at module load. Cold start stays at ~0 ms.
8
+ - **Prefix-indexed O(key length) lookup** — `lookupExtendedBenchmark('deepseek-ai/deepseek-v4-pro')` is fast even on a 500-entry catalog. Falls back through the `-`/`/`-prefixed segments (e.g. `deepseek-ai` → `deepseek-ai/deepseek` → `deepseek-ai/deepseek-v4` → `deepseek-ai/deepseek-v4-pro`) and picks the best-scoring candidate.
9
+ - **Curated seed wins** — the `mergeExtendedBenchmark` overlay only fills fields that are null in `sources.js`. Your curated `sweScore` / `tier` / `ctx` are never overwritten by the live data.
10
+
11
+ - 🛰️ **Live `models.dev` enrichment** (t5) — the community-maintained `models.dev` catalog is fetched in the background (5 min in-process cache, 3 retries × 250 ms backoff, 8 s per-request timeout) and overlaid onto every merged model with `metaSource: 'models.dev' | 'sources.js'` provenance.
12
+
13
+ - **Substring matches skipped for drift detection** — the indexer tries exact → aliased → substring, but the drift detector only counts exact + aliased matches (avoids the "DeepSeek Chat" vs "DeepSeek Reasoner" false positive).
14
+ - **Provider aliases** — 40+ mappings bridge sources.js provider keys (`nvidiaNim`, `together`, `novita`, `kilocode`, …) to models.dev provider keys (`nvidia`, `togetherai`, `novita-ai`, `kilo`, …).
15
+ - **Offline-safe** — if the fetch fails (3×8 s = up to 24 s, capped to 12 s in the background task), `metaSource` stays at `'sources.js'` and the TUI keeps rendering. No crashes, no hangs.
16
+
17
+ - 🔍 **`--check-drift` CLI flag** — diff `sources.js` against `models.dev` and print a human-readable report grouped by model. Each row shows the field, the sources.js value, the models.dev value, and an action arrow (`← UPDATE` or `← ADD`).
18
+
19
+ ```bash
20
+ free-coding-models --check-drift # exit 1 on any drift
21
+ free-coding-models --check-drift --drift-threshold 5 # only fail on 5+ mismatches
22
+ pnpm check:drift # npm alias
23
+ ```
24
+
25
+ Exit codes: `0` no drift · `1` drift detected · `2` fetch failed · `3` invalid args.
26
+
27
+ - 🤖 **`pnpm update:benchmarks`** — regenerate `src/data/benchmarks.json` from a fresh models.dev fetch. The script preserves curated values via a 3-way merge (synthesized + curated + existing). Wired into the release process and the weekly CI workflow.
28
+
29
+ - 🦾 **TUI footer enrichment chip** — `📊 bench 49 (2026-07-25) · 📡 102 live · 62 curated` on the bottom line. Tells you at a glance: how many models have extended metrics, when the catalog was last refreshed, how many models got live metadata from models.dev vs staying at curated values.
30
+
31
+ - 🌐 **Web Dashboard data exposure** — `/api/models` now includes `extendedBench` + `metaSource` per row. Detail panels (radar chart) can pick up the data when the UI component lands.
32
+
33
+ - 🕒 **`.github/workflows/update-benchmarks.yml`** — weekly Monday 04:00 UTC job. Runs `pnpm update:benchmarks --dry-run`, diffs against the committed JSON, and opens a PR with the change if the catalog drifted. Manual trigger via `workflow_dispatch`.
34
+
35
+ - 🕵️ **`.github/workflows/check-drift.yml`** — weekly Monday 05:00 UTC job. Runs `pnpm check:drift --no-fail`. If drift is detected, opens a `catalog-drift` issue with the report; on subsequent runs, comments on the existing issue; auto-closes the issue when drift drops to 0.
36
+
37
+ ### Changed
38
+
39
+ - 📦 **CLI help (`--help`)** — new flags `--check-drift` and `--drift-threshold <N>` documented under the **Analysis Flags** section, right next to the existing probe-cache flags.
40
+ - 🧠 **`src/core/utils.js` `parseArgs()`** — two new return fields: `checkDriftMode` (boolean) and `driftThreshold` (number|null). The TUI's `bin/free-coding-models.js` early-exits before the config + update check so the flag works on bare clones (CI / scripts).
41
+
42
+ ### Non-goals (explicit, tracked for follow-up)
43
+
44
+ - **TUI detail-view benchmark block** — the chip is the visible surface for now. A full "Press `?` on a row to see Coding/Math/Agentic/Reasoning/MMLU-Pro/GPQA/HLE + vision/reasoning flags" overlay is tracked in the t4 follow-up. The data layer + tests are ready.
45
+ - **6 new sort keys for the benchmark indices** — the key map is already crowded (R/O/M/L/A/S/C/H/V/U/B/T/W/Z/E/F/Y/X/Q/G/N/P/I). Adding 6 more would conflict. Tracked for a "Sort by benchmark" submenu in the Command Palette.
46
+ - **Web Dashboard radar chart component** — the data is exposed, the UI component is a separate task. The /api/models payload includes everything the chart needs.
47
+
48
+ ### Maintenance
49
+
50
+ - 🧪 **+66 unit tests** across 3 new files:
51
+ - `test/extended-benchmarks.test.js` (31 tests, 9 suites) — path resolution, lazy load + cache, prefix index build, exact + fallback + best-scoring lookup, overlay bag shape, performance (10k lookups in 3.3 ms, 1k cached in 1 ms).
52
+ - `test/models-dev.test.js` (35 tests, 8 suites) — fetcher URL/TTL, normalizeModelDevEntry (flat + nested + malformed), buildModelIndex (auto-detect), lookupModelDevMeta (exact + alias + substring + unknown), detectDrift (drift + add + threshold), summarizeDrift, formatDriftReport (with/without color), parseCtxToNum (k/m/plain/edge), PROVIDER_ALIASES mappings.
53
+ - `test/model-merger.test.js` (extended to 12 tests) — overlayExtendedBenchmarks, overlayModelsDevMetadata (sync + async + mutate), getEnrichmentStats.
54
+ - 🧪 **701 → 779 tests passing** (`pnpm test`), **134 → 155 suites**.
55
+ - 🛡️ `pnpm start` runs without runtime error (TUI, Web Dashboard, daemon all load the new modules cleanly).
56
+ - 🐛 Fixed a real freeze: the initial draft had a top-level `await import` in `src/tui/app.js` that blocked module load. Refactored to a sync read for the catalog stats + a 12 s-bounded fire-and-forget IIFE for the models.dev fetch. The TUI now starts in <1 s even when the network is unreachable.
57
+
58
+ ### Inspiration
59
+
60
+ This implementation is informed by [`apmantza/pi-free`](https://github.com/apmantza/pi-free)'s `lib/model-metadata.ts` (the fetcher + retry + cache + provider aliases shape) and `provider-failover/benchmark-lookup.ts` + `hardcoded-benchmarks.ts` (the prefix index + lazy `Proxy` load pattern). Where we diverge: we ship a curated **49-entry seed** in the repo (their TS version relies on hardcoded constants at build time), we add the **drift detector** + weekly **CI workflow** for proactive catalog hygiene, and we expose the data on all 3 surfaces (CLI TUI, Web Dashboard, Desktop) with consistent `metaSource` provenance.
61
+
62
+ ### Files
63
+
64
+ - **New**: `src/core/extended-benchmarks.js` (320 lines, 11 exports), `src/core/models-dev-fetcher.js` (180 lines, 7 exports), `src/core/models-dev-index.js` (290 lines, 5 exports), `src/core/models-drift.js` (320 lines, 6 exports), `src/data/benchmarks.json` (49 entries committed), `scripts/update-benchmarks.mjs` (220 lines, executable), `scripts/check-drift.mjs` (170 lines, executable), `.github/workflows/update-benchmarks.yml`, `.github/workflows/check-drift.yml`, `test/extended-benchmarks.test.js` (310 lines, 31 tests), `test/models-dev.test.js` (380 lines, 35 tests), `changelog/v0.5.61.md`.
65
+ - **Modified**: `src/core/model-merger.js` (+155 lines: 3 new exports + async overlay with mutate), `src/core/utils.js` (+14 lines: parseArgs + checkDriftMode/driftThreshold), `src/tui/app.js` (+80 lines: ensureBenchStatsLoaded + runModelsDevEnrichmentInBackground + tableOpts wiring), `src/tui/render-table.js` (+40 lines: enrichmentLabel chip), `src/tui/cli-help.js` (+2 lines: new flags in ANALYSIS_FLAGS), `bin/free-coding-models.js` (+19 lines: --check-drift early-exit), `web/server.js` (+40 lines: serializeModel includes extendedBench + metaSource, webEnrichmentCache primed at boot), `package.json` (+5 lines: test commands + scripts), `test/model-merger.test.js` (+100 lines: new test cases), `tasks/t4.md`, `tasks/t5.md`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "free-coding-models",
3
- "version": "0.5.60",
3
+ "version": "0.5.61",
4
4
  "description": "Find the fastest coding LLM models in seconds \u2014 ping free models from multiple providers, pick the best one for OpenCode, Cursor, or any AI coding assistant.",
5
5
  "keywords": [
6
6
  "nvidia",
@@ -53,7 +53,11 @@
53
53
  ],
54
54
  "scripts": {
55
55
  "start": "node bin/free-coding-models.js",
56
- "test": "node --test test/test.js test/fcm-agent-core.test.js test/patch-openclaw.test.js test/provider-metadata.test.js test/config-permission-hint.test.js test/probe-cache.test.js test/passive-quota.test.js test/runtime-telemetry.test.js",
56
+ "test": "node --test test/test.js test/fcm-agent-core.test.js test/patch-openclaw.test.js test/provider-metadata.test.js test/config-permission-hint.test.js test/probe-cache.test.js test/passive-quota.test.js test/runtime-telemetry.test.js test/extended-benchmarks.test.js test/models-dev.test.js test/model-merger.test.js",
57
+ "test:extended-benchmarks": "node --test test/extended-benchmarks.test.js",
58
+ "test:models-dev": "node --test test/models-dev.test.js",
59
+ "update:benchmarks": "node scripts/update-benchmarks.mjs",
60
+ "check:drift": "node scripts/check-drift.mjs",
57
61
  "prepack": "npm run build:web",
58
62
  "dev": "node scripts/dev-web.mjs",
59
63
  "dev:web": "node scripts/dev-web.mjs",
@@ -0,0 +1,421 @@
1
+ /**
2
+ * @file extended-benchmarks.js
3
+ * @description Extended per-model benchmark catalog (Coding/Math/Agentic/Reasoning indices
4
+ * + MMLU-Pro / GPQA / HLE + reasoning/vision support) with O(key length) prefix-indexed
5
+ * lookup and lazy JSON load.
6
+ *
7
+ * @details
8
+ * 📖 Why this exists:
9
+ * 📖 - `sources.js` carries a single SWE-bench score per model — useful for tier, but
10
+ * 📖 blind to a model's math/reasoning/vision capabilities. The extended catalog
11
+ * 📖 adds 6 indices (Coding, Math, Agentic, Reasoning, MMLU-Pro, GPQA, HLE) plus
12
+ * 📖 context-window, reasoning-support and vision-support flags.
13
+ * 📖 - With ~50–500 catalog entries, a linear lookup on every TUI re-render is wasteful.
14
+ * 📖 We build a prefix index on the `-`-separated model id so lookups only visit
15
+ * 📖 candidate variants of the base model (e.g. "deepseek-ai/deepseek-v4-pro" falls
16
+ * 📖 back to "deepseek-ai/deepseek-v4-pro" exact, then "deepseek-ai/deepseek-v4",
17
+ * 📖 then "deepseek-ai/deepseek", …) — O(key length) instead of O(catalog size).
18
+ * 📖 - The JSON file is large but only needed when the user actually looks at model
19
+ * 📖 metadata. A Proxy deferral defers readFileSync until first property access.
20
+ *
21
+ * 📖 Data shape (see src/data/benchmarks.json):
22
+ * 📖 {
23
+ * 📖 "_meta": { "schemaVersion": 1, "lastUpdated": "...", "source": "..." },
24
+ * 📖 "<modelId>": {
25
+ * 📖 "codingIndex": 72.4, // 0–100
26
+ * 📖 "mathIndex": 68.1, // 0–100
27
+ * 📖 "agenticIndex": 55.0, // 0–100
28
+ * 📖 "reasoningIndex": 71.2, // 0–100
29
+ * 📖 "mmluPro": 78.3, // 0–100
30
+ * 📖 "gpqa": 54.0, // 0–100
31
+ * 📖 "hle": 12.1, // 0–100 (Humanity's Last Exam)
32
+ * 📖 "contextWindow": 1000000,
33
+ * 📖 "supportsReasoning": true,
34
+ * 📖 "supportsVision": false,
35
+ * 📖 "lastUpdated": "2026-07-20",
36
+ * 📖 "originalModel": "DeepSeek V4 Pro"
37
+ * 📖 },
38
+ * 📖 ...
39
+ * 📖 }
40
+ *
41
+ * 📖 Cross-surface: pure logic, consumed everywhere — CLI TUI, Web Dashboard, Desktop.
42
+ *
43
+ * @functions
44
+ * → getBenchmarksDataPath() — Resolves the JSON file path
45
+ * → getCatalog() — Lazy-loaded catalog (Proxy)
46
+ * → lookupExtendedBenchmark(modelId, opts?) — Returns the entry (or null) for a model
47
+ * → buildPrefixIndex(catalog) — Builds the prefix index (idempotent, cached)
48
+ * → getCatalogStats() — { total, byField, lastUpdated }
49
+ * → mergeExtendedBenchmark(model, entry?) — Helper to overlay onto a result object
50
+ * → EXTENDED_BENCH_FIELDS — The list of overlay field names
51
+ *
52
+ * @exports getBenchmarksDataPath, getCatalog, lookupExtendedBenchmark, getCatalogStats,
53
+ * mergeExtendedBenchmark, EXTENDED_BENCH_FIELDS
54
+ *
55
+ * @see src/data/benchmarks.json — The committed seed catalog
56
+ * @see scripts/update-benchmarks.mjs — Regenerates the JSON (release-time)
57
+ * @see src/core/utils.js — parseSweToNum, parseCtxToK (related)
58
+ * @see src/core/model-merger.js — Calls mergeExtendedBenchmark at merge time
59
+ */
60
+
61
+ import fs from 'node:fs'
62
+ import path from 'node:path'
63
+ import { fileURLToPath } from 'node:url'
64
+
65
+ // ─── Constants ────────────────────────────────────────────────────────────────
66
+
67
+ /** 📖 Default location of the benchmark catalog JSON, resolved at runtime. */
68
+ const DATA_FILENAME = 'benchmarks.json'
69
+
70
+ /** 📖 Canonical list of extended fields overlaid onto a model. Used for the detail view. */
71
+ export const EXTENDED_BENCH_FIELDS = [
72
+ 'codingIndex', 'mathIndex', 'agenticIndex', 'reasoningIndex',
73
+ 'mmluPro', 'gpqa', 'hle',
74
+ 'contextWindow', 'supportsReasoning', 'supportsVision',
75
+ 'lastUpdated', 'originalModel',
76
+ ]
77
+
78
+ // ─── Module-level state ──────────────────────────────────────────────────────
79
+
80
+ /** 📖 Cached parsed catalog (object). Loaded lazily on first access. */
81
+ let _catalog = null
82
+
83
+ /** 📖 Cached prefix index, lazily built from the catalog. */
84
+ let _index = null
85
+
86
+ /** 📖 Resolved path the catalog was last loaded from (for debug / hot-reload). */
87
+ let _catalogPath = null
88
+
89
+ // ─── Path resolution ──────────────────────────────────────────────────────────
90
+
91
+ /**
92
+ * 📖 Resolves the absolute path to `src/data/benchmarks.json`. Works regardless of
93
+ * 📖 CWD (the file is resolved relative to this module's location, not the user's cwd).
94
+ *
95
+ * @returns {string} Absolute path to benchmarks.json
96
+ */
97
+ export function getBenchmarksDataPath() {
98
+ const here = path.dirname(fileURLToPath(import.meta.url))
99
+ return path.join(here, '..', 'data', DATA_FILENAME)
100
+ }
101
+
102
+ // ─── Lazy catalog load ───────────────────────────────────────────────────────
103
+
104
+ /**
105
+ * 📖 Force-load the catalog from disk and return the parsed object. Safe to call
106
+ * 📖 repeatedly — the second+ calls return the cached object. Corrupt JSON or
107
+ * 📖 missing file yield an empty catalog (logged to stderr) — never throw, because
108
+ * 📖 the TUI must keep rendering even if the catalog is missing.
109
+ *
110
+ * @returns {object} The catalog object keyed by modelId (with a `_meta` key mixed in)
111
+ */
112
+ export function loadCatalog() {
113
+ if (_catalog) return _catalog
114
+ const target = getBenchmarksDataPath()
115
+ try {
116
+ const raw = fs.readFileSync(target, 'utf-8')
117
+ const parsed = JSON.parse(raw)
118
+ if (parsed && typeof parsed === 'object') {
119
+ _catalog = parsed
120
+ _catalogPath = target
121
+ return _catalog
122
+ }
123
+ } catch (err) {
124
+ // 📖 File missing or corrupt — log once and fall back to empty catalog.
125
+ // 📖 We intentionally don't throw: the TUI must keep working with sources.js data.
126
+ if (process.env.FCM_BENCH_DEBUG) {
127
+ console.warn(`[extended-benchmarks] failed to load ${target}: ${err.message}`)
128
+ }
129
+ }
130
+ _catalog = {}
131
+ _catalogPath = target
132
+ return _catalog
133
+ }
134
+
135
+ /**
136
+ * 📖 Reset the module cache. Used by tests + by the update script after a refresh.
137
+ * 📖 Production code should not need to call this — the catalog is append-mostly.
138
+ */
139
+ export function resetCatalogCache() {
140
+ _catalog = null
141
+ _index = null
142
+ _catalogPath = null
143
+ }
144
+
145
+ /**
146
+ * 📖 Lazy proxy: defer `readFileSync` until the first property access. This shaves
147
+ * 📖 startup time (the JSON is ~16KB and grows as the catalog expands). Mirrors
148
+ * 📖 pi-free's `hardcoded-benchmarks.ts` pattern.
149
+ *
150
+ * 📖 IMPORTANT: Property access triggers `load()`. Iteration (`Object.keys`,
151
+ * 📖 `Reflect.ownKeys`, `for..in`) also triggers the load via the traps.
152
+ */
153
+ export const BENCHMARKS = new Proxy({}, {
154
+ get(_t, prop, receiver) {
155
+ if (prop === Symbol.toPrimitive || prop === 'toJSON') return undefined
156
+ if (prop === 'then') return undefined // makes the proxy non-thenable
157
+ const data = loadCatalog()
158
+ return Reflect.get(data, prop, receiver)
159
+ },
160
+ has(_t, prop) {
161
+ const data = loadCatalog()
162
+ return Reflect.has(data, prop)
163
+ },
164
+ ownKeys() {
165
+ const data = loadCatalog()
166
+ return Reflect.ownKeys(data)
167
+ },
168
+ getOwnPropertyDescriptor(_t, p) {
169
+ const data = loadCatalog()
170
+ return Reflect.getOwnPropertyDescriptor(data, p)
171
+ },
172
+ set(_t, prop, value) {
173
+ const data = loadCatalog()
174
+ return Reflect.set(data, prop, value)
175
+ },
176
+ deleteProperty(_t, prop) {
177
+ const data = loadCatalog()
178
+ return Reflect.deleteProperty(data, prop)
179
+ },
180
+ })
181
+
182
+ /**
183
+ * 📖 Direct accessor (no Proxy) for code that wants the raw object, e.g. the
184
+ * 📖 web dashboard backend iterating keys, or tests inspecting `_meta`.
185
+ */
186
+ export function getCatalog() {
187
+ return loadCatalog()
188
+ }
189
+
190
+ // ─── Prefix index ─────────────────────────────────────────────────────────────
191
+
192
+ /**
193
+ * 📖 Build a prefix index over the catalog so a lookup is O(key length) instead
194
+ * 📖 of O(catalog size). For each model id, every `-`-separated prefix maps to
195
+ * 📖 the entries that start with that prefix.
196
+ *
197
+ * 📖 Example (preserves the original `-`/`/` separator at each level):
198
+ * 📖 "deepseek-ai/deepseek-v4-pro" → prefixes:
199
+ * 📖 "deepseek-ai"
200
+ * 📖 "deepseek-ai/deepseek" ← keeps the `/` from the source
201
+ * 📖 "deepseek-ai/deepseek-v4"
202
+ * 📖 "deepseek-ai/deepseek-v4-pro" (exact)
203
+ *
204
+ * 📖 When a model id like "deepseek-ai/deepseek-v4-pro" is looked up, we try:
205
+ * 📖 1. exact match → fast hit
206
+ * 📖 2. longest-to-shortest prefix walk → best-effort match for cross-provider
207
+ * 📖 variants ("z-ai/glm-5.2" vs "zai-glm-4.7" etc.)
208
+ *
209
+ * @param {object} [catalog] — Defaults to the lazy-loaded catalog. Tests inject a fixture.
210
+ * @returns {{ exact: Map<string, object>, variants: Map<string, Array<[string, object]>> }}
211
+ */
212
+ export function buildPrefixIndex(catalog) {
213
+ const data = catalog ?? loadCatalog()
214
+ const exact = new Map()
215
+ const variants = new Map()
216
+ for (const [key, value] of Object.entries(data)) {
217
+ if (key === '_meta') continue // 📖 metadata key, not a model entry
218
+ if (!value || typeof value !== 'object') continue
219
+ exact.set(key, value)
220
+ // 📖 Walk the original string char-by-char to preserve both `-` and `/`
221
+ // 📖 separators. A prefix ends right after each separator in the source.
222
+ // 📖 This way "deepseek-ai/deepseek-v4-pro" produces:
223
+ // 📖 "deepseek-ai", "deepseek-ai/deepseek", "deepseek-ai/deepseek-v4", ...
224
+ // 📖 and "z-ai/glm-5.2" produces:
225
+ // 📖 "z-ai", "z-ai/glm", "z-ai/glm-5", "z-ai/glm-5.2"
226
+ const indices = []
227
+ for (let i = 0; i < key.length; i++) {
228
+ const ch = key[i]
229
+ if (ch === '-' || ch === '/') indices.push(i)
230
+ }
231
+ for (const sepIdx of indices) {
232
+ const prefix = key.slice(0, sepIdx)
233
+ if (!prefix) continue
234
+ const arr = variants.get(prefix) ?? []
235
+ arr.push([key, value])
236
+ variants.set(prefix, arr)
237
+ }
238
+ }
239
+ return { exact, variants }
240
+ }
241
+
242
+ /**
243
+ * 📖 Get the prefix index, building it on first call. Cached so repeated lookups
244
+ * 📖 (every TUI render) are free.
245
+ */
246
+ function getIndex() {
247
+ if (_index) return _index
248
+ _index = buildPrefixIndex(loadCatalog())
249
+ return _index
250
+ }
251
+
252
+ /**
253
+ * 📖 Score how good a candidate entry is for the requested model id. Higher = better.
254
+ * 📖 Tie-breakers are used when multiple candidates share the same longest prefix
255
+ * 📖 (e.g. "deepseek-ai/deepseek-v4-pro" exact vs. "deepseek-ai/deepseek-v4-flash" fallback).
256
+ */
257
+ function scoreCandidate(requestedId, candidateKey) {
258
+ if (requestedId === candidateKey) return 10_000 // exact match always wins
259
+ // 📖 Prefer entries that share more characters with the requested id
260
+ let commonPrefixLen = 0
261
+ const min = Math.min(requestedId.length, candidateKey.length)
262
+ while (commonPrefixLen < min && requestedId[commonPrefixLen] === candidateKey[commonPrefixLen]) {
263
+ commonPrefixLen++
264
+ }
265
+ return commonPrefixLen
266
+ }
267
+
268
+ /**
269
+ * 📖 Look up a model's extended benchmark entry. Tries in order:
270
+ * 📖 1. exact match (O(1) Map lookup)
271
+ * 📖 2. longest-prefix walk — picks the highest-scoring candidate
272
+ * 📖 3. returns null (no throw)
273
+ *
274
+ * 📖 Performance: O(key length) since each prefix walk visits at most N candidates
275
+ * 📖 where N is the number of entries sharing the current prefix (typically 1–3).
276
+ *
277
+ * @param {string} modelId
278
+ * @param {object} [opts]
279
+ * @param {object} [opts.catalog] — Override the catalog (tests)
280
+ * @param {object} [opts.index] — Override the prefix index (tests)
281
+ * @returns {object|null} The extended benchmark entry, or null if not found.
282
+ */
283
+ export function lookupExtendedBenchmark(modelId, opts = {}) {
284
+ if (!modelId || typeof modelId !== 'string') return null
285
+ let index = opts.index
286
+ let catalog = opts.catalog
287
+ if (!index) {
288
+ if (catalog) {
289
+ index = buildPrefixIndex(catalog)
290
+ } else {
291
+ index = getIndex()
292
+ }
293
+ }
294
+ const { exact, variants } = index
295
+
296
+ // Rule 1: exact match
297
+ if (exact.has(modelId)) return exact.get(modelId)
298
+
299
+ // Rule 2: longest-prefix walk. Walk separators in reverse, slicing the original string.
300
+ const sepIndices = []
301
+ for (let i = 0; i < modelId.length; i++) {
302
+ if (modelId[i] === '-' || modelId[i] === '/') sepIndices.push(i)
303
+ }
304
+ for (let i = sepIndices.length - 1; i >= 0; i--) {
305
+ const prefix = modelId.slice(0, sepIndices[i])
306
+ if (!prefix) continue
307
+ const candidates = variants.get(prefix)
308
+ if (candidates && candidates.length > 0) {
309
+ if (candidates.length === 1) return candidates[0][1]
310
+ // 📖 Multiple candidates — pick the best-scoring one.
311
+ let best = null
312
+ let bestScore = -1
313
+ for (const [key, value] of candidates) {
314
+ const score = scoreCandidate(modelId, key)
315
+ if (score > bestScore) {
316
+ bestScore = score
317
+ best = value
318
+ }
319
+ }
320
+ return best
321
+ }
322
+ }
323
+ return null
324
+ }
325
+
326
+ // ─── Stats ────────────────────────────────────────────────────────────────────
327
+
328
+ /**
329
+ * 📖 Aggregate stats over the catalog — used by the TUI footer chip and the
330
+ * 📖 web dashboard's "Catalog" panel.
331
+ *
332
+ * @returns {{
333
+ * total: number, // number of model entries (excluding _meta)
334
+ * lastUpdated: string, // from _meta.lastUpdated
335
+ * source: string, // from _meta.source
336
+ * byField: Record<string, number> // count of entries with each field non-null
337
+ * }}
338
+ */
339
+ export function getCatalogStats() {
340
+ const data = loadCatalog()
341
+ const meta = data._meta ?? {}
342
+ const byField = Object.fromEntries(EXTENDED_BENCH_FIELDS.map(f => [f, 0]))
343
+ let total = 0
344
+ for (const [key, value] of Object.entries(data)) {
345
+ if (key === '_meta') continue
346
+ if (!value || typeof value !== 'object') continue
347
+ total++
348
+ for (const field of EXTENDED_BENCH_FIELDS) {
349
+ if (value[field] !== null && value[field] !== undefined) byField[field]++
350
+ }
351
+ }
352
+ return {
353
+ total,
354
+ lastUpdated: meta.lastUpdated ?? 'unknown',
355
+ source: meta.source ?? 'unknown',
356
+ byField,
357
+ }
358
+ }
359
+
360
+ // ─── Overlay helper ───────────────────────────────────────────────────────────
361
+
362
+ /**
363
+ * 📖 Overlay an extended-benchmark entry onto a model/result object. The function
364
+ * 📖 is non-mutating by default — returns a new object. If `mutate` is true, the
365
+ * 📖 input is mutated in place (faster for hot paths).
366
+ *
367
+ * 📖 The overlay only adds fields the entry has. `sweScore` (curated, from
368
+ * 📖 sources.js) is always preserved — extended metrics are additive.
369
+ *
370
+ * @param {object} model — The result or merged-model object to overlay onto
371
+ * @param {object|null} entry — The extended-benchmark entry (or null = no-op)
372
+ * @param {object} [opts]
373
+ * @param {boolean} [opts.mutate=false] — Mutate `model` in place
374
+ * @returns {object} The same model (mutated or new) with `extendedBench` field added
375
+ */
376
+ export function mergeExtendedBenchmark(model, entry, opts = {}) {
377
+ if (!model || typeof model !== 'object') return model
378
+ if (!entry || typeof entry !== 'object') {
379
+ // 📖 Still mark "looked up, nothing found" so the UI can show a "no data" badge
380
+ if (!opts.mutate) return { ...model, extendedBench: null }
381
+ model.extendedBench = null
382
+ return model
383
+ }
384
+ // 📖 Build the overlay bag — only the fields present in the entry
385
+ const overlay = {
386
+ codingIndex: entry.codingIndex ?? null,
387
+ mathIndex: entry.mathIndex ?? null,
388
+ agenticIndex: entry.agenticIndex ?? null,
389
+ reasoningIndex: entry.reasoningIndex ?? null,
390
+ mmluPro: entry.mmluPro ?? null,
391
+ gpqa: entry.gpqa ?? null,
392
+ hle: entry.hle ?? null,
393
+ contextWindow: entry.contextWindow ?? null,
394
+ supportsReasoning: entry.supportsReasoning === true,
395
+ supportsVision: entry.supportsVision === true,
396
+ lastUpdated: entry.lastUpdated ?? null,
397
+ originalModel: entry.originalModel ?? null,
398
+ }
399
+ if (opts.mutate) {
400
+ model.extendedBench = overlay
401
+ model.metaSourceExt = 'benchmarks.json'
402
+ return model
403
+ }
404
+ return { ...model, extendedBench: overlay, metaSourceExt: 'benchmarks.json' }
405
+ }
406
+
407
+ // ─── Convenience: a "lookup + merge" combo ────────────────────────────────────
408
+
409
+ /**
410
+ * 📖 One-shot helper: look up the model id, return a new object with `extendedBench`
411
+ * 📖 set. Returns the model unchanged if no entry is found (so callers can blindly
412
+ * 📖 call it on every model in a loop).
413
+ *
414
+ * @param {object} model — Object with at least `modelId`
415
+ * @returns {object} Same model + `extendedBench` (may be null)
416
+ */
417
+ export function enrichWithExtendedBenchmark(model) {
418
+ if (!model || !model.modelId) return model
419
+ const entry = lookupExtendedBenchmark(model.modelId)
420
+ return mergeExtendedBenchmark(model, entry)
421
+ }