heartcode 0.1.45 → 0.1.56

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/guided.js CHANGED
@@ -8,7 +8,9 @@ import { prompt, userInstructions } from './prompts.js'
8
8
  import path from 'node:path'
9
9
  import { est } from './client.js'
10
10
  import { applyEdit, parseBlocks, cleanCode, lostNames, reindent } from './edit.js'
11
- import { listFiles, namedFiles, readFileTool, searchFiles, numberLines, proposeWrite, runConfirmed, suggestCommands, resolveIn, writeResult, clip } from './tools.js'
11
+ import { listFiles, namedFiles, readFileTool, searchFiles, numberLines, proposeWrite, runConfirmed, suggestCommands, resolveIn, writeResult, clip, allowed } from './tools.js'
12
+ import { runHooks } from './hooks.js'
13
+ import { foldersOf } from './agent.js'
12
14
  import { c } from './ui.js'
13
15
 
14
16
  // The steps, as "name: description" lines in prompts/guided/actions.md.
@@ -22,9 +24,10 @@ const TEST_FILE = /(^|[/._-])(tests?|spec|__tests__)([/._-]|$)/i
22
24
  // Obvious next steps are taken without asking: a weak model's effort goes into
23
25
  // writing code, not into navigating. Returns an action, or null to ask.
24
26
  export function autoAction(st) {
27
+ if (st.held) return null // a Stop hook said it isn't done: the model chooses from here
25
28
  if (st.delegated) return 'finish' // another model did the task: say what it did
26
29
  if (st.lastRun !== null && st.lastRun !== 0 && !st.editsSinceRun && st.wantsChange && st.fixes < 3) return 'edit'
27
- if (st.wantsChange && st.reads && !st.edits) return 'edit'
30
+ if (st.wantsChange && st.reads && !st.edits && !st.editTries) return 'edit' // once: a declined or failed edit leaves it to the model
28
31
  if (st.lastRun === 0 && st.edits && !st.editsSinceRun) return 'finish'
29
32
  return null
30
33
  }
@@ -36,7 +39,7 @@ export function nextActions(st) {
36
39
  if (!st.reads && st.hasFiles) first = ['read', 'search']
37
40
  else if (st.wantsChange && !st.edits) first = st.hasFiles ? ['edit', 'create', 'read'] : ['create']
38
41
  else first = ['finish', 'edit', 'run']
39
- return [...new Set([...first, ...ACTIONS.map(([n]) => n)])].filter((n) => n !== 'delegate' || st.canDelegate)
42
+ return [...new Set([...first, ...ACTIONS.map(([n]) => n)])].filter((n) => (n !== 'delegate' || st.canDelegate) && (n !== 'ask' || !st.noAsk) && n !== st.avoid) // a step that just repeated with nothing new isn't offered again (a small model picks it over and over)
40
43
  }
41
44
 
42
45
  // A reply may be plain text or JSON like {"path": "a.js"}.
@@ -168,11 +171,13 @@ class Guided {
168
171
  this.notes = []
169
172
  this.changed = new Set()
170
173
  this.files = listFiles(s.root)
171
- this.st = { reads: 0, edits: 0, editsSinceRun: 0, runs: 0, fixes: 0, lastRun: null, hasFiles: this.files.length > 0, canRun: suggestCommands(s.root).length > 0, canDelegate: Boolean(s.team?.().some((t) => t.tools)) }
174
+ this.st = { reads: 0, edits: 0, editsSinceRun: 0, runs: 0, fixes: 0, lastRun: null, hasFiles: this.files.length > 0, canRun: suggestCommands(s.root).length > 0, editTries: 0, noAsk: Boolean(s.ui.noUser || s.isSub) } // ask: not headless, nor a helper (it reports to the main agent, which asks)
175
+ this.calls = 0
176
+ this.stops = 0
172
177
  }
173
178
 
174
179
  async yesNo(question, fallback) {
175
- const res = await this.query(prompt('guided/yes-no', { question }), { room: 20, oneLine: true })
180
+ const res = await this.query(question, { room: 20, oneLine: true })
176
181
  const m = /\b(yes|no)\b/i.exec(answerText(res.content))
177
182
  return m ? m[1].toLowerCase() === 'yes' : fallback
178
183
  }
@@ -259,6 +264,8 @@ class Guided {
259
264
 
260
265
  async start(images) {
261
266
  this.images = images.length > 0
267
+ this.st.canDelegate = Boolean(this.s.team?.().some((t) => t.tools && (!this.images || t.images))) // one that sees them, with images
268
+ if (!this.s.isSub) Object.assign(this.s, { research: [], ran: [], dirsBefore: foldersOf(this.s.root) }) // this message's, for the wrap-up (a helper adds to its main agent's)
262
269
  if (images.length) await this.describeImages(images)
263
270
  this.autoRead()
264
271
  this.ui.spinner('reading the task')
@@ -272,7 +279,14 @@ class Guided {
272
279
  const action = auto ?? (await this.pickAction())
273
280
  log('guided', `step ${step + 1}: ${action}${auto ? ' (autopilot)' : ''}`, this.st)
274
281
  if (auto === 'edit' && this.st.runs) this.st.fixes++
275
- if (action === 'finish') break
282
+ if (action === 'finish') {
283
+ // the Stop hooks, as in native mode (the main conversation's, not a helper's): one that blocks has it carry on
284
+ const hook = this.s.isSub ? {} : await runHooks(this.s, 'Stop', { stop_hook_active: this.stops++ > 0 }, this.signal)
285
+ if (!hook.block) break
286
+ this.note(null, 'not done yet', prompt('agent/hook', { reason: hook.block, stop: true }))
287
+ this.st.held = true
288
+ continue
289
+ }
276
290
  let sig
277
291
  try {
278
292
  sig = await this[action]()
@@ -284,6 +298,7 @@ class Guided {
284
298
  }
285
299
  repeats = sig === last ? repeats + 1 : 0
286
300
  last = sig
301
+ this.st.avoid = repeats ? action : null
287
302
  if (repeats >= 2) {
288
303
  // the next of your models carries on; with none, it goes on being told (only Esc stops it)
289
304
  const was = this.s.client.model
@@ -295,7 +310,31 @@ class Guided {
295
310
  }
296
311
  if (repeats === 1) this.note(null, 'warning', prompt('guided/note-repeated'))
297
312
  }
298
- return this.finish()
313
+ const answer = await this.finish()
314
+ this.s.wrapUpLater?.(this.task, answer) // after the answer, beside what comes next (skipped for helpers and without memory)
315
+ return answer
316
+ }
317
+
318
+ // A step as native mode's tool call: the same allowed tools (--allowedTools), hooks, a helper's own
319
+ // files, and events (headless stream-json, editors). run(id) does it and returns its result.
320
+ async tool(name, args, run) {
321
+ const { s } = this
322
+ const id = `guided_${++this.calls}`
323
+ s.onEvent?.({ type: 'assistant', model: `${s.client.provider}/${s.client.model}`, content: '', toolCalls: [{ id, type: 'function', function: { name, arguments: JSON.stringify(args) } }] })
324
+ let out
325
+ const pre = allowed(s, name) && (await runHooks(s, 'PreToolUse', { tool_name: name, tool_input: args }, this.signal))
326
+ const notMine = name === 'write_file' && s.ownFiles && !s.ownFiles.includes(path.resolve(s.root, args.path))
327
+ if (!pre) out = `error: the tool ${name} is not allowed here`
328
+ else if (pre.block) out = prompt('agent/hook', { reason: pre.block, blocked: true })
329
+ else if (notMine) out = prompt('agent/part-files', { file: args.path, files: s.ownFiles.map((f) => path.relative(s.root, f)).join(', ') })
330
+ else {
331
+ out = await run(id)
332
+ const post = await runHooks(s, 'PostToolUse', { tool_name: name, tool_input: args, tool_response: out }, this.signal)
333
+ if (post.block) out += `\n\n${prompt('agent/hook', { reason: post.block, after: true })}`
334
+ }
335
+ if (!pre || pre.block || notMine) this.ui.result(c.red(clip(out, 120)))
336
+ s.onEvent?.({ type: 'tool', id, name, output: out })
337
+ return out
299
338
  }
300
339
 
301
340
  async describeImages(images) {
@@ -321,41 +360,47 @@ class Guided {
321
360
  this.note(`read:${f}`, `contents of ${f}`, clip(body, Math.floor(this.s.strat.context * 3.5 * 0.4)))
322
361
  if (!quiet) this.ui.step('read', f)
323
362
  this.st.reads++
363
+ return body
324
364
  }
325
365
 
326
366
  async pickAction() {
327
367
  const names = nextActions(this.st)
328
368
  const menu = names.map((n, i) => `${i + 1}. ${n} - ${DESC[n]}`).join('\n')
329
- let q = prompt('guided/next-action', { menu })
369
+ let q = prompt('guided/next-action', { menu, reply: '', count: names.length })
330
370
  for (let i = 0; i < 2; i++) {
331
371
  const res = await this.query(q, { room: 16, oneLine: true })
332
372
  const a = parsePick(res.content, names)
333
373
  if (a) return a
334
- q += '\n\n' + prompt('guided/next-action-retry', { reply: clip(res.content, 40), count: names.length })
374
+ q = prompt('guided/next-action', { menu, reply: clip(res.content, 40) || '(nothing)', count: names.length })
335
375
  }
336
376
  return 'finish'
337
377
  }
338
378
 
339
- async pickFile(question, candidates) {
379
+ // edit: the file to change (else the file to read)
380
+ async pickFile(edit, candidates) {
340
381
  if (!candidates.length) {
341
382
  this.note(null, 'note', prompt('guided/note-no-files'))
342
383
  return null
343
384
  }
344
- let q = prompt('guided/pick-file', { question })
385
+ let q = prompt('guided/pick-file', { edit, said: '', choices: '' })
345
386
  for (let i = 0; i < 2; i++) {
346
387
  const res = await this.query(q, { room: 60, oneLine: true })
347
388
  const said = answerText(res.content)
348
389
  const f = matchFile(candidates, said)
349
390
  if (f) return f
350
- q = prompt('guided/pick-file-retry', { question, said: clip(said, 60), choices: closest(candidates, said, 15).join('\n') })
391
+ q = prompt('guided/pick-file', { edit, said: clip(said, 60) || '(nothing)', choices: closest(candidates, said, 15).join('\n') })
351
392
  }
352
393
  this.note(null, 'note', prompt('guided/note-unknown-file'))
353
394
  return null
354
395
  }
355
396
 
356
397
  async read() {
357
- const f = await this.pickFile(prompt('guided/which-file-to-read'), this.files)
358
- if (f) this.readNote(f)
398
+ const f = await this.pickFile(false, this.files)
399
+ if (f) {
400
+ let done = false
401
+ const out = await this.tool('read_file', { path: f }, () => ((done = true), this.readNote(f)))
402
+ if (!done) this.note(null, `reading ${f}`, out) // refused (--disallowedTools, a hook)
403
+ }
359
404
  return `read:${f}`
360
405
  }
361
406
 
@@ -364,7 +409,7 @@ class Guided {
364
409
  const q = unquote(answerText(res.content).split('\n')[0].trim())
365
410
  if (!q) return 'search:'
366
411
  this.ui.step('search', q)
367
- const out = searchFiles(this.s.root, q)
412
+ const out = await this.tool('search', { query: q }, () => searchFiles(this.s.root, q))
368
413
  this.ui.result(out.startsWith('no matches') ? 'no matches' : `${out.split('\n').length} matches`)
369
414
  this.note(`search:${q}`, `search results for "${q}"`, out)
370
415
  return `search:${q}`
@@ -375,7 +420,8 @@ class Guided {
375
420
  // Weak models pick the first option: offer the code under test before the tests themselves.
376
421
  let files = [...new Set([...seen, ...this.files])]
377
422
  files = [...files.filter((x) => !TEST_FILE.test(x)), ...files.filter((x) => TEST_FILE.test(x))]
378
- let f = await this.pickFile(prompt('guided/which-file-to-edit'), files)
423
+ this.st.editTries++
424
+ let f = await this.pickFile(true, files)
379
425
  if (!f) return 'edit:'
380
426
  const old = fs.readFileSync(resolveIn(this.s.root, f), 'utf8')
381
427
  this.ui.step('edit', f)
@@ -478,9 +524,13 @@ class Guided {
478
524
 
479
525
  async apply(f, old, next) {
480
526
  this.ui.stopSpin()
481
- const r = await proposeWrite(this.s, f, old, next)
482
- this.note(null, `${old ? 'edit' : 'create'} ${f}`, writeResult(f, r) + (r.diff ? '\n' + r.diff : ''))
483
- if (r.status === 'applied') {
527
+ let r
528
+ const out = await this.tool('write_file', { path: f, content: next }, async () => {
529
+ r = await proposeWrite(this.s, f, old, next)
530
+ return writeResult(f, r)
531
+ })
532
+ this.note(null, `${old ? 'edit' : 'create'} ${f}`, out + (r?.diff ? '\n' + r.diff : ''))
533
+ if (r?.status === 'applied') {
484
534
  this.st.edits++
485
535
  this.changed.add(f)
486
536
  this.st.editsSinceRun++
@@ -519,7 +569,8 @@ class Guided {
519
569
  const n = sugg[Number(/^(\d+)[.):]?(\s|$)/.exec(t)?.[1]) - 1] // "2", "2.", "2. npm test"
520
570
  const cmd = n ?? cleanCommand(t)
521
571
  if (!cmd) return 'run:'
522
- const out = await runConfirmed(this.s, cmd, this.signal)
572
+ const out = await this.tool('run_command', { command: cmd }, () => runConfirmed(this.s, cmd, this.signal))
573
+ this.s.ran?.push({ command: cmd, result: clip(out.split('\n').filter((l) => l.trim()).slice(0, 2).join(' · '), 160) }) // for the wrap-up, as native mode's
523
574
  const code = /^exit code (\S+)/.exec(out)?.[1]
524
575
  this.st.runs++
525
576
  this.st.editsSinceRun = 0
@@ -541,18 +592,18 @@ class Guided {
541
592
  async ask() {
542
593
  const res = await this.query(prompt('guided/ask-user'), { room: 120 })
543
594
  const q = res.content.trim()
544
- const a = await this.ui.ask(`${c.cyan('heartcode asks:')} ${q}\n${c.magenta('> ')}`)
545
- this.note(null, `you asked the user: ${q}`, `The user answered: ${a ?? '(no answer)'}`)
595
+ const out = await this.tool('ask_user', { question: q }, async () => `The user answered: ${(await this.ui.ask(`${c.cyan('heartcode asks:')} ${q}\n${c.magenta('> ')}`)) ?? '(no answer)'}`)
596
+ this.note(null, `you asked the user: ${q}`, out)
546
597
  return `ask:${q}`
547
598
  }
548
599
 
549
600
  // Another of your models, one with tool calls, does the whole task; what it did goes in the notes.
550
601
  async delegate() {
551
- // the model with tool calls that failed least this session (and sees images, if the task came with some)
552
- const fails = (t) => this.s.failures?.[`${t.provider} ${t.model}`] ?? 0
553
- const team = this.s.team().filter((t) => t.tools).sort((a, b) => (this.images ? b.images - a.images : 0) || fails(a) - fails(b))
602
+ // the first of yours with tool calls (that sees images, if the task came with some)
603
+ const team = this.s.team().filter((t) => t.tools && (!this.images || t.images))
554
604
  const t = team[0]
555
- const done = await this.s.subagent({ description: 'the task', prompt: this.task, model: `${t.provider} ${t.model}` }, this.signal)
605
+ const args = { description: 'the task', prompt: this.task, model: `${t.provider} ${t.model}` }
606
+ const done = await this.tool('agent', args, (id) => this.s.subagent(args, this.signal, id))
556
607
  this.note('delegate', `what ${t.model} did for the task`, done)
557
608
  this.st.delegated = true
558
609
  return 'delegate'
package/src/headless.js CHANGED
@@ -48,8 +48,33 @@ export class HeadlessUI {
48
48
  setPermission(mode) {
49
49
  this.permission = mode
50
50
  }
51
- response() {
52
- return { text() {}, think() {}, end() {} }
51
+ // A model's reply as it comes, for --include-partial-messages (stream-json): Claude Code's events
52
+ // (message_start, a content block each for its thinking and its text with their deltas,
53
+ // message_stop) through this.partial. Without it, or a helper's reply (its steps come whole, with
54
+ // their parent): nothing.
55
+ response(who, { helper = false } = {}) {
56
+ const send = !helper && this.partial
57
+ if (!send) return { text() {}, think() {}, end() {} }
58
+ let started = false
59
+ let kind = null
60
+ let index = -1
61
+ const open = (k) => {
62
+ if (!started) (started = true), send({ type: 'message_start', message: { role: 'assistant', model: who, content: [] } })
63
+ if (kind === k) return
64
+ if (kind) send({ type: 'content_block_stop', index })
65
+ kind = k
66
+ send({ type: 'content_block_start', index: ++index, content_block: k === 'thinking' ? { type: 'thinking', thinking: '' } : { type: 'text', text: '' } })
67
+ }
68
+ return {
69
+ think: (t) => t && (open('thinking'), send({ type: 'content_block_delta', index, delta: { type: 'thinking_delta', thinking: t } })),
70
+ text: (t) => t && (open('text'), send({ type: 'content_block_delta', index, delta: { type: 'text_delta', text: t } })),
71
+ end: () => {
72
+ if (kind) send({ type: 'content_block_stop', index })
73
+ if (started) send({ type: 'message_stop' })
74
+ started = false
75
+ kind = null
76
+ },
77
+ }
53
78
  }
54
79
  async ask() {
55
80
  return null
@@ -74,6 +99,8 @@ export class HeadlessUI {
74
99
  setLog() {}
75
100
  close() {}
76
101
  leaveFullscreen() {}
102
+ recolor() {}
103
+ setMouse() {}
77
104
  }
78
105
 
79
106
  // Runs the messages (prompt, or stdin) and writes the output. Returns the exit code.
@@ -125,6 +152,7 @@ export async function runHeadless(app, opts) {
125
152
  const asClaude = (name, input) => (name === 'mcp' && input?.server && input?.tool ? { name: mcpName(String(input.server), String(input.tool)), input: input.arguments ?? {} } : { name, input })
126
153
  let said = false // the model's text was already sent as an assistant message
127
154
  if (out === 'stream-json') {
155
+ if (opts.partial) app.ui.partial = (event) => emit({ type: 'stream_event', event, session_id, parent_tool_use_id: null }) // the replies as they come (--include-partial-messages)
128
156
  s.onEvent = (e) => {
129
157
  if (e.type === 'assistant') {
130
158
  const content = [
@@ -160,7 +188,7 @@ export async function runHeadless(app, opts) {
160
188
  let error = null
161
189
  try {
162
190
  const k = /^\/(\S+)\s*([\s\S]*)$/.exec(text)
163
- const skill = k && app.skills.get(k[1])
191
+ const skill = k && app.skills.get(k[1].replace(/^skill:/, '')) // /name or /skill:name, as in the full screen
164
192
  answer = await s.run(skill && skill.use !== 'model' ? await app.expandSkill(skill, k[2]) : text, current.ctl.signal, images)
165
193
  } catch (e) {
166
194
  error = current.ctl.signal.aborted ? 'interrupted' : e.message
package/src/log.js CHANGED
@@ -25,7 +25,7 @@ export const LOG_DIR = process.env.HEART_LOG === 'off' ? null : path.resolve(pro
25
25
  // listed goes in debug.
26
26
  export const LOG_KINDS = {
27
27
  tools: { label: 'Tools & commands', about: 'what HeartCode did on your machine: each tool call and its result, commands and background commands, MCP calls, files written', topics: ['tool', 'command', 'mcp', 'background', 'lsp', 'format', 'write', 'web', 'research', 'worktree'] },
28
- models: { label: 'Model choices', about: 'why a model answered or didn\'t: fallbacks, retries, best-fit picks and quirks found', topics: ['rotate', 'retry', 'fit', 'quirk'] },
28
+ models: { label: 'Model choices', about: 'why a model answered or didn\'t: fallbacks, retries and quirks found', topics: ['rotate', 'retry', 'quirk'] },
29
29
  agent: { label: "Agent's decisions", about: 'why it did what it did: each task and its answer, plan-first, reviews, page checks, helpers and parts, compacting, lessons, the wrap-up', topics: ['task', 'look', 'review', 'compact', 'wrapup', 'learn', 'agent', 'director', 'guided', 'rewind', 'btw', 'parts'] },
30
30
  errors: { label: 'Errors', about: 'what went wrong: errors, crashes and warnings, with where they came from', topics: ['error', 'crash', 'warn', 'exit'] },
31
31
  conversation: { label: 'Conversation', about: 'a plain transcript: what you typed, its answers, its questions and your answers', topics: ['input', 'ask', 'answer'] },
package/src/lsp.js CHANGED
@@ -10,6 +10,8 @@ import { spawn } from 'node:child_process'
10
10
  import { pathToFileURL, fileURLToPath } from 'node:url'
11
11
  import { log } from './log.js'
12
12
  import { HOME, readJson, writeJson } from './config.js'
13
+ import { prompt } from './prompts.js'
14
+ import { allowed, declined } from './tools.js'
13
15
 
14
16
  const SERVERS_FILE = path.join(HOME, 'lsp.json') // { [project root]: { [".ts"]: { server, language } } }
15
17
 
@@ -256,6 +258,14 @@ export async function lspTool(s, args, signal) {
256
258
  if (!args.file) return 'error: lsp needs "file"'
257
259
  const abs = path.resolve(root, String(args.file))
258
260
  if (!fs.existsSync(abs)) return `error: no file ${args.file}`
261
+ // a server this project hasn't used runs a command the model chose: asked like run_command
262
+ if (!Object.values(knownServers(root)).some((k) => k.server === server) && !s.lspAllowed?.has(server)) {
263
+ if (!allowed(s, 'run_command')) return `error: ${server} isn't a language server this project uses, and running commands isn't allowed here. Use search and read_file instead.`
264
+ if (s.ui.permission === 'plan') return prompt('agent/plan-refused', { command: true })
265
+ const ok = await s.ui.confirm(`Start the language server ${server}?`, 'command')
266
+ if (ok !== true) return declined(s, ok, 'The user declined to start this language server.')
267
+ ;(s.lspAllowed ??= new Set()).add(server)
268
+ }
259
269
  const sv = serverFor(root, server, language)
260
270
  if (typeof sv === 'string') return `error: ${sv}. Check with find_command; install it, or use search and read_file instead.`
261
271
  const first = !sv.used
package/src/mcp.js CHANGED
@@ -19,27 +19,36 @@ import { HOME, readJson, readConfig, writeJson, VERSION } from './config.js'
19
19
  import { log } from './log.js'
20
20
  import { savedToken, signIn, hasToken } from './oauth.js'
21
21
 
22
- // Built in; a config entry with the same name changes it, "disabled": true turns it off.
23
- export const DEFAULT_SERVERS = {
24
- 'chrome-devtools': {
25
- command: 'npx',
26
- // headless: no window pops up (works over SSH too); isolated: its own throwaway profile, so
27
- // runs don't fight over one. Override args in ~/.heart/mcp.json for a visible browser.
28
- args: ['-y', 'chrome-devtools-mcp@latest', '--headless', '--isolated'],
29
- // a screenshot/snapshot saved by a relative path lands in the server's cwd: a scratch dir, not
30
- // the project, so the browser never litters it (pages are opened by absolute file:// URLs).
31
- scratchCwd: true,
32
- description: 'a Chrome browser: open pages, click, fill forms, read the console and network requests, take screenshots',
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
- },
22
+ // Built in: none. HeartCode comes with no MCP servers; you add the ones you want (/settings → MCP
23
+ // servers, /mcp, or ~/.heart/mcp.json). Kept as a map so a server could be built in again by name.
24
+ export const DEFAULT_SERVERS = {}
25
+
26
+ // A server's name from how it's started, so nobody has to make one up: the package or program it
27
+ // runs, without its scope, version and "mcp"/"server" words (npx -y chrome-devtools-mcp@latest →
28
+ // chrome-devtools; uvx mcp-server-fetch → fetch; docker run -i mcp/github → github), or a URL's site
29
+ // (https://mcp.notion.com/mcp → notion). taken: names in use (then -2, -3…). The settings page has a copy.
30
+ const RUNNERS = new Set(['npx', 'bunx', 'pnpx', 'uvx', 'pipx', 'node', 'python', 'python3', 'deno', 'bun', 'docker', 'pnpm', 'yarn', 'uv'])
31
+ const RUNNER_WORDS = new Set(['dlx', 'exec', 'run', 'x', 'tool'])
32
+ export function serverName(given, taken = []) {
33
+ const s = String(given ?? '').trim()
34
+ let base = ''
35
+ if (/^https?:\/\//i.test(s)) {
36
+ try {
37
+ const parts = new URL(s).hostname.replace(/^(www|api|mcp)\./, '').split('.')
38
+ base = parts.length > 1 ? parts.at(-2) : parts[0]
39
+ } catch {}
40
+ } else {
41
+ const words = s.match(/"[^"]*"|'[^']*'|\S+/g)?.map((w) => w.replace(/^(["'])(.*)\1$/, '$2')) ?? []
42
+ const what = words.find((w, i) => !(i === 0 && RUNNERS.has(path.basename(w))) && !w.startsWith('-') && !RUNNER_WORDS.has(w)) ?? words[0] ?? ''
43
+ const pkg = what.replace(/^(@?[^@]+)@.*$/, '$1')
44
+ base = pkg.split(/[\\/]/).pop().replace(/\.(m?js|ts|py)$/, '')
45
+ base = base.replace(/^(mcp[-_]server[-_]|server[-_]|mcp[-_])/, '').replace(/([-_]mcp[-_]server|[-_]mcp|[-_]server)$/, '')
46
+ if (/^(mcp|server|mcp-server)?$/.test(base) && pkg.startsWith('@')) base = pkg.slice(1).split('/')[0] // @playwright/mcp → playwright
47
+ }
48
+ base = base.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '') || 'server'
49
+ let name = base
50
+ for (let n = 2; taken.includes(name); n++) name = `${base}-${n}`
51
+ return name
43
52
  }
44
53
 
45
54
  // extra: more configs from the caller (--mcp-config: a file path or JSON text); strict: only those
package/src/prompts.js CHANGED
@@ -67,6 +67,7 @@ export function prompt(id, vars = {}) {
67
67
  if (!(k in vars)) throw new Error(`prompt "${id}" needs {{${k}}}`)
68
68
  return String(vars[k])
69
69
  })
70
+ .trim() // a part left out ({{#if}}) leaves no blank lines behind
70
71
  }
71
72
 
72
73
  // The user's standing instructions: ~/.heart/HEARTCODE.md, then the project's own file. The project's
package/src/reset.js CHANGED
@@ -21,7 +21,7 @@ export const RESETS = [
21
21
  {
22
22
  level: 'everything',
23
23
  label: 'Everything',
24
- desc: `the above, and your sessions, global memory, skills, instructions (HEARTCODE.md), history, logs: all of ${HOME}`,
24
+ desc: `the above, and global memory, skills, instructions (HEARTCODE.md), history, logs: all of ${HOME} (a project's sessions stay in its .heartcode/sessions)`,
25
25
  files: null, // the whole folder
26
26
  },
27
27
  ]
package/src/sessions.js CHANGED
@@ -1,10 +1,25 @@
1
- // Saved conversations: one file per chat in ~/.heart/sessions, written after every message, so a
2
- // chat can be resumed later and rewound to any earlier message (conversation, files, or both).
1
+ // Saved conversations: one file per chat in the project's .heartcode/sessions, written after every
2
+ // message, so a chat can be resumed later and rewound to any earlier message (conversation, files,
3
+ // or both). It stays with the project; the folder ignores itself in git (conversations can hold
4
+ // secrets). Sessions from before (~/.heart/sessions) still list, and move over when next saved.
3
5
  import fs from 'node:fs'
4
6
  import path from 'node:path'
5
- import { HOME, readJson, writeJson } from './config.js'
7
+ import { HOME, projectDir, readJson, writeJson } from './config.js'
6
8
 
7
- const DIR = path.join(HOME, 'sessions')
9
+ const LEGACY = path.join(HOME, 'sessions') // where they all were; also where one goes if its project folder can't be written
10
+ const INDEX = path.join(HOME, 'sessions.json') // id → its folder, so --resume <id> and an editor's session/load work from anywhere
11
+
12
+ // The project a chat belongs to: a worktree's (<top>/.heartcode/worktrees/<name>) is its top's,
13
+ // so removing the worktree doesn't take its sessions with it.
14
+ const projectOf = (root) => path.resolve(root).replace(/[\\/]\.heartcode[\\/]worktrees[\\/][^\\/]+$/, '')
15
+ function dirOf(root) {
16
+ const dir = projectDir(projectOf(root), 'sessions')
17
+ if (!fs.existsSync(path.join(dir, '.gitignore'))) {
18
+ fs.mkdirSync(dir, { recursive: true })
19
+ fs.writeFileSync(path.join(dir, '.gitignore'), '*\n')
20
+ }
21
+ return dir
22
+ }
8
23
 
9
24
  // A chat: what the model has seen (messages for tool mode, history for guided mode), what the
10
25
  // screen showed (log), and per message ("turn") where each of those stood and the files as they
@@ -16,15 +31,29 @@ export function newChat(root) {
16
31
  }
17
32
 
18
33
  export function saveChat(chat) {
19
- const file = path.join(DIR, `${chat.id}.json`)
34
+ const legacy = path.join(LEGACY, `${chat.id}.json`)
35
+ let dir = LEGACY
36
+ try {
37
+ dir = dirOf(chat.root)
38
+ } catch {} // a folder that can't be written (read-only, gone): the global one
39
+ const file = path.join(dir, `${chat.id}.json`)
20
40
  const first = chat.turns[0] ?? chat.branches?.[0]?.state.turns[0] // gone back to the start: its branches remain
21
41
  if (!first) {
22
42
  fs.rmSync(path.join(HOME, 'outputs', chat.id), { recursive: true, force: true }) // its saved tool output goes with it
43
+ fs.rmSync(legacy, { force: true })
23
44
  return fs.rmSync(file, { force: true }) // nothing (left) worth keeping
24
45
  }
25
46
  chat.updated = new Date().toISOString()
26
47
  chat.title = chat.name || first.task.split('\n')[0].slice(0, 80) // its name (/rename), else the first message, even after a rewind
27
- writeJson(file, chat)
48
+ try {
49
+ writeJson(file, chat)
50
+ } catch {
51
+ dir = LEGACY
52
+ writeJson(legacy, chat)
53
+ }
54
+ if (dir !== LEGACY) fs.rmSync(legacy, { force: true }) // an older session, now moved into its project
55
+ const index = readJson(INDEX, {})
56
+ if (index[chat.id] !== dir) writeJson(INDEX, { ...index, [chat.id]: dir })
28
57
  }
29
58
 
30
59
  // /fork: a copy of the chat to go on with (the original stays as it is, in /resume).
@@ -94,20 +123,30 @@ ${body.join('\n')}
94
123
  `
95
124
  }
96
125
 
97
- // One chat by its id (any folder), or null.
98
- export function loadChat(id) {
99
- return /^[\w.-]+$/.test(id) ? readJson(path.join(DIR, `${id}.json`), null) : null
126
+ // One chat by its id, or null: in this folder's project, wherever the index last saw it, or the old place.
127
+ export function loadChat(id, root = process.cwd()) {
128
+ if (!/^[\w.-]+$/.test(id)) return null
129
+ const here = projectDir(projectOf(root), 'sessions')
130
+ for (const dir of new Set([here, readJson(INDEX, {})[id], LEGACY].filter(Boolean))) {
131
+ const chat = readJson(path.join(dir, `${id}.json`), null)
132
+ if (chat) return chat
133
+ }
134
+ return null
100
135
  }
101
136
 
102
- // This folder's chats, newest first.
103
- export function listChats(root) {
104
- let files = []
137
+ const chatsIn = (dir) => {
105
138
  try {
106
- files = fs.readdirSync(DIR).filter((f) => f.endsWith('.json'))
107
- } catch {}
108
- return files
109
- .map((f) => readJson(path.join(DIR, f), null))
110
- .filter((c) => c && c.root === root && (c.turns?.length || c.branches?.length))
139
+ return fs.readdirSync(dir).filter((f) => f.endsWith('.json')).map((f) => readJson(path.join(dir, f), null))
140
+ } catch {
141
+ return []
142
+ }
143
+ }
144
+
145
+ // This folder's chats, newest first: the project's own, and older ones still in the global place.
146
+ export function listChats(root) {
147
+ const seen = new Set()
148
+ return [...chatsIn(projectDir(projectOf(root), 'sessions')), ...chatsIn(LEGACY)]
149
+ .filter((c) => c && c.root === root && (c.turns?.length || c.branches?.length) && !seen.has(c.id) && seen.add(c.id))
111
150
  .sort((a, b) => b.updated.localeCompare(a.updated))
112
151
  }
113
152