heartcode 0.1.69 → 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/client.js CHANGED
@@ -5,6 +5,7 @@ import { log, logRequest, requestLog } from './log.js'
5
5
  import { loadRankings, scoreOf } from './rankings.js'
6
6
  import { byRecord, unreliable, record } from './record.js'
7
7
  import { fetch } from './http.js' // not the built-in one: see http.js
8
+ import { cliOf, cliModels, cliChat } from './clis.js'
8
9
 
9
10
  // Tokens in a text, estimated the way tokenizers split it: a word or a number is about one, a long
10
11
  // word more, every symbol one. Prose comes out near characters ÷ 4; code, CSS, JSON and SVG paths,
@@ -225,6 +226,10 @@ export class Client {
225
226
  this.rotation = { list, on, retries, next, at: 0, good: list[0] }
226
227
  this.#use(list[0])
227
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
+ }
228
233
  get target() {
229
234
  return this.rotation?.list[this.rotation.at] ?? null
230
235
  }
@@ -297,7 +302,10 @@ export class Client {
297
302
  if (!r || r.next !== 'first') return
298
303
  const i = Math.max(0, r.list.findIndex((t) => !unreliable(t)))
299
304
  if (r.at !== i) {
300
- if (i) log('rotate', `${r.list[0].model} failed most of its recent work (its track record): this message starts with ${r.list[i].model}`)
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
+ }
301
309
  this.#use(r.list[(r.at = i)])
302
310
  }
303
311
  }
@@ -390,6 +398,7 @@ export class Client {
390
398
  }
391
399
  // The server's own entries for its models ({ id, owned_by, context_length, pricing… }, as it sends them).
392
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
393
402
  const data = await this.#json(this.baseUrl + '/models', undefined, timeout)
394
403
  // { result: [...] } (Cloudflare's shape): there the id is an internal one and the name is the model's
395
404
  if (Array.isArray(data.result)) return data.result.filter((m) => m?.name).map((m) => ({ ...m, id: m.name }))
@@ -402,6 +411,7 @@ export class Client {
402
411
  // server that is one of these is treated as a model server on this machine or network; its
403
412
  // address (localhost, 192.168…) says nothing (a proxy there may serve Gemini).
404
413
  async contextSize() {
414
+ if (this.cli) return { size: undefined, server: null }
405
415
  const root = this.baseUrl.replace(/\/v1$/, '')
406
416
  const host = new URL(root).hostname
407
417
  const n = (x) => (Number(x) > 0 ? Number(x) : undefined)
@@ -450,6 +460,7 @@ export class Client {
450
460
  // 131072"). Refused requests aren't charged. If it's accepted (a window that big), it's stopped
451
461
  // at once. Returns { limit } | { over } (it took that many) | { error }. Not logged: it's 4 MB.
452
462
  async measureContext({ signal, tokens = 2_200_000 } = {}) {
463
+ if (this.cli) return { error: 'a coding CLI keeps its own context' }
453
464
  const headers = { 'content-type': 'application/json', ...(this.apiKey && { authorization: `Bearer ${this.apiKey}` }) }
454
465
  const body = JSON.stringify({ model: this.model, messages: [{ role: 'user', content: 'a '.repeat(tokens) }], stream: true })
455
466
  const stop = new AbortController()
@@ -495,6 +506,7 @@ export class Client {
495
506
  let rounds = 0 // whole rounds of the list that failed
496
507
  const tried = new Set() // places in the model list tried for this request
497
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
498
510
  for (let attempt = 0; ; attempt++) {
499
511
  // The list moved on to a model whose window can't hold this request (a smaller one): not sent
500
512
  // to it as it is; the caller compacts the conversation for that model, then sends it (fit: the
@@ -511,7 +523,10 @@ export class Client {
511
523
  } catch (e) {
512
524
  if (e.name === 'AbortError' || opts.signal?.aborted) throw e
513
525
  this.onFail?.(e, { provider: this.provider, model: this.model }) // what it says is learned (a stated limit)
514
- if (e.status !== 429) record({ provider: this.provider, model: this.model }, 'no-answer') // its track record: didn't answer, refused the key, needs a paid plan… (a rate limit passes)
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')
515
530
  // With a list of models, any failure makes way for the next one (another provider's first).
516
531
  // Without one, only what waiting can fix is tried again.
517
532
  if (!(this.rotation?.list.length > 1) && !outage(e)) throw e
@@ -548,6 +563,7 @@ export class Client {
548
563
  async #timed(body, opts) {
549
564
  this.inFlight = Date.now()
550
565
  try {
566
+ if (this.cli) return await cliChat(this, body, opts) // a coding CLI (clis.js) answers it
551
567
  return await this.#chat(body, opts)
552
568
  } catch (e) {
553
569
  if (!e.recorded && this.last) this.#record(this.last.req, this.last.sent, { error: e }) // failed while the reply streamed in
@@ -748,9 +764,11 @@ export class Client {
748
764
  if (chunk.usage) usage = chunk.usage
749
765
  const ch = chunk.choices?.[0]
750
766
  if (!ch) continue
751
- started() // it answers (a keep-alive or an empty frame doesn't get here)
752
767
  if (ch.finish_reason) finishReason = ch.finish_reason
753
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()
754
772
  this.#reasoningField(d)
755
773
  if (Array.isArray(d.content)) d.content = textOf(d.content)
756
774
  const r = d.reasoning_content || d.reasoning || d.thinking