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.
- package/CHANGELOG.md +21 -0
- package/README.md +4 -0
- package/package.json +2 -1
- package/src/auto-routing.ts +370 -0
- package/src/compat.ts +419 -51
- package/src/config-defaults.ts +13 -0
- package/src/dashboard.ts +2 -2
- package/src/db-store.ts +9 -3
- package/src/fetch-with-retry.ts +71 -0
- package/src/key-auth.ts +15 -15
- package/src/onboarding.ts +174 -2
- package/src/providers/adapter.ts +1 -0
- package/src/providers/google-antigravity/forward.ts +38 -5
- package/src/providers/google-antigravity/translators.ts +2 -1
- package/src/providers/ollama/forward.ts +5 -2
- package/src/providers/openai-codex/compat.ts +95 -12
- package/src/providers/openai-codex/forward.ts +5 -2
- package/src/providers/opencode-zen/forward.ts +36 -4
- package/src/providers/registry.ts +12 -1
- package/src/proxy.ts +138 -24
- package/src/rate-limit-parser.ts +29 -0
- package/src/response-headers.ts +21 -0
- package/src/rotator.ts +233 -62
- package/src/stream-guards.ts +85 -0
- package/src/token-encryption.ts +91 -0
- package/src/types.ts +23 -0
- package/src/validators.ts +38 -0
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(
|
|
@@ -183,6 +188,7 @@ import {
|
|
|
183
188
|
import { authenticateVirtualKey, sendAuthErrorResponse } from "./key-auth.js";
|
|
184
189
|
import { logSpend } from "./spend-logger.js";
|
|
185
190
|
import { hashKey } from "./virtual-keys.js";
|
|
191
|
+
import { STREAM_BACKPRESSURE_TIMEOUT_MS } from "./stream-guards.js";
|
|
186
192
|
|
|
187
193
|
const proxyLogger = logger.child("proxy");
|
|
188
194
|
const GENERIC_UPSTREAM_ERROR = "Upstream request failed";
|
|
@@ -234,6 +240,10 @@ export interface RequestBody {
|
|
|
234
240
|
userAgent?: string;
|
|
235
241
|
requestId?: string;
|
|
236
242
|
displayModel?: string;
|
|
243
|
+
providerId?: string;
|
|
244
|
+
selectionMode?: "typesafe" | "deterministic" | "disabled";
|
|
245
|
+
selectionConfidence?: number;
|
|
246
|
+
selectionReason?: string;
|
|
237
247
|
[key: string]: unknown;
|
|
238
248
|
}
|
|
239
249
|
|
|
@@ -274,6 +284,12 @@ export interface RotationAttemptContext {
|
|
|
274
284
|
requestStartMs: number;
|
|
275
285
|
endpoint: string;
|
|
276
286
|
retries: number;
|
|
287
|
+
providerId?: string;
|
|
288
|
+
requestedModel?: string;
|
|
289
|
+
selectedModel?: string;
|
|
290
|
+
selectionMode?: "typesafe" | "deterministic" | "disabled";
|
|
291
|
+
selectionConfidence?: number;
|
|
292
|
+
selectionReason?: string;
|
|
277
293
|
}
|
|
278
294
|
|
|
279
295
|
export type RotationOutcome<T> =
|
|
@@ -334,7 +350,7 @@ export async function classifyUpstreamResponse(
|
|
|
334
350
|
const rateLimitReason = classifyRateLimitReason(errorText, response.status);
|
|
335
351
|
const providerResourceExhausted = rateLimitReason === "quota-exhausted";
|
|
336
352
|
const cooldownMs = providerResourceExhausted
|
|
337
|
-
? providerId === DEFAULT_PROVIDER
|
|
353
|
+
? providerId === DEFAULT_PROVIDER || providerId === "openai-codex"
|
|
338
354
|
? parseRetryAfterMs(
|
|
339
355
|
errorText,
|
|
340
356
|
response.headers,
|
|
@@ -761,7 +777,7 @@ function isFetchTransportError(err: unknown): boolean {
|
|
|
761
777
|
return true;
|
|
762
778
|
}
|
|
763
779
|
if (err && typeof err === "object" && "code" in err) {
|
|
764
|
-
return ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(
|
|
780
|
+
return ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_SOCKET"].includes(
|
|
765
781
|
String(err.code),
|
|
766
782
|
);
|
|
767
783
|
}
|
|
@@ -815,9 +831,12 @@ async function streamResponseBody(
|
|
|
815
831
|
} | null>((resolve, reject) => {
|
|
816
832
|
let settled = false;
|
|
817
833
|
let idleTimer: ReturnType<typeof setTimeout> | null = null;
|
|
834
|
+
let backpressureTimer: ReturnType<typeof setTimeout> | null = null;
|
|
835
|
+
let waitingForDrain = false;
|
|
818
836
|
|
|
819
837
|
const cleanup = (): void => {
|
|
820
838
|
if (idleTimer) clearTimeout(idleTimer);
|
|
839
|
+
if (backpressureTimer) clearTimeout(backpressureTimer);
|
|
821
840
|
nodeStream.off("data", onData);
|
|
822
841
|
nodeStream.off("end", onEnd);
|
|
823
842
|
nodeStream.off("error", onError);
|
|
@@ -825,6 +844,8 @@ async function streamResponseBody(
|
|
|
825
844
|
req.off("close", onClientClose);
|
|
826
845
|
res.off("close", onResponseClose);
|
|
827
846
|
res.off("error", onResponseError);
|
|
847
|
+
res.off("drain", onDrain);
|
|
848
|
+
waitingForDrain = false;
|
|
828
849
|
};
|
|
829
850
|
|
|
830
851
|
const finish = (reason?: string): void => {
|
|
@@ -861,6 +882,31 @@ async function streamResponseBody(
|
|
|
861
882
|
);
|
|
862
883
|
};
|
|
863
884
|
|
|
885
|
+
const onDrain = (): void => {
|
|
886
|
+
if (!waitingForDrain) return;
|
|
887
|
+
waitingForDrain = false;
|
|
888
|
+
if (backpressureTimer) clearTimeout(backpressureTimer);
|
|
889
|
+
backpressureTimer = null;
|
|
890
|
+
if (!settled && !nodeStream.destroyed) nodeStream.resume();
|
|
891
|
+
};
|
|
892
|
+
|
|
893
|
+
const pauseForBackpressure = (): void => {
|
|
894
|
+
if (waitingForDrain || settled) return;
|
|
895
|
+
waitingForDrain = true;
|
|
896
|
+
nodeStream.pause();
|
|
897
|
+
backpressureTimer = setTimeout(() => {
|
|
898
|
+
backpressureTimer = null;
|
|
899
|
+
if (!waitingForDrain || settled) return;
|
|
900
|
+
const error = new Error(
|
|
901
|
+
`client backpressure timeout after ${Math.round(STREAM_BACKPRESSURE_TIMEOUT_MS / 1000)}s`,
|
|
902
|
+
);
|
|
903
|
+
emitStreamError(error);
|
|
904
|
+
finish(error.message);
|
|
905
|
+
if (!nodeStream.destroyed) nodeStream.destroy();
|
|
906
|
+
}, STREAM_BACKPRESSURE_TIMEOUT_MS);
|
|
907
|
+
res.once("drain", onDrain);
|
|
908
|
+
};
|
|
909
|
+
|
|
864
910
|
const resetIdleTimer = (): void => {
|
|
865
911
|
if (idleTimer) clearTimeout(idleTimer);
|
|
866
912
|
idleTimer = setTimeout(() => {
|
|
@@ -882,7 +928,7 @@ async function streamResponseBody(
|
|
|
882
928
|
if (!res.destroyed && !res.writableEnded) {
|
|
883
929
|
if (!res.headersSent) res.writeHead(responseStatus, responseHeaders);
|
|
884
930
|
hasForwardedBytes = true;
|
|
885
|
-
res.write(chunk);
|
|
931
|
+
if (!res.write(chunk)) pauseForBackpressure();
|
|
886
932
|
}
|
|
887
933
|
// Extract usage from any newly-completed SSE events
|
|
888
934
|
if (!firstUsage) {
|
|
@@ -1166,7 +1212,7 @@ export async function withRotation<T>(
|
|
|
1166
1212
|
context?: RotationAttemptContext,
|
|
1167
1213
|
): RotationOutcome<T> => {
|
|
1168
1214
|
log(`[${model}] No healthy account available: ${reason}`, rotator, "warn");
|
|
1169
|
-
const retryAfterMs = rotator.getRetryAfterMs(model);
|
|
1215
|
+
const retryAfterMs = rotator.getRetryAfterMs(model, body.providerId);
|
|
1170
1216
|
const contextFields = context
|
|
1171
1217
|
? { context, totalMs: Date.now() - context.requestStartMs }
|
|
1172
1218
|
: {};
|
|
@@ -1191,7 +1237,8 @@ export async function withRotation<T>(
|
|
|
1191
1237
|
const maxAttempts = maxRetries + 1;
|
|
1192
1238
|
|
|
1193
1239
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1194
|
-
const
|
|
1240
|
+
const admissionStartedMs = Date.now();
|
|
1241
|
+
const account = await rotator.getActiveAccount(model, signal, body.providerId);
|
|
1195
1242
|
if (!account) {
|
|
1196
1243
|
if (signal?.aborted) {
|
|
1197
1244
|
return { ok: false, status: 499, errorText: "Client closed request" };
|
|
@@ -1200,12 +1247,13 @@ export async function withRotation<T>(
|
|
|
1200
1247
|
}
|
|
1201
1248
|
|
|
1202
1249
|
const label = account.config.label || account.config.email;
|
|
1203
|
-
const modelKey = routingModelKey(rotator, model);
|
|
1250
|
+
const modelKey = routingModelKey(rotator, model, body.providerId);
|
|
1204
1251
|
const displayModelKey = observedModelKey(
|
|
1205
1252
|
rotator,
|
|
1206
1253
|
body.displayModel || model,
|
|
1207
1254
|
body.model,
|
|
1208
1255
|
);
|
|
1256
|
+
const queueWaitMs = Date.now() - admissionStartedMs;
|
|
1209
1257
|
const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
|
|
1210
1258
|
const requestStartMs = Date.now();
|
|
1211
1259
|
let accountReleased = false;
|
|
@@ -1216,7 +1264,7 @@ export async function withRotation<T>(
|
|
|
1216
1264
|
};
|
|
1217
1265
|
const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
|
|
1218
1266
|
releaseCurrentAccount();
|
|
1219
|
-
const nextAccount = await rotator.rotateToNext(model, account);
|
|
1267
|
+
const nextAccount = await rotator.rotateToNext(model, account, body.providerId);
|
|
1220
1268
|
return nextAccount;
|
|
1221
1269
|
};
|
|
1222
1270
|
const logRequestEnd = (status: string | number, extra = ""): void => {
|
|
@@ -1228,7 +1276,7 @@ export async function withRotation<T>(
|
|
|
1228
1276
|
};
|
|
1229
1277
|
|
|
1230
1278
|
log(
|
|
1231
|
-
`[${requestId}] START account=${label} model=${model} attempt=${attempt + 1}`,
|
|
1279
|
+
`[${requestId}] START account=${label} model=${model} attempt=${attempt + 1} queueMs=${queueWaitMs}`,
|
|
1232
1280
|
rotator,
|
|
1233
1281
|
);
|
|
1234
1282
|
|
|
@@ -1264,6 +1312,7 @@ export async function withRotation<T>(
|
|
|
1264
1312
|
account,
|
|
1265
1313
|
model,
|
|
1266
1314
|
rotator,
|
|
1315
|
+
body.providerId,
|
|
1267
1316
|
);
|
|
1268
1317
|
// A parent account may carry Google + Codex credentials; refresh the
|
|
1269
1318
|
// selected provider, never merely the account's primary provider.
|
|
@@ -1284,6 +1333,12 @@ export async function withRotation<T>(
|
|
|
1284
1333
|
requestStartMs,
|
|
1285
1334
|
endpoint,
|
|
1286
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,
|
|
1287
1342
|
};
|
|
1288
1343
|
|
|
1289
1344
|
const action = await classifyUpstreamResponse(
|
|
@@ -1316,7 +1371,7 @@ export async function withRotation<T>(
|
|
|
1316
1371
|
|
|
1317
1372
|
// success
|
|
1318
1373
|
const result = await onSuccess(response, context);
|
|
1319
|
-
const shouldRotate = rotator.recordRequest(account, model);
|
|
1374
|
+
const shouldRotate = rotator.recordRequest(account, model, body.providerId);
|
|
1320
1375
|
const inTokens =
|
|
1321
1376
|
result && typeof result === "object" && "inputTokens" in result
|
|
1322
1377
|
? (result as Record<string, unknown>).inputTokens
|
|
@@ -1334,7 +1389,7 @@ export async function withRotation<T>(
|
|
|
1334
1389
|
inTokens || outTokens ? ` inTokens=${inTokens} outTokens=${outTokens}` : "";
|
|
1335
1390
|
logRequestEnd(response.status, `endpoint=${endpoint}${ttfbInfo}${tokensInfo}`);
|
|
1336
1391
|
if (shouldRotate) {
|
|
1337
|
-
await rotator.rotateToNext(model, account);
|
|
1392
|
+
await rotator.rotateToNext(model, account, body.providerId);
|
|
1338
1393
|
}
|
|
1339
1394
|
return { ok: true, result, endpoint, context };
|
|
1340
1395
|
} catch (err) {
|
|
@@ -1390,9 +1445,18 @@ export async function withRotation<T>(
|
|
|
1390
1445
|
}
|
|
1391
1446
|
const nextAccount = await rotateAndRelease();
|
|
1392
1447
|
if (!nextAccount) {
|
|
1393
|
-
|
|
1394
|
-
|
|
1448
|
+
const waited = await sleepTransportRetry(
|
|
1449
|
+
requestId,
|
|
1450
|
+
label,
|
|
1451
|
+
attempt,
|
|
1452
|
+
maxRetries,
|
|
1453
|
+
rotator,
|
|
1454
|
+
signal,
|
|
1395
1455
|
);
|
|
1456
|
+
if (!waited) {
|
|
1457
|
+
return { ok: false, status: 499, errorText: "Client closed request" };
|
|
1458
|
+
}
|
|
1459
|
+
continue;
|
|
1396
1460
|
}
|
|
1397
1461
|
continue;
|
|
1398
1462
|
} finally {
|
|
@@ -1412,6 +1476,29 @@ function log(
|
|
|
1412
1476
|
rotator?.recordProxyEvent(msg, level);
|
|
1413
1477
|
}
|
|
1414
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
|
+
|
|
1415
1502
|
function isGeminiGenerateContentPath(pathname: string): boolean {
|
|
1416
1503
|
const prefix = "/v1beta/models/";
|
|
1417
1504
|
if (!pathname.startsWith(prefix)) return false;
|
|
@@ -1634,6 +1721,7 @@ async function handleProxyRequest(
|
|
|
1634
1721
|
const maxRetries = getStreamRecoveryMaxRetries(rotator);
|
|
1635
1722
|
const maxAttempts = maxRetries + 1;
|
|
1636
1723
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1724
|
+
const admissionStartedMs = Date.now();
|
|
1637
1725
|
const account = await rotator.getActiveAccount(
|
|
1638
1726
|
body.model,
|
|
1639
1727
|
clientController.signal,
|
|
@@ -1647,6 +1735,7 @@ async function handleProxyRequest(
|
|
|
1647
1735
|
const label = account.config.label || account.config.email;
|
|
1648
1736
|
const modelKey = rotator.resolveQuotaModelKeyForDisplay(body.model) ?? body.model; // quota routing
|
|
1649
1737
|
const displayModelKey = observedModelKey(rotator, body.model); // metrics/logs
|
|
1738
|
+
const queueWaitMs = Date.now() - admissionStartedMs;
|
|
1650
1739
|
const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
|
|
1651
1740
|
let accountReleased = false;
|
|
1652
1741
|
const releaseCurrentAccount = (): void => {
|
|
@@ -1663,7 +1752,7 @@ async function handleProxyRequest(
|
|
|
1663
1752
|
return nextAccount;
|
|
1664
1753
|
};
|
|
1665
1754
|
proxyLog(
|
|
1666
|
-
`[${requestId}] START account=${label} model=${body.model} attempt=${attempt + 1}`,
|
|
1755
|
+
`[${requestId}] START account=${label} model=${body.model} attempt=${attempt + 1} queueMs=${queueWaitMs}`,
|
|
1667
1756
|
);
|
|
1668
1757
|
const requestStartMs = Date.now();
|
|
1669
1758
|
const logRequestEnd = (status: string | number, extra = ""): void => {
|
|
@@ -1733,6 +1822,12 @@ async function handleProxyRequest(
|
|
|
1733
1822
|
requestStartMs,
|
|
1734
1823
|
endpoint,
|
|
1735
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,
|
|
1736
1831
|
};
|
|
1737
1832
|
|
|
1738
1833
|
const action = await classifyUpstreamResponse(
|
|
@@ -1785,6 +1880,11 @@ async function handleProxyRequest(
|
|
|
1785
1880
|
healthScore: account.healthScore,
|
|
1786
1881
|
routingPolicy: rotator?.getConfig?.()?.routingPolicy || "timer-first",
|
|
1787
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,
|
|
1788
1888
|
});
|
|
1789
1889
|
Object.assign(responseHeaders, rotatorHeaders);
|
|
1790
1890
|
|
|
@@ -1876,10 +1976,16 @@ async function handleProxyRequest(
|
|
|
1876
1976
|
}
|
|
1877
1977
|
const nextAccount = await rotateAndRelease();
|
|
1878
1978
|
if (!nextAccount) {
|
|
1879
|
-
|
|
1880
|
-
|
|
1979
|
+
const waited = await sleepTransportRetry(
|
|
1980
|
+
requestId,
|
|
1981
|
+
label,
|
|
1982
|
+
attempt,
|
|
1983
|
+
maxRetries,
|
|
1984
|
+
rotator,
|
|
1985
|
+
clientController.signal,
|
|
1881
1986
|
);
|
|
1882
|
-
return;
|
|
1987
|
+
if (!waited) return;
|
|
1988
|
+
continue;
|
|
1883
1989
|
}
|
|
1884
1990
|
continue;
|
|
1885
1991
|
} finally {
|
|
@@ -2003,12 +2109,20 @@ async function handleCodeAssistPassthrough(
|
|
|
2003
2109
|
}
|
|
2004
2110
|
releaseCurrentAccount();
|
|
2005
2111
|
const nextAccount = await rotator.rotateToNext(CODE_ASSIST_ROUTING_MODEL, account);
|
|
2006
|
-
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;
|
|
2007
2123
|
continue;
|
|
2008
2124
|
}
|
|
2009
|
-
|
|
2010
|
-
res.end(JSON.stringify({ error: "No replacement Google account available" }));
|
|
2011
|
-
return;
|
|
2125
|
+
continue;
|
|
2012
2126
|
} finally {
|
|
2013
2127
|
releaseCurrentAccount();
|
|
2014
2128
|
}
|
|
@@ -2134,7 +2248,7 @@ export function startProxy(
|
|
|
2134
2248
|
if (method === "GET" && pathname === "/login-cli") {
|
|
2135
2249
|
if (!requireAdmin(req, res)) return;
|
|
2136
2250
|
trackFeature("cliLogin");
|
|
2137
|
-
serveCliLogin(res);
|
|
2251
|
+
serveCliLogin(res, rotator);
|
|
2138
2252
|
return;
|
|
2139
2253
|
}
|
|
2140
2254
|
|
package/src/rate-limit-parser.ts
CHANGED
|
@@ -24,6 +24,8 @@ export function classifyRateLimitReason(errorText: string, status?: number): Rat
|
|
|
24
24
|
lower.includes("quotaresettimestamp") ||
|
|
25
25
|
lower.includes("resource_exhausted") ||
|
|
26
26
|
lower.includes("resource exhausted") ||
|
|
27
|
+
lower.includes("usage_limit_reached") ||
|
|
28
|
+
lower.includes("usage limit reached") ||
|
|
27
29
|
lower.includes("daily limit") ||
|
|
28
30
|
lower.includes("quota exceeded")
|
|
29
31
|
) {
|
|
@@ -88,6 +90,33 @@ export function parseRetryAfterMs(
|
|
|
88
90
|
if (Number.isFinite(seconds) && seconds > 0) return Math.ceil(seconds * 1000 + 1000);
|
|
89
91
|
}
|
|
90
92
|
|
|
93
|
+
const codexResetSecondsMatch = errorText.match(
|
|
94
|
+
/["']?resets_in_seconds["']?\s*:\s*["']?(\d+(?:\.\d+)?)/i,
|
|
95
|
+
);
|
|
96
|
+
if (codexResetSecondsMatch?.[1]) {
|
|
97
|
+
const seconds = Number(codexResetSecondsMatch[1]);
|
|
98
|
+
if (Number.isFinite(seconds) && seconds > 0) {
|
|
99
|
+
return Math.ceil(seconds * 1000 + 1000);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const codexResetAtMatch = errorText.match(
|
|
104
|
+
/["']?resets_at["']?\s*:\s*(?:["']([^"']+)["']|(\d{10,13}))/i,
|
|
105
|
+
);
|
|
106
|
+
if (codexResetAtMatch) {
|
|
107
|
+
const rawResetAt = codexResetAtMatch[1] ?? codexResetAtMatch[2];
|
|
108
|
+
const numericResetAt = Number(rawResetAt);
|
|
109
|
+
const resetAt = Number.isFinite(numericResetAt)
|
|
110
|
+
? numericResetAt < 1_000_000_000_000
|
|
111
|
+
? numericResetAt * 1000
|
|
112
|
+
: numericResetAt
|
|
113
|
+
: Date.parse(rawResetAt ?? "");
|
|
114
|
+
if (Number.isFinite(resetAt)) {
|
|
115
|
+
const delta = resetAt - Date.now();
|
|
116
|
+
if (delta > 0) return Math.ceil(delta + 1000);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
91
120
|
const quotaDelayMatch = errorText.match(/quotaResetDelay[:\s"]+(\d+(?:\.\d+)?)(ms|s)/i);
|
|
92
121
|
if (quotaDelayMatch) {
|
|
93
122
|
const value = parseFloat(quotaDelayMatch[1]);
|
package/src/response-headers.ts
CHANGED
|
@@ -28,6 +28,11 @@ export interface CompressionHeaderOptions {
|
|
|
28
28
|
export interface RotatorResponseHeaderOptions {
|
|
29
29
|
accountLabel?: string;
|
|
30
30
|
model?: string;
|
|
31
|
+
requestedModel?: string;
|
|
32
|
+
selectedProvider?: string;
|
|
33
|
+
modelSelection?: "typesafe" | "deterministic" | "disabled";
|
|
34
|
+
selectionConfidence?: number;
|
|
35
|
+
selectionReason?: string;
|
|
31
36
|
latencyMs?: number;
|
|
32
37
|
ttfbMs?: number;
|
|
33
38
|
inputTokens?: number;
|
|
@@ -61,6 +66,22 @@ export function buildRotatorResponseHeaders(
|
|
|
61
66
|
if (opts.model) {
|
|
62
67
|
headers["X-Rotator-Model"] = opts.model;
|
|
63
68
|
}
|
|
69
|
+
if (opts.requestedModel && opts.requestedModel !== opts.model) {
|
|
70
|
+
headers["X-Rotator-Requested-Model"] = opts.requestedModel;
|
|
71
|
+
}
|
|
72
|
+
if (opts.selectedProvider) {
|
|
73
|
+
headers["X-Rotator-Selected-Provider"] = opts.selectedProvider;
|
|
74
|
+
}
|
|
75
|
+
if (opts.modelSelection) {
|
|
76
|
+
headers["X-Rotator-Model-Selection"] = opts.modelSelection;
|
|
77
|
+
}
|
|
78
|
+
if (opts.selectionConfidence !== undefined && Number.isFinite(opts.selectionConfidence)) {
|
|
79
|
+
headers["X-Rotator-Selection-Confidence"] = opts.selectionConfidence.toFixed(3);
|
|
80
|
+
}
|
|
81
|
+
if (opts.selectionReason) {
|
|
82
|
+
const reason = opts.selectionReason.replace(/[^a-zA-Z0-9._-]/g, "").slice(0, 64);
|
|
83
|
+
if (reason) headers["X-Rotator-Selection-Reason"] = reason;
|
|
84
|
+
}
|
|
64
85
|
if (opts.latencyMs !== undefined && opts.latencyMs >= 0) {
|
|
65
86
|
headers["X-Rotator-Latency-Ms"] = String(Math.round(opts.latencyMs));
|
|
66
87
|
}
|