tuxevil-rotator 4.0.0 → 4.1.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +6 -1
  3. package/package.json +1 -1
  4. package/src/audio-transcription.ts +44 -4
  5. package/src/compat.ts +196 -222
  6. package/src/config-defaults.ts +5 -0
  7. package/src/dashboard-live.ts +10 -8
  8. package/src/dashboard-types.ts +39 -1
  9. package/src/dashboard.ts +156 -1
  10. package/src/model-catalog-revision.ts +17 -0
  11. package/src/model-catalog.ts +302 -0
  12. package/src/providers/adapter.ts +18 -0
  13. package/src/providers/google-antigravity/catalog.ts +190 -1
  14. package/src/providers/google-antigravity/forward.ts +2 -0
  15. package/src/providers/google-antigravity/index.ts +11 -0
  16. package/src/providers/google-antigravity/translators.ts +4 -0
  17. package/src/providers/ollama/index.ts +11 -1
  18. package/src/providers/ollama/quota-poll-store.ts +22 -1
  19. package/src/providers/ollama/quota.ts +95 -23
  20. package/src/providers/openai-codex/index.ts +18 -2
  21. package/src/providers/opencode-zen/index.ts +11 -2
  22. package/src/proxy.ts +143 -28
  23. package/src/rotator.ts +219 -10
  24. package/src/settings-repository.ts +36 -5
  25. package/src/types.ts +68 -26
  26. package/src/validators.ts +35 -0
  27. package/src/web/app.tsx +4 -0
  28. package/src/web/components/icons.tsx +29 -0
  29. package/src/web/components/ui.tsx +6 -1
  30. package/src/web/lib/accounts.ts +1 -0
  31. package/src/web/lib/attention.ts +12 -0
  32. package/src/web/lib/models.ts +279 -0
  33. package/src/web/lib/pools.ts +53 -9
  34. package/src/web/lib/status.ts +13 -3
  35. package/src/web/nav.ts +1 -0
  36. package/src/web/pages/AccountDetail.tsx +16 -2
  37. package/src/web/pages/Models.tsx +852 -0
  38. package/src/web/pages/Overview.tsx +31 -15
  39. package/src/web/pages/Usage.tsx +3 -3
  40. package/src/web/state/api.ts +18 -0
  41. package/src/web/state/model-catalog.ts +103 -0
  42. package/src/web/state/router.ts +24 -16
  43. package/src/web/state/store.ts +6 -6
  44. package/src/web/styles/app.css +294 -0
package/src/proxy.ts CHANGED
@@ -20,6 +20,13 @@ import {
20
20
  import type { AccountRuntime } from "./types.js";
21
21
  import type { AccountRotator } from "./rotator.js";
22
22
  import { DEFAULT_PROVIDER, getProviderAdapter, getProviderForAccount, findProviderForModel, isKnownProvider } from "./providers/registry.js";
23
+ import {
24
+ isProviderModelOff,
25
+ isRequestOff,
26
+ modelOffMessage,
27
+ routedProviderId,
28
+ type ModelCatalogSource,
29
+ } from "./model-catalog.js";
23
30
  import { isRecord } from "./compat/schema-sanitizer.js";
24
31
  import type { ProviderAdapter, StreamAccumulator } from "./providers/adapter.js";
25
32
  import {
@@ -60,6 +67,7 @@ import {
60
67
  serveGetSpendSummaryApi,
61
68
  serveGetSpendByKeyApi,
62
69
  serveModelsApi,
70
+ serveCatalogApi,
63
71
  serveSessionInfoApi,
64
72
  serveCreateSessionApi,
65
73
  serveDeleteSessionApi,
@@ -106,13 +114,15 @@ import type { FlagEventData } from "./telemetry.js";
106
114
  * models like `minimax-m3`, `kimi-k3`, `glm-5.1` have no tag, and some
107
115
  * Google model aliases do).
108
116
  *
109
- * The rotator is required only when it exposes `getOllamaModels()`; test
110
- * stubs that omit it fall back to the credentials-only dispatch.
117
+ * Ids a provider lists follow the Models page provider order (see
118
+ * model-catalog.ts). The rotator is required only when it exposes
119
+ * `getOllamaModels()`; test stubs that omit it fall back to the
120
+ * credentials-only dispatch.
111
121
  */
112
122
  export function providerAdapterForModel(
113
123
  account: AccountRuntime,
114
124
  model: string | undefined,
115
- rotator?: { getOllamaModels?: () => string[]; getCodexModels?: () => string[] },
125
+ rotator?: ModelCatalogSource,
116
126
  providerHint?: string,
117
127
  ): ProviderAdapter {
118
128
  const creds = account.config.credentials ?? [];
@@ -130,6 +140,8 @@ export function providerAdapterForModel(
130
140
  `Effort routing ${effortRoutingKind} "${model}" matches a live Ollama model; live provider dispatch wins`,
131
141
  );
132
142
  }
143
+ const routed = rotator ? routedProviderId(rotator, model) : null;
144
+ if (routed) return getProviderAdapter(routed);
133
145
  const matched = findProviderForModel(model, context);
134
146
  if (matched) return matched;
135
147
  }
@@ -251,6 +263,10 @@ export interface RequestBody {
251
263
  userAgent?: string;
252
264
  requestId?: string;
253
265
  displayModel?: string;
266
+ /** Concrete model or effort alias before target selection; excludes the auto display label. */
267
+ requestedModel?: string;
268
+ /** Catalog id after effort routing, before upstream aliasing (Antigravity). */
269
+ catalogModel?: string;
254
270
  providerId?: string;
255
271
  selectionMode?: "typesafe" | "deterministic" | "shadow" | "disabled";
256
272
  selectionConfidence?: number;
@@ -1043,7 +1059,21 @@ export async function benchmarkAccount(
1043
1059
  };
1044
1060
  }
1045
1061
 
1046
- const benchmarkSpec = getProviderForAccount(account.config).getBenchmark(account);
1062
+ const benchmarkProvider = getProviderForAccount(account.config);
1063
+ const benchmarkSpec = benchmarkProvider.getBenchmark(account);
1064
+ const turnedOff = (): boolean =>
1065
+ Boolean(rotator.isProviderOffForAccount?.(account, benchmarkProvider.id)) ||
1066
+ isProviderModelOff(rotator, benchmarkProvider.id, benchmarkSpec.body.model);
1067
+ const turnedOffResult: BenchmarkResult = {
1068
+ account: label,
1069
+ status: "skipped",
1070
+ latencyMs: null,
1071
+ ttfbMs: null,
1072
+ outputTokens: null,
1073
+ tokensPerSecond: null,
1074
+ error: `${benchmarkProvider.displayName} is turned off on the Models page`,
1075
+ };
1076
+ if (turnedOff()) return turnedOffResult;
1047
1077
  rotator.startRequest(account, benchmarkSpec.body.model);
1048
1078
  const timeoutController = new AbortController();
1049
1079
  const timeout = setTimeout(
@@ -1057,6 +1087,7 @@ export async function benchmarkAccount(
1057
1087
 
1058
1088
  try {
1059
1089
  await rotator.ensureValidToken(account);
1090
+ if (turnedOff()) return turnedOffResult;
1060
1091
  const forwarded = await providerAdapterForModel(
1061
1092
  account,
1062
1093
  benchmarkSpec.body.model,
@@ -1220,12 +1251,29 @@ export async function withRotation<T>(
1220
1251
  ) => Promise<T>,
1221
1252
  signal?: AbortSignal,
1222
1253
  ): Promise<RotationOutcome<T>> {
1254
+ // Keep the admission pool and wire protocol stable across async waits and
1255
+ // retries, even if provider order or switches change while the request waits.
1256
+ const providerId = body.providerId ?? routedProviderId(rotator, model) ?? findProviderForModel(model, {
1257
+ ollamaModels: new Set(rotator.getOllamaModels?.() ?? []),
1258
+ codexModels: new Set(rotator.getCodexModels?.() ?? []),
1259
+ })?.id;
1260
+ const requestIsOff = (selectedProviderId = providerId): boolean => isRequestOff(rotator, {
1261
+ model,
1262
+ requestedModel: body.requestedModel,
1263
+ catalogModel: body.catalogModel,
1264
+ providerId: selectedProviderId,
1265
+ });
1266
+ const modelOffOutcome = (): RotationOutcome<T> => ({
1267
+ ok: false,
1268
+ status: 404,
1269
+ errorText: modelOffMessage(body.displayModel || model),
1270
+ });
1223
1271
  const sendNoAccountsAvailable = (
1224
1272
  reason: string,
1225
1273
  context?: RotationAttemptContext,
1226
1274
  ): RotationOutcome<T> => {
1227
1275
  log(`[${model}] No healthy account available: ${reason}`, rotator, "warn");
1228
- const retryAfterMs = rotator.getRetryAfterMs(model, body.providerId);
1276
+ const retryAfterMs = rotator.getRetryAfterMs(model, providerId);
1229
1277
  const contextFields = context
1230
1278
  ? { context, totalMs: Date.now() - context.requestStartMs }
1231
1279
  : {};
@@ -1250,17 +1298,21 @@ export async function withRotation<T>(
1250
1298
  const maxAttempts = maxRetries + 1;
1251
1299
 
1252
1300
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1301
+ if (requestIsOff()) return modelOffOutcome();
1253
1302
  const admissionStartedMs = Date.now();
1254
- const account = await rotator.getActiveAccount(model, signal, body.providerId);
1303
+ const account = await rotator.getActiveAccount(model, signal, providerId);
1255
1304
  if (!account) {
1256
1305
  if (signal?.aborted) {
1257
1306
  return { ok: false, status: 499, errorText: "Client closed request" };
1258
1307
  }
1308
+ if (requestIsOff()) return modelOffOutcome();
1259
1309
  return sendNoAccountsAvailable("rotation returned no available account");
1260
1310
  }
1261
1311
 
1262
1312
  const label = account.config.label || account.config.email;
1263
- const modelKey = routingModelKey(rotator, model, body.providerId);
1313
+ // Release this admission's pool even if later settings or catalog updates
1314
+ // change routing while token validation or the upstream request awaits.
1315
+ const modelKey = routingModelKey(rotator, model, providerId);
1264
1316
  const displayModelKey = observedModelKey(
1265
1317
  rotator,
1266
1318
  body.displayModel || model,
@@ -1277,7 +1329,7 @@ export async function withRotation<T>(
1277
1329
  };
1278
1330
  const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
1279
1331
  releaseCurrentAccount();
1280
- const nextAccount = await rotator.rotateToNext(model, account, body.providerId);
1332
+ const nextAccount = await rotator.rotateToNext(model, account, providerId);
1281
1333
  return nextAccount;
1282
1334
  };
1283
1335
  const logRequestEnd = (status: string | number, extra = ""): void => {
@@ -1294,6 +1346,8 @@ export async function withRotation<T>(
1294
1346
  );
1295
1347
 
1296
1348
  try {
1349
+ const provider = providerAdapterForModel(account, model, rotator, providerId);
1350
+ if (requestIsOff(provider.id)) return modelOffOutcome();
1297
1351
  const skipJitter = Boolean(
1298
1352
  originalHeaders &&
1299
1353
  (originalHeaders["x-skip-safety-jitter"] === "true" ||
@@ -1320,16 +1374,18 @@ export async function withRotation<T>(
1320
1374
  await sleep(totalDelayMs, signal);
1321
1375
  }
1322
1376
 
1323
- rotator.recordUpstreamAttempt(account);
1324
- const provider = providerAdapterForModel(
1325
- account,
1326
- model,
1327
- rotator,
1328
- body.providerId,
1329
- );
1377
+ if (requestIsOff(provider.id)) return modelOffOutcome();
1330
1378
  // A parent account may carry Google + Codex credentials; refresh the
1331
1379
  // selected provider, never merely the account's primary provider.
1332
1380
  await provider.ensureValidToken(account);
1381
+ if (requestIsOff(provider.id)) return modelOffOutcome();
1382
+ // The operator may also turn this provider off for just this account.
1383
+ if (rotator.isProviderOffForAccount?.(account, provider.id)) {
1384
+ logRequestEnd("account-provider-off");
1385
+ if (attempt < maxRetries) continue;
1386
+ return sendNoAccountsAvailable(`${provider.id} turned off for ${label}`);
1387
+ }
1388
+ rotator.recordUpstreamAttempt(account);
1333
1389
  const forwarded = await provider.forwardRequest(
1334
1390
  account,
1335
1391
  { ...body },
@@ -1384,7 +1440,7 @@ export async function withRotation<T>(
1384
1440
 
1385
1441
  // success
1386
1442
  const result = await onSuccess(response, context);
1387
- const shouldRotate = rotator.recordRequest(account, model, body.providerId);
1443
+ const shouldRotate = rotator.recordRequest(account, model, providerId);
1388
1444
  const inTokens =
1389
1445
  result && typeof result === "object" && "inputTokens" in result
1390
1446
  ? (result as Record<string, unknown>).inputTokens
@@ -1402,7 +1458,7 @@ export async function withRotation<T>(
1402
1458
  inTokens || outTokens ? ` inTokens=${inTokens} outTokens=${outTokens}` : "";
1403
1459
  logRequestEnd(response.status, `endpoint=${endpoint}${ttfbInfo}${tokensInfo}`);
1404
1460
  if (shouldRotate) {
1405
- await rotator.rotateToNext(model, account, body.providerId);
1461
+ await rotator.rotateToNext(model, account, providerId);
1406
1462
  }
1407
1463
  return { ok: true, result, endpoint, context };
1408
1464
  } catch (err) {
@@ -1552,6 +1608,8 @@ async function handleProxyRequest(
1552
1608
  throw err;
1553
1609
  }
1554
1610
  let body: RequestBody;
1611
+ let providerHint: unknown;
1612
+ const providerId = nativeOllamaChat ? "ollama" : DEFAULT_PROVIDER;
1555
1613
  if (nativeOllamaChat) {
1556
1614
  // Native /api/chat payload ({model, messages, stream, options}) is
1557
1615
  // translated to the internal body shape; the internal validator expects
@@ -1577,6 +1635,7 @@ async function handleProxyRequest(
1577
1635
  );
1578
1636
  return;
1579
1637
  }
1638
+ providerHint = raw.providerId;
1580
1639
  body = {
1581
1640
  project: "",
1582
1641
  model: raw.model,
@@ -1599,6 +1658,7 @@ async function handleProxyRequest(
1599
1658
  return;
1600
1659
  }
1601
1660
  body = validation.value as RequestBody;
1661
+ providerHint = body.providerId;
1602
1662
  } catch {
1603
1663
  res.writeHead(400, { "Content-Type": "application/json" });
1604
1664
  res.end(JSON.stringify({ error: "Invalid JSON body" }));
@@ -1611,6 +1671,28 @@ async function handleProxyRequest(
1611
1671
  sendAuthErrorResponse(res, auth);
1612
1672
  return;
1613
1673
  }
1674
+ // Native envelopes belong to their endpoint's provider. A hint may confirm
1675
+ // that provider, but cannot change how this payload is admitted or forwarded.
1676
+ if (providerHint !== undefined && providerHint !== providerId) {
1677
+ res.writeHead(400, { "Content-Type": "application/json" });
1678
+ res.end(JSON.stringify({ error: `body.providerId must be '${providerId}' for this native endpoint` }));
1679
+ return;
1680
+ }
1681
+ body.providerId = providerId;
1682
+ const requestIsOff = (): boolean => isRequestOff(rotator, {
1683
+ model: body.model,
1684
+ requestedModel: body.requestedModel,
1685
+ catalogModel: body.catalogModel,
1686
+ providerId,
1687
+ });
1688
+ const sendModelOff = (): void => {
1689
+ res.writeHead(404, { "Content-Type": "application/json" });
1690
+ res.end(JSON.stringify({ error: modelOffMessage(body.model), model: body.model }));
1691
+ };
1692
+ if (requestIsOff()) {
1693
+ sendModelOff();
1694
+ return;
1695
+ }
1614
1696
  const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
1615
1697
  const clientController = new AbortController();
1616
1698
  const abortClient = (): void => clientController.abort();
@@ -1638,7 +1720,7 @@ async function handleProxyRequest(
1638
1720
  const sendNoAccountsAvailable = (reason: string): void => {
1639
1721
  if (clientController.signal.aborted || res.destroyed) return;
1640
1722
  proxyLog(`[${body.model}] No healthy account available: ${reason}`, "warn");
1641
- const retryAfterMs = rotator.getRetryAfterMs(body.model);
1723
+ const retryAfterMs = rotator.getRetryAfterMs(body.model, providerId);
1642
1724
  if (retryAfterMs > 0) {
1643
1725
  const retrySec = Math.ceil(retryAfterMs / 1000);
1644
1726
  res.writeHead(429, {
@@ -1734,19 +1816,28 @@ async function handleProxyRequest(
1734
1816
  const maxRetries = getStreamRecoveryMaxRetries(rotator);
1735
1817
  const maxAttempts = maxRetries + 1;
1736
1818
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1819
+ if (requestIsOff()) {
1820
+ sendModelOff();
1821
+ return;
1822
+ }
1737
1823
  const admissionStartedMs = Date.now();
1738
1824
  const account = await rotator.getActiveAccount(
1739
1825
  body.model,
1740
1826
  clientController.signal,
1827
+ providerId,
1741
1828
  );
1742
1829
  if (!account) {
1743
1830
  if (clientController.signal.aborted || res.destroyed) return;
1831
+ if (requestIsOff()) {
1832
+ sendModelOff();
1833
+ return;
1834
+ }
1744
1835
  sendNoAccountsAvailable("rotation returned no available account");
1745
1836
  return;
1746
1837
  }
1747
1838
 
1748
1839
  const label = account.config.label || account.config.email;
1749
- const modelKey = rotator.resolveQuotaModelKeyForDisplay(body.model) ?? body.model; // quota routing
1840
+ const modelKey = routingModelKey(rotator, body.model, providerId);
1750
1841
  const displayModelKey = observedModelKey(rotator, body.model); // metrics/logs
1751
1842
  const queueWaitMs = Date.now() - admissionStartedMs;
1752
1843
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
@@ -1754,14 +1845,11 @@ async function handleProxyRequest(
1754
1845
  const releaseCurrentAccount = (): void => {
1755
1846
  if (accountReleased) return;
1756
1847
  accountReleased = true;
1757
- rotator.finishRequest(
1758
- account,
1759
- routingModelKey(rotator, body.model),
1760
- );
1848
+ rotator.finishRequest(account, modelKey);
1761
1849
  };
1762
1850
  const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
1763
1851
  releaseCurrentAccount();
1764
- const nextAccount = await rotator.rotateToNext(body.model, account);
1852
+ const nextAccount = await rotator.rotateToNext(body.model, account, providerId);
1765
1853
  return nextAccount;
1766
1854
  };
1767
1855
  proxyLog(
@@ -1793,6 +1881,10 @@ async function handleProxyRequest(
1793
1881
  };
1794
1882
 
1795
1883
  try {
1884
+ if (requestIsOff()) {
1885
+ sendModelOff();
1886
+ return;
1887
+ }
1796
1888
  const skipJitter = req.headers["x-skip-safety-jitter"] === "true" || req.headers["x-live-request"] === "true";
1797
1889
  const jitterMs = skipJitter ? 0 : rotator.getSafetyJitterMs(account);
1798
1890
  const globalDelayMs = skipJitter ? 0 : rotator.getGlobalDelayMs();
@@ -1812,13 +1904,29 @@ async function handleProxyRequest(
1812
1904
  }
1813
1905
  await sleep(totalDelayMs, clientController.signal);
1814
1906
  }
1815
- rotator.recordUpstreamAttempt(account);
1907
+ if (requestIsOff()) {
1908
+ sendModelOff();
1909
+ return;
1910
+ }
1816
1911
  const provider = providerAdapterForModel(
1817
1912
  account,
1818
1913
  body.model,
1819
1914
  rotator,
1915
+ providerId,
1820
1916
  );
1821
1917
  await provider.ensureValidToken(account);
1918
+ if (requestIsOff()) {
1919
+ sendModelOff();
1920
+ return;
1921
+ }
1922
+ // The operator may also turn this provider off for just this account.
1923
+ if (rotator.isProviderOffForAccount?.(account, providerId)) {
1924
+ logRequestEnd("account-provider-off");
1925
+ if (attempt < maxRetries) continue;
1926
+ sendNoAccountsAvailable(`${providerId} turned off for ${label}`);
1927
+ return;
1928
+ }
1929
+ rotator.recordUpstreamAttempt(account);
1822
1930
  const forwarded = await provider.forwardRequest(
1823
1931
  account,
1824
1932
  { ...body },
@@ -1874,7 +1982,7 @@ async function handleProxyRequest(
1874
1982
  }
1875
1983
 
1876
1984
  // Success or non-error client response
1877
- const shouldRotate = rotator.recordRequest(account, body.model);
1985
+ const shouldRotate = rotator.recordRequest(account, body.model, providerId);
1878
1986
 
1879
1987
  const responseHeaders: Record<string, string> = {};
1880
1988
  response.headers.forEach((value, key) => {
@@ -1960,7 +2068,7 @@ async function handleProxyRequest(
1960
2068
  res.end();
1961
2069
 
1962
2070
  if (shouldRotate) {
1963
- await rotator.rotateToNext(body.model, account);
2071
+ await rotator.rotateToNext(body.model, account, providerId);
1964
2072
  }
1965
2073
  return;
1966
2074
  } catch (err) {
@@ -2588,6 +2696,13 @@ export function startProxy(
2588
2696
  return;
2589
2697
  }
2590
2698
 
2699
+ // Dashboard Models page: providers, provider order and model switches.
2700
+ if (pathname === "/api/catalog" || pathname.startsWith("/api/catalog/")) {
2701
+ if (!requireAdmin(req, res)) return;
2702
+ void serveCatalogApi(req, res, rotator, method ?? "GET", pathname);
2703
+ return;
2704
+ }
2705
+
2591
2706
  // Admin-only model catalog used by the dashboard's Generate/Edit
2592
2707
  // Virtual Key modal so every active provider's models (Ollama, OpenCode
2593
2708
  // Zen, OpenAI Codex, Google Antigravity) can be selected.
@@ -2639,7 +2754,7 @@ export function startProxy(
2639
2754
  }
2640
2755
 
2641
2756
  if (method === "GET" && pathname === "/v1beta/models") {
2642
- serveGeminiModels(res);
2757
+ serveGeminiModels(res, rotator);
2643
2758
  return;
2644
2759
  }
2645
2760