ucode-agent 1.0.0

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.
@@ -0,0 +1,740 @@
1
+ /**
2
+ * provider.js — the only module that knows a model provider exists.
3
+ *
4
+ * Everything above this file speaks one small neutral message format and calls
5
+ * ask(). Moving ucode to a different host means rewriting this file and
6
+ * nothing else.
7
+ *
8
+ * The neutral formats:
9
+ * { role: 'system', content }
10
+ * { role: 'user', content, images?: [dataUrl] }
11
+ * { role: 'assistant', content?, toolCalls?: [{ id, name, args }] }
12
+ * { role: 'tool', toolCallId, name, content }
13
+ *
14
+ * tool: { name, description, parameters: <JSON Schema> }
15
+ *
16
+ * ask() resolves to:
17
+ * { text, reasoning, toolCalls, usage, finishReason, model }
18
+ */
19
+
20
+ import { join, dirname } from 'node:path';
21
+ import { homedir } from 'node:os';
22
+ import { fileURLToPath } from 'node:url';
23
+ import dotenv from 'dotenv';
24
+ import OpenAI from 'openai';
25
+ import { Failure } from './failure.js';
26
+
27
+ const HERE = dirname(fileURLToPath(import.meta.url));
28
+ const PACKAGE_ROOT = join(HERE, '..', '..');
29
+
30
+ /** Personal config lives here, outside the package, so upgrades never touch it. */
31
+ export const UCODE_HOME = join(homedir(), '.ucode');
32
+ export const ENV_FILE = join(UCODE_HOME, '.env');
33
+
34
+ export const BASE_URL = 'https://openrouter.ai/api/v1';
35
+ export const PROVIDER = 'OpenRouter';
36
+
37
+ // First definition wins — dotenv never overwrites a variable that already
38
+ // exists — so the order here is the precedence order:
39
+ // real environment > ./.env (this project) > ~/.ucode/.env (this machine)
40
+ // > the checkout's own .env (only when developing on a clone)
41
+ dotenv.config({ path: join(process.cwd(), '.env'), quiet: true });
42
+ dotenv.config({ path: ENV_FILE, quiet: true });
43
+ dotenv.config({ path: join(PACKAGE_ROOT, '.env'), quiet: true });
44
+
45
+ /**
46
+ * The whole model list. Not a starting point — the list.
47
+ *
48
+ * ucode runs on NVIDIA and Cohere only. Both vendors serve genuinely capable
49
+ * models free through OpenRouter, both handle tool calling properly, and
50
+ * keeping the set to five means every one of them has been used in anger
51
+ * rather than listed on the strength of a benchmark. A picker offering sixty
52
+ * models is a picker nobody reads.
53
+ *
54
+ * `name` is what the status bar shows. `note` is what the picker shows.
55
+ */
56
+ export const MODELS = {
57
+ 'nvidia/nemotron-3-ultra-550b-a55b:free': {
58
+ name: 'Nemotron 3 Ultra (free)',
59
+ context: 1_000_000,
60
+ star: true,
61
+ note: 'deepest reasoning, 1M context — the default',
62
+ },
63
+ 'nvidia/nemotron-3.5-lightning:free': {
64
+ name: 'Nemotron 3.5 Lightning (free)',
65
+ context: 1_000_000,
66
+ note: 'same huge window, answers much sooner',
67
+ },
68
+ 'nvidia/nemotron-3-super-120b-a12b:free': {
69
+ name: 'Nemotron 3 Super (free)',
70
+ context: 262_144,
71
+ note: 'strong all-rounder, quick to first token',
72
+ },
73
+ 'nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free': {
74
+ name: 'Nemotron 3 Nano Omni (free)',
75
+ context: 256_000,
76
+ note: 'small and fast, reasoning tuned',
77
+ },
78
+ 'cohere/north-mini-code:free': {
79
+ name: 'North Mini Code (free)',
80
+ context: 256_000,
81
+ star: true,
82
+ note: 'code and UI specialist — reach for it on frontend work',
83
+ },
84
+ };
85
+
86
+ /**
87
+ * Nemotron 3 Ultra is the default because the work ucode is for — read a
88
+ * codebase, hold it in mind, change several files consistently — is exactly
89
+ * what a million-token window and a long think buy you. It is slower to the
90
+ * first token than the others and that is the trade being made. /model swaps
91
+ * to Lightning or North Mini Code when the wait stops being worth it.
92
+ */
93
+ export const DEFAULT_MODEL = 'nvidia/nemotron-3-ultra-550b-a55b:free';
94
+
95
+ let current = process.env.UCODE_MODEL || DEFAULT_MODEL;
96
+ let client = null;
97
+
98
+ export function model() {
99
+ return current;
100
+ }
101
+
102
+ export function setModel(id) {
103
+ const wanted = String(id ?? '').trim();
104
+ if (!wanted) {
105
+ throw new Failure({
106
+ kind: 'bad_model',
107
+ attempted: 'switching model',
108
+ failed: 'No model name was given.',
109
+ fix: `Pick one of: ${Object.keys(MODELS).join(', ')}`,
110
+ });
111
+ }
112
+ if (!MODELS[wanted]) {
113
+ throw new Failure({
114
+ kind: 'bad_model',
115
+ attempted: `switching to "${wanted}"`,
116
+ failed: 'ucode only runs NVIDIA and Cohere models, and that is not one of them.',
117
+ fix: `Run /model to choose from: ${Object.keys(MODELS).join(', ')}`,
118
+ });
119
+ }
120
+ current = wanted;
121
+ return current;
122
+ }
123
+
124
+ /** The short name for a model id: "Nemotron 3 Ultra (free)". */
125
+ export function modelName(id = current) {
126
+ return MODELS[id]?.name ?? id;
127
+ }
128
+
129
+ /** Every model, in list order, annotated with whether it is the active one. */
130
+ export function modelList() {
131
+ return Object.entries(MODELS).map(([id, info]) => ({
132
+ id,
133
+ ...info,
134
+ active: id === current,
135
+ }));
136
+ }
137
+
138
+ /**
139
+ * How many tokens one request may occupy.
140
+ *
141
+ * OpenRouter meters requests rather than tokens, so nothing here is rationing
142
+ * a quota — the binding limit is simply the window the model has. On the two
143
+ * million-token models compaction essentially never fires.
144
+ */
145
+ export function contextLimit(id = current) {
146
+ const override = Number(process.env.UCODE_MAX_CONTEXT_TOKENS);
147
+ if (Number.isFinite(override) && override > 0) return override;
148
+ return MODELS[id]?.context ?? 128_000;
149
+ }
150
+
151
+ /**
152
+ * A rough local token count, used to decide when to compact *before* a
153
+ * request goes out. Real numbers come back in the response usage; this only
154
+ * has to be close enough to trigger at the right time.
155
+ */
156
+ export function estimateTokens(text) {
157
+ return text ? Math.ceil(String(text).length / 4) : 0;
158
+ }
159
+
160
+ export function estimateConversation(messages) {
161
+ let total = 0;
162
+ for (const m of messages) {
163
+ total += estimateTokens(m.content || '');
164
+ for (const call of m.toolCalls || []) {
165
+ total += estimateTokens(call.name) + estimateTokens(JSON.stringify(call.args || {}));
166
+ }
167
+ total += 4; // role and framing overhead per message
168
+ }
169
+ return total;
170
+ }
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // Client
174
+ // ---------------------------------------------------------------------------
175
+
176
+ /**
177
+ * No key is bundled here, and none ever should be. A key committed to a public
178
+ * package is readable by anyone who runs `npm pack ucode-agent`, and no amount
179
+ * of first-run convenience is worth handing out a live credential.
180
+ */
181
+ function apiKey() {
182
+ const key = (process.env.OPENROUTER_API_KEY ?? '').trim();
183
+ if (!key) {
184
+ throw new Failure({
185
+ kind: 'no_api_key',
186
+ attempted: 'connecting to OpenRouter',
187
+ failed: 'OPENROUTER_API_KEY is not set in the environment or in any .env file.',
188
+ fix:
189
+ `Put OPENROUTER_API_KEY=your-key in ${ENV_FILE} — that applies to every ` +
190
+ 'project on this machine — or in a .env file beside your code. ' +
191
+ 'Keys are free at https://openrouter.ai/keys',
192
+ });
193
+ }
194
+ return key;
195
+ }
196
+
197
+ function connection() {
198
+ if (client) return client;
199
+ client = new OpenAI({
200
+ apiKey: apiKey(),
201
+ baseURL: process.env.UCODE_BASE_URL || BASE_URL,
202
+ // Nemotron Ultra can think for a long time before its first token, so the
203
+ // ceiling is deliberately generous. maxRetries is 0 because ask() owns
204
+ // retrying: its attempts are narrated on screen instead of happening
205
+ // silently somewhere inside the SDK.
206
+ timeout: Number(process.env.UCODE_REQUEST_TIMEOUT_MS) || 300_000,
207
+ maxRetries: 0,
208
+ defaultHeaders: {
209
+ 'HTTP-Referer': 'https://github.com/sppideey/ucode-agent',
210
+ 'X-Title': 'ucode',
211
+ },
212
+ });
213
+ return client;
214
+ }
215
+
216
+ /** Drop the cached client so the next request picks up a changed key. */
217
+ export function resetConnection() {
218
+ client = null;
219
+ }
220
+
221
+ // ---------------------------------------------------------------------------
222
+ // Live quota, taken from whatever rate-limit headers come back
223
+ // ---------------------------------------------------------------------------
224
+
225
+ let limits = null;
226
+
227
+ export function rateLimits() {
228
+ return limits;
229
+ }
230
+
231
+ /** "1.5s", "2m59.56s", "1h2m" -> seconds */
232
+ function seconds(value) {
233
+ if (!value) return null;
234
+ const m = /^(?:(\d+(?:\.\d+)?)h)?(?:(\d+(?:\.\d+)?)m(?!s))?(?:(\d+(?:\.\d+)?)m?s)?$/
235
+ .exec(String(value).trim());
236
+ if (!m) return null;
237
+ const total = (parseFloat(m[1]) || 0) * 3600 + (parseFloat(m[2]) || 0) * 60 + (parseFloat(m[3]) || 0);
238
+ return total > 0 ? total : null;
239
+ }
240
+
241
+ function noteLimits(headers) {
242
+ if (!headers?.get) return;
243
+ const num = (name) => {
244
+ const n = Number(headers.get(name));
245
+ return Number.isFinite(n) ? n : null;
246
+ };
247
+ limits = {
248
+ requestsLimit: num('x-ratelimit-limit-requests'),
249
+ requestsRemaining: num('x-ratelimit-remaining-requests'),
250
+ requestsReset: seconds(headers.get('x-ratelimit-reset-requests')),
251
+ tokensLimit: num('x-ratelimit-limit-tokens'),
252
+ tokensRemaining: num('x-ratelimit-remaining-tokens'),
253
+ tokensReset: seconds(headers.get('x-ratelimit-reset-tokens')),
254
+ at: Date.now(),
255
+ };
256
+ }
257
+
258
+ // ---------------------------------------------------------------------------
259
+ // Neutral format -> wire format
260
+ // ---------------------------------------------------------------------------
261
+
262
+ function wireTools(tools) {
263
+ if (!tools?.length) return undefined;
264
+ return tools.map((t) => ({
265
+ type: 'function',
266
+ function: {
267
+ name: t.name,
268
+ description: t.description,
269
+ parameters: t.parameters ?? { type: 'object', properties: {} },
270
+ },
271
+ }));
272
+ }
273
+
274
+ function wireMessages(messages) {
275
+ const out = [];
276
+ for (const m of messages) {
277
+ if (m.role === 'user' && m.images?.length) {
278
+ out.push({
279
+ role: 'user',
280
+ content: [
281
+ { type: 'text', text: m.content ?? '' },
282
+ ...m.images.map((url) => ({ type: 'image_url', image_url: { url } })),
283
+ ],
284
+ });
285
+ } else if (m.role === 'system' || m.role === 'user') {
286
+ out.push({ role: m.role, content: m.content ?? '' });
287
+ } else if (m.role === 'assistant') {
288
+ const wire = { role: 'assistant', content: m.content || '' };
289
+ if (m.toolCalls?.length) {
290
+ wire.tool_calls = m.toolCalls.map((c) => ({
291
+ id: c.id,
292
+ type: 'function',
293
+ function: { name: c.name, arguments: JSON.stringify(c.args ?? {}) },
294
+ }));
295
+ }
296
+ out.push(wire);
297
+ } else if (m.role === 'tool') {
298
+ out.push({ role: 'tool', tool_call_id: m.toolCallId, content: m.content ?? '' });
299
+ }
300
+ }
301
+ return out;
302
+ }
303
+
304
+ // ---------------------------------------------------------------------------
305
+ // Turning provider errors into something a person can act on
306
+ // ---------------------------------------------------------------------------
307
+
308
+ function bodyOf(err) {
309
+ if (err?.error) return { error: err.error };
310
+ const raw = String(err?.message ?? '');
311
+ const start = raw.indexOf('{');
312
+ if (start === -1) return null;
313
+ try {
314
+ return JSON.parse(raw.slice(start));
315
+ } catch {
316
+ return null;
317
+ }
318
+ }
319
+
320
+ export function explain(err, id) {
321
+ if (err instanceof Failure) return err;
322
+
323
+ const status = err?.status ?? err?.statusCode ?? null;
324
+ const body = bodyOf(err);
325
+ const detail = body?.error?.message ?? String(err?.message ?? err);
326
+ const attempted = `asking ${modelName(id)} for a reply`;
327
+
328
+ // The useful text is often not on the error itself. undici reports a socket
329
+ // that closed mid-response as a bare `TypeError: terminated` and puts the
330
+ // real reason on `cause`, so the whole chain is matched rather than the top
331
+ // message alone — otherwise an ordinary dropped connection, which is worth
332
+ // retrying, gets reported as an unknown fault, which is not.
333
+ const chain = [err?.message, err?.code, err?.cause?.message, err?.cause?.code]
334
+ .filter(Boolean)
335
+ .join(' | ');
336
+ const raw = chain || String(err);
337
+
338
+ if (err?.name === 'AbortError' || /aborted|The operation was aborted/i.test(raw)) {
339
+ return new Failure({
340
+ kind: 'aborted',
341
+ attempted,
342
+ failed: 'The request was cancelled.',
343
+ fix: 'Send the message again when you are ready.',
344
+ cause: err,
345
+ });
346
+ }
347
+
348
+ if (status === 401 || status === 403 || /invalid[_ ]api[_ ]key/i.test(raw)) {
349
+ return new Failure({
350
+ kind: 'invalid_api_key',
351
+ attempted,
352
+ failed: `OpenRouter rejected the API key (HTTP ${status ?? 401}).`,
353
+ fix:
354
+ 'Check OPENROUTER_API_KEY for a typo or trailing space, and confirm the key ' +
355
+ 'is still active at https://openrouter.ai/keys',
356
+ cause: err,
357
+ });
358
+ }
359
+
360
+ if (status === 429 || /rate[_ ]limit/i.test(raw)) {
361
+ // `??` cannot be used to chain through Number(): Number(undefined) is NaN,
362
+ // which is neither null nor undefined, so it would swallow every fallback
363
+ // after it and the wait would silently never be found.
364
+ const header = err?.headers?.get?.('retry-after');
365
+ const asNumber = Number(header);
366
+ const retryAfter =
367
+ seconds(header) ??
368
+ (Number.isFinite(asNumber) && asNumber > 0 ? asNumber : null) ??
369
+ seconds(/try again in ([\dhms.]+)/i.exec(detail)?.[1]) ??
370
+ null;
371
+ const daily = /per day|RPD|TPD|tokens per day/i.test(detail);
372
+ const wait = Number.isFinite(retryAfter) && retryAfter
373
+ ? (retryAfter >= 60 ? `${Math.ceil(retryAfter / 60)} min` : `${Math.ceil(retryAfter)}s`)
374
+ : null;
375
+
376
+ return new Failure({
377
+ kind: 'rate_limit',
378
+ attempted,
379
+ failed: daily
380
+ ? `The free daily request cap for ${modelName(id)} is used up.`
381
+ : `Too many requests for ${modelName(id)} just now${wait ? ` — clear in ${wait}` : ''}.`,
382
+ fix: daily
383
+ ? 'Free caps reset each day. /model switches to another one, or add credit at ' +
384
+ 'https://openrouter.ai/credits to lift the ceiling.'
385
+ : 'ucode waits these out on its own. Free endpoints are shared, so it usually ' +
386
+ 'clears in seconds; /model moves to a quieter one.',
387
+ detail: { retryAfter, daily },
388
+ cause: err,
389
+ });
390
+ }
391
+
392
+ // A 404 on a model in this list is almost never a bad name. It is OpenRouter
393
+ // having no upstream free to serve it at that instant, and it clears by
394
+ // itself — so it is retried rather than reported as a missing model.
395
+ if (status === 404 || /does not exist|not found|decommissioned/i.test(raw)) {
396
+ if (MODELS[id]) {
397
+ return new Failure({
398
+ kind: 'server',
399
+ attempted,
400
+ failed: `No provider was free to serve ${modelName(id)} at that moment.`,
401
+ fix: 'ucode retries this by itself. If it keeps up, /model switches.',
402
+ detail: { status },
403
+ cause: err,
404
+ });
405
+ }
406
+ return new Failure({
407
+ kind: 'bad_model',
408
+ attempted,
409
+ failed: `OpenRouter has no model "${id}" available to this key.`,
410
+ fix: `Run /model. ucode ships with: ${Object.keys(MODELS).join(', ')}`,
411
+ cause: err,
412
+ });
413
+ }
414
+
415
+ // Some upstreams validate tool calls themselves and reject an invented one,
416
+ // which fails the whole request. Recoverable: the loop feeds this back.
417
+ if (body?.error?.code === 'tool_use_failed' || /tool call validation failed/i.test(detail)) {
418
+ const attemptedName = /call tool '([^']+)'/.exec(detail)?.[1];
419
+ return new Failure({
420
+ kind: 'bad_tool_call',
421
+ attempted,
422
+ failed: attemptedName
423
+ ? `The model tried to call "${attemptedName}", which is not one of its tools.`
424
+ : `The model produced a tool call the provider rejected: ${detail}`,
425
+ fix: 'Use only the tools supplied with the request.',
426
+ detail: { attemptedName },
427
+ cause: err,
428
+ });
429
+ }
430
+
431
+ if (status === 400) {
432
+ const noTools = /tool calling.*not supported/i.test(detail);
433
+ return new Failure({
434
+ kind: noTools ? 'no_tool_support' : 'bad_request',
435
+ attempted,
436
+ failed: noTools
437
+ ? `${modelName(id)} cannot call tools, which ucode needs for every task.`
438
+ : `OpenRouter rejected the request as malformed (HTTP 400): ${detail}`,
439
+ fix: noTools
440
+ ? 'Run /model and pick another one.'
441
+ : 'Usually an oversized conversation. /new starts a fresh one.',
442
+ cause: err,
443
+ });
444
+ }
445
+
446
+ if (status === 413 || /too large|context.*length/i.test(detail)) {
447
+ return new Failure({
448
+ kind: 'too_large',
449
+ attempted,
450
+ failed: `The conversation no longer fits in ${modelName(id)}: ${detail}`,
451
+ fix: 'Run /new for a fresh session, or lower UCODE_MAX_CONTEXT_TOKENS so ucode folds older turns away sooner.',
452
+ cause: err,
453
+ });
454
+ }
455
+
456
+ // OpenRouter drops a request when the upstream goes quiet on it. That is the
457
+ // ordinary failure mode of a busy free endpoint, and of a big reasoning model
458
+ // that spends a long time thinking before its first token. Nothing was
459
+ // generated, so retrying is safe — and ask() does it before anyone notices.
460
+ if (
461
+ status === 408 || status === 504 || status === 524 || status === 522 ||
462
+ err?.name === 'APIConnectionTimeoutError' ||
463
+ /idle timeout|timed out|timeout/i.test(detail) || /idle timeout|timed out/i.test(raw)
464
+ ) {
465
+ return new Failure({
466
+ kind: 'timeout',
467
+ attempted,
468
+ failed: `${modelName(id)} sent nothing back in time — the provider dropped the request.`,
469
+ fix:
470
+ 'Free endpoints stall under load, and the largest reasoning models are the ' +
471
+ 'first to. ucode already retried. If it keeps happening, /model to Nemotron ' +
472
+ '3.5 Lightning or North Mini Code, which answer sooner.',
473
+ detail: { status },
474
+ cause: err,
475
+ });
476
+ }
477
+
478
+ if (status >= 500 || /internal|unavailable|overloaded/i.test(raw)) {
479
+ return new Failure({
480
+ kind: 'server',
481
+ attempted,
482
+ failed: `The provider returned HTTP ${status}. That is their side, not yours.`,
483
+ fix: 'Wait a few seconds and send again. If it persists, /model to another one.',
484
+ cause: err,
485
+ });
486
+ }
487
+
488
+ // `terminated` and `premature close` are what a connection dropped part way
489
+ // through a reply looks like. Nothing usable arrived, so it is safe to send
490
+ // again — and on a free endpoint under load it happens often enough that
491
+ // treating it as fatal would be the single most visible flaw in the agent.
492
+ if (
493
+ /ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|ETIMEDOUT|EPIPE|network|fetch failed|socket hang up|terminated|premature close|other side closed|UND_ERR/i.test(raw) ||
494
+ err?.name === 'APIConnectionError' ||
495
+ (err instanceof TypeError && /terminated/i.test(raw))
496
+ ) {
497
+ return new Failure({
498
+ kind: 'network',
499
+ attempted,
500
+ failed: `The connection to OpenRouter dropped: ${raw}`,
501
+ fix:
502
+ 'ucode retries this by itself. If it keeps happening, check your connection, ' +
503
+ 'VPN and any corporate proxy (HTTPS_PROXY) — or /model to a lighter one, since ' +
504
+ 'a long think on a busy free endpoint is the usual cause.',
505
+ cause: err,
506
+ });
507
+ }
508
+
509
+ return new Failure({
510
+ kind: 'unknown',
511
+ attempted,
512
+ failed: detail,
513
+ fix: 'Retry once. If it repeats, run ucode --debug for the full trace.',
514
+ cause: err,
515
+ });
516
+ }
517
+
518
+ const pause = (ms) => new Promise((r) => setTimeout(r, ms));
519
+
520
+ // ---------------------------------------------------------------------------
521
+ // The one call
522
+ // ---------------------------------------------------------------------------
523
+
524
+ /**
525
+ * Send a conversation and get a normalized reply.
526
+ *
527
+ * @param {Array} messages neutral messages
528
+ * @param {Array} [tools] neutral tool definitions
529
+ * @param {object} [opts] { model, temperature, signal, maxOutputTokens,
530
+ * onText, onThinking, onWait }
531
+ */
532
+ export async function ask(messages, tools = [], opts = {}) {
533
+ const id = opts.model || current;
534
+
535
+ const request = {
536
+ model: id,
537
+ messages: wireMessages(messages),
538
+ // Ask for the working. Without it OpenRouter withholds reasoning entirely,
539
+ // and on a reasoning model that *is* the whole reply until the very end:
540
+ // the socket sits silent for the length of the think, the screen shows
541
+ // nothing, and the provider eventually drops the request as idle. Asking
542
+ // for it fixes the blank screen and the dropped request together. Models
543
+ // that do not reason ignore the flag.
544
+ include_reasoning: true,
545
+ };
546
+
547
+ const wired = wireTools(tools);
548
+ if (wired) {
549
+ request.tools = wired;
550
+ request.tool_choice = 'auto';
551
+ }
552
+ if (opts.temperature !== undefined) request.temperature = opts.temperature;
553
+ if (opts.maxOutputTokens) request.max_tokens = opts.maxOutputTokens;
554
+
555
+ const attempts = 4;
556
+ let problem;
557
+
558
+ // Text already on screen cannot be unprinted, so a stream is only safe to
559
+ // retry while it is still silent. Every timeout worth retrying happens
560
+ // before the first token, so this costs nothing in practice.
561
+ let printed = 0;
562
+ const callOpts = opts.onText
563
+ ? { ...opts, onText: (d) => { printed += d.length; opts.onText(d); } }
564
+ : opts;
565
+
566
+ for (let attempt = 1; attempt <= attempts; attempt++) {
567
+ try {
568
+ if (opts.onText) return await streamed(request, callOpts, id);
569
+ const { data, response } = await connection().chat.completions
570
+ .create(request, { signal: opts.signal })
571
+ .withResponse();
572
+ noteLimits(response?.headers);
573
+ return normalize(data, id);
574
+ } catch (err) {
575
+ noteLimits(err?.headers);
576
+ problem = explain(err, id);
577
+
578
+ // A per-minute limit is a wait, not a failure. Sit it out rather than
579
+ // making the user retype their message.
580
+ const wait = problem.detail?.retryAfter;
581
+ if (
582
+ problem.kind === 'rate_limit' && !problem.detail?.daily &&
583
+ Number.isFinite(wait) && wait > 0 && wait <= 90 &&
584
+ attempt < attempts && !opts.signal?.aborted
585
+ ) {
586
+ const until = Date.now() + wait * 1000;
587
+ while (Date.now() < until && !opts.signal?.aborted) {
588
+ opts.onWait?.(`rate limited — resuming in ${Math.ceil((until - Date.now()) / 1000)}s`);
589
+ await pause(Math.min(1000, until - Date.now()));
590
+ }
591
+ if (opts.signal?.aborted) break;
592
+ continue;
593
+ }
594
+
595
+ const worthRetrying =
596
+ problem.kind === 'server' || problem.kind === 'network' || problem.kind === 'timeout';
597
+ if (!worthRetrying || attempt === attempts || opts.signal?.aborted) break;
598
+ if (printed > 0) break; // half an answer is on screen; do not print it twice
599
+
600
+ // A stalled provider needs longer to come back than a dropped socket
601
+ // does, and the wait is narrated so a slow turn never looks like a hang.
602
+ const backoff = problem.kind === 'timeout'
603
+ ? 1500 * 2 ** (attempt - 1)
604
+ : 400 * 2 ** (attempt - 1);
605
+ opts.onWait?.(
606
+ `${problem.kind === 'timeout' ? 'provider stalled' : 'connection failed'} — ` +
607
+ `retrying (${attempt + 1}/${attempts})`
608
+ );
609
+ await pause(backoff);
610
+ }
611
+ }
612
+
613
+ throw problem;
614
+ }
615
+
616
+ /** Collect a streamed reply, handing deltas out as they land. */
617
+ async function streamed(request, opts, id) {
618
+ const { data: stream, response } = await connection().chat.completions
619
+ .create(
620
+ { ...request, stream: true, stream_options: { include_usage: true } },
621
+ { signal: opts.signal }
622
+ )
623
+ .withResponse();
624
+ noteLimits(response?.headers);
625
+
626
+ let text = '';
627
+ let reasoning = '';
628
+ let finishReason = 'stop';
629
+ let usage = null;
630
+ const partial = new Map();
631
+
632
+ for await (const chunk of stream) {
633
+ if (opts.signal?.aborted) break;
634
+ if (chunk.usage) usage = chunk.usage;
635
+
636
+ const choice = chunk.choices?.[0];
637
+ if (!choice) continue;
638
+ if (choice.finish_reason) finishReason = choice.finish_reason;
639
+ const delta = choice.delta ?? {};
640
+
641
+ // Reasoning arrives on a separate channel: `reasoning` on OpenRouter,
642
+ // `reasoning_content` on some upstreams.
643
+ const thinking = delta.reasoning ?? delta.reasoning_content;
644
+ if (thinking) {
645
+ reasoning += thinking;
646
+ opts.onThinking?.(thinking);
647
+ }
648
+
649
+ if (delta.content) {
650
+ text += delta.content;
651
+ opts.onText(delta.content);
652
+ }
653
+
654
+ // A tool call's name and arguments arrive across several chunks, keyed by
655
+ // index, so they are stitched back together here.
656
+ for (const call of delta.tool_calls ?? []) {
657
+ const slot = partial.get(call.index) ?? { id: '', name: '', args: '' };
658
+ if (call.id) slot.id = call.id;
659
+ if (call.function?.name) slot.name += call.function.name;
660
+ if (call.function?.arguments) slot.args += call.function.arguments;
661
+ partial.set(call.index, slot);
662
+ }
663
+ }
664
+
665
+ const toolCalls = [];
666
+ let n = 0;
667
+ for (const slot of partial.values()) {
668
+ toolCalls.push(readCall({ id: slot.id || `call_${n++}`, name: slot.name, raw: slot.args }));
669
+ }
670
+
671
+ return {
672
+ text: text.trim(),
673
+ reasoning: reasoning.trim(),
674
+ toolCalls,
675
+ usage: {
676
+ promptTokens: usage?.prompt_tokens ?? 0,
677
+ outputTokens: usage?.completion_tokens ?? 0,
678
+ totalTokens: usage?.total_tokens ?? 0,
679
+ },
680
+ finishReason,
681
+ model: id,
682
+ };
683
+ }
684
+
685
+ /**
686
+ * Parse one tool call's arguments.
687
+ *
688
+ * A parse error is recorded on the call rather than thrown. The loop hands it
689
+ * back to the model, which usually fixes its own JSON on the next step —
690
+ * cheaper than failing the whole turn over a stray comma.
691
+ */
692
+ function readCall({ id, name, raw }) {
693
+ const call = { id, name, args: {} };
694
+ const text = String(raw ?? '').trim();
695
+ if (!text) return call;
696
+ try {
697
+ const parsed = JSON.parse(text);
698
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) call.args = parsed;
699
+ else call.parseError = `arguments must be a JSON object, got ${Array.isArray(parsed) ? 'array' : typeof parsed}`;
700
+ } catch (err) {
701
+ call.parseError = `${err.message} — the raw arguments were: ${text.slice(0, 300)}`;
702
+ }
703
+ return call;
704
+ }
705
+
706
+ function normalize(data, id) {
707
+ const choice = data?.choices?.[0];
708
+ const message = choice?.message ?? {};
709
+
710
+ const toolCalls = (message.tool_calls ?? []).map((c) =>
711
+ readCall({ id: c.id, name: c.function?.name, raw: c.function?.arguments })
712
+ );
713
+
714
+ const u = data?.usage ?? {};
715
+ const finishReason = choice?.finish_reason ?? 'stop';
716
+ const text = (message.content ?? '').trim();
717
+
718
+ if (!text && toolCalls.length === 0 && finishReason === 'length') {
719
+ throw new Failure({
720
+ kind: 'no_content',
721
+ attempted: `asking ${modelName(id)} for a reply`,
722
+ failed: 'The reply hit the output limit before producing anything at all.',
723
+ fix: 'Ask for something shorter, or split the task into steps.',
724
+ detail: { finishReason },
725
+ });
726
+ }
727
+
728
+ return {
729
+ text,
730
+ reasoning: (message.reasoning ?? '').trim(),
731
+ toolCalls,
732
+ usage: {
733
+ promptTokens: u.prompt_tokens ?? 0,
734
+ outputTokens: u.completion_tokens ?? 0,
735
+ totalTokens: u.total_tokens ?? 0,
736
+ },
737
+ finishReason,
738
+ model: id,
739
+ };
740
+ }