tuxevil-rotator 4.2.2 → 4.4.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 +48 -1
- package/README.md +11 -4
- package/package.json +2 -1
- package/plugins/opencode-discovery/capabilities.d.mts +7 -0
- package/plugins/opencode-discovery/capabilities.mjs +54 -0
- package/plugins/opencode-discovery/index.d.mts +2 -1
- package/plugins/opencode-discovery/index.mjs +6 -1
- package/plugins/opencode-discovery/package.json +3 -1
- package/src/access-evidence.ts +153 -0
- package/src/access-probe.ts +85 -0
- package/src/admin-auth.ts +4 -1
- package/src/audio-transcription.ts +32 -6
- package/src/auto-access-shadow.ts +11 -0
- package/src/auto-model-access.ts +185 -0
- package/src/auto-output-health.ts +12 -0
- package/src/auto-routing-evaluation.ts +80 -0
- package/src/auto-routing-quality.ts +308 -0
- package/src/auto-routing.ts +403 -26
- package/src/cli.ts +3 -3
- package/src/compat/model-specs.ts +4 -0
- package/src/compat.ts +253 -37
- package/src/compression/index.ts +6 -6
- package/src/compression/lite.ts +3 -9
- package/src/compression/rtk/index.ts +0 -3
- package/src/config-defaults.ts +7 -0
- package/src/dashboard-app.ts +1 -0
- package/src/dashboard.ts +5 -0
- package/src/db-store.ts +10 -0
- package/src/index.ts +2 -0
- package/src/install-agent.ts +211 -129
- package/src/install-opencode.ts +80 -18
- package/src/model-access-api.ts +74 -0
- package/src/model-access.ts +56 -0
- package/src/ollama-output-gate.ts +18 -0
- package/src/onboarding.ts +1 -1
- package/src/provider-catalog-evidence.ts +26 -0
- package/src/providers/google-antigravity/catalog.ts +14 -6
- package/src/providers/google-antigravity/dynamic-catalog.ts +87 -3
- package/src/providers/google-antigravity/forward.ts +4 -2
- package/src/providers/google-antigravity/quota.ts +7 -0
- package/src/providers/ollama/context-window.ts +13 -0
- package/src/providers/ollama/forward.ts +10 -0
- package/src/providers/ollama/quota.ts +4 -0
- package/src/providers/ollama/translators.ts +19 -2
- package/src/providers/openai-codex/catalog.ts +157 -18
- package/src/providers/openai-codex/compat.ts +5 -1
- package/src/providers/openai-codex/credentials.ts +22 -6
- package/src/providers/openai-codex/index.ts +9 -1
- package/src/providers/openai-codex/quota.ts +19 -6
- package/src/providers/opencode-zen/forward.ts +1 -1
- package/src/providers/opencode-zen/quota.ts +2 -0
- package/src/proxy.ts +113 -5
- package/src/quota-observation.ts +26 -0
- package/src/quota-pools.ts +322 -0
- package/src/rotator.ts +167 -40
- package/src/settings-repository.ts +1 -0
- package/src/types.ts +106 -29
- package/src/usage-limits-auth.ts +24 -0
- package/src/usage-limits.ts +148 -0
- package/src/validators.ts +26 -0
- package/src/web/app.tsx +4 -0
- package/src/web/components/icons.tsx +15 -0
- package/src/web/components/overlays.tsx +4 -0
- package/src/web/components/ui.tsx +9 -9
- package/src/web/lib/audio-recorder.ts +159 -0
- package/src/web/lib/colors.ts +4 -0
- package/src/web/lib/playground-storage.ts +261 -0
- package/src/web/lib/playground.ts +483 -0
- package/src/web/lib/pool-navigation.ts +4 -0
- package/src/web/lib/pools.ts +2 -243
- package/src/web/nav.ts +1 -0
- package/src/web/pages/AccountDetail.tsx +2 -1
- package/src/web/pages/ModelAccess.tsx +88 -0
- package/src/web/pages/Models.tsx +2 -0
- package/src/web/pages/Overview.tsx +26 -9
- package/src/web/pages/Playground.tsx +1692 -0
- package/src/web/pages/Transcription.tsx +562 -0
- package/src/web/state/api.ts +6 -0
- package/src/web/state/playground-client.ts +136 -0
- package/src/web/state/playground.ts +69 -0
- package/src/web/state/router.ts +2 -2
- package/src/web/state/transcription-client.ts +93 -0
- package/src/web/styles/app.css +501 -0
- package/tools/telemetry-receiver/receiver.js +59 -46
package/src/proxy.ts
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import { serveAccessProbe } from "./access-probe.js";
|
|
2
|
+
import { observeAccessAttempt, logAccessPolicyShadow } from "./access-evidence.js";
|
|
3
|
+
import { serveModelAccessApi, serveProviderPlanApi } from "./model-access-api.js";
|
|
4
|
+
import { createUsageLimitsHandler, USAGE_LIMITS_PATH } from "./usage-limits.js";
|
|
5
|
+
import { carriesUsageReadToken } from "./usage-limits-auth.js";
|
|
1
6
|
// HTTP reverse proxy - forwards requests to Antigravity with credential rotation
|
|
2
7
|
|
|
3
8
|
import {
|
|
@@ -42,6 +47,7 @@ import {
|
|
|
42
47
|
GOOGLE_BENCHMARK_CONSTANTS,
|
|
43
48
|
} from "./providers/google-antigravity/forward.js";
|
|
44
49
|
import { isDynamicallyAvailableAntigravityModel } from "./providers/google-antigravity/catalog.js";
|
|
50
|
+
import { dynamicCatalog } from "./providers/google-antigravity/dynamic-catalog.js";
|
|
45
51
|
export { forwardRequest, SseEventAccumulator, extractUsageFromSseEvent };
|
|
46
52
|
import {
|
|
47
53
|
serveStatusApi,
|
|
@@ -94,7 +100,7 @@ import {
|
|
|
94
100
|
handleCliLoginApi,
|
|
95
101
|
} from "./onboarding.js";
|
|
96
102
|
import { requireAdmin } from "./admin-auth.js";
|
|
97
|
-
import { PayloadTooLargeError, readLimitedBody } from "./body-limit.js";
|
|
103
|
+
import { getMaxBodyBytes, PayloadTooLargeError, readLimitedBody } from "./body-limit.js";
|
|
98
104
|
import { validateConfig, validateProxyRequestBody } from "./validators.js";
|
|
99
105
|
import { calculateBackoffMs } from "./fetch-with-retry.js";
|
|
100
106
|
import { logger } from "./logger.js";
|
|
@@ -190,6 +196,7 @@ import {
|
|
|
190
196
|
handleAnthropicMessages,
|
|
191
197
|
handleGeminiGenerateContent,
|
|
192
198
|
handleOpenAIChatCompletions,
|
|
199
|
+
handlePlaygroundChatCompletions,
|
|
193
200
|
handleOpenAIResponsesCancel,
|
|
194
201
|
handleOpenAIResponsesCreate,
|
|
195
202
|
handleOpenAIResponsesDelete,
|
|
@@ -200,6 +207,7 @@ import {
|
|
|
200
207
|
} from "./compat.js";
|
|
201
208
|
import {
|
|
202
209
|
handleOpenAIAudioTranscriptions,
|
|
210
|
+
handlePlaygroundAudioTranscriptions,
|
|
203
211
|
handleAudioWebSocket,
|
|
204
212
|
closeAllAudioWebSockets,
|
|
205
213
|
WS_SHUTDOWN_CLOSE_GRACE_MS,
|
|
@@ -1262,6 +1270,7 @@ export async function withRotation<T>(
|
|
|
1262
1270
|
context: RotationAttemptContext,
|
|
1263
1271
|
) => Promise<T>,
|
|
1264
1272
|
signal?: AbortSignal,
|
|
1273
|
+
options?: { autoRecovery?: boolean },
|
|
1265
1274
|
): Promise<RotationOutcome<T>> {
|
|
1266
1275
|
// Keep the admission pool and wire protocol stable across async waits and
|
|
1267
1276
|
// retries, even if provider order or switches change while the request waits.
|
|
@@ -1269,11 +1278,15 @@ export async function withRotation<T>(
|
|
|
1269
1278
|
ollamaModels: new Set(rotator.getOllamaModels?.() ?? []),
|
|
1270
1279
|
codexModels: new Set(rotator.getCodexModels?.() ?? []),
|
|
1271
1280
|
})?.id;
|
|
1281
|
+
const autoScope = body.displayModel?.toLowerCase() === "auto" && providerId
|
|
1282
|
+
? { providerId, modelId: model }
|
|
1283
|
+
: undefined;
|
|
1272
1284
|
const modelQuotaFamily = resolveQuotaModelKey(model) ??
|
|
1273
1285
|
resolveQuotaModelKey(applyModelAlias(model));
|
|
1274
1286
|
if (
|
|
1275
1287
|
(providerId === DEFAULT_PROVIDER ||
|
|
1276
|
-
(!providerId && (modelQuotaFamily === "claude" || modelQuotaFamily === "gemini"
|
|
1288
|
+
(!providerId && (modelQuotaFamily === "claude" || modelQuotaFamily === "gemini" ||
|
|
1289
|
+
dynamicCatalog.wasDiscovered(model) || dynamicCatalog.wasDiscovered(applyModelAlias(model))))) &&
|
|
1277
1290
|
!isDynamicallyAvailableAntigravityModel(model)
|
|
1278
1291
|
) {
|
|
1279
1292
|
return {
|
|
@@ -1325,7 +1338,7 @@ export async function withRotation<T>(
|
|
|
1325
1338
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1326
1339
|
if (requestIsOff()) return modelOffOutcome();
|
|
1327
1340
|
const admissionStartedMs = Date.now();
|
|
1328
|
-
const account = await rotator.getActiveAccount(model, signal, providerId);
|
|
1341
|
+
const account = await rotator.getActiveAccount(model, signal, providerId, autoScope);
|
|
1329
1342
|
if (!account) {
|
|
1330
1343
|
if (signal?.aborted) {
|
|
1331
1344
|
return { ok: false, status: 499, errorText: "Client closed request" };
|
|
@@ -1354,7 +1367,7 @@ export async function withRotation<T>(
|
|
|
1354
1367
|
};
|
|
1355
1368
|
const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
|
|
1356
1369
|
releaseCurrentAccount();
|
|
1357
|
-
const nextAccount = await rotator.rotateToNext(model, account, providerId);
|
|
1370
|
+
const nextAccount = await rotator.rotateToNext(model, account, providerId, autoScope);
|
|
1358
1371
|
return nextAccount;
|
|
1359
1372
|
};
|
|
1360
1373
|
const logRequestEnd = (status: string | number, extra = ""): void => {
|
|
@@ -1370,6 +1383,7 @@ export async function withRotation<T>(
|
|
|
1370
1383
|
rotator,
|
|
1371
1384
|
);
|
|
1372
1385
|
|
|
1386
|
+
let accessHttpStatus: number | null = null;
|
|
1373
1387
|
try {
|
|
1374
1388
|
const provider = providerAdapterForModel(account, model, rotator, providerId);
|
|
1375
1389
|
if (requestIsOff(provider.id)) return modelOffOutcome();
|
|
@@ -1410,6 +1424,7 @@ export async function withRotation<T>(
|
|
|
1410
1424
|
if (attempt < maxRetries) continue;
|
|
1411
1425
|
return sendNoAccountsAvailable(`${provider.id} turned off for ${label}`);
|
|
1412
1426
|
}
|
|
1427
|
+
if (rotator.getConfig?.().modelAccessShadow === true) logAccessPolicyShadow(account.config, provider.id, model, originalHeaders);
|
|
1413
1428
|
rotator.recordUpstreamAttempt(account);
|
|
1414
1429
|
const forwarded = await provider.forwardRequest(
|
|
1415
1430
|
account,
|
|
@@ -1418,6 +1433,7 @@ export async function withRotation<T>(
|
|
|
1418
1433
|
signal,
|
|
1419
1434
|
);
|
|
1420
1435
|
const { response, endpoint } = forwarded;
|
|
1436
|
+
accessHttpStatus = response.status;
|
|
1421
1437
|
const context: RotationAttemptContext = {
|
|
1422
1438
|
account,
|
|
1423
1439
|
label,
|
|
@@ -1435,6 +1451,26 @@ export async function withRotation<T>(
|
|
|
1435
1451
|
selectionReason: body.selectionReason,
|
|
1436
1452
|
};
|
|
1437
1453
|
|
|
1454
|
+
// Preserve explicit-model behavior. Auto uses payment/plan and timeout
|
|
1455
|
+
// responses as request-local exclusions before any client bytes are sent.
|
|
1456
|
+
if (options?.autoRecovery && [402, 408].includes(response.status)) {
|
|
1457
|
+
const errorText = response.status === 402
|
|
1458
|
+
? "Upstream payment or plan restriction"
|
|
1459
|
+
: "Upstream request timed out";
|
|
1460
|
+
await response.body?.cancel().catch(() => {});
|
|
1461
|
+
observeAccessAttempt(account.config, provider.id, model, originalHeaders, response.status, errorText);
|
|
1462
|
+
logRequestEnd(response.status);
|
|
1463
|
+
return {
|
|
1464
|
+
ok: false,
|
|
1465
|
+
status: response.status,
|
|
1466
|
+
errorText,
|
|
1467
|
+
endpoint,
|
|
1468
|
+
context,
|
|
1469
|
+
totalMs: Date.now() - requestStartMs,
|
|
1470
|
+
};
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
if (!response.ok) observeAccessAttempt(account.config, provider.id, model, originalHeaders, response.status);
|
|
1438
1474
|
const action = await classifyUpstreamResponse(
|
|
1439
1475
|
response,
|
|
1440
1476
|
endpoint,
|
|
@@ -1445,6 +1481,7 @@ export async function withRotation<T>(
|
|
|
1445
1481
|
);
|
|
1446
1482
|
|
|
1447
1483
|
if (action.kind !== "success") {
|
|
1484
|
+
observeAccessAttempt(account.config, provider.id, model, originalHeaders, response.status, action.errorText);
|
|
1448
1485
|
const decision = await handleUpstreamAccountAction({
|
|
1449
1486
|
action,
|
|
1450
1487
|
provider,
|
|
@@ -1465,6 +1502,7 @@ export async function withRotation<T>(
|
|
|
1465
1502
|
|
|
1466
1503
|
// success
|
|
1467
1504
|
const result = await onSuccess(response, context);
|
|
1505
|
+
observeAccessAttempt(account.config, provider.id, model, originalHeaders, response.ok && result && typeof result === "object" && "streamError" in result && result.streamError ? 502 : response.status);
|
|
1468
1506
|
const shouldRotate = rotator.recordRequest(account, model, providerId);
|
|
1469
1507
|
const inTokens =
|
|
1470
1508
|
result && typeof result === "object" && "inputTokens" in result
|
|
@@ -1483,13 +1521,14 @@ export async function withRotation<T>(
|
|
|
1483
1521
|
inTokens || outTokens ? ` inTokens=${inTokens} outTokens=${outTokens}` : "";
|
|
1484
1522
|
logRequestEnd(response.status, `endpoint=${endpoint}${ttfbInfo}${tokensInfo}`);
|
|
1485
1523
|
if (shouldRotate) {
|
|
1486
|
-
await rotator.rotateToNext(model, account, providerId);
|
|
1524
|
+
await rotator.rotateToNext(model, account, providerId, autoScope);
|
|
1487
1525
|
}
|
|
1488
1526
|
return { ok: true, result, endpoint, context };
|
|
1489
1527
|
} catch (err) {
|
|
1490
1528
|
if (signal?.aborted) {
|
|
1491
1529
|
return { ok: false, status: 499, errorText: "Client closed request" };
|
|
1492
1530
|
}
|
|
1531
|
+
if (accessHttpStatus === null || accessHttpStatus < 400) observeAccessAttempt(account.config, providerId ?? DEFAULT_PROVIDER, model, originalHeaders, null, "", isFetchTransportError(err));
|
|
1493
1532
|
const formattedError = formatError(err);
|
|
1494
1533
|
log(
|
|
1495
1534
|
`[${label}] Request failed: ${formattedError}`,
|
|
@@ -1905,6 +1944,7 @@ async function handleProxyRequest(
|
|
|
1905
1944
|
});
|
|
1906
1945
|
};
|
|
1907
1946
|
|
|
1947
|
+
let accessHttpStatus: number | null = null;
|
|
1908
1948
|
try {
|
|
1909
1949
|
if (requestIsOff()) {
|
|
1910
1950
|
sendModelOff();
|
|
@@ -1951,6 +1991,7 @@ async function handleProxyRequest(
|
|
|
1951
1991
|
sendNoAccountsAvailable(`${providerId} turned off for ${label}`);
|
|
1952
1992
|
return;
|
|
1953
1993
|
}
|
|
1994
|
+
if (rotator.getConfig?.().modelAccessShadow === true) logAccessPolicyShadow(account.config, provider.id, body.model, flattenHeaders(req.headers));
|
|
1954
1995
|
rotator.recordUpstreamAttempt(account);
|
|
1955
1996
|
const forwarded = await provider.forwardRequest(
|
|
1956
1997
|
account,
|
|
@@ -1959,6 +2000,7 @@ async function handleProxyRequest(
|
|
|
1959
2000
|
clientController.signal,
|
|
1960
2001
|
);
|
|
1961
2002
|
const { response, endpoint } = forwarded;
|
|
2003
|
+
accessHttpStatus = response.status;
|
|
1962
2004
|
const context: RotationAttemptContext = {
|
|
1963
2005
|
account,
|
|
1964
2006
|
label,
|
|
@@ -1976,6 +2018,7 @@ async function handleProxyRequest(
|
|
|
1976
2018
|
selectionReason: body.selectionReason,
|
|
1977
2019
|
};
|
|
1978
2020
|
|
|
2021
|
+
if (!response.ok) observeAccessAttempt(account.config, provider.id, body.model, flattenHeaders(req.headers), response.status);
|
|
1979
2022
|
const action = await classifyUpstreamResponse(
|
|
1980
2023
|
response,
|
|
1981
2024
|
endpoint,
|
|
@@ -1986,6 +2029,7 @@ async function handleProxyRequest(
|
|
|
1986
2029
|
);
|
|
1987
2030
|
|
|
1988
2031
|
if (action.kind !== "success") {
|
|
2032
|
+
observeAccessAttempt(account.config, provider.id, body.model, flattenHeaders(req.headers), response.status, action.errorText);
|
|
1989
2033
|
const decision = await handleUpstreamAccountAction({
|
|
1990
2034
|
action,
|
|
1991
2035
|
provider,
|
|
@@ -2048,6 +2092,7 @@ async function handleProxyRequest(
|
|
|
2048
2092
|
const totalMs = Date.now() - requestStartMs;
|
|
2049
2093
|
const ttfbMs = usage?.firstByteMs ?? totalMs;
|
|
2050
2094
|
const outcomeStatus = usage?.streamError ? 502 : response.status;
|
|
2095
|
+
observeAccessAttempt(account.config, provider.id, body.model, flattenHeaders(req.headers), response.ok ? outcomeStatus : response.status);
|
|
2051
2096
|
rotator.recordLatency(body.displayModel || body.model, ttfbMs, totalMs);
|
|
2052
2097
|
logRequestEnd(outcomeStatus, `ttfbMs=${ttfbMs} inTokens=${usage?.inputTokens ?? 0} outTokens=${usage?.outputTokens ?? 0} endpoint=${endpoint}`);
|
|
2053
2098
|
rotator.recordRequestLog({
|
|
@@ -2098,6 +2143,7 @@ async function handleProxyRequest(
|
|
|
2098
2143
|
return;
|
|
2099
2144
|
} catch (err) {
|
|
2100
2145
|
if (clientController.signal.aborted || res.destroyed) return;
|
|
2146
|
+
if (accessHttpStatus === null || accessHttpStatus < 400) observeAccessAttempt(account.config, providerId, body.model, flattenHeaders(req.headers), null, "", isFetchTransportError(err));
|
|
2101
2147
|
const formattedError = formatError(err);
|
|
2102
2148
|
proxyLog(
|
|
2103
2149
|
`[${label}] Request failed: ${formattedError}`,
|
|
@@ -2331,11 +2377,22 @@ export function startProxy(
|
|
|
2331
2377
|
return write;
|
|
2332
2378
|
};
|
|
2333
2379
|
|
|
2380
|
+
const usageLimits = createUsageLimitsHandler(() => liveHub.snapshot().overview);
|
|
2334
2381
|
const server = createServer((req, res) => {
|
|
2335
2382
|
const method = req.method?.toUpperCase();
|
|
2336
2383
|
const url = req.url || "";
|
|
2337
2384
|
const pathname = url.split("?")[0];
|
|
2338
2385
|
|
|
2386
|
+
if (pathname === USAGE_LIMITS_PATH) {
|
|
2387
|
+
void usageLimits(req, res);
|
|
2388
|
+
return;
|
|
2389
|
+
}
|
|
2390
|
+
if (carriesUsageReadToken(req)) {
|
|
2391
|
+
res.writeHead(403, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
2392
|
+
res.end('{"error":"read_credential_scope"}');
|
|
2393
|
+
return;
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2339
2396
|
// CORS headers for API consumers (e.g. MindWhisperAI, local frontends)
|
|
2340
2397
|
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
2341
2398
|
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
|
|
@@ -2465,6 +2522,24 @@ export function startProxy(
|
|
|
2465
2522
|
return;
|
|
2466
2523
|
}
|
|
2467
2524
|
|
|
2525
|
+
if (method === "POST" && pathname === "/api/model-access/probe") {
|
|
2526
|
+
if (!requireAdmin(req, res)) return;
|
|
2527
|
+
void serveAccessProbe(req, res, rotator);
|
|
2528
|
+
return;
|
|
2529
|
+
}
|
|
2530
|
+
|
|
2531
|
+
if (method === "PUT" && pathname === "/api/model-access/plan") {
|
|
2532
|
+
if (!requireAdmin(req, res)) return;
|
|
2533
|
+
void serveProviderPlanApi(req, res, rotator.getConfig());
|
|
2534
|
+
return;
|
|
2535
|
+
}
|
|
2536
|
+
|
|
2537
|
+
if (method === "GET" && pathname === "/api/model-access") {
|
|
2538
|
+
if (!requireAdmin(req, res)) return;
|
|
2539
|
+
serveModelAccessApi(res, rotator.getConfig(), new URL(req.url ?? "/", "http://localhost").searchParams);
|
|
2540
|
+
return;
|
|
2541
|
+
}
|
|
2542
|
+
|
|
2468
2543
|
if (method === "GET" && pathname === "/api/status") {
|
|
2469
2544
|
if (!requireAdmin(req, res)) return;
|
|
2470
2545
|
serveStatusApi(res, rotator);
|
|
@@ -2773,6 +2848,35 @@ export function startProxy(
|
|
|
2773
2848
|
return;
|
|
2774
2849
|
}
|
|
2775
2850
|
|
|
2851
|
+
if (method === "GET" && pathname === "/api/playground/config") {
|
|
2852
|
+
if (!requireAdmin(req, res)) return;
|
|
2853
|
+
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
2854
|
+
res.end(JSON.stringify({ maxBodyBytes: getMaxBodyBytes() }));
|
|
2855
|
+
return;
|
|
2856
|
+
}
|
|
2857
|
+
|
|
2858
|
+
if (method === "POST" && pathname === "/api/playground/audio/transcriptions") {
|
|
2859
|
+
void handlePlaygroundAudioTranscriptions(req, res, rotator).catch((err) => {
|
|
2860
|
+
log(`Playground audio error: ${err}`, rotator, "error");
|
|
2861
|
+
if (!res.headersSent) {
|
|
2862
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2863
|
+
res.end(JSON.stringify({ error: { message: "Internal transcription error", type: "server_error" } }));
|
|
2864
|
+
} else res.destroy();
|
|
2865
|
+
});
|
|
2866
|
+
return;
|
|
2867
|
+
}
|
|
2868
|
+
|
|
2869
|
+
if (method === "POST" && pathname === "/api/playground/chat/completions") {
|
|
2870
|
+
void handlePlaygroundChatCompletions(req, res, rotator).catch((err) => {
|
|
2871
|
+
log(`Playground compat error: ${err}`, rotator, "error");
|
|
2872
|
+
if (!res.headersSent) {
|
|
2873
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2874
|
+
res.end(JSON.stringify({ error: { message: "Internal playground error", type: "server_error" } }));
|
|
2875
|
+
} else res.destroy();
|
|
2876
|
+
});
|
|
2877
|
+
return;
|
|
2878
|
+
}
|
|
2879
|
+
|
|
2776
2880
|
// OpenAI-compatible adapter route (additive; does not affect native v1internal route)
|
|
2777
2881
|
if (method === "GET" && pathname === "/v1/models") {
|
|
2778
2882
|
serveOpenAIModels(res, rotator);
|
|
@@ -2946,6 +3050,10 @@ export function startProxy(
|
|
|
2946
3050
|
const serverClosing = new AbortController();
|
|
2947
3051
|
|
|
2948
3052
|
server.on("upgrade", (req, socket) => {
|
|
3053
|
+
if (carriesUsageReadToken(req)) {
|
|
3054
|
+
socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
|
|
3055
|
+
return;
|
|
3056
|
+
}
|
|
2949
3057
|
const url = req.url || "";
|
|
2950
3058
|
const pathname = url.split("?")[0];
|
|
2951
3059
|
if (
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ModelQuota, QuotaObservation } from "./types.js";
|
|
2
|
+
|
|
3
|
+
/** Pure annotation; preserves all router-facing values. Call only for fresh data. */
|
|
4
|
+
export function observeQuota(
|
|
5
|
+
quota: Pick<ModelQuota, "percentRemaining" | "resetTime">,
|
|
6
|
+
observedAt: number,
|
|
7
|
+
percentageSource: QuotaObservation["percentageSource"],
|
|
8
|
+
resetSource: QuotaObservation["resetSource"],
|
|
9
|
+
): QuotaObservation {
|
|
10
|
+
const known = percentageSource !== "unknown" && Number.isFinite(quota.percentRemaining)
|
|
11
|
+
&& quota.percentRemaining >= 0 && quota.percentRemaining <= 100;
|
|
12
|
+
return {
|
|
13
|
+
observedAt,
|
|
14
|
+
percentageSource: known ? percentageSource : "unknown",
|
|
15
|
+
remainingPercent: known ? quota.percentRemaining : null,
|
|
16
|
+
resetSource: quota.resetTime && Number.isFinite(Date.parse(quota.resetTime)) ? resetSource : "unknown",
|
|
17
|
+
resetAt: quota.resetTime && Number.isFinite(Date.parse(quota.resetTime)) ? quota.resetTime : null,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** No global poll timestamp fallback, including for restored legacy rows. */
|
|
22
|
+
export function quotaFreshness(quota: ModelQuota, now: number, maxAgeMs: number): "fresh" | "stale" | "unknown" {
|
|
23
|
+
const at = quota.observation?.observedAt;
|
|
24
|
+
if (!Number.isFinite(at) || !at || at > now || maxAgeMs < 0) return "unknown";
|
|
25
|
+
return now - at > maxAgeMs ? "stale" : "fresh";
|
|
26
|
+
}
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
// Model-first view of the fleet: one row per quota pool (Claude, Gemini,
|
|
2
|
+
// Codex, Ollama session/weekly, …) instead of one card per account.
|
|
3
|
+
|
|
4
|
+
import { quotaFreshness } from "./quota-observation.js";
|
|
5
|
+
import type { AccountTier, ModelQuota } from "./types.js";
|
|
6
|
+
import type {
|
|
7
|
+
DashboardAccount,
|
|
8
|
+
DashboardOverview,
|
|
9
|
+
DashboardRoutingAccount,
|
|
10
|
+
DashboardRoutingDiagnostics,
|
|
11
|
+
} from "./dashboard-types.js";
|
|
12
|
+
import { isOutOfService, providerRank, providerIds, quotaProvider } from "./web/lib/status.js";
|
|
13
|
+
|
|
14
|
+
/** Rough requests per full quota window, used only to weight pooled capacity. */
|
|
15
|
+
const TIER_CAPACITY: Record<string, number> = {
|
|
16
|
+
ultra: 2000,
|
|
17
|
+
max: 2000,
|
|
18
|
+
team: 1500,
|
|
19
|
+
pro: 1500,
|
|
20
|
+
plus: 1000,
|
|
21
|
+
free: 250,
|
|
22
|
+
unknown: 250,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export function tierWeight(tier: AccountTier | string | undefined): number {
|
|
26
|
+
return TIER_CAPACITY[String(tier || "unknown")] ?? 250;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export type PoolState = "ok" | "low" | "empty" | "blocked";
|
|
30
|
+
|
|
31
|
+
export interface PoolMember {
|
|
32
|
+
account: DashboardAccount;
|
|
33
|
+
quota: ModelQuota;
|
|
34
|
+
diagnostic: DashboardRoutingAccount | null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ModelPool {
|
|
38
|
+
key: string;
|
|
39
|
+
/** Collision-safe observability identity; key remains the router's model key. */
|
|
40
|
+
id: string;
|
|
41
|
+
observedCapacity: number | null;
|
|
42
|
+
quotaCoverage: { knownAccounts: number; totalAccounts: number };
|
|
43
|
+
partialObservation: {
|
|
44
|
+
remainingPercent: number;
|
|
45
|
+
accountsWithQuota: number;
|
|
46
|
+
percentageBasis: "tier-estimate" | "included-credits";
|
|
47
|
+
observedAt: number | null;
|
|
48
|
+
freshness: "fresh" | "stale" | "unknown";
|
|
49
|
+
} | null;
|
|
50
|
+
catalogAccessible: boolean | null;
|
|
51
|
+
observedWithQuota: number | null;
|
|
52
|
+
eligibleNow: number | null;
|
|
53
|
+
observedAt: number | null;
|
|
54
|
+
freshness: "fresh" | "stale" | "unknown";
|
|
55
|
+
capacityBasis: "tier-estimate" | "included-credits" | "unknown";
|
|
56
|
+
resetBasis: "reported" | "estimated" | "unknown";
|
|
57
|
+
observedNextResetAt: number | null;
|
|
58
|
+
name: string;
|
|
59
|
+
provider: string;
|
|
60
|
+
/** In-service accounts that carry this pool. */
|
|
61
|
+
members: PoolMember[];
|
|
62
|
+
/** Members with quota left. */
|
|
63
|
+
withQuota: number;
|
|
64
|
+
/** Remaining included quota, weighted by credit allowance or account tier, 0–100. */
|
|
65
|
+
capacity: number;
|
|
66
|
+
/** Actual included credits, summed across in-service accounts. */
|
|
67
|
+
credits: ModelQuota["credits"] | null;
|
|
68
|
+
/** The account routing this pool now; null before its first request or after it stops being routable. */
|
|
69
|
+
serving: DashboardAccount | null;
|
|
70
|
+
/** Eligible accounts after `serving`, the policy's pick first. */
|
|
71
|
+
nextUp: DashboardAccount[];
|
|
72
|
+
nextResetAt: number | null;
|
|
73
|
+
/** Requests per hour over the last hour (estimate). */
|
|
74
|
+
burnPerHour: number;
|
|
75
|
+
/** Hours until the pool runs dry at the current burn; null when idle. */
|
|
76
|
+
hoursLeft: number | null;
|
|
77
|
+
breakerUntil: number | null;
|
|
78
|
+
diagnostics: DashboardRoutingDiagnostics | null;
|
|
79
|
+
state: PoolState;
|
|
80
|
+
/** Why nothing is serving, when that is the case. */
|
|
81
|
+
blockedReason: string | null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Map a request model id to the quota pool it draws from (best effort). */
|
|
85
|
+
export function poolKeyForModel(model: string): string {
|
|
86
|
+
const lower = model.toLowerCase();
|
|
87
|
+
if (lower === "big-pickle" || lower.endsWith("-free")) return "opencode-zen";
|
|
88
|
+
if (lower.includes("claude") || lower.startsWith("gpt-oss-120b")) return "claude";
|
|
89
|
+
if (lower.includes("gemini")) return "gemini";
|
|
90
|
+
if (/^gpt-\d/.test(lower) || lower.includes("codex")) return "openai-codex";
|
|
91
|
+
return "session";
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function isRollingFullWindow(quota: ModelQuota, remaining: number): boolean {
|
|
95
|
+
// A pool at 100% whose reset is exactly one window away is a rolling
|
|
96
|
+
// window that has not started; its "reset" is not a real event.
|
|
97
|
+
if (quota.percentRemaining !== 100) return false;
|
|
98
|
+
const tolerance = 10 * 60_000;
|
|
99
|
+
return (
|
|
100
|
+
Math.abs(remaining - 5 * 3_600_000) < tolerance ||
|
|
101
|
+
Math.abs(remaining - 7 * 86_400_000) < tolerance
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
/** Shared dashboard/future API calculation; tier weights are relative estimates. */
|
|
107
|
+
export function pooledCapacity(members: PoolMember[]): number {
|
|
108
|
+
let weighted = 0;
|
|
109
|
+
let weightTotal = 0;
|
|
110
|
+
let balance = 0;
|
|
111
|
+
let allowance = 0;
|
|
112
|
+
for (const { account, quota } of members) {
|
|
113
|
+
const weight = quota.credits?.allowanceUsd ?? tierWeight(account.tier);
|
|
114
|
+
weighted += Math.max(0, Math.min(100, quota.percentRemaining || 0)) * weight;
|
|
115
|
+
weightTotal += weight;
|
|
116
|
+
balance += quota.credits?.balanceUsd ?? 0;
|
|
117
|
+
allowance += quota.credits?.allowanceUsd ?? 0;
|
|
118
|
+
}
|
|
119
|
+
return allowance > 0 ? Math.max(0, Math.min(100, Math.round(balance / allowance * 100)))
|
|
120
|
+
: weightTotal > 0 ? Math.round(weighted / weightTotal) : 0;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function buildPools(overview: DashboardOverview, now: number): ModelPool[] {
|
|
124
|
+
const byKey = new Map<string, { name: string; provider: string; members: PoolMember[] }>();
|
|
125
|
+
|
|
126
|
+
for (const account of overview.accounts) {
|
|
127
|
+
for (const quota of account.quota || []) {
|
|
128
|
+
const identity = JSON.stringify([quotaProvider(quota), quota.modelKey]);
|
|
129
|
+
let pool = byKey.get(identity);
|
|
130
|
+
if (!pool) {
|
|
131
|
+
pool = {
|
|
132
|
+
name: quota.displayName || quota.modelKey,
|
|
133
|
+
provider: quotaProvider(quota),
|
|
134
|
+
members: [],
|
|
135
|
+
};
|
|
136
|
+
byKey.set(identity, pool);
|
|
137
|
+
}
|
|
138
|
+
if (isOutOfService(account) || account.disabledProviders?.includes(quotaProvider(quota))) continue;
|
|
139
|
+
const diag = overview.routingDiagnostics[quota.modelKey];
|
|
140
|
+
pool.members.push({
|
|
141
|
+
account,
|
|
142
|
+
quota,
|
|
143
|
+
diagnostic: diag?.accounts.find((d) => d.id && account.id ? d.id === account.id : d.email === account.email) ?? null,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const burnByPool: Record<string, number> = {};
|
|
149
|
+
for (const [model, requests] of Object.entries(overview.recentRequestsByModel || {})) {
|
|
150
|
+
const key = poolKeyForModel(model);
|
|
151
|
+
burnByPool[key] = (burnByPool[key] || 0) + requests;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const accountByEmail = new Map(overview.accounts.map((a) => [a.email, a]));
|
|
155
|
+
const pools: ModelPool[] = [];
|
|
156
|
+
|
|
157
|
+
for (const [id, pool] of byKey) {
|
|
158
|
+
const key = (JSON.parse(id) as [string, string])[1];
|
|
159
|
+
const diagnostics = overview.routingDiagnostics[key] ?? null;
|
|
160
|
+
let remainingRequests = 0;
|
|
161
|
+
let withQuota = 0;
|
|
162
|
+
let nextResetAt: number | null = null;
|
|
163
|
+
let credits: ModelQuota["credits"] | null = null;
|
|
164
|
+
|
|
165
|
+
for (const member of pool.members) {
|
|
166
|
+
const credit = member.quota.credits;
|
|
167
|
+
const weight = credit?.allowanceUsd ?? tierWeight(member.account.tier);
|
|
168
|
+
if (credit) {
|
|
169
|
+
credits ??= { balanceUsd: 0, allowanceUsd: 0, purchasedUsd: 0 };
|
|
170
|
+
credits.balanceUsd += credit.balanceUsd;
|
|
171
|
+
credits.allowanceUsd += credit.allowanceUsd;
|
|
172
|
+
credits.purchasedUsd += credit.purchasedUsd;
|
|
173
|
+
}
|
|
174
|
+
const pct = Math.max(0, Math.min(100, member.quota.percentRemaining || 0));
|
|
175
|
+
remainingRequests += (pct / 100) * weight;
|
|
176
|
+
if (pct > 0 || (credit?.purchasedUsd ?? 0) > 0) withQuota += 1;
|
|
177
|
+
if (member.quota.resetTime && member.quota.timerType !== "fresh") {
|
|
178
|
+
const resetAt = Date.parse(member.quota.resetTime);
|
|
179
|
+
const remaining = resetAt - now;
|
|
180
|
+
if (remaining > 0 && !isRollingFullWindow(member.quota, remaining)) {
|
|
181
|
+
if (nextResetAt === null || resetAt < nextResetAt) nextResetAt = resetAt;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// The account routing this pool right now, the same one whose status reads
|
|
187
|
+
// Serving. The policy's pick for the next rotation leads nextUp.
|
|
188
|
+
const servingEmail = overview.activeAccounts[key] ?? null;
|
|
189
|
+
const serving = servingEmail ? accountByEmail.get(servingEmail) ?? null : null;
|
|
190
|
+
const selectedEmail = diagnostics?.selectedEmail ?? null;
|
|
191
|
+
|
|
192
|
+
const nextUp = (diagnostics?.accounts ?? [])
|
|
193
|
+
.filter((d) => !d.rejectedReason && d.email !== servingEmail)
|
|
194
|
+
.sort(
|
|
195
|
+
(a, b) =>
|
|
196
|
+
Number(b.email === selectedEmail) - Number(a.email === selectedEmail) ||
|
|
197
|
+
(b.score ?? -Infinity) - (a.score ?? -Infinity),
|
|
198
|
+
)
|
|
199
|
+
.map((d) => accountByEmail.get(d.email))
|
|
200
|
+
.filter((a): a is DashboardAccount => Boolean(a))
|
|
201
|
+
.slice(0, 2);
|
|
202
|
+
|
|
203
|
+
const capacity = pooledCapacity(pool.members);
|
|
204
|
+
const availableCapacity = credits && credits.allowanceUsd > 0
|
|
205
|
+
? (credits.balanceUsd + credits.purchasedUsd) / credits.allowanceUsd * 100
|
|
206
|
+
: capacity;
|
|
207
|
+
const burnPerHour = burnByPool[key] || 0;
|
|
208
|
+
const hoursLeft = !credits && burnPerHour > 0 ? remainingRequests / burnPerHour : null;
|
|
209
|
+
const breaker = overview.circuitBreakers.model[key];
|
|
210
|
+
const breakerUntil = breaker && breaker > now ? breaker : null;
|
|
211
|
+
|
|
212
|
+
let state: PoolState = "ok";
|
|
213
|
+
if (breakerUntil || (pool.members.length > 0 && withQuota === 0)) state = "blocked";
|
|
214
|
+
else if (diagnostics && !diagnostics.selectedEmail && diagnostics.availableCandidates === 0)
|
|
215
|
+
state = "blocked";
|
|
216
|
+
else if (availableCapacity === 0) state = "empty";
|
|
217
|
+
else if (availableCapacity < 20) state = "low";
|
|
218
|
+
|
|
219
|
+
const measured = pool.members.filter(({ quota }) => {
|
|
220
|
+
const observation = quota.observation;
|
|
221
|
+
return observation && ["reported", "derived", "estimated"].includes(observation.percentageSource)
|
|
222
|
+
&& observation.remainingPercent !== null && Number.isFinite(observation.remainingPercent)
|
|
223
|
+
&& observation.remainingPercent >= 0 && observation.remainingPercent <= 100;
|
|
224
|
+
});
|
|
225
|
+
const known = pool.members.length > 0 && measured.length === pool.members.length;
|
|
226
|
+
const observedMembers = measured.map(member => ({ ...member, quota: {
|
|
227
|
+
...member.quota, percentRemaining: member.quota.observation!.remainingPercent!,
|
|
228
|
+
} }));
|
|
229
|
+
const partialAges = measured.map(({ quota }) => quotaFreshness(quota, now, 15 * 60_000));
|
|
230
|
+
const partialFreshness = partialAges.includes("unknown") ? "unknown" as const
|
|
231
|
+
: partialAges.includes("stale") ? "stale" as const : "fresh" as const;
|
|
232
|
+
const partialObservation: ModelPool["partialObservation"] = measured.length > 0 && !known ? {
|
|
233
|
+
remainingPercent: pooledCapacity(observedMembers),
|
|
234
|
+
accountsWithQuota: observedMembers.filter(({ quota }) => quota.percentRemaining > 0 || (quota.credits?.purchasedUsd ?? 0) > 0).length,
|
|
235
|
+
percentageBasis: measured.some(({ quota }) => quota.credits) ? "included-credits" : "tier-estimate",
|
|
236
|
+
observedAt: partialFreshness === "unknown" ? null : Math.min(...measured.map(({ quota }) => quota.observation!.observedAt)),
|
|
237
|
+
freshness: partialFreshness,
|
|
238
|
+
} : null;
|
|
239
|
+
const ages = pool.members.map(({ quota }) => quotaFreshness(quota, now, 15 * 60_000));
|
|
240
|
+
const freshness = ages.length === 0 || ages.includes("unknown") ? "unknown"
|
|
241
|
+
: ages.includes("stale") ? "stale" : "fresh";
|
|
242
|
+
const observedAt = freshness === "unknown" ? null
|
|
243
|
+
: Math.min(...pool.members.map(({ quota }) => quota.observation!.observedAt));
|
|
244
|
+
const resetMembers = pool.members.filter(({ quota }) => quota.observation?.resetAt &&
|
|
245
|
+
Date.parse(quota.observation.resetAt) > now);
|
|
246
|
+
const observedNextResetAt = resetMembers.length ? Math.min(...resetMembers.map(({ quota }) =>
|
|
247
|
+
Date.parse(quota.observation!.resetAt!))) : null;
|
|
248
|
+
const selectedResets = resetMembers.filter(({ quota }) => Date.parse(quota.observation!.resetAt!) === observedNextResetAt);
|
|
249
|
+
const collision = [...byKey.keys()].filter((identity) => (JSON.parse(identity) as string[])[1] === key).length > 1;
|
|
250
|
+
const eligibleNow = !diagnostics || collision || pool.members.some(member => !member.diagnostic) ? null : pool.members.filter(({ diagnostic }) =>
|
|
251
|
+
diagnostic && !diagnostic.rejectedReason).length;
|
|
252
|
+
pools.push({
|
|
253
|
+
key,
|
|
254
|
+
id,
|
|
255
|
+
catalogAccessible: pool.members.some(({ quota }) => quota.observation?.catalogAccessible === true) ? true : null,
|
|
256
|
+
quotaCoverage: { knownAccounts: measured.length, totalAccounts: pool.members.length },
|
|
257
|
+
partialObservation,
|
|
258
|
+
observedCapacity: known ? pooledCapacity(observedMembers) : null,
|
|
259
|
+
observedWithQuota: known ? observedMembers.filter(({ quota }) => quota.percentRemaining > 0 || (quota.credits?.purchasedUsd ?? 0) > 0).length : null,
|
|
260
|
+
eligibleNow,
|
|
261
|
+
observedAt,
|
|
262
|
+
freshness,
|
|
263
|
+
capacityBasis: !known ? "unknown" : credits ? "included-credits" : "tier-estimate",
|
|
264
|
+
resetBasis: selectedResets.length === 0 ? "unknown" : selectedResets.some(({ quota }) => quota.observation!.resetSource === "estimated") ? "estimated" : selectedResets.every(({ quota }) => quota.observation!.resetSource === "reported") ? "reported" : "unknown",
|
|
265
|
+
observedNextResetAt,
|
|
266
|
+
name: pool.name,
|
|
267
|
+
provider: pool.provider,
|
|
268
|
+
members: pool.members,
|
|
269
|
+
withQuota,
|
|
270
|
+
capacity,
|
|
271
|
+
credits,
|
|
272
|
+
serving,
|
|
273
|
+
nextUp,
|
|
274
|
+
nextResetAt,
|
|
275
|
+
burnPerHour,
|
|
276
|
+
hoursLeft,
|
|
277
|
+
breakerUntil,
|
|
278
|
+
diagnostics,
|
|
279
|
+
state,
|
|
280
|
+
blockedReason:
|
|
281
|
+
state === "blocked"
|
|
282
|
+
? breakerUntil
|
|
283
|
+
? "Circuit breaker open after repeated provider rate limits."
|
|
284
|
+
: diagnostics?.reason || "No account has quota left in this pool."
|
|
285
|
+
: null,
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
return pools.sort(
|
|
290
|
+
(a, b) =>
|
|
291
|
+
providerRank(a.provider) - providerRank(b.provider) ||
|
|
292
|
+
a.name.localeCompare(b.name),
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export interface ProviderGroup {
|
|
297
|
+
provider: string;
|
|
298
|
+
accounts: DashboardAccount[];
|
|
299
|
+
pools: ModelPool[];
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Connected providers remain visible even before their first successful quota poll. */
|
|
303
|
+
export function buildProviderGroups(overview: DashboardOverview, now: number): ProviderGroup[] {
|
|
304
|
+
const groups = new Map<string, ProviderGroup>();
|
|
305
|
+
const ensure = (provider: string): ProviderGroup => {
|
|
306
|
+
let group = groups.get(provider);
|
|
307
|
+
if (!group) {
|
|
308
|
+
group = { provider, accounts: [], pools: [] };
|
|
309
|
+
groups.set(provider, group);
|
|
310
|
+
}
|
|
311
|
+
return group;
|
|
312
|
+
};
|
|
313
|
+
for (const account of overview.accounts) {
|
|
314
|
+
const providers = new Set([
|
|
315
|
+
...providerIds(account),
|
|
316
|
+
...account.quota.map(quotaProvider),
|
|
317
|
+
]);
|
|
318
|
+
for (const provider of providers) ensure(provider).accounts.push(account);
|
|
319
|
+
}
|
|
320
|
+
for (const pool of buildPools(overview, now)) ensure(pool.provider).pools.push(pool);
|
|
321
|
+
return [...groups.values()].sort((a, b) => providerRank(a.provider) - providerRank(b.provider));
|
|
322
|
+
}
|