heartcode 0.1.37 → 0.1.41

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/src/probe.js CHANGED
@@ -1,14 +1,8 @@
1
- // Capability probes: small, automatic tests that decide how HeartCode talks to a model.
1
+ // A model's profile (what it can do: models.dev's word, or your settings) and how HeartCode talks to it.
2
2
  import path from 'node:path'
3
- import { deflateSync } from 'node:zlib'
4
- import { HOME, readJson, writeJson } from './config.js'
5
- import { est } from './client.js'
6
- import { contextWindow, contextSource, LOCAL_SERVERS, ASSUMED_REMOTE, LIMIT_MS } from './context.js'
7
- import { loadPrices, limitsOf } from './usage.js'
8
- import { applyEdit, parseBlocks } from './edit.js'
3
+ import { HOME, readJson } from './config.js'
4
+ import { contextWindow, contextSource, ASSUMED_REMOTE, LIMIT_MS } from './context.js'
9
5
  import { c } from './ui.js'
10
- import { log } from './log.js'
11
- import { prompt } from './prompts.js'
12
6
 
13
7
  // One cached profile per server + model. The URL path counts: proxies serve several providers
14
8
  // from one host (https://proxy.dev/groq, https://proxy.dev/openrouter).
@@ -17,7 +11,7 @@ export const profilePath = (client) => {
17
11
  const where = u.host + u.pathname.replace(/\/v1$/, '')
18
12
  return path.join(HOME, 'models', `${where}_${client.model}`.replace(/[^\w.-]+/g, '_') + '.json')
19
13
  }
20
- // Bump when the probe learns something new, so older cached profiles are probed again once.
14
+ // Bump when a profile's shape changes, so older saved ones are made again once.
21
15
  const PROBE_VERSION = 2
22
16
  export const loadProfile = (client) => {
23
17
  const p = readJson(profilePath(client), null)
@@ -25,282 +19,25 @@ export const loadProfile = (client) => {
25
19
  return p?.version === PROBE_VERSION && (!p.model || p.model === client.model) ? p : null
26
20
  }
27
21
 
28
- // --- tiny PNG encoder, for the vision probe ---
29
- const CRC = new Uint32Array(256).map((_, n) => {
30
- let v = n
31
- for (let k = 0; k < 8; k++) v = v & 1 ? 0xedb88320 ^ (v >>> 1) : v >>> 1
32
- return v
33
- })
34
- const crc32 = (buf) => {
35
- let v = 0xffffffff
36
- for (const b of buf) v = CRC[(v ^ b) & 0xff] ^ (v >>> 8)
37
- return (v ^ 0xffffffff) >>> 0
38
- }
39
- const pngChunk = (type, data) => {
40
- const head = Buffer.alloc(4)
41
- head.writeUInt32BE(data.length)
42
- const body = Buffer.concat([Buffer.from(type), data])
43
- const crc = Buffer.alloc(4)
44
- crc.writeUInt32BE(crc32(body))
45
- return Buffer.concat([head, body, crc])
46
- }
47
- export function solidPng(w, h, [r, g, b]) {
48
- const ihdr = Buffer.alloc(13)
49
- ihdr.writeUInt32BE(w, 0)
50
- ihdr.writeUInt32BE(h, 4)
51
- ihdr[8] = 8 // bit depth
52
- ihdr[9] = 2 // RGB
53
- const row = Buffer.alloc(1 + w * 3)
54
- for (let x = 0; x < w; x++) row.set([r, g, b], 1 + x * 3)
55
- const raw = Buffer.concat(Array(h).fill(row))
56
- const sig = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])
57
- return Buffer.concat([sig, pngChunk('IHDR', ihdr), pngChunk('IDAT', deflateSync(raw)), pngChunk('IEND', Buffer.alloc(0))])
58
- }
59
-
60
- const COLORS = { red: [220, 30, 30], green: [30, 170, 60], blue: [30, 60, 220], yellow: [245, 220, 30] }
61
- const firstInt = (t) => Number(/\d+/.exec(t)?.[0])
62
-
63
- // Rate limits, server errors and dropped connections are waited out (with the countdown, Esc
64
- // stops it), so a probe that starts finishes and is saved, and the model is never probed again.
65
- // A request the server rejects (400, 404 "no endpoint supports images", …) just means "no".
66
- const transient = (e) => !e.status || [408, 409, 429].includes(e.status) || e.status >= 500
67
- export async function probe(client, status, signal) {
68
- const [retryIf, purpose] = [client.retryIf, client.purpose]
69
- client.retryIf = (e, attempt) => transient(e) && attempt < 8 // about 4 minutes of waiting at most
70
- client.purpose = 'test' // in the requests log
71
- try {
72
- return await runProbe(client, status, signal)
73
- } finally {
74
- Object.assign(client, { retryIf, purpose })
75
- }
76
- }
77
-
78
- async function runProbe(client, report = () => {}, signal) {
79
- const status = (label) => {
80
- log('probe', label)
81
- report(label)
82
- }
83
- const p = { version: PROBE_VERSION, model: client.model, baseUrl: client.baseUrl, probedAt: new Date().toISOString() }
84
- let tokens = 0
85
- let ms = 0
86
- let calls = 0
87
- let lastError = null
88
- const chat = async (body, opts) => {
89
- const t0 = Date.now()
90
- const r = await client.chat({ temperature: 0, ...body }, { signal, ...opts }) // no max_tokens: the model decides how long
91
- ms += Date.now() - t0
92
- calls++
93
- if (r.usage?.completion_tokens) p.usage = true
94
- tokens += r.usage?.completion_tokens ?? est(r.content + r.reasoning)
95
- if (r.thinking) p.thinking = true
96
- return r
97
- }
98
- const say = (user, system) =>
99
- chat({ messages: system ? [{ role: 'system', content: system }, { role: 'user', content: user }] : [{ role: 'user', content: user }] }).then((r) =>
100
- r.content.trim(),
101
- )
102
- // A rejected request (400, 422, a 404 "no endpoint supports images", …) or an unparsable reply
103
- // means "not supported". Dead connections, auth errors, rate limits, outages, and a model that
104
- // was never reachable abort the probe, so a bad profile never gets cached.
105
- const safe = async (fn) => {
106
- try {
107
- return Boolean(await fn())
108
- } catch (e) {
109
- if (e.name === 'AbortError' || /^cannot reach/.test(e.message)) throw e
110
- // no answer (a timeout, a stalled reply): nothing learned, nothing saved; an answer it can't
111
- // read (not JSON) counts as "not supported" below
112
- if (e.name === 'TimeoutError') throw new Error(`probe stopped, nothing saved: ${e.message}`)
113
- if ([401, 429].includes(e.status) || e.status >= 500 || ([403, 404].includes(e.status) && !calls))
114
- throw new Error(`probe stopped, nothing saved: ${e.message}`)
115
- lastError = e
116
- return false
117
- }
118
- }
119
- const trials = async (label, fns) => {
120
- status(label)
121
- let pass = 0
122
- for (const fn of fns) if (await safe(fn)) pass++
123
- return { pass, total: fns.length }
124
- }
125
-
126
- status('streaming')
127
- let streamed = 0
128
- p.stream = await safe(async () => {
129
- const r = await chat({ messages: [{ role: 'user', content: prompt('probe/hello') }], stream: true }, { onToken: () => streamed++ })
130
- return streamed > 0 || r.thinking
131
- })
132
-
133
- status('context size')
134
- // what the server is and says; else models.dev's published size (context.js decides between them)
135
- const found = await client.contextSize()
136
- p.server = found.server
137
- p.context = found.size || (LOCAL_SERVERS.includes(found.server) ? 4096 : ASSUMED_REMOTE)
138
- p.contextGuessed = !found.size
139
- await loadPrices()
140
- const known = limitsOf(client.provider, client.baseUrl, client.model)
141
- if (known) p.known = known
142
-
143
- p.system = await trials(
144
- 'system prompt',
145
- ['What is 2 + 2?', 'Name a color.'].map((q) => async () => /banana/i.test(await say(q, prompt('probe/system')))),
146
- )
147
-
148
- p.format = await trials(
149
- 'exact format',
150
- [7, 42].map((n) => async () => (await say(prompt('probe/exact-number', { n }))).replace(/[.\s`*"']/g, '') === String(n)),
151
- )
152
-
153
- const menus = [
154
- ['a fruit', ['a hammer', 'an apple', 'a car'], 2],
155
- ['an animal', ['a river', 'a chair', 'a dog'], 3],
156
- ['a color', ['blue', 'a table', 'a spoon'], 1],
157
- ]
158
- p.menu = await trials(
159
- 'menu picking',
160
- menus.map(([what, opts, ans]) => async () => {
161
- const list = opts.map((o, i) => `${i + 1}. ${o}`).join('\n')
162
- return firstInt(await say(prompt('probe/menu', { what, list }))) === ans
163
- }),
164
- )
165
-
166
- status('stop sequences')
167
- p.stop = await safe(async () => {
168
- const r = await chat({ messages: [{ role: 'user', content: prompt('probe/count') }], stop: ['5'] })
169
- return /4/.test(r.content) && !/6/.test(r.content)
170
- })
171
-
172
- const tool = {
173
- type: 'function',
174
- function: {
175
- name: 'get_secret_code',
176
- description: prompt('probe/tool-description'),
177
- parameters: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },
178
- },
179
- }
180
- const toolMsg = (name) => ({ role: 'user', content: prompt('probe/tool-question', { name }) })
181
- const toolCall = (r, name) => {
182
- const call = r.toolCalls.find((t) => t.function.name === 'get_secret_code')
183
- try {
184
- return call && String(JSON.parse(call.function.arguments).name).toLowerCase().includes(name) ? call : null
185
- } catch {
186
- return null
187
- }
188
- }
189
- p.tools = await trials(
190
- 'tool calls',
191
- ['alpha', 'falcon', 'ember'].map((n) => async () => toolCall(await chat({ messages: [toolMsg(n)], tools: [tool] }), n)),
192
- )
193
- if (p.tools.pass) {
194
- status('tool results')
195
- p.toolResult = await safe(async () => {
196
- const r = await chat({ messages: [toolMsg('alpha')], tools: [tool] })
197
- const call = toolCall(r, 'alpha')
198
- if (!call) return false
199
- const r2 = await chat({
200
- messages: [
201
- toolMsg('alpha'),
202
- { role: 'assistant', content: r.content || '', tool_calls: [call] },
203
- { role: 'tool', tool_call_id: call.id, content: prompt('probe/tool-result') },
204
- ],
205
- tools: [tool],
206
- })
207
- return r2.content.includes('4417')
208
- })
209
- status('streamed tool calls')
210
- p.toolsStream = await safe(async () => toolCall(await chat({ messages: [toolMsg('falcon')], tools: [tool], stream: true }), 'falcon'))
211
-
212
- }
213
-
214
- status('constrained output')
215
- const words = ['zebra-purple', 'mango-teal']
216
- p.constrained = await safe(async () => {
217
- const schema = { type: 'object', properties: { word: { type: 'string', enum: words } }, required: ['word'], additionalProperties: false }
218
- const r = await chat({
219
- messages: [{ role: 'user', content: prompt('probe/capital') }],
220
- response_format: { type: 'json_schema', json_schema: { name: 'probe', strict: true, schema } },
221
- })
222
- return words.includes(JSON.parse(r.content).word)
223
- })
224
-
225
- const names = Object.keys(COLORS).sort(() => Math.random() - 0.5).slice(0, 2)
226
- p.vision = await trials(
227
- 'vision',
228
- names.map((name) => async () => {
229
- const url = 'data:image/png;base64,' + solidPng(256, 256, COLORS[name]).toString('base64')
230
- const r = await chat({
231
- messages: [{ role: 'user', content: [{ type: 'text', text: prompt('probe/image-color') }, { type: 'image_url', image_url: { url } }] }],
232
- })
233
- const t = r.content.toLowerCase()
234
- return t.includes(name) && Object.keys(COLORS).every((k) => k === name || !t.includes(k))
235
- }),
236
- )
237
-
238
- const cases = [
239
- {
240
- code: 'function add(a, b) {\n return a + b\n}\n\nfunction sub(a, b) {\n return a - b\n}\n',
241
- ask: 'Change the add function so it returns a * b instead of a + b.',
242
- ok: (t) => t.includes('return a * b') && t.includes('return a - b'),
243
- },
244
- {
245
- code: 'const greeting = "hello"\nconsole.log(greeting)\n',
246
- ask: 'Change the greeting from "hello" to "good morning".',
247
- ok: (t) => t.includes('good morning') && t.includes('console.log(greeting)'),
248
- },
249
- ]
250
- p.edit = await trials(
251
- 'edit skill',
252
- cases.map((cs) => async () => {
253
- const reply = await say(prompt('probe/edit', { code: cs.code, ask: cs.ask }))
254
- let text = cs.code
255
- const blocks = parseBlocks(reply)
256
- for (const b of blocks) {
257
- const r = applyEdit(text, b.search, b.replace)
258
- if (r.error) return false
259
- text = r.text
260
- }
261
- return blocks.length > 0 && cs.ok(text)
262
- }),
263
- )
264
-
265
- p.speed = ms ? Math.round(tokens / (ms / 1000)) : 0
266
- p.latency = calls ? Math.round(ms / calls) : 0
267
- // Every request failed: that's a broken model or endpoint, not a weak model.
268
- if (!calls) throw new Error(`probe stopped, nothing saved: no request succeeded${lastError ? ` (last error: ${lastError.message})` : ''}`)
269
- log('probe', 'result', p)
270
- writeJson(profilePath(client), p)
271
- return p
272
- }
273
-
274
- const all = (s) => Boolean(s && s.total && s.pass === s.total)
275
- const most = (s) => Boolean(s && s.total && s.pass * 3 >= s.total * 2)
276
-
277
- // A model's profile without testing it: what models.dev says (info: limitsOf), or, for a model it
278
- // doesn't know, plain assumptions (source 'assumed': tool calls, streaming, a 128k window) until you
279
- // say on the settings page what it can do (set: { context, tools, thinking, images, stream },
280
- // source 'you'). Profiles from a test (/test_model, heart probe) have no source.
22
+ // A model's profile: what models.dev says (info: limitsOf), or, for a model it doesn't know, plain
23
+ // assumptions (source 'assumed': tool calls, streaming, a 128k window) until you say on the settings
24
+ // page what it can do (set: { context, tools, thinking, images, stream }, source 'you').
281
25
  export function profileFrom(client, info) {
282
26
  return { version: PROBE_VERSION, model: client.model, baseUrl: client.baseUrl, source: info ? 'models.dev' : 'assumed', at: new Date().toISOString(), usage: true, context: ASSUMED_REMOTE, contextGuessed: true, ...(info && { known: info }) }
283
27
  }
284
28
 
285
- // Turns a profile into decisions. Your settings for the model (p.set) come first; then, for a model
286
- // that wasn't tested, what models.dev says; for a tested one, what the test found. Config/flags
287
- // can override the window (--context).
29
+ // Turns a profile into decisions: your settings for the model (p.set) first, then what models.dev
30
+ // says. Config/flags can override the window (--context).
288
31
  export function strategy(p, cfg = {}) {
289
32
  const set = p.set ?? {}
290
- const said = p.source ? (p.known ?? {}) : null // not tested: models.dev's word (or nothing known)
291
- const tools = set.tools ?? (said ? said.tools !== false : most(p.tools) && p.toolResult)
292
- const thinking = set.thinking ?? (said ? Boolean(said.thinking) : Boolean(p.thinking))
293
- const stream = set.stream ?? (said ? true : Boolean(p.stream))
33
+ const said = p.known ?? {}
34
+ const thinking = set.thinking ?? Boolean(said.thinking)
294
35
  const win = contextWindow(p)
295
36
  return {
296
- actions: tools ? 'tools' : 'guided',
297
- edits: said || all(p.edit) ? 'search_replace' : 'rewrite',
298
- enforce: !said && Boolean(p.constrained),
299
- stream,
300
- toolsStream: stream && (said ? true : Boolean(p.toolsStream)),
301
- stop: said ? !thinking : Boolean(p.stop), // stop sequences cut into a thinking model's thinking
302
- mergeSystem: said ? false : !most(p.system),
303
- vision: !(Date.now() - (p.quirks?.noImages ?? -Infinity) < LIMIT_MS) && (set.images ?? (said ? Boolean(said.images) : all(p.vision))), // its provider refused images this week: none
37
+ actions: (set.tools ?? said.tools !== false) ? 'tools' : 'guided',
38
+ stream: set.stream ?? true,
39
+ stop: !thinking, // stop sequences cut into a thinking model's thinking
40
+ vision: !(Date.now() - (p.quirks?.noImages ?? -Infinity) < LIMIT_MS) && (set.images ?? Boolean(said.images)), // its provider refused images this week: none
304
41
  thinking,
305
42
  context: cfg.context || set.context || win.size, // context.js: measured, said, models.dev, learned, or assumed
306
43
  contextSure: Boolean(cfg.context || set.context) || win.sure,
@@ -311,37 +48,10 @@ export function strategy(p, cfg = {}) {
311
48
 
312
49
  export function describe(p, s) {
313
50
  const yn = (v) => (v ? c.green('yes') : c.red('no'))
314
- const score = (x) => {
315
- if (!x) return c.dim('–')
316
- const t = `${x.pass}/${x.total}`
317
- return x.pass === x.total ? c.green(t) : x.pass ? c.yellow(t) : c.red(t)
318
- }
319
51
  const context = ['context', `${s.context}${c.dim(` (${p.set?.context ? 'set by you on /settings' : contextSource(p)}; change it on /settings)`)}`]
320
- // not tested: where it's from, and what it can do
321
- if (p.source) {
322
- const from = { 'models.dev': 'models.dev', you: 'you, on /settings', assumed: "nothing: it isn't in models.dev. Set what it can do on /settings" }[p.source]
323
- const mine = (k) => (p.set?.[k] !== undefined ? c.dim(' (set by you)') : '')
324
- return [['from', from], context, ['tool calls', yn(s.actions === 'tools') + mine('tools')], ['thinking', yn(s.thinking) + mine('thinking')], ['images', yn(s.vision) + (Date.now() - (p.quirks?.noImages ?? -Infinity) < LIMIT_MS ? c.dim(' (its provider refused an image today)') : mine('images'))], ['streaming', yn(s.stream) + mine('stream')]]
325
- .map(([k, v]) => ` ${c.dim(k.padEnd(15))} ${v}`)
326
- .join('\n')
327
- }
328
- const rows = [
329
- ['streaming', yn(p.stream) + (p.thinking ? c.dim(' (thinking model)') : '')],
330
- context,
331
- ['system prompt', score(p.system)],
332
- ['exact format', score(p.format)],
333
- ['menu picking', score(p.menu)],
334
- ['stop sequences', yn(p.stop) + (!p.stop && p.thinking ? c.dim(' (they cut into the thinking; not used)') : '')],
335
- ['tool calls', score(p.tools) + (p.tools?.pass ? c.dim(` uses results: ${p.toolResult ? 'yes' : 'no'} · streamed: ${p.toolsStream ? 'yes' : 'no'}`) : '')],
336
- ['constrained', yn(p.constrained)],
337
- ['vision', score(p.vision)],
338
- ['edit skill', score(p.edit)],
339
- ['speed', `${p.speed} tok/s` + (p.latency ? c.dim(` · ${(p.latency / 1000).toFixed(1)}s per reply`) : '')],
340
- ]
341
- const lines = rows.map(([k, v]) => ` ${c.dim(k.padEnd(15))} ${v}`)
342
- lines.push(
343
- ` ${c.bold('→')} actions: ${c.cyan(s.actions)} · edits: ${c.cyan(s.edits)}` +
344
- `${s.enforce ? ' · enforced answers' : ''}${s.vision ? ' · images' : ''}${s.mergeSystem ? ' · system→user' : ''}`,
345
- )
346
- return lines.join('\n')
52
+ const from = { 'models.dev': 'models.dev', you: 'you, on /settings', assumed: "nothing: it isn't in models.dev. Set what it can do on /settings" }[p.source] ?? 'an earlier test'
53
+ const mine = (k) => (p.set?.[k] !== undefined ? c.dim(' (set by you)') : '')
54
+ return [['from', from], context, ['tool calls', yn(s.actions === 'tools') + mine('tools')], ['thinking', yn(s.thinking) + mine('thinking')], ['images', yn(s.vision) + (Date.now() - (p.quirks?.noImages ?? -Infinity) < LIMIT_MS ? c.dim(' (its provider refused an image today)') : mine('images'))], ['streaming', yn(s.stream) + mine('stream')]]
55
+ .map(([k, v]) => ` ${c.dim(k.padEnd(15))} ${v}`)
56
+ .join('\n')
347
57
  }
package/src/prompts.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // Every text HeartCode sends to a model is a section of a markdown file in prompts/ (agent.md,
2
- // guided.md, compact.md, probe.md). prompt('guided/next-action') is the "## next-action" section of
2
+ // guided.md, compact.md). prompt('guided/next-action') is the "## next-action" section of
3
3
  // guided.md. The user's own sections override the built-in ones, by name:
4
4
  // ~/.heart/prompts/<file>.md for every project
5
5
  // <project>/.heartcode/prompts/<file>.md for one project
@@ -0,0 +1,122 @@
1
+ // What each model is good at, from public rankings (LMArena: people comparing two models' answers
2
+ // to the same prompt, by skill): coding, web apps, images, long inputs… Fetched once a week into
3
+ // ~/.heart/rankings.json (best fit only); a model is matched to its entry by name.
4
+ import path from 'node:path'
5
+ import { HOME, readJson, writeJson } from './config.js'
6
+ import { log } from './log.js'
7
+ import { readParquet } from './parquet.js'
8
+
9
+ const FILE = path.join(HOME, 'rankings.json')
10
+ const WEEK = 7 * 24 * 3600_000
11
+ const VERSION = 2 // 2: with each model's score; an older file is fetched again
12
+ const FILES = 'https://huggingface.co/datasets/lmarena-ai/leaderboard-dataset/resolve/main' // one Parquet file per ranking: text, webdev, vision, agent
13
+
14
+ // The skills a task can need: [ranking, its category, what it's for] (the pick names them).
15
+ export const SKILLS = {
16
+ coding: ['text', 'coding', 'writing and fixing code'],
17
+ webdev: ['webdev', 'webdev', 'building web apps (any stack)'],
18
+ 'webdev-html': ['webdev', 'webdev-html', 'plain HTML/CSS/JS pages, canvas and browser games'],
19
+ 'webdev-react': ['webdev', 'webdev-react', 'React apps'],
20
+ hard: ['text', 'hard_prompts', 'hard, multi-part problems'],
21
+ instructions: ['text', 'instruction_following', 'following detailed instructions exactly'],
22
+ 'long-input': ['text', 'longer_query', 'long inputs: big files, long specs'],
23
+ 'multi-turn': ['text', 'multi_turn', 'long back-and-forth work'],
24
+ math: ['text', 'math', 'math and algorithms'],
25
+ writing: ['text', 'creative_writing', 'prose, docs, copy'],
26
+ software: ['text', 'industry_software_and_it_services', 'software and IT know-how'],
27
+ vision: ['vision', 'overall', 'understanding images and screenshots'],
28
+ ocr: ['vision', 'ocr', 'reading text in images'],
29
+ diagrams: ['vision', 'diagram', 'reading diagrams and charts'],
30
+ agent: ['agent', 'overall', 'agent work: tool calls, commands, many steps'],
31
+ }
32
+ const OVERALL = 'text:overall' // a skill a model isn't ranked on: its overall place stands in
33
+
34
+ export const loadRankings = () => readJson(FILE, null)
35
+
36
+ // One ranking (text, webdev…), every category in it: { 'text:coding': [{ name, rank, score, votes }], … } (score: its rating there)
37
+ async function fetchRanking(config, signal) {
38
+ const res = await fetch(`${FILES}/${config}/latest-00000-of-00001.parquet`, { signal: AbortSignal.any([AbortSignal.timeout(120_000), ...(signal ? [signal] : [])]) })
39
+ if (!res.ok) throw new Error(`rankings ${config}: HTTP ${res.status}`)
40
+ const out = {}
41
+ for (const r of readParquet(Buffer.from(await res.arrayBuffer()), ['model_name', 'rank', 'category', 'rating', 'vote_count'])) (out[`${config}:${r.category}`] ??= []).push({ name: r.model_name, rank: r.rank, score: Math.round(r.rating), votes: r.vote_count })
42
+ return out
43
+ }
44
+
45
+ // The rankings: fetched when there are none or they're a week old (then the old ones are used
46
+ // meanwhile, refreshed behind). null when there are none and fetching failed.
47
+ let refreshing = null
48
+ export async function rankings({ signal, onWait, now = false } = {}) {
49
+ const have = loadRankings()
50
+ if (have && have.v === VERSION && Date.now() - have.fetched < WEEK && !now) return have
51
+ refreshing ??= (async () => {
52
+ const wanted = new Set([...Object.values(SKILLS).map(([c, k]) => `${c}:${k}`), OVERALL])
53
+ const all = Object.assign({}, ...(await Promise.all([...new Set([...wanted].map((p) => p.split(':')[0]))].map((c) => fetchRanking(c, have ? undefined : signal)))))
54
+ const lists = Object.fromEntries(Object.entries(all).filter(([k]) => wanted.has(k)))
55
+ const out = { v: VERSION, fetched: Date.now(), source: 'LMArena (huggingface.co/datasets/lmarena-ai/leaderboard-dataset)', lists }
56
+ writeJson(FILE, out)
57
+ log('fit', `rankings fetched: ${Object.entries(lists).map(([k, v]) => `${k} ${v.length}`).join(', ')}`)
58
+ return out
59
+ })().finally(() => (refreshing = null))
60
+ if (have && !now) {
61
+ refreshing.catch((e) => log('fit', `rankings not refreshed: ${e.message}`))
62
+ return have
63
+ }
64
+ onWait?.()
65
+ try {
66
+ return await refreshing
67
+ } catch (e) {
68
+ if (signal?.aborted) throw e
69
+ log('fit', `no rankings: ${e.message}`)
70
+ return null
71
+ }
72
+ }
73
+
74
+ // A name as words: "models/gemini-3.6-flash" and "Gemini 3.6 Flash (High)" are both "gemini 3 6 flash"
75
+ const DROP = new Set(['latest', 'preview', 'free', 'it', 'instruct', 'exp', 'chat'])
76
+ const WORDS = new Map() // name → its words: thousands of models are matched against hundreds of entries, each parsed once
77
+ export const words = (name) => {
78
+ const k = String(name)
79
+ if (!WORDS.has(k)) WORDS.set(k, toWords(k))
80
+ return WORDS.get(k)
81
+ }
82
+ const toWords = (name) =>
83
+ name
84
+ .toLowerCase()
85
+ .replace(/\([^)]*\)/g, ' ')
86
+ .replace(/^.*\//, '')
87
+ .replace(/([a-z])(\d)/g, '$1 $2')
88
+ .replace(/(\d)([a-z])/g, '$1 $2')
89
+ .split(/[^a-z0-9]+/)
90
+ .filter((w) => w && !DROP.has(w) && !/^\d{4}$/.test(w)) // dated versions (2512, 0127)
91
+
92
+ // Where a model stands in a list, 0 (best) to 1 (last); null when it isn't in it. Its entry: the
93
+ // same words, or those followed only by its size ("nemotron 3 super" = "Nemotron 3 Super 120B A12B"),
94
+ // maybe after the maker's name; of several (High, Low…), the best.
95
+ export function place(model, list) {
96
+ const mine = words(model)
97
+ if (!mine.length || !list?.length) return null
98
+ const size = /^(\d+|[abmkt])$/
99
+ const at = list.filter((e) => {
100
+ const theirs = words(e.name)
101
+ // from their first word, or their second (a maker's name first: "NVIDIA-Nemotron-3-Super-120B-A12B")
102
+ return [0, 1].some((from) => theirs.length >= from + mine.length && mine.every((w, i) => theirs[from + i] === w) && theirs.slice(from + mine.length).every((w) => size.test(w)))
103
+ })
104
+ return at.length ? Math.min(...at.map((e) => e.rank)) / list.length : null
105
+ }
106
+
107
+ // A model's score for some skills, 0 (best) to 1: the average of its places; a skill it isn't
108
+ // ranked on counts as its overall place. null: not ranked at all.
109
+ export function score(model, skills, data) {
110
+ const overall = place(model, data?.lists[OVERALL])
111
+ const each = skills.map((k) => place(model, data?.lists[SKILLS[k] && `${SKILLS[k][0]}:${SKILLS[k][1]}`]) ?? overall)
112
+ return each.every((x) => x == null) ? null : each.reduce((n, x) => n + (x ?? 1), 0) / each.length
113
+ }
114
+
115
+ // A model's place in one list ('text:coding'…), for showing: { rank, of, as, score, votes } (as: its name there); null when not in it
116
+ export function rankIn(model, key, data) {
117
+ const list = data?.lists[key]
118
+ const at = list?.filter((e) => place(model, [e]) != null)
119
+ if (!at?.length) return null
120
+ const best = at.reduce((a, b) => (b.rank < a.rank ? b : a))
121
+ return { rank: best.rank, of: list.length, as: best.name, score: best.score, votes: best.votes }
122
+ }