tuxevil-rotator 3.2.1 → 3.2.3

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
@@ -1,5 +1,33 @@
1
1
  # Changelog
2
2
 
3
+ ## [3.2.3] - 2026-08-21
4
+
5
+ ### Fixed
6
+ - **Account-scoped 429 `RESOURCE_EXHAUSTED` resilience & account lifecycle**: When an individual account exhausts its quota (returning 429 `RESOURCE_EXHAUSTED` on Claude or Gemini), the proxy now safely releases the failed account before rotating, allowing immediate retry with the next eligible account in the pool instead of failing prematurely ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
7
+ - **Synchronous account leasing & atomic concurrency accounting**: `inFlightRequests` reservation and model assignment tracking now occur synchronously and indivisibly at lease time before asynchronous save or refresh operations. If activation fails, in-flight counters are rolled back and token buckets are refunded immediately ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
8
+ - **Snapshot-based token refresh & generation tracking**: Provider token refreshes execute against isolated account snapshot clones. Refreshed tokens are published only if the credential generation has not changed during flight, cleanly discarding stale tokens if credentials were reconfigured ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
9
+ - **Provider-scoped token publication**: Token refreshes for multi-provider accounts (e.g. Google Antigravity + OpenAI Codex) now update strictly provider-owned fields, preventing cross-provider token and credential overwrites ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
10
+ - **Identity resolution with non-secret credential fingerprinting**: Duplicate-email accounts without stable provider IDs are resolved using a 12-character SHA-256 non-secret credential fingerprint, isolating runtime state during `replaceConfig` ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
11
+ - **Exact incarnation exclusion on retry**: `rotateToNext(model, failedAccount)` binds exclusion strictly to the exact runtime object instance, preventing false 503 errors when an account is replaced by a healthy incarnation ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
12
+
13
+ ## [3.2.2] - 2026-08-21
14
+
15
+ ### Fixed
16
+ - **Spend-logger memory leak in file-based storage mode**: When running in default file-based storage mode (without PostgreSQL), `flushSpendLogs()` returned early without draining or clearing the log `queue`. Since requests with sanitized payloads (up to 512 KB each) were being enqueued, heap memory grew indefinitely. `logSpend()` now short-circuits and clears `queue` when PostgreSQL is not configured ([#22](https://github.com/tuxevil/tuxevil-rotator/pull/22) by [@javargasm](https://github.com/javargasm)).
17
+ - **Atomic PostgreSQL spend log insert & daily aggregation via CTE**: Combined `rotator_spend_logs` insert and `rotator_daily_spend` upsert into a single atomic Common Table Expression query. Re-attempted inserts with existing `request_id` values return 0 rows from `ins_log`, ensuring daily metrics are not double-counted on retries. On database errors, only uncommitted logs are re-enqueued and bounded by a strict FIFO cap (`MAX_QUEUE_CAP = 100`) ([#22](https://github.com/tuxevil/tuxevil-rotator/pull/22) by [@javargasm](https://github.com/javargasm)).
18
+ - **Unbounded Virtual Key cache bounded**: Added `KEY_CACHE_MAX = 500` with 1-minute TTL and FIFO eviction to `keyCache` in `src/virtual-keys.ts`, preventing memory exhaustion from negative lookup caching and key scanning ([#22](https://github.com/tuxevil/tuxevil-rotator/pull/22) by [@javargasm](https://github.com/javargasm)).
19
+ - `/v1/models` no longer reports the outdated 500K Claude context window.
20
+
21
+ ### Added
22
+ - **Official per-model context windows surfaced across providers**: New `src/providers/google-antigravity/catalog.ts` publishes the upstream context windows for Claude (Opus 4.6 / Sonnet 4.6 → 1M, Opus 4.5 / Sonnet 4.5 → 200K), Google Gemini (3.1 Pro, 3 Pro, 3 Flash variants, 2.5 Pro/Flash → 1M each), and `gpt-oss-120b` (131,072). The new `getAntigravityContextWindow(model)` helper is the single source of truth.
23
+ - **`/api/show` lookup for Ollama model context windows**: `src/providers/ollama/context-window.ts` calls `POST https://ollama.com/api/show` to read `model_info.<arch>.context_length`, cached for `TAGS_CACHE_TTL_MS` and falling back to the operator-provided `OLLAMA_NUM_CTX` env (default 8192).
24
+ - **`ModelSpec.contextWindow`**: Optional `contextWindow` field in `src/compat/model-specs.ts` reflects upstream values; resolved automatically via `getModelSpec()` and propagated through `/v1/models`-adjacent surfaces.
25
+
26
+ ### Changed
27
+ - **OpenAI Codex catalog updated to GPT-5.6 family official 1.05M window**: `CODEX_CONTEXT_WINDOW` raised from 272_000 to 1_050_000 per `https://platform.openai.com/docs/models`. The 2M safety cap on `/models`-discovered ids is preserved.
28
+ - **OpenCode Zen catalog now exposes a per-id helper** (`getOpenCodeZenContextWindow`) that documents the placeholder 128K window until OpenCode publishes per-model specs.
29
+ - **`MODEL_CATALOG` in `src/compat.ts`**: Claude Opus 4.6 / Sonnet 4.6 context window raised from 500_000 to 1_000_000 to match Anthropic's published spec.
30
+
3
31
  ## [3.2.1] - 2026-08-16
4
32
 
5
33
  ### Fixed
package/README.md CHANGED
@@ -343,7 +343,7 @@ Thanks to these amazing people who have contributed to the project:
343
343
  - **[@CyR1en](https://github.com/CyR1en)** (Ethan Bacurio) — Added Gemini 3.6 Flash and Gemini 3.7 Flash model families, shared quota-pool routing, pricing, dashboard support, and regression coverage. ([PR #18](https://github.com/tuxevil/tuxevil-rotator/pull/18), [PR #21](https://github.com/tuxevil/tuxevil-rotator/pull/21))
344
344
  - **[@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))
345
345
  - **[@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))
346
- - **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) — Anthropic tool-use compatibility layer (`tool_use`/`tool_result` content block conversion), JSON schema round-trip fixes, and compat test suite expansion. ([PR #3](https://github.com/tuxevil/tuxevil-rotator/pull/3), [PR #7](https://github.com/tuxevil/tuxevil-rotator/pull/7))
346
+ - **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) — 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, and compat test suite expansion. ([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))
347
347
 
348
348
  ## Development
349
349
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tuxevil-rotator",
3
- "version": "3.2.1",
3
+ "version": "3.2.3",
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",
@@ -2,34 +2,37 @@ export interface ModelSpec {
2
2
  maxOutputTokens: number;
3
3
  thinkingBudget: number; // -1 = adaptive (model decides), >=0 = fixed
4
4
  isThinking: boolean;
5
+ /** Upstream-published context window (input tokens). Optional. */
6
+ contextWindow?: number;
5
7
  }
6
8
 
7
9
  export const DEFAULT_MODEL_SPECS: Record<string, ModelSpec> = {
8
- "gemini-pro-agent": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true },
9
- "gemini-3-flash-agent": { maxOutputTokens: 65536, thinkingBudget: 10000, isThinking: true },
10
- "gemini-3-pro-high": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true },
11
- "gemini-3-pro-low": { maxOutputTokens: 65535, thinkingBudget: 1001, isThinking: true },
12
- "gemini-3.1-pro": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true },
13
- "gemini-3.1-pro-high": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true },
14
- "gemini-3.1-pro-low": { maxOutputTokens: 65535, thinkingBudget: 1001, isThinking: true },
15
- "gemini-3.1-pro-preview": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true },
16
- "gemini-3.5-flash": { maxOutputTokens: 65536, thinkingBudget: 10000, isThinking: true },
17
- "gemini-3.5-flash-medium": { maxOutputTokens: 65536, thinkingBudget: 4000, isThinking: true },
18
- "gemini-3.5-flash-low": { maxOutputTokens: 65536, thinkingBudget: 4000, isThinking: true },
19
- "gemini-3.5-flash-high": { maxOutputTokens: 65536, thinkingBudget: 10000, isThinking: true },
20
- "gemini-3.6-flash-high": { maxOutputTokens: 65536, thinkingBudget: 10000, isThinking: true },
21
- "gemini-3.6-flash-medium": { maxOutputTokens: 65536, thinkingBudget: 4000, isThinking: true },
22
- "gemini-3.6-flash-low": { maxOutputTokens: 65536, thinkingBudget: 1000, isThinking: true },
23
- "gemini-3.6-flash-tiered": { maxOutputTokens: 65536, thinkingBudget: -1, isThinking: true },
24
- "gemini-3.7-flash-tiered": { maxOutputTokens: 65536, thinkingBudget: -1, isThinking: true },
25
- "gemini-3-flash": { maxOutputTokens: 65536, thinkingBudget: 4000, isThinking: true },
26
- "gemini-2.5-flash": { maxOutputTokens: 65535, thinkingBudget: 24576, isThinking: true },
27
- "gemini-2.5-pro": { maxOutputTokens: 65535, thinkingBudget: 1024, isThinking: true },
28
- "claude-sonnet-4-6": { maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true },
29
- "claude-sonnet-4-6-thinking":{ maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true },
30
- "claude-opus-4-6-thinking": { maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true },
31
- "gpt-oss-120b-medium": { maxOutputTokens: 32768, thinkingBudget: 8192, isThinking: true },
32
- "gpt-oss-120b": { maxOutputTokens: 32768, thinkingBudget: 8192, isThinking: true },
10
+ "gemini-pro-agent": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true, contextWindow: 1_000_000 },
11
+ "gemini-3-flash-agent": { maxOutputTokens: 65536, thinkingBudget: 10000, isThinking: true, contextWindow: 1_000_000 },
12
+ "gemini-3-pro-high": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true, contextWindow: 1_000_000 },
13
+ "gemini-3-pro-low": { maxOutputTokens: 65535, thinkingBudget: 1001, isThinking: true, contextWindow: 1_000_000 },
14
+ "gemini-3.1-pro": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true, contextWindow: 1_000_000 },
15
+ "gemini-3.1-pro-high": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true, contextWindow: 1_000_000 },
16
+ "gemini-3.1-pro-low": { maxOutputTokens: 65535, thinkingBudget: 1001, isThinking: true, contextWindow: 1_000_000 },
17
+ "gemini-3.1-pro-preview": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true, contextWindow: 1_000_000 },
18
+ "gemini-3.5-flash": { maxOutputTokens: 65536, thinkingBudget: 10000, isThinking: true, contextWindow: 1_000_000 },
19
+ "gemini-3.5-flash-medium": { maxOutputTokens: 65536, thinkingBudget: 4000, isThinking: true, contextWindow: 1_000_000 },
20
+ "gemini-3.5-flash-low": { maxOutputTokens: 65536, thinkingBudget: 4000, isThinking: true, contextWindow: 1_000_000 },
21
+ "gemini-3.5-flash-high": { maxOutputTokens: 65536, thinkingBudget: 10000, isThinking: true, contextWindow: 1_000_000 },
22
+ "gemini-3.6-flash-high": { maxOutputTokens: 65536, thinkingBudget: 10000, isThinking: true, contextWindow: 1_000_000 },
23
+ "gemini-3.6-flash-medium": { maxOutputTokens: 65536, thinkingBudget: 4000, isThinking: true, contextWindow: 1_000_000 },
24
+ "gemini-3.6-flash-low": { maxOutputTokens: 65536, thinkingBudget: 1000, isThinking: true, contextWindow: 1_000_000 },
25
+ "gemini-3.6-flash-tiered": { maxOutputTokens: 65536, thinkingBudget: -1, isThinking: true, contextWindow: 1_000_000 },
26
+ "gemini-3.7-flash-tiered": { maxOutputTokens: 65536, thinkingBudget: -1, isThinking: true, contextWindow: 1_000_000 },
27
+ "gemini-3-flash": { maxOutputTokens: 65536, thinkingBudget: 4000, isThinking: true, contextWindow: 1_000_000 },
28
+ "gemini-2.5-flash": { maxOutputTokens: 65535, thinkingBudget: 24576, isThinking: true, contextWindow: 1_000_000 },
29
+ "gemini-2.5-pro": { maxOutputTokens: 65535, thinkingBudget: 1024, isThinking: true, contextWindow: 1_000_000 },
30
+ "claude-sonnet-4-6": { maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true, contextWindow: 1_000_000 },
31
+ "claude-sonnet-4-6-thinking":{ maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true, contextWindow: 1_000_000 },
32
+ "claude-opus-4-6-thinking": { maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true, contextWindow: 1_000_000 },
33
+ "claude-opus-4-6": { maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true, contextWindow: 1_000_000 },
34
+ "gpt-oss-120b-medium": { maxOutputTokens: 32768, thinkingBudget: 8192, isThinking: true, contextWindow: 131_072 },
35
+ "gpt-oss-120b": { maxOutputTokens: 32768, thinkingBudget: 8192, isThinking: true, contextWindow: 131_072 },
33
36
  };
34
37
 
35
38
  let modelSpecsOverride: Record<string, ModelSpec> | null = null;
@@ -66,9 +69,9 @@ export function getModelSpec(model: string): ModelSpec {
66
69
  if (lower.includes(key)) return spec;
67
70
  }
68
71
  const family = getModelFamily(model);
69
- if (family === "claude") return { maxOutputTokens: CLAUDE_MAX_OUTPUT_TOKENS, thinkingBudget: CLAUDE_DEFAULT_THINKING_BUDGET, isThinking: true };
70
- if (family === "gemini") return { maxOutputTokens: GEMINI_MAX_OUTPUT_TOKENS, thinkingBudget: FALLBACK_THINKING_BUDGET, isThinking: true };
71
- return { maxOutputTokens: 65536, thinkingBudget: FALLBACK_THINKING_BUDGET, isThinking: false };
72
+ if (family === "claude") return { maxOutputTokens: CLAUDE_MAX_OUTPUT_TOKENS, thinkingBudget: CLAUDE_DEFAULT_THINKING_BUDGET, isThinking: true, contextWindow: 1_000_000 };
73
+ if (family === "gemini") return { maxOutputTokens: GEMINI_MAX_OUTPUT_TOKENS, thinkingBudget: FALLBACK_THINKING_BUDGET, isThinking: true, contextWindow: 1_000_000 };
74
+ return { maxOutputTokens: 65536, thinkingBudget: FALLBACK_THINKING_BUDGET, isThinking: false, contextWindow: 128_000 };
72
75
  }
73
76
 
74
77
  export function isThinkingModel(model: string): boolean {
package/src/compat.ts CHANGED
@@ -2036,7 +2036,7 @@ const MODEL_CATALOG = [
2036
2036
  {
2037
2037
  id: "claude-sonnet-4-6",
2038
2038
  family: "claude",
2039
- ctx: 500000,
2039
+ ctx: 1000000,
2040
2040
  quotaPool: "claude",
2041
2041
  multimodal: true,
2042
2042
  tools: true,
@@ -2044,7 +2044,7 @@ const MODEL_CATALOG = [
2044
2044
  {
2045
2045
  id: "claude-opus-4-6-thinking",
2046
2046
  family: "claude",
2047
- ctx: 500000,
2047
+ ctx: 1000000,
2048
2048
  quotaPool: "claude",
2049
2049
  multimodal: true,
2050
2050
  tools: true,
@@ -0,0 +1,99 @@
1
+ // Google Antigravity provider catalog: per-model context windows.
2
+ //
3
+ // Sources (verified at fetch time):
4
+ // - Google DeepMind model pages (https://deepmind.google/models/gemini/*)
5
+ // - Google AI Studio / Gemini API docs (https://ai.google.dev/gemini-api/docs/models)
6
+ // - Anthropic Claude models overview (https://docs.anthropic.com/en/docs/about-claude/models/overview)
7
+ // - OpenAI model docs (https://platform.openai.com/docs/models, https://platform.openai.com/docs/models/gpt-oss-120b)
8
+ //
9
+ // Values reflect input/context window only. Output max tokens are tracked
10
+ // separately in `src/compat/model-specs.ts` via `maxOutputTokens`.
11
+
12
+ export interface AntigravityModelSpec {
13
+ id: string;
14
+ contextWindow: number;
15
+ }
16
+
17
+ /**
18
+ * Exact context windows per Antigravity (Cloud Code Assist) model id, as
19
+ * published by the upstream providers.
20
+ *
21
+ * The keys are normalized to the lower-cased id used by the request path so
22
+ * `getAntigravityContextWindow` can do an O(1) lookup.
23
+ */
24
+ export const ANTIGRAVITY_CONTEXT_WINDOWS: Record<string, number> = {
25
+ // Anthropic Claude 4.6 family — 1M context window per Anthropic docs.
26
+ "claude-opus-4-6": 1_000_000,
27
+ "claude-opus-4-6-thinking": 1_000_000,
28
+ "claude-sonnet-4-6": 1_000_000,
29
+ "claude-sonnet-4-6-thinking": 1_000_000,
30
+ // Anthropic Claude 4.5 family — 200K context window per Anthropic docs.
31
+ "claude-opus-4-5": 200_000,
32
+ "claude-opus-4-5-thinking": 200_000,
33
+ "claude-sonnet-4-5": 200_000,
34
+ "claude-sonnet-4-5-thinking": 200_000,
35
+ // OpenAI gpt-oss-120b — 131,072 per platform.openai.com/docs/models/gpt-oss-120b.
36
+ "gpt-oss-120b": 131_072,
37
+ "gpt-oss-120b-medium": 131_072,
38
+ // Google Gemini 3.x — 1M context window per deepmind.google/models/gemini/*.
39
+ "gemini-3.7-flash": 1_000_000,
40
+ "gemini-3.7-flash-tiered": 1_000_000,
41
+ "gemini-3.6-flash": 1_000_000,
42
+ "gemini-3.6-flash-high": 1_000_000,
43
+ "gemini-3.6-flash-medium": 1_000_000,
44
+ "gemini-3.6-flash-low": 1_000_000,
45
+ "gemini-3.6-flash-tiered": 1_000_000,
46
+ "gemini-3.5-flash": 1_000_000,
47
+ "gemini-3.5-flash-medium": 1_000_000,
48
+ "gemini-3.5-flash-low": 1_000_000,
49
+ "gemini-3.5-flash-high": 1_000_000,
50
+ "gemini-3.5-flash-lite": 1_000_000,
51
+ "gemini-3-flash": 1_000_000,
52
+ "gemini-3-flash-agent": 1_000_000,
53
+ "gemini-3-pro": 1_000_000,
54
+ "gemini-3-pro-high": 1_000_000,
55
+ "gemini-3-pro-low": 1_000_000,
56
+ "gemini-3.1-pro": 1_000_000,
57
+ "gemini-3.1-pro-high": 1_000_000,
58
+ "gemini-3.1-pro-low": 1_000_000,
59
+ "gemini-3.1-pro-preview": 1_000_000,
60
+ // Google Gemini 2.5 — 1M context window per Google docs.
61
+ "gemini-2.5-pro": 1_000_000,
62
+ "gemini-2.5-flash": 1_000_000,
63
+ // Antigravity-internal alias mapped to the Gemini Pro family.
64
+ "gemini-pro-agent": 1_000_000,
65
+ };
66
+
67
+ const CLAUDE_DEFAULT_CONTEXT_WINDOW = 1_000_000;
68
+ const GEMINI_DEFAULT_CONTEXT_WINDOW = 1_000_000;
69
+ const GPT_OSS_DEFAULT_CONTEXT_WINDOW = 131_072;
70
+ const FALLBACK_CONTEXT_WINDOW = 128_000;
71
+
72
+ /**
73
+ * Resolve the upstream-published context window for an Antigravity model id.
74
+ *
75
+ * Lookup order:
76
+ * 1. Exact id match (lowercased).
77
+ * 2. Substring match across the table (longest key wins via the order here).
78
+ * 3. Family defaults: claude -> 1M, gemini -> 1M, gpt-oss -> 131_072.
79
+ * 4. Defensive fallback: 128_000.
80
+ */
81
+ export function getAntigravityContextWindow(model: string): number {
82
+ if (!model) return FALLBACK_CONTEXT_WINDOW;
83
+ const lower = model.toLowerCase().trim();
84
+ if (!lower) return FALLBACK_CONTEXT_WINDOW;
85
+ const exact = ANTIGRAVITY_CONTEXT_WINDOWS[lower];
86
+ if (typeof exact === "number") return exact;
87
+ // Substring fallback: pick the longest registered key that appears in lower.
88
+ let best: { key: string; value: number } | null = null;
89
+ for (const [key, value] of Object.entries(ANTIGRAVITY_CONTEXT_WINDOWS)) {
90
+ if (lower.includes(key)) {
91
+ if (!best || key.length > best.key.length) best = { key, value };
92
+ }
93
+ }
94
+ if (best) return best.value;
95
+ if (lower.includes("claude")) return CLAUDE_DEFAULT_CONTEXT_WINDOW;
96
+ if (lower.includes("gemini")) return GEMINI_DEFAULT_CONTEXT_WINDOW;
97
+ if (lower.includes("gpt-oss")) return GPT_OSS_DEFAULT_CONTEXT_WINDOW;
98
+ return FALLBACK_CONTEXT_WINDOW;
99
+ }
@@ -51,6 +51,11 @@ async function ensureGoogleToken(account: AccountRuntime): Promise<void> {
51
51
  `Account ${account.config.email} has no refreshToken; re-run login`,
52
52
  );
53
53
  }
54
+ if (account.config.refreshToken.startsWith("enc:")) {
55
+ throw new Error(
56
+ `Account ${account.config.email} has an encrypted refreshToken (enc:*) but it could not be decrypted. Set TUXEVIL_ROTATOR_ENCRYPTION_KEY or re-run login.`,
57
+ );
58
+ }
54
59
  const oauth = getOAuthClientConfig();
55
60
  const response = await fetchWithRetry(TOKEN_URL, {
56
61
  method: "POST",
@@ -0,0 +1,117 @@
1
+ // Ollama Cloud model info: read the upstream-published context window for an
2
+ // Ollama model from `POST /api/show`.
3
+ //
4
+ // `/api/show` returns `model_info.<arch>.context_length` for the active
5
+ // quantisation (and several other arch-specific lengths for older builds).
6
+ // We pick the largest positive value across the `model_info` keys. If the
7
+ // endpoint is unavailable (e.g. anonymous `/api/tags` cache when no Ollama
8
+ // account is configured) we fall back to the operator-provided
9
+ // `OLLAMA_NUM_CTX` env var, defaulting to 8192 (Ollama's own `num_ctx`
10
+ // default per https://github.com/ollama/ollama/blob/main/docs/faq.md).
11
+
12
+ import {
13
+ OLLAMA_API_BASE,
14
+ TAGS_CACHE_TTL_MS,
15
+ } from "../../types.js";
16
+ import type { AccountRuntime } from "../../types.js";
17
+ import { rotatorEnv } from "../../env.js";
18
+ import { getOllamaApiKey } from "./credentials.js";
19
+ import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
20
+
21
+ const DEFAULT_OLLAMA_NUM_CTX = 8_192;
22
+
23
+ interface CacheEntry {
24
+ contextWindow: number;
25
+ expiresAt: number;
26
+ }
27
+
28
+ const cache = new Map<string, CacheEntry>();
29
+
30
+ function defaultNumCtx(): number {
31
+ const raw = rotatorEnv("OLLAMA_NUM_CTX") ?? rotatorEnv("OLLAMA_CONTEXT_LENGTH");
32
+ if (!raw) return DEFAULT_OLLAMA_NUM_CTX;
33
+ const parsed = Number.parseInt(raw, 10);
34
+ if (!Number.isFinite(parsed) || parsed <= 0) return DEFAULT_OLLAMA_NUM_CTX;
35
+ return parsed;
36
+ }
37
+
38
+ /**
39
+ * Read `POST /api/show` from Ollama Cloud. Returns an empty object when the
40
+ * model cannot be fetched (offline, missing creds, missing field).
41
+ */
42
+ async function fetchOllamaShowPayload(
43
+ account: AccountRuntime | undefined,
44
+ model: string,
45
+ signal?: AbortSignal,
46
+ ): Promise<Record<string, unknown>> {
47
+ const apiKey = account ? getOllamaApiKey(account.config) : undefined;
48
+ if (!apiKey) return {};
49
+ const dispatcher = account
50
+ ? getAccountProxyDispatcher(account, "ollama")
51
+ : undefined;
52
+ const headers: Record<string, string> = {
53
+ "Content-Type": "application/json",
54
+ Accept: "application/json",
55
+ Authorization: `Bearer ${apiKey}`,
56
+ };
57
+ const init: RequestInit & { dispatcher?: unknown; signal?: AbortSignal } = {
58
+ method: "POST",
59
+ headers,
60
+ body: JSON.stringify({ name: model, verbose: false }),
61
+ signal: signal ?? AbortSignal.timeout(4_000),
62
+ };
63
+ if (dispatcher) init.dispatcher = dispatcher;
64
+ try {
65
+ const res = await fetch(`${OLLAMA_API_BASE}/show`, init);
66
+ if (!res.ok) return {};
67
+ const data = await res.json() as Record<string, unknown>;
68
+ return data ?? {};
69
+ } catch {
70
+ return {};
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Pull a positive integer context length out of `model_info`. The Ollama
76
+ * Go server publishes per-arch keys like `llama.context_length`,
77
+ * `qwen2.context_length`, `gptoss.context_length`, etc. We pick the
78
+ * largest positive candidate as the upper bound.
79
+ */
80
+ function extractContextWindow(modelInfo: unknown): number | undefined {
81
+ if (!modelInfo || typeof modelInfo !== "object") return undefined;
82
+ let best: number | undefined;
83
+ for (const [key, value] of Object.entries(modelInfo as Record<string, unknown>)) {
84
+ if (!key.endsWith(".context_length")) continue;
85
+ if (typeof value !== "number") continue;
86
+ if (!Number.isFinite(value) || value <= 0) continue;
87
+ if (best === undefined || value > best) best = value;
88
+ }
89
+ return best;
90
+ }
91
+
92
+ /**
93
+ * Resolve the Ollama Cloud context window for a model id. Cached for
94
+ * `TAGS_CACHE_TTL_MS` (currently 5 minutes — same TTL as `/api/tags`).
95
+ *
96
+ * Returns the operator `OLLAMA_NUM_CTX` fallback when `/api/show` is not
97
+ * reachable or does not include a `context_length`.
98
+ */
99
+ export async function getOllamaContextWindow(
100
+ model: string,
101
+ account?: AccountRuntime,
102
+ ): Promise<number> {
103
+ if (!model) return defaultNumCtx();
104
+ const now = Date.now();
105
+ const cached = cache.get(model);
106
+ if (cached && cached.expiresAt > now) return cached.contextWindow;
107
+ const payload = await fetchOllamaShowPayload(account, model);
108
+ const modelInfo = (payload as { model_info?: unknown }).model_info;
109
+ const detected = extractContextWindow(modelInfo);
110
+ const contextWindow = typeof detected === "number" ? detected : defaultNumCtx();
111
+ cache.set(model, { contextWindow, expiresAt: now + TAGS_CACHE_TTL_MS });
112
+ return contextWindow;
113
+ }
114
+
115
+ export function clearOllamaContextCache(): void {
116
+ cache.clear();
117
+ }
@@ -91,3 +91,4 @@ export const ollamaAdapter: ProviderAdapter = {
91
91
  };
92
92
 
93
93
  export type { ExhaustionPrediction, UsagePredictor };
94
+ export { getOllamaContextWindow, clearOllamaContextCache } from "./context-window.js";
@@ -18,7 +18,13 @@ export interface CodexModel {
18
18
  // The Codex /models endpoint can expose models from other ChatGPT-backed
19
19
  // providers (for example Claude), so model IDs alone must be filtered before
20
20
  // they influence routing.
21
- const CODEX_CONTEXT_WINDOW = 272_000;
21
+ // Official context window for the GPT-5.6 family per
22
+ // https://platform.openai.com/docs/models (gpt-5.6-sol / gpt-5.6-terra / gpt-5.6-luna
23
+ // each report 1.05M context / 128K max output).
24
+ const CODEX_CONTEXT_WINDOW = 1_050_000;
25
+ // Hard cap to defend against `/models` upstream reporting absurd values for
26
+ // discovered ids. 2M is comfortably above the published 1.05M baseline.
27
+ const CODEX_DISCOVERED_MAX_CONTEXT_WINDOW = 2_000_000;
22
28
  const CODEX_DISCOVERED_ID_PATTERN = /^gpt-5(?:\.\d+)?(?:-[a-z0-9]+)+$/i;
23
29
  export const CODEX_BASE_MODELS: readonly CodexModel[] = [
24
30
  { id: "gpt-5.6-sol", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
@@ -77,7 +83,7 @@ function parseModel(value: unknown): CodexModel | null {
77
83
  .find((candidate) => typeof candidate === "number" && Number.isFinite(candidate) && candidate > 0);
78
84
  return {
79
85
  id,
80
- contextWindow: typeof contextWindow === "number" ? Math.min(contextWindow, 2_000_000) : CODEX_CONTEXT_WINDOW,
86
+ contextWindow: typeof contextWindow === "number" ? Math.min(contextWindow, CODEX_DISCOVERED_MAX_CONTEXT_WINDOW) : CODEX_CONTEXT_WINDOW,
81
87
  reasoning: record.reasoning !== false,
82
88
  multimodal: record.multimodal !== false && record.vision !== false,
83
89
  tools: record.tools !== false && record.tool_calling !== false,
@@ -20,14 +20,26 @@ export interface OpenCodeZenModelSpec {
20
20
  free: boolean;
21
21
  }
22
22
 
23
+ // TODO: replace placeholders with per-model official context windows once
24
+ // OpenCode publishes specs at https://opencode.ai/zen or /docs/models. Until
25
+ // then all curated `*-free` models advertise a conservative 128K window
26
+ // (validated by the upstream Providers Anomaly team in their "reliable
27
+ // optimized models for coding agents" announcement, which stated tested-
28
+ // consistent windows without enumerating per-model values).
29
+ const OPENCODE_ZEN_DEFAULT_CONTEXT_WINDOW = 128_000;
30
+
23
31
  export const OPENCODE_ZEN_CATALOG: OpenCodeZenModelSpec[] = OPENCODE_ZEN_FREE_MODELS.map(
24
32
  (id) => ({
25
33
  id,
26
- contextWindow: 128000,
34
+ contextWindow: OPENCODE_ZEN_DEFAULT_CONTEXT_WINDOW,
27
35
  free: true,
28
36
  }),
29
37
  );
30
38
 
39
+ export function getOpenCodeZenContextWindow(_model: string): number {
40
+ return OPENCODE_ZEN_DEFAULT_CONTEXT_WINDOW;
41
+ }
42
+
31
43
  const OPENCODE_ZEN_MODEL_SET = new Set<string>(OPENCODE_ZEN_FREE_MODELS);
32
44
 
33
45
  export function isOpenCodeZenModel(model: string): boolean {
package/src/proxy.ts CHANGED
@@ -1139,17 +1139,6 @@ export async function withRotation<T>(
1139
1139
  };
1140
1140
  };
1141
1141
 
1142
- const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
1143
- const nextAccount = await rotator.rotateToNext(model);
1144
- if (nextAccount) {
1145
- rotator.finishRequest(
1146
- nextAccount,
1147
- routingModelKey(rotator, model),
1148
- );
1149
- }
1150
- return nextAccount;
1151
- };
1152
-
1153
1142
  const maxRetries = getStreamRecoveryMaxRetries(rotator);
1154
1143
  const maxAttempts = maxRetries + 1;
1155
1144
 
@@ -1164,6 +1153,17 @@ export async function withRotation<T>(
1164
1153
  const displayModelKey = resolveDisplayModelKey(body.displayModel || model);
1165
1154
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
1166
1155
  const requestStartMs = Date.now();
1156
+ let accountReleased = false;
1157
+ const releaseCurrentAccount = (): void => {
1158
+ if (accountReleased) return;
1159
+ accountReleased = true;
1160
+ rotator.finishRequest(account, modelKey);
1161
+ };
1162
+ const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
1163
+ releaseCurrentAccount();
1164
+ const nextAccount = await rotator.rotateToNext(model, account);
1165
+ return nextAccount;
1166
+ };
1167
1167
  const logRequestEnd = (status: string | number, extra = ""): void => {
1168
1168
  log(
1169
1169
  `[${requestId}] END account=${label} model=${model} status=${status}${extra ? ` ${extra}` : ""} totalMs=${Date.now() - requestStartMs}`,
@@ -1258,7 +1258,7 @@ export async function withRotation<T>(
1258
1258
  const shouldRotate = rotator.recordRequest(account, model);
1259
1259
  logRequestEnd(response.status, `endpoint=${endpoint}`);
1260
1260
  if (shouldRotate) {
1261
- await rotateAndRelease();
1261
+ await rotator.rotateToNext(model, account);
1262
1262
  }
1263
1263
  return { ok: true, result, endpoint, context };
1264
1264
  } catch (err) {
@@ -1317,7 +1317,7 @@ export async function withRotation<T>(
1317
1317
  }
1318
1318
  continue;
1319
1319
  } finally {
1320
- rotator.finishRequest(account, routingModelKey(rotator, model));
1320
+ releaseCurrentAccount();
1321
1321
  }
1322
1322
  }
1323
1323
 
@@ -1477,16 +1477,6 @@ async function handleProxyRequest(
1477
1477
  }),
1478
1478
  );
1479
1479
  };
1480
- const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
1481
- const nextAccount = await rotator.rotateToNext(body.model);
1482
- if (nextAccount) {
1483
- rotator.finishRequest(
1484
- nextAccount,
1485
- routingModelKey(rotator, body.model),
1486
- );
1487
- }
1488
- return nextAccount;
1489
- };
1490
1480
  const sendFailureDecision = (decision: UpstreamFailureDecision): void => {
1491
1481
  if (decision.noReplacementReason) {
1492
1482
  sendNoAccountsAvailable(decision.noReplacementReason);
@@ -1564,6 +1554,20 @@ async function handleProxyRequest(
1564
1554
  const modelKey = rotator.resolveQuotaModelKeyForDisplay(body.model) ?? body.model; // quota routing
1565
1555
  const displayModelKey = resolveDisplayModelKey(body.model); // metrics/logs
1566
1556
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
1557
+ let accountReleased = false;
1558
+ const releaseCurrentAccount = (): void => {
1559
+ if (accountReleased) return;
1560
+ accountReleased = true;
1561
+ rotator.finishRequest(
1562
+ account,
1563
+ routingModelKey(rotator, body.model),
1564
+ );
1565
+ };
1566
+ const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
1567
+ releaseCurrentAccount();
1568
+ const nextAccount = await rotator.rotateToNext(body.model, account);
1569
+ return nextAccount;
1570
+ };
1567
1571
  proxyLog(
1568
1572
  `[${requestId}] START account=${label} model=${body.model} attempt=${attempt + 1}`,
1569
1573
  );
@@ -1746,7 +1750,7 @@ async function handleProxyRequest(
1746
1750
  res.end();
1747
1751
 
1748
1752
  if (shouldRotate) {
1749
- await rotateAndRelease();
1753
+ await rotator.rotateToNext(body.model, account);
1750
1754
  }
1751
1755
  return;
1752
1756
  } catch (err) {
@@ -1781,10 +1785,7 @@ async function handleProxyRequest(
1781
1785
  }
1782
1786
  continue;
1783
1787
  } finally {
1784
- rotator.finishRequest(
1785
- account,
1786
- routingModelKey(rotator, body.model),
1787
- );
1788
+ releaseCurrentAccount();
1788
1789
  if (onComplete) onComplete();
1789
1790
  }
1790
1791
  }
@@ -1850,6 +1851,16 @@ async function handleCodeAssistPassthrough(
1850
1851
  return;
1851
1852
  }
1852
1853
 
1854
+ let accountReleased = false;
1855
+ const releaseCurrentAccount = (): void => {
1856
+ if (accountReleased) return;
1857
+ accountReleased = true;
1858
+ rotator.finishRequest(
1859
+ account,
1860
+ resolveQuotaModelKey(CODE_ASSIST_ROUTING_MODEL) ?? undefined,
1861
+ );
1862
+ };
1863
+
1853
1864
  try {
1854
1865
  // getActiveAccount performs the normal account lifecycle check, but the
1855
1866
  // explicit provider call is required for dual Google+Ollama accounts.
@@ -1873,22 +1884,16 @@ async function handleCodeAssistPassthrough(
1873
1884
  res.end(JSON.stringify({ error: "Code Assist upstream request failed" }));
1874
1885
  return;
1875
1886
  }
1876
- const nextAccount = await rotator.rotateToNext(CODE_ASSIST_ROUTING_MODEL);
1887
+ releaseCurrentAccount();
1888
+ const nextAccount = await rotator.rotateToNext(CODE_ASSIST_ROUTING_MODEL, account);
1877
1889
  if (nextAccount) {
1878
- rotator.finishRequest(
1879
- nextAccount,
1880
- resolveQuotaModelKey(CODE_ASSIST_ROUTING_MODEL) ?? undefined,
1881
- );
1882
1890
  continue;
1883
1891
  }
1884
1892
  res.writeHead(503, { "Content-Type": "application/json" });
1885
1893
  res.end(JSON.stringify({ error: "No replacement Google account available" }));
1886
1894
  return;
1887
1895
  } finally {
1888
- rotator.finishRequest(
1889
- account,
1890
- resolveQuotaModelKey(CODE_ASSIST_ROUTING_MODEL) ?? undefined,
1891
- );
1896
+ releaseCurrentAccount();
1892
1897
  }
1893
1898
  }
1894
1899
  }