heartcode 0.1.58 → 0.1.60

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/agent.js CHANGED
@@ -8,7 +8,7 @@ import path from 'node:path'
8
8
  import { est, estMessages, Client, tokensOf, COMPACT_SHARE } from './client.js'
9
9
  import { runGuided } from './guided.js'
10
10
  import { markUsed, removeResearch, findResearch } from './research.js'
11
- import { TOOL_DEFS, PLAN_HIDDEN, folderView, readOnlyCommand, searchesOutside, extraTools, runTool, listFiles, namedFiles, readFileTool, clip, allowed, loadMcpTools, saveOutput, isSavedOutput, runningCall, imageUrl, MAX_IMAGE, failed, refusal, noteNamedPaths } from './tools.js'
11
+ import { TOOL_DEFS, PLAN_HIDDEN, folderView, readOnlyCommand, searchesOutside, extraTools, runTool, listFiles, namedFiles, readFileTool, clip, allowed, loadMcpTools, saveOutput, isSavedOutput, runningCall, imageUrl, MAX_IMAGE, failed, refusal, noteNamedPaths, sendTodos, stuckSaid } from './tools.js'
12
12
  import { serversNote } from './lsp.js'
13
13
  import { newlyEnded, jobLine } from './background.js'
14
14
  import { loadHooks, runHooks } from './hooks.js'
@@ -239,31 +239,25 @@ export class Session {
239
239
  async subagent(args, signal, id) {
240
240
  const task = String(args.prompt ?? args.task ?? '').trim()
241
241
  if (!task) return 'error: give the helper its job in "prompt"'
242
+ // an image named in the job but not given in "images" (a screenshot's path): given, so a model
243
+ // that can see takes the job; one that can't would answer without looking
244
+ const named = [...task.matchAll(/(?:^|[\s"'`(])((?:~|\/|\.{0,2}\/)?[\w./-]+\.(?:png|jpe?g|webp|gif))\b/gi)].map((m) => m[1]).filter((f) => fs.existsSync(path.resolve(this.root, f.replace(/^~(?=\/)/, os.homedir()))))
245
+ const given = [].concat(args.images ?? []).filter(Boolean)
242
246
  let images
243
247
  try {
244
- images = await loadImages(args.images, this, signal)
248
+ images = await loadImages(given.length || !named.length ? args.images : [...new Set(named)], this, signal)
245
249
  } catch (e) {
246
250
  if (e.name === 'AbortError') throw e
247
- return `error: ${e.message}`
251
+ if (given.length || !named.length) return `error: ${e.message}`
252
+ images = [] // only named in the job (one it may not send): the job as it was
248
253
  }
249
254
  const name = (t) => `${t.provider} ${t.model}`
250
- const self = { provider: this.client.provider, model: this.client.model, images: this.strat.vision, tools: this.strat.actions === 'tools', self: true }
251
- const team = this.team?.() ?? []
252
- const helpers = helpersOf(team)
253
- // the helpers you ticked (then this model), else this model and your others, in your list's order
254
- const all = helpers ? [...helpers, self] : [self, ...team]
255
- const want = String(args.model ?? '').trim()
256
- // only one model available (a pinned model, or you have just one): helpers use it, whatever was asked
257
- const first = !want || all.length === 1 ? all[0] : (all.find((t) => name(t) === want || `${t.provider}/${t.model}` === want) ?? all.find((t) => t.model === want || want.endsWith(` ${t.model}`) || t.model.endsWith(`/${want}`)))
258
- if (!first) return `error: no model "${want}". ${helpers ? 'Your helpers' : 'Yours'}: ${all.map(name).join(', ')}`
259
- // the one asked for first, then the others in your list's order: only those that can do the job
260
- // (images need a model that sees them)
261
- const able = (t) => !images.length || t.images
262
- let order = [first, ...all.filter((t) => t !== first)].filter(able)
263
- if (!order.length && helpers) order = [self, ...team].filter(able) // no helper sees images: any of yours that does
255
+ const { order, first, all, helpers } = this.helperModels(args, images.length > 0)
256
+ if (!first) return `error: no model "${String(args.model).trim()}". ${helpers ? 'Your helpers' : 'Yours'}: ${all.map(name).join(', ')}`
264
257
  if (!order.length) return 'error: none of your models can see images'
265
258
  const failed = []
266
259
  for (const [i, t] of order.entries()) {
260
+ if (args.part) (args.part.by = t.model), (args.part.byProvider = t.provider ?? this.client.provider), sendTodos(this) // a part of the plan: the model doing it, shown beside it
267
261
  let answer = ''
268
262
  try {
269
263
  answer = (await this.#helper(t, task, images, args.description, id, signal, args.ownFiles))?.trim()
@@ -279,6 +273,24 @@ export class Session {
279
273
  return `error: none of your models that can do it managed: ${failed.join('; ')}`
280
274
  }
281
275
 
276
+ // The models a helper's job goes to, in order: the one asked for (args.model), then the helpers you
277
+ // ticked (then this model), else this model and your others, in your list's order; only those that
278
+ // see images when it comes with some. first: the one asked for (undefined: no such model).
279
+ helperModels(args, withImages) {
280
+ const name = (t) => `${t.provider} ${t.model}`
281
+ const self = { provider: this.client.provider, model: this.client.model, images: this.strat.vision, tools: this.strat.actions === 'tools', self: true }
282
+ const team = this.team?.() ?? []
283
+ const helpers = helpersOf(team)
284
+ const all = helpers ? [...helpers, self] : [self, ...team]
285
+ const want = String(args.model ?? '').trim()
286
+ // only one model available (a pinned model, or you have just one): helpers use it, whatever was asked
287
+ const first = !want || all.length === 1 ? all[0] : (all.find((t) => name(t) === want || `${t.provider}/${t.model}` === want) ?? all.find((t) => t.model === want || want.endsWith(` ${t.model}`) || t.model.endsWith(`/${want}`)))
288
+ const able = (t) => !withImages || t.images
289
+ let order = first ? [first, ...all.filter((t) => t !== first)].filter(able) : []
290
+ if (first && !order.length && helpers) order = [self, ...team].filter(able) // no helper sees images: any of yours that does
291
+ return { order, first, all, helpers }
292
+ }
293
+
282
294
  // One helper on one model (t: this one, or another of yours), with its own connection (a helper's
283
295
  // failure moves no one else on to another model) that gives up after a few tries (then the next
284
296
  // model gets the job).
@@ -290,15 +302,19 @@ export class Session {
290
302
  client.retryIf = (e, attempt) => attempt < 3 && e.name !== 'TimeoutError' && e.status !== 429 && e.status !== 413 && (!was || was(e, attempt)) // silent (not starting, or stopping midway: each try would wait as long again), rate-limited or too large: the next model, not another try
291
303
  }
292
304
  const label = clip(String(description ?? '').trim() || task.split('\n')[0], 60) // its model is named on the agent line
293
- const helper = new Session({ client, profile, strat, root: this.root, ui: helperUI(this.ui, label), chat: newChat(this.root) })
305
+ const helper = new Session({ client, profile, strat, root: this.root, ui: helperUI(this.ui, label, client.model), chat: newChat(this.root) })
294
306
  helper.chat.turns = this.chat.turns.slice(-1) // this message's turn: its file changes go there (track), the changes tool reads them
295
307
  if (ownFiles?.length) helper.ownFiles = ownFiles.map((f) => path.resolve(this.root, f)) // a part of the plan: changes only its own files
296
308
  Object.assign(helper, { isSub: true, research: this.research, ran: this.ran, noResearch: this.noResearch, mcp: this.mcp, skills: this.skills, hooks: this.hooks, allowTools: this.allowTools, denyTools: this.denyTools, maxTurns: this.maxTurns, autoCompact: this.autoCompact, appendSystem: this.appendSystem, fileCache: this.fileCache, noFormat: this.noFormat, noLsp: this.noLsp })
297
309
  helper.track = (rel, before) => this.track(rel, before)
310
+ // a helper that can't see, given screenshots by a tool (a browser): one of your models that can
311
+ // describes them for its job (it has no helpers of its own to ask)
312
+ const seers = strat.vision ? [] : (this.team?.() ?? []).filter((x) => x.images)
313
+ if (seers.length && this.engineFor) helper.describeFor = async (files) => (await this.describeImages(files.map((f) => imageUrl(f)), seers, task, signal, () => prompt('agent/describe-screenshot', { task: clip(task, 1500) }))).trim()
298
314
  helper.mcpGate = async () => (await this.#gate(helper), () => {})
299
315
  if (this.onEvent) helper.onEvent = (e) => this.onEvent({ ...e, parent: id, helper: label })
300
316
  log('agent', `helper "${label}" (${images.length} image(s)): ${task}`)
301
- this.ui.helpers?.set(label, 'starting') // a line under the spinner while it works (helperUI keeps it up to date)
317
+ this.ui.helpers?.set(label, { id, model: `${t.provider ?? client.provider}/${t.model ?? client.model}`, what: 'starting' }) // a line under the spinner while it works (helperUI keeps it up to date)
302
318
  try {
303
319
  const answer = await (strat.actions === 'tools' ? runNative : runGuided)(helper, task, images, signal)
304
320
  log('agent', `helper "${label}" done`, answer)
@@ -343,7 +359,8 @@ export class Session {
343
359
 
344
360
  // Images for a model that can't see them: your models that can describe each, for the task (the
345
361
  // next one when one fails).
346
- async describeImages(images, seers, task, signal) {
362
+ // ask: the request for each (default: an image the user attached).
363
+ async describeImages(images, seers, task, signal, ask = () => prompt('guided/describe-image', { task })) {
347
364
  const out = []
348
365
  let by = ''
349
366
  for (const [i, url] of images.entries()) {
@@ -353,7 +370,7 @@ export class Session {
353
370
  try {
354
371
  const { client } = await this.engineFor(seer)
355
372
  client.retryIf = (e, attempt) => attempt < 3 && !e.notStarted
356
- said = (await client.chat({ messages: [{ role: 'user', content: [{ type: 'text', text: prompt('guided/describe-image', { task }) }, { type: 'image_url', image_url: { url } }] }] }, { signal })).content.trim()
373
+ said = (await client.chat({ messages: [{ role: 'user', content: [{ type: 'text', text: ask() }, { type: 'image_url', image_url: { url } }] }] }, { signal })).content.trim()
357
374
  } catch (e) {
358
375
  if (e.name === 'AbortError' || signal?.aborted) throw e
359
376
  this.ui.warn(`${seer.model} couldn't look at image ${i + 1}: ${clip(e.message, 120)}`)
@@ -453,7 +470,7 @@ export class Session {
453
470
  // It runs after the answer is back (wrapUpLater), beside whatever you do next: its own connection,
454
471
  // one wrap-up at a time; what it needs is taken from the task first, before the next one changes it.
455
472
  wrapUpLater(task, answer) {
456
- const at = { research: this.research, turn: this.chat.turns.at(-1), dirsBefore: this.dirsBefore, ran: this.ran, runs: this.runs }
473
+ const at = { research: this.research, turn: this.chat.turns.at(-1), dirsBefore: this.dirsBefore, ran: this.ran, runs: this.runs, troubles: this.troubles?.splice(0) ?? [], stuckLeft: (this.chat.todos ?? []).some((t) => t.status === 'stuck'), review: this.lastReview, model: this.client.model, unstuckLearned: this.unstuckLearned }
457
474
  const job = (this.wrapping ?? Promise.resolve())
458
475
  .then(() => this.wrapUp(task, answer, undefined, at))
459
476
  .catch((e) => log('wrapup', `failed: ${e.message}`))
@@ -464,6 +481,16 @@ export class Session {
464
481
  // at: the task's own state (wrapUpLater), else this message's
465
482
  async wrapUp(task, answer, signal, at = { research: this.research, turn: this.chat.turns.at(-1), dirsBefore: this.dirsBefore, ran: this.ran, runs: this.runs }) {
466
483
  if (this.isSub || !this.memory || this.ui.permission === 'plan') return
484
+ // it struggled (said it was stuck, gave up, was handed over): what blocked it is learned, so the
485
+ // next task like this starts knowing it. Solved: what got it out; not: what to know or try first
486
+ // What it learns from: how it ended (the answer, the review's points), not the excuses given on the
487
+ // way ("I can't browse" would teach giving up); the steps it said it was stuck on, with why.
488
+ const unsolved = Boolean(at.stuckLeft || at.review?.verdict === 'no' || SAYS_FAILED.test(String(answer ?? '').slice(0, 400)))
489
+ if (at.troubles?.length && (unsolved || !at.unstuckLearned)) { // solved, and what got it out learned already: not again
490
+ const steps = [...new Set(at.troubles.filter((t) => t.step !== 'the task' && t.step !== 'handed over').map((t) => `${t.step}: ${t.why}`))].slice(-2)
491
+ const what = [`${unsolved ? 'Not done' : `Done by ${at.model} after other tries failed`}. Its answer: ${clip(String(answer ?? '').replace(/\s+/g, ' '), 400)}`, at.review?.verdict === 'no' && `The review said: ${clip(at.review.issues.replace(/\s+/g, ' '), 300)}`, steps.length && `Stuck on: ${steps.join(' / ')}`].filter(Boolean).join('\n')
492
+ await learnFromFixes(this, [{ error: what, context: 'general' }], signal, { unsolved, task }).catch((e) => log('learn', `troubles: ${e.message}`))
493
+ }
467
494
  const pages = at.research ?? []
468
495
  const turn = at.turn
469
496
  const made = Object.entries(turn?.files ?? {}).filter(([rel, before]) => before === null && fs.existsSync(path.join(this.root, rel))).map(([rel]) => rel)
@@ -572,7 +599,7 @@ const alwaysSkill = (k) => {
572
599
  const SYSTEM = (s) => {
573
600
  const instructions = userInstructions(s.root)
574
601
  return [
575
- prompt('agent/system', { root: s.root, env: envLine(), today: new Date().toISOString().slice(0, 10), rootList: rootList(s.root), servers: serversNote(s.root), files: '', more: '', caller: Boolean(s.appendSystem), see: Boolean(s.strat.vision), noUser: Boolean(s.ui.noUser || s.isSub) }), // models that can see often say they can't: told they can
602
+ prompt('agent/system', { root: s.root, env: envLine(), today: new Date().toISOString().slice(0, 10), rootList: rootList(s.root), servers: serversNote(s.root), files: '', more: '', caller: Boolean(s.appendSystem), see: Boolean(s.strat.vision), noUser: Boolean(s.ui.noUser || s.isSub), memory: Boolean(s.memory) && !s.isSub }), // models that can see often say they can't: told they can
576
603
  instructions && prompt('agent/instructions', { instructions }),
577
604
  ...[...(s.skills?.values() ?? [])].filter((k) => k.use === 'always').map(alwaysSkill), // skills that say how to work (use: always), with the files they bring
578
605
  !s.isSub && teamPrompt(s),
@@ -592,7 +619,7 @@ const teamPrompt = (s) => {
592
619
  const team = s.team?.() ?? []
593
620
  if (!team.length) return ''
594
621
  const helpers = helpersOf(team)
595
- const can = (t) => [t.tools === false && 'no tool calls', t.images && 'images', t.thinking && 'thinking'].filter(Boolean)
622
+ const can = (t) => [t.tools === false && 'no tool calls', t.images && 'images', t.thinking && 'thinking', t.context && `${kTokens(t.context)} context`].filter(Boolean)
596
623
  const good = (t) => (t.jobs?.length ? ` · good at: ${t.jobs.map((j) => HELPER_JOBS[j]?.[1]).filter(Boolean).join('; ')}` : '')
597
624
  const line = (t) => `- ${t.provider} ${t.model}${can(t).length ? `: ${can(t).join(', ')}` : ''}${good(t)}`
598
625
  return prompt('agent/team', { helpers: Boolean(helpers), models: (helpers ?? team).map(line).join('\n'), you: [s.strat.vision ? 'images' : 'no images', s.strat.thinking && 'thinking'].filter(Boolean).join(', ') })
@@ -870,9 +897,11 @@ async function runNative(s, task, images, signal) {
870
897
  s.splitAsked = false // asked whether a plan's parts could run side by side, this message
871
898
  s.lookedUp = s.researchAsked = false // searched or read the web this message / asked whether the plan needs it
872
899
  // what changed and when it was last checked, this message: a change not run/tested since isn't done
873
- Object.assign(s, { changed: new Set(), seq: 0, lastChangeAt: -1, lastCheckAt: -1, reviewedAt: -1, checksSince: 0, spots: new Map() })
900
+ Object.assign(s, { changed: new Set(), seq: 0, lastChangeAt: -1, lastCheckAt: -1, reviewedAt: -1, checksSince: 0, spots: new Map(), stuckReports: 0, stuckSelf: null, stuckHandovers: 0, troubles: [], unstuck: [], reviewedRan: 0, lastReview: null, gaveUp: new Set(), toldLast: false, unstuckLearned: false })
874
901
 
875
902
  let empty = 0 // replies in a row with neither text nor tool calls
903
+ let lastFinal = '' // the last answer it gave (a next one the same, after being told it isn't done: it's stuck)
904
+ let refusedCan = 0 // replies saying it can't (browse, run…) before trying a tool, this message
876
905
  let looping = 0 // replies cut for going into a loop, this message
877
906
  let stuck = null // why it's going round in circles (then the next model takes over; nothing stops but Esc)
878
907
  // Going round in circles: the next of your models carries on (a different model often gets out of
@@ -881,12 +910,21 @@ async function runNative(s, task, images, signal) {
881
910
  // the job goes to your next model.
882
911
  const handOver = (why) => {
883
912
  const was = client.model
884
- if (client.moveOn?.(`${was} ${why}`)) ui.warn(`${was} ${why}; handing over to ${client.model}`)
913
+ s.gaveUp.add(`${client.provider}/${was}`) // not gone back to this message, nor asked for a second opinion
914
+ if (client.moveOn?.(`${was} ${why}`, s.gaveUp)) {
915
+ ui.warn(`${was} ${why}; handing over to ${client.model}`)
916
+ // the next model sees the whole conversation: told it's taking over, and not to repeat what didn't work
917
+ s.messages.push({ role: 'user', content: prompt('agent/taken-over', { was, why, plan: (s.chat.todos ?? []).filter((t) => t.status !== 'completed').map((t) => `- ${t.content}${t.why ? ` (stuck: ${t.why})` : ''}`).join('\n') }) })
918
+ s.stuckReports = 0
919
+ s.troubles?.push({ model: was, step: 'handed over', why })
920
+ }
885
921
  else if (s.isSub) throw Object.assign(new Error(`${was} ${why}`), { stuck: true })
886
922
  else ui.warn(`${was} ${why} — it carries on, told so; Esc stops it`)
887
923
  }
888
924
  let garbled = 0 // replies with a tool call written as text (template markup), this message
889
925
  let movedOn = 0 // models given up on for that, in this message
926
+ let cut = '' // a reply cut off (its provider's output limit, or the connection ended early): what came of it so far
927
+ let cuts = 0 // cut off in a row: asked to go on, up to 3 times
890
928
  let refitted = false // this step's conversation was just compacted for a smaller model the list moved on to
891
929
  // No step limit (helpers too): a long fix takes many steps, and Esc stops it. A caller can set one (--max-turns).
892
930
  for (let step = 0; ; step++) {
@@ -931,7 +969,11 @@ async function runNative(s, task, images, signal) {
931
969
  }
932
970
  const stream = strat.stream
933
971
  // A long tool call (a whole file) streams in silently: say what's being written.
934
- const onToolDelta = (name, args) => ui.spinner(`${name === 'run_command' ? 'preparing a command' : `writing ${/"path"\s*:\s*"([^"]+)"/.exec(args)?.[1] ?? name}`} · ${args.length >= 1000 ? `${(args.length / 1000).toFixed(1)}k` : args.length} chars`)
972
+ const onToolDelta = (name, args) => {
973
+ const file = /"path"\s*:\s*"([^"]+)"/.exec(args)?.[1]
974
+ const what = name === 'run_command' ? 'preparing a command' : EDITS.has(name) && file ? `writing ${file}` : `preparing ${name}${file ? ` ${file}` : ''}` // only an edit is "writing" a file
975
+ ui.spinner(`${what} · ${args.length >= 1000 ? `${(args.length / 1000).toFixed(1)}k` : args.length} chars`)
976
+ }
935
977
  // the prompts or HEARTCODE.md changed meanwhile (applySettings): the system prompt again, now
936
978
  if (s.refreshSystem && s.messages[0]?.role === 'system') s.messages[0] = { ...s.messages[0], content: SYSTEM(s) }
937
979
  s.refreshSystem = false
@@ -1014,7 +1056,20 @@ async function runNative(s, task, images, signal) {
1014
1056
  showHeld(res.content) // not the answer: shown now, before its calls
1015
1057
  s.acted = sinceNudge = true // did real work this message, for the premature-stop check
1016
1058
  }
1017
- s.onEvent?.({ type: 'assistant', model: `${client.provider}/${client.model}`, content: res.content, reasoning: res.reasoning, toolCalls: res.toolCalls }) // headless output
1059
+ s.lastStop = res.finishReason // why the last reply ended (headless: its stop_reason)
1060
+ s.onEvent?.({ type: 'assistant', model: `${client.provider}/${client.model}`, content: res.content, reasoning: res.reasoning, toolCalls: res.toolCalls, stop: res.finishReason }) // headless output
1061
+ // An answer cut off (its provider's output limit: no max_tokens is sent, so each has its own; or a
1062
+ // connection that ended early): the model goes on where it stopped (3 times in a row at most); the
1063
+ // answer is the pieces together. Still cut after that: it stays cut, and says so (stop_reason).
1064
+ if (!res.toolCalls.length && res.content?.trim() && (res.finishReason === 'length' || res.finishReason === 'incomplete') && cuts < 3) {
1065
+ cuts++
1066
+ cut += res.content
1067
+ log('task', `${client.model}: reply cut off (${res.finishReason}); asking it to go on`)
1068
+ s.messages.push({ role: 'user', content: prompt('agent/cut-off') })
1069
+ continue
1070
+ }
1071
+ if (cut && !res.toolCalls.length) res.content = cut + res.content
1072
+ if (!res.toolCalls.length || res.finishReason !== 'length') [cut, cuts] = ['', 0]
1018
1073
  if (!res.toolCalls.length && !res.content?.trim()) {
1019
1074
  // Nothing at all (seen after a failed tool call): not an answer. The same request again
1020
1075
  // first (often fine the second time), then asked to go on; three in a row ends the task.
@@ -1035,6 +1090,45 @@ async function runNative(s, task, images, signal) {
1035
1090
  return finalAnswer(s, signal)
1036
1091
  }
1037
1092
  empty = 0
1093
+ // "I can't browse / run / see…" with no tool tried this message: it has tools for that. Told what
1094
+ // it has, once; said again without trying, the next of your models takes the task
1095
+ if (!res.toolCalls.length && !s.acted && !s.isSub && CANT.test(res.content)) {
1096
+ log('task', `${client.model} said it can't, without trying a tool (${++refusedCan})`)
1097
+ if (refusedCan === 1) {
1098
+ s.messages.push({ role: 'user', content: prompt('agent/you-can', { mcp: (s.mcp?.names ?? []).join(', ') }) })
1099
+ continue
1100
+ }
1101
+ if (refusedCan === 2) {
1102
+ const was = client.model
1103
+ handOver(`said it can't do it, without trying its tools`)
1104
+ if (client.model !== was) refusedCan = 0 // the next model: told once too
1105
+ continue
1106
+ }
1107
+ }
1108
+ // its answer says it didn't manage ("couldn't", "still not loading", "unable to"): taken as saying
1109
+ // it's stuck: told to change approach, then a second opinion, then the next model (stuckSaid);
1110
+ // after two models took over, its plain account of what blocks it is the answer
1111
+ const sameAfterNo = s.lastReview?.verdict === 'no' && lastFinal && res.content.replace(/\s+/g, ' ').trim().slice(0, 300) === lastFinal.replace(/\s+/g, ' ').trim().slice(0, 300) // a review said no, and it gives the same answer again
1112
+ if (!res.toolCalls.length && s.acted && !s.isSub && !s.toldLast && (sameAfterNo || SAYS_FAILED.test(res.content.slice(0, 400)))) { // told to say plainly what blocks it: that answer is the answer
1113
+ const why = clip(res.content.replace(/\s+/g, ' ').trim(), 200)
1114
+ s.messages.push({ role: 'user', content: await stuckSaid(s, 'the task', why, signal, undefined, true) })
1115
+ if (s.stuckSelf) {
1116
+ handOver(s.stuckSelf)
1117
+ s.stuckSelf = null
1118
+ s.stuckHandovers++
1119
+ }
1120
+ continue
1121
+ }
1122
+ // told it isn't done (open todos, a review's no, its own "couldn't"), and it answers again without
1123
+ // doing anything: the same answer, or one that only promises: the next of your models takes the task
1124
+ const same = (a, b) => a && b && a.replace(/\s+/g, ' ').trim().slice(0, 300) === b.replace(/\s+/g, ' ').trim().slice(0, 300)
1125
+ if (!res.toolCalls.length && !sinceNudge && nudged && !s.isSub && client.rotation && (s.stuckHandovers ?? 0) < 2 && (same(res.content, lastFinal) || PROMISED_MORE.test(res.content) || SAYS_FAILED.test(res.content.slice(0, 400)))) {
1126
+ handOver(`was told it isn't done and answered again without doing anything`)
1127
+ s.stuckHandovers++
1128
+ sinceNudge = true
1129
+ continue
1130
+ }
1131
+ if (!res.toolCalls.length) lastFinal = res.content
1038
1132
  if (!res.toolCalls.length) {
1039
1133
  const more = sinceNudge && ((await notDone(s, signal, nudged > 0, res.content)) ?? (await review(s, task, res.content, signal)))
1040
1134
  showHeld(res.content) // after the review's line
@@ -1058,7 +1152,7 @@ async function runNative(s, task, images, signal) {
1058
1152
  }
1059
1153
  }
1060
1154
  // a helper's line: its job, and the model doing it (named once here; its steps go by its job)
1061
- const helperLine = (a) => `${clip(String(a.description ?? '').trim() || 'helper', 70)} ${c.faint(`· ${a.model || client.model}`)}`
1155
+ const helperLine = (a) => `${clip(String(a.description ?? '').trim() || 'helper', 70)} ${c.faint(`· ${s.helperModels?.(a, [a.images ?? []].flat().length > 0).order[0]?.model ?? (a.model || client.model)}`)}` // the model that will do it
1062
1156
  const together = new Map()
1063
1157
  for (const call of res.toolCalls) {
1064
1158
  const args = argsOf(call)
@@ -1105,7 +1199,7 @@ async function runNative(s, task, images, signal) {
1105
1199
  : name === 'todo' || name === 'ask_user'
1106
1200
  ? ''
1107
1201
  : (args.path ?? args.url ?? args.query ?? args.filter ?? args.name ?? '')
1108
- if (name !== 'run_command' && !together.has(call.id) && !askedWith.has(call.id)) ui.step(name, name === 'agent' && args ? helperLine(args) : clip(detail, 80)) // asked together: shown once, with the first
1202
+ if (name !== 'run_command' && !together.has(call.id) && !askedWith.has(call.id)) ui.step(name, name === 'agent' && args ? helperLine(args) : clip(detail, 80), name === 'agent' ? '' : client.model) // asked together: shown once, with the first; named by the model that made the call (an agent line names the helper's)
1109
1203
  const pre = early.get(call.id)
1110
1204
  // the first changes to the files with no plan yet (this message, or still open from an earlier one):
1111
1205
  // not made — the plan first, then the changes again. Every change in that reply (one made beside a
@@ -1116,6 +1210,7 @@ async function runNative(s, task, images, signal) {
1116
1210
  let out = refused ?? (askedWith.has(call.id) ? 'Asked together with the first ask_user call of this reply: its result has this answer too.' : pre ? await pre.running : together.has(call.id) ? await together.get(call.id) : !allowed(s, name) ? `error: the tool ${name} is not allowed here` : args ? await runTool(name, args, s, signal, call.id) : 'error: the tool arguments were not valid JSON')
1117
1211
  if (!refused && args) out += guard.after(name, args, out)
1118
1212
  if (guard.stuck) stuck ??= guard.stuck
1213
+ if (s.stuckSelf) (stuck ??= s.stuckSelf), (s.stuckSelf = null), s.stuckHandovers++ // it said so itself (todo stuck, a third time)
1119
1214
  if (args && !refused) {
1120
1215
  s.seq++
1121
1216
  if (EDITS.has(name) && !failed(out)) {
@@ -1137,8 +1232,17 @@ async function runNative(s, task, images, signal) {
1137
1232
  if (++s.checksSince === 5 && (s.changed.size || s.isSub)) out += `\n\n${prompt('agent/enough-checks', { n: s.checksSince, choices: (s.chat?.choices ?? []).join('; ') })}`
1138
1233
  }
1139
1234
  }
1140
- if (name === 'run_command' && args && !refused) s.ran?.push({ command: String(args.command ?? ''), result: clip(String(out).split('\n').filter((l) => l.trim()).slice(0, 2).join(' · '), 160) })
1235
+ // what was run or checked, for the review and the wrap-up: commands, MCP tools (a browser), helpers, the language server
1236
+ const checked = !args || refused ? null : name === 'run_command' ? String(args.command ?? '') : name === 'mcp' ? `${args.server} · ${args.tool}` : name === 'agent' ? `helper: ${args.description ?? clip(String(args.prompt ?? ''), 60)}` : name === 'lsp' ? `language server: ${args.action} ${args.file ?? ''}` : null
1237
+ if (checked) s.ran?.push({ command: checked, result: clip(String(out).split('\n').filter((l) => l.trim()).slice(0, 2).join(' · '), 160) })
1141
1238
  if (!s.isSub && s.memory && !refused && args) await noteRun(s, name, args, out, signal).catch((e) => log('learn', `run note: ${e.message}`)) // learn from any run that failed then passed
1239
+ // a step it said it was stuck on, now done: what got it out is a lesson
1240
+ if (!s.isSub && s.memory && s.unstuck?.length) {
1241
+ const out = s.unstuck.splice(0)
1242
+ s.troubles = s.troubles.filter((t) => !out.some((u) => u.step === t.step)) // learned here: not again at the wrap-up
1243
+ s.unstuckLearned = true
1244
+ await learnFromFixes(s, out.map((u) => ({ error: `stuck on "${u.step}": ${u.why}`, context: 'general' })), signal, { task: s.task ?? '' }).catch((e) => log('learn', `unstuck: ${e.message}`))
1245
+ }
1142
1246
  // the same call again and again in a row (a weak model going round): told at the third, stopped at the fifth
1143
1247
  const sig = `${name} ${call.function.arguments}`
1144
1248
  inRow = sig === lastCall ? inRow + 1 : 1
@@ -1162,7 +1266,7 @@ async function runNative(s, task, images, signal) {
1162
1266
  const msg = { role: 'tool', tool_call_id: call.id, content: fitResult(s, name, out, s.chat.outputs?.[call.id]) }
1163
1267
  if (name === 'read_file' && args && !args.start_line && !args.end_line && !failed(out)) replaceCopy(s, args.path, msg)
1164
1268
  s.messages.push(msg)
1165
- s.onEvent?.({ type: 'tool', id: call.id, name, output: out })
1269
+ s.onEvent?.({ type: 'tool', id: call.id, name, output: out, model: `${client.provider}/${client.model}` })
1166
1270
  }
1167
1271
  if (s.userSaid.length) s.messages.push({ role: 'user', content: s.userSaid.splice(0).join('\n\n') }) // their own words, as they typed them
1168
1272
  trimOldResults(s)
@@ -1226,8 +1330,17 @@ export function newGuard() {
1226
1330
  if (repeats >= 10) g.stuck = 'kept making calls it had already made (10 repeats)' // going round, not finding anything new
1227
1331
  return prompt('agent/already-done', { result: was.out, circling: repeats >= 3 })
1228
1332
  }
1333
+ let sameTool = null // the tool (an MCP server's own tool by name) whose calls failed in a row
1334
+ let sameFails = 0
1229
1335
  g.after = (name, a, out) => {
1230
1336
  let note = ''
1337
+ // any other tool (a browser's wait, click…) failing again and again: told at the third to stop and think
1338
+ const tool = name === 'mcp' ? `${a.server} · ${a.tool}` : name
1339
+ if (name !== 'run_command') {
1340
+ sameFails = failed(out) ? (tool === sameTool ? sameFails + 1 : 1) : 0
1341
+ sameTool = tool
1342
+ if (sameFails === 3) note += `\n\n${prompt('agent/same-tool-failing', { tool })}`
1343
+ }
1231
1344
  if (name === 'run_command') {
1232
1345
  const code = Number(/^exit code (-?\d+)/.exec(out)?.[1] ?? 0)
1233
1346
  failing = code ? failing + 1 : 0
@@ -1276,7 +1389,8 @@ async function noteRun(s, name, args, out, signal) {
1276
1389
  // Turn each fixed mistake into one reusable rule and save it (global memory, tagged by the tool it came from). The
1277
1390
  // model writes the rule from the error; a near-duplicate lesson is skipped. Recall is automatic
1278
1391
  // (memory.relevant attaches matching notes to a later message).
1279
- async function learnFromFixes(s, fixed, signal) {
1392
+ // unsolved: it blocked a task that wasn't done (the rule: what to know or try first); task: what was asked (found by it later).
1393
+ async function learnFromFixes(s, fixed, signal, { unsolved = false, task = '' } = {}) {
1280
1394
  for (const { error, context } of fixed.slice(0, 5)) {
1281
1395
  const tags = [runTool_(context ?? error) || 'general'] // the tool it came from (npm, python3, cargo…)
1282
1396
  const near = s.memory.search(`tag:lesson ${tags.join(' ')}`).find((n) => n.body.toLowerCase().includes(error.replace(/^[^:]*:\s*/, '').toLowerCase().slice(0, 30)))
@@ -1288,7 +1402,7 @@ async function learnFromFixes(s, fixed, signal) {
1288
1402
  s.client.purpose = 'lesson'
1289
1403
  let reply
1290
1404
  try {
1291
- reply = await s.client.chat({ messages: [{ role: 'user', content: prompt('agent/lesson', { error }) }] }, { signal })
1405
+ reply = await s.client.chat({ messages: [{ role: 'user', content: prompt('agent/lesson', { error, unsolved, task: clip(task, 300) }) }] }, { signal })
1292
1406
  } finally {
1293
1407
  s.client.purpose = was
1294
1408
  }
@@ -1299,7 +1413,7 @@ async function learnFromFixes(s, fixed, signal) {
1299
1413
  if (e.name === 'AbortError') throw e
1300
1414
  }
1301
1415
  if (!rule || rule.length < 10) rule = error.replace(/^[^:]*:\s*/, '') // the model couldn't phrase it: keep the error's own wording
1302
- const name = s.memory.write({ description: rule, type: 'reference', tags: ['lesson', ...tags], content: `${rule}\n\nLearned on ${new Date().toISOString().slice(0, 10)} after this was caught and fixed while building: ${error}`, scope })
1416
+ const name = s.memory.write({ description: rule, type: 'reference', tags: ['lesson', ...tags], content: `${rule}\n\nLearned on ${new Date().toISOString().slice(0, 10)} ${unsolved ? 'after this blocked a task that was not done' : 'after this was caught and fixed'}${task ? ` (the task: ${clip(task, 200)})` : ' while building'}: ${error}`, scope })
1303
1417
  s.ui.step('learned', `${rule.slice(0, 90)}${scope === 'project' ? ' (this project)' : ''}`)
1304
1418
  log('learn', `saved lesson [[${name}]] (${scope}, #${tags.join(' #')}): ${rule}`)
1305
1419
  }
@@ -1311,7 +1425,14 @@ async function learnFromFixes(s, fixed, signal) {
1311
1425
  // The model said it would do something but stopped without doing it ("let me rewrite…", "I'll fix…"):
1312
1426
  // a next action named, then no tool call. Not matched by explanations ("let me explain", "you can run").
1313
1427
  const PROMISED_MORE =
1314
- /\b(?:let me|i['’]?ll|i will|i['’]?m going to|i am going to|i need to|i['’]?m about to|next,? i['’]?ll|now,? i['’]?ll)\b[^.!?\n]{0,70}\b(?:do|make|create|add|fix|write|update|change|implement|build|run|rewrite|replace|edit|install|set ?up|finish|continue|proceed|start|redo|retry|try|hand|pass|send|give)\b/i
1428
+ /\b(?:let me|let['’]?s|let us|i['’]?ll|i will|i['’]?m going to|i am going to|i need to|i['’]?m about to|next,? i['’]?ll|now,? i['’]?ll)\b[^.!?\n]{0,70}\b(?:do|make|create|add|fix|write|update|change|implement|build|run|rewrite|replace|edit|install|set ?up|finish|continue|proceed|start|redo|retry|try|hand|pass|send|give|use|open|navigate|click|solve)\b/i
1429
+
1430
+ // The start of a final answer saying it didn't manage: "I couldn't…", "unable to…", "still showing…".
1431
+ const SAYS_FAILED = /\b(?:could ?n['’]?t|could not|was(?: not|n['’]?t) able to|(?:am|was|i['’]m) unable to|failed to|did(?: not|n['’]?t) (?:manage|succeed|work|load|pass)|not (?:yet )?(?:complete[d]?|finished|solved|possible|loaded)|still (?:in progress|pending|blocked|loading|stuck|showing|failing|not)|has not (?:yet )?(?:complet|finish|load|pass))/i
1432
+
1433
+ // "I can't browse the web", "I'm unable to run commands", "I don't have access to…": a model
1434
+ // saying it lacks an ability (it has tools for it).
1435
+ const CANT = /\b(?:i\s*(?:['’]m|am)\s*(?:unable|not able)\s*to|i\s*(?:can(?:['’]?t| ?not)|do(?:n['’]?t| not))\s*(?:directly\s*)?(?:have\s*(?:the\s*)?(?:ability|access|capabilit|tools?)|browse|access|open|visit|view|see|interact|click|navigate|run|execute|take|solve|use|control))|\bas an ai\b/i
1315
1436
 
1316
1437
  // Is the task really done, or did the model stop early? Open todo items, or (after it did real work)
1317
1438
  // a reply that only promises more, get one nudge to keep going. Then any Stop hook. null = truly done.
@@ -1415,8 +1536,12 @@ const isEmptyDir = (abs) => {
1415
1536
  // a NO goes back to the model to fix. Asked again only once files changed since its last look.
1416
1537
  // Returns what to tell the model, or null.
1417
1538
  export async function review(s, task, answer, signal) {
1418
- if (s.isSub || !s.changed?.size || s.lastChangeAt <= s.reviewedAt || s.ui.permission === 'plan') return null
1539
+ // no files changed, but it ran things to do the task (a browser, commands, helpers): its answer is
1540
+ // checked against the request too (once per new batch of them)
1541
+ const acted = !s.changed?.size && (s.ran?.length ?? 0) > (s.reviewedRan ?? 0)
1542
+ if (s.isSub || s.ui.permission === 'plan' || (!acted && (!s.changed?.size || s.lastChangeAt <= s.reviewedAt))) return null
1419
1543
  s.reviewedAt = s.lastChangeAt
1544
+ s.reviewedRan = s.ran?.length ?? 0
1420
1545
  const turn = s.chat.turns.at(-1)
1421
1546
  const diffs = []
1422
1547
  let room = 16_000
@@ -1437,14 +1562,15 @@ export async function review(s, task, answer, signal) {
1437
1562
  break
1438
1563
  }
1439
1564
  }
1440
- if (!diffs.length) return null
1565
+ if (!diffs.length && !acted) return null
1566
+ if (!diffs.length) diffs.push('(no files changed)')
1441
1567
  const plan = (s.chat.todos ?? []).map((t) => `- [${t.status === 'completed' ? 'x' : ' '}] ${t.content}`).join('\n')
1442
1568
  const ran = (s.ran ?? []).slice(-15).map((r) => `- ${clip(r.command.replace(/\s+/g, ' '), 160)} → ${r.result}`).join('\n')
1443
1569
  const ask = prompt('agent/review', { request: requestsOf(s.chat, 1200), emphasis: (s.chat?.choices ?? []).join('; '), plan: plan || '(none)', answer: clip(String(answer ?? ''), 3000), changes: diffs.join('\n\n'), ran: ran || '(nothing)' })
1444
1570
  const self = { provider: s.client.provider, model: s.client.model, self: true }
1445
1571
  const others = (s.team?.() ?? []).filter((t) => t.tools !== false && !(t.provider === self.provider && t.model === self.model))
1446
1572
  const reviewers = others.filter((t) => t.jobs?.includes('code')).sort((a, b) => Boolean(b.thinking) - Boolean(a.thinking)) // ticked for Code & logic on Your models, the thinking ones first
1447
- const team = reviewers.length ? reviewers : others // else your next two, in your order
1573
+ const team = [...reviewers, ...others.filter((t) => !reviewers.includes(t))] // then your others, in your order (two at most, then this one)
1448
1574
  for (const t of [...team.slice(0, 2), self]) {
1449
1575
  s.ui.spinner(`${t.model} is reviewing the work`)
1450
1576
  try {
@@ -1461,11 +1587,15 @@ export async function review(s, task, answer, signal) {
1461
1587
  s.ui.stopSpin()
1462
1588
  log('review', `${t.model}: ${said}`)
1463
1589
  if (/^\W*yes\b/i.test(said)) {
1590
+ s.lastReview = { verdict: 'yes' }
1591
+ s.ui.event?.({ subtype: 'review', model: `${t.provider}/${t.model}`, verdict: 'yes', issues: '' })
1464
1592
  s.ui.step('review', `${t.model}: looks right`)
1465
1593
  return null
1466
1594
  }
1467
1595
  if (/^\W*no\b/i.test(said)) {
1468
1596
  const issues = said.replace(/^\W*no\b[\s.:—-]*/i, '').trim()
1597
+ s.lastReview = { verdict: 'no', issues }
1598
+ s.ui.event?.({ subtype: 'review', model: `${t.provider}/${t.model}`, verdict: 'no', issues })
1469
1599
  s.ui.step('review', `${t.model}: ${clip(issues.split('\n').find((l) => l.trim()) ?? 'problems found', 90)}`)
1470
1600
  return prompt('agent/review-failed', { model: t.model, issues: issues || '(no details given)' })
1471
1601
  }
@@ -1491,7 +1621,8 @@ const lineCount = (out) => {
1491
1621
  // Questions to the user (confirm, pick, ask) wait their turn: helpers working at once ask one by one.
1492
1622
  const asking = new WeakMap() // ui → the question being asked
1493
1623
  const streaming = new WeakMap() // ui → helper replies coming in now (only one: its thinking is shown as it comes)
1494
- function helperUI(ui, label) {
1624
+ // model: the helper's, named on each of its steps
1625
+ function helperUI(ui, label, model) {
1495
1626
  // What the helper says is shown in full under its name. Its thinking is shown as it comes, like the
1496
1627
  // conversation's; with other helpers replying at the
1497
1628
  // same time, held until its reply ends, then printed at once (two streams would interleave).
@@ -1526,7 +1657,7 @@ function helperUI(ui, label) {
1526
1657
  // what it's doing, for the line per helper under the spinner (ui.helpers: full screen only)
1527
1658
  const status = (text) => {
1528
1659
  if (!ui.helpers?.has(label)) return
1529
- ui.helpers.set(label, clip(String(text), 60))
1660
+ ui.helpers.set(label, { ...ui.helpers.get(label), what: clip(String(text), 60) })
1530
1661
  ui.render?.()
1531
1662
  }
1532
1663
  const own = {
@@ -1534,7 +1665,7 @@ function helperUI(ui, label) {
1534
1665
  step: (name, detail = '') => {
1535
1666
  if (ui.afterBlock) ui.gap()
1536
1667
  ui.afterBlock = false
1537
- ui.print(` ${c.accent('●')} ${c.accent(c.bold(`${label} › ${name}`))} ${c.info(detail)}`)
1668
+ ui.print(` ${c.accent('●')} ${c.accent(c.bold(`${label} › ${name}`))} ${c.info(detail)}${model ? c.faint(` · ${model}`) : ''}`)
1538
1669
  status(`${name} ${detail}`)
1539
1670
  },
1540
1671
  result: (text) => ui.print(` ${c.ghost('⎿')} ${c.faint(text)}`),
@@ -1675,14 +1806,14 @@ export function contextReport(s) {
1675
1806
  const text = typeof m.content === 'string' ? m.content : (m.content ?? []).map((p) => p.text ?? '').join(' ')
1676
1807
  const yours = tasks.some((t) => text.startsWith(t))
1677
1808
  yours ? (parts.you += n) : (parts.notes += n)
1678
- pieces.push({ tokens: n, what: yours ? `your message "${clip(text.split('\n')[0], 50)}"` : `a note to the model "${clip(text.split('\n')[0], 50)}"`, ago })
1809
+ pieces.push({ tokens: n, what: yours ? `a typed message "${clip(text.split('\n')[0], 50)}"` : `a note to the model "${clip(text.split('\n')[0], 50)}"`, ago })
1679
1810
  }
1680
1811
  })
1681
1812
  const toolTokens = tok(tools.map((f) => ({ type: 'function', function: f })))
1682
1813
  const list = [
1683
1814
  { name: 'system prompt', tokens: parts.system },
1684
1815
  { name: `tools (${tools.length})`, tokens: toolTokens },
1685
- { name: 'your messages', tokens: parts.you },
1816
+ { name: 'typed messages', tokens: parts.you },
1686
1817
  { name: 'notes to the model', tokens: parts.notes, note: 'summaries, guides, reminders, saved notes found' },
1687
1818
  { name: 'model replies', tokens: parts.replies },
1688
1819
  { name: 'tool results', tokens: parts.results, note: `${whole} whole` },
@@ -33,7 +33,7 @@ export function capabilities(cfg = {}) {
33
33
  else if (/whisper-cli/.test(vp)) need = 'whisper (whisper-cli) and a model — or a transcription provider'
34
34
  else need = 'a whisper model — or a transcription provider'
35
35
  }
36
- caps.push({ id: 'voice', name: 'Voice input', what: 'Dictate your message — Space in an empty box, or /voice.', ok: !vp, need })
36
+ caps.push({ id: 'voice', name: 'Voice input', what: 'Dictate a message — Space in an empty box, or /voice.', ok: !vp, need })
37
37
  const chrome = chromeHere()
38
38
  const npx = onPath('npx')
39
39
  caps.push({
package/src/client.js CHANGED
@@ -175,6 +175,13 @@ export function fitFor(messages, can, model) {
175
175
  // usage in a stream, the thinking sent back, the tools' full schemas, images.
176
176
  export const QUIRKS = ['noTemperature', 'noEffort', 'noThoughts', 'noStreamUsage', 'noReasoningBack', 'simpleSchemas', 'noImages', 'noParallel']
177
177
 
178
+ // A model's name without its version: its date, "latest", "preview" ("mistral-large-2411" → "mistral-large").
179
+ export const family = (m) => {
180
+ let f = String(m).split('/').pop().toLowerCase()
181
+ for (let was; was !== f; ) (was = f), (f = f.replace(/[-_:@.]?(latest|preview|exp|\d{4}(-\d{2}){0,2}|\d{6,8})$/, ''))
182
+ return f
183
+ }
184
+
178
185
  export class Client {
179
186
  constructor({ baseUrl, apiKey, model, provider, timeout = 600_000 } = {}) {
180
187
  this.provider = provider // its name in config.json, for the requests log
@@ -220,9 +227,24 @@ export class Client {
220
227
  }
221
228
  // The model in use answers but gives nothing usable (agent.js: empty replies, again and again):
222
229
  // the next one in the list takes over. False when there's no list.
223
- moveOn(why) {
230
+ // Another version of the same model (voxtral-small-latest → voxtral-small-2507) would likely do the
231
+ // same: skipped for the next one in your order, while there is one.
232
+ // avoid: models ("provider/model") given up on already (this message): not gone back to; false when
233
+ // every other model is one of them.
234
+ moveOn(why, avoid = new Set()) {
224
235
  if (!this.rotation) return false
225
- this.#next(why)
236
+ const r = this.rotation
237
+ const n = r.list.length
238
+ const was = family(r.list[r.at].model)
239
+ const ok = (t) => !avoid.has(`${t.provider}/${t.model}`) && t !== r.list[r.at]
240
+ let k = 1
241
+ while (k < n && (family(r.list[(r.at + k) % n].model) === was || !ok(r.list[(r.at + k) % n]))) k++
242
+ if (k === n) { // only versions of this model (or ones given up on) left: the first of those not given up on
243
+ k = 1
244
+ while (k < n && !ok(r.list[(r.at + k) % n])) k++
245
+ if (k === n) return false
246
+ }
247
+ this.#next(why, () => (r.at + k) % n)
226
248
  return true
227
249
  }
228
250
  #next(why, pick) {
@@ -353,15 +375,15 @@ export class Client {
353
375
  return (await this.#fetch(url, init, { timeout })).json()
354
376
  }
355
377
 
356
- async listModels(timeout = 10_000) {
378
+ async listModels(timeout = 60_000) {
357
379
  return (await this.modelEntries(timeout)).map((m) => m.id ?? m.name)
358
380
  }
359
381
  // The server's own entries for its models ({ id, owned_by, context_length, pricing… }, as it sends them).
360
- async modelEntries(timeout = 10_000) {
382
+ async modelEntries(timeout = 60_000) {
361
383
  const data = await this.#json(this.baseUrl + '/models', undefined, timeout)
362
384
  // { result: [...] } (Cloudflare's shape): there the id is an internal one and the name is the model's
363
385
  if (Array.isArray(data.result)) return data.result.filter((m) => m?.name).map((m) => ({ ...m, id: m.name }))
364
- return (data.data ?? data.models ?? []).filter((m) => m && (m.id ?? m.name))
386
+ return (Array.isArray(data) ? data : (data.data ?? data.models ?? [])).filter((m) => m && (m.id ?? m.name)) // a bare list too (Typhoon)
365
387
  }
366
388
 
367
389
  // Best effort: asks the server how big the loaded context window is.
@@ -397,7 +419,7 @@ export class Client {
397
419
  },
398
420
  async () => {
399
421
  const d = await this.#json(this.baseUrl + '/models')
400
- const m = (d.data ?? d.models ?? []).find((x) => x.id === this.model || x.name === this.model)
422
+ const m = (Array.isArray(d) ? d : (d.data ?? d.models ?? [])).find((x) => x.id === this.model || x.name === this.model)
401
423
  return { size: n(windowOf(m)), server: m?.owned_by === 'vllm' || m?.max_model_len ? 'vllm' : null }
402
424
  },
403
425
  async () => ({ size: n(windowOf(await this.#json(`${this.baseUrl}/models/${encodeURIComponent(this.model)}`))), server: null }),
@@ -444,7 +466,7 @@ export class Client {
444
466
  return text
445
467
  }
446
468
  })()
447
- return { error: `${res.status}: ${String(why).slice(0, 300)}${said?.rate ? ' (a per-minute cap on your account, not the window)' : ''}` }
469
+ return { error: `${res.status}: ${String(why).slice(0, 300)}${said?.rate ? ' (a per-minute cap on the account, not the window)' : ''}` }
448
470
  }
449
471
 
450
472
  // Returns { content, reasoning, toolCalls, usage, finishReason, thinking }.
@@ -654,6 +676,7 @@ export class Client {
654
676
  let thought = ''
655
677
  let usage
656
678
  let finishReason
679
+ let sawDone = false
657
680
  const calls = []
658
681
  let raw = '' // the stream as it came (its start), kept for a reply that turns out empty
659
682
  // A reply going round (a small model repeating itself, which could fill the window): checked
@@ -682,8 +705,7 @@ export class Client {
682
705
  }
683
706
  poke()
684
707
  firstAt ??= Date.now()
685
- if (end) break
686
- buf += dec.decode(value, { stream: true })
708
+ buf += end ? dec.decode() + '\n' : dec.decode(value, { stream: true }) // the end: its last line too, even without a line break after it
687
709
  let nl
688
710
  while ((nl = buf.indexOf('\n')) !== -1) {
689
711
  const line = buf.slice(0, nl).trim()
@@ -691,7 +713,10 @@ export class Client {
691
713
  if (raw.length < 100_000 && line) raw += line + '\n'
692
714
  if (!line.startsWith('data:')) continue
693
715
  const payload = line.slice(5).trim()
694
- if (payload === '[DONE]') continue
716
+ if (payload === '[DONE]') {
717
+ sawDone = true
718
+ continue
719
+ }
695
720
  let chunk
696
721
  try {
697
722
  chunk = JSON.parse(payload)
@@ -749,6 +774,12 @@ export class Client {
749
774
  await reader.cancel().catch(() => {}) // the server stops generating
750
775
  break
751
776
  }
777
+ if (end) break
778
+ }
779
+ // closed with neither [DONE] nor a reason it ended: the connection ended early, the reply may be cut
780
+ if (!looped && !sawDone && !finishReason) {
781
+ finishReason = 'incomplete'
782
+ log('reply', `${this.model}: the stream ended without [DONE] or a finish reason: the reply may be cut off`)
752
783
  }
753
784
  clearTimeout(timer), started()
754
785
  if (looped) {