heartcode 0.1.33 → 0.1.36

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/settings.js CHANGED
@@ -127,7 +127,7 @@ const LIST_V = 2 // how a saved list was read (2: airforce's cents, Cloudflare's
127
127
  // The page's own choices (sorts, folded providers, the provider ranking): kept here, not in the
128
128
  // browser, whose storage is per address (a new port each time)
129
129
  const PREFS = path.join(HOME, 'settings-page.json')
130
- const PREF_KEYS = ['catSort', 'freeOnly', 'folded', 'sort', 'rank']
130
+ const PREF_KEYS = ['catSort', 'freeOnly', 'folded', 'sort', 'sorts', 'rank', 'filters']
131
131
  function forgetList(...names) {
132
132
  const all = readJson(LISTS, {})
133
133
  if (!names.some((n) => n in all)) return
@@ -145,7 +145,9 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
145
145
  log('web', `applying ${what}: ${e.stack}`)
146
146
  }
147
147
  }
148
- const save = (what) => (saveConfig(cfg), changed(what))
148
+ // a file this page's server writes itself: its watcher (below) needn't look at it again
149
+ let ownWrite = 0
150
+ const save = (what) => ((ownWrite = Date.now()), saveConfig(cfg), changed(what))
149
151
 
150
152
  // the page listens (GET /api/events): a model's profile as it changes, a request as it's logged
151
153
  const listeners = new Set()
@@ -236,6 +238,9 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
236
238
  for (const key of Object.keys(tests)) if (!mine.has(key)) (delete tests[key]), gone++
237
239
  if (gone) saveTests()
238
240
  }
241
+ // How long a model test waits for its answer (cfg.testTimeout, seconds; the settings page sets it).
242
+ const testWait = () => (Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : 10) * 1000
243
+ const noAnswer = () => `no answer within ${testWait() / 1000} seconds`
239
244
  // Never throws: { ok, ms, reply } or { ok: false, ms, status, error }; { stopped } when stop
240
245
  // (a run's Stop) cancels it.
241
246
  async function tryOne({ provider, model }, stop) {
@@ -244,14 +249,14 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
244
249
  c.purpose = 'test'
245
250
  const t0 = Date.now()
246
251
  try {
247
- const signal = stop ? AbortSignal.any([AbortSignal.timeout(90_000), stop]) : AbortSignal.timeout(90_000)
252
+ const signal = stop ? AbortSignal.any([AbortSignal.timeout(testWait()), stop]) : AbortSignal.timeout(testWait())
248
253
  const r = await c.chat({ messages: [{ role: 'user', content: 'Reply with just the word OK.' }], stream: true }, { signal })
249
254
  const reply = (r.content || '').trim()
250
255
  if (!reply && !r.toolCalls.length) return { ok: false, ms: Date.now() - t0, error: `it answered with nothing${r.usage?.completion_tokens ? ` (${r.usage.completion_tokens} tokens it said it wrote)` : ''}` }
251
256
  return { ok: true, ms: Date.now() - t0, reply: reply.slice(0, 80) }
252
257
  } catch (e) {
253
258
  if (stop?.aborted) return { stopped: true }
254
- return { ok: false, ms: Date.now() - t0, status: e.status ?? null, error: e.name === 'TimeoutError' ? 'no answer within 90 seconds' : whyFailed(e), ...(e.retryAfter > 0 && { retryAfter: Number(e.retryAfter) }) }
259
+ return { ok: false, ms: Date.now() - t0, status: e.status ?? null, error: e.name === 'TimeoutError' ? noAnswer() : whyFailed(e), ...(e.retryAfter > 0 && { retryAfter: Number(e.retryAfter) }) }
255
260
  }
256
261
  }
257
262
  // result: kept and sent to the page (given: a test already made, as a run decided to end it)
@@ -360,7 +365,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
360
365
  model: cfg.model ?? null,
361
366
  order: [...(cfg.providers[cfg.provider] && cfg.model ? [{ provider: cfg.provider, model: cfg.model }] : []), ...rotationOf(cfg).then].map((t) => ({ ...t, tested: testedOf(t), known: knownOf(t), price: priceFor(t) })),
362
367
  rotation: (({ then, ...opts }) => opts)(rotationOf(cfg)),
363
- settings: { permissions: cfg.permissions ?? 'all', effort: cfg.effort ?? 'default', theme: cfg.theme ?? 'dark', context: cfg.context ?? null, ...Object.fromEntries(Object.keys(TOGGLES).map((k) => [k, cfg[k] !== false])), ...Object.fromEntries(LOG_SWITCHES.map((k) => [k, cfg[k] === true])), logDetail: cfg.logDetail === 'summary' ? 'summary' : 'full', logDays: logDays(cfg) },
368
+ settings: { permissions: cfg.permissions ?? 'all', effort: cfg.effort ?? 'default', theme: cfg.theme ?? 'dark', context: cfg.context ?? null, ...Object.fromEntries(Object.keys(TOGGLES).map((k) => [k, cfg[k] !== false])), ...Object.fromEntries(LOG_SWITCHES.map((k) => [k, cfg[k] === true])), logDetail: cfg.logDetail === 'summary' ? 'summary' : 'full', logDays: logDays(cfg), testTimeout: Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : 10 },
364
369
  logs: { runs: tilde(path.join(LOGS, 'runs')), requests: tilde(REQUESTS) },
365
370
  voice: cfg.voice ? JSON.stringify(cfg.voice, null, 2) : '',
366
371
  statusBar: cfg.statusBar === undefined ? null : cfg.statusBar, // false (off), a list of lines, or null (default)
@@ -382,6 +387,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
382
387
  'GET /api/log-size': () => logSize(),
383
388
  'POST /api/prefs': ({ key, value }) => {
384
389
  if (!PREF_KEYS.includes(key)) throw new Error(`no such choice: ${key}`)
390
+ ownWrite = Date.now() // the page's own choice: not sent back to it as a change (a second redraw)
385
391
  writeJson(PREFS, { ...readJson(PREFS, {}), [key]: value })
386
392
  return {}
387
393
  },
@@ -529,6 +535,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
529
535
  const changed1 = cfg.provider !== clean[0]?.provider || cfg.model !== clean[0]?.model
530
536
  Object.assign(cfg, { provider: clean[0]?.provider, model: clean[0]?.model })
531
537
  cfg.rotation = { on: opts.on, retries: opts.retries, next: opts.next, then: clean.slice(1) }
538
+ ownWrite = Date.now()
532
539
  saveConfig(cfg)
533
540
  changed(changed1 ? 'model' : 'setting:rotation')
534
541
  test(clean)
@@ -552,7 +559,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
552
559
  const sent = { method: 'POST', url, headers: { 'content-type': 'application/json', ...(c.apiKey && { authorization: `Bearer ${mask(c.apiKey)}` }) }, body }
553
560
  const t0 = Date.now()
554
561
  try {
555
- const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...(c.apiKey && { authorization: `Bearer ${c.apiKey}` }) }, body: JSON.stringify(body), signal: AbortSignal.timeout(90_000) })
562
+ const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...(c.apiKey && { authorization: `Bearer ${c.apiKey}` }) }, body: JSON.stringify(body), signal: AbortSignal.timeout(testWait()) })
556
563
  const text = await res.text()
557
564
  let json = null
558
565
  try {
@@ -561,7 +568,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
561
568
  const reply = json?.choices?.[0]?.message?.content ?? null
562
569
  return { sent, received: { status: res.status, ok: res.ok, ms: Date.now() - t0, type: res.headers.get('content-type'), body: json ?? text.slice(0, 20_000) }, reply }
563
570
  } catch (e) {
564
- return { sent, received: { error: e.name === 'TimeoutError' ? 'no answer within 90 seconds' : `couldn't send it: ${e.cause?.code || e.cause?.message || e.message}`, ms: Date.now() - t0 } }
571
+ return { sent, received: { error: e.name === 'TimeoutError' ? noAnswer() : `couldn't send it: ${e.cause?.code || e.cause?.message || e.message}`, ms: Date.now() - t0 } }
565
572
  }
566
573
  },
567
574
  'POST /api/tests': () => ({ results: tests, run: run && { ...runState(), pending: [...run.pending] } }),
@@ -640,7 +647,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
640
647
  if ((name in TOGGLES || LOG_SWITCHES.includes(name)) && typeof value !== 'boolean') throw new Error(`${name}: on or off`)
641
648
  if (name === 'logDays' && !(Number.isInteger(value) && value >= 1 && value <= 3650)) throw new Error('logDays: a whole number of days, 1 to 3650')
642
649
  if (name === 'logDetail' && !DETAILS.includes(value)) throw new Error(`logDetail: ${DETAILS.join(' or ')}`)
643
- if (!['permissions', 'effort', 'theme', 'context', 'logDetail', 'logDays', ...Object.keys(TOGGLES), ...LOG_SWITCHES].includes(name)) throw new Error(`no setting "${name}"`)
650
+ if (name === 'testTimeout' && !(Number.isInteger(value) && value >= 1 && value <= 600)) throw new Error('test timeout: a whole number of seconds, 1 to 600')
651
+ if (!['permissions', 'effort', 'theme', 'context', 'logDetail', 'logDays', 'testTimeout', ...Object.keys(TOGGLES), ...LOG_SWITCHES].includes(name)) throw new Error(`no setting "${name}"`)
644
652
  cfg[name] = name === 'effort' && value === 'default' ? undefined : name === 'context' ? (value === null ? undefined : Number(value)) : value
645
653
  save(`setting:${name}`)
646
654
  if (name === 'logRequests' || name === 'logDetail') useRequestLog(cfg) // from the next request (a running HeartCode takes it in too: applySettings)
@@ -882,6 +890,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
882
890
  try {
883
891
  const w = fs.watch(HOME, { recursive: true }, (_, f) => {
884
892
  if (!SETTINGS_FILES.includes(String(f ?? '').split(path.sep)[0])) return
893
+ if (Date.now() - ownWrite < 1000 && ['config.json', 'settings-page.json'].includes(String(f))) return // written here a moment ago: the page has it
885
894
  clearTimeout(pending)
886
895
  pending = setTimeout(pushState, 150) // a file written in parts, several at once: one look
887
896
  })
package/src/ui.js CHANGED
@@ -1132,7 +1132,7 @@ export class UI {
1132
1132
  for (const [i, l] of this.ahead.slice(0, 5).entries()) bottom.push(fit(` ${c.accent(`${i + 1}.`)} ${c.muted(l.replace(/\s+/g, ' '))}`, cols))
1133
1133
  if (this.ahead.length > 5) bottom.push(c.faint(` … ${this.ahead.length - 5} more`))
1134
1134
  }
1135
- if (this.noticeText) bottom.push(fit(`${c.warn('!')} ${c.muted(this.noticeText)}`, cols))
1135
+ if (this.noticeText) bottom.push(fit(this.noticeMark ? `${c.warn(this.noticeMark)} ${c.muted(this.noticeText)}` : ` ${c.muted(this.noticeText)}`, cols))
1136
1136
  if (menu.on && !asked) bottom.push(...this.#menuLines(cols))
1137
1137
  bottom.push(first ? note(first, '↑') : rule)
1138
1138
  const head = [...(this.tabBar?.(cols) ?? []), ...(this.header?.(cols) ?? [])].map((l) => fit(l, cols))
@@ -1464,14 +1464,27 @@ export class UI {
1464
1464
  write('\r', { name: 'return' })
1465
1465
  }
1466
1466
 
1467
- // The words go where the cursor is, in the box (also while it works).
1468
- async dictateIn() {
1467
+ // Voice: listening at once; the words go where the cursor is, in the box (also while it works), and
1468
+ // on Enter they're sent: at the prompt as if Enter was pressed, while it works as a message typed
1469
+ // then (a command that can run beside the task runs; the rest waits in the queue).
1470
+ async dictateIn(send = true) {
1469
1471
  const text = await this.dictate()
1470
1472
  if (!text) return
1471
1473
  const rl = this.rl
1472
1474
  const pad = rl.line && !/\s$/.test(rl.line.slice(0, rl.cursor)) ? ' ' : ''
1473
1475
  rl.line = rl.line.slice(0, rl.cursor) + pad + text + rl.line.slice(rl.cursor)
1474
1476
  rl.cursor += pad.length + text.length
1477
+ if (!send) return this.render()
1478
+ if (this.asking && this.histOn) {
1479
+ this.sent = rl.line
1480
+ this.menu.items = []
1481
+ return this.ttyWrite('\r', { name: 'return' })
1482
+ }
1483
+ if (this.asking) return this.render() // a question's answer: in its box, to check and send
1484
+ const line = rl.line.trim()
1485
+ rl.line = ''
1486
+ rl.cursor = 0
1487
+ if (line && !this.onNow?.(line)) this.ahead.push(line)
1475
1488
  this.render()
1476
1489
  }
1477
1490
 
@@ -1514,9 +1527,9 @@ export class UI {
1514
1527
  }
1515
1528
  const draw = () => {
1516
1529
  showBox()
1517
- const keys = 'Enter to finish · Esc to cancel'
1518
- if (finishing) return this.notice('transcribing…', 60 * 60_000)
1519
- this.notice(mic ? `● listening ${Math.floor(mic.seconds())}s · Space to pause · ${keys}` : `voice · Space to ${said ? 'go on' : 'talk'} · ${keys}`, 60 * 60_000)
1530
+ const keys = 'Enter to send · Esc to cancel'
1531
+ if (finishing) return this.notice('transcribing the last part… (Esc cancels)', 60 * 60_000, '')
1532
+ this.notice(mic ? `${c.red('●')} listening ${Math.floor(mic.seconds())}s · Space to pause · ${keys}` : `paused · Space to go on · ${keys}`, 60 * 60_000, '')
1520
1533
  }
1521
1534
  const heard = (pcm, fast) =>
1522
1535
  transcribePcm(pcm, voice, providers, { fast }).catch((e) => {
@@ -1552,9 +1565,9 @@ export class UI {
1552
1565
  draw()
1553
1566
  })
1554
1567
  }
1555
- draw()
1568
+ start() // listening at once: the key that got here was the go-ahead
1556
1569
  const tick = setInterval(() => mic && draw(), 1000)
1557
- const go = await new Promise((resolve) => {
1570
+ let go = await new Promise((resolve) => {
1558
1571
  this.recording = {
1559
1572
  key: (key, bound) => {
1560
1573
  if (key.name === 'escape') resolve(false)
@@ -1564,10 +1577,12 @@ export class UI {
1564
1577
  }
1565
1578
  })
1566
1579
  clearInterval(tick)
1567
- this.recording = null
1580
+ // the last part being transcribed: keys still wait (an Enter now would send half of it); Esc cancels
1581
+ this.recording = { key: (key) => key.name === 'escape' && (go = false) }
1568
1582
  if (!go) mic?.cancel(), (mic = null)
1569
1583
  else if (mic) (finishing = true), pause()
1570
1584
  await busy
1585
+ this.recording = null
1571
1586
  if (rl) [rl.line, rl.cursor] = [base.line, base.cursor] // the caller puts the words in
1572
1587
  const text = go ? words().trim() : ''
1573
1588
  log('voice', go ? text : '(cancelled)')
@@ -1644,8 +1659,10 @@ export class UI {
1644
1659
 
1645
1660
  // initial: text already typed in, ready to edit. suggest: show the suggestion menu while typing.
1646
1661
  // A one-line message just above the input until `ms` pass or a key is pressed ('' hides it).
1647
- notice(text, ms = 2000) {
1662
+ // mark: what goes before it ('!' a warning; '' none, for a state like voice listening)
1663
+ notice(text, ms = 2000, mark = '!') {
1648
1664
  this.noticeText = text
1665
+ this.noticeMark = mark
1649
1666
  clearTimeout(this.noticeTimer)
1650
1667
  if (text) this.noticeTimer = setTimeout(() => this.notice(''), ms)
1651
1668
  this.render()