tuxevil-rotator 3.7.2 → 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.
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,
@@ -330,7 +330,14 @@ export async function forwardRequest(
330
330
  // of truth: src/types.ts:applyModelAlias)
331
331
  body.model = applyModelAlias(body.model);
332
332
 
333
- 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;
334
341
  const requestBody = JSON.stringify(bodyToForward);
335
342
 
336
343
  // Build headers: keep originals but swap Authorization
@@ -37,6 +37,11 @@ export interface CodexCompatOptions {
37
37
  apiKeyHash?: string | null;
38
38
  requesterIp?: string | null;
39
39
  rawRequest?: unknown;
40
+ providerId?: string;
41
+ requestedModel?: string;
42
+ selectionMode?: "typesafe" | "deterministic" | "disabled";
43
+ selectionConfidence?: number;
44
+ selectionReason?: string;
40
45
  }
41
46
 
42
47
  function recordCodexTokenUsage(
@@ -357,7 +362,7 @@ function codexResponseJson(
357
362
  };
358
363
  }
359
364
 
360
- function upstreamHeaders(response: Response, context: { account?: { healthScore: number }; requestStartMs: number; label: string; retries: number }, model: string): Record<string, string> {
365
+ function upstreamHeaders(response: Response, context: RotationAttemptContext, model: string): Record<string, string> {
361
366
  const headers: Record<string, string> = {};
362
367
  response.headers.forEach((value, key) => {
363
368
  if (key !== "connection" && key !== "transfer-encoding" && key !== "content-length") headers[key] = value;
@@ -365,6 +370,11 @@ function upstreamHeaders(response: Response, context: { account?: { healthScore:
365
370
  Object.assign(headers, buildRotatorResponseHeaders({
366
371
  accountLabel: context.label,
367
372
  model,
373
+ requestedModel: context.requestedModel,
374
+ selectedProvider: context.providerId,
375
+ modelSelection: context.selectionMode,
376
+ selectionConfidence: context.selectionConfidence,
377
+ selectionReason: context.selectionReason,
368
378
  ttfbMs: Date.now() - context.requestStartMs,
369
379
  healthScore: context.account?.healthScore,
370
380
  retries: context.retries,
@@ -377,7 +387,7 @@ async function pipeNativeResponses(
377
387
  response: Response,
378
388
  req: IncomingMessage,
379
389
  res: ServerResponse,
380
- context: { account?: { healthScore: number }; requestStartMs: number; label: string; retries: number },
390
+ context: RotationAttemptContext,
381
391
  model: string,
382
392
  ): Promise<CompatCompletion> {
383
393
  res.writeHead(response.status, upstreamHeaders(response, context, model));
@@ -435,7 +445,7 @@ async function pipeCodexAsChat(
435
445
  req: IncomingMessage,
436
446
  res: ServerResponse,
437
447
  model: string,
438
- context: { account?: { healthScore: number }; requestStartMs: number; label: string; retries: number },
448
+ context: RotationAttemptContext,
439
449
  ): Promise<CompatCompletion> {
440
450
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive", ...upstreamHeaders(response, context, model) });
441
451
  const id = `chatcmpl-${Date.now().toString(36)}`;
@@ -520,7 +530,16 @@ export async function serveCodexResponses(
520
530
  request: OpenAIResponsesRequest,
521
531
  options?: CodexCompatOptions,
522
532
  ): Promise<void> {
523
- const body: RequestBody = { project: "", model: request.model, request: buildCodexPayload({ project: "", model: request.model, request }) };
533
+ const body: RequestBody = {
534
+ project: "",
535
+ model: request.model,
536
+ request: buildCodexPayload({ project: "", model: request.model, request }),
537
+ ...(options?.providerId ? { providerId: options.providerId } : {}),
538
+ ...(options?.requestedModel ? { displayModel: options.requestedModel } : {}),
539
+ ...(options?.selectionMode ? { selectionMode: options.selectionMode } : {}),
540
+ ...(options?.selectionConfidence !== undefined ? { selectionConfidence: options.selectionConfidence } : {}),
541
+ ...(options?.selectionReason ? { selectionReason: options.selectionReason } : {}),
542
+ };
524
543
  const controller = new AbortController();
525
544
  const abort = (): void => controller.abort();
526
545
  req.once("aborted", abort);
@@ -567,7 +586,16 @@ export async function serveCodexChat(
567
586
  options?: CodexCompatOptions,
568
587
  ): Promise<void> {
569
588
  const codexRequest = chatToCodexResponsesRequest(request);
570
- const body: RequestBody = { project: "", model: request.model, request: codexRequest };
589
+ const body: RequestBody = {
590
+ project: "",
591
+ model: request.model,
592
+ request: codexRequest,
593
+ ...(options?.providerId ? { providerId: options.providerId } : {}),
594
+ ...(options?.requestedModel ? { displayModel: options.requestedModel } : {}),
595
+ ...(options?.selectionMode ? { selectionMode: options.selectionMode } : {}),
596
+ ...(options?.selectionConfidence !== undefined ? { selectionConfidence: options.selectionConfidence } : {}),
597
+ ...(options?.selectionReason ? { selectionReason: options.selectionReason } : {}),
598
+ };
571
599
  const controller = new AbortController();
572
600
  const abort = (): void => controller.abort();
573
601
  req.once("aborted", abort);
@@ -63,8 +63,19 @@ export function isKnownProvider(providerId: string): boolean {
63
63
 
64
64
  export function findProviderForModel(
65
65
  model: string,
66
- context?: { ollamaModels?: Set<string>; codexModels?: Set<string> },
66
+ context?: {
67
+ ollamaModels?: Set<string>;
68
+ codexModels?: Set<string>;
69
+ providerId?: string;
70
+ },
67
71
  ): ProviderAdapter | null {
72
+ if (context?.providerId) {
73
+ try {
74
+ return getProviderAdapter(context.providerId);
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
68
79
  // Check non-default explicit providers first to prevent Google fallback overlap
69
80
  for (const adapter of [opencodeZenAdapter, openaiCodexAdapter, ollamaAdapter, googleAntigravityAdapter]) {
70
81
  if (adapter.ownsModel?.(model, context)) {
package/src/proxy.ts CHANGED
@@ -78,6 +78,7 @@ import {
78
78
  import { requireAdmin } from "./admin-auth.js";
79
79
  import { PayloadTooLargeError, readLimitedBody } from "./body-limit.js";
80
80
  import { validateConfig, validateProxyRequestBody } from "./validators.js";
81
+ import { calculateBackoffMs } from "./fetch-with-retry.js";
81
82
  import { logger } from "./logger.js";
82
83
  import {
83
84
  trackFeature,
@@ -103,8 +104,12 @@ export function providerAdapterForModel(
103
104
  account: AccountRuntime,
104
105
  model: string | undefined,
105
106
  rotator?: { getOllamaModels?: () => string[]; getCodexModels?: () => string[] },
107
+ providerHint?: string,
106
108
  ): ProviderAdapter {
107
109
  const creds = account.config.credentials ?? [];
110
+ if (providerHint && isKnownProvider(providerHint)) {
111
+ return getProviderAdapter(providerHint);
112
+ }
108
113
  if (model) {
109
114
  const context = {
110
115
  ollamaModels: new Set(rotator?.getOllamaModels?.() ?? []),
@@ -134,11 +139,11 @@ export function providerAdapterForModel(
134
139
  : fallback;
135
140
  }
136
141
 
137
- function routingModelKey(rotator: AccountRotator, model: string): string {
142
+ function routingModelKey(rotator: AccountRotator, model: string, providerId?: string): string {
138
143
  const resolver = (rotator as unknown as {
139
- resolveQuotaModelKeyForDisplay?: (value: string) => string | null;
144
+ resolveQuotaModelKeyForDisplay?: (value: string, provider?: string) => string | null;
140
145
  }).resolveQuotaModelKeyForDisplay;
141
- return resolver?.call(rotator, model) ?? resolveQuotaModelKey(model) ?? model;
146
+ return resolver?.call(rotator, model, providerId) ?? resolveQuotaModelKey(model) ?? model;
142
147
  }
143
148
 
144
149
  function observedModelKey(
@@ -235,6 +240,10 @@ export interface RequestBody {
235
240
  userAgent?: string;
236
241
  requestId?: string;
237
242
  displayModel?: string;
243
+ providerId?: string;
244
+ selectionMode?: "typesafe" | "deterministic" | "disabled";
245
+ selectionConfidence?: number;
246
+ selectionReason?: string;
238
247
  [key: string]: unknown;
239
248
  }
240
249
 
@@ -275,6 +284,12 @@ export interface RotationAttemptContext {
275
284
  requestStartMs: number;
276
285
  endpoint: string;
277
286
  retries: number;
287
+ providerId?: string;
288
+ requestedModel?: string;
289
+ selectedModel?: string;
290
+ selectionMode?: "typesafe" | "deterministic" | "disabled";
291
+ selectionConfidence?: number;
292
+ selectionReason?: string;
278
293
  }
279
294
 
280
295
  export type RotationOutcome<T> =
@@ -1197,7 +1212,7 @@ export async function withRotation<T>(
1197
1212
  context?: RotationAttemptContext,
1198
1213
  ): RotationOutcome<T> => {
1199
1214
  log(`[${model}] No healthy account available: ${reason}`, rotator, "warn");
1200
- const retryAfterMs = rotator.getRetryAfterMs(model);
1215
+ const retryAfterMs = rotator.getRetryAfterMs(model, body.providerId);
1201
1216
  const contextFields = context
1202
1217
  ? { context, totalMs: Date.now() - context.requestStartMs }
1203
1218
  : {};
@@ -1223,7 +1238,7 @@ export async function withRotation<T>(
1223
1238
 
1224
1239
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1225
1240
  const admissionStartedMs = Date.now();
1226
- const account = await rotator.getActiveAccount(model, signal);
1241
+ const account = await rotator.getActiveAccount(model, signal, body.providerId);
1227
1242
  if (!account) {
1228
1243
  if (signal?.aborted) {
1229
1244
  return { ok: false, status: 499, errorText: "Client closed request" };
@@ -1232,7 +1247,7 @@ export async function withRotation<T>(
1232
1247
  }
1233
1248
 
1234
1249
  const label = account.config.label || account.config.email;
1235
- const modelKey = routingModelKey(rotator, model);
1250
+ const modelKey = routingModelKey(rotator, model, body.providerId);
1236
1251
  const displayModelKey = observedModelKey(
1237
1252
  rotator,
1238
1253
  body.displayModel || model,
@@ -1249,7 +1264,7 @@ export async function withRotation<T>(
1249
1264
  };
1250
1265
  const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
1251
1266
  releaseCurrentAccount();
1252
- const nextAccount = await rotator.rotateToNext(model, account);
1267
+ const nextAccount = await rotator.rotateToNext(model, account, body.providerId);
1253
1268
  return nextAccount;
1254
1269
  };
1255
1270
  const logRequestEnd = (status: string | number, extra = ""): void => {
@@ -1297,6 +1312,7 @@ export async function withRotation<T>(
1297
1312
  account,
1298
1313
  model,
1299
1314
  rotator,
1315
+ body.providerId,
1300
1316
  );
1301
1317
  // A parent account may carry Google + Codex credentials; refresh the
1302
1318
  // selected provider, never merely the account's primary provider.
@@ -1317,6 +1333,12 @@ export async function withRotation<T>(
1317
1333
  requestStartMs,
1318
1334
  endpoint,
1319
1335
  retries: attempt,
1336
+ providerId: provider.id,
1337
+ requestedModel: body.displayModel || model,
1338
+ selectedModel: model,
1339
+ selectionMode: body.selectionMode,
1340
+ selectionConfidence: body.selectionConfidence,
1341
+ selectionReason: body.selectionReason,
1320
1342
  };
1321
1343
 
1322
1344
  const action = await classifyUpstreamResponse(
@@ -1349,7 +1371,7 @@ export async function withRotation<T>(
1349
1371
 
1350
1372
  // success
1351
1373
  const result = await onSuccess(response, context);
1352
- const shouldRotate = rotator.recordRequest(account, model);
1374
+ const shouldRotate = rotator.recordRequest(account, model, body.providerId);
1353
1375
  const inTokens =
1354
1376
  result && typeof result === "object" && "inputTokens" in result
1355
1377
  ? (result as Record<string, unknown>).inputTokens
@@ -1367,7 +1389,7 @@ export async function withRotation<T>(
1367
1389
  inTokens || outTokens ? ` inTokens=${inTokens} outTokens=${outTokens}` : "";
1368
1390
  logRequestEnd(response.status, `endpoint=${endpoint}${ttfbInfo}${tokensInfo}`);
1369
1391
  if (shouldRotate) {
1370
- await rotator.rotateToNext(model, account);
1392
+ await rotator.rotateToNext(model, account, body.providerId);
1371
1393
  }
1372
1394
  return { ok: true, result, endpoint, context };
1373
1395
  } catch (err) {
@@ -1423,9 +1445,18 @@ export async function withRotation<T>(
1423
1445
  }
1424
1446
  const nextAccount = await rotateAndRelease();
1425
1447
  if (!nextAccount) {
1426
- return sendNoAccountsAvailable(
1427
- `no replacement account remained after ${label} request error`,
1448
+ const waited = await sleepTransportRetry(
1449
+ requestId,
1450
+ label,
1451
+ attempt,
1452
+ maxRetries,
1453
+ rotator,
1454
+ signal,
1428
1455
  );
1456
+ if (!waited) {
1457
+ return { ok: false, status: 499, errorText: "Client closed request" };
1458
+ }
1459
+ continue;
1429
1460
  }
1430
1461
  continue;
1431
1462
  } finally {
@@ -1445,6 +1476,29 @@ function log(
1445
1476
  rotator?.recordProxyEvent(msg, level);
1446
1477
  }
1447
1478
 
1479
+ async function sleepTransportRetry(
1480
+ requestId: string,
1481
+ label: string,
1482
+ attempt: number,
1483
+ maxRetries: number,
1484
+ rotator?: AccountRotator,
1485
+ signal?: AbortSignal,
1486
+ ): Promise<boolean> {
1487
+ if (signal?.aborted) return false;
1488
+ const backoffMs = calculateBackoffMs(attempt, 500, 5_000);
1489
+ log(
1490
+ `[${requestId}] Retrying after transport error on current account ${label} in ${backoffMs}ms (attempt ${attempt + 1}/${maxRetries})`,
1491
+ rotator,
1492
+ "warn",
1493
+ );
1494
+ try {
1495
+ await sleep(backoffMs, signal);
1496
+ return true;
1497
+ } catch {
1498
+ return false;
1499
+ }
1500
+ }
1501
+
1448
1502
  function isGeminiGenerateContentPath(pathname: string): boolean {
1449
1503
  const prefix = "/v1beta/models/";
1450
1504
  if (!pathname.startsWith(prefix)) return false;
@@ -1768,6 +1822,12 @@ async function handleProxyRequest(
1768
1822
  requestStartMs,
1769
1823
  endpoint,
1770
1824
  retries: attempt,
1825
+ providerId: provider.id,
1826
+ requestedModel: body.displayModel || body.model,
1827
+ selectedModel: body.model,
1828
+ selectionMode: body.selectionMode,
1829
+ selectionConfidence: body.selectionConfidence,
1830
+ selectionReason: body.selectionReason,
1771
1831
  };
1772
1832
 
1773
1833
  const action = await classifyUpstreamResponse(
@@ -1820,6 +1880,11 @@ async function handleProxyRequest(
1820
1880
  healthScore: account.healthScore,
1821
1881
  routingPolicy: rotator?.getConfig?.()?.routingPolicy || "timer-first",
1822
1882
  retries: attempt,
1883
+ requestedModel: body.displayModel || body.model,
1884
+ selectedProvider: provider.id,
1885
+ modelSelection: body.selectionMode,
1886
+ selectionConfidence: body.selectionConfidence,
1887
+ selectionReason: body.selectionReason,
1823
1888
  });
1824
1889
  Object.assign(responseHeaders, rotatorHeaders);
1825
1890
 
@@ -1911,10 +1976,16 @@ async function handleProxyRequest(
1911
1976
  }
1912
1977
  const nextAccount = await rotateAndRelease();
1913
1978
  if (!nextAccount) {
1914
- sendNoAccountsAvailable(
1915
- `no replacement account remained after ${label} request error`,
1979
+ const waited = await sleepTransportRetry(
1980
+ requestId,
1981
+ label,
1982
+ attempt,
1983
+ maxRetries,
1984
+ rotator,
1985
+ clientController.signal,
1916
1986
  );
1917
- return;
1987
+ if (!waited) return;
1988
+ continue;
1918
1989
  }
1919
1990
  continue;
1920
1991
  } finally {
@@ -2038,12 +2109,20 @@ async function handleCodeAssistPassthrough(
2038
2109
  }
2039
2110
  releaseCurrentAccount();
2040
2111
  const nextAccount = await rotator.rotateToNext(CODE_ASSIST_ROUTING_MODEL, account);
2041
- if (nextAccount) {
2112
+ if (!nextAccount) {
2113
+ const label = account.config.label || account.config.email;
2114
+ const waited = await sleepTransportRetry(
2115
+ action,
2116
+ label,
2117
+ attempt,
2118
+ maxRetries,
2119
+ rotator,
2120
+ clientController.signal,
2121
+ );
2122
+ if (!waited) return;
2042
2123
  continue;
2043
2124
  }
2044
- res.writeHead(503, { "Content-Type": "application/json" });
2045
- res.end(JSON.stringify({ error: "No replacement Google account available" }));
2046
- return;
2125
+ continue;
2047
2126
  } finally {
2048
2127
  releaseCurrentAccount();
2049
2128
  }
@@ -2169,7 +2248,7 @@ export function startProxy(
2169
2248
  if (method === "GET" && pathname === "/login-cli") {
2170
2249
  if (!requireAdmin(req, res)) return;
2171
2250
  trackFeature("cliLogin");
2172
- serveCliLogin(res);
2251
+ serveCliLogin(res, rotator);
2173
2252
  return;
2174
2253
  }
2175
2254