heartcode 0.1.36 → 0.1.40
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/.claude/scheduled_tasks.lock +1 -0
- package/CHANGELOG.md +93 -0
- package/README.md +20 -7
- package/SKILL.md +5 -3
- package/bin/heart.js +7 -20
- package/bin/heartcode.js +61 -13
- package/package.json +1 -1
- package/prompts/agent.md +114 -115
- package/src/agent.js +63 -252
- package/src/background.js +39 -12
- package/src/client.js +41 -6
- package/src/config.js +1 -1
- package/src/fit.js +65 -0
- package/src/log.js +69 -18
- package/src/parquet.js +209 -0
- package/src/rankings.js +115 -0
- package/src/settings.html +173 -52
- package/src/settings.js +45 -13
- package/src/skills.js +7 -3
- package/src/tools.js +189 -50
- package/src/ui.js +37 -10
- package/src/update.js +59 -0
package/src/client.js
CHANGED
|
@@ -134,7 +134,8 @@ export function fitFor(messages, can, model) {
|
|
|
134
134
|
const { tool_calls, ...rest } = x
|
|
135
135
|
return { ...rest, content: [x.content, ...tool_calls.map((c) => `(called ${c.function.name} ${c.function.arguments || '{}'})`)].filter(Boolean).join('\n') }
|
|
136
136
|
}
|
|
137
|
-
|
|
137
|
+
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)
|
|
138
|
+
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) } }))
|
|
138
139
|
if (x.role === 'tool') x.tool_call_id = callId(x.tool_call_id)
|
|
139
140
|
return x
|
|
140
141
|
})
|
|
@@ -157,6 +158,9 @@ export class Client {
|
|
|
157
158
|
// how long a streamed reply may go without sending anything before it counts as stalled (then
|
|
158
159
|
// tried again, or the next model asked); a reply that keeps coming has no limit, however long
|
|
159
160
|
this.idleMs = 150_000
|
|
161
|
+
// how long a streamed reply may take to start (text, thinking or a tool call; a provider's
|
|
162
|
+
// keep-alive pings while it queues don't count): then it's a failure, and the next model goes on
|
|
163
|
+
this.startMs = 60_000
|
|
160
164
|
this.tokenRatio = 1 // the server's token count / est(): calibrated from usage (context.js)
|
|
161
165
|
this.knownGood = 0 // the biggest request known to work, in tokens
|
|
162
166
|
this.onUsage = null // (prompt tokens the server counted, estimate of what was sent): learns the window
|
|
@@ -231,6 +235,27 @@ export class Client {
|
|
|
231
235
|
}
|
|
232
236
|
return i
|
|
233
237
|
}
|
|
238
|
+
// "Best fit": these models first ("provider model", best first), the others after in your list's
|
|
239
|
+
// order; this message starts with the first, and a failure goes on to the next best. false: no list.
|
|
240
|
+
// null: your order again (best fit switched off).
|
|
241
|
+
orderBy(names) {
|
|
242
|
+
const r = this.rotation
|
|
243
|
+
if (!r) return false
|
|
244
|
+
if (!names) {
|
|
245
|
+
if (!r.base) return false // never reordered: nothing to undo (and "stay on the last that answered" holds)
|
|
246
|
+
;[r.list, r.base, r.at] = [r.base, null, 0]
|
|
247
|
+
this.#use(r.list[0])
|
|
248
|
+
return true
|
|
249
|
+
}
|
|
250
|
+
r.base ??= [...r.list] // your order, kept for when best fit is switched off
|
|
251
|
+
const first = names.map((n) => r.list.find((t) => `${t.provider} ${t.model}` === n)).filter(Boolean)
|
|
252
|
+
if (!first.length) return false
|
|
253
|
+
r.list = [...new Set([...first, ...r.base])]
|
|
254
|
+
r.at = 0
|
|
255
|
+
log('rotate', `best fit: ${first.map((t) => t.model).join(', ')} first`)
|
|
256
|
+
this.#use(r.list[0])
|
|
257
|
+
return true
|
|
258
|
+
}
|
|
234
259
|
// A new message: back to #1 (unless it stays on the one that worked)
|
|
235
260
|
newMessage() {
|
|
236
261
|
const r = this.rotation
|
|
@@ -492,6 +517,9 @@ export class Client {
|
|
|
492
517
|
// One request. Without `once`, rate limits and server errors get three quiet retries.
|
|
493
518
|
async #chat(body, { onToken, onReasoning, onToolDelta, signal, once } = {}) {
|
|
494
519
|
const req = { model: this.model, ...body }
|
|
520
|
+
// a request that doesn't say (a review, a pick, a summary…) is streamed too, when it has no tools:
|
|
521
|
+
// a model that goes silent is then given up on after idleMs, not after the whole timeout
|
|
522
|
+
if (body.stream === undefined && !body.tools?.length && !this.quirks.noStream) req.stream = true
|
|
495
523
|
const can = this.can && { ...this.can, vision: this.can.vision && !this.quirks.noImages }
|
|
496
524
|
if (can && req.messages) req.messages = fitFor(req.messages, can, this.model)
|
|
497
525
|
if (can?.actions === 'guided') delete req.tools
|
|
@@ -521,6 +549,10 @@ export class Client {
|
|
|
521
549
|
timer.unref?.()
|
|
522
550
|
}
|
|
523
551
|
const stop = idle ? (signal ? AbortSignal.any([signal, idle.signal]) : idle.signal) : signal
|
|
552
|
+
// not started answering in startMs: given up on like a failure (the next model of the list takes it)
|
|
553
|
+
let startTimer = idle && setTimeout(() => idle.abort(Object.assign(new Error(`${this.model} didn't start answering within ${Math.round(this.startMs / 1000)}s`), { name: 'TimeoutError', notStarted: true })), this.startMs)
|
|
554
|
+
startTimer?.unref?.()
|
|
555
|
+
const started = () => startTimer && (clearTimeout(startTimer), (startTimer = null))
|
|
524
556
|
try {
|
|
525
557
|
for (let attempt = 0; ; attempt++) {
|
|
526
558
|
sent = Date.now()
|
|
@@ -539,7 +571,7 @@ export class Client {
|
|
|
539
571
|
}
|
|
540
572
|
}
|
|
541
573
|
} catch (e) {
|
|
542
|
-
clearTimeout(timer)
|
|
574
|
+
clearTimeout(timer), started()
|
|
543
575
|
// A provider that refuses one part of the request (400, or 422 from the ones that check
|
|
544
576
|
// requests against a schema): the same request without that part. Learned (onLearn: kept in
|
|
545
577
|
// the model's profile) only when that works; else it's put back and the refusal stands. The
|
|
@@ -566,6 +598,7 @@ export class Client {
|
|
|
566
598
|
if (/reasoning_effort/.test(said) && 'reasoning_effort' in req && !this.quirks.noEffort) return without('noEffort')
|
|
567
599
|
if (/stream_options/.test(said) && req.stream_options && !this.quirks.noStreamUsage) return without('noStreamUsage')
|
|
568
600
|
if (/parallel_tool_calls/.test(said) && req.parallel_tool_calls && !this.quirks.noParallel) return without('noParallel')
|
|
601
|
+
if (/stream/i.test(said) && req.stream && body.stream === undefined && !this.quirks.noStream) return without('noStream') // streamed by HeartCode's choice: not again
|
|
569
602
|
if (reasoningSent && /reasoning(?!_effort)/i.test(said)) return without('noReasoningBack')
|
|
570
603
|
if (imagesSent && /image|vision|multimodal|modalit|content.{0,20}(type|part)/i.test(said)) return without('noImages')
|
|
571
604
|
if (req.tools?.length && !this.quirks.simpleSchemas && /schema|function_declarations|parameters|additionalProperties|exclusiveM|minItems|unknown name|invalid.{0,40}(tool|function)|tools\[/i.test(said)) return without('simpleSchemas')
|
|
@@ -590,7 +623,7 @@ export class Client {
|
|
|
590
623
|
this.#record(req, sent, { reply: r, firstAt })
|
|
591
624
|
return r
|
|
592
625
|
}
|
|
593
|
-
if (!
|
|
626
|
+
if (!req.stream) {
|
|
594
627
|
const data = await res.json()
|
|
595
628
|
const choice = data.choices?.[0] ?? {}
|
|
596
629
|
const msg = choice.message ?? {}
|
|
@@ -631,7 +664,7 @@ export class Client {
|
|
|
631
664
|
try {
|
|
632
665
|
;({ value, done: end } = await reader.read())
|
|
633
666
|
} catch (e) {
|
|
634
|
-
clearTimeout(timer)
|
|
667
|
+
clearTimeout(timer), started()
|
|
635
668
|
throw e
|
|
636
669
|
}
|
|
637
670
|
poke()
|
|
@@ -655,7 +688,7 @@ export class Client {
|
|
|
655
688
|
if (chunk.error) {
|
|
656
689
|
// an error sent in the stream: its status from its code, else a "too large" one as 400
|
|
657
690
|
// (sent smaller, not again as it is), else a server error (tried again, a few times)
|
|
658
|
-
clearTimeout(timer)
|
|
691
|
+
clearTimeout(timer), started()
|
|
659
692
|
const said = chunk.error.message ?? JSON.stringify(chunk.error)
|
|
660
693
|
const code = Number(chunk.error.code ?? chunk.error.status)
|
|
661
694
|
const err = Object.assign(new Error(`server error: ${said}`), { body: payload })
|
|
@@ -666,6 +699,7 @@ export class Client {
|
|
|
666
699
|
if (chunk.usage) usage = chunk.usage
|
|
667
700
|
const ch = chunk.choices?.[0]
|
|
668
701
|
if (!ch) continue
|
|
702
|
+
started() // it answers (a keep-alive or an empty frame doesn't get here)
|
|
669
703
|
if (ch.finish_reason) finishReason = ch.finish_reason
|
|
670
704
|
const d = ch.delta ?? ch.message ?? {} // some proxies send the whole message in a chunk
|
|
671
705
|
this.#reasoningField(d)
|
|
@@ -682,6 +716,7 @@ export class Client {
|
|
|
682
716
|
if (tc.id) call.id = tc.id
|
|
683
717
|
if (tc.function?.name) call.function.name ||= tc.function.name
|
|
684
718
|
if (tc.function?.arguments) call.function.arguments += tc.function.arguments
|
|
719
|
+
if (tc.extra_content) call.extra_content = { ...call.extra_content, ...tc.extra_content } // Gemini's thought_signature: refused next time without it
|
|
685
720
|
onToolDelta?.(call.function.name, call.function.arguments)
|
|
686
721
|
watch(`call ${i}`, call.function.arguments)
|
|
687
722
|
}
|
|
@@ -702,7 +737,7 @@ export class Client {
|
|
|
702
737
|
break
|
|
703
738
|
}
|
|
704
739
|
}
|
|
705
|
-
clearTimeout(timer)
|
|
740
|
+
clearTimeout(timer), started()
|
|
706
741
|
if (looped) {
|
|
707
742
|
log('reply', `${this.model}: went into a loop in its ${looped.what} (cut after ${looped.at} characters): "${looped.sample}"`)
|
|
708
743
|
if (looped.what === 'reasoning') reasoning = reasoning.slice(0, looped.at)
|
package/src/config.js
CHANGED
|
@@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url'
|
|
|
6
6
|
export const HOME = process.env.HEART_HOME || path.join(os.homedir(), '.heart')
|
|
7
7
|
export const CONFIG_FILE = path.join(HOME, 'config.json')
|
|
8
8
|
|
|
9
|
-
const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search', 'testTimeout']
|
|
9
|
+
const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search', 'testTimeout', 'updateCheck', 'modelChoice', 'logs', 'replyStart', 'mouse']
|
|
10
10
|
const LOCAL_NAMES = { 11434: 'ollama', 1234: 'lmstudio', 8080: 'llamacpp' }
|
|
11
11
|
|
|
12
12
|
export function readJson(file, fallback) {
|
package/src/fit.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// "Best fit" (modelChoice: 'fit'): for each new message, your models ranked by how good each is at
|
|
2
|
+
// what this message needs — by public rankings (rankings.js), not by a model's opinion of models.
|
|
3
|
+
// One short request names the skills the task needs (web pages, code, images…); the rest is
|
|
4
|
+
// arithmetic: who leads the work (and who next when one fails) and who reviews it (not the lead).
|
|
5
|
+
// A model the rankings don't know comes after those they do, in your order. A message that only says to go on keeps the last pick.
|
|
6
|
+
// "Your order" (the default): none of this — your list as you set it.
|
|
7
|
+
import { prompt } from './prompts.js'
|
|
8
|
+
import { log } from './log.js'
|
|
9
|
+
import { rankings, score, SKILLS } from './rankings.js'
|
|
10
|
+
|
|
11
|
+
const name = (t) => `${t.provider} ${t.model}`
|
|
12
|
+
const GO_ON = /^\s*(continue|go on|carry on|keep going|resume|proceed|ok(ay)?|yes|do it|go ahead)\W*$/i
|
|
13
|
+
|
|
14
|
+
// The skills this task needs, from SKILLS: { work: [...] } — asked of the model in use (naming
|
|
15
|
+
// what a task needs is easy; judging models is what the rankings are for). ['coding'] when it can't say.
|
|
16
|
+
async function skillsFor(s, task, signal) {
|
|
17
|
+
const ask = prompt('agent/pick-skills', { task: task.slice(0, 1500), choices: (s.chat.choices ?? []).join('; '), skills: Object.entries(SKILLS).map(([k, [, , what]]) => `${k}: ${what}`).join('\n') })
|
|
18
|
+
const was = s.client.purpose
|
|
19
|
+
s.client.purpose = 'pick-skills'
|
|
20
|
+
try {
|
|
21
|
+
const said = (await s.client.chat({ messages: [{ role: 'user', content: ask }] }, { signal: AbortSignal.any([AbortSignal.timeout(30_000), ...(signal ? [signal] : [])]) })).content
|
|
22
|
+
const line = /^\W*skills?\W*:\s*(.+)$/im.exec(said)?.[1] ?? said
|
|
23
|
+
const named = Object.keys(SKILLS).filter((k) => new RegExp(`(^|[^\\w-])${k}($|[^\\w-])`, 'i').test(line))
|
|
24
|
+
return named.length ? named : ['coding']
|
|
25
|
+
} catch (e) {
|
|
26
|
+
if (signal?.aborted) throw e
|
|
27
|
+
log('fit', `no skills named (${e.message}): coding`)
|
|
28
|
+
return ['coding']
|
|
29
|
+
} finally {
|
|
30
|
+
s.client.purpose = was
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// { work, review, why } (names, best first), kept in chat.fit; null when there's nothing to choose.
|
|
35
|
+
export async function pickModels(s, task, signal, { images = 0, size = 0 } = {}) {
|
|
36
|
+
const all = s.allModels?.() ?? []
|
|
37
|
+
const can = all.filter((t) => t.tools && (!images || t.images) && (!size || !t.context || t.context > size * 1.2))
|
|
38
|
+
if (can.length < 2) return null
|
|
39
|
+
if (GO_ON.test(task) && s.chat.fit) return s.chat.fit // the same work: the same models (and the provider's cache still holds)
|
|
40
|
+
const data = await rankings({ signal, onWait: () => s.ui.spinner('getting the model rankings (once a week)') })
|
|
41
|
+
s.ui.stopSpin()
|
|
42
|
+
if (!data) return null
|
|
43
|
+
s.ui.spinner('what does this task need')
|
|
44
|
+
const skills = await skillsFor(s, task, signal)
|
|
45
|
+
s.ui.stopSpin()
|
|
46
|
+
if (images && !skills.includes('vision')) skills.push('vision')
|
|
47
|
+
// best first by score; not ranked: after, in your order
|
|
48
|
+
const ranked = (models, wanted) =>
|
|
49
|
+
models
|
|
50
|
+
.map((t, i) => ({ t, i, sc: score(t.model, wanted, data) }))
|
|
51
|
+
.sort((a, b) => (a.sc ?? 2) - (b.sc ?? 2) || a.i - b.i)
|
|
52
|
+
const order = ranked(can, skills)
|
|
53
|
+
const lead = name(order[0].t)
|
|
54
|
+
const fit = {
|
|
55
|
+
work: order.map((x) => name(x.t)),
|
|
56
|
+
review: ranked(can, ['coding', 'hard']).filter((x) => x.sc != null).map((x) => name(x.t)).filter((n) => n !== lead).slice(0, 2),
|
|
57
|
+
why: skills.join(', '),
|
|
58
|
+
}
|
|
59
|
+
log('fit', { skills, scores: order.slice(0, 8).map((x) => `${x.t.model} ${x.sc == null ? 'not ranked' : x.sc.toFixed(2)}`), review: fit.review })
|
|
60
|
+
s.chat.fit = fit
|
|
61
|
+
return fit
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Others (reviewers, page checkers) in the pick's order, the rest after in your list's order.
|
|
65
|
+
export const byPick = (models, names = []) => [...models].sort((a, b) => ((names.indexOf(name(a)) + 1 || 1e9) - (names.indexOf(name(b)) + 1 || 1e9)))
|
package/src/log.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
// Logs,
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
1
|
+
// Logs, each kind switched on by itself (the settings page: Logs; config.json "logs"), all off unless
|
|
2
|
+
// you switch one on:
|
|
3
|
+
// - Text logs, one file per kind in the run's folder <logs>/runs/<when it started>/ (tools.log,
|
|
4
|
+
// models.log, agent.log, errors.log, conversation.log, debug.log), each line with its tab.
|
|
5
|
+
// HEART_LOG=/path/file.log: everything in that one file, whatever is switched on (for debugging).
|
|
5
6
|
// - Requests: each request to a model, and its reply or error, a JSON file of its own in
|
|
6
7
|
// <logs>/requests/<when the run started>/, and a line for it in that folder's index.jsonl.
|
|
7
8
|
// Written synchronously so the last lines survive a crash.
|
|
@@ -12,16 +13,31 @@ import { inspect } from 'node:util'
|
|
|
12
13
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
13
14
|
|
|
14
15
|
export const LOG_FILE = process.env.HEART_LOG && process.env.HEART_LOG !== 'off' ? path.resolve(process.env.HEART_LOG) : null
|
|
15
|
-
export const LOG_DIR = !LOG_FILE && process.env.HEART_LOG !== 'off' && process.env.HEART_LOG_DIR ? path.resolve(process.env.HEART_LOG_DIR) : null
|
|
16
|
-
// The run's log on or off. HEART_LOG_RUN=on|off (bin/heart.js): its folder is set aside, and config.json's
|
|
17
|
-
// "log" switches it, also while HeartCode runs (useRequestLog); else it's on when a file or folder is given.
|
|
18
|
-
const AUTO = Boolean(LOG_DIR) && ['on', 'off'].includes(process.env.HEART_LOG_RUN)
|
|
19
|
-
export const runLog = { on: Boolean(LOG_FILE || (LOG_DIR && (!AUTO || process.env.HEART_LOG_RUN === 'on'))) }
|
|
20
16
|
// Where the logs go: bin/heart.js says (the system's temp folder with --temp)
|
|
21
17
|
export const LOGS = path.resolve(process.env.HEART_LOGS || path.join(process.env.HEART_HOME || path.join(os.homedir(), '.heart'), 'logs'))
|
|
22
18
|
export const REQUESTS = path.join(LOGS, 'requests')
|
|
23
19
|
export const DAYS = 3 // how long logs are kept, unless config.json's logDays says otherwise
|
|
24
20
|
const STAMP = process.env.HEART_LOG_STAMP || stamp()
|
|
21
|
+
// this run's folder of text logs (made with its first line)
|
|
22
|
+
export const LOG_DIR = process.env.HEART_LOG === 'off' ? null : path.resolve(process.env.HEART_LOG_DIR || path.join(LOGS, 'runs', STAMP))
|
|
23
|
+
|
|
24
|
+
// The kinds of text log, what each is for, and which topics (log('topic', …)) go in it. A topic not
|
|
25
|
+
// listed goes in debug.
|
|
26
|
+
export const LOG_KINDS = {
|
|
27
|
+
tools: { label: 'Tools & commands', about: 'what HeartCode did on your machine: each tool call and its result, commands and background commands, MCP calls, files written', topics: ['tool', 'command', 'mcp', 'background', 'lsp', 'format', 'write', 'web', 'research', 'worktree'] },
|
|
28
|
+
models: { label: 'Model choices', about: 'why a model answered or didn\'t: fallbacks, retries, best-fit picks, strengths learned, probes and quirks found', topics: ['rotate', 'retry', 'fit', 'strengths', 'probe', 'quirk'] },
|
|
29
|
+
agent: { label: "Agent's decisions", about: 'why it did what it did: each task and its answer, plan-first, reviews, page checks, helpers and parts, compacting, lessons, the wrap-up', topics: ['task', 'look', 'review', 'compact', 'wrapup', 'learn', 'agent', 'director', 'guided', 'rewind', 'btw', 'parts'] },
|
|
30
|
+
errors: { label: 'Errors', about: 'what went wrong: errors, crashes and warnings, with where they came from', topics: ['error', 'crash', 'warn', 'exit'] },
|
|
31
|
+
conversation: { label: 'Conversation', about: 'a plain transcript: what you typed, its answers, its questions and your answers', topics: ['input', 'ask', 'answer'] },
|
|
32
|
+
debug: { label: 'Debug', about: 'everything else, for a bug report: HTTP, settings, voice, Telegram, sign-ins, tabs, headless and ACP', topics: [] },
|
|
33
|
+
}
|
|
34
|
+
const KIND_OF = Object.fromEntries(Object.entries(LOG_KINDS).flatMap(([k, v]) => v.topics.map((t) => [t, k])))
|
|
35
|
+
export const kindOf = (topic) => KIND_OF[topic] ?? 'debug'
|
|
36
|
+
// which kinds are on (useRequestLog sets it from config.json)
|
|
37
|
+
export const logKinds = Object.fromEntries(Object.keys(LOG_KINDS).map((k) => [k, false]))
|
|
38
|
+
// config.json → what's on: "logs": { tools: true, … }; older ones: "log": true (every text kind),
|
|
39
|
+
// "logRequests": true (requests)
|
|
40
|
+
export const kindsOn = (cfg) => ({ ...Object.fromEntries(Object.keys(LOG_KINDS).map((k) => [k, cfg.logs?.[k] ?? cfg.log === true])), requests: cfg.logs?.requests ?? cfg.logRequests === true })
|
|
25
41
|
|
|
26
42
|
export function stamp(d = new Date()) {
|
|
27
43
|
return `${d.getDate()}-${d.getMonth() + 1}-${d.getFullYear()}-${d.getHours()}-${d.getMinutes()}-${d.getSeconds()}`.replace(/\b(\d)\b/g, '0$1')
|
|
@@ -84,9 +100,9 @@ export const logContext = new AsyncLocalStorage()
|
|
|
84
100
|
const tabOf = () => logContext.getStore()?.tab ?? null
|
|
85
101
|
|
|
86
102
|
const fds = new Map()
|
|
87
|
-
function fdFor() {
|
|
88
|
-
if (!
|
|
89
|
-
const file = LOG_FILE ?? (LOG_DIR && path.join(LOG_DIR,
|
|
103
|
+
function fdFor(kind) {
|
|
104
|
+
if (!LOG_FILE && !logKinds[kind]) return null
|
|
105
|
+
const file = LOG_FILE ?? (LOG_DIR && path.join(LOG_DIR, `${kind}.log`))
|
|
90
106
|
if (!file) return null
|
|
91
107
|
if (!fds.has(file)) {
|
|
92
108
|
try {
|
|
@@ -101,21 +117,23 @@ function fdFor() {
|
|
|
101
117
|
|
|
102
118
|
const show = (x) => (typeof x === 'string' ? x : inspect(x, { depth: 8, breakLength: 140, maxArrayLength: 200, maxStringLength: 50_000 }))
|
|
103
119
|
|
|
104
|
-
// log('http', 'POST', url, body) → "2026-10-25T08:00:00.000Z [http] POST https://… {…}"
|
|
120
|
+
// log('http', 'POST', url, body) → "2026-10-25T08:00:00.000Z tab 2 [http] POST https://… {…}" in the
|
|
121
|
+
// kind's file (debug.log here), when that kind is on
|
|
105
122
|
export function log(topic, ...parts) {
|
|
106
|
-
const fd = fdFor()
|
|
107
|
-
if (fd
|
|
123
|
+
const fd = fdFor(kindOf(topic))
|
|
124
|
+
if (!fd) return
|
|
108
125
|
try {
|
|
109
126
|
const text = parts.map(show).join(' ').replace(/\x1b\[[0-9;]*m/g, '')
|
|
110
|
-
fs.writeSync(fd, `${new Date().toISOString()} [${topic}] ${text}\n`)
|
|
127
|
+
fs.writeSync(fd, `${new Date().toISOString()}${tabOf() ? ` tab ${tabOf()}` : ''} [${topic}] ${text}\n`)
|
|
111
128
|
} catch {}
|
|
112
129
|
}
|
|
113
130
|
|
|
114
131
|
// The requests log: on, and how much of each (from config.json: logRequests, logDetail).
|
|
115
132
|
export const requestLog = { on: false, detail: 'full', dir: null }
|
|
116
133
|
export function useRequestLog(cfg) {
|
|
117
|
-
|
|
118
|
-
|
|
134
|
+
const on = kindsOn(cfg)
|
|
135
|
+
for (const k of Object.keys(logKinds)) logKinds[k] = on[k]
|
|
136
|
+
return Object.assign(requestLog, { on: on.requests, detail: cfg.logDetail === 'summary' ? 'summary' : 'full' })
|
|
119
137
|
}
|
|
120
138
|
// At the start: the request log as set, and logs past their days gone.
|
|
121
139
|
export function useLogs(cfg) {
|
|
@@ -171,3 +189,36 @@ export function readRequest(run, file) {
|
|
|
171
189
|
if (![run, file].every((x) => /^[\w.-]+$/.test(String(x ?? '')) && !/^\.+$/.test(x)) || !file.endsWith('.json')) throw new Error('no such request')
|
|
172
190
|
return JSON.parse(fs.readFileSync(path.join(REQUESTS, run, file), 'utf8'))
|
|
173
191
|
}
|
|
192
|
+
|
|
193
|
+
// The runs that have text logs, newest first: { run, at, kinds: { tools: bytes, … }, current }.
|
|
194
|
+
export function listLogRuns() {
|
|
195
|
+
const dir = path.join(LOGS, 'runs')
|
|
196
|
+
const out = []
|
|
197
|
+
try {
|
|
198
|
+
for (const run of fs.readdirSync(dir)) {
|
|
199
|
+
const at = path.join(dir, run)
|
|
200
|
+
if (!fs.statSync(at).isDirectory()) continue
|
|
201
|
+
const kinds = {}
|
|
202
|
+
for (const f of fs.readdirSync(at)) if (f.endsWith('.log')) kinds[f.slice(0, -4)] = fs.statSync(path.join(at, f)).size
|
|
203
|
+
const when = lastWritten(at)
|
|
204
|
+
if (Object.keys(kinds).length) out.push({ run, at: when, kinds, current: at === LOG_DIR, live: at === LOG_DIR || Date.now() - when < 60_000 }) // live: still being written (this or another HeartCode)
|
|
205
|
+
}
|
|
206
|
+
} catch {}
|
|
207
|
+
return out.sort((a, b) => b.at - a.at)
|
|
208
|
+
}
|
|
209
|
+
// A run's log of one kind: its last `most` bytes (a long one: from a whole line on), and its size.
|
|
210
|
+
export function readLog(run, kind, most = 1_000_000) {
|
|
211
|
+
if (!/^[\w.-]+$/.test(String(run ?? '')) || /^\.+$/.test(run) || !/^[\w-]+$/.test(String(kind ?? ''))) throw new Error('no such log')
|
|
212
|
+
const file = path.join(LOGS, 'runs', run, `${kind}.log`)
|
|
213
|
+
const size = fs.statSync(file).size
|
|
214
|
+
const fd = fs.openSync(file, 'r')
|
|
215
|
+
try {
|
|
216
|
+
const len = Math.min(size, most)
|
|
217
|
+
const buf = Buffer.alloc(len)
|
|
218
|
+
fs.readSync(fd, buf, 0, len, size - len)
|
|
219
|
+
const text = buf.toString('utf8')
|
|
220
|
+
return { size, cut: size > len, text: size > len ? text.slice(text.indexOf('\n') + 1) : text }
|
|
221
|
+
} finally {
|
|
222
|
+
fs.closeSync(fd)
|
|
223
|
+
}
|
|
224
|
+
}
|
package/src/parquet.js
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// Just enough Parquet to read a flat table (the public model rankings come only as Parquet): the
|
|
2
|
+
// footer's Thrift metadata, Snappy or uncompressed pages (v1 and v2), PLAIN and dictionary
|
|
3
|
+
// encodings; booleans, int32/64, double and strings. readParquet(buffer, ['a', 'b']) → [{ a, b }, …]
|
|
4
|
+
// ponytail: no nested columns, no other codecs (zstd, gzip) or encodings (delta): an error says so.
|
|
5
|
+
|
|
6
|
+
// Thrift compact protocol: a struct as { fieldId: value }
|
|
7
|
+
function thrift(buf, pos) {
|
|
8
|
+
const varint = () => {
|
|
9
|
+
let n = 0n
|
|
10
|
+
let shift = 0n
|
|
11
|
+
for (;;) {
|
|
12
|
+
const b = buf[pos++]
|
|
13
|
+
n |= BigInt(b & 0x7f) << shift
|
|
14
|
+
if (!(b & 0x80)) return n
|
|
15
|
+
shift += 7n
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const zigzag = () => {
|
|
19
|
+
const n = varint()
|
|
20
|
+
return Number((n >> 1n) ^ -(n & 1n))
|
|
21
|
+
}
|
|
22
|
+
const value = (type) => {
|
|
23
|
+
switch (type) {
|
|
24
|
+
case 1:
|
|
25
|
+
return true
|
|
26
|
+
case 2:
|
|
27
|
+
return false
|
|
28
|
+
case 3:
|
|
29
|
+
return buf.readInt8(pos++)
|
|
30
|
+
case 4:
|
|
31
|
+
case 5:
|
|
32
|
+
case 6:
|
|
33
|
+
return zigzag()
|
|
34
|
+
case 7:
|
|
35
|
+
return (pos += 8), buf.readDoubleLE(pos - 8)
|
|
36
|
+
case 8: {
|
|
37
|
+
const len = Number(varint())
|
|
38
|
+
return (pos += len), buf.subarray(pos - len, pos)
|
|
39
|
+
}
|
|
40
|
+
case 9:
|
|
41
|
+
case 10: {
|
|
42
|
+
const head = buf[pos++]
|
|
43
|
+
const size = head >> 4 === 15 ? Number(varint()) : head >> 4
|
|
44
|
+
const t = head & 15
|
|
45
|
+
return Array.from({ length: size }, () => (t === 1 || t === 2 ? buf[pos++] === 1 : value(t)))
|
|
46
|
+
}
|
|
47
|
+
case 12:
|
|
48
|
+
return struct()
|
|
49
|
+
default:
|
|
50
|
+
throw new Error(`parquet: thrift type ${type} not read`)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const struct = () => {
|
|
54
|
+
const out = {}
|
|
55
|
+
let id = 0
|
|
56
|
+
for (;;) {
|
|
57
|
+
const head = buf[pos++]
|
|
58
|
+
if (!head) return out
|
|
59
|
+
id = head >> 4 ? id + (head >> 4) : zigzag()
|
|
60
|
+
out[id] = value(head & 15)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const s = struct()
|
|
64
|
+
return { value: s, end: pos }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function snappy(src) {
|
|
68
|
+
let pos = 0
|
|
69
|
+
let len = 0
|
|
70
|
+
for (let shift = 0; ; shift += 7) {
|
|
71
|
+
const b = src[pos++]
|
|
72
|
+
len |= (b & 0x7f) << shift
|
|
73
|
+
if (!(b & 0x80)) break
|
|
74
|
+
}
|
|
75
|
+
const out = Buffer.alloc(len)
|
|
76
|
+
let o = 0
|
|
77
|
+
while (pos < src.length) {
|
|
78
|
+
const tag = src[pos++]
|
|
79
|
+
if ((tag & 3) === 0) {
|
|
80
|
+
let n = (tag >> 2) + 1
|
|
81
|
+
if (n > 60) {
|
|
82
|
+
const bytes = n - 60
|
|
83
|
+
n = src.readUIntLE(pos, bytes) + 1
|
|
84
|
+
pos += bytes
|
|
85
|
+
}
|
|
86
|
+
src.copy(out, o, pos, pos + n)
|
|
87
|
+
pos += n
|
|
88
|
+
o += n
|
|
89
|
+
continue
|
|
90
|
+
}
|
|
91
|
+
let n, off
|
|
92
|
+
if ((tag & 3) === 1) (n = ((tag >> 2) & 7) + 4), (off = ((tag >> 5) << 8) | src[pos++])
|
|
93
|
+
else if ((tag & 3) === 2) (n = (tag >> 2) + 1), (off = src.readUInt16LE(pos)), (pos += 2)
|
|
94
|
+
else (n = (tag >> 2) + 1), (off = src.readUInt32LE(pos)), (pos += 4)
|
|
95
|
+
for (let i = 0; i < n; i++, o++) out[o] = out[o - off] // overlapping copies repeat
|
|
96
|
+
}
|
|
97
|
+
return out
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// RLE / bit-packed hybrid: `count` values of `width` bits
|
|
101
|
+
function hybrid(buf, pos, end, width, count) {
|
|
102
|
+
const out = []
|
|
103
|
+
const bytes = Math.ceil(width / 8)
|
|
104
|
+
while (out.length < count && pos < end) {
|
|
105
|
+
let head = 0
|
|
106
|
+
for (let shift = 0; ; shift += 7) {
|
|
107
|
+
const b = buf[pos++]
|
|
108
|
+
head += (b & 0x7f) * 2 ** shift
|
|
109
|
+
if (!(b & 0x80)) break
|
|
110
|
+
}
|
|
111
|
+
if (head & 1) {
|
|
112
|
+
const n = Math.floor(head / 2) * 8
|
|
113
|
+
let bit = 0
|
|
114
|
+
for (let i = 0; i < n; i++) {
|
|
115
|
+
let v = 0
|
|
116
|
+
for (let k = 0; k < width; k++, bit++) v |= ((buf[pos + (bit >> 3)] >> (bit & 7)) & 1) << k
|
|
117
|
+
out.push(v)
|
|
118
|
+
}
|
|
119
|
+
pos += Math.floor(head / 2) * width
|
|
120
|
+
} else {
|
|
121
|
+
const v = bytes ? buf.readUIntLE(pos, bytes) : 0
|
|
122
|
+
pos += bytes
|
|
123
|
+
for (let i = Math.floor(head / 2); i > 0; i--) out.push(v)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return out.slice(0, count)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function plain(buf, type, count) {
|
|
130
|
+
const out = []
|
|
131
|
+
let pos = 0
|
|
132
|
+
for (let i = 0; i < count; i++) {
|
|
133
|
+
if (type === 6) {
|
|
134
|
+
const len = buf.readUInt32LE(pos)
|
|
135
|
+
out.push(buf.toString('utf8', pos + 4, pos + 4 + len))
|
|
136
|
+
pos += 4 + len
|
|
137
|
+
} else if (type === 5) out.push(buf.readDoubleLE(pos)), (pos += 8)
|
|
138
|
+
else if (type === 2) out.push(Number(buf.readBigInt64LE(pos))), (pos += 8)
|
|
139
|
+
else if (type === 1) out.push(buf.readInt32LE(pos)), (pos += 4)
|
|
140
|
+
else if (type === 0) out.push(((buf[i >> 3] >> (i & 7)) & 1) === 1) // bit-packed
|
|
141
|
+
else throw new Error(`parquet: column type ${type} not read`)
|
|
142
|
+
}
|
|
143
|
+
return out
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function readColumn(file, meta, optional) {
|
|
147
|
+
const type = meta[1]
|
|
148
|
+
const codec = meta[4]
|
|
149
|
+
if (codec !== 0 && codec !== 1) throw new Error(`parquet: codec ${codec} not read (only none and snappy)`)
|
|
150
|
+
const inflate = (b) => (codec === 1 ? snappy(b) : b)
|
|
151
|
+
let pos = Number(meta[11] ?? meta[9])
|
|
152
|
+
const total = Number(meta[5])
|
|
153
|
+
let dict = null
|
|
154
|
+
const out = []
|
|
155
|
+
while (out.length < total) {
|
|
156
|
+
const { value: page, end } = thrift(file, pos)
|
|
157
|
+
const body = file.subarray(end, end + page[3])
|
|
158
|
+
pos = end + page[3]
|
|
159
|
+
if (page[1] === 2) {
|
|
160
|
+
dict = plain(inflate(body), type, page[7][1])
|
|
161
|
+
continue
|
|
162
|
+
}
|
|
163
|
+
let data, n, defs, encoding
|
|
164
|
+
if (page[1] === 0) {
|
|
165
|
+
;[n, encoding] = [page[5][1], page[5][2]]
|
|
166
|
+
data = inflate(body)
|
|
167
|
+
let at = 0
|
|
168
|
+
if (optional) {
|
|
169
|
+
const len = data.readUInt32LE(0)
|
|
170
|
+
defs = hybrid(data, 4, 4 + len, 1, n)
|
|
171
|
+
at = 4 + len
|
|
172
|
+
}
|
|
173
|
+
data = data.subarray(at)
|
|
174
|
+
} else if (page[1] === 3) {
|
|
175
|
+
const h = page[8]
|
|
176
|
+
;[n, encoding] = [h[1], h[4]]
|
|
177
|
+
const dl = h[5]
|
|
178
|
+
const rl = h[6]
|
|
179
|
+
if (optional && dl) defs = hybrid(body, rl, rl + dl, 1, n)
|
|
180
|
+
data = h[7] === false ? body.subarray(rl + dl) : inflate(body.subarray(rl + dl))
|
|
181
|
+
} else continue // index pages and the like
|
|
182
|
+
const present = defs ? defs.filter((d) => d === 1).length : n
|
|
183
|
+
const values = encoding === 0 ? plain(data, type, present) : encoding === 2 || encoding === 8 ? hybrid(data, 1, data.length, data[0], present).map((i) => dict[i]) : null
|
|
184
|
+
if (!values) throw new Error(`parquet: encoding ${encoding} not read`)
|
|
185
|
+
let k = 0
|
|
186
|
+
for (let i = 0; i < n; i++) out.push(!defs || defs[i] === 1 ? values[k++] : null)
|
|
187
|
+
}
|
|
188
|
+
return out
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function readParquet(file, columns) {
|
|
192
|
+
if (file.toString('latin1', file.length - 4) !== 'PAR1') throw new Error('not a Parquet file')
|
|
193
|
+
const len = file.readUInt32LE(file.length - 8)
|
|
194
|
+
const { value: meta } = thrift(file, file.length - 8 - len)
|
|
195
|
+
const schema = meta[2].slice(1) // the root first, then a flat table's columns
|
|
196
|
+
const rows = []
|
|
197
|
+
for (const group of meta[4]) {
|
|
198
|
+
const cols = {}
|
|
199
|
+
for (const chunk of group[1]) {
|
|
200
|
+
const name = chunk[3][3].map((b) => b.toString()).join('.')
|
|
201
|
+
if (!columns.includes(name)) continue
|
|
202
|
+
const el = schema.find((e) => e[4].toString() === name)
|
|
203
|
+
cols[name] = readColumn(file, chunk[3], el?.[3] === 1)
|
|
204
|
+
}
|
|
205
|
+
const n = Number(group[3])
|
|
206
|
+
for (let i = 0; i < n; i++) rows.push(Object.fromEntries(columns.map((c) => [c, cols[c]?.[i] ?? null])))
|
|
207
|
+
}
|
|
208
|
+
return rows
|
|
209
|
+
}
|