heartcode 0.1.25 → 0.1.27

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
@@ -8,7 +8,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'
11
+ import { applyEdit, closest, trimBlank } from './edit.js'
12
12
  import { readJson } from './config.js'
13
13
  import { c, diffLines, renderDiff } from './ui.js'
14
14
  import { webFetch, webSearch } from './web.js'
@@ -486,7 +486,7 @@ export const TOOL_DEFS = [
486
486
  { name: 'find_command', description: prompt('agent/tool-find_command'), parameters: obj({ names: { type: 'array', items: str } }, ['names']) },
487
487
  { 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
488
  // 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']) },
489
+ { 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
490
  { name: 'write_file', description: prompt('agent/tool-write_file'), parameters: obj({ path: str, content: str, append: { type: 'boolean' } }, ['path', 'content']) },
491
491
  { name: 'run_command', description: prompt('agent/tool-run_command'), parameters: obj({ command: str }, ['command']) },
492
492
  { 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']) },
@@ -826,7 +826,7 @@ async function editFiles(s, args) {
826
826
  }
827
827
  }
828
828
  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 }]
829
+ if (!Array.isArray(edits)) edits = [{ search: args.search, replace: args.replace, start_line: args.start_line, end_line: args.end_line }]
830
830
  const files = new Map() // path → { old, text }
831
831
  const textOf = (rel) => {
832
832
  if (!files.has(rel)) files.set(rel, { old: fs.readFileSync(resolveIn(root, rel), 'utf8') })
@@ -847,15 +847,34 @@ async function editFiles(s, args) {
847
847
  return hits.length === 1 ? hits[0] : null
848
848
  }
849
849
  for (const [i, e] of edits.entries()) {
850
- const { search: s0, replace: r0, path: p0 } = normalize(e ?? {})
850
+ const { search: s0, replace: r0, path: p0, start_line: a0, end_line: b0 } = normalize(e ?? {})
851
851
  const search = String(s0 ?? '')
852
852
  const given = p0 ?? args.path
853
853
  const label = edits.length > 1 ? `edit ${i + 1} of ${edits.length}: ` : ''
854
854
  // no "replace" at all isn't "replace with nothing": a model that left it out would delete code
855
855
  // (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.`
856
+ 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
857
  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
858
  const replace = Array.isArray(r0) ? r0.join('\n') : r0
859
+
860
+ // Line-range edit: given start_line (and optionally end_line), replace exactly those lines —
861
+ // no text to reproduce, so a weak model that can't copy the file byte-for-byte can still edit it.
862
+ if (a0 !== undefined && a0 !== null && String(a0).trim() !== '') {
863
+ const rel = given && fs.existsSync(resolveIn(root, given)) ? path.relative(root, resolveIn(root, given)) : null
864
+ if (!rel) return `error: ${label}${given ? `${given} does not exist; use write_file to create it` : 'start_line needs a "path"'}. Nothing was changed.`
865
+ const lines = textOf(rel).split('\n')
866
+ const a = Math.trunc(Number(a0))
867
+ const b = b0 === undefined || b0 === null || String(b0).trim() === '' ? a : Math.trunc(Number(b0))
868
+ if (!Number.isFinite(a) || !Number.isFinite(b) || a < 1 || b < a || a > lines.length)
869
+ 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.`
870
+ lines.splice(a - 1, Math.min(b, lines.length) - a + 1, ...(replace === '' ? [] : replace.split('\n'))) // "" deletes the lines
871
+
872
+ files.get(rel).text = lines.join('\n')
873
+ s.editFails?.delete(rel) // it landed: clear the miss count for this file
874
+ continue
875
+ }
876
+
877
+ 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
878
  let rel = given && fs.existsSync(resolveIn(root, given)) ? path.relative(root, resolveIn(root, given)) : null
860
879
  let r = rel ? applyEdit(textOf(rel), search, replace) : null
861
880
  if (!r || r.error) {
@@ -865,18 +884,48 @@ async function editFiles(s, args) {
865
884
  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
885
  }
867
886
  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.`
887
+ if (r.error) {
888
+ // a second miss on the same file: show it, numbered, so the model can copy an exact block or
889
+ // rewrite it instead of guessing the search text over and over
890
+ const fails = (s.editFails ??= new Map())
891
+ const n = (fails.get(rel) ?? 0) + 1
892
+ fails.set(rel, n)
893
+ return `error: ${label}${r.error}. Nothing was changed.${n >= 2 ? fileToCopy(root, rel, search) : ''}`
894
+ }
869
895
  files.get(rel).text = r.text
870
896
  }
871
897
  const out = []
872
898
  for (const [rel, f] of files) {
873
899
  if (f.text === undefined) continue
874
900
  const res = await proposeWrite(s, rel, f.old, f.text)
901
+ if (res.status === 'applied') s.editFails?.delete(rel) // it worked: start the fail count over
875
902
  out.push(writeResult(rel, res) + (res.status === 'applied' ? `\nNow:\n${excerpt(res.text, res.ops)}` : ''))
876
903
  }
877
904
  return out.join('\n\n')
878
905
  }
879
906
 
907
+ // After an edit keeps missing: the file with line numbers (the whole thing if short, else the lines
908
+ // around where the search text most nearly fits) so the model can copy an exact block or write_file.
909
+ function fileToCopy(root, rel, search) {
910
+ let text
911
+ try {
912
+ text = fs.readFileSync(resolveIn(root, rel), 'utf8')
913
+ } catch {
914
+ return ''
915
+ }
916
+ const lines = text.split('\n')
917
+ let a = 0
918
+ let b = lines.length
919
+ if (lines.length > 150) {
920
+ const at = closest(lines, trimBlank(search.split('\n')))
921
+ const c = at < 0 ? 0 : at
922
+ a = Math.max(0, c - 8)
923
+ b = Math.min(lines.length, c + trimBlank(search.split('\n')).length + 8)
924
+ }
925
+ const where = lines.length > 150 ? `${rel} around there` : `all of ${rel}`
926
+ 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)}`
927
+ }
928
+
880
929
  // apply_patch (patch.js): every file's change is worked out first (nothing is written if one
881
930
  // fails), then each is shown, asked about and written like an edit_file change.
882
931
  async function applyPatch(s, text) {
@@ -953,7 +1002,7 @@ async function toolRun(name, args, s, signal, id) {
953
1002
 
954
1003
  // Argument names other tools use (Claude Code's file_path, old_string, new_string, …): models
955
1004
  // 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' }
1005
+ 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
1006
  function normalize(args) {
958
1007
  const out = { ...args }
959
1008
  for (const [from, to] of Object.entries(ALIASES)) if (out[to] === undefined && out[from] !== undefined) out[to] = out[from]
package/src/ui.js CHANGED
@@ -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
@@ -1443,7 +1467,7 @@ export class UI {
1443
1467
  this.render() // cursor to the input row
1444
1468
  }
1445
1469
  rl.setPrompt(prompt)
1446
- rl.prompt()
1470
+ 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
1471
  // put in the box as it is: typed in (rl.write), each line break would be an Enter
1448
1472
  if (initial && rl.terminal && this.full) [rl.line, rl.cursor] = [initial, initial.length]
1449
1473
  else if (initial && rl.terminal) rl.write(initial.replace(/\n/g, ' '))