heartcode 0.1.30 → 0.1.33

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/bin/heartcode.js CHANGED
@@ -5,7 +5,8 @@ import { Client } from '../src/client.js'
5
5
  import { loadConfig, saveConfig, readJson, writeJson, providerName, CONFIG_FILE, HOME, AUTO_MODEL, isAuto, parseModel, takeIn, whatOf, VERSION } from '../src/config.js'
6
6
  import { probe, loadProfile, strategy, describe, profilePath, profileFrom } from '../src/probe.js'
7
7
  import { learnFromUsage, LIMIT_MS } from '../src/context.js'
8
- import { Session, transcript } from '../src/agent.js'
8
+ import { Session, transcript, contextReport } from '../src/agent.js'
9
+ import { listJobs, getJob, stopJob, removeJob, runningJobs, tailLines, ago as ranFor } from '../src/background.js'
9
10
  import { treeItems, codePlan, move, leaving, leftText, leftFiles } from '../src/tree.js'
10
11
  import { UI, c, PERMISSIONS, duration, copyText, rank, setTheme, themeCodes, renderDiff, diffLines, DEFAULT_KEYS, loadKeys, width } from '../src/ui.js'
11
12
  import { listFiles, runCommand, clip } from '../src/tools.js'
@@ -117,6 +118,8 @@ const SECTIONS = [
117
118
  ['/init', 'look at the project and write AGENTS.md: its commands, conventions and layout'],
118
119
  ['/btw', 'ask something on the side, also while it works; the answer stays out of the conversation', true],
119
120
  ['/cost', 'tokens used and what they cost, this session'],
121
+ ['/context', "what's in the context now: system prompt, tools, messages, tool results, and the biggest pieces"],
122
+ ['/background', 'commands running in the background (servers, watchers): their logs live, a tab each (Alt+B) · /background stop [id] · /background files', true],
120
123
  ['/model_info', 'what the model can do and how HeartCode uses it'],
121
124
  ['/test_model', 'test the model for real (otherwise what it can do comes from models.dev, or your settings)'],
122
125
  ['/tidy_memory', 'merge, update and link the memory notes now'],
@@ -135,7 +138,12 @@ const SECTIONS = [
135
138
  ['/exit', 'quit HeartCode (Alt+W closes just this tab)'],
136
139
  ]],
137
140
  ]
138
- const COMMANDS = SECTIONS.flatMap(([, list]) => list)
141
+ const byName = (a, b) => a[0].localeCompare(b[0])
142
+ for (const [, list] of SECTIONS) list.sort(byName) // alphabetical, in /help and in the "/" menu
143
+ const COMMANDS = SECTIONS.flatMap(([, list]) => list).sort(byName)
144
+ // Typed while a task works, these run at once, beside it: they leave the conversation alone. The
145
+ // others (/compact, /rewind, /resume, /init…) wait in the queue until it's done.
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'])
139
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')
140
148
  const SLASH = helpText(SECTIONS)
141
149
 
@@ -148,11 +156,12 @@ function keysHelp(keys = {}) {
148
156
  const tabs = /(^|,)alt\+[1-9]/.test(Object.keys(keys).join(','))
149
157
  const rows = [
150
158
  ['Space', 'start voice input (when the input box is empty)'],
151
- ['Enter', 'send · while it works, queue the message'],
159
+ ['Enter', 'send · while it works, queue the message (commands like /help, /cost, /select_model run at once)'],
152
160
  ['Option/Shift/Ctrl+Enter', 'new line in the box'],
153
161
  ['Esc', 'stop the task (press twice to confirm)'],
154
162
  ['Esc Esc', 'rewind to an earlier message (at the prompt)'],
155
163
  ['Shift+Tab', 'change what runs without asking (permissions)'],
164
+ [forAct('background_log'), "the background commands' logs in a dialog, a tab each (←/→ switch, ↑/↓ scroll, K twice stops one, Esc closes)"],
156
165
  [forAct('new_tab'), 'new tab'],
157
166
  [forAct('close_tab'), 'close this tab'],
158
167
  [forAct('next_tab'), 'next tab'],
@@ -164,6 +173,9 @@ function keysHelp(keys = {}) {
164
173
  [[forAct('scroll_up'), forAct('scroll_down')].filter(Boolean).join(' / '), 'scroll the conversation a page'],
165
174
  [[forAct('scroll_line_up'), forAct('scroll_line_down')].filter(Boolean).join(' / '), 'scroll a few lines'],
166
175
  ['Ctrl+C', 'stop · twice quits HeartCode'],
176
+ ['Drag', 'select and copy: the conversation, a dialog, the folder, the input, the status bar'],
177
+ ['Double-click', 'copy the word under it (an address, a path, a model)'],
178
+ [process.platform === 'darwin' ? 'Option+drag' : 'Shift+drag', "the terminal's own selection, past HeartCode's"],
167
179
  ].filter(([k]) => k)
168
180
  return rows
169
181
  }
@@ -195,7 +207,7 @@ const mask = (k) => (k ? (k.length > 12 ? `${k.slice(0, 4)}…${k.slice(-4)}` :
195
207
  // overrides it — see App.status for the item names and format.
196
208
  const DEFAULT_STATUS = [
197
209
  { left: ['provider', 'model'], right: ['mode', 'thinking', 'images'] },
198
- { left: ['ctx', 'tps', 'autocompact'], right: ['permissions', 'worktree', 'cost'] },
210
+ { left: ['ctx', 'tps', 'autocompact'], right: ['background', 'permissions', 'worktree', 'cost'] },
199
211
  ]
200
212
 
201
213
  class App {
@@ -220,7 +232,7 @@ class App {
220
232
  if (this.cfg.session) return
221
233
  const saved = readJson(path.join(this.root, '.heartcode', 'models.json'), null)
222
234
  const valid = (saved?.session ?? []).filter((t) => t?.provider && t?.model && this.cfg.providers[t.provider])
223
- if (valid.length) this.cfg.session = valid
235
+ if (valid.length) [this.cfg.session, this.folderModels] = [valid, true]
224
236
  }
225
237
 
226
238
  saveProjectModels() {
@@ -235,7 +247,7 @@ class App {
235
247
  if (!this.ui.noUser)
236
248
  mcp.onSignIn = (name, url) => {
237
249
  this.ui.print(`${c.info('↗')} ${c.bold(name)} ${c.muted('needs you to sign in; opening your browser…')}\n ${c.faint(url)}`)
238
- const [cmd, ...args] = process.platform === 'darwin' ? ['open', url] : process.platform === 'win32' ? ['cmd', '/c', 'start', '', url] : ['xdg-open', url]
250
+ const [cmd, ...args] = process.platform === 'darwin' ? ['open', url] : process.platform === 'win32' ? ['rundll32', 'url.dll,FileProtocolHandler', url] : ['xdg-open', url]
239
251
  spawnSync(cmd, args, { stdio: 'ignore' })
240
252
  this.ui.spinner(`waiting for you to sign in to ${name} in the browser · Esc to stop`)
241
253
  }
@@ -573,7 +585,7 @@ class App {
573
585
  // Built-in commands (/name), then the skills you can type, namespaced as /skill:name so they're
574
586
  // easy to tell apart from HeartCode's own commands (and can't clash with them).
575
587
  commands() {
576
- const mine = [...this.skills.values()].filter((k) => k.use !== 'model').map((k) => [`/skill:${k.name}`, k.description, true])
588
+ const mine = [...this.skills.values()].filter((k) => k.use !== 'model').map((k) => [`/skill:${k.name}`, k.description, true]).sort(byName)
577
589
  return [...COMMANDS, ...mine]
578
590
  }
579
591
 
@@ -679,6 +691,7 @@ class App {
679
691
  cost: null,
680
692
  autocompact: cfg.autoCompact === false ? c.faint('auto-compact off') : null,
681
693
  worktree: this.worktree ? c.info(`⎇ ${this.worktree.branch}`) : null,
694
+ background: runningJobs(this.root).length ? c.info(`⚙ ${runningJobs(this.root).length} running`) + c.faint(' Alt+B') : null,
682
695
  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],
683
696
  }
684
697
  if (strat) {
@@ -693,7 +706,9 @@ class App {
693
706
  }
694
707
  const sep = c.ghost(' │ ')
695
708
  const vis = (str) => width(str.replace(/\x1b\[[0-9;]*m/g, ''))
696
- const layout = Array.isArray(cfg.statusBar) && cfg.statusBar.length ? cfg.statusBar : DEFAULT_STATUS
709
+ let layout = Array.isArray(cfg.statusBar) && cfg.statusBar.length ? cfg.statusBar : DEFAULT_STATUS
710
+ // commands running in the background are shown also on a bar laid out before there was this item
711
+ if (parts.background && !JSON.stringify(layout).includes('"background"')) layout = [...layout.slice(0, -1), ...layout.slice(-1).map((row) => (Array.isArray(row) ? { left: row, right: ['background'] } : { ...row, right: ['background', ...(row.right ?? [])] }))]
697
712
  const line = (row) => {
698
713
  const names = (g) => (g ?? []).map((t) => parts[t]).filter(Boolean).join(sep)
699
714
  const left = names(Array.isArray(row) ? row : row?.left)
@@ -860,31 +875,133 @@ class App {
860
875
  return cfg.session.filter((t) => cfg.providers[t.provider] && (all || !cfg.providers[t.provider].off) && t.model && !seen.has(`${t.provider}/${t.model}`) && seen.add(`${t.provider}/${t.model}`))
861
876
  }
862
877
 
878
+ // Alt+B, /background: the background commands' logs in a dialog, one at a time with a tab each.
879
+ // ←/→ (or a click on a tab): another one; ↑/↓, PgUp/PgDn, the wheel: back in its log (End: the
880
+ // newest again); K twice: stop it and close its tab; Esc or Alt+B: closed.
881
+ toggleJobs(on = !this.jobsShown) {
882
+ const { ui } = this
883
+ if (!on) return ui.setDialog(null)
884
+ this.jobsShown = true
885
+ const ERROR = /\b(error|errors|failed|fail|exception|traceback|panic|fatal)\b/i
886
+ const jobs = () => listJobs(this.root)
887
+ const current = () => jobs().find((j) => j.id === this.jobTab) ?? jobs().findLast((j) => !j.exited) ?? jobs().at(-1)
888
+ let spots = [] // where each tab is on its row: { from, to, id }
889
+ let back = 0 // lines scrolled back from the newest (0: following it)
890
+ let page = 10
891
+ let armed = 0 // K pressed once, when
892
+ let said = '' // a line for the footer (K's question)
893
+ const go = (d) => {
894
+ const all = jobs()
895
+ if (!all.length) return
896
+ this.jobTab = all[(all.indexOf(current()) + d + all.length) % all.length].id
897
+ back = 0
898
+ }
899
+ const kill = () => {
900
+ const job = current()
901
+ if (!job) return
902
+ if (Date.now() - armed > 2500) return (armed = Date.now()), (said = `Press K again to ${job.exited ? 'close' : 'stop and close'} #${job.id}`)
903
+ armed = 0
904
+ said = ''
905
+ const all = jobs()
906
+ const next = all[all.indexOf(job) + 1] ?? all[all.indexOf(job) - 1]
907
+ removeJob(job)
908
+ ui.print(c.dim(`${job.exited ? 'closed' : 'stopped'} #${job.id} ${clip(job.command, 80)}`))
909
+ if (!next) return this.toggleJobs(false)
910
+ this.jobTab = next.id
911
+ back = 0
912
+ }
913
+ ui.setDialog({
914
+ title: 'Background commands',
915
+ toggle: 'background_log', // Alt+B closes it too
916
+ close: () => (this.jobsShown = false),
917
+ key: (key) => {
918
+ if (key.name !== 'k') (armed = 0), (said = '')
919
+ if (key.name === 'left' || key.name === 'right') return go(key.name === 'left' ? -1 : 1)
920
+ if (key.name === 'up' || key.name === 'down') return (back = Math.max(0, back + (key.name === 'up' ? (key.wheel ? 3 : 1) : key.wheel ? -3 : -1)))
921
+ if (key.name === 'pageup' || key.name === 'pagedown') return (back = Math.max(0, back + (key.name === 'pageup' ? page : -page)))
922
+ if (key.name === 'end') return (back = 0)
923
+ if (key.name === 'home') return (back = 1e6)
924
+ if (key.name === 'k' && !key.ctrl && !key.meta) return kill()
925
+ },
926
+ click: (col, row) => {
927
+ const hit = row === 0 && spots.find((t) => col >= t.from && col < t.to)
928
+ if (hit) (this.jobTab = hit.id), (back = 0)
929
+ },
930
+ draw: (w, h) => {
931
+ const all = jobs()
932
+ if (!all.length) return ['', ` ${c.faint('Nothing runs in the background. The model starts servers and watchers there.')}`, '', ` ${c.faint('Esc close')}`]
933
+ const job = current()
934
+ this.jobTab = job.id
935
+ // the tabs, scrolled so the one shown is on screen
936
+ const label = (j) => ` ${j.exited ? '○' : '●'} #${j.id} ${clip(j.command.replace(/\s+/g, ' '), 18)} `
937
+ let first = 0
938
+ while (first < all.indexOf(job) && all.slice(first, all.indexOf(job) + 1).reduce((n, j) => n + width(label(j)) + 1, 0) > w - 2) first++
939
+ spots = []
940
+ let x = 1
941
+ let bar = ' '
942
+ for (const j of all.slice(first)) {
943
+ const lw = width(label(j))
944
+ if (x + lw > w - 2) break
945
+ spots.push({ from: x, to: x + lw, id: j.id })
946
+ bar += (j === job ? `\x1b[7m${c.brand(c.bold(label(j)))}\x1b[27m` : j.exited ? c.faint(label(j)) : c.muted(label(j))) + ' '
947
+ x += lw + 1
948
+ }
949
+ const hidden = all.length - spots.length
950
+ page = Math.max(1, h - 6)
951
+ const n = h - 5 // tabs, a rule, the command, (the log), a rule, the keys
952
+ const lines = tailLines(job, n + back + 2000) // enough to scroll back through
953
+ back = Math.min(back, Math.max(0, lines.length - n))
954
+ const shown = lines.slice(Math.max(0, lines.length - n - back), lines.length - back)
955
+ const state = job.exited ? c.yellow(`exited with ${job.code}`) : c.green('running')
956
+ const where = back ? c.yellow(` · ${back} line${back > 1 ? 's' : ''} back (End: the newest)`) : ''
957
+ return [
958
+ bar + (hidden ? c.faint(` +${hidden} more`) : ''),
959
+ c.ghost('─'.repeat(w)),
960
+ ` ${c.bold(clip(job.command, w - 40))} ${c.faint('·')} ${state} ${c.faint(`· ${ranFor(job)}`)}${where}`,
961
+ ...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)')}`)),
962
+ c.ghost('─'.repeat(w)),
963
+ ` ${said ? c.yellow(said) : c.faint(`${all.length > 1 ? '←/→ another one · ' : ''}↑/↓ PgUp/PgDn scroll · K ${job.exited ? 'close' : 'stop'} it · Esc close`)}`,
964
+ ]
965
+ },
966
+ })
967
+ }
968
+
863
969
  // Use a chosen set of models for this session: one pins it (no rotation), several rotate among
864
970
  // just those. Remembered for this folder (.heartcode/models.json); the saved ranking is untouched.
865
- async setSession(list) {
971
+ // later: chosen while a task works; it goes on with its models, yours from the next message.
972
+ async setSession(list, later = false) {
866
973
  const { cfg } = this
867
- cfg.session = list // the global #1 (cfg.provider/model) stays, so your whole list and the picker are unchanged
868
- this.saveProjectModels()
869
- this.s = null
870
- this.ui.print(list.length === 1 ? `${c.green('using')} ${c.cyan(list[0].model)} ${c.dim('· pinned for this folder')}` : `${c.green(`using ${list.length} models for this folder`)}: ${c.cyan(list.map((t) => t.model).join(', '))}`)
974
+ const apply = () => {
975
+ cfg.session = list // the global #1 (cfg.provider/model) stays, so your whole list and the picker are unchanged
976
+ this.saveProjectModels()
977
+ this.s = null
978
+ }
979
+ const msg = list.length === 1 ? `${c.green('using')} ${c.cyan(list[0].model)} ${c.dim('· pinned for this folder')}` : `${c.green(`using ${list.length} models for this folder`)}: ${c.cyan(list.map((t) => t.model).join(', '))}`
980
+ if (later) return this.later.push(apply), this.ui.print(`${msg} ${c.dim('· from your next message')}`)
981
+ apply()
982
+ this.ui.print(msg)
871
983
  await this.session()
872
984
  }
873
985
 
874
986
  // Back to auto: your whole list again (#1, then the next when one fails), following the saved
875
987
  // ranking. The folder's remembered choice is cleared.
876
- async auto() {
988
+ async auto(later = false) {
877
989
  const { cfg } = this
878
- delete cfg.session
879
- this.saveProjectModels()
880
- this.s = null
881
- this.ui.print(`${c.green('using')} ${c.dim('auto')} ${c.cyan(`(${this.myModels().length} models)`)}`)
990
+ const apply = () => {
991
+ delete cfg.session
992
+ this.saveProjectModels()
993
+ this.s = null
994
+ }
995
+ const msg = `${c.green('using')} ${c.dim('auto')} ${c.cyan(`(${this.myModels().length} models)`)}`
996
+ if (later) return this.later.push(apply), this.ui.print(`${msg} ${c.dim('· from your next message')}`)
997
+ apply()
998
+ this.ui.print(msg)
882
999
  await this.session()
883
1000
  }
884
1001
 
885
1002
  // The picker: tick the models for this session — one pins it, several rotate among them, all of
886
1003
  // them (or none) is the same as auto (your whole list). "auto" is the first entry.
887
- async chooseModel(filter = '') {
1004
+ async chooseModel(filter = '', later = false) {
888
1005
  const { ui, cfg } = this
889
1006
  const mine = this.myModels()
890
1007
  if (!mine.length) {
@@ -894,18 +1011,21 @@ class App {
894
1011
  const key = (t) => `${t.provider}/${t.model}`
895
1012
  const chosen = new Set((cfg.session ?? mine).map(key)) // pre-ticked: this session's set, or all (auto)
896
1013
  const items = mine.map((t) => ({ label: t.model, t, checked: chosen.has(key(t)), desc: this.modelDesc(t, mine.indexOf(t)) }))
897
- const picked = await ui.pick('Models for this session — tick several to rotate, one to pin (all = auto)', items, { filter, multi: true })
1014
+ // first, standing alone: back to auto (Enter on it, whatever is ticked)
1015
+ 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'}` }
1016
+ const picked = await ui.pick('Models for this session — tick several to rotate, one to pin, or auto', [auto, ...items], { filter, multi: true })
898
1017
  if (!picked) return
1018
+ if (picked.some((it) => it.auto)) return cfg.session ? this.auto(later) : ui.print(c.dim('already on auto'))
899
1019
  const list = picked.map((it) => it.t)
900
- return list.length >= mine.length ? this.auto() : this.setSession(list)
1020
+ return list.length >= mine.length ? this.auto(later) : this.setSession(list, later)
901
1021
  }
902
1022
 
903
1023
  // "/select_model a, b, c": use those models this session (one pins, several rotate). One model:
904
1024
  // "model", "provider model" or "provider/model". "/select_model auto": your whole list. No
905
1025
  // argument: the picker.
906
- async pickModel(args) {
907
- if (!args.length) return this.chooseModel()
908
- if (args.every((a) => isAuto(a))) return this.cfg.session ? this.auto() : this.ui.print(c.dim('already on auto'))
1026
+ async pickModel(args, later = false) {
1027
+ if (!args.length) return this.chooseModel('', later)
1028
+ if (args.every((a) => isAuto(a))) return this.cfg.session ? this.auto(later) : this.ui.print(c.dim('already on auto'))
909
1029
  const raw = args.join(' ')
910
1030
  const specs = raw.includes(',') ? raw.split(',').map((x) => x.trim()).filter(Boolean) : [raw]
911
1031
  const resolve = (spec) => {
@@ -922,9 +1042,9 @@ class App {
922
1042
  for (const spec of specs) (resolve(spec) ? found : missing).push(resolve(spec) ?? spec)
923
1043
  if (missing.length || !found.length) {
924
1044
  if (missing.length) this.ui.print(c.dim(`not in your models: ${missing.join(', ')} · add on /settings`))
925
- return this.chooseModel(specs.length === 1 ? specs[0] : '')
1045
+ return this.chooseModel(specs.length === 1 ? specs[0] : '', later)
926
1046
  }
927
- return this.setSession(found)
1047
+ return this.setSession(found, later)
928
1048
  }
929
1049
 
930
1050
  listProviders() {
@@ -1047,9 +1167,11 @@ function useModel(app, { provider, model }) {
1047
1167
  // The settings page (/settings): on while its dialog is (one at a time).
1048
1168
  let settingsPage = null
1049
1169
 
1170
+ // The browser, with a page. Windows: its URL handler (cmd's start mangles a URL whose arguments
1171
+ // it reads as its own, and wants a quoted empty title first).
1050
1172
  function openBrowser(url) {
1051
1173
  if (process.env.HEART_NO_BROWSER) return
1052
- const [cmd, ...args] = process.platform === 'darwin' ? ['open', url] : process.platform === 'win32' ? ['cmd', '/c', 'start', '', url] : ['xdg-open', url]
1174
+ const [cmd, ...args] = process.platform === 'darwin' ? ['open', url] : process.platform === 'win32' ? ['rundll32', 'url.dll,FileProtocolHandler', url] : ['xdg-open', url]
1053
1175
  spawnSync(cmd, args, { stdio: 'ignore' })
1054
1176
  }
1055
1177
 
@@ -1245,22 +1367,30 @@ async function signInMcp(app, name, signal) {
1245
1367
  return `signed in to ${name} · ${tools.length} tools`
1246
1368
  }
1247
1369
 
1248
- async function slash(app, line) {
1370
+ // working: typed while a task works and run beside it (RIGHT_AWAY): no spinner of its own, nothing
1371
+ // that would end the task's.
1372
+ async function slash(app, line, working = false) {
1249
1373
  const [cmd, ...args] = line.slice(1).trim().split(/\s+/)
1250
1374
  const { ui, cfg } = app
1375
+ const spin = (label) => !working && ui.spinner(label)
1376
+ const unspin = () => !working && ui.stopSpin()
1251
1377
  switch (cmd) {
1252
1378
  case 'close_tab':
1253
- return void (await app.closeTab())
1379
+ return void (await app.closeTab(working))
1254
1380
  case 'exit':
1255
1381
  case 'quit': {
1256
1382
  const n = app.tabs?.list.length ?? 1
1257
- if (n > 1) {
1258
- const go = await ui.pick(`Quit HeartCode? ${n} tabs are open`, [
1383
+ if (n > 1 || working) {
1384
+ const go = await ui.pick(`Quit HeartCode?${working ? ' It is still working: that stops.' : ''}${n > 1 ? ` ${n} tabs are open` : ''}`, [
1259
1385
  { label: 'Yes, quit', desc: 'they come back next time you start HeartCode here', yes: true },
1260
1386
  { label: 'No', desc: 'Alt+W closes just this tab' },
1261
1387
  ])
1262
1388
  if (!go?.yes) return
1263
1389
  }
1390
+ if (!working && app.s?.wrapping) {
1391
+ ui.spinner('keeping what the last task learned · Ctrl+C to quit now')
1392
+ await app.s.wrapping
1393
+ }
1264
1394
  return 'exit'
1265
1395
  }
1266
1396
  case 'reset': {
@@ -1285,11 +1415,12 @@ async function slash(app, line) {
1285
1415
  openBrowser(url)
1286
1416
  ui.print(`${c.info('↗')} ${c.bold('settings')} ${c.muted('opened in your browser:')}\n ${c.faint(url)}`)
1287
1417
  // a dialog until it's turned off: nothing else meanwhile, in any tab (Esc turns it off too).
1288
- // Not busy meanwhile: what's changed on the page applies at once, here too.
1289
- ui.idle()
1418
+ // Not busy meanwhile: what's changed on the page applies at once, here too (opened while a task
1419
+ // works: once it's done).
1420
+ if (!working) ui.idle()
1290
1421
  if (app.tabs) app.tabs.locked = true
1291
1422
  try {
1292
- await ui.pick(`${c.info('↗')} ${c.bold('The settings page is on')}`, [{ label: 'Turn off', desc: 'stops the page and gives HeartCode back' }], { fixed: true })
1423
+ 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.` })
1293
1424
  } finally {
1294
1425
  if (app.tabs) app.tabs.locked = false
1295
1426
  close()
@@ -1309,9 +1440,9 @@ async function slash(app, line) {
1309
1440
  return ui.print(`${c.cyan('/tab')} ${c.faint('a new tab ·')} ${c.cyan('/tab worktree')} ${c.muted('[name]')} ${c.faint('a new tab in its own git worktree ·')} ${c.cyan('/tab')} ${c.muted('<1–' + tabs.list.length + '>')} ${c.faint('go to that tab')}`)
1310
1441
  }
1311
1442
  case 'help':
1312
- return ui.print(app.help())
1443
+ return ui.showText('Commands and keys', app.help())
1313
1444
  case 'select_model':
1314
- return app.pickModel(args)
1445
+ return app.pickModel(args, working)
1315
1446
  case 'rename': {
1316
1447
  const name = args.join(' ').trim() || (await ui.ask(` ${c.bold('Name for this session')}: `, { initial: app.chat.name ?? '' }))?.trim()
1317
1448
  if (!name) return ui.print(c.dim('cancelled'))
@@ -1347,16 +1478,18 @@ async function slash(app, line) {
1347
1478
  const files = [...first.keys()].filter((f) => !want || f.includes(want)).sort()
1348
1479
  if (!files.length) return ui.print(want ? `No changes to ${want} in this session.` : 'No changes in this session yet.')
1349
1480
  let shown = 0
1481
+ const out = []
1350
1482
  for (const rel of files) {
1351
1483
  const abs = path.join(app.root, rel)
1352
1484
  const now = fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null
1353
1485
  const was = first.get(rel)
1354
1486
  if (was === now) continue
1355
1487
  shown++
1356
- if (was === null || now === null) ui.print(`${c.bold(rel)} ${was === null ? c.green('(new)') : c.red('(deleted)')}`)
1357
- if (now !== null) ui.print(renderDiff(diffLines(was ?? '', now), rel, undefined, 3, 400))
1488
+ if (was === null || now === null) out.push(`${c.bold(rel)} ${was === null ? c.green('(new)') : c.red('(deleted)')}`)
1489
+ if (now !== null) out.push(renderDiff(diffLines(was ?? '', now), rel, undefined, 3, 400))
1358
1490
  }
1359
- return ui.print(c.dim(shown ? `${shown} file${shown > 1 ? 's' : ''} changed in this session${files.length > shown ? ` (${files.length - shown} back as they were)` : ''}` : 'every file HeartCode changed is back as it was'))
1491
+ out.push(c.dim(shown ? `${shown} file${shown > 1 ? 's' : ''} changed in this session${files.length > shown ? ` (${files.length - shown} back as they were)` : ''}` : 'every file HeartCode changed is back as it was'))
1492
+ return ui.showText(want ? `Changes to ${want}` : 'Changes in this session', out.join('\n'))
1360
1493
  }
1361
1494
  case 'init': {
1362
1495
  const has = (f) => fs.existsSync(path.join(app.root, f))
@@ -1370,15 +1503,54 @@ async function slash(app, line) {
1370
1503
  const how = copyText(answer)
1371
1504
  return ui.print(c.dim(`copied the last answer (${answer.split('\n').length} lines)${how === 'osc' ? ' through the terminal' : ''}`))
1372
1505
  }
1506
+ case 'background': {
1507
+ const jobs = listJobs(app.root)
1508
+ const label = (j) => `#${j.id} ${clip(j.command, 70)}`
1509
+ if (args[0] === 'off' || args[0] === 'hide') return app.toggleJobs(false)
1510
+ if (args[0] === 'stop') {
1511
+ const j = args[1] ? getJob(args[1]) : null
1512
+ const running = jobs.filter((x) => !x.exited)
1513
+ if (!j && !running.length) return ui.print(c.dim('Nothing is running in the background.'))
1514
+ const pick = j ? { j } : await ui.pick('Stop which one?', running.map((x) => ({ label: label(x), desc: `running · ${ranFor(x)}`, j: x })))
1515
+ if (!pick?.j) return
1516
+ return ui.print(stopJob(pick.j) ? `${c.ok('✓')} stopped ${label(pick.j)}` : c.dim(`#${pick.j.id} had already exited`))
1517
+ }
1518
+ if (args[0] === 'files') return jobs.length ? ui.showText('Background logs', jobs.map((j) => `${label(j)}\n ${c.faint(j.file)}`).join('\n')) : ui.print(c.dim('No background commands yet.'))
1519
+ if (getJob(args[0])) app.jobTab = getJob(args[0]).id // /background 2: its tab
1520
+ return app.toggleJobs(true) // their logs, live, a tab each
1521
+ }
1522
+ case 'context': {
1523
+ const s = app.s
1524
+ if (!s?.messages?.length) return ui.print('Nothing in the context yet: it fills with your first message.')
1525
+ const r = contextReport(s)
1526
+ const share = (n) => (r.window ? `${Math.round((n / r.window) * 100)}%` : '')
1527
+ const bar = (n) => c.brand('█'.repeat(r.window ? Math.round((n / r.window) * 40) : 0) || (n ? '▏' : ''))
1528
+ const row = (name, n, note = '') => ` ${name.padEnd(20)} ${kTokens(n).padStart(6)} ${c.faint(share(n).padStart(4))} ${bar(n)}${note ? ` ${c.faint(note)}` : ''}`
1529
+ const free = Math.max(0, r.compactAt - r.total)
1530
+ ui.showText(
1531
+ 'Context',
1532
+ [
1533
+ `${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)}`) : ''}`,
1534
+ ...r.parts.filter((p) => p.tokens).map((p) => row(p.name, p.tokens, p.note)),
1535
+ ` ${'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`)}`,
1536
+ '',
1537
+ c.bold('Biggest pieces'),
1538
+ ...r.biggest.map((b) => ` ${kTokens(b.tokens).padStart(6)} ${b.what} ${c.faint(b.ago ? `· ${b.ago} message${b.ago > 1 ? 's' : ''} ago` : '· the newest')}`),
1539
+ c.faint(' /compact summarizes it (add what to keep); older tool results become pointers to their files on their own'),
1540
+ ].join('\n'),
1541
+ )
1542
+ return
1543
+ }
1373
1544
  case 'cost': {
1374
1545
  const u = app.chat.usage
1375
1546
  if (!u?.requests) return ui.print('Nothing used yet in this session.')
1376
1547
  const price = app.s?.client.price?.()
1377
- ui.print(`${c.bold('tokens')} ${kTokens(u.input)} in${u.cached ? ` (${kTokens(u.cached)} from the cache)` : ''} · ${kTokens(u.output)} out · ${u.requests} request${u.requests > 1 ? 's' : ''}`)
1378
- return ui.print(
1379
- u.priced
1380
- ? `${c.bold('cost')} ${money(u.cost)}${price ? c.faint(` (${app.inUse()?.model}: $${price.input ?? 0} in / $${price.output ?? 0} out per million tokens, from models.dev)`) : ''}`
1381
- : c.faint(`cost: not known for ${app.inUse()?.model ?? 'this model'} (models.dev doesn't list it; local and subscription models have none)`),
1548
+ return ui.showText(
1549
+ 'Cost',
1550
+ `${c.bold('tokens')} ${kTokens(u.input)} in${u.cached ? ` (${kTokens(u.cached)} from the cache)` : ''} · ${kTokens(u.output)} out · ${u.requests} request${u.requests > 1 ? 's' : ''}\n` +
1551
+ (u.priced
1552
+ ? `${c.bold('cost')} ${money(u.cost)}${price ? c.faint(` (${app.inUse()?.model}: $${price.input ?? 0} in / $${price.output ?? 0} out per million tokens, from models.dev)`) : ''}`
1553
+ : c.faint(`cost: not known for ${app.inUse()?.model ?? 'this model'} (models.dev doesn't list it; local and subscription models have none)`)),
1382
1554
  )
1383
1555
  }
1384
1556
  case 'clear_chat': // a new session; the old one stays in /resume
@@ -1403,7 +1575,7 @@ async function slash(app, line) {
1403
1575
  const head = ` ${cp.ok ? c.green('✓') : c.red('✗')} ${c.bold(cp.name)}${cp.ok ? c.dim(' · ready') : c.yellow(' · needs setup')}`
1404
1576
  return cp.ok ? head : `${head}\n ${c.faint(`install ${cp.need}`)}`
1405
1577
  })
1406
- return ui.print(`${c.bold('External tools HeartCode features use')}\n${rows.join('\n')}`)
1578
+ return ui.showText('External tools HeartCode features use', rows.join('\n'))
1407
1579
  }
1408
1580
  case 'mcp': {
1409
1581
  const all = loadServers(app.root, { includeDisabled: true }) // enabled and off, so off ones are visible
@@ -1420,20 +1592,20 @@ async function slash(app, line) {
1420
1592
  })
1421
1593
  const needs = names.some((n) => running.has(n) && mcpAuth(all[n]) === 'out')
1422
1594
  const off = names.some((n) => !running.has(n))
1423
- return ui.print(`${c.bold('MCP servers')}\n${rows.join('\n')}${needs ? `\n ${c.dim('sign in to a remote one with /login_mcp <name>')}` : ''}${off ? `\n ${c.dim('turn one on in /settings → MCP servers')}` : ''}`)
1595
+ return ui.showText('MCP servers', `${rows.join('\n')}${needs ? `\n ${c.dim('sign in to a remote one with /login_mcp <name>')}` : ''}${off ? `\n ${c.dim('turn one on in /settings → MCP servers')}` : ''}`)
1424
1596
  }
1425
1597
  case 'login_mcp': {
1426
1598
  const remote = app.mcp.names.filter((n) => app.mcp.get(n).url)
1427
1599
  const name = args[0] ?? (await ui.pick('Sign in to which server?', remote.map((n) => ({ label: n, desc: app.mcp.get(n).url, hint: mcpAuth(app.mcp.get(n).cfg) === 'in' ? 'signed in' : 'not signed in' }))))?.label
1428
1600
  if (!name) return remote.length ? undefined : ui.print('No remote MCP servers (ones with a "url") to sign in to.')
1429
1601
  if (!app.mcp.get(name)?.url) return ui.print(`No remote MCP server "${name}".`)
1430
- ui.spinner(`connecting to ${name}`)
1602
+ spin(`connecting to ${name}`)
1431
1603
  try {
1432
1604
  const msg = await signInMcp(app, name, app.signal)
1433
- ui.stopSpin()
1605
+ unspin()
1434
1606
  return ui.print(`${c.green('✓')} ${msg}`)
1435
1607
  } catch (e) {
1436
- ui.stopSpin()
1608
+ unspin()
1437
1609
  return ui.print(`${c.red('✗')} ${e.message}`)
1438
1610
  }
1439
1611
  }
@@ -1450,7 +1622,7 @@ async function slash(app, line) {
1450
1622
  }
1451
1623
  }
1452
1624
  app.reload('skill')
1453
- app.reload('mcp')
1625
+ app.reload('mcp', working) // working: the old servers stop once the task is done
1454
1626
  log('import', chosen.map((it) => `${it.group}: ${it.label}`))
1455
1627
  return
1456
1628
  }
@@ -1458,20 +1630,21 @@ async function slash(app, line) {
1458
1630
  const url = args.find((a) => !a.startsWith('--'))
1459
1631
  if (!url) return ui.print('Usage: /install_skill <github repo or a SKILL.md url> [--project]')
1460
1632
  const scope = args.includes('--project') ? 'project' : 'global'
1461
- ui.spinner(`installing from ${url}`)
1633
+ spin(`installing from ${url}`)
1462
1634
  try {
1463
1635
  const msg = await installSkill(app.root, url, scope, { signal: app.signal })
1464
- ui.stopSpin()
1636
+ unspin()
1465
1637
  app.reload('skill')
1466
1638
  return ui.print(`${c.green('✓')} ${msg}${scope === 'project' ? ' (this folder)' : ''} ${c.dim('· run with /skill:<name>, /help lists them')}`)
1467
1639
  } catch (e) {
1468
- ui.stopSpin()
1640
+ unspin()
1469
1641
  return ui.print(`${c.red('✗')} could not install: ${e.message}`)
1470
1642
  }
1471
1643
  }
1472
1644
  case 'btw':
1473
- return app.btw(line.trim().replace(/^\/btw\b/, '').trim())
1645
+ return app.btw(line.trim().replace(/^\/btw\b/, '').trim(), working)
1474
1646
  case 'voice': {
1647
+ if (working) return ui.dictateIn() // into the box, as Space does while it works
1475
1648
  const text = await ui.dictate()
1476
1649
  if (text) app.nextInput = text // in the box, to read over and send
1477
1650
  return
@@ -1502,7 +1675,7 @@ async function slash(app, line) {
1502
1675
  return app.save()
1503
1676
  }
1504
1677
  case 'model_info':
1505
- return ui.print(`${c.cyan(s.client.model)}\n${describe(s.profile, s.strat)}`)
1678
+ return ui.showText(s.client.model, describe(s.profile, s.strat))
1506
1679
  case 'test_model': {
1507
1680
  const tested = await getProfile(app.client(s.client.provider, s.client.model), ui, true, app.signal) // tested on a fresh connection (requests not fitted to what it was thought to do), and saved
1508
1681
  s.reset()
@@ -1544,7 +1717,15 @@ async function repl(app, f = {}) {
1544
1717
  ui.onDoubleEscape = () => '/rewind'
1545
1718
  let ctl = null
1546
1719
  ui.onEscape = () => ctl?.abort()
1547
- ui.onBtw = (q) => app.btw(q, true) // /btw typed while it works
1720
+ // a command typed while it works: run now, beside the task, if it leaves the conversation alone
1721
+ ui.onPanel = () => app.toggleJobs() // Alt+B: the background commands' logs, side by side, live
1722
+ ui.onNow = (line) => {
1723
+ if (!RIGHT_AWAY.has(/^\/([\w-]+)/.exec(line)?.[1]) || !app.isCommand(line)) return false
1724
+ slash(app, line, true)
1725
+ .then((r) => r === 'exit' && (ctl?.abort(), app.save(), quit()))
1726
+ .catch((e) => (log('error', e.stack), ui.print(c.red(`error: ${e.message}`))))
1727
+ return true
1728
+ }
1548
1729
  ui.onWaiting = (question) => notify(cfg, 'waiting', `⏳ Waiting for you · ${path.basename(app.root)}\n${clip(question.replace(/\x1b\[[0-9;]*m/g, '').replace(/\s*›\s*$/, '').replace(/^\?\s*/, '').trim(), 1000)}`) // a question or a permission while it works (Telegram)
1549
1730
  ui.isCommand = (l) => app.isCommand(l)
1550
1731
  loadPrices().then(() => ui.render?.()) // models.dev: what each model can do, for the model lists
@@ -1605,6 +1786,7 @@ async function repl(app, f = {}) {
1605
1786
  // Pinned to the top of the screen; /clear_chat and scrolling leave it alone.
1606
1787
  const home = process.env.HOME
1607
1788
  const where = home && app.root.startsWith(home) ? '~' + app.root.slice(home.length) : app.root
1789
+ ui.folder = app.root // what a double click on the header's folder copies
1608
1790
  ui.header = (cols = 100) => [
1609
1791
  `${c.brand('♥')} ${c.bright(c.bold('HeartCode'))} ${c.faint(VERSION)} ${c.muted(where.length > cols - 16 ? '…' + where.slice(-(cols - 17)) : where)}`,
1610
1792
  [['/', '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(' · ')),
@@ -1620,6 +1802,8 @@ async function repl(app, f = {}) {
1620
1802
  if (f['resume-id']) await app.resume(loadChat(f['resume-id']))
1621
1803
  else if (f.resume) await app.resume()
1622
1804
  if (f.model) useModel(app, f.model) // a continued tab's own model
1805
+ // models this folder picked earlier (/select_model): said, with the way back to your whole list
1806
+ if (app.folderModels && cfg.session?.length) ui.print(`${c.muted('this folder uses')} ${c.cyan(cfg.session.map((t) => t.model).join(', '))} ${c.faint(`(picked earlier) · ${c.cyan('/select_model auto')} for your whole list again`)}`)
1623
1807
  app.tabs?.onChange?.() // the conversation it opened with
1624
1808
  for (;;) {
1625
1809
  const line = await ui.ask(` ${c.magenta('♥')} `, { suggest: true, initial: app.nextInput, history: true })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heartcode",
3
- "version": "0.1.30",
3
+ "version": "0.1.33",
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
@@ -156,7 +156,7 @@ Instructions from the user (follow them):
156
156
  ## command-timeout
157
157
 
158
158
  <!-- Added to a command's result when it ran too long and was stopped. {{root}}: the project folder. -->
159
- (It ran for more than 2 minutes and was stopped. Searching the whole disk or home folder is the usual cause: the project is {{root}}; search inside it, with the search tool. If it's a server or a watcher, run it in the background with its output to a file.)
159
+ (It ran for more than 2 minutes and was stopped. Searching the whole disk or home folder is the usual cause: the project is {{root}}; search inside it, with the search tool. If it's a server or a watcher, run it again with background: true.)
160
160
 
161
161
  ## command-too-wide
162
162
 
@@ -196,7 +196,26 @@ Create a file, or overwrite one with its full content. With append: true, add to
196
196
 
197
197
  ## tool-run_command
198
198
 
199
- Run a shell command in the project folder; returns the exit code and output.
199
+ Run a shell command in the project folder; returns the exit code and output. A command that keeps running (a dev server, a watcher, a long build): set background true; it answers after a few seconds with its id and first output, and keeps running (the background tool reads it later).
200
+
201
+ ## tool-background
202
+
203
+ <!-- The background tool: commands started with run_command background true. -->
204
+ Commands started with run_command background true. action "output": what one printed since you last looked (id; the newest if left out). "list": all of them, running or exited. "stop": stop one (id). Stop what you started once you no longer need it.
205
+
206
+ ## background-started
207
+
208
+ <!-- run_command's result for a command started in the background. {{id}}, {{running}}, {{code}} (when it exited), {{output}}: what it printed so far, {{file}}: its whole output. -->
209
+ {{#if running}}Started in the background as #{{id}}; it is still running.{{else}}Started as #{{id}}, but it has already exited with {{code}}.{{/if}} Its output so far:
210
+ {{output}}
211
+ (All of it goes to {{file}}. background action "output" shows what's new, "stop" stops it.)
212
+
213
+ ## background-ended
214
+
215
+ <!-- Told to the model at its next step when commands it started in the background have ended. {{jobs}}: one line each. -->
216
+ (Background commands that have ended since your last step:
217
+ {{jobs}}
218
+ background action "output" shows what each printed last.)
200
219
 
201
220
  ## tool-mcp
202
221