tuxevil-rotator 3.4.0 → 3.5.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [3.5.0] - 2026-09-03
6
+
7
+ ### Added
8
+ - **Live Antigravity model discovery**: Successful quota polls now reconcile model IDs, context windows, output limits, thinking metadata, and account availability into `/v1/models` without a second discovery request ([#29](https://github.com/tuxevil/tuxevil-rotator/pull/29) by [@javargasm](https://github.com/javargasm)).
9
+
10
+ ### Fixed
11
+ - **Dynamic catalog safety**: Discovery now excludes retired `gemini-3.5-*` IDs, keys snapshots by full account identity, honors case-insensitive operator `modelSpecs` substring overrides, and keeps removed dynamic models from falling through to the generic Gemini pool ([#29](https://github.com/tuxevil/tuxevil-rotator/pull/29) by [@javargasm](https://github.com/javargasm)).
12
+
5
13
  ## [3.4.0] - 2026-09-03
6
14
 
7
15
  ### Added
package/README.md CHANGED
@@ -54,6 +54,7 @@ Originally built as a multi-account rotator for Google Antigravity. It now gener
54
54
  ## Current Model Update
55
55
 
56
56
  - **Gemini 3.8 Flash Support**: Native Antigravity model IDs `gemini-3.8-flash-high`, `gemini-3.8-flash-medium`, and `gemini-3.8-flash-low`, with 1M-token context, 65,536-token output, pricing, quota routing, dashboard visualization, and telemetry support. Gemini 3.5 Flash has been removed from the user-facing catalog to match Antigravity 2.11. ([PR #28](https://github.com/tuxevil/tuxevil-rotator/pull/28) by [@CyR1en](https://github.com/CyR1en))
57
+ - **Dynamic Antigravity Discovery**: Successful quota polls reconcile live model IDs and metadata per full account identity. Newly advertised models appear in `/v1/models` and route only to accounts that advertised them; removed models disappear without falling back to the generic Gemini pool. Legacy `gemini-3.5-*` IDs stay hidden, and configured `modelSpecs` substring overrides retain precedence. ([PR #29](https://github.com/tuxevil/tuxevil-rotator/pull/29) by [@javargasm](https://github.com/javargasm))
57
58
 
58
59
  ## v3.2 Highlights
59
60
 
@@ -348,7 +349,7 @@ Thanks to these amazing people who have contributed to the project:
348
349
  - **[@CyR1en](https://github.com/CyR1en)** (Ethan Bacurio) — Added Gemini 3.6, Gemini 3.7, and Gemini 3.8 Flash model families, shared quota-pool routing, pricing, dashboard support, integration documentation, and regression coverage. ([PR #18](https://github.com/tuxevil/tuxevil-rotator/pull/18), [PR #21](https://github.com/tuxevil/tuxevil-rotator/pull/21), [PR #28](https://github.com/tuxevil/tuxevil-rotator/pull/28))
349
350
  - **[@josenicomaia](https://github.com/josenicomaia)** (José Nicodemos Maia Neto) — Modularized the compatibility layer architecture, added multimodal tool response support, fixed streaming pass-through for tool executions, and added PostgreSQL storage and weighted pool quota forecasting. ([PR #8](https://github.com/tuxevil/tuxevil-rotator/pull/8), [PR #9](https://github.com/tuxevil/tuxevil-rotator/pull/9), [PR #11](https://github.com/tuxevil/tuxevil-rotator/pull/11), [PR #13](https://github.com/tuxevil/tuxevil-rotator/pull/13), [PR #14](https://github.com/tuxevil/tuxevil-rotator/pull/14))
350
351
  - **[@yashyadav711](https://github.com/yashyadav711)** (Yash) — Fixed Draft-2020-12 inline JSON-Schema union type mapping for Gemini tools support. ([PR #10](https://github.com/tuxevil/tuxevil-rotator/pull/10))
351
- - **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) — Queued multi-request Antigravity account pooling (5×5 concurrent streams), strict FIFO overflow queue, dashboard concurrency metrics, canonical project ID resolution, 429 quota resilience with account-scoped retry, synchronous leasing, snapshot-based token refresh with generation validation, provider-scoped token publication, spend-logger memory leak fix, atomic PostgreSQL CTE daily spend aggregation with idempotent retries, virtual-key cache bounding, Anthropic tool-use compatibility layer (`tool_use`/`tool_result` content block conversion), JSON schema round-trip fixes, compat test suite expansion, model-scoped cooldowns, explicit Antigravity reset-duration parsing, idle pool normalization, RAW POLL deadline reconciliation, serialized per-account quota polling, and Ollama kickstart routing for multi-provider accounts. ([PR #3](https://github.com/tuxevil/tuxevil-rotator/pull/3), [PR #7](https://github.com/tuxevil/tuxevil-rotator/pull/7), [PR #22](https://github.com/tuxevil/tuxevil-rotator/pull/22), [PR #23](https://github.com/tuxevil/tuxevil-rotator/pull/23), [PR #24](https://github.com/tuxevil/tuxevil-rotator/pull/24), [PR #26](https://github.com/tuxevil/tuxevil-rotator/pull/26))
352
+ - **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) — Queued multi-request Antigravity account pooling (5×5 concurrent streams), strict FIFO overflow queue, dashboard concurrency metrics, canonical project ID resolution, account-scoped dynamic Antigravity discovery and routing, 429 quota resilience with account-scoped retry, synchronous leasing, snapshot-based token refresh with generation validation, provider-scoped token publication, spend-logger memory leak fix, atomic PostgreSQL CTE daily spend aggregation with idempotent retries, virtual-key cache bounding, Anthropic tool-use compatibility layer (`tool_use`/`tool_result` content block conversion), JSON schema round-trip fixes, compat test suite expansion, model-scoped cooldowns, explicit Antigravity reset-duration parsing, idle pool normalization, RAW POLL deadline reconciliation, serialized per-account quota polling, and Ollama kickstart routing for multi-provider accounts. ([PR #3](https://github.com/tuxevil/tuxevil-rotator/pull/3), [PR #7](https://github.com/tuxevil/tuxevil-rotator/pull/7), [PR #22](https://github.com/tuxevil/tuxevil-rotator/pull/22), [PR #23](https://github.com/tuxevil/tuxevil-rotator/pull/23), [PR #24](https://github.com/tuxevil/tuxevil-rotator/pull/24), [PR #26](https://github.com/tuxevil/tuxevil-rotator/pull/26), [PR #29](https://github.com/tuxevil/tuxevil-rotator/pull/29))
352
353
 
353
354
  ## Development
354
355
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tuxevil-rotator",
3
- "version": "3.4.0",
3
+ "version": "3.5.0",
4
4
  "description": "Multi-provider, multi-account AI proxy rotator with per-model routing, real-time quota tracking, and infringement detection (Google Antigravity, Ollama Cloud)",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,70 @@
1
+ import { createHash } from "node:crypto";
2
+ import { normalizeAccountConfig } from "./config-normalize.js";
3
+ import type {
4
+ AccountConfig,
5
+ AccountRuntime,
6
+ ProviderCredential,
7
+ } from "./types.js";
8
+ import {
9
+ DEFAULT_PROVIDER,
10
+ getProviderProjectId,
11
+ } from "./providers/credential-helpers.js";
12
+
13
+ function credentialFingerprint(secret?: string): string {
14
+ if (!secret) return "";
15
+ // SHA-256 is intentional: this is a non-secret deduplication fingerprint, not a
16
+ // password hash. It must be deterministic and fast (bcrypt/argon2 would be wrong here).
17
+ // codeql[js/insufficient-password-hash]
18
+ return createHash("sha256").update(secret).digest("hex").slice(0, 12);
19
+ }
20
+
21
+ export function getProviderCredentialDetails(
22
+ norm: AccountConfig,
23
+ cred?: ProviderCredential,
24
+ ): {
25
+ provider: string;
26
+ projectId: string;
27
+ providerAccountId: string;
28
+ secret: string;
29
+ fingerprint: string;
30
+ } {
31
+ const provider = cred?.provider ?? DEFAULT_PROVIDER;
32
+ const projectId = getProviderProjectId(norm, provider);
33
+ let providerAccountId = cred?.providerAccountId || "";
34
+ let secret = cred?.refreshToken || cred?.apiKey || "";
35
+
36
+ if (provider === "google-antigravity") {
37
+ secret ||= norm.refreshToken || norm.apiKey || "";
38
+ } else if (provider === "openai-codex") {
39
+ providerAccountId ||= norm.codexAccountId || "";
40
+ secret ||= norm.codexRefreshToken || "";
41
+ }
42
+
43
+ const fingerprint = !projectId && !providerAccountId && secret
44
+ ? credentialFingerprint(secret)
45
+ : "";
46
+ return { provider, projectId, providerAccountId, secret, fingerprint };
47
+ }
48
+
49
+ export function getAccountIdentity(
50
+ account: AccountConfig | AccountRuntime,
51
+ ): string {
52
+ const config = "config" in account ? account.config : account;
53
+ const norm = normalizeAccountConfig(config);
54
+ const email = norm.email.toLowerCase().trim();
55
+ const creds = (norm.credentials ?? [])
56
+ .slice()
57
+ .sort((a, b) => a.provider.localeCompare(b.provider))
58
+ .map((credential) => {
59
+ const details = getProviderCredentialDetails(norm, credential);
60
+ return `${details.provider}:${details.projectId}:${details.providerAccountId}:${details.fingerprint}`;
61
+ })
62
+ .join("|");
63
+ if (!creds) {
64
+ const details = getProviderCredentialDetails(norm, {
65
+ provider: DEFAULT_PROVIDER,
66
+ });
67
+ return `${email}#${details.provider}:${details.projectId}:${details.providerAccountId}:${details.fingerprint}`;
68
+ }
69
+ return `${email}#${creds}`;
70
+ }
@@ -1,3 +1,5 @@
1
+ import { dynamicCatalog } from "../providers/google-antigravity/dynamic-catalog.js";
2
+
1
3
  export interface ModelSpec {
2
4
  maxOutputTokens: number;
3
5
  thinkingBudget: number; // -1 = adaptive (model decides), >=0 = fixed
@@ -40,8 +42,12 @@ let modelSpecsOverride: Record<string, ModelSpec> | null = null;
40
42
  * Replace the bundled model spec table with operator-provided overrides.
41
43
  * Pass `null` to restore defaults. Called once at startup from index.ts.
42
44
  */
43
- export function setModelSpecsOverride(specs: Record<string, ModelSpec> | null): void {
44
- modelSpecsOverride = specs && Object.keys(specs).length > 0 ? specs : null;
45
+ export function setModelSpecsOverride(specs: Record<string, ModelSpec> | null): void {
46
+ modelSpecsOverride = specs && Object.keys(specs).length > 0
47
+ ? Object.fromEntries(
48
+ Object.entries(specs).map(([key, spec]) => [key.toLowerCase(), spec]),
49
+ )
50
+ : null;
45
51
  }
46
52
 
47
53
  export function getActiveModelSpecs(): Record<string, ModelSpec> {
@@ -60,13 +66,23 @@ export function getModelFamily(model: string): "claude" | "gemini" | "unknown" {
60
66
  return "unknown";
61
67
  }
62
68
 
63
- export function getModelSpec(model: string): ModelSpec {
64
- const specs = getActiveModelSpecs();
65
- const lower = model.toLowerCase();
66
- if (specs[lower]) return specs[lower];
67
- for (const [key, spec] of Object.entries(specs)) {
68
- if (lower.includes(key)) return spec;
69
- }
69
+ export function getModelSpec(model: string): ModelSpec {
70
+ const lower = model.toLowerCase();
71
+ if (modelSpecsOverride) {
72
+ if (modelSpecsOverride[lower]) return modelSpecsOverride[lower];
73
+ for (const [key, spec] of Object.entries(modelSpecsOverride)) {
74
+ if (lower.includes(key)) return spec;
75
+ }
76
+ } else if (DEFAULT_MODEL_SPECS[lower]) {
77
+ return DEFAULT_MODEL_SPECS[lower];
78
+ }
79
+ const dynamicSpec = dynamicCatalog.getModelSpec(lower);
80
+ if (dynamicSpec) return dynamicSpec;
81
+ if (!modelSpecsOverride) {
82
+ for (const [key, spec] of Object.entries(DEFAULT_MODEL_SPECS)) {
83
+ if (lower.includes(key)) return spec;
84
+ }
85
+ }
70
86
  const family = getModelFamily(model);
71
87
  if (family === "claude") return { maxOutputTokens: CLAUDE_MAX_OUTPUT_TOKENS, thinkingBudget: CLAUDE_DEFAULT_THINKING_BUDGET, isThinking: true, contextWindow: 1_000_000 };
72
88
  if (family === "gemini") return { maxOutputTokens: GEMINI_MAX_OUTPUT_TOKENS, thinkingBudget: FALLBACK_THINKING_BUDGET, isThinking: true, contextWindow: 1_000_000 };
package/src/compat.ts CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  sanitizeGeminiSchema,
29
29
  sanitizeClaudeViaGeminiSchema,
30
30
  } from "./compat/schema-sanitizer.js";
31
+ import { dynamicCatalog } from "./providers/google-antigravity/dynamic-catalog.js";
31
32
  import {
32
33
  DEFAULT_MODEL_SPECS,
33
34
  setModelSpecsOverride,
@@ -515,6 +516,10 @@ function recordCompatOutcome(
515
516
  inputTokens: completion?.inputTokens ?? 0,
516
517
  outputTokens: completion?.outputTokens ?? 0,
517
518
  });
519
+ rotator.recordProxyEvent(
520
+ `[${context.requestId}] COMPAT END account=${context.label} model=${context.displayModelKey} status=${statusCode} ttfbMs=${ttfbMs} totalMs=${totalMs} inTokens=${completion?.inputTokens ?? 0} outTokens=${completion?.outputTokens ?? 0}`,
521
+ "info",
522
+ );
518
523
  logSpend({
519
524
  requestId: context.requestId,
520
525
  apiKeyHash: options?.apiKeyHash || null,
@@ -2089,23 +2094,44 @@ export interface OpenAIModelCatalogEntry {
2089
2094
  meta: Record<string, unknown>;
2090
2095
  }
2091
2096
 
2097
+ export interface CompatModelEntry {
2098
+ id: string;
2099
+ family: string;
2100
+ ctx: number;
2101
+ quotaPool: string;
2102
+ multimodal: boolean;
2103
+ tools: boolean;
2104
+ }
2105
+
2106
+ export function getEffectiveAntigravityModels(): CompatModelEntry[] {
2107
+ const dynamic = dynamicCatalog.getAllModels();
2108
+ const seen = new Set(MODEL_CATALOG.map((model) => model.id.toLowerCase()));
2109
+ const result: CompatModelEntry[] = MODEL_CATALOG.map((model) => ({ ...model }));
2110
+ for (const m of dynamic) {
2111
+ if (seen.has(m.id.toLowerCase())) continue;
2112
+ seen.add(m.id.toLowerCase());
2113
+ result.push({
2114
+ id: m.id,
2115
+ family: m.family,
2116
+ ctx: m.ctx,
2117
+ quotaPool: m.quotaPool,
2118
+ multimodal: m.multimodal,
2119
+ tools: m.tools,
2120
+ });
2121
+ }
2122
+ return result;
2123
+ }
2124
+
2092
2125
  /**
2093
- * Build the full OpenAI-compatible model catalog (static Antigravity catalog
2094
- * + active-provider models for Ollama, OpenAI Codex and OpenCode Zen).
2095
- *
2096
- * This is the single source of truth for "what models can the rotator route
2097
- * today" and is consumed by:
2098
- * - the public /v1/models endpoint (OpenAI compat)
2099
- * - the admin /api/models endpoint (dashboard virtual key editor)
2126
+ * Build the OpenAI-compatible `/v1/models` catalog for the proxy.
2100
2127
  *
2101
- * Pass the live AccountRotator so dynamic provider catalogs (Ollama tags
2102
- * fetched at startup, Codex base + discovered models) are included. Without
2103
- * a rotator, only the static MODEL_CATALOG is returned.
2128
+ * The static Antigravity baseline and dynamically-discovered Antigravity models
2129
+ * are always included. An active rotator also contributes its other providers.
2104
2130
  */
2105
2131
  export function buildOpenAIModelCatalog(
2106
2132
  rotator?: AccountRotator,
2107
2133
  ): OpenAIModelCatalogEntry[] {
2108
- const catalog: OpenAIModelCatalogEntry[] = MODEL_CATALOG.map(
2134
+ const catalog: OpenAIModelCatalogEntry[] = getEffectiveAntigravityModels().map(
2109
2135
  ({ id, ctx, family, quotaPool, multimodal, tools }) => ({
2110
2136
  id,
2111
2137
  object: "model",
@@ -2195,7 +2221,7 @@ export function serveOpenAIModels(
2195
2221
 
2196
2222
  export function serveGeminiModels(res: ServerResponse): void {
2197
2223
  writeJson(res, 200, {
2198
- models: MODEL_CATALOG.map(
2224
+ models: getEffectiveAntigravityModels().map(
2199
2225
  ({ id, ctx, family, quotaPool, multimodal, tools }) => ({
2200
2226
  name: `models/${id}`,
2201
2227
  baseModelId: family,
@@ -9,6 +9,8 @@
9
9
  // Values reflect input/context window only. Output max tokens are tracked
10
10
  // separately in `src/compat/model-specs.ts` via `maxOutputTokens`.
11
11
 
12
+ import { dynamicCatalog } from "./dynamic-catalog.js";
13
+
12
14
  export interface AntigravityModelSpec {
13
15
  id: string;
14
16
  contextWindow: number;
@@ -71,10 +73,11 @@ const FALLBACK_CONTEXT_WINDOW = 128_000;
71
73
  * Resolve the upstream-published context window for an Antigravity model id.
72
74
  *
73
75
  * Lookup order:
74
- * 1. Exact id match (lowercased).
75
- * 2. Substring match across the table (longest key wins via the order here).
76
- * 3. Family defaults: claude -> 1M, gemini -> 1M, gpt-oss -> 131_072.
77
- * 4. Defensive fallback: 128_000.
76
+ * 1. Exact id match in static table (lowercased).
77
+ * 2. Dynamic catalog entry from live Antigravity endpoint.
78
+ * 3. Substring match across the table (longest key wins via the order here).
79
+ * 4. Family defaults: claude -> 1M, gemini -> 1M, gpt-oss -> 131_072.
80
+ * 5. Defensive fallback: 128_000.
78
81
  */
79
82
  export function getAntigravityContextWindow(model: string): number {
80
83
  if (!model) return FALLBACK_CONTEXT_WINDOW;
@@ -82,6 +85,8 @@ export function getAntigravityContextWindow(model: string): number {
82
85
  if (!lower) return FALLBACK_CONTEXT_WINDOW;
83
86
  const exact = ANTIGRAVITY_CONTEXT_WINDOWS[lower];
84
87
  if (typeof exact === "number") return exact;
88
+ const dynamicCtx = dynamicCatalog.getContextWindow(lower);
89
+ if (typeof dynamicCtx === "number") return dynamicCtx;
85
90
  // Substring fallback: pick the longest registered key that appears in lower.
86
91
  let best: { key: string; value: number } | null = null;
87
92
  for (const [key, value] of Object.entries(ANTIGRAVITY_CONTEXT_WINDOWS)) {
@@ -0,0 +1,252 @@
1
+ // Dynamic Google Antigravity model availability discovered during quota polling.
2
+
3
+ import type { ModelSpec } from "../../compat/model-specs.js";
4
+ import type { GoogleQuotaResponse } from "../../types.js";
5
+
6
+ export interface DynamicModelEntry {
7
+ id: string;
8
+ family: string;
9
+ ctx: number;
10
+ quotaPool: string;
11
+ multimodal: boolean;
12
+ tools: boolean;
13
+ maxOutputTokens: number;
14
+ thinkingBudget: number;
15
+ isThinking: boolean;
16
+ isTiered: boolean;
17
+ displayName?: string;
18
+ }
19
+
20
+ const DEFAULT_ACCOUNT_KEY = "__default__";
21
+
22
+ function accountKey(value: string): string {
23
+ return value.trim();
24
+ }
25
+
26
+ function familyDefaults(
27
+ family: string,
28
+ ): Pick<
29
+ DynamicModelEntry,
30
+ "ctx" | "multimodal" | "tools" | "maxOutputTokens" | "thinkingBudget" | "isThinking"
31
+ > {
32
+ if (family === "gpt-oss") {
33
+ return {
34
+ ctx: 131_072,
35
+ multimodal: false,
36
+ tools: true,
37
+ maxOutputTokens: 32_768,
38
+ thinkingBudget: 8_192,
39
+ isThinking: true,
40
+ };
41
+ }
42
+ if (family.includes("claude")) {
43
+ return {
44
+ ctx: 1_000_000,
45
+ multimodal: true,
46
+ tools: true,
47
+ maxOutputTokens: 64_000,
48
+ thinkingBudget: 32_768,
49
+ isThinking: true,
50
+ };
51
+ }
52
+ if (family.includes("gemini")) {
53
+ return {
54
+ ctx: 1_000_000,
55
+ multimodal: true,
56
+ tools: true,
57
+ maxOutputTokens: 65_536,
58
+ thinkingBudget: 24_576,
59
+ isThinking: true,
60
+ };
61
+ }
62
+ return {
63
+ ctx: 128_000,
64
+ multimodal: false,
65
+ tools: true,
66
+ maxOutputTokens: 65_536,
67
+ thinkingBudget: 24_576,
68
+ isThinking: false,
69
+ };
70
+ }
71
+
72
+ export class DynamicModelRegistry {
73
+ private static instance: DynamicModelRegistry | null = null;
74
+ private accountModels = new Map<string, Map<string, DynamicModelEntry>>();
75
+ private defaultAgentModelIds = new Map<string, string>();
76
+ private discoveredModelIds = new Set<string>();
77
+
78
+ static getInstance(): DynamicModelRegistry {
79
+ DynamicModelRegistry.instance ??= new DynamicModelRegistry();
80
+ return DynamicModelRegistry.instance;
81
+ }
82
+
83
+ /** Reset dynamic account state (primarily for tests). */
84
+ reset(): void {
85
+ this.accountModels.clear();
86
+ this.defaultAgentModelIds.clear();
87
+ this.discoveredModelIds.clear();
88
+ }
89
+
90
+ /** Derive the model family and quota pool from a model ID string. */
91
+ static inferFamilyAndPool(modelId: string): { family: string; quotaPool: string } {
92
+ const lower = modelId.toLowerCase();
93
+ if (lower.includes("claude") || lower.includes("sonnet") || lower.includes("opus")) {
94
+ const match = lower.match(/(claude-[a-z0-9.-]+)/);
95
+ return { family: match?.[1] ?? "claude", quotaPool: "claude" };
96
+ }
97
+ if (lower.includes("gpt-oss")) {
98
+ return { family: "gpt-oss", quotaPool: "claude" };
99
+ }
100
+ if (lower.includes("gemini")) {
101
+ const match = lower.match(/(gemini-[0-9.]+-?[a-z]*)/);
102
+ return { family: match?.[1] ?? "gemini", quotaPool: "gemini" };
103
+ }
104
+ return { family: lower, quotaPool: "gemini" };
105
+ }
106
+
107
+ /** Replace one account's advertised models with its latest successful response. */
108
+ updateFromEndpointResponse(
109
+ data: GoogleQuotaResponse,
110
+ accountId = DEFAULT_ACCOUNT_KEY,
111
+ ): number {
112
+ if (!data || typeof data !== "object" || !data.models) return 0;
113
+
114
+ const key = accountKey(accountId);
115
+ const previous = this.accountModels.get(key);
116
+ const knownBefore = new Set(this.getAllModels().map((model) => model.id.toLowerCase()));
117
+ const next = new Map<string, DynamicModelEntry>();
118
+ const tieredIds = new Set(
119
+ Object.values(data.tieredModelIds ?? {}).flat().map((id) => id.trim().toLowerCase()),
120
+ );
121
+ let newModelsCount = 0;
122
+
123
+ if (data.defaultAgentModelId) {
124
+ this.defaultAgentModelIds.delete(key);
125
+ this.defaultAgentModelIds.set(key, data.defaultAgentModelId);
126
+ } else {
127
+ this.defaultAgentModelIds.delete(key);
128
+ }
129
+
130
+ for (const [rawId, info] of Object.entries(data.models)) {
131
+ const normalizedId = rawId.trim();
132
+ const lowerId = normalizedId.toLowerCase();
133
+ if (
134
+ !lowerId ||
135
+ lowerId.startsWith("chat_") ||
136
+ lowerId.startsWith("tab_") ||
137
+ lowerId.startsWith("gemini-3.5-")
138
+ ) continue;
139
+
140
+ this.discoveredModelIds.add(lowerId);
141
+ const { family, quotaPool } = DynamicModelRegistry.inferFamilyAndPool(normalizedId);
142
+ const defaults = previous?.get(lowerId) ?? familyDefaults(family);
143
+ const isTiered = lowerId.includes("-tiered") || tieredIds.has(lowerId);
144
+ const hasThinkingBudget = typeof info.thinkingBudget === "number";
145
+ const thinkingBudget = hasThinkingBudget
146
+ ? info.thinkingBudget!
147
+ : isTiered
148
+ ? -1
149
+ : defaults.thinkingBudget;
150
+ const isThinking = typeof info.supportsThinking === "boolean"
151
+ ? info.supportsThinking
152
+ : hasThinkingBudget
153
+ ? thinkingBudget !== 0
154
+ : defaults.isThinking;
155
+ const hasMultimodalMetadata =
156
+ typeof info.supportsImages === "boolean" || typeof info.supportsVideo === "boolean";
157
+
158
+ next.set(lowerId, {
159
+ id: normalizedId,
160
+ family,
161
+ ctx: typeof info.maxTokens === "number" && info.maxTokens > 0
162
+ ? info.maxTokens
163
+ : defaults.ctx,
164
+ quotaPool,
165
+ multimodal: hasMultimodalMetadata
166
+ ? Boolean(info.supportsImages || info.supportsVideo)
167
+ : defaults.multimodal,
168
+ tools: defaults.tools,
169
+ maxOutputTokens:
170
+ typeof info.maxOutputTokens === "number" && info.maxOutputTokens > 0
171
+ ? info.maxOutputTokens
172
+ : defaults.maxOutputTokens,
173
+ thinkingBudget,
174
+ isThinking,
175
+ isTiered,
176
+ displayName: info.displayName ?? previous?.get(lowerId)?.displayName ?? normalizedId,
177
+ });
178
+ if (!knownBefore.has(lowerId)) newModelsCount++;
179
+ }
180
+
181
+ this.accountModels.set(key, next);
182
+ return newModelsCount;
183
+ }
184
+
185
+ /** Expire catalogs belonging to accounts that are no longer active. */
186
+ retainAccounts(accountIds: Iterable<string>): void {
187
+ const active = new Set(Array.from(accountIds, accountKey));
188
+ for (const key of this.accountModels.keys()) {
189
+ if (!active.has(key)) this.accountModels.delete(key);
190
+ }
191
+ for (const key of this.defaultAgentModelIds.keys()) {
192
+ if (!active.has(key)) this.defaultAgentModelIds.delete(key);
193
+ }
194
+ }
195
+
196
+ getAllModels(): DynamicModelEntry[] {
197
+ const models = new Map<string, DynamicModelEntry>();
198
+ for (const accountCatalog of this.accountModels.values()) {
199
+ for (const [id, model] of accountCatalog) models.set(id, model);
200
+ }
201
+ return Array.from(models.values());
202
+ }
203
+
204
+ getModel(id: string): DynamicModelEntry | undefined {
205
+ let match: DynamicModelEntry | undefined;
206
+ const lowerId = id.toLowerCase();
207
+ for (const accountCatalog of this.accountModels.values()) {
208
+ match = accountCatalog.get(lowerId) ?? match;
209
+ }
210
+ return match;
211
+ }
212
+
213
+ hasModelForAccount(accountId: string, id: string): boolean {
214
+ return this.accountModels
215
+ .get(accountKey(accountId))
216
+ ?.has(id.trim().toLowerCase()) ?? false;
217
+ }
218
+
219
+ wasDiscovered(id: string): boolean {
220
+ return this.discoveredModelIds.has(id.trim().toLowerCase());
221
+ }
222
+
223
+ getModelSpec(id: string): ModelSpec | undefined {
224
+ const entry = this.getModel(id);
225
+ if (!entry) return undefined;
226
+ return {
227
+ maxOutputTokens: entry.maxOutputTokens,
228
+ thinkingBudget: entry.thinkingBudget,
229
+ isThinking: entry.isThinking,
230
+ contextWindow: entry.ctx,
231
+ };
232
+ }
233
+
234
+ getContextWindow(id: string): number | undefined {
235
+ return this.getModel(id)?.ctx;
236
+ }
237
+
238
+ isTiered(id: string): boolean {
239
+ const lowerId = id.toLowerCase();
240
+ return lowerId.includes("-tiered") || (this.getModel(lowerId)?.isTiered ?? false);
241
+ }
242
+
243
+ resolveQuotaPool(id: string): string | undefined {
244
+ return this.getModel(id)?.quotaPool;
245
+ }
246
+
247
+ getDefaultAgentModelId(): string | null {
248
+ return Array.from(this.defaultAgentModelIds.values()).at(-1) ?? null;
249
+ }
250
+ }
251
+
252
+ export const dynamicCatalog = DynamicModelRegistry.getInstance();
@@ -12,11 +12,14 @@ import {
12
12
  QUOTA_MODEL_KEYS,
13
13
  } from "../../types.js";
14
14
  import { fetchWithRetry } from "../../fetch-with-retry.js";
15
+ import { getAccountIdentity } from "../../account-identity.js";
15
16
  import type { QuotaFetchContext } from "../adapter.js";
16
17
  import { DEFAULT_PROVIDER, getProviderProjectId } from "../credential-helpers.js";
17
18
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
18
19
  import { sortQuotaPools } from "../registry.js";
19
20
 
21
+ import { dynamicCatalog, DynamicModelRegistry } from "./dynamic-catalog.js";
22
+
20
23
  /**
21
24
  * Extract per-model quotas from a Google quota response, preserving the
22
25
  * previously classified timer type when the reset time is unchanged.
@@ -38,6 +41,15 @@ export function extractQuotas(
38
41
  }
39
42
  }
40
43
 
44
+ if (!modelInfo) {
45
+ for (const [modelKey, info] of Object.entries(data.models)) {
46
+ if (DynamicModelRegistry.inferFamilyAndPool(modelKey).quotaPool === config.key) {
47
+ modelInfo = info;
48
+ break;
49
+ }
50
+ }
51
+ }
52
+
41
53
  if (modelInfo?.quotaInfo) {
42
54
  const remainingFraction = modelInfo.quotaInfo.remainingFraction ?? 0;
43
55
  // Google can publish a nominal reset for an untouched pool; no usage means
@@ -119,6 +131,15 @@ export async function fetchProviderQuota(
119
131
  }
120
132
 
121
133
  const data = (await response.json()) as GoogleQuotaResponse;
134
+ const newModels = dynamicCatalog.updateFromEndpointResponse(
135
+ data,
136
+ getAccountIdentity(account),
137
+ );
138
+ if (newModels > 0) {
139
+ ctx.log(
140
+ `${account.config.email}: discovered ${newModels} Antigravity model(s) from quota response`,
141
+ );
142
+ }
122
143
  const oldQuota = account.quota || [];
123
144
  const fresh = extractQuotas(data, oldQuota);
124
145
  // Drop the previous Antigravity entries so the new ones fully replace
@@ -841,20 +841,35 @@ export function convertResponsesToChatRequest(
841
841
  * reasoning_effort. Matched case-insensitively against the exact ID only;
842
842
  * virtual siblings (e.g. `gemini-3.7-flash-tiered-high`) are excluded.
843
843
  */
844
+ import { dynamicCatalog } from "./dynamic-catalog.js";
845
+
844
846
  export const TIERED_EFFORT_MODEL_ID = "gemini-3.7-flash-tiered";
847
+ export const TIERED_EFFORT_MODEL_IDS = new Set([
848
+ "gemini-3.7-flash-tiered",
849
+ ]);
850
+
851
+ export function isTieredEffortModel(modelId: string): boolean {
852
+ const l = modelId.toLowerCase().trim();
853
+ if (l.includes("3.6")) return false;
854
+ if (TIERED_EFFORT_MODEL_IDS.has(l)) return true;
855
+ // Exclude virtual siblings like gemini-X-tiered-high
856
+ if (l.includes("-tiered-")) return false;
857
+ if (l.endsWith("-tiered")) return true;
858
+ return dynamicCatalog.isTiered(l);
859
+ }
845
860
 
846
861
  /**
847
862
  * Map an OpenAI Chat `reasoning_effort` to a Gemini `thinkingLevel` for
848
- * `gemini-3.7-flash-tiered` only. Accepts exactly low/medium/high
849
- * (case-insensitive); anything else returns undefined so the caller falls
850
- * back to the existing adaptive/fixed-budget semantics and never emits an
851
- * invalid upstream enum.
863
+ * tiered models (`gemini-3.7-flash-tiered`) only.
864
+ * Accepts exactly low/medium/high (case-insensitive); anything else returns
865
+ * undefined so the caller falls back to the existing adaptive/fixed-budget
866
+ * semantics and never emits an invalid upstream enum.
852
867
  */
853
868
  export function mapTieredReasoningEffortToThinkingLevel(
854
869
  effort: string | undefined,
855
870
  modelId: string,
856
871
  ): "LOW" | "MEDIUM" | "HIGH" | undefined {
857
- if (modelId.toLowerCase() !== TIERED_EFFORT_MODEL_ID) return undefined;
872
+ if (!isTieredEffortModel(modelId)) return undefined;
858
873
  if (!isNonEmptyString(effort)) return undefined;
859
874
  switch (effort.toLowerCase()) {
860
875
  case "low":
package/src/proxy.ts CHANGED
@@ -1280,7 +1280,22 @@ export async function withRotation<T>(
1280
1280
  // success
1281
1281
  const result = await onSuccess(response, context);
1282
1282
  const shouldRotate = rotator.recordRequest(account, model);
1283
- logRequestEnd(response.status, `endpoint=${endpoint}`);
1283
+ const inTokens =
1284
+ result && typeof result === "object" && "inputTokens" in result
1285
+ ? (result as Record<string, unknown>).inputTokens
1286
+ : 0;
1287
+ const outTokens =
1288
+ result && typeof result === "object" && "outputTokens" in result
1289
+ ? (result as Record<string, unknown>).outputTokens
1290
+ : 0;
1291
+ const ttfbMs =
1292
+ result && typeof result === "object" && "firstByteMs" in result
1293
+ ? (result as Record<string, unknown>).firstByteMs
1294
+ : undefined;
1295
+ const ttfbInfo = ttfbMs !== undefined ? ` ttfbMs=${ttfbMs}` : "";
1296
+ const tokensInfo =
1297
+ inTokens || outTokens ? ` inTokens=${inTokens} outTokens=${outTokens}` : "";
1298
+ logRequestEnd(response.status, `endpoint=${endpoint}${ttfbInfo}${tokensInfo}`);
1284
1299
  if (shouldRotate) {
1285
1300
  await rotator.rotateToNext(model, account);
1286
1301
  }
@@ -1750,7 +1765,7 @@ async function handleProxyRequest(
1750
1765
  const ttfbMs = usage?.firstByteMs ?? totalMs;
1751
1766
  const outcomeStatus = usage?.streamError ? 502 : response.status;
1752
1767
  rotator.recordLatency(body.displayModel || body.model, ttfbMs, totalMs);
1753
- logRequestEnd(outcomeStatus, `ttfbMs=${ttfbMs} endpoint=${endpoint}`);
1768
+ logRequestEnd(outcomeStatus, `ttfbMs=${ttfbMs} inTokens=${usage?.inputTokens ?? 0} outTokens=${usage?.outputTokens ?? 0} endpoint=${endpoint}`);
1754
1769
  rotator.recordRequestLog({
1755
1770
  model: displayModelKey,
1756
1771
  account: label,
package/src/rotator.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { createHash } from "node:crypto";
2
1
  import {
3
2
  type AccountConfig,
4
3
  type AccountRuntime,
@@ -9,7 +8,6 @@ import {
9
8
  type ModelQuota,
10
9
  type ModelRotationState,
11
10
  type PersistedState,
12
- type ProviderCredential,
13
11
  type RoutingAccountDiagnostic,
14
12
  type RoutingModelDiagnostics,
15
13
  type RoutingRejectionReason,
@@ -17,8 +15,8 @@ import {
17
15
  type TokenBucket,
18
16
  type TokenUsageData,
19
17
  type TokenUsageTiered,
20
- MODEL_PRICING,
21
18
  MODEL_TIER_ACCESS,
19
+ getModelPricing,
22
20
  QUOTA_USER_AGENT,
23
21
  REQUEST_GOOG_API_CLIENT,
24
22
  REQUEST_CLIENT_METADATA,
@@ -29,9 +27,11 @@ import {
29
27
  DEFAULT_QUOTA_POLL_INTERVAL_MS,
30
28
  MAX_QUOTA_POLL_INTERVAL_MS,
31
29
  MIN_QUOTA_POLL_INTERVAL_MS,
30
+ isStaticAntigravityModel,
32
31
  resolveQuotaModelKey,
33
32
  resolveDisplayModelKey,
34
33
  } from "./types.js";
34
+ import { dynamicCatalog } from "./providers/google-antigravity/dynamic-catalog.js";
35
35
  import {
36
36
  reportFlagEvent,
37
37
  FLAG_PATTERNS,
@@ -88,59 +88,15 @@ import {
88
88
  parseRetryAfterMs,
89
89
  RESOURCE_EXHAUSTED_FALLBACK_MS,
90
90
  } from "./rate-limit-parser.js";
91
+ import {
92
+ getAccountIdentity,
93
+ getProviderCredentialDetails,
94
+ } from "./account-identity.js";
91
95
 
92
- function credentialFingerprint(secret?: string): string {
93
- if (!secret) return "";
94
- // SHA-256 is intentional: this is a non-secret deduplication fingerprint, not a
95
- // password hash. It must be deterministic and fast (bcrypt/argon2 would be wrong here).
96
- // codeql[js/insufficient-password-hash]
97
- return createHash("sha256").update(secret).digest("hex").slice(0, 12);
98
- }
99
-
100
- export function getProviderCredentialDetails(
101
- norm: AccountConfig,
102
- cred?: ProviderCredential,
103
- ): {
104
- provider: string;
105
- projectId: string;
106
- providerAccountId: string;
107
- secret: string;
108
- fingerprint: string;
109
- } {
110
- const provider = cred?.provider ?? DEFAULT_PROVIDER;
111
- const projectId = getProviderProjectId(norm, provider);
112
- let providerAccountId = cred?.providerAccountId || "";
113
- let secret = cred?.refreshToken || cred?.apiKey || "";
114
-
115
- if (provider === "google-antigravity") {
116
- secret ||= norm.refreshToken || norm.apiKey || "";
117
- } else if (provider === "openai-codex") {
118
- providerAccountId ||= norm.codexAccountId || "";
119
- secret ||= norm.codexRefreshToken || "";
120
- }
121
-
122
- const fingerprint = !projectId && !providerAccountId && secret ? credentialFingerprint(secret) : "";
123
- return { provider, projectId, providerAccountId, secret, fingerprint };
124
- }
125
-
126
- export function getAccountIdentity(account: AccountConfig | AccountRuntime): string {
127
- const config = "config" in account ? account.config : account;
128
- const norm = normalizeAccountConfig(config);
129
- const email = norm.email.toLowerCase().trim();
130
- const creds = (norm.credentials ?? [])
131
- .slice()
132
- .sort((a, b) => a.provider.localeCompare(b.provider))
133
- .map((c) => {
134
- const details = getProviderCredentialDetails(norm, c);
135
- return `${details.provider}:${details.projectId}:${details.providerAccountId}:${details.fingerprint}`;
136
- })
137
- .join("|");
138
- if (!creds) {
139
- const details = getProviderCredentialDetails(norm, { provider: DEFAULT_PROVIDER });
140
- return `${email}#${details.provider}:${details.projectId}:${details.providerAccountId}:${details.fingerprint}`;
141
- }
142
- return `${email}#${creds}`;
143
- }
96
+ export {
97
+ getAccountIdentity,
98
+ getProviderCredentialDetails,
99
+ } from "./account-identity.js";
144
100
 
145
101
  export function areAccountIdentitiesCompatible(
146
102
  incomingConfig: AccountConfig,
@@ -904,6 +860,11 @@ export class AccountRotator {
904
860
  void this.refreshOllamaCatalogOnce().catch(() => {});
905
861
 
906
862
  const available = this.accounts.filter((a) => !a.disabled && !a.flagged);
863
+ dynamicCatalog.retainAccounts(
864
+ available
865
+ .filter((account) => hasCredential(account.config, DEFAULT_PROVIDER))
866
+ .map(getAccountIdentity),
867
+ );
907
868
  let quotaPublished = false;
908
869
  for (const account of available) {
909
870
  if (await this.pollAccountQuota(account)) {
@@ -1000,10 +961,13 @@ export class AccountRotator {
1000
961
 
1001
962
  // Get quota % for a specific model on an account. Returns -1 if no data.
1002
963
  private getModelQuota(account: AccountRuntime, modelKey: string): number {
1003
- const q = account.quota.find((q) => q.modelKey === modelKey) ??
1004
- (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
964
+ const quotaKey = isStaticAntigravityModel(modelKey)
965
+ ? modelKey
966
+ : dynamicCatalog.resolveQuotaPool(modelKey) ?? modelKey;
967
+ const q = account.quota.find((q) => q.modelKey === quotaKey) ??
968
+ (quotaKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
1005
969
  ? account.quota.find((candidate) => candidate.modelKey === CODEX_QUOTA_MODEL_KEY)
1006
- : modelKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
970
+ : quotaKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
1007
971
  ? account.quota.find((candidate) => candidate.providerId === OPENCODE_ZEN_PROVIDER_ID)
1008
972
  : undefined);
1009
973
  if (!q) return -1;
@@ -1011,7 +975,7 @@ export class AccountRotator {
1011
975
  // quota is fully exhausted (0%), the account cannot accept any requests
1012
976
  // regardless of how much session quota remains. Treat it as 0 so the
1013
977
  // account is skipped at all call sites that check `quota === 0`.
1014
- if (modelKey === "session") {
978
+ if (quotaKey === "session") {
1015
979
  const weekly = account.quota.find((w) => w.modelKey === "weekly");
1016
980
  if (weekly && weekly.percentRemaining === 0) return 0;
1017
981
  }
@@ -1023,10 +987,13 @@ export class AccountRotator {
1023
987
  account: AccountRuntime,
1024
988
  modelKey: string,
1025
989
  ): "fresh" | "5h" | "7d" {
1026
- const q = account.quota.find((q) => q.modelKey === modelKey) ??
1027
- (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
990
+ const quotaKey = isStaticAntigravityModel(modelKey)
991
+ ? modelKey
992
+ : dynamicCatalog.resolveQuotaPool(modelKey) ?? modelKey;
993
+ const q = account.quota.find((q) => q.modelKey === quotaKey) ??
994
+ (quotaKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`)
1028
995
  ? account.quota.find((candidate) => candidate.modelKey === CODEX_QUOTA_MODEL_KEY)
1029
- : modelKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
996
+ : quotaKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
1030
997
  ? account.quota.find((candidate) => candidate.providerId === OPENCODE_ZEN_PROVIDER_ID)
1031
998
  : undefined);
1032
999
  return q?.timerType ?? "fresh";
@@ -2888,17 +2855,7 @@ export class AccountRotator {
2888
2855
  let totalUsd = 0;
2889
2856
  const byModel: TokenUsageData["savings"]["byModel"] = {};
2890
2857
  for (const [model, totals] of Object.entries(modelTotals)) {
2891
- let pricing = MODEL_PRICING[model];
2892
- if (!pricing) {
2893
- const lower = model.toLowerCase();
2894
- if (lower.includes("opus")) pricing = MODEL_PRICING["claude-opus-4-6-thinking"];
2895
- else if (lower.includes("sonnet")) pricing = MODEL_PRICING["claude-sonnet-4-6"];
2896
- else if (lower.includes("3.8-flash")) pricing = MODEL_PRICING["gemini-3.8-flash-high"];
2897
- else if (lower.includes("3.7-flash")) pricing = MODEL_PRICING["gemini-3.7-flash-tiered"];
2898
- else if (lower.includes("3.6-flash")) pricing = MODEL_PRICING["gemini-3.6-flash-high"];
2899
- else if (lower.includes("flash")) pricing = MODEL_PRICING["gemini-3-flash"];
2900
- else if (lower.includes("pro")) pricing = MODEL_PRICING["gemini-3.1-pro"];
2901
- }
2858
+ const pricing = getModelPricing(model);
2902
2859
  if (!pricing) continue;
2903
2860
  const inputUsd = (totals.input / 1_000_000) * pricing.inputPer1M;
2904
2861
  const outputUsd = (totals.output / 1_000_000) * pricing.outputPer1M;
@@ -3538,6 +3495,13 @@ export class AccountRotator {
3538
3495
  account: AccountRuntime,
3539
3496
  modelKey: string,
3540
3497
  ): boolean {
3498
+ if (
3499
+ !isStaticAntigravityModel(modelKey) &&
3500
+ dynamicCatalog.wasDiscovered(modelKey) &&
3501
+ !dynamicCatalog.hasModelForAccount(getAccountIdentity(account), modelKey)
3502
+ ) {
3503
+ return false;
3504
+ }
3541
3505
  const providerId = getProviderIdForPoolKey(modelKey);
3542
3506
  return hasCredential(account.config, providerId) &&
3543
3507
  !account.invalidProviders?.[providerId] &&
@@ -3554,6 +3518,10 @@ export class AccountRotator {
3554
3518
  }
3555
3519
 
3556
3520
  private resolvePoolKeyForModel(model: string): string | null {
3521
+ if (
3522
+ !isStaticAntigravityModel(model) &&
3523
+ dynamicCatalog.wasDiscovered(model)
3524
+ ) return model.toLowerCase();
3557
3525
  const context = {
3558
3526
  ollamaModels: this.ollamaModels,
3559
3527
  codexModels: this.codexModels,
@@ -1,5 +1,5 @@
1
1
  import randomBytes from "node:crypto";
2
- import { MODEL_PRICING, type SpendLog, type DailySpend } from "./types.js";
2
+ import { getModelPricing, type SpendLog, type DailySpend } from "./types.js";
3
3
  import { isDbConfigured, queryDb } from "./db-store.js";
4
4
  import { rotatorEnv } from "./env.js";
5
5
 
@@ -59,7 +59,7 @@ export function logSpend(
59
59
  return;
60
60
  }
61
61
 
62
- const pricing = MODEL_PRICING[log.model] || { inputPer1M: 0, outputPer1M: 0 };
62
+ const pricing = getModelPricing(log.model) ?? { inputPer1M: 0, outputPer1M: 0 };
63
63
  const promptTokens = Math.max(0, log.promptTokens || 0);
64
64
  const completionTokens = Math.max(0, log.completionTokens || 0);
65
65
  const promptCostUsd = (promptTokens / 1_000_000) * (pricing.inputPer1M || 0);
@@ -253,25 +253,7 @@ export async function flushSpendLogs(): Promise<void> {
253
253
  }
254
254
 
255
255
  export function calculateCost(model: string, promptTokens: number, completionTokens: number): number {
256
- let pricing = MODEL_PRICING[model];
257
- if (!pricing) {
258
- const lower = model.toLowerCase();
259
- if (lower.includes("opus")) {
260
- pricing = MODEL_PRICING["claude-opus-4-6-thinking"];
261
- } else if (lower.includes("sonnet")) {
262
- pricing = MODEL_PRICING["claude-sonnet-4-6"];
263
- } else if (lower.includes("3.8-flash")) {
264
- pricing = MODEL_PRICING["gemini-3.8-flash-high"];
265
- } else if (lower.includes("3.7-flash")) {
266
- pricing = MODEL_PRICING["gemini-3.7-flash-tiered"];
267
- } else if (lower.includes("3.6-flash")) {
268
- pricing = MODEL_PRICING["gemini-3.6-flash-high"];
269
- } else if (lower.includes("flash")) {
270
- pricing = MODEL_PRICING["gemini-3-flash"];
271
- } else if (lower.includes("pro")) {
272
- pricing = MODEL_PRICING["gemini-3.1-pro"];
273
- }
274
- }
256
+ const pricing = getModelPricing(model);
275
257
  if (!pricing) return 0;
276
258
  const inputCost = (promptTokens / 1_000_000) * pricing.inputPer1M;
277
259
  const outputCost = (completionTokens / 1_000_000) * pricing.outputPer1M;
@@ -1228,6 +1228,7 @@ function getModelPricingClient(m) {
1228
1228
  if (lower.indexOf("3.6-flash") !== -1) return MODEL_PRICING_CLIENT["gemini-3.6-flash-high"];
1229
1229
  if (lower.indexOf("flash") !== -1) return MODEL_PRICING_CLIENT["gemini-3-flash"];
1230
1230
  if (lower.indexOf("pro") !== -1) return MODEL_PRICING_CLIENT["gemini-3.1-pro"];
1231
+ if (lower.indexOf("gpt-oss") !== -1) return MODEL_PRICING_CLIENT["gpt-oss-120b-medium"];
1231
1232
  return null;
1232
1233
  }
1233
1234
 
package/src/types.ts CHANGED
@@ -207,8 +207,18 @@ export interface GoogleQuotaResponse {
207
207
  remainingFraction?: number;
208
208
  resetTime?: string;
209
209
  };
210
+ displayName?: string;
211
+ maxTokens?: number;
212
+ maxOutputTokens?: number;
213
+ thinkingBudget?: number;
214
+ minThinkingBudget?: number;
215
+ supportsThinking?: boolean;
216
+ supportsImages?: boolean;
217
+ supportsVideo?: boolean;
210
218
  }
211
219
  >;
220
+ defaultAgentModelId?: string;
221
+ tieredModelIds?: Record<string, string[]>;
212
222
  }
213
223
 
214
224
  // Per-model thinking/output spec used by the compat layer.
@@ -279,6 +289,14 @@ export const QUOTA_MODEL_KEYS: Record<
279
289
  },
280
290
  };
281
291
 
292
+ const STATIC_ANTIGRAVITY_MODEL_IDS = new Set(
293
+ Object.values(QUOTA_MODEL_KEYS).flatMap(({ altKeys }) => altKeys),
294
+ );
295
+
296
+ export function isStaticAntigravityModel(model: string): boolean {
297
+ return STATIC_ANTIGRAVITY_MODEL_IDS.has(model.toLowerCase());
298
+ }
299
+
282
300
  // Map request model names to quota model keys (family buckets).
283
301
  export function resolveQuotaModelKey(requestModel: string): string | null {
284
302
  const lower = requestModel.toLowerCase();
@@ -691,16 +709,15 @@ export interface TokenUsageData {
691
709
  };
692
710
  }
693
711
 
712
+ export interface ModelPricing {
713
+ inputPer1M: number;
714
+ outputPer1M: number;
715
+ cachingPer1M?: number;
716
+ cachingStoragePer1MPerHour?: number;
717
+ }
718
+
694
719
  // Pricing per 1M tokens (USD) — what these would cost on paid APIs
695
- export const MODEL_PRICING: Record<
696
- string,
697
- {
698
- inputPer1M: number;
699
- outputPer1M: number;
700
- cachingPer1M?: number;
701
- cachingStoragePer1MPerHour?: number;
702
- }
703
- > = {
720
+ export const MODEL_PRICING: Record<string, ModelPricing> = {
704
721
  "claude-opus-4-6-thinking": { inputPer1M: 5.0, outputPer1M: 25.0 },
705
722
  "claude-sonnet-4-6": { inputPer1M: 3.0, outputPer1M: 15.0 },
706
723
  "gemini-3.1-pro": { inputPer1M: 2.0, outputPer1M: 12.0 },
@@ -823,6 +840,24 @@ export const MODEL_PRICING: Record<
823
840
 
824
841
  };
825
842
 
843
+ /**
844
+ * Resolves pricing for a model, using exact lookup first and dynamic family fallbacks
845
+ * for newly released models without manual pricing entries.
846
+ */
847
+ export function getModelPricing(model: string): ModelPricing | undefined {
848
+ if (!model) return undefined;
849
+ if (MODEL_PRICING[model]) return MODEL_PRICING[model];
850
+ const lower = model.toLowerCase();
851
+ if (MODEL_PRICING[lower]) return MODEL_PRICING[lower];
852
+ // Dynamic family fallbacks for unseen future models:
853
+ if (lower.includes("opus")) return MODEL_PRICING["claude-opus-4-6-thinking"];
854
+ if (lower.includes("sonnet")) return MODEL_PRICING["claude-sonnet-4-6"];
855
+ if (lower.includes("flash")) return MODEL_PRICING["gemini-3.8-flash-high"] ?? MODEL_PRICING["gemini-3.7-flash-tiered"];
856
+ if (lower.includes("pro")) return MODEL_PRICING["gemini-3.1-pro"];
857
+ if (lower.includes("gpt-oss")) return MODEL_PRICING["gpt-oss-120b-medium"];
858
+ return undefined;
859
+ }
860
+
826
861
  // Which Ollama Cloud models respond on which subscription tiers, verified
827
862
  // 2026-08-30 via scripts/verify_ollama_models.ts (/api/tags discovery +
828
863
  // /api/chat probes: HTTP 200 = free, HTTP 402 = subscription-only).
@@ -906,9 +941,11 @@ export const ANTIGRAVITY_VERSION =
906
941
  rotatorEnv("ANTIGRAVITY_VERSION") ||
907
942
  process.env.PI_AI_ANTIGRAVITY_VERSION ||
908
943
  "2.11.0";
944
+ export const DEFAULT_ANTIGRAVITY_USER_AGENT =
945
+ `antigravity/ide/${ANTIGRAVITY_VERSION} (aidev_client; os_type=darwin; arch=arm64)`;
909
946
  export const QUOTA_USER_AGENT =
910
947
  rotatorEnv("QUOTA_USER_AGENT") ||
911
- `antigravity/${ANTIGRAVITY_VERSION} darwin/arm64`;
948
+ DEFAULT_ANTIGRAVITY_USER_AGENT;
912
949
  export const REQUEST_USER_AGENT =
913
950
  rotatorEnv("REQUEST_USER_AGENT") || QUOTA_USER_AGENT;
914
951
  export const REQUEST_GOOG_API_CLIENT =