heartcode 0.1.69 → 0.1.95

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/config.js CHANGED
@@ -31,28 +31,19 @@ export function speedOf(cfg) {
31
31
  // would call a model broken that a task still waits for)
32
32
  export const testWaitOf = (cfg) => (Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : Math.max(60, speedOf(cfg).replyStart))
33
33
 
34
- // The time limits that depend on one another, kept from contradicting: a test waits at least as long as
35
- // a model gets to start answering (Tests wait ≥ Give up), and a reply that has started may go quiet at
36
- // least that long too (Stalled ≥ Give up: a pause mid-reply has the same causes as a slow start, a
37
- // queue or thinking that isn't sent). The one just set (changed) stays; the other moves to fit. Returns
34
+ // The time limits that depend on one another, kept from contradicting: a reply that has started may go
35
+ // quiet at least as long as a model gets to start answering (Stalled ≥ Give up: a pause mid-reply has
36
+ // the same causes as a slow start, a queue or thinking that isn't sent). Tests wait is the tests' own. The one just set (changed) stays; the other moves to fit. Returns
38
37
  // what moved and why, for the page to say.
39
38
  export function fitTimes(cfg, changed) {
40
39
  const notes = []
41
40
  const { replyStart: start, replyIdle: idle } = speedOf(cfg)
42
- const test = Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : null
43
41
  const [sLo] = SPEED_LIMITS.replyStart
44
42
  if (changed === 'replyStart') {
45
- if (test !== null && test < start) (cfg.testTimeout = start), notes.push({ name: 'testTimeout', text: `Tests wait raised to ${start} s too: a test should wait at least as long as Give up, or it calls a model broken that real work would still wait for` })
46
43
  if (idle < start) (cfg.replyIdle = start), notes.push({ name: 'replyIdle', text: `Stalled raised to ${start} s too: a reply that has started may go quiet at least as long as a model gets to start` })
47
44
  } else if (changed === 'replyIdle') {
48
45
  if (start > idle) (cfg.replyStart = Math.max(sLo, idle)), notes.push({ name: 'replyStart', text: `Give up lowered to ${cfg.replyStart} s too: a model can't get longer to start than a started reply may go quiet` })
49
- } else if (changed === 'testTimeout' && test !== null && test < start) {
50
- if (test >= sLo) (cfg.replyStart = test), notes.push({ name: 'replyStart', text: `Give up lowered to ${test} s too: real work shouldn't wait longer for a model than its test does` })
51
- else {
52
- Object.assign(cfg, { testTimeout: sLo, replyStart: sLo })
53
- notes.push({ name: 'testTimeout', text: `Tests wait set to ${sLo} s: the shortest Give up can be, and a test must wait at least as long` }, { name: 'replyStart', text: `Give up lowered to ${sLo} s too: real work shouldn't wait longer for a model than its test does` })
54
- }
55
- }
46
+ } // Tests wait is the tests' own: a short one doesn't shorten how long real work waits for a model
56
47
  return notes
57
48
  }
58
49
 
@@ -66,7 +57,8 @@ export const HELPER_JOBS = {
66
57
  }
67
58
  // a helper's jobs as saved, in today's names (picks from before the four: search, research → quick, review → code)
68
59
  const WAS = { search: 'quick', research: 'quick', review: 'code' }
69
- export const jobsOf = (jobs) => (Array.isArray(jobs) ? [...new Set(jobs.map((j) => WAS[j] ?? j).filter((j) => HELPER_JOBS[j]))] : undefined)
60
+ // none left (only names it doesn't know): not a helper
61
+ export const jobsOf = (jobs) => (Array.isArray(jobs) ? ((l) => (l.length ? l : undefined))([...new Set(jobs.map((j) => WAS[j] ?? j).filter((j) => HELPER_JOBS[j]))]) : undefined)
70
62
  export const helpersOf = (map) => Object.fromEntries(Object.entries(map ?? {}).map(([k, jobs]) => [k, jobsOf(jobs)]).filter(([, jobs]) => jobs))
71
63
  export const SPEED_LIMITS = { replyStart: [5, 600], replyIdle: [10, 1800] }
72
64
 
@@ -209,17 +201,20 @@ function saved(cfg) {
209
201
  // Several HeartCodes (and the settings page in each) keep a copy of the settings. A save writes only
210
202
  // what this one changed since it last read or wrote the file, onto the file as it is now, and
211
203
  // takeIn brings in what the others changed: no copy undoes another's change with an old value.
212
- // file: config.json as last read or written here; mine: what this run's cfg stood for then (a -m
213
- // model for this run is no change of its own, so a save doesn't write it as #1).
204
+ // file: config.json as last read or written here; mine: what each cfg (a tab's own copy too) stood
205
+ // for then (a -m model for this run is no change of its own, so a save doesn't write it as #1).
214
206
  let file = null
215
- let mine = null
207
+ const mine = new WeakMap()
208
+ // A tab's copy of the settings: it starts from what the one it was copied from stood for, so its
209
+ // saves write only its own changes (not its old values over another tab's)
210
+ export const track = (copy, from) => (mine.set(copy, mine.get(from) ?? saved(copy)), copy)
216
211
  const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
217
212
  const keysOf = (...objs) => [...new Set(objs.flatMap((o) => Object.keys(o ?? {})))]
218
- const synced = (cfg, disk) => ((file = disk), (mine = saved(cfg)))
213
+ const synced = (cfg, disk) => ((file = disk), mine.set(cfg, saved(cfg)))
219
214
 
220
215
  export function saveConfig(cfg) {
221
216
  const out = saved(cfg)
222
- const was = mine ?? {}
217
+ const was = mine.get(cfg) ?? {}
223
218
  const disk = readJson(CONFIG_FILE, {})
224
219
  for (const k of keysOf(out, was)) {
225
220
  if (k === 'providers') {
@@ -250,6 +245,6 @@ export function takeIn(cfg) {
250
245
  }
251
246
  oneEach(cfg)
252
247
  file = disk
253
- mine = saved(cfg)
248
+ mine.set(cfg, saved(cfg))
254
249
  return keys
255
250
  }
package/src/edit.js CHANGED
@@ -15,6 +15,8 @@ export function trimBlank(lines) {
15
15
  // whitespace-insensitive line match (re-indenting the replacement).
16
16
  export function applyEdit(text, search, replace) {
17
17
  if (!search.trim()) return { error: 'the SEARCH text is empty' }
18
+ const crlf = text.includes('\r\n') // a Windows file: its new lines end the same way (\r\n), not mixed
19
+ if (crlf) replace = replace.replace(/\r?\n/g, '\r\n')
18
20
  const exact = text.split(search).length - 1
19
21
  if (exact === 1) return { text: text.replace(search, () => replace) }
20
22
  if (exact > 1) return { error: `the SEARCH text matches ${exact} places; include more surrounding lines so it matches only one` }
@@ -30,7 +32,8 @@ export function applyEdit(text, search, replace) {
30
32
  if (!hits.length) return { error: notFound(lines, s) }
31
33
 
32
34
  const i = hits[0]
33
- lines.splice(i, s.length, ...reindent(s, trimBlank(replace.split('\n')), lines.slice(i, i + s.length)))
35
+ const repl = reindent(s, trimBlank(replace.replace(/\r\n/g, '\n').split('\n')), lines.slice(i, i + s.length))
36
+ lines.splice(i, s.length, ...(crlf ? repl.map((l) => `${l.replace(/\r$/, '')}\r`) : repl))
34
37
  return { text: lines.join('\n') }
35
38
  }
36
39
 
package/src/guard.js ADDED
@@ -0,0 +1,88 @@
1
+ // HeartCode is never stopped by a command it runs. A model freeing a port (`lsof -ti :3000 | xargs
2
+ // kill -9` lists every process with a connection to it, HeartCode's own too), `pkill -f node`,
3
+ // `killall node`, `kill -9 -1`: each would kill HeartCode with it. The commands it runs (macOS, Linux)
4
+ // find kill, pkill and killall in a folder of HeartCode's first on their PATH (and `kill`, a shell
5
+ // builtin, as a function before the command): these leave out HeartCode, the programs it runs in
6
+ // (its terminal, its launcher) and "every process"; the rest are stopped as asked.
7
+ // ponytail: an absolute /bin/kill still gets through; Windows' taskkill isn't covered.
8
+ import fs from 'node:fs'
9
+ import path from 'node:path'
10
+ import { execFileSync } from 'node:child_process'
11
+ import { HOME } from './config.js'
12
+
13
+ const WIN = process.platform === 'win32'
14
+ const DIR = path.join(HOME, 'guard')
15
+ const VERSION = 3 // the scripts are written again when this changes
16
+
17
+ // HeartCode and the processes above it (its launcher, the shell, the terminal), not pid 1
18
+ function protectedPids() {
19
+ const pids = [process.pid]
20
+ try {
21
+ let p = process.ppid
22
+ for (let i = 0; i < 8 && p > 1; i++) {
23
+ pids.push(p)
24
+ p = Number(execFileSync('ps', ['-o', 'ppid=', '-p', String(p)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim())
25
+ }
26
+ } catch {}
27
+ return pids
28
+ }
29
+
30
+ // what both scripts share: the real kill, and the check of one target
31
+ const COMMON = `KILL=/bin/kill; [ -x "$KILL" ] || KILL=/usr/bin/kill
32
+ mine() { for p in $HEART_PIDS; do [ "$1" = "$p" ] || [ "$1" = "-$p" ] && return 0; done; return 1; }
33
+ `
34
+ const KILL = `#!/bin/sh
35
+ # HeartCode's kill: as kill, but never HeartCode itself (HEART_PIDS) nor every process (-1)
36
+ ${COMMON}sig=""
37
+ case "$1" in -l|-L) exec "$KILL" "$@";; -s|-n) sig="$1 $2"; shift 2;; -*) sig="$1"; shift;; esac
38
+ [ "$1" = "--" ] && shift
39
+ out=""; for a in "$@"; do
40
+ case "$a" in -1|0|-0) echo "kill $a: that's every process (HeartCode too): not sent" >&2; continue;; esac
41
+ if mine "$a"; then echo "kill $a: that's HeartCode itself (the program running this command): not stopped" >&2; continue; fi
42
+ out="$out $a"
43
+ done
44
+ [ -n "$out" ] || exit 1
45
+ exec "$KILL" $sig $out
46
+ `
47
+ // pkill and killall: the processes they'd match (pgrep), without HeartCode's, stopped with kill
48
+ const MATCH = (name, toPgrep) => `#!/bin/sh
49
+ # HeartCode's ${name}: as ${name}, but never HeartCode itself (HEART_PIDS)
50
+ ${COMMON}sig="-TERM"
51
+ case "$1" in -[0-9]*|-[A-Z]*) sig="$1"; shift;; -s|--signal) sig="-$2"; shift 2;; esac
52
+ pids=$(${toPgrep} | tr '\\n' ' ')
53
+ out=""; for p in $pids; do mine "$p" && { echo "${name}: left out HeartCode itself (pid $p)" >&2; continue; }; out="$out $p"; done
54
+ [ -n "$out" ] || exit 1
55
+ exec "$KILL" $sig $out
56
+ `
57
+ const SCRIPTS = {
58
+ kill: KILL,
59
+ pkill: MATCH('pkill', 'pgrep "$@"'),
60
+ killall: MATCH('killall', 'for n in "$@"; do case "$n" in -*) ;; *) pgrep -x "$n";; esac; done'),
61
+ }
62
+
63
+ let made = null
64
+ // The environment and the command, guarded: { env, command }. Nothing changes on Windows.
65
+ export function guarded(command, env = process.env) {
66
+ if (WIN) return { env, command }
67
+ try {
68
+ made ??= (() => {
69
+ const stamp = path.join(DIR, `.v${VERSION}`)
70
+ if (!fs.existsSync(stamp)) {
71
+ fs.mkdirSync(DIR, { recursive: true })
72
+ for (const [name, text] of Object.entries(SCRIPTS)) fs.writeFileSync(path.join(DIR, name), text, { mode: 0o755 })
73
+ fs.writeFileSync(path.join(DIR, 'env.sh'), `kill() { "${DIR}/kill" "$@"; }\n`)
74
+ // zsh reads $ZDOTDIR/.zshenv first, always: the function, then back to your own startup files
75
+ fs.writeFileSync(path.join(DIR, '.zshenv'), `kill() { "${DIR}/kill" "$@"; }\nunset ZDOTDIR\n[ -f "$HOME/.zshenv" ] && . "$HOME/.zshenv"\n`)
76
+ fs.writeFileSync(stamp, '')
77
+ }
78
+ return protectedPids().join(' ')
79
+ })()
80
+ } catch {
81
+ return { env, command }
82
+ }
83
+ const fn = `() { "${DIR}/kill" "$@"; }` // the shell's own kill in shells it starts too (bash: exported functions, both formats; BASH_ENV)
84
+ return {
85
+ env: { ...env, PATH: `${DIR}${path.delimiter}${env.PATH ?? ''}`, HEART_PIDS: made, 'BASH_FUNC_kill%%': fn, 'BASH_FUNC_kill()': fn, BASH_ENV: path.join(DIR, 'env.sh'), ENV: path.join(DIR, 'env.sh'), ZDOTDIR: DIR },
86
+ command: `kill() { "${DIR}/kill" "$@"; }\n${command}`, // the shell's own kill, too
87
+ }
88
+ }
package/src/guided.js CHANGED
@@ -40,6 +40,8 @@ export function nextActions(st) {
40
40
  let first
41
41
  if (!st.reads && st.hasFiles) first = ['read', 'search']
42
42
  else if (st.wantsChange && !st.edits) first = st.hasFiles ? ['edit', 'create', 'read'] : ['create']
43
+ else if (st.missing === 'unchecked') first = ['run', 'edit', 'finish'] // "finish" was just held: what's missing goes first
44
+ else if (st.missing === 'nothing') first = st.hasFiles ? ['edit', 'create', 'read'] : ['create']
43
45
  else first = ['finish', 'edit', 'run']
44
46
  return [...new Set([...first, ...actions().map(([n]) => n)])].filter((n) => (n !== 'delegate' || st.canDelegate) && (n !== 'ask' || !st.noAsk) && n !== st.avoid) // a step that just repeated with nothing new isn't offered again (a small model picks it over and over)
45
47
  }
@@ -173,7 +175,7 @@ class Guided {
173
175
  this.notes = []
174
176
  this.changed = new Set()
175
177
  this.files = listFiles(s.root)
176
- this.st = { reads: 0, edits: 0, editsSinceRun: 0, runs: 0, fixes: 0, lastRun: null, hasFiles: this.files.length > 0, canRun: suggestCommands(s.root).length > 0, editTries: 0, noAsk: Boolean(s.ui.noUser || s.isSub) } // ask: not headless, nor a helper (it reports to the main agent, which asks)
178
+ this.st = { reads: 0, edits: 0, editsSinceRun: 0, runs: 0, fixes: 0, lastRun: null, hasFiles: this.files.length > 0, editTries: 0, noAsk: Boolean(s.ui.noUser || s.isSub) } // ask: not headless, nor a helper (it reports to the main agent, which asks)
177
179
  this.calls = 0
178
180
  this.stops = 0
179
181
  }
@@ -296,13 +298,14 @@ class Guided {
296
298
  const gone = { provider: this.s.client.provider, model: was } // before moveOn changes them
297
299
  if (this.s.client.moveOn?.(`${was} said it was done, but ${missing === 'nothing' ? 'changed nothing' : "didn't run its change"}`)) {
298
300
  record(gone, 'handover') // its track record (record.js)
299
- this.ui.warn(`${was} said it was done, but ${missing === 'nothing' ? 'changed nothing' : "didn't run its change"}; handing over to ${this.s.client.model}`)
301
+ this.ui.handover(this.s.client.model, `${was} said it was done, but ${missing === 'nothing' ? 'changed nothing' : "didn't run its change"}`)
300
302
  this.held = 0
301
303
  }
302
304
  }
303
305
  log('guided', `finish held: ${missing}`)
304
306
  this.note('not-done', 'not done yet', prompt(`guided/not-done-${missing}`))
305
307
  this.st.held = true
308
+ this.st.missing = missing
306
309
  continue
307
310
  }
308
311
  this.unproven = missing
@@ -318,7 +321,7 @@ class Guided {
318
321
  sig = await this[action]()
319
322
  } catch (e) {
320
323
  if (e.name === 'AbortError' || e.name === 'TimeoutError' || e.status || /cannot reach/.test(e.message)) throw e
321
- this.ui.result(c.red(e.message))
324
+ this.ui.result(e.message, { ok: false })
322
325
  this.note(null, `${action} failed`, e.message)
323
326
  sig = `${action}:error`
324
327
  }
@@ -336,7 +339,7 @@ class Guided {
336
339
  const gone = { provider: this.s.client.provider, model: was } // before moveOn changes them
337
340
  const why = repeats >= 2 ? 'did the same thing three times in a row' : 'kept doing the same thing (three times)'
338
341
  record(gone, 'handover') // its track record (record.js)
339
- if (this.s.client.moveOn?.(`${was} ${why}`)) this.ui.warn(`${was} ${why}; handing over to ${this.s.client.model}`)
342
+ if (this.s.client.moveOn?.(`${was} ${why}`)) this.ui.handover(this.s.client.model, `${was} ${why}`)
340
343
  else this.ui.warn(`${was} ${why} — it carries on, told so; Esc stops it`)
341
344
  this.note(null, 'warning', prompt('guided/note-repeated'))
342
345
  repeats = 0
@@ -371,7 +374,7 @@ class Guided {
371
374
  const post = await runHooks(s, 'PostToolUse', { tool_name: name, tool_input: args, tool_response: out }, this.signal)
372
375
  if (post.block) out += `\n\n${prompt('agent/hook', { reason: post.block, after: true })}`
373
376
  }
374
- if (!pre || pre.block || notMine) this.ui.result(c.red(clip(out, 120)))
377
+ if (!pre || pre.block || notMine) this.ui.result(clip(out, 120), { ok: false })
375
378
  s.onEvent?.({ type: 'tool', id, name, output: out, model: `${s.client.provider}/${s.client.model}` })
376
379
  return out
377
380
  }
@@ -471,7 +474,7 @@ class Guided {
471
474
  if (next === null) return `edit:${f}`
472
475
  const lost = lostNames(old, next, this.task)
473
476
  if (lost.length) {
474
- this.ui.result(c.yellow(`that edit deleted ${lost.join(', ')}; retrying`))
477
+ this.ui.result(`that edit deleted ${lost.join(', ')}; retrying`, { refused: true })
475
478
  const again = await this.editRewrite(f, old, prompt('guided/keep-names', { names: lost.join(', '), them: lost.length > 1 ? 'them' : 'it' }))
476
479
  const still = again === null ? lost : lostNames(old, again, this.task)
477
480
  if (again !== null && !still.length) next = again
@@ -557,7 +560,7 @@ class Guided {
557
560
  }
558
561
 
559
562
  failed(f, why) {
560
- this.ui.result(c.red(`edit failed: ${why}`))
563
+ this.ui.result(`edit failed: ${why}`, { ok: false })
561
564
  this.note(null, `editing ${f} failed`, why)
562
565
  return null
563
566
  }
@@ -572,6 +575,7 @@ class Guided {
572
575
  this.note(null, `${old ? 'edit' : 'create'} ${f}`, out + (r?.diff ? '\n' + r.diff : ''))
573
576
  if (r?.status === 'applied') {
574
577
  this.st.edits++
578
+ if (this.st.missing === 'nothing') this.st.missing = null // what finish was held for is done (a change still to be run: still missing)
575
579
  this.changed.add(f)
576
580
  this.st.editsSinceRun++
577
581
  this.st.hasFiles = true
@@ -613,6 +617,7 @@ class Guided {
613
617
  this.s.ran?.push({ command: cmd, result: clip(out.split('\n').filter((l) => l.trim()).slice(0, 2).join(' · '), 160) }) // for the wrap-up, as native mode's
614
618
  const code = /^exit code (\S+)/.exec(out)?.[1]
615
619
  this.st.runs++
620
+ this.st.missing = null // what finish was held for is done
616
621
  this.st.editsSinceRun = 0
617
622
  this.st.lastRun = code === undefined ? null : code === '0' ? 0 : code
618
623
  this.note(null, `ran: ${cmd}`, out)
package/src/guides.js ADDED
@@ -0,0 +1,73 @@
1
+ // Guides for kinds of work (prompts/guides.md): web, api, mobile, desktop, cli, automation, long-task,
2
+ // game, data, library, extension, devops, database, upgrade. Easy to find two ways:
3
+ // - the guide tool, always there: its description lists each guide and when it's for;
4
+ // - HeartCode adds the right one itself, once per conversation, with the first tool result of a
5
+ // message whose words or project files show the kind of work (detect), so a model that doesn't
6
+ // think of the tool still gets it. At most two at a time: the message's kind first, then the project's.
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+ import { fileURLToPath } from 'node:url'
10
+ import { prompt } from './prompts.js'
11
+
12
+ // name → when it's for (the tool's list) and the words in a message that mean it
13
+ export const GUIDES = {
14
+ web: ['web sites and web apps, front ends, pages', /\b(web ?site|web ?app|web ?page|landing page|front-?end|react|vue|svelte|next\.?js|angular|tailwind)\b/i],
15
+ api: ['back ends, HTTP APIs, servers, webhooks', /\b(api|apis|endpoints?|back-?end|rest api|graphql|webhooks?|express|fastapi|flask|django)\b/i],
16
+ mobile: ['mobile apps: Flutter, React Native, Android, iOS', /\b(mobile|android|ios|iphone|flutter|react native|expo|swiftui|kotlin)\b/i],
17
+ desktop: ['desktop apps: Electron, Tauri, native GUIs', /\b(desktop|electron|tauri|gui|window app|menu ?bar app|tray app)\b/i],
18
+ cli: ['command-line tools and terminal programs', /\b(cli|command[- ]line|terminal (tool|app)|shell script)\b/i],
19
+ automation: ['scripts, bots, scraping, scheduled and unattended jobs', /\b(automat\w*|scrap(e|er|ing)|crawl\w*|bots?|cron|scheduled?|every (day|hour|morning|week|night))\b/i],
20
+ 'long-task': ['big or long work: many parts or files, rewrites, migrations, hours of work', /\b(whole (project|app|codebase)|entire (project|app|codebase)|from scratch|rewrite|overnight|all (the )?(files|pages|modules))\b/i],
21
+ game: ['games: browser (canvas) and engines', /\b(game|games|phaser|canvas|unity|godot|pygame|platformer|arcade)\b/i],
22
+ data: ['data: CSV/JSON/Excel, analysis, charts, notebooks, machine learning', /\b(csv|excel|xlsx|dataset|data ?frame|pandas|charts?|notebook|jupyter|data analysis|machine learning|train(ing)? a model)\b/i],
23
+ library: ['libraries and packages for others: npm, PyPI, crates, SDKs', /\b((write|make|build|create|publish) (a|an|my|the) (library|package|sdk)|npm publish|pypi|crates\.io)\b/i],
24
+ extension: ['browser and editor extensions (Chrome, Firefox, VS Code)', /\b((browser|chrome|firefox|edge|vs ?code|editor) (extension|add-?on|plugin))\b/i],
25
+ devops: ['Docker, CI, deploying, servers config', /\b(docker\w*|deploy\w*|ci\/cd|github actions|kubernetes|k8s|nginx|vps)\b/i],
26
+ database: ['databases: schemas, migrations, queries, ORMs', /\b(database|sql|sqlite|postgres\w*|mysql|mongo\w*|migrations?|prisma|orm)\b/i],
27
+ upgrade: ['upgrades and refactors: new versions, moving to another library, restructuring', /\b(upgrade|migrate to|refactor\w*|update (to|the) (version|latest)|port (it )?to)\b/i],
28
+ }
29
+ export const GUIDE_NAMES = Object.keys(GUIDES)
30
+
31
+ // The tool's list: "web: web sites and web apps…", one a line
32
+ export const guideList = () => GUIDE_NAMES.map((n) => `${n}: ${GUIDES[n][0]}`).join('\n')
33
+
34
+ // What a guide (or one of agent.md's guide-*) may use: the browser check's command, a memory tool, nobody to ask
35
+ const BIN = fileURLToPath(new URL('../bin/heartcode.js', import.meta.url))
36
+ export const guideVars = (s) => ({ memory: Boolean(s.memory) && !s.isSub, noUser: Boolean(s.ui?.noUser || s.isSub), page: `"${process.execPath}" "${BIN}" page` })
37
+ export const guideText = (s, name) => prompt(`guides/${name}`, guideVars(s))
38
+
39
+ // What kind of project the folder is, from its files: a guide name or null
40
+ function projectKind(root) {
41
+ const has = (f) => fs.existsSync(path.join(root, f))
42
+ let pkg = {}
43
+ try {
44
+ pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
45
+ } catch {}
46
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies }
47
+ const dep = (...names) => names.some((n) => n in deps)
48
+ let py = ''
49
+ for (const f of ['requirements.txt', 'pyproject.toml']) {
50
+ try {
51
+ py += fs.readFileSync(path.join(root, f), 'utf8')
52
+ } catch {}
53
+ }
54
+ if (has('pubspec.yaml') || dep('react-native', 'expo') || (has('android') && has('ios'))) return 'mobile'
55
+ if (has('src-tauri') || has('tauri.conf.json') || dep('electron')) return 'desktop'
56
+ if (pkg.engines?.vscode || (has('manifest.json') && /"manifest_version"/.test(fs.readFileSync(path.join(root, 'manifest.json'), 'utf8')))) return 'extension'
57
+ if (dep('phaser', 'pixi.js', 'three', 'kaboom') || has('project.godot')) return 'game'
58
+ if (dep('react', 'vue', 'svelte', 'next', 'nuxt', 'vite', 'astro', '@angular/core', 'solid-js') || has('index.html')) return 'web'
59
+ if (dep('express', 'fastify', 'koa', 'hono', '@nestjs/core') || /\b(flask|fastapi|django)\b/i.test(py)) return 'api'
60
+ if (/\b(pandas|numpy|scikit-learn|torch|jupyter)\b/i.test(py) || fs.readdirSync(root).some((f) => f.endsWith('.ipynb'))) return 'data'
61
+ if (pkg.bin) return 'cli'
62
+ return null
63
+ }
64
+
65
+ // The guides for a message in this folder (at most two): the kinds its words name, else the project's
66
+ export function detect(root, task) {
67
+ const said = GUIDE_NAMES.filter((n) => GUIDES[n][1].test(String(task ?? '')))
68
+ let kind = null
69
+ try {
70
+ kind = projectKind(root)
71
+ } catch {}
72
+ return [...new Set([...said, ...(kind ? [kind] : [])])].slice(0, 2)
73
+ }
package/src/headless.js CHANGED
@@ -38,7 +38,7 @@ export const PERMISSION_MODES = { all: 'all', commands: 'commands', ask: 'ask',
38
38
  // by stream-json: a system message each) as data.
39
39
  export class HeadlessUI {
40
40
  constructor({ permission = 'all', verbose = false } = {}) {
41
- Object.assign(this, { permission, verbose, log: [], showThinking: true, full: false, noUser: true, event: null })
41
+ Object.assign(this, { permission, verbose, log: [], full: false, noUser: true, event: null })
42
42
  // helpers at work (agent.js: label → { id, model, what }): each change sent as a "helper" event
43
43
  const ui = this
44
44
  this.helpers = new (class extends Map {
@@ -56,6 +56,9 @@ export class HeadlessUI {
56
56
  #err(text) {
57
57
  if (this.verbose) process.stderr.write(`${text}\n`)
58
58
  }
59
+ handover(to, why) {
60
+ this.warn(`${to} takes over: ${why}`)
61
+ }
59
62
  warn(text) {
60
63
  log('warn', text)
61
64
  this.#err(`heartcode: ${text}`)
@@ -83,7 +86,7 @@ export class HeadlessUI {
83
86
  this.said = null
84
87
  }
85
88
  async confirm(question, kind = 'edit') {
86
- if (this.permission === 'all' || (this.permission === 'commands' && kind === 'edit') || (this.permission === 'plan' && kind === 'read')) return true // plan: only reading
89
+ if (kind !== 'setup' && (this.permission === 'all' || (this.permission === 'commands' && kind === 'edit') || (this.permission === 'plan' && kind === 'read'))) return true // plan: only reading; setup (HeartCode's or git's settings here): never without someone to ask
87
90
  log('headless', `declined: ${question}`)
88
91
  return `Not allowed: HeartCode runs headless with permission mode "${this.permission}", so this can't be approved. Don't retry it; say in your reply what you would have done.`
89
92
  }
package/src/hooks.js CHANGED
@@ -10,6 +10,7 @@
10
10
  // tool_input, tool_response, prompt, stop_hook_active), runs in the project folder, and can also
11
11
  // answer with JSON on stdout: {"decision": "block", "reason": "…"} (or "continue": false).
12
12
  // Matchers are regexes, tested against HeartCode's tool names and Claude Code's (Edit, Bash, …).
13
+ import { trusted } from './trust.js'
13
14
  import fs from 'node:fs'
14
15
  import path from 'node:path'
15
16
  import { HOME, readConfig } from './config.js'
@@ -21,7 +22,7 @@ export const EVENTS = ['UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'Stop']
21
22
  // HeartCode's tool names → Claude Code's, for matchers and tool_input written for Claude Code.
22
23
  export const CLAUDE_NAMES = { read_file: 'Read', edit_file: 'Edit', write_file: 'Write', run_command: 'Bash', search: 'Grep', list_files: 'Glob', web_fetch: 'WebFetch', web_search: 'WebSearch', todo: 'TodoWrite', agent: 'Task' }
23
24
 
24
- export const hookFiles = (root) => [path.join(HOME, 'hooks.json'), path.join(root, '.heartcode', 'hooks.json')]
25
+ export const hookFiles = (root) => [path.join(HOME, 'hooks.json'), ...(trusted(root) ? [path.join(root, '.heartcode', 'hooks.json')] : [])] // the folder's own: once you said yes to it (trust.js)
25
26
 
26
27
  // { event: [{ matcher, command, timeout, file }] }
27
28
  export function loadHooks(root) {
@@ -70,7 +71,7 @@ export async function runHooks(s, event, data = {}, signal) {
70
71
  const reason = (json?.reason ?? json?.stopReason ?? stderr.trim()) || output.trim() || `blocked by the hook ${h.command}`
71
72
  if (code === 2 || json?.decision === 'block' || json?.continue === false) {
72
73
  s.ui.step('hook', `${event}: ${clip(h.command, 50)}`)
73
- s.ui.result(`blocked: ${clip(reason.split('\n')[0], 100)}`)
74
+ s.ui.result(`blocked: ${clip(reason.split('\n')[0], 100)}`, { refused: true })
74
75
  return { block: clip(reason, 4000), context: context.join('\n') }
75
76
  }
76
77
  if (code !== 0) s.ui.warn(`hook ${h.command} (${event}) failed: exit ${code}${stderr.trim() ? `: ${clip(stderr.trim().split('\n')[0], 120)}` : ''}`)
package/src/http.js CHANGED
@@ -21,7 +21,7 @@ const ACCEPT = Object.keys(DECODE).filter((k) => k !== 'x-gzip').join(', ')
21
21
  const NO_BODY = new Set([101, 103, 204, 205, 304])
22
22
 
23
23
  export async function fetch(input, init = {}) {
24
- const { signal, redirect = 'follow' } = init
24
+ const { signal, redirect = 'follow', guard } = init // guard(url): checks each place it goes (a redirect too); throws to refuse
25
25
  // the body and headers as fetch would send them (a string, JSON, form data, URLSearchParams, a Blob…)
26
26
  const asked = new Request(input, { method: init.method, headers: init.headers, body: init.body, duplex: 'half' })
27
27
  let url = new URL(asked.url)
@@ -31,6 +31,7 @@ export async function fetch(input, init = {}) {
31
31
  let body = asked.body ? Buffer.from(await asked.arrayBuffer()) : null
32
32
  for (let hops = 0; ; hops++) {
33
33
  signal?.throwIfAborted()
34
+ if (guard) await guard(url)
34
35
  const res = await send(url, method, body ? { ...headers, 'content-length': String(body.length) } : headers, body, signal)
35
36
  const to = res.headers.location
36
37
  if (redirect === 'manual' || ![301, 302, 303, 307, 308].includes(res.statusCode) || !to) return respond(res, url, hops > 0, signal)
@@ -44,7 +45,8 @@ export async function fetch(input, init = {}) {
44
45
  body = null
45
46
  for (const h of ['content-type', 'content-length']) delete headers[h]
46
47
  }
47
- if (next.origin !== url.origin) delete headers.authorization // a key isn't handed to another site
48
+ // another site: only the plain headers go with it (no key, no token, no custom header)
49
+ if (next.origin !== url.origin) for (const h of Object.keys(headers)) if (!['accept', 'accept-encoding', 'accept-language', 'user-agent', 'content-type'].includes(h.toLowerCase())) delete headers[h]
48
50
  url = next
49
51
  }
50
52
  }
package/src/importer.js CHANGED
@@ -247,6 +247,17 @@ export function findImports(root, home = os.homedir()) {
247
247
  // one-file skill). Clones (git) or downloads a tarball, finds every SKILL.md, and copies each skill
248
248
  // folder into the skills dir (global by default). Returns a short summary; nothing existing is
249
249
  // overwritten. scope: "global" (~/.heart/skills) or "project" (.heartcode/skills).
250
+ // a path whose real place (links followed) is inside dir
251
+ const insideOf = (dir, p) => {
252
+ try {
253
+ const r = fs.realpathSync.native(p)
254
+ const d = fs.realpathSync.native(dir)
255
+ return r === d || r.startsWith(d + path.sep)
256
+ } catch {
257
+ return false
258
+ }
259
+ }
260
+
250
261
  export async function installSkill(root, source, scope = 'global', { signal } = {}) {
251
262
  source = String(source ?? '').trim()
252
263
  if (!source) throw new Error('give a GitHub repo (user/repo or its URL) or a link to a SKILL.md')
@@ -279,7 +290,7 @@ export async function installSkill(root, source, scope = 'global', { signal } =
279
290
  done.push(`${name} (already installed)`)
280
291
  continue
281
292
  }
282
- fs.cpSync(dir, path.join(dest, name), { recursive: true, filter: (s) => !/[/\\]\.git([/\\]|$)/.test(s) })
293
+ fs.cpSync(dir, path.join(dest, name), { recursive: true, dereference: true, filter: (s) => !/[/\\]\.git([/\\]|$)/.test(s) && !(fs.lstatSync(s).isSymbolicLink() && !insideOf(dir, s)) }) // a link out of the skill: not copied (nor what it points to)
283
294
  done.push(name)
284
295
  }
285
296
  return `installed ${done.filter((d) => !d.includes('already')).length} of ${found.length} skill${found.length === 1 ? '' : 's'}: ${done.join(', ')}`
package/src/mcp.js CHANGED
@@ -9,6 +9,7 @@
9
9
  // list it gave the last time it ran (kept in ~/.heart/mcp-tools.json, with its instructions): so a
10
10
  // server starts the first time the model uses it, or once to say its tools; it stops when
11
11
  // HeartCode exits.
12
+ import { trusted } from './trust.js'
12
13
  import crypto from 'node:crypto'
13
14
  import fs from 'node:fs'
14
15
  import os from 'node:os'
@@ -56,7 +57,7 @@ export function serverName(given, taken = []) {
56
57
  // (no built-in or configured servers), like Claude Code's --strict-mcp-config.
57
58
  export function loadServers(root, { extra = [], strict = false, includeDisabled = false } = {}) {
58
59
  const merged = strict ? {} : structuredClone(DEFAULT_SERVERS) // yours (below) win on a name
59
- const own = strict ? [] : [path.join(HOME, 'mcp.json'), root && path.join(root, '.heartcode', 'mcp.json')].filter(Boolean).map((f) => readConfig(f, {}))
60
+ const own = strict ? [] : [path.join(HOME, 'mcp.json'), root && trusted(root) && path.join(root, '.heartcode', 'mcp.json')].filter(Boolean).map((f) => readConfig(f, {})) // the folder's own: once you said yes to it (trust.js)
60
61
  const given = extra.map((c) => {
61
62
  const data = /^\s*\{/.test(c) ? JSON.parse(c) : readJson(path.resolve(c), null)
62
63
  if (!data) throw new Error(`can't read the MCP config ${c}`)
@@ -167,6 +168,7 @@ class Server {
167
168
  }
168
169
  })
169
170
  child.stderr.on('data', (d) => log('mcp', `${this.name} stderr: ${String(d).trim()}`))
171
+ child.stdin.on('error', (e) => log('mcp', `${this.name} stdin: ${e.message}`)) // it quit while being written to (EPIPE): its exit says so, not a crash
170
172
  const gone = new Promise((_, reject) => {
171
173
  child.on('error', (e) => reject(new Error(`${this.name} could not start: ${e.message}`)))
172
174
  child.on('exit', (code) => {
@@ -257,7 +259,15 @@ class Server {
257
259
  }
258
260
 
259
261
  #send(msg) {
260
- if (!this.url) return this.child.stdin.write(JSON.stringify(msg) + '\n')
262
+ if (!this.url) {
263
+ if (!this.child?.stdin.writable) {
264
+ log('mcp', `${this.name}: not running, ${msg.method ?? 'reply'} not sent`) // stopped, or gone
265
+ const p = this.pending.get(msg.id)
266
+ if (p) this.pending.delete(msg.id), p.reject(new Error(`${this.name} isn't running`)) // not left waiting
267
+ return
268
+ }
269
+ return this.child.stdin.write(JSON.stringify(msg) + '\n')
270
+ }
261
271
  this.#post(msg).catch((e) => {
262
272
  const p = this.pending.get(msg.id)
263
273
  if (!p) return log('mcp', `${this.name}: ${e.message}`)
package/src/probe.js CHANGED
@@ -4,6 +4,7 @@ import path from 'node:path'
4
4
  import { HOME, readJson } from './config.js'
5
5
  import { contextWindow, contextSource, ASSUMED_REMOTE, LIMIT_MS } from './context.js'
6
6
  import { c } from './ui.js'
7
+ import { cliOf } from './clis.js'
7
8
 
8
9
  // One cached profile per server + model. The URL path counts: proxies serve several providers
9
10
  // from one host (https://proxy.dev/groq, https://proxy.dev/openrouter).
@@ -12,6 +13,7 @@ export const profilePath = (client) => {
12
13
  const where = u.host + u.pathname.replace(/\/v1$/, '')
13
14
  return path.join(HOME, 'models', `${where}_${client.model}`.replace(/[^\w.-]+/g, '_') + '.json')
14
15
  }
16
+ export const CLI_CONTEXT = 10_000_000 // a CLI's: never compacted by HeartCode
15
17
  // Bump when a profile's shape changes, so older saved ones are made again once.
16
18
  const PROBE_VERSION = 2
17
19
  // Kept in memory by file and its time: a page listing thousands of models reads only the ones that
@@ -33,6 +35,8 @@ export const loadProfile = (client) => {
33
35
  // assumptions (source 'assumed': tool calls, streaming, a 128k window) until you say on the settings
34
36
  // page what it can do (set: { context, tools, thinking, images, stream }, source 'you').
35
37
  export function profileFrom(client, info) {
38
+ // a coding CLI's model (clis.js): it works with its own tools and keeps its own context; nothing to look up
39
+ if (cliOf(client.baseUrl)) return { version: PROBE_VERSION, model: client.model, baseUrl: client.baseUrl, source: 'cli', at: new Date().toISOString(), set: { tools: true, stream: true, images: false, thinking: false, context: CLI_CONTEXT } }
36
40
  return { version: PROBE_VERSION, model: client.model, baseUrl: client.baseUrl, source: info ? 'models.dev' : 'assumed', at: new Date().toISOString(), usage: true, context: ASSUMED_REMOTE, contextGuessed: true, ...(info && { known: info }) }
37
41
  }
38
42
 
@@ -59,7 +63,7 @@ export function strategy(p, cfg = {}) {
59
63
  export function describe(p, s) {
60
64
  const yn = (v) => (v ? c.green('yes') : c.red('no'))
61
65
  const context = ['context', `${s.context}${c.dim(` (${p.set?.context ? 'set on /settings' : contextSource(p)}; change it on /settings)`)}`]
62
- const from = { 'models.dev': 'models.dev', you: '/settings (set by hand)', assumed: "nothing: it isn't in models.dev. Set what it can do on /settings" }[p.source] ?? 'an earlier test'
66
+ const from = { cli: 'its CLI (it keeps its own context)', 'models.dev': 'models.dev', you: '/settings (set by hand)', assumed: "nothing: it isn't in models.dev. Set what it can do on /settings" }[p.source] ?? 'an earlier test'
63
67
  const mine = (k) => (p.set?.[k] !== undefined ? c.dim(' (set by hand)') : '')
64
68
  return [['from', from], context, ['tool calls', yn(s.actions === 'tools') + mine('tools')], ['thinking', yn(s.thinking) + mine('thinking')], ['images', yn(s.vision) + (Date.now() - (p.quirks?.noImages ?? -Infinity) < LIMIT_MS ? c.dim(' (its provider refused an image today)') : mine('images'))], ['streaming', yn(s.stream) + mine('stream')]]
65
69
  .map(([k, v]) => ` ${c.dim(k.padEnd(15))} ${v}`)
package/src/prompts.js CHANGED
@@ -7,6 +7,7 @@
7
7
  // {{name}} filled in from `vars`; a missing one is an error
8
8
  // {{#if name}} … {{else}} … {{/if}} optional parts (else is optional)
9
9
  // <!-- … --> a note right under the heading; never sent
10
+ import { trusted } from './trust.js'
10
11
  import fs from 'node:fs'
11
12
  import path from 'node:path'
12
13
  import { fileURLToPath } from 'node:url'
@@ -46,7 +47,7 @@ export function sections(text) {
46
47
  function load(file) {
47
48
  if (!cache.has(file)) {
48
49
  const merged = new Map()
49
- for (const dir of [BUILTIN, path.join(HOME, 'prompts'), project && path.join(project, '.heartcode', 'prompts')]) {
50
+ for (const dir of [BUILTIN, path.join(HOME, 'prompts'), project && trusted(project) && path.join(project, '.heartcode', 'prompts')]) { // the folder's own: once you said yes to it (trust.js)
50
51
  if (!dir) continue
51
52
  try {
52
53
  for (const [k, v] of sections(fs.readFileSync(path.join(dir, `${file}.md`), 'utf8'))) merged.set(k, v)
package/src/rankings.js CHANGED
@@ -67,7 +67,7 @@ export async function rankings({ signal, onWait, now = false } = {}) {
67
67
  // A name as words: "models/gemini-3.6-flash" and "Gemini 3.6 Flash (High)" are both "gemini 3 6 flash"
68
68
  const DROP = new Set(['latest', 'preview', 'free', 'it', 'instruct', 'exp', 'chat'])
69
69
  const WORDS = new Map() // name → its words: thousands of models are matched against hundreds of entries, each parsed once
70
- export const words = (name) => {
70
+ const words = (name) => {
71
71
  const k = String(name)
72
72
  if (!WORDS.has(k)) WORDS.set(k, toWords(k))
73
73
  return WORDS.get(k)
@@ -85,20 +85,30 @@ const toWords = (name) =>
85
85
  // Where a model stands in a list, 0 (best) to 1 (last); null when it isn't in it. Its entry: the
86
86
  // same words, or those followed only by its size ("nemotron 3 super" = "Nemotron 3 Super 120B A12B"),
87
87
  // maybe after the maker's name; of several (High, Low…), the best.
88
- export function place(model, list) {
88
+ function place(model, list) {
89
89
  const mine = words(model)
90
90
  if (!mine.length || !list?.length) return null
91
- const size = /^(\d+|[abmkt])$/
91
+ // only a size after it ("120 b", "a 12 b"): a number with its unit, never a bare one ("gpt 5" isn't "GPT-5.1")
92
+ const sizes = (rest) => rest.every((w, i) => /^[abmkt]$/.test(w) || (/^\d+$/.test(w) && /^[bmkt]$/.test(rest[i + 1] ?? '')))
92
93
  const at = list.filter((e) => {
93
94
  const theirs = words(e.name)
94
95
  // from their first word, or their second (a maker's name first: "NVIDIA-Nemotron-3-Super-120B-A12B")
95
- return [0, 1].some((from) => theirs.length >= from + mine.length && mine.every((w, i) => theirs[from + i] === w) && theirs.slice(from + mine.length).every((w) => size.test(w)))
96
+ return [0, 1].some((from) => theirs.length >= from + mine.length && mine.every((w, i) => theirs[from + i] === w) && sizes(theirs.slice(from + mine.length)))
96
97
  })
97
98
  return at.length ? Math.min(...at.map((e) => e.rank)) / list.length : null
98
99
  }
99
100
 
100
101
  // A model's place in one list ('text:coding'…), for showing: { rank, of, as, score, votes } (as: its name there); null when not in it
102
+ // looked up once per rankings loaded (the settings page asks for every model, in every list, often)
103
+ const seen = new WeakMap()
101
104
  export function rankIn(model, key, data) {
105
+ if (!data) return null
106
+ const memo = seen.get(data) ?? seen.set(data, new Map()).get(data)
107
+ const k = `${key}\n${model}`
108
+ if (!memo.has(k)) memo.set(k, lookUpRank(model, key, data))
109
+ return memo.get(k)
110
+ }
111
+ function lookUpRank(model, key, data) {
102
112
  const list = data?.lists[key]
103
113
  const at = list?.filter((e) => place(model, [e]) != null)
104
114
  if (!at?.length) return null
package/src/record.js CHANGED
@@ -24,6 +24,14 @@ function all() {
24
24
  return cache.all
25
25
  }
26
26
 
27
+ // A provider renamed: its models' records go with it
28
+ export function renameRecords(from, to) {
29
+ const now = readJson(FILE, {})
30
+ let moved = 0
31
+ for (const k of Object.keys(now)) if (k.startsWith(`${from}/`)) (now[`${to}/${k.slice(from.length + 1)}`] = now[k]), delete now[k], moved++
32
+ if (moved) writeJson(FILE, now)
33
+ }
34
+
27
35
  // One event for a model ({ provider, model }). Older events fade (each new one counts a little more
28
36
  // than the last: after about 25 more, an event counts half), so a model that got better shows it.
29
37
  export function record(t, what) {