heartcode 0.1.60 → 0.1.63

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/mcp.js CHANGED
@@ -9,7 +9,6 @@
9
9
  // list it gave the last time it ran (kept in ~/.heart/mcp-tools.json, with its instructions): so a
10
10
  // server starts the first time the model uses it, or once to say its tools; it stops when
11
11
  // HeartCode exits.
12
- import { spawn } from 'node:child_process'
13
12
  import crypto from 'node:crypto'
14
13
  import fs from 'node:fs'
15
14
  import os from 'node:os'
@@ -17,7 +16,9 @@ import path from 'node:path'
17
16
  import { pathToFileURL } from 'node:url'
18
17
  import { HOME, readJson, readConfig, writeJson, VERSION } from './config.js'
19
18
  import { log } from './log.js'
19
+ import { spawnCmd, killTree } from './spawn.js'
20
20
  import { savedToken, signIn, hasToken } from './oauth.js'
21
+ import { fetch } from './http.js' // not the built-in one: see http.js
21
22
 
22
23
  // Built in: none. HeartCode comes with no MCP servers; you add the ones you want (/settings → MCP
23
24
  // servers, /mcp, or ~/.heart/mcp.json). Kept as a map so a server could be built in again by name.
@@ -153,7 +154,7 @@ class Server {
153
154
  const { command, args = [], env = {} } = this.cfg
154
155
  log('mcp', `starting ${this.name}: ${command} ${args.join(' ')}`)
155
156
  const cwd = this.cfg.scratchCwd ? scratchDir(this.root, this.name) : (this.root ?? undefined) // in the project, so a relative path in its config works; a browser gets a scratch dir instead
156
- const child = (this.child = spawn(command, args, { cwd, env: { ...process.env, ...env }, stdio: ['pipe', 'pipe', 'pipe'], detached: process.platform !== 'win32' }))
157
+ const child = (this.child = spawnCmd(command, args, { cwd, env: { ...process.env, ...env }, stdio: ['pipe', 'pipe', 'pipe'], detached: process.platform !== 'win32' }))
157
158
  let buf = ''
158
159
  child.stdout.setEncoding('utf8') // a character split between two chunks stays whole
159
160
  child.stdout.on('data', (d) => {
@@ -349,10 +350,7 @@ class Server {
349
350
  return
350
351
  }
351
352
  if (!this.child) return
352
- try {
353
- if (this.child.pid && process.platform !== 'win32') process.kill(-this.child.pid, 'SIGTERM')
354
- else this.child.kill()
355
- } catch {}
353
+ if (!killTree(this.child.pid)) try { this.child.kill() } catch {}
356
354
  this.child = null
357
355
  this.ready = null
358
356
  this.#failAll(new Error(`${this.name} was stopped`)) // calls waiting on it fail now (its exit comes later, ignored)
package/src/oauth.js CHANGED
@@ -8,6 +8,7 @@ import path from 'node:path'
8
8
  import { createHash, randomBytes } from 'node:crypto'
9
9
  import { HOME, readJson, writeJson } from './config.js'
10
10
  import { log } from './log.js'
11
+ import { fetch } from './http.js' // not the built-in one: see http.js
11
12
 
12
13
  const FILE = path.join(HOME, 'mcp-auth.json')
13
14
  const b64url = (buf) => Buffer.from(buf).toString('base64url')
package/src/rankings.js CHANGED
@@ -5,6 +5,7 @@ import path from 'node:path'
5
5
  import { HOME, readJson, writeJson } from './config.js'
6
6
  import { log } from './log.js'
7
7
  import { readParquet } from './parquet.js'
8
+ import { fetch } from './http.js' // not the built-in one: see http.js
8
9
 
9
10
  const FILE = path.join(HOME, 'rankings.json')
10
11
  const WEEK = 7 * 24 * 3600_000
@@ -96,3 +97,9 @@ export function rankIn(model, key, data) {
96
97
  const best = at.reduce((a, b) => (b.rank < a.rank ? b : a))
97
98
  return { rank: best.rank, of: list.length, as: best.name, score: best.score, votes: best.votes }
98
99
  }
100
+
101
+ // How good a model is, by its best share of the rankings that matter for coding work (coding, web
102
+ // apps, long real tasks, hard prompts): #5 of 200 is 0.025; lower is better, Infinity when it's in none
103
+ export function scoreOf(model, data = loadRankings()) {
104
+ return Math.min(...['text:coding', 'webdev:webdev', 'agent:overall', 'text:hard_prompts'].map((l) => rankIn(model, l, data)).filter(Boolean).map((r) => r.rank / r.of), Infinity)
105
+ }
package/src/settings.html CHANGED
@@ -582,11 +582,11 @@
582
582
  .mt-mode-sets .h-order select { height: 34px; }
583
583
  .mt-mode-sets .seg { height: 34px; }
584
584
  .mt-mode-sets .seg label { padding: 0 11px; font-size: 12.5px; }
585
- @media (min-width: 861px) and (max-width: 1400px) { .mt-mode-sets { column-gap: 6px; } .mt-mode-sets .seg label { padding: 0 7px; font-size: 12px; } .mt-div { margin: 0; } .mt-setc input[type=number], .mt-setc input.tries { width: 42px; } } /* a small laptop (1280): the settings stay on one line */
585
+ @media (min-width: 861px) and (max-width: 1400px) { .mt-mode-sets { column-gap: 6px; } .mt-mode-sets .seg label { padding: 0 7px; font-size: 12px; } .mt-div { margin: 0; } .mt-setc input[type=number], .mt-setc input.tries { width: calc(4ch + 18px); padding-inline: 6px; } } /* a small laptop (1280): the settings stay on one line */
586
586
  .mt-setc { display: flex; align-items: center; gap: 6px; }
587
587
  .mt-setc select { width: auto; min-width: 0; height: 34px; padding-top: 0; padding-bottom: 0; line-height: 32px; }
588
588
  .mt-setc input[type=number] { width: 50px; height: 34px; }
589
- .mt-setc input.tries { width: 50px; }
589
+ .mt-setc input.tries { width: calc(4ch + 24px); } /* up to 4 digits (Stalled goes to 1800) */
590
590
  .mt-setc input[type=number] { appearance: textfield; -moz-appearance: textfield; text-align: center; } /* typed: no spinner taking the digits' room */
591
591
  .mt-setc input[type=number]::-webkit-inner-spin-button, .mt-setc input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
592
592
  .mt-setc .unit { color: var(--muted); font-size: 13px; }
@@ -596,7 +596,7 @@
596
596
  .mt-row .f-search { flex: 1 1 140px; min-width: 130px; }
597
597
  .mt-line { display: flex; align-items: center; gap: 8px; flex: none; margin-left: auto; font-size: 13px; color: var(--muted); }
598
598
  .mt-line .count { white-space: nowrap; }
599
- .mt-sets[inert], .mt-row[inert], .mt-hwrap[inert], .mt-actions[inert] { opacity: .5; transition: opacity .15s; }
599
+ .mt-sets[inert], .mt-row[inert], .mt-hwrap[inert], .mt-actions[inert], .mt-actions > [inert] { opacity: .5; transition: opacity .15s; }
600
600
  .mt-line .count b { color: var(--text); }
601
601
  .mt-hpick .mt-pickbar { grid-column: 3 / -1; display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--text); }
602
602
  .mt-hpick { background: var(--brand-soft); }
@@ -676,6 +676,9 @@
676
676
  /* every other tooltip (titles): at once, the page's own look */
677
677
  #hint { position: fixed; z-index: 31; max-width: 340px; padding: 7px 10px; border-radius: 8px; background: var(--text); color: var(--bg); font-size: 12px; line-height: 1.45; box-shadow: var(--shadow-pop); pointer-events: none; opacity: 0; transition: opacity .06s; white-space: pre-line; }
678
678
  #hint.show { opacity: 1; }
679
+ /* a time limit moved to fit another one just set: flashes a moment */
680
+ .mt-sets input.moved { animation: moved 2.4s ease-out; }
681
+ @keyframes moved { 0%, 40% { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 35%, transparent); } 100% { box-shadow: none; } }
679
682
  .with-q { display: inline-flex; align-items: center; gap: 5px; }
680
683
  .q { display: inline-grid; place-items: center; width: 17px; height: 17px; border-radius: 50%; border: 1px solid var(--line); color: var(--muted); font-size: 11px; font-weight: 700; cursor: help; }
681
684
  .q:hover, .q:focus-visible { color: var(--text); border-color: var(--muted); outline: none; }
@@ -688,7 +691,7 @@
688
691
  #tip .tjob { font-weight: 650; font-size: 13.5px; }
689
692
  #tip .tcover { color: var(--muted); margin-top: 6px; line-height: 1.5; }
690
693
  #tip .thint { margin-top: 10px; padding-top: 8px; border-top: 1px solid var(--line); color: var(--accent); font-weight: 600; }
691
- #toast { position: fixed; bottom: 24px; left: 50%; transform: translate(-50%, 8px); padding: 10px 18px; border-radius: 12px; background: var(--text); color: var(--bg); font-weight: 500; box-shadow: var(--shadow-pop); opacity: 0; transition: opacity .2s, transform .2s; pointer-events: none; max-width: calc(100% - 32px); z-index: 10; }
694
+ #toast { position: fixed; bottom: 24px; left: 50%; transform: translate(-50%, 8px); padding: 10px 18px; border-radius: 12px; background: var(--text); color: var(--bg); font-weight: 500; box-shadow: var(--shadow-pop); opacity: 0; transition: opacity .2s, transform .2s; pointer-events: none; max-width: min(560px, calc(100% - 32px)); z-index: 10; white-space: pre-line; }
692
695
  #toast.show { opacity: 1; transform: translate(-50%, 0); }
693
696
  #toast.err { background: var(--err); color: #fff; }
694
697
  /* what's running (tests, loading): a strip at the top of the panel it's about, updated in place */
@@ -1344,12 +1347,12 @@ addEventListener('DOMContentLoaded', () => {
1344
1347
  const put = (el, ...kids) => el.replaceChildren(...kids.flat(Infinity).filter((x) => x != null && x !== false))
1345
1348
  let S = null
1346
1349
  let toastTimer
1347
- function toast(text, err = false) {
1350
+ function toast(text, err = false, ms = err ? 6000 : 2400) {
1348
1351
  const t = $('toast')
1349
1352
  t.textContent = text
1350
1353
  t.className = 'show' + (err ? ' err' : '')
1351
1354
  clearTimeout(toastTimer)
1352
- toastTimer = setTimeout(() => (t.className = ''), err ? 6000 : 2400)
1355
+ toastTimer = setTimeout(() => (t.className = ''), ms)
1353
1356
  }
1354
1357
  // What's running (a test, lists loading, models.dev), shown at the top of the panels it's about
1355
1358
  // while it runs: job(id, { what, where, done, total, detail, stop }) to show or update it (no total:
@@ -2474,7 +2477,7 @@ const dirText = (key, dir) => COLS[key].words[dir === 'up' ? 0 : 1] + (key === '
2474
2477
  // Filters on the Your models page: which models are shown (and tested by "Test N shown", counted,
2475
2478
  // sorted, selected by "select all", saved first by Save list). Combined: a model shows when it passes
2476
2479
  // all of them. Kept with the page's choices.
2477
- const NO_FILTER = { text: '', provider: '', works: '', context: 0, tools: false, thinking: false, images: false, free: false, helpers: false }
2480
+ const NO_FILTER = { text: '', provider: '', works: '', context: 0, tools: false, thinking: false, images: false, free: false }
2478
2481
  let FILTER = { ...NO_FILTER }
2479
2482
  let filtersLoaded = false
2480
2483
  const filtering = () => Object.keys(NO_FILTER).some((k) => FILTER[k] !== NO_FILTER[k])
@@ -2494,7 +2497,6 @@ function passes(t, skip) {
2494
2497
  const c = can(t)
2495
2498
  if ((f.tools && !c.tools) || (f.thinking && !c.thinking) || (f.images && !c.images)) return false
2496
2499
  if (f.free && !(t.price?.input === 0 && t.price?.output === 0)) return false
2497
- if (f.helpers && !helpers()[keyOf(t)] && !HSUG?.[keyOf(t)]) return false // and the ones suggested, while they are
2498
2500
  return true
2499
2501
  }
2500
2502
  const setFilter = (change) => {
@@ -2528,8 +2530,7 @@ function filterBarOf(order, counts = {}) {
2528
2530
  toggle('tools', 'Tools', 'only models that call tools', 'wrench'),
2529
2531
  toggle('thinking', 'Thinking', 'only models that think', 'bulb'),
2530
2532
  toggle('images', 'Images', 'only models that see images', 'image'),
2531
- toggle('free', 'Free', 'only models that cost nothing, in and out', 'tag'),
2532
- toggle('helpers', 'Helpers', 'only the helpers (the models #1 can start for side jobs), and the ones suggested', 'sparkles')))
2533
+ toggle('free', 'Free', 'only models that cost nothing, in and out', 'tag')))
2533
2534
  }
2534
2535
  const bar = filterBar
2535
2536
  const focused = (el) => document.activeElement === el
@@ -2566,10 +2567,10 @@ function drawMine(s) {
2566
2567
  const n = (x) => x.toLocaleString()
2567
2568
 
2568
2569
  // --- what you do to the list ---
2569
- // the order you see, saved as yours; the sort then goes (your own order from here on: drag on)
2570
+ // the order you see, saved as yours. Saved with Save list: the sort and filters stay as they are, so
2571
+ // the page looks the same next time. A row dragged: the sort goes (your own order from there on)
2570
2572
  const keep = (list, moved) => {
2571
- SORT = []
2572
- savePref('sorts', SORT)
2573
+ if (moved) (SORT = []), savePref('sorts', SORT)
2573
2574
  return saveOrder(withOff(list), list[0] !== order[0] ? `${moved ? '' : 'list saved: '}HeartCode now uses ${list[0].provider} · ${list[0].model}` : 'list saved')
2574
2575
  }
2575
2576
  // a row dragged (in the order shown, sorted or not). Filtered: it moves among the ones shown; the
@@ -2602,56 +2603,67 @@ function drawMine(s) {
2602
2603
  const pickedList = order.filter((t) => PICKED.has(keyOf(t)))
2603
2604
 
2604
2605
  // --- the page's header: how a model is picked (left), what's known about the models (right) ---
2605
- $('mt-lead').textContent = 'The models HeartCode uses, in order: #1 answers, the next one when it fails.'
2606
+ $('mt-lead').textContent = 'The models HeartCode uses: #1 answers; when a model fails, another takes over (the best-ranked one not tried yet). Hover a setting to see what it does.'
2606
2607
  const busy = locked()
2607
- $('mt-actions').inert = busy
2608
+ $('mt-actions').inert = false // Save list works at any time; the rest wait while something runs (below)
2608
2609
  // the order helpers are picked in when #1 starts them: your list's, or your provider ranking's
2609
2610
  const helperOrder = (by) => api('/api/helper-order', { by, rank: RANK }).then((r) => ((S.helperOrder = r.helperOrder), drawMine(S)), (e) => toast(e.message, true))
2610
2611
  // who chooses the helpers: HeartCode (from the tests and the rankings, again when those change) or you
2611
- const chooser = h('label', { className: 'h-order', title: 'Automatic: HeartCode chooses the helpers and what each is for, from the models that answered their test and the rankings, and again whenever those change. Manual: switched on and given their jobs by hand in the Helper column.' },
2612
+ const chooser = h('label', { className: 'h-order', title: 'Helpers\nWho picks the helpers: the models #1 can hand side jobs to (looking at a screenshot, a review, a part of the plan).\n\nAutomatic: HeartCode picks them, and what each is for, from the tests and the rankings, and picks again when those change.\nManual: you switch them on, and pick their jobs, in the Helper column.' },
2612
2613
  h('span', { className: 'mt-setl' }, ic('sparkles'), h('span', { className: 'lt', textContent: 'Helpers' })),
2613
2614
  h('select', { id: 'h-auto', onchange: (e) => setAuto(e.target.value === 'auto', e.target) },
2614
2615
  [['auto', 'Automatic'], ['manual', 'Manual']].map(([v, t]) => h('option', { value: v, textContent: t, selected: (S.helpersAuto ? 'auto' : 'manual') === v }))))
2615
- const orderBy = h('span', { className: 'h-order', title: 'Used: the order #1 takes helpers in' }, h('span', { className: 'mt-setl' }, ic('bars'), h('span', { className: 'lt', textContent: 'Used' })),
2616
+ const orderBy = h('span', { className: 'h-order', title: 'Used\nWhich helper #1 takes first when several fit a job.\n\nBy score: the best-ranked in public rankings (the default).\nIn list order: the first in your list.\nBy provider: by your provider ranking (Order providers).' }, h('span', { className: 'mt-setl' }, ic('bars'), h('span', { className: 'lt', textContent: 'Used' })),
2616
2617
  h('div', { className: 'seg', role: 'radiogroup', 'aria-label': 'The order helpers are used in' },
2617
2618
  [['own', 'in list order', 'when #1 starts a helper, it takes the first one that fits the job, in the list\'s order'], ['provider', 'by provider', 'when #1 starts a helper, it takes them by the provider ranking (Order providers), each provider\'s in the list\'s order. The list itself stays as it is'], ['score', 'by score', 'when #1 starts a helper, it takes the best ranked first: its best place in LMArena\'s public rankings for coding, web apps, long real tasks and hard prompts (Update model info). Models not ranked come after, in the list\'s order']].map(([v, t, about]) =>
2618
- h('label', { className: (S.helperOrder ?? 'own') === v ? 'on' : '', title: about },
2619
- h('input', { type: 'radio', name: 'helper-order', checked: (S.helperOrder ?? 'own') === v, disabled: v === 'provider' && !order.some((t) => t.provider !== order[0]?.provider), onchange: () => helperOrder(v) }), t))))
2619
+ h('label', { className: (S.helperOrder ?? 'score') === v ? 'on' : '', title: about },
2620
+ h('input', { type: 'radio', name: 'helper-order', checked: (S.helperOrder ?? 'score') === v, disabled: v === 'provider' && !order.some((t) => t.provider !== order[0]?.provider), onchange: () => helperOrder(v) }), t))))
2620
2621
  put($('mt-actions'),
2621
2622
  ((why) => h('span', { title: why ?? '' }, h('button', { className: 'small', textContent: 'Order providers', disabled: Boolean(why), title: why ? '' : 'drag the providers into order; the Provider column sorts by it', onclick: openRanking })))( // disabled: why, on a span (a disabled button shows no tooltip in every browser)
2622
2623
  !order.some((t) => t.provider !== order[0]?.provider) ? 'All the models are from one provider: nothing to order' : null),
2623
2624
  h('button', { className: 'small', textContent: 'Update model info', disabled: !order.length, title: `what each model can do (context, tools, thinking, images, price) from models.dev, and its places in LMArena's public rankings (coding, web apps, vision${S.rankings ? `; rankings from ${new Date(S.rankings.fetched).toLocaleDateString()}` : ''})`, onclick: () => lookUp() }),
2624
2625
  h('button', { className: 'small', textContent: filtered ? `Test ${n(shown.length)}` : 'Test all', disabled: testingAll || !shown.length, title: `send ${filtered ? 'the models shown' : 'each model'} a short message to see which really answer, and how fast`, onclick: () => tryAll(filtered ? shown : order) }),
2625
- // not on the helpers' view: they're not a list to keep only
2626
- filtered && FILTER.helpers ? null : h('button', { className: 'small primary', textContent: filtered ? `Use only these ${n(view.length)}` : 'Save list', disabled: !view.length || order.length < 2, title: filtered ? `HeartCode uses only these ${n(view.length)}, in the order shown (the others stay under Providers)` : 'save the list as shown: HeartCode uses them in this order (#1 first)', onclick: saveList }))
2626
+ // always there: the list as it's shown (sorted, filtered), saved whenever
2627
+ h('button', { className: 'small primary', textContent: filtered ? `Use only these ${n(view.length)}` : 'Save list', disabled: !view.length, title: filtered ? `HeartCode uses only these ${n(view.length)}, in the order shown (the others stay under Providers)` : 'save the list as shown: HeartCode uses them in this order (#1 first)', onclick: saveList }))
2628
+ for (const b of $('mt-actions').children) if (!b.classList.contains('primary')) b.inert = busy // all but Save list wait while something runs
2627
2629
 
2628
2630
  // --- row 2, the list's settings: when a model fails (left), the helpers (right); an icon and a short label each ---
2629
2631
  const ro = s.rotation
2630
- const cell = (icon, label, about, ...control) => h('label', { className: 'mt-set', title: `${label}: ${about}` }, h('span', { className: 'mt-setl' }, ic(icon), h('span', { className: 'lt', textContent: label })), h('span', { className: 'mt-setc' }, ...control))
2632
+ // about: its tooltip, in plain words (the label is its first line)
2633
+ const cell = (icon, label, about, ...control) => h('label', { className: 'mt-set', title: `${label}\n${about}` }, h('span', { className: 'mt-setl' }, ic(icon), h('span', { className: 'lt', textContent: label })), h('span', { className: 'mt-setc' }, ...control))
2631
2634
  // a whole number setting (seconds), with its limits from the server (SPEED_LIMITS)
2632
2635
  const LIMITS = { replyStart: [5, 600], replyIdle: [10, 1800] }
2633
- const num = (name, label, said) => h('input', { type: 'number', className: 'tries', 'aria-label': label, min: LIMITS[name][0], max: LIMITS[name][1], value: S.settings[name], onchange: (e) => {
2636
+ // a time limit saved; the ones that depend on it (Give up, Stalled, Tests wait) may move to fit: said
2637
+ // for longer, and the boxes that moved flash
2638
+ const saveTime = async (name, v, said) => {
2639
+ const r = await act('/api/setting', { name, value: v })
2640
+ if (!r) return
2641
+ if (!r.notes?.length) return toast(said)
2642
+ toast([said, ...r.notes.map((x) => x.text)].join('\n'), false, 9000)
2643
+ for (const x of r.notes) document.querySelector(`.mt-sets input[data-name="${x.name}"]`)?.classList.add('moved')
2644
+ }
2645
+ const num = (name, label, said) => h('input', { type: 'number', className: 'tries', 'data-name': name, 'aria-label': label, min: LIMITS[name][0], max: LIMITS[name][1], value: S.settings[name], onchange: (e) => {
2634
2646
  const v = Math.round(Number(e.target.value))
2635
2647
  const [lo, hi] = LIMITS[name]
2636
2648
  if (!(v >= lo && v <= hi)) return (e.target.value = S.settings[name]), toast(`a whole number, ${lo} to ${hi}`, true)
2637
- act('/api/setting', { name, value: v }, said(v))
2649
+ saveTime(name, v, said(v))
2638
2650
  } })
2639
2651
  const secsCell = (icon, label, name, about, unit, said) => cell(icon, label, about, num(name, label, said), h('span', { className: 'unit', textContent: unit }))
2640
2652
  const settings = h('div', { className: 'mt-sets', inert: busy },
2641
2653
  h('div', { className: 'mt-mode-sets' },
2642
- cell('swap', 'If one fails', ro.on === 'retries' ? 'a rate limit or outage: that model gets that many tries in all before the next one; any other error moves on at once' : "any error moves on at once, to the next model (after an error from its provider: another provider's first)",
2654
+ cell('swap', 'If one fails', 'What happens when a model errors, doesn\'t answer in time, or is rate-limited.\n\nSwitch model: another of your models takes over at once (the best-ranked one not tried yet).\nRetry it first: when the model is only busy or briefly down (a rate limit, an outage), the same one is tried again, up to the number of tries set here; any other error switches at once.',
2643
2655
  h('select', { onchange: (e) => saveOrder(S.order, 'saved', { on: e.target.value }) },
2644
- [['failure', 'go to the next'], ['retries', 'retry it first']].map(([v, t]) => h('option', { value: v, textContent: t, selected: ro.on === v }))),
2645
- ro.on === 'retries' ? h('input', { type: 'number', className: 'tries', 'aria-label': 'tries', title: 'tries of the same model first (rate limits, outages)', min: 1, max: 20, value: ro.retries, onchange: (e) => saveOrder(S.order, 'saved', { retries: Number(e.target.value) }) }) : null),
2646
- secsCell('clock', 'Give up', 'replyStart', "a model that hasn't started answering (text, thinking or a tool call) in this many seconds counts as failed (a streamed reply: a model set up without streaming waits for its whole reply)", 's', (v) => `a model that hasn't started answering in ${v}s counts as failed`),
2647
- secsCell('pause', 'Stalled', 'replyIdle', 'a reply that stops sending anything for this many seconds is stalled: tried again, or the next model', 's', (v) => `a reply silent for ${v}s counts as stalled`),
2648
- cell('hourglass', 'Tests wait', 'how long a test waits for each answer',
2649
- h('input', { type: 'number', className: 'tries', min: 1, max: 600, step: 1, value: S.settings.testTimeout ?? 10, 'aria-label': 'Test timeout in seconds', onchange: (e) => {
2656
+ [['failure', 'switch model'], ['retries', 'retry it first']].map(([v, t]) => h('option', { value: v, textContent: t, selected: ro.on === v }))),
2657
+ ro.on === 'retries' ? h('input', { type: 'number', className: 'tries', 'aria-label': 'tries', title: 'Tries\nHow many times in all the same model is tried when it\'s busy or briefly down, before another model takes over.', min: 1, max: 20, value: ro.retries, onchange: (e) => saveOrder(S.order, 'saved', { retries: Number(e.target.value) }) }) : null),
2658
+ secsCell('clock', 'Give up', 'replyStart', "How long a model gets to start answering.\n\nAfter HeartCode asks, the first word, thought or tool call must come within this many seconds. If nothing comes, the model counts as failed and another one takes over.\n\nRaise it if your providers are slow but do answer (fewer switches). Lower it to move on faster from models that hang.\nStalled and Tests wait are never shorter than this: they move up with it.", 's', (v) => `a model that hasn't started answering in ${v}s counts as failed`),
2659
+ secsCell('pause', 'Stalled', 'replyIdle', "How long a reply may go quiet once it has started.\n\nA model that keeps sending (text or thinking) is never cut off, however long it takes. One that sends nothing at all for this many seconds counts as stalled: it's asked again, or another model takes over.\n\nAt least as long as Give up (a pause mid-reply has the same causes as a slow start).", 's', (v) => `a reply silent for ${v}s counts as stalled`),
2660
+ cell('hourglass', 'Tests wait', "Only for the Test buttons on this page, not for real work.\n\nHow long each model gets to answer a short test message. No answer by then shows as \"no answer\" in Works?.\n\nAt least as long as Give up, so a test doesn't call a model broken that real work would still wait for.",
2661
+ h('input', { type: 'number', className: 'tries', 'data-name': 'testTimeout', min: 1, max: 600, step: 1, value: S.settings.testTimeout, 'aria-label': 'Test timeout in seconds', onchange: (e) => {
2650
2662
  const v = Math.round(Number(e.target.value))
2651
- if (!(v >= 1 && v <= 600)) return (e.target.value = S.settings.testTimeout ?? 10), toast('a whole number of seconds, 1 to 600', true)
2652
- act('/api/setting', { name: 'testTimeout', value: v }, `tests wait ${v} second${v === 1 ? '' : 's'} for an answer`)
2663
+ if (!(v >= 1 && v <= 600)) return (e.target.value = S.settings.testTimeout), toast('a whole number of seconds, 1 to 600', true)
2664
+ saveTime('testTimeout', v, `tests wait ${v} second${v === 1 ? '' : 's'} for an answer`)
2653
2665
  } }), h('span', { className: 'unit', textContent: 's' })),
2654
- cell('send', 'New message', 'the model a new message goes to first: #1, or the last one that worked',
2666
+ cell('send', 'New message', 'Which model a new message goes to first.\n\n#1: always the top of the list.\nLast working: the one that answered last (useful while #1 keeps failing).',
2655
2667
  h('select', { onchange: (e) => saveOrder(S.order, 'saved', { next: e.target.value }) },
2656
2668
  [['first', '#1'], ['stay', 'last working']].map(([v, t]) => h('option', { value: v, textContent: t, selected: ro.next === v })))),
2657
2669
  h('span', { className: 'mt-div', 'aria-hidden': 'true' }),
@@ -2660,7 +2672,9 @@ function drawMine(s) {
2660
2672
  // --- beside the filters: what's shown · what you do with it (the sorts show in the column heads) ---
2661
2673
  const line = h('div', { className: 'mt-line' },
2662
2674
  h('span', { className: 'count', title: SORT.length ? `sorted by ${SORT.map(({ key, dir }) => `${COLS[key].label} ${COLS[key].words[dir === 'up' ? 0 : 1]}`).join(', then ')}; ties keep the list order` : '' }, filtered ? [h('b', { textContent: n(shown.length) }), ` of ${n(order.length)}`] : [h('b', { textContent: n(order.length) }), ` model${order.length === 1 ? '' : 's'}`]),
2663
- filtering() || SORT.length ? h('button', { className: 'small ghost', textContent: 'Clear', title: 'every filter and the sort off: the whole list, in order', onclick: clearView }) : null,
2675
+ // the sorting off in one click (the filters stay); with filters on too, Clear all turns both off
2676
+ SORT.length ? h('button', { className: 'small ghost', textContent: 'Clear sort', title: 'every sort off: the list in its own order again (the filters stay)', onclick: () => setSort([]) }) : null,
2677
+ filtering() ? h('button', { className: 'small ghost', textContent: 'Clear all', title: 'every filter and the sort off: the whole list, in order', onclick: clearView }) : null,
2664
2678
  order.length > 1 ? drawHelperBar() : null)
2665
2679
 
2666
2680
  // --- the table ---
@@ -2883,7 +2897,7 @@ async function suggestNow(b) {
2883
2897
  if (!r) return
2884
2898
  HSUG = Object.keys(r.suggest).length ? r.suggest : null
2885
2899
  if (!HSUG) return toast(working() ? 'Nothing more to suggest' : 'No model worked in the test: nothing to pick from', !working())
2886
- setFilter({ helpers: true }) // your helpers and the suggested ones, together: not lost among the rest
2900
+ drawMine(S) // shown dashed in the Helper column, in the list as it is: nothing filtered
2887
2901
  }
2888
2902
  // The toolbar's helpers part: suggestions waiting (take all · dismiss), or Suggest helpers and Clear
2889
2903
  // helpers. Each saves at once, its own button saying so.
@@ -2904,11 +2918,11 @@ function drawHelperBar() {
2904
2918
  saveHelpers(next, [], `${took.length} model${took.length === 1 ? ' is a helper' : 's are helpers'} now`).then(() => drawMine(S))
2905
2919
  } }),
2906
2920
  h('button', { className: 'small ghost', textContent: 'Dismiss', onclick: () => ((HSUG = null), drawMine(S)) })) : null,
2907
- !HSUG && !S.helpersAuto ? h('button', { className: 'small', title: working() ? `suggest helpers from the ${working()} models that answered their test (their provider switched on), each with what it's good at that it doesn't have yet (from the rankings, its test, thinking and context): shown first, to take or not` : 'suggest helpers: the models are tested first (helpers are picked from the ones that answer)', onclick: (e) => (working() ? suggestNow(e.currentTarget) : testFirst('suggest')), 'aria-label': 'Suggest helpers' }, ic('sparkles'), h('span', { className: 'lt', textContent: 'Suggest helpers' })) : null,
2921
+ !HSUG && !S.helpersAuto ? h('button', { className: 'small', title: working() ? `suggest helpers from the ${working()} models that answered their test (their provider switched on), each with what it's good at that it doesn't have yet (from the rankings, its test, thinking and context): marked dashed in the Helper column, to take or not; the list isn't filtered` : 'suggest helpers: the models are tested first (helpers are picked from the ones that answer)', onclick: (e) => (working() ? suggestNow(e.currentTarget) : testFirst('suggest')), 'aria-label': 'Suggest helpers' }, ic('sparkles'), h('span', { className: 'lt', textContent: 'Suggest helpers' })) : null,
2908
2922
  !HSUG && n ? h('button', { className: 'small ghost', 'aria-label': 'Clear helpers', title: `Clear helpers: no model a helper (${n} now): #1 can then start any model again, as before`, onclick: (e) => {
2909
2923
  if (!confirm(`Clear the ${n} helper${n === 1 ? '' : 's'}? #1 can then start any model again, as before.`)) return
2910
2924
  busy(e.currentTarget)
2911
- saveHelpers({}, [], 'no helpers: #1 can start any model again').then(() => (FILTER.helpers ? setFilter({ helpers: false }) : drawMine(S))) // no helpers left to show only
2925
+ saveHelpers({}, [], 'no helpers: #1 can start any model again').then(() => drawMine(S))
2912
2926
  } }, ic('x'), h('span', { className: 'lt', textContent: 'Clear helpers' })) : null)
2913
2927
  return helperBar
2914
2928
  }
@@ -3767,7 +3781,7 @@ function render(s) {
3767
3781
  // server can be older than a change made here a moment ago)
3768
3782
  if (!filtersLoaded) SORT = Array.isArray(p.sorts) ? p.sorts.filter((x) => COLS[x?.key]) : Array.isArray(p.sort) ? p.sort.filter((x) => COLS[x?.key]).map(flip) : []
3769
3783
  RANK = Array.isArray(p.rank) ? p.rank.filter((x) => typeof x === 'string') : []
3770
- if (!filtersLoaded) (filtersLoaded = true), (FILTER = { ...NO_FILTER, ...(p.filters && typeof p.filters === 'object' ? p.filters : {}) }) // after that the page's own are the latest
3784
+ if (!filtersLoaded) (filtersLoaded = true), (FILTER = { ...NO_FILTER, ...Object.fromEntries(Object.entries(p.filters && typeof p.filters === 'object' ? p.filters : {}).filter(([k]) => k in NO_FILTER)) }) // after that the page's own are the latest (a filter that's gone, like the old Helpers one, isn't kept)
3771
3785
  }
3772
3786
  S = s
3773
3787
  for (const [key, r] of Object.entries(TRIES)) if (!r.going && placeOf(...key.split(/\/(.*)/s)) === undefined) delete TRIES[key] // off your list: its result too
package/src/settings.js CHANGED
@@ -8,7 +8,7 @@ import fs from 'node:fs'
8
8
  import path from 'node:path'
9
9
  import crypto from 'node:crypto'
10
10
  import os from 'node:os'
11
- import { HOME, saveConfig, readJson, writeJson, byName, takeIn, whatOf, VERSION, speedOf, SPEED_LIMITS, HELPER_JOBS, helpersOf } from './config.js'
11
+ import { HOME, saveConfig, readJson, writeJson, byName, takeIn, whatOf, VERSION, speedOf, SPEED_LIMITS, HELPER_JOBS, helpersOf, testWaitOf, fitTimes } from './config.js'
12
12
  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'
@@ -27,6 +27,7 @@ import { capabilities } from './capabilities.js'
27
27
  import { connect, sendTelegram, tokenHint, tgReady, EVENTS } from './telegram.js'
28
28
  import { searchSettings, testSearxng, ENGINE_NAMES } from './web.js'
29
29
  import { log, LOGS, REQUESTS, useRequestLog, listRequests, readRequest, pruneLogs, logDays, logSize, clearLogs, LOG_KINDS, kindsOn, listLogRuns, readLog } from './log.js'
30
+ import { fetch } from './http.js' // not the built-in one: see http.js
30
31
 
31
32
  const PAGE = new URL('./settings.html', import.meta.url)
32
33
  const EFFORTS = ['default', 'low', 'medium', 'high']
@@ -270,7 +271,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
270
271
  if (gone) saveTests()
271
272
  }
272
273
  // How long a model test waits for its answer (cfg.testTimeout, seconds; the settings page sets it).
273
- const testWait = () => (Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : 10) * 1000
274
+ const testWait = () => testWaitOf(cfg) * 1000
274
275
  const noAnswer = () => `no answer within ${testWait() / 1000} seconds`
275
276
  // A provider's models tested a few at a time (more for a long list: startRun)
276
277
  const AT_ONCE = 4
@@ -464,10 +465,10 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
464
465
  rankings: ranked && { fetched: ranked.fetched, source: ranked.source },
465
466
  rotation: (({ then, ...opts }) => opts)(rotationOf(cfg)),
466
467
  helpers: helpersOf(cfg.helpers), // { 'provider/model': [jobs] }
467
- helperOrder: cfg.helperOrder === 'provider' || cfg.helperOrder === 'score' ? cfg.helperOrder : 'own', // the order helpers are picked in: your list's, your provider ranking's, or by their rankings
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
468
469
  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
469
470
  jobs: HELPER_JOBS,
470
- 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: Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : 10, ...speedOf(cfg) },
471
+ 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) },
471
472
  logs: { runs: tilde(path.join(LOGS, 'runs')), requests: tilde(REQUESTS) },
472
473
  voice: cfg.voice ? JSON.stringify(cfg.voice, null, 2) : '',
473
474
  statusBar: cfg.statusBar === undefined ? null : cfg.statusBar, // false (off), a list of lines, or null (default)
@@ -643,14 +644,14 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
643
644
  save('setting:helpers')
644
645
  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
645
646
  },
646
- // the order helpers are picked in: 'own' (your list's), 'provider' (your provider ranking's, each
647
- // provider's in your list's order; rank: the ranking as the page has it, kept for HeartCode to use)
648
- // or 'score' (best placed in LMArena's rankings first)
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)
649
650
  'POST /api/helper-order': ({ by, rank }) => {
650
- cfg.helperOrder = by === 'provider' || by === 'score' ? by : undefined
651
+ cfg.helperOrder = by === 'provider' || by === 'own' ? by : undefined
651
652
  cfg.providerRank = cfg.helperOrder === 'provider' ? (Array.isArray(rank) ? rank.filter((x) => typeof x === 'string') : readJson(PREFS, {}).rank) : undefined
652
653
  save('setting:helperOrder')
653
- return { helperOrder: cfg.helperOrder ?? 'own' }
654
+ return { helperOrder: cfg.helperOrder ?? 'score' }
654
655
  },
655
656
  // the model list, in order (#1 is the model), and when to go on to the next
656
657
  'POST /api/order': ({ list, on, retries, next }) => {
@@ -793,7 +794,9 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
793
794
  if (name in SPEED_LIMITS && !(Number.isInteger(value) && value >= SPEED_LIMITS[name][0] && value <= SPEED_LIMITS[name][1])) throw new Error(`${name}: a whole number, ${SPEED_LIMITS[name][0]} to ${SPEED_LIMITS[name][1]}`)
794
795
  if (!['permissions', 'effort', 'theme', 'context', 'logDetail', 'logDays', 'testTimeout', ...Object.keys(SPEED_LIMITS), ...Object.keys(TOGGLES)].includes(name)) throw new Error(`no setting "${name}"`)
795
796
  cfg[name] = name === 'effort' && value === 'default' ? undefined : name === 'context' ? (value === null ? undefined : Number(value)) : value
797
+ const notes = ['replyStart', 'replyIdle', 'testTimeout'].includes(name) ? fitTimes(cfg, name) : [] // the others moved to fit, said on the page
796
798
  save(`setting:${name}`)
799
+ if (notes.length) return { ...state(), notes }
797
800
  if (name === 'logDetail') useRequestLog(cfg) // from the next request (a running HeartCode takes it in too: applySettings)
798
801
  if (name === 'logDays') pruneLogs(value) // older ones go now
799
802
  return state()
package/src/spawn.js ADDED
@@ -0,0 +1,48 @@
1
+ // Starting and stopping other programs the same way on every OS.
2
+ // Windows: npm, npx and most tools installed by npm are .cmd files, which Node won't start without a
3
+ // shell (EINVAL, or ENOENT for a bare "npx"); they go through cmd.exe, each word quoted for it. And a
4
+ // program started through a shell is stopped with its whole tree (taskkill /T): killing only the
5
+ // shell would leave the program itself running.
6
+ import { spawn as nodeSpawn, spawnSync } from 'node:child_process'
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+
10
+ const WIN = process.platform === 'win32'
11
+
12
+ // cmd.exe's quoting: a word with spaces or its special characters in double quotes ("" for a quote;
13
+ // backslashes at its end doubled, or the last one would hide the closing quote from the program)
14
+ const quote = (w) => (w === '' || /[\s"&|<>^()%!,;=]/.test(w) ? `"${String(w).replace(/"/g, '""').replace(/(\\+)$/, '$1$1')}"` : String(w))
15
+
16
+ // spawn(command, args, options), started through cmd.exe on Windows (spawnCmdSync: spawnSync's)
17
+ const viaCmd = (run) => (command, args = [], opts = {}) => (WIN ? run(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', `"${[command, ...args].map(quote).join(' ')}"`], { ...opts, windowsVerbatimArguments: true }) : run(command, args, opts))
18
+ export const spawnCmd = viaCmd(nodeSpawn)
19
+ export const spawnCmdSync = viaCmd(spawnSync)
20
+
21
+ // A program's path on the PATH, or '' (Windows: with its extension, .exe, .cmd…, as PATHEXT lists them)
22
+ const EXTS = WIN ? ['', ...(process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean)] : ['']
23
+ export function onPath(cmd) {
24
+ for (const d of (process.env.PATH ?? '').split(path.delimiter)) {
25
+ if (!d) continue
26
+ for (const e of EXTS) {
27
+ const p = path.join(d, cmd + e)
28
+ try {
29
+ if (fs.statSync(p).isFile()) return p
30
+ } catch {}
31
+ }
32
+ }
33
+ return ''
34
+ }
35
+
36
+ // Stops a program and what it started: its process group elsewhere (when it was started detached),
37
+ // its process tree on Windows. sig 0: only whether it's still there. False when nothing was there.
38
+ export function killTree(pid, sig = 'SIGTERM', group = !WIN) {
39
+ if (!pid) return false
40
+ try {
41
+ if (sig === 0) return process.kill(group ? -pid : pid, 0)
42
+ if (WIN) return spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' }).status === 0
43
+ process.kill(group ? -pid : pid, sig)
44
+ return true
45
+ } catch {
46
+ return false
47
+ }
48
+ }
package/src/telegram.js CHANGED
@@ -5,6 +5,7 @@
5
5
  // (cfg.telegram: { token, chatId, chatName, bot, on, events }). The token is never logged or shown whole.
6
6
  import { log } from './log.js'
7
7
  import { saveConfig } from './config.js'
8
+ import { fetch } from './http.js' // not the built-in one: see http.js
8
9
 
9
10
  const API = process.env.HEART_TELEGRAM_API || 'https://api.telegram.org' // the env: a stand-in server, for tests
10
11
  export const EVENTS = {