heartcode 0.1.45 → 0.1.56

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/check.js ADDED
@@ -0,0 +1,411 @@
1
+ // Checks HeartCode runs itself, so "done" is something proven rather than claimed: a handoff's check
2
+ // (a shell command that must exit 0, or "page <file|url>": a web page opened in a real browser) and
3
+ // the browser the skill tests use. The browser: Chrome, Chromium or Edge, headless, driven over the
4
+ // DevTools protocol (Node's own WebSocket), with nothing installed (none on the computer: a headless
5
+ // one is fetched once, ensureChrome). No browser at all: a page gets a static check instead (the
6
+ // files it uses are there, its scripts parse), and says so.
7
+ import { spawn, execFileSync } from 'node:child_process'
8
+ import fs from 'node:fs'
9
+ import http from 'node:http'
10
+ import os from 'node:os'
11
+ import path from 'node:path'
12
+ import zlib from 'node:zlib'
13
+ import { HOME } from './config.js'
14
+ import { log } from './log.js'
15
+
16
+ const wait = (ms) => new Promise((r) => setTimeout(r, ms))
17
+ const tail = (t, n = 2500) => ((t = String(t).trim()), t.length > n ? `…${t.slice(-n)}` : t)
18
+
19
+ // --- a browser ---
20
+ let chrome // its path, once found ('' when there's none)
21
+ export function findChrome() {
22
+ if (chrome !== undefined) return chrome
23
+ const mac = ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium', '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge']
24
+ const win = ['PROGRAMFILES', 'PROGRAMFILES(X86)', 'LOCALAPPDATA'].flatMap((v) => (process.env[v] ? [path.join(process.env[v], 'Google/Chrome/Application/chrome.exe'), path.join(process.env[v], 'Microsoft/Edge/Application/msedge.exe')] : []))
25
+ const named = ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser', 'microsoft-edge']
26
+ const which = (n) => {
27
+ try {
28
+ return execFileSync(process.platform === 'win32' ? 'where' : 'which', [n], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).split('\n')[0].trim()
29
+ } catch {
30
+ return ''
31
+ }
32
+ }
33
+ chrome = [process.env.CHROME_PATH, ...mac, ...win].find((p) => p && fs.existsSync(p)) ?? named.map(which).find(Boolean) ?? fetched() ?? ''
34
+ return chrome
35
+ }
36
+
37
+ // No browser on the computer: Google's headless one for testing (Chrome for Testing's
38
+ // chrome-headless-shell, about 100 MB), fetched once into ~/.heart/browser. note(text): what's happening.
39
+ const SHELL = { 'linux-x64': 'linux64', 'linux-arm64': 'linux-arm64', 'darwin-arm64': 'mac-arm64', 'darwin-x64': 'mac-x64', 'win32-x64': 'win64', 'win32-ia32': 'win32' }[`${process.platform}-${process.arch}`]
40
+ const BROWSERS = path.join(HOME, 'browser')
41
+ const shellPath = (dir) => path.join(dir, `chrome-headless-shell-${SHELL}`, `chrome-headless-shell${process.platform === 'win32' ? '.exe' : ''}`)
42
+ function fetched() {
43
+ if (!SHELL || !fs.existsSync(BROWSERS)) return undefined
44
+ const got = fs.readdirSync(BROWSERS).sort().reverse().map((v) => shellPath(path.join(BROWSERS, v))).find((f) => fs.existsSync(f))
45
+ return got
46
+ }
47
+ let fetching = null
48
+ export async function ensureChrome(note = () => {}) {
49
+ if (findChrome()) return chrome
50
+ if (!SHELL) return ''
51
+ return (fetching ??= (async () => {
52
+ try {
53
+ note('no browser here: fetching a headless one for page checks (once, about 100 MB)')
54
+ const list = await (await fetch('https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json', { signal: AbortSignal.timeout(30_000) })).json()
55
+ const stable = list.channels.Stable
56
+ const url = stable.downloads['chrome-headless-shell'].find((d) => d.platform === SHELL)?.url
57
+ if (!url) return ''
58
+ const res = await fetch(url, { signal: AbortSignal.timeout(10 * 60_000) })
59
+ if (!res.ok) throw new Error(`${res.status} from ${url}`)
60
+ const dir = path.join(BROWSERS, stable.version)
61
+ unzip(Buffer.from(await res.arrayBuffer()), dir)
62
+ chrome = fs.existsSync(shellPath(dir)) ? shellPath(dir) : ''
63
+ note(chrome ? `browser ready: ${chrome}` : "couldn't unpack the browser")
64
+ return chrome
65
+ } catch (e) {
66
+ note(`couldn't fetch a browser: ${e.message}`)
67
+ return ''
68
+ } finally {
69
+ fetching = null
70
+ }
71
+ })())
72
+ }
73
+
74
+ // A zip archive into dest (stored or deflated entries, with their file modes): Node has no unzip,
75
+ // and not every system has one either (GNU tar can't read zips).
76
+ export function unzip(buf, dest) {
77
+ let end = buf.length - 22
78
+ while (end >= 0 && buf.readUInt32LE(end) !== 0x06054b50) end--
79
+ if (end < 0) throw new Error('not a zip file')
80
+ let at = buf.readUInt32LE(end + 16)
81
+ for (let n = buf.readUInt16LE(end + 10); n > 0; n--) {
82
+ if (buf.readUInt32LE(at) !== 0x02014b50) throw new Error('a broken zip file')
83
+ const method = buf.readUInt16LE(at + 10), size = buf.readUInt32LE(at + 20), nameLen = buf.readUInt16LE(at + 28), extraLen = buf.readUInt16LE(at + 30), commentLen = buf.readUInt16LE(at + 32)
84
+ const mode = buf.readUInt32LE(at + 38) >>> 16, local = buf.readUInt32LE(at + 42)
85
+ const name = buf.toString('utf8', at + 46, at + 46 + nameLen)
86
+ at += 46 + nameLen + extraLen + commentLen
87
+ const file = path.resolve(dest, name)
88
+ if (!file.startsWith(path.resolve(dest) + path.sep)) continue // no writing outside it
89
+ if (name.endsWith('/')) {
90
+ fs.mkdirSync(file, { recursive: true })
91
+ continue
92
+ }
93
+ const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28)
94
+ const data = buf.subarray(start, start + size)
95
+ fs.mkdirSync(path.dirname(file), { recursive: true })
96
+ if ((mode & 0o170000) === 0o120000) {
97
+ fs.symlinkSync((method === 8 ? zlib.inflateRawSync(data) : data).toString(), file)
98
+ continue
99
+ }
100
+ fs.writeFileSync(file, method === 8 ? zlib.inflateRawSync(data) : data)
101
+ if (mode & 0o111 && process.platform !== 'win32') fs.chmodSync(file, mode & 0o777)
102
+ }
103
+ }
104
+
105
+ // A file server for a folder, on a free port: { url, close() } (pages loaded as files can't use
106
+ // modules or fetch, so they'd fail in a way they don't for the user)
107
+ const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.glb': 'model/gltf-binary', '.gltf': 'model/gltf+json', '.wasm': 'application/wasm', '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.ogg': 'audio/ogg' }
108
+ function serve(dir) {
109
+ const server = http.createServer((req, res) => {
110
+ let file
111
+ try {
112
+ file = path.join(dir, decodeURIComponent(new URL(req.url, 'http://x').pathname))
113
+ } catch {
114
+ return res.writeHead(400).end('bad path') // "50%off.png": what the page asked for isn't a path
115
+ }
116
+ if (file !== dir && !file.startsWith(dir + path.sep)) return res.writeHead(403).end()
117
+ try {
118
+ if (fs.statSync(file).isDirectory()) file = path.join(file, 'index.html')
119
+ if (!fs.statSync(file).isFile()) throw new Error()
120
+ } catch {
121
+ return res.writeHead(404).end('not found')
122
+ }
123
+ res.writeHead(200, { 'content-type': TYPES[path.extname(file).toLowerCase()] ?? 'application/octet-stream' })
124
+ fs.createReadStream(file).on('error', () => res.destroy()).pipe(res)
125
+ })
126
+ return new Promise((r) => server.listen(0, '127.0.0.1', () => r({ url: `http://127.0.0.1:${server.address().port}`, close: () => server.close() })))
127
+ }
128
+
129
+ // Opens url in a headless browser and calls fn(page) with it; returns what fn returns. page:
130
+ // { send(method, params), run(js) (its value), errors (the page's errors so far), size(w, h), key(name) }.
131
+ // Every step has a time limit (a page stuck in a loop answers nothing), and signal (Esc) ends it at once.
132
+ const STEP_WAIT = 20_000
133
+ export async function browse(url, fn, { width = 1280, height = 800, signal } = {}) {
134
+ if (typeof WebSocket === 'undefined') throw new Error('page checks need Node 22 or newer (this is ' + process.version + ')')
135
+ const exe = await ensureChrome()
136
+ if (!exe) throw new Error('no Chrome, Chromium or Edge found, and none could be fetched (set CHROME_PATH)')
137
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'heart-chrome-'))
138
+ // its own sandbox off only where the system won't let it make one (root; Ubuntu's AppArmor refusing
139
+ // a browser it doesn't know): it's then tried again without
140
+ const launch = (bare) => spawn(exe, ['--headless=new', '--remote-debugging-port=0', `--user-data-dir=${dir}`, `--window-size=${width},${height}`, '--no-first-run', '--no-default-browser-check', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', ...(bare || process.getuid?.() === 0 ? ['--no-sandbox'] : []), 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] })
141
+ let proc
142
+ let said = ''
143
+ let exited
144
+ const start = (bare) => {
145
+ proc = launch(bare)
146
+ said = ''
147
+ proc.stderr.on('data', (d) => (said = (said + d).slice(-2000)))
148
+ exited = new Promise((r) => proc.once('exit', r))
149
+ }
150
+ start(false)
151
+ let ws
152
+ const pending = new Map()
153
+ const fail = (e) => {
154
+ for (const reject of pending.values()) reject(e)
155
+ pending.clear()
156
+ }
157
+ const stop = () => (fail(signal.reason ?? Object.assign(new Error('stopped'), { name: 'AbortError' })), ws?.close())
158
+ signal?.addEventListener('abort', stop, { once: true })
159
+ try {
160
+ let port
161
+ for (let round = 0; round < 2 && !port; round++) {
162
+ for (let i = 0; i < 100 && !port; i++) {
163
+ if (signal?.aborted) throw signal.reason
164
+ if (proc.exitCode !== null) break
165
+ port = fs.existsSync(path.join(dir, 'DevToolsActivePort')) && fs.readFileSync(path.join(dir, 'DevToolsActivePort'), 'utf8').split('\n')[0]
166
+ if (!port) await wait(100)
167
+ }
168
+ if (port || round || !/sandbox/i.test(said)) break
169
+ proc.kill('SIGKILL')
170
+ await Promise.race([exited, wait(3000)])
171
+ start(true)
172
+ }
173
+ if (!port) throw new Error(`the browser didn't start${said.trim() ? `: ${tail(said.split('\n').filter((l) => /error|cannot|failed/i.test(l)).join(' ') || said, 300)}` : ''}`)
174
+ const target = (await (await fetch(`http://127.0.0.1:${port}/json`)).json()).find((t) => t.type === 'page')
175
+ ws = new WebSocket(target.webSocketDebuggerUrl)
176
+ await new Promise((ok, bad) => ((ws.onopen = ok), (ws.onerror = () => bad(new Error("couldn't reach the browser")))))
177
+ ws.onclose = () => fail(new Error('the browser went away'))
178
+ let id = 0
179
+ const errors = []
180
+ let loaded = null
181
+ const onLoad = new Promise((r) => (loaded = r))
182
+ ws.onmessage = (m) => {
183
+ const d = JSON.parse(m.data)
184
+ if (d.id) return pending.get(d.id)?.(null, d), pending.delete(d.id)
185
+ const p = d.params
186
+ if (d.method === 'Page.loadEventFired') loaded()
187
+ else if (d.method === 'Runtime.exceptionThrown') errors.push(tail(p.exceptionDetails.exception?.description ?? p.exceptionDetails.text, 300))
188
+ else if (d.method === 'Runtime.consoleAPICalled' && p.type === 'error') errors.push(tail(`console.error: ${p.args.map((a) => a.value ?? a.description).join(' ')}`, 300))
189
+ else if (d.method === 'Network.responseReceived' && p.response.status >= 400 && !/favicon\.ico$/.test(p.response.url)) errors.push(`${p.response.status} for ${p.response.url.replace(/^https?:\/\/127\.0\.0\.1:\d+/, '')}`)
190
+ else if (d.method === 'Network.loadingFailed' && !p.canceled && p.type !== 'Other') errors.push(`couldn't load a ${String(p.type).toLowerCase()}: ${p.errorText}`)
191
+ }
192
+ // one DevTools call: its result, or an error when it isn't answered in time. Then the page is asked
193
+ // the smallest thing: no answer, its script is stuck (a loop: stuck, the page's fault); an answer,
194
+ // the computer is just slow at it (a 3D page drawn without a graphics card: slow, not the page's)
195
+ const call = (method, params, ms) =>
196
+ new Promise((ok, bad) => {
197
+ if (signal?.aborted) return bad(signal.reason)
198
+ const n = ++id
199
+ const timer = setTimeout(() => (pending.delete(n), bad(Object.assign(new Error('no answer'), { late: true }))), ms)
200
+ pending.set(n, (e, d) => (clearTimeout(timer), e ? bad(e) : d.error ? bad(new Error(d.error.message)) : ok(d.result)))
201
+ ws.send(JSON.stringify({ id: n, method, params }))
202
+ })
203
+ const send = async (method, params = {}) => {
204
+ try {
205
+ return await call(method, params, STEP_WAIT)
206
+ } catch (e) {
207
+ if (!e.late) throw e
208
+ const alive = await call('Runtime.evaluate', { expression: '1', returnByValue: true }, STEP_WAIT).then(() => true, () => false)
209
+ throw alive
210
+ ? Object.assign(new Error(`this computer was too slow to finish ${method.replace(/^\w+\./, '')} in ${STEP_WAIT / 1000} s (the page itself still responds)`), { slow: true })
211
+ : Object.assign(new Error(`the page stopped responding (${method} got no answer in ${STEP_WAIT / 1000} s, nor did a check after): its script may be stuck in a loop`), { stuck: true })
212
+ }
213
+ }
214
+ const run = async (js) => {
215
+ const r = await send('Runtime.evaluate', { expression: js, returnByValue: true, awaitPromise: true })
216
+ if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text)
217
+ return r.result.value
218
+ }
219
+ const key = async (name, hold = 60) => {
220
+ const code = { Enter: 13, ' ': 32, ArrowUp: 38, ArrowDown: 40, ArrowLeft: 37, ArrowRight: 39 }[name] ?? name.toUpperCase().charCodeAt(0)
221
+ const k = { key: name, code: name === ' ' ? 'Space' : name.length === 1 ? `Key${name.toUpperCase()}` : name, windowsVirtualKeyCode: code }
222
+ await send('Input.dispatchKeyEvent', { type: 'keyDown', ...k, ...(name === 'Enter' && { text: '\r' }) })
223
+ await wait(hold)
224
+ await send('Input.dispatchKeyEvent', { type: 'keyUp', ...k })
225
+ }
226
+ const size = (w, h) => send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: w < 600 })
227
+ await Promise.all([send('Page.enable'), send('Runtime.enable'), send('Network.enable')])
228
+ await send('Page.navigate', { url })
229
+ await Promise.race([onLoad, wait(20_000)])
230
+ await wait(1500) // what starts after the load (a game's first frames)
231
+ return await fn({ send, run, errors, size, key })
232
+ } finally {
233
+ signal?.removeEventListener('abort', stop)
234
+ try {
235
+ ws?.close()
236
+ } catch {}
237
+ proc.kill('SIGKILL')
238
+ await Promise.race([exited, wait(3000)]) // gone before its folder is: it writes there until then
239
+ try {
240
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 3 })
241
+ } catch {} // (Windows can hold a file a moment longer: the system's temp folder is cleaned anyway)
242
+ }
243
+ }
244
+
245
+ // Serves root and browses the file in it (or a URL as it is)
246
+ export async function browseFile(root, target, fn, opts) {
247
+ if (/^https?:\/\//.test(target)) return browse(target, fn, opts)
248
+ const srv = await serve(path.resolve(root))
249
+ try {
250
+ return await browse(`${srv.url}/${target.replace(/^\.?\//, '').split(path.sep).join('/')}`, fn, opts)
251
+ } finally {
252
+ srv.close()
253
+ }
254
+ }
255
+
256
+ // --- a page's check ---
257
+ // "heartcode page <file|url>": a page checked from a shell (a model checks its own page), with
258
+ // screenshots at desktop and phone size in .heartcode/page-shots/ to look at. Exit 0 when it passes.
259
+ export async function pageCommand(target) {
260
+ if (!target) return console.error('usage: heartcode page <file or URL>'), 2
261
+ const shots = path.join(process.cwd(), '.heartcode', 'page-shots')
262
+ const r = await pageCheck(process.cwd(), target, null, shots, (t) => console.error(t))
263
+ console.log(`${r.ok ? 'PASSED' : 'FAILED'}: ${r.report}`)
264
+ return r.ok ? 0 : 1
265
+ }
266
+
267
+ // A web page: it loads without errors, shows something, and pressing its first button and a few keys
268
+ // breaks nothing
269
+ async function pageCheck(root, target, signal, shots, note) {
270
+ const isUrl = /^https?:\/\//.test(target)
271
+ if (!isUrl) {
272
+ const file = path.resolve(root, target)
273
+ if (!fs.existsSync(file)) return { ok: false, report: `page ${target}: there's no such file` }
274
+ if (fs.statSync(file).isDirectory()) { // a folder: its index.html
275
+ if (!fs.existsSync(path.join(file, 'index.html'))) return { ok: false, report: `page ${target}: a folder with no index.html` }
276
+ target = path.join(target, 'index.html')
277
+ }
278
+ }
279
+ const unchecked = (why) => (isUrl ? { ok: true, report: `page ${target}: not checked (${why})` } : staticPage(root, target, why))
280
+ if (!(await ensureChrome(note))) return unchecked('no browser here')
281
+ try {
282
+ return await browseFile(root, target, async (page) => {
283
+ const seen = await page.run(`(() => {
284
+ const shown = [...document.querySelectorAll('body *')].filter((e) => { const r = e.getBoundingClientRect(), st = getComputedStyle(e); return r.width * r.height > 4 && st.visibility !== 'hidden' && st.display !== 'none' && Number(st.opacity) > 0 })
285
+ return { shown: shown.length, text: (document.body?.innerText ?? '').trim().length, canvas: shown.filter((e) => e.tagName === 'CANVAS').length, pictures: shown.filter((e) => /^(IMG|SVG|VIDEO)$/.test(e.tagName)).length, wide: document.documentElement.scrollWidth > innerWidth + 1 }
286
+ })()`)
287
+ const looks = await page.run(LOOKS).catch((e) => (log('check', `looks: ${e.message}`), null))
288
+ const atLoad = page.errors.length
289
+ const saved = []
290
+ let tooSlow = '' // a screenshot this computer couldn't take in time: left out, the rest still checked
291
+ const shot = async (name) => {
292
+ if (tooSlow) return
293
+ fs.mkdirSync(shots, { recursive: true })
294
+ fs.writeFileSync(path.join(shots, '.gitignore'), '*\n') // HeartCode's, not the project's: git leaves them out
295
+ const file = path.join(shots, `${name}.png`)
296
+ try {
297
+ fs.writeFileSync(file, Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'))
298
+ saved.push(path.relative(root, file))
299
+ } catch (e) {
300
+ if (!e.slow) throw e
301
+ tooSlow = e.message
302
+ }
303
+ }
304
+ if (shots) {
305
+ await shot('desktop')
306
+ await page.size(390, 844)
307
+ await wait(800)
308
+ seen.phoneWide = await page.run('document.documentElement.scrollWidth > innerWidth + 1')
309
+ await shot('phone')
310
+ await page.send('Emulation.clearDeviceMetricsOverride')
311
+ await wait(500)
312
+ }
313
+ const button = await page.run(`(() => { const b = [...document.querySelectorAll('button, [role=button], input[type=button], input[type=submit]')].find((e) => !e.disabled && e.getBoundingClientRect().width > 0 && getComputedStyle(e).visibility !== 'hidden'); if (!b) return ''; b.click(); return (b.innerText || b.value || b.getAttribute('aria-label') || 'a button').trim().slice(0, 40) })()`).catch(() => '')
314
+ await wait(500)
315
+ for (const k of ['Enter', ' ', 'ArrowUp', 'ArrowLeft']) await page.key(k, 150)
316
+ await wait(1500)
317
+ const problems = []
318
+ if (!seen.shown || (!seen.text && !seen.canvas && !seen.pictures)) problems.push('the page shows nothing')
319
+ 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
+ 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
+ if (looks?.icons.length) problems.push(`icons that didn't draw (no such name): ${looks.icons.join(', ')}`)
322
+ if (seen.phoneWide) problems.push('on a phone (390 px) it scrolls sideways: something is wider than the screen')
323
+ 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
+ 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}` }
326
+ }, { signal })
327
+ } catch (e) {
328
+ 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
330
+ return unchecked(e.message)
331
+ }
332
+ }
333
+
334
+ // What a page looks like, measured in the browser, for what can be told for sure: text whose contrast
335
+ // with what's behind it is under WCAG's minimum (colors through a canvas, so any CSS color works;
336
+ // text on an image or gradient is skipped), how much of the text is invisible at load (opacity 0,
337
+ // visibility hidden: revealed later by scrolling or a timer), and Lucide icons left undrawn.
338
+ const LOOKS = `(() => {
339
+ const cv = document.createElement('canvas'); cv.width = cv.height = 1
340
+ const cx = cv.getContext('2d', { willReadFrequently: true })
341
+ const rgba = (c) => { cx.clearRect(0, 0, 1, 1); cx.fillStyle = '#000'; cx.fillStyle = c; cx.fillRect(0, 0, 1, 1); const d = cx.getImageData(0, 0, 1, 1).data; return [d[0], d[1], d[2], d[3] / 255] }
342
+ const lum = ([r, g, b]) => { const f = (v) => (v /= 255) <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b) }
343
+ const over = (top, under) => top.slice(0, 3).map((v, i) => v * top[3] + under[i] * (1 - top[3]))
344
+ const behind = (el) => { // the solid color behind el, or null over an image or gradient
345
+ const layers = []
346
+ for (let e = el; e; e = e.parentElement) {
347
+ const st = getComputedStyle(e)
348
+ if (st.backgroundImage !== 'none') return null
349
+ const c = rgba(st.backgroundColor)
350
+ if (c[3] > 0) layers.push(c)
351
+ if (c[3] >= 1) break
352
+ }
353
+ return layers.reduceRight((acc, c) => over(c, acc), [255, 255, 255])
354
+ }
355
+ const hex = (c) => '#' + c.slice(0, 3).map((v) => Math.round(v).toString(16).padStart(2, '0')).join('')
356
+ const low = []
357
+ let all = 0, unseen = 0
358
+ for (const el of document.querySelectorAll('body *')) {
359
+ const own = [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent).join('').trim()
360
+ if (!/[\\p{L}\\p{N}]/u.test(own) || el.closest('[aria-hidden=true],[inert],script,style,noscript,template,option') || el.matches(':disabled')) continue
361
+ const st = getComputedStyle(el), r = el.getBoundingClientRect()
362
+ if (st.display === 'none' || !r.width || !r.height) continue
363
+ all += own.length
364
+ if (!el.checkVisibility({ opacityProperty: true, visibilityProperty: true })) { unseen += own.length; continue }
365
+ const bg = behind(el)
366
+ if (!bg) continue
367
+ const fg = rgba(st.color)
368
+ const text = over(fg, bg)
369
+ const [a, b] = [lum(text), lum(bg)].sort((x, y) => y - x)
370
+ const ratio = (a + 0.05) / (b + 0.05)
371
+ const size = parseFloat(st.fontSize), bold = Number(st.fontWeight) >= 700
372
+ const need = size >= 24 || (bold && size >= 18.66) ? 3 : 4.5
373
+ if (ratio < need) low.push({ text: own.slice(0, 40), ratio: Math.round(ratio * 10) / 10, fg: hex(text), bg: hex(bg) })
374
+ }
375
+ return { lowContrast: low.slice(0, 6), hidden: all && unseen / all > 0.25 ? Math.round((100 * unseen) / all) : 0, icons: [...new Set([...document.querySelectorAll('i[data-lucide]')].map((e) => e.dataset.lucide))].slice(0, 10) }
376
+ })()`
377
+
378
+ // No browser: the files a page uses are there and its scripts parse
379
+ function staticPage(root, target, why = 'no browser here') {
380
+ const file = path.resolve(root, target)
381
+ let html
382
+ try {
383
+ html = fs.readFileSync(file, 'utf8')
384
+ } catch (e) {
385
+ return { ok: false, report: `page ${target}: couldn't read it (${e.code ?? e.message})` }
386
+ }
387
+ const dir = path.dirname(file)
388
+ const problems = []
389
+ const refs = [...html.matchAll(/<(?:script|img|link|source|audio|video)\b[^>]*?\b(?:src|href)=["']([^"'#?]+)/gi)].map((m) => m[1]).filter((u) => !/^(https?:|data:|\/\/|mailto:)/.test(u))
390
+ for (const u of refs) if (!fs.existsSync(path.resolve(dir, u.replace(/^\//, '')))) problems.push(`it uses ${u}, which isn't there`)
391
+ const parse = (code, name, module) => {
392
+ const tmp = path.join(os.tmpdir(), `heart-check-${process.pid}-${Math.random().toString(36).slice(2)}${module ? '.mjs' : '.js'}`)
393
+ fs.writeFileSync(tmp, code)
394
+ try {
395
+ execFileSync(process.execPath, ['--check', tmp], { stdio: ['ignore', 'ignore', 'pipe'] })
396
+ } catch (e) {
397
+ problems.push(`${name} doesn't parse: ${tail(String(e.stderr).split(/\n\s+at /)[0].replaceAll(tmp, name), 300)}`)
398
+ } finally {
399
+ fs.rmSync(tmp, { force: true })
400
+ }
401
+ }
402
+ for (const [i, m] of [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].entries()) {
403
+ if (/\bsrc=/.test(m[1]) || /type=["'](?!module|text\/javascript)/i.test(m[1]) || !m[2].trim()) continue
404
+ parse(m[2], `the page's script #${i + 1}`, /module/.test(m[1]))
405
+ }
406
+ for (const u of refs.filter((u) => /\.m?js$/.test(u))) {
407
+ const f = path.resolve(dir, u.replace(/^\//, ''))
408
+ if (fs.existsSync(f)) parse(fs.readFileSync(f, 'utf8'), u, /import|export/.test(fs.readFileSync(f, 'utf8')))
409
+ }
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'}` }
411
+ }
package/src/client.js CHANGED
@@ -102,35 +102,35 @@ export function normalizeBaseUrl(url) {
102
102
  }
103
103
 
104
104
  // Removes the thinking some models put in the normal content: a <think> block the reply starts
105
- // with (still open: all of it so far). A reply that only mentions the tag later keeps its text. A
106
- // closing tag with no opening one counts only for a model that thinks (some leave the opening out).
105
+ // with (<thought> from Gemini; still open: all of it so far). A reply that only mentions the tag
106
+ // later keeps its text. A closing tag with no opening one counts only for a model that thinks (some
107
+ // leave the opening out).
107
108
  export function stripThink(text, thinks = false) {
108
109
  const t = String(text ?? '')
109
- const lead = /^\s*<think>[\s\S]*?(<\/think>|$)/.exec(t)
110
+ const lead = /^\s*<(think|thought)>[\s\S]*?(<\/\1>|$)/.exec(t)
110
111
  if (lead) return t.slice(lead[0].length).trimStart()
111
112
  const close = thinks && !t.includes('<think>') ? t.indexOf('</think>') : -1
112
113
  return close !== -1 ? t.slice(close + 8).trimStart() : t
113
114
  }
114
115
 
115
- // What can be shown so far while streaming: holds back a half-received "<think>".
116
+ // What can be shown so far while streaming: holds back a half-received "<think>" or "<thought>".
116
117
  function visible(full, thinks) {
117
118
  let v = stripThink(full, thinks)
118
- for (let k = 7; k > 0; k--) {
119
- if (v.endsWith('<think>'.slice(0, k))) return v.slice(0, -k)
120
- }
119
+ for (const tag of ['<thought>', '<think>']) for (let k = tag.length - 1; k > 0; k--) if (v.endsWith(tag.slice(0, k)) && v.trim() === tag.slice(0, k)) return v.slice(0, -k)
121
120
  return v
122
121
  }
123
122
 
124
- // The text inside the <think> block the reply starts with, so far (an unclosed one counts),
125
- // holding back a half-received "</think>".
123
+ // The text inside the <think> (or <thought>) block the reply starts with, so far (an unclosed one
124
+ // counts), holding back a half-received closing tag.
126
125
  export function thinkOf(full) {
127
- const m = /^\s*<think>/.exec(full)
126
+ const m = /^\s*<(think|thought)>/.exec(full)
128
127
  if (!m) return ''
129
- const close = full.indexOf('</think>', m[0].length)
128
+ const end = `</${m[1]}>`
129
+ const close = full.indexOf(end, m[0].length)
130
130
  if (close !== -1) return full.slice(m[0].length, close)
131
131
  let rest = full.slice(m[0].length)
132
- for (let k = 8; k > 0; k--) {
133
- if (rest.endsWith('</think>'.slice(0, k))) return rest.slice(0, -k)
132
+ for (let k = end.length; k > 0; k--) {
133
+ if (rest.endsWith(end.slice(0, k))) return rest.slice(0, -k)
134
134
  }
135
135
  return rest
136
136
  }
@@ -140,7 +140,8 @@ export function thinkOf(full) {
140
140
  // calls only for one that calls tools (else as text), tool call ids in one form every provider
141
141
  // takes (9 letters and digits), tool arguments always JSON, and only its own thinking sent back.
142
142
  // can: { vision, actions } (the model's abilities); the saved conversation stays as it is.
143
- export const writtenBy = new WeakMap() // an assistant message → the model that wrote it
143
+ // writer: the model that wrote an assistant message (agent.js), kept on it so a resumed or forked
144
+ // chat still knows; never sent (providers refuse unknown fields).
144
145
  const IMAGE_NOTE = "(an image is here, but you can't see images: to know what's in it, ask a model that can, with the agent tool's images)"
145
146
  const callId = (id) => (/^[A-Za-z0-9]{9}$/.test(id) ? id : createHash('sha256').update(String(id)).digest('hex').slice(0, 9))
146
147
  const asJson = (a) => {
@@ -153,16 +154,16 @@ const asJson = (a) => {
153
154
  }
154
155
  export function fitFor(messages, can, model) {
155
156
  const tools = can.actions !== 'guided'
156
- return messages.map((m) => {
157
- let x = { ...m }
158
- if (x.reasoning_content && writtenBy.has(m) && writtenBy.get(m) !== model) delete x.reasoning_content
157
+ return messages.map(({ writer, ...m }) => {
158
+ let x = m
159
+ if (x.reasoning_content && writer && writer !== model) delete x.reasoning_content
159
160
  if (Array.isArray(x.content) && !can.vision) x.content = x.content.map((p) => (p.type === 'image_url' ? IMAGE_NOTE : (p.text ?? ''))).join('\n')
160
161
  if (!tools && x.role === 'tool') return { role: 'user', content: `(the result of your earlier tool call)\n${x.content}` }
161
162
  if (!tools && x.tool_calls) {
162
163
  const { tool_calls, ...rest } = x
163
164
  return { ...rest, content: [x.content, ...tool_calls.map((c) => `(called ${c.function.name} ${c.function.arguments || '{}'})`)].filter(Boolean).join('\n') }
164
165
  }
165
- const own = !writtenBy.has(m) || writtenBy.get(m) === model // extra_content (Gemini's thought_signature) only back to its writer: others refuse it (Mistral: 422 extra_forbidden)
166
+ const own = !writer || writer === model // extra_content (Gemini's thought_signature) only back to its writer: others refuse it (Mistral: 422 extra_forbidden)
166
167
  if (x.tool_calls) x.tool_calls = x.tool_calls.map(({ extra_content, ...c }) => ({ ...c, ...(own && extra_content && { extra_content }), id: callId(c.id), function: { ...c.function, arguments: asJson(c.function.arguments) } }))
167
168
  if (x.role === 'tool') x.tool_call_id = callId(x.tool_call_id)
168
169
  return x
@@ -172,7 +173,7 @@ export function fitFor(messages, can, model) {
172
173
  // Refusals a provider may make of one part of a request, learned when sending it without that
173
174
  // part works (then kept in the model's profile for a day): temperature, reasoning_effort, the
174
175
  // usage in a stream, the thinking sent back, the tools' full schemas, images.
175
- export const QUIRKS = ['noTemperature', 'noEffort', 'noStreamUsage', 'noReasoningBack', 'simpleSchemas', 'noImages', 'noParallel']
176
+ export const QUIRKS = ['noTemperature', 'noEffort', 'noThoughts', 'noStreamUsage', 'noReasoningBack', 'simpleSchemas', 'noImages', 'noParallel']
176
177
 
177
178
  export class Client {
178
179
  constructor({ baseUrl, apiKey, model, provider, timeout = 600_000 } = {}) {
@@ -263,27 +264,6 @@ export class Client {
263
264
  }
264
265
  return i
265
266
  }
266
- // An orchestrator: these models first ("provider model"), the others after in your list's order;
267
- // this message starts with the first, and a failure goes on to the next. false: no list.
268
- // null: your order again (switched off).
269
- orderBy(names) {
270
- const r = this.rotation
271
- if (!r) return false
272
- if (!names) {
273
- if (!r.base) return false // never reordered: nothing to undo (and "stay on the last that answered" holds)
274
- ;[r.list, r.base, r.at] = [r.base, null, 0]
275
- this.#use(r.list[0])
276
- return true
277
- }
278
- r.base ??= [...r.list] // your order, kept for when it's switched off
279
- const first = names.map((n) => r.list.find((t) => `${t.provider} ${t.model}` === n)).filter(Boolean)
280
- if (!first.length) return false
281
- r.list = [...new Set([...first, ...r.base])]
282
- r.at = 0
283
- log('rotate', `orchestrators: ${first.map((t) => t.model).join(', ')} first`)
284
- this.#use(r.list[0])
285
- return true
286
- }
287
267
  // A new message: back to #1 (unless it stays on the one that worked)
288
268
  newMessage() {
289
269
  const r = this.rotation
@@ -498,7 +478,7 @@ export class Client {
498
478
  return r
499
479
  } catch (e) {
500
480
  if (e.name === 'AbortError' || opts.signal?.aborted) throw e
501
- this.onFail?.(e, { provider: this.provider, model: this.model }) // counted for orchestration
481
+ this.onFail?.(e, { provider: this.provider, model: this.model }) // what it says is learned (a stated limit)
502
482
  // With a list of models, any failure makes way for the next one (another provider's first).
503
483
  // Without one, only what waiting can fix is tried again.
504
484
  if (!(this.rotation?.list.length > 1) && !outage(e)) throw e
@@ -551,7 +531,7 @@ export class Client {
551
531
  // a model that goes silent is then given up on after idleMs, not after the whole timeout
552
532
  if (body.stream === undefined && !body.tools?.length && !this.quirks.noStream) req.stream = true
553
533
  const can = this.can && { ...this.can, vision: this.can.vision && !this.quirks.noImages }
554
- if (can && req.messages) req.messages = fitFor(req.messages, can, this.model)
534
+ if (req.messages) req.messages = can ? fitFor(req.messages, can, this.model) : req.messages.map(({ writer, ...m }) => m)
555
535
  if (can?.actions === 'guided') delete req.tools
556
536
  const thinks = Boolean(this.can?.thinking)
557
537
  // The model's thinking on its earlier steps (agent.js keeps it as reasoning_content): sent by the
@@ -564,6 +544,8 @@ export class Client {
564
544
  if (this.quirks.simpleSchemas && req.tools) req.tools = req.tools.map((t) => ({ ...t, function: { ...t.function, parameters: simpleSchema(t.function.parameters) } }))
565
545
  if (this.quirks.noTemperature) delete req.temperature
566
546
  if (this.effort && !this.quirks.noEffort) req.reasoning_effort = this.effort
547
+ // Google's own Gemini (gemini-…, models/gemini-…) sends its thinking only when asked, in <thought> tags
548
+ if (this.effort && /^(models\/)?gemini/.test(this.model) && !this.quirks.noThoughts) req.extra_body = { google: { thinking_config: { include_thoughts: true } } }
567
549
  if (req.stream && !this.quirks.noStreamUsage) req.stream_options = { include_usage: true } // token counts for the status bar
568
550
  if (req.tools?.length && !this.quirks.noParallel) req.parallel_tool_calls = true // several calls in one reply (llama.cpp's default is one)
569
551
  let res
@@ -626,6 +608,7 @@ export class Client {
626
608
  const imagesSent = !this.quirks.noImages && req.messages?.some((m) => Array.isArray(m.content) && m.content.some((p) => p.type === 'image_url'))
627
609
  if (/temperature/i.test(said) && 'temperature' in req && !this.quirks.noTemperature) return without('noTemperature')
628
610
  if (/reasoning_effort/.test(said) && 'reasoning_effort' in req && !this.quirks.noEffort) return without('noEffort')
611
+ if (/extra_body|thinking_config|include_thoughts/i.test(said) && req.extra_body && !this.quirks.noThoughts) return without('noThoughts')
629
612
  if (/stream_options/.test(said) && req.stream_options && !this.quirks.noStreamUsage) return without('noStreamUsage')
630
613
  if (/parallel_tool_calls/.test(said) && req.parallel_tool_calls && !this.quirks.noParallel) return without('noParallel')
631
614
  if (/stream/i.test(said) && req.stream && body.stream === undefined && !this.quirks.noStream) return without('noStream') // streamed by HeartCode's choice: not again
package/src/config.js CHANGED
@@ -19,7 +19,16 @@ export function projectDir(root, what) {
19
19
  return dir
20
20
  }
21
21
 
22
- const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search', 'testTimeout', 'updateCheck', 'modelChoice', 'orchestrators', 'logs', 'replyStart', 'mouse']
22
+ const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search', 'testTimeout', 'updateCheck', 'logs', 'replyStart', 'replyIdle', 'mouse']
23
+ // How long a reply may take (the settings page's Your models), in seconds, with the defaults:
24
+ // replyStart: a reply must start within it, else that model failed; replyIdle: a reply that stops
25
+ // sending for it is stalled.
26
+ export function speedOf(cfg) {
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) }
29
+ }
30
+ export const SPEED_LIMITS = { replyStart: [5, 600], replyIdle: [10, 1800] }
31
+
23
32
  const LOCAL_NAMES = { 11434: 'ollama', 1234: 'lmstudio', 8080: 'llamacpp' }
24
33
 
25
34
  export function readJson(file, fallback) {