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/onboarding.ts CHANGED
@@ -15,6 +15,21 @@ import {
15
15
  defaultAccountEmail,
16
16
  validateApiKey,
17
17
  } from "./providers/ollama/api-key-validation.js";
18
+ import {
19
+ validateApiKey as validateZenApiKey,
20
+ } from "./providers/opencode-zen/login.js";
21
+ import {
22
+ defaultAccountEmail as zenDefaultAccountEmail,
23
+ OPENCODE_ZEN_PROVIDER_ID,
24
+ } from "./providers/opencode-zen/credentials.js";
25
+ import {
26
+ codexOAuthErrorMessage,
27
+ createCodexAuthorizationFlow,
28
+ exchangeCodexAuthorizationCode,
29
+ getCodexOAuthConfig,
30
+ parseCodexIdentity,
31
+ type CodexOAuthConfig,
32
+ } from "./providers/openai-codex/oauth.js";
18
33
  import type { AccountConfig } from "./types.js";
19
34
 
20
35
  interface AccountSink {
@@ -261,11 +276,13 @@ export function startHostedLogin(
261
276
  // user signs in and pastes the redirect URL back, server exchanges the code.
262
277
 
263
278
  interface CliLoginSession {
279
+ provider: "google-antigravity" | "openai-codex";
264
280
  verifier: string;
265
281
  challenge: string;
266
282
  oauthState: string;
267
283
  authUrl: string;
268
284
  createdAt: number;
285
+ codexConfig?: CodexOAuthConfig;
269
286
  }
270
287
 
271
288
  const cliLoginSessions = new Map<string, CliLoginSession>();
@@ -283,27 +300,44 @@ export function serveCliLogin(res: ServerResponse): void {
283
300
  pruneCliSessions();
284
301
  const { verifier, challenge } = generatePkce();
285
302
  const oauthState = generateState();
286
- let authUrl: string;
303
+ let authUrl: string | null = null;
304
+ let sessionId: string | null = null;
287
305
  try {
288
306
  authUrl = buildAuthUrl(oauthState, challenge);
289
- } catch (err) {
290
- res.writeHead(503, { "Content-Type": "text/html; charset=utf-8" });
291
- res.end(
292
- renderPage(
293
- "OAuth Not Configured",
294
- `<h1>OAuth Login Isn’t Ready</h1><p>${escapeHtml(err instanceof Error ? err.message : String(err))}</p>`,
295
- ),
296
- );
297
- return;
307
+ sessionId = generateState();
308
+ cliLoginSessions.set(sessionId, {
309
+ provider: "google-antigravity",
310
+ verifier,
311
+ challenge,
312
+ oauthState,
313
+ authUrl,
314
+ createdAt: Date.now(),
315
+ });
316
+ } catch {
317
+ // Google is optional for this provider-aware page. Codex and Ollama stay
318
+ // available when Antigravity OAuth is not configured.
319
+ }
320
+
321
+ let codexAuthUrl: string | null = null;
322
+ let codexSessionId: string | null = null;
323
+ try {
324
+ const codexConfig = getCodexOAuthConfig();
325
+ const codexFlow = createCodexAuthorizationFlow(codexConfig);
326
+ codexSessionId = generateState();
327
+ codexAuthUrl = codexFlow.url;
328
+ cliLoginSessions.set(codexSessionId, {
329
+ provider: "openai-codex",
330
+ verifier: codexFlow.verifier,
331
+ challenge: "",
332
+ oauthState: codexFlow.state,
333
+ authUrl: codexFlow.url,
334
+ createdAt: Date.now(),
335
+ codexConfig,
336
+ });
337
+ } catch {
338
+ // Keep Google/Ollama login usable if an operator supplied malformed Codex
339
+ // OAuth environment overrides.
298
340
  }
299
- const sessionId = generateState();
300
- cliLoginSessions.set(sessionId, {
301
- verifier,
302
- challenge,
303
- oauthState,
304
- authUrl,
305
- createdAt: Date.now(),
306
- });
307
341
 
308
342
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
309
343
  res.end(
@@ -314,11 +348,13 @@ export function serveCliLogin(res: ServerResponse): void {
314
348
 
315
349
  <div class="tabs">
316
350
  <button class="tab active" data-panel="panel-google">Google (Antigravity)</button>
351
+ <button class="tab" data-panel="panel-codex">OpenAI Codex</button>
317
352
  <button class="tab" data-panel="panel-ollama">Ollama Cloud</button>
353
+ <button class="tab" data-panel="panel-zen">OpenCode Zen</button>
318
354
  </div>
319
355
 
320
356
  <div class="panel active" id="panel-google">
321
- <h3 style="margin:24px 0 8px;font-size:18px;">Step 1 &mdash; Sign in with Google</h3>
357
+ ${authUrl && sessionId ? `<h3 style="margin:24px 0 8px;font-size:18px;">Step 1 &mdash; Sign in with Google</h3>
322
358
  <p>Click the button below to open the Google sign-in page in a new tab:</p>
323
359
  <a class="cta" href="${escapeHtml(authUrl)}" target="_blank" rel="noopener" style="font-size:16px;">
324
360
  Sign in with Google &nearr;
@@ -336,7 +372,29 @@ export function serveCliLogin(res: ServerResponse): void {
336
372
  <button type="submit" class="cta" style="cursor:pointer;border:none;font-family:inherit;font-size:16px;margin-top:12px;">
337
373
  Connect Account
338
374
  </button>
339
- </form>
375
+ </form>` : `<div class="note error">Google OAuth is not configured for this server. Set ANTIGRAVITY_CLIENT_ID, ANTIGRAVITY_CLIENT_SECRET and ANTIGRAVITY_REDIRECT_URI to enable it.</div>`}
376
+ </div>
377
+
378
+ <div class="panel" id="panel-codex">
379
+ ${codexAuthUrl && codexSessionId ? `<h3 style="margin:24px 0 8px;font-size:18px;">Step 1 &mdash; Sign in with ChatGPT</h3>
380
+ <p>Open the OpenAI sign-in page in a new tab. Codex OAuth will return to the loopback URL configured for the Codex CLI.</p>
381
+ <a class="cta" href="${escapeHtml(codexAuthUrl)}" target="_blank" rel="noopener" style="font-size:16px;">
382
+ Sign in with OpenAI Codex &nearr;
383
+ </a>
384
+
385
+ <h3 style="margin:24px 0 8px;font-size:18px;">Step 2 &mdash; Paste the callback URL</h3>
386
+ <p>Copy the complete URL from the browser address bar, even if the loopback page does not load, and paste it here:</p>
387
+ <form id="codexPasteForm" style="margin-top:12px;">
388
+ <input type="hidden" name="session" value="${escapeHtml(codexSessionId)}" />
389
+ <textarea name="redirectUrl" rows="4" placeholder="Paste the Codex callback URL (http://localhost:1455/auth/callback?... )" style="
390
+ width:100%;font-family:'IBM Plex Mono',monospace;font-size:13px;
391
+ padding:12px 14px;border-radius:12px;border:1px solid rgba(31,42,31,0.15);
392
+ background:rgba(31,42,31,0.03);resize:vertical;
393
+ "></textarea>
394
+ <button type="submit" class="cta" style="cursor:pointer;border:none;font-family:inherit;font-size:16px;margin-top:12px;">
395
+ Connect Codex Account
396
+ </button>
397
+ </form>` : `<div class="note error">Codex OAuth is not available because its configuration is invalid. Check the CODEX_OAUTH_* environment variables and reload this page.</div>`}
340
398
  </div>
341
399
 
342
400
  <div class="panel" id="panel-ollama">
@@ -353,6 +411,20 @@ export function serveCliLogin(res: ServerResponse): void {
353
411
  </form>
354
412
  </div>
355
413
 
414
+ <div class="panel" id="panel-zen">
415
+ <p>Paste an OpenCode Zen API key to add the account to this rotator. The key is validated against opencode.ai/zen before saving.</p>
416
+ <p class="mono">Create a key at https://opencode.ai/zen</p>
417
+ <form id="zenForm" style="margin-top:12px;">
418
+ <label for="zenEmail">Account identifier (email or label)</label>
419
+ <input id="zenEmail" name="email" class="field" placeholder="me@example.com (optional)" autocomplete="off" />
420
+ <label for="zenApiKey">OpenCode Zen API key</label>
421
+ <input id="zenApiKey" name="apiKey" class="field" type="password" placeholder="sk-..." autocomplete="off" required />
422
+ <button type="submit" class="cta" style="cursor:pointer;border:none;font-family:inherit;font-size:16px;margin-top:12px;">
423
+ Connect Account
424
+ </button>
425
+ </form>
426
+ </div>
427
+
356
428
  <div id="result" style="margin-top:18px;"></div>
357
429
 
358
430
  <script>
@@ -367,7 +439,8 @@ function showResult(html) {
367
439
  document.getElementById('result').innerHTML = html;
368
440
  }
369
441
 
370
- document.getElementById('pasteForm').addEventListener('submit', async (e) => {
442
+ const googleForm = document.getElementById('pasteForm');
443
+ if (googleForm) googleForm.addEventListener('submit', async (e) => {
371
444
  e.preventDefault();
372
445
  const form = e.target;
373
446
  const btn = form.querySelector('button[type=submit]');
@@ -453,6 +526,90 @@ document.getElementById('keyForm').addEventListener('submit', async (e) => {
453
526
  btn.textContent = 'Connect Account';
454
527
  }
455
528
  });
529
+
530
+ const codexForm = document.getElementById('codexPasteForm');
531
+ if (codexForm) codexForm.addEventListener('submit', async (e) => {
532
+ e.preventDefault();
533
+ const form = e.target;
534
+ const btn = form.querySelector('button[type=submit]');
535
+ const redirectUrl = form.redirectUrl.value.trim();
536
+ const session = form.session.value;
537
+ if (!redirectUrl) { showResult('<div class="note error">Please paste the Codex callback URL.</div>'); return; }
538
+ btn.disabled = true;
539
+ btn.textContent = 'Connecting...';
540
+ showResult('<div class="note">Exchanging the Codex authorization code securely...</div>');
541
+ try {
542
+ const params = new URLSearchParams(window.location.search);
543
+ const token = params.get('token') || '';
544
+ const res = await fetch('/api/cli-login', {
545
+ method: 'POST',
546
+ headers: { 'Content-Type': 'application/json', ...(token ? { 'X-Rotator-Admin-Token': token } : {}) },
547
+ body: JSON.stringify({ provider: 'openai-codex', session, redirectUrl }),
548
+ });
549
+ const data = await res.json();
550
+ if (data.ok) {
551
+ showResult('<div class="note" style="border-left-color:var(--accent);background:rgba(30,107,82,0.12);"><strong id="codexLoginResultEmail"></strong> ' + (data.isNew ? 'added' : 'updated') + ' successfully. The isolated Codex pool is ready.</div>');
552
+ document.getElementById('codexLoginResultEmail').textContent = data.email || '';
553
+ } else {
554
+ const errorDiv = document.createElement('div');
555
+ errorDiv.className = 'note error';
556
+ errorDiv.textContent = data.error || 'Unknown error';
557
+ document.getElementById('result').innerHTML = '';
558
+ document.getElementById('result').appendChild(errorDiv);
559
+ }
560
+ } catch (err) {
561
+ const errorDiv = document.createElement('div');
562
+ errorDiv.className = 'note error';
563
+ errorDiv.textContent = 'Request failed: ' + err.message;
564
+ document.getElementById('result').innerHTML = '';
565
+ document.getElementById('result').appendChild(errorDiv);
566
+ } finally {
567
+ btn.disabled = false;
568
+ btn.textContent = 'Connect Codex Account';
569
+ }
570
+ });
571
+
572
+ const zenForm = document.getElementById('zenForm');
573
+ if (zenForm) zenForm.addEventListener('submit', async (e) => {
574
+ e.preventDefault();
575
+ const form = e.target;
576
+ const btn = form.querySelector('button[type=submit]');
577
+ const apiKey = form.apiKey.value.trim();
578
+ const email = form.email.value.trim();
579
+ if (!apiKey) { showResult('<div class="note error">Please paste an API key.</div>'); return; }
580
+ btn.disabled = true;
581
+ btn.textContent = 'Validating...';
582
+ showResult('<div class="note">Checking the key against opencode.ai/zen...</div>');
583
+ try {
584
+ const params = new URLSearchParams(window.location.search);
585
+ const token = params.get('token') || '';
586
+ const res = await fetch('/api/cli-login', {
587
+ method: 'POST',
588
+ headers: { 'Content-Type': 'application/json', ...(token ? { 'X-Rotator-Admin-Token': token } : {}) },
589
+ body: JSON.stringify({ provider: 'opencode-zen', email, apiKey }),
590
+ });
591
+ const data = await res.json();
592
+ if (data.ok) {
593
+ showResult('<div class="note" style="border-left-color:var(--accent);background:rgba(30,107,82,0.12);">' +
594
+ '<strong>' + (data.email || '') + '</strong> ' + (data.isNew ? 'added' : 'updated') + ' successfully. The rotator will start using OpenCode Zen on the next poll.</div>');
595
+ } else {
596
+ var zenErrDiv = document.createElement('div');
597
+ zenErrDiv.className = 'note error';
598
+ zenErrDiv.textContent = data.error || 'Unknown error';
599
+ document.getElementById('result').innerHTML = '';
600
+ document.getElementById('result').appendChild(zenErrDiv);
601
+ }
602
+ } catch (err) {
603
+ var zenErr2 = document.createElement('div');
604
+ zenErr2.className = 'note error';
605
+ zenErr2.textContent = 'Request failed: ' + err.message;
606
+ document.getElementById('result').innerHTML = '';
607
+ document.getElementById('result').appendChild(zenErr2);
608
+ } finally {
609
+ btn.disabled = false;
610
+ btn.textContent = 'Connect Account';
611
+ }
612
+ });
456
613
  </script>
457
614
  `,
458
615
  ),
@@ -499,6 +656,16 @@ export async function handleCliLoginApi(
499
656
  return;
500
657
  }
501
658
 
659
+ if (provider === "openai-codex") {
660
+ await handleCodexCliLogin(body, res, rotator);
661
+ return;
662
+ }
663
+
664
+ if (provider === "opencode-zen") {
665
+ await handleZenCliLogin(body, res, rotator);
666
+ return;
667
+ }
668
+
502
669
  if (provider !== "google-antigravity") {
503
670
  res.writeHead(400, { "Content-Type": "application/json" });
504
671
  res.end(JSON.stringify({ ok: false, error: `Unknown provider "${provider}"` }));
@@ -533,6 +700,11 @@ export async function handleCliLoginApi(
533
700
  );
534
701
  return;
535
702
  }
703
+ if (session.provider !== "google-antigravity") {
704
+ res.writeHead(400, { "Content-Type": "application/json" });
705
+ res.end(JSON.stringify({ ok: false, error: "Session does not belong to Google login" }));
706
+ return;
707
+ }
536
708
 
537
709
  // Parse the redirect URL to extract code
538
710
  let code: string | undefined;
@@ -612,6 +784,107 @@ export async function handleCliLoginApi(
612
784
  }
613
785
  }
614
786
 
787
+ async function handleCodexCliLogin(
788
+ body: { session?: string; redirectUrl?: string },
789
+ res: ServerResponse,
790
+ rotator: AccountSink,
791
+ ): Promise<void> {
792
+ const sessionId = body.session;
793
+ const redirectUrl = body.redirectUrl;
794
+ if (
795
+ typeof sessionId !== "string" ||
796
+ typeof redirectUrl !== "string" ||
797
+ sessionId.length === 0 ||
798
+ redirectUrl.length === 0 ||
799
+ sessionId.length > 256 ||
800
+ redirectUrl.length > 8 * 1024
801
+ ) {
802
+ res.writeHead(400, { "Content-Type": "application/json" });
803
+ res.end(JSON.stringify({ ok: false, error: "Missing session or redirectUrl" }));
804
+ return;
805
+ }
806
+
807
+ pruneCliSessions();
808
+ const session = cliLoginSessions.get(sessionId);
809
+ if (!session || session.provider !== "openai-codex" || !session.codexConfig) {
810
+ res.writeHead(400, { "Content-Type": "application/json" });
811
+ res.end(JSON.stringify({
812
+ ok: false,
813
+ error: "Session expired or invalid. Reload the page and try again.",
814
+ }));
815
+ return;
816
+ }
817
+
818
+ let code: string | undefined;
819
+ let state: string | null;
820
+ try {
821
+ const url = new URL(redirectUrl.trim());
822
+ code = url.searchParams.get("code") ?? undefined;
823
+ state = url.searchParams.get("state");
824
+ } catch {
825
+ res.writeHead(400, { "Content-Type": "application/json" });
826
+ res.end(JSON.stringify({
827
+ ok: false,
828
+ error: "Could not parse the URL. Paste the complete Codex callback URL.",
829
+ }));
830
+ return;
831
+ }
832
+
833
+ if (!code) {
834
+ res.writeHead(400, { "Content-Type": "application/json" });
835
+ res.end(JSON.stringify({ ok: false, error: "No authorization code found in the URL." }));
836
+ return;
837
+ }
838
+ if (state !== session.oauthState) {
839
+ res.writeHead(400, { "Content-Type": "application/json" });
840
+ res.end(JSON.stringify({
841
+ ok: false,
842
+ error: "State mismatch - reload the login page and try again.",
843
+ }));
844
+ return;
845
+ }
846
+
847
+ // Consume the one-time browser session before exchanging the authorization
848
+ // code. A retry must start a new PKCE flow.
849
+ cliLoginSessions.delete(sessionId);
850
+
851
+ try {
852
+ const tokens = await exchangeCodexAuthorizationCode(
853
+ code,
854
+ session.verifier,
855
+ session.codexConfig,
856
+ );
857
+ const identity = parseCodexIdentity(tokens.accessToken, tokens.idToken);
858
+ const email = identity.email ??
859
+ (identity.providerAccountId ? `${identity.providerAccountId}@codex.local` : undefined);
860
+ if (!email) throw new Error("Codex OAuth did not return an account identity");
861
+
862
+ const entry: AccountConfig = {
863
+ email,
864
+ label: email.split("@")[0],
865
+ provider: "openai-codex",
866
+ credentials: [{
867
+ provider: "openai-codex",
868
+ refreshToken: tokens.refreshToken,
869
+ ...(identity.providerAccountId ? { providerAccountId: identity.providerAccountId } : {}),
870
+ }],
871
+ };
872
+ const { isNew } = await addAccountToConfig(entry);
873
+ await rotator.addOrUpdateAccount(entry);
874
+
875
+ res.writeHead(200, { "Content-Type": "application/json" });
876
+ res.end(JSON.stringify({ ok: true, email: entry.email, isNew, provider: "openai-codex" }));
877
+ } catch (error) {
878
+ res.writeHead(400, { "Content-Type": "application/json" });
879
+ res.end(JSON.stringify({
880
+ ok: false,
881
+ error: error instanceof Error && error.message.startsWith("Codex OAuth")
882
+ ? codexOAuthErrorMessage(error)
883
+ : "Unable to complete Codex login. Please reload and try again.",
884
+ }));
885
+ }
886
+ }
887
+
615
888
  const MAX_ACCOUNT_EMAIL_LENGTH = 320;
616
889
  const MAX_ACCOUNT_LABEL_LENGTH = 200;
617
890
 
@@ -669,6 +942,61 @@ async function handleOllamaCliLogin(
669
942
  res.end(JSON.stringify({ ok: true, email: entry.email, isNew }));
670
943
  }
671
944
 
945
+ async function handleZenCliLogin(
946
+ body: { email?: string; apiKey?: string },
947
+ res: ServerResponse,
948
+ rotator: AccountSink,
949
+ ): Promise<void> {
950
+ const apiKey = typeof body.apiKey === "string" ? body.apiKey.trim() : "";
951
+ const email = typeof body.email === "string" ? body.email.trim() : "";
952
+
953
+ if (!apiKey) {
954
+ res.writeHead(400, { "Content-Type": "application/json" });
955
+ res.end(JSON.stringify({ ok: false, error: "Missing apiKey" }));
956
+ return;
957
+ }
958
+ if (apiKey.length > 4096) {
959
+ res.writeHead(400, { "Content-Type": "application/json" });
960
+ res.end(JSON.stringify({ ok: false, error: "API key too long" }));
961
+ return;
962
+ }
963
+ if (email.length > MAX_ACCOUNT_EMAIL_LENGTH) {
964
+ res.writeHead(400, { "Content-Type": "application/json" });
965
+ res.end(JSON.stringify({ ok: false, error: "Account identifier too long" }));
966
+ return;
967
+ }
968
+
969
+ const validation = await validateZenApiKey(apiKey);
970
+ if (!validation.ok) {
971
+ res.writeHead(400, { "Content-Type": "application/json" });
972
+ res.end(
973
+ JSON.stringify({
974
+ ok: false,
975
+ error: `Key rejected (${validation.status}): ${validation.error}`,
976
+ }),
977
+ );
978
+ return;
979
+ }
980
+
981
+ const derivedEmail = email || zenDefaultAccountEmail(apiKey);
982
+ const entry: AccountConfig = {
983
+ email: derivedEmail,
984
+ credentials: [
985
+ {
986
+ provider: OPENCODE_ZEN_PROVIDER_ID,
987
+ apiKey,
988
+ },
989
+ ],
990
+ label: email || derivedEmail.split("@")[0],
991
+ };
992
+
993
+ const { isNew } = await addAccountToConfig(entry);
994
+ await rotator.addOrUpdateAccount(entry);
995
+
996
+ res.writeHead(200, { "Content-Type": "application/json" });
997
+ res.end(JSON.stringify({ ok: true, email: entry.email, isNew, provider: OPENCODE_ZEN_PROVIDER_ID }));
998
+ }
999
+
672
1000
  export async function handleHostedCallback(
673
1001
  req: IncomingMessage,
674
1002
  res: ServerResponse,
@@ -42,6 +42,17 @@ export interface QuotaFetchContext {
42
42
  statusCode: number,
43
43
  errorText: string,
44
44
  ): void;
45
+ /** Provider-scoped invalidation/cooldown hooks; never affect sibling providers. */
46
+ markProviderInvalid?(
47
+ account: AccountRuntime,
48
+ providerId: string,
49
+ reason: string,
50
+ ): void;
51
+ setProviderCooldown?(
52
+ account: AccountRuntime,
53
+ providerId: string,
54
+ durationMs: number,
55
+ ): void;
45
56
  }
46
57
 
47
58
  export type CredentialValidationResult =
@@ -120,6 +131,13 @@ export interface ProviderAdapter {
120
131
  createStreamAccumulator(): StreamAccumulator;
121
132
 
122
133
  // --- Catalog / helpers ---
134
+ /** Whether a model belongs to this provider. */
135
+ ownsModel?(
136
+ model: string,
137
+ context?: { ollamaModels?: Set<string>; codexModels?: Set<string> },
138
+ ): boolean;
139
+ /** Returns the pool key for a model served by this provider. */
140
+ getPoolKey?(model: string): string;
123
141
  /** Cheap upstream model that warms a quota pool during kickstart. */
124
142
  getKickstartModelForPool(quotaModelKey: string): string | undefined;
125
143
  /** Benchmark request used to measure account latency/health. */
@@ -9,6 +9,7 @@ export interface CredentialEntry {
9
9
  apiKey?: string;
10
10
  refreshToken?: string;
11
11
  projectId?: string;
12
+ providerAccountId?: string;
12
13
  projectSource?: "google" | "manual";
13
14
  proxyUrl?: string;
14
15
  }
@@ -19,6 +20,8 @@ export interface AccountLike {
19
20
  apiKey?: string;
20
21
  refreshToken?: string;
21
22
  projectId?: string;
23
+ codexRefreshToken?: string;
24
+ codexAccountId?: string;
22
25
  projectSource?: "google" | "manual";
23
26
  proxyUrl?: string;
24
27
  }
@@ -50,6 +53,10 @@ export function getCredential(
50
53
  if (account.apiKey !== undefined) legacy.apiKey = account.apiKey;
51
54
  if (account.refreshToken !== undefined) legacy.refreshToken = account.refreshToken;
52
55
  if (account.projectId !== undefined) legacy.projectId = account.projectId;
56
+ if (providerId === "openai-codex") {
57
+ if (account.codexRefreshToken !== undefined) legacy.refreshToken = account.codexRefreshToken;
58
+ if (account.codexAccountId !== undefined) legacy.providerAccountId = account.codexAccountId;
59
+ }
53
60
  if (account.projectSource !== undefined) legacy.projectSource = account.projectSource;
54
61
  if (account.proxyUrl !== undefined) legacy.proxyUrl = account.proxyUrl;
55
62
  return legacy;
@@ -70,3 +77,60 @@ export function getProviderProxyUrl(
70
77
  if (credential?.proxyUrl !== undefined) return credential.proxyUrl;
71
78
  return undefined;
72
79
  }
80
+
81
+ export const PROVIDER_ORDER: string[] = [
82
+ "google-antigravity",
83
+ "ollama",
84
+ "opencode-zen",
85
+ "openai-codex",
86
+ ];
87
+
88
+ export const PROVIDER_ORDER_RANK: Record<string, number> = {
89
+ "google-antigravity": 1,
90
+ ollama: 2,
91
+ "opencode-zen": 3,
92
+ "openai-codex": 4,
93
+ };
94
+
95
+ export function getProviderIdForPoolKey(poolKey: string): string {
96
+ if (poolKey.startsWith("codex:") || poolKey.startsWith("openai-codex")) return "openai-codex";
97
+ if (poolKey.startsWith("opencode-zen:") || poolKey === "opencode-zen") return "opencode-zen";
98
+ if (poolKey === "session" || poolKey === "weekly") return "ollama";
99
+ if (poolKey === "claude" || poolKey === "gemini") return "google-antigravity";
100
+ if (PROVIDER_ORDER_RANK[poolKey] !== undefined) return poolKey;
101
+ return DEFAULT_PROVIDER;
102
+ }
103
+
104
+ export type QuotaPoolLike = {
105
+ modelKey: string;
106
+ providerId?: string;
107
+ };
108
+
109
+ export function getQuotaItemProviderId(q: QuotaPoolLike): string {
110
+ if (q.providerId && PROVIDER_ORDER_RANK[q.providerId] !== undefined) {
111
+ return q.providerId;
112
+ }
113
+ return getProviderIdForPoolKey(q.modelKey);
114
+ }
115
+
116
+ export function sortQuotaPools<T extends QuotaPoolLike>(quotas: T[]): T[] {
117
+ return [...quotas].sort((a, b) => {
118
+ const rankA = PROVIDER_ORDER_RANK[getQuotaItemProviderId(a)] ?? 99;
119
+ const rankB = PROVIDER_ORDER_RANK[getQuotaItemProviderId(b)] ?? 99;
120
+ if (rankA !== rankB) {
121
+ return rankA - rankB;
122
+ }
123
+ return 0;
124
+ });
125
+ }
126
+
127
+ export function sortAccountCredentials<T extends { provider: string }>(credentials: T[]): T[] {
128
+ return [...credentials].sort((a, b) => {
129
+ const rankA = PROVIDER_ORDER_RANK[a.provider] ?? 99;
130
+ const rankB = PROVIDER_ORDER_RANK[b.provider] ?? 99;
131
+ if (rankA !== rankB) {
132
+ return rankA - rankB;
133
+ }
134
+ return 0;
135
+ });
136
+ }
@@ -28,6 +28,7 @@ import {
28
28
  import {
29
29
  TOKEN_URL,
30
30
  KICKSTART_MODEL_FOR_QUOTA_POOL,
31
+ resolveQuotaModelKey,
31
32
  } from "../../types.js";
32
33
  import type { AccountRuntime } from "../../types.js";
33
34
  import { fetchWithRetry } from "../../fetch-with-retry.js";
@@ -159,6 +160,14 @@ export const googleAntigravityAdapter: ProviderAdapter = {
159
160
  return KICKSTART_MODEL_FOR_QUOTA_POOL[quotaModelKey];
160
161
  },
161
162
 
163
+ ownsModel(model: string): boolean {
164
+ return resolveQuotaModelKey(model) !== null || model.includes("gemini") || model.includes("claude");
165
+ },
166
+
167
+ getPoolKey(model: string): string {
168
+ return resolveQuotaModelKey(model) ?? model;
169
+ },
170
+
162
171
  getBenchmark(account: AccountRuntime) {
163
172
  return getBenchmarkSpec(account);
164
173
  },
@@ -14,6 +14,7 @@ import {
14
14
  import { fetchWithRetry } from "../../fetch-with-retry.js";
15
15
  import type { QuotaFetchContext } from "../adapter.js";
16
16
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
17
+ import { sortQuotaPools } from "../registry.js";
17
18
 
18
19
  /**
19
20
  * Extract per-model quotas from a Google quota response, preserving the
@@ -126,7 +127,7 @@ export async function fetchProviderQuota(
126
127
  fresh.forEach(
127
128
  (q) => ((q as { providerId?: string }).providerId = "google-antigravity"),
128
129
  );
129
- account.quota = [...otherProviders, ...fresh];
130
+ account.quota = sortQuotaPools([...otherProviders, ...fresh]);
130
131
  account.lastQuotaPoll = Date.now();
131
132
 
132
133
  // Stash the provider-local poll log for the rotator to emit as a