heartcode 0.1.58 → 0.1.60

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/config.js CHANGED
@@ -31,9 +31,9 @@ export function speedOf(cfg) {
31
31
  // what the pill covers (its tooltip)]
32
32
  export const HELPER_JOBS = {
33
33
  ui: ['UI & visuals', 'websites, app screens, games, animation, 3D, charts', 'Websites and landing pages, app screens, games and animation, 3D, charts and SVG: anything people look at.'],
34
- code: ['Code & logic', 'backend, APIs, scripts, automation, fixing bugs, tests, reviewing changes', 'Backend and APIs, scripts and automation, fixing bugs, tests and refactoring. Reviews of the work go to these first.'],
34
+ code: ['Code & logic', 'backend, APIs, scripts, automation, fixing bugs, tests, reviewing changes', 'Backend and APIs, scripts and automation, fixing bugs, tests and refactoring. Reviews of the work go to these first, then to the other models.'],
35
35
  hard: ['Big & hard', 'hard thinking, planning, long tasks with many steps, huge files', 'Planning and architecture, tricky logic, long tasks with many steps, huge files or whole folders.'],
36
- quick: ['Quick & cheap', 'small jobs: searching and reading code, lookups, small edits', 'Searching and reading code, looking things up, small edits: simple jobs where fast and cheap matter most.'],
36
+ quick: ['Quick & cheap', 'small jobs: searching and reading code, lookups, small edits', 'Searching and reading code, looking things up, small edits: simple jobs, on a model that answered fast.'],
37
37
  }
38
38
  // a helper's jobs as saved, in today's names (picks from before the four: search, research → quick, review → code)
39
39
  const WAS = { search: 'quick', research: 'quick', review: 'code' }
@@ -146,7 +146,7 @@ export function loadConfig(flags = {}) {
146
146
  const model = flags.model || process.env.HEART_MODEL
147
147
  if (model && !isAuto(model)) Object.assign(cfg, parseModel(model, cfg.providers, cfg.provider))
148
148
  // -m / an ad-hoc URL pins the chosen model for this run (a session of one): cfg.session, below
149
- if ((baseUrl || (model && !isAuto(model))) && cfg.providers[cfg.provider] && cfg.model) cfg.session = [{ provider: cfg.provider, model: cfg.model }]
149
+ if ((baseUrl || (model && !isAuto(model))) && cfg.providers[cfg.provider] && cfg.model) Object.assign(cfg, { session: [{ provider: cfg.provider, model: cfg.model }], pinned: true }) // pinned: asked for by name, so it runs even if its provider is switched off
150
150
  synced(cfg, readJson(CONFIG_FILE, {}))
151
151
  return cfg
152
152
  }
package/src/context.js CHANGED
@@ -85,7 +85,7 @@ export function contextSource(p, cfg = {}) {
85
85
  if (from === 'server') return `reported by the server${p.server ? ` (${p.server})` : ''}`
86
86
  if (from === 'models.dev') return "models.dev's published limit for this model"
87
87
  if (from === 'learned') return 'learned from the server refusing or cutting a bigger request'
88
- if (from === 'rate') return `your per-minute token cap at this provider, until ${new Date(p.rateCap.until).toLocaleString()}`
88
+ if (from === 'rate') return `the account's per-minute token cap at this provider, until ${new Date(p.rateCap.until).toLocaleString()}`
89
89
  if (LOCAL_SERVERS.includes(p.server)) return `the ${p.server} server doesn't say; assumed`
90
90
  return `the server doesn't say; assumed${p.largestAccepted ? `, and seen working up to ${p.largestAccepted} tokens` : ''} (grows as bigger requests work)`
91
91
  }
package/src/guided.js CHANGED
@@ -13,12 +13,13 @@ import { runHooks } from './hooks.js'
13
13
  import { foldersOf } from './agent.js'
14
14
  import { c } from './ui.js'
15
15
 
16
- // The steps, as "name: description" lines in prompts/guided/actions.md.
17
- const ACTIONS = prompt('guided/actions')
18
- .split('\n')
19
- .map((l) => l.split(/:\s*/, 2))
20
- .filter(([n, d]) => n && d)
21
- const DESC = Object.fromEntries(ACTIONS)
16
+ // The steps, as "name: description" lines in prompts/guided/actions.md (read each time: a project's
17
+ // own prompts and the settings page's edits apply at once)
18
+ const actions = () =>
19
+ prompt('guided/actions')
20
+ .split('\n')
21
+ .map((l) => l.split(/:\s*/, 2))
22
+ .filter(([n, d]) => n && d)
22
23
  const TEST_FILE = /(^|[/._-])(tests?|spec|__tests__)([/._-]|$)/i
23
24
 
24
25
  // Obvious next steps are taken without asking: a weak model's effort goes into
@@ -39,7 +40,7 @@ export function nextActions(st) {
39
40
  if (!st.reads && st.hasFiles) first = ['read', 'search']
40
41
  else if (st.wantsChange && !st.edits) first = st.hasFiles ? ['edit', 'create', 'read'] : ['create']
41
42
  else first = ['finish', 'edit', 'run']
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)
43
+ 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)
43
44
  }
44
45
 
45
46
  // A reply may be plain text or JSON like {"path": "a.js"}.
@@ -264,7 +265,8 @@ class Guided {
264
265
 
265
266
  async start(images) {
266
267
  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
+ const team = this.s.team?.() ?? []
269
+ this.st.canDelegate = Boolean((team.some((t) => t.jobs) ? team.filter((t) => t.jobs) : team).some((t) => t.tools && (!this.images || t.images))) // one that sees them, with images; your helpers when you ticked some
268
270
  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)
269
271
  if (images.length) await this.describeImages(images)
270
272
  this.autoRead()
@@ -273,7 +275,8 @@ class Guided {
273
275
  let last = ''
274
276
  let repeats = 0
275
277
  // No step limit (Esc stops it); a model doing the same thing three times in a row is stopped.
276
- for (let step = 0; !this.s.maxTurns || step < this.s.maxTurns; step++) {
278
+ let step = 0
279
+ for (; !this.s.maxTurns || step < this.s.maxTurns; step++) {
277
280
  this.ui.spinner('deciding next step')
278
281
  const auto = autoAction(this.st)
279
282
  const action = auto ?? (await this.pickAction())
@@ -310,6 +313,10 @@ class Guided {
310
313
  }
311
314
  if (repeats === 1) this.note(null, 'warning', prompt('guided/note-repeated'))
312
315
  }
316
+ if (this.s.maxTurns && step >= this.s.maxTurns) {
317
+ if (!this.s.isSub) this.ui.warn(`stopped after ${this.s.maxTurns} steps (--max-turns); say "continue" to go on`)
318
+ throw Object.assign(new Error(`stopped after ${this.s.maxTurns} steps (--max-turns)`), { maxTurns: true })
319
+ }
313
320
  const answer = await this.finish()
314
321
  this.s.wrapUpLater?.(this.task, answer) // after the answer, beside what comes next (skipped for helpers and without memory)
315
322
  return answer
@@ -320,7 +327,7 @@ class Guided {
320
327
  async tool(name, args, run) {
321
328
  const { s } = this
322
329
  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) } }] })
330
+ s.onEvent?.({ type: 'assistant', model: `${s.client.provider}/${s.client.model}`, content: '', toolCalls: [{ id, type: 'function', function: { name, arguments: JSON.stringify(args) } }], stop: 'tool_calls' })
324
331
  let out
325
332
  const pre = allowed(s, name) && (await runHooks(s, 'PreToolUse', { tool_name: name, tool_input: args }, this.signal))
326
333
  const notMine = name === 'write_file' && s.ownFiles && !s.ownFiles.includes(path.resolve(s.root, args.path))
@@ -333,7 +340,7 @@ class Guided {
333
340
  if (post.block) out += `\n\n${prompt('agent/hook', { reason: post.block, after: true })}`
334
341
  }
335
342
  if (!pre || pre.block || notMine) this.ui.result(c.red(clip(out, 120)))
336
- s.onEvent?.({ type: 'tool', id, name, output: out })
343
+ s.onEvent?.({ type: 'tool', id, name, output: out, model: `${s.client.provider}/${s.client.model}` })
337
344
  return out
338
345
  }
339
346
 
@@ -358,14 +365,15 @@ class Guided {
358
365
  readNote(f, quiet = false) {
359
366
  const body = readFileTool(this.s.root, f, 1, undefined, 2000)
360
367
  this.note(`read:${f}`, `contents of ${f}`, clip(body, Math.floor(this.s.strat.context * 3.5 * 0.4)))
361
- if (!quiet) this.ui.step('read', f)
368
+ if (!quiet) this.ui.step('read', f, this.s.client.model)
362
369
  this.st.reads++
363
370
  return body
364
371
  }
365
372
 
366
373
  async pickAction() {
367
374
  const names = nextActions(this.st)
368
- const menu = names.map((n, i) => `${i + 1}. ${n} - ${DESC[n]}`).join('\n')
375
+ const desc = Object.fromEntries(actions())
376
+ const menu = names.map((n, i) => `${i + 1}. ${n} - ${desc[n]}`).join('\n')
369
377
  let q = prompt('guided/next-action', { menu, reply: '', count: names.length })
370
378
  for (let i = 0; i < 2; i++) {
371
379
  const res = await this.query(q, { room: 16, oneLine: true })
@@ -408,7 +416,7 @@ class Guided {
408
416
  const res = await this.query(prompt('guided/search'), { room: 40, oneLine: true })
409
417
  const q = unquote(answerText(res.content).split('\n')[0].trim())
410
418
  if (!q) return 'search:'
411
- this.ui.step('search', q)
419
+ this.ui.step('search', q, this.s.client.model)
412
420
  const out = await this.tool('search', { query: q }, () => searchFiles(this.s.root, q))
413
421
  this.ui.result(out.startsWith('no matches') ? 'no matches' : `${out.split('\n').length} matches`)
414
422
  this.note(`search:${q}`, `search results for "${q}"`, out)
@@ -424,7 +432,7 @@ class Guided {
424
432
  let f = await this.pickFile(true, files)
425
433
  if (!f) return 'edit:'
426
434
  const old = fs.readFileSync(resolveIn(this.s.root, f), 'utf8')
427
- this.ui.step('edit', f)
435
+ this.ui.step('edit', f, this.s.client.model)
428
436
  let next = null
429
437
  next = await this.editBlocks(f, old)
430
438
  if (next === null) next = await this.editRewrite(f, old)
@@ -546,7 +554,7 @@ class Guided {
546
554
  if (!rel) return 'create:'
547
555
  const abs = resolveIn(this.s.root, rel)
548
556
  const f = path.relative(this.s.root, abs)
549
- this.ui.step('create', f)
557
+ this.ui.step('create', f, this.s.client.model)
550
558
  if (fs.existsSync(abs)) {
551
559
  const old = fs.readFileSync(abs, 'utf8')
552
560
  const next = await this.editRewrite(f, old)
@@ -600,7 +608,8 @@ class Guided {
600
608
  // Another of your models, one with tool calls, does the whole task; what it did goes in the notes.
601
609
  async delegate() {
602
610
  // 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)).sort((a, b) => Boolean(b.jobs) - Boolean(a.jobs)) // your helpers first
611
+ const all = this.s.team()
612
+ const team = (all.some((t) => t.jobs) ? all.filter((t) => t.jobs) : all).filter((t) => t.tools && (!this.images || t.images)) // your helpers, when you ticked some
604
613
  const t = team[0]
605
614
  const args = { description: 'the task', prompt: this.task, model: `${t.provider} ${t.model}` }
606
615
  const done = await this.tool('agent', args, (id) => this.s.subagent(args, this.signal, id))
package/src/headless.js CHANGED
@@ -7,16 +7,25 @@
7
7
  // stdin: {"type":"user","message":{"role":"user","content":"…"}} one per line, any number
8
8
  // {"type":"control_request","request_id":"1","request":{"subtype":"interrupt"}}
9
9
  // stdout: {"type":"system","subtype":"init",…}, {"type":"assistant",…}, {"type":"user",…}
10
- // (tool results), {"type":"result",…} after each message
10
+ // (tool results), {"type":"result",…} after each message; and what the full screen
11
+ // shows besides, as {"type":"system","subtype":…}: "todos" (the plan: content, status,
12
+ // why: a stuck step's reason, by: the model a part went to), "stuck" (the model says it's
13
+ // stuck: step, why, count, model), "helper" (one at work: tool_use_id, label, model, status;
14
+ // "done" at its end), "review" (model, verdict yes/no, issues), "model_switch" (from, to,
15
+ // reason), "warning" (message), "retry" (attempt, delay_ms, error), "status" (what it's
16
+ // doing now, as the spinner says it: a running command's latest output line too)
11
17
  // Nothing asks anything: what the permission mode would ask about is declined, with the reason
12
- // told to the model. Logs and warnings go to stderr (and HEART_LOG), never stdout.
18
+ // told to the model. Logs go to their files (or HEART_LOG), never stdout; warnings and retries go to
19
+ // stderr with --verbose (and, in stream-json, as system lines).
13
20
  import readline from 'node:readline'
14
21
  import { log } from './log.js'
15
22
  import { clip, TOOL_DEFS, extraTools, loadMcpTools, mcpName, failed as toolFailed } from './tools.js'
16
23
  import { allowed } from './agent.js'
17
24
 
25
+ const plain = (t) => String(t ?? '').replace(/\x1b\[[0-9;]*m/g, '')
26
+
18
27
  // Claude Code's tool names → HeartCode's (for --allowedTools / --disallowedTools).
19
- const CLAUDE_TOOLS = { Read: 'read_file', Grep: 'search', Glob: 'list_files', LS: 'list_files', Edit: 'edit_file', MultiEdit: 'edit_file', Write: 'write_file', NotebookEdit: 'edit_file', Bash: 'run_command', BashOutput: 'background', KillShell: 'background', KillBash: 'background' }
28
+ const CLAUDE_TOOLS = { Read: 'read_file', Grep: 'search', Glob: 'list_files', LS: 'list_files', Edit: 'edit_file', MultiEdit: 'edit_file', Write: 'write_file', NotebookEdit: 'edit_file', Bash: 'run_command', BashOutput: 'background', KillShell: 'background', KillBash: 'background', WebFetch: 'web_fetch', WebSearch: 'web_search', TodoWrite: 'todo', Task: 'agent' }
20
29
  export function toolNames(list) {
21
30
  const names = list.flatMap((x) => String(x).split(/[,\s]+/)).filter(Boolean).map((t) => t.replace(/\(.*$/, '')) // ponytail: "Bash(git:*)" allows every command, not just git
22
31
  return new Set(names.map((t) => CLAUDE_TOOLS[t] ?? t)) // mcp__server__tool and mcp__server as they are (tools.js allowed)
@@ -25,10 +34,24 @@ export function toolNames(list) {
25
34
  // --permission-mode, in HeartCode's terms or Claude Code's.
26
35
  export const PERMISSION_MODES = { all: 'all', commands: 'commands', ask: 'ask', bypassPermissions: 'all', acceptEdits: 'commands', default: 'ask', plan: 'plan', dontAsk: 'ask' }
27
36
 
28
- // A UI that shows nothing and asks nobody.
37
+ // A UI that shows nothing and asks nobody; what the full screen would show goes to this.event (set
38
+ // by stream-json: a system message each) as data.
29
39
  export class HeadlessUI {
30
40
  constructor({ permission = 'all', verbose = false } = {}) {
31
- Object.assign(this, { permission, verbose, log: [], showThinking: true, full: false, noUser: true })
41
+ Object.assign(this, { permission, verbose, log: [], showThinking: true, full: false, noUser: true, event: null })
42
+ // helpers at work (agent.js: label → { id, model, what }): each change sent as a "helper" event
43
+ const ui = this
44
+ this.helpers = new (class extends Map {
45
+ set(label, v) {
46
+ ui.event?.({ subtype: 'helper', tool_use_id: v?.id ?? null, label, model: v?.model ?? null, status: v?.what ?? null })
47
+ return super.set(label, v)
48
+ }
49
+ delete(label) {
50
+ const v = this.get(label)
51
+ if (v) ui.event?.({ subtype: 'helper', tool_use_id: v.id ?? null, label, model: v.model ?? null, status: 'done' })
52
+ return super.delete(label)
53
+ }
54
+ })()
32
55
  }
33
56
  #err(text) {
34
57
  if (this.verbose) process.stderr.write(`${text}\n`)
@@ -36,9 +59,28 @@ export class HeadlessUI {
36
59
  warn(text) {
37
60
  log('warn', text)
38
61
  this.#err(`heartcode: ${text}`)
62
+ this.event?.({ subtype: 'warning', message: plain(text) })
39
63
  }
40
64
  retrying(err, ms, attempt) {
41
65
  if (err) this.#err(`heartcode: retrying in ${Math.ceil(ms / 1000)}s (attempt ${attempt}): ${err.message}`)
66
+ if (err) this.event?.({ subtype: 'retry', attempt, delay_ms: ms, error: plain(err.message) })
67
+ }
68
+ // What it's doing now, as the spinner would say it: sent when it changes (a label that's a function,
69
+ // a running command's latest line: read once a second)
70
+ spinner(label) {
71
+ clearInterval(this.spinTimer)
72
+ const say = () => {
73
+ const text = plain(typeof label === 'function' ? label() : label)
74
+ // model: a helper's when it's that helper's ("<its job> · …"), else the main conversation's
75
+ const helper = [...this.helpers].find(([job]) => text.startsWith(`${job} · `))?.[1]
76
+ if (text && text !== this.said) this.event?.({ subtype: 'status', status: (this.said = text), model: helper?.model ?? this.waitingFor?.() ?? null })
77
+ }
78
+ say()
79
+ if (typeof label === 'function') this.spinTimer = setInterval(say, 1000).unref() // never what keeps a finished run going
80
+ }
81
+ stopSpin() {
82
+ clearInterval(this.spinTimer)
83
+ this.said = null
42
84
  }
43
85
  async confirm(question, kind = 'edit') {
44
86
  if (this.permission === 'all' || (this.permission === 'commands' && kind === 'edit') || (this.permission === 'plan' && kind === 'read')) return true // plan: only reading
@@ -82,8 +124,6 @@ export class HeadlessUI {
82
124
  async pick() {
83
125
  return null
84
126
  }
85
- spinner() {}
86
- stopSpin() {}
87
127
  print() {}
88
128
  write() {}
89
129
  gap() {}
@@ -110,7 +150,7 @@ export async function runHeadless(app, opts) {
110
150
  const emit = (obj) => process.stdout.write(JSON.stringify(obj) + '\n')
111
151
  const s = await app.session()
112
152
  if (!s) {
113
- const error = app.allOff() ? "the providers of all your models are switched off: switch one on (heart settings), or pass --model" : 'no model set up: add a provider and choose a model (heart settings), or pass --base-url and --model'
153
+ const error = app.allOff() ? "the providers of all the models are switched off: switch one on (heart settings), or pass --model" : 'no model set up: add a provider and choose a model (heart settings), or pass --base-url and --model'
114
154
  if (out === 'text') process.stderr.write(`heartcode: ${error}\n`)
115
155
  else emit({ type: 'result', subtype: 'error_during_execution', is_error: true, result: error, num_turns: 0, session_id: app.chat.id })
116
156
  return 1
@@ -150,9 +190,14 @@ export async function runHeadless(app, opts) {
150
190
  // its own arguments, not HeartCode's one mcp tool around them (a program reading it, Nibedita,
151
191
  // knows its tools by those names).
152
192
  const asClaude = (name, input) => (name === 'mcp' && input?.server && input?.tool ? { name: mcpName(String(input.server), String(input.tool)), input: input.arguments ?? {} } : { name, input })
153
- let said = false // the model's text was already sent as an assistant message
193
+ let said = '' // the main conversation's last text sent as an assistant message
194
+ // why a reply ended, in Claude's words (stop_reason)
195
+ const STOP = { stop: 'end_turn', tool_calls: 'tool_use', function_call: 'tool_use', length: 'max_tokens', incomplete: 'max_tokens', content_filter: 'refusal', loop: 'end_turn' }
196
+ const stopOf = (r) => (r ? (STOP[r] ?? r) : null)
154
197
  if (out === 'stream-json') {
155
198
  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)
199
+ app.ui.event = (e) => emit({ type: 'system', ...e, session_id })
200
+ app.ui.waitingFor = () => `${s.client.provider}/${s.client.model}` // the model at work now, on status events // the plan, helpers, reviews, model switches, warnings, retries, status
156
201
  s.onEvent = (e) => {
157
202
  if (e.type === 'assistant') {
158
203
  const content = [
@@ -160,11 +205,11 @@ export async function runHeadless(app, opts) {
160
205
  ...(e.content ? [{ type: 'text', text: e.content }] : []),
161
206
  ...e.toolCalls.map((t) => ({ type: 'tool_use', id: t.id, ...asClaude(t.function.name, parseArgs(t.function.arguments)) })),
162
207
  ]
163
- if (e.content && !e.parent) said = true
208
+ if (e.content && !e.parent) said = e.content
164
209
  // a helper's (agent) steps too, as Claude Code sends a subagent's: parent_tool_use_id is its agent call
165
- if (content.length) emit({ type: 'assistant', message: { role: 'assistant', model: e.model ?? model, content }, parent_tool_use_id: e.parent ?? null, session_id })
210
+ if (content.length) emit({ type: 'assistant', message: { role: 'assistant', model: e.model ?? model, content, stop_reason: stopOf(e.stop) }, parent_tool_use_id: e.parent ?? null, session_id })
166
211
  } else if (e.type === 'tool') {
167
- emit({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: e.id, content: e.output, is_error: toolFailed(e.output) }] }, parent_tool_use_id: e.parent ?? null, session_id })
212
+ emit({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: e.id, content: e.output, is_error: toolFailed(e.output) }] }, model: e.model ?? null, parent_tool_use_id: e.parent ?? null, session_id }) // model: the one that made the call
168
213
  }
169
214
  }
170
215
  if (s.strat.actions === 'tools' && s.mcp?.names.length) await loadMcpTools(s) // their tools are in the list, as in Claude Code's
@@ -180,7 +225,8 @@ export async function runHeadless(app, opts) {
180
225
  usage = { input_tokens: 0, output_tokens: 0 }
181
226
  byModel = {}
182
227
  requests = 0
183
- said = false
228
+ said = ''
229
+ s.lastStop = null
184
230
  current = { ctl: new AbortController() }
185
231
  app.signal = current.ctl.signal
186
232
  app.working = true // settings changed meanwhile: MCP servers and skills wait for the end of it
@@ -201,9 +247,11 @@ export async function runHeadless(app, opts) {
201
247
  }
202
248
  const subtype = current.maxTurns ? 'error_max_turns' : error ? 'error_during_execution' : 'success' // as Claude Code names them
203
249
  current = null
204
- const result = { type: 'result', subtype, is_error: Boolean(error), result: error ?? answer, num_turns: Math.max(1, requests), duration_ms: Date.now() - t0, total_cost_usd: (app.chat.usage?.cost ?? 0) - spent, usage, modelUsage: Object.keys(byModel).length ? byModel : { [model]: { inputTokens: 0, outputTokens: 0 } }, session_id }
250
+ const result = { type: 'result', subtype, is_error: Boolean(error), result: error ?? answer, stop_reason: error ? null : stopOf(s.lastStop ?? 'stop'), num_turns: Math.max(1, requests), duration_ms: Date.now() - t0, total_cost_usd: (app.chat.usage?.cost ?? 0) - spent, usage, modelUsage: Object.keys(byModel).length ? byModel : { [model]: { inputTokens: 0, outputTokens: 0 } }, session_id }
205
251
  if (out === 'stream-json') {
206
- if (!error && answer && !said) emit({ type: 'assistant', message: { role: 'assistant', model: `${s.client.provider}/${s.client.model}`, content: [{ type: 'text', text: answer }] }, parent_tool_use_id: null, session_id }) // guided mode
252
+ // the answer as a reply of its own, unless it just went out as one (as it was: a cut-off answer is
253
+ // its pieces together; guided mode, an answer made after empty replies: never sent)
254
+ if (!error && answer && said.trim() !== answer.trim()) emit({ type: 'assistant', message: { role: 'assistant', model: `${s.client.provider}/${s.client.model}`, content: [{ type: 'text', text: answer }], stop_reason: stopOf(s.lastStop ?? 'stop') }, parent_tool_use_id: null, session_id })
207
255
  emit(result)
208
256
  } else if (out === 'json') emit(result)
209
257
  else if (error) process.stderr.write(`heartcode: ${error}\n`)
package/src/importer.js CHANGED
@@ -65,7 +65,7 @@ function skillBodies(root, scope) {
65
65
  function skillDup(root, scope, name, body) {
66
66
  if (taken(root, scope, name)) return `a skill named ${name} is already there`
67
67
  const twin = skillBodies(root, scope).find(([, b]) => same(b, body))
68
- return twin ? `the same as your skill ${twin[0]}` : ''
68
+ return twin ? `the same as the skill ${twin[0]}` : ''
69
69
  }
70
70
 
71
71
  // A markdown command (Claude Code, Codex, OpenCode) → a HeartCode skill you type ("use: me").
@@ -109,7 +109,7 @@ function mcpDup(root, scope, name, cfg) {
109
109
  const have = readJson(mcpFile(root, scope), {}).mcpServers ?? {}
110
110
  if (have[name]) return `an MCP server named ${name} is already there`
111
111
  const twin = Object.entries(have).find(([, c]) => serverKey(c) === serverKey(cfg))
112
- return twin ? `the same server as your ${twin[0]}` : ''
112
+ return twin ? `the same server as ${twin[0]}` : ''
113
113
  }
114
114
 
115
115
  function importMcp(root, scope, name, cfg) {
@@ -189,13 +189,13 @@ export function findImports(root, home = os.homedir()) {
189
189
  for (const [rel, file] of filesIn(dir, ['.md'])) {
190
190
  const name = safe(rel)
191
191
  const { meta, body } = frontMatter(fs.readFileSync(file, 'utf8'))
192
- 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))
192
+ add(`${tool} · ${scope === 'global' ? 'global' : 'this project'} · commands`, `/${name}`, (meta.description || body.split('\n')[0]).slice(0, 90), () => importCommand(root, scope, name, file), () => skillDup(root, scope, name, body))
193
193
  }
194
194
  }
195
195
  for (const [scope, dir] of [['project', path.join(root, '.gemini', 'commands')], ['global', path.join(home, '.gemini', 'commands')]]) {
196
196
  for (const [rel, file] of filesIn(dir, ['.toml'])) {
197
197
  const name = safe(rel)
198
- 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` : ''))
198
+ add(`Gemini CLI · ${scope === 'global' ? 'global' : '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` : ''))
199
199
  }
200
200
  }
201
201
  const skillSources = [
@@ -212,7 +212,7 @@ export function findImports(root, home = os.homedir()) {
212
212
  const file = path.join(dir, e.name, 'SKILL.md')
213
213
  if (!e.isDirectory() || !exists(file)) continue
214
214
  const { meta, body } = frontMatter(fs.readFileSync(file, 'utf8'))
215
- 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))
215
+ add(`${tool} · ${scope === 'global' ? 'global' : '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))
216
216
  }
217
217
  }
218
218
  const claudeJson = readJson(path.join(home, '.claude.json'), {})
@@ -229,11 +229,11 @@ export function findImports(root, home = os.homedir()) {
229
229
  for (const [tool, scope, servers] of mcpSources) {
230
230
  for (const [name, cfg] of Object.entries(servers ?? {})) {
231
231
  if (!cfg?.command && !cfg?.url && !cfg?.httpUrl) continue
232
- 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))
232
+ add(`${tool} · ${scope === 'global' ? 'global' : '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))
233
233
  }
234
234
  }
235
235
  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')]]) {
236
- if (exists(file)) add(`${tool} · yours · instructions`, path.basename(file), `your ${tool} instructions → ~/.heart/HEARTCODE.md`, () => importInstructions(file, tool))
236
+ if (exists(file)) add(`${tool} · global · instructions`, path.basename(file), `${tool} instructions → ~/.heart/HEARTCODE.md`, () => importInstructions(file, tool))
237
237
  }
238
238
  const claudeMemory = path.join(home, '.claude', 'projects', root.replace(/[^a-zA-Z0-9]/g, '-'), 'memory')
239
239
  const notes = filesIn(claudeMemory, ['.md']).filter(([n]) => n !== 'MEMORY')
package/src/log.js CHANGED
@@ -24,11 +24,11 @@ export const LOG_DIR = process.env.HEART_LOG === 'off' ? null : path.resolve(pro
24
24
  // The kinds of text log, what each is for, and which topics (log('topic', …)) go in it. A topic not
25
25
  // listed goes in debug.
26
26
  export const LOG_KINDS = {
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'] },
27
+ tools: { label: 'Tools & commands', about: 'what HeartCode did on this 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
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
- conversation: { label: 'Conversation', about: 'a plain transcript: what you typed, its answers, its questions and your answers', topics: ['input', 'ask', 'answer'] },
31
+ conversation: { label: 'Conversation', about: 'a plain transcript: the messages typed, the answers, its questions and the replies', topics: ['input', 'ask', 'answer'] },
32
32
  debug: { label: 'Debug', about: 'everything else, for a bug report: HTTP, settings, voice, Telegram, sign-ins, tabs, headless and ACP', topics: [] },
33
33
  }
34
34
  const KIND_OF = Object.fromEntries(Object.entries(LOG_KINDS).flatMap(([k, v]) => v.topics.map((t) => [t, k])))
@@ -147,7 +147,7 @@ const safe = (s) => String(s ?? '').replace(/[^\w.-]+/g, '_').slice(0, 60) || 'n
147
147
  // firstTokenMs, usage, request, reply }. "full" keeps what was sent and what came back; "summary"
148
148
  // only their sizes. API keys are never in it (they're headers, not the body).
149
149
  export function logRequest(rec) {
150
- if (!requestLog.on) return
150
+ if (!requestLog.on || process.env.HEART_LOG === 'off') return // HEART_LOG=off: no logs of any kind
151
151
  try {
152
152
  if (!requestLog.dir) {
153
153
  let dir = path.join(REQUESTS, STAMP)
package/src/mcp.js CHANGED
@@ -209,7 +209,7 @@ class Server {
209
209
 
210
210
  #signIn(how, signal) {
211
211
  const open = this.hub.onSignIn
212
- if (!open) throw new Error(`${this.name} needs you to sign in: start heartcode and run /login_mcp ${this.name}`)
212
+ if (!open) throw new Error(`${this.name} needs a sign-in first: start heartcode and run /login_mcp ${this.name}`)
213
213
  return signIn(this.url, how, (link) => open(this.name, link), { signal, oauth: this.cfg.oauth })
214
214
  }
215
215
 
package/src/memory.js CHANGED
@@ -137,7 +137,7 @@ class Notes {
137
137
  // Keeps MEMORY.md in step with the notes.
138
138
  changed() {
139
139
  fs.mkdirSync(this.dir, { recursive: true })
140
- const what = this.scope === 'global' ? 'The notes HeartCode keeps about you, for every project' : "This project's notes, kept by HeartCode"
140
+ const what = this.scope === 'global' ? 'The notes HeartCode keeps about the user, for every project' : "This project's notes, kept by HeartCode"
141
141
  fs.writeFileSync(path.join(this.dir, 'MEMORY.md'), `# Memory\n\n${what}. Each line links to a note.\n\n${this.index(Infinity) || '(no notes yet)'}\n`)
142
142
  }
143
143
  }
package/src/oauth.js CHANGED
@@ -108,7 +108,7 @@ export async function signIn(url, wwwAuth, open, { signal, oauth = {} } = {}) {
108
108
  const q = new URL(req.url, redirect)
109
109
  if (q.pathname !== '/callback') return res.writeHead(404).end()
110
110
  const ok = q.searchParams.get('state') === state && q.searchParams.get('code')
111
- res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(`<!doctype html><meta charset="utf-8"><title>HeartCode</title><body style="font:16px system-ui;padding:40px">${ok ? '♥ Signed in. You can close this tab and go back to HeartCode.' : `Sign-in failed: ${String(q.searchParams.get('error_description') ?? q.searchParams.get('error') ?? 'wrong state').replace(/</g, '&lt;')}`}</body>`)
111
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(`<!doctype html><meta charset="utf-8"><title>HeartCode</title><body style="font:16px system-ui;padding:40px">${ok ? '♥ Signed in. This tab can be closed now.' : `Sign-in failed: ${String(q.searchParams.get('error_description') ?? q.searchParams.get('error') ?? 'wrong state').replace(/</g, '&lt;')}`}</body>`)
112
112
  clearTimeout(timer)
113
113
  ok ? resolve(ok) : reject(new Error(`sign-in failed: ${q.searchParams.get('error_description') ?? q.searchParams.get('error') ?? 'the reply did not match'}`))
114
114
  })
package/src/probe.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // A model's profile (what it can do: models.dev's word, or your settings) and how HeartCode talks to it.
2
+ import fs from 'node:fs'
2
3
  import path from 'node:path'
3
4
  import { HOME, readJson } from './config.js'
4
5
  import { contextWindow, contextSource, ASSUMED_REMOTE, LIMIT_MS } from './context.js'
@@ -13,8 +14,17 @@ export const profilePath = (client) => {
13
14
  }
14
15
  // Bump when a profile's shape changes, so older saved ones are made again once.
15
16
  const PROBE_VERSION = 2
17
+ // Kept in memory by file and its time: a page listing thousands of models reads only the ones that
18
+ // changed (a test, a setup, another HeartCode), not every file every time.
19
+ const profiles = new Map() // file → { at: its mtime, p }
16
20
  export const loadProfile = (client) => {
17
- const p = readJson(profilePath(client), null)
21
+ const file = profilePath(client)
22
+ const st = fs.statSync(file, { throwIfNoEntry: false })
23
+ if (!st) return profiles.delete(file), null
24
+ const at = `${st.mtimeMs}:${st.size}` // the size too: a file system that keeps times to the second
25
+ let hit = profiles.get(file)
26
+ if (hit?.at !== at) profiles.set(file, (hit = { at, p: readJson(file, null) }))
27
+ const p = hit.p && structuredClone(hit.p) // a copy, as a read gave: a caller may change it before writing
18
28
  // another model's (a model list switch once saved the first model's profile under the next one's name)
19
29
  return p?.version === PROBE_VERSION && (!p.model || p.model === client.model) ? p : null
20
30
  }
@@ -48,9 +58,9 @@ export function strategy(p, cfg = {}) {
48
58
 
49
59
  export function describe(p, s) {
50
60
  const yn = (v) => (v ? c.green('yes') : c.red('no'))
51
- const context = ['context', `${s.context}${c.dim(` (${p.set?.context ? 'set by you on /settings' : contextSource(p)}; change it on /settings)`)}`]
52
- const from = { 'models.dev': 'models.dev', you: 'you, on /settings', assumed: "nothing: it isn't in models.dev. Set what it can do on /settings" }[p.source] ?? 'an earlier test'
53
- const mine = (k) => (p.set?.[k] !== undefined ? c.dim(' (set by you)') : '')
61
+ const context = ['context', `${s.context}${c.dim(` (${p.set?.context ? 'set on /settings' : contextSource(p)}; change it on /settings)`)}`]
62
+ const from = { 'models.dev': 'models.dev', you: '/settings (set by hand)', assumed: "nothing: it isn't in models.dev. Set what it can do on /settings" }[p.source] ?? 'an earlier test'
63
+ const mine = (k) => (p.set?.[k] !== undefined ? c.dim(' (set by hand)') : '')
54
64
  return [['from', from], context, ['tool calls', yn(s.actions === 'tools') + mine('tools')], ['thinking', yn(s.thinking) + mine('thinking')], ['images', yn(s.vision) + (Date.now() - (p.quirks?.noImages ?? -Infinity) < LIMIT_MS ? c.dim(' (its provider refused an image today)') : mine('images'))], ['streaming', yn(s.stream) + mine('stream')]]
55
65
  .map(([k, v]) => ` ${c.dim(k.padEnd(15))} ${v}`)
56
66
  .join('\n')
package/src/reset.js CHANGED
@@ -9,13 +9,13 @@ export const RESETS = [
9
9
  {
10
10
  level: 'settings',
11
11
  label: 'Settings',
12
- desc: 'permissions, theme, effort, the toggles, the model list, voice; your keys, colors, formatters, prompts, MCP servers and hooks. Your providers, keys and model stay.',
12
+ desc: 'permissions, theme, effort, the toggles, the model list, voice; keys, colors, formatters, prompts, MCP servers and hooks. Providers, keys and the model stay.',
13
13
  files: ['keybindings.json', 'theme.json', 'format.json', 'prompts', 'mcp.json', 'hooks.json'],
14
14
  },
15
15
  {
16
16
  level: 'providers',
17
17
  label: 'Settings and providers',
18
- desc: 'the above, and your providers with their API keys, MCP sign-ins, what HeartCode learned about each model, prices',
18
+ desc: 'the above, and the providers with their API keys, MCP sign-ins, what HeartCode learned about each model, prices',
19
19
  files: ['config.json', 'mcp-auth.json', 'models', 'prices.json'],
20
20
  },
21
21
  {
package/src/sessions.js CHANGED
@@ -94,13 +94,13 @@ export function exportChat(chat, format, model = '') {
94
94
  if (format === 'md') {
95
95
  const body = list.map((e) => {
96
96
  const tools = e.tools.map((t) => `<details><summary>${t.name} ${esc(t.args.slice(0, 120))}</summary>\n\n${fence(t.result ?? '')}\n</details>`).join('\n')
97
- return [`## ${e.role === 'user' ? 'You' : 'HeartCode'}`, e.text, tools].filter(Boolean).join('\n\n')
97
+ return [`## ${e.role === 'user' ? 'User' : 'HeartCode'}`, e.text, tools].filter(Boolean).join('\n\n')
98
98
  })
99
99
  return `# ${title}\n\n_${when}_\n\n${body.join('\n\n')}\n`
100
100
  }
101
101
  const body = list.map((e) => {
102
102
  const tools = e.tools.map((t) => `<details><summary><b>${esc(t.name)}</b> <code>${esc(t.args.slice(0, 160))}</code></summary><pre>${esc(t.result ?? '')}</pre></details>`).join('')
103
- return `<section class="${e.role}"><h2>${e.role === 'user' ? 'You' : 'HeartCode'}</h2>${e.text ? `<div class="text">${esc(e.text)}</div>` : ''}${tools}</section>`
103
+ return `<section class="${e.role}"><h2>${e.role === 'user' ? 'User' : 'HeartCode'}</h2>${e.text ? `<div class="text">${esc(e.text)}</div>` : ''}${tools}</section>`
104
104
  })
105
105
  return `<!doctype html>
106
106
  <html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${esc(title)}</title>