heartcode 0.1.59 → 0.1.62

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
@@ -8,7 +8,7 @@ import fs from 'node:fs'
8
8
  import path from 'node:path'
9
9
  import crypto from 'node:crypto'
10
10
  import os from 'node:os'
11
- import { HOME, saveConfig, readJson, writeJson, byName, takeIn, whatOf, VERSION, speedOf, SPEED_LIMITS, HELPER_JOBS, helpersOf } from './config.js'
11
+ import { HOME, saveConfig, readJson, writeJson, byName, takeIn, whatOf, VERSION, speedOf, SPEED_LIMITS, HELPER_JOBS, helpersOf, testWaitOf, fitTimes } from './config.js'
12
12
  import { newer } from './update.js'
13
13
  import { DEFAULT_SERVERS, mcpAuth, serverName } from './mcp.js'
14
14
  import { sections, BUILTIN_PROMPTS, prompt, reloadPrompts } from './prompts.js'
@@ -27,6 +27,7 @@ import { capabilities } from './capabilities.js'
27
27
  import { connect, sendTelegram, tokenHint, tgReady, EVENTS } from './telegram.js'
28
28
  import { searchSettings, testSearxng, ENGINE_NAMES } from './web.js'
29
29
  import { log, LOGS, REQUESTS, useRequestLog, listRequests, readRequest, pruneLogs, logDays, logSize, clearLogs, LOG_KINDS, kindsOn, listLogRuns, readLog } from './log.js'
30
+ import { fetch } from './http.js' // not the built-in one: see http.js
30
31
 
31
32
  const PAGE = new URL('./settings.html', import.meta.url)
32
33
  const EFFORTS = ['default', 'low', 'medium', 'high']
@@ -54,11 +55,11 @@ const DETAILS = ['full', 'summary']
54
55
  // Files in ~/.heart the page edits as text: [name, what it is, JSON?]
55
56
  const FILES = [
56
57
  ['mcp.json', 'MCP servers: programs that give the model more tools', true, '{\n "mcpServers": {\n "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"] },\n "docs": { "url": "https://mcp.example.com/mcp" }\n }\n}'],
57
- ['hooks.json', 'Your commands, run before or after the model uses a tool (one can block it)', true, '{\n "hooks": {\n "PreToolUse": [\n { "matcher": "run_command", "hooks": [{ "type": "command", "command": "./check-command.sh" }] }\n ]\n }\n}'],
58
- ['keybindings.json', 'Your own keys: an action, or a /command to send', true, '{\n "alt+g": "cycle_permissions",\n "alt+r": "/rewind"\n}'],
59
- ['theme.json', 'Your own colors, on top of the theme you chose', true, '{\n "brand": "#ff6b9d",\n "background": "#101014"\n}'],
58
+ ['hooks.json', 'Commands run before or after the model uses a tool (one can block it)', true, '{\n "hooks": {\n "PreToolUse": [\n { "matcher": "run_command", "hooks": [{ "type": "command", "command": "./check-command.sh" }] }\n ]\n }\n}'],
59
+ ['keybindings.json', 'Custom keys: an action, or a /command to send', true, '{\n "alt+g": "cycle_permissions",\n "alt+r": "/rewind"\n}'],
60
+ ['theme.json', 'Custom colors, on top of the chosen theme', true, '{\n "brand": "#ff6b9d",\n "background": "#101014"\n}'],
60
61
  ['format.json', 'The formatter to run on each kind of file HeartCode writes', true, '{\n ".go": "gofmt -w {file}",\n ".py": "ruff format {file}"\n}'],
61
- ['HEARTCODE.md', 'Your instructions for every project (like AGENTS.md, for all of them)', false, '- Answer briefly.\n- Use pnpm, not npm.'],
62
+ ['HEARTCODE.md', 'Instructions for every project (like AGENTS.md, for all of them)', false, '- Answer briefly.\n- Use pnpm, not npm.'],
62
63
  ]
63
64
  // The prompts the page edits: every section of these files (prompts/*.md); the system prompts first.
64
65
  const PROMPT_FILES = ['agent', 'guided', 'compact', 'tests']
@@ -87,7 +88,7 @@ function setPrompt(file, name, text) {
87
88
  else own.set(name, text.trim())
88
89
  if (!own.size) return fs.rmSync(f, { force: true })
89
90
  fs.mkdirSync(path.dirname(f), { recursive: true })
90
- fs.writeFileSync(f, `# ${file}.md: your changes to HeartCode's prompts (the settings page; prompts/README.md in HeartCode)\n\n` + [...own].map(([n, t]) => `## ${n}\n\n${t}\n`).join('\n'))
91
+ fs.writeFileSync(f, `# ${file}.md: changes to HeartCode's prompts (the settings page; prompts/README.md in HeartCode)\n\n` + [...own].map(([n, t]) => `## ${n}\n\n${t}\n`).join('\n'))
91
92
  }
92
93
 
93
94
  // MCP servers: yours (mcp.json), each on or off (an entry with neither command nor url only switched off a
@@ -150,8 +151,16 @@ const LIST_V = 2 // how a saved list was read (2: airforce's cents, Cloudflare's
150
151
  // browser, whose storage is per address (a new port each time)
151
152
  const PREFS = path.join(HOME, 'settings-page.json')
152
153
  const PREF_KEYS = ['catSort', 'freeOnly', 'folded', 'sort', 'sorts', 'rank', 'filters']
154
+ // The saved lists (a MB or more): kept in memory, read again only when the file changes
155
+ let lists = null
156
+ const readLists = () => {
157
+ const st = fs.statSync(LISTS, { throwIfNoEntry: false })
158
+ const at = st ? `${st.mtimeMs}:${st.size}` : ''
159
+ if (lists?.at !== at) lists = { at, all: readJson(LISTS, {}) }
160
+ return lists.all
161
+ }
153
162
  function forgetList(...names) {
154
- const all = readJson(LISTS, {})
163
+ const all = { ...readLists() }
155
164
  if (!names.some((n) => n in all)) return
156
165
  for (const n of names) delete all[n]
157
166
  writeJson(LISTS, all)
@@ -262,7 +271,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
262
271
  if (gone) saveTests()
263
272
  }
264
273
  // How long a model test waits for its answer (cfg.testTimeout, seconds; the settings page sets it).
265
- const testWait = () => (Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : 10) * 1000
274
+ const testWait = () => testWaitOf(cfg) * 1000
266
275
  const noAnswer = () => `no answer within ${testWait() / 1000} seconds`
267
276
  // A provider's models tested a few at a time (more for a long list: startRun)
268
277
  const AT_ONCE = 4
@@ -456,10 +465,10 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
456
465
  rankings: ranked && { fetched: ranked.fetched, source: ranked.source },
457
466
  rotation: (({ then, ...opts }) => opts)(rotationOf(cfg)),
458
467
  helpers: helpersOf(cfg.helpers), // { 'provider/model': [jobs] }
459
- helperOrder: cfg.helperOrder === 'provider' ? 'provider' : 'own', // the order helpers are picked in: your list's, or your provider ranking's
468
+ helperOrder: cfg.helperOrder === 'provider' || cfg.helperOrder === 'own' ? cfg.helperOrder : 'score', // the order helpers are picked in: by their rankings (the default), your list's, or your provider ranking's
460
469
  helpersAuto: cfg.helpersAuto === true, // picked for you (pickHelpers), again whenever what's known changes: the models #1 may start as helpers, and what you picked each for
461
470
  jobs: HELPER_JOBS,
462
- 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])), logs: kindsOn(cfg), logDetail: cfg.logDetail === 'summary' ? 'summary' : 'full', logDays: logDays(cfg), testTimeout: Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : 10, ...speedOf(cfg) },
471
+ 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])), logs: kindsOn(cfg), logDetail: cfg.logDetail === 'summary' ? 'summary' : 'full', logDays: logDays(cfg), testTimeout: testWaitOf(cfg), ...speedOf(cfg) },
463
472
  logs: { runs: tilde(path.join(LOGS, 'runs')), requests: tilde(REQUESTS) },
464
473
  voice: cfg.voice ? JSON.stringify(cfg.voice, null, 2) : '',
465
474
  statusBar: cfg.statusBar === undefined ? null : cfg.statusBar, // false (off), a list of lines, or null (default)
@@ -579,7 +588,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
579
588
  const p = cfg.providers[name]
580
589
  if (!p) throw new Error(`no provider "${name}"`)
581
590
  if (p.list === false) return { models: [], details: {}, off: true }
582
- const lists = readJson(LISTS, {})
591
+ const lists = readLists()
583
592
  let saved = lists[name]?.baseUrl === p.baseUrl && lists[name].models?.length && lists[name].v === LIST_V ? lists[name] : null // an empty one, or one read the old way: asked again
584
593
  if (!saved) {
585
594
  const entries = await new Client({ baseUrl: p.baseUrl, apiKey: p.apiKey }).modelEntries()
@@ -592,7 +601,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
592
601
  description: m.description ? String(m.description).slice(0, 400) : undefined,
593
602
  price: listedPrice(m),
594
603
  }])) }
595
- writeJson(LISTS, { ...readJson(LISTS, {}), [name]: saved })
604
+ writeJson(LISTS, { ...readLists(), [name]: saved })
596
605
  }
597
606
  await loadPrices().catch(() => null)
598
607
  // and what's known now: its test or setup, and models.dev
@@ -635,13 +644,14 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
635
644
  save('setting:helpers')
636
645
  return { helpers: helpersOf(cfg.helpers), helpersAuto: false } // only these: the page saves a click at once, and the whole state of a long list takes seconds
637
646
  },
638
- // the order helpers are picked in: 'own' (your list's) or 'provider' (your provider ranking's, each
639
- // provider's in your list's order; rank: the ranking as the page has it, kept for HeartCode to use)
647
+ // the order helpers are picked in: 'score' (the default: best placed in LMArena's rankings first),
648
+ // 'own' (your list's) or 'provider' (your provider ranking's, each provider's in your list's order;
649
+ // rank: the ranking as the page has it, kept for HeartCode to use)
640
650
  'POST /api/helper-order': ({ by, rank }) => {
641
- cfg.helperOrder = by === 'provider' ? 'provider' : undefined
642
- cfg.providerRank = cfg.helperOrder && (Array.isArray(rank) ? rank.filter((x) => typeof x === 'string') : readJson(PREFS, {}).rank)
651
+ cfg.helperOrder = by === 'provider' || by === 'own' ? by : undefined
652
+ cfg.providerRank = cfg.helperOrder === 'provider' ? (Array.isArray(rank) ? rank.filter((x) => typeof x === 'string') : readJson(PREFS, {}).rank) : undefined
643
653
  save('setting:helperOrder')
644
- return { helperOrder: cfg.helperOrder ?? 'own' }
654
+ return { helperOrder: cfg.helperOrder ?? 'score' }
645
655
  },
646
656
  // the model list, in order (#1 is the model), and when to go on to the next
647
657
  'POST /api/order': ({ list, on, retries, next }) => {
@@ -784,7 +794,9 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
784
794
  if (name in SPEED_LIMITS && !(Number.isInteger(value) && value >= SPEED_LIMITS[name][0] && value <= SPEED_LIMITS[name][1])) throw new Error(`${name}: a whole number, ${SPEED_LIMITS[name][0]} to ${SPEED_LIMITS[name][1]}`)
785
795
  if (!['permissions', 'effort', 'theme', 'context', 'logDetail', 'logDays', 'testTimeout', ...Object.keys(SPEED_LIMITS), ...Object.keys(TOGGLES)].includes(name)) throw new Error(`no setting "${name}"`)
786
796
  cfg[name] = name === 'effort' && value === 'default' ? undefined : name === 'context' ? (value === null ? undefined : Number(value)) : value
797
+ const notes = ['replyStart', 'replyIdle', 'testTimeout'].includes(name) ? fitTimes(cfg, name) : [] // the others moved to fit, said on the page
787
798
  save(`setting:${name}`)
799
+ if (notes.length) return { ...state(), notes }
788
800
  if (name === 'logDetail') useRequestLog(cfg) // from the next request (a running HeartCode takes it in too: applySettings)
789
801
  if (name === 'logDays') pruneLogs(value) // older ones go now
790
802
  return state()
@@ -821,19 +833,19 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
821
833
  // it gets a first message saying so.
822
834
  'POST /api/telegram/connect': async ({ token }) => {
823
835
  const tk = String(token ?? '').trim() || cfg.telegram?.token
824
- if (!tk) throw new Error('paste the token @BotFather gave you')
836
+ if (!tk) throw new Error('paste the token from @BotFather')
825
837
  if (!/^\d+:[\w-]{20,}$/.test(tk)) throw new Error("that doesn't look like a bot token (it's like 123456789:AAH…, from @BotFather)")
826
838
  const r = await connect(tk)
827
839
  const chat = r.chats[0]
828
840
  const was = cfg.telegram?.token === tk ? cfg.telegram : {}
829
841
  cfg.telegram = { ...was, token: tk, bot: r.bot, ...(chat ? { chatId: chat.id, chatName: chat.name } : { chatId: undefined, chatName: undefined }), on: was.on ?? true }
830
842
  save('setting:telegram')
831
- if (chat) await sendTelegram(cfg.telegram, "✅ HeartCode is connected. You'll get a message here when a task finishes, fails, or waits for you.")
843
+ if (chat) await sendTelegram(cfg.telegram, "✅ HeartCode is connected. A message comes here when a task finishes, fails, or waits for an answer.")
832
844
  return { ...state(), found: chat?.name ?? null }
833
845
  },
834
846
  'POST /api/telegram/test': async () => {
835
847
  if (!tgReady({ ...cfg.telegram, on: true })) throw new Error('connect Telegram first')
836
- await sendTelegram(cfg.telegram, '🔔 A test from HeartCode\'s settings: notifications reach you.')
848
+ await sendTelegram(cfg.telegram, '🔔 A test from HeartCode\'s settings: notifications arrive.')
837
849
  return state()
838
850
  },
839
851
  'POST /api/telegram/set': ({ on, event, value }) => {
@@ -876,7 +888,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
876
888
  },
877
889
  'POST /api/search/test': async ({ searxng }) => {
878
890
  const u = String(searxng ?? '').trim() || searchSettings().searxng
879
- if (!u) throw new Error('type your SearXNG address first')
891
+ if (!u) throw new Error('type the SearXNG address first')
880
892
  const n = await testSearxng(/^https?:\/\//i.test(u) ? u : `https://${u}`).catch((e) => {
881
893
  throw new Error(`${u} didn't answer a search: ${e.cause?.code || e.message}`)
882
894
  })
@@ -954,7 +966,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
954
966
  if (fs.existsSync(file) && !readJson(file, null)) throw new Error("mcp.json isn't valid JSON: fix it first")
955
967
  const data = readJson(file, null) ?? {}
956
968
  const c = data.mcpServers?.[name]
957
- if (!c?.command) throw new Error(`no local MCP server "${name}" of yours`)
969
+ if (!c?.command) throw new Error(`no added local MCP server "${name}"`)
958
970
  flag = String(flag ?? '').trim().replace(/\s+/g, ' ')
959
971
  const words = flag.split(' ')
960
972
  if (!/^-/.test(words[0]) || words.length > 2) throw new Error('a flag starts with - (and may have one value: --port 3000)')
@@ -972,7 +984,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
972
984
  'POST /api/mcp/remove': ({ name }) => {
973
985
  const file = path.join(HOME, 'mcp.json')
974
986
  const data = readJson(file, null)
975
- if (!data?.mcpServers?.[name]) throw new Error(`no server "${name}" of yours`)
987
+ if (!data?.mcpServers?.[name]) throw new Error(`no added server "${name}"`)
976
988
  delete data.mcpServers[name]
977
989
  writeJson(file, data)
978
990
  changed('mcp')
@@ -1023,7 +1035,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1023
1035
  return state()
1024
1036
  },
1025
1037
  'POST /api/skill/delete': ({ name }) => {
1026
- if (!removeSkill(name)) throw new Error(`no skill "${name}" of yours`)
1038
+ if (!removeSkill(name)) throw new Error(`no added skill "${name}"`)
1027
1039
  changed('skill')
1028
1040
  return state()
1029
1041
  },
@@ -1133,12 +1145,27 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
1133
1145
  loadPrices().then(() => {
1134
1146
  for (const t of state().order) testNews(`${t.provider}/${t.model}`, t)
1135
1147
  test(state().order) // any without a profile yet
1148
+ warm()
1136
1149
  })
1137
1150
  resolve({ url, local, server, close: () => (watcher?.close(), server.closeAllConnections?.(), server.close()) })
1138
1151
  })
1139
1152
  })
1140
1153
  }
1141
1154
 
1155
+ // The saved model lists' models, looked up once in the background (their profiles, models.dev's word),
1156
+ // a few hundred at a time so the page isn't held up: then the Providers page loads at once.
1157
+ function warm() {
1158
+ const all = Object.entries(readLists()).flatMap(([name, l]) => (l.models ?? []).map((id) => [name, l.baseUrl, id]))
1159
+ const step = (i) => {
1160
+ for (const [name, baseUrl, id] of all.slice(i, i + 300)) {
1161
+ loadProfile(new Client({ baseUrl, model: id }))
1162
+ limitsOf(name, baseUrl, id)
1163
+ }
1164
+ if (i + 300 < all.length) setImmediate(() => step(i + 300))
1165
+ }
1166
+ step(0)
1167
+ }
1168
+
1142
1169
  // This machine's IPv4 addresses on its networks (Wi-Fi, Ethernet, a VPN), not the loopback one
1143
1170
  const addresses = () => Object.values(os.networkInterfaces()).flat().filter((n) => n && n.family === 'IPv4' && !n.internal).map((n) => n.address)
1144
1171
 
package/src/spawn.js ADDED
@@ -0,0 +1,48 @@
1
+ // Starting and stopping other programs the same way on every OS.
2
+ // Windows: npm, npx and most tools installed by npm are .cmd files, which Node won't start without a
3
+ // shell (EINVAL, or ENOENT for a bare "npx"); they go through cmd.exe, each word quoted for it. And a
4
+ // program started through a shell is stopped with its whole tree (taskkill /T): killing only the
5
+ // shell would leave the program itself running.
6
+ import { spawn as nodeSpawn, spawnSync } from 'node:child_process'
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+
10
+ const WIN = process.platform === 'win32'
11
+
12
+ // cmd.exe's quoting: a word with spaces or its special characters in double quotes ("" for a quote;
13
+ // backslashes at its end doubled, or the last one would hide the closing quote from the program)
14
+ const quote = (w) => (w === '' || /[\s"&|<>^()%!,;=]/.test(w) ? `"${String(w).replace(/"/g, '""').replace(/(\\+)$/, '$1$1')}"` : String(w))
15
+
16
+ // spawn(command, args, options), started through cmd.exe on Windows (spawnCmdSync: spawnSync's)
17
+ const viaCmd = (run) => (command, args = [], opts = {}) => (WIN ? run(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', `"${[command, ...args].map(quote).join(' ')}"`], { ...opts, windowsVerbatimArguments: true }) : run(command, args, opts))
18
+ export const spawnCmd = viaCmd(nodeSpawn)
19
+ export const spawnCmdSync = viaCmd(spawnSync)
20
+
21
+ // A program's path on the PATH, or '' (Windows: with its extension, .exe, .cmd…, as PATHEXT lists them)
22
+ const EXTS = WIN ? ['', ...(process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean)] : ['']
23
+ export function onPath(cmd) {
24
+ for (const d of (process.env.PATH ?? '').split(path.delimiter)) {
25
+ if (!d) continue
26
+ for (const e of EXTS) {
27
+ const p = path.join(d, cmd + e)
28
+ try {
29
+ if (fs.statSync(p).isFile()) return p
30
+ } catch {}
31
+ }
32
+ }
33
+ return ''
34
+ }
35
+
36
+ // Stops a program and what it started: its process group elsewhere (when it was started detached),
37
+ // its process tree on Windows. sig 0: only whether it's still there. False when nothing was there.
38
+ export function killTree(pid, sig = 'SIGTERM', group = !WIN) {
39
+ if (!pid) return false
40
+ try {
41
+ if (sig === 0) return process.kill(group ? -pid : pid, 0)
42
+ if (WIN) return spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' }).status === 0
43
+ process.kill(group ? -pid : pid, sig)
44
+ return true
45
+ } catch {
46
+ return false
47
+ }
48
+ }
package/src/telegram.js CHANGED
@@ -5,12 +5,13 @@
5
5
  // (cfg.telegram: { token, chatId, chatName, bot, on, events }). The token is never logged or shown whole.
6
6
  import { log } from './log.js'
7
7
  import { saveConfig } from './config.js'
8
+ import { fetch } from './http.js' // not the built-in one: see http.js
8
9
 
9
10
  const API = process.env.HEART_TELEGRAM_API || 'https://api.telegram.org' // the env: a stand-in server, for tests
10
11
  export const EVENTS = {
11
12
  done: 'A task finished',
12
13
  failed: 'A task failed',
13
- waiting: 'HeartCode is waiting for you (a question or a permission)',
14
+ waiting: 'HeartCode is waiting for an answer (a question or a permission)',
14
15
  }
15
16
 
16
17
  async function call(token, method, body = {}, timeout = 15_000) {