@namzu/openrouter 3.2.0 → 3.2.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.2.2
4
+
5
+ ### Patch Changes
6
+
7
+ - f71fe3c: A slow OpenRouter model listing no longer holds up the model picker, the context-window lookup or the first `max` or `ultra` effort request: each read of `/models` gives up after 5 seconds. A lookup that gives up behaves as if the listing had no entry (the built-in window table and the `xhigh` effort apply), and the picker reports a timeout. HTTP 402, 403 and 404 answers from OpenRouter now carry the new SDK error kinds `credits`, `moderation` and `no_endpoints`; they need `@namzu/sdk` with those kinds.
8
+
9
+ ## 3.2.1
10
+
11
+ ### Patch Changes
12
+
13
+ - daa889c: An OpenRouter failure now says which upstream host refused the request and its code (for example `host AcmeCloud, code bad_param`), on an HTTP error and on an error that arrives mid-stream, so a person can tell a host's refusal from the router's. The host's raw echo of the request is still never shown. Cache writes are now counted for models with explicit caching (`prompt_tokens_details.cache_write_tokens`, used when the older field is absent; the prompt size is unchanged). A thinking budget is no longer sent at or above the request's output limit: with an output limit above 1024 it is brought under it, and a budget under 1024 is raised to 1024; effort-mode requests are untouched.
14
+ - f9ff8e8: Through OpenRouter, a DeepSeek V4 sub-agent no longer ends with the vendor's HTTP 400 "Thinking mode does not support this tool_choice", and choosing effort `max` or `ultra` no longer throws. The OpenRouter driver leaves a forced tool choice (`required` or a named function) off the request for the models that refuse it while they reason, and when a host answers a forced choice with a 400 that names `tool_choice` it sends the request once more without it (`auto` and `none` are untouched, and a host that accepts the choice still gets it). Effort `max` and `ultra` now send the highest level the model's OpenRouter listing names (`max` for DeepSeek V4.1 Flash), or `xhigh` when the listing cannot be read. `OpenRouterConfig` gains an optional `logger` for the driver's debug lines. In the SDK, a tool choice set by a step (`prepareStep`) is now asked of the provider with `acceptsForcedToolChoiceFor`, as the loop's own forced step already was, and is not sent when the provider says it refuses it. Nothing is removed; a request that used to fail now succeeds. One behaviour changes for any provider that answers `acceptsForcedToolChoiceFor` with `false` (the DeepSeek driver with thinking on, Anthropic models that refuse a forced choice): a `prepareStep` choice of `required` or a named function used to fail the step with the provider's refusal, and is now left off the request, with one line added in words that the reply must be a tool call. A caller that wants the hard failure back checks the choice itself before returning it from `prepareStep`.
15
+
3
16
  ## 3.2.0
4
17
 
5
18
  ### Minor Changes
package/dist/client.d.ts CHANGED
@@ -7,12 +7,22 @@ import type { OpenRouterConfig } from './types.js';
7
7
  * until the message translation handles them.
8
8
  */
9
9
  export declare const OPENROUTER_CAPABILITIES: ProviderCapabilities;
10
+ /**
11
+ * How long a read of the `/models` listing may take. The listing is several
12
+ * hundred entries and normally answers well inside a second; 5 s is long
13
+ * enough for a slow link and short enough that the first `max` request, which
14
+ * waits on this read, does not feel stuck. It is a bound on waiting, not a
15
+ * retry: past it the listing counts as absent and each reader's documented
16
+ * fallback applies.
17
+ */
18
+ export declare const MODEL_LISTING_TIMEOUT_MS = 5000;
10
19
  export declare class OpenRouterProvider implements LLMProvider {
11
20
  readonly id = "openrouter";
12
21
  readonly name = "OpenRouter";
13
22
  readonly capabilities: ProviderCapabilities;
14
23
  private config;
15
24
  private baseUrl;
25
+ private logger;
16
26
  constructor(config: OpenRouterConfig);
17
27
  /**
18
28
  * Whether a forced tool choice (`required` or a named function) is taken
@@ -20,14 +30,19 @@ export declare class OpenRouterProvider implements LLMProvider {
20
30
  * the DeepSeek models whose own API refuses it while they reason, and
21
31
  * reasoning is on for them unless thinking is disabled or effort is `none`
22
32
  * (the same rule the DeepSeek driver applies). The kernel asks first and,
23
- * on `false`, keeps the step at low effort and asks in words. Nothing is
24
- * refused here before transport: on the live route a forced choice with
25
- * reasoning on was served (HTTP 200) by five different upstream hosts, and
26
- * when the request was pinned to the vendor's own host the router answered
27
- * its own 404 "no endpoints" (its tool-compatibility filter drops that host
28
- * for a forced choice) rather than passing the vendor's 400 through. So the
29
- * vendor's refusal never reaches this driver as a 400, and refusing here
30
- * would turn a working call into an error; only the advice changes.
33
+ * on `false`, keeps the step at low effort and asks in words.
34
+ *
35
+ * The vendor's refusal is not what every route returns. On the live route a
36
+ * forced choice with reasoning on was served (HTTP 200) by five different
37
+ * upstream hosts, and when the request was pinned to the vendor's own host
38
+ * the router answered its own 404 "no endpoints" (its tool-compatibility
39
+ * filter drops that host for a forced choice). Yet a real session got the
40
+ * vendor's own 400 "Thinking mode does not support this tool_choice" from
41
+ * some host. So this driver acts on both facts: where this answer is
42
+ * `false` the forced choice is not put on the wire, and a request that did
43
+ * carry one and drew a 400 naming `tool_choice` is sent once more without
44
+ * it. A host that accepts the choice keeps getting it; only a host that
45
+ * rejects it costs a second request.
31
46
  */
32
47
  acceptsForcedToolChoiceFor(model: string, thinking?: ThinkingConfig, effort?: ReasoningEffort): boolean;
33
48
  private getHeaders;
@@ -73,6 +88,14 @@ export declare class OpenRouterProvider implements LLMProvider {
73
88
  * one bad minute forever.
74
89
  */
75
90
  resolveContextWindow(model: string, signal?: AbortSignal): Promise<number | undefined>;
91
+ /**
92
+ * The reasoning levels the listing names for `model` (`reasoning.supported_efforts`),
93
+ * or `undefined` when the listing cannot be read or names none. Read only
94
+ * for a `max` or `ultra` request, and kept for this driver once fulfilled; a
95
+ * failure is not kept. A caller abort still propagates.
96
+ */
97
+ private resolveSupportedEfforts;
98
+ private supportedEfforts?;
76
99
  /** First fulfilled listing; see the note on `resolveContextWindow`. */
77
100
  private contextWindows?;
78
101
  listModels(signal?: AbortSignal): Promise<ModelInfo[]>;
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,oBAAoB,EACpB,WAAW,EACX,SAAS,EACT,oBAAoB,EAGpB,eAAe,EACf,WAAW,EACX,cAAc,EAGd,MAAM,YAAY,CAAA;AASnB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AA2hBlD;;;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,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" —
@@ -219,7 +220,7 @@ function parseUsage(raw) {
219
220
  completionTokens: raw.completion_tokens,
220
221
  totalTokens: raw.total_tokens,
221
222
  cachedTokens: raw.prompt_tokens_details?.cached_tokens ?? raw.cache_read_input_tokens ?? 0,
222
- cacheWriteTokens: raw.cache_creation_input_tokens ?? 0,
223
+ cacheWriteTokens: raw.cache_creation_input_tokens ?? raw.prompt_tokens_details?.cache_write_tokens ?? 0,
223
224
  ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
224
225
  ...(cost !== undefined ? { reportedCostUsd: cost } : {}),
225
226
  };
@@ -415,29 +416,50 @@ function refusesForcedChoiceWhileReasoning(model) {
415
416
  const bare = afterSlash.slice(afterSlash.lastIndexOf('/') + 1).split(':')[0] ?? '';
416
417
  return /^deepseek-(v([4-9]|\d{2,})(\.|-|$)|r\d+(-|$)|reasoner(-|$)|(flash|pro)(-|$))/.test(bare);
417
418
  }
419
+ /** Highest first. What a request for `max` or `ultra` falls down through. */
420
+ const EFFORT_DESCENDING = ['max', 'xhigh', 'high', 'medium', 'low', 'minimal'];
418
421
  /**
419
- * The effort levels this wire can carry.
422
+ * The level that stands in for an SDK effort the wire may not carry.
420
423
  *
421
- * OpenRouter's unified `reasoning.effort` publishes exactly these. The SDK's
422
- * `max` and `ultra` are OpenAI-model-specific names with no equivalent here,
423
- * and a driver must not send one and hope: an effort that arrives as a
424
- * different depth is indistinguishable from one that was honoured.
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.
425
432
  */
426
- const OPENROUTER_REASONING_EFFORT = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh'];
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
+ }
427
454
  /**
428
455
  * Map the SDK's thinking controls onto OpenRouter's unified `reasoning` object.
429
456
  *
430
457
  * `undefined` means "say nothing", which leaves the vendor's own default in
431
458
  * place — the only correct answer for a driver that was asked for nothing.
432
459
  */
433
- function formatReasoning(thinking, effort) {
434
- if (effort !== undefined) {
435
- const carried = OPENROUTER_REASONING_EFFORT.includes(effort);
436
- if (!carried) {
437
- 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.`);
438
- }
460
+ function formatReasoning(thinking, effort, maxTokens) {
461
+ if (effort !== undefined)
439
462
  return { effort };
440
- }
441
463
  if (!thinking || thinking.type === undefined)
442
464
  return undefined;
443
465
  if (thinking.type === 'disabled')
@@ -445,12 +467,94 @@ function formatReasoning(thinking, effort) {
445
467
  // 'adaptive' has no separate spelling on this wire: the model decides its
446
468
  // own depth, which is what `enabled: true` without a budget expresses.
447
469
  // 'enabled' fixes the depth with budgetTokens, so it carries the cap.
448
- const budgetTokens = thinking.type === 'enabled' ? thinking.budgetTokens : undefined;
470
+ const budgetTokens = fitBudget(thinking.type === 'enabled' ? thinking.budgetTokens : undefined, maxTokens);
449
471
  return {
450
472
  enabled: true,
451
473
  ...(budgetTokens !== undefined ? { max_tokens: budgetTokens } : {}),
452
474
  };
453
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
+ }
454
558
  function formatToolChoice(tc) {
455
559
  if (typeof tc === 'string')
456
560
  return tc;
@@ -475,18 +579,70 @@ export const OPENROUTER_CAPABILITIES = {
475
579
  // OpenRouter states the charge on every response (`usage.cost`).
476
580
  reportsRequestCost: true,
477
581
  };
582
+ /**
583
+ * How long a read of the `/models` listing may take. The listing is several
584
+ * hundred entries and normally answers well inside a second; 5 s is long
585
+ * enough for a slow link and short enough that the first `max` request, which
586
+ * waits on this read, does not feel stuck. It is a bound on waiting, not a
587
+ * retry: past it the listing counts as absent and each reader's documented
588
+ * fallback applies.
589
+ */
590
+ export const MODEL_LISTING_TIMEOUT_MS = 5000;
591
+ /**
592
+ * Run `read` with a signal that fires at the listing bound or when the
593
+ * caller's signal does. The bound is an ordinary timer, cleared when the read
594
+ * settles, so a test can advance it with a fake clock.
595
+ */
596
+ async function withListingBound(signal, read) {
597
+ const bound = new AbortController();
598
+ let timer;
599
+ // Rejects at the bound even when the transport ignores its signal.
600
+ const expired = new Promise((_, reject) => {
601
+ timer = setTimeout(() => {
602
+ const reason = new DOMException('the models listing did not answer in time', 'TimeoutError');
603
+ bound.abort(reason);
604
+ reject(reason);
605
+ }, MODEL_LISTING_TIMEOUT_MS);
606
+ });
607
+ let onAbort;
608
+ // The caller's abort also ends the wait, whether or not the transport honours it.
609
+ const cancelled = new Promise((_, reject) => {
610
+ if (!signal)
611
+ return;
612
+ onAbort = () => reject(signal.reason ?? new DOMException('aborted', 'AbortError'));
613
+ signal.addEventListener('abort', onAbort, { once: true });
614
+ });
615
+ try {
616
+ return await Promise.race([
617
+ read(signal ? AbortSignal.any([bound.signal, signal]) : bound.signal),
618
+ expired,
619
+ cancelled,
620
+ ]);
621
+ }
622
+ finally {
623
+ if (onAbort)
624
+ signal?.removeEventListener('abort', onAbort);
625
+ clearTimeout(timer);
626
+ }
627
+ }
628
+ /** Did the listing read run past its bound (as opposed to failing some other way)? */
629
+ function isListingTimeout(err) {
630
+ return err instanceof Error && err.name === 'TimeoutError';
631
+ }
478
632
  export class OpenRouterProvider {
479
633
  id = 'openrouter';
480
634
  name = 'OpenRouter';
481
635
  capabilities = OPENROUTER_CAPABILITIES;
482
636
  config;
483
637
  baseUrl;
638
+ logger;
484
639
  constructor(config) {
485
640
  if (!config.apiKey) {
486
641
  throw new Error('OpenRouter API key is required. Set OPENROUTER_API_KEY env variable.');
487
642
  }
488
643
  this.config = config;
489
644
  this.baseUrl = config.baseUrl ?? OPENROUTER_BASE_URL;
645
+ this.logger = config.logger ?? NOOP_LOGGER;
490
646
  }
491
647
  /**
492
648
  * Whether a forced tool choice (`required` or a named function) is taken
@@ -494,14 +650,19 @@ export class OpenRouterProvider {
494
650
  * the DeepSeek models whose own API refuses it while they reason, and
495
651
  * reasoning is on for them unless thinking is disabled or effort is `none`
496
652
  * (the same rule the DeepSeek driver applies). The kernel asks first and,
497
- * on `false`, keeps the step at low effort and asks in words. Nothing is
498
- * refused here before transport: on the live route a forced choice with
499
- * reasoning on was served (HTTP 200) by five different upstream hosts, and
500
- * when the request was pinned to the vendor's own host the router answered
501
- * its own 404 "no endpoints" (its tool-compatibility filter drops that host
502
- * for a forced choice) rather than passing the vendor's 400 through. So the
503
- * vendor's refusal never reaches this driver as a 400, and refusing here
504
- * would turn a working call into an error; only the advice changes.
653
+ * on `false`, keeps the step at low effort and asks in words.
654
+ *
655
+ * The vendor's refusal is not what every route returns. On the live route a
656
+ * forced choice with reasoning on was served (HTTP 200) by five different
657
+ * upstream hosts, and when the request was pinned to the vendor's own host
658
+ * the router answered its own 404 "no endpoints" (its tool-compatibility
659
+ * filter drops that host for a forced choice). Yet a real session got the
660
+ * vendor's own 400 "Thinking mode does not support this tool_choice" from
661
+ * some host. So this driver acts on both facts: where this answer is
662
+ * `false` the forced choice is not put on the wire, and a request that did
663
+ * carry one and drew a 400 naming `tool_choice` is sent once more without
664
+ * it. A host that accepts the choice keeps getting it; only a host that
665
+ * rejects it costs a second request.
505
666
  */
506
667
  acceptsForcedToolChoiceFor(model, thinking, effort) {
507
668
  if (!refusesForcedChoiceWhileReasoning(model))
@@ -562,7 +723,7 @@ export class OpenRouterProvider {
562
723
  return { role: msg.role, content: msg.content, ...replay };
563
724
  });
564
725
  }
565
- buildRequestBody(params, stream) {
726
+ buildRequestBody(params, stream, supportedEfforts) {
566
727
  const body = {
567
728
  model: params.model,
568
729
  messages: this.formatMessages(params.messages, routeOf(params)),
@@ -572,7 +733,18 @@ export class OpenRouterProvider {
572
733
  body.tools = params.tools;
573
734
  }
574
735
  if (params.toolChoice !== undefined) {
575
- body.tool_choice = formatToolChoice(params.toolChoice);
736
+ if (isForcedToolChoice(params.toolChoice) &&
737
+ !this.acceptsForcedToolChoiceFor(params.model, params.thinking, params.effort)) {
738
+ // The model's vendor refuses a forced choice while it reasons. Not
739
+ // sending it costs the caller nothing it could have had: the step
740
+ // goes out with the choice left to the model.
741
+ this.logger.debug('openrouter: forced tool_choice not sent, the model refuses it here', {
742
+ 'namzu.model': params.model,
743
+ });
744
+ }
745
+ else {
746
+ body.tool_choice = formatToolChoice(params.toolChoice);
747
+ }
576
748
  }
577
749
  if (params.parallelToolCalls !== undefined) {
578
750
  body.parallel_tool_calls = params.parallelToolCalls;
@@ -596,9 +768,9 @@ export class OpenRouterProvider {
596
768
  if (params.cacheControl && takesExplicitBreakpoints(params.model)) {
597
769
  applyCacheBreakpoints(params.messages, body.messages);
598
770
  }
599
- // Refused, not dropped, when this wire cannot carry the level asked
600
- // for — see `formatReasoning`.
601
- const reasoning = formatReasoning(params.thinking, params.effort);
771
+ // `max` and `ultra` resolve against the model's own list — see
772
+ // `carriedEffort`.
773
+ const reasoning = formatReasoning(params.thinking, params.effort !== undefined ? carriedEffort(params.effort, supportedEfforts) : undefined, params.maxTokens);
602
774
  if (reasoning !== undefined) {
603
775
  body.reasoning = reasoning;
604
776
  }
@@ -608,40 +780,62 @@ export class OpenRouterProvider {
608
780
  return body;
609
781
  }
610
782
  async *chatStream(params) {
611
- const body = this.buildRequestBody(params, true);
783
+ const supportedEfforts = params.effort === 'max' || params.effort === 'ultra'
784
+ ? await this.resolveSupportedEfforts(params.model, params.signal)
785
+ : undefined;
786
+ const body = this.buildRequestBody(params, true, supportedEfforts);
612
787
  const timeout = AbortSignal.timeout(this.config.timeout ?? 120_000);
613
788
  // Compose the caller abort with the request timeout so a Stop cancels the
614
789
  // response body stream. When no caller signal is present this is the exact
615
790
  // prior `AbortSignal.timeout(...)` expression (byte-identical).
616
791
  const signal = params.signal ? AbortSignal.any([timeout, params.signal]) : timeout;
617
- let response;
618
- try {
619
- response = await fetch(`${this.baseUrl}/chat/completions`, {
620
- method: 'POST',
621
- headers: this.getHeaders(),
622
- body: JSON.stringify(body),
623
- signal,
624
- });
625
- }
626
- catch (err) {
627
- if (isCallerAbortError(err, params.signal))
628
- throw params.signal?.reason ?? err;
629
- throw providerVendorError({ providerId: 'openrouter', error: err });
630
- }
792
+ const send = async (payload) => {
793
+ try {
794
+ return await fetch(`${this.baseUrl}/chat/completions`, {
795
+ method: 'POST',
796
+ headers: this.getHeaders(),
797
+ body: JSON.stringify(payload),
798
+ signal,
799
+ });
800
+ }
801
+ catch (err) {
802
+ if (isCallerAbortError(err, params.signal))
803
+ throw params.signal?.reason ?? err;
804
+ throw providerVendorError({ providerId: 'openrouter', error: err });
805
+ }
806
+ };
807
+ let response = await send(body);
631
808
  if (!response.ok) {
632
809
  // The body is read to CLASSIFY (a 400 saying "prompt is too long" is a
633
810
  // context overflow, any other 400 is a bad request) and then dropped. It
634
811
  // used to be interpolated straight into the message, which is how a
635
812
  // credential the upstream echoed back reached every log that recorded
636
813
  // the failure — proven with a planted fake token.
637
- const errorBody = await response.text().catch(() => '');
638
- throw providerHttpError({
639
- providerId: 'openrouter',
640
- status: response.status,
641
- body: errorBody,
642
- retryAfter: response.headers.get('retry-after'),
643
- shouldRetry: response.headers.get('x-should-retry'),
644
- });
814
+ let errorBody = await response.text().catch(() => '');
815
+ const sentForced = body.tool_choice !== undefined && isForcedToolChoice(body.tool_choice);
816
+ if (response.status === 400 &&
817
+ sentForced &&
818
+ refusesToolChoice(errorBody, parseJson(errorBody))) {
819
+ // This host refuses a forced choice. Ask once more without it; the
820
+ // model decides whether to call a tool. Anything the second attempt
821
+ // answers is final.
822
+ this.logger.debug('openrouter: a 400 named tool_choice, sending once more without it', {
823
+ 'namzu.model': params.model,
824
+ });
825
+ const { tool_choice: _dropped, ...withoutChoice } = body;
826
+ response = await send(withoutChoice);
827
+ if (!response.ok)
828
+ errorBody = await response.text().catch(() => '');
829
+ }
830
+ if (!response.ok) {
831
+ throw providerHttpError({
832
+ providerId: 'openrouter',
833
+ status: response.status,
834
+ body: nameUpstream(errorBody, parseJson(errorBody), 'provider_code'),
835
+ retryAfter: response.headers.get('retry-after'),
836
+ shouldRetry: response.headers.get('x-should-retry'),
837
+ });
838
+ }
645
839
  }
646
840
  if (!response.body) {
647
841
  throw new ProviderRequestError({
@@ -696,7 +890,7 @@ export class OpenRouterProvider {
696
890
  if (parsed.error !== undefined) {
697
891
  throw providerVendorError({
698
892
  providerId: 'openrouter',
699
- error: new Error(data),
893
+ error: new Error(nameUpstream(data, parsed, 'error_type')),
700
894
  });
701
895
  }
702
896
  const choice = parsed.choices[0];
@@ -843,7 +1037,19 @@ export class OpenRouterProvider {
843
1037
  return undefined;
844
1038
  let windows = this.contextWindows;
845
1039
  if (!windows) {
846
- const models = await this.listModels(signal);
1040
+ let models;
1041
+ try {
1042
+ models = await this.listModels(signal);
1043
+ }
1044
+ catch (err) {
1045
+ // A listing that outlasts its bound is "no listing": the
1046
+ // caller's static table answers. A caller abort stays an abort.
1047
+ if (signal?.aborted)
1048
+ return undefined;
1049
+ if (isListingTimeout(err))
1050
+ return undefined;
1051
+ throw err;
1052
+ }
847
1053
  if (signal?.aborted)
848
1054
  return undefined;
849
1055
  windows = new Map(models
@@ -863,18 +1069,63 @@ export class OpenRouterProvider {
863
1069
  const reported = windows.get(model) ?? (tag > 0 ? windows.get(model.slice(0, tag)) : undefined);
864
1070
  return typeof reported === 'number' && reported > 0 ? reported : undefined;
865
1071
  }
1072
+ /**
1073
+ * The reasoning levels the listing names for `model` (`reasoning.supported_efforts`),
1074
+ * or `undefined` when the listing cannot be read or names none. Read only
1075
+ * for a `max` or `ultra` request, and kept for this driver once fulfilled; a
1076
+ * failure is not kept. A caller abort still propagates.
1077
+ */
1078
+ async resolveSupportedEfforts(model, signal) {
1079
+ let table = this.supportedEfforts;
1080
+ if (!table) {
1081
+ try {
1082
+ signal?.throwIfAborted();
1083
+ // Bounded on its own: this read sits in front of the first max or
1084
+ // ultra request, so a stalled listing must not stall that request.
1085
+ const data = await withListingBound(signal, async (bounded) => {
1086
+ const response = await fetch(`${this.baseUrl}/models`, {
1087
+ headers: this.getHeaders(),
1088
+ signal: bounded,
1089
+ });
1090
+ if (!response.ok)
1091
+ return undefined;
1092
+ return (await response.json());
1093
+ });
1094
+ if (!data)
1095
+ return undefined;
1096
+ table = new Map();
1097
+ for (const m of data.data ?? []) {
1098
+ const levels = m.reasoning?.supported_efforts;
1099
+ if (Array.isArray(levels)) {
1100
+ table.set(m.id, levels.filter((l) => typeof l === 'string'));
1101
+ }
1102
+ }
1103
+ this.supportedEfforts = table;
1104
+ }
1105
+ catch (err) {
1106
+ if (signal?.aborted)
1107
+ throw signal.reason ?? err;
1108
+ return undefined;
1109
+ }
1110
+ }
1111
+ const tag = model.indexOf(':');
1112
+ return table.get(model) ?? (tag > 0 ? table.get(model.slice(0, tag)) : undefined);
1113
+ }
1114
+ supportedEfforts;
866
1115
  /** First fulfilled listing; see the note on `resolveContextWindow`. */
867
1116
  contextWindows;
868
1117
  async listModels(signal) {
869
1118
  signal?.throwIfAborted();
870
- const response = await fetch(`${this.baseUrl}/models`, {
871
- headers: this.getHeaders(),
872
- ...(signal ? { signal } : {}),
1119
+ const data = await withListingBound(signal, async (bounded) => {
1120
+ const response = await fetch(`${this.baseUrl}/models`, {
1121
+ headers: this.getHeaders(),
1122
+ signal: bounded,
1123
+ });
1124
+ if (!response.ok) {
1125
+ throw new Error(`Failed to list models: ${response.status}`);
1126
+ }
1127
+ return (await response.json());
873
1128
  });
874
- if (!response.ok) {
875
- throw new Error(`Failed to list models: ${response.status}`);
876
- }
877
- const data = (await response.json());
878
1129
  signal?.throwIfAborted();
879
1130
  return data.data.map((m) => {
880
1131
  const inputPrice = pricePerMillion(m.pricing?.prompt);
@@ -893,11 +1144,13 @@ export class OpenRouterProvider {
893
1144
  }
894
1145
  async healthCheck() {
895
1146
  try {
896
- const response = await fetch(`${this.baseUrl}/models`, {
897
- headers: this.getHeaders(),
898
- signal: AbortSignal.timeout(5000),
1147
+ return await withListingBound(undefined, async (bounded) => {
1148
+ const response = await fetch(`${this.baseUrl}/models`, {
1149
+ headers: this.getHeaders(),
1150
+ signal: bounded,
1151
+ });
1152
+ return response.ok;
899
1153
  });
900
- return response.ok;
901
1154
  }
902
1155
  catch {
903
1156
  return false;