heartcode 0.1.63 → 0.1.95

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,7 +7,8 @@ import { skillFiles, readSkillFile } from './skills.js'
7
7
  import path from 'node:path'
8
8
  import { fileURLToPath } from 'node:url'
9
9
  import { est, estMessages, Client, tokensOf, COMPACT_SHARE, family } from './client.js'
10
- import { scoreOf } from './rankings.js'
10
+ import { scoreOf, rankIn, loadRankings } from './rankings.js'
11
+ import { record, byRecord, recordOf, unreliable, records } from './record.js'
11
12
  import { pageCheck } from './check.js'
12
13
  import { runGuided } from './guided.js'
13
14
  import { markUsed, removeResearch, findResearch } from './research.js'
@@ -16,8 +17,9 @@ import { serversNote } from './lsp.js'
16
17
  import { newlyEnded, jobLine } from './background.js'
17
18
  import { loadHooks, runHooks } from './hooks.js'
18
19
  import { takeConfigErrors, HELPER_JOBS } from './config.js'
19
- import { c, duration, Block, Markdown, color, diffLines, renderDiff } from './ui.js'
20
+ import { c, Block, Markdown, color, diffLines, renderDiff, STEP_NAMES } from './ui.js'
20
21
  import { fetch } from './http.js' // not the built-in one: see http.js
22
+ import { detect, guideText, guideVars } from './guides.js'
21
23
 
22
24
  // Images for a helper (the agent tool's "images"), as data: URLs: image URLs (fetched), data: URLs,
23
25
  // or files: in the project, saved screenshots (OUTPUTS), or a path the user gave in a message.
@@ -241,6 +243,7 @@ export class Session {
241
243
  // do it, until one does. id: the agent tool call's; the helper's steps go to onEvent (headless,
242
244
  // ACP) as that call's.
243
245
  async subagent(args, signal, id) {
246
+ if (String(args.model ?? '').trim().toLowerCase() === 'list') return teamLines(this).join('\n') || 'No other models.' // all of them (the system prompt has the first few)
244
247
  const task = String(args.prompt ?? args.task ?? '').trim()
245
248
  if (!task) return 'error: give the helper its job in "prompt"'
246
249
  // an image named in the job but not given in "images" (a screenshot's path): given, so a model
@@ -260,19 +263,22 @@ export class Session {
260
263
  if (!first) return `error: no model "${String(args.model).trim()}". ${helpers ? 'Your helpers' : 'Yours'}: ${all.map(name).join(', ')}`
261
264
  if (!order.length) return 'error: none of your models can see images'
262
265
  const failed = []
266
+ let carry = '' // what a helper that failed had done: the next one is told, not starting over
263
267
  for (const [i, t] of order.entries()) {
264
268
  if (args.part) (args.part.by = t.model), (args.part.byProvider = t.provider ?? this.client.provider), sendTodos(this) // a part of the plan: the model doing it, shown beside it
265
269
  let answer = ''
266
270
  try {
267
- answer = (await this.#helper(t, task, images, args.description, id, signal, args.ownFiles, args.root))?.trim()
271
+ answer = (await this.#helper(t, carry ? `${task}\n\n${carry}` : task, images, args.description, id, signal, args.ownFiles, args.root))?.trim()
268
272
  } catch (e) {
269
273
  if (e.name === 'AbortError' || signal?.aborted) throw e
270
274
  if (e.maxTurns) return `error: the helper ${e.message}` // the caller's limit: every other model would stop there too
271
275
  failed.push(`${t.model}: ${clip(e.message, 150)}`)
276
+ if (e.progress) carry = prompt('agent/helper-progress', { model: t.model, why: clip(e.message, 150), done: e.progress })
272
277
  }
278
+ record({ provider: t.provider ?? this.client.provider, model: t.model ?? this.client.model }, answer ? 'helped' : 'helper-failed') // its track record (record.js)
273
279
  if (answer) return t === first ? answer : `(Answered by ${name(t)}, not ${name(first)}${failed.length ? `: ${failed.join('; ')}` : ''})\n\n${answer}`
274
280
  if (failed.length < i + 1) failed.push(`${t.model}: no reply`)
275
- 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}`)
281
+ if (order[i + 1]) this.ui.handover(order[i + 1].model, `${t.model} couldn't do it (${failed.at(-1).slice(t.model.length + 2)})`)
276
282
  }
277
283
  return `error: none of your models that can do it managed: ${failed.join('; ')}`
278
284
  }
@@ -290,6 +296,17 @@ export class Session {
290
296
  // only one model available (a pinned model, or you have just one): helpers use it, whatever was asked
291
297
  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}`)))
292
298
  const able = (t) => !withImages || t.images
299
+ // a kind of job and no model named: the helpers good at it first. Picked for you (auto): the
300
+ // fastest of them in its test, and if it fails the best-ranked of the rest (a stronger one, by
301
+ // the rankings and the track record); picked by you: best-ranked first
302
+ const fit = !want && helpers && HELPER_JOBS[args.job] ? helpers.filter((t) => t.jobs.includes(args.job) && able(t)) : []
303
+ if (fit.length) {
304
+ const auto = fit[0].auto
305
+ const fast = auto ? [...fit].sort((a, b) => (a.ms ?? Infinity) - (b.ms ?? Infinity))[0] : fit[0]
306
+ const rest = all.filter((t) => t !== fast && able(t))
307
+ const strong = auto ? rest.map((t) => ({ t, score: scoreOf(t.model) })).sort(byRecord).map((x) => x.t) : [...fit.filter((t) => t !== fast), ...rest.filter((t) => !fit.includes(t))]
308
+ return { order: [fast, ...strong], first: fast, all, helpers }
309
+ }
293
310
  let order = first ? [first, ...all.filter((t) => t !== first)].filter(able) : []
294
311
  if (first && !order.length && helpers) order = [self, ...team].filter(able) // no helper sees images: any of yours that does
295
312
  return { order, first, all, helpers }
@@ -312,7 +329,7 @@ export class Session {
312
329
  const helper = new Session({ client, profile, strat, root, ui: helperUI(this.ui, label, client.model), chat: newChat(root) })
313
330
  helper.chat.turns = this.chat.turns.slice(-1) // this message's turn: its file changes go there (track), the changes tool reads them
314
331
  if (ownFiles?.length) helper.ownFiles = ownFiles.map((f) => path.resolve(root, f)) // a part of the plan: changes only its own files
315
- 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 })
332
+ 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, ownSystem: this.ownSystem, fileCache: this.fileCache, noFormat: this.noFormat, noLsp: this.noLsp })
316
333
  helper.track = own ? (rel, before) => this.track(rel, before) : () => {}
317
334
  // a helper that can't see, given screenshots by a tool (a browser): one of your models that can
318
335
  // describes them for its job (it has no helpers of its own to ask)
@@ -326,6 +343,9 @@ export class Session {
326
343
  const answer = await (strat.actions === 'tools' ? runNative : runGuided)(helper, task, images, signal)
327
344
  log('agent', `helper "${label}" done`, answer)
328
345
  return answer
346
+ } catch (e) {
347
+ e.progress ??= progressOf(helper) // what it did before it failed: the next helper goes on from there
348
+ throw e
329
349
  } finally {
330
350
  if (this.ui.helpers?.delete(label)) this.ui.render?.()
331
351
  this.#release(helper)
@@ -384,7 +404,7 @@ export class Session {
384
404
  }
385
405
  if (said) {
386
406
  by = seer.model
387
- this.ui.step('image', `${seer.model} described image ${i + 1}`)
407
+ this.ui.step('image', `${seer.model} described image ${i + 1}`, '', { note: true })
388
408
  break
389
409
  }
390
410
  }
@@ -463,7 +483,7 @@ export class Session {
463
483
  args = JSON.parse(call.function.arguments || '{}')
464
484
  } catch {}
465
485
  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}`)
466
- 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)' : ''}`)
486
+ 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)' : ''}`, '', { note: true })
467
487
  messages.push({ role: 'tool', tool_call_id: call.id, content: out })
468
488
  }
469
489
  }
@@ -544,7 +564,7 @@ export class Session {
544
564
  } else fs.rmSync(path.join(this.root, rel), { force: true })
545
565
  scratch.delete(rel)
546
566
  removed.push(rel)
547
- this.ui.step('cleanup', `removed ${rel}`)
567
+ this.ui.step('cleanup', `removed ${rel}`, '', { note: true })
548
568
  return `Deleted ${rel}.`
549
569
  }
550
570
  }
@@ -553,7 +573,7 @@ export class Session {
553
573
  const { client } = this.engineFor ? await this.engineFor(own) : { client: this.client }
554
574
  const said = await this.memoryTask(prompt('agent/wrapup'), request, signal, { defs, run, client, purpose: 'wrapup' })
555
575
  log('wrapup', `${said} | pages kept ${kept.length}, deleted ${dropped.length}; files removed ${removed.length}`)
556
- if (kept.length || dropped.length) this.ui.step('research', `kept ${kept.length} page${kept.length === 1 ? '' : 's'}${dropped.length ? `, deleted ${dropped.length} as junk` : ''}`)
576
+ if (kept.length || dropped.length) this.ui.step('research', `kept ${kept.length} page${kept.length === 1 ? '' : 's'}${dropped.length ? `, deleted ${dropped.length} as junk` : ''}`, '', { note: true })
557
577
  } catch (e) {
558
578
  if (e.name === 'AbortError' || signal?.aborted) throw e
559
579
  log('wrapup', `failed: ${e.message}`)
@@ -606,9 +626,10 @@ const alwaysSkill = (k) => {
606
626
  }
607
627
 
608
628
  const SYSTEM = (s) => {
629
+ if (s.ownSystem) return [s.ownSystem, s.appendSystem].filter(Boolean).join('\n\n') // --system-prompt: only the program's
609
630
  const instructions = userInstructions(s.root)
610
631
  return [
611
- prompt('agent/system', { root: s.root, env: envLine(), today: new Date().toISOString().slice(0, 10), rootList: rootList(s.root), servers: serversNote(s.root), files: '', more: '', caller: Boolean(s.appendSystem), see: Boolean(s.strat.vision), noUser: Boolean(s.ui.noUser || s.isSub), memory: Boolean(s.memory) && !s.isSub }), // models that can see often say they can't: told they can
632
+ prompt('agent/system', { root: s.root, env: envLine(), today: new Date().toISOString().slice(0, 10), rootList: rootList(s.root), servers: serversNote(s.root), files: '', more: '', caller: Boolean(s.appendSystem), see: Boolean(s.strat.vision), noUser: Boolean(s.ui.noUser || s.isSub), memory: Boolean(s.memory) && !s.isSub, doneFirst: !s.isSub && !s.ui.noUser && s.ui.permission !== 'plan' ? 'call done, then ' : '' }), // the done tool's there (askDone) // models that can see often say they can't: told they can
612
633
  instructions && prompt('agent/instructions', { instructions }),
613
634
  ...[...(s.skills?.values() ?? [])].filter((k) => k.use === 'always').map(alwaysSkill), // skills that say how to work (use: always), with the files they bring
614
635
  !s.isSub && teamPrompt(s),
@@ -619,19 +640,56 @@ const SYSTEM = (s) => {
619
640
  .join('\n\n')
620
641
  }
621
642
 
622
- // The helpers you ticked on Your models (jobs: what for), in your order; null when none are.
643
+ // The helpers you ticked on Your models (jobs: what for), best-ranked first; null when none are.
623
644
  export const helpersOf = (team) => (team.some((t) => t.jobs) ? team.filter((t) => t.jobs) : null)
624
645
 
625
646
  // Your other models and what each can do, for the agent tool's model (only when there are any): a
626
647
  // short line each, in your list's order. With helpers ticked: only them, and what each is good at.
648
+ // What a helper did before it failed, for the one that takes its job over: its calls and what came
649
+ // back (newest kept when it's long), and the files it changed.
650
+ const GUIDE_TEXT = /\n\n(?:How to [^\n]*\(once; keep it in mind\)|Parts on other models \(once)[\s\S]*$/
651
+ function progressOf(h) {
652
+ const out = []
653
+ for (const m of h.messages ?? []) {
654
+ if (m.role === 'assistant' && m.content && typeof m.content === 'string') out.push(`said: ${clip(m.content.replace(/\s+/g, ' '), 300)}`)
655
+ if (m.role === 'assistant') for (const c of m.tool_calls ?? []) out.push(`- ${c.function.name} ${clip(c.function.arguments ?? '', 200)}`)
656
+ if (m.role === 'tool') out.push(` → ${clip(String(m.content ?? '').replace(GUIDE_TEXT, '').replace(/\s+/g, ' '), 300)}`) // without the guidance that came with it
657
+ }
658
+ let text = ''
659
+ for (let i = out.length - 1; i >= 0 && text.length < 8000; i--) text = `${out[i]}\n${text}`
660
+ const files = [...(h.changed ?? [])]
661
+ return [text.trim(), files.length && `Files it changed: ${files.join(', ')}`].filter(Boolean).join('\n')
662
+ }
663
+
664
+ // Only the first few are in the system prompt (a list of hundreds would fill it); the agent tool
665
+ // with model "list" gives them all (teamLines).
666
+ const TEAM_SHOWN = 5
667
+ // Each of your other models, for the one answering to choose from: what it can do, its places in the
668
+ // public rankings (LMArena), how fast it answered its test, its price, and how it did here (its track record)
669
+ const RANKED = { 'text:coding': 'coding', 'webdev:webdev': 'web apps', 'agent:overall': 'long tasks with tools', 'text:hard_prompts': 'hard prompts', 'vision:overall': 'images' }
670
+ const teamLines = (s) => {
671
+ const team = s.team?.() ?? []
672
+ const data = loadRankings()
673
+ const can = (t) => [t.tools === false && 'no tool calls', t.images && 'images', t.thinking && 'thinking', t.context && `${kTokens(t.context)} context`].filter(Boolean)
674
+ const ranks = (t) => {
675
+ if (!data) return null
676
+ const at = Object.entries(RANKED).flatMap(([k, what]) => ((r) => (r ? [`${what} #${r.rank} of ${r.of}`] : []))(rankIn(t.model, k, data)))
677
+ return at.length ? `ranked ${at.join(', ')}` : 'not in the rankings'
678
+ }
679
+ const speed = (t) => (t.ms != null ? `answered its test in ${(t.ms / 1000).toFixed(1)}s` : 'not tested')
680
+ const price = (t) => (!t.price || (t.price.input == null && t.price.output == null) ? 'price unknown' : !t.price.input && !t.price.output ? 'free' : `$${t.price.input ?? '?'} in / $${t.price.output ?? '?'} out per M tokens`)
681
+ const done = (t) => {
682
+ const r = records.on && recordOf(t)
683
+ return r && r.good + r.bad >= 1 ? `here: ${Math.round(r.good)} done, ${Math.round(r.bad)} failed${unreliable(t) ? ' (fails most of its work)' : ''}` : null
684
+ }
685
+ const good = (t) => (t.jobs?.length ? `good at: ${t.jobs.map((j) => HELPER_JOBS[j]?.[1]).filter(Boolean).join('; ')}` : null)
686
+ return (helpersOf(team) ?? team).map((t) => `- ${t.provider} ${t.model}: ${[can(t).join(', '), ranks(t), speed(t), price(t), done(t), good(t)].filter(Boolean).join(' · ')}`)
687
+ }
627
688
  const teamPrompt = (s) => {
628
689
  const team = s.team?.() ?? []
629
690
  if (!team.length) return ''
630
- const helpers = helpersOf(team)
631
- const can = (t) => [t.tools === false && 'no tool calls', t.images && 'images', t.thinking && 'thinking', t.context && `${kTokens(t.context)} context`].filter(Boolean)
632
- const good = (t) => (t.jobs?.length ? ` · good at: ${t.jobs.map((j) => HELPER_JOBS[j]?.[1]).filter(Boolean).join('; ')}` : '')
633
- const line = (t) => `- ${t.provider} ${t.model}${can(t).length ? `: ${can(t).join(', ')}` : ''}${good(t)}`
634
- return prompt('agent/team', { helpers: Boolean(helpers), models: (helpers ?? team).map(line).join('\n'), you: [s.strat.vision ? 'images' : 'no images', s.strat.thinking && 'thinking'].filter(Boolean).join(', ') })
691
+ const lines = teamLines(s)
692
+ return prompt('agent/team', { helpers: Boolean(helpersOf(team)), models: [...lines.slice(0, TEAM_SHOWN), ...(lines.length > TEAM_SHOWN ? [`…and ${lines.length - TEAM_SHOWN} more: the agent tool with model "list" lists them all`] : [])].join('\n'), you: [s.strat.vision ? 'images' : 'no images', s.strat.thinking && 'thinking'].filter(Boolean).join(', ') })
635
693
  }
636
694
 
637
695
  const sizeOf = (m) =>
@@ -881,10 +939,15 @@ async function runNative(s, task, images, signal) {
881
939
  const said = ui.permission === 'plan' && !s.isSub ? `${text}\n\n${prompt('agent/plan-mode')}` : text
882
940
  const content = images.length ? [{ type: 'text', text: said }, ...images.map((url) => ({ type: 'image_url', image_url: { url } }))] : said
883
941
  s.messages.push({ role: 'user', content })
884
- attachNamed(s, task) // files the message names: as if already read (saves a round trip each)
942
+ s.domainGuides = detect(s.root, task) // the guides for this kind of work, added once it starts on it (guidesFor)
943
+ if (!s.client.cli) attachNamed(s, task) // files the message names: as if already read (saves a round trip each); a coding CLI reads them itself
885
944
  // the tools: built again each step (the model answering may change; client.js leaves them out for
886
945
  // one that can't call tools; plan mode may be left mid-message)
887
- const toolList = () => [...TOOL_DEFS, ...extraTools(s)].filter((f) => allowed(s, f.name) && !(ui.permission === 'plan' && PLAN_HIDDEN.has(f.name)) && !(f.name === 'ask_user' && (ui.noUser || s.isSub))).map((f) => ({ type: 'function', function: f })) // ask_user: not headless, nor a helper (it reports to the main agent, which asks)
946
+ const toolList = () => [...TOOL_DEFS, ...extraTools(s)].filter((f) => allowed(s, f.name) && !(ui.permission === 'plan' && PLAN_HIDDEN.has(f.name)) && !(f.name === 'ask_user' && (ui.noUser || s.isSub)) && !(f.name === 'done' && !askDone())).map((f) => ({ type: 'function', function: f })) // ask_user: not headless, nor a helper (it reports to the main agent, which asks)
947
+ // done (the model says it's finished): the interactive CLI's main conversation only, not -p (its caller
948
+ // checks), a helper (it reports), plan mode (the plan's approval ends it) or another program's system prompt
949
+ const askDone = () => !s.isSub && !ui.noUser && !s.ownSystem && ui.permission !== 'plan'
950
+ s.saidDone = null // called done this message (tools.js): { checked, waiting }
888
951
  const guard = newGuard() // calls made again with nothing changed: the earlier result instead
889
952
  let lastCall = '' // the last call (tool and arguments), and how many times in a row
890
953
  let inRow = 0
@@ -907,7 +970,7 @@ async function runNative(s, task, images, signal) {
907
970
  s.split = undefined // the user's answer this message: 'several' agents at once, or 'one' (tools.js)
908
971
  s.lookedUp = s.researchAsked = false // searched or read the web this message / asked whether the plan needs it
909
972
  // what changed and when it was last checked, this message: a change not run/tested since isn't done
910
- Object.assign(s, { changed: new Set(), seq: 0, lastChangeAt: -1, lastCheckAt: -1, reviewedAt: -1, checksSince: 0, spots: new Map(), stuckReports: 0, stuckSelf: null, stuckHandovers: 0, troubles: [], unstuck: [], reviewedRan: 0, lastReview: null, gaveUp: new Set(), toldLast: false, unstuckLearned: false, provedAt: -1, proofFails: 0, shrunkTold: false })
973
+ Object.assign(s, { systemKey: null, changed: new Set(), seq: 0, lastChangeAt: -1, lastCheckAt: -1, reviewedAt: -1, checksSince: 0, spots: new Map(), stuckReports: 0, stuckSelf: null, stuckHandovers: 0, troubles: [], unstuck: [], reviewedRan: 0, lastReview: null, gaveUp: new Set(), toldLast: false, unstuckLearned: false, provedAt: -1, proofFails: 0, shrunkTold: false, proofShots: [] })
911
974
 
912
975
  let empty = 0 // replies in a row with neither text nor tool calls
913
976
  let lastFinal = '' // the last answer it gave (a next one the same, after being told it isn't done: it's stuck)
@@ -920,9 +983,10 @@ async function runNative(s, task, images, signal) {
920
983
  // the job goes to your next model.
921
984
  const handOver = (why) => {
922
985
  const was = client.model
986
+ record(client, 'handover') // its track record (record.js)
923
987
  s.gaveUp.add(`${client.provider}/${was}`) // not gone back to this message, nor asked for a second opinion
924
988
  if (strongest(s, client, `${was} ${why}`) || client.moveOn?.(`${was} ${why}`, s.gaveUp)) {
925
- ui.warn(`${was} ${why}; handing over to ${client.model}`)
989
+ ui.handover(client.model, `${was} ${why}`)
926
990
  // the next model sees the whole conversation: told it's taking over, and not to repeat what didn't work
927
991
  s.messages.push({ role: 'user', content: prompt('agent/taken-over', { was, why, plan: (s.chat.todos ?? []).filter((t) => t.status !== 'completed').map((t) => `- ${t.content}${t.why ? ` (stuck: ${t.why})` : ''}`).join('\n') }) })
928
992
  s.stuckReports = 0
@@ -938,7 +1002,7 @@ async function runNative(s, task, images, signal) {
938
1002
  let refitted = false // this step's conversation was just compacted for a smaller model the list moved on to
939
1003
  // No step limit (helpers too): a long fix takes many steps, and Esc stops it. A caller can set one (--max-turns).
940
1004
  for (let step = 0; ; step++) {
941
- if (step && !s.isSub) s.onTurn?.() // saved after every step: a quit, crash or kill mid-task loses nothing done so far
1005
+ if (step && !s.isSub && Date.now() - (s.savedAt ?? 0) > 5000) (s.savedAt = Date.now()), s.onTurn?.() // saved as it goes (every few seconds: a long chat is a big file): a quit, crash or kill mid-task loses little
942
1006
  const tools = toolList()
943
1007
  s.lastTools = tools // what the requests carry: the findings note before compacting sends the same (compact)
944
1008
  if (s.maxTurns && step >= s.maxTurns) {
@@ -958,9 +1022,16 @@ async function runNative(s, task, images, signal) {
958
1022
  },
959
1023
  )
960
1024
  }
961
- // the model answering can change mid-message (your model list): the system prompt follows it
962
- const now = SYSTEM(s)
963
- if (s.messages[0]?.content !== now && s.messages[0]?.role === 'system') s.messages[0] = { ...s.messages[0], content: now }
1025
+ // the system prompt: built once a message, and again when another model answers (your model list)
1026
+ // or the prompts changed. Not every step: a change mid-task (a new file at the root, a model's
1027
+ // track record) makes the provider read the whole conversation again (its cache is of the start)
1028
+ const sysKey = `${client.provider}/${client.model}`
1029
+ if (s.systemKey !== sysKey || s.refreshSystem) {
1030
+ s.systemKey = sysKey
1031
+ s.refreshSystem = false
1032
+ const now = SYSTEM(s)
1033
+ if (s.messages[0]?.content !== now && s.messages[0]?.role === 'system') s.messages[0] = { ...s.messages[0], content: now }
1034
+ }
964
1035
  pairTools(s.messages)
965
1036
  ui.spinner('thinking')
966
1037
  // named by the model that answers: opened at its first word (a failed one moves the list on
@@ -969,7 +1040,8 @@ async function runNative(s, task, images, signal) {
969
1040
  const reply = () => (live ??= ui.response(client.model))
970
1041
  // a reply that may be the answer, with a review to come (files changed since the last one): its
971
1042
  // text is held and shown after the review's line, so the answer is what's last on screen
972
- const hold = sinceNudge && !s.isSub && s.changed?.size > 0 && s.lastChangeAt > (s.reviewedAt ?? 0) && ui.permission !== 'plan'
1043
+ // (after being sent back: held too, so the same answer again isn't printed twice)
1044
+ const hold = !s.isSub && ((sinceNudge && s.changed?.size > 0 && s.lastChangeAt > (s.reviewedAt ?? 0) && ui.permission !== 'plan') || s.undeclaredSent || (!sinceNudge && nudged > 0))
973
1045
  const out = { think: (t) => reply().think(t), text: hold ? (t) => t?.trim() && ui.spinner('writing the answer') : (t) => reply().text(t), end: () => reply().end() }
974
1046
  const showHeld = (text) => {
975
1047
  if (!hold || !text?.trim()) return
@@ -981,15 +1053,14 @@ async function runNative(s, task, images, signal) {
981
1053
  // A long tool call (a whole file) streams in silently: say what's being written.
982
1054
  const onToolDelta = (name, args) => {
983
1055
  const file = /"path"\s*:\s*"([^"]+)"/.exec(args)?.[1]
984
- const what = name === 'run_command' ? 'preparing a command' : EDITS.has(name) && file ? `writing ${file}` : `preparing ${name}${file ? ` ${file}` : ''}` // only an edit is "writing" a file
985
- ui.spinner(`${what} · ${args.length >= 1000 ? `${(args.length / 1000).toFixed(1)}k` : args.length} chars`)
1056
+ const what = name === 'run_command' ? 'writing a command' : EDITS.has(name) && file ? `writing ${file}` : `${{ read_file: 'reading', search: 'searching', list_files: 'listing', web_fetch: 'fetching', web_search: 'searching the web', todo: 'planning', agent: 'briefing a helper' }[name] ?? 'preparing'}${file ? ` ${file}` : ''}` // only an edit is "writing" a file
1057
+ ui.spinner(`${what}${args.length >= 2000 ? ` · ${(args.length / 1000).toFixed(1)}k characters` : '…'}`)
986
1058
  }
987
- // the prompts or HEARTCODE.md changed meanwhile (applySettings): the system prompt again, now
988
- if (s.refreshSystem && s.messages[0]?.role === 'system') s.messages[0] = { ...s.messages[0], content: SYSTEM(s) }
989
- s.refreshSystem = false
990
1059
  let res
991
1060
  try {
992
- res = await client.chat({ messages: s.messages, tools, stream }, { signal, onToken: out.text, onReasoning: out.think, onToolDelta, fit: s.autoCompact && !refitted })
1061
+ // a coding CLI (clis.js) works on the message itself: its steps shown as they come, each after the words before it
1062
+ const cliStep = (name, detail) => (live && (live.end(), (live = null)), ui.step(name, detail, '', {}))
1063
+ res = await client.chat({ messages: s.messages, tools, stream }, { signal, onToken: out.text, onReasoning: out.think, onToolDelta, fit: s.autoCompact && !refitted, agent: true, cwd: s.root, permission: ui.permission, confirm: (q, kind) => ui.confirm(q, kind), onStep: cliStep, onStepFailed: () => ui.result('failed', { ok: false }) })
993
1064
  } catch (e) {
994
1065
  if (!e.tooBig) {
995
1066
  ui.stopSpin()
@@ -1029,6 +1100,7 @@ async function runNative(s, task, images, signal) {
1029
1100
  client.announceSwitch?.() // "↻ … answered": under the reply, on a line of its own
1030
1101
  // the reply went round and round (client.js cut it): told so, and asked again
1031
1102
  if (res.looped) {
1103
+ record(client, 'bad-reply') // its track record (record.js)
1032
1104
  if (++looping > 3) {
1033
1105
  handOver(`keeps going into a loop`)
1034
1106
  looping = 0
@@ -1053,6 +1125,7 @@ async function runNative(s, task, images, signal) {
1053
1125
  // markup is the answer.
1054
1126
  const markup = !res.toolCalls.length ? leakedMarkup(res.content) : null
1055
1127
  if (markup && garbled++ < 2) {
1128
+ record(client, 'bad-reply') // its track record (record.js)
1056
1129
  log('task', `${client.model}: a tool call written as text; asking again`, res.content)
1057
1130
  s.messages.pop()
1058
1131
  s.messages.push({ role: 'user', content: prompt('agent/bad-reply', { sample: '' }) })
@@ -1068,6 +1141,12 @@ async function runNative(s, task, images, signal) {
1068
1141
  }
1069
1142
  s.lastStop = res.finishReason // why the last reply ended (headless: its stop_reason)
1070
1143
  s.onEvent?.({ type: 'assistant', model: `${client.provider}/${client.model}`, content: res.content, reasoning: res.reasoning, toolCalls: res.toolCalls, stop: res.finishReason }) // headless output
1144
+ // a coding CLI did the work itself, with its own tools and checks: its answer is the answer
1145
+ if (res.cli) {
1146
+ ui.finishSteps?.('') // headless and editors (ACP) have no steps on screen
1147
+ showHeld(res.content)
1148
+ return res.content
1149
+ }
1071
1150
  // An answer cut off (its provider's output limit: no max_tokens is sent, so each has its own; or a
1072
1151
  // connection that ended early): the model goes on where it stopped (3 times in a row at most); the
1073
1152
  // answer is the pieces together. Still cut after that: it stays cut, and says so (stop_reason).
@@ -1082,7 +1161,7 @@ async function runNative(s, task, images, signal) {
1082
1161
  if (!res.toolCalls.length || res.finishReason !== 'length') [cut, cuts] = ['', 0]
1083
1162
  if (!res.toolCalls.length && !res.content?.trim()) {
1084
1163
  // Nothing at all (seen after a failed tool call): not an answer. The same request again
1085
- // first (often fine the second time), then asked to go on; three in a row ends the task.
1164
+ // first (often fine the second time), then asked to go on; after four in a row the next model goes on.
1086
1165
  s.messages.pop() // some APIs reject an empty assistant message
1087
1166
  if (empty++ < 3) {
1088
1167
  log('task', `empty reply ${empty}; ${empty === 1 ? 'asking again' : 'asking the model to continue'}`)
@@ -1094,7 +1173,7 @@ async function runNative(s, task, images, signal) {
1094
1173
  if (movedOn < (client.rotation?.list.length ?? 1) - 1 && client.moveOn(`${was}: ${empty} empty replies in a row`)) {
1095
1174
  movedOn++
1096
1175
  empty = 0
1097
- ui.warn(`${was} keeps replying with nothing; going on with ${client.model}`)
1176
+ ui.handover(client.model, `${was} keeps replying with nothing`)
1098
1177
  continue
1099
1178
  }
1100
1179
  return finalAnswer(s, signal)
@@ -1102,6 +1181,11 @@ async function runNative(s, task, images, signal) {
1102
1181
  empty = 0
1103
1182
  // "I can't browse / run / see…" with no tool tried this message: it has tools for that. Told what
1104
1183
  // it has, once; said again without trying, the next of your models takes the task
1184
+ // --system-prompt: HeartCode's own workflow is off: an answer is the answer (no checks, reviews or handovers)
1185
+ if (!res.toolCalls.length && s.ownSystem) {
1186
+ showHeld(res.content)
1187
+ return res.content
1188
+ }
1105
1189
  if (!res.toolCalls.length && !s.acted && !s.isSub && CANT.test(res.content)) {
1106
1190
  log('task', `${client.model} said it can't, without trying a tool (${++refusedCan})`)
1107
1191
  if (refusedCan === 1) {
@@ -1132,24 +1216,35 @@ async function runNative(s, task, images, signal) {
1132
1216
  // told it isn't done (open todos, a review's no, its own "couldn't"), and it answers again without
1133
1217
  // doing anything: the same answer, or one that only promises: the next of your models takes the task
1134
1218
  const same = (a, b) => a && b && a.replace(/\s+/g, ' ').trim().slice(0, 300) === b.replace(/\s+/g, ' ').trim().slice(0, 300)
1135
- if (!res.toolCalls.length && !sinceNudge && nudged && !s.isSub && client.rotation && (s.stuckHandovers ?? 0) < 2 && (same(res.content, lastFinal) || PROMISED_MORE.test(res.content) || SAYS_FAILED.test(res.content.slice(0, 400)) || s.proofFails > 0)) {
1219
+ if (!res.toolCalls.length && !sinceNudge && nudged && !s.undeclaredSent && !s.isSub && client.rotation && (s.stuckHandovers ?? 0) < 2 && (same(res.content, lastFinal) || PROMISED_MORE.test(res.content) || SAYS_FAILED.test(res.content.slice(0, 400)) || s.proofFails > 0)) {
1136
1220
  handOver(s.proofFails > 0 ? `was told its page doesn't work when HeartCode opens it, and said it's done without changing anything` : `was told it isn't done and answered again without doing anything`)
1137
1221
  s.stuckHandovers++
1138
1222
  sinceNudge = true
1139
1223
  continue
1140
1224
  }
1225
+ const before = lastFinal
1141
1226
  if (!res.toolCalls.length) lastFinal = res.content
1142
1227
  // its page is still broken in HeartCode's check and nobody's left to take over: said, not hidden behind "done"
1143
1228
  if (!res.toolCalls.length && !sinceNudge && s.proofFails > 0 && !s.isSub) ui.warn(`HeartCode's own check: the page still doesn't work (errors, or nothing shown or drawn); this answer isn't proven`)
1144
1229
  if (!res.toolCalls.length) {
1145
- const more = sinceNudge && ((await notDone(s, signal, nudged > 0, res.content)) ?? (await review(s, task, res.content, signal)))
1146
- showHeld(res.content) // after the review's line
1230
+ // worked on the task (changed or ran something) and stopped without saying it's finished: asked
1231
+ // whether every part is done and checked, with the request. No cap: it ends when it calls done,
1232
+ // or answers again without doing anything (sinceNudge), or Esc
1233
+ const undeclared = sinceNudge && askDone() && !s.saidDone && worked(s) ? prompt('agent/not-done', { undeclared: true, request: clip(task, 3000) }) : null
1234
+ const afterAsk = s.undeclaredSent // the answer after "is every part done?": the final one, checked like any
1235
+ s.undeclaredSent = Boolean(undeclared) // answering that again with nothing done isn't a handover
1236
+ if (undeclared) log('task', 'stopped without calling done; asked whether it is finished')
1237
+ const more = (sinceNudge || afterAsk) && (undeclared ?? (s.saidDone?.waiting ? null : (await notDone(s, signal, nudged > 0, res.content)) ?? (await review(s, task, res.content, signal))))
1238
+ if (!((afterAsk || (!sinceNudge && nudged > 0)) && same(res.content, before))) showHeld(res.content) // after the review's line; the same answer again: not twice
1147
1239
  if (!more) {
1240
+ if (!s.isSub && worked(s) && !s.saidDone?.waiting && (s.saidDone || !askDone() || afterAsk)) record(client, s.proofFails > 0 ? 'not-proven' : 'done') // work done (not a chat answer): its track record (record.js)
1148
1241
  s.wrapUpLater?.(task, res.content) // after the answer, beside what comes next
1149
1242
  return res.content
1150
1243
  }
1244
+ if (!s.isSub) ui.print(c.faint(c.italic(`✻ ${undeclared ? 'HeartCode asked whether every part is done and checked' : 'not finished yet: HeartCode asked it to go on'}`))) // the next answer isn't a mystery
1151
1245
  nudged++
1152
1246
  sinceNudge = false
1247
+ // sent back: what it said with done stands (it isn't asked to call done again, only to finish)
1153
1248
  s.messages.push({ role: 'user', content: more })
1154
1249
  // said done twice and its page is still broken in HeartCode's own check: the best-ranked model takes over
1155
1250
  if (s.proofFails >= 2 && !s.isSub && client.rotation) {
@@ -1213,15 +1308,20 @@ async function runNative(s, task, images, signal) {
1213
1308
  ? [args.action, args.kind, args.name, args.id && `#${args.id}`].filter(Boolean).join(' ')
1214
1309
  : name === 'agent'
1215
1310
  ? ''
1216
- : name === 'todo' || name === 'ask_user'
1311
+ : name === 'done'
1312
+ ? `${args.waiting ? 'waiting for you: ' : ''}${String(args.checked ?? '').split('\n').find((l) => l.trim()) ?? ''}`
1313
+ : name === 'todo' || name === 'ask_user'
1217
1314
  ? ''
1218
- : (args.path ?? args.url ?? args.query ?? args.filter ?? args.name ?? '')
1219
- if (name !== 'run_command' && !together.has(call.id) && !askedWith.has(call.id)) ui.step(name, name === 'agent' && args ? helperLine(args) : clip(detail, 80), name === 'agent' ? '' : client.model) // asked together: shown once, with the first; named by the model that made the call (an agent line names the helper's)
1315
+ : name === 'search'
1316
+ ? `"${clip(String(args.query ?? ''), 50)}"${args.path ? ` in ${args.path}` : ''}`
1317
+ : (args.path ?? args.url ?? args.query ?? args.filter ?? args.name ?? '')
1318
+ const shown = name !== 'run_command' && !together.has(call.id) && !askedWith.has(call.id) // its step is on screen (its result goes on that line)
1319
+ if (shown) ui.step(name, name === 'agent' && args ? helperLine(args) : clip(detail, 80), name === 'agent' ? '' : client.model) // asked together: shown once, with the first; named by the model that made the call (an agent line names the helper's)
1220
1320
  const pre = early.get(call.id)
1221
1321
  // the first changes to the files with no plan yet (this message, or still open from an earlier one):
1222
1322
  // not made — the plan first, then the changes again. Every change in that reply (one made beside a
1223
1323
  // refused one is easily taken for refused too), once a message; not a helper's (its job is its plan)
1224
- 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')
1324
+ const planFirst = !s.isSub && !s.ownSystem && (!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')
1225
1325
  if (planFirst) Object.assign(s, { planAsked: true, planHeldIn: res })
1226
1326
  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
1227
1327
  let out = refused ?? (askedWith.has(call.id) ? 'Asked together with the first ask_user call of this reply: its result has this answer too.' : pre ? await pre.running : together.has(call.id) ? await together.get(call.id) : !allowed(s, name) ? `error: the tool ${name} is not allowed here` : args ? await runTool(name, args, s, signal, call.id) : 'error: the tool arguments were not valid JSON')
@@ -1232,6 +1332,7 @@ async function runNative(s, task, images, signal) {
1232
1332
  s.seq++
1233
1333
  if (EDITS.has(name) && !failed(out)) {
1234
1334
  s.lastChangeAt = s.seq
1335
+ s.workBy = { provider: client.provider, model: client.model } // whose changes a review judges
1235
1336
  s.checksSince = 0
1236
1337
  // the same spot changed again and again (and what it checks still comes out the same): told
1237
1338
  // at the third time that the cause is likely elsewhere
@@ -1251,7 +1352,7 @@ async function runNative(s, task, images, signal) {
1251
1352
  }
1252
1353
  // what was run or checked, for the review and the wrap-up: commands, MCP tools (a browser), helpers, the language server
1253
1354
  const checked = !args || refused ? null : name === 'run_command' ? String(args.command ?? '') : name === 'mcp' ? `${args.server} · ${args.tool}` : name === 'agent' ? `helper: ${args.description ?? clip(String(args.prompt ?? ''), 60)}` : name === 'lsp' ? `language server: ${args.action} ${args.file ?? ''}` : null
1254
- if (checked) s.ran?.push({ command: checked, result: clip(String(out).split('\n').filter((l) => l.trim()).slice(0, 2).join(' · '), 160) })
1355
+ if (checked) s.ran?.push({ command: checked, result: clip(String(out).split('\n').filter((l) => l.trim()).slice(0, 2).join(' · '), 160), look: name === 'run_command' && readOnlyCommand(checked) }) // look: it only read (git log, ls, grep): a question being answered, not work
1255
1356
  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
1256
1357
  // a step it said it was stuck on, now done: what got it out is a lesson
1257
1358
  if (!s.isSub && s.memory && s.unstuck?.length) {
@@ -1269,10 +1370,12 @@ async function runNative(s, task, images, signal) {
1269
1370
  const no = refusal(out) // refused, held, declined: said so, not left looking done
1270
1371
  if (no) {
1271
1372
  if (name === 'run_command' && refused) ui.step('run', clip(String(args.command ?? ''), 80)) // a command shows itself where it runs, which this one never reached
1272
- if (name !== 'run_command' || refused) ui.result(no) // a command's own refusals are shown there too
1273
- } else if (name === 'read_file' || name === 'search' || name === 'list_files' || name === 'web_fetch' || name === 'web_search' || name === 'changes') ui.result(lineCount(out))
1274
- else if (name === 'agent' && !failed(out)) ui.result(s.ui.permission === 'plan' ? 'planned' : 'done') // its reply is shown above, under its name
1275
- else if (failed(out)) ui.result(clip(out, 120))
1373
+ if (name !== 'run_command' || refused) ui.result(no, { refused: true }) // a command's own refusals are shown there too
1374
+ } else if (shown) {
1375
+ const r = outcomeOf(name, args ?? {}, out)
1376
+ if (name === 'agent' && r.ok !== false) r.text = s.ui.permission === 'plan' ? 'planned' : 'done' // its reply is shown above, under its name
1377
+ ui.result(r.text, r)
1378
+ }
1276
1379
  client.refresh?.() // a setting changed while the tool ran (the window): its result is cut by the new one
1277
1380
  // every sizable result is saved as it comes (a web page already is, in research): later it can
1278
1381
  // become a pointer to its file in the conversation without anything being lost
@@ -1281,6 +1384,7 @@ async function runNative(s, task, images, signal) {
1281
1384
  if (file) (s.chat.outputs ??= {})[call.id] = file
1282
1385
  }
1283
1386
  const msg = { role: 'tool', tool_call_id: call.id, content: fitResult(s, name, out, s.chat.outputs?.[call.id]) }
1387
+ if (args && !refused && !failed(out)) msg.content += guidesFor(s, name) // the fuller guidance for this kind of work, the first time
1284
1388
  if (name === 'read_file' && args && !args.start_line && !args.end_line && !failed(out)) replaceCopy(s, args.path, msg)
1285
1389
  s.messages.push(msg)
1286
1390
  s.onEvent?.({ type: 'tool', id: call.id, name, output: out, model: `${client.provider}/${client.model}` })
@@ -1289,7 +1393,7 @@ async function runNative(s, task, images, signal) {
1289
1393
  trimOldResults(s)
1290
1394
  const ended = newlyEnded(s.root) // background commands that exited meanwhile: the model hears it now
1291
1395
  if (ended.length) {
1292
- for (const j of ended) ui.step('background', `#${j.id} ${clip(j.command, 60)} exited with ${j.code}`)
1396
+ for (const j of ended) ui.step('background', `#${j.id} ${clip(j.command, 60)} exited with ${j.code}`, '', { note: true })
1293
1397
  s.messages.push({ role: 'user', content: prompt('agent/background-ended', { jobs: ended.map(jobLine).join('\n') }) })
1294
1398
  }
1295
1399
  if (stuck) {
@@ -1313,6 +1417,25 @@ async function runNative(s, task, images, signal) {
1313
1417
  // (ten calls already made) stops it.
1314
1418
  // before: what to send back instead of running it (the earlier result), or null; after: a note for its result.
1315
1419
  const EDITS = new Set(['edit_file', 'write_file', 'append_file', 'apply_patch'])
1420
+
1421
+ // The system prompt has only the core rules; the fuller guidance for a kind of work (agent/guide-*)
1422
+ // comes after the first tool result of that kind, once per conversation (sentNotes: again after
1423
+ // compacting or going back, which drop it). Not with --system-prompt (the program's workflow), and
1424
+ // not after read_file (a file read again replaces its earlier copy, and what came with it).
1425
+ const GUIDES = { list_files: ['find'], search: ['find'], lsp: ['find'], find_command: ['find'], todo: ['code', 'parts'], edit_file: ['code', 'check'], write_file: ['code', 'check'], append_file: ['code', 'check'], apply_patch: ['code', 'check'], run_command: ['check'], web_search: ['research'], web_fetch: ['research'] }
1426
+ // The guide for the kind of work (guides.js: a web app, a game, a scraper…) comes the same way, with the
1427
+ // first plan or change of a message whose words or project show that kind: not for a question
1428
+ // answered by looking. Once per conversation each, and not when the model already read it (guide tool).
1429
+ const STARTS_WORK = new Set(['todo', 'edit_file', 'write_file', 'append_file', 'apply_patch'])
1430
+ function guidesFor(s, name) {
1431
+ if (s.ownSystem) return ''
1432
+ const sent = (s.chat.sentNotes ??= [])
1433
+ const due = (GUIDES[name] ?? []).filter((k) => !sent.includes(`guide:${k}`) && (k !== 'parts' || (!s.isSub && s.subagent && s.team?.().length))) // parts: only with other models to give them to
1434
+ sent.push(...due.map((k) => `guide:${k}`))
1435
+ const kinds = STARTS_WORK.has(name) ? (s.domainGuides ?? []).filter((g) => !sent.includes(`domain:${g}`)) : []
1436
+ sent.push(...kinds.map((g) => `domain:${g}`))
1437
+ return [...due.map((k) => prompt(`agent/guide-${k}`, guideVars(s))), ...kinds.map((g) => guideText(s, g))].map((t) => `\n\n${t}`).join('')
1438
+ }
1316
1439
  // Tools that run or look at what was made (a command, a test, a browser, a helper): a check after a change.
1317
1440
  const CHECKS = new Set(['run_command', 'mcp', 'agent', 'lsp'])
1318
1441
  // Files only read by people (a change there needs no run to check it).
@@ -1389,7 +1512,7 @@ async function noteRun(s, name, args, out, signal) {
1389
1512
  const tool = runTool_(args.command)
1390
1513
  if (!tool) return
1391
1514
  const code = Number(/^exit code (-?\d+)/.exec(out)?.[1] ?? (failed(out) ? 1 : 0))
1392
- const bad = code !== 0 || /\b(error|traceback|exception|failed|cannot|not found|undefined)\b/i.test(out.split('\n').slice(0, 6).join(' '))
1515
+ const bad = code !== 0 // what it printed ("0 failed", "undefined") says nothing; its exit code does
1393
1516
  if (bad) {
1394
1517
  const line = out.split('\n').find((l) => /\b(error|traceback|exception|failed|cannot|not found)\b/i.test(l)) ?? out.split('\n').find((l) => l.trim()) ?? ''
1395
1518
  s.runFails.set(tool, { error: `${args.command.split(/\s+/)[0]}: ${line.trim().slice(0, 160)}`, atEdits: s.edits, cmd: args.command })
@@ -1415,23 +1538,25 @@ async function learnFromFixes(s, fixed, signal, { unsolved = false, task = '' }
1415
1538
  let rule = ''
1416
1539
  let scope = 'global'
1417
1540
  try {
1418
- const was = s.client.purpose
1419
- s.client.purpose = 'lesson'
1541
+ // a client of its own (the same model): not the one the task is using, its state stays the task's
1542
+ const { client } = s.engineFor ? await s.engineFor({ provider: s.client.provider, model: s.client.model }) : { client: s.client }
1543
+ const was = client.purpose
1544
+ client.purpose = 'lesson'
1420
1545
  let reply
1421
1546
  try {
1422
- reply = await s.client.chat({ messages: [{ role: 'user', content: prompt('agent/lesson', { error, unsolved, task: clip(task, 300) }) }] }, { signal })
1547
+ reply = await client.chat({ messages: [{ role: 'user', content: prompt('agent/lesson', { error, unsolved, task: clip(task, 300) }) }] }, { signal })
1423
1548
  } finally {
1424
- s.client.purpose = was
1549
+ client.purpose = was
1425
1550
  }
1426
- const said = reply.content.trim().split('\n').filter((l) => l.trim())
1551
+ if (/^\W*none\b/i.test(reply.content.trim())) continue // not a lesson worth keeping
1427
1552
  rule = (said.find((l) => !/^\s*\W*scope\s*:/i.test(l)) ?? '').replace(/^\s*(?:\d+[.)]|[-*])\s*/, '').replace(/^["'\s-]+|["']+$/g, '').slice(0, 200)
1428
1553
  if (/scope\s*:\W*project/i.test(said.join('\n'))) scope = 'project'
1429
1554
  } catch (e) {
1430
1555
  if (e.name === 'AbortError') throw e
1431
1556
  }
1432
- if (!rule || rule.length < 10) rule = error.replace(/^[^:]*:\s*/, '') // the model couldn't phrase it: keep the error's own wording
1557
+ if (!rule || rule.length < 10) continue // the model couldn't phrase it: an error's own wording isn't a rule
1433
1558
  const name = s.memory.write({ description: rule, type: 'reference', tags: ['lesson', ...tags], content: `${rule}\n\nLearned on ${new Date().toISOString().slice(0, 10)} ${unsolved ? 'after this blocked a task that was not done' : 'after this was caught and fixed'}${task ? ` (the task: ${clip(task, 200)})` : ' while building'}: ${error}`, scope })
1434
- s.ui.step('learned', `${rule.slice(0, 90)}${scope === 'project' ? ' (this project)' : ''}`)
1559
+ s.ui.step('learned', `${rule.slice(0, 90)}${scope === 'project' ? ' (this project)' : ''}`, '', { note: true })
1435
1560
  log('learn', `saved lesson [[${name}]] (${scope}, #${tags.join(' #')}): ${rule}`)
1436
1561
  }
1437
1562
  }
@@ -1441,15 +1566,24 @@ async function learnFromFixes(s, fixed, signal, { unsolved = false, task = '' }
1441
1566
  // most (the caller counts), so a model that can't finish still ends.
1442
1567
  // The model said it would do something but stopped without doing it ("let me rewrite…", "I'll fix…"):
1443
1568
  // a next action named, then no tool call. Not matched by explanations ("let me explain", "you can run").
1444
- const PROMISED_MORE =
1445
- /\b(?:let me|let['’]?s|let us|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|use|open|navigate|click|solve)\b/i
1569
+ const PROMISED_RE =
1570
+ /\b(?:let me(?! know)|let['’]?s|let us|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|use|open|navigate|click|solve)\b/i
1571
+ // …in a sentence of its own: not an offer ("Let me know if you want me to add tests", "Would you like me to…")
1572
+ const OFFER = /\b(?:if you(?:['’]d)? (?:want|like|need|prefer)|would you like|want me to|like me to|let me know|shall i|should i|do you want)\b/i
1573
+ const PROMISED_MORE = { test: (text) => String(text).split(/(?<=[.!?])\s+|\n+/).some((x) => PROMISED_RE.test(x) && !OFFER.test(x)) }
1446
1574
 
1447
1575
  // The start of a final answer saying it didn't manage: "I couldn't…", "unable to…", "still showing…".
1448
- const SAYS_FAILED = /\b(?:could ?n['’]?t|could not|was(?: not|n['’]?t) able to|(?:am|was|i['’]m) unable to|failed to|did(?: not|n['’]?t) (?:manage|succeed|work|load|pass)|not (?:yet )?(?:complete[d]?|finished|solved|possible|loaded)|still (?:in progress|pending|blocked|loading|stuck|showing|failing|not)|has not (?:yet )?(?:complet|finish|load|pass))/i
1576
+ const FAILED_WORDS = /\b(?:could ?n['’]?t|could not|was(?: not|n['’]?t) able to|(?:am|was|i['’]m) unable to|failed to|did(?: not|n['’]?t) (?:manage|succeed|work|load|pass)|not (?:yet )?(?:complete[d]?|finished|solved|possible|loaded)|still (?:in progress|pending|blocked|loading|stuck|showing|failing|not)|has not (?:yet )?(?:complet|finish|load|pass))/gi
1577
+ // An answer that says it didn't manage: those words, not in a condition or a "what if" ("without which
1578
+ // the test could not pass", "otherwise it would fail", "if it couldn't connect")
1579
+ const CONDITIONAL = /\b(?:without (?:which|it|this|that)|otherwise|or else|would(?:n['’]?t)?|if|unless|so (?:that )?it)\b(?:[^.;!?\n]|\.(?!\s))*$/i // within the same sentence (a dot in a file name isn't its end)
1580
+ // …and not one it got past in the same sentence ("I couldn't find existing tests, so I added some")
1581
+ const GOT_PAST = /^[^.;!?\n]*\b(?:so|instead|but|then)\b[^.;!?\n]*\b(?:i|we)\b/i
1582
+ const SAYS_FAILED = { test: (text) => [...String(text).matchAll(FAILED_WORDS)].some((m) => !CONDITIONAL.test(text.slice(Math.max(0, m.index - 40), m.index)) && !GOT_PAST.test(text.slice(m.index + m[0].length))) }
1449
1583
 
1450
1584
  // "I can't browse the web", "I'm unable to run commands", "I don't have access to…": a model
1451
1585
  // saying it lacks an ability (it has tools for it).
1452
- const CANT = /\b(?:i\s*(?:['’]m|am)\s*(?:unable|not able)\s*to|i\s*(?:can(?:['’]?t| ?not)|do(?:n['’]?t| not))\s*(?:directly\s*)?(?:have\s*(?:the\s*)?(?:ability|access|capabilit|tools?)|browse|access|open|visit|view|see|interact|click|navigate|run|execute|take|solve|use|control))|\bas an ai\b/i
1586
+ const CANT = /\b(?:i\s*(?:['’]m|am)\s*(?:unable|not able)\s*to|i\s*(?:can(?:['’]?t| ?not)|do(?:n['’]?t| not))\s*(?:directly\s*)?(?:have\s*(?:the\s*)?(?:ability|access|capabilit|tools?)|browse(?: the web)?|access (?:the (?:web|internet)|files|your)|visit|interact|click|navigate|run (?:commands|code|scripts|programs)|execute|control))|\bas an ai\b/i // an ability, not what it looked at ("I can't see any errors")
1453
1587
 
1454
1588
  // Is the task really done, or did the model stop early? Open todo items, or (after it did real work)
1455
1589
  // a reply that only promises more, get one nudge to keep going. Then any Stop hook. null = truly done.
@@ -1471,8 +1605,8 @@ function strongest(s, client, why) {
1471
1605
  const best = (s.team?.() ?? [])
1472
1606
  .filter((t) => t.tools !== false && !s.gaveUp.has(`${t.provider}/${t.model}`) && family(t.model) !== now)
1473
1607
  .map((t) => ({ t, score: scoreOf(t.model) }))
1474
- .filter((x) => x.score < Infinity)
1475
- .sort((a, b) => a.score - b.score)[0]
1608
+ .sort(byRecord) // the rankings, moved by each model's track record (record.js)
1609
+ .filter((x) => x.score < Infinity)[0]
1476
1610
  const target = best && client.rotation?.list.find((x) => x.provider === best.t.provider && x.model === best.t.model)
1477
1611
  return Boolean(target && client.switchTo(target, `${why}; the best-ranked of your models not tried yet`))
1478
1612
  }
@@ -1523,8 +1657,11 @@ export async function notDone(s, signal, again, reply = '') {
1523
1657
  s.ui.stopSpin()
1524
1658
  if (!r) continue
1525
1659
  s.ran?.push({ command: `HeartCode opened ${page} in a browser`, result: clip(r.report.split('\n')[0], 300) }) // the review sees it
1526
- s.ui.step('check', `${page} in a browser: ${r.broken ? 'broken' : 'works'}`)
1527
- if (!r.broken) continue
1660
+ s.ui.step('check', `${page} in a browser: ${r.broken ? 'broken' : 'works'}`, '', { note: true, ok: !r.broken })
1661
+ if (!r.broken) {
1662
+ s.proofShots = (r.shots ?? []).filter((f) => /desktop/.test(f)) // the review looks at it (reviewers that can see)
1663
+ continue
1664
+ }
1528
1665
  s.proofFails = (s.proofFails ?? 0) + 1
1529
1666
  log('task', `HeartCode's page check failed (${s.proofFails}): ${r.report}`)
1530
1667
  return prompt('agent/not-done', { broken: r.report, page, shots: (r.shots ?? []).map((f) => path.relative(s.root, f)).join(', '), command: `"${process.execPath}" "${BIN}" page ${page}` })
@@ -1601,10 +1738,15 @@ const isEmptyDir = (abs) => {
1601
1738
  // answer, the changes and what was run since. It answers YES (done right) or NO with what's wrong;
1602
1739
  // a NO goes back to the model to fix. Asked again only once files changed since its last look.
1603
1740
  // Returns what to tell the model, or null.
1741
+ // Work was done this message: files changed, or something run that does more than look (a build, a
1742
+ // server, a browser, a helper). Not a question answered by looking around (git log, ls, grep): that
1743
+ // gets no "is every part done?" and no review.
1744
+ const worked = (s) => Boolean(s.changed?.size || (s.ran ?? []).some((r) => !r.look))
1745
+
1604
1746
  export async function review(s, task, answer, signal) {
1605
1747
  // no files changed, but it ran things to do the task (a browser, commands, helpers): its answer is
1606
1748
  // checked against the request too (once per new batch of them)
1607
- const acted = !s.changed?.size && (s.ran?.length ?? 0) > (s.reviewedRan ?? 0)
1749
+ const acted = !s.changed?.size && (s.ran ?? []).slice(s.reviewedRan ?? 0).some((r) => !r.look) // only looked (a question answered with git log, ls…): nothing to review
1608
1750
  if (s.isSub || s.ui.permission === 'plan' || (!acted && (!s.changed?.size || s.lastChangeAt <= s.reviewedAt))) return null
1609
1751
  s.reviewedAt = s.lastChangeAt
1610
1752
  s.reviewedRan = s.ran?.length ?? 0
@@ -1630,9 +1772,19 @@ export async function review(s, task, answer, signal) {
1630
1772
  }
1631
1773
  if (!diffs.length && !acted) return null
1632
1774
  if (!diffs.length) diffs.push('(no files changed)')
1633
- const plan = (s.chat.todos ?? []).map((t) => `- [${t.status === 'completed' ? 'x' : ' '}] ${t.content}`).join('\n')
1775
+ const plan = s.todoTouched ? (s.chat.todos ?? []).map((t) => `- [${t.status === 'completed' ? 'x' : ' '}] ${t.content}`).join('\n') : '' // a plan from an earlier message isn't this one's
1634
1776
  const ran = (s.ran ?? []).slice(-15).map((r) => `- ${clip(r.command.replace(/\s+/g, ' '), 160)} → ${r.result}`).join('\n')
1635
- 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)', shrunk: shrunkNote(s, [...(s.changed ?? [])]) })
1777
+ const earlier = requestsOf({ turns: s.chat.turns.slice(0, -1) }, 800)
1778
+ const vars = { request: clip(String(task ?? ''), 3000), earlier, emphasis: (s.chat?.choices ?? []).join('; '), plan: plan || '(none)', answer: clip(String(answer ?? ''), 3000), changes: diffs.join('\n\n'), ran: ran || '(nothing)', shrunk: shrunkNote(s, [...(s.changed ?? [])]) }
1779
+ // the page's screenshot from HeartCode's browser check, for a reviewer that can see: what the user gets
1780
+ const shots = (s.proofShots ?? []).flatMap((f) => {
1781
+ try {
1782
+ return [{ type: 'image_url', image_url: { url: imageUrl(f) } }]
1783
+ } catch {
1784
+ return []
1785
+ }
1786
+ })
1787
+ const askFor = (t) => ((t.self ? s.strat.vision : t.images) && shots.length ? [{ type: 'text', text: prompt('agent/review', { ...vars, shots: true }) }, ...shots] : prompt('agent/review', vars))
1636
1788
  const self = { provider: s.client.provider, model: s.client.model, self: true }
1637
1789
  const others = (s.team?.() ?? []).filter((t) => t.tools !== false && !(t.provider === self.provider && t.model === self.model))
1638
1790
  const reviewers = others.filter((t) => t.jobs?.includes('code')).sort((a, b) => Boolean(b.thinking) - Boolean(a.thinking)) // ticked for Code & logic on Your models, the thinking ones first
@@ -1646,7 +1798,7 @@ export async function review(s, task, answer, signal) {
1646
1798
  client.purpose = 'review'
1647
1799
  let said
1648
1800
  try {
1649
- said = (await client.chat({ messages: [{ role: 'user', content: ask }] }, { signal })).content.trim()
1801
+ said = (await client.chat({ messages: [{ role: 'user', content: askFor(t) }] }, { signal })).content.trim()
1650
1802
  } finally {
1651
1803
  client.purpose = was
1652
1804
  }
@@ -1655,14 +1807,15 @@ export async function review(s, task, answer, signal) {
1655
1807
  if (/^\W*yes\b/i.test(said)) {
1656
1808
  s.lastReview = { verdict: 'yes' }
1657
1809
  s.ui.event?.({ subtype: 'review', model: `${t.provider}/${t.model}`, verdict: 'yes', issues: '' })
1658
- s.ui.step('review', `${t.model}: looks right`)
1810
+ s.ui.step('review', `${t.model}: looks right`, '', { note: true })
1659
1811
  return null
1660
1812
  }
1661
1813
  if (/^\W*no\b/i.test(said)) {
1662
1814
  const issues = said.replace(/^\W*no\b[\s.:—-]*/i, '').trim()
1663
1815
  s.lastReview = { verdict: 'no', issues }
1816
+ record(s.workBy ?? s.client, 'review-no') // the model that made the changes (another may answer now): its track record (record.js)
1664
1817
  s.ui.event?.({ subtype: 'review', model: `${t.provider}/${t.model}`, verdict: 'no', issues })
1665
- s.ui.step('review', `${t.model}: ${clip(issues.split('\n').find((l) => l.trim()) ?? 'problems found', 90)}`)
1818
+ s.ui.step('review', `${t.model}: ${clip(issues.split('\n').find((l) => l.trim()) ?? 'problems found', 90)}`, '', { note: true, ok: false })
1666
1819
  return prompt('agent/review-failed', { model: t.model, issues: issues || '(no details given)' })
1667
1820
  }
1668
1821
  log('review', `${t.model} didn't answer YES or NO; trying another`)
@@ -1676,6 +1829,54 @@ export async function review(s, task, answer, signal) {
1676
1829
  }
1677
1830
 
1678
1831
  // "3 lines" for a result; an empty last line isn't one (a file ends with a newline, and read_file numbers the empty line after it)
1832
+ // How a tool call went, for its step's line (ui.result): { text, ok, none, n, unit, files }.
1833
+ export function outcomeOf(name, args, out) {
1834
+ const o = String(out)
1835
+ if (failed(o)) {
1836
+ const why = o.replace(/^error: /, '').split('\n')[0]
1837
+ return { ok: false, text: /\b(does not exist|doesn't exist|no such file|ENOENT)\b/i.test(why) ? 'not found' : clip(why.replace(/\. .*$/, ''), 90) }
1838
+ }
1839
+ const count = (n, one, many) => `${n} ${n === 1 ? one : many}`
1840
+ switch (name) {
1841
+ case 'read_file': {
1842
+ if (o.startsWith('data:')) return { text: 'an image' }
1843
+ const nums = [...o.matchAll(/^(\d+)\| /gm)].map((m) => Number(m[1]))
1844
+ if (!nums.length) return { text: clip(o.split('\n')[0], 60), none: !o.trim() }
1845
+ const total = Number(/\((\d+) lines total;/.exec(o)?.[1]) || null
1846
+ const [a, b] = [nums[0], nums.at(-1)]
1847
+ return { text: a === 1 && !total ? count(b, 'line', 'lines') : `lines ${a}–${b}${total ? ` of ${total}` : ''}`, n: b - a + 1, unit: 'lines' }
1848
+ }
1849
+ case 'search': {
1850
+ if (/^(no matches|nothing was searched)/.test(o)) return { none: true, text: 'no matches' }
1851
+ const hits = o.split('\n').filter((l) => /^[^\n:]+:\d+: /.test(l))
1852
+ const files = [...new Set(hits.map((l) => l.slice(0, l.search(/:\d+: /))))]
1853
+ const more = /\(stopped at \d+ matches\)/.test(o) ? '+' : ''
1854
+ return { text: `${count(hits.length, 'match', 'matches')}${more} in ${count(files.length, 'file', 'files')}`, n: hits.length, unit: 'matches', files }
1855
+ }
1856
+ case 'list_files': {
1857
+ if (/^(\(empty folder\)|no files)$/.test(o.trim())) return { none: true, text: 'empty' }
1858
+ const lines = o.split('\n').filter((l) => l.trim())
1859
+ const n = lines.filter((l) => !/^… \d+ more$/.test(l)).length + Number(/^… (\d+) more$/m.exec(o)?.[1] ?? 0)
1860
+ return { text: count(n, 'entry', 'entries'), n, unit: 'entries' }
1861
+ }
1862
+ case 'web_fetch': {
1863
+ const kb = Math.max(1, Math.round(o.length / 1000))
1864
+ return { text: `${kb} KB`, n: kb, unit: 'KB' }
1865
+ }
1866
+ case 'web_search': {
1867
+ if (/^no results/.test(o)) return { none: true, text: 'no results' }
1868
+ const n = new Set(o.match(/https?:\/\/\S+/g) ?? []).size
1869
+ return n ? { text: count(n, 'result', 'results'), n, unit: 'results' } : { text: '' }
1870
+ }
1871
+ case 'changes':
1872
+ return { text: lineCount(o) }
1873
+ case 'agent':
1874
+ return { text: '' }
1875
+ default:
1876
+ return { text: '' }
1877
+ }
1878
+ }
1879
+
1679
1880
  const lineCount = (out) => {
1680
1881
  const n = String(out).replace(/\n\s*(\d+\|)?\s*$/, '').split('\n').length
1681
1882
  return `${n} line${n === 1 ? '' : 's'}`
@@ -1693,7 +1894,6 @@ function helperUI(ui, label, model) {
1693
1894
  // conversation's; with other helpers replying at the
1694
1895
  // same time, held until its reply ends, then printed at once (two streams would interleave).
1695
1896
  const response = () => {
1696
- const t0 = Date.now()
1697
1897
  let thought = ''
1698
1898
  let said = ''
1699
1899
  const alone = !streaming.get(ui)
@@ -1705,7 +1905,7 @@ function helperUI(ui, label, model) {
1705
1905
  end() {
1706
1906
  streaming.set(ui, streaming.get(ui) - 1)
1707
1907
  if (live) live.end()
1708
- 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, ' ')))}` : ''))
1908
+ else if (thought.trim()) ui.print(c.faint(c.italic(` ✻ ${label} thinking`)) + `\n${c.think(c.italic(thought.trim().replace(/^/gm, ' ')))}`)
1709
1909
  if (!said.trim()) return
1710
1910
  ui.print(` ${c.bright(c.bold('●'))} ${c.bold(label)}`)
1711
1911
  let block = new Block((x) => ui.write(x), { marker: ' ', style: c.text })
@@ -1728,13 +1928,11 @@ function helperUI(ui, label, model) {
1728
1928
  }
1729
1929
  const own = {
1730
1930
  // its steps one level in, under the agent line
1731
- step: (name, detail = '') => {
1732
- if (ui.afterBlock) ui.gap()
1733
- ui.afterBlock = false
1734
- ui.print(` ${c.accent('●')} ${c.accent(c.bold(`${label} › ${name}`))} ${c.info(detail)}${model ? c.faint(` · ${model}`) : ''}`)
1735
- status(`${name} ${detail}`)
1931
+ step: (name, detail = '', _who, opts) => {
1932
+ ui.step(name, detail, model, { ...opts, sub: label })
1933
+ status(`${(STEP_NAMES[name] ?? name).toLowerCase()} ${detail}`)
1736
1934
  },
1737
- result: (text) => ui.print(` ${c.ghost('⎿')} ${c.faint(text)}`),
1935
+ result: (text, opts) => ui.result(text, { ...opts, sub: label }),
1738
1936
  response,
1739
1937
  spinner: (text) => {
1740
1938
  status(typeof text === 'function' ? text() : text)
@@ -1839,7 +2037,8 @@ function attachNamed(s, task) {
1839
2037
  replaceCopy(s, f, msg)
1840
2038
  results.push(msg)
1841
2039
  s.ui.step('read_file', f)
1842
- s.ui.result(lineCount(body))
2040
+ const r = outcomeOf('read_file', { path: f }, body)
2041
+ s.ui.result(r.text, r)
1843
2042
  }
1844
2043
  if (calls.length) s.messages.push({ role: 'assistant', content: '', tool_calls: calls }, ...results)
1845
2044
  }