heartcode 0.1.69 → 0.1.101

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,35 +557,29 @@ 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
544
574
  const before = snapshot(s)
545
575
  const job = startJob(s.root, cmd)
546
- // its latest output line beside it, read a few times a second (the label is re-read every frame)
547
- let last = ''
548
- let readAt = 0
549
- s.ui.spinner(() => {
550
- if (Date.now() - readAt > 250) [readAt, last] = [Date.now(), tailLines(job, 3).filter((l) => l.trim()).at(-1)?.trim() ?? '']
551
- return `running ${clip(cmd, 50)}${last ? ` › ${clip(last, 60)}` : ''}`
552
- })
576
+ s.ui.spinner('running a command') // the command itself is the step above, in the conversation
553
577
  await waitFor(job, secs * 1000, signal)
554
578
  s.ui.stopSpin()
555
579
  if (!job.exited) {
556
580
  if (signal?.aborted && !background) {
557
581
  removeJob(job) // Esc stops what it was waiting on
558
- s.ui.result('stopped')
582
+ s.ui.result('stopped', { refused: true })
559
583
  return `Stopped by the user (Esc) after ${Math.round((Date.now() - job.started) / 1000)}s.`
560
584
  }
561
585
  s.ui.result(`still running: #${job.id} in the background`)
@@ -569,12 +593,13 @@ export async function runConfirmed(s, cmd, signal, background = false, wait) {
569
593
  try {
570
594
  lines = fs.readFileSync(job.file, 'utf8').split(/\r?\n|\r/).filter((l) => l.trim()).length
571
595
  } 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))}`)
596
+ const took = `${Math.max(0, Math.round((job.ended - job.started) / 100) / 10)}s`
597
+ s.ui.result(job.code === 0 ? `ok · ${took}${lines ? '' : ' · no output'}` : `exit ${job.code} · ${took}`, { ok: job.code === 0 })
598
+ // its last lines under it; failed: the last error line and what follows it (a stack's end says
599
+ // nothing), else the last lines
600
+ const tail = tailLines(job, 40).filter((x) => x.trim())
601
+ const at = job.code !== 0 ? tail.findLastIndex((l) => /\b(error|exception|failed|fail|assert\w*|cannot|not found|denied)\b/i.test(l)) : -1
602
+ 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
603
  const changed = changesSince(s, before)
579
604
  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
605
  }
@@ -592,7 +617,7 @@ async function backgroundTool(s, a, signal) {
592
617
  return was ? `Stopped #${job.id} (${job.command}).` : `#${job.id} had already exited with ${job.code}.`
593
618
  }
594
619
  if (Number(a.wait) > 0) {
595
- s.ui.spinner(`waiting on #${job.id} ${clip(job.command, 60)}`)
620
+ s.ui.spinner('waiting for a background command')
596
621
  await waitFor(job, Number(a.wait) * 1000, signal)
597
622
  s.ui.stopSpin()
598
623
  }
@@ -691,7 +716,7 @@ export const TOOL_DEFS = [
691
716
  // Plan mode (permission "plan"): looking around is fine, changing things isn't. Edits are refused,
692
717
  // and a command runs only when it only reads (else it's refused, not asked about).
693
718
  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/
719
+ 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
720
  // A command that went into a folder outside the project (a small model copying the project's long
696
721
  // path wrong, then lost in what it finds there): told where the project is.
697
722
  function outsideNote(root, cmd) {
@@ -702,7 +727,7 @@ function outsideNote(root, cmd) {
702
727
 
703
728
  export function readOnlyCommand(cmd) {
704
729
  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)
730
+ 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
731
  return c.split(/\s*(?:&&|\|\||[;|&\n])\s*/).every((part) => READ_ONLY.test(part)) // `a & b`, a new line: each its own command
707
732
  }
708
733
 
@@ -751,6 +776,8 @@ export function extraTools(s) {
751
776
  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
777
  })
753
778
  }
779
+ // guides for kinds of work (guides.js): always there, so the model can look one up whenever it needs it
780
+ if (!s.ownSystem) out.push({ name: 'guide', description: prompt('agent/tool-guide', { guides: guideList() }), parameters: obj({ name: { type: 'string', enum: GUIDE_NAMES } }, ['name']) })
754
781
  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
782
  if (forModel.length) {
756
783
  const skills = forModel.map((k) => `${k.name}: ${k.description}`).join('\n')
@@ -825,7 +852,7 @@ async function todoTool(s, args, signal, id) {
825
852
  // or one does it step by step. Nobody to answer (headless, no reply in time): several, the recommended
826
853
  const pending = todos.filter((t) => t.status === 'pending')
827
854
  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' }] })
855
+ 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
856
  s.split = /One agent/.test(said) ? 'one' : 'several'
830
857
  log('parts', `the user chose: ${s.split} (${said})`)
831
858
  }
@@ -868,7 +895,7 @@ export async function stuckSaid(s, step, why, signal, id, answer = false) {
868
895
  let advice = ''
869
896
  const other = n === 2 && !s.isSub && s.subagent && secondOpinionModel(s)
870
897
  if (other) {
871
- s.ui.step('stuck', `asking ${other.model} for a second opinion`)
898
+ s.ui.step('stuck', `asking ${other.model} for a second opinion`, '', { note: true })
872
899
  const tried = (s.ran ?? []).slice(-12).map((r) => `- ${r.command} → ${r.result}`).join('\n')
873
900
  try {
874
901
  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 +962,7 @@ async function runParts(s, todos, signal, id) {
935
962
  const shown = todos.map((t) => ({ ...t })) // as printed: after the parts, what they changed
936
963
  for (const t of parts) t.status = 'in_progress'
937
964
  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(' · ')}`)
965
+ 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
966
  const plan = todos.map((t) => `- ${t.content}`).join('\n')
940
967
  const choices = (s.chat?.choices ?? []).join('; ')
941
968
  const reports = await Promise.all(
@@ -977,7 +1004,7 @@ async function comparePart(s, t, brief, signal, id) {
977
1004
  if (!first || !second) return null
978
1005
  const pair = [first, second]
979
1006
  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`)
1007
+ s.ui.step('compare', `${clip(t.content, 50)}: ${first.model} and ${second.model}, each in a copy`, '', { note: true })
981
1008
  const copies = pair.map(() => copyProject(s.root))
982
1009
  try {
983
1010
  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 +1044,7 @@ async function comparePart(s, t, brief, signal, id) {
1017
1044
  }
1018
1045
  }
1019
1046
  }
1020
- s.ui.step('compare', pick < 0 ? `${clip(t.content, 50)}: neither worked` : `kept ${pair[pick].model}'s (${why})`)
1047
+ s.ui.step('compare', pick < 0 ? `${clip(t.content, 50)}: neither worked` : `kept ${pair[pick].model}'s (${why})`, '', { note: true })
1021
1048
  if (pick < 0) t.status = 'pending'
1022
1049
  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
1050
  // the better one's files into the project, each recorded for /rewind and the checks
@@ -1167,7 +1194,7 @@ async function webTool(s, name, args, signal) {
1167
1194
  log('research', `"${what}": ${saved.length} saved page(s) offered first`)
1168
1195
  return prompt('agent/research-saved', { query: what, pages: saved.map((r) => `- ${r.title} — ${r.url} (read ${r.fetched}${r.used_for ? `; used for: ${r.used_for}` : ''}) → ${r.file}`).join('\n') })
1169
1196
  }
1170
- s.ui.spinner(`searching: ${clip(what, 60)}`)
1197
+ s.ui.spinner('searching the web')
1171
1198
  const out = await webSearch(what, { signal })
1172
1199
  if (s.root && !s.noResearch && !/^(error:|no results)/.test(out)) {
1173
1200
  const { file } = saveSearch(s.root, what, out)
@@ -1175,9 +1202,10 @@ async function webTool(s, name, args, signal) {
1175
1202
  }
1176
1203
  return out
1177
1204
  }
1178
- 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 })
1205
+ s.ui.spinner('reading a web page')
1206
+ const allowed = hostsIn(s.task) // a local or private host you named: may be fetched
1207
+ if (!s.root || s.noResearch) return await webFetch(what, { start: args.start, signal, allowed }) // nothing kept (--no-memory)
1208
+ const page = await fetchPage(what, { signal, allowed })
1181
1209
  if (page.error) return `error: ${page.error}`
1182
1210
  const head = `${page.ok ? '' : `error: HTTP ${page.status}\n`}${page.url !== page.asked ? `(redirected to ${page.url})\n` : ''}`
1183
1211
  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 +1215,7 @@ async function webTool(s, name, args, signal) {
1187
1215
  if (id && s.chat) (s.chat.outputs ??= {})[id] = file // its result, cut from the conversation later, points here
1188
1216
  log('research', `saved ${page.url} → ${file}`)
1189
1217
  // "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}.)`
1218
+ 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
1219
  return `${head}${page.title ? `# ${page.title}\n` : ''}${page.url}\n\n${pageView(page.text, { lookFor: args.look_for, file, bodyLine })}`
1192
1220
  }
1193
1221
  const MAX_PAGE = 10_000
@@ -1370,9 +1398,14 @@ async function callMcp(s, server, tool, a, signal) {
1370
1398
  if (s.ui.permission === 'plan') return prompt('agent/plan-refused', { command: false }) // might change something
1371
1399
  const ok = await s.ui.confirm(`Use ${server.name} → ${tool}?`, 'command')
1372
1400
  if (ok !== true) return declined(s, ok, 'The user declined this call.')
1401
+ } else if (s.ui.permission !== 'plan' && !(s.mcpRead ??= new Set()).has(`${server.name}\n${tool}`)) {
1402
+ // it says it only reads: the server's word, so asked once a session (plan mode: taken, it's for looking)
1403
+ const ok = await s.ui.confirm(`Use ${server.name} → ${tool}? (it says it only reads; not asked again this session)`, 'command')
1404
+ if (ok !== true) return declined(s, ok, 'The user declined this call.')
1405
+ s.mcpRead.add(`${server.name}\n${tool}`)
1373
1406
  }
1374
1407
  const done = await s.mcpGate?.() // a helper may be using the MCP servers (a browser): its turn first
1375
- s.ui.spinner(`${server.name} · ${tool}`)
1408
+ s.ui.spinner(`using ${server.name}`)
1376
1409
  const started = Date.now()
1377
1410
  let r
1378
1411
  try {
@@ -1671,7 +1704,7 @@ async function toolRun(name, args, s, signal, id) {
1671
1704
  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
1705
  if (stop && name === 'run_command') {
1673
1706
  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))
1707
+ s.ui.result(refusal(stop), { refused: true })
1675
1708
  }
1676
1709
  if (stop) return stop
1677
1710
  let out = await tool(name, args, s, signal, id)
@@ -1790,6 +1823,13 @@ async function tool(name, args, s, signal, id) {
1790
1823
  return await s.subagent(args, signal, id)
1791
1824
  case 'ask_user':
1792
1825
  return await askUser(s, args)
1826
+ case 'guide': {
1827
+ const g = String(args.name ?? '').trim().toLowerCase()
1828
+ if (!GUIDE_NAMES.includes(g)) return `error: no guide "${args.name}". Guides: ${GUIDE_NAMES.join(', ')}`
1829
+ const sent = (s.chat.sentNotes ??= [])
1830
+ if (!sent.includes(`domain:${g}`)) sent.push(`domain:${g}`) // not added again by itself (agent.js guidesFor)
1831
+ return guideText(s, g)
1832
+ }
1793
1833
  case 'skill': {
1794
1834
  const k = s.skills?.get(String(args.name ?? ''))
1795
1835
  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
+ }