heartcode 0.1.27 → 0.1.32
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/CHANGELOG.md +123 -0
- package/README.md +84 -30
- package/SKILL.md +37 -11
- package/bin/heartcode.js +252 -56
- package/package.json +1 -1
- package/prompts/agent.md +131 -22
- package/src/agent.js +498 -77
- package/src/background.js +105 -0
- package/src/client.js +14 -3
- package/src/config.js +1 -1
- package/src/guided.js +7 -2
- package/src/headless.js +10 -4
- package/src/memory.js +6 -2
- package/src/research.js +142 -0
- package/src/sessions.js +4 -1
- package/src/settings.html +331 -76
- package/src/settings.js +73 -0
- package/src/telegram.js +81 -0
- package/src/tools.js +163 -53
- package/src/ui.js +235 -34
- package/src/web.js +150 -40
package/src/agent.js
CHANGED
|
@@ -5,13 +5,15 @@ import { prompt, userInstructions } from './prompts.js'
|
|
|
5
5
|
import { newChat } from './sessions.js'
|
|
6
6
|
import path from 'node:path'
|
|
7
7
|
import { pathToFileURL } from 'node:url'
|
|
8
|
-
import { est, Client, writtenBy, tokensOf, COMPACT_SHARE } from './client.js'
|
|
8
|
+
import { est, estMessages, Client, writtenBy, tokensOf, COMPACT_SHARE } from './client.js'
|
|
9
9
|
import { runGuided } from './guided.js'
|
|
10
|
-
import {
|
|
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'
|
|
13
|
+
import { newlyEnded, jobLine } from './background.js'
|
|
12
14
|
import { loadHooks, runHooks } from './hooks.js'
|
|
13
15
|
import { takeConfigErrors } from './config.js'
|
|
14
|
-
import { c, duration } from './ui.js'
|
|
16
|
+
import { c, duration, Block, Markdown, color, diffLines, renderDiff } from './ui.js'
|
|
15
17
|
|
|
16
18
|
// Images for a helper (the agent tool's "images"), as data: URLs: image URLs (fetched), data: URLs,
|
|
17
19
|
// or files: in the project, saved screenshots (OUTPUTS), or a path the user gave in a message.
|
|
@@ -38,7 +40,7 @@ async function loadImages(list, s, signal) {
|
|
|
38
40
|
} else {
|
|
39
41
|
const abs = path.resolve(s.root, x.replace(/^~(?=\/)/, os.homedir()))
|
|
40
42
|
const inside = (dir) => abs.startsWith(dir + path.sep)
|
|
41
|
-
if (fs.existsSync(abs) && !inside(s.root) && !
|
|
43
|
+
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
44
|
out.push(imageUrl(abs, x))
|
|
43
45
|
}
|
|
44
46
|
}
|
|
@@ -147,6 +149,7 @@ export class Session {
|
|
|
147
149
|
// images: data: URLs from the caller (headless input), besides @shot.png in the task.
|
|
148
150
|
async run(task, signal, extra = []) {
|
|
149
151
|
if (!this.isSub) this.client.newMessage?.() // the model list: from #1 again (unless set to stay)
|
|
152
|
+
this.runs = (this.runs ?? 0) + 1
|
|
150
153
|
const { chat, ui } = this
|
|
151
154
|
repairSummary(chat)
|
|
152
155
|
if (this.hooks !== false) this.hooks = loadHooks(this.root) // edits to hooks.json apply right away
|
|
@@ -247,7 +250,7 @@ export class Session {
|
|
|
247
250
|
}
|
|
248
251
|
const label = clip(`${client.model}: ${String(description ?? '').trim() || task.split('\n')[0]}`, 60)
|
|
249
252
|
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 })
|
|
253
|
+
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
254
|
helper.track = (rel, before) => this.track(rel, before)
|
|
252
255
|
helper.mcpGate = async () => (await this.#gate(helper), () => {})
|
|
253
256
|
if (this.onEvent) helper.onEvent = (e) => this.onEvent({ ...e, parent: id, helper: label })
|
|
@@ -357,32 +360,119 @@ export class Session {
|
|
|
357
360
|
return prompt('agent/memory-extract', { tags: this.memory.tagSummary() || '(none yet)', notes })
|
|
358
361
|
}
|
|
359
362
|
|
|
360
|
-
// A small tool loop with
|
|
361
|
-
|
|
362
|
-
|
|
363
|
+
// A small tool loop with the memory tool (saving and tidying notes), and any `extra` tools ({ defs,
|
|
364
|
+
// run(name, args) → result or undefined for the memory tool }). It ends when the model answers, or
|
|
365
|
+
// makes exactly the calls it just made (going round, not getting anywhere).
|
|
366
|
+
async memoryTask(system, user, signal, extra = null) {
|
|
367
|
+
const tools = [...extraTools({ memory: this.memory }), ...(extra?.defs ?? [])].map((f) => ({ type: 'function', function: f }))
|
|
363
368
|
const messages = [{ role: 'system', content: system }, { role: 'user', content: user }]
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
369
|
+
let last = ''
|
|
370
|
+
const client = extra?.client ?? this.client
|
|
371
|
+
for (;;) {
|
|
372
|
+
const was = client.purpose
|
|
373
|
+
client.purpose = extra?.purpose ?? 'memory' // in the requests log
|
|
367
374
|
let res
|
|
368
375
|
try {
|
|
369
|
-
res = await
|
|
376
|
+
res = await client.chat({ messages, tools }, { signal })
|
|
370
377
|
} finally {
|
|
371
|
-
|
|
378
|
+
client.purpose = was
|
|
372
379
|
}
|
|
373
380
|
messages.push({ role: 'assistant', content: res.content || '', ...(res.toolCalls.length && { tool_calls: res.toolCalls }) })
|
|
374
381
|
if (!res.toolCalls.length) return res.content.trim()
|
|
382
|
+
const these = res.toolCalls.map((t) => `${t.function.name} ${t.function.arguments}`).join('\n')
|
|
383
|
+
if (these === last) return res.content.trim()
|
|
384
|
+
last = these
|
|
375
385
|
for (const call of res.toolCalls) {
|
|
376
386
|
let args = {}
|
|
377
387
|
try {
|
|
378
388
|
args = JSON.parse(call.function.arguments || '{}')
|
|
379
389
|
} catch {}
|
|
380
|
-
const out = await
|
|
381
|
-
if (args.action === 'write' || args.action === 'delete') this.ui.step('memory', `${args.action === 'write' ? 'saved' : 'deleted'} ${out.match(/\[\[[^\]]+\]\]/)?.[0] ?? ''}`)
|
|
390
|
+
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}`)
|
|
391
|
+
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
392
|
messages.push({ role: 'tool', tool_call_id: call.id, content: out })
|
|
383
393
|
}
|
|
384
394
|
}
|
|
385
|
-
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// After a task that read the web, ran commands or made files: what's worth knowing next time is
|
|
398
|
+
// saved as notes (project or global), each page it read is kept (marked with what it was used for)
|
|
399
|
+
// or deleted as junk, and throwaway files it made are removed. Done by code after every such task,
|
|
400
|
+
// not left to the model to remember: a fresh, small request (the task, its answer, the lists), on
|
|
401
|
+
// the model that did the task. Helpers' pages are in the same list (they share it).
|
|
402
|
+
// It runs after the answer is back (wrapUpLater), beside whatever you do next: its own connection,
|
|
403
|
+
// one wrap-up at a time; what it needs is taken from the task first, before the next one changes it.
|
|
404
|
+
wrapUpLater(task, answer) {
|
|
405
|
+
const at = { research: this.research, turn: this.chat.turns.at(-1), dirsBefore: this.dirsBefore, ran: this.ran, runs: this.runs }
|
|
406
|
+
const job = (this.wrapping ?? Promise.resolve())
|
|
407
|
+
.then(() => this.wrapUp(task, answer, undefined, at))
|
|
408
|
+
.catch((e) => log('wrapup', `failed: ${e.message}`))
|
|
409
|
+
.finally(() => this.wrapping === job && (this.wrapping = null))
|
|
410
|
+
this.wrapping = job
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// at: the task's own state (wrapUpLater), else this message's
|
|
414
|
+
async wrapUp(task, answer, signal, at = { research: this.research, turn: this.chat.turns.at(-1), dirsBefore: this.dirsBefore, ran: this.ran, runs: this.runs }) {
|
|
415
|
+
if (this.isSub || !this.memory || this.ui.permission === 'plan') return
|
|
416
|
+
const pages = at.research ?? []
|
|
417
|
+
const turn = at.turn
|
|
418
|
+
const made = Object.entries(turn?.files ?? {}).filter(([rel, before]) => before === null && fs.existsSync(path.join(this.root, rel))).map(([rel]) => rel)
|
|
419
|
+
// folders the task made that are still empty (a test folder): offered for cleanup too
|
|
420
|
+
if (at.dirsBefore) for (const d of foldersOf(this.root)) if (!at.dirsBefore.has(d) && isEmptyDir(path.join(this.root, d))) made.push(`${d}/`)
|
|
421
|
+
const ran = at.ran ?? []
|
|
422
|
+
if (!pages.length && !made.length && !ran.length) return
|
|
423
|
+
const commands = ran.map((r) => `- ${clip(r.command.replace(/\s+/g, ' '), 200)} → ${r.result}`).join('\n')
|
|
424
|
+
const known = this.memory.relevant(`${task}\n${answer}\n${pages.map((p) => p.title).join('\n')}`, 12)
|
|
425
|
+
const request = prompt('agent/wrapup-task', {
|
|
426
|
+
task: clip(task, 4000),
|
|
427
|
+
answer: clip(String(answer ?? ''), 4000) + (commands ? `\n\nCommands it ran (newest last):\n${commands.length > 6000 ? `…\n${commands.slice(-6000)}` : commands}` : ''),
|
|
428
|
+
pages: pages.map((p) => `- [${p.kind}] ${p.title}${p.url ? ` — ${p.url}` : ''} → file: ${p.file}`).join('\n') || '(none)',
|
|
429
|
+
files: made.map((f) => `- ${f}`).join('\n') || '(none)',
|
|
430
|
+
notes: known.map((n) => `- [[${n.name}]] (${n.scope}) — ${n.description}`).join('\n') || '(none)',
|
|
431
|
+
})
|
|
432
|
+
const files = new Set(pages.map((p) => p.file))
|
|
433
|
+
const scratch = new Set(made)
|
|
434
|
+
const mine = at.runs // a message sent since: its task may use these files, so none are deleted
|
|
435
|
+
const kept = []
|
|
436
|
+
const dropped = []
|
|
437
|
+
const removed = []
|
|
438
|
+
const defs = [
|
|
439
|
+
{ 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'] } },
|
|
440
|
+
{ 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'] } },
|
|
441
|
+
]
|
|
442
|
+
const run = (name, a) => {
|
|
443
|
+
if (name === 'research') {
|
|
444
|
+
const f = [...files].find((x) => x === a.file || path.basename(x) === path.basename(String(a.file ?? '')))
|
|
445
|
+
if (!f) return `error: "${a.file}" isn't one of the pages this task read: ${[...files].join(', ')}`
|
|
446
|
+
if (a.verdict === 'junk') return removeResearch(this.root, f) ? (dropped.push(f), `Deleted ${f}.`) : `error: ${f} is gone already`
|
|
447
|
+
return markUsed(this.root, f, String(a.used_for ?? '').trim()) ? (kept.push(f), `Kept ${f}.`) : `error: ${f} is gone`
|
|
448
|
+
}
|
|
449
|
+
if (name === 'scratch') {
|
|
450
|
+
let rel = String(a.path ?? '').trim().replace(/^\.\//, '')
|
|
451
|
+
if (!scratch.has(rel) && scratch.has(`${rel}/`)) rel = `${rel}/` // a folder named without its slash
|
|
452
|
+
if (!scratch.has(rel)) return `error: "${rel}" isn't one of the new files this task made: ${[...scratch].join(', ')}`
|
|
453
|
+
if (a.verdict !== 'delete') return `Kept ${rel}.`
|
|
454
|
+
if (this.runs !== mine) return `Kept ${rel}: the user has gone on to another task, which may use it.`
|
|
455
|
+
if (rel.endsWith('/')) {
|
|
456
|
+
if (!isEmptyDir(path.join(this.root, rel))) return `error: ${rel} isn't empty: delete the files in it first, or keep it`
|
|
457
|
+
fs.rmSync(path.join(this.root, rel, '.DS_Store'), { force: true })
|
|
458
|
+
fs.rmdirSync(path.join(this.root, rel))
|
|
459
|
+
} else fs.rmSync(path.join(this.root, rel), { force: true })
|
|
460
|
+
scratch.delete(rel)
|
|
461
|
+
removed.push(rel)
|
|
462
|
+
this.ui.step('cleanup', `removed ${rel}`)
|
|
463
|
+
return `Deleted ${rel}.`
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
const own = { provider: this.client.provider, model: this.client.model }
|
|
467
|
+
try {
|
|
468
|
+
const { client } = this.engineFor ? await this.engineFor(own) : { client: this.client }
|
|
469
|
+
const said = await this.memoryTask(prompt('agent/wrapup'), request, signal, { defs, run, client, purpose: 'wrapup' })
|
|
470
|
+
log('wrapup', `${said} | pages kept ${kept.length}, deleted ${dropped.length}; files removed ${removed.length}`)
|
|
471
|
+
if (kept.length || dropped.length) this.ui.step('research', `kept ${kept.length} page${kept.length === 1 ? '' : 's'}${dropped.length ? `, deleted ${dropped.length} as junk` : ''}`)
|
|
472
|
+
} catch (e) {
|
|
473
|
+
if (e.name === 'AbortError' || signal?.aborted) throw e
|
|
474
|
+
log('wrapup', `failed: ${e.message}`)
|
|
475
|
+
}
|
|
386
476
|
}
|
|
387
477
|
|
|
388
478
|
// /tidy_memory: merge duplicates, drop what's outdated, link related notes.
|
|
@@ -393,7 +483,7 @@ export class Session {
|
|
|
393
483
|
const room = Math.floor(this.strat.context * 0.5 * 3.5)
|
|
394
484
|
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
485
|
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
|
|
486
|
+
const summary = await this.memoryTask(this.#extractPrompt(''), prompt('agent/memory-tidy', { notes: text, broken }), signal)
|
|
397
487
|
this.ui.stopSpin()
|
|
398
488
|
this.ui.print(`${c.faint('✻')} ${c.muted(`Tidied the memory${summary && summary !== 'NONE' ? `: ${clip(summary.split('\n')[0], 140)}` : ''}`)}`)
|
|
399
489
|
return summary
|
|
@@ -456,9 +546,6 @@ const sizeOf = (m) =>
|
|
|
456
546
|
export const size = (messages) => messages.reduce((n, m) => n + sizeOf(m), 0)
|
|
457
547
|
const kTokens = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n))
|
|
458
548
|
|
|
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
549
|
// A chat template's tool-call markup in a reply's text (a tool call the model wrote out): outside
|
|
463
550
|
// code blocks, and the reply ends in it (an answer that only mentions such tags isn't one).
|
|
464
551
|
const MARKUP = /<\/?tool_call>|<\/?arg_(?:key|value)>|<function=[\w.-]+>|<\|[a-z_]+\|>/i
|
|
@@ -570,6 +657,28 @@ async function finalAnswer(s, signal, why = 'empty replies in a row') {
|
|
|
570
657
|
return text
|
|
571
658
|
}
|
|
572
659
|
|
|
660
|
+
// An older conversation called MCP tools by their own names (mcp__server__tool: each was offered as
|
|
661
|
+
// a tool then). Now they're all behind the one mcp tool, so those calls are rewritten as mcp calls:
|
|
662
|
+
// a request then names only tools it offers (some providers refuse one that doesn't). In place.
|
|
663
|
+
export function legacyMcpCalls(messages, direct) {
|
|
664
|
+
for (const m of messages ?? []) {
|
|
665
|
+
for (const t of m.tool_calls ?? []) {
|
|
666
|
+
const name = t.function?.name ?? ''
|
|
667
|
+
if (!name.startsWith('mcp__')) continue
|
|
668
|
+
const d = direct?.get(name)
|
|
669
|
+
const parts = /^mcp__(.+?)__(.+)$/.exec(name)
|
|
670
|
+
const server = d?.server ?? parts?.[1]
|
|
671
|
+
const tool = d?.tool ?? parts?.[2]
|
|
672
|
+
if (!server || !tool) continue
|
|
673
|
+
let args = {}
|
|
674
|
+
try {
|
|
675
|
+
args = JSON.parse(t.function.arguments || '{}')
|
|
676
|
+
} catch {}
|
|
677
|
+
t.function = { name: 'mcp', arguments: JSON.stringify({ server, tool, arguments: args }) }
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
573
682
|
// Every tool call needs its result right after it, and every result its call, or the API rejects
|
|
574
683
|
// the request (and it would be retried forever). Esc during a tool leaves a call without a result;
|
|
575
684
|
// trimming can leave a result without its call. Mends both, in place.
|
|
@@ -599,6 +708,7 @@ async function runNative(s, task, images, signal) {
|
|
|
599
708
|
// The model's thinking goes back with its steps while it works on a message (it keeps its plan
|
|
600
709
|
// from one tool call to the next), not into later messages.
|
|
601
710
|
for (const m of s.messages ?? []) delete m.reasoning_content
|
|
711
|
+
legacyMcpCalls(s.messages, s.mcpDirect)
|
|
602
712
|
// The system prompt is rebuilt for every message: files come and go, and a resumed chat's is
|
|
603
713
|
// from back then (it once told the model the project was empty after it had made files).
|
|
604
714
|
// Unchanged, it stays the same text, so a provider's prompt cache still holds.
|
|
@@ -632,8 +742,28 @@ async function runNative(s, task, images, signal) {
|
|
|
632
742
|
// schemas, takes most of the window): compacting again won't free anything, so not until it has
|
|
633
743
|
// grown by another 5% (not a summary request at every step).
|
|
634
744
|
const afterCompact = () => (s.compactFailedAt = used() >= strat.context * COMPACT_SHARE ? used() + Math.round(strat.context * 0.05) : 0)
|
|
635
|
-
//
|
|
636
|
-
|
|
745
|
+
// Over the current model's window and your list holds a model that can take the whole conversation:
|
|
746
|
+
// move to it instead of compacting — losing nothing beats summarizing when you have a roomier model.
|
|
747
|
+
// Scanned in your list order, so it picks your highest-priority model that fits; false when none of
|
|
748
|
+
// your other models has more room (then the caller compacts: use what's available).
|
|
749
|
+
const roomier = () => {
|
|
750
|
+
const r = client.rotation
|
|
751
|
+
if (!r || r.list.length < 2 || !s.windowOf) return false
|
|
752
|
+
const need = used()
|
|
753
|
+
for (let k = 0; k < r.list.length; k++) {
|
|
754
|
+
if (k === r.at) continue
|
|
755
|
+
const win = s.windowOf(r.list[k])
|
|
756
|
+
if (win > 0 && need <= win * COMPACT_SHARE) {
|
|
757
|
+
ui.print(c.dim(`↻ this chat (~${kTokens(need)}) is past ${client.model}'s window — moving to ${r.list[k].model} (holds ~${kTokens(win)})`))
|
|
758
|
+
client.switchTo(r.list[k], `context ~${kTokens(need)} > ${client.model} window`)
|
|
759
|
+
return true
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
return false
|
|
763
|
+
}
|
|
764
|
+
// Already that long from earlier messages: switch to a roomier model, or else compact first, so the
|
|
765
|
+
// new message stays word for word.
|
|
766
|
+
if (nearlyFull() && !roomier()) {
|
|
637
767
|
await s.compact({ signal, why: fullness() }).then(afterCompact, (e) => (e.name === 'AbortError' ? Promise.reject(e) : ui.warn(`could not compact: ${e.message}`)))
|
|
638
768
|
}
|
|
639
769
|
// only the memory notes this message matches go with it (the system prompt has just the tags)
|
|
@@ -641,8 +771,20 @@ async function runNative(s, task, images, signal) {
|
|
|
641
771
|
const sent = new Set(s.chat.sentNotes ?? [])
|
|
642
772
|
const key = (n) => `${n.scope}:${n.name}:${n.description}`
|
|
643
773
|
const notes = (s.memory?.relevant(task) ?? []).filter((n) => !sent.has(key(n)))
|
|
644
|
-
|
|
645
|
-
const
|
|
774
|
+
// pages already read for this project that match: titles only (the model opens one when needed)
|
|
775
|
+
const pages = s.isSub || !s.memory ? [] : findResearch(s.root, task, 6).filter((r) => r.kind !== 'search' && !sent.has(`research:${r.name}:${r.fetched}`))
|
|
776
|
+
s.chat.sentNotes = [...sent, ...notes.map(key), ...pages.map((r) => `research:${r.name}:${r.fetched}`)]
|
|
777
|
+
const guideSent = () => (s.chat.sentNotes ?? []).includes('guide:ui')
|
|
778
|
+
// the UI guide: once per conversation, with a message about a UI (else with the first UI file written)
|
|
779
|
+
const uiGuide = !sent.has('guide:ui') && UI_TASK.test(task)
|
|
780
|
+
if (uiGuide) s.chat.sentNotes = [...(s.chat.sentNotes ?? []), 'guide:ui']
|
|
781
|
+
const known = [
|
|
782
|
+
uiGuide && prompt('agent/ui-guide'),
|
|
783
|
+
notes.length && prompt('agent/memory-relevant', { notes: notes.map((n) => `[[${n.name}]] — ${n.description}`).join('\n') }),
|
|
784
|
+
pages.length && prompt('agent/research-known', { pages: pages.map((r) => `- ${r.title} — ${r.url} (read ${r.fetched}) → ${r.file}`).join('\n') }),
|
|
785
|
+
].filter(Boolean)
|
|
786
|
+
const text = known.length ? `${task}\n\n${known.join('\n\n')}` : task
|
|
787
|
+
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
788
|
const planning = ui.permission === 'plan'
|
|
647
789
|
// the research-first reminder: small models follow the user's message far more than the system
|
|
648
790
|
// prompt (not a helper's job, nor a program's own task with its own instructions)
|
|
@@ -668,28 +810,33 @@ async function runNative(s, task, images, signal) {
|
|
|
668
810
|
s.edits = 0 // successful file edits so far this message (to tell a real fix from a lucky rerun)
|
|
669
811
|
s.acted = false // used a tool this message (so a reply that only promises more is a premature stop)
|
|
670
812
|
let nudged = 0 // reminders sent this message about open todo items, a premature stop, or a Stop hook
|
|
813
|
+
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)
|
|
814
|
+
s.planAsked = false // asked for a plan before its first change, this message
|
|
815
|
+
// what changed and when it was last checked, this message: a change not run/tested since isn't done
|
|
816
|
+
Object.assign(s, { changed: new Set(), seq: 0, lastChangeAt: -1, lastCheckAt: -1, reviewedAt: -1 })
|
|
671
817
|
|
|
672
818
|
let empty = 0 // replies in a row with neither text nor tool calls
|
|
673
819
|
let looping = 0 // replies cut for going into a loop, this message
|
|
674
|
-
let stuck = null // why it's
|
|
820
|
+
let stuck = null // why it's going round in circles (then the next model takes over; nothing stops but Esc)
|
|
821
|
+
// Going round in circles: the next of your models carries on (a different model often gets out of
|
|
822
|
+
// it); with no other model, a warning, and it goes on being told what it repeats — only Esc stops it.
|
|
823
|
+
const handOver = (why) => {
|
|
824
|
+
const was = client.model
|
|
825
|
+
if (client.moveOn?.(`${was} ${why}`)) ui.warn(`${was} ${why}; handing over to ${client.model}`)
|
|
826
|
+
else ui.warn(`${was} ${why} — it carries on, told so; Esc stops it`)
|
|
827
|
+
}
|
|
675
828
|
let garbled = 0 // replies with a tool call written as text (template markup), this message
|
|
676
829
|
let movedOn = 0 // models given up on for that, in this message
|
|
677
830
|
let refitted = false // this step's conversation was just compacted for a smaller model the list moved on to
|
|
678
|
-
// No step limit: a long fix takes many steps, and Esc stops it. A caller can set one (--max-turns).
|
|
831
|
+
// No step limit (helpers too): a long fix takes many steps, and Esc stops it. A caller can set one (--max-turns).
|
|
679
832
|
for (let step = 0; ; step++) {
|
|
680
833
|
const tools = toolList()
|
|
681
|
-
// a helper has a budget: then it answers with what it has (one once searched the web for 40
|
|
682
|
-
// steps to answer which of two numbers is bigger)
|
|
683
|
-
if (s.isSub && step >= HELPER_STEPS) {
|
|
684
|
-
ui.warn(`${client.model} took ${HELPER_STEPS} steps; asking it for its answer`)
|
|
685
|
-
return finalAnswer(s, signal, `helper: ${HELPER_STEPS} steps`)
|
|
686
|
-
}
|
|
687
834
|
if (s.maxTurns && step >= s.maxTurns) {
|
|
688
835
|
ui.warn(`stopped after ${s.maxTurns} steps (--max-turns); say "continue" to go on`)
|
|
689
836
|
throw Object.assign(new Error(`stopped after ${s.maxTurns} steps (--max-turns)`), { maxTurns: true })
|
|
690
837
|
}
|
|
691
838
|
// after a failed compaction, the next try waits until the conversation has grown by 5% of the window
|
|
692
|
-
if (nearlyFull() && step !== s.compactedAt) {
|
|
839
|
+
if (nearlyFull() && step !== s.compactedAt && !roomier()) {
|
|
693
840
|
s.compactedAt = step
|
|
694
841
|
await s.compact({ signal, midTask: true, task, why: fullness() }).then(
|
|
695
842
|
afterCompact,
|
|
@@ -741,10 +888,9 @@ async function runNative(s, task, images, signal) {
|
|
|
741
888
|
// the reply went round and round (client.js cut it): told so, and asked again
|
|
742
889
|
if (res.looped) {
|
|
743
890
|
if (++looping > 3) {
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
}
|
|
747
|
-
ui.warn(`${client.model} went into a loop; cut, and asked again`)
|
|
891
|
+
handOver(`keeps going into a loop`)
|
|
892
|
+
looping = 0
|
|
893
|
+
} else ui.warn(`${client.model} went into a loop; cut, and asked again`)
|
|
748
894
|
if (res.content.trim()) s.messages.push({ role: 'assistant', content: res.content })
|
|
749
895
|
s.messages.push({ role: 'user', content: prompt('agent/looped', { sample: res.looped }) })
|
|
750
896
|
continue
|
|
@@ -774,7 +920,7 @@ async function runNative(s, task, images, signal) {
|
|
|
774
920
|
res.content = res.content.slice(0, markup.index).trim()
|
|
775
921
|
s.messages[s.messages.length - 1] = { ...s.messages.at(-1), content: res.content }
|
|
776
922
|
}
|
|
777
|
-
if (res.toolCalls.length) s.acted = true // did real work this message, for the premature-stop check
|
|
923
|
+
if (res.toolCalls.length) s.acted = sinceNudge = true // did real work this message, for the premature-stop check
|
|
778
924
|
s.onEvent?.({ type: 'assistant', model: `${client.provider}/${client.model}`, content: res.content, reasoning: res.reasoning, toolCalls: res.toolCalls }) // headless output
|
|
779
925
|
if (!res.toolCalls.length && !res.content?.trim()) {
|
|
780
926
|
// Nothing at all (seen after a failed tool call): not an answer. The same request again
|
|
@@ -803,9 +949,13 @@ async function runNative(s, task, images, signal) {
|
|
|
803
949
|
s.messages.push({ role: 'user', content: look })
|
|
804
950
|
continue
|
|
805
951
|
}
|
|
806
|
-
const more =
|
|
807
|
-
if (!more)
|
|
952
|
+
const more = sinceNudge && !s.isSub && ((await notDone(s, signal, nudged > 0, res.content)) ?? (await review(s, task, res.content, signal)))
|
|
953
|
+
if (!more) {
|
|
954
|
+
s.wrapUpLater?.(task, res.content) // after the answer, beside what comes next
|
|
955
|
+
return res.content
|
|
956
|
+
}
|
|
808
957
|
nudged++
|
|
958
|
+
sinceNudge = false
|
|
809
959
|
s.messages.push({ role: 'user', content: more })
|
|
810
960
|
continue
|
|
811
961
|
}
|
|
@@ -847,8 +997,8 @@ async function runNative(s, task, images, signal) {
|
|
|
847
997
|
? `${args.server} · ${args.tool ?? ''}`
|
|
848
998
|
: name === 'memory'
|
|
849
999
|
? `${args.action} ${args.name ? `[[${args.name}]]` : (args.query ?? '')}`
|
|
850
|
-
: name === 'manage'
|
|
851
|
-
? [args.action, args.kind, args.name].filter(Boolean).join(' ')
|
|
1000
|
+
: name === 'manage' || name === 'background'
|
|
1001
|
+
? [args.action, args.kind, args.name, args.id && `#${args.id}`].filter(Boolean).join(' ')
|
|
852
1002
|
: name === 'agent'
|
|
853
1003
|
? [args.model && `${args.model}:`, args.description].filter(Boolean).join(' ')
|
|
854
1004
|
: name === 'todo' || name === 'ask_user'
|
|
@@ -856,10 +1006,22 @@ async function runNative(s, task, images, signal) {
|
|
|
856
1006
|
: (args.path ?? args.url ?? args.query ?? args.filter ?? args.name ?? '')
|
|
857
1007
|
if (name !== 'run_command' && !together.has(call.id)) ui.step(name, clip(detail, 80))
|
|
858
1008
|
const pre = early.get(call.id)
|
|
859
|
-
|
|
1009
|
+
// the first change to the files with no plan yet (this message, or still open from an earlier one):
|
|
1010
|
+
// not made — the plan first, then the change again. Once a message; not a helper's (its job is its plan)
|
|
1011
|
+
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')
|
|
1012
|
+
if (planFirst) s.planAsked = true
|
|
1013
|
+
const refused = planFirst ? prompt('agent/plan-first') : pre ? (pre.refused ?? null) : !together.has(call.id) && args && allowed(s, name) ? guard.before(name, args) : null
|
|
860
1014
|
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')
|
|
861
1015
|
if (!refused && args) out += guard.after(name, args, out)
|
|
862
1016
|
if (guard.stuck) stuck ??= guard.stuck
|
|
1017
|
+
if (args && !refused) {
|
|
1018
|
+
s.seq++
|
|
1019
|
+
if (EDITS.has(name) && !failed(out)) {
|
|
1020
|
+
s.lastChangeAt = s.seq
|
|
1021
|
+
if (args.path) s.changed.add(String(args.path))
|
|
1022
|
+
} else if (CHECKS.has(name)) s.lastCheckAt = s.seq // ran something: a check of what changed (the model judges its result)
|
|
1023
|
+
}
|
|
1024
|
+
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) })
|
|
863
1025
|
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
|
|
864
1026
|
// the same call again and again in a row (a weak model going round): told at the third, stopped at the fifth
|
|
865
1027
|
const sig = `${name} ${call.function.arguments}`
|
|
@@ -871,15 +1033,33 @@ async function runNative(s, task, images, signal) {
|
|
|
871
1033
|
else if (name === 'agent' && !failed(out)) ui.result(`${s.ui.permission === 'plan' ? 'planned' : 'done'}: ${clip(out.split('\n').find((l) => l.trim()) ?? '', 100)}`)
|
|
872
1034
|
else if (failed(out)) ui.result(clip(out, 120))
|
|
873
1035
|
client.refresh?.() // a setting changed while the tool ran (the window): its result is cut by the new one
|
|
874
|
-
|
|
1036
|
+
// the first UI file written in a conversation that hasn't had the UI guide: it comes with the result
|
|
1037
|
+
if (EDITS.has(name) && args && UI_FILE.test(String(args.path ?? '')) && !failed(out) && !guideSent()) {
|
|
1038
|
+
s.chat.sentNotes = [...(s.chat.sentNotes ?? []), 'guide:ui']
|
|
1039
|
+
out += `\n\n${prompt('agent/ui-guide')}`
|
|
1040
|
+
}
|
|
1041
|
+
// every sizable result is saved as it comes (a web page already is, in research): later it can
|
|
1042
|
+
// become a pointer to its file in the conversation without anything being lost
|
|
1043
|
+
if (out.length > SAVE_AT && name !== 'read_file' && !s.chat.outputs?.[call.id]) {
|
|
1044
|
+
const file = saveOutput(s.chat?.id, name, out)
|
|
1045
|
+
if (file) (s.chat.outputs ??= {})[call.id] = file
|
|
1046
|
+
}
|
|
1047
|
+
const msg = { role: 'tool', tool_call_id: call.id, content: fitResult(s, name, out, s.chat.outputs?.[call.id]) }
|
|
875
1048
|
if (name === 'read_file' && args && !args.start_line && !args.end_line && !failed(out)) replaceCopy(s, args.path, msg)
|
|
876
1049
|
s.messages.push(msg)
|
|
877
1050
|
s.onEvent?.({ type: 'tool', id: call.id, name, output: out })
|
|
878
1051
|
}
|
|
879
1052
|
trimOldResults(s)
|
|
1053
|
+
const ended = newlyEnded(s.root) // background commands that exited meanwhile: the model hears it now
|
|
1054
|
+
if (ended.length) {
|
|
1055
|
+
for (const j of ended) ui.step('background', `#${j.id} ${clip(j.command, 60)} exited with ${j.code}`)
|
|
1056
|
+
s.messages.push({ role: 'user', content: prompt('agent/background-ended', { jobs: ended.map(jobLine).join('\n') }) })
|
|
1057
|
+
}
|
|
880
1058
|
if (stuck) {
|
|
881
|
-
|
|
882
|
-
|
|
1059
|
+
handOver(stuck)
|
|
1060
|
+
stuck = null
|
|
1061
|
+
inRow = 0
|
|
1062
|
+
guard.calm()
|
|
883
1063
|
}
|
|
884
1064
|
// screenshots from MCP tools: tool results are text only, so images follow as a message
|
|
885
1065
|
if (s.pendingImages?.length) {
|
|
@@ -896,6 +1076,13 @@ async function runNative(s, task, images, signal) {
|
|
|
896
1076
|
// (ten calls already made) stops it.
|
|
897
1077
|
// before: what to send back instead of running it (the earlier result), or null; after: a note for its result.
|
|
898
1078
|
const EDITS = new Set(['edit_file', 'write_file', 'append_file', 'apply_patch'])
|
|
1079
|
+
// Tools that run or look at what was made (a command, a test, a browser, a helper): a check after a change.
|
|
1080
|
+
const CHECKS = new Set(['run_command', 'mcp', 'agent', 'lsp'])
|
|
1081
|
+
// Files only read by people (a change there needs no run to check it).
|
|
1082
|
+
const DOC_FILE = /\.(md|mdx|txt|rst|adoc)$/i
|
|
1083
|
+
// A message about something people look at (gets the UI guide), and a file that is one.
|
|
1084
|
+
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
|
|
1085
|
+
const UI_FILE = /\.(html?|css|scss|sass|less|jsx|tsx|vue|svelte|astro)$/i
|
|
899
1086
|
// Tools that only look (nothing changes): several in one reply run at the same time.
|
|
900
1087
|
const LOOKUPS = new Set(['web_search', 'web_fetch', 'read_file', 'search', 'list_files', 'find_command', 'lsp'])
|
|
901
1088
|
export function newGuard() {
|
|
@@ -904,10 +1091,15 @@ export function newGuard() {
|
|
|
904
1091
|
let failing = 0
|
|
905
1092
|
let repeats = 0
|
|
906
1093
|
const g = { stuck: null }
|
|
1094
|
+
g.calm = () => { // after a handover or a warning: counted again from nothing
|
|
1095
|
+
g.stuck = null
|
|
1096
|
+
repeats = 0
|
|
1097
|
+
failing = 0
|
|
1098
|
+
}
|
|
907
1099
|
const words = (q) => [...new Set(String(q ?? '').toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [])].sort().join(' ')
|
|
908
1100
|
const keyOf = (name, a) => {
|
|
909
|
-
if (name === 'web_search') return `search: ${words(a.query)}`
|
|
910
|
-
if (name === 'web_fetch') return `page: ${String(a.url ?? '').toLowerCase().replace(/^https?:\/\/(www\.)?/, '').replace(/\/+$/, '')} @${a.start ?? 0}`
|
|
1101
|
+
if (name === 'web_search') return `search: ${words(a.query)}${a.fresh ? ' (fresh)' : ''}`
|
|
1102
|
+
if (name === 'web_fetch') return `page: ${String(a.url ?? '').toLowerCase().replace(/^https?:\/\/(www\.)?/, '').replace(/\/+$/, '')} @${a.start ?? 0} ${words(a.look_for)}`
|
|
911
1103
|
if (['run_command', 'read_file', 'search', 'list_files', 'find_command', 'lsp'].includes(name)) return `${name} ${JSON.stringify(a)} @${epoch}`
|
|
912
1104
|
return null
|
|
913
1105
|
}
|
|
@@ -939,9 +1131,9 @@ export function newGuard() {
|
|
|
939
1131
|
|
|
940
1132
|
// The pages this message wrote or restyled (an .html written, or one using a .css written),
|
|
941
1133
|
// opened in the built-in browser (chrome-devtools): a screenshot at desktop width (the whole page)
|
|
942
|
-
// and at phone width, given to the model to check against its brief and fix.
|
|
943
|
-
//
|
|
944
|
-
// yours that can.
|
|
1134
|
+
// and at phone width, given to the model to check against its brief and fix. Again whenever pages
|
|
1135
|
+
// changed since the last look; nothing when there's no browser. A model that can't see gets them
|
|
1136
|
+
// described by one of yours that can.
|
|
945
1137
|
// Problems found in a built page without a browser: JavaScript that doesn't parse, and the Tailwind
|
|
946
1138
|
// CDN used with @apply/@layer (it throws "Cannot apply unknown utility class" at runtime and the
|
|
947
1139
|
// styling breaks). These are caught even when the browser can't be opened.
|
|
@@ -1037,13 +1229,26 @@ async function learnFromFixes(s, fixed, signal) {
|
|
|
1037
1229
|
const near = s.memory.search(`tag:lesson ${tags.join(' ')}`).find((n) => n.body.toLowerCase().includes(error.replace(/^[^:]*:\s*/, '').toLowerCase().slice(0, 30)))
|
|
1038
1230
|
if (near) continue // already learned
|
|
1039
1231
|
let rule = ''
|
|
1232
|
+
let scope = 'global'
|
|
1040
1233
|
try {
|
|
1041
|
-
|
|
1042
|
-
|
|
1234
|
+
const was = s.client.purpose
|
|
1235
|
+
s.client.purpose = 'lesson'
|
|
1236
|
+
let reply
|
|
1237
|
+
try {
|
|
1238
|
+
reply = await s.client.chat({ messages: [{ role: 'user', content: prompt('agent/lesson', { error }) }] }, { signal })
|
|
1239
|
+
} finally {
|
|
1240
|
+
s.client.purpose = was
|
|
1241
|
+
}
|
|
1242
|
+
const said = reply.content.trim().split('\n').filter((l) => l.trim())
|
|
1243
|
+
rule = (said.find((l) => !/^\s*\W*scope\s*:/i.test(l)) ?? '').replace(/^\s*(?:\d+[.)]|[-*])\s*/, '').replace(/^["'\s-]+|["']+$/g, '').slice(0, 200)
|
|
1244
|
+
if (/scope\s*:\W*project/i.test(said.join('\n'))) scope = 'project'
|
|
1245
|
+
} catch (e) {
|
|
1246
|
+
if (e.name === 'AbortError') throw e
|
|
1247
|
+
}
|
|
1043
1248
|
if (!rule || rule.length < 10) rule = error.replace(/^[^:]*:\s*/, '') // the model couldn't phrase it: keep the error's own wording
|
|
1044
|
-
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
|
|
1045
|
-
s.ui.step('learned', rule.slice(0, 90))
|
|
1046
|
-
log('learn', `saved lesson [[${name}]] (#${tags.join(' #')}): ${rule}`)
|
|
1249
|
+
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 })
|
|
1250
|
+
s.ui.step('learned', `${rule.slice(0, 90)}${scope === 'project' ? ' (this project)' : ''}`)
|
|
1251
|
+
log('learn', `saved lesson [[${name}]] (${scope}, #${tags.join(' #')}): ${rule}`)
|
|
1047
1252
|
}
|
|
1048
1253
|
}
|
|
1049
1254
|
|
|
@@ -1062,14 +1267,14 @@ const SMOKE_TEST = `async () => {
|
|
|
1062
1267
|
}
|
|
1063
1268
|
const btns = [...document.querySelectorAll('button, [role=button], input[type=button], input[type=submit], a[href^="#"], a:not([href]), [onclick]')]
|
|
1064
1269
|
let controls = btns.length
|
|
1065
|
-
for (const el of btns
|
|
1270
|
+
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)) }
|
|
1066
1271
|
for (const cb of document.querySelectorAll('input[type=checkbox], input[type=radio]')) { controls++; try { cb.click() } catch (e) { push('toggle: ' + e.message) } }
|
|
1067
1272
|
await new Promise((r) => setTimeout(r, 200))
|
|
1068
1273
|
return JSON.stringify({ errors: errs, controls })
|
|
1069
1274
|
}`
|
|
1070
1275
|
|
|
1071
1276
|
async function lookAtUi(s, signal) {
|
|
1072
|
-
if (!s.uiTouched?.size || s.
|
|
1277
|
+
if (!s.uiTouched?.size || s.ui.permission === 'plan') return null // again whenever pages changed since the last look
|
|
1073
1278
|
const touched = [...s.uiTouched]
|
|
1074
1279
|
s.uiTouched.clear()
|
|
1075
1280
|
const styles = touched.filter((f) => /\.css$/i.test(f)).map((f) => path.basename(f))
|
|
@@ -1081,7 +1286,7 @@ async function lookAtUi(s, signal) {
|
|
|
1081
1286
|
} catch {}
|
|
1082
1287
|
}
|
|
1083
1288
|
}
|
|
1084
|
-
const shown = [...new Set(pages)].filter((f) => fs.existsSync(path.join(s.root, f)))
|
|
1289
|
+
const shown = [...new Set(pages)].filter((f) => fs.existsSync(path.join(s.root, f)))
|
|
1085
1290
|
if (!shown.length) return null
|
|
1086
1291
|
s.uiLooks++
|
|
1087
1292
|
const browser = s.mcp?.get?.('chrome-devtools')
|
|
@@ -1112,7 +1317,7 @@ async function lookAtUi(s, signal) {
|
|
|
1112
1317
|
if (blob) {
|
|
1113
1318
|
try {
|
|
1114
1319
|
const r = JSON.parse(blob[0])
|
|
1115
|
-
for (const err of r.errors
|
|
1320
|
+
for (const err of r.errors) errors.push(`${rel}: a control is broken — ${err}`)
|
|
1116
1321
|
log('look', `${rel}: exercised ${r.controls} control(s), ${r.errors.length} broke`)
|
|
1117
1322
|
} catch (e) {
|
|
1118
1323
|
log('look', `smoke parse: ${e.message}`)
|
|
@@ -1133,6 +1338,7 @@ async function lookAtUi(s, signal) {
|
|
|
1133
1338
|
done?.()
|
|
1134
1339
|
s.ui.stopSpin()
|
|
1135
1340
|
}
|
|
1341
|
+
if (opened) s.lastCheckAt = s.seq ?? 0 // it ran in a browser: what changed was checked
|
|
1136
1342
|
if (errors.length) log('look', `problems found: ${errors.join(' | ')}`)
|
|
1137
1343
|
// Learn: a hard error that was there last look and is gone now was fixed — save the lesson so it
|
|
1138
1344
|
// isn't made again (recalled on later tasks about the same tech). Only in the main agent.
|
|
@@ -1161,7 +1367,13 @@ async function lookAtUi(s, signal) {
|
|
|
1161
1367
|
s.ui.spinner(`${t.model} is reviewing ${shown.join(', ')}`)
|
|
1162
1368
|
try {
|
|
1163
1369
|
const { client } = t === self ? { client: s.client } : await s.engineFor(t)
|
|
1164
|
-
|
|
1370
|
+
const was = client.purpose
|
|
1371
|
+
client.purpose = 'ui-review'
|
|
1372
|
+
try {
|
|
1373
|
+
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()
|
|
1374
|
+
} finally {
|
|
1375
|
+
client.purpose = was
|
|
1376
|
+
}
|
|
1165
1377
|
if (found) break
|
|
1166
1378
|
} catch (e) {
|
|
1167
1379
|
if (signal?.aborted) throw e
|
|
@@ -1190,12 +1402,24 @@ const PROMISED_MORE =
|
|
|
1190
1402
|
|
|
1191
1403
|
// Is the task really done, or did the model stop early? Open todo items, or (after it did real work)
|
|
1192
1404
|
// a reply that only promises more, get one nudge to keep going. Then any Stop hook. null = truly done.
|
|
1193
|
-
async function notDone(s, signal, again, reply = '') {
|
|
1405
|
+
export async function notDone(s, signal, again, reply = '') {
|
|
1194
1406
|
const open = s.todoTouched && s.ui.permission !== 'plan' ? (s.chat.todos ?? []).filter((t) => t.status !== 'completed') : [] // plan mode: they wait for the approval
|
|
1195
1407
|
if (open.length) {
|
|
1196
1408
|
log('task', `stopped with ${open.length} open todo item(s); reminding`)
|
|
1197
1409
|
return prompt('agent/todo-unfinished', { items: open.map((t) => `- ${t.content}`).join('\n') })
|
|
1198
1410
|
}
|
|
1411
|
+
// changed files and hasn't run anything since: not proven to work
|
|
1412
|
+
const changed = [...(s.changed ?? [])]
|
|
1413
|
+
if (changed.length && s.lastCheckAt < s.lastChangeAt && !changed.every((f) => DOC_FILE.test(f)) && s.ui.permission !== 'plan') {
|
|
1414
|
+
log('task', `finished with changes not checked since (${changed.join(', ')}); asking for a check`)
|
|
1415
|
+
return prompt('agent/unchecked', { files: changed.join(', ') })
|
|
1416
|
+
}
|
|
1417
|
+
// says it made files that aren't there
|
|
1418
|
+
const missing = missingFiles(s.root, reply)
|
|
1419
|
+
if (missing.length) {
|
|
1420
|
+
log('task', `the answer names files that don't exist: ${missing.join(', ')}`)
|
|
1421
|
+
return prompt('agent/missing-files', { files: missing.join(', ') })
|
|
1422
|
+
}
|
|
1199
1423
|
if (s.acted && reply && PROMISED_MORE.test(reply)) {
|
|
1200
1424
|
log('task', 'reply names a next step but no tool call followed; nudging to finish')
|
|
1201
1425
|
return prompt('agent/stopped-early')
|
|
@@ -1204,21 +1428,149 @@ async function notDone(s, signal, again, reply = '') {
|
|
|
1204
1428
|
return hook.block ? prompt('agent/hook-stop', { reason: hook.block }) : null
|
|
1205
1429
|
}
|
|
1206
1430
|
|
|
1431
|
+
// Files the final answer says were made, that aren't in the project: a path in backticks, or one
|
|
1432
|
+
// with a folder, with a source/config/doc extension, while the answer says it created or wrote
|
|
1433
|
+
// something. A name that's anywhere in the project (by its file name) counts as there.
|
|
1434
|
+
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'
|
|
1435
|
+
export function missingFiles(root, reply) {
|
|
1436
|
+
const text = String(reply ?? '')
|
|
1437
|
+
if (!/\b(created?|wrote|written|added|saved|generated|made|new file)\b/i.test(text)) return []
|
|
1438
|
+
const named = new Set()
|
|
1439
|
+
for (const m of text.matchAll(new RegExp(`\`([^\`\\s]+\\.(?:${FILE_EXT}))\``, 'gi'))) named.add(m[1])
|
|
1440
|
+
for (const m of text.matchAll(new RegExp(`(?:^|[\\s(])((?:[\\w.-]+/)+[\\w.-]+\\.(?:${FILE_EXT}))(?=[\\s),.:;]|$)`, 'gim'))) named.add(m[1])
|
|
1441
|
+
const out = []
|
|
1442
|
+
let names = null
|
|
1443
|
+
for (const f of named) {
|
|
1444
|
+
if (/^(https?:|\/\/|~|\$)/.test(f) || path.isAbsolute(f)) continue
|
|
1445
|
+
if (fs.existsSync(path.join(root, f))) continue
|
|
1446
|
+
names ??= new Set(listFiles(root).map((x) => path.basename(x)))
|
|
1447
|
+
if (names.has(path.basename(f))) continue
|
|
1448
|
+
out.push(f)
|
|
1449
|
+
}
|
|
1450
|
+
return out
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
// Every folder in the project (relative paths), the ignored ones (.git, node_modules…) and
|
|
1454
|
+
// HeartCode's own left out: to tell the folders a task made.
|
|
1455
|
+
function foldersOf(root) {
|
|
1456
|
+
const out = new Set()
|
|
1457
|
+
const walk = (rel, depth) => {
|
|
1458
|
+
if (out.size > 20_000 || depth > 12) return
|
|
1459
|
+
let entries = []
|
|
1460
|
+
try {
|
|
1461
|
+
entries = fs.readdirSync(path.join(root, rel), { withFileTypes: true })
|
|
1462
|
+
} catch {
|
|
1463
|
+
return
|
|
1464
|
+
}
|
|
1465
|
+
for (const e of entries) {
|
|
1466
|
+
if (!e.isDirectory() || IGNORED_DIRS.has(e.name) || e.name === '.heartcode') continue
|
|
1467
|
+
const r = rel ? `${rel}/${e.name}` : e.name
|
|
1468
|
+
out.add(r)
|
|
1469
|
+
walk(r, depth + 1)
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
walk('', 0)
|
|
1473
|
+
return out
|
|
1474
|
+
}
|
|
1475
|
+
const IGNORED_DIRS = new Set(['.git', 'node_modules', 'dist', 'build', '.next', 'coverage', '.venv', 'venv', '__pycache__', 'target', '.cache', '.gradle', '.idea'])
|
|
1476
|
+
const isEmptyDir = (abs) => {
|
|
1477
|
+
try {
|
|
1478
|
+
return fs.readdirSync(abs).filter((f) => f !== '.DS_Store').length === 0
|
|
1479
|
+
} catch {
|
|
1480
|
+
return false
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1484
|
+
// A second look before it's called done, in a request of its own: another of your models when
|
|
1485
|
+
// there is one (fresh eyes), else this one, with nothing but the user's request, the plan, the
|
|
1486
|
+
// answer, the changes and what was run since. It answers YES (done right) or NO with what's wrong;
|
|
1487
|
+
// a NO goes back to the model to fix. Asked again only once files changed since its last look.
|
|
1488
|
+
// Returns what to tell the model, or null.
|
|
1489
|
+
export async function review(s, task, answer, signal) {
|
|
1490
|
+
if (s.isSub || !s.changed?.size || s.lastChangeAt <= s.reviewedAt || s.ui.permission === 'plan') return null
|
|
1491
|
+
s.reviewedAt = s.lastChangeAt
|
|
1492
|
+
const turn = s.chat.turns.at(-1)
|
|
1493
|
+
const diffs = []
|
|
1494
|
+
let room = 16_000
|
|
1495
|
+
for (const [rel, before] of Object.entries(turn?.files ?? {})) {
|
|
1496
|
+
let now = null
|
|
1497
|
+
try {
|
|
1498
|
+
now = fs.readFileSync(path.join(s.root, rel), 'utf8')
|
|
1499
|
+
} catch {}
|
|
1500
|
+
if (now === before) continue
|
|
1501
|
+
const text = before === null ? `${rel} (new file):\n${now ?? ''}` : now === null ? `${rel}: deleted` : renderDiff(diffLines(before, now), rel, false, 3, 400)
|
|
1502
|
+
const piece = clip(text, Math.min(5000, room))
|
|
1503
|
+
room -= piece.length
|
|
1504
|
+
diffs.push(piece)
|
|
1505
|
+
if (room <= 500) {
|
|
1506
|
+
diffs.push('(more changes not shown)')
|
|
1507
|
+
break
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
if (!diffs.length) return null
|
|
1511
|
+
const plan = (s.chat.todos ?? []).map((t) => `- [${t.status === 'completed' ? 'x' : ' '}] ${t.content}`).join('\n')
|
|
1512
|
+
const ran = (s.ran ?? []).slice(-15).map((r) => `- ${clip(r.command.replace(/\s+/g, ' '), 160)} → ${r.result}`).join('\n')
|
|
1513
|
+
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)' })
|
|
1514
|
+
const self = { provider: s.client.provider, model: s.client.model, self: true }
|
|
1515
|
+
const fails = (t) => s.failures?.[`${t.provider} ${t.model}`] ?? 0
|
|
1516
|
+
const others = (s.team?.() ?? []).filter((t) => t.tools !== false && !(t.provider === self.provider && t.model === self.model)).sort((a, b) => fails(a) - fails(b))
|
|
1517
|
+
for (const t of [...others.slice(0, 2), self]) {
|
|
1518
|
+
s.ui.spinner(`${t.model} is reviewing the work`)
|
|
1519
|
+
try {
|
|
1520
|
+
const { client } = t.self ? { client: s.client } : await s.engineFor(t)
|
|
1521
|
+
if (!t.self) client.retryIf = (e, attempt) => attempt < 2
|
|
1522
|
+
const was = client.purpose
|
|
1523
|
+
client.purpose = 'review'
|
|
1524
|
+
let said
|
|
1525
|
+
try {
|
|
1526
|
+
said = (await client.chat({ messages: [{ role: 'user', content: ask }] }, { signal })).content.trim()
|
|
1527
|
+
} finally {
|
|
1528
|
+
client.purpose = was
|
|
1529
|
+
}
|
|
1530
|
+
s.ui.stopSpin()
|
|
1531
|
+
log('review', `${t.model}: ${said}`)
|
|
1532
|
+
if (/^\W*yes\b/i.test(said)) {
|
|
1533
|
+
s.ui.step('review', `${t.model}: looks right`)
|
|
1534
|
+
return null
|
|
1535
|
+
}
|
|
1536
|
+
if (/^\W*no\b/i.test(said)) {
|
|
1537
|
+
const issues = said.replace(/^\W*no\b[\s.:—-]*/i, '').trim()
|
|
1538
|
+
s.ui.step('review', `${t.model}: ${clip(issues.split('\n').find((l) => l.trim()) ?? 'problems found', 90)}`)
|
|
1539
|
+
return prompt('agent/review-failed', { model: t.model, issues: issues || '(no details given)' })
|
|
1540
|
+
}
|
|
1541
|
+
log('review', `${t.model} didn't answer YES or NO; trying another`)
|
|
1542
|
+
} catch (e) {
|
|
1543
|
+
if (e.name === 'AbortError' || signal?.aborted) throw e
|
|
1544
|
+
log('review', `${t.model} couldn't review: ${e.message}`)
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
s.ui.stopSpin()
|
|
1548
|
+
return null
|
|
1549
|
+
}
|
|
1550
|
+
|
|
1207
1551
|
// A helper agent's view of the screen: its steps are labelled, and its replies (which go to the
|
|
1208
1552
|
// main agent) aren't shown as answers. Everything else is the main UI's.
|
|
1209
1553
|
// Its thinking is shown whole when its reply is in (helpers working at once don't mix), named.
|
|
1210
1554
|
// Questions to the user (confirm, pick, ask) wait their turn: helpers working at once ask one by one.
|
|
1211
1555
|
const asking = new WeakMap() // ui → the question being asked
|
|
1212
1556
|
function helperUI(ui, label) {
|
|
1557
|
+
// What the helper says is shown in full under its name. Held until its reply ends, then printed at
|
|
1558
|
+
// once: helpers run side by side, and streamed text from two would interleave.
|
|
1213
1559
|
const response = () => {
|
|
1214
1560
|
const t0 = Date.now()
|
|
1215
1561
|
let thought = ''
|
|
1562
|
+
let said = ''
|
|
1216
1563
|
return {
|
|
1217
1564
|
think: (t) => (thought += t ?? ''),
|
|
1218
|
-
text()
|
|
1565
|
+
text: (t) => (said += t ?? ''),
|
|
1219
1566
|
end() {
|
|
1220
|
-
if (
|
|
1221
|
-
|
|
1567
|
+
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, ' ')))}` : ''))
|
|
1568
|
+
if (!said.trim()) return
|
|
1569
|
+
ui.print(` ${c.bright(c.bold('●'))} ${c.bold(label)}`)
|
|
1570
|
+
let block = new Block((x) => ui.write(x), { marker: ' ', style: c.text })
|
|
1571
|
+
if (color) block = new Markdown(block, c.text)
|
|
1572
|
+
block.push(said.trim())
|
|
1573
|
+
block.end()
|
|
1222
1574
|
},
|
|
1223
1575
|
}
|
|
1224
1576
|
}
|
|
@@ -1244,26 +1596,48 @@ export { allowed }
|
|
|
1244
1596
|
const shortened = new WeakSet() // kept outside the messages: providers reject unknown message fields
|
|
1245
1597
|
|
|
1246
1598
|
// How long a tool result may be in the conversation: a tenth of the window, 4k to 100k characters
|
|
1247
|
-
// (Claude Code allows about 25k tokens). A longer one: its start, and the whole of it
|
|
1248
|
-
//
|
|
1249
|
-
export function fitResult(s, name, out) {
|
|
1599
|
+
// (Claude Code allows about 25k tokens). A longer one: its start, and the whole of it in a file the
|
|
1600
|
+
// model can read in parts (read_file, search), as Claude Code does. file: where it's saved already.
|
|
1601
|
+
export function fitResult(s, name, out, file) {
|
|
1250
1602
|
const max = Math.max(4000, Math.min(100_000, Math.floor((s.strat.context * 3.5 * 0.1) / (s.strat.ratio ?? 1))))
|
|
1251
1603
|
if (out.length <= max) return out
|
|
1252
|
-
|
|
1604
|
+
file ??= saveOutput(s.chat?.id, name, out)
|
|
1253
1605
|
log('tool', `${name}: ${out.length} characters, ${max} shown${file ? `; all of it in ${file}` : ''}`)
|
|
1254
1606
|
return `${out.slice(0, max)}\n…\n${prompt('agent/output-cut', { shown: max, total: out.length, file })}`
|
|
1255
1607
|
}
|
|
1256
1608
|
|
|
1257
|
-
//
|
|
1258
|
-
|
|
1259
|
-
//
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1609
|
+
// Results longer than this are saved to a file when they come (so they can leave the conversation later).
|
|
1610
|
+
const SAVE_AT = 1500
|
|
1611
|
+
// What a tool call was, in a few words: "web_fetch https://…", "run_command npm test".
|
|
1612
|
+
function callOf(messages, id) {
|
|
1613
|
+
for (const m of messages) {
|
|
1614
|
+
const t = m.tool_calls?.find((x) => x.id === id)
|
|
1615
|
+
if (!t) continue
|
|
1616
|
+
let a = {}
|
|
1617
|
+
try {
|
|
1618
|
+
a = JSON.parse(t.function.arguments || '{}')
|
|
1619
|
+
} catch {}
|
|
1620
|
+
const what = a.server ? `${a.server} · ${a.tool ?? ''}` : (a.path ?? a.url ?? a.command ?? a.query ?? a.description ?? '')
|
|
1621
|
+
return `${t.function.name}${what ? ` ${clip(String(what).replace(/\s+/g, ' '), 120)}` : ''}`
|
|
1622
|
+
}
|
|
1623
|
+
return 'a tool'
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
// The conversation carries only the newest results whole: the model decides what else it needs and
|
|
1627
|
+
// reads it from the files (every sizable result is saved when it comes; web pages are in the
|
|
1628
|
+
// project's research). Once there are more than `most` long ones, all but the newest `keep` become a
|
|
1629
|
+
// pointer: what the call was, how long, where it's saved, and its first lines. All at once, so a
|
|
1630
|
+
// provider's prompt cache (the conversation's unchanged start) is broken rarely, not every step.
|
|
1631
|
+
// An older conversation's results (no file yet) are saved now, before they're cut.
|
|
1632
|
+
export function trimOldResults(s, keep = 4, most = 8) {
|
|
1633
|
+
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))
|
|
1263
1634
|
if (long.length <= most) return
|
|
1264
1635
|
for (const m of long.slice(0, -keep)) {
|
|
1265
|
-
const
|
|
1266
|
-
|
|
1636
|
+
const call = callOf(s.messages, m.tool_call_id)
|
|
1637
|
+
const read = /^read_file /.test(call) ? call.slice('read_file '.length) : '' // a project file: read it again
|
|
1638
|
+
const file = read || s.chat.outputs?.[m.tool_call_id] || saveOutput(s.chat?.id, 'older', m.content)
|
|
1639
|
+
if (file && !read) (s.chat.outputs ??= {})[m.tool_call_id] = file
|
|
1640
|
+
m.content = `${prompt('agent/output-old', { call, total: m.content.length, file })}\n${m.content.slice(0, 300)}\n…`
|
|
1267
1641
|
shortened.add(m)
|
|
1268
1642
|
}
|
|
1269
1643
|
log('tool', `older tool output cut: ${long.length - keep} results`)
|
|
@@ -1305,3 +1679,50 @@ function attachNamed(s, task) {
|
|
|
1305
1679
|
}
|
|
1306
1680
|
if (calls.length) s.messages.push({ role: 'assistant', content: '', tool_calls: calls }, ...results)
|
|
1307
1681
|
}
|
|
1682
|
+
|
|
1683
|
+
// /context: what the next request carries, part by part, in tokens (estimated, by this model's
|
|
1684
|
+
// ratio of counted to estimated; the server's count of the last request beside it), and the
|
|
1685
|
+
// biggest single pieces. Returns { total, window, compactAt, counted, parts: [{ name, tokens, note }], biggest: [{ tokens, what, ago }] }.
|
|
1686
|
+
export function contextReport(s) {
|
|
1687
|
+
const ratio = s.strat?.ratio ?? 1
|
|
1688
|
+
const tok = (x) => Math.round(est(typeof x === 'string' ? x : JSON.stringify(x ?? '')) * ratio)
|
|
1689
|
+
const msgs = s.messages ?? []
|
|
1690
|
+
const tasks = (s.chat.turns ?? []).map((t) => String(t.task ?? '').slice(0, 60)).filter(Boolean)
|
|
1691
|
+
const tools = [...TOOL_DEFS, ...extraTools(s)].filter((f) => allowed(s, f.name))
|
|
1692
|
+
const parts = { system: 0, you: 0, notes: 0, replies: 0, results: 0, pointers: 0 }
|
|
1693
|
+
let whole = 0
|
|
1694
|
+
let cut = 0
|
|
1695
|
+
const pieces = []
|
|
1696
|
+
msgs.forEach((m, i) => {
|
|
1697
|
+
const n = Math.round(estMessages([m]) * ratio)
|
|
1698
|
+
const ago = msgs.length - 1 - i
|
|
1699
|
+
if (i === 0 && (m.role === 'system' || s.strat?.mergeSystem)) return void (parts.system += n)
|
|
1700
|
+
if (i === 1 && s.strat?.mergeSystem && m.role === 'assistant') return void (parts.system += n)
|
|
1701
|
+
if (m.role === 'tool') {
|
|
1702
|
+
const old = typeof m.content === 'string' && /^\[older output/.test(m.content)
|
|
1703
|
+
old ? (parts.pointers += n, cut++) : (parts.results += n, whole++)
|
|
1704
|
+
pieces.push({ tokens: n, what: `${callOf(msgs, m.tool_call_id)} (result${old ? ', a pointer' : ''})`, ago })
|
|
1705
|
+
} else if (m.role === 'assistant') {
|
|
1706
|
+
parts.replies += n
|
|
1707
|
+
pieces.push({ tokens: n, what: 'a model reply', ago })
|
|
1708
|
+
} else {
|
|
1709
|
+
const text = typeof m.content === 'string' ? m.content : (m.content ?? []).map((p) => p.text ?? '').join(' ')
|
|
1710
|
+
const yours = tasks.some((t) => text.startsWith(t))
|
|
1711
|
+
yours ? (parts.you += n) : (parts.notes += n)
|
|
1712
|
+
pieces.push({ tokens: n, what: yours ? `your message "${clip(text.split('\n')[0], 50)}"` : `a note to the model "${clip(text.split('\n')[0], 50)}"`, ago })
|
|
1713
|
+
}
|
|
1714
|
+
})
|
|
1715
|
+
const toolTokens = tok(tools.map((f) => ({ type: 'function', function: f })))
|
|
1716
|
+
const list = [
|
|
1717
|
+
{ name: 'system prompt', tokens: parts.system },
|
|
1718
|
+
{ name: `tools (${tools.length})`, tokens: toolTokens },
|
|
1719
|
+
{ name: 'your messages', tokens: parts.you },
|
|
1720
|
+
{ name: 'notes to the model', tokens: parts.notes, note: 'summaries, guides, reminders, saved notes found' },
|
|
1721
|
+
{ name: 'model replies', tokens: parts.replies },
|
|
1722
|
+
{ name: 'tool results', tokens: parts.results, note: `${whole} whole` },
|
|
1723
|
+
{ name: 'older results', tokens: parts.pointers, note: `${cut} shortened to pointers to their files` },
|
|
1724
|
+
]
|
|
1725
|
+
const total = list.reduce((a, p) => a + p.tokens, 0)
|
|
1726
|
+
const window = s.strat?.context ?? 0
|
|
1727
|
+
return { total, window, compactAt: Math.round(window * COMPACT_SHARE), counted: s.counted?.tokens ?? 0, parts: list, biggest: pieces.sort((a, b) => b.tokens - a.tokens).slice(0, 5) }
|
|
1728
|
+
}
|