heartcode 0.1.40 → 0.1.42

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
@@ -218,12 +218,25 @@ function readImage(s, p) {
218
218
  export function searchFiles(root, query, sub = '', limit = 50) {
219
219
  const ci = query === query.toLowerCase()
220
220
  let re
221
+ let literal = false // not a valid regular expression: searched as the text it is
221
222
  try {
222
223
  re = new RegExp(query, ci ? 'i' : '')
223
224
  } catch {
224
225
  re = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), ci ? 'i' : '')
226
+ literal = true
227
+ }
228
+ // a pattern given as the path ("src/*.css", "**/*.ts"): the folder before it, and its files that fit
229
+ let only = null
230
+ const pattern = sub
231
+ if (/[*?]/.test(sub)) {
232
+ const parts = String(sub).split(/[\\/]/)
233
+ const at = parts.findIndex((p) => /[*?]/.test(p))
234
+ const glob = parts.slice(at).filter((p) => p !== '**').join('/') || '*'
235
+ only = new RegExp(`(^|/)${glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]')}$`)
236
+ sub = parts.slice(0, at).join('/')
225
237
  }
226
238
  const abs = sub ? resolveIn(root, sub, true) : ''
239
+ if (abs && !fs.existsSync(abs)) return `error: ${sub} doesn't exist, so nothing was searched (this is not "no matches"). Give a file or folder that exists, or leave path out to search the whole project.`
227
240
  const away = abs && abs !== root && !abs.startsWith(root + path.sep) && !isSavedOutput(abs) // a folder the user named outside the project
228
241
  let single = false // one file named: searched whatever lists leave out (a saved page, a .gitignored file)
229
242
  try {
@@ -232,8 +245,11 @@ export function searchFiles(root, query, sub = '', limit = 50) {
232
245
  const saved = isSavedOutput(abs) || single
233
246
  const prefix = sub && !saved && !away ? path.relative(root, abs) : ''
234
247
  const hits = []
248
+ let searched = 0
235
249
  for (const f of saved ? [abs] : away ? listFiles(abs).map((f) => path.join(abs, f)) : listFiles(root)) {
236
250
  if (prefix && f !== prefix && !f.startsWith(prefix + '/')) continue
251
+ if (only && !only.test(f)) continue
252
+ searched++
237
253
  let buf
238
254
  try {
239
255
  buf = fs.readFileSync(path.resolve(root, f))
@@ -248,7 +264,8 @@ export function searchFiles(root, query, sub = '', limit = 50) {
248
264
  if (hits.length >= limit) return hits.join('\n') + `\n… (stopped at ${limit} matches)`
249
265
  }
250
266
  }
251
- return hits.join('\n') || `no matches for ${query}`
267
+ if (hits.length) return hits.join('\n')
268
+ return searched ? `no matches for ${query} in ${searched} file${searched === 1 ? '' : 's'} searched${literal ? ' (as plain text: it isn\'t a valid regular expression)' : ''}` : `nothing was searched: no files${only ? ` fit ${pattern}` : ''} in ${sub || 'the project'} (this is not "no matches")`
252
269
  }
253
270
 
254
271
  // Runs a shell command in its own process group. The command is over when its shell exits, even
@@ -295,11 +312,12 @@ export function runCommand(root, cmd, { signal, timeout = 120_000, stdin, env, s
295
312
  child.stdout.destroy()
296
313
  child.stderr.destroy()
297
314
  const plain = (t) => t.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '')
298
- resolve({ code, output: plain(out) + note, ...(split && { stderr: plain(err) }) })
315
+ resolve({ code, output: (dropped ? '(the start of a very long output was left out: only its last 100,000 characters are here; the command itself was not affected)\n…' : '') + plain(out) + note, ...(split && { stderr: plain(err) }) })
299
316
  }
317
+ let dropped = false // a very long output's start, left out (said, so it isn't read as the command failing)
300
318
  const add = (d) => {
301
319
  out += d
302
- if (out.length > 200_000) out = out.slice(-100_000)
320
+ if (out.length > 200_000) (out = out.slice(-100_000)), (dropped = true)
303
321
  }
304
322
  const addErr = (d) => {
305
323
  err += d
@@ -332,6 +350,38 @@ export function suggestCommands(root) {
332
350
  return out.slice(0, 9)
333
351
  }
334
352
 
353
+ // What the model changed in files: this message's (or with all, the conversation's), each file from
354
+ // before its first change to now (the turns keep that first version for /rewind; /diff shows the same).
355
+ function changesTool(s, args) {
356
+ const turns = args.all ? (s.chat?.turns ?? []) : (s.chat?.turns ?? []).slice(-1)
357
+ const first = new Map()
358
+ for (const t of turns) for (const [rel, before] of Object.entries(t.files ?? {})) if (!first.has(rel)) first.set(rel, before)
359
+ const want = String(args.path ?? '').trim().replace(/^\.\//, '')
360
+ const out = []
361
+ for (const rel of [...first.keys()].filter((f) => !want || f === want || f.endsWith('/' + want)).sort()) {
362
+ const abs = path.join(s.root, rel)
363
+ const now = fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null
364
+ const was = first.get(rel)
365
+ if (was === now) continue
366
+ out.push(was === null ? `${rel} (new)\n${renderDiff(diffLines('', now), rel, false, 3, 400)}` : now === null ? `${rel} (deleted)` : renderDiff(diffLines(was, now), rel, false, 3, 400))
367
+ }
368
+ const where = args.all ? 'in this conversation' : 'for this message'
369
+ 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
+ }
371
+
372
+ // A "no" from the user, with what they typed instead. Their words go to the model as their own message,
373
+ // after the tool results (s.userSaid, which the agent sends): inside a result a model reads them as the
374
+ // tool talking, and tries again. Where there's no queue (guided mode) or no user (headless: the "no" is
375
+ // HeartCode's), they stay in the result.
376
+ export function declined(s, ok, what) {
377
+ const said = typeof ok === 'string' ? ok.trim() : ''
378
+ if (said && s.userSaid && !s.ui.noUser) {
379
+ s.userSaid.push(said)
380
+ return `${what} What they want instead is in their message that follows.`
381
+ }
382
+ return `${what}${said ? ` ${s.ui.noUser ? said : `User feedback: ${said}`}` : ''}`
383
+ }
384
+
335
385
  const PLACEHOLDER = /(\.\.\.|…)\s*(rest|existing|remaining|unchanged|other)|rest of (the )?(code|file)|existing code (here|unchanged)/i
336
386
 
337
387
  // Shows the diff, asks the user, writes (next = null: deletes the file). Shared by both agent modes.
@@ -343,7 +393,7 @@ export async function proposeWrite(s, rel, old, next) {
343
393
  if (next !== null && PLACEHOLDER.test(next) && !PLACEHOLDER.test(old)) s.ui.warn('the new content seems to contain a placeholder like "rest of code unchanged"')
344
394
  const ok = await s.ui.confirm(next === null ? `Delete ${rel}?` : old ? `Apply this change to ${rel}?` : `Create ${rel}?`)
345
395
  log('write', rel, ok === true ? 'approved' : `rejected ${typeof ok === 'string' ? ok : ''}`)
346
- if (ok !== true) return { status: 'rejected', feedback: typeof ok === 'string' ? ok : '' }
396
+ if (ok !== true) return { status: 'rejected', said: declined(s, ok, '') }
347
397
  const abs = resolveIn(s.root, rel)
348
398
  s.track?.(rel, fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null) // for /rewind
349
399
  if (next === null) fs.rmSync(abs, { force: true })
@@ -426,7 +476,7 @@ export async function runConfirmed(s, cmd, signal, background = false, wait) {
426
476
  return prompt('agent/command-too-wide', { root: s.root })
427
477
  }
428
478
  const ok = s.ui.permission === 'plan' ? true : await s.ui.confirm(`Run ${c.bold(cmd)}?`, 'command') // plan mode: only read-only ones get here
429
- if (ok !== true) return `The user declined to run this command.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
479
+ if (ok !== true) return declined(s, ok, 'The user declined to run this command.')
430
480
  const secs = Number(wait) > 0 ? Number(wait) : background ? 3 : 30
431
481
  const before = snapshot(s)
432
482
  s.ui.spinner(`running ${cmd}`)
@@ -531,7 +581,7 @@ function changesSince(s, before) {
531
581
  export function writeResult(rel, r) {
532
582
  if (r.status === 'applied') return `${r.deleted ? 'Deleted' : 'Changed'} ${rel} (${r.summary}).${r.note ? `\n${r.note}` : ''}`
533
583
  if (r.status === 'unchanged') return `No change: the new content of ${rel} is identical to the old content.`
534
- return `The user rejected the change to ${rel}.${r.feedback ? ' User feedback: ' + r.feedback : ''}`
584
+ return r.feedback ? r.feedback : `The user rejected the change to ${rel}.${r.said ?? ''}`
535
585
  }
536
586
 
537
587
  // --- native tool calling ---
@@ -543,6 +593,7 @@ const obj = (properties, required = []) => ({ type: 'object', properties, requir
543
593
  export const TOOL_DEFS = [
544
594
  { name: 'read_file', description: prompt('agent/tool-read_file'), parameters: obj({ path: str, start_line: int, end_line: int }, ['path']) },
545
595
  { name: 'search', description: prompt('agent/tool-search'), parameters: obj({ query: str, path: str }, ['query']) },
596
+ { name: 'changes', description: prompt('agent/tool-changes'), parameters: obj({ path: str, all: { type: 'boolean' } }) },
546
597
  { name: 'list_files', description: prompt('agent/tool-list_files'), parameters: obj({ path: str, filter: str }) },
547
598
  { name: 'find_command', description: prompt('agent/tool-find_command'), parameters: obj({ names: { type: 'array', items: str } }, ['names']) },
548
599
  { 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']) },
@@ -737,7 +788,7 @@ async function webTool(s, name, args, signal) {
737
788
  const what = name === 'web_search' ? String(args.query ?? '') : String(args.url ?? '')
738
789
  if (!what.trim()) return `error: ${name} needs ${name === 'web_search' ? '"query"' : '"url"'}`
739
790
  const ok = await s.ui.confirm(name === 'web_search' ? `Search the web for ${c.bold(what)}?` : `Fetch ${c.bold(what)}?`, 'read')
740
- if (ok !== true) return `The user declined this.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
791
+ if (ok !== true) return declined(s, ok, 'The user declined this.')
741
792
  // what this message's research is for: the page's look_for, else the last search, else the task
742
793
  const purpose = String(args.look_for ?? '').trim() || s.lastQuery || String(s.task ?? '').split('\n')[0].slice(0, 160)
743
794
  if (name === 'web_search') {
@@ -949,7 +1000,7 @@ async function callMcp(s, server, tool, a, signal) {
949
1000
  // declines what it would ask, so a browser's snapshot must not be); any other like a command
950
1001
  if (!def?.annotations?.readOnlyHint) {
951
1002
  const ok = await s.ui.confirm(`Use ${server.name} → ${tool}?`, 'command')
952
- if (ok !== true) return `The user declined this call.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
1003
+ if (ok !== true) return declined(s, ok, 'The user declined this call.')
953
1004
  }
954
1005
  const done = await s.mcpGate?.() // a helper may be using the MCP servers (a browser): its turn first
955
1006
  s.ui.spinner(`${server.name} · ${tool}`)
@@ -1296,6 +1347,8 @@ async function tool(name, args, s, signal, id) {
1296
1347
  }
1297
1348
  case 'search':
1298
1349
  return searchFiles(root, String(args.query ?? ''), args.path)
1350
+ case 'changes':
1351
+ return changesTool(s, args)
1299
1352
  case 'find_command': {
1300
1353
  const names = (Array.isArray(args.names) ? args.names : String(args.names ?? args.name ?? '').split(/[\s,]+/)).map(String).filter(Boolean)
1301
1354
  if (!names.length) return 'error: find_command needs "names": the commands to look for, like ["rg", "pnpm"]'
package/src/ui.js CHANGED
@@ -1828,6 +1828,7 @@ export class UI {
1828
1828
  const picked = Array.isArray(pick?.chosen) ? pick.chosen.map((x) => x.label).join(', ') : pick?.chosen?.label
1829
1829
  if (pick?.quiet) this.render()
1830
1830
  else if (pick) this.write(echo + (picked ?? c.dim('cancelled')) + '\n')
1831
+ else if (l !== null && history && this.isCommand(l.trim()) && !/^\s*\/skill:/.test(l)) this.notice(/^\S+/.exec(l.trim())[0], 3000, '›') // a command isn't part of the conversation: its name for a moment (not its arguments: maybe a key)
1831
1832
  else if (l !== null) this.write(echo + c.bright(l.replace(/\n/g, '\n' + ' '.repeat(width(echo.replace(/\x1b\[[0-9;]*m/g, ''))))) + '\n')
1832
1833
  else this.render()
1833
1834
  }
@@ -1930,6 +1931,23 @@ export class UI {
1930
1931
  })
1931
1932
  }
1932
1933
  }
1934
+ // A /command's output is taken back out of the conversation once it's done (nothing of a command
1935
+ // stays): one line shown as a notice for a moment, more in a box (Esc closes). Not when the command
1936
+ // put another conversation on the screen (/resume, /clear_chat…): that's what it's for.
1937
+ mark() {
1938
+ return { log: this.log, at: this.log.length - 1, base: this.log.at(-1), tail: this.tail, sgr: this.sgr }
1939
+ }
1940
+ unmark(m, title) {
1941
+ if (this.log !== m.log || this.log.length <= m.at || !this.log[m.at].startsWith(m.base)) return this.render()
1942
+ const text = [this.log[m.at].slice(m.base.length), ...this.log.slice(m.at + 1)].join('\n').replace(/^(\s*\n)+|\s+$/g, '')
1943
+ this.log.length = m.at + 1
1944
+ this.log[m.at] = m.base
1945
+ Object.assign(this, { tail: m.tail, sgr: m.sgr })
1946
+ const lines = text ? text.split('\n') : []
1947
+ if (lines.length === 1 || (lines.length && this.dialog)) this.notice(lines[0], 4000, '›')
1948
+ else if (lines.length) this.showText(title, text)
1949
+ else this.render()
1950
+ }
1933
1951
  // A blank line before a new block, unless there already is one.
1934
1952
  gap() {
1935
1953
  if (this.tail && this.tail !== '\n\n') this.write(this.tail.endsWith('\n') ? '\n' : '\n\n')
package/src/update.js CHANGED
@@ -1,4 +1,4 @@
1
- // A newer HeartCode: asked of npm at most once a day (in the background, never waited on), shown in
1
+ // A newer HeartCode: asked of npm at every start (in the background, never waited on), shown in
2
2
  // the status bar, installed with /update the way HeartCode was installed. A git checkout (npm link)
3
3
  // isn't npm-installed over: it's told to git pull.
4
4
  import fs from 'node:fs'
@@ -7,7 +7,6 @@ import { fileURLToPath } from 'node:url'
7
7
  import { HOME, VERSION, readJson, writeJson } from './config.js'
8
8
 
9
9
  const FILE = path.join(HOME, 'update-check.json')
10
- const DAY = 24 * 60 * 60 * 1000
11
10
  const PKG = fileURLToPath(new URL('..', import.meta.url))
12
11
 
13
12
  // "0.1.38" > "0.1.37": numbers compared part by part (a pre-release tag isn't offered)
@@ -17,18 +16,16 @@ export const newer = (a, b) => {
17
16
  return false
18
17
  }
19
18
 
20
- // { current, latest, newer }, or null when npm can't be reached. force: ask now, not from the day's answer.
21
- export async function checkUpdate({ force = false } = {}) {
22
- const was = readJson(FILE, {})
23
- let latest = was.latest
24
- if (force || !latest || Date.now() - (was.checked ?? 0) > DAY) {
25
- try {
26
- const r = await fetch('https://registry.npmjs.org/heartcode/latest', { signal: AbortSignal.timeout(8000) })
27
- latest = (await r.json()).version
28
- writeJson(FILE, { checked: Date.now(), latest })
29
- } catch {
30
- if (!latest) return null
31
- }
19
+ // { current, latest, newer }: npm asked now (its answer kept for the settings page); npm out of
20
+ // reach, its last answer; null when there's none.
21
+ export async function checkUpdate() {
22
+ let latest = readJson(FILE, {}).latest
23
+ try {
24
+ const r = await fetch('https://registry.npmjs.org/heartcode/latest', { signal: AbortSignal.timeout(8000) })
25
+ latest = (await r.json()).version
26
+ writeJson(FILE, { checked: Date.now(), latest })
27
+ } catch {
28
+ if (!latest) return null
32
29
  }
33
30
  return { current: VERSION, latest, newer: Boolean(latest) && newer(latest, VERSION) }
34
31
  }
package/prompts/probe.md DELETED
@@ -1,67 +0,0 @@
1
- # probe.md
2
-
3
- The one-time test of a new model's abilities. Changing these changes how models are judged.
4
- Each `## name` below is one prompt. `{{placeholders}}` are filled in by HeartCode;
5
- a `<!-- … -->` note under a heading explains the prompt and is never sent. To change one, copy
6
- its section into ~/.heart/prompts/probe.md (every project) or .heartcode/prompts/probe.md (one project).
7
-
8
- ## capital
9
-
10
- What is the capital of France? Answer in one word.
11
-
12
- ## count
13
-
14
- Count from 1 to 10, separated by spaces. Reply with only the numbers.
15
-
16
- ## edit
17
-
18
- <!-- The "edit skill" test. {{code}}: a small file. {{ask}}: the change to make. -->
19
- Here is a file:
20
- ```
21
- {{code}}```
22
-
23
- {{ask}}
24
- Reply with only a SEARCH/REPLACE block in exactly this format:
25
- <<<<<<< SEARCH
26
- (exact lines to find)
27
- =======
28
- (replacement lines)
29
- >>>>>>> REPLACE
30
-
31
- ## exact-number
32
-
33
- <!-- The "exact format" test. {{n}}: a number. -->
34
- Reply with only the number {{n}}. No other words.
35
-
36
- ## hello
37
-
38
- Say hello in one short sentence.
39
-
40
- ## image-color
41
-
42
- What color is this image? Reply with one word.
43
-
44
- ## menu
45
-
46
- <!-- The "menu picking" test. {{what}}: e.g. "a fruit". {{list}}: numbered options. -->
47
- Which of these is {{what}}?
48
- {{list}}
49
- Reply with only the number.
50
-
51
- ## system
52
-
53
- <!-- The system prompt of the "follows the system prompt" test; the model passes by replying BANANA. -->
54
- Whatever the user says, reply with only the single word BANANA.
55
-
56
- ## tool-description
57
-
58
- Look up the secret code for a name.
59
-
60
- ## tool-question
61
-
62
- <!-- The tool-call test. {{name}}: the name to look up. -->
63
- What is the secret code for "{{name}}"? Use the get_secret_code tool to find out.
64
-
65
- ## tool-result
66
-
67
- The secret code is ZX-4417.