tuxevil-rotator 3.0.0 → 3.2.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 (42) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +20 -6
  3. package/package.json +1 -1
  4. package/src/account-store.ts +37 -5
  5. package/src/cli.ts +24 -3
  6. package/src/compat/model-specs.ts +1 -0
  7. package/src/compat.ts +540 -24
  8. package/src/config-normalize.ts +73 -30
  9. package/src/dashboard.ts +43 -42
  10. package/src/index.ts +1 -0
  11. package/src/onboarding.ts +349 -21
  12. package/src/providers/adapter.ts +18 -0
  13. package/src/providers/credential-helpers.ts +64 -0
  14. package/src/providers/google-antigravity/index.ts +9 -0
  15. package/src/providers/google-antigravity/quota.ts +2 -1
  16. package/src/providers/google-antigravity/translators.ts +83 -24
  17. package/src/providers/ollama/index.ts +8 -0
  18. package/src/providers/ollama/quota.ts +2 -1
  19. package/src/providers/openai-codex/catalog.ts +117 -0
  20. package/src/providers/openai-codex/compat.ts +556 -0
  21. package/src/providers/openai-codex/credentials.ts +82 -0
  22. package/src/providers/openai-codex/forward.ts +240 -0
  23. package/src/providers/openai-codex/index.ts +153 -0
  24. package/src/providers/openai-codex/login.ts +172 -0
  25. package/src/providers/openai-codex/oauth.ts +359 -0
  26. package/src/providers/openai-codex/quota.ts +231 -0
  27. package/src/providers/opencode-zen/catalog.ts +37 -0
  28. package/src/providers/opencode-zen/credentials.ts +31 -0
  29. package/src/providers/opencode-zen/forward.ts +214 -0
  30. package/src/providers/opencode-zen/index.ts +73 -0
  31. package/src/providers/opencode-zen/login.ts +81 -0
  32. package/src/providers/opencode-zen/quota.ts +67 -0
  33. package/src/providers/registry.ts +24 -5
  34. package/src/proxy.ts +75 -27
  35. package/src/rate-limit-parser.ts +2 -1
  36. package/src/rotator.ts +259 -48
  37. package/src/spend-logger.ts +2 -0
  38. package/src/static/dashboard-keys.js +152 -2
  39. package/src/static/dashboard.js +161 -37
  40. package/src/types.ts +83 -1
  41. package/src/validators.ts +11 -2
  42. package/tools/telemetry-receiver/receiver.js +14 -0
package/src/proxy.ts CHANGED
@@ -17,7 +17,7 @@ import {
17
17
  } from "./types.js";
18
18
  import type { AccountRuntime } from "./types.js";
19
19
  import type { AccountRotator } from "./rotator.js";
20
- import { DEFAULT_PROVIDER, getProviderAdapter, getProviderForAccount } from "./providers/registry.js";
20
+ import { DEFAULT_PROVIDER, getProviderAdapter, getProviderForAccount, findProviderForModel, isKnownProvider } from "./providers/registry.js";
21
21
  import { isRecord } from "./compat/schema-sanitizer.js";
22
22
  import type { ProviderAdapter, StreamAccumulator } from "./providers/adapter.js";
23
23
  import {
@@ -58,6 +58,7 @@ import {
58
58
  serveGetSpendLogsApi,
59
59
  serveGetSpendSummaryApi,
60
60
  serveGetSpendByKeyApi,
61
+ serveModelsApi,
61
62
  serveDashboardKeys,
62
63
  serveDashboardLogs,
63
64
  serveStaticKeysJs,
@@ -96,31 +97,40 @@ import type { FlagEventData } from "./telemetry.js";
96
97
  * The rotator is required only when it exposes `getOllamaModels()`; test
97
98
  * stubs that omit it fall back to the credentials-only dispatch.
98
99
  */
99
- function providerAdapterForModel(
100
+ export function providerAdapterForModel(
100
101
  account: AccountRuntime,
101
102
  model: string | undefined,
102
- rotator?: { getOllamaModels?: () => string[] },
103
+ rotator?: { getOllamaModels?: () => string[]; getCodexModels?: () => string[] },
103
104
  ): ProviderAdapter {
104
105
  const creds = account.config.credentials ?? [];
105
- if (creds.length > 0) {
106
- const onlyOllama = creds.every((c) => c.provider === "ollama");
107
- const onlyGoogle = creds.every((c) => c.provider !== "ollama");
108
- if (onlyOllama) return getProviderAdapter("ollama");
109
- if (onlyGoogle) return getProviderAdapter(DEFAULT_PROVIDER);
106
+ if (model) {
107
+ const context = {
108
+ ollamaModels: new Set(rotator?.getOllamaModels?.() ?? []),
109
+ codexModels: new Set(rotator?.getCodexModels?.() ?? []),
110
+ };
111
+ const matched = findProviderForModel(model, context);
112
+ if (matched) return matched;
110
113
  }
111
- let isOllamaModel = false;
112
- try {
113
- const ollamaList = rotator?.getOllamaModels?.() ?? [];
114
- if (ollamaList.length > 0 && model) {
115
- isOllamaModel = ollamaList.includes(model);
114
+ if (creds.length > 0) {
115
+ const providers = new Set(creds.map((c) => c.provider));
116
+ if (providers.size === 1) {
117
+ const soleProvider = Array.from(providers)[0];
118
+ if (isKnownProvider(soleProvider)) {
119
+ return getProviderAdapter(soleProvider);
120
+ }
116
121
  }
117
- } catch {
118
- // ignore — fall through to primary dispatch
119
- }
120
- if (isOllamaModel) {
121
- return getProviderAdapter("ollama");
122
122
  }
123
- return getProviderForAccount(account.config);
123
+ const fallback = getProviderForAccount(account.config);
124
+ return fallback.id === "openai-codex"
125
+ ? getProviderAdapter(DEFAULT_PROVIDER)
126
+ : fallback;
127
+ }
128
+
129
+ function routingModelKey(rotator: AccountRotator, model: string): string {
130
+ const resolver = (rotator as unknown as {
131
+ resolveQuotaModelKeyForDisplay?: (value: string) => string | null;
132
+ }).resolveQuotaModelKeyForDisplay;
133
+ return resolver?.call(rotator, model) ?? resolveQuotaModelKey(model) ?? model;
124
134
  }
125
135
  import { startVersionChecker, performSelfUpdate } from "./version-check.js";
126
136
  import { startNotificationPoller } from "./notification-poller.js";
@@ -453,6 +463,23 @@ async function handleUpstreamAccountAction(
453
463
  recordFailureAttempt,
454
464
  } = options;
455
465
 
466
+ if (
467
+ provider.id === "openai-codex" &&
468
+ (action.kind === "flagged-401" ||
469
+ action.kind === "flagged-403" ||
470
+ action.kind === "forbidden")
471
+ ) {
472
+ const status = action.kind === "flagged-401" ? 401 : 403;
473
+ const message = `Codex credential rejected (${status}); re-authentication required`;
474
+ writeLog(`[${label}] ${message}`, "warn");
475
+ rotator.markProviderInvalid(account, "openai-codex", message);
476
+ logRequestEnd(status, `endpoint=${action.endpoint}`);
477
+ if (!options.canRetry) return buildFailureDecision(options, status, message);
478
+ const nextAccount = await rotateAndRelease();
479
+ if (nextAccount) return { kind: "retry" };
480
+ return buildNoReplacementDecision(options, `no replacement Codex account remained after ${label} was rejected`);
481
+ }
482
+
456
483
  if (action.kind === "rate-limited") {
457
484
  writeLog(
458
485
  `[${label}] 429 rate limited${action.providerResourceExhausted ? " (RESOURCE_EXHAUSTED)" : ""}, cooldown ${Math.ceil(action.cooldownMs / 1000)}s. Error text: ${action.errorText.slice(0, 300)}`,
@@ -476,8 +503,12 @@ async function handleUpstreamAccountAction(
476
503
  `cooldownMs=${action.cooldownMs}${action.providerResourceExhausted ? " resourceExhausted=true" : ""} endpoint=${action.endpoint}`,
477
504
  );
478
505
 
506
+ const shouldRetryProviderRateLimit =
507
+ provider.id === "openai-codex" ||
508
+ provider.id === "opencode-zen" ||
509
+ action.providerResourceExhausted;
479
510
  if (
480
- action.providerResourceExhausted &&
511
+ shouldRetryProviderRateLimit &&
481
512
  options.canRetry &&
482
513
  provider.shouldRetryOnQuotaExhaustion(account, model, action.errorText)
483
514
  ) {
@@ -1080,6 +1111,7 @@ export async function withRotation<T>(
1080
1111
  response: Response,
1081
1112
  context: RotationAttemptContext,
1082
1113
  ) => Promise<T>,
1114
+ signal?: AbortSignal,
1083
1115
  ): Promise<RotationOutcome<T>> {
1084
1116
  const sendNoAccountsAvailable = (
1085
1117
  reason: string,
@@ -1112,7 +1144,7 @@ export async function withRotation<T>(
1112
1144
  if (nextAccount) {
1113
1145
  rotator.finishRequest(
1114
1146
  nextAccount,
1115
- resolveQuotaModelKey(model) ?? undefined,
1147
+ routingModelKey(rotator, model),
1116
1148
  );
1117
1149
  }
1118
1150
  return nextAccount;
@@ -1128,7 +1160,7 @@ export async function withRotation<T>(
1128
1160
  }
1129
1161
 
1130
1162
  const label = account.config.label || account.config.email;
1131
- const modelKey = resolveQuotaModelKey(model) ?? model;
1163
+ const modelKey = routingModelKey(rotator, model);
1132
1164
  const displayModelKey = resolveDisplayModelKey(body.displayModel || model);
1133
1165
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
1134
1166
  const requestStartMs = Date.now();
@@ -1173,10 +1205,14 @@ export async function withRotation<T>(
1173
1205
  model,
1174
1206
  rotator,
1175
1207
  );
1208
+ // A parent account may carry Google + Codex credentials; refresh the
1209
+ // selected provider, never merely the account's primary provider.
1210
+ await provider.ensureValidToken(account);
1176
1211
  const forwarded = await provider.forwardRequest(
1177
1212
  account,
1178
1213
  { ...body },
1179
1214
  originalHeaders,
1215
+ signal,
1180
1216
  );
1181
1217
  const { response, endpoint } = forwarded;
1182
1218
  const context: RotationAttemptContext = {
@@ -1281,7 +1317,7 @@ export async function withRotation<T>(
1281
1317
  }
1282
1318
  continue;
1283
1319
  } finally {
1284
- rotator.finishRequest(account, resolveQuotaModelKey(model) ?? undefined);
1320
+ rotator.finishRequest(account, routingModelKey(rotator, model));
1285
1321
  }
1286
1322
  }
1287
1323
 
@@ -1415,16 +1451,18 @@ async function handleProxyRequest(
1415
1451
  proxyLog(`[${body.model}] No healthy account available: ${reason}`, "warn");
1416
1452
  const retryAfterMs = rotator.getRetryAfterMs(body.model);
1417
1453
  if (retryAfterMs > 0) {
1454
+ const retrySec = Math.ceil(retryAfterMs / 1000);
1418
1455
  res.writeHead(429, {
1419
1456
  "Content-Type": "application/json",
1420
- "Retry-After": String(Math.ceil(retryAfterMs / 1000)),
1457
+ "Retry-After": String(retrySec),
1421
1458
  });
1422
1459
  res.end(
1423
1460
  JSON.stringify({
1424
- error: "All accounts cooling down or model circuit breaker active",
1461
+ error: `Rate limit exceeded. All accounts cooling down. Please wait ${retrySec} seconds before retrying.`,
1425
1462
  reason,
1426
1463
  model: body.model,
1427
1464
  retryAfterMs,
1465
+ retryAfterSeconds: retrySec,
1428
1466
  }),
1429
1467
  );
1430
1468
  return;
@@ -1444,7 +1482,7 @@ async function handleProxyRequest(
1444
1482
  if (nextAccount) {
1445
1483
  rotator.finishRequest(
1446
1484
  nextAccount,
1447
- resolveQuotaModelKey(body.model) ?? undefined,
1485
+ routingModelKey(rotator, body.model),
1448
1486
  );
1449
1487
  }
1450
1488
  return nextAccount;
@@ -1579,6 +1617,7 @@ async function handleProxyRequest(
1579
1617
  body.model,
1580
1618
  rotator,
1581
1619
  );
1620
+ await provider.ensureValidToken(account);
1582
1621
  const forwarded = await provider.forwardRequest(
1583
1622
  account,
1584
1623
  { ...body },
@@ -1744,7 +1783,7 @@ async function handleProxyRequest(
1744
1783
  } finally {
1745
1784
  rotator.finishRequest(
1746
1785
  account,
1747
- resolveQuotaModelKey(body.model) ?? undefined,
1786
+ routingModelKey(rotator, body.model),
1748
1787
  );
1749
1788
  if (onComplete) onComplete();
1750
1789
  }
@@ -2252,6 +2291,15 @@ export function startProxy(
2252
2291
  return;
2253
2292
  }
2254
2293
 
2294
+ // Admin-only model catalog used by the dashboard's Generate/Edit
2295
+ // Virtual Key modal so every active provider's models (Ollama, OpenCode
2296
+ // Zen, OpenAI Codex, Google Antigravity) can be selected.
2297
+ if (method === "GET" && pathname === "/api/models") {
2298
+ if (!requireAdmin(req, res)) return;
2299
+ serveModelsApi(res, rotator);
2300
+ return;
2301
+ }
2302
+
2255
2303
  if (pathname.startsWith("/api/keys/")) {
2256
2304
  if (!requireAdmin(req, res)) return;
2257
2305
  const hash = decodeURIComponent(pathname.slice("/api/keys/".length));
@@ -38,7 +38,8 @@ export function classifyRateLimitReason(errorText: string, status?: number): Rat
38
38
  lower.includes("rate_limit_exceeded") ||
39
39
  lower.includes("rate limit") ||
40
40
  lower.includes("too many requests") ||
41
- lower.includes("throttl")
41
+ lower.includes("throttl") ||
42
+ lower.includes("freeusagelimit")
42
43
  ) {
43
44
  return "rate-limit";
44
45
  }