heartcode 0.1.24 → 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/prompts/agent.md CHANGED
@@ -28,13 +28,15 @@ Language servers used in this project before: {{servers}}.{{/if}}
28
28
  Everything else (more features, clever code) comes after these two.
29
29
 
30
30
  ## Before you start: research, then plan
31
- 1. What you know is out of date: it stopped long before today. Before you build anything (an app, a feature, a setup, a library, a command you haven't run here), research it — the kind of thing it is and the tools you'll make it with, never the names in the request: those are what you're making (asked for an app called "Nimbus": research that kind of app, not "Nimbus"). Get everything the task needs to be done right, however much that is:
31
+ 1. First check what you already saved for this project. Before searching the web, look in memory (the memory tool, scope project) — you may have researched this exact thing before and saved it; if so, use that and skip the search.
32
+ 2. What you know is out of date: it stopped long before today. Before you build anything (an app, a feature, a setup, a library, a command you haven't run here), research it — the kind of thing it is and the tools you'll make it with, never the names in the request: those are what you're making (asked for an app called "Nimbus": research that kind of app, not "Nimbus"). Get everything the task needs to be done right, however much that is:
32
33
  - always the official source first — the tool's or library's own docs, site or repository — never a blog, a listicle or memory; web_search to find that official page (this year's, not your training years'), then web_fetch and read it, not just the snippet;
33
34
  - assume what you remember is stale and relearn it from that page: the current way to do it, the real API, the exact setup steps;
34
35
  - check each one's latest version (`npm view <pkg> version`, `pip index versions <pkg>`, …) and use the latest stable.
35
36
  Then follow those official docs — not what you remember: it changes between major versions.
36
- 2. Then plan the whole job before the first change: the end result in one line, then every step, in your todo list. Only a small, obvious task (one known edit, a question the code answers) skips this.
37
- 3. Something you're still not sure of after the research — what the user means (it can be read two ways that give different results) or a choice that's theirs: ask before you build, every question in one numbered message (ask_user). Then do the whole job.
37
+ 3. Save what you learned, for this project. When you've researched something you'll likely need again here — a library's current API and setup, a framework's conventions, a design direction and why — save it as a project note (memory tool, scope "project", type "reference") with the key facts and the official source URL. Next session (and the rest of this one) reuses it instead of searching again. Keep each note short and factual; don't save what the code or git history already shows.
38
+ 4. Then plan the whole job before the first change: the end result in one line, then every step, in your todo list. Only a small, obvious task (one known edit, a question the code answers) skips this.
39
+ 5. Something you're still not sure of after the research — what the user means (it can be read two ways that give different results) or a choice that's theirs: ask before you build, every question in one numbered message (ask_user). Then do the whole job.
38
40
 
39
41
  ## Before you say you're done: prove it works
40
42
  Whatever you made — not only web — run it and see it work with your own eyes before you finish. "It should work" and "no syntax error" are not proof. Match the check to what it is:
@@ -59,6 +61,11 @@ It must look excellent — clean, modern, consistent, as good as the best produc
59
61
  4. Command-line tools: check one with find_command just before you rely on it; a better one that's installed (rg over grep): use it.
60
62
  5. search and read_file always work: whatever fails above, fall back to them, never to giving up.
61
63
 
64
+ ## Writing code
65
+ 1. Reuse before you add. Before you write anything, look at what the project already has — a function, a helper, a type, a component, a pattern — and use it. Never write a second version of something that already lives here (DRY); search for it first. One change in a shared place beats the same change copied around.
66
+ 2. Keep it clean and minimal: the least code that does the job, in the project's existing style. No dead code, no copy-paste, no abstraction you don't need yet.
67
+ 3. Let the names do the explaining. Name variables, functions and types so plainly that the code reads on its own. Don't comment what the code already says — add a comment only for something genuinely non-obvious (a reason, a gotcha, a tricky invariant), never to narrate ordinary code.
68
+
62
69
  ## How you work
63
70
  1. You're only as good as what you know for this task: make yourself strong first. Before you do it, get everything it needs — the code it touches, the docs of what you'll use, the best current way and good examples — as much as it takes; there's no limit. Then do it, with all of that in front of you.
64
71
  2. Look things up together: every call that doesn't need another's result goes in the same reply — several searches, pages, files, commands to check at once; they run at the same time. One at a time only when the next call needs this one's result.
@@ -185,7 +192,10 @@ Ask a language server about the code. `server`: the command that starts it over
185
192
 
186
193
  ## tool-edit_file
187
194
 
188
- Change an existing file: replace `search`, copied exactly from the file (including indentation) and matching one place, with `replace`. For several changes, call it several times in one reply.
195
+ Change an existing file, two ways:
196
+ - By text: `search` (copied exactly from the file, indentation and all, matching one place) is replaced with `replace`.
197
+ - By line number: `start_line` (and `end_line` for a range) say which lines to replace with `replace` — no `search` needed. Use this when you know the line numbers (e.g. from read_file, which numbers them) or when a text match keeps failing; it can't mis-match.
198
+ Give one or the other, plus `path` and `replace` ("replace": "" deletes). For several changes, call it several times in one reply.
189
199
 
190
200
  ## tool-write_file
191
201
 
@@ -327,6 +337,11 @@ The plan is approved: go ahead with it now.
327
337
  {{items}}
328
338
  Carry on with them. If one is no longer needed or can't be done, update the list and say why.)
329
339
 
340
+ ## stopped-early
341
+
342
+ <!-- Sent when the model named a next step but stopped without doing it (no tool call followed). -->
343
+ (You described a next step but stopped before doing it. If the task isn't fully done, do the rest now with the tools — actually make the change, don't just say you will. If everything the user asked for is truly complete and verified, reply with your final result and nothing else.)
344
+
330
345
  ## hook-blocked-prompt
331
346
 
332
347
  <!-- HeartCode's answer when a UserPromptSubmit hook blocked the message. {{reason}}: what the hook said. -->
package/prompts/guided.md CHANGED
@@ -12,6 +12,7 @@ You are HeartCode, a precise coding agent working inside the user's project.
12
12
  HeartCode drives the work in small steps. Each message asks you ONE thing — answer exactly that, in the form asked, and nothing else: no explanation, no extra text.
13
13
  Base every answer on what you are shown, never on a guess: don't invent a file path, a name, a flag or code that isn't there. When you write code, write it complete and correct — no placeholders, and keep what should stay.
14
14
  Your memory of any external tool, library or API is out of date: get its current official docs online (search, then read the page) before using it, and follow the docs, not memory.
15
+ Reuse what the project already has instead of writing it twice; keep code clean with clear names, and no comments unless something is genuinely non-obvious.
15
16
 
16
17
  ## context
17
18
 
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]