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/client.js CHANGED
@@ -2,6 +2,8 @@
2
2
  import { createHash } from 'node:crypto'
3
3
  import { setTimeout as sleep } from 'node:timers/promises'
4
4
  import { log, logRequest, requestLog } from './log.js'
5
+ import { loadRankings, scoreOf } from './rankings.js'
6
+ import { fetch } from './http.js' // not the built-in one: see http.js
5
7
 
6
8
  // Tokens in a text, estimated the way tokenizers split it: a word or a number is about one, a long
7
9
  // word more, every symbol one. Prose comes out near characters ÷ 4; code, CSS, JSON and SVG paths,
@@ -175,6 +177,13 @@ export function fitFor(messages, can, model) {
175
177
  // usage in a stream, the thinking sent back, the tools' full schemas, images.
176
178
  export const QUIRKS = ['noTemperature', 'noEffort', 'noThoughts', 'noStreamUsage', 'noReasoningBack', 'simpleSchemas', 'noImages', 'noParallel']
177
179
 
180
+ // A model's name without its version: its date, "latest", "preview" ("mistral-large-2411" → "mistral-large").
181
+ export const family = (m) => {
182
+ let f = String(m).split('/').pop().toLowerCase()
183
+ for (let was; was !== f; ) (was = f), (f = f.replace(/[-_:@.]?(latest|preview|exp|\d{4}(-\d{2}){0,2}|\d{6,8})$/, ''))
184
+ return f
185
+ }
186
+
178
187
  export class Client {
179
188
  constructor({ baseUrl, apiKey, model, provider, timeout = 600_000 } = {}) {
180
189
  this.provider = provider // its name in config.json, for the requests log
@@ -220,9 +229,24 @@ export class Client {
220
229
  }
221
230
  // The model in use answers but gives nothing usable (agent.js: empty replies, again and again):
222
231
  // the next one in the list takes over. False when there's no list.
223
- moveOn(why) {
232
+ // Another version of the same model (voxtral-small-latest → voxtral-small-2507) would likely do the
233
+ // same: skipped for the next one in your order, while there is one.
234
+ // avoid: models ("provider/model") given up on already (this message): not gone back to; false when
235
+ // every other model is one of them.
236
+ moveOn(why, avoid = new Set()) {
224
237
  if (!this.rotation) return false
225
- this.#next(why)
238
+ const r = this.rotation
239
+ const n = r.list.length
240
+ const was = family(r.list[r.at].model)
241
+ const ok = (t) => !avoid.has(`${t.provider}/${t.model}`) && t !== r.list[r.at]
242
+ let k = 1
243
+ while (k < n && (family(r.list[(r.at + k) % n].model) === was || !ok(r.list[(r.at + k) % n]))) k++
244
+ if (k === n) { // only versions of this model (or ones given up on) left: the first of those not given up on
245
+ k = 1
246
+ while (k < n && !ok(r.list[(r.at + k) % n])) k++
247
+ if (k === n) return false
248
+ }
249
+ this.#next(why, () => (r.at + k) % n)
226
250
  return true
227
251
  }
228
252
  #next(why, pick) {
@@ -245,17 +269,18 @@ export class Client {
245
269
  // Which model of the list to go on to after this one failed, for one request (tried: the places
246
270
  // tried, down: the providers that answered with an error, 400 or above). A provider that answered
247
271
  // with an error isn't asked again through its next model: the next one is from another provider.
248
- // When every provider has failed, the models not tried yet, in order; when all have been tried,
272
+ // The best-ranked of your models first (scoreOf: the next in a list is often a much smaller model,
273
+ // and the work goes on with it), then the unranked ones in your order. Your #1 still starts each
274
+ // message. When every provider has failed, the models not tried yet; when all have been tried,
249
275
  // simply the next one (round again).
250
276
  #pick(e, tried, down) {
251
277
  const r = this.rotation
252
278
  tried.add(r.at)
253
279
  if (e?.status >= 400) down.add(r.list[r.at].provider)
254
280
  const n = r.list.length
255
- const after = (ok) => {
256
- for (let k = 1; k <= n; k++) if (ok((r.at + k) % n)) return (r.at + k) % n
257
- return -1
258
- }
281
+ const data = loadRankings()
282
+ const order = [...Array(n - 1).keys()].map((k) => (r.at + k + 1) % n).map((i) => ({ i, score: (r.list[i].score ??= scoreOf(r.list[i].model, data)) })).sort((a, b) => a.score - b.score).map((x) => x.i) // stable: unranked keep your order
283
+ const after = (ok) => order.find(ok) ?? -1
259
284
  let i = after((i) => !tried.has(i) && !down.has(r.list[i].provider))
260
285
  if (i < 0) i = after((i) => !tried.has(i))
261
286
  if (i < 0) {
@@ -353,15 +378,15 @@ export class Client {
353
378
  return (await this.#fetch(url, init, { timeout })).json()
354
379
  }
355
380
 
356
- async listModels(timeout = 10_000) {
381
+ async listModels(timeout = 60_000) {
357
382
  return (await this.modelEntries(timeout)).map((m) => m.id ?? m.name)
358
383
  }
359
384
  // The server's own entries for its models ({ id, owned_by, context_length, pricing… }, as it sends them).
360
- async modelEntries(timeout = 10_000) {
385
+ async modelEntries(timeout = 60_000) {
361
386
  const data = await this.#json(this.baseUrl + '/models', undefined, timeout)
362
387
  // { result: [...] } (Cloudflare's shape): there the id is an internal one and the name is the model's
363
388
  if (Array.isArray(data.result)) return data.result.filter((m) => m?.name).map((m) => ({ ...m, id: m.name }))
364
- return (data.data ?? data.models ?? []).filter((m) => m && (m.id ?? m.name))
389
+ return (Array.isArray(data) ? data : (data.data ?? data.models ?? [])).filter((m) => m && (m.id ?? m.name)) // a bare list too (Typhoon)
365
390
  }
366
391
 
367
392
  // Best effort: asks the server how big the loaded context window is.
@@ -397,7 +422,7 @@ export class Client {
397
422
  },
398
423
  async () => {
399
424
  const d = await this.#json(this.baseUrl + '/models')
400
- const m = (d.data ?? d.models ?? []).find((x) => x.id === this.model || x.name === this.model)
425
+ const m = (Array.isArray(d) ? d : (d.data ?? d.models ?? [])).find((x) => x.id === this.model || x.name === this.model)
401
426
  return { size: n(windowOf(m)), server: m?.owned_by === 'vllm' || m?.max_model_len ? 'vllm' : null }
402
427
  },
403
428
  async () => ({ size: n(windowOf(await this.#json(`${this.baseUrl}/models/${encodeURIComponent(this.model)}`))), server: null }),
@@ -444,7 +469,7 @@ export class Client {
444
469
  return text
445
470
  }
446
471
  })()
447
- return { error: `${res.status}: ${String(why).slice(0, 300)}${said?.rate ? ' (a per-minute cap on your account, not the window)' : ''}` }
472
+ return { error: `${res.status}: ${String(why).slice(0, 300)}${said?.rate ? ' (a per-minute cap on the account, not the window)' : ''}` }
448
473
  }
449
474
 
450
475
  // Returns { content, reasoning, toolCalls, usage, finishReason, thinking }.
package/src/config.js CHANGED
@@ -27,11 +27,40 @@ export function speedOf(cfg) {
27
27
  const sec = (v, d, min, max) => (Number.isInteger(Number(v)) && Number(v) >= min && Number(v) <= max ? Number(v) : d)
28
28
  return { replyStart: sec(cfg.replyStart, 60, 5, 600), replyIdle: sec(cfg.replyIdle, 150, 10, 1800) }
29
29
  }
30
+ // A model test's wait (seconds): the one set, else Give up's (a test that waits less would call a model
31
+ // broken that a task still waits for)
32
+ export const testWaitOf = (cfg) => (Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : speedOf(cfg).replyStart)
33
+
34
+ // The time limits that depend on one another, kept from contradicting: a test waits at least as long as
35
+ // a model gets to start answering (Tests wait ≥ Give up), and a reply that has started may go quiet at
36
+ // least that long too (Stalled ≥ Give up: a pause mid-reply has the same causes as a slow start, a
37
+ // queue or thinking that isn't sent). The one just set (changed) stays; the other moves to fit. Returns
38
+ // what moved and why, for the page to say.
39
+ export function fitTimes(cfg, changed) {
40
+ const notes = []
41
+ const { replyStart: start, replyIdle: idle } = speedOf(cfg)
42
+ const test = Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : null
43
+ const [sLo] = SPEED_LIMITS.replyStart
44
+ if (changed === 'replyStart') {
45
+ if (test !== null && test < start) (cfg.testTimeout = start), notes.push({ name: 'testTimeout', text: `Tests wait raised to ${start} s too: a test should wait at least as long as Give up, or it calls a model broken that real work would still wait for` })
46
+ if (idle < start) (cfg.replyIdle = start), notes.push({ name: 'replyIdle', text: `Stalled raised to ${start} s too: a reply that has started may go quiet at least as long as a model gets to start` })
47
+ } else if (changed === 'replyIdle') {
48
+ if (start > idle) (cfg.replyStart = Math.max(sLo, idle)), notes.push({ name: 'replyStart', text: `Give up lowered to ${cfg.replyStart} s too: a model can't get longer to start than a started reply may go quiet` })
49
+ } else if (changed === 'testTimeout' && test !== null && test < start) {
50
+ if (test >= sLo) (cfg.replyStart = test), notes.push({ name: 'replyStart', text: `Give up lowered to ${test} s too: real work shouldn't wait longer for a model than its test does` })
51
+ else {
52
+ Object.assign(cfg, { testTimeout: sLo, replyStart: sLo })
53
+ notes.push({ name: 'testTimeout', text: `Tests wait set to ${sLo} s: the shortest Give up can be, and a test must wait at least as long` }, { name: 'replyStart', text: `Give up lowered to ${sLo} s too: real work shouldn't wait longer for a model than its test does` })
54
+ }
55
+ }
56
+ return notes
57
+ }
58
+
30
59
  // What a helper can be picked for (Your models' pills): [its label there, what #1 is told it's good at,
31
60
  // what the pill covers (its tooltip)]
32
61
  export const HELPER_JOBS = {
33
62
  ui: ['UI & visuals', 'websites, app screens, games, animation, 3D, charts', 'Websites and landing pages, app screens, games and animation, 3D, charts and SVG: anything people look at.'],
34
- code: ['Code & logic', 'backend, APIs, scripts, automation, fixing bugs, tests, reviewing changes', 'Backend and APIs, scripts and automation, fixing bugs, tests and refactoring. Reviews of the work go to these first, then to your other models.'],
63
+ code: ['Code & logic', 'backend, APIs, scripts, automation, fixing bugs, tests, reviewing changes', 'Backend and APIs, scripts and automation, fixing bugs, tests and refactoring. Reviews of the work go to these first, then to the other models.'],
35
64
  hard: ['Big & hard', 'hard thinking, planning, long tasks with many steps, huge files', 'Planning and architecture, tricky logic, long tasks with many steps, huge files or whole folders.'],
36
65
  quick: ['Quick & cheap', 'small jobs: searching and reading code, lookups, small edits', 'Searching and reading code, looking things up, small edits: simple jobs, on a model that answered fast.'],
37
66
  }
package/src/context.js CHANGED
@@ -85,7 +85,7 @@ export function contextSource(p, cfg = {}) {
85
85
  if (from === 'server') return `reported by the server${p.server ? ` (${p.server})` : ''}`
86
86
  if (from === 'models.dev') return "models.dev's published limit for this model"
87
87
  if (from === 'learned') return 'learned from the server refusing or cutting a bigger request'
88
- if (from === 'rate') return `your per-minute token cap at this provider, until ${new Date(p.rateCap.until).toLocaleString()}`
88
+ if (from === 'rate') return `the account's per-minute token cap at this provider, until ${new Date(p.rateCap.until).toLocaleString()}`
89
89
  if (LOCAL_SERVERS.includes(p.server)) return `the ${p.server} server doesn't say; assumed`
90
90
  return `the server doesn't say; assumed${p.largestAccepted ? `, and seen working up to ${p.largestAccepted} tokens` : ''} (grows as bigger requests work)`
91
91
  }
package/src/format.js CHANGED
@@ -11,6 +11,7 @@ import path from 'node:path'
11
11
  import { HOME, readJson } from './config.js'
12
12
  import { runCommand } from './tools.js'
13
13
  import { log } from './log.js'
14
+ import { onPath } from './spawn.js'
14
15
 
15
16
  const has = (root, f) => fs.existsSync(path.join(root, f))
16
17
  const read = (root, f) => {
@@ -20,9 +21,10 @@ const read = (root, f) => {
20
21
  return ''
21
22
  }
22
23
  }
23
- const onPath = (cmd) => (process.env.PATH ?? '').split(path.delimiter).some((d) => d && fs.existsSync(path.join(d, cmd)))
24
- const local = (root, cmd) => (has(root, `node_modules/.bin/${cmd}`) ? path.join(root, 'node_modules/.bin', cmd) : null)
25
- const q = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`
24
+ const WIN = process.platform === 'win32'
25
+ const local = (root, cmd) => ((cmd = WIN ? `${cmd}.cmd` : cmd), has(root, `node_modules/.bin/${cmd}`) ? path.join(root, 'node_modules/.bin', cmd) : null) // npm's .cmd on Windows
26
+ // a path quoted for the shell the command runs in: cmd.exe on Windows (double quotes), sh elsewhere
27
+ const q = (s) => (WIN ? `"${String(s).replace(/"/g, '""')}"` : `'${String(s).replace(/'/g, `'\\''`)}'`)
26
28
 
27
29
  // [file pattern, (root) → the command (the file's path is added at the end), or null]
28
30
  const BUILTIN = [
package/src/headless.js CHANGED
@@ -9,7 +9,8 @@
9
9
  // stdout: {"type":"system","subtype":"init",…}, {"type":"assistant",…}, {"type":"user",…}
10
10
  // (tool results), {"type":"result",…} after each message; and what the full screen
11
11
  // shows besides, as {"type":"system","subtype":…}: "todos" (the plan: content, status,
12
- // by: the model a part went to), "helper" (one at work: tool_use_id, label, model, status;
12
+ // why: a stuck step's reason, by: the model a part went to), "stuck" (the model says it's
13
+ // stuck: step, why, count, model), "helper" (one at work: tool_use_id, label, model, status;
13
14
  // "done" at its end), "review" (model, verdict yes/no, issues), "model_switch" (from, to,
14
15
  // reason), "warning" (message), "retry" (attempt, delay_ms, error), "status" (what it's
15
16
  // doing now, as the spinner says it: a running command's latest output line too)
@@ -149,7 +150,7 @@ export async function runHeadless(app, opts) {
149
150
  const emit = (obj) => process.stdout.write(JSON.stringify(obj) + '\n')
150
151
  const s = await app.session()
151
152
  if (!s) {
152
- const error = app.allOff() ? "the providers of all your models are switched off: switch one on (heart settings), or pass --model" : 'no model set up: add a provider and choose a model (heart settings), or pass --base-url and --model'
153
+ const error = app.allOff() ? "the providers of all the models are switched off: switch one on (heart settings), or pass --model" : 'no model set up: add a provider and choose a model (heart settings), or pass --base-url and --model'
153
154
  if (out === 'text') process.stderr.write(`heartcode: ${error}\n`)
154
155
  else emit({ type: 'result', subtype: 'error_during_execution', is_error: true, result: error, num_turns: 0, session_id: app.chat.id })
155
156
  return 1
package/src/http.js ADDED
@@ -0,0 +1,96 @@
1
+ // fetch, over node:http and node:https (HTTP/1.1) instead of Node's built-in fetch.
2
+ // The built-in one speaks HTTP/2 when a server offers it, and HTTP/2 puts every request to a host on
3
+ // one connection. When that connection dies without a word (the server or a router drops it, no FIN
4
+ // arrives), Node keeps it as open, every later request waits on it, and none is ever sent: a
5
+ // session whose providers all sit behind one proxy host had every model "not answering" for hours
6
+ // while the host answered curl at once. Here each request has a socket of its own (idle ones reused
7
+ // for a few seconds at most, Node's keep-alive agent), and a request that's stopped (Esc, a timeout)
8
+ // takes its socket with it, so a dead connection can't outlive the request that found it.
9
+ // Same shape as fetch: a standard Response, the signal's reason when stopped, a TypeError with
10
+ // cause (the code: ECONNREFUSED, ENOTFOUND…) when the server can't be reached.
11
+ import http from 'node:http'
12
+ import https from 'node:https'
13
+ import zlib from 'node:zlib'
14
+ import { Readable } from 'node:stream'
15
+
16
+ // each decoder flushing what it has as it comes (a streamed answer arrives piece by piece)
17
+ const Z = { flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH }
18
+ const BR = { flush: zlib.constants.BROTLI_OPERATION_FLUSH, finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH }
19
+ const DECODE = { gzip: () => zlib.createGunzip(Z), 'x-gzip': () => zlib.createGunzip(Z), deflate: () => zlib.createInflate(Z), br: () => zlib.createBrotliDecompress(BR), ...(zlib.createZstdDecompress && { zstd: () => zlib.createZstdDecompress() }) }
20
+ const ACCEPT = Object.keys(DECODE).filter((k) => k !== 'x-gzip').join(', ')
21
+ const NO_BODY = new Set([101, 103, 204, 205, 304])
22
+
23
+ export async function fetch(input, init = {}) {
24
+ const { signal, redirect = 'follow' } = init
25
+ // the body and headers as fetch would send them (a string, JSON, form data, URLSearchParams, a Blob…)
26
+ const asked = new Request(input, { method: init.method, headers: init.headers, body: init.body, duplex: 'half' })
27
+ let url = new URL(asked.url)
28
+ let method = asked.method
29
+ const headers = Object.fromEntries(asked.headers)
30
+ headers['accept-encoding'] ??= ACCEPT
31
+ let body = asked.body ? Buffer.from(await asked.arrayBuffer()) : null
32
+ for (let hops = 0; ; hops++) {
33
+ signal?.throwIfAborted()
34
+ const res = await send(url, method, body ? { ...headers, 'content-length': String(body.length) } : headers, body, signal)
35
+ const to = res.headers.location
36
+ if (redirect === 'manual' || ![301, 302, 303, 307, 308].includes(res.statusCode) || !to) return respond(res, url, hops > 0, signal)
37
+ res.resume() // a redirect's own body isn't read
38
+ if (redirect === 'error') throw new TypeError('fetch failed', { cause: new Error(`redirected to ${to}`) })
39
+ if (hops >= 20) throw new TypeError('fetch failed', { cause: new Error('too many redirects') })
40
+ const next = new URL(to, url)
41
+ // 303, and 301/302 after a POST: the next one is a GET, without the body (as fetch does)
42
+ if (res.statusCode === 303 || ([301, 302].includes(res.statusCode) && method === 'POST')) {
43
+ if (method !== 'HEAD') method = 'GET'
44
+ body = null
45
+ for (const h of ['content-type', 'content-length']) delete headers[h]
46
+ }
47
+ if (next.origin !== url.origin) delete headers.authorization // a key isn't handed to another site
48
+ url = next
49
+ }
50
+ }
51
+
52
+ // One request; resolves with the response once its headers are in.
53
+ function send(url, method, headers, body, signal) {
54
+ return new Promise((resolve, reject) => {
55
+ const req = (url.protocol === 'https:' ? https : http).request(url, { method, headers })
56
+ const stop = () => req.destroy(signal.reason)
57
+ signal?.addEventListener('abort', stop, { once: true })
58
+ req.on('response', (res) => {
59
+ // stopped later (while the body streams): the body ends with the reason, and the socket goes too
60
+ res.once('close', () => signal?.removeEventListener('abort', stop))
61
+ resolve(res)
62
+ })
63
+ req.on('error', (e) => {
64
+ signal?.removeEventListener('abort', stop)
65
+ reject(signal?.aborted ? signal.reason : new TypeError('fetch failed', { cause: e }))
66
+ })
67
+ req.end(body ?? undefined)
68
+ })
69
+ }
70
+
71
+ function respond(res, url, redirected, signal) {
72
+ const headers = new Headers()
73
+ for (let i = 0; i < res.rawHeaders.length; i += 2) headers.append(res.rawHeaders[i], res.rawHeaders[i + 1])
74
+ let body = null
75
+ if (NO_BODY.has(res.statusCode) || res.req?.method === 'HEAD') res.resume()
76
+ else {
77
+ let stream = res
78
+ const decode = DECODE[String(res.headers['content-encoding'] ?? '').trim().toLowerCase()]
79
+ if (decode) {
80
+ stream = decode()
81
+ res.on('error', (e) => stream.destroy(e))
82
+ res.pipe(stream)
83
+ }
84
+ stream.on('error', () => {}) // reported through the body (below), not as a crash
85
+ // the body errors with the signal's reason when stopped (as fetch's does), else with a TypeError
86
+ const reason = (e) => (signal?.aborted ? signal.reason : new TypeError('terminated', { cause: e }))
87
+ const reader = Readable.toWeb(stream).getReader()
88
+ body = new ReadableStream({
89
+ pull: (c) => reader.read().then(({ done, value }) => (done ? c.close() : c.enqueue(new Uint8Array(value))), (e) => c.error(reason(e))),
90
+ cancel: (why) => (res.destroy(), reader.cancel(why).catch(() => {})),
91
+ })
92
+ }
93
+ const r = new Response(body, { status: res.statusCode, statusText: res.statusMessage, headers })
94
+ Object.defineProperties(r, { url: { value: url.href }, redirected: { value: redirected } })
95
+ return r
96
+ }
package/src/importer.js CHANGED
@@ -10,6 +10,7 @@ import { spawnSync } from 'node:child_process'
10
10
  import { HOME, TEMP, readJson, writeJson } from './config.js'
11
11
  import { frontMatter } from './skills.js'
12
12
  import { Memory } from './memory.js'
13
+ import { fetch } from './http.js' // not the built-in one: see http.js
13
14
 
14
15
  const exists = (p) => {
15
16
  try {
@@ -65,7 +66,7 @@ function skillBodies(root, scope) {
65
66
  function skillDup(root, scope, name, body) {
66
67
  if (taken(root, scope, name)) return `a skill named ${name} is already there`
67
68
  const twin = skillBodies(root, scope).find(([, b]) => same(b, body))
68
- return twin ? `the same as your skill ${twin[0]}` : ''
69
+ return twin ? `the same as the skill ${twin[0]}` : ''
69
70
  }
70
71
 
71
72
  // A markdown command (Claude Code, Codex, OpenCode) → a HeartCode skill you type ("use: me").
@@ -109,7 +110,7 @@ function mcpDup(root, scope, name, cfg) {
109
110
  const have = readJson(mcpFile(root, scope), {}).mcpServers ?? {}
110
111
  if (have[name]) return `an MCP server named ${name} is already there`
111
112
  const twin = Object.entries(have).find(([, c]) => serverKey(c) === serverKey(cfg))
112
- return twin ? `the same server as your ${twin[0]}` : ''
113
+ return twin ? `the same server as ${twin[0]}` : ''
113
114
  }
114
115
 
115
116
  function importMcp(root, scope, name, cfg) {
@@ -189,13 +190,13 @@ export function findImports(root, home = os.homedir()) {
189
190
  for (const [rel, file] of filesIn(dir, ['.md'])) {
190
191
  const name = safe(rel)
191
192
  const { meta, body } = frontMatter(fs.readFileSync(file, 'utf8'))
192
- add(`${tool} · ${scope === 'global' ? 'yours' : 'this project'} · commands`, `/${name}`, (meta.description || body.split('\n')[0]).slice(0, 90), () => importCommand(root, scope, name, file), () => skillDup(root, scope, name, body))
193
+ add(`${tool} · ${scope === 'global' ? 'global' : 'this project'} · commands`, `/${name}`, (meta.description || body.split('\n')[0]).slice(0, 90), () => importCommand(root, scope, name, file), () => skillDup(root, scope, name, body))
193
194
  }
194
195
  }
195
196
  for (const [scope, dir] of [['project', path.join(root, '.gemini', 'commands')], ['global', path.join(home, '.gemini', 'commands')]]) {
196
197
  for (const [rel, file] of filesIn(dir, ['.toml'])) {
197
198
  const name = safe(rel)
198
- add(`Gemini CLI · ${scope === 'global' ? 'yours' : 'this project'} · commands`, `/${name}`, /^description\s*=\s*"([^"]*)"/m.exec(fs.readFileSync(file, 'utf8'))?.[1] ?? '', () => importToml(root, scope, name, file), () => (taken(root, scope, name) ? `a skill named ${name} is already there` : ''))
199
+ add(`Gemini CLI · ${scope === 'global' ? 'global' : 'this project'} · commands`, `/${name}`, /^description\s*=\s*"([^"]*)"/m.exec(fs.readFileSync(file, 'utf8'))?.[1] ?? '', () => importToml(root, scope, name, file), () => (taken(root, scope, name) ? `a skill named ${name} is already there` : ''))
199
200
  }
200
201
  }
201
202
  const skillSources = [
@@ -212,7 +213,7 @@ export function findImports(root, home = os.homedir()) {
212
213
  const file = path.join(dir, e.name, 'SKILL.md')
213
214
  if (!e.isDirectory() || !exists(file)) continue
214
215
  const { meta, body } = frontMatter(fs.readFileSync(file, 'utf8'))
215
- add(`${tool} · ${scope === 'global' ? 'yours' : 'this project'} · skills`, safe(e.name), (meta.description ?? '').slice(0, 90), () => importSkillFolder(root, scope, safe(e.name), path.join(dir, e.name)), () => skillDup(root, scope, safe(e.name), body))
216
+ add(`${tool} · ${scope === 'global' ? 'global' : 'this project'} · skills`, safe(e.name), (meta.description ?? '').slice(0, 90), () => importSkillFolder(root, scope, safe(e.name), path.join(dir, e.name)), () => skillDup(root, scope, safe(e.name), body))
216
217
  }
217
218
  }
218
219
  const claudeJson = readJson(path.join(home, '.claude.json'), {})
@@ -229,11 +230,11 @@ export function findImports(root, home = os.homedir()) {
229
230
  for (const [tool, scope, servers] of mcpSources) {
230
231
  for (const [name, cfg] of Object.entries(servers ?? {})) {
231
232
  if (!cfg?.command && !cfg?.url && !cfg?.httpUrl) continue
232
- add(`${tool} · ${scope === 'global' ? 'yours' : 'this project'} · MCP servers`, name, (cfg.command ? `${cfg.command} ${(cfg.args ?? []).join(' ')}` : (cfg.url ?? cfg.httpUrl)).slice(0, 90), () => importMcp(root, scope, name, cfg), () => mcpDup(root, scope, name, cfg))
233
+ add(`${tool} · ${scope === 'global' ? 'global' : 'this project'} · MCP servers`, name, (cfg.command ? `${cfg.command} ${(cfg.args ?? []).join(' ')}` : (cfg.url ?? cfg.httpUrl)).slice(0, 90), () => importMcp(root, scope, name, cfg), () => mcpDup(root, scope, name, cfg))
233
234
  }
234
235
  }
235
236
  for (const [tool, file] of [['Claude Code', path.join(home, '.claude', 'CLAUDE.md')], ['Codex', path.join(home, '.codex', 'AGENTS.md')], ['Gemini CLI', path.join(home, '.gemini', 'GEMINI.md')]]) {
236
- if (exists(file)) add(`${tool} · yours · instructions`, path.basename(file), `your ${tool} instructions → ~/.heart/HEARTCODE.md`, () => importInstructions(file, tool))
237
+ if (exists(file)) add(`${tool} · global · instructions`, path.basename(file), `${tool} instructions → ~/.heart/HEARTCODE.md`, () => importInstructions(file, tool))
237
238
  }
238
239
  const claudeMemory = path.join(home, '.claude', 'projects', root.replace(/[^a-zA-Z0-9]/g, '-'), 'memory')
239
240
  const notes = filesIn(claudeMemory, ['.md']).filter(([n]) => n !== 'MEMORY')
package/src/log.js CHANGED
@@ -24,11 +24,11 @@ export const LOG_DIR = process.env.HEART_LOG === 'off' ? null : path.resolve(pro
24
24
  // The kinds of text log, what each is for, and which topics (log('topic', …)) go in it. A topic not
25
25
  // listed goes in debug.
26
26
  export const LOG_KINDS = {
27
- tools: { label: 'Tools & commands', about: 'what HeartCode did on your machine: each tool call and its result, commands and background commands, MCP calls, files written', topics: ['tool', 'command', 'mcp', 'background', 'lsp', 'format', 'write', 'web', 'research', 'worktree'] },
27
+ tools: { label: 'Tools & commands', about: 'what HeartCode did on this machine: each tool call and its result, commands and background commands, MCP calls, files written', topics: ['tool', 'command', 'mcp', 'background', 'lsp', 'format', 'write', 'web', 'research', 'worktree'] },
28
28
  models: { label: 'Model choices', about: 'why a model answered or didn\'t: fallbacks, retries and quirks found', topics: ['rotate', 'retry', 'quirk'] },
29
29
  agent: { label: "Agent's decisions", about: 'why it did what it did: each task and its answer, plan-first, reviews, page checks, helpers and parts, compacting, lessons, the wrap-up', topics: ['task', 'look', 'review', 'compact', 'wrapup', 'learn', 'agent', 'director', 'guided', 'rewind', 'btw', 'parts'] },
30
30
  errors: { label: 'Errors', about: 'what went wrong: errors, crashes and warnings, with where they came from', topics: ['error', 'crash', 'warn', 'exit'] },
31
- conversation: { label: 'Conversation', about: 'a plain transcript: what you typed, its answers, its questions and your answers', topics: ['input', 'ask', 'answer'] },
31
+ conversation: { label: 'Conversation', about: 'a plain transcript: the messages typed, the answers, its questions and the replies', topics: ['input', 'ask', 'answer'] },
32
32
  debug: { label: 'Debug', about: 'everything else, for a bug report: HTTP, settings, voice, Telegram, sign-ins, tabs, headless and ACP', topics: [] },
33
33
  }
34
34
  const KIND_OF = Object.fromEntries(Object.entries(LOG_KINDS).flatMap(([k, v]) => v.topics.map((t) => [t, k])))
package/src/lsp.js CHANGED
@@ -6,7 +6,7 @@
6
6
  // back to the model with the edit's result. The settings page (General → Features) turns that off.
7
7
  import fs from 'node:fs'
8
8
  import path from 'node:path'
9
- import { spawn } from 'node:child_process'
9
+ import { spawnCmd, killTree } from './spawn.js'
10
10
  import { pathToFileURL, fileURLToPath } from 'node:url'
11
11
  import { log } from './log.js'
12
12
  import { HOME, readJson, writeJson } from './config.js'
@@ -45,7 +45,7 @@ const words = (cmd) => [...String(cmd).matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].m
45
45
  class Server {
46
46
  constructor(spec, argv, root) {
47
47
  Object.assign(this, { spec, root, next: 1, pending: new Map(), docs: new Map(), diags: new Map(), waiters: new Set(), dead: false })
48
- this.child = spawn(argv[0], argv.slice(1), { cwd: root, stdio: ['pipe', 'pipe', 'ignore'], detached: process.platform !== 'win32' })
48
+ this.child = spawnCmd(argv[0], argv.slice(1), { cwd: root, stdio: ['pipe', 'pipe', 'ignore'], detached: process.platform !== 'win32' })
49
49
  let buf = Buffer.alloc(0)
50
50
  this.child.stdout.on('data', (d) => {
51
51
  buf = Buffer.concat([buf, d])
@@ -176,10 +176,7 @@ class Server {
176
176
  stop() {
177
177
  if (this.dead) return
178
178
  this.dead = true
179
- try {
180
- if (process.platform !== 'win32') process.kill(-this.child.pid, 'SIGTERM')
181
- else this.child.kill()
182
- } catch {}
179
+ if (!killTree(this.child.pid)) try { this.child.kill() } catch {}
183
180
  }
184
181
  }
185
182
 
package/src/mcp.js CHANGED
@@ -9,7 +9,6 @@
9
9
  // list it gave the last time it ran (kept in ~/.heart/mcp-tools.json, with its instructions): so a
10
10
  // server starts the first time the model uses it, or once to say its tools; it stops when
11
11
  // HeartCode exits.
12
- import { spawn } from 'node:child_process'
13
12
  import crypto from 'node:crypto'
14
13
  import fs from 'node:fs'
15
14
  import os from 'node:os'
@@ -17,7 +16,9 @@ import path from 'node:path'
17
16
  import { pathToFileURL } from 'node:url'
18
17
  import { HOME, readJson, readConfig, writeJson, VERSION } from './config.js'
19
18
  import { log } from './log.js'
19
+ import { spawnCmd, killTree } from './spawn.js'
20
20
  import { savedToken, signIn, hasToken } from './oauth.js'
21
+ import { fetch } from './http.js' // not the built-in one: see http.js
21
22
 
22
23
  // Built in: none. HeartCode comes with no MCP servers; you add the ones you want (/settings → MCP
23
24
  // servers, /mcp, or ~/.heart/mcp.json). Kept as a map so a server could be built in again by name.
@@ -153,7 +154,7 @@ class Server {
153
154
  const { command, args = [], env = {} } = this.cfg
154
155
  log('mcp', `starting ${this.name}: ${command} ${args.join(' ')}`)
155
156
  const cwd = this.cfg.scratchCwd ? scratchDir(this.root, this.name) : (this.root ?? undefined) // in the project, so a relative path in its config works; a browser gets a scratch dir instead
156
- const child = (this.child = spawn(command, args, { cwd, env: { ...process.env, ...env }, stdio: ['pipe', 'pipe', 'pipe'], detached: process.platform !== 'win32' }))
157
+ const child = (this.child = spawnCmd(command, args, { cwd, env: { ...process.env, ...env }, stdio: ['pipe', 'pipe', 'pipe'], detached: process.platform !== 'win32' }))
157
158
  let buf = ''
158
159
  child.stdout.setEncoding('utf8') // a character split between two chunks stays whole
159
160
  child.stdout.on('data', (d) => {
@@ -209,7 +210,7 @@ class Server {
209
210
 
210
211
  #signIn(how, signal) {
211
212
  const open = this.hub.onSignIn
212
- if (!open) throw new Error(`${this.name} needs you to sign in: start heartcode and run /login_mcp ${this.name}`)
213
+ if (!open) throw new Error(`${this.name} needs a sign-in first: start heartcode and run /login_mcp ${this.name}`)
213
214
  return signIn(this.url, how, (link) => open(this.name, link), { signal, oauth: this.cfg.oauth })
214
215
  }
215
216
 
@@ -349,10 +350,7 @@ class Server {
349
350
  return
350
351
  }
351
352
  if (!this.child) return
352
- try {
353
- if (this.child.pid && process.platform !== 'win32') process.kill(-this.child.pid, 'SIGTERM')
354
- else this.child.kill()
355
- } catch {}
353
+ if (!killTree(this.child.pid)) try { this.child.kill() } catch {}
356
354
  this.child = null
357
355
  this.ready = null
358
356
  this.#failAll(new Error(`${this.name} was stopped`)) // calls waiting on it fail now (its exit comes later, ignored)
package/src/memory.js CHANGED
@@ -137,7 +137,7 @@ class Notes {
137
137
  // Keeps MEMORY.md in step with the notes.
138
138
  changed() {
139
139
  fs.mkdirSync(this.dir, { recursive: true })
140
- const what = this.scope === 'global' ? 'The notes HeartCode keeps about you, for every project' : "This project's notes, kept by HeartCode"
140
+ const what = this.scope === 'global' ? 'The notes HeartCode keeps about the user, for every project' : "This project's notes, kept by HeartCode"
141
141
  fs.writeFileSync(path.join(this.dir, 'MEMORY.md'), `# Memory\n\n${what}. Each line links to a note.\n\n${this.index(Infinity) || '(no notes yet)'}\n`)
142
142
  }
143
143
  }
package/src/oauth.js CHANGED
@@ -8,6 +8,7 @@ import path from 'node:path'
8
8
  import { createHash, randomBytes } from 'node:crypto'
9
9
  import { HOME, readJson, writeJson } from './config.js'
10
10
  import { log } from './log.js'
11
+ import { fetch } from './http.js' // not the built-in one: see http.js
11
12
 
12
13
  const FILE = path.join(HOME, 'mcp-auth.json')
13
14
  const b64url = (buf) => Buffer.from(buf).toString('base64url')
@@ -108,7 +109,7 @@ export async function signIn(url, wwwAuth, open, { signal, oauth = {} } = {}) {
108
109
  const q = new URL(req.url, redirect)
109
110
  if (q.pathname !== '/callback') return res.writeHead(404).end()
110
111
  const ok = q.searchParams.get('state') === state && q.searchParams.get('code')
111
- res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(`<!doctype html><meta charset="utf-8"><title>HeartCode</title><body style="font:16px system-ui;padding:40px">${ok ? '♥ Signed in. You can close this tab and go back to HeartCode.' : `Sign-in failed: ${String(q.searchParams.get('error_description') ?? q.searchParams.get('error') ?? 'wrong state').replace(/</g, '&lt;')}`}</body>`)
112
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(`<!doctype html><meta charset="utf-8"><title>HeartCode</title><body style="font:16px system-ui;padding:40px">${ok ? '♥ Signed in. This tab can be closed now.' : `Sign-in failed: ${String(q.searchParams.get('error_description') ?? q.searchParams.get('error') ?? 'wrong state').replace(/</g, '&lt;')}`}</body>`)
112
113
  clearTimeout(timer)
113
114
  ok ? resolve(ok) : reject(new Error(`sign-in failed: ${q.searchParams.get('error_description') ?? q.searchParams.get('error') ?? 'the reply did not match'}`))
114
115
  })
package/src/probe.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // A model's profile (what it can do: models.dev's word, or your settings) and how HeartCode talks to it.
2
+ import fs from 'node:fs'
2
3
  import path from 'node:path'
3
4
  import { HOME, readJson } from './config.js'
4
5
  import { contextWindow, contextSource, ASSUMED_REMOTE, LIMIT_MS } from './context.js'
@@ -13,8 +14,17 @@ export const profilePath = (client) => {
13
14
  }
14
15
  // Bump when a profile's shape changes, so older saved ones are made again once.
15
16
  const PROBE_VERSION = 2
17
+ // Kept in memory by file and its time: a page listing thousands of models reads only the ones that
18
+ // changed (a test, a setup, another HeartCode), not every file every time.
19
+ const profiles = new Map() // file → { at: its mtime, p }
16
20
  export const loadProfile = (client) => {
17
- const p = readJson(profilePath(client), null)
21
+ const file = profilePath(client)
22
+ const st = fs.statSync(file, { throwIfNoEntry: false })
23
+ if (!st) return profiles.delete(file), null
24
+ const at = `${st.mtimeMs}:${st.size}` // the size too: a file system that keeps times to the second
25
+ let hit = profiles.get(file)
26
+ if (hit?.at !== at) profiles.set(file, (hit = { at, p: readJson(file, null) }))
27
+ const p = hit.p && structuredClone(hit.p) // a copy, as a read gave: a caller may change it before writing
18
28
  // another model's (a model list switch once saved the first model's profile under the next one's name)
19
29
  return p?.version === PROBE_VERSION && (!p.model || p.model === client.model) ? p : null
20
30
  }
@@ -48,9 +58,9 @@ export function strategy(p, cfg = {}) {
48
58
 
49
59
  export function describe(p, s) {
50
60
  const yn = (v) => (v ? c.green('yes') : c.red('no'))
51
- const context = ['context', `${s.context}${c.dim(` (${p.set?.context ? 'set by you on /settings' : contextSource(p)}; change it on /settings)`)}`]
52
- const from = { 'models.dev': 'models.dev', you: 'you, on /settings', assumed: "nothing: it isn't in models.dev. Set what it can do on /settings" }[p.source] ?? 'an earlier test'
53
- const mine = (k) => (p.set?.[k] !== undefined ? c.dim(' (set by you)') : '')
61
+ const context = ['context', `${s.context}${c.dim(` (${p.set?.context ? 'set on /settings' : contextSource(p)}; change it on /settings)`)}`]
62
+ const from = { 'models.dev': 'models.dev', you: '/settings (set by hand)', assumed: "nothing: it isn't in models.dev. Set what it can do on /settings" }[p.source] ?? 'an earlier test'
63
+ const mine = (k) => (p.set?.[k] !== undefined ? c.dim(' (set by hand)') : '')
54
64
  return [['from', from], context, ['tool calls', yn(s.actions === 'tools') + mine('tools')], ['thinking', yn(s.thinking) + mine('thinking')], ['images', yn(s.vision) + (Date.now() - (p.quirks?.noImages ?? -Infinity) < LIMIT_MS ? c.dim(' (its provider refused an image today)') : mine('images'))], ['streaming', yn(s.stream) + mine('stream')]]
55
65
  .map(([k, v]) => ` ${c.dim(k.padEnd(15))} ${v}`)
56
66
  .join('\n')
package/src/rankings.js CHANGED
@@ -5,6 +5,7 @@ import path from 'node:path'
5
5
  import { HOME, readJson, writeJson } from './config.js'
6
6
  import { log } from './log.js'
7
7
  import { readParquet } from './parquet.js'
8
+ import { fetch } from './http.js' // not the built-in one: see http.js
8
9
 
9
10
  const FILE = path.join(HOME, 'rankings.json')
10
11
  const WEEK = 7 * 24 * 3600_000
@@ -96,3 +97,9 @@ export function rankIn(model, key, data) {
96
97
  const best = at.reduce((a, b) => (b.rank < a.rank ? b : a))
97
98
  return { rank: best.rank, of: list.length, as: best.name, score: best.score, votes: best.votes }
98
99
  }
100
+
101
+ // How good a model is, by its best share of the rankings that matter for coding work (coding, web
102
+ // apps, long real tasks, hard prompts): #5 of 200 is 0.025; lower is better, Infinity when it's in none
103
+ export function scoreOf(model, data = loadRankings()) {
104
+ return Math.min(...['text:coding', 'webdev:webdev', 'agent:overall', 'text:hard_prompts'].map((l) => rankIn(model, l, data)).filter(Boolean).map((r) => r.rank / r.of), Infinity)
105
+ }
package/src/reset.js CHANGED
@@ -9,13 +9,13 @@ export const RESETS = [
9
9
  {
10
10
  level: 'settings',
11
11
  label: 'Settings',
12
- desc: 'permissions, theme, effort, the toggles, the model list, voice; your keys, colors, formatters, prompts, MCP servers and hooks. Your providers, keys and model stay.',
12
+ desc: 'permissions, theme, effort, the toggles, the model list, voice; keys, colors, formatters, prompts, MCP servers and hooks. Providers, keys and the model stay.',
13
13
  files: ['keybindings.json', 'theme.json', 'format.json', 'prompts', 'mcp.json', 'hooks.json'],
14
14
  },
15
15
  {
16
16
  level: 'providers',
17
17
  label: 'Settings and providers',
18
- desc: 'the above, and your providers with their API keys, MCP sign-ins, what HeartCode learned about each model, prices',
18
+ desc: 'the above, and the providers with their API keys, MCP sign-ins, what HeartCode learned about each model, prices',
19
19
  files: ['config.json', 'mcp-auth.json', 'models', 'prices.json'],
20
20
  },
21
21
  {
package/src/sessions.js CHANGED
@@ -94,13 +94,13 @@ export function exportChat(chat, format, model = '') {
94
94
  if (format === 'md') {
95
95
  const body = list.map((e) => {
96
96
  const tools = e.tools.map((t) => `<details><summary>${t.name} ${esc(t.args.slice(0, 120))}</summary>\n\n${fence(t.result ?? '')}\n</details>`).join('\n')
97
- return [`## ${e.role === 'user' ? 'You' : 'HeartCode'}`, e.text, tools].filter(Boolean).join('\n\n')
97
+ return [`## ${e.role === 'user' ? 'User' : 'HeartCode'}`, e.text, tools].filter(Boolean).join('\n\n')
98
98
  })
99
99
  return `# ${title}\n\n_${when}_\n\n${body.join('\n\n')}\n`
100
100
  }
101
101
  const body = list.map((e) => {
102
102
  const tools = e.tools.map((t) => `<details><summary><b>${esc(t.name)}</b> <code>${esc(t.args.slice(0, 160))}</code></summary><pre>${esc(t.result ?? '')}</pre></details>`).join('')
103
- return `<section class="${e.role}"><h2>${e.role === 'user' ? 'You' : 'HeartCode'}</h2>${e.text ? `<div class="text">${esc(e.text)}</div>` : ''}${tools}</section>`
103
+ return `<section class="${e.role}"><h2>${e.role === 'user' ? 'User' : 'HeartCode'}</h2>${e.text ? `<div class="text">${esc(e.text)}</div>` : ''}${tools}</section>`
104
104
  })
105
105
  return `<!doctype html>
106
106
  <html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${esc(title)}</title>