heartcode 0.1.44 → 0.1.54

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
8
  import { est, estMessages, Client, writtenBy, 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, 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'
@@ -117,7 +117,7 @@ export class Session {
117
117
  // A model shown its own work tends to carry on with it (calling tools, or writing tool calls
118
118
  // as text) instead of summarizing: so it's told what it is, and a reply that isn't a summary
119
119
  // 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
120
+ const request = (extra) => prompt('compact/summarize', { conversation: cut(), focus, branch: false, files: '' }) + extra
121
121
  const send = (extra) =>
122
122
  client.chat({ messages: [{ role: 'system', content: prompt('compact/summarizer') }, { role: 'user', content: request(extra) }] }, { signal })
123
123
  const ask = (extra = '') => send(extra)
@@ -182,7 +182,7 @@ export class Session {
182
182
  if (!this.isSub) for (const e of takeConfigErrors()) ui.warn(e) // a hooks.json or mcp.json that doesn't parse
183
183
  const hook = await runHooks(this, 'UserPromptSubmit', { prompt: task }, signal)
184
184
  if (hook.block) {
185
- const answer = prompt('agent/hook-blocked-prompt', { reason: hook.block })
185
+ const answer = prompt('agent/hook', { reason: hook.block, blocked: true })
186
186
  ui.warn(answer)
187
187
  return answer
188
188
  }
@@ -202,22 +202,12 @@ export class Session {
202
202
  let { text, images } = extractImages(task, this.root)
203
203
  images = [...images, ...extra]
204
204
  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
205
+ const seers = (this.team?.() ?? []).filter((t) => t.images) // your models that can, in your order: they describe them
207
206
  if (seers.length) text += await this.describeImages(images, seers, text, signal)
208
207
  else this.ui.warn(`${this.client.model} can't read images (per its probe); ignoring ${images.length} image(s)`)
209
208
  images = []
210
209
  }
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
- }
210
+ 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
211
  log('task', `${text} (${this.strat.actions} mode, ${images.length} image(s))`)
222
212
  const answer = this.strat.actions === 'tools' ? await runNative(this, text, images, signal) : await runGuided(this, text, images, signal)
223
213
  log('answer', answer) // the conversation's log
@@ -245,16 +235,15 @@ export class Session {
245
235
  }
246
236
  const name = (t) => `${t.provider} ${t.model}`
247
237
  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
238
+ const all = [self, ...(this.team?.() ?? [])] // this model, then your others in your list's order
249
239
  const want = String(args.model ?? '').trim()
250
240
  // 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}`)))
241
+ 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
242
  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
243
+ // the one asked for first, then the others in your list's order: only those that can do the job
244
+ // (images need a model that sees them)
255
245
  const able = (t) => !images.length || t.images
256
- const fails = (t) => this.failures?.[name(t)] ?? 0
257
- const order = [first, ...all.filter((t) => t !== first).sort((a, b) => b.tools - a.tools || fails(a) - fails(b))].filter(able)
246
+ const order = [first, ...all.filter((t) => t !== first)].filter(able)
258
247
  if (!order.length) return 'error: none of your models can see images'
259
248
  const failed = []
260
249
  for (const [i, t] of order.entries()) {
@@ -266,10 +255,7 @@ export class Session {
266
255
  failed.push(`${t.model}: ${clip(e.message, 150)}`)
267
256
  }
268
257
  if (answer) return t === first ? answer : `(Answered by ${name(t)}, not ${name(first)}${failed.length ? `: ${failed.join('; ')}` : ''})\n\n${answer}`
269
- if (failed.length < i + 1) {
270
- failed.push(`${t.model}: no reply`)
271
- if (this.failures) this.failures[name(t)] = fails(t) + 1 // (a failed request is counted where it fails: engine's onFail)
272
- }
258
+ if (failed.length < i + 1) failed.push(`${t.model}: no reply`)
273
259
  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}`)
274
260
  }
275
261
  return `error: none of your models that can do it managed: ${failed.join('; ')}`
@@ -283,7 +269,7 @@ export class Session {
283
269
  if (this.engineFor) {
284
270
  ;({ client, profile, strat } = await this.engineFor(t))
285
271
  const was = client.retryIf
286
- client.retryIf = (e, attempt) => attempt < 3 && !e.notStarted && (!was || was(e, attempt)) // not answering in time: the next model, not another wait
272
+ 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
287
273
  }
288
274
  const label = clip(`${client.model}: ${String(description ?? '').trim() || task.split('\n')[0]}`, 60)
289
275
  const helper = new Session({ client, profile, strat, root: this.root, ui: helperUI(this.ui, label), chat: newChat(this.root) })
@@ -386,7 +372,7 @@ export class Session {
386
372
  const { client, strat } = this
387
373
  const room = Math.floor((strat.context * 0.6 * 3.5) / (strat.ratio ?? 1))
388
374
  const text = conversation.length > room ? `[… the earliest part is cut]\n${conversation.slice(-room)}` : conversation
389
- const request = prompt('compact/branch-summarize', { conversation: text, files: files.join(', ') })
375
+ const request = prompt('compact/summarize', { conversation: text, files: files.join(', '), branch: true, focus: '' })
390
376
  const messages = [{ role: 'system', content: prompt('compact/summarizer') }, { role: 'user', content: request }]
391
377
  const summary = notSummary((await client.chat({ messages }, { signal })).content)
392
378
  if (!summary) throw new Error('the model did not write a summary')
@@ -549,42 +535,35 @@ const rootList = (root) => {
549
535
  return v.error ? `(can't read it: ${v.error})` : v.entries.length ? v.entries.join(' · ') + (v.more ? ` · … ${v.more} more` : '') : '(empty)'
550
536
  }
551
537
 
538
+ // An always-on skill in the system prompt as the skill tool would give it: its text, the files it
539
+ // says come with it (load), and the list of its other files (read with the skill tool's "file")
540
+ const alwaysSkill = (k) => {
541
+ const files = skillFiles(k)
542
+ 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') })}` : '')
543
+ }
544
+
552
545
  const SYSTEM = (s) => {
553
- if (s.orchestrating) return prompt('agent/orchestrator', { root: s.root, env: envLine(), today: new Date().toISOString().slice(0, 10), ...teamOf(s) })
554
546
  const instructions = userInstructions(s.root)
555
547
  return [
556
- 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) }),
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
557
549
  instructions && prompt('agent/instructions', { instructions }),
558
- ...[...(s.skills?.values() ?? [])].filter((k) => k.use === 'always').map((k) => k.body), // skills that say how to work (use: always)
559
- s.memory && prompt('agent/memory', { tags: s.memory.tagSummary() || '(none yet)' }),
560
- s.strat.vision && prompt('agent/you-see'), // models that can see often say they can't
561
- s.director && !s.appendSystem && s.director.app.cfg.director !== false && prompt('agent/director'),
550
+ ...[...(s.skills?.values() ?? [])].filter((k) => k.use === 'always').map(alwaysSkill), // skills that say how to work (use: always), with the files they bring
562
551
  !s.isSub && teamPrompt(s),
563
552
  s.isSub && prompt('agent/subagent'),
564
- s.appendSystem && prompt('agent/caller'),
565
- s.appendSystem,
553
+ s.appendSystem && prompt('agent/instructions', { instructions: s.appendSystem, caller: true }),
566
554
  ]
567
555
  .filter(Boolean)
568
556
  .join('\n\n')
569
557
  }
570
558
 
571
559
  // Your other models and what each can do, for the agent tool's model (only when there are any): a
572
- // short line each — with an orchestrator, with its places in the public rankings (rankings.js).
573
- const RANKED_AS = { overall: 'text:overall', code: 'text:coding', web: 'webdev:webdev', vision: 'vision:overall' }
560
+ // short line each, in your list's order.
574
561
  const teamPrompt = (s) => {
575
562
  const team = s.team?.() ?? []
576
- return team.length ? prompt('agent/team', teamOf(s, team)) : ''
577
- }
578
- const teamOf = (s, team = s.team?.() ?? []) => {
579
- const data = s.fitMode?.() ? loadRankings() : null
580
- const ranks = (t) => (data ? Object.entries(RANKED_AS).map(([k, list]) => ((r) => r && `${k} #${r.rank}`)(rankIn(t.model, list, data))).filter(Boolean).join(' ') : '')
581
- const line = (t) => {
582
- const failed = s.failures?.[`${t.provider} ${t.model}`]
583
- const facts = [t.tools === false && 'no tool calls', t.images && 'images', t.thinking && 'thinking', ranks(t) && `ranked ${ranks(t)}`, failed && `failed ${failed}× this session`].filter(Boolean)
584
- return `- ${t.provider} ${t.model}${facts.length ? `: ${facts.join(', ')}` : ''}`
585
- }
586
- const you = [s.strat.vision ? 'images' : 'no images', s.strat.thinking && 'thinking', ranks(s.client) && `ranked ${ranks(s.client)}`].filter(Boolean).join(', ')
587
- return { models: team.map(line).join('\n'), you, ranked: Boolean(data) }
563
+ if (!team.length) return ''
564
+ const can = (t) => [t.tools === false && 'no tool calls', t.images && 'images', t.thinking && 'thinking'].filter(Boolean)
565
+ const line = (t) => `- ${t.provider} ${t.model}${can(t).length ? `: ${can(t).join(', ')}` : ''}`
566
+ return prompt('agent/team', { models: team.map(line).join('\n'), you: [s.strat.vision ? 'images' : 'no images', s.strat.thinking && 'thinking'].filter(Boolean).join(', ') })
588
567
  }
589
568
 
590
569
  const sizeOf = (m) =>
@@ -824,11 +803,8 @@ async function runNative(s, task, images, signal) {
824
803
  // pages already read for this project that match: titles only (the model opens one when needed)
825
804
  const pages = s.isSub || !s.memory ? [] : findResearch(s.root, task, 6).filter((r) => r.kind !== 'search' && !sent.has(`research:${r.name}:${r.fetched}`))
826
805
  s.chat.sentNotes = [...sent, ...notes.map(key), ...pages.map((r) => `research:${r.name}:${r.fetched}`)]
827
- const known = [
828
- notes.length && prompt('agent/memory-relevant', { notes: notes.map((n) => `[[${n.name}]] — ${n.description}`).join('\n') }),
829
- pages.length && prompt('agent/research-known', { pages: pages.map((r) => `- ${r.title} — ${r.url} (read ${r.fetched}) → ${r.file}`).join('\n') }),
830
- ].filter(Boolean)
831
- const text = known.length ? `${task}\n\n${known.join('\n\n')}` : task
806
+ 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
+ const text = known ? `${task}\n\n${known}` : task
832
808
  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
833
809
  const planning = ui.permission === 'plan'
834
810
  const said = planning && !s.isSub ? `${text}\n\n${prompt('agent/plan-mode')}` : text
@@ -855,7 +831,9 @@ async function runNative(s, task, images, signal) {
855
831
  let nudged = 0 // reminders sent this message about open todo items, a premature stop, or a Stop hook
856
832
  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)
857
833
  s.planAsked = false // asked for a plan before its first change, this message
834
+ s.askedUser = s.askNudged = false // asked with ask_user / told to, this message (a reply of questions as text: askedInText)
858
835
  s.splitAsked = false // asked whether a plan's parts could run side by side, this message
836
+ s.lookedUp = s.researchAsked = false // searched or read the web this message / asked whether the plan needs it
859
837
  // what changed and when it was last checked, this message: a change not run/tested since isn't done
860
838
  Object.assign(s, { changed: new Set(), seq: 0, lastChangeAt: -1, lastCheckAt: -1, reviewedAt: -1, checksSince: 0, spots: new Map() })
861
839
 
@@ -864,9 +842,12 @@ async function runNative(s, task, images, signal) {
864
842
  let stuck = null // why it's going round in circles (then the next model takes over; nothing stops but Esc)
865
843
  // Going round in circles: the next of your models carries on (a different model often gets out of
866
844
  // it); with no other model, a warning, and it goes on being told what it repeats — only Esc stops it.
845
+ // A helper has only the model it was given and maybe nobody to press Esc: it ends, failed, and
846
+ // the job goes to your next model.
867
847
  const handOver = (why) => {
868
848
  const was = client.model
869
849
  if (client.moveOn?.(`${was} ${why}`)) ui.warn(`${was} ${why}; handing over to ${client.model}`)
850
+ else if (s.isSub) throw Object.assign(new Error(`${was} ${why}`), { stuck: true })
870
851
  else ui.warn(`${was} ${why} — it carries on, told so; Esc stops it`)
871
852
  }
872
853
  let garbled = 0 // replies with a tool call written as text (template markup), this message
@@ -910,7 +891,11 @@ async function runNative(s, task, images, signal) {
910
891
  try {
911
892
  res = await client.chat({ messages: s.messages, tools, stream }, { signal, onToken: out.text, onReasoning: out.think, onToolDelta, fit: !refitted })
912
893
  } catch (e) {
913
- if (!e.tooBig) throw e
894
+ if (!e.tooBig) {
895
+ ui.stopSpin()
896
+ out.end() // what came of it is closed (a helper's turn to show its thinking ends)
897
+ throw e
898
+ }
914
899
  // The model list moved on (the one before failed) to a model whose window can't hold the
915
900
  // conversation: compacted for it (by it, to its size), then the same step again. Once: still
916
901
  // too big after that (its window can't even hold the start), it's sent anyway.
@@ -932,6 +917,7 @@ async function runNative(s, task, images, signal) {
932
917
  out.text(res.content)
933
918
  }
934
919
  out.end()
920
+ client.announceSwitch?.() // "↻ … answered": under the reply, on a line of its own
935
921
  // the reply went round and round (client.js cut it): told so, and asked again
936
922
  if (res.looped) {
937
923
  if (++looping > 3) {
@@ -939,7 +925,7 @@ async function runNative(s, task, images, signal) {
939
925
  looping = 0
940
926
  } else ui.warn(`${client.model} went into a loop; cut, and asked again`)
941
927
  if (res.content.trim()) s.messages.push({ role: 'assistant', content: res.content })
942
- s.messages.push({ role: 'user', content: prompt('agent/looped', { sample: res.looped }) })
928
+ s.messages.push({ role: 'user', content: prompt('agent/bad-reply', { sample: res.looped }) })
943
929
  continue
944
930
  }
945
931
  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
@@ -960,7 +946,7 @@ async function runNative(s, task, images, signal) {
960
946
  if (markup && garbled++ < 2) {
961
947
  log('task', `${client.model}: a tool call written as text; asking again`, res.content)
962
948
  s.messages.pop()
963
- s.messages.push({ role: 'user', content: prompt('agent/garbled-call') })
949
+ s.messages.push({ role: 'user', content: prompt('agent/bad-reply', { sample: '' }) })
964
950
  continue
965
951
  }
966
952
  if (markup) {
@@ -1052,7 +1038,7 @@ async function runNative(s, task, images, signal) {
1052
1038
  // refused one is easily taken for refused too), once a message; not a helper's (its job is its plan)
1053
1039
  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')
1054
1040
  if (planFirst) Object.assign(s, { planAsked: true, planHeldIn: res })
1055
- const refused = planFirst ? prompt('agent/plan-first') : pre ? (pre.refused ?? null) : !together.has(call.id) && args && allowed(s, name) ? guard.before(name, args) : null
1041
+ 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
1056
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')
1057
1043
  if (!refused && args) out += guard.after(name, args, out)
1058
1044
  if (guard.stuck) stuck ??= guard.stuck
@@ -1083,7 +1069,7 @@ async function runNative(s, task, images, signal) {
1083
1069
  const sig = `${name} ${call.function.arguments}`
1084
1070
  inRow = sig === lastCall ? inRow + 1 : 1
1085
1071
  lastCall = sig
1086
- if (inRow >= 3) out += `\n\n${prompt('agent/repeating', { n: inRow })}`
1072
+ if (inRow >= 3) out += `\n\n${prompt('agent/repeating', { n: inRow, failed: false })}`
1087
1073
  if (inRow >= 5) stuck = `made the same ${name} call five times in a row`
1088
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`)
1089
1075
  else if (name === 'agent' && !failed(out)) ui.result(`${s.ui.permission === 'plan' ? 'planned' : 'done'}: ${clip(out.split('\n').find((l) => l.trim()) ?? '', 100)}`)
@@ -1115,7 +1101,7 @@ async function runNative(s, task, images, signal) {
1115
1101
  }
1116
1102
  // screenshots from MCP tools: tool results are text only, so images follow as a message
1117
1103
  if (s.pendingImages?.length) {
1118
- 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 } }))] })
1104
+ 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 } }))] })
1119
1105
  s.pendingImages = []
1120
1106
  }
1121
1107
  }
@@ -1132,6 +1118,7 @@ const EDITS = new Set(['edit_file', 'write_file', 'append_file', 'apply_patch'])
1132
1118
  const CHECKS = new Set(['run_command', 'mcp', 'agent', 'lsp'])
1133
1119
  // Files only read by people (a change there needs no run to check it).
1134
1120
  const DOC_FILE = /\.(md|mdx|txt|rst|adoc)$/i
1121
+
1135
1122
  // Tools that only look (nothing changes): several in one reply run at the same time.
1136
1123
  const LOOKUPS = new Set(['web_search', 'web_fetch', 'read_file', 'search', 'list_files', 'find_command', 'lsp', 'changes'])
1137
1124
  export function newGuard() {
@@ -1159,14 +1146,14 @@ export function newGuard() {
1159
1146
  if (!was || (name === 'run_command' && Date.now() - was.at > 20_000)) return null
1160
1147
  repeats++
1161
1148
  if (repeats >= 10) g.stuck = 'kept making calls it had already made (10 repeats)' // going round, not finding anything new
1162
- return prompt('agent/already-done', { result: was.out }) + (repeats >= 3 ? `\n\n${prompt('agent/circling')}` : '')
1149
+ return prompt('agent/already-done', { result: was.out, circling: repeats >= 3 })
1163
1150
  }
1164
1151
  g.after = (name, a, out) => {
1165
1152
  let note = ''
1166
1153
  if (name === 'run_command') {
1167
1154
  const code = Number(/^exit code (-?\d+)/.exec(out)?.[1] ?? 0)
1168
1155
  failing = code ? failing + 1 : 0
1169
- if (failing >= 4) note += `\n\n${prompt('agent/failing-in-row', { n: failing })}`
1156
+ if (failing >= 4) note += `\n\n${prompt('agent/repeating', { n: failing, failed: true })}`
1170
1157
  if (failing >= 8) g.stuck = 'had eight commands in a row fail'
1171
1158
  if (!readOnlyCommand(String(a.command ?? ''))) epoch++ // it may have changed things: what came before can be done again
1172
1159
  }
@@ -1246,34 +1233,49 @@ async function learnFromFixes(s, fixed, signal) {
1246
1233
  // The model said it would do something but stopped without doing it ("let me rewrite…", "I'll fix…"):
1247
1234
  // a next action named, then no tool call. Not matched by explanations ("let me explain", "you can run").
1248
1235
  const PROMISED_MORE =
1249
- /\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
1236
+ /\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
1250
1237
 
1251
1238
  // Is the task really done, or did the model stop early? Open todo items, or (after it did real work)
1252
1239
  // a reply that only promises more, get one nudge to keep going. Then any Stop hook. null = truly done.
1240
+ // A reply that is mostly questions for the user, written as text: only ask_user opens the dialog to
1241
+ // answer them in (weaker models type them out and stop). At least two questions, and most of what it says.
1242
+ export function askedInText(reply) {
1243
+ const sentences = String(reply).replace(/```[\s\S]*?```/g, '').split(/(?<=[.?!])\s+|\n+/).map((x) => x.trim()).filter((x) => /\w/.test(x))
1244
+ const questions = sentences.filter((x) => /\?["')\]]*$/.test(x)).length
1245
+ return questions >= 2 && questions / sentences.length >= 0.4
1246
+ }
1247
+
1253
1248
  export async function notDone(s, signal, again, reply = '') {
1249
+ // questions typed out instead of asked: once a message, asked again with the tool (someone's there to answer)
1250
+ if (!s.isSub && !s.ui.noUser && !s.askedUser && !s.askNudged && askedInText(reply)) {
1251
+ s.askNudged = true
1252
+ log('task', 'asked its questions as text; told to use ask_user')
1253
+ return prompt('agent/not-done', { asked: true })
1254
+ }
1254
1255
  const open = s.todoTouched && s.ui.permission !== 'plan' ? (s.chat.todos ?? []).filter((t) => t.status !== 'completed') : [] // plan mode: they wait for the approval
1255
1256
  if (open.length) {
1256
1257
  log('task', `stopped with ${open.length} open todo item(s); reminding`)
1257
- return prompt('agent/todo-unfinished', { items: open.map((t) => `- ${t.content}`).join('\n') })
1258
+ return prompt('agent/not-done', { todos: open.map((t) => `- ${t.content}`).join('\n') })
1258
1259
  }
1259
1260
  // changed files and hasn't run anything since: not proven to work
1260
1261
  const changed = [...(s.changed ?? [])]
1261
1262
  if (changed.length && s.lastCheckAt < s.lastChangeAt && !changed.every((f) => DOC_FILE.test(f)) && s.ui.permission !== 'plan') {
1262
1263
  log('task', `finished with changes not checked since (${changed.join(', ')}); asking for a check`)
1263
- return prompt('agent/unchecked', { files: changed.join(', ') })
1264
+ return prompt('agent/not-done', { unchecked: changed.join(', ') })
1264
1265
  }
1265
1266
  // says it made files that aren't there
1266
1267
  const missing = missingFiles(s.root, reply)
1267
1268
  if (missing.length) {
1268
1269
  log('task', `the answer names files that don't exist: ${missing.join(', ')}`)
1269
- return prompt('agent/missing-files', { files: missing.join(', ') })
1270
+ return prompt('agent/not-done', { missing: missing.join(', ') })
1270
1271
  }
1271
1272
  if (s.acted && reply && PROMISED_MORE.test(reply)) {
1272
1273
  log('task', 'reply names a next step but no tool call followed; nudging to finish')
1273
- return prompt('agent/stopped-early')
1274
+ return prompt('agent/not-done', { early: true })
1274
1275
  }
1276
+ if (s.isSub) return null // a helper: the Stop hooks are the main conversation's
1275
1277
  const hook = await runHooks(s, 'Stop', { stop_hook_active: again }, signal)
1276
- return hook.block ? prompt('agent/hook-stop', { reason: hook.block }) : null
1278
+ return hook.block ? prompt('agent/hook', { reason: hook.block, stop: true }) : null
1277
1279
  }
1278
1280
 
1279
1281
  // Files the final answer says were made, that aren't in the project: a path in backticks, or one
@@ -1347,7 +1349,9 @@ export async function review(s, task, answer, signal) {
1347
1349
  } catch {}
1348
1350
  if (now === before) continue
1349
1351
  const text = before === null ? `${rel} (new file):\n${now ?? ''}` : now === null ? `${rel}: deleted` : renderDiff(diffLines(before, now), rel, false, 3, 400)
1350
- const piece = clip(text, Math.min(5000, room))
1352
+ // cut to save room, said so in words: a bare "…" reads as a file left unfinished
1353
+ const most = Math.min(5000, room)
1354
+ 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
1351
1355
  room -= piece.length
1352
1356
  diffs.push(piece)
1353
1357
  if (room <= 500) {
@@ -1360,9 +1364,8 @@ export async function review(s, task, answer, signal) {
1360
1364
  const ran = (s.ran ?? []).slice(-15).map((r) => `- ${clip(r.command.replace(/\s+/g, ' '), 160)} → ${r.result}`).join('\n')
1361
1365
  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)' })
1362
1366
  const self = { provider: s.client.provider, model: s.client.model, self: true }
1363
- const fails = (t) => s.failures?.[`${t.provider} ${t.model}`] ?? 0
1364
- const team = (s.team?.() ?? []).filter((t) => t.tools !== false && !(t.provider === self.provider && t.model === self.model)).sort((a, b) => fails(a) - fails(b))
1365
- for (const t of [...team.slice(0, 2), ...(s.orchestrating ? [] : [self])]) { // an orchestrator doesn't check the work
1367
+ const team = (s.team?.() ?? []).filter((t) => t.tools !== false && !(t.provider === self.provider && t.model === self.model)) // your next two, in your order
1368
+ for (const t of [...team.slice(0, 2), self]) {
1366
1369
  s.ui.spinner(`${t.model} is reviewing the work`)
1367
1370
  try {
1368
1371
  const { client } = t.self ? { client: s.client } : await s.engineFor(t)
@@ -1401,18 +1404,25 @@ export async function review(s, task, answer, signal) {
1401
1404
  // Its thinking is shown whole when its reply is in (helpers working at once don't mix), named.
1402
1405
  // Questions to the user (confirm, pick, ask) wait their turn: helpers working at once ask one by one.
1403
1406
  const asking = new WeakMap() // ui → the question being asked
1407
+ const streaming = new WeakMap() // ui → helper replies coming in now (only one: its thinking is shown as it comes)
1404
1408
  function helperUI(ui, label) {
1405
- // What the helper says is shown in full under its name. Held until its reply ends, then printed at
1406
- // once: helpers run side by side, and streamed text from two would interleave.
1409
+ // What the helper says is shown in full under its name. Its thinking is shown as it comes, like the
1410
+ // conversation's; with other helpers replying at the
1411
+ // same time, held until its reply ends, then printed at once (two streams would interleave).
1407
1412
  const response = () => {
1408
1413
  const t0 = Date.now()
1409
1414
  let thought = ''
1410
1415
  let said = ''
1416
+ const alone = !streaming.get(ui)
1417
+ streaming.set(ui, (streaming.get(ui) ?? 0) + 1)
1418
+ const live = alone ? ui.response(label, { helper: true }) : null // "✻ <model> is thinking…", then its thinking as it comes
1411
1419
  return {
1412
- think: (t) => (thought += t ?? ''),
1420
+ think: (t) => (live ? live.think(t) : (thought += t ?? '')),
1413
1421
  text: (t) => (said += t ?? ''),
1414
1422
  end() {
1415
- 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, ' ')))}` : ''))
1423
+ streaming.set(ui, streaming.get(ui) - 1)
1424
+ if (live) live.end()
1425
+ 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, ' ')))}` : ''))
1416
1426
  if (!said.trim()) return
1417
1427
  ui.print(` ${c.bright(c.bold('●'))} ${c.bold(label)}`)
1418
1428
  let block = new Block((x) => ui.write(x), { marker: ' ', style: c.text })
@@ -1451,7 +1461,7 @@ export function fitResult(s, name, out, file) {
1451
1461
  if (out.length <= max) return out
1452
1462
  file ??= saveOutput(s.chat?.id, name, out)
1453
1463
  log('tool', `${name}: ${out.length} characters, ${max} shown${file ? `; all of it in ${file}` : ''}`)
1454
- return `${out.slice(0, max)}\n…\n${prompt('agent/output-cut', { shown: max, total: out.length, file })}`
1464
+ return `${out.slice(0, max)}\n…\n${prompt('agent/output-cut', { shown: max, total: out.length, file, call: '' })}`
1455
1465
  }
1456
1466
 
1457
1467
  // Results longer than this are saved to a file when they come (so they can leave the conversation later).
@@ -1478,7 +1488,7 @@ function callOf(messages, id) {
1478
1488
  // provider's prompt cache (the conversation's unchanged start) is broken rarely, not every step.
1479
1489
  // An older conversation's results (no file yet) are saved now, before they're cut.
1480
1490
  export function trimOldResults(s, keep = 4, most = 8) {
1481
- 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))
1491
+ 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))
1482
1492
  if (long.length <= most) return
1483
1493
  dropStale(s) // the conversation changes here anyway: the older copies of files read again go too
1484
1494
  for (const m of long.slice(0, -keep)) {
@@ -1486,7 +1496,7 @@ export function trimOldResults(s, keep = 4, most = 8) {
1486
1496
  const read = /^read_file /.test(call) ? call.slice('read_file '.length) : '' // a project file: read it again
1487
1497
  const file = read || s.chat.outputs?.[m.tool_call_id] || saveOutput(s.chat?.id, 'older', m.content)
1488
1498
  if (file && !read) (s.chat.outputs ??= {})[m.tool_call_id] = file
1489
- m.content = `${prompt('agent/output-old', { call, total: m.content.length, file })}\n${m.content.slice(0, 300)}\n…`
1499
+ 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…`
1490
1500
  shortened.add(m)
1491
1501
  }
1492
1502
  log('tool', `older tool output cut: ${long.length - keep} results`)
@@ -1554,7 +1564,7 @@ export function contextReport(s) {
1554
1564
  const ago = msgs.length - 1 - i
1555
1565
  if (i === 0 && m.role === 'system') return void (parts.system += n)
1556
1566
  if (m.role === 'tool') {
1557
- const old = typeof m.content === 'string' && /^\[older output/.test(m.content)
1567
+ const old = typeof m.content === 'string' && /^\[older output/i.test(m.content)
1558
1568
  old ? (parts.pointers += n, cut++) : (parts.results += n, whole++)
1559
1569
  pieces.push({ tokens: n, what: `${callOf(msgs, m.tool_call_id)} (result${old ? ', a pointer' : ''})`, ago })
1560
1570
  } else if (m.role === 'assistant') {