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/tools.js CHANGED
@@ -5,6 +5,7 @@ import { log } from './log.js'
5
5
  import { slug, fullSlug, keywords } from './memory.js'
6
6
  import { fillArgs, skillFiles, readSkillFile } from './skills.js'
7
7
  import { prompt } from './prompts.js'
8
+ import { GUIDE_NAMES, guideList, guideText } from './guides.js'
8
9
  import path from 'node:path'
9
10
  import os from 'node:os'
10
11
  import { spawn, execFileSync } from 'node:child_process'
@@ -14,8 +15,11 @@ import { c, diffLines, renderDiff, planPick } from './ui.js'
14
15
  import { pageCheck } from './check.js'
15
16
  import { killTree } from './spawn.js'
16
17
  import { scoreOf } from './rankings.js'
18
+ import { byRecord } from './record.js'
17
19
  import { family } from './client.js'
18
- import { webFetch, webSearch, fetchPage, pageView } from './web.js'
20
+ import { guarded } from './guard.js'
21
+ import { trusted, trust } from './trust.js'
22
+ import { webFetch, webSearch, fetchPage, pageView, hostsIn } from './web.js'
19
23
  import { savePage, saveSearch, findResearch } from './research.js'
20
24
  import { runHooks } from './hooks.js'
21
25
  import { parsePatch, applyChunks } from './patch.js'
@@ -74,8 +78,24 @@ export function resolveIn(root, p, read = false) {
74
78
  if (trimmed !== abs && !fs.existsSync(abs) && fs.existsSync(trimmed)) abs = trimmed
75
79
  if (abs !== root && !abs.startsWith(root + path.sep)) abs = intoProject(root, clean) ?? abs
76
80
  if (abs !== root && !abs.startsWith(root + path.sep)) throw new Error(`${clean} is outside the project; use a path relative to the project folder (${root}), like "index.html" or "src/app.js"`)
81
+ // where it really is: a link in the project (a repo can hold one to ~) doesn't take reads or writes out of it
82
+ const real = realOf(abs)
83
+ const top = realOf(root)
84
+ if (real !== top && !real.startsWith(top + path.sep) && !(read && readableOutside(real)) && !isSavedOutput(real)) throw new Error(`${clean} is a link to ${real}, outside the project: not read or written through it`)
77
85
  return abs
78
86
  }
87
+ // a path whose real place is in the project
88
+ const insideReal = (root, p) => ((r, top) => r === top || r.startsWith(top + path.sep))(realOf(p), realOf(root))
89
+ // The real place a path points to, its links followed; the part that doesn't exist yet, as it is
90
+ function realOf(p) {
91
+ for (let q = p; ; q = path.dirname(q)) {
92
+ try {
93
+ return path.join(fs.realpathSync.native(q), path.relative(q, p))
94
+ } catch {
95
+ if (q === path.dirname(q)) return p
96
+ }
97
+ }
98
+ }
79
99
 
80
100
  // A small model's mangled copy of the project's long path, meant inside it: any path with the
81
101
  // project folder's name in it ("/Users-me-…/myapp/index.html"): what comes after that name.
@@ -112,7 +132,7 @@ export function listFiles(root, limit = 2000) {
112
132
  })
113
133
  return out
114
134
  .split('\0')
115
- .filter((f) => f && fs.existsSync(path.join(root, f)))
135
+ .filter((f) => f && !OWN_DATA.test(f) && fs.existsSync(path.join(root, f))) // not HeartCode's own records
116
136
  .sort()
117
137
  .slice(0, limit)
118
138
  } catch {}
@@ -129,7 +149,7 @@ export function listFiles(root, limit = 2000) {
129
149
  if (IGNORE.has(e.name)) continue
130
150
  const p = path.join(dir, e.name)
131
151
  if (e.isDirectory()) walk(p)
132
- else if (e.isFile()) files.push(path.relative(root, p))
152
+ else if (e.isFile() && !OWN_DATA.test(path.relative(root, p).split(path.sep).join('/'))) files.push(path.relative(root, p)) // not HeartCode's own records
133
153
  }
134
154
  }
135
155
  walk(root)
@@ -256,6 +276,7 @@ export function searchFiles(root, query, sub = '', limit = 50) {
256
276
  searched++
257
277
  let buf
258
278
  try {
279
+ if (fs.lstatSync(path.resolve(root, f)).isSymbolicLink() && !insideReal(root, path.resolve(root, f))) continue // a link out of the project: not searched through
259
280
  buf = fs.readFileSync(path.resolve(root, f))
260
281
  } catch {
261
282
  continue
@@ -283,12 +304,13 @@ export function runCommand(root, cmd, { signal, timeout = 120_000, stdin, env, s
283
304
  let err = ''
284
305
  let done = false
285
306
  const group = process.platform !== 'win32'
286
- const child = spawn(cmd, {
307
+ const safe = guarded(cmd, { ...process.env, CI: '1', FORCE_COLOR: '0', NO_COLOR: '1', ...env }) // it can't stop HeartCode (guard.js)
308
+ const child = spawn(safe.command, {
287
309
  cwd: root,
288
310
  shell: true,
289
311
  detached: group,
290
312
  stdio: [stdin === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
291
- env: { ...process.env, CI: '1', FORCE_COLOR: '0', NO_COLOR: '1', ...env },
313
+ env: safe.env,
292
314
  })
293
315
  if (stdin !== undefined) {
294
316
  child.stdin.on('error', () => {}) // a command that doesn't read its input
@@ -307,7 +329,7 @@ export function runCommand(root, cmd, { signal, timeout = 120_000, stdin, env, s
307
329
  setTimeout(() => kill('SIGKILL'), 2000).unref()
308
330
  child.stdout.destroy()
309
331
  child.stderr.destroy()
310
- const plain = (t) => t.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '')
332
+ const plain = (t) => t.replace(/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g, '').replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').replace(/\x1b|[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\x9b]/g, '') // no escape sequences (OSC 52, titles) for the model or the screen
311
333
  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) }) })
312
334
  }
313
335
  let dropped = false // a very long output's start, left out (said, so it isn't read as the command failing)
@@ -438,16 +460,29 @@ export function declined(s, ok, what) {
438
460
  const PLACEHOLDER = /(\.\.\.|…)\s*(rest|existing|remaining|unchanged|other)|rest of (the )?(code|file)|existing code (here|unchanged)/i
439
461
 
440
462
  // Shows the diff, asks the user, writes (next = null: deletes the file). Shared by both agent modes.
463
+ // HeartCode's own records in the project: the conversations, saved outputs, worktrees and the folder's
464
+ // model choice. A model never writes them (a small one once wrote its notes over this conversation).
465
+ const OWN_DATA = /^\.heartcode\/(?:sessions|outputs|worktrees)(?:\/|$)|^\.heartcode\/models\.json$/
466
+
467
+ // HeartCode's settings for this folder (hooks and MCP servers run commands, prompts steer it) and
468
+ // git's (its hooks run commands): never written without asking, whatever the mode (a file or page
469
+ // telling the model to write one would run its commands next time)
470
+ const SETUP_FILES = /^(?:\.heartcode|\.git)(?:\/|$)/
471
+
441
472
  export async function proposeWrite(s, rel, old, next) {
442
473
  if (old === next) return { status: 'unchanged' }
474
+ const where = path.relative(s.root, resolveIn(s.root, rel)).split(path.sep).join('/')
475
+ if (OWN_DATA.test(where)) return { status: 'rejected', feedback: `${rel} is HeartCode's own record (this conversation and its state), not a project file: it can't be written. Put what you write in the project's own files.` }
443
476
  if (s.ui.permission === 'plan') return { status: 'rejected', feedback: prompt('agent/plan-refused', { command: false }) } // both modes write through here
444
477
  if (s.ownFiles && !s.ownFiles.includes(path.resolve(s.root, rel))) return { status: 'rejected', feedback: prompt('agent/part-files', { file: rel, files: s.ownFiles.map((f) => path.relative(s.root, f)).join(', ') }) } // a part's helper: every way of writing (a patch in run_command, guided mode)
445
478
  const ops = diffLines(old, next ?? '')
446
479
  s.ui.print(renderDiff(ops, rel))
447
480
  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"')
448
- const ok = await s.ui.confirm(next === null ? `Delete ${rel}?` : old ? `Apply this change to ${rel}?` : `Create ${rel}?`)
481
+ const setup = SETUP_FILES.test(where)
482
+ const ok = await s.ui.confirm(`${next === null ? `Delete ${rel}?` : old ? `Apply this change to ${rel}?` : `Create ${rel}?`}${setup ? ' (it sets up HeartCode or git here: it can run commands)' : ''}`, setup ? 'setup' : 'edit')
449
483
  log('write', rel, ok === true ? 'approved' : `rejected ${typeof ok === 'string' ? ok : ''}`)
450
484
  if (ok !== true) return { status: 'rejected', said: declined(s, ok, '') }
485
+ const wasTrusted = setup && trusted(s.root) // the folder's setup was yours: with this change you approved, still yours
451
486
  const abs = resolveIn(s.root, rel)
452
487
  s.track?.(rel, fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null) // for /rewind
453
488
  if (next === null) fs.rmSync(abs, { force: true })
@@ -455,6 +490,7 @@ export async function proposeWrite(s, rel, old, next) {
455
490
  fs.mkdirSync(path.dirname(abs), { recursive: true })
456
491
  fs.writeFileSync(abs, next)
457
492
  }
493
+ if (wasTrusted) trust(s.root)
458
494
  const add = ops.filter(([t]) => t === '+').length
459
495
  const del = ops.filter(([t]) => t === '-').length
460
496
  const res = { status: 'applied', summary: `+${add} -${del}`, diff: renderDiff(ops, rel, false, 2, 60), ops, text: next }
@@ -521,17 +557,17 @@ export function searchesOutside(cmd, root) {
521
557
  export async function runConfirmed(s, cmd, signal, background = false, wait) {
522
558
  s.ui.step(background ? 'run in background' : 'run', cmd, s.client?.model)
523
559
  if (s.ui.permission === 'plan' && !readOnlyCommand(cmd)) {
524
- s.ui.result('not run: plan mode')
560
+ s.ui.result('not run: plan mode', { refused: true })
525
561
  return prompt('agent/plan-refused', { command: true })
526
562
  }
527
563
  if (searchesOutside(cmd, s.root)) {
528
564
  log('command', `refused (searches outside the project): ${cmd}`)
529
- s.ui.result('not run: searches outside the project')
565
+ s.ui.result('not run: searches outside the project', { refused: true })
530
566
  return prompt('agent/outside-project', { root: s.root, wide: true })
531
567
  }
532
568
  const ok = s.ui.permission === 'plan' ? true : await s.ui.confirm(`Run ${c.bold(cmd)}?`, 'command') // plan mode: only read-only ones get here
533
569
  if (ok !== true) {
534
- s.ui.result('declined')
570
+ s.ui.result('declined', { refused: true })
535
571
  return declined(s, ok, 'The user declined to run this command.')
536
572
  }
537
573
  const secs = Number(wait) > 0 ? Number(wait) : background ? 3 : 30
@@ -549,7 +585,7 @@ export async function runConfirmed(s, cmd, signal, background = false, wait) {
549
585
  if (!job.exited) {
550
586
  if (signal?.aborted && !background) {
551
587
  removeJob(job) // Esc stops what it was waiting on
552
- s.ui.result('stopped')
588
+ s.ui.result('stopped', { refused: true })
553
589
  return `Stopped by the user (Esc) after ${Math.round((Date.now() - job.started) / 1000)}s.`
554
590
  }
555
591
  s.ui.result(`still running: #${job.id} in the background`)
@@ -563,12 +599,13 @@ export async function runConfirmed(s, cmd, signal, background = false, wait) {
563
599
  try {
564
600
  lines = fs.readFileSync(job.file, 'utf8').split(/\r?\n|\r/).filter((l) => l.trim()).length
565
601
  } catch {}
566
- s.ui.result(`exit ${job.code}${lines ? ` · ${lines} line${lines === 1 ? '' : 's'}` : ''}`)
567
- // failed: its last lines under it (what went wrong, usually), aligned with the result's text
568
- // why it failed: the last error line and what follows it (a stack's end says nothing), else the last lines
569
- const tail = job.code !== 0 ? tailLines(job, 40).filter((x) => x.trim()) : []
570
- const at = tail.findLastIndex((l) => /\b(error|exception|failed|fail|assert\w*|cannot|not found|denied)\b/i.test(l))
571
- if (job.code !== 0) for (const l of at === -1 ? tail.slice(-3) : tail.slice(at, at + 3)) s.ui.print(`${s.isSub ? ' ' : ' '}${c.faint(clip(l.trimEnd(), 120))}`)
602
+ const took = `${Math.max(0, Math.round((job.ended - job.started) / 100) / 10)}s`
603
+ s.ui.result(job.code === 0 ? `ok · ${took}${lines ? '' : ' · no output'}` : `exit ${job.code} · ${took}`, { ok: job.code === 0 })
604
+ // its last lines under it; failed: the last error line and what follows it (a stack's end says
605
+ // nothing), else the last lines
606
+ const tail = tailLines(job, 40).filter((x) => x.trim())
607
+ const at = job.code !== 0 ? tail.findLastIndex((l) => /\b(error|exception|failed|fail|assert\w*|cannot|not found|denied)\b/i.test(l)) : -1
608
+ for (const l of at === -1 ? tail.slice(-3) : tail.slice(at, at + 3)) s.ui.print(`${s.isSub ? ' ' : ' '}${(job.code === 0 ? c.faint : c.err)(clip(l.trimEnd(), 120))}`)
572
609
  const changed = changesSince(s, before)
573
610
  return `exit code ${left ? 0 : job.code}\n${output.trim() || '(no output)'}${changed ? `\nFiles this command changed: ${changed}` : ''}${left ? `\n${prompt('agent/left-running', { id: job.id })}` : ''}`
574
611
  }
@@ -676,6 +713,7 @@ export const TOOL_DEFS = [
676
713
  { name: 'run_command', get description() { return prompt('agent/tool-run_command') }, parameters: obj({ command: str, wait: int, background: { type: 'boolean' } }, ['command']) },
677
714
  { name: 'background', get description() { return prompt('agent/tool-background') }, parameters: obj({ action: { type: 'string', enum: ['output', 'list', 'stop'] }, id: int, wait: int }, ['action']) },
678
715
  { name: 'todo', get description() { return prompt('agent/tool-todo') }, parameters: obj({ todos: { type: 'array', items: obj({ content: str, status: { type: 'string', enum: ['pending', 'in_progress', 'completed', 'stuck'] }, why: str, parallel: { type: 'boolean' }, compare: { type: 'boolean' }, model: str, files: { type: 'array', items: str } }, ['content', 'status']) } }, ['todos']) },
716
+ { name: 'done', get description() { return prompt('agent/tool-done') }, parameters: obj({ checked: str, waiting: { type: 'boolean' } }, ['checked']) },
679
717
  { name: 'web_search', get description() { return prompt('agent/tool-web_search') }, parameters: obj({ query: str, fresh: { type: 'boolean' } }, ['query']) },
680
718
  { name: 'web_fetch', get description() { return prompt('agent/tool-web_fetch') }, parameters: obj({ url: str, look_for: str, start: int }, ['url']) },
681
719
  { name: 'ask_user', get description() { return prompt('agent/tool-ask_user') }, parameters: obj({ question: str, header: str, options: { type: 'array', items: str }, multiple: { type: 'boolean' }, emphasis: { type: 'boolean' } }, ['question', 'options']) }, // one question a call (small models manage that); several calls in one reply are one dialog (agent.js)
@@ -684,7 +722,7 @@ export const TOOL_DEFS = [
684
722
  // Plan mode (permission "plan"): looking around is fine, changing things isn't. Edits are refused,
685
723
  // and a command runs only when it only reads (else it's refused, not asked about).
686
724
  export const PLAN_HIDDEN = new Set(['edit_file', 'write_file', 'apply_patch'])
687
- const READ_ONLY = /^(cd|ls|cat|head|tail|wc|grep|egrep|rg|find|fd|tree|pwd|file|stat|du|df|which|type|echo|date|printenv|diff|cmp|sort|uniq|cut|jq|nl|basename|dirname|realpath|readlink|uname|whoami|(node|npm|python3?|go|cargo) --version|npm (ls|list|view|outdated)|git (status|log|diff|show|ls-files|blame|grep|describe|shortlog|rev-parse|config --get)|git (branch|tag|remote)( -[avlr]+| --list| -v)*$)\b/
725
+ const READ_ONLY = /^(cd|ls|cat|head|tail|wc|grep|egrep|rg|find|fd|tree|pwd|file|stat|du|df|which|type|echo|date|diff|cmp|sort|uniq|cut|jq|nl|basename|dirname|realpath|readlink|uname|whoami|(node|npm|python3?|go|cargo) --version|npm (ls|list|view|outdated)|git (status|log|diff|show|ls-files|blame|grep|describe|shortlog|rev-parse|config --get)|git (branch|tag|remote)( -[avlr]+| --list| -v)*$)\b/
688
726
  // A command that went into a folder outside the project (a small model copying the project's long
689
727
  // path wrong, then lost in what it finds there): told where the project is.
690
728
  function outsideNote(root, cmd) {
@@ -695,7 +733,7 @@ function outsideNote(root, cmd) {
695
733
 
696
734
  export function readOnlyCommand(cmd) {
697
735
  const c = String(cmd).trim()
698
- if (/[>`]|\$\(|<\(|\b(sudo|rm|mv|cp|tee|chmod|chown|dd|truncate|mkdir|touch|ln)\b|-delete\b|-exec|-ok\b|-fprint|-fls\b|--output\b|--pre\b|sed\s+-i|\bsort\b.*\s-o/.test(c)) return false // writes, or runs something else (git's --output, find's -fprint/-fls, rg's --pre)
736
+ if (/[>`]|\$\(|<\(|\b(sudo|rm|mv|cp|tee|chmod|chown|dd|truncate|mkdir|touch|ln)\b|-delete\b|-exec|-ok\b|-fprint|-fls\b|--output\b|--pre\b|sed\s+-i|\bsort\b.*\s-o|\s-O\S*|--open-files-in-pager|--ext-diff|--textconv|\s-c\s|\bprintenv\b|\benv\b/.test(c)) return false // writes, or runs something else (git's --output, find's -fprint/-fls, rg's --pre, git grep's -O<program>, git -c), or shows the environment (keys)
699
737
  return c.split(/\s*(?:&&|\|\||[;|&\n])\s*/).every((part) => READ_ONLY.test(part)) // `a & b`, a new line: each its own command
700
738
  }
701
739
 
@@ -744,6 +782,8 @@ export function extraTools(s) {
744
782
  parameters: obj({ action: { type: 'string', enum: ['write', 'read', 'search', 'delete'] }, name: str, description: str, type: str, tags: str, scope: { type: 'string', enum: ['project', 'global'] }, content: str, query: str }, ['action']),
745
783
  })
746
784
  }
785
+ // guides for kinds of work (guides.js): always there, so the model can look one up whenever it needs it
786
+ if (!s.ownSystem) out.push({ name: 'guide', description: prompt('agent/tool-guide', { guides: guideList() }), parameters: obj({ name: { type: 'string', enum: GUIDE_NAMES } }, ['name']) })
747
787
  const forModel = [...(s.skills?.values() ?? [])].filter((k) => k.use !== 'me') // "use: me" skills cost nothing here; "always" ones are in the system prompt, and listed so their files can be read
748
788
  if (forModel.length) {
749
789
  const skills = forModel.map((k) => `${k.name}: ${k.description}`).join('\n')
@@ -751,11 +791,12 @@ export function extraTools(s) {
751
791
  }
752
792
  if (!s.isSub && s.subagent) {
753
793
  const team = s.team?.() ?? []
754
- const model = { type: 'string', description: team.some((t) => t.jobs) ? 'Which helper does the job ("provider model" from "Your helpers"). Left out: the first helper.' : 'Which of your models does the job ("provider model" from "Your other models"). Left out: yours, or with images you can\'t see, the first of yours that can.' }
794
+ const model = { type: 'string', description: team.some((t) => t.jobs) ? 'Which helper does the job ("provider model" from "Your helpers"). Left out: the first helper. "list": all of them, nothing started.' : 'Which of your models does the job ("provider model" from "Your other models"). Left out: yours, or with images you can\'t see, the first of yours that can. "list": all of them, nothing started.' }
755
795
  const images = { type: 'array', items: str, description: 'Image paths or URLs for the helper to look at. Needs a model that sees images.' }
756
- out.push({ name: 'agent', get description() { return prompt('agent/tool-agent') }, parameters: obj({ description: str, prompt: str, ...(team.length && { model, images }) }, ['description', 'prompt']) })
796
+ const job = { type: 'string', enum: ['ui', 'code', 'hard', 'quick'], description: 'What kind of job: ui (anything people look at), code (logic, bugs, tests, reviews), hard (planning, long or tricky work), quick (searching, reading, small edits). With "model" left out, HeartCode gives it to a helper good at it.' }
797
+ out.push({ name: 'agent', get description() { return prompt('agent/tool-agent') }, parameters: obj({ description: str, prompt: str, ...(team.length && { model, images }), ...(team.some((t) => t.jobs) && { job }) }, ['description', 'prompt']) })
757
798
  }
758
- return [...out, ...(s.director && !s.appendSystem ? s.director.toolDefs(s) : [])] // manage (director.js); not when a program gives the instructions (--append-system-prompt)
799
+ return [...out, ...(s.director && !s.appendSystem && !s.ownSystem ? s.director.toolDefs(s) : [])] // manage (director.js); not when a program gives the instructions (--append-system-prompt, --system-prompt)
759
800
  }
760
801
 
761
802
  // todo: the model's checklist for this message, shown to the user each time it changes.
@@ -817,7 +858,7 @@ async function todoTool(s, args, signal, id) {
817
858
  // or one does it step by step. Nobody to answer (headless, no reply in time): several, the recommended
818
859
  const pending = todos.filter((t) => t.status === 'pending')
819
860
  if (s.split === undefined && !s.isSub && s.subagent && s.team?.().length && s.ui.permission !== 'plan' && pending.length >= 2) {
820
- const said = await askUser(s, { question: `The plan has ${todos.length} steps. Work on it with several agents at once?`, header: 'Agents', options: [{ label: 'Several agents at once', description: 'steps that stand alone run side by side, each on the model best at it; one no model is sure of is done by two, and the better kept' }, { label: 'One agent', description: 'one model does every step, in turn' }] })
861
+ const said = await askUser(s, { question: `The plan has ${todos.length} steps. Work on it with several agents at once?`, header: 'Agents', options: [{ label: 'Several agents at once', description: 'steps that stand alone run side by side, each on the model best at it' }, { label: 'One agent', description: 'one model does every step in turn' }] })
821
862
  s.split = /One agent/.test(said) ? 'one' : 'several'
822
863
  log('parts', `the user chose: ${s.split} (${said})`)
823
864
  }
@@ -860,7 +901,7 @@ export async function stuckSaid(s, step, why, signal, id, answer = false) {
860
901
  let advice = ''
861
902
  const other = n === 2 && !s.isSub && s.subagent && secondOpinionModel(s)
862
903
  if (other) {
863
- s.ui.step('stuck', `asking ${other.model} for a second opinion`)
904
+ s.ui.step('stuck', `asking ${other.model} for a second opinion`, '', { note: true })
864
905
  const tried = (s.ran ?? []).slice(-12).map((r) => `- ${r.command} → ${r.result}`).join('\n')
865
906
  try {
866
907
  advice = await s.subagent({ prompt: prompt('agent/second-opinion', { task: s.task ?? '', step: t.content, why: t.why, tried }), model: `${other.provider} ${other.model}`, description: 'second opinion' }, signal, id)
@@ -927,7 +968,7 @@ async function runParts(s, todos, signal, id) {
927
968
  const shown = todos.map((t) => ({ ...t })) // as printed: after the parts, what they changed
928
969
  for (const t of parts) t.status = 'in_progress'
929
970
  log('parts', parts.map((t) => `${t.content}${t.model ? ` (${t.model})` : ''}${t.files ? ` [${t.files.join(', ')}]` : ''}`))
930
- s.ui.step('parts', `${parts.length} part${parts.length > 1 ? 's' : ''} at once: ${parts.map((t) => `${clip(t.content, 40)}${t.model ? ` (${t.model})` : ''}`).join(' · ')}`)
971
+ s.ui.step('parts', `${parts.length} part${parts.length > 1 ? 's' : ''} at once: ${parts.map((t) => `${clip(t.content, 40)}${t.model ? ` (${t.model})` : ''}`).join(' · ')}`, '', { note: true })
931
972
  const plan = todos.map((t) => `- ${t.content}`).join('\n')
932
973
  const choices = (s.chat?.choices ?? []).join('; ')
933
974
  const reports = await Promise.all(
@@ -963,13 +1004,13 @@ async function comparePart(s, t, brief, signal, id) {
963
1004
  const tools = [{ provider: s.client?.provider, model: s.client?.model }, ...(s.team?.() ?? []).filter((x) => x.tools !== false)]
964
1005
  const pool = tools.some((x) => x.jobs) ? tools.filter((x, i) => i === 0 || x.jobs) : tools // helpers ticked: those (and this model)
965
1006
  const named = t.model && pool.find((x) => `${x.provider} ${x.model}` === t.model || x.model === t.model || t.model.endsWith(` ${x.model}`))
966
- const ranked = pool.map((x) => ({ x, score: scoreOf(x.model) })).sort((a, b) => a.score - b.score).map((r) => r.x)
1007
+ const ranked = pool.map((x) => ({ x, t: x, score: scoreOf(x.model) })).sort(byRecord).map((r) => r.x) // moved by the track record (record.js)
967
1008
  const first = named ?? ranked[0]
968
1009
  const second = ranked.find((x) => x !== first && family(x.model) !== family(first.model))
969
1010
  if (!first || !second) return null
970
1011
  const pair = [first, second]
971
1012
  const name = (x) => `${x.provider} ${x.model}`
972
- s.ui.step('compare', `${clip(t.content, 50)}: ${first.model} and ${second.model}, each in a copy`)
1013
+ s.ui.step('compare', `${clip(t.content, 50)}: ${first.model} and ${second.model}, each in a copy`, '', { note: true })
973
1014
  const copies = pair.map(() => copyProject(s.root))
974
1015
  try {
975
1016
  const outs = await Promise.all(pair.map((x, i) => s.subagent({ prompt: brief, model: name(x), description: `${clip(t.content, 30)} · ${x.model}`, ownFiles: t.files, root: copies[i] }, signal, id).catch((e) => (e.name === 'AbortError' || signal?.aborted ? Promise.reject(e) : `error: ${e.message}`))))
@@ -990,7 +1031,7 @@ async function comparePart(s, t, brief, signal, id) {
990
1031
  pick = 0
991
1032
  why = 'no one could compare them; the first kept'
992
1033
  const ask = prompt('agent/compare', { task: s.task ?? '', part: t.content, ...Object.fromEntries(results.flatMap((r, i) => [[`model${i}`, r.model.model], [`said${i}`, clip(r.said, 1500)], [`changes${i}`, clip(r.diffs.join('\n\n'), 6000)], [`check${i}`, r.check ? clip(r.check.report, 600) : '(no page to open)']])) })
993
- const judges = [...(s.team?.() ?? []).filter((x) => !pair.some((p) => p.provider === x.provider && p.model === x.model)).map((x) => ({ x, score: scoreOf(x.model) })).sort((a, b) => a.score - b.score).map((r) => r.x).slice(0, 2), null]
1034
+ const judges = [...(s.team?.() ?? []).filter((x) => !pair.some((p) => p.provider === x.provider && p.model === x.model)).map((x) => ({ x, t: x, score: scoreOf(x.model) })).sort(byRecord).map((r) => r.x).slice(0, 2), null]
994
1035
  for (const j of judges) {
995
1036
  try {
996
1037
  const { client } = j ? await s.engineFor(j) : { client: s.client }
@@ -1009,7 +1050,7 @@ async function comparePart(s, t, brief, signal, id) {
1009
1050
  }
1010
1051
  }
1011
1052
  }
1012
- s.ui.step('compare', pick < 0 ? `${clip(t.content, 50)}: neither worked` : `kept ${pair[pick].model}'s (${why})`)
1053
+ s.ui.step('compare', pick < 0 ? `${clip(t.content, 50)}: neither worked` : `kept ${pair[pick].model}'s (${why})`, '', { note: true })
1013
1054
  if (pick < 0) t.status = 'pending'
1014
1055
  if (pick < 0) return `## ${t.content}: not done\n${results.map((r) => `${r.model.model}: ${clip(r.said, 800)}${r.check?.broken ? `\nHeartCode's check: ${clip(r.check.report, 400)}` : ''}`).join('\n\n')}`
1015
1056
  // the better one's files into the project, each recorded for /rewind and the checks
@@ -1168,8 +1209,9 @@ async function webTool(s, name, args, signal) {
1168
1209
  return out
1169
1210
  }
1170
1211
  s.ui.spinner(`fetching ${clip(what, 60)}`)
1171
- if (!s.root || s.noResearch) return await webFetch(what, { start: args.start, signal }) // nothing kept (--no-memory)
1172
- const page = await fetchPage(what, { signal })
1212
+ const allowed = hostsIn(s.task) // a local or private host you named: may be fetched
1213
+ if (!s.root || s.noResearch) return await webFetch(what, { start: args.start, signal, allowed }) // nothing kept (--no-memory)
1214
+ const page = await fetchPage(what, { signal, allowed })
1173
1215
  if (page.error) return `error: ${page.error}`
1174
1216
  const head = `${page.ok ? '' : `error: HTTP ${page.status}\n`}${page.url !== page.asked ? `(redirected to ${page.url})\n` : ''}`
1175
1217
  if (!page.ok || !page.text.trim()) return `${head}${page.text.slice(0, MAX_PAGE) || '(empty page)'}` // an error page isn't worth keeping
@@ -1179,7 +1221,7 @@ async function webTool(s, name, args, signal) {
1179
1221
  if (id && s.chat) (s.chat.outputs ??= {})[id] = file // its result, cut from the conversation later, points here
1180
1222
  log('research', `saved ${page.url} → ${file}`)
1181
1223
  // "start": the part from there on, as before (an older conversation's way of reading on)
1182
- if (Number(args.start) > 0) return `${head}${await webFetch(page.url, { start: args.start, signal })}\n\n(All of this page is saved in ${file}.)`
1224
+ if (Number(args.start) > 0) return `${head}${await webFetch(page.url, { start: args.start, signal, allowed })}\n\n(All of this page is saved in ${file}.)`
1183
1225
  return `${head}${page.title ? `# ${page.title}\n` : ''}${page.url}\n\n${pageView(page.text, { lookFor: args.look_for, file, bodyLine })}`
1184
1226
  }
1185
1227
  const MAX_PAGE = 10_000
@@ -1362,6 +1404,11 @@ async function callMcp(s, server, tool, a, signal) {
1362
1404
  if (s.ui.permission === 'plan') return prompt('agent/plan-refused', { command: false }) // might change something
1363
1405
  const ok = await s.ui.confirm(`Use ${server.name} → ${tool}?`, 'command')
1364
1406
  if (ok !== true) return declined(s, ok, 'The user declined this call.')
1407
+ } else if (s.ui.permission !== 'plan' && !(s.mcpRead ??= new Set()).has(`${server.name}\n${tool}`)) {
1408
+ // it says it only reads: the server's word, so asked once a session (plan mode: taken, it's for looking)
1409
+ const ok = await s.ui.confirm(`Use ${server.name} → ${tool}? (it says it only reads; not asked again this session)`, 'command')
1410
+ if (ok !== true) return declined(s, ok, 'The user declined this call.')
1411
+ s.mcpRead.add(`${server.name}\n${tool}`)
1365
1412
  }
1366
1413
  const done = await s.mcpGate?.() // a helper may be using the MCP servers (a browser): its turn first
1367
1414
  s.ui.spinner(`${server.name} · ${tool}`)
@@ -1663,7 +1710,7 @@ async function toolRun(name, args, s, signal, id) {
1663
1710
  const stop = pre.block ? prompt('agent/hook', { reason: pre.block, blocked: true }) : notMine ? prompt('agent/part-files', { file: notMine, files: s.ownFiles.map((f) => path.relative(s.root, f)).join(', ') }) : null
1664
1711
  if (stop && name === 'run_command') {
1665
1712
  s.ui.step('run', String(args?.command ?? ''), s.client?.model) // a command's lines are shown where it runs, which this one never reaches
1666
- s.ui.result(refusal(stop))
1713
+ s.ui.result(refusal(stop), { refused: true })
1667
1714
  }
1668
1715
  if (stop) return stop
1669
1716
  let out = await tool(name, args, s, signal, id)
@@ -1771,6 +1818,9 @@ async function tool(name, args, s, signal, id) {
1771
1818
  return memoryTool(s, args)
1772
1819
  case 'todo':
1773
1820
  return await todoTool(s, args, signal, id)
1821
+ case 'done':
1822
+ s.saidDone = { checked: String(args.checked ?? ''), waiting: args.waiting === true }
1823
+ return s.saidDone.waiting ? 'Noted. Now ask the user exactly what you need, once.' : 'Noted. Now write your final answer, once. Already wrote it? Then only what is new since, or nothing.'
1774
1824
  case 'web_search':
1775
1825
  case 'web_fetch':
1776
1826
  return await webTool(s, name, args, signal)
@@ -1779,6 +1829,13 @@ async function tool(name, args, s, signal, id) {
1779
1829
  return await s.subagent(args, signal, id)
1780
1830
  case 'ask_user':
1781
1831
  return await askUser(s, args)
1832
+ case 'guide': {
1833
+ const g = String(args.name ?? '').trim().toLowerCase()
1834
+ if (!GUIDE_NAMES.includes(g)) return `error: no guide "${args.name}". Guides: ${GUIDE_NAMES.join(', ')}`
1835
+ const sent = (s.chat.sentNotes ??= [])
1836
+ if (!sent.includes(`domain:${g}`)) sent.push(`domain:${g}`) // not added again by itself (agent.js guidesFor)
1837
+ return guideText(s, g)
1838
+ }
1782
1839
  case 'skill': {
1783
1840
  const k = s.skills?.get(String(args.name ?? ''))
1784
1841
  if (!k || k.use === 'me') return `error: no skill "${args.name}". Skills: ${[...(s.skills?.values() ?? [])].filter((x) => x.use !== 'me').map((x) => x.name).join(', ') || 'none'}`
package/src/trust.js ADDED
@@ -0,0 +1,49 @@
1
+ // A folder's own HeartCode setup (.heartcode/hooks.json and mcp.json run commands, .heartcode/prompts
2
+ // steer the model) is used only once you said yes to it, for these files as they are: a cloned
3
+ // repo's would otherwise run its commands at your first message. Kept in ~/.heart/trusted.json
4
+ // (folder → a hash of those files); changed files are asked about again. Headless (-p) and editors
5
+ // (ACP) use it as it is: whoever runs them there chose that folder (as Claude Code's -p does).
6
+ import fs from 'node:fs'
7
+ import path from 'node:path'
8
+ import crypto from 'node:crypto'
9
+ import { HOME, readJson, writeJson } from './config.js'
10
+
11
+ const FILE = path.join(HOME, 'trusted.json')
12
+ export const trustAll = { on: false } // headless and ACP
13
+ const NAMES = ['hooks.json', 'mcp.json', 'prompts']
14
+
15
+ // the setup files this folder has (relative paths)
16
+ export function setupFiles(root) {
17
+ const dir = path.join(root, '.heartcode')
18
+ const out = []
19
+ for (const n of NAMES) {
20
+ const p = path.join(dir, n)
21
+ const st = fs.statSync(p, { throwIfNoEntry: false })
22
+ if (st?.isFile()) out.push(n)
23
+ else if (st?.isDirectory()) for (const f of fs.readdirSync(p).sort()) if (f.endsWith('.md')) out.push(`${n}/${f}`)
24
+ }
25
+ return out.map((f) => `.heartcode/${f}`)
26
+ }
27
+
28
+ const hashOf = (root, files) => {
29
+ const h = crypto.createHash('sha256')
30
+ for (const f of files) h.update(`${f}\0`).update(fs.readFileSync(path.join(root, f)))
31
+ return h.digest('hex')
32
+ }
33
+
34
+ export function trusted(root) {
35
+ if (trustAll.on || !root) return true
36
+ const files = setupFiles(root)
37
+ if (!files.length) return true
38
+ try {
39
+ return readJson(FILE, {})[path.resolve(root)] === hashOf(root, files)
40
+ } catch {
41
+ return false
42
+ }
43
+ }
44
+
45
+ export function trust(root) {
46
+ const all = readJson(FILE, {})
47
+ all[path.resolve(root)] = hashOf(root, setupFiles(root))
48
+ writeJson(FILE, all)
49
+ }