heartcode 0.1.40 → 0.1.42

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/importer.js CHANGED
@@ -1,12 +1,13 @@
1
1
  // /import: finds what other coding CLIs have set up (commands, skills, MCP servers, instructions,
2
2
  // memory) and copies what the user picks into HeartCode's places, converted. Nothing is used from
3
3
  // the other tools until it's imported, so their setups never cost tokens by surprise; nothing that
4
- // already exists in HeartCode is overwritten.
4
+ // already exists in HeartCode is overwritten. A duplicate (the same name, the same text, the same
5
+ // server) is told in the picker (dup) and added only when the user says so, under a free name.
5
6
  import fs from 'node:fs'
6
7
  import os from 'node:os'
7
8
  import path from 'node:path'
8
9
  import { spawnSync } from 'node:child_process'
9
- import { HOME, readJson, writeJson } from './config.js'
10
+ import { HOME, TEMP, readJson, writeJson } from './config.js'
10
11
  import { frontMatter } from './skills.js'
11
12
  import { Memory } from './memory.js'
12
13
 
@@ -37,12 +38,39 @@ function filesIn(dir, exts) {
37
38
  }
38
39
 
39
40
  const safe = (n) => String(n).toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '')
40
- const skillsDir = (root, scope) => (scope === 'global' ? path.join(HOME, 'skills') : path.join(root, '.heartcode', 'skills'))
41
+ // --temp: the throwaway folder, never the project (nothing is kept from a --temp run)
42
+ const skillsDir = (root, scope) => (scope === 'global' || TEMP ? path.join(HOME, 'skills') : path.join(root, '.heartcode', 'skills'))
41
43
  const taken = (root, scope, name) => exists(path.join(skillsDir(root, scope), `${name}.md`)) || exists(path.join(skillsDir(root, scope), name))
44
+ // name, else name-2, name-3…: the first not taken
45
+ const freeName = (isTaken, name) => {
46
+ let n = name
47
+ for (let i = 2; isTaken(n); i++) n = `${name}-${i}`
48
+ return n
49
+ }
50
+ const same = (a, b) => a.replace(/\s+/g, ' ').trim() === b.replace(/\s+/g, ' ').trim()
51
+ // The skills there are (one file, or a folder with SKILL.md): [name, body]
52
+ function skillBodies(root, scope) {
53
+ const dir = skillsDir(root, scope)
54
+ let entries = []
55
+ try {
56
+ entries = fs.readdirSync(dir, { withFileTypes: true })
57
+ } catch {}
58
+ return entries.flatMap((e) => {
59
+ const file = e.isDirectory() ? path.join(dir, e.name, 'SKILL.md') : e.name.endsWith('.md') ? path.join(dir, e.name) : null
60
+ if (!file || !exists(file)) return []
61
+ return [[e.name.replace(/\.md$/, ''), frontMatter(fs.readFileSync(file, 'utf8')).body]]
62
+ })
63
+ }
64
+ // Why a skill or command would be a duplicate there, or ''
65
+ function skillDup(root, scope, name, body) {
66
+ if (taken(root, scope, name)) return `a skill named ${name} is already there`
67
+ const twin = skillBodies(root, scope).find(([, b]) => same(b, body))
68
+ return twin ? `the same as your skill ${twin[0]}` : ''
69
+ }
42
70
 
43
71
  // A markdown command (Claude Code, Codex, OpenCode) → a HeartCode skill you type ("use: me").
44
72
  function importCommand(root, scope, name, file) {
45
- if (taken(root, scope, name)) return `/${name} already exists, kept it`
73
+ name = freeName((n) => taken(root, scope, n), name)
46
74
  const { meta, body } = frontMatter(fs.readFileSync(file, 'utf8'))
47
75
  const head = [`description: ${(meta.description || body.split('\n')[0]).replace(/\n/g, ' ').slice(0, 200)}`, `use: ${meta['user-invocable'] === 'false' ? 'model' : 'me'}`]
48
76
  if (meta['argument-hint']) head.push(`argument-hint: ${meta['argument-hint']}`)
@@ -54,7 +82,7 @@ function importCommand(root, scope, name, file) {
54
82
  // A Gemini CLI command (.toml with prompt and description) → a HeartCode skill. {{args}} stays as
55
83
  // is (it's HeartCode's too); !{cmd} becomes !`cmd`.
56
84
  function importToml(root, scope, name, file) {
57
- if (taken(root, scope, name)) return `/${name} already exists, kept it`
85
+ name = freeName((n) => taken(root, scope, n), name)
58
86
  const text = fs.readFileSync(file, 'utf8')
59
87
  const str = (key) => {
60
88
  const m = new RegExp(`^${key}\\s*=\\s*(?:"""([\\s\\S]*?)"""|'''([\\s\\S]*?)'''|"((?:[^"\\\\]|\\\\.)*)"|'([^']*)')`, 'm').exec(text)
@@ -69,16 +97,26 @@ function importToml(root, scope, name, file) {
69
97
 
70
98
  // A skill folder (Claude Code, Codex): copied as is, supporting files included.
71
99
  function importSkillFolder(root, scope, name, dir) {
72
- if (taken(root, scope, name)) return `${name} already exists, kept it`
100
+ name = freeName((n) => taken(root, scope, n), name)
73
101
  fs.cpSync(dir, path.join(skillsDir(root, scope), name), { recursive: true })
74
102
  return name
75
103
  }
76
104
 
105
+ const mcpFile = (root, scope) => (scope === 'global' || TEMP ? path.join(HOME, 'mcp.json') : path.join(root, '.heartcode', 'mcp.json'))
106
+ const serverKey = (cfg) => (cfg.command ? [cfg.command, ...(cfg.args ?? [])].join(' ') : (cfg.url ?? cfg.httpUrl ?? ''))
107
+ // Why an MCP server would be a duplicate there, or ''
108
+ function mcpDup(root, scope, name, cfg) {
109
+ const have = readJson(mcpFile(root, scope), {}).mcpServers ?? {}
110
+ if (have[name]) return `an MCP server named ${name} is already there`
111
+ const twin = Object.entries(have).find(([, c]) => serverKey(c) === serverKey(cfg))
112
+ return twin ? `the same server as your ${twin[0]}` : ''
113
+ }
114
+
77
115
  function importMcp(root, scope, name, cfg) {
78
- const file = scope === 'global' ? path.join(HOME, 'mcp.json') : path.join(root, '.heartcode', 'mcp.json')
116
+ const file = mcpFile(root, scope)
79
117
  const data = readJson(file, {})
80
118
  data.mcpServers ??= {}
81
- if (data.mcpServers[name]) return `MCP server ${name} already exists, kept it`
119
+ name = freeName((n) => data.mcpServers[n], name)
82
120
  const { command, args, env, url, httpUrl, headers, type } = cfg
83
121
  data.mcpServers[name] = command
84
122
  ? { command, ...(args?.length && { args }), ...(env && Object.keys(env).length && { env }) }
@@ -136,7 +174,8 @@ function codexServers(file) {
136
174
  // Everything importable, as picker items: { label, desc, group, run() → what was done }.
137
175
  export function findImports(root, home = os.homedir()) {
138
176
  const items = []
139
- const add = (group, label, desc, run) => items.push({ group, label, desc, run })
177
+ // dup(): why it would be a duplicate (asked when it runs: an earlier pick may have just added it)
178
+ const add = (group, label, desc, run, dup) => items.push({ group, label, desc, run, dup })
140
179
  const commandSources = [
141
180
  ['Claude Code', 'project', path.join(root, '.claude', 'commands')],
142
181
  ['Claude Code', 'global', path.join(home, '.claude', 'commands')],
@@ -150,13 +189,13 @@ export function findImports(root, home = os.homedir()) {
150
189
  for (const [rel, file] of filesIn(dir, ['.md'])) {
151
190
  const name = safe(rel)
152
191
  const { meta, body } = frontMatter(fs.readFileSync(file, 'utf8'))
153
- add(`${tool} · ${scope === 'global' ? 'yours' : 'this project'} · commands`, `/${name}`, (meta.description || body.split('\n')[0]).slice(0, 90), () => importCommand(root, scope, name, file))
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))
154
193
  }
155
194
  }
156
195
  for (const [scope, dir] of [['project', path.join(root, '.gemini', 'commands')], ['global', path.join(home, '.gemini', 'commands')]]) {
157
196
  for (const [rel, file] of filesIn(dir, ['.toml'])) {
158
197
  const name = safe(rel)
159
- 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))
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` : ''))
160
199
  }
161
200
  }
162
201
  const skillSources = [
@@ -172,8 +211,8 @@ export function findImports(root, home = os.homedir()) {
172
211
  for (const e of entries) {
173
212
  const file = path.join(dir, e.name, 'SKILL.md')
174
213
  if (!e.isDirectory() || !exists(file)) continue
175
- const { meta } = frontMatter(fs.readFileSync(file, 'utf8'))
176
- 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)))
214
+ 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))
177
216
  }
178
217
  }
179
218
  const claudeJson = readJson(path.join(home, '.claude.json'), {})
@@ -190,7 +229,7 @@ export function findImports(root, home = os.homedir()) {
190
229
  for (const [tool, scope, servers] of mcpSources) {
191
230
  for (const [name, cfg] of Object.entries(servers ?? {})) {
192
231
  if (!cfg?.command && !cfg?.url && !cfg?.httpUrl) continue
193
- 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))
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))
194
233
  }
195
234
  }
196
235
  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')]]) {
package/src/log.js CHANGED
@@ -25,7 +25,7 @@ export const LOG_DIR = process.env.HEART_LOG === 'off' ? null : path.resolve(pro
25
25
  // listed goes in debug.
26
26
  export const LOG_KINDS = {
27
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'] },
28
- models: { label: 'Model choices', about: 'why a model answered or didn\'t: fallbacks, retries, best-fit picks, strengths learned, probes and quirks found', topics: ['rotate', 'retry', 'fit', 'strengths', 'probe', 'quirk'] },
28
+ models: { label: 'Model choices', about: 'why a model answered or didn\'t: fallbacks, retries, best-fit picks and quirks found', topics: ['rotate', 'retry', 'fit', '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
31
  conversation: { label: 'Conversation', about: 'a plain transcript: what you typed, its answers, its questions and your answers', topics: ['input', 'ask', 'answer'] },
package/src/memory.js CHANGED
@@ -14,7 +14,7 @@
14
14
  // less: the tag list in the system prompt, and with each message only the notes it matches.
15
15
  import fs from 'node:fs'
16
16
  import path from 'node:path'
17
- import { HOME } from './config.js'
17
+ import { HOME, projectDir } from './config.js'
18
18
 
19
19
  export const TYPES = ['user', 'project', 'feedback', 'reference']
20
20
  const LINK = /\[\[([^\]|#]+)(?:[#|][^\]]*)?\]\]/g
@@ -146,7 +146,7 @@ class Notes {
146
146
  // the same name); writing goes to the scope asked for, or where the note already is.
147
147
  export class Memory {
148
148
  constructor(root, globalDir = path.join(HOME, 'memory')) {
149
- this.project = new Notes(path.join(root, '.heartcode', 'memory'), 'project')
149
+ this.project = new Notes(projectDir(root, 'memory'), 'project')
150
150
  this.global = new Notes(globalDir, 'global')
151
151
  }
152
152
 
package/src/probe.js CHANGED
@@ -1,14 +1,8 @@
1
- // Capability probes: small, automatic tests that decide how HeartCode talks to a model.
1
+ // A model's profile (what it can do: models.dev's word, or your settings) and how HeartCode talks to it.
2
2
  import path from 'node:path'
3
- import { deflateSync } from 'node:zlib'
4
- import { HOME, readJson, writeJson } from './config.js'
5
- import { est } from './client.js'
6
- import { contextWindow, contextSource, LOCAL_SERVERS, ASSUMED_REMOTE, LIMIT_MS } from './context.js'
7
- import { loadPrices, limitsOf } from './usage.js'
8
- import { applyEdit, parseBlocks } from './edit.js'
3
+ import { HOME, readJson } from './config.js'
4
+ import { contextWindow, contextSource, ASSUMED_REMOTE, LIMIT_MS } from './context.js'
9
5
  import { c } from './ui.js'
10
- import { log } from './log.js'
11
- import { prompt } from './prompts.js'
12
6
 
13
7
  // One cached profile per server + model. The URL path counts: proxies serve several providers
14
8
  // from one host (https://proxy.dev/groq, https://proxy.dev/openrouter).
@@ -17,7 +11,7 @@ export const profilePath = (client) => {
17
11
  const where = u.host + u.pathname.replace(/\/v1$/, '')
18
12
  return path.join(HOME, 'models', `${where}_${client.model}`.replace(/[^\w.-]+/g, '_') + '.json')
19
13
  }
20
- // Bump when the probe learns something new, so older cached profiles are probed again once.
14
+ // Bump when a profile's shape changes, so older saved ones are made again once.
21
15
  const PROBE_VERSION = 2
22
16
  export const loadProfile = (client) => {
23
17
  const p = readJson(profilePath(client), null)
@@ -25,282 +19,25 @@ export const loadProfile = (client) => {
25
19
  return p?.version === PROBE_VERSION && (!p.model || p.model === client.model) ? p : null
26
20
  }
27
21
 
28
- // --- tiny PNG encoder, for the vision probe ---
29
- const CRC = new Uint32Array(256).map((_, n) => {
30
- let v = n
31
- for (let k = 0; k < 8; k++) v = v & 1 ? 0xedb88320 ^ (v >>> 1) : v >>> 1
32
- return v
33
- })
34
- const crc32 = (buf) => {
35
- let v = 0xffffffff
36
- for (const b of buf) v = CRC[(v ^ b) & 0xff] ^ (v >>> 8)
37
- return (v ^ 0xffffffff) >>> 0
38
- }
39
- const pngChunk = (type, data) => {
40
- const head = Buffer.alloc(4)
41
- head.writeUInt32BE(data.length)
42
- const body = Buffer.concat([Buffer.from(type), data])
43
- const crc = Buffer.alloc(4)
44
- crc.writeUInt32BE(crc32(body))
45
- return Buffer.concat([head, body, crc])
46
- }
47
- export function solidPng(w, h, [r, g, b]) {
48
- const ihdr = Buffer.alloc(13)
49
- ihdr.writeUInt32BE(w, 0)
50
- ihdr.writeUInt32BE(h, 4)
51
- ihdr[8] = 8 // bit depth
52
- ihdr[9] = 2 // RGB
53
- const row = Buffer.alloc(1 + w * 3)
54
- for (let x = 0; x < w; x++) row.set([r, g, b], 1 + x * 3)
55
- const raw = Buffer.concat(Array(h).fill(row))
56
- const sig = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])
57
- return Buffer.concat([sig, pngChunk('IHDR', ihdr), pngChunk('IDAT', deflateSync(raw)), pngChunk('IEND', Buffer.alloc(0))])
58
- }
59
-
60
- const COLORS = { red: [220, 30, 30], green: [30, 170, 60], blue: [30, 60, 220], yellow: [245, 220, 30] }
61
- const firstInt = (t) => Number(/\d+/.exec(t)?.[0])
62
-
63
- // Rate limits, server errors and dropped connections are waited out (with the countdown, Esc
64
- // stops it), so a probe that starts finishes and is saved, and the model is never probed again.
65
- // A request the server rejects (400, 404 "no endpoint supports images", …) just means "no".
66
- const transient = (e) => !e.status || [408, 409, 429].includes(e.status) || e.status >= 500
67
- export async function probe(client, status, signal) {
68
- const [retryIf, purpose] = [client.retryIf, client.purpose]
69
- client.retryIf = (e, attempt) => transient(e) && attempt < 8 // about 4 minutes of waiting at most
70
- client.purpose = 'test' // in the requests log
71
- try {
72
- return await runProbe(client, status, signal)
73
- } finally {
74
- Object.assign(client, { retryIf, purpose })
75
- }
76
- }
77
-
78
- async function runProbe(client, report = () => {}, signal) {
79
- const status = (label) => {
80
- log('probe', label)
81
- report(label)
82
- }
83
- const p = { version: PROBE_VERSION, model: client.model, baseUrl: client.baseUrl, probedAt: new Date().toISOString() }
84
- let tokens = 0
85
- let ms = 0
86
- let calls = 0
87
- let lastError = null
88
- const chat = async (body, opts) => {
89
- const t0 = Date.now()
90
- const r = await client.chat({ temperature: 0, ...body }, { signal, ...opts }) // no max_tokens: the model decides how long
91
- ms += Date.now() - t0
92
- calls++
93
- if (r.usage?.completion_tokens) p.usage = true
94
- tokens += r.usage?.completion_tokens ?? est(r.content + r.reasoning)
95
- if (r.thinking) p.thinking = true
96
- return r
97
- }
98
- const say = (user, system) =>
99
- chat({ messages: system ? [{ role: 'system', content: system }, { role: 'user', content: user }] : [{ role: 'user', content: user }] }).then((r) =>
100
- r.content.trim(),
101
- )
102
- // A rejected request (400, 422, a 404 "no endpoint supports images", …) or an unparsable reply
103
- // means "not supported". Dead connections, auth errors, rate limits, outages, and a model that
104
- // was never reachable abort the probe, so a bad profile never gets cached.
105
- const safe = async (fn) => {
106
- try {
107
- return Boolean(await fn())
108
- } catch (e) {
109
- if (e.name === 'AbortError' || /^cannot reach/.test(e.message)) throw e
110
- // no answer (a timeout, a stalled reply): nothing learned, nothing saved; an answer it can't
111
- // read (not JSON) counts as "not supported" below
112
- if (e.name === 'TimeoutError') throw new Error(`probe stopped, nothing saved: ${e.message}`)
113
- if ([401, 429].includes(e.status) || e.status >= 500 || ([403, 404].includes(e.status) && !calls))
114
- throw new Error(`probe stopped, nothing saved: ${e.message}`)
115
- lastError = e
116
- return false
117
- }
118
- }
119
- const trials = async (label, fns) => {
120
- status(label)
121
- let pass = 0
122
- for (const fn of fns) if (await safe(fn)) pass++
123
- return { pass, total: fns.length }
124
- }
125
-
126
- status('streaming')
127
- let streamed = 0
128
- p.stream = await safe(async () => {
129
- const r = await chat({ messages: [{ role: 'user', content: prompt('probe/hello') }], stream: true }, { onToken: () => streamed++ })
130
- return streamed > 0 || r.thinking
131
- })
132
-
133
- status('context size')
134
- // what the server is and says; else models.dev's published size (context.js decides between them)
135
- const found = await client.contextSize()
136
- p.server = found.server
137
- p.context = found.size || (LOCAL_SERVERS.includes(found.server) ? 4096 : ASSUMED_REMOTE)
138
- p.contextGuessed = !found.size
139
- await loadPrices()
140
- const known = limitsOf(client.provider, client.baseUrl, client.model)
141
- if (known) p.known = known
142
-
143
- p.system = await trials(
144
- 'system prompt',
145
- ['What is 2 + 2?', 'Name a color.'].map((q) => async () => /banana/i.test(await say(q, prompt('probe/system')))),
146
- )
147
-
148
- p.format = await trials(
149
- 'exact format',
150
- [7, 42].map((n) => async () => (await say(prompt('probe/exact-number', { n }))).replace(/[.\s`*"']/g, '') === String(n)),
151
- )
152
-
153
- const menus = [
154
- ['a fruit', ['a hammer', 'an apple', 'a car'], 2],
155
- ['an animal', ['a river', 'a chair', 'a dog'], 3],
156
- ['a color', ['blue', 'a table', 'a spoon'], 1],
157
- ]
158
- p.menu = await trials(
159
- 'menu picking',
160
- menus.map(([what, opts, ans]) => async () => {
161
- const list = opts.map((o, i) => `${i + 1}. ${o}`).join('\n')
162
- return firstInt(await say(prompt('probe/menu', { what, list }))) === ans
163
- }),
164
- )
165
-
166
- status('stop sequences')
167
- p.stop = await safe(async () => {
168
- const r = await chat({ messages: [{ role: 'user', content: prompt('probe/count') }], stop: ['5'] })
169
- return /4/.test(r.content) && !/6/.test(r.content)
170
- })
171
-
172
- const tool = {
173
- type: 'function',
174
- function: {
175
- name: 'get_secret_code',
176
- description: prompt('probe/tool-description'),
177
- parameters: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },
178
- },
179
- }
180
- const toolMsg = (name) => ({ role: 'user', content: prompt('probe/tool-question', { name }) })
181
- const toolCall = (r, name) => {
182
- const call = r.toolCalls.find((t) => t.function.name === 'get_secret_code')
183
- try {
184
- return call && String(JSON.parse(call.function.arguments).name).toLowerCase().includes(name) ? call : null
185
- } catch {
186
- return null
187
- }
188
- }
189
- p.tools = await trials(
190
- 'tool calls',
191
- ['alpha', 'falcon', 'ember'].map((n) => async () => toolCall(await chat({ messages: [toolMsg(n)], tools: [tool] }), n)),
192
- )
193
- if (p.tools.pass) {
194
- status('tool results')
195
- p.toolResult = await safe(async () => {
196
- const r = await chat({ messages: [toolMsg('alpha')], tools: [tool] })
197
- const call = toolCall(r, 'alpha')
198
- if (!call) return false
199
- const r2 = await chat({
200
- messages: [
201
- toolMsg('alpha'),
202
- { role: 'assistant', content: r.content || '', tool_calls: [call] },
203
- { role: 'tool', tool_call_id: call.id, content: prompt('probe/tool-result') },
204
- ],
205
- tools: [tool],
206
- })
207
- return r2.content.includes('4417')
208
- })
209
- status('streamed tool calls')
210
- p.toolsStream = await safe(async () => toolCall(await chat({ messages: [toolMsg('falcon')], tools: [tool], stream: true }), 'falcon'))
211
-
212
- }
213
-
214
- status('constrained output')
215
- const words = ['zebra-purple', 'mango-teal']
216
- p.constrained = await safe(async () => {
217
- const schema = { type: 'object', properties: { word: { type: 'string', enum: words } }, required: ['word'], additionalProperties: false }
218
- const r = await chat({
219
- messages: [{ role: 'user', content: prompt('probe/capital') }],
220
- response_format: { type: 'json_schema', json_schema: { name: 'probe', strict: true, schema } },
221
- })
222
- return words.includes(JSON.parse(r.content).word)
223
- })
224
-
225
- const names = Object.keys(COLORS).sort(() => Math.random() - 0.5).slice(0, 2)
226
- p.vision = await trials(
227
- 'vision',
228
- names.map((name) => async () => {
229
- const url = 'data:image/png;base64,' + solidPng(256, 256, COLORS[name]).toString('base64')
230
- const r = await chat({
231
- messages: [{ role: 'user', content: [{ type: 'text', text: prompt('probe/image-color') }, { type: 'image_url', image_url: { url } }] }],
232
- })
233
- const t = r.content.toLowerCase()
234
- return t.includes(name) && Object.keys(COLORS).every((k) => k === name || !t.includes(k))
235
- }),
236
- )
237
-
238
- const cases = [
239
- {
240
- code: 'function add(a, b) {\n return a + b\n}\n\nfunction sub(a, b) {\n return a - b\n}\n',
241
- ask: 'Change the add function so it returns a * b instead of a + b.',
242
- ok: (t) => t.includes('return a * b') && t.includes('return a - b'),
243
- },
244
- {
245
- code: 'const greeting = "hello"\nconsole.log(greeting)\n',
246
- ask: 'Change the greeting from "hello" to "good morning".',
247
- ok: (t) => t.includes('good morning') && t.includes('console.log(greeting)'),
248
- },
249
- ]
250
- p.edit = await trials(
251
- 'edit skill',
252
- cases.map((cs) => async () => {
253
- const reply = await say(prompt('probe/edit', { code: cs.code, ask: cs.ask }))
254
- let text = cs.code
255
- const blocks = parseBlocks(reply)
256
- for (const b of blocks) {
257
- const r = applyEdit(text, b.search, b.replace)
258
- if (r.error) return false
259
- text = r.text
260
- }
261
- return blocks.length > 0 && cs.ok(text)
262
- }),
263
- )
264
-
265
- p.speed = ms ? Math.round(tokens / (ms / 1000)) : 0
266
- p.latency = calls ? Math.round(ms / calls) : 0
267
- // Every request failed: that's a broken model or endpoint, not a weak model.
268
- if (!calls) throw new Error(`probe stopped, nothing saved: no request succeeded${lastError ? ` (last error: ${lastError.message})` : ''}`)
269
- log('probe', 'result', p)
270
- writeJson(profilePath(client), p)
271
- return p
272
- }
273
-
274
- const all = (s) => Boolean(s && s.total && s.pass === s.total)
275
- const most = (s) => Boolean(s && s.total && s.pass * 3 >= s.total * 2)
276
-
277
- // A model's profile without testing it: what models.dev says (info: limitsOf), or, for a model it
278
- // doesn't know, plain assumptions (source 'assumed': tool calls, streaming, a 128k window) until you
279
- // say on the settings page what it can do (set: { context, tools, thinking, images, stream },
280
- // source 'you'). Profiles from a test (/test_model, heart probe) have no source.
22
+ // A model's profile: what models.dev says (info: limitsOf), or, for a model it doesn't know, plain
23
+ // assumptions (source 'assumed': tool calls, streaming, a 128k window) until you say on the settings
24
+ // page what it can do (set: { context, tools, thinking, images, stream }, source 'you').
281
25
  export function profileFrom(client, info) {
282
26
  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 }) }
283
27
  }
284
28
 
285
- // Turns a profile into decisions. Your settings for the model (p.set) come first; then, for a model
286
- // that wasn't tested, what models.dev says; for a tested one, what the test found. Config/flags
287
- // can override the window (--context).
29
+ // Turns a profile into decisions: your settings for the model (p.set) first, then what models.dev
30
+ // says. Config/flags can override the window (--context).
288
31
  export function strategy(p, cfg = {}) {
289
32
  const set = p.set ?? {}
290
- const said = p.source ? (p.known ?? {}) : null // not tested: models.dev's word (or nothing known)
291
- const tools = set.tools ?? (said ? said.tools !== false : most(p.tools) && p.toolResult)
292
- const thinking = set.thinking ?? (said ? Boolean(said.thinking) : Boolean(p.thinking))
293
- const stream = set.stream ?? (said ? true : Boolean(p.stream))
33
+ const said = p.known ?? {}
34
+ const thinking = set.thinking ?? Boolean(said.thinking)
294
35
  const win = contextWindow(p)
295
36
  return {
296
- actions: tools ? 'tools' : 'guided',
297
- edits: said || all(p.edit) ? 'search_replace' : 'rewrite',
298
- enforce: !said && Boolean(p.constrained),
299
- stream,
300
- toolsStream: stream && (said ? true : Boolean(p.toolsStream)),
301
- stop: said ? !thinking : Boolean(p.stop), // stop sequences cut into a thinking model's thinking
302
- mergeSystem: said ? false : !most(p.system),
303
- vision: !(Date.now() - (p.quirks?.noImages ?? -Infinity) < LIMIT_MS) && (set.images ?? (said ? Boolean(said.images) : all(p.vision))), // its provider refused images this week: none
37
+ actions: (set.tools ?? said.tools !== false) ? 'tools' : 'guided',
38
+ stream: set.stream ?? true,
39
+ stop: !thinking, // stop sequences cut into a thinking model's thinking
40
+ vision: !(Date.now() - (p.quirks?.noImages ?? -Infinity) < LIMIT_MS) && (set.images ?? Boolean(said.images)), // its provider refused images this week: none
304
41
  thinking,
305
42
  context: cfg.context || set.context || win.size, // context.js: measured, said, models.dev, learned, or assumed
306
43
  contextSure: Boolean(cfg.context || set.context) || win.sure,
@@ -311,37 +48,10 @@ export function strategy(p, cfg = {}) {
311
48
 
312
49
  export function describe(p, s) {
313
50
  const yn = (v) => (v ? c.green('yes') : c.red('no'))
314
- const score = (x) => {
315
- if (!x) return c.dim('–')
316
- const t = `${x.pass}/${x.total}`
317
- return x.pass === x.total ? c.green(t) : x.pass ? c.yellow(t) : c.red(t)
318
- }
319
51
  const context = ['context', `${s.context}${c.dim(` (${p.set?.context ? 'set by you on /settings' : contextSource(p)}; change it on /settings)`)}`]
320
- // not tested: where it's from, and what it can do
321
- if (p.source) {
322
- 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]
323
- const mine = (k) => (p.set?.[k] !== undefined ? c.dim(' (set by you)') : '')
324
- 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')]]
325
- .map(([k, v]) => ` ${c.dim(k.padEnd(15))} ${v}`)
326
- .join('\n')
327
- }
328
- const rows = [
329
- ['streaming', yn(p.stream) + (p.thinking ? c.dim(' (thinking model)') : '')],
330
- context,
331
- ['system prompt', score(p.system)],
332
- ['exact format', score(p.format)],
333
- ['menu picking', score(p.menu)],
334
- ['stop sequences', yn(p.stop) + (!p.stop && p.thinking ? c.dim(' (they cut into the thinking; not used)') : '')],
335
- ['tool calls', score(p.tools) + (p.tools?.pass ? c.dim(` uses results: ${p.toolResult ? 'yes' : 'no'} · streamed: ${p.toolsStream ? 'yes' : 'no'}`) : '')],
336
- ['constrained', yn(p.constrained)],
337
- ['vision', score(p.vision)],
338
- ['edit skill', score(p.edit)],
339
- ['speed', `${p.speed} tok/s` + (p.latency ? c.dim(` · ${(p.latency / 1000).toFixed(1)}s per reply`) : '')],
340
- ]
341
- const lines = rows.map(([k, v]) => ` ${c.dim(k.padEnd(15))} ${v}`)
342
- lines.push(
343
- ` ${c.bold('→')} actions: ${c.cyan(s.actions)} · edits: ${c.cyan(s.edits)}` +
344
- `${s.enforce ? ' · enforced answers' : ''}${s.vision ? ' · images' : ''}${s.mergeSystem ? ' · system→user' : ''}`,
345
- )
346
- return lines.join('\n')
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)') : '')
54
+ 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
+ .map(([k, v]) => ` ${c.dim(k.padEnd(15))} ${v}`)
56
+ .join('\n')
347
57
  }
package/src/prompts.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // Every text HeartCode sends to a model is a section of a markdown file in prompts/ (agent.md,
2
- // guided.md, compact.md, probe.md). prompt('guided/next-action') is the "## next-action" section of
2
+ // guided.md, compact.md). prompt('guided/next-action') is the "## next-action" section of
3
3
  // guided.md. The user's own sections override the built-in ones, by name:
4
4
  // ~/.heart/prompts/<file>.md for every project
5
5
  // <project>/.heartcode/prompts/<file>.md for one project
package/src/rankings.js CHANGED
@@ -8,6 +8,7 @@ import { readParquet } from './parquet.js'
8
8
 
9
9
  const FILE = path.join(HOME, 'rankings.json')
10
10
  const WEEK = 7 * 24 * 3600_000
11
+ const VERSION = 2 // 2: with each model's score; an older file is fetched again
11
12
  const FILES = 'https://huggingface.co/datasets/lmarena-ai/leaderboard-dataset/resolve/main' // one Parquet file per ranking: text, webdev, vision, agent
12
13
 
13
14
  // The skills a task can need: [ranking, its category, what it's for] (the pick names them).
@@ -32,12 +33,12 @@ const OVERALL = 'text:overall' // a skill a model isn't ranked on: its overall p
32
33
 
33
34
  export const loadRankings = () => readJson(FILE, null)
34
35
 
35
- // One ranking (text, webdev…), every category in it: { 'text:coding': [{ name, rank }], … }
36
+ // One ranking (text, webdev…), every category in it: { 'text:coding': [{ name, rank, score, votes }], … } (score: its rating there)
36
37
  async function fetchRanking(config, signal) {
37
38
  const res = await fetch(`${FILES}/${config}/latest-00000-of-00001.parquet`, { signal: AbortSignal.any([AbortSignal.timeout(120_000), ...(signal ? [signal] : [])]) })
38
39
  if (!res.ok) throw new Error(`rankings ${config}: HTTP ${res.status}`)
39
40
  const out = {}
40
- for (const r of readParquet(Buffer.from(await res.arrayBuffer()), ['model_name', 'rank', 'category'])) (out[`${config}:${r.category}`] ??= []).push({ name: r.model_name, rank: r.rank })
41
+ for (const r of readParquet(Buffer.from(await res.arrayBuffer()), ['model_name', 'rank', 'category', 'rating', 'vote_count'])) (out[`${config}:${r.category}`] ??= []).push({ name: r.model_name, rank: r.rank, score: Math.round(r.rating), votes: r.vote_count })
41
42
  return out
42
43
  }
43
44
 
@@ -46,12 +47,12 @@ async function fetchRanking(config, signal) {
46
47
  let refreshing = null
47
48
  export async function rankings({ signal, onWait, now = false } = {}) {
48
49
  const have = loadRankings()
49
- if (have && Date.now() - have.fetched < WEEK && !now) return have
50
+ if (have && have.v === VERSION && Date.now() - have.fetched < WEEK && !now) return have
50
51
  refreshing ??= (async () => {
51
52
  const wanted = new Set([...Object.values(SKILLS).map(([c, k]) => `${c}:${k}`), OVERALL])
52
53
  const all = Object.assign({}, ...(await Promise.all([...new Set([...wanted].map((p) => p.split(':')[0]))].map((c) => fetchRanking(c, have ? undefined : signal)))))
53
54
  const lists = Object.fromEntries(Object.entries(all).filter(([k]) => wanted.has(k)))
54
- const out = { fetched: Date.now(), source: 'LMArena (huggingface.co/datasets/lmarena-ai/leaderboard-dataset)', lists }
55
+ const out = { v: VERSION, fetched: Date.now(), source: 'LMArena (huggingface.co/datasets/lmarena-ai/leaderboard-dataset)', lists }
55
56
  writeJson(FILE, out)
56
57
  log('fit', `rankings fetched: ${Object.entries(lists).map(([k, v]) => `${k} ${v.length}`).join(', ')}`)
57
58
  return out
@@ -72,8 +73,14 @@ export async function rankings({ signal, onWait, now = false } = {}) {
72
73
 
73
74
  // A name as words: "models/gemini-3.6-flash" and "Gemini 3.6 Flash (High)" are both "gemini 3 6 flash"
74
75
  const DROP = new Set(['latest', 'preview', 'free', 'it', 'instruct', 'exp', 'chat'])
75
- export const words = (name) =>
76
- String(name)
76
+ const WORDS = new Map() // name → its words: thousands of models are matched against hundreds of entries, each parsed once
77
+ export const words = (name) => {
78
+ const k = String(name)
79
+ if (!WORDS.has(k)) WORDS.set(k, toWords(k))
80
+ return WORDS.get(k)
81
+ }
82
+ const toWords = (name) =>
83
+ name
77
84
  .toLowerCase()
78
85
  .replace(/\([^)]*\)/g, ' ')
79
86
  .replace(/^.*\//, '')
@@ -105,11 +112,11 @@ export function score(model, skills, data) {
105
112
  return each.every((x) => x == null) ? null : each.reduce((n, x) => n + (x ?? 1), 0) / each.length
106
113
  }
107
114
 
108
- // A model's place in one list ('text:coding'…), for showing: { rank, of, as } (as: its name there); null when not in it
115
+ // 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
109
116
  export function rankIn(model, key, data) {
110
117
  const list = data?.lists[key]
111
118
  const at = list?.filter((e) => place(model, [e]) != null)
112
119
  if (!at?.length) return null
113
120
  const best = at.reduce((a, b) => (b.rank < a.rank ? b : a))
114
- return { rank: best.rank, of: list.length, as: best.name }
121
+ return { rank: best.rank, of: list.length, as: best.name, score: best.score, votes: best.votes }
115
122
  }
package/src/research.js CHANGED
@@ -17,8 +17,9 @@ import fs from 'node:fs'
17
17
  import path from 'node:path'
18
18
  import { createHash } from 'node:crypto'
19
19
  import { keywords } from './memory.js'
20
+ import { projectDir } from './config.js'
20
21
 
21
- export const researchDir = (root) => path.join(root, '.heartcode', 'research')
22
+ export const researchDir = (root) => projectDir(root, 'research')
22
23
  const slugOf = (s, n) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, n).replace(/-+$/, '')
23
24
  const hash = (s) => createHash('sha256').update(String(s)).digest('hex').slice(0, 8)
24
25
  const today = () => new Date().toISOString().slice(0, 10)