heartcode 0.1.59 → 0.1.62

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/tools.js CHANGED
@@ -10,7 +10,11 @@ import os from 'node:os'
10
10
  import { spawn, execFileSync } from 'node:child_process'
11
11
  import { applyEdit, closest, trimBlank } from './edit.js'
12
12
  import { readJson, HOME } from './config.js'
13
- import { c, diffLines, renderDiff } from './ui.js'
13
+ import { c, diffLines, renderDiff, planPick } from './ui.js'
14
+ import { pageCheck } from './check.js'
15
+ import { killTree } from './spawn.js'
16
+ import { scoreOf } from './rankings.js'
17
+ import { family } from './client.js'
14
18
  import { webFetch, webSearch, fetchPage, pageView } from './web.js'
15
19
  import { savePage, saveSearch, findResearch } from './research.js'
16
20
  import { runHooks } from './hooks.js'
@@ -290,15 +294,7 @@ export function runCommand(root, cmd, { signal, timeout = 120_000, stdin, env, s
290
294
  child.stdin.on('error', () => {}) // a command that doesn't read its input
291
295
  child.stdin.end(stdin)
292
296
  }
293
- const kill = (sig) => {
294
- try {
295
- if (group) process.kill(-child.pid, sig)
296
- else child.kill(sig)
297
- return true
298
- } catch {
299
- return false // nothing left
300
- }
301
- }
297
+ const kill = (sig) => killTree(child.pid, sig, group) // false: nothing left
302
298
  const finish = (code, note = '') => {
303
299
  if (done) return
304
300
  done = true
@@ -353,6 +349,7 @@ export function suggestCommands(root) {
353
349
  // What the model changed in files: this message's (or with all, the conversation's), each file from
354
350
  // before its first change to now (the turns keep that first version for /rewind; /diff shows the same).
355
351
  function changesTool(s, args) {
352
+ if (args.versions || args.version) return versionsOf(s, args)
356
353
  const turns = args.all ? (s.chat?.turns ?? []) : (s.chat?.turns ?? []).slice(-1)
357
354
  const first = new Map()
358
355
  for (const t of turns) for (const [rel, before] of Object.entries(t.files ?? {})) if (!first.has(rel)) first.set(rel, before)
@@ -369,6 +366,62 @@ function changesTool(s, args) {
369
366
  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
367
  }
371
368
 
369
+ // Files that are much smaller now than an earlier version of them (under 70% of its lines, 50 lines or
370
+ // more gone): a sign that what an earlier message made was lost. One line each, or ''.
371
+ export function shrunkNote(s, files) {
372
+ const out = []
373
+ for (const f of files) {
374
+ let now
375
+ try {
376
+ now = fs.readFileSync(path.join(s.root, f), 'utf8').split('\n').length
377
+ } catch {
378
+ continue
379
+ }
380
+ const list = fileVersions(s, f)
381
+ const big = list.reduce((m, v, i) => { const n = v.text.split('\n').length; return n > (m?.n ?? 0) ? { n, i, v } : m }, null)
382
+ if (big && now < big.n * 0.7 && big.n - now >= 50) out.push(`${f}: ${now} lines now; ${big.n} lines before the message "${clip(big.v.task.replace(/\s+/g, ' '), 80)}" (${String(big.v.at).slice(0, 10)}; changes with path and version: ${big.i + 1})`)
383
+ }
384
+ return out.join('\n')
385
+ }
386
+
387
+ // A file's versions kept in this project, newest first, each { at, task, rel, text }: as it was before
388
+ // each message HeartCode worked on, in any conversation here, and this one's (not saved yet)
389
+ export function fileVersions(s, want) {
390
+ want = String(want).replace(/\\/g, '/').replace(/^\.\//, '')
391
+ const dir = path.join(s.root, '.heartcode', 'sessions')
392
+ const found = []
393
+ const take = (t) => {
394
+ const rel = Object.keys(t.files ?? {}).find((r) => (r = r.replace(/\\/g, '/')) === want || r.endsWith(`/${want}`))
395
+ if (rel && typeof t.files[rel] === 'string' && !found.some((x) => x.at === t.at && x.text === t.files[rel])) found.push({ at: t.at ?? '', task: String(t.task ?? ''), rel, text: t.files[rel] })
396
+ }
397
+ for (const f of fs.existsSync(dir) ? fs.readdirSync(dir).filter((x) => x.endsWith('.json')) : []) {
398
+ try {
399
+ for (const t of JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')).turns ?? []) take(t)
400
+ } catch {}
401
+ }
402
+ for (const t of s.chat?.turns ?? []) take(t)
403
+ return found.sort((a, b) => String(b.at).localeCompare(String(a.at))).filter((v, i, all) => i === 0 || v.text !== all[i - 1].text)
404
+ }
405
+
406
+ // A file's earlier versions in this project: as it was before each message HeartCode worked on, in any
407
+ // conversation here (the snapshots kept for /rewind). versions: the list, newest first; version: that
408
+ // one saved to .heartcode/versions/ (to read whole) and its diff to the file now. For "it worked before".
409
+ function versionsOf(s, args) {
410
+ const want = String(args.path ?? '').trim().replace(/^\.\//, '')
411
+ if (!want) return 'error: changes with versions/version needs "path": the file'
412
+ const list = fileVersions(s, want)
413
+ if (!list.length) return `No earlier versions of ${want} kept in this project.`
414
+ if (!args.version) return `Earlier versions of ${want}, newest first (each as it was before that message):\n${list.map((v, i) => `${i + 1}. ${String(v.at).slice(0, 16).replace('T', ' ')} · ${v.text.split('\n').length} lines · before: "${clip(v.task.replace(/\s+/g, ' '), 80)}"`).join('\n')}\nchanges with version: N shows one and what changed since.`
415
+ const v = list[Number(args.version) - 1]
416
+ if (!v) return `error: no version ${args.version}; there are ${list.length}`
417
+ const out = path.join(s.root, '.heartcode', 'versions', `${v.rel.replace(/[\\/]/g, '__')}@${args.version}`)
418
+ fs.mkdirSync(path.dirname(out), { recursive: true })
419
+ fs.writeFileSync(out, v.text)
420
+ const abs = path.join(s.root, v.rel)
421
+ const now = fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : ''
422
+ return `Version ${args.version} of ${v.rel} (before "${clip(v.task.replace(/\s+/g, ' '), 80)}", ${String(v.at).slice(0, 16).replace('T', ' ')}), whole: ${path.relative(s.root, out)} (read_file it).\nWhat changed from it to the file now:\n${clip(renderDiff(diffLines(v.text, now), v.rel, false, 3, 400), 12000)}`
423
+ }
424
+
372
425
  // A "no" from the user, with what they typed instead. Their words go to the model as their own message,
373
426
  // after the tool results (s.userSaid, which the agent sends): inside a result a model reads them as the
374
427
  // tool talking, and tries again. Where there's no queue (guided mode) or no user (headless: the "no" is
@@ -613,7 +666,7 @@ const obj = (properties, required = []) => ({ type: 'object', properties, requir
613
666
  export const TOOL_DEFS = [
614
667
  { name: 'read_file', get description() { return prompt('agent/tool-read_file') }, parameters: obj({ path: str, start_line: int, end_line: int }, ['path']) },
615
668
  { 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' } }) },
669
+ { name: 'changes', get description() { return prompt('agent/tool-changes') }, parameters: obj({ path: str, all: { type: 'boolean' }, versions: { type: 'boolean' }, version: int }) },
617
670
  { name: 'list_files', get description() { return prompt('agent/tool-list_files') }, parameters: obj({ path: str, filter: str }) },
618
671
  { name: 'find_command', get description() { return prompt('agent/tool-find_command') }, parameters: obj({ names: { type: 'array', items: str } }, ['names']) },
619
672
  { 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']) },
@@ -622,7 +675,7 @@ export const TOOL_DEFS = [
622
675
  { name: 'write_file', get description() { return prompt('agent/tool-write_file') }, parameters: obj({ path: str, content: str, append: { type: 'boolean' } }, ['path', 'content']) },
623
676
  { name: 'run_command', get description() { return prompt('agent/tool-run_command') }, parameters: obj({ command: str, wait: int, background: { type: 'boolean' } }, ['command']) },
624
677
  { 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']) },
678
+ { 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' }, compare: { type: 'boolean' }, model: str, files: { type: 'array', items: str } }, ['content', 'status']) } }, ['todos']) },
626
679
  { name: 'web_search', get description() { return prompt('agent/tool-web_search') }, parameters: obj({ query: str, fresh: { type: 'boolean' } }, ['query']) },
627
680
  { name: 'web_fetch', get description() { return prompt('agent/tool-web_fetch') }, parameters: obj({ url: str, look_for: str, start: int }, ['url']) },
628
681
  { 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 +760,28 @@ export function extraTools(s) {
707
760
 
708
761
  // todo: the model's checklist for this message, shown to the user each time it changes.
709
762
  // Lenient: the list as JSON text, plain strings for items, "done" for completed.
710
- const MARK = { pending: '☐', in_progress: '◐', completed: '☑' }
711
- // In the conversation: the whole plan when it's new (or its steps changed), else only the steps whose
712
- // status changed, on one line; the whole of it stays in sight under the spinner (full screen).
763
+ const MARK = { pending: '☐', in_progress: '◐', completed: '☑', stuck: '⚠' }
764
+ // In the conversation: three of its steps when it's new (or its steps changed; the rest on a key), else
765
+ // only the steps whose status changed, on one line; it stays in sight under the spinner (full screen).
713
766
  // 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 }) })) })
767
+ 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
768
  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}`) : '')
769
+ const paint = { pending: c.muted, in_progress: (x) => c.info(c.bold(x)), completed: (x) => c.faint(x), stuck: (x) => c.warn(x) }
770
+ 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
771
  // full screen, the same plan changed (most of its steps still in it): only what changed, on one line
719
772
  // (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]))
773
+ const was = new Map((before ?? []).map((t) => [t.content, `${t.status}${t.why ?? ''}`]))
721
774
  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)'))
775
+ if (!s.ui.full || !before?.length || kept < Math.max(1, todos.length / 2)) {
776
+ if (!todos.length) return s.ui.print(c.faint(' (todo list cleared)'))
777
+ // three of its steps (what's being done, then what's next), the rest a count and the key that shows them
778
+ const { shown, hidden } = planPick(todos)
779
+ const key = s.ui.keyFor?.('show_plan')
780
+ return s.ui.print([...shown.map((t) => ` ${item(t)}`), ...(hidden ? [c.faint(` … ${hidden} more${key ? ` · ${key} shows all of it` : ''}`)] : [])].join('\n'))
781
+ }
723
782
  const now = new Set(todos.map((t) => t.content))
724
783
  const changes = [
725
- ...todos.filter((t) => was.get(t.content) !== t.status).map((t) => (was.has(t.content) ? item(t) : `${c.faint('+')} ${item(t)}`)),
784
+ ...todos.filter((t) => was.get(t.content) !== `${t.status}${t.why ?? ''}`).map((t) => (was.has(t.content) ? item(t) : `${c.faint('+')} ${item(t)}`)),
726
785
  ...(before ?? []).filter((t) => !now.has(t.content)).map((t) => c.faint(`− ${t.content}`)),
727
786
  ]
728
787
  if (changes.length) s.ui.print(` ${changes.join(c.faint(' · '))}`)
@@ -738,20 +797,36 @@ async function todoTool(s, args, signal, id) {
738
797
  }
739
798
  if (!Array.isArray(list)) return 'error: todos must be a list of {content, status}'
740
799
  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) }) }))
800
+ .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?.compare === true || t?.compare === 'true') && { compare: true, parallel: true }), ...([t?.files ?? []].flat().filter(Boolean).length && { files: [t.files].flat().map(String) }) }))
742
801
  .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' }))
802
+ .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' }))
803
+ .map(({ why, ...t }) => (t.status === 'stuck' ? { ...t, why: why || 'no reason given' } : t)) // a reason only on a stuck step
744
804
  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
805
+ // newly stuck (or stuck for a new reason): the model says it's struggling. Counted per message; not
806
+ // the same stuck step sent again with the rest of the list
807
+ const before = new Map((s.chat.todos ?? []).map((t) => [t.content, t]))
808
+ const newlyStuck = todos.filter((t) => t.status === 'stuck' && !(before.get(t.content)?.status === 'stuck' && before.get(t.content)?.why === t.why))
745
809
  showTodos(s, s.chat.todos, todos)
746
810
  s.chat.todos = todos
747
811
  sendTodos(s)
748
812
  s.todoTouched = true
749
- const parts = await runParts(s, todos, signal, id)
813
+ // a step it said it was stuck on, now done: what got it out is worth learning (agent.js)
814
+ 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 })
815
+ 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)}`
816
+ // a plan of several steps: the user says (once a message) whether several agents work on it at once
817
+ // or one does it step by step. Nobody to answer (headless, no reply in time): several, the recommended
818
+ const pending = todos.filter((t) => t.status === 'pending')
819
+ if (s.split === undefined && !s.isSub && s.subagent && s.team?.().length && s.ui.permission !== 'plan' && pending.length >= 2) {
820
+ const said = await askUser(s, { question: `The plan has ${todos.length} steps. Work on it with several agents at once?`, header: 'Agents', options: [{ label: 'Several agents at once', description: 'steps that stand alone run side by side, each on the model best at it; one no model is sure of is done by two, and the better kept' }, { label: 'One agent', description: 'one model does every step, in turn' }] })
821
+ s.split = /One agent/.test(said) ? 'one' : 'several'
822
+ log('parts', `the user chose: ${s.split} (${said})`)
823
+ }
824
+ const parts = s.split === 'one' ? '' : await runParts(s, todos, signal, id)
750
825
  const done = todos.filter((t) => t.status === 'completed').length
751
826
  const next = todos.find((t) => t.status !== 'completed')
752
827
  // a plan of several parts with none given to another model or run side by side: asked once a message
753
828
  const open = todos.filter((t) => t.status === 'pending')
754
- const askSplit = !parts && !s.isSub && !s.splitAsked && open.length >= 3 && !todos.some((t) => t.parallel || t.model) && s.subagent && s.team?.().length && s.ui.permission !== 'plan'
829
+ const askSplit = !parts && !s.isSub && !s.splitAsked && open.length >= 2 && s.split === 'several' && !todos.some((t) => t.parallel || t.model) && s.subagent && s.team?.().length && s.ui.permission !== 'plan'
755
830
  if (askSplit) s.splitAsked = true
756
831
  // a plan of a few steps made without looking anything up: asked once a message whether it uses something to read up on
757
832
  const askResearch = !parts && !s.isSub && !s.researchAsked && !s.lookedUp && !s.research?.lookedUp && open.length >= 2
@@ -760,6 +835,83 @@ async function todoTool(s, args, signal, id) {
760
835
  return `Todo list saved: ${done} of ${todos.length} done.${next ? ` Next: ${next.content}` : ''}${parts ? `\n\n${parts}` : ''}${check}`
761
836
  }
762
837
 
838
+ // The model says it's stuck on a step (todo status "stuck", with why). Believed: a model rarely says
839
+ // so when it isn't (a "done" is what gets checked). The 1st time this message: told to change its
840
+ // approach; the 2nd: a second opinion from another of your models (a Big & hard helper first),
841
+ // which looks into it without changing files; the 3rd: the next of your models takes over (agent.js).
842
+ // Also when its final answer says it didn't manage (agent.js). Returns what to tell it.
843
+ export async function stuckSaid(s, step, why, signal, id, answer = false) {
844
+ const t = { content: step, why }
845
+ const n = (s.stuckReports = (s.stuckReports ?? 0) + 1)
846
+ 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 }))
847
+ log('stuck', `${s.client?.model} says it's stuck (${n}): ${t.content} — ${t.why}`)
848
+ s.ui.event?.({ subtype: 'stuck', step: t.content, why: t.why, count: n, model: `${s.client?.provider}/${s.client?.model}` })
849
+ if (!s.isSub) (s.troubles ??= []).push({ model: s.client?.model, step: t.content, why: t.why })
850
+ // models it could go to: yours, not this one, not one given up on this message
851
+ const r = s.client?.rotation
852
+ const others = (r?.list ?? []).filter((x) => x !== r.list[r.at] && !s.gaveUp?.has(`${x.provider}/${x.model}`)).length
853
+ if (n >= 3 && !s.isSub && others) {
854
+ // two models have taken over already this message: no more; it says plainly what blocks it
855
+ if ((s.stuckHandovers ?? 0) >= 2) return say({ last: true })
856
+ s.stuckSelf = `said it's stuck ${n} times (last: "${clip(t.content, 60)}": ${clip(t.why, 120)})`
857
+ return '(Noted. Another of your models takes over from here.)'
858
+ }
859
+ 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
860
+ let advice = ''
861
+ const other = n === 2 && !s.isSub && s.subagent && secondOpinionModel(s)
862
+ if (other) {
863
+ s.ui.step('stuck', `asking ${other.model} for a second opinion`)
864
+ const tried = (s.ran ?? []).slice(-12).map((r) => `- ${r.command} → ${r.result}`).join('\n')
865
+ try {
866
+ 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)
867
+ } catch (e) {
868
+ if (e.name === 'AbortError' || signal?.aborted) throw e
869
+ advice = `error: ${e.message}`
870
+ }
871
+ if (failed(advice)) advice = ''
872
+ }
873
+ return say({ advice: clip(advice, 4000), adviser: other ? `${other.provider} ${other.model}` : '' })
874
+ }
875
+ // Another of your models for a second opinion: a Big & hard helper, else your first helper or model that isn't this one.
876
+ function secondOpinionModel(s) {
877
+ const me = (t) => t.model === s.client?.model && (t.provider ?? s.client?.provider) === s.client?.provider
878
+ const team = (s.team?.() ?? []).filter((t) => !me(t) && !s.gaveUp?.has(`${t.provider ?? s.client?.provider}/${t.model}`))
879
+ const helpers = team.filter((t) => t.jobs)
880
+ return helpers.find((t) => t.jobs.includes('hard')) ?? helpers[0] ?? (team.some((t) => t.jobs) ? null : team[0]) ?? null
881
+ }
882
+
883
+ // The web pages a change can break, to open in a browser: changed .html files, and the project's
884
+ // pages that use a changed file by name or sit in a folder above it. Not pages a build tool or the
885
+ // project's own server serves (a bundler or server in package.json, .ts/.jsx/.vue scripts): they don't
886
+ // open as plain files. Three at most.
887
+ export function pagesOf(root, changed) {
888
+ const slash = (f) => f.split(path.sep).join('/') // Windows paths compared the same way
889
+ const web = changed.map((f) => slash(path.relative(root, path.resolve(root, f)))).filter((f) => /\.(html?|m?js|css)$/i.test(f) && !f.startsWith('..') && !f.startsWith('.heartcode'))
890
+ if (!web.length) return []
891
+ try {
892
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
893
+ if (Object.keys({ ...pkg.dependencies, ...pkg.devDependencies }).some((d) => /^(vite|webpack|parcel|next|react-scripts|astro|@sveltejs\/kit|nuxt|@angular\/core|esbuild|rollup|express|fastify|koa|hono)$/.test(d))) return [] // built, or served by its own server
894
+ } catch {}
895
+ const uses = (page) => {
896
+ if (web.includes(page)) return true
897
+ let text = ''
898
+ try {
899
+ text = fs.readFileSync(path.join(root, page), 'utf8')
900
+ } catch {
901
+ return false
902
+ }
903
+ if (/<script[^>]+src=["'][^"']+\.(tsx?|jsx|vue|svelte)["']/i.test(text)) return false
904
+ const dir = path.dirname(page)
905
+ return web.some((f) => text.includes(path.basename(f)) || dir === '.' || f.startsWith(`${dir}/`))
906
+ }
907
+ return listFiles(root)
908
+ .map(slash)
909
+ .filter((f) => /\.html?$/i.test(f) && !f.startsWith('.heartcode/') && !/(^|\/)(node_modules|dist|build|coverage)\//.test(f))
910
+ .sort((a, b) => web.includes(b) - web.includes(a) || /index\.html?$/i.test(b) - /index\.html?$/i.test(a) || a.split('/').length - b.split('/').length)
911
+ .filter(uses)
912
+ .slice(0, 3)
913
+ }
914
+
763
915
  // The plan's parts marked parallel (or given to another model): each started at once as a helper
764
916
  // on its model, all at the same time, each changing only the files its part owns; marked done when
765
917
  // it reports back. What they did, for the model to put together and check. '' when none.
@@ -781,6 +933,10 @@ async function runParts(s, todos, signal, id) {
781
933
  const reports = await Promise.all(
782
934
  parts.map(async (t) => {
783
935
  const brief = prompt('agent/part', { task: s.task ?? '', plan, part: t.content, files: (t.files ?? []).join(', '), choices })
936
+ if (t.compare && t.files?.length) {
937
+ const r = await comparePart(s, t, brief, signal, id)
938
+ if (r) return r
939
+ }
784
940
  let out
785
941
  try {
786
942
  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)
@@ -798,6 +954,94 @@ async function runParts(s, todos, signal, id) {
798
954
  return prompt('agent/parts-done', { reports: reports.join('\n\n'), unknown: unknown.join(', '), models: yours.map((y) => `${y.provider} ${y.model}`).join(', ') })
799
955
  }
800
956
 
957
+ // A part no one model is sure to do well (compare): the two best-ranked of your models (the one the
958
+ // plan named first) each do it in a copy of the project, at the same time. What each changed in the
959
+ // part's files is checked (HeartCode opens a web page it changed in a browser), and another of your
960
+ // models picks the better one; only that one's files come into the project. Returns the part's report,
961
+ // or null when there aren't two models to compare (then it runs as any other part).
962
+ async function comparePart(s, t, brief, signal, id) {
963
+ const tools = [{ provider: s.client?.provider, model: s.client?.model }, ...(s.team?.() ?? []).filter((x) => x.tools !== false)]
964
+ const pool = tools.some((x) => x.jobs) ? tools.filter((x, i) => i === 0 || x.jobs) : tools // helpers ticked: those (and this model)
965
+ const named = t.model && pool.find((x) => `${x.provider} ${x.model}` === t.model || x.model === t.model || t.model.endsWith(` ${x.model}`))
966
+ const ranked = pool.map((x) => ({ x, score: scoreOf(x.model) })).sort((a, b) => a.score - b.score).map((r) => r.x)
967
+ const first = named ?? ranked[0]
968
+ const second = ranked.find((x) => x !== first && family(x.model) !== family(first.model))
969
+ if (!first || !second) return null
970
+ const pair = [first, second]
971
+ const name = (x) => `${x.provider} ${x.model}`
972
+ s.ui.step('compare', `${clip(t.content, 50)}: ${first.model} and ${second.model}, each in a copy`)
973
+ const copies = pair.map(() => copyProject(s.root))
974
+ try {
975
+ const outs = await Promise.all(pair.map((x, i) => s.subagent({ prompt: brief, model: name(x), description: `${clip(t.content, 30)} · ${x.model}`, ownFiles: t.files, root: copies[i] }, signal, id).catch((e) => (e.name === 'AbortError' || signal?.aborted ? Promise.reject(e) : `error: ${e.message}`))))
976
+ const results = await Promise.all(copies.map(async (dir, i) => {
977
+ const diffs = []
978
+ for (const f of t.files) {
979
+ const read = (root) => { try { return fs.readFileSync(path.join(root, f), 'utf8') } catch { return null } }
980
+ const before = read(s.root), now = read(dir)
981
+ if (before !== now) diffs.push(now === null ? `${f}: deleted` : before === null ? `${f} (new):\n${clip(now, 4000)}` : renderDiff(diffLines(before, now), f, false, 3, 300))
982
+ }
983
+ const page = diffs.length ? pagesOf(dir, t.files)[0] : null
984
+ const check = page ? await pageCheck(dir, page, signal, null, () => {}).catch((e) => (signal?.aborted ? Promise.reject(e) : null)) : null
985
+ return { model: pair[i], said: outs[i], diffs, check, out: failed(outs[i]) || !diffs.length || check?.broken }
986
+ }))
987
+ let pick = results.findIndex((r) => !r.out)
988
+ let why = pick < 0 ? 'neither worked' : 'the other one failed'
989
+ if (results.every((r) => !r.out)) {
990
+ pick = 0
991
+ why = 'no one could compare them; the first kept'
992
+ const ask = prompt('agent/compare', { task: s.task ?? '', part: t.content, ...Object.fromEntries(results.flatMap((r, i) => [[`model${i}`, r.model.model], [`said${i}`, clip(r.said, 1500)], [`changes${i}`, clip(r.diffs.join('\n\n'), 6000)], [`check${i}`, r.check ? clip(r.check.report, 600) : '(no page to open)']])) })
993
+ const judges = [...(s.team?.() ?? []).filter((x) => !pair.some((p) => p.provider === x.provider && p.model === x.model)).map((x) => ({ x, score: scoreOf(x.model) })).sort((a, b) => a.score - b.score).map((r) => r.x).slice(0, 2), null]
994
+ for (const j of judges) {
995
+ try {
996
+ const { client } = j ? await s.engineFor(j) : { client: s.client }
997
+ s.ui.spinner(`${client.model} is comparing the two`)
998
+ const said = (await client.chat({ messages: [{ role: 'user', content: ask }] }, { signal })).content.trim()
999
+ s.ui.stopSpin()
1000
+ const m = /^\W*(A|B)\b[\s.:—-]*(.*)/is.exec(said)
1001
+ if (!m) continue
1002
+ pick = m[1].toUpperCase() === 'A' ? 0 : 1
1003
+ why = `${client.model}: ${clip(m[2].split('\n')[0] || 'better', 120)}`
1004
+ break
1005
+ } catch (e) {
1006
+ s.ui.stopSpin()
1007
+ if (e.name === 'AbortError' || signal?.aborted) throw e
1008
+ log('parts', `compare judge: ${e.message}`)
1009
+ }
1010
+ }
1011
+ }
1012
+ s.ui.step('compare', pick < 0 ? `${clip(t.content, 50)}: neither worked` : `kept ${pair[pick].model}'s (${why})`)
1013
+ if (pick < 0) t.status = 'pending'
1014
+ if (pick < 0) return `## ${t.content}: not done\n${results.map((r) => `${r.model.model}: ${clip(r.said, 800)}${r.check?.broken ? `\nHeartCode's check: ${clip(r.check.report, 400)}` : ''}`).join('\n\n')}`
1015
+ // the better one's files into the project, each recorded for /rewind and the checks
1016
+ for (const f of t.files) {
1017
+ const from = path.join(copies[pick], f), to = path.join(s.root, f)
1018
+ const before = fs.existsSync(to) ? fs.readFileSync(to, 'utf8') : null
1019
+ const now = fs.existsSync(from) ? fs.readFileSync(from, 'utf8') : null
1020
+ if (before === now) continue
1021
+ s.track?.(f, before)
1022
+ if (now === null) fs.rmSync(to, { force: true })
1023
+ else fs.mkdirSync(path.dirname(to), { recursive: true }), fs.writeFileSync(to, now)
1024
+ s.changed?.add(f)
1025
+ s.lastChangeAt = ++s.seq
1026
+ }
1027
+ t.status = 'completed'
1028
+ t.by = pair[pick].model
1029
+ t.byProvider = pair[pick].provider
1030
+ return `## ${t.content} (done by ${pair[pick].model} and ${pair[1 - pick].model}; ${pair[pick].model}'s kept: ${why}): done\n${clip(results[pick].said, 3000)}`
1031
+ } finally {
1032
+ for (const d of copies) fs.rmSync(d, { recursive: true, force: true })
1033
+ }
1034
+ }
1035
+
1036
+ // The project in a folder of its own, for a helper to work in apart (node_modules linked, not copied;
1037
+ // .git and HeartCode's own folder left out). ponytail: copies every other file; a huge project is slow to copy.
1038
+ function copyProject(root) {
1039
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'heartcode-part-'))
1040
+ fs.cpSync(root, dir, { recursive: true, filter: (src) => src === root || !['node_modules', '.git', '.heartcode'].includes(path.basename(src)) })
1041
+ if (fs.existsSync(path.join(root, 'node_modules'))) fs.symlinkSync(path.join(root, 'node_modules'), path.join(dir, 'node_modules'), 'junction') // a junction: Windows needs no admin rights for it
1042
+ return dir
1043
+ }
1044
+
801
1045
  // ask_user: questions for the user mid-task, each with choices (and their own answer); several are
802
1046
  // tabs in one dialog (←/→ between them, then Send). Nobody answers for ASK_WAIT seconds (each key
803
1047
  // starts the wait again): the recommended ones, the first of each, are taken for what's unanswered.
@@ -825,7 +1069,7 @@ async function askUser(s, args) {
825
1069
  s.askedUser = true // asked through the dialog this message (not as text: see askedInText)
826
1070
  for (const q of qs) {
827
1071
  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 }
1072
+ q.own = { label: 'Something else', desc: 'type an answer', own: true }
829
1073
  }
830
1074
  s.ui.stopSpin()
831
1075
  const tabbed = qs.length > 1 && s.ui.full
@@ -841,7 +1085,7 @@ async function askUser(s, args) {
841
1085
  // the last tab: every answer, sent with Enter (or after ASK_WAIT seconds)
842
1086
  const body = qs.map((q, j) => `${q.question} ${c.faint('›')} ${answerOf(said[j]) || `${q.items[0].label} ${c.faint('(recommended)')}`}`).join('\n')
843
1087
  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' } })
1088
+ 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
1089
  if (got?.nav) {
846
1090
  i = Math.min(qs.length, Math.max(0, i + got.nav)) // → on Send: stays there
847
1091
  continue
@@ -864,8 +1108,8 @@ async function askUser(s, args) {
864
1108
  let text = ''
865
1109
  if (list.some((x) => x.own)) {
866
1110
  // 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' })
1111
+ text = q.own.text?.trim() || ((await s.ui.ask(`${c.bold('Answer')} ${c.dim('›')} `, { initial: said[i]?.text ?? '' }))?.trim() ?? '')
1112
+ Object.assign(q.own, { text, desc: text ? `› ${text}` : 'type an answer' })
869
1113
  if (!text && list.length === 1) continue // nothing typed: the same question again
870
1114
  }
871
1115
  if (s.ui.autoPicked) {
@@ -1161,6 +1405,7 @@ async function callMcp(s, server, tool, a, signal) {
1161
1405
  }
1162
1406
  note = `\n(${s.pendingImages.length - shown} image(s): shown to you in the next message${left.length ? `; not shown: ${left.join('; ')}` : ''})`
1163
1407
  } else if (files.length && s.team?.().some((t) => t.images)) note = `\n${prompt('agent/tool-images', { files: files.join('\n'), unseen: true })}`
1408
+ else if (files.length && s.describeFor) note = `\n${await s.describeFor(files).catch((e) => `(couldn't have the image(s) described: ${e.message})`)}`
1164
1409
  else if (files.length) note = `\n(${files.length} image(s) not shown: this model can't see images)`
1165
1410
  const mendNote = mended.fixed.length ? `\n(HeartCode corrected the arguments: ${mended.fixed.join('; ')}. Use them that way next time.)` : ''
1166
1411
  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,