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/rotator.ts
CHANGED
|
@@ -84,6 +84,7 @@ import {
|
|
|
84
84
|
getCachedTokenUsage,
|
|
85
85
|
setCachedTokenUsage,
|
|
86
86
|
} from "./db-store.js";
|
|
87
|
+
import { isRedactedSecret, redactTypeSafeRoutingInConfig } from "./token-encryption.js";
|
|
87
88
|
import {
|
|
88
89
|
classifyRateLimitReason,
|
|
89
90
|
parseRetryAfterMs,
|
|
@@ -178,9 +179,15 @@ function projectModelKey(projectId: string, modelKey: string): string {
|
|
|
178
179
|
}
|
|
179
180
|
|
|
180
181
|
const REQUEST_QUEUE_TIMEOUT_MS = 300_000;
|
|
182
|
+
// Node clamps delays above the signed 32-bit millisecond limit to 1ms. Long
|
|
183
|
+
// provider cooldowns (for example Codex weekly resets) must be rechecked in
|
|
184
|
+
// safe-sized timer slices instead of creating a hot timer loop.
|
|
185
|
+
const MAX_NODE_TIMEOUT_MS = 2_147_483_647;
|
|
181
186
|
|
|
182
187
|
interface AccountRequestWaiter {
|
|
188
|
+
queueKey: string;
|
|
183
189
|
model?: string;
|
|
190
|
+
providerId?: string;
|
|
184
191
|
signal?: AbortSignal;
|
|
185
192
|
timer: ReturnType<typeof setTimeout>;
|
|
186
193
|
onAbort?: () => void;
|
|
@@ -255,6 +262,50 @@ export class AccountRotator {
|
|
|
255
262
|
);
|
|
256
263
|
}
|
|
257
264
|
|
|
265
|
+
/**
|
|
266
|
+
* Exposes only aggregate routing health to the optional Jev selector.
|
|
267
|
+
* Account identities and credentials stay inside the rotator.
|
|
268
|
+
*/
|
|
269
|
+
getAutoRoutingCandidateStatus(
|
|
270
|
+
model: string,
|
|
271
|
+
providerId: string,
|
|
272
|
+
): {
|
|
273
|
+
available: boolean;
|
|
274
|
+
operationalScore: number;
|
|
275
|
+
poolKey: string;
|
|
276
|
+
reason?: string;
|
|
277
|
+
} {
|
|
278
|
+
const poolKey = this.resolvePoolKeyForModel(model, providerId);
|
|
279
|
+
if (!poolKey) {
|
|
280
|
+
return { available: false, operationalScore: 0, poolKey: model, reason: "unknown-provider" };
|
|
281
|
+
}
|
|
282
|
+
const now = Date.now();
|
|
283
|
+
const policy = this.config.routingPolicy || "timer-first";
|
|
284
|
+
let bestScore = 0;
|
|
285
|
+
let available = false;
|
|
286
|
+
let firstReason: string | undefined;
|
|
287
|
+
for (const account of this.accounts) {
|
|
288
|
+
const rejection = this.getRoutingRejectionForModel(account, poolKey, now, policy);
|
|
289
|
+
if (rejection) {
|
|
290
|
+
firstReason ??= rejection.detail;
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
available = true;
|
|
294
|
+
const quota = this.getModelQuota(account, poolKey);
|
|
295
|
+
const quotaScore = quota < 0 ? 0.5 : Math.max(0, Math.min(1, quota / 100));
|
|
296
|
+
const capacity = Math.max(1, this.config.maxConcurrentRequestsPerAccount ?? 5);
|
|
297
|
+
const loadScore = Math.max(0, Math.min(1, 1 - account.inFlightRequests / capacity));
|
|
298
|
+
const healthScore = this.getHealthScoreBreakdown(account).score;
|
|
299
|
+
bestScore = Math.max(bestScore, 0.55 * healthScore + 0.3 * quotaScore + 0.15 * loadScore);
|
|
300
|
+
}
|
|
301
|
+
return {
|
|
302
|
+
available,
|
|
303
|
+
operationalScore: bestScore,
|
|
304
|
+
poolKey,
|
|
305
|
+
...(available ? {} : { reason: firstReason ?? "no-routable-account" }),
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
258
309
|
setCodexModels(models: string[]): void {
|
|
259
310
|
this.codexModels = new Set(
|
|
260
311
|
models
|
|
@@ -334,6 +385,8 @@ export class AccountRotator {
|
|
|
334
385
|
account: string;
|
|
335
386
|
}> = [];
|
|
336
387
|
private routingDiagnostics: Record<string, RoutingModelDiagnostics> = {};
|
|
388
|
+
private routingWarningLastLoggedAt = new Map<string, number>();
|
|
389
|
+
private static readonly ROUTING_WARNING_DEDUP_MS = 60_000;
|
|
337
390
|
private autoWarmupEnabled = false;
|
|
338
391
|
// Debounced state writer: batches multiple saveState() calls within a 1s window
|
|
339
392
|
// to a single disk write. Hot paths (markError, recordRequest, etc.) call
|
|
@@ -1492,11 +1545,12 @@ export class AccountRotator {
|
|
|
1492
1545
|
return { reason: "disabled", detail: "account disabled" };
|
|
1493
1546
|
if (account.flagged)
|
|
1494
1547
|
return { reason: "flagged", detail: "account quarantined or flagged" };
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1548
|
+
const providerRejection = this.getProviderEligibilityRejection(
|
|
1549
|
+
account,
|
|
1550
|
+
modelKey,
|
|
1551
|
+
now,
|
|
1552
|
+
);
|
|
1553
|
+
if (providerRejection) return providerRejection;
|
|
1500
1554
|
const defaultCooldown = account.cooldownsByModel["__default__"] ?? 0;
|
|
1501
1555
|
if (defaultCooldown > now)
|
|
1502
1556
|
return { reason: "cooldown", detail: "default cooldown active" };
|
|
@@ -1859,29 +1913,45 @@ export class AccountRotator {
|
|
|
1859
1913
|
async getActiveAccount(
|
|
1860
1914
|
model?: string,
|
|
1861
1915
|
signal?: AbortSignal,
|
|
1916
|
+
providerId?: string,
|
|
1862
1917
|
): Promise<AccountRuntime | null> {
|
|
1863
1918
|
if (signal?.aborted) return null;
|
|
1919
|
+
const queueKey = this.getRequestQueueKey(model, providerId);
|
|
1864
1920
|
if (
|
|
1865
|
-
this.
|
|
1866
|
-
this.isConcurrencySaturated(model)
|
|
1921
|
+
this.hasQueuedRequest(queueKey) ||
|
|
1922
|
+
this.isConcurrencySaturated(model, providerId)
|
|
1867
1923
|
) {
|
|
1868
|
-
return this.enqueueAccountRequest(model, signal);
|
|
1924
|
+
return this.enqueueAccountRequest(model, signal, queueKey, providerId);
|
|
1869
1925
|
}
|
|
1870
1926
|
|
|
1871
|
-
const account = await this.tryGetActiveAccount(model);
|
|
1872
|
-
if (account || !this.isConcurrencySaturated(model)) return account;
|
|
1873
|
-
return this.enqueueAccountRequest(model, signal);
|
|
1927
|
+
const account = await this.tryGetActiveAccount(model, providerId);
|
|
1928
|
+
if (account || !this.isConcurrencySaturated(model, providerId)) return account;
|
|
1929
|
+
return this.enqueueAccountRequest(model, signal, queueKey, providerId);
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
/** Keep fairness within a provider pool without making unrelated providers wait. */
|
|
1933
|
+
private getRequestQueueKey(model?: string, providerId?: string): string {
|
|
1934
|
+
if (!model) return DEFAULT_PROVIDER;
|
|
1935
|
+
return providerId ?? getProviderIdForPoolKey(this.resolveRequestPoolKey(model, providerId));
|
|
1936
|
+
}
|
|
1937
|
+
|
|
1938
|
+
private hasQueuedRequest(queueKey: string): boolean {
|
|
1939
|
+
return this.requestWaiters.some((waiter) => waiter.queueKey === queueKey);
|
|
1874
1940
|
}
|
|
1875
1941
|
|
|
1876
1942
|
private enqueueAccountRequest(
|
|
1877
1943
|
model?: string,
|
|
1878
1944
|
signal?: AbortSignal,
|
|
1945
|
+
queueKey = this.getRequestQueueKey(model),
|
|
1946
|
+
providerId?: string,
|
|
1879
1947
|
): Promise<AccountRuntime | null> {
|
|
1880
1948
|
if (signal?.aborted) return Promise.resolve(null);
|
|
1881
1949
|
|
|
1882
1950
|
return new Promise<AccountRuntime | null>((resolve, reject) => {
|
|
1883
1951
|
const waiter = {} as AccountRequestWaiter;
|
|
1952
|
+
waiter.queueKey = queueKey;
|
|
1884
1953
|
waiter.model = model;
|
|
1954
|
+
waiter.providerId = providerId;
|
|
1885
1955
|
waiter.signal = signal;
|
|
1886
1956
|
waiter.resolve = resolve;
|
|
1887
1957
|
waiter.reject = reject;
|
|
@@ -1945,6 +2015,10 @@ export class AccountRotator {
|
|
|
1945
2015
|
}
|
|
1946
2016
|
this.clearRequestWaiterWake();
|
|
1947
2017
|
this.requestWaiterWakeAt = wakeAt;
|
|
2018
|
+
const delayMs = Math.min(
|
|
2019
|
+
MAX_NODE_TIMEOUT_MS,
|
|
2020
|
+
Math.max(1, wakeAt - Date.now()),
|
|
2021
|
+
);
|
|
1948
2022
|
this.requestWaiterWakeTimer = setTimeout(() => {
|
|
1949
2023
|
this.requestWaiterWakeTimer = null;
|
|
1950
2024
|
if (this.requestWaiters.length === 0) {
|
|
@@ -1957,7 +2031,7 @@ export class AccountRotator {
|
|
|
1957
2031
|
}
|
|
1958
2032
|
this.requestWaiterWakeAt = 0;
|
|
1959
2033
|
this.requestWaiterDrain();
|
|
1960
|
-
},
|
|
2034
|
+
}, delayMs);
|
|
1961
2035
|
}
|
|
1962
2036
|
|
|
1963
2037
|
private requestWaiterDrain(): void {
|
|
@@ -1975,20 +2049,27 @@ export class AccountRotator {
|
|
|
1975
2049
|
do {
|
|
1976
2050
|
this.requestWaiterDrainRequested = false;
|
|
1977
2051
|
progressed = false;
|
|
1978
|
-
|
|
2052
|
+
const queueKeys = [
|
|
2053
|
+
...new Set(this.requestWaiters.map((waiter) => waiter.queueKey)),
|
|
2054
|
+
];
|
|
2055
|
+
for (const queueKey of queueKeys) {
|
|
2056
|
+
const waiter = this.requestWaiters.find(
|
|
2057
|
+
(candidate) => candidate.queueKey === queueKey,
|
|
2058
|
+
);
|
|
2059
|
+
if (!waiter) continue;
|
|
1979
2060
|
if (waiter.signal?.aborted) {
|
|
1980
2061
|
this.settleAccountRequestWaiter(waiter, null);
|
|
1981
2062
|
progressed = true;
|
|
1982
|
-
|
|
2063
|
+
continue;
|
|
1983
2064
|
}
|
|
1984
2065
|
|
|
1985
2066
|
let account: AccountRuntime | null;
|
|
1986
2067
|
try {
|
|
1987
|
-
account = await this.tryGetActiveAccount(waiter.model);
|
|
2068
|
+
account = await this.tryGetActiveAccount(waiter.model, waiter.providerId);
|
|
1988
2069
|
} catch (error) {
|
|
1989
2070
|
this.rejectAccountRequestWaiter(waiter, error);
|
|
1990
2071
|
progressed = true;
|
|
1991
|
-
|
|
2072
|
+
continue;
|
|
1992
2073
|
}
|
|
1993
2074
|
|
|
1994
2075
|
if (!this.requestWaiters.includes(waiter)) {
|
|
@@ -1996,29 +2077,28 @@ export class AccountRotator {
|
|
|
1996
2077
|
this.finishRequest(
|
|
1997
2078
|
account,
|
|
1998
2079
|
waiter.model
|
|
1999
|
-
? this.resolveRequestPoolKey(waiter.model)
|
|
2080
|
+
? this.resolveRequestPoolKey(waiter.model, waiter.providerId)
|
|
2000
2081
|
: undefined,
|
|
2001
2082
|
);
|
|
2002
2083
|
}
|
|
2003
2084
|
progressed = true;
|
|
2004
|
-
|
|
2085
|
+
continue;
|
|
2005
2086
|
}
|
|
2006
2087
|
if (account) {
|
|
2007
2088
|
this.settleAccountRequestWaiter(waiter, account);
|
|
2008
2089
|
progressed = true;
|
|
2009
|
-
|
|
2090
|
+
continue;
|
|
2010
2091
|
}
|
|
2011
2092
|
if (this.requestWaiterDrainRequested) {
|
|
2012
2093
|
progressed = true;
|
|
2013
|
-
|
|
2094
|
+
continue;
|
|
2014
2095
|
}
|
|
2015
|
-
const wakeAt = this.getNextRequestAvailabilityAt(waiter.model);
|
|
2096
|
+
const wakeAt = this.getNextRequestAvailabilityAt(waiter.model, waiter.providerId);
|
|
2016
2097
|
if (wakeAt !== null) this.scheduleRequestWaiterWake(wakeAt);
|
|
2017
|
-
if (!this.isConcurrencySaturated(waiter.model) && wakeAt === null) {
|
|
2098
|
+
if (!this.isConcurrencySaturated(waiter.model, waiter.providerId) && wakeAt === null) {
|
|
2018
2099
|
this.settleAccountRequestWaiter(waiter, null);
|
|
2019
2100
|
progressed = true;
|
|
2020
2101
|
}
|
|
2021
|
-
break;
|
|
2022
2102
|
}
|
|
2023
2103
|
} while (progressed || this.requestWaiterDrainRequested);
|
|
2024
2104
|
} finally {
|
|
@@ -2027,10 +2107,10 @@ export class AccountRotator {
|
|
|
2027
2107
|
}
|
|
2028
2108
|
}
|
|
2029
2109
|
|
|
2030
|
-
private isConcurrencySaturated(model?: string): boolean {
|
|
2110
|
+
private isConcurrencySaturated(model?: string, providerId?: string): boolean {
|
|
2031
2111
|
const now = Date.now();
|
|
2032
2112
|
if (this.isProtectivePauseActive(now)) return false;
|
|
2033
|
-
const modelKey = model ? this.resolveRequestPoolKey(model) : null;
|
|
2113
|
+
const modelKey = model ? this.resolveRequestPoolKey(model, providerId) : null;
|
|
2034
2114
|
if (!modelKey) return false;
|
|
2035
2115
|
const policy = this.config.routingPolicy || "timer-first";
|
|
2036
2116
|
|
|
@@ -2066,12 +2146,12 @@ export class AccountRotator {
|
|
|
2066
2146
|
|
|
2067
2147
|
// Try to reserve an account immediately. The public method queues only
|
|
2068
2148
|
// when every otherwise-eligible account is blocked by concurrency.
|
|
2069
|
-
private async tryGetActiveAccount(model?: string): Promise<AccountRuntime | null> {
|
|
2149
|
+
private async tryGetActiveAccount(model?: string, providerId?: string): Promise<AccountRuntime | null> {
|
|
2070
2150
|
const now = Date.now();
|
|
2071
2151
|
if (this.accounts.length === 0) return null;
|
|
2072
2152
|
if (this.isProtectivePauseActive(now)) return null;
|
|
2073
2153
|
|
|
2074
|
-
const modelKey = model ? this.resolveRequestPoolKey(model) : null;
|
|
2154
|
+
const modelKey = model ? this.resolveRequestPoolKey(model, providerId) : null;
|
|
2075
2155
|
const state = modelKey ? this.modelState.get(modelKey) : null;
|
|
2076
2156
|
const idx = state?.activeAccountIndex ?? this.defaultIndex;
|
|
2077
2157
|
const current = this.accounts[idx];
|
|
@@ -2130,12 +2210,32 @@ export class AccountRotator {
|
|
|
2130
2210
|
}
|
|
2131
2211
|
}
|
|
2132
2212
|
|
|
2133
|
-
if (current && modelKey
|
|
2134
|
-
this.
|
|
2135
|
-
|
|
2136
|
-
|
|
2213
|
+
if (current && modelKey) {
|
|
2214
|
+
const providerRejection = this.getProviderEligibilityRejection(
|
|
2215
|
+
current,
|
|
2216
|
+
modelKey,
|
|
2217
|
+
now,
|
|
2137
2218
|
);
|
|
2138
|
-
|
|
2219
|
+
if (providerRejection) {
|
|
2220
|
+
// A cooldown is expected after a provider 429 and can be hit by many
|
|
2221
|
+
// concurrent callers. Keep that path quiet; diagnostics already show
|
|
2222
|
+
// the cooldown and the generic no-route warning is deduplicated below.
|
|
2223
|
+
if (providerRejection.reason === "provider-ineligible") {
|
|
2224
|
+
const warningKey = `${modelKey}:provider-ineligible`;
|
|
2225
|
+
const lastLoggedAt = this.routingWarningLastLoggedAt.get(warningKey);
|
|
2226
|
+
if (
|
|
2227
|
+
lastLoggedAt === undefined ||
|
|
2228
|
+
now - lastLoggedAt >= AccountRotator.ROUTING_WARNING_DEDUP_MS
|
|
2229
|
+
) {
|
|
2230
|
+
this.routingWarningLastLoggedAt.set(warningKey, now);
|
|
2231
|
+
this.log(
|
|
2232
|
+
`${current.config.label || current.config.email}: provider unavailable for model (${providerRejection.detail}), rotating`,
|
|
2233
|
+
"warn",
|
|
2234
|
+
);
|
|
2235
|
+
}
|
|
2236
|
+
}
|
|
2237
|
+
return this.rotateModelForRequest(modelKey, now, idx);
|
|
2238
|
+
}
|
|
2139
2239
|
}
|
|
2140
2240
|
if (
|
|
2141
2241
|
current &&
|
|
@@ -2351,10 +2451,17 @@ export class AccountRotator {
|
|
|
2351
2451
|
} else {
|
|
2352
2452
|
const diagnostics = this.buildRoutingDiagnostics(modelKey, now);
|
|
2353
2453
|
this.routingDiagnostics[modelKey] = diagnostics;
|
|
2354
|
-
this.
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2454
|
+
const lastLoggedAt = this.routingWarningLastLoggedAt.get(modelKey);
|
|
2455
|
+
if (
|
|
2456
|
+
lastLoggedAt === undefined ||
|
|
2457
|
+
now - lastLoggedAt >= AccountRotator.ROUTING_WARNING_DEDUP_MS
|
|
2458
|
+
) {
|
|
2459
|
+
this.routingWarningLastLoggedAt.set(modelKey, now);
|
|
2460
|
+
this.log(
|
|
2461
|
+
`[${modelKey}] All accounts disabled or unavailable: ${diagnostics.reason}`,
|
|
2462
|
+
"warn",
|
|
2463
|
+
);
|
|
2464
|
+
}
|
|
2358
2465
|
}
|
|
2359
2466
|
return null;
|
|
2360
2467
|
}
|
|
@@ -2460,9 +2567,10 @@ export class AccountRotator {
|
|
|
2460
2567
|
async rotateToNext(
|
|
2461
2568
|
model?: string,
|
|
2462
2569
|
failedAccount?: AccountRuntime | number | string,
|
|
2570
|
+
providerId?: string,
|
|
2463
2571
|
): Promise<AccountRuntime | null> {
|
|
2464
2572
|
if (this.isProtectivePauseActive(Date.now())) return null;
|
|
2465
|
-
const modelKey = model ? this.resolveRequestPoolKey(model) : null;
|
|
2573
|
+
const modelKey = model ? this.resolveRequestPoolKey(model, providerId) : null;
|
|
2466
2574
|
let excludeIdx: number;
|
|
2467
2575
|
if (typeof failedAccount === "number") {
|
|
2468
2576
|
excludeIdx = failedAccount;
|
|
@@ -2485,14 +2593,14 @@ export class AccountRotator {
|
|
|
2485
2593
|
}
|
|
2486
2594
|
|
|
2487
2595
|
// Record a successful request. Returns true if rotation is needed.
|
|
2488
|
-
recordRequest(account: AccountRuntime, model?: string): boolean {
|
|
2596
|
+
recordRequest(account: AccountRuntime, model?: string, providerId?: string): boolean {
|
|
2489
2597
|
account.requestsSinceRotation++;
|
|
2490
2598
|
account.totalRequests++;
|
|
2491
2599
|
account.lastUsed = Date.now();
|
|
2492
2600
|
account.consecutiveErrors = 0;
|
|
2493
2601
|
account.lastError = null;
|
|
2494
2602
|
|
|
2495
|
-
const modelKey = model ? this.resolveRequestPoolKey(model) : null;
|
|
2603
|
+
const modelKey = model ? this.resolveRequestPoolKey(model, providerId) : null;
|
|
2496
2604
|
const state = modelKey ? this.modelState.get(modelKey) : null;
|
|
2497
2605
|
const shouldRotate =
|
|
2498
2606
|
!!modelKey &&
|
|
@@ -3005,7 +3113,7 @@ export class AccountRotator {
|
|
|
3005
3113
|
const modelKey = model
|
|
3006
3114
|
? this.resolveAccountPoolKey(account, model)
|
|
3007
3115
|
: "__default__";
|
|
3008
|
-
if (model && (
|
|
3116
|
+
if (model && (this.isCodexPoolKey(modelKey) || isCodexRequestModel(model))) {
|
|
3009
3117
|
this.setProviderCooldown(account, "openai-codex", cooldownMs);
|
|
3010
3118
|
}
|
|
3011
3119
|
account.cooldownsByModel[modelKey] = now + cooldownMs;
|
|
@@ -3019,6 +3127,7 @@ export class AccountRotator {
|
|
|
3019
3127
|
candidate.modelKey === modelKey &&
|
|
3020
3128
|
(candidate.providerId === DEFAULT_PROVIDER ||
|
|
3021
3129
|
candidate.providerId === "ollama" ||
|
|
3130
|
+
candidate.providerId === "openai-codex" ||
|
|
3022
3131
|
candidate.providerId === undefined),
|
|
3023
3132
|
);
|
|
3024
3133
|
if (quota) {
|
|
@@ -3047,11 +3156,11 @@ export class AccountRotator {
|
|
|
3047
3156
|
providerResourceExhausted = false,
|
|
3048
3157
|
): void {
|
|
3049
3158
|
const now = Date.now();
|
|
3050
|
-
|
|
3159
|
+
const poolKey = model ? this.resolveAccountPoolKey(account, model) : null;
|
|
3160
|
+
if (model && (isCodexRequestModel(model) || (poolKey && this.isCodexPoolKey(poolKey)))) {
|
|
3051
3161
|
this.setProviderCooldown(account, "openai-codex", cooldownMs);
|
|
3052
3162
|
return;
|
|
3053
3163
|
}
|
|
3054
|
-
const poolKey = model ? this.resolveAccountPoolKey(account, model) : null;
|
|
3055
3164
|
const isAccountScopedProvider =
|
|
3056
3165
|
providerResourceExhausted ||
|
|
3057
3166
|
(poolKey &&
|
|
@@ -3482,7 +3591,8 @@ export class AccountRotator {
|
|
|
3482
3591
|
}
|
|
3483
3592
|
|
|
3484
3593
|
private isCodexPoolKey(modelKey: string): boolean {
|
|
3485
|
-
return modelKey
|
|
3594
|
+
return modelKey === CODEX_QUOTA_MODEL_KEY ||
|
|
3595
|
+
modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`);
|
|
3486
3596
|
}
|
|
3487
3597
|
|
|
3488
3598
|
private async ensureValidTokenForModel(
|
|
@@ -3622,23 +3732,59 @@ export class AccountRotator {
|
|
|
3622
3732
|
account: AccountRuntime,
|
|
3623
3733
|
modelKey: string,
|
|
3624
3734
|
): boolean {
|
|
3735
|
+
return this.getProviderEligibilityRejection(account, modelKey) === null;
|
|
3736
|
+
}
|
|
3737
|
+
|
|
3738
|
+
private getProviderEligibilityRejection(
|
|
3739
|
+
account: AccountRuntime,
|
|
3740
|
+
modelKey: string,
|
|
3741
|
+
now = Date.now(),
|
|
3742
|
+
): { reason: RoutingRejectionReason; detail: string } | null {
|
|
3625
3743
|
const accountId = getAccountIdentity(account);
|
|
3626
3744
|
if (
|
|
3627
3745
|
!isStaticAntigravityModel(modelKey) &&
|
|
3628
3746
|
dynamicCatalog.hasOwnershipForModel(modelKey) &&
|
|
3629
3747
|
!dynamicCatalog.hasModelForAccount(accountId, modelKey)
|
|
3630
3748
|
) {
|
|
3631
|
-
return
|
|
3749
|
+
return {
|
|
3750
|
+
reason: "provider-ineligible",
|
|
3751
|
+
detail: "account does not own this provider model",
|
|
3752
|
+
};
|
|
3632
3753
|
}
|
|
3633
3754
|
const providerId = getProviderIdForPoolKey(modelKey);
|
|
3634
|
-
|
|
3635
|
-
|
|
3636
|
-
|
|
3755
|
+
if (!hasCredential(account.config, providerId)) {
|
|
3756
|
+
return {
|
|
3757
|
+
reason: "provider-ineligible",
|
|
3758
|
+
detail: `account has no ${providerId} credential for this provider pool`,
|
|
3759
|
+
};
|
|
3760
|
+
}
|
|
3761
|
+
if (account.invalidProviders?.[providerId]) {
|
|
3762
|
+
return {
|
|
3763
|
+
reason: "provider-ineligible",
|
|
3764
|
+
detail: `${providerId} credential is invalid; re-authentication required`,
|
|
3765
|
+
};
|
|
3766
|
+
}
|
|
3767
|
+
if (
|
|
3768
|
+
providerId === "openai-codex" &&
|
|
3769
|
+
!getProviderAdapter(providerId).hasValidCredentials(account)
|
|
3770
|
+
) {
|
|
3771
|
+
return {
|
|
3772
|
+
reason: "provider-ineligible",
|
|
3773
|
+
detail: "Codex credential is missing or empty",
|
|
3774
|
+
};
|
|
3775
|
+
}
|
|
3776
|
+
if ((account.providerCooldowns?.[providerId] ?? 0) > now) {
|
|
3777
|
+
return {
|
|
3778
|
+
reason: "cooldown",
|
|
3779
|
+
detail: "provider cooldown active",
|
|
3780
|
+
};
|
|
3781
|
+
}
|
|
3782
|
+
return null;
|
|
3637
3783
|
}
|
|
3638
3784
|
|
|
3639
3785
|
/** Public pool-key resolution for quota routing display/logging. */
|
|
3640
|
-
resolveQuotaModelKeyForDisplay(model: string): string {
|
|
3641
|
-
return this.resolveRequestPoolKey(model);
|
|
3786
|
+
resolveQuotaModelKeyForDisplay(model: string, providerId?: string): string {
|
|
3787
|
+
return this.resolveRequestPoolKey(model, providerId);
|
|
3642
3788
|
}
|
|
3643
3789
|
|
|
3644
3790
|
/** Preserve the exact identity of models learned from the runtime catalog. */
|
|
@@ -3646,11 +3792,11 @@ export class AccountRotator {
|
|
|
3646
3792
|
return dynamicCatalog.getObservedModelId(model) ?? resolveDisplayModelKey(model);
|
|
3647
3793
|
}
|
|
3648
3794
|
|
|
3649
|
-
private resolveRequestPoolKey(model: string): string {
|
|
3650
|
-
return this.resolvePoolKeyForModel(model) ?? "__default__";
|
|
3795
|
+
private resolveRequestPoolKey(model: string, providerId?: string): string {
|
|
3796
|
+
return this.resolvePoolKeyForModel(model, providerId) ?? "__default__";
|
|
3651
3797
|
}
|
|
3652
3798
|
|
|
3653
|
-
private resolvePoolKeyForModel(model: string): string | null {
|
|
3799
|
+
private resolvePoolKeyForModel(model: string, providerId?: string): string | null {
|
|
3654
3800
|
const normalizedModel = model.trim().toLowerCase();
|
|
3655
3801
|
if (
|
|
3656
3802
|
!isStaticAntigravityModel(model) &&
|
|
@@ -3662,6 +3808,7 @@ export class AccountRotator {
|
|
|
3662
3808
|
const context = {
|
|
3663
3809
|
ollamaModels: this.ollamaModels,
|
|
3664
3810
|
codexModels: this.codexModels,
|
|
3811
|
+
providerId,
|
|
3665
3812
|
};
|
|
3666
3813
|
const adapter = findProviderForModel(model, context);
|
|
3667
3814
|
if (adapter?.getPoolKey) {
|
|
@@ -3743,12 +3890,13 @@ export class AccountRotator {
|
|
|
3743
3890
|
private getRequestAvailabilityTimes(
|
|
3744
3891
|
model: string | undefined,
|
|
3745
3892
|
now: number,
|
|
3893
|
+
providerId?: string,
|
|
3746
3894
|
): number[] {
|
|
3747
3895
|
const retryTimes: number[] = [];
|
|
3748
3896
|
if (this.protectivePauseUntil > now)
|
|
3749
3897
|
retryTimes.push(this.protectivePauseUntil);
|
|
3750
3898
|
const modelKey = model
|
|
3751
|
-
? (this.resolvePoolKeyForModel(model) ?? resolveQuotaModelKey(model) ?? "__default__")
|
|
3899
|
+
? (this.resolvePoolKeyForModel(model, providerId) ?? resolveQuotaModelKey(model) ?? "__default__")
|
|
3752
3900
|
: "__default__";
|
|
3753
3901
|
const quotaStateKey = this.resolveQuotaStateKey(modelKey);
|
|
3754
3902
|
const dailyResetAt = nextUtcDayStartMs(now);
|
|
@@ -3756,14 +3904,14 @@ export class AccountRotator {
|
|
|
3756
3904
|
if (modelBreaker > now) retryTimes.push(modelBreaker);
|
|
3757
3905
|
for (const account of this.accounts) {
|
|
3758
3906
|
if (account.disabled || account.flagged) continue;
|
|
3759
|
-
const
|
|
3907
|
+
const candidateProviderId = providerId ?? getProviderIdForPoolKey(modelKey);
|
|
3760
3908
|
if (
|
|
3761
|
-
!hasCredential(account.config,
|
|
3762
|
-
account.invalidProviders?.[
|
|
3909
|
+
!hasCredential(account.config, candidateProviderId) ||
|
|
3910
|
+
account.invalidProviders?.[candidateProviderId]
|
|
3763
3911
|
) {
|
|
3764
3912
|
continue;
|
|
3765
3913
|
}
|
|
3766
|
-
const providerCooldown = account.providerCooldowns?.[
|
|
3914
|
+
const providerCooldown = account.providerCooldowns?.[candidateProviderId] ?? 0;
|
|
3767
3915
|
if (providerCooldown > now) retryTimes.push(providerCooldown);
|
|
3768
3916
|
if (this.isDailySafetyStopped(account, now))
|
|
3769
3917
|
retryTimes.push(dailyResetAt);
|
|
@@ -3792,15 +3940,15 @@ export class AccountRotator {
|
|
|
3792
3940
|
return retryTimes;
|
|
3793
3941
|
}
|
|
3794
3942
|
|
|
3795
|
-
private getNextRequestAvailabilityAt(model?: string): number | null {
|
|
3943
|
+
private getNextRequestAvailabilityAt(model?: string, providerId?: string): number | null {
|
|
3796
3944
|
const now = Date.now();
|
|
3797
|
-
const retryTimes = this.getRequestAvailabilityTimes(model, now);
|
|
3945
|
+
const retryTimes = this.getRequestAvailabilityTimes(model, now, providerId);
|
|
3798
3946
|
return retryTimes.length > 0 ? Math.min(...retryTimes) : null;
|
|
3799
3947
|
}
|
|
3800
3948
|
|
|
3801
|
-
getRetryAfterMs(model?: string): number {
|
|
3949
|
+
getRetryAfterMs(model?: string, providerId?: string): number {
|
|
3802
3950
|
const now = Date.now();
|
|
3803
|
-
const retryTimes = this.getRequestAvailabilityTimes(model, now);
|
|
3951
|
+
const retryTimes = this.getRequestAvailabilityTimes(model, now, providerId);
|
|
3804
3952
|
if (retryTimes.length === 0) return 0;
|
|
3805
3953
|
return Math.max(1000, Math.min(...retryTimes) - now);
|
|
3806
3954
|
}
|
|
@@ -3974,8 +4122,31 @@ export class AccountRotator {
|
|
|
3974
4122
|
return applyConfigDefaults(structuredClone(this.config));
|
|
3975
4123
|
}
|
|
3976
4124
|
|
|
4125
|
+
getPublicConfig(): Config {
|
|
4126
|
+
return redactTypeSafeRoutingInConfig(this.getConfig());
|
|
4127
|
+
}
|
|
4128
|
+
|
|
3977
4129
|
async replaceConfig(nextConfig: Config): Promise<void> {
|
|
3978
4130
|
const normalized = applyConfigDefaults(nextConfig);
|
|
4131
|
+
const incomingTypeSafe = normalized.typesafeRouting;
|
|
4132
|
+
const existingTypeSafe = this.config.typesafeRouting;
|
|
4133
|
+
if (existingTypeSafe && incomingTypeSafe) {
|
|
4134
|
+
const incomingKey = incomingTypeSafe.apiKey;
|
|
4135
|
+
normalized.typesafeRouting = {
|
|
4136
|
+
...existingTypeSafe,
|
|
4137
|
+
...incomingTypeSafe,
|
|
4138
|
+
apiKey:
|
|
4139
|
+
!incomingKey || isRedactedSecret(incomingKey)
|
|
4140
|
+
? existingTypeSafe.apiKey
|
|
4141
|
+
: incomingKey,
|
|
4142
|
+
};
|
|
4143
|
+
} else if (existingTypeSafe && !incomingTypeSafe) {
|
|
4144
|
+
// Public dashboard exports omit the secret; preserve it on unrelated
|
|
4145
|
+
// config edits instead of disabling Jev unexpectedly.
|
|
4146
|
+
normalized.typesafeRouting = existingTypeSafe;
|
|
4147
|
+
} else if (incomingTypeSafe && isRedactedSecret(incomingTypeSafe.apiKey)) {
|
|
4148
|
+
normalized.typesafeRouting = { ...incomingTypeSafe, apiKey: undefined };
|
|
4149
|
+
}
|
|
3979
4150
|
const unmatchedExisting = [...this.accounts];
|
|
3980
4151
|
const matchAndReuseAccount = (config: AccountConfig): AccountRuntime => {
|
|
3981
4152
|
const targetId = getAccountIdentity(config);
|
|
@@ -4621,7 +4792,7 @@ export class AccountRotator {
|
|
|
4621
4792
|
const providerResourceExhausted =
|
|
4622
4793
|
classifyRateLimitReason(errorText, response.status) === "quota-exhausted";
|
|
4623
4794
|
const cooldownMs = providerResourceExhausted
|
|
4624
|
-
? target.providerId === DEFAULT_PROVIDER
|
|
4795
|
+
? target.providerId === DEFAULT_PROVIDER || target.providerId === "openai-codex"
|
|
4625
4796
|
? parseRetryAfterMs(
|
|
4626
4797
|
errorText,
|
|
4627
4798
|
response.headers,
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { ServerResponse } from "node:http";
|
|
2
|
+
|
|
3
|
+
export const STREAM_IDLE_TIMEOUT_MS = 2 * 60 * 1000;
|
|
4
|
+
export const STREAM_BACKPRESSURE_TIMEOUT_MS = 30 * 1000;
|
|
5
|
+
|
|
6
|
+
export class StreamIdleTimeoutError extends Error {
|
|
7
|
+
constructor(timeoutMs: number) {
|
|
8
|
+
super(`upstream stream idle timeout after ${Math.round(timeoutMs / 1000)}s`);
|
|
9
|
+
this.name = "StreamIdleTimeoutError";
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Resettable guard used to release upstream streams that stop producing data. */
|
|
14
|
+
export function createStreamIdleGuard(
|
|
15
|
+
onTimeout: (error: StreamIdleTimeoutError) => void,
|
|
16
|
+
timeoutMs = STREAM_IDLE_TIMEOUT_MS,
|
|
17
|
+
): { reset: () => void; clear: () => void } {
|
|
18
|
+
const effectiveTimeoutMs = Number.isFinite(timeoutMs)
|
|
19
|
+
? Math.max(1, timeoutMs)
|
|
20
|
+
: STREAM_IDLE_TIMEOUT_MS;
|
|
21
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
22
|
+
|
|
23
|
+
const reset = (): void => {
|
|
24
|
+
if (timer) clearTimeout(timer);
|
|
25
|
+
timer = setTimeout(() => {
|
|
26
|
+
timer = null;
|
|
27
|
+
onTimeout(new StreamIdleTimeoutError(effectiveTimeoutMs));
|
|
28
|
+
}, effectiveTimeoutMs);
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const clear = (): void => {
|
|
32
|
+
if (timer) clearTimeout(timer);
|
|
33
|
+
timer = null;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
reset();
|
|
37
|
+
return { reset, clear };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Respect the HTTP response's high-water mark so a client that stopped
|
|
42
|
+
* reading cannot make the proxy buffer an unbounded streamed response.
|
|
43
|
+
*/
|
|
44
|
+
export function waitForResponseDrain(
|
|
45
|
+
res: ServerResponse,
|
|
46
|
+
timeoutMs = STREAM_BACKPRESSURE_TIMEOUT_MS,
|
|
47
|
+
): Promise<void> {
|
|
48
|
+
if (res.destroyed || res.writableEnded || !res.writableNeedDrain) {
|
|
49
|
+
return Promise.resolve();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return new Promise<void>((resolve, reject) => {
|
|
53
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
54
|
+
let settled = false;
|
|
55
|
+
|
|
56
|
+
const cleanup = (): void => {
|
|
57
|
+
if (timer) clearTimeout(timer);
|
|
58
|
+
res.off("drain", onDrain);
|
|
59
|
+
res.off("close", onClose);
|
|
60
|
+
res.off("error", onError);
|
|
61
|
+
};
|
|
62
|
+
const finish = (error?: Error): void => {
|
|
63
|
+
if (settled) return;
|
|
64
|
+
settled = true;
|
|
65
|
+
cleanup();
|
|
66
|
+
if (error) reject(error);
|
|
67
|
+
else resolve();
|
|
68
|
+
};
|
|
69
|
+
const onDrain = (): void => finish();
|
|
70
|
+
const onClose = (): void =>
|
|
71
|
+
finish(new Error("client response closed while draining backpressure"));
|
|
72
|
+
const onError = (error: Error): void => finish(error);
|
|
73
|
+
|
|
74
|
+
res.once("drain", onDrain);
|
|
75
|
+
res.once("close", onClose);
|
|
76
|
+
res.once("error", onError);
|
|
77
|
+
timer = setTimeout(() => {
|
|
78
|
+
finish(
|
|
79
|
+
new Error(
|
|
80
|
+
`client backpressure timeout after ${Math.round(timeoutMs / 1000)}s`,
|
|
81
|
+
),
|
|
82
|
+
);
|
|
83
|
+
}, Math.max(1, timeoutMs));
|
|
84
|
+
});
|
|
85
|
+
}
|