ucode-agent 1.45.0 → 1.47.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.
@@ -1,800 +1,807 @@
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 { jsonrepair } from 'jsonrepair';
26
- import { Failure } from './failure.js';
27
-
28
- const HERE = dirname(fileURLToPath(import.meta.url));
29
- const PACKAGE_ROOT = join(HERE, '..', '..');
30
-
31
- /** Personal config lives here, outside the package, so upgrades never touch it. */
32
- export const UCODE_HOME = join(homedir(), '.ucode');
33
- export const ENV_FILE = join(UCODE_HOME, '.env');
34
-
35
- export const BASE_URL = 'https://openrouter.ai/api/v1';
36
- export const PROVIDER = 'OpenRouter';
37
-
38
- // First definition wins — dotenv never overwrites a variable that already
39
- // exists — so the order here is the precedence order:
40
- // real environment > ./.env (this project) > ~/.ucode/.env (this machine)
41
- // > the checkout's own .env (only when developing on a clone)
42
- dotenv.config({ path: join(process.cwd(), '.env'), quiet: true });
43
- dotenv.config({ path: ENV_FILE, quiet: true });
44
- dotenv.config({ path: join(PACKAGE_ROOT, '.env'), quiet: true });
45
-
46
- /**
47
- * The whole model list. Not a starting point — the list.
48
- *
49
- * ucode runs on NVIDIA and Cohere only. Both vendors serve genuinely capable
50
- * models free through OpenRouter, both handle tool calling properly, and
51
- * keeping the set to five means every one of them has been used in anger
52
- * rather than listed on the strength of a benchmark. A picker offering sixty
53
- * models is a picker nobody reads.
54
- *
55
- * `name` is what the status bar shows. `note` is what the picker shows.
56
- */
57
- export const MODELS = {
58
- 'nvidia/nemotron-3-ultra-550b-a55b:free': {
59
- name: 'Nemotron 3 Ultra',
60
- context: 1_000_000,
61
- star: true,
62
- note: 'deepest reasoning, 1M context — slowest to answer',
63
- },
64
- 'nvidia/nemotron-3.5-lightning:free': {
65
- name: 'Nemotron 3.5 Lightning',
66
- context: 1_000_000,
67
- note: 'same huge window, answers much sooner',
68
- },
69
- 'nvidia/nemotron-3-super-120b-a12b:free': {
70
- name: 'Nemotron 3 Super',
71
- context: 262_144,
72
- note: 'strong all-rounder, quick to first token',
73
- },
74
- 'nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free': {
75
- name: 'Nemotron 3 Nano Omni',
76
- context: 256_000,
77
- note: 'small and fast, reasoning tuned',
78
- },
79
- 'cohere/north-mini-code:free': {
80
- name: 'North Mini Code',
81
- context: 256_000,
82
- star: true,
83
- note: 'the default — built for code and interface work, quick to answer',
84
- },
85
- };
86
-
87
- /**
88
- * North Mini Code is the default: it is built for code and interface work,
89
- * which is what ucode is mostly asked to do, and it answers far sooner than
90
- * the big reasoning models. /model moves to Ultra when a problem needs the
91
- * million-token window and the long think more than it needs the speed.
92
- */
93
- export const DEFAULT_MODEL = 'cohere/north-mini-code:free';
94
-
95
- /**
96
- * Where to go when a model is busy, in order of preference. Each is served by
97
- * a different upstream, so a rate limit on one rarely means a limit on the
98
- * next — which is what lets a long build keep going instead of stopping at
99
- * the first "too many requests".
100
- */
101
- export const FALLBACKS = [
102
- 'cohere/north-mini-code:free',
103
- 'nvidia/nemotron-3.5-lightning:free',
104
- 'nvidia/nemotron-3-super-120b-a12b:free',
105
- 'nvidia/nemotron-3-ultra-550b-a55b:free',
106
- ];
107
-
108
- /** The next model to try after `id`, skipping any already tried this round. */
109
- export function fallbackFor(id, tried = new Set()) {
110
- // Off unless UCODE_FALLBACK=1. A build that starts on one model and finishes
111
- // on another finishes to a different standard, and the swap lands exactly
112
- // when the user is least placed to work out why the output changed —
113
- // mid-build, behind a note that scrolls past. Which model to run is the one
114
- // decision they made before starting; it is not one to take back for them.
115
- //
116
- // Every caller already reads "no fallback" as "wait, then try this one
117
- // again": failover waits a minute and returns to the same model, the
118
- // stuck-detector simply does not switch, and a worker retries its own. That
119
- // is why this can be a single gate rather than four.
120
- if (process.env.UCODE_FALLBACK !== '1') return null;
121
-
122
- const start = Math.max(0, FALLBACKS.indexOf(id));
123
- for (let i = 1; i <= FALLBACKS.length; i++) {
124
- const next = FALLBACKS[(start + i) % FALLBACKS.length];
125
- if (next !== id && !tried.has(next)) return next;
126
- }
127
- return null;
128
- }
129
-
130
- /** Seconds to wait on successive rate limits that come with no retry-after. */
131
- const RATE_LIMIT_BACKOFF = [5, 10, 20];
132
-
133
- let current = process.env.UCODE_MODEL || DEFAULT_MODEL;
134
- let client = null;
135
-
136
- export function model() {
137
- return current;
138
- }
139
-
140
- export function setModel(id) {
141
- const wanted = String(id ?? '').trim();
142
- if (!wanted) {
143
- throw new Failure({
144
- kind: 'bad_model',
145
- attempted: 'switching model',
146
- failed: 'No model name was given.',
147
- fix: `Pick one of: ${Object.keys(MODELS).join(', ')}`,
148
- });
149
- }
150
- if (!MODELS[wanted]) {
151
- throw new Failure({
152
- kind: 'bad_model',
153
- attempted: `switching to "${wanted}"`,
154
- failed: 'ucode only runs NVIDIA and Cohere models, and that is not one of them.',
155
- fix: `Run /model to choose from: ${Object.keys(MODELS).join(', ')}`,
156
- });
157
- }
158
- current = wanted;
159
- return current;
160
- }
161
-
162
- /** The short name for a model id: "Nemotron 3 Ultra". */
163
- export function modelName(id = current) {
164
- return MODELS[id]?.name ?? id;
165
- }
166
-
167
- /** Every model, in list order, annotated with whether it is the active one. */
168
- export function modelList() {
169
- return Object.entries(MODELS).map(([id, info]) => ({
170
- id,
171
- ...info,
172
- active: id === current,
173
- }));
174
- }
175
-
176
- /**
177
- * How many tokens one request may occupy.
178
- *
179
- * OpenRouter meters requests rather than tokens, so nothing here is rationing
180
- * a quota — the binding limit is simply the window the model has. On the two
181
- * million-token models compaction essentially never fires.
182
- */
183
- export function contextLimit(id = current) {
184
- const override = Number(process.env.UCODE_MAX_CONTEXT_TOKENS);
185
- if (Number.isFinite(override) && override > 0) return override;
186
- return MODELS[id]?.context ?? 128_000;
187
- }
188
-
189
- /**
190
- * A rough local token count, used to decide when to compact *before* a
191
- * request goes out. Real numbers come back in the response usage; this only
192
- * has to be close enough to trigger at the right time.
193
- */
194
- export function estimateTokens(text) {
195
- return text ? Math.ceil(String(text).length / 4) : 0;
196
- }
197
-
198
- export function estimateConversation(messages) {
199
- let total = 0;
200
- for (const m of messages) {
201
- total += estimateTokens(m.content || '');
202
- for (const call of m.toolCalls || []) {
203
- total += estimateTokens(call.name) + estimateTokens(JSON.stringify(call.args || {}));
204
- }
205
- total += 4; // role and framing overhead per message
206
- }
207
- return total;
208
- }
209
-
210
- // ---------------------------------------------------------------------------
211
- // Client
212
- // ---------------------------------------------------------------------------
213
-
214
- /**
215
- * No key is bundled here, and none ever should be. A key committed to a public
216
- * package is readable by anyone who runs `npm pack ucode-agent`, and no amount
217
- * of first-run convenience is worth handing out a live credential.
218
- */
219
- function apiKey() {
220
- // UCODE_API_KEY is the documented name. The provider's own variable name is
221
- // still read, so a key set up for another tool keeps working here.
222
- const key = (process.env.UCODE_API_KEY || process.env.OPENROUTER_API_KEY || '').trim();
223
- if (!key) {
224
- throw new Failure({
225
- kind: 'no_api_key',
226
- attempted: 'connecting to the model',
227
- failed: 'No API key is set - UCODE_API_KEY is missing from the environment and from every .env file.',
228
- fix:
229
- `Put UCODE_API_KEY=your-key in ${ENV_FILE} — that applies to every ` +
230
- 'project on this machine — or in a .env file beside your code. ' +
231
- 'Free keys: https://openrouter.ai/keys',
232
- });
233
- }
234
- return key;
235
- }
236
-
237
- function connection() {
238
- if (client) return client;
239
- client = new OpenAI({
240
- apiKey: apiKey(),
241
- baseURL: process.env.UCODE_BASE_URL || BASE_URL,
242
- // Nemotron Ultra can think for a long time before its first token, so the
243
- // ceiling is deliberately generous. maxRetries is 0 because ask() owns
244
- // retrying: its attempts are narrated on screen instead of happening
245
- // silently somewhere inside the SDK.
246
- timeout: Number(process.env.UCODE_REQUEST_TIMEOUT_MS) || 300_000,
247
- maxRetries: 0,
248
- defaultHeaders: {
249
- 'HTTP-Referer': 'https://github.com/sppideey/ucode-agent',
250
- 'X-Title': 'ucode',
251
- },
252
- });
253
- return client;
254
- }
255
-
256
- /** Drop the cached client so the next request picks up a changed key. */
257
- export function resetConnection() {
258
- client = null;
259
- }
260
-
261
- // ---------------------------------------------------------------------------
262
- // Live quota, taken from whatever rate-limit headers come back
263
- // ---------------------------------------------------------------------------
264
-
265
- let limits = null;
266
-
267
- export function rateLimits() {
268
- return limits;
269
- }
270
-
271
- /** "1.5s", "2m59.56s", "1h2m" -> seconds */
272
- function seconds(value) {
273
- if (!value) return null;
274
- const m = /^(?:(\d+(?:\.\d+)?)h)?(?:(\d+(?:\.\d+)?)m(?!s))?(?:(\d+(?:\.\d+)?)m?s)?$/
275
- .exec(String(value).trim());
276
- if (!m) return null;
277
- const total = (parseFloat(m[1]) || 0) * 3600 + (parseFloat(m[2]) || 0) * 60 + (parseFloat(m[3]) || 0);
278
- return total > 0 ? total : null;
279
- }
280
-
281
- function noteLimits(headers) {
282
- if (!headers?.get) return;
283
- const num = (name) => {
284
- const n = Number(headers.get(name));
285
- return Number.isFinite(n) ? n : null;
286
- };
287
- limits = {
288
- requestsLimit: num('x-ratelimit-limit-requests'),
289
- requestsRemaining: num('x-ratelimit-remaining-requests'),
290
- requestsReset: seconds(headers.get('x-ratelimit-reset-requests')),
291
- tokensLimit: num('x-ratelimit-limit-tokens'),
292
- tokensRemaining: num('x-ratelimit-remaining-tokens'),
293
- tokensReset: seconds(headers.get('x-ratelimit-reset-tokens')),
294
- at: Date.now(),
295
- };
296
- }
297
-
298
- // ---------------------------------------------------------------------------
299
- // Neutral format -> wire format
300
- // ---------------------------------------------------------------------------
301
-
302
- function wireTools(tools) {
303
- if (!tools?.length) return undefined;
304
- return tools.map((t) => ({
305
- type: 'function',
306
- function: {
307
- name: t.name,
308
- description: t.description,
309
- parameters: t.parameters ?? { type: 'object', properties: {} },
310
- },
311
- }));
312
- }
313
-
314
- function wireMessages(messages) {
315
- const out = [];
316
- for (const m of messages) {
317
- if (m.role === 'user' && m.images?.length) {
318
- out.push({
319
- role: 'user',
320
- content: [
321
- { type: 'text', text: m.content ?? '' },
322
- ...m.images.map((url) => ({ type: 'image_url', image_url: { url } })),
323
- ],
324
- });
325
- } else if (m.role === 'system' || m.role === 'user') {
326
- out.push({ role: m.role, content: m.content ?? '' });
327
- } else if (m.role === 'assistant') {
328
- const wire = { role: 'assistant', content: m.content || '' };
329
- if (m.toolCalls?.length) {
330
- wire.tool_calls = m.toolCalls.map((c) => ({
331
- id: c.id,
332
- type: 'function',
333
- function: { name: c.name, arguments: JSON.stringify(c.args ?? {}) },
334
- }));
335
- }
336
- out.push(wire);
337
- } else if (m.role === 'tool') {
338
- out.push({ role: 'tool', tool_call_id: m.toolCallId, content: m.content ?? '' });
339
- }
340
- }
341
- return out;
342
- }
343
-
344
- // ---------------------------------------------------------------------------
345
- // Turning provider errors into something a person can act on
346
- // ---------------------------------------------------------------------------
347
-
348
- function bodyOf(err) {
349
- if (err?.error) return { error: err.error };
350
- const raw = String(err?.message ?? '');
351
- const start = raw.indexOf('{');
352
- if (start === -1) return null;
353
- try {
354
- return JSON.parse(raw.slice(start));
355
- } catch {
356
- return null;
357
- }
358
- }
359
-
360
- export function explain(err, id) {
361
- if (err instanceof Failure) return err;
362
-
363
- const status = err?.status ?? err?.statusCode ?? null;
364
- const body = bodyOf(err);
365
- const detail = body?.error?.message ?? String(err?.message ?? err);
366
- const attempted = `asking ${modelName(id)} for a reply`;
367
-
368
- // The useful text is often not on the error itself. undici reports a socket
369
- // that closed mid-response as a bare `TypeError: terminated` and puts the
370
- // real reason on `cause`, so the whole chain is matched rather than the top
371
- // message alone — otherwise an ordinary dropped connection, which is worth
372
- // retrying, gets reported as an unknown fault, which is not.
373
- const chain = [err?.message, err?.code, err?.cause?.message, err?.cause?.code]
374
- .filter(Boolean)
375
- .join(' | ');
376
- const raw = chain || String(err);
377
-
378
- if (err?.name === 'AbortError' || /aborted|The operation was aborted/i.test(raw)) {
379
- return new Failure({
380
- kind: 'aborted',
381
- attempted,
382
- failed: 'The request was cancelled.',
383
- fix: 'Send the message again when you are ready.',
384
- cause: err,
385
- });
386
- }
387
-
388
- if (status === 401 || status === 403 || /invalid[_ ]api[_ ]key/i.test(raw)) {
389
- return new Failure({
390
- kind: 'invalid_api_key',
391
- attempted,
392
- failed: `The API key was rejected (HTTP ${status ?? 401}).`,
393
- fix:
394
- 'Check UCODE_API_KEY in ~/.ucode/.env for a typo or trailing space, and ' +
395
- 'confirm the key is still active in your account.',
396
- cause: err,
397
- });
398
- }
399
-
400
- if (status === 429 || /rate[_ ]limit/i.test(raw)) {
401
- // `??` cannot be used to chain through Number(): Number(undefined) is NaN,
402
- // which is neither null nor undefined, so it would swallow every fallback
403
- // after it and the wait would silently never be found.
404
- const header = err?.headers?.get?.('retry-after');
405
- const asNumber = Number(header);
406
- const retryAfter =
407
- seconds(header) ??
408
- (Number.isFinite(asNumber) && asNumber > 0 ? asNumber : null) ??
409
- seconds(/try again in ([\dhms.]+)/i.exec(detail)?.[1]) ??
410
- null;
411
- // The daily cap reads "free-models-per-day-high-balance", with hyphens, and
412
- // names its source in the metadata. It is one cap across every free model,
413
- // so it is reported at once rather than waited on model after model.
414
- const meta = body?.error?.metadata ?? {};
415
- const daily = /per[- ]day|RPD|TPD|daily/i.test(`${detail} ${meta.limit_source ?? ''}`);
416
- const resetMs = Number(meta.headers?.['X-RateLimit-Reset'] ?? err?.headers?.get?.('x-ratelimit-reset'));
417
- const resetAt = daily && Number.isFinite(resetMs) && resetMs > Date.now() ? new Date(resetMs) : null;
418
- const cap = Number(meta.headers?.['X-RateLimit-Limit']) || null;
419
- const wait = Number.isFinite(retryAfter) && retryAfter
420
- ? (retryAfter >= 60 ? `${Math.ceil(retryAfter / 60)} min` : `${Math.ceil(retryAfter)}s`)
421
- : null;
422
-
423
- return new Failure({
424
- kind: 'rate_limit',
425
- attempted,
426
- failed: daily
427
- ? `This key's free daily limit${cap ? ` of ${cap} requests` : ''} is used up. It covers every free model, so switching will not help.`
428
- : `Too many requests for ${modelName(id)} just now${wait ? ` — clear in ${wait}` : ''}.`,
429
- fix: daily
430
- ? `It resets ${resetAt ? `at ${resetAt.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}` : 'once a day'}. ` +
431
- 'Adding credit to your account raises the limit.'
432
- : 'ucode waits these out on its own. Free endpoints are shared, so it usually ' +
433
- 'clears in seconds; /model moves to a quieter one.',
434
- detail: { retryAfter, daily, resetAt: resetAt?.getTime() ?? null },
435
- cause: err,
436
- });
437
- }
438
-
439
- // A 404 on a model in this list is almost never a bad name. It is OpenRouter
440
- // having no upstream free to serve it at that instant, and it clears by
441
- // itself — so it is retried rather than reported as a missing model.
442
- if (status === 404 || /does not exist|not found|decommissioned/i.test(raw)) {
443
- if (MODELS[id]) {
444
- return new Failure({
445
- kind: 'server',
446
- attempted,
447
- failed: `No provider was free to serve ${modelName(id)} at that moment.`,
448
- fix: 'ucode retries this by itself. If it keeps up, /model switches.',
449
- detail: { status },
450
- cause: err,
451
- });
452
- }
453
- return new Failure({
454
- kind: 'bad_model',
455
- attempted,
456
- failed: `No model "${id}" is available to this key.`,
457
- fix: `Run /model. ucode ships with: ${Object.keys(MODELS).join(', ')}`,
458
- cause: err,
459
- });
460
- }
461
-
462
- // Some upstreams validate tool calls themselves and reject an invented one,
463
- // which fails the whole request. Recoverable: the loop feeds this back.
464
- if (body?.error?.code === 'tool_use_failed' || /tool call validation failed/i.test(detail)) {
465
- const attemptedName = /call tool '([^']+)'/.exec(detail)?.[1];
466
- return new Failure({
467
- kind: 'bad_tool_call',
468
- attempted,
469
- failed: attemptedName
470
- ? `The model tried to call "${attemptedName}", which is not one of its tools.`
471
- : `The model produced a tool call the provider rejected: ${detail}`,
472
- fix: 'Use only the tools supplied with the request.',
473
- detail: { attemptedName },
474
- cause: err,
475
- });
476
- }
477
-
478
- if (status === 400) {
479
- const noTools = /tool calling.*not supported/i.test(detail);
480
- return new Failure({
481
- kind: noTools ? 'no_tool_support' : 'bad_request',
482
- attempted,
483
- failed: noTools
484
- ? `${modelName(id)} cannot call tools, which ucode needs for every task.`
485
- : `The request was rejected as malformed (HTTP 400): ${detail}`,
486
- fix: noTools
487
- ? 'Run /model and pick another one.'
488
- : 'The conversation has something in it the provider will not accept. /new starts a fresh one.',
489
- cause: err,
490
- });
491
- }
492
-
493
- if (status === 413 || /too large|context.*length/i.test(detail)) {
494
- return new Failure({
495
- kind: 'too_large',
496
- attempted,
497
- failed: `The conversation no longer fits in ${modelName(id)}: ${detail}`,
498
- fix: 'Run /new for a fresh session, or lower UCODE_MAX_CONTEXT_TOKENS so ucode folds older turns away sooner.',
499
- cause: err,
500
- });
501
- }
502
-
503
- // OpenRouter drops a request when the upstream goes quiet on it. That is the
504
- // ordinary failure mode of a busy free endpoint, and of a big reasoning model
505
- // that spends a long time thinking before its first token. Nothing was
506
- // generated, so retrying is safe — and ask() does it before anyone notices.
507
- if (
508
- status === 408 || status === 504 || status === 524 || status === 522 ||
509
- err?.name === 'APIConnectionTimeoutError' ||
510
- /idle timeout|timed out|timeout/i.test(detail) || /idle timeout|timed out/i.test(raw)
511
- ) {
512
- return new Failure({
513
- kind: 'timeout',
514
- attempted,
515
- failed: `${modelName(id)} sent nothing back in time — the provider dropped the request.`,
516
- fix:
517
- 'Free endpoints stall under load, and the largest reasoning models are the ' +
518
- 'first to. ucode already retried. If it keeps happening, /model to Nemotron ' +
519
- '3.5 Lightning or North Mini Code, which answer sooner.',
520
- detail: { status },
521
- cause: err,
522
- });
523
- }
524
-
525
- if (status >= 500 || /internal|unavailable|overloaded/i.test(raw)) {
526
- return new Failure({
527
- kind: 'server',
528
- attempted,
529
- failed: `The provider returned HTTP ${status}. That is their side, not yours.`,
530
- fix: 'Wait a few seconds and send again. If it persists, /model to another one.',
531
- cause: err,
532
- });
533
- }
534
-
535
- // `terminated` and `premature close` are what a connection dropped part way
536
- // through a reply looks like. Nothing usable arrived, so it is safe to send
537
- // again — and on a free endpoint under load it happens often enough that
538
- // treating it as fatal would be the single most visible flaw in the agent.
539
- if (
540
- /ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|ETIMEDOUT|EPIPE|network|fetch failed|socket hang up|terminated|premature close|other side closed|UND_ERR/i.test(raw) ||
541
- err?.name === 'APIConnectionError' ||
542
- (err instanceof TypeError && /terminated/i.test(raw))
543
- ) {
544
- return new Failure({
545
- kind: 'network',
546
- attempted,
547
- failed: `The connection to the model dropped: ${raw}`,
548
- fix:
549
- 'ucode retries this by itself. If it keeps happening, check your connection, ' +
550
- 'VPN and any corporate proxy (HTTPS_PROXY) — or /model to a lighter one, since ' +
551
- 'a long think on a busy free endpoint is the usual cause.',
552
- cause: err,
553
- });
554
- }
555
-
556
- return new Failure({
557
- kind: 'unknown',
558
- attempted,
559
- failed: detail,
560
- fix: 'Retry once. If it repeats, run ucode --debug for the full trace.',
561
- cause: err,
562
- });
563
- }
564
-
565
- const pause = (ms) => new Promise((r) => setTimeout(r, ms));
566
-
567
- // ---------------------------------------------------------------------------
568
- // The one call
569
- // ---------------------------------------------------------------------------
570
-
571
- /**
572
- * Send a conversation and get a normalized reply.
573
- *
574
- * @param {Array} messages neutral messages
575
- * @param {Array} [tools] neutral tool definitions
576
- * @param {object} [opts] { model, temperature, signal, maxOutputTokens,
577
- * reasoning, attempts, onText, onThinking, onWait }
578
- */
579
- export async function ask(messages, tools = [], opts = {}) {
580
- const id = opts.model || current;
581
-
582
- const request = {
583
- model: id,
584
- messages: wireMessages(messages),
585
- // Ask for the working. Without it OpenRouter withholds reasoning entirely,
586
- // and on a reasoning model that *is* the whole reply until the very end:
587
- // the socket sits silent for the length of the think, the screen shows
588
- // nothing, and the provider eventually drops the request as idle. Asking
589
- // for it fixes the blank screen and the dropped request together. Models
590
- // that do not reason ignore the flag.
591
- include_reasoning: true,
592
- };
593
-
594
- const wired = wireTools(tools);
595
- if (wired) {
596
- request.tools = wired;
597
- request.tool_choice = 'auto';
598
- }
599
- if (opts.temperature !== undefined) request.temperature = opts.temperature;
600
- if (opts.maxOutputTokens) request.max_tokens = opts.maxOutputTokens;
601
- if (opts.reasoning) request.reasoning = opts.reasoning;
602
-
603
- // A side call (the design review) passes fewer: it is better skipped than
604
- // waited on through a string of rate-limit pauses.
605
- const attempts = opts.attempts ?? 4;
606
- let problem;
607
-
608
- // Text already on screen cannot be unprinted, so a stream is only safe to
609
- // retry while it is still silent. Every timeout worth retrying happens
610
- // before the first token, so this costs nothing in practice.
611
- let printed = 0;
612
- const callOpts = opts.onText
613
- ? { ...opts, onText: (d) => { printed += d.length; opts.onText(d); } }
614
- : opts;
615
-
616
- for (let attempt = 1; attempt <= attempts; attempt++) {
617
- try {
618
- if (opts.onText) return await streamed(request, callOpts, id);
619
- const { data, response } = await connection().chat.completions
620
- .create(request, { signal: opts.signal })
621
- .withResponse();
622
- noteLimits(response?.headers);
623
- return normalize(data, id);
624
- } catch (err) {
625
- noteLimits(err?.headers);
626
- problem = explain(err, id);
627
-
628
- // A per-minute limit is a wait, not a failure. Sit it out rather than
629
- // making the user retype their message. Free endpoints often refuse
630
- // without saying how long to wait, so when there is no retry-after the
631
- // pauses grow on their own — 5s, 10s, 20s — and only then does the
632
- // error go up to the loop, which moves to another model.
633
- const told = problem.detail?.retryAfter;
634
- const wait = Number.isFinite(told) && told > 0 && told <= 90 ? told : RATE_LIMIT_BACKOFF[attempt - 1];
635
- if (
636
- problem.kind === 'rate_limit' && !problem.detail?.daily &&
637
- wait && attempt < attempts && printed === 0 && !opts.signal?.aborted
638
- ) {
639
- const until = Date.now() + wait * 1000;
640
- while (Date.now() < until && !opts.signal?.aborted) {
641
- opts.onWait?.(`rate limited — resuming in ${Math.ceil((until - Date.now()) / 1000)}s`);
642
- await pause(Math.min(1000, until - Date.now()));
643
- }
644
- if (opts.signal?.aborted) break;
645
- continue;
646
- }
647
-
648
- const worthRetrying =
649
- problem.kind === 'server' || problem.kind === 'network' || problem.kind === 'timeout';
650
- if (!worthRetrying || attempt === attempts || opts.signal?.aborted) break;
651
- if (printed > 0) break; // half an answer is on screen; do not print it twice
652
-
653
- // A stalled provider needs longer to come back than a dropped socket
654
- // does, and the wait is narrated so a slow turn never looks like a hang.
655
- const backoff = problem.kind === 'timeout'
656
- ? 1500 * 2 ** (attempt - 1)
657
- : 400 * 2 ** (attempt - 1);
658
- opts.onWait?.(
659
- `${problem.kind === 'timeout' ? 'provider stalled' : 'connection failed'} — ` +
660
- `retrying (${attempt + 1}/${attempts})`
661
- );
662
- await pause(backoff);
663
- }
664
- }
665
-
666
- throw problem;
667
- }
668
-
669
- /** Collect a streamed reply, handing deltas out as they land. */
670
- async function streamed(request, opts, id) {
671
- const { data: stream, response } = await connection().chat.completions
672
- .create(
673
- { ...request, stream: true, stream_options: { include_usage: true } },
674
- { signal: opts.signal }
675
- )
676
- .withResponse();
677
- noteLimits(response?.headers);
678
-
679
- let text = '';
680
- let reasoning = '';
681
- let finishReason = 'stop';
682
- let usage = null;
683
- const partial = new Map();
684
- const handed = new Set();
685
- let highest = -1;
686
-
687
- for await (const chunk of stream) {
688
- if (opts.signal?.aborted) break;
689
- if (chunk.usage) usage = chunk.usage;
690
-
691
- const choice = chunk.choices?.[0];
692
- if (!choice) continue;
693
- if (choice.finish_reason) finishReason = choice.finish_reason;
694
- const delta = choice.delta ?? {};
695
-
696
- // Reasoning arrives on a separate channel: `reasoning` on OpenRouter,
697
- // `reasoning_content` on some upstreams.
698
- const thinking = delta.reasoning ?? delta.reasoning_content;
699
- if (thinking) {
700
- reasoning += thinking;
701
- opts.onThinking?.(thinking);
702
- }
703
-
704
- if (delta.content) {
705
- text += delta.content;
706
- opts.onText(delta.content);
707
- }
708
-
709
- // A tool call's name and arguments arrive across several chunks, keyed by
710
- // index, so they are stitched back together here.
711
- for (const call of delta.tool_calls ?? []) {
712
- // Calls arrive one after another, so the first chunk of call N means
713
- // every call before it is complete. Those are handed over at once, and
714
- // the caller can start running them while the rest are still being
715
- // written — the reply streaming and the tools working overlap.
716
- if (opts.onToolCall && call.index > highest) {
717
- for (const [index, slot] of partial) {
718
- if (index < call.index && !handed.has(index)) {
719
- handed.add(index);
720
- opts.onToolCall(readCall({ id: slot.id || `call_${index}`, name: slot.name, raw: slot.args }));
721
- }
722
- }
723
- highest = call.index;
724
- }
725
-
726
- const slot = partial.get(call.index) ?? { id: '', name: '', args: '' };
727
- if (call.id) slot.id = call.id;
728
- if (call.function?.name) slot.name += call.function.name;
729
- if (call.function?.arguments) slot.args += call.function.arguments;
730
- partial.set(call.index, slot);
731
-
732
- // A whole app arrives as one enormous arguments string that takes a
733
- // minute or two to write. Handing it over as it grows is what lets the
734
- // caller say which file is being written right now, instead of showing
735
- // a spinner that has meant nothing for ninety seconds.
736
- if (call.function?.arguments) opts.onToolArgs?.({ index: call.index, name: slot.name, args: slot.args });
737
- }
738
- }
739
-
740
- const toolCalls = [];
741
- for (const [index, slot] of partial) {
742
- toolCalls.push(readCall({ id: slot.id || `call_${index}`, name: slot.name, raw: slot.args, cutOff: finishReason === 'length' }));
743
- }
744
-
745
- return {
746
- text: text.trim(),
747
- reasoning: reasoning.trim(),
748
- toolCalls,
749
- usage: {
750
- promptTokens: usage?.prompt_tokens ?? 0,
751
- outputTokens: usage?.completion_tokens ?? 0,
752
- totalTokens: usage?.total_tokens ?? 0,
753
- },
754
- finishReason,
755
- model: id,
756
- };
757
- }
758
-
759
- /**
760
- * Recover the files from a file-write call whose JSON will not parse.
761
- *
762
- * The usual cause is a double quote inside the code that the model forgot to
763
- * escape — `className="flex"` — which ends the JSON string early. No general
764
- * repair can know which quote was meant, but a file write has a fixed shape:
765
- * "path", then "content", then either the next file or the end. Splitting on
766
- * that shape and escaping the stray quotes gets every file back.
767
- */
768
- /**
769
- * Which calls can be rebuilt out of broken JSON.
770
- *
771
- * All three carry file contents — hundreds of lines of HTML, CSS and
772
- * JavaScript escaped into a JSON string — which is the one argument shape a
773
- * model gets wrong often enough to matter. Everything else is short enough
774
- * that a parse failure is a real mistake, worth reporting rather than guessing
775
- * around.
776
- */
777
- const SALVAGEABLE = new Set(['write_file', 'batch_write', 'create_app']);
778
-
779
- /**
780
- * The plain string arguments sitting beside a files array, read off the raw
781
- * text when the object as a whole will not parse.
782
- *
783
- * Only the keys create_app needs, and only from before the files begin, so a
784
- * "name" belonging to something nested inside a file cannot be mistaken for
785
- * the app's own.
786
- */
787
- function scalarArgs(text) {
788
- const at = text.search(/"files"\s*:/);
789
- const head = at > 0 ? text.slice(0, at) : text;
790
- const out = {};
791
- for (const key of ['folder', 'name', 'description', 'template', 'design']) {
792
- const hit = new RegExp(`"${key}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`).exec(head);
793
- if (hit) out[key] = hit[1].replace(/\\(["\\/])/g, '$1');
794
- }
795
- return out;
796
- }
797
-
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 { jsonrepair } from 'jsonrepair';
26
+ import { Failure } from './failure.js';
27
+
28
+ const HERE = dirname(fileURLToPath(import.meta.url));
29
+ const PACKAGE_ROOT = join(HERE, '..', '..');
30
+
31
+ /** Personal config lives here, outside the package, so upgrades never touch it. */
32
+ export const UCODE_HOME = join(homedir(), '.ucode');
33
+ export const ENV_FILE = join(UCODE_HOME, '.env');
34
+
35
+ export const BASE_URL = 'https://openrouter.ai/api/v1';
36
+ export const PROVIDER = 'OpenRouter';
37
+
38
+ // First definition wins — dotenv never overwrites a variable that already
39
+ // exists — so the order here is the precedence order:
40
+ // real environment > ./.env (this project) > ~/.ucode/.env (this machine)
41
+ // > the checkout's own .env (only when developing on a clone)
42
+ dotenv.config({ path: join(process.cwd(), '.env'), quiet: true });
43
+ dotenv.config({ path: ENV_FILE, quiet: true });
44
+ dotenv.config({ path: join(PACKAGE_ROOT, '.env'), quiet: true });
45
+
46
+ /**
47
+ * The whole model list. Not a starting point — the list.
48
+ *
49
+ * ucode runs on NVIDIA, Cohere and Nex AGI only. All three serve genuinely
50
+ * capable models free through OpenRouter, all handle tool calling properly,
51
+ * and keeping the set to six means every one of them has been used in anger
52
+ * rather than listed on the strength of a benchmark. A picker offering sixty
53
+ * models is a picker nobody reads.
54
+ *
55
+ * `name` is what the status bar shows. `note` is what the picker shows.
56
+ */
57
+ export const MODELS = {
58
+ 'nvidia/nemotron-3-ultra-550b-a55b:free': {
59
+ name: 'Nemotron 3 Ultra',
60
+ context: 1_000_000,
61
+ star: true,
62
+ note: 'deepest reasoning, 1M context — slowest to answer',
63
+ },
64
+ 'nvidia/nemotron-3.5-lightning:free': {
65
+ name: 'Nemotron 3.5 Lightning',
66
+ context: 1_000_000,
67
+ note: 'same huge window, answers much sooner',
68
+ },
69
+ 'nvidia/nemotron-3-super-120b-a12b:free': {
70
+ name: 'Nemotron 3 Super',
71
+ context: 262_144,
72
+ note: 'strong all-rounder, quick to first token',
73
+ },
74
+ 'nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free': {
75
+ name: 'Nemotron 3 Nano Omni',
76
+ context: 256_000,
77
+ note: 'small and fast, reasoning tuned',
78
+ },
79
+ 'cohere/north-mini-code:free': {
80
+ name: 'North Mini Code',
81
+ context: 256_000,
82
+ star: true,
83
+ note: 'the default — built for code and interface work, quick to answer',
84
+ },
85
+ // On trial, so not the default and not in FALLBACKS yet. Nex AGI is its only
86
+ // upstream, so a stall there has nowhere else to go.
87
+ 'nex-agi/nex-n2.5-pro:free': {
88
+ name: 'Nex N2.5 Pro',
89
+ context: 262_144,
90
+ note: 'new agentic coder, on trial — can stall on big builds',
91
+ },
92
+ };
93
+
94
+ /**
95
+ * North Mini Code is the default: it is built for code and interface work,
96
+ * which is what ucode is mostly asked to do, and it answers far sooner than
97
+ * the big reasoning models. /model moves to Ultra when a problem needs the
98
+ * million-token window and the long think more than it needs the speed.
99
+ */
100
+ export const DEFAULT_MODEL = 'cohere/north-mini-code:free';
101
+
102
+ /**
103
+ * Where to go when a model is busy, in order of preference. Each is served by
104
+ * a different upstream, so a rate limit on one rarely means a limit on the
105
+ * next — which is what lets a long build keep going instead of stopping at
106
+ * the first "too many requests".
107
+ */
108
+ export const FALLBACKS = [
109
+ 'cohere/north-mini-code:free',
110
+ 'nvidia/nemotron-3.5-lightning:free',
111
+ 'nvidia/nemotron-3-super-120b-a12b:free',
112
+ 'nvidia/nemotron-3-ultra-550b-a55b:free',
113
+ ];
114
+
115
+ /** The next model to try after `id`, skipping any already tried this round. */
116
+ export function fallbackFor(id, tried = new Set()) {
117
+ // Off unless UCODE_FALLBACK=1. A build that starts on one model and finishes
118
+ // on another finishes to a different standard, and the swap lands exactly
119
+ // when the user is least placed to work out why the output changed —
120
+ // mid-build, behind a note that scrolls past. Which model to run is the one
121
+ // decision they made before starting; it is not one to take back for them.
122
+ //
123
+ // Every caller already reads "no fallback" as "wait, then try this one
124
+ // again": failover waits a minute and returns to the same model, the
125
+ // stuck-detector simply does not switch, and a worker retries its own. That
126
+ // is why this can be a single gate rather than four.
127
+ if (process.env.UCODE_FALLBACK !== '1') return null;
128
+
129
+ const start = Math.max(0, FALLBACKS.indexOf(id));
130
+ for (let i = 1; i <= FALLBACKS.length; i++) {
131
+ const next = FALLBACKS[(start + i) % FALLBACKS.length];
132
+ if (next !== id && !tried.has(next)) return next;
133
+ }
134
+ return null;
135
+ }
136
+
137
+ /** Seconds to wait on successive rate limits that come with no retry-after. */
138
+ const RATE_LIMIT_BACKOFF = [5, 10, 20];
139
+
140
+ let current = process.env.UCODE_MODEL || DEFAULT_MODEL;
141
+ let client = null;
142
+
143
+ export function model() {
144
+ return current;
145
+ }
146
+
147
+ export function setModel(id) {
148
+ const wanted = String(id ?? '').trim();
149
+ if (!wanted) {
150
+ throw new Failure({
151
+ kind: 'bad_model',
152
+ attempted: 'switching model',
153
+ failed: 'No model name was given.',
154
+ fix: `Pick one of: ${Object.keys(MODELS).join(', ')}`,
155
+ });
156
+ }
157
+ if (!MODELS[wanted]) {
158
+ throw new Failure({
159
+ kind: 'bad_model',
160
+ attempted: `switching to "${wanted}"`,
161
+ failed: 'ucode only runs NVIDIA, Cohere and Nex AGI models, and that is not one of them.',
162
+ fix: `Run /model to choose from: ${Object.keys(MODELS).join(', ')}`,
163
+ });
164
+ }
165
+ current = wanted;
166
+ return current;
167
+ }
168
+
169
+ /** The short name for a model id: "Nemotron 3 Ultra". */
170
+ export function modelName(id = current) {
171
+ return MODELS[id]?.name ?? id;
172
+ }
173
+
174
+ /** Every model, in list order, annotated with whether it is the active one. */
175
+ export function modelList() {
176
+ return Object.entries(MODELS).map(([id, info]) => ({
177
+ id,
178
+ ...info,
179
+ active: id === current,
180
+ }));
181
+ }
182
+
183
+ /**
184
+ * How many tokens one request may occupy.
185
+ *
186
+ * OpenRouter meters requests rather than tokens, so nothing here is rationing
187
+ * a quota — the binding limit is simply the window the model has. On the two
188
+ * million-token models compaction essentially never fires.
189
+ */
190
+ export function contextLimit(id = current) {
191
+ const override = Number(process.env.UCODE_MAX_CONTEXT_TOKENS);
192
+ if (Number.isFinite(override) && override > 0) return override;
193
+ return MODELS[id]?.context ?? 128_000;
194
+ }
195
+
196
+ /**
197
+ * A rough local token count, used to decide when to compact *before* a
198
+ * request goes out. Real numbers come back in the response usage; this only
199
+ * has to be close enough to trigger at the right time.
200
+ */
201
+ export function estimateTokens(text) {
202
+ return text ? Math.ceil(String(text).length / 4) : 0;
203
+ }
204
+
205
+ export function estimateConversation(messages) {
206
+ let total = 0;
207
+ for (const m of messages) {
208
+ total += estimateTokens(m.content || '');
209
+ for (const call of m.toolCalls || []) {
210
+ total += estimateTokens(call.name) + estimateTokens(JSON.stringify(call.args || {}));
211
+ }
212
+ total += 4; // role and framing overhead per message
213
+ }
214
+ return total;
215
+ }
216
+
217
+ // ---------------------------------------------------------------------------
218
+ // Client
219
+ // ---------------------------------------------------------------------------
220
+
221
+ /**
222
+ * No key is bundled here, and none ever should be. A key committed to a public
223
+ * package is readable by anyone who runs `npm pack ucode-agent`, and no amount
224
+ * of first-run convenience is worth handing out a live credential.
225
+ */
226
+ function apiKey() {
227
+ // UCODE_API_KEY is the documented name. The provider's own variable name is
228
+ // still read, so a key set up for another tool keeps working here.
229
+ const key = (process.env.UCODE_API_KEY || process.env.OPENROUTER_API_KEY || '').trim();
230
+ if (!key) {
231
+ throw new Failure({
232
+ kind: 'no_api_key',
233
+ attempted: 'connecting to the model',
234
+ failed: 'No API key is set - UCODE_API_KEY is missing from the environment and from every .env file.',
235
+ fix:
236
+ `Put UCODE_API_KEY=your-key in ${ENV_FILE} — that applies to every ` +
237
+ 'project on this machine — or in a .env file beside your code. ' +
238
+ 'Free keys: https://openrouter.ai/keys',
239
+ });
240
+ }
241
+ return key;
242
+ }
243
+
244
+ function connection() {
245
+ if (client) return client;
246
+ client = new OpenAI({
247
+ apiKey: apiKey(),
248
+ baseURL: process.env.UCODE_BASE_URL || BASE_URL,
249
+ // Nemotron Ultra can think for a long time before its first token, so the
250
+ // ceiling is deliberately generous. maxRetries is 0 because ask() owns
251
+ // retrying: its attempts are narrated on screen instead of happening
252
+ // silently somewhere inside the SDK.
253
+ timeout: Number(process.env.UCODE_REQUEST_TIMEOUT_MS) || 300_000,
254
+ maxRetries: 0,
255
+ defaultHeaders: {
256
+ 'HTTP-Referer': 'https://github.com/sppideey/ucode-agent',
257
+ 'X-Title': 'ucode',
258
+ },
259
+ });
260
+ return client;
261
+ }
262
+
263
+ /** Drop the cached client so the next request picks up a changed key. */
264
+ export function resetConnection() {
265
+ client = null;
266
+ }
267
+
268
+ // ---------------------------------------------------------------------------
269
+ // Live quota, taken from whatever rate-limit headers come back
270
+ // ---------------------------------------------------------------------------
271
+
272
+ let limits = null;
273
+
274
+ export function rateLimits() {
275
+ return limits;
276
+ }
277
+
278
+ /** "1.5s", "2m59.56s", "1h2m" -> seconds */
279
+ function seconds(value) {
280
+ if (!value) return null;
281
+ const m = /^(?:(\d+(?:\.\d+)?)h)?(?:(\d+(?:\.\d+)?)m(?!s))?(?:(\d+(?:\.\d+)?)m?s)?$/
282
+ .exec(String(value).trim());
283
+ if (!m) return null;
284
+ const total = (parseFloat(m[1]) || 0) * 3600 + (parseFloat(m[2]) || 0) * 60 + (parseFloat(m[3]) || 0);
285
+ return total > 0 ? total : null;
286
+ }
287
+
288
+ function noteLimits(headers) {
289
+ if (!headers?.get) return;
290
+ const num = (name) => {
291
+ const n = Number(headers.get(name));
292
+ return Number.isFinite(n) ? n : null;
293
+ };
294
+ limits = {
295
+ requestsLimit: num('x-ratelimit-limit-requests'),
296
+ requestsRemaining: num('x-ratelimit-remaining-requests'),
297
+ requestsReset: seconds(headers.get('x-ratelimit-reset-requests')),
298
+ tokensLimit: num('x-ratelimit-limit-tokens'),
299
+ tokensRemaining: num('x-ratelimit-remaining-tokens'),
300
+ tokensReset: seconds(headers.get('x-ratelimit-reset-tokens')),
301
+ at: Date.now(),
302
+ };
303
+ }
304
+
305
+ // ---------------------------------------------------------------------------
306
+ // Neutral format -> wire format
307
+ // ---------------------------------------------------------------------------
308
+
309
+ function wireTools(tools) {
310
+ if (!tools?.length) return undefined;
311
+ return tools.map((t) => ({
312
+ type: 'function',
313
+ function: {
314
+ name: t.name,
315
+ description: t.description,
316
+ parameters: t.parameters ?? { type: 'object', properties: {} },
317
+ },
318
+ }));
319
+ }
320
+
321
+ function wireMessages(messages) {
322
+ const out = [];
323
+ for (const m of messages) {
324
+ if (m.role === 'user' && m.images?.length) {
325
+ out.push({
326
+ role: 'user',
327
+ content: [
328
+ { type: 'text', text: m.content ?? '' },
329
+ ...m.images.map((url) => ({ type: 'image_url', image_url: { url } })),
330
+ ],
331
+ });
332
+ } else if (m.role === 'system' || m.role === 'user') {
333
+ out.push({ role: m.role, content: m.content ?? '' });
334
+ } else if (m.role === 'assistant') {
335
+ const wire = { role: 'assistant', content: m.content || '' };
336
+ if (m.toolCalls?.length) {
337
+ wire.tool_calls = m.toolCalls.map((c) => ({
338
+ id: c.id,
339
+ type: 'function',
340
+ function: { name: c.name, arguments: JSON.stringify(c.args ?? {}) },
341
+ }));
342
+ }
343
+ out.push(wire);
344
+ } else if (m.role === 'tool') {
345
+ out.push({ role: 'tool', tool_call_id: m.toolCallId, content: m.content ?? '' });
346
+ }
347
+ }
348
+ return out;
349
+ }
350
+
351
+ // ---------------------------------------------------------------------------
352
+ // Turning provider errors into something a person can act on
353
+ // ---------------------------------------------------------------------------
354
+
355
+ function bodyOf(err) {
356
+ if (err?.error) return { error: err.error };
357
+ const raw = String(err?.message ?? '');
358
+ const start = raw.indexOf('{');
359
+ if (start === -1) return null;
360
+ try {
361
+ return JSON.parse(raw.slice(start));
362
+ } catch {
363
+ return null;
364
+ }
365
+ }
366
+
367
+ export function explain(err, id) {
368
+ if (err instanceof Failure) return err;
369
+
370
+ const status = err?.status ?? err?.statusCode ?? null;
371
+ const body = bodyOf(err);
372
+ const detail = body?.error?.message ?? String(err?.message ?? err);
373
+ const attempted = `asking ${modelName(id)} for a reply`;
374
+
375
+ // The useful text is often not on the error itself. undici reports a socket
376
+ // that closed mid-response as a bare `TypeError: terminated` and puts the
377
+ // real reason on `cause`, so the whole chain is matched rather than the top
378
+ // message alone — otherwise an ordinary dropped connection, which is worth
379
+ // retrying, gets reported as an unknown fault, which is not.
380
+ const chain = [err?.message, err?.code, err?.cause?.message, err?.cause?.code]
381
+ .filter(Boolean)
382
+ .join(' | ');
383
+ const raw = chain || String(err);
384
+
385
+ if (err?.name === 'AbortError' || /aborted|The operation was aborted/i.test(raw)) {
386
+ return new Failure({
387
+ kind: 'aborted',
388
+ attempted,
389
+ failed: 'The request was cancelled.',
390
+ fix: 'Send the message again when you are ready.',
391
+ cause: err,
392
+ });
393
+ }
394
+
395
+ if (status === 401 || status === 403 || /invalid[_ ]api[_ ]key/i.test(raw)) {
396
+ return new Failure({
397
+ kind: 'invalid_api_key',
398
+ attempted,
399
+ failed: `The API key was rejected (HTTP ${status ?? 401}).`,
400
+ fix:
401
+ 'Check UCODE_API_KEY in ~/.ucode/.env for a typo or trailing space, and ' +
402
+ 'confirm the key is still active in your account.',
403
+ cause: err,
404
+ });
405
+ }
406
+
407
+ if (status === 429 || /rate[_ ]limit/i.test(raw)) {
408
+ // `??` cannot be used to chain through Number(): Number(undefined) is NaN,
409
+ // which is neither null nor undefined, so it would swallow every fallback
410
+ // after it and the wait would silently never be found.
411
+ const header = err?.headers?.get?.('retry-after');
412
+ const asNumber = Number(header);
413
+ const retryAfter =
414
+ seconds(header) ??
415
+ (Number.isFinite(asNumber) && asNumber > 0 ? asNumber : null) ??
416
+ seconds(/try again in ([\dhms.]+)/i.exec(detail)?.[1]) ??
417
+ null;
418
+ // The daily cap reads "free-models-per-day-high-balance", with hyphens, and
419
+ // names its source in the metadata. It is one cap across every free model,
420
+ // so it is reported at once rather than waited on model after model.
421
+ const meta = body?.error?.metadata ?? {};
422
+ const daily = /per[- ]day|RPD|TPD|daily/i.test(`${detail} ${meta.limit_source ?? ''}`);
423
+ const resetMs = Number(meta.headers?.['X-RateLimit-Reset'] ?? err?.headers?.get?.('x-ratelimit-reset'));
424
+ const resetAt = daily && Number.isFinite(resetMs) && resetMs > Date.now() ? new Date(resetMs) : null;
425
+ const cap = Number(meta.headers?.['X-RateLimit-Limit']) || null;
426
+ const wait = Number.isFinite(retryAfter) && retryAfter
427
+ ? (retryAfter >= 60 ? `${Math.ceil(retryAfter / 60)} min` : `${Math.ceil(retryAfter)}s`)
428
+ : null;
429
+
430
+ return new Failure({
431
+ kind: 'rate_limit',
432
+ attempted,
433
+ failed: daily
434
+ ? `This key's free daily limit${cap ? ` of ${cap} requests` : ''} is used up. It covers every free model, so switching will not help.`
435
+ : `Too many requests for ${modelName(id)} just now${wait ? ` — clear in ${wait}` : ''}.`,
436
+ fix: daily
437
+ ? `It resets ${resetAt ? `at ${resetAt.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}` : 'once a day'}. ` +
438
+ 'Adding credit to your account raises the limit.'
439
+ : 'ucode waits these out on its own. Free endpoints are shared, so it usually ' +
440
+ 'clears in seconds; /model moves to a quieter one.',
441
+ detail: { retryAfter, daily, resetAt: resetAt?.getTime() ?? null },
442
+ cause: err,
443
+ });
444
+ }
445
+
446
+ // A 404 on a model in this list is almost never a bad name. It is OpenRouter
447
+ // having no upstream free to serve it at that instant, and it clears by
448
+ // itself — so it is retried rather than reported as a missing model.
449
+ if (status === 404 || /does not exist|not found|decommissioned/i.test(raw)) {
450
+ if (MODELS[id]) {
451
+ return new Failure({
452
+ kind: 'server',
453
+ attempted,
454
+ failed: `No provider was free to serve ${modelName(id)} at that moment.`,
455
+ fix: 'ucode retries this by itself. If it keeps up, /model switches.',
456
+ detail: { status },
457
+ cause: err,
458
+ });
459
+ }
460
+ return new Failure({
461
+ kind: 'bad_model',
462
+ attempted,
463
+ failed: `No model "${id}" is available to this key.`,
464
+ fix: `Run /model. ucode ships with: ${Object.keys(MODELS).join(', ')}`,
465
+ cause: err,
466
+ });
467
+ }
468
+
469
+ // Some upstreams validate tool calls themselves and reject an invented one,
470
+ // which fails the whole request. Recoverable: the loop feeds this back.
471
+ if (body?.error?.code === 'tool_use_failed' || /tool call validation failed/i.test(detail)) {
472
+ const attemptedName = /call tool '([^']+)'/.exec(detail)?.[1];
473
+ return new Failure({
474
+ kind: 'bad_tool_call',
475
+ attempted,
476
+ failed: attemptedName
477
+ ? `The model tried to call "${attemptedName}", which is not one of its tools.`
478
+ : `The model produced a tool call the provider rejected: ${detail}`,
479
+ fix: 'Use only the tools supplied with the request.',
480
+ detail: { attemptedName },
481
+ cause: err,
482
+ });
483
+ }
484
+
485
+ if (status === 400) {
486
+ const noTools = /tool calling.*not supported/i.test(detail);
487
+ return new Failure({
488
+ kind: noTools ? 'no_tool_support' : 'bad_request',
489
+ attempted,
490
+ failed: noTools
491
+ ? `${modelName(id)} cannot call tools, which ucode needs for every task.`
492
+ : `The request was rejected as malformed (HTTP 400): ${detail}`,
493
+ fix: noTools
494
+ ? 'Run /model and pick another one.'
495
+ : 'The conversation has something in it the provider will not accept. /new starts a fresh one.',
496
+ cause: err,
497
+ });
498
+ }
499
+
500
+ if (status === 413 || /too large|context.*length/i.test(detail)) {
501
+ return new Failure({
502
+ kind: 'too_large',
503
+ attempted,
504
+ failed: `The conversation no longer fits in ${modelName(id)}: ${detail}`,
505
+ fix: 'Run /new for a fresh session, or lower UCODE_MAX_CONTEXT_TOKENS so ucode folds older turns away sooner.',
506
+ cause: err,
507
+ });
508
+ }
509
+
510
+ // OpenRouter drops a request when the upstream goes quiet on it. That is the
511
+ // ordinary failure mode of a busy free endpoint, and of a big reasoning model
512
+ // that spends a long time thinking before its first token. Nothing was
513
+ // generated, so retrying is safe — and ask() does it before anyone notices.
514
+ if (
515
+ status === 408 || status === 504 || status === 524 || status === 522 ||
516
+ err?.name === 'APIConnectionTimeoutError' ||
517
+ /idle timeout|timed out|timeout/i.test(detail) || /idle timeout|timed out/i.test(raw)
518
+ ) {
519
+ return new Failure({
520
+ kind: 'timeout',
521
+ attempted,
522
+ failed: `${modelName(id)} sent nothing back in time — the provider dropped the request.`,
523
+ fix:
524
+ 'Free endpoints stall under load, and the largest reasoning models are the ' +
525
+ 'first to. ucode already retried. If it keeps happening, /model to Nemotron ' +
526
+ '3.5 Lightning or North Mini Code, which answer sooner.',
527
+ detail: { status },
528
+ cause: err,
529
+ });
530
+ }
531
+
532
+ if (status >= 500 || /internal|unavailable|overloaded/i.test(raw)) {
533
+ return new Failure({
534
+ kind: 'server',
535
+ attempted,
536
+ failed: `The provider returned HTTP ${status}. That is their side, not yours.`,
537
+ fix: 'Wait a few seconds and send again. If it persists, /model to another one.',
538
+ cause: err,
539
+ });
540
+ }
541
+
542
+ // `terminated` and `premature close` are what a connection dropped part way
543
+ // through a reply looks like. Nothing usable arrived, so it is safe to send
544
+ // again — and on a free endpoint under load it happens often enough that
545
+ // treating it as fatal would be the single most visible flaw in the agent.
546
+ if (
547
+ /ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|ETIMEDOUT|EPIPE|network|fetch failed|socket hang up|terminated|premature close|other side closed|UND_ERR/i.test(raw) ||
548
+ err?.name === 'APIConnectionError' ||
549
+ (err instanceof TypeError && /terminated/i.test(raw))
550
+ ) {
551
+ return new Failure({
552
+ kind: 'network',
553
+ attempted,
554
+ failed: `The connection to the model dropped: ${raw}`,
555
+ fix:
556
+ 'ucode retries this by itself. If it keeps happening, check your connection, ' +
557
+ 'VPN and any corporate proxy (HTTPS_PROXY) — or /model to a lighter one, since ' +
558
+ 'a long think on a busy free endpoint is the usual cause.',
559
+ cause: err,
560
+ });
561
+ }
562
+
563
+ return new Failure({
564
+ kind: 'unknown',
565
+ attempted,
566
+ failed: detail,
567
+ fix: 'Retry once. If it repeats, run ucode --debug for the full trace.',
568
+ cause: err,
569
+ });
570
+ }
571
+
572
+ const pause = (ms) => new Promise((r) => setTimeout(r, ms));
573
+
574
+ // ---------------------------------------------------------------------------
575
+ // The one call
576
+ // ---------------------------------------------------------------------------
577
+
578
+ /**
579
+ * Send a conversation and get a normalized reply.
580
+ *
581
+ * @param {Array} messages neutral messages
582
+ * @param {Array} [tools] neutral tool definitions
583
+ * @param {object} [opts] { model, temperature, signal, maxOutputTokens,
584
+ * reasoning, attempts, onText, onThinking, onWait }
585
+ */
586
+ export async function ask(messages, tools = [], opts = {}) {
587
+ const id = opts.model || current;
588
+
589
+ const request = {
590
+ model: id,
591
+ messages: wireMessages(messages),
592
+ // Ask for the working. Without it OpenRouter withholds reasoning entirely,
593
+ // and on a reasoning model that *is* the whole reply until the very end:
594
+ // the socket sits silent for the length of the think, the screen shows
595
+ // nothing, and the provider eventually drops the request as idle. Asking
596
+ // for it fixes the blank screen and the dropped request together. Models
597
+ // that do not reason ignore the flag.
598
+ include_reasoning: true,
599
+ };
600
+
601
+ const wired = wireTools(tools);
602
+ if (wired) {
603
+ request.tools = wired;
604
+ request.tool_choice = 'auto';
605
+ }
606
+ if (opts.temperature !== undefined) request.temperature = opts.temperature;
607
+ if (opts.maxOutputTokens) request.max_tokens = opts.maxOutputTokens;
608
+ if (opts.reasoning) request.reasoning = opts.reasoning;
609
+
610
+ // A side call (the design review) passes fewer: it is better skipped than
611
+ // waited on through a string of rate-limit pauses.
612
+ const attempts = opts.attempts ?? 4;
613
+ let problem;
614
+
615
+ // Text already on screen cannot be unprinted, so a stream is only safe to
616
+ // retry while it is still silent. Every timeout worth retrying happens
617
+ // before the first token, so this costs nothing in practice.
618
+ let printed = 0;
619
+ const callOpts = opts.onText
620
+ ? { ...opts, onText: (d) => { printed += d.length; opts.onText(d); } }
621
+ : opts;
622
+
623
+ for (let attempt = 1; attempt <= attempts; attempt++) {
624
+ try {
625
+ if (opts.onText) return await streamed(request, callOpts, id);
626
+ const { data, response } = await connection().chat.completions
627
+ .create(request, { signal: opts.signal })
628
+ .withResponse();
629
+ noteLimits(response?.headers);
630
+ return normalize(data, id);
631
+ } catch (err) {
632
+ noteLimits(err?.headers);
633
+ problem = explain(err, id);
634
+
635
+ // A per-minute limit is a wait, not a failure. Sit it out rather than
636
+ // making the user retype their message. Free endpoints often refuse
637
+ // without saying how long to wait, so when there is no retry-after the
638
+ // pauses grow on their own — 5s, 10s, 20s — and only then does the
639
+ // error go up to the loop, which moves to another model.
640
+ const told = problem.detail?.retryAfter;
641
+ const wait = Number.isFinite(told) && told > 0 && told <= 90 ? told : RATE_LIMIT_BACKOFF[attempt - 1];
642
+ if (
643
+ problem.kind === 'rate_limit' && !problem.detail?.daily &&
644
+ wait && attempt < attempts && printed === 0 && !opts.signal?.aborted
645
+ ) {
646
+ const until = Date.now() + wait * 1000;
647
+ while (Date.now() < until && !opts.signal?.aborted) {
648
+ opts.onWait?.(`rate limited — resuming in ${Math.ceil((until - Date.now()) / 1000)}s`);
649
+ await pause(Math.min(1000, until - Date.now()));
650
+ }
651
+ if (opts.signal?.aborted) break;
652
+ continue;
653
+ }
654
+
655
+ const worthRetrying =
656
+ problem.kind === 'server' || problem.kind === 'network' || problem.kind === 'timeout';
657
+ if (!worthRetrying || attempt === attempts || opts.signal?.aborted) break;
658
+ if (printed > 0) break; // half an answer is on screen; do not print it twice
659
+
660
+ // A stalled provider needs longer to come back than a dropped socket
661
+ // does, and the wait is narrated so a slow turn never looks like a hang.
662
+ const backoff = problem.kind === 'timeout'
663
+ ? 1500 * 2 ** (attempt - 1)
664
+ : 400 * 2 ** (attempt - 1);
665
+ opts.onWait?.(
666
+ `${problem.kind === 'timeout' ? 'provider stalled' : 'connection failed'} — ` +
667
+ `retrying (${attempt + 1}/${attempts})`
668
+ );
669
+ await pause(backoff);
670
+ }
671
+ }
672
+
673
+ throw problem;
674
+ }
675
+
676
+ /** Collect a streamed reply, handing deltas out as they land. */
677
+ async function streamed(request, opts, id) {
678
+ const { data: stream, response } = await connection().chat.completions
679
+ .create(
680
+ { ...request, stream: true, stream_options: { include_usage: true } },
681
+ { signal: opts.signal }
682
+ )
683
+ .withResponse();
684
+ noteLimits(response?.headers);
685
+
686
+ let text = '';
687
+ let reasoning = '';
688
+ let finishReason = 'stop';
689
+ let usage = null;
690
+ const partial = new Map();
691
+ const handed = new Set();
692
+ let highest = -1;
693
+
694
+ for await (const chunk of stream) {
695
+ if (opts.signal?.aborted) break;
696
+ if (chunk.usage) usage = chunk.usage;
697
+
698
+ const choice = chunk.choices?.[0];
699
+ if (!choice) continue;
700
+ if (choice.finish_reason) finishReason = choice.finish_reason;
701
+ const delta = choice.delta ?? {};
702
+
703
+ // Reasoning arrives on a separate channel: `reasoning` on OpenRouter,
704
+ // `reasoning_content` on some upstreams.
705
+ const thinking = delta.reasoning ?? delta.reasoning_content;
706
+ if (thinking) {
707
+ reasoning += thinking;
708
+ opts.onThinking?.(thinking);
709
+ }
710
+
711
+ if (delta.content) {
712
+ text += delta.content;
713
+ opts.onText(delta.content);
714
+ }
715
+
716
+ // A tool call's name and arguments arrive across several chunks, keyed by
717
+ // index, so they are stitched back together here.
718
+ for (const call of delta.tool_calls ?? []) {
719
+ // Calls arrive one after another, so the first chunk of call N means
720
+ // every call before it is complete. Those are handed over at once, and
721
+ // the caller can start running them while the rest are still being
722
+ // written — the reply streaming and the tools working overlap.
723
+ if (opts.onToolCall && call.index > highest) {
724
+ for (const [index, slot] of partial) {
725
+ if (index < call.index && !handed.has(index)) {
726
+ handed.add(index);
727
+ opts.onToolCall(readCall({ id: slot.id || `call_${index}`, name: slot.name, raw: slot.args }));
728
+ }
729
+ }
730
+ highest = call.index;
731
+ }
732
+
733
+ const slot = partial.get(call.index) ?? { id: '', name: '', args: '' };
734
+ if (call.id) slot.id = call.id;
735
+ if (call.function?.name) slot.name += call.function.name;
736
+ if (call.function?.arguments) slot.args += call.function.arguments;
737
+ partial.set(call.index, slot);
738
+
739
+ // A whole app arrives as one enormous arguments string that takes a
740
+ // minute or two to write. Handing it over as it grows is what lets the
741
+ // caller say which file is being written right now, instead of showing
742
+ // a spinner that has meant nothing for ninety seconds.
743
+ if (call.function?.arguments) opts.onToolArgs?.({ index: call.index, name: slot.name, args: slot.args });
744
+ }
745
+ }
746
+
747
+ const toolCalls = [];
748
+ for (const [index, slot] of partial) {
749
+ toolCalls.push(readCall({ id: slot.id || `call_${index}`, name: slot.name, raw: slot.args, cutOff: finishReason === 'length' }));
750
+ }
751
+
752
+ return {
753
+ text: text.trim(),
754
+ reasoning: reasoning.trim(),
755
+ toolCalls,
756
+ usage: {
757
+ promptTokens: usage?.prompt_tokens ?? 0,
758
+ outputTokens: usage?.completion_tokens ?? 0,
759
+ totalTokens: usage?.total_tokens ?? 0,
760
+ },
761
+ finishReason,
762
+ model: id,
763
+ };
764
+ }
765
+
766
+ /**
767
+ * Recover the files from a file-write call whose JSON will not parse.
768
+ *
769
+ * The usual cause is a double quote inside the code that the model forgot to
770
+ * escape — `className="flex"` — which ends the JSON string early. No general
771
+ * repair can know which quote was meant, but a file write has a fixed shape:
772
+ * "path", then "content", then either the next file or the end. Splitting on
773
+ * that shape and escaping the stray quotes gets every file back.
774
+ */
775
+ /**
776
+ * Which calls can be rebuilt out of broken JSON.
777
+ *
778
+ * All three carry file contents — hundreds of lines of HTML, CSS and
779
+ * JavaScript escaped into a JSON string — which is the one argument shape a
780
+ * model gets wrong often enough to matter. Everything else is short enough
781
+ * that a parse failure is a real mistake, worth reporting rather than guessing
782
+ * around.
783
+ */
784
+ const SALVAGEABLE = new Set(['write_file', 'batch_write', 'create_app']);
785
+
786
+ /**
787
+ * The plain string arguments sitting beside a files array, read off the raw
788
+ * text when the object as a whole will not parse.
789
+ *
790
+ * Only the keys create_app needs, and only from before the files begin, so a
791
+ * "name" belonging to something nested inside a file cannot be mistaken for
792
+ * the app's own.
793
+ */
794
+ function scalarArgs(text) {
795
+ const at = text.search(/"files"\s*:/);
796
+ const head = at > 0 ? text.slice(0, at) : text;
797
+ const out = {};
798
+ for (const key of ['folder', 'name', 'description', 'template', 'design']) {
799
+ const hit = new RegExp(`"${key}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`).exec(head);
800
+ if (hit) out[key] = hit[1].replace(/\\(["\\/])/g, '$1');
801
+ }
802
+ return out;
803
+ }
804
+
798
805
  /**
799
806
  * Rebuild the edits out of a broken edit_file or edit_files call.
800
807
  *
@@ -858,78 +865,78 @@ export function groupEdits(edits) {
858
865
  return [...byPath].map(([path, list]) => ({ path, edits: list }));
859
866
  }
860
867
 
861
- export function salvageWrites(text) {
862
- const heads = [...text.matchAll(/"path"\s*:\s*"((?:[^"\\]|\\.)*)"\s*,\s*"content"\s*:\s*"/g)];
863
- if (!heads.length) return null;
864
-
865
- const files = [];
866
- for (let i = 0; i < heads.length; i++) {
867
- const from = heads[i].index + heads[i][0].length;
868
- const to = i + 1 < heads.length ? heads[i + 1].index : text.length;
869
- // The string ends at the last quote that is followed by nothing but JSON
870
- // punctuation — `"}, {`, or `"}}, {` when the model added a brace, or `"}]}`.
871
- const body = text.slice(from, to).replace(/"[\s,{}[\]]*$/, '');
872
- const content = unescapeLoose(body);
873
- const pathValue = unescapeLoose(heads[i][1]);
874
- if (!pathValue || !content) return null; // not the shape we thought — leave it an honest error
875
- files.push({ path: pathValue, content });
876
- }
877
- return files.length ? files : null;
878
- }
879
-
880
- /**
881
- * Decode a JSON string body the forgiving way: the standard escapes are
882
- * honoured, and everything JSON would reject — a raw line break, a tab, a stray
883
- * quote, an escape JSON does not know — is kept as the character it plainly is.
884
- */
885
- function unescapeLoose(s) {
886
- const simple = { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', '"': '"', '\\': '\\', '/': '/' };
887
- let out = '';
888
- for (let i = 0; i < s.length; i++) {
889
- const c = s[i];
890
- if (c !== '\\' || i === s.length - 1) { out += c; continue; }
891
- const next = s[++i];
892
- if (next === 'u' && /^[0-9a-fA-F]{4}$/.test(s.slice(i + 1, i + 5))) {
893
- out += String.fromCharCode(parseInt(s.slice(i + 1, i + 5), 16));
894
- i += 4;
895
- } else {
896
- out += simple[next] ?? next;
897
- }
898
- }
899
- return out;
900
- }
901
-
902
- /**
903
- * Parse one tool call's arguments.
904
- *
905
- * A parse error is recorded on the call rather than thrown. The loop hands it
906
- * back to the model, which usually fixes its own JSON on the next step —
907
- * cheaper than failing the whole turn over a stray comma.
908
- */
909
- export function readCall({ id, name, raw, cutOff = false }) {
910
- const call = { id, name, args: {} };
911
- const text = String(raw ?? '').trim();
912
- if (!text) return call;
913
- try {
914
- const parsed = JSON.parse(text);
915
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) call.args = parsed;
916
- else call.parseError = `arguments must be a JSON object, got ${Array.isArray(parsed) ? 'array' : typeof parsed}`;
917
- } catch (err) {
918
- // A missing comma or a stray control character in a 3,000-token
919
- // batch_write used to throw the whole step away — half a minute of output
920
- // discarded over one character. Repair the usual slips instead. Never when
921
- // the reply was cut off at the output limit, though: repairing that would
922
- // close the string and quietly write half a file.
923
- if (!cutOff) {
924
- try {
925
- const fixed = JSON.parse(jsonrepair(text));
926
- if (fixed && typeof fixed === 'object' && !Array.isArray(fixed)) {
927
- call.args = fixed;
928
- call.repaired = true;
929
- return call;
930
- }
931
- } catch { /* beyond general repair — try the file-write shape next */ }
932
-
868
+ export function salvageWrites(text) {
869
+ const heads = [...text.matchAll(/"path"\s*:\s*"((?:[^"\\]|\\.)*)"\s*,\s*"content"\s*:\s*"/g)];
870
+ if (!heads.length) return null;
871
+
872
+ const files = [];
873
+ for (let i = 0; i < heads.length; i++) {
874
+ const from = heads[i].index + heads[i][0].length;
875
+ const to = i + 1 < heads.length ? heads[i + 1].index : text.length;
876
+ // The string ends at the last quote that is followed by nothing but JSON
877
+ // punctuation — `"}, {`, or `"}}, {` when the model added a brace, or `"}]}`.
878
+ const body = text.slice(from, to).replace(/"[\s,{}[\]]*$/, '');
879
+ const content = unescapeLoose(body);
880
+ const pathValue = unescapeLoose(heads[i][1]);
881
+ if (!pathValue || !content) return null; // not the shape we thought — leave it an honest error
882
+ files.push({ path: pathValue, content });
883
+ }
884
+ return files.length ? files : null;
885
+ }
886
+
887
+ /**
888
+ * Decode a JSON string body the forgiving way: the standard escapes are
889
+ * honoured, and everything JSON would reject — a raw line break, a tab, a stray
890
+ * quote, an escape JSON does not know — is kept as the character it plainly is.
891
+ */
892
+ function unescapeLoose(s) {
893
+ const simple = { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', '"': '"', '\\': '\\', '/': '/' };
894
+ let out = '';
895
+ for (let i = 0; i < s.length; i++) {
896
+ const c = s[i];
897
+ if (c !== '\\' || i === s.length - 1) { out += c; continue; }
898
+ const next = s[++i];
899
+ if (next === 'u' && /^[0-9a-fA-F]{4}$/.test(s.slice(i + 1, i + 5))) {
900
+ out += String.fromCharCode(parseInt(s.slice(i + 1, i + 5), 16));
901
+ i += 4;
902
+ } else {
903
+ out += simple[next] ?? next;
904
+ }
905
+ }
906
+ return out;
907
+ }
908
+
909
+ /**
910
+ * Parse one tool call's arguments.
911
+ *
912
+ * A parse error is recorded on the call rather than thrown. The loop hands it
913
+ * back to the model, which usually fixes its own JSON on the next step —
914
+ * cheaper than failing the whole turn over a stray comma.
915
+ */
916
+ export function readCall({ id, name, raw, cutOff = false }) {
917
+ const call = { id, name, args: {} };
918
+ const text = String(raw ?? '').trim();
919
+ if (!text) return call;
920
+ try {
921
+ const parsed = JSON.parse(text);
922
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) call.args = parsed;
923
+ else call.parseError = `arguments must be a JSON object, got ${Array.isArray(parsed) ? 'array' : typeof parsed}`;
924
+ } catch (err) {
925
+ // A missing comma or a stray control character in a 3,000-token
926
+ // batch_write used to throw the whole step away — half a minute of output
927
+ // discarded over one character. Repair the usual slips instead. Never when
928
+ // the reply was cut off at the output limit, though: repairing that would
929
+ // close the string and quietly write half a file.
930
+ if (!cutOff) {
931
+ try {
932
+ const fixed = JSON.parse(jsonrepair(text));
933
+ if (fixed && typeof fixed === 'object' && !Array.isArray(fixed)) {
934
+ call.args = fixed;
935
+ call.repaired = true;
936
+ return call;
937
+ }
938
+ } catch { /* beyond general repair — try the file-write shape next */ }
939
+
933
940
  if (name === 'edit_file' || name === 'edit_files' || name === 'multi_edit') {
934
941
  const edits = salvageEdits(text);
935
942
  if (edits) {
@@ -942,58 +949,58 @@ export function readCall({ id, name, raw, cutOff = false }) {
942
949
  }
943
950
  }
944
951
 
945
- const salvaged = SALVAGEABLE.has(name) ? salvageWrites(text) : null;
946
- if (salvaged) {
947
- if (name === 'write_file') call.args = salvaged[0];
948
- // create_app carries the app in the same { path, content } shape, with
949
- // a few plain strings beside it. Losing the entire call because one of
950
- // several hundred lines of HTML held a raw newline is how a build ends
951
- // with no files at all — which is what it did: refused three times,
952
- // the folder never created, the turn over in sixty-six seconds having
953
- // produced nothing. The scalars are read back off the same text.
954
- else if (name === 'create_app') call.args = { ...scalarArgs(text), files: salvaged };
955
- else call.args = { files: salvaged };
956
- call.repaired = true;
957
- return call;
958
- }
959
- }
960
- call.parseError = `${err.message} — the raw arguments were: ${text.slice(0, 300)}`;
961
- }
962
- return call;
963
- }
964
-
965
- function normalize(data, id) {
966
- const choice = data?.choices?.[0];
967
- const message = choice?.message ?? {};
968
-
969
- const toolCalls = (message.tool_calls ?? []).map((c) =>
970
- readCall({ id: c.id, name: c.function?.name, raw: c.function?.arguments, cutOff: choice?.finish_reason === 'length' })
971
- );
972
-
973
- const u = data?.usage ?? {};
974
- const finishReason = choice?.finish_reason ?? 'stop';
975
- const text = (message.content ?? '').trim();
976
-
977
- if (!text && toolCalls.length === 0 && finishReason === 'length') {
978
- throw new Failure({
979
- kind: 'no_content',
980
- attempted: `asking ${modelName(id)} for a reply`,
981
- failed: 'The reply hit the output limit before producing anything at all.',
982
- fix: 'Ask for something shorter, or split the task into steps.',
983
- detail: { finishReason },
984
- });
985
- }
986
-
987
- return {
988
- text,
989
- reasoning: (message.reasoning ?? '').trim(),
990
- toolCalls,
991
- usage: {
992
- promptTokens: u.prompt_tokens ?? 0,
993
- outputTokens: u.completion_tokens ?? 0,
994
- totalTokens: u.total_tokens ?? 0,
995
- },
996
- finishReason,
997
- model: id,
998
- };
999
- }
952
+ const salvaged = SALVAGEABLE.has(name) ? salvageWrites(text) : null;
953
+ if (salvaged) {
954
+ if (name === 'write_file') call.args = salvaged[0];
955
+ // create_app carries the app in the same { path, content } shape, with
956
+ // a few plain strings beside it. Losing the entire call because one of
957
+ // several hundred lines of HTML held a raw newline is how a build ends
958
+ // with no files at all — which is what it did: refused three times,
959
+ // the folder never created, the turn over in sixty-six seconds having
960
+ // produced nothing. The scalars are read back off the same text.
961
+ else if (name === 'create_app') call.args = { ...scalarArgs(text), files: salvaged };
962
+ else call.args = { files: salvaged };
963
+ call.repaired = true;
964
+ return call;
965
+ }
966
+ }
967
+ call.parseError = `${err.message} — the raw arguments were: ${text.slice(0, 300)}`;
968
+ }
969
+ return call;
970
+ }
971
+
972
+ function normalize(data, id) {
973
+ const choice = data?.choices?.[0];
974
+ const message = choice?.message ?? {};
975
+
976
+ const toolCalls = (message.tool_calls ?? []).map((c) =>
977
+ readCall({ id: c.id, name: c.function?.name, raw: c.function?.arguments, cutOff: choice?.finish_reason === 'length' })
978
+ );
979
+
980
+ const u = data?.usage ?? {};
981
+ const finishReason = choice?.finish_reason ?? 'stop';
982
+ const text = (message.content ?? '').trim();
983
+
984
+ if (!text && toolCalls.length === 0 && finishReason === 'length') {
985
+ throw new Failure({
986
+ kind: 'no_content',
987
+ attempted: `asking ${modelName(id)} for a reply`,
988
+ failed: 'The reply hit the output limit before producing anything at all.',
989
+ fix: 'Ask for something shorter, or split the task into steps.',
990
+ detail: { finishReason },
991
+ });
992
+ }
993
+
994
+ return {
995
+ text,
996
+ reasoning: (message.reasoning ?? '').trim(),
997
+ toolCalls,
998
+ usage: {
999
+ promptTokens: u.prompt_tokens ?? 0,
1000
+ outputTokens: u.completion_tokens ?? 0,
1001
+ totalTokens: u.total_tokens ?? 0,
1002
+ },
1003
+ finishReason,
1004
+ model: id,
1005
+ };
1006
+ }