heartcode 0.1.37 → 0.1.41

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/background.js CHANGED
@@ -1,7 +1,8 @@
1
- // Commands that keep running (a dev server, a watcher, a long build): run_command with background
2
- // true starts one and answers after a few seconds with what it printed so far; the background tool
3
- // (and /background) reads what it printed since, lists them, stops one. Each runs in its own process
4
- // group, its output going to a file; all of them are stopped when HeartCode exits.
1
+ // Every command run_command runs: started here, waited on for as long as the model chose, and if
2
+ // it's still running then, it carries on in the background (nothing ever blocks HeartCode); the
3
+ // background tool (and /background) reads what it printed since, waits on it, lists them, stops
4
+ // one. Each runs in its own process group, its output going to a file; all of them are stopped when
5
+ // HeartCode exits.
5
6
  import fs from 'node:fs'
6
7
  import path from 'node:path'
7
8
  import { spawn } from 'node:child_process'
@@ -23,22 +24,35 @@ const kill = (job, sig) => {
23
24
  }
24
25
  }
25
26
 
26
- // Started, and after `wait` ms: { job, output } (what it printed so far).
27
- export async function startJob(root, command, { wait = 3000 } = {}) {
27
+ // Started (it runs on; waitFor waits on it).
28
+ export function startJob(root, command) {
28
29
  fs.mkdirSync(DIR, { recursive: true })
29
30
  const id = ++made
30
31
  const file = path.join(DIR, `${process.pid}-${id}.log`)
31
32
  const fd = fs.openSync(file, 'w')
32
- const child = spawn(command, { cwd: root, shell: true, detached: group, stdio: ['ignore', fd, fd], env: { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1' } })
33
+ const child = spawn(command, { cwd: root, shell: true, detached: group, stdio: ['ignore', fd, fd], env: { ...process.env, CI: '1', FORCE_COLOR: '0', NO_COLOR: '1' } })
33
34
  fs.closeSync(fd)
34
35
  const job = { id, command, root, pid: child.pid, file, started: Date.now(), code: null, read: 0, exited: false, told: false }
35
36
  jobs.set(id, job)
36
- child.on('error', (e) => fs.appendFileSync(file, `\n${e.message}\n`))
37
- child.on('exit', (code, sig) => Object.assign(job, { code: code ?? sig, exited: true, ended: Date.now() }))
37
+ job.over = new Promise((r) => {
38
+ const end = (code) => r(Object.assign(job, { code, exited: true, ended: Date.now() }))
39
+ child.on('error', (e) => (fs.appendFileSync(file, `\n${e.message}\n`), end('error')))
40
+ child.on('exit', (code, sig) => end(code ?? sig))
41
+ })
38
42
  child.unref()
39
43
  log('background', `#${id} started: ${command} (pid ${child.pid})`)
40
- await new Promise((r) => setTimeout(r, wait))
41
- return { job, output: newOutput(job) }
44
+ return job
45
+ }
46
+
47
+ // Until it exits, `ms` pass or `signal` aborts, whichever comes first.
48
+ export function waitFor(job, ms, signal) {
49
+ if (job.exited || signal?.aborted) return Promise.resolve()
50
+ return new Promise((r) => {
51
+ const done = () => (clearTimeout(t), signal?.removeEventListener('abort', done), r())
52
+ const t = setTimeout(done, ms)
53
+ job.over.then(done)
54
+ signal?.addEventListener('abort', done, { once: true })
55
+ })
42
56
  }
43
57
 
44
58
  // What it printed since the last look (the last `most` characters of it).
@@ -69,16 +83,29 @@ export function tailLines(job, n) {
69
83
 
70
84
  export const listJobs = (root) => [...jobs.values()].filter((j) => !root || j.root === root)
71
85
  export const getJob = (id) => jobs.get(Number(String(id).replace(/^#/, '')))
72
- export const runningJobs = (root) => listJobs(root).filter((j) => !j.exited)
86
+ // what a command left running has no exit to wait for: it's looked at (gone: marked so)
87
+ const settle = (j) => j.left && !j.exited && !kill(j, 0) && Object.assign(j, { exited: true, code: 'gone', ended: Date.now() })
88
+ export const runningJobs = (root) => listJobs(root).filter((j) => (settle(j), !j.exited))
73
89
 
74
90
  export function stopJob(job) {
75
91
  if (job.exited) return false
76
92
  kill(job, 'SIGTERM')
77
93
  setTimeout(() => kill(job, 'SIGKILL'), 2000).unref()
94
+ if (job.left) Object.assign(job, { exited: true, code: 'SIGTERM', ended: Date.now() }) // what a command left running: its shell's exit was long ago, so marked here
78
95
  log('background', `#${job.id} stopped: ${job.command}`)
79
96
  return true
80
97
  }
81
98
 
99
+ // A command that ended but left processes running (`server &`, `nohup … &`): they're kept, as this
100
+ // background command (listed, stoppable, stopped when HeartCode exits), not killed — killing them
101
+ // left a model starting server after server. True when there were some.
102
+ export function keepLeftovers(job) {
103
+ if (!job.exited || !group || !kill(job, 0)) return false
104
+ Object.assign(job, { exited: false, code: null, left: true })
105
+ log('background', `#${job.id} left processes running: kept (${job.command})`)
106
+ return true
107
+ }
108
+
82
109
  // Stopped (if it still runs) and taken off the list; its log file stays.
83
110
  export function removeJob(job) {
84
111
  stopJob(job)
@@ -38,8 +38,8 @@ export function capabilities(cfg = {}) {
38
38
  const npx = onPath('npx')
39
39
  caps.push({
40
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.',
41
+ name: 'Browser',
42
+ what: 'The browser tools: the model opens a page in a real browser, uses it, reads the console and takes screenshots.',
43
43
  ok: chrome && npx,
44
44
  need: !npx ? 'Node.js' : !chrome ? 'Google Chrome' : '',
45
45
  })
package/src/client.js CHANGED
@@ -134,7 +134,8 @@ export function fitFor(messages, can, model) {
134
134
  const { tool_calls, ...rest } = x
135
135
  return { ...rest, content: [x.content, ...tool_calls.map((c) => `(called ${c.function.name} ${c.function.arguments || '{}'})`)].filter(Boolean).join('\n') }
136
136
  }
137
- if (x.tool_calls) x.tool_calls = x.tool_calls.map((c) => ({ ...c, id: callId(c.id), function: { ...c.function, arguments: asJson(c.function.arguments) } }))
137
+ const own = !writtenBy.has(m) || writtenBy.get(m) === model // extra_content (Gemini's thought_signature) only back to its writer: others refuse it (Mistral: 422 extra_forbidden)
138
+ if (x.tool_calls) x.tool_calls = x.tool_calls.map(({ extra_content, ...c }) => ({ ...c, ...(own && extra_content && { extra_content }), id: callId(c.id), function: { ...c.function, arguments: asJson(c.function.arguments) } }))
138
139
  if (x.role === 'tool') x.tool_call_id = callId(x.tool_call_id)
139
140
  return x
140
141
  })
@@ -157,6 +158,9 @@ export class Client {
157
158
  // how long a streamed reply may go without sending anything before it counts as stalled (then
158
159
  // tried again, or the next model asked); a reply that keeps coming has no limit, however long
159
160
  this.idleMs = 150_000
161
+ // how long a streamed reply may take to start (text, thinking or a tool call; a provider's
162
+ // keep-alive pings while it queues don't count): then it's a failure, and the next model goes on
163
+ this.startMs = 60_000
160
164
  this.tokenRatio = 1 // the server's token count / est(): calibrated from usage (context.js)
161
165
  this.knownGood = 0 // the biggest request known to work, in tokens
162
166
  this.onUsage = null // (prompt tokens the server counted, estimate of what was sent): learns the window
@@ -231,6 +235,27 @@ export class Client {
231
235
  }
232
236
  return i
233
237
  }
238
+ // "Best fit": these models first ("provider model", best first), the others after in your list's
239
+ // order; this message starts with the first, and a failure goes on to the next best. false: no list.
240
+ // null: your order again (best fit switched off).
241
+ orderBy(names) {
242
+ const r = this.rotation
243
+ if (!r) return false
244
+ if (!names) {
245
+ if (!r.base) return false // never reordered: nothing to undo (and "stay on the last that answered" holds)
246
+ ;[r.list, r.base, r.at] = [r.base, null, 0]
247
+ this.#use(r.list[0])
248
+ return true
249
+ }
250
+ r.base ??= [...r.list] // your order, kept for when best fit is switched off
251
+ const first = names.map((n) => r.list.find((t) => `${t.provider} ${t.model}` === n)).filter(Boolean)
252
+ if (!first.length) return false
253
+ r.list = [...new Set([...first, ...r.base])]
254
+ r.at = 0
255
+ log('rotate', `best fit: ${first.map((t) => t.model).join(', ')} first`)
256
+ this.#use(r.list[0])
257
+ return true
258
+ }
234
259
  // A new message: back to #1 (unless it stays on the one that worked)
235
260
  newMessage() {
236
261
  const r = this.rotation
@@ -492,6 +517,9 @@ export class Client {
492
517
  // One request. Without `once`, rate limits and server errors get three quiet retries.
493
518
  async #chat(body, { onToken, onReasoning, onToolDelta, signal, once } = {}) {
494
519
  const req = { model: this.model, ...body }
520
+ // a request that doesn't say (a review, a pick, a summary…) is streamed too, when it has no tools:
521
+ // a model that goes silent is then given up on after idleMs, not after the whole timeout
522
+ if (body.stream === undefined && !body.tools?.length && !this.quirks.noStream) req.stream = true
495
523
  const can = this.can && { ...this.can, vision: this.can.vision && !this.quirks.noImages }
496
524
  if (can && req.messages) req.messages = fitFor(req.messages, can, this.model)
497
525
  if (can?.actions === 'guided') delete req.tools
@@ -521,6 +549,10 @@ export class Client {
521
549
  timer.unref?.()
522
550
  }
523
551
  const stop = idle ? (signal ? AbortSignal.any([signal, idle.signal]) : idle.signal) : signal
552
+ // not started answering in startMs: given up on like a failure (the next model of the list takes it)
553
+ let startTimer = idle && setTimeout(() => idle.abort(Object.assign(new Error(`${this.model} didn't start answering within ${Math.round(this.startMs / 1000)}s`), { name: 'TimeoutError', notStarted: true })), this.startMs)
554
+ startTimer?.unref?.()
555
+ const started = () => startTimer && (clearTimeout(startTimer), (startTimer = null))
524
556
  try {
525
557
  for (let attempt = 0; ; attempt++) {
526
558
  sent = Date.now()
@@ -539,7 +571,7 @@ export class Client {
539
571
  }
540
572
  }
541
573
  } catch (e) {
542
- clearTimeout(timer)
574
+ clearTimeout(timer), started()
543
575
  // A provider that refuses one part of the request (400, or 422 from the ones that check
544
576
  // requests against a schema): the same request without that part. Learned (onLearn: kept in
545
577
  // the model's profile) only when that works; else it's put back and the refusal stands. The
@@ -566,6 +598,7 @@ export class Client {
566
598
  if (/reasoning_effort/.test(said) && 'reasoning_effort' in req && !this.quirks.noEffort) return without('noEffort')
567
599
  if (/stream_options/.test(said) && req.stream_options && !this.quirks.noStreamUsage) return without('noStreamUsage')
568
600
  if (/parallel_tool_calls/.test(said) && req.parallel_tool_calls && !this.quirks.noParallel) return without('noParallel')
601
+ if (/stream/i.test(said) && req.stream && body.stream === undefined && !this.quirks.noStream) return without('noStream') // streamed by HeartCode's choice: not again
569
602
  if (reasoningSent && /reasoning(?!_effort)/i.test(said)) return without('noReasoningBack')
570
603
  if (imagesSent && /image|vision|multimodal|modalit|content.{0,20}(type|part)/i.test(said)) return without('noImages')
571
604
  if (req.tools?.length && !this.quirks.simpleSchemas && /schema|function_declarations|parameters|additionalProperties|exclusiveM|minItems|unknown name|invalid.{0,40}(tool|function)|tools\[/i.test(said)) return without('simpleSchemas')
@@ -590,7 +623,7 @@ export class Client {
590
623
  this.#record(req, sent, { reply: r, firstAt })
591
624
  return r
592
625
  }
593
- if (!body.stream) {
626
+ if (!req.stream) {
594
627
  const data = await res.json()
595
628
  const choice = data.choices?.[0] ?? {}
596
629
  const msg = choice.message ?? {}
@@ -631,7 +664,7 @@ export class Client {
631
664
  try {
632
665
  ;({ value, done: end } = await reader.read())
633
666
  } catch (e) {
634
- clearTimeout(timer)
667
+ clearTimeout(timer), started()
635
668
  throw e
636
669
  }
637
670
  poke()
@@ -655,7 +688,7 @@ export class Client {
655
688
  if (chunk.error) {
656
689
  // an error sent in the stream: its status from its code, else a "too large" one as 400
657
690
  // (sent smaller, not again as it is), else a server error (tried again, a few times)
658
- clearTimeout(timer)
691
+ clearTimeout(timer), started()
659
692
  const said = chunk.error.message ?? JSON.stringify(chunk.error)
660
693
  const code = Number(chunk.error.code ?? chunk.error.status)
661
694
  const err = Object.assign(new Error(`server error: ${said}`), { body: payload })
@@ -666,6 +699,7 @@ export class Client {
666
699
  if (chunk.usage) usage = chunk.usage
667
700
  const ch = chunk.choices?.[0]
668
701
  if (!ch) continue
702
+ started() // it answers (a keep-alive or an empty frame doesn't get here)
669
703
  if (ch.finish_reason) finishReason = ch.finish_reason
670
704
  const d = ch.delta ?? ch.message ?? {} // some proxies send the whole message in a chunk
671
705
  this.#reasoningField(d)
@@ -682,6 +716,7 @@ export class Client {
682
716
  if (tc.id) call.id = tc.id
683
717
  if (tc.function?.name) call.function.name ||= tc.function.name
684
718
  if (tc.function?.arguments) call.function.arguments += tc.function.arguments
719
+ if (tc.extra_content) call.extra_content = { ...call.extra_content, ...tc.extra_content } // Gemini's thought_signature: refused next time without it
685
720
  onToolDelta?.(call.function.name, call.function.arguments)
686
721
  watch(`call ${i}`, call.function.arguments)
687
722
  }
@@ -702,7 +737,7 @@ export class Client {
702
737
  break
703
738
  }
704
739
  }
705
- clearTimeout(timer)
740
+ clearTimeout(timer), started()
706
741
  if (looped) {
707
742
  log('reply', `${this.model}: went into a loop in its ${looped.what} (cut after ${looped.at} characters): "${looped.sample}"`)
708
743
  if (looped.what === 'reasoning') reasoning = reasoning.slice(0, looped.at)
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', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search', 'testTimeout']
9
+ const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search', 'testTimeout', 'updateCheck', 'modelChoice', 'logs', 'replyStart', 'mouse']
10
10
  const LOCAL_NAMES = { 11434: 'ollama', 1234: 'lmstudio', 8080: 'llamacpp' }
11
11
 
12
12
  export function readJson(file, fallback) {
package/src/fit.js ADDED
@@ -0,0 +1,65 @@
1
+ // "Best fit" (modelChoice: 'fit'): for each new message, your models ranked by how good each is at
2
+ // what this message needs — by public rankings (rankings.js), not by a model's opinion of models.
3
+ // One short request names the skills the task needs (web pages, code, images…); the rest is
4
+ // arithmetic: who leads the work (and who next when one fails) and who reviews it (not the lead).
5
+ // A model the rankings don't know comes after those they do, in your order. A message that only says to go on keeps the last pick.
6
+ // "Your order" (the default): none of this — your list as you set it.
7
+ import { prompt } from './prompts.js'
8
+ import { log } from './log.js'
9
+ import { rankings, score, SKILLS } from './rankings.js'
10
+
11
+ const name = (t) => `${t.provider} ${t.model}`
12
+ const GO_ON = /^\s*(continue|go on|carry on|keep going|resume|proceed|ok(ay)?|yes|do it|go ahead)\W*$/i
13
+
14
+ // The skills this task needs, from SKILLS: { work: [...] } — asked of the model in use (naming
15
+ // what a task needs is easy; judging models is what the rankings are for). ['coding'] when it can't say.
16
+ async function skillsFor(s, task, signal) {
17
+ const ask = prompt('agent/pick-skills', { task: task.slice(0, 1500), choices: (s.chat.choices ?? []).join('; '), skills: Object.entries(SKILLS).map(([k, [, , what]]) => `${k}: ${what}`).join('\n') })
18
+ const was = s.client.purpose
19
+ s.client.purpose = 'pick-skills'
20
+ try {
21
+ const said = (await s.client.chat({ messages: [{ role: 'user', content: ask }] }, { signal: AbortSignal.any([AbortSignal.timeout(30_000), ...(signal ? [signal] : [])]) })).content
22
+ const line = /^\W*skills?\W*:\s*(.+)$/im.exec(said)?.[1] ?? said
23
+ const named = Object.keys(SKILLS).filter((k) => new RegExp(`(^|[^\\w-])${k}($|[^\\w-])`, 'i').test(line))
24
+ return named.length ? named : ['coding']
25
+ } catch (e) {
26
+ if (signal?.aborted) throw e
27
+ log('fit', `no skills named (${e.message}): coding`)
28
+ return ['coding']
29
+ } finally {
30
+ s.client.purpose = was
31
+ }
32
+ }
33
+
34
+ // { work, review, why } (names, best first), kept in chat.fit; null when there's nothing to choose.
35
+ export async function pickModels(s, task, signal, { images = 0, size = 0 } = {}) {
36
+ const all = s.allModels?.() ?? []
37
+ const can = all.filter((t) => t.tools && (!images || t.images) && (!size || !t.context || t.context > size * 1.2))
38
+ if (can.length < 2) return null
39
+ if (GO_ON.test(task) && s.chat.fit) return s.chat.fit // the same work: the same models (and the provider's cache still holds)
40
+ const data = await rankings({ signal, onWait: () => s.ui.spinner('getting the model rankings (once a week)') })
41
+ s.ui.stopSpin()
42
+ if (!data) return null
43
+ s.ui.spinner('what does this task need')
44
+ const skills = await skillsFor(s, task, signal)
45
+ s.ui.stopSpin()
46
+ if (images && !skills.includes('vision')) skills.push('vision')
47
+ // best first by score; not ranked: after, in your order
48
+ const ranked = (models, wanted) =>
49
+ models
50
+ .map((t, i) => ({ t, i, sc: score(t.model, wanted, data) }))
51
+ .sort((a, b) => (a.sc ?? 2) - (b.sc ?? 2) || a.i - b.i)
52
+ const order = ranked(can, skills)
53
+ const lead = name(order[0].t)
54
+ const fit = {
55
+ work: order.map((x) => name(x.t)),
56
+ review: ranked(can, ['coding', 'hard']).filter((x) => x.sc != null).map((x) => name(x.t)).filter((n) => n !== lead).slice(0, 2),
57
+ why: skills.join(', '),
58
+ }
59
+ log('fit', { skills, scores: order.slice(0, 8).map((x) => `${x.t.model} ${x.sc == null ? 'not ranked' : x.sc.toFixed(2)}`), review: fit.review })
60
+ s.chat.fit = fit
61
+ return fit
62
+ }
63
+
64
+ // Others (reviewers, page checkers) in the pick's order, the rest after in your list's order.
65
+ export const byPick = (models, names = []) => [...models].sort((a, b) => ((names.indexOf(name(a)) + 1 || 1e9) - (names.indexOf(name(b)) + 1 || 1e9)))
package/src/guided.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Guided mode, for models without (reliable) tool calls. HeartCode drives the
2
2
  // task as a series of single questions; every answer has one trivial shape
3
3
  // (a number, a path, or "the whole reply is code") and is checked against
4
- // reality before use. With constrained output, the server enforces the shape.
4
+ // reality before use.
5
5
  import fs from 'node:fs'
6
6
  import { log } from './log.js'
7
7
  import { prompt, userInstructions } from './prompts.js'
@@ -39,7 +39,7 @@ export function nextActions(st) {
39
39
  return [...new Set([...first, ...ACTIONS.map(([n]) => n)])].filter((n) => n !== 'delegate' || st.canDelegate)
40
40
  }
41
41
 
42
- // A reply may be plain text or (when enforced) JSON like {"path": "a.js"}.
42
+ // A reply may be plain text or JSON like {"path": "a.js"}.
43
43
  export function answerText(reply) {
44
44
  const t = String(reply).trim()
45
45
  if (t.startsWith('{')) {
@@ -172,8 +172,7 @@ class Guided {
172
172
  }
173
173
 
174
174
  async yesNo(question, fallback) {
175
- const schema = { type: 'object', properties: { answer: { type: 'string', enum: ['yes', 'no'] } }, required: ['answer'], additionalProperties: false }
176
- const res = await this.query(prompt('guided/yes-no', { question }), { room: 20, schema, oneLine: true })
175
+ const res = await this.query(prompt('guided/yes-no', { question }), { room: 20, oneLine: true })
177
176
  const m = /\b(yes|no)\b/i.exec(answerText(res.content))
178
177
  return m ? m[1].toLowerCase() === 'yes' : fallback
179
178
  }
@@ -229,24 +228,21 @@ class Guided {
229
228
  return this.ask1(question, opts)
230
229
  }
231
230
 
232
- async ask1(question, { room = 32, schema, oneLine, onToken, answer, skipKey } = {}, tries = 0) {
231
+ async ask1(question, { room = 32, oneLine, onToken, answer, skipKey } = {}, tries = 0) {
233
232
  const { client, strat } = this.s
234
233
  const think = strat.thinking ? 4096 : 0
235
234
  const user = `${this.context(est(question) + room + think + tries * 600, skipKey)}\n\n${question}`
236
235
  this.instructions ??= userInstructions(this.s.root)
237
236
  const system = [prompt('guided/system'), this.instructions && prompt('agent/instructions', { instructions: this.instructions }), this.s.appendSystem].filter(Boolean).join('\n\n')
238
- const messages = strat.mergeSystem
239
- ? [{ role: 'user', content: `${system}\n\n${user}` }]
240
- : [
241
- { role: 'system', content: system },
242
- { role: 'user', content: user },
243
- ]
237
+ const messages = [
238
+ { role: 'system', content: system },
239
+ { role: 'user', content: user },
240
+ ]
244
241
  const out = this.ui.response()
245
242
  if (answer) onToken = out.text
246
243
  const stream = Boolean(strat.stream && (onToken || strat.thinking))
247
244
  const body = { messages, temperature: 0, stream } // no max_tokens: the model decides how long
248
- if (schema && strat.enforce) body.response_format = { type: 'json_schema', json_schema: { name: 'answer', strict: true, schema } }
249
- else if (oneLine && strat.stop) body.stop = ['\n\n']
245
+ if (oneLine && strat.stop) body.stop = ['\n\n']
250
246
  const res = await client.chat(body, { signal: this.signal, onToken, onReasoning: out.think })
251
247
  if (!stream) out.think(res.reasoning)
252
248
  if (answer && !stream) out.text(res.content)
@@ -331,9 +327,8 @@ class Guided {
331
327
  const names = nextActions(this.st)
332
328
  const menu = names.map((n, i) => `${i + 1}. ${n} - ${DESC[n]}`).join('\n')
333
329
  let q = prompt('guided/next-action', { menu })
334
- const schema = { type: 'object', properties: { choice: { type: 'integer', enum: names.map((_, i) => i + 1) } }, required: ['choice'], additionalProperties: false }
335
330
  for (let i = 0; i < 2; i++) {
336
- const res = await this.query(q, { room: 16, schema, oneLine: true })
331
+ const res = await this.query(q, { room: 16, oneLine: true })
337
332
  const a = parsePick(res.content, names)
338
333
  if (a) return a
339
334
  q += '\n\n' + prompt('guided/next-action-retry', { reply: clip(res.content, 40), count: names.length })
@@ -346,11 +341,9 @@ class Guided {
346
341
  this.note(null, 'note', prompt('guided/note-no-files'))
347
342
  return null
348
343
  }
349
- const schema =
350
- candidates.length <= 300 ? { type: 'object', properties: { path: { type: 'string', enum: candidates } }, required: ['path'], additionalProperties: false } : undefined
351
344
  let q = prompt('guided/pick-file', { question })
352
345
  for (let i = 0; i < 2; i++) {
353
- const res = await this.query(q, { room: 60, schema, oneLine: true })
346
+ const res = await this.query(q, { room: 60, oneLine: true })
354
347
  const said = answerText(res.content)
355
348
  const f = matchFile(candidates, said)
356
349
  if (f) return f
@@ -387,7 +380,7 @@ class Guided {
387
380
  const old = fs.readFileSync(resolveIn(this.s.root, f), 'utf8')
388
381
  this.ui.step('edit', f)
389
382
  let next = null
390
- if (this.s.strat.edits === 'search_replace') next = await this.editBlocks(f, old)
383
+ next = await this.editBlocks(f, old)
391
384
  if (next === null) next = await this.editRewrite(f, old)
392
385
  if (next === null) return `edit:${f}`
393
386
  const lost = lostNames(old, next, this.task)
@@ -443,11 +436,9 @@ class Guided {
443
436
  win = focusWindow(lines, answerText(res.content), room) ?? [0, lines.length]
444
437
  }
445
438
  const view = clip(numberLines(lines.slice(win[0], win[1]), win[0] + 1), room)
446
- const schema = { type: 'object', properties: { start: { type: 'integer' }, end: { type: 'integer' } }, required: ['start', 'end'], additionalProperties: false }
447
439
  const part = win[0] > 0 || win[1] < lines.length ? ` (lines ${win[0] + 1}-${win[1]} of ${lines.length})` : ''
448
440
  const rres = await this.query(prompt('guided/pick-range', { file: f, part, view: fence(view) }), {
449
441
  room: 20,
450
- schema,
451
442
  oneLine: true,
452
443
  skipKey,
453
444
  })
package/src/importer.js CHANGED
@@ -1,7 +1,8 @@
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'
@@ -39,10 +40,36 @@ function filesIn(dir, exts) {
39
40
  const safe = (n) => String(n).toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '')
40
41
  const skillsDir = (root, scope) => (scope === 'global' ? path.join(HOME, 'skills') : path.join(root, '.heartcode', 'skills'))
41
42
  const taken = (root, scope, name) => exists(path.join(skillsDir(root, scope), `${name}.md`)) || exists(path.join(skillsDir(root, scope), name))
43
+ // name, else name-2, name-3…: the first not taken
44
+ const freeName = (isTaken, name) => {
45
+ let n = name
46
+ for (let i = 2; isTaken(n); i++) n = `${name}-${i}`
47
+ return n
48
+ }
49
+ const same = (a, b) => a.replace(/\s+/g, ' ').trim() === b.replace(/\s+/g, ' ').trim()
50
+ // The skills there are (one file, or a folder with SKILL.md): [name, body]
51
+ function skillBodies(root, scope) {
52
+ const dir = skillsDir(root, scope)
53
+ let entries = []
54
+ try {
55
+ entries = fs.readdirSync(dir, { withFileTypes: true })
56
+ } catch {}
57
+ return entries.flatMap((e) => {
58
+ const file = e.isDirectory() ? path.join(dir, e.name, 'SKILL.md') : e.name.endsWith('.md') ? path.join(dir, e.name) : null
59
+ if (!file || !exists(file)) return []
60
+ return [[e.name.replace(/\.md$/, ''), frontMatter(fs.readFileSync(file, 'utf8')).body]]
61
+ })
62
+ }
63
+ // Why a skill or command would be a duplicate there, or ''
64
+ function skillDup(root, scope, name, body) {
65
+ if (taken(root, scope, name)) return `a skill named ${name} is already there`
66
+ const twin = skillBodies(root, scope).find(([, b]) => same(b, body))
67
+ return twin ? `the same as your skill ${twin[0]}` : ''
68
+ }
42
69
 
43
70
  // A markdown command (Claude Code, Codex, OpenCode) → a HeartCode skill you type ("use: me").
44
71
  function importCommand(root, scope, name, file) {
45
- if (taken(root, scope, name)) return `/${name} already exists, kept it`
72
+ name = freeName((n) => taken(root, scope, n), name)
46
73
  const { meta, body } = frontMatter(fs.readFileSync(file, 'utf8'))
47
74
  const head = [`description: ${(meta.description || body.split('\n')[0]).replace(/\n/g, ' ').slice(0, 200)}`, `use: ${meta['user-invocable'] === 'false' ? 'model' : 'me'}`]
48
75
  if (meta['argument-hint']) head.push(`argument-hint: ${meta['argument-hint']}`)
@@ -54,7 +81,7 @@ function importCommand(root, scope, name, file) {
54
81
  // A Gemini CLI command (.toml with prompt and description) → a HeartCode skill. {{args}} stays as
55
82
  // is (it's HeartCode's too); !{cmd} becomes !`cmd`.
56
83
  function importToml(root, scope, name, file) {
57
- if (taken(root, scope, name)) return `/${name} already exists, kept it`
84
+ name = freeName((n) => taken(root, scope, n), name)
58
85
  const text = fs.readFileSync(file, 'utf8')
59
86
  const str = (key) => {
60
87
  const m = new RegExp(`^${key}\\s*=\\s*(?:"""([\\s\\S]*?)"""|'''([\\s\\S]*?)'''|"((?:[^"\\\\]|\\\\.)*)"|'([^']*)')`, 'm').exec(text)
@@ -69,16 +96,26 @@ function importToml(root, scope, name, file) {
69
96
 
70
97
  // A skill folder (Claude Code, Codex): copied as is, supporting files included.
71
98
  function importSkillFolder(root, scope, name, dir) {
72
- if (taken(root, scope, name)) return `${name} already exists, kept it`
99
+ name = freeName((n) => taken(root, scope, n), name)
73
100
  fs.cpSync(dir, path.join(skillsDir(root, scope), name), { recursive: true })
74
101
  return name
75
102
  }
76
103
 
104
+ const mcpFile = (root, scope) => (scope === 'global' ? path.join(HOME, 'mcp.json') : path.join(root, '.heartcode', 'mcp.json'))
105
+ const serverKey = (cfg) => (cfg.command ? [cfg.command, ...(cfg.args ?? [])].join(' ') : (cfg.url ?? cfg.httpUrl ?? ''))
106
+ // Why an MCP server would be a duplicate there, or ''
107
+ function mcpDup(root, scope, name, cfg) {
108
+ const have = readJson(mcpFile(root, scope), {}).mcpServers ?? {}
109
+ if (have[name]) return `an MCP server named ${name} is already there`
110
+ const twin = Object.entries(have).find(([, c]) => serverKey(c) === serverKey(cfg))
111
+ return twin ? `the same server as your ${twin[0]}` : ''
112
+ }
113
+
77
114
  function importMcp(root, scope, name, cfg) {
78
- const file = scope === 'global' ? path.join(HOME, 'mcp.json') : path.join(root, '.heartcode', 'mcp.json')
115
+ const file = mcpFile(root, scope)
79
116
  const data = readJson(file, {})
80
117
  data.mcpServers ??= {}
81
- if (data.mcpServers[name]) return `MCP server ${name} already exists, kept it`
118
+ name = freeName((n) => data.mcpServers[n], name)
82
119
  const { command, args, env, url, httpUrl, headers, type } = cfg
83
120
  data.mcpServers[name] = command
84
121
  ? { command, ...(args?.length && { args }), ...(env && Object.keys(env).length && { env }) }
@@ -136,7 +173,8 @@ function codexServers(file) {
136
173
  // Everything importable, as picker items: { label, desc, group, run() → what was done }.
137
174
  export function findImports(root, home = os.homedir()) {
138
175
  const items = []
139
- const add = (group, label, desc, run) => items.push({ group, label, desc, run })
176
+ // dup(): why it would be a duplicate (asked when it runs: an earlier pick may have just added it)
177
+ const add = (group, label, desc, run, dup) => items.push({ group, label, desc, run, dup })
140
178
  const commandSources = [
141
179
  ['Claude Code', 'project', path.join(root, '.claude', 'commands')],
142
180
  ['Claude Code', 'global', path.join(home, '.claude', 'commands')],
@@ -150,13 +188,13 @@ export function findImports(root, home = os.homedir()) {
150
188
  for (const [rel, file] of filesIn(dir, ['.md'])) {
151
189
  const name = safe(rel)
152
190
  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))
191
+ 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
192
  }
155
193
  }
156
194
  for (const [scope, dir] of [['project', path.join(root, '.gemini', 'commands')], ['global', path.join(home, '.gemini', 'commands')]]) {
157
195
  for (const [rel, file] of filesIn(dir, ['.toml'])) {
158
196
  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))
197
+ 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
198
  }
161
199
  }
162
200
  const skillSources = [
@@ -172,8 +210,8 @@ export function findImports(root, home = os.homedir()) {
172
210
  for (const e of entries) {
173
211
  const file = path.join(dir, e.name, 'SKILL.md')
174
212
  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)))
213
+ const { meta, body } = frontMatter(fs.readFileSync(file, 'utf8'))
214
+ 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
215
  }
178
216
  }
179
217
  const claudeJson = readJson(path.join(home, '.claude.json'), {})
@@ -190,7 +228,7 @@ export function findImports(root, home = os.homedir()) {
190
228
  for (const [tool, scope, servers] of mcpSources) {
191
229
  for (const [name, cfg] of Object.entries(servers ?? {})) {
192
230
  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))
231
+ 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
232
  }
195
233
  }
196
234
  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')]]) {