tuxevil-rotator 3.7.1 → 3.8.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.
@@ -58,6 +58,19 @@ export function applyConfigDefaults(config: Config): Config {
58
58
  modelSpecs: config.modelSpecs,
59
59
  modelAliases: config.modelAliases,
60
60
  effortRouting: config.effortRouting,
61
+ typesafeRouting: config.typesafeRouting
62
+ ? {
63
+ enabled: config.typesafeRouting.enabled ?? Boolean(config.typesafeRouting.apiKey),
64
+ apiKey: config.typesafeRouting.apiKey,
65
+ model: config.typesafeRouting.model ?? "jev-latest",
66
+ baseURL: config.typesafeRouting.baseURL,
67
+ timeoutMs: config.typesafeRouting.timeoutMs ?? 3_000,
68
+ minConfidence: config.typesafeRouting.minConfidence ?? 0.45,
69
+ maxCandidates: config.typesafeRouting.maxCandidates ?? 32,
70
+ shortlistSize: config.typesafeRouting.shortlistSize ?? 12,
71
+ maxExcerptChars: config.typesafeRouting.maxExcerptChars ?? 12_000,
72
+ }
73
+ : undefined,
61
74
  accounts: config.accounts ? config.accounts.map((account) => ({
62
75
  ...normalizeAccountConfig(account),
63
76
  tier: account.tier || "unknown",
package/src/dashboard.ts CHANGED
@@ -106,7 +106,7 @@ export function serveConfigApi(
106
106
  "Content-Type": "application/json",
107
107
  "Cache-Control": "no-store",
108
108
  });
109
- res.end(JSON.stringify(rotator.getConfig()));
109
+ res.end(JSON.stringify(rotator.getPublicConfig()));
110
110
  }
111
111
 
112
112
  /**
@@ -145,7 +145,7 @@ export function serveConfigExportApi(
145
145
  "Content-Disposition":
146
146
  'attachment; filename="tuxevil-rotator-config.json"',
147
147
  });
148
- res.end(JSON.stringify(rotator.getConfig(), null, 2));
148
+ res.end(JSON.stringify(rotator.getPublicConfig(), null, 2));
149
149
  }
150
150
 
151
151
  export async function serveConfigImportApi(
package/src/db-store.ts CHANGED
@@ -12,7 +12,9 @@ import { rotatorEnv } from "./env.js";
12
12
  import { applyConfigDefaults } from "./config-defaults.js";
13
13
  import {
14
14
  decryptAccountsInConfig,
15
+ decryptTypeSafeRoutingInConfig,
15
16
  encryptAccountsInConfig,
17
+ encryptTypeSafeRoutingInConfig,
16
18
  } from "./token-encryption.js";
17
19
  import {
18
20
  type ISettingsRepository,
@@ -94,8 +96,10 @@ export function getCachedConfig(): Config | null {
94
96
  const validation = validateConfig(parsed);
95
97
  if (validation.ok && validation.value) {
96
98
  const withDefaults = applyConfigDefaults(validation.value);
97
- const { config: decryptedConfig, migrated } = decryptAccountsInConfig(withDefaults);
98
- if (migrated) {
99
+ const accountsResult = decryptAccountsInConfig(withDefaults);
100
+ const typesafeResult = decryptTypeSafeRoutingInConfig(accountsResult.config);
101
+ const decryptedConfig = typesafeResult.config;
102
+ if (accountsResult.migrated || typesafeResult.migrated) {
99
103
  void setCachedConfig(decryptedConfig).catch((err) => {
100
104
  console.error(`Failed to persist migrated accounts config: ${err}`);
101
105
  });
@@ -111,7 +115,9 @@ export function getCachedConfig(): Config | null {
111
115
  export async function setCachedConfig(config: Config): Promise<void> {
112
116
  assertInitialized();
113
117
  const withDefaults = applyConfigDefaults(config);
114
- const encryptedConfig = encryptAccountsInConfig(withDefaults);
118
+ const encryptedConfig = encryptTypeSafeRoutingInConfig(
119
+ encryptAccountsInConfig(withDefaults),
120
+ );
115
121
  await repository.set("accounts_json", JSON.stringify(encryptedConfig, null, 2));
116
122
  }
117
123
 
@@ -15,6 +15,23 @@ export interface FetchWithRetryOptions extends RequestInit {
15
15
  export type RequestInitWithDispatcher = RequestInit & { dispatcher?: Dispatcher };
16
16
 
17
17
  export const DEFAULT_RETRY_STATUSES = [408, 429, 500, 502, 503, 504] as const;
18
+ export const DEFAULT_HEADERS_TIMEOUT_MS = 30_000;
19
+
20
+ /** Raised when an upstream accepts a request but never sends response headers. */
21
+ export class UpstreamHeadersTimeoutError extends Error {
22
+ readonly code = "UND_ERR_HEADERS_TIMEOUT";
23
+
24
+ constructor(timeoutMs: number) {
25
+ super(`upstream response headers timeout after ${timeoutMs}ms`);
26
+ this.name = "UpstreamHeadersTimeoutError";
27
+ }
28
+ }
29
+
30
+ export interface FetchWithHeadersTimeoutOptions extends RequestInit {
31
+ timeoutMs?: number;
32
+ fetchImpl?: typeof fetch;
33
+ dispatcher?: Dispatcher;
34
+ }
18
35
 
19
36
  export function isRetryableStatus(status: number, retryStatuses: readonly number[] = DEFAULT_RETRY_STATUSES): boolean {
20
37
  return retryStatuses.includes(status);
@@ -22,6 +39,7 @@ export function isRetryableStatus(status: number, retryStatuses: readonly number
22
39
 
23
40
  export function isRetryableFetchError(error: unknown): boolean {
24
41
  if (error instanceof DOMException && error.name === "AbortError") return true;
42
+ if (error instanceof UpstreamHeadersTimeoutError) return true;
25
43
  return error instanceof TypeError;
26
44
  }
27
45
 
@@ -47,6 +65,59 @@ function createTimeoutSignal(timeoutMs: number | undefined, inputSignal: AbortSi
47
65
  return AbortSignal.any([inputSignal, timeoutSignal]);
48
66
  }
49
67
 
68
+ /**
69
+ * Fetch a response while bounding only the time spent waiting for its headers.
70
+ * Once headers arrive, the caller owns the response body and its stream-level
71
+ * idle/backpressure guards continue to apply.
72
+ */
73
+ export async function fetchWithHeadersTimeout(
74
+ input: RequestInfo | URL,
75
+ options: FetchWithHeadersTimeoutOptions = {},
76
+ ): Promise<Response> {
77
+ const {
78
+ timeoutMs = DEFAULT_HEADERS_TIMEOUT_MS,
79
+ fetchImpl = fetch,
80
+ dispatcher,
81
+ signal: inputSignal,
82
+ ...init
83
+ } = options;
84
+
85
+ if (!timeoutMs || timeoutMs <= 0) {
86
+ return fetchImpl(input, {
87
+ ...init,
88
+ dispatcher,
89
+ signal: inputSignal,
90
+ } as RequestInitWithDispatcher);
91
+ }
92
+
93
+ const timeoutController = new AbortController();
94
+ let timedOut = false;
95
+ const timeout = setTimeout(() => {
96
+ timedOut = true;
97
+ timeoutController.abort();
98
+ }, timeoutMs);
99
+ const requestSignal = inputSignal
100
+ ? AbortSignal.any([inputSignal, timeoutController.signal])
101
+ : timeoutController.signal;
102
+
103
+ try {
104
+ return await fetchImpl(input, {
105
+ ...init,
106
+ dispatcher,
107
+ signal: requestSignal,
108
+ } as RequestInitWithDispatcher);
109
+ } catch (error) {
110
+ // A client cancellation must retain its original error and must not cause
111
+ // the rotator to retry work the client no longer wants.
112
+ if (timedOut && !inputSignal?.aborted) {
113
+ throw new UpstreamHeadersTimeoutError(timeoutMs);
114
+ }
115
+ throw error;
116
+ } finally {
117
+ clearTimeout(timeout);
118
+ }
119
+ }
120
+
50
121
  /**
51
122
  * Fetch wrapper for non-streaming calls. Retries only transport failures and explicit retryable statuses.
52
123
  * Do not use for streaming responses: retrying streams can duplicate upstream work.
package/src/key-auth.ts CHANGED
@@ -15,6 +15,20 @@ export interface KeyAuthResult {
15
15
  statusCode?: number;
16
16
  }
17
17
 
18
+ /** Checks a resolved model against the optional virtual-key model scope. */
19
+ export function isVirtualKeyModelAllowed(
20
+ key: VirtualKey | null,
21
+ targetModel: string,
22
+ ): boolean {
23
+ if (!key?.models || key.models.length === 0 || key.models.includes("*")) return true;
24
+ const normalizedTarget = targetModel.toLowerCase();
25
+ return key.models.some(
26
+ (model) =>
27
+ model.toLowerCase() === normalizedTarget ||
28
+ normalizedTarget.includes(model.toLowerCase()),
29
+ );
30
+ }
31
+
18
32
  /**
19
33
  * Extracts virtual key raw string from headers or query parameters.
20
34
  */
@@ -110,20 +124,7 @@ export async function authenticateVirtualKey(
110
124
  }
111
125
 
112
126
  // Model access restrictions
113
- if (
114
- targetModel &&
115
- key.models &&
116
- key.models.length > 0 &&
117
- !key.models.includes("*")
118
- ) {
119
- const normalizedTarget = targetModel.toLowerCase();
120
- const isAllowed = key.models.some(
121
- (m) =>
122
- m.toLowerCase() === normalizedTarget ||
123
- normalizedTarget.includes(m.toLowerCase()),
124
- );
125
-
126
- if (!isAllowed) {
127
+ if (targetModel && !isVirtualKeyModelAllowed(key, targetModel)) {
127
128
  return {
128
129
  authenticated: false,
129
130
  key,
@@ -131,7 +132,6 @@ export async function authenticateVirtualKey(
131
132
  error: `Model '${targetModel}' is not allowed for this Virtual Key`,
132
133
  statusCode: 403,
133
134
  };
134
- }
135
135
  }
136
136
 
137
137
  touchVirtualKeyLastActive(key.tokenHash);
package/src/onboarding.ts CHANGED
@@ -31,10 +31,17 @@ import {
31
31
  parseCodexIdentity,
32
32
  type CodexOAuthConfig,
33
33
  } from "./providers/openai-codex/oauth.js";
34
- import type { AccountConfig } from "./types.js";
34
+ import type { AccountConfig, Config } from "./types.js";
35
35
 
36
36
  interface AccountSink {
37
37
  addOrUpdateAccount(account: AccountConfig): Promise<void>;
38
+ getConfig?(): Config;
39
+ replaceConfig?(config: Config): Promise<void>;
40
+ }
41
+
42
+ interface TypeSafeConfigSink {
43
+ getConfig(): Config;
44
+ replaceConfig(config: Config): Promise<void>;
38
45
  }
39
46
 
40
47
  interface PendingSession {
@@ -303,8 +310,14 @@ function pruneCliSessions(): void {
303
310
  }
304
311
  }
305
312
 
306
- export function serveCliLogin(res: ServerResponse): void {
313
+ export function serveCliLogin(
314
+ res: ServerResponse,
315
+ configSource?: Pick<TypeSafeConfigSink, "getConfig">,
316
+ ): void {
307
317
  pruneCliSessions();
318
+ const currentTypeSafe = configSource?.getConfig().typesafeRouting;
319
+ const typeSafeConfigured = Boolean(currentTypeSafe?.apiKey);
320
+ const typeSafeModel = currentTypeSafe?.model || "jev-latest";
308
321
  const { verifier, challenge } = generatePkce();
309
322
  const oauthState = generateState();
310
323
  let authUrl: string | null = null;
@@ -358,6 +371,7 @@ export function serveCliLogin(res: ServerResponse): void {
358
371
  <button class="tab" data-panel="panel-codex">OpenAI Codex</button>
359
372
  <button class="tab" data-panel="panel-ollama">Ollama Cloud</button>
360
373
  <button class="tab" data-panel="panel-zen">OpenCode Zen</button>
374
+ <button class="tab" data-panel="panel-typesafe">TypeSafe Jev</button>
361
375
  </div>
362
376
 
363
377
  <div class="panel active" id="panel-google">
@@ -432,6 +446,24 @@ ${codexAuthUrl && codexSessionId ? `<h3 style="margin:24px 0 8px;font-size:18px;
432
446
  </form>
433
447
  </div>
434
448
 
449
+ <div class="panel" id="panel-typesafe">
450
+ <p>Configure TypeSafe Jev for optional <code>model: "auto"</code> routing. The key is stored encrypted with the rotator configuration in PostgreSQL when a database is configured.</p>
451
+ <p class="mono">${typeSafeConfigured ? "A Jev key is already configured. Leave the key field empty to keep it." : "No Jev key is configured yet."}</p>
452
+ <form id="typesafeForm" style="margin-top:12px;">
453
+ <label for="typesafeApiKey">TypeSafe API key</label>
454
+ <input id="typesafeApiKey" name="apiKey" class="field" type="password" placeholder="Paste a new TypeSafe API key" autocomplete="new-password" />
455
+ <label for="typesafeModel">Jev model</label>
456
+ <input id="typesafeModel" name="model" class="field" value="${escapeHtml(typeSafeModel)}" placeholder="jev-latest" autocomplete="off" />
457
+ <label style="display:flex;align-items:center;gap:8px;margin-top:16px;">
458
+ <input name="enabled" type="checkbox" ${currentTypeSafe?.enabled !== false ? "checked" : ""} />
459
+ Enable Jev when requests use <code>model: "auto"</code>
460
+ </label>
461
+ <button type="submit" class="cta" style="cursor:pointer;border:none;font-family:inherit;font-size:16px;margin-top:16px;">
462
+ Save Jev configuration
463
+ </button>
464
+ </form>
465
+ </div>
466
+
435
467
  <div id="result" style="margin-top:18px;"></div>
436
468
 
437
469
  <script>
@@ -617,6 +649,49 @@ if (zenForm) zenForm.addEventListener('submit', async (e) => {
617
649
  btn.textContent = 'Connect Account';
618
650
  }
619
651
  });
652
+
653
+ const typesafeForm = document.getElementById('typesafeForm');
654
+ if (typesafeForm) typesafeForm.addEventListener('submit', async (e) => {
655
+ e.preventDefault();
656
+ const form = e.target;
657
+ const btn = form.querySelector('button[type=submit]');
658
+ const apiKey = form.apiKey.value.trim();
659
+ const model = form.model.value.trim();
660
+ const enabled = form.enabled.checked;
661
+ if (!model) { showResult('<div class="note error">Please enter a Jev model alias.</div>'); return; }
662
+ btn.disabled = true;
663
+ btn.textContent = 'Saving...';
664
+ showResult('<div class="note">Saving the encrypted Jev configuration...</div>');
665
+ try {
666
+ const params = new URLSearchParams(window.location.search);
667
+ const token = params.get('token') || '';
668
+ const payload = { provider: 'typesafe', ...(apiKey ? { apiKey } : {}), model, enabled };
669
+ const res = await fetch('/api/cli-login', {
670
+ method: 'POST',
671
+ headers: { 'Content-Type': 'application/json', ...(token ? { 'X-Rotator-Admin-Token': token } : {}) },
672
+ body: JSON.stringify(payload),
673
+ });
674
+ const data = await res.json();
675
+ if (data.ok) {
676
+ showResult('<div class="note" style="border-left-color:var(--accent);background:rgba(30,107,82,0.12);">TypeSafe Jev configuration saved. The API key is not returned by the server.</div>');
677
+ } else {
678
+ const errorDiv = document.createElement('div');
679
+ errorDiv.className = 'note error';
680
+ errorDiv.textContent = data.error || 'Unable to save TypeSafe configuration';
681
+ document.getElementById('result').innerHTML = '';
682
+ document.getElementById('result').appendChild(errorDiv);
683
+ }
684
+ } catch (err) {
685
+ const errorDiv = document.createElement('div');
686
+ errorDiv.className = 'note error';
687
+ errorDiv.textContent = 'Request failed: ' + err.message;
688
+ document.getElementById('result').innerHTML = '';
689
+ document.getElementById('result').appendChild(errorDiv);
690
+ } finally {
691
+ btn.disabled = false;
692
+ btn.textContent = 'Save Jev configuration';
693
+ }
694
+ });
620
695
  </script>
621
696
  `,
622
697
  ),
@@ -634,6 +709,8 @@ export async function handleCliLoginApi(
634
709
  redirectUrl?: string;
635
710
  email?: string;
636
711
  apiKey?: string;
712
+ model?: string;
713
+ enabled?: boolean;
637
714
  };
638
715
  try {
639
716
  const raw = await readLimitedBody(req, MAX_CLI_LOGIN_BODY_BYTES);
@@ -647,6 +724,8 @@ export async function handleCliLoginApi(
647
724
  redirectUrl?: string;
648
725
  email?: string;
649
726
  apiKey?: string;
727
+ model?: string;
728
+ enabled?: boolean;
650
729
  };
651
730
  } catch (err) {
652
731
  res.writeHead(err instanceof PayloadTooLargeError ? 413 : 400, {
@@ -673,6 +752,25 @@ export async function handleCliLoginApi(
673
752
  return;
674
753
  }
675
754
 
755
+ if (provider === "typesafe") {
756
+ if (
757
+ typeof rotator.getConfig !== "function" ||
758
+ typeof rotator.replaceConfig !== "function"
759
+ ) {
760
+ res.writeHead(500, { "Content-Type": "application/json" });
761
+ res.end(JSON.stringify({
762
+ ok: false,
763
+ error: "TypeSafe configuration is unavailable on this server",
764
+ }));
765
+ return;
766
+ }
767
+ await handleTypeSafeCliLogin(body, res, {
768
+ getConfig: () => rotator.getConfig!(),
769
+ replaceConfig: (config) => rotator.replaceConfig!(config),
770
+ });
771
+ return;
772
+ }
773
+
676
774
  if (provider !== "google-antigravity") {
677
775
  res.writeHead(400, { "Content-Type": "application/json" });
678
776
  res.end(JSON.stringify({ ok: false, error: `Unknown provider "${provider}"` }));
@@ -791,6 +889,80 @@ export async function handleCliLoginApi(
791
889
  }
792
890
  }
793
891
 
892
+ async function handleTypeSafeCliLogin(
893
+ body: { apiKey?: string; model?: string; enabled?: boolean },
894
+ res: ServerResponse,
895
+ rotator: TypeSafeConfigSink,
896
+ ): Promise<void> {
897
+ if (body.apiKey !== undefined && typeof body.apiKey !== "string") {
898
+ res.writeHead(400, { "Content-Type": "application/json" });
899
+ res.end(JSON.stringify({ ok: false, error: "Invalid apiKey" }));
900
+ return;
901
+ }
902
+ if (body.model !== undefined && typeof body.model !== "string") {
903
+ res.writeHead(400, { "Content-Type": "application/json" });
904
+ res.end(JSON.stringify({ ok: false, error: "Invalid Jev model" }));
905
+ return;
906
+ }
907
+ if (body.enabled !== undefined && typeof body.enabled !== "boolean") {
908
+ res.writeHead(400, { "Content-Type": "application/json" });
909
+ res.end(JSON.stringify({ ok: false, error: "Invalid enabled flag" }));
910
+ return;
911
+ }
912
+
913
+ const apiKey = body.apiKey?.trim() ?? "";
914
+ const model = body.model?.trim() ?? "";
915
+ const enabled = body.enabled ?? true;
916
+ if (apiKey.length > 4096) {
917
+ res.writeHead(400, { "Content-Type": "application/json" });
918
+ res.end(JSON.stringify({ ok: false, error: "API key too long" }));
919
+ return;
920
+ }
921
+ if (!model || model.length > 128) {
922
+ res.writeHead(400, { "Content-Type": "application/json" });
923
+ res.end(JSON.stringify({ ok: false, error: "Invalid Jev model" }));
924
+ return;
925
+ }
926
+
927
+ const current = rotator.getConfig();
928
+ const currentRouting = current.typesafeRouting ?? {};
929
+ if (!apiKey && !currentRouting.apiKey) {
930
+ res.writeHead(400, { "Content-Type": "application/json" });
931
+ res.end(JSON.stringify({ ok: false, error: "Missing TypeSafe API key" }));
932
+ return;
933
+ }
934
+
935
+ const nextConfig: Config = {
936
+ ...current,
937
+ typesafeRouting: {
938
+ ...currentRouting,
939
+ ...(apiKey ? { apiKey } : {}),
940
+ enabled,
941
+ model,
942
+ },
943
+ };
944
+
945
+ try {
946
+ await rotator.replaceConfig(nextConfig);
947
+ } catch (error) {
948
+ const message = error instanceof Error ? error.message : "";
949
+ const userError = /ENCRYPTION_KEY/i.test(message)
950
+ ? "Configure TUXEVIL_ROTATOR_ENCRYPTION_KEY before saving the Jev key."
951
+ : "Unable to save TypeSafe configuration.";
952
+ res.writeHead(500, { "Content-Type": "application/json" });
953
+ res.end(JSON.stringify({ ok: false, error: userError }));
954
+ return;
955
+ }
956
+
957
+ res.writeHead(200, { "Content-Type": "application/json" });
958
+ res.end(JSON.stringify({
959
+ ok: true,
960
+ configured: true,
961
+ enabled,
962
+ model,
963
+ }));
964
+ }
965
+
794
966
  async function handleCodexCliLogin(
795
967
  body: { session?: string; redirectUrl?: string },
796
968
  res: ServerResponse,
@@ -14,6 +14,7 @@ import type { AccountConfig } from "../types.js";
14
14
  export interface TokenUsage {
15
15
  inputTokens: number;
16
16
  outputTokens: number;
17
+ cachedTokens?: number;
17
18
  }
18
19
 
19
20
  /**
@@ -15,7 +15,10 @@ import { logger } from "../../logger.js";
15
15
  import type { TokenUsage } from "../adapter.js";
16
16
  import { DEFAULT_PROVIDER, getProviderProjectId } from "../credential-helpers.js";
17
17
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
18
- import type { RequestInitWithDispatcher } from "../../fetch-with-retry.js";
18
+ import {
19
+ fetchWithHeadersTimeout,
20
+ type RequestInitWithDispatcher,
21
+ } from "../../fetch-with-retry.js";
19
22
 
20
23
  const forwardLogger = logger.child("google-forward");
21
24
 
@@ -53,8 +56,18 @@ function findUsageInJson(
53
56
  : typeof usageMetadata.outputTokenCount === "number"
54
57
  ? usageMetadata.outputTokenCount
55
58
  : 0;
59
+ const cached =
60
+ typeof usageMetadata.cachedContentTokenCount === "number"
61
+ ? usageMetadata.cachedContentTokenCount
62
+ : typeof usageMetadata.cached_tokens === "number"
63
+ ? usageMetadata.cached_tokens
64
+ : undefined;
56
65
  if (input > 0 || output > 0)
57
- return { inputTokens: input, outputTokens: output };
66
+ return {
67
+ inputTokens: input,
68
+ outputTokens: output,
69
+ ...(cached !== undefined ? { cachedTokens: cached } : {}),
70
+ };
58
71
  }
59
72
  // OpenAI / Anthropic format
60
73
  const usage = value.usage;
@@ -71,8 +84,21 @@ function findUsageInJson(
71
84
  : typeof usage.output_tokens === "number"
72
85
  ? usage.output_tokens
73
86
  : 0;
87
+ const cached =
88
+ isRecord(usage.prompt_tokens_details) &&
89
+ typeof usage.prompt_tokens_details.cached_tokens === "number"
90
+ ? usage.prompt_tokens_details.cached_tokens
91
+ : typeof usage.cached_tokens === "number"
92
+ ? usage.cached_tokens
93
+ : typeof usage.cache_read_input_tokens === "number"
94
+ ? usage.cache_read_input_tokens
95
+ : undefined;
74
96
  if (input > 0 || output > 0)
75
- return { inputTokens: input, outputTokens: output };
97
+ return {
98
+ inputTokens: input,
99
+ outputTokens: output,
100
+ ...(cached !== undefined ? { cachedTokens: cached } : {}),
101
+ };
76
102
  }
77
103
  // Recurse into common nesting locations.
78
104
  for (const key of ["candidates", "output", "response", "message"]) {
@@ -304,7 +330,14 @@ export async function forwardRequest(
304
330
  // of truth: src/types.ts:applyModelAlias)
305
331
  body.model = applyModelAlias(body.model);
306
332
 
307
- const { displayModel: _displayModel, ...bodyToForward } = body;
333
+ const {
334
+ displayModel: _displayModel,
335
+ providerId: _providerId,
336
+ selectionMode: _selectionMode,
337
+ selectionConfidence: _selectionConfidence,
338
+ selectionReason: _selectionReason,
339
+ ...bodyToForward
340
+ } = body;
308
341
  const requestBody = JSON.stringify(bodyToForward);
309
342
 
310
343
  // Build headers: keep originals but swap Authorization
@@ -381,7 +414,7 @@ export async function forwardRequest(
381
414
  ? AbortSignal.any([controller.signal, signal])
382
415
  : signal ?? controller?.signal;
383
416
 
384
- const response = await fetch(url, {
417
+ const response = await fetchWithHeadersTimeout(url, {
385
418
  method: "POST",
386
419
  headers: forwardHeaders,
387
420
  body: requestBody,
@@ -178,6 +178,7 @@ export interface CompatCompletion {
178
178
  thinkingText?: string; // Gemini thought blocks (thought: true), emitted as reasoning_content
179
179
  inputTokens: number;
180
180
  outputTokens: number;
181
+ cachedTokens?: number;
181
182
  firstByteMs?: number;
182
183
  responseId?: string;
183
184
  toolCalls?: OpenAIToolCall[];
@@ -1683,7 +1684,7 @@ export function responseUsageFromCompletion(
1683
1684
  ): Record<string, unknown> {
1684
1685
  return {
1685
1686
  input_tokens: completion.inputTokens,
1686
- input_tokens_details: { cached_tokens: 0 },
1687
+ input_tokens_details: { cached_tokens: completion.cachedTokens ?? 0 },
1687
1688
  output_tokens: completion.outputTokens,
1688
1689
  output_tokens_details: { reasoning_tokens: 0 },
1689
1690
  total_tokens: completion.inputTokens + completion.outputTokens,
@@ -18,7 +18,10 @@ import {
18
18
  } from "../google-antigravity/translators.js";
19
19
  import type { StreamAccumulator, TokenUsage } from "../adapter.js";
20
20
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
21
- import type { RequestInitWithDispatcher } from "../../fetch-with-retry.js";
21
+ import {
22
+ fetchWithHeadersTimeout,
23
+ type RequestInitWithDispatcher,
24
+ } from "../../fetch-with-retry.js";
22
25
 
23
26
  const OLLAMA_BENCHMARK_MODEL = "gpt-oss:20b";
24
27
 
@@ -146,7 +149,7 @@ export async function forwardRequest(
146
149
  delete forwardHeaders["content-length"];
147
150
 
148
151
  const endpoint = OLLAMA_CHAT_ENDPOINTS[0] || "https://ollama.com/api/chat";
149
- const response = await fetch(endpoint, {
152
+ const response = await fetchWithHeadersTimeout(endpoint, {
150
153
  method: "POST",
151
154
  headers: forwardHeaders,
152
155
  body: requestBody,