heartcode 0.1.25 → 0.1.30

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
@@ -7,17 +7,19 @@ import { probe, loadProfile, strategy, describe, profilePath, profileFrom } from
7
7
  import { learnFromUsage, LIMIT_MS } from '../src/context.js'
8
8
  import { Session, transcript } from '../src/agent.js'
9
9
  import { treeItems, codePlan, move, leaving, leftText, leftFiles } from '../src/tree.js'
10
- import { UI, c, PERMISSIONS, duration, copyText, rank, setTheme, themeCodes, renderDiff, diffLines, DEFAULT_KEYS, loadKeys } from '../src/ui.js'
10
+ import { UI, c, PERMISSIONS, duration, copyText, rank, setTheme, themeCodes, renderDiff, diffLines, DEFAULT_KEYS, loadKeys, width } from '../src/ui.js'
11
11
  import { listFiles, runCommand, clip } from '../src/tools.js'
12
+ import { notify } from '../src/telegram.js'
12
13
  import { log, LOG_FILE, LOG_DIR, requestLog, useRequestLog, useLogs, pruneLogs, logDays } from '../src/log.js'
13
14
  import { prompt, usePromptsFrom, reloadPrompts } from '../src/prompts.js'
14
15
  import { newChat, saveChat, listChats, loadChat, restoreFiles, ago, forkChat, exportChat } from '../src/sessions.js'
15
16
  import { loadPrices, priceOf, addUsage, money, limitsOf } from '../src/usage.js'
16
- import { Mcp } from '../src/mcp.js'
17
+ import { Mcp, mcpAuth, loadServers } from '../src/mcp.js'
17
18
  import { forget } from '../src/oauth.js'
18
19
  import { loadSkills, fillArgs, extraSkillDirs } from '../src/skills.js'
19
20
  import { HeadlessUI, runHeadless, toolNames, PERMISSION_MODES } from '../src/headless.js'
20
- import { findImports } from '../src/importer.js'
21
+ import { findImports, installSkill } from '../src/importer.js'
22
+ import { capabilities } from '../src/capabilities.js'
21
23
  import { spawnSync } from 'node:child_process'
22
24
  import fs from 'node:fs'
23
25
  import { Memory } from '../src/memory.js'
@@ -119,21 +121,53 @@ const SECTIONS = [
119
121
  ['/test_model', 'test the model for real (otherwise what it can do comes from models.dev, or your settings)'],
120
122
  ['/tidy_memory', 'merge, update and link the memory notes now'],
121
123
  ['/import', 'bring commands, skills, MCP servers and memory from other CLIs'],
124
+ ['/install_skill', 'install a skill from a GitHub repo or a SKILL.md URL (add --project for this folder only)', true],
125
+ ['/doctor', 'check the outside tools HeartCode features need (voice, browser, git) and what to install'],
126
+ ['/mcp', 'your MCP servers and whether each needs signing in'],
122
127
  ['/login_mcp', 'sign in (again) to a remote MCP server', true],
123
128
  ['/compact', 'summarize the conversation to free up context (add what to keep)', true],
124
129
  ['/clear_chat', 'forget the conversation'],
125
130
  ['/reset', "HeartCode's settings (or also providers, or everything) back to the start; asks for a code first"],
126
131
  ['/settings', 'change providers, models, settings, MCP servers, hooks, keys and skills in your browser'],
127
132
  ['/help', 'this list'],
128
- ['/tab', 'a new tab (Ctrl+T): another conversation beside this one · /tab worktree [name]: in its own git worktree · /tab 2: go to tab 2 (Ctrl+N/P) · Ctrl+Q closes one', true],
129
- ['/close_tab', 'close this tab (Ctrl+Q); asks first'],
130
- ['/exit', 'quit HeartCode (Ctrl+Q closes just this tab)'],
133
+ ['/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],
134
+ ['/close_tab', 'close this tab (Alt+W); asks first'],
135
+ ['/exit', 'quit HeartCode (Alt+W closes just this tab)'],
131
136
  ]],
132
137
  ]
133
138
  const COMMANDS = SECTIONS.flatMap(([, list]) => list)
134
139
  const helpText = (sections) => sections.map(([title, list]) => ` ${c.bold(title)}\n` + list.map(([n, d]) => ` ${c.cyan(n.padEnd(18))} ${d}`).join('\n')).join('\n\n')
135
140
  const SLASH = helpText(SECTIONS)
136
141
 
142
+ // The keyboard shortcuts, as [keys, what] rows, read from the effective keybindings (keybindings.json
143
+ // can change any of them) plus the fixed ones (Space, Enter, Esc, Shift+Tab, Ctrl+C).
144
+ function keysHelp(keys = {}) {
145
+ const NAMES = { pageup: 'PgUp', pagedown: 'PgDn', up: '↑', down: '↓', left: '←', right: '→', ctrl: 'Ctrl', alt: 'Alt', shift: 'Shift' }
146
+ const pretty = (k) => k.split('+').map((p) => NAMES[p] ?? (p.length === 1 ? p.toUpperCase() : p[0].toUpperCase() + p.slice(1))).join('+')
147
+ const forAct = (a) => Object.entries(keys).filter(([, v]) => v === a).map(([k]) => pretty(k)).join(' / ')
148
+ const tabs = /(^|,)alt\+[1-9]/.test(Object.keys(keys).join(','))
149
+ const rows = [
150
+ ['Space', 'start voice input (when the input box is empty)'],
151
+ ['Enter', 'send · while it works, queue the message'],
152
+ ['Option/Shift/Ctrl+Enter', 'new line in the box'],
153
+ ['Esc', 'stop the task (press twice to confirm)'],
154
+ ['Esc Esc', 'rewind to an earlier message (at the prompt)'],
155
+ ['Shift+Tab', 'change what runs without asking (permissions)'],
156
+ [forAct('new_tab'), 'new tab'],
157
+ [forAct('close_tab'), 'close this tab'],
158
+ [forAct('next_tab'), 'next tab'],
159
+ [forAct('prev_tab'), 'previous tab'],
160
+ [tabs ? 'Alt+1…9' : '', 'go to tab 1–9'],
161
+ [forAct('send_first'), 'queue: send the first one now'],
162
+ [forAct('send_all'), 'queue: send all now'],
163
+ [forAct('queue_mode'), 'queue: one by one, or all together'],
164
+ [[forAct('scroll_up'), forAct('scroll_down')].filter(Boolean).join(' / '), 'scroll the conversation a page'],
165
+ [[forAct('scroll_line_up'), forAct('scroll_line_down')].filter(Boolean).join(' / '), 'scroll a few lines'],
166
+ ['Ctrl+C', 'stop · twice quits HeartCode'],
167
+ ].filter(([k]) => k)
168
+ return rows
169
+ }
170
+
137
171
  const HOWTO = `${c.yellow('No model set up yet.')} Add a provider and choose its models in your browser:
138
172
 
139
173
  ${c.cyan('/settings')} (or ${c.cyan('heart settings')} in another terminal)
@@ -156,6 +190,14 @@ const kTokens = (n) => (n >= 1e6 ? `${Math.round(n / 1e5) / 10}M` : n >= 1000 ?
156
190
 
157
191
  const mask = (k) => (k ? (k.length > 12 ? `${k.slice(0, 4)}…${k.slice(-4)}` : '…') : c.dim('no key'))
158
192
 
193
+ // The status bar's default layout (two lines): the model and what it can do, then the run's stats and
194
+ // controls — model and context on the left, abilities and controls pushed to the right. cfg.statusBar
195
+ // overrides it — see App.status for the item names and format.
196
+ const DEFAULT_STATUS = [
197
+ { left: ['provider', 'model'], right: ['mode', 'thinking', 'images'] },
198
+ { left: ['ctx', 'tps', 'autocompact'], right: ['permissions', 'worktree', 'cost'] },
199
+ ]
200
+
159
201
  class App {
160
202
  constructor(cfg, ui, root) {
161
203
  Object.assign(this, { cfg, ui, root })
@@ -528,31 +570,37 @@ class App {
528
570
  this.save()
529
571
  }
530
572
 
531
- // Built-in commands, then the skills you can type (a built-in wins on the same name).
573
+ // Built-in commands (/name), then the skills you can type, namespaced as /skill:name so they're
574
+ // easy to tell apart from HeartCode's own commands (and can't clash with them).
532
575
  commands() {
533
- const builtIn = new Set(COMMANDS.map(([n]) => n))
534
- const mine = [...this.skills.values()].filter((k) => k.use !== 'model' && !builtIn.has(`/${k.name}`)).map((k) => [`/${k.name}`, k.description, true])
576
+ const mine = [...this.skills.values()].filter((k) => k.use !== 'model').map((k) => [`/skill:${k.name}`, k.description, true])
535
577
  return [...COMMANDS, ...mine]
536
578
  }
537
579
 
538
- // A command: "/name …" with the name of a built-in command or a skill you can type. Anything else
539
- // starting with "/" (a path like /Users/me/shot.png) is a message for the model.
580
+ // A command: a built-in "/name", or a skill "/skill:name". A bare "/name" that matches a skill is
581
+ // still caught (slash points it to /skill:name). Anything else starting with "/" (a path like
582
+ // /Users/me/shot.png) is a message for the model.
540
583
  isCommand(line) {
584
+ if (/^\s*\/skill:\S/.test(line)) return true // any /skill:x is a command attempt; slash() says if the skill is unknown
541
585
  const name = /^\/([\w-]+)(?=\s|$)/.exec(line)?.[1]
542
- return Boolean(name) && (name === 'quit' || this.commands().some(([n]) => n === `/${name}`))
586
+ if (!name) return false
587
+ return name === 'quit' || COMMANDS.some(([n]) => n === `/${name}`) || this.skills.has(name)
543
588
  }
544
589
 
545
590
  help() {
546
591
  const mine = this.commands().slice(COMMANDS.length)
547
- return helpText(mine.length ? [...SECTIONS, ['your skills', mine]] : SECTIONS)
592
+ const sections = [...SECTIONS]
593
+ if (mine.length) sections.push(['your skills (type /skill:name)', mine])
594
+ sections.push(['keyboard', keysHelp(this.ui.keys)])
595
+ return helpText(sections)
548
596
  }
549
597
 
550
- // "/review focus on tests": the skill's text, arguments filled in, `!command` output added.
598
+ // "/skill:review focus on tests": the skill's text, arguments filled in, `!command` output added.
551
599
  async expandSkill(k, args) {
552
600
  let text = fillArgs(k.body, args).replace(/(^|\s)@([\w./-]+)/g, '$1$2') // @file: HeartCode attaches files a message names
553
601
  for (const m of [...text.matchAll(/!`([^`]+)`|```!\n([\s\S]*?)```/g)]) {
554
602
  const cmd = (m[1] ?? m[2]).trim()
555
- const ok = await this.ui.confirm(`Run ${c.bold(cmd)} (from /${k.name})?`, 'command')
603
+ const ok = await this.ui.confirm(`Run ${c.bold(cmd)} (from /skill:${k.name})?`, 'command')
556
604
  const out = ok === true ? (await runCommand(this.root, cmd, { signal: this.signal })).output.trim() : '(not run)'
557
605
  log('skill', `/${k.name} ran ${cmd}`)
558
606
  text = text.replace(m[0], () => `\n\`\`\`\n$ ${cmd}\n${clip(out, 8000)}\n\`\`\`\n`)
@@ -596,56 +644,66 @@ class App {
596
644
  return rank(items, typed).slice(0, 200)
597
645
  }
598
646
 
599
- // The status bar: what's in use, its abilities, and how full the context is.
600
- status() {
647
+ // The status bar. The layout is config-driven (cfg.statusBar): a list of lines, each either a list
648
+ // of item names (all left-aligned) or { left: [...], right: [...] } to push some to the right edge.
649
+ // Item names: provider, model, mode, thinking, images, ctx, tps, cost, autocompact, worktree,
650
+ // permissions. cfg.statusBar === false hides the whole bar. Unknown names and items that don't
651
+ // apply right now are skipped. `cols` (from the renderer) is used to right-align.
652
+ status(cols = 100) {
601
653
  const { cfg, ui } = this
602
- const sep = c.ghost(' │ ')
654
+ if (cfg.statusBar === false) return '' // turned off: no status bar at all
603
655
  if (!cfg.providers[cfg.provider] || !cfg.model) return c.dim('no model · /settings to choose one')
604
656
  const rot = this.s?.client.rotation
605
657
  const now = this.inUse() // the model list's one in use; never one of a provider that's off
606
658
  if (!now) return c.dim('the providers of all your models are off · /settings to switch one on')
607
- // provider (providers on) · the model. Auto (rotating your list): "auto (current model) (list
608
- // size)". A model you picked (pinned, no rotation): just its name.
609
659
  const on = Object.values(cfg.providers).filter((p) => !p.off).length
610
- // one model (pinned): just its name. Several chosen for this session: the one in use + "N chosen".
611
- // Your whole list (auto): "auto (in use) (N)". ↻ shows the rotation position while rotating.
612
660
  const count = this.sessionModels().length
613
- // the model answering now; a "↻" before it, in yellow, when it's a fallback (rotated to after one
614
- // failed) — so you can see at a glance it isn't the first/preferred one
661
+ // the model answering now; a yellow "↻" before it when it's a fallback (rotated to after one failed)
615
662
  const rotated = rot && rot.at > 0
616
- const name = rotated ? `${c.yellow('↻ ' + now.model)}` : c.info(now.model)
663
+ const name = rotated ? c.yellow('↻ ' + now.model) : c.info(now.model)
617
664
  const model =
618
- count === 1
619
- ? name
620
- : cfg.session
621
- ? `${name} ${c.faint(`(${count} chosen)`)}`
622
- : `${c.muted('auto')} ${c.faint('(')}${name}${c.faint(')')} ${c.faint(`(${count})`)}`
623
- // two lines so nothing is crammed: the model and what it can do, then the run's stats and controls
624
- const first = [`${c.brand('●')} ${c.muted(now.provider)} ${c.faint(`(${on})`)} ${c.ghost('·')} ${model}`]
625
- const second = []
665
+ count === 1 ? name : cfg.session ? `${name} ${c.faint(`(${count} chosen)`)}` : `${c.muted('auto')} ${c.faint('(')}${name}${c.faint(')')} ${c.faint(`(${count})`)}`
626
666
  const key = `${now.provider}/${now.model}`
627
667
  if (this.profileKey !== key) [this.profileKey, this.profile] = [key, this.s?.profile ?? loadProfile(this.client(now.provider, now.model))]
628
668
  const profile = this.s?.profile ?? this.profile
629
- if (profile) {
630
- const strat = this.s?.strat ?? strategy(profile, cfg)
631
- first.push(c.muted(strat.actions === 'tools' ? 'tools' : 'guided'))
632
- if (strat.thinking) first.push(c.think(`thinking${cfg.effort ? ` · ${cfg.effort}` : ''}`) + (ui.showThinking ? '' : c.faint(' (collapsed)')))
633
- if (strat.vision) first.push(c.muted('images'))
669
+ const strat = profile && (this.s?.strat ?? strategy(profile, cfg))
670
+ // each item, rendered (or null when it doesn't apply)
671
+ const parts = {
672
+ provider: `${c.brand('●')} ${c.muted(now.provider)} ${c.faint(`(${on})`)}`,
673
+ model,
674
+ mode: strat ? c.muted(strat.actions === 'tools' ? 'tools' : 'guided') : c.dim('not probed yet'),
675
+ thinking: strat?.thinking ? c.think(`thinking${cfg.effort ? ` · ${cfg.effort}` : ''}`) + (ui.showThinking ? '' : c.faint(' (collapsed)')) : null,
676
+ images: strat?.vision ? c.muted('images') : null,
677
+ ctx: null,
678
+ tps: null,
679
+ cost: null,
680
+ autocompact: cfg.autoCompact === false ? c.faint('auto-compact off') : null,
681
+ worktree: this.worktree ? c.info(`⎇ ${this.worktree.branch}`) : null,
682
+ permissions: { all: c.green('⏵⏵ all allowed'), commands: c.yellow('ask before commands'), ask: c.yellow('ask before changes'), plan: c.info('⏸ plan mode') }[ui.permission],
683
+ }
684
+ if (strat) {
634
685
  const used = this.s?.client.lastTokens ?? 0
635
686
  const pct = Math.round((used / strat.context) * 100)
636
687
  const paint = pct >= 80 ? c.red : pct >= 50 ? c.yellow : c.green
637
688
  const guess = strat.contextSure ? '' : '~' // not said by the server: assumed, and growing as bigger requests work
638
- second.push(`${c.faint('ctx')} ${paint(`${kTokens(used)}/${guess}${kTokens(strat.context)}`)} ${c.faint(`${pct}%`)}`)
689
+ parts.ctx = `${c.faint('ctx')} ${paint(`${kTokens(used)}/${guess}${kTokens(strat.context)}`)} ${c.faint(`${pct}%`)}`
639
690
  const tps = this.s?.client.tps
640
- if (tps) second.push(`${c.muted(String(tps))} ${c.faint('tok/s')}`)
641
- if (this.chat.usage?.priced) second.push(c.muted(money(this.chat.usage.cost)))
642
- } else {
643
- first.push(c.dim('not probed yet'))
691
+ if (tps) parts.tps = `${c.muted(String(tps))} ${c.faint('tok/s')}`
692
+ if (this.chat.usage?.priced) parts.cost = c.muted(money(this.chat.usage.cost))
644
693
  }
645
- if (cfg.autoCompact === false) second.push(c.faint('auto-compact off'))
646
- if (this.worktree) second.push(c.info(`⎇ ${this.worktree.branch}`))
647
- second.push({ all: c.green('⏵⏵ all allowed'), commands: c.yellow('ask before commands'), ask: c.yellow('ask before changes'), plan: c.info('⏸ plan mode') }[ui.permission]) // Shift+Tab changes it
648
- return [first.join(sep), second.join(sep)].filter((l) => l.replace(/\x1b\[[0-9;]*m/g, '').trim()).join('\n')
694
+ const sep = c.ghost(' │ ')
695
+ const vis = (str) => width(str.replace(/\x1b\[[0-9;]*m/g, ''))
696
+ const layout = Array.isArray(cfg.statusBar) && cfg.statusBar.length ? cfg.statusBar : DEFAULT_STATUS
697
+ const line = (row) => {
698
+ const names = (g) => (g ?? []).map((t) => parts[t]).filter(Boolean).join(sep)
699
+ const left = names(Array.isArray(row) ? row : row?.left)
700
+ const right = names(Array.isArray(row) ? null : row?.right)
701
+ if (!right) return left
702
+ if (!left) return right
703
+ const pad = cols - 1 - vis(left) - vis(right) - 1 // the renderer adds a leading space; keep 1 to spare on the right
704
+ return pad > 0 ? left + ' '.repeat(pad) + right : `${left}${sep}${right}` // too narrow to split: just join
705
+ }
706
+ return layout.map(line).filter((l) => l.replace(/\x1b\[[0-9;]*m/g, '').trim()).join('\n')
649
707
  }
650
708
 
651
709
  client(name, model) {
@@ -700,6 +758,17 @@ class App {
700
758
  Object.assign(this.s, { mcp: this.mcp, memory: this.memory, skills: this.skills, director: this.director })
701
759
  this.s.team = () => this.team() // your other models: a job this one can't do goes to one of them
702
760
  this.s.engineFor = (t) => this.engine(t.provider, t.model, ui, undefined, { quiet: true })
761
+ // A model's context window, read from its saved profile (no probe, no network): so the agent can
762
+ // see, before compacting, whether another model in the list has room for the whole conversation.
763
+ this.s.windowOf = (t) => {
764
+ try {
765
+ const cl = this.client(t.provider, t.model)
766
+ const profile = loadProfile(cl) || profileFrom(cl, limitsOf(t.provider, cl.baseUrl, t.model))
767
+ return strategy(profile, cfg).context || 0
768
+ } catch {
769
+ return 0
770
+ }
771
+ }
703
772
  this.s.failures = this.failures
704
773
  if (this.allowTools?.length) this.s.allowTools = toolNames(this.allowTools) // headless --allowedTools
705
774
  if (this.denyTools?.length) this.s.denyTools = toolNames(this.denyTools)
@@ -998,7 +1067,7 @@ function applySettings(apps, cfg, what) {
998
1067
  const { ui } = app
999
1068
  const busy = Boolean(ui.busySince || app.working)
1000
1069
  const now = (fn) => (busy ? app.later.push(fn) : fn())
1001
- if (app.cfg !== cfg) for (const k of ['providers', 'provider', 'model', 'effort', 'theme', 'context', 'autoCompact', 'director', 'format', 'lsp', 'voice', 'rotation']) app.cfg[k] = cfg[k]
1070
+ 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]
1002
1071
  // a model pinned in this CLI (/select_model) is a session choice: a model/order change on the
1003
1072
  // settings page leaves it alone (only /select_model auto here returns it to the list)
1004
1073
  if (what === 'model' && !app.cfg.session) {
@@ -1015,6 +1084,7 @@ function applySettings(apps, cfg, what) {
1015
1084
  }
1016
1085
  if (what === 'provider') app.lists = {} // its list switched on or off, a model added by name
1017
1086
  if (what === 'setting:permissions') ui.setPermission(cfg.permissions)
1087
+ if (what === 'setting:statusBar') ui.render?.() // the status bar's layout changed: redraw it now
1018
1088
  if (what === 'setting:effort' && app.s?.strat.thinking) app.s.client.effort = cfg.effort
1019
1089
  if (what === 'setting:autoCompact' && app.s) app.s.autoCompact = cfg.autoCompact !== false
1020
1090
  if (what === 'setting:format' && app.s) app.s.noFormat = cfg.format === false
@@ -1163,6 +1233,18 @@ async function choose(ui, cmd, arg, title, current) {
1163
1233
  return (await ui.pick(title, ARGS[cmd].map(([label, desc]) => ({ label, desc, current: label === current }))))?.label ?? null
1164
1234
  }
1165
1235
 
1236
+ // Fresh sign-in to a remote MCP server: forget the old token, reconnect (opens the browser via
1237
+ // app.mcp.onSignIn), list its tools. Used by /login_mcp and the settings page's Sign in button.
1238
+ async function signInMcp(app, name, signal) {
1239
+ const sv = app.mcp.get(name)
1240
+ if (!sv?.url) throw new Error(`no remote MCP server "${name}"`)
1241
+ forget(sv.url)
1242
+ sv.stop()
1243
+ Object.assign(sv, { token: null, tools: null })
1244
+ const tools = await sv.listTools(signal)
1245
+ return `signed in to ${name} · ${tools.length} tools`
1246
+ }
1247
+
1166
1248
  async function slash(app, line) {
1167
1249
  const [cmd, ...args] = line.slice(1).trim().split(/\s+/)
1168
1250
  const { ui, cfg } = app
@@ -1175,7 +1257,7 @@ async function slash(app, line) {
1175
1257
  if (n > 1) {
1176
1258
  const go = await ui.pick(`Quit HeartCode? ${n} tabs are open`, [
1177
1259
  { label: 'Yes, quit', desc: 'they come back next time you start HeartCode here', yes: true },
1178
- { label: 'No', desc: 'Ctrl+Q closes just this tab' },
1260
+ { label: 'No', desc: 'Alt+W closes just this tab' },
1179
1261
  ])
1180
1262
  if (!go?.yes) return
1181
1263
  }
@@ -1198,7 +1280,7 @@ async function slash(app, line) {
1198
1280
  return ui.print(`${c.ok('✓')} ${c.muted(`reset: ${it.label.toLowerCase()}`)}${it.level === 'settings' ? '' : c.dim(' · add a provider on /settings')}`)
1199
1281
  }
1200
1282
  case 'settings': {
1201
- settingsPage ??= startSettings({ cfg, apply: (what) => applySettings(app.tabs ? app.tabs.list.map((t) => t.app) : [app], cfg, what) })
1283
+ 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) })
1202
1284
  const { url, close } = await settingsPage
1203
1285
  openBrowser(url)
1204
1286
  ui.print(`${c.info('↗')} ${c.bold('settings')} ${c.muted('opened in your browser:')}\n ${c.faint(url)}`)
@@ -1315,19 +1397,45 @@ async function slash(app, line) {
1315
1397
  if (!s) return
1316
1398
  return s.tidyMemory(app.signal)
1317
1399
  }
1400
+ case 'doctor': {
1401
+ const caps = capabilities(cfg)
1402
+ const rows = caps.map((cp) => {
1403
+ const head = ` ${cp.ok ? c.green('✓') : c.red('✗')} ${c.bold(cp.name)}${cp.ok ? c.dim(' · ready') : c.yellow(' · needs setup')}`
1404
+ return cp.ok ? head : `${head}\n ${c.faint(`install ${cp.need}`)}`
1405
+ })
1406
+ return ui.print(`${c.bold('External tools HeartCode features use')}\n${rows.join('\n')}`)
1407
+ }
1408
+ case 'mcp': {
1409
+ const all = loadServers(app.root, { includeDisabled: true }) // enabled and off, so off ones are visible
1410
+ const names = Object.keys(all)
1411
+ if (!names.length) return ui.print('No MCP servers. Add one in /settings → MCP servers, or /import from another CLI.')
1412
+ const running = new Set(app.mcp.names)
1413
+ const label = { local: c.dim('local · no sign-in'), in: c.green('signed in'), out: c.yellow('sign-in needed') }
1414
+ const rows = names.map((n) => {
1415
+ const cfg = all[n]
1416
+ const on = running.has(n)
1417
+ const where = cfg.url ?? [cfg.command, ...(cfg.args ?? [])].filter(Boolean).join(' ')
1418
+ const head = on ? `${c.brand('●')} ${c.bold(n.padEnd(16))} ${label[mcpAuth(cfg)]}` : `${c.dim('○')} ${c.dim(n.padEnd(16))} ${c.dim('off')}`
1419
+ return ` ${head}\n ${c.faint(clip(where, 90))}`
1420
+ })
1421
+ const needs = names.some((n) => running.has(n) && mcpAuth(all[n]) === 'out')
1422
+ const off = names.some((n) => !running.has(n))
1423
+ return ui.print(`${c.bold('MCP servers')}\n${rows.join('\n')}${needs ? `\n ${c.dim('sign in to a remote one with /login_mcp <name>')}` : ''}${off ? `\n ${c.dim('turn one on in /settings → MCP servers')}` : ''}`)
1424
+ }
1318
1425
  case 'login_mcp': {
1319
1426
  const remote = app.mcp.names.filter((n) => app.mcp.get(n).url)
1320
- const name = args[0] ?? (await ui.pick('Sign in to which server?', remote.map((n) => ({ label: n, desc: app.mcp.get(n).url }))))?.label
1427
+ const name = args[0] ?? (await ui.pick('Sign in to which server?', remote.map((n) => ({ label: n, desc: app.mcp.get(n).url, hint: mcpAuth(app.mcp.get(n).cfg) === 'in' ? 'signed in' : 'not signed in' }))))?.label
1321
1428
  if (!name) return remote.length ? undefined : ui.print('No remote MCP servers (ones with a "url") to sign in to.')
1322
- const sv = app.mcp.get(name)
1323
- if (!sv?.url) return ui.print(`No remote MCP server "${name}".`)
1324
- forget(sv.url) // a fresh sign-in
1325
- sv.stop()
1326
- Object.assign(sv, { token: null, tools: null })
1429
+ if (!app.mcp.get(name)?.url) return ui.print(`No remote MCP server "${name}".`)
1327
1430
  ui.spinner(`connecting to ${name}`)
1328
- const tools = await sv.listTools(app.signal)
1329
- ui.stopSpin()
1330
- return ui.print(`${c.green('connected')} ${c.bold(name)} · ${tools.length} tools`)
1431
+ try {
1432
+ const msg = await signInMcp(app, name, app.signal)
1433
+ ui.stopSpin()
1434
+ return ui.print(`${c.green('✓')} ${msg}`)
1435
+ } catch (e) {
1436
+ ui.stopSpin()
1437
+ return ui.print(`${c.red('✗')} ${e.message}`)
1438
+ }
1331
1439
  }
1332
1440
  case 'import': {
1333
1441
  const items = findImports(app.root)
@@ -1346,6 +1454,21 @@ async function slash(app, line) {
1346
1454
  log('import', chosen.map((it) => `${it.group}: ${it.label}`))
1347
1455
  return
1348
1456
  }
1457
+ case 'install_skill': {
1458
+ const url = args.find((a) => !a.startsWith('--'))
1459
+ if (!url) return ui.print('Usage: /install_skill <github repo or a SKILL.md url> [--project]')
1460
+ const scope = args.includes('--project') ? 'project' : 'global'
1461
+ ui.spinner(`installing from ${url}`)
1462
+ try {
1463
+ const msg = await installSkill(app.root, url, scope, { signal: app.signal })
1464
+ ui.stopSpin()
1465
+ app.reload('skill')
1466
+ return ui.print(`${c.green('✓')} ${msg}${scope === 'project' ? ' (this folder)' : ''} ${c.dim('· run with /skill:<name>, /help lists them')}`)
1467
+ } catch (e) {
1468
+ ui.stopSpin()
1469
+ return ui.print(`${c.red('✗')} could not install: ${e.message}`)
1470
+ }
1471
+ }
1349
1472
  case 'btw':
1350
1473
  return app.btw(line.trim().replace(/^\/btw\b/, '').trim())
1351
1474
  case 'voice': {
@@ -1360,8 +1483,13 @@ async function slash(app, line) {
1360
1483
  if (!['model_info', 'test_model', 'compact'].includes(cmd)) {
1361
1484
  app.skills = loadSkills(app.root) // edits to skill files apply right away
1362
1485
  if (app.s) app.s.skills = app.skills
1363
- const k = app.skills.get(cmd)
1364
- if (k && k.use !== 'model') return runTask(app, await app.expandSkill(k, args.join(' ')), { signal: app.signal })
1486
+ if (cmd.startsWith('skill:')) {
1487
+ const name = cmd.slice(6)
1488
+ const k = app.skills.get(name)
1489
+ if (k && k.use !== 'model') return runTask(app, await app.expandSkill(k, args.join(' ')), { signal: app.signal })
1490
+ return ui.print(`unknown skill /skill:${name} ${c.dim('· /help lists your skills')}`)
1491
+ }
1492
+ 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
1365
1493
  return ui.print(`unknown command /${cmd} ${c.dim('· /help lists them')}`)
1366
1494
  }
1367
1495
  const s = await app.session()
@@ -1390,16 +1518,21 @@ async function runTask(app, task, ctl) {
1390
1518
  try {
1391
1519
  const s = await app.session()
1392
1520
  if (!s) return false
1521
+ let answer
1393
1522
  try {
1394
- await s.run(task, ctl?.signal)
1523
+ answer = await s.run(task, ctl?.signal)
1395
1524
  } finally {
1396
1525
  app.save()
1397
1526
  }
1527
+ notify(app.cfg, 'done', `✅ Done · ${path.basename(app.root)} · ${duration(ui.worked())}\n${clip(task.split('\n')[0], 200)}\n\n${clip(String(answer ?? '').trim(), 3500)}`)
1398
1528
  } catch (e) {
1399
1529
  ui.stopSpin()
1400
1530
  log('error', e.name === 'AbortError' || ctl?.signal.aborted ? 'task interrupted by the user' : e.stack)
1401
1531
  if (e.name === 'AbortError' || ctl?.signal.aborted) ui.print(c.yellow('\ninterrupted'))
1402
- else ui.print(c.red(`\nerror: ${e.message}`))
1532
+ else {
1533
+ ui.print(c.red(`\nerror: ${e.message}`))
1534
+ notify(app.cfg, 'failed', `❌ Failed · ${path.basename(app.root)}\n${clip(task.split('\n')[0], 200)}\n\n${clip(e.message, 1500)}`)
1535
+ }
1403
1536
  return false
1404
1537
  }
1405
1538
  return true
@@ -1412,6 +1545,7 @@ async function repl(app, f = {}) {
1412
1545
  let ctl = null
1413
1546
  ui.onEscape = () => ctl?.abort()
1414
1547
  ui.onBtw = (q) => app.btw(q, true) // /btw typed while it works
1548
+ 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)
1415
1549
  ui.isCommand = (l) => app.isCommand(l)
1416
1550
  loadPrices().then(() => ui.render?.()) // models.dev: what each model can do, for the model lists
1417
1551
  ui.voiceConfig = () => ({ voice: cfg.voice, providers: cfg.providers })
@@ -1425,7 +1559,7 @@ async function repl(app, f = {}) {
1425
1559
  ui.close()
1426
1560
  process.exit(0)
1427
1561
  }
1428
- // Ctrl+Q, /close_tab: this tab, after asking (working: that stops too); the last one quits
1562
+ // Alt+W, /close_tab: this tab, after asking (working: that stops too); the last one quits
1429
1563
  let closing = false
1430
1564
  app.closeTab = async (working = false) => {
1431
1565
  if (closing) return
@@ -1448,7 +1582,7 @@ async function repl(app, f = {}) {
1448
1582
  ui.onCloseTab = () => {
1449
1583
  if (closing) return
1450
1584
  if (!ui.asking) return app.closeTab(true) // working: asked over the work
1451
- if (!ui.histOn || ui.menu.pick) return ui.notice('Answer this first, then Ctrl+Q', 2000)
1585
+ if (!ui.histOn || ui.menu.pick) return ui.notice('Answer this first, then Alt+W', 2000)
1452
1586
  ui.submit('/close_tab') // at the prompt: asked in its turn, like a typed /close_tab
1453
1587
  }
1454
1588
  const others = () => (app.tabs?.list.length ?? 1) - 1
@@ -1473,7 +1607,7 @@ async function repl(app, f = {}) {
1473
1607
  const where = home && app.root.startsWith(home) ? '~' + app.root.slice(home.length) : app.root
1474
1608
  ui.header = (cols = 100) => [
1475
1609
  `${c.brand('♥')} ${c.bright(c.bold('HeartCode'))} ${c.faint(VERSION)} ${c.muted(where.length > cols - 16 ? '…' + where.slice(-(cols - 17)) : where)}`,
1476
- [['/', 'run a command'], ['@', 'attach a file'], [NEWLINE_KEY, 'add a new line'], ['Esc', 'stop'], ['Shift+Tab', 'change permissions']].map(([k, d]) => `${c.muted(k)} ${c.faint(d)}`).join(c.ghost(' · ')),
1610
+ [['/', 'run a command'], ['@', 'attach a file'], ...(ui.voiceReady?.() ? [['Space', 'talk (voice)']] : []), [NEWLINE_KEY, 'add a new line'], ['Esc', 'stop'], ['Shift+Tab', 'change permissions']].map(([k, d]) => `${c.muted(k)} ${c.faint(d)}`).join(c.ghost(' · ')),
1477
1611
  '',
1478
1612
  ]
1479
1613
  if (!ui.full) ui.print(ui.header().join('\n'))
@@ -1495,6 +1629,7 @@ async function repl(app, f = {}) {
1495
1629
  if (!t) continue
1496
1630
  ctl = new AbortController()
1497
1631
  app.signal = ctl.signal // Esc stops whatever this line started (a task, a probe, …)
1632
+ ui.escArm = 0 // a fresh task: a first Esc from before doesn't count toward stopping this one
1498
1633
  ui.busy() // the spinner stays until this line's work is done
1499
1634
  if (app.isCommand(t)) {
1500
1635
  try {
@@ -1668,7 +1803,7 @@ async function main() {
1668
1803
  const app = new App(cfg, ui, root)
1669
1804
  usePromptsFrom(app.root) // its .heartcode/prompts override the built-in sections
1670
1805
  ui.suggest = (line, cursor) => app.suggest(line, cursor)
1671
- ui.status = () => app.status()
1806
+ ui.status = (cols) => app.status(cols)
1672
1807
  ui.requestSince = () => app.s?.client.inFlight // the spinner shows how long the model has been answering
1673
1808
  return app
1674
1809
  }
@@ -1679,7 +1814,7 @@ async function main() {
1679
1814
  log('worktree', `working in ${wt.dir} on ${wt.branch}`)
1680
1815
  process.on('exit', () => wt.done || activeUI?.noUser || console.error(c.dim(`worktree kept: ${wt.dir} (branch ${wt.branch})`)))
1681
1816
  }
1682
- // The full screen: in tabs (the first one is this folder; /tab and Ctrl+T open more).
1817
+ // The full screen: in tabs (the first one is this folder; /tab and Alt+T open more).
1683
1818
  if (!headless && !sub && !positionals.length && process.stdin.isTTY && process.stdout.isTTY) {
1684
1819
  if (f['resume-id'] && !loadChat(f['resume-id'])) throw new Error(`no session ${f['resume-id']}`)
1685
1820
  const saved = readJson(TABS_FILE, {})[root] // before this run's first tab replaces it
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heartcode",
3
- "version": "0.1.25",
3
+ "version": "0.1.30",
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",