tuxevil-rotator 3.2.0 → 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 +38 -0
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/account-store.ts +4 -3
- package/src/compat/model-specs.ts +31 -28
- package/src/compat.ts +2 -2
- package/src/index.ts +6 -2
- package/src/onboarding.ts +3 -3
- package/src/providers/google-antigravity/catalog.ts +99 -0
- package/src/providers/ollama/context-window.ts +117 -0
- package/src/providers/ollama/index.ts +1 -0
- package/src/providers/openai-codex/catalog.ts +8 -2
- package/src/providers/opencode-zen/catalog.ts +13 -1
- package/src/rotator.ts +21 -4
- package/src/settings-repository.ts +17 -14
- package/src/spend-logger.ts +75 -38
- package/src/virtual-keys.ts +28 -4
- package/tools/telemetry-receiver/receiver.js +5 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,43 @@
|
|
|
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
|
+
|
|
21
|
+
## [3.2.1] - 2026-08-16
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
|
|
25
|
+
- **Credential persistence across restarts with PostgreSQL**: When PostgreSQL is configured as the account store, credentials added via the login panel (`ollama`, `opencode-zen`, `openai-codex`) were stored using the legacy flat `apiKey` field instead of the structured `credentials[{provider, apiKey}]` shape. On the next quota poll, the rotator read back the correct structured credential from the database but the Ollama provider adapter found nothing, flagging the account with 401. The `handleOllamaCliLogin` onboarding handler now always persists as `credentials: [{ provider: "ollama", apiKey }]`.
|
|
26
|
+
|
|
27
|
+
- **OpenCode Zen and sibling credentials lost on `replaceConfig`**: When the dashboard config editor saved a new config (e.g. after changing routing settings), `replaceConfig()` merged credentials correctly in memory but then persisted the original unmerged `config.accounts` payload to PostgreSQL. After the next restart the database-sourced config lacked the `opencode-zen` (or `ollama`) credential entirely. The fix builds the merged account list first and persists that merged list, so no credential is ever dropped by a config save.
|
|
28
|
+
|
|
29
|
+
- **Legacy Ollama JSON re-imported on every boot with PostgreSQL**: `importLegacyOllamaRotatorAccounts()` ran unconditionally at startup, allowing a stale `~/.ollama-rotator/accounts.json` to re-introduce revoked API keys each time the service restarted. The import is now skipped when `TUXEVIL_ROTATOR_DATABASE_URL` is configured, making PostgreSQL the sole authoritative source.
|
|
30
|
+
|
|
31
|
+
- **`accounts.json` disk file migrated into PostgreSQL on startup**: `PostgresSettingsRepository.init()` migrated any on-disk `accounts.json` into the database on first boot. If the file contained an outdated credential it would silently overwrite the database value. The `accounts_json` key is now excluded from the disk-to-database migration path; only non-credential settings (state, token usage, admin token) are migrated from disk.
|
|
32
|
+
|
|
33
|
+
- **PostgreSQL writes were fire-and-forget**: Account config writes to PostgreSQL were non-blocking background promises. A service restart occurring within the write window could lose the latest credential update. All settings writes are now awaited before returning a success response.
|
|
34
|
+
|
|
35
|
+
- **`mergeCredentials` called on pre-normalization data in `addAccountToConfig`**: The merge was applied against the raw (possibly legacy-shaped) existing account instead of its normalized form, causing duplicate or missing credentials in edge cases. The existing account is now normalized before merging.
|
|
36
|
+
|
|
37
|
+
### Changed
|
|
38
|
+
|
|
39
|
+
- **`replaceConfig` syncs in-memory and persisted accounts atomically**: The merged account list is computed once and used for both `this.accounts`/`this.config` and the PostgreSQL write, preventing divergence.
|
|
40
|
+
|
|
3
41
|
## [3.2.0] - 2026-08-14
|
|
4
42
|
|
|
5
43
|
### Added
|
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.
|
|
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",
|
package/src/account-store.ts
CHANGED
|
@@ -92,7 +92,7 @@ function validateCredentialLengths(
|
|
|
92
92
|
|
|
93
93
|
export { validateAccountConfigLengths };
|
|
94
94
|
|
|
95
|
-
function mergeCredentials(
|
|
95
|
+
export function mergeCredentials(
|
|
96
96
|
existing: AccountConfig["credentials"] | undefined,
|
|
97
97
|
incoming: AccountConfig["credentials"] | undefined,
|
|
98
98
|
): AccountConfig["credentials"] {
|
|
@@ -141,10 +141,11 @@ export async function addAccountToConfig(
|
|
|
141
141
|
if (existing) {
|
|
142
142
|
assertCodexIdentityCompatible(existing, entryNorm);
|
|
143
143
|
validateCredentialLengths(entryNorm.credentials);
|
|
144
|
+
const existingNorm = normalizeAccountConfig(existing);
|
|
144
145
|
config.accounts[config.accounts.indexOf(existing)] = {
|
|
145
|
-
...
|
|
146
|
+
...existingNorm,
|
|
146
147
|
...entryNorm,
|
|
147
|
-
credentials: mergeCredentials(
|
|
148
|
+
credentials: mergeCredentials(existingNorm.credentials, entryNorm.credentials),
|
|
148
149
|
};
|
|
149
150
|
await saveAccountsConfig(config);
|
|
150
151
|
return { isNew: false };
|
|
@@ -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
|
-
"
|
|
32
|
-
"gpt-oss-120b":
|
|
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:
|
|
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:
|
|
2047
|
+
ctx: 1000000,
|
|
2048
2048
|
quotaPool: "claude",
|
|
2049
2049
|
multimodal: true,
|
|
2050
2050
|
tools: true,
|
package/src/index.ts
CHANGED
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
} from "./compat.js";
|
|
22
22
|
import { setModelAliasesOverride } from "./types.js";
|
|
23
23
|
import { readTextFile, writeTextFileAtomic } from "./storage.js";
|
|
24
|
-
import { initDb } from "./db-store.js";
|
|
24
|
+
import { initDb, isDbConfigured } from "./db-store.js";
|
|
25
25
|
import { runKeyMigrations } from "./key-migrations.js";
|
|
26
26
|
import { flushSpendLogs, stopRetentionCleanup, startRetentionCleanup } from "./spend-logger.js";
|
|
27
27
|
import { stopPendingSessionReaper } from "./onboarding.js";
|
|
@@ -170,7 +170,11 @@ export async function main(): Promise<void> {
|
|
|
170
170
|
|
|
171
171
|
await initDb();
|
|
172
172
|
await runKeyMigrations();
|
|
173
|
-
|
|
173
|
+
// PostgreSQL is the authoritative account store. Importing the legacy
|
|
174
|
+
// Ollama JSON here would allow a stale disk credential to re-enter on boot.
|
|
175
|
+
if (!isDbConfigured()) {
|
|
176
|
+
await importLegacyOllamaRotatorAccounts();
|
|
177
|
+
}
|
|
174
178
|
startRetentionCleanup();
|
|
175
179
|
|
|
176
180
|
const config = loadConfig();
|
package/src/onboarding.ts
CHANGED
|
@@ -924,12 +924,12 @@ async function handleOllamaCliLogin(
|
|
|
924
924
|
return;
|
|
925
925
|
}
|
|
926
926
|
|
|
927
|
-
const entry = {
|
|
927
|
+
const entry: AccountConfig = {
|
|
928
928
|
email: email || defaultAccountEmail(apiKey),
|
|
929
|
-
apiKey,
|
|
929
|
+
credentials: [{ provider: "ollama", apiKey }],
|
|
930
930
|
label: email || defaultAccountEmail(apiKey).split("@")[0],
|
|
931
931
|
};
|
|
932
|
-
if (entry.label.length > MAX_ACCOUNT_LABEL_LENGTH) {
|
|
932
|
+
if (typeof entry.label !== "string" || entry.label.length > MAX_ACCOUNT_LABEL_LENGTH) {
|
|
933
933
|
res.writeHead(400, { "Content-Type": "application/json" });
|
|
934
934
|
res.end(JSON.stringify({ ok: false, error: "Account label too long" }));
|
|
935
935
|
return;
|
|
@@ -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
|
+
}
|
|
@@ -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
|
-
|
|
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,
|
|
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:
|
|
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/rotator.ts
CHANGED
|
@@ -41,6 +41,7 @@ import {
|
|
|
41
41
|
applyConfigDefaults,
|
|
42
42
|
saveAccountsConfig,
|
|
43
43
|
removeAccountFromConfig,
|
|
44
|
+
mergeCredentials,
|
|
44
45
|
} from "./account-store.js";
|
|
45
46
|
import { isHostedOAuthConfigured } from "./providers/google-antigravity/oauth.js";
|
|
46
47
|
import type { RequestBody } from "./proxy.js";
|
|
@@ -799,7 +800,16 @@ export class AccountRotator {
|
|
|
799
800
|
: modelKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
|
|
800
801
|
? account.quota.find((candidate) => candidate.providerId === OPENCODE_ZEN_PROVIDER_ID)
|
|
801
802
|
: undefined);
|
|
802
|
-
|
|
803
|
+
if (!q) return -1;
|
|
804
|
+
// Ollama: the session pool is gated by the weekly pool. If the weekly
|
|
805
|
+
// quota is fully exhausted (0%), the account cannot accept any requests
|
|
806
|
+
// regardless of how much session quota remains. Treat it as 0 so the
|
|
807
|
+
// account is skipped at all call sites that check `quota === 0`.
|
|
808
|
+
if (modelKey === "session") {
|
|
809
|
+
const weekly = account.quota.find((w) => w.modelKey === "weekly");
|
|
810
|
+
if (weekly && weekly.percentRemaining === 0) return 0;
|
|
811
|
+
}
|
|
812
|
+
return q.percentRemaining;
|
|
803
813
|
}
|
|
804
814
|
|
|
805
815
|
// Get timer type for a specific model on an account
|
|
@@ -3157,13 +3167,17 @@ export class AccountRotator {
|
|
|
3157
3167
|
const previous = new Map(
|
|
3158
3168
|
this.accounts.map((account) => [account.config.email, account]),
|
|
3159
3169
|
);
|
|
3160
|
-
|
|
3161
|
-
this.accounts = normalized.accounts.map((config) => {
|
|
3170
|
+
const mergedAccounts = normalized.accounts.map((config) => {
|
|
3162
3171
|
const existing = previous.get(config.email);
|
|
3163
3172
|
if (existing) {
|
|
3173
|
+
const mergedConfig = {
|
|
3174
|
+
...existing.config,
|
|
3175
|
+
...config,
|
|
3176
|
+
credentials: mergeCredentials(existing.config.credentials, config.credentials),
|
|
3177
|
+
};
|
|
3164
3178
|
return {
|
|
3165
3179
|
...existing,
|
|
3166
|
-
config:
|
|
3180
|
+
config: mergedConfig,
|
|
3167
3181
|
};
|
|
3168
3182
|
}
|
|
3169
3183
|
return {
|
|
@@ -3199,6 +3213,8 @@ export class AccountRotator {
|
|
|
3199
3213
|
},
|
|
3200
3214
|
};
|
|
3201
3215
|
});
|
|
3216
|
+
this.config = { ...normalized, accounts: mergedAccounts.map((account) => account.config) };
|
|
3217
|
+
this.accounts = mergedAccounts;
|
|
3202
3218
|
await saveAccountsConfig(this.config);
|
|
3203
3219
|
await this.saveState();
|
|
3204
3220
|
this.refreshHealthScores();
|
|
@@ -3260,6 +3276,7 @@ export class AccountRotator {
|
|
|
3260
3276
|
existing.config = {
|
|
3261
3277
|
...existing.config,
|
|
3262
3278
|
...accountConfig,
|
|
3279
|
+
credentials: mergeCredentials(existing.config.credentials, accountConfig.credentials),
|
|
3263
3280
|
tier: accountConfig.tier || existing.config.tier || "unknown",
|
|
3264
3281
|
};
|
|
3265
3282
|
existing.disabled = false;
|
|
@@ -118,8 +118,11 @@ export class PostgresSettingsRepository implements ISettingsRepository {
|
|
|
118
118
|
this.cache.set(row.key, row.value);
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
-
// Migrate from disk for any keys not already in DB
|
|
121
|
+
// Migrate non-account settings from disk for any keys not already in DB.
|
|
122
|
+
// accounts.json is deliberately excluded: when PostgreSQL is configured,
|
|
123
|
+
// it must be the sole source of account credentials.
|
|
122
124
|
for (const [key, spec] of Object.entries(DISK_FILES)) {
|
|
125
|
+
if (key === "accounts_json") continue;
|
|
123
126
|
if (this.cache.has(key)) continue;
|
|
124
127
|
try {
|
|
125
128
|
const path = join(getConfigDir(), spec.filename);
|
|
@@ -166,21 +169,21 @@ export class PostgresSettingsRepository implements ISettingsRepository {
|
|
|
166
169
|
async set(key: string, value: string): Promise<void> {
|
|
167
170
|
this.cache.set(key, value);
|
|
168
171
|
if (this.pool) {
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
.
|
|
172
|
+
try {
|
|
173
|
+
// Account changes must be durable before the API reports success.
|
|
174
|
+
// A background-only write could be lost when the service restarts.
|
|
175
|
+
await this.pool.query(
|
|
172
176
|
`INSERT INTO rotator_settings (key, value, updated_at)
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
177
|
+
VALUES ($1, $2, CURRENT_TIMESTAMP)
|
|
178
|
+
ON CONFLICT (key) DO UPDATE
|
|
179
|
+
SET value = EXCLUDED.value, updated_at = CURRENT_TIMESTAMP`,
|
|
176
180
|
[key, value],
|
|
177
|
-
)
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
});
|
|
181
|
+
);
|
|
182
|
+
} catch (err) {
|
|
183
|
+
console.error(`Failed to save ${key} to database: ${err}`);
|
|
184
|
+
this.enqueueRetry(key, value);
|
|
185
|
+
throw err;
|
|
186
|
+
}
|
|
184
187
|
}
|
|
185
188
|
}
|
|
186
189
|
|
package/src/spend-logger.ts
CHANGED
|
@@ -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 (
|
|
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 (
|
|
148
|
-
|
|
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
|
-
`
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
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
|
|
212
|
-
|
|
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
|
}
|
package/src/virtual-keys.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
188
|
+
setCachedKey(tokenHash, { key: null, fetchedAt: now });
|
|
165
189
|
return null;
|
|
166
190
|
}
|
|
167
191
|
|
|
168
192
|
const key = mapRowToVirtualKey(res.rows[0]);
|
|
169
|
-
|
|
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
|
-
|
|
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);
|
|
@@ -371,6 +371,11 @@ const MODEL_PRICING = {
|
|
|
371
371
|
"hy3-free": { inputPer1M: 0.25, outputPer1M: 1.00 },
|
|
372
372
|
"ling-3.0-tiny-free": { inputPer1M: 0.05, outputPer1M: 0.20 },
|
|
373
373
|
"laguna-s-2.1-free": { inputPer1M: 0.20, outputPer1M: 0.80 },
|
|
374
|
+
|
|
375
|
+
// OpenAI Codex models — mirrors MODEL_PRICING in src/types.ts
|
|
376
|
+
"gpt-5.6-sol": { inputPer1M: 5.00, outputPer1M: 30.00 },
|
|
377
|
+
"gpt-5.6-terra": { inputPer1M: 2.00, outputPer1M: 12.00 },
|
|
378
|
+
"gpt-5.6-luna": { inputPer1M: 0.20, outputPer1M: 1.20 },
|
|
374
379
|
};
|
|
375
380
|
|
|
376
381
|
function getModelPricing(model) {
|