heartcode 0.1.54 → 0.1.57

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/settings.js CHANGED
@@ -159,7 +159,7 @@ function forgetList(...names) {
159
159
 
160
160
  export function startSettings({ cfg, apply = () => {}, port = 0, root = process.cwd(), onLoginMcp = null } = {}) {
161
161
  let importCache = [] // the last /api/imports listing, so /api/imports/run can execute by id
162
- const token = crypto.randomBytes(24).toString('hex')
162
+ const token = crypto.randomBytes(16).toString('hex') // short enough for the link to stay on one row of an 80-column dialog, to select it
163
163
  const changed = (what) => {
164
164
  if (what === 'prompts') reloadPrompts() // this page's own Tests use them too (heart settings has no HeartCode to apply them)
165
165
  try {
@@ -1050,7 +1050,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1050
1050
  server.listen(port, '0.0.0.0', () => {
1051
1051
  const at = (host) => `http://${host}:${server.address().port}/?t=${token}`
1052
1052
  const local = at('127.0.0.1') // for a browser on this machine
1053
- const url = at(addresses()[0] ?? '127.0.0.1') // its network address when it has one: works from another device too
1053
+ const ssh = process.env.SSH_CONNECTION?.split(' ')[2] // over SSH: the address you reached this machine at
1054
+ const url = at((ssh?.includes(':') ? `[${ssh}]` : ssh) ?? addresses()[0] ?? '127.0.0.1') // else its network address when it has one: works from another device too
1054
1055
  log('web', `settings page at ${new URL(url).host}`)
1055
1056
  // models.dev's list (its sizes for your models, whether their providers' lists are on or not):
1056
1057
  // loaded now, and your models' lines brought up to date when it's in
package/src/tabs.js CHANGED
@@ -74,6 +74,7 @@ export class Tabs {
74
74
  this.onShow?.(tab)
75
75
  this.onChange?.()
76
76
  tab.ui.wrapped = []
77
+ tab.ui.resumeAuto()
77
78
  tab.ui.render()
78
79
  }
79
80
 
@@ -137,8 +138,11 @@ export class Tabs {
137
138
  mid += line('│') + label + line('│') + ' '
138
139
  bottom += (on ? c.brand(`╯${' '.repeat(w)}╰`) : c.ghost(`┴${'─'.repeat(w)}┴`)) + c.ghost('─')
139
140
  })
140
- const hint = this.list.length > 1 ? 'Alt+T open a tab · Alt+W close this one · Alt+N/P switch tabs' : 'Alt+T open a new tab'
141
- mid += ` ${c.faint(hint)}`
141
+ // the keys that fit whole, the rest left out (never one cut in the middle)
142
+ const hints = this.list.length > 1 ? ['Alt+T open a tab', 'Alt+W close this one', 'Alt+N/P switch tabs'] : ['Alt+T open a new tab']
143
+ let hint = ''
144
+ for (const h of hints) if (width(mid.replace(/\x1b\[[0-9;]*m/g, '')) + 1 + width(hint ? `${hint} · ${h}` : h) <= cols - 1) hint = hint ? `${hint} · ${h}` : h
145
+ if (hint) mid += ` ${c.faint(hint)}`
142
146
  bottom += c.ghost('─'.repeat(Math.max(0, cols - width(bottom.replace(/\x1b\[[0-9;]*m/g, '')))))
143
147
  return [top, mid, bottom]
144
148
  }
package/src/tools.js CHANGED
@@ -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
 
@@ -388,6 +388,7 @@ const PLACEHOLDER = /(\.\.\.|…)\s*(rest|existing|remaining|unchanged|other)|re
388
388
  export async function proposeWrite(s, rel, old, next) {
389
389
  if (old === next) return { status: 'unchanged' }
390
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"')
@@ -476,11 +477,20 @@ export async function runConfirmed(s, cmd, signal, background = false, wait) {
476
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,
@@ -622,8 +641,8 @@ function outsideNote(root, cmd) {
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
@@ -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')
@@ -714,7 +742,7 @@ async function todoTool(s, args, signal, id) {
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
744
  // a plan of a few steps made without looking anything up: asked once a message whether it uses something to read up on
717
- const askResearch = !parts && !s.isSub && !s.researchAsked && !s.lookedUp && open.length >= 2
745
+ const askResearch = !parts && !s.isSub && !s.researchAsked && !s.lookedUp && !s.research?.lookedUp && open.length >= 2
718
746
  if (askResearch) s.researchAsked = true
719
747
  const check = askSplit || askResearch ? `\n\n${prompt('agent/plan-check', { split: askSplit, research: askResearch })}` : ''
720
748
  return `Todo list saved: ${done} of ${todos.length} done.${next ? ` Next: ${next.content}` : ''}${parts ? `\n\n${parts}` : ''}${check}`
@@ -731,6 +759,7 @@ async function runParts(s, todos, signal, id) {
731
759
  const known = (m) => yours.some((y) => `${y.provider} ${y.model}` === m || y.model === m || m.endsWith(` ${y.model}`))
732
760
  const unknown = [...new Set(parts.filter((t) => t.model && !known(t.model)).map((t) => t.model))]
733
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
734
763
  for (const t of parts) t.status = 'in_progress'
735
764
  log('parts', parts.map((t) => `${t.content}${t.model ? ` (${t.model})` : ''}${t.files ? ` [${t.files.join(', ')}]` : ''}`))
736
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(' · ')}`)
@@ -751,51 +780,115 @@ async function runParts(s, todos, signal, id) {
751
780
  }),
752
781
  )
753
782
  s.chat.todos = todos
754
- const paint = { pending: c.muted, in_progress: (x) => c.info(c.bold(x)), completed: (x) => c.faint(x) }
755
- s.ui.print(todos.map((t) => ` ${paint[t.status](`${MARK[t.status]} ${t.content}`)}`).join('\n'))
783
+ showTodos(s, shown, todos)
756
784
  return prompt('agent/parts-done', { reports: reports.join('\n\n'), unknown: unknown.join(', '), models: yours.map((y) => `${y.provider} ${y.model}`).join(', ') })
757
785
  }
758
786
 
759
- // ask_user: a question for the user mid-task, with choices (and their own answer). Nobody answers for
760
- // ASK_WAIT seconds (each key starts the wait again): the recommended one, the first, is taken.
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.
761
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
+ }
762
799
  async function askUser(s, args) {
763
- const question = String(args.question ?? '').trim()
764
- if (!question) return 'error: ask_user needs "question"'
765
- if (s.ui.noUser) return prompt('agent/no-answer')
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)'
766
811
  s.askedUser = true // asked through the dialog this message (not as text: see askedInText)
767
- let options = args.options ?? []
768
- if (typeof options === 'string') {
769
- try {
770
- options = JSON.parse(options)
771
- } catch {
772
- options = options.split('\n')
773
- }
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 }
774
815
  }
775
- 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)
776
- // always a recommended answer (the first option): taken when nobody answers (ASK_WAIT seconds without a key)
777
- if (!items.length) return 'error: ask_user needs options: 2-4 short answers, your recommended one first (the user can still type their own)'
778
- items[0].desc = ['recommended', items[0].desc].filter(Boolean).join(' · ')
779
816
  s.ui.stopSpin()
780
- const got = [await s.ui.pick(question, [...items, { label: 'Something else', desc: 'type your own answer', own: true }], { multi: Boolean(args.multiple), auto: { item: items[0], secs: ASK_WAIT } })].flat().filter(Boolean)
781
- const own = got.some((x) => x.own) ? await s.ui.ask(`${c.bold('Your answer')} ${c.dim('›')} `) : ''
782
- const answer = [...got.filter((x) => !x.own).map((x) => x.label), own?.trim()].filter(Boolean).join(', ')
783
- 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
784
870
  // how the user wants the work done: kept with the conversation (a "continue" later still knows), the
785
871
  // first such question of a new message starts them afresh; steers the checks and reviews
786
- if (args.emphasis && answer && s.chat) {
872
+ for (const [i, q] of qs.entries()) {
873
+ if (!q.emphasis || !answers[i] || !s.chat) continue
787
874
  if (!s.choicesFresh) s.chat.choices = []
788
875
  s.choicesFresh = true
789
- s.chat.choices.push(`${question} → ${answer}`)
876
+ s.chat.choices.push(`${q.question} → ${answers[i]}`)
790
877
  }
791
- if (s.ui.autoPicked) return `No answer in ${ASK_WAIT} seconds, so your recommended one was taken: ${answer}`
792
- return answer ? `The user answered: ${answer}` : prompt('agent/no-answer')
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]}`
883
+ }
884
+ return `The user answered:\n${qs.map((q, i) => `- ${q.question} → ${answers[i]}${said[i].auto ? ` (${why}: your recommended one)` : ''}`).join('\n')}`
793
885
  }
794
886
 
795
887
  async function webTool(s, name, args, signal) {
796
888
  const what = name === 'web_search' ? String(args.query ?? '') : String(args.url ?? '')
797
889
  if (!what.trim()) return `error: ${name} needs ${name === 'web_search' ? '"query"' : '"url"'}`
798
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
799
892
  const ok = await s.ui.confirm(name === 'web_search' ? `Search the web for ${c.bold(what)}?` : `Fetch ${c.bold(what)}?`, 'read')
800
893
  if (ok !== true) return declined(s, ok, 'The user declined this.')
801
894
  // what this message's research is for: the page's look_for, else the last search, else the task
@@ -1008,6 +1101,7 @@ async function callMcp(s, server, tool, a, signal) {
1008
1101
  // a tool its server marks read-only isn't asked about (reading isn't, in any mode; headless
1009
1102
  // declines what it would ask, so a browser's snapshot must not be); any other like a command
1010
1103
  if (!def?.annotations?.readOnlyHint) {
1104
+ if (s.ui.permission === 'plan') return prompt('agent/plan-refused', { command: false }) // might change something
1011
1105
  const ok = await s.ui.confirm(`Use ${server.name} → ${tool}?`, 'command')
1012
1106
  if (ok !== true) return declined(s, ok, 'The user declined this call.')
1013
1107
  }
@@ -1277,6 +1371,25 @@ export const runningCall = new AsyncLocalStorage()
1277
1371
  // A tool's result that is HeartCode's error, not the tool's output (command output starts with
1278
1372
  // "exit code", a file's with line numbers).
1279
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
+ }
1280
1393
 
1281
1394
  // id: the tool call's (a helper's steps are sent as its, for other apps to show under it)
1282
1395
  export async function runTool(name, args, s, signal, id) {
@@ -1287,9 +1400,13 @@ async function toolRun(name, args, s, signal, id) {
1287
1400
  // hooks see an MCP tool by its own name (mcp__server__tool), also when called through "mcp"
1288
1401
  const hookName = name === 'mcp' && args?.server && args?.tool ? mcpName(String(args.server), String(args.tool)) : name
1289
1402
  const pre = await runHooks(s, 'PreToolUse', { tool_name: hookName, tool_input: args }, signal)
1290
- if (pre.block) return prompt('agent/hook', { reason: pre.block, blocked: true })
1291
- const notMine = s.ownFiles && partPaths(name, args).find((f) => !s.ownFiles.includes(path.resolve(s.root, f)))
1292
- 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
1293
1410
  let out = await tool(name, args, s, signal, id)
1294
1411
  const post = await runHooks(s, 'PostToolUse', { tool_name: hookName, tool_input: args, tool_response: out }, signal)
1295
1412
  if (post.block) out += `\n\n${prompt('agent/hook', { reason: post.block, after: true })}`
@@ -1382,7 +1499,7 @@ async function tool(name, args, s, signal, id) {
1382
1499
  return writeResult(rel, res) + (res.formatted ? `\nNow:\n${excerpt(res.text, res.ops)}` : '') // what it wrote isn't what's there now
1383
1500
  }
1384
1501
  case 'run_command':
1385
- 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
1386
1503
  return (await runConfirmed(s, String(args.command ?? ''), signal, args.background === true || args.background === 'true', args.wait)) + outsideNote(root, String(args.command ?? ''))
1387
1504
  case 'background':
1388
1505
  return await backgroundTool(s, args, signal)
@@ -1398,6 +1515,7 @@ async function tool(name, args, s, signal, id) {
1398
1515
  case 'web_fetch':
1399
1516
  return await webTool(s, name, args, signal)
1400
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
1401
1519
  return await s.subagent(args, signal, id)
1402
1520
  case 'ask_user':
1403
1521
  return await askUser(s, args)