heartcode 0.1.69 → 0.1.101

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ui.js CHANGED
@@ -7,7 +7,7 @@ import { spawnSync } from 'node:child_process'
7
7
  import path from 'node:path'
8
8
  import { log } from './log.js'
9
9
  import { HOME } from './config.js'
10
- import { listen, transcribePcm, voiceProblem } from './voice.js'
10
+ import { listen, transcribePcm, voiceProblem, engineOf } from './voice.js'
11
11
 
12
12
  export const color = (process.stdout.isTTY || Boolean(process.env.FORCE_COLOR)) && !process.env.NO_COLOR
13
13
  // 24-bit where the terminal says so, else the nearest of 256 (Terminal.app, xterm-256color), else 16.
@@ -109,7 +109,7 @@ setTheme()
109
109
 
110
110
  // keybindings.json: { "alt+g": "cycle_permissions", "alt+r": "/rewind", "shift+tab": "none" }.
111
111
  // Actions: stop, send_first, send_all, queue_mode, cycle_permissions, newline, clear_input, scroll_up, scroll_down (a page),
112
- // scroll_line_up, scroll_line_down (3 lines), scroll_top, scroll_bottom, voice, toggle_thinking, show_plan, background_log, new_tab,
112
+ // scroll_line_up, scroll_line_down (3 lines), scroll_top, scroll_bottom, voice, show_plan, background_log, new_tab,
113
113
  // close_tab, next_tab, prev_tab, tab_1…tab_9, none (turns a
114
114
  // built-in key off); anything else is sent as typed (a /command or a message). Ctrl+C stays Ctrl+C.
115
115
  // A key as people read it ("alt+shift+down" → "Alt+Shift+↓")
@@ -145,7 +145,7 @@ export const keyId = (key, s = '') => CONTROL_KEYS[key.sequence ?? s] ?? [key.ct
145
145
  // wheel do), Alt+Shift+↑↓ to its top and bottom; Alt+O: all of the model's thinking, or its last lines;
146
146
  // Alt+L: the whole plan.
147
147
  // keybindings.json can move any of them.
148
- export const DEFAULT_KEYS = { 'alt+o': 'toggle_thinking', 'alt+l': 'show_plan', '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}`])) }
148
+ export const DEFAULT_KEYS = { 'alt+l': 'show_plan', '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}`])) }
149
149
  export function loadKeys(file = path.join(HOME, 'keybindings.json')) {
150
150
  let raw = {}
151
151
  try {
@@ -202,6 +202,7 @@ function sliceCols(text, from, to) {
202
202
  return out
203
203
  }
204
204
  const FRAMES = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
205
+ const BEAT = [1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0] // the ♥ while it works, a frame (80 ms) each: lub, dub, rest
205
206
 
206
207
  // 75000 → "1 minute 15 seconds"; the two biggest units: "5 hours 33 minutes", "2 days 3 hours"
207
208
  export function duration(ms) {
@@ -424,6 +425,20 @@ export function wrapParts(line, cols, sep = ' · ') {
424
425
  }
425
426
 
426
427
  // 4000 → "4s", 75000 → "1m 15s", 2h 3m: a clock that fits on a busy line
428
+ // a step's line says what it does, in words (the tools' own names stay the model's)
429
+ // steps of these kinds in a row are one entry: [verb, one, many, while running]
430
+ const ONE = { lines: 'line', matches: 'match', entries: 'entry', results: 'result', files: 'file' }
431
+ const GROUPS = { read_file: ['Read', 'file', 'files', 'reading'], search: ['Searched', 'time', 'times', 'searching'], list_files: ['Listed', 'folder', 'folders', 'listing'], web_fetch: ['Fetched', 'page', 'pages', 'fetching'], web_search: ['Searched the web', 'time', 'times', 'searching'] }
432
+ // Text for the screen: colors (SGR) only. Every other escape sequence and control character goes: an
433
+ // OSC 52 in a file the model printed would set your clipboard, a title or a link could hide a URL,
434
+ // cursor moves could draw over the screen.
435
+ // A command you ran while a task works (/select_model, Alt+W…): what it asks and says is yours, not the
436
+ // task's: no "waiting for you" notification, nothing left in the conversation (bin/heartcode.js onNow)
437
+ export const ownAsk = new AsyncLocalStorage()
438
+
439
+ export const safeText = (t) => String(t).replace(/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g, '').replace(/\x1b(?!\[[0-9;]*m)|[\x00-\x08\x0b\x0c\x0e-\x1a\x1c-\x1f\x7f\x9b]/g, '')
440
+ export const STEP_NAMES = { read_file: 'Read', write_file: 'Write', edit_file: 'Edit', run: 'Run', run_command: 'Run', 'run in background': 'Run in background', search: 'Search', list_files: 'List', web_fetch: 'Fetch', web_search: 'Web search', todo: 'Plan', agent: 'Helper', ask_user: 'Ask', changes: 'Changes', find_command: 'Find command', lsp: 'Code check', mcp: 'Tool', memory: 'Memory', skill: 'Skill', guide: 'Guide', background: 'Background', done: 'Done' }
441
+
427
442
  const short = (ms) => {
428
443
  const s = Math.max(0, Math.floor(ms / 1000))
429
444
  return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m ${s % 60}s` : `${Math.floor(s / 3600)}h ${Math.floor(s / 60) % 60}m`
@@ -787,8 +802,6 @@ export class UI {
787
802
  this.onInterrupt = null
788
803
  this.timer = null
789
804
  this.label = ''
790
- this.showThinking = false // all of it as it comes (Alt+O); off: its last two lines, live, above the spinner
791
- this.thinkTail = '' // the thinking coming in now, for those two lines
792
805
  this.tail = ''
793
806
  // suggest(line, cursor) → [{ value, desc, start, end, space, insertOnly }] for the menu under the prompt
794
807
  this.suggest = null
@@ -818,6 +831,12 @@ export class UI {
818
831
  if (was && was !== dialog) was.close?.()
819
832
  this.render()
820
833
  }
834
+ // a question's long text moved by n lines (drawn in #question, which keeps it in range)
835
+ #scrollText(n) {
836
+ const p = this.menu.pick
837
+ p.textTop = Math.max(0, Math.min((p.textTop ?? 0) + n, p.textMax))
838
+ this.render()
839
+ }
821
840
  // Text to read (a command's answer: /help, /context, /diff…) in a dialog: ↑/↓, PgUp/PgDn, Home/End
822
841
  // and the wheel scroll it, Esc closes it (and toggle: a key's action, as the key that opened it).
823
842
  // Without the full screen: printed.
@@ -926,6 +945,18 @@ export class UI {
926
945
  const r = wrapWords(t, w)
927
946
  return r.length <= n ? r : [...r.slice(0, n - 1), `${fit(r[n - 1], w - 1)}…`]
928
947
  }
948
+ // a picker's text longer than its room (the whole changelog on /update): a window of it, which
949
+ // PgUp/PgDn and the wheel move (↑↓ still choose), and where it is under it
950
+ const scrolled = (lines, n) => {
951
+ if (!pick) return clip(lines, n)
952
+ const room = Math.max(1, n - 1)
953
+ pick.textMax = Math.max(0, lines.length - room)
954
+ if (!pick.textMax) return lines
955
+ pick.textTop = Math.max(0, Math.min(pick.textTop ?? 0, pick.textMax))
956
+ pick.textPage = Math.max(1, room - 1)
957
+ const t = pick.textTop
958
+ return [...lines.slice(t, t + room), c.faint(`${t + 1}–${Math.min(lines.length, t + room)} of ${lines.length} lines · PgUp/PgDn or the wheel scroll`)]
959
+ }
929
960
  let at = 0
930
961
  return {
931
962
  title: long || title.length > 200 ? '' : title,
@@ -957,7 +988,7 @@ export class UI {
957
988
  })
958
989
  const want = cards ? blocks.flat().length : Math.max(1, m.items.length)
959
990
  const least = Math.min(want, cards ? Math.max(...blocks.map((b) => b.length)) + 2 : 3) // the choices give way first, down to this
960
- const top0 = clip(intro, Math.max(3, h - tail.length - filter.length - least))
991
+ const top0 = scrolled(intro, Math.max(3, h - tail.length - filter.length - least))
961
992
  const room = Math.max(1, h - tail.length - filter.length - top0.length)
962
993
  let list
963
994
  if (!choices.length) list = [c.faint(`nothing matches "${rl.line}"`)]
@@ -985,24 +1016,6 @@ export class UI {
985
1016
  }
986
1017
  }
987
1018
 
988
- // The plan (todo list) while it works, kept in sight under the spinner: how much is done, and three
989
- // of its steps (what's being done, then what's next); the rest on a key (show_plan).
990
- #todoLines(cols) {
991
- const todos = this.todos?.() ?? []
992
- const open = todos.filter((t) => t.status !== 'completed')
993
- if (!open.length) return []
994
- const done = todos.length - open.length
995
- const mark = { pending: c.muted('☐'), in_progress: c.info('◐'), completed: c.faint('☑'), stuck: c.warn('⚠') }
996
- const by = (t) => (t.by ? c.faint(' · ') + (t.status === 'in_progress' ? c.info(t.by) : c.faint(t.by)) : '') // the model a part was given to
997
- const line = (t) => fit(` ${mark[t.status]} ${t.status === 'in_progress' ? c.info(c.bold(t.content)) : t.status === 'completed' ? c.faint(t.content) : t.status === 'stuck' ? c.warn(t.content) : c.muted(t.content)}${by(t)}`, cols)
998
- const { shown, hidden } = planPick(todos)
999
- return [
1000
- fit(` ${c.muted('Plan')} ${c.faint(`· ${done} of ${todos.length} done`)}`, cols),
1001
- ...shown.map(line),
1002
- ...(hidden ? [fit(` ${c.faint(`… ${hidden} more${this.keyFor('show_plan') ? ` · ${this.keyFor('show_plan')} shows all of it` : ''}`)}`, cols)] : []),
1003
- ]
1004
- }
1005
-
1006
1019
  // The whole plan in a box (show_plan, /todos): every step and its state; the key closes it again.
1007
1020
  showPlan() {
1008
1021
  const todos = this.todos?.() ?? []
@@ -1043,45 +1056,25 @@ export class UI {
1043
1056
  return out
1044
1057
  }
1045
1058
 
1046
- // One model reply: thinking (dim, its own block) kept apart from the answer.
1059
+ // One model reply: its thinking (dim, its own block), all of it as it comes, then the answer.
1047
1060
  // who: the model thinking, named over its thinking (helpers say their own: helperUI in agent.js)
1048
1061
  response(who) {
1049
- const t0 = Date.now()
1050
- this.lastThought = null // the key shows this reply's thinking from now on, not an older one's
1051
- const secs = () => duration(Date.now() - t0)
1052
1062
  const write = (x) => this.write(x)
1053
1063
  let think = null
1054
1064
  let text = null
1055
- let thought = '' // all of it so far: shown whole when Alt+O switches to all of it midway
1056
- const summary = () => {
1057
- this.thinkTail = ''
1058
- if (thought.trim() && !think) {
1059
- // what it thought stays in the conversation: its last two rows on this screen (all of it: Alt+O)
1060
- const last = lastRows(thought, Math.max(20, (this.out.columns || 80) - 4), 2)
1061
- this.print(c.faint(c.italic(`✻ ${who ? `${who} ` : ''}thought for ${secs()}${this.keyFor('toggle_thinking') ? ` · ${this.keyFor('toggle_thinking')} shows all of it` : ''}`)))
1062
- this.print(c.think(c.italic(last.map((l) => ` ${l}`).join('\n'))))
1063
- this.lastThought = { who, text: thought } // Alt+O shows it, now that it's over (showLastThought)
1064
- }
1065
- }
1066
1065
  return {
1067
1066
  think: (t) => {
1068
1067
  if (!t || text) return
1069
1068
  this.tokenAt = Date.now() // it answers: no longer "waiting for" it
1070
- thought += t
1071
- if (!this.showThinking && !think) {
1072
- this.thinkTail = thought.slice(-4000) // its last two lines, live (render)
1073
- return this.spinner('thinking') // the time: in the line under it (and "thought for" after)
1074
- }
1075
1069
  if (!think) {
1076
- this.thinkTail = ''
1077
1070
  this.replying = true // its own text shows it's at work: no spinner line after it
1078
1071
  this.liveStep = null
1072
+ this.label = 'thinking'
1079
1073
  this.gap()
1080
- this.print(c.faint(c.italic(`✻ ${who ? `${who} is thinking` : 'Thinking'}…`)))
1074
+ this.print(c.faint(c.italic(`✻ ${who ? `${who} thinking` : 'thinking'}`)))
1081
1075
  const style = (x) => c.think(c.italic(x))
1082
1076
  think = new Block(write, { style })
1083
1077
  if (color) think = new Markdown(think, style)
1084
- return think.push(thought) // what came before the switch too
1085
1078
  }
1086
1079
  think.push(t)
1087
1080
  },
@@ -1094,7 +1087,6 @@ export class UI {
1094
1087
  if (this.label === 'thinking') this.label = 'answering'
1095
1088
  think?.end()
1096
1089
  this.gap()
1097
- summary()
1098
1090
  text = new Block(write, { marker: '● ', markerStyle: (x) => c.bright(c.bold(x)), style: c.text })
1099
1091
  if (color) text = new Markdown(text, c.text) // plain text (piped, NO_COLOR) stays as the model wrote it
1100
1092
  }
@@ -1103,23 +1095,12 @@ export class UI {
1103
1095
  end: () => {
1104
1096
  if (text) text.end()
1105
1097
  else if (think) think.end()
1106
- else summary()
1107
1098
  this.replying = false
1108
1099
  this.afterBlock = Boolean(text || think)
1109
1100
  },
1110
1101
  }
1111
1102
  }
1112
1103
 
1113
- // The thinking that was shown as two lines, all of it (Alt+O after it's over): true when there was some
1114
- showLastThought() {
1115
- const t = this.lastThought
1116
- if (!t?.text.trim()) return false
1117
- this.lastThought = null
1118
- this.print(c.faint(c.italic(`✻ ${t.who ? `${t.who}'s` : 'The'} thinking, all of it:`)))
1119
- this.print(c.think(c.italic(t.text.trim().replace(/^/gm, ' '))))
1120
- return true
1121
- }
1122
-
1123
1104
  #rl() {
1124
1105
  if (this.rl) return this.rl
1125
1106
  const terminal = Boolean(this.input.isTTY && this.out.isTTY)
@@ -1127,7 +1108,11 @@ export class UI {
1127
1108
  // escapeCodeTimeout: how long a lone Esc waits to be the start of a key's sequence. Readline's
1128
1109
  // 500ms made Esc Esc and a letter typed right after one Alt+letter: the letter was lost and the
1129
1110
  // input not cleared. Sequences come in one piece (and keyStream holds a split one for 50ms).
1130
- this.rl = readline.createInterface({ input, output: this.out, terminal, historySize: 0, escapeCodeTimeout: 50 }) // HeartCode keeps its own history (below)
1111
+ // In full screen render() draws everything: readline writes nothing. Its own redraws (a refresh,
1112
+ // Enter, a resize) wrote "clear to the end of the screen" straight to the terminal, wiping the input
1113
+ // box and the status bar until the next frame that differed.
1114
+ const output = terminal ? Object.create(this.out, { write: { value: (...a) => (this.full ? true : this.out.write(...a)) } }) : this.out
1115
+ this.rl = readline.createInterface({ input, output, terminal, historySize: 0, escapeCodeTimeout: 50 }) // HeartCode keeps its own history (below)
1131
1116
  // Our own line queue, so piped input isn't lost between questions.
1132
1117
  this.rl.on('line', (l) => {
1133
1118
  if (this.sent !== undefined) [l, this.sent] = [this.sent, undefined] // readline mangles multi-line text
@@ -1159,7 +1144,8 @@ export class UI {
1159
1144
  // which took the input box and the status bar with it)
1160
1145
  this.out.on('resize', () => setImmediate(() => ((this.frameSize = this.lastFrame = null), this.render())))
1161
1146
  this.#rl()
1162
- process.on('exit', () => this.leaveFullscreen())
1147
+ this.onExit = () => this.leaveFullscreen()
1148
+ process.on('exit', this.onExit) // taken off when this UI closes (a tab each: they'd pile up)
1163
1149
  }
1164
1150
 
1165
1151
  // Hands the terminal to another program (an editor) and takes it back afterwards.
@@ -1206,6 +1192,7 @@ export class UI {
1206
1192
  if (b & 64) {
1207
1193
  if ((b & 0xc3) !== 64 && (b & 0xc3) !== 65) return
1208
1194
  if (this.dialog) return this.dialog.key?.({ name: b & 1 ? 'down' : 'up', wheel: true }), this.render()
1195
+ if (this.asking && this.menu.pick?.textMax) return this.#scrollText(b & 1 ? 3 : -3) // a question's long text
1209
1196
  return this.#wheel(b & 1 ? -1 : 1) // 64 up, 65 down
1210
1197
  }
1211
1198
  if ((b & 3) !== 0 && !up) return // the left button only (a release says 3 in some terminals)
@@ -1219,7 +1206,7 @@ export class UI {
1219
1206
  this.flash = null
1220
1207
  const d = this.dialogAt
1221
1208
  if (modal && d && (x < d.x || y < d.y || x > d.x + d.W + 1 || y > d.y + d.H + 1)) return this.dialog ? this.setDialog(null) : this.render() // outside a dialog: closed (a question stays)
1222
- if (!modal && y <= 3 && this.onTabClick) return this.onTabClick(x - 1) // the tab bar's 3 rows
1209
+ if (!modal && y <= (this.tabBar?.(this.out.columns || 80)?.length ?? 0) && this.onTabClick) return this.onTabClick(x - 1) // the tab bar's rows (none with one tab)
1223
1210
  if (modal || this.regions?.has(y)) {
1224
1211
  // a dialog, the header, the input, the status bar: a screen selection (a click without a drag: the dialog's own)
1225
1212
  this.ssel = { a: { x, y }, b: { x, y }, moved: false, rows: this.regions, inDialog: modal }
@@ -1378,7 +1365,7 @@ export class UI {
1378
1365
  const spin = this.timer && !this.asking ? c.brand(FRAMES[this.frame % FRAMES.length]) : null
1379
1366
  let last = this.log.length - 1
1380
1367
  while (last >= 0 && !this.log[last]) last--
1381
- const live = spin && this.liveStep && this.log[last] === this.liveStep ? last : -1 // only while nothing came after it
1368
+ const live = spin && this.liveStep ? [last, last - 1].find((i) => i >= 0 && this.log[i] === this.liveStep) ?? -1 : -1 // only while nothing came after it (but a group's names)
1382
1369
  const out = []
1383
1370
  this.log.forEach((line, i) => {
1384
1371
  if (i === live) return out.push(...wrapHang(line.replace('●', spin), cols)) // not kept: it changes every frame
@@ -1400,7 +1387,9 @@ export class UI {
1400
1387
  const asked = this.asking && !this.histOn && rl
1401
1388
  // The input box: the rows around the cursor, at most INPUT_ROWS; the rules count the rest.
1402
1389
  const typing = !this.asking && rl && this.mainPrompt // working: what's typed meanwhile shows in the box
1403
- const input = asked ? layoutInput(this.mainPrompt ?? ' ', '', 0, cols) : this.asking || typing ? layoutInput(this.asking ? rl._prompt : this.mainPrompt, rl.line, rl.cursor, cols) : { rows: [''], cur: { row: 0, col: 0 } }
1390
+ // while it works on your message, the input's ♥ beats (lub-dub, then a rest), a beat a second
1391
+ const prompt = typing && this.busySince && this.timer && !BEAT[this.frame % BEAT.length] ? this.mainPrompt.replace('♥', '♡') : this.mainPrompt
1392
+ const input = asked ? layoutInput(this.mainPrompt ?? ' ', '', 0, cols) : this.asking || typing ? layoutInput(this.asking ? rl._prompt : prompt, rl.line, rl.cursor, cols) : { rows: [''], cur: { row: 0, col: 0 } }
1404
1393
  const first = Math.max(0, Math.min(input.cur.row - INPUT_ROWS + 1, input.rows.length - INPUT_ROWS))
1405
1394
  const box = input.rows.slice(first, first + INPUT_ROWS)
1406
1395
  const inputRows = box.length
@@ -1415,33 +1404,41 @@ export class UI {
1415
1404
  // else what's being done; the time in all (and Esc) on the next, on more lines when it doesn't fit
1416
1405
  const request = this.requestSince?.()
1417
1406
  const label = this.#label()
1418
- const waiting = request && !(this.tokenAt >= request) && this.beforeRetry === undefined
1419
- const status = waiting ? `${/^(working|thinking|answering)$/.test(plainOf(label)) ? '' : `${label} · `}waiting for ${this.waitingFor?.() || 'the model'} ${short(Date.now() - request)}` : label
1420
- const timer = this.busySince ? [this.beforeRetry !== undefined && 'no answer yet', `${short(this.worked())} in all`, 'Esc twice to stop', this.thinkTail && this.keyFor('toggle_thinking') && `${this.keyFor('toggle_thinking')} shows all thinking`].filter(Boolean).join(' · ') : ''
1421
- if (this.thinkTail) {
1422
- // the thinking's last two lines (long ones wrapped), dim, changing as it comes
1423
- for (const l of lastRows(this.thinkTail, Math.max(20, cols - 6), 2)) bottom.push(fit(` ${c.think(c.italic(l))}`, cols))
1424
- }
1425
- bottom.push(fit(`${c.brand(FRAMES[this.frame % FRAMES.length])} ${c.muted(status)}`, cols))
1426
- if (timer) bottom.push(...wrapParts(timer, cols - 2).map((r) => fit(` ${c.faint(r)}`, cols)))
1427
- // helpers at work (agent.js keeps them in this.helpers: label → what it's doing), then the plan
1428
- const helpers = [...this.helpers]
1429
- for (const [name, { model, what }] of helpers.slice(0, helpers.length > 6 ? 5 : 6)) bottom.push(fit(` ${c.faint('◦')} ${c.muted(name)}${model ? `${c.faint(' · ')}${c.info(model)}` : ''}${what ? c.faint(` · ${what}`) : ''}`, cols))
1430
- if (helpers.length > 6) bottom.push(c.faint(` … ${helpers.length - 5} more`))
1431
- bottom.push(...this.#todoLines(cols))
1407
+ const waiting = request && !(this.tokenAt >= request) && this.beforeRetry === undefined && Date.now() - request > 2000
1408
+ const status = String(waiting ? `${/^(working|thinking|answering)$/.test(plainOf(label)) ? '' : `${label} · `}waiting for ${this.waitingFor?.() || 'the model'}` : label).replace(/\s*[\r\n\t]+\s*/g, ' ') // never a line break or tab to the terminal: it would write on a row the screen doesn't know about, left there
1409
+ const timer = this.busySince ? `${short(this.worked())} · Esc twice to stop` : ''
1410
+ // One row, always: what's happening in a few words, how far the plan is, helpers at work, the
1411
+ // time. What's being done shows in the conversation above (its steps); nothing more here.
1412
+ const todos = this.todos?.() ?? []
1413
+ const done = todos.filter((t) => t.status === 'completed').length
1414
+ const extra = [todos.length && done < todos.length ? `plan ${done}/${todos.length}` : '', this.helpers.size ? `${this.helpers.size} helper${this.helpers.size === 1 ? '' : 's'}` : ''].filter(Boolean)
1415
+ const what = plainOf(status).split(' › ')[0]
1416
+ const tail = [...extra, timer].filter(Boolean).join(' · ')
1417
+ const room = Math.max(10, cols - 3 - width(tail) - (tail ? 3 : 0))
1418
+ bottom.push(...Array(rows >= 24 ? 3 : 1).fill(''), fit(`${c.brand(FRAMES[this.frame % FRAMES.length])} ${c.muted(width(what) > room ? `${fit(what, room - 1)}…` : what)}${tail ? c.faint(` · ${tail}`) : ''}`, cols)) // apart from the conversation above it: three empty rows (one on a short screen)
1432
1419
  }
1433
1420
  if (this.scroll) bottom.push(c.dim(` ↓ ${Number.isFinite(this.scroll) ? this.scroll : 'more'} lines below · held here for reading${this.keyFor('scroll_bottom') ? ` · ${this.keyFor('scroll_bottom')} to the bottom` : ''}`))
1434
1421
  if (this.ahead.length) {
1435
1422
  const key = (k, d) => `${c.muted(k)} ${c.faint(d)}`
1436
1423
  const sep = c.ghost(' · ')
1437
- const queued = `${c.bright(`queued ${this.ahead.length}`)}${sep}${c.faint(`when done: ${this.queueMode === 'one' ? 'one by one' : 'all together'}`)}${sep}${[['Esc', 'edit or cancel'], [this.keyFor('send_first'), 'send first now'], [this.keyFor('send_all'), 'send all now'], [this.keyFor('queue_mode'), 'change when done']].filter(([k]) => k).map(([k, d]) => key(k, d)).join(sep)}`
1438
- bottom.push(...wrapParts(queued, cols - 2, sep).map((r) => fit(` ${r}`, cols))) // on more lines, not cut
1439
- for (const [i, l] of this.ahead.slice(0, 5).entries()) bottom.push(fit(` ${c.accent(`${i + 1}.`)} ${c.muted(l.replace(/\s+/g, ' '))}`, cols))
1440
- if (this.ahead.length > 5) bottom.push(c.faint(` … ${this.ahead.length - 5} more`))
1424
+ const all = [['↑', 'edit'], [this.keyFor('send_first'), 'send now'], [this.keyFor('queue_mode'), this.queueMode === 'one' ? 'one by one' : 'all together']].filter(([k]) => k)
1425
+ const said = `${c.faint(this.ahead.length > 3 ? `${this.ahead.length} queued` : 'queued')}`
1426
+ // the keys that fit (never one cut in half); the message itself gives way first
1427
+ let keys = all.map(([k, d]) => key(k, d)).join(sep)
1428
+ for (let n = all.length; n > 1 && width(plainOf(` ↳ x${sep}${said}${sep}${keys}`)) > cols - 10; n--) keys = all.slice(0, n - 1).map(([k, d]) => key(k, d)).join(sep)
1429
+ const end = `${sep}${said}${sep}${keys}`
1430
+ const shown = this.ahead.slice(-3)
1431
+ for (const [i, l] of shown.entries()) {
1432
+ const tail = i === shown.length - 1 ? end : ''
1433
+ const room = Math.max(8, cols - 4 - width(plainOf(tail)))
1434
+ const msg = l.replace(/\s+/g, ' ')
1435
+ bottom.push(fit(` ${c.accent('↳')} ${c.muted(width(msg) > room ? `${fit(msg, room - 1)}…` : msg)}${tail}`, cols))
1436
+ }
1441
1437
  }
1442
1438
  if (this.noticeText) bottom.push(fit(this.noticeMark ? `${c.warn(this.noticeMark)} ${c.muted(this.noticeText)}` : ` ${c.muted(this.noticeText)}`, cols))
1443
1439
  if (menu.on && !asked) bottom.push(...this.#menuLines(cols))
1444
1440
  bottom.push(first ? note(first, '↑') : rule)
1441
+ for (let i = 0; i < bottom.length; i++) bottom[i] = bottom[i].replace(/[\r\n\t]/g, ' ') // a row is one row: a break in a label (a helper's, a command's) would be written on a row the screen doesn't track
1445
1442
  const head = [...(this.tabBar?.(cols) ?? []), ...(this.header?.(cols) ?? [])].map((l) => fit(l, cols))
1446
1443
  const inputTop = rows - below.length - inputRows + 1 // first row of the input
1447
1444
  const avail = Math.max(0, inputTop - 1 - bottom.length - head.length)
@@ -1594,6 +1591,7 @@ export class UI {
1594
1591
  return this.render()
1595
1592
  }
1596
1593
  }
1594
+ if ((key.name === 'pageup' || key.name === 'pagedown') && this.menu.pick?.textMax) return this.#scrollText(key.name === 'pageup' ? -this.menu.pick.textPage : this.menu.pick.textPage)
1597
1595
  if (key.name === 'pageup' || key.name === 'pagedown') return this.scrollBy(key.name === 'pageup' ? this.page() : -this.page())
1598
1596
  const m = this.menu
1599
1597
  const it = m.on && m.items[m.sel]
@@ -1709,7 +1707,7 @@ export class UI {
1709
1707
  if (!this.onEscape) return
1710
1708
  if (Date.now() - (this.escArm ?? 0) < 2500) return (this.escArm = 0), this.onEscape()
1711
1709
  this.escArm = Date.now()
1712
- this.notice('Press Esc again to stop', 2500)
1710
+ this.notice('Esc again to stop', 2500, '⏹')
1713
1711
  }
1714
1712
 
1715
1713
  // input), sent when the answer is done, or at once with send_first / send_all. Esc stops the task.
@@ -1725,16 +1723,12 @@ export class UI {
1725
1723
  const rl = this.rl
1726
1724
  const m = this.menu
1727
1725
  const it = m.on && m.items[m.sel] // a suggestion is highlighted (commands/@files show while working too)
1728
- // Esc, a layer at a time, and the work goes on: the queued messages come back into the box (to
1729
- // change, or drop); then what's in the box is cleared; only then does Esc stop the work
1726
+ // Ctrl+D: readline would close on it (the keyboard dead, the screen left as it is); quitting is /exit
1727
+ if (key.ctrl && key.name === 'd') return rl.line ? write(s, key) : this.notice('Esc twice stops the task · /exit quits HeartCode', 2500)
1728
+ // Esc while it works: stop it (twice, so a stray tap doesn't); the suggestions open: closes them first.
1729
+ // What's typed and what's queued stay (↑ brings a queued one back into the box)
1730
1730
  if (key.name === 'escape') {
1731
- if (m.on) return (m.off = rl.line), this.#suggestWhileWorking() // first Esc just closes the suggestions
1732
- if (this.ahead.length) {
1733
- const n = this.ahead.length
1734
- this.#unqueue(this.ahead.splice(0))
1735
- return this.notice(`${n === 1 ? 'The queued message is' : `${n} queued messages are`} back in the box: change ${n === 1 ? 'it' : 'them'} and press Enter, or Esc to clear`, 4000)
1736
- }
1737
- if (rl.line.trim()) return this.clearInput(), (this.escArm = 0), this.notice('Cleared · Esc twice stops the answer', 2500)
1731
+ if (m.on) return (m.off = rl.line), this.#suggestWhileWorking()
1738
1732
  return this.escStop()
1739
1733
  }
1740
1734
  // ↑ in an empty box: the last queued message back into it, to change or drop
@@ -1795,19 +1789,6 @@ export class UI {
1795
1789
  switch (what) {
1796
1790
  case 'none':
1797
1791
  return
1798
- // the model's thinking: all of it as it comes, or its last two lines; one just over, all of it in a
1799
- // box now (the key closes it). A key, not a message: nothing is sent, queued or kept in ↑
1800
- // after an answer: its whole thinking in a box (the key closes it again; how thinking shows
1801
- // stays as it was); else how thinking shows switches: all of it as it comes, or its last two
1802
- // lines (a thought shown in full already goes on in full until its reply ends)
1803
- case 'toggle_thinking':
1804
- case '/toggle_thinking': {
1805
- const t = !this.busySince ? this.lastThought : null
1806
- if (t?.text?.trim()) return this.showText(`${t.who ? `${t.who}'s thinking` : 'Thinking'}`, t.text.trim(), 'toggle_thinking')
1807
- this.showThinking = !this.showThinking
1808
- const k = this.keyFor('toggle_thinking') ?? 'the key'
1809
- return this.notice(this.showThinking ? `Thinking: all of it, as it comes · ${k}: its last two lines` : `Thinking: its last two lines from the next reply on · ${k}: all of it`, 2500)
1810
- }
1811
1792
  case 'new_tab':
1812
1793
  case 'close_tab':
1813
1794
  case 'next_tab':
@@ -1855,7 +1836,7 @@ export class UI {
1855
1836
  return this.scrollBy(what === 'scroll_top' ? Infinity : -Infinity)
1856
1837
  }
1857
1838
  if (!this.asking) {
1858
- this.ahead.push(what)
1839
+ if (!this.onNow?.(what)) this.ahead.push(what) // a command that can run beside the task runs now, as typed would
1859
1840
  return this.render()
1860
1841
  }
1861
1842
  if (!this.histOn || m.pick) return // only at the main prompt, not in a question or picker
@@ -1910,7 +1891,7 @@ export class UI {
1910
1891
  const rl = this.rl
1911
1892
  const base = { line: rl?.line ?? '', cursor: rl?.cursor ?? 0 }
1912
1893
  const keep = !this.asking // working: the spinner line stays the task's
1913
- const every = voice.provider ? 3000 : 900 // a provider's API is asked less often than whisper here
1894
+ const every = engineOf(voice, providers) === 'openai' ? 3000 : 900 // OpenAI's API (paid) is asked less often than this computer
1914
1895
  let said = '' // the stretches finished (paused), as the best model heard them
1915
1896
  let live = '' // the stretch going on, as heard so far
1916
1897
  let mic = null
@@ -1932,8 +1913,9 @@ export class UI {
1932
1913
  if (finishing) return this.notice('transcribing the last part… (Esc cancels)', 60 * 60_000, '')
1933
1914
  this.notice(mic ? `${c.red('●')} listening ${Math.floor(mic.seconds())}s · Space to pause · ${keys}` : `paused · Space to go on · ${keys}`, 60 * 60_000, '')
1934
1915
  }
1916
+ const cancel = new AbortController() // Esc while the last part is transcribed: that request stops too
1935
1917
  const heard = (pcm, fast) =>
1936
- transcribePcm(pcm, voice, providers, { fast }).catch((e) => {
1918
+ transcribePcm(pcm, voice, providers, { fast, signal: AbortSignal.any([cancel.signal, AbortSignal.timeout(30_000)]) }).catch((e) => { // a provider that hangs: given up on, never the keyboard held
1937
1919
  log('voice', e.message)
1938
1920
  failed = e.message
1939
1921
  return null
@@ -1971,7 +1953,7 @@ export class UI {
1971
1953
  let go = await new Promise((resolve) => {
1972
1954
  this.recording = {
1973
1955
  key: (key, bound) => {
1974
- if (key.name === 'escape') resolve(false)
1956
+ if (key.name === 'escape' || (key.ctrl && key.name === 'c')) resolve(false) // Ctrl+C: as Esc (it stops the recording, never lost)
1975
1957
  else if (key.name === 'return' || bound === 'voice') resolve(true)
1976
1958
  else if (key.name === 'space') mic ? pause() : start()
1977
1959
  },
@@ -1979,7 +1961,7 @@ export class UI {
1979
1961
  })
1980
1962
  clearInterval(tick)
1981
1963
  // the last part being transcribed: keys still wait (an Enter now would send half of it); Esc cancels
1982
- this.recording = { key: (key) => key.name === 'escape' && (go = false) }
1964
+ this.recording = { key: (key) => (key.name === 'escape' || (key.ctrl && key.name === 'c')) && ((go = false), cancel.abort()) }
1983
1965
  if (!go) mic?.cancel(), (mic = null)
1984
1966
  else if (mic) (finishing = true), pause()
1985
1967
  await busy
@@ -2063,7 +2045,8 @@ export class UI {
2063
2045
  // initial: text already typed in, ready to edit. suggest: show the suggestion menu while typing.
2064
2046
  // A one-line message just above the input until `ms` pass or a key is pressed ('' hides it).
2065
2047
  // mark: what goes before it ('!' a warning; '' none, for a state like voice listening)
2066
- notice(text, ms = 2000, mark = '!') {
2048
+ notice(text, ms = 2000, mark = '') {
2049
+ if (!this.full) return text && this.out.isTTY && this.print(c.dim(text)) // no screen of its own (a plain terminal): a line, as before
2067
2050
  this.noticeText = text
2068
2051
  this.noticeMark = mark
2069
2052
  clearTimeout(this.noticeTimer)
@@ -2142,6 +2125,7 @@ export class UI {
2142
2125
  }
2143
2126
 
2144
2127
  ask(prompt, { initial = '', suggest = false, history = false } = {}) {
2128
+ const own = ownAsk.getStore() || this.inCommand // asked by a command you ran (its answer comes from a key, outside it): not echoed into the conversation
2145
2129
  if (this.dialog && !history) this.setDialog(null) // a question (a permission, a picker) needs you: the dialog makes way
2146
2130
  if (this.full && (this.asking || (this.recording && !history))) return this.#free().then(() => this.ask(prompt, { initial, suggest, history }))
2147
2131
  if (history && this.kept) [initial, this.kept] = [initial || this.kept, ''] // typed before a submit()
@@ -2157,7 +2141,11 @@ export class UI {
2157
2141
  const l = together ? msgs.join('\n\n') : this.ahead.shift()
2158
2142
  if (together) this.ahead = this.ahead.filter((x) => this.isCommand(x))
2159
2143
  log('input', `${prompt.trim()} ${l} (typed while working)`)
2160
- this.write(prompt.replace(/^ /, '') + c.bright(l) + '\n')
2144
+ this.remember(l) // in ↑'s history, as a message typed at the prompt is
2145
+ if (this.isCommand(l.trim())) return Promise.resolve(l) // a command: not echoed (its own output says what it did)
2146
+ const echo = prompt.replace(/^ /, '')
2147
+ this.inputMark = this.log.length - 1 // where this message starts, for /rewind
2148
+ this.write(echo + c.bright(l.replace(/\n/g, '\n' + ' '.repeat(width(echo.replace(/\x1b\[[0-9;]*m/g, ''))))) + '\n') // its lines under its first, as typed ones
2161
2149
  return Promise.resolve(l)
2162
2150
  }
2163
2151
  // a question in the middle of work: what's being typed for later waits until it's answered
@@ -2171,7 +2159,7 @@ export class UI {
2171
2159
  return Promise.resolve(l)
2172
2160
  }
2173
2161
  if (this.closed) return Promise.resolve(null)
2174
- if (this.busySince && !history) this.onWaiting?.(prompt) // asked mid-task: you may be away (Telegram)
2162
+ if (this.busySince && this.busyTask && !history && !ownAsk.getStore()) this.onWaiting?.(prompt) // asked mid-task: you may be away (a notification, Telegram); a command you just ran (rewind's list…): you're right here
2175
2163
  this.menu.on = Boolean(suggest && (this.suggest || this.menu.pick) && this.full)
2176
2164
  this.histOn = history
2177
2165
  this.histAt = -1
@@ -2206,7 +2194,7 @@ export class UI {
2206
2194
  this.inputMark = this.log.length - 1 // where this message starts, for /rewind
2207
2195
  const said = (x) => (x.own && x.text?.trim() ? x.text.trim() : x.label) // their own answer: what they typed
2208
2196
  const picked = Array.isArray(pick?.chosen) ? pick.chosen.map(said).join(', ') : pick?.chosen && said(pick.chosen)
2209
- if (pick?.quiet) this.render()
2197
+ if (pick?.quiet || own) this.render()
2210
2198
  else if (pick) this.write(echo + (picked ?? c.dim(pick.closedAs ?? 'cancelled')) + (pick.auto?.fired ? c.dim(` · no answer in ${pick.auto.secs}s: ${pick.auto.fired === 'theirs' ? 'the typed one' : 'the recommended one'}`) : '') + '\n')
2211
2199
  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)
2212
2200
  else if (l?.trim()) this.write(echo + c.bright(l.replace(/\n/g, '\n' + ' '.repeat(width(echo.replace(/\x1b\[[0-9;]*m/g, ''))))) + '\n')
@@ -2322,7 +2310,7 @@ export class UI {
2322
2310
  async confirm(question, kind = 'edit') {
2323
2311
  if (kind === 'read' && this.permission === 'plan') return true
2324
2312
  const mode = this.permission === 'plan' ? (this.beforePlan ?? 'ask') : this.permission
2325
- if (mode === 'all' || (mode === 'commands' && kind === 'edit')) return true
2313
+ if (kind !== 'setup' && (mode === 'all' || (mode === 'commands' && kind === 'edit'))) return true // setup: always asked (tools.js SETUP_FILES)
2326
2314
  if (this.full) {
2327
2315
  this.askAbout = true // the dialog shows what it's about (the diff, the command) above the choices
2328
2316
  try {
@@ -2356,6 +2344,7 @@ export class UI {
2356
2344
  write(s) {
2357
2345
  if (!this.full) this.stopSpin() // inline, the spinner shares the line; full screen it has its own row
2358
2346
  if (!s) return
2347
+ s = safeText(s) // what a file, a page, a command or the model wrote can't drive the terminal
2359
2348
  this.tail = (this.tail + s.replace(/\x1b\[[0-9;]*m/g, '')).slice(-2)
2360
2349
  if (!this.full) return this.out.write(s)
2361
2350
  // The screen draws each line on its own, so a style still open at a line break is reopened
@@ -2387,8 +2376,8 @@ export class UI {
2387
2376
  this.log[m.at] = m.base
2388
2377
  Object.assign(this, { tail: m.tail, sgr: m.sgr })
2389
2378
  const lines = text ? text.split('\n') : []
2390
- if (lines.length === 1 || (lines.length && this.dialog)) this.notice(lines[0], 4000, '›')
2391
- else if (lines.length) this.showText(title === '/toggle_thinking' ? 'Thinking' : title, text, title) // its key (Alt+O) closes it again
2379
+ if (lines.length === 1 || (lines.length && this.dialog)) this.notice(lines[0], 8000, '›') // a command's answer isn't the conversation's: above the input until a key
2380
+ else if (lines.length) this.showText(title, text, title)
2392
2381
  else this.render()
2393
2382
  }
2394
2383
  // A blank line before a new block, unless there already is one.
@@ -2396,34 +2385,141 @@ export class UI {
2396
2385
  if (this.tail && this.tail !== '\n\n') this.write(this.tail.endsWith('\n') ? '\n' : '\n\n')
2397
2386
  }
2398
2387
  print(s = '') {
2388
+ // a command run beside a task: its line above the input for a moment, not in the conversation
2389
+ if (ownAsk.getStore() && this.full) return this.notice(String(s).split('\n').filter((l) => l.trim()).at(-1)?.replace(/\x1b\[[0-9;]*m/g, '').trim() ?? '', 8000, '›')
2399
2390
  this.write(s + '\n')
2400
2391
  }
2401
- // who: the model that made this call (named after it)
2402
- // The same call again right after it (nothing printed between but its result, as a model polling a
2403
- // page does): the line it has counts it (×2, ×3…) instead of another of the same, and its result
2404
- // makes way for the new one's.
2405
- step(name, detail = '', who = '') {
2406
- const line = `${c.accent('●')} ${c.accent(c.bold(name))} ${c.info(detail)}${who ? c.faint(` · ${who}`) : ''}`
2407
- const was = this.lastStep
2408
- const end = this.log.length - 1 // the line being written (empty, after a whole line)
2409
- if (this.full && was?.line === line && was.log === this.log && this.log[was.at] === was.shown && !plainOf(this.log[end]) && (end === was.at + 1 || end === was.after)) {
2410
- const open = this.log[end]
2411
- this.log.length = was.at + 1 // its result out: the new one's comes
2412
- this.log.push(open)
2413
- was.shown = `${line}${c.faint(` ×${++was.n}`)}`
2414
- this.log[was.at] = this.liveStep = was.shown // its ● spins until its result (#rows)
2415
- return this.render()
2392
+ // A step: one line that says what it does, at what, and (once its result is in) how it went:
2393
+ // ● Read src/app.js while it runs (the ● spins)
2394
+ // ✓ Read src/app.js · 90 lines worked; ✗ … · file not found failed; ⊘ … · declined not done
2395
+ // Steps of one kind in a row that worked (reads, searches, lists, fetches) are one entry, counted:
2396
+ // ✓ Read 8 files · 237 lines
2397
+ // in src/: app.js, util.js, … +3 more
2398
+ // a failed one stands on its own line. The same call again right after it: counted (×2) on its line.
2399
+ // who: the model that made the call, named only when it changes. sub: a helper's label (its steps
2400
+ // are indented under it, kept apart from the others')
2401
+ // note: says what happened (learned, reviewed, removed), no result to wait for; ok false: a bad one
2402
+ step(name, detail = '', who = '', { sub = '', note = false, ok = true } = {}) {
2403
+ detail = String(detail ?? '').replace(/\s*[\r\n\t]+\s*/g, ' ') // one line (a multi-line command): a step is a row, and a break in it scrambles the rows around it
2404
+ const key = sub
2405
+ if (note) {
2406
+ if (this.afterBlock) this.gap()
2407
+ this.afterBlock = false
2408
+ return this.print(this.#stepLines({ name, label: STEP_NAMES[name] ?? name.replace(/_/g, ' ').replace(/^./, (x) => x.toUpperCase()), sub, items: [{ detail, texts: [], done: true, ok }] })[0])
2409
+ }
2410
+ this.finishSteps(key) // one before it still without a result: done
2411
+ this.stepWho ??= new Map()
2412
+ if (who && who === this.stepWho.get(key)) who = '' // the model's name only when another one takes the next step
2413
+ else if (who) this.stepWho.set(key, who)
2414
+ if (this.full) {
2415
+ this.steps ??= new Map()
2416
+ const was = this.steps.get(key)
2417
+ const last = was && was.log === this.log && !plainOf(this.log.at(-1)) && this.log.length - 2 === was.end && was.items.every((i) => i.done && i.ok && !i.refused)
2418
+ if (last && was.name === name && was.items.length === 1 && was.items[0].detail === detail) {
2419
+ was.count = (was.count ?? 1) + 1
2420
+ Object.assign(was.items[0], { done: false, texts: [] })
2421
+ return this.#drawStep(was)
2422
+ }
2423
+ if (last && was.name === name && GROUPS[name]) {
2424
+ was.items.push({ detail, texts: [] })
2425
+ return this.#drawStep(was)
2426
+ }
2416
2427
  }
2417
2428
  if (this.afterBlock) this.gap()
2418
2429
  this.afterBlock = false
2419
- this.print(line)
2420
- this.liveStep = line // its ● spins until its result (#rows)
2421
- this.lastStep = { line, shown: line, n: 1, log: this.log, at: this.log.length - 2 }
2430
+ const st = { name, label: STEP_NAMES[name] ?? name.replace(/_/g, ' ').replace(/^./, (x) => x.toUpperCase()), who, sub, items: [{ detail, texts: [] }], log: this.log }
2431
+ st.at = st.end = this.log.length - 1 // the line it's on (the open line, written next)
2432
+ this.steps?.set(key, st)
2433
+ this.print(this.#stepLines(st)[0])
2434
+ this.liveStep = this.log[st.at] // its ● spins until its result (#rows)
2435
+ }
2436
+ // The outcome of the last step (of this helper, sub): text (a few words); ok false: it failed;
2437
+ // refused: not done (declined, held); none: found nothing (said, not a failure); n, unit: what it
2438
+ // got, summed over a group (90 lines, 12 matches); files: the files a search found them in.
2439
+ // Called again for the same step: its words are added (an edit: "formatted with prettier").
2440
+ result(text = '', { ok = true, refused = false, none = false, n, unit, files, sub = '' } = {}) {
2441
+ text = String(text ?? '').replace(/\s*[\r\n\t]+\s*/g, ' ') // one line, as the step's
2442
+ const st = this.steps?.get(sub)
2443
+ const item = st?.items.at(-1)
2444
+ if (!this.full || !st || st.log !== this.log) {
2445
+ if (!text) return
2446
+ this.liveStep = null
2447
+ return this.print(`${sub ? ' ' : ' '}${!ok ? c.err('✗') : refused ? c.warn('⊘') : c.ghost('⎿')} ${c.faint(text)}`)
2448
+ }
2449
+ if (text && !item.texts.includes(text)) item.texts.push(text)
2450
+ Object.assign(item, { done: true, ok: item.ok !== false && ok, refused: item.refused || refused, none: none && !item.n, n: n ?? item.n, unit: unit ?? item.unit, files: files ?? item.files })
2451
+ // a failed or refused one in a group: out of it, on its own line under it
2452
+ if (st.items.length > 1 && (!item.ok || item.refused)) {
2453
+ st.items.pop()
2454
+ this.#drawStep(st)
2455
+ const own = { ...st, who: '', items: [item], count: 1, at: this.log.length - 1, end: this.log.length - 1 }
2456
+ this.steps.set(sub, own)
2457
+ this.print(this.#stepLines(own)[0])
2458
+ return this.render()
2459
+ }
2460
+ this.#drawStep(st)
2422
2461
  }
2423
- result(text) {
2424
- this.liveStep = null
2425
- this.print(` ${c.ghost('⎿')} ${c.faint(text)}`)
2426
- if (this.lastStep?.log === this.log && this.lastStep.at === this.log.length - 3) this.lastStep.after = this.log.length - 1 // its step's, right under it
2462
+ // Steps still waiting for a result (one that never gets one, the work stopped): shown as done.
2463
+ // key: only that helper's (undefined: all)
2464
+ finishSteps(key) {
2465
+ for (const [k, st] of this.steps ?? []) {
2466
+ if ((key !== undefined && k !== key) || st.log !== this.log || st.items.every((i) => i.done)) continue
2467
+ for (const i of st.items) if (!i.done) Object.assign(i, { done: true, ok: i.ok !== false })
2468
+ this.#drawStep(st)
2469
+ }
2470
+ }
2471
+ // a step's line(s) in the conversation, again (its state changed)
2472
+ #drawStep(st) {
2473
+ const lines = this.#stepLines(st)
2474
+ const had = st.end - st.at + 1
2475
+ this.log.splice(st.at, had, ...lines)
2476
+ st.end = st.at + lines.length - 1
2477
+ this.liveStep = st.items.some((i) => !i.done) ? this.log[st.at] : null
2478
+ this.render()
2479
+ }
2480
+ #stepLines(st) {
2481
+ const pad = st.sub ? ' ' : ''
2482
+ const name = st.sub ? `${st.sub} › ${st.label}` : st.label
2483
+ const who = st.who ? c.faint(` · ${st.who}`) : ''
2484
+ const items = st.items
2485
+ const running = items.find((i) => !i.done)
2486
+ const icon = (x) => (running ? c.accent('●') : !x.ok ? c.err('✗') : x.refused ? c.warn('⊘') : x.none ? c.faint('✓') : c.ok('✓'))
2487
+ const words = (x) => (x.texts.length ? x.texts.join(' · ') : '')
2488
+ if (items.length === 1) {
2489
+ const x = items[0]
2490
+ const said = words(x)
2491
+ const paint = !x.ok ? c.err : x.refused ? c.warn : c.faint
2492
+ return [`${pad}${icon(x)} ${(x.ok ? c.accent : c.err)(c.bold(name))}${x.detail ? ` ${c.info(x.detail)}` : ''}${st.count > 1 ? c.faint(` ×${st.count}`) : ''}${said && !running ? paint(` · ${said}`) : ''}${who}`]
2493
+ }
2494
+ // a group: how many, what they got in all; then what each was at, on one row
2495
+ const [verb, one, many, doing] = GROUPS[st.name]
2496
+ const sum = items.reduce((a, i) => a + (i.n ?? 0), 0)
2497
+ const unit = items.find((i) => i.unit)?.unit
2498
+ const files = new Set(items.flatMap((i) => i.files ?? []))
2499
+ const got = running ? `${doing} ${running.detail}…` : [sum && unit ? `${sum} ${sum === 1 ? (ONE[unit] ?? unit) : unit}` : 'nothing found', files.size ? `in ${files.size} file${files.size === 1 ? '' : 's'}` : ''].filter(Boolean).join(' ')
2500
+ const head = `${pad}${icon(items[0])} ${c.accent(c.bold(`${st.sub ? `${st.sub} › ` : ''}${verb} ${items.length} ${many}`))}${c.faint(` · ${got}`)}${who}`
2501
+ // the folder they share said once, then the names
2502
+ const all = items.map((i) => i.detail)
2503
+ const dirs = all.map((d) => d.slice(0, d.lastIndexOf('/') + 1))
2504
+ const dir = (st.name === 'read_file' || st.name === 'list_files') && dirs.every((d) => d && d === dirs[0]) ? dirs[0] : '' // all in one folder
2505
+ const names = all.map((d) => d.slice(dir.length))
2506
+ const room = Math.max(20, (this.out.columns || 80) - pad.length - 4 - (dir ? dir.length + 5 : 0))
2507
+ let list = ''
2508
+ for (let k = 0; k < names.length; k++) {
2509
+ const more = names.length - k - 1 ? `, +${names.length - k - 1} more` : ''
2510
+ const next = list ? `${list}, ${names[k]}` : names[k]
2511
+ if (width(next + more) > room && list) {
2512
+ list += `, +${names.length - k} more`
2513
+ break
2514
+ }
2515
+ list = next
2516
+ }
2517
+ return [head, `${pad} ${dir ? c.faint(`in ${dir}: `) : ''}${c.info(list)}`]
2518
+ }
2519
+ // another model takes over: one dim shape for all of them (not a warning: nothing to do)
2520
+ handover(to, why) {
2521
+ log('warn', `${to} takes over: ${why}`)
2522
+ this.print(c.faint(`↻ ${to} takes over · ${why}`))
2427
2523
  }
2428
2524
  warn(text) {
2429
2525
  log('warn', text)
@@ -2460,10 +2556,11 @@ export class UI {
2460
2556
  const until = Date.now() + ms
2461
2557
  // why first, short: "cannot reach http://127.0.0.1:47329/v1/chat/completions (ECONNREFUSED)" → "can't reach 127.0.0.1:47329"
2462
2558
  let why = shortError(err).replace(/^cannot reach (\S+)(?: \([^)]*\))?/, (m, u) => `can't reach ${URL.canParse(u) ? new URL(u).host : u}`)
2463
- if (why.length > 50) why = `${why.slice(0, 49)}…`
2559
+ if (why.length > 80) why = `${why.slice(0, 79)}…`
2464
2560
  const left = () => Math.max(0, Math.ceil((until - Date.now()) / 1000)) * 1000
2465
- if (next) return this.spinner(() => `${c.yellow('⚠')} ${why} · trying ${next.provider} · ${next.model}${left() ? ` in ${short(left())} (all failed once)` : ''} (try ${attempt})`)
2466
- this.spinner(() => `${c.yellow('⚠')} ${why} · retrying in ${short(left())} (try ${attempt})`)
2561
+ const who = this.waitingFor?.()
2562
+ if (next) return this.spinner(() => `⚠ ${who ? `${who}: ` : ''}${why} · trying ${next.model}${left() ? ` in ${short(left())}` : ''}`)
2563
+ this.spinner(() => `⚠ ${who ? `${who}: ` : ''}${why} · trying again in ${short(left())} (try ${attempt})`)
2467
2564
  }
2468
2565
 
2469
2566
  stopSpin() {
@@ -2478,22 +2575,31 @@ export class UI {
2478
2575
 
2479
2576
  // Full screen: from the moment work starts until it's done (a task, a probe, a command), the
2480
2577
  // spinner row stays on, whatever gets printed meanwhile. It steps aside while asking the user.
2481
- busy() {
2578
+ // later: the spinner only if it's still at work then (a command that answers at once shows none)
2579
+ // task: the model at work (not a command you ran): its questions may tell you (onWaiting)
2580
+ busy(later = 0, { task = true } = {}) {
2482
2581
  if (!this.full) return
2582
+ this.busyTask = task
2483
2583
  this.busySince = Date.now()
2484
2584
  this.waited = 0
2485
- this.spinner('working')
2585
+ clearTimeout(this.busyLater)
2586
+ if (!later) return this.spinner('working')
2587
+ this.busyLater = setTimeout(() => this.busySince && !this.timer && this.spinner('working'), later)
2588
+ this.busyLater.unref?.()
2486
2589
  }
2487
2590
  // time spent on the work so far, without the time it waited for your answers
2488
2591
  worked() {
2489
2592
  return Date.now() - this.busySince - this.waited - (this.asking ? Date.now() - this.askedAt : 0)
2490
2593
  }
2491
2594
  idle() {
2595
+ this.finishSteps()
2596
+ clearTimeout(this.busyLater)
2492
2597
  this.busySince = null
2493
2598
  this.stopSpin()
2494
2599
  }
2495
2600
 
2496
2601
  close() {
2602
+ if (this.onExit) process.off('exit', this.onExit)
2497
2603
  this.busySince = null // closing ends any work in progress: the spinner stops too
2498
2604
  clearInterval(this.dialogTimer)
2499
2605
  this.stopSpin()