heartcode 0.1.25 → 0.1.27

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/agent.js CHANGED
@@ -666,7 +666,8 @@ async function runNative(s, task, images, signal) {
666
666
  s.uiErrorsPrev = [] // hard errors from the last look: when one is gone next look, it was fixed — learn from it
667
667
  s.runFails = new Map() // a command that failed (by its tool) → its error; when the same tool runs clean after an edit, that's a verified fix to learn from (any language, not just web)
668
668
  s.edits = 0 // successful file edits so far this message (to tell a real fix from a lucky rerun)
669
- let nudged = 0 // reminders sent this message about open todo items or a Stop hook
669
+ s.acted = false // used a tool this message (so a reply that only promises more is a premature stop)
670
+ let nudged = 0 // reminders sent this message about open todo items, a premature stop, or a Stop hook
670
671
 
671
672
  let empty = 0 // replies in a row with neither text nor tool calls
672
673
  let looping = 0 // replies cut for going into a loop, this message
@@ -773,6 +774,7 @@ async function runNative(s, task, images, signal) {
773
774
  res.content = res.content.slice(0, markup.index).trim()
774
775
  s.messages[s.messages.length - 1] = { ...s.messages.at(-1), content: res.content }
775
776
  }
777
+ if (res.toolCalls.length) s.acted = true // did real work this message, for the premature-stop check
776
778
  s.onEvent?.({ type: 'assistant', model: `${client.provider}/${client.model}`, content: res.content, reasoning: res.reasoning, toolCalls: res.toolCalls }) // headless output
777
779
  if (!res.toolCalls.length && !res.content?.trim()) {
778
780
  // Nothing at all (seen after a failed tool call): not an answer. The same request again
@@ -801,7 +803,7 @@ async function runNative(s, task, images, signal) {
801
803
  s.messages.push({ role: 'user', content: look })
802
804
  continue
803
805
  }
804
- const more = nudged < 3 && !s.isSub && (await notDone(s, signal, nudged > 0))
806
+ const more = nudged < 3 && !s.isSub && (await notDone(s, signal, nudged > 0, res.content))
805
807
  if (!more) return res.content
806
808
  nudged++
807
809
  s.messages.push({ role: 'user', content: more })
@@ -1181,12 +1183,23 @@ async function lookAtUi(s, signal) {
1181
1183
  // The model says it's done: is it? Not while its todo list (from this message) has open items, or
1182
1184
  // while a Stop hook says otherwise. Returns what to tell it, or null. Each is asked a few times at
1183
1185
  // most (the caller counts), so a model that can't finish still ends.
1184
- async function notDone(s, signal, again) {
1186
+ // The model said it would do something but stopped without doing it ("let me rewrite…", "I'll fix…"):
1187
+ // a next action named, then no tool call. Not matched by explanations ("let me explain", "you can run").
1188
+ const PROMISED_MORE =
1189
+ /\b(?:let me|i'?ll|i will|i'?m going to|i am going to|i need to|i'?m about to|next,? i'?ll|now,? i'?ll)\b[^.!?\n]{0,70}\b(?:do|make|create|add|fix|write|update|change|implement|build|run|rewrite|replace|edit|install|set ?up|finish|continue|proceed|start|redo|retry|try)\b/i
1190
+
1191
+ // Is the task really done, or did the model stop early? Open todo items, or (after it did real work)
1192
+ // a reply that only promises more, get one nudge to keep going. Then any Stop hook. null = truly done.
1193
+ async function notDone(s, signal, again, reply = '') {
1185
1194
  const open = s.todoTouched && s.ui.permission !== 'plan' ? (s.chat.todos ?? []).filter((t) => t.status !== 'completed') : [] // plan mode: they wait for the approval
1186
1195
  if (open.length) {
1187
1196
  log('task', `stopped with ${open.length} open todo item(s); reminding`)
1188
1197
  return prompt('agent/todo-unfinished', { items: open.map((t) => `- ${t.content}`).join('\n') })
1189
1198
  }
1199
+ if (s.acted && reply && PROMISED_MORE.test(reply)) {
1200
+ log('task', 'reply names a next step but no tool call followed; nudging to finish')
1201
+ return prompt('agent/stopped-early')
1202
+ }
1190
1203
  const hook = await runHooks(s, 'Stop', { stop_hook_active: again }, signal)
1191
1204
  return hook.block ? prompt('agent/hook-stop', { reason: hook.block }) : null
1192
1205
  }
@@ -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/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']
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/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/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]