tuxevil-rotator 3.4.0 → 3.6.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,26 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [3.6.0] - 2026-09-04
6
+
7
+ ### Added
8
+
9
+ - **Persistent dynamic model ownership**: Dynamic Antigravity model ownership is persisted by complete account identity and credential-generation fingerprint, so cold restarts cannot route a model through an account or project that never advertised it. ([#30](https://github.com/tuxevil/tuxevil-rotator/pull/30) by [@javargasm](https://github.com/javargasm))
10
+
11
+ ### Fixed
12
+
13
+ - **Dynamic catalog and quota safety**: Malformed quota entries are ignored without replacing the last known-good snapshot; exhausted sibling pools, stale in-flight responses, retired/reserved model IDs, and account removal or credential changes are handled safely. Persisted cooldown, circuit-breaker, and 429 state is migrated without shortening valid deadlines or losing history. ([#30](https://github.com/tuxevil/tuxevil-rotator/pull/30) by [@javargasm](https://github.com/javargasm))
14
+ - **Dynamic model compatibility metadata**: Effective output-token and thinking metadata now honor runtime constraints and operator overrides across Chat, Responses, and Anthropic compatibility paths, with provider- and version-aware Gemini pricing fallbacks. ([#30](https://github.com/tuxevil/tuxevil-rotator/pull/30) by [@javargasm](https://github.com/javargasm))
15
+ - **Partial model specification overrides**: Operators can now override only selected `modelSpecs` fields while inheriting the effective runtime, static, or family defaults for omitted metadata. Overrides are retained through configuration normalization and persistence, including context-window lookups. ([#31](https://github.com/tuxevil/tuxevil-rotator/pull/31) by [@javargasm](https://github.com/javargasm))
16
+
17
+ ## [3.5.0] - 2026-09-03
18
+
19
+ ### Added
20
+ - **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)).
21
+
22
+ ### Fixed
23
+ - **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)).
24
+
5
25
  ## [3.4.0] - 2026-09-03
6
26
 
7
27
  ### Added
package/README.md CHANGED
@@ -54,6 +54,9 @@ 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))
58
+ - **Dynamic Catalog Hardening**: Quota snapshots reject malformed data while preserving the last known-good state, stale account responses are ignored, and dynamic model ownership and quota-safety state survive restarts without routing a model through an account that did not advertise it. ([PR #30](https://github.com/tuxevil/tuxevil-rotator/pull/30) by [@javargasm](https://github.com/javargasm))
59
+ - **Partial Model Specification Overrides**: `modelSpecs` entries can override selected output, thinking, and context fields while inheriting the remaining effective runtime, static, or family metadata. Overrides are preserved through configuration normalization and persistence. ([PR #31](https://github.com/tuxevil/tuxevil-rotator/pull/31) by [@javargasm](https://github.com/javargasm))
57
60
 
58
61
  ## v3.2 Highlights
59
62
 
@@ -348,7 +351,7 @@ Thanks to these amazing people who have contributed to the project:
348
351
  - **[@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
352
  - **[@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
353
  - **[@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))
354
+ - **[@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, dynamic catalog and quota-safety hardening, persistent dynamic model ownership across restarts, 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), [PR #30](https://github.com/tuxevil/tuxevil-rotator/pull/30))
352
355
 
353
356
  ## Development
354
357
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tuxevil-rotator",
3
- "version": "3.4.0",
3
+ "version": "3.6.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,96 @@
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
+ }
71
+
72
+ /** Identify the exact provider credential revision used by an async operation. */
73
+ export function getCredentialGeneration(
74
+ account: AccountRuntime | AccountConfig,
75
+ providerId: string,
76
+ ): string {
77
+ const config = "config" in account ? account.config : account;
78
+ const norm = normalizeAccountConfig(config);
79
+ const cred = norm.credentials?.find((candidate) => candidate.provider === providerId);
80
+ const details = getProviderCredentialDetails(
81
+ norm,
82
+ cred ?? { provider: providerId },
83
+ );
84
+ if (!cred && !details.secret) return "none";
85
+ return `${providerId}:${details.projectId}:${details.providerAccountId}:${details.secret}`;
86
+ }
87
+
88
+ /** Persist a credential revision without exposing its raw secret. */
89
+ export function getCredentialGenerationFingerprint(
90
+ account: AccountRuntime | AccountConfig,
91
+ providerId: string,
92
+ ): string {
93
+ return createHash("sha256")
94
+ .update(getCredentialGeneration(account, providerId))
95
+ .digest("hex");
96
+ }
@@ -1,11 +1,16 @@
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
6
+ minThinkingBudget?: number;
4
7
  isThinking: boolean;
5
8
  /** Upstream-published context window (input tokens). Optional. */
6
9
  contextWindow?: number;
7
10
  }
8
11
 
12
+ export type ModelSpecOverride = Partial<ModelSpec>;
13
+
9
14
  export const DEFAULT_MODEL_SPECS: Record<string, ModelSpec> = {
10
15
  "gemini-pro-agent": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true, contextWindow: 1_000_000 },
11
16
  "gemini-3-flash-agent": { maxOutputTokens: 65536, thinkingBudget: 10000, isThinking: true, contextWindow: 1_000_000 },
@@ -30,22 +35,33 @@ export const DEFAULT_MODEL_SPECS: Record<string, ModelSpec> = {
30
35
  "claude-sonnet-4-6-thinking":{ maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true, contextWindow: 1_000_000 },
31
36
  "claude-opus-4-6-thinking": { maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true, contextWindow: 1_000_000 },
32
37
  "claude-opus-4-6": { maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true, contextWindow: 1_000_000 },
38
+ "claude-sonnet-4-5": { maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true, contextWindow: 200_000 },
39
+ "claude-sonnet-4-5-thinking":{ maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true, contextWindow: 200_000 },
40
+ "claude-opus-4-5": { maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true, contextWindow: 200_000 },
41
+ "claude-opus-4-5-thinking": { maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true, contextWindow: 200_000 },
33
42
  "gpt-oss-120b-medium": { maxOutputTokens: 32768, thinkingBudget: 8192, isThinking: true, contextWindow: 131_072 },
34
43
  "gpt-oss-120b": { maxOutputTokens: 32768, thinkingBudget: 8192, isThinking: true, contextWindow: 131_072 },
35
44
  };
36
45
 
37
- let modelSpecsOverride: Record<string, ModelSpec> | null = null;
46
+ let modelSpecsOverride: Record<string, ModelSpecOverride> | null = null;
38
47
 
39
48
  /**
40
- * Replace the bundled model spec table with operator-provided overrides.
49
+ * Apply operator-provided partial overrides over effective model specs.
41
50
  * Pass `null` to restore defaults. Called once at startup from index.ts.
42
51
  */
43
- export function setModelSpecsOverride(specs: Record<string, ModelSpec> | null): void {
44
- modelSpecsOverride = specs && Object.keys(specs).length > 0 ? specs : null;
52
+ export function setModelSpecsOverride(specs: Record<string, ModelSpecOverride> | null): void {
53
+ modelSpecsOverride = specs && Object.keys(specs).length > 0
54
+ ? Object.fromEntries(
55
+ Object.entries(specs).map(([key, spec]) => [key.toLowerCase(), spec]),
56
+ )
57
+ : null;
45
58
  }
46
59
 
47
60
  export function getActiveModelSpecs(): Record<string, ModelSpec> {
48
- return modelSpecsOverride ?? DEFAULT_MODEL_SPECS;
61
+ if (!modelSpecsOverride) return DEFAULT_MODEL_SPECS;
62
+ return Object.fromEntries(
63
+ Object.keys(modelSpecsOverride).map((model) => [model, getModelSpec(model)]),
64
+ );
49
65
  }
50
66
 
51
67
  const GEMINI_MAX_OUTPUT_TOKENS = 65536;
@@ -60,26 +76,76 @@ export function getModelFamily(model: string): "claude" | "gemini" | "unknown" {
60
76
  return "unknown";
61
77
  }
62
78
 
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
- }
70
- const family = getModelFamily(model);
71
- if (family === "claude") return { maxOutputTokens: CLAUDE_MAX_OUTPUT_TOKENS, thinkingBudget: CLAUDE_DEFAULT_THINKING_BUDGET, isThinking: true, contextWindow: 1_000_000 };
72
- if (family === "gemini") return { maxOutputTokens: GEMINI_MAX_OUTPUT_TOKENS, thinkingBudget: FALLBACK_THINKING_BUDGET, isThinking: true, contextWindow: 1_000_000 };
73
- return { maxOutputTokens: 65536, thinkingBudget: FALLBACK_THINKING_BUDGET, isThinking: false, contextWindow: 128_000 };
74
- }
79
+ /** Resolve bundled static metadata without consulting the dynamic registry. */
80
+ export function getStaticModelSpec(model: string): ModelSpec | undefined {
81
+ const lower = model.toLowerCase();
82
+ if (DEFAULT_MODEL_SPECS[lower]) return DEFAULT_MODEL_SPECS[lower];
83
+ let best: { key: string; spec: ModelSpec } | undefined;
84
+ for (const [key, spec] of Object.entries(DEFAULT_MODEL_SPECS)) {
85
+ if (lower.includes(key) && (!best || key.length > best.key.length)) {
86
+ best = { key, spec };
87
+ }
88
+ }
89
+ return best?.spec;
90
+ }
91
+
92
+ export function getModelSpecOverride(model: string): ModelSpecOverride | undefined {
93
+ if (!modelSpecsOverride) return undefined;
94
+ const lower = model.toLowerCase();
95
+ if (modelSpecsOverride[lower]) return modelSpecsOverride[lower];
96
+ for (const [key, spec] of Object.entries(modelSpecsOverride)) {
97
+ if (lower.includes(key)) return spec;
98
+ }
99
+ return undefined;
100
+ }
101
+
102
+ function mergeModelSpec(
103
+ defaults: ModelSpec,
104
+ override: ModelSpecOverride,
105
+ ): ModelSpec {
106
+ const minThinkingBudget = typeof override.minThinkingBudget === "number" &&
107
+ Number.isFinite(override.minThinkingBudget) &&
108
+ override.minThinkingBudget >= 0
109
+ ? override.minThinkingBudget
110
+ : defaults.minThinkingBudget;
111
+ const contextWindow = typeof override.contextWindow === "number" &&
112
+ Number.isFinite(override.contextWindow) &&
113
+ override.contextWindow > 0
114
+ ? override.contextWindow
115
+ : defaults.contextWindow;
116
+ return {
117
+ maxOutputTokens: typeof override.maxOutputTokens === "number" &&
118
+ Number.isFinite(override.maxOutputTokens) &&
119
+ override.maxOutputTokens > 0
120
+ ? override.maxOutputTokens
121
+ : defaults.maxOutputTokens,
122
+ thinkingBudget: typeof override.thinkingBudget === "number" &&
123
+ Number.isFinite(override.thinkingBudget)
124
+ ? override.thinkingBudget
125
+ : defaults.thinkingBudget,
126
+ ...(minThinkingBudget !== undefined ? { minThinkingBudget } : {}),
127
+ isThinking: typeof override.isThinking === "boolean"
128
+ ? override.isThinking
129
+ : defaults.isThinking,
130
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
131
+ };
132
+ }
133
+
134
+ export function getModelSpec(model: string): ModelSpec {
135
+ const lower = model.toLowerCase();
136
+ const dynamicSpec = dynamicCatalog.getModelSpec(lower);
137
+ const staticSpec = getStaticModelSpec(lower);
138
+ const family = getModelFamily(model);
139
+ const defaults = dynamicSpec ?? staticSpec ??
140
+ (family === "claude"
141
+ ? { maxOutputTokens: CLAUDE_MAX_OUTPUT_TOKENS, thinkingBudget: CLAUDE_DEFAULT_THINKING_BUDGET, isThinking: true, contextWindow: 1_000_000 }
142
+ : family === "gemini"
143
+ ? { maxOutputTokens: GEMINI_MAX_OUTPUT_TOKENS, thinkingBudget: FALLBACK_THINKING_BUDGET, isThinking: true, contextWindow: 1_000_000 }
144
+ : { maxOutputTokens: 65536, thinkingBudget: FALLBACK_THINKING_BUDGET, isThinking: false, contextWindow: 128_000 });
145
+ const override = getModelSpecOverride(lower);
146
+ return override ? mergeModelSpec(defaults, override) : defaults;
147
+ }
75
148
 
76
- export function isThinkingModel(model: string): boolean {
77
- const spec = getModelSpec(model);
78
- if (spec.isThinking) return true;
79
- const l = model.toLowerCase();
80
- if (l.includes("gemini")) {
81
- const m = l.match(/gemini-(\d+)/);
82
- if (m && parseInt(m[1], 10) >= 3) return true;
83
- }
84
- return false;
85
- }
149
+ export function isThinkingModel(model: string): boolean {
150
+ return getModelSpec(model).isThinking;
151
+ }
package/src/compat.ts CHANGED
@@ -28,12 +28,14 @@ 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,
34
35
  getActiveModelSpecs,
35
36
  getModelFamily,
36
37
  getModelSpec,
38
+ getModelSpecOverride,
37
39
  isThinkingModel,
38
40
  } from "./compat/model-specs.js";
39
41
  import type { ModelSpec } from "./compat/model-specs.js";
@@ -318,6 +320,7 @@ export function parseAntigravitySse(raw: string): CompatCompletion {
318
320
  let inputTokens = 0;
319
321
  let outputTokens = 0;
320
322
  let responseId: string | undefined;
323
+ let upstreamFinishReason: string | undefined;
321
324
  const toolCallsMap = new Map<string, OpenAIToolCall>();
322
325
  let toolCallIndex = 0;
323
326
 
@@ -334,6 +337,13 @@ export function parseAntigravitySse(raw: string): CompatCompletion {
334
337
  ? response.candidates
335
338
  : [];
336
339
  for (const candidate of candidates) {
340
+ if (
341
+ isRecord(candidate) &&
342
+ typeof candidate.finishReason === "string" &&
343
+ candidate.finishReason
344
+ ) {
345
+ upstreamFinishReason = candidate.finishReason;
346
+ }
337
347
  if (
338
348
  !isRecord(candidate) ||
339
349
  !isRecord(candidate.content) ||
@@ -432,6 +442,7 @@ export function parseAntigravitySse(raw: string): CompatCompletion {
432
442
  outputTokens,
433
443
  responseId,
434
444
  toolCalls,
445
+ finishReason: upstreamFinishReason,
435
446
  };
436
447
  }
437
448
 
@@ -515,6 +526,10 @@ function recordCompatOutcome(
515
526
  inputTokens: completion?.inputTokens ?? 0,
516
527
  outputTokens: completion?.outputTokens ?? 0,
517
528
  });
529
+ rotator.recordProxyEvent(
530
+ `[${context.requestId}] COMPAT END account=${context.label} model=${context.displayModelKey} status=${statusCode} ttfbMs=${ttfbMs} totalMs=${totalMs} inTokens=${completion?.inputTokens ?? 0} outTokens=${completion?.outputTokens ?? 0}`,
531
+ "info",
532
+ );
518
533
  logSpend({
519
534
  requestId: context.requestId,
520
535
  apiKeyHash: options?.apiKeyHash || null,
@@ -637,6 +652,7 @@ async function streamCompatSse(
637
652
  let tailBuffer = "";
638
653
  let reqClosed = false;
639
654
  let streamError: string | undefined;
655
+ let upstreamFinishReason: string | undefined;
640
656
  interface OpenAiStreamingToolState {
641
657
  id: string;
642
658
  name: string;
@@ -953,6 +969,13 @@ async function streamCompatSse(
953
969
  ? response.candidates
954
970
  : [];
955
971
  for (const candidate of candidates) {
972
+ if (
973
+ isRecord(candidate) &&
974
+ typeof candidate.finishReason === "string" &&
975
+ candidate.finishReason
976
+ ) {
977
+ upstreamFinishReason = candidate.finishReason;
978
+ }
956
979
  if (
957
980
  !isRecord(candidate) ||
958
981
  !isRecord(candidate.content) ||
@@ -1103,7 +1126,14 @@ async function streamCompatSse(
1103
1126
  if (streamError) {
1104
1127
  writeCompatStreamError(res, format, streamError);
1105
1128
  } else if (format === "openai") {
1106
- const openaiFinishReason = toolCallIndex > 0 ? "tool_calls" : "stop";
1129
+ const openaiFinishReason =
1130
+ toolCallIndex > 0
1131
+ ? "tool_calls"
1132
+ : upstreamFinishReason === "MAX_TOKENS"
1133
+ ? "length"
1134
+ : upstreamFinishReason === "SAFETY"
1135
+ ? "content_filter"
1136
+ : "stop";
1107
1137
  res.write(
1108
1138
  `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta: {}, finish_reason: openaiFinishReason }] })}\n\n`,
1109
1139
  );
@@ -1127,7 +1157,12 @@ async function streamCompatSse(
1127
1157
  );
1128
1158
  }
1129
1159
  }
1130
- const anthropicStopReason = anthropicHasToolUse ? "tool_use" : "end_turn";
1160
+ const anthropicStopReason =
1161
+ anthropicHasToolUse
1162
+ ? "tool_use"
1163
+ : upstreamFinishReason === "MAX_TOKENS"
1164
+ ? "max_tokens"
1165
+ : "end_turn";
1131
1166
  // message_delta carries output_tokens; also include input_tokens so Hermes shows full context count
1132
1167
  res.write(
1133
1168
  `event: message_delta\ndata: ${JSON.stringify({ type: "message_delta", delta: { stop_reason: anthropicStopReason, stop_sequence: null }, usage: { input_tokens: inputTokens, output_tokens: outputTokens } })}\n\n`,
@@ -1161,7 +1196,13 @@ async function streamCompatSse(
1161
1196
  content: text || null,
1162
1197
  ...(collectedToolCalls ? { tool_calls: collectedToolCalls } : {}),
1163
1198
  },
1164
- finish_reason: collectedToolCalls ? "tool_calls" : "stop",
1199
+ finish_reason: collectedToolCalls
1200
+ ? "tool_calls"
1201
+ : upstreamFinishReason === "MAX_TOKENS"
1202
+ ? "length"
1203
+ : upstreamFinishReason === "SAFETY"
1204
+ ? "content_filter"
1205
+ : "stop",
1165
1206
  },
1166
1207
  ],
1167
1208
  usage: {
@@ -1186,7 +1227,11 @@ async function streamCompatSse(
1186
1227
  }))
1187
1228
  : []),
1188
1229
  ],
1189
- stop_reason: anthropicHasToolUse ? "tool_use" : "end_turn",
1230
+ stop_reason: anthropicHasToolUse
1231
+ ? "tool_use"
1232
+ : upstreamFinishReason === "MAX_TOKENS"
1233
+ ? "max_tokens"
1234
+ : "end_turn",
1190
1235
  usage: { input_tokens: inputTokens, output_tokens: outputTokens },
1191
1236
  };
1192
1237
 
@@ -1199,6 +1244,7 @@ async function streamCompatSse(
1199
1244
  toolCalls: collectedToolCalls,
1200
1245
  rawResponse,
1201
1246
  streamError,
1247
+ finishReason: upstreamFinishReason,
1202
1248
  };
1203
1249
  }
1204
1250
 
@@ -2089,24 +2135,77 @@ export interface OpenAIModelCatalogEntry {
2089
2135
  meta: Record<string, unknown>;
2090
2136
  }
2091
2137
 
2138
+ export interface CompatModelEntry {
2139
+ id: string;
2140
+ family: string;
2141
+ ctx: number;
2142
+ quotaPool: string;
2143
+ multimodal: boolean;
2144
+ tools: boolean;
2145
+ maxOutputTokens: number;
2146
+ thinkingBudget: number;
2147
+ minThinkingBudget?: number;
2148
+ isThinking: boolean;
2149
+ }
2150
+
2151
+ export function getEffectiveAntigravityModels(): CompatModelEntry[] {
2152
+ const dynamic = dynamicCatalog.getAllModels();
2153
+ const seen = new Set(MODEL_CATALOG.map((model) => model.id.toLowerCase()));
2154
+ const result: CompatModelEntry[] = MODEL_CATALOG.map((model) => {
2155
+ const spec = getModelSpec(model.id);
2156
+ const contextWindow = getModelSpecOverride(model.id)?.contextWindow ??
2157
+ dynamicCatalog.getModelSpec(model.id)?.contextWindow;
2158
+ return {
2159
+ ...model,
2160
+ ctx: contextWindow ?? model.ctx,
2161
+ maxOutputTokens: spec.maxOutputTokens,
2162
+ thinkingBudget: spec.thinkingBudget,
2163
+ minThinkingBudget: spec.minThinkingBudget,
2164
+ isThinking: spec.isThinking,
2165
+ };
2166
+ });
2167
+ for (const m of dynamic) {
2168
+ if (seen.has(m.id.toLowerCase())) continue;
2169
+ seen.add(m.id.toLowerCase());
2170
+ const spec = getModelSpec(m.id);
2171
+ result.push({
2172
+ id: m.id,
2173
+ family: m.family,
2174
+ ctx: spec.contextWindow ?? m.ctx,
2175
+ quotaPool: m.quotaPool,
2176
+ multimodal: m.multimodal,
2177
+ tools: m.tools,
2178
+ maxOutputTokens: spec.maxOutputTokens,
2179
+ thinkingBudget: spec.thinkingBudget,
2180
+ minThinkingBudget: spec.minThinkingBudget,
2181
+ isThinking: spec.isThinking,
2182
+ });
2183
+ }
2184
+ return result;
2185
+ }
2186
+
2092
2187
  /**
2093
- * Build the full OpenAI-compatible model catalog (static Antigravity catalog
2094
- * + active-provider models for Ollama, OpenAI Codex and OpenCode Zen).
2188
+ * Build the OpenAI-compatible `/v1/models` catalog for the proxy.
2095
2189
  *
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)
2100
- *
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.
2190
+ * The static Antigravity baseline and dynamically-discovered Antigravity models
2191
+ * are always included. An active rotator also contributes its other providers.
2104
2192
  */
2105
2193
  export function buildOpenAIModelCatalog(
2106
2194
  rotator?: AccountRotator,
2107
2195
  ): OpenAIModelCatalogEntry[] {
2108
- const catalog: OpenAIModelCatalogEntry[] = MODEL_CATALOG.map(
2109
- ({ id, ctx, family, quotaPool, multimodal, tools }) => ({
2196
+ const catalog: OpenAIModelCatalogEntry[] = getEffectiveAntigravityModels().map(
2197
+ ({
2198
+ id,
2199
+ ctx,
2200
+ family,
2201
+ quotaPool,
2202
+ multimodal,
2203
+ tools,
2204
+ maxOutputTokens,
2205
+ thinkingBudget,
2206
+ minThinkingBudget,
2207
+ isThinking,
2208
+ }) => ({
2110
2209
  id,
2111
2210
  object: "model",
2112
2211
  created: 0,
@@ -2119,6 +2218,12 @@ export function buildOpenAIModelCatalog(
2119
2218
  quota_pool: quotaPool,
2120
2219
  multimodal,
2121
2220
  tool_calling: tools,
2221
+ max_output_tokens: maxOutputTokens,
2222
+ thinking: isThinking,
2223
+ thinking_budget: thinkingBudget,
2224
+ ...(minThinkingBudget !== undefined
2225
+ ? { min_thinking_budget: minThinkingBudget }
2226
+ : {}),
2122
2227
  },
2123
2228
  }),
2124
2229
  );
@@ -2195,15 +2300,26 @@ export function serveOpenAIModels(
2195
2300
 
2196
2301
  export function serveGeminiModels(res: ServerResponse): void {
2197
2302
  writeJson(res, 200, {
2198
- models: MODEL_CATALOG.map(
2199
- ({ id, ctx, family, quotaPool, multimodal, tools }) => ({
2303
+ models: getEffectiveAntigravityModels().map(
2304
+ ({
2305
+ id,
2306
+ ctx,
2307
+ family,
2308
+ quotaPool,
2309
+ multimodal,
2310
+ tools,
2311
+ maxOutputTokens,
2312
+ thinkingBudget,
2313
+ minThinkingBudget,
2314
+ isThinking,
2315
+ }) => ({
2200
2316
  name: `models/${id}`,
2201
2317
  baseModelId: family,
2202
2318
  version: "v2.0",
2203
2319
  displayName: id,
2204
2320
  description: `Tuxevil Rotator Gemini-compatible model entry for ${id}`,
2205
2321
  inputTokenLimit: ctx,
2206
- outputTokenLimit: ctx,
2322
+ outputTokenLimit: maxOutputTokens,
2207
2323
  supportedGenerationMethods: [
2208
2324
  "generateContent",
2209
2325
  "streamGenerateContent",
@@ -2212,6 +2328,11 @@ export function serveGeminiModels(res: ServerResponse): void {
2212
2328
  tools,
2213
2329
  multimodal,
2214
2330
  quotaPool,
2331
+ thinking: isThinking,
2332
+ thinkingBudget,
2333
+ ...(minThinkingBudget !== undefined
2334
+ ? { minThinkingBudget }
2335
+ : {}),
2215
2336
  },
2216
2337
  }),
2217
2338
  ),
@@ -2460,7 +2581,13 @@ export async function handleOpenAIChatCompletions(
2460
2581
  ? { reasoning_content: result.completion.thinkingText }
2461
2582
  : {}),
2462
2583
  },
2463
- finish_reason: hasToolCalls ? "tool_calls" : "stop",
2584
+ finish_reason: hasToolCalls
2585
+ ? "tool_calls"
2586
+ : result.completion.finishReason === "MAX_TOKENS"
2587
+ ? "length"
2588
+ : result.completion.finishReason === "SAFETY"
2589
+ ? "content_filter"
2590
+ : "stop",
2464
2591
  },
2465
2592
  ],
2466
2593
  usage: {
@@ -55,7 +55,8 @@ export function applyConfigDefaults(config: Config): Config {
55
55
  idempotencyWindowMs: config.idempotencyWindowMs ?? 2000,
56
56
  streamRecoveryMaxRetries: safeStreamRecoveryMaxRetries(config.streamRecoveryMaxRetries),
57
57
  compressionMode: config.compressionMode ?? "off",
58
- accounts: config.accounts ? config.accounts.map((account) => ({
58
+ modelSpecs: config.modelSpecs,
59
+ accounts: config.accounts ? config.accounts.map((account) => ({
59
60
  ...normalizeAccountConfig(account),
60
61
  tier: account.tier || "unknown",
61
62
  })) : [],
@@ -9,6 +9,9 @@
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
+ import { getModelSpecOverride } from "../../compat/model-specs.js";
14
+
12
15
  export interface AntigravityModelSpec {
13
16
  id: string;
14
17
  contextWindow: number;
@@ -71,17 +74,25 @@ const FALLBACK_CONTEXT_WINDOW = 128_000;
71
74
  * Resolve the upstream-published context window for an Antigravity model id.
72
75
  *
73
76
  * 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.
77
+ * 1. Operator exact/substring override.
78
+ * 2. Exact id match in static table (lowercased).
79
+ * 3. Dynamic catalog entry from live Antigravity endpoint.
80
+ * 4. Substring match across the table (longest key wins via the order here).
81
+ * 5. Family defaults: claude -> 1M, gemini -> 1M, gpt-oss -> 131_072.
82
+ * 6. Defensive fallback: 128_000.
78
83
  */
79
84
  export function getAntigravityContextWindow(model: string): number {
80
85
  if (!model) return FALLBACK_CONTEXT_WINDOW;
81
86
  const lower = model.toLowerCase().trim();
82
87
  if (!lower) return FALLBACK_CONTEXT_WINDOW;
88
+ const overrideCtx = getModelSpecOverride(lower)?.contextWindow;
89
+ if (typeof overrideCtx === "number" && Number.isFinite(overrideCtx) && overrideCtx > 0) {
90
+ return overrideCtx;
91
+ }
83
92
  const exact = ANTIGRAVITY_CONTEXT_WINDOWS[lower];
84
93
  if (typeof exact === "number") return exact;
94
+ const dynamicCtx = dynamicCatalog.getContextWindow(lower);
95
+ if (typeof dynamicCtx === "number") return dynamicCtx;
85
96
  // Substring fallback: pick the longest registered key that appears in lower.
86
97
  let best: { key: string; value: number } | null = null;
87
98
  for (const [key, value] of Object.entries(ANTIGRAVITY_CONTEXT_WINDOWS)) {