heartcode 0.1.69 → 0.1.95

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/settings.js CHANGED
@@ -13,12 +13,14 @@ import { newer } from './update.js'
13
13
  import { DEFAULT_SERVERS, mcpAuth, serverName } from './mcp.js'
14
14
  import { sections, BUILTIN_PROMPTS, prompt, reloadPrompts } from './prompts.js'
15
15
  import { Client } from './client.js'
16
+ import { clisInfo, installCli, cliOf, cliUrl, CLIS } from './clis.js'
16
17
  import { clip, TOOL_DEFS } from './tools.js'
17
18
  import { loadProfile, strategy, profilePath, profileFrom } from './probe.js'
18
19
  import { loadPrices, priceOf, limitsOf } from './usage.js'
19
20
  import { THEMES, PERMISSIONS } from './ui.js'
20
21
  import { loadSkills, frontMatter, skillFiles } from './skills.js'
21
22
  import { loadRankings, rankings, rankIn } from './rankings.js'
23
+ import { renameRecords } from './record.js'
22
24
  // a model's places in LMArena's public rankings, shown on Your models: { coding, web, vision } as { rank, of, score }
23
25
  const RANKED_ON = { coding: 'text:coding', web: 'webdev:webdev', vision: 'vision:overall' }
24
26
  const ranksOf = (model, data) => (data ? Object.fromEntries(Object.entries(RANKED_ON).map(([k, list]) => [k, rankIn(model, list, data)])) : null)
@@ -64,7 +66,7 @@ const FILES = [
64
66
  ['HEARTCODE.md', 'Instructions for every project (like AGENTS.md, for all of them)', false, '- Answer briefly.\n- Use pnpm, not npm.'],
65
67
  ]
66
68
  // The prompts the page edits: every section of these files (prompts/*.md); the system prompts first.
67
- const PROMPT_FILES = ['agent', 'guided', 'compact', 'tests']
69
+ const PROMPT_FILES = ['agent', 'guides', 'guided', 'compact', 'tests']
68
70
  const FIRST = { 'agent/system': 'System prompt (models with tool calls)', 'guided/system': 'System prompt (guided mode: models without tool calls)' }
69
71
  const ownPrompts = (file) => path.join(HOME, 'prompts', `${file}.md`)
70
72
  const tilde = (p) => (p.startsWith(os.homedir() + path.sep) ? '~' + p.slice(os.homedir().length) : p)
@@ -152,7 +154,7 @@ const LIST_V = 2 // how a saved list was read (2: airforce's cents, Cloudflare's
152
154
  // The page's own choices (sorts, folded providers, the provider ranking): kept here, not in the
153
155
  // browser, whose storage is per address (a new port each time)
154
156
  const PREFS = path.join(HOME, 'settings-page.json')
155
- const PREF_KEYS = ['catSort', 'freeOnly', 'folded', 'sort', 'sorts', 'rank', 'filters']
157
+ const PREF_KEYS = ['catSort', 'freeOnly', 'onOnly', 'catKind', 'folded', 'sort', 'sorts', 'rank', 'filters']
156
158
  // The saved lists (a MB or more): kept in memory, read again only when the file changes
157
159
  let lists = null
158
160
  const readLists = () => {
@@ -221,7 +223,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
221
223
  if (!p) return null
222
224
  const known = limitsOf(t.provider, c.baseUrl, t.model) ?? p.known
223
225
  const st = strategy({ ...p, known, source: p.source === 'assumed' && known ? 'models.dev' : p.source })
224
- return { source: p.source === 'assumed' && known ? 'models.dev' : (p.source ?? 'tested'), mode: st.actions, context: st.context, sure: st.contextSure, thinking: st.thinking, vision: st.vision, stream: st.stream, set: p.set ?? {} }
226
+ return { source: p.source === 'assumed' && known ? 'models.dev' : (p.source ?? 'tested'), mode: st.actions, context: p.source === 'cli' ? 0 : st.context, sure: st.contextSure, thinking: st.thinking, vision: st.vision, stream: st.stream, set: p.set ?? {} }
225
227
  }
226
228
  const knownOf = (t) => {
227
229
  const p = cfg.providers[t.provider]
@@ -264,13 +266,23 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
264
266
  const TESTS_FILE = path.join(HOME, 'model-tests.json')
265
267
  const tests = readJson(TESTS_FILE, {})
266
268
  let saving = null
267
- const saveTests = () => (saving ??= setTimeout(() => ((saving = null), writeJson(TESTS_FILE, tests)), 1000)) // at most once a second
269
+ const gone = new Set() // tests forgotten here since the last write
270
+ // merged with the file as it is now: another HeartCode's results written meanwhile stay
271
+ const writeTests = () => {
272
+ saving = null
273
+ const disk = readJson(TESTS_FILE, {})
274
+ for (const k of gone) delete disk[k]
275
+ gone.clear()
276
+ for (const [k, v] of Object.entries(disk)) if (!(k in tests)) tests[k] = v
277
+ writeJson(TESTS_FILE, Object.assign(disk, tests))
278
+ }
279
+ const saveTests = () => (saving ??= setTimeout(writeTests, 1000)) // at most once a second
268
280
  // a model taken off your list: its test result goes too (added again, it's not tested)
269
281
  const forgetTests = () => {
270
- const mine = new Set(state().order.map((t) => `${t.provider}/${t.model}`))
271
- let gone = 0
272
- for (const key of Object.keys(tests)) if (!mine.has(key)) (delete tests[key]), gone++
273
- if (gone) saveTests()
282
+ const mine = new Set(orderOf().map((t) => `${t.provider}/${t.model}`))
283
+ let n = 0
284
+ for (const key of Object.keys(tests)) if (!mine.has(key)) (delete tests[key]), gone.add(key), n++
285
+ if (n) saveTests()
274
286
  }
275
287
  // How long a model test waits for its answer (cfg.testTimeout, seconds; the settings page sets it).
276
288
  const testWait = () => testWaitOf(cfg) * 1000
@@ -295,12 +307,12 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
295
307
  const signal = stop ? AbortSignal.any([AbortSignal.timeout(testWait()), stop]) : AbortSignal.timeout(testWait())
296
308
  const r = await c.chat({ messages: [{ role: 'user', content: prompt('tests/hello') }], stream: true }, { signal })
297
309
  const reply = (r.content || '').trim()
298
- if (!reply && !r.toolCalls.length) return { ok: false, ms: Date.now() - t0, error: `it answered with nothing${r.usage?.completion_tokens ? ` (${r.usage.completion_tokens} tokens it said it wrote)` : ''}` }
310
+ if (!reply && !r.toolCalls.length) return { ok: false, kind: 'empty', ms: Date.now() - t0, error: `it answered with nothing${r.usage?.completion_tokens ? ` (${r.usage.completion_tokens} tokens it said it wrote)` : ''}` }
299
311
  const ms = Date.now() - t0
300
- return { ok: true, ms, reply: reply.slice(0, 80), ...(testedOf({ provider, model })?.mode === 'tools' && (await toolTest(c, stop))) }
312
+ return { ok: true, ms, reply: reply.slice(0, 80), ...(testedOf({ provider, model })?.mode === 'tools' && !c.cli && (await toolTest(c, stop))) }
301
313
  } catch (e) {
302
314
  if (stop?.aborted) return { stopped: true }
303
- return { ok: false, ms: Date.now() - t0, status: e.status ?? null, error: e.name === 'TimeoutError' ? noAnswer() : whyFailed(e), ...(e.retryAfter > 0 && { retryAfter: Number(e.retryAfter) }) }
315
+ return { ok: false, ms: Date.now() - t0, status: e.status ?? null, ...(e.name === 'TimeoutError' && { kind: 'timeout' }), error: e.name === 'TimeoutError' ? noAnswer() : whyFailed(e), ...(e.retryAfter > 0 && { retryAfter: Number(e.retryAfter) }) }
304
316
  }
305
317
  }
306
318
  // A model that says it calls tools: can it do work with one? One of HeartCode's own tools and a
@@ -320,7 +332,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
320
332
  }
321
333
  return /notes\.txt$/.test(String(a.path ?? '')) && /hello/i.test(String(a.content ?? '')) ? { toolsOk: true } : { toolsOk: false, toolsWhy: `wrong arguments: ${clip(call.function.arguments, 100)}` }
322
334
  } catch (e) {
323
- if (stop?.aborted || e.name === 'TimeoutError') return {}
335
+ if (stop?.aborted) return {}
336
+ if (e.name === 'TimeoutError') return { toolsOk: false, toolsWhy: `no answer to a request with tools within ${testWait() / 1000} seconds` } // hung: not a pass
324
337
  return { toolsOk: false, toolsWhy: `a request with tools failed: ${whyFailed(e)}` }
325
338
  }
326
339
  }
@@ -333,13 +346,14 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
333
346
  emit('tested', { key, result })
334
347
  return result
335
348
  }
336
- // The run going now: every provider at once, and from each one model at a time (testOrder: "auto",
349
+ // The run going now: every provider at once (at most TEST_AT_ONCE tests running), and from each one model at a time (testOrder: "auto",
337
350
  // then "free", then the rest). A provider that says it's busy (429)
338
351
  // isn't a result about the model: that provider pauses (as long
339
352
  // as it asks, else 15s, 30s… up to 2 minutes), and the model is tried again later; it's kept as
340
353
  // a 429 only after the provider refused it RATE_TRIES times. A model taken off your list while
341
354
  // it runs isn't tested. Stop: each provider finishes the one it's on.
342
355
  const RATE_TRIES = 4
356
+ const TEST_AT_ONCE = 10 // tests at the same time in a run: one per provider, at most this many
343
357
  let run = null
344
358
  const runState = () => ({
345
359
  total: run.total, done: run.done, good: run.good, each: run.each, busy: [...run.busy.keys()], now: [...run.now], stopping: run.stopping, some: run.some, started: run.started,
@@ -349,25 +363,29 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
349
363
  let mineOf = { then: undefined, model: undefined, keys: null }
350
364
  const inMine = (key) => {
351
365
  if (mineOf.then !== cfg.rotation?.then || mineOf.model !== cfg.model || mineOf.provider !== cfg.provider)
352
- mineOf = { then: cfg.rotation?.then, model: cfg.model, provider: cfg.provider, keys: new Set(state().order.map((t) => `${t.provider}/${t.model}`)) }
366
+ mineOf = { then: cfg.rotation?.then, model: cfg.model, provider: cfg.provider, keys: new Set(orderOf().map((t) => `${t.provider}/${t.model}`)) }
353
367
  return mineOf.keys.has(key)
354
368
  }
355
369
  const wait = (ms) => new Promise((r) => setTimeout(r, ms))
356
370
  async function startRun(list, some) {
357
- const each = 1 // one model at a time from each provider; the providers side by side
358
- run = { total: list.length, done: 0, good: 0, each, busy: new Map(), now: new Set(), pending: new Set(list.map((t) => `${t.provider}/${t.model}`)), stopping: false, some, started: Date.now(), providers: new Map(), cancel: new AbortController() }
371
+ // one model at a time from each provider; the providers side by side
372
+ run = { total: list.length, done: 0, good: 0, each: 1, busy: new Map(), now: new Set(), pending: new Set(list.map((t) => `${t.provider}/${t.model}`)), stopping: false, some, started: Date.now(), providers: new Map(), cancel: new AbortController() }
359
373
  emit('testrun', runState())
360
374
  for (const t of list) {
361
- if (!run.providers.has(t.provider)) run.providers.set(t.provider, { queue: [], cap: each, until: 0, pausedAt: 0, backoff: 15_000, refused: new Map() })
375
+ if (!run.providers.has(t.provider)) run.providers.set(t.provider, { queue: [], until: 0, pausedAt: 0, backoff: 15_000, refused: new Map() })
362
376
  run.providers.get(t.provider).queue.push(t)
363
377
  }
364
378
  for (const p of run.providers.values()) p.queue.sort(testOrder)
365
379
  const ticker = setInterval(() => run && Object.keys(runState().paused).length && emit('testrun', runState()), 1000) // the pauses counting down
366
- // a provider's worker n: its next model, while there's one and n is under its cap (a busy
367
- // provider's cap goes down to one: the others stop; the last one left never does)
368
- const worker = async (provider, n) => {
380
+ // the slots: a test takes one before it starts (a provider paused for a rate limit holds none)
381
+ let using = 0
382
+ const queue = []
383
+ const slot = () => (using < TEST_AT_ONCE ? (using++, Promise.resolve()) : new Promise((r) => queue.push(r)))
384
+ const free = () => (queue.length ? queue.shift()() : using--)
385
+ // a provider's worker: its next model, while there's one
386
+ const worker = async (provider) => {
369
387
  const p = run.providers.get(provider)
370
- while (!run.stopping && p.queue.length && (n < p.cap || p.live === 1)) {
388
+ while (!run.stopping && p.queue.length) {
371
389
  if (p.until > Date.now()) {
372
390
  await wait(Math.min(200, p.until - Date.now()))
373
391
  continue
@@ -380,26 +398,29 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
380
398
  emit('testrun', runState())
381
399
  continue
382
400
  }
383
- run.busy.set(provider, (run.busy.get(provider) ?? 0) + 1)
401
+ await slot() // at most TEST_AT_ONCE tests at a time, whatever the number of providers
402
+ if (run.stopping) {
403
+ free()
404
+ break
405
+ }
406
+ run.busy.set(provider, 1)
384
407
  const sent = Date.now()
385
408
  run.now.add(`${t.provider} ${t.model}`) // the models being tested this moment, for the page
386
409
  emit('testrun', runState())
387
- const r = await tryOne(t, run.cancel.signal)
410
+ const r = await tryOne(t, run.cancel.signal).finally(free)
388
411
  run.now.delete(`${t.provider} ${t.model}`)
389
412
  if (r.stopped) break // Stop: not a result (its last one stays)
390
- run.busy.get(provider) > 1 ? run.busy.set(provider, run.busy.get(provider) - 1) : run.busy.delete(provider)
413
+ run.busy.delete(provider)
391
414
  if (r.status === 429) {
392
415
  const times = (p.refused.get(key) ?? 0) + 1
393
416
  p.refused.set(key, times)
394
- p.cap = 1
395
- // a pause, longer each time; not for refusals of requests sent before the last pause began
396
- // (several at once are one burst)
417
+ // a pause, longer each time; not for a refusal of a request sent before the last pause began
397
418
  if (!(sent < p.pausedAt)) {
398
419
  p.pausedAt = Date.now()
399
420
  p.until = Date.now() + Math.min(120_000, r.retryAfter > 0 ? r.retryAfter * 1000 : p.backoff)
400
421
  p.backoff = Math.min(120_000, p.backoff * 2)
401
422
  }
402
- log('test', `${provider} is busy (429): one at a time, pausing ${Math.round((p.until - Date.now()) / 1000)}s${times < RATE_TRIES ? `; ${t.model} again later` : ''}`)
423
+ log('test', `${provider} is busy (429): pausing ${Math.round((p.until - Date.now()) / 1000)}s${times < RATE_TRIES ? `; ${t.model} again later` : ''}`)
403
424
  if (times < RATE_TRIES) {
404
425
  p.queue.push(t)
405
426
  emit('testrun', runState())
@@ -413,11 +434,9 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
413
434
  if (r.ok) run.good++
414
435
  emit('testrun', runState())
415
436
  }
416
- p.live--
417
437
  }
418
- for (const p of run.providers.values()) p.live = Math.min(each, p.queue.length)
419
438
  try {
420
- await Promise.all([...run.providers].flatMap(([provider, p]) => Array.from({ length: p.live }, (_, n) => worker(provider, n))))
439
+ await Promise.all([...run.providers.keys()].map((provider) => worker(provider)))
421
440
  } finally {
422
441
  clearInterval(ticker)
423
442
  const over = { ...runState(), over: true }
@@ -445,7 +464,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
445
464
  const times = pool.filter(ran).map((t) => t.test.ms).sort((x, y) => x - y)
446
465
  const fast = times[Math.floor((times.length - 1) / 2)] // the middle time: faster than that is quick
447
466
  const picks = Object.fromEntries(pool.flatMap((t) => {
448
- const jobs = [top(t, 'webdev:webdev') && 'ui', top(t, 'text:coding') && 'code', ((t.can?.thinking && t.can.context >= 128_000) || top(t, 'agent:overall') || top(t, 'text:hard_prompts')) && 'hard', ran(t) && t.test.ms <= fast && 'quick'].filter(Boolean)
467
+ const tools = t.test?.toolsOk !== false // its tool test failed: the bigger jobs aren't for it
468
+ const jobs = [tools && top(t, 'webdev:webdev') && 'ui', tools && top(t, 'text:coding') && 'code', tools && ((t.can?.thinking && t.can.context >= 128_000) || top(t, 'agent:overall') || top(t, 'text:hard_prompts')) && 'hard', ran(t) && t.test.ms <= fast && 'quick'].filter(Boolean)
449
469
  return jobs.length ? [[keyOf(t), jobs]] : ran(t) ? [[keyOf(t), ['quick']]] : []
450
470
  }))
451
471
  const out = {}
@@ -471,6 +491,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
471
491
  const r = recordOf(t)
472
492
  return r && { done: Math.round(r.good), failed: Math.round(r.bad), poor: unreliable(t) }
473
493
  }
494
+ // your models in order (#1, then the list): what most routes need, without building the whole state
495
+ const orderOf = () => [...(cfg.providers[cfg.provider] && cfg.model ? [{ provider: cfg.provider, model: cfg.model }] : []), ...rotationOf(cfg).then]
474
496
  const state = (ranked = loadRankings()) => ({
475
497
  providers: Object.entries(byName(cfg.providers))
476
498
  .filter(([n]) => n !== cfg.adhoc)
@@ -479,7 +501,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
479
501
  model: cfg.model ?? null,
480
502
  version: VERSION,
481
503
  update: (({ latest } = {}) => (cfg.updateCheck !== false && latest && newer(latest, VERSION) ? latest : null))(readJson(path.join(HOME, 'update-check.json'), {})), // the day's answer from npm: no request here
482
- order: [...(cfg.providers[cfg.provider] && cfg.model ? [{ provider: cfg.provider, model: cfg.model }] : []), ...rotationOf(cfg).then].map((t) => ({ ...t, tested: testedOf(t), known: knownOf(t), price: priceFor(t), ranks: ranksOf(t.model, ranked), record: records.on ? recordView(t) : null })),
504
+ limits: SPEED_LIMITS, // the seconds settings' bounds, for the page's boxes
505
+ order: orderOf().map((t) => ({ ...t, tested: testedOf(t), known: knownOf(t), price: priceFor(t), ranks: ranksOf(t.model, ranked), record: records.on ? recordView(t) : null })),
483
506
  rankings: ranked && { fetched: ranked.fetched, source: ranked.source },
484
507
  rotation: (({ then, ...opts }) => opts)(rotationOf(cfg)),
485
508
  helpers: helpersOf(cfg.helpers), // { 'provider/model': [jobs] }
@@ -524,9 +547,10 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
524
547
  name = safeName(name)
525
548
  if (!name) throw new Error('a name is needed')
526
549
  baseUrl = String(baseUrl ?? '').trim()
550
+ if (/^cli:/i.test(baseUrl) && !cliOf(baseUrl)) throw new Error(`"${baseUrl}": no such CLI`)
527
551
  // an address without http(s)://: whichever of the two the server answers on (any answer, even
528
552
  // a 401, means it's there), https first
529
- if (!/^https?:\/\//i.test(baseUrl)) baseUrl = await schemeFor(baseUrl)
553
+ if (!/^(https?|cli):\/\//i.test(baseUrl)) baseUrl = await schemeFor(baseUrl) // cli://claude: a coding CLI (clis.js)
530
554
  try {
531
555
  if (!new URL(baseUrl).hostname) throw new Error()
532
556
  } catch {
@@ -536,17 +560,44 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
536
560
  const old = cfg.providers[was ?? name]
537
561
  const key = keepKey ? old?.apiKey : String(apiKey ?? '').trim() || undefined
538
562
  if (was && was !== name) {
563
+ if (cfg.providers[name]) throw new Error(`there's a provider named "${name}" already`)
539
564
  delete cfg.providers[was]
540
565
  if (cfg.provider === was) cfg.provider = name
541
566
  for (const t of cfg.rotation?.then ?? []) if (t.provider === was) t.provider = name
567
+ // what's kept per model goes with it: the helpers, the tests, the track record
568
+ const rekey = (o) => {
569
+ for (const k of Object.keys(o ?? {})) if (k.startsWith(`${was}/`)) (o[`${name}/${k.slice(was.length + 1)}`] = o[k]), delete o[k]
570
+ }
571
+ rekey(cfg.helpers)
572
+ rekey(tests)
573
+ saveTests()
574
+ renameRecords(was, name)
542
575
  }
543
576
  cfg.providers[name] = { ...old, baseUrl, apiKey: key } // its list switch and added models stay
544
577
  if (!key) delete cfg.providers[name].apiKey
545
578
  forgetList(name, ...(was ? [was] : [])) // a new URL or key: its models asked for again
546
579
  save('model')
547
580
  forgetTests()
581
+ autoPick()
582
+ return state()
583
+ },
584
+ // the coding CLIs (clis.js): which are installed, how to install the rest, an install going on
585
+ 'GET /api/clis': () => clisInfo(),
586
+ // several CLIs added at once (Add CLIs): each a provider named after it; one added already is skipped
587
+ 'POST /api/clis/add': ({ ids }) => {
588
+ if (!Array.isArray(ids) || !ids.length) throw new Error('no CLI picked')
589
+ for (const id of ids) {
590
+ if (!CLIS[id]) throw new Error(`no CLI "${id}"`)
591
+ if (Object.values(cfg.providers).some((p) => cliOf(p.baseUrl) === id)) continue
592
+ const name = cfg.providers[id] ? `${id}-cli` : id
593
+ cfg.providers[name] = { baseUrl: cliUrl(id) }
594
+ forgetList(name)
595
+ }
596
+ save('model')
597
+ autoPick()
548
598
  return state()
549
599
  },
600
+ 'POST /api/cli/install': ({ id }) => (installCli(id, () => emit('clis', {})), clisInfo()),
550
601
  'POST /api/provider/delete': ({ name }) => {
551
602
  if (!cfg.providers[name]) throw new Error(`no provider "${name}"`)
552
603
  delete cfg.providers[name]
@@ -559,6 +610,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
559
610
  }
560
611
  save('model')
561
612
  forgetTests()
613
+ autoPick()
562
614
  return state()
563
615
  },
564
616
  // a provider's models, and what's known about each (for the page's tooltip): what the provider
@@ -578,11 +630,16 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
578
630
  },
579
631
  // A provider switched off: kept (its key, its models in your list), but HeartCode skips its models
580
632
  // until it's on again.
581
- 'POST /api/provider/on': ({ name, on }) => {
582
- if (!cfg.providers[name]) throw new Error(`no provider "${name}"`)
583
- if (on) delete cfg.providers[name].off
584
- else cfg.providers[name].off = true
585
- save('provider')
633
+ // names: several at once (the ones selected); neither: every provider (Turn all on / off)
634
+ 'POST /api/provider/on': ({ name, names, on }) => {
635
+ const list = names ?? (name !== undefined ? [name] : Object.keys(cfg.providers))
636
+ for (const n of list) if (!cfg.providers[n]) throw new Error(`no provider "${n}"`)
637
+ for (const p of list.map((n) => cfg.providers[n])) {
638
+ if (on) delete p.off
639
+ else p.off = true
640
+ }
641
+ save('model') // the running sessions' model lists follow at once
642
+ autoPick()
586
643
  return state()
587
644
  },
588
645
  // A model added by its name (one the provider doesn't list, or its list is off): remembered under
@@ -678,9 +735,6 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
678
735
  save('setting:helpers')
679
736
  return { helpers: helpersOf(cfg.helpers), helpersAuto: false } // only these: the page saves a click at once, and the whole state of a long list takes seconds
680
737
  },
681
- // the order helpers are picked in: 'score' (the default: best placed in LMArena's rankings first),
682
- // 'own' (your list's) or 'provider' (your provider ranking's, each provider's in your list's order;
683
- // rank: the ranking as the page has it, kept for HeartCode to use)
684
738
  // the model list, in order (#1 is the model), and when to go on to the next
685
739
  'POST /api/order': ({ list, on, retries, next }) => {
686
740
  if (!Array.isArray(list)) throw new Error('a list of models is needed')
@@ -752,11 +806,11 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
752
806
  // a run: all your models, or the ones given (only); one at a time if one is going already
753
807
  'POST /api/tests/start': ({ only } = {}) => {
754
808
  if (run) throw new Error('a test is running: wait for it, or stop it')
755
- const order = state().order
809
+ const order = orderOf()
756
810
  const mine = new Set(order.map((t) => `${t.provider}/${t.model}`))
757
811
  const list = Array.isArray(only) ? only.map((t) => ({ provider: String(t?.provider ?? ''), model: String(t?.model ?? '') })).filter((t) => mine.has(`${t.provider}/${t.model}`)) : order.map(({ provider, model }) => ({ provider, model }))
758
812
  if (!list.length) throw new Error('no model to test')
759
- startRun(list, Array.isArray(only))
813
+ startRun(list, Array.isArray(only)).catch((e) => log('settings', `test run: ${e.message}`)) // a write that failed: logged, not an unhandled rejection in HeartCode
760
814
  return { run: { ...runState(), pending: [...run.pending] } }
761
815
  },
762
816
  'POST /api/tests/stop': () => {
@@ -765,7 +819,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
765
819
  },
766
820
  'POST /api/models-dev': async ({ provider, model } = {}) => {
767
821
  await loadPrices({ force: true })
768
- const list = provider && model ? [{ provider, model: String(model) }] : state().order.map(({ provider, model }) => ({ provider, model }))
822
+ const list = provider && model ? [{ provider, model: String(model) }] : orderOf()
769
823
  let found = 0
770
824
  for (const t of list) {
771
825
  const c = clientFor(t)
@@ -778,6 +832,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
778
832
  testNews(`${t.provider}/${t.model}`, t)
779
833
  }
780
834
  changed('profile')
835
+ autoPick() // picked for you: what models.dev says each can do counts
781
836
  return { ...state(), found, of: list.length }
782
837
  },
783
838
  // What a model can do, set by you (a model models.dev doesn't know, or to correct it): its
@@ -792,7 +847,12 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
792
847
  for (const [k, v] of Object.entries({ tools, thinking, images, stream })) if (typeof v !== 'boolean') throw new Error(`${k}: yes or no`)
793
848
  await loadPrices()
794
849
  const p = loadProfile(c) ?? profileFrom(c, limitsOf(t.provider, c.baseUrl, t.model))
795
- p.set = { ...(context ? { context } : {}), tools, thinking, images, stream }
850
+ // only what differs from models.dev is yours: the rest follows models.dev when it corrects itself
851
+ const said = p.known ?? {}
852
+ const as = { tools: said.tools !== false, thinking: Boolean(said.thinking), images: Boolean(said.images), stream: true }
853
+ p.set = Object.fromEntries(Object.entries({ tools, thinking, images, stream }).filter(([k, v]) => v !== as[k]))
854
+ if (context) p.set.context = context
855
+ if (!Object.keys(p.set).length) delete p.set
796
856
  if (p.source === 'assumed') p.source = 'you'
797
857
  writeJson(profilePath(c), p)
798
858
  changed('profile')
@@ -1125,7 +1185,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1125
1185
 
1126
1186
  // Settings changed by anyone else (another HeartCode or page on this folder, a hand): taken in, and
1127
1187
  // every open page shown them at once (an event: the whole state, when it's different)
1128
- const SETTINGS_FILES = ['config.json', 'settings-page.json', 'mcp.json', 'hooks.json', 'keybindings.json', 'theme.json', 'format.json', 'HEARTCODE.md', 'prompts', 'skills']
1188
+ const SETTINGS_FILES = ['config.json', 'settings-page.json', 'mcp.json', 'hooks.json', 'keybindings.json', 'theme.json', 'format.json', 'HEARTCODE.md', 'prompts', 'skills', 'records.json', 'rankings.json', 'models', 'model-tests.json'] // and what other runs learn (track records, rankings, models' profiles, tests)
1129
1189
  let shown = ''
1130
1190
  const pushState = () => {
1131
1191
  for (const what of new Set(takeIn(cfg).map(whatOf))) changed(what)
@@ -1139,6 +1199,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1139
1199
  const w = fs.watch(HOME, { recursive: true }, (_, f) => {
1140
1200
  if (!SETTINGS_FILES.includes(String(f ?? '').split(path.sep)[0])) return
1141
1201
  if (Date.now() - ownWrite < 1000 && ['config.json', 'settings-page.json'].includes(String(f))) return // written here a moment ago: the page has it
1202
+ if (String(f) === 'model-tests.json') for (const [k, v] of Object.entries(readJson(TESTS_FILE, {}))) if (!(k in tests) && !gone.has(k)) tests[k] = v // another HeartCode's tests
1142
1203
  clearTimeout(pending)
1143
1204
  pending = setTimeout(pushState, 150) // a file written in parts, several at once: one look
1144
1205
  })
@@ -1188,20 +1249,22 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1188
1249
  return new Promise((resolve, reject) => {
1189
1250
  server.on('error', reject)
1190
1251
  forgetTests() // results of models no longer yours, left from before
1191
- server.listen(port, '0.0.0.0', () => {
1252
+ // this machine only; over SSH, the address you reached it at too (the page holds your keys' settings,
1253
+ // over plain HTTP: not offered to everyone on the network)
1254
+ const ssh = process.env.SSH_CONNECTION?.split(' ')[2]
1255
+ server.listen(port, ssh ? '0.0.0.0' : '127.0.0.1', () => {
1192
1256
  const at = (host) => `http://${host}:${server.address().port}/?t=${token}`
1193
1257
  const local = at('127.0.0.1') // for a browser on this machine
1194
- const ssh = process.env.SSH_CONNECTION?.split(' ')[2] // over SSH: the address you reached this machine at
1195
- const url = at((ssh?.includes(':') ? `[${ssh}]` : ssh) ?? addresses()[0] ?? '127.0.0.1') // else its network address when it has one: works from another device too
1258
+ const url = ssh ? at(ssh.includes(':') ? `[${ssh}]` : ssh) : local
1196
1259
  log('web', `settings page at ${new URL(url).host}`)
1197
1260
  // models.dev's list (its sizes for your models, whether their providers' lists are on or not):
1198
1261
  // loaded now, and your models' lines brought up to date when it's in
1199
1262
  loadPrices().then(() => {
1200
- for (const t of state().order) testNews(`${t.provider}/${t.model}`, t)
1201
- test(state().order) // any without a profile yet
1263
+ for (const t of orderOf()) testNews(`${t.provider}/${t.model}`, t)
1264
+ test(orderOf()) // any without a profile yet
1202
1265
  warm()
1203
1266
  })
1204
- resolve({ url, local, server, close: () => (watcher?.close(), server.closeAllConnections?.(), server.close()) })
1267
+ resolve({ url, local, server, close: () => (saving && (clearTimeout(saving), writeTests()), watcher?.close(), server.closeAllConnections?.(), server.close()) }) // a test result not written yet: written now
1205
1268
  })
1206
1269
  })
1207
1270
  }
package/src/skills.js CHANGED
@@ -113,6 +113,8 @@ export function readSkillFile(k, file) {
113
113
  const abs = path.resolve(dir, file)
114
114
  if (path.basename(k.file) !== 'SKILL.md' || !abs.startsWith(dir + path.sep)) return `error: the ${k.name} skill has no file "${file}"`
115
115
  try {
116
+ const real = fs.realpathSync.native(abs)
117
+ if (!real.startsWith(fs.realpathSync.native(dir) + path.sep)) return `error: ${file} in the ${k.name} skill is a link out of it: not read` // a link to ~/.ssh
116
118
  return fs.readFileSync(abs, 'utf8')
117
119
  } catch {
118
120
  return `error: the ${k.name} skill has no file "${file}". Its files: ${skillFiles(k).join(', ') || 'none'}`
package/src/tabs.js CHANGED
@@ -119,6 +119,7 @@ export class Tabs {
119
119
  // │ 1 heart_cli │ │ 2 fix tests ●│ Alt+T open a new tab
120
120
  // ─╯ ╰─┴──────────────┴──────────────────
121
121
  bar(cols = 100) {
122
+ if (this.list.length < 2) return [] // one tab: no bar (the header says how to open another)
122
123
  const mark = { '?': c.warn('?'), '●': c.brand('●'), '✓': c.ok('✓') }
123
124
  const room = Math.max(6, Math.floor((cols - 24) / this.list.length) - 7) // a name's cells, so they all fit
124
125
  let [top, mid, bottom] = [' ', ' ', c.ghost('─')]