heartcode 0.1.60 → 0.1.63

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, stuckSaid } 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.
@@ -260,7 +264,7 @@ export class Session {
260
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
261
265
  let answer = ''
262
266
  try {
263
- 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()
264
268
  } catch (e) {
265
269
  if (e.name === 'AbortError' || signal?.aborted) throw e
266
270
  if (e.maxTurns) return `error: the helper ${e.message}` // the caller's limit: every other model would stop there too
@@ -294,7 +298,10 @@ export class Session {
294
298
  // One helper on one model (t: this one, or another of yours), with its own connection (a helper's
295
299
  // failure moves no one else on to another model) that gives up after a few tries (then the next
296
300
  // model gets the job).
297
- 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
298
305
  let { client, profile, strat } = this
299
306
  if (this.engineFor) {
300
307
  ;({ client, profile, strat } = await this.engineFor(t))
@@ -302,11 +309,11 @@ export class Session {
302
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
303
310
  }
304
311
  const label = clip(String(description ?? '').trim() || task.split('\n')[0], 60) // its model is named on the agent line
305
- 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) })
306
313
  helper.chat.turns = this.chat.turns.slice(-1) // this message's turn: its file changes go there (track), the changes tool reads them
307
- 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
308
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 })
309
- helper.track = (rel, before) => this.track(rel, before)
316
+ helper.track = own ? (rel, before) => this.track(rel, before) : () => {}
310
317
  // a helper that can't see, given screenshots by a tool (a browser): one of your models that can
311
318
  // describes them for its job (it has no helpers of its own to ask)
312
319
  const seers = strat.vision ? [] : (this.team?.() ?? []).filter((x) => x.images)
@@ -323,7 +330,7 @@ export class Session {
323
330
  if (this.ui.helpers?.delete(label)) this.ui.render?.()
324
331
  this.#release(helper)
325
332
  // its changes are this message's: the not-done checks and the review see them
326
- if (helper.changed?.size && this.changed) {
333
+ if (own && helper.changed?.size && this.changed) {
327
334
  for (const f of helper.changed) this.changed.add(f)
328
335
  this.lastChangeAt = ++this.seq
329
336
  this.checksSince = 0
@@ -579,7 +586,9 @@ export class Session {
579
586
  // One line of context about where HeartCode runs, so the model knows the OS, shell and tools to expect.
580
587
  const OS_NAMES = { darwin: 'macOS', linux: 'Linux', win32: 'Windows' }
581
588
  const envLine = () => {
582
- 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'
583
592
  return `${OS_NAMES[process.platform] ?? process.platform} (${process.platform} ${os.release()}, ${process.arch})${shell ? `, shell ${shell}` : ''}`
584
593
  }
585
594
 
@@ -895,9 +904,10 @@ async function runNative(s, task, images, signal) {
895
904
  s.planAsked = false // asked for a plan before its first change, this message
896
905
  s.askedUser = s.askNudged = false // asked with ask_user / told to, this message (a reply of questions as text: askedInText)
897
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)
898
908
  s.lookedUp = s.researchAsked = false // searched or read the web this message / asked whether the plan needs it
899
909
  // what changed and when it was last checked, this message: a change not run/tested since isn't done
900
- 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 })
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 })
901
911
 
902
912
  let empty = 0 // replies in a row with neither text nor tool calls
903
913
  let lastFinal = '' // the last answer it gave (a next one the same, after being told it isn't done: it's stuck)
@@ -911,7 +921,7 @@ async function runNative(s, task, images, signal) {
911
921
  const handOver = (why) => {
912
922
  const was = client.model
913
923
  s.gaveUp.add(`${client.provider}/${was}`) // not gone back to this message, nor asked for a second opinion
914
- if (client.moveOn?.(`${was} ${why}`, s.gaveUp)) {
924
+ if (strongest(s, client, `${was} ${why}`) || client.moveOn?.(`${was} ${why}`, s.gaveUp)) {
915
925
  ui.warn(`${was} ${why}; handing over to ${client.model}`)
916
926
  // the next model sees the whole conversation: told it's taking over, and not to repeat what didn't work
917
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') }) })
@@ -1122,13 +1132,15 @@ async function runNative(s, task, images, signal) {
1122
1132
  // told it isn't done (open todos, a review's no, its own "couldn't"), and it answers again without
1123
1133
  // doing anything: the same answer, or one that only promises: the next of your models takes the task
1124
1134
  const same = (a, b) => a && b && a.replace(/\s+/g, ' ').trim().slice(0, 300) === b.replace(/\s+/g, ' ').trim().slice(0, 300)
1125
- 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)))) {
1126
- handOver(`was told it isn't done and answered again without doing anything`)
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`)
1127
1137
  s.stuckHandovers++
1128
1138
  sinceNudge = true
1129
1139
  continue
1130
1140
  }
1131
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`)
1132
1144
  if (!res.toolCalls.length) {
1133
1145
  const more = sinceNudge && ((await notDone(s, signal, nudged > 0, res.content)) ?? (await review(s, task, res.content, signal)))
1134
1146
  showHeld(res.content) // after the review's line
@@ -1139,6 +1151,11 @@ async function runNative(s, task, images, signal) {
1139
1151
  nudged++
1140
1152
  sinceNudge = false
1141
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
+ }
1142
1159
  continue
1143
1160
  }
1144
1161
 
@@ -1444,6 +1461,22 @@ export function askedInText(reply) {
1444
1461
  return questions >= 2 && questions / sentences.length >= 0.4
1445
1462
  }
1446
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
+
1447
1480
  export async function notDone(s, signal, again, reply = '') {
1448
1481
  // questions typed out instead of asked: once a message, asked again with the tool (someone's there to answer)
1449
1482
  if (!s.isSub && !s.ui.noUser && !s.askedUser && !s.askNudged && askedInText(reply)) {
@@ -1468,6 +1501,36 @@ export async function notDone(s, signal, again, reply = '') {
1468
1501
  log('task', `the answer names files that don't exist: ${missing.join(', ')}`)
1469
1502
  return prompt('agent/not-done', { missing: missing.join(', ') })
1470
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
+ }
1471
1534
  if (s.acted && reply && PROMISED_MORE.test(reply)) {
1472
1535
  log('task', 'reply names a next step but no tool call followed; nudging to finish')
1473
1536
  return prompt('agent/not-done', { early: true })
@@ -1477,6 +1540,9 @@ export async function notDone(s, signal, again, reply = '') {
1477
1540
  return hook.block ? prompt('agent/hook', { reason: hook.block, stop: true }) : null
1478
1541
  }
1479
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
+
1480
1546
  // Files the final answer says were made, that aren't in the project: a path in backticks, or one
1481
1547
  // with a folder, with a source/config/doc extension, while the answer says it created or wrote
1482
1548
  // something. A name that's anywhere in the project (by its file name) counts as there.
@@ -1566,7 +1632,7 @@ export async function review(s, task, answer, signal) {
1566
1632
  if (!diffs.length) diffs.push('(no files changed)')
1567
1633
  const plan = (s.chat.todos ?? []).map((t) => `- [${t.status === 'completed' ? 'x' : ' '}] ${t.content}`).join('\n')
1568
1634
  const ran = (s.ran ?? []).slice(-15).map((r) => `- ${clip(r.command.replace(/\s+/g, ' '), 160)} → ${r.result}`).join('\n')
1569
- 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 ?? [])]) })
1570
1636
  const self = { provider: s.client.provider, model: s.client.model, self: true }
1571
1637
  const others = (s.team?.() ?? []).filter((t) => t.tools !== false && !(t.provider === self.provider && t.model === self.model))
1572
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
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)
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
  }
package/src/client.js CHANGED
@@ -2,6 +2,8 @@
2
2
  import { createHash } from 'node:crypto'
3
3
  import { setTimeout as sleep } from 'node:timers/promises'
4
4
  import { log, logRequest, requestLog } from './log.js'
5
+ import { loadRankings, scoreOf } from './rankings.js'
6
+ import { fetch } from './http.js' // not the built-in one: see http.js
5
7
 
6
8
  // Tokens in a text, estimated the way tokenizers split it: a word or a number is about one, a long
7
9
  // word more, every symbol one. Prose comes out near characters ÷ 4; code, CSS, JSON and SVG paths,
@@ -267,17 +269,18 @@ export class Client {
267
269
  // Which model of the list to go on to after this one failed, for one request (tried: the places
268
270
  // tried, down: the providers that answered with an error, 400 or above). A provider that answered
269
271
  // with an error isn't asked again through its next model: the next one is from another provider.
270
- // When every provider has failed, the models not tried yet, in order; when all have been tried,
272
+ // The best-ranked of your models first (scoreOf: the next in a list is often a much smaller model,
273
+ // and the work goes on with it), then the unranked ones in your order. Your #1 still starts each
274
+ // message. When every provider has failed, the models not tried yet; when all have been tried,
271
275
  // simply the next one (round again).
272
276
  #pick(e, tried, down) {
273
277
  const r = this.rotation
274
278
  tried.add(r.at)
275
279
  if (e?.status >= 400) down.add(r.list[r.at].provider)
276
280
  const n = r.list.length
277
- const after = (ok) => {
278
- for (let k = 1; k <= n; k++) if (ok((r.at + k) % n)) return (r.at + k) % n
279
- return -1
280
- }
281
+ const data = loadRankings()
282
+ const order = [...Array(n - 1).keys()].map((k) => (r.at + k + 1) % n).map((i) => ({ i, score: (r.list[i].score ??= scoreOf(r.list[i].model, data)) })).sort((a, b) => a.score - b.score).map((x) => x.i) // stable: unranked keep your order
283
+ const after = (ok) => order.find(ok) ?? -1
281
284
  let i = after((i) => !tried.has(i) && !down.has(r.list[i].provider))
282
285
  if (i < 0) i = after((i) => !tried.has(i))
283
286
  if (i < 0) {
package/src/config.js CHANGED
@@ -25,8 +25,37 @@ const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director',
25
25
  // sending for it is stalled.
26
26
  export function speedOf(cfg) {
27
27
  const sec = (v, d, min, max) => (Number.isInteger(Number(v)) && Number(v) >= min && Number(v) <= max ? Number(v) : d)
28
- return { replyStart: sec(cfg.replyStart, 60, 5, 600), replyIdle: sec(cfg.replyIdle, 150, 10, 1800) }
28
+ return { replyStart: sec(cfg.replyStart, 45, 5, 600), replyIdle: sec(cfg.replyIdle, 60, 10, 1800) }
29
29
  }
30
+ // A model test's wait (seconds): the one set, else 60, never less than Give up's (a test that waits less
31
+ // would call a model broken that a task still waits for)
32
+ export const testWaitOf = (cfg) => (Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : Math.max(60, speedOf(cfg).replyStart))
33
+
34
+ // The time limits that depend on one another, kept from contradicting: a test waits at least as long as
35
+ // a model gets to start answering (Tests wait ≥ Give up), and a reply that has started may go quiet at
36
+ // least that long too (Stalled ≥ Give up: a pause mid-reply has the same causes as a slow start, a
37
+ // queue or thinking that isn't sent). The one just set (changed) stays; the other moves to fit. Returns
38
+ // what moved and why, for the page to say.
39
+ export function fitTimes(cfg, changed) {
40
+ const notes = []
41
+ const { replyStart: start, replyIdle: idle } = speedOf(cfg)
42
+ const test = Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : null
43
+ const [sLo] = SPEED_LIMITS.replyStart
44
+ if (changed === 'replyStart') {
45
+ if (test !== null && test < start) (cfg.testTimeout = start), notes.push({ name: 'testTimeout', text: `Tests wait raised to ${start} s too: a test should wait at least as long as Give up, or it calls a model broken that real work would still wait for` })
46
+ if (idle < start) (cfg.replyIdle = start), notes.push({ name: 'replyIdle', text: `Stalled raised to ${start} s too: a reply that has started may go quiet at least as long as a model gets to start` })
47
+ } else if (changed === 'replyIdle') {
48
+ if (start > idle) (cfg.replyStart = Math.max(sLo, idle)), notes.push({ name: 'replyStart', text: `Give up lowered to ${cfg.replyStart} s too: a model can't get longer to start than a started reply may go quiet` })
49
+ } else if (changed === 'testTimeout' && test !== null && test < start) {
50
+ if (test >= sLo) (cfg.replyStart = test), notes.push({ name: 'replyStart', text: `Give up lowered to ${test} s too: real work shouldn't wait longer for a model than its test does` })
51
+ else {
52
+ Object.assign(cfg, { testTimeout: sLo, replyStart: sLo })
53
+ notes.push({ name: 'testTimeout', text: `Tests wait set to ${sLo} s: the shortest Give up can be, and a test must wait at least as long` }, { name: 'replyStart', text: `Give up lowered to ${sLo} s too: real work shouldn't wait longer for a model than its test does` })
54
+ }
55
+ }
56
+ return notes
57
+ }
58
+
30
59
  // What a helper can be picked for (Your models' pills): [its label there, what #1 is told it's good at,
31
60
  // what the pill covers (its tooltip)]
32
61
  export const HELPER_JOBS = {
package/src/format.js CHANGED
@@ -11,6 +11,7 @@ import path from 'node:path'
11
11
  import { HOME, readJson } from './config.js'
12
12
  import { runCommand } from './tools.js'
13
13
  import { log } from './log.js'
14
+ import { onPath } from './spawn.js'
14
15
 
15
16
  const has = (root, f) => fs.existsSync(path.join(root, f))
16
17
  const read = (root, f) => {
@@ -20,9 +21,10 @@ const read = (root, f) => {
20
21
  return ''
21
22
  }
22
23
  }
23
- const onPath = (cmd) => (process.env.PATH ?? '').split(path.delimiter).some((d) => d && fs.existsSync(path.join(d, cmd)))
24
- const local = (root, cmd) => (has(root, `node_modules/.bin/${cmd}`) ? path.join(root, 'node_modules/.bin', cmd) : null)
25
- const q = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`
24
+ const WIN = process.platform === 'win32'
25
+ const local = (root, cmd) => ((cmd = WIN ? `${cmd}.cmd` : cmd), has(root, `node_modules/.bin/${cmd}`) ? path.join(root, 'node_modules/.bin', cmd) : null) // npm's .cmd on Windows
26
+ // a path quoted for the shell the command runs in: cmd.exe on Windows (double quotes), sh elsewhere
27
+ const q = (s) => (WIN ? `"${String(s).replace(/"/g, '""')}"` : `'${String(s).replace(/'/g, `'\\''`)}'`)
26
28
 
27
29
  // [file pattern, (root) → the command (the file's path is added at the end), or null]
28
30
  const BUILTIN = [
package/src/http.js ADDED
@@ -0,0 +1,96 @@
1
+ // fetch, over node:http and node:https (HTTP/1.1) instead of Node's built-in fetch.
2
+ // The built-in one speaks HTTP/2 when a server offers it, and HTTP/2 puts every request to a host on
3
+ // one connection. When that connection dies without a word (the server or a router drops it, no FIN
4
+ // arrives), Node keeps it as open, every later request waits on it, and none is ever sent: a
5
+ // session whose providers all sit behind one proxy host had every model "not answering" for hours
6
+ // while the host answered curl at once. Here each request has a socket of its own (idle ones reused
7
+ // for a few seconds at most, Node's keep-alive agent), and a request that's stopped (Esc, a timeout)
8
+ // takes its socket with it, so a dead connection can't outlive the request that found it.
9
+ // Same shape as fetch: a standard Response, the signal's reason when stopped, a TypeError with
10
+ // cause (the code: ECONNREFUSED, ENOTFOUND…) when the server can't be reached.
11
+ import http from 'node:http'
12
+ import https from 'node:https'
13
+ import zlib from 'node:zlib'
14
+ import { Readable } from 'node:stream'
15
+
16
+ // each decoder flushing what it has as it comes (a streamed answer arrives piece by piece)
17
+ const Z = { flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH }
18
+ const BR = { flush: zlib.constants.BROTLI_OPERATION_FLUSH, finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH }
19
+ const DECODE = { gzip: () => zlib.createGunzip(Z), 'x-gzip': () => zlib.createGunzip(Z), deflate: () => zlib.createInflate(Z), br: () => zlib.createBrotliDecompress(BR), ...(zlib.createZstdDecompress && { zstd: () => zlib.createZstdDecompress() }) }
20
+ const ACCEPT = Object.keys(DECODE).filter((k) => k !== 'x-gzip').join(', ')
21
+ const NO_BODY = new Set([101, 103, 204, 205, 304])
22
+
23
+ export async function fetch(input, init = {}) {
24
+ const { signal, redirect = 'follow' } = init
25
+ // the body and headers as fetch would send them (a string, JSON, form data, URLSearchParams, a Blob…)
26
+ const asked = new Request(input, { method: init.method, headers: init.headers, body: init.body, duplex: 'half' })
27
+ let url = new URL(asked.url)
28
+ let method = asked.method
29
+ const headers = Object.fromEntries(asked.headers)
30
+ headers['accept-encoding'] ??= ACCEPT
31
+ let body = asked.body ? Buffer.from(await asked.arrayBuffer()) : null
32
+ for (let hops = 0; ; hops++) {
33
+ signal?.throwIfAborted()
34
+ const res = await send(url, method, body ? { ...headers, 'content-length': String(body.length) } : headers, body, signal)
35
+ const to = res.headers.location
36
+ if (redirect === 'manual' || ![301, 302, 303, 307, 308].includes(res.statusCode) || !to) return respond(res, url, hops > 0, signal)
37
+ res.resume() // a redirect's own body isn't read
38
+ if (redirect === 'error') throw new TypeError('fetch failed', { cause: new Error(`redirected to ${to}`) })
39
+ if (hops >= 20) throw new TypeError('fetch failed', { cause: new Error('too many redirects') })
40
+ const next = new URL(to, url)
41
+ // 303, and 301/302 after a POST: the next one is a GET, without the body (as fetch does)
42
+ if (res.statusCode === 303 || ([301, 302].includes(res.statusCode) && method === 'POST')) {
43
+ if (method !== 'HEAD') method = 'GET'
44
+ body = null
45
+ for (const h of ['content-type', 'content-length']) delete headers[h]
46
+ }
47
+ if (next.origin !== url.origin) delete headers.authorization // a key isn't handed to another site
48
+ url = next
49
+ }
50
+ }
51
+
52
+ // One request; resolves with the response once its headers are in.
53
+ function send(url, method, headers, body, signal) {
54
+ return new Promise((resolve, reject) => {
55
+ const req = (url.protocol === 'https:' ? https : http).request(url, { method, headers })
56
+ const stop = () => req.destroy(signal.reason)
57
+ signal?.addEventListener('abort', stop, { once: true })
58
+ req.on('response', (res) => {
59
+ // stopped later (while the body streams): the body ends with the reason, and the socket goes too
60
+ res.once('close', () => signal?.removeEventListener('abort', stop))
61
+ resolve(res)
62
+ })
63
+ req.on('error', (e) => {
64
+ signal?.removeEventListener('abort', stop)
65
+ reject(signal?.aborted ? signal.reason : new TypeError('fetch failed', { cause: e }))
66
+ })
67
+ req.end(body ?? undefined)
68
+ })
69
+ }
70
+
71
+ function respond(res, url, redirected, signal) {
72
+ const headers = new Headers()
73
+ for (let i = 0; i < res.rawHeaders.length; i += 2) headers.append(res.rawHeaders[i], res.rawHeaders[i + 1])
74
+ let body = null
75
+ if (NO_BODY.has(res.statusCode) || res.req?.method === 'HEAD') res.resume()
76
+ else {
77
+ let stream = res
78
+ const decode = DECODE[String(res.headers['content-encoding'] ?? '').trim().toLowerCase()]
79
+ if (decode) {
80
+ stream = decode()
81
+ res.on('error', (e) => stream.destroy(e))
82
+ res.pipe(stream)
83
+ }
84
+ stream.on('error', () => {}) // reported through the body (below), not as a crash
85
+ // the body errors with the signal's reason when stopped (as fetch's does), else with a TypeError
86
+ const reason = (e) => (signal?.aborted ? signal.reason : new TypeError('terminated', { cause: e }))
87
+ const reader = Readable.toWeb(stream).getReader()
88
+ body = new ReadableStream({
89
+ pull: (c) => reader.read().then(({ done, value }) => (done ? c.close() : c.enqueue(new Uint8Array(value))), (e) => c.error(reason(e))),
90
+ cancel: (why) => (res.destroy(), reader.cancel(why).catch(() => {})),
91
+ })
92
+ }
93
+ const r = new Response(body, { status: res.statusCode, statusText: res.statusMessage, headers })
94
+ Object.defineProperties(r, { url: { value: url.href }, redirected: { value: redirected } })
95
+ return r
96
+ }
package/src/importer.js CHANGED
@@ -10,6 +10,7 @@ import { spawnSync } from 'node:child_process'
10
10
  import { HOME, TEMP, readJson, writeJson } from './config.js'
11
11
  import { frontMatter } from './skills.js'
12
12
  import { Memory } from './memory.js'
13
+ import { fetch } from './http.js' // not the built-in one: see http.js
13
14
 
14
15
  const exists = (p) => {
15
16
  try {
package/src/lsp.js CHANGED
@@ -6,7 +6,7 @@
6
6
  // back to the model with the edit's result. The settings page (General → Features) turns that off.
7
7
  import fs from 'node:fs'
8
8
  import path from 'node:path'
9
- import { spawn } from 'node:child_process'
9
+ import { spawnCmd, killTree } from './spawn.js'
10
10
  import { pathToFileURL, fileURLToPath } from 'node:url'
11
11
  import { log } from './log.js'
12
12
  import { HOME, readJson, writeJson } from './config.js'
@@ -45,7 +45,7 @@ const words = (cmd) => [...String(cmd).matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].m
45
45
  class Server {
46
46
  constructor(spec, argv, root) {
47
47
  Object.assign(this, { spec, root, next: 1, pending: new Map(), docs: new Map(), diags: new Map(), waiters: new Set(), dead: false })
48
- this.child = spawn(argv[0], argv.slice(1), { cwd: root, stdio: ['pipe', 'pipe', 'ignore'], detached: process.platform !== 'win32' })
48
+ this.child = spawnCmd(argv[0], argv.slice(1), { cwd: root, stdio: ['pipe', 'pipe', 'ignore'], detached: process.platform !== 'win32' })
49
49
  let buf = Buffer.alloc(0)
50
50
  this.child.stdout.on('data', (d) => {
51
51
  buf = Buffer.concat([buf, d])
@@ -176,10 +176,7 @@ class Server {
176
176
  stop() {
177
177
  if (this.dead) return
178
178
  this.dead = true
179
- try {
180
- if (process.platform !== 'win32') process.kill(-this.child.pid, 'SIGTERM')
181
- else this.child.kill()
182
- } catch {}
179
+ if (!killTree(this.child.pid)) try { this.child.kill() } catch {}
183
180
  }
184
181
  }
185
182