heartcode 0.1.45 → 0.1.56

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
@@ -3,7 +3,7 @@ import { createHash } from 'node:crypto'
3
3
  import { AsyncLocalStorage } from 'node:async_hooks'
4
4
  import { log } from './log.js'
5
5
  import { slug, fullSlug, keywords } from './memory.js'
6
- import { fillArgs } from './skills.js'
6
+ import { fillArgs, skillFiles, readSkillFile } from './skills.js'
7
7
  import { prompt } from './prompts.js'
8
8
  import path from 'node:path'
9
9
  import os from 'node:os'
@@ -17,7 +17,7 @@ import { runHooks } from './hooks.js'
17
17
  import { parsePatch, applyChunks } from './patch.js'
18
18
  import { formatFile } from './format.js'
19
19
  import { diagnose, lspTool, findCommand } from './lsp.js'
20
- import { startJob, waitFor, newOutput, listJobs, getJob, stopJob, removeJob, keepLeftovers, jobLine } from './background.js'
20
+ import { startJob, waitFor, newOutput, tailLines, listJobs, getJob, stopJob, removeJob, keepLeftovers, jobLine } from './background.js'
21
21
 
22
22
  const IGNORE = new Set(['.git', 'node_modules', 'dist', 'build', '.next', 'coverage', '.venv', 'venv', '__pycache__', 'target', '.cache', '.DS_Store'])
23
23
 
@@ -212,7 +212,7 @@ function readImage(s, p) {
212
212
  }
213
213
  return `${rel}: the image is attached in the next message`
214
214
  }
215
- return s.team?.().some((t) => t.images) ? prompt('agent/images-unseen', { files: rel }) : `${rel} is an image, and you can't see images.`
215
+ return s.team?.().some((t) => t.images) ? prompt('agent/tool-images', { files: rel, unseen: true }) : `${rel} is an image, and you can't see images.`
216
216
  }
217
217
 
218
218
  export function searchFiles(root, query, sub = '', limit = 50) {
@@ -387,7 +387,8 @@ const PLACEHOLDER = /(\.\.\.|…)\s*(rest|existing|remaining|unchanged|other)|re
387
387
  // Shows the diff, asks the user, writes (next = null: deletes the file). Shared by both agent modes.
388
388
  export async function proposeWrite(s, rel, old, next) {
389
389
  if (old === next) return { status: 'unchanged' }
390
- if (s.ui.permission === 'plan') return { status: 'rejected', feedback: prompt('agent/plan-refused') } // both modes write through here
390
+ if (s.ui.permission === 'plan') return { status: 'rejected', feedback: prompt('agent/plan-refused', { command: false }) } // both modes write through here
391
+ 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)
391
392
  const ops = diffLines(old, next ?? '')
392
393
  s.ui.print(renderDiff(ops, rel))
393
394
  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"')
@@ -468,19 +469,28 @@ export async function runConfirmed(s, cmd, signal, background = false, wait) {
468
469
  s.ui.step(background ? 'run in background' : 'run', cmd)
469
470
  if (s.ui.permission === 'plan' && !readOnlyCommand(cmd)) {
470
471
  s.ui.result('not run: plan mode')
471
- return prompt('agent/plan-refused-command')
472
+ return prompt('agent/plan-refused', { command: true })
472
473
  }
473
474
  if (searchesOutside(cmd, s.root)) {
474
475
  log('command', `refused (searches outside the project): ${cmd}`)
475
476
  s.ui.result('not run: searches outside the project')
476
- return prompt('agent/command-too-wide', { root: s.root })
477
+ return prompt('agent/outside-project', { root: s.root, wide: true })
477
478
  }
478
479
  const ok = s.ui.permission === 'plan' ? true : await s.ui.confirm(`Run ${c.bold(cmd)}?`, 'command') // plan mode: only read-only ones get here
479
- if (ok !== true) return declined(s, ok, 'The user declined to run this command.')
480
+ if (ok !== true) {
481
+ s.ui.result('declined')
482
+ return declined(s, ok, 'The user declined to run this command.')
483
+ }
480
484
  const secs = Number(wait) > 0 ? Number(wait) : background ? 3 : 30
481
485
  const before = snapshot(s)
482
- s.ui.spinner(`running ${cmd}`)
483
486
  const job = startJob(s.root, cmd)
487
+ // its latest output line beside it, read a few times a second (the label is re-read every frame)
488
+ let last = ''
489
+ let readAt = 0
490
+ s.ui.spinner(() => {
491
+ if (Date.now() - readAt > 250) [readAt, last] = [Date.now(), tailLines(job, 3).filter((l) => l.trim()).at(-1)?.trim() ?? '']
492
+ return `running ${clip(cmd, 50)}${last ? ` › ${clip(last, 60)}` : ''}`
493
+ })
484
494
  await waitFor(job, secs * 1000, signal)
485
495
  s.ui.stopSpin()
486
496
  if (!job.exited) {
@@ -496,7 +506,16 @@ export async function runConfirmed(s, cmd, signal, background = false, wait) {
496
506
  const left = keepLeftovers(job) // `server &`: kept running, as a background command
497
507
  if (!left) removeJob(job) // done: not one of the background list
498
508
  log('command', `${cmd} → exit ${job.code} in ${job.ended - job.started}ms\n${output}`)
499
- s.ui.result(`exit ${job.code}`)
509
+ let lines = 0
510
+ try {
511
+ lines = fs.readFileSync(job.file, 'utf8').split(/\r?\n|\r/).filter((l) => l.trim()).length
512
+ } catch {}
513
+ s.ui.result(`exit ${job.code}${lines ? ` · ${lines} line${lines === 1 ? '' : 's'}` : ''}`)
514
+ // failed: its last lines under it (what went wrong, usually), aligned with the result's text
515
+ // why it failed: the last error line and what follows it (a stack's end says nothing), else the last lines
516
+ const tail = job.code !== 0 ? tailLines(job, 40).filter((x) => x.trim()) : []
517
+ const at = tail.findLastIndex((l) => /\b(error|exception|failed|fail|assert\w*|cannot|not found|denied)\b/i.test(l))
518
+ 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))}`)
500
519
  const changed = changesSince(s, before)
501
520
  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 })}` : ''}`
502
521
  }
@@ -605,7 +624,7 @@ export const TOOL_DEFS = [
605
624
  { name: 'todo', description: prompt('agent/tool-todo'), parameters: obj({ todos: { type: 'array', items: obj({ content: str, status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] }, parallel: { type: 'boolean' }, model: str, files: { type: 'array', items: str } }, ['content', 'status']) } }, ['todos']) },
606
625
  { name: 'web_search', description: prompt('agent/tool-web_search'), parameters: obj({ query: str, fresh: { type: 'boolean' } }, ['query']) },
607
626
  { name: 'web_fetch', description: prompt('agent/tool-web_fetch'), parameters: obj({ url: str, look_for: str, start: int }, ['url']) },
608
- { name: 'ask_user', description: prompt('agent/tool-ask_user'), parameters: obj({ question: str, options: { type: 'array', items: str }, multiple: { type: 'boolean' }, emphasis: { type: 'boolean' } }, ['question']) },
627
+ { name: 'ask_user', description: 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)
609
628
  ]
610
629
 
611
630
  // Plan mode (permission "plan"): looking around is fine, changing things isn't. Edits are refused,
@@ -617,13 +636,13 @@ const READ_ONLY = /^(cd|ls|cat|head|tail|wc|grep|egrep|rg|find|fd|tree|pwd|file|
617
636
  function outsideNote(root, cmd) {
618
637
  const dirs = [...cmd.matchAll(/(?:^|&&|;|\|\|)\s*cd\s+("[^"]+"|'[^']+'|\S+)/g)].map((m) => m[1].replace(/^["']|["']$/g, '').replace(/^~(?=\/|$)/, os.homedir()))
619
638
  const out = dirs.map((d) => path.resolve(root, d)).find((d) => d !== root && !d.startsWith(root + path.sep) && !readableOutside(d))
620
- return out ? `\n\n${prompt('agent/outside-project', { dir: out, root })}` : ''
639
+ return out ? `\n\n${prompt('agent/outside-project', { dir: out, root, wide: false })}` : ''
621
640
  }
622
641
 
623
642
  export function readOnlyCommand(cmd) {
624
643
  const c = String(cmd).trim()
625
- if (/[>`]|\$\(|\b(sudo|rm|mv|cp|tee|chmod|chown|dd|truncate|mkdir|touch|ln)\b|-delete\b|-exec|-ok\b|sed\s+-i|\bsort\b.*\s-o/.test(c)) return false // writes, or runs something else
626
- return c.split(/\s*(?:&&|\|\||;|\|)\s*/).every((part) => READ_ONLY.test(part))
644
+ 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)
645
+ return c.split(/\s*(?:&&|\|\||[;|&\n])\s*/).every((part) => READ_ONLY.test(part)) // `a & b`, a new line: each its own command
627
646
  }
628
647
 
629
648
  // MCP servers' tools as the model sees them: one tool, mcp, whose description lists every server's
@@ -667,20 +686,20 @@ export function extraTools(s) {
667
686
  if (s.memory) {
668
687
  out.push({
669
688
  name: 'memory',
670
- description: prompt('agent/tool-memory'),
689
+ description: prompt('agent/tool-memory', { tags: s.memory.tagSummary() || '(none yet)' }),
671
690
  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']),
672
691
  })
673
692
  }
674
- const forModel = [...(s.skills?.values() ?? [])].filter((k) => k.use === 'model' || k.use === 'both') // "use: me" skills cost nothing here; "always" ones are in the system prompt
693
+ 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
675
694
  if (forModel.length) {
676
695
  const skills = forModel.map((k) => `${k.name}: ${k.description}`).join('\n')
677
- out.push({ name: 'skill', description: prompt('agent/tool-skill', { skills }), parameters: obj({ name: str }, ['name']) })
696
+ out.push({ name: 'skill', description: prompt('agent/tool-skill', { skills }), parameters: obj({ name: str, file: str }, ['name']) })
678
697
  }
679
698
  if (!s.isSub && s.subagent) {
680
699
  const team = s.team?.() ?? []
681
- const model = { type: 'string', description: prompt(s.orchestrating ? 'agent/tool-hand-model' : 'agent/tool-agent-model') }
682
- const images = { type: 'array', items: str, description: prompt('agent/tool-agent-images') }
683
- out.push({ name: 'agent', description: prompt(s.orchestrating ? 'agent/tool-hand' : 'agent/tool-agent'), parameters: obj({ description: str, prompt: str, ...(team.length && { model, images }) }, ['description', 'prompt']) })
700
+ const model = { type: 'string', description: '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.' }
701
+ const images = { type: 'array', items: str, description: 'Image paths or URLs for the helper to look at. Needs a model that sees images.' }
702
+ out.push({ name: 'agent', description: prompt('agent/tool-agent'), parameters: obj({ description: str, prompt: str, ...(team.length && { model, images }) }, ['description', 'prompt']) })
684
703
  }
685
704
  return [...out, ...(s.director && !s.appendSystem ? s.director.toolDefs(s) : [])] // manage (director.js); not when a program gives the instructions (--append-system-prompt)
686
705
  }
@@ -688,6 +707,16 @@ export function extraTools(s) {
688
707
  // todo: the model's checklist for this message, shown to the user each time it changes.
689
708
  // Lenient: the list as JSON text, plain strings for items, "done" for completed.
690
709
  const MARK = { pending: '☐', in_progress: '◐', completed: '☑' }
710
+ // In the conversation: the whole plan when it's new (or its steps changed), else only the steps whose
711
+ // status changed, on one line; the whole of it stays in sight under the spinner (full screen).
712
+ function showTodos(s, before, todos) {
713
+ const paint = { pending: c.muted, in_progress: (x) => c.info(c.bold(x)), completed: (x) => c.faint(x) }
714
+ const item = (t) => paint[t.status](`${MARK[t.status]} ${t.content}`)
715
+ const same = s.ui.full && before?.length === todos.length && before.every((t, i) => t.content === todos[i].content)
716
+ if (!same) return s.ui.print(todos.map((t) => ` ${item(t)}`).join('\n') || c.faint(' (todo list cleared)'))
717
+ const moved = todos.filter((t, i) => t.status !== before[i].status)
718
+ if (moved.length) s.ui.print(` ${moved.map(item).join(c.faint(' · '))}`)
719
+ }
691
720
  async function todoTool(s, args, signal, id) {
692
721
  let list = args.todos ?? args.items ?? args
693
722
  if (typeof list === 'string') {
@@ -702,10 +731,9 @@ async function todoTool(s, args, signal, id) {
702
731
  .map((t) => (typeof t === 'string' ? { content: t, status: 'pending' } : { content: String(t?.content ?? t?.task ?? t?.title ?? ''), status: String(t?.status ?? 'pending'), ...(t?.model && { model: String(t.model) }), ...((t?.parallel === true || t?.parallel === 'true') && { parallel: true }), ...([t?.files ?? []].flat().filter(Boolean).length && { files: [t.files].flat().map(String) }) }))
703
732
  .filter((t) => t.content.trim())
704
733
  .map((t) => ({ ...t, status: /done|complete/i.test(t.status) ? 'completed' : /progress|doing|active/i.test(t.status) ? 'in_progress' : 'pending' }))
734
+ showTodos(s, s.chat.todos, todos)
705
735
  s.chat.todos = todos
706
736
  s.todoTouched = true
707
- const paint = { pending: c.muted, in_progress: (x) => c.info(c.bold(x)), completed: (x) => c.faint(x) }
708
- s.ui.print(todos.map((t) => ` ${paint[t.status](`${MARK[t.status]} ${t.content}`)}`).join('\n') || c.faint(' (todo list cleared)'))
709
737
  const parts = await runParts(s, todos, signal, id)
710
738
  const done = todos.filter((t) => t.status === 'completed').length
711
739
  const next = todos.find((t) => t.status !== 'completed')
@@ -713,7 +741,11 @@ async function todoTool(s, args, signal, id) {
713
741
  const open = todos.filter((t) => t.status === 'pending')
714
742
  const askSplit = !parts && !s.isSub && !s.splitAsked && open.length >= 3 && !todos.some((t) => t.parallel || t.model) && s.subagent && s.team?.().length && s.ui.permission !== 'plan'
715
743
  if (askSplit) s.splitAsked = true
716
- return `Todo list saved: ${done} of ${todos.length} done.${next ? ` Next: ${next.content}` : ''}${parts ? `\n\n${parts}` : ''}${askSplit ? `\n\n${prompt('agent/split-check')}` : ''}`
744
+ // a plan of a few steps made without looking anything up: asked once a message whether it uses something to read up on
745
+ const askResearch = !parts && !s.isSub && !s.researchAsked && !s.lookedUp && !s.research?.lookedUp && open.length >= 2
746
+ if (askResearch) s.researchAsked = true
747
+ const check = askSplit || askResearch ? `\n\n${prompt('agent/plan-check', { split: askSplit, research: askResearch })}` : ''
748
+ return `Todo list saved: ${done} of ${todos.length} done.${next ? ` Next: ${next.content}` : ''}${parts ? `\n\n${parts}` : ''}${check}`
717
749
  }
718
750
 
719
751
  // The plan's parts marked parallel (or given to another model): each started at once as a helper
@@ -727,6 +759,7 @@ async function runParts(s, todos, signal, id) {
727
759
  const known = (m) => yours.some((y) => `${y.provider} ${y.model}` === m || y.model === m || m.endsWith(` ${y.model}`))
728
760
  const unknown = [...new Set(parts.filter((t) => t.model && !known(t.model)).map((t) => t.model))]
729
761
  for (const t of parts) if (t.model && !known(t.model)) delete t.model
762
+ const shown = todos.map((t) => ({ ...t })) // as printed: after the parts, what they changed
730
763
  for (const t of parts) t.status = 'in_progress'
731
764
  log('parts', parts.map((t) => `${t.content}${t.model ? ` (${t.model})` : ''}${t.files ? ` [${t.files.join(', ')}]` : ''}`))
732
765
  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(' · ')}`)
@@ -747,46 +780,115 @@ async function runParts(s, todos, signal, id) {
747
780
  }),
748
781
  )
749
782
  s.chat.todos = todos
750
- const paint = { pending: c.muted, in_progress: (x) => c.info(c.bold(x)), completed: (x) => c.faint(x) }
751
- s.ui.print(todos.map((t) => ` ${paint[t.status](`${MARK[t.status]} ${t.content}`)}`).join('\n'))
783
+ showTodos(s, shown, todos)
752
784
  return prompt('agent/parts-done', { reports: reports.join('\n\n'), unknown: unknown.join(', '), models: yours.map((y) => `${y.provider} ${y.model}`).join(', ') })
753
785
  }
754
786
 
755
- // ask_user: a question for the user mid-task, with choices (and their own answer) or free text.
787
+ // ask_user: questions for the user mid-task, each with choices (and their own answer); several are
788
+ // tabs in one dialog (←/→ between them, then Send). Nobody answers for ASK_WAIT seconds (each key
789
+ // starts the wait again): the recommended ones, the first of each, are taken for what's unanswered.
790
+ const ASK_WAIT = 30
791
+ const listOf = (v) => {
792
+ if (typeof v !== 'string') return [v ?? []].flat()
793
+ try {
794
+ return [JSON.parse(v)].flat()
795
+ } catch {
796
+ return v.split('\n')
797
+ }
798
+ }
756
799
  async function askUser(s, args) {
757
- const question = String(args.question ?? '').trim()
758
- if (!question) return 'error: ask_user needs "question"'
759
- if (s.ui.noUser) return prompt('agent/ask-nobody')
760
- let options = args.options ?? []
761
- if (typeof options === 'string') {
762
- try {
763
- options = JSON.parse(options)
764
- } catch {
765
- options = options.split('\n')
766
- }
800
+ const qs = listOf(args.questions ?? [args]).map((q) => ({
801
+ question: String(q?.question ?? '').trim(),
802
+ header: String(q?.header ?? '').trim(),
803
+ multi: q?.multiple === true || q?.multiple === 'true',
804
+ emphasis: q?.emphasis === true || q?.emphasis === 'true',
805
+ items: listOf(q?.options).map((o) => (typeof o === 'string' ? { label: o.trim() } : { label: String(o?.label ?? o?.value ?? '').trim(), desc: o?.description })).filter((o) => o.label),
806
+ }))
807
+ if (!qs.length || qs.some((q) => !q.question)) return 'error: ask_user needs "question" (or "questions", each with its "question")'
808
+ if (s.ui.noUser || s.isSub) return prompt('agent/no-answer')
809
+ // always a recommended answer (the first option): taken when nobody answers (ASK_WAIT seconds without a key)
810
+ if (qs.some((q) => !q.items.length)) return 'error: ask_user needs options for every question: 2-4 short answers, your recommended one first (the user can still type their own)'
811
+ s.askedUser = true // asked through the dialog this message (not as text: see askedInText)
812
+ for (const q of qs) {
813
+ q.items[0].desc = ['recommended', q.items[0].desc].filter(Boolean).join(' · ')
814
+ q.own = { label: 'Something else', desc: 'type your own answer', own: true }
767
815
  }
768
- const items = [options].flat().map((o) => (typeof o === 'string' ? { label: o.trim() } : { label: String(o?.label ?? o?.value ?? '').trim(), desc: o?.description })).filter((o) => o.label)
769
816
  s.ui.stopSpin()
770
- let answer
771
- if (items.length) {
772
- const got = [await s.ui.pick(question, [...items, { label: 'Something else', desc: 'type your own answer', own: true }], { multi: Boolean(args.multiple) })].flat().filter(Boolean)
773
- const own = got.some((x) => x.own) ? await s.ui.ask(`${c.bold('Your answer')} ${c.dim('›')} `) : ''
774
- answer = [...got.filter((x) => !x.own).map((x) => x.label), own?.trim()].filter(Boolean).join(', ')
775
- } else answer = (await s.ui.ask(`${c.yellow('?')} ${c.bold(question)} `))?.trim()
776
- log('ask', question, answer)
817
+ const tabbed = qs.length > 1 && s.ui.full
818
+ const said = qs.map(() => null) // each: { got: [items], text: own answer, auto }
819
+ const answerOf = (a) => (a ? [...a.got.filter((x) => !x.own).map((x) => x.label), a.text].filter(Boolean).join(', ') : '')
820
+ const tabs = (at) =>
821
+ [...qs.map((q, i) => `${said[i] ? '✓' : '○'} ${q.header || clip(q.question, 18)}`), ' Send']
822
+ .map((t, i) => (i === at ? c.select(c.bright(c.bold(` ${t} `))) : said[i] ? c.text(` ${t} `) : c.faint(` ${t} `))) // its own color on the highlight: the terminal's may not show on it (light theme, dark terminal)
823
+ .join(c.ghost('│'))
824
+ let auto = false
825
+ for (let i = 0; i < qs.length || tabbed; ) {
826
+ if (i === qs.length) {
827
+ // the last tab: every answer, sent with Enter (or after ASK_WAIT seconds)
828
+ const body = qs.map((q, j) => `${q.question} ${c.faint('›')} ${answerOf(said[j]) || `${q.items[0].label} ${c.faint('(recommended)')}`}`).join('\n')
829
+ const send = { label: 'Send answers', desc: 'or ← to change one' }
830
+ const got = await s.ui.pick('Send these answers?', [send], { body, tabs: tabs(i), nav: true, quiet: true, auto: { item: send, secs: ASK_WAIT, say: 'your answers are sent' } })
831
+ if (got?.nav) {
832
+ i = Math.min(qs.length, Math.max(0, i + got.nav)) // → on Send: stays there
833
+ continue
834
+ }
835
+ if (!got) return prompt('agent/no-answer')
836
+ auto = s.ui.autoPicked
837
+ break
838
+ }
839
+ const q = qs[i]
840
+ const items = [...q.items, q.own]
841
+ const typed = Boolean(q.own.text?.trim()) // typed in its row, then off to another tab without Enter: that row again
842
+ for (const x of items) x.current = typed ? x === q.own : Boolean(said[i]?.got.includes(x)) // back on a tab: its answer selected
843
+ const got = await s.ui.pick(q.question, items, { multi: q.multi, tabs: tabbed ? tabs(i) : '', nav: tabbed, quiet: s.ui.full, auto: { item: q.items[0], secs: ASK_WAIT, say: tabbed ? 'the recommended answers are sent' : 'the recommended answer is chosen' } })
844
+ if (got?.nav) {
845
+ i = Math.min(qs.length, Math.max(0, i + got.nav))
846
+ continue
847
+ }
848
+ if (!got) return prompt('agent/no-answer') // Esc: the whole dialog
849
+ const list = [got].flat().filter(Boolean)
850
+ let text = ''
851
+ if (list.some((x) => x.own)) {
852
+ // typed in its row (full screen); without full screen, asked for now
853
+ text = q.own.text?.trim() || ((await s.ui.ask(`${c.bold('Your answer')} ${c.dim('›')} `, { initial: said[i]?.text ?? '' }))?.trim() ?? '')
854
+ Object.assign(q.own, { text, desc: text ? `› ${text}` : 'type your own answer' })
855
+ if (!text && list.length === 1) continue // nothing typed: the same question again
856
+ }
857
+ if (s.ui.autoPicked) {
858
+ auto = s.ui.autoPicked
859
+ if (auto === 'theirs' || !said[i]) said[i] = { got: list, text, auto: auto !== 'theirs' } // what's ticked or typed is theirs; answered before (back on its tab): theirs stays
860
+ break
861
+ }
862
+ said[i] = { got: list, text }
863
+ i++
864
+ }
865
+ // nobody there: what's unanswered gets the recommended one
866
+ for (const [i, q] of qs.entries()) if (!answerOf(said[i])) said[i] = { got: [q.items[0]], text: '', auto: true }
867
+ const answers = qs.map((q, i) => answerOf(said[i]))
868
+ for (const [i, q] of qs.entries()) log('ask', q.question, answers[i])
869
+ if (s.ui.full) s.ui.print(qs.map((q, i) => ` ${c.dim(q.question)} ${c.dim('›')} ${c.bright(answers[i])}${said[i].auto ? c.faint(' (recommended, no answer in time)') : ''}`).join('\n')) // each question with its answer
777
870
  // how the user wants the work done: kept with the conversation (a "continue" later still knows), the
778
871
  // first such question of a new message starts them afresh; steers the checks and reviews
779
- if (args.emphasis && answer && s.chat) {
872
+ for (const [i, q] of qs.entries()) {
873
+ if (!q.emphasis || !answers[i] || !s.chat) continue
780
874
  if (!s.choicesFresh) s.chat.choices = []
781
875
  s.choicesFresh = true
782
- s.chat.choices.push(`${question} → ${answer}`)
876
+ s.chat.choices.push(`${q.question} → ${answers[i]}`)
877
+ }
878
+ const why = auto === 'nobody' ? "nobody can answer (the input isn't a terminal)" : `no answer in ${ASK_WAIT} seconds`
879
+ if (qs.length === 1) {
880
+ if (auto === 'theirs') return `Not sent within ${ASK_WAIT} seconds, so what the user had chosen was taken: ${answers[0]}`
881
+ if (auto) return `${why[0].toUpperCase()}${why.slice(1)}, so your recommended one was taken: ${answers[0]}`
882
+ return `The user answered: ${answers[0]}`
783
883
  }
784
- return answer ? `The user answered: ${answer}` : prompt('agent/ask-no-answer')
884
+ return `The user answered:\n${qs.map((q, i) => `- ${q.question} → ${answers[i]}${said[i].auto ? ` (${why}: your recommended one)` : ''}`).join('\n')}`
785
885
  }
786
886
 
787
887
  async function webTool(s, name, args, signal) {
788
888
  const what = name === 'web_search' ? String(args.query ?? '') : String(args.url ?? '')
789
889
  if (!what.trim()) return `error: ${name} needs ${name === 'web_search' ? '"query"' : '"url"'}`
890
+ s.lookedUp = true // looked something up this message (the plan check doesn't ask then)
891
+ if (s.research) s.research.lookedUp = true // this message's research, shared with its helpers: theirs count too
790
892
  const ok = await s.ui.confirm(name === 'web_search' ? `Search the web for ${c.bold(what)}?` : `Fetch ${c.bold(what)}?`, 'read')
791
893
  if (ok !== true) return declined(s, ok, 'The user declined this.')
792
894
  // what this message's research is for: the page's look_for, else the last search, else the task
@@ -999,6 +1101,7 @@ async function callMcp(s, server, tool, a, signal) {
999
1101
  // a tool its server marks read-only isn't asked about (reading isn't, in any mode; headless
1000
1102
  // declines what it would ask, so a browser's snapshot must not be); any other like a command
1001
1103
  if (!def?.annotations?.readOnlyHint) {
1104
+ if (s.ui.permission === 'plan') return prompt('agent/plan-refused', { command: false }) // might change something
1002
1105
  const ok = await s.ui.confirm(`Use ${server.name} → ${tool}?`, 'command')
1003
1106
  if (ok !== true) return declined(s, ok, 'The user declined this call.')
1004
1107
  }
@@ -1043,7 +1146,7 @@ async function callMcp(s, server, tool, a, signal) {
1043
1146
  }
1044
1147
  }
1045
1148
  note = `\n(${s.pendingImages.length - shown} image(s): shown to you in the next message${left.length ? `; not shown: ${left.join('; ')}` : ''})`
1046
- } else if (files.length && s.team?.().some((t) => t.images)) note = `\n${prompt('agent/images-unseen', { files: files.join('\n') })}`
1149
+ } else if (files.length && s.team?.().some((t) => t.images)) note = `\n${prompt('agent/tool-images', { files: files.join('\n'), unseen: true })}`
1047
1150
  else if (files.length) note = `\n(${files.length} image(s) not shown: this model can't see images)`
1048
1151
  const mendNote = mended.fixed.length ? `\n(HeartCode corrected the arguments: ${mended.fixed.join('; ')}. Use them that way next time.)` : ''
1049
1152
  return `${r.isError ? 'error: ' : ''}${text || '(no text)'}${note}${mendNote}`
@@ -1268,6 +1371,25 @@ export const runningCall = new AsyncLocalStorage()
1268
1371
  // A tool's result that is HeartCode's error, not the tool's output (command output starts with
1269
1372
  // "exit code", a file's with line numbers).
1270
1373
  export const failed = (out) => /^error: /.test(String(out))
1374
+ // A call that wasn't done (held for a plan, plan mode, a hook, another part's file, declined, already
1375
+ // made): why, in a few words, for the ⎿ line under it; '' when it ran. Matched on the built-in prompts' starts.
1376
+ const REFUSALS = [
1377
+ [/^NOT DONE: nothing was written/, 'not done: no plan yet'],
1378
+ [/^Not done: plan mode/, 'not done: plan mode'],
1379
+ [/^Not run: in plan mode/, 'not run: plan mode'],
1380
+ [/^Not run: it searches/, 'not run: searches outside the project'],
1381
+ [/^Not done: the user's hook blocked it: (.*)/, (m) => `blocked by a hook: ${clip(m[1], 80)}`],
1382
+ [/^Not changed: \S+ belongs to another part/, "not changed: another part's file"],
1383
+ [/^The user (declined|rejected)/, 'declined'],
1384
+ [/^\(Already done, and nothing changed/, 'not run again: nothing changed since'],
1385
+ ]
1386
+ export function refusal(out) {
1387
+ for (const [re, why] of REFUSALS) {
1388
+ const m = re.exec(String(out))
1389
+ if (m) return typeof why === 'function' ? why(m) : why
1390
+ }
1391
+ return ''
1392
+ }
1271
1393
 
1272
1394
  // id: the tool call's (a helper's steps are sent as its, for other apps to show under it)
1273
1395
  export async function runTool(name, args, s, signal, id) {
@@ -1278,12 +1400,16 @@ async function toolRun(name, args, s, signal, id) {
1278
1400
  // hooks see an MCP tool by its own name (mcp__server__tool), also when called through "mcp"
1279
1401
  const hookName = name === 'mcp' && args?.server && args?.tool ? mcpName(String(args.server), String(args.tool)) : name
1280
1402
  const pre = await runHooks(s, 'PreToolUse', { tool_name: hookName, tool_input: args }, signal)
1281
- if (pre.block) return prompt('agent/hook-blocked-tool', { reason: pre.block })
1282
- const notMine = s.ownFiles && partPaths(name, args).find((f) => !s.ownFiles.includes(path.resolve(s.root, f)))
1283
- if (notMine) return prompt('agent/part-files', { file: notMine, files: s.ownFiles.map((f) => path.relative(s.root, f)).join(', ') })
1403
+ const notMine = !pre.block && s.ownFiles && partPaths(name, args).find((f) => !s.ownFiles.includes(path.resolve(s.root, f)))
1404
+ 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
1405
+ if (stop && name === 'run_command') {
1406
+ s.ui.step('run', String(args?.command ?? '')) // a command's lines are shown where it runs, which this one never reaches
1407
+ s.ui.result(refusal(stop))
1408
+ }
1409
+ if (stop) return stop
1284
1410
  let out = await tool(name, args, s, signal, id)
1285
1411
  const post = await runHooks(s, 'PostToolUse', { tool_name: hookName, tool_input: args, tool_response: out }, signal)
1286
- if (post.block) out += `\n\n${prompt('agent/hook-after-tool', { reason: post.block })}`
1412
+ if (post.block) out += `\n\n${prompt('agent/hook', { reason: post.block, after: true })}`
1287
1413
  log('tool', `${name} result:`, clip(out, 4000))
1288
1414
  return out
1289
1415
  }
@@ -1320,9 +1446,7 @@ function mcpTarget(s, name) {
1320
1446
 
1321
1447
  // Tools the caller allowed (--allowedTools) or took away (--disallowedTools); all by default. An
1322
1448
  // MCP tool goes by its own name, its server's (mcp__server, as in Claude Code) or "mcp" (all of them).
1323
- // An orchestrator: only handing work out (and asking the user).
1324
1449
  export function allowed(s, name) {
1325
- if (s.orchestrating && name !== 'agent' && name !== 'ask_user') return false
1326
1450
  const names = name.startsWith('mcp__') ? [name, name.split('__').slice(0, 2).join('__'), 'mcp'] : [name]
1327
1451
  if (names.some((n) => s.denyTools?.has(n))) return false
1328
1452
  if (!s.allowTools) return true
@@ -1334,7 +1458,7 @@ async function tool(name, args, s, signal, id) {
1334
1458
  try {
1335
1459
  const { root } = s
1336
1460
  if (s.ui.permission === 'plan') {
1337
- if (PLAN_HIDDEN.has(name) || name === 'append_file' || name === 'manage' && args.action !== 'list' && args.action !== 'show' && args.action !== 'help') return prompt('agent/plan-refused')
1461
+ if (PLAN_HIDDEN.has(name) || name === 'append_file' || name === 'manage' && args.action !== 'list' && args.action !== 'show' && args.action !== 'help') return prompt('agent/plan-refused', { command: false })
1338
1462
  }
1339
1463
  switch (name) {
1340
1464
  case 'read_file':
@@ -1375,7 +1499,7 @@ async function tool(name, args, s, signal, id) {
1375
1499
  return writeResult(rel, res) + (res.formatted ? `\nNow:\n${excerpt(res.text, res.ops)}` : '') // what it wrote isn't what's there now
1376
1500
  }
1377
1501
  case 'run_command':
1378
- if (/^\s*apply_patch\b[\s\S]*\*\*\* Begin Patch/.test(String(args.command ?? ''))) return await applyPatch(s, args.command) // apply_patch <<'EOF' … as Codex runs it
1502
+ if (/^\s*apply_patch\b[\s\S]*\*\*\* Begin Patch/.test(String(args.command ?? ''))) return !allowed(s, 'apply_patch') ? 'error: the tool apply_patch is not allowed here' : await applyPatch(s, args.command) // apply_patch <<'EOF' … as Codex runs it
1379
1503
  return (await runConfirmed(s, String(args.command ?? ''), signal, args.background === true || args.background === 'true', args.wait)) + outsideNote(root, String(args.command ?? ''))
1380
1504
  case 'background':
1381
1505
  return await backgroundTool(s, args, signal)
@@ -1391,12 +1515,17 @@ async function tool(name, args, s, signal, id) {
1391
1515
  case 'web_fetch':
1392
1516
  return await webTool(s, name, args, signal)
1393
1517
  case 'agent':
1518
+ if (s.isSub) return 'error: a helper can\'t start helpers. Do the job yourself.' // hidden from helpers; a call anyway would nest without end
1394
1519
  return await s.subagent(args, signal, id)
1395
1520
  case 'ask_user':
1396
1521
  return await askUser(s, args)
1397
1522
  case 'skill': {
1398
1523
  const k = s.skills?.get(String(args.name ?? ''))
1399
- return k && k.use !== 'me' ? fillArgs(k.body, '') : `error: no skill "${args.name}". Skills: ${[...(s.skills?.values() ?? [])].filter((x) => x.use !== 'me').map((x) => x.name).join(', ') || 'none'}`
1524
+ 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'}`
1525
+ if (args.file) return readSkillFile(k, String(args.file))
1526
+ const files = skillFiles(k)
1527
+ const loaded = (k.load ?? []).map((f) => `\n\n--- ${f} ---\n${readSkillFile(k, f)}`).join('')
1528
+ return fillArgs(k.body, '') + loaded + (files.length ? `\n\n${prompt('agent/skill-files', { name: k.name, files: files.join('\n') })}` : '')
1400
1529
  }
1401
1530
  default: {
1402
1531
  const m = mcpTarget(s, name)