tuxevil-rotator 3.1.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.
@@ -6,6 +6,7 @@ import type { QuotaFetchContext } from "../adapter.js";
6
6
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
7
7
  import { OPENCODE_ZEN_MODELS_URL } from "./catalog.js";
8
8
  import { getOpenCodeZenApiKey, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
9
+ import { sortQuotaPools } from "../registry.js";
9
10
 
10
11
  export async function fetchOpenCodeZenQuota(
11
12
  account: AccountRuntime,
@@ -54,7 +55,7 @@ export async function fetchOpenCodeZenQuota(
54
55
  timerType: "fresh",
55
56
  };
56
57
 
57
- account.quota = [...otherProviders, freshQuota];
58
+ account.quota = sortQuotaPools([...otherProviders, freshQuota]);
58
59
  account.lastQuotaPoll = Date.now();
59
60
 
60
61
  account.lastPollByProvider ??= {};
@@ -10,14 +10,11 @@ import type { ProviderAdapter } from "./adapter.js";
10
10
  import { googleAntigravityAdapter } from "./google-antigravity/index.js";
11
11
  import { ollamaAdapter } from "./ollama/index.js";
12
12
  import { openaiCodexAdapter } from "./openai-codex/index.js";
13
+ import { opencodeZenAdapter } from "./opencode-zen/index.js";
13
14
  import { logger } from "../logger.js";
14
15
  import {
15
16
  DEFAULT_PROVIDER,
16
17
  primaryProviderId,
17
- hasCredential,
18
- getCredential,
19
- type CredentialEntry,
20
- type AccountLike as ProviderCredentialLike,
21
18
  } from "./credential-helpers.js";
22
19
 
23
20
  export {
@@ -27,12 +24,20 @@ export {
27
24
  getCredential,
28
25
  type CredentialEntry,
29
26
  type AccountLike as ProviderCredentialLike,
27
+ PROVIDER_ORDER,
28
+ PROVIDER_ORDER_RANK,
29
+ getProviderIdForPoolKey,
30
+ getQuotaItemProviderId,
31
+ sortQuotaPools,
32
+ sortAccountCredentials,
33
+ type QuotaPoolLike,
30
34
  } from "./credential-helpers.js";
31
35
 
32
36
  const PROVIDERS: Record<string, ProviderAdapter> = {
33
37
  "google-antigravity": googleAntigravityAdapter,
34
38
  ollama: ollamaAdapter,
35
39
  "openai-codex": openaiCodexAdapter,
40
+ "opencode-zen": opencodeZenAdapter,
36
41
  };
37
42
 
38
43
  export function getProviderAdapter(providerId: string): ProviderAdapter {
@@ -53,6 +58,19 @@ export function isKnownProvider(providerId: string): boolean {
53
58
  return Object.prototype.hasOwnProperty.call(PROVIDERS, providerId);
54
59
  }
55
60
 
61
+ export function findProviderForModel(
62
+ model: string,
63
+ context?: { ollamaModels?: Set<string>; codexModels?: Set<string> },
64
+ ): ProviderAdapter | null {
65
+ // Check non-default explicit providers first to prevent Google fallback overlap
66
+ for (const adapter of [opencodeZenAdapter, openaiCodexAdapter, ollamaAdapter, googleAntigravityAdapter]) {
67
+ if (adapter.ownsModel?.(model, context)) {
68
+ return adapter;
69
+ }
70
+ }
71
+ return null;
72
+ }
73
+
56
74
  export function getProviderForAccount(
57
75
  account: { credentials?: Array<{ provider: string }>; provider?: string },
58
76
  providerId?: string,
package/src/proxy.ts CHANGED
@@ -15,15 +15,9 @@ import {
15
15
  resolveQuotaModelKey,
16
16
  resolveDisplayModelKey,
17
17
  } from "./types.js";
18
- import {
19
- isCodexRequestModel,
20
- isCodexProviderModelId,
21
- } from "./providers/openai-codex/catalog.js";
22
- import { isOpenCodeZenModel } from "./providers/opencode-zen/catalog.js";
23
- import { OPENCODE_ZEN_PROVIDER_ID } from "./providers/opencode-zen/index.js";
24
18
  import type { AccountRuntime } from "./types.js";
25
19
  import type { AccountRotator } from "./rotator.js";
26
- import { DEFAULT_PROVIDER, getProviderAdapter, getProviderForAccount } from "./providers/registry.js";
20
+ import { DEFAULT_PROVIDER, getProviderAdapter, getProviderForAccount, findProviderForModel, isKnownProvider } from "./providers/registry.js";
27
21
  import { isRecord } from "./compat/schema-sanitizer.js";
28
22
  import type { ProviderAdapter, StreamAccumulator } from "./providers/adapter.js";
29
23
  import {
@@ -64,6 +58,7 @@ import {
64
58
  serveGetSpendLogsApi,
65
59
  serveGetSpendSummaryApi,
66
60
  serveGetSpendByKeyApi,
61
+ serveModelsApi,
67
62
  serveDashboardKeys,
68
63
  serveDashboardLogs,
69
64
  serveStaticKeysJs,
@@ -108,45 +103,22 @@ export function providerAdapterForModel(
108
103
  rotator?: { getOllamaModels?: () => string[]; getCodexModels?: () => string[] },
109
104
  ): ProviderAdapter {
110
105
  const creds = account.config.credentials ?? [];
111
- if (model && isOpenCodeZenModel(model)) {
112
- return getProviderAdapter(OPENCODE_ZEN_PROVIDER_ID);
113
- }
114
- let isCodex = Boolean(model && isCodexRequestModel(model));
115
- try {
116
- if (
117
- model &&
118
- isCodexProviderModelId(model) &&
119
- rotator?.getCodexModels?.().includes(model)
120
- ) isCodex = true;
121
- } catch {
122
- // Ignore catalog read failures and retain the safe static allowlist.
123
- }
124
- if (isCodex) {
125
- // Codex models are provider-owned and never fall back to Google/Ollama.
126
- return getProviderAdapter("openai-codex");
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;
127
113
  }
128
114
  if (creds.length > 0) {
129
- const onlyZen = creds.every((c) => c.provider === OPENCODE_ZEN_PROVIDER_ID);
130
- const onlyOllama = creds.every((c) => c.provider === "ollama");
131
- const onlyGoogle = creds.every((c) => c.provider === DEFAULT_PROVIDER);
132
- if (onlyZen) return getProviderAdapter(OPENCODE_ZEN_PROVIDER_ID);
133
- if (onlyOllama) return getProviderAdapter("ollama");
134
- if (onlyGoogle) return getProviderAdapter(DEFAULT_PROVIDER);
135
- }
136
- let isOllamaModel = false;
137
- try {
138
- const ollamaList = rotator?.getOllamaModels?.() ?? [];
139
- if (ollamaList.length > 0 && model) {
140
- isOllamaModel = ollamaList.includes(model);
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
+ }
141
121
  }
142
- } catch {
143
- // ignore — fall through to primary dispatch
144
- }
145
- if (isOllamaModel) {
146
- return getProviderAdapter("ollama");
147
- }
148
- if (creds.some((credential) => credential.provider === DEFAULT_PROVIDER)) {
149
- return getProviderAdapter(DEFAULT_PROVIDER);
150
122
  }
151
123
  const fallback = getProviderForAccount(account.config);
152
124
  return fallback.id === "openai-codex"
@@ -532,7 +504,9 @@ async function handleUpstreamAccountAction(
532
504
  );
533
505
 
534
506
  const shouldRetryProviderRateLimit =
535
- provider.id === "openai-codex" || action.providerResourceExhausted;
507
+ provider.id === "openai-codex" ||
508
+ provider.id === "opencode-zen" ||
509
+ action.providerResourceExhausted;
536
510
  if (
537
511
  shouldRetryProviderRateLimit &&
538
512
  options.canRetry &&
@@ -1477,16 +1451,18 @@ async function handleProxyRequest(
1477
1451
  proxyLog(`[${body.model}] No healthy account available: ${reason}`, "warn");
1478
1452
  const retryAfterMs = rotator.getRetryAfterMs(body.model);
1479
1453
  if (retryAfterMs > 0) {
1454
+ const retrySec = Math.ceil(retryAfterMs / 1000);
1480
1455
  res.writeHead(429, {
1481
1456
  "Content-Type": "application/json",
1482
- "Retry-After": String(Math.ceil(retryAfterMs / 1000)),
1457
+ "Retry-After": String(retrySec),
1483
1458
  });
1484
1459
  res.end(
1485
1460
  JSON.stringify({
1486
- 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.`,
1487
1462
  reason,
1488
1463
  model: body.model,
1489
1464
  retryAfterMs,
1465
+ retryAfterSeconds: retrySec,
1490
1466
  }),
1491
1467
  );
1492
1468
  return;
@@ -2315,6 +2291,15 @@ export function startProxy(
2315
2291
  return;
2316
2292
  }
2317
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
+
2318
2303
  if (pathname.startsWith("/api/keys/")) {
2319
2304
  if (!requireAdmin(req, res)) return;
2320
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
  }
package/src/rotator.ts CHANGED
@@ -54,6 +54,9 @@ import {
54
54
  getProviderForAccount,
55
55
  hasCredential,
56
56
  primaryProviderId,
57
+ findProviderForModel,
58
+ getProviderIdForPoolKey,
59
+ PROVIDER_ORDER,
57
60
  } from "./providers/registry.js";
58
61
  import type { QuotaFetchContext } from "./providers/adapter.js";
59
62
  import { logger } from "./logger.js";
@@ -66,6 +69,7 @@ import {
66
69
  } from "./providers/openai-codex/catalog.js";
67
70
  import { CodexOAuthError } from "./providers/openai-codex/oauth.js";
68
71
  import { CODEX_QUOTA_MODEL_KEY } from "./providers/openai-codex/quota.js";
72
+ import { OPENCODE_ZEN_PROVIDER_ID } from "./providers/opencode-zen/credentials.js";
69
73
  import { getUpdateInfo } from "./version-check.js";
70
74
  import { getNotifications } from "./notification-poller.js";
71
75
  import { getConfiguredAdminToken } from "./admin-auth.js";
@@ -628,7 +632,7 @@ export class AccountRotator {
628
632
  private logConsolidatedPoll(account: AccountRuntime): void {
629
633
  const stash = account.lastPollByProvider;
630
634
  if (!stash) return;
631
- const ordered = ["google-antigravity", "ollama", "openai-codex", "opencode-zen"]
635
+ const ordered = PROVIDER_ORDER
632
636
  .filter((pid) => stash[pid])
633
637
  .map((pid) => `${pid}: ${stash[pid]}`);
634
638
  if (ordered.length > 0) {
@@ -792,7 +796,9 @@ export class AccountRotator {
792
796
  const q = account.quota.find((q) => q.modelKey === modelKey) ??
793
797
  (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
794
798
  ? account.quota.find((candidate) => candidate.modelKey === CODEX_QUOTA_MODEL_KEY)
795
- : undefined);
799
+ : modelKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
800
+ ? account.quota.find((candidate) => candidate.providerId === OPENCODE_ZEN_PROVIDER_ID)
801
+ : undefined);
796
802
  return q ? q.percentRemaining : -1;
797
803
  }
798
804
 
@@ -804,7 +810,9 @@ export class AccountRotator {
804
810
  const q = account.quota.find((q) => q.modelKey === modelKey) ??
805
811
  (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
806
812
  ? account.quota.find((candidate) => candidate.modelKey === CODEX_QUOTA_MODEL_KEY)
807
- : undefined);
813
+ : modelKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
814
+ ? account.quota.find((candidate) => candidate.providerId === OPENCODE_ZEN_PROVIDER_ID)
815
+ : undefined);
808
816
  return q?.timerType ?? "fresh";
809
817
  }
810
818
 
@@ -2344,6 +2352,7 @@ export class AccountRotator {
2344
2352
  const lower = model.toLowerCase();
2345
2353
  if (lower.includes("opus")) pricing = MODEL_PRICING["claude-opus-4-6-thinking"];
2346
2354
  else if (lower.includes("sonnet")) pricing = MODEL_PRICING["claude-sonnet-4-6"];
2355
+ else if (lower.includes("3.7-flash")) pricing = MODEL_PRICING["gemini-3.7-flash-tiered"];
2347
2356
  else if (lower.includes("3.6-flash")) pricing = MODEL_PRICING["gemini-3.6-flash-high"];
2348
2357
  else if (lower.includes("3.5-flash")) pricing = MODEL_PRICING["gemini-3.5-flash-high"];
2349
2358
  else if (lower.includes("flash")) pricing = MODEL_PRICING["gemini-3-flash"];
@@ -2428,8 +2437,13 @@ export class AccountRotator {
2428
2437
  this.setProviderCooldown(account, "openai-codex", cooldownMs);
2429
2438
  return;
2430
2439
  }
2431
- if (providerResourceExhausted) {
2432
- // Account-level daily/weekly quota exhaustion is not a model outage:
2440
+ const poolKey = model ? this.resolvePoolKeyForModel(model) : null;
2441
+ const isAccountScopedProvider =
2442
+ providerResourceExhausted ||
2443
+ (poolKey && (poolKey.startsWith("opencode-zen") || poolKey.startsWith("session")));
2444
+
2445
+ if (isAccountScopedProvider) {
2446
+ // Account-level daily/weekly quota exhaustion or per-key rate limit is not a model outage:
2433
2447
  // the account already gets an individual cooldown from markExhausted,
2434
2448
  // so it must not arm the project or model circuit breaker and block
2435
2449
  // healthy accounts that still have quota.
@@ -2701,7 +2715,11 @@ export class AccountRotator {
2701
2715
  return true;
2702
2716
  }
2703
2717
 
2704
- async ensureValidToken(account: AccountRuntime): Promise<void> {
2718
+ async ensureValidToken(account: AccountRuntime, providerId?: string): Promise<void> {
2719
+ if (providerId) {
2720
+ await this.ensureValidTokenForProvider(account, providerId);
2721
+ return;
2722
+ }
2705
2723
  const adapter = getProviderForAccount(account.config);
2706
2724
  try {
2707
2725
  await adapter.ensureValidToken(account);
@@ -2748,12 +2766,9 @@ export class AccountRotator {
2748
2766
  account: AccountRuntime,
2749
2767
  modelKey: string | null,
2750
2768
  ): Promise<void> {
2751
- if (modelKey?.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)) {
2752
- await this.ensureValidTokenForProvider(account, "openai-codex");
2753
- return;
2754
- }
2755
- if (modelKey === "session") {
2756
- await this.ensureValidTokenForProvider(account, "ollama");
2769
+ if (modelKey) {
2770
+ const providerId = getProviderIdForPoolKey(modelKey);
2771
+ await this.ensureValidToken(account, providerId);
2757
2772
  return;
2758
2773
  }
2759
2774
  await this.ensureValidToken(account);
@@ -2800,10 +2815,9 @@ export class AccountRotator {
2800
2815
  now: number,
2801
2816
  ): boolean {
2802
2817
  if (!this.isAvailable(account, now)) return false;
2803
- if (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)) {
2804
- if (account.invalidProviders?.["openai-codex"]) return false;
2805
- if ((account.providerCooldowns?.["openai-codex"] ?? 0) > now) return false;
2806
- }
2818
+ const providerId = getProviderIdForPoolKey(modelKey);
2819
+ if (account.invalidProviders?.[providerId]) return false;
2820
+ if ((account.providerCooldowns?.[providerId] ?? 0) > now) return false;
2807
2821
  const modelCooldown = account.cooldownsByModel[modelKey] ?? 0;
2808
2822
  if (modelCooldown > now) return false;
2809
2823
  // Ollama Cloud (pool key "session") imposes no per-account concurrency
@@ -2879,17 +2893,10 @@ export class AccountRotator {
2879
2893
  account: AccountRuntime,
2880
2894
  modelKey: string,
2881
2895
  ): boolean {
2882
- if (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)) {
2883
- return hasCredential(account.config, "openai-codex") &&
2884
- !account.invalidProviders?.["openai-codex"] &&
2885
- (account.providerCooldowns?.["openai-codex"] ?? 0) <= Date.now();
2886
- }
2887
- if (modelKey === "session") {
2888
- return hasCredential(account.config, "ollama");
2889
- }
2890
- // Google pools (claude/gemini) require a google credential. A dual
2891
- // account (google + ollama) must stay eligible here — it can serve both.
2892
- return hasCredential(account.config, DEFAULT_PROVIDER);
2896
+ const providerId = getProviderIdForPoolKey(modelKey);
2897
+ return hasCredential(account.config, providerId) &&
2898
+ !account.invalidProviders?.[providerId] &&
2899
+ (account.providerCooldowns?.[providerId] ?? 0) <= Date.now();
2893
2900
  }
2894
2901
 
2895
2902
  /** Public pool-key resolution for quota routing display/logging. */
@@ -2898,10 +2905,14 @@ export class AccountRotator {
2898
2905
  }
2899
2906
 
2900
2907
  private resolvePoolKeyForModel(model: string): string | null {
2901
- if (this.codexModels.has(model) || isCodexRequestModel(model)) {
2902
- return `${CODEX_QUOTA_MODEL_KEY}:${model}`;
2908
+ const context = {
2909
+ ollamaModels: this.ollamaModels,
2910
+ codexModels: this.codexModels,
2911
+ };
2912
+ const adapter = findProviderForModel(model, context);
2913
+ if (adapter?.getPoolKey) {
2914
+ return adapter.getPoolKey(model);
2903
2915
  }
2904
- if (this.ollamaModels.has(model)) return "session";
2905
2916
  return resolveQuotaModelKey(model) ?? null;
2906
2917
  }
2907
2918
 
@@ -223,6 +223,8 @@ export function calculateCost(model: string, promptTokens: number, completionTok
223
223
  pricing = MODEL_PRICING["claude-opus-4-6-thinking"];
224
224
  } else if (lower.includes("sonnet")) {
225
225
  pricing = MODEL_PRICING["claude-sonnet-4-6"];
226
+ } else if (lower.includes("3.7-flash")) {
227
+ pricing = MODEL_PRICING["gemini-3.7-flash-tiered"];
226
228
  } else if (lower.includes("3.6-flash")) {
227
229
  pricing = MODEL_PRICING["gemini-3.6-flash-high"];
228
230
  } else if (lower.includes("3.5-flash")) {
@@ -149,6 +149,151 @@ function setCheckedModels(models) {
149
149
  updateModelsCountBadge();
150
150
  }
151
151
 
152
+ // ── Dynamic model grid (fetched from /api/models) ──────────────────
153
+ //
154
+ // The Generate/Edit Virtual Key modal used to ship with a hardcoded list
155
+ // of legacy Gemini/Claude/GPT-OSS models, so adding new providers
156
+ // (Ollama, OpenAI Codex, OpenCode Zen, ...) silently hid those models
157
+ // from the Allowed Models picker. The grid is now rendered from
158
+ // /api/models, which returns every model the rotator can route today
159
+ // grouped by `owned_by` provider. A static fallback is used only when
160
+ // the API is unreachable (e.g. dashboard served from a stale build).
161
+
162
+ // Provider id → human-readable group title for the modal UI.
163
+ var PROVIDER_LABELS = {
164
+ "tuxevil-rotator": "Google Antigravity",
165
+ "openai-codex": "OpenAI Codex",
166
+ "ollama": "Ollama Cloud",
167
+ "opencode-zen": "OpenCode Zen",
168
+ };
169
+
170
+ function providerLabel(ownedBy) {
171
+ if (PROVIDER_LABELS[ownedBy]) return PROVIDER_LABELS[ownedBy];
172
+ if (typeof ownedBy === "string" && ownedBy.length > 0) {
173
+ return ownedBy.charAt(0).toUpperCase() + ownedBy.slice(1);
174
+ }
175
+ return "Other";
176
+ }
177
+
178
+ function renderModelGridFromCatalog(catalog) {
179
+ var grid = document.getElementById("modelGrid");
180
+ var empty = document.getElementById("modelGridEmpty");
181
+ if (!grid) return false;
182
+
183
+ // Group models by `owned_by` provider while preserving the order in
184
+ // which the API returned them (static catalog first, then dynamic
185
+ // provider catalogs in the order they were enabled).
186
+ var groups = [];
187
+ var byKey = {};
188
+ (catalog || []).forEach(function(m) {
189
+ if (!m || !m.id) return;
190
+ var key = m.owned_by || "other";
191
+ if (!byKey[key]) {
192
+ byKey[key] = { key: key, label: providerLabel(key), models: [] };
193
+ groups.push(byKey[key]);
194
+ }
195
+ byKey[key].models.push(m);
196
+ });
197
+
198
+ if (groups.length === 0) {
199
+ grid.innerHTML = "";
200
+ if (empty) empty.style.display = "";
201
+ updateModelsCountBadge();
202
+ return false;
203
+ }
204
+
205
+ if (empty) empty.style.display = "none";
206
+
207
+ grid.innerHTML = groups.map(function(group) {
208
+ var cards = group.models.map(function(m) {
209
+ var id = "model-" + m.id.replace(/[^a-zA-Z0-9_-]/g, "_");
210
+ return '<label class="model-card">' +
211
+ '<input type="checkbox" id="' + escapeHtml(id) + '" value="' + escapeHtml(m.id) + '" class="modelCb" onchange="updateModelsCountBadge()">' +
212
+ '<span class="model-name" title="' + escapeHtml(m.id) + '">' + escapeHtml(m.id) + '</span>' +
213
+ '</label>';
214
+ }).join("");
215
+ return '<div class="model-category">' +
216
+ '<div class="cat-title">' + escapeHtml(group.label) + '</div>' +
217
+ '<div class="cat-grid">' + cards + '</div>' +
218
+ '</div>';
219
+ }).join("");
220
+
221
+ updateModelsCountBadge();
222
+ return true;
223
+ }
224
+
225
+ // Last successful catalog (cached so the Edit modal opens instantly
226
+ // without re-fetching when the user clicks Edit right after Generate).
227
+ var lastModelCatalog = null;
228
+ var modelCatalogInflight = null;
229
+
230
+ function fetchModelCatalog() {
231
+ if (modelCatalogInflight) return modelCatalogInflight;
232
+ modelCatalogInflight = fetch("/api/models", { headers: authHeaders() })
233
+ .then(function(r) {
234
+ if (!r.ok) throw new Error("HTTP " + r.status);
235
+ return r.json();
236
+ })
237
+ .then(function(d) {
238
+ var catalog = Array.isArray(d && d.data) ? d.data : [];
239
+ lastModelCatalog = catalog;
240
+ return catalog;
241
+ })
242
+ .finally(function() {
243
+ modelCatalogInflight = null;
244
+ });
245
+ return modelCatalogInflight;
246
+ }
247
+
248
+ // Static fallback used only when /api/models is unreachable. Mirrors
249
+ // the pre-refactor hardcoded list so the modal still works against an
250
+ // older server build that hasn't been restarted with this change.
251
+ var FALLBACK_MODEL_CATALOG = [
252
+ { id: "gemini-3.1-pro-low", owned_by: "tuxevil-rotator" },
253
+ { id: "gemini-3.1-pro-high", owned_by: "tuxevil-rotator" },
254
+ { id: "gemini-3.5-flash-medium", owned_by: "tuxevil-rotator" },
255
+ { id: "gemini-3.5-flash-high", owned_by: "tuxevil-rotator" },
256
+ { id: "gemini-3-flash", owned_by: "tuxevil-rotator" },
257
+ { id: "gemini-3.6-flash-low", owned_by: "tuxevil-rotator" },
258
+ { id: "gemini-3.6-flash-medium", owned_by: "tuxevil-rotator" },
259
+ { id: "gemini-3.6-flash-high", owned_by: "tuxevil-rotator" },
260
+ { id: "gemini-3.6-flash-tiered", owned_by: "tuxevil-rotator" },
261
+ { id: "gemini-3.7-flash-tiered", owned_by: "tuxevil-rotator" },
262
+ { id: "claude-sonnet-4-6", owned_by: "tuxevil-rotator" },
263
+ { id: "claude-opus-4-6-thinking", owned_by: "tuxevil-rotator" },
264
+ { id: "gpt-oss-120b-medium", owned_by: "tuxevil-rotator" },
265
+ ];
266
+
267
+ function ensureModelGridRendered(preselectedModels, callback) {
268
+ function applySelection() {
269
+ if (typeof preselectedModels !== "undefined") {
270
+ setCheckedModels(preselectedModels || []);
271
+ } else {
272
+ updateModelsCountBadge();
273
+ }
274
+ if (typeof callback === "function") callback();
275
+ }
276
+
277
+ if (lastModelCatalog && lastModelCatalog.length > 0) {
278
+ renderModelGridFromCatalog(lastModelCatalog);
279
+ applySelection();
280
+ return;
281
+ }
282
+
283
+ fetchModelCatalog()
284
+ .then(function(catalog) {
285
+ renderModelGridFromCatalog(catalog);
286
+ applySelection();
287
+ })
288
+ .catch(function() {
289
+ // Stale build or network glitch: fall back to the static list so
290
+ // the modal is never empty. The fallback lacks Ollama/Codex/Zen
291
+ // models, but at least existing keys can still be edited.
292
+ renderModelGridFromCatalog(FALLBACK_MODEL_CATALOG);
293
+ applySelection();
294
+ });
295
+ }
296
+
152
297
  function loadKeys() {
153
298
  fetch("/api/keys", { headers: authHeaders() })
154
299
  .then(function(r) { return r.json(); })
@@ -248,7 +393,6 @@ function showGenerateModal() {
248
393
  document.getElementById("keyFormAlias").disabled = false;
249
394
  document.getElementById("keyFormUserId").value = "";
250
395
  document.getElementById("keyFormUserId").disabled = false;
251
- selectNoModels();
252
396
  document.getElementById("keyFormError").textContent = "";
253
397
  document.getElementById("generatedKeyResult").style.display = "none";
254
398
  document.getElementById("submitKeyBtn").textContent = "Generate Key";
@@ -257,6 +401,10 @@ function showGenerateModal() {
257
401
  var sub = document.getElementById("modalSubtitle");
258
402
  if (sub) sub.textContent = "Configure key access and model restrictions";
259
403
  document.getElementById("keyModal").classList.add("open");
404
+ // Render the live provider catalog and default to "all models allowed"
405
+ // (empty selection). ensureModelGridRendered reuses the cached catalog
406
+ // when possible, so this opens instantly on the second open.
407
+ ensureModelGridRendered([]);
260
408
  }
261
409
 
262
410
  function showEditModal(hash) {
@@ -271,7 +419,6 @@ function showEditModal(hash) {
271
419
  document.getElementById("keyFormAlias").disabled = true;
272
420
  document.getElementById("keyFormUserId").value = k.userId || "";
273
421
  document.getElementById("keyFormUserId").disabled = true;
274
- setCheckedModels(k.models || []);
275
422
  document.getElementById("keyFormError").textContent = "";
276
423
  document.getElementById("generatedKeyResult").style.display = "none";
277
424
  document.getElementById("submitKeyBtn").textContent = "Save Changes";
@@ -280,6 +427,9 @@ function showEditModal(hash) {
280
427
  var sub = document.getElementById("modalSubtitle");
281
428
  if (sub) sub.textContent = "Updating model restrictions for alias: " + k.keyAlias;
282
429
  document.getElementById("keyModal").classList.add("open");
430
+ // Render the live catalog and preselect the key's existing allowlist
431
+ // (or all models when the key is unrestricted).
432
+ ensureModelGridRendered(k.models || []);
283
433
  }
284
434
 
285
435
  function hideModal() {
@@ -51,11 +51,33 @@ function isKickstartSupported(q) {
51
51
  );
52
52
  }
53
53
 
54
+ function getQuotaItemProviderRank(q) {
55
+ var p = q.providerId;
56
+ if (!p) {
57
+ var k = String(q.modelKey || "");
58
+ if (k === "claude" || k === "gemini") p = "google-antigravity";
59
+ else if (k === "session" || k === "weekly") p = "ollama";
60
+ else if (k.indexOf("opencode") === 0 || k === "opencode-zen") p = "opencode-zen";
61
+ else if (k.indexOf("codex") === 0 || k.indexOf("openai-codex") === 0) p = "openai-codex";
62
+ else p = "google-antigravity";
63
+ }
64
+ var ranks = {
65
+ "google-antigravity": 1,
66
+ "ollama": 2,
67
+ "opencode-zen": 3,
68
+ "openai-codex": 4
69
+ };
70
+ return ranks[p] || 99;
71
+ }
72
+
54
73
  function renderQuotaBars(account) {
55
74
  var quota = account.quota;
56
75
  if (!quota || quota.length === 0) return "";
76
+ var sortedQuota = quota.slice().sort(function (a, b) {
77
+ return getQuotaItemProviderRank(a) - getQuotaItemProviderRank(b);
78
+ });
57
79
  var now = Date.now();
58
- var rows = quota
80
+ var rows = sortedQuota
59
81
  .map(function (q) {
60
82
  var inFlightForModel = (account.inFlightByModel || {})[q.modelKey] || 0;
61
83
  var clearButton =
@@ -331,20 +353,6 @@ function renderAccounts(data) {
331
353
  Math.min(100, (cooldownRemaining / Math.max(totalCooldown, 1)) * 100),
332
354
  );
333
355
  }
334
- var modelBadges = (a.activeForModels || [])
335
- .map(function (m) {
336
- if (m.startsWith("claude")) {
337
- return '<span class="badge badge-model">CLAUDE</span>';
338
- }
339
- if (m === "gemini-3.1-pro") {
340
- return '<span class="badge badge-model">PRO</span>';
341
- }
342
- if (m === "gemini-3.5-flash") {
343
- return '<span class="badge badge-model">FLASH</span>';
344
- }
345
- return "";
346
- })
347
- .join("");
348
356
  var tierLabel = a.tier ? String(a.tier).toUpperCase() : "UNKNOWN";
349
357
 
350
358
  return (
@@ -393,7 +401,6 @@ function renderAccounts(data) {
393
401
  "ULTRA</div>" +
394
402
  "</div>" +
395
403
  "</div>" +
396
- modelBadges +
397
404
  "</div>" +
398
405
  "</div>" +
399
406
  '<div class="card-email">' +
@@ -1161,6 +1168,10 @@ var MODEL_PRICING_CLIENT = {
1161
1168
  "gemini-3.6-flash-medium": { input: 1.5, output: 7.5 },
1162
1169
  "gemini-3.6-flash-low": { input: 1.5, output: 7.5 },
1163
1170
  "gemini-3.6-flash-tiered": { input: 1.5, output: 7.5 },
1171
+ // Gemini 3.7 Flash tiered — public Gemini API pricing, verified 2026-08-13.
1172
+ // Introductory rates through 2026-12-31; from 2027-01-01 these double to
1173
+ // input 1.50 / output 7.50 per 1M tokens — update this entry then.
1174
+ "gemini-3.7-flash-tiered": { input: 0.75, output: 3.75 },
1164
1175
  "gpt-oss-120b-medium": { input: 2.0, output: 10.0 },
1165
1176
  // OpenAI Codex GPT-5.6 models — mirrors MODEL_PRICING in types.ts.
1166
1177
  "gpt-5.6-sol": { input: 5.0, output: 30.0 },
@@ -1185,6 +1196,14 @@ var MODEL_PRICING_CLIENT = {
1185
1196
  "nemotron-3-nano:30b": { input: 0.5, output: 1.5 },
1186
1197
  "nemotron-3-super": { input: 0.6, output: 1.8 },
1187
1198
  "nemotron-3-ultra": { input: 0.6, output: 1.8 },
1199
+ // OpenCode Zen free models — mirrors MODEL_PRICING in src/types.ts
1200
+ "deepseek-v4-flash-free": { input: 0.14, output: 0.28 },
1201
+ "nemotron-3.5-lightning-free": { input: 0.35, output: 1.05 },
1202
+ "nemotron-3-ultra-free": { input: 0.6, output: 1.8 },
1203
+ "mimo-v2.5-free": { input: 0.15, output: 0.6 },
1204
+ "hy3-free": { input: 0.25, output: 1.0 },
1205
+ "ling-3.0-tiny-free": { input: 0.05, output: 0.2 },
1206
+ "laguna-s-2.1-free": { input: 0.2, output: 0.8 },
1188
1207
  };
1189
1208
 
1190
1209
  function getModelPricingClient(m) {
@@ -1192,6 +1211,7 @@ function getModelPricingClient(m) {
1192
1211
  var lower = (m || "").toLowerCase();
1193
1212
  if (lower.indexOf("opus") !== -1) return MODEL_PRICING_CLIENT["claude-opus-4-6-thinking"];
1194
1213
  if (lower.indexOf("sonnet") !== -1) return MODEL_PRICING_CLIENT["claude-sonnet-4-6"];
1214
+ if (lower.indexOf("3.7-flash") !== -1) return MODEL_PRICING_CLIENT["gemini-3.7-flash-tiered"];
1195
1215
  if (lower.indexOf("3.6-flash") !== -1) return MODEL_PRICING_CLIENT["gemini-3.6-flash-high"];
1196
1216
  if (lower.indexOf("3.5-flash") !== -1) return MODEL_PRICING_CLIENT["gemini-3.5-flash-high"];
1197
1217
  if (lower.indexOf("flash") !== -1) return MODEL_PRICING_CLIENT["gemini-3-flash"];