heartcode 0.1.44 → 0.1.54

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'
@@ -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,7 @@ 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
391
  const ops = diffLines(old, next ?? '')
392
392
  s.ui.print(renderDiff(ops, rel))
393
393
  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,12 +468,12 @@ export async function runConfirmed(s, cmd, signal, background = false, wait) {
468
468
  s.ui.step(background ? 'run in background' : 'run', cmd)
469
469
  if (s.ui.permission === 'plan' && !readOnlyCommand(cmd)) {
470
470
  s.ui.result('not run: plan mode')
471
- return prompt('agent/plan-refused-command')
471
+ return prompt('agent/plan-refused', { command: true })
472
472
  }
473
473
  if (searchesOutside(cmd, s.root)) {
474
474
  log('command', `refused (searches outside the project): ${cmd}`)
475
475
  s.ui.result('not run: searches outside the project')
476
- return prompt('agent/command-too-wide', { root: s.root })
476
+ return prompt('agent/outside-project', { root: s.root, wide: true })
477
477
  }
478
478
  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
479
  if (ok !== true) return declined(s, ok, 'The user declined to run this command.')
@@ -617,7 +617,7 @@ const READ_ONLY = /^(cd|ls|cat|head|tail|wc|grep|egrep|rg|find|fd|tree|pwd|file|
617
617
  function outsideNote(root, cmd) {
618
618
  const dirs = [...cmd.matchAll(/(?:^|&&|;|\|\|)\s*cd\s+("[^"]+"|'[^']+'|\S+)/g)].map((m) => m[1].replace(/^["']|["']$/g, '').replace(/^~(?=\/|$)/, os.homedir()))
619
619
  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 })}` : ''
620
+ return out ? `\n\n${prompt('agent/outside-project', { dir: out, root, wide: false })}` : ''
621
621
  }
622
622
 
623
623
  export function readOnlyCommand(cmd) {
@@ -667,20 +667,20 @@ export function extraTools(s) {
667
667
  if (s.memory) {
668
668
  out.push({
669
669
  name: 'memory',
670
- description: prompt('agent/tool-memory'),
670
+ description: prompt('agent/tool-memory', { tags: s.memory.tagSummary() || '(none yet)' }),
671
671
  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
672
  })
673
673
  }
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
674
+ 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
675
  if (forModel.length) {
676
676
  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']) })
677
+ out.push({ name: 'skill', description: prompt('agent/tool-skill', { skills }), parameters: obj({ name: str, file: str }, ['name']) })
678
678
  }
679
679
  if (!s.isSub && s.subagent) {
680
680
  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']) })
681
+ 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.' }
682
+ const images = { type: 'array', items: str, description: 'Image paths or URLs for the helper to look at. Needs a model that sees images.' }
683
+ out.push({ name: 'agent', description: prompt('agent/tool-agent'), parameters: obj({ description: str, prompt: str, ...(team.length && { model, images }) }, ['description', 'prompt']) })
684
684
  }
685
685
  return [...out, ...(s.director && !s.appendSystem ? s.director.toolDefs(s) : [])] // manage (director.js); not when a program gives the instructions (--append-system-prompt)
686
686
  }
@@ -713,7 +713,11 @@ async function todoTool(s, args, signal, id) {
713
713
  const open = todos.filter((t) => t.status === 'pending')
714
714
  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
715
  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')}` : ''}`
716
+ // 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
718
+ if (askResearch) s.researchAsked = true
719
+ const check = askSplit || askResearch ? `\n\n${prompt('agent/plan-check', { split: askSplit, research: askResearch })}` : ''
720
+ return `Todo list saved: ${done} of ${todos.length} done.${next ? ` Next: ${next.content}` : ''}${parts ? `\n\n${parts}` : ''}${check}`
717
721
  }
718
722
 
719
723
  // The plan's parts marked parallel (or given to another model): each started at once as a helper
@@ -752,11 +756,14 @@ async function runParts(s, todos, signal, id) {
752
756
  return prompt('agent/parts-done', { reports: reports.join('\n\n'), unknown: unknown.join(', '), models: yours.map((y) => `${y.provider} ${y.model}`).join(', ') })
753
757
  }
754
758
 
755
- // ask_user: a question for the user mid-task, with choices (and their own answer) or free text.
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.
761
+ const ASK_WAIT = 30
756
762
  async function askUser(s, args) {
757
763
  const question = String(args.question ?? '').trim()
758
764
  if (!question) return 'error: ask_user needs "question"'
759
- if (s.ui.noUser) return prompt('agent/ask-nobody')
765
+ if (s.ui.noUser) return prompt('agent/no-answer')
766
+ s.askedUser = true // asked through the dialog this message (not as text: see askedInText)
760
767
  let options = args.options ?? []
761
768
  if (typeof options === 'string') {
762
769
  try {
@@ -766,13 +773,13 @@ async function askUser(s, args) {
766
773
  }
767
774
  }
768
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(' · ')
769
779
  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()
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(', ')
776
783
  log('ask', question, answer)
777
784
  // how the user wants the work done: kept with the conversation (a "continue" later still knows), the
778
785
  // first such question of a new message starts them afresh; steers the checks and reviews
@@ -781,12 +788,14 @@ async function askUser(s, args) {
781
788
  s.choicesFresh = true
782
789
  s.chat.choices.push(`${question} → ${answer}`)
783
790
  }
784
- return answer ? `The user answered: ${answer}` : prompt('agent/ask-no-answer')
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')
785
793
  }
786
794
 
787
795
  async function webTool(s, name, args, signal) {
788
796
  const what = name === 'web_search' ? String(args.query ?? '') : String(args.url ?? '')
789
797
  if (!what.trim()) return `error: ${name} needs ${name === 'web_search' ? '"query"' : '"url"'}`
798
+ s.lookedUp = true // looked something up this message (the plan check doesn't ask then)
790
799
  const ok = await s.ui.confirm(name === 'web_search' ? `Search the web for ${c.bold(what)}?` : `Fetch ${c.bold(what)}?`, 'read')
791
800
  if (ok !== true) return declined(s, ok, 'The user declined this.')
792
801
  // what this message's research is for: the page's look_for, else the last search, else the task
@@ -1043,7 +1052,7 @@ async function callMcp(s, server, tool, a, signal) {
1043
1052
  }
1044
1053
  }
1045
1054
  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') })}`
1055
+ } else if (files.length && s.team?.().some((t) => t.images)) note = `\n${prompt('agent/tool-images', { files: files.join('\n'), unseen: true })}`
1047
1056
  else if (files.length) note = `\n(${files.length} image(s) not shown: this model can't see images)`
1048
1057
  const mendNote = mended.fixed.length ? `\n(HeartCode corrected the arguments: ${mended.fixed.join('; ')}. Use them that way next time.)` : ''
1049
1058
  return `${r.isError ? 'error: ' : ''}${text || '(no text)'}${note}${mendNote}`
@@ -1278,12 +1287,12 @@ async function toolRun(name, args, s, signal, id) {
1278
1287
  // hooks see an MCP tool by its own name (mcp__server__tool), also when called through "mcp"
1279
1288
  const hookName = name === 'mcp' && args?.server && args?.tool ? mcpName(String(args.server), String(args.tool)) : name
1280
1289
  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 })
1290
+ if (pre.block) return prompt('agent/hook', { reason: pre.block, blocked: true })
1282
1291
  const notMine = s.ownFiles && partPaths(name, args).find((f) => !s.ownFiles.includes(path.resolve(s.root, f)))
1283
1292
  if (notMine) return prompt('agent/part-files', { file: notMine, files: s.ownFiles.map((f) => path.relative(s.root, f)).join(', ') })
1284
1293
  let out = await tool(name, args, s, signal, id)
1285
1294
  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 })}`
1295
+ if (post.block) out += `\n\n${prompt('agent/hook', { reason: post.block, after: true })}`
1287
1296
  log('tool', `${name} result:`, clip(out, 4000))
1288
1297
  return out
1289
1298
  }
@@ -1320,9 +1329,7 @@ function mcpTarget(s, name) {
1320
1329
 
1321
1330
  // Tools the caller allowed (--allowedTools) or took away (--disallowedTools); all by default. An
1322
1331
  // 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
1332
  export function allowed(s, name) {
1325
- if (s.orchestrating && name !== 'agent' && name !== 'ask_user') return false
1326
1333
  const names = name.startsWith('mcp__') ? [name, name.split('__').slice(0, 2).join('__'), 'mcp'] : [name]
1327
1334
  if (names.some((n) => s.denyTools?.has(n))) return false
1328
1335
  if (!s.allowTools) return true
@@ -1334,7 +1341,7 @@ async function tool(name, args, s, signal, id) {
1334
1341
  try {
1335
1342
  const { root } = s
1336
1343
  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')
1344
+ 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
1345
  }
1339
1346
  switch (name) {
1340
1347
  case 'read_file':
@@ -1396,7 +1403,11 @@ async function tool(name, args, s, signal, id) {
1396
1403
  return await askUser(s, args)
1397
1404
  case 'skill': {
1398
1405
  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'}`
1406
+ 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'}`
1407
+ if (args.file) return readSkillFile(k, String(args.file))
1408
+ const files = skillFiles(k)
1409
+ const loaded = (k.load ?? []).map((f) => `\n\n--- ${f} ---\n${readSkillFile(k, f)}`).join('')
1410
+ return fillArgs(k.body, '') + loaded + (files.length ? `\n\n${prompt('agent/skill-files', { name: k.name, files: files.join('\n') })}` : '')
1400
1411
  }
1401
1412
  default: {
1402
1413
  const m = mcpTarget(s, name)
package/src/ui.js CHANGED
@@ -103,23 +103,24 @@ export function setTheme(name = 'dark') {
103
103
  }
104
104
  setTheme()
105
105
 
106
- // keybindings.json: { "ctrl+o": "cycle_permissions", "ctrl+g": "/toggle_thinking", "shift+tab": "none" }.
106
+ // keybindings.json: { "alt+o": "cycle_permissions", "alt+g": "/toggle_thinking", "shift+tab": "none" }.
107
107
  // Actions: stop, send_first, send_all, queue_mode, cycle_permissions, newline, clear_input, scroll_up, scroll_down (a page),
108
108
  // scroll_line_up, scroll_line_down (3 lines), scroll_top, scroll_bottom, voice, new_tab,
109
109
  // close_tab, next_tab, prev_tab, tab_1…tab_9, none (turns a
110
110
  // built-in key off); anything else is sent as typed (a /command or a message). Ctrl+C stays Ctrl+C.
111
111
  const CONTROL_KEYS = { '\x1c': 'ctrl+\\', '\x1d': 'ctrl+]', '\x1e': 'ctrl+^', '\x1f': 'ctrl+_' } // no name from readline
112
112
  export const keyId = (key, s = '') => CONTROL_KEYS[key.sequence ?? s] ?? [key.ctrl && 'ctrl', key.meta && 'alt', key.shift && 'shift', key.name ?? s].filter(Boolean).join('+').toLowerCase()
113
- // The built-in keys use Alt/Option, not Ctrl, so they don't clash with the shell and readline (Ctrl+N/P
114
- // history, Ctrl+T transpose, Ctrl+Q flow-control, Ctrl+\ quit). On macOS Terminal.app, Alt keys need
115
- // "Use Option as Meta key" on (Settings → Profiles → Keyboard); Ctrl+PgUp/PgDn cycle tabs without it.
113
+ // The built-in keys use Alt/Option, never Ctrl (the user's rule; Ctrl keys also clash with the shell and
114
+ // readline: Ctrl+N/P history, Ctrl+T transpose, Ctrl+Q flow-control, Ctrl+\ quit). Only Ctrl+C (stop)
115
+ // and Ctrl+D (quit) stay, the terminal's own. On macOS Terminal.app, Alt keys need "Use Option as Meta
116
+ // key" on (Settings → Profiles → Keyboard).
116
117
  // While it works, Enter queues a message; Alt+S stops the answer and sends the first queued one,
117
118
  // Alt+A all of them (as one message); Alt+M switches what goes when an answer is done (all or the
118
119
  // next one). /voice records (Space in an empty box, or a key in keybindings.json); Alt+T, Alt+W,
119
- // Alt+N/P (or Ctrl+PgDn/PgUp), Alt+1…9: tabs; Shift+↑↓ and Alt+↑↓ scroll the conversation (as
120
- // PgUp/PgDn and the mouse wheel do), Alt+Shift+↑↓ (or Ctrl+Home/End) to its top and bottom.
120
+ // Alt+N/P, Alt+1…9: tabs; Shift+↑↓ and Alt+↑↓ scroll the conversation (as PgUp/PgDn and the mouse
121
+ // wheel do), Alt+Shift+↑↓ to its top and bottom; Alt+O: all of the model's thinking, or its last lines.
121
122
  // keybindings.json can move any of them.
122
- export const DEFAULT_KEYS = { 'alt+b': 'background_log', 'alt+s': 'send_first', 'alt+a': 'send_all', 'alt+m': 'queue_mode', 'shift+up': 'scroll_line_up', 'shift+down': 'scroll_line_down', 'alt+up': 'scroll_up', 'alt+down': 'scroll_down', 'alt+shift+up': 'scroll_top', 'alt+shift+down': 'scroll_bottom', 'ctrl+home': 'scroll_top', 'ctrl+end': 'scroll_bottom', 'alt+t': 'new_tab', 'alt+w': 'close_tab', 'alt+n': 'next_tab', 'alt+p': 'prev_tab', 'ctrl+pagedown': 'next_tab', 'ctrl+pageup': 'prev_tab', ...Object.fromEntries([1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => [`alt+${n}`, `tab_${n}`])) }
123
+ export const DEFAULT_KEYS = { 'alt+o': '/toggle_thinking', 'alt+b': 'background_log', 'alt+s': 'send_first', 'alt+a': 'send_all', 'alt+m': 'queue_mode', 'shift+up': 'scroll_line_up', 'shift+down': 'scroll_line_down', 'alt+up': 'scroll_up', 'alt+down': 'scroll_down', 'alt+shift+up': 'scroll_top', 'alt+shift+down': 'scroll_bottom', 'alt+t': 'new_tab', 'alt+w': 'close_tab', 'alt+n': 'next_tab', 'alt+p': 'prev_tab', ...Object.fromEntries([1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => [`alt+${n}`, `tab_${n}`])) }
123
124
  export function loadKeys(file = path.join(HOME, 'keybindings.json')) {
124
125
  let raw = {}
125
126
  try {
@@ -135,9 +136,11 @@ export function loadKeys(file = path.join(HOME, 'keybindings.json')) {
135
136
  const MOUSE_ON = '\x1b[?1000h\x1b[?1002h\x1b[?1006h'
136
137
  const MOUSE_OFF = '\x1b[?1006l\x1b[?1002l\x1b[?1000l'
137
138
 
138
- // The system clipboard (pbcopy, clip, wl-copy, xclip, xsel); else the terminal's (OSC 52, works over SSH too).
139
+ // The system clipboard (pbcopy, clip, wl-copy, xclip, xsel); else the terminal's (OSC 52). Over SSH,
140
+ // the terminal's only: the system's would be the remote machine's, not the one you're at.
139
141
  export function copyText(text) {
140
- const tools = process.platform === 'darwin' ? [['pbcopy']] : process.platform === 'win32' ? [['clip']] : [['wl-copy'], ['xclip', '-selection', 'clipboard'], ['xsel', '-b', '-i']]
142
+ const remote = Boolean(process.env.SSH_CONNECTION || process.env.SSH_TTY || process.env.SSH_CLIENT)
143
+ const tools = remote ? [] : process.platform === 'darwin' ? [['pbcopy']] : process.platform === 'win32' ? [['clip']] : [['wl-copy'], ['xclip', '-selection', 'clipboard'], ['xsel', '-b', '-i']]
141
144
  for (const [cmd, ...args] of tools) if (spawnSync(cmd, args, { input: text, stdio: ['pipe', 'ignore', 'ignore'] }).status === 0) return 'system'
142
145
  process.stdout.write(`\x1b]52;c;${Buffer.from(text).toString('base64')}\x07`)
143
146
  return 'osc'
@@ -652,6 +655,7 @@ export const PERMISSIONS = [
652
655
  ['plan', 'plan first: look around without changing anything, then approve the plan'],
653
656
  ]
654
657
 
658
+ let drewLast = null // the UI (tab) that last drew the screen: only its own last frame can be diffed against
655
659
  export class UI {
656
660
  constructor({ yes = false, input = process.stdin, output = process.stdout } = {}) {
657
661
  this.permission = yes ? 'all' : 'ask' // see PERMISSIONS
@@ -670,7 +674,8 @@ export class UI {
670
674
  this.onInterrupt = null
671
675
  this.timer = null
672
676
  this.label = ''
673
- this.showThinking = true
677
+ this.showThinking = false // all of it as it comes (Alt+O); off: its last two lines, live, above the spinner
678
+ this.thinkTail = '' // the thinking coming in now, for those two lines
674
679
  this.tail = ''
675
680
  // suggest(line, cursor) → [{ value, desc, start, end, space, insertOnly }] for the menu under the prompt
676
681
  this.suggest = null
@@ -786,7 +791,7 @@ export class UI {
786
791
  const choices = pick ? m.items.filter((x) => !x.header) : []
787
792
  const cards = pick && !pick.multi && pick.items.length <= 6 && !m.items.some((x) => x.header)
788
793
  const body = pick?.body ? String(pick.body).split('\n') : []
789
- const hint = pick ? (pick.fixed ? '↑↓ move · Enter choose · Esc close' : pick.multi ? '↑↓ move · Space tick · Ctrl+A all · Ctrl+N none · Enter take · Esc cancel · type to filter' : `↑↓ move · Enter choose · Esc cancel${cards ? '' : ' · type to filter'}`) : 'Enter send · Esc cancel'
794
+ const hint = (pick ? (pick.fixed ? '↑↓ move · Enter choose · Esc close' : pick.multi ? '↑↓ move · Space tick · Alt+A all · Alt+N none · Enter take · Esc cancel · type to filter' : `↑↓ move · Enter choose · Esc cancel${cards ? '' : ' · type to filter'}`) : 'Enter send · Esc cancel') + this.autoHint()
790
795
  let at = 0
791
796
  const long = (w) => width(title) > w // too long for the border: all of it inside too
792
797
  return {
@@ -843,21 +848,33 @@ export class UI {
843
848
  const write = (x) => this.write(x)
844
849
  let think = null
845
850
  let text = null
846
- let thought = false
851
+ let thought = '' // all of it so far: shown whole when Alt+O switches to all of it midway
847
852
  const summary = () => {
848
- if (thought && !this.showThinking) this.print(c.faint(c.italic(`✻ ${who ? `${who} ` : ''}thought for ${secs()}`)))
853
+ this.thinkTail = ''
854
+ if (thought.trim() && !think) {
855
+ // what it thought stays in the conversation: its last two lines (all of it: Alt+O)
856
+ const last = thought.split('\n').map((l) => l.trim()).filter(Boolean).slice(-2)
857
+ this.print(c.faint(c.italic(`✻ ${who ? `${who} ` : ''}thought for ${secs()} · Alt+O shows all of it`)))
858
+ this.print(c.think(c.italic(last.map((l) => ` ${l}`).join('\n'))))
859
+ this.lastThought = { who, text: thought } // Alt+O shows it, now that it's over (showLastThought)
860
+ }
849
861
  }
850
862
  return {
851
863
  think: (t) => {
852
864
  if (!t || text) return
853
- thought = true
854
- if (!this.showThinking) return this.spinner(`thinking · ${secs()}`)
865
+ thought += t
866
+ if (!this.showThinking && !think) {
867
+ this.thinkTail = thought.slice(-4000) // its last two lines, live (render)
868
+ return this.spinner(`thinking · ${secs()}`)
869
+ }
855
870
  if (!think) {
871
+ this.thinkTail = ''
856
872
  this.gap()
857
873
  this.print(c.faint(c.italic(`✻ ${who ? `${who} is thinking` : 'Thinking'}…`)))
858
874
  const style = (x) => c.think(c.italic(x))
859
875
  think = new Block(write, { style })
860
876
  if (color) think = new Markdown(think, style)
877
+ return think.push(thought) // what came before the switch too
861
878
  }
862
879
  think.push(t)
863
880
  },
@@ -881,6 +898,16 @@ export class UI {
881
898
  }
882
899
  }
883
900
 
901
+ // The thinking that was shown as two lines, all of it (Alt+O after it's over): true when there was some
902
+ showLastThought() {
903
+ const t = this.lastThought
904
+ if (!t?.text.trim()) return false
905
+ this.lastThought = null
906
+ this.print(c.faint(c.italic(`✻ ${t.who ? `${t.who}'s` : 'The'} thinking, all of it:`)))
907
+ this.print(c.think(c.italic(t.text.trim().replace(/^/gm, ' '))))
908
+ return true
909
+ }
910
+
884
911
  #rl() {
885
912
  if (this.rl) return this.rl
886
913
  const terminal = Boolean(this.input.isTTY && this.out.isTTY)
@@ -915,6 +942,7 @@ export class UI {
915
942
  // alternate screen · kitty keyboard protocol (Shift/Cmd+Enter are told apart) · bracketed paste
916
943
  // · mouse reports (SGR), when HeartCode takes the mouse
917
944
  this.out.write('\x1b[?1049h\x1b[H\x1b[2J\x1b[>1u\x1b[?2004h' + this.mouseOn)
945
+ this.frame0 = null
918
946
  this.out.on('resize', () => this.render())
919
947
  this.#rl()
920
948
  process.on('exit', () => this.leaveFullscreen())
@@ -933,11 +961,18 @@ export class UI {
933
961
  this.rl?.resume()
934
962
  if (wasFull) {
935
963
  this.out.write('\x1b[?1049h\x1b[>1u\x1b[?2004h' + this.mouseOn)
964
+ this.frame0 = null
936
965
  this.render()
937
966
  }
938
967
  }
939
968
  }
940
969
 
970
+ // Taking the mouse, or giving it back to the terminal, now (the settings page's switch)
971
+ setMouse(on) {
972
+ this.mouseOn = on ? MOUSE_ON : ''
973
+ if (this.full) this.out.write(on ? MOUSE_ON : MOUSE_OFF)
974
+ }
975
+
941
976
  // The mouse: the wheel scrolls the conversation; dragging selects in it, copied when let go
942
977
  // (the terminal can't select itself while HeartCode takes the mouse). A click or a key clears it.
943
978
  // The mouse: the wheel scrolls (a dialog's own text, else the conversation); dragging selects, copied
@@ -951,7 +986,7 @@ export class UI {
951
986
  if (b & 64) {
952
987
  if ((b & 0xc3) !== 64 && (b & 0xc3) !== 65) return
953
988
  if (this.dialog) return this.dialog.key?.({ name: b & 1 ? 'down' : 'up', wheel: true }), this.render()
954
- return this.scrollBy(b & 1 ? -3 : 3) // 64 up, 65 down
989
+ return this.#wheel(b & 1 ? -1 : 1) // 64 up, 65 down
955
990
  }
956
991
  if ((b & 3) !== 0 && !up) return // the left button only (a release says 3 in some terminals)
957
992
  const press = !(b & 32) && !up
@@ -1060,6 +1095,16 @@ export class UI {
1060
1095
  this.scroll = Math.max(0, this.scroll + n) // Infinity: the top (render keeps it in range)
1061
1096
  this.render()
1062
1097
  }
1098
+ // The wheel: a line per event when they come in a stream (a trackpad, a wheel spun fast), three for a
1099
+ // lone notch; the screen drawn once a frame however many come (each its own drawing was jerky)
1100
+ #wheel(dir) {
1101
+ if (!this.full || this.out.hidden) return
1102
+ const now = Date.now()
1103
+ const step = now - (this.wheelAt ?? 0) < 60 ? 1 : 3
1104
+ this.wheelAt = now
1105
+ this.scroll = Math.max(0, this.scroll + dir * step)
1106
+ this.wheelDraw ??= setTimeout(() => ((this.wheelDraw = null), this.render()), 16)
1107
+ }
1063
1108
  page() {
1064
1109
  return Math.max(1, (this.out.rows || 24) - 4)
1065
1110
  }
@@ -1141,7 +1186,13 @@ export class UI {
1141
1186
  if (this.timer && !this.asking) {
1142
1187
  // the spinner on its own line; the timer (and Esc) on the next, so neither line is crammed
1143
1188
  const request = this.requestSince?.()
1144
- const timer = this.busySince ? `responding ${duration(this.worked())}${request ? ` · waiting for model ${duration(Date.now() - request)}` : ''} · Esc to stop` : ''
1189
+ const timer = this.busySince ? `responding ${duration(this.worked())}${request ? ` · waiting for model ${duration(Date.now() - request)}` : ''} · Esc to stop${this.thinkTail ? ' · Alt+O shows all thinking' : ''}` : ''
1190
+ if (this.thinkTail) {
1191
+ // the thinking's last two lines (long ones wrapped), dim, changing as it comes
1192
+ const w = Math.max(20, cols - 6)
1193
+ const lines = this.thinkTail.split('\n').map((l) => l.replace(/\s+/g, ' ').trim()).filter(Boolean).flatMap((l) => l.match(new RegExp(`.{1,${w}}(\\s|$)|.{${w}}`, 'g')) ?? [l]).map((l) => l.trim()).filter(Boolean)
1194
+ for (const l of lines.slice(-2)) bottom.push(fit(` ${c.think(c.italic(l))}`, cols))
1195
+ }
1145
1196
  bottom.push(fit(`${c.brand(FRAMES[this.frame % FRAMES.length])} ${c.muted(this.#label())}`, cols))
1146
1197
  if (timer) bottom.push(fit(` ${c.faint(timer)}`, cols))
1147
1198
  }
@@ -1179,13 +1230,25 @@ export class UI {
1179
1230
  const plainRow = row
1180
1231
  row = (line) => plainRow(`\x1b[2m${line.replace(/\x1b\[(0|22)?m/g, (m) => m + '\x1b[2m')}`)
1181
1232
  }
1233
+ // only the rows that changed since the last frame are written (scrolling rewrote the whole screen
1234
+ // every time); a dialog or a selection over it, or a resize: all of them
1235
+ const overlay = Boolean(this.dialog || asked || this.ssel || this.flash)
1236
+ const was = !overlay && !this.frameOverlay && this.frameSize === `${rows}x${cols}` && drewLast === this ? this.frame0 : null // another tab drew since: all of it
1237
+ const frame = []
1238
+ const put = (r, line, always = false) => {
1239
+ const text = row(line)
1240
+ frame[r] = text
1241
+ if (always || was?.[r] !== text) s += `\x1b[${r};1H${text}`
1242
+ }
1182
1243
  for (let r = 0; r < inputTop - 1; r++) {
1183
1244
  const i = r - head.length
1184
- const line = i < 0 ? head[r] : i < avail ? (view[i] ?? '') : bottom[i - avail]
1185
- s += `\x1b[${r + 1};1H${row(line)}`
1245
+ put(r + 1, i < 0 ? head[r] : i < avail ? (view[i] ?? '') : bottom[i - avail])
1186
1246
  }
1187
- box.forEach((line, i) => (s += `\x1b[${inputTop + i};1H${row(line)}`))
1188
- below.forEach((line, i) => (s += `\x1b[${inputTop + inputRows + i};1H${row(line)}`))
1247
+ // the input and what's under it, every time: readline clears from the cursor down on its own (Enter)
1248
+ box.forEach((line, i) => put(inputTop + i, line, true))
1249
+ below.forEach((line, i) => put(inputTop + inputRows + i, line, true))
1250
+ ;[this.frame0, this.frameOverlay, this.frameSize] = [frame, overlay, `${rows}x${cols}`]
1251
+ drewLast = this
1189
1252
  // what can be selected besides the conversation (screen rows from 1): the header's first line (the
1190
1253
  // project's folder), the input box, the status bar; with a dialog open, only what's in it
1191
1254
  const plain = (t) => String(t ?? '').replace(/\x1b\[[0-9;]*m/g, '')
@@ -1241,6 +1304,7 @@ export class UI {
1241
1304
  this.ttyWrite = write
1242
1305
  rl._ttyWrite = (s, key = {}) => {
1243
1306
  if (!this.full) return write(s, key)
1307
+ if (this.menu.pick?.auto) this.#armAuto() // a key: you're there; the wait starts again (debounced)
1244
1308
  if (this.sel || this.ssel) (this.sel = this.ssel = null), this.render() // a key ends a selection
1245
1309
  const bound = !(key.ctrl && key.name === 'c') && this.keys[keyId(key, s)] // ~/.heart/keybindings.json
1246
1310
  // a dialog: its keys, all of them; Esc (or its own key) closes it; Ctrl+C still stops and quits
@@ -1251,8 +1315,8 @@ export class UI {
1251
1315
  if (this.recording) return this.recording.key(key, bound) // voice: Space, Enter, Esc; the rest waits
1252
1316
  // a fixed dialog (pick(…, { fixed })): only its keys, nothing typed and no shortcuts
1253
1317
  if (this.menu.pick?.fixed && !['up', 'down', 'return', 'escape'].includes(key.name) && !(key.ctrl && key.name === 'c')) return
1254
- // In a multi-select: Ctrl+A ticks all, Ctrl+N unticks all (before tab shortcuts claim Ctrl+N)
1255
- if (this.menu.pick?.multi && key.ctrl && (key.name === 'a' || key.name === 'n')) {
1318
+ // In a multi-select: Alt+A ticks all, Alt+N unticks all (before Alt+A sends and Alt+N switches tabs)
1319
+ if (this.menu.pick?.multi && key.meta && (key.name === 'a' || key.name === 'n')) {
1256
1320
  for (const x of this.menu.pick.items) if (!x.only) x.checked = key.name === 'a'
1257
1321
  return this.refreshMenu()
1258
1322
  }
@@ -1317,7 +1381,7 @@ export class UI {
1317
1381
  if (key.name === 'up' || key.name === 'down') return this.#move(key.name === 'up' ? -1 : 1)
1318
1382
  if (key.name === 'tab') return
1319
1383
  if (m.pick.multi && key.name === 'space' && it && !it.item.only) {
1320
- it.item.checked = !it.item.checked // Space ticks; Enter takes the ticked ones; Ctrl+A/N all/none (handled earlier, before tab shortcuts)
1384
+ it.item.checked = !it.item.checked // Space ticks; Enter takes the ticked ones; Alt+A/N all/none (handled earlier, before tab shortcuts)
1321
1385
  return this.refreshMenu()
1322
1386
  }
1323
1387
  if (key.name === 'escape' || (key.name === 'return' && it)) {
@@ -1678,8 +1742,8 @@ export class UI {
1678
1742
  })
1679
1743
  const more = m.items.length - first - shown.length
1680
1744
  if (more > 0) lines.push(c.faint(` … ${more} more`))
1681
- const how = m.pick?.multi ? '↑↓ move · Space tick · Ctrl+A all · Ctrl+N none · Enter take · Esc cancel · type to filter' : '↑↓ move · Enter choose · Esc cancel · type to filter'
1682
- if (m.pick) lines.unshift(c.faint(m.items.length ? how : `nothing matches "${this.rl.line}" · Esc cancel`))
1745
+ const how = m.pick?.multi ? '↑↓ move · Space tick · Alt+A all · Alt+N none · Enter take · Esc cancel · type to filter' : '↑↓ move · Enter choose · Esc cancel · type to filter'
1746
+ if (m.pick) lines.unshift(c.faint(m.items.length ? how + this.autoHint() : `nothing matches "${this.rl.line}" · Esc cancel`))
1683
1747
  return lines
1684
1748
  }
1685
1749
 
@@ -1827,7 +1891,7 @@ export class UI {
1827
1891
  this.inputMark = this.log.length - 1 // where this message starts, for /rewind
1828
1892
  const picked = Array.isArray(pick?.chosen) ? pick.chosen.map((x) => x.label).join(', ') : pick?.chosen?.label
1829
1893
  if (pick?.quiet) this.render()
1830
- else if (pick) this.write(echo + (picked ?? c.dim('cancelled')) + '\n')
1894
+ else if (pick) this.write(echo + (picked ?? c.dim(pick.closedAs ?? 'cancelled')) + (pick.auto?.fired ? c.dim(` · no answer in ${pick.auto.secs}s: the recommended one`) : '') + '\n')
1831
1895
  else if (l !== null && history && this.isCommand(l.trim()) && !/^\s*\/skill:/.test(l)) this.notice(/^\S+/.exec(l.trim())[0], 3000, '›') // a command isn't part of the conversation: its name for a moment (not its arguments: maybe a key)
1832
1896
  else if (l !== null) this.write(echo + c.bright(l.replace(/\n/g, '\n' + ' '.repeat(width(echo.replace(/\x1b\[[0-9;]*m/g, ''))))) + '\n')
1833
1897
  else this.render()
@@ -1839,7 +1903,9 @@ export class UI {
1839
1903
  )
1840
1904
  }
1841
1905
 
1842
- cancelAsk() {
1906
+ // as: what the dialog it closes says it came to (the default: cancelled)
1907
+ cancelAsk(as) {
1908
+ if (as && this.menu.pick) this.menu.pick.closedAs = as
1843
1909
  for (const w of this.waiters.splice(0)) w(null)
1844
1910
  }
1845
1911
 
@@ -1848,7 +1914,8 @@ export class UI {
1848
1914
  // multi: tick several with Space; returns the ticked items (an array), or null.
1849
1915
  // quiet: the question and answer aren't left in the conversation (a question before it starts).
1850
1916
  // fixed: a dialog: no typing to filter, no other keys meanwhile.
1851
- async pick(title, items, { filter = '', multi = false, quiet = false, fixed = false, body = '' } = {}) {
1917
+ // auto: { item, secs }: nobody answers for secs seconds (each key starts the wait again) → item is chosen.
1918
+ async pick(title, items, { filter = '', multi = false, quiet = false, fixed = false, body = '', auto = null } = {}) {
1852
1919
  if (!this.full) {
1853
1920
  items.forEach((it, i) => this.print(` ${i + 1}. ${it.group ? `${it.group} · ` : ''}${it.label}${it.desc ? ' ' + c.dim(it.desc) : ''}`))
1854
1921
  const a = await this.ask(`${title} ${c.dim(multi ? '(numbers, like 1,3)' : '(number)')}: `)
@@ -1858,15 +1925,44 @@ export class UI {
1858
1925
  }
1859
1926
  await this.#free()
1860
1927
  if (multi) for (const it of items) if (!it.only) it.checked ??= false
1861
- this.menu.pick = { items, chosen: null, multi, quiet, fixed, body }
1928
+ this.menu.pick = { items, chosen: null, multi, quiet, fixed, body, auto: auto && { ...auto } }
1929
+ this.autoPicked = false // chosen for the user (nobody answered in time), for the caller to say so
1930
+ if (auto) {
1931
+ this.#armAuto()
1932
+ this.autoTick = setInterval(() => this.menu.pick?.auto && this.render(), 1000) // the countdown in the hint
1933
+ }
1862
1934
  try {
1863
1935
  await this.ask(`${c.bold(title)} ${c.dim('›')} `, { suggest: true, initial: filter })
1864
1936
  return this.menu.pick.chosen
1865
1937
  } finally {
1938
+ clearTimeout(this.menu.pick?.auto?.timer)
1939
+ clearInterval(this.autoTick)
1866
1940
  this.menu.pick = null
1867
1941
  }
1868
1942
  }
1869
1943
 
1944
+ // The wait of a pick with auto, from now: a key starts it again (debounced); at its end the item is chosen.
1945
+ #armAuto() {
1946
+ const a = this.menu.pick.auto
1947
+ clearTimeout(a.timer)
1948
+ a.until = Date.now() + a.secs * 1000
1949
+ a.timer = setTimeout(() => {
1950
+ const pick = this.menu.pick
1951
+ if (pick?.auto !== a) return
1952
+ a.fired = this.autoPicked = true
1953
+ pick.chosen = pick.multi ? [a.item] : a.item
1954
+ this.rl.line = ''
1955
+ this.rl.cursor = 0
1956
+ this.ttyWrite('\r', { name: 'return' })
1957
+ }, a.secs * 1000)
1958
+ this.render()
1959
+ }
1960
+
1961
+ autoHint() {
1962
+ const a = this.menu.pick?.auto
1963
+ return a ? ` · recommended in ${Math.max(0, Math.ceil((a.until - Date.now()) / 1000))}s` : ''
1964
+ }
1965
+
1870
1966
  setPermission(mode) {
1871
1967
  log('permissions', mode)
1872
1968
  if (mode === 'plan' && this.permission !== 'plan') this.beforePlan = this.permission // what plan mode asks like, and goes back to