tuxevil-rotator 3.7.0 → 3.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [3.7.1] - 2026-09-12
6
+
7
+ ### Added
8
+
9
+ - **OpenCode Zen free-model catalog update**: Added `big-pickle` to the OpenCode Zen catalog and removed the retired `deepseek-v4-flash-free` and `hy3-free` entries.
10
+
11
+ ### Fixed
12
+
13
+ - **Muse Spark routing**: `muse-spark-1.3-contributor-free` is now forwarded through the OpenCode Zen Responses endpoint while Chat, Responses, and Anthropic compatibility surfaces are all preserved.
14
+ - **Tier-first routing under concurrency**: Concurrent least-loaded account selection now respects tier priority, and persisted lower-tier assignments are re-evaluated while idle.
15
+ - **Ollama monthly quota parsing**: The Ollama monthly quota pool is correctly parsed when the provider reports monthly-style usage.
16
+ - **Provider quota labels**: Simplified and aligned provider-level quota display labels for Ollama, Codex, and OpenCode Zen.
17
+ - **Codex kickstart lifecycle**: Unstarted Codex quota timers are now kicked off on startup; stale kickstart responses are drained to avoid blocking subsequent requests.
18
+ - **Ollama pricing and forecast label**: Corrected the Ollama pricing entry and aligned the forecast label shown in the dashboard.
19
+
5
20
  ## [3.7.0] - 2026-09-07
6
21
 
7
22
  ### Added
package/README.md CHANGED
@@ -53,6 +53,9 @@ Originally built as a multi-account rotator for Google Antigravity. It now gener
53
53
 
54
54
  ## Current Model Update
55
55
 
56
+ - **OpenCode Zen catalog sync**: Added `big-pickle` and removed the retired `deepseek-v4-flash-free` and `hy3-free` entries; `muse-spark-1.3-contributor-free` is now routed through the Responses endpoint with full Chat, Responses, and Anthropic surface compatibility. ([v3.7.1](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.7.1))
57
+ - **Tier-first routing under concurrency**: Concurrent least-loaded account selection now enforces tier priority, and persisted lower-tier assignments are re-evaluated while idle. ([v3.7.1](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.7.1))
58
+ - **Codex kickstart lifecycle**: Unstarted Codex quota timers are kicked off on startup and stale kickstart responses are drained to avoid blocking subsequent requests. ([v3.7.1](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.7.1))
56
59
  - **Gemini 3.8 Flash Support**: Native Antigravity model IDs `gemini-3.8-flash-high`, `gemini-3.8-flash-medium`, and `gemini-3.8-flash-low`, with 1M-token context, 65,536-token output, pricing, quota routing, dashboard visualization, and telemetry support. Gemini 3.5 Flash has been removed from the user-facing catalog to match Antigravity 2.11. ([PR #28](https://github.com/tuxevil/tuxevil-rotator/pull/28) by [@CyR1en](https://github.com/CyR1en))
57
60
  - **Dynamic Antigravity Discovery**: Successful quota polls reconcile live model IDs and metadata per full account identity. Newly advertised models appear in `/v1/models` and route only to accounts that advertised them; removed models disappear without falling back to the generic Gemini pool. Legacy `gemini-3.5-*` IDs stay hidden, and configured `modelSpecs` substring overrides retain precedence. ([PR #29](https://github.com/tuxevil/tuxevil-rotator/pull/29) by [@javargasm](https://github.com/javargasm))
58
61
  - **Dynamic Catalog Hardening**: Quota snapshots reject malformed data while preserving the last known-good state, stale account responses are ignored, and dynamic model ownership and quota-safety state survive restarts without routing a model through an account that did not advertise it. ([PR #30](https://github.com/tuxevil/tuxevil-rotator/pull/30) by [@javargasm](https://github.com/javargasm))
@@ -65,7 +68,7 @@ Originally built as a multi-account rotator for Google Antigravity. It now gener
65
68
  ## v3.2 Highlights
66
69
 
67
70
  - **Gemini 3.7 Flash Support**: Full support for Google's Gemini 3.7 Flash models (`gemini-3.7-flash`, `gemini-3.7-flash-tiered`, `gemini-3.7-flash-high`, `gemini-3.7-flash-medium`, `gemini-3.7-flash-low`) with reasoning effort / thinking level translation, pricing, dashboard visualization, and telemetry.
68
- - **OpenCode Zen Provider**: Added `opencode-zen` provider support (`deepseek-v4-flash-free`, `nemotron-3.5-lightning-free`, `nemotron-3-ultra-free`, `mimo-v2.5-free`, `hy3-free`) with static API key validation, onboarding UI tabs in `/login` and `/login-cli`, real-time quota tracking, and market-based cost savings estimates.
71
+ - **OpenCode Zen Provider**: Added `opencode-zen` provider support (`big-pickle`, `mimo-v2.5-free`, `ling-3.0-flash-fin-free`, `nemotron-3-ultra-free`, `nemotron-3.5-lightning-free`, `muse-spark-1.3-contributor-free`) with static API key validation, onboarding UI tabs in `/login` and `/login-cli`, real-time quota tracking, and cost tracking.
69
72
  - **Streaming Tool Call Reliability**: Stateful preservation of tool call names and IDs across fragmented SSE chunks in multi-turn tool calling sessions.
70
73
  - **Standardized Rate-Limit Retries**: Error responses for 429 now provide `retryAfterMs` and `retry_after_seconds` headers and payload data for fine-grained cooldown handling.
71
74
  - **Provider Precedence Order**: Standardized provider order across quota pools, credentials, and UI displays (`google-antigravity` -> `ollama` -> `opencode-zen` -> `openai-codex`).
@@ -141,7 +144,7 @@ Existing `enc:v1` records remain decryptable during migration; newly written rec
141
144
  - **Multi-account load balancing** — Distributes traffic across a pool of accounts with per-model independent routing
142
145
  - **One-command account setup** — `tuxevil-rotator login` auto-discovers (or provisions) the Cloud Code companion project for brand-new Google accounts; `login --provider ollama` adds an Ollama Cloud API key to an existing email or creates a new one
143
146
  - **Smart rotation & health scoring** — Six routing policies (`timer-first`, `tier-first`, `quota-first`, `hybrid`, `sequential-quota`, `sticky-quota`) with composite health scores per account
144
- - **Real-time quota monitoring** — Polls each provider's quota API on its own cadence; Antigravity quota pools are consolidated by family (`claude`, `gemini`) and Ollama reports session/weekly usage
147
+ - **Real-time quota monitoring** — Polls each provider's quota API on its own cadence; Antigravity quota pools are consolidated by family (`claude`, `gemini`) and Ollama reports monthly usage
145
148
  - **Infringement & abuse detection** — Flags accounts on enforcement signals and triggers protective pause to preserve the rest of the pool
146
149
  - **Virtual Keys & access control** — Issue scoped `rk-...` keys for teams, agents, or CI pipelines with per-key model restrictions
147
150
  - **Spend logging & audit inspector** — Full request/response audit trail with 6-decimal USD cost estimates for both Antigravity and Ollama traffic (requires PostgreSQL)
@@ -264,7 +267,7 @@ After starting the proxy, open `http://localhost:51200/dashboard`.
264
267
 
265
268
  The dashboard shows:
266
269
  - **Routing state** — real-time status, uptime, requests, protective pause timers
267
- - **Account cards** — quota bars (Antigravity family buckets `claude` / `gemini`; Ollama session/weekly usage), per-model timers, health scores, flagged alerts
270
+ - **Account cards** — quota bars (Antigravity family buckets `claude` / `gemini`; Ollama monthly usage), per-model timers, health scores, flagged alerts
268
271
  - **Token usage & savings** — interactive chart with time ranges and CSV/JSON export (real USD for both providers)
269
272
  - **Latency (p50/p95)** — per-model TTFB and total duration
270
273
  - **Activity heatmap** — 60-day GitHub-style request intensity grid
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tuxevil-rotator",
3
- "version": "3.7.0",
3
+ "version": "3.7.1",
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/compat.ts CHANGED
@@ -73,7 +73,11 @@ import {
73
73
  anthropicToOllamaBody,
74
74
  parseOllamaNdjson,
75
75
  } from "./providers/ollama/translators.js";
76
- import { OPENCODE_ZEN_CATALOG, isOpenCodeZenModel } from "./providers/opencode-zen/catalog.js";
76
+ import {
77
+ OPENCODE_ZEN_CATALOG,
78
+ isOpenCodeZenModel,
79
+ isOpenCodeZenResponsesModel,
80
+ } from "./providers/opencode-zen/catalog.js";
77
81
  import { OPENCODE_ZEN_PROVIDER_ID } from "./providers/opencode-zen/index.js";
78
82
  import type {
79
83
  ChatMessage,
@@ -1260,7 +1264,7 @@ async function streamResponsesSse(
1260
1264
  context?: RotationAttemptContext,
1261
1265
  rotator?: AccountRotator,
1262
1266
  compressionStats?: CompressionStats | null,
1263
- upstream: "google" | "ollama" = "google",
1267
+ upstream: "google" | "ollama" | "opencode-zen" = "google",
1264
1268
  ): Promise<CompatCompletion> {
1265
1269
  const nodeStream = Readable.fromWeb(
1266
1270
  body as import("node:stream/web").ReadableStream,
@@ -1281,6 +1285,7 @@ async function streamResponsesSse(
1281
1285
  let reasoningDone = false;
1282
1286
  let reqClosed = false;
1283
1287
  let streamError: string | undefined;
1288
+ let upstreamFinishReason: string | undefined;
1284
1289
  const closeUpstreamForClient = (): void => {
1285
1290
  reqClosed = true;
1286
1291
  if (!nodeStream.destroyed) nodeStream.destroy();
@@ -1339,6 +1344,200 @@ async function streamResponsesSse(
1339
1344
  ),
1340
1345
  });
1341
1346
 
1347
+ interface OpenCodeStreamingToolState {
1348
+ id: string;
1349
+ name: string;
1350
+ arguments: string;
1351
+ itemId: string;
1352
+ outputIndex: number;
1353
+ }
1354
+ const openCodeStreamingTools = new Map<number, OpenCodeStreamingToolState>();
1355
+ const closeReasoning = (): void => {
1356
+ if (reasoningOutputIndex === -1 || reasoningDone) return;
1357
+ reasoningDone = true;
1358
+ writeResponsesEvent(res, {
1359
+ type: "response.reasoning_summary_text.done",
1360
+ item_id: reasoningItemId,
1361
+ output_index: reasoningOutputIndex,
1362
+ summary_index: 0,
1363
+ text: thinkingText,
1364
+ });
1365
+ writeResponsesEvent(res, {
1366
+ type: "response.output_item.done",
1367
+ output_index: reasoningOutputIndex,
1368
+ item: {
1369
+ id: reasoningItemId,
1370
+ type: "reasoning",
1371
+ status: "completed",
1372
+ summary: [{ type: "summary_text", text: thinkingText }],
1373
+ },
1374
+ });
1375
+ };
1376
+ const ensureMessage = (): void => {
1377
+ if (messageOutputIndex !== -1) return;
1378
+ messageOutputIndex = nextOutputIndex++;
1379
+ messageItemId = makeCompatId("msg");
1380
+ writeResponsesEvent(res, {
1381
+ type: "response.output_item.added",
1382
+ output_index: messageOutputIndex,
1383
+ item: {
1384
+ id: messageItemId,
1385
+ type: "message",
1386
+ status: "in_progress",
1387
+ role: "assistant",
1388
+ content: [{ type: "output_text", text: "", annotations: [] }],
1389
+ },
1390
+ });
1391
+ };
1392
+ const emitOpenCodeZenLine = (line: string): void => {
1393
+ if (!line.startsWith("data:")) return;
1394
+ const payload = line.slice(5).trim();
1395
+ if (!payload || payload === "[DONE]") return;
1396
+ try {
1397
+ const parsed = JSON.parse(payload) as Record<string, unknown>;
1398
+ if (!isRecord(parsed)) return;
1399
+ const usage = isRecord(parsed.usage) ? parsed.usage : null;
1400
+ if (usage) {
1401
+ if (typeof usage.prompt_tokens === "number") inputTokens = usage.prompt_tokens;
1402
+ if (typeof usage.completion_tokens === "number") outputTokens = usage.completion_tokens;
1403
+ if (typeof usage.input_tokens === "number") inputTokens = usage.input_tokens;
1404
+ if (typeof usage.output_tokens === "number") outputTokens = usage.output_tokens;
1405
+ }
1406
+ if (!Array.isArray(parsed.choices) || parsed.choices.length === 0) return;
1407
+ const choice = parsed.choices[0];
1408
+ if (!isRecord(choice)) return;
1409
+ if (typeof choice.finish_reason === "string" && choice.finish_reason) {
1410
+ upstreamFinishReason = choice.finish_reason;
1411
+ }
1412
+ const delta = isRecord(choice.delta) ? choice.delta : {};
1413
+ const reasoningDelta = typeof delta.reasoning_content === "string"
1414
+ ? delta.reasoning_content
1415
+ : "";
1416
+ if (reasoningDelta) {
1417
+ if (reasoningOutputIndex === -1) {
1418
+ reasoningOutputIndex = nextOutputIndex++;
1419
+ reasoningItemId = makeCompatId("rs");
1420
+ writeResponsesEvent(res, {
1421
+ type: "response.output_item.added",
1422
+ output_index: reasoningOutputIndex,
1423
+ item: {
1424
+ id: reasoningItemId,
1425
+ type: "reasoning",
1426
+ status: "in_progress",
1427
+ summary: [],
1428
+ },
1429
+ });
1430
+ }
1431
+ thinkingText += reasoningDelta;
1432
+ writeResponsesEvent(res, {
1433
+ type: "response.reasoning_summary_text.delta",
1434
+ item_id: reasoningItemId,
1435
+ output_index: reasoningOutputIndex,
1436
+ summary_index: 0,
1437
+ delta: reasoningDelta,
1438
+ });
1439
+ }
1440
+
1441
+ const contentDelta = typeof delta.content === "string" ? delta.content : "";
1442
+ if (contentDelta) {
1443
+ closeReasoning();
1444
+ ensureMessage();
1445
+ text += contentDelta;
1446
+ writeResponsesEvent(res, {
1447
+ type: "response.output_text.delta",
1448
+ item_id: messageItemId,
1449
+ output_index: messageOutputIndex,
1450
+ content_index: 0,
1451
+ delta: contentDelta,
1452
+ });
1453
+ }
1454
+
1455
+ if (Array.isArray(delta.tool_calls)) {
1456
+ for (const rawToolCall of delta.tool_calls) {
1457
+ if (!isRecord(rawToolCall) || !isRecord(rawToolCall.function)) continue;
1458
+ const index = typeof rawToolCall.index === "number"
1459
+ ? rawToolCall.index
1460
+ : openCodeStreamingTools.size;
1461
+ const fn = rawToolCall.function;
1462
+ const name = typeof fn.name === "string" && fn.name ? fn.name : "unknown";
1463
+ const args = typeof fn.arguments === "string" ? fn.arguments : "";
1464
+ let state = openCodeStreamingTools.get(index);
1465
+ if (!state) {
1466
+ closeReasoning();
1467
+ const id = typeof rawToolCall.id === "string" && rawToolCall.id
1468
+ ? rawToolCall.id
1469
+ : `call_${Date.now().toString(36)}_${toolCallIndex++}`;
1470
+ state = {
1471
+ id,
1472
+ name,
1473
+ arguments: "",
1474
+ itemId: makeCompatId("fc"),
1475
+ outputIndex: nextOutputIndex++,
1476
+ };
1477
+ openCodeStreamingTools.set(index, state);
1478
+ toolCalls.push({
1479
+ id,
1480
+ type: "function",
1481
+ function: { name, arguments: "" },
1482
+ });
1483
+ writeResponsesEvent(res, {
1484
+ type: "response.output_item.added",
1485
+ output_index: state.outputIndex,
1486
+ item: {
1487
+ id: state.itemId,
1488
+ type: "function_call",
1489
+ status: "in_progress",
1490
+ call_id: state.id,
1491
+ name: state.name,
1492
+ arguments: "",
1493
+ },
1494
+ });
1495
+ } else if (name !== "unknown") {
1496
+ state.name = name;
1497
+ const call = toolCalls.find((candidate) => candidate.id === state?.id);
1498
+ if (call) call.function.name = name;
1499
+ }
1500
+ if (args) {
1501
+ state.arguments += args;
1502
+ const call = toolCalls.find((candidate) => candidate.id === state?.id);
1503
+ if (call) call.function.arguments = state.arguments;
1504
+ writeResponsesEvent(res, {
1505
+ type: "response.function_call_arguments.delta",
1506
+ item_id: state.itemId,
1507
+ output_index: state.outputIndex,
1508
+ delta: args,
1509
+ });
1510
+ }
1511
+ }
1512
+ }
1513
+ } catch {
1514
+ // Ignore malformed compatibility chunks; the normal stream finaliser
1515
+ // still returns a valid Responses envelope when possible.
1516
+ }
1517
+ };
1518
+ const closeOpenCodeTools = (): void => {
1519
+ for (const state of openCodeStreamingTools.values()) {
1520
+ writeResponsesEvent(res, {
1521
+ type: "response.function_call_arguments.done",
1522
+ item_id: state.itemId,
1523
+ output_index: state.outputIndex,
1524
+ arguments: state.arguments,
1525
+ });
1526
+ writeResponsesEvent(res, {
1527
+ type: "response.output_item.done",
1528
+ output_index: state.outputIndex,
1529
+ item: {
1530
+ id: state.itemId,
1531
+ type: "function_call",
1532
+ status: "completed",
1533
+ call_id: state.id,
1534
+ name: state.name,
1535
+ arguments: state.arguments,
1536
+ },
1537
+ });
1538
+ }
1539
+ };
1540
+
1342
1541
  let tailBuffer = "";
1343
1542
  const emitOllamaLine = (line: string): void => {
1344
1543
  try {
@@ -1471,6 +1670,10 @@ async function streamResponsesSse(
1471
1670
  if (line) emitOllamaLine(line);
1472
1671
  continue;
1473
1672
  }
1673
+ if (upstream === "opencode-zen") {
1674
+ emitOpenCodeZenLine(line);
1675
+ continue;
1676
+ }
1474
1677
  if (!line.startsWith("data:")) continue;
1475
1678
  const payload = line.slice(5).trim();
1476
1679
  if (!payload || payload === "[DONE]") continue;
@@ -1676,6 +1879,7 @@ async function streamResponsesSse(
1676
1879
  firstByteMs,
1677
1880
  toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
1678
1881
  streamError,
1882
+ finishReason: upstreamFinishReason,
1679
1883
  rawResponse: {
1680
1884
  id: responseId,
1681
1885
  object: "response",
@@ -1715,6 +1919,7 @@ async function streamResponsesSse(
1715
1919
  },
1716
1920
  });
1717
1921
  }
1922
+ if (upstream === "opencode-zen") closeOpenCodeTools();
1718
1923
  if (messageOutputIndex !== -1) {
1719
1924
  writeResponsesEvent(res, {
1720
1925
  type: "response.output_text.done",
@@ -1797,9 +2002,11 @@ async function completeResponsesViaRotator(
1797
2002
  context,
1798
2003
  rotator,
1799
2004
  options?.compressionStats,
1800
- (rotator?.getOllamaModels?.() ?? []).includes(body.model)
1801
- ? "ollama"
1802
- : "google",
2005
+ isOpenCodeZenResponsesModel(body.model)
2006
+ ? "opencode-zen"
2007
+ : (rotator?.getOllamaModels?.() ?? []).includes(body.model)
2008
+ ? "ollama"
2009
+ : "google",
1803
2010
  );
1804
2011
  if (completion.inputTokens > 0 || completion.outputTokens > 0) {
1805
2012
  rotator.recordTokenUsage(
@@ -2584,7 +2791,7 @@ export async function handleOpenAIChatCompletions(
2584
2791
  const started = Date.now();
2585
2792
  const streamMode = validation.value.stream ? "openai" : "none";
2586
2793
  const bodyToForward: RequestBody = isOpenCodeZenModel(chatReq.model)
2587
- ? { project: "", model: chatReq.model, request: chatReq }
2794
+ ? { project: "", model: chatReq.model, request: chatReq, requestType: "openai-chat" }
2588
2795
  : (rotator?.getOllamaModels?.().includes(chatReq.model) ? openAIToOllamaBody(chatReq) : openAIToAntigravityBody(chatReq));
2589
2796
  const result = await completeViaRotator(
2590
2797
  req,
@@ -2749,7 +2956,7 @@ export async function handleOpenAIResponsesCreate(
2749
2956
  : converted.chatRequest;
2750
2957
 
2751
2958
  const requestBody: RequestBody = isOpenCodeZenModel(chatRequest.model)
2752
- ? { project: "", model: chatRequest.model, request: chatRequest }
2959
+ ? { project: "", model: chatRequest.model, request: chatRequest, requestType: "openai-responses" }
2753
2960
  : (rotator?.getOllamaModels?.().includes(chatRequest.model) ? openAIToOllamaBody(chatRequest) : openAIToAntigravityBody(chatRequest));
2754
2961
  requestBody.requestId = responseId;
2755
2962
 
@@ -3003,7 +3210,7 @@ export async function handleAnthropicMessages(
3003
3210
  const started = Date.now();
3004
3211
  const streamMode = validation.value.stream ? "anthropic" : "none";
3005
3212
  const bodyToForward: RequestBody = isOpenCodeZenModel(anthropicReq.model)
3006
- ? { project: "", model: anthropicReq.model, request: anthropicToOpenAIChatRequest(anthropicReq) }
3213
+ ? { project: "", model: anthropicReq.model, request: anthropicToOpenAIChatRequest(anthropicReq), requestType: "anthropic" }
3007
3214
  : (rotator?.getOllamaModels?.().includes(anthropicReq.model) ? anthropicToOllamaBody(anthropicReq) : anthropicToAntigravityBody(anthropicReq));
3008
3215
  const result = await completeViaRotator(
3009
3216
  req,
@@ -130,6 +130,15 @@ export interface ProviderAdapter {
130
130
  /** Accumulator matching this provider's stream format. */
131
131
  createStreamAccumulator(): StreamAccumulator;
132
132
 
133
+ /** Provider-native minimal request used to start an idle quota timer. */
134
+ forwardKickstartRequest?(
135
+ account: AccountRuntime,
136
+ model: string,
137
+ signal?: AbortSignal,
138
+ ): Promise<ForwardedResponse>;
139
+ /** Drop provider-local quota cache after a state-changing kickstart. */
140
+ clearQuotaCache?(account: AccountRuntime): void;
141
+
133
142
  // --- Catalog / helpers ---
134
143
  /** Whether a model belongs to this provider. */
135
144
  ownsModel?(
@@ -104,10 +104,21 @@ export const PROVIDER_ORDER_RANK: Record<string, number> = {
104
104
  "openai-codex": 4,
105
105
  };
106
106
 
107
+ // Ollama Cloud currently exposes one account-wide usage pool. Keep the old
108
+ // names as aliases so persisted state and older API responses remain readable
109
+ // during the transition.
110
+ export const OLLAMA_QUOTA_POOL_KEY = "monthly";
111
+
112
+ export function isOllamaQuotaPoolKey(poolKey: string): boolean {
113
+ return poolKey === OLLAMA_QUOTA_POOL_KEY ||
114
+ poolKey === "session" ||
115
+ poolKey === "weekly";
116
+ }
117
+
107
118
  export function getProviderIdForPoolKey(poolKey: string): string {
108
119
  if (poolKey.startsWith("codex:") || poolKey.startsWith("openai-codex")) return "openai-codex";
109
120
  if (poolKey.startsWith("opencode-zen:") || poolKey === "opencode-zen") return "opencode-zen";
110
- if (poolKey === "session" || poolKey === "weekly") return "ollama";
121
+ if (isOllamaQuotaPoolKey(poolKey)) return "ollama";
111
122
  if (poolKey === "claude" || poolKey === "gemini") return "google-antigravity";
112
123
  if (PROVIDER_ORDER_RANK[poolKey] !== undefined) return poolKey;
113
124
  return DEFAULT_PROVIDER;
@@ -1,7 +1,7 @@
1
1
  // Ollama Cloud provider adapter.
2
2
  //
3
3
  // Implements the ProviderAdapter contract for Ollama Cloud (ollama.com):
4
- // static API keys, NDJSON `/api/chat` forwarding, and session/weekly
4
+ // static API keys, NDJSON `/api/chat` forwarding, and monthly
5
5
  // usage-fraction quota pools with exhaustion prediction.
6
6
  //
7
7
  // Ported from the ollama-rotator project (same author) into the
@@ -18,6 +18,7 @@ import { runLogin } from "./login.js";
18
18
  import { getOllamaApiKey, validateCredentials } from "./credentials.js";
19
19
  import { UsagePredictor, type ExhaustionPrediction } from "./prediction.js";
20
20
  import type { AccountRuntime } from "../../types.js";
21
+ import { OLLAMA_QUOTA_POOL_KEY } from "../credential-helpers.js";
21
22
 
22
23
  const OLLAMA_TIER_RANKING = {
23
24
  max: 0,
@@ -75,7 +76,8 @@ export const ollamaAdapter: ProviderAdapter = {
75
76
  createStreamAccumulator: () => new OllamaNdjsonAccumulator(),
76
77
 
77
78
  getKickstartModelForPool(quotaModelKey: string): string | undefined {
78
- // Only the session pool can be kickstarted for Ollama accounts.
79
+ // The current monthly pool has no idle timer to start. Keep the legacy
80
+ // session path for operators upgrading from the old API shape.
79
81
  return quotaModelKey === "session" ? OLLAMA_KICKSTART_MODEL : undefined;
80
82
  },
81
83
 
@@ -85,7 +87,7 @@ export const ollamaAdapter: ProviderAdapter = {
85
87
  },
86
88
 
87
89
  getPoolKey(): string {
88
- return "session";
90
+ return OLLAMA_QUOTA_POOL_KEY;
89
91
  },
90
92
 
91
93
  getBenchmark() {
@@ -7,18 +7,19 @@
7
7
  // that window. The rotator rounds these to whole percents for routing;
8
8
  // this store keeps the raw values so operators can correlate tokens
9
9
  // (from `rotator_spend_logs`) against usage fractions over time and
10
- // calibrate the real per-model session/weekly budgets without burning
10
+ // calibrate the real per-model monthly budget without burning
11
11
  // quota (see docs/usage-calibration.md).
12
12
  //
13
13
  // Postgres-only, like spend logs: when no database is configured the
14
14
  // store is a silent no-op.
15
15
  //
16
16
  // The table is created lazily on first write. A typical deployment
17
- // produces ~2 rows per account per poll (session + weekly), which at the
17
+ // current API produces ~1 row per account per poll (monthly), which at the
18
18
  // default 5-minute poll interval is ~576 rows/account/day.
19
19
 
20
20
  import { rotatorEnv } from "../../env.js";
21
21
  import type { OllamaUsageResponse } from "./quota.js";
22
+ import { OLLAMA_QUOTA_POOL_KEY } from "../credential-helpers.js";
22
23
 
23
24
  const RETENTION_DEFAULT_DAYS = 14;
24
25
 
@@ -27,7 +28,7 @@ let schemaReady: Promise<void> | null = null;
27
28
  export interface QuotaPollRecord {
28
29
  accountEmail: string;
29
30
  polledAt: string;
30
- pool: "session" | "weekly";
31
+ pool: "monthly" | "session" | "weekly";
31
32
  usageRaw: number;
32
33
  percentRemaining: number;
33
34
  /** Per-model request counts observed inside this pool's window. */
@@ -93,8 +94,9 @@ export async function recordQuotaPoll(record: QuotaPollRecord): Promise<void> {
93
94
  }
94
95
 
95
96
  /**
96
- * Persist both pools from a parsed `GET /api/usage` response. No-op when
97
- * the response lacks the expected shape.
97
+ * Persist the current monthly pool, or both legacy pools when talking to an
98
+ * older `GET /api/usage` response. No-op when the response lacks the expected
99
+ * shape.
98
100
  */
99
101
  export async function recordUsagePoll(
100
102
  accountEmail: string,
@@ -104,7 +106,13 @@ export async function recordUsagePoll(
104
106
  const limits = data?.limits;
105
107
  if (!limits || typeof limits !== "object") return;
106
108
 
107
- for (const pool of ["session", "weekly"] as const) {
109
+ const monthlyLimit = limits[OLLAMA_QUOTA_POOL_KEY];
110
+ const pools: Array<"monthly" | "session" | "weekly"> =
111
+ monthlyLimit && typeof monthlyLimit === "object"
112
+ ? [OLLAMA_QUOTA_POOL_KEY]
113
+ : ["session", "weekly"];
114
+
115
+ for (const pool of pools) {
108
116
  const info = limits[pool] as
109
117
  | { usage?: number | string; models?: unknown[] }
110
118
  | undefined;
@@ -1,4 +1,4 @@
1
- // Ollama Cloud quota polling: `GET /api/usage` → session/weekly pools.
1
+ // Ollama Cloud quota polling: `GET /api/usage` → monthly pool.
2
2
  //
3
3
  // Ported from the ollama-rotator project (same author) into the
4
4
  // tuxevil-rotator provider layer.
@@ -16,6 +16,7 @@ import {
16
16
  } from "./usage-windows.js";
17
17
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
18
18
  import { sortQuotaPools } from "../registry.js";
19
+ import { OLLAMA_QUOTA_POOL_KEY } from "../credential-helpers.js";
19
20
 
20
21
  /**
21
22
  * Poll `GET /api/usage` for one account and store the parsed pool quotas.
@@ -103,10 +104,11 @@ export interface OllamaUsageResponse {
103
104
  }
104
105
 
105
106
  /**
106
- * Parse `GET /api/usage` into the two Ollama quota pools (session + weekly).
107
- * The API reports each pool's usage as a fraction (0..1); reset times are
108
- * computed from the window rules in ./usage-windows.ts, anchored at the
109
- * first observed usage for the session pool.
107
+ * Parse `GET /api/usage` into Ollama quota pools.
108
+ *
109
+ * Current Ollama Cloud responses expose one account-wide `monthly` pool. The
110
+ * legacy session/weekly parser remains as a fallback for older responses so
111
+ * an upgrade does not make an account temporarily unroutable.
110
112
  */
111
113
  export function extractUsagePools(
112
114
  data: OllamaUsageResponse,
@@ -117,6 +119,30 @@ export function extractUsagePools(
117
119
  const limits = data?.limits;
118
120
  if (!limits || typeof limits !== "object") return quotas;
119
121
 
122
+ const monthly = limits[OLLAMA_QUOTA_POOL_KEY];
123
+ if (monthly && typeof monthly === "object") {
124
+ const usageFraction =
125
+ typeof monthly.usage === "number"
126
+ ? monthly.usage
127
+ : typeof monthly.usage === "string"
128
+ ? parseFloat(monthly.usage)
129
+ : NaN;
130
+ if (Number.isFinite(usageFraction)) {
131
+ quotas.push({
132
+ modelKey: OLLAMA_QUOTA_POOL_KEY,
133
+ displayName: "Ollama",
134
+ percentRemaining: Math.max(
135
+ 0,
136
+ Math.min(100, Math.round((1 - usageFraction) * 100)),
137
+ ),
138
+ usageRaw: usageFraction,
139
+ resetTime: null,
140
+ timerType: "monthly",
141
+ });
142
+ return quotas;
143
+ }
144
+ }
145
+
120
146
  for (const pool of ["session", "weekly"] as const) {
121
147
  const info = limits[pool];
122
148
  if (!info || typeof info !== "object") continue;
@@ -158,6 +158,54 @@ export async function forwardCodexRequest(
158
158
  return { response, endpoint: codexResponsesEndpoint() };
159
159
  }
160
160
 
161
+ function codexStreamErrorMessage(value: Record<string, unknown>): string {
162
+ const error = value.error;
163
+ if (typeof error === "string" && error.trim()) return error.trim();
164
+ if (isRecord(error) && typeof error.message === "string" && error.message.trim()) {
165
+ return error.message.trim();
166
+ }
167
+ return "Codex Responses stream failed";
168
+ }
169
+
170
+ /**
171
+ * A kickstart must let Codex finish its Responses stream. Receiving HTTP 200
172
+ * only means that the stream was accepted; cancelling it before a terminal
173
+ * event can prevent the provider from recording quota consumption.
174
+ */
175
+ export async function consumeCodexKickstartResponse(response: Response): Promise<void> {
176
+ if (!response.body) throw new Error("Codex kickstart returned an empty response body");
177
+ const raw = await response.text();
178
+ if (!raw.trim()) throw new Error("Codex kickstart returned an empty stream");
179
+
180
+ let terminal = false;
181
+ for (const line of raw.split(/\r?\n/)) {
182
+ const payload = line.startsWith("data:") ? line.slice(5).trim() : line.trim();
183
+ if (!payload) continue;
184
+ if (payload === "[DONE]") {
185
+ terminal = true;
186
+ continue;
187
+ }
188
+ let parsed: unknown;
189
+ try {
190
+ parsed = JSON.parse(payload);
191
+ } catch {
192
+ continue;
193
+ }
194
+ if (!isRecord(parsed)) continue;
195
+ const type = typeof parsed.type === "string" ? parsed.type : "";
196
+ if (type === "error" || type === "response.error" || type === "response.failed") {
197
+ throw new Error(codexStreamErrorMessage(parsed));
198
+ }
199
+ if (type === "response.completed" || type === "response.incomplete") {
200
+ terminal = true;
201
+ }
202
+ }
203
+
204
+ if (!terminal) {
205
+ throw new Error("Codex kickstart stream ended before a terminal response event");
206
+ }
207
+ }
208
+
161
209
  function usageFromRecord(record: Record<string, unknown>): TokenUsage | null {
162
210
  const usage = isRecord(record.usage)
163
211
  ? record.usage
@@ -15,10 +15,15 @@ import {
15
15
  import { runCodexLogin } from "./login.js";
16
16
  import {
17
17
  CodexSseAccumulator,
18
+ consumeCodexKickstartResponse,
18
19
  extractCodexUsage,
19
20
  forwardCodexRequest,
20
21
  } from "./forward.js";
21
- import { fetchCodexQuota, CODEX_QUOTA_MODEL_KEY } from "./quota.js";
22
+ import {
23
+ clearCodexQuotaCache,
24
+ fetchCodexQuota,
25
+ CODEX_QUOTA_MODEL_KEY,
26
+ } from "./quota.js";
22
27
  import { isCodexRequestModel, isCodexProviderModelId } from "./catalog.js";
23
28
 
24
29
  const providerLog = logger.child("provider/openai-codex");
@@ -122,7 +127,26 @@ export const openaiCodexAdapter: ProviderAdapter = {
122
127
  forwardRequest: forwardCodexRequest,
123
128
  createStreamAccumulator: () => new CodexSseAccumulator(),
124
129
 
125
- getKickstartModelForPool(): string | undefined { return undefined; },
130
+ async forwardKickstartRequest(account, model, signal) {
131
+ const forwarded = await forwardCodexRequest(
132
+ account,
133
+ {
134
+ project: "",
135
+ model,
136
+ request: { input: ".", stream: true, store: false },
137
+ },
138
+ {},
139
+ signal,
140
+ );
141
+ if (forwarded.response.ok) {
142
+ await consumeCodexKickstartResponse(forwarded.response);
143
+ }
144
+ return forwarded;
145
+ },
146
+
147
+ clearQuotaCache: clearCodexQuotaCache,
148
+
149
+ getKickstartModelForPool(): string | undefined { return "gpt-5.6-luna"; },
126
150
 
127
151
  ownsModel(model: string, context?: { codexModels?: Set<string> }): boolean {
128
152
  if (isCodexRequestModel(model)) return true;