heartcode 0.1.37 → 0.1.41

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/log.js CHANGED
@@ -1,7 +1,8 @@
1
- // Logs, when they're switched on (the settings page: Logging).
2
- // - The run's log: everything HeartCode does, as readable text. HEART_LOG_DIR (bin/heart.js sets
3
- // one folder per run): a file per tab (tab-1.log, tab-2.log…; heartcode.log before any tab).
4
- // HEART_LOG=/path/file.log: all of it in that one file.
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 and quirks found', topics: ['rotate', 'retry', 'fit', '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 (!runLog.on) return null
89
- const file = LOG_FILE ?? (LOG_DIR && path.join(LOG_DIR, tabOf() ? `tab-${tabOf()}.log` : 'heartcode.log'))
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 === null) return
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
- if (AUTO) runLog.on = cfg.log === true
118
- return Object.assign(requestLog, { on: cfg.logRequests === true, detail: cfg.logDetail === 'summary' ? 'summary' : 'full' })
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
+ }