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/src/settings.js CHANGED
@@ -9,7 +9,7 @@ import path from 'node:path'
9
9
  import crypto from 'node:crypto'
10
10
  import os from 'node:os'
11
11
  import { HOME, saveConfig, readJson, writeJson, byName, takeIn, whatOf } from './config.js'
12
- import { DEFAULT_SERVERS } from './mcp.js'
12
+ import { DEFAULT_SERVERS, mcpAuth } from './mcp.js'
13
13
  import { sections, BUILTIN_PROMPTS } from './prompts.js'
14
14
  import { Client } from './client.js'
15
15
  import { clip } from './tools.js'
@@ -17,6 +17,9 @@ import { loadProfile, strategy, profilePath, profileFrom } from './probe.js'
17
17
  import { loadPrices, priceOf, limitsOf } from './usage.js'
18
18
  import { THEMES, PERMISSIONS } from './ui.js'
19
19
  import { loadSkills, frontMatter } from './skills.js'
20
+ import { installSkill, findImports } from './importer.js'
21
+ import { capabilities } from './capabilities.js'
22
+ import { connect, sendTelegram, tokenHint, tgReady, EVENTS } from './telegram.js'
20
23
  import { log, LOGS, REQUESTS, useRequestLog, listRequests, readRequest, pruneLogs, logDays, logSize, clearLogs } from './log.js'
21
24
 
22
25
  const PAGE = new URL('./settings.html', import.meta.url)
@@ -24,6 +27,22 @@ const EFFORTS = ['default', 'low', 'medium', 'high']
24
27
  const TOGGLES = { autoCompact: 'compact the conversation when it fills 85% of the model\'s context window', director: 'let the model add skills, MCP servers and change settings when asked', format: "run the project's formatter on every file HeartCode writes", lsp: "show the model a language server's errors after each edit" }
25
28
  // The Logging page's: both off unless switched on; how much of each request ("full" or "summary")
26
29
  const LOG_SWITCHES = ['log', 'logRequests']
30
+ // The status-bar items the visual editor offers (id must match App.status in bin/heartcode.js).
31
+ // `sample` is shown in the page's live preview.
32
+ const STATUS_ITEMS = [
33
+ { id: 'provider', label: 'Provider', sample: '● openai (2)' },
34
+ { id: 'model', label: 'Model', sample: 'gpt-5' },
35
+ { id: 'mode', label: 'Mode', sample: 'tools' },
36
+ { id: 'thinking', label: 'Thinking', sample: 'thinking' },
37
+ { id: 'images', label: 'Images', sample: 'images' },
38
+ { id: 'ctx', label: 'Context used', sample: 'ctx 12k/128k 9%' },
39
+ { id: 'tps', label: 'Tokens / sec', sample: '48 tok/s' },
40
+ { id: 'cost', label: 'Cost', sample: '$0.14' },
41
+ { id: 'autocompact', label: 'Auto-compact off', sample: 'auto-compact off' },
42
+ { id: 'worktree', label: 'Git worktree', sample: '⎇ feature' },
43
+ { id: 'permissions', label: 'Permissions', sample: '⏵⏵ all allowed' },
44
+ ]
45
+ const STATUS_IDS = new Set(STATUS_ITEMS.map((i) => i.id))
27
46
  const DETAILS = ['full', 'summary']
28
47
  // Files in ~/.heart the page edits as text: [name, what it is, JSON?]
29
48
  const FILES = [
@@ -70,7 +89,7 @@ function mcpServers() {
70
89
  const from = Object.fromEntries(Object.keys(DEFAULT_SERVERS).map((n) => [n, 'built in']))
71
90
  const all = structuredClone(DEFAULT_SERVERS)
72
91
  for (const [n, c] of Object.entries(own)) all[n] = { ...all[n], ...c }
73
- return Object.entries(all).map(([name, c]) => ({ name, from: from[name] ?? 'yours', on: !c.disabled, what: c.url ?? [c.command, ...(c.args ?? [])].filter(Boolean).join(' '), description: c.description ?? '' }))
92
+ return Object.entries(all).map(([name, c]) => ({ name, from: from[name] ?? 'yours', on: !c.disabled, remote: Boolean(c.url), auth: mcpAuth(c), what: c.url ?? [c.command, ...(c.args ?? [])].filter(Boolean).join(' '), description: c.description ?? '' }))
74
93
  }
75
94
 
76
95
  // The model list: #1 is the model (cfg.provider/model), the rest cfg.rotation.then, in order.
@@ -114,7 +133,8 @@ function forgetList(...names) {
114
133
  writeJson(LISTS, all)
115
134
  }
116
135
 
117
- export function startSettings({ cfg, apply = () => {}, port = 0 } = {}) {
136
+ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.cwd(), onLoginMcp = null } = {}) {
137
+ let importCache = [] // the last /api/imports listing, so /api/imports/run can execute by id
118
138
  const token = crypto.randomBytes(24).toString('hex')
119
139
  const changed = (what) => {
120
140
  try {
@@ -341,7 +361,11 @@ export function startSettings({ cfg, apply = () => {}, port = 0 } = {}) {
341
361
  settings: { permissions: cfg.permissions ?? 'all', effort: cfg.effort ?? 'default', theme: cfg.theme ?? 'dark', context: cfg.context ?? null, ...Object.fromEntries(Object.keys(TOGGLES).map((k) => [k, cfg[k] !== false])), ...Object.fromEntries(LOG_SWITCHES.map((k) => [k, cfg[k] === true])), logDetail: cfg.logDetail === 'summary' ? 'summary' : 'full', logDays: logDays(cfg) },
342
362
  logs: { runs: tilde(path.join(LOGS, 'runs')), requests: tilde(REQUESTS) },
343
363
  voice: cfg.voice ? JSON.stringify(cfg.voice, null, 2) : '',
344
- choices: { permissions: PERMISSIONS, effort: EFFORTS, theme: Object.keys(THEMES), toggles: TOGGLES },
364
+ statusBar: cfg.statusBar === undefined ? null : cfg.statusBar, // false (off), a list of lines, or null (default)
365
+ // Telegram notifications: never the token itself, only a hint of it
366
+ telegram: (({ token, bot, chatName, chatId, on, events } = {}) => ({ hint: tokenHint(token), bot: bot ?? null, chatName: chatName ?? null, connected: Boolean(token && chatId), on: on !== false, events: Object.fromEntries(Object.keys(EVENTS).map((k) => [k, events?.[k] !== false])), names: EVENTS }))(cfg.telegram),
367
+ capabilities: capabilities(cfg), // features that need outside tools, and whether they're here
368
+ choices: { permissions: PERMISSIONS, effort: EFFORTS, theme: Object.keys(THEMES), toggles: TOGGLES, statusItems: STATUS_ITEMS },
345
369
  files: FILES.map(([name, about, json, example]) => ({ name, about, json, example, text: fs.existsSync(path.join(HOME, name)) ? fs.readFileSync(path.join(HOME, name), 'utf8') : '' })),
346
370
  skills: [...loadSkills(null).values()].map((s) => ({ name: s.name, description: s.description, use: s.use, mine: s.file.startsWith(skillsDir() + path.sep), text: fs.readFileSync(s.file, 'utf8') })),
347
371
  mcp: mcpServers(),
@@ -628,6 +652,55 @@ export function startSettings({ cfg, apply = () => {}, port = 0 } = {}) {
628
652
  save('setting:voice')
629
653
  return state()
630
654
  },
655
+ // The status bar's layout from the visual editor: false (off), null (back to default), or a list
656
+ // of lines ({ left:[item ids], right:[item ids] }). Unknown item ids are dropped; empty = off.
657
+ // Telegram: a bot token checked (or the saved one, to look again for the chat once you pressed
658
+ // Start in the bot); the newest chat that wrote to the bot is the one notifications go to, and
659
+ // it gets a first message saying so.
660
+ 'POST /api/telegram/connect': async ({ token }) => {
661
+ const tk = String(token ?? '').trim() || cfg.telegram?.token
662
+ if (!tk) throw new Error('paste the token @BotFather gave you')
663
+ if (!/^\d+:[\w-]{20,}$/.test(tk)) throw new Error("that doesn't look like a bot token (it's like 123456789:AAH…, from @BotFather)")
664
+ const r = await connect(tk)
665
+ const chat = r.chats[0]
666
+ const was = cfg.telegram?.token === tk ? cfg.telegram : {}
667
+ cfg.telegram = { ...was, token: tk, bot: r.bot, ...(chat ? { chatId: chat.id, chatName: chat.name } : { chatId: undefined, chatName: undefined }), on: was.on ?? true }
668
+ save('setting:telegram')
669
+ if (chat) await sendTelegram(cfg.telegram, "✅ HeartCode is connected. You'll get a message here when a task finishes, fails, or waits for you.")
670
+ return { ...state(), found: chat?.name ?? null }
671
+ },
672
+ 'POST /api/telegram/test': async () => {
673
+ if (!tgReady({ ...cfg.telegram, on: true })) throw new Error('connect Telegram first')
674
+ await sendTelegram(cfg.telegram, '🔔 A test from HeartCode\'s settings: notifications reach you.')
675
+ return state()
676
+ },
677
+ 'POST /api/telegram/set': ({ on, event, value }) => {
678
+ if (!cfg.telegram) throw new Error('connect Telegram first')
679
+ if (typeof on === 'boolean') cfg.telegram.on = on
680
+ if (event !== undefined) {
681
+ if (!EVENTS[event] || typeof value !== 'boolean') throw new Error(`event: ${Object.keys(EVENTS).join(', ')}, on or off`)
682
+ cfg.telegram.events = { ...cfg.telegram.events, [event]: value }
683
+ }
684
+ save('setting:telegram')
685
+ return state()
686
+ },
687
+ 'POST /api/telegram/remove': () => {
688
+ cfg.telegram = undefined
689
+ save('setting:telegram')
690
+ return state()
691
+ },
692
+ 'POST /api/statusbar': ({ statusBar }) => {
693
+ const clean = (a) => (Array.isArray(a) ? a.filter((x) => STATUS_IDS.has(x)) : [])
694
+ if (statusBar === false) cfg.statusBar = false
695
+ else if (statusBar == null) cfg.statusBar = undefined
696
+ else if (Array.isArray(statusBar)) {
697
+ const line = (row) => (Array.isArray(row) ? { left: clean(row), right: [] } : { left: clean(row?.left), right: clean(row?.right) }) // a line is a bare list (all left) or { left, right }
698
+ const lines = statusBar.map(line).filter((r) => r.left.length || r.right.length)
699
+ cfg.statusBar = lines.length ? lines : false // every line emptied out: same as off
700
+ } else throw new Error('statusBar: false, null, or a list of lines')
701
+ save('setting:statusBar')
702
+ return state()
703
+ },
631
704
  'POST /api/file': ({ name, text }) => {
632
705
  const f = FILES.find(([n]) => n === name)
633
706
  if (!f) throw new Error(`not a settings file: ${name}`)
@@ -654,7 +727,9 @@ export function startSettings({ cfg, apply = () => {}, port = 0 } = {}) {
654
727
  const servers = (data.mcpServers ??= {})
655
728
  if (on) {
656
729
  if (servers[name]) delete servers[name].disabled
657
- if (servers[name] && !Object.keys(servers[name]).length) delete servers[name] // only the "off" was ours
730
+ if (DEFAULT_SERVERS[name]?.disabled)
731
+ servers[name] = { ...(servers[name] ?? {}), disabled: false } // a built-in that's off by default: write an explicit "on" to beat the default
732
+ else if (servers[name] && !Object.keys(servers[name]).length) delete servers[name] // a default-on server we'd only turned off: back to the default
658
733
  } else servers[name] = { ...servers[name], disabled: true }
659
734
  writeJson(file, data)
660
735
  changed('mcp')
@@ -687,6 +762,13 @@ export function startSettings({ cfg, apply = () => {}, port = 0 } = {}) {
687
762
  changed('mcp')
688
763
  return state()
689
764
  },
765
+ // Sign in to a remote MCP server — needs the running HeartCode (it opens your browser). Not
766
+ // available when the page was opened standalone with `heart settings`.
767
+ 'POST /api/mcp/login': async ({ name }) => {
768
+ if (!onLoginMcp) throw new Error('open the settings from HeartCode (/settings), or sign in there with /login_mcp')
769
+ const message = await onLoginMcp(String(name ?? ''))
770
+ return { ...state(), message }
771
+ },
690
772
  'POST /api/prompt': ({ id, text }) => {
691
773
  const [file, name] = String(id ?? '').split('/')
692
774
  const b = PROMPT_FILES.includes(file) && builtinPrompts(file).find((x) => x.name === name)
@@ -720,6 +802,34 @@ export function startSettings({ cfg, apply = () => {}, port = 0 } = {}) {
720
802
  changed('skill')
721
803
  return state()
722
804
  },
805
+ // Install a skill from a GitHub repo or a SKILL.md URL (same as /install_skill); global scope,
806
+ // since the dashboard isn't tied to a project folder.
807
+ 'POST /api/skill/install': async ({ url }) => {
808
+ const msg = await installSkill(null, String(url ?? ''), 'global')
809
+ changed('skill')
810
+ return { ...state(), message: msg }
811
+ },
812
+ // What other coding CLIs have set up that can be brought in (same as /import), listed to pick from.
813
+ 'POST /api/imports': () => {
814
+ importCache = findImports(root)
815
+ return { items: importCache.map((it, id) => ({ id, group: it.group, label: it.label, desc: it.desc })) }
816
+ },
817
+ // Run the picked imports (by id, from the last listing) and reload.
818
+ 'POST /api/imports/run': ({ ids }) => {
819
+ const results = []
820
+ for (const id of Array.isArray(ids) ? ids : []) {
821
+ const it = importCache[id]
822
+ if (!it) continue
823
+ try {
824
+ results.push({ ok: true, label: it.label, message: it.run() })
825
+ } catch (e) {
826
+ results.push({ ok: false, label: it.label, message: e.message })
827
+ }
828
+ }
829
+ changed('skill')
830
+ changed('mcp')
831
+ return { ...state(), results }
832
+ },
723
833
  }
724
834
 
725
835
  // Settings changed by anyone else (another HeartCode or page on this folder, a hand): taken in, and
package/src/tabs.js CHANGED
@@ -115,7 +115,7 @@ export class Tabs {
115
115
  // The tab bar, three rows: tabs drawn as tabs, the one on screen open onto it (its bottom
116
116
  // edge missing), the others closed off. Number, name, and what it's doing.
117
117
  // ╭─────────────╮ ╭──────────────╮
118
- // │ 1 heart_cli │ │ 2 fix tests ●│ Ctrl+T open a new tab
118
+ // │ 1 heart_cli │ │ 2 fix tests ●│ Alt+T open a new tab
119
119
  // ─╯ ╰─┴──────────────┴──────────────────
120
120
  bar(cols = 100) {
121
121
  const mark = { '?': c.warn('?'), '●': c.brand('●'), '✓': c.ok('✓') }
@@ -137,7 +137,7 @@ export class Tabs {
137
137
  mid += line('│') + label + line('│') + ' '
138
138
  bottom += (on ? c.brand(`╯${' '.repeat(w)}╰`) : c.ghost(`┴${'─'.repeat(w)}┴`)) + c.ghost('─')
139
139
  })
140
- const hint = this.list.length > 1 ? 'Ctrl+T open a tab · Ctrl+Q close this one · Ctrl+N/P switch tabs' : 'Ctrl+T open a new tab'
140
+ const hint = this.list.length > 1 ? 'Alt+T open a tab · Alt+W close this one · Alt+N/P (or Ctrl+PgUp/PgDn) switch tabs' : 'Alt+T open a new tab'
141
141
  mid += ` ${c.faint(hint)}`
142
142
  bottom += c.ghost('─'.repeat(Math.max(0, cols - width(bottom.replace(/\x1b\[[0-9;]*m/g, '')))))
143
143
  return [top, mid, bottom]
@@ -0,0 +1,81 @@
1
+ // Telegram notifications: HeartCode messages you through your own bot when a task finishes, fails
2
+ // or waits for you (a question, a permission). Telegram's Bot API (https://core.telegram.org/bots/api):
3
+ // getMe checks the token, getUpdates finds your chat once you've pressed Start in the bot,
4
+ // sendMessage sends (plain text, 4096 characters at most). Set up on the settings page
5
+ // (cfg.telegram: { token, chatId, chatName, bot, on, events }). The token is never logged or shown whole.
6
+ import { log } from './log.js'
7
+ import { saveConfig } from './config.js'
8
+
9
+ const API = process.env.HEART_TELEGRAM_API || 'https://api.telegram.org' // the env: a stand-in server, for tests
10
+ export const EVENTS = {
11
+ done: 'A task finished',
12
+ failed: 'A task failed',
13
+ waiting: 'HeartCode is waiting for you (a question or a permission)',
14
+ }
15
+
16
+ async function call(token, method, body = {}, timeout = 15_000) {
17
+ let res
18
+ try {
19
+ res = await fetch(`${API}/bot${token}/${method}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal: AbortSignal.timeout(timeout) })
20
+ } catch (e) {
21
+ throw new Error(`can't reach Telegram (${e.cause?.code || e.name})`) // not e.message: the URL has the token in it
22
+ }
23
+ const j = await res.json().catch(() => ({ ok: false, description: `HTTP ${res.status}` }))
24
+ if (!j.ok) throw Object.assign(new Error(j.error_code === 401 || j.error_code === 404 ? 'Telegram refused the bot token (check it in @BotFather)' : j.description || `HTTP ${res.status}`), { code: j.error_code, retryAfter: j.parameters?.retry_after })
25
+ return j.result
26
+ }
27
+
28
+ // The token shown to people: its bot's number and the last 4 characters.
29
+ export const tokenHint = (token) => (token ? `${String(token).split(':')[0]}:…${String(token).slice(-4)}` : '')
30
+
31
+ // A token checked, and the chats that have written to the bot (newest first): { bot, chats: [{ id, name }] }.
32
+ // None yet: the user hasn't pressed Start in the bot (or wrote to it more than a day ago).
33
+ export async function connect(token) {
34
+ const me = await call(token, 'getMe')
35
+ const updates = await call(token, 'getUpdates', { limit: 100, allowed_updates: ['message'] }).catch((e) => {
36
+ if (e.code === 409) throw new Error('this bot is set up with a webhook, so its messages can\'t be read here: use a bot of its own for HeartCode')
37
+ throw e
38
+ })
39
+ const chats = new Map()
40
+ for (const u of [...updates].reverse()) {
41
+ const chat = u.message?.chat
42
+ if (!chat || chats.has(chat.id)) continue
43
+ chats.set(chat.id, { id: chat.id, name: chat.title || [chat.first_name, chat.last_name].filter(Boolean).join(' ') || (chat.username ? `@${chat.username}` : String(chat.id)) })
44
+ }
45
+ return { bot: me.username, chats: [...chats.values()] }
46
+ }
47
+
48
+ export const tgReady = (t) => Boolean(t?.token && t?.chatId && t.on !== false)
49
+
50
+ // One message; a rate limit is waited out once (Telegram says how long).
51
+ export async function sendTelegram(t, text, { silent = false } = {}) {
52
+ const body = { chat_id: t.chatId, text: String(text).slice(0, 4096), disable_notification: silent, link_preview_options: { is_disabled: true } }
53
+ try {
54
+ return await call(t.token, 'sendMessage', body)
55
+ } catch (e) {
56
+ if (!e.retryAfter) throw e
57
+ await new Promise((r) => setTimeout(r, Math.min(e.retryAfter, 60) * 1000))
58
+ return await call(t.token, 'sendMessage', body)
59
+ }
60
+ }
61
+
62
+ // An event, if Telegram is set up and that event is on. Never waits on it, never throws: a
63
+ // notification that can't be sent is logged, the work goes on.
64
+ // A token saved before Start was pressed in the bot has no chat yet: it's looked up then (and kept).
65
+ export function notify(cfg, event, text) {
66
+ const t = cfg?.telegram
67
+ if (!t?.token || t.on === false || t.events?.[event] === false) return
68
+ const chat = t.chatId ? Promise.resolve(t) : findChat(cfg)
69
+ chat.then((ready) => ready && sendTelegram(ready, text)).catch((e) => log('telegram', `${event}: couldn't send (${e.message})`))
70
+ }
71
+ async function findChat(cfg) {
72
+ const { chats } = await connect(cfg.telegram.token)
73
+ if (!chats.length) {
74
+ log('telegram', "no chat yet: press Start in the bot (Telegram), then HeartCode finds it")
75
+ return null
76
+ }
77
+ Object.assign(cfg.telegram, { chatId: chats[0].id, chatName: chats[0].name })
78
+ saveConfig(cfg)
79
+ log('telegram', `found the chat: ${chats[0].name}`)
80
+ return cfg.telegram
81
+ }