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
@@ -10,7 +10,7 @@
10
10
  // separately in `src/compat/model-specs.ts` via `maxOutputTokens`.
11
11
 
12
12
  import { dynamicCatalog } from "./dynamic-catalog.js";
13
- import { getModelSpecOverride } from "../../compat/model-specs.js";
13
+ import { getModelSpec, getModelSpecOverride } from "../../compat/model-specs.js";
14
14
 
15
15
  export interface AntigravityModelSpec {
16
16
  id: string;
@@ -106,3 +106,192 @@ export function getAntigravityContextWindow(model: string): number {
106
106
  if (lower.includes("gpt-oss")) return GPT_OSS_DEFAULT_CONTEXT_WINDOW;
107
107
  return FALLBACK_CONTEXT_WINDOW;
108
108
  }
109
+
110
+ // Static Antigravity models every install lists, before dynamic discovery adds
111
+ // the models each account reports.
112
+ const MODEL_CATALOG = [
113
+ {
114
+ id: "gemini-3-flash",
115
+ family: "gemini-3-flash",
116
+ ctx: 1048576,
117
+ quotaPool: "gemini",
118
+ multimodal: true,
119
+ tools: true,
120
+ },
121
+ {
122
+ id: "gemini-3.6-flash-high",
123
+ family: "gemini-3.6-flash",
124
+ ctx: 1048576,
125
+ quotaPool: "gemini",
126
+ multimodal: true,
127
+ tools: true,
128
+ },
129
+ {
130
+ id: "gemini-3.6-flash-medium",
131
+ family: "gemini-3.6-flash",
132
+ ctx: 1048576,
133
+ quotaPool: "gemini",
134
+ multimodal: true,
135
+ tools: true,
136
+ },
137
+ {
138
+ id: "gemini-3.6-flash-low",
139
+ family: "gemini-3.6-flash",
140
+ ctx: 1048576,
141
+ quotaPool: "gemini",
142
+ multimodal: true,
143
+ tools: true,
144
+ },
145
+ {
146
+ id: "gemini-3.6-flash-tiered",
147
+ family: "gemini-3.6-flash",
148
+ ctx: 1048576,
149
+ quotaPool: "gemini",
150
+ multimodal: true,
151
+ tools: true,
152
+ },
153
+ {
154
+ id: "gemini-3.7-flash-tiered",
155
+ family: "gemini-3.7-flash",
156
+ ctx: 1048576,
157
+ quotaPool: "gemini",
158
+ multimodal: true,
159
+ tools: true,
160
+ },
161
+ {
162
+ id: "gemini-3.8-flash-high",
163
+ family: "gemini-3.8-flash",
164
+ ctx: 1048576,
165
+ quotaPool: "gemini",
166
+ multimodal: true,
167
+ tools: true,
168
+ },
169
+ {
170
+ id: "gemini-3.8-flash-medium",
171
+ family: "gemini-3.8-flash",
172
+ ctx: 1048576,
173
+ quotaPool: "gemini",
174
+ multimodal: true,
175
+ tools: true,
176
+ },
177
+ {
178
+ id: "gemini-3.8-flash-low",
179
+ family: "gemini-3.8-flash",
180
+ ctx: 1048576,
181
+ quotaPool: "gemini",
182
+ multimodal: true,
183
+ tools: true,
184
+ },
185
+ {
186
+ id: "gemini-3.1-pro-low",
187
+ family: "gemini-3.1-pro",
188
+ ctx: 1048576,
189
+ quotaPool: "gemini",
190
+ multimodal: true,
191
+ tools: true,
192
+ },
193
+ {
194
+ id: "gemini-3.1-pro-high",
195
+ family: "gemini-3.1-pro",
196
+ ctx: 1048576,
197
+ quotaPool: "gemini",
198
+ multimodal: true,
199
+ tools: true,
200
+ },
201
+ {
202
+ id: "claude-sonnet-4-6",
203
+ family: "claude",
204
+ ctx: 1000000,
205
+ quotaPool: "claude",
206
+ multimodal: true,
207
+ tools: true,
208
+ },
209
+ {
210
+ id: "claude-opus-4-6-thinking",
211
+ family: "claude",
212
+ ctx: 1000000,
213
+ quotaPool: "claude",
214
+ multimodal: true,
215
+ tools: true,
216
+ },
217
+ {
218
+ id: "gpt-oss-120b-medium",
219
+ family: "gpt-oss",
220
+ ctx: 131072,
221
+ quotaPool: "claude",
222
+ multimodal: false,
223
+ tools: true,
224
+ },
225
+ {
226
+ id: "gemini-3.5-flash-lite",
227
+ family: "gemini-3.5-flash",
228
+ ctx: 1048576,
229
+ quotaPool: "gemini",
230
+ multimodal: true,
231
+ tools: true,
232
+ },
233
+ {
234
+ id: "whisper-1",
235
+ family: "gemini-3.8-flash",
236
+ ctx: 1048576,
237
+ quotaPool: "gemini",
238
+ multimodal: true,
239
+ tools: false,
240
+ },
241
+ ] as const;
242
+
243
+ /** Whether the rotator ships this id, as opposed to an account reporting it. */
244
+ export function isBuiltInAntigravityModel(model: string): boolean {
245
+ const wanted = model.trim().toLowerCase();
246
+ return MODEL_CATALOG.some((entry) => entry.id.toLowerCase() === wanted);
247
+ }
248
+
249
+ export interface CompatModelEntry {
250
+ id: string;
251
+ family: string;
252
+ ctx: number;
253
+ quotaPool: string;
254
+ multimodal: boolean;
255
+ tools: boolean;
256
+ maxOutputTokens: number;
257
+ thinkingBudget: number;
258
+ minThinkingBudget?: number;
259
+ isThinking: boolean;
260
+ }
261
+
262
+ export function getEffectiveAntigravityModels(): CompatModelEntry[] {
263
+ const dynamic = dynamicCatalog.getAllModels();
264
+ const seen = new Set(MODEL_CATALOG.map((model) => model.id.toLowerCase()));
265
+ const result: CompatModelEntry[] = MODEL_CATALOG.map((model) => {
266
+ const spec = getModelSpec(model.id);
267
+ const contextWindow = getModelSpecOverride(model.id)?.contextWindow ??
268
+ dynamicCatalog.getModelSpec(model.id)?.contextWindow;
269
+ return {
270
+ ...model,
271
+ ctx: contextWindow ?? model.ctx,
272
+ maxOutputTokens: spec.maxOutputTokens,
273
+ thinkingBudget: spec.thinkingBudget,
274
+ minThinkingBudget: spec.minThinkingBudget,
275
+ isThinking: spec.isThinking,
276
+ };
277
+ });
278
+ for (const m of dynamic) {
279
+ if (seen.has(m.id.toLowerCase())) continue;
280
+ seen.add(m.id.toLowerCase());
281
+ const spec = getModelSpec(m.id);
282
+ result.push({
283
+ id: m.id,
284
+ family: m.family,
285
+ ctx: spec.contextWindow ?? m.ctx,
286
+ quotaPool: m.quotaPool,
287
+ multimodal: m.multimodal,
288
+ tools: m.tools,
289
+ maxOutputTokens: spec.maxOutputTokens,
290
+ thinkingBudget: spec.thinkingBudget,
291
+ minThinkingBudget: spec.minThinkingBudget,
292
+ isThinking: spec.isThinking,
293
+ });
294
+ }
295
+
296
+ return result;
297
+ }
@@ -332,6 +332,8 @@ export async function forwardRequest(
332
332
 
333
333
  const {
334
334
  displayModel: _displayModel,
335
+ requestedModel: _requestedModel,
336
+ catalogModel: _catalogModel,
335
337
  providerId: _providerId,
336
338
  selectionMode: _selectionMode,
337
339
  selectionConfidence: _selectionConfidence,
@@ -7,8 +7,10 @@
7
7
 
8
8
  import type {
9
9
  ProviderAdapter,
10
+ ProviderModel,
10
11
  QuotaFetchContext,
11
12
  } from "../adapter.js";
13
+ import { getEffectiveAntigravityModels, isBuiltInAntigravityModel } from "./catalog.js";
12
14
  import { fetchProviderQuota } from "./quota.js";
13
15
  import {
14
16
  forwardRequest,
@@ -168,6 +170,15 @@ export const googleAntigravityAdapter: ProviderAdapter = {
168
170
  );
169
171
  },
170
172
 
173
+ listModels(): ProviderModel[] {
174
+ return getEffectiveAntigravityModels().map((model) => ({
175
+ id: model.id,
176
+ contextWindow: model.ctx,
177
+ quotaPool: model.quotaPool,
178
+ source: isBuiltInAntigravityModel(model.id) ? "catalog" : "discovered",
179
+ }));
180
+ },
181
+
171
182
  ownsModel(model: string): boolean {
172
183
  return resolveQuotaModelKey(model) !== null || model.includes("gemini") || model.includes("claude");
173
184
  },
@@ -1373,6 +1373,10 @@ export function openAIToAntigravityBody(
1373
1373
  project: "compat-placeholder",
1374
1374
  model: mappedModel,
1375
1375
  displayModel: requestedModel,
1376
+ requestedModel,
1377
+ // The catalog id after effort routing, before upstream aliasing, so the
1378
+ // Models page switches can be checked against it.
1379
+ catalogModel: effortTarget,
1376
1380
  userAgent: "antigravity",
1377
1381
  requestType: "agent",
1378
1382
  request,
@@ -7,7 +7,7 @@
7
7
  // Ported from the ollama-rotator project (same author) into the
8
8
  // tuxevil-rotator provider layer.
9
9
 
10
- import type { ProviderAdapter, ProviderFeatures } from "../adapter.js";
10
+ import type { ModelListContext, ProviderAdapter, ProviderFeatures, ProviderModel } from "../adapter.js";
11
11
  import { fetchProviderUsage } from "./quota.js";
12
12
  import {
13
13
  forwardRequest,
@@ -81,6 +81,16 @@ export const ollamaAdapter: ProviderAdapter = {
81
81
  return quotaModelKey === "session" ? OLLAMA_KICKSTART_MODEL : undefined;
82
82
  },
83
83
 
84
+ listModels(context: ModelListContext): ProviderModel[] {
85
+ // The live catalog carries names only; /v1/models has always advertised 128K.
86
+ return context.ollamaModels.map((id) => ({
87
+ id,
88
+ contextWindow: 128_000,
89
+ quotaPool: OLLAMA_QUOTA_POOL_KEY,
90
+ source: "discovered",
91
+ }));
92
+ },
93
+
84
94
  ownsModel(model: string, context?: { ollamaModels?: Set<string> }): boolean {
85
95
  return model === OLLAMA_KICKSTART_MODEL ||
86
96
  (context?.ollamaModels?.has(model) ?? false);
@@ -2,7 +2,8 @@
2
2
  // tuxevil-rotator provider layer.
3
3
  // Persistent store of raw quota-poll observations.
4
4
  //
5
- // Every `GET /api/usage` poll returns each pool's usage as a fraction
5
+ // `GET /api/balance` supplies remaining credits or window percentages.
6
+ // Legacy `GET /api/usage` responses report each pool's usage as a fraction
6
7
  // (0..1) with 3-decimal precision, plus per-model request counts inside
7
8
  // that window. The rotator rounds these to whole percents for routing;
8
9
  // this store keeps the raw values so operators can correlate tokens
@@ -19,6 +20,7 @@
19
20
 
20
21
  import { rotatorEnv } from "../../env.js";
21
22
  import type { OllamaUsageResponse } from "./quota.js";
23
+ import type { ModelQuota } from "../../types.js";
22
24
  import { OLLAMA_QUOTA_POOL_KEY } from "../credential-helpers.js";
23
25
 
24
26
  const RETENTION_DEFAULT_DAYS = 14;
@@ -166,3 +168,22 @@ export async function pruneQuotaPolls(days: number = RETENTION_DEFAULT_DAYS): Pr
166
168
  return 0;
167
169
  }
168
170
  }
171
+
172
+ /** Normalize balance observations to the same included-usage calibration series. */
173
+ export async function recordParsedQuotaPolls(
174
+ accountEmail: string,
175
+ polledAt: string,
176
+ quotas: ModelQuota[],
177
+ ): Promise<void> {
178
+ for (const quota of quotas) {
179
+ if (quota.modelKey !== "monthly" && quota.modelKey !== "session" && quota.modelKey !== "weekly") continue;
180
+ if (typeof quota.usageRaw !== "number" || !Number.isFinite(quota.usageRaw)) continue;
181
+ await recordQuotaPoll({
182
+ accountEmail,
183
+ polledAt,
184
+ pool: quota.modelKey,
185
+ usageRaw: quota.usageRaw,
186
+ percentRemaining: quota.percentRemaining,
187
+ });
188
+ }
189
+ }
@@ -1,14 +1,14 @@
1
- // Ollama Cloud quota polling: `GET /api/usage` → monthly pool.
1
+ // Ollama Cloud quota polling: `GET /api/balance` → included credits/windows.
2
2
  //
3
3
  // Ported from the ollama-rotator project (same author) into the
4
4
  // tuxevil-rotator provider layer.
5
5
 
6
6
  import { fetchWithRetry } from "../../fetch-with-retry.js";
7
- import { OLLAMA_USAGE_URL, OLLAMA_USER_AGENT } from "../../types.js";
7
+ import { OLLAMA_BALANCE_URL, OLLAMA_USAGE_URL, OLLAMA_USER_AGENT } from "../../types.js";
8
8
  import { getOllamaApiKey } from "./credentials.js";
9
9
  import type { AccountRuntime, ModelQuota } from "../../types.js";
10
10
  import type { QuotaFetchContext } from "../adapter.js";
11
- import { recordUsagePoll } from "./quota-poll-store.js";
11
+ import { recordParsedQuotaPolls, recordUsagePoll } from "./quota-poll-store.js";
12
12
  import {
13
13
  nextWeeklyResetMs,
14
14
  sessionWindowEndMs,
@@ -16,10 +16,11 @@ import {
16
16
  } from "./usage-windows.js";
17
17
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
18
18
  import { sortQuotaPools } from "../registry.js";
19
- import { OLLAMA_QUOTA_POOL_KEY } from "../credential-helpers.js";
19
+ import { getQuotaItemProviderId, OLLAMA_QUOTA_POOL_KEY } from "../credential-helpers.js";
20
20
 
21
21
  /**
22
- * Poll `GET /api/usage` for one account and store the parsed pool quotas.
22
+ * Poll balance for actual remaining quota; the usage endpoint now reports
23
+ * historical consumption, not subscription limits.
23
24
  * Non-2xx responses flag the account (401/403) via the context callbacks;
24
25
  * network errors are swallowed (quota stays stale, rotation falls back to
25
26
  * request-count based rotation).
@@ -29,7 +30,7 @@ export async function fetchProviderUsage(
29
30
  ctx: QuotaFetchContext,
30
31
  ): Promise<void> {
31
32
  try {
32
- const response = await fetchWithRetry(OLLAMA_USAGE_URL, {
33
+ const options = {
33
34
  method: "GET",
34
35
  headers: {
35
36
  Authorization: `Bearer ${getOllamaApiKey(account.config) ?? ""}`,
@@ -37,47 +38,58 @@ export async function fetchProviderUsage(
37
38
  },
38
39
  timeoutMs: 8000,
39
40
  dispatcher: getAccountProxyDispatcher(account, "ollama"),
40
- });
41
+ };
42
+ let response = await fetchWithRetry(OLLAMA_BALANCE_URL, options);
43
+ const legacy = response.status === 404;
44
+ if (legacy) {
45
+ await response.body?.cancel();
46
+ response = await fetchWithRetry(OLLAMA_USAGE_URL, options);
47
+ }
41
48
 
42
49
  if (!response.ok) {
43
50
  if (response.status === 401 || response.status === 403) {
44
51
  const errorText = await response.text().catch(() => "");
45
52
  ctx.log(
46
- `${account.config.email}: usage API returned ${response.status}, flagging account`,
53
+ `${account.config.email}: Ollama quota API returned ${response.status}, flagging account`,
47
54
  );
48
55
  ctx.reportQuotaPollFlag(account, response.status, errorText);
49
56
  ctx.markFlagged(
50
57
  account,
51
- `Usage API ${response.status}: ${errorText}`,
58
+ `Ollama quota API ${response.status}: ${errorText}`,
52
59
  { triggerProtectivePause: false },
53
60
  );
54
61
  }
55
62
  return;
56
63
  }
57
64
 
58
- const data = (await response.json()) as OllamaUsageResponse;
65
+ const data: unknown = await response.json();
59
66
  const oldQuota = account.quota || [];
60
- const fresh = extractUsagePools(data, oldQuota);
61
- // Drop the previous Ollama entries so the new ones fully replace
62
- // them; keep entries from OTHER providers (Antigravity) so multi-
63
- // provider accounts accumulate quotas across credentials.
67
+ const fresh = legacy
68
+ ? extractUsagePools(data as OllamaUsageResponse, oldQuota)
69
+ : extractBalancePools(data);
70
+ if (fresh.length === 0) {
71
+ ctx.log(`${account.config.email}: Ollama quota response has no recognized limits; retaining last known quota`);
72
+ return;
73
+ }
74
+ // Replace only this provider's quota after parsing a valid response.
64
75
  const otherProviders = (oldQuota || []).filter(
65
- (q) => (q as { providerId?: string }).providerId &&
66
- (q as { providerId?: string }).providerId !== "ollama",
76
+ (q) => getQuotaItemProviderId(q) !== "ollama",
67
77
  );
68
78
  fresh.forEach(
69
- (q) => ((q as { providerId?: string }).providerId = "ollama"),
79
+ (q) => (q.providerId = "ollama"),
70
80
  );
71
81
  account.quota = sortQuotaPools([...otherProviders, ...fresh]);
72
82
  account.lastQuotaPoll = Date.now();
73
- void recordUsagePoll(account.config.email, new Date().toISOString(), data);
83
+ const polledAt = new Date(account.lastQuotaPoll).toISOString();
84
+ if (legacy) void recordUsagePoll(account.config.email, polledAt, data as OllamaUsageResponse);
85
+ else void recordParsedQuotaPolls(account.config.email, polledAt, fresh);
74
86
 
75
87
  // Stash the provider-local poll log for the rotator to emit as a
76
88
  // single consolidated line per cycle.
77
89
  account.lastPollByProvider ??= {};
78
90
  account.lastPollByProvider["ollama"] = account.quota
79
91
  .filter(
80
- (q) => (q as { providerId?: string }).providerId === "ollama",
92
+ (q) => q.providerId === "ollama",
81
93
  )
82
94
  .map((q) => {
83
95
  const remain = q.resetTime
@@ -91,7 +103,7 @@ export async function fetchProviderUsage(
91
103
  })
92
104
  .join(" | ");
93
105
  } catch {
94
- // Network error, skip
106
+ ctx.log(`${account.config.email}: Ollama quota poll failed; retaining last known quota`);
95
107
  }
96
108
  }
97
109
 
@@ -106,9 +118,9 @@ export interface OllamaUsageResponse {
106
118
  /**
107
119
  * Parse `GET /api/usage` into Ollama quota pools.
108
120
  *
109
- * Current Ollama Cloud responses expose one account-wide `monthly` pool. The
110
- * legacy session/weekly parser remains as a fallback for older responses so
111
- * an upgrade does not make an account temporarily unroutable.
121
+ * Older Ollama Cloud usage responses exposed a monthly pool or legacy
122
+ * session/weekly pools. Used only when /api/balance is unavailable; today
123
+ * /api/usage returns consumption totals and must not be treated as quota.
112
124
  */
113
125
  export function extractUsagePools(
114
126
  data: OllamaUsageResponse,
@@ -214,3 +226,63 @@ export function extractUsagePools(
214
226
 
215
227
  return quotas;
216
228
  }
229
+
230
+ /** Read the current balance endpoint without guessing budgets from historic spend. */
231
+ export function extractBalancePools(data: unknown): ModelQuota[] {
232
+ if (!isObject(data) || !isObject(data.included)) return [];
233
+ const included = data.included;
234
+ const balance = included.balance_usd;
235
+ const allowance = included.allowance_usd;
236
+ const purchased = isObject(data.purchased) ? data.purchased.balance_usd : undefined;
237
+ if (isFiniteNumber(balance) && isFiniteNumber(allowance) && allowance > 0) {
238
+ const remaining = Math.max(0, Math.min(1, balance / allowance));
239
+ return [{
240
+ modelKey: OLLAMA_QUOTA_POOL_KEY,
241
+ displayName: "Ollama",
242
+ percentRemaining: remainingPercent(remaining * 100),
243
+ usageRaw: 1 - remaining,
244
+ credits: {
245
+ balanceUsd: Math.max(0, balance),
246
+ allowanceUsd: allowance,
247
+ purchasedUsd: isFiniteNumber(purchased) ? Math.max(0, purchased) : 0,
248
+ },
249
+ resetTime: isObject(included.period) ? validResetTime(included.period.until) : null,
250
+ timerType: "monthly",
251
+ }];
252
+ }
253
+
254
+ const quotas: ModelQuota[] = [];
255
+ for (const pool of ["monthly", "session", "weekly"] as const) {
256
+ const window = included[pool];
257
+ if (!isObject(window) || !isFiniteNumber(window.remaining_percent)) continue;
258
+ const percentRemaining = remainingPercent(window.remaining_percent);
259
+ const resetTime = validResetTime(window.resets_at);
260
+ quotas.push({
261
+ modelKey: pool,
262
+ displayName: pool === "monthly" ? "Ollama" : pool === "session" ? "Session" : "Weekly",
263
+ percentRemaining,
264
+ usageRaw: 1 - Math.max(0, Math.min(100, window.remaining_percent)) / 100,
265
+ resetTime,
266
+ timerType: pool === "monthly" ? "monthly" : pool === "weekly" ? "7d"
267
+ : !resetTime && percentRemaining === 100 ? "fresh" : "5h",
268
+ });
269
+ }
270
+ return quotas;
271
+ }
272
+
273
+ function isObject(value: unknown): value is Record<string, unknown> {
274
+ return value !== null && typeof value === "object" && !Array.isArray(value);
275
+ }
276
+
277
+ function isFiniteNumber(value: unknown): value is number {
278
+ return typeof value === "number" && Number.isFinite(value);
279
+ }
280
+
281
+ function remainingPercent(percent: number): number {
282
+ // A rounding artifact must not make a still-usable credit balance unroutable.
283
+ return percent > 0 ? Math.max(1, Math.min(100, Math.round(percent))) : 0;
284
+ }
285
+
286
+ function validResetTime(value: unknown): string | null {
287
+ return typeof value === "string" && Number.isFinite(Date.parse(value)) ? value : null;
288
+ }
@@ -1,5 +1,5 @@
1
1
  import type { AccountRuntime, AccountConfig } from "../../types.js";
2
- import type { ProviderAdapter, QuotaFetchContext, CredentialValidationResult } from "../adapter.js";
2
+ import type { ModelListContext, ProviderAdapter, ProviderModel, QuotaFetchContext, CredentialValidationResult } from "../adapter.js";
3
3
  import { logger } from "../../logger.js";
4
4
  import {
5
5
  getCodexAccountId,
@@ -24,7 +24,7 @@ import {
24
24
  fetchCodexQuota,
25
25
  CODEX_QUOTA_MODEL_KEY,
26
26
  } from "./quota.js";
27
- import { isCodexRequestModel, isCodexProviderModelId } from "./catalog.js";
27
+ import { getCodexModel, getCodexModels, isCodexRequestModel, isCodexProviderModelId } from "./catalog.js";
28
28
 
29
29
  const providerLog = logger.child("provider/openai-codex");
30
30
  const refreshFlights = new Map<string, Promise<void>>();
@@ -148,6 +148,22 @@ export const openaiCodexAdapter: ProviderAdapter = {
148
148
 
149
149
  getKickstartModelForPool(): string | undefined { return "gpt-5.6-luna"; },
150
150
 
151
+ listModels(context: ModelListContext): ProviderModel[] {
152
+ // Discovery can surface other vendors' models; only GPT ids belong to Codex.
153
+ const ids = context.codexModels.length > 0
154
+ ? context.codexModels.filter((id) => isCodexRequestModel(id) || isCodexProviderModelId(id))
155
+ : getCodexModels().map((model) => model.id);
156
+ return ids.map((id) => {
157
+ const model = getCodexModel(id);
158
+ return {
159
+ id,
160
+ contextWindow: model?.contextWindow ?? null,
161
+ quotaPool: CODEX_QUOTA_MODEL_KEY,
162
+ source: model?.source === "allowlist" ? "catalog" : "discovered",
163
+ };
164
+ });
165
+ },
166
+
151
167
  ownsModel(model: string, context?: { codexModels?: Set<string> }): boolean {
152
168
  if (isCodexRequestModel(model)) return true;
153
169
  if (isCodexProviderModelId(model) && (context?.codexModels?.has(model) ?? false)) return true;
@@ -1,11 +1,11 @@
1
1
  // OpenCode Zen provider adapter.
2
2
 
3
- import type { ProviderAdapter, ProviderFeatures } from "../adapter.js";
3
+ import type { ProviderAdapter, ProviderFeatures, ProviderModel } from "../adapter.js";
4
4
  import { runLogin } from "./login.js";
5
5
  import { getOpenCodeZenApiKey, validateCredentials, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
6
6
  import { forwardRequest, OpenCodeZenSseAccumulator, getBenchmarkSpec } from "./forward.js";
7
7
  import { fetchOpenCodeZenQuota } from "./quota.js";
8
- import { isOpenCodeZenModel } from "./catalog.js";
8
+ import { isOpenCodeZenModel, OPENCODE_ZEN_CATALOG } from "./catalog.js";
9
9
  import type { AccountRuntime } from "../../types.js";
10
10
 
11
11
  const OPENCODE_ZEN_TIER_RANKING = {
@@ -57,6 +57,15 @@ export const opencodeZenAdapter: ProviderAdapter = {
57
57
  return undefined;
58
58
  },
59
59
 
60
+ listModels(): ProviderModel[] {
61
+ return OPENCODE_ZEN_CATALOG.map((model) => ({
62
+ id: model.id,
63
+ contextWindow: model.contextWindow,
64
+ quotaPool: OPENCODE_ZEN_PROVIDER_ID,
65
+ source: "catalog",
66
+ }));
67
+ },
68
+
60
69
  ownsModel(model: string): boolean {
61
70
  return isOpenCodeZenModel(model);
62
71
  },