tuxevil-rotator 3.2.1 → 3.2.2

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,23 @@
1
1
  # Changelog
2
2
 
3
+ ## [3.2.2] - 2026-08-21
4
+
5
+ ### Fixed
6
+ - **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)).
7
+ - **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)).
8
+ - **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)).
9
+ - `/v1/models` no longer reports the outdated 500K Claude context window.
10
+
11
+ ### Added
12
+ - **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.
13
+ - **`/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).
14
+ - **`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.
15
+
16
+ ### Changed
17
+ - **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.
18
+ - **OpenCode Zen catalog now exposes a per-id helper** (`getOpenCodeZenContextWindow`) that documents the placeholder 128K window until OpenCode publishes per-model specs.
19
+ - **`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.
20
+
3
21
  ## [3.2.1] - 2026-08-16
4
22
 
5
23
  ### 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) — 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))
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.2",
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
+ }
@@ -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 {
@@ -5,6 +5,7 @@ import { rotatorEnv } from "./env.js";
5
5
 
6
6
  const FLUSH_INTERVAL_MS = 5_000;
7
7
  const MAX_QUEUE_SIZE = 50;
8
+ const MAX_QUEUE_CAP = 100;
8
9
  const DEFAULT_KEY_HASH_LABEL = "unauthenticated";
9
10
 
10
11
  const storeMessagesConfig =
@@ -19,6 +20,27 @@ let queue: SpendLog[] = [];
19
20
  let flushTimer: ReturnType<typeof setTimeout> | null = null;
20
21
  let isFlushing = false;
21
22
 
23
+ export function getSpendQueueSizeForTests(): number {
24
+ return queue.length;
25
+ }
26
+
27
+ export function getSpendQueueItemsForTests(): SpendLog[] {
28
+ return [...queue];
29
+ }
30
+
31
+ export function setSpendQueueForTests(items: SpendLog[]): void {
32
+ queue = [...items];
33
+ }
34
+
35
+ export function resetSpendLoggerForTests(): void {
36
+ queue = [];
37
+ if (flushTimer) {
38
+ clearTimeout(flushTimer);
39
+ flushTimer = null;
40
+ }
41
+ isFlushing = false;
42
+ }
43
+
22
44
  export function generateRequestId(): string {
23
45
  return `req_${Date.now().toString(36)}_${randomBytes.randomBytes(8).toString("hex")}`;
24
46
  }
@@ -32,6 +54,11 @@ export function logSpend(
32
54
  totalTokens?: number;
33
55
  },
34
56
  ): void {
57
+ if (!isDbConfigured()) {
58
+ if (queue.length > 0) queue = [];
59
+ return;
60
+ }
61
+
35
62
  const pricing = MODEL_PRICING[log.model] || { inputPer1M: 0, outputPer1M: 0 };
36
63
  const promptTokens = Math.max(0, log.promptTokens || 0);
37
64
  const completionTokens = Math.max(0, log.completionTokens || 0);
@@ -71,6 +98,9 @@ export function logSpend(
71
98
  createdAt: new Date().toISOString(),
72
99
  };
73
100
 
101
+ if (queue.length >= MAX_QUEUE_CAP) {
102
+ queue.splice(0, queue.length - MAX_QUEUE_CAP + 1);
103
+ }
74
104
  queue.push(fullLog);
75
105
 
76
106
  if (queue.length >= MAX_QUEUE_SIZE) {
@@ -137,23 +167,52 @@ function cleanValue(val: unknown, depth = 0): unknown {
137
167
  * Flush accumulated spend logs to database.
138
168
  */
139
169
  export async function flushSpendLogs(): Promise<void> {
140
- if (isFlushing || queue.length === 0 || !isDbConfigured()) return;
170
+ if (!isDbConfigured()) {
171
+ queue = [];
172
+ return;
173
+ }
174
+ if (isFlushing || queue.length === 0) return;
141
175
  isFlushing = true;
142
176
 
143
177
  const logsToFlush = queue;
144
178
  queue = [];
145
179
 
180
+ let lastProcessedIndex = -1;
146
181
  try {
147
- for (const log of logsToFlush) {
148
- // 1. Insert detailed spend log
182
+ for (let i = 0; i < logsToFlush.length; i++) {
183
+ const log = logsToFlush[i];
184
+ const dateStr = log.startTime.slice(0, 10); // YYYY-MM-DD
185
+ const keyHashForDaily = log.apiKeyHash || DEFAULT_KEY_HASH_LABEL;
186
+ const isSuccess = log.status === "success" ? 1 : 0;
187
+ const isFail = log.status === "failure" ? 1 : 0;
188
+
189
+ // Atomic insert: detailed log + daily aggregation in a single query CTE.
190
+ // If the request_id was already inserted, ins_log yields 0 rows, making
191
+ // the daily aggregation update completely idempotent against retries.
149
192
  await queryDb(
150
- `INSERT INTO rotator_spend_logs (
151
- request_id, api_key_hash, model, account_email, call_type, status,
152
- prompt_tokens, completion_tokens, total_tokens, start_time, end_time,
153
- ttfb_ms, duration_ms, request_messages, response_content, metadata,
154
- requester_ip, created_at
155
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)
156
- ON CONFLICT (request_id) DO NOTHING`,
193
+ `WITH ins_log AS (
194
+ INSERT INTO rotator_spend_logs (
195
+ request_id, api_key_hash, model, account_email, call_type, status,
196
+ prompt_tokens, completion_tokens, total_tokens, start_time, end_time,
197
+ ttfb_ms, duration_ms, request_messages, response_content, metadata,
198
+ requester_ip, created_at
199
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)
200
+ ON CONFLICT (request_id) DO NOTHING
201
+ RETURNING request_id
202
+ )
203
+ INSERT INTO rotator_daily_spend (
204
+ api_key_hash, model, date, prompt_tokens, completion_tokens,
205
+ total_requests, successful_requests, failed_requests, total_duration_ms
206
+ )
207
+ SELECT $19, $3, $20::date, $7, $8, 1, $21, $22, $13
208
+ FROM ins_log
209
+ ON CONFLICT (api_key_hash, model, date) DO UPDATE SET
210
+ prompt_tokens = rotator_daily_spend.prompt_tokens + EXCLUDED.prompt_tokens,
211
+ completion_tokens = rotator_daily_spend.completion_tokens + EXCLUDED.completion_tokens,
212
+ total_requests = rotator_daily_spend.total_requests + 1,
213
+ successful_requests = rotator_daily_spend.successful_requests + EXCLUDED.successful_requests,
214
+ failed_requests = rotator_daily_spend.failed_requests + EXCLUDED.failed_requests,
215
+ total_duration_ms = rotator_daily_spend.total_duration_ms + EXCLUDED.total_duration_ms`,
157
216
  [
158
217
  log.requestId,
159
218
  log.apiKeyHash,
@@ -173,43 +232,21 @@ export async function flushSpendLogs(): Promise<void> {
173
232
  JSON.stringify(log.metadata || {}),
174
233
  log.requesterIp,
175
234
  log.createdAt || new Date().toISOString(),
176
- ],
177
- );
178
-
179
- // 2. Upsert daily aggregation
180
- const dateStr = log.startTime.slice(0, 10); // YYYY-MM-DD
181
- const keyHashForDaily = log.apiKeyHash || DEFAULT_KEY_HASH_LABEL;
182
- const isSuccess = log.status === "success" ? 1 : 0;
183
- const isFail = log.status === "failure" ? 1 : 0;
184
-
185
- await queryDb(
186
- `INSERT INTO rotator_daily_spend (
187
- api_key_hash, model, date, prompt_tokens, completion_tokens,
188
- total_requests, successful_requests, failed_requests, total_duration_ms
189
- ) VALUES ($1, $2, $3, $4, $5, 1, $6, $7, $8)
190
- ON CONFLICT (api_key_hash, model, date) DO UPDATE SET
191
- prompt_tokens = rotator_daily_spend.prompt_tokens + EXCLUDED.prompt_tokens,
192
- completion_tokens = rotator_daily_spend.completion_tokens + EXCLUDED.completion_tokens,
193
- total_requests = rotator_daily_spend.total_requests + 1,
194
- successful_requests = rotator_daily_spend.successful_requests + EXCLUDED.successful_requests,
195
- failed_requests = rotator_daily_spend.failed_requests + EXCLUDED.failed_requests,
196
- total_duration_ms = rotator_daily_spend.total_duration_ms + EXCLUDED.total_duration_ms`,
197
- [
198
235
  keyHashForDaily,
199
- log.model,
200
236
  dateStr,
201
- log.promptTokens,
202
- log.completionTokens,
203
237
  isSuccess,
204
238
  isFail,
205
- log.durationMs,
206
239
  ],
207
240
  );
241
+
242
+ lastProcessedIndex = i;
208
243
  }
209
244
  } catch (err) {
210
245
  console.error("Failed to flush spend logs to database:", err);
211
- // Put unfetched items back in queue if flush failed
212
- queue = [...logsToFlush, ...queue];
246
+ // Put only uncommitted items back in queue and consistently enforce FIFO (keep newest, drop oldest)
247
+ const uncommitted = logsToFlush.slice(lastProcessedIndex + 1);
248
+ const combined = [...uncommitted, ...queue];
249
+ queue = combined.length > MAX_QUEUE_CAP ? combined.slice(-MAX_QUEUE_CAP) : combined;
213
250
  } finally {
214
251
  isFlushing = false;
215
252
  }
@@ -15,9 +15,33 @@ interface CachedKey {
15
15
  fetchedAt: number;
16
16
  }
17
17
 
18
+ const KEY_CACHE_MAX = 500;
18
19
  const keyCache = new Map<string, CachedKey>(); // tokenHash -> CachedKey
19
20
  let hasKeysCache: { value: boolean; fetchedAt: number } | null = null;
20
21
 
22
+ export function getKeyCacheSizeForTests(): number {
23
+ return keyCache.size;
24
+ }
25
+
26
+ function setCachedKey(tokenHash: string, entry: CachedKey): void {
27
+ const now = Date.now();
28
+ if (keyCache.size >= KEY_CACHE_MAX) {
29
+ // Prune expired entries first
30
+ for (const [k, v] of keyCache.entries()) {
31
+ if (now - v.fetchedAt >= CACHE_TTL_MS) {
32
+ keyCache.delete(k);
33
+ }
34
+ }
35
+ // If still at capacity, drop oldest entries (FIFO)
36
+ while (keyCache.size >= KEY_CACHE_MAX) {
37
+ const oldest = keyCache.keys().next();
38
+ if (oldest.done) break;
39
+ keyCache.delete(oldest.value);
40
+ }
41
+ }
42
+ keyCache.set(tokenHash, entry);
43
+ }
44
+
21
45
  // Debounced last_active updates to prevent DB write spam
22
46
  const pendingLastActive = new Set<string>();
23
47
  let lastActiveFlushTimer: ReturnType<typeof setTimeout> | null = null;
@@ -130,7 +154,7 @@ export async function generateVirtualKey(params: {
130
154
  );
131
155
 
132
156
  const key = mapRowToVirtualKey(res.rows[0]);
133
- keyCache.set(tokenHash, { key, fetchedAt: Date.now() });
157
+ setCachedKey(tokenHash, { key, fetchedAt: Date.now() });
134
158
  hasKeysCache = { value: true, fetchedAt: Date.now() };
135
159
 
136
160
  return { rawKey, key };
@@ -161,12 +185,12 @@ export async function lookupVirtualKey(
161
185
  );
162
186
 
163
187
  if (res.rows.length === 0) {
164
- keyCache.set(tokenHash, { key: null, fetchedAt: now });
188
+ setCachedKey(tokenHash, { key: null, fetchedAt: now });
165
189
  return null;
166
190
  }
167
191
 
168
192
  const key = mapRowToVirtualKey(res.rows[0]);
169
- keyCache.set(tokenHash, { key, fetchedAt: now });
193
+ setCachedKey(tokenHash, { key, fetchedAt: now });
170
194
  return key;
171
195
  } catch (err) {
172
196
  console.error("Failed to lookup virtual key:", err);
@@ -250,7 +274,7 @@ export async function updateVirtualKey(
250
274
  if (res.rows.length === 0) return null;
251
275
 
252
276
  const updated = mapRowToVirtualKey(res.rows[0]);
253
- keyCache.set(tokenHash, { key: updated, fetchedAt: Date.now() });
277
+ setCachedKey(tokenHash, { key: updated, fetchedAt: Date.now() });
254
278
  return updated;
255
279
  } catch (err) {
256
280
  console.error("Failed to update virtual key:", err);