heartcode 0.1.58 → 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+o": "cycle_permissions",\n "alt+g": "/toggle_thinking"\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
  },
@@ -675,7 +684,11 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
675
684
  // for it stay above). A running HeartCode takes it at once.
676
685
  // Test: one short message to the model, to see that it answers (key, access, name, the server
677
686
  // itself). In the requests log as a model test. Never throws: { ok, ms, reply } or { ok: false, error }.
678
- 'POST /api/try': ({ provider, model } = {}) => testOne({ provider, model: String(model ?? '') }),
687
+ 'POST /api/try': async ({ provider, model } = {}) => {
688
+ const r = await testOne({ provider, model: String(model ?? '') })
689
+ if (autoPick()) emit('helpers', { helpers: helpersOf(cfg.helpers) }) // picked for you: what this test found counts
690
+ return r
691
+ },
679
692
  // Test, on a model's row: one "Hello" to it, and exactly what was sent and what came back (the
680
693
  // key masked), for the page to show. Not streamed, so the answer is the provider's own JSON.
681
694
  'POST /api/hello': async ({ provider, model }) => {
@@ -748,6 +761,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
748
761
  writeJson(profilePath(c), p)
749
762
  changed('profile')
750
763
  testNews(`${provider}/${t.model}`, t)
764
+ autoPick() // picked for you: what it can do now counts (thinking, context)
751
765
  return state()
752
766
  },
753
767
  // Measure a tested model's window: one oversized request (client.measureContext); the limit the
@@ -816,19 +830,19 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
816
830
  // it gets a first message saying so.
817
831
  'POST /api/telegram/connect': async ({ token }) => {
818
832
  const tk = String(token ?? '').trim() || cfg.telegram?.token
819
- if (!tk) throw new Error('paste the token @BotFather gave you')
833
+ if (!tk) throw new Error('paste the token from @BotFather')
820
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)")
821
835
  const r = await connect(tk)
822
836
  const chat = r.chats[0]
823
837
  const was = cfg.telegram?.token === tk ? cfg.telegram : {}
824
838
  cfg.telegram = { ...was, token: tk, bot: r.bot, ...(chat ? { chatId: chat.id, chatName: chat.name } : { chatId: undefined, chatName: undefined }), on: was.on ?? true }
825
839
  save('setting:telegram')
826
- 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.")
827
841
  return { ...state(), found: chat?.name ?? null }
828
842
  },
829
843
  'POST /api/telegram/test': async () => {
830
844
  if (!tgReady({ ...cfg.telegram, on: true })) throw new Error('connect Telegram first')
831
- 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.')
832
846
  return state()
833
847
  },
834
848
  'POST /api/telegram/set': ({ on, event, value }) => {
@@ -871,7 +885,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
871
885
  },
872
886
  'POST /api/search/test': async ({ searxng }) => {
873
887
  const u = String(searxng ?? '').trim() || searchSettings().searxng
874
- if (!u) throw new Error('type your SearXNG address first')
888
+ if (!u) throw new Error('type the SearXNG address first')
875
889
  const n = await testSearxng(/^https?:\/\//i.test(u) ? u : `https://${u}`).catch((e) => {
876
890
  throw new Error(`${u} didn't answer a search: ${e.cause?.code || e.message}`)
877
891
  })
@@ -949,7 +963,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
949
963
  if (fs.existsSync(file) && !readJson(file, null)) throw new Error("mcp.json isn't valid JSON: fix it first")
950
964
  const data = readJson(file, null) ?? {}
951
965
  const c = data.mcpServers?.[name]
952
- 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}"`)
953
967
  flag = String(flag ?? '').trim().replace(/\s+/g, ' ')
954
968
  const words = flag.split(' ')
955
969
  if (!/^-/.test(words[0]) || words.length > 2) throw new Error('a flag starts with - (and may have one value: --port 3000)')
@@ -967,7 +981,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
967
981
  'POST /api/mcp/remove': ({ name }) => {
968
982
  const file = path.join(HOME, 'mcp.json')
969
983
  const data = readJson(file, null)
970
- if (!data?.mcpServers?.[name]) throw new Error(`no server "${name}" of yours`)
984
+ if (!data?.mcpServers?.[name]) throw new Error(`no added server "${name}"`)
971
985
  delete data.mcpServers[name]
972
986
  writeJson(file, data)
973
987
  changed('mcp')
@@ -1018,7 +1032,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1018
1032
  return state()
1019
1033
  },
1020
1034
  'POST /api/skill/delete': ({ name }) => {
1021
- if (!removeSkill(name)) throw new Error(`no skill "${name}" of yours`)
1035
+ if (!removeSkill(name)) throw new Error(`no added skill "${name}"`)
1022
1036
  changed('skill')
1023
1037
  return state()
1024
1038
  },
@@ -1128,12 +1142,27 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1128
1142
  loadPrices().then(() => {
1129
1143
  for (const t of state().order) testNews(`${t.provider}/${t.model}`, t)
1130
1144
  test(state().order) // any without a profile yet
1145
+ warm()
1131
1146
  })
1132
1147
  resolve({ url, local, server, close: () => (watcher?.close(), server.closeAllConnections?.(), server.close()) })
1133
1148
  })
1134
1149
  })
1135
1150
  }
1136
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
+
1137
1166
  // This machine's IPv4 addresses on its networks (Wi-Fi, Ethernet, a VPN), not the loopback one
1138
1167
  const addresses = () => Object.values(os.networkInterfaces()).flat().filter((n) => n && n.family === 'IPv4' && !n.internal).map((n) => n.address)
1139
1168
 
package/src/tabs.js CHANGED
@@ -139,7 +139,10 @@ export class Tabs {
139
139
  bottom += (on ? c.brand(`╯${' '.repeat(w)}╰`) : c.ghost(`┴${'─'.repeat(w)}┴`)) + c.ghost('─')
140
140
  })
141
141
  // the keys that fit whole, the rest left out (never one cut in the middle)
142
- const hints = this.list.length > 1 ? ['Alt+T open a tab', 'Alt+W close this one', 'Alt+N/P switch tabs'] : ['Alt+T open a new tab']
142
+ // as keybindings.json has them now (one moved or turned off: said so, or left out)
143
+ const k = (a) => this.at?.ui.keyFor?.(a)
144
+ const sw = [k('next_tab'), k('prev_tab')].filter(Boolean).join('/')
145
+ const hints = (this.list.length > 1 ? [k('new_tab') && `${k('new_tab')} open a tab`, k('close_tab') && `${k('close_tab')} close this one`, sw && `${sw} switch tabs`] : [k('new_tab') && `${k('new_tab')} open a new tab`]).filter(Boolean)
143
146
  let hint = ''
144
147
  for (const h of hints) if (width(mid.replace(/\x1b\[[0-9;]*m/g, '')) + 1 + width(hint ? `${hint} · ${h}` : h) <= cols - 1) hint = hint ? `${hint} · ${h}` : h
145
148
  if (hint) mid += ` ${c.faint(hint)}`
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
@@ -466,7 +466,7 @@ export function searchesOutside(cmd, root) {
466
466
  // Waited on for `wait` seconds (the model's choice): finished by then, its exit code and output;
467
467
  // still running, it carries on in the background, and the model checks on it when it likes.
468
468
  export async function runConfirmed(s, cmd, signal, background = false, wait) {
469
- s.ui.step(background ? 'run in background' : 'run', cmd)
469
+ s.ui.step(background ? 'run in background' : 'run', cmd, s.client?.model)
470
470
  if (s.ui.permission === 'plan' && !readOnlyCommand(cmd)) {
471
471
  s.ui.result('not run: plan mode')
472
472
  return prompt('agent/plan-refused', { command: true })
@@ -609,22 +609,23 @@ export function writeResult(rel, r) {
609
609
  const str = { type: 'string' }
610
610
  const int = { type: 'integer' }
611
611
  const obj = (properties, required = []) => ({ type: 'object', properties, required })
612
+ // (descriptions read each time: a project's own prompts and the settings page's edits apply at once)
612
613
  export const TOOL_DEFS = [
613
- { name: 'read_file', description: prompt('agent/tool-read_file'), parameters: obj({ path: str, start_line: int, end_line: int }, ['path']) },
614
- { name: 'search', description: prompt('agent/tool-search'), parameters: obj({ query: str, path: str }, ['query']) },
615
- { name: 'changes', description: prompt('agent/tool-changes'), parameters: obj({ path: str, all: { type: 'boolean' } }) },
616
- { name: 'list_files', description: prompt('agent/tool-list_files'), parameters: obj({ path: str, filter: str }) },
617
- { name: 'find_command', description: prompt('agent/tool-find_command'), parameters: obj({ names: { type: 'array', items: str } }, ['names']) },
618
- { 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']) },
614
+ { name: 'read_file', get description() { return prompt('agent/tool-read_file') }, parameters: obj({ path: str, start_line: int, end_line: int }, ['path']) },
615
+ { name: 'search', get description() { return prompt('agent/tool-search') }, parameters: obj({ query: str, path: str }, ['query']) },
616
+ { name: 'changes', get description() { return prompt('agent/tool-changes') }, parameters: obj({ path: str, all: { type: 'boolean' } }) },
617
+ { name: 'list_files', get description() { return prompt('agent/tool-list_files') }, parameters: obj({ path: str, filter: str }) },
618
+ { name: 'find_command', get description() { return prompt('agent/tool-find_command') }, parameters: obj({ names: { type: 'array', items: str } }, ['names']) },
619
+ { name: 'lsp', get description() { return 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']) },
619
620
  // One edit per call: a list of edits per call measured 2–6 malformed calls per benchmark run vs 0.
620
- { name: 'edit_file', description: prompt('agent/tool-edit_file'), parameters: obj({ path: str, search: str, replace: str, start_line: int, end_line: int }, ['path', 'replace']) },
621
- { name: 'write_file', description: prompt('agent/tool-write_file'), parameters: obj({ path: str, content: str, append: { type: 'boolean' } }, ['path', 'content']) },
622
- { name: 'run_command', description: prompt('agent/tool-run_command'), parameters: obj({ command: str, wait: int, background: { type: 'boolean' } }, ['command']) },
623
- { name: 'background', description: prompt('agent/tool-background'), parameters: obj({ action: { type: 'string', enum: ['output', 'list', 'stop'] }, id: int, wait: int }, ['action']) },
624
- { name: 'todo', description: 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: 'web_search', description: prompt('agent/tool-web_search'), parameters: obj({ query: str, fresh: { type: 'boolean' } }, ['query']) },
626
- { name: 'web_fetch', description: prompt('agent/tool-web_fetch'), parameters: obj({ url: str, look_for: str, start: int }, ['url']) },
627
- { name: 'ask_user', description: 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)
621
+ { name: 'edit_file', get description() { return prompt('agent/tool-edit_file') }, parameters: obj({ path: str, search: str, replace: str, start_line: int, end_line: int }, ['path', 'replace']) },
622
+ { name: 'write_file', get description() { return prompt('agent/tool-write_file') }, parameters: obj({ path: str, content: str, append: { type: 'boolean' } }, ['path', 'content']) },
623
+ { name: 'run_command', get description() { return prompt('agent/tool-run_command') }, parameters: obj({ command: str, wait: int, background: { type: 'boolean' } }, ['command']) },
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', 'stuck'] }, why: str, parallel: { type: 'boolean' }, model: str, files: { type: 'array', items: str } }, ['content', 'status']) } }, ['todos']) },
626
+ { name: 'web_search', get description() { return prompt('agent/tool-web_search') }, parameters: obj({ query: str, fresh: { type: 'boolean' } }, ['query']) },
627
+ { name: 'web_fetch', get description() { return prompt('agent/tool-web_fetch') }, parameters: obj({ url: str, look_for: str, start: int }, ['url']) },
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)
628
629
  ]
629
630
 
630
631
  // Plan mode (permission "plan"): looking around is fine, changing things isn't. Edits are refused,
@@ -699,23 +700,32 @@ export function extraTools(s) {
699
700
  const team = s.team?.() ?? []
700
701
  const model = { type: 'string', description: team.some((t) => t.jobs) ? 'Which helper does the job ("provider model" from "Your helpers"). Left out: the first helper.' : 'Which of your models does the job ("provider model" from "Your other models"). Left out: yours, or with images you can\'t see, the first of yours that can.' }
701
702
  const images = { type: 'array', items: str, description: 'Image paths or URLs for the helper to look at. Needs a model that sees images.' }
702
- out.push({ name: 'agent', description: prompt('agent/tool-agent'), parameters: obj({ description: str, prompt: str, ...(team.length && { model, images }) }, ['description', 'prompt']) })
703
+ out.push({ name: 'agent', get description() { return prompt('agent/tool-agent') }, parameters: obj({ description: str, prompt: str, ...(team.length && { model, images }) }, ['description', 'prompt']) })
703
704
  }
704
705
  return [...out, ...(s.director && !s.appendSystem ? s.director.toolDefs(s) : [])] // manage (director.js); not when a program gives the instructions (--append-system-prompt)
705
706
  }
706
707
 
707
708
  // todo: the model's checklist for this message, shown to the user each time it changes.
708
709
  // Lenient: the list as JSON text, plain strings for items, "done" for completed.
709
- const MARK = { pending: '☐', in_progress: '◐', completed: '☑' }
710
+ const MARK = { pending: '☐', in_progress: '◐', completed: '☑', stuck: '⚠' }
710
711
  // In the conversation: the whole plan when it's new (or its steps changed), else only the steps whose
711
712
  // status changed, on one line; the whole of it stays in sight under the spinner (full screen).
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, why, by, byProvider }) => ({ content, status, ...(why && { why }), ...(by && { by: byProvider ? `${byProvider}/${by}` : by }) })) })
712
715
  function showTodos(s, before, todos) {
713
- const paint = { pending: c.muted, in_progress: (x) => c.info(c.bold(x)), completed: (x) => c.faint(x) }
714
- const item = (t) => paint[t.status](`${MARK[t.status]} ${t.content}`)
715
- const same = s.ui.full && before?.length === todos.length && before.every((t, i) => t.content === todos[i].content)
716
- if (!same) return s.ui.print(todos.map((t) => ` ${item(t)}`).join('\n') || c.faint(' (todo list cleared)'))
717
- const moved = todos.filter((t, i) => t.status !== before[i].status)
718
- if (moved.length) s.ui.print(` ${moved.map(item).join(c.faint(' · '))}`)
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
+ // full screen, the same plan changed (most of its steps still in it): only what changed, on one line
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}${t.why ?? ''}`]))
721
+ const kept = todos.filter((t) => was.has(t.content)).length
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
+ const now = new Set(todos.map((t) => t.content))
724
+ const changes = [
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
+ ...(before ?? []).filter((t) => !now.has(t.content)).map((t) => c.faint(`− ${t.content}`)),
727
+ ]
728
+ if (changes.length) s.ui.print(` ${changes.join(c.faint(' · '))}`)
719
729
  }
720
730
  async function todoTool(s, args, signal, id) {
721
731
  let list = args.todos ?? args.items ?? args
@@ -728,12 +738,22 @@ async function todoTool(s, args, signal, id) {
728
738
  }
729
739
  if (!Array.isArray(list)) return 'error: todos must be a list of {content, status}'
730
740
  const todos = list
731
- .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) }) }))
732
742
  .filter((t) => t.content.trim())
733
- .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
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))
734
750
  showTodos(s, s.chat.todos, todos)
735
751
  s.chat.todos = todos
752
+ sendTodos(s)
736
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)}`
737
757
  const parts = await runParts(s, todos, signal, id)
738
758
  const done = todos.filter((t) => t.status === 'completed').length
739
759
  const next = todos.find((t) => t.status !== 'completed')
@@ -748,6 +768,51 @@ async function todoTool(s, args, signal, id) {
748
768
  return `Todo list saved: ${done} of ${todos.length} done.${next ? ` Next: ${next.content}` : ''}${parts ? `\n\n${parts}` : ''}${check}`
749
769
  }
750
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
+
751
816
  // The plan's parts marked parallel (or given to another model): each started at once as a helper
752
817
  // on its model, all at the same time, each changing only the files its part owns; marked done when
753
818
  // it reports back. What they did, for the model to put together and check. '' when none.
@@ -755,7 +820,8 @@ async function runParts(s, todos, signal, id) {
755
820
  const parts = todos.filter((t) => t.status === 'pending' && (t.parallel || t.model))
756
821
  if (!parts.length || s.isSub || !s.subagent || s.ui.permission === 'plan') return ''
757
822
  // a model that isn't one of yours (a name made up, the product's own name): the part runs on this one
758
- const yours = [{ provider: s.client?.provider, model: s.client?.model }, ...(s.team?.() ?? [])]
823
+ const team = s.team?.() ?? []
824
+ const yours = [{ provider: s.client?.provider, model: s.client?.model }, ...(team.some((t) => t.jobs) ? team.filter((t) => t.jobs) : team)] // with helpers ticked: those (only they can be started)
759
825
  const known = (m) => yours.some((y) => `${y.provider} ${y.model}` === m || y.model === m || m.endsWith(` ${y.model}`))
760
826
  const unknown = [...new Set(parts.filter((t) => t.model && !known(t.model)).map((t) => t.model))]
761
827
  for (const t of parts) if (t.model && !known(t.model)) delete t.model
@@ -770,7 +836,7 @@ async function runParts(s, todos, signal, id) {
770
836
  const brief = prompt('agent/part', { task: s.task ?? '', plan, part: t.content, files: (t.files ?? []).join(', '), choices })
771
837
  let out
772
838
  try {
773
- out = await s.subagent({ prompt: brief, model: t.model, description: clip(t.content, 40), ownFiles: t.files }, signal, id)
839
+ out = await s.subagent({ prompt: brief, model: t.model, description: clip(t.content, 40), ownFiles: t.files, part: t }, signal, id) // part: its model is noted on it (by)
774
840
  } catch (e) {
775
841
  if (e.name === 'AbortError' || signal?.aborted) throw e
776
842
  out = `error: ${e.message}`
@@ -781,6 +847,7 @@ async function runParts(s, todos, signal, id) {
781
847
  )
782
848
  s.chat.todos = todos
783
849
  showTodos(s, shown, todos)
850
+ sendTodos(s)
784
851
  return prompt('agent/parts-done', { reports: reports.join('\n\n'), unknown: unknown.join(', '), models: yours.map((y) => `${y.provider} ${y.model}`).join(', ') })
785
852
  }
786
853
 
@@ -811,7 +878,7 @@ async function askUser(s, args) {
811
878
  s.askedUser = true // asked through the dialog this message (not as text: see askedInText)
812
879
  for (const q of qs) {
813
880
  q.items[0].desc = ['recommended', q.items[0].desc].filter(Boolean).join(' · ')
814
- q.own = { label: 'Something else', desc: 'type your own answer', own: true }
881
+ q.own = { label: 'Something else', desc: 'type an answer', own: true }
815
882
  }
816
883
  s.ui.stopSpin()
817
884
  const tabbed = qs.length > 1 && s.ui.full
@@ -827,7 +894,7 @@ async function askUser(s, args) {
827
894
  // the last tab: every answer, sent with Enter (or after ASK_WAIT seconds)
828
895
  const body = qs.map((q, j) => `${q.question} ${c.faint('›')} ${answerOf(said[j]) || `${q.items[0].label} ${c.faint('(recommended)')}`}`).join('\n')
829
896
  const send = { label: 'Send answers', desc: 'or ← to change one' }
830
- 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' } })
831
898
  if (got?.nav) {
832
899
  i = Math.min(qs.length, Math.max(0, i + got.nav)) // → on Send: stays there
833
900
  continue
@@ -850,8 +917,8 @@ async function askUser(s, args) {
850
917
  let text = ''
851
918
  if (list.some((x) => x.own)) {
852
919
  // typed in its row (full screen); without full screen, asked for now
853
- text = q.own.text?.trim() || ((await s.ui.ask(`${c.bold('Your answer')} ${c.dim('›')} `, { initial: said[i]?.text ?? '' }))?.trim() ?? '')
854
- 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' })
855
922
  if (!text && list.length === 1) continue // nothing typed: the same question again
856
923
  }
857
924
  if (s.ui.autoPicked) {
@@ -1147,6 +1214,7 @@ async function callMcp(s, server, tool, a, signal) {
1147
1214
  }
1148
1215
  note = `\n(${s.pendingImages.length - shown} image(s): shown to you in the next message${left.length ? `; not shown: ${left.join('; ')}` : ''})`
1149
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})`)}`
1150
1218
  else if (files.length) note = `\n(${files.length} image(s) not shown: this model can't see images)`
1151
1219
  const mendNote = mended.fixed.length ? `\n(HeartCode corrected the arguments: ${mended.fixed.join('; ')}. Use them that way next time.)` : ''
1152
1220
  return `${r.isError ? 'error: ' : ''}${text || '(no text)'}${note}${mendNote}`
@@ -1403,7 +1471,7 @@ async function toolRun(name, args, s, signal, id) {
1403
1471
  const notMine = !pre.block && s.ownFiles && partPaths(name, args).find((f) => !s.ownFiles.includes(path.resolve(s.root, f)))
1404
1472
  const stop = pre.block ? prompt('agent/hook', { reason: pre.block, blocked: true }) : notMine ? prompt('agent/part-files', { file: notMine, files: s.ownFiles.map((f) => path.relative(s.root, f)).join(', ') }) : null
1405
1473
  if (stop && name === 'run_command') {
1406
- s.ui.step('run', String(args?.command ?? '')) // a command's lines are shown where it runs, which this one never reaches
1474
+ s.ui.step('run', String(args?.command ?? ''), s.client?.model) // a command's lines are shown where it runs, which this one never reaches
1407
1475
  s.ui.result(refusal(stop))
1408
1476
  }
1409
1477
  if (stop) return stop
@@ -1468,7 +1536,8 @@ async function tool(name, args, s, signal, id) {
1468
1536
  const v = folderView(root, String(args.path))
1469
1537
  return v.error ? `error: ${v.error}` : v.entries.join('\n') + (v.more ? `\n… ${v.more} more` : '') || '(empty folder)'
1470
1538
  }
1471
- const files = listFiles(root).filter((f) => !args.filter || f.includes(args.filter))
1539
+ const under = String(args.path ?? '').replace(/^\.?\/+|\/+$/g, '') // with a filter too: the files under that folder that match
1540
+ const files = listFiles(root).filter((f) => (!under || under === '.' || f === under || f.startsWith(`${under}/`)) && (!args.filter || f.includes(args.filter)))
1472
1541
  return files.slice(0, 500).join('\n') + (files.length > 500 ? `\n… ${files.length - 500} more` : '') || 'no files'
1473
1542
  }
1474
1543
  case 'search':
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,