heartcode 0.1.45 → 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,17 +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 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))
246
+ const order = [first, ...all.filter((t) => t !== first)].filter(able)
259
247
  if (!order.length) return 'error: none of your models can see images'
260
248
  const failed = []
261
249
  for (const [i, t] of order.entries()) {
@@ -267,10 +255,7 @@ export class Session {
267
255
  failed.push(`${t.model}: ${clip(e.message, 150)}`)
268
256
  }
269
257
  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
- }
258
+ if (failed.length < i + 1) failed.push(`${t.model}: no reply`)
274
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}`)
275
260
  }
276
261
  return `error: none of your models that can do it managed: ${failed.join('; ')}`
@@ -284,7 +269,7 @@ export class Session {
284
269
  if (this.engineFor) {
285
270
  ;({ client, profile, strat } = await this.engineFor(t))
286
271
  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
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
288
273
  }
289
274
  const label = clip(`${client.model}: ${String(description ?? '').trim() || task.split('\n')[0]}`, 60)
290
275
  const helper = new Session({ client, profile, strat, root: this.root, ui: helperUI(this.ui, label), chat: newChat(this.root) })
@@ -387,7 +372,7 @@ export class Session {
387
372
  const { client, strat } = this
388
373
  const room = Math.floor((strat.context * 0.6 * 3.5) / (strat.ratio ?? 1))
389
374
  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(', ') })
375
+ const request = prompt('compact/summarize', { conversation: text, files: files.join(', '), branch: true, focus: '' })
391
376
  const messages = [{ role: 'system', content: prompt('compact/summarizer') }, { role: 'user', content: request }]
392
377
  const summary = notSummary((await client.chat({ messages }, { signal })).content)
393
378
  if (!summary) throw new Error('the model did not write a summary')
@@ -550,43 +535,35 @@ const rootList = (root) => {
550
535
  return v.error ? `(can't read it: ${v.error})` : v.entries.length ? v.entries.join(' · ') + (v.more ? ` · … ${v.more} more` : '') : '(empty)'
551
536
  }
552
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
+
553
545
  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
546
  const instructions = userInstructions(s.root)
556
547
  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) }),
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
558
549
  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'),
550
+ ...[...(s.skills?.values() ?? [])].filter((k) => k.use === 'always').map(alwaysSkill), // skills that say how to work (use: always), with the files they bring
563
551
  !s.isSub && teamPrompt(s),
564
552
  s.isSub && prompt('agent/subagent'),
565
- s.appendSystem && prompt('agent/caller'),
566
- s.appendSystem,
553
+ s.appendSystem && prompt('agent/instructions', { instructions: s.appendSystem, caller: true }),
567
554
  ]
568
555
  .filter(Boolean)
569
556
  .join('\n\n')
570
557
  }
571
558
 
572
559
  // 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' }
560
+ // short line each, in your list's order.
575
561
  const teamPrompt = (s) => {
576
562
  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) }
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(', ') })
590
567
  }
591
568
 
592
569
  const sizeOf = (m) =>
@@ -826,11 +803,8 @@ async function runNative(s, task, images, signal) {
826
803
  // pages already read for this project that match: titles only (the model opens one when needed)
827
804
  const pages = s.isSub || !s.memory ? [] : findResearch(s.root, task, 6).filter((r) => r.kind !== 'search' && !sent.has(`research:${r.name}:${r.fetched}`))
828
805
  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
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
834
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
835
809
  const planning = ui.permission === 'plan'
836
810
  const said = planning && !s.isSub ? `${text}\n\n${prompt('agent/plan-mode')}` : text
@@ -857,7 +831,9 @@ async function runNative(s, task, images, signal) {
857
831
  let nudged = 0 // reminders sent this message about open todo items, a premature stop, or a Stop hook
858
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)
859
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)
860
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
861
837
  // what changed and when it was last checked, this message: a change not run/tested since isn't done
862
838
  Object.assign(s, { changed: new Set(), seq: 0, lastChangeAt: -1, lastCheckAt: -1, reviewedAt: -1, checksSince: 0, spots: new Map() })
863
839
 
@@ -866,9 +842,12 @@ async function runNative(s, task, images, signal) {
866
842
  let stuck = null // why it's going round in circles (then the next model takes over; nothing stops but Esc)
867
843
  // Going round in circles: the next of your models carries on (a different model often gets out of
868
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.
869
847
  const handOver = (why) => {
870
848
  const was = client.model
871
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 })
872
851
  else ui.warn(`${was} ${why} — it carries on, told so; Esc stops it`)
873
852
  }
874
853
  let garbled = 0 // replies with a tool call written as text (template markup), this message
@@ -912,7 +891,11 @@ async function runNative(s, task, images, signal) {
912
891
  try {
913
892
  res = await client.chat({ messages: s.messages, tools, stream }, { signal, onToken: out.text, onReasoning: out.think, onToolDelta, fit: !refitted })
914
893
  } catch (e) {
915
- 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
+ }
916
899
  // The model list moved on (the one before failed) to a model whose window can't hold the
917
900
  // conversation: compacted for it (by it, to its size), then the same step again. Once: still
918
901
  // too big after that (its window can't even hold the start), it's sent anyway.
@@ -934,6 +917,7 @@ async function runNative(s, task, images, signal) {
934
917
  out.text(res.content)
935
918
  }
936
919
  out.end()
920
+ client.announceSwitch?.() // "↻ … answered": under the reply, on a line of its own
937
921
  // the reply went round and round (client.js cut it): told so, and asked again
938
922
  if (res.looped) {
939
923
  if (++looping > 3) {
@@ -941,7 +925,7 @@ async function runNative(s, task, images, signal) {
941
925
  looping = 0
942
926
  } else ui.warn(`${client.model} went into a loop; cut, and asked again`)
943
927
  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 }) })
928
+ s.messages.push({ role: 'user', content: prompt('agent/bad-reply', { sample: res.looped }) })
945
929
  continue
946
930
  }
947
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
@@ -962,7 +946,7 @@ async function runNative(s, task, images, signal) {
962
946
  if (markup && garbled++ < 2) {
963
947
  log('task', `${client.model}: a tool call written as text; asking again`, res.content)
964
948
  s.messages.pop()
965
- s.messages.push({ role: 'user', content: prompt('agent/garbled-call') })
949
+ s.messages.push({ role: 'user', content: prompt('agent/bad-reply', { sample: '' }) })
966
950
  continue
967
951
  }
968
952
  if (markup) {
@@ -1054,7 +1038,7 @@ async function runNative(s, task, images, signal) {
1054
1038
  // refused one is easily taken for refused too), once a message; not a helper's (its job is its plan)
1055
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')
1056
1040
  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
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
1058
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')
1059
1043
  if (!refused && args) out += guard.after(name, args, out)
1060
1044
  if (guard.stuck) stuck ??= guard.stuck
@@ -1085,7 +1069,7 @@ async function runNative(s, task, images, signal) {
1085
1069
  const sig = `${name} ${call.function.arguments}`
1086
1070
  inRow = sig === lastCall ? inRow + 1 : 1
1087
1071
  lastCall = sig
1088
- 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 })}`
1089
1073
  if (inRow >= 5) stuck = `made the same ${name} call five times in a row`
1090
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`)
1091
1075
  else if (name === 'agent' && !failed(out)) ui.result(`${s.ui.permission === 'plan' ? 'planned' : 'done'}: ${clip(out.split('\n').find((l) => l.trim()) ?? '', 100)}`)
@@ -1117,7 +1101,7 @@ async function runNative(s, task, images, signal) {
1117
1101
  }
1118
1102
  // screenshots from MCP tools: tool results are text only, so images follow as a message
1119
1103
  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 } }))] })
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 } }))] })
1121
1105
  s.pendingImages = []
1122
1106
  }
1123
1107
  }
@@ -1134,6 +1118,7 @@ const EDITS = new Set(['edit_file', 'write_file', 'append_file', 'apply_patch'])
1134
1118
  const CHECKS = new Set(['run_command', 'mcp', 'agent', 'lsp'])
1135
1119
  // Files only read by people (a change there needs no run to check it).
1136
1120
  const DOC_FILE = /\.(md|mdx|txt|rst|adoc)$/i
1121
+
1137
1122
  // Tools that only look (nothing changes): several in one reply run at the same time.
1138
1123
  const LOOKUPS = new Set(['web_search', 'web_fetch', 'read_file', 'search', 'list_files', 'find_command', 'lsp', 'changes'])
1139
1124
  export function newGuard() {
@@ -1161,14 +1146,14 @@ export function newGuard() {
1161
1146
  if (!was || (name === 'run_command' && Date.now() - was.at > 20_000)) return null
1162
1147
  repeats++
1163
1148
  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')}` : '')
1149
+ return prompt('agent/already-done', { result: was.out, circling: repeats >= 3 })
1165
1150
  }
1166
1151
  g.after = (name, a, out) => {
1167
1152
  let note = ''
1168
1153
  if (name === 'run_command') {
1169
1154
  const code = Number(/^exit code (-?\d+)/.exec(out)?.[1] ?? 0)
1170
1155
  failing = code ? failing + 1 : 0
1171
- 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 })}`
1172
1157
  if (failing >= 8) g.stuck = 'had eight commands in a row fail'
1173
1158
  if (!readOnlyCommand(String(a.command ?? ''))) epoch++ // it may have changed things: what came before can be done again
1174
1159
  }
@@ -1248,34 +1233,49 @@ async function learnFromFixes(s, fixed, signal) {
1248
1233
  // The model said it would do something but stopped without doing it ("let me rewrite…", "I'll fix…"):
1249
1234
  // a next action named, then no tool call. Not matched by explanations ("let me explain", "you can run").
1250
1235
  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
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
1252
1237
 
1253
1238
  // Is the task really done, or did the model stop early? Open todo items, or (after it did real work)
1254
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
+
1255
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
+ }
1256
1255
  const open = s.todoTouched && s.ui.permission !== 'plan' ? (s.chat.todos ?? []).filter((t) => t.status !== 'completed') : [] // plan mode: they wait for the approval
1257
1256
  if (open.length) {
1258
1257
  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') })
1258
+ return prompt('agent/not-done', { todos: open.map((t) => `- ${t.content}`).join('\n') })
1260
1259
  }
1261
1260
  // changed files and hasn't run anything since: not proven to work
1262
1261
  const changed = [...(s.changed ?? [])]
1263
1262
  if (changed.length && s.lastCheckAt < s.lastChangeAt && !changed.every((f) => DOC_FILE.test(f)) && s.ui.permission !== 'plan') {
1264
1263
  log('task', `finished with changes not checked since (${changed.join(', ')}); asking for a check`)
1265
- return prompt('agent/unchecked', { files: changed.join(', ') })
1264
+ return prompt('agent/not-done', { unchecked: changed.join(', ') })
1266
1265
  }
1267
1266
  // says it made files that aren't there
1268
1267
  const missing = missingFiles(s.root, reply)
1269
1268
  if (missing.length) {
1270
1269
  log('task', `the answer names files that don't exist: ${missing.join(', ')}`)
1271
- return prompt('agent/missing-files', { files: missing.join(', ') })
1270
+ return prompt('agent/not-done', { missing: missing.join(', ') })
1272
1271
  }
1273
1272
  if (s.acted && reply && PROMISED_MORE.test(reply)) {
1274
1273
  log('task', 'reply names a next step but no tool call followed; nudging to finish')
1275
- return prompt('agent/stopped-early')
1274
+ return prompt('agent/not-done', { early: true })
1276
1275
  }
1276
+ if (s.isSub) return null // a helper: the Stop hooks are the main conversation's
1277
1277
  const hook = await runHooks(s, 'Stop', { stop_hook_active: again }, signal)
1278
- return hook.block ? prompt('agent/hook-stop', { reason: hook.block }) : null
1278
+ return hook.block ? prompt('agent/hook', { reason: hook.block, stop: true }) : null
1279
1279
  }
1280
1280
 
1281
1281
  // Files the final answer says were made, that aren't in the project: a path in backticks, or one
@@ -1349,7 +1349,9 @@ export async function review(s, task, answer, signal) {
1349
1349
  } catch {}
1350
1350
  if (now === before) continue
1351
1351
  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))
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
1353
1355
  room -= piece.length
1354
1356
  diffs.push(piece)
1355
1357
  if (room <= 500) {
@@ -1362,9 +1364,8 @@ export async function review(s, task, answer, signal) {
1362
1364
  const ran = (s.ran ?? []).slice(-15).map((r) => `- ${clip(r.command.replace(/\s+/g, ' '), 160)} → ${r.result}`).join('\n')
1363
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)' })
1364
1366
  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
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]) {
1368
1369
  s.ui.spinner(`${t.model} is reviewing the work`)
1369
1370
  try {
1370
1371
  const { client } = t.self ? { client: s.client } : await s.engineFor(t)
@@ -1403,18 +1404,25 @@ export async function review(s, task, answer, signal) {
1403
1404
  // Its thinking is shown whole when its reply is in (helpers working at once don't mix), named.
1404
1405
  // Questions to the user (confirm, pick, ask) wait their turn: helpers working at once ask one by one.
1405
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)
1406
1408
  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.
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).
1409
1412
  const response = () => {
1410
1413
  const t0 = Date.now()
1411
1414
  let thought = ''
1412
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
1413
1419
  return {
1414
- think: (t) => (thought += t ?? ''),
1420
+ think: (t) => (live ? live.think(t) : (thought += t ?? '')),
1415
1421
  text: (t) => (said += t ?? ''),
1416
1422
  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, ' ')))}` : ''))
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, ' ')))}` : ''))
1418
1426
  if (!said.trim()) return
1419
1427
  ui.print(` ${c.bright(c.bold('●'))} ${c.bold(label)}`)
1420
1428
  let block = new Block((x) => ui.write(x), { marker: ' ', style: c.text })
@@ -1453,7 +1461,7 @@ export function fitResult(s, name, out, file) {
1453
1461
  if (out.length <= max) return out
1454
1462
  file ??= saveOutput(s.chat?.id, name, out)
1455
1463
  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 })}`
1464
+ return `${out.slice(0, max)}\n…\n${prompt('agent/output-cut', { shown: max, total: out.length, file, call: '' })}`
1457
1465
  }
1458
1466
 
1459
1467
  // Results longer than this are saved to a file when they come (so they can leave the conversation later).
@@ -1480,7 +1488,7 @@ function callOf(messages, id) {
1480
1488
  // provider's prompt cache (the conversation's unchanged start) is broken rarely, not every step.
1481
1489
  // An older conversation's results (no file yet) are saved now, before they're cut.
1482
1490
  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))
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))
1484
1492
  if (long.length <= most) return
1485
1493
  dropStale(s) // the conversation changes here anyway: the older copies of files read again go too
1486
1494
  for (const m of long.slice(0, -keep)) {
@@ -1488,7 +1496,7 @@ export function trimOldResults(s, keep = 4, most = 8) {
1488
1496
  const read = /^read_file /.test(call) ? call.slice('read_file '.length) : '' // a project file: read it again
1489
1497
  const file = read || s.chat.outputs?.[m.tool_call_id] || saveOutput(s.chat?.id, 'older', m.content)
1490
1498
  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…`
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…`
1492
1500
  shortened.add(m)
1493
1501
  }
1494
1502
  log('tool', `older tool output cut: ${long.length - keep} results`)
@@ -1556,7 +1564,7 @@ export function contextReport(s) {
1556
1564
  const ago = msgs.length - 1 - i
1557
1565
  if (i === 0 && m.role === 'system') return void (parts.system += n)
1558
1566
  if (m.role === 'tool') {
1559
- const old = typeof m.content === 'string' && /^\[older output/.test(m.content)
1567
+ const old = typeof m.content === 'string' && /^\[older output/i.test(m.content)
1560
1568
  old ? (parts.pointers += n, cut++) : (parts.results += n, whole++)
1561
1569
  pieces.push({ tokens: n, what: `${callOf(msgs, m.tool_call_id)} (result${old ? ', a pointer' : ''})`, ago })
1562
1570
  } else if (m.role === 'assistant') {