@namzu/openrouter 3.1.2 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ProviderRequestError, isCallerAbortError, isProviderRequestError, providerHttpError, providerVendorError, } from '@namzu/sdk';
2
2
  import { attributionHeaders } from '@namzu/sdk';
3
+ import { NOOP_LOGGER } from '@namzu/sdk';
3
4
  /**
4
5
  * The words a proxied backend's own `native_finish_reason` uses for "the
5
6
  * model's context window, not its output-token budget, is what ran out" —
@@ -147,6 +148,9 @@ function applyCacheBreakpoints(source, formatted) {
147
148
  return;
148
149
  }
149
150
  }
151
+ function routeOf(params) {
152
+ return params.providerRoute ?? { providerId: 'openrouter', model: params.model, chainIndex: 0 };
153
+ }
150
154
  const OPENROUTER_BASE_URL = process.env.OPENROUTER_BASE_URL ?? 'https://openrouter.ai/api/v1';
151
155
  /**
152
156
  * A rate OpenRouter published for a model, or nothing.
@@ -168,6 +172,27 @@ function pricePerMillion(raw) {
168
172
  const parsed = Number.parseFloat(raw);
169
173
  return Number.isFinite(parsed) ? parsed * 1_000_000 : undefined;
170
174
  }
175
+ /**
176
+ * What the request cost, as OpenRouter reports it, or `undefined`.
177
+ *
178
+ * `usage.cost` is "the total charged to your account", on every response
179
+ * without being asked (the documented `usage: { include: true }` is now a
180
+ * no-op, so this driver does not send it). A request on the caller's own
181
+ * upstream key (BYOK) is billed twice over: the upstream bills the caller
182
+ * directly and `cost` is only OpenRouter's share, so the upstream figure the
183
+ * response also carries is added, or the report would understate what the
184
+ * person spent. A missing, null or non-numeric `cost` is "not reported", never
185
+ * zero; a reported `0` (a free model) is a real zero.
186
+ */
187
+ function reportedCost(raw) {
188
+ const charged = raw.cost;
189
+ if (typeof charged !== 'number' || !Number.isFinite(charged) || charged < 0)
190
+ return undefined;
191
+ const upstream = raw.cost_details?.upstream_inference_cost;
192
+ return raw.is_byok === true && typeof upstream === 'number' && Number.isFinite(upstream)
193
+ ? charged + Math.max(0, upstream)
194
+ : charged;
195
+ }
171
196
  /**
172
197
  * The reasoning breakdown, when the vendor reports one.
173
198
  *
@@ -189,13 +214,15 @@ function parseUsage(raw) {
189
214
  };
190
215
  }
191
216
  const reasoningTokens = raw.completion_tokens_details?.reasoning_tokens;
217
+ const cost = reportedCost(raw);
192
218
  return {
193
219
  promptTokens: raw.prompt_tokens,
194
220
  completionTokens: raw.completion_tokens,
195
221
  totalTokens: raw.total_tokens,
196
222
  cachedTokens: raw.prompt_tokens_details?.cached_tokens ?? raw.cache_read_input_tokens ?? 0,
197
- cacheWriteTokens: raw.cache_creation_input_tokens ?? 0,
223
+ cacheWriteTokens: raw.cache_creation_input_tokens ?? raw.prompt_tokens_details?.cache_write_tokens ?? 0,
198
224
  ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
225
+ ...(cost !== undefined ? { reportedCostUsd: cost } : {}),
199
226
  };
200
227
  }
201
228
  /**
@@ -235,29 +262,204 @@ function parseReasoning(details, flat) {
235
262
  ? [{ index: 0, type: 'thinking', text: flat }]
236
263
  : [];
237
264
  }
265
+ function sameRoute(left, right) {
266
+ return (left.providerId === right.providerId &&
267
+ left.model === right.model &&
268
+ left.chainIndex === right.chainIndex);
269
+ }
270
+ function isReplayState(value) {
271
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
272
+ return false;
273
+ const state = value;
274
+ const route = state.route;
275
+ if (state.kind !== 'namzu-openrouter-reasoning' ||
276
+ state.version !== 1 ||
277
+ typeof route !== 'object' ||
278
+ route === null ||
279
+ typeof route.providerId !== 'string' ||
280
+ typeof route.model !== 'string' ||
281
+ !Number.isSafeInteger(route.chainIndex)) {
282
+ return false;
283
+ }
284
+ const hasDetails = Array.isArray(state.details) &&
285
+ state.details.length > 0 &&
286
+ state.details.every((d) => typeof d === 'object' && d !== null && !Array.isArray(d));
287
+ const hasFlat = typeof state.reasoning === 'string' && state.reasoning.length > 0;
288
+ return hasDetails !== hasFlat;
289
+ }
290
+ /**
291
+ * Fold the `reasoning_details` fragments of a stream into the entries the
292
+ * complete response held: fragments of one `index` are one entry, its text
293
+ * (or summary, or encrypted data) concatenated in arrival order, every other
294
+ * field kept as first sent and a signature kept when one arrives.
295
+ */
296
+ class ReasoningDetailsAccumulator {
297
+ entries = new Map();
298
+ flat = '';
299
+ addFlat(text) {
300
+ if (typeof text === 'string')
301
+ this.flat += text;
302
+ }
303
+ add(fragments) {
304
+ for (const [position, fragment] of (fragments ?? []).entries()) {
305
+ if (typeof fragment !== 'object' || fragment === null)
306
+ continue;
307
+ const raw = fragment;
308
+ const index = typeof raw.index === 'number' ? raw.index : position;
309
+ const entry = this.entries.get(index);
310
+ if (!entry) {
311
+ this.entries.set(index, { ...raw });
312
+ continue;
313
+ }
314
+ for (const [key, value] of Object.entries(raw)) {
315
+ if (key === 'text' || key === 'summary' || key === 'data') {
316
+ if (typeof value === 'string') {
317
+ entry[key] = (typeof entry[key] === 'string' ? entry[key] : '') + value;
318
+ }
319
+ }
320
+ else if (key === 'signature') {
321
+ if (typeof value === 'string' && value.length > 0)
322
+ entry[key] = value;
323
+ }
324
+ else if (entry[key] === undefined) {
325
+ entry[key] = value;
326
+ }
327
+ }
328
+ }
329
+ }
330
+ get hasAny() {
331
+ return this.entries.size > 0 || this.flat.length > 0;
332
+ }
333
+ state(route) {
334
+ if (this.entries.size > 0) {
335
+ const details = [...this.entries.entries()].sort((a, b) => a[0] - b[0]).map(([, v]) => v);
336
+ return { kind: 'namzu-openrouter-reasoning', version: 1, route, details };
337
+ }
338
+ return this.flat.length > 0
339
+ ? { kind: 'namzu-openrouter-reasoning', version: 1, route, reasoning: this.flat }
340
+ : undefined;
341
+ }
342
+ }
343
+ /** The text and the opaque payloads the kernel's own blocks would hold for a state. */
344
+ function durableFingerprint(state) {
345
+ if (state.details === undefined)
346
+ return JSON.stringify([state.reasoning, '']);
347
+ let text = '';
348
+ let encrypted = '';
349
+ for (const d of state.details) {
350
+ if (d.type === 'reasoning.encrypted') {
351
+ if (typeof d.data === 'string')
352
+ encrypted += d.data;
353
+ }
354
+ else if (typeof d.text === 'string') {
355
+ text += d.text;
356
+ }
357
+ }
358
+ return JSON.stringify([text, encrypted]);
359
+ }
360
+ function blocksFingerprint(blocks) {
361
+ let text = '';
362
+ let encrypted = '';
363
+ for (const b of blocks ?? []) {
364
+ if (b.type === 'redacted_thinking')
365
+ encrypted += b.encrypted ?? '';
366
+ else
367
+ text += b.text ?? '';
368
+ }
369
+ return JSON.stringify([text, encrypted]);
370
+ }
238
371
  /**
239
- * The effort levels this wire can carry.
372
+ * The reasoning to send back with an assistant message, or nothing.
240
373
  *
241
- * OpenRouter's unified `reasoning.effort` publishes exactly these. The SDK's
242
- * `max` and `ultra` are OpenAI-model-specific names with no equivalent here,
243
- * and a driver must not send one and hope: an effort that arrives as a
244
- * different depth is indistinguishable from one that was honoured.
374
+ * Only from a validated envelope of the same route whose content still matches
375
+ * the stored reasoning (request repair or compaction that rewrote the blocks
376
+ * leaves the envelope behind, and a mismatch means history-neutral). Names
377
+ * alone never prove it.
378
+ */
379
+ function replayFor(message, target) {
380
+ const source = message.source;
381
+ if (!source || source.type !== 'model' || !sameRoute(source, target))
382
+ return undefined;
383
+ const state = source.replayState;
384
+ if (!isReplayState(state) || !sameRoute(state.route, target))
385
+ return undefined;
386
+ if (durableFingerprint(state) !== blocksFingerprint(message.reasoning))
387
+ return undefined;
388
+ return state.details !== undefined
389
+ ? { reasoning_details: state.details }
390
+ : { reasoning: state.reasoning };
391
+ }
392
+ /**
393
+ * Index of the first message of the current turn: the last user message that
394
+ * is not host-generated context. Reasoning is sent back for the assistant
395
+ * messages from there on, which is what the guide asks for between a tool
396
+ * call and the model's next step; an earlier turn is history and is not
397
+ * resent. Answers 0 when the conversation holds no such user message.
245
398
  */
246
- const OPENROUTER_REASONING_EFFORT = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh'];
399
+ function currentTurnStart(messages) {
400
+ for (let i = messages.length - 1; i >= 0; i--) {
401
+ const msg = messages[i];
402
+ if (msg?.role === 'user' && msg.source?.type !== 'runtime-context')
403
+ return i;
404
+ }
405
+ return 0;
406
+ }
407
+ /**
408
+ * Whether a model is one whose vendor refuses a forced tool choice while it
409
+ * reasons: the DeepSeek V4 generation and its reasoner line. Its own API
410
+ * answers 400 "Thinking mode does not support this tool_choice". Matched on
411
+ * the id's bare name (a `deepseek/` prefix, an OpenRouter `~` alias marker and a
412
+ * `:tag` removed), never by substring, so a derivative is not swept in.
413
+ */
414
+ function refusesForcedChoiceWhileReasoning(model) {
415
+ const afterSlash = model.replace(/^~/, '').toLowerCase();
416
+ const bare = afterSlash.slice(afterSlash.lastIndexOf('/') + 1).split(':')[0] ?? '';
417
+ return /^deepseek-(v([4-9]|\d{2,})(\.|-|$)|r\d+(-|$)|reasoner(-|$)|(flash|pro)(-|$))/.test(bare);
418
+ }
419
+ /** Highest first. What a request for `max` or `ultra` falls down through. */
420
+ const EFFORT_DESCENDING = ['max', 'xhigh', 'high', 'medium', 'low', 'minimal'];
421
+ /**
422
+ * The level that stands in for an SDK effort the wire may not carry.
423
+ *
424
+ * `max` and `ultra` are legal SDK values, so refusing them stopped a run for a
425
+ * setting nobody did wrong. Each asks for the deepest reasoning the model
426
+ * offers, so each resolves to the highest level in the model's own list
427
+ * (`supported_efforts` in the `/models` listing), never `none`. When the
428
+ * listing could not be read or does not carry a list for the model, the
429
+ * highest level the unified `reasoning.effort` documents for every model, `xhigh`, is sent: a level the
430
+ * vendor accepts, one step short of what was asked for rather than a failure.
431
+ * Every other level is sent as given.
432
+ */
433
+ function carriedEffort(effort, supported) {
434
+ if (effort !== 'max' && effort !== 'ultra')
435
+ return effort;
436
+ if (!supported)
437
+ return 'xhigh';
438
+ return EFFORT_DESCENDING.find((level) => supported.includes(level)) ?? 'xhigh';
439
+ }
440
+ /** The least thinking budget a budgeted model accepts. */
441
+ const MIN_THINKING_BUDGET = 1024;
442
+ /**
443
+ * A thinking budget has to leave room for the answer: a budget at or above the
444
+ * request's output limit is refused by the host. With both numbers present and
445
+ * a limit above 1024, the budget is brought under the limit (and up to 1024 if
446
+ * it was lower); in every other case it is sent as given.
447
+ */
448
+ function fitBudget(budget, maxTokens) {
449
+ if (budget === undefined || maxTokens === undefined || maxTokens <= MIN_THINKING_BUDGET) {
450
+ return budget;
451
+ }
452
+ return Math.max(MIN_THINKING_BUDGET, Math.min(budget, maxTokens - 1));
453
+ }
247
454
  /**
248
455
  * Map the SDK's thinking controls onto OpenRouter's unified `reasoning` object.
249
456
  *
250
457
  * `undefined` means "say nothing", which leaves the vendor's own default in
251
458
  * place — the only correct answer for a driver that was asked for nothing.
252
459
  */
253
- function formatReasoning(thinking, effort) {
254
- if (effort !== undefined) {
255
- const carried = OPENROUTER_REASONING_EFFORT.includes(effort);
256
- if (!carried) {
257
- throw new Error(`OpenRouterProvider cannot carry effort "${effort}". Its reasoning.effort accepts ${OPENROUTER_REASONING_EFFORT.join(', ')}. Sending a different level would return a perfectly ordinary completion that no caller could tell apart from the one that was asked for.`);
258
- }
460
+ function formatReasoning(thinking, effort, maxTokens) {
461
+ if (effort !== undefined)
259
462
  return { effort };
260
- }
261
463
  if (!thinking || thinking.type === undefined)
262
464
  return undefined;
263
465
  if (thinking.type === 'disabled')
@@ -265,12 +467,94 @@ function formatReasoning(thinking, effort) {
265
467
  // 'adaptive' has no separate spelling on this wire: the model decides its
266
468
  // own depth, which is what `enabled: true` without a budget expresses.
267
469
  // 'enabled' fixes the depth with budgetTokens, so it carries the cap.
268
- const budgetTokens = thinking.type === 'enabled' ? thinking.budgetTokens : undefined;
470
+ const budgetTokens = fitBudget(thinking.type === 'enabled' ? thinking.budgetTokens : undefined, maxTokens);
269
471
  return {
270
472
  enabled: true,
271
473
  ...(budgetTokens !== undefined ? { max_tokens: budgetTokens } : {}),
272
474
  };
273
475
  }
476
+ /** Longest host name or code worth naming in an error. */
477
+ const UPSTREAM_FIELD_MAX = 64;
478
+ function upstreamField(value) {
479
+ if (typeof value !== 'string' && typeof value !== 'number')
480
+ return undefined;
481
+ const text = String(value)
482
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: stripping control characters is the point
483
+ .replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ')
484
+ .trim();
485
+ return text === '' ? undefined : text.slice(0, UPSTREAM_FIELD_MAX);
486
+ }
487
+ /**
488
+ * The refusing host and its code, read from an error object's `metadata`
489
+ * (`provider_name`, and `provider_code` on an HTTP error or `error_type` on a
490
+ * mid-stream one). `metadata.raw` is never read: it can echo prompt text.
491
+ */
492
+ function upstreamNote(error, codeKey) {
493
+ const meta = error.metadata;
494
+ if (typeof meta !== 'object' || meta === null)
495
+ return undefined;
496
+ const m = meta;
497
+ const host = upstreamField(m.provider_name);
498
+ const code = upstreamField(m[codeKey]);
499
+ if (host === undefined && code === undefined)
500
+ return undefined;
501
+ return [host !== undefined ? `host ${host}` : '', code !== undefined ? `code ${code}` : '']
502
+ .filter(Boolean)
503
+ .join(', ');
504
+ }
505
+ /**
506
+ * A failed body with the refusing host named in its message. `metadata` stays
507
+ * in the body: the classifier reads the whole text (the upstream's own
508
+ * sentence about a full context window lives in `metadata.raw`), and the error
509
+ * the SDK builds carries only the message, type, code and param, never `raw`.
510
+ * Anything that is not a JSON object with an `error` object, or that
511
+ * names no host or code, comes back unchanged.
512
+ */
513
+ function nameUpstream(body, parsed, codeKey) {
514
+ if (typeof parsed !== 'object' || parsed === null)
515
+ return body;
516
+ const error = parsed.error;
517
+ if (typeof error !== 'object' || error === null)
518
+ return body;
519
+ const note = upstreamNote(error, codeKey);
520
+ if (note === undefined)
521
+ return body;
522
+ const rest = error;
523
+ const message = typeof rest.message === 'string' ? rest.message : '';
524
+ return JSON.stringify({
525
+ ...parsed,
526
+ error: { ...rest, message: message ? `${message} (${note})` : note },
527
+ });
528
+ }
529
+ function parseJson(text) {
530
+ try {
531
+ return JSON.parse(text);
532
+ }
533
+ catch {
534
+ return undefined;
535
+ }
536
+ }
537
+ /** A choice that makes the model call a tool: `required` or a named function. */
538
+ function isForcedToolChoice(tc) {
539
+ return tc !== 'auto' && tc !== 'none';
540
+ }
541
+ /**
542
+ * Whether a 400 body is the vendor refusing the tool choice. The router passes
543
+ * the upstream sentence through ("Thinking mode does not support this
544
+ * tool_choice"). Only the error's message is read (the whole body when it is
545
+ * not JSON), and it must both name the field and say it is refused, so a 400
546
+ * that merely mentions `tool_choice` (an echo of the request, a schema error
547
+ * about another field) is not retried.
548
+ */
549
+ function refusesToolChoice(errorBody, parsedBody) {
550
+ let text = errorBody;
551
+ const e = parsedBody?.error;
552
+ const message = typeof e === 'string' ? e : e?.message;
553
+ if (typeof message === 'string')
554
+ text = message;
555
+ return (/tool_choice/i.test(text) &&
556
+ /(not\s+support|unsupported|not\s+supported|not\s+allowed|cannot|can't|only\s+support|invalid)/i.test(text));
557
+ }
274
558
  function formatToolChoice(tc) {
275
559
  if (typeof tc === 'string')
276
560
  return tc;
@@ -292,6 +576,8 @@ export const OPENROUTER_CAPABILITIES = {
292
576
  supportsDocuments: false,
293
577
  supportsToolResultImages: false,
294
578
  supportsToolResultDocuments: false,
579
+ // OpenRouter states the charge on every response (`usage.cost`).
580
+ reportsRequestCost: true,
295
581
  };
296
582
  export class OpenRouterProvider {
297
583
  id = 'openrouter';
@@ -299,12 +585,39 @@ export class OpenRouterProvider {
299
585
  capabilities = OPENROUTER_CAPABILITIES;
300
586
  config;
301
587
  baseUrl;
588
+ logger;
302
589
  constructor(config) {
303
590
  if (!config.apiKey) {
304
591
  throw new Error('OpenRouter API key is required. Set OPENROUTER_API_KEY env variable.');
305
592
  }
306
593
  this.config = config;
307
594
  this.baseUrl = config.baseUrl ?? OPENROUTER_BASE_URL;
595
+ this.logger = config.logger ?? NOOP_LOGGER;
596
+ }
597
+ /**
598
+ * Whether a forced tool choice (`required` or a named function) is taken
599
+ * under the thinking configuration the request will carry. `false` only for
600
+ * the DeepSeek models whose own API refuses it while they reason, and
601
+ * reasoning is on for them unless thinking is disabled or effort is `none`
602
+ * (the same rule the DeepSeek driver applies). The kernel asks first and,
603
+ * on `false`, keeps the step at low effort and asks in words.
604
+ *
605
+ * The vendor's refusal is not what every route returns. On the live route a
606
+ * forced choice with reasoning on was served (HTTP 200) by five different
607
+ * upstream hosts, and when the request was pinned to the vendor's own host
608
+ * the router answered its own 404 "no endpoints" (its tool-compatibility
609
+ * filter drops that host for a forced choice). Yet a real session got the
610
+ * vendor's own 400 "Thinking mode does not support this tool_choice" from
611
+ * some host. So this driver acts on both facts: where this answer is
612
+ * `false` the forced choice is not put on the wire, and a request that did
613
+ * carry one and drew a 400 naming `tool_choice` is sent once more without
614
+ * it. A host that accepts the choice keeps getting it; only a host that
615
+ * rejects it costs a second request.
616
+ */
617
+ acceptsForcedToolChoiceFor(model, thinking, effort) {
618
+ if (!refusesForcedChoiceWhileReasoning(model))
619
+ return true;
620
+ return thinking?.type === 'disabled' || effort === 'none';
308
621
  }
309
622
  getHeaders() {
310
623
  const headers = {
@@ -323,14 +636,17 @@ export class OpenRouterProvider {
323
636
  }
324
637
  return headers;
325
638
  }
326
- formatMessages(messages) {
639
+ formatMessages(messages, route) {
640
+ const turnStart = currentTurnStart(messages);
327
641
  // An assistant entry with neither text nor a tool call (the model produced
328
642
  // only reasoning, or was cut off) is rejected upstream with "content or
329
643
  // tool_calls must be set". Leave it out; no filler is invented. An entry
330
644
  // with tool calls is never dropped, so every tool result still follows the
331
645
  // call it answers, and the stored history is untouched.
332
- const sendable = messages.filter((msg) => msg.role !== 'assistant' || Boolean(msg.content) || (msg.toolCalls?.length ?? 0) > 0);
333
- return sendable.map((msg) => {
646
+ const sendable = messages
647
+ .map((msg, index) => ({ msg, index }))
648
+ .filter(({ msg }) => msg.role !== 'assistant' || Boolean(msg.content) || (msg.toolCalls?.length ?? 0) > 0);
649
+ return sendable.map(({ msg, index }) => {
334
650
  if (msg.role === 'tool') {
335
651
  return {
336
652
  role: 'tool',
@@ -338,6 +654,10 @@ export class OpenRouterProvider {
338
654
  tool_call_id: msg.toolCallId,
339
655
  };
340
656
  }
657
+ // The model's own reasoning for the steps of THIS turn goes back with the
658
+ // message that produced it, so it can continue from where it left off
659
+ // after a tool result. An earlier turn's reasoning is not resent.
660
+ const replay = msg.role === 'assistant' && index >= turnStart ? replayFor(msg, route) : undefined;
341
661
  if (msg.role === 'assistant' && 'toolCalls' in msg && msg.toolCalls?.length) {
342
662
  return {
343
663
  role: 'assistant',
@@ -347,22 +667,34 @@ export class OpenRouterProvider {
347
667
  type: tc.type,
348
668
  function: tc.function,
349
669
  })),
670
+ ...replay,
350
671
  };
351
672
  }
352
- return { role: msg.role, content: msg.content };
673
+ return { role: msg.role, content: msg.content, ...replay };
353
674
  });
354
675
  }
355
- buildRequestBody(params, stream) {
676
+ buildRequestBody(params, stream, supportedEfforts) {
356
677
  const body = {
357
678
  model: params.model,
358
- messages: this.formatMessages(params.messages),
679
+ messages: this.formatMessages(params.messages, routeOf(params)),
359
680
  stream,
360
681
  };
361
682
  if (params.tools && params.tools.length > 0) {
362
683
  body.tools = params.tools;
363
684
  }
364
685
  if (params.toolChoice !== undefined) {
365
- body.tool_choice = formatToolChoice(params.toolChoice);
686
+ if (isForcedToolChoice(params.toolChoice) &&
687
+ !this.acceptsForcedToolChoiceFor(params.model, params.thinking, params.effort)) {
688
+ // The model's vendor refuses a forced choice while it reasons. Not
689
+ // sending it costs the caller nothing it could have had: the step
690
+ // goes out with the choice left to the model.
691
+ this.logger.debug('openrouter: forced tool_choice not sent, the model refuses it here', {
692
+ 'namzu.model': params.model,
693
+ });
694
+ }
695
+ else {
696
+ body.tool_choice = formatToolChoice(params.toolChoice);
697
+ }
366
698
  }
367
699
  if (params.parallelToolCalls !== undefined) {
368
700
  body.parallel_tool_calls = params.parallelToolCalls;
@@ -386,9 +718,9 @@ export class OpenRouterProvider {
386
718
  if (params.cacheControl && takesExplicitBreakpoints(params.model)) {
387
719
  applyCacheBreakpoints(params.messages, body.messages);
388
720
  }
389
- // Refused, not dropped, when this wire cannot carry the level asked
390
- // for — see `formatReasoning`.
391
- const reasoning = formatReasoning(params.thinking, params.effort);
721
+ // `max` and `ultra` resolve against the model's own list — see
722
+ // `carriedEffort`.
723
+ const reasoning = formatReasoning(params.thinking, params.effort !== undefined ? carriedEffort(params.effort, supportedEfforts) : undefined, params.maxTokens);
392
724
  if (reasoning !== undefined) {
393
725
  body.reasoning = reasoning;
394
726
  }
@@ -398,40 +730,62 @@ export class OpenRouterProvider {
398
730
  return body;
399
731
  }
400
732
  async *chatStream(params) {
401
- const body = this.buildRequestBody(params, true);
733
+ const supportedEfforts = params.effort === 'max' || params.effort === 'ultra'
734
+ ? await this.resolveSupportedEfforts(params.model, params.signal)
735
+ : undefined;
736
+ const body = this.buildRequestBody(params, true, supportedEfforts);
402
737
  const timeout = AbortSignal.timeout(this.config.timeout ?? 120_000);
403
738
  // Compose the caller abort with the request timeout so a Stop cancels the
404
739
  // response body stream. When no caller signal is present this is the exact
405
740
  // prior `AbortSignal.timeout(...)` expression (byte-identical).
406
741
  const signal = params.signal ? AbortSignal.any([timeout, params.signal]) : timeout;
407
- let response;
408
- try {
409
- response = await fetch(`${this.baseUrl}/chat/completions`, {
410
- method: 'POST',
411
- headers: this.getHeaders(),
412
- body: JSON.stringify(body),
413
- signal,
414
- });
415
- }
416
- catch (err) {
417
- if (isCallerAbortError(err, params.signal))
418
- throw params.signal?.reason ?? err;
419
- throw providerVendorError({ providerId: 'openrouter', error: err });
420
- }
742
+ const send = async (payload) => {
743
+ try {
744
+ return await fetch(`${this.baseUrl}/chat/completions`, {
745
+ method: 'POST',
746
+ headers: this.getHeaders(),
747
+ body: JSON.stringify(payload),
748
+ signal,
749
+ });
750
+ }
751
+ catch (err) {
752
+ if (isCallerAbortError(err, params.signal))
753
+ throw params.signal?.reason ?? err;
754
+ throw providerVendorError({ providerId: 'openrouter', error: err });
755
+ }
756
+ };
757
+ let response = await send(body);
421
758
  if (!response.ok) {
422
759
  // The body is read to CLASSIFY (a 400 saying "prompt is too long" is a
423
760
  // context overflow, any other 400 is a bad request) and then dropped. It
424
761
  // used to be interpolated straight into the message, which is how a
425
762
  // credential the upstream echoed back reached every log that recorded
426
763
  // the failure — proven with a planted fake token.
427
- const errorBody = await response.text().catch(() => '');
428
- throw providerHttpError({
429
- providerId: 'openrouter',
430
- status: response.status,
431
- body: errorBody,
432
- retryAfter: response.headers.get('retry-after'),
433
- shouldRetry: response.headers.get('x-should-retry'),
434
- });
764
+ let errorBody = await response.text().catch(() => '');
765
+ const sentForced = body.tool_choice !== undefined && isForcedToolChoice(body.tool_choice);
766
+ if (response.status === 400 &&
767
+ sentForced &&
768
+ refusesToolChoice(errorBody, parseJson(errorBody))) {
769
+ // This host refuses a forced choice. Ask once more without it; the
770
+ // model decides whether to call a tool. Anything the second attempt
771
+ // answers is final.
772
+ this.logger.debug('openrouter: a 400 named tool_choice, sending once more without it', {
773
+ 'namzu.model': params.model,
774
+ });
775
+ const { tool_choice: _dropped, ...withoutChoice } = body;
776
+ response = await send(withoutChoice);
777
+ if (!response.ok)
778
+ errorBody = await response.text().catch(() => '');
779
+ }
780
+ if (!response.ok) {
781
+ throw providerHttpError({
782
+ providerId: 'openrouter',
783
+ status: response.status,
784
+ body: nameUpstream(errorBody, parseJson(errorBody), 'provider_code'),
785
+ retryAfter: response.headers.get('retry-after'),
786
+ shouldRetry: response.headers.get('x-should-retry'),
787
+ });
788
+ }
435
789
  }
436
790
  if (!response.body) {
437
791
  throw new ProviderRequestError({
@@ -447,6 +801,10 @@ export class OpenRouterProvider {
447
801
  // Reasoning blocks this stream has opened and not yet closed, in the
448
802
  // order the wire reported them.
449
803
  const openReasoning = new Set();
804
+ // The reasoning entries as the wire sent them, kept for replay.
805
+ const replay = new ReasoningDetailsAccumulator();
806
+ const route = routeOf(params);
807
+ let replayStateEmitted = false;
450
808
  // A choice reported why it stopped. A stream that ends without one, with or
451
809
  // without `[DONE]`, was cut by the connection.
452
810
  let finished = false;
@@ -482,7 +840,7 @@ export class OpenRouterProvider {
482
840
  if (parsed.error !== undefined) {
483
841
  throw providerVendorError({
484
842
  providerId: 'openrouter',
485
- error: new Error(data),
843
+ error: new Error(nameUpstream(data, parsed, 'error_type')),
486
844
  });
487
845
  }
488
846
  const choice = parsed.choices[0];
@@ -491,6 +849,12 @@ export class OpenRouterProvider {
491
849
  if (choice.finish_reason)
492
850
  finished = true;
493
851
  const fragments = parseReasoning(choice.delta.reasoning_details, choice.delta.reasoning);
852
+ if (choice.delta.reasoning_details && choice.delta.reasoning_details.length > 0) {
853
+ replay.add(choice.delta.reasoning_details);
854
+ }
855
+ else {
856
+ replay.addFlat(choice.delta.reasoning);
857
+ }
494
858
  const content = choice.delta.content;
495
859
  const toolCalls = choice.delta.tool_calls?.map((tc) => ({
496
860
  index: tc.index,
@@ -518,8 +882,14 @@ export class OpenRouterProvider {
518
882
  toolCalls !== undefined ||
519
883
  choice.finish_reason !== undefined ||
520
884
  parsed.usage !== undefined) {
885
+ const replayState = !replayStateEmitted && choice.finish_reason && replay.hasAny
886
+ ? replay.state(route)
887
+ : undefined;
888
+ if (replayState !== undefined)
889
+ replayStateEmitted = true;
521
890
  yield {
522
891
  id: parsed.id,
892
+ ...(replayState !== undefined ? { replayState } : {}),
523
893
  delta: {
524
894
  ...(firstFragment ? { reasoning: firstFragment } : {}),
525
895
  content,
@@ -631,9 +1001,53 @@ export class OpenRouterProvider {
631
1001
  this.contextWindows ??= windows;
632
1002
  windows = this.contextWindows;
633
1003
  }
634
- const reported = windows.get(model);
1004
+ // A variant tag (`:batch`, `:nitro`) names the same model at the same
1005
+ // window; when the listing has only the untagged id, that is the answer.
1006
+ const tag = model.indexOf(':');
1007
+ const reported = windows.get(model) ?? (tag > 0 ? windows.get(model.slice(0, tag)) : undefined);
635
1008
  return typeof reported === 'number' && reported > 0 ? reported : undefined;
636
1009
  }
1010
+ /**
1011
+ * The reasoning levels the listing names for `model` (`reasoning.supported_efforts`),
1012
+ * or `undefined` when the listing cannot be read or names none. Read only
1013
+ * for a `max` or `ultra` request, and kept for this driver once fulfilled; a
1014
+ * failure is not kept. A caller abort still propagates.
1015
+ */
1016
+ async resolveSupportedEfforts(model, signal) {
1017
+ let table = this.supportedEfforts;
1018
+ if (!table) {
1019
+ try {
1020
+ signal?.throwIfAborted();
1021
+ const response = await fetch(`${this.baseUrl}/models`, {
1022
+ headers: this.getHeaders(),
1023
+ // Bounded on its own: this read sits in front of the first max or
1024
+ // ultra request, so a stalled listing must not stall that request.
1025
+ signal: signal
1026
+ ? AbortSignal.any([AbortSignal.timeout(5000), signal])
1027
+ : AbortSignal.timeout(5000),
1028
+ });
1029
+ if (!response.ok)
1030
+ return undefined;
1031
+ const data = (await response.json());
1032
+ table = new Map();
1033
+ for (const m of data.data ?? []) {
1034
+ const levels = m.reasoning?.supported_efforts;
1035
+ if (Array.isArray(levels)) {
1036
+ table.set(m.id, levels.filter((l) => typeof l === 'string'));
1037
+ }
1038
+ }
1039
+ this.supportedEfforts = table;
1040
+ }
1041
+ catch (err) {
1042
+ if (signal?.aborted)
1043
+ throw signal.reason ?? err;
1044
+ return undefined;
1045
+ }
1046
+ }
1047
+ const tag = model.indexOf(':');
1048
+ return table.get(model) ?? (tag > 0 ? table.get(model.slice(0, tag)) : undefined);
1049
+ }
1050
+ supportedEfforts;
637
1051
  /** First fulfilled listing; see the note on `resolveContextWindow`. */
638
1052
  contextWindows;
639
1053
  async listModels(signal) {