heartcode 0.1.25 → 0.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,48 @@
1
+ // What each feature that leans on an outside tool, package or service needs, and whether it's here.
2
+ // One place so the settings page can gray a feature out and name what's missing, and /doctor can list
3
+ // the same in the CLI. Pure checks (looking on PATH and in a couple of app folders): no network.
4
+ // We only name what's needed — not how to install it, since that differs from one OS to the next.
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { voiceProblem } from './voice.js'
8
+
9
+ const onPath = (cmd) => (process.env.PATH ?? '').split(path.delimiter).some((d) => d && (fs.existsSync(path.join(d, cmd)) || fs.existsSync(path.join(d, cmd + '.exe'))))
10
+ const exists = (p) => {
11
+ try {
12
+ fs.accessSync(p)
13
+ return true
14
+ } catch {
15
+ return false
16
+ }
17
+ }
18
+ const chromeHere = () =>
19
+ onPath('google-chrome') ||
20
+ onPath('chromium') ||
21
+ onPath('chrome') ||
22
+ onPath('chrome.exe') ||
23
+ ['/Applications/Google Chrome.app', '/Applications/Chromium.app', '/Applications/Microsoft Edge.app', 'C:/Program Files/Google/Chrome/Application/chrome.exe'].some(exists)
24
+
25
+ // Each feature that needs something external: { id, name, what, ok, need }. `ok` false means the
26
+ // feature can't run as things are; `need` names what to install to make it work.
27
+ export function capabilities(cfg = {}) {
28
+ const caps = []
29
+ const vp = voiceProblem(cfg.voice ?? {}, cfg.providers ?? {})
30
+ let need = ''
31
+ if (vp) {
32
+ if (/ffmpeg/.test(vp)) need = 'ffmpeg, and a whisper model (or a transcription provider)'
33
+ else if (/whisper-cli/.test(vp)) need = 'whisper (whisper-cli) and a model — or a transcription provider'
34
+ else need = 'a whisper model — or a transcription provider'
35
+ }
36
+ caps.push({ id: 'voice', name: 'Voice input', what: 'Dictate your message — Space in an empty box, or /voice.', ok: !vp, need })
37
+ const chrome = chromeHere()
38
+ const npx = onPath('npx')
39
+ caps.push({
40
+ id: 'browser',
41
+ name: 'Browser preview & UI review',
42
+ what: 'HeartCode opens pages it builds in a real browser, reads the console and takes screenshots to check them.',
43
+ ok: chrome && npx,
44
+ need: !npx ? 'Node.js' : !chrome ? 'Google Chrome' : '',
45
+ })
46
+ caps.push({ id: 'git', name: 'Install skills from GitHub', what: '/install_skill and git-based imports clone a repo.', ok: onPath('git'), need: onPath('git') ? '' : 'git' })
47
+ return caps
48
+ }
package/src/client.js CHANGED
@@ -198,6 +198,17 @@ export class Client {
198
198
  log('rotate', `${why} → ${r.list[r.at].provider} · ${r.list[r.at].model}`)
199
199
  this.#use(r.list[r.at])
200
200
  }
201
+ // Jump straight to a particular model in the list — the caller found it has room the current one
202
+ // doesn't (the conversation outgrew this model's window), so move there instead of compacting.
203
+ // No-op (false) without a list, or if it's not in the list or already the one in use.
204
+ switchTo(target, why) {
205
+ const r = this.rotation
206
+ if (!r) return false
207
+ const i = r.list.indexOf(target)
208
+ if (i < 0 || i === r.at) return false
209
+ this.#next(why, () => i)
210
+ return true
211
+ }
201
212
  // Which model of the list to go on to after this one failed, for one request (tried: the places
202
213
  // tried, down: the providers that answered with an error, 400 or above). A provider that answered
203
214
  // with an error isn't asked again through its next model: the next one is from another provider.
@@ -455,8 +466,8 @@ export class Client {
455
466
  } else this.onRetry(e, 0, attempt + 1, this.target)
456
467
  continue
457
468
  }
458
- // a server error or no connection, again and again (not a rate limit, which is waited out)
459
- if (e.status !== 429 && tries >= 8) throw e
469
+ // a server error or no connection, again and again: waited out like a rate limit (the wait
470
+ // grows to a minute), until it comes back or Esc — never given up on
460
471
  const wait = Math.min(Number(e.retryAfter) * 1000 || this.retryBase * 2 ** (tries - 1), 60_000)
461
472
  log('retry', `attempt ${attempt + 1} failed, waiting ${wait}ms: ${e.message}`)
462
473
  this.onRetry(e, wait, attempt + 1)
@@ -567,7 +578,7 @@ export class Client {
567
578
  // Speed counts from the first streamed token (or the request, if not streaming) to the end.
568
579
  const count = (r) => {
569
580
  if (r.usage?.prompt_tokens) this.onUsage?.(r.usage.prompt_tokens, estMessages(req.messages) + est(JSON.stringify(req.tools ?? '')))
570
- this.lastTokens = r.usage?.total_tokens || estMessages(req.messages) + est(r.content + r.reasoning)
581
+ if ((this.purpose ?? 'chat') === 'chat') this.lastTokens = r.usage?.total_tokens || estMessages(req.messages) + est(r.content + r.reasoning) // the conversation's size: not a side request's (a review, the wrap-up, a lesson)
571
582
  const out = r.usage?.completion_tokens || est(r.content + r.reasoning + r.toolCalls.map((t) => t.function.arguments).join(''))
572
583
  this.onSpend?.(r.usage?.prompt_tokens || r.usage?.completion_tokens ? r.usage : { prompt_tokens: estMessages(req.messages), completion_tokens: out, estimated: true }) // usage and cost (usage.js)
573
584
  const ms = Date.now() - (firstAt ?? sent)
package/src/config.js CHANGED
@@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url'
6
6
  export const HOME = process.env.HEART_HOME || path.join(os.homedir(), '.heart')
7
7
  export const CONFIG_FILE = path.join(HOME, 'config.json')
8
8
 
9
- const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'log', 'logRequests', 'logDetail', 'logDays']
9
+ const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram']
10
10
  const LOCAL_NAMES = { 11434: 'ollama', 1234: 'lmstudio', 8080: 'llamacpp' }
11
11
 
12
12
  export function readJson(file, fallback) {
package/src/edit.js CHANGED
@@ -3,7 +3,7 @@
3
3
  const lead = (l) => /^\s*/.exec(l)[0]
4
4
  const key = (l) => l.trim().replace(/\s+/g, ' ')
5
5
 
6
- function trimBlank(lines) {
6
+ export function trimBlank(lines) {
7
7
  let a = 0
8
8
  let b = lines.length
9
9
  while (a < b && !lines[a].trim()) a++
@@ -27,7 +27,7 @@ export function applyEdit(text, search, replace) {
27
27
  if (sk.every((k, j) => key(lines[i + j]) === k)) hits.push(i)
28
28
  }
29
29
  if (hits.length > 1) return { error: `the SEARCH text matches ${hits.length} places; include more surrounding lines so it matches only one` }
30
- if (!hits.length) return { error: notFound(lines, sk) }
30
+ if (!hits.length) return { error: notFound(lines, s) }
31
31
 
32
32
  const i = hits[0]
33
33
  lines.splice(i, s.length, ...reindent(s, trimBlank(replace.split('\n')), lines.slice(i, i + s.length)))
@@ -46,17 +46,47 @@ export function reindent(seen, repl, orig = seen) {
46
46
  return repl.map((l) => (l.trim() && l.startsWith(from) ? to + l.slice(from.length) : l))
47
47
  }
48
48
 
49
- function notFound(lines, sk) {
50
- const words = new Set(sk.join(' ').split(/\W+/).filter((w) => w.length > 2))
49
+ // How alike two lines are, 0–1: 1 if equal ignoring whitespace, else the share of words in common
50
+ // (so a line the model got slightly wrong still counts). Blank-vs-blank is a full match.
51
+ const toks = (l) => l.split(/\W+/).filter(Boolean)
52
+ function sim(a, b) {
53
+ if (key(a) === key(b)) return 1
54
+ const ta = toks(a)
55
+ const tb = new Set(toks(b))
56
+ if (!ta.length) return 0
57
+ return ta.filter((t) => tb.has(t)).length / Math.max(ta.length, toks(b).length || 1)
58
+ }
59
+
60
+ // Where the search block most likely belongs: the window of its height whose lines are, in sum, most
61
+ // like the search lines (blank search lines don't count). -1 only if nothing overlaps at all.
62
+ export function closest(lines, s) {
63
+ const span = Math.min(s.length, lines.length)
64
+ if (!span) return -1
51
65
  let best = -1
52
66
  let score = 0
53
- lines.forEach((l, i) => {
54
- const sc = l.split(/\W+/).filter((w) => words.has(w)).length
67
+ for (let i = 0; i + span <= lines.length; i++) {
68
+ let sc = 0
69
+ for (let j = 0; j < span; j++) if (s[j].trim()) sc += sim(s[j], lines[i + j])
55
70
  if (sc > score) [best, score] = [i, sc]
56
- })
71
+ }
72
+ return score > 0 ? best : -1
73
+ }
74
+
75
+ // The not-found message, as a line-by-line diff of what the model sent (✗) against what the file
76
+ // actually has (✓) at the closest place — so it can see exactly which lines are off and copy them.
77
+ function notFound(lines, s) {
57
78
  const msg = 'the SEARCH text was not found in the file'
58
- if (best < 0) return msg
59
- return `${msg}. The closest lines are around line ${best + 1}:\n${lines.slice(Math.max(0, best - 2), best + 3).join('\n')}`
79
+ const at = closest(lines, s)
80
+ if (at < 0) return `${msg}. Read the file again (read_file) and copy the exact lines, or use write_file.`
81
+ const out = [`${msg}. The closest place is line ${at + 1} — your SEARCH (✗) against the file (✓); copy the ✓ lines exactly, whitespace included, or use write_file:`]
82
+ const n = Math.min(s.length, lines.length - at, 14)
83
+ for (let j = 0; j < n; j++) {
84
+ const have = lines[at + j]
85
+ const want = s[j] ?? ''
86
+ if (key(want) === key(have)) out.push(` ${have}`)
87
+ else out.push(`✗ you sent: ${want}`, `✓ file has: ${have}`)
88
+ }
89
+ return out.join('\n')
60
90
  }
61
91
 
62
92
  // Parses git-conflict-style blocks. Accepts 5-9 marker chars and missing SEARCH/REPLACE words; a
package/src/guided.js CHANGED
@@ -289,8 +289,13 @@ class Guided {
289
289
  repeats = sig === last ? repeats + 1 : 0
290
290
  last = sig
291
291
  if (repeats >= 2) {
292
- this.ui.warn(`stopped: ${this.s.client.model} did the same thing three times in a row`)
293
- break
292
+ // the next of your models carries on; with none, it goes on being told (only Esc stops it)
293
+ const was = this.s.client.model
294
+ if (this.s.client.moveOn?.(`${was} did the same thing three times in a row`)) this.ui.warn(`${was} did the same thing three times in a row; handing over to ${this.s.client.model}`)
295
+ else this.ui.warn(`${was} did the same thing three times in a row — it carries on, told so; Esc stops it`)
296
+ this.note(null, 'warning', prompt('guided/note-repeated'))
297
+ repeats = 0
298
+ continue
294
299
  }
295
300
  if (repeats === 1) this.note(null, 'warning', prompt('guided/note-repeated'))
296
301
  }
package/src/headless.js CHANGED
@@ -12,7 +12,7 @@
12
12
  // told to the model. Logs and warnings go to stderr (and HEART_LOG), never stdout.
13
13
  import readline from 'node:readline'
14
14
  import { log } from './log.js'
15
- import { clip, TOOL_DEFS, extraTools, loadMcpTools, failed as toolFailed } from './tools.js'
15
+ import { clip, TOOL_DEFS, extraTools, loadMcpTools, mcpName, failed as toolFailed } from './tools.js'
16
16
  import { allowed } from './agent.js'
17
17
 
18
18
  // Claude Code's tool names → HeartCode's (for --allowedTools / --disallowedTools).
@@ -119,6 +119,10 @@ export async function runHeadless(app, opts) {
119
119
  return e
120
120
  }
121
121
 
122
+ // An MCP call goes out as Claude Code sends one: the tool by its own name (mcp__server__tool) with
123
+ // its own arguments, not HeartCode's one mcp tool around them (a program reading it, Nibedita,
124
+ // knows its tools by those names).
125
+ const asClaude = (name, input) => (name === 'mcp' && input?.server && input?.tool ? { name: mcpName(String(input.server), String(input.tool)), input: input.arguments ?? {} } : { name, input })
122
126
  let said = false // the model's text was already sent as an assistant message
123
127
  if (out === 'stream-json') {
124
128
  s.onEvent = (e) => {
@@ -126,7 +130,7 @@ export async function runHeadless(app, opts) {
126
130
  const content = [
127
131
  ...(e.reasoning ? [{ type: 'thinking', thinking: e.reasoning }] : []),
128
132
  ...(e.content ? [{ type: 'text', text: e.content }] : []),
129
- ...e.toolCalls.map((t) => ({ type: 'tool_use', id: t.id, name: t.function.name, input: parseArgs(t.function.arguments) })),
133
+ ...e.toolCalls.map((t) => ({ type: 'tool_use', id: t.id, ...asClaude(t.function.name, parseArgs(t.function.arguments)) })),
130
134
  ]
131
135
  if (e.content && !e.parent) said = true
132
136
  // a helper's (agent) steps too, as Claude Code sends a subagent's: parent_tool_use_id is its agent call
@@ -136,7 +140,8 @@ export async function runHeadless(app, opts) {
136
140
  }
137
141
  }
138
142
  if (s.strat.actions === 'tools' && s.mcp?.names.length) await loadMcpTools(s) // their tools are in the list, as in Claude Code's
139
- const tools = s.strat.actions === 'tools' ? [...TOOL_DEFS, ...extraTools(s)].map((f) => f.name).filter((n) => allowed(s, n)) : []
143
+ // each MCP tool by its own name (mcp__server__tool), as Claude Code lists them; the model reaches them through its one mcp tool
144
+ const tools = s.strat.actions === 'tools' ? [...[...TOOL_DEFS, ...extraTools(s)].map((f) => f.name), ...(s.mcpDirect?.keys() ?? [])].filter((n) => allowed(s, n)) : []
140
145
  emit({ type: 'system', subtype: 'init', session_id, model, cwd: app.root, tools, mcp_servers: app.mcp.names.map((name) => ({ name, status: s.mcpCatalog?.has(name) ? 'connected' : 'pending' })), permissionMode: app.ui.permission, apiKeySource: 'none' })
141
146
  }
142
147
 
package/src/importer.js CHANGED
@@ -5,6 +5,7 @@
5
5
  import fs from 'node:fs'
6
6
  import os from 'node:os'
7
7
  import path from 'node:path'
8
+ import { spawnSync } from 'node:child_process'
8
9
  import { HOME, readJson, writeJson } from './config.js'
9
10
  import { frontMatter } from './skills.js'
10
11
  import { Memory } from './memory.js'
@@ -200,3 +201,101 @@ export function findImports(root, home = os.homedir()) {
200
201
  if (notes.length) add('Claude Code · this project · memory', `${notes.length} memory notes`, 'become HeartCode memory notes for this project', () => importClaudeMemory(root, claudeMemory))
201
202
  return items
202
203
  }
204
+
205
+ // Install a skill straight from a GitHub repo or a URL — not another CLI's config. Accepts
206
+ // "user/repo", a github repo URL, a .git URL, or a direct link to a SKILL.md / <name>.md (a
207
+ // one-file skill). Clones (git) or downloads a tarball, finds every SKILL.md, and copies each skill
208
+ // folder into the skills dir (global by default). Returns a short summary; nothing existing is
209
+ // overwritten. scope: "global" (~/.heart/skills) or "project" (.heartcode/skills).
210
+ export async function installSkill(root, source, scope = 'global', { signal } = {}) {
211
+ source = String(source ?? '').trim()
212
+ if (!source) throw new Error('give a GitHub repo (user/repo or its URL) or a link to a SKILL.md')
213
+ const dest = skillsDir(root, scope)
214
+ fs.mkdirSync(dest, { recursive: true })
215
+
216
+ // a single .md file → a one-file skill
217
+ if (/^https?:\/\/\S+\.md(\?\S*)?$/i.test(source)) {
218
+ const res = await fetch(source, { signal, redirect: 'follow' })
219
+ if (!res.ok) throw new Error(`could not download: HTTP ${res.status}`)
220
+ const text = await res.text()
221
+ const { meta } = frontMatter(text)
222
+ if (!meta.description) throw new Error('that .md is not a skill (it needs YAML frontmatter with a description)')
223
+ const name = safe(meta.name || source.split('/').pop().replace(/\.md.*$/i, '')) || 'skill'
224
+ if (taken(root, scope, name)) return `${name} is already installed`
225
+ fs.writeFileSync(path.join(dest, `${name}.md`), text)
226
+ return `installed skill ${name}`
227
+ }
228
+
229
+ // otherwise a repo
230
+ const { gitUrl, tarUrl } = repoUrls(source)
231
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'heart-skill-'))
232
+ try {
233
+ await fetchRepo(gitUrl, tarUrl, tmp, signal)
234
+ const found = findSkillFolders(tmp)
235
+ if (!found.length) throw new Error('no SKILL.md found in that repo')
236
+ const done = []
237
+ for (const { name, dir } of found) {
238
+ if (taken(root, scope, name)) {
239
+ done.push(`${name} (already installed)`)
240
+ continue
241
+ }
242
+ fs.cpSync(dir, path.join(dest, name), { recursive: true, filter: (s) => !/[/\\]\.git([/\\]|$)/.test(s) })
243
+ done.push(name)
244
+ }
245
+ return `installed ${done.filter((d) => !d.includes('already')).length} of ${found.length} skill${found.length === 1 ? '' : 's'}: ${done.join(', ')}`
246
+ } finally {
247
+ fs.rmSync(tmp, { recursive: true, force: true })
248
+ }
249
+ }
250
+
251
+ // "user/repo" or a github link → a clone URL and a codeload tarball URL (for when git isn't around).
252
+ function repoUrls(source) {
253
+ let m = /github\.com[/:]([^/]+)\/([^/#?]+?)(?:\.git)?(?:[/#?].*)?$/i.exec(source)
254
+ if (!m && /^[\w.-]+\/[\w.-]+$/.test(source)) m = [, ...source.split('/')]
255
+ if (m) return { gitUrl: `https://github.com/${m[1]}/${m[2]}.git`, tarUrl: `https://codeload.github.com/${m[1]}/${m[2]}/tar.gz/HEAD` }
256
+ if (/^https?:\/\/\S+/.test(source) || /\.git$/.test(source)) return { gitUrl: source.replace(/\/$/, ''), tarUrl: null }
257
+ throw new Error(`can't tell what "${source}" is — give a GitHub repo (user/repo or its URL) or a link to a SKILL.md`)
258
+ }
259
+
260
+ // Shallow git clone, or download and extract the tarball if git isn't installed.
261
+ async function fetchRepo(gitUrl, tarUrl, into, signal) {
262
+ const hasGit = spawnSync('git', ['--version'], { stdio: 'ignore' }).status === 0
263
+ if (hasGit) {
264
+ const r = spawnSync('git', ['clone', '--depth', '1', gitUrl, into], { encoding: 'utf8', timeout: 120_000 })
265
+ if (r.status === 0) return
266
+ if (!tarUrl) throw new Error(`git clone failed: ${(r.stderr || '').trim().slice(0, 200)}`)
267
+ } else if (!tarUrl) {
268
+ throw new Error('git is not installed; install git, or give a GitHub repo so the tarball can be downloaded')
269
+ }
270
+ const res = await fetch(tarUrl, { signal, redirect: 'follow' })
271
+ if (!res.ok) throw new Error(`could not download the repo: HTTP ${res.status}`)
272
+ fs.writeFileSync(path.join(into, '_repo.tgz'), Buffer.from(await res.arrayBuffer()))
273
+ const r = spawnSync('tar', ['-xzf', '_repo.tgz', '--strip-components=1'], { cwd: into, encoding: 'utf8' })
274
+ fs.rmSync(path.join(into, '_repo.tgz'), { force: true })
275
+ if (r.status !== 0) throw new Error(`could not extract the repo: ${(r.stderr || '').trim().slice(0, 200)}`)
276
+ }
277
+
278
+ // Every SKILL.md in the tree (depth-limited) as { name, dir }; doesn't descend into a skill folder.
279
+ // A skill at the repo root is named from its frontmatter; a nested one from its folder.
280
+ function findSkillFolders(base, depth = 4) {
281
+ const out = []
282
+ const walk = (d, left) => {
283
+ let entries = []
284
+ try {
285
+ entries = fs.readdirSync(d, { withFileTypes: true })
286
+ } catch {
287
+ return
288
+ }
289
+ if (entries.some((e) => e.isFile() && e.name === 'SKILL.md')) {
290
+ const { meta } = frontMatter(fs.readFileSync(path.join(d, 'SKILL.md'), 'utf8'))
291
+ const name = safe((d === base ? meta.name : path.basename(d)) || meta.name || path.basename(d)) || 'skill'
292
+ out.push({ name, dir: d })
293
+ if (left > 0 && entries.some((e) => e.isDirectory() && e.name === 'skills')) walk(path.join(d, 'skills'), left - 1) // a repo that's one skill plus a skills/ collection
294
+ return
295
+ }
296
+ if (left <= 0) return
297
+ for (const e of entries) if (e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules') walk(path.join(d, e.name), left - 1)
298
+ }
299
+ walk(base, depth)
300
+ return out
301
+ }
package/src/mcp.js CHANGED
@@ -17,7 +17,7 @@ import path from 'node:path'
17
17
  import { pathToFileURL } from 'node:url'
18
18
  import { HOME, readJson, readConfig, writeJson, VERSION } from './config.js'
19
19
  import { log } from './log.js'
20
- import { savedToken, signIn } from './oauth.js'
20
+ import { savedToken, signIn, hasToken } from './oauth.js'
21
21
 
22
22
  // Built in; a config entry with the same name changes it, "disabled": true turns it off.
23
23
  export const DEFAULT_SERVERS = {
@@ -31,11 +31,20 @@ export const DEFAULT_SERVERS = {
31
31
  scratchCwd: true,
32
32
  description: 'a Chrome browser: open pages, click, fill forms, read the console and network requests, take screenshots',
33
33
  },
34
+ 'computer-use': {
35
+ command: 'npx',
36
+ args: ['-y', '@zavora-ai/computer-use-mcp@latest'],
37
+ // Off until you switch it on (/settings → MCP servers, or /mcp): it controls your whole desktop.
38
+ // Needs the OS's permission (macOS: Screen Recording + Accessibility for your terminal) and a
39
+ // vision model that's good at computer use — a weak model won't drive it well.
40
+ disabled: true,
41
+ description: 'control your computer like a person — screenshots, mouse, keyboard, clipboard (off by default; needs screen/accessibility permission and a capable vision model)',
42
+ },
34
43
  }
35
44
 
36
45
  // extra: more configs from the caller (--mcp-config: a file path or JSON text); strict: only those
37
46
  // (no built-in or configured servers), like Claude Code's --strict-mcp-config.
38
- export function loadServers(root, { extra = [], strict = false } = {}) {
47
+ export function loadServers(root, { extra = [], strict = false, includeDisabled = false } = {}) {
39
48
  const merged = strict ? {} : structuredClone(DEFAULT_SERVERS) // yours (below) win on a name
40
49
  const own = strict ? [] : [path.join(HOME, 'mcp.json'), root && path.join(root, '.heartcode', 'mcp.json')].filter(Boolean).map((f) => readConfig(f, {}))
41
50
  const given = extra.map((c) => {
@@ -46,11 +55,20 @@ export function loadServers(root, { extra = [], strict = false } = {}) {
46
55
  for (const data of [...own, ...given]) {
47
56
  for (const [name, cfg] of Object.entries(data.mcpServers ?? {})) merged[name] = { ...merged[name], ...cfg }
48
57
  }
49
- return Object.fromEntries(Object.entries(merged).filter(([, cfg]) => (cfg.command || cfg.url) && !cfg.disabled))
58
+ return Object.fromEntries(Object.entries(merged).filter(([, cfg]) => (cfg.command || cfg.url) && (includeDisabled || !cfg.disabled)))
50
59
  }
51
60
 
52
61
  const expand = (v) => String(v).replace(/\$\{(\w+)\}/g, (m, k) => process.env[k] ?? '')
53
62
 
63
+ // A server's sign-in status, for listings: 'local' (a command, no sign-in), 'in' (remote, a token is
64
+ // saved), or 'out' (remote, not signed in — may need it). A server with its own headers/token in the
65
+ // config counts as 'in' (it authenticates itself).
66
+ export function mcpAuth(cfg) {
67
+ if (!cfg?.url) return 'local'
68
+ if (cfg.headers && Object.keys(cfg.headers).length) return 'in'
69
+ return hasToken(expand(cfg.url)) ? 'in' : 'out'
70
+ }
71
+
54
72
  // A server's server-sent events: { event, data }.
55
73
  async function* sseEvents(body) {
56
74
  const dec = new TextDecoder()
package/src/memory.js CHANGED
@@ -26,7 +26,11 @@ export const fullSlug = (s) =>
26
26
  .replace(/\.md$/, '')
27
27
  .replace(/[^a-z0-9]+/g, '-')
28
28
  .replace(/^-+|-+$/g, '')
29
- export const slug = (s) => fullSlug(s).slice(0, 60) || 'note'
29
+ // cut at a word's end, not in the middle of one ("…-and-use-an-abso")
30
+ export const slug = (s) => {
31
+ const f = fullSlug(s)
32
+ return (f.length <= 60 ? f : f.slice(0, 61).replace(/-[^-]*$/, '').slice(0, 60)) || 'note'
33
+ }
30
34
 
31
35
  // One folder of notes.
32
36
  class Notes {
@@ -215,7 +219,7 @@ const tagList = (v) => (Array.isArray(v) ? v : String(v ?? '').split(/[,\s#]+/))
215
219
 
216
220
  // Words worth matching on: lowercased, without short or very common words, plural/-ing cut off.
217
221
  const STOP = new Set('the and for with this that from have what when where which into your you our are was were can will should could would about there their them then than just also only some more most very please make like want need does doing done how why who its it\'s use using'.split(' '))
218
- function keywords(text) {
222
+ export function keywords(text) {
219
223
  return String(text)
220
224
  .toLowerCase()
221
225
  .split(/[^a-z0-9]+/)
package/src/oauth.js CHANGED
@@ -13,6 +13,9 @@ const FILE = path.join(HOME, 'mcp-auth.json')
13
13
  const b64url = (buf) => Buffer.from(buf).toString('base64url')
14
14
  const store = () => readJson(FILE, {})
15
15
  const keep = (url, entry) => writeJson(FILE, { ...store(), [url]: entry })
16
+ // Whether a sign-in token is already saved for this server's URL (cheap, no network). Doesn't prove
17
+ // the token still works or that the server even needs auth — just whether we've signed in before.
18
+ export const hasToken = (url) => Boolean(store()[url]?.accessToken)
16
19
  export const forget = (url) => {
17
20
  const all = store()
18
21
  delete all[url]
@@ -0,0 +1,142 @@
1
+ // Research: every web page and search HeartCode reads for a project, kept in
2
+ // <project>/.heartcode/research/ as Markdown (one file per page, the whole page), so nothing it looked
3
+ // up is lost: helpers' pages too. The same URL always maps to the same file (fetched again: replaced).
4
+ // ---
5
+ // url: https://…
6
+ // title: …
7
+ // fetched: 2026-10-31
8
+ // query: what it was looking for
9
+ // used_for: what it turned out to be used for (set when the task wraps up)
10
+ // ---
11
+ // # Title
12
+ // the page as Markdown
13
+ // INDEX.md lists them for people (and Obsidian); the model is given matching titles with each message
14
+ // and reads a file when it needs the detail. The folder ignores itself in git (raw pages can be big;
15
+ // the notes they lead to in .heartcode/memory are what's worth committing).
16
+ import fs from 'node:fs'
17
+ import path from 'node:path'
18
+ import { createHash } from 'node:crypto'
19
+ import { keywords } from './memory.js'
20
+
21
+ export const researchDir = (root) => path.join(root, '.heartcode', 'research')
22
+ const slugOf = (s, n) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, n).replace(/-+$/, '')
23
+ const hash = (s) => createHash('sha256').update(String(s)).digest('hex').slice(0, 8)
24
+ const today = () => new Date().toISOString().slice(0, 10)
25
+ const oneLine = (s) => String(s ?? '').replace(/\s+/g, ' ').trim()
26
+
27
+ // The file a page is kept in: its address, readable ("react.dev--learn-start-a-new-react-project.md").
28
+ export function pageFile(url) {
29
+ let host = 'page'
30
+ let rest = String(url)
31
+ try {
32
+ const u = new URL(url)
33
+ host = u.hostname.replace(/^www\./, '')
34
+ rest = u.pathname + u.search
35
+ } catch {}
36
+ const name = `${host.toLowerCase().replace(/[^a-z0-9.]+/g, '-').slice(0, 60) || 'page'}--${slugOf(rest, 200) || 'index'}`
37
+ return `${name.length > 110 ? `${name.slice(0, 100).replace(/-+$/, '')}-${hash(url)}` : name}.md`
38
+ }
39
+ const searchFile = (query) => `search--${slugOf(query, 90) || hash(query)}.md`
40
+
41
+ function write(root, file, meta, body) {
42
+ const dir = researchDir(root)
43
+ fs.mkdirSync(dir, { recursive: true })
44
+ const ignore = path.join(dir, '.gitignore')
45
+ if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, '# HeartCode research: raw pages, kept out of git (the notes in ../memory are what to commit)\n*\n')
46
+ const head = Object.entries(meta)
47
+ .filter(([, v]) => v !== undefined && v !== '')
48
+ .map(([k, v]) => `${k}: ${oneLine(v)}`)
49
+ fs.writeFileSync(path.join(dir, file), `---\n${head.join('\n')}\n---\n\n${String(body).trim()}\n`)
50
+ rebuildIndex(root)
51
+ return { file: path.relative(root, path.join(dir, file)), bodyLine: head.length + 4 } // bodyLine: the page's first line in the file
52
+ }
53
+
54
+ // A fetched page (text: as Markdown). Returns { file (relative to the project), bodyLine }.
55
+ export function savePage(root, { url, title, text, query }) {
56
+ const file = pageFile(url)
57
+ const was = read(root, file)
58
+ return write(root, file, { url, title: title || url, fetched: today(), query: query || was?.query, used_for: was?.used_for }, text)
59
+ }
60
+
61
+ // A search's results (text: as the model was given them).
62
+ export function saveSearch(root, query, text) {
63
+ return write(root, searchFile(query), { kind: 'search', title: `Search: ${query}`, query, fetched: today() }, text)
64
+ }
65
+
66
+ function parse(root, name) {
67
+ const abs = path.join(researchDir(root), name)
68
+ let text
69
+ try {
70
+ text = fs.readFileSync(abs, 'utf8')
71
+ } catch {
72
+ return null
73
+ }
74
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text)
75
+ const meta = Object.fromEntries((m?.[1] ?? '').split('\n').map((l) => /^(\w+):\s*(.*)$/.exec(l.trim())).filter(Boolean).map(([, k, v]) => [k, v.trim()]))
76
+ return { ...meta, name, file: path.relative(root, abs), kind: meta.kind || 'page', size: text.length }
77
+ }
78
+ const read = (root, name) => parse(root, name)
79
+
80
+ // Every saved page and search: { name, file, url, title, fetched, query, used_for, kind, size }, newest first.
81
+ export function listResearch(root) {
82
+ let names = []
83
+ try {
84
+ names = fs.readdirSync(researchDir(root)).filter((f) => f.endsWith('.md') && f !== 'INDEX.md')
85
+ } catch {}
86
+ return names
87
+ .map((n) => parse(root, n))
88
+ .filter(Boolean)
89
+ .sort((a, b) => String(b.fetched).localeCompare(String(a.fetched)) || a.name.localeCompare(b.name))
90
+ }
91
+
92
+ // Saved research that matches a text (a task, a search query): pages first, the best matches first.
93
+ // A word in the title, the query that found it or what it was used for counts most; in the address, less.
94
+ export function findResearch(root, text, max = 6) {
95
+ const words = new Set(keywords(text))
96
+ if (!words.size) return []
97
+ return listResearch(root)
98
+ .map((r) => {
99
+ let score = 0
100
+ for (const w of new Set([...keywords(r.title), ...keywords(r.query), ...keywords(r.used_for)])) if (words.has(w)) score += 2
101
+ for (const w of new Set(keywords(r.url))) if (words.has(w)) score += 1
102
+ return { r, score: score - (r.kind === 'search' ? 1 : 0) }
103
+ })
104
+ .filter((x) => x.score >= 3)
105
+ .sort((a, b) => b.score - a.score)
106
+ .slice(0, max)
107
+ .map((x) => x.r)
108
+ }
109
+
110
+ // The file a model names: its name, or its path in the project ("…/research/x.md").
111
+ const nameOf = (file) => path.basename(String(file ?? '').trim())
112
+
113
+ // Kept: what it was used for goes in its header (and the index).
114
+ export function markUsed(root, file, usedFor) {
115
+ const r = read(root, nameOf(file))
116
+ if (!r) return false
117
+ const abs = path.join(researchDir(root), r.name)
118
+ const text = fs.readFileSync(abs, 'utf8')
119
+ const body = text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '')
120
+ const { name, file: _f, size, ...meta } = r
121
+ write(root, r.name, { ...meta, used_for: usedFor || meta.used_for || 'yes' }, body)
122
+ return true
123
+ }
124
+
125
+ export function removeResearch(root, file) {
126
+ const r = read(root, nameOf(file))
127
+ if (!r) return false
128
+ fs.rmSync(path.join(researchDir(root), r.name), { force: true })
129
+ rebuildIndex(root)
130
+ return true
131
+ }
132
+
133
+ function rebuildIndex(root) {
134
+ const all = listResearch(root)
135
+ const line = (r) => `- ${r.fetched ?? ''} · [${r.title || r.name}](${r.name})${r.url ? ` · ${r.url}` : ''}${r.used_for ? ` · used for: ${r.used_for}` : ''}`
136
+ const pages = all.filter((r) => r.kind !== 'search')
137
+ const searches = all.filter((r) => r.kind === 'search')
138
+ fs.writeFileSync(
139
+ path.join(researchDir(root), 'INDEX.md'),
140
+ `# Research\n\nWhat HeartCode read on the web for this project, newest first. Each page is kept whole in its file; the notes it led to are in ../memory.\n\n## Pages\n\n${pages.map(line).join('\n') || '(none yet)'}\n\n## Searches\n\n${searches.map(line).join('\n') || '(none yet)'}\n`,
141
+ )
142
+ }
package/src/sessions.js CHANGED
@@ -18,7 +18,10 @@ export function newChat(root) {
18
18
  export function saveChat(chat) {
19
19
  const file = path.join(DIR, `${chat.id}.json`)
20
20
  const first = chat.turns[0] ?? chat.branches?.[0]?.state.turns[0] // gone back to the start: its branches remain
21
- if (!first) return fs.rmSync(file, { force: true }) // nothing (left) worth keeping
21
+ if (!first) {
22
+ fs.rmSync(path.join(HOME, 'outputs', chat.id), { recursive: true, force: true }) // its saved tool output goes with it
23
+ return fs.rmSync(file, { force: true }) // nothing (left) worth keeping
24
+ }
22
25
  chat.updated = new Date().toISOString()
23
26
  chat.title = chat.name || first.task.split('\n')[0].slice(0, 80) // its name (/rename), else the first message, even after a rewind
24
27
  writeJson(file, chat)