heartcode 0.1.69 → 0.1.101

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]
@@ -262,15 +264,25 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
262
264
  // doesn't stop them. Each result is kept in ~/.heart/model-tests.json ("provider/model" → { ok, ms,
263
265
  // reply | error, status, at }) and sent to the page as it comes.
264
266
  const TESTS_FILE = path.join(HOME, 'model-tests.json')
265
- const tests = readJson(TESTS_FILE, {})
267
+ const tests = Object.fromEntries(Object.entries(readJson(TESTS_FILE, {})).map(([k, r]) => [k, judged(r)])) // older results judged the same way
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,14 @@ 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
+ const verdict = judged({ ok: true, ms, reply: reply.slice(0, 200) })
313
+ if (!verdict.ok) return verdict // an error said as its answer, or no answer to the question: no tool test
314
+ return { ...verdict, ...(testedOf({ provider, model })?.mode === 'tools' && !c.cli && (await toolTest(c, stop))) }
301
315
  } catch (e) {
302
316
  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) }) }
317
+ 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
318
  }
305
319
  }
306
320
  // A model that says it calls tools: can it do work with one? One of HeartCode's own tools and a
@@ -320,7 +334,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
320
334
  }
321
335
  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
336
  } catch (e) {
323
- if (stop?.aborted || e.name === 'TimeoutError') return {}
337
+ if (stop?.aborted) return {}
338
+ if (e.name === 'TimeoutError') return { toolsOk: false, toolsWhy: `no answer to a request with tools within ${testWait() / 1000} seconds` } // hung: not a pass
324
339
  return { toolsOk: false, toolsWhy: `a request with tools failed: ${whyFailed(e)}` }
325
340
  }
326
341
  }
@@ -333,13 +348,14 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
333
348
  emit('tested', { key, result })
334
349
  return result
335
350
  }
336
- // The run going now: every provider at once, and from each one model at a time (testOrder: "auto",
351
+ // 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
352
  // then "free", then the rest). A provider that says it's busy (429)
338
353
  // isn't a result about the model: that provider pauses (as long
339
354
  // as it asks, else 15s, 30s… up to 2 minutes), and the model is tried again later; it's kept as
340
355
  // a 429 only after the provider refused it RATE_TRIES times. A model taken off your list while
341
356
  // it runs isn't tested. Stop: each provider finishes the one it's on.
342
357
  const RATE_TRIES = 4
358
+ const TEST_AT_ONCE = 10 // tests at the same time in a run: one per provider, at most this many
343
359
  let run = null
344
360
  const runState = () => ({
345
361
  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 +365,29 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
349
365
  let mineOf = { then: undefined, model: undefined, keys: null }
350
366
  const inMine = (key) => {
351
367
  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}`)) }
368
+ mineOf = { then: cfg.rotation?.then, model: cfg.model, provider: cfg.provider, keys: new Set(orderOf().map((t) => `${t.provider}/${t.model}`)) }
353
369
  return mineOf.keys.has(key)
354
370
  }
355
371
  const wait = (ms) => new Promise((r) => setTimeout(r, ms))
356
372
  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() }
373
+ // one model at a time from each provider; the providers side by side
374
+ 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
375
  emit('testrun', runState())
360
376
  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() })
377
+ if (!run.providers.has(t.provider)) run.providers.set(t.provider, { queue: [], until: 0, pausedAt: 0, backoff: 15_000, refused: new Map() })
362
378
  run.providers.get(t.provider).queue.push(t)
363
379
  }
364
380
  for (const p of run.providers.values()) p.queue.sort(testOrder)
365
381
  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) => {
382
+ // the slots: a test takes one before it starts (a provider paused for a rate limit holds none)
383
+ let using = 0
384
+ const queue = []
385
+ const slot = () => (using < TEST_AT_ONCE ? (using++, Promise.resolve()) : new Promise((r) => queue.push(r)))
386
+ const free = () => (queue.length ? queue.shift()() : using--)
387
+ // a provider's worker: its next model, while there's one
388
+ const worker = async (provider) => {
369
389
  const p = run.providers.get(provider)
370
- while (!run.stopping && p.queue.length && (n < p.cap || p.live === 1)) {
390
+ while (!run.stopping && p.queue.length) {
371
391
  if (p.until > Date.now()) {
372
392
  await wait(Math.min(200, p.until - Date.now()))
373
393
  continue
@@ -380,26 +400,29 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
380
400
  emit('testrun', runState())
381
401
  continue
382
402
  }
383
- run.busy.set(provider, (run.busy.get(provider) ?? 0) + 1)
403
+ await slot() // at most TEST_AT_ONCE tests at a time, whatever the number of providers
404
+ if (run.stopping) {
405
+ free()
406
+ break
407
+ }
408
+ run.busy.set(provider, 1)
384
409
  const sent = Date.now()
385
410
  run.now.add(`${t.provider} ${t.model}`) // the models being tested this moment, for the page
386
411
  emit('testrun', runState())
387
- const r = await tryOne(t, run.cancel.signal)
412
+ const r = await tryOne(t, run.cancel.signal).finally(free)
388
413
  run.now.delete(`${t.provider} ${t.model}`)
389
414
  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)
415
+ run.busy.delete(provider)
391
416
  if (r.status === 429) {
392
417
  const times = (p.refused.get(key) ?? 0) + 1
393
418
  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)
419
+ // a pause, longer each time; not for a refusal of a request sent before the last pause began
397
420
  if (!(sent < p.pausedAt)) {
398
421
  p.pausedAt = Date.now()
399
422
  p.until = Date.now() + Math.min(120_000, r.retryAfter > 0 ? r.retryAfter * 1000 : p.backoff)
400
423
  p.backoff = Math.min(120_000, p.backoff * 2)
401
424
  }
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` : ''}`)
425
+ log('test', `${provider} is busy (429): pausing ${Math.round((p.until - Date.now()) / 1000)}s${times < RATE_TRIES ? `; ${t.model} again later` : ''}`)
403
426
  if (times < RATE_TRIES) {
404
427
  p.queue.push(t)
405
428
  emit('testrun', runState())
@@ -413,11 +436,9 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
413
436
  if (r.ok) run.good++
414
437
  emit('testrun', runState())
415
438
  }
416
- p.live--
417
439
  }
418
- for (const p of run.providers.values()) p.live = Math.min(each, p.queue.length)
419
440
  try {
420
- await Promise.all([...run.providers].flatMap(([provider, p]) => Array.from({ length: p.live }, (_, n) => worker(provider, n))))
441
+ await Promise.all([...run.providers.keys()].map((provider) => worker(provider)))
421
442
  } finally {
422
443
  clearInterval(ticker)
423
444
  const over = { ...runState(), over: true }
@@ -445,7 +466,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
445
466
  const times = pool.filter(ran).map((t) => t.test.ms).sort((x, y) => x - y)
446
467
  const fast = times[Math.floor((times.length - 1) / 2)] // the middle time: faster than that is quick
447
468
  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)
469
+ const tools = t.test?.toolsOk !== false // its tool test failed: the bigger jobs aren't for it
470
+ 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
471
  return jobs.length ? [[keyOf(t), jobs]] : ran(t) ? [[keyOf(t), ['quick']]] : []
450
472
  }))
451
473
  const out = {}
@@ -471,6 +493,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
471
493
  const r = recordOf(t)
472
494
  return r && { done: Math.round(r.good), failed: Math.round(r.bad), poor: unreliable(t) }
473
495
  }
496
+ // your models in order (#1, then the list): what most routes need, without building the whole state
497
+ const orderOf = () => [...(cfg.providers[cfg.provider] && cfg.model ? [{ provider: cfg.provider, model: cfg.model }] : []), ...rotationOf(cfg).then]
474
498
  const state = (ranked = loadRankings()) => ({
475
499
  providers: Object.entries(byName(cfg.providers))
476
500
  .filter(([n]) => n !== cfg.adhoc)
@@ -479,7 +503,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
479
503
  model: cfg.model ?? null,
480
504
  version: VERSION,
481
505
  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 })),
506
+ limits: SPEED_LIMITS, // the seconds settings' bounds, for the page's boxes
507
+ 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
508
  rankings: ranked && { fetched: ranked.fetched, source: ranked.source },
484
509
  rotation: (({ then, ...opts }) => opts)(rotationOf(cfg)),
485
510
  helpers: helpersOf(cfg.helpers), // { 'provider/model': [jobs] }
@@ -524,9 +549,10 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
524
549
  name = safeName(name)
525
550
  if (!name) throw new Error('a name is needed')
526
551
  baseUrl = String(baseUrl ?? '').trim()
552
+ if (/^cli:/i.test(baseUrl) && !cliOf(baseUrl)) throw new Error(`"${baseUrl}": no such CLI`)
527
553
  // an address without http(s)://: whichever of the two the server answers on (any answer, even
528
554
  // a 401, means it's there), https first
529
- if (!/^https?:\/\//i.test(baseUrl)) baseUrl = await schemeFor(baseUrl)
555
+ if (!/^(https?|cli):\/\//i.test(baseUrl)) baseUrl = await schemeFor(baseUrl) // cli://claude: a coding CLI (clis.js)
530
556
  try {
531
557
  if (!new URL(baseUrl).hostname) throw new Error()
532
558
  } catch {
@@ -536,17 +562,44 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
536
562
  const old = cfg.providers[was ?? name]
537
563
  const key = keepKey ? old?.apiKey : String(apiKey ?? '').trim() || undefined
538
564
  if (was && was !== name) {
565
+ if (cfg.providers[name]) throw new Error(`there's a provider named "${name}" already`)
539
566
  delete cfg.providers[was]
540
567
  if (cfg.provider === was) cfg.provider = name
541
568
  for (const t of cfg.rotation?.then ?? []) if (t.provider === was) t.provider = name
569
+ // what's kept per model goes with it: the helpers, the tests, the track record
570
+ const rekey = (o) => {
571
+ for (const k of Object.keys(o ?? {})) if (k.startsWith(`${was}/`)) (o[`${name}/${k.slice(was.length + 1)}`] = o[k]), delete o[k]
572
+ }
573
+ rekey(cfg.helpers)
574
+ rekey(tests)
575
+ saveTests()
576
+ renameRecords(was, name)
542
577
  }
543
578
  cfg.providers[name] = { ...old, baseUrl, apiKey: key } // its list switch and added models stay
544
579
  if (!key) delete cfg.providers[name].apiKey
545
580
  forgetList(name, ...(was ? [was] : [])) // a new URL or key: its models asked for again
546
581
  save('model')
547
582
  forgetTests()
583
+ autoPick()
584
+ return state()
585
+ },
586
+ // the coding CLIs (clis.js): which are installed, how to install the rest, an install going on
587
+ 'GET /api/clis': () => clisInfo(),
588
+ // several CLIs added at once (Add CLIs): each a provider named after it; one added already is skipped
589
+ 'POST /api/clis/add': ({ ids }) => {
590
+ if (!Array.isArray(ids) || !ids.length) throw new Error('no CLI picked')
591
+ for (const id of ids) {
592
+ if (!CLIS[id]) throw new Error(`no CLI "${id}"`)
593
+ if (Object.values(cfg.providers).some((p) => cliOf(p.baseUrl) === id)) continue
594
+ const name = cfg.providers[id] ? `${id}-cli` : id
595
+ cfg.providers[name] = { baseUrl: cliUrl(id) }
596
+ forgetList(name)
597
+ }
598
+ save('model')
599
+ autoPick()
548
600
  return state()
549
601
  },
602
+ 'POST /api/cli/install': ({ id }) => (installCli(id, () => emit('clis', {})), clisInfo()),
550
603
  'POST /api/provider/delete': ({ name }) => {
551
604
  if (!cfg.providers[name]) throw new Error(`no provider "${name}"`)
552
605
  delete cfg.providers[name]
@@ -559,6 +612,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
559
612
  }
560
613
  save('model')
561
614
  forgetTests()
615
+ autoPick()
562
616
  return state()
563
617
  },
564
618
  // a provider's models, and what's known about each (for the page's tooltip): what the provider
@@ -578,11 +632,16 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
578
632
  },
579
633
  // A provider switched off: kept (its key, its models in your list), but HeartCode skips its models
580
634
  // 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')
635
+ // names: several at once (the ones selected); neither: every provider (Turn all on / off)
636
+ 'POST /api/provider/on': ({ name, names, on }) => {
637
+ const list = names ?? (name !== undefined ? [name] : Object.keys(cfg.providers))
638
+ for (const n of list) if (!cfg.providers[n]) throw new Error(`no provider "${n}"`)
639
+ for (const p of list.map((n) => cfg.providers[n])) {
640
+ if (on) delete p.off
641
+ else p.off = true
642
+ }
643
+ save('model') // the running sessions' model lists follow at once
644
+ autoPick()
586
645
  return state()
587
646
  },
588
647
  // A model added by its name (one the provider doesn't list, or its list is off): remembered under
@@ -678,9 +737,6 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
678
737
  save('setting:helpers')
679
738
  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
739
  },
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
740
  // the model list, in order (#1 is the model), and when to go on to the next
685
741
  'POST /api/order': ({ list, on, retries, next }) => {
686
742
  if (!Array.isArray(list)) throw new Error('a list of models is needed')
@@ -752,11 +808,11 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
752
808
  // a run: all your models, or the ones given (only); one at a time if one is going already
753
809
  'POST /api/tests/start': ({ only } = {}) => {
754
810
  if (run) throw new Error('a test is running: wait for it, or stop it')
755
- const order = state().order
811
+ const order = orderOf()
756
812
  const mine = new Set(order.map((t) => `${t.provider}/${t.model}`))
757
813
  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
814
  if (!list.length) throw new Error('no model to test')
759
- startRun(list, Array.isArray(only))
815
+ 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
816
  return { run: { ...runState(), pending: [...run.pending] } }
761
817
  },
762
818
  'POST /api/tests/stop': () => {
@@ -765,7 +821,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
765
821
  },
766
822
  'POST /api/models-dev': async ({ provider, model } = {}) => {
767
823
  await loadPrices({ force: true })
768
- const list = provider && model ? [{ provider, model: String(model) }] : state().order.map(({ provider, model }) => ({ provider, model }))
824
+ const list = provider && model ? [{ provider, model: String(model) }] : orderOf()
769
825
  let found = 0
770
826
  for (const t of list) {
771
827
  const c = clientFor(t)
@@ -778,6 +834,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
778
834
  testNews(`${t.provider}/${t.model}`, t)
779
835
  }
780
836
  changed('profile')
837
+ autoPick() // picked for you: what models.dev says each can do counts
781
838
  return { ...state(), found, of: list.length }
782
839
  },
783
840
  // What a model can do, set by you (a model models.dev doesn't know, or to correct it): its
@@ -792,7 +849,12 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
792
849
  for (const [k, v] of Object.entries({ tools, thinking, images, stream })) if (typeof v !== 'boolean') throw new Error(`${k}: yes or no`)
793
850
  await loadPrices()
794
851
  const p = loadProfile(c) ?? profileFrom(c, limitsOf(t.provider, c.baseUrl, t.model))
795
- p.set = { ...(context ? { context } : {}), tools, thinking, images, stream }
852
+ // only what differs from models.dev is yours: the rest follows models.dev when it corrects itself
853
+ const said = p.known ?? {}
854
+ const as = { tools: said.tools !== false, thinking: Boolean(said.thinking), images: Boolean(said.images), stream: true }
855
+ p.set = Object.fromEntries(Object.entries({ tools, thinking, images, stream }).filter(([k, v]) => v !== as[k]))
856
+ if (context) p.set.context = context
857
+ if (!Object.keys(p.set).length) delete p.set
796
858
  if (p.source === 'assumed') p.source = 'you'
797
859
  writeJson(profilePath(c), p)
798
860
  changed('profile')
@@ -1125,7 +1187,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1125
1187
 
1126
1188
  // Settings changed by anyone else (another HeartCode or page on this folder, a hand): taken in, and
1127
1189
  // 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']
1190
+ 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
1191
  let shown = ''
1130
1192
  const pushState = () => {
1131
1193
  for (const what of new Set(takeIn(cfg).map(whatOf))) changed(what)
@@ -1139,6 +1201,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1139
1201
  const w = fs.watch(HOME, { recursive: true }, (_, f) => {
1140
1202
  if (!SETTINGS_FILES.includes(String(f ?? '').split(path.sep)[0])) return
1141
1203
  if (Date.now() - ownWrite < 1000 && ['config.json', 'settings-page.json'].includes(String(f))) return // written here a moment ago: the page has it
1204
+ 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
1205
  clearTimeout(pending)
1143
1206
  pending = setTimeout(pushState, 150) // a file written in parts, several at once: one look
1144
1207
  })
@@ -1188,20 +1251,22 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1188
1251
  return new Promise((resolve, reject) => {
1189
1252
  server.on('error', reject)
1190
1253
  forgetTests() // results of models no longer yours, left from before
1191
- server.listen(port, '0.0.0.0', () => {
1254
+ // this machine only; over SSH, the address you reached it at too (the page holds your keys' settings,
1255
+ // over plain HTTP: not offered to everyone on the network)
1256
+ const ssh = process.env.SSH_CONNECTION?.split(' ')[2]
1257
+ server.listen(port, ssh ? '0.0.0.0' : '127.0.0.1', () => {
1192
1258
  const at = (host) => `http://${host}:${server.address().port}/?t=${token}`
1193
1259
  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
1260
+ const url = ssh ? at(ssh.includes(':') ? `[${ssh}]` : ssh) : local
1196
1261
  log('web', `settings page at ${new URL(url).host}`)
1197
1262
  // models.dev's list (its sizes for your models, whether their providers' lists are on or not):
1198
1263
  // loaded now, and your models' lines brought up to date when it's in
1199
1264
  loadPrices().then(() => {
1200
- for (const t of state().order) testNews(`${t.provider}/${t.model}`, t)
1201
- test(state().order) // any without a profile yet
1265
+ for (const t of orderOf()) testNews(`${t.provider}/${t.model}`, t)
1266
+ test(orderOf()) // any without a profile yet
1202
1267
  warm()
1203
1268
  })
1204
- resolve({ url, local, server, close: () => (watcher?.close(), server.closeAllConnections?.(), server.close()) })
1269
+ resolve({ url, local, server, close: () => (saving && (clearTimeout(saving), writeTests()), watcher?.close(), server.closeAllConnections?.(), server.close()) }) // a test result not written yet: written now
1205
1270
  })
1206
1271
  })
1207
1272
  }
@@ -1220,6 +1285,20 @@ function warm() {
1220
1285
  step(0)
1221
1286
  }
1222
1287
 
1288
+ // A test's answer, judged: asked to reply with just "OK", a model that answered with an error as its
1289
+ // text (a provider's "not enough credits", a CLI's "Model … is not available") or with something else
1290
+ // altogether (an image link, a safety verdict, a persona's greeting) doesn't work for HeartCode,
1291
+ // though the request went through. OK with more around it (thinking written into the answer) works.
1292
+ const SAID_ERROR = /\b(error|exception|execution failed|not available|unavailable|not supported|insufficient|not enough credits|enough credits|top ?up|upgrade your plan|recharg\w*|quota|rate.?limit\w*|unauthori[sz]ed|forbidden|invalid (api )?key|access denied|not allowed|exceeded|billing|payment required)\b/i
1293
+ export function judged(r) {
1294
+ if (!r?.ok || typeof r.reply !== 'string') return r
1295
+ const text = r.reply.trim()
1296
+ if (/^\W*ok(ay)?\W*$/i.test(text)) return r
1297
+ if (SAID_ERROR.test(text)) return { ...r, ok: false, kind: 'said-error', error: `it answered with an error: "${clip(text.replace(/\s+/g, ' '), 160)}"` }
1298
+ if (!/\bok(ay)?\b/i.test(text)) return { ...r, ok: false, kind: 'off-task', error: `it didn't answer the question (asked to reply "OK"): "${clip(text.replace(/\s+/g, ' '), 160)}"` }
1299
+ return r
1300
+ }
1301
+
1223
1302
  // This machine's IPv4 addresses on its networks (Wi-Fi, Ethernet, a VPN), not the loopback one
1224
1303
  const addresses = () => Object.values(os.networkInterfaces()).flat().filter((n) => n && n.family === 'IPv4' && !n.internal).map((n) => n.address)
1225
1304
 
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('─')]