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/CHANGELOG.md CHANGED
@@ -2,6 +2,66 @@
2
2
 
3
3
  What changed in each version of HeartCode, newest first.
4
4
 
5
+ ## 0.1.57 (2026-11-06)
6
+
7
+ - **The `/settings` link can be copied over SSH**: while the page is on, the mouse is the terminal's,
8
+ so you select the link and copy it as usual (some terminals, like macOS Terminal, drop the copy
9
+ HeartCode sends through them). The link is shorter and stays on one row at 80 columns, uses the
10
+ address you reached the machine at, and no browser is started on the remote machine. Copies sent
11
+ through the terminal now say "if your terminal allows it".
12
+ - **Turning the page off closes it**: no second box to close; Enter, Esc or Ctrl+C turn it off.
13
+
14
+ ## 0.1.56 (2026-11-05)
15
+
16
+ - **Questions as tabs**: several questions come in one dialog, a tab each; go back and forth with
17
+ ←/→ or Tab, and send all answers from the Send tab, which lists each question and its answer.
18
+ "Something else" is typed right in the row (kept when you switch tabs); a timer line shows when
19
+ the recommended answer will be taken; afterwards each question is shown with its answer.
20
+ - **The plan stays in sight**: while working, the todo list is pinned under the spinner; updates
21
+ print only what changed. Each running helper gets its own line, named by its job.
22
+ - **Clearer while it works**: one clock ("waiting for m1", then "Ns in all"); a running command's
23
+ latest line shows in the spinner, then `exit N · M lines`, and a failed one shows its error line;
24
+ refusals and retries say why; "↻ … rate-limited (429) → …" says why the model changed; the
25
+ review comes before the final answer, so the answer is last.
26
+ - **Dialogs**: Shift+Tab never changes the mode inside one; typing doesn't vanish into hidden
27
+ filters; "what to do instead" is typed in the permission dialog; on small terminals dialogs are
28
+ 90% wide and keep their timer and keys, with "↑/↓ n more".
29
+ - **Text**: words wrap whole with indented continuation lines, hint lines wrap instead of being
30
+ cut, Markdown tables line up, code blocks get a `│` gutter and quotes a `▎`; the light theme is
31
+ readable on a dark terminal.
32
+ - **Input and the rest**: Esc puts queued messages back into the input; a draft cleared with
33
+ Esc Esc is in ↑ history; empty Enter adds nothing; the header keeps the project folder's name;
34
+ the context size is right after resuming; tokens/s resets on clear; the setup help shows on first
35
+ run; a task over 10 seconds rings the bell, notifies the desktop and sets the terminal title;
36
+ `/help`, Alt+B, `/select_model`, `/context` and Alt+O ("Thinking") tidied.
37
+
38
+ ## 0.1.55 (2026-11-05)
39
+
40
+ - **Helpers never ask you anything**: a helper's question no longer pops up as your dialog (in
41
+ tool and guided mode); it decides and says what it assumed, and the main model asks if needed.
42
+ Helpers can't start helpers, get the "not done yet" checks, write only their own files (patches
43
+ through commands too), and their changes go to the review.
44
+ - **Plan mode only reads**: commands like `ls & node x`, a line break, `git diff --output`,
45
+ `find -fprint` or `rg --pre` aren't taken as reading; MCP tools that may change something are
46
+ refused; an unknown language server isn't started; "don't ask again" keeps plan mode on;
47
+ Shift+Tab out of plan goes back to the mode before it.
48
+ - **Headless and editors**: no crash when the theme or mouse setting changes; another session's
49
+ permission change doesn't change theirs; told to decide instead of asking; `/skill:name` works;
50
+ editors use the project's prompt overrides; a helper's thinking isn't shown as the agent's.
51
+ - **Models**: a stated rate or size limit moves on to the next model (it crashed); guided and
52
+ tool-calling turns see each other's conversation; a move to a model without tool calls mid-message
53
+ goes on in guided mode; a Gemini chat resumed or forked onto another provider isn't refused;
54
+ auto-compact off stays off after a move; a resumed chat doesn't keep the last one's token count.
55
+ - **Guided mode**: your hooks and allowed tools apply, steps show in stream-json and editors,
56
+ memory notes after a task, no endless "Apply this change?" after a no.
57
+ - **Full screen**: the 30-second pick waits while its tab is in the background, and a question waits
58
+ for dictation to end; piped input doesn't answer questions; ticked options are kept; no full
59
+ screen on `TERM=dumb`.
60
+ - **After a review says no**, the answer is written to you (what was made, how to use it), not as a
61
+ reply to the reviewer.
62
+ - `--resume <id>` from another folder runs in that session's project, so /rewind can't touch the
63
+ wrong folder.
64
+
5
65
  ## 0.1.54 (2026-11-04)
6
66
 
7
67
  - **Questions always come with a recommended answer**: ask_user needs options, the first one marked
package/bin/heartcode.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import path from 'node:path'
3
3
  import { parseArgs } from 'node:util'
4
- import { Client, limitSaid } from '../src/client.js'
4
+ import { Client, limitSaid, estMessages } from '../src/client.js'
5
5
  import { loadConfig, saveConfig, readJson, writeJson, providerName, CONFIG_FILE, HOME, TEMP, AUTO_MODEL, isAuto, parseModel, takeIn, whatOf, VERSION, speedOf } from '../src/config.js'
6
6
  import { loadProfile, strategy, describe, profilePath, profileFrom } from '../src/probe.js'
7
7
  import { learnFromUsage, LIMIT_MS, RATE_CAP_MS } from '../src/context.js'
@@ -9,7 +9,7 @@ import { Session, transcript, contextReport } from '../src/agent.js'
9
9
  import { listJobs, getJob, stopJob, removeJob, runningJobs, tailLines, ago as ranFor } from '../src/background.js'
10
10
  import { checkUpdate, installKind, UPDATE_COMMANDS, packageDir, whatsNew } from '../src/update.js'
11
11
  import { treeItems, codePlan, move, leaving, leftText, leftFiles } from '../src/tree.js'
12
- import { UI, c, PERMISSIONS, duration, copyText, rank, setTheme, themeCodes, renderDiff, diffLines, DEFAULT_KEYS, loadKeys, width } from '../src/ui.js'
12
+ import { UI, c, PERMISSIONS, duration, copyText, overSsh, rank, setTheme, themeCodes, renderDiff, diffLines, DEFAULT_KEYS, loadKeys, width, shortError, wrapWords } from '../src/ui.js'
13
13
  import { listFiles, runCommand, clip } from '../src/tools.js'
14
14
  import { notify } from '../src/telegram.js'
15
15
  import { log, LOG_FILE, LOG_DIR, requestLog, useRequestLog, useLogs, pruneLogs, logDays } from '../src/log.js'
@@ -144,7 +144,7 @@ const COMMANDS = SECTIONS.flatMap(([, list]) => list).sort(byName)
144
144
  // Typed while a task works, these run at once, beside it: they leave the conversation alone. The
145
145
  // others (/compact, /rewind, /resume, /init…) wait in the queue until it's done.
146
146
  const RIGHT_AWAY = new Set(['help', 'cost', 'context', 'background', 'model_info', 'diff', 'copy', 'mcp', 'doctor', 'toggle_thinking', 'btw', 'rename', 'export', 'tab', 'close_tab', 'exit', 'quit', 'settings', 'login_mcp', 'install_skill', 'import', 'voice', 'select_model'])
147
- const helpText = (sections) => sections.map(([title, list]) => ` ${c.bold(title)}\n` + list.map(([n, d]) => ` ${c.cyan(n.padEnd(18))} ${d}`).join('\n')).join('\n\n')
147
+ const helpText = (sections) => sections.map(([title, list]) => ` ${c.bold(title)}\n` + list.map(([n, d]) => ` ${c.cyan(n.padEnd(17))} ${d}`).join('\n')).join('\n\n')
148
148
  const SLASH = helpText(SECTIONS)
149
149
 
150
150
  // The keyboard shortcuts, as [keys, what] rows, read from the effective keybindings (keybindings.json
@@ -332,11 +332,21 @@ class App {
332
332
  let price = null
333
333
  // tokens and cost, into the chat (also a helper's, the probe's, compaction's)
334
334
  client.price = () => price
335
- client.onSpend = (u) => addUsage((this.chat.usage ??= {}), u, price)
335
+ let failed = null // { t, e }: the failure that made the model list move on (said with the model that answered)
336
+ let ok = false // a reply came since it
337
+ const spend = (u) => addUsage((this.chat.usage ??= {}), u, price)
338
+ // serverCount: the conversation's last request size (lastTokens) is the server's, not HeartCode's estimate (/context)
339
+ client.onSpend = function (u) {
340
+ if ((this.purpose ?? 'chat') === 'chat') this.serverCount = Boolean(u.total_tokens)
341
+ ok = true
342
+ spend(u)
343
+ }
336
344
  client.onRetry = (err, ms, attempt, next) => ui.retrying(err, ms, attempt, next) // keep trying until Esc (also while probing)
337
345
  // a failed request: what it says about the model's limits is learned
338
346
  client.onFail = (e, t) => {
339
347
  if (e.name === 'AbortError') return
348
+ if (ok) [failed, ok] = [null, false] // the first failure since a reply: why the list moves on (onSwitch)
349
+ failed ??= { t, e }
340
350
  // "too large" with the limit stated (Groq: "Limit 2000 … tokens per minute"): kept in its profile,
341
351
  // so it isn't sent what it can't take
342
352
  const said = limitSaid(e)
@@ -346,7 +356,7 @@ class App {
346
356
  if (said.rate) p.rateCap = { tokens: said.tokens, until: Date.now() + RATE_CAP_MS }
347
357
  else Object.assign(p, { inputLimit: said.tokens, inputLimitAt: Date.now() })
348
358
  writeJson(profilePath(cl), p)
349
- log('context', `${k}: ${said.rate ? 'a per-minute cap' : 'a request limit'} of ${said.tokens} tokens, from its provider`)
359
+ log('context', `${t.provider}/${t.model}: ${said.rate ? 'a per-minute cap' : 'a request limit'} of ${said.tokens} tokens, from its provider`)
350
360
  }
351
361
  }
352
362
  // the model list (settings page): another model answered
@@ -356,7 +366,10 @@ class App {
356
366
  client.announceSwitch = () => switched && (ui.print(switched), (switched = null))
357
367
  client.onSwitch = (t) => {
358
368
  const i = client.rotation.list.indexOf(t)
359
- switched = c.dim(`↻ ${t.provider} · ${t.model} answered${i ? ` (#${i + 1} in your model list)` : ' (#1 again)'}`)
369
+ const f = failed?.e
370
+ const why = f ? `${failed.t.model} ${f.status === 429 ? 'rate-limited (429)' : `failed (${clip(shortError(f), 50)})`} → ` : ''
371
+ failed = null
372
+ switched = c.dim(`↻ ${why}${t.provider} · ${t.model} answered${i ? ` (#${i + 1} in your model list)` : ' (#1 again)'}`)
360
373
  setImmediate(client.announceSwitch)
361
374
  }
362
375
  if (cfg.maxRetries !== undefined) client.retryIf = (e, attempt) => attempt < cfg.maxRetries // headless: then give up
@@ -446,7 +459,7 @@ class App {
446
459
 
447
460
  setChat(chat) {
448
461
  this.chat = chat
449
- if (this.s) this.s.chat = chat
462
+ if (this.s) Object.assign(this.s, { chat, counted: null, compactFailedAt: 0 }) // the last chat's token count and failed compaction aren't this one's
450
463
  }
451
464
 
452
465
  save() {
@@ -685,22 +698,21 @@ class App {
685
698
  const rot = this.s?.client.rotation
686
699
  const now = this.inUse() // the model list's one in use; never one of a provider that's off
687
700
  if (!now) return c.dim('the providers of all your models are off · /settings to switch one on')
688
- const on = Object.values(cfg.providers).filter((p) => !p.off).length
689
701
  const count = this.sessionModels().length
690
702
  // the model answering now; a yellow "↻" before it when it's a fallback (rotated to after one failed)
691
703
  const rotated = rot && rot.at > 0
692
704
  const name = rotated ? c.yellow('↻ ' + now.model) : c.info(now.model)
693
705
  const model =
694
- count === 1 ? name : cfg.session ? `${name} ${c.faint(`(${count} chosen)`)}` : `${c.muted('auto')} ${c.faint('(')}${name}${c.faint(')')} ${c.faint(`(${count})`)}`
706
+ count === 1 ? name : cfg.session ? `${name} ${c.faint(`(${count} chosen)`)}` : `${c.muted('auto')} ${c.faint('(')}${name}${c.faint(')')} ${c.faint(`(${count} models)`)}`
695
707
  const key = `${now.provider}/${now.model}`
696
708
  if (this.profileKey !== key) [this.profileKey, this.profile] = [key, this.s?.profile ?? loadProfile(this.client(now.provider, now.model))]
697
709
  const profile = this.s?.profile ?? this.profile
698
710
  const strat = profile && (this.s?.strat ?? strategy(profile, cfg))
699
711
  // each item, rendered (or null when it doesn't apply)
700
712
  const parts = {
701
- provider: `${c.brand('●')} ${c.muted(now.provider)} ${c.faint(`(${on})`)}`,
713
+ provider: `${c.brand('●')} ${c.muted(now.provider)}`,
702
714
  model,
703
- mode: strat ? c.muted(strat.actions === 'tools' ? 'tools' : 'guided') : c.dim('not loaded yet'),
715
+ mode: strat ? (strat.actions === 'tools' ? null : c.muted('no tool calls (guided)')) : c.faint('checked at your first message'), // what it can do: known once it's been asked
704
716
  thinking: strat?.thinking ? c.think(`thinking · ${effortOf(cfg)}`) + (ui.showThinking ? c.faint(' (all)') : '') : null,
705
717
  images: strat?.vision ? c.muted('images') : null,
706
718
  ctx: null,
@@ -713,7 +725,7 @@ class App {
713
725
  permissions: { all: c.green('⏵⏵ all allowed'), commands: c.yellow('ask before commands'), ask: c.yellow('ask before changes'), plan: c.info('⏸ plan mode') }[ui.permission],
714
726
  }
715
727
  if (strat) {
716
- const used = this.s?.client.lastTokens ?? 0
728
+ const used = this.s?.client.lastTokens || Math.round(estMessages(this.chat?.messages ?? []) * (strat.ratio ?? 1)) // a resumed chat before its first request: estimated
717
729
  const pct = Math.round((used / strat.context) * 100)
718
730
  const paint = pct >= 80 ? c.red : pct >= 50 ? c.yellow : c.green
719
731
  const guess = strat.contextSure ? '' : '~' // not said by the server: assumed, and growing as bigger requests work
@@ -855,7 +867,7 @@ class App {
855
867
  // "tools · images · thinking · 1M", for the model lists.
856
868
  canText(t) {
857
869
  const a = this.abilities(t)
858
- return [a.tools ? 'tools' : 'no tools', a.images && 'images', a.thinking && 'thinking', kTokens(a.context) + (a.guessed ? '?' : '')].filter(Boolean).join(' · ')
870
+ return [a.tools ? 'tools' : 'no tools', a.images && 'images', a.thinking && 'thinking', (a.guessed ? '~' : '') + kTokens(a.context)].filter(Boolean).join(' · ')
859
871
  }
860
872
 
861
873
  // Your models, in order: this one (#1), then the fallbacks (chosen on /settings, where every
@@ -946,7 +958,7 @@ class App {
946
958
  },
947
959
  draw: (w, h) => {
948
960
  const all = jobs()
949
- if (!all.length) return ['', ` ${c.faint('Nothing runs in the background. The model starts servers and watchers there.')}`, '', ` ${c.faint('Esc close')}`]
961
+ if (!all.length) return ['', ...wrapWords('Nothing runs in the background. The model starts servers and watchers there.', w - 2).map((l) => ` ${c.faint(l.trim())}`), '', ` ${c.faint('Esc close')}`]
950
962
  const job = current()
951
963
  this.jobTab = job.id
952
964
  // the tabs, scrolled so the one shown is on screen
@@ -974,7 +986,7 @@ class App {
974
986
  return [
975
987
  bar + (hidden ? c.faint(` +${hidden} more`) : ''),
976
988
  c.ghost('─'.repeat(w)),
977
- ` ${c.bold(clip(job.command, w - 40))} ${c.faint('·')} ${state} ${c.faint(`· ${ranFor(job)}`)}${where}`,
989
+ ` ${c.bold(clip(job.command, Math.max(10, w - 2 - width(` · ${state} · ${ranFor(job)}${where}`.replace(/\x1b\[[0-9;]*m/g, '')))))} ${c.faint('·')} ${state} ${c.faint(`· ${ranFor(job)}`)}${where}`, // the command, as much as the rest leaves room for
978
990
  ...Array.from({ length: n }, (_, i) => (shown.length ? (shown[i] === undefined ? '' : ` ${ERROR.test(shown[i]) ? c.red(shown[i]) : c.muted(shown[i])}`) : i ? '' : ` ${c.faint('(no output yet)')}`)),
979
991
  c.ghost('─'.repeat(w)),
980
992
  ` ${said ? c.yellow(said) : c.faint(`${all.length > 1 ? '←/→ another one · ' : ''}↑/↓ PgUp/PgDn scroll · K ${job.exited ? 'close' : 'stop'} it · Esc close`)}`,
@@ -1009,7 +1021,8 @@ class App {
1009
1021
  this.saveProjectModels()
1010
1022
  this.s = null
1011
1023
  }
1012
- const msg = `${c.green('using')} ${c.dim('auto')} ${c.cyan(`(${this.myModels().length} models)`)}`
1024
+ const n = this.myModels().length
1025
+ const msg = `${c.green('using')} ${c.dim('auto')} ${c.cyan(`(${n} model${n === 1 ? '' : 's'})`)}`
1013
1026
  if (later) return this.later.push(apply), this.ui.print(`${msg} ${c.dim('· from your next message')}`)
1014
1027
  apply()
1015
1028
  this.ui.print(msg)
@@ -1029,8 +1042,9 @@ class App {
1029
1042
  const chosen = new Set((cfg.session ?? mine).map(key)) // pre-ticked: this session's set, or all (auto)
1030
1043
  const items = mine.map((t) => ({ label: t.model, t, checked: chosen.has(key(t)), desc: this.modelDesc(t, mine.indexOf(t)) }))
1031
1044
  // first, standing alone: back to auto (Enter on it, whatever is ticked)
1032
- const auto = { label: 'auto', only: true, auto: true, desc: `your whole list, in its order (${mine.length} models)${cfg.session ? ' · forgets what this folder picked' : ' · in use'}` }
1033
- const picked = await ui.pick('Models for this session — tick several to rotate, one to pin, or auto', [auto, ...items], { filter, multi: true })
1045
+ const auto = { label: 'auto', only: true, auto: true, desc: `your whole list, in its order (${mine.length} model${mine.length === 1 ? '' : 's'})${cfg.session ? ' · forgets what this folder picked' : ' · in use'}` }
1046
+ const guessed = mine.some((t) => this.abilities(t).guessed) ? "\n~128k and the like: the window's size is a guess (models.dev doesn't list the model)" : ''
1047
+ const picked = await ui.pick('Models for this session', [auto, ...items], { filter, multi: true, body: `Tick several to rotate among them, one to pin it, or choose auto.${guessed}` })
1034
1048
  if (!picked) return
1035
1049
  if (picked.some((it) => it.auto)) return cfg.session ? this.auto(later) : ui.print(c.dim('already on auto'))
1036
1050
  const list = picked.map((it) => it.t)
@@ -1152,7 +1166,7 @@ async function continueTabs(app, saved) {
1152
1166
  const go = await ui.pick(many ? `Continue where you left off? ${open.length} tabs` : 'Continue your last session here?', [
1153
1167
  { label: many ? `Yes, with its ${open.length} tabs` : 'Yes', desc: `${open.map((t) => `"${t.chat.title}"`).join(', ')} · ${ago(newest)}`, yes: true },
1154
1168
  { label: 'No, start a new session', desc: '/resume finds it later' },
1155
- ], { quiet: true })
1169
+ ], { quiet: true, fixed: true })
1156
1170
  if (!go?.yes) return
1157
1171
  // this tab takes the first one in this folder; the rest (and worktree ones) open as tabs
1158
1172
  const here = open.find((t) => !t.worktree) ?? null
@@ -1191,7 +1205,7 @@ let settingsPage = null
1191
1205
  const effortOf = (cfg) => cfg.effort ?? 'low'
1192
1206
 
1193
1207
  function openBrowser(url) {
1194
- if (process.env.HEART_NO_BROWSER) return
1208
+ if (process.env.HEART_NO_BROWSER || overSsh) return // over SSH your browser isn't on this machine
1195
1209
  const [cmd, ...args] = process.platform === 'darwin' ? ['open', url] : process.platform === 'win32' ? ['rundll32', 'url.dll,FileProtocolHandler', url] : ['xdg-open', url]
1196
1210
  spawnSync(cmd, args, { stdio: 'ignore' })
1197
1211
  }
@@ -1226,7 +1240,7 @@ function applySettings(apps, cfg, what) {
1226
1240
  if (is !== was) ui.print(c.dim(`settings: ${is} now`))
1227
1241
  }
1228
1242
  if (what === 'provider') app.lists = {} // its list switched on or off, a model added by name
1229
- if (what === 'setting:permissions') ui.setPermission(cfg.permissions)
1243
+ if (what === 'setting:permissions' && !ui.noUser) ui.setPermission(cfg.permissions) // -p and ACP keep the mode they were given (--permission-mode, the editor's)
1230
1244
  if (what === 'setting:mouse') ui.setMouse(cfg.mouse !== false)
1231
1245
  if (what === 'setting:statusBar') ui.render?.() // the status bar's layout changed: redraw it now
1232
1246
  if (what === 'setting:effort' && app.s?.strat.thinking) app.s.client.effort = effortOf(cfg)
@@ -1426,15 +1440,17 @@ async function slash(app, line, working = false) {
1426
1440
  settingsPage ??= startSettings({ cfg, root: app.root, onLoginMcp: (name) => signInMcp(app, name, null), apply: (what) => applySettings(app.tabs ? app.tabs.list.map((t) => t.app) : [app], cfg, what) })
1427
1441
  const { url, local, close } = await settingsPage
1428
1442
  openBrowser(local)
1429
- ui.print(`${c.info('↗')} ${c.bold('settings')} ${c.muted('opened in your browser:')}\n ${c.faint(url)}`)
1443
+ if (!ui.full) ui.print(`${c.info('↗')} ${c.bold('settings')} ${c.muted(overSsh ? 'open this link in your browser:' : 'opened in your browser:')}\n ${c.faint(url)}`)
1430
1444
  // a dialog until it's turned off: nothing else meanwhile, in any tab (Esc turns it off too).
1431
1445
  // Not busy meanwhile: what's changed on the page applies at once, here too (opened while a task
1432
1446
  // works: once it's done).
1433
1447
  if (!working) ui.idle()
1434
1448
  if (app.tabs) app.tabs.locked = true
1449
+ ui.setMouse(false) // the terminal's own selection for the link: OSC 52 copying fails in some terminals
1435
1450
  try {
1436
- await ui.pick('The settings page is on', [{ label: 'Turn off', desc: 'stops the page and gives HeartCode back' }], { fixed: true, body: `It's open in your browser:\n${url}\n\nWhat you change there applies right away.` })
1451
+ await ui.pick('The settings page is on', [{ label: 'Turn off', desc: 'stops the page and gives HeartCode back' }], { fixed: true, quiet: true, ctrlC: true, body: `${overSsh ? 'Open this link in your browser:' : "It's open in your browser:"}\n${url}\n\nTo copy it, select it with the mouse.\nWhat you change there applies right away.` })
1437
1452
  } finally {
1453
+ ui.setMouse(cfg.mouse !== false)
1438
1454
  if (app.tabs) app.tabs.locked = false
1439
1455
  close()
1440
1456
  settingsPage = null
@@ -1536,7 +1552,7 @@ async function slash(app, line, working = false) {
1536
1552
  const answer = app.chat.history.at(-1)?.answer?.trim()
1537
1553
  if (!answer) return ui.print('No answer to copy yet.')
1538
1554
  const how = copyText(answer)
1539
- return ui.print(c.dim(`copied the last answer (${answer.split('\n').length} lines)${how === 'osc' ? ' through the terminal' : ''}`))
1555
+ return ui.print(c.dim(`copied the last answer (${answer.split('\n').length} lines)${how === 'osc' ? ' if your terminal allows it' : ''}`))
1540
1556
  }
1541
1557
  case 'background': {
1542
1558
  const jobs = listJobs(app.root)
@@ -1565,7 +1581,7 @@ async function slash(app, line, working = false) {
1565
1581
  ui.showText(
1566
1582
  'Context',
1567
1583
  [
1568
- `${c.muted(`~${kTokens(r.total)} of ${kTokens(r.window)} (${share(r.total)}) · ${s.client.model}`)}${r.counted ? c.faint(` · the last request, as the server counted it: ${kTokens(r.counted)}`) : ''}`,
1584
+ `${c.muted(`~${kTokens(r.total)} of ${kTokens(r.window)} (${share(r.total)}) · ${s.client.model}`)}${r.counted ? c.faint(` · the last request, ${s.client.serverCount ? 'as the server counted it' : 'estimated (the server sent no count)'}: ${kTokens(r.counted)}`) : ''}`,
1569
1585
  ...r.parts.filter((p) => p.tokens).map((p) => row(p.name, p.tokens, p.note)),
1570
1586
  ` ${'room left'.padEnd(20)} ${kTokens(free).padStart(6)} ${c.faint(share(free).padStart(4))} ${c.faint(`before it summarizes, at 85% (${kTokens(r.compactAt)}) — or moves to a model with more room`)}`,
1571
1587
  '',
@@ -1591,7 +1607,7 @@ async function slash(app, line, working = false) {
1591
1607
  case 'clear_chat': // a new session; the old one stays in /resume
1592
1608
  ui.clear()
1593
1609
  app.setChat(newChat(app.root))
1594
- if (app.s) app.s.client.lastTokens = 0
1610
+ if (app.s) Object.assign(app.s.client, { lastTokens: 0, speed: { tokens: 0, ms: 0 } }) // the status bar starts over too
1595
1611
  return
1596
1612
  case 'resume':
1597
1613
  return app.resume()
@@ -1693,7 +1709,7 @@ async function slash(app, line, working = false) {
1693
1709
  }
1694
1710
  case 'toggle_thinking':
1695
1711
  ui.showThinking = !ui.showThinking
1696
- ui.print(c.dim(ui.showThinking ? 'thinking: all of it, as it comes (Alt+O: its last two lines)' : 'thinking: its last two lines while it thinks (Alt+O: all of it)'))
1712
+ ui.print(c.dim(ui.showThinking ? 'thinking shown: all of it (Alt+O: last two lines)' : 'thinking shown: its last two lines (Alt+O: all of it)'))
1697
1713
  if (ui.showThinking && !ui.thinkTail) ui.showLastThought() // the one just over: all of it now
1698
1714
  return
1699
1715
  }
@@ -1723,11 +1739,12 @@ async function slash(app, line, working = false) {
1723
1739
  }
1724
1740
  }
1725
1741
 
1742
+ // true: done; false: stopped or failed; null: no model to run it
1726
1743
  async function runTask(app, task, ctl) {
1727
1744
  const { ui } = app
1728
1745
  try {
1729
1746
  const s = await app.session()
1730
- if (!s) return false
1747
+ if (!s) return null
1731
1748
  let answer
1732
1749
  try {
1733
1750
  answer = await s.run(task, ctl?.signal)
@@ -1753,7 +1770,15 @@ async function repl(app, f = {}) {
1753
1770
  ui.fullscreen({ mouse: cfg.mouse !== false }) // HeartCode's wheel and selection ("mouse": false: the terminal's own: then its wheel scrolls the whole screen)
1754
1771
  ui.onDoubleEscape = () => '/rewind'
1755
1772
  let ctl = null
1756
- ui.onEscape = () => ctl?.abort()
1773
+ // stopped by you (Esc, Ctrl+C; not Alt+S/Alt+A, which stop to send it): the queue isn't sent, it's
1774
+ // back in the input (with what's typed there), to edit or drop
1775
+ const stop = () => {
1776
+ if (!ctl) return
1777
+ ui.notice('') // "Press Esc again to stop" is done with
1778
+ if (!ui.sendNow && ui.ahead.length) app.nextInput = [...ui.ahead.splice(0), ui.rl?.line].filter(Boolean).join('\n')
1779
+ ctl.abort()
1780
+ }
1781
+ ui.onEscape = stop
1757
1782
  // a command typed while it works: run now, beside the task, if it leaves the conversation alone
1758
1783
  ui.onPanel = () => app.toggleJobs() // Alt+B: the background commands' logs, side by side, live
1759
1784
  ui.onNow = (line) => {
@@ -1809,7 +1834,7 @@ async function repl(app, f = {}) {
1809
1834
  lastInterrupt = Date.now()
1810
1835
  if (ctl) {
1811
1836
  if (again) return quit()
1812
- ctl.abort()
1837
+ stop()
1813
1838
  ui.cancelAsk()
1814
1839
  return ui.warn(`stopping… (Ctrl+C again to quit${others() ? ` HeartCode, all ${others() + 1} tabs` : ''})`)
1815
1840
  }
@@ -1824,12 +1849,26 @@ async function repl(app, f = {}) {
1824
1849
  const home = process.env.HOME
1825
1850
  const where = home && app.root.startsWith(home) ? '~' + app.root.slice(home.length) : app.root
1826
1851
  ui.folder = app.root // what a double click on the header's folder copies
1827
- ui.header = (cols = 100) => [
1828
- `${c.brand('♥')} ${c.bright(c.bold('HeartCode'))} ${c.faint(VERSION)} ${c.muted(where.length > cols - 16 ? '…' + where.slice(-(cols - 17)) : where)}`,
1829
- [['/', 'run a command'], ['@', 'attach a file'], ...(ui.voiceReady?.() ? [['Space', 'talk (voice)']] : []), [NEWLINE_KEY, 'add a new line'], ['Esc', 'stop'], ['Shift+Tab', 'change permissions']].map(([k, d]) => `${c.muted(k)} ${c.faint(d)}`).join(c.ghost(' · ')),
1830
- '',
1831
- ]
1852
+ ui.header = (cols = 100) => {
1853
+ const room = cols - 2 - width(`♥ HeartCode ${VERSION} `) // the folder's own name (its end) stays in sight
1854
+ const keys = [['/', 'run a command'], ['@', 'attach a file'], ...(ui.voiceReady?.() ? [['Space', 'talk (voice)']] : []), [NEWLINE_KEY, 'add a new line'], ['Esc', 'stop'], ['Shift+Tab', 'change permissions']]
1855
+ // the keys: on a second line when they don't fit one, broken between keys (never inside one)
1856
+ const rows = []
1857
+ for (const kd of keys) {
1858
+ const row = rows.at(-1)
1859
+ if (row && width([...row, kd].map((x) => x.join(' ')).join(' · ')) <= cols - 2) row.push(kd)
1860
+ else rows.push([kd])
1861
+ }
1862
+ return [
1863
+ `${c.brand('♥')} ${c.bright(c.bold('HeartCode'))} ${c.faint(VERSION)} ${c.muted(width(where) > room ? '…' + where.slice(-(room - 1)) : where)}`,
1864
+ ...rows.map((row) => row.map(([k, d]) => `${c.muted(k)} ${c.faint(d)}`).join(c.ghost(' · '))),
1865
+ '',
1866
+ ]
1867
+ }
1832
1868
  if (!ui.full) ui.print(ui.header().join('\n'))
1869
+ // nothing set up yet: how to, at once (not only after a first message); a local server is looked for first
1870
+ if (!Object.keys(cfg.providers).length) app.detectLocal().then((found) => (found ? ui.render?.() : ui.print(HOWTO)))
1871
+ else if (!cfg.providers[cfg.provider] || !cfg.model) ui.print(NO_MODELS)
1833
1872
  if (f.onStart) await f.onStart(app)
1834
1873
  if (f.continue) {
1835
1874
  const last = listChats(app.root)[0]
@@ -1877,6 +1916,7 @@ async function repl(app, f = {}) {
1877
1916
  }
1878
1917
  if (mark) ui.unmark(mark, /^\S+/.exec(t)[0])
1879
1918
  } else {
1919
+ if (process.stdout.isTTY) process.stdout.write(`\x1b]0;● ${path.basename(app.root)} · HeartCode\x07`)
1880
1920
  let ok = await runTask(app, t, ctl)
1881
1921
  // plan mode: the plan is done; go ahead with it?
1882
1922
  while (ok && ui.permission === 'plan' && !ctl.signal.aborted) {
@@ -1890,7 +1930,9 @@ async function repl(app, f = {}) {
1890
1930
  ui.setPermission(go.mode)
1891
1931
  ok = await runTask(app, prompt('agent/plan-approved'), ctl)
1892
1932
  }
1893
- if (ui.busySince) ui.print(c.faint(c.italic(`✻ took ${duration(ui.worked())}`))) // fixed once the reply is in
1933
+ if (ui.busySince && ok !== null) ui.print(c.faint(c.italic(`✻ took ${duration(ui.worked())}`))) // fixed once the reply is in (not when no model ran)
1934
+ // done, said by the terminal too: its title, and after a long task a bell and a notification (OSC 9)
1935
+ if (process.stdout.isTTY) process.stdout.write(`\x1b]0;${ok === null ? '♥' : '✓'} ${path.basename(app.root)} · HeartCode\x07` + (ok !== null && !ctl.signal.aborted && ui.worked() > 10_000 ? '\x07\x1b]9;HeartCode: done\x07' : ''))
1894
1936
  }
1895
1937
  ui.idle()
1896
1938
  ctl = null
@@ -1995,7 +2037,7 @@ async function main() {
1995
2037
 
1996
2038
  if (sub === 'settings') {
1997
2039
  const { url, local } = await startSettings({ cfg })
1998
- console.log(`${c.brand('♥')} HeartCode settings: ${url}\n${c.dim('opened in your browser · from another device on this network, open the link above · Ctrl+C to stop')}`)
2040
+ console.log(`${c.brand('♥')} HeartCode settings: ${url}\n${c.dim(`${overSsh ? 'open it in your browser' : 'opened in your browser'} · from another device on this network, open the link above · Ctrl+C to stop`)}`)
1999
2041
  openBrowser(local)
2000
2042
  return new Promise(() => {}) // until Ctrl+C
2001
2043
  }
@@ -2011,7 +2053,11 @@ async function main() {
2011
2053
  cfg.maxRetries ??= 10
2012
2054
  // each editor session its own settings (one choosing a model doesn't change the others')
2013
2055
  const apps = []
2014
- const makeApp = (root, ui, mcp) => apps[apps.push(new App({ ...structuredClone(cfg), ...(mcp && { mcp: { extra: [mcp] } }) }, ui, root)) - 1]
2056
+ const makeApp = (root, ui, mcp) => {
2057
+ const app = new App({ ...structuredClone(cfg), ...(mcp && { mcp: { extra: [mcp] } }) }, ui, root)
2058
+ usePromptsFrom(app.root) // its .heartcode/prompts override the built-in sections (as newApp's)
2059
+ return apps[apps.push(app) - 1]
2060
+ }
2015
2061
  watchSettings(() => apps, cfg) // the settings page's changes, into every editor session
2016
2062
  process.exit(await runAcp({ makeApp, version: VERSION, permission: f['permission-mode'] ? PERMISSION_MODES[f['permission-mode']] : (cfg.permissions ?? 'ask') }))
2017
2063
  }
@@ -2040,10 +2086,19 @@ async function main() {
2040
2086
  usePromptsFrom(app.root) // its .heartcode/prompts override the built-in sections
2041
2087
  ui.suggest = (line, cursor) => app.suggest(line, cursor)
2042
2088
  ui.status = (cols) => app.status(cols)
2089
+ ui.todos = () => app.chat?.todos // the plan, kept in sight while it works
2043
2090
  ui.requestSince = () => app.s?.client.inFlight // the spinner shows how long the model has been answering
2091
+ ui.waitingFor = () => app.s?.client.model // the spinner: "waiting for <model>"
2044
2092
  return app
2045
2093
  }
2046
2094
  let root = path.resolve(f.cwd ?? process.cwd())
2095
+ // a session of another folder (--resume <id> from anywhere): run in its project, where its files
2096
+ // are (what it changed is kept relative to it, and /rewind puts files back there)
2097
+ const other = (f['resume-id'] || f['session-id']) && loadChat(f['resume-id'] || f['session-id'], root)
2098
+ if (other?.root && path.resolve(other.root) !== root) {
2099
+ if (!fs.existsSync(other.root)) throw new Error(`session ${other.id} was in ${other.root}, which is gone`)
2100
+ root = path.resolve(other.root)
2101
+ }
2047
2102
  const wt = f.worktree !== undefined ? createWorktree(root, f.worktree) : null
2048
2103
  if (wt) {
2049
2104
  root = wt.cwd
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heartcode",
3
- "version": "0.1.54",
3
+ "version": "0.1.57",
4
4
  "description": "A coding CLI for any local or OpenAI-compatible model, including small models without tool calling.",
5
5
  "keywords": [
6
6
  "ai",
package/prompts/agent.md CHANGED
@@ -14,6 +14,7 @@ its section into ~/.heart/prompts/agent.md (every project) or .heartcode/prompts
14
14
  {{servers}}: language servers used in this project before ("typescript-language-server --stdio (typescript) for .ts"), or empty.
15
15
  {{see}}: set when the model can see images.
16
16
  {{caller}}: set when a program started HeartCode with its own instructions (--append-system-prompt), which come at the end.
17
+ {{noUser}}: set when nobody can answer questions (headless, ACP, a helper agent): there is no ask_user tool.
17
18
  {{files}} and {{more}} are passed empty, so older copies of this prompt keep working. -->
18
19
  {{#if caller}}You are running in HeartCode, a coding agent in the terminal. Your role and instructions are at the end of this prompt. Where they differ from the rules below, follow them.{{else}}You are HeartCode, a coding agent in the terminal, working on the user's project.{{/if}}
19
20
  Do the work with your tools, all of it, in this turn. Don't just describe what could be done.
@@ -24,10 +25,10 @@ Language servers used here before: {{servers}}.{{/if}}{{#if see}}
24
25
  You can see images: in the user's messages, from tools (screenshots), and image files you read_file. Look at them yourself. Never say you can't see images.{{/if}}
25
26
 
26
27
  ## 1. Ask first
27
- When the user asks you to make or change something, first ask every question whose answer changes what you build. Ask only with the ask_user tool (emphasis: true, options written for this task, your recommended option first), never as plain text. Ask them all in one reply, then any that depend on the answers. If the message already settles everything, don't ask: start.
28
+ {{#if noUser}}Nobody can answer questions here. Where a choice changes what you build, pick the most likely option, start, and say in your answer what you assumed.{{else}}When the user asks you to make or change something, first ask every question whose answer changes what you build. Ask only with the ask_user tool (emphasis: true, options written for this task, your recommended option first), never as plain text. Ask them all in one reply (one ask_user call each), then any that depend on the answers. If the message already settles everything, don't ask: start.
28
29
  - Ask about: what it's for, how it should look, testing (none, normal, edge cases), how robust, anything left open.
29
30
  - A request with two meanings: ask. Never pick silently.
30
- - Don't ask what you can look up (files, docs, the web), what the message already says, or about a question, a typo or a one-line fix.
31
+ - Don't ask what you can look up (files, docs, the web), what the message already says, or about a question, a typo or a one-line fix.{{/if}}
31
32
  Then build exactly what they chose. Nothing extra: no polish, features, tests or edge cases they didn't ask for. Nobody to ask: make it work, nothing more.
32
33
 
33
34
  ## 2. Research and plan
@@ -227,7 +228,7 @@ Fetch a web page (any http/https URL) as Markdown. The whole page is saved in th
227
228
 
228
229
  ## tool-ask_user
229
230
 
230
- Ask the user a question and wait for the answer. Only for what you can't find out or decide yourself: their choice, or a request with two meanings. Always give 2-4 short options, your recommended one first: if the user doesn't answer within 30 seconds, it is taken. They can always type their own; multiple: true lets them pick several. emphasis: true marks a question about how they want this task done (what for, looks, testing, scope): the answer then guides the checks and reviews too.
231
+ Ask the user and wait for the answers. Only for what you can't find out or decide yourself: their choice, or a request with two meanings. One question a call; several questions: several calls in one reply, which the user sees as tabs in one dialog. Each: 2-4 short options, your recommended one first (taken if the user doesn't answer within 30 seconds); header: 1-2 words for its tab ("Purpose", "Look"). They can always type their own; multiple: true lets them pick several. emphasis: true marks a question about how they want this task done (what for, looks, testing, scope): the answer then guides the checks and reviews too.
231
232
 
232
233
  ## no-answer
233
234
 
@@ -273,6 +274,7 @@ To act on them, ask a model that can see: the agent tool with these in "images"
273
274
  <!-- Added to a helper agent's system prompt. -->
274
275
  You are a helper agent. The main agent gave you one job; your final reply goes to it, not to the user.
275
276
  - Do the whole job and nothing else.
277
+ - You can't ask the user. Something unclear: decide, and say in your reply what you assumed.
276
278
  - Never guess: look it up (search the web for anything current). A question you can answer from what you know or were given: answer at once.
277
279
  - Something fails: try another way. Check that what you report is true.
278
280
  - Reply with exactly what it needs: findings with file paths and line numbers, what you changed, or what failed and why. Complete but brief.
@@ -301,7 +303,7 @@ Write the plan with the todo tool: the result in one line, then each step with h
301
303
  ## not-done
302
304
 
303
305
  <!-- Sent when the model stops but isn't done. One placeholder is set, and only its part is sent. {{asked}}: it wrote questions for the user as text (only ask_user lets them answer); {{todos}}: open todo items, a "- item" per line; {{unchecked}}: files changed and not run or tested since; {{missing}}: files its answer names that don't exist; {{early}}: it named a next step but didn't take it. -->
304
- {{#if asked}}(The user can't answer questions written as text. Ask each one with the ask_user tool: question, options (your recommended one first), emphasis: true. Put all the calls in one reply.){{/if}}
306
+ {{#if asked}}(The user can't answer questions written as text. Ask each one with the ask_user tool: question, header, options (your recommended one first), emphasis: true. Put all the calls in one reply.){{/if}}
305
307
  {{#if todos}}(Not done: your todo list has open items:
306
308
  {{todos}}
307
309
  Do them. If one is no longer needed, update the list and say why.){{/if}}
@@ -341,7 +343,8 @@ The FIRST word of your reply must be YES (done right) or NO. If NO, follow with
341
343
  <!-- Sent when the review says the work isn't right. {{model}}: who reviewed; {{issues}}: its list. -->
342
344
  (Not done: {{model}} reviewed your work and found:
343
345
  {{issues}}
344
- Check each point against the code. Fix the real ones and check the fix. If a point is wrong, say why in your answer.)
346
+ Check each point against the code. Fix the real ones and check the fix.
347
+ Then answer the user, who didn't see this review: what you made and how to use it, as if no review happened. Don't reply to the review or list its points. A point you think is wrong: skip it.)
345
348
 
346
349
  ## hook
347
350
 
package/prompts/guided.md CHANGED
@@ -12,7 +12,7 @@ You are HeartCode, a careful coding agent working in the user's project.
12
12
  HeartCode does the work in small steps. Each message asks you ONE thing. Answer exactly that, in the form asked. No explanation, no extra text.
13
13
  - Use only what you are shown. Never invent a file path, name, flag or code.
14
14
  - Write code complete and correct. No placeholders. Keep what should stay.
15
- - Your memory of tools, libraries and APIs is out of date: read their current docs online (search, then read) and follow the docs.
15
+ - Your memory of tools, libraries and APIs may be out of date: follow how the project's own files use them.
16
16
  - Reuse what the project already has. Clear names. Comments only for what isn't obvious.
17
17
 
18
18
  ## context
package/src/acp.js CHANGED
@@ -26,16 +26,21 @@ class AcpUI extends HeadlessUI {
26
26
  update(u) {
27
27
  this.conn.notify('session/update', { sessionId: this.sessionId, update: u })
28
28
  }
29
- response() {
29
+ // a helper's reply isn't the agent's own thoughts or message: its steps come as tool calls, named
30
+ response(who, { helper = false } = {}) {
31
+ if (helper) return { text() {}, think() {}, end() {} }
30
32
  const chunk = (sessionUpdate) => (text) => text && this.update({ sessionUpdate, content: { type: 'text', text } })
31
33
  return { text: chunk('agent_message_chunk'), think: chunk('agent_thought_chunk'), end() {} }
32
34
  }
33
35
  setPermission(mode) {
36
+ if (mode === 'plan' && this.permission !== 'plan') this.beforePlan = this.permission // what plan mode asks like
34
37
  super.setPermission(mode)
35
38
  if (this.sessionId) this.update({ sessionUpdate: 'current_mode_update', currentModeId: mode })
36
39
  }
37
40
  async confirm(question, kind = 'edit') {
38
- if ((this.permission === 'all' || (this.permission === 'commands' && kind === 'edit') || (this.permission === 'plan' && kind === 'read'))) return true
41
+ if (kind === 'read' && this.permission === 'plan') return true
42
+ const mode = this.permission === 'plan' ? (this.beforePlan ?? 'ask') : this.permission // plan mode asks as the mode before it did (as the full screen's)
43
+ if (mode === 'all' || (mode === 'commands' && kind === 'edit')) return true
39
44
  const toolCallId = runningCall.getStore() ?? this.calls[0] ?? `ask_${Date.now()}` // the call asking
40
45
  const r = await this.conn
41
46
  .request('session/request_permission', {
@@ -49,7 +54,7 @@ class AcpUI extends HeadlessUI {
49
54
  })
50
55
  .catch(() => null)
51
56
  const id = r?.outcome?.outcome === 'selected' ? r.outcome.optionId : null
52
- if (id === 'all') this.setPermission('all')
57
+ if (id === 'all') this.permission === 'plan' ? (this.beforePlan = 'all') : this.setPermission('all') // in plan mode: still planning, everything allowed after it
53
58
  return id === 'allow' || id === 'all'
54
59
  }
55
60
  }
@@ -132,7 +137,7 @@ export async function runAcp({ makeApp, version, permission = 'ask', input = pro
132
137
  if (!s) throw Object.assign(new Error(app.allOff() ? 'the providers of all your models are switched off: switch one on in heart settings' : 'no model set up: run heart settings to add a provider and choose a model'), { code: -32000 })
133
138
  s.onEvent ??= (e) => events(it.ui, s, e)
134
139
  const k = /^\/(\S+)\s*([\s\S]*)$/.exec(text)
135
- const skill = k && app.skills.get(k[1])
140
+ const skill = k && app.skills.get(k[1].replace(/^skill:/, '')) // /name or /skill:name, as in the full screen
136
141
  await s.run(skill && skill.use !== 'model' ? await app.expandSkill(skill, k[2]) : text, it.ctl.signal, images)
137
142
  return { stopReason: 'end_turn' }
138
143
  } catch (e) {