tuxevil-rotator 3.6.1 → 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 +25 -0
- package/README.md +12 -5
- package/package.json +1 -1
- package/src/account-identity.ts +2 -3
- package/src/audio-transcription.ts +1538 -0
- package/src/compat.ts +231 -8
- package/src/providers/adapter.ts +9 -0
- package/src/providers/credential-helpers.ts +12 -1
- package/src/providers/ollama/index.ts +5 -3
- package/src/providers/ollama/quota-poll-store.ts +14 -6
- package/src/providers/ollama/quota.ts +31 -5
- package/src/providers/openai-codex/forward.ts +48 -0
- package/src/providers/openai-codex/index.ts +26 -2
- package/src/providers/openai-codex/quota.ts +32 -6
- package/src/providers/opencode-zen/catalog.ts +15 -4
- package/src/providers/opencode-zen/forward.ts +704 -13
- package/src/providers/opencode-zen/quota.ts +1 -1
- package/src/providers/registry.ts +2 -0
- package/src/proxy.ts +59 -4
- package/src/rotator.ts +94 -37
- package/src/static/dashboard.css +1 -0
- package/src/static/dashboard.js +14 -15
- package/src/telemetry.ts +1 -1
- package/src/types.ts +24 -23
- package/tools/telemetry-receiver/receiver.js +12 -11
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 {
|
|
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
|
-
(
|
|
1801
|
-
? "
|
|
1802
|
-
:
|
|
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(
|
|
@@ -2124,6 +2331,22 @@ const MODEL_CATALOG = [
|
|
|
2124
2331
|
multimodal: false,
|
|
2125
2332
|
tools: true,
|
|
2126
2333
|
},
|
|
2334
|
+
{
|
|
2335
|
+
id: "models/proactive-observer-v10",
|
|
2336
|
+
family: "proactive-observer",
|
|
2337
|
+
ctx: 1048576,
|
|
2338
|
+
quotaPool: "gemini",
|
|
2339
|
+
multimodal: true,
|
|
2340
|
+
tools: false,
|
|
2341
|
+
},
|
|
2342
|
+
{
|
|
2343
|
+
id: "whisper-1",
|
|
2344
|
+
family: "proactive-observer",
|
|
2345
|
+
ctx: 1048576,
|
|
2346
|
+
quotaPool: "gemini",
|
|
2347
|
+
multimodal: true,
|
|
2348
|
+
tools: false,
|
|
2349
|
+
},
|
|
2127
2350
|
] as const;
|
|
2128
2351
|
|
|
2129
2352
|
export interface OpenAIModelCatalogEntry {
|
|
@@ -2568,7 +2791,7 @@ export async function handleOpenAIChatCompletions(
|
|
|
2568
2791
|
const started = Date.now();
|
|
2569
2792
|
const streamMode = validation.value.stream ? "openai" : "none";
|
|
2570
2793
|
const bodyToForward: RequestBody = isOpenCodeZenModel(chatReq.model)
|
|
2571
|
-
? { project: "", model: chatReq.model, request: chatReq }
|
|
2794
|
+
? { project: "", model: chatReq.model, request: chatReq, requestType: "openai-chat" }
|
|
2572
2795
|
: (rotator?.getOllamaModels?.().includes(chatReq.model) ? openAIToOllamaBody(chatReq) : openAIToAntigravityBody(chatReq));
|
|
2573
2796
|
const result = await completeViaRotator(
|
|
2574
2797
|
req,
|
|
@@ -2733,7 +2956,7 @@ export async function handleOpenAIResponsesCreate(
|
|
|
2733
2956
|
: converted.chatRequest;
|
|
2734
2957
|
|
|
2735
2958
|
const requestBody: RequestBody = isOpenCodeZenModel(chatRequest.model)
|
|
2736
|
-
? { project: "", model: chatRequest.model, request: chatRequest }
|
|
2959
|
+
? { project: "", model: chatRequest.model, request: chatRequest, requestType: "openai-responses" }
|
|
2737
2960
|
: (rotator?.getOllamaModels?.().includes(chatRequest.model) ? openAIToOllamaBody(chatRequest) : openAIToAntigravityBody(chatRequest));
|
|
2738
2961
|
requestBody.requestId = responseId;
|
|
2739
2962
|
|
|
@@ -2987,7 +3210,7 @@ export async function handleAnthropicMessages(
|
|
|
2987
3210
|
const started = Date.now();
|
|
2988
3211
|
const streamMode = validation.value.stream ? "anthropic" : "none";
|
|
2989
3212
|
const bodyToForward: RequestBody = isOpenCodeZenModel(anthropicReq.model)
|
|
2990
|
-
? { project: "", model: anthropicReq.model, request: anthropicToOpenAIChatRequest(anthropicReq) }
|
|
3213
|
+
? { project: "", model: anthropicReq.model, request: anthropicToOpenAIChatRequest(anthropicReq), requestType: "anthropic" }
|
|
2991
3214
|
: (rotator?.getOllamaModels?.().includes(anthropicReq.model) ? anthropicToOllamaBody(anthropicReq) : anthropicToAntigravityBody(anthropicReq));
|
|
2992
3215
|
const result = await completeViaRotator(
|
|
2993
3216
|
req,
|
package/src/providers/adapter.ts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
-
//
|
|
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
|
|
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
|
|
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 ~
|
|
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
|
|
97
|
-
* the response lacks the expected
|
|
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
|
-
|
|
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` →
|
|
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
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
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 {
|
|
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
|
-
|
|
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;
|