heartcode 0.1.63 → 0.1.95

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/log.js CHANGED
@@ -22,7 +22,8 @@ const STAMP = process.env.HEART_LOG_STAMP || stamp()
22
22
  export const LOG_DIR = process.env.HEART_LOG === 'off' ? null : path.resolve(process.env.HEART_LOG_DIR || path.join(LOGS, 'runs', STAMP))
23
23
 
24
24
  // The kinds of text log, what each is for, and which topics (log('topic', …)) go in it. A topic not
25
- // listed goes in debug.
25
+ // listed goes in debug. size and example: shown on the settings page (measured on real runs: a small
26
+ // fix is about 10 requests, a long task a few hundred).
26
27
  export const LOG_KINDS = {
27
28
  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
29
  models: { label: 'Model choices', about: 'why a model answered or didn\'t: fallbacks, retries and quirks found', topics: ['rotate', 'retry', 'quirk'] },
@@ -31,6 +32,20 @@ export const LOG_KINDS = {
31
32
  conversation: { label: 'Conversation', about: 'a plain transcript: the messages typed, the answers, its questions and the replies', topics: ['input', 'ask', 'answer'] },
32
33
  debug: { label: 'Debug', about: 'everything else, for a bug report: HTTP, settings, voice, Telegram, sign-ins, tabs, headless and ACP', topics: [] },
33
34
  }
35
+ // Each kind's size and a few of its lines, for the settings page (measured on real runs)
36
+ export const LOG_SAMPLES = {
37
+ requests: {
38
+ short: '~20 kB+ a request',
39
+ size: '~20 kB a request, growing with the conversation (each holds all of it): ~200 kB a small fix, tens of MB a long task. Summary: ~1 kB a request',
40
+ example: '0003-ok-openrouter-nemotron-3-ultra.json: the model, its place in the list, status 200, 10.9 s (first word after 10.6 s), tokens in and out, and (Everything) the whole request and reply',
41
+ },
42
+ tools: { short: '~2 kB a small fix', size: '~2 kB a small fix; up to a few MB a long task (results are written whole)', example: "[tool] read_file { path: 'math.js' }\n[tool] read_file result: 1| function add(a, b) {…\n[command] node test.js → exit code 0" },
43
+ models: { short: '<1 kB a task', size: 'under 1 kB a task; more when models fail and switch', example: "[rotate] this message starts on openrouter · nemotron-3-ultra\n[retry] attempt 1 failed, waiting 1000ms: 429 rate-limited\n[rotate] GLM-4.7-Flash didn't start answering within 45s → glm-5.3-flash" },
44
+ agent: { short: '<1 kB a task', size: 'under 1 kB a task', example: '[task] node test.js fails, fix it (tools mode)\n[review] nemotron-3-ultra: YES\n[agent] track record: openrouter/nemotron-3-ultra done' },
45
+ errors: { short: 'tiny', size: 'tiny: only when something goes wrong', example: '[error] task interrupted by the user\n[crash] Error: write EPIPE\n[exit] code 1' },
46
+ conversation: { short: '~1 kB a task', size: 'about what was typed and answered: ~1 kB a task', example: '[input] node test.js fails, fix it\n[answer] Fixed. The loop started at i = 1, skipping the first element…' },
47
+ debug: { short: '~140 kB a small fix', size: "big: every request's whole body too: ~140 kB a small fix, tens of MB a long task", example: '[http] → POST …/chat/completions {"model": "…", "messages": [the whole conversation]}\n[settings] taken in: models changed\n[session] openrouter · nemotron-3-ultra at https://…' },
48
+ }
34
49
  const KIND_OF = Object.fromEntries(Object.entries(LOG_KINDS).flatMap(([k, v]) => v.topics.map((t) => [t, k])))
35
50
  export const kindOf = (topic) => KIND_OF[topic] ?? 'debug'
36
51
  // which kinds are on (useRequestLog sets it from config.json)
@@ -130,8 +145,18 @@ export function log(topic, ...parts) {
130
145
 
131
146
  // The requests log: on, and how much of each (from config.json: logRequests, logDetail).
132
147
  export const requestLog = { on: false, detail: 'full', dir: null }
148
+ // --logs: this run's kinds, whatever config.json and the settings page say: "none", "all", or a
149
+ // comma-separated list of kinds (tools, models, agent, errors, conversation, debug, requests)
150
+ let forced = null
151
+ export function forceLogs(spec) {
152
+ const all = [...Object.keys(LOG_KINDS), 'requests']
153
+ const want = String(spec).split(',').map((w) => w.trim().toLowerCase()).filter(Boolean)
154
+ const bad = want.filter((w) => !all.includes(w) && w !== 'all' && w !== 'none')
155
+ if (bad.length || !want.length) throw new Error(`--logs: none, all, or some of ${all.join(', ')} (comma-separated)`)
156
+ forced = Object.fromEntries(all.map((k) => [k, !want.includes('none') && (want.includes('all') || want.includes(k))]))
157
+ }
133
158
  export function useRequestLog(cfg) {
134
- const on = kindsOn(cfg)
159
+ const on = forced ?? kindsOn(cfg)
135
160
  for (const k of Object.keys(logKinds)) logKinds[k] = on[k]
136
161
  return Object.assign(requestLog, { on: on.requests, detail: cfg.logDetail === 'summary' ? 'summary' : 'full' })
137
162
  }
package/src/mcp.js CHANGED
@@ -9,6 +9,7 @@
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 { trusted } from './trust.js'
12
13
  import crypto from 'node:crypto'
13
14
  import fs from 'node:fs'
14
15
  import os from 'node:os'
@@ -56,7 +57,7 @@ export function serverName(given, taken = []) {
56
57
  // (no built-in or configured servers), like Claude Code's --strict-mcp-config.
57
58
  export function loadServers(root, { extra = [], strict = false, includeDisabled = false } = {}) {
58
59
  const merged = strict ? {} : structuredClone(DEFAULT_SERVERS) // yours (below) win on a name
59
- const own = strict ? [] : [path.join(HOME, 'mcp.json'), root && path.join(root, '.heartcode', 'mcp.json')].filter(Boolean).map((f) => readConfig(f, {}))
60
+ const own = strict ? [] : [path.join(HOME, 'mcp.json'), root && trusted(root) && path.join(root, '.heartcode', 'mcp.json')].filter(Boolean).map((f) => readConfig(f, {})) // the folder's own: once you said yes to it (trust.js)
60
61
  const given = extra.map((c) => {
61
62
  const data = /^\s*\{/.test(c) ? JSON.parse(c) : readJson(path.resolve(c), null)
62
63
  if (!data) throw new Error(`can't read the MCP config ${c}`)
@@ -167,6 +168,7 @@ class Server {
167
168
  }
168
169
  })
169
170
  child.stderr.on('data', (d) => log('mcp', `${this.name} stderr: ${String(d).trim()}`))
171
+ child.stdin.on('error', (e) => log('mcp', `${this.name} stdin: ${e.message}`)) // it quit while being written to (EPIPE): its exit says so, not a crash
170
172
  const gone = new Promise((_, reject) => {
171
173
  child.on('error', (e) => reject(new Error(`${this.name} could not start: ${e.message}`)))
172
174
  child.on('exit', (code) => {
@@ -257,7 +259,15 @@ class Server {
257
259
  }
258
260
 
259
261
  #send(msg) {
260
- if (!this.url) return this.child.stdin.write(JSON.stringify(msg) + '\n')
262
+ if (!this.url) {
263
+ if (!this.child?.stdin.writable) {
264
+ log('mcp', `${this.name}: not running, ${msg.method ?? 'reply'} not sent`) // stopped, or gone
265
+ const p = this.pending.get(msg.id)
266
+ if (p) this.pending.delete(msg.id), p.reject(new Error(`${this.name} isn't running`)) // not left waiting
267
+ return
268
+ }
269
+ return this.child.stdin.write(JSON.stringify(msg) + '\n')
270
+ }
261
271
  this.#post(msg).catch((e) => {
262
272
  const p = this.pending.get(msg.id)
263
273
  if (!p) return log('mcp', `${this.name}: ${e.message}`)
package/src/probe.js CHANGED
@@ -4,6 +4,7 @@ import path from 'node:path'
4
4
  import { HOME, readJson } from './config.js'
5
5
  import { contextWindow, contextSource, ASSUMED_REMOTE, LIMIT_MS } from './context.js'
6
6
  import { c } from './ui.js'
7
+ import { cliOf } from './clis.js'
7
8
 
8
9
  // One cached profile per server + model. The URL path counts: proxies serve several providers
9
10
  // from one host (https://proxy.dev/groq, https://proxy.dev/openrouter).
@@ -12,6 +13,7 @@ export const profilePath = (client) => {
12
13
  const where = u.host + u.pathname.replace(/\/v1$/, '')
13
14
  return path.join(HOME, 'models', `${where}_${client.model}`.replace(/[^\w.-]+/g, '_') + '.json')
14
15
  }
16
+ export const CLI_CONTEXT = 10_000_000 // a CLI's: never compacted by HeartCode
15
17
  // Bump when a profile's shape changes, so older saved ones are made again once.
16
18
  const PROBE_VERSION = 2
17
19
  // Kept in memory by file and its time: a page listing thousands of models reads only the ones that
@@ -33,6 +35,8 @@ export const loadProfile = (client) => {
33
35
  // assumptions (source 'assumed': tool calls, streaming, a 128k window) until you say on the settings
34
36
  // page what it can do (set: { context, tools, thinking, images, stream }, source 'you').
35
37
  export function profileFrom(client, info) {
38
+ // a coding CLI's model (clis.js): it works with its own tools and keeps its own context; nothing to look up
39
+ if (cliOf(client.baseUrl)) return { version: PROBE_VERSION, model: client.model, baseUrl: client.baseUrl, source: 'cli', at: new Date().toISOString(), set: { tools: true, stream: true, images: false, thinking: false, context: CLI_CONTEXT } }
36
40
  return { version: PROBE_VERSION, model: client.model, baseUrl: client.baseUrl, source: info ? 'models.dev' : 'assumed', at: new Date().toISOString(), usage: true, context: ASSUMED_REMOTE, contextGuessed: true, ...(info && { known: info }) }
37
41
  }
38
42
 
@@ -59,7 +63,7 @@ export function strategy(p, cfg = {}) {
59
63
  export function describe(p, s) {
60
64
  const yn = (v) => (v ? c.green('yes') : c.red('no'))
61
65
  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'
66
+ const from = { cli: 'its CLI (it keeps its own context)', '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
67
  const mine = (k) => (p.set?.[k] !== undefined ? c.dim(' (set by hand)') : '')
64
68
  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')]]
65
69
  .map(([k, v]) => ` ${c.dim(k.padEnd(15))} ${v}`)
package/src/prompts.js CHANGED
@@ -7,6 +7,7 @@
7
7
  // {{name}} filled in from `vars`; a missing one is an error
8
8
  // {{#if name}} … {{else}} … {{/if}} optional parts (else is optional)
9
9
  // <!-- … --> a note right under the heading; never sent
10
+ import { trusted } from './trust.js'
10
11
  import fs from 'node:fs'
11
12
  import path from 'node:path'
12
13
  import { fileURLToPath } from 'node:url'
@@ -46,7 +47,7 @@ export function sections(text) {
46
47
  function load(file) {
47
48
  if (!cache.has(file)) {
48
49
  const merged = new Map()
49
- for (const dir of [BUILTIN, path.join(HOME, 'prompts'), project && path.join(project, '.heartcode', 'prompts')]) {
50
+ for (const dir of [BUILTIN, path.join(HOME, 'prompts'), project && trusted(project) && path.join(project, '.heartcode', 'prompts')]) { // the folder's own: once you said yes to it (trust.js)
50
51
  if (!dir) continue
51
52
  try {
52
53
  for (const [k, v] of sections(fs.readFileSync(path.join(dir, `${file}.md`), 'utf8'))) merged.set(k, v)
package/src/rankings.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // What each model is good at, from public rankings (LMArena: people comparing two models' answers
2
2
  // to the same prompt, by skill): overall, coding, web apps, images. Fetched once a week into
3
3
  // ~/.heart/rankings.json (with an orchestrator, or Update model info); a model is matched to its entry by name.
4
+ import fs from 'node:fs'
4
5
  import path from 'node:path'
5
6
  import { HOME, readJson, writeJson } from './config.js'
6
7
  import { log } from './log.js'
@@ -16,7 +17,14 @@ const FILES = 'https://huggingface.co/datasets/lmarena-ai/leaderboard-dataset/re
16
17
  // (agent: long real tasks, done by the model with tools; hard prompts: the hardest questions)
17
18
  const LISTS = ['text:overall', 'text:coding', 'text:hard_prompts', 'webdev:webdev', 'vision:overall', 'agent:overall']
18
19
 
19
- export const loadRankings = () => readJson(FILE, null)
20
+ // read again only when the file changed (the team list in the system prompt asks at every step)
21
+ let cache = { at: null, data: null }
22
+ export function loadRankings() {
23
+ const st = fs.statSync(FILE, { throwIfNoEntry: false })
24
+ const at = st ? `${st.mtimeMs}:${st.size}` : ''
25
+ if (cache.at !== at) cache = { at, data: st ? readJson(FILE, null) : null }
26
+ return cache.data
27
+ }
20
28
 
21
29
  // One ranking (text, webdev…), every category in it: { 'text:coding': [{ name, rank, score, votes }], … } (score: its rating there)
22
30
  async function fetchRanking(config, signal) {
@@ -59,7 +67,7 @@ export async function rankings({ signal, onWait, now = false } = {}) {
59
67
  // A name as words: "models/gemini-3.6-flash" and "Gemini 3.6 Flash (High)" are both "gemini 3 6 flash"
60
68
  const DROP = new Set(['latest', 'preview', 'free', 'it', 'instruct', 'exp', 'chat'])
61
69
  const WORDS = new Map() // name → its words: thousands of models are matched against hundreds of entries, each parsed once
62
- export const words = (name) => {
70
+ const words = (name) => {
63
71
  const k = String(name)
64
72
  if (!WORDS.has(k)) WORDS.set(k, toWords(k))
65
73
  return WORDS.get(k)
@@ -77,20 +85,30 @@ const toWords = (name) =>
77
85
  // Where a model stands in a list, 0 (best) to 1 (last); null when it isn't in it. Its entry: the
78
86
  // same words, or those followed only by its size ("nemotron 3 super" = "Nemotron 3 Super 120B A12B"),
79
87
  // maybe after the maker's name; of several (High, Low…), the best.
80
- export function place(model, list) {
88
+ function place(model, list) {
81
89
  const mine = words(model)
82
90
  if (!mine.length || !list?.length) return null
83
- const size = /^(\d+|[abmkt])$/
91
+ // only a size after it ("120 b", "a 12 b"): a number with its unit, never a bare one ("gpt 5" isn't "GPT-5.1")
92
+ const sizes = (rest) => rest.every((w, i) => /^[abmkt]$/.test(w) || (/^\d+$/.test(w) && /^[bmkt]$/.test(rest[i + 1] ?? '')))
84
93
  const at = list.filter((e) => {
85
94
  const theirs = words(e.name)
86
95
  // from their first word, or their second (a maker's name first: "NVIDIA-Nemotron-3-Super-120B-A12B")
87
- return [0, 1].some((from) => theirs.length >= from + mine.length && mine.every((w, i) => theirs[from + i] === w) && theirs.slice(from + mine.length).every((w) => size.test(w)))
96
+ return [0, 1].some((from) => theirs.length >= from + mine.length && mine.every((w, i) => theirs[from + i] === w) && sizes(theirs.slice(from + mine.length)))
88
97
  })
89
98
  return at.length ? Math.min(...at.map((e) => e.rank)) / list.length : null
90
99
  }
91
100
 
92
101
  // A model's place in one list ('text:coding'…), for showing: { rank, of, as, score, votes } (as: its name there); null when not in it
102
+ // looked up once per rankings loaded (the settings page asks for every model, in every list, often)
103
+ const seen = new WeakMap()
93
104
  export function rankIn(model, key, data) {
105
+ if (!data) return null
106
+ const memo = seen.get(data) ?? seen.set(data, new Map()).get(data)
107
+ const k = `${key}\n${model}`
108
+ if (!memo.has(k)) memo.set(k, lookUpRank(model, key, data))
109
+ return memo.get(k)
110
+ }
111
+ function lookUpRank(model, key, data) {
94
112
  const list = data?.lists[key]
95
113
  const at = list?.filter((e) => place(model, [e]) != null)
96
114
  if (!at?.length) return null
package/src/record.js ADDED
@@ -0,0 +1,80 @@
1
+ // Each model's track record from real work: what it finished and what it failed at, kept across
2
+ // projects in ~/.heart/records.json. On unless config.json's "trackRecord" is false (the settings
3
+ // page: General). Where HeartCode picks a model by ranking (the next one after a failure, a
4
+ // handover, helpers by score), a model that keeps doing well moves up and one that keeps failing
5
+ // moves down; a model that has failed most of its work doesn't start a message while another can.
6
+ import fs from 'node:fs'
7
+ import path from 'node:path'
8
+ import { HOME, readJson, writeJson } from './config.js'
9
+ import { log } from './log.js'
10
+
11
+ const FILE = path.join(HOME, 'records.json')
12
+ // what each event adds: [good, bad]
13
+ const WEIGHT = { done: [1, 0], helped: [1, 0], 'review-no': [0, 1], handover: [0, 1], 'helper-failed': [0, 1], 'bad-reply': [0, 0.5], 'not-proven': [0, 1], 'no-answer': [0, 1] }
14
+ export const records = { on: true }
15
+ export const useRecords = (cfg) => (records.on = cfg.trackRecord !== false)
16
+ const key = (t) => `${t.provider}/${t.model}`
17
+
18
+ // read again only when the file changed (other tabs and runs write it too)
19
+ let cache = { at: null, all: {} }
20
+ function all() {
21
+ const st = fs.statSync(FILE, { throwIfNoEntry: false })
22
+ const at = st ? `${st.mtimeMs}:${st.size}` : ''
23
+ if (cache.at !== at) cache = { at, all: readJson(FILE, {}) }
24
+ return cache.all
25
+ }
26
+
27
+ // A provider renamed: its models' records go with it
28
+ export function renameRecords(from, to) {
29
+ const now = readJson(FILE, {})
30
+ let moved = 0
31
+ for (const k of Object.keys(now)) if (k.startsWith(`${from}/`)) (now[`${to}/${k.slice(from.length + 1)}`] = now[k]), delete now[k], moved++
32
+ if (moved) writeJson(FILE, now)
33
+ }
34
+
35
+ // One event for a model ({ provider, model }). Older events fade (each new one counts a little more
36
+ // than the last: after about 25 more, an event counts half), so a model that got better shows it.
37
+ export function record(t, what) {
38
+ if (!records.on || !t?.model || !WEIGHT[what]) return
39
+ const [good, bad] = WEIGHT[what]
40
+ log('agent', `track record: ${key(t)} ${what}`)
41
+ try {
42
+ const now = readJson(FILE, {})
43
+ const r = now[key(t)] ?? { good: 0, bad: 0 }
44
+ now[key(t)] = { good: r.good * 0.97 + good, bad: r.bad * 0.97 + bad, at: Date.now() }
45
+ writeJson(FILE, now)
46
+ } catch {}
47
+ }
48
+
49
+ export const recordOf = (t) => all()[key(t)] ?? null
50
+ export const forgetRecords = () => fs.rmSync(FILE, { force: true })
51
+
52
+ // How often it failed, from 0 to 1 (0.5 with no record either way); null: too little to tell, or off
53
+ function failRate(t) {
54
+ const r = records.on ? recordOf(t) : null
55
+ if (!r || r.good + r.bad < 3) return null
56
+ return (r.bad + 1) / (r.good + r.bad + 2)
57
+ }
58
+ // failed most of its work (3.5 events' worth after fading: about 4 recent ones): last wherever
59
+ // HeartCode picks
60
+ export const unreliable = (t) => (failRate(t) ?? 0) >= 0.7 && recordOf(t).good + recordOf(t).bad >= 3.5
61
+
62
+ // A ranking score (scoreOf: lower is better, Infinity: not ranked) moved by the record: a model
63
+ // that never failed ×0.3, one that always does ×1.7, no record ×1. A model not ranked with a good
64
+ // record comes before the other unranked ones.
65
+ export function withRecord(t, rank) {
66
+ const f = failRate(t)
67
+ if (f === null) return rank
68
+ if (rank === Infinity) return f < 0.5 ? 1 + f : Infinity
69
+ return rank * (0.3 + 1.4 * f)
70
+ }
71
+
72
+ // Sorts [{ t, score }] (score: scoreOf's) best first: the unreliable last, then by score with the record
73
+ export const byRecord = (a, b) => {
74
+ const ua = unreliable(a.t)
75
+ const ub = unreliable(b.t)
76
+ if (ua !== ub) return ua ? 1 : -1
77
+ const x = withRecord(a.t, a.score)
78
+ const y = withRecord(b.t, b.score)
79
+ return x === y ? 0 : x < y ? -1 : 1
80
+ }