heartcode 0.1.60 → 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/CHANGELOG.md +42 -0
- package/README.md +24 -11
- package/bin/heartcode.js +27 -13
- package/package.json +1 -1
- package/prompts/agent.md +47 -9
- package/src/agent.js +80 -14
- package/src/background.js +2 -8
- package/src/capabilities.js +1 -1
- package/src/check.js +69 -4
- package/src/client.js +8 -5
- package/src/config.js +29 -0
- package/src/format.js +5 -3
- package/src/http.js +96 -0
- package/src/importer.js +1 -0
- package/src/lsp.js +3 -6
- package/src/mcp.js +4 -6
- package/src/oauth.js +1 -0
- package/src/rankings.js +7 -0
- package/src/settings.html +53 -39
- package/src/settings.js +12 -9
- package/src/spawn.js +48 -0
- package/src/telegram.js +1 -0
- package/src/tools.js +209 -18
- package/src/ui.js +58 -19
- package/src/update.js +1 -0
- package/src/usage.js +1 -0
- package/src/voice.js +20 -6
- package/src/web.js +1 -0
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', 'stuck'] }, why: str, 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)
|
|
@@ -708,8 +761,8 @@ export function extraTools(s) {
|
|
|
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
763
|
const MARK = { pending: '☐', in_progress: '◐', completed: '☑', stuck: '⚠' }
|
|
711
|
-
// In the conversation:
|
|
712
|
-
// status changed, on one line;
|
|
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
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) {
|
|
@@ -719,7 +772,13 @@ function showTodos(s, before, todos) {
|
|
|
719
772
|
// (steps added, taken out, or whose status moved); the whole plan is pinned under the spinner
|
|
720
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))
|
|
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
784
|
...todos.filter((t) => was.get(t.content) !== `${t.status}${t.why ?? ''}`).map((t) => (was.has(t.content) ? item(t) : `${c.faint('+')} ${item(t)}`)),
|
|
@@ -738,7 +797,7 @@ 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?.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) }) }))
|
|
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
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' }))
|
|
744
803
|
.map(({ why, ...t }) => (t.status === 'stuck' ? { ...t, why: why || 'no reason given' } : t)) // a reason only on a stuck step
|
|
@@ -754,12 +813,20 @@ async function todoTool(s, args, signal, id) {
|
|
|
754
813
|
// a step it said it was stuck on, now done: what got it out is worth learning (agent.js)
|
|
755
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 })
|
|
756
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)}`
|
|
757
|
-
|
|
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)
|
|
758
825
|
const done = todos.filter((t) => t.status === 'completed').length
|
|
759
826
|
const next = todos.find((t) => t.status !== 'completed')
|
|
760
827
|
// a plan of several parts with none given to another model or run side by side: asked once a message
|
|
761
828
|
const open = todos.filter((t) => t.status === 'pending')
|
|
762
|
-
const askSplit = !parts && !s.isSub && !s.splitAsked && open.length >=
|
|
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'
|
|
763
830
|
if (askSplit) s.splitAsked = true
|
|
764
831
|
// a plan of a few steps made without looking anything up: asked once a message whether it uses something to read up on
|
|
765
832
|
const askResearch = !parts && !s.isSub && !s.researchAsked && !s.lookedUp && !s.research?.lookedUp && open.length >= 2
|
|
@@ -813,6 +880,38 @@ function secondOpinionModel(s) {
|
|
|
813
880
|
return helpers.find((t) => t.jobs.includes('hard')) ?? helpers[0] ?? (team.some((t) => t.jobs) ? null : team[0]) ?? null
|
|
814
881
|
}
|
|
815
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
|
+
|
|
816
915
|
// The plan's parts marked parallel (or given to another model): each started at once as a helper
|
|
817
916
|
// on its model, all at the same time, each changing only the files its part owns; marked done when
|
|
818
917
|
// it reports back. What they did, for the model to put together and check. '' when none.
|
|
@@ -834,6 +933,10 @@ async function runParts(s, todos, signal, id) {
|
|
|
834
933
|
const reports = await Promise.all(
|
|
835
934
|
parts.map(async (t) => {
|
|
836
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
|
+
}
|
|
837
940
|
let out
|
|
838
941
|
try {
|
|
839
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)
|
|
@@ -851,6 +954,94 @@ async function runParts(s, todos, signal, id) {
|
|
|
851
954
|
return prompt('agent/parts-done', { reports: reports.join('\n\n'), unknown: unknown.join(', '), models: yours.map((y) => `${y.provider} ${y.model}`).join(', ') })
|
|
852
955
|
}
|
|
853
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
|
+
|
|
854
1045
|
// ask_user: questions for the user mid-task, each with choices (and their own answer); several are
|
|
855
1046
|
// tabs in one dialog (←/→ between them, then Send). Nobody answers for ASK_WAIT seconds (each key
|
|
856
1047
|
// starts the wait again): the recommended ones, the first of each, are taken for what's unanswered.
|
package/src/ui.js
CHANGED
|
@@ -109,11 +109,28 @@ setTheme()
|
|
|
109
109
|
|
|
110
110
|
// keybindings.json: { "alt+g": "cycle_permissions", "alt+r": "/rewind", "shift+tab": "none" }.
|
|
111
111
|
// Actions: stop, send_first, send_all, queue_mode, cycle_permissions, newline, clear_input, scroll_up, scroll_down (a page),
|
|
112
|
-
// scroll_line_up, scroll_line_down (3 lines), scroll_top, scroll_bottom, voice, toggle_thinking, background_log, new_tab,
|
|
112
|
+
// scroll_line_up, scroll_line_down (3 lines), scroll_top, scroll_bottom, voice, toggle_thinking, show_plan, background_log, new_tab,
|
|
113
113
|
// close_tab, next_tab, prev_tab, tab_1…tab_9, none (turns a
|
|
114
114
|
// built-in key off); anything else is sent as typed (a /command or a message). Ctrl+C stays Ctrl+C.
|
|
115
115
|
// A key as people read it ("alt+shift+down" → "Alt+Shift+↓")
|
|
116
116
|
const KEY_NAMES = { pageup: 'PgUp', pagedown: 'PgDn', up: '↑', down: '↓', left: '←', right: '→', ctrl: 'Ctrl', alt: 'Alt', shift: 'Shift' }
|
|
117
|
+
// A text's last n rows at width w (its lines' spaces squeezed, long ones wrapped at spaces), the
|
|
118
|
+
// first starting with … when there was more before it: thinking shown in two rows, however long.
|
|
119
|
+
export function lastRows(text, w, n) {
|
|
120
|
+
w = Math.max(4, w - 2) // room for the "… " in front
|
|
121
|
+
const rows = String(text).split('\n').map((l) => l.replace(/\s+/g, ' ').trim()).filter(Boolean).flatMap((l) => l.match(new RegExp(`.{1,${w}}(\\s|$)|.{${w}}`, 'g')) ?? [l]).map((l) => l.trim()).filter(Boolean)
|
|
122
|
+
const out = rows.slice(-n)
|
|
123
|
+
if (rows.length > n) out[0] = `… ${out[0]}`
|
|
124
|
+
return out
|
|
125
|
+
}
|
|
126
|
+
// The steps of a plan to show when only n fit: what's being done or stuck first, then what's next,
|
|
127
|
+
// then the last ones done; in the plan's order. The rest: a count, and the key that shows all of it.
|
|
128
|
+
export function planPick(todos, n = 3) {
|
|
129
|
+
const rank = { in_progress: 0, stuck: 0, pending: 1, completed: 2 }
|
|
130
|
+
const order = todos.map((t, i) => [t, i]).sort((a, b) => rank[a[0].status] - rank[b[0].status] || (a[0].status === 'completed' ? b[1] - a[1] : a[1] - b[1]))
|
|
131
|
+
const keep = new Set(order.slice(0, n).map(([, i]) => i))
|
|
132
|
+
return { shown: todos.filter((_, i) => keep.has(i)), hidden: todos.length - keep.size }
|
|
133
|
+
}
|
|
117
134
|
export const prettyKey = (k) => k.split('+').map((p) => KEY_NAMES[p] ?? (p.length === 1 ? p.toUpperCase() : p[0].toUpperCase() + p.slice(1))).join('+')
|
|
118
135
|
const CONTROL_KEYS = { '\x1c': 'ctrl+\\', '\x1d': 'ctrl+]', '\x1e': 'ctrl+^', '\x1f': 'ctrl+_' } // no name from readline
|
|
119
136
|
export const keyId = (key, s = '') => CONTROL_KEYS[key.sequence ?? s] ?? [key.ctrl && 'ctrl', key.meta && 'alt', key.shift && 'shift', key.name ?? s].filter(Boolean).join('+').toLowerCase()
|
|
@@ -125,9 +142,10 @@ export const keyId = (key, s = '') => CONTROL_KEYS[key.sequence ?? s] ?? [key.ct
|
|
|
125
142
|
// Alt+A all of them (as one message); Alt+M switches what goes when an answer is done (all or the
|
|
126
143
|
// next one). /voice records (Space in an empty box, or a key in keybindings.json); Alt+T, Alt+W,
|
|
127
144
|
// Alt+N/P, Alt+1…9: tabs; Shift+↑↓ and Alt+↑↓ scroll the conversation (as PgUp/PgDn and the mouse
|
|
128
|
-
// wheel do), Alt+Shift+↑↓ to its top and bottom; Alt+O: all of the model's thinking, or its last lines
|
|
145
|
+
// wheel do), Alt+Shift+↑↓ to its top and bottom; Alt+O: all of the model's thinking, or its last lines;
|
|
146
|
+
// Alt+L: the whole plan.
|
|
129
147
|
// keybindings.json can move any of them.
|
|
130
|
-
export const DEFAULT_KEYS = { 'alt+o': 'toggle_thinking', 'alt+b': 'background_log', 'alt+s': 'send_first', 'alt+a': 'send_all', 'alt+m': 'queue_mode', 'shift+up': 'scroll_line_up', 'shift+down': 'scroll_line_down', 'alt+up': 'scroll_up', 'alt+down': 'scroll_down', 'alt+shift+up': 'scroll_top', 'alt+shift+down': 'scroll_bottom', 'alt+t': 'new_tab', 'alt+w': 'close_tab', 'alt+n': 'next_tab', 'alt+p': 'prev_tab', ...Object.fromEntries([1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => [`alt+${n}`, `tab_${n}`])) }
|
|
148
|
+
export const DEFAULT_KEYS = { 'alt+o': 'toggle_thinking', 'alt+l': 'show_plan', 'alt+b': 'background_log', 'alt+s': 'send_first', 'alt+a': 'send_all', 'alt+m': 'queue_mode', 'shift+up': 'scroll_line_up', 'shift+down': 'scroll_line_down', 'alt+up': 'scroll_up', 'alt+down': 'scroll_down', 'alt+shift+up': 'scroll_top', 'alt+shift+down': 'scroll_bottom', 'alt+t': 'new_tab', 'alt+w': 'close_tab', 'alt+n': 'next_tab', 'alt+p': 'prev_tab', ...Object.fromEntries([1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => [`alt+${n}`, `tab_${n}`])) }
|
|
131
149
|
export function loadKeys(file = path.join(HOME, 'keybindings.json')) {
|
|
132
150
|
let raw = {}
|
|
133
151
|
try {
|
|
@@ -967,8 +985,8 @@ export class UI {
|
|
|
967
985
|
}
|
|
968
986
|
}
|
|
969
987
|
|
|
970
|
-
// The plan (todo list) while it works, kept in sight under the spinner: how much is done,
|
|
971
|
-
// being done, what's
|
|
988
|
+
// The plan (todo list) while it works, kept in sight under the spinner: how much is done, and three
|
|
989
|
+
// of its steps (what's being done, then what's next); the rest on a key (show_plan).
|
|
972
990
|
#todoLines(cols) {
|
|
973
991
|
const todos = this.todos?.() ?? []
|
|
974
992
|
const open = todos.filter((t) => t.status !== 'completed')
|
|
@@ -977,15 +995,24 @@ export class UI {
|
|
|
977
995
|
const mark = { pending: c.muted('☐'), in_progress: c.info('◐'), completed: c.faint('☑'), stuck: c.warn('⚠') }
|
|
978
996
|
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
997
|
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
|
-
const shown
|
|
998
|
+
const { shown, hidden } = planPick(todos)
|
|
981
999
|
return [
|
|
982
1000
|
fit(` ${c.muted('Plan')} ${c.faint(`· ${done} of ${todos.length} done`)}`, cols),
|
|
983
|
-
...(todos.length > 8 && done ? [fit(` ${c.faint(`☑ ${done} done`)}`, cols)] : []),
|
|
984
1001
|
...shown.map(line),
|
|
985
|
-
...(
|
|
1002
|
+
...(hidden ? [fit(` ${c.faint(`… ${hidden} more${this.keyFor('show_plan') ? ` · ${this.keyFor('show_plan')} shows all of it` : ''}`)}`, cols)] : []),
|
|
986
1003
|
]
|
|
987
1004
|
}
|
|
988
1005
|
|
|
1006
|
+
// The whole plan in a box (show_plan, /todos): every step and its state; the key closes it again.
|
|
1007
|
+
showPlan() {
|
|
1008
|
+
const todos = this.todos?.() ?? []
|
|
1009
|
+
if (!todos.length) return this.notice('No plan right now: the model writes one for a task of a few steps', 2500)
|
|
1010
|
+
const mark = { pending: '☐', in_progress: '◐', completed: '☑', stuck: '⚠' }
|
|
1011
|
+
const paint = { pending: c.muted, in_progress: (x) => c.info(c.bold(x)), completed: c.faint, stuck: c.warn }
|
|
1012
|
+
const done = todos.filter((t) => t.status === 'completed').length
|
|
1013
|
+
this.showText(`Plan · ${done} of ${todos.length} done`, todos.map((t) => paint[t.status](`${mark[t.status]} ${t.content}`) + (t.status === 'stuck' && t.why ? c.warn(`: ${t.why}`) : '') + (t.by ? c.faint(` · ${t.by}`) : '')).join('\n'), 'show_plan')
|
|
1014
|
+
}
|
|
1015
|
+
|
|
989
1016
|
// The last lines of this task's output, at most n rows of w (what a question in the middle of the work
|
|
990
1017
|
// is about): whole lines, from the start of a block (not mid-sentence), without what the question
|
|
991
1018
|
// itself says (about: its text, e.g. the command it asks to run).
|
|
@@ -1029,8 +1056,8 @@ export class UI {
|
|
|
1029
1056
|
const summary = () => {
|
|
1030
1057
|
this.thinkTail = ''
|
|
1031
1058
|
if (thought.trim() && !think) {
|
|
1032
|
-
// what it thought stays in the conversation: its last two
|
|
1033
|
-
const last = thought.
|
|
1059
|
+
// what it thought stays in the conversation: its last two rows on this screen (all of it: Alt+O)
|
|
1060
|
+
const last = lastRows(thought, Math.max(20, (this.out.columns || 80) - 4), 2)
|
|
1034
1061
|
this.print(c.faint(c.italic(`✻ ${who ? `${who} ` : ''}thought for ${secs()}${this.keyFor('toggle_thinking') ? ` · ${this.keyFor('toggle_thinking')} shows all of it` : ''}`)))
|
|
1035
1062
|
this.print(c.think(c.italic(last.map((l) => ` ${l}`).join('\n'))))
|
|
1036
1063
|
this.lastThought = { who, text: thought } // Alt+O shows it, now that it's over (showLastThought)
|
|
@@ -1344,9 +1371,8 @@ export class UI {
|
|
|
1344
1371
|
}
|
|
1345
1372
|
|
|
1346
1373
|
// The conversation as screen rows (wrapped to the width; cached per line).
|
|
1347
|
-
// While it works, the
|
|
1348
|
-
//
|
|
1349
|
-
// spinner under the conversation says it.
|
|
1374
|
+
// While it works, the step running spins its ● until its result; what it waits on between steps is
|
|
1375
|
+
// said once, by the spinner under the conversation.
|
|
1350
1376
|
#rows(cols) {
|
|
1351
1377
|
if (this.wrapCols !== cols) [this.wrapped, this.wrapCols] = [[], cols]
|
|
1352
1378
|
const spin = this.timer && !this.asking ? c.brand(FRAMES[this.frame % FRAMES.length]) : null
|
|
@@ -1360,7 +1386,6 @@ export class UI {
|
|
|
1360
1386
|
if (!w || w.src !== line) this.wrapped[i] = { src: line, rows: wrapHang(line, cols) } // at spaces, wrapped rows under the text
|
|
1361
1387
|
out.push(...this.wrapped[i].rows)
|
|
1362
1388
|
})
|
|
1363
|
-
if (spin && live === -1 && !this.replying && this.statusText) out.push(...wrapHang(`${spin} ${c.muted(this.statusText)}`, cols))
|
|
1364
1389
|
return out
|
|
1365
1390
|
}
|
|
1366
1391
|
|
|
@@ -1395,11 +1420,8 @@ export class UI {
|
|
|
1395
1420
|
const timer = this.busySince ? [this.beforeRetry !== undefined && 'no answer yet', `${short(this.worked())} in all`, 'Esc twice to stop', this.thinkTail && this.keyFor('toggle_thinking') && `${this.keyFor('toggle_thinking')} shows all thinking`].filter(Boolean).join(' · ') : ''
|
|
1396
1421
|
if (this.thinkTail) {
|
|
1397
1422
|
// the thinking's last two lines (long ones wrapped), dim, changing as it comes
|
|
1398
|
-
const
|
|
1399
|
-
const lines = this.thinkTail.split('\n').map((l) => l.replace(/\s+/g, ' ').trim()).filter(Boolean).flatMap((l) => l.match(new RegExp(`.{1,${w}}(\\s|$)|.{${w}}`, 'g')) ?? [l]).map((l) => l.trim()).filter(Boolean)
|
|
1400
|
-
for (const l of lines.slice(-2)) bottom.push(fit(` ${c.think(c.italic(l))}`, cols))
|
|
1423
|
+
for (const l of lastRows(this.thinkTail, Math.max(20, cols - 6), 2)) bottom.push(fit(` ${c.think(c.italic(l))}`, cols))
|
|
1401
1424
|
}
|
|
1402
|
-
this.statusText = status // the same, at the end of the conversation (#rows)
|
|
1403
1425
|
bottom.push(fit(`${c.brand(FRAMES[this.frame % FRAMES.length])} ${c.muted(status)}`, cols))
|
|
1404
1426
|
if (timer) bottom.push(...wrapParts(timer, cols - 2).map((r) => fit(` ${c.faint(r)}`, cols)))
|
|
1405
1427
|
// helpers at work (agent.js keeps them in this.helpers: label → what it's doing), then the plan
|
|
@@ -1796,6 +1818,8 @@ export class UI {
|
|
|
1796
1818
|
return this.dictateIn()
|
|
1797
1819
|
case 'background_log':
|
|
1798
1820
|
return this.onPanel?.()
|
|
1821
|
+
case 'show_plan':
|
|
1822
|
+
return this.showPlan()
|
|
1799
1823
|
case 'stop':
|
|
1800
1824
|
return this.asking ? undefined : this.onEscape?.()
|
|
1801
1825
|
case 'cycle_permissions':
|
|
@@ -2375,16 +2399,31 @@ export class UI {
|
|
|
2375
2399
|
this.write(s + '\n')
|
|
2376
2400
|
}
|
|
2377
2401
|
// who: the model that made this call (named after it)
|
|
2402
|
+
// The same call again right after it (nothing printed between but its result, as a model polling a
|
|
2403
|
+
// page does): the line it has counts it (×2, ×3…) instead of another of the same, and its result
|
|
2404
|
+
// makes way for the new one's.
|
|
2378
2405
|
step(name, detail = '', who = '') {
|
|
2406
|
+
const line = `${c.accent('●')} ${c.accent(c.bold(name))} ${c.info(detail)}${who ? c.faint(` · ${who}`) : ''}`
|
|
2407
|
+
const was = this.lastStep
|
|
2408
|
+
const end = this.log.length - 1 // the line being written (empty, after a whole line)
|
|
2409
|
+
if (this.full && was?.line === line && was.log === this.log && this.log[was.at] === was.shown && !plainOf(this.log[end]) && (end === was.at + 1 || end === was.after)) {
|
|
2410
|
+
const open = this.log[end]
|
|
2411
|
+
this.log.length = was.at + 1 // its result out: the new one's comes
|
|
2412
|
+
this.log.push(open)
|
|
2413
|
+
was.shown = `${line}${c.faint(` ×${++was.n}`)}`
|
|
2414
|
+
this.log[was.at] = this.liveStep = was.shown // its ● spins until its result (#rows)
|
|
2415
|
+
return this.render()
|
|
2416
|
+
}
|
|
2379
2417
|
if (this.afterBlock) this.gap()
|
|
2380
2418
|
this.afterBlock = false
|
|
2381
|
-
const line = `${c.accent('●')} ${c.accent(c.bold(name))} ${c.info(detail)}${who ? c.faint(` · ${who}`) : ''}`
|
|
2382
2419
|
this.print(line)
|
|
2383
2420
|
this.liveStep = line // its ● spins until its result (#rows)
|
|
2421
|
+
this.lastStep = { line, shown: line, n: 1, log: this.log, at: this.log.length - 2 }
|
|
2384
2422
|
}
|
|
2385
2423
|
result(text) {
|
|
2386
2424
|
this.liveStep = null
|
|
2387
2425
|
this.print(` ${c.ghost('⎿')} ${c.faint(text)}`)
|
|
2426
|
+
if (this.lastStep?.log === this.log && this.lastStep.at === this.log.length - 3) this.lastStep.after = this.log.length - 1 // its step's, right under it
|
|
2388
2427
|
}
|
|
2389
2428
|
warn(text) {
|
|
2390
2429
|
log('warn', text)
|
package/src/update.js
CHANGED
|
@@ -5,6 +5,7 @@ import fs from 'node:fs'
|
|
|
5
5
|
import path from 'node:path'
|
|
6
6
|
import { fileURLToPath } from 'node:url'
|
|
7
7
|
import { HOME, VERSION, readJson, writeJson } from './config.js'
|
|
8
|
+
import { fetch } from './http.js' // not the built-in one: see http.js
|
|
8
9
|
|
|
9
10
|
const FILE = path.join(HOME, 'update-check.json')
|
|
10
11
|
const PKG = fileURLToPath(new URL('..', import.meta.url))
|
package/src/usage.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import path from 'node:path'
|
|
7
7
|
import { HOME, readJson, writeJson } from './config.js'
|
|
8
8
|
import { log } from './log.js'
|
|
9
|
+
import { fetch } from './http.js' // not the built-in one: see http.js
|
|
9
10
|
|
|
10
11
|
const FILE = path.join(HOME, 'prices.json')
|
|
11
12
|
const DAY = 86_400_000
|
package/src/voice.js
CHANGED
|
@@ -10,12 +10,13 @@
|
|
|
10
10
|
import fs from 'node:fs'
|
|
11
11
|
import os from 'node:os'
|
|
12
12
|
import path from 'node:path'
|
|
13
|
-
import { spawn } from 'node:child_process'
|
|
13
|
+
import { spawn, spawnSync } from 'node:child_process'
|
|
14
14
|
import { HOME } from './config.js'
|
|
15
15
|
import { runCommand } from './tools.js'
|
|
16
|
+
import { onPath } from './spawn.js'
|
|
16
17
|
import { log } from './log.js'
|
|
18
|
+
import { fetch } from './http.js' // not the built-in one: see http.js
|
|
17
19
|
|
|
18
|
-
const onPath = (cmd) => (process.env.PATH ?? '').split(path.delimiter).find((d) => d && fs.existsSync(path.join(d, cmd)))
|
|
19
20
|
|
|
20
21
|
// A whisper.cpp model already on disk: the configured one, else the best found (small > base > tiny).
|
|
21
22
|
// fast: the quickest found instead (tiny > base > small), for the words shown while you speak.
|
|
@@ -33,11 +34,24 @@ export function localModel(cfg = {}, { fast = false } = {}) {
|
|
|
33
34
|
return found.sort((a, b) => (rank(a) === -1 ? 9 : rank(a)) - (rank(b) === -1 ? 9 : rank(b)))[0] ?? (fast ? localModel(cfg) : null)
|
|
34
35
|
}
|
|
35
36
|
|
|
37
|
+
// How to install a program here: the usual package manager of this OS
|
|
38
|
+
const install = (mac, win, linux) => (process.platform === 'darwin' ? `brew install ${mac}` : process.platform === 'win32' ? `winget install ${win}` : linux)
|
|
39
|
+
|
|
40
|
+
// The microphone, as ffmpeg's input: the default device (macOS, PulseAudio/PipeWire on Linux); on
|
|
41
|
+
// Windows DirectShow needs a device's name, so the first microphone ffmpeg lists (kept once found)
|
|
42
|
+
let winMic
|
|
43
|
+
function micInput() {
|
|
44
|
+
if (process.platform === 'darwin') return ['-f', 'avfoundation', '-i', ':default']
|
|
45
|
+
if (process.platform !== 'win32') return ['-f', 'pulse', '-i', 'default']
|
|
46
|
+
winMic ??= /"([^"]+)"\s*\(audio\)/.exec(spawnSync('ffmpeg', ['-hide_banner', '-list_devices', 'true', '-f', 'dshow', '-i', 'dummy'], { encoding: 'utf8' }).stderr ?? '')?.[1] ?? ''
|
|
47
|
+
return ['-f', 'dshow', '-i', `audio=${winMic || 'default'}`]
|
|
48
|
+
}
|
|
49
|
+
|
|
36
50
|
// Why voice can't work here, or null when it can.
|
|
37
51
|
export function voiceProblem(cfg = {}, providers = {}) {
|
|
38
|
-
if (!onPath('ffmpeg')) return
|
|
52
|
+
if (!onPath('ffmpeg')) return `voice input needs ffmpeg to record (${install('ffmpeg', 'ffmpeg', 'install ffmpeg with your package manager')})`
|
|
39
53
|
if (cfg.provider) return providers[cfg.provider] ? null : `voice.provider "${cfg.provider}" isn't one of the providers`
|
|
40
|
-
if (!onPath('whisper-cli')) return
|
|
54
|
+
if (!onPath('whisper-cli')) return `voice input needs whisper-cli (${process.platform === 'darwin' ? 'brew install whisper-cpp' : 'whisper.cpp, from github.com/ggml-org/whisper.cpp'}) and a model, or "voice": { "provider": …, "model": … } in ~/.heart/config.json`
|
|
41
55
|
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
56
|
}
|
|
43
57
|
|
|
@@ -47,7 +61,7 @@ const RATE = 16000 // 16 kHz mono, 16-bit: what whisper wants
|
|
|
47
61
|
// said so far (raw), seconds(), stop() → all of it, cancel() }.
|
|
48
62
|
export function listen() {
|
|
49
63
|
// HEART_VOICE_FILE: a sound file played in at its own speed instead of the microphone (tests)
|
|
50
|
-
const input = process.env.HEART_VOICE_FILE ? ['-re', '-i', process.env.HEART_VOICE_FILE] :
|
|
64
|
+
const input = process.env.HEART_VOICE_FILE ? ['-re', '-i', process.env.HEART_VOICE_FILE] : micInput()
|
|
51
65
|
const child = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', ...input, '-ac', '1', '-ar', String(RATE), '-f', 's16le', 'pipe:1'], { stdio: ['pipe', 'pipe', 'pipe'] })
|
|
52
66
|
const chunks = []
|
|
53
67
|
let size = 0
|
|
@@ -106,7 +120,7 @@ export async function transcribePcm(pcm, cfg = {}, providers = {}, { fast = fals
|
|
|
106
120
|
// Starts recording to a 16 kHz mono WAV. Returns { stop() → the file, cancel() }.
|
|
107
121
|
export function record() {
|
|
108
122
|
const file = path.join(os.tmpdir(), `heartcode-voice-${process.pid}-${Date.now()}.wav`)
|
|
109
|
-
const input =
|
|
123
|
+
const input = micInput()
|
|
110
124
|
const start = (inp) => spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-y', ...inp, '-ac', '1', '-ar', '16000', file], { stdio: ['pipe', 'ignore', 'pipe'] })
|
|
111
125
|
let child = start(input)
|
|
112
126
|
let err = ''
|
package/src/web.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import path from 'node:path'
|
|
8
8
|
import { HOME, CONFIG_FILE, readJson, writeJson } from './config.js'
|
|
9
9
|
import { keywords } from './memory.js'
|
|
10
|
+
import { fetch } from './http.js' // not the built-in one: see http.js
|
|
10
11
|
// ponytail: scraping, no API; add a keyed backend (Brave, Tavily) if DuckDuckGo blocks for good.
|
|
11
12
|
|
|
12
13
|
const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124 Safari/537.36'
|