heartcode 0.1.63 → 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
@@ -19,7 +19,7 @@ export function projectDir(root, what) {
19
19
  return dir
20
20
  }
21
21
 
22
- const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search', 'testTimeout', 'updateCheck', 'logs', 'replyStart', 'replyIdle', 'mouse', 'helpers', 'helpersAuto', 'helperOrder', 'providerRank']
22
+ const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search', 'testTimeout', 'updateCheck', 'logs', 'replyStart', 'replyIdle', 'mouse', 'helpers', 'helpersAuto', 'trackRecord', 'alerts']
23
23
  // How long a reply may take (the settings page's Your models), in seconds, with the defaults:
24
24
  // replyStart: a reply must start within it, else that model failed; replyIdle: a reply that stops
25
25
  // sending for it is stalled.
@@ -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
 
@@ -118,6 +110,16 @@ export function providerName(url) {
118
110
  return (parts.length > 1 ? parts.at(-2) : parts[0]) || u.hostname
119
111
  }
120
112
 
113
+ // The model list never holds a model twice (the #1 again further down, or one twice): the first
114
+ // stays. On what's read and what's written, whoever changed the #1 or the list.
115
+ function oneEach(c) {
116
+ if (!Array.isArray(c?.rotation?.then)) return c
117
+ const seen = new Set(c.model ? [`${c.provider}/${c.model}`] : [])
118
+ const then = c.rotation.then.filter((t) => !seen.has(`${t?.provider}/${t?.model}`) && seen.add(`${t?.provider}/${t?.model}`))
119
+ if (then.length !== c.rotation.then.length) c.rotation = { ...c.rotation, then }
120
+ return c
121
+ }
122
+
121
123
  function fromFile() {
122
124
  const file = readJson(CONFIG_FILE, {})
123
125
  const cfg = { ...file, providers: { ...file.providers }, adhoc: null }
@@ -159,6 +161,7 @@ export function loadConfig(flags = {}) {
159
161
  const file = fromFile()
160
162
  const cfg = { providers: byName(file.providers), provider: file.provider, model: file.model, adhoc: null }
161
163
  for (const k of SETTINGS) cfg[k] = flags[k] ?? file[k]
164
+ oneEach(cfg)
162
165
  if (cfg.context) cfg.context = Number(cfg.context)
163
166
 
164
167
  const baseUrl = flags.baseUrl || process.env.HEART_BASE_URL || process.env.OPENAI_BASE_URL
@@ -184,28 +187,34 @@ export function loadConfig(flags = {}) {
184
187
  function saved(cfg) {
185
188
  const providers = byName(cfg.providers)
186
189
  if (cfg.adhoc) delete providers[cfg.adhoc]
187
- // a run-only provider (-m URL) or models chosen for this session (cfg.session, /select_model) aren't
188
- // saved as the current model: the pin is local, it must not become everyone's #1 on disk
189
- const keep = (cfg.adhoc && cfg.provider === cfg.adhoc) || cfg.session?.length ? fromFile() : null // a run-only provider or a model set chosen for this session isn't saved as the current
190
+ // a run-only provider (-u URL) or a model given for this run (-m, cfg.pinned: it's put in
191
+ // cfg.provider/model) isn't saved as the current model: it must not become everyone's #1 on disk.
192
+ // A folder's /select_model set (cfg.session alone) leaves cfg.provider/model as the list's #1, so a
193
+ // new #1 from the settings page is saved.
194
+ const keep = (cfg.adhoc && cfg.provider === cfg.adhoc) || cfg.pinned ? fromFile() : null
190
195
  const out = { providers, provider: keep?.provider ?? cfg.provider, model: keep?.model ?? cfg.model }
191
196
  for (const k of SETTINGS) if (cfg[k] !== undefined) out[k] = cfg[k]
197
+
192
198
  return JSON.parse(JSON.stringify(out))
193
199
  }
194
200
 
195
201
  // Several HeartCodes (and the settings page in each) keep a copy of the settings. A save writes only
196
202
  // what this one changed since it last read or wrote the file, onto the file as it is now, and
197
203
  // takeIn brings in what the others changed: no copy undoes another's change with an old value.
198
- // file: config.json as last read or written here; mine: what this run's cfg stood for then (a -m
199
- // 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).
200
206
  let file = null
201
- 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)
202
211
  const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
203
212
  const keysOf = (...objs) => [...new Set(objs.flatMap((o) => Object.keys(o ?? {})))]
204
- const synced = (cfg, disk) => ((file = disk), (mine = saved(cfg)))
213
+ const synced = (cfg, disk) => ((file = disk), mine.set(cfg, saved(cfg)))
205
214
 
206
215
  export function saveConfig(cfg) {
207
216
  const out = saved(cfg)
208
- const was = mine ?? {}
217
+ const was = mine.get(cfg) ?? {}
209
218
  const disk = readJson(CONFIG_FILE, {})
210
219
  for (const k of keysOf(out, was)) {
211
220
  if (k === 'providers') {
@@ -215,6 +224,7 @@ export function saveConfig(cfg) {
215
224
  disk.providers = byName(ps)
216
225
  } else if (!same(out[k], was[k])) out[k] === undefined ? delete disk[k] : (disk[k] = out[k])
217
226
  }
227
+ oneEach(disk)
218
228
  writeJson(CONFIG_FILE, disk)
219
229
  synced(cfg, disk)
220
230
  }
@@ -233,7 +243,8 @@ export function takeIn(cfg) {
233
243
  const value = k === 'providers' ? { ...byName(disk.providers), ...(cfg.adhoc && { [cfg.adhoc]: cfg.providers[cfg.adhoc] }) } : disk[k]
234
244
  value === undefined ? delete cfg[k] : (cfg[k] = value)
235
245
  }
246
+ oneEach(cfg)
236
247
  file = disk
237
- mine = saved(cfg)
248
+ mine.set(cfg, saved(cfg))
238
249
  return keys
239
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
@@ -10,6 +10,7 @@ import { est } from './client.js'
10
10
  import { applyEdit, parseBlocks, cleanCode, lostNames, reindent } from './edit.js'
11
11
  import { listFiles, namedFiles, readFileTool, searchFiles, numberLines, proposeWrite, runConfirmed, suggestCommands, resolveIn, writeResult, clip, allowed } from './tools.js'
12
12
  import { runHooks } from './hooks.js'
13
+ import { record } from './record.js'
13
14
  import { foldersOf } from './agent.js'
14
15
  import { c } from './ui.js'
15
16
 
@@ -39,6 +40,8 @@ export function nextActions(st) {
39
40
  let first
40
41
  if (!st.reads && st.hasFiles) first = ['read', 'search']
41
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']
42
45
  else first = ['finish', 'edit', 'run']
43
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)
44
47
  }
@@ -172,7 +175,7 @@ class Guided {
172
175
  this.notes = []
173
176
  this.changed = new Set()
174
177
  this.files = listFiles(s.root)
175
- 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)
176
179
  this.calls = 0
177
180
  this.stops = 0
178
181
  }
@@ -239,7 +242,8 @@ class Guided {
239
242
  const think = strat.thinking ? 4096 : 0
240
243
  const user = `${this.context(est(question) + room + think + tries * 600, skipKey)}\n\n${question}`
241
244
  this.instructions ??= userInstructions(this.s.root)
242
- const system = [prompt('guided/system'), this.instructions && prompt('agent/instructions', { instructions: this.instructions }), this.s.appendSystem].filter(Boolean).join('\n\n')
245
+ // --system-prompt: the program's after the step format only (that format is how this mode works at all)
246
+ const system = (this.s.ownSystem ? [prompt('guided/system'), this.s.ownSystem] : [prompt('guided/system'), this.instructions && prompt('agent/instructions', { instructions: this.instructions }), this.s.appendSystem]).filter(Boolean).join('\n\n')
243
247
  const messages = [
244
248
  { role: 'system', content: system },
245
249
  { role: 'user', content: user },
@@ -274,6 +278,7 @@ class Guided {
274
278
  this.st.wantsChange = await this.yesNo(prompt('guided/intent'), false) // the model says, not words in the task
275
279
  let last = ''
276
280
  let repeats = 0
281
+ const done = new Map() // each step's signature (and the edits made by then) → how many times this message
277
282
  // No step limit (Esc stops it); a model doing the same thing three times in a row is stopped.
278
283
  let step = 0
279
284
  for (; !this.s.maxTurns || step < this.s.maxTurns; step++) {
@@ -283,6 +288,27 @@ class Guided {
283
288
  log('guided', `step ${step + 1}: ${action}${auto ? ' (autopilot)' : ''}`, this.st)
284
289
  if (auto === 'edit' && this.st.runs) this.st.fixes++
285
290
  if (action === 'finish') {
291
+ // not done, as native mode's checks: it said the task needs a change (or tried one) and changed nothing, or it
292
+ // changed files and ran nothing since. Told twice; then the next of your models; with none
293
+ // left, the answer says what's missing (it isn't claimed done)
294
+ const missing = this.s.ownSystem ? null : (this.st.wantsChange || this.st.editTries) && !this.st.edits ? 'nothing' : this.st.edits && this.st.editsSinceRun ? 'unchecked' : null
295
+ if (missing && (this.held = (this.held ?? 0) + 1) <= 3) {
296
+ if (this.held === 3) {
297
+ const was = this.s.client.model
298
+ const gone = { provider: this.s.client.provider, model: was } // before moveOn changes them
299
+ if (this.s.client.moveOn?.(`${was} said it was done, but ${missing === 'nothing' ? 'changed nothing' : "didn't run its change"}`)) {
300
+ record(gone, 'handover') // its track record (record.js)
301
+ this.ui.handover(this.s.client.model, `${was} said it was done, but ${missing === 'nothing' ? 'changed nothing' : "didn't run its change"}`)
302
+ this.held = 0
303
+ }
304
+ }
305
+ log('guided', `finish held: ${missing}`)
306
+ this.note('not-done', 'not done yet', prompt(`guided/not-done-${missing}`))
307
+ this.st.held = true
308
+ this.st.missing = missing
309
+ continue
310
+ }
311
+ this.unproven = missing
286
312
  // the Stop hooks, as in native mode (the main conversation's, not a helper's): one that blocks has it carry on
287
313
  const hook = this.s.isSub ? {} : await runHooks(this.s, 'Stop', { stop_hook_active: this.stops++ > 0 }, this.signal)
288
314
  if (!hook.block) break
@@ -295,20 +321,29 @@ class Guided {
295
321
  sig = await this[action]()
296
322
  } catch (e) {
297
323
  if (e.name === 'AbortError' || e.name === 'TimeoutError' || e.status || /cannot reach/.test(e.message)) throw e
298
- this.ui.result(c.red(e.message))
324
+ this.ui.result(e.message, { ok: false })
299
325
  this.note(null, `${action} failed`, e.message)
300
326
  sig = `${action}:error`
301
327
  }
302
328
  repeats = sig === last ? repeats + 1 : 0
303
329
  last = sig
304
330
  this.st.avoid = repeats ? action : null
305
- if (repeats >= 2) {
306
- // the next of your models carries on; with none, it goes on being told (only Esc stops it)
331
+ // the same step again and again, in a row or with others between (search X, something else,
332
+ // search X…: a small model going round): the third time, the next of your models carries on;
333
+ // with none, it goes on being told (only Esc stops it)
334
+ const key = `${sig}#${this.st.edits}` // a step again with nothing changed since (editing a file again, or reading it after an edit, is progress)
335
+ const times = (done.get(key) ?? 0) + 1
336
+ done.set(key, times)
337
+ if (repeats >= 2 || times >= 3) {
307
338
  const was = this.s.client.model
308
- if (this.s.client.moveOn?.(`${was} did the same thing three times in a row`)) this.ui.warn(`${was} did the same thing three times in a row; handing over to ${this.s.client.model}`)
309
- else this.ui.warn(`${was} did the same thing three times in a row — it carries on, told so; Esc stops it`)
339
+ const gone = { provider: this.s.client.provider, model: was } // before moveOn changes them
340
+ const why = repeats >= 2 ? 'did the same thing three times in a row' : 'kept doing the same thing (three times)'
341
+ record(gone, 'handover') // its track record (record.js)
342
+ if (this.s.client.moveOn?.(`${was} ${why}`)) this.ui.handover(this.s.client.model, `${was} ${why}`)
343
+ else this.ui.warn(`${was} ${why} — it carries on, told so; Esc stops it`)
310
344
  this.note(null, 'warning', prompt('guided/note-repeated'))
311
345
  repeats = 0
346
+ done.clear()
312
347
  continue
313
348
  }
314
349
  if (repeats === 1) this.note(null, 'warning', prompt('guided/note-repeated'))
@@ -339,7 +374,7 @@ class Guided {
339
374
  const post = await runHooks(s, 'PostToolUse', { tool_name: name, tool_input: args, tool_response: out }, this.signal)
340
375
  if (post.block) out += `\n\n${prompt('agent/hook', { reason: post.block, after: true })}`
341
376
  }
342
- 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 })
343
378
  s.onEvent?.({ type: 'tool', id, name, output: out, model: `${s.client.provider}/${s.client.model}` })
344
379
  return out
345
380
  }
@@ -439,7 +474,7 @@ class Guided {
439
474
  if (next === null) return `edit:${f}`
440
475
  const lost = lostNames(old, next, this.task)
441
476
  if (lost.length) {
442
- this.ui.result(c.yellow(`that edit deleted ${lost.join(', ')}; retrying`))
477
+ this.ui.result(`that edit deleted ${lost.join(', ')}; retrying`, { refused: true })
443
478
  const again = await this.editRewrite(f, old, prompt('guided/keep-names', { names: lost.join(', '), them: lost.length > 1 ? 'them' : 'it' }))
444
479
  const still = again === null ? lost : lostNames(old, again, this.task)
445
480
  if (again !== null && !still.length) next = again
@@ -525,7 +560,7 @@ class Guided {
525
560
  }
526
561
 
527
562
  failed(f, why) {
528
- this.ui.result(c.red(`edit failed: ${why}`))
563
+ this.ui.result(`edit failed: ${why}`, { ok: false })
529
564
  this.note(null, `editing ${f} failed`, why)
530
565
  return null
531
566
  }
@@ -540,6 +575,7 @@ class Guided {
540
575
  this.note(null, `${old ? 'edit' : 'create'} ${f}`, out + (r?.diff ? '\n' + r.diff : ''))
541
576
  if (r?.status === 'applied') {
542
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)
543
579
  this.changed.add(f)
544
580
  this.st.editsSinceRun++
545
581
  this.st.hasFiles = true
@@ -581,6 +617,7 @@ class Guided {
581
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
582
618
  const code = /^exit code (\S+)/.exec(out)?.[1]
583
619
  this.st.runs++
620
+ this.st.missing = null // what finish was held for is done
584
621
  this.st.editsSinceRun = 0
585
622
  this.st.lastRun = code === undefined ? null : code === '0' ? 0 : code
586
623
  this.note(null, `ran: ${cmd}`, out)
@@ -637,6 +674,8 @@ class Guided {
637
674
  return text
638
675
  }
639
676
  this.ui.stopSpin()
677
+ // said done without doing it, and no model left to: said so, not left looking done
678
+ if (this.unproven) return `${res.content}\n\n${prompt(`guided/unproven-${this.unproven}`)}`
640
679
  return res.content
641
680
  }
642
681
  }
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
  }
@@ -144,7 +147,7 @@ export class HeadlessUI {
144
147
  }
145
148
 
146
149
  // Runs the messages (prompt, or stdin) and writes the output. Returns the exit code.
147
- // app: the App (bin/heartcode.js); opts: { prompt, input, output, appendSystem }
150
+ // app: the App (bin/heartcode.js); opts: { prompt, input, output, appendSystem, ownSystem }
148
151
  export async function runHeadless(app, opts) {
149
152
  const out = opts.output ?? 'text'
150
153
  const emit = (obj) => process.stdout.write(JSON.stringify(obj) + '\n')
@@ -156,6 +159,7 @@ export async function runHeadless(app, opts) {
156
159
  return 1
157
160
  }
158
161
  s.appendSystem = opts.appendSystem || undefined
162
+ s.ownSystem = opts.ownSystem || undefined // --system-prompt: the program's, instead of HeartCode's (agent.js)
159
163
  const session_id = app.chat.id
160
164
  const model = `${s.client.provider ?? app.cfg.provider}/${s.client.model}`
161
165
 
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(', ')}`