heartcode 0.1.63 → 0.1.95

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
@@ -2,24 +2,27 @@
2
2
  import path from 'node:path'
3
3
  import { parseArgs } from 'node:util'
4
4
  import { Client, limitSaid, estMessages } from '../src/client.js'
5
- import { loadConfig, saveConfig, readJson, writeJson, providerName, CONFIG_FILE, HOME, TEMP, AUTO_MODEL, isAuto, parseModel, takeIn, whatOf, VERSION, speedOf, jobsOf } from '../src/config.js'
5
+ import { loadConfig, saveConfig, readJson, writeJson, providerName, CONFIG_FILE, HOME, TEMP, AUTO_MODEL, isAuto, parseModel, takeIn, whatOf, VERSION, speedOf, jobsOf, track } 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'
8
8
  import { loadRankings, scoreOf } from '../src/rankings.js'
9
+ import { byRecord, useRecords } from '../src/record.js'
9
10
  import { Session, transcript, contextReport } from '../src/agent.js'
10
11
  import { listJobs, getJob, stopJob, removeJob, runningJobs, tailLines, ago as ranFor } from '../src/background.js'
11
12
  import { checkUpdate, installKind, UPDATE_COMMANDS, packageDir, whatsNew } from '../src/update.js'
12
13
  import { treeItems, codePlan, move, leaving, leftText, leftFiles } from '../src/tree.js'
13
- import { UI, c, PERMISSIONS, duration, copyText, overSsh, prettyKey, rank, setTheme, themeCodes, renderDiff, diffLines, DEFAULT_KEYS, loadKeys, width, shortError, wrapWords } from '../src/ui.js'
14
+ import { UI, c, PERMISSIONS, duration, copyText, overSsh, prettyKey, rank, setTheme, themeCodes, renderDiff, diffLines, DEFAULT_KEYS, loadKeys, width, shortError, wrapWords, ownAsk } from '../src/ui.js'
14
15
  import { listFiles, runCommand, clip } from '../src/tools.js'
15
- import { notify } from '../src/telegram.js'
16
- import { log, LOG_FILE, LOG_DIR, requestLog, useRequestLog, useLogs, pruneLogs, logDays } from '../src/log.js'
16
+ import { notify as telegram } from '../src/telegram.js'
17
+ import { alert, playSound } from '../src/alert.js'
18
+ import { log, LOG_FILE, LOG_DIR, requestLog, useRequestLog, useLogs, pruneLogs, logDays, forceLogs } from '../src/log.js'
17
19
  import { prompt, usePromptsFrom, reloadPrompts } from '../src/prompts.js'
18
20
  import { newChat, saveChat, listChats, loadChat, restoreFiles, ago, forkChat, exportChat } from '../src/sessions.js'
19
21
  import { loadPrices, priceOf, addUsage, money, limitsOf } from '../src/usage.js'
20
22
  import { Mcp, mcpAuth, loadServers } from '../src/mcp.js'
21
23
  import { forget } from '../src/oauth.js'
22
24
  import { loadSkills, fillArgs, extraSkillDirs } from '../src/skills.js'
25
+ import { trusted, trust, setupFiles, trustAll } from '../src/trust.js'
23
26
  import { HeadlessUI, runHeadless, toolNames, PERMISSION_MODES } from '../src/headless.js'
24
27
  import { findImports, installSkill } from '../src/importer.js'
25
28
  import { capabilities } from '../src/capabilities.js'
@@ -58,7 +61,6 @@ ${c.bold('options')}
58
61
  --api-key <key> API key for --base-url
59
62
  -y, --yes do everything without asking (the default; through --acp, an editor: ask)
60
63
  --ask ask before every edit and command, this run
61
- --hide-thinking the model's thinking: only its last two lines while it thinks (the default; Alt+O shows all of it)
62
64
  -C, --cwd <dir> project folder (default: current folder)
63
65
  --temp keep nothing: a throwaway settings folder (providers, model info,
64
66
  prices and notes copied in), shared by the --temp runs going on at once
@@ -77,6 +79,9 @@ ${c.bold('headless')} (for other programs; flags and output as in Claude Code's
77
79
  --output-format <f> text (default), json, or stream-json (one JSON event per line)
78
80
  --input-format <f> text (default; the prompt, or stdin) or stream-json (messages on stdin)
79
81
  --append-system-prompt <text> added to HeartCode's system prompt
82
+ --system-prompt <text> instead of HeartCode's: the model is only what this says, and HeartCode's
83
+ own workflow is off (plan first, "not done" checks, reviews, memory);
84
+ its tools, permissions and model fallback stay. --system-prompt-file <file>: from a file
80
85
  --mcp-config <file|json> more MCP servers (repeatable); --strict-mcp-config: only those
81
86
  --skills-dir <dir> more skills (repeatable)
82
87
  --allowedTools <list> only these tools (HeartCode's or Claude Code's names: Read, Edit, Bash…)
@@ -90,6 +95,8 @@ ${c.bold('headless')} (for other programs; flags and output as in Claude Code's
90
95
  interactive: until Esc)
91
96
  --max-turns <n> stop after n model steps in one message (default: no limit)
92
97
  --verbose warnings and retries on stderr
98
+ --logs <kinds> this run's logs, whatever the settings say: none, all, or some of
99
+ tools, models, agent, errors, conversation, debug, requests (comma-separated)
93
100
 
94
101
  ${c.bold('editors')} heartcode --acp the Agent Client Protocol on stdin/stdout (Zed, JetBrains, Neovim)
95
102
 
@@ -105,9 +112,9 @@ const SECTIONS = [
105
112
  ['/select_model', 'pick the model(s) for this session: one pins it, several rotate among them, auto = the whole list', true],
106
113
  ]],
107
114
  ['settings', [
108
- ['/toggle_thinking', "the model's thinking: its last two lines, or all of it (Alt+O)"],
115
+ ['/notifications', 'a sound and/or a desktop notification when a task finishes, fails or waits for you: on or off'],
109
116
  ['/todos', 'the whole plan of the task at work, every step and its state (Alt+L)'],
110
- ['/voice', 'dictate a message (or Space in an empty box, once voice is set up): it shows in the box while speaking, Enter sends it, Esc cancels'],
117
+ ['/voice', 'dictate a message (or Space in an empty box, once voice is set up): it shows in the box while speaking, Enter sends it, Esc cancels · with Hex, whisper-cli or OpenAI (/settings → General)'],
111
118
  ]],
112
119
  ['session', [
113
120
  ['/resume', 'continue an earlier session in this folder'],
@@ -146,7 +153,7 @@ for (const [, list] of SECTIONS) list.sort(byName) // alphabetical, in /help and
146
153
  const COMMANDS = SECTIONS.flatMap(([, list]) => list).sort(byName)
147
154
  // Typed while a task works, these run at once, beside it: they leave the conversation alone. The
148
155
  // others (/compact, /rewind, /resume, /init…) wait in the queue until it's done.
149
- const RIGHT_AWAY = new Set(['help', 'todos', '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'])
156
+ const RIGHT_AWAY = new Set(['help', 'todos', 'cost', 'context', 'background', 'model_info', 'diff', 'copy', 'mcp', 'doctor', 'notifications', 'btw', 'rename', 'export', 'tab', 'close_tab', 'exit', 'quit', 'settings', 'login_mcp', 'install_skill', 'import', 'voice', 'select_model'])
150
157
  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')
151
158
  const SLASH = helpText(SECTIONS)
152
159
 
@@ -159,10 +166,9 @@ function keysHelp(keys = {}, mouse = false, voice = false) {
159
166
  [voice ? 'Space' : '', 'voice: listens at once, Enter sends what was said (in an empty box)'],
160
167
  ['Enter', 'send · while it works, queue the message (commands like /help, /cost, /select_model run at once)'],
161
168
  ['Option+Enter or Shift+Enter', 'new line in the box (also while it works)'],
162
- ['Esc', 'while it works: queued messages back into the box, then clears the box, then stops the task (twice)'],
169
+ ['Esc', 'while it works: twice stops the task (the first closes the suggestions, if open) · ↑ in an empty box: the last queued message back into it'],
163
170
  ['Esc Esc', 'rewind to an earlier message (at the prompt)'],
164
171
  ['Shift+Tab', 'change what runs without asking (permissions)'],
165
- [forAct('toggle_thinking'), "the model's thinking: after an answer, all of it in a box; while it works, all of it as it comes or its last two lines"],
166
172
  [forAct('show_plan'), 'the whole plan in a box (only three of its steps show while it works)'],
167
173
  [forAct('background_log'), "the background commands' logs in a dialog, a tab each (←/→ switch, ↑/↓ scroll, K twice stops one, Esc closes); with text in the box it moves back a word instead"],
168
174
  [forAct('new_tab'), 'new tab'],
@@ -176,7 +182,7 @@ function keysHelp(keys = {}, mouse = false, voice = false) {
176
182
  [[forAct('scroll_up'), forAct('scroll_down')].filter(Boolean).join(' / '), 'scroll the conversation a page'],
177
183
  [[forAct('scroll_top'), forAct('scroll_bottom')].filter(Boolean).join(' / '), 'to the top / bottom of the conversation (scrolled up, it stays put while the answer comes in)'],
178
184
  [[forAct('scroll_line_up'), forAct('scroll_line_down')].filter(Boolean).join(' / '), 'scroll a few lines'],
179
- ['Ctrl+C', 'stop · twice quits HeartCode'],
185
+ ['Ctrl+C', 'twice stops · then again quits HeartCode'],
180
186
  [mouse ? 'Drag' : '', 'select and copy: the conversation, a dialog, the folder, the input, the status bar'],
181
187
  [mouse ? 'Double-click' : '', 'copy the word under it (an address, a path, a model)'],
182
188
  [mouse ? (process.platform === 'darwin' ? 'Option+drag' : 'Shift+drag') : '', "the terminal's own selection, past HeartCode's"],
@@ -210,10 +216,8 @@ const mask = (k) => (k ? (k.length > 12 ? `${k.slice(0, 4)}…${k.slice(-4)}` :
210
216
  // The status bar's default layout (two lines): the model and what it can do, then the run's stats and
211
217
  // controls — model and context on the left, abilities and controls pushed to the right. cfg.statusBar
212
218
  // overrides it — see App.status for the item names and format.
213
- const DEFAULT_STATUS = [
214
- { left: ['provider', 'model'], right: ['mode', 'thinking', 'images'] },
215
- { left: ['ctx', 'tps', 'autocompact'], right: ['background', 'permissions', 'worktree', 'cost'] },
216
- ]
219
+ const DEFAULT_STATUS = [{ left: ['provider', 'model', 'ctx', 'tps'], right: ['mode', 'thinking', 'autocompact', 'background', 'worktree', 'permissions', 'cost'] }] // one row
220
+ const DROP_FIRST = ['tps', 'images', 'thinking', 'autocompact', 'provider', 'cost', 'mode', 'ctx', 'worktree'] // too narrow: these go, in this order (never cut mid-word)
217
221
 
218
222
  class App {
219
223
  constructor(cfg, ui, root) {
@@ -367,13 +371,14 @@ class App {
367
371
  // that line): the agent says it then (announceSwitch), else right after
368
372
  let switched = null
369
373
  client.announceSwitch = () => switched && (ui.print(switched), (switched = null))
374
+ client.onNotice = (text) => ui.print(c.faint(text))
370
375
  client.onSwitch = (t) => {
371
376
  const i = client.rotation.list.indexOf(t)
372
377
  const f = failed?.e
373
378
  const from = failed?.t
374
- const why = f ? `${failed.t.model} ${f.status === 429 ? 'rate-limited (429)' : `failed (${clip(shortError(f), 50)})`} → ` : ''
379
+ const why = f ? `${failed.t.model} ${f.status === 429 ? 'hit its rate limit' : `failed (${clip(shortError(f), 60)})`}` : i ? 'the model before it failed' : 'your first model again'
375
380
  failed = null
376
- switched = c.dim(`↻ ${why}${t.provider} · ${t.model} answered${i ? ` (#${i + 1} in the model list)` : ' (#1 again)'}`)
381
+ switched = c.faint(`↻ ${t.model} takes over · ${why}`)
377
382
  ui.event?.({ subtype: 'model_switch', from: from ? `${from.provider}/${from.model}` : null, to: `${t.provider}/${t.model}`, reason: f ? (f.status === 429 ? 'rate-limited (429)' : shortError(f)) : null, place: i + 1 })
378
383
  setImmediate(client.announceSwitch)
379
384
  }
@@ -503,7 +508,7 @@ class App {
503
508
  }
504
509
  this.setChat(chat)
505
510
  ui.setLog(chat.log)
506
- ui.print(c.dim(`resumed "${chat.title}" · ${chat.turns.length} message${chat.turns.length > 1 ? 's' : ''} · ${ago(chat.updated)}`))
511
+ ui.notice(`resumed "${chat.title}" · ${chat.turns.length} message${chat.turns.length > 1 ? 's' : ''} · ${ago(chat.updated)}`, 8000)
507
512
  }
508
513
 
509
514
  // /rewind: back to before one of your messages; the conversation, the files HeartCode changed, or both.
@@ -536,7 +541,7 @@ class App {
536
541
  log('rewind', `files restored to before "${turn.task}":`, files)
537
542
  for (const t of chat.turns.slice(i)) t.files = {}
538
543
  chat.messages?.push({ role: 'user', content: prompt('agent/files-restored', { task: turn.task, files: files.join(', ') }) })
539
- ui.print(c.dim(`restored ${files.join(', ')} to before "${turn.task.split('\n')[0].slice(0, 60)}"`))
544
+ ui.notice(`restored ${files.join(', ')} to before "${turn.task.split('\n')[0].slice(0, 60)}"`, 8000)
540
545
  }
541
546
  if (how.conversation) {
542
547
  // what came after is kept as a branch (/tree), never lost: with its files as they are now,
@@ -545,8 +550,7 @@ class App {
545
550
  const { files } = move(chat, null, i, { code: Boolean(how.code) })
546
551
  log('rewind', `files restored to before "${turn.task}":`, files)
547
552
  ui.setLog(chat.log)
548
- if (how.code) ui.print(c.dim(`restored ${files.join(', ') || 'nothing (no file differed)'}`))
549
- ui.print(c.dim('the messages after it are kept as a branch: /tree goes back to them'))
553
+ ui.notice(`${how.code ? `Restored ${files.join(', ') || 'nothing (no file differed)'} · ` : ''}the messages after it are kept as a branch: /tree goes back to them`, 8000)
550
554
  this.nextInput = turn.task // back in the input, to edit and send again
551
555
  }
552
556
  log('rewind', `to before message ${i + 1}`, { conversation: Boolean(how.conversation), code: Boolean(how.code) })
@@ -592,7 +596,7 @@ class App {
592
596
  }
593
597
  const { left, files } = move(chat, it.branch, go.keep, { code })
594
598
  ui.setLog(chat.log)
595
- if (files.length) ui.print(c.dim(`files now as on this branch: ${files.join(', ')}`))
599
+ if (files.length) ui.notice(`files now as on this branch: ${files.join(', ')}`, 8000)
596
600
  if (code && unknown.length) ui.warn(`not known how ${unknown.join(', ')} looked there; left as they are`)
597
601
  if (summarize) {
598
602
  const s = await this.session()
@@ -611,7 +615,7 @@ class App {
611
615
  }
612
616
  }
613
617
  }
614
- ui.print(c.dim(`${go.edit ? 'edit the message and send it: a new branch' : 'here now'} · the branch left behind stays in /tree`))
618
+ ui.notice(`${go.edit ? 'edit the message and send it: a new branch' : 'here now'} · the branch left behind stays in /tree`, 8000)
615
619
  if (go.edit) this.nextInput = it.task
616
620
  if (this.s) this.s.client.lastTokens = 0
617
621
  this.save()
@@ -661,8 +665,14 @@ class App {
661
665
  const end = cursor + (/^\S*/.exec(line.slice(cursor))?.[0].length ?? 0)
662
666
  let m = /^\/(\S*)$/.exec(before)
663
667
  if (m) {
664
- const items = this.commands().map(([value, desc, args]) => ({ value, desc, space: args, start: 0, end }))
665
- const hits = rank(items, '/' + m[1])
668
+ // the menu says each in a few words (/help says all of it); just "/": the ones you used last first
669
+ let items = this.commands().map(([value, desc, args]) => ({ value, desc: desc?.split(/ · |: |; | \(/)[0], space: args, start: 0, end }))
670
+ if (!m[1]) {
671
+ const used = [...new Set([...(this.ui.history?.() ?? [])].reverse().map((l) => /^\/\S+/.exec(l)?.[0]).filter(Boolean))]
672
+ const at = (x) => (used.includes(x.value) ? used.indexOf(x.value) : Infinity)
673
+ items = [...items].sort((a, b) => at(a) - at(b))
674
+ }
675
+ const hits = m[1] ? rank(items, '/' + m[1]) : items
666
676
  return hits.length === 1 && hits[0].value === before ? [] : hits
667
677
  }
668
678
  m = /^\/(\w+)\s+(?:(\S+)\s+)?(\S*)$/.exec(before)
@@ -717,8 +727,8 @@ class App {
717
727
  const parts = {
718
728
  provider: `${c.brand('●')} ${c.muted(now.provider)}`,
719
729
  model,
720
- mode: strat ? (strat.actions === 'tools' ? null : c.muted('no tool calls (guided)')) : c.faint('checked at the first message'), // what it can do: known once it's been asked
721
- thinking: strat?.thinking ? c.think(`thinking · ${effortOf(cfg)}`) + (ui.showThinking ? c.faint(' (all)') : '') : null,
730
+ mode: strat && strat.actions !== 'tools' ? c.muted('no tools') : null, // what it can do: known once it's been asked
731
+ thinking: strat?.thinking ? c.think(`thinking${cfg.effort ? ` · ${cfg.effort}` : ''}`) : null, // the effort only when it was set
722
732
  images: strat?.vision ? c.muted('images') : null,
723
733
  ctx: null,
724
734
  tps: null,
@@ -727,14 +737,14 @@ class App {
727
737
  worktree: this.worktree ? c.info(`⎇ ${this.worktree.branch}`) : null,
728
738
  background: runningJobs(this.root).length ? c.info(`⚙ ${runningJobs(this.root).length} running`) + c.faint(' Alt+B') : null,
729
739
  update: this.update?.newer ? c.green(`⬆ ${this.update.latest}`) + c.faint(' /update') : null,
730
- 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],
740
+ permissions: { all: c.green('runs everything'), commands: c.yellow('asks before commands'), ask: c.yellow('asks before changes'), plan: c.info('plan mode') }[ui.permission],
731
741
  }
732
742
  if (strat) {
733
743
  const used = this.s?.client.lastTokens || Math.round(estMessages(this.chat?.messages ?? []) * (strat.ratio ?? 1)) // a resumed chat before its first request: estimated
734
744
  const pct = Math.round((used / strat.context) * 100)
735
745
  const paint = pct >= 80 ? c.red : pct >= 50 ? c.yellow : c.green
736
746
  const guess = strat.contextSure ? '' : '~' // not said by the server: assumed, and growing as bigger requests work
737
- parts.ctx = `${c.faint('ctx')} ${paint(`${kTokens(used)}/${guess}${kTokens(strat.context)}`)} ${c.faint(`${pct}%`)}`
747
+ if (!this.s?.client.cli) parts.ctx = `${c.faint('ctx')} ${paint(`${kTokens(used)}/${guess}${kTokens(strat.context)}`)} ${c.faint(`${pct}%`)}` // a coding CLI keeps its own
738
748
  const tps = this.s?.client.tps
739
749
  if (tps) parts.tps = `${c.muted(String(tps))} ${c.faint('tok/s')}`
740
750
  if (this.chat.usage?.priced) parts.cost = c.muted(money(this.chat.usage.cost))
@@ -745,7 +755,10 @@ class App {
745
755
  // background commands and a newer HeartCode are shown also on a bar laid out before there were these items
746
756
  for (const id of ['update', 'background']) if (parts[id] && !JSON.stringify(layout).includes(`"${id}"`)) layout = [...layout.slice(0, -1), ...layout.slice(-1).map((row) => (Array.isArray(row) ? { left: row, right: [id] } : { ...row, right: [id, ...(row.right ?? [])] }))]
747
757
  const line = (row) => {
748
- const names = (g) => (g ?? []).map((t) => parts[t]).filter(Boolean).join(sep)
758
+ const gone = new Set()
759
+ const names = (g) => (g ?? []).filter((t) => !gone.has(t)).map((t) => parts[t]).filter(Boolean).join(sep)
760
+ const all = () => [names(Array.isArray(row) ? row : row?.left), names(Array.isArray(row) ? null : row?.right)].filter(Boolean).join(sep)
761
+ for (const t of DROP_FIRST) if (vis(all()) > cols - 2 && parts[t]) gone.add(t)
749
762
  const left = names(Array.isArray(row) ? row : row?.left)
750
763
  const right = names(Array.isArray(row) ? null : row?.right)
751
764
  if (!right) return left
@@ -851,33 +864,32 @@ class App {
851
864
  // helpers use this session's models (the set you chose, else your list), minus the one in use —
852
865
  // so a pinned single model gives no team, and a chosen set keeps helpers within it
853
866
  const now = this.s?.client.rotation?.list[this.s.client.rotation.at] ?? this.sessionModels()[0]
854
- return this.sessionModels()
867
+ // asked for several times a step (the system prompt, the tool list, helpers, reviews): built once
868
+ // in a moment for the same model (each build reads files and ranks every model)
869
+ const key = `${now?.provider}/${now?.model}`
870
+ if (this.teamMemo?.key === key && this.teamMemo.cfg === this.cfg && Date.now() - this.teamMemo.at < 2000) return this.teamMemo.list.slice()
871
+ const tested = readJson(path.join(HOME, 'model-tests.json'), {}) // the settings page's tests
872
+ const list = this.sessionModels()
855
873
  .filter((t) => !(t.provider === now?.provider && t.model === now?.model))
856
- .map((t) => ({ ...t, ...this.abilities(t), jobs: jobsOf(this.cfg.helpers?.[`${t.provider}/${t.model}`]) })) // jobs: ticked as a helper on Your models (what for)
857
- .sort(this.byProvider()) // helpers picked in your list's order, your provider ranking's, or by score (Your models)
858
- }
859
-
860
- // Your models' "Helper order": by your provider ranking, a sort that puts the higher-ranked
861
- // provider's models first (each provider's in your list's order; providers not ranked after, A to
862
- // Z); in your list's order, one that keeps it.
863
- // By score: the best placed in LMArena's rankings first (its best share of a list: #5 of 200 is 2.5%),
864
- // across the lists the helpers are picked by (coding, web apps, long real tasks, hard prompts);
865
- // models not in them after, in your list's order.
866
- byProvider() {
867
- if ((this.cfg.helperOrder ?? 'score') === 'score') { // the default: a small model early in your list isn't who looks at a screenshot
868
- const data = loadRankings()
869
- const share = new Map()
870
- const of = (t) => {
871
- const k = `${t.provider}/${t.model}`
872
- if (!share.has(k)) share.set(k, scoreOf(t.model, data))
873
- return share.get(k)
874
- }
875
- return (a, b) => (of(a) === of(b) ? 0 : of(a) < of(b) ? -1 : 1) // Infinity (not ranked) last; ties keep your order
874
+ .map((t) => ({ ...t, ...this.abilities(t), jobs: jobsOf(this.cfg.helpers?.[`${t.provider}/${t.model}`]), ms: tested[`${t.provider}/${t.model}`]?.ms, price: priceOf(t.provider, this.cfg.providers[t.provider]?.baseUrl, t.model), auto: this.cfg.helpersAuto === true })) // price: models.dev's, $ per million tokens // jobs: ticked as a helper on Your models (what for); ms: how fast it answered its test; auto: helpers picked for you (a job goes to the fastest that's good at it)
875
+ .sort(this.byScore()) // best-ranked first
876
+ this.teamMemo = { key, cfg: this.cfg, at: Date.now(), list }
877
+ return list.slice()
878
+ }
879
+
880
+ // Helpers in order: the best placed in LMArena's rankings first (its best share of a list: #5 of 200
881
+ // is 2.5%), across coding, web apps, long real tasks and hard prompts, moved by the track record;
882
+ // models not in them after, in your list's order. A small model early in your list isn't who looks
883
+ // at a screenshot.
884
+ byScore() {
885
+ const data = loadRankings()
886
+ const share = new Map()
887
+ const of = (t) => {
888
+ const k = `${t.provider}/${t.model}`
889
+ if (!share.has(k)) share.set(k, scoreOf(t.model, data))
890
+ return share.get(k)
876
891
  }
877
- const rank = this.cfg.helperOrder === 'provider' && Array.isArray(this.cfg.providerRank) ? this.cfg.providerRank : null
878
- if (!rank) return () => 0
879
- const at = (p) => (rank.includes(p) ? rank.indexOf(p) : rank.length)
880
- return (a, b) => at(a.provider) - at(b.provider) || (at(a.provider) === rank.length ? a.provider.localeCompare(b.provider) : 0)
892
+ return (a, b) => byRecord({ t: a, score: of(a) }, { t: b, score: of(b) }) // Infinity (not ranked) last; ties keep your order (record.js)
881
893
  }
882
894
 
883
895
  // What a model can do, from its saved profile or models.dev (guessed: neither knows it).
@@ -1187,7 +1199,8 @@ async function leaveWorktree(app) {
1187
1199
  const TABS_FILE = path.join(HOME, 'tabs.json')
1188
1200
  function saveTabs(tabs) {
1189
1201
  const all = readJson(TABS_FILE, {})
1190
- all[tabs.root] = { at: tabs.list.indexOf(tabs.at), tabs: tabs.list.map((t) => ({ chat: t.app.chat.id, worktree: t.app.worktree?.name ?? null, provider: t.app.cfg.provider ?? null, model: t.app.cfg.model ?? null })) }
1202
+ // a tab's own models only when it chose some (/select_model): the list's #1 is everyone's, not the tab's
1203
+ all[tabs.root] = { at: tabs.list.indexOf(tabs.at), tabs: tabs.list.map((t) => ({ chat: t.app.chat.id, worktree: t.app.worktree?.name ?? null, ...(t.app.cfg.session?.length && { session: t.app.cfg.session.map(({ provider, model }) => ({ provider, model })) }) })) }
1191
1204
  writeJson(TABS_FILE, all)
1192
1205
  }
1193
1206
 
@@ -1226,11 +1239,13 @@ async function continueTabs(app, saved) {
1226
1239
  }
1227
1240
 
1228
1241
  // A continued tab's own model, as it was (unless its provider is gone: then the current one).
1229
- function useModel(app, { provider, model }) {
1230
- if (!provider || !model || (provider === app.cfg.provider && model === app.cfg.model)) return
1231
- if (!app.cfg.providers[provider]) return app.ui.warn(`this tab used ${provider} · ${model}, but there's no provider "${provider}" now: using the list`)
1232
- if (app.cfg.providers[provider].off) return app.ui.warn(`this tab used ${provider} · ${model}, but ${provider} is switched off: using the list`)
1233
- Object.assign(app.cfg, { provider, model })
1242
+ // A continued tab's own models (the ones it chose with /select_model), for that tab only: the
1243
+ // list's #1 (cfg.provider/model) is never changed here. (Older tabs.json entries have a provider and
1244
+ // model: that was the list's #1 back then, not the tab's choice, so it's left alone.)
1245
+ function useModel(app, { session }) {
1246
+ const ok = (session ?? []).filter((t) => app.cfg.providers[t?.provider] && !app.cfg.providers[t.provider].off && t.model)
1247
+ if (!ok.length) return
1248
+ app.cfg.session = ok
1234
1249
  app.s = null
1235
1250
  }
1236
1251
 
@@ -1258,25 +1273,26 @@ function applySettings(apps, cfg, what) {
1258
1273
  if (what === 'prompts') reloadPrompts()
1259
1274
  if (['setting:logs', 'setting:log', 'setting:logRequests', 'setting:logDetail'].includes(what)) useRequestLog(cfg) // each kind of log, on or off now
1260
1275
  if (what === 'setting:logDays') pruneLogs(logDays(cfg))
1276
+ if (what === 'setting:trackRecord') useRecords(cfg)
1261
1277
  settingsSeen(what) // the watcher (watchSettings) mustn't take it in a second time
1262
1278
  for (const app of apps) {
1263
1279
  const { ui } = app
1264
1280
  const busy = Boolean(ui.busySince || app.working)
1265
1281
  const now = (fn) => (busy ? app.later.push(fn) : fn())
1266
- if (app.cfg !== cfg) for (const k of ['providers', 'provider', 'model', 'effort', 'theme', 'context', 'autoCompact', 'director', 'format', 'lsp', 'voice', 'rotation', 'statusBar', 'helpers', 'helpersAuto', 'helperOrder', 'providerRank', 'replyStart', 'replyIdle', 'telegram', 'queue', 'mouse']) app.cfg[k] = cfg[k]
1282
+ if (app.cfg !== cfg) for (const k of ['providers', 'provider', 'model', 'effort', 'theme', 'context', 'autoCompact', 'director', 'format', 'lsp', 'voice', 'rotation', 'statusBar', 'helpers', 'helpersAuto', 'replyStart', 'replyIdle', 'telegram', 'queue', 'mouse']) app.cfg[k] = cfg[k]
1267
1283
  // a model pinned in this CLI (/select_model) is a session choice: a model/order change on the
1268
1284
  // settings page leaves it alone (only /select_model auto here returns it to the list)
1269
1285
  if (what === 'model' && !app.cfg.session) {
1270
1286
  app.lists = {}
1271
- if (app.s && !(cfg.providers[cfg.provider] && cfg.model)) now(() => ((app.s = null), ui.print(c.dim('settings: no model chosen'))))
1272
- else if (app.s && !app.myModels().length) now(() => ((app.s = null), ui.print(c.dim('settings: the providers of all the models are switched off'))))
1287
+ if (app.s && !(cfg.providers[cfg.provider] && cfg.model)) now(() => ((app.s = null), ui.notice('settings: no model chosen')), 8000)
1288
+ else if (app.s && !app.myModels().length) now(() => ((app.s = null), ui.notice('settings: the providers of all the models are switched off')), 8000)
1273
1289
  }
1274
1290
  // your model list: into the running session now, its next request goes to the new #1
1275
1291
  if (['model', 'setting:rotation'].includes(what) && !app.cfg.session && app.s && cfg.providers[cfg.provider] && cfg.model) {
1276
1292
  const was = `${app.s.client.provider} · ${app.s.client.model}`
1277
1293
  app.useRotation()
1278
1294
  const is = `${app.s.client.provider} · ${app.s.client.model}`
1279
- if (is !== was) ui.print(c.dim(`settings: ${is} now`))
1295
+ if (is !== was) ui.notice(`settings: ${is} now`, 8000)
1280
1296
  }
1281
1297
  if (what === 'provider') app.lists = {} // its list switched on or off, a model added by name
1282
1298
  if (what === 'setting:permissions' && !ui.noUser) ui.setPermission(cfg.permissions) // -p and ACP keep the mode they were given (--permission-mode, the editor's)
@@ -1363,6 +1379,7 @@ function watchSettings(apps, cfg) {
1363
1379
  function afterReset(apps, level) {
1364
1380
  const fresh = loadConfig()
1365
1381
  useRequestLog(fresh)
1382
+ useRecords(fresh)
1366
1383
  const before = themeCodes()
1367
1384
  setTheme(fresh.theme)
1368
1385
  reloadPrompts()
@@ -1494,7 +1511,7 @@ async function slash(app, line, working = false) {
1494
1511
  close()
1495
1512
  settingsPage = null
1496
1513
  }
1497
- return ui.print(c.dim('settings page turned off'))
1514
+ return ui.notice('Settings page turned off', 3000) // not a message: above the input, for a moment
1498
1515
  }
1499
1516
  case 'tab': {
1500
1517
  const { tabs } = app
@@ -1521,8 +1538,9 @@ async function slash(app, line, working = false) {
1521
1538
  const notes = await whatsNew(u.current, u.latest)
1522
1539
  if (kind === 'git') return ui.showText(`HeartCode ${u.latest} is out (this is ${u.current})`, `${notes || '(no changelog found)'}\n\nThis HeartCode runs from a git checkout (${packageDir}): update it there with git pull.`)
1523
1540
  const cmd = UPDATE_COMMANDS[kind]
1524
- ui.showText(`HeartCode ${u.latest} is out (this is ${u.current})`, notes || '(no changelog found)')
1525
- if ((await ui.confirm(`Update now with ${c.bold(cmd)}?`, 'command')) !== true) return ui.print(c.dim('not updated'))
1541
+ // what changed and the question in one dialog (a question closed the notes before they could be read)
1542
+ const go = await ui.pick(`HeartCode ${u.latest} is out (this is ${u.current}). Update now with ${cmd}?`, [{ label: 'Update now', yes: true }, { label: 'Not now' }], { body: notes || '(no changelog found)' })
1543
+ if (!go?.yes) return ui.notice('Not updated', 3000)
1526
1544
  ui.spinner(`running ${cmd}`)
1527
1545
  const r = await runCommand(process.cwd(), cmd, { timeout: 300_000 })
1528
1546
  ui.stopSpin()
@@ -1748,11 +1766,8 @@ async function slash(app, line, working = false) {
1748
1766
  }
1749
1767
  case 'todos':
1750
1768
  return ui.showPlan()
1751
- case 'toggle_thinking':
1752
- ui.showThinking = !ui.showThinking
1753
- 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)'))
1754
- if (ui.showThinking && !ui.thinkTail) ui.showLastThought() // the one just over: all of it now
1755
- return
1769
+ case 'notifications':
1770
+ return askAlerts(app)
1756
1771
  }
1757
1772
  if (!['model_info', 'compact'].includes(cmd)) {
1758
1773
  app.skills = loadSkills(app.root) // edits to skill files apply right away
@@ -1781,6 +1796,32 @@ async function slash(app, line, working = false) {
1781
1796
  }
1782
1797
 
1783
1798
  // true: done; false: stopped or failed; null: no model to run it
1799
+ // a task finished, failed or waits for you: Telegram and this computer, each if set up
1800
+ const notify = (cfg, event, text) => (telegram(cfg, event, text), alert(cfg, event, text))
1801
+
1802
+ // Notifications on this computer (alert.js): asked once at the first start in the terminal, and
1803
+ // any time with /notifications. Saved whatever the answer (Esc: off), so the first start's question
1804
+ // isn't asked again; how to change it is said each time.
1805
+ let alertsAsked = false
1806
+ async function askAlerts(app, first = false) {
1807
+ const { ui, cfg } = app
1808
+ const a = cfg.alerts ?? {}
1809
+ const now = a.sound && a.popup ? 'both' : a.sound ? 'sound' : a.popup ? 'popup' : 'off'
1810
+ const items = [
1811
+ { label: 'A sound and a desktop notification', key: 'both', sound: true, popup: true },
1812
+ { label: 'Only a sound', desc: "HeartCode's own: a heartbeat", key: 'sound', sound: true, popup: false },
1813
+ { label: 'Only a desktop notification', key: 'popup', sound: false, popup: true },
1814
+ { label: first ? 'No, thanks' : 'Off', key: 'off', sound: false, popup: false },
1815
+ ].map((it) => (!first && it.key === now ? { ...it, label: `${it.label} ${c.faint('(now)')}` } : it))
1816
+ const it = await ui.pick(first ? 'Let HeartCode tell you when a task finishes, fails or waits for you?' : 'Notifications on this computer', items, { quiet: true }) // not a message: nothing left in the conversation
1817
+ const pick = it ?? (first ? items.at(-1) : null)
1818
+ if (!pick) return
1819
+ cfg.alerts = { ...a, sound: pick.sound, popup: pick.popup }
1820
+ saveConfig(cfg)
1821
+ ui.notice(`Notifications: ${pick.key === 'off' ? 'off' : pick.key === 'both' ? 'a sound and a desktop notification' : pick.key === 'sound' ? 'a sound' : 'a desktop notification'} · change them any time: /notifications or /settings → Notifications`, 10000)
1822
+ if (pick.sound && first) playSound('done') // what it sounds like
1823
+ }
1824
+
1784
1825
  async function runTask(app, task, ctl) {
1785
1826
  const { ui } = app
1786
1827
  try {
@@ -1796,7 +1837,7 @@ async function runTask(app, task, ctl) {
1796
1837
  } catch (e) {
1797
1838
  ui.stopSpin()
1798
1839
  log('error', e.name === 'AbortError' || ctl?.signal.aborted ? 'task interrupted by the user' : e.stack)
1799
- if (e.name === 'AbortError' || ctl?.signal.aborted) ui.print(c.yellow('\ninterrupted'))
1840
+ if (e.name === 'AbortError' || ctl?.signal.aborted) ui.print(c.muted('\n⏹ stopped'))
1800
1841
  else {
1801
1842
  ui.print(c.red(`\nerror: ${e.message}`))
1802
1843
  notify(app.cfg, 'failed', `❌ Failed · ${path.basename(app.root)}\n${clip(task.split('\n')[0], 200)}\n\n${clip(e.message, 1500)}`)
@@ -1824,7 +1865,8 @@ async function repl(app, f = {}) {
1824
1865
  ui.onPanel = () => app.toggleJobs() // Alt+B: the background commands' logs, side by side, live
1825
1866
  ui.onNow = (line) => {
1826
1867
  if (!RIGHT_AWAY.has(/^\/([\w-]+)/.exec(line)?.[1]) || !app.isCommand(line)) return false
1827
- slash(app, line, true)
1868
+ ownAsk
1869
+ .run(true, () => slash(app, line, true)) // its questions and lines are yours, not the task's (ui.js ownAsk)
1828
1870
  .then((r) => r === 'exit' && (ctl?.abort(), app.save(), quit()))
1829
1871
  .catch((e) => (log('error', e.stack), ui.print(c.red(`error: ${e.message}`))))
1830
1872
  return true
@@ -1858,6 +1900,7 @@ async function repl(app, f = {}) {
1858
1900
  if (last && app.tabs) app.tabs.quitting = true
1859
1901
  ctl?.abort()
1860
1902
  ui.cancelAsk()
1903
+ app.mcp?.dispose?.() // its servers stop now, and their exit hook goes
1861
1904
  ui.close()
1862
1905
  } finally {
1863
1906
  closing = false
@@ -1870,15 +1913,20 @@ async function repl(app, f = {}) {
1870
1913
  ui.submit('/close_tab') // at the prompt: asked in its turn, like a typed /close_tab
1871
1914
  }
1872
1915
  const others = () => (app.tabs?.list.length ?? 1) - 1
1916
+ // working: like Esc, a second Ctrl+C within 2.5s stops it (a stray one doesn't); one more quits
1917
+ let stopArm = 0
1873
1918
  ui.onInterrupt = () => {
1874
1919
  const again = Date.now() - lastInterrupt < 2000
1875
1920
  lastInterrupt = Date.now()
1876
1921
  if (ctl) {
1877
- if (again) return quit()
1922
+ if (again && !stopArm) return quit() // already stopping (or stuck): quits
1923
+ if (Date.now() - stopArm >= 2500) return (stopArm = Date.now()), (lastInterrupt = 0), ui.notice('Press Ctrl+C again to stop', 2500)
1924
+ stopArm = 0
1878
1925
  stop()
1879
1926
  ui.cancelAsk()
1880
1927
  return ui.warn(`stopping… (Ctrl+C again to quit${others() ? ` HeartCode, all ${others() + 1} tabs` : ''})`)
1881
1928
  }
1929
+ stopArm = 0
1882
1930
  if (ui.rl?.line) {
1883
1931
  lastInterrupt = 0 // clearing isn't the first half of quitting
1884
1932
  return ui.clearInput()
@@ -1892,7 +1940,8 @@ async function repl(app, f = {}) {
1892
1940
  ui.folder = app.root // what a double click on the header's folder copies
1893
1941
  ui.header = (cols = 100) => {
1894
1942
  const room = cols - 2 - width(`♥ HeartCode ${VERSION} `) // the folder's own name (its end) stays in sight
1895
- const keys = [['/', 'run a command'], ['@', 'attach a file'], ...(ui.voiceReady?.() ? [['Space', 'talk (voice)']] : []), [NEWLINE_KEY, 'add a new line'], ui.busySince ? ['Esc twice', 'stop'] : ['Esc Esc', 'go back to a message'], ['Shift+Tab', 'change permissions']]
1943
+ // the keys only until the first message: after that the room is the conversation's (/help has them all)
1944
+ const keys = app.chat?.messages?.length ? [] : [['/', 'commands'], ['@', 'attach a file'], ...(ui.voiceReady?.() ? [['Space', 'talk']] : []), [NEWLINE_KEY, 'new line'], ['Esc Esc', 'go back to a message'], ['Shift+Tab', 'permissions'], ...(ui.keyFor('new_tab') ? [[ui.keyFor('new_tab'), 'new tab']] : [])]
1896
1945
  // the keys: on a second line when they don't fit one, broken between keys (never inside one)
1897
1946
  const rows = []
1898
1947
  for (const kd of keys) {
@@ -1903,7 +1952,7 @@ async function repl(app, f = {}) {
1903
1952
  return [
1904
1953
  `${c.brand('♥')} ${c.bright(c.bold('HeartCode'))} ${c.faint(VERSION)} ${c.muted(width(where) > room ? '…' + where.slice(-(room - 1)) : where)}`,
1905
1954
  ...rows.map((row) => row.map(([k, d]) => `${c.muted(k)} ${c.faint(d)}`).join(c.ghost(' · '))),
1906
- '',
1955
+ ...(rows.length ? [''] : []),
1907
1956
  ]
1908
1957
  }
1909
1958
  if (!ui.full) ui.print(ui.header().join('\n'))
@@ -1914,13 +1963,13 @@ async function repl(app, f = {}) {
1914
1963
  if (f.continue) {
1915
1964
  const last = listChats(app.root)[0]
1916
1965
  if (last) await app.resume(last)
1917
- else ui.print(c.dim('No earlier session in this folder to continue.'))
1966
+ else ui.notice('No earlier session in this folder to continue', 6000)
1918
1967
  }
1919
1968
  if (f['resume-id']) await app.resume(loadChat(f['resume-id'], app.root))
1920
1969
  else if (f.resume) await app.resume()
1921
1970
  if (f.model) useModel(app, f.model) // a continued tab's own model
1922
1971
  // models this folder picked earlier (/select_model): said, with the way back to your whole list
1923
- 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 the whole list again`)}`)
1972
+ if (app.folderModels && cfg.session?.length) ui.notice(`This folder uses ${cfg.session.map((t) => t.model).join(', ')} (picked earlier) · /select_model auto for the whole list again`, 10000) // not a message
1924
1973
  app.tabs?.onChange?.() // the conversation it opened with
1925
1974
  // a newer HeartCode: asked of npm in the background at every start, said once and kept in the status bar
1926
1975
  if (cfg.updateCheck !== false)
@@ -1928,11 +1977,27 @@ async function repl(app, f = {}) {
1928
1977
  .then((u) => {
1929
1978
  if (!u?.newer) return
1930
1979
  app.update = u
1931
- ui.print(`${c.green('⬆')} ${c.muted('HeartCode')} ${c.green(u.latest)} ${c.muted(`is out (this is ${u.current})`)} ${c.faint('·')} ${c.cyan('/update')}`)
1980
+ ui.notice(`HeartCode ${u.latest} is out (this is ${u.current}) · /update`, 10000) // and in the status bar
1932
1981
  ui.render?.()
1933
1982
  })
1934
1983
  .catch(() => {})
1984
+ // this folder's own setup (a cloned repo's hooks and MCP servers run commands): used once you say so
1985
+ if (!trusted(app.root)) {
1986
+ const files = setupFiles(app.root)
1987
+ const yes = await ui.pick(`This folder has its own HeartCode setup (${files.join(', ')}). Its hooks and MCP servers run commands on this computer. Use it?`, [
1988
+ { label: 'Yes, use it', desc: 'for these files as they are now; asked again if they change', use: true },
1989
+ { label: 'No', desc: 'HeartCode works here without them' },
1990
+ ], { quiet: true })
1991
+ if (yes?.use) trust(app.root), reloadPrompts()
1992
+ else ui.notice(`This folder's own setup isn't used (${files.join(', ')}); you're asked again next time`, 8000)
1993
+ }
1935
1994
  for (;;) {
1995
+ // the first start: whether to be told when a task finishes (once, in one tab); once there's a model
1996
+ // to work with (not over the "set up a model" screen)
1997
+ if (cfg.alerts === undefined && !alertsAsked && cfg.providers[cfg.provider] && cfg.model) {
1998
+ alertsAsked = true
1999
+ await askAlerts(app, true)
2000
+ }
1936
2001
  const line = await ui.ask(` ${c.magenta('♥')} `, { suggest: true, initial: app.nextInput, history: true })
1937
2002
  app.nextInput = undefined
1938
2003
  if (line === null) break
@@ -1941,10 +2006,11 @@ async function repl(app, f = {}) {
1941
2006
  ctl = new AbortController()
1942
2007
  app.signal = ctl.signal // Esc stops whatever this line started (a task, a probe, …)
1943
2008
  ui.escArm = 0 // a fresh task: a first Esc from before doesn't count toward stopping this one
1944
- ui.busy() // the spinner stays until this line's work is done
1945
2009
  const command = app.isCommand(t)
2010
+ ui.busy(command ? 400 : 0, { task: !command }) // the spinner stays until this line's work is done (a command: if it takes a while)
1946
2011
  if (command) {
1947
2012
  const mark = ui.mark?.() // what it prints goes back out of the conversation when it's done
2013
+ ui.inCommand = true // its own questions aren't echoed (one line said: above the input, not a box)
1948
2014
  try {
1949
2015
  if ((await slash(app, t)) === 'exit') {
1950
2016
  if (app.tabs) app.tabs.quitting = true
@@ -1955,6 +2021,7 @@ async function repl(app, f = {}) {
1955
2021
  log('error', e.stack)
1956
2022
  ui.print(c.red(`error: ${e.message}`))
1957
2023
  }
2024
+ ui.inCommand = false
1958
2025
  if (mark) ui.unmark(mark, /^\S+/.exec(t)[0])
1959
2026
  } else {
1960
2027
  if (process.stdout.isTTY) process.stdout.write(`\x1b]0;● ${path.basename(app.root)} · HeartCode\x07`)
@@ -1972,8 +2039,8 @@ async function repl(app, f = {}) {
1972
2039
  ok = await runTask(app, prompt('agent/plan-approved'), ctl)
1973
2040
  }
1974
2041
  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)
1975
- // done, said by the terminal too: its title, and after a long task a bell and a notification (OSC 9)
1976
- 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' : ''))
2042
+ // done, said by the terminal too: its title (the desktop notification and sound: notify, as chosen)
2043
+ 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 && overSsh && cfg.alerts?.popup ? '\x1b]9;HeartCode: done\x07' : '')) // the terminal's own popup only over SSH (this computer's can't reach you there), and only when you chose notifications
1977
2044
  }
1978
2045
  ui.idle()
1979
2046
  ctl = null
@@ -2021,6 +2088,8 @@ async function main() {
2021
2088
  'output-format': { type: 'string' },
2022
2089
  'input-format': { type: 'string' },
2023
2090
  'append-system-prompt': { type: 'string' },
2091
+ 'system-prompt': { type: 'string' },
2092
+ 'system-prompt-file': { type: 'string' },
2024
2093
  'mcp-config': { type: 'string', multiple: true },
2025
2094
  'strict-mcp-config': { type: 'boolean' },
2026
2095
  'skills-dir': { type: 'string', multiple: true },
@@ -2034,6 +2103,7 @@ async function main() {
2034
2103
  effort: { type: 'string' },
2035
2104
  'no-memory': { type: 'boolean' },
2036
2105
  verbose: { type: 'boolean' },
2106
+ logs: { type: 'string' },
2037
2107
  'max-retries': { type: 'string' },
2038
2108
  'max-turns': { type: 'string' },
2039
2109
  all: { type: 'boolean' }, // heart models --all
@@ -2055,7 +2125,9 @@ async function main() {
2055
2125
  if (f.effort && !['default', 'low', 'medium', 'high'].includes(f.effort)) throw new Error('--effort must be low, medium, high or default')
2056
2126
  const cfg = loadConfig({ baseUrl: f['base-url'], model: f.provider && f.model ? `${f.provider} ${f.model}` : f.model, apiKey: f['api-key'], context: f.context })
2057
2127
  setTheme(cfg.theme)
2128
+ if (f.logs !== undefined) forceLogs(f.logs)
2058
2129
  useLogs(cfg)
2130
+ useRecords(cfg)
2059
2131
  const safe = { ...cfg, providers: Object.fromEntries(Object.entries(cfg.providers).map(([n, p]) => [n, { ...p, apiKey: p.apiKey && mask(p.apiKey) }])) }
2060
2132
  log('start', `heartcode ${VERSION} · node ${process.version} · ${process.platform} · cwd ${process.cwd()}`, { args: process.argv.slice(2).map((a) => (a === f['api-key'] ? mask(a) : a)), config: safe })
2061
2133
  // --provider: one model alone, as -m does: with -m, that one (above); alone, that provider's first
@@ -2110,9 +2182,11 @@ async function main() {
2110
2182
  return apps[apps.push(app) - 1]
2111
2183
  }
2112
2184
  watchSettings(() => apps, cfg) // the settings page's changes, into every editor session
2185
+ trustAll.on = true // an editor: its own workspace trust decides
2113
2186
  process.exit(await runAcp({ makeApp, version: VERSION, permission: f['permission-mode'] ? PERMISSION_MODES[f['permission-mode']] : (cfg.permissions ?? 'ask') }))
2114
2187
  }
2115
2188
  const headless = f.print || f['output-format'] || f['input-format'] === 'stream-json'
2189
+ if (headless) trustAll.on = true // -p: the folder's own setup is used, as it is (whoever runs it chose the folder)
2116
2190
  if (f['max-retries'] !== undefined || headless) cfg.maxRetries = Number(f['max-retries'] ?? 10) // nobody is there to press Esc
2117
2191
  if (f['max-turns']) cfg.maxTurns = Number(f['max-turns'])
2118
2192
  // A UI and an App on it (one per tab; io: the tab's input and output).
@@ -2132,7 +2206,6 @@ async function main() {
2132
2206
  saveConfig(cfg)
2133
2207
  }
2134
2208
  }
2135
- ui.showThinking = false // the thinking's last two lines while it thinks; Alt+O shows all of it (--hide-thinking: the same)
2136
2209
  const app = new App(cfg, ui, root)
2137
2210
  usePromptsFrom(app.root) // its .heartcode/prompts override the built-in sections
2138
2211
  ui.suggest = (line, cursor) => app.suggest(line, cursor)
@@ -2162,7 +2235,7 @@ async function main() {
2162
2235
  const saved = readJson(TABS_FILE, {})[root] // before this run's first tab replaces it
2163
2236
  const asked = f.continue || f.resume || f['resume-id'] || f['session-id'] // a session was chosen already
2164
2237
  const tabs = new Tabs((tab, o) => {
2165
- const app = newApp(o.first ? cfg : { ...cfg }, o.root, tab)
2238
+ const app = newApp(o.first ? cfg : track({ ...cfg }, cfg), o.root, tab) // its own copy, its own changes saved (config.js track)
2166
2239
  Object.assign(tab, { app, ui: app.ui })
2167
2240
  Object.assign(app.ui, tab.hooks)
2168
2241
  Object.assign(app, { tabs, tab, worktree: o.wt ?? null })
@@ -2196,6 +2269,8 @@ async function main() {
2196
2269
  if (sub === 'providers') return app.listProviders(), ui.close()
2197
2270
  if (sub === 'models') return await app.listModels(positionals[1] ?? '', { all: f.all, json: f.json }), ui.close()
2198
2271
  if (f['no-memory']) app.memory = null
2272
+ const ownSystem = f['system-prompt'] ?? (f['system-prompt-file'] && fs.readFileSync(f['system-prompt-file'], 'utf8'))
2273
+ if (ownSystem) app.memory = null // HeartCode's notes and lessons are its own workflow: off
2199
2274
  const chat = f['resume-id'] ? loadChat(f['resume-id'], app.root) : f.continue && headless ? listChats(app.root)[0] : f['session-id'] ? (loadChat(f['session-id'], app.root) ?? { ...newChat(app.root), id: f['session-id'] }) : null
2200
2275
  if (f['resume-id'] && !chat) throw new Error(`no session ${f['resume-id']}`)
2201
2276
  if (chat && (headless || !f['resume-id'])) app.setChat(chat) // interactive: resumed below, with its transcript
@@ -2203,7 +2278,7 @@ async function main() {
2203
2278
  if (headless) {
2204
2279
  app.allowTools = [...(f.allowedTools ?? []), ...(f['allowed-tools'] ?? [])]
2205
2280
  app.denyTools = [...(f.disallowedTools ?? []), ...(f['disallowed-tools'] ?? [])]
2206
- const code = await runHeadless(app, { prompt: positionals.join(' '), input: f['input-format'], output: f['output-format'], appendSystem: f['append-system-prompt'], partial: f['include-partial-messages'] })
2281
+ const code = await runHeadless(app, { prompt: positionals.join(' '), input: f['input-format'], output: f['output-format'], appendSystem: f['append-system-prompt'], ownSystem, partial: f['include-partial-messages'] })
2207
2282
  if (wt && worktreeState(wt).empty) removeWorktree(wt) // else kept, for the caller to merge (its path is in the log)
2208
2283
  process.exit(code) // MCP servers are stopped by the exit hooks
2209
2284
  }
@@ -2220,8 +2295,15 @@ async function main() {
2220
2295
  }
2221
2296
 
2222
2297
  let activeUI = null
2298
+ // A bug in HeartCode itself: logged and said, and HeartCode goes on (the conversation, the work, the
2299
+ // screen stay); only before the screen is up does it stop.
2223
2300
  process.on('uncaughtException', (e) => {
2224
2301
  log('crash', e.stack)
2302
+ if (activeUI?.full) {
2303
+ try {
2304
+ return activeUI.warn(`HeartCode hit an error of its own and carried on: ${e.message} (the whole of it is in the errors log)`)
2305
+ } catch {}
2306
+ }
2225
2307
  activeUI?.close()
2226
2308
  console.error(`${c.red('crash:')} ${e.stack}`)
2227
2309
  process.exit(1)