heartcode 0.1.54 → 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/agent.js CHANGED
@@ -5,10 +5,10 @@ import { prompt, userInstructions } from './prompts.js'
5
5
  import { newChat } from './sessions.js'
6
6
  import { skillFiles, readSkillFile } from './skills.js'
7
7
  import path from 'node:path'
8
- import { est, estMessages, Client, writtenBy, tokensOf, COMPACT_SHARE } from './client.js'
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, 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 } 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'
@@ -75,6 +75,17 @@ export class Session {
75
75
  Object.assign(this, { client, profile, strat, root, ui, chat: chat ?? newChat(root) })
76
76
  }
77
77
 
78
+ // A conversation with messages already (resumed, forked, another tab's): its size estimated until
79
+ // the server counts it with the first request (the status bar's ctx)
80
+ #chat
81
+ get chat() {
82
+ return this.#chat
83
+ }
84
+ set chat(v) {
85
+ this.#chat = v
86
+ if (v?.messages?.length && this.client) this.client.lastTokens = Math.round(estMessages(v.messages) * (this.strat?.ratio ?? 1))
87
+ }
88
+
78
89
  get messages() {
79
90
  return this.chat.messages
80
91
  }
@@ -104,8 +115,8 @@ export class Session {
104
115
  // why: what the spinner says the compacting is for ("context 85% full (650k/768k)").
105
116
  async compact({ signal, focus = '', midTask = false, task = '', why = '' } = {}) {
106
117
  const { chat, client, strat, ui } = this
107
- const native = Boolean(chat.messages?.length)
108
- const head = native ? chat.messages.slice(0, chat.messages[0].role === 'system' ? 1 : 2) : [] // the system prompt stays
118
+ const native = strat.actions === 'tools' && Boolean(chat.messages?.length) // guided mode: from chat.history, which has every turn
119
+ const head = chat.messages?.length ? chat.messages.slice(0, chat.messages[0].role === 'system' ? 1 : 2) : [] // the system prompt stays
109
120
  const body = native ? chat.messages.slice(head.length) : []
110
121
  const conversation = native ? transcript(body) : chat.history.map((h) => `User: ${h.task}\nAssistant: ${h.answer}`).join('\n\n')
111
122
  if (!conversation.trim()) return null
@@ -132,8 +143,8 @@ export class Session {
132
143
  chat.sentNotes = [] // the summary replaces the messages the notes came with
133
144
  chat.epoch = epoch + 1
134
145
  const recap = prompt('compact/summary', { summary, findings, requests: requestsOf(chat) })
135
- if (native) {
136
- chat.messages = midTask
146
+ if (chat.messages?.length) {
147
+ chat.messages = midTask && native
137
148
  ? [...head, { role: 'user', content: `${recap}\n\n${prompt('compact/continue', { task })}` }]
138
149
  : [...head, { role: 'user', content: recap }, { role: 'assistant', content: prompt('compact/acknowledged') }]
139
150
  }
@@ -209,7 +220,9 @@ export class Session {
209
220
  }
210
221
  if (!this.isSub) log('rotate', `this message starts on ${this.client.provider ?? ''} · ${this.client.model}${this.client.rotation ? ` (#${this.client.rotation.at + 1} of ${this.client.rotation.list.length})` : ''}`)
211
222
  log('task', `${text} (${this.strat.actions} mode, ${images.length} image(s))`)
212
- const answer = this.strat.actions === 'tools' ? await runNative(this, text, images, signal) : await runGuided(this, text, images, signal)
223
+ const native = this.strat.actions === 'tools'
224
+ const answer = native ? await runNative(this, text, images, signal) : await runGuided(this, text, images, signal)
225
+ if (!native && chat.messages?.length) chat.messages.push({ role: 'user', content: text }, { role: 'assistant', content: answer ?? '' }) // a model with tool calls later reads only chat.messages
213
226
  log('answer', answer) // the conversation's log
214
227
  log('task', `answered (${String(answer ?? '').length} characters)`)
215
228
  this.history.push({ task: text, answer })
@@ -252,6 +265,7 @@ export class Session {
252
265
  answer = (await this.#helper(t, task, images, args.description, id, signal, args.ownFiles))?.trim()
253
266
  } catch (e) {
254
267
  if (e.name === 'AbortError' || signal?.aborted) throw e
268
+ if (e.maxTurns) return `error: the helper ${e.message}` // the caller's limit: every other model would stop there too
255
269
  failed.push(`${t.model}: ${clip(e.message, 150)}`)
256
270
  }
257
271
  if (answer) return t === first ? answer : `(Answered by ${name(t)}, not ${name(first)}${failed.length ? `: ${failed.join('; ')}` : ''})\n\n${answer}`
@@ -271,20 +285,29 @@ export class Session {
271
285
  const was = client.retryIf
272
286
  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
273
287
  }
274
- const label = clip(`${client.model}: ${String(description ?? '').trim() || task.split('\n')[0]}`, 60)
288
+ const label = clip(String(description ?? '').trim() || task.split('\n')[0], 60) // its model is named on the agent line
275
289
  const helper = new Session({ client, profile, strat, root: this.root, ui: helperUI(this.ui, label), chat: newChat(this.root) })
290
+ helper.chat.turns = this.chat.turns.slice(-1) // this message's turn: its file changes go there (track), the changes tool reads them
276
291
  if (ownFiles?.length) helper.ownFiles = ownFiles.map((f) => path.resolve(this.root, f)) // a part of the plan: changes only its own files
277
292
  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 })
278
293
  helper.track = (rel, before) => this.track(rel, before)
279
294
  helper.mcpGate = async () => (await this.#gate(helper), () => {})
280
295
  if (this.onEvent) helper.onEvent = (e) => this.onEvent({ ...e, parent: id, helper: label })
281
296
  log('agent', `helper "${label}" (${images.length} image(s)): ${task}`)
297
+ this.ui.helpers?.set(label, 'starting') // a line under the spinner while it works (helperUI keeps it up to date)
282
298
  try {
283
299
  const answer = await (strat.actions === 'tools' ? runNative : runGuided)(helper, task, images, signal)
284
300
  log('agent', `helper "${label}" done`, answer)
285
301
  return answer
286
302
  } finally {
303
+ if (this.ui.helpers?.delete(label)) this.ui.render?.()
287
304
  this.#release(helper)
305
+ // its changes are this message's: the not-done checks and the review see them
306
+ if (helper.changed?.size && this.changed) {
307
+ for (const f of helper.changed) this.changed.add(f)
308
+ this.lastChangeAt = ++this.seq
309
+ this.checksSince = 0
310
+ }
288
311
  }
289
312
  }
290
313
 
@@ -545,7 +568,7 @@ const alwaysSkill = (k) => {
545
568
  const SYSTEM = (s) => {
546
569
  const instructions = userInstructions(s.root)
547
570
  return [
548
- 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) }), // models that can see often say they can't: told they can
571
+ 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
549
572
  instructions && prompt('agent/instructions', { instructions }),
550
573
  ...[...(s.skills?.values() ?? [])].filter((k) => k.use === 'always').map(alwaysSkill), // skills that say how to work (use: always), with the files they bring
551
574
  !s.isSub && teamPrompt(s),
@@ -741,7 +764,8 @@ async function runNative(s, task, images, signal) {
741
764
  // Unchanged, it stays the same text, so a provider's prompt cache still holds.
742
765
  const sys = SYSTEM(s)
743
766
  if (!s.messages) {
744
- s.messages = [{ role: 'system', content: sys }]
767
+ // the chat so far was in guided mode (chat.history only; this message's entry isn't in it yet)
768
+ s.messages = [{ role: 'system', content: sys }, ...s.history.flatMap((h) => [{ role: 'user', content: h.task }, { role: 'assistant', content: h.answer ?? '' }])]
745
769
  } else if (s.messages[0]?.content !== sys && s.messages[0]?.role === 'system') {
746
770
  s.messages[0] = { ...s.messages[0], content: sys }
747
771
  }
@@ -764,7 +788,10 @@ async function runNative(s, task, images, signal) {
764
788
  if (!k?.tokens || k.upTo > s.messages.length) return all
765
789
  return Math.max(all, k.tokens + tokensOf(s.messages.slice(k.upTo), null, Math.max(1, ratio)))
766
790
  }
767
- const nearlyFull = () => s.autoCompact && strat.context > 0 && used() >= strat.context * COMPACT_SHARE && used() >= (s.compactFailedAt ?? 0)
791
+ const nearlyFull = () => {
792
+ if (s.compactModel !== client.model) Object.assign(s, { compactModel: client.model, compactFailedAt: 0 }) // a failed try was for another model's window
793
+ return s.autoCompact && strat.context > 0 && used() >= strat.context * COMPACT_SHARE && used() >= (s.compactFailedAt ?? 0)
794
+ }
768
795
  const fullness = () => `context ${Math.round((used() / strat.context) * 100)}% full (~${kTokens(used())} of ${kTokens(strat.context)})`
769
796
  // Still that full after compacting (what every request carries, the system prompt and the tools'
770
797
  // schemas, takes most of the window): compacting again won't free anything, so not until it has
@@ -806,14 +833,13 @@ async function runNative(s, task, images, signal) {
806
833
  const known = notes.length || pages.length ? prompt('agent/known', { notes: notes.map((n) => `[[${n.name}]] — ${n.description}`).join('\n'), pages: pages.map((r) => `- ${r.title} — ${r.url} (read ${r.fetched}) → ${r.file}`).join('\n') }).trim() : ''
807
834
  const text = known ? `${task}\n\n${known}` : task
808
835
  if (!s.isSub) Object.assign(s, { research: [], ran: [], lastQuery: '', dirsBefore: foldersOf(s.root), noResearch: !s.memory }) // this message's pages and commands (helpers add theirs), and the folders there were, for the wrap-up
809
- const planning = ui.permission === 'plan'
810
- const said = planning && !s.isSub ? `${text}\n\n${prompt('agent/plan-mode')}` : text
836
+ const said = ui.permission === 'plan' && !s.isSub ? `${text}\n\n${prompt('agent/plan-mode')}` : text
811
837
  const content = images.length ? [{ type: 'text', text: said }, ...images.map((url) => ({ type: 'image_url', image_url: { url } }))] : said
812
838
  s.messages.push({ role: 'user', content })
813
839
  attachNamed(s, task) // files the message names: as if already read (saves a round trip each)
814
840
  // the tools: built again each step (the model answering may change; client.js leaves them out for
815
- // one that can't call tools)
816
- const toolList = () => [...TOOL_DEFS, ...extraTools(s)].filter((f) => allowed(s, f.name) && !(planning && PLAN_HIDDEN.has(f.name)) && !(f.name === 'ask_user' && ui.noUser)).map((f) => ({ type: 'function', function: f }))
841
+ // one that can't call tools; plan mode may be left mid-message)
842
+ const toolList = () => [...TOOL_DEFS, ...extraTools(s)].filter((f) => allowed(s, f.name) && !(ui.permission === 'plan' && PLAN_HIDDEN.has(f.name)) && !(f.name === 'ask_user' && (ui.noUser || s.isSub))).map((f) => ({ type: 'function', function: f })) // ask_user: not headless, nor a helper (it reports to the main agent, which asks)
817
843
  const guard = newGuard() // calls made again with nothing changed: the earlier result instead
818
844
  let lastCall = '' // the last call (tool and arguments), and how many times in a row
819
845
  let inRow = 0
@@ -859,7 +885,7 @@ async function runNative(s, task, images, signal) {
859
885
  const tools = toolList()
860
886
  s.lastTools = tools // what the requests carry: the findings note before compacting sends the same (compact)
861
887
  if (s.maxTurns && step >= s.maxTurns) {
862
- ui.warn(`stopped after ${s.maxTurns} steps (--max-turns); say "continue" to go on`)
888
+ if (!s.isSub) ui.warn(`stopped after ${s.maxTurns} steps (--max-turns); say "continue" to go on`)
863
889
  throw Object.assign(new Error(`stopped after ${s.maxTurns} steps (--max-turns)`), { maxTurns: true })
864
890
  }
865
891
  // after a failed compaction, the next try waits until the conversation has grown by 5% of the window
@@ -880,7 +906,20 @@ async function runNative(s, task, images, signal) {
880
906
  if (s.messages[0]?.content !== now && s.messages[0]?.role === 'system') s.messages[0] = { ...s.messages[0], content: now }
881
907
  pairTools(s.messages)
882
908
  ui.spinner('thinking')
883
- const out = ui.response(client.model) // named: helpers think too (theirs are named in helperUI)
909
+ // named by the model that answers: opened at its first word (a failed one moves the list on
910
+ // before that, mid-request); helpers are named in helperUI
911
+ let live = null
912
+ const reply = () => (live ??= ui.response(client.model))
913
+ // a reply that may be the answer, with a review to come (files changed since the last one): its
914
+ // text is held and shown after the review's line, so the answer is what's last on screen
915
+ const hold = sinceNudge && !s.isSub && s.changed?.size > 0 && s.lastChangeAt > (s.reviewedAt ?? 0) && ui.permission !== 'plan'
916
+ const out = { think: (t) => reply().think(t), text: hold ? (t) => t?.trim() && ui.spinner('writing the answer') : (t) => reply().text(t), end: () => reply().end() }
917
+ const showHeld = (text) => {
918
+ if (!hold || !text?.trim()) return
919
+ const r = ui.response(client.model)
920
+ r.text(text)
921
+ r.end()
922
+ }
884
923
  const stream = strat.stream
885
924
  // A long tool call (a whole file) streams in silently: say what's being written.
886
925
  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`)
@@ -889,7 +928,7 @@ async function runNative(s, task, images, signal) {
889
928
  s.refreshSystem = false
890
929
  let res
891
930
  try {
892
- res = await client.chat({ messages: s.messages, tools, stream }, { signal, onToken: out.text, onReasoning: out.think, onToolDelta, fit: !refitted })
931
+ res = await client.chat({ messages: s.messages, tools, stream }, { signal, onToken: out.text, onReasoning: out.think, onToolDelta, fit: s.autoCompact && !refitted })
893
932
  } catch (e) {
894
933
  if (!e.tooBig) {
895
934
  ui.stopSpin()
@@ -912,6 +951,15 @@ async function runNative(s, task, images, signal) {
912
951
  }
913
952
  refitted = false
914
953
  ui.stopSpin()
954
+ // the model list moved on to a model without tool calls: it can't act here, so guided mode does
955
+ // the rest of this message (its reply to a request it couldn't take part in is dropped)
956
+ if (strat.actions !== 'tools') {
957
+ out.end()
958
+ log('rotate', `${client.model} has no tool calls; guided mode carries on with this message`)
959
+ const answer = await runGuided(s, task, images, signal)
960
+ s.messages.push({ role: 'assistant', content: answer ?? '' })
961
+ return answer
962
+ }
915
963
  if (!stream) {
916
964
  out.think(res.reasoning)
917
965
  out.text(res.content)
@@ -930,7 +978,7 @@ async function runNative(s, task, images, signal) {
930
978
  }
931
979
  s.messages.push({ role: 'assistant', content: res.content || '', ...(res.toolCalls.length && { tool_calls: res.toolCalls }), ...(res.reasoning && res.toolCalls.length && { reasoning_content: res.reasoning }) }) // client.js sends it by the name the provider uses, or not at all
932
980
  s.counted = { tokens: client.lastTokens, upTo: s.messages.length } // the server's count: up to this reply (auto-compact)
933
- writtenBy.set(s.messages.at(-1), client.model) // its thinking goes back to this model only
981
+ s.messages.at(-1).writer = client.model // its thinking goes back to this model only (client.js; the field isn't sent)
934
982
  // a tool call written out as text instead of made (some models do, after a long conversation): made
935
983
  const leak = !res.toolCalls.length && leakedCall(res.content)
936
984
  if (leak && tools.some((t) => t.function.name === leak.name)) {
@@ -953,7 +1001,10 @@ async function runNative(s, task, images, signal) {
953
1001
  res.content = res.content.slice(0, markup.index).trim()
954
1002
  s.messages[s.messages.length - 1] = { ...s.messages.at(-1), content: res.content }
955
1003
  }
956
- if (res.toolCalls.length) s.acted = sinceNudge = true // did real work this message, for the premature-stop check
1004
+ if (res.toolCalls.length) {
1005
+ showHeld(res.content) // not the answer: shown now, before its calls
1006
+ s.acted = sinceNudge = true // did real work this message, for the premature-stop check
1007
+ }
957
1008
  s.onEvent?.({ type: 'assistant', model: `${client.provider}/${client.model}`, content: res.content, reasoning: res.reasoning, toolCalls: res.toolCalls }) // headless output
958
1009
  if (!res.toolCalls.length && !res.content?.trim()) {
959
1010
  // Nothing at all (seen after a failed tool call): not an answer. The same request again
@@ -976,7 +1027,8 @@ async function runNative(s, task, images, signal) {
976
1027
  }
977
1028
  empty = 0
978
1029
  if (!res.toolCalls.length) {
979
- const more = sinceNudge && !s.isSub && ((await notDone(s, signal, nudged > 0, res.content)) ?? (await review(s, task, res.content, signal)))
1030
+ const more = sinceNudge && ((await notDone(s, signal, nudged > 0, res.content)) ?? (await review(s, task, res.content, signal)))
1031
+ showHeld(res.content) // after the review's line
980
1032
  if (!more) {
981
1033
  s.wrapUpLater?.(task, res.content) // after the answer, beside what comes next
982
1034
  return res.content
@@ -996,13 +1048,26 @@ async function runNative(s, task, images, signal) {
996
1048
  return null
997
1049
  }
998
1050
  }
1051
+ // a helper's line: its job, and the model doing it (named once here; its steps go by its job)
1052
+ const helperLine = (a) => `${clip(String(a.description ?? '').trim() || 'helper', 70)} ${c.faint(`· ${a.model || client.model}`)}`
999
1053
  const together = new Map()
1000
1054
  for (const call of res.toolCalls) {
1001
1055
  const args = argsOf(call)
1002
1056
  if (call.function.name !== 'agent' || !args || !allowed(s, 'agent') || res.toolCalls.filter((x) => x.function.name === 'agent').length < 2) continue
1003
- ui.step('agent', clip([args.model && `${args.model}:`, args.description].filter(Boolean).join(' '), 80))
1057
+ ui.step('agent', helperLine(args))
1004
1058
  together.set(call.id, runTool('agent', args, s, signal, call.id))
1005
1059
  }
1060
+ // several ask_user calls in one reply: one dialog, a tab each (the first call asks them all)
1061
+ const questionsOf = (a) => {
1062
+ try {
1063
+ return typeof a.questions === 'string' ? JSON.parse(a.questions) : (a.questions ?? a)
1064
+ } catch {
1065
+ return a
1066
+ }
1067
+ }
1068
+ const asks = res.toolCalls.filter((call) => call.function.name === 'ask_user' && argsOf(call))
1069
+ const askedWith = new Set(asks.length > 1 ? asks.slice(1).map((call) => call.id) : [])
1070
+ if (askedWith.size) asks[0].function.arguments = JSON.stringify({ questions: asks.flatMap((call) => [questionsOf(argsOf(call))].flat()) })
1006
1071
  // lookups in one reply (searches, pages, files) run at the same time; the same one twice, once
1007
1072
  const early = new Map() // call id → { refused } or { running }
1008
1073
  const bySig = new Map()
@@ -1027,11 +1092,11 @@ async function runNative(s, task, images, signal) {
1027
1092
  : name === 'manage' || name === 'background'
1028
1093
  ? [args.action, args.kind, args.name, args.id && `#${args.id}`].filter(Boolean).join(' ')
1029
1094
  : name === 'agent'
1030
- ? [args.model && `${args.model}:`, args.description].filter(Boolean).join(' ')
1095
+ ? ''
1031
1096
  : name === 'todo' || name === 'ask_user'
1032
1097
  ? ''
1033
1098
  : (args.path ?? args.url ?? args.query ?? args.filter ?? args.name ?? '')
1034
- if (name !== 'run_command' && !together.has(call.id)) ui.step(name, clip(detail, 80))
1099
+ 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
1035
1100
  const pre = early.get(call.id)
1036
1101
  // the first changes to the files with no plan yet (this message, or still open from an earlier one):
1037
1102
  // not made — the plan first, then the changes again. Every change in that reply (one made beside a
@@ -1039,7 +1104,7 @@ async function runNative(s, task, images, signal) {
1039
1104
  const planFirst = !s.isSub && (!s.planAsked || s.planHeldIn === res) && EDITS.has(name) && args && allowed(s, name) && ui.permission !== 'plan' && !s.todoTouched && !(s.chat.todos ?? []).some((t) => t.status !== 'completed')
1040
1105
  if (planFirst) Object.assign(s, { planAsked: true, planHeldIn: res })
1041
1106
  const refused = planFirst ? prompt('agent/plan-first', { file: String(args.path ?? args.file ?? 'the file') }) : pre ? (pre.refused ?? null) : !together.has(call.id) && args && allowed(s, name) ? guard.before(name, args) : null
1042
- let out = refused ?? (pre ? await pre.running : together.has(call.id) ? await together.get(call.id) : !allowed(s, name) ? `error: the tool ${name} is not allowed here` : args ? await runTool(name, args, s, signal, call.id) : 'error: the tool arguments were not valid JSON')
1107
+ let out = refused ?? (askedWith.has(call.id) ? 'Asked together with the first ask_user call of this reply: its result has this answer too.' : pre ? await pre.running : together.has(call.id) ? await together.get(call.id) : !allowed(s, name) ? `error: the tool ${name} is not allowed here` : args ? await runTool(name, args, s, signal, call.id) : 'error: the tool arguments were not valid JSON')
1043
1108
  if (!refused && args) out += guard.after(name, args, out)
1044
1109
  if (guard.stuck) stuck ??= guard.stuck
1045
1110
  if (args && !refused) {
@@ -1071,8 +1136,12 @@ async function runNative(s, task, images, signal) {
1071
1136
  lastCall = sig
1072
1137
  if (inRow >= 3) out += `\n\n${prompt('agent/repeating', { n: inRow, failed: false })}`
1073
1138
  if (inRow >= 5) stuck = `made the same ${name} call five times in a row`
1074
- if (name === 'read_file' || name === 'search' || name === 'list_files' || name === 'web_fetch' || name === 'web_search' || name === 'changes') ui.result(`${out.split('\n').length} lines`)
1075
- else if (name === 'agent' && !failed(out)) ui.result(`${s.ui.permission === 'plan' ? 'planned' : 'done'}: ${clip(out.split('\n').find((l) => l.trim()) ?? '', 100)}`)
1139
+ const no = refusal(out) // refused, held, declined: said so, not left looking done
1140
+ if (no) {
1141
+ if (name === 'run_command' && refused) ui.step('run', clip(String(args.command ?? ''), 80)) // a command shows itself where it runs, which this one never reached
1142
+ if (name !== 'run_command' || refused) ui.result(no) // a command's own refusals are shown there too
1143
+ } else if (name === 'read_file' || name === 'search' || name === 'list_files' || name === 'web_fetch' || name === 'web_search' || name === 'changes') ui.result(lineCount(out))
1144
+ else if (name === 'agent' && !failed(out)) ui.result(s.ui.permission === 'plan' ? 'planned' : 'done') // its reply is shown above, under its name
1076
1145
  else if (failed(out)) ui.result(clip(out, 120))
1077
1146
  client.refresh?.() // a setting changed while the tool ran (the window): its result is cut by the new one
1078
1147
  // every sizable result is saved as it comes (a web page already is, in research): later it can
@@ -1302,7 +1371,7 @@ export function missingFiles(root, reply) {
1302
1371
 
1303
1372
  // Every folder in the project (relative paths), the ignored ones (.git, node_modules…) and
1304
1373
  // HeartCode's own left out: to tell the folders a task made.
1305
- function foldersOf(root) {
1374
+ export function foldersOf(root) {
1306
1375
  const out = new Set()
1307
1376
  const walk = (rel, depth) => {
1308
1377
  if (out.size > 20_000 || depth > 12) return
@@ -1399,6 +1468,12 @@ export async function review(s, task, answer, signal) {
1399
1468
  return null
1400
1469
  }
1401
1470
 
1471
+ // "3 lines" for a result; an empty last line isn't one (a file ends with a newline, and read_file numbers the empty line after it)
1472
+ const lineCount = (out) => {
1473
+ const n = String(out).replace(/\n\s*(\d+\|)?\s*$/, '').split('\n').length
1474
+ return `${n} line${n === 1 ? '' : 's'}`
1475
+ }
1476
+
1402
1477
  // A helper agent's view of the screen: its steps are labelled, and its replies (which go to the
1403
1478
  // main agent) aren't shown as answers. Everything else is the main UI's.
1404
1479
  // Its thinking is shown whole when its reply is in (helpers working at once don't mix), named.
@@ -1437,11 +1512,26 @@ function helperUI(ui, label) {
1437
1512
  asking.set(ui, next.catch(() => {}))
1438
1513
  return next
1439
1514
  }
1515
+ // what it's doing, for the line per helper under the spinner (ui.helpers: full screen only)
1516
+ const status = (text) => {
1517
+ if (!ui.helpers?.has(label)) return
1518
+ ui.helpers.set(label, clip(String(text), 60))
1519
+ ui.render?.()
1520
+ }
1440
1521
  const own = {
1441
- step: (name, detail) => ui.step(` ${label} › ${name}`, detail),
1442
- result: (text) => ui.result(` ${text}`),
1522
+ // its steps one level in, under the agent line
1523
+ step: (name, detail = '') => {
1524
+ if (ui.afterBlock) ui.gap()
1525
+ ui.afterBlock = false
1526
+ ui.print(` ${c.accent('●')} ${c.accent(c.bold(`${label} › ${name}`))} ${c.info(detail)}`)
1527
+ status(`${name} ${detail}`)
1528
+ },
1529
+ result: (text) => ui.print(` ${c.ghost('⎿')} ${c.faint(text)}`),
1443
1530
  response,
1444
- spinner: (text) => ui.spinner(`${label} · ${text}`),
1531
+ spinner: (text) => {
1532
+ status(typeof text === 'function' ? text() : text)
1533
+ ui.spinner(typeof text === 'function' ? () => `${label} · ${text()}` : `${label} · ${text}`) // a function: re-read every frame
1534
+ },
1445
1535
  confirm: inTurn('confirm'),
1446
1536
  pick: inTurn('pick'),
1447
1537
  ask: inTurn('ask'),
@@ -1541,7 +1631,7 @@ function attachNamed(s, task) {
1541
1631
  replaceCopy(s, f, msg)
1542
1632
  results.push(msg)
1543
1633
  s.ui.step('read_file', f)
1544
- s.ui.result(`${body.split('\n').length} lines`)
1634
+ s.ui.result(lineCount(body))
1545
1635
  }
1546
1636
  if (calls.length) s.messages.push({ role: 'assistant', content: '', tool_calls: calls }, ...results)
1547
1637
  }
package/src/client.js CHANGED
@@ -140,7 +140,8 @@ export function thinkOf(full) {
140
140
  // calls only for one that calls tools (else as text), tool call ids in one form every provider
141
141
  // takes (9 letters and digits), tool arguments always JSON, and only its own thinking sent back.
142
142
  // can: { vision, actions } (the model's abilities); the saved conversation stays as it is.
143
- export const writtenBy = new WeakMap() // an assistant message → the model that wrote it
143
+ // writer: the model that wrote an assistant message (agent.js), kept on it so a resumed or forked
144
+ // chat still knows; never sent (providers refuse unknown fields).
144
145
  const IMAGE_NOTE = "(an image is here, but you can't see images: to know what's in it, ask a model that can, with the agent tool's images)"
145
146
  const callId = (id) => (/^[A-Za-z0-9]{9}$/.test(id) ? id : createHash('sha256').update(String(id)).digest('hex').slice(0, 9))
146
147
  const asJson = (a) => {
@@ -153,16 +154,16 @@ const asJson = (a) => {
153
154
  }
154
155
  export function fitFor(messages, can, model) {
155
156
  const tools = can.actions !== 'guided'
156
- return messages.map((m) => {
157
- let x = { ...m }
158
- if (x.reasoning_content && writtenBy.has(m) && writtenBy.get(m) !== model) delete x.reasoning_content
157
+ return messages.map(({ writer, ...m }) => {
158
+ let x = m
159
+ if (x.reasoning_content && writer && writer !== model) delete x.reasoning_content
159
160
  if (Array.isArray(x.content) && !can.vision) x.content = x.content.map((p) => (p.type === 'image_url' ? IMAGE_NOTE : (p.text ?? ''))).join('\n')
160
161
  if (!tools && x.role === 'tool') return { role: 'user', content: `(the result of your earlier tool call)\n${x.content}` }
161
162
  if (!tools && x.tool_calls) {
162
163
  const { tool_calls, ...rest } = x
163
164
  return { ...rest, content: [x.content, ...tool_calls.map((c) => `(called ${c.function.name} ${c.function.arguments || '{}'})`)].filter(Boolean).join('\n') }
164
165
  }
165
- const own = !writtenBy.has(m) || writtenBy.get(m) === model // extra_content (Gemini's thought_signature) only back to its writer: others refuse it (Mistral: 422 extra_forbidden)
166
+ const own = !writer || writer === model // extra_content (Gemini's thought_signature) only back to its writer: others refuse it (Mistral: 422 extra_forbidden)
166
167
  if (x.tool_calls) x.tool_calls = x.tool_calls.map(({ extra_content, ...c }) => ({ ...c, ...(own && extra_content && { extra_content }), id: callId(c.id), function: { ...c.function, arguments: asJson(c.function.arguments) } }))
167
168
  if (x.role === 'tool') x.tool_call_id = callId(x.tool_call_id)
168
169
  return x
@@ -530,7 +531,7 @@ export class Client {
530
531
  // a model that goes silent is then given up on after idleMs, not after the whole timeout
531
532
  if (body.stream === undefined && !body.tools?.length && !this.quirks.noStream) req.stream = true
532
533
  const can = this.can && { ...this.can, vision: this.can.vision && !this.quirks.noImages }
533
- if (can && req.messages) req.messages = fitFor(req.messages, can, this.model)
534
+ if (req.messages) req.messages = can ? fitFor(req.messages, can, this.model) : req.messages.map(({ writer, ...m }) => m)
534
535
  if (can?.actions === 'guided') delete req.tools
535
536
  const thinks = Boolean(this.can?.thinking)
536
537
  // The model's thinking on its earlier steps (agent.js keeps it as reasoning_content): sent by the
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) && n !== st.avoid) // a step that just repeated with nothing new isn't offered again (a small model picks it over and over)
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,7 +171,9 @@ 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) {
@@ -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]()
@@ -296,7 +310,31 @@ class Guided {
296
310
  }
297
311
  if (repeats === 1) this.note(null, 'warning', prompt('guided/note-repeated'))
298
312
  }
299
- 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
300
338
  }
301
339
 
302
340
  async describeImages(images) {
@@ -322,6 +360,7 @@ class Guided {
322
360
  this.note(`read:${f}`, `contents of ${f}`, clip(body, Math.floor(this.s.strat.context * 3.5 * 0.4)))
323
361
  if (!quiet) this.ui.step('read', f)
324
362
  this.st.reads++
363
+ return body
325
364
  }
326
365
 
327
366
  async pickAction() {
@@ -357,7 +396,11 @@ class Guided {
357
396
 
358
397
  async read() {
359
398
  const f = await this.pickFile(false, this.files)
360
- if (f) this.readNote(f)
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
+ }
361
404
  return `read:${f}`
362
405
  }
363
406
 
@@ -366,7 +409,7 @@ class Guided {
366
409
  const q = unquote(answerText(res.content).split('\n')[0].trim())
367
410
  if (!q) return 'search:'
368
411
  this.ui.step('search', q)
369
- const out = searchFiles(this.s.root, q)
412
+ const out = await this.tool('search', { query: q }, () => searchFiles(this.s.root, q))
370
413
  this.ui.result(out.startsWith('no matches') ? 'no matches' : `${out.split('\n').length} matches`)
371
414
  this.note(`search:${q}`, `search results for "${q}"`, out)
372
415
  return `search:${q}`
@@ -377,6 +420,7 @@ class Guided {
377
420
  // Weak models pick the first option: offer the code under test before the tests themselves.
378
421
  let files = [...new Set([...seen, ...this.files])]
379
422
  files = [...files.filter((x) => !TEST_FILE.test(x)), ...files.filter((x) => TEST_FILE.test(x))]
423
+ this.st.editTries++
380
424
  let f = await this.pickFile(true, files)
381
425
  if (!f) return 'edit:'
382
426
  const old = fs.readFileSync(resolveIn(this.s.root, f), 'utf8')
@@ -480,9 +524,13 @@ class Guided {
480
524
 
481
525
  async apply(f, old, next) {
482
526
  this.ui.stopSpin()
483
- const r = await proposeWrite(this.s, f, old, next)
484
- this.note(null, `${old ? 'edit' : 'create'} ${f}`, writeResult(f, r) + (r.diff ? '\n' + r.diff : ''))
485
- 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') {
486
534
  this.st.edits++
487
535
  this.changed.add(f)
488
536
  this.st.editsSinceRun++
@@ -521,7 +569,8 @@ class Guided {
521
569
  const n = sugg[Number(/^(\d+)[.):]?(\s|$)/.exec(t)?.[1]) - 1] // "2", "2.", "2. npm test"
522
570
  const cmd = n ?? cleanCommand(t)
523
571
  if (!cmd) return 'run:'
524
- 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
525
574
  const code = /^exit code (\S+)/.exec(out)?.[1]
526
575
  this.st.runs++
527
576
  this.st.editsSinceRun = 0
@@ -543,8 +592,8 @@ class Guided {
543
592
  async ask() {
544
593
  const res = await this.query(prompt('guided/ask-user'), { room: 120 })
545
594
  const q = res.content.trim()
546
- const a = await this.ui.ask(`${c.cyan('heartcode asks:')} ${q}\n${c.magenta('> ')}`)
547
- 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)
548
597
  return `ask:${q}`
549
598
  }
550
599
 
@@ -553,7 +602,8 @@ class Guided {
553
602
  // the first of yours with tool calls (that sees images, if the task came with some)
554
603
  const team = this.s.team().filter((t) => t.tools && (!this.images || t.images))
555
604
  const t = team[0]
556
- 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))
557
607
  this.note('delegate', `what ${t.model} did for the task`, done)
558
608
  this.st.delegated = true
559
609
  return 'delegate'
package/src/headless.js CHANGED
@@ -99,6 +99,8 @@ export class HeadlessUI {
99
99
  setLog() {}
100
100
  close() {}
101
101
  leaveFullscreen() {}
102
+ recolor() {}
103
+ setMouse() {}
102
104
  }
103
105
 
104
106
  // Runs the messages (prompt, or stdin) and writes the output. Returns the exit code.
@@ -186,7 +188,7 @@ export async function runHeadless(app, opts) {
186
188
  let error = null
187
189
  try {
188
190
  const k = /^\/(\S+)\s*([\s\S]*)$/.exec(text)
189
- 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
190
192
  answer = await s.run(skill && skill.use !== 'model' ? await app.expandSkill(skill, k[2]) : text, current.ctl.signal, images)
191
193
  } catch (e) {
192
194
  error = current.ctl.signal.aborted ? 'interrupted' : e.message
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