heartcode 0.1.25 → 0.1.30

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
@@ -7,11 +7,12 @@ import path from 'node:path'
7
7
  import { pathToFileURL } from 'node:url'
8
8
  import { est, Client, writtenBy, tokensOf, COMPACT_SHARE } from './client.js'
9
9
  import { runGuided } from './guided.js'
10
- import { TOOL_DEFS, PLAN_HIDDEN, folderView, readOnlyCommand, extraTools, runTool, listFiles, namedFiles, readFileTool, clip, allowed, loadMcpTools, saveOutput, OUTPUTS, imageUrl, MAX_IMAGE, failed } from './tools.js'
10
+ import { markUsed, removeResearch, findResearch } from './research.js'
11
+ import { TOOL_DEFS, PLAN_HIDDEN, folderView, readOnlyCommand, extraTools, runTool, listFiles, namedFiles, readFileTool, clip, allowed, loadMcpTools, saveOutput, isSavedOutput, runningCall, imageUrl, MAX_IMAGE, failed } from './tools.js'
11
12
  import { serversNote } from './lsp.js'
12
13
  import { loadHooks, runHooks } from './hooks.js'
13
14
  import { takeConfigErrors } from './config.js'
14
- import { c, duration } from './ui.js'
15
+ import { c, duration, Block, Markdown, color, diffLines, renderDiff } from './ui.js'
15
16
 
16
17
  // Images for a helper (the agent tool's "images"), as data: URLs: image URLs (fetched), data: URLs,
17
18
  // or files: in the project, saved screenshots (OUTPUTS), or a path the user gave in a message.
@@ -38,7 +39,7 @@ async function loadImages(list, s, signal) {
38
39
  } else {
39
40
  const abs = path.resolve(s.root, x.replace(/^~(?=\/)/, os.homedir()))
40
41
  const inside = (dir) => abs.startsWith(dir + path.sep)
41
- if (fs.existsSync(abs) && !inside(s.root) && !inside(OUTPUTS) && !s.toolImages?.has(abs) && !s.chat.turns.some((t) => t.task.includes(x) || t.task.includes(abs))) throw new Error(`${x} is outside the project; only images in it, saved screenshots and ones the user named can be sent`)
42
+ if (fs.existsSync(abs) && !inside(s.root) && !isSavedOutput(abs) && !s.toolImages?.has(abs) && !s.chat.turns.some((t) => t.task.includes(x) || t.task.includes(abs))) throw new Error(`${x} is outside the project; only images in it, saved screenshots and ones the user named can be sent`)
42
43
  out.push(imageUrl(abs, x))
43
44
  }
44
45
  }
@@ -247,7 +248,7 @@ export class Session {
247
248
  }
248
249
  const label = clip(`${client.model}: ${String(description ?? '').trim() || task.split('\n')[0]}`, 60)
249
250
  const helper = new Session({ client, profile, strat, root: this.root, ui: helperUI(this.ui, label), chat: newChat(this.root) })
250
- Object.assign(helper, { isSub: true, 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 })
251
+ 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 })
251
252
  helper.track = (rel, before) => this.track(rel, before)
252
253
  helper.mcpGate = async () => (await this.#gate(helper), () => {})
253
254
  if (this.onEvent) helper.onEvent = (e) => this.onEvent({ ...e, parent: id, helper: label })
@@ -357,11 +358,14 @@ export class Session {
357
358
  return prompt('agent/memory-extract', { tags: this.memory.tagSummary() || '(none yet)', notes })
358
359
  }
359
360
 
360
- // A small tool loop with only the memory tool (saving and tidying notes).
361
- async memoryTask(system, user, signal, steps = 12) {
362
- const tools = extraTools({ memory: this.memory }).map((f) => ({ type: 'function', function: f }))
361
+ // A small tool loop with the memory tool (saving and tidying notes), and any `extra` tools ({ defs,
362
+ // run(name, args) → result or undefined for the memory tool }). It ends when the model answers, or
363
+ // makes exactly the calls it just made (going round, not getting anywhere).
364
+ async memoryTask(system, user, signal, extra = null) {
365
+ const tools = [...extraTools({ memory: this.memory }), ...(extra?.defs ?? [])].map((f) => ({ type: 'function', function: f }))
363
366
  const messages = [{ role: 'system', content: system }, { role: 'user', content: user }]
364
- for (let step = 0; step < steps; step++) {
367
+ let last = ''
368
+ for (;;) {
365
369
  const was = this.client.purpose
366
370
  this.client.purpose = 'memory' // in the requests log
367
371
  let res
@@ -372,17 +376,90 @@ export class Session {
372
376
  }
373
377
  messages.push({ role: 'assistant', content: res.content || '', ...(res.toolCalls.length && { tool_calls: res.toolCalls }) })
374
378
  if (!res.toolCalls.length) return res.content.trim()
379
+ const these = res.toolCalls.map((t) => `${t.function.name} ${t.function.arguments}`).join('\n')
380
+ if (these === last) return res.content.trim()
381
+ last = these
375
382
  for (const call of res.toolCalls) {
376
383
  let args = {}
377
384
  try {
378
385
  args = JSON.parse(call.function.arguments || '{}')
379
386
  } catch {}
380
- const out = await runTool(call.function.name, args, this, signal)
381
- if (args.action === 'write' || args.action === 'delete') this.ui.step('memory', `${args.action === 'write' ? 'saved' : 'deleted'} ${out.match(/\[\[[^\]]+\]\]/)?.[0] ?? ''}`)
387
+ const out = (await extra?.run(call.function.name, args)) ?? (call.function.name === 'memory' ? await runTool('memory', args, this, signal) : `error: there is no tool named ${call.function.name}`)
388
+ if (call.function.name === 'memory' && (args.action === 'write' || args.action === 'delete') && !failed(out)) this.ui.step('memory', `${args.action === 'write' ? 'saved' : 'deleted'} ${out.match(/\[\[[^\]]+\]\]/)?.[0] ?? ''}${args.scope === 'global' ? ' (global)' : ''}`)
382
389
  messages.push({ role: 'tool', tool_call_id: call.id, content: out })
383
390
  }
384
391
  }
385
- return ''
392
+ }
393
+
394
+ // After a task that read the web, ran commands or made files: what's worth knowing next time is
395
+ // saved as notes (project or global), each page it read is kept (marked with what it was used for)
396
+ // or deleted as junk, and throwaway files it made are removed. Done by code after every such task,
397
+ // not left to the model to remember: a fresh, small request (the task, its answer, the lists), on
398
+ // the model that did the task. Helpers' pages are in the same list (they share it).
399
+ async wrapUp(task, answer, signal) {
400
+ if (this.isSub || !this.memory || this.ui.permission === 'plan') return
401
+ const pages = this.research ?? []
402
+ const turn = this.chat.turns.at(-1)
403
+ const made = Object.entries(turn?.files ?? {}).filter(([rel, before]) => before === null && fs.existsSync(path.join(this.root, rel))).map(([rel]) => rel)
404
+ // folders the task made that are still empty (a test folder): offered for cleanup too
405
+ if (this.dirsBefore) for (const d of foldersOf(this.root)) if (!this.dirsBefore.has(d) && isEmptyDir(path.join(this.root, d))) made.push(`${d}/`)
406
+ const ran = this.ran ?? []
407
+ if (!pages.length && !made.length && !ran.length) return
408
+ const commands = ran.map((r) => `- ${clip(r.command.replace(/\s+/g, ' '), 200)} → ${r.result}`).join('\n')
409
+ const known = this.memory.relevant(`${task}\n${answer}\n${pages.map((p) => p.title).join('\n')}`, 12)
410
+ const request = prompt('agent/wrapup-task', {
411
+ task: clip(task, 4000),
412
+ answer: clip(String(answer ?? ''), 4000) + (commands ? `\n\nCommands it ran (newest last):\n${commands.length > 6000 ? `…\n${commands.slice(-6000)}` : commands}` : ''),
413
+ pages: pages.map((p) => `- [${p.kind}] ${p.title}${p.url ? ` — ${p.url}` : ''} → file: ${p.file}`).join('\n') || '(none)',
414
+ files: made.map((f) => `- ${f}`).join('\n') || '(none)',
415
+ notes: known.map((n) => `- [[${n.name}]] (${n.scope}) — ${n.description}`).join('\n') || '(none)',
416
+ })
417
+ const files = new Set(pages.map((p) => p.file))
418
+ const scratch = new Set(made)
419
+ const kept = []
420
+ const dropped = []
421
+ const removed = []
422
+ const defs = [
423
+ { name: 'research', description: 'Keep (verdict "used", with used_for) or delete (verdict "junk") one page or search the task read.', parameters: { type: 'object', properties: { file: { type: 'string' }, verdict: { type: 'string', enum: ['used', 'junk'] }, used_for: { type: 'string' } }, required: ['file', 'verdict'] } },
424
+ { name: 'scratch', description: 'Keep or delete one new file the task made.', parameters: { type: 'object', properties: { path: { type: 'string' }, verdict: { type: 'string', enum: ['keep', 'delete'] } }, required: ['path', 'verdict'] } },
425
+ ]
426
+ const run = (name, a) => {
427
+ if (name === 'research') {
428
+ const f = [...files].find((x) => x === a.file || path.basename(x) === path.basename(String(a.file ?? '')))
429
+ if (!f) return `error: "${a.file}" isn't one of the pages this task read: ${[...files].join(', ')}`
430
+ if (a.verdict === 'junk') return removeResearch(this.root, f) ? (dropped.push(f), `Deleted ${f}.`) : `error: ${f} is gone already`
431
+ return markUsed(this.root, f, String(a.used_for ?? '').trim()) ? (kept.push(f), `Kept ${f}.`) : `error: ${f} is gone`
432
+ }
433
+ if (name === 'scratch') {
434
+ let rel = String(a.path ?? '').trim().replace(/^\.\//, '')
435
+ if (!scratch.has(rel) && scratch.has(`${rel}/`)) rel = `${rel}/` // a folder named without its slash
436
+ if (!scratch.has(rel)) return `error: "${rel}" isn't one of the new files this task made: ${[...scratch].join(', ')}`
437
+ if (a.verdict !== 'delete') return `Kept ${rel}.`
438
+ if (rel.endsWith('/')) {
439
+ if (!isEmptyDir(path.join(this.root, rel))) return `error: ${rel} isn't empty: delete the files in it first, or keep it`
440
+ fs.rmSync(path.join(this.root, rel, '.DS_Store'), { force: true })
441
+ fs.rmdirSync(path.join(this.root, rel))
442
+ } else fs.rmSync(path.join(this.root, rel), { force: true })
443
+ scratch.delete(rel)
444
+ removed.push(rel)
445
+ this.ui.step('cleanup', `removed ${rel}`)
446
+ return `Deleted ${rel}.`
447
+ }
448
+ }
449
+ this.ui.spinner('keeping what this task learned')
450
+ const was = this.client.purpose
451
+ try {
452
+ this.client.purpose = 'wrapup'
453
+ const said = await this.memoryTask(prompt('agent/wrapup'), request, signal, { defs, run })
454
+ log('wrapup', `${said} | pages kept ${kept.length}, deleted ${dropped.length}; files removed ${removed.length}`)
455
+ if (kept.length || dropped.length) this.ui.step('research', `kept ${kept.length} page${kept.length === 1 ? '' : 's'}${dropped.length ? `, deleted ${dropped.length} as junk` : ''}`)
456
+ } catch (e) {
457
+ if (e.name === 'AbortError' || signal?.aborted) throw e
458
+ log('wrapup', `failed: ${e.message}`)
459
+ } finally {
460
+ this.client.purpose = was
461
+ this.ui.stopSpin()
462
+ }
386
463
  }
387
464
 
388
465
  // /tidy_memory: merge duplicates, drop what's outdated, link related notes.
@@ -393,7 +470,7 @@ export class Session {
393
470
  const room = Math.floor(this.strat.context * 0.5 * 3.5)
394
471
  const text = notes.map((n) => `## [[${n.name}]] (${n.scope}, ${n.type}; tags: ${n.tags.join(', ') || 'none'}) — ${n.description}\n${n.body}`).join('\n\n').slice(0, room)
395
472
  const broken = this.memory.brokenLinks().map((b) => `[[${b.to}]] in [[${b.from}]]`).join(', ')
396
- const summary = await this.memoryTask(this.#extractPrompt(''), prompt('agent/memory-tidy', { notes: text, broken }), signal, 30 + notes.length * 3)
473
+ const summary = await this.memoryTask(this.#extractPrompt(''), prompt('agent/memory-tidy', { notes: text, broken }), signal)
397
474
  this.ui.stopSpin()
398
475
  this.ui.print(`${c.faint('✻')} ${c.muted(`Tidied the memory${summary && summary !== 'NONE' ? `: ${clip(summary.split('\n')[0], 140)}` : ''}`)}`)
399
476
  return summary
@@ -456,9 +533,6 @@ const sizeOf = (m) =>
456
533
  export const size = (messages) => messages.reduce((n, m) => n + sizeOf(m), 0)
457
534
  const kTokens = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n))
458
535
 
459
- // How many steps a helper (the agent tool) takes at most before it answers with what it has.
460
- const HELPER_STEPS = 25
461
-
462
536
  // A chat template's tool-call markup in a reply's text (a tool call the model wrote out): outside
463
537
  // code blocks, and the reply ends in it (an answer that only mentions such tags isn't one).
464
538
  const MARKUP = /<\/?tool_call>|<\/?arg_(?:key|value)>|<function=[\w.-]+>|<\|[a-z_]+\|>/i
@@ -570,6 +644,28 @@ async function finalAnswer(s, signal, why = 'empty replies in a row') {
570
644
  return text
571
645
  }
572
646
 
647
+ // An older conversation called MCP tools by their own names (mcp__server__tool: each was offered as
648
+ // a tool then). Now they're all behind the one mcp tool, so those calls are rewritten as mcp calls:
649
+ // a request then names only tools it offers (some providers refuse one that doesn't). In place.
650
+ export function legacyMcpCalls(messages, direct) {
651
+ for (const m of messages ?? []) {
652
+ for (const t of m.tool_calls ?? []) {
653
+ const name = t.function?.name ?? ''
654
+ if (!name.startsWith('mcp__')) continue
655
+ const d = direct?.get(name)
656
+ const parts = /^mcp__(.+?)__(.+)$/.exec(name)
657
+ const server = d?.server ?? parts?.[1]
658
+ const tool = d?.tool ?? parts?.[2]
659
+ if (!server || !tool) continue
660
+ let args = {}
661
+ try {
662
+ args = JSON.parse(t.function.arguments || '{}')
663
+ } catch {}
664
+ t.function = { name: 'mcp', arguments: JSON.stringify({ server, tool, arguments: args }) }
665
+ }
666
+ }
667
+ }
668
+
573
669
  // Every tool call needs its result right after it, and every result its call, or the API rejects
574
670
  // the request (and it would be retried forever). Esc during a tool leaves a call without a result;
575
671
  // trimming can leave a result without its call. Mends both, in place.
@@ -599,6 +695,7 @@ async function runNative(s, task, images, signal) {
599
695
  // The model's thinking goes back with its steps while it works on a message (it keeps its plan
600
696
  // from one tool call to the next), not into later messages.
601
697
  for (const m of s.messages ?? []) delete m.reasoning_content
698
+ legacyMcpCalls(s.messages, s.mcpDirect)
602
699
  // The system prompt is rebuilt for every message: files come and go, and a resumed chat's is
603
700
  // from back then (it once told the model the project was empty after it had made files).
604
701
  // Unchanged, it stays the same text, so a provider's prompt cache still holds.
@@ -632,8 +729,28 @@ async function runNative(s, task, images, signal) {
632
729
  // schemas, takes most of the window): compacting again won't free anything, so not until it has
633
730
  // grown by another 5% (not a summary request at every step).
634
731
  const afterCompact = () => (s.compactFailedAt = used() >= strat.context * COMPACT_SHARE ? used() + Math.round(strat.context * 0.05) : 0)
635
- // Already that long from earlier messages: compact first, so the new message stays word for word.
636
- if (nearlyFull()) {
732
+ // Over the current model's window and your list holds a model that can take the whole conversation:
733
+ // move to it instead of compacting — losing nothing beats summarizing when you have a roomier model.
734
+ // Scanned in your list order, so it picks your highest-priority model that fits; false when none of
735
+ // your other models has more room (then the caller compacts: use what's available).
736
+ const roomier = () => {
737
+ const r = client.rotation
738
+ if (!r || r.list.length < 2 || !s.windowOf) return false
739
+ const need = used()
740
+ for (let k = 0; k < r.list.length; k++) {
741
+ if (k === r.at) continue
742
+ const win = s.windowOf(r.list[k])
743
+ if (win > 0 && need <= win * COMPACT_SHARE) {
744
+ ui.print(c.dim(`↻ this chat (~${kTokens(need)}) is past ${client.model}'s window — moving to ${r.list[k].model} (holds ~${kTokens(win)})`))
745
+ client.switchTo(r.list[k], `context ~${kTokens(need)} > ${client.model} window`)
746
+ return true
747
+ }
748
+ }
749
+ return false
750
+ }
751
+ // Already that long from earlier messages: switch to a roomier model, or else compact first, so the
752
+ // new message stays word for word.
753
+ if (nearlyFull() && !roomier()) {
637
754
  await s.compact({ signal, why: fullness() }).then(afterCompact, (e) => (e.name === 'AbortError' ? Promise.reject(e) : ui.warn(`could not compact: ${e.message}`)))
638
755
  }
639
756
  // only the memory notes this message matches go with it (the system prompt has just the tags)
@@ -641,8 +758,20 @@ async function runNative(s, task, images, signal) {
641
758
  const sent = new Set(s.chat.sentNotes ?? [])
642
759
  const key = (n) => `${n.scope}:${n.name}:${n.description}`
643
760
  const notes = (s.memory?.relevant(task) ?? []).filter((n) => !sent.has(key(n)))
644
- s.chat.sentNotes = [...sent, ...notes.map(key)]
645
- const text = notes.length ? `${task}\n\n${prompt('agent/memory-relevant', { notes: notes.map((n) => `[[${n.name}]] — ${n.description}`).join('\n') })}` : task
761
+ // pages already read for this project that match: titles only (the model opens one when needed)
762
+ const pages = s.isSub || !s.memory ? [] : findResearch(s.root, task, 6).filter((r) => r.kind !== 'search' && !sent.has(`research:${r.name}:${r.fetched}`))
763
+ s.chat.sentNotes = [...sent, ...notes.map(key), ...pages.map((r) => `research:${r.name}:${r.fetched}`)]
764
+ const guideSent = () => (s.chat.sentNotes ?? []).includes('guide:ui')
765
+ // the UI guide: once per conversation, with a message about a UI (else with the first UI file written)
766
+ const uiGuide = !sent.has('guide:ui') && UI_TASK.test(task)
767
+ if (uiGuide) s.chat.sentNotes = [...(s.chat.sentNotes ?? []), 'guide:ui']
768
+ const known = [
769
+ uiGuide && prompt('agent/ui-guide'),
770
+ notes.length && prompt('agent/memory-relevant', { notes: notes.map((n) => `[[${n.name}]] — ${n.description}`).join('\n') }),
771
+ pages.length && prompt('agent/research-known', { pages: pages.map((r) => `- ${r.title} — ${r.url} (read ${r.fetched}) → ${r.file}`).join('\n') }),
772
+ ].filter(Boolean)
773
+ const text = known.length ? `${task}\n\n${known.join('\n\n')}` : task
774
+ 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
646
775
  const planning = ui.permission === 'plan'
647
776
  // the research-first reminder: small models follow the user's message far more than the system
648
777
  // prompt (not a helper's job, nor a program's own task with its own instructions)
@@ -666,29 +795,35 @@ async function runNative(s, task, images, signal) {
666
795
  s.uiErrorsPrev = [] // hard errors from the last look: when one is gone next look, it was fixed — learn from it
667
796
  s.runFails = new Map() // a command that failed (by its tool) → its error; when the same tool runs clean after an edit, that's a verified fix to learn from (any language, not just web)
668
797
  s.edits = 0 // successful file edits so far this message (to tell a real fix from a lucky rerun)
669
- let nudged = 0 // reminders sent this message about open todo items or a Stop hook
798
+ s.acted = false // used a tool this message (so a reply that only promises more is a premature stop)
799
+ let nudged = 0 // reminders sent this message about open todo items, a premature stop, or a Stop hook
800
+ 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)
801
+ s.planAsked = false // asked for a plan before its first change, this message
802
+ // what changed and when it was last checked, this message: a change not run/tested since isn't done
803
+ Object.assign(s, { changed: new Set(), seq: 0, lastChangeAt: -1, lastCheckAt: -1, reviewedAt: -1 })
670
804
 
671
805
  let empty = 0 // replies in a row with neither text nor tool calls
672
806
  let looping = 0 // replies cut for going into a loop, this message
673
- let stuck = null // why it's stopped: going round in circles this message
807
+ let stuck = null // why it's going round in circles (then the next model takes over; nothing stops but Esc)
808
+ // Going round in circles: the next of your models carries on (a different model often gets out of
809
+ // it); with no other model, a warning, and it goes on being told what it repeats — only Esc stops it.
810
+ const handOver = (why) => {
811
+ const was = client.model
812
+ if (client.moveOn?.(`${was} ${why}`)) ui.warn(`${was} ${why}; handing over to ${client.model}`)
813
+ else ui.warn(`${was} ${why} — it carries on, told so; Esc stops it`)
814
+ }
674
815
  let garbled = 0 // replies with a tool call written as text (template markup), this message
675
816
  let movedOn = 0 // models given up on for that, in this message
676
817
  let refitted = false // this step's conversation was just compacted for a smaller model the list moved on to
677
- // No step limit: a long fix takes many steps, and Esc stops it. A caller can set one (--max-turns).
818
+ // No step limit (helpers too): a long fix takes many steps, and Esc stops it. A caller can set one (--max-turns).
678
819
  for (let step = 0; ; step++) {
679
820
  const tools = toolList()
680
- // a helper has a budget: then it answers with what it has (one once searched the web for 40
681
- // steps to answer which of two numbers is bigger)
682
- if (s.isSub && step >= HELPER_STEPS) {
683
- ui.warn(`${client.model} took ${HELPER_STEPS} steps; asking it for its answer`)
684
- return finalAnswer(s, signal, `helper: ${HELPER_STEPS} steps`)
685
- }
686
821
  if (s.maxTurns && step >= s.maxTurns) {
687
822
  ui.warn(`stopped after ${s.maxTurns} steps (--max-turns); say "continue" to go on`)
688
823
  throw Object.assign(new Error(`stopped after ${s.maxTurns} steps (--max-turns)`), { maxTurns: true })
689
824
  }
690
825
  // after a failed compaction, the next try waits until the conversation has grown by 5% of the window
691
- if (nearlyFull() && step !== s.compactedAt) {
826
+ if (nearlyFull() && step !== s.compactedAt && !roomier()) {
692
827
  s.compactedAt = step
693
828
  await s.compact({ signal, midTask: true, task, why: fullness() }).then(
694
829
  afterCompact,
@@ -740,10 +875,9 @@ async function runNative(s, task, images, signal) {
740
875
  // the reply went round and round (client.js cut it): told so, and asked again
741
876
  if (res.looped) {
742
877
  if (++looping > 3) {
743
- ui.warn(`stopped: ${client.model} keeps going into a loop`)
744
- return finalAnswer(s, signal, 'its replies kept going into a loop')
745
- }
746
- ui.warn(`${client.model} went into a loop; cut, and asked again`)
878
+ handOver(`keeps going into a loop`)
879
+ looping = 0
880
+ } else ui.warn(`${client.model} went into a loop; cut, and asked again`)
747
881
  if (res.content.trim()) s.messages.push({ role: 'assistant', content: res.content })
748
882
  s.messages.push({ role: 'user', content: prompt('agent/looped', { sample: res.looped }) })
749
883
  continue
@@ -773,6 +907,7 @@ async function runNative(s, task, images, signal) {
773
907
  res.content = res.content.slice(0, markup.index).trim()
774
908
  s.messages[s.messages.length - 1] = { ...s.messages.at(-1), content: res.content }
775
909
  }
910
+ if (res.toolCalls.length) s.acted = sinceNudge = true // did real work this message, for the premature-stop check
776
911
  s.onEvent?.({ type: 'assistant', model: `${client.provider}/${client.model}`, content: res.content, reasoning: res.reasoning, toolCalls: res.toolCalls }) // headless output
777
912
  if (!res.toolCalls.length && !res.content?.trim()) {
778
913
  // Nothing at all (seen after a failed tool call): not an answer. The same request again
@@ -801,9 +936,13 @@ async function runNative(s, task, images, signal) {
801
936
  s.messages.push({ role: 'user', content: look })
802
937
  continue
803
938
  }
804
- const more = nudged < 3 && !s.isSub && (await notDone(s, signal, nudged > 0))
805
- if (!more) return res.content
939
+ const more = sinceNudge && !s.isSub && ((await notDone(s, signal, nudged > 0, res.content)) ?? (await review(s, task, res.content, signal)))
940
+ if (!more) {
941
+ await s.wrapUp?.(task, res.content, signal)
942
+ return res.content
943
+ }
806
944
  nudged++
945
+ sinceNudge = false
807
946
  s.messages.push({ role: 'user', content: more })
808
947
  continue
809
948
  }
@@ -854,10 +993,22 @@ async function runNative(s, task, images, signal) {
854
993
  : (args.path ?? args.url ?? args.query ?? args.filter ?? args.name ?? '')
855
994
  if (name !== 'run_command' && !together.has(call.id)) ui.step(name, clip(detail, 80))
856
995
  const pre = early.get(call.id)
857
- const refused = pre ? (pre.refused ?? null) : !together.has(call.id) && args && allowed(s, name) ? guard.before(name, args) : null
996
+ // the first change to the files with no plan yet (this message, or still open from an earlier one):
997
+ // not made — the plan first, then the change again. Once a message; not a helper's (its job is its plan)
998
+ const planFirst = !s.isSub && !s.planAsked && EDITS.has(name) && args && allowed(s, name) && ui.permission !== 'plan' && !s.todoTouched && !(s.chat.todos ?? []).some((t) => t.status !== 'completed')
999
+ if (planFirst) s.planAsked = true
1000
+ const refused = planFirst ? prompt('agent/plan-first') : pre ? (pre.refused ?? null) : !together.has(call.id) && args && allowed(s, name) ? guard.before(name, args) : null
858
1001
  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')
859
1002
  if (!refused && args) out += guard.after(name, args, out)
860
1003
  if (guard.stuck) stuck ??= guard.stuck
1004
+ if (args && !refused) {
1005
+ s.seq++
1006
+ if (EDITS.has(name) && !failed(out)) {
1007
+ s.lastChangeAt = s.seq
1008
+ if (args.path) s.changed.add(String(args.path))
1009
+ } else if (CHECKS.has(name)) s.lastCheckAt = s.seq // ran something: a check of what changed (the model judges its result)
1010
+ }
1011
+ if (name === 'run_command' && args && !refused) s.ran?.push({ command: String(args.command ?? ''), result: clip(String(out).split('\n').filter((l) => l.trim()).slice(0, 2).join(' · '), 160) })
861
1012
  if (!s.isSub && s.memory && !refused && args) await noteRun(s, name, args, out, signal).catch((e) => log('learn', `run note: ${e.message}`)) // learn from any run that failed then passed
862
1013
  // the same call again and again in a row (a weak model going round): told at the third, stopped at the fifth
863
1014
  const sig = `${name} ${call.function.arguments}`
@@ -869,15 +1020,28 @@ async function runNative(s, task, images, signal) {
869
1020
  else if (name === 'agent' && !failed(out)) ui.result(`${s.ui.permission === 'plan' ? 'planned' : 'done'}: ${clip(out.split('\n').find((l) => l.trim()) ?? '', 100)}`)
870
1021
  else if (failed(out)) ui.result(clip(out, 120))
871
1022
  client.refresh?.() // a setting changed while the tool ran (the window): its result is cut by the new one
872
- const msg = { role: 'tool', tool_call_id: call.id, content: fitResult(s, name, out) }
1023
+ // the first UI file written in a conversation that hasn't had the UI guide: it comes with the result
1024
+ if (EDITS.has(name) && args && UI_FILE.test(String(args.path ?? '')) && !failed(out) && !guideSent()) {
1025
+ s.chat.sentNotes = [...(s.chat.sentNotes ?? []), 'guide:ui']
1026
+ out += `\n\n${prompt('agent/ui-guide')}`
1027
+ }
1028
+ // every sizable result is saved as it comes (a web page already is, in research): later it can
1029
+ // become a pointer to its file in the conversation without anything being lost
1030
+ if (out.length > SAVE_AT && name !== 'read_file' && !s.chat.outputs?.[call.id]) {
1031
+ const file = saveOutput(s.chat?.id, name, out)
1032
+ if (file) (s.chat.outputs ??= {})[call.id] = file
1033
+ }
1034
+ const msg = { role: 'tool', tool_call_id: call.id, content: fitResult(s, name, out, s.chat.outputs?.[call.id]) }
873
1035
  if (name === 'read_file' && args && !args.start_line && !args.end_line && !failed(out)) replaceCopy(s, args.path, msg)
874
1036
  s.messages.push(msg)
875
1037
  s.onEvent?.({ type: 'tool', id: call.id, name, output: out })
876
1038
  }
877
1039
  trimOldResults(s)
878
1040
  if (stuck) {
879
- ui.warn(`stopped: ${client.model} ${stuck}`)
880
- return finalAnswer(s, signal, stuck)
1041
+ handOver(stuck)
1042
+ stuck = null
1043
+ inRow = 0
1044
+ guard.calm()
881
1045
  }
882
1046
  // screenshots from MCP tools: tool results are text only, so images follow as a message
883
1047
  if (s.pendingImages?.length) {
@@ -894,6 +1058,13 @@ async function runNative(s, task, images, signal) {
894
1058
  // (ten calls already made) stops it.
895
1059
  // before: what to send back instead of running it (the earlier result), or null; after: a note for its result.
896
1060
  const EDITS = new Set(['edit_file', 'write_file', 'append_file', 'apply_patch'])
1061
+ // Tools that run or look at what was made (a command, a test, a browser, a helper): a check after a change.
1062
+ const CHECKS = new Set(['run_command', 'mcp', 'agent', 'lsp'])
1063
+ // Files only read by people (a change there needs no run to check it).
1064
+ const DOC_FILE = /\.(md|mdx|txt|rst|adoc)$/i
1065
+ // A message about something people look at (gets the UI guide), and a file that is one.
1066
+ const UI_TASK = /\b(ui|ux|web ?page|page|website|web ?site|landing|dashboard|screen|component|front-?end|layout|redesign|design|css|html|styles?|styling|theme|tailwind|navbar|modal|button)s?\b/i
1067
+ const UI_FILE = /\.(html?|css|scss|sass|less|jsx|tsx|vue|svelte|astro)$/i
897
1068
  // Tools that only look (nothing changes): several in one reply run at the same time.
898
1069
  const LOOKUPS = new Set(['web_search', 'web_fetch', 'read_file', 'search', 'list_files', 'find_command', 'lsp'])
899
1070
  export function newGuard() {
@@ -902,10 +1073,15 @@ export function newGuard() {
902
1073
  let failing = 0
903
1074
  let repeats = 0
904
1075
  const g = { stuck: null }
1076
+ g.calm = () => { // after a handover or a warning: counted again from nothing
1077
+ g.stuck = null
1078
+ repeats = 0
1079
+ failing = 0
1080
+ }
905
1081
  const words = (q) => [...new Set(String(q ?? '').toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [])].sort().join(' ')
906
1082
  const keyOf = (name, a) => {
907
- if (name === 'web_search') return `search: ${words(a.query)}`
908
- if (name === 'web_fetch') return `page: ${String(a.url ?? '').toLowerCase().replace(/^https?:\/\/(www\.)?/, '').replace(/\/+$/, '')} @${a.start ?? 0}`
1083
+ if (name === 'web_search') return `search: ${words(a.query)}${a.fresh ? ' (fresh)' : ''}`
1084
+ if (name === 'web_fetch') return `page: ${String(a.url ?? '').toLowerCase().replace(/^https?:\/\/(www\.)?/, '').replace(/\/+$/, '')} @${a.start ?? 0} ${words(a.look_for)}`
909
1085
  if (['run_command', 'read_file', 'search', 'list_files', 'find_command', 'lsp'].includes(name)) return `${name} ${JSON.stringify(a)} @${epoch}`
910
1086
  return null
911
1087
  }
@@ -937,9 +1113,9 @@ export function newGuard() {
937
1113
 
938
1114
  // The pages this message wrote or restyled (an .html written, or one using a .css written),
939
1115
  // opened in the built-in browser (chrome-devtools): a screenshot at desktop width (the whole page)
940
- // and at phone width, given to the model to check against its brief and fix. Twice per message at
941
- // most; nothing when there's no browser. A model that can't see gets them described by one of
942
- // yours that can.
1116
+ // and at phone width, given to the model to check against its brief and fix. Again whenever pages
1117
+ // changed since the last look; nothing when there's no browser. A model that can't see gets them
1118
+ // described by one of yours that can.
943
1119
  // Problems found in a built page without a browser: JavaScript that doesn't parse, and the Tailwind
944
1120
  // CDN used with @apply/@layer (it throws "Cannot apply unknown utility class" at runtime and the
945
1121
  // styling breaks). These are caught even when the browser can't be opened.
@@ -1035,13 +1211,26 @@ async function learnFromFixes(s, fixed, signal) {
1035
1211
  const near = s.memory.search(`tag:lesson ${tags.join(' ')}`).find((n) => n.body.toLowerCase().includes(error.replace(/^[^:]*:\s*/, '').toLowerCase().slice(0, 30)))
1036
1212
  if (near) continue // already learned
1037
1213
  let rule = ''
1214
+ let scope = 'global'
1038
1215
  try {
1039
- rule = (await s.client.chat({ messages: [{ role: 'user', content: prompt('agent/lesson', { error }) }] }, { signal })).content.trim().split('\n')[0].replace(/^["'\s-]+|["']+$/g, '').slice(0, 200)
1040
- } catch {}
1216
+ const was = s.client.purpose
1217
+ s.client.purpose = 'lesson'
1218
+ let reply
1219
+ try {
1220
+ reply = await s.client.chat({ messages: [{ role: 'user', content: prompt('agent/lesson', { error }) }] }, { signal })
1221
+ } finally {
1222
+ s.client.purpose = was
1223
+ }
1224
+ const said = reply.content.trim().split('\n').filter((l) => l.trim())
1225
+ rule = (said.find((l) => !/^\s*\W*scope\s*:/i.test(l)) ?? '').replace(/^\s*(?:\d+[.)]|[-*])\s*/, '').replace(/^["'\s-]+|["']+$/g, '').slice(0, 200)
1226
+ if (/scope\s*:\W*project/i.test(said.join('\n'))) scope = 'project'
1227
+ } catch (e) {
1228
+ if (e.name === 'AbortError') throw e
1229
+ }
1041
1230
  if (!rule || rule.length < 10) rule = error.replace(/^[^:]*:\s*/, '') // the model couldn't phrase it: keep the error's own wording
1042
- const name = s.memory.write({ description: rule, type: 'reference', tags: ['lesson', ...tags], content: `${rule}\n\nLearned after this was caught and fixed while building: ${error}`, scope: 'global' })
1043
- s.ui.step('learned', rule.slice(0, 90))
1044
- log('learn', `saved lesson [[${name}]] (#${tags.join(' #')}): ${rule}`)
1231
+ const name = s.memory.write({ description: rule, type: 'reference', tags: ['lesson', ...tags], content: `${rule}\n\nLearned on ${new Date().toISOString().slice(0, 10)} after this was caught and fixed while building: ${error}`, scope })
1232
+ s.ui.step('learned', `${rule.slice(0, 90)}${scope === 'project' ? ' (this project)' : ''}`)
1233
+ log('learn', `saved lesson [[${name}]] (${scope}, #${tags.join(' #')}): ${rule}`)
1045
1234
  }
1046
1235
  }
1047
1236
 
@@ -1060,14 +1249,14 @@ const SMOKE_TEST = `async () => {
1060
1249
  }
1061
1250
  const btns = [...document.querySelectorAll('button, [role=button], input[type=button], input[type=submit], a[href^="#"], a:not([href]), [onclick]')]
1062
1251
  let controls = btns.length
1063
- for (const el of btns.slice(0, 30)) { try { el.click() } catch (e) { push('click "' + ((el.textContent || el.getAttribute('aria-label') || el.value || '').trim().slice(0, 30)) + '": ' + e.message) } ; await new Promise((r) => setTimeout(r, 10)) }
1252
+ for (const el of btns) { try { el.click() } catch (e) { push('click "' + ((el.textContent || el.getAttribute('aria-label') || el.value || '').trim().slice(0, 30)) + '": ' + e.message) } ; await new Promise((r) => setTimeout(r, 10)) }
1064
1253
  for (const cb of document.querySelectorAll('input[type=checkbox], input[type=radio]')) { controls++; try { cb.click() } catch (e) { push('toggle: ' + e.message) } }
1065
1254
  await new Promise((r) => setTimeout(r, 200))
1066
1255
  return JSON.stringify({ errors: errs, controls })
1067
1256
  }`
1068
1257
 
1069
1258
  async function lookAtUi(s, signal) {
1070
- if (!s.uiTouched?.size || s.uiLooks >= 3 || s.ui.permission === 'plan') return null
1259
+ if (!s.uiTouched?.size || s.ui.permission === 'plan') return null // again whenever pages changed since the last look
1071
1260
  const touched = [...s.uiTouched]
1072
1261
  s.uiTouched.clear()
1073
1262
  const styles = touched.filter((f) => /\.css$/i.test(f)).map((f) => path.basename(f))
@@ -1079,7 +1268,7 @@ async function lookAtUi(s, signal) {
1079
1268
  } catch {}
1080
1269
  }
1081
1270
  }
1082
- const shown = [...new Set(pages)].filter((f) => fs.existsSync(path.join(s.root, f))).slice(0, 2)
1271
+ const shown = [...new Set(pages)].filter((f) => fs.existsSync(path.join(s.root, f)))
1083
1272
  if (!shown.length) return null
1084
1273
  s.uiLooks++
1085
1274
  const browser = s.mcp?.get?.('chrome-devtools')
@@ -1110,7 +1299,7 @@ async function lookAtUi(s, signal) {
1110
1299
  if (blob) {
1111
1300
  try {
1112
1301
  const r = JSON.parse(blob[0])
1113
- for (const err of r.errors.slice(0, 8)) errors.push(`${rel}: a control is broken — ${err}`)
1302
+ for (const err of r.errors) errors.push(`${rel}: a control is broken — ${err}`)
1114
1303
  log('look', `${rel}: exercised ${r.controls} control(s), ${r.errors.length} broke`)
1115
1304
  } catch (e) {
1116
1305
  log('look', `smoke parse: ${e.message}`)
@@ -1131,6 +1320,7 @@ async function lookAtUi(s, signal) {
1131
1320
  done?.()
1132
1321
  s.ui.stopSpin()
1133
1322
  }
1323
+ if (opened) s.lastCheckAt = s.seq ?? 0 // it ran in a browser: what changed was checked
1134
1324
  if (errors.length) log('look', `problems found: ${errors.join(' | ')}`)
1135
1325
  // Learn: a hard error that was there last look and is gone now was fixed — save the lesson so it
1136
1326
  // isn't made again (recalled on later tasks about the same tech). Only in the main agent.
@@ -1159,7 +1349,13 @@ async function lookAtUi(s, signal) {
1159
1349
  s.ui.spinner(`${t.model} is reviewing ${shown.join(', ')}`)
1160
1350
  try {
1161
1351
  const { client } = t === self ? { client: s.client } : await s.engineFor(t)
1162
- found = (await client.chat({ messages: [{ role: 'user', content: [{ type: 'text', text: ask }, ...shots.map((x) => ({ type: 'image_url', image_url: { url: x.url } }))] }] }, { signal })).content.trim()
1352
+ const was = client.purpose
1353
+ client.purpose = 'ui-review'
1354
+ try {
1355
+ found = (await client.chat({ messages: [{ role: 'user', content: [{ type: 'text', text: ask }, ...shots.map((x) => ({ type: 'image_url', image_url: { url: x.url } }))] }] }, { signal })).content.trim()
1356
+ } finally {
1357
+ client.purpose = was
1358
+ }
1163
1359
  if (found) break
1164
1360
  } catch (e) {
1165
1361
  if (signal?.aborted) throw e
@@ -1181,31 +1377,182 @@ async function lookAtUi(s, signal) {
1181
1377
  // The model says it's done: is it? Not while its todo list (from this message) has open items, or
1182
1378
  // while a Stop hook says otherwise. Returns what to tell it, or null. Each is asked a few times at
1183
1379
  // most (the caller counts), so a model that can't finish still ends.
1184
- async function notDone(s, signal, again) {
1380
+ // The model said it would do something but stopped without doing it ("let me rewrite…", "I'll fix…"):
1381
+ // a next action named, then no tool call. Not matched by explanations ("let me explain", "you can run").
1382
+ const PROMISED_MORE =
1383
+ /\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
1384
+
1385
+ // Is the task really done, or did the model stop early? Open todo items, or (after it did real work)
1386
+ // a reply that only promises more, get one nudge to keep going. Then any Stop hook. null = truly done.
1387
+ export async function notDone(s, signal, again, reply = '') {
1185
1388
  const open = s.todoTouched && s.ui.permission !== 'plan' ? (s.chat.todos ?? []).filter((t) => t.status !== 'completed') : [] // plan mode: they wait for the approval
1186
1389
  if (open.length) {
1187
1390
  log('task', `stopped with ${open.length} open todo item(s); reminding`)
1188
1391
  return prompt('agent/todo-unfinished', { items: open.map((t) => `- ${t.content}`).join('\n') })
1189
1392
  }
1393
+ // changed files and hasn't run anything since: not proven to work
1394
+ const changed = [...(s.changed ?? [])]
1395
+ if (changed.length && s.lastCheckAt < s.lastChangeAt && !changed.every((f) => DOC_FILE.test(f)) && s.ui.permission !== 'plan') {
1396
+ log('task', `finished with changes not checked since (${changed.join(', ')}); asking for a check`)
1397
+ return prompt('agent/unchecked', { files: changed.join(', ') })
1398
+ }
1399
+ // says it made files that aren't there
1400
+ const missing = missingFiles(s.root, reply)
1401
+ if (missing.length) {
1402
+ log('task', `the answer names files that don't exist: ${missing.join(', ')}`)
1403
+ return prompt('agent/missing-files', { files: missing.join(', ') })
1404
+ }
1405
+ if (s.acted && reply && PROMISED_MORE.test(reply)) {
1406
+ log('task', 'reply names a next step but no tool call followed; nudging to finish')
1407
+ return prompt('agent/stopped-early')
1408
+ }
1190
1409
  const hook = await runHooks(s, 'Stop', { stop_hook_active: again }, signal)
1191
1410
  return hook.block ? prompt('agent/hook-stop', { reason: hook.block }) : null
1192
1411
  }
1193
1412
 
1413
+ // Files the final answer says were made, that aren't in the project: a path in backticks, or one
1414
+ // with a folder, with a source/config/doc extension, while the answer says it created or wrote
1415
+ // something. A name that's anywhere in the project (by its file name) counts as there.
1416
+ const FILE_EXT = 'html?|css|scss|m?js|cjs|tsx?|jsx|json|md|py|go|rs|java|kts?|swift|rb|php|c|h|cpp|cs|sh|ya?ml|toml|xml|gradle|vue|svelte|sql|txt|env'
1417
+ export function missingFiles(root, reply) {
1418
+ const text = String(reply ?? '')
1419
+ if (!/\b(created?|wrote|written|added|saved|generated|made|new file)\b/i.test(text)) return []
1420
+ const named = new Set()
1421
+ for (const m of text.matchAll(new RegExp(`\`([^\`\\s]+\\.(?:${FILE_EXT}))\``, 'gi'))) named.add(m[1])
1422
+ for (const m of text.matchAll(new RegExp(`(?:^|[\\s(])((?:[\\w.-]+/)+[\\w.-]+\\.(?:${FILE_EXT}))(?=[\\s),.:;]|$)`, 'gim'))) named.add(m[1])
1423
+ const out = []
1424
+ let names = null
1425
+ for (const f of named) {
1426
+ if (/^(https?:|\/\/|~|\$)/.test(f) || path.isAbsolute(f)) continue
1427
+ if (fs.existsSync(path.join(root, f))) continue
1428
+ names ??= new Set(listFiles(root).map((x) => path.basename(x)))
1429
+ if (names.has(path.basename(f))) continue
1430
+ out.push(f)
1431
+ }
1432
+ return out
1433
+ }
1434
+
1435
+ // Every folder in the project (relative paths), the ignored ones (.git, node_modules…) and
1436
+ // HeartCode's own left out: to tell the folders a task made.
1437
+ function foldersOf(root) {
1438
+ const out = new Set()
1439
+ const walk = (rel, depth) => {
1440
+ if (out.size > 20_000 || depth > 12) return
1441
+ let entries = []
1442
+ try {
1443
+ entries = fs.readdirSync(path.join(root, rel), { withFileTypes: true })
1444
+ } catch {
1445
+ return
1446
+ }
1447
+ for (const e of entries) {
1448
+ if (!e.isDirectory() || IGNORED_DIRS.has(e.name) || e.name === '.heartcode') continue
1449
+ const r = rel ? `${rel}/${e.name}` : e.name
1450
+ out.add(r)
1451
+ walk(r, depth + 1)
1452
+ }
1453
+ }
1454
+ walk('', 0)
1455
+ return out
1456
+ }
1457
+ const IGNORED_DIRS = new Set(['.git', 'node_modules', 'dist', 'build', '.next', 'coverage', '.venv', 'venv', '__pycache__', 'target', '.cache', '.gradle', '.idea'])
1458
+ const isEmptyDir = (abs) => {
1459
+ try {
1460
+ return fs.readdirSync(abs).filter((f) => f !== '.DS_Store').length === 0
1461
+ } catch {
1462
+ return false
1463
+ }
1464
+ }
1465
+
1466
+ // A second look before it's called done, in a request of its own: another of your models when
1467
+ // there is one (fresh eyes), else this one, with nothing but the user's request, the plan, the
1468
+ // answer, the changes and what was run since. It answers YES (done right) or NO with what's wrong;
1469
+ // a NO goes back to the model to fix. Asked again only once files changed since its last look.
1470
+ // Returns what to tell the model, or null.
1471
+ export async function review(s, task, answer, signal) {
1472
+ if (s.isSub || !s.changed?.size || s.lastChangeAt <= s.reviewedAt || s.ui.permission === 'plan') return null
1473
+ s.reviewedAt = s.lastChangeAt
1474
+ const turn = s.chat.turns.at(-1)
1475
+ const diffs = []
1476
+ let room = 16_000
1477
+ for (const [rel, before] of Object.entries(turn?.files ?? {})) {
1478
+ let now = null
1479
+ try {
1480
+ now = fs.readFileSync(path.join(s.root, rel), 'utf8')
1481
+ } catch {}
1482
+ if (now === before) continue
1483
+ const text = before === null ? `${rel} (new file):\n${now ?? ''}` : now === null ? `${rel}: deleted` : renderDiff(diffLines(before, now), rel, false, 3, 400)
1484
+ const piece = clip(text, Math.min(5000, room))
1485
+ room -= piece.length
1486
+ diffs.push(piece)
1487
+ if (room <= 500) {
1488
+ diffs.push('(more changes not shown)')
1489
+ break
1490
+ }
1491
+ }
1492
+ if (!diffs.length) return null
1493
+ const plan = (s.chat.todos ?? []).map((t) => `- [${t.status === 'completed' ? 'x' : ' '}] ${t.content}`).join('\n')
1494
+ const ran = (s.ran ?? []).slice(-15).map((r) => `- ${clip(r.command.replace(/\s+/g, ' '), 160)} → ${r.result}`).join('\n')
1495
+ const ask = prompt('agent/review', { request: requestsOf(s.chat, 1200), plan: plan || '(none)', answer: clip(String(answer ?? ''), 3000), changes: diffs.join('\n\n'), ran: ran || '(nothing)' })
1496
+ const self = { provider: s.client.provider, model: s.client.model, self: true }
1497
+ const fails = (t) => s.failures?.[`${t.provider} ${t.model}`] ?? 0
1498
+ const others = (s.team?.() ?? []).filter((t) => t.tools !== false && !(t.provider === self.provider && t.model === self.model)).sort((a, b) => fails(a) - fails(b))
1499
+ for (const t of [...others.slice(0, 2), self]) {
1500
+ s.ui.spinner(`${t.model} is reviewing the work`)
1501
+ try {
1502
+ const { client } = t.self ? { client: s.client } : await s.engineFor(t)
1503
+ if (!t.self) client.retryIf = (e, attempt) => attempt < 2
1504
+ const was = client.purpose
1505
+ client.purpose = 'review'
1506
+ let said
1507
+ try {
1508
+ said = (await client.chat({ messages: [{ role: 'user', content: ask }] }, { signal })).content.trim()
1509
+ } finally {
1510
+ client.purpose = was
1511
+ }
1512
+ s.ui.stopSpin()
1513
+ log('review', `${t.model}: ${said}`)
1514
+ if (/^\W*yes\b/i.test(said)) {
1515
+ s.ui.step('review', `${t.model}: looks right`)
1516
+ return null
1517
+ }
1518
+ if (/^\W*no\b/i.test(said)) {
1519
+ const issues = said.replace(/^\W*no\b[\s.:—-]*/i, '').trim()
1520
+ s.ui.step('review', `${t.model}: ${clip(issues.split('\n').find((l) => l.trim()) ?? 'problems found', 90)}`)
1521
+ return prompt('agent/review-failed', { model: t.model, issues: issues || '(no details given)' })
1522
+ }
1523
+ log('review', `${t.model} didn't answer YES or NO; trying another`)
1524
+ } catch (e) {
1525
+ if (e.name === 'AbortError' || signal?.aborted) throw e
1526
+ log('review', `${t.model} couldn't review: ${e.message}`)
1527
+ }
1528
+ }
1529
+ s.ui.stopSpin()
1530
+ return null
1531
+ }
1532
+
1194
1533
  // A helper agent's view of the screen: its steps are labelled, and its replies (which go to the
1195
1534
  // main agent) aren't shown as answers. Everything else is the main UI's.
1196
1535
  // Its thinking is shown whole when its reply is in (helpers working at once don't mix), named.
1197
1536
  // Questions to the user (confirm, pick, ask) wait their turn: helpers working at once ask one by one.
1198
1537
  const asking = new WeakMap() // ui → the question being asked
1199
1538
  function helperUI(ui, label) {
1539
+ // What the helper says is shown in full under its name. Held until its reply ends, then printed at
1540
+ // once: helpers run side by side, and streamed text from two would interleave.
1200
1541
  const response = () => {
1201
1542
  const t0 = Date.now()
1202
1543
  let thought = ''
1544
+ let said = ''
1203
1545
  return {
1204
1546
  think: (t) => (thought += t ?? ''),
1205
- text() {},
1547
+ text: (t) => (said += t ?? ''),
1206
1548
  end() {
1207
- if (!thought.trim()) return
1208
- ui.print(c.faint(c.italic(` ✻ ${label} thought for ${duration(Date.now() - t0)}`)) + (ui.showThinking ? `\n${c.think(c.italic(thought.trim().replace(/^/gm, ' ')))}` : ''))
1549
+ 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, ' ')))}` : ''))
1550
+ if (!said.trim()) return
1551
+ ui.print(` ${c.bright(c.bold('●'))} ${c.bold(label)}`)
1552
+ let block = new Block((x) => ui.write(x), { marker: ' ', style: c.text })
1553
+ if (color) block = new Markdown(block, c.text)
1554
+ block.push(said.trim())
1555
+ block.end()
1209
1556
  },
1210
1557
  }
1211
1558
  }
@@ -1231,26 +1578,48 @@ export { allowed }
1231
1578
  const shortened = new WeakSet() // kept outside the messages: providers reject unknown message fields
1232
1579
 
1233
1580
  // How long a tool result may be in the conversation: a tenth of the window, 4k to 100k characters
1234
- // (Claude Code allows about 25k tokens). A longer one: its start, and the whole of it saved to a
1235
- // file the model can read in parts (read_file, search), as Claude Code does.
1236
- export function fitResult(s, name, out) {
1581
+ // (Claude Code allows about 25k tokens). A longer one: its start, and the whole of it in a file the
1582
+ // model can read in parts (read_file, search), as Claude Code does. file: where it's saved already.
1583
+ export function fitResult(s, name, out, file) {
1237
1584
  const max = Math.max(4000, Math.min(100_000, Math.floor((s.strat.context * 3.5 * 0.1) / (s.strat.ratio ?? 1))))
1238
1585
  if (out.length <= max) return out
1239
- const file = saveOutput(s.chat?.id, name, out)
1586
+ file ??= saveOutput(s.chat?.id, name, out)
1240
1587
  log('tool', `${name}: ${out.length} characters, ${max} shown${file ? `; all of it in ${file}` : ''}`)
1241
1588
  return `${out.slice(0, max)}\n…\n${prompt('agent/output-cut', { shown: max, total: out.length, file })}`
1242
1589
  }
1243
1590
 
1244
- // A long task's conversation fills up with old tool output (a browser's page snapshots, each out of
1245
- // date by the next). Past 12 long results, all but the newest 4 are cut to their start, each saved
1246
- // to a file first. All at once, so a provider's prompt cache (the conversation's unchanged start)
1247
- // is broken rarely, not at every step.
1248
- export function trimOldResults(s, keep = 4, most = 12) {
1249
- const long = s.messages.filter((m) => m.role === 'tool' && typeof m.content === 'string' && m.content.length > 2000 && !shortened.has(m) && !/^\[older output/.test(m.content))
1591
+ // Results longer than this are saved to a file when they come (so they can leave the conversation later).
1592
+ const SAVE_AT = 1500
1593
+ // What a tool call was, in a few words: "web_fetch https://…", "run_command npm test".
1594
+ function callOf(messages, id) {
1595
+ for (const m of messages) {
1596
+ const t = m.tool_calls?.find((x) => x.id === id)
1597
+ if (!t) continue
1598
+ let a = {}
1599
+ try {
1600
+ a = JSON.parse(t.function.arguments || '{}')
1601
+ } catch {}
1602
+ const what = a.server ? `${a.server} · ${a.tool ?? ''}` : (a.path ?? a.url ?? a.command ?? a.query ?? a.description ?? '')
1603
+ return `${t.function.name}${what ? ` ${clip(String(what).replace(/\s+/g, ' '), 120)}` : ''}`
1604
+ }
1605
+ return 'a tool'
1606
+ }
1607
+
1608
+ // The conversation carries only the newest results whole: the model decides what else it needs and
1609
+ // reads it from the files (every sizable result is saved when it comes; web pages are in the
1610
+ // project's research). Once there are more than `most` long ones, all but the newest `keep` become a
1611
+ // pointer: what the call was, how long, where it's saved, and its first lines. All at once, so a
1612
+ // provider's prompt cache (the conversation's unchanged start) is broken rarely, not every step.
1613
+ // An older conversation's results (no file yet) are saved now, before they're cut.
1614
+ export function trimOldResults(s, keep = 4, most = 8) {
1615
+ 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))
1250
1616
  if (long.length <= most) return
1251
1617
  for (const m of long.slice(0, -keep)) {
1252
- const file = saveOutput(s.chat?.id, 'older', m.content)
1253
- m.content = `${prompt('agent/output-old', { total: m.content.length, file })}\n${m.content.slice(0, 600)}\n…`
1618
+ const call = callOf(s.messages, m.tool_call_id)
1619
+ const read = /^read_file /.test(call) ? call.slice('read_file '.length) : '' // a project file: read it again
1620
+ const file = read || s.chat.outputs?.[m.tool_call_id] || saveOutput(s.chat?.id, 'older', m.content)
1621
+ if (file && !read) (s.chat.outputs ??= {})[m.tool_call_id] = file
1622
+ m.content = `${prompt('agent/output-old', { call, total: m.content.length, file })}\n${m.content.slice(0, 300)}\n…`
1254
1623
  shortened.add(m)
1255
1624
  }
1256
1625
  log('tool', `older tool output cut: ${long.length - keep} results`)