heartcode 0.1.45 → 0.1.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/agent.js CHANGED
@@ -3,12 +3,12 @@ import os from 'node:os'
3
3
  import { log } from './log.js'
4
4
  import { prompt, userInstructions } from './prompts.js'
5
5
  import { newChat } from './sessions.js'
6
+ import { skillFiles, readSkillFile } from './skills.js'
6
7
  import path from 'node:path'
7
- import { est, estMessages, Client, writtenBy, tokensOf, COMPACT_SHARE } from './client.js'
8
+ import { est, estMessages, Client, tokensOf, COMPACT_SHARE } from './client.js'
8
9
  import { runGuided } from './guided.js'
9
10
  import { markUsed, removeResearch, findResearch } from './research.js'
10
- import { loadRankings, rankIn, rankings } from './rankings.js'
11
- import { TOOL_DEFS, PLAN_HIDDEN, folderView, readOnlyCommand, 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
@@ -117,7 +128,7 @@ export class Session {
117
128
  // A model shown its own work tends to carry on with it (calling tools, or writing tool calls
118
129
  // as text) instead of summarizing: so it's told what it is, and a reply that isn't a summary
119
130
  // is asked for again once; then the compaction fails (the conversation is trimmed instead).
120
- const request = (extra) => prompt('compact/summarize', { conversation: cut(), focus }) + extra
131
+ const request = (extra) => prompt('compact/summarize', { conversation: cut(), focus, branch: false, files: '' }) + extra
121
132
  const send = (extra) =>
122
133
  client.chat({ messages: [{ role: 'system', content: prompt('compact/summarizer') }, { role: 'user', content: request(extra) }] }, { signal })
123
134
  const ask = (extra = '') => send(extra)
@@ -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
  }
@@ -182,7 +193,7 @@ export class Session {
182
193
  if (!this.isSub) for (const e of takeConfigErrors()) ui.warn(e) // a hooks.json or mcp.json that doesn't parse
183
194
  const hook = await runHooks(this, 'UserPromptSubmit', { prompt: task }, signal)
184
195
  if (hook.block) {
185
- const answer = prompt('agent/hook-blocked-prompt', { reason: hook.block })
196
+ const answer = prompt('agent/hook', { reason: hook.block, blocked: true })
186
197
  ui.warn(answer)
187
198
  return answer
188
199
  }
@@ -202,24 +213,16 @@ export class Session {
202
213
  let { text, images } = extractImages(task, this.root)
203
214
  images = [...images, ...extra]
204
215
  if (images.length && !this.strat.vision) {
205
- const fails = (t) => this.failures?.[`${t.provider} ${t.model}`] ?? 0
206
- const seers = (this.team?.() ?? []).filter((t) => t.images).sort((a, b) => fails(a) - fails(b)) // your models that can: they describe them
216
+ const seers = (this.team?.() ?? []).filter((t) => t.images) // your models that can, in your order: they describe them
207
217
  if (seers.length) text += await this.describeImages(images, seers, text, signal)
208
218
  else this.ui.warn(`${this.client.model} can't read images (per its probe); ignoring ${images.length} image(s)`)
209
219
  images = []
210
220
  }
211
- // An orchestrator: the message starts on one of the models picked for it, which answers at once
212
- // or hands the work to your other models (it decides) — only when there are others to hand to.
213
- if (!this.isSub) {
214
- const lead = this.fitMode?.() ? (this.orchestrators?.() ?? []) : []
215
- this.client.orderBy?.(lead.length ? lead.map((t) => `${t.provider} ${t.model}`) : null)
216
- this.orchestrating = lead.length > 0 // (then team() leaves the orchestrators out)
217
- if (this.orchestrating && !this.team?.().length) this.orchestrating = false // no one to hand to: it does the work itself
218
- if (this.orchestrating) rankings().catch(() => {}) // their places, for its list of models: fetched behind (once a week), never waited for
219
- 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}${this.orchestrating ? ', orchestrating' : ', your order'})` : ''}`)
220
- }
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})` : ''}`)
221
222
  log('task', `${text} (${this.strat.actions} mode, ${images.length} image(s))`)
222
- 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
223
226
  log('answer', answer) // the conversation's log
224
227
  log('task', `answered (${String(answer ?? '').length} characters)`)
225
228
  this.history.push({ task: text, answer })
@@ -245,17 +248,15 @@ export class Session {
245
248
  }
246
249
  const name = (t) => `${t.provider} ${t.model}`
247
250
  const self = { provider: this.client.provider, model: this.client.model, images: this.strat.vision, tools: this.strat.actions === 'tools', self: true }
248
- const all = [...(this.orchestrating ? [] : [self]), ...(this.team?.() ?? [])] // an orchestrator hands work out, never to itself
251
+ const all = [self, ...(this.team?.() ?? [])] // this model, then your others in your list's order
249
252
  const want = String(args.model ?? '').trim()
250
253
  // only one model available (a pinned model, or you have just one): helpers use it, whatever was asked
251
- const first = !want || all.length === 1 ? all[0] : (all.find((t) => name(t) === want) ?? all.find((t) => t.model === want || want.endsWith(` ${t.model}`)))
254
+ 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}`)))
252
255
  if (!first) return `error: no model "${want}". Yours: ${all.map(name).join(', ')}`
253
- // the one asked for first (if it can do the job), then the others that can: those that call
254
- // tools first, then the ones that failed least this session, in your list's order
256
+ // the one asked for first, then the others in your list's order: only those that can do the job
257
+ // (images need a model that sees them)
255
258
  const able = (t) => !images.length || t.images
256
- const fails = (t) => this.failures?.[name(t)] ?? 0
257
- const rests = (t) => (this.resting?.[name(t)] ?? 0) > Date.now() // out of quota: tried last
258
- const order = [first, ...all.filter((t) => t !== first).sort((a, b) => b.tools - a.tools || fails(a) - fails(b))].filter(able).sort((a, b) => rests(a) - rests(b))
259
+ const order = [first, ...all.filter((t) => t !== first)].filter(able)
259
260
  if (!order.length) return 'error: none of your models can see images'
260
261
  const failed = []
261
262
  for (const [i, t] of order.entries()) {
@@ -264,13 +265,11 @@ export class Session {
264
265
  answer = (await this.#helper(t, task, images, args.description, id, signal, args.ownFiles))?.trim()
265
266
  } catch (e) {
266
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
267
269
  failed.push(`${t.model}: ${clip(e.message, 150)}`)
268
270
  }
269
271
  if (answer) return t === first ? answer : `(Answered by ${name(t)}, not ${name(first)}${failed.length ? `: ${failed.join('; ')}` : ''})\n\n${answer}`
270
- if (failed.length < i + 1) {
271
- failed.push(`${t.model}: no reply`)
272
- if (this.failures) this.failures[name(t)] = fails(t) + 1 // (a failed request is counted where it fails: engine's onFail)
273
- }
272
+ if (failed.length < i + 1) failed.push(`${t.model}: no reply`)
274
273
  if (order[i + 1]) this.ui.warn(`${t.model} couldn't do it (${failed.at(-1).slice(t.model.length + 2)}); handing it to ${order[i + 1].model}`)
275
274
  }
276
275
  return `error: none of your models that can do it managed: ${failed.join('; ')}`
@@ -284,22 +283,31 @@ export class Session {
284
283
  if (this.engineFor) {
285
284
  ;({ client, profile, strat } = await this.engineFor(t))
286
285
  const was = client.retryIf
287
- client.retryIf = (e, attempt) => attempt < 3 && !e.notStarted && e.status !== 429 && (!was || was(e, attempt)) // not answering in time or rate-limited: the next model, not another wait
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
288
287
  }
289
- 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
290
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
291
291
  if (ownFiles?.length) helper.ownFiles = ownFiles.map((f) => path.resolve(this.root, f)) // a part of the plan: changes only its own files
292
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 })
293
293
  helper.track = (rel, before) => this.track(rel, before)
294
294
  helper.mcpGate = async () => (await this.#gate(helper), () => {})
295
295
  if (this.onEvent) helper.onEvent = (e) => this.onEvent({ ...e, parent: id, helper: label })
296
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)
297
298
  try {
298
299
  const answer = await (strat.actions === 'tools' ? runNative : runGuided)(helper, task, images, signal)
299
300
  log('agent', `helper "${label}" done`, answer)
300
301
  return answer
301
302
  } finally {
303
+ if (this.ui.helpers?.delete(label)) this.ui.render?.()
302
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
+ }
303
311
  }
304
312
  }
305
313
 
@@ -387,7 +395,7 @@ export class Session {
387
395
  const { client, strat } = this
388
396
  const room = Math.floor((strat.context * 0.6 * 3.5) / (strat.ratio ?? 1))
389
397
  const text = conversation.length > room ? `[… the earliest part is cut]\n${conversation.slice(-room)}` : conversation
390
- const request = prompt('compact/branch-summarize', { conversation: text, files: files.join(', ') })
398
+ const request = prompt('compact/summarize', { conversation: text, files: files.join(', '), branch: true, focus: '' })
391
399
  const messages = [{ role: 'system', content: prompt('compact/summarizer') }, { role: 'user', content: request }]
392
400
  const summary = notSummary((await client.chat({ messages }, { signal })).content)
393
401
  if (!summary) throw new Error('the model did not write a summary')
@@ -550,43 +558,35 @@ const rootList = (root) => {
550
558
  return v.error ? `(can't read it: ${v.error})` : v.entries.length ? v.entries.join(' · ') + (v.more ? ` · … ${v.more} more` : '') : '(empty)'
551
559
  }
552
560
 
561
+ // An always-on skill in the system prompt as the skill tool would give it: its text, the files it
562
+ // says come with it (load), and the list of its other files (read with the skill tool's "file")
563
+ const alwaysSkill = (k) => {
564
+ const files = skillFiles(k)
565
+ return k.body + (k.load ?? []).map((f) => `\n\n--- ${f} ---\n${readSkillFile(k, f)}`).join('') + (files.length ? `\n\n${prompt('agent/skill-files', { name: k.name, files: files.join('\n') })}` : '')
566
+ }
567
+
553
568
  const SYSTEM = (s) => {
554
- if (s.orchestrating) return prompt('agent/orchestrator', { root: s.root, env: envLine(), today: new Date().toISOString().slice(0, 10), ...teamOf(s) })
555
569
  const instructions = userInstructions(s.root)
556
570
  return [
557
- 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) }),
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
558
572
  instructions && prompt('agent/instructions', { instructions }),
559
- ...[...(s.skills?.values() ?? [])].filter((k) => k.use === 'always').map((k) => k.body), // skills that say how to work (use: always)
560
- s.memory && prompt('agent/memory', { tags: s.memory.tagSummary() || '(none yet)' }),
561
- s.strat.vision && prompt('agent/you-see'), // models that can see often say they can't
562
- s.director && !s.appendSystem && s.director.app.cfg.director !== false && prompt('agent/director'),
573
+ ...[...(s.skills?.values() ?? [])].filter((k) => k.use === 'always').map(alwaysSkill), // skills that say how to work (use: always), with the files they bring
563
574
  !s.isSub && teamPrompt(s),
564
575
  s.isSub && prompt('agent/subagent'),
565
- s.appendSystem && prompt('agent/caller'),
566
- s.appendSystem,
576
+ s.appendSystem && prompt('agent/instructions', { instructions: s.appendSystem, caller: true }),
567
577
  ]
568
578
  .filter(Boolean)
569
579
  .join('\n\n')
570
580
  }
571
581
 
572
582
  // Your other models and what each can do, for the agent tool's model (only when there are any): a
573
- // short line each — with an orchestrator, with its places in the public rankings (rankings.js).
574
- const RANKED_AS = { overall: 'text:overall', code: 'text:coding', web: 'webdev:webdev', vision: 'vision:overall' }
583
+ // short line each, in your list's order.
575
584
  const teamPrompt = (s) => {
576
585
  const team = s.team?.() ?? []
577
- return team.length ? prompt('agent/team', teamOf(s, team)) : ''
578
- }
579
- const teamOf = (s, team = s.team?.() ?? []) => {
580
- const data = s.fitMode?.() ? loadRankings() : null
581
- const ranks = (t) => (data ? Object.entries(RANKED_AS).map(([k, list]) => ((r) => r && `${k} #${r.rank}`)(rankIn(t.model, list, data))).filter(Boolean).join(' ') : '')
582
- const line = (t) => {
583
- const failed = s.failures?.[`${t.provider} ${t.model}`]
584
- const rest = Math.ceil(((s.resting?.[`${t.provider} ${t.model}`] ?? 0) - Date.now()) / 60_000)
585
- const facts = [t.tools === false && 'no tool calls', t.images && 'images', t.thinking && 'thinking', ranks(t) && `ranked ${ranks(t)}`, failed && `failed ${failed}× this session`, rest > 0 && `out of quota for ${rest < 120 ? `${rest} min` : `${Math.round(rest / 60)} h`}`].filter(Boolean)
586
- return `- ${t.provider} ${t.model}${facts.length ? `: ${facts.join(', ')}` : ''}`
587
- }
588
- const you = [s.strat.vision ? 'images' : 'no images', s.strat.thinking && 'thinking', ranks(s.client) && `ranked ${ranks(s.client)}`].filter(Boolean).join(', ')
589
- return { models: team.map(line).join('\n'), you, ranked: Boolean(data) }
586
+ if (!team.length) return ''
587
+ const can = (t) => [t.tools === false && 'no tool calls', t.images && 'images', t.thinking && 'thinking'].filter(Boolean)
588
+ const line = (t) => `- ${t.provider} ${t.model}${can(t).length ? `: ${can(t).join(', ')}` : ''}`
589
+ return prompt('agent/team', { models: team.map(line).join('\n'), you: [s.strat.vision ? 'images' : 'no images', s.strat.thinking && 'thinking'].filter(Boolean).join(', ') })
590
590
  }
591
591
 
592
592
  const sizeOf = (m) =>
@@ -764,7 +764,8 @@ async function runNative(s, task, images, signal) {
764
764
  // Unchanged, it stays the same text, so a provider's prompt cache still holds.
765
765
  const sys = SYSTEM(s)
766
766
  if (!s.messages) {
767
- 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 ?? '' }])]
768
769
  } else if (s.messages[0]?.content !== sys && s.messages[0]?.role === 'system') {
769
770
  s.messages[0] = { ...s.messages[0], content: sys }
770
771
  }
@@ -787,7 +788,10 @@ async function runNative(s, task, images, signal) {
787
788
  if (!k?.tokens || k.upTo > s.messages.length) return all
788
789
  return Math.max(all, k.tokens + tokensOf(s.messages.slice(k.upTo), null, Math.max(1, ratio)))
789
790
  }
790
- 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
+ }
791
795
  const fullness = () => `context ${Math.round((used() / strat.context) * 100)}% full (~${kTokens(used())} of ${kTokens(strat.context)})`
792
796
  // Still that full after compacting (what every request carries, the system prompt and the tools'
793
797
  // schemas, takes most of the window): compacting again won't free anything, so not until it has
@@ -826,20 +830,16 @@ async function runNative(s, task, images, signal) {
826
830
  // pages already read for this project that match: titles only (the model opens one when needed)
827
831
  const pages = s.isSub || !s.memory ? [] : findResearch(s.root, task, 6).filter((r) => r.kind !== 'search' && !sent.has(`research:${r.name}:${r.fetched}`))
828
832
  s.chat.sentNotes = [...sent, ...notes.map(key), ...pages.map((r) => `research:${r.name}:${r.fetched}`)]
829
- const known = [
830
- notes.length && prompt('agent/memory-relevant', { notes: notes.map((n) => `[[${n.name}]] — ${n.description}`).join('\n') }),
831
- pages.length && prompt('agent/research-known', { pages: pages.map((r) => `- ${r.title} — ${r.url} (read ${r.fetched}) → ${r.file}`).join('\n') }),
832
- ].filter(Boolean)
833
- const text = known.length ? `${task}\n\n${known.join('\n\n')}` : task
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() : ''
834
+ const text = known ? `${task}\n\n${known}` : task
834
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
835
- const planning = ui.permission === 'plan'
836
- 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
837
837
  const content = images.length ? [{ type: 'text', text: said }, ...images.map((url) => ({ type: 'image_url', image_url: { url } }))] : said
838
838
  s.messages.push({ role: 'user', content })
839
839
  attachNamed(s, task) // files the message names: as if already read (saves a round trip each)
840
840
  // the tools: built again each step (the model answering may change; client.js leaves them out for
841
- // one that can't call tools)
842
- 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)
843
843
  const guard = newGuard() // calls made again with nothing changed: the earlier result instead
844
844
  let lastCall = '' // the last call (tool and arguments), and how many times in a row
845
845
  let inRow = 0
@@ -857,7 +857,9 @@ async function runNative(s, task, images, signal) {
857
857
  let nudged = 0 // reminders sent this message about open todo items, a premature stop, or a Stop hook
858
858
  let sinceNudge = true // a tool call made since the last reminder: one that changed nothing isn't sent again (no count: it goes on while the model gets on)
859
859
  s.planAsked = false // asked for a plan before its first change, this message
860
+ s.askedUser = s.askNudged = false // asked with ask_user / told to, this message (a reply of questions as text: askedInText)
860
861
  s.splitAsked = false // asked whether a plan's parts could run side by side, this message
862
+ s.lookedUp = s.researchAsked = false // searched or read the web this message / asked whether the plan needs it
861
863
  // what changed and when it was last checked, this message: a change not run/tested since isn't done
862
864
  Object.assign(s, { changed: new Set(), seq: 0, lastChangeAt: -1, lastCheckAt: -1, reviewedAt: -1, checksSince: 0, spots: new Map() })
863
865
 
@@ -866,9 +868,12 @@ async function runNative(s, task, images, signal) {
866
868
  let stuck = null // why it's going round in circles (then the next model takes over; nothing stops but Esc)
867
869
  // Going round in circles: the next of your models carries on (a different model often gets out of
868
870
  // it); with no other model, a warning, and it goes on being told what it repeats — only Esc stops it.
871
+ // A helper has only the model it was given and maybe nobody to press Esc: it ends, failed, and
872
+ // the job goes to your next model.
869
873
  const handOver = (why) => {
870
874
  const was = client.model
871
875
  if (client.moveOn?.(`${was} ${why}`)) ui.warn(`${was} ${why}; handing over to ${client.model}`)
876
+ else if (s.isSub) throw Object.assign(new Error(`${was} ${why}`), { stuck: true })
872
877
  else ui.warn(`${was} ${why} — it carries on, told so; Esc stops it`)
873
878
  }
874
879
  let garbled = 0 // replies with a tool call written as text (template markup), this message
@@ -880,7 +885,7 @@ async function runNative(s, task, images, signal) {
880
885
  const tools = toolList()
881
886
  s.lastTools = tools // what the requests carry: the findings note before compacting sends the same (compact)
882
887
  if (s.maxTurns && step >= s.maxTurns) {
883
- 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`)
884
889
  throw Object.assign(new Error(`stopped after ${s.maxTurns} steps (--max-turns)`), { maxTurns: true })
885
890
  }
886
891
  // after a failed compaction, the next try waits until the conversation has grown by 5% of the window
@@ -901,7 +906,20 @@ async function runNative(s, task, images, signal) {
901
906
  if (s.messages[0]?.content !== now && s.messages[0]?.role === 'system') s.messages[0] = { ...s.messages[0], content: now }
902
907
  pairTools(s.messages)
903
908
  ui.spinner('thinking')
904
- 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
+ }
905
923
  const stream = strat.stream
906
924
  // A long tool call (a whole file) streams in silently: say what's being written.
907
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`)
@@ -910,9 +928,13 @@ async function runNative(s, task, images, signal) {
910
928
  s.refreshSystem = false
911
929
  let res
912
930
  try {
913
- 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 })
914
932
  } catch (e) {
915
- if (!e.tooBig) throw e
933
+ if (!e.tooBig) {
934
+ ui.stopSpin()
935
+ out.end() // what came of it is closed (a helper's turn to show its thinking ends)
936
+ throw e
937
+ }
916
938
  // The model list moved on (the one before failed) to a model whose window can't hold the
917
939
  // conversation: compacted for it (by it, to its size), then the same step again. Once: still
918
940
  // too big after that (its window can't even hold the start), it's sent anyway.
@@ -929,11 +951,21 @@ async function runNative(s, task, images, signal) {
929
951
  }
930
952
  refitted = false
931
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
+ }
932
963
  if (!stream) {
933
964
  out.think(res.reasoning)
934
965
  out.text(res.content)
935
966
  }
936
967
  out.end()
968
+ client.announceSwitch?.() // "↻ … answered": under the reply, on a line of its own
937
969
  // the reply went round and round (client.js cut it): told so, and asked again
938
970
  if (res.looped) {
939
971
  if (++looping > 3) {
@@ -941,12 +973,12 @@ async function runNative(s, task, images, signal) {
941
973
  looping = 0
942
974
  } else ui.warn(`${client.model} went into a loop; cut, and asked again`)
943
975
  if (res.content.trim()) s.messages.push({ role: 'assistant', content: res.content })
944
- s.messages.push({ role: 'user', content: prompt('agent/looped', { sample: res.looped }) })
976
+ s.messages.push({ role: 'user', content: prompt('agent/bad-reply', { sample: res.looped }) })
945
977
  continue
946
978
  }
947
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
948
980
  s.counted = { tokens: client.lastTokens, upTo: s.messages.length } // the server's count: up to this reply (auto-compact)
949
- 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)
950
982
  // a tool call written out as text instead of made (some models do, after a long conversation): made
951
983
  const leak = !res.toolCalls.length && leakedCall(res.content)
952
984
  if (leak && tools.some((t) => t.function.name === leak.name)) {
@@ -962,14 +994,17 @@ async function runNative(s, task, images, signal) {
962
994
  if (markup && garbled++ < 2) {
963
995
  log('task', `${client.model}: a tool call written as text; asking again`, res.content)
964
996
  s.messages.pop()
965
- s.messages.push({ role: 'user', content: prompt('agent/garbled-call') })
997
+ s.messages.push({ role: 'user', content: prompt('agent/bad-reply', { sample: '' }) })
966
998
  continue
967
999
  }
968
1000
  if (markup) {
969
1001
  res.content = res.content.slice(0, markup.index).trim()
970
1002
  s.messages[s.messages.length - 1] = { ...s.messages.at(-1), content: res.content }
971
1003
  }
972
- 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
+ }
973
1008
  s.onEvent?.({ type: 'assistant', model: `${client.provider}/${client.model}`, content: res.content, reasoning: res.reasoning, toolCalls: res.toolCalls }) // headless output
974
1009
  if (!res.toolCalls.length && !res.content?.trim()) {
975
1010
  // Nothing at all (seen after a failed tool call): not an answer. The same request again
@@ -992,7 +1027,8 @@ async function runNative(s, task, images, signal) {
992
1027
  }
993
1028
  empty = 0
994
1029
  if (!res.toolCalls.length) {
995
- 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
996
1032
  if (!more) {
997
1033
  s.wrapUpLater?.(task, res.content) // after the answer, beside what comes next
998
1034
  return res.content
@@ -1012,13 +1048,26 @@ async function runNative(s, task, images, signal) {
1012
1048
  return null
1013
1049
  }
1014
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}`)}`
1015
1053
  const together = new Map()
1016
1054
  for (const call of res.toolCalls) {
1017
1055
  const args = argsOf(call)
1018
1056
  if (call.function.name !== 'agent' || !args || !allowed(s, 'agent') || res.toolCalls.filter((x) => x.function.name === 'agent').length < 2) continue
1019
- ui.step('agent', clip([args.model && `${args.model}:`, args.description].filter(Boolean).join(' '), 80))
1057
+ ui.step('agent', helperLine(args))
1020
1058
  together.set(call.id, runTool('agent', args, s, signal, call.id))
1021
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()) })
1022
1071
  // lookups in one reply (searches, pages, files) run at the same time; the same one twice, once
1023
1072
  const early = new Map() // call id → { refused } or { running }
1024
1073
  const bySig = new Map()
@@ -1043,19 +1092,19 @@ async function runNative(s, task, images, signal) {
1043
1092
  : name === 'manage' || name === 'background'
1044
1093
  ? [args.action, args.kind, args.name, args.id && `#${args.id}`].filter(Boolean).join(' ')
1045
1094
  : name === 'agent'
1046
- ? [args.model && `${args.model}:`, args.description].filter(Boolean).join(' ')
1095
+ ? ''
1047
1096
  : name === 'todo' || name === 'ask_user'
1048
1097
  ? ''
1049
1098
  : (args.path ?? args.url ?? args.query ?? args.filter ?? args.name ?? '')
1050
- 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
1051
1100
  const pre = early.get(call.id)
1052
1101
  // the first changes to the files with no plan yet (this message, or still open from an earlier one):
1053
1102
  // not made — the plan first, then the changes again. Every change in that reply (one made beside a
1054
1103
  // refused one is easily taken for refused too), once a message; not a helper's (its job is its plan)
1055
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')
1056
1105
  if (planFirst) Object.assign(s, { planAsked: true, planHeldIn: res })
1057
- const refused = planFirst ? prompt('agent/plan-first') : pre ? (pre.refused ?? null) : !together.has(call.id) && args && allowed(s, name) ? guard.before(name, args) : null
1058
- 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')
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
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')
1059
1108
  if (!refused && args) out += guard.after(name, args, out)
1060
1109
  if (guard.stuck) stuck ??= guard.stuck
1061
1110
  if (args && !refused) {
@@ -1085,10 +1134,14 @@ async function runNative(s, task, images, signal) {
1085
1134
  const sig = `${name} ${call.function.arguments}`
1086
1135
  inRow = sig === lastCall ? inRow + 1 : 1
1087
1136
  lastCall = sig
1088
- if (inRow >= 3) out += `\n\n${prompt('agent/repeating', { n: inRow })}`
1137
+ if (inRow >= 3) out += `\n\n${prompt('agent/repeating', { n: inRow, failed: false })}`
1089
1138
  if (inRow >= 5) stuck = `made the same ${name} call five times in a row`
1090
- if (name === 'read_file' || name === 'search' || name === 'list_files' || name === 'web_fetch' || name === 'web_search' || name === 'changes') ui.result(`${out.split('\n').length} lines`)
1091
- 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
1092
1145
  else if (failed(out)) ui.result(clip(out, 120))
1093
1146
  client.refresh?.() // a setting changed while the tool ran (the window): its result is cut by the new one
1094
1147
  // every sizable result is saved as it comes (a web page already is, in research): later it can
@@ -1117,7 +1170,7 @@ async function runNative(s, task, images, signal) {
1117
1170
  }
1118
1171
  // screenshots from MCP tools: tool results are text only, so images follow as a message
1119
1172
  if (s.pendingImages?.length) {
1120
- s.messages.push({ role: 'user', content: [{ type: 'text', text: prompt('agent/tool-images', { files: s.pendingImages.map((p) => p.file).join(', ') }) }, ...s.pendingImages.map(({ url }) => ({ type: 'image_url', image_url: { url } }))] })
1173
+ s.messages.push({ role: 'user', content: [{ type: 'text', text: prompt('agent/tool-images', { unseen: false, files: s.pendingImages.map((p) => p.file).join(', ') }) }, ...s.pendingImages.map(({ url }) => ({ type: 'image_url', image_url: { url } }))] })
1121
1174
  s.pendingImages = []
1122
1175
  }
1123
1176
  }
@@ -1134,6 +1187,7 @@ const EDITS = new Set(['edit_file', 'write_file', 'append_file', 'apply_patch'])
1134
1187
  const CHECKS = new Set(['run_command', 'mcp', 'agent', 'lsp'])
1135
1188
  // Files only read by people (a change there needs no run to check it).
1136
1189
  const DOC_FILE = /\.(md|mdx|txt|rst|adoc)$/i
1190
+
1137
1191
  // Tools that only look (nothing changes): several in one reply run at the same time.
1138
1192
  const LOOKUPS = new Set(['web_search', 'web_fetch', 'read_file', 'search', 'list_files', 'find_command', 'lsp', 'changes'])
1139
1193
  export function newGuard() {
@@ -1161,14 +1215,14 @@ export function newGuard() {
1161
1215
  if (!was || (name === 'run_command' && Date.now() - was.at > 20_000)) return null
1162
1216
  repeats++
1163
1217
  if (repeats >= 10) g.stuck = 'kept making calls it had already made (10 repeats)' // going round, not finding anything new
1164
- return prompt('agent/already-done', { result: was.out }) + (repeats >= 3 ? `\n\n${prompt('agent/circling')}` : '')
1218
+ return prompt('agent/already-done', { result: was.out, circling: repeats >= 3 })
1165
1219
  }
1166
1220
  g.after = (name, a, out) => {
1167
1221
  let note = ''
1168
1222
  if (name === 'run_command') {
1169
1223
  const code = Number(/^exit code (-?\d+)/.exec(out)?.[1] ?? 0)
1170
1224
  failing = code ? failing + 1 : 0
1171
- if (failing >= 4) note += `\n\n${prompt('agent/failing-in-row', { n: failing })}`
1225
+ if (failing >= 4) note += `\n\n${prompt('agent/repeating', { n: failing, failed: true })}`
1172
1226
  if (failing >= 8) g.stuck = 'had eight commands in a row fail'
1173
1227
  if (!readOnlyCommand(String(a.command ?? ''))) epoch++ // it may have changed things: what came before can be done again
1174
1228
  }
@@ -1248,34 +1302,49 @@ async function learnFromFixes(s, fixed, signal) {
1248
1302
  // The model said it would do something but stopped without doing it ("let me rewrite…", "I'll fix…"):
1249
1303
  // a next action named, then no tool call. Not matched by explanations ("let me explain", "you can run").
1250
1304
  const PROMISED_MORE =
1251
- /\b(?:let me|i'?ll|i will|i'?m going to|i am going to|i need to|i'?m about to|next,? i'?ll|now,? i'?ll)\b[^.!?\n]{0,70}\b(?:do|make|create|add|fix|write|update|change|implement|build|run|rewrite|replace|edit|install|set ?up|finish|continue|proceed|start|redo|retry|try)\b/i
1305
+ /\b(?:let me|i['’]?ll|i will|i['’]?m going to|i am going to|i need to|i['’]?m about to|next,? i['’]?ll|now,? i['’]?ll)\b[^.!?\n]{0,70}\b(?:do|make|create|add|fix|write|update|change|implement|build|run|rewrite|replace|edit|install|set ?up|finish|continue|proceed|start|redo|retry|try|hand|pass|send|give)\b/i
1252
1306
 
1253
1307
  // Is the task really done, or did the model stop early? Open todo items, or (after it did real work)
1254
1308
  // a reply that only promises more, get one nudge to keep going. Then any Stop hook. null = truly done.
1309
+ // A reply that is mostly questions for the user, written as text: only ask_user opens the dialog to
1310
+ // answer them in (weaker models type them out and stop). At least two questions, and most of what it says.
1311
+ export function askedInText(reply) {
1312
+ const sentences = String(reply).replace(/```[\s\S]*?```/g, '').split(/(?<=[.?!])\s+|\n+/).map((x) => x.trim()).filter((x) => /\w/.test(x))
1313
+ const questions = sentences.filter((x) => /\?["')\]]*$/.test(x)).length
1314
+ return questions >= 2 && questions / sentences.length >= 0.4
1315
+ }
1316
+
1255
1317
  export async function notDone(s, signal, again, reply = '') {
1318
+ // questions typed out instead of asked: once a message, asked again with the tool (someone's there to answer)
1319
+ if (!s.isSub && !s.ui.noUser && !s.askedUser && !s.askNudged && askedInText(reply)) {
1320
+ s.askNudged = true
1321
+ log('task', 'asked its questions as text; told to use ask_user')
1322
+ return prompt('agent/not-done', { asked: true })
1323
+ }
1256
1324
  const open = s.todoTouched && s.ui.permission !== 'plan' ? (s.chat.todos ?? []).filter((t) => t.status !== 'completed') : [] // plan mode: they wait for the approval
1257
1325
  if (open.length) {
1258
1326
  log('task', `stopped with ${open.length} open todo item(s); reminding`)
1259
- return prompt('agent/todo-unfinished', { items: open.map((t) => `- ${t.content}`).join('\n') })
1327
+ return prompt('agent/not-done', { todos: open.map((t) => `- ${t.content}`).join('\n') })
1260
1328
  }
1261
1329
  // changed files and hasn't run anything since: not proven to work
1262
1330
  const changed = [...(s.changed ?? [])]
1263
1331
  if (changed.length && s.lastCheckAt < s.lastChangeAt && !changed.every((f) => DOC_FILE.test(f)) && s.ui.permission !== 'plan') {
1264
1332
  log('task', `finished with changes not checked since (${changed.join(', ')}); asking for a check`)
1265
- return prompt('agent/unchecked', { files: changed.join(', ') })
1333
+ return prompt('agent/not-done', { unchecked: changed.join(', ') })
1266
1334
  }
1267
1335
  // says it made files that aren't there
1268
1336
  const missing = missingFiles(s.root, reply)
1269
1337
  if (missing.length) {
1270
1338
  log('task', `the answer names files that don't exist: ${missing.join(', ')}`)
1271
- return prompt('agent/missing-files', { files: missing.join(', ') })
1339
+ return prompt('agent/not-done', { missing: missing.join(', ') })
1272
1340
  }
1273
1341
  if (s.acted && reply && PROMISED_MORE.test(reply)) {
1274
1342
  log('task', 'reply names a next step but no tool call followed; nudging to finish')
1275
- return prompt('agent/stopped-early')
1343
+ return prompt('agent/not-done', { early: true })
1276
1344
  }
1345
+ if (s.isSub) return null // a helper: the Stop hooks are the main conversation's
1277
1346
  const hook = await runHooks(s, 'Stop', { stop_hook_active: again }, signal)
1278
- return hook.block ? prompt('agent/hook-stop', { reason: hook.block }) : null
1347
+ return hook.block ? prompt('agent/hook', { reason: hook.block, stop: true }) : null
1279
1348
  }
1280
1349
 
1281
1350
  // Files the final answer says were made, that aren't in the project: a path in backticks, or one
@@ -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
@@ -1349,7 +1418,9 @@ export async function review(s, task, answer, signal) {
1349
1418
  } catch {}
1350
1419
  if (now === before) continue
1351
1420
  const text = before === null ? `${rel} (new file):\n${now ?? ''}` : now === null ? `${rel}: deleted` : renderDiff(diffLines(before, now), rel, false, 3, 400)
1352
- const piece = clip(text, Math.min(5000, room))
1421
+ // cut to save room, said so in words: a bare "…" reads as a file left unfinished
1422
+ const most = Math.min(5000, room)
1423
+ const piece = text.length > most ? `${text.slice(0, most)}\n[${text.length - most} more characters of this change not shown here, to save room. The file itself is whole.]` : text
1353
1424
  room -= piece.length
1354
1425
  diffs.push(piece)
1355
1426
  if (room <= 500) {
@@ -1362,9 +1433,8 @@ export async function review(s, task, answer, signal) {
1362
1433
  const ran = (s.ran ?? []).slice(-15).map((r) => `- ${clip(r.command.replace(/\s+/g, ' '), 160)} → ${r.result}`).join('\n')
1363
1434
  const ask = prompt('agent/review', { request: requestsOf(s.chat, 1200), emphasis: (s.chat?.choices ?? []).join('; '), plan: plan || '(none)', answer: clip(String(answer ?? ''), 3000), changes: diffs.join('\n\n'), ran: ran || '(nothing)' })
1364
1435
  const self = { provider: s.client.provider, model: s.client.model, self: true }
1365
- const fails = (t) => s.failures?.[`${t.provider} ${t.model}`] ?? 0
1366
- const team = (s.team?.() ?? []).filter((t) => t.tools !== false && !(t.provider === self.provider && t.model === self.model)).sort((a, b) => fails(a) - fails(b))
1367
- for (const t of [...team.slice(0, 2), ...(s.orchestrating ? [] : [self])]) { // an orchestrator doesn't check the work
1436
+ const team = (s.team?.() ?? []).filter((t) => t.tools !== false && !(t.provider === self.provider && t.model === self.model)) // your next two, in your order
1437
+ for (const t of [...team.slice(0, 2), self]) {
1368
1438
  s.ui.spinner(`${t.model} is reviewing the work`)
1369
1439
  try {
1370
1440
  const { client } = t.self ? { client: s.client } : await s.engineFor(t)
@@ -1398,23 +1468,36 @@ export async function review(s, task, answer, signal) {
1398
1468
  return null
1399
1469
  }
1400
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
+
1401
1477
  // A helper agent's view of the screen: its steps are labelled, and its replies (which go to the
1402
1478
  // main agent) aren't shown as answers. Everything else is the main UI's.
1403
1479
  // Its thinking is shown whole when its reply is in (helpers working at once don't mix), named.
1404
1480
  // Questions to the user (confirm, pick, ask) wait their turn: helpers working at once ask one by one.
1405
1481
  const asking = new WeakMap() // ui → the question being asked
1482
+ const streaming = new WeakMap() // ui → helper replies coming in now (only one: its thinking is shown as it comes)
1406
1483
  function helperUI(ui, label) {
1407
- // What the helper says is shown in full under its name. Held until its reply ends, then printed at
1408
- // once: helpers run side by side, and streamed text from two would interleave.
1484
+ // What the helper says is shown in full under its name. Its thinking is shown as it comes, like the
1485
+ // conversation's; with other helpers replying at the
1486
+ // same time, held until its reply ends, then printed at once (two streams would interleave).
1409
1487
  const response = () => {
1410
1488
  const t0 = Date.now()
1411
1489
  let thought = ''
1412
1490
  let said = ''
1491
+ const alone = !streaming.get(ui)
1492
+ streaming.set(ui, (streaming.get(ui) ?? 0) + 1)
1493
+ const live = alone ? ui.response(label, { helper: true }) : null // "✻ <model> is thinking…", then its thinking as it comes
1413
1494
  return {
1414
- think: (t) => (thought += t ?? ''),
1495
+ think: (t) => (live ? live.think(t) : (thought += t ?? '')),
1415
1496
  text: (t) => (said += t ?? ''),
1416
1497
  end() {
1417
- if (thought.trim()) ui.print(c.faint(c.italic(` ✻ ${label} thought for ${duration(Date.now() - t0)}`)) + (ui.showThinking ? `\n${c.think(c.italic(thought.trim().replace(/^/gm, ' ')))}` : ''))
1498
+ streaming.set(ui, streaming.get(ui) - 1)
1499
+ if (live) live.end()
1500
+ else if (thought.trim()) ui.print(c.faint(c.italic(` ✻ ${label} thought for ${duration(Date.now() - t0)}`)) + (ui.showThinking ? `\n${c.think(c.italic(thought.trim().replace(/^/gm, ' ')))}` : ''))
1418
1501
  if (!said.trim()) return
1419
1502
  ui.print(` ${c.bright(c.bold('●'))} ${c.bold(label)}`)
1420
1503
  let block = new Block((x) => ui.write(x), { marker: ' ', style: c.text })
@@ -1429,11 +1512,26 @@ function helperUI(ui, label) {
1429
1512
  asking.set(ui, next.catch(() => {}))
1430
1513
  return next
1431
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
+ }
1432
1521
  const own = {
1433
- step: (name, detail) => ui.step(` ${label} › ${name}`, detail),
1434
- 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)}`),
1435
1530
  response,
1436
- 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
+ },
1437
1535
  confirm: inTurn('confirm'),
1438
1536
  pick: inTurn('pick'),
1439
1537
  ask: inTurn('ask'),
@@ -1453,7 +1551,7 @@ export function fitResult(s, name, out, file) {
1453
1551
  if (out.length <= max) return out
1454
1552
  file ??= saveOutput(s.chat?.id, name, out)
1455
1553
  log('tool', `${name}: ${out.length} characters, ${max} shown${file ? `; all of it in ${file}` : ''}`)
1456
- return `${out.slice(0, max)}\n…\n${prompt('agent/output-cut', { shown: max, total: out.length, file })}`
1554
+ return `${out.slice(0, max)}\n…\n${prompt('agent/output-cut', { shown: max, total: out.length, file, call: '' })}`
1457
1555
  }
1458
1556
 
1459
1557
  // Results longer than this are saved to a file when they come (so they can leave the conversation later).
@@ -1480,7 +1578,7 @@ function callOf(messages, id) {
1480
1578
  // provider's prompt cache (the conversation's unchanged start) is broken rarely, not every step.
1481
1579
  // An older conversation's results (no file yet) are saved now, before they're cut.
1482
1580
  export function trimOldResults(s, keep = 4, most = 8) {
1483
- const long = s.messages.filter((m) => m.role === 'tool' && typeof m.content === 'string' && m.content.length > SAVE_AT && !shortened.has(m) && !/^\[older output/.test(m.content) && !s.staleCopies?.has(m))
1581
+ const long = s.messages.filter((m) => m.role === 'tool' && typeof m.content === 'string' && m.content.length > SAVE_AT && !shortened.has(m) && !/^\[older output/i.test(m.content) && !s.staleCopies?.has(m))
1484
1582
  if (long.length <= most) return
1485
1583
  dropStale(s) // the conversation changes here anyway: the older copies of files read again go too
1486
1584
  for (const m of long.slice(0, -keep)) {
@@ -1488,7 +1586,7 @@ export function trimOldResults(s, keep = 4, most = 8) {
1488
1586
  const read = /^read_file /.test(call) ? call.slice('read_file '.length) : '' // a project file: read it again
1489
1587
  const file = read || s.chat.outputs?.[m.tool_call_id] || saveOutput(s.chat?.id, 'older', m.content)
1490
1588
  if (file && !read) (s.chat.outputs ??= {})[m.tool_call_id] = file
1491
- m.content = `${prompt('agent/output-old', { call, total: m.content.length, file })}\n${m.content.slice(0, 300)}\n…`
1589
+ m.content = `${prompt('agent/output-cut', { call, shown: Math.min(300, m.content.length), total: m.content.length, file })}\n${m.content.slice(0, 300)}\n…`
1492
1590
  shortened.add(m)
1493
1591
  }
1494
1592
  log('tool', `older tool output cut: ${long.length - keep} results`)
@@ -1533,7 +1631,7 @@ function attachNamed(s, task) {
1533
1631
  replaceCopy(s, f, msg)
1534
1632
  results.push(msg)
1535
1633
  s.ui.step('read_file', f)
1536
- s.ui.result(`${body.split('\n').length} lines`)
1634
+ s.ui.result(lineCount(body))
1537
1635
  }
1538
1636
  if (calls.length) s.messages.push({ role: 'assistant', content: '', tool_calls: calls }, ...results)
1539
1637
  }
@@ -1556,7 +1654,7 @@ export function contextReport(s) {
1556
1654
  const ago = msgs.length - 1 - i
1557
1655
  if (i === 0 && m.role === 'system') return void (parts.system += n)
1558
1656
  if (m.role === 'tool') {
1559
- const old = typeof m.content === 'string' && /^\[older output/.test(m.content)
1657
+ const old = typeof m.content === 'string' && /^\[older output/i.test(m.content)
1560
1658
  old ? (parts.pointers += n, cut++) : (parts.results += n, whole++)
1561
1659
  pieces.push({ tokens: n, what: `${callOf(msgs, m.tool_call_id)} (result${old ? ', a pointer' : ''})`, ago })
1562
1660
  } else if (m.role === 'assistant') {