heartcode 0.1.59 → 0.1.60

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
@@ -54,11 +54,11 @@ const DETAILS = ['full', 'summary']
54
54
  // Files in ~/.heart the page edits as text: [name, what it is, JSON?]
55
55
  const FILES = [
56
56
  ['mcp.json', 'MCP servers: programs that give the model more tools', true, '{\n "mcpServers": {\n "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"] },\n "docs": { "url": "https://mcp.example.com/mcp" }\n }\n}'],
57
- ['hooks.json', 'Your commands, run before or after the model uses a tool (one can block it)', true, '{\n "hooks": {\n "PreToolUse": [\n { "matcher": "run_command", "hooks": [{ "type": "command", "command": "./check-command.sh" }] }\n ]\n }\n}'],
58
- ['keybindings.json', 'Your own keys: an action, or a /command to send', true, '{\n "alt+g": "cycle_permissions",\n "alt+r": "/rewind"\n}'],
59
- ['theme.json', 'Your own colors, on top of the theme you chose', true, '{\n "brand": "#ff6b9d",\n "background": "#101014"\n}'],
57
+ ['hooks.json', 'Commands run before or after the model uses a tool (one can block it)', true, '{\n "hooks": {\n "PreToolUse": [\n { "matcher": "run_command", "hooks": [{ "type": "command", "command": "./check-command.sh" }] }\n ]\n }\n}'],
58
+ ['keybindings.json', 'Custom keys: an action, or a /command to send', true, '{\n "alt+g": "cycle_permissions",\n "alt+r": "/rewind"\n}'],
59
+ ['theme.json', 'Custom colors, on top of the chosen theme', true, '{\n "brand": "#ff6b9d",\n "background": "#101014"\n}'],
60
60
  ['format.json', 'The formatter to run on each kind of file HeartCode writes', true, '{\n ".go": "gofmt -w {file}",\n ".py": "ruff format {file}"\n}'],
61
- ['HEARTCODE.md', 'Your instructions for every project (like AGENTS.md, for all of them)', false, '- Answer briefly.\n- Use pnpm, not npm.'],
61
+ ['HEARTCODE.md', 'Instructions for every project (like AGENTS.md, for all of them)', false, '- Answer briefly.\n- Use pnpm, not npm.'],
62
62
  ]
63
63
  // The prompts the page edits: every section of these files (prompts/*.md); the system prompts first.
64
64
  const PROMPT_FILES = ['agent', 'guided', 'compact', 'tests']
@@ -87,7 +87,7 @@ function setPrompt(file, name, text) {
87
87
  else own.set(name, text.trim())
88
88
  if (!own.size) return fs.rmSync(f, { force: true })
89
89
  fs.mkdirSync(path.dirname(f), { recursive: true })
90
- fs.writeFileSync(f, `# ${file}.md: your changes to HeartCode's prompts (the settings page; prompts/README.md in HeartCode)\n\n` + [...own].map(([n, t]) => `## ${n}\n\n${t}\n`).join('\n'))
90
+ fs.writeFileSync(f, `# ${file}.md: changes to HeartCode's prompts (the settings page; prompts/README.md in HeartCode)\n\n` + [...own].map(([n, t]) => `## ${n}\n\n${t}\n`).join('\n'))
91
91
  }
92
92
 
93
93
  // MCP servers: yours (mcp.json), each on or off (an entry with neither command nor url only switched off a
@@ -150,8 +150,16 @@ const LIST_V = 2 // how a saved list was read (2: airforce's cents, Cloudflare's
150
150
  // browser, whose storage is per address (a new port each time)
151
151
  const PREFS = path.join(HOME, 'settings-page.json')
152
152
  const PREF_KEYS = ['catSort', 'freeOnly', 'folded', 'sort', 'sorts', 'rank', 'filters']
153
+ // The saved lists (a MB or more): kept in memory, read again only when the file changes
154
+ let lists = null
155
+ const readLists = () => {
156
+ const st = fs.statSync(LISTS, { throwIfNoEntry: false })
157
+ const at = st ? `${st.mtimeMs}:${st.size}` : ''
158
+ if (lists?.at !== at) lists = { at, all: readJson(LISTS, {}) }
159
+ return lists.all
160
+ }
153
161
  function forgetList(...names) {
154
- const all = readJson(LISTS, {})
162
+ const all = { ...readLists() }
155
163
  if (!names.some((n) => n in all)) return
156
164
  for (const n of names) delete all[n]
157
165
  writeJson(LISTS, all)
@@ -456,7 +464,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
456
464
  rankings: ranked && { fetched: ranked.fetched, source: ranked.source },
457
465
  rotation: (({ then, ...opts }) => opts)(rotationOf(cfg)),
458
466
  helpers: helpersOf(cfg.helpers), // { 'provider/model': [jobs] }
459
- helperOrder: cfg.helperOrder === 'provider' ? 'provider' : 'own', // the order helpers are picked in: your list's, or your provider ranking's
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
460
468
  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
461
469
  jobs: HELPER_JOBS,
462
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) },
@@ -579,7 +587,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
579
587
  const p = cfg.providers[name]
580
588
  if (!p) throw new Error(`no provider "${name}"`)
581
589
  if (p.list === false) return { models: [], details: {}, off: true }
582
- const lists = readJson(LISTS, {})
590
+ const lists = readLists()
583
591
  let saved = lists[name]?.baseUrl === p.baseUrl && lists[name].models?.length && lists[name].v === LIST_V ? lists[name] : null // an empty one, or one read the old way: asked again
584
592
  if (!saved) {
585
593
  const entries = await new Client({ baseUrl: p.baseUrl, apiKey: p.apiKey }).modelEntries()
@@ -592,7 +600,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
592
600
  description: m.description ? String(m.description).slice(0, 400) : undefined,
593
601
  price: listedPrice(m),
594
602
  }])) }
595
- writeJson(LISTS, { ...readJson(LISTS, {}), [name]: saved })
603
+ writeJson(LISTS, { ...readLists(), [name]: saved })
596
604
  }
597
605
  await loadPrices().catch(() => null)
598
606
  // and what's known now: its test or setup, and models.dev
@@ -635,11 +643,12 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
635
643
  save('setting:helpers')
636
644
  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
637
645
  },
638
- // the order helpers are picked in: 'own' (your list's) or 'provider' (your provider ranking's, each
646
+ // the order helpers are picked in: 'own' (your list's), 'provider' (your provider ranking's, each
639
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)
640
649
  'POST /api/helper-order': ({ by, rank }) => {
641
- cfg.helperOrder = by === 'provider' ? 'provider' : undefined
642
- cfg.providerRank = cfg.helperOrder && (Array.isArray(rank) ? rank.filter((x) => typeof x === 'string') : readJson(PREFS, {}).rank)
650
+ cfg.helperOrder = by === 'provider' || by === 'score' ? by : undefined
651
+ cfg.providerRank = cfg.helperOrder === 'provider' ? (Array.isArray(rank) ? rank.filter((x) => typeof x === 'string') : readJson(PREFS, {}).rank) : undefined
643
652
  save('setting:helperOrder')
644
653
  return { helperOrder: cfg.helperOrder ?? 'own' }
645
654
  },
@@ -821,19 +830,19 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
821
830
  // it gets a first message saying so.
822
831
  'POST /api/telegram/connect': async ({ token }) => {
823
832
  const tk = String(token ?? '').trim() || cfg.telegram?.token
824
- if (!tk) throw new Error('paste the token @BotFather gave you')
833
+ if (!tk) throw new Error('paste the token from @BotFather')
825
834
  if (!/^\d+:[\w-]{20,}$/.test(tk)) throw new Error("that doesn't look like a bot token (it's like 123456789:AAH…, from @BotFather)")
826
835
  const r = await connect(tk)
827
836
  const chat = r.chats[0]
828
837
  const was = cfg.telegram?.token === tk ? cfg.telegram : {}
829
838
  cfg.telegram = { ...was, token: tk, bot: r.bot, ...(chat ? { chatId: chat.id, chatName: chat.name } : { chatId: undefined, chatName: undefined }), on: was.on ?? true }
830
839
  save('setting:telegram')
831
- if (chat) await sendTelegram(cfg.telegram, "✅ HeartCode is connected. You'll get a message here when a task finishes, fails, or waits for you.")
840
+ if (chat) await sendTelegram(cfg.telegram, "✅ HeartCode is connected. A message comes here when a task finishes, fails, or waits for an answer.")
832
841
  return { ...state(), found: chat?.name ?? null }
833
842
  },
834
843
  'POST /api/telegram/test': async () => {
835
844
  if (!tgReady({ ...cfg.telegram, on: true })) throw new Error('connect Telegram first')
836
- await sendTelegram(cfg.telegram, '🔔 A test from HeartCode\'s settings: notifications reach you.')
845
+ await sendTelegram(cfg.telegram, '🔔 A test from HeartCode\'s settings: notifications arrive.')
837
846
  return state()
838
847
  },
839
848
  'POST /api/telegram/set': ({ on, event, value }) => {
@@ -876,7 +885,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
876
885
  },
877
886
  'POST /api/search/test': async ({ searxng }) => {
878
887
  const u = String(searxng ?? '').trim() || searchSettings().searxng
879
- if (!u) throw new Error('type your SearXNG address first')
888
+ if (!u) throw new Error('type the SearXNG address first')
880
889
  const n = await testSearxng(/^https?:\/\//i.test(u) ? u : `https://${u}`).catch((e) => {
881
890
  throw new Error(`${u} didn't answer a search: ${e.cause?.code || e.message}`)
882
891
  })
@@ -954,7 +963,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
954
963
  if (fs.existsSync(file) && !readJson(file, null)) throw new Error("mcp.json isn't valid JSON: fix it first")
955
964
  const data = readJson(file, null) ?? {}
956
965
  const c = data.mcpServers?.[name]
957
- if (!c?.command) throw new Error(`no local MCP server "${name}" of yours`)
966
+ if (!c?.command) throw new Error(`no added local MCP server "${name}"`)
958
967
  flag = String(flag ?? '').trim().replace(/\s+/g, ' ')
959
968
  const words = flag.split(' ')
960
969
  if (!/^-/.test(words[0]) || words.length > 2) throw new Error('a flag starts with - (and may have one value: --port 3000)')
@@ -972,7 +981,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
972
981
  'POST /api/mcp/remove': ({ name }) => {
973
982
  const file = path.join(HOME, 'mcp.json')
974
983
  const data = readJson(file, null)
975
- if (!data?.mcpServers?.[name]) throw new Error(`no server "${name}" of yours`)
984
+ if (!data?.mcpServers?.[name]) throw new Error(`no added server "${name}"`)
976
985
  delete data.mcpServers[name]
977
986
  writeJson(file, data)
978
987
  changed('mcp')
@@ -1023,7 +1032,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1023
1032
  return state()
1024
1033
  },
1025
1034
  'POST /api/skill/delete': ({ name }) => {
1026
- if (!removeSkill(name)) throw new Error(`no skill "${name}" of yours`)
1035
+ if (!removeSkill(name)) throw new Error(`no added skill "${name}"`)
1027
1036
  changed('skill')
1028
1037
  return state()
1029
1038
  },
@@ -1133,12 +1142,27 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1133
1142
  loadPrices().then(() => {
1134
1143
  for (const t of state().order) testNews(`${t.provider}/${t.model}`, t)
1135
1144
  test(state().order) // any without a profile yet
1145
+ warm()
1136
1146
  })
1137
1147
  resolve({ url, local, server, close: () => (watcher?.close(), server.closeAllConnections?.(), server.close()) })
1138
1148
  })
1139
1149
  })
1140
1150
  }
1141
1151
 
1152
+ // The saved model lists' models, looked up once in the background (their profiles, models.dev's word),
1153
+ // a few hundred at a time so the page isn't held up: then the Providers page loads at once.
1154
+ function warm() {
1155
+ const all = Object.entries(readLists()).flatMap(([name, l]) => (l.models ?? []).map((id) => [name, l.baseUrl, id]))
1156
+ const step = (i) => {
1157
+ for (const [name, baseUrl, id] of all.slice(i, i + 300)) {
1158
+ loadProfile(new Client({ baseUrl, model: id }))
1159
+ limitsOf(name, baseUrl, id)
1160
+ }
1161
+ if (i + 300 < all.length) setImmediate(() => step(i + 300))
1162
+ }
1163
+ step(0)
1164
+ }
1165
+
1142
1166
  // This machine's IPv4 addresses on its networks (Wi-Fi, Ethernet, a VPN), not the loopback one
1143
1167
  const addresses = () => Object.values(os.networkInterfaces()).flat().filter((n) => n && n.family === 'IPv4' && !n.internal).map((n) => n.address)
1144
1168
 
package/src/telegram.js CHANGED
@@ -10,7 +10,7 @@ const API = process.env.HEART_TELEGRAM_API || 'https://api.telegram.org' // the
10
10
  export const EVENTS = {
11
11
  done: 'A task finished',
12
12
  failed: 'A task failed',
13
- waiting: 'HeartCode is waiting for you (a question or a permission)',
13
+ waiting: 'HeartCode is waiting for an answer (a question or a permission)',
14
14
  }
15
15
 
16
16
  async function call(token, method, body = {}, timeout = 15_000) {
package/src/tools.js CHANGED
@@ -622,7 +622,7 @@ export const TOOL_DEFS = [
622
622
  { name: 'write_file', get description() { return prompt('agent/tool-write_file') }, parameters: obj({ path: str, content: str, append: { type: 'boolean' } }, ['path', 'content']) },
623
623
  { name: 'run_command', get description() { return prompt('agent/tool-run_command') }, parameters: obj({ command: str, wait: int, background: { type: 'boolean' } }, ['command']) },
624
624
  { name: 'background', get description() { return prompt('agent/tool-background') }, parameters: obj({ action: { type: 'string', enum: ['output', 'list', 'stop'] }, id: int, wait: int }, ['action']) },
625
- { name: 'todo', get description() { return prompt('agent/tool-todo') }, parameters: obj({ todos: { type: 'array', items: obj({ content: str, status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] }, parallel: { type: 'boolean' }, model: str, files: { type: 'array', items: str } }, ['content', 'status']) } }, ['todos']) },
625
+ { name: 'todo', get description() { return prompt('agent/tool-todo') }, parameters: obj({ todos: { type: 'array', items: obj({ content: str, status: { type: 'string', enum: ['pending', 'in_progress', 'completed', 'stuck'] }, why: str, parallel: { type: 'boolean' }, model: str, files: { type: 'array', items: str } }, ['content', 'status']) } }, ['todos']) },
626
626
  { name: 'web_search', get description() { return prompt('agent/tool-web_search') }, parameters: obj({ query: str, fresh: { type: 'boolean' } }, ['query']) },
627
627
  { name: 'web_fetch', get description() { return prompt('agent/tool-web_fetch') }, parameters: obj({ url: str, look_for: str, start: int }, ['url']) },
628
628
  { name: 'ask_user', get description() { return prompt('agent/tool-ask_user') }, parameters: obj({ question: str, header: str, options: { type: 'array', items: str }, multiple: { type: 'boolean' }, emphasis: { type: 'boolean' } }, ['question', 'options']) }, // one question a call (small models manage that); several calls in one reply are one dialog (agent.js)
@@ -707,22 +707,22 @@ export function extraTools(s) {
707
707
 
708
708
  // todo: the model's checklist for this message, shown to the user each time it changes.
709
709
  // Lenient: the list as JSON text, plain strings for items, "done" for completed.
710
- const MARK = { pending: '☐', in_progress: '◐', completed: '☑' }
710
+ const MARK = { pending: '☐', in_progress: '◐', completed: '☑', stuck: '⚠' }
711
711
  // In the conversation: the whole plan when it's new (or its steps changed), else only the steps whose
712
712
  // status changed, on one line; the whole of it stays in sight under the spinner (full screen).
713
713
  // the plan for a program reading HeartCode (headless stream-json): its steps, and who's doing a part
714
- export const sendTodos = (s) => !s.isSub && s.ui.event?.({ subtype: 'todos', todos: (s.chat.todos ?? []).map(({ content, status, by, byProvider }) => ({ content, status, ...(by && { by: byProvider ? `${byProvider}/${by}` : by }) })) })
714
+ export const sendTodos = (s) => !s.isSub && s.ui.event?.({ subtype: 'todos', todos: (s.chat.todos ?? []).map(({ content, status, why, by, byProvider }) => ({ content, status, ...(why && { why }), ...(by && { by: byProvider ? `${byProvider}/${by}` : by }) })) })
715
715
  function showTodos(s, before, todos) {
716
- const paint = { pending: c.muted, in_progress: (x) => c.info(c.bold(x)), completed: (x) => c.faint(x) }
717
- const item = (t) => paint[t.status](`${MARK[t.status]} ${t.content}`) + (t.by ? c.faint(` · ${t.by}`) : '')
716
+ const paint = { pending: c.muted, in_progress: (x) => c.info(c.bold(x)), completed: (x) => c.faint(x), stuck: (x) => c.warn(x) }
717
+ const item = (t) => paint[t.status](`${MARK[t.status]} ${t.content}`) + (t.status === 'stuck' && t.why ? c.warn(`: ${clip(t.why, 80)}`) : '') + (t.by ? c.faint(` · ${t.by}`) : '')
718
718
  // full screen, the same plan changed (most of its steps still in it): only what changed, on one line
719
719
  // (steps added, taken out, or whose status moved); the whole plan is pinned under the spinner
720
- const was = new Map((before ?? []).map((t) => [t.content, t.status]))
720
+ const was = new Map((before ?? []).map((t) => [t.content, `${t.status}${t.why ?? ''}`]))
721
721
  const kept = todos.filter((t) => was.has(t.content)).length
722
722
  if (!s.ui.full || !before?.length || kept < Math.max(1, todos.length / 2)) return s.ui.print(todos.map((t) => ` ${item(t)}`).join('\n') || c.faint(' (todo list cleared)'))
723
723
  const now = new Set(todos.map((t) => t.content))
724
724
  const changes = [
725
- ...todos.filter((t) => was.get(t.content) !== t.status).map((t) => (was.has(t.content) ? item(t) : `${c.faint('+')} ${item(t)}`)),
725
+ ...todos.filter((t) => was.get(t.content) !== `${t.status}${t.why ?? ''}`).map((t) => (was.has(t.content) ? item(t) : `${c.faint('+')} ${item(t)}`)),
726
726
  ...(before ?? []).filter((t) => !now.has(t.content)).map((t) => c.faint(`− ${t.content}`)),
727
727
  ]
728
728
  if (changes.length) s.ui.print(` ${changes.join(c.faint(' · '))}`)
@@ -738,14 +738,22 @@ async function todoTool(s, args, signal, id) {
738
738
  }
739
739
  if (!Array.isArray(list)) return 'error: todos must be a list of {content, status}'
740
740
  const todos = list
741
- .map((t) => (typeof t === 'string' ? { content: t, status: 'pending' } : { content: String(t?.content ?? t?.task ?? t?.title ?? ''), status: String(t?.status ?? 'pending'), ...(t?.model && { model: String(t.model) }), ...((t?.parallel === true || t?.parallel === 'true') && { parallel: true }), ...([t?.files ?? []].flat().filter(Boolean).length && { files: [t.files].flat().map(String) }) }))
741
+ .map((t) => (typeof t === 'string' ? { content: t, status: 'pending' } : { content: String(t?.content ?? t?.task ?? t?.title ?? ''), status: String(t?.status ?? 'pending'), ...(t?.why && { why: String(t.why).trim() }), ...(t?.model && { model: String(t.model) }), ...((t?.parallel === true || t?.parallel === 'true') && { parallel: true }), ...([t?.files ?? []].flat().filter(Boolean).length && { files: [t.files].flat().map(String) }) }))
742
742
  .filter((t) => t.content.trim())
743
- .map((t) => ({ ...t, status: /done|complete/i.test(t.status) ? 'completed' : /progress|doing|active/i.test(t.status) ? 'in_progress' : 'pending' }))
743
+ .map((t) => ({ ...t, status: /stuck|block|fail|struggl/i.test(t.status) ? 'stuck' : /done|complete/i.test(t.status) ? 'completed' : /progress|doing|active/i.test(t.status) ? 'in_progress' : 'pending' }))
744
+ .map(({ why, ...t }) => (t.status === 'stuck' ? { ...t, why: why || 'no reason given' } : t)) // a reason only on a stuck step
744
745
  for (const t of todos) Object.assign(t, ((x) => (x?.by && !t.by ? { by: x.by, byProvider: x.byProvider } : {}))(s.chat.todos?.find((x) => x.content === t.content))) // the model a part was given to: kept when the plan is written again
746
+ // newly stuck (or stuck for a new reason): the model says it's struggling. Counted per message; not
747
+ // the same stuck step sent again with the rest of the list
748
+ const before = new Map((s.chat.todos ?? []).map((t) => [t.content, t]))
749
+ const newlyStuck = todos.filter((t) => t.status === 'stuck' && !(before.get(t.content)?.status === 'stuck' && before.get(t.content)?.why === t.why))
745
750
  showTodos(s, s.chat.todos, todos)
746
751
  s.chat.todos = todos
747
752
  sendTodos(s)
748
753
  s.todoTouched = true
754
+ // a step it said it was stuck on, now done: what got it out is worth learning (agent.js)
755
+ for (const t of todos) if (t.status === 'completed' && before.get(t.content)?.status === 'stuck') (s.unstuck ??= []).push({ step: t.content, why: before.get(t.content).why })
756
+ if (newlyStuck.length) return `Todo list saved: ${todos.filter((x) => x.status === 'completed').length} of ${todos.length} done.\n\n${await stuckSaid(s, newlyStuck[0].content, newlyStuck[0].why, signal, id)}`
749
757
  const parts = await runParts(s, todos, signal, id)
750
758
  const done = todos.filter((t) => t.status === 'completed').length
751
759
  const next = todos.find((t) => t.status !== 'completed')
@@ -760,6 +768,51 @@ async function todoTool(s, args, signal, id) {
760
768
  return `Todo list saved: ${done} of ${todos.length} done.${next ? ` Next: ${next.content}` : ''}${parts ? `\n\n${parts}` : ''}${check}`
761
769
  }
762
770
 
771
+ // The model says it's stuck on a step (todo status "stuck", with why). Believed: a model rarely says
772
+ // so when it isn't (a "done" is what gets checked). The 1st time this message: told to change its
773
+ // approach; the 2nd: a second opinion from another of your models (a Big & hard helper first),
774
+ // which looks into it without changing files; the 3rd: the next of your models takes over (agent.js).
775
+ // Also when its final answer says it didn't manage (agent.js). Returns what to tell it.
776
+ export async function stuckSaid(s, step, why, signal, id, answer = false) {
777
+ const t = { content: step, why }
778
+ const n = (s.stuckReports = (s.stuckReports ?? 0) + 1)
779
+ const say = (more = {}) => (more.last && (s.toldLast = true), prompt('agent/stuck', { why, last: false, advice: '', adviser: '', ...more, plain: !answer && !more.advice && !more.last, answer: answer && !more.advice && !more.last }))
780
+ log('stuck', `${s.client?.model} says it's stuck (${n}): ${t.content} — ${t.why}`)
781
+ s.ui.event?.({ subtype: 'stuck', step: t.content, why: t.why, count: n, model: `${s.client?.provider}/${s.client?.model}` })
782
+ if (!s.isSub) (s.troubles ??= []).push({ model: s.client?.model, step: t.content, why: t.why })
783
+ // models it could go to: yours, not this one, not one given up on this message
784
+ const r = s.client?.rotation
785
+ const others = (r?.list ?? []).filter((x) => x !== r.list[r.at] && !s.gaveUp?.has(`${x.provider}/${x.model}`)).length
786
+ if (n >= 3 && !s.isSub && others) {
787
+ // two models have taken over already this message: no more; it says plainly what blocks it
788
+ if ((s.stuckHandovers ?? 0) >= 2) return say({ last: true })
789
+ s.stuckSelf = `said it's stuck ${n} times (last: "${clip(t.content, 60)}": ${clip(t.why, 120)})`
790
+ return '(Noted. Another of your models takes over from here.)'
791
+ }
792
+ if (n >= 3 && !s.isSub) return say({ last: true }) // no model left to take over (or the others were stuck too): it says plainly what blocks it
793
+ let advice = ''
794
+ const other = n === 2 && !s.isSub && s.subagent && secondOpinionModel(s)
795
+ if (other) {
796
+ s.ui.step('stuck', `asking ${other.model} for a second opinion`)
797
+ const tried = (s.ran ?? []).slice(-12).map((r) => `- ${r.command} → ${r.result}`).join('\n')
798
+ try {
799
+ advice = await s.subagent({ prompt: prompt('agent/second-opinion', { task: s.task ?? '', step: t.content, why: t.why, tried }), model: `${other.provider} ${other.model}`, description: 'second opinion' }, signal, id)
800
+ } catch (e) {
801
+ if (e.name === 'AbortError' || signal?.aborted) throw e
802
+ advice = `error: ${e.message}`
803
+ }
804
+ if (failed(advice)) advice = ''
805
+ }
806
+ return say({ advice: clip(advice, 4000), adviser: other ? `${other.provider} ${other.model}` : '' })
807
+ }
808
+ // Another of your models for a second opinion: a Big & hard helper, else your first helper or model that isn't this one.
809
+ function secondOpinionModel(s) {
810
+ const me = (t) => t.model === s.client?.model && (t.provider ?? s.client?.provider) === s.client?.provider
811
+ const team = (s.team?.() ?? []).filter((t) => !me(t) && !s.gaveUp?.has(`${t.provider ?? s.client?.provider}/${t.model}`))
812
+ const helpers = team.filter((t) => t.jobs)
813
+ return helpers.find((t) => t.jobs.includes('hard')) ?? helpers[0] ?? (team.some((t) => t.jobs) ? null : team[0]) ?? null
814
+ }
815
+
763
816
  // The plan's parts marked parallel (or given to another model): each started at once as a helper
764
817
  // on its model, all at the same time, each changing only the files its part owns; marked done when
765
818
  // it reports back. What they did, for the model to put together and check. '' when none.
@@ -825,7 +878,7 @@ async function askUser(s, args) {
825
878
  s.askedUser = true // asked through the dialog this message (not as text: see askedInText)
826
879
  for (const q of qs) {
827
880
  q.items[0].desc = ['recommended', q.items[0].desc].filter(Boolean).join(' · ')
828
- q.own = { label: 'Something else', desc: 'type your own answer', own: true }
881
+ q.own = { label: 'Something else', desc: 'type an answer', own: true }
829
882
  }
830
883
  s.ui.stopSpin()
831
884
  const tabbed = qs.length > 1 && s.ui.full
@@ -841,7 +894,7 @@ async function askUser(s, args) {
841
894
  // the last tab: every answer, sent with Enter (or after ASK_WAIT seconds)
842
895
  const body = qs.map((q, j) => `${q.question} ${c.faint('›')} ${answerOf(said[j]) || `${q.items[0].label} ${c.faint('(recommended)')}`}`).join('\n')
843
896
  const send = { label: 'Send answers', desc: 'or ← to change one' }
844
- const got = await s.ui.pick('Send these answers?', [send], { body, tabs: tabs(i), nav: true, quiet: true, auto: { item: send, secs: ASK_WAIT, say: 'your answers are sent' } })
897
+ const got = await s.ui.pick('Send these answers?', [send], { body, tabs: tabs(i), nav: true, quiet: true, auto: { item: send, secs: ASK_WAIT, say: 'the answers are sent' } })
845
898
  if (got?.nav) {
846
899
  i = Math.min(qs.length, Math.max(0, i + got.nav)) // → on Send: stays there
847
900
  continue
@@ -864,8 +917,8 @@ async function askUser(s, args) {
864
917
  let text = ''
865
918
  if (list.some((x) => x.own)) {
866
919
  // typed in its row (full screen); without full screen, asked for now
867
- text = q.own.text?.trim() || ((await s.ui.ask(`${c.bold('Your answer')} ${c.dim('›')} `, { initial: said[i]?.text ?? '' }))?.trim() ?? '')
868
- Object.assign(q.own, { text, desc: text ? `› ${text}` : 'type your own answer' })
920
+ text = q.own.text?.trim() || ((await s.ui.ask(`${c.bold('Answer')} ${c.dim('›')} `, { initial: said[i]?.text ?? '' }))?.trim() ?? '')
921
+ Object.assign(q.own, { text, desc: text ? `› ${text}` : 'type an answer' })
869
922
  if (!text && list.length === 1) continue // nothing typed: the same question again
870
923
  }
871
924
  if (s.ui.autoPicked) {
@@ -1161,6 +1214,7 @@ async function callMcp(s, server, tool, a, signal) {
1161
1214
  }
1162
1215
  note = `\n(${s.pendingImages.length - shown} image(s): shown to you in the next message${left.length ? `; not shown: ${left.join('; ')}` : ''})`
1163
1216
  } else if (files.length && s.team?.().some((t) => t.images)) note = `\n${prompt('agent/tool-images', { files: files.join('\n'), unseen: true })}`
1217
+ else if (files.length && s.describeFor) note = `\n${await s.describeFor(files).catch((e) => `(couldn't have the image(s) described: ${e.message})`)}`
1164
1218
  else if (files.length) note = `\n(${files.length} image(s) not shown: this model can't see images)`
1165
1219
  const mendNote = mended.fixed.length ? `\n(HeartCode corrected the arguments: ${mended.fixed.join('; ')}. Use them that way next time.)` : ''
1166
1220
  return `${r.isError ? 'error: ' : ''}${text || '(no text)'}${note}${mendNote}`
package/src/tree.js CHANGED
@@ -82,7 +82,7 @@ export function treeItems(chat, ago = (x) => x) {
82
82
  const files = Object.keys(n.turn.files ?? {}).length
83
83
  items.push({
84
84
  label: `${lead}${fork ? (i === kids.length - 1 ? '└─ ' : '├─ ') : ''}${n.turn.task.split('\n')[0].slice(0, 70)}`,
85
- desc: [ago(n.turn.at), files && `${files} file${files > 1 ? 's' : ''}`, here && '● you are here', !here && n.ends && '◆ end of a branch'].filter(Boolean).join(' · '),
85
+ desc: [ago(n.turn.at), files && `${files} file${files > 1 ? 's' : ''}`, here && '● current', !here && n.ends && '◆ end of a branch'].filter(Boolean).join(' · '),
86
86
  depth: d,
87
87
  task: n.turn.task,
88
88
  branch: mine.branch,
package/src/ui.js CHANGED
@@ -898,7 +898,7 @@ export class UI {
898
898
  const own = pick?.items.some((x) => x.own) // typing goes into "Something else", not a filter
899
899
  const typingOwn = m.items[m.sel]?.item?.own && m.items[m.sel].item.text // ←/→ move in what's typed; Tab goes on
900
900
  const body = pick?.body ? String(pick.body).split('\n') : []
901
- const hint = (pick?.nav ? (typingOwn ? 'Tab questions · ' : '←→ questions · ') : '') + (pick ? (pick.ctrlC ? 'Enter, Esc or Ctrl+C turn it off' : pick.fixed ? '↑↓ move · Enter choose · Esc close' : pick.multi ? `↑↓ move · Space tick · Alt+A/N all/none · Enter take · Esc cancel · ${own ? 'type your own' : 'type to filter'}` : `↑↓ move · Enter choose · Esc cancel${own ? ' · type your own' : cards ? '' : ' · type to filter'}`) : 'Enter send · Esc cancel')
901
+ const hint = (pick?.nav ? (typingOwn ? 'Tab questions · ' : '←→ questions · ') : '') + (pick ? (pick.ctrlC ? 'Enter, Esc or Ctrl+C turn it off' : pick.fixed ? '↑↓ move · Enter choose · Esc close' : pick.multi ? `↑↓ move · Space tick · Alt+A/N all/none · Enter take · Esc cancel · ${own ? 'type an answer' : 'type to filter'}` : `↑↓ move · Enter choose · Esc cancel${own ? ' · type an answer' : cards ? '' : ' · type to filter'}`) : 'Enter send · Esc cancel')
902
902
  const timer = this.autoLine() // on its own line, so it's seen (and not cut off with the keys)
903
903
  const long = width(title) > this.#dialogBox(cols, rows).w - 6 // too long for the border: inside instead, said once
904
904
  // at most n rows; the rest said to be there
@@ -974,9 +974,9 @@ export class UI {
974
974
  const open = todos.filter((t) => t.status !== 'completed')
975
975
  if (!open.length) return []
976
976
  const done = todos.length - open.length
977
- const mark = { pending: c.muted('☐'), in_progress: c.info('◐'), completed: c.faint('☑') }
977
+ const mark = { pending: c.muted('☐'), in_progress: c.info('◐'), completed: c.faint('☑'), stuck: c.warn('⚠') }
978
978
  const by = (t) => (t.by ? c.faint(' · ') + (t.status === 'in_progress' ? c.info(t.by) : c.faint(t.by)) : '') // the model a part was given to
979
- const line = (t) => fit(` ${mark[t.status]} ${t.status === 'in_progress' ? c.info(c.bold(t.content)) : t.status === 'completed' ? c.faint(t.content) : c.muted(t.content)}${by(t)}`, cols)
979
+ const line = (t) => fit(` ${mark[t.status]} ${t.status === 'in_progress' ? c.info(c.bold(t.content)) : t.status === 'completed' ? c.faint(t.content) : t.status === 'stuck' ? c.warn(t.content) : c.muted(t.content)}${by(t)}`, cols)
980
980
  const shown = todos.length <= 8 ? todos : open.slice(0, 7)
981
981
  return [
982
982
  fit(` ${c.muted('Plan')} ${c.faint(`· ${done} of ${todos.length} done`)}`, cols),
@@ -1233,7 +1233,7 @@ export class UI {
1233
1233
  this.render()
1234
1234
  }
1235
1235
  #copied(text) {
1236
- this.notice(`copied ${text.length} character${text.length === 1 ? '' : 's'}${copyText(text) === 'osc' ? ' (if your terminal allows it)' : ''}`)
1236
+ this.notice(`copied ${text.length} character${text.length === 1 ? '' : 's'}${copyText(text) === 'osc' ? ' (if the terminal allows it)' : ''}`)
1237
1237
  }
1238
1238
  // A double click: the word under it (no spaces; quotes and brackets around it left out), copied.
1239
1239
  #copyWord(x, y) {
@@ -1408,7 +1408,7 @@ export class UI {
1408
1408
  if (helpers.length > 6) bottom.push(c.faint(` … ${helpers.length - 5} more`))
1409
1409
  bottom.push(...this.#todoLines(cols))
1410
1410
  }
1411
- if (this.scroll) bottom.push(c.dim(` ↓ ${Number.isFinite(this.scroll) ? this.scroll : 'more'} lines below · held here while you read${this.keyFor('scroll_bottom') ? ` · ${this.keyFor('scroll_bottom')} to the bottom` : ''}`))
1411
+ if (this.scroll) bottom.push(c.dim(` ↓ ${Number.isFinite(this.scroll) ? this.scroll : 'more'} lines below · held here for reading${this.keyFor('scroll_bottom') ? ` · ${this.keyFor('scroll_bottom')} to the bottom` : ''}`))
1412
1412
  if (this.ahead.length) {
1413
1413
  const key = (k, d) => `${c.muted(k)} ${c.faint(d)}`
1414
1414
  const sep = c.ghost(' · ')
@@ -1611,7 +1611,7 @@ export class UI {
1611
1611
  const onOwn = own && it?.item === own
1612
1612
  const typing = own && !key.ctrl && !key.meta && ((key.name === 'backspace' && onOwn) || (/^[^\x00-\x1f\x7f]+$/.test(s ?? '') && !(key.name === 'space' && m.pick.multi && !onOwn)))
1613
1613
  if (typing) {
1614
- own.hint ??= own.text ? 'type your own answer' : own.desc // what it says before anything's typed
1614
+ own.hint ??= own.text ? 'type an answer' : own.desc // what it says before anything's typed
1615
1615
  own.text = key.name === 'backspace' ? (own.text ?? '').slice(0, -1) : (own.text ?? '') + s
1616
1616
  own.desc = own.text ? `› ${own.text}▏` : own.hint
1617
1617
  if (m.pick.multi) own.checked = Boolean(own.text)
@@ -2183,7 +2183,7 @@ export class UI {
2183
2183
  const said = (x) => (x.own && x.text?.trim() ? x.text.trim() : x.label) // their own answer: what they typed
2184
2184
  const picked = Array.isArray(pick?.chosen) ? pick.chosen.map(said).join(', ') : pick?.chosen && said(pick.chosen)
2185
2185
  if (pick?.quiet) this.render()
2186
- else if (pick) this.write(echo + (picked ?? c.dim(pick.closedAs ?? 'cancelled')) + (pick.auto?.fired ? c.dim(` · no answer in ${pick.auto.secs}s: ${pick.auto.fired === 'theirs' ? 'yours' : 'the recommended one'}`) : '') + '\n')
2186
+ else if (pick) this.write(echo + (picked ?? c.dim(pick.closedAs ?? 'cancelled')) + (pick.auto?.fired ? c.dim(` · no answer in ${pick.auto.secs}s: ${pick.auto.fired === 'theirs' ? 'the typed one' : 'the recommended one'}`) : '') + '\n')
2187
2187
  else if (l !== null && history && this.isCommand(l.trim()) && !/^\s*\/skill:/.test(l)) this.notice(/^\S+/.exec(l.trim())[0], 3000, '›') // a command isn't part of the conversation: its name for a moment (not its arguments: maybe a key)
2188
2188
  else if (l?.trim()) this.write(echo + c.bright(l.replace(/\n/g, '\n' + ' '.repeat(width(echo.replace(/\x1b\[[0-9;]*m/g, ''))))) + '\n')
2189
2189
  else this.render()
@@ -2273,7 +2273,7 @@ export class UI {
2273
2273
  const a = pick?.auto
2274
2274
  if (!a) return ''
2275
2275
  const theirs = pick.items.some((x) => x.checked || (x.own && x.text?.trim())) // ticked or typed: that's what goes
2276
- return `◷ ${Math.max(0, Math.ceil((a.until - Date.now()) / 1000))}s · then ${theirs ? 'yours is sent' : (a.say ?? 'the recommended answer is chosen')} · a key restarts it`
2276
+ return `◷ ${Math.max(0, Math.ceil((a.until - Date.now()) / 1000))}s · then ${theirs ? 'the typed answer is sent' : (a.say ?? 'the recommended answer is chosen')} · a key restarts it`
2277
2277
  }
2278
2278
 
2279
2279
  setPermission(mode) {
package/src/usage.js CHANGED
@@ -106,8 +106,17 @@ function newestOf(name) {
106
106
  // however it's written (google/gemini-2.5-flash, models/gemini-2.5-flash, gpt-oss:120b ≈
107
107
  // gpt-oss-120b): at this provider first; else, among all that list it, the size most say (a
108
108
  // proxy or a provider models.dev doesn't know serves the model at its usual size).
109
+ // Remembered per models.dev list (a new list: worked out again): the settings page asks for every
110
+ // model of every provider each time it loads.
111
+ const looked = new WeakMap()
109
112
  export function limitsOf(provider, baseUrl, model) {
110
113
  if (!table || !model) return null
114
+ const memo = looked.get(table) ?? looked.set(table, new Map()).get(table)
115
+ const key = `${provider}\n${baseUrl}\n${model}`
116
+ if (!memo.has(key)) memo.set(key, lookUpLimits(provider, baseUrl, model))
117
+ return memo.get(key)
118
+ }
119
+ function lookUpLimits(provider, baseUrl, model) {
111
120
  const last = (m) => m.split('/').pop()
112
121
  const own = ownBy(provider, baseUrl)
113
122
  const found = { own: [], all: [] }
package/src/voice.js CHANGED
@@ -36,7 +36,7 @@ export function localModel(cfg = {}, { fast = false } = {}) {
36
36
  // Why voice can't work here, or null when it can.
37
37
  export function voiceProblem(cfg = {}, providers = {}) {
38
38
  if (!onPath('ffmpeg')) return 'voice input needs ffmpeg to record (brew install ffmpeg)'
39
- if (cfg.provider) return providers[cfg.provider] ? null : `voice.provider "${cfg.provider}" isn't one of your providers`
39
+ if (cfg.provider) return providers[cfg.provider] ? null : `voice.provider "${cfg.provider}" isn't one of the providers`
40
40
  if (!onPath('whisper-cli')) return 'voice input needs whisper-cli (brew install whisper-cpp) and a model, or "voice": { "provider": …, "model": … } in ~/.heart/config.json'
41
41
  return localModel(cfg) ? null : 'voice input needs a whisper model: put a ggml-*.bin in ~/.whisper-models, or set "voice": { "model": "/path/to/ggml-….bin" }'
42
42
  }
package/src/web.js CHANGED
@@ -336,7 +336,7 @@ export async function testSearxng(url) {
336
336
  // go (on 2026-10-31 most LibreY, Whoogle and 4get ones were down or blocked, so they aren't here),
337
337
  // and DuckDuckGo is blocked on some networks.
338
338
  export const ENGINES = { searxng: mySearxng, searx, duckduckgo, mwmbl, stackoverflow, npm, github }
339
- export const ENGINE_NAMES = { searxng: 'Your SearXNG', searx: 'Public SearXNG instances', duckduckgo: 'DuckDuckGo', mwmbl: 'Mwmbl', stackoverflow: 'Stack Overflow', npm: 'npm', github: 'GitHub' }
339
+ export const ENGINE_NAMES = { searxng: 'SearXNG (self-hosted)', searx: 'Public SearXNG instances', duckduckgo: 'DuckDuckGo', mwmbl: 'Mwmbl', stackoverflow: 'Stack Overflow', npm: 'npm', github: 'GitHub' }
340
340
  // The settings page's order and switches (cfg.search: { searxng, order, off }), read at each search
341
341
  // (a change applies at once, also in other HeartCodes). Engines missing from a saved order go after it.
342
342
  export function searchSettings() {