heartcode 0.1.58 → 0.1.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/agent.js CHANGED
@@ -8,7 +8,7 @@ import path from 'node:path'
8
8
  import { est, estMessages, Client, tokensOf, COMPACT_SHARE } from './client.js'
9
9
  import { runGuided } from './guided.js'
10
10
  import { markUsed, removeResearch, findResearch } from './research.js'
11
- import { TOOL_DEFS, PLAN_HIDDEN, folderView, readOnlyCommand, searchesOutside, extraTools, runTool, listFiles, namedFiles, readFileTool, clip, allowed, loadMcpTools, saveOutput, isSavedOutput, runningCall, imageUrl, MAX_IMAGE, failed, refusal, noteNamedPaths } from './tools.js'
11
+ import { TOOL_DEFS, PLAN_HIDDEN, folderView, readOnlyCommand, searchesOutside, extraTools, runTool, listFiles, namedFiles, readFileTool, clip, allowed, loadMcpTools, saveOutput, isSavedOutput, runningCall, imageUrl, MAX_IMAGE, failed, refusal, noteNamedPaths, sendTodos } from './tools.js'
12
12
  import { serversNote } from './lsp.js'
13
13
  import { newlyEnded, jobLine } from './background.js'
14
14
  import { loadHooks, runHooks } from './hooks.js'
@@ -247,23 +247,12 @@ export class Session {
247
247
  return `error: ${e.message}`
248
248
  }
249
249
  const name = (t) => `${t.provider} ${t.model}`
250
- const self = { provider: this.client.provider, model: this.client.model, images: this.strat.vision, tools: this.strat.actions === 'tools', self: true }
251
- const team = this.team?.() ?? []
252
- const helpers = helpersOf(team)
253
- // the helpers you ticked (then this model), else this model and your others, in your list's order
254
- const all = helpers ? [...helpers, self] : [self, ...team]
255
- const want = String(args.model ?? '').trim()
256
- // only one model available (a pinned model, or you have just one): helpers use it, whatever was asked
257
- const first = !want || all.length === 1 ? all[0] : (all.find((t) => name(t) === want || `${t.provider}/${t.model}` === want) ?? all.find((t) => t.model === want || want.endsWith(` ${t.model}`) || t.model.endsWith(`/${want}`)))
258
- if (!first) return `error: no model "${want}". ${helpers ? 'Your helpers' : 'Yours'}: ${all.map(name).join(', ')}`
259
- // the one asked for first, then the others in your list's order: only those that can do the job
260
- // (images need a model that sees them)
261
- const able = (t) => !images.length || t.images
262
- let order = [first, ...all.filter((t) => t !== first)].filter(able)
263
- if (!order.length && helpers) order = [self, ...team].filter(able) // no helper sees images: any of yours that does
250
+ const { order, first, all, helpers } = this.helperModels(args, images.length > 0)
251
+ if (!first) return `error: no model "${String(args.model).trim()}". ${helpers ? 'Your helpers' : 'Yours'}: ${all.map(name).join(', ')}`
264
252
  if (!order.length) return 'error: none of your models can see images'
265
253
  const failed = []
266
254
  for (const [i, t] of order.entries()) {
255
+ if (args.part) (args.part.by = t.model), (args.part.byProvider = t.provider ?? this.client.provider), sendTodos(this) // a part of the plan: the model doing it, shown beside it
267
256
  let answer = ''
268
257
  try {
269
258
  answer = (await this.#helper(t, task, images, args.description, id, signal, args.ownFiles))?.trim()
@@ -279,6 +268,24 @@ export class Session {
279
268
  return `error: none of your models that can do it managed: ${failed.join('; ')}`
280
269
  }
281
270
 
271
+ // The models a helper's job goes to, in order: the one asked for (args.model), then the helpers you
272
+ // ticked (then this model), else this model and your others, in your list's order; only those that
273
+ // see images when it comes with some. first: the one asked for (undefined: no such model).
274
+ helperModels(args, withImages) {
275
+ const name = (t) => `${t.provider} ${t.model}`
276
+ const self = { provider: this.client.provider, model: this.client.model, images: this.strat.vision, tools: this.strat.actions === 'tools', self: true }
277
+ const team = this.team?.() ?? []
278
+ const helpers = helpersOf(team)
279
+ const all = helpers ? [...helpers, self] : [self, ...team]
280
+ const want = String(args.model ?? '').trim()
281
+ // only one model available (a pinned model, or you have just one): helpers use it, whatever was asked
282
+ const first = !want || all.length === 1 ? all[0] : (all.find((t) => name(t) === want || `${t.provider}/${t.model}` === want) ?? all.find((t) => t.model === want || want.endsWith(` ${t.model}`) || t.model.endsWith(`/${want}`)))
283
+ const able = (t) => !withImages || t.images
284
+ let order = first ? [first, ...all.filter((t) => t !== first)].filter(able) : []
285
+ if (first && !order.length && helpers) order = [self, ...team].filter(able) // no helper sees images: any of yours that does
286
+ return { order, first, all, helpers }
287
+ }
288
+
282
289
  // One helper on one model (t: this one, or another of yours), with its own connection (a helper's
283
290
  // failure moves no one else on to another model) that gives up after a few tries (then the next
284
291
  // model gets the job).
@@ -290,7 +297,7 @@ export class Session {
290
297
  client.retryIf = (e, attempt) => attempt < 3 && e.name !== 'TimeoutError' && e.status !== 429 && e.status !== 413 && (!was || was(e, attempt)) // silent (not starting, or stopping midway: each try would wait as long again), rate-limited or too large: the next model, not another try
291
298
  }
292
299
  const label = clip(String(description ?? '').trim() || task.split('\n')[0], 60) // its model is named on the agent line
293
- const helper = new Session({ client, profile, strat, root: this.root, ui: helperUI(this.ui, label), chat: newChat(this.root) })
300
+ const helper = new Session({ client, profile, strat, root: this.root, ui: helperUI(this.ui, label, client.model), chat: newChat(this.root) })
294
301
  helper.chat.turns = this.chat.turns.slice(-1) // this message's turn: its file changes go there (track), the changes tool reads them
295
302
  if (ownFiles?.length) helper.ownFiles = ownFiles.map((f) => path.resolve(this.root, f)) // a part of the plan: changes only its own files
296
303
  Object.assign(helper, { isSub: true, research: this.research, ran: this.ran, noResearch: this.noResearch, mcp: this.mcp, skills: this.skills, hooks: this.hooks, allowTools: this.allowTools, denyTools: this.denyTools, maxTurns: this.maxTurns, autoCompact: this.autoCompact, appendSystem: this.appendSystem, fileCache: this.fileCache, noFormat: this.noFormat, noLsp: this.noLsp })
@@ -298,7 +305,7 @@ export class Session {
298
305
  helper.mcpGate = async () => (await this.#gate(helper), () => {})
299
306
  if (this.onEvent) helper.onEvent = (e) => this.onEvent({ ...e, parent: id, helper: label })
300
307
  log('agent', `helper "${label}" (${images.length} image(s)): ${task}`)
301
- this.ui.helpers?.set(label, 'starting') // a line under the spinner while it works (helperUI keeps it up to date)
308
+ this.ui.helpers?.set(label, { id, model: `${t.provider ?? client.provider}/${t.model ?? client.model}`, what: 'starting' }) // a line under the spinner while it works (helperUI keeps it up to date)
302
309
  try {
303
310
  const answer = await (strat.actions === 'tools' ? runNative : runGuided)(helper, task, images, signal)
304
311
  log('agent', `helper "${label}" done`, answer)
@@ -572,7 +579,7 @@ const alwaysSkill = (k) => {
572
579
  const SYSTEM = (s) => {
573
580
  const instructions = userInstructions(s.root)
574
581
  return [
575
- prompt('agent/system', { root: s.root, env: envLine(), today: new Date().toISOString().slice(0, 10), rootList: rootList(s.root), servers: serversNote(s.root), files: '', more: '', caller: Boolean(s.appendSystem), see: Boolean(s.strat.vision), noUser: Boolean(s.ui.noUser || s.isSub) }), // models that can see often say they can't: told they can
582
+ prompt('agent/system', { root: s.root, env: envLine(), today: new Date().toISOString().slice(0, 10), rootList: rootList(s.root), servers: serversNote(s.root), files: '', more: '', caller: Boolean(s.appendSystem), see: Boolean(s.strat.vision), noUser: Boolean(s.ui.noUser || s.isSub), memory: Boolean(s.memory) && !s.isSub }), // models that can see often say they can't: told they can
576
583
  instructions && prompt('agent/instructions', { instructions }),
577
584
  ...[...(s.skills?.values() ?? [])].filter((k) => k.use === 'always').map(alwaysSkill), // skills that say how to work (use: always), with the files they bring
578
585
  !s.isSub && teamPrompt(s),
@@ -592,7 +599,7 @@ const teamPrompt = (s) => {
592
599
  const team = s.team?.() ?? []
593
600
  if (!team.length) return ''
594
601
  const helpers = helpersOf(team)
595
- const can = (t) => [t.tools === false && 'no tool calls', t.images && 'images', t.thinking && 'thinking'].filter(Boolean)
602
+ const can = (t) => [t.tools === false && 'no tool calls', t.images && 'images', t.thinking && 'thinking', t.context && `${kTokens(t.context)} context`].filter(Boolean)
596
603
  const good = (t) => (t.jobs?.length ? ` · good at: ${t.jobs.map((j) => HELPER_JOBS[j]?.[1]).filter(Boolean).join('; ')}` : '')
597
604
  const line = (t) => `- ${t.provider} ${t.model}${can(t).length ? `: ${can(t).join(', ')}` : ''}${good(t)}`
598
605
  return prompt('agent/team', { helpers: Boolean(helpers), models: (helpers ?? team).map(line).join('\n'), you: [s.strat.vision ? 'images' : 'no images', s.strat.thinking && 'thinking'].filter(Boolean).join(', ') })
@@ -887,6 +894,8 @@ async function runNative(s, task, images, signal) {
887
894
  }
888
895
  let garbled = 0 // replies with a tool call written as text (template markup), this message
889
896
  let movedOn = 0 // models given up on for that, in this message
897
+ let cut = '' // a reply cut off (its provider's output limit, or the connection ended early): what came of it so far
898
+ let cuts = 0 // cut off in a row: asked to go on, up to 3 times
890
899
  let refitted = false // this step's conversation was just compacted for a smaller model the list moved on to
891
900
  // No step limit (helpers too): a long fix takes many steps, and Esc stops it. A caller can set one (--max-turns).
892
901
  for (let step = 0; ; step++) {
@@ -931,7 +940,11 @@ async function runNative(s, task, images, signal) {
931
940
  }
932
941
  const stream = strat.stream
933
942
  // A long tool call (a whole file) streams in silently: say what's being written.
934
- const onToolDelta = (name, args) => ui.spinner(`${name === 'run_command' ? 'preparing a command' : `writing ${/"path"\s*:\s*"([^"]+)"/.exec(args)?.[1] ?? name}`} · ${args.length >= 1000 ? `${(args.length / 1000).toFixed(1)}k` : args.length} chars`)
943
+ const onToolDelta = (name, args) => {
944
+ const file = /"path"\s*:\s*"([^"]+)"/.exec(args)?.[1]
945
+ const what = name === 'run_command' ? 'preparing a command' : EDITS.has(name) && file ? `writing ${file}` : `preparing ${name}${file ? ` ${file}` : ''}` // only an edit is "writing" a file
946
+ ui.spinner(`${what} · ${args.length >= 1000 ? `${(args.length / 1000).toFixed(1)}k` : args.length} chars`)
947
+ }
935
948
  // the prompts or HEARTCODE.md changed meanwhile (applySettings): the system prompt again, now
936
949
  if (s.refreshSystem && s.messages[0]?.role === 'system') s.messages[0] = { ...s.messages[0], content: SYSTEM(s) }
937
950
  s.refreshSystem = false
@@ -1014,7 +1027,20 @@ async function runNative(s, task, images, signal) {
1014
1027
  showHeld(res.content) // not the answer: shown now, before its calls
1015
1028
  s.acted = sinceNudge = true // did real work this message, for the premature-stop check
1016
1029
  }
1017
- s.onEvent?.({ type: 'assistant', model: `${client.provider}/${client.model}`, content: res.content, reasoning: res.reasoning, toolCalls: res.toolCalls }) // headless output
1030
+ s.lastStop = res.finishReason // why the last reply ended (headless: its stop_reason)
1031
+ s.onEvent?.({ type: 'assistant', model: `${client.provider}/${client.model}`, content: res.content, reasoning: res.reasoning, toolCalls: res.toolCalls, stop: res.finishReason }) // headless output
1032
+ // An answer cut off (its provider's output limit: no max_tokens is sent, so each has its own; or a
1033
+ // connection that ended early): the model goes on where it stopped (3 times in a row at most); the
1034
+ // answer is the pieces together. Still cut after that: it stays cut, and says so (stop_reason).
1035
+ if (!res.toolCalls.length && res.content?.trim() && (res.finishReason === 'length' || res.finishReason === 'incomplete') && cuts < 3) {
1036
+ cuts++
1037
+ cut += res.content
1038
+ log('task', `${client.model}: reply cut off (${res.finishReason}); asking it to go on`)
1039
+ s.messages.push({ role: 'user', content: prompt('agent/cut-off') })
1040
+ continue
1041
+ }
1042
+ if (cut && !res.toolCalls.length) res.content = cut + res.content
1043
+ if (!res.toolCalls.length || res.finishReason !== 'length') [cut, cuts] = ['', 0]
1018
1044
  if (!res.toolCalls.length && !res.content?.trim()) {
1019
1045
  // Nothing at all (seen after a failed tool call): not an answer. The same request again
1020
1046
  // first (often fine the second time), then asked to go on; three in a row ends the task.
@@ -1058,7 +1084,7 @@ async function runNative(s, task, images, signal) {
1058
1084
  }
1059
1085
  }
1060
1086
  // a helper's line: its job, and the model doing it (named once here; its steps go by its job)
1061
- const helperLine = (a) => `${clip(String(a.description ?? '').trim() || 'helper', 70)} ${c.faint(`· ${a.model || client.model}`)}`
1087
+ const helperLine = (a) => `${clip(String(a.description ?? '').trim() || 'helper', 70)} ${c.faint(`· ${s.helperModels?.(a, [a.images ?? []].flat().length > 0).order[0]?.model ?? (a.model || client.model)}`)}` // the model that will do it
1062
1088
  const together = new Map()
1063
1089
  for (const call of res.toolCalls) {
1064
1090
  const args = argsOf(call)
@@ -1105,7 +1131,7 @@ async function runNative(s, task, images, signal) {
1105
1131
  : name === 'todo' || name === 'ask_user'
1106
1132
  ? ''
1107
1133
  : (args.path ?? args.url ?? args.query ?? args.filter ?? args.name ?? '')
1108
- if (name !== 'run_command' && !together.has(call.id) && !askedWith.has(call.id)) ui.step(name, name === 'agent' && args ? helperLine(args) : clip(detail, 80)) // asked together: shown once, with the first
1134
+ if (name !== 'run_command' && !together.has(call.id) && !askedWith.has(call.id)) ui.step(name, name === 'agent' && args ? helperLine(args) : clip(detail, 80), name === 'agent' ? '' : client.model) // asked together: shown once, with the first; named by the model that made the call (an agent line names the helper's)
1109
1135
  const pre = early.get(call.id)
1110
1136
  // the first changes to the files with no plan yet (this message, or still open from an earlier one):
1111
1137
  // not made — the plan first, then the changes again. Every change in that reply (one made beside a
@@ -1137,7 +1163,9 @@ async function runNative(s, task, images, signal) {
1137
1163
  if (++s.checksSince === 5 && (s.changed.size || s.isSub)) out += `\n\n${prompt('agent/enough-checks', { n: s.checksSince, choices: (s.chat?.choices ?? []).join('; ') })}`
1138
1164
  }
1139
1165
  }
1140
- if (name === 'run_command' && args && !refused) s.ran?.push({ command: String(args.command ?? ''), result: clip(String(out).split('\n').filter((l) => l.trim()).slice(0, 2).join(' · '), 160) })
1166
+ // what was run or checked, for the review and the wrap-up: commands, MCP tools (a browser), helpers, the language server
1167
+ const checked = !args || refused ? null : name === 'run_command' ? String(args.command ?? '') : name === 'mcp' ? `${args.server} · ${args.tool}` : name === 'agent' ? `helper: ${args.description ?? clip(String(args.prompt ?? ''), 60)}` : name === 'lsp' ? `language server: ${args.action} ${args.file ?? ''}` : null
1168
+ if (checked) s.ran?.push({ command: checked, result: clip(String(out).split('\n').filter((l) => l.trim()).slice(0, 2).join(' · '), 160) })
1141
1169
  if (!s.isSub && s.memory && !refused && args) await noteRun(s, name, args, out, signal).catch((e) => log('learn', `run note: ${e.message}`)) // learn from any run that failed then passed
1142
1170
  // the same call again and again in a row (a weak model going round): told at the third, stopped at the fifth
1143
1171
  const sig = `${name} ${call.function.arguments}`
@@ -1162,7 +1190,7 @@ async function runNative(s, task, images, signal) {
1162
1190
  const msg = { role: 'tool', tool_call_id: call.id, content: fitResult(s, name, out, s.chat.outputs?.[call.id]) }
1163
1191
  if (name === 'read_file' && args && !args.start_line && !args.end_line && !failed(out)) replaceCopy(s, args.path, msg)
1164
1192
  s.messages.push(msg)
1165
- s.onEvent?.({ type: 'tool', id: call.id, name, output: out })
1193
+ s.onEvent?.({ type: 'tool', id: call.id, name, output: out, model: `${client.provider}/${client.model}` })
1166
1194
  }
1167
1195
  if (s.userSaid.length) s.messages.push({ role: 'user', content: s.userSaid.splice(0).join('\n\n') }) // their own words, as they typed them
1168
1196
  trimOldResults(s)
@@ -1444,7 +1472,7 @@ export async function review(s, task, answer, signal) {
1444
1472
  const self = { provider: s.client.provider, model: s.client.model, self: true }
1445
1473
  const others = (s.team?.() ?? []).filter((t) => t.tools !== false && !(t.provider === self.provider && t.model === self.model))
1446
1474
  const reviewers = others.filter((t) => t.jobs?.includes('code')).sort((a, b) => Boolean(b.thinking) - Boolean(a.thinking)) // ticked for Code & logic on Your models, the thinking ones first
1447
- const team = reviewers.length ? reviewers : others // else your next two, in your order
1475
+ const team = [...reviewers, ...others.filter((t) => !reviewers.includes(t))] // then your others, in your order (two at most, then this one)
1448
1476
  for (const t of [...team.slice(0, 2), self]) {
1449
1477
  s.ui.spinner(`${t.model} is reviewing the work`)
1450
1478
  try {
@@ -1461,11 +1489,13 @@ export async function review(s, task, answer, signal) {
1461
1489
  s.ui.stopSpin()
1462
1490
  log('review', `${t.model}: ${said}`)
1463
1491
  if (/^\W*yes\b/i.test(said)) {
1492
+ s.ui.event?.({ subtype: 'review', model: `${t.provider}/${t.model}`, verdict: 'yes', issues: '' })
1464
1493
  s.ui.step('review', `${t.model}: looks right`)
1465
1494
  return null
1466
1495
  }
1467
1496
  if (/^\W*no\b/i.test(said)) {
1468
1497
  const issues = said.replace(/^\W*no\b[\s.:—-]*/i, '').trim()
1498
+ s.ui.event?.({ subtype: 'review', model: `${t.provider}/${t.model}`, verdict: 'no', issues })
1469
1499
  s.ui.step('review', `${t.model}: ${clip(issues.split('\n').find((l) => l.trim()) ?? 'problems found', 90)}`)
1470
1500
  return prompt('agent/review-failed', { model: t.model, issues: issues || '(no details given)' })
1471
1501
  }
@@ -1491,7 +1521,8 @@ const lineCount = (out) => {
1491
1521
  // Questions to the user (confirm, pick, ask) wait their turn: helpers working at once ask one by one.
1492
1522
  const asking = new WeakMap() // ui → the question being asked
1493
1523
  const streaming = new WeakMap() // ui → helper replies coming in now (only one: its thinking is shown as it comes)
1494
- function helperUI(ui, label) {
1524
+ // model: the helper's, named on each of its steps
1525
+ function helperUI(ui, label, model) {
1495
1526
  // What the helper says is shown in full under its name. Its thinking is shown as it comes, like the
1496
1527
  // conversation's; with other helpers replying at the
1497
1528
  // same time, held until its reply ends, then printed at once (two streams would interleave).
@@ -1526,7 +1557,7 @@ function helperUI(ui, label) {
1526
1557
  // what it's doing, for the line per helper under the spinner (ui.helpers: full screen only)
1527
1558
  const status = (text) => {
1528
1559
  if (!ui.helpers?.has(label)) return
1529
- ui.helpers.set(label, clip(String(text), 60))
1560
+ ui.helpers.set(label, { ...ui.helpers.get(label), what: clip(String(text), 60) })
1530
1561
  ui.render?.()
1531
1562
  }
1532
1563
  const own = {
@@ -1534,7 +1565,7 @@ function helperUI(ui, label) {
1534
1565
  step: (name, detail = '') => {
1535
1566
  if (ui.afterBlock) ui.gap()
1536
1567
  ui.afterBlock = false
1537
- ui.print(` ${c.accent('●')} ${c.accent(c.bold(`${label} › ${name}`))} ${c.info(detail)}`)
1568
+ ui.print(` ${c.accent('●')} ${c.accent(c.bold(`${label} › ${name}`))} ${c.info(detail)}${model ? c.faint(` · ${model}`) : ''}`)
1538
1569
  status(`${name} ${detail}`)
1539
1570
  },
1540
1571
  result: (text) => ui.print(` ${c.ghost('⎿')} ${c.faint(text)}`),
package/src/client.js CHANGED
@@ -654,6 +654,7 @@ export class Client {
654
654
  let thought = ''
655
655
  let usage
656
656
  let finishReason
657
+ let sawDone = false
657
658
  const calls = []
658
659
  let raw = '' // the stream as it came (its start), kept for a reply that turns out empty
659
660
  // A reply going round (a small model repeating itself, which could fill the window): checked
@@ -682,8 +683,7 @@ export class Client {
682
683
  }
683
684
  poke()
684
685
  firstAt ??= Date.now()
685
- if (end) break
686
- buf += dec.decode(value, { stream: true })
686
+ buf += end ? dec.decode() + '\n' : dec.decode(value, { stream: true }) // the end: its last line too, even without a line break after it
687
687
  let nl
688
688
  while ((nl = buf.indexOf('\n')) !== -1) {
689
689
  const line = buf.slice(0, nl).trim()
@@ -691,7 +691,10 @@ export class Client {
691
691
  if (raw.length < 100_000 && line) raw += line + '\n'
692
692
  if (!line.startsWith('data:')) continue
693
693
  const payload = line.slice(5).trim()
694
- if (payload === '[DONE]') continue
694
+ if (payload === '[DONE]') {
695
+ sawDone = true
696
+ continue
697
+ }
695
698
  let chunk
696
699
  try {
697
700
  chunk = JSON.parse(payload)
@@ -749,6 +752,12 @@ export class Client {
749
752
  await reader.cancel().catch(() => {}) // the server stops generating
750
753
  break
751
754
  }
755
+ if (end) break
756
+ }
757
+ // closed with neither [DONE] nor a reason it ended: the connection ended early, the reply may be cut
758
+ if (!looped && !sawDone && !finishReason) {
759
+ finishReason = 'incomplete'
760
+ log('reply', `${this.model}: the stream ended without [DONE] or a finish reason: the reply may be cut off`)
752
761
  }
753
762
  clearTimeout(timer), started()
754
763
  if (looped) {
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 your 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/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,24 @@
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
+ // by: the model a part went to), "helper" (one at work: tool_use_id, label, model, status;
13
+ // "done" at its end), "review" (model, verdict yes/no, issues), "model_switch" (from, to,
14
+ // reason), "warning" (message), "retry" (attempt, delay_ms, error), "status" (what it's
15
+ // doing now, as the spinner says it: a running command's latest output line too)
11
16
  // 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.
17
+ // told to the model. Logs go to their files (or HEART_LOG), never stdout; warnings and retries go to
18
+ // stderr with --verbose (and, in stream-json, as system lines).
13
19
  import readline from 'node:readline'
14
20
  import { log } from './log.js'
15
21
  import { clip, TOOL_DEFS, extraTools, loadMcpTools, mcpName, failed as toolFailed } from './tools.js'
16
22
  import { allowed } from './agent.js'
17
23
 
24
+ const plain = (t) => String(t ?? '').replace(/\x1b\[[0-9;]*m/g, '')
25
+
18
26
  // 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' }
27
+ 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
28
  export function toolNames(list) {
21
29
  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
30
  return new Set(names.map((t) => CLAUDE_TOOLS[t] ?? t)) // mcp__server__tool and mcp__server as they are (tools.js allowed)
@@ -25,10 +33,24 @@ export function toolNames(list) {
25
33
  // --permission-mode, in HeartCode's terms or Claude Code's.
26
34
  export const PERMISSION_MODES = { all: 'all', commands: 'commands', ask: 'ask', bypassPermissions: 'all', acceptEdits: 'commands', default: 'ask', plan: 'plan', dontAsk: 'ask' }
27
35
 
28
- // A UI that shows nothing and asks nobody.
36
+ // A UI that shows nothing and asks nobody; what the full screen would show goes to this.event (set
37
+ // by stream-json: a system message each) as data.
29
38
  export class HeadlessUI {
30
39
  constructor({ permission = 'all', verbose = false } = {}) {
31
- Object.assign(this, { permission, verbose, log: [], showThinking: true, full: false, noUser: true })
40
+ Object.assign(this, { permission, verbose, log: [], showThinking: true, full: false, noUser: true, event: null })
41
+ // helpers at work (agent.js: label → { id, model, what }): each change sent as a "helper" event
42
+ const ui = this
43
+ this.helpers = new (class extends Map {
44
+ set(label, v) {
45
+ ui.event?.({ subtype: 'helper', tool_use_id: v?.id ?? null, label, model: v?.model ?? null, status: v?.what ?? null })
46
+ return super.set(label, v)
47
+ }
48
+ delete(label) {
49
+ const v = this.get(label)
50
+ if (v) ui.event?.({ subtype: 'helper', tool_use_id: v.id ?? null, label, model: v.model ?? null, status: 'done' })
51
+ return super.delete(label)
52
+ }
53
+ })()
32
54
  }
33
55
  #err(text) {
34
56
  if (this.verbose) process.stderr.write(`${text}\n`)
@@ -36,9 +58,28 @@ export class HeadlessUI {
36
58
  warn(text) {
37
59
  log('warn', text)
38
60
  this.#err(`heartcode: ${text}`)
61
+ this.event?.({ subtype: 'warning', message: plain(text) })
39
62
  }
40
63
  retrying(err, ms, attempt) {
41
64
  if (err) this.#err(`heartcode: retrying in ${Math.ceil(ms / 1000)}s (attempt ${attempt}): ${err.message}`)
65
+ if (err) this.event?.({ subtype: 'retry', attempt, delay_ms: ms, error: plain(err.message) })
66
+ }
67
+ // What it's doing now, as the spinner would say it: sent when it changes (a label that's a function,
68
+ // a running command's latest line: read once a second)
69
+ spinner(label) {
70
+ clearInterval(this.spinTimer)
71
+ const say = () => {
72
+ const text = plain(typeof label === 'function' ? label() : label)
73
+ // model: a helper's when it's that helper's ("<its job> · …"), else the main conversation's
74
+ const helper = [...this.helpers].find(([job]) => text.startsWith(`${job} · `))?.[1]
75
+ if (text && text !== this.said) this.event?.({ subtype: 'status', status: (this.said = text), model: helper?.model ?? this.waitingFor?.() ?? null })
76
+ }
77
+ say()
78
+ if (typeof label === 'function') this.spinTimer = setInterval(say, 1000).unref() // never what keeps a finished run going
79
+ }
80
+ stopSpin() {
81
+ clearInterval(this.spinTimer)
82
+ this.said = null
42
83
  }
43
84
  async confirm(question, kind = 'edit') {
44
85
  if (this.permission === 'all' || (this.permission === 'commands' && kind === 'edit') || (this.permission === 'plan' && kind === 'read')) return true // plan: only reading
@@ -82,8 +123,6 @@ export class HeadlessUI {
82
123
  async pick() {
83
124
  return null
84
125
  }
85
- spinner() {}
86
- stopSpin() {}
87
126
  print() {}
88
127
  write() {}
89
128
  gap() {}
@@ -150,9 +189,14 @@ export async function runHeadless(app, opts) {
150
189
  // its own arguments, not HeartCode's one mcp tool around them (a program reading it, Nibedita,
151
190
  // knows its tools by those names).
152
191
  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
192
+ let said = '' // the main conversation's last text sent as an assistant message
193
+ // why a reply ended, in Claude's words (stop_reason)
194
+ 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' }
195
+ const stopOf = (r) => (r ? (STOP[r] ?? r) : null)
154
196
  if (out === 'stream-json') {
155
197
  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)
198
+ app.ui.event = (e) => emit({ type: 'system', ...e, session_id })
199
+ 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
200
  s.onEvent = (e) => {
157
201
  if (e.type === 'assistant') {
158
202
  const content = [
@@ -160,11 +204,11 @@ export async function runHeadless(app, opts) {
160
204
  ...(e.content ? [{ type: 'text', text: e.content }] : []),
161
205
  ...e.toolCalls.map((t) => ({ type: 'tool_use', id: t.id, ...asClaude(t.function.name, parseArgs(t.function.arguments)) })),
162
206
  ]
163
- if (e.content && !e.parent) said = true
207
+ if (e.content && !e.parent) said = e.content
164
208
  // 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 })
209
+ 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
210
  } 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 })
211
+ 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
212
  }
169
213
  }
170
214
  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 +224,8 @@ export async function runHeadless(app, opts) {
180
224
  usage = { input_tokens: 0, output_tokens: 0 }
181
225
  byModel = {}
182
226
  requests = 0
183
- said = false
227
+ said = ''
228
+ s.lastStop = null
184
229
  current = { ctl: new AbortController() }
185
230
  app.signal = current.ctl.signal
186
231
  app.working = true // settings changed meanwhile: MCP servers and skills wait for the end of it
@@ -201,9 +246,11 @@ export async function runHeadless(app, opts) {
201
246
  }
202
247
  const subtype = current.maxTurns ? 'error_max_turns' : error ? 'error_during_execution' : 'success' // as Claude Code names them
203
248
  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 }
249
+ 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
250
  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
251
+ // the answer as a reply of its own, unless it just went out as one (as it was: a cut-off answer is
252
+ // its pieces together; guided mode, an answer made after empty replies: never sent)
253
+ 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
254
  emit(result)
208
255
  } else if (out === 'json') emit(result)
209
256
  else if (error) process.stderr.write(`heartcode: ${error}\n`)
package/src/log.js CHANGED
@@ -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)