heartcode 0.1.41 → 0.1.44

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.html CHANGED
@@ -585,6 +585,12 @@
585
585
  /* a model's tooltip: shown at once on hover (or keyboard focus), next to the row */
586
586
  #tip { position: fixed; z-index: 30; max-width: 380px; padding: 13px 15px; border-radius: 12px; background: var(--panel); border: 1px solid var(--line); box-shadow: var(--shadow-pop); font-size: 12.5px; pointer-events: none; opacity: 0; transition: opacity .08s; }
587
587
  #tip.show { opacity: 1; }
588
+ /* every other tooltip (titles): at once, the page's own look */
589
+ #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; }
590
+ #hint.show { opacity: 1; }
591
+ .with-q { display: inline-flex; align-items: center; gap: 5px; }
592
+ .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; }
593
+ .q:hover, .q:focus-visible { color: var(--text); border-color: var(--muted); outline: none; }
588
594
  #tip .tid { font-family: var(--mono); font-weight: 700; font-size: 13px; word-break: break-all; }
589
595
  #tip .tname { color: var(--muted); margin-top: 1px; }
590
596
  #tip dl { display: grid; grid-template-columns: auto 1fr; gap: 3px 12px; margin: 10px 0 0; }
@@ -1295,6 +1301,7 @@ const DOING = {
1295
1301
  '/api/provider/list': 'Saving the model list setting',
1296
1302
  '/api/provider/on': 'Switching the provider',
1297
1303
  '/api/order': 'Saving your models',
1304
+ '/api/orchestrators': 'Saving the orchestrators',
1298
1305
  '/api/mcp/login': 'Signing in — your browser will open',
1299
1306
  '/api/telegram/connect': 'Checking the token with Telegram',
1300
1307
  '/api/telegram/test': 'Sending a test message',
@@ -1820,6 +1827,46 @@ function withTip(el, content) {
1820
1827
  }
1821
1828
  addEventListener('scroll', () => $('tip').classList.remove('show'), true)
1822
1829
 
1830
+ // Every other tooltip (an element's title): shown at once in a box of the page's own, not the
1831
+ // browser's (which waits a second and can't be styled). The title moves to data-tip on first hover,
1832
+ // so the browser's own doesn't show as well; a title set again later is taken in the same way.
1833
+ const hint = h('div', { id: 'hint', role: 'tooltip' })
1834
+ document.body.append(hint)
1835
+ let hintFor = null
1836
+ const tipOf = (el) => {
1837
+ for (; el && el !== document.body; el = el.parentElement) {
1838
+ const title = el.getAttribute('title')
1839
+ if (title !== null) {
1840
+ el.removeAttribute('title') // set again to '' later: no tooltip now
1841
+ if (title) (el.dataset.tip = title), el.getAttribute('aria-label') || el.setAttribute('aria-description', title)
1842
+ else delete el.dataset.tip
1843
+ }
1844
+ if (el.dataset?.tip) return el
1845
+ }
1846
+ return null
1847
+ }
1848
+ const hideHint = () => ((hintFor = null), hint.classList.remove('show'))
1849
+ const showHint = (el) => {
1850
+ hintFor = el
1851
+ hint.textContent = el.dataset.tip
1852
+ hint.classList.add('show')
1853
+ const r = el.getBoundingClientRect()
1854
+ const t = hint.getBoundingClientRect()
1855
+ const below = r.bottom + 8 + t.height < innerHeight
1856
+ hint.style.top = `${below ? r.bottom + 6 : Math.max(8, r.top - t.height - 6)}px`
1857
+ hint.style.left = `${Math.min(Math.max(8, r.left + r.width / 2 - t.width / 2), innerWidth - t.width - 8)}px`
1858
+ }
1859
+ const hintAt = (e) => {
1860
+ const el = document.body.classList.contains('sorting') ? null : tipOf(e.target)
1861
+ if (el === hintFor) return
1862
+ el ? showHint(el) : hideHint()
1863
+ }
1864
+ document.addEventListener('mouseover', hintAt)
1865
+ document.addEventListener('focusin', hintAt)
1866
+ document.addEventListener('focusout', hideHint)
1867
+ document.addEventListener('mousedown', hideHint)
1868
+ addEventListener('scroll', hideHint, true)
1869
+
1823
1870
  function drawProviders(s) {
1824
1871
  const order = s.order
1825
1872
  const none = !s.providers.length
@@ -1835,7 +1882,7 @@ function drawProviders(s) {
1835
1882
  const shown = shownOrder()
1836
1883
  $('p-mine').hidden = !shown.length
1837
1884
  $('p-mine').textContent = `Your models (${shown.length}) →`
1838
- $('p-mine').title = shown.length ? `${S.settings.modelChoice === 'fit' ? 'HeartCode picks the best of them for each task' : `HeartCode uses ${shown[0].provider} · ${shown[0].model}`}. Open the Your models page: the order, tests, and what happens when one fails` : ''
1885
+ $('p-mine').title = shown.length ? `${S.settings.modelChoice === 'fit' ? 'An orchestrator answers each message or hands the work to the others' : `HeartCode uses ${shown[0].provider} · ${shown[0].model}`}. Open the Your models page: the order, tests, and what happens when one fails` : ''
1839
1886
  fillHeight()
1840
1887
 
1841
1888
  // every provider's models, A to Z; one click adds it (the first one becomes #1). Built
@@ -2198,6 +2245,15 @@ function buildCatalog(s) {
2198
2245
  }
2199
2246
  // --- Your models page: the list as a table; sorted by several columns at once (each a tie-break
2200
2247
  // for the ones before it), the sort kept in this browser ---
2248
+ // The orchestrators (Pick: "an orchestrator hands it out"): those picked that call tools; none: your first that does
2249
+ const leads = (s = S) => {
2250
+ const able = s.order.filter((t) => !isOff(t.provider) && can(t).tools)
2251
+ const picked = able.filter((t) => (s.orchestrators ?? []).some((o) => o.provider === t.provider && o.model === t.model))
2252
+ return picked.length ? picked : able.slice(0, 1)
2253
+ }
2254
+ const ORCH_ABOUT = 'Makes the selected models your orchestrators, in place of the ones you have now. Every message then goes to one of them first: it replies on its own when it can (a hello, a quick question), and hands real work to the other models it picks. They only orchestrate and do no work themselves. A model that can\'t call tools is skipped.'
2255
+ const isLead = (t) => leads().some((o) => o.provider === t.provider && o.model === t.model)
2256
+ const setLeads = (list, done) => act('/api/orchestrators', { list: list.map(({ provider, model }) => ({ provider, model })) }, done)
2201
2257
  const can = (t) => ({ tools: t.tested ? t.tested.mode === 'tools' : t.known?.tools !== false, thinking: Boolean(t.tested ? t.tested.thinking : t.known?.thinking), images: Boolean(t.tested ? t.tested.vision : t.known?.images) })
2202
2258
  // Every column sorts by the value it shows: up (↑) smallest first, down (↓) largest first. first: the
2203
2259
  // direction of the first click (the useful one). get: the value; null when there's none (no price, no
@@ -2376,7 +2432,9 @@ function drawMine(s) {
2376
2432
  const order = shownOrder() // a provider switched off: its models aren't shown (nor tested, sorted, ranked)
2377
2433
  $('n-mine').textContent = order.length || ''
2378
2434
  const shown = filtering() ? order.filter((t) => passes(t)) : order
2379
- const view = sorted(shown)
2435
+ // an orchestrator: they come first (they answer first), in your order; the rest as sorted
2436
+ const first = new Set(S.settings.modelChoice === 'fit' ? leads().map(keyOf) : [])
2437
+ const view = ((v) => (first.size ? [...v.filter((t) => first.has(keyOf(t))), ...v.filter((t) => !first.has(keyOf(t)))] : v))(sorted(shown))
2380
2438
  const filtered = shown.length !== order.length
2381
2439
  for (const k of PICKED) if (placeOf(...k.split(/\/(.*)/s)) === undefined) PICKED.delete(k) // gone from the list
2382
2440
  const n = (x) => x.toLocaleString()
@@ -2419,24 +2477,23 @@ function drawMine(s) {
2419
2477
 
2420
2478
  // --- the page's header: how a model is picked (left), what's known about the models (right) ---
2421
2479
  $('mt-lead').textContent = S.settings.modelChoice === 'fit'
2422
- ? 'Each message goes to the models that score best for it. Your order breaks ties, and decides among models with no score. Filter, sort or drag, then Save order.'
2480
+ ? 'An orchestrator answers each message at once, or hands the work to the models it picks from the others. To choose them, select models and press Mark as orchestrators (a quick, cheap model is enough).'
2423
2481
  : 'HeartCode uses #1, and the next one when it fails. Filter, sort or drag, then Save order.'
2424
2482
  const busy = locked()
2425
2483
  $('mt-actions').inert = busy
2426
2484
  put($('mt-actions'),
2427
2485
  ((why) => h('span', { title: why ?? '' }, h('button', { className: 'small', textContent: 'Order providers', disabled: Boolean(why), title: why ? '' : 'drag your 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)
2428
- S.settings.modelChoice === 'fit' ? 'Not used while Pick is "the best for each task": each message gets the models ranked best for it, whatever their provider. Pick "in your order" to use it'
2429
- : !order.some((t) => t.provider !== order[0]?.provider) ? 'All your models are from one provider: nothing to order' : null),
2430
- 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 scores in LMArena's public rankings (coding, web apps, vision${S.rankings ? `; scores from ${new Date(S.rankings.fetched).toLocaleDateString()}` : ''}). Best fit also gets the scores again once a week`, onclick: () => lookUp() }))
2486
+ !order.some((t) => t.provider !== order[0]?.provider) ? 'All your models are from one provider: nothing to order' : null),
2487
+ 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 scores in LMArena's public rankings (coding, web apps, vision${S.rankings ? `; scores from ${new Date(S.rankings.fetched).toLocaleDateString()}` : ''}). With an orchestrator they come again once a week`, onclick: () => lookUp() }))
2431
2488
 
2432
2489
  // --- the list's settings: one line, a short label beside each control ---
2433
2490
  const ro = s.rotation
2434
2491
  const cell = (label, about, ...control) => h('label', { className: 'mt-set', title: about }, h('span', { className: 'mt-setl', textContent: label }), h('span', { className: 'mt-setc' }, ...control))
2435
2492
  const fit = S.settings.modelChoice === 'fit'
2436
2493
  const settings = h('div', { className: 'mt-sets', inert: busy },
2437
- cell('Pick', fit ? 'for each new message, your models ranked by public rankings (LMArena, fetched once a week) on the skills it needs: web pages, code, images…; models not ranked come after, in your order' : 'your order: #1 works, the next takes over when it fails',
2438
- h('select', { onchange: (e) => act('/api/setting', { name: 'modelChoice', value: e.target.value }, e.target.value === 'fit' ? 'models picked for each task by public rankings' : 'models used in your order') },
2439
- [['order', 'in your order'], ['fit', 'the best for each task']].map(([v, t]) => h('option', { value: v, textContent: t, selected: S.settings.modelChoice === v })))),
2494
+ cell('Pick', fit ? "each message starts on an orchestrator: it answers itself (a hello), or hands the work to the models it picks from the others (it sees what each can do, and its place in LMArena's public rankings). It only hands work out; the others do it" : 'your order: #1 works, the next takes over when it fails',
2495
+ h('select', { onchange: (e) => act('/api/setting', { name: 'modelChoice', value: e.target.value }, e.target.value === 'fit' ? 'an orchestrator hands each task out' : 'models used in your order') },
2496
+ [['order', 'in your order'], ['fit', 'an orchestrator hands it out']].map(([v, t]) => h('option', { value: v, textContent: t, selected: S.settings.modelChoice === v })))),
2440
2497
  cell('If one fails', ro.on === 'retries' ? 'a rate limit or outage: that model is tried again that many times first; any other error moves on at once' : "any error moves on at once, to another provider's model first",
2441
2498
  h('select', { onchange: (e) => saveOrder(S.order, 'saved', { on: e.target.value }) },
2442
2499
  [['failure', 'go to the next'], ['retries', 'retry it first']].map(([v, t]) => h('option', { value: v, textContent: t, selected: ro.on === v }))),
@@ -2447,7 +2504,9 @@ function drawMine(s) {
2447
2504
  if (!(v >= 5 && v <= 600)) return (e.target.value = S.settings.replyStart ?? 60), toast('a whole number of seconds, 5 to 600', true)
2448
2505
  act('/api/setting', { name: 'replyStart', value: v }, `a model that hasn't started answering in ${v}s counts as failed`)
2449
2506
  } }), h('span', { className: 'unit', textContent: 'seconds of silence' })),
2450
- cell('New message to', fit ? 'best fit picks it for each message' : 'the model a new message goes to first',
2507
+ fit ? cell('Orchestrators', 'the models that answer first and hand the work out (the next one when one fails). Select models in the list and press Mark as orchestrators; click a model\'s "orchestrator ✕" tag to unmark it. None chosen: your first model that calls tools',
2508
+ h('span', { className: 'unit', textContent: (S.orchestrators ?? []).length ? leads().map((t) => t.model).join(', ') || 'none that calls tools' : `${leads()[0]?.model ?? 'none'} (your first)` })) : null,
2509
+ cell('New message to', fit ? 'each message starts on an orchestrator' : 'the model a new message goes to first',
2451
2510
  h('select', { disabled: fit, onchange: (e) => saveOrder(S.order, 'saved', { next: e.target.value }) },
2452
2511
  [['first', '#1'], ['stay', 'the last that worked']].map(([v, t]) => h('option', { value: v, textContent: t, selected: ro.next === v })))),
2453
2512
  cell('Tests wait', 'every model test: Test, Test all, Request',
@@ -2463,7 +2522,7 @@ function drawMine(s) {
2463
2522
  busy ? h('span', { className: 'sort-live', textContent: `${testingAll ? 'testing' : 'updating'}: filters and changes wait until it's done (or Stop)` }) : null,
2464
2523
  filtering() || SORT.length ? h('button', { className: 'small ghost', textContent: 'Clear', title: 'every filter and the sort off: your whole list, in your order', onclick: clearView }) : null,
2465
2524
  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`, onclick: () => tryAll(filtered ? shown : order) }),
2466
- h('button', { className: 'small primary', textContent: filtered ? `Use only these ${n(view.length)}` : 'Save order', disabled: !view.length || order.length < 2, title: filtered ? `HeartCode uses only these ${n(view.length)}, in the order shown (the others stay under Providers)` : S.settings.modelChoice === 'fit' ? 'keep the order shown: it breaks ties between equally scored models' : 'HeartCode uses them in the order shown (#1 first)', onclick: saveList }))
2525
+ h('button', { className: 'small primary', textContent: filtered ? `Use only these ${n(view.length)}` : 'Save order', disabled: !view.length || order.length < 2, title: filtered ? `HeartCode uses only these ${n(view.length)}, in the order shown (the others stay under Providers)` : S.settings.modelChoice === 'fit' ? 'keep the order shown: the orchestrator sees the others in this order, and a failed model goes to the next' : 'HeartCode uses them in the order shown (#1 first)', onclick: saveList }))
2467
2526
 
2468
2527
  // --- the table ---
2469
2528
  const all = view.length > 0 && view.every((t) => PICKED.has(keyOf(t)))
@@ -2479,6 +2538,12 @@ function drawMine(s) {
2479
2538
  h('div', { className: 'mt-pickbar' },
2480
2539
  h('b', { textContent: `${n(PICKED.size)} selected` }),
2481
2540
  h('button', { className: 'small', textContent: 'Test', disabled: testingAll, onclick: () => tryAll(pickedList) }),
2541
+ S.settings.modelChoice === 'fit' ? h('span', { className: 'with-q' }, h('button', { className: 'small', textContent: PICKED.size === 1 ? 'Mark as orchestrator' : 'Mark as orchestrators', title: ORCH_ABOUT, onclick: () => {
2542
+ const list = pickedList.filter((t) => can(t).tools)
2543
+ if (!list.length) return toast("none of these can call tools, and an orchestrator hands work out with a tool call", true)
2544
+ PICKED.clear()
2545
+ setLeads(list, `${list.length} orchestrator${list.length === 1 ? '' : 's'}: ${list.map((t) => t.model).join(', ')}`)
2546
+ } }), h('span', { className: 'q', tabIndex: 0, textContent: '?', title: ORCH_ABOUT, 'aria-label': 'what Mark as orchestrator does' })) : null,
2482
2547
  h('button', { className: 'small danger', textContent: 'Remove', onclick: removePicked }),
2483
2548
  h('button', { className: 'small ghost', textContent: 'Invert', title: "select the ones shown that aren't selected, unselect the ones that are", onclick: () => (view.forEach((t) => (PICKED.has(keyOf(t)) ? PICKED.delete(keyOf(t)) : PICKED.add(keyOf(t)))), (lastPicked = null), drawMine(S)) }),
2484
2549
  h('button', { className: 'small ghost', textContent: 'Select none', onclick: () => (PICKED.clear(), drawMine(S)) })))
@@ -2556,13 +2621,16 @@ function tableRow(t, at, pick) {
2556
2621
  const tag = !x ? h('span', { className: 'tag', textContent: '…', title: 'looking it up in models.dev' })
2557
2622
  : x.source === 'assumed' ? h('button', { type: 'button', className: 'tag warn', textContent: 'unknown', title: "models.dev doesn't know it: what it can do is a guess. Click to set it up", onclick: () => openSetup(t) })
2558
2623
  : Object.keys(x.set ?? {}).length ? h('button', { type: 'button', className: 'tag', textContent: 'edited', title: 'what it can do: set by you (click to change)', onclick: () => openSetup(t) }) : null
2624
+ const lead = S.settings.modelChoice === 'fit' && isLead(t) && (S.orchestrators ?? []).length
2625
+ ? h('button', { type: 'button', className: 'tag brand', textContent: 'orchestrator ✕', title: 'An orchestrator: every message goes to it first, and it replies or hands the work out. Click to unmark it (it goes back to being one of the models that do the work)', onclick: () => setLeads(leads().filter((o) => o !== t), `${t.model}: not an orchestrator now`) })
2626
+ : S.settings.modelChoice === 'fit' && isLead(t) ? h('span', { className: 'tag brand', textContent: 'orchestrator', title: 'None are marked, so your first model that calls tools orchestrates. To choose them, select models and press Mark as orchestrators' }) : null
2559
2627
  const going = Boolean(TRIES[keyOf(t)]?.going)
2560
2628
  const busy = locked()
2561
2629
  return h('li', { className: 'in' + (picked ? ' picked' : '') + (isOff(t.provider) ? ' off' : ''), 'data-key': `${t.provider}/${t.model}`, title: isOff(t.provider) ? `${t.provider} is switched off: HeartCode skips this model until it's on` : '' },
2562
2630
  h('span', { className: 'grip', textContent: '⋮⋮', 'aria-hidden': 'true' }),
2563
2631
  h('input', { type: 'checkbox', checked: picked, disabled: busy, 'aria-label': `select ${t.model}`, title: 'select (Shift: and every row up to the last one selected)', onclick: (e) => (e.preventDefault(), pick(e)) }),
2564
2632
  h('span', { className: 'n', textContent: `#${at + 1}`, title: SORT.length || filtering() ? 'its place in your list' : '' }),
2565
- h('span', { className: 'm' }, h('span', { className: 'name', textContent: t.model, title: t.model }), tag),
2633
+ h('span', { className: 'm' }, h('span', { className: 'name', textContent: t.model, title: t.model }), lead, tag),
2566
2634
  h('span', { className: 'p', textContent: isOff(t.provider) ? `${t.provider} · off` : t.provider, title: t.provider }),
2567
2635
  h('span', { className: 'num', textContent: ctx ? `${t.tested?.sure === false ? '~' : ''}${kTok(ctx)}` : '–', title: ctx ? `${ctx.toLocaleString()} tokens${t.tested?.sure === false ? ' (assumed: the server and models.dev don\'t say)' : ''}` : '' }),
2568
2636
  yes(c.tools), yes(c.thinking), yes(c.images),
@@ -2595,8 +2663,8 @@ function markCatalog() {
2595
2663
  function drawUsing(s) {
2596
2664
  const o = s.order.filter((t) => !isOff(t.provider))
2597
2665
  $('using').hidden = page() === 'providers' // there it's on the page itself
2598
- const fit = s.settings.modelChoice === 'fit' // best fit: no one model is "the one"
2599
- put($('using'), o.length && fit ? [h('span', { className: 'k', textContent: 'HeartCode picks' }), h('b', { textContent: 'the best for each task' }), h('span', { className: 'k', textContent: `from your ${o.length.toLocaleString()} model${o.length > 1 ? 's' : ''}` })]
2666
+ const fit = s.settings.modelChoice === 'fit' // an orchestrator: no one model is "the one"
2667
+ put($('using'), o.length && fit ? [h('span', { className: 'k', textContent: 'Orchestrated by' }), h('b', { textContent: leads(s).map((t) => t.model).join(', ') || o[0].model }), h('span', { className: 'k', textContent: `with your ${o.length.toLocaleString()} model${o.length > 1 ? 's' : ''}` })]
2600
2668
  : o.length ? [h('span', { className: 'k', textContent: 'HeartCode uses' }), h('b', { textContent: o[0].model }), h('span', { className: 'k', textContent: `${o[0].provider}${o.length > 1 ? ` · ${o.length - 1} fallback${o.length > 2 ? 's' : ''}` : ''}` })] : s.order.length ? [h('span', { className: 'k', textContent: 'The providers of all your models are switched off' }), h('a', { href: '#providers', textContent: 'Switch one on' })] : [h('span', { className: 'k', textContent: 'No model chosen yet' }), h('a', { href: '#providers', textContent: 'Choose one' })])
2601
2669
  }
2602
2670
 
package/src/settings.js CHANGED
@@ -30,7 +30,7 @@ import { log, LOGS, REQUESTS, useRequestLog, listRequests, readRequest, pruneLog
30
30
 
31
31
  const PAGE = new URL('./settings.html', import.meta.url)
32
32
  const EFFORTS = ['default', 'low', 'medium', 'high']
33
- 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 once a day whether a newer HeartCode is out (shown in the status bar; /update installs it)' }
33
+ 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)' }
34
34
  // The Logging page's: both off unless switched on; how much of each request ("full" or "summary")
35
35
  // The status-bar items the visual editor offers (id must match App.status in bin/heartcode.js).
36
36
  // `sample` is shown in the page's live preview.
@@ -372,6 +372,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
372
372
  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
373
373
  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) })),
374
374
  rankings: ranked && { fetched: ranked.fetched, source: ranked.source },
375
+ orchestrators: cfg.orchestrators ?? [],
375
376
  rotation: (({ then, ...opts }) => opts)(rotationOf(cfg)),
376
377
  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, modelChoice: cfg.modelChoice === 'fit' ? 'fit' : 'order', replyStart: Number(cfg.replyStart) > 0 ? Number(cfg.replyStart) : 60 },
377
378
  logs: { runs: tilde(path.join(LOGS, 'runs')), requests: tilde(REQUESTS) },
@@ -555,6 +556,15 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
555
556
  forgetTests()
556
557
  return state()
557
558
  },
559
+ // The models that orchestrate when Pick is "an orchestrator hands it out": [{ provider, model }]
560
+ // (none: your first that calls tools)
561
+ 'POST /api/orchestrators': ({ list }) => {
562
+ if (!Array.isArray(list)) throw new Error('a list of models is needed')
563
+ const clean = list.map((t) => ({ provider: String(t?.provider ?? ''), model: String(t?.model ?? '').trim() })).filter((t) => cfg.providers[t.provider] && t.model)
564
+ cfg.orchestrators = clean.length ? clean : undefined
565
+ save('setting:orchestrators')
566
+ return state()
567
+ },
558
568
  // models.dev again (one model, or all of yours): its list fetched anew, and each model's profile
559
569
  // takes what it says now (one it didn't know before becomes "from models.dev"; your own settings
560
570
  // for it stay above). A running HeartCode takes it at once.
@@ -663,7 +673,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
663
673
  if (name === 'testTimeout' && !(Number.isInteger(value) && value >= 1 && value <= 600)) throw new Error('test timeout: a whole number of seconds, 1 to 600')
664
674
  if (name === 'replyStart' && !(Number.isInteger(value) && value >= 5 && value <= 600)) throw new Error('a reply must start within: a whole number of seconds, 5 to 600')
665
675
  if (!['permissions', 'effort', 'theme', 'context', 'logDetail', 'logDays', 'testTimeout', 'modelChoice', 'replyStart', ...Object.keys(TOGGLES)].includes(name)) throw new Error(`no setting "${name}"`)
666
- if (name === 'modelChoice' && !['order', 'fit'].includes(value)) throw new Error('modelChoice: order or fit')
676
+ if (name === 'modelChoice' && !['order', 'fit'].includes(value)) throw new Error('modelChoice: order or fit (an orchestrator)')
667
677
  cfg[name] = name === 'effort' && value === 'default' ? undefined : name === 'context' ? (value === null ? undefined : Number(value)) : value
668
678
  save(`setting:${name}`)
669
679
  if (name === 'logDetail') useRequestLog(cfg) // from the next request (a running HeartCode takes it in too: applySettings)
package/src/tools.js CHANGED
@@ -218,12 +218,25 @@ function readImage(s, p) {
218
218
  export function searchFiles(root, query, sub = '', limit = 50) {
219
219
  const ci = query === query.toLowerCase()
220
220
  let re
221
+ let literal = false // not a valid regular expression: searched as the text it is
221
222
  try {
222
223
  re = new RegExp(query, ci ? 'i' : '')
223
224
  } catch {
224
225
  re = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), ci ? 'i' : '')
226
+ literal = true
227
+ }
228
+ // a pattern given as the path ("src/*.css", "**/*.ts"): the folder before it, and its files that fit
229
+ let only = null
230
+ const pattern = sub
231
+ if (/[*?]/.test(sub)) {
232
+ const parts = String(sub).split(/[\\/]/)
233
+ const at = parts.findIndex((p) => /[*?]/.test(p))
234
+ const glob = parts.slice(at).filter((p) => p !== '**').join('/') || '*'
235
+ only = new RegExp(`(^|/)${glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]')}$`)
236
+ sub = parts.slice(0, at).join('/')
225
237
  }
226
238
  const abs = sub ? resolveIn(root, sub, true) : ''
239
+ if (abs && !fs.existsSync(abs)) return `error: ${sub} doesn't exist, so nothing was searched (this is not "no matches"). Give a file or folder that exists, or leave path out to search the whole project.`
227
240
  const away = abs && abs !== root && !abs.startsWith(root + path.sep) && !isSavedOutput(abs) // a folder the user named outside the project
228
241
  let single = false // one file named: searched whatever lists leave out (a saved page, a .gitignored file)
229
242
  try {
@@ -232,8 +245,11 @@ export function searchFiles(root, query, sub = '', limit = 50) {
232
245
  const saved = isSavedOutput(abs) || single
233
246
  const prefix = sub && !saved && !away ? path.relative(root, abs) : ''
234
247
  const hits = []
248
+ let searched = 0
235
249
  for (const f of saved ? [abs] : away ? listFiles(abs).map((f) => path.join(abs, f)) : listFiles(root)) {
236
250
  if (prefix && f !== prefix && !f.startsWith(prefix + '/')) continue
251
+ if (only && !only.test(f)) continue
252
+ searched++
237
253
  let buf
238
254
  try {
239
255
  buf = fs.readFileSync(path.resolve(root, f))
@@ -248,7 +264,8 @@ export function searchFiles(root, query, sub = '', limit = 50) {
248
264
  if (hits.length >= limit) return hits.join('\n') + `\n… (stopped at ${limit} matches)`
249
265
  }
250
266
  }
251
- return hits.join('\n') || `no matches for ${query}`
267
+ if (hits.length) return hits.join('\n')
268
+ return searched ? `no matches for ${query} in ${searched} file${searched === 1 ? '' : 's'} searched${literal ? ' (as plain text: it isn\'t a valid regular expression)' : ''}` : `nothing was searched: no files${only ? ` fit ${pattern}` : ''} in ${sub || 'the project'} (this is not "no matches")`
252
269
  }
253
270
 
254
271
  // Runs a shell command in its own process group. The command is over when its shell exits, even
@@ -295,11 +312,12 @@ export function runCommand(root, cmd, { signal, timeout = 120_000, stdin, env, s
295
312
  child.stdout.destroy()
296
313
  child.stderr.destroy()
297
314
  const plain = (t) => t.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '')
298
- resolve({ code, output: plain(out) + note, ...(split && { stderr: plain(err) }) })
315
+ resolve({ code, output: (dropped ? '(the start of a very long output was left out: only its last 100,000 characters are here; the command itself was not affected)\n…' : '') + plain(out) + note, ...(split && { stderr: plain(err) }) })
299
316
  }
317
+ let dropped = false // a very long output's start, left out (said, so it isn't read as the command failing)
300
318
  const add = (d) => {
301
319
  out += d
302
- if (out.length > 200_000) out = out.slice(-100_000)
320
+ if (out.length > 200_000) (out = out.slice(-100_000)), (dropped = true)
303
321
  }
304
322
  const addErr = (d) => {
305
323
  err += d
@@ -332,6 +350,38 @@ export function suggestCommands(root) {
332
350
  return out.slice(0, 9)
333
351
  }
334
352
 
353
+ // What the model changed in files: this message's (or with all, the conversation's), each file from
354
+ // before its first change to now (the turns keep that first version for /rewind; /diff shows the same).
355
+ function changesTool(s, args) {
356
+ const turns = args.all ? (s.chat?.turns ?? []) : (s.chat?.turns ?? []).slice(-1)
357
+ const first = new Map()
358
+ for (const t of turns) for (const [rel, before] of Object.entries(t.files ?? {})) if (!first.has(rel)) first.set(rel, before)
359
+ const want = String(args.path ?? '').trim().replace(/^\.\//, '')
360
+ const out = []
361
+ for (const rel of [...first.keys()].filter((f) => !want || f === want || f.endsWith('/' + want)).sort()) {
362
+ const abs = path.join(s.root, rel)
363
+ const now = fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null
364
+ const was = first.get(rel)
365
+ if (was === now) continue
366
+ out.push(was === null ? `${rel} (new)\n${renderDiff(diffLines('', now), rel, false, 3, 400)}` : now === null ? `${rel} (deleted)` : renderDiff(diffLines(was, now), rel, false, 3, 400))
367
+ }
368
+ const where = args.all ? 'in this conversation' : 'for this message'
369
+ return out.join('\n\n') || (want ? `No changes to ${want} ${where}.` : `No file changes ${where}${first.size ? ' (the files you changed are back as they were)' : ''}.`)
370
+ }
371
+
372
+ // A "no" from the user, with what they typed instead. Their words go to the model as their own message,
373
+ // after the tool results (s.userSaid, which the agent sends): inside a result a model reads them as the
374
+ // tool talking, and tries again. Where there's no queue (guided mode) or no user (headless: the "no" is
375
+ // HeartCode's), they stay in the result.
376
+ export function declined(s, ok, what) {
377
+ const said = typeof ok === 'string' ? ok.trim() : ''
378
+ if (said && s.userSaid && !s.ui.noUser) {
379
+ s.userSaid.push(said)
380
+ return `${what} What they want instead is in their message that follows.`
381
+ }
382
+ return `${what}${said ? ` ${s.ui.noUser ? said : `User feedback: ${said}`}` : ''}`
383
+ }
384
+
335
385
  const PLACEHOLDER = /(\.\.\.|…)\s*(rest|existing|remaining|unchanged|other)|rest of (the )?(code|file)|existing code (here|unchanged)/i
336
386
 
337
387
  // Shows the diff, asks the user, writes (next = null: deletes the file). Shared by both agent modes.
@@ -343,7 +393,7 @@ export async function proposeWrite(s, rel, old, next) {
343
393
  if (next !== null && PLACEHOLDER.test(next) && !PLACEHOLDER.test(old)) s.ui.warn('the new content seems to contain a placeholder like "rest of code unchanged"')
344
394
  const ok = await s.ui.confirm(next === null ? `Delete ${rel}?` : old ? `Apply this change to ${rel}?` : `Create ${rel}?`)
345
395
  log('write', rel, ok === true ? 'approved' : `rejected ${typeof ok === 'string' ? ok : ''}`)
346
- if (ok !== true) return { status: 'rejected', feedback: typeof ok === 'string' ? ok : '' }
396
+ if (ok !== true) return { status: 'rejected', said: declined(s, ok, '') }
347
397
  const abs = resolveIn(s.root, rel)
348
398
  s.track?.(rel, fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null) // for /rewind
349
399
  if (next === null) fs.rmSync(abs, { force: true })
@@ -426,7 +476,7 @@ export async function runConfirmed(s, cmd, signal, background = false, wait) {
426
476
  return prompt('agent/command-too-wide', { root: s.root })
427
477
  }
428
478
  const ok = s.ui.permission === 'plan' ? true : await s.ui.confirm(`Run ${c.bold(cmd)}?`, 'command') // plan mode: only read-only ones get here
429
- if (ok !== true) return `The user declined to run this command.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
479
+ if (ok !== true) return declined(s, ok, 'The user declined to run this command.')
430
480
  const secs = Number(wait) > 0 ? Number(wait) : background ? 3 : 30
431
481
  const before = snapshot(s)
432
482
  s.ui.spinner(`running ${cmd}`)
@@ -531,7 +581,7 @@ function changesSince(s, before) {
531
581
  export function writeResult(rel, r) {
532
582
  if (r.status === 'applied') return `${r.deleted ? 'Deleted' : 'Changed'} ${rel} (${r.summary}).${r.note ? `\n${r.note}` : ''}`
533
583
  if (r.status === 'unchanged') return `No change: the new content of ${rel} is identical to the old content.`
534
- return `The user rejected the change to ${rel}.${r.feedback ? ' User feedback: ' + r.feedback : ''}`
584
+ return r.feedback ? r.feedback : `The user rejected the change to ${rel}.${r.said ?? ''}`
535
585
  }
536
586
 
537
587
  // --- native tool calling ---
@@ -543,6 +593,7 @@ const obj = (properties, required = []) => ({ type: 'object', properties, requir
543
593
  export const TOOL_DEFS = [
544
594
  { name: 'read_file', description: prompt('agent/tool-read_file'), parameters: obj({ path: str, start_line: int, end_line: int }, ['path']) },
545
595
  { name: 'search', description: prompt('agent/tool-search'), parameters: obj({ query: str, path: str }, ['query']) },
596
+ { name: 'changes', description: prompt('agent/tool-changes'), parameters: obj({ path: str, all: { type: 'boolean' } }) },
546
597
  { name: 'list_files', description: prompt('agent/tool-list_files'), parameters: obj({ path: str, filter: str }) },
547
598
  { name: 'find_command', description: prompt('agent/tool-find_command'), parameters: obj({ names: { type: 'array', items: str } }, ['names']) },
548
599
  { name: 'lsp', description: prompt('agent/tool-lsp'), parameters: obj({ server: str, language: str, action: { type: 'string', enum: ['definition', 'references', 'hover', 'errors'] }, file: str, line: int, column: int, name: str }, ['server', 'language', 'action', 'file']) },
@@ -627,9 +678,9 @@ export function extraTools(s) {
627
678
  }
628
679
  if (!s.isSub && s.subagent) {
629
680
  const team = s.team?.() ?? []
630
- const model = { type: 'string', description: prompt('agent/tool-agent-model') }
681
+ const model = { type: 'string', description: prompt(s.orchestrating ? 'agent/tool-hand-model' : 'agent/tool-agent-model') }
631
682
  const images = { type: 'array', items: str, description: prompt('agent/tool-agent-images') }
632
- out.push({ name: 'agent', description: prompt('agent/tool-agent'), parameters: obj({ description: str, prompt: str, ...(team.length && { model, images }) }, ['description', 'prompt']) })
683
+ out.push({ name: 'agent', description: prompt(s.orchestrating ? 'agent/tool-hand' : 'agent/tool-agent'), parameters: obj({ description: str, prompt: str, ...(team.length && { model, images }) }, ['description', 'prompt']) })
633
684
  }
634
685
  return [...out, ...(s.director && !s.appendSystem ? s.director.toolDefs(s) : [])] // manage (director.js); not when a program gives the instructions (--append-system-prompt)
635
686
  }
@@ -737,7 +788,7 @@ async function webTool(s, name, args, signal) {
737
788
  const what = name === 'web_search' ? String(args.query ?? '') : String(args.url ?? '')
738
789
  if (!what.trim()) return `error: ${name} needs ${name === 'web_search' ? '"query"' : '"url"'}`
739
790
  const ok = await s.ui.confirm(name === 'web_search' ? `Search the web for ${c.bold(what)}?` : `Fetch ${c.bold(what)}?`, 'read')
740
- if (ok !== true) return `The user declined this.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
791
+ if (ok !== true) return declined(s, ok, 'The user declined this.')
741
792
  // what this message's research is for: the page's look_for, else the last search, else the task
742
793
  const purpose = String(args.look_for ?? '').trim() || s.lastQuery || String(s.task ?? '').split('\n')[0].slice(0, 160)
743
794
  if (name === 'web_search') {
@@ -949,7 +1000,7 @@ async function callMcp(s, server, tool, a, signal) {
949
1000
  // declines what it would ask, so a browser's snapshot must not be); any other like a command
950
1001
  if (!def?.annotations?.readOnlyHint) {
951
1002
  const ok = await s.ui.confirm(`Use ${server.name} → ${tool}?`, 'command')
952
- if (ok !== true) return `The user declined this call.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
1003
+ if (ok !== true) return declined(s, ok, 'The user declined this call.')
953
1004
  }
954
1005
  const done = await s.mcpGate?.() // a helper may be using the MCP servers (a browser): its turn first
955
1006
  s.ui.spinner(`${server.name} · ${tool}`)
@@ -1269,7 +1320,9 @@ function mcpTarget(s, name) {
1269
1320
 
1270
1321
  // Tools the caller allowed (--allowedTools) or took away (--disallowedTools); all by default. An
1271
1322
  // MCP tool goes by its own name, its server's (mcp__server, as in Claude Code) or "mcp" (all of them).
1323
+ // An orchestrator: only handing work out (and asking the user).
1272
1324
  export function allowed(s, name) {
1325
+ if (s.orchestrating && name !== 'agent' && name !== 'ask_user') return false
1273
1326
  const names = name.startsWith('mcp__') ? [name, name.split('__').slice(0, 2).join('__'), 'mcp'] : [name]
1274
1327
  if (names.some((n) => s.denyTools?.has(n))) return false
1275
1328
  if (!s.allowTools) return true
@@ -1296,6 +1349,8 @@ async function tool(name, args, s, signal, id) {
1296
1349
  }
1297
1350
  case 'search':
1298
1351
  return searchFiles(root, String(args.query ?? ''), args.path)
1352
+ case 'changes':
1353
+ return changesTool(s, args)
1299
1354
  case 'find_command': {
1300
1355
  const names = (Array.isArray(args.names) ? args.names : String(args.names ?? args.name ?? '').split(/[\s,]+/)).map(String).filter(Boolean)
1301
1356
  if (!names.length) return 'error: find_command needs "names": the commands to look for, like ["rg", "pnpm"]'
package/src/update.js CHANGED
@@ -1,4 +1,4 @@
1
- // A newer HeartCode: asked of npm at most once a day (in the background, never waited on), shown in
1
+ // A newer HeartCode: asked of npm at every start (in the background, never waited on), shown in
2
2
  // the status bar, installed with /update the way HeartCode was installed. A git checkout (npm link)
3
3
  // isn't npm-installed over: it's told to git pull.
4
4
  import fs from 'node:fs'
@@ -7,7 +7,6 @@ import { fileURLToPath } from 'node:url'
7
7
  import { HOME, VERSION, readJson, writeJson } from './config.js'
8
8
 
9
9
  const FILE = path.join(HOME, 'update-check.json')
10
- const DAY = 24 * 60 * 60 * 1000
11
10
  const PKG = fileURLToPath(new URL('..', import.meta.url))
12
11
 
13
12
  // "0.1.38" > "0.1.37": numbers compared part by part (a pre-release tag isn't offered)
@@ -17,18 +16,16 @@ export const newer = (a, b) => {
17
16
  return false
18
17
  }
19
18
 
20
- // { current, latest, newer }, or null when npm can't be reached. force: ask now, not from the day's answer.
21
- export async function checkUpdate({ force = false } = {}) {
22
- const was = readJson(FILE, {})
23
- let latest = was.latest
24
- if (force || !latest || Date.now() - (was.checked ?? 0) > DAY) {
25
- try {
26
- const r = await fetch('https://registry.npmjs.org/heartcode/latest', { signal: AbortSignal.timeout(8000) })
27
- latest = (await r.json()).version
28
- writeJson(FILE, { checked: Date.now(), latest })
29
- } catch {
30
- if (!latest) return null
31
- }
19
+ // { current, latest, newer }: npm asked now (its answer kept for the settings page); npm out of
20
+ // reach, its last answer; null when there's none.
21
+ export async function checkUpdate() {
22
+ let latest = readJson(FILE, {}).latest
23
+ try {
24
+ const r = await fetch('https://registry.npmjs.org/heartcode/latest', { signal: AbortSignal.timeout(8000) })
25
+ latest = (await r.json()).version
26
+ writeJson(FILE, { checked: Date.now(), latest })
27
+ } catch {
28
+ if (!latest) return null
32
29
  }
33
30
  return { current: VERSION, latest, newer: Boolean(latest) && newer(latest, VERSION) }
34
31
  }
package/src/fit.js DELETED
@@ -1,65 +0,0 @@
1
- // "Best fit" (modelChoice: 'fit'): for each new message, your models ranked by how good each is at
2
- // what this message needs — by public rankings (rankings.js), not by a model's opinion of models.
3
- // One short request names the skills the task needs (web pages, code, images…); the rest is
4
- // arithmetic: who leads the work (and who next when one fails) and who reviews it (not the lead).
5
- // A model the rankings don't know comes after those they do, in your order. A message that only says to go on keeps the last pick.
6
- // "Your order" (the default): none of this — your list as you set it.
7
- import { prompt } from './prompts.js'
8
- import { log } from './log.js'
9
- import { rankings, score, SKILLS } from './rankings.js'
10
-
11
- const name = (t) => `${t.provider} ${t.model}`
12
- const GO_ON = /^\s*(continue|go on|carry on|keep going|resume|proceed|ok(ay)?|yes|do it|go ahead)\W*$/i
13
-
14
- // The skills this task needs, from SKILLS: { work: [...] } — asked of the model in use (naming
15
- // what a task needs is easy; judging models is what the rankings are for). ['coding'] when it can't say.
16
- async function skillsFor(s, task, signal) {
17
- const ask = prompt('agent/pick-skills', { task: task.slice(0, 1500), choices: (s.chat.choices ?? []).join('; '), skills: Object.entries(SKILLS).map(([k, [, , what]]) => `${k}: ${what}`).join('\n') })
18
- const was = s.client.purpose
19
- s.client.purpose = 'pick-skills'
20
- try {
21
- const said = (await s.client.chat({ messages: [{ role: 'user', content: ask }] }, { signal: AbortSignal.any([AbortSignal.timeout(30_000), ...(signal ? [signal] : [])]) })).content
22
- const line = /^\W*skills?\W*:\s*(.+)$/im.exec(said)?.[1] ?? said
23
- const named = Object.keys(SKILLS).filter((k) => new RegExp(`(^|[^\\w-])${k}($|[^\\w-])`, 'i').test(line))
24
- return named.length ? named : ['coding']
25
- } catch (e) {
26
- if (signal?.aborted) throw e
27
- log('fit', `no skills named (${e.message}): coding`)
28
- return ['coding']
29
- } finally {
30
- s.client.purpose = was
31
- }
32
- }
33
-
34
- // { work, review, why } (names, best first), kept in chat.fit; null when there's nothing to choose.
35
- export async function pickModels(s, task, signal, { images = 0, size = 0 } = {}) {
36
- const all = s.allModels?.() ?? []
37
- const can = all.filter((t) => t.tools && (!images || t.images) && (!size || !t.context || t.context > size * 1.2))
38
- if (can.length < 2) return null
39
- if (GO_ON.test(task) && s.chat.fit) return s.chat.fit // the same work: the same models (and the provider's cache still holds)
40
- const data = await rankings({ signal, onWait: () => s.ui.spinner('getting the model rankings (once a week)') })
41
- s.ui.stopSpin()
42
- if (!data) return null
43
- s.ui.spinner('what does this task need')
44
- const skills = await skillsFor(s, task, signal)
45
- s.ui.stopSpin()
46
- if (images && !skills.includes('vision')) skills.push('vision')
47
- // best first by score; not ranked: after, in your order
48
- const ranked = (models, wanted) =>
49
- models
50
- .map((t, i) => ({ t, i, sc: score(t.model, wanted, data) }))
51
- .sort((a, b) => (a.sc ?? 2) - (b.sc ?? 2) || a.i - b.i)
52
- const order = ranked(can, skills)
53
- const lead = name(order[0].t)
54
- const fit = {
55
- work: order.map((x) => name(x.t)),
56
- review: ranked(can, ['coding', 'hard']).filter((x) => x.sc != null).map((x) => name(x.t)).filter((n) => n !== lead).slice(0, 2),
57
- why: skills.join(', '),
58
- }
59
- log('fit', { skills, scores: order.slice(0, 8).map((x) => `${x.t.model} ${x.sc == null ? 'not ranked' : x.sc.toFixed(2)}`), review: fit.review })
60
- s.chat.fit = fit
61
- return fit
62
- }
63
-
64
- // Others (reviewers, page checkers) in the pick's order, the rest after in your list's order.
65
- export const byPick = (models, names = []) => [...models].sort((a, b) => ((names.indexOf(name(a)) + 1 || 1e9) - (names.indexOf(name(b)) + 1 || 1e9)))