heartcode 0.1.63 → 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,25 +13,29 @@ 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)
25
27
  import { installSkill, findImports } from './importer.js'
26
28
  import { capabilities } from './capabilities.js'
27
29
  import { connect, sendTelegram, tokenHint, tgReady, EVENTS } from './telegram.js'
30
+ import { alert, ALERT_EVENTS } from './alert.js'
28
31
  import { searchSettings, testSearxng, ENGINE_NAMES } from './web.js'
29
- import { log, LOGS, REQUESTS, useRequestLog, listRequests, readRequest, pruneLogs, logDays, logSize, clearLogs, LOG_KINDS, kindsOn, listLogRuns, readLog } from './log.js'
32
+ import { recordOf, unreliable, records } from './record.js'
33
+ import { log, LOGS, REQUESTS, useRequestLog, listRequests, readRequest, pruneLogs, logDays, logSize, clearLogs, LOG_KINDS, LOG_SAMPLES, kindsOn, listLogRuns, readLog } from './log.js'
30
34
  import { fetch } from './http.js' // not the built-in one: see http.js
31
35
 
32
36
  const PAGE = new URL('./settings.html', import.meta.url)
33
37
  const EFFORTS = ['default', 'low', 'medium', 'high']
34
- const TOGGLES = { autoCompact: 'compact the conversation when it fills 85% of the model\'s context window', director: 'let the model add skills, MCP servers and change settings when asked', format: "run the project's formatter on every file HeartCode writes", lsp: "show the model a language server's errors after each edit", updateCheck: 'check at every start whether a newer HeartCode is out (shown in the status bar; /update installs it)', mouse: "the wheel scrolls only the conversation (the tabs, the input and the status bar stay put) and dragging copies; Option+drag (Shift+drag elsewhere) is the terminal's own selection. Off: the terminal's own mouse, and its wheel scrolls the whole screen" }
38
+ const TOGGLES = { autoCompact: 'compact the conversation when it fills 85% of the model\'s context window', director: 'let the model add skills, MCP servers and change settings when asked', format: "run the project's formatter on every file HeartCode writes", lsp: "show the model a language server's errors after each edit", updateCheck: 'check at every start whether a newer HeartCode is out (shown in the status bar; /update installs it)', trackRecord: "remember how each model does in real work (tasks finished; handed over, reviews that said no, broken replies): one that keeps doing well comes first where HeartCode picks by ranking (the next model after a failure, a handover, helpers by score), and one that fails most of its work moves down and doesn't start a message while another can. Off: the rankings and your order only", mouse: "the wheel scrolls only the conversation (the tabs, the input and the status bar stay put) and dragging copies; Option+drag (Shift+drag elsewhere) is the terminal's own selection. Off: the terminal's own mouse, and its wheel scrolls the whole screen" }
35
39
  // The Logging page's: both off unless switched on; how much of each request ("full" or "summary")
36
40
  // The status-bar items the visual editor offers (id must match App.status in bin/heartcode.js).
37
41
  // `sample` is shown in the page's live preview.
@@ -62,7 +66,7 @@ const FILES = [
62
66
  ['HEARTCODE.md', 'Instructions for every project (like AGENTS.md, for all of them)', false, '- Answer briefly.\n- Use pnpm, not npm.'],
63
67
  ]
64
68
  // The prompts the page edits: every section of these files (prompts/*.md); the system prompts first.
65
- const PROMPT_FILES = ['agent', 'guided', 'compact', 'tests']
69
+ const PROMPT_FILES = ['agent', 'guides', 'guided', 'compact', 'tests']
66
70
  const FIRST = { 'agent/system': 'System prompt (models with tool calls)', 'guided/system': 'System prompt (guided mode: models without tool calls)' }
67
71
  const ownPrompts = (file) => path.join(HOME, 'prompts', `${file}.md`)
68
72
  const tilde = (p) => (p.startsWith(os.homedir() + path.sep) ? '~' + p.slice(os.homedir().length) : p)
@@ -150,7 +154,7 @@ const LIST_V = 2 // how a saved list was read (2: airforce's cents, Cloudflare's
150
154
  // The page's own choices (sorts, folded providers, the provider ranking): kept here, not in the
151
155
  // browser, whose storage is per address (a new port each time)
152
156
  const PREFS = path.join(HOME, 'settings-page.json')
153
- const PREF_KEYS = ['catSort', 'freeOnly', 'folded', 'sort', 'sorts', 'rank', 'filters']
157
+ const PREF_KEYS = ['catSort', 'freeOnly', 'onOnly', 'catKind', 'folded', 'sort', 'sorts', 'rank', 'filters']
154
158
  // The saved lists (a MB or more): kept in memory, read again only when the file changes
155
159
  let lists = null
156
160
  const readLists = () => {
@@ -219,7 +223,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
219
223
  if (!p) return null
220
224
  const known = limitsOf(t.provider, c.baseUrl, t.model) ?? p.known
221
225
  const st = strategy({ ...p, known, source: p.source === 'assumed' && known ? 'models.dev' : p.source })
222
- 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 ?? {} }
223
227
  }
224
228
  const knownOf = (t) => {
225
229
  const p = cfg.providers[t.provider]
@@ -262,19 +266,36 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
262
266
  const TESTS_FILE = path.join(HOME, 'model-tests.json')
263
267
  const tests = readJson(TESTS_FILE, {})
264
268
  let saving = null
265
- 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
266
280
  // a model taken off your list: its test result goes too (added again, it's not tested)
267
281
  const forgetTests = () => {
268
- const mine = new Set(state().order.map((t) => `${t.provider}/${t.model}`))
269
- let gone = 0
270
- for (const key of Object.keys(tests)) if (!mine.has(key)) (delete tests[key]), gone++
271
- 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()
272
286
  }
273
287
  // How long a model test waits for its answer (cfg.testTimeout, seconds; the settings page sets it).
274
288
  const testWait = () => testWaitOf(cfg) * 1000
275
289
  const noAnswer = () => `no answer within ${testWait() / 1000} seconds`
276
- // A provider's models tested a few at a time (more for a long list: startRun)
277
- const AT_ONCE = 4
290
+ // A run's order within a provider: names with the word "auto" (a router) first, then "free", then the
291
+ // rest, each A to Z (a word: "openrouter/auto", "llama:free"; not "autoglm"). The name only, never the price.
292
+ const word = (w) => new RegExp(`(^|[^a-z0-9])${w}([^a-z0-9]|$)`, 'i')
293
+ const AUTO = word('auto')
294
+ const FREE = word('free')
295
+ const testOrder = (a, b) => {
296
+ const group = (t) => (AUTO.test(t.model) ? 0 : FREE.test(t.model) ? 1 : 2)
297
+ return group(a) - group(b) || a.model.localeCompare(b.model, undefined, { sensitivity: 'base' })
298
+ }
278
299
  // Never throws: { ok, ms, reply } or { ok: false, ms, status, error }; { stopped } when stop
279
300
  // (a run's Stop) cancels it.
280
301
  async function tryOne({ provider, model }, stop) {
@@ -286,12 +307,12 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
286
307
  const signal = stop ? AbortSignal.any([AbortSignal.timeout(testWait()), stop]) : AbortSignal.timeout(testWait())
287
308
  const r = await c.chat({ messages: [{ role: 'user', content: prompt('tests/hello') }], stream: true }, { signal })
288
309
  const reply = (r.content || '').trim()
289
- 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)` : ''}` }
290
311
  const ms = Date.now() - t0
291
- 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))) }
292
313
  } catch (e) {
293
314
  if (stop?.aborted) return { stopped: true }
294
- 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) }) }
295
316
  }
296
317
  }
297
318
  // A model that says it calls tools: can it do work with one? One of HeartCode's own tools and a
@@ -311,7 +332,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
311
332
  }
312
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)}` }
313
334
  } catch (e) {
314
- 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
315
337
  return { toolsOk: false, toolsWhy: `a request with tools failed: ${whyFailed(e)}` }
316
338
  }
317
339
  }
@@ -324,13 +346,14 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
324
346
  emit('tested', { key, result })
325
347
  return result
326
348
  }
327
- // The run going now: every provider at once, and from each a few models at a time: one per 100
328
- // models being tested (100: one at a time, 200: two…). A provider that says it's busy (429)
329
- // isn't a result about the model: that provider goes down to one at a time and pauses (as long
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",
350
+ // then "free", then the rest). A provider that says it's busy (429)
351
+ // isn't a result about the model: that provider pauses (as long
330
352
  // as it asks, else 15s, 30s… up to 2 minutes), and the model is tried again later; it's kept as
331
353
  // a 429 only after the provider refused it RATE_TRIES times. A model taken off your list while
332
354
  // it runs isn't tested. Stop: each provider finishes the one it's on.
333
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
334
357
  let run = null
335
358
  const runState = () => ({
336
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,
@@ -340,24 +363,29 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
340
363
  let mineOf = { then: undefined, model: undefined, keys: null }
341
364
  const inMine = (key) => {
342
365
  if (mineOf.then !== cfg.rotation?.then || mineOf.model !== cfg.model || mineOf.provider !== cfg.provider)
343
- 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}`)) }
344
367
  return mineOf.keys.has(key)
345
368
  }
346
369
  const wait = (ms) => new Promise((r) => setTimeout(r, ms))
347
370
  async function startRun(list, some) {
348
- const each = Math.max(AT_ONCE, Math.ceil(list.length / 100))
349
- 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() }
350
373
  emit('testrun', runState())
351
374
  for (const t of list) {
352
- 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() })
353
376
  run.providers.get(t.provider).queue.push(t)
354
377
  }
378
+ for (const p of run.providers.values()) p.queue.sort(testOrder)
355
379
  const ticker = setInterval(() => run && Object.keys(runState().paused).length && emit('testrun', runState()), 1000) // the pauses counting down
356
- // a provider's worker n: its next model, while there's one and n is under its cap (a busy
357
- // provider's cap goes down to one: the others stop; the last one left never does)
358
- 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) => {
359
387
  const p = run.providers.get(provider)
360
- while (!run.stopping && p.queue.length && (n < p.cap || p.live === 1)) {
388
+ while (!run.stopping && p.queue.length) {
361
389
  if (p.until > Date.now()) {
362
390
  await wait(Math.min(200, p.until - Date.now()))
363
391
  continue
@@ -370,26 +398,29 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
370
398
  emit('testrun', runState())
371
399
  continue
372
400
  }
373
- 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)
374
407
  const sent = Date.now()
375
408
  run.now.add(`${t.provider} ${t.model}`) // the models being tested this moment, for the page
376
409
  emit('testrun', runState())
377
- const r = await tryOne(t, run.cancel.signal)
410
+ const r = await tryOne(t, run.cancel.signal).finally(free)
378
411
  run.now.delete(`${t.provider} ${t.model}`)
379
412
  if (r.stopped) break // Stop: not a result (its last one stays)
380
- run.busy.get(provider) > 1 ? run.busy.set(provider, run.busy.get(provider) - 1) : run.busy.delete(provider)
413
+ run.busy.delete(provider)
381
414
  if (r.status === 429) {
382
415
  const times = (p.refused.get(key) ?? 0) + 1
383
416
  p.refused.set(key, times)
384
- p.cap = 1
385
- // a pause, longer each time; not for refusals of requests sent before the last pause began
386
- // (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
387
418
  if (!(sent < p.pausedAt)) {
388
419
  p.pausedAt = Date.now()
389
420
  p.until = Date.now() + Math.min(120_000, r.retryAfter > 0 ? r.retryAfter * 1000 : p.backoff)
390
421
  p.backoff = Math.min(120_000, p.backoff * 2)
391
422
  }
392
- 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` : ''}`)
393
424
  if (times < RATE_TRIES) {
394
425
  p.queue.push(t)
395
426
  emit('testrun', runState())
@@ -403,11 +434,9 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
403
434
  if (r.ok) run.good++
404
435
  emit('testrun', runState())
405
436
  }
406
- p.live--
407
437
  }
408
- for (const p of run.providers.values()) p.live = Math.min(each, p.queue.length)
409
438
  try {
410
- 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)))
411
440
  } finally {
412
441
  clearInterval(ticker)
413
442
  const over = { ...runState(), over: true }
@@ -419,21 +448,25 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
419
448
 
420
449
  const keyOf = (t) => `${t.provider}/${t.model}`
421
450
 
422
- // Helpers picked from what's known: every model of yours (#1 too) that answered its test and whose
423
- // provider is on, each with the jobs it's good at (at least one): UI & visuals and Code &
424
- // logic when it's in the top half of LMArena's web-app or coding ranking; Big & hard when it thinks
425
- // with a big context, or is in the top half of its agent (long real tasks) or hardest-prompts ranking; Quick & cheap when its test was faster than most (or it's good at none of the
426
- // others). have: picks already made (a job a model has isn't picked again). { key: [jobs] }.
451
+ // Helpers picked from what's known: every model of yours (#1 too) whose provider is on and that
452
+ // didn't fail its test, each with the jobs it's good at: UI & visuals and Code & logic when it's in
453
+ // the top half of LMArena's web-app or coding ranking; Big & hard when it thinks with a big context,
454
+ // or is in the top half of its agent (long real tasks) or hardest-prompts ranking; Quick & cheap when
455
+ // its test was faster than most (a tested model good at none of the others: that). A model not
456
+ // tested and good at none isn't picked. have: picks already made (a job a model has isn't picked
457
+ // again). { key: [jobs] }.
427
458
  const pickHelpers = (have = {}) => {
428
459
  const ranked = loadRankings()
429
460
  const order = [{ provider: cfg.provider, model: cfg.model }, ...rotationOf(cfg).then]
430
- const pool = order.map((t) => ({ ...t, can: testedOf(t), test: tests[keyOf(t)] })).filter((t) => !cfg.providers[t.provider]?.off && t.test?.ok && t.test.ms != null) // without tool calls too: a helper then works in guided mode
461
+ const pool = order.map((t) => ({ ...t, can: testedOf(t), test: tests[keyOf(t)] })).filter((t) => cfg.providers[t.provider] && !cfg.providers[t.provider].off && !(t.test && !t.test.ok)) // without tool calls too: a helper then works in guided mode
462
+ const ran = (t) => t.test?.ok && t.test.ms != null
431
463
  const top = (t, list) => ((x) => Boolean(x && x.rank / x.of <= 0.5))(rankIn(t.model, list, ranked))
432
- const times = pool.map((t) => t.test.ms).sort((x, y) => x - y)
464
+ const times = pool.filter(ran).map((t) => t.test.ms).sort((x, y) => x - y)
433
465
  const fast = times[Math.floor((times.length - 1) / 2)] // the middle time: faster than that is quick
434
- const picks = Object.fromEntries(pool.map((t) => {
435
- 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', t.test.ms <= fast && 'quick'].filter(Boolean)
436
- return [keyOf(t), jobs.length ? jobs : ['quick']]
466
+ const picks = Object.fromEntries(pool.flatMap((t) => {
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)
469
+ return jobs.length ? [[keyOf(t), jobs]] : ran(t) ? [[keyOf(t), ['quick']]] : []
437
470
  }))
438
471
  const out = {}
439
472
  for (const [k, jobs] of Object.entries(picks)) {
@@ -453,6 +486,13 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
453
486
  return true
454
487
  }
455
488
 
489
+ // its track record (record.js), rounded: { done, failed, poor } (poor: it doesn't start a message)
490
+ const recordView = (t) => {
491
+ const r = recordOf(t)
492
+ return r && { done: Math.round(r.good), failed: Math.round(r.bad), poor: unreliable(t) }
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]
456
496
  const state = (ranked = loadRankings()) => ({
457
497
  providers: Object.entries(byName(cfg.providers))
458
498
  .filter(([n]) => n !== cfg.adhoc)
@@ -461,11 +501,11 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
461
501
  model: cfg.model ?? null,
462
502
  version: VERSION,
463
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
464
- 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) })),
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 })),
465
506
  rankings: ranked && { fetched: ranked.fetched, source: ranked.source },
466
507
  rotation: (({ then, ...opts }) => opts)(rotationOf(cfg)),
467
508
  helpers: helpersOf(cfg.helpers), // { 'provider/model': [jobs] }
468
- helperOrder: cfg.helperOrder === 'provider' || cfg.helperOrder === 'own' ? cfg.helperOrder : 'score', // the order helpers are picked in: by their rankings (the default), your list's, or your provider ranking's
469
509
  helpersAuto: cfg.helpersAuto === true, // picked for you (pickHelpers), again whenever what's known changes: the models #1 may start as helpers, and what you picked each for
470
510
  jobs: HELPER_JOBS,
471
511
  settings: { permissions: cfg.permissions ?? 'all', effort: cfg.effort ?? 'default', theme: cfg.theme ?? 'dark', context: cfg.context ?? null, ...Object.fromEntries(Object.keys(TOGGLES).map((k) => [k, cfg[k] !== false])), logs: kindsOn(cfg), logDetail: cfg.logDetail === 'summary' ? 'summary' : 'full', logDays: logDays(cfg), testTimeout: testWaitOf(cfg), ...speedOf(cfg) },
@@ -474,9 +514,11 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
474
514
  statusBar: cfg.statusBar === undefined ? null : cfg.statusBar, // false (off), a list of lines, or null (default)
475
515
  // Telegram notifications: never the token itself, only a hint of it
476
516
  telegram: (({ token, bot, chatName, chatId, on, events } = {}) => ({ hint: tokenHint(token), bot: bot ?? null, chatName: chatName ?? null, connected: Boolean(token && chatId), on: on !== false, events: Object.fromEntries(Object.keys(EVENTS).map((k) => [k, events?.[k] !== false])), names: EVENTS }))(cfg.telegram),
517
+ // this computer: a sound and/or a desktop notification, off until switched on (alert.js)
518
+ alerts: { sound: Boolean(cfg.alerts?.sound), popup: Boolean(cfg.alerts?.popup), events: Object.fromEntries(ALERT_EVENTS.map((k) => [k, cfg.alerts?.events?.[k] !== false])) },
477
519
  search: { ...(({ searxng, order, off }) => ({ searxng, order, off }))(searchSettings()), names: ENGINE_NAMES }, // web search: your SearXNG, the engines' order and switches
478
520
  capabilities: capabilities(cfg), // features that need outside tools, and whether they're here
479
- choices: { permissions: PERMISSIONS, effort: EFFORTS, theme: Object.keys(THEMES), toggles: TOGGLES, statusItems: STATUS_ITEMS, logKinds: Object.fromEntries(Object.entries(LOG_KINDS).map(([k, { label, about }]) => [k, { label, about }])) },
521
+ choices: { permissions: PERMISSIONS, effort: EFFORTS, theme: Object.keys(THEMES), toggles: TOGGLES, statusItems: STATUS_ITEMS, logKinds: Object.fromEntries(Object.entries(LOG_KINDS).map(([k, { label, about }]) => [k, { label, about, ...LOG_SAMPLES[k] }])), logSamples: LOG_SAMPLES },
480
522
  files: FILES.map(([name, about, json, example]) => ({ name, about, json, example, text: fs.existsSync(path.join(HOME, name)) ? fs.readFileSync(path.join(HOME, name), 'utf8') : '' })),
481
523
  skills: [...loadSkills(null).values()].map((s) => ({ name: s.name, description: s.description, use: s.use, mine: s.file.startsWith(skillsDir() + path.sep), text: fs.readFileSync(s.file, 'utf8'), path: tilde(path.basename(s.file) === 'SKILL.md' ? path.dirname(s.file) : s.file), files: skillFiles(s) })), // a folder skill: its other files (guides, assets)
482
524
  mcp: mcpServers(),
@@ -505,9 +547,10 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
505
547
  name = safeName(name)
506
548
  if (!name) throw new Error('a name is needed')
507
549
  baseUrl = String(baseUrl ?? '').trim()
550
+ if (/^cli:/i.test(baseUrl) && !cliOf(baseUrl)) throw new Error(`"${baseUrl}": no such CLI`)
508
551
  // an address without http(s)://: whichever of the two the server answers on (any answer, even
509
552
  // a 401, means it's there), https first
510
- 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)
511
554
  try {
512
555
  if (!new URL(baseUrl).hostname) throw new Error()
513
556
  } catch {
@@ -517,17 +560,44 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
517
560
  const old = cfg.providers[was ?? name]
518
561
  const key = keepKey ? old?.apiKey : String(apiKey ?? '').trim() || undefined
519
562
  if (was && was !== name) {
563
+ if (cfg.providers[name]) throw new Error(`there's a provider named "${name}" already`)
520
564
  delete cfg.providers[was]
521
565
  if (cfg.provider === was) cfg.provider = name
522
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)
523
575
  }
524
576
  cfg.providers[name] = { ...old, baseUrl, apiKey: key } // its list switch and added models stay
525
577
  if (!key) delete cfg.providers[name].apiKey
526
578
  forgetList(name, ...(was ? [was] : [])) // a new URL or key: its models asked for again
527
579
  save('model')
528
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()
529
598
  return state()
530
599
  },
600
+ 'POST /api/cli/install': ({ id }) => (installCli(id, () => emit('clis', {})), clisInfo()),
531
601
  'POST /api/provider/delete': ({ name }) => {
532
602
  if (!cfg.providers[name]) throw new Error(`no provider "${name}"`)
533
603
  delete cfg.providers[name]
@@ -540,6 +610,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
540
610
  }
541
611
  save('model')
542
612
  forgetTests()
613
+ autoPick()
543
614
  return state()
544
615
  },
545
616
  // a provider's models, and what's known about each (for the page's tooltip): what the provider
@@ -559,16 +630,22 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
559
630
  },
560
631
  // A provider switched off: kept (its key, its models in your list), but HeartCode skips its models
561
632
  // until it's on again.
562
- 'POST /api/provider/on': ({ name, on }) => {
563
- if (!cfg.providers[name]) throw new Error(`no provider "${name}"`)
564
- if (on) delete cfg.providers[name].off
565
- else cfg.providers[name].off = true
566
- 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()
567
643
  return state()
568
644
  },
569
- // A model added by its name (one the provider doesn't list, or its list is off): remembered.
645
+ // A model added by its name (one the provider doesn't list, or its list is off): remembered under
646
+ // the provider, not put in the list (clicked there, it is). models: several at once.
570
647
  // all: every model added by name forgotten at once
571
- 'POST /api/provider/added': ({ name, model, remove, all }) => {
648
+ 'POST /api/provider/added': ({ name, model, models, remove, all }) => {
572
649
  const p = cfg.providers[name]
573
650
  if (!p) throw new Error(`no provider "${name}"`)
574
651
  if (all) {
@@ -576,6 +653,13 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
576
653
  save('provider')
577
654
  return state()
578
655
  }
656
+ if (Array.isArray(models)) {
657
+ const add = models.map((m) => String(m ?? '').trim()).filter(Boolean)
658
+ if (!add.length) throw new Error('a model is needed')
659
+ p.models = [...new Set([...(p.models ?? []), ...add])]
660
+ save('provider')
661
+ return state()
662
+ }
579
663
  model = String(model ?? '').trim()
580
664
  if (!model) throw new Error('a model is needed')
581
665
  const rest = (p.models ?? []).filter((m) => m !== model)
@@ -618,7 +702,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
618
702
  'POST /api/model': ({ provider, model }) => {
619
703
  if (!cfg.providers[provider]) throw new Error(`no provider "${provider}"`)
620
704
  if (!String(model ?? '').trim()) throw new Error('a model is needed')
621
- Object.assign(cfg, { provider, model: String(model).trim() })
705
+ Object.assign(cfg, { provider, model: String(model).trim(), pinned: undefined }) // saved, also from a run given -m (config.js saved)
622
706
  if (cfg.rotation?.then) cfg.rotation.then = cfg.rotation.then.filter((t) => t.provider !== provider || t.model !== cfg.model) // #1 now, not also further down
623
707
  save('model')
624
708
  test([{ provider, model: cfg.model }])
@@ -633,8 +717,15 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
633
717
  if (!autoPick()) save('setting:helpersAuto')
634
718
  return { helpers: helpersOf(cfg.helpers), helpersAuto: cfg.helpersAuto === true }
635
719
  },
636
- // Suggest helpers: what would be picked, beside what you have (nothing saved)
637
- 'POST /api/helpers/suggest': () => ({ suggest: pickHelpers(helpersOf(cfg.helpers)) }),
720
+ // Update model info, with your picks: the helpers picked from what's known now, added to yours
721
+ // (saved; what you picked stays). marked: how many models got a job they didn't have
722
+ 'POST /api/helpers/mark': () => {
723
+ const add = pickHelpers(helpersOf(cfg.helpers))
724
+ const next = { ...helpersOf(cfg.helpers) }
725
+ for (const [k, jobs] of Object.entries(add)) next[k] = [...new Set([...(next[k] ?? []), ...jobs])]
726
+ if (Object.keys(add).length) (cfg.helpers = next), save('setting:helpers')
727
+ return { helpers: helpersOf(cfg.helpers), helpersAuto: cfg.helpersAuto === true, marked: Object.keys(add).length }
728
+ },
638
729
  'POST /api/helpers': ({ helpers }) => {
639
730
  if (!helpers || typeof helpers !== 'object') throw new Error('helpers: an object')
640
731
  cfg.helpersAuto = undefined // your own picks now
@@ -644,15 +735,6 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
644
735
  save('setting:helpers')
645
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
646
737
  },
647
- // the order helpers are picked in: 'score' (the default: best placed in LMArena's rankings first),
648
- // 'own' (your list's) or 'provider' (your provider ranking's, each provider's in your list's order;
649
- // rank: the ranking as the page has it, kept for HeartCode to use)
650
- 'POST /api/helper-order': ({ by, rank }) => {
651
- cfg.helperOrder = by === 'provider' || by === 'own' ? by : undefined
652
- cfg.providerRank = cfg.helperOrder === 'provider' ? (Array.isArray(rank) ? rank.filter((x) => typeof x === 'string') : readJson(PREFS, {}).rank) : undefined
653
- save('setting:helperOrder')
654
- return { helperOrder: cfg.helperOrder ?? 'score' }
655
- },
656
738
  // the model list, in order (#1 is the model), and when to go on to the next
657
739
  'POST /api/order': ({ list, on, retries, next }) => {
658
740
  if (!Array.isArray(list)) throw new Error('a list of models is needed')
@@ -669,8 +751,15 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
669
751
  if (!Number.isInteger(opts.retries) || opts.retries < 1 || opts.retries > 20) throw new Error('tries before moving on: 1 to 20')
670
752
  if (!ROTATION.next.includes(opts.next)) throw new Error(`a new message starts with: ${ROTATION.next.join(', ')}`)
671
753
  // an empty list: no model (HeartCode says so until one is chosen)
754
+ // one taken off the list that its provider doesn't list (added by name): kept under the provider
755
+ const kept = new Set(clean.map((t) => `${t.provider}/${t.model}`))
756
+ for (const t of [{ provider: cfg.provider, model: cfg.model }, ...(cfg.rotation?.then ?? [])]) {
757
+ const p = cfg.providers[t.provider]
758
+ if (!p || !t.model || kept.has(`${t.provider}/${t.model}`) || readLists()[t.provider]?.models?.includes(t.model) || p.models?.includes(t.model)) continue
759
+ p.models = [...(p.models ?? []), t.model]
760
+ }
672
761
  const changed1 = cfg.provider !== clean[0]?.provider || cfg.model !== clean[0]?.model
673
- Object.assign(cfg, { provider: clean[0]?.provider, model: clean[0]?.model })
762
+ Object.assign(cfg, { provider: clean[0]?.provider, model: clean[0]?.model, pinned: undefined }) // a new #1 chosen here is saved, also from a run given -m (config.js saved)
674
763
  cfg.rotation = { on: opts.on, retries: opts.retries, next: opts.next, then: clean.slice(1) }
675
764
  ownWrite = Date.now()
676
765
  saveConfig(cfg)
@@ -717,11 +806,11 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
717
806
  // a run: all your models, or the ones given (only); one at a time if one is going already
718
807
  'POST /api/tests/start': ({ only } = {}) => {
719
808
  if (run) throw new Error('a test is running: wait for it, or stop it')
720
- const order = state().order
809
+ const order = orderOf()
721
810
  const mine = new Set(order.map((t) => `${t.provider}/${t.model}`))
722
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 }))
723
812
  if (!list.length) throw new Error('no model to test')
724
- 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
725
814
  return { run: { ...runState(), pending: [...run.pending] } }
726
815
  },
727
816
  'POST /api/tests/stop': () => {
@@ -730,7 +819,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
730
819
  },
731
820
  'POST /api/models-dev': async ({ provider, model } = {}) => {
732
821
  await loadPrices({ force: true })
733
- 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()
734
823
  let found = 0
735
824
  for (const t of list) {
736
825
  const c = clientFor(t)
@@ -743,6 +832,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
743
832
  testNews(`${t.provider}/${t.model}`, t)
744
833
  }
745
834
  changed('profile')
835
+ autoPick() // picked for you: what models.dev says each can do counts
746
836
  return { ...state(), found, of: list.length }
747
837
  },
748
838
  // What a model can do, set by you (a model models.dev doesn't know, or to correct it): its
@@ -757,7 +847,12 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
757
847
  for (const [k, v] of Object.entries({ tools, thinking, images, stream })) if (typeof v !== 'boolean') throw new Error(`${k}: yes or no`)
758
848
  await loadPrices()
759
849
  const p = loadProfile(c) ?? profileFrom(c, limitsOf(t.provider, c.baseUrl, t.model))
760
- 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
761
856
  if (p.source === 'assumed') p.source = 'you'
762
857
  writeJson(profilePath(c), p)
763
858
  changed('profile')
@@ -858,6 +953,25 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
858
953
  save('setting:telegram')
859
954
  return state()
860
955
  },
956
+ 'POST /api/alerts/set': ({ sound, popup, event, value }) => {
957
+ const a = { ...cfg.alerts }
958
+ if (typeof sound === 'boolean') a.sound = sound
959
+ if (typeof popup === 'boolean') a.popup = popup
960
+ if (event !== undefined) {
961
+ if (!ALERT_EVENTS.includes(event) || typeof value !== 'boolean') throw new Error(`event: ${ALERT_EVENTS.join(', ')}, on or off`)
962
+ a.events = { ...a.events, [event]: value }
963
+ }
964
+ cfg.alerts = a
965
+ save('setting:alerts')
966
+ return state()
967
+ },
968
+ // what each event sounds and looks like, whatever is switched on
969
+ 'POST /api/alerts/test': ({ event }) => {
970
+ if (!ALERT_EVENTS.includes(event)) throw new Error(`event: ${ALERT_EVENTS.join(', ')}`)
971
+ const texts = { done: '✅ Done · a test from the settings', failed: '❌ Failed · a test from the settings', waiting: '⏳ Waiting for an answer · a test from the settings' }
972
+ alert({ alerts: { sound: true, popup: Boolean(cfg.alerts?.popup), events: {} } }, event, texts[event])
973
+ return state()
974
+ },
861
975
  'POST /api/telegram/remove': () => {
862
976
  cfg.telegram = undefined
863
977
  save('setting:telegram')
@@ -1071,7 +1185,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1071
1185
 
1072
1186
  // Settings changed by anyone else (another HeartCode or page on this folder, a hand): taken in, and
1073
1187
  // every open page shown them at once (an event: the whole state, when it's different)
1074
- 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)
1075
1189
  let shown = ''
1076
1190
  const pushState = () => {
1077
1191
  for (const what of new Set(takeIn(cfg).map(whatOf))) changed(what)
@@ -1085,6 +1199,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1085
1199
  const w = fs.watch(HOME, { recursive: true }, (_, f) => {
1086
1200
  if (!SETTINGS_FILES.includes(String(f ?? '').split(path.sep)[0])) return
1087
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
1088
1203
  clearTimeout(pending)
1089
1204
  pending = setTimeout(pushState, 150) // a file written in parts, several at once: one look
1090
1205
  })
@@ -1134,20 +1249,22 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1134
1249
  return new Promise((resolve, reject) => {
1135
1250
  server.on('error', reject)
1136
1251
  forgetTests() // results of models no longer yours, left from before
1137
- 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', () => {
1138
1256
  const at = (host) => `http://${host}:${server.address().port}/?t=${token}`
1139
1257
  const local = at('127.0.0.1') // for a browser on this machine
1140
- const ssh = process.env.SSH_CONNECTION?.split(' ')[2] // over SSH: the address you reached this machine at
1141
- 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
1142
1259
  log('web', `settings page at ${new URL(url).host}`)
1143
1260
  // models.dev's list (its sizes for your models, whether their providers' lists are on or not):
1144
1261
  // loaded now, and your models' lines brought up to date when it's in
1145
1262
  loadPrices().then(() => {
1146
- for (const t of state().order) testNews(`${t.provider}/${t.model}`, t)
1147
- 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
1148
1265
  warm()
1149
1266
  })
1150
- 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
1151
1268
  })
1152
1269
  })
1153
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('─')]