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/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'
@@ -16,7 +17,9 @@ import { killTree } from './spawn.js'
16
17
  import { scoreOf } from './rankings.js'
17
18
  import { byRecord } from './record.js'
18
19
  import { family } from './client.js'
19
- 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'
20
23
  import { savePage, saveSearch, findResearch } from './research.js'
21
24
  import { runHooks } from './hooks.js'
22
25
  import { parsePatch, applyChunks } from './patch.js'
@@ -75,8 +78,24 @@ export function resolveIn(root, p, read = false) {
75
78
  if (trimmed !== abs && !fs.existsSync(abs) && fs.existsSync(trimmed)) abs = trimmed
76
79
  if (abs !== root && !abs.startsWith(root + path.sep)) abs = intoProject(root, clean) ?? abs
77
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`)
78
85
  return abs
79
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
+ }
80
99
 
81
100
  // A small model's mangled copy of the project's long path, meant inside it: any path with the
82
101
  // project folder's name in it ("/Users-me-…/myapp/index.html"): what comes after that name.
@@ -257,6 +276,7 @@ export function searchFiles(root, query, sub = '', limit = 50) {
257
276
  searched++
258
277
  let buf
259
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
260
280
  buf = fs.readFileSync(path.resolve(root, f))
261
281
  } catch {
262
282
  continue
@@ -284,12 +304,13 @@ export function runCommand(root, cmd, { signal, timeout = 120_000, stdin, env, s
284
304
  let err = ''
285
305
  let done = false
286
306
  const group = process.platform !== 'win32'
287
- 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, {
288
309
  cwd: root,
289
310
  shell: true,
290
311
  detached: group,
291
312
  stdio: [stdin === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
292
- env: { ...process.env, CI: '1', FORCE_COLOR: '0', NO_COLOR: '1', ...env },
313
+ env: safe.env,
293
314
  })
294
315
  if (stdin !== undefined) {
295
316
  child.stdin.on('error', () => {}) // a command that doesn't read its input
@@ -308,7 +329,7 @@ export function runCommand(root, cmd, { signal, timeout = 120_000, stdin, env, s
308
329
  setTimeout(() => kill('SIGKILL'), 2000).unref()
309
330
  child.stdout.destroy()
310
331
  child.stderr.destroy()
311
- 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
312
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) }) })
313
334
  }
314
335
  let dropped = false // a very long output's start, left out (said, so it isn't read as the command failing)
@@ -443,17 +464,25 @@ const PLACEHOLDER = /(\.\.\.|…)\s*(rest|existing|remaining|unchanged|other)|re
443
464
  // model choice. A model never writes them (a small one once wrote its notes over this conversation).
444
465
  const OWN_DATA = /^\.heartcode\/(?:sessions|outputs|worktrees)(?:\/|$)|^\.heartcode\/models\.json$/
445
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
+
446
472
  export async function proposeWrite(s, rel, old, next) {
447
473
  if (old === next) return { status: 'unchanged' }
448
- if (OWN_DATA.test(path.relative(s.root, resolveIn(s.root, rel)).split(path.sep).join('/'))) 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.` }
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.` }
449
476
  if (s.ui.permission === 'plan') return { status: 'rejected', feedback: prompt('agent/plan-refused', { command: false }) } // both modes write through here
450
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)
451
478
  const ops = diffLines(old, next ?? '')
452
479
  s.ui.print(renderDiff(ops, rel))
453
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"')
454
- 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')
455
483
  log('write', rel, ok === true ? 'approved' : `rejected ${typeof ok === 'string' ? ok : ''}`)
456
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
457
486
  const abs = resolveIn(s.root, rel)
458
487
  s.track?.(rel, fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null) // for /rewind
459
488
  if (next === null) fs.rmSync(abs, { force: true })
@@ -461,6 +490,7 @@ export async function proposeWrite(s, rel, old, next) {
461
490
  fs.mkdirSync(path.dirname(abs), { recursive: true })
462
491
  fs.writeFileSync(abs, next)
463
492
  }
493
+ if (wasTrusted) trust(s.root)
464
494
  const add = ops.filter(([t]) => t === '+').length
465
495
  const del = ops.filter(([t]) => t === '-').length
466
496
  const res = { status: 'applied', summary: `+${add} -${del}`, diff: renderDiff(ops, rel, false, 2, 60), ops, text: next }
@@ -527,17 +557,17 @@ export function searchesOutside(cmd, root) {
527
557
  export async function runConfirmed(s, cmd, signal, background = false, wait) {
528
558
  s.ui.step(background ? 'run in background' : 'run', cmd, s.client?.model)
529
559
  if (s.ui.permission === 'plan' && !readOnlyCommand(cmd)) {
530
- s.ui.result('not run: plan mode')
560
+ s.ui.result('not run: plan mode', { refused: true })
531
561
  return prompt('agent/plan-refused', { command: true })
532
562
  }
533
563
  if (searchesOutside(cmd, s.root)) {
534
564
  log('command', `refused (searches outside the project): ${cmd}`)
535
- s.ui.result('not run: searches outside the project')
565
+ s.ui.result('not run: searches outside the project', { refused: true })
536
566
  return prompt('agent/outside-project', { root: s.root, wide: true })
537
567
  }
538
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
539
569
  if (ok !== true) {
540
- s.ui.result('declined')
570
+ s.ui.result('declined', { refused: true })
541
571
  return declined(s, ok, 'The user declined to run this command.')
542
572
  }
543
573
  const secs = Number(wait) > 0 ? Number(wait) : background ? 3 : 30
@@ -555,7 +585,7 @@ export async function runConfirmed(s, cmd, signal, background = false, wait) {
555
585
  if (!job.exited) {
556
586
  if (signal?.aborted && !background) {
557
587
  removeJob(job) // Esc stops what it was waiting on
558
- s.ui.result('stopped')
588
+ s.ui.result('stopped', { refused: true })
559
589
  return `Stopped by the user (Esc) after ${Math.round((Date.now() - job.started) / 1000)}s.`
560
590
  }
561
591
  s.ui.result(`still running: #${job.id} in the background`)
@@ -569,12 +599,13 @@ export async function runConfirmed(s, cmd, signal, background = false, wait) {
569
599
  try {
570
600
  lines = fs.readFileSync(job.file, 'utf8').split(/\r?\n|\r/).filter((l) => l.trim()).length
571
601
  } catch {}
572
- s.ui.result(`exit ${job.code}${lines ? ` · ${lines} line${lines === 1 ? '' : 's'}` : ''}`)
573
- // failed: its last lines under it (what went wrong, usually), aligned with the result's text
574
- // why it failed: the last error line and what follows it (a stack's end says nothing), else the last lines
575
- const tail = job.code !== 0 ? tailLines(job, 40).filter((x) => x.trim()) : []
576
- const at = tail.findLastIndex((l) => /\b(error|exception|failed|fail|assert\w*|cannot|not found|denied)\b/i.test(l))
577
- 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))}`)
578
609
  const changed = changesSince(s, before)
579
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 })}` : ''}`
580
611
  }
@@ -691,7 +722,7 @@ export const TOOL_DEFS = [
691
722
  // Plan mode (permission "plan"): looking around is fine, changing things isn't. Edits are refused,
692
723
  // and a command runs only when it only reads (else it's refused, not asked about).
693
724
  export const PLAN_HIDDEN = new Set(['edit_file', 'write_file', 'apply_patch'])
694
- 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/
695
726
  // A command that went into a folder outside the project (a small model copying the project's long
696
727
  // path wrong, then lost in what it finds there): told where the project is.
697
728
  function outsideNote(root, cmd) {
@@ -702,7 +733,7 @@ function outsideNote(root, cmd) {
702
733
 
703
734
  export function readOnlyCommand(cmd) {
704
735
  const c = String(cmd).trim()
705
- 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)
706
737
  return c.split(/\s*(?:&&|\|\||[;|&\n])\s*/).every((part) => READ_ONLY.test(part)) // `a & b`, a new line: each its own command
707
738
  }
708
739
 
@@ -751,6 +782,8 @@ export function extraTools(s) {
751
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']),
752
783
  })
753
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']) })
754
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
755
788
  if (forModel.length) {
756
789
  const skills = forModel.map((k) => `${k.name}: ${k.description}`).join('\n')
@@ -825,7 +858,7 @@ async function todoTool(s, args, signal, id) {
825
858
  // or one does it step by step. Nobody to answer (headless, no reply in time): several, the recommended
826
859
  const pending = todos.filter((t) => t.status === 'pending')
827
860
  if (s.split === undefined && !s.isSub && s.subagent && s.team?.().length && s.ui.permission !== 'plan' && pending.length >= 2) {
828
- 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' }] })
829
862
  s.split = /One agent/.test(said) ? 'one' : 'several'
830
863
  log('parts', `the user chose: ${s.split} (${said})`)
831
864
  }
@@ -868,7 +901,7 @@ export async function stuckSaid(s, step, why, signal, id, answer = false) {
868
901
  let advice = ''
869
902
  const other = n === 2 && !s.isSub && s.subagent && secondOpinionModel(s)
870
903
  if (other) {
871
- 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 })
872
905
  const tried = (s.ran ?? []).slice(-12).map((r) => `- ${r.command} → ${r.result}`).join('\n')
873
906
  try {
874
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)
@@ -935,7 +968,7 @@ async function runParts(s, todos, signal, id) {
935
968
  const shown = todos.map((t) => ({ ...t })) // as printed: after the parts, what they changed
936
969
  for (const t of parts) t.status = 'in_progress'
937
970
  log('parts', parts.map((t) => `${t.content}${t.model ? ` (${t.model})` : ''}${t.files ? ` [${t.files.join(', ')}]` : ''}`))
938
- 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 })
939
972
  const plan = todos.map((t) => `- ${t.content}`).join('\n')
940
973
  const choices = (s.chat?.choices ?? []).join('; ')
941
974
  const reports = await Promise.all(
@@ -977,7 +1010,7 @@ async function comparePart(s, t, brief, signal, id) {
977
1010
  if (!first || !second) return null
978
1011
  const pair = [first, second]
979
1012
  const name = (x) => `${x.provider} ${x.model}`
980
- 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 })
981
1014
  const copies = pair.map(() => copyProject(s.root))
982
1015
  try {
983
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}`))))
@@ -1017,7 +1050,7 @@ async function comparePart(s, t, brief, signal, id) {
1017
1050
  }
1018
1051
  }
1019
1052
  }
1020
- 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 })
1021
1054
  if (pick < 0) t.status = 'pending'
1022
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')}`
1023
1056
  // the better one's files into the project, each recorded for /rewind and the checks
@@ -1176,8 +1209,9 @@ async function webTool(s, name, args, signal) {
1176
1209
  return out
1177
1210
  }
1178
1211
  s.ui.spinner(`fetching ${clip(what, 60)}`)
1179
- if (!s.root || s.noResearch) return await webFetch(what, { start: args.start, signal }) // nothing kept (--no-memory)
1180
- 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 })
1181
1215
  if (page.error) return `error: ${page.error}`
1182
1216
  const head = `${page.ok ? '' : `error: HTTP ${page.status}\n`}${page.url !== page.asked ? `(redirected to ${page.url})\n` : ''}`
1183
1217
  if (!page.ok || !page.text.trim()) return `${head}${page.text.slice(0, MAX_PAGE) || '(empty page)'}` // an error page isn't worth keeping
@@ -1187,7 +1221,7 @@ async function webTool(s, name, args, signal) {
1187
1221
  if (id && s.chat) (s.chat.outputs ??= {})[id] = file // its result, cut from the conversation later, points here
1188
1222
  log('research', `saved ${page.url} → ${file}`)
1189
1223
  // "start": the part from there on, as before (an older conversation's way of reading on)
1190
- 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}.)`
1191
1225
  return `${head}${page.title ? `# ${page.title}\n` : ''}${page.url}\n\n${pageView(page.text, { lookFor: args.look_for, file, bodyLine })}`
1192
1226
  }
1193
1227
  const MAX_PAGE = 10_000
@@ -1370,6 +1404,11 @@ async function callMcp(s, server, tool, a, signal) {
1370
1404
  if (s.ui.permission === 'plan') return prompt('agent/plan-refused', { command: false }) // might change something
1371
1405
  const ok = await s.ui.confirm(`Use ${server.name} → ${tool}?`, 'command')
1372
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}`)
1373
1412
  }
1374
1413
  const done = await s.mcpGate?.() // a helper may be using the MCP servers (a browser): its turn first
1375
1414
  s.ui.spinner(`${server.name} · ${tool}`)
@@ -1671,7 +1710,7 @@ async function toolRun(name, args, s, signal, id) {
1671
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
1672
1711
  if (stop && name === 'run_command') {
1673
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
1674
- s.ui.result(refusal(stop))
1713
+ s.ui.result(refusal(stop), { refused: true })
1675
1714
  }
1676
1715
  if (stop) return stop
1677
1716
  let out = await tool(name, args, s, signal, id)
@@ -1790,6 +1829,13 @@ async function tool(name, args, s, signal, id) {
1790
1829
  return await s.subagent(args, signal, id)
1791
1830
  case 'ask_user':
1792
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
+ }
1793
1839
  case 'skill': {
1794
1840
  const k = s.skills?.get(String(args.name ?? ''))
1795
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
+ }