heartcode 0.1.27 → 0.1.32

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,10 +5,12 @@ 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'
13
+ import { notify } from '../src/telegram.js'
12
14
  import { log, LOG_FILE, LOG_DIR, requestLog, useRequestLog, useLogs, pruneLogs, logDays } from '../src/log.js'
13
15
  import { prompt, usePromptsFrom, reloadPrompts } from '../src/prompts.js'
14
16
  import { newChat, saveChat, listChats, loadChat, restoreFiles, ago, forkChat, exportChat } from '../src/sessions.js'
@@ -116,6 +118,8 @@ const SECTIONS = [
116
118
  ['/init', 'look at the project and write AGENTS.md: its commands, conventions and layout'],
117
119
  ['/btw', 'ask something on the side, also while it works; the answer stays out of the conversation', true],
118
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],
119
123
  ['/model_info', 'what the model can do and how HeartCode uses it'],
120
124
  ['/test_model', 'test the model for real (otherwise what it can do comes from models.dev, or your settings)'],
121
125
  ['/tidy_memory', 'merge, update and link the memory notes now'],
@@ -134,7 +138,12 @@ const SECTIONS = [
134
138
  ['/exit', 'quit HeartCode (Alt+W closes just this tab)'],
135
139
  ]],
136
140
  ]
137
- 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'])
138
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')
139
148
  const SLASH = helpText(SECTIONS)
140
149
 
@@ -147,11 +156,12 @@ function keysHelp(keys = {}) {
147
156
  const tabs = /(^|,)alt\+[1-9]/.test(Object.keys(keys).join(','))
148
157
  const rows = [
149
158
  ['Space', 'start voice input (when the input box is empty)'],
150
- ['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)'],
151
160
  ['Option/Shift/Ctrl+Enter', 'new line in the box'],
152
161
  ['Esc', 'stop the task (press twice to confirm)'],
153
162
  ['Esc Esc', 'rewind to an earlier message (at the prompt)'],
154
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)"],
155
165
  [forAct('new_tab'), 'new tab'],
156
166
  [forAct('close_tab'), 'close this tab'],
157
167
  [forAct('next_tab'), 'next tab'],
@@ -194,7 +204,7 @@ const mask = (k) => (k ? (k.length > 12 ? `${k.slice(0, 4)}…${k.slice(-4)}` :
194
204
  // overrides it — see App.status for the item names and format.
195
205
  const DEFAULT_STATUS = [
196
206
  { left: ['provider', 'model'], right: ['mode', 'thinking', 'images'] },
197
- { left: ['ctx', 'tps', 'autocompact'], right: ['permissions', 'worktree', 'cost'] },
207
+ { left: ['ctx', 'tps', 'autocompact'], right: ['background', 'permissions', 'worktree', 'cost'] },
198
208
  ]
199
209
 
200
210
  class App {
@@ -219,7 +229,7 @@ class App {
219
229
  if (this.cfg.session) return
220
230
  const saved = readJson(path.join(this.root, '.heartcode', 'models.json'), null)
221
231
  const valid = (saved?.session ?? []).filter((t) => t?.provider && t?.model && this.cfg.providers[t.provider])
222
- if (valid.length) this.cfg.session = valid
232
+ if (valid.length) [this.cfg.session, this.folderModels] = [valid, true]
223
233
  }
224
234
 
225
235
  saveProjectModels() {
@@ -572,7 +582,7 @@ class App {
572
582
  // Built-in commands (/name), then the skills you can type, namespaced as /skill:name so they're
573
583
  // easy to tell apart from HeartCode's own commands (and can't clash with them).
574
584
  commands() {
575
- const mine = [...this.skills.values()].filter((k) => k.use !== 'model').map((k) => [`/skill:${k.name}`, k.description, true])
585
+ const mine = [...this.skills.values()].filter((k) => k.use !== 'model').map((k) => [`/skill:${k.name}`, k.description, true]).sort(byName)
576
586
  return [...COMMANDS, ...mine]
577
587
  }
578
588
 
@@ -678,6 +688,7 @@ class App {
678
688
  cost: null,
679
689
  autocompact: cfg.autoCompact === false ? c.faint('auto-compact off') : null,
680
690
  worktree: this.worktree ? c.info(`⎇ ${this.worktree.branch}`) : null,
691
+ background: runningJobs(this.root).length ? c.info(`⚙ ${runningJobs(this.root).length} running`) + c.faint(' Alt+B') : null,
681
692
  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],
682
693
  }
683
694
  if (strat) {
@@ -692,7 +703,9 @@ class App {
692
703
  }
693
704
  const sep = c.ghost(' │ ')
694
705
  const vis = (str) => width(str.replace(/\x1b\[[0-9;]*m/g, ''))
695
- const layout = Array.isArray(cfg.statusBar) && cfg.statusBar.length ? cfg.statusBar : DEFAULT_STATUS
706
+ let layout = Array.isArray(cfg.statusBar) && cfg.statusBar.length ? cfg.statusBar : DEFAULT_STATUS
707
+ // commands running in the background are shown also on a bar laid out before there was this item
708
+ 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 ?? [])] }))]
696
709
  const line = (row) => {
697
710
  const names = (g) => (g ?? []).map((t) => parts[t]).filter(Boolean).join(sep)
698
711
  const left = names(Array.isArray(row) ? row : row?.left)
@@ -757,6 +770,17 @@ class App {
757
770
  Object.assign(this.s, { mcp: this.mcp, memory: this.memory, skills: this.skills, director: this.director })
758
771
  this.s.team = () => this.team() // your other models: a job this one can't do goes to one of them
759
772
  this.s.engineFor = (t) => this.engine(t.provider, t.model, ui, undefined, { quiet: true })
773
+ // A model's context window, read from its saved profile (no probe, no network): so the agent can
774
+ // see, before compacting, whether another model in the list has room for the whole conversation.
775
+ this.s.windowOf = (t) => {
776
+ try {
777
+ const cl = this.client(t.provider, t.model)
778
+ const profile = loadProfile(cl) || profileFrom(cl, limitsOf(t.provider, cl.baseUrl, t.model))
779
+ return strategy(profile, cfg).context || 0
780
+ } catch {
781
+ return 0
782
+ }
783
+ }
760
784
  this.s.failures = this.failures
761
785
  if (this.allowTools?.length) this.s.allowTools = toolNames(this.allowTools) // headless --allowedTools
762
786
  if (this.denyTools?.length) this.s.denyTools = toolNames(this.denyTools)
@@ -848,31 +872,133 @@ class App {
848
872
  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}`))
849
873
  }
850
874
 
875
+ // Alt+B, /background: the background commands' logs in a dialog, one at a time with a tab each.
876
+ // ←/→ (or a click on a tab): another one; ↑/↓, PgUp/PgDn, the wheel: back in its log (End: the
877
+ // newest again); K twice: stop it and close its tab; Esc or Alt+B: closed.
878
+ toggleJobs(on = !this.jobsShown) {
879
+ const { ui } = this
880
+ if (!on) return ui.setDialog(null)
881
+ this.jobsShown = true
882
+ const ERROR = /\b(error|errors|failed|fail|exception|traceback|panic|fatal)\b/i
883
+ const jobs = () => listJobs(this.root)
884
+ const current = () => jobs().find((j) => j.id === this.jobTab) ?? jobs().findLast((j) => !j.exited) ?? jobs().at(-1)
885
+ let spots = [] // where each tab is on its row: { from, to, id }
886
+ let back = 0 // lines scrolled back from the newest (0: following it)
887
+ let page = 10
888
+ let armed = 0 // K pressed once, when
889
+ let said = '' // a line for the footer (K's question)
890
+ const go = (d) => {
891
+ const all = jobs()
892
+ if (!all.length) return
893
+ this.jobTab = all[(all.indexOf(current()) + d + all.length) % all.length].id
894
+ back = 0
895
+ }
896
+ const kill = () => {
897
+ const job = current()
898
+ if (!job) return
899
+ if (Date.now() - armed > 2500) return (armed = Date.now()), (said = `Press K again to ${job.exited ? 'close' : 'stop and close'} #${job.id}`)
900
+ armed = 0
901
+ said = ''
902
+ const all = jobs()
903
+ const next = all[all.indexOf(job) + 1] ?? all[all.indexOf(job) - 1]
904
+ removeJob(job)
905
+ ui.print(c.dim(`${job.exited ? 'closed' : 'stopped'} #${job.id} ${clip(job.command, 80)}`))
906
+ if (!next) return this.toggleJobs(false)
907
+ this.jobTab = next.id
908
+ back = 0
909
+ }
910
+ ui.setDialog({
911
+ title: 'Background commands',
912
+ toggle: 'background_log', // Alt+B closes it too
913
+ close: () => (this.jobsShown = false),
914
+ key: (key) => {
915
+ if (key.name !== 'k') (armed = 0), (said = '')
916
+ if (key.name === 'left' || key.name === 'right') return go(key.name === 'left' ? -1 : 1)
917
+ if (key.name === 'up' || key.name === 'down') return (back = Math.max(0, back + (key.name === 'up' ? (key.wheel ? 3 : 1) : key.wheel ? -3 : -1)))
918
+ if (key.name === 'pageup' || key.name === 'pagedown') return (back = Math.max(0, back + (key.name === 'pageup' ? page : -page)))
919
+ if (key.name === 'end') return (back = 0)
920
+ if (key.name === 'home') return (back = 1e6)
921
+ if (key.name === 'k' && !key.ctrl && !key.meta) return kill()
922
+ },
923
+ click: (col, row) => {
924
+ const hit = row === 0 && spots.find((t) => col >= t.from && col < t.to)
925
+ if (hit) (this.jobTab = hit.id), (back = 0)
926
+ },
927
+ draw: (w, h) => {
928
+ const all = jobs()
929
+ if (!all.length) return ['', ` ${c.faint('Nothing runs in the background. The model starts servers and watchers there.')}`, '', ` ${c.faint('Esc close')}`]
930
+ const job = current()
931
+ this.jobTab = job.id
932
+ // the tabs, scrolled so the one shown is on screen
933
+ const label = (j) => ` ${j.exited ? '○' : '●'} #${j.id} ${clip(j.command.replace(/\s+/g, ' '), 18)} `
934
+ let first = 0
935
+ while (first < all.indexOf(job) && all.slice(first, all.indexOf(job) + 1).reduce((n, j) => n + width(label(j)) + 1, 0) > w - 2) first++
936
+ spots = []
937
+ let x = 1
938
+ let bar = ' '
939
+ for (const j of all.slice(first)) {
940
+ const lw = width(label(j))
941
+ if (x + lw > w - 2) break
942
+ spots.push({ from: x, to: x + lw, id: j.id })
943
+ bar += (j === job ? `\x1b[7m${c.brand(c.bold(label(j)))}\x1b[27m` : j.exited ? c.faint(label(j)) : c.muted(label(j))) + ' '
944
+ x += lw + 1
945
+ }
946
+ const hidden = all.length - spots.length
947
+ page = Math.max(1, h - 6)
948
+ const n = h - 5 // tabs, a rule, the command, (the log), a rule, the keys
949
+ const lines = tailLines(job, n + back + 2000) // enough to scroll back through
950
+ back = Math.min(back, Math.max(0, lines.length - n))
951
+ const shown = lines.slice(Math.max(0, lines.length - n - back), lines.length - back)
952
+ const state = job.exited ? c.yellow(`exited with ${job.code}`) : c.green('running')
953
+ const where = back ? c.yellow(` · ${back} line${back > 1 ? 's' : ''} back (End: the newest)`) : ''
954
+ return [
955
+ bar + (hidden ? c.faint(` +${hidden} more`) : ''),
956
+ c.ghost('─'.repeat(w)),
957
+ ` ${c.bold(clip(job.command, w - 40))} ${c.faint('·')} ${state} ${c.faint(`· ${ranFor(job)}`)}${where}`,
958
+ ...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)')}`)),
959
+ c.ghost('─'.repeat(w)),
960
+ ` ${said ? c.yellow(said) : c.faint(`${all.length > 1 ? '←/→ another one · ' : ''}↑/↓ PgUp/PgDn scroll · K ${job.exited ? 'close' : 'stop'} it · Esc close`)}`,
961
+ ]
962
+ },
963
+ })
964
+ }
965
+
851
966
  // Use a chosen set of models for this session: one pins it (no rotation), several rotate among
852
967
  // just those. Remembered for this folder (.heartcode/models.json); the saved ranking is untouched.
853
- async setSession(list) {
968
+ // later: chosen while a task works; it goes on with its models, yours from the next message.
969
+ async setSession(list, later = false) {
854
970
  const { cfg } = this
855
- cfg.session = list // the global #1 (cfg.provider/model) stays, so your whole list and the picker are unchanged
856
- this.saveProjectModels()
857
- this.s = null
858
- 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(', '))}`)
971
+ const apply = () => {
972
+ cfg.session = list // the global #1 (cfg.provider/model) stays, so your whole list and the picker are unchanged
973
+ this.saveProjectModels()
974
+ this.s = null
975
+ }
976
+ 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(', '))}`
977
+ if (later) return this.later.push(apply), this.ui.print(`${msg} ${c.dim('· from your next message')}`)
978
+ apply()
979
+ this.ui.print(msg)
859
980
  await this.session()
860
981
  }
861
982
 
862
983
  // Back to auto: your whole list again (#1, then the next when one fails), following the saved
863
984
  // ranking. The folder's remembered choice is cleared.
864
- async auto() {
985
+ async auto(later = false) {
865
986
  const { cfg } = this
866
- delete cfg.session
867
- this.saveProjectModels()
868
- this.s = null
869
- this.ui.print(`${c.green('using')} ${c.dim('auto')} ${c.cyan(`(${this.myModels().length} models)`)}`)
987
+ const apply = () => {
988
+ delete cfg.session
989
+ this.saveProjectModels()
990
+ this.s = null
991
+ }
992
+ const msg = `${c.green('using')} ${c.dim('auto')} ${c.cyan(`(${this.myModels().length} models)`)}`
993
+ if (later) return this.later.push(apply), this.ui.print(`${msg} ${c.dim('· from your next message')}`)
994
+ apply()
995
+ this.ui.print(msg)
870
996
  await this.session()
871
997
  }
872
998
 
873
999
  // The picker: tick the models for this session — one pins it, several rotate among them, all of
874
1000
  // them (or none) is the same as auto (your whole list). "auto" is the first entry.
875
- async chooseModel(filter = '') {
1001
+ async chooseModel(filter = '', later = false) {
876
1002
  const { ui, cfg } = this
877
1003
  const mine = this.myModels()
878
1004
  if (!mine.length) {
@@ -882,18 +1008,21 @@ class App {
882
1008
  const key = (t) => `${t.provider}/${t.model}`
883
1009
  const chosen = new Set((cfg.session ?? mine).map(key)) // pre-ticked: this session's set, or all (auto)
884
1010
  const items = mine.map((t) => ({ label: t.model, t, checked: chosen.has(key(t)), desc: this.modelDesc(t, mine.indexOf(t)) }))
885
- const picked = await ui.pick('Models for this session — tick several to rotate, one to pin (all = auto)', items, { filter, multi: true })
1011
+ // first, standing alone: back to auto (Enter on it, whatever is ticked)
1012
+ 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'}` }
1013
+ const picked = await ui.pick('Models for this session — tick several to rotate, one to pin, or auto', [auto, ...items], { filter, multi: true })
886
1014
  if (!picked) return
1015
+ if (picked.some((it) => it.auto)) return cfg.session ? this.auto(later) : ui.print(c.dim('already on auto'))
887
1016
  const list = picked.map((it) => it.t)
888
- return list.length >= mine.length ? this.auto() : this.setSession(list)
1017
+ return list.length >= mine.length ? this.auto(later) : this.setSession(list, later)
889
1018
  }
890
1019
 
891
1020
  // "/select_model a, b, c": use those models this session (one pins, several rotate). One model:
892
1021
  // "model", "provider model" or "provider/model". "/select_model auto": your whole list. No
893
1022
  // argument: the picker.
894
- async pickModel(args) {
895
- if (!args.length) return this.chooseModel()
896
- if (args.every((a) => isAuto(a))) return this.cfg.session ? this.auto() : this.ui.print(c.dim('already on auto'))
1023
+ async pickModel(args, later = false) {
1024
+ if (!args.length) return this.chooseModel('', later)
1025
+ if (args.every((a) => isAuto(a))) return this.cfg.session ? this.auto(later) : this.ui.print(c.dim('already on auto'))
897
1026
  const raw = args.join(' ')
898
1027
  const specs = raw.includes(',') ? raw.split(',').map((x) => x.trim()).filter(Boolean) : [raw]
899
1028
  const resolve = (spec) => {
@@ -910,9 +1039,9 @@ class App {
910
1039
  for (const spec of specs) (resolve(spec) ? found : missing).push(resolve(spec) ?? spec)
911
1040
  if (missing.length || !found.length) {
912
1041
  if (missing.length) this.ui.print(c.dim(`not in your models: ${missing.join(', ')} · add on /settings`))
913
- return this.chooseModel(specs.length === 1 ? specs[0] : '')
1042
+ return this.chooseModel(specs.length === 1 ? specs[0] : '', later)
914
1043
  }
915
- return this.setSession(found)
1044
+ return this.setSession(found, later)
916
1045
  }
917
1046
 
918
1047
  listProviders() {
@@ -1233,22 +1362,30 @@ async function signInMcp(app, name, signal) {
1233
1362
  return `signed in to ${name} · ${tools.length} tools`
1234
1363
  }
1235
1364
 
1236
- async function slash(app, line) {
1365
+ // working: typed while a task works and run beside it (RIGHT_AWAY): no spinner of its own, nothing
1366
+ // that would end the task's.
1367
+ async function slash(app, line, working = false) {
1237
1368
  const [cmd, ...args] = line.slice(1).trim().split(/\s+/)
1238
1369
  const { ui, cfg } = app
1370
+ const spin = (label) => !working && ui.spinner(label)
1371
+ const unspin = () => !working && ui.stopSpin()
1239
1372
  switch (cmd) {
1240
1373
  case 'close_tab':
1241
- return void (await app.closeTab())
1374
+ return void (await app.closeTab(working))
1242
1375
  case 'exit':
1243
1376
  case 'quit': {
1244
1377
  const n = app.tabs?.list.length ?? 1
1245
- if (n > 1) {
1246
- const go = await ui.pick(`Quit HeartCode? ${n} tabs are open`, [
1378
+ if (n > 1 || working) {
1379
+ const go = await ui.pick(`Quit HeartCode?${working ? ' It is still working: that stops.' : ''}${n > 1 ? ` ${n} tabs are open` : ''}`, [
1247
1380
  { label: 'Yes, quit', desc: 'they come back next time you start HeartCode here', yes: true },
1248
1381
  { label: 'No', desc: 'Alt+W closes just this tab' },
1249
1382
  ])
1250
1383
  if (!go?.yes) return
1251
1384
  }
1385
+ if (!working && app.s?.wrapping) {
1386
+ ui.spinner('keeping what the last task learned · Ctrl+C to quit now')
1387
+ await app.s.wrapping
1388
+ }
1252
1389
  return 'exit'
1253
1390
  }
1254
1391
  case 'reset': {
@@ -1273,11 +1410,12 @@ async function slash(app, line) {
1273
1410
  openBrowser(url)
1274
1411
  ui.print(`${c.info('↗')} ${c.bold('settings')} ${c.muted('opened in your browser:')}\n ${c.faint(url)}`)
1275
1412
  // a dialog until it's turned off: nothing else meanwhile, in any tab (Esc turns it off too).
1276
- // Not busy meanwhile: what's changed on the page applies at once, here too.
1277
- ui.idle()
1413
+ // Not busy meanwhile: what's changed on the page applies at once, here too (opened while a task
1414
+ // works: once it's done).
1415
+ if (!working) ui.idle()
1278
1416
  if (app.tabs) app.tabs.locked = true
1279
1417
  try {
1280
- 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 })
1418
+ 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.` })
1281
1419
  } finally {
1282
1420
  if (app.tabs) app.tabs.locked = false
1283
1421
  close()
@@ -1297,9 +1435,9 @@ async function slash(app, line) {
1297
1435
  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')}`)
1298
1436
  }
1299
1437
  case 'help':
1300
- return ui.print(app.help())
1438
+ return ui.showText('Commands and keys', app.help())
1301
1439
  case 'select_model':
1302
- return app.pickModel(args)
1440
+ return app.pickModel(args, working)
1303
1441
  case 'rename': {
1304
1442
  const name = args.join(' ').trim() || (await ui.ask(` ${c.bold('Name for this session')}: `, { initial: app.chat.name ?? '' }))?.trim()
1305
1443
  if (!name) return ui.print(c.dim('cancelled'))
@@ -1335,16 +1473,18 @@ async function slash(app, line) {
1335
1473
  const files = [...first.keys()].filter((f) => !want || f.includes(want)).sort()
1336
1474
  if (!files.length) return ui.print(want ? `No changes to ${want} in this session.` : 'No changes in this session yet.')
1337
1475
  let shown = 0
1476
+ const out = []
1338
1477
  for (const rel of files) {
1339
1478
  const abs = path.join(app.root, rel)
1340
1479
  const now = fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null
1341
1480
  const was = first.get(rel)
1342
1481
  if (was === now) continue
1343
1482
  shown++
1344
- if (was === null || now === null) ui.print(`${c.bold(rel)} ${was === null ? c.green('(new)') : c.red('(deleted)')}`)
1345
- if (now !== null) ui.print(renderDiff(diffLines(was ?? '', now), rel, undefined, 3, 400))
1483
+ if (was === null || now === null) out.push(`${c.bold(rel)} ${was === null ? c.green('(new)') : c.red('(deleted)')}`)
1484
+ if (now !== null) out.push(renderDiff(diffLines(was ?? '', now), rel, undefined, 3, 400))
1346
1485
  }
1347
- 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'))
1486
+ 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'))
1487
+ return ui.showText(want ? `Changes to ${want}` : 'Changes in this session', out.join('\n'))
1348
1488
  }
1349
1489
  case 'init': {
1350
1490
  const has = (f) => fs.existsSync(path.join(app.root, f))
@@ -1358,15 +1498,54 @@ async function slash(app, line) {
1358
1498
  const how = copyText(answer)
1359
1499
  return ui.print(c.dim(`copied the last answer (${answer.split('\n').length} lines)${how === 'osc' ? ' through the terminal' : ''}`))
1360
1500
  }
1501
+ case 'background': {
1502
+ const jobs = listJobs(app.root)
1503
+ const label = (j) => `#${j.id} ${clip(j.command, 70)}`
1504
+ if (args[0] === 'off' || args[0] === 'hide') return app.toggleJobs(false)
1505
+ if (args[0] === 'stop') {
1506
+ const j = args[1] ? getJob(args[1]) : null
1507
+ const running = jobs.filter((x) => !x.exited)
1508
+ if (!j && !running.length) return ui.print(c.dim('Nothing is running in the background.'))
1509
+ const pick = j ? { j } : await ui.pick('Stop which one?', running.map((x) => ({ label: label(x), desc: `running · ${ranFor(x)}`, j: x })))
1510
+ if (!pick?.j) return
1511
+ return ui.print(stopJob(pick.j) ? `${c.ok('✓')} stopped ${label(pick.j)}` : c.dim(`#${pick.j.id} had already exited`))
1512
+ }
1513
+ 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.'))
1514
+ if (getJob(args[0])) app.jobTab = getJob(args[0]).id // /background 2: its tab
1515
+ return app.toggleJobs(true) // their logs, live, a tab each
1516
+ }
1517
+ case 'context': {
1518
+ const s = app.s
1519
+ if (!s?.messages?.length) return ui.print('Nothing in the context yet: it fills with your first message.')
1520
+ const r = contextReport(s)
1521
+ const share = (n) => (r.window ? `${Math.round((n / r.window) * 100)}%` : '')
1522
+ const bar = (n) => c.brand('█'.repeat(r.window ? Math.round((n / r.window) * 40) : 0) || (n ? '▏' : ''))
1523
+ const row = (name, n, note = '') => ` ${name.padEnd(20)} ${kTokens(n).padStart(6)} ${c.faint(share(n).padStart(4))} ${bar(n)}${note ? ` ${c.faint(note)}` : ''}`
1524
+ const free = Math.max(0, r.compactAt - r.total)
1525
+ ui.showText(
1526
+ 'Context',
1527
+ [
1528
+ `${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)}`) : ''}`,
1529
+ ...r.parts.filter((p) => p.tokens).map((p) => row(p.name, p.tokens, p.note)),
1530
+ ` ${'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`)}`,
1531
+ '',
1532
+ c.bold('Biggest pieces'),
1533
+ ...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')}`),
1534
+ c.faint(' /compact summarizes it (add what to keep); older tool results become pointers to their files on their own'),
1535
+ ].join('\n'),
1536
+ )
1537
+ return
1538
+ }
1361
1539
  case 'cost': {
1362
1540
  const u = app.chat.usage
1363
1541
  if (!u?.requests) return ui.print('Nothing used yet in this session.')
1364
1542
  const price = app.s?.client.price?.()
1365
- 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' : ''}`)
1366
- return ui.print(
1367
- u.priced
1368
- ? `${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)`) : ''}`
1369
- : c.faint(`cost: not known for ${app.inUse()?.model ?? 'this model'} (models.dev doesn't list it; local and subscription models have none)`),
1543
+ return ui.showText(
1544
+ 'Cost',
1545
+ `${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` +
1546
+ (u.priced
1547
+ ? `${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)`) : ''}`
1548
+ : c.faint(`cost: not known for ${app.inUse()?.model ?? 'this model'} (models.dev doesn't list it; local and subscription models have none)`)),
1370
1549
  )
1371
1550
  }
1372
1551
  case 'clear_chat': // a new session; the old one stays in /resume
@@ -1391,7 +1570,7 @@ async function slash(app, line) {
1391
1570
  const head = ` ${cp.ok ? c.green('✓') : c.red('✗')} ${c.bold(cp.name)}${cp.ok ? c.dim(' · ready') : c.yellow(' · needs setup')}`
1392
1571
  return cp.ok ? head : `${head}\n ${c.faint(`install ${cp.need}`)}`
1393
1572
  })
1394
- return ui.print(`${c.bold('External tools HeartCode features use')}\n${rows.join('\n')}`)
1573
+ return ui.showText('External tools HeartCode features use', rows.join('\n'))
1395
1574
  }
1396
1575
  case 'mcp': {
1397
1576
  const all = loadServers(app.root, { includeDisabled: true }) // enabled and off, so off ones are visible
@@ -1408,20 +1587,20 @@ async function slash(app, line) {
1408
1587
  })
1409
1588
  const needs = names.some((n) => running.has(n) && mcpAuth(all[n]) === 'out')
1410
1589
  const off = names.some((n) => !running.has(n))
1411
- 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')}` : ''}`)
1590
+ 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')}` : ''}`)
1412
1591
  }
1413
1592
  case 'login_mcp': {
1414
1593
  const remote = app.mcp.names.filter((n) => app.mcp.get(n).url)
1415
1594
  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
1416
1595
  if (!name) return remote.length ? undefined : ui.print('No remote MCP servers (ones with a "url") to sign in to.')
1417
1596
  if (!app.mcp.get(name)?.url) return ui.print(`No remote MCP server "${name}".`)
1418
- ui.spinner(`connecting to ${name}`)
1597
+ spin(`connecting to ${name}`)
1419
1598
  try {
1420
1599
  const msg = await signInMcp(app, name, app.signal)
1421
- ui.stopSpin()
1600
+ unspin()
1422
1601
  return ui.print(`${c.green('✓')} ${msg}`)
1423
1602
  } catch (e) {
1424
- ui.stopSpin()
1603
+ unspin()
1425
1604
  return ui.print(`${c.red('✗')} ${e.message}`)
1426
1605
  }
1427
1606
  }
@@ -1438,7 +1617,7 @@ async function slash(app, line) {
1438
1617
  }
1439
1618
  }
1440
1619
  app.reload('skill')
1441
- app.reload('mcp')
1620
+ app.reload('mcp', working) // working: the old servers stop once the task is done
1442
1621
  log('import', chosen.map((it) => `${it.group}: ${it.label}`))
1443
1622
  return
1444
1623
  }
@@ -1446,20 +1625,21 @@ async function slash(app, line) {
1446
1625
  const url = args.find((a) => !a.startsWith('--'))
1447
1626
  if (!url) return ui.print('Usage: /install_skill <github repo or a SKILL.md url> [--project]')
1448
1627
  const scope = args.includes('--project') ? 'project' : 'global'
1449
- ui.spinner(`installing from ${url}`)
1628
+ spin(`installing from ${url}`)
1450
1629
  try {
1451
1630
  const msg = await installSkill(app.root, url, scope, { signal: app.signal })
1452
- ui.stopSpin()
1631
+ unspin()
1453
1632
  app.reload('skill')
1454
1633
  return ui.print(`${c.green('✓')} ${msg}${scope === 'project' ? ' (this folder)' : ''} ${c.dim('· run with /skill:<name>, /help lists them')}`)
1455
1634
  } catch (e) {
1456
- ui.stopSpin()
1635
+ unspin()
1457
1636
  return ui.print(`${c.red('✗')} could not install: ${e.message}`)
1458
1637
  }
1459
1638
  }
1460
1639
  case 'btw':
1461
- return app.btw(line.trim().replace(/^\/btw\b/, '').trim())
1640
+ return app.btw(line.trim().replace(/^\/btw\b/, '').trim(), working)
1462
1641
  case 'voice': {
1642
+ if (working) return ui.dictateIn() // into the box, as Space does while it works
1463
1643
  const text = await ui.dictate()
1464
1644
  if (text) app.nextInput = text // in the box, to read over and send
1465
1645
  return
@@ -1490,7 +1670,7 @@ async function slash(app, line) {
1490
1670
  return app.save()
1491
1671
  }
1492
1672
  case 'model_info':
1493
- return ui.print(`${c.cyan(s.client.model)}\n${describe(s.profile, s.strat)}`)
1673
+ return ui.showText(s.client.model, describe(s.profile, s.strat))
1494
1674
  case 'test_model': {
1495
1675
  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
1496
1676
  s.reset()
@@ -1506,16 +1686,21 @@ async function runTask(app, task, ctl) {
1506
1686
  try {
1507
1687
  const s = await app.session()
1508
1688
  if (!s) return false
1689
+ let answer
1509
1690
  try {
1510
- await s.run(task, ctl?.signal)
1691
+ answer = await s.run(task, ctl?.signal)
1511
1692
  } finally {
1512
1693
  app.save()
1513
1694
  }
1695
+ notify(app.cfg, 'done', `✅ Done · ${path.basename(app.root)} · ${duration(ui.worked())}\n${clip(task.split('\n')[0], 200)}\n\n${clip(String(answer ?? '').trim(), 3500)}`)
1514
1696
  } catch (e) {
1515
1697
  ui.stopSpin()
1516
1698
  log('error', e.name === 'AbortError' || ctl?.signal.aborted ? 'task interrupted by the user' : e.stack)
1517
1699
  if (e.name === 'AbortError' || ctl?.signal.aborted) ui.print(c.yellow('\ninterrupted'))
1518
- else ui.print(c.red(`\nerror: ${e.message}`))
1700
+ else {
1701
+ ui.print(c.red(`\nerror: ${e.message}`))
1702
+ notify(app.cfg, 'failed', `❌ Failed · ${path.basename(app.root)}\n${clip(task.split('\n')[0], 200)}\n\n${clip(e.message, 1500)}`)
1703
+ }
1519
1704
  return false
1520
1705
  }
1521
1706
  return true
@@ -1527,7 +1712,16 @@ async function repl(app, f = {}) {
1527
1712
  ui.onDoubleEscape = () => '/rewind'
1528
1713
  let ctl = null
1529
1714
  ui.onEscape = () => ctl?.abort()
1530
- ui.onBtw = (q) => app.btw(q, true) // /btw typed while it works
1715
+ // a command typed while it works: run now, beside the task, if it leaves the conversation alone
1716
+ ui.onPanel = () => app.toggleJobs() // Alt+B: the background commands' logs, side by side, live
1717
+ ui.onNow = (line) => {
1718
+ if (!RIGHT_AWAY.has(/^\/([\w-]+)/.exec(line)?.[1]) || !app.isCommand(line)) return false
1719
+ slash(app, line, true)
1720
+ .then((r) => r === 'exit' && (ctl?.abort(), app.save(), quit()))
1721
+ .catch((e) => (log('error', e.stack), ui.print(c.red(`error: ${e.message}`))))
1722
+ return true
1723
+ }
1724
+ 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)
1531
1725
  ui.isCommand = (l) => app.isCommand(l)
1532
1726
  loadPrices().then(() => ui.render?.()) // models.dev: what each model can do, for the model lists
1533
1727
  ui.voiceConfig = () => ({ voice: cfg.voice, providers: cfg.providers })
@@ -1602,6 +1796,8 @@ async function repl(app, f = {}) {
1602
1796
  if (f['resume-id']) await app.resume(loadChat(f['resume-id']))
1603
1797
  else if (f.resume) await app.resume()
1604
1798
  if (f.model) useModel(app, f.model) // a continued tab's own model
1799
+ // models this folder picked earlier (/select_model): said, with the way back to your whole list
1800
+ 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`)}`)
1605
1801
  app.tabs?.onChange?.() // the conversation it opened with
1606
1802
  for (;;) {
1607
1803
  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.27",
3
+ "version": "0.1.32",
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",