heartcode 0.1.59 → 0.1.62

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
@@ -5,15 +5,19 @@ import { prompt, userInstructions } from './prompts.js'
5
5
  import { newChat } from './sessions.js'
6
6
  import { skillFiles, readSkillFile } from './skills.js'
7
7
  import path from 'node:path'
8
- import { est, estMessages, Client, tokensOf, COMPACT_SHARE } from './client.js'
8
+ import { fileURLToPath } from 'node:url'
9
+ import { est, estMessages, Client, tokensOf, COMPACT_SHARE, family } from './client.js'
10
+ import { scoreOf } from './rankings.js'
11
+ import { pageCheck } from './check.js'
9
12
  import { runGuided } from './guided.js'
10
13
  import { markUsed, removeResearch, findResearch } from './research.js'
11
- import { TOOL_DEFS, PLAN_HIDDEN, folderView, readOnlyCommand, searchesOutside, extraTools, runTool, listFiles, namedFiles, readFileTool, clip, allowed, loadMcpTools, saveOutput, isSavedOutput, runningCall, imageUrl, MAX_IMAGE, failed, refusal, noteNamedPaths, sendTodos } from './tools.js'
14
+ import { TOOL_DEFS, PLAN_HIDDEN, folderView, readOnlyCommand, searchesOutside, extraTools, runTool, listFiles, namedFiles, readFileTool, clip, allowed, loadMcpTools, saveOutput, isSavedOutput, runningCall, imageUrl, MAX_IMAGE, failed, refusal, noteNamedPaths, sendTodos, stuckSaid, pagesOf, shrunkNote } from './tools.js'
12
15
  import { serversNote } from './lsp.js'
13
16
  import { newlyEnded, jobLine } from './background.js'
14
17
  import { loadHooks, runHooks } from './hooks.js'
15
18
  import { takeConfigErrors, HELPER_JOBS } from './config.js'
16
19
  import { c, duration, Block, Markdown, color, diffLines, renderDiff } from './ui.js'
20
+ import { fetch } from './http.js' // not the built-in one: see http.js
17
21
 
18
22
  // Images for a helper (the agent tool's "images"), as data: URLs: image URLs (fetched), data: URLs,
19
23
  // or files: in the project, saved screenshots (OUTPUTS), or a path the user gave in a message.
@@ -239,12 +243,17 @@ export class Session {
239
243
  async subagent(args, signal, id) {
240
244
  const task = String(args.prompt ?? args.task ?? '').trim()
241
245
  if (!task) return 'error: give the helper its job in "prompt"'
246
+ // an image named in the job but not given in "images" (a screenshot's path): given, so a model
247
+ // that can see takes the job; one that can't would answer without looking
248
+ const named = [...task.matchAll(/(?:^|[\s"'`(])((?:~|\/|\.{0,2}\/)?[\w./-]+\.(?:png|jpe?g|webp|gif))\b/gi)].map((m) => m[1]).filter((f) => fs.existsSync(path.resolve(this.root, f.replace(/^~(?=\/)/, os.homedir()))))
249
+ const given = [].concat(args.images ?? []).filter(Boolean)
242
250
  let images
243
251
  try {
244
- images = await loadImages(args.images, this, signal)
252
+ images = await loadImages(given.length || !named.length ? args.images : [...new Set(named)], this, signal)
245
253
  } catch (e) {
246
254
  if (e.name === 'AbortError') throw e
247
- return `error: ${e.message}`
255
+ if (given.length || !named.length) return `error: ${e.message}`
256
+ images = [] // only named in the job (one it may not send): the job as it was
248
257
  }
249
258
  const name = (t) => `${t.provider} ${t.model}`
250
259
  const { order, first, all, helpers } = this.helperModels(args, images.length > 0)
@@ -255,7 +264,7 @@ export class Session {
255
264
  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
256
265
  let answer = ''
257
266
  try {
258
- answer = (await this.#helper(t, task, images, args.description, id, signal, args.ownFiles))?.trim()
267
+ answer = (await this.#helper(t, task, images, args.description, id, signal, args.ownFiles, args.root))?.trim()
259
268
  } catch (e) {
260
269
  if (e.name === 'AbortError' || signal?.aborted) throw e
261
270
  if (e.maxTurns) return `error: the helper ${e.message}` // the caller's limit: every other model would stop there too
@@ -289,7 +298,10 @@ export class Session {
289
298
  // One helper on one model (t: this one, or another of yours), with its own connection (a helper's
290
299
  // failure moves no one else on to another model) that gives up after a few tries (then the next
291
300
  // model gets the job).
292
- async #helper(t, task, images, description, id, signal, ownFiles) {
301
+ // root: a copy of the project to work in instead (a part done by two models to compare): its
302
+ // changes stay there, not this message's, until the better one is brought over (tools.js)
303
+ async #helper(t, task, images, description, id, signal, ownFiles, root = this.root) {
304
+ const own = root === this.root
293
305
  let { client, profile, strat } = this
294
306
  if (this.engineFor) {
295
307
  ;({ client, profile, strat } = await this.engineFor(t))
@@ -297,11 +309,15 @@ export class Session {
297
309
  client.retryIf = (e, attempt) => attempt < 3 && e.name !== 'TimeoutError' && e.status !== 429 && e.status !== 413 && (!was || was(e, attempt)) // silent (not starting, or stopping midway: each try would wait as long again), rate-limited or too large: the next model, not another try
298
310
  }
299
311
  const label = clip(String(description ?? '').trim() || task.split('\n')[0], 60) // its model is named on the agent line
300
- const helper = new Session({ client, profile, strat, root: this.root, ui: helperUI(this.ui, label, client.model), chat: newChat(this.root) })
312
+ const helper = new Session({ client, profile, strat, root, ui: helperUI(this.ui, label, client.model), chat: newChat(root) })
301
313
  helper.chat.turns = this.chat.turns.slice(-1) // this message's turn: its file changes go there (track), the changes tool reads them
302
- if (ownFiles?.length) helper.ownFiles = ownFiles.map((f) => path.resolve(this.root, f)) // a part of the plan: changes only its own files
314
+ if (ownFiles?.length) helper.ownFiles = ownFiles.map((f) => path.resolve(root, f)) // a part of the plan: changes only its own files
303
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 })
304
- helper.track = (rel, before) => this.track(rel, before)
316
+ helper.track = own ? (rel, before) => this.track(rel, before) : () => {}
317
+ // a helper that can't see, given screenshots by a tool (a browser): one of your models that can
318
+ // describes them for its job (it has no helpers of its own to ask)
319
+ const seers = strat.vision ? [] : (this.team?.() ?? []).filter((x) => x.images)
320
+ if (seers.length && this.engineFor) helper.describeFor = async (files) => (await this.describeImages(files.map((f) => imageUrl(f)), seers, task, signal, () => prompt('agent/describe-screenshot', { task: clip(task, 1500) }))).trim()
305
321
  helper.mcpGate = async () => (await this.#gate(helper), () => {})
306
322
  if (this.onEvent) helper.onEvent = (e) => this.onEvent({ ...e, parent: id, helper: label })
307
323
  log('agent', `helper "${label}" (${images.length} image(s)): ${task}`)
@@ -314,7 +330,7 @@ export class Session {
314
330
  if (this.ui.helpers?.delete(label)) this.ui.render?.()
315
331
  this.#release(helper)
316
332
  // its changes are this message's: the not-done checks and the review see them
317
- if (helper.changed?.size && this.changed) {
333
+ if (own && helper.changed?.size && this.changed) {
318
334
  for (const f of helper.changed) this.changed.add(f)
319
335
  this.lastChangeAt = ++this.seq
320
336
  this.checksSince = 0
@@ -350,7 +366,8 @@ export class Session {
350
366
 
351
367
  // Images for a model that can't see them: your models that can describe each, for the task (the
352
368
  // next one when one fails).
353
- async describeImages(images, seers, task, signal) {
369
+ // ask: the request for each (default: an image the user attached).
370
+ async describeImages(images, seers, task, signal, ask = () => prompt('guided/describe-image', { task })) {
354
371
  const out = []
355
372
  let by = ''
356
373
  for (const [i, url] of images.entries()) {
@@ -360,7 +377,7 @@ export class Session {
360
377
  try {
361
378
  const { client } = await this.engineFor(seer)
362
379
  client.retryIf = (e, attempt) => attempt < 3 && !e.notStarted
363
- said = (await client.chat({ messages: [{ role: 'user', content: [{ type: 'text', text: prompt('guided/describe-image', { task }) }, { type: 'image_url', image_url: { url } }] }] }, { signal })).content.trim()
380
+ said = (await client.chat({ messages: [{ role: 'user', content: [{ type: 'text', text: ask() }, { type: 'image_url', image_url: { url } }] }] }, { signal })).content.trim()
364
381
  } catch (e) {
365
382
  if (e.name === 'AbortError' || signal?.aborted) throw e
366
383
  this.ui.warn(`${seer.model} couldn't look at image ${i + 1}: ${clip(e.message, 120)}`)
@@ -460,7 +477,7 @@ export class Session {
460
477
  // It runs after the answer is back (wrapUpLater), beside whatever you do next: its own connection,
461
478
  // one wrap-up at a time; what it needs is taken from the task first, before the next one changes it.
462
479
  wrapUpLater(task, answer) {
463
- const at = { research: this.research, turn: this.chat.turns.at(-1), dirsBefore: this.dirsBefore, ran: this.ran, runs: this.runs }
480
+ const at = { research: this.research, turn: this.chat.turns.at(-1), dirsBefore: this.dirsBefore, ran: this.ran, runs: this.runs, troubles: this.troubles?.splice(0) ?? [], stuckLeft: (this.chat.todos ?? []).some((t) => t.status === 'stuck'), review: this.lastReview, model: this.client.model, unstuckLearned: this.unstuckLearned }
464
481
  const job = (this.wrapping ?? Promise.resolve())
465
482
  .then(() => this.wrapUp(task, answer, undefined, at))
466
483
  .catch((e) => log('wrapup', `failed: ${e.message}`))
@@ -471,6 +488,16 @@ export class Session {
471
488
  // at: the task's own state (wrapUpLater), else this message's
472
489
  async wrapUp(task, answer, signal, at = { research: this.research, turn: this.chat.turns.at(-1), dirsBefore: this.dirsBefore, ran: this.ran, runs: this.runs }) {
473
490
  if (this.isSub || !this.memory || this.ui.permission === 'plan') return
491
+ // it struggled (said it was stuck, gave up, was handed over): what blocked it is learned, so the
492
+ // next task like this starts knowing it. Solved: what got it out; not: what to know or try first
493
+ // What it learns from: how it ended (the answer, the review's points), not the excuses given on the
494
+ // way ("I can't browse" would teach giving up); the steps it said it was stuck on, with why.
495
+ const unsolved = Boolean(at.stuckLeft || at.review?.verdict === 'no' || SAYS_FAILED.test(String(answer ?? '').slice(0, 400)))
496
+ if (at.troubles?.length && (unsolved || !at.unstuckLearned)) { // solved, and what got it out learned already: not again
497
+ const steps = [...new Set(at.troubles.filter((t) => t.step !== 'the task' && t.step !== 'handed over').map((t) => `${t.step}: ${t.why}`))].slice(-2)
498
+ const what = [`${unsolved ? 'Not done' : `Done by ${at.model} after other tries failed`}. Its answer: ${clip(String(answer ?? '').replace(/\s+/g, ' '), 400)}`, at.review?.verdict === 'no' && `The review said: ${clip(at.review.issues.replace(/\s+/g, ' '), 300)}`, steps.length && `Stuck on: ${steps.join(' / ')}`].filter(Boolean).join('\n')
499
+ await learnFromFixes(this, [{ error: what, context: 'general' }], signal, { unsolved, task }).catch((e) => log('learn', `troubles: ${e.message}`))
500
+ }
474
501
  const pages = at.research ?? []
475
502
  const turn = at.turn
476
503
  const made = Object.entries(turn?.files ?? {}).filter(([rel, before]) => before === null && fs.existsSync(path.join(this.root, rel))).map(([rel]) => rel)
@@ -559,7 +586,9 @@ export class Session {
559
586
  // One line of context about where HeartCode runs, so the model knows the OS, shell and tools to expect.
560
587
  const OS_NAMES = { darwin: 'macOS', linux: 'Linux', win32: 'Windows' }
561
588
  const envLine = () => {
562
- const shell = (process.env.SHELL || process.env.ComSpec || '').split(/[/\\]/).pop()
589
+ // the shell run_command really uses (Node's: cmd.exe on Windows, /bin/sh elsewhere), not $SHELL,
590
+ // which on Windows can say bash (Git Bash) while commands still run in cmd.exe
591
+ const shell = process.platform === 'win32' ? (process.env.ComSpec || 'cmd.exe').split(/[/\\]/).pop() : 'sh'
563
592
  return `${OS_NAMES[process.platform] ?? process.platform} (${process.platform} ${os.release()}, ${process.arch})${shell ? `, shell ${shell}` : ''}`
564
593
  }
565
594
 
@@ -875,11 +904,14 @@ async function runNative(s, task, images, signal) {
875
904
  s.planAsked = false // asked for a plan before its first change, this message
876
905
  s.askedUser = s.askNudged = false // asked with ask_user / told to, this message (a reply of questions as text: askedInText)
877
906
  s.splitAsked = false // asked whether a plan's parts could run side by side, this message
907
+ s.split = undefined // the user's answer this message: 'several' agents at once, or 'one' (tools.js)
878
908
  s.lookedUp = s.researchAsked = false // searched or read the web this message / asked whether the plan needs it
879
909
  // what changed and when it was last checked, this message: a change not run/tested since isn't done
880
- Object.assign(s, { changed: new Set(), seq: 0, lastChangeAt: -1, lastCheckAt: -1, reviewedAt: -1, checksSince: 0, spots: new Map() })
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 })
881
911
 
882
912
  let empty = 0 // replies in a row with neither text nor tool calls
913
+ let lastFinal = '' // the last answer it gave (a next one the same, after being told it isn't done: it's stuck)
914
+ let refusedCan = 0 // replies saying it can't (browse, run…) before trying a tool, this message
883
915
  let looping = 0 // replies cut for going into a loop, this message
884
916
  let stuck = null // why it's going round in circles (then the next model takes over; nothing stops but Esc)
885
917
  // Going round in circles: the next of your models carries on (a different model often gets out of
@@ -888,7 +920,14 @@ async function runNative(s, task, images, signal) {
888
920
  // the job goes to your next model.
889
921
  const handOver = (why) => {
890
922
  const was = client.model
891
- if (client.moveOn?.(`${was} ${why}`)) ui.warn(`${was} ${why}; handing over to ${client.model}`)
923
+ s.gaveUp.add(`${client.provider}/${was}`) // not gone back to this message, nor asked for a second opinion
924
+ if (strongest(s, client, `${was} ${why}`) || client.moveOn?.(`${was} ${why}`, s.gaveUp)) {
925
+ ui.warn(`${was} ${why}; handing over to ${client.model}`)
926
+ // the next model sees the whole conversation: told it's taking over, and not to repeat what didn't work
927
+ 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
+ s.stuckReports = 0
929
+ s.troubles?.push({ model: was, step: 'handed over', why })
930
+ }
892
931
  else if (s.isSub) throw Object.assign(new Error(`${was} ${why}`), { stuck: true })
893
932
  else ui.warn(`${was} ${why} — it carries on, told so; Esc stops it`)
894
933
  }
@@ -1061,6 +1100,47 @@ async function runNative(s, task, images, signal) {
1061
1100
  return finalAnswer(s, signal)
1062
1101
  }
1063
1102
  empty = 0
1103
+ // "I can't browse / run / see…" with no tool tried this message: it has tools for that. Told what
1104
+ // it has, once; said again without trying, the next of your models takes the task
1105
+ if (!res.toolCalls.length && !s.acted && !s.isSub && CANT.test(res.content)) {
1106
+ log('task', `${client.model} said it can't, without trying a tool (${++refusedCan})`)
1107
+ if (refusedCan === 1) {
1108
+ s.messages.push({ role: 'user', content: prompt('agent/you-can', { mcp: (s.mcp?.names ?? []).join(', ') }) })
1109
+ continue
1110
+ }
1111
+ if (refusedCan === 2) {
1112
+ const was = client.model
1113
+ handOver(`said it can't do it, without trying its tools`)
1114
+ if (client.model !== was) refusedCan = 0 // the next model: told once too
1115
+ continue
1116
+ }
1117
+ }
1118
+ // its answer says it didn't manage ("couldn't", "still not loading", "unable to"): taken as saying
1119
+ // it's stuck: told to change approach, then a second opinion, then the next model (stuckSaid);
1120
+ // after two models took over, its plain account of what blocks it is the answer
1121
+ const sameAfterNo = s.lastReview?.verdict === 'no' && lastFinal && res.content.replace(/\s+/g, ' ').trim().slice(0, 300) === lastFinal.replace(/\s+/g, ' ').trim().slice(0, 300) // a review said no, and it gives the same answer again
1122
+ if (!res.toolCalls.length && s.acted && !s.isSub && !s.toldLast && (sameAfterNo || SAYS_FAILED.test(res.content.slice(0, 400)))) { // told to say plainly what blocks it: that answer is the answer
1123
+ const why = clip(res.content.replace(/\s+/g, ' ').trim(), 200)
1124
+ s.messages.push({ role: 'user', content: await stuckSaid(s, 'the task', why, signal, undefined, true) })
1125
+ if (s.stuckSelf) {
1126
+ handOver(s.stuckSelf)
1127
+ s.stuckSelf = null
1128
+ s.stuckHandovers++
1129
+ }
1130
+ continue
1131
+ }
1132
+ // told it isn't done (open todos, a review's no, its own "couldn't"), and it answers again without
1133
+ // doing anything: the same answer, or one that only promises: the next of your models takes the task
1134
+ 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)) {
1136
+ 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
+ s.stuckHandovers++
1138
+ sinceNudge = true
1139
+ continue
1140
+ }
1141
+ if (!res.toolCalls.length) lastFinal = res.content
1142
+ // its page is still broken in HeartCode's check and nobody's left to take over: said, not hidden behind "done"
1143
+ 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`)
1064
1144
  if (!res.toolCalls.length) {
1065
1145
  const more = sinceNudge && ((await notDone(s, signal, nudged > 0, res.content)) ?? (await review(s, task, res.content, signal)))
1066
1146
  showHeld(res.content) // after the review's line
@@ -1071,6 +1151,11 @@ async function runNative(s, task, images, signal) {
1071
1151
  nudged++
1072
1152
  sinceNudge = false
1073
1153
  s.messages.push({ role: 'user', content: more })
1154
+ // said done twice and its page is still broken in HeartCode's own check: the best-ranked model takes over
1155
+ if (s.proofFails >= 2 && !s.isSub && client.rotation) {
1156
+ handOver(`said it was done ${s.proofFails} times, and its page still doesn't work when HeartCode opens it`)
1157
+ s.proofFails = 0
1158
+ }
1074
1159
  continue
1075
1160
  }
1076
1161
 
@@ -1142,6 +1227,7 @@ async function runNative(s, task, images, signal) {
1142
1227
  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')
1143
1228
  if (!refused && args) out += guard.after(name, args, out)
1144
1229
  if (guard.stuck) stuck ??= guard.stuck
1230
+ if (s.stuckSelf) (stuck ??= s.stuckSelf), (s.stuckSelf = null), s.stuckHandovers++ // it said so itself (todo stuck, a third time)
1145
1231
  if (args && !refused) {
1146
1232
  s.seq++
1147
1233
  if (EDITS.has(name) && !failed(out)) {
@@ -1167,6 +1253,13 @@ async function runNative(s, task, images, signal) {
1167
1253
  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
1168
1254
  if (checked) s.ran?.push({ command: checked, result: clip(String(out).split('\n').filter((l) => l.trim()).slice(0, 2).join(' · '), 160) })
1169
1255
  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
+ // a step it said it was stuck on, now done: what got it out is a lesson
1257
+ if (!s.isSub && s.memory && s.unstuck?.length) {
1258
+ const out = s.unstuck.splice(0)
1259
+ s.troubles = s.troubles.filter((t) => !out.some((u) => u.step === t.step)) // learned here: not again at the wrap-up
1260
+ s.unstuckLearned = true
1261
+ await learnFromFixes(s, out.map((u) => ({ error: `stuck on "${u.step}": ${u.why}`, context: 'general' })), signal, { task: s.task ?? '' }).catch((e) => log('learn', `unstuck: ${e.message}`))
1262
+ }
1170
1263
  // the same call again and again in a row (a weak model going round): told at the third, stopped at the fifth
1171
1264
  const sig = `${name} ${call.function.arguments}`
1172
1265
  inRow = sig === lastCall ? inRow + 1 : 1
@@ -1254,8 +1347,17 @@ export function newGuard() {
1254
1347
  if (repeats >= 10) g.stuck = 'kept making calls it had already made (10 repeats)' // going round, not finding anything new
1255
1348
  return prompt('agent/already-done', { result: was.out, circling: repeats >= 3 })
1256
1349
  }
1350
+ let sameTool = null // the tool (an MCP server's own tool by name) whose calls failed in a row
1351
+ let sameFails = 0
1257
1352
  g.after = (name, a, out) => {
1258
1353
  let note = ''
1354
+ // any other tool (a browser's wait, click…) failing again and again: told at the third to stop and think
1355
+ const tool = name === 'mcp' ? `${a.server} · ${a.tool}` : name
1356
+ if (name !== 'run_command') {
1357
+ sameFails = failed(out) ? (tool === sameTool ? sameFails + 1 : 1) : 0
1358
+ sameTool = tool
1359
+ if (sameFails === 3) note += `\n\n${prompt('agent/same-tool-failing', { tool })}`
1360
+ }
1259
1361
  if (name === 'run_command') {
1260
1362
  const code = Number(/^exit code (-?\d+)/.exec(out)?.[1] ?? 0)
1261
1363
  failing = code ? failing + 1 : 0
@@ -1304,7 +1406,8 @@ async function noteRun(s, name, args, out, signal) {
1304
1406
  // Turn each fixed mistake into one reusable rule and save it (global memory, tagged by the tool it came from). The
1305
1407
  // model writes the rule from the error; a near-duplicate lesson is skipped. Recall is automatic
1306
1408
  // (memory.relevant attaches matching notes to a later message).
1307
- async function learnFromFixes(s, fixed, signal) {
1409
+ // unsolved: it blocked a task that wasn't done (the rule: what to know or try first); task: what was asked (found by it later).
1410
+ async function learnFromFixes(s, fixed, signal, { unsolved = false, task = '' } = {}) {
1308
1411
  for (const { error, context } of fixed.slice(0, 5)) {
1309
1412
  const tags = [runTool_(context ?? error) || 'general'] // the tool it came from (npm, python3, cargo…)
1310
1413
  const near = s.memory.search(`tag:lesson ${tags.join(' ')}`).find((n) => n.body.toLowerCase().includes(error.replace(/^[^:]*:\s*/, '').toLowerCase().slice(0, 30)))
@@ -1316,7 +1419,7 @@ async function learnFromFixes(s, fixed, signal) {
1316
1419
  s.client.purpose = 'lesson'
1317
1420
  let reply
1318
1421
  try {
1319
- reply = await s.client.chat({ messages: [{ role: 'user', content: prompt('agent/lesson', { error }) }] }, { signal })
1422
+ reply = await s.client.chat({ messages: [{ role: 'user', content: prompt('agent/lesson', { error, unsolved, task: clip(task, 300) }) }] }, { signal })
1320
1423
  } finally {
1321
1424
  s.client.purpose = was
1322
1425
  }
@@ -1327,7 +1430,7 @@ async function learnFromFixes(s, fixed, signal) {
1327
1430
  if (e.name === 'AbortError') throw e
1328
1431
  }
1329
1432
  if (!rule || rule.length < 10) rule = error.replace(/^[^:]*:\s*/, '') // the model couldn't phrase it: keep the error's own wording
1330
- 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 })
1433
+ 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 })
1331
1434
  s.ui.step('learned', `${rule.slice(0, 90)}${scope === 'project' ? ' (this project)' : ''}`)
1332
1435
  log('learn', `saved lesson [[${name}]] (${scope}, #${tags.join(' #')}): ${rule}`)
1333
1436
  }
@@ -1339,7 +1442,14 @@ async function learnFromFixes(s, fixed, signal) {
1339
1442
  // The model said it would do something but stopped without doing it ("let me rewrite…", "I'll fix…"):
1340
1443
  // a next action named, then no tool call. Not matched by explanations ("let me explain", "you can run").
1341
1444
  const PROMISED_MORE =
1342
- /\b(?:let me|i['’]?ll|i will|i['’]?m going to|i am going to|i need to|i['’]?m about to|next,? i['’]?ll|now,? i['’]?ll)\b[^.!?\n]{0,70}\b(?:do|make|create|add|fix|write|update|change|implement|build|run|rewrite|replace|edit|install|set ?up|finish|continue|proceed|start|redo|retry|try|hand|pass|send|give)\b/i
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
1446
+
1447
+ // 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
1449
+
1450
+ // "I can't browse the web", "I'm unable to run commands", "I don't have access to…": a model
1451
+ // 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
1343
1453
 
1344
1454
  // Is the task really done, or did the model stop early? Open todo items, or (after it did real work)
1345
1455
  // a reply that only promises more, get one nudge to keep going. Then any Stop hook. null = truly done.
@@ -1351,6 +1461,22 @@ export function askedInText(reply) {
1351
1461
  return questions >= 2 && questions / sentences.length >= 0.4
1352
1462
  }
1353
1463
 
1464
+ // A model that showed it can't do this task (went round in circles, stuck, its work still broken):
1465
+ // the task goes to the best of your models by the rankings (scoreOf) that can use tools and hasn't
1466
+ // been given up on this message, not just the next in your list: the next is often a smaller one.
1467
+ // Your list's order still decides who starts, and who answers when one is only unavailable.
1468
+ // False when none is ranked (then the list's next, moveOn).
1469
+ function strongest(s, client, why) {
1470
+ const now = family(client.model)
1471
+ const best = (s.team?.() ?? [])
1472
+ .filter((t) => t.tools !== false && !s.gaveUp.has(`${t.provider}/${t.model}`) && family(t.model) !== now)
1473
+ .map((t) => ({ t, score: scoreOf(t.model) }))
1474
+ .filter((x) => x.score < Infinity)
1475
+ .sort((a, b) => a.score - b.score)[0]
1476
+ const target = best && client.rotation?.list.find((x) => x.provider === best.t.provider && x.model === best.t.model)
1477
+ return Boolean(target && client.switchTo(target, `${why}; the best-ranked of your models not tried yet`))
1478
+ }
1479
+
1354
1480
  export async function notDone(s, signal, again, reply = '') {
1355
1481
  // questions typed out instead of asked: once a message, asked again with the tool (someone's there to answer)
1356
1482
  if (!s.isSub && !s.ui.noUser && !s.askedUser && !s.askNudged && askedInText(reply)) {
@@ -1375,6 +1501,36 @@ export async function notDone(s, signal, again, reply = '') {
1375
1501
  log('task', `the answer names files that don't exist: ${missing.join(', ')}`)
1376
1502
  return prompt('agent/not-done', { missing: missing.join(', ') })
1377
1503
  }
1504
+ // a file it changed is much smaller than an earlier version: what earlier messages made may be lost.
1505
+ // Told once a message, before the browser check; the review sees it too
1506
+ if (!s.isSub && !s.shrunkTold && changed.length) {
1507
+ const note = shrunkNote(s, changed)
1508
+ if (note) {
1509
+ s.shrunkTold = true
1510
+ log('task', `files much smaller than before: ${note}`)
1511
+ return prompt('agent/not-done', { shrunk: note })
1512
+ }
1513
+ }
1514
+ // web pages it changed (or that use what it changed): HeartCode opens them in a browser itself, once
1515
+ // per batch of changes. Broken (errors, nothing shown, a canvas drawing nothing) isn't done, whatever
1516
+ // the model's own checks said; how it looks (contrast…) is left to the model and the review.
1517
+ const pages = s.ui.permission === 'plan' || s.lastChangeAt <= (s.provedAt ?? -1) ? [] : pagesOf(s.root, changed)
1518
+ if (pages.length) {
1519
+ s.provedAt = s.lastChangeAt
1520
+ for (const page of pages) {
1521
+ s.ui.spinner(`opening ${page} in a browser to check it`)
1522
+ const r = await pageCheck(s.root, page, signal, path.join(s.root, '.heartcode', 'page-shots'), () => {}).catch((e) => (signal?.aborted ? Promise.reject(e) : null))
1523
+ s.ui.stopSpin()
1524
+ if (!r) continue
1525
+ 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
1528
+ s.proofFails = (s.proofFails ?? 0) + 1
1529
+ log('task', `HeartCode's page check failed (${s.proofFails}): ${r.report}`)
1530
+ 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}` })
1531
+ }
1532
+ s.proofFails = 0
1533
+ }
1378
1534
  if (s.acted && reply && PROMISED_MORE.test(reply)) {
1379
1535
  log('task', 'reply names a next step but no tool call followed; nudging to finish')
1380
1536
  return prompt('agent/not-done', { early: true })
@@ -1384,6 +1540,9 @@ export async function notDone(s, signal, again, reply = '') {
1384
1540
  return hook.block ? prompt('agent/hook', { reason: hook.block, stop: true }) : null
1385
1541
  }
1386
1542
 
1543
+ // HeartCode itself, for the check commands it gives the model
1544
+ const BIN = fileURLToPath(new URL('../bin/heartcode.js', import.meta.url))
1545
+
1387
1546
  // Files the final answer says were made, that aren't in the project: a path in backticks, or one
1388
1547
  // with a folder, with a source/config/doc extension, while the answer says it created or wrote
1389
1548
  // something. A name that's anywhere in the project (by its file name) counts as there.
@@ -1443,8 +1602,12 @@ const isEmptyDir = (abs) => {
1443
1602
  // a NO goes back to the model to fix. Asked again only once files changed since its last look.
1444
1603
  // Returns what to tell the model, or null.
1445
1604
  export async function review(s, task, answer, signal) {
1446
- if (s.isSub || !s.changed?.size || s.lastChangeAt <= s.reviewedAt || s.ui.permission === 'plan') return null
1605
+ // no files changed, but it ran things to do the task (a browser, commands, helpers): its answer is
1606
+ // checked against the request too (once per new batch of them)
1607
+ const acted = !s.changed?.size && (s.ran?.length ?? 0) > (s.reviewedRan ?? 0)
1608
+ if (s.isSub || s.ui.permission === 'plan' || (!acted && (!s.changed?.size || s.lastChangeAt <= s.reviewedAt))) return null
1447
1609
  s.reviewedAt = s.lastChangeAt
1610
+ s.reviewedRan = s.ran?.length ?? 0
1448
1611
  const turn = s.chat.turns.at(-1)
1449
1612
  const diffs = []
1450
1613
  let room = 16_000
@@ -1465,10 +1628,11 @@ export async function review(s, task, answer, signal) {
1465
1628
  break
1466
1629
  }
1467
1630
  }
1468
- if (!diffs.length) return null
1631
+ if (!diffs.length && !acted) return null
1632
+ if (!diffs.length) diffs.push('(no files changed)')
1469
1633
  const plan = (s.chat.todos ?? []).map((t) => `- [${t.status === 'completed' ? 'x' : ' '}] ${t.content}`).join('\n')
1470
1634
  const ran = (s.ran ?? []).slice(-15).map((r) => `- ${clip(r.command.replace(/\s+/g, ' '), 160)} → ${r.result}`).join('\n')
1471
- 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)' })
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 ?? [])]) })
1472
1636
  const self = { provider: s.client.provider, model: s.client.model, self: true }
1473
1637
  const others = (s.team?.() ?? []).filter((t) => t.tools !== false && !(t.provider === self.provider && t.model === self.model))
1474
1638
  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
@@ -1489,12 +1653,14 @@ export async function review(s, task, answer, signal) {
1489
1653
  s.ui.stopSpin()
1490
1654
  log('review', `${t.model}: ${said}`)
1491
1655
  if (/^\W*yes\b/i.test(said)) {
1656
+ s.lastReview = { verdict: 'yes' }
1492
1657
  s.ui.event?.({ subtype: 'review', model: `${t.provider}/${t.model}`, verdict: 'yes', issues: '' })
1493
1658
  s.ui.step('review', `${t.model}: looks right`)
1494
1659
  return null
1495
1660
  }
1496
1661
  if (/^\W*no\b/i.test(said)) {
1497
1662
  const issues = said.replace(/^\W*no\b[\s.:—-]*/i, '').trim()
1663
+ s.lastReview = { verdict: 'no', issues }
1498
1664
  s.ui.event?.({ subtype: 'review', model: `${t.provider}/${t.model}`, verdict: 'no', issues })
1499
1665
  s.ui.step('review', `${t.model}: ${clip(issues.split('\n').find((l) => l.trim()) ?? 'problems found', 90)}`)
1500
1666
  return prompt('agent/review-failed', { model: t.model, issues: issues || '(no details given)' })
@@ -1706,14 +1872,14 @@ export function contextReport(s) {
1706
1872
  const text = typeof m.content === 'string' ? m.content : (m.content ?? []).map((p) => p.text ?? '').join(' ')
1707
1873
  const yours = tasks.some((t) => text.startsWith(t))
1708
1874
  yours ? (parts.you += n) : (parts.notes += n)
1709
- 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 })
1875
+ pieces.push({ tokens: n, what: yours ? `a typed message "${clip(text.split('\n')[0], 50)}"` : `a note to the model "${clip(text.split('\n')[0], 50)}"`, ago })
1710
1876
  }
1711
1877
  })
1712
1878
  const toolTokens = tok(tools.map((f) => ({ type: 'function', function: f })))
1713
1879
  const list = [
1714
1880
  { name: 'system prompt', tokens: parts.system },
1715
1881
  { name: `tools (${tools.length})`, tokens: toolTokens },
1716
- { name: 'your messages', tokens: parts.you },
1882
+ { name: 'typed messages', tokens: parts.you },
1717
1883
  { name: 'notes to the model', tokens: parts.notes, note: 'summaries, guides, reminders, saved notes found' },
1718
1884
  { name: 'model replies', tokens: parts.replies },
1719
1885
  { name: 'tool results', tokens: parts.results, note: `${whole} whole` },
package/src/background.js CHANGED
@@ -8,6 +8,7 @@ import path from 'node:path'
8
8
  import { spawn } from 'node:child_process'
9
9
  import { HOME } from './config.js'
10
10
  import { log } from './log.js'
11
+ import { killTree } from './spawn.js'
11
12
 
12
13
  const DIR = path.join(HOME, 'outputs', 'background')
13
14
  const jobs = new Map() // id → { id, command, root, pid, file, started, code, read, exited }
@@ -15,14 +16,7 @@ let made = 0
15
16
 
16
17
  const plain = (t) => t.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').replace(/\r(?!\n)/g, '\n')
17
18
  const group = process.platform !== 'win32'
18
- const kill = (job, sig) => {
19
- try {
20
- group ? process.kill(-job.pid, sig) : process.kill(job.pid, sig)
21
- return true
22
- } catch {
23
- return false
24
- }
25
- }
19
+ const kill = (job, sig) => killTree(job.pid, sig, group)
26
20
 
27
21
  // Started (it runs on; waitFor waits on it).
28
22
  export function startJob(root, command) {
@@ -5,8 +5,8 @@
5
5
  import fs from 'node:fs'
6
6
  import path from 'node:path'
7
7
  import { voiceProblem } from './voice.js'
8
+ import { onPath } from './spawn.js'
8
9
 
9
- const onPath = (cmd) => (process.env.PATH ?? '').split(path.delimiter).some((d) => d && (fs.existsSync(path.join(d, cmd)) || fs.existsSync(path.join(d, cmd + '.exe'))))
10
10
  const exists = (p) => {
11
11
  try {
12
12
  fs.accessSync(p)
@@ -33,7 +33,7 @@ export function capabilities(cfg = {}) {
33
33
  else if (/whisper-cli/.test(vp)) need = 'whisper (whisper-cli) and a model — or a transcription provider'
34
34
  else need = 'a whisper model — or a transcription provider'
35
35
  }
36
- caps.push({ id: 'voice', name: 'Voice input', what: 'Dictate your message — Space in an empty box, or /voice.', ok: !vp, need })
36
+ caps.push({ id: 'voice', name: 'Voice input', what: 'Dictate a message — Space in an empty box, or /voice.', ok: !vp, need })
37
37
  const chrome = chromeHere()
38
38
  const npx = onPath('npx')
39
39
  caps.push({
package/src/check.js CHANGED
@@ -12,6 +12,7 @@ import path from 'node:path'
12
12
  import zlib from 'node:zlib'
13
13
  import { HOME } from './config.js'
14
14
  import { log } from './log.js'
15
+ import { fetch } from './http.js' // not the built-in one: see http.js
15
16
 
16
17
  const wait = (ms) => new Promise((r) => setTimeout(r, ms))
17
18
  const tail = (t, n = 2500) => ((t = String(t).trim()), t.length > n ? `…${t.slice(-n)}` : t)
@@ -266,7 +267,7 @@ export async function pageCommand(target) {
266
267
 
267
268
  // A web page: it loads without errors, shows something, and pressing its first button and a few keys
268
269
  // breaks nothing
269
- async function pageCheck(root, target, signal, shots, note) {
270
+ export async function pageCheck(root, target, signal, shots, note) {
270
271
  const isUrl = /^https?:\/\//.test(target)
271
272
  if (!isUrl) {
272
273
  const file = path.resolve(root, target)
@@ -314,23 +315,87 @@ async function pageCheck(root, target, signal, shots, note) {
314
315
  await wait(500)
315
316
  for (const k of ['Enter', ' ', 'ArrowUp', 'ArrowLeft']) await page.key(k, 150)
316
317
  await wait(1500)
318
+ const flat = seen.canvas ? await flatCanvases(page).catch((e) => (log('check', `canvas: ${e.message}`), 0)) : 0
317
319
  const problems = []
318
320
  if (!seen.shown || (!seen.text && !seen.canvas && !seen.pictures)) problems.push('the page shows nothing')
321
+ if (flat) problems.push(`${flat === 1 ? 'its canvas draws' : `${flat} canvases draw`} nothing: one flat color, also after pressing ${button ? `"${button}" and ` : ''}keys (is something drawing each frame, e.g. a render call in the loop, and is the camera or view looking at what's there?)`)
319
322
  if (looks?.lowContrast.length) problems.push(`text too faint to read (WCAG 1.4.3: 4.5:1, large text 3:1): ${looks.lowContrast.map((x) => `"${x.text}" ${x.ratio}:1 (${x.fg} on ${x.bg})`).join('; ')}`)
320
323
  if (looks?.hidden) problems.push(`${looks.hidden}% of the page's text is invisible (opacity 0 or hidden) when it's loaded: content shown only after scrolling or an animation is blank in screenshots, print and with reduced motion; show it by default`)
321
324
  if (looks?.icons.length) problems.push(`icons that didn't draw (no such name): ${looks.icons.join(', ')}`)
322
325
  if (seen.phoneWide) problems.push('on a phone (390 px) it scrolls sideways: something is wider than the screen')
323
326
  if (page.errors.length) problems.push(`${page.errors.length} error${page.errors.length === 1 ? '' : 's'}${page.errors.length > atLoad ? (atLoad ? ` (${page.errors.length - atLoad} after pressing ${button ? `"${button}" and ` : ''}keys)` : ` after pressing ${button ? `"${button}" and ` : ''}keys`) : ''}:\n${[...new Set(page.errors)].slice(0, 8).join('\n')}`)
324
327
  const what = `${seen.shown} things shown${seen.canvas ? `, ${seen.canvas} canvas` : ''}${button ? `; pressed "${button}"` : ''} and keys (Enter, Space, arrows)${seen.wide ? '; wider than the window (scrolls sideways)' : ''}${seen.phoneWide ? '; on a phone it scrolls sideways' : ''}${saved.length ? `\nscreenshots (look at them): ${saved.join(', ')}` : ''}${tooSlow ? `\nno screenshots: ${tooSlow}` : ''}`
325
- return { ok: !problems.length, report: `page ${target} in a browser: ${problems.length ? problems.join('; ') : 'loaded without errors'}; ${what}` }
328
+ // broken: it doesn't work (errors, nothing shown or drawn), not just how it looks
329
+ return { ok: !problems.length, broken: Boolean(!seen.shown || (!seen.text && !seen.canvas && !seen.pictures) || flat || page.errors.length), report: `page ${target} in a browser: ${problems.length ? problems.join('; ') : 'loaded without errors'}; ${what}`, shots: saved.map((f) => path.join(root, f)) }
326
330
  }, { signal })
327
331
  } catch (e) {
328
332
  if (signal?.aborted) throw e
329
- if (e.stuck) return { ok: false, report: `page ${target} in a browser: ${e.message}` } // the page's fault, not the browser's
333
+ if (e.stuck) return { ok: false, broken: true, report: `page ${target} in a browser: ${e.message}` } // the page's fault, not the browser's
330
334
  return unchecked(e.message)
331
335
  }
332
336
  }
333
337
 
338
+ // How many of the page's big canvases (a tenth of the window or more) show a single flat color: drawn
339
+ // on by nothing (a game whose loop updates but never renders). Screenshots, not the canvas's own
340
+ // pixels (a WebGL canvas reads back empty), with everything but canvases hidden for the shot.
341
+ async function flatCanvases(page) {
342
+ const rects = await page.run(`[...document.querySelectorAll('canvas')].map((e) => e.getBoundingClientRect()).filter((r) => r.width * r.height >= innerWidth * innerHeight / 10).map((r) => ({ x: Math.max(0, r.x), y: Math.max(0, r.y), width: Math.min(r.width, innerWidth - Math.max(0, r.x)), height: Math.min(r.height, innerHeight - Math.max(0, r.y)) })).filter((r) => r.width > 0 && r.height > 0)`)
343
+ if (!rects?.length) return 0
344
+ await page.run(`(() => { const st = document.createElement('style'); st.id = '__hc_flat'; st.textContent = 'body *:not(canvas) { visibility: hidden !important } canvas { visibility: visible !important }'; document.head.append(st) })()`)
345
+ let flat = 0
346
+ try {
347
+ for (const r of rects) {
348
+ const { data } = await page.send('Page.captureScreenshot', { format: 'png', clip: { ...r, scale: Math.min(1, 200 / r.width) } })
349
+ const px = pngPixels(Buffer.from(data, 'base64'))
350
+ const count = new Map()
351
+ for (let i = 0; i < px.length; i += 4) {
352
+ const k = (px[i] << 16) | (px[i + 1] << 8) | px[i + 2]
353
+ count.set(k, (count.get(k) ?? 0) + 1)
354
+ }
355
+ if (Math.max(...count.values()) >= (px.length / 4) * 0.995) flat++
356
+ }
357
+ } finally {
358
+ await page.run(`document.getElementById('__hc_flat')?.remove()`).catch(() => {})
359
+ }
360
+ return flat
361
+ }
362
+
363
+ // A PNG's pixels as RGBA bytes (8-bit, not interlaced: what Chrome's screenshots are)
364
+ export function pngPixels(buf) {
365
+ let w = 0, h = 0, type = 0
366
+ const idat = []
367
+ for (let at = 8; at < buf.length; ) {
368
+ const len = buf.readUInt32BE(at)
369
+ const kind = buf.toString('latin1', at + 4, at + 8)
370
+ const body = buf.subarray(at + 8, at + 8 + len)
371
+ if (kind === 'IHDR') {
372
+ ;[w, h, type] = [body.readUInt32BE(0), body.readUInt32BE(4), body[9]]
373
+ if (body[8] !== 8 || body[12] !== 0 || ![2, 6].includes(type)) throw new Error('a PNG kind not read here')
374
+ } else if (kind === 'IDAT') idat.push(body)
375
+ at += 12 + len
376
+ }
377
+ const bpp = type === 6 ? 4 : 3
378
+ const raw = zlib.inflateSync(Buffer.concat(idat))
379
+ const stride = w * bpp
380
+ const out = Buffer.alloc(w * h * 4)
381
+ let prev = Buffer.alloc(stride)
382
+ for (let y = 0; y < h; y++) {
383
+ const f = raw[y * (stride + 1)]
384
+ const line = Buffer.from(raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)))
385
+ for (let i = 0; i < stride; i++) {
386
+ const a = i >= bpp ? line[i - bpp] : 0, b = prev[i], c = i >= bpp ? prev[i - bpp] : 0
387
+ const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c)
388
+ line[i] = (line[i] + [0, a, b, (a + b) >> 1, pa <= pb && pa <= pc ? a : pb <= pc ? b : c][f]) & 255
389
+ }
390
+ for (let x = 0; x < w; x++) {
391
+ for (let k = 0; k < 3; k++) out[(y * w + x) * 4 + k] = line[x * bpp + k]
392
+ out[(y * w + x) * 4 + 3] = bpp === 4 ? line[x * bpp + 3] : 255
393
+ }
394
+ prev = line
395
+ }
396
+ return out
397
+ }
398
+
334
399
  // What a page looks like, measured in the browser, for what can be told for sure: text whose contrast
335
400
  // with what's behind it is under WCAG's minimum (colors through a canvas, so any CSS color works;
336
401
  // text on an image or gradient is skipped), how much of the text is invisible at load (opacity 0,
@@ -407,5 +472,5 @@ function staticPage(root, target, why = 'no browser here') {
407
472
  const f = path.resolve(dir, u.replace(/^\//, ''))
408
473
  if (fs.existsSync(f)) parse(fs.readFileSync(f, 'utf8'), u, /import|export/.test(fs.readFileSync(f, 'utf8')))
409
474
  }
410
- return { ok: !problems.length, report: `page ${target}, checked without a browser (${why}): ${problems.length ? problems.join('; ') : 'the files it uses are there and its scripts parse'}` }
475
+ return { ok: !problems.length, broken: problems.length > 0, report: `page ${target}, checked without a browser (${why}): ${problems.length ? problems.join('; ') : 'the files it uses are there and its scripts parse'}` }
411
476
  }