tuxevil-rotator 4.3.0 → 4.4.1

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +5 -2
  3. package/package.json +5 -1
  4. package/src/access-evidence.ts +153 -0
  5. package/src/access-probe.ts +85 -0
  6. package/src/admin-auth.ts +4 -1
  7. package/src/auto-access-shadow.ts +11 -0
  8. package/src/auto-model-access.ts +185 -0
  9. package/src/auto-output-health.ts +12 -0
  10. package/src/auto-routing-evaluation.ts +80 -0
  11. package/src/auto-routing-quality.ts +308 -0
  12. package/src/auto-routing.ts +403 -26
  13. package/src/compat.ts +223 -36
  14. package/src/compression/index.ts +6 -6
  15. package/src/compression/lite.ts +3 -9
  16. package/src/compression/rtk/index.ts +0 -3
  17. package/src/config-defaults.ts +7 -0
  18. package/src/dashboard.ts +5 -0
  19. package/src/db-store.ts +10 -0
  20. package/src/index.ts +2 -0
  21. package/src/model-access-api.ts +74 -0
  22. package/src/model-access.ts +56 -0
  23. package/src/ollama-output-gate.ts +18 -0
  24. package/src/onboarding.ts +1 -1
  25. package/src/provider-catalog-evidence.ts +26 -0
  26. package/src/providers/google-antigravity/dynamic-catalog.ts +8 -0
  27. package/src/providers/google-antigravity/quota.ts +3 -0
  28. package/src/providers/ollama/context-window.ts +13 -0
  29. package/src/providers/ollama/quota.ts +4 -0
  30. package/src/providers/ollama/translators.ts +19 -2
  31. package/src/providers/openai-codex/compat.ts +5 -1
  32. package/src/providers/openai-codex/credentials.ts +22 -6
  33. package/src/providers/openai-codex/index.ts +9 -1
  34. package/src/providers/openai-codex/quota.ts +19 -6
  35. package/src/providers/opencode-zen/forward.ts +1 -1
  36. package/src/providers/opencode-zen/quota.ts +2 -0
  37. package/src/proxy.ts +78 -3
  38. package/src/quota-observation.ts +26 -0
  39. package/src/quota-pools.ts +322 -0
  40. package/src/rotator.ts +151 -38
  41. package/src/settings-repository.ts +1 -0
  42. package/src/telemetry.ts +3 -1
  43. package/src/types.ts +28 -0
  44. package/src/usage-limits-auth.ts +24 -0
  45. package/src/usage-limits.ts +148 -0
  46. package/src/validators.ts +26 -0
  47. package/src/web/components/icons.tsx +15 -0
  48. package/src/web/components/overlays.tsx +4 -0
  49. package/src/web/components/ui.tsx +9 -9
  50. package/src/web/lib/playground.ts +35 -0
  51. package/src/web/lib/pool-navigation.ts +4 -0
  52. package/src/web/lib/pools.ts +2 -243
  53. package/src/web/pages/AccountDetail.tsx +2 -1
  54. package/src/web/pages/ModelAccess.tsx +88 -0
  55. package/src/web/pages/Models.tsx +2 -0
  56. package/src/web/pages/Overview.tsx +26 -9
  57. package/src/web/pages/Playground.tsx +1132 -551
  58. package/src/web/pages/Transcription.tsx +304 -170
  59. package/src/web/state/api.ts +3 -0
  60. package/src/web/styles/app.css +501 -45
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 {
@@ -1265,6 +1270,7 @@ export async function withRotation<T>(
1265
1270
  context: RotationAttemptContext,
1266
1271
  ) => Promise<T>,
1267
1272
  signal?: AbortSignal,
1273
+ options?: { autoRecovery?: boolean },
1268
1274
  ): Promise<RotationOutcome<T>> {
1269
1275
  // Keep the admission pool and wire protocol stable across async waits and
1270
1276
  // retries, even if provider order or switches change while the request waits.
@@ -1272,6 +1278,9 @@ export async function withRotation<T>(
1272
1278
  ollamaModels: new Set(rotator.getOllamaModels?.() ?? []),
1273
1279
  codexModels: new Set(rotator.getCodexModels?.() ?? []),
1274
1280
  })?.id;
1281
+ const autoScope = body.displayModel?.toLowerCase() === "auto" && providerId
1282
+ ? { providerId, modelId: model }
1283
+ : undefined;
1275
1284
  const modelQuotaFamily = resolveQuotaModelKey(model) ??
1276
1285
  resolveQuotaModelKey(applyModelAlias(model));
1277
1286
  if (
@@ -1329,7 +1338,7 @@ export async function withRotation<T>(
1329
1338
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1330
1339
  if (requestIsOff()) return modelOffOutcome();
1331
1340
  const admissionStartedMs = Date.now();
1332
- const account = await rotator.getActiveAccount(model, signal, providerId);
1341
+ const account = await rotator.getActiveAccount(model, signal, providerId, autoScope);
1333
1342
  if (!account) {
1334
1343
  if (signal?.aborted) {
1335
1344
  return { ok: false, status: 499, errorText: "Client closed request" };
@@ -1358,7 +1367,7 @@ export async function withRotation<T>(
1358
1367
  };
1359
1368
  const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
1360
1369
  releaseCurrentAccount();
1361
- const nextAccount = await rotator.rotateToNext(model, account, providerId);
1370
+ const nextAccount = await rotator.rotateToNext(model, account, providerId, autoScope);
1362
1371
  return nextAccount;
1363
1372
  };
1364
1373
  const logRequestEnd = (status: string | number, extra = ""): void => {
@@ -1374,6 +1383,7 @@ export async function withRotation<T>(
1374
1383
  rotator,
1375
1384
  );
1376
1385
 
1386
+ let accessHttpStatus: number | null = null;
1377
1387
  try {
1378
1388
  const provider = providerAdapterForModel(account, model, rotator, providerId);
1379
1389
  if (requestIsOff(provider.id)) return modelOffOutcome();
@@ -1414,6 +1424,7 @@ export async function withRotation<T>(
1414
1424
  if (attempt < maxRetries) continue;
1415
1425
  return sendNoAccountsAvailable(`${provider.id} turned off for ${label}`);
1416
1426
  }
1427
+ if (rotator.getConfig?.().modelAccessShadow === true) logAccessPolicyShadow(account.config, provider.id, model, originalHeaders);
1417
1428
  rotator.recordUpstreamAttempt(account);
1418
1429
  const forwarded = await provider.forwardRequest(
1419
1430
  account,
@@ -1422,6 +1433,7 @@ export async function withRotation<T>(
1422
1433
  signal,
1423
1434
  );
1424
1435
  const { response, endpoint } = forwarded;
1436
+ accessHttpStatus = response.status;
1425
1437
  const context: RotationAttemptContext = {
1426
1438
  account,
1427
1439
  label,
@@ -1439,6 +1451,26 @@ export async function withRotation<T>(
1439
1451
  selectionReason: body.selectionReason,
1440
1452
  };
1441
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);
1442
1474
  const action = await classifyUpstreamResponse(
1443
1475
  response,
1444
1476
  endpoint,
@@ -1449,6 +1481,7 @@ export async function withRotation<T>(
1449
1481
  );
1450
1482
 
1451
1483
  if (action.kind !== "success") {
1484
+ observeAccessAttempt(account.config, provider.id, model, originalHeaders, response.status, action.errorText);
1452
1485
  const decision = await handleUpstreamAccountAction({
1453
1486
  action,
1454
1487
  provider,
@@ -1469,6 +1502,7 @@ export async function withRotation<T>(
1469
1502
 
1470
1503
  // success
1471
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);
1472
1506
  const shouldRotate = rotator.recordRequest(account, model, providerId);
1473
1507
  const inTokens =
1474
1508
  result && typeof result === "object" && "inputTokens" in result
@@ -1487,13 +1521,14 @@ export async function withRotation<T>(
1487
1521
  inTokens || outTokens ? ` inTokens=${inTokens} outTokens=${outTokens}` : "";
1488
1522
  logRequestEnd(response.status, `endpoint=${endpoint}${ttfbInfo}${tokensInfo}`);
1489
1523
  if (shouldRotate) {
1490
- await rotator.rotateToNext(model, account, providerId);
1524
+ await rotator.rotateToNext(model, account, providerId, autoScope);
1491
1525
  }
1492
1526
  return { ok: true, result, endpoint, context };
1493
1527
  } catch (err) {
1494
1528
  if (signal?.aborted) {
1495
1529
  return { ok: false, status: 499, errorText: "Client closed request" };
1496
1530
  }
1531
+ if (accessHttpStatus === null || accessHttpStatus < 400) observeAccessAttempt(account.config, providerId ?? DEFAULT_PROVIDER, model, originalHeaders, null, "", isFetchTransportError(err));
1497
1532
  const formattedError = formatError(err);
1498
1533
  log(
1499
1534
  `[${label}] Request failed: ${formattedError}`,
@@ -1909,6 +1944,7 @@ async function handleProxyRequest(
1909
1944
  });
1910
1945
  };
1911
1946
 
1947
+ let accessHttpStatus: number | null = null;
1912
1948
  try {
1913
1949
  if (requestIsOff()) {
1914
1950
  sendModelOff();
@@ -1955,6 +1991,7 @@ async function handleProxyRequest(
1955
1991
  sendNoAccountsAvailable(`${providerId} turned off for ${label}`);
1956
1992
  return;
1957
1993
  }
1994
+ if (rotator.getConfig?.().modelAccessShadow === true) logAccessPolicyShadow(account.config, provider.id, body.model, flattenHeaders(req.headers));
1958
1995
  rotator.recordUpstreamAttempt(account);
1959
1996
  const forwarded = await provider.forwardRequest(
1960
1997
  account,
@@ -1963,6 +2000,7 @@ async function handleProxyRequest(
1963
2000
  clientController.signal,
1964
2001
  );
1965
2002
  const { response, endpoint } = forwarded;
2003
+ accessHttpStatus = response.status;
1966
2004
  const context: RotationAttemptContext = {
1967
2005
  account,
1968
2006
  label,
@@ -1980,6 +2018,7 @@ async function handleProxyRequest(
1980
2018
  selectionReason: body.selectionReason,
1981
2019
  };
1982
2020
 
2021
+ if (!response.ok) observeAccessAttempt(account.config, provider.id, body.model, flattenHeaders(req.headers), response.status);
1983
2022
  const action = await classifyUpstreamResponse(
1984
2023
  response,
1985
2024
  endpoint,
@@ -1990,6 +2029,7 @@ async function handleProxyRequest(
1990
2029
  );
1991
2030
 
1992
2031
  if (action.kind !== "success") {
2032
+ observeAccessAttempt(account.config, provider.id, body.model, flattenHeaders(req.headers), response.status, action.errorText);
1993
2033
  const decision = await handleUpstreamAccountAction({
1994
2034
  action,
1995
2035
  provider,
@@ -2052,6 +2092,7 @@ async function handleProxyRequest(
2052
2092
  const totalMs = Date.now() - requestStartMs;
2053
2093
  const ttfbMs = usage?.firstByteMs ?? totalMs;
2054
2094
  const outcomeStatus = usage?.streamError ? 502 : response.status;
2095
+ observeAccessAttempt(account.config, provider.id, body.model, flattenHeaders(req.headers), response.ok ? outcomeStatus : response.status);
2055
2096
  rotator.recordLatency(body.displayModel || body.model, ttfbMs, totalMs);
2056
2097
  logRequestEnd(outcomeStatus, `ttfbMs=${ttfbMs} inTokens=${usage?.inputTokens ?? 0} outTokens=${usage?.outputTokens ?? 0} endpoint=${endpoint}`);
2057
2098
  rotator.recordRequestLog({
@@ -2102,6 +2143,7 @@ async function handleProxyRequest(
2102
2143
  return;
2103
2144
  } catch (err) {
2104
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));
2105
2147
  const formattedError = formatError(err);
2106
2148
  proxyLog(
2107
2149
  `[${label}] Request failed: ${formattedError}`,
@@ -2335,11 +2377,22 @@ export function startProxy(
2335
2377
  return write;
2336
2378
  };
2337
2379
 
2380
+ const usageLimits = createUsageLimitsHandler(() => liveHub.snapshot().overview);
2338
2381
  const server = createServer((req, res) => {
2339
2382
  const method = req.method?.toUpperCase();
2340
2383
  const url = req.url || "";
2341
2384
  const pathname = url.split("?")[0];
2342
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
+
2343
2396
  // CORS headers for API consumers (e.g. MindWhisperAI, local frontends)
2344
2397
  res.setHeader("Access-Control-Allow-Origin", "*");
2345
2398
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
@@ -2469,6 +2522,24 @@ export function startProxy(
2469
2522
  return;
2470
2523
  }
2471
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
+
2472
2543
  if (method === "GET" && pathname === "/api/status") {
2473
2544
  if (!requireAdmin(req, res)) return;
2474
2545
  serveStatusApi(res, rotator);
@@ -2979,6 +3050,10 @@ export function startProxy(
2979
3050
  const serverClosing = new AbortController();
2980
3051
 
2981
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
+ }
2982
3057
  const url = req.url || "";
2983
3058
  const pathname = url.split("?")[0];
2984
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
+ }