heartcode 0.1.25 → 0.1.30

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
@@ -2,16 +2,17 @@ import fs from 'node:fs'
2
2
  import { createHash } from 'node:crypto'
3
3
  import { AsyncLocalStorage } from 'node:async_hooks'
4
4
  import { log } from './log.js'
5
- import { slug, fullSlug } from './memory.js'
5
+ import { slug, fullSlug, keywords } from './memory.js'
6
6
  import { fillArgs } from './skills.js'
7
7
  import { prompt } from './prompts.js'
8
8
  import path from 'node:path'
9
9
  import os from 'node:os'
10
10
  import { spawn, execFileSync } from 'node:child_process'
11
- import { applyEdit } from './edit.js'
12
- import { readJson } from './config.js'
11
+ import { applyEdit, closest, trimBlank } from './edit.js'
12
+ import { readJson, HOME } from './config.js'
13
13
  import { c, diffLines, renderDiff } from './ui.js'
14
- import { webFetch, webSearch } from './web.js'
14
+ import { webFetch, webSearch, fetchPage, pageView } from './web.js'
15
+ import { savePage, saveSearch, findResearch } from './research.js'
15
16
  import { runHooks } from './hooks.js'
16
17
  import { parsePatch, applyChunks } from './patch.js'
17
18
  import { formatFile } from './format.js'
@@ -24,13 +25,16 @@ export const tail = (s, n) => (s.length > n ? '…' + s.slice(-n) : s)
24
25
 
25
26
  // Tool output too long for the conversation is saved here (one folder per chat), where read_file
26
27
  // and search can read it although it's outside the project.
27
- export const OUTPUTS = path.join(os.tmpdir(), 'heartcode-outputs')
28
+ export const OUTPUTS = path.join(HOME, 'outputs') // kept with the chat: a resumed one's pointers still open
29
+ const LEGACY_OUTPUTS = path.join(os.tmpdir(), 'heartcode-outputs') // where older HeartCode kept them
30
+ export const isSavedOutput = (abs) => [OUTPUTS, LEGACY_OUTPUTS].some((d) => String(abs).startsWith(d + path.sep))
28
31
  // data: text, or an image's bytes (ext: png…)
32
+ let saved = 0
29
33
  export function saveOutput(chatId, name, data, ext = 'txt') {
30
34
  try {
31
35
  const dir = path.join(OUTPUTS, String(chatId ?? 'chat'))
32
36
  fs.mkdirSync(dir, { recursive: true })
33
- const file = path.join(dir, `${Date.now().toString(36)}-${String(name).replace(/[^\w-]/g, '_').slice(0, 60)}.${ext}`)
37
+ const file = path.join(dir, `${Date.now().toString(36)}-${(++saved).toString(36)}-${String(name).replace(/[^\w-]/g, '_').slice(0, 60)}.${ext}`) // several in one millisecond: each its own file
34
38
  fs.writeFileSync(file, data)
35
39
  return file
36
40
  } catch (e) {
@@ -44,7 +48,7 @@ export function resolveIn(root, p) {
44
48
  if (!clean) throw new Error('no path given')
45
49
  const bare = root.replace(/^[\\/]+/, '') // the project's own path, its leading "/" left out by a sloppy copy
46
50
  let abs = clean === bare || clean.startsWith(bare + '/') ? path.join(root, clean.slice(bare.length)) : path.resolve(root, clean)
47
- if (abs.startsWith(OUTPUTS + path.sep)) return abs // a saved tool output
51
+ if (isSavedOutput(abs)) return abs // a saved tool output
48
52
  // "num.js:" or "num.js," from a sloppy model: the file without the stray mark, if that one exists
49
53
  const trimmed = path.resolve(root, clean.replace(/[:;,.]+$/, ''))
50
54
  if (trimmed !== abs && !fs.existsSync(abs) && fs.existsSync(trimmed)) abs = trimmed
@@ -204,7 +208,11 @@ export function searchFiles(root, query, sub = '', limit = 50) {
204
208
  re = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), ci ? 'i' : '')
205
209
  }
206
210
  const abs = sub ? resolveIn(root, sub) : ''
207
- const saved = abs.startsWith(OUTPUTS + path.sep) // a tool output saved outside the project
211
+ let single = false // one file named: searched whatever lists leave out (a saved page, a .gitignored file)
212
+ try {
213
+ single = Boolean(abs) && fs.statSync(abs).isFile()
214
+ } catch {}
215
+ const saved = isSavedOutput(abs) || single
208
216
  const prefix = sub && !saved ? path.relative(root, abs) : ''
209
217
  const hits = []
210
218
  for (const f of saved ? [abs] : listFiles(root)) {
@@ -449,6 +457,7 @@ function changesSince(s, before) {
449
457
  const notes = []
450
458
  for (const rel of new Set([...before.keys(), ...after.keys()])) {
451
459
  if (before.get(rel) === after.get(rel)) continue
460
+ if (/^\.heartcode[\\/]/.test(rel)) continue // HeartCode's own (research, memory, models) written meanwhile — a page fetched while the command ran — not the command's
452
461
  if (!(before.complete && after.complete) && (!before.has(rel) || !after.has(rel))) continue // a list cut at its limit: in one, not the other, says nothing
453
462
  const old = was.get(rel)
454
463
  const next = after.has(rel) ? s.fileCache.get(rel)?.text : undefined
@@ -486,12 +495,12 @@ export const TOOL_DEFS = [
486
495
  { name: 'find_command', description: prompt('agent/tool-find_command'), parameters: obj({ names: { type: 'array', items: str } }, ['names']) },
487
496
  { 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']) },
488
497
  // One edit per call: a list of edits per call measured 2–6 malformed calls per benchmark run vs 0.
489
- { name: 'edit_file', description: prompt('agent/tool-edit_file'), parameters: obj({ path: str, search: str, replace: str }, ['path', 'search', 'replace']) },
498
+ { 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']) },
490
499
  { name: 'write_file', description: prompt('agent/tool-write_file'), parameters: obj({ path: str, content: str, append: { type: 'boolean' } }, ['path', 'content']) },
491
500
  { name: 'run_command', description: prompt('agent/tool-run_command'), parameters: obj({ command: str }, ['command']) },
492
501
  { name: 'todo', description: prompt('agent/tool-todo'), parameters: obj({ todos: { type: 'array', items: obj({ content: str, status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] } }, ['content', 'status']) } }, ['todos']) },
493
- { name: 'web_search', description: prompt('agent/tool-web_search'), parameters: obj({ query: str }, ['query']) },
494
- { name: 'web_fetch', description: prompt('agent/tool-web_fetch'), parameters: obj({ url: str, start: int }, ['url']) },
502
+ { name: 'web_search', description: prompt('agent/tool-web_search'), parameters: obj({ query: str, fresh: { type: 'boolean' } }, ['query']) },
503
+ { name: 'web_fetch', description: prompt('agent/tool-web_fetch'), parameters: obj({ url: str, look_for: str, start: int }, ['url']) },
495
504
  { name: 'ask_user', description: prompt('agent/tool-ask_user'), parameters: obj({ question: str, options: { type: 'array', items: str }, multiple: { type: 'boolean' } }, ['question']) },
496
505
  ]
497
506
 
@@ -513,21 +522,20 @@ export function readOnlyCommand(cmd) {
513
522
  return c.split(/\s*(?:&&|\|\||;|\|)\s*/).every((part) => READ_ONLY.test(part))
514
523
  }
515
524
 
516
- // MCP servers' tools as the model sees them: each its own tool, mcp__server__tool (Claude Code's
517
- // names), with its description and arguments, the way the model would see them in Claude Code.
518
- // Servers whose tools aren't known yet (still starting, failed), or too many tools at once, go
519
- // through the one mcp tool instead. Sets s.mcpDirect (name → { server, tool, def }), s.mcpMeta
520
- // (servers behind the mcp tool) and s.mcpInstructions (what the servers say about using them).
521
- export const MAX_MCP_TOOLS = 100
525
+ // MCP servers' tools as the model sees them: one tool, mcp, whose description lists every server's
526
+ // tools by name with one line on what each does — not each tool's whole schema in every request
527
+ // (two browser servers' schemas alone were ~14k tokens a request). A tool's arguments come when
528
+ // they're needed: "describe" shows them, and a call whose arguments don't fit its schema gets the
529
+ // schema back with what's wrong (nothing is sent to the server). Sets s.mcpDirect
530
+ // (mcp__server__tool → { server, tool, def }: only to understand a call by that name — an older
531
+ // conversation's, or a model used to Claude Code's names), s.mcpCatalog and s.mcpInstructions (what
532
+ // the servers say about using them).
522
533
  export async function loadMcpTools(s, signal) {
523
- if (!s.mcp?.names.length) return Object.assign(s, { mcpDirect: new Map(), mcpMeta: [], mcpInstructions: '' })
534
+ if (!s.mcp?.names.length) return Object.assign(s, { mcpDirect: new Map(), mcpInstructions: '' })
524
535
  const catalog = await s.mcp.catalog(signal)
525
- // the servers with the fewest tools first, while they fit
526
- const known = [...catalog].sort((a, b) => a[1].tools.length - b[1].tools.length)
527
536
  const direct = new Map()
528
537
  const notes = []
529
- for (const [server, { tools, instructions }] of known) {
530
- if (direct.size + tools.length > MAX_MCP_TOOLS) continue
538
+ for (const [server, { tools, instructions }] of catalog) {
531
539
  for (const t of tools) {
532
540
  let n = mcpName(server, t.name)
533
541
  if (direct.has(n)) n = `${n.slice(0, 57)}_${createHash('sha256').update(`${server}/${t.name}`).digest('hex').slice(0, 6)}` // cut to the same 64 characters as another
@@ -535,33 +543,26 @@ export async function loadMcpTools(s, signal) {
535
543
  }
536
544
  if (instructions) notes.push(`### ${server}\n${instructions}`)
537
545
  }
538
- const shown = new Set([...direct.values()].map((d) => d.server))
539
- return Object.assign(s, { mcpDirect: direct, mcpMeta: s.mcp.names.filter((n) => !shown.has(n)), mcpInstructions: notes.join('\n\n'), mcpCatalog: catalog })
546
+ return Object.assign(s, { mcpDirect: direct, mcpInstructions: notes.join('\n\n'), mcpCatalog: catalog })
540
547
  }
541
548
  // Tool names may only have letters, digits, _ and - (64 at most).
542
549
  export const mcpName = (server, tool) => `mcp__${server}__${tool}`.replace(/[^\w-]/g, '_').slice(0, 64)
543
- // A schema as providers take it: an object, without the keys some refuse ($schema).
544
- function cleanSchema(x) {
545
- if (Array.isArray(x)) return x.map(cleanSchema)
546
- if (!x || typeof x !== 'object') return x
547
- return Object.fromEntries(Object.entries(x).filter(([k]) => k !== '$schema').map(([k, v]) => [k, cleanSchema(v)]))
548
- }
549
- function mcpDefs(s) {
550
- return [...(s.mcpDirect?.entries() ?? [])].map(([name, { server, tool, def }]) => {
551
- const schema = cleanSchema(def.inputSchema ?? {})
552
- return { name, description: clip(String(def.description ?? `${tool} (${server})`).trim(), 2000), parameters: { ...schema, type: 'object', properties: schema.properties ?? {} } }
553
- })
554
- }
550
+ // A tool's description cut to its first sentence (what it does), for the list.
551
+ const firstLine = (d) => String(d ?? '').trim().split(/\n|(?<=\.)\s/)[0].slice(0, 140)
555
552
 
556
- // The MCP servers' tools, the one tool for the rest, and the skill loader; each only when there's
557
- // something to offer.
553
+ // The MCP servers (one tool for all of their tools), the memory and the skill loader; each only when
554
+ // there's something to offer.
558
555
  export function extraTools(s) {
559
- const out = mcpDefs(s)
560
- const meta = s.mcpMeta ?? s.mcp?.names ?? []
561
- if (meta.length) {
562
- // no description: the names of its tools, when known, say what it's for
563
- const about = (n) => s.mcp.get(n).cfg.description || (s.mcpCatalog?.get(n) ? `tools: ${clip(s.mcpCatalog.get(n).tools.map((t) => t.name).join(', '), 300)}` : 'no description')
564
- out.push({ name: 'mcp', description: prompt('agent/tool-mcp', { servers: meta.map((n) => `${n}: ${about(n)}`).join('\n') }), parameters: obj({ server: str, tool: str, arguments: { type: 'object' } }, ['server', 'tool']) })
556
+ const out = []
557
+ const servers = s.mcp?.names ?? []
558
+ if (servers.length) {
559
+ const list = (n) => {
560
+ const cfg = s.mcp.get(n)?.cfg ?? {}
561
+ const tools = s.mcpCatalog?.get(n)?.tools
562
+ const head = `${n}${cfg.description ? ` — ${cfg.description}` : ''}`
563
+ return tools ? `${head}\n${tools.map((t) => ` - ${t.name}: ${firstLine(t.description)}`).join('\n')}` : `${head} (its tools aren't known yet: tool "list" shows them)`
564
+ }
565
+ out.push({ name: 'mcp', description: prompt('agent/tool-mcp', { servers: servers.map(list).join('\n') }), parameters: obj({ server: str, tool: str, arguments: { type: 'object' } }, ['server', 'tool']) })
565
566
  }
566
567
  if (s.memory) {
567
568
  out.push({
@@ -640,9 +641,40 @@ async function webTool(s, name, args, signal) {
640
641
  if (!what.trim()) return `error: ${name} needs ${name === 'web_search' ? '"query"' : '"url"'}`
641
642
  const ok = await s.ui.confirm(name === 'web_search' ? `Search the web for ${c.bold(what)}?` : `Fetch ${c.bold(what)}?`, 'read')
642
643
  if (ok !== true) return `The user declined this.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
643
- s.ui.spinner(name === 'web_search' ? `searching: ${clip(what, 60)}` : `fetching ${clip(what, 60)}`)
644
- return name === 'web_search' ? await webSearch(what, { signal }) : await webFetch(what, { start: args.start, signal })
644
+ // what this message's research is for: the page's look_for, else the last search, else the task
645
+ const purpose = String(args.look_for ?? '').trim() || s.lastQuery || String(s.task ?? '').split('\n')[0].slice(0, 160)
646
+ if (name === 'web_search') {
647
+ s.lastQuery = what
648
+ // already read for this project: offered first (the model decides: use it, or search fresh)
649
+ const saved = !args.fresh && s.root && !s.noResearch ? findResearch(s.root, what, 5).filter((r) => r.kind !== 'search') : []
650
+ if (saved.length) {
651
+ log('research', `"${what}": ${saved.length} saved page(s) offered first`)
652
+ return prompt('agent/research-saved', { query: what, pages: saved.map((r) => `- ${r.title} — ${r.url} (read ${r.fetched}${r.used_for ? `; used for: ${r.used_for}` : ''}) → ${r.file}`).join('\n') })
653
+ }
654
+ s.ui.spinner(`searching: ${clip(what, 60)}`)
655
+ const out = await webSearch(what, { signal })
656
+ if (s.root && !s.noResearch && !/^(error:|no results)/.test(out)) {
657
+ const { file } = saveSearch(s.root, what, out)
658
+ s.research?.push({ kind: 'search', file, title: `Search: ${what}` })
659
+ }
660
+ return out
661
+ }
662
+ s.ui.spinner(`fetching ${clip(what, 60)}`)
663
+ if (!s.root || s.noResearch) return await webFetch(what, { start: args.start, signal }) // nothing kept (--no-memory)
664
+ const page = await fetchPage(what, { signal })
665
+ if (page.error) return `error: ${page.error}`
666
+ const head = `${page.ok ? '' : `error: HTTP ${page.status}\n`}${page.url !== page.asked ? `(redirected to ${page.url})\n` : ''}`
667
+ if (!page.ok || !page.text.trim()) return `${head}${page.text.slice(0, MAX_PAGE) || '(empty page)'}` // an error page isn't worth keeping
668
+ const { file, bodyLine } = savePage(s.root, { url: page.url, title: page.title, text: page.text, query: purpose })
669
+ s.research?.push({ kind: 'page', file, url: page.url, title: page.title || page.url })
670
+ const id = runningCall.getStore()
671
+ if (id && s.chat) (s.chat.outputs ??= {})[id] = file // its result, cut from the conversation later, points here
672
+ log('research', `saved ${page.url} → ${file}`)
673
+ // "start": the part from there on, as before (an older conversation's way of reading on)
674
+ if (Number(args.start) > 0) return `${head}${await webFetch(page.url, { start: args.start, signal })}\n\n(All of this page is saved in ${file}.)`
675
+ return `${head}${page.title ? `# ${page.title}\n` : ''}${page.url}\n\n${pageView(page.text, { lookFor: args.look_for, file, bodyLine })}`
645
676
  }
677
+ const MAX_PAGE = 10_000
646
678
 
647
679
  function memoryTool(s, args) {
648
680
  const m = s.memory
@@ -653,8 +685,16 @@ function memoryTool(s, args) {
653
685
  if (!args.content && !args.description) return 'error: write needs at least content or a description'
654
686
  if (!String(args.name ?? '').trim() && !String(args.description ?? '').trim()) return 'error: write needs a "name" (or a description to name it by). Nothing was saved.'
655
687
  if (String(args.name ?? '').trim() && fullSlug(args.name).length > 60) return 'error: the name is too long (60 characters at most, as a file name). Nothing was saved.'
688
+ const isNew = !m.read(args.name || args.description)
656
689
  const n = m.write(args)
657
- return `Saved [[${n}]]${m.read(n)?.scope === 'global' ? ' (global)' : ''}.`
690
+ // a new note that says much the same as one there already: said, so they're merged, not piled up
691
+ const words = new Set(keywords(`${n} ${args.description ?? ''}`))
692
+ const overlap = (x) => {
693
+ const theirs = new Set(keywords(`${x.name} ${x.description}`))
694
+ return [...theirs].filter((w) => words.has(w)).length / Math.max(1, Math.min(theirs.size, words.size))
695
+ }
696
+ const similar = isNew && words.size >= 3 ? m.list().filter((x) => x.name !== n && overlap(x) >= 0.6).slice(0, 3) : []
697
+ return `Saved [[${n}]]${m.read(n)?.scope === 'global' ? ' (global)' : ''}.${similar.length ? ` Similar notes exist: ${similar.map((x) => `[[${x.name}]] — ${x.description}`).join('; ')}. If one says the same thing, merge them: write the merged note under one name and delete the other.` : ''}`
658
698
  }
659
699
  case 'read': {
660
700
  if (!name.trim()) return 'error: read needs the note\'s "name" (search finds notes by words).'
@@ -704,16 +744,61 @@ async function mcpTool(s, args, signal) {
704
744
  s.ui.spinner(`starting ${server.name}`)
705
745
  const tools = await server.listTools(signal)
706
746
  if (tool === 'list') return tools.map((t) => `${t.name}: ${String(t.description ?? '').split(/(?<=\.)\s/)[0].slice(0, 160)}`).join('\n')
707
- const t = tools.find((x) => x.name === a.name)
708
- return t ? `${t.name}: ${t.description ?? ''}\nArguments (JSON schema): ${JSON.stringify(t.inputSchema ?? {})}` : `error: ${server.name} has no tool "${a.name}"; tool "list" shows its tools`
747
+ const t = tools.find((x) => x.name === (a.name ?? a.tool))
748
+ return t ? describeTool(t) : `error: ${server.name} has no tool "${a.name ?? a.tool}"; tool "list" shows its tools`
709
749
  }
710
750
  return callMcp(s, server, tool, a, signal)
711
751
  }
712
752
 
753
+ // What's wrong with a call's arguments for a tool's JSON schema (the common part of it: required,
754
+ // unknown names, types, enums), or [] when they fit. Unknown names get the closest real one.
755
+ export function argProblems(schema, a) {
756
+ const props = schema?.properties ?? {}
757
+ const out = []
758
+ if (!a || typeof a !== 'object' || Array.isArray(a)) return ['"arguments" must be an object']
759
+ for (const k of schema?.required ?? []) if (a[k] === undefined) out.push(`"${k}" is required`)
760
+ const near = (k) => {
761
+ const d = (x, y) => {
762
+ const m = Array.from({ length: x.length + 1 }, (_, i) => [i, ...Array(y.length).fill(0)])
763
+ for (let j = 1; j <= y.length; j++) m[0][j] = j
764
+ for (let i = 1; i <= x.length; i++) for (let j = 1; j <= y.length; j++) m[i][j] = Math.min(m[i - 1][j] + 1, m[i][j - 1] + 1, m[i - 1][j - 1] + (x[i - 1] === y[j - 1] ? 0 : 1))
765
+ return m[x.length][y.length]
766
+ }
767
+ const best = Object.keys(props).map((p) => [p, d(k.toLowerCase(), p.toLowerCase())]).sort((x, y) => x[1] - y[1])[0]
768
+ return best && best[1] <= Math.max(2, Math.floor(best[0].length / 3)) ? ` (did you mean "${best[0]}"?)` : ''
769
+ }
770
+ const typeOk = (t, v) => ({ string: typeof v === 'string', number: typeof v === 'number', integer: Number.isInteger(v), boolean: typeof v === 'boolean', array: Array.isArray(v), object: v !== null && typeof v === 'object' && !Array.isArray(v), null: v === null })[t] ?? true
771
+ for (const [k, v] of Object.entries(a)) {
772
+ const p = props[k]
773
+ if (!p) {
774
+ if (schema?.properties && schema.additionalProperties !== true) out.push(`"${k}" is not one of its arguments${near(k)}`)
775
+ continue
776
+ }
777
+ const types = [p.type ?? []].flat()
778
+ if (types.length && !types.some((t) => typeOk(t, v))) out.push(`"${k}" must be ${types.join(' or ')}, not ${Array.isArray(v) ? 'an array' : v === null ? 'null' : typeof v}`)
779
+ if (p.enum && !p.enum.includes(v)) out.push(`"${k}" must be one of ${p.enum.map((x) => JSON.stringify(x)).join(', ')}`)
780
+ }
781
+ return out
782
+ }
783
+
784
+ // One tool's description and arguments, for the model (describe, or a call that didn't fit).
785
+ const describeTool = (t) => `${t.name}: ${t.description ?? ''}\nArguments (JSON schema): ${JSON.stringify(t.inputSchema ?? {})}`
786
+
713
787
  // One MCP tool call. Asked about like a command, unless the server marks the tool read-only.
714
788
  async function callMcp(s, server, tool, a, signal) {
715
789
  if (!allowed(s, mcpName(server.name, tool))) return `error: the tool ${mcpName(server.name, tool)} is not allowed here`
716
- const def = (server.tools ?? s.mcpCatalog?.get(server.name)?.tools)?.find((t) => t.name === tool)
790
+ let def = (server.tools ?? s.mcpCatalog?.get(server.name)?.tools)?.find((t) => t.name === tool)
791
+ if (!def) {
792
+ const tools = await server.listTools(signal).catch(() => null)
793
+ def = tools?.find((t) => t.name === tool)
794
+ if (tools && !def) {
795
+ const close = tools.filter((t) => t.name.includes(tool) || tool.includes(t.name)).map((t) => t.name)
796
+ return `error: ${server.name} has no tool "${tool}".${close.length ? ` Did you mean ${close.join(' or ')}?` : ''} Its tools: ${tools.map((t) => t.name).join(', ')}`
797
+ }
798
+ }
799
+ // arguments that don't fit: the schema comes back with what's wrong, and nothing is sent
800
+ const problems = def?.inputSchema ? argProblems(def.inputSchema, a) : []
801
+ if (problems.length) return `error: ${server.name} · ${tool} wasn't called — ${problems.join('; ')}.\n${describeTool(def)}\nCall it again with arguments that fit.`
717
802
  // a tool its server marks read-only isn't asked about (reading isn't, in any mode; headless
718
803
  // declines what it would ask, so a browser's snapshot must not be); any other like a command
719
804
  if (!def?.annotations?.readOnlyHint) {
@@ -826,7 +911,7 @@ async function editFiles(s, args) {
826
911
  }
827
912
  }
828
913
  if (edits && typeof edits === 'object' && !Array.isArray(edits)) edits = [edits] // one edit, not in a list
829
- if (!Array.isArray(edits)) edits = [{ search: args.search, replace: args.replace }]
914
+ if (!Array.isArray(edits)) edits = [{ search: args.search, replace: args.replace, start_line: args.start_line, end_line: args.end_line }]
830
915
  const files = new Map() // path → { old, text }
831
916
  const textOf = (rel) => {
832
917
  if (!files.has(rel)) files.set(rel, { old: fs.readFileSync(resolveIn(root, rel), 'utf8') })
@@ -847,15 +932,34 @@ async function editFiles(s, args) {
847
932
  return hits.length === 1 ? hits[0] : null
848
933
  }
849
934
  for (const [i, e] of edits.entries()) {
850
- const { search: s0, replace: r0, path: p0 } = normalize(e ?? {})
935
+ const { search: s0, replace: r0, path: p0, start_line: a0, end_line: b0 } = normalize(e ?? {})
851
936
  const search = String(s0 ?? '')
852
937
  const given = p0 ?? args.path
853
938
  const label = edits.length > 1 ? `edit ${i + 1} of ${edits.length}: ` : ''
854
939
  // no "replace" at all isn't "replace with nothing": a model that left it out would delete code
855
940
  // (one did). Deleting is an explicit "replace": "".
856
- if (r0 === undefined || r0 === null) return `error: ${label}"replace" is missing: give the new text (or "replace": "" to delete the search text). Nothing was changed.`
941
+ if (r0 === undefined || r0 === null) return `error: ${label}"replace" is missing: give the new text (or "replace": "" to delete the lines). Nothing was changed.`
857
942
  if (typeof r0 !== 'string' && !(Array.isArray(r0) && r0.every((l) => typeof l === 'string'))) return `error: ${label}"replace" must be text, a string. Nothing was changed.`
858
943
  const replace = Array.isArray(r0) ? r0.join('\n') : r0
944
+
945
+ // Line-range edit: given start_line (and optionally end_line), replace exactly those lines —
946
+ // no text to reproduce, so a weak model that can't copy the file byte-for-byte can still edit it.
947
+ if (a0 !== undefined && a0 !== null && String(a0).trim() !== '') {
948
+ const rel = given && fs.existsSync(resolveIn(root, given)) ? path.relative(root, resolveIn(root, given)) : null
949
+ if (!rel) return `error: ${label}${given ? `${given} does not exist; use write_file to create it` : 'start_line needs a "path"'}. Nothing was changed.`
950
+ const lines = textOf(rel).split('\n')
951
+ const a = Math.trunc(Number(a0))
952
+ const b = b0 === undefined || b0 === null || String(b0).trim() === '' ? a : Math.trunc(Number(b0))
953
+ if (!Number.isFinite(a) || !Number.isFinite(b) || a < 1 || b < a || a > lines.length)
954
+ return `error: ${label}start_line ${a0}/end_line ${b0 ?? a0} is out of range; ${rel} has ${lines.length} lines (read_file to see them). Nothing was changed.`
955
+ lines.splice(a - 1, Math.min(b, lines.length) - a + 1, ...(replace === '' ? [] : replace.split('\n'))) // "" deletes the lines
956
+
957
+ files.get(rel).text = lines.join('\n')
958
+ s.editFails?.delete(rel) // it landed: clear the miss count for this file
959
+ continue
960
+ }
961
+
962
+ if (!search.trim()) return `error: ${label}give "search" (the exact text to find) or "start_line"/"end_line" (the line numbers to replace). Nothing was changed.`
859
963
  let rel = given && fs.existsSync(resolveIn(root, given)) ? path.relative(root, resolveIn(root, given)) : null
860
964
  let r = rel ? applyEdit(textOf(rel), search, replace) : null
861
965
  if (!r || r.error) {
@@ -865,18 +969,48 @@ async function editFiles(s, args) {
865
969
  else if (other && other !== rel) return `error: ${label}${rel ? `the search text isn't in ${given}` : `${given} does not exist`}, but the text is in ${other}: give that path if that's the file to change. Nothing was changed.`
866
970
  }
867
971
  if (!rel) return `error: ${label}${given ? `${given} does not exist; use write_file to create it` : 'no "path" given, and its search text is not in exactly one file'}. Nothing was changed.`
868
- if (r.error) return `error: ${label}${r.error}. Nothing was changed.`
972
+ if (r.error) {
973
+ // a second miss on the same file: show it, numbered, so the model can copy an exact block or
974
+ // rewrite it instead of guessing the search text over and over
975
+ const fails = (s.editFails ??= new Map())
976
+ const n = (fails.get(rel) ?? 0) + 1
977
+ fails.set(rel, n)
978
+ return `error: ${label}${r.error}. Nothing was changed.${n >= 2 ? fileToCopy(root, rel, search) : ''}`
979
+ }
869
980
  files.get(rel).text = r.text
870
981
  }
871
982
  const out = []
872
983
  for (const [rel, f] of files) {
873
984
  if (f.text === undefined) continue
874
985
  const res = await proposeWrite(s, rel, f.old, f.text)
986
+ if (res.status === 'applied') s.editFails?.delete(rel) // it worked: start the fail count over
875
987
  out.push(writeResult(rel, res) + (res.status === 'applied' ? `\nNow:\n${excerpt(res.text, res.ops)}` : ''))
876
988
  }
877
989
  return out.join('\n\n')
878
990
  }
879
991
 
992
+ // After an edit keeps missing: the file with line numbers (the whole thing if short, else the lines
993
+ // around where the search text most nearly fits) so the model can copy an exact block or write_file.
994
+ function fileToCopy(root, rel, search) {
995
+ let text
996
+ try {
997
+ text = fs.readFileSync(resolveIn(root, rel), 'utf8')
998
+ } catch {
999
+ return ''
1000
+ }
1001
+ const lines = text.split('\n')
1002
+ let a = 0
1003
+ let b = lines.length
1004
+ if (lines.length > 150) {
1005
+ const at = closest(lines, trimBlank(search.split('\n')))
1006
+ const c = at < 0 ? 0 : at
1007
+ a = Math.max(0, c - 8)
1008
+ b = Math.min(lines.length, c + trimBlank(search.split('\n')).length + 8)
1009
+ }
1010
+ const where = lines.length > 150 ? `${rel} around there` : `all of ${rel}`
1011
+ return `\nThis edit has missed twice. Stop guessing the SEARCH text. Here is ${where}, with line numbers. Easiest: call edit_file again with start_line and end_line (the line numbers below) and the new "replace" text — no search needed. Or copy an exact block (without the "N| " prefixes) for SEARCH, or use write_file for the whole file:\n${numberLines(lines.slice(a, b), a + 1)}`
1012
+ }
1013
+
880
1014
  // apply_patch (patch.js): every file's change is worked out first (nothing is written if one
881
1015
  // fails), then each is shown, asked about and written like an edit_file change.
882
1016
  async function applyPatch(s, text) {
@@ -953,7 +1087,7 @@ async function toolRun(name, args, s, signal, id) {
953
1087
 
954
1088
  // Argument names other tools use (Claude Code's file_path, old_string, new_string, …): models
955
1089
  // trained on them send them here too.
956
- const ALIASES = { file_path: 'path', filePath: 'path', file: 'path', old_string: 'search', old_str: 'search', oldText: 'search', new_string: 'replace', new_str: 'replace', newText: 'replace', cmd: 'command' }
1090
+ const ALIASES = { file_path: 'path', filePath: 'path', file: 'path', old_string: 'search', old_str: 'search', oldText: 'search', new_string: 'replace', new_str: 'replace', newText: 'replace', cmd: 'command', startLine: 'start_line', lineStart: 'start_line', start: 'start_line', endLine: 'end_line', lineEnd: 'end_line', end: 'end_line' }
957
1091
  function normalize(args) {
958
1092
  const out = { ...args }
959
1093
  for (const [from, to] of Object.entries(ALIASES)) if (out[to] === undefined && out[from] !== undefined) out[to] = out[from]
package/src/ui.js CHANGED
@@ -9,7 +9,7 @@ import { log } from './log.js'
9
9
  import { HOME } from './config.js'
10
10
  import { listen, transcribePcm, voiceProblem } from './voice.js'
11
11
 
12
- const color = (process.stdout.isTTY || Boolean(process.env.FORCE_COLOR)) && !process.env.NO_COLOR
12
+ export const color = (process.stdout.isTTY || Boolean(process.env.FORCE_COLOR)) && !process.env.NO_COLOR
13
13
  // 24-bit where the terminal says so, else the nearest of 256 (Terminal.app, xterm-256color), else 16.
14
14
  const depth = !color ? 0 : /truecolor|24bit/i.test(process.env.COLORTERM ?? '') ? 3 : /256/.test(process.env.TERM ?? '') || process.env.TERM_PROGRAM === 'Apple_Terminal' ? 2 : 1
15
15
  const to256 = ([r, g, b]) => {
@@ -110,11 +110,15 @@ setTheme()
110
110
  // built-in key off); anything else is sent as typed (a /command or a message). Ctrl+C stays Ctrl+C.
111
111
  const CONTROL_KEYS = { '\x1c': 'ctrl+\\', '\x1d': 'ctrl+]', '\x1e': 'ctrl+^', '\x1f': 'ctrl+_' } // no name from readline
112
112
  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()
113
- // While it works, Enter queues a message; Ctrl+] stops the answer and sends the first queued one,
114
- // Ctrl+\ all of them (as one message); Ctrl+_ switches what goes when an answer is done (all or
115
- // the next one). /voice records (no key unless keybindings.json gives it one); Ctrl+T, Ctrl+Q, Ctrl+N/P (or Ctrl+PgDn/PgUp), Alt+1…9: tabs; Shift+↑↓ and Alt+↑↓
116
- // scroll the conversation (as PgUp/PgDn and the mouse wheel do). keybindings.json can move them.
117
- export const DEFAULT_KEYS = { 'ctrl+]': 'send_first', 'ctrl+\\': 'send_all', 'ctrl+_': 'queue_mode', 'shift+up': 'scroll_line_up', 'shift+down': 'scroll_line_down', 'alt+up': 'scroll_up', 'alt+down': 'scroll_down', 'ctrl+t': 'new_tab', 'ctrl+q': 'close_tab', 'ctrl+n': 'next_tab', 'ctrl+p': 'prev_tab', 'ctrl+pagedown': 'next_tab', 'ctrl+pageup': 'prev_tab', ...Object.fromEntries([1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => [`alt+${n}`, `tab_${n}`])) }
113
+ // The built-in keys use Alt/Option, not Ctrl, so they don't clash with the shell and readline (Ctrl+N/P
114
+ // history, Ctrl+T transpose, Ctrl+Q flow-control, Ctrl+\ quit). On macOS Terminal.app, Alt keys need
115
+ // "Use Option as Meta key" on (Settings → Profiles → Keyboard); Ctrl+PgUp/PgDn cycle tabs without it.
116
+ // While it works, Enter queues a message; Alt+S stops the answer and sends the first queued one,
117
+ // Alt+A all of them (as one message); Alt+M switches what goes when an answer is done (all or the
118
+ // next one). /voice records (Space in an empty box, or a key in keybindings.json); Alt+T, Alt+W,
119
+ // Alt+N/P (or Ctrl+PgDn/PgUp), Alt+1…9: tabs; Shift+↑↓ and Alt+↑↓ scroll the conversation (as
120
+ // PgUp/PgDn and the mouse wheel do). keybindings.json can move any of them.
121
+ export const DEFAULT_KEYS = { '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+t': 'new_tab', 'alt+w': 'close_tab', 'alt+n': 'next_tab', 'alt+p': 'prev_tab', 'ctrl+pagedown': 'next_tab', 'ctrl+pageup': 'prev_tab', ...Object.fromEntries([1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => [`alt+${n}`, `tab_${n}`])) }
118
122
  export function loadKeys(file = path.join(HOME, 'keybindings.json')) {
119
123
  let raw = {}
120
124
  try {
@@ -885,7 +889,8 @@ export class UI {
885
889
  const hiddenBelow = input.rows.length - first - box.length
886
890
  const rule = c.ghost('─'.repeat(cols))
887
891
  const note = (n, arrow) => c.ghost('── ') + c.faint(`${arrow} ${n} more line${n > 1 ? 's' : ''}`) + c.ghost(` ${'─'.repeat(Math.max(0, cols - 18 - String(n).length))}`)
888
- const below = [hiddenBelow ? note(hiddenBelow, '↓') : rule, ...(this.status ? this.status().split('\n').map((l) => fit(' ' + l, cols)) : [])] // the status bar, one line or more
892
+ const statusText = this.status?.(cols) // the status bar (may be several lines, or '' when turned off)
893
+ const below = [hiddenBelow ? note(hiddenBelow, '↓') : rule, ...(statusText ? statusText.split('\n').map((l) => fit(' ' + l, cols)) : [])]
889
894
  const bottom = []
890
895
  if (this.timer && !this.asking) {
891
896
  // the spinner on its own line; the timer (and Esc) on the next, so neither line is crammed
@@ -898,7 +903,7 @@ export class UI {
898
903
  if (this.ahead.length) {
899
904
  const key = (k, d) => `${c.muted(k)} ${c.faint(d)}`
900
905
  const sep = c.ghost(' · ')
901
- bottom.push(fit(` ${c.bright(`queued ${this.ahead.length}`)}${sep}${c.faint(`when done: ${this.queueMode === 'one' ? 'one by one' : 'all together'}`)}${sep}${[key('Ctrl+]', 'send first now'), key('Ctrl+\\', 'send all now'), key('Ctrl+_', 'change when done')].join(sep)}`, cols))
906
+ bottom.push(fit(` ${c.bright(`queued ${this.ahead.length}`)}${sep}${c.faint(`when done: ${this.queueMode === 'one' ? 'one by one' : 'all together'}`)}${sep}${[key('Alt+S', 'send first now'), key('Alt+A', 'send all now'), key('Alt+M', 'change when done')].join(sep)}`, cols))
902
907
  for (const [i, l] of this.ahead.slice(0, 5).entries()) bottom.push(fit(` ${c.accent(`${i + 1}.`)} ${c.muted(l.replace(/\s+/g, ' '))}`, cols))
903
908
  if (this.ahead.length > 5) bottom.push(c.faint(` … ${this.ahead.length - 5} more`))
904
909
  }
@@ -953,6 +958,9 @@ export class UI {
953
958
  return this.refreshMenu()
954
959
  }
955
960
  if (bound) return this.#action(bound, write)
961
+ // Space in an empty box starts voice straight away — no /voice needed (only when it's set up,
962
+ // and not in a menu or a mid-task yes/no question, where Space types a space as usual)
963
+ if (key.name === 'space' && !this.rl.line && !this.menu.pick && !(this.asking && !this.histOn) && this.voiceReady()) return this.#action('voice', write)
956
964
  if (!this.asking && !(key.ctrl && key.name === 'c')) return this.#typeAhead(s, key, write)
957
965
  if (key.name === 'tab' && key.shift) return this.setPermission(PERMISSIONS[(PERMISSIONS.findIndex(([p]) => p === this.permission) + 1) % PERMISSIONS.length][0])
958
966
  // A new line instead of sending: Shift/Ctrl/Alt/Cmd+Enter (arrive as "\n" or ESC+Enter),
@@ -1059,6 +1067,15 @@ export class UI {
1059
1067
  }
1060
1068
 
1061
1069
  // Typing while HeartCode works: the text stays in the box; Enter queues it (shown above the
1070
+ // Esc to stop a running task asks for a second Esc within 2.5s first, so a stray tap doesn't kill
1071
+ // the work. (Flushing the queue with send_first/send_all still stops at once — that's deliberate.)
1072
+ escStop() {
1073
+ if (!this.onEscape) return
1074
+ if (Date.now() - (this.escArm ?? 0) < 2500) return (this.escArm = 0), this.onEscape()
1075
+ this.escArm = Date.now()
1076
+ this.notice('Press Esc again to stop', 2500)
1077
+ }
1078
+
1062
1079
  // input), sent when the answer is done, or at once with send_first / send_all. Esc stops the task.
1063
1080
  #typeAhead(s, key, write) {
1064
1081
  const rl = this.rl
@@ -1066,7 +1083,7 @@ export class UI {
1066
1083
  const it = m.on && m.items[m.sel] // a suggestion is highlighted (commands/@files show while working too)
1067
1084
  if (key.name === 'escape') {
1068
1085
  if (m.on) return (m.off = rl.line), this.#suggestWhileWorking() // first Esc just closes the suggestions
1069
- return this.onEscape?.()
1086
+ return this.escStop()
1070
1087
  }
1071
1088
  if (key.name === 'tab' && key.shift) return this.setPermission(PERMISSIONS[(PERMISSIONS.findIndex(([p]) => p === this.permission) + 1) % PERMISSIONS.length][0])
1072
1089
  if (key.name === 'pageup' || key.name === 'pagedown') return this.scrollBy(key.name === 'pageup' ? this.page() : -this.page())
@@ -1179,6 +1196,13 @@ export class UI {
1179
1196
  // the input box (where the cursor was), redone about every second with the quickest model; a
1180
1197
  // stretch you pause or finish is done again with the best one. Returns the words, or null (Esc,
1181
1198
  // or it failed: said in a notice); the box is as it was, for the caller to put them in.
1199
+ // Is voice set up and usable (a provider/whisper and its key)? Space-to-talk and the header hint
1200
+ // only show up when it is; otherwise Space types a space as normal.
1201
+ voiceReady() {
1202
+ const { voice = {}, providers = {} } = this.voiceConfig?.() ?? {}
1203
+ return !voiceProblem(voice, providers)
1204
+ }
1205
+
1182
1206
  // voiceConfig() → { voice, providers }: set by the app.
1183
1207
  async dictate() {
1184
1208
  if (this.recording) return null
@@ -1433,6 +1457,7 @@ export class UI {
1433
1457
  return Promise.resolve(l)
1434
1458
  }
1435
1459
  if (this.closed) return Promise.resolve(null)
1460
+ if (this.busySince && !history) this.onWaiting?.(prompt) // asked mid-task: you may be away (Telegram)
1436
1461
  this.menu.on = Boolean(suggest && (this.suggest || this.menu.pick) && this.full)
1437
1462
  this.histOn = history
1438
1463
  this.histAt = -1
@@ -1443,7 +1468,7 @@ export class UI {
1443
1468
  this.render() // cursor to the input row
1444
1469
  }
1445
1470
  rl.setPrompt(prompt)
1446
- rl.prompt()
1471
+ rl.prompt(true) // keep the cursor where it is: text typed while the model worked stays put, cursor and all (rl.prompt() would snap it to 0)
1447
1472
  // put in the box as it is: typed in (rl.write), each line break would be an Enter
1448
1473
  if (initial && rl.terminal && this.full) [rl.line, rl.cursor] = [initial, initial.length]
1449
1474
  else if (initial && rl.terminal) rl.write(initial.replace(/\n/g, ' '))