@namzu/openrouter 3.2.1 → 3.3.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - db1019a: Each driver now implements `readLimits`: Anthropic answers from the subscription rate-limit headers of the last response (no extra request; `undefined` for an API key), OpenRouter reads the key's limit and use with one `GET /key`, and DeepSeek reads the balance with one `GET /user/balance` to its own host only. The parsers (`parseUnifiedLimits`, `parseKeyLimits`, `parseBalance`) are exported and return `undefined` for any shape they do not recognise. Additive; no existing call changes.
8
+
9
+ ### Patch Changes
10
+
11
+ - 7b8e762: A long conversation through OpenRouter reads far more of its input from the prompt cache. Each assistant message now goes back with the reasoning it was sent with before, on every request; earlier turns used to be re-sent without it, which changed the cached prefix at each new user message and billed the whole history again (one run read 67% of its input from the cache instead of about 90%). Reasoning still leaves the history only when a compaction rewrites it. The model list now reads a negative rate (`-1`, OpenRouter's mark for a router such as `openrouter/auto`) as unknown instead of as a price.
12
+ - 7ab6117: A pasted image now reaches an OpenRouter model that reads images; before, every OpenRouter model was told "image omitted" and answered that it could not see the picture. A model whose listing shows it takes text only still gets the notice.
13
+ - aa665e7: A screenshot or an image file that a tool returns now reaches an OpenRouter model that reads images, so it can describe what it asked to see. The image goes in a user message right after that turn's tool results, each labelled with the tool call it came from; a text-only model still gets the short omission note. Nothing to change on your side.
14
+
15
+ ## 3.2.2
16
+
17
+ ### Patch Changes
18
+
19
+ - 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.
20
+
3
21
  ## 3.2.1
4
22
 
5
23
  ### Patch Changes
package/README.md CHANGED
@@ -94,13 +94,15 @@ the thinking share of the completion tokens OpenRouter already bills as output.
94
94
  sends each fragment twice (a flat `reasoning` string and the indexed `reasoning_details`);
95
95
  the driver emits it once.
96
96
 
97
- Between the steps of one turn the model's reasoning goes back to it. OpenRouter's guide says
97
+ The model's reasoning goes back to it with the message that produced it. OpenRouter's guide says
98
98
  to send the assistant message with its `reasoning_details` unmodified, so the driver keeps the
99
99
  entries as the wire sent them in the message's replay state (a `namzu-openrouter-reasoning`
100
- envelope that names its route) and sends them on the assistant messages after the turn's last
101
- user message. A route that sends only the flat string gets `reasoning` back instead. An earlier
102
- turn's reasoning is not resent, and state that names another route or no longer matches the
103
- stored reasoning is ignored.
100
+ envelope that names its route) and sends them on every assistant message of the conversation,
101
+ not only the current turn's: the upstream caches by prefix, and an earlier message sent without
102
+ the reasoning it carried before moves the prefix and bills the whole history again at the next
103
+ user message. A route that sends only the flat string gets `reasoning` back instead. State that
104
+ names another route or no longer matches the stored reasoning (a compaction rewrote it) is
105
+ ignored, so reasoning leaves the history only when the history is rewritten anyway.
104
106
 
105
107
  ## Cost and window
106
108
 
package/dist/client.d.ts CHANGED
@@ -1,12 +1,23 @@
1
- import type { ChatCompletionParams, LLMProvider, ModelInfo, ProviderCapabilities, ReasoningEffort, StreamChunk, ThinkingConfig } from '@namzu/sdk';
1
+ import type { ChatCompletionParams, LLMProvider, ModelInfo, ProviderCapabilities, ProviderLimits, ReasoningEffort, StreamChunk, ThinkingConfig } from '@namzu/sdk';
2
2
  import type { OpenRouterConfig } from './types.js';
3
3
  /**
4
4
  * What this DRIVER does, not what OpenRouter could do: tools pass
5
- * through to the request body, but user-message image `attachments`
6
- * are not mapped into content parts — `supportsVision` stays false
7
- * until the message translation handles them.
5
+ * through to the request body, and user-message image `attachments` are
6
+ * mapped into `image_url` content parts; an image a tool returns rides in a user
7
+ * message right after that turn's tool messages. Whether a given MODEL reads them is
8
+ * answered per model by `supportsImageInputFor`, from the listing's input
9
+ * modalities; the runtime keeps images away from a model known to be text-only.
8
10
  */
9
11
  export declare const OPENROUTER_CAPABILITIES: ProviderCapabilities;
12
+ /**
13
+ * How long a read of the `/models` listing may take. The listing is several
14
+ * hundred entries and normally answers well inside a second; 5 s is long
15
+ * enough for a slow link and short enough that the first `max` request, which
16
+ * waits on this read, does not feel stuck. It is a bound on waiting, not a
17
+ * retry: past it the listing counts as absent and each reader's documented
18
+ * fallback applies.
19
+ */
20
+ export declare const MODEL_LISTING_TIMEOUT_MS = 5000;
10
21
  export declare class OpenRouterProvider implements LLMProvider {
11
22
  readonly id = "openrouter";
12
23
  readonly name = "OpenRouter";
@@ -54,6 +65,11 @@ export declare class OpenRouterProvider implements LLMProvider {
54
65
  * requires the credential and returns its metadata, so a 401 here means the
55
66
  * key is genuinely refused.
56
67
  */
68
+ /**
69
+ * The key's limit and use, from one GET of `/key`. Any failure or unexpected body is "not
70
+ * reported", never a zero.
71
+ */
72
+ readLimits(signal?: AbortSignal): Promise<ProviderLimits | undefined>;
57
73
  probeCredential(signal?: AbortSignal): Promise<void>;
58
74
  /**
59
75
  * The vendor's own `context_length` for this model.
@@ -87,6 +103,19 @@ export declare class OpenRouterProvider implements LLMProvider {
87
103
  */
88
104
  private resolveSupportedEfforts;
89
105
  private supportedEfforts?;
106
+ /**
107
+ * Whether the model reads images, as the listing last said (`architecture.input_modalities`).
108
+ * Filled by `listModels`, which the context-window lookup runs once per driver, so
109
+ * answering costs no request of its own. Empty until a listing was read.
110
+ */
111
+ private imageInput;
112
+ /**
113
+ * Whether `model` reads images. `false` only when the listing named the model's input
114
+ * kinds and `image` was not among them. A model the listing does not name, or a
115
+ * listing not read yet, answers `true`: a wrong "no" blinds a vision model, while a
116
+ * wrong "yes" is recovered from when the router refuses the request.
117
+ */
118
+ supportsImageInputFor(model: string): boolean;
90
119
  /** First fulfilled listing; see the note on `resolveContextWindow`. */
91
120
  private contextWindows?;
92
121
  listModels(signal?: Ab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,SAAS,CAAC;IAarE,eAAe,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IAgB1D;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACG,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;IAqC5F;;;;;OAKG;YACW,uBAAuB;IAyCrC,OAAO,CAAC,gBAAgB,CAAC,CAAuB;IAEhD;;;;OAIG;IACH,OAAO,CAAC,UAAU,CAA6B;IAE/C;;;;;OAKG;IACH,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO;IAS7C,uEAAuE;IACvE,OAAO,CAAC,cAAc,CAAC,CAAqB;IAEtC,UAAU,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;IAwDtD,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;CAarC"}
package/dist/client.js CHANGED
@@ -1,6 +1,7 @@
1
- import { ProviderRequestError, isCallerAbortError, isProviderRequestError, providerHttpError, providerVendorError, } from '@namzu/sdk';
1
+ import { ProviderRequestError, isCallerAbortError, isModelContentOmission, isProviderRequestError, providerHttpError, providerVendorError, toToolResultBlocks, } from '@namzu/sdk';
2
2
  import { attributionHeaders } from '@namzu/sdk';
3
3
  import { NOOP_LOGGER } from '@namzu/sdk';
4
+ import { parseKeyLimits } from './limits.js';
4
5
  /**
5
6
  * The words a proxied backend's own `native_finish_reason` uses for "the
6
7
  * model's context window, not its output-token budget, is what ran out" —
@@ -128,7 +129,13 @@ function markLastPart(message) {
128
129
  * and its text changes from step to step, so a marker there would end the
129
130
  * prefix on bytes the next request does not repeat.
130
131
  */
131
- function applyCacheBreakpoints(source, formatted) {
132
+ function applyCacheBreakpoints(source, formatted, origin) {
133
+ // `origin[w]` is the source index of wire entry `w`, or -1 for an entry the
134
+ // driver added (the user message that carries a tool's images).
135
+ const wireOf = (sourceIndex) => {
136
+ const at = origin.indexOf(sourceIndex);
137
+ return at >= 0 ? formatted[at] : undefined;
138
+ };
132
139
  let lastStatic = -1;
133
140
  let historyEnd = source.length;
134
141
  for (const [i, msg] of source.entries()) {
@@ -137,13 +144,13 @@ function applyCacheBreakpoints(source, formatted) {
137
144
  if (historyEnd === source.length && isRequestOnlyContext(msg))
138
145
  historyEnd = i;
139
146
  }
140
- const staticMessage = lastStatic >= 0 ? formatted[lastStatic] : undefined;
147
+ const staticMessage = lastStatic >= 0 ? wireOf(lastStatic) : undefined;
141
148
  if (staticMessage)
142
149
  markLastPart(staticMessage);
143
150
  for (let i = historyEnd - 1; i > lastStatic; i--) {
144
151
  if (source[i]?.role === 'system')
145
152
  continue;
146
- const message = formatted[i];
153
+ const message = wireOf(i);
147
154
  if (message && markLastPart(message))
148
155
  return;
149
156
  }
@@ -170,7 +177,9 @@ function pricePerMillion(raw) {
170
177
  if (raw === undefined)
171
178
  return undefined;
172
179
  const parsed = Number.parseFloat(raw);
173
- return Number.isFinite(parsed) ? parsed * 1_000_000 : undefined;
180
+ // `"-1"` is how the listing marks a router with no fixed rate (`openrouter/auto`):
181
+ // a rate nobody stated, not a negative one.
182
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed * 1_000_000 : undefined;
174
183
  }
175
184
  /**
176
185
  * What the request cost, as OpenRouter reports it, or `undefined`.
@@ -389,21 +398,6 @@ function replayFor(message, target) {
389
398
  ? { reasoning_details: state.details }
390
399
  : { reasoning: state.reasoning };
391
400
  }
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.
398
- */
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
401
  /**
408
402
  * Whether a model is one whose vendor refuses a forced tool choice while it
409
403
  * reasons: the DeepSeek V4 generation and its reasoner line. Its own API
@@ -562,23 +556,77 @@ function formatToolChoice(tc) {
562
556
  }
563
557
  /**
564
558
  * What this DRIVER does, not what OpenRouter could do: tools pass
565
- * through to the request body, but user-message image `attachments`
566
- * are not mapped into content parts — `supportsVision` stays false
567
- * until the message translation handles them.
559
+ * through to the request body, and user-message image `attachments` are
560
+ * mapped into `image_url` content parts; an image a tool returns rides in a user
561
+ * message right after that turn's tool messages. Whether a given MODEL reads them is
562
+ * answered per model by `supportsImageInputFor`, from the listing's input
563
+ * modalities; the runtime keeps images away from a model known to be text-only.
568
564
  */
569
565
  export const OPENROUTER_CAPABILITIES = {
570
566
  supportsTools: true,
571
567
  supportsStreaming: true,
572
568
  supportsFunctionCalling: true,
573
569
  supportsNativeStructuredOutput: true,
574
- supportsVision: false,
570
+ supportsVision: true,
575
571
  // Images only. A document degrades to a named placeholder.
576
572
  supportsDocuments: false,
577
- supportsToolResultImages: false,
573
+ // An image a tool returns follows its tool messages in one user message
574
+ // (a chat-completions tool message carries text only).
575
+ supportsToolResultImages: true,
578
576
  supportsToolResultDocuments: false,
579
577
  // OpenRouter states the charge on every response (`usage.cost`).
580
578
  reportsRequestCost: true,
581
579
  };
580
+ /**
581
+ * How long a read of the `/models` listing may take. The listing is several
582
+ * hundred entries and normally answers well inside a second; 5 s is long
583
+ * enough for a slow link and short enough that the first `max` request, which
584
+ * waits on this read, does not feel stuck. It is a bound on waiting, not a
585
+ * retry: past it the listing counts as absent and each reader's documented
586
+ * fallback applies.
587
+ */
588
+ export const MODEL_LISTING_TIMEOUT_MS = 5000;
589
+ /**
590
+ * Run `read` with a signal that fires at the listing bound or when the
591
+ * caller's signal does. The bound is an ordinary timer, cleared when the read
592
+ * settles, so a test can advance it with a fake clock.
593
+ */
594
+ async function withListingBound(signal, read) {
595
+ const bound = new AbortController();
596
+ let timer;
597
+ // Rejects at the bound even when the transport ignores its signal.
598
+ const expired = new Promise((_, reject) => {
599
+ timer = setTimeout(() => {
600
+ const reason = new DOMException('the models listing did not answer in time', 'TimeoutError');
601
+ bound.abort(reason);
602
+ reject(reason);
603
+ }, MODEL_LISTING_TIMEOUT_MS);
604
+ });
605
+ let onAbort;
606
+ // The caller's abort also ends the wait, whether or not the transport honours it.
607
+ const cancelled = new Promise((_, reject) => {
608
+ if (!signal)
609
+ return;
610
+ onAbort = () => reject(signal.reason ?? new DOMException('aborted', 'AbortError'));
611
+ signal.addEventListener('abort', onAbort, { once: true });
612
+ });
613
+ try {
614
+ return await Promise.race([
615
+ read(signal ? AbortSignal.any([bound.signal, signal]) : bound.signal),
616
+ expired,
617
+ cancelled,
618
+ ]);
619
+ }
620
+ finally {
621
+ if (onAbort)
622
+ signal?.removeEventListener('abort', onAbort);
623
+ clearTimeout(timer);
624
+ }
625
+ }
626
+ /** Did the listing read run past its bound (as opposed to failing some other way)? */
627
+ function isListingTimeout(err) {
628
+ return err instanceof Error && err.name === 'TimeoutError';
629
+ }
582
630
  export class OpenRouterProvider {
583
631
  id = 'openrouter';
584
632
  name = 'OpenRouter';
@@ -637,7 +685,7 @@ export class OpenRouterProvider {
637
685
  return headers;
638
686
  }
639
687
  formatMessages(messages, route) {
640
- const turnStart = currentTurnStart(messages);
688
+ const readsImages = this.supportsImageInputFor(route.model);
641
689
  // An assistant entry with neither text nor a tool call (the model produced
642
690
  // only reasoning, or was cut off) is rejected upstream with "content or
643
691
  // tool_calls must be set". Leave it out; no filler is invented. An entry
@@ -646,20 +694,78 @@ export class OpenRouterProvider {
646
694
  const sendable = messages
647
695
  .map((msg, index) => ({ msg, index }))
648
696
  .filter(({ msg }) => msg.role !== 'assistant' || Boolean(msg.content) || (msg.toolCalls?.length ?? 0) > 0);
649
- return sendable.map(({ msg, index }) => {
697
+ const wire = [];
698
+ const origin = [];
699
+ const callNames = new Map();
700
+ // A tool message carries text only on this wire. The images a turn's tools
701
+ // returned wait here and go out as ONE user message after the last of that
702
+ // turn's tool messages, because every tool message has to follow the
703
+ // assistant message that made the calls directly.
704
+ let pendingImages = [];
705
+ const flushToolImages = () => {
706
+ if (pendingImages.length === 0)
707
+ return;
708
+ const parts = [];
709
+ for (const { callId, image } of pendingImages) {
710
+ const name = callNames.get(callId);
711
+ parts.push({
712
+ type: 'text',
713
+ text: `Image returned by the ${name ? `\`${name}\` ` : ''}tool call ${callId}:`,
714
+ });
715
+ parts.push({
716
+ type: 'image_url',
717
+ image_url: { url: `data:${image.mediaType};base64,${image.data}` },
718
+ });
719
+ }
720
+ wire.push({ role: 'user', content: parts });
721
+ origin.push(-1);
722
+ pendingImages = [];
723
+ };
724
+ const push = (entry, index) => {
725
+ wire.push(entry);
726
+ origin.push(index);
727
+ };
728
+ for (const { msg, index } of sendable) {
729
+ if (msg.role !== 'tool')
730
+ flushToolImages();
650
731
  if (msg.role === 'tool') {
651
- return {
652
- role: 'tool',
653
- content: msg.content,
654
- tool_call_id: msg.toolCallId,
655
- };
732
+ const callId = msg.toolCallId;
733
+ if (typeof msg.content === 'string') {
734
+ push({ role: 'tool', content: msg.content, tool_call_id: callId }, index);
735
+ continue;
736
+ }
737
+ const text = [];
738
+ for (const block of toToolResultBlocks(msg.content)) {
739
+ if (block.type === 'text')
740
+ text.push(block.text);
741
+ else if (block.type === 'image') {
742
+ if (readsImages && !isModelContentOmission(block.modelOmission) && callId) {
743
+ pendingImages.push({ callId, image: block });
744
+ text.push('[image attached in the next message]');
745
+ }
746
+ else {
747
+ text.push(`[image omitted: this model cannot read it (${block.mediaType}, ${block.data.length} B)]`);
748
+ }
749
+ }
750
+ else
751
+ text.push(`[document omitted: ${block.mediaType} cannot be sent here]`);
752
+ }
753
+ push({ role: 'tool', content: text.join('\n'), tool_call_id: callId }, index);
754
+ continue;
656
755
  }
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;
756
+ // The model's own reasoning goes back with the message that produced it,
757
+ // for every assistant message of the conversation, not only the current
758
+ // turn's. A message's bytes must not change from one request to the next:
759
+ // the upstream caches by prefix, and an earlier message re-sent without
760
+ // the reasoning it was sent with before moves the prefix and bills the
761
+ // whole history again at the first new user message. Reasoning leaves
762
+ // the history only when a compaction rewrites it (the stored reasoning
763
+ // then no longer matches the envelope and `replayFor` answers nothing).
764
+ const replay = msg.role === 'assistant' ? replayFor(msg, route) : undefined;
661
765
  if (msg.role === 'assistant' && 'toolCalls' in msg && msg.toolCalls?.length) {
662
- return {
766
+ for (const tc of msg.toolCalls)
767
+ callNames.set(tc.id, tc.function.name);
768
+ push({
663
769
  role: 'assistant',
664
770
  content: msg.content,
665
771
  tool_calls: msg.toolCalls.map((tc) => ({
@@ -668,15 +774,43 @@ export class OpenRouterProvider {
668
774
  function: tc.function,
669
775
  })),
670
776
  ...replay,
671
- };
777
+ }, index);
778
+ continue;
672
779
  }
673
- return { role: msg.role, content: msg.content, ...replay };
674
- });
780
+ if (msg.role === 'user' && msg.attachments && msg.attachments.length > 0) {
781
+ const parts = [];
782
+ if (msg.content.length > 0)
783
+ parts.push({ type: 'text', text: msg.content });
784
+ for (const attachment of msg.attachments) {
785
+ // Only inline images have a wire form here. A document is turned
786
+ // into a placeholder and a stored reference is resolved by the
787
+ // runtime before this point; an image the runtime already withheld
788
+ // from the model stays withheld.
789
+ if (attachment.type === 'stored' || attachment.type === 'document')
790
+ continue;
791
+ if (isModelContentOmission(attachment.modelOmission))
792
+ continue;
793
+ parts.push({
794
+ type: 'image_url',
795
+ image_url: { url: `data:${attachment.mediaType};base64,${attachment.data}` },
796
+ });
797
+ }
798
+ push({
799
+ role: 'user',
800
+ content: parts.some((part) => part.type === 'image_url') ? parts : msg.content,
801
+ }, index);
802
+ continue;
803
+ }
804
+ push({ role: msg.role, content: msg.content, ...replay }, index);
805
+ }
806
+ flushToolImages();
807
+ return { wire, origin };
675
808
  }
676
809
  buildRequestBody(params, stream, supportedEfforts) {
810
+ const formatted = this.formatMessages(params.messages, routeOf(params));
677
811
  const body = {
678
812
  model: params.model,
679
- messages: this.formatMessages(params.messages, routeOf(params)),
813
+ messages: formatted.wire,
680
814
  stream,
681
815
  };
682
816
  if (params.tools && params.tools.length > 0) {
@@ -716,7 +850,7 @@ export class OpenRouterProvider {
716
850
  if (params.stop)
717
851
  body.stop = params.stop;
718
852
  if (params.cacheControl && takesExplicitBreakpoints(params.model)) {
719
- applyCacheBreakpoints(params.messages, body.messages);
853
+ applyCacheBreakpoints(params.messages, body.messages, formatted.origin);
720
854
  }
721
855
  // `max` and `ultra` resolve against the model's own list — see
722
856
  // `carriedEffort`.
@@ -946,6 +1080,24 @@ export class OpenRouterProvider {
946
1080
  * requires the credential and returns its metadata, so a 401 here means the
947
1081
  * key is genuinely refused.
948
1082
  */
1083
+ /**
1084
+ * The key's limit and use, from one GET of `/key`. Any failure or unexpected body is "not
1085
+ * reported", never a zero.
1086
+ */
1087
+ async readLimits(signal) {
1088
+ try {
1089
+ const response = await fetch(`${this.baseUrl}/key`, {
1090
+ headers: this.getHeaders(),
1091
+ ...(signal ? { signal } : {}),
1092
+ });
1093
+ if (!response.ok)
1094
+ return undefined;
1095
+ return parseKeyLimits(await response.json(), Date.now());
1096
+ }
1097
+ catch {
1098
+ return undefined;
1099
+ }
1100
+ }
949
1101
  async probeCredential(signal) {
950
1102
  signal?.throwIfAborted();
951
1103
  const response = await fetch(`${this.baseUrl}/key`, {
@@ -987,7 +1139,19 @@ export class OpenRouterProvider {
987
1139
  return undefined;
988
1140
  let windows = this.contextWindows;
989
1141
  if (!windows) {
990
- const models = await this.listModels(signal);
1142
+ let models;
1143
+ try {
1144
+ models = await this.listModels(signal);
1145
+ }
1146
+ catch (err) {
1147
+ // A listing that outlasts its bound is "no listing": the
1148
+ // caller's static table answers. A caller abort stays an abort.
1149
+ if (signal?.aborted)
1150
+ return undefined;
1151
+ if (isListingTimeout(err))
1152
+ return undefined;
1153
+ throw err;
1154
+ }
991
1155
  if (signal?.aborted)
992
1156
  return undefined;
993
1157
  windows = new Map(models
@@ -1018,17 +1182,19 @@ export class OpenRouterProvider {
1018
1182
  if (!table) {
1019
1183
  try {
1020
1184
  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),
1185
+ // Bounded on its own: this read sits in front of the first max or
1186
+ // ultra request, so a stalled listing must not stall that request.
1187
+ const data = await withListingBound(signal, async (bounded) => {
1188
+ const response = await fetch(`${this.baseUrl}/models`, {
1189
+ headers: this.getHeaders(),
1190
+ signal: bounded,
1191
+ });
1192
+ if (!response.ok)
1193
+ return undefined;
1194
+ return (await response.json());
1028
1195
  });
1029
- if (!response.ok)
1196
+ if (!data)
1030
1197
  return undefined;
1031
- const data = (await response.json());
1032
1198
  table = new Map();
1033
1199
  for (const m of data.data ?? []) {
1034
1200
  const levels = m.reasoning?.supported_efforts;
@@ -1048,19 +1214,46 @@ export class OpenRouterProvider {
1048
1214
  return table.get(model) ?? (tag > 0 ? table.get(model.slice(0, tag)) : undefined);
1049
1215
  }
1050
1216
  supportedEfforts;
1217
+ /**
1218
+ * Whether the model reads images, as the listing last said (`architecture.input_modalities`).
1219
+ * Filled by `listModels`, which the context-window lookup runs once per driver, so
1220
+ * answering costs no request of its own. Empty until a listing was read.
1221
+ */
1222
+ imageInput = new Map();
1223
+ /**
1224
+ * Whether `model` reads images. `false` only when the listing named the model's input
1225
+ * kinds and `image` was not among them. A model the listing does not name, or a
1226
+ * listing not read yet, answers `true`: a wrong "no" blinds a vision model, while a
1227
+ * wrong "yes" is recovered from when the router refuses the request.
1228
+ */
1229
+ supportsImageInputFor(model) {
1230
+ const tag = model.indexOf(':');
1231
+ return (this.imageInput.get(model) ??
1232
+ (tag > 0 ? this.imageInput.get(model.slice(0, tag)) : undefined) ??
1233
+ true);
1234
+ }
1051
1235
  /** First fulfilled listing; see the note on `resolveContextWindow`. */
1052
1236
  contextWindows;
1053
1237
  async listModels(signal) {
1054
1238
  signal?.throwIfAborted();
1055
- const response = await fetch(`${this.baseUrl}/models`, {
1056
- headers: this.getHeaders(),
1057
- ...(signal ? { signal } : {}),
1239
+ const data = await withListingBound(signal, async (bounded) => {
1240
+ const response = await fetch(`${this.baseUrl}/models`, {
1241
+ headers: this.getHeaders(),
1242
+ signal: bounded,
1243
+ });
1244
+ if (!response.ok) {
1245
+ throw new Error(`Failed to list models: ${response.status}`);
1246
+ }
1247
+ return (await response.json());
1058
1248
  });
1059
- if (!response.ok) {
1060
- throw new Error(`Failed to list models: ${response.status}`);
1061
- }
1062
- const data = (await response.json());
1063
1249
  signal?.throwIfAborted();
1250
+ const imageInput = new Map();
1251
+ for (const m of data.data) {
1252
+ const kinds = m.architecture?.input_modalities;
1253
+ if (Array.isArray(kinds))
1254
+ imageInput.set(m.id, kinds.includes('image'));
1255
+ }
1256
+ this.imageInput = imageInput;
1064
1257
  return data.data.map((m) => {
1065
1258
  const inputPrice = pricePerMillion(m.pricing?.prompt);
1066
1259
  const outputPrice = pricePerMillion(m.pricing?.completion);
@@ -1071,6 +1264,14 @@ export class OpenRouterProvider {
1071
1264
  maxOutputTokens: m.top_provider?.max_completion_tokens ?? 4096,
1072
1265
  ...(inputPrice !== undefined ? { inputPrice } : {}),
1073
1266
  ...(outputPrice !== undefined ? { outputPrice } : {}),
1267
+ ...(Array.isArray(m.architecture?.input_modalities)
1268
+ ? {
1269
+ inputModalities: [
1270
+ 'text',
1271
+ ...(imageInput.get(m.id) ? ['image'] : []),
1272
+ ],
1273
+ }
1274
+ : {}),
1074
1275
  supportsToolUse: true,
1075
1276
  supportsStreaming: true,
1076
1277
  };
@@ -1078,11 +1279,13 @@ export class OpenRouterProvider {
1078
1279
  }
1079
1280
  async healthCheck() {
1080
1281
  try {
1081
- const response = await fetch(`${this.baseUrl}/models`, {
1082
- headers: this.getHeaders(),
1083
- signal: AbortSignal.timeout(5000),
1282
+ return await withListingBound(undefined, async (bounded) => {
1283
+ const response = await fetch(`${this.baseUrl}/models`, {
1284
+ headers: this.getHeaders(),
1285
+ signal: bounded,
1286
+ });
1287
+ return response.ok;
1084
1288
  });
1085
- return response.ok;
1086
1289
  }
1087
1290
  catch {
1088
1291
  return false;