heartcode 0.1.63 → 0.1.95

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/alert.js ADDED
@@ -0,0 +1,93 @@
1
+ // Notifications on this computer: a sound and/or a desktop notification when a task finishes,
2
+ // fails, or waits for an answer. Off until switched on (settings: Notifications;
3
+ // cfg.alerts: { sound, popup, events: { done, failed, waiting } }). The interactive CLI only: a
4
+ // caller of -p has its own. HeartCode's own sound, a heartbeat made here (no sound files shipped):
5
+ // "lub-dub" rising when done, falling when it failed, twice when it waits for you.
6
+ import fs from 'node:fs'
7
+ import path from 'node:path'
8
+ import { HOME } from './config.js'
9
+ import { log } from './log.js'
10
+ import { onPath, spawnCmd } from './spawn.js'
11
+
12
+ const WIN = process.platform === 'win32'
13
+ const MAC = process.platform === 'darwin'
14
+
15
+ // beats: [Hz, ms, pause after in ms]
16
+ const BEATS = {
17
+ done: [[220, 120, 90], [262, 160, 0]],
18
+ failed: [[196, 140, 100], [147, 220, 0]],
19
+ waiting: [[220, 100, 70], [262, 130, 260], [220, 100, 70], [262, 130, 0]],
20
+ }
21
+
22
+ // A beat: a low thump (a quick attack, a slight fall in pitch, a fast fade) with two overtones, so
23
+ // laptop speakers play it too. 16-bit mono WAV.
24
+ export function heartbeat(beats, rate = 22050) {
25
+ const parts = []
26
+ for (const [f, ms, pause] of beats) {
27
+ const n = Math.round((rate * ms) / 1000)
28
+ let phase = 0
29
+ for (let i = 0; i < n; i++) {
30
+ const t = i / n
31
+ phase += (2 * Math.PI * f * (1 - 0.15 * t)) / rate
32
+ const env = Math.min(1, i / (rate * 0.005)) * Math.exp(-5 * t)
33
+ parts.push(env * 0.55 * (Math.sin(phase) + 0.5 * Math.sin(2 * phase) + 0.25 * Math.sin(3 * phase)) / 1.75)
34
+ }
35
+ for (let i = 0; i < Math.round((rate * pause) / 1000); i++) parts.push(0)
36
+ }
37
+ const b = Buffer.alloc(44 + parts.length * 2)
38
+ b.write('RIFF', 0), b.writeUInt32LE(36 + parts.length * 2, 4), b.write('WAVEfmt ', 8)
39
+ b.writeUInt32LE(16, 16), b.writeUInt16LE(1, 20), b.writeUInt16LE(1, 22), b.writeUInt32LE(rate, 24)
40
+ b.writeUInt32LE(rate * 2, 28), b.writeUInt16LE(2, 32), b.writeUInt16LE(16, 34)
41
+ b.write('data', 36), b.writeUInt32LE(parts.length * 2, 40)
42
+ parts.forEach((v, i) => b.writeInt16LE(Math.round(v * 32767), 44 + i * 2))
43
+ return b
44
+ }
45
+
46
+ function soundFile(event) {
47
+ const file = path.join(HOME, 'sounds', `heartbeat-${event}-1.wav`) // -1: made again if the sound changes
48
+ if (!fs.existsSync(file)) {
49
+ fs.mkdirSync(path.dirname(file), { recursive: true })
50
+ fs.writeFileSync(file, heartbeat(BEATS[event] ?? BEATS.done))
51
+ }
52
+ return file
53
+ }
54
+
55
+ // started and left: never waited on
56
+ const start = (cmd, args, env) => {
57
+ const p = spawnCmd(cmd, args, { stdio: 'ignore', detached: !WIN, windowsHide: true, env: { ...process.env, ...env } })
58
+ p.on('error', (e) => log('alert', `${cmd}: ${e.message}`))
59
+ p.unref()
60
+ }
61
+
62
+ export function playSound(event) {
63
+ const file = soundFile(event)
64
+ if (MAC) return start('afplay', [file])
65
+ if (WIN) return start('powershell', ['-NoProfile', '-Command', '(New-Object Media.SoundPlayer $env:HC_SOUND).PlaySync()'], { HC_SOUND: file })
66
+ const player = ['paplay', 'pw-play', 'aplay'].find((p) => onPath(p))
67
+ if (player) start(player, player === 'aplay' ? ['-q', file] : [file])
68
+ else log('alert', 'no sound player found (paplay, pw-play or aplay)')
69
+ }
70
+
71
+ // title and text go as arguments or the environment, never into a script's source
72
+ export function showPopup(title, text) {
73
+ text = String(text).slice(0, 240)
74
+ if (MAC) return start('osascript', ['-e', 'on run argv', '-e', 'display notification (item 2 of argv) with title (item 1 of argv)', '-e', 'end run', title, text])
75
+ if (WIN) return start('powershell', ['-NoProfile', '-Command', "Add-Type -AssemblyName System.Windows.Forms; $n = New-Object System.Windows.Forms.NotifyIcon; $n.Icon = [System.Drawing.SystemIcons]::Information; $n.Visible = $true; $n.ShowBalloonTip(6000, $env:HC_TITLE, $env:HC_TEXT, 'None'); Start-Sleep 7; $n.Dispose()"], { HC_TITLE: title, HC_TEXT: text })
76
+ if (onPath('notify-send')) start('notify-send', ['-a', 'HeartCode', title, text])
77
+ else log('alert', 'no notify-send: no desktop notification')
78
+ }
79
+
80
+ export const ALERT_EVENTS = ['done', 'failed', 'waiting']
81
+ const TITLES = { done: 'HeartCode: done', failed: 'HeartCode: failed', waiting: 'HeartCode is waiting for you' }
82
+
83
+ // An event, if switched on: never waits, never throws
84
+ export function alert(cfg, event, text) {
85
+ const a = cfg?.alerts
86
+ if (!a || (!a.sound && !a.popup) || a.events?.[event] === false) return
87
+ try {
88
+ if (a.sound) playSound(event)
89
+ if (a.popup) showPopup(TITLES[event] ?? 'HeartCode', String(text).replace(/^\S+ /, '').split('\n').filter((l) => l.trim()).slice(0, 2).join(' — '))
90
+ } catch (e) {
91
+ log('alert', `${event}: ${e.message}`)
92
+ }
93
+ }
package/src/background.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // background tool (and /background) reads what it printed since, waits on it, lists them, stops
4
4
  // one. Each runs in its own process group, its output going to a file; all of them are stopped when
5
5
  // HeartCode exits.
6
+ import { guarded } from './guard.js'
6
7
  import fs from 'node:fs'
7
8
  import path from 'node:path'
8
9
  import { spawn } from 'node:child_process'
@@ -14,7 +15,7 @@ const DIR = path.join(HOME, 'outputs', 'background')
14
15
  const jobs = new Map() // id → { id, command, root, pid, file, started, code, read, exited }
15
16
  let made = 0
16
17
 
17
- const plain = (t) => t.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').replace(/\r(?!\n)/g, '\n')
18
+ const plain = (t) => t.replace(/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g, '').replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').replace(/\r(?!\n)/g, '\n').replace(/\x1b|[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\x9b]/g, '')
18
19
  const group = process.platform !== 'win32'
19
20
  const kill = (job, sig) => killTree(job.pid, sig, group)
20
21
 
@@ -24,7 +25,8 @@ export function startJob(root, command) {
24
25
  const id = ++made
25
26
  const file = path.join(DIR, `${process.pid}-${id}.log`)
26
27
  const fd = fs.openSync(file, 'w')
27
- const child = spawn(command, { cwd: root, shell: true, detached: group, stdio: ['ignore', fd, fd], env: { ...process.env, CI: '1', FORCE_COLOR: '0', NO_COLOR: '1' } })
28
+ const safe = guarded(command, { ...process.env, CI: '1', FORCE_COLOR: '0', NO_COLOR: '1' }) // it can't stop HeartCode (guard.js)
29
+ const child = spawn(safe.command, { cwd: root, shell: true, detached: group, stdio: ['ignore', fd, fd], env: safe.env })
28
30
  fs.closeSync(fd)
29
31
  const job = { id, command, root, pid: child.pid, file, started: Date.now(), code: null, read: 0, exited: false, told: false }
30
32
  jobs.set(id, job)
@@ -29,9 +29,8 @@ export function capabilities(cfg = {}) {
29
29
  const vp = voiceProblem(cfg.voice ?? {}, cfg.providers ?? {})
30
30
  let need = ''
31
31
  if (vp) {
32
- if (/ffmpeg/.test(vp)) need = 'ffmpeg, and a whisper model (or a transcription provider)'
33
- else if (/whisper-cli/.test(vp)) need = 'whisper (whisper-cli) and a model — or a transcription provider'
34
- else need = 'a whisper model — or a transcription provider'
32
+ if (/ffmpeg/.test(vp)) need = 'ffmpeg, and Hex or whisper-cli (or OpenAI)'
33
+ else need = vp.replace(/^voice (input )?/, '') // what it says is missing: Hex's Labs switch, a whisper model, an OpenAI provider
35
34
  }
36
35
  caps.push({ id: 'voice', name: 'Voice input', what: 'Dictate a message — Space in an empty box, or /voice.', ok: !vp, need })
37
36
  const chrome = chromeHere()
package/src/client.js CHANGED
@@ -3,7 +3,9 @@ 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
5
  import { loadRankings, scoreOf } from './rankings.js'
6
+ import { byRecord, unreliable, record } from './record.js'
6
7
  import { fetch } from './http.js' // not the built-in one: see http.js
8
+ import { cliOf, cliModels, cliChat } from './clis.js'
7
9
 
8
10
  // Tokens in a text, estimated the way tokenizers split it: a word or a number is about one, a long
9
11
  // word more, every symbol one. Prose comes out near characters ÷ 4; code, CSS, JSON and SVG paths,
@@ -224,6 +226,10 @@ export class Client {
224
226
  this.rotation = { list, on, retries, next, at: 0, good: list[0] }
225
227
  this.#use(list[0])
226
228
  }
229
+ // the coding CLI this model is one of (a provider at cli://claude…: clis.js), or null
230
+ get cli() {
231
+ return cliOf(this.baseUrl)
232
+ }
227
233
  get target() {
228
234
  return this.rotation?.list[this.rotation.at] ?? null
229
235
  }
@@ -279,7 +285,7 @@ export class Client {
279
285
  if (e?.status >= 400) down.add(r.list[r.at].provider)
280
286
  const n = r.list.length
281
287
  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
288
+ const order = [...Array(n - 1).keys()].map((k) => (r.at + k + 1) % n).map((i) => ({ i, t: r.list[i], score: (r.list[i].score ??= scoreOf(r.list[i].model, data)) })).sort(byRecord).map((x) => x.i) // stable: unranked keep your order; moved by each model's track record (record.js)
283
289
  const after = (ok) => order.find(ok) ?? -1
284
290
  let i = after((i) => !tried.has(i) && !down.has(r.list[i].provider))
285
291
  if (i < 0) i = after((i) => !tried.has(i))
@@ -289,10 +295,19 @@ export class Client {
289
295
  }
290
296
  return i
291
297
  }
292
- // A new message: back to #1 (unless it stays on the one that worked)
298
+ // A new message: back to #1 (unless it stays on the one that worked); #1 failed most of its work
299
+ // (its track record, record.js): the first in your order that hasn't
293
300
  newMessage() {
294
301
  const r = this.rotation
295
- if (r && r.next === 'first' && r.at) this.#use(r.list[(r.at = 0)])
302
+ if (!r || r.next !== 'first') return
303
+ const i = Math.max(0, r.list.findIndex((t) => !unreliable(t)))
304
+ if (r.at !== i) {
305
+ if (i) {
306
+ log('rotate', `${r.list[0].model} failed most of its recent work (its track record): this message starts with ${r.list[i].model}`)
307
+ this.onNotice?.(`↻ ${r.list[i].model} starts this message · ${r.list[0].model} failed most of its recent work here`) // your order skipped: said, not hidden in a log
308
+ }
309
+ this.#use(r.list[(r.at = i)])
310
+ }
296
311
  }
297
312
  // onUse(target): the model the next request goes to changed (its abilities and profile follow)
298
313
  #use(t) {
@@ -383,6 +398,7 @@ export class Client {
383
398
  }
384
399
  // The server's own entries for its models ({ id, owned_by, context_length, pricing… }, as it sends them).
385
400
  async modelEntries(timeout = 60_000) {
401
+ if (this.cli) return (await cliModels(this.cli)).map((m) => ({ ...m, name: m.name ?? m.id })) // a coding CLI (clis.js): its own list
386
402
  const data = await this.#json(this.baseUrl + '/models', undefined, timeout)
387
403
  // { result: [...] } (Cloudflare's shape): there the id is an internal one and the name is the model's
388
404
  if (Array.isArray(data.result)) return data.result.filter((m) => m?.name).map((m) => ({ ...m, id: m.name }))
@@ -395,6 +411,7 @@ export class Client {
395
411
  // server that is one of these is treated as a model server on this machine or network; its
396
412
  // address (localhost, 192.168…) says nothing (a proxy there may serve Gemini).
397
413
  async contextSize() {
414
+ if (this.cli) return { size: undefined, server: null }
398
415
  const root = this.baseUrl.replace(/\/v1$/, '')
399
416
  const host = new URL(root).hostname
400
417
  const n = (x) => (Number(x) > 0 ? Number(x) : undefined)
@@ -443,6 +460,7 @@ export class Client {
443
460
  // 131072"). Refused requests aren't charged. If it's accepted (a window that big), it's stopped
444
461
  // at once. Returns { limit } | { over } (it took that many) | { error }. Not logged: it's 4 MB.
445
462
  async measureContext({ signal, tokens = 2_200_000 } = {}) {
463
+ if (this.cli) return { error: 'a coding CLI keeps its own context' }
446
464
  const headers = { 'content-type': 'application/json', ...(this.apiKey && { authorization: `Bearer ${this.apiKey}` }) }
447
465
  const body = JSON.stringify({ model: this.model, messages: [{ role: 'user', content: 'a '.repeat(tokens) }], stream: true })
448
466
  const stop = new AbortController()
@@ -488,6 +506,7 @@ export class Client {
488
506
  let rounds = 0 // whole rounds of the list that failed
489
507
  const tried = new Set() // places in the model list tried for this request
490
508
  const down = new Set() // providers that answered it with an error (400 or above): their other models are skipped
509
+ const blamed = new Set() // models already given a "no-answer" for this request
491
510
  for (let attempt = 0; ; attempt++) {
492
511
  // The list moved on to a model whose window can't hold this request (a smaller one): not sent
493
512
  // to it as it is; the caller compacts the conversation for that model, then sends it (fit: the
@@ -504,6 +523,10 @@ export class Client {
504
523
  } catch (e) {
505
524
  if (e.name === 'AbortError' || opts.signal?.aborted) throw e
506
525
  this.onFail?.(e, { provider: this.provider, model: this.model }) // what it says is learned (a stated limit)
526
+ // its track record: refused the key, no such model, a bad request… once per request; an outage
527
+ // (no connection, a timeout, a server error, a rate limit) isn't the model's doing
528
+ const who = `${this.provider}/${this.model}`
529
+ if (!outage(e) && !blamed.has(who)) blamed.add(who), record({ provider: this.provider, model: this.model }, 'no-answer')
507
530
  // With a list of models, any failure makes way for the next one (another provider's first).
508
531
  // Without one, only what waiting can fix is tried again.
509
532
  if (!(this.rotation?.list.length > 1) && !outage(e)) throw e
@@ -540,6 +563,7 @@ export class Client {
540
563
  async #timed(body, opts) {
541
564
  this.inFlight = Date.now()
542
565
  try {
566
+ if (this.cli) return await cliChat(this, body, opts) // a coding CLI (clis.js) answers it
543
567
  return await this.#chat(body, opts)
544
568
  } catch (e) {
545
569
  if (!e.recorded && this.last) this.#record(this.last.req, this.last.sent, { error: e }) // failed while the reply streamed in
@@ -740,9 +764,11 @@ export class Client {
740
764
  if (chunk.usage) usage = chunk.usage
741
765
  const ch = chunk.choices?.[0]
742
766
  if (!ch) continue
743
- started() // it answers (a keep-alive or an empty frame doesn't get here)
744
767
  if (ch.finish_reason) finishReason = ch.finish_reason
745
768
  const d = ch.delta ?? ch.message ?? {} // some proxies send the whole message in a chunk
769
+ // it answers: words, thinking, a tool call or the end (a first chunk with only its role, sent
770
+ // before it queues the request, isn't an answer yet; nor a keep-alive)
771
+ if (ch.finish_reason || d.content?.length || d.reasoning_content || d.reasoning || d.thinking || d.tool_calls?.length) started()
746
772
  this.#reasoningField(d)
747
773
  if (Array.isArray(d.content)) d.content = textOf(d.content)
748
774
  const r = d.reasoning_content || d.reasoning || d.thinking