heartcode 0.1.58 → 0.1.60

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,11 +5,12 @@ import { Client, limitSaid, estMessages } from '../src/client.js'
5
5
  import { loadConfig, saveConfig, readJson, writeJson, providerName, CONFIG_FILE, HOME, TEMP, AUTO_MODEL, isAuto, parseModel, takeIn, whatOf, VERSION, speedOf, jobsOf } 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
+ import { loadRankings, rankIn } from '../src/rankings.js'
8
9
  import { Session, transcript, contextReport } from '../src/agent.js'
9
10
  import { listJobs, getJob, stopJob, removeJob, runningJobs, tailLines, ago as ranFor } from '../src/background.js'
10
11
  import { checkUpdate, installKind, UPDATE_COMMANDS, packageDir, whatsNew } from '../src/update.js'
11
12
  import { treeItems, codePlan, move, leaving, leftText, leftFiles } from '../src/tree.js'
12
- import { UI, c, PERMISSIONS, duration, copyText, overSsh, rank, setTheme, themeCodes, renderDiff, diffLines, DEFAULT_KEYS, loadKeys, width, shortError, wrapWords } from '../src/ui.js'
13
+ import { UI, c, PERMISSIONS, duration, copyText, overSsh, prettyKey, rank, setTheme, themeCodes, renderDiff, diffLines, DEFAULT_KEYS, loadKeys, width, shortError, wrapWords } from '../src/ui.js'
13
14
  import { listFiles, runCommand, clip } from '../src/tools.js'
14
15
  import { notify } from '../src/telegram.js'
15
16
  import { log, LOG_FILE, LOG_DIR, requestLog, useRequestLog, useLogs, pruneLogs, logDays } from '../src/log.js'
@@ -42,24 +43,24 @@ ${c.bold('usage')}
42
43
  heart ~/code/my-app in that folder (a folder, not a file)
43
44
  heart "fix the failing test" run one task and exit
44
45
  heart providers list added providers
45
- heart models [filter] what -m takes, one per line: "auto" (your list), then your models
46
+ heart models [filter] what -m takes, one per line: "auto" (the list), then each model
46
47
  as provider/model, #1 first
47
48
  heart models --all [filter] every provider's models (provider/model)
48
49
  heart models --json as JSON (with --all too), for other programs
49
50
  heart config show the config file
50
- heart settings change providers, models and settings in your browser
51
+ heart settings change providers, models and settings in the browser
51
52
 
52
53
  ${c.bold('options')}
53
54
  -u, --base-url <url> use this server for this run (add --save to keep it)
54
55
  -m, --model <name> this model alone for this run (provider/model, or a model of #1's provider);
55
- "auto" (the default): your list, #1 then the next when one fails
56
+ "auto" (the default): the list, #1 then the next when one fails
56
57
  --fallback-model <name> after -m's model when it fails (repeatable)
57
58
  --api-key <key> API key for --base-url
58
- -y, --yes do everything without asking (the default)
59
+ -y, --yes do everything without asking (the default; through --acp, an editor: ask)
59
60
  --ask ask before every edit and command, this run
60
61
  --hide-thinking the model's thinking: only its last two lines while it thinks (the default; Alt+O shows all of it)
61
62
  -C, --cwd <dir> project folder (default: current folder)
62
- --temp keep nothing: a throwaway settings folder (your providers, model info,
63
+ --temp keep nothing: a throwaway settings folder (providers, model info,
63
64
  prices and notes copied in), shared by the --temp runs going on at once
64
65
  and deleted after the last, with its logs; ~/.heart and the project's
65
66
  .heartcode/ aren't touched (their notes and research are read from a copy)
@@ -93,23 +94,24 @@ ${c.bold('headless')} (for other programs; flags and output as in Claude Code's
93
94
  ${c.bold('editors')} heartcode --acp the Agent Client Protocol on stdin/stdout (Zed, JetBrains, Neovim)
94
95
 
95
96
  ${c.bold('env')} HEART_BASE_URL, HEART_MODEL, HEART_API_KEY (or OPENAI_BASE_URL / OPENAI_API_KEY)
96
- HEART_LOG=<file> every kind of log of this run in that one file, whatever is switched on (off: none)
97
+ HEART_LOG=<file> every text log of this run in that one file, whatever is switched on (requests stay
98
+ in their own folder); HEART_LOG=off: no logs at all
97
99
 
98
100
  ${c.bold('in a session')} attach an image with @path/to/shot.png · /help for commands`
99
101
 
100
102
  // [name, description, takes an argument], by section. /help and the "/" menu are built from it.
101
103
  const SECTIONS = [
102
104
  ['providers and models', [
103
- ['/select_model', 'pick the model(s) for this session: one pins it, several rotate among them, auto = your whole list', true],
105
+ ['/select_model', 'pick the model(s) for this session: one pins it, several rotate among them, auto = the whole list', true],
104
106
  ]],
105
107
  ['settings', [
106
108
  ['/toggle_thinking', "the model's thinking: its last two lines, or all of it (Alt+O)"],
107
- ['/voice', 'say your message (or Space in an empty box): it shows in the box as you speak, Enter sends it, Esc cancels'],
109
+ ['/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'],
108
110
  ]],
109
111
  ['session', [
110
112
  ['/resume', 'continue an earlier session in this folder'],
111
113
  ['/rewind', 'go back to an earlier message: conversation, code or both (Esc Esc); what came after stays in /tree'],
112
- ['/tree', "every message on every branch of this session: go to any, the files follow, a summary of what you leave comes along"],
114
+ ['/tree', "every message on every branch of this session: go to any, the files follow, a summary of the branch left behind comes along"],
113
115
  ['/rename', 'name this session (shown in /resume)', true],
114
116
  ['/fork', 'go on in a copy of this session (the original stays in /resume)'],
115
117
  ['/export', 'save the conversation as Markdown, HTML or JSON', true],
@@ -126,14 +128,14 @@ const SECTIONS = [
126
128
  ['/install_skill', 'install a skill from a GitHub repo or a SKILL.md URL (add --project for this folder only)', true],
127
129
  ['/doctor', 'check the outside tools HeartCode features need (voice, browser, git) and what to install'],
128
130
  ['/update', 'install the newest HeartCode (shows what changed first)'],
129
- ['/mcp', 'your MCP servers and whether each needs signing in'],
131
+ ['/mcp', 'the MCP servers and whether each needs signing in'],
130
132
  ['/login_mcp', 'sign in (again) to a remote MCP server', true],
131
133
  ['/compact', 'summarize the conversation to free up context (add what to keep)', true],
132
134
  ['/clear_chat', 'forget the conversation'],
133
135
  ['/reset', "HeartCode's settings (or also providers, or everything) back to the start; asks for a code first"],
134
- ['/settings', 'change providers, models, settings, MCP servers, hooks, keys and skills in your browser'],
136
+ ['/settings', 'change providers, models, settings, MCP servers, hooks, keys and skills in the browser'],
135
137
  ['/help', 'this list'],
136
- ['/tab', 'a new tab (Alt+T): another conversation beside this one · /tab worktree [name]: in its own git worktree · /tab 2: go to tab 2 (Alt+N/P) · Alt+W closes one', true],
138
+ ['/tab', 'a new tab (Alt+T): another conversation beside this one · /tab worktree [name]: in its own git worktree · /tab 2: go to tab 2 (Alt+2; Alt+N/P: the next or previous) · Alt+W closes one', true],
137
139
  ['/close_tab', 'close this tab (Alt+W); asks first'],
138
140
  ['/exit', 'quit HeartCode (Alt+W closes just this tab)'],
139
141
  ]],
@@ -149,19 +151,18 @@ const SLASH = helpText(SECTIONS)
149
151
 
150
152
  // The keyboard shortcuts, as [keys, what] rows, read from the effective keybindings (keybindings.json
151
153
  // can change any of them) plus the fixed ones (Space, Enter, Esc, Shift+Tab, Ctrl+C).
152
- function keysHelp(keys = {}, mouse = false) {
153
- const NAMES = { pageup: 'PgUp', pagedown: 'PgDn', up: '↑', down: '↓', left: '←', right: '→', ctrl: 'Ctrl', alt: 'Alt', shift: 'Shift' }
154
- const pretty = (k) => k.split('+').map((p) => NAMES[p] ?? (p.length === 1 ? p.toUpperCase() : p[0].toUpperCase() + p.slice(1))).join('+')
155
- const forAct = (a) => Object.entries(keys).filter(([, v]) => v === a).map(([k]) => pretty(k)).join(' / ')
156
- const tabs = /(^|,)alt\+[1-9]/.test(Object.keys(keys).join(','))
154
+ function keysHelp(keys = {}, mouse = false, voice = false) {
155
+ const forAct = (a) => Object.entries(keys).filter(([, v]) => v === a).map(([k]) => prettyKey(k)).join(' / ')
156
+ const tabs = Object.values(keys).some((v) => /^tab_[1-9]$/.test(v))
157
157
  const rows = [
158
- ['Space', 'voice: listens at once, Enter sends what you said (in an empty box)'],
158
+ [voice ? 'Space' : '', 'voice: listens at once, Enter sends what was said (in an empty box)'],
159
159
  ['Enter', 'send · while it works, queue the message (commands like /help, /cost, /select_model run at once)'],
160
- ['Option+Enter or Shift+Enter', 'new line in the box'],
161
- ['Esc', 'stop the task (press twice to confirm)'],
160
+ ['Option+Enter or Shift+Enter', 'new line in the box (also while it works)'],
161
+ ['Esc', 'while it works: queued messages back into the box, then clears the box, then stops the task (twice)'],
162
162
  ['Esc Esc', 'rewind to an earlier message (at the prompt)'],
163
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)"],
164
+ [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"],
165
+ [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"],
165
166
  [forAct('new_tab'), 'new tab'],
166
167
  [forAct('close_tab'), 'close this tab'],
167
168
  [forAct('next_tab'), 'next tab'],
@@ -182,13 +183,13 @@ function keysHelp(keys = {}, mouse = false) {
182
183
  return rows
183
184
  }
184
185
 
185
- const HOWTO = `${c.yellow('No model set up yet.')} Add a provider and choose its models in your browser:
186
+ const HOWTO = `${c.yellow('No model set up yet.')} Add a provider and choose its models in the browser:
186
187
 
187
188
  ${c.cyan('/settings')} (or ${c.cyan('heart settings')} in another terminal)
188
189
 
189
190
  ${c.dim('Ollama, LM Studio or llama.cpp running on this machine is found on its own.')}`
190
191
  const NO_MODELS = `${c.yellow('No model chosen yet.')} Choose one on ${c.cyan('/settings')}: a provider's models, click one.`
191
- const ALL_OFF = `${c.yellow('The providers of all your models are switched off.')} Switch one on on ${c.cyan('/settings')}, or add a model of one that's on.`
192
+ const ALL_OFF = `${c.yellow('The providers of all the models are switched off.')} Switch one on on ${c.cyan('/settings')}, or add a model of one that's on.`
192
193
 
193
194
  // Choices for commands that take one (also offered in the "/" menu).
194
195
  const ARGS = {
@@ -248,10 +249,10 @@ class App {
248
249
  // a remote server asks to sign in: its page opens in the browser (and the link is shown)
249
250
  if (!this.ui.noUser)
250
251
  mcp.onSignIn = (name, url) => {
251
- this.ui.print(`${c.info('↗')} ${c.bold(name)} ${c.muted('needs you to sign in; opening your browser…')}\n ${c.faint(url)}`)
252
+ this.ui.print(`${c.info('↗')} ${c.bold(name)} ${c.muted('needs a sign-in; opening the browser…')}\n ${c.faint(url)}`)
252
253
  const [cmd, ...args] = process.platform === 'darwin' ? ['open', url] : process.platform === 'win32' ? ['rundll32', 'url.dll,FileProtocolHandler', url] : ['xdg-open', url]
253
254
  spawnSync(cmd, args, { stdio: 'ignore' })
254
- this.ui.spinner(`waiting for you to sign in to ${name} in the browser · Esc to stop`)
255
+ this.ui.spinner(`waiting for the sign-in to ${name} in the browser · Esc twice to stop`)
255
256
  }
256
257
  return mcp
257
258
  }
@@ -367,9 +368,11 @@ class App {
367
368
  client.onSwitch = (t) => {
368
369
  const i = client.rotation.list.indexOf(t)
369
370
  const f = failed?.e
371
+ const from = failed?.t
370
372
  const why = f ? `${failed.t.model} ${f.status === 429 ? 'rate-limited (429)' : `failed (${clip(shortError(f), 50)})`} → ` : ''
371
373
  failed = null
372
- switched = c.dim(`↻ ${why}${t.provider} · ${t.model} answered${i ? ` (#${i + 1} in your model list)` : ' (#1 again)'}`)
374
+ switched = c.dim(`↻ ${why}${t.provider} · ${t.model} answered${i ? ` (#${i + 1} in the model list)` : ' (#1 again)'}`)
375
+ 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 })
373
376
  setImmediate(client.announceSwitch)
374
377
  }
375
378
  if (cfg.maxRetries !== undefined) client.retryIf = (e, attempt) => attempt < cfg.maxRetries // headless: then give up
@@ -553,7 +556,7 @@ class App {
553
556
  // leave is kept, the files can follow, and a summary of what you leave can come along.
554
557
  async tree() {
555
558
  const { ui, chat } = this
556
- if (!chat.turns.length && !chat.branches?.length) return ui.print('Nothing here yet: the tree grows as you send messages and go back (/rewind, /tree).')
559
+ if (!chat.turns.length && !chat.branches?.length) return ui.print('Nothing here yet: the tree grows as messages are sent and rewound (/rewind, /tree).')
557
560
  chat.log = ui.log
558
561
  const n = (chat.branches?.length ?? 0) + 1
559
562
  const it = await ui.pick(`This session${n > 1 ? `, ${n} branches` : ''} · pick a message`, treeItems(chat, ago))
@@ -578,7 +581,7 @@ class App {
578
581
  }
579
582
  let summarize = false
580
583
  if (leaving(chat, it.branch, go.keep) && (this.s || this.cfg.providers[this.cfg.provider])) {
581
- const a = await ui.pick('Bring a summary of the messages you leave?', [
584
+ const a = await ui.pick('Bring a summary of the messages left behind?', [
582
585
  { label: 'Yes', desc: 'one request to the model, so this branch knows what was tried there', yes: true },
583
586
  { label: 'No', desc: 'they stay in the tree, the model just won\'t know about them' },
584
587
  ])
@@ -592,13 +595,13 @@ class App {
592
595
  if (summarize) {
593
596
  const s = await this.session()
594
597
  if (s) {
595
- ui.spinner('summarizing the branch you left')
598
+ ui.spinner('summarizing the branch left behind')
596
599
  try {
597
600
  const changedThere = leftFiles(left)
598
601
  const summary = await s.summarizeBranch(leftText(left, transcript), changedThere, this.signal)
599
602
  chat.branchNote = prompt('compact/branch-note', { summary, files: changedThere.join(', '), kept: changedThere.length && !code, restored: changedThere.length && code })
600
603
  ui.stopSpin()
601
- ui.print(`${c.faint('✻')} ${c.muted(`summary of the branch you left (goes with your next message): ${clip(summary.split('\n').find((l) => l.trim()) ?? '', 120)}`)}`)
604
+ ui.print(`${c.faint('✻')} ${c.muted(`summary of the branch left behind (goes with the next message): ${clip(summary.split('\n').find((l) => l.trim()) ?? '', 120)}`)}`)
602
605
  } catch (e) {
603
606
  ui.stopSpin()
604
607
  if (e.name === 'AbortError') throw e
@@ -606,7 +609,7 @@ class App {
606
609
  }
607
610
  }
608
611
  }
609
- ui.print(c.dim(`${go.edit ? 'edit the message and send it: a new branch' : 'here now'} · the branch you left stays in /tree`))
612
+ ui.print(c.dim(`${go.edit ? 'edit the message and send it: a new branch' : 'here now'} · the branch left behind stays in /tree`))
610
613
  if (go.edit) this.nextInput = it.task
611
614
  if (this.s) this.s.client.lastTokens = 0
612
615
  this.save()
@@ -632,8 +635,8 @@ class App {
632
635
  help() {
633
636
  const mine = this.commands().slice(COMMANDS.length)
634
637
  const sections = [...SECTIONS]
635
- if (mine.length) sections.push(['your skills (type /skill:name)', mine])
636
- sections.push(['keyboard', keysHelp(this.ui.keys, this.cfg?.mouse !== false)])
638
+ if (mine.length) sections.push(['skills (type /skill:name)', mine])
639
+ sections.push(['keyboard', keysHelp(this.ui.keys, this.cfg?.mouse !== false, Boolean(this.ui.voiceReady?.()))])
637
640
  return helpText(sections)
638
641
  }
639
642
 
@@ -697,7 +700,7 @@ class App {
697
700
  if (!cfg.providers[cfg.provider] || !cfg.model) return c.dim('no model · /settings to choose one')
698
701
  const rot = this.s?.client.rotation
699
702
  const now = this.inUse() // the model list's one in use; never one of a provider that's off
700
- if (!now) return c.dim('the providers of all your models are off · /settings to switch one on')
703
+ if (!now) return c.dim('the providers of all the models are off · /settings to switch one on')
701
704
  const count = this.sessionModels().length
702
705
  // the model answering now; a yellow "↻" before it when it's a fallback (rotated to after one failed)
703
706
  const rotated = rot && rot.at > 0
@@ -712,7 +715,7 @@ class App {
712
715
  const parts = {
713
716
  provider: `${c.brand('●')} ${c.muted(now.provider)}`,
714
717
  model,
715
- mode: strat ? (strat.actions === 'tools' ? null : c.muted('no tool calls (guided)')) : c.faint('checked at your first message'), // what it can do: known once it's been asked
718
+ 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
716
719
  thinking: strat?.thinking ? c.think(`thinking · ${effortOf(cfg)}`) + (ui.showThinking ? c.faint(' (all)') : '') : null,
717
720
  images: strat?.vision ? c.muted('images') : null,
718
721
  ctx: null,
@@ -849,13 +852,26 @@ class App {
849
852
  return this.sessionModels()
850
853
  .filter((t) => !(t.provider === now?.provider && t.model === now?.model))
851
854
  .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)
852
- .sort(this.byProvider()) // helpers picked in your list's order, or your provider ranking's (Your models)
855
+ .sort(this.byProvider()) // helpers picked in your list's order, your provider ranking's, or by score (Your models)
853
856
  }
854
857
 
855
858
  // Your models' "Helper order": by your provider ranking, a sort that puts the higher-ranked
856
859
  // provider's models first (each provider's in your list's order; providers not ranked after, A to
857
860
  // Z); in your list's order, one that keeps it.
861
+ // By score: the best placed in LMArena's rankings first (its best share of a list: #5 of 200 is 2.5%),
862
+ // across the lists the helpers are picked by (coding, web apps, long real tasks, hard prompts);
863
+ // models not in them after, in your list's order.
858
864
  byProvider() {
865
+ if (this.cfg.helperOrder === 'score') {
866
+ const data = loadRankings()
867
+ const share = new Map()
868
+ const of = (t) => {
869
+ const k = `${t.provider}/${t.model}`
870
+ if (!share.has(k)) share.set(k, Math.min(...['text:coding', 'webdev:webdev', 'agent:overall', 'text:hard_prompts'].map((l) => rankIn(t.model, l, data)).filter(Boolean).map((r) => r.rank / r.of), Infinity))
871
+ return share.get(k)
872
+ }
873
+ return (a, b) => (of(a) === of(b) ? 0 : of(a) < of(b) ? -1 : 1) // Infinity (not ranked) last; ties keep your order
874
+ }
859
875
  const rank = this.cfg.helperOrder === 'provider' && Array.isArray(this.cfg.providerRank) ? this.cfg.providerRank : null
860
876
  if (!rank) return () => 0
861
877
  const at = (p) => (rank.includes(p) ? rank.indexOf(p) : rank.length)
@@ -912,7 +928,7 @@ class App {
912
928
  const { cfg } = this
913
929
  if (!cfg.session) return this.myModels(all)
914
930
  const seen = new Set()
915
- 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}`))
931
+ return cfg.session.filter((t) => cfg.providers[t.provider] && (all || cfg.pinned || !cfg.providers[t.provider].off) && t.model && !seen.has(`${t.provider}/${t.model}`) && seen.add(`${t.provider}/${t.model}`))
916
932
  }
917
933
 
918
934
  // Alt+B, /background: the background commands' logs in a dialog, one at a time with a tab each.
@@ -1017,7 +1033,7 @@ class App {
1017
1033
  this.s = null
1018
1034
  }
1019
1035
  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(', '))}`
1020
- if (later) return this.later.push(apply), this.ui.print(`${msg} ${c.dim('· from your next message')}`)
1036
+ if (later) return this.later.push(apply), this.ui.print(`${msg} ${c.dim('· from the next message')}`)
1021
1037
  apply()
1022
1038
  this.ui.print(msg)
1023
1039
  await this.session()
@@ -1034,7 +1050,7 @@ class App {
1034
1050
  }
1035
1051
  const n = this.myModels().length
1036
1052
  const msg = `${c.green('using')} ${c.dim('auto')} ${c.cyan(`(${n} model${n === 1 ? '' : 's'})`)}`
1037
- if (later) return this.later.push(apply), this.ui.print(`${msg} ${c.dim('· from your next message')}`)
1053
+ if (later) return this.later.push(apply), this.ui.print(`${msg} ${c.dim('· from the next message')}`)
1038
1054
  apply()
1039
1055
  this.ui.print(msg)
1040
1056
  await this.session()
@@ -1053,7 +1069,7 @@ class App {
1053
1069
  const chosen = new Set((cfg.session ?? mine).map(key)) // pre-ticked: this session's set, or all (auto)
1054
1070
  const items = mine.map((t) => ({ label: t.model, t, checked: chosen.has(key(t)), desc: this.modelDesc(t, mine.indexOf(t)) }))
1055
1071
  // first, standing alone: back to auto (Enter on it, whatever is ticked)
1056
- const auto = { label: 'auto', only: true, auto: true, desc: `your whole list, in its order (${mine.length} model${mine.length === 1 ? '' : 's'})${cfg.session ? ' · forgets what this folder picked' : ' · in use'}` }
1072
+ const auto = { label: 'auto', only: true, auto: true, desc: `the whole list, in its order (${mine.length} model${mine.length === 1 ? '' : 's'})${cfg.session ? ' · forgets what this folder picked' : ' · in use'}` }
1057
1073
  const guessed = mine.some((t) => this.abilities(t).guessed) ? "\n~128k and the like: the window's size is a guess (models.dev doesn't list the model)" : ''
1058
1074
  const picked = await ui.pick('Models for this session', [auto, ...items], { filter, multi: true, body: `Tick several to rotate among them, one to pin it, or choose auto.${guessed}` })
1059
1075
  if (!picked) return
@@ -1083,7 +1099,7 @@ class App {
1083
1099
  const missing = []
1084
1100
  for (const spec of specs) (resolve(spec) ? found : missing).push(resolve(spec) ?? spec)
1085
1101
  if (missing.length || !found.length) {
1086
- if (missing.length) this.ui.print(c.dim(`not in your models: ${missing.join(', ')} · add on /settings`))
1102
+ if (missing.length) this.ui.print(c.dim(`not in the model list: ${missing.join(', ')} · add on /settings`))
1087
1103
  return this.chooseModel(specs.length === 1 ? specs[0] : '', later)
1088
1104
  }
1089
1105
  return this.setSession(found, later)
@@ -1174,7 +1190,7 @@ async function continueTabs(app, saved) {
1174
1190
  if (!open.length) return
1175
1191
  const many = open.length > 1
1176
1192
  const newest = open.map((t) => t.chat.updated).sort().at(-1)
1177
- const go = await ui.pick(many ? `Continue where you left off? ${open.length} tabs` : 'Continue your last session here?', [
1193
+ const go = await ui.pick(many ? `Continue where it left off? ${open.length} tabs` : 'Continue the last session here?', [
1178
1194
  { label: many ? `Yes, with its ${open.length} tabs` : 'Yes', desc: `${open.map((t) => `"${t.chat.title}"`).join(', ')} · ${ago(newest)}`, yes: true },
1179
1195
  { label: 'No, start a new session', desc: '/resume finds it later' },
1180
1196
  ], { quiet: true, fixed: true })
@@ -1200,8 +1216,8 @@ async function continueTabs(app, saved) {
1200
1216
  // A continued tab's own model, as it was (unless its provider is gone: then the current one).
1201
1217
  function useModel(app, { provider, model }) {
1202
1218
  if (!provider || !model || (provider === app.cfg.provider && model === app.cfg.model)) return
1203
- if (!app.cfg.providers[provider]) return app.ui.warn(`this tab used ${provider} · ${model}, but there's no provider "${provider}" now: using your list`)
1204
- if (app.cfg.providers[provider].off) return app.ui.warn(`this tab used ${provider} · ${model}, but ${provider} is switched off: using your list`)
1219
+ if (!app.cfg.providers[provider]) return app.ui.warn(`this tab used ${provider} · ${model}, but there's no provider "${provider}" now: using the list`)
1220
+ if (app.cfg.providers[provider].off) return app.ui.warn(`this tab used ${provider} · ${model}, but ${provider} is switched off: using the list`)
1205
1221
  Object.assign(app.cfg, { provider, model })
1206
1222
  app.s = null
1207
1223
  }
@@ -1235,13 +1251,13 @@ function applySettings(apps, cfg, what) {
1235
1251
  const { ui } = app
1236
1252
  const busy = Boolean(ui.busySince || app.working)
1237
1253
  const now = (fn) => (busy ? app.later.push(fn) : fn())
1238
- if (app.cfg !== cfg) for (const k of ['providers', 'provider', 'model', 'effort', 'theme', 'context', 'autoCompact', 'director', 'format', 'lsp', 'voice', 'rotation', 'statusBar']) app.cfg[k] = cfg[k]
1254
+ 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]
1239
1255
  // a model pinned in this CLI (/select_model) is a session choice: a model/order change on the
1240
1256
  // settings page leaves it alone (only /select_model auto here returns it to the list)
1241
1257
  if (what === 'model' && !app.cfg.session) {
1242
1258
  app.lists = {}
1243
1259
  if (app.s && !(cfg.providers[cfg.provider] && cfg.model)) now(() => ((app.s = null), ui.print(c.dim('settings: no model chosen'))))
1244
- else if (app.s && !app.myModels().length) now(() => ((app.s = null), ui.print(c.dim('settings: the providers of all your models are switched off'))))
1260
+ 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'))))
1245
1261
  }
1246
1262
  // your model list: into the running session now, its next request goes to the new #1
1247
1263
  if (['model', 'setting:rotation'].includes(what) && !app.cfg.session && app.s && cfg.providers[cfg.provider] && cfg.model) {
@@ -1420,13 +1436,13 @@ async function slash(app, line, working = false) {
1420
1436
  const n = app.tabs?.list.length ?? 1
1421
1437
  if (n > 1 || working) {
1422
1438
  const go = await ui.pick(`Quit HeartCode?${working ? ' It is still working: that stops.' : ''}${n > 1 ? ` ${n} tabs are open` : ''}`, [
1423
- { label: 'Yes, quit', desc: 'they come back next time you start HeartCode here', yes: true },
1439
+ { label: 'Yes, quit', desc: 'they come back the next time HeartCode starts here', yes: true },
1424
1440
  { label: 'No', desc: 'Alt+W closes just this tab' },
1425
1441
  ])
1426
1442
  if (!go?.yes) return
1427
1443
  }
1428
1444
  if (!working && app.s?.wrapping) {
1429
- ui.spinner('keeping what the last task learned · Ctrl+C to quit now')
1445
+ ui.spinner('keeping what the last task learned · Ctrl+C twice to quit now')
1430
1446
  await app.s.wrapping
1431
1447
  }
1432
1448
  return 'exit'
@@ -1437,7 +1453,7 @@ async function slash(app, line, working = false) {
1437
1453
  const home = process.env.HOME
1438
1454
  const tilde = (f) => (home && f.startsWith(home) ? '~' + f.slice(home.length) : f)
1439
1455
  const files = resetPaths(it.level)
1440
- const what = [...(it.level === 'settings' ? [`the settings in ${tilde(CONFIG_FILE)} (not your providers, keys or model)`] : []), ...files.map(tilde)]
1456
+ const what = [...(it.level === 'settings' ? [`the settings in ${tilde(CONFIG_FILE)} (not the providers, keys or model)`] : []), ...files.map(tilde)]
1441
1457
  ui.print(`${c.warn('!')} ${c.bold(`Reset: ${it.label.toLowerCase()}.`)} ${c.muted("This can't be undone. It removes:")}\n${what.length ? what.map((f) => ` ${c.faint('·')} ${f}`).join('\n') : c.faint(' (nothing there yet)')}`)
1442
1458
  const code = resetCode()
1443
1459
  const typed = await ui.ask(` Type ${c.bold(code)} to reset ${c.dim('(anything else: no)')}: `)
@@ -1451,7 +1467,7 @@ async function slash(app, line, working = false) {
1451
1467
  settingsPage ??= startSettings({ cfg, root: app.root, onLoginMcp: (name) => signInMcp(app, name, null), apply: (what) => applySettings(app.tabs ? app.tabs.list.map((t) => t.app) : [app], cfg, what) })
1452
1468
  const { url, local, close } = await settingsPage
1453
1469
  openBrowser(local)
1454
- if (!ui.full) ui.print(`${c.info('↗')} ${c.bold('settings')} ${c.muted(overSsh ? 'open this link in your browser:' : 'opened in your browser:')}\n ${c.faint(url)}`)
1470
+ if (!ui.full) ui.print(`${c.info('↗')} ${c.bold('settings')} ${c.muted(overSsh ? 'open this link in a browser:' : 'opened in the browser:')}\n ${c.faint(url)}`)
1455
1471
  // a dialog until it's turned off: nothing else meanwhile, in any tab (Esc turns it off too).
1456
1472
  // Not busy meanwhile: what's changed on the page applies at once, here too (opened while a task
1457
1473
  // works: once it's done).
@@ -1459,7 +1475,7 @@ async function slash(app, line, working = false) {
1459
1475
  if (app.tabs) app.tabs.locked = true
1460
1476
  ui.setMouse(false) // the terminal's own selection for the link: OSC 52 copying fails in some terminals
1461
1477
  try {
1462
- await ui.pick('The settings page is on', [{ label: 'Turn off', desc: 'stops the page and gives HeartCode back' }], { fixed: true, quiet: true, ctrlC: true, body: `${overSsh ? 'Open this link in your browser:' : "It's open in your browser:"}\n${url}\n\nTo copy it, select it with the mouse.\nWhat you change there applies right away.` })
1478
+ await ui.pick('The settings page is on', [{ label: 'Turn off', desc: 'stops the page and gives HeartCode back' }], { fixed: true, quiet: true, ctrlC: true, body: `${overSsh ? 'Open this link in a browser:' : "It's open in the browser:"}\n${url}\n\nTo copy it, select it with the mouse.\nChanges there apply right away.` })
1463
1479
  } finally {
1464
1480
  ui.setMouse(cfg.mouse !== false)
1465
1481
  if (app.tabs) app.tabs.locked = false
@@ -1491,9 +1507,9 @@ async function slash(app, line, working = false) {
1491
1507
  if (!u.newer) return ui.print(c.dim(`HeartCode ${u.current} is the newest`))
1492
1508
  const kind = installKind()
1493
1509
  const notes = await whatsNew(u.current, u.latest)
1494
- if (kind === 'git') return ui.showText(`HeartCode ${u.latest} is out (you have ${u.current})`, `${notes || '(no changelog found)'}\n\nThis HeartCode runs from a git checkout (${packageDir}): update it there with git pull.`)
1510
+ 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.`)
1495
1511
  const cmd = UPDATE_COMMANDS[kind]
1496
- ui.showText(`HeartCode ${u.latest} is out (you have ${u.current})`, notes || '(no changelog found)')
1512
+ ui.showText(`HeartCode ${u.latest} is out (this is ${u.current})`, notes || '(no changelog found)')
1497
1513
  if ((await ui.confirm(`Update now with ${c.bold(cmd)}?`, 'command')) !== true) return ui.print(c.dim('not updated'))
1498
1514
  ui.spinner(`running ${cmd}`)
1499
1515
  const r = await runCommand(process.cwd(), cmd, { timeout: 300_000 })
@@ -1518,7 +1534,7 @@ async function slash(app, line, working = false) {
1518
1534
  const was = app.chat.id
1519
1535
  app.setChat(forkChat(app.chat))
1520
1536
  app.save()
1521
- return ui.print(c.dim(`forked: you're in "${app.chat.name}" now; the original (${was}) stays in /resume`))
1537
+ return ui.print(c.dim(`forked: now in "${app.chat.name}"; the original (${was}) stays in /resume`))
1522
1538
  }
1523
1539
  case 'export': {
1524
1540
  if (!app.chat.turns.length) return ui.print('Nothing to export yet.')
@@ -1563,7 +1579,7 @@ async function slash(app, line, working = false) {
1563
1579
  const answer = app.chat.history.at(-1)?.answer?.trim()
1564
1580
  if (!answer) return ui.print('No answer to copy yet.')
1565
1581
  const how = copyText(answer)
1566
- return ui.print(c.dim(`copied the last answer (${answer.split('\n').length} lines)${how === 'osc' ? ' if your terminal allows it' : ''}`))
1582
+ return ui.print(c.dim(`copied the last answer (${answer.split('\n').length} lines)${how === 'osc' ? ' if the terminal allows it' : ''}`))
1567
1583
  }
1568
1584
  case 'background': {
1569
1585
  const jobs = listJobs(app.root)
@@ -1583,7 +1599,7 @@ async function slash(app, line, working = false) {
1583
1599
  }
1584
1600
  case 'context': {
1585
1601
  const s = app.s
1586
- if (!s?.messages?.length) return ui.print('Nothing in the context yet: it fills with your first message.')
1602
+ if (!s?.messages?.length) return ui.print('Nothing in the context yet: it fills with the first message.')
1587
1603
  const r = contextReport(s)
1588
1604
  const share = (n) => (r.window ? `${Math.round((n / r.window) * 100)}%` : '')
1589
1605
  const bar = (n) => c.brand('█'.repeat(r.window ? Math.round((n / r.window) * 40) : 0) || (n ? '▏' : ''))
@@ -1731,7 +1747,7 @@ async function slash(app, line, working = false) {
1731
1747
  const name = cmd.slice(6)
1732
1748
  const k = app.skills.get(name)
1733
1749
  if (k && (k.use === 'me' || k.use === 'both')) return runTask(app, await app.expandSkill(k, args.join(' ')), { signal: app.signal })
1734
- return ui.print(`unknown skill /skill:${name} ${c.dim('· /help lists your skills')}`)
1750
+ return ui.print(`unknown skill /skill:${name} ${c.dim('· /help lists the skills')}`)
1735
1751
  }
1736
1752
  if (app.skills.has(cmd)) return ui.print(`${c.dim(`/${cmd} is a skill — run it as`)} ${c.cyan(`/skill:${cmd}`)}`) // bare skill name: point to the namespaced form
1737
1753
  return ui.print(`unknown command /${cmd} ${c.dim('· /help lists them')}`)
@@ -1799,7 +1815,7 @@ async function repl(app, f = {}) {
1799
1815
  .catch((e) => (log('error', e.stack), ui.print(c.red(`error: ${e.message}`))))
1800
1816
  return true
1801
1817
  }
1802
- 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)
1818
+ ui.onWaiting = (question) => notify(cfg, 'waiting', `⏳ Waiting for an answer · ${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)
1803
1819
  ui.isCommand = (l) => app.isCommand(l)
1804
1820
  loadPrices().then(() => ui.render?.()) // models.dev: what each model can do, for the model lists
1805
1821
  ui.voiceConfig = () => ({ voice: cfg.voice, providers: cfg.providers })
@@ -1862,7 +1878,7 @@ async function repl(app, f = {}) {
1862
1878
  ui.folder = app.root // what a double click on the header's folder copies
1863
1879
  ui.header = (cols = 100) => {
1864
1880
  const room = cols - 2 - width(`♥ HeartCode ${VERSION} `) // the folder's own name (its end) stays in sight
1865
- const keys = [['/', 'run a command'], ['@', 'attach a file'], ...(ui.voiceReady?.() ? [['Space', 'talk (voice)']] : []), [NEWLINE_KEY, 'add a new line'], ['Esc', 'stop'], ['Shift+Tab', 'change permissions']]
1881
+ 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']]
1866
1882
  // the keys: on a second line when they don't fit one, broken between keys (never inside one)
1867
1883
  const rows = []
1868
1884
  for (const kd of keys) {
@@ -1890,7 +1906,7 @@ async function repl(app, f = {}) {
1890
1906
  else if (f.resume) await app.resume()
1891
1907
  if (f.model) useModel(app, f.model) // a continued tab's own model
1892
1908
  // models this folder picked earlier (/select_model): said, with the way back to your whole list
1893
- 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`)}`)
1909
+ 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`)}`)
1894
1910
  app.tabs?.onChange?.() // the conversation it opened with
1895
1911
  // a newer HeartCode: asked of npm in the background at every start, said once and kept in the status bar
1896
1912
  if (cfg.updateCheck !== false)
@@ -1898,7 +1914,7 @@ async function repl(app, f = {}) {
1898
1914
  .then((u) => {
1899
1915
  if (!u?.newer) return
1900
1916
  app.update = u
1901
- ui.print(`${c.green('⬆')} ${c.muted('HeartCode')} ${c.green(u.latest)} ${c.muted(`is out (you have ${u.current})`)} ${c.faint('·')} ${c.cyan('/update')}`)
1917
+ ui.print(`${c.green('⬆')} ${c.muted('HeartCode')} ${c.green(u.latest)} ${c.muted(`is out (this is ${u.current})`)} ${c.faint('·')} ${c.cyan('/update')}`)
1902
1918
  ui.render?.()
1903
1919
  })
1904
1920
  .catch(() => {})
@@ -1959,6 +1975,7 @@ async function main() {
1959
1975
  // that starts with "page" ("page fix the footer") is a prompt
1960
1976
  const target = process.argv[3]
1961
1977
  if (process.argv[2] === 'page' && process.argv.length === 4 && (/^https?:\/\//.test(target) || fs.existsSync(target))) return (process.exitCode = await (await import('../src/check.js')).pageCommand(target))
1978
+ if (process.argv[2] === 'page' && process.argv.length === 4 && /[./\\]/.test(target)) return console.error(`heart page: no such file: ${target}`), (process.exitCode = 1) // a file meant, not there: not taken as a task
1962
1979
  // "--resume <id>" (as in Claude Code) vs a bare "--resume" (pick one): an id follows it
1963
1980
  const argv = process.argv.slice(2)
1964
1981
  const print = argv.includes('-p') || argv.includes('--print') // headless: an id after --resume is always an id
@@ -2021,19 +2038,26 @@ async function main() {
2021
2038
  for (const k of ['output-format', 'input-format']) if (f[k] && !['text', 'json', 'stream-json'].includes(f[k])) throw new Error(`--${k} must be text, json or stream-json`)
2022
2039
  if (f['permission-mode'] && !PERMISSION_MODES[f['permission-mode']]) throw new Error(`--permission-mode must be one of ${Object.keys(PERMISSION_MODES).join(', ')}`)
2023
2040
 
2024
- const cfg = loadConfig({ baseUrl: f['base-url'], model: f.model, apiKey: f['api-key'], context: f.context })
2041
+ if (f.effort && !['default', 'low', 'medium', 'high'].includes(f.effort)) throw new Error('--effort must be low, medium, high or default')
2042
+ 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 })
2025
2043
  setTheme(cfg.theme)
2026
2044
  useLogs(cfg)
2027
2045
  const safe = { ...cfg, providers: Object.fromEntries(Object.entries(cfg.providers).map(([n, p]) => [n, { ...p, apiKey: p.apiKey && mask(p.apiKey) }])) }
2028
2046
  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 })
2047
+ // --provider: one model alone, as -m does: with -m, that one (above); alone, that provider's first
2048
+ // model in your list
2029
2049
  if (f.provider) {
2030
2050
  if (!cfg.providers[f.provider]) throw new Error(`no provider "${f.provider}" (heartcode providers lists them)`)
2031
- Object.assign(cfg, { provider: f.provider, fixed: true })
2051
+ if (!f.model) {
2052
+ const t = [{ provider: cfg.provider, model: cfg.model }, ...(cfg.rotation?.then ?? [])].find((x) => x.provider === f.provider && x.model)
2053
+ if (!t) throw new Error(`--provider ${f.provider}: no model in the list is from it; add -m <model>`)
2054
+ Object.assign(cfg, { ...t, session: [t], pinned: true })
2055
+ }
2032
2056
  }
2033
2057
  // --fallback-model: after the model given (as in Claude Code's -p), when it fails
2034
2058
  cfg.fallbacks = (f['fallback-model'] ?? []).map((v) => {
2035
2059
  const t = parseModel(v, cfg.providers, cfg.provider)
2036
- if (isAuto(v) || !cfg.providers[t.provider]) throw new Error(`--fallback-model ${v}: give provider/model, or a model of ${cfg.provider} (heart models lists yours)`)
2060
+ if (isAuto(v) || !cfg.providers[t.provider]) throw new Error(`--fallback-model ${v}: give provider/model, or a model of ${cfg.provider} (heart models lists them)`)
2037
2061
  return t
2038
2062
  })
2039
2063
  if (f.effort) cfg.effort = f.effort === 'default' ? undefined : f.effort
@@ -2041,6 +2065,8 @@ async function main() {
2041
2065
  extraSkillDirs.push(...(f['skills-dir'] ?? []).map((d) => path.resolve(d)))
2042
2066
  if (f.save) {
2043
2067
  cfg.adhoc = null
2068
+ // the model given (-m, -u): saved as #1, not just for this run
2069
+ if (cfg.session?.length) [cfg.provider, cfg.model, cfg.session, cfg.pinned] = [cfg.session[0].provider, cfg.session[0].model, undefined, undefined]
2044
2070
  saveConfig(cfg)
2045
2071
  console.log(c.dim(`saved to ${CONFIG_FILE}`))
2046
2072
  }
@@ -2048,7 +2074,7 @@ async function main() {
2048
2074
 
2049
2075
  if (sub === 'settings') {
2050
2076
  const { url, local } = await startSettings({ cfg })
2051
- console.log(`${c.brand('♥')} HeartCode settings: ${url}\n${c.dim(`${overSsh ? 'open it in your browser' : 'opened in your browser'} · from another device on this network, open the link above · Ctrl+C to stop`)}`)
2077
+ console.log(`${c.brand('♥')} HeartCode settings: ${url}\n${c.dim(`${overSsh ? 'open it in a browser' : 'opened in the browser'} · from another device on this network, open the link above · Ctrl+C to stop`)}`)
2052
2078
  openBrowser(local)
2053
2079
  return new Promise(() => {}) // until Ctrl+C
2054
2080
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heartcode",
3
- "version": "0.1.58",
3
+ "version": "0.1.60",
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",