tuxevil-rotator 4.0.0 → 4.2.0
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 +62 -0
- package/README.md +8 -1
- package/package.json +1 -1
- package/src/audio-transcription.ts +44 -4
- package/src/compat.ts +196 -222
- package/src/config-defaults.ts +5 -0
- package/src/config-overrides.ts +16 -0
- package/src/dashboard-live.ts +10 -8
- package/src/dashboard-types.ts +94 -1
- package/src/dashboard.ts +194 -1
- package/src/effort-levels.ts +43 -0
- package/src/effort-routing.ts +304 -0
- package/src/index.ts +2 -5
- package/src/model-catalog-revision.ts +20 -0
- package/src/model-catalog.ts +304 -0
- package/src/providers/adapter.ts +18 -0
- package/src/providers/google-antigravity/catalog.ts +190 -1
- package/src/providers/google-antigravity/forward.ts +2 -0
- package/src/providers/google-antigravity/index.ts +11 -0
- package/src/providers/google-antigravity/translators.ts +67 -14
- package/src/providers/ollama/index.ts +11 -1
- package/src/providers/ollama/quota-poll-store.ts +22 -1
- package/src/providers/ollama/quota.ts +95 -23
- package/src/providers/openai-codex/catalog.ts +9 -4
- package/src/providers/openai-codex/index.ts +18 -2
- package/src/providers/opencode-zen/index.ts +11 -2
- package/src/proxy.ts +143 -28
- package/src/rotator.ts +296 -21
- package/src/settings-repository.ts +36 -5
- package/src/types.ts +72 -26
- package/src/validators.ts +37 -1
- package/src/web/app.tsx +6 -1
- package/src/web/components/icons.tsx +29 -0
- package/src/web/components/overlays.tsx +13 -1
- package/src/web/components/ui.tsx +6 -1
- package/src/web/lib/accounts.ts +1 -0
- package/src/web/lib/attention.ts +12 -0
- package/src/web/lib/effort.ts +407 -0
- package/src/web/lib/models.ts +284 -0
- package/src/web/lib/pools.ts +53 -9
- package/src/web/lib/status.ts +13 -3
- package/src/web/nav.ts +1 -0
- package/src/web/pages/AccountDetail.tsx +16 -2
- package/src/web/pages/EffortRouting.tsx +1130 -0
- package/src/web/pages/Models.tsx +888 -0
- package/src/web/pages/Overview.tsx +31 -15
- package/src/web/pages/Usage.tsx +3 -3
- package/src/web/state/api.ts +31 -0
- package/src/web/state/model-catalog.ts +103 -0
- package/src/web/state/router.ts +150 -19
- package/src/web/state/store.ts +6 -6
- package/src/web/styles/app.css +854 -0
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { logger, redactSensitive } from "../../logger.js";
|
|
2
2
|
import { applyModelAlias, getEffortRoutingRule } from "../../types.js";
|
|
3
|
+
import {
|
|
4
|
+
CLAUDE_THINKING_BUDGET_EFFORTS,
|
|
5
|
+
CLAUDE_THINKING_DISABLED_EFFORT,
|
|
6
|
+
} from "../../effort-levels.js";
|
|
3
7
|
import type { RequestBody } from "../../proxy.js";
|
|
4
8
|
import {
|
|
5
9
|
isRecord,
|
|
@@ -945,13 +949,55 @@ export function resolveEffortAliasModel(
|
|
|
945
949
|
: null;
|
|
946
950
|
}
|
|
947
951
|
|
|
952
|
+
function outputConfigEffort(value: unknown): string | undefined {
|
|
953
|
+
if (!isRecord(value)) return undefined;
|
|
954
|
+
const effort = value.effort;
|
|
955
|
+
return typeof effort === "string" && effort.trim() ? effort : undefined;
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
/**
|
|
959
|
+
* Effort level an Anthropic Messages request asks for, used to pick an effort
|
|
960
|
+
* alias's target. The latest per-message `output_config.effort` wins, then the
|
|
961
|
+
* top-level one. Without either, `thinking` decides: a `budget_tokens` maps to
|
|
962
|
+
* a level through CLAUDE_THINKING_BUDGET_EFFORTS, and thinking turned off asks
|
|
963
|
+
* for the lowest level. Adaptive or absent thinking asks for none, so the
|
|
964
|
+
* alias uses its default.
|
|
965
|
+
*/
|
|
966
|
+
export function claudeRoutingEffort(
|
|
967
|
+
input: AnthropicMessagesRequest,
|
|
968
|
+
): string | undefined {
|
|
969
|
+
const messages = Array.isArray(input.messages) ? input.messages : [];
|
|
970
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
971
|
+
const message: unknown = messages[i];
|
|
972
|
+
if (!isRecord(message) || message.role !== "system") continue;
|
|
973
|
+
const effort = outputConfigEffort(message.output_config);
|
|
974
|
+
if (effort) return effort;
|
|
975
|
+
}
|
|
976
|
+
const effort = outputConfigEffort(input.output_config);
|
|
977
|
+
if (effort) return effort;
|
|
978
|
+
const thinking = input.thinking;
|
|
979
|
+
if (!isRecord(thinking)) return undefined;
|
|
980
|
+
if (thinking.type === "disabled") return CLAUDE_THINKING_DISABLED_EFFORT;
|
|
981
|
+
const budget = thinking.budget_tokens;
|
|
982
|
+
if (thinking.type === "enabled" && typeof budget === "number" && Number.isFinite(budget)) {
|
|
983
|
+
return CLAUDE_THINKING_BUDGET_EFFORTS.find((bucket) => budget < bucket.below)?.effort;
|
|
984
|
+
}
|
|
985
|
+
return undefined;
|
|
986
|
+
}
|
|
987
|
+
|
|
948
988
|
export function openAIToAntigravityBody(
|
|
949
989
|
input: OpenAIChatCompletionRequest,
|
|
990
|
+
options: {
|
|
991
|
+
/** Picks an effort alias's target when the request has no reasoning_effort. */
|
|
992
|
+
routingEffort?: string;
|
|
993
|
+
} = {},
|
|
950
994
|
): RequestBody {
|
|
951
995
|
const requestedModel = input.model;
|
|
952
996
|
const effortTarget =
|
|
953
|
-
resolveEffortAliasModel(
|
|
954
|
-
|
|
997
|
+
resolveEffortAliasModel(
|
|
998
|
+
requestedModel,
|
|
999
|
+
input.reasoning_effort ?? options.routingEffort,
|
|
1000
|
+
) ?? requestedModel;
|
|
955
1001
|
|
|
956
1002
|
const systemParts: string[] = [];
|
|
957
1003
|
const conversationMessages = input.messages.filter((msg) => {
|
|
@@ -1373,6 +1419,10 @@ export function openAIToAntigravityBody(
|
|
|
1373
1419
|
project: "compat-placeholder",
|
|
1374
1420
|
model: mappedModel,
|
|
1375
1421
|
displayModel: requestedModel,
|
|
1422
|
+
requestedModel,
|
|
1423
|
+
// The catalog id after effort routing, before upstream aliasing, so the
|
|
1424
|
+
// Models page switches can be checked against it.
|
|
1425
|
+
catalogModel: effortTarget,
|
|
1376
1426
|
userAgent: "antigravity",
|
|
1377
1427
|
requestType: "agent",
|
|
1378
1428
|
request,
|
|
@@ -1497,18 +1547,21 @@ export function anthropicToAntigravityBody(
|
|
|
1497
1547
|
const tools = convertAnthropicToolsToOpenAI(input.tools);
|
|
1498
1548
|
const toolChoice = convertAnthropicToolChoice(input.tool_choice);
|
|
1499
1549
|
const convertedMessages = convertAnthropicMessagesToOpenAI(input.messages);
|
|
1500
|
-
return openAIToAntigravityBody(
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1550
|
+
return openAIToAntigravityBody(
|
|
1551
|
+
{
|
|
1552
|
+
model: input.model,
|
|
1553
|
+
stream: input.stream,
|
|
1554
|
+
temperature: input.temperature,
|
|
1555
|
+
max_tokens: input.max_tokens,
|
|
1556
|
+
tools,
|
|
1557
|
+
tool_choice: toolChoice,
|
|
1558
|
+
messages: [
|
|
1559
|
+
...(systemText ? [{ role: "system" as const, content: systemText }] : []),
|
|
1560
|
+
...convertedMessages,
|
|
1561
|
+
],
|
|
1562
|
+
},
|
|
1563
|
+
{ routingEffort: claudeRoutingEffort(input) },
|
|
1564
|
+
);
|
|
1512
1565
|
}
|
|
1513
1566
|
|
|
1514
1567
|
export function mapReasoningEffortToThinkingLevel(
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// Ported from the ollama-rotator project (same author) into the
|
|
8
8
|
// tuxevil-rotator provider layer.
|
|
9
9
|
|
|
10
|
-
import type { ProviderAdapter, ProviderFeatures } from "../adapter.js";
|
|
10
|
+
import type { ModelListContext, ProviderAdapter, ProviderFeatures, ProviderModel } from "../adapter.js";
|
|
11
11
|
import { fetchProviderUsage } from "./quota.js";
|
|
12
12
|
import {
|
|
13
13
|
forwardRequest,
|
|
@@ -81,6 +81,16 @@ export const ollamaAdapter: ProviderAdapter = {
|
|
|
81
81
|
return quotaModelKey === "session" ? OLLAMA_KICKSTART_MODEL : undefined;
|
|
82
82
|
},
|
|
83
83
|
|
|
84
|
+
listModels(context: ModelListContext): ProviderModel[] {
|
|
85
|
+
// The live catalog carries names only; /v1/models has always advertised 128K.
|
|
86
|
+
return context.ollamaModels.map((id) => ({
|
|
87
|
+
id,
|
|
88
|
+
contextWindow: 128_000,
|
|
89
|
+
quotaPool: OLLAMA_QUOTA_POOL_KEY,
|
|
90
|
+
source: "discovered",
|
|
91
|
+
}));
|
|
92
|
+
},
|
|
93
|
+
|
|
84
94
|
ownsModel(model: string, context?: { ollamaModels?: Set<string> }): boolean {
|
|
85
95
|
return model === OLLAMA_KICKSTART_MODEL ||
|
|
86
96
|
(context?.ollamaModels?.has(model) ?? false);
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// tuxevil-rotator provider layer.
|
|
3
3
|
// Persistent store of raw quota-poll observations.
|
|
4
4
|
//
|
|
5
|
-
//
|
|
5
|
+
// `GET /api/balance` supplies remaining credits or window percentages.
|
|
6
|
+
// Legacy `GET /api/usage` responses report each pool's usage as a fraction
|
|
6
7
|
// (0..1) with 3-decimal precision, plus per-model request counts inside
|
|
7
8
|
// that window. The rotator rounds these to whole percents for routing;
|
|
8
9
|
// this store keeps the raw values so operators can correlate tokens
|
|
@@ -19,6 +20,7 @@
|
|
|
19
20
|
|
|
20
21
|
import { rotatorEnv } from "../../env.js";
|
|
21
22
|
import type { OllamaUsageResponse } from "./quota.js";
|
|
23
|
+
import type { ModelQuota } from "../../types.js";
|
|
22
24
|
import { OLLAMA_QUOTA_POOL_KEY } from "../credential-helpers.js";
|
|
23
25
|
|
|
24
26
|
const RETENTION_DEFAULT_DAYS = 14;
|
|
@@ -166,3 +168,22 @@ export async function pruneQuotaPolls(days: number = RETENTION_DEFAULT_DAYS): Pr
|
|
|
166
168
|
return 0;
|
|
167
169
|
}
|
|
168
170
|
}
|
|
171
|
+
|
|
172
|
+
/** Normalize balance observations to the same included-usage calibration series. */
|
|
173
|
+
export async function recordParsedQuotaPolls(
|
|
174
|
+
accountEmail: string,
|
|
175
|
+
polledAt: string,
|
|
176
|
+
quotas: ModelQuota[],
|
|
177
|
+
): Promise<void> {
|
|
178
|
+
for (const quota of quotas) {
|
|
179
|
+
if (quota.modelKey !== "monthly" && quota.modelKey !== "session" && quota.modelKey !== "weekly") continue;
|
|
180
|
+
if (typeof quota.usageRaw !== "number" || !Number.isFinite(quota.usageRaw)) continue;
|
|
181
|
+
await recordQuotaPoll({
|
|
182
|
+
accountEmail,
|
|
183
|
+
polledAt,
|
|
184
|
+
pool: quota.modelKey,
|
|
185
|
+
usageRaw: quota.usageRaw,
|
|
186
|
+
percentRemaining: quota.percentRemaining,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
}
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
// Ollama Cloud quota polling: `GET /api/
|
|
1
|
+
// Ollama Cloud quota polling: `GET /api/balance` → included credits/windows.
|
|
2
2
|
//
|
|
3
3
|
// Ported from the ollama-rotator project (same author) into the
|
|
4
4
|
// tuxevil-rotator provider layer.
|
|
5
5
|
|
|
6
6
|
import { fetchWithRetry } from "../../fetch-with-retry.js";
|
|
7
|
-
import { OLLAMA_USAGE_URL, OLLAMA_USER_AGENT } from "../../types.js";
|
|
7
|
+
import { OLLAMA_BALANCE_URL, OLLAMA_USAGE_URL, OLLAMA_USER_AGENT } from "../../types.js";
|
|
8
8
|
import { getOllamaApiKey } from "./credentials.js";
|
|
9
9
|
import type { AccountRuntime, ModelQuota } from "../../types.js";
|
|
10
10
|
import type { QuotaFetchContext } from "../adapter.js";
|
|
11
|
-
import { recordUsagePoll } from "./quota-poll-store.js";
|
|
11
|
+
import { recordParsedQuotaPolls, recordUsagePoll } from "./quota-poll-store.js";
|
|
12
12
|
import {
|
|
13
13
|
nextWeeklyResetMs,
|
|
14
14
|
sessionWindowEndMs,
|
|
@@ -16,10 +16,11 @@ 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
|
+
import { getQuotaItemProviderId, OLLAMA_QUOTA_POOL_KEY } from "../credential-helpers.js";
|
|
20
20
|
|
|
21
21
|
/**
|
|
22
|
-
* Poll
|
|
22
|
+
* Poll balance for actual remaining quota; the usage endpoint now reports
|
|
23
|
+
* historical consumption, not subscription limits.
|
|
23
24
|
* Non-2xx responses flag the account (401/403) via the context callbacks;
|
|
24
25
|
* network errors are swallowed (quota stays stale, rotation falls back to
|
|
25
26
|
* request-count based rotation).
|
|
@@ -29,7 +30,7 @@ export async function fetchProviderUsage(
|
|
|
29
30
|
ctx: QuotaFetchContext,
|
|
30
31
|
): Promise<void> {
|
|
31
32
|
try {
|
|
32
|
-
const
|
|
33
|
+
const options = {
|
|
33
34
|
method: "GET",
|
|
34
35
|
headers: {
|
|
35
36
|
Authorization: `Bearer ${getOllamaApiKey(account.config) ?? ""}`,
|
|
@@ -37,47 +38,58 @@ export async function fetchProviderUsage(
|
|
|
37
38
|
},
|
|
38
39
|
timeoutMs: 8000,
|
|
39
40
|
dispatcher: getAccountProxyDispatcher(account, "ollama"),
|
|
40
|
-
}
|
|
41
|
+
};
|
|
42
|
+
let response = await fetchWithRetry(OLLAMA_BALANCE_URL, options);
|
|
43
|
+
const legacy = response.status === 404;
|
|
44
|
+
if (legacy) {
|
|
45
|
+
await response.body?.cancel();
|
|
46
|
+
response = await fetchWithRetry(OLLAMA_USAGE_URL, options);
|
|
47
|
+
}
|
|
41
48
|
|
|
42
49
|
if (!response.ok) {
|
|
43
50
|
if (response.status === 401 || response.status === 403) {
|
|
44
51
|
const errorText = await response.text().catch(() => "");
|
|
45
52
|
ctx.log(
|
|
46
|
-
`${account.config.email}:
|
|
53
|
+
`${account.config.email}: Ollama quota API returned ${response.status}, flagging account`,
|
|
47
54
|
);
|
|
48
55
|
ctx.reportQuotaPollFlag(account, response.status, errorText);
|
|
49
56
|
ctx.markFlagged(
|
|
50
57
|
account,
|
|
51
|
-
`
|
|
58
|
+
`Ollama quota API ${response.status}: ${errorText}`,
|
|
52
59
|
{ triggerProtectivePause: false },
|
|
53
60
|
);
|
|
54
61
|
}
|
|
55
62
|
return;
|
|
56
63
|
}
|
|
57
64
|
|
|
58
|
-
const data =
|
|
65
|
+
const data: unknown = await response.json();
|
|
59
66
|
const oldQuota = account.quota || [];
|
|
60
|
-
const fresh =
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
67
|
+
const fresh = legacy
|
|
68
|
+
? extractUsagePools(data as OllamaUsageResponse, oldQuota)
|
|
69
|
+
: extractBalancePools(data);
|
|
70
|
+
if (fresh.length === 0) {
|
|
71
|
+
ctx.log(`${account.config.email}: Ollama quota response has no recognized limits; retaining last known quota`);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
// Replace only this provider's quota after parsing a valid response.
|
|
64
75
|
const otherProviders = (oldQuota || []).filter(
|
|
65
|
-
(q) => (q
|
|
66
|
-
(q as { providerId?: string }).providerId !== "ollama",
|
|
76
|
+
(q) => getQuotaItemProviderId(q) !== "ollama",
|
|
67
77
|
);
|
|
68
78
|
fresh.forEach(
|
|
69
|
-
(q) => (
|
|
79
|
+
(q) => (q.providerId = "ollama"),
|
|
70
80
|
);
|
|
71
81
|
account.quota = sortQuotaPools([...otherProviders, ...fresh]);
|
|
72
82
|
account.lastQuotaPoll = Date.now();
|
|
73
|
-
|
|
83
|
+
const polledAt = new Date(account.lastQuotaPoll).toISOString();
|
|
84
|
+
if (legacy) void recordUsagePoll(account.config.email, polledAt, data as OllamaUsageResponse);
|
|
85
|
+
else void recordParsedQuotaPolls(account.config.email, polledAt, fresh);
|
|
74
86
|
|
|
75
87
|
// Stash the provider-local poll log for the rotator to emit as a
|
|
76
88
|
// single consolidated line per cycle.
|
|
77
89
|
account.lastPollByProvider ??= {};
|
|
78
90
|
account.lastPollByProvider["ollama"] = account.quota
|
|
79
91
|
.filter(
|
|
80
|
-
(q) =>
|
|
92
|
+
(q) => q.providerId === "ollama",
|
|
81
93
|
)
|
|
82
94
|
.map((q) => {
|
|
83
95
|
const remain = q.resetTime
|
|
@@ -91,7 +103,7 @@ export async function fetchProviderUsage(
|
|
|
91
103
|
})
|
|
92
104
|
.join(" | ");
|
|
93
105
|
} catch {
|
|
94
|
-
|
|
106
|
+
ctx.log(`${account.config.email}: Ollama quota poll failed; retaining last known quota`);
|
|
95
107
|
}
|
|
96
108
|
}
|
|
97
109
|
|
|
@@ -106,9 +118,9 @@ export interface OllamaUsageResponse {
|
|
|
106
118
|
/**
|
|
107
119
|
* Parse `GET /api/usage` into Ollama quota pools.
|
|
108
120
|
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
*
|
|
121
|
+
* Older Ollama Cloud usage responses exposed a monthly pool or legacy
|
|
122
|
+
* session/weekly pools. Used only when /api/balance is unavailable; today
|
|
123
|
+
* /api/usage returns consumption totals and must not be treated as quota.
|
|
112
124
|
*/
|
|
113
125
|
export function extractUsagePools(
|
|
114
126
|
data: OllamaUsageResponse,
|
|
@@ -214,3 +226,63 @@ export function extractUsagePools(
|
|
|
214
226
|
|
|
215
227
|
return quotas;
|
|
216
228
|
}
|
|
229
|
+
|
|
230
|
+
/** Read the current balance endpoint without guessing budgets from historic spend. */
|
|
231
|
+
export function extractBalancePools(data: unknown): ModelQuota[] {
|
|
232
|
+
if (!isObject(data) || !isObject(data.included)) return [];
|
|
233
|
+
const included = data.included;
|
|
234
|
+
const balance = included.balance_usd;
|
|
235
|
+
const allowance = included.allowance_usd;
|
|
236
|
+
const purchased = isObject(data.purchased) ? data.purchased.balance_usd : undefined;
|
|
237
|
+
if (isFiniteNumber(balance) && isFiniteNumber(allowance) && allowance > 0) {
|
|
238
|
+
const remaining = Math.max(0, Math.min(1, balance / allowance));
|
|
239
|
+
return [{
|
|
240
|
+
modelKey: OLLAMA_QUOTA_POOL_KEY,
|
|
241
|
+
displayName: "Ollama",
|
|
242
|
+
percentRemaining: remainingPercent(remaining * 100),
|
|
243
|
+
usageRaw: 1 - remaining,
|
|
244
|
+
credits: {
|
|
245
|
+
balanceUsd: Math.max(0, balance),
|
|
246
|
+
allowanceUsd: allowance,
|
|
247
|
+
purchasedUsd: isFiniteNumber(purchased) ? Math.max(0, purchased) : 0,
|
|
248
|
+
},
|
|
249
|
+
resetTime: isObject(included.period) ? validResetTime(included.period.until) : null,
|
|
250
|
+
timerType: "monthly",
|
|
251
|
+
}];
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const quotas: ModelQuota[] = [];
|
|
255
|
+
for (const pool of ["monthly", "session", "weekly"] as const) {
|
|
256
|
+
const window = included[pool];
|
|
257
|
+
if (!isObject(window) || !isFiniteNumber(window.remaining_percent)) continue;
|
|
258
|
+
const percentRemaining = remainingPercent(window.remaining_percent);
|
|
259
|
+
const resetTime = validResetTime(window.resets_at);
|
|
260
|
+
quotas.push({
|
|
261
|
+
modelKey: pool,
|
|
262
|
+
displayName: pool === "monthly" ? "Ollama" : pool === "session" ? "Session" : "Weekly",
|
|
263
|
+
percentRemaining,
|
|
264
|
+
usageRaw: 1 - Math.max(0, Math.min(100, window.remaining_percent)) / 100,
|
|
265
|
+
resetTime,
|
|
266
|
+
timerType: pool === "monthly" ? "monthly" : pool === "weekly" ? "7d"
|
|
267
|
+
: !resetTime && percentRemaining === 100 ? "fresh" : "5h",
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
return quotas;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
274
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function isFiniteNumber(value: unknown): value is number {
|
|
278
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function remainingPercent(percent: number): number {
|
|
282
|
+
// A rounding artifact must not make a still-usable credit balance unroutable.
|
|
283
|
+
return percent > 0 ? Math.max(1, Math.min(100, Math.round(percent))) : 0;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function validResetTime(value: unknown): string | null {
|
|
287
|
+
return typeof value === "string" && Number.isFinite(Date.parse(value)) ? value : null;
|
|
288
|
+
}
|
|
@@ -14,7 +14,7 @@ export interface CodexModel {
|
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
// The base list contains OpenAI models published in the Codex model catalog.
|
|
17
|
-
// Authenticated discovery can add
|
|
17
|
+
// Authenticated discovery can add versioned GPT IDs without a release allowlist.
|
|
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.
|
|
@@ -24,7 +24,10 @@ const CODEX_CONTEXT_WINDOW = 1_050_000;
|
|
|
24
24
|
// Hard cap to defend against `/models` upstream reporting absurd values for
|
|
25
25
|
// discovered ids. 2M is comfortably above the published 1.05M baseline.
|
|
26
26
|
const CODEX_DISCOVERED_MAX_CONTEXT_WINDOW = 2_000_000;
|
|
27
|
-
|
|
27
|
+
// The upstream catalog requires a Codex protocol version, independent of our
|
|
28
|
+
// package version. Keep it configurable for deployments using a newer client.
|
|
29
|
+
const DEFAULT_CODEX_CLIENT_VERSION = "0.162.1";
|
|
30
|
+
const CODEX_DISCOVERED_ID_PATTERN = /^gpt-\d+(?:\.\d+)*(?:-[a-z0-9]+)+$/i;
|
|
28
31
|
export const CODEX_BASE_MODELS: readonly CodexModel[] = [
|
|
29
32
|
{ id: "gpt-6-astra", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
|
|
30
33
|
{ id: "gpt-6-sol", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
|
|
@@ -79,7 +82,7 @@ function parseModel(value: unknown): CodexModel | null {
|
|
|
79
82
|
}
|
|
80
83
|
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
81
84
|
const record = value as Record<string, unknown>;
|
|
82
|
-
const id = record.id ?? record.model ?? record.name;
|
|
85
|
+
const id = record.id ?? record.slug ?? record.model ?? record.name;
|
|
83
86
|
if (!isCodexProviderModelId(id)) return null;
|
|
84
87
|
const contextWindow = [record.context_window, record.contextWindow, record.context_length]
|
|
85
88
|
.find((candidate) => typeof candidate === "number" && Number.isFinite(candidate) && candidate > 0);
|
|
@@ -102,13 +105,15 @@ export async function fetchCodexCatalog(
|
|
|
102
105
|
const base = codexBaseUrl();
|
|
103
106
|
const endpoint = base.endsWith("/models") ? base : `${base}/models`;
|
|
104
107
|
try {
|
|
108
|
+
const url = new URL(endpoint);
|
|
109
|
+
url.searchParams.set("client_version", process.env.CODEX_CLIENT_VERSION?.trim() || DEFAULT_CODEX_CLIENT_VERSION);
|
|
105
110
|
const headers: Record<string, string> = {
|
|
106
111
|
Authorization: `Bearer ${token}`,
|
|
107
112
|
Accept: "application/json",
|
|
108
113
|
};
|
|
109
114
|
const accountId = getCodexAccountId(account.config);
|
|
110
115
|
if (accountId) headers["chatgpt-account-id"] = accountId;
|
|
111
|
-
const response = await fetch(
|
|
116
|
+
const response = await fetch(url.toString(), {
|
|
112
117
|
headers,
|
|
113
118
|
signal: signal ?? AbortSignal.timeout(8_000),
|
|
114
119
|
dispatcher: getAccountProxyDispatcher(account, CODEX_PROVIDER_ID),
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AccountRuntime, AccountConfig } from "../../types.js";
|
|
2
|
-
import type { ProviderAdapter, QuotaFetchContext, CredentialValidationResult } from "../adapter.js";
|
|
2
|
+
import type { ModelListContext, ProviderAdapter, ProviderModel, QuotaFetchContext, CredentialValidationResult } from "../adapter.js";
|
|
3
3
|
import { logger } from "../../logger.js";
|
|
4
4
|
import {
|
|
5
5
|
getCodexAccountId,
|
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
fetchCodexQuota,
|
|
25
25
|
CODEX_QUOTA_MODEL_KEY,
|
|
26
26
|
} from "./quota.js";
|
|
27
|
-
import { isCodexRequestModel, isCodexProviderModelId } from "./catalog.js";
|
|
27
|
+
import { getCodexModel, getCodexModels, isCodexRequestModel, isCodexProviderModelId } from "./catalog.js";
|
|
28
28
|
|
|
29
29
|
const providerLog = logger.child("provider/openai-codex");
|
|
30
30
|
const refreshFlights = new Map<string, Promise<void>>();
|
|
@@ -148,6 +148,22 @@ export const openaiCodexAdapter: ProviderAdapter = {
|
|
|
148
148
|
|
|
149
149
|
getKickstartModelForPool(): string | undefined { return "gpt-5.6-luna"; },
|
|
150
150
|
|
|
151
|
+
listModels(context: ModelListContext): ProviderModel[] {
|
|
152
|
+
// Discovery can surface other vendors' models; only GPT ids belong to Codex.
|
|
153
|
+
const ids = context.codexModels.length > 0
|
|
154
|
+
? context.codexModels.filter((id) => isCodexRequestModel(id) || isCodexProviderModelId(id))
|
|
155
|
+
: getCodexModels().map((model) => model.id);
|
|
156
|
+
return ids.map((id) => {
|
|
157
|
+
const model = getCodexModel(id);
|
|
158
|
+
return {
|
|
159
|
+
id,
|
|
160
|
+
contextWindow: model?.contextWindow ?? null,
|
|
161
|
+
quotaPool: CODEX_QUOTA_MODEL_KEY,
|
|
162
|
+
source: model?.source === "allowlist" ? "catalog" : "discovered",
|
|
163
|
+
};
|
|
164
|
+
});
|
|
165
|
+
},
|
|
166
|
+
|
|
151
167
|
ownsModel(model: string, context?: { codexModels?: Set<string> }): boolean {
|
|
152
168
|
if (isCodexRequestModel(model)) return true;
|
|
153
169
|
if (isCodexProviderModelId(model) && (context?.codexModels?.has(model) ?? false)) return true;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// OpenCode Zen provider adapter.
|
|
2
2
|
|
|
3
|
-
import type { ProviderAdapter, ProviderFeatures } from "../adapter.js";
|
|
3
|
+
import type { ProviderAdapter, ProviderFeatures, ProviderModel } from "../adapter.js";
|
|
4
4
|
import { runLogin } from "./login.js";
|
|
5
5
|
import { getOpenCodeZenApiKey, validateCredentials, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
|
|
6
6
|
import { forwardRequest, OpenCodeZenSseAccumulator, getBenchmarkSpec } from "./forward.js";
|
|
7
7
|
import { fetchOpenCodeZenQuota } from "./quota.js";
|
|
8
|
-
import { isOpenCodeZenModel } from "./catalog.js";
|
|
8
|
+
import { isOpenCodeZenModel, OPENCODE_ZEN_CATALOG } from "./catalog.js";
|
|
9
9
|
import type { AccountRuntime } from "../../types.js";
|
|
10
10
|
|
|
11
11
|
const OPENCODE_ZEN_TIER_RANKING = {
|
|
@@ -57,6 +57,15 @@ export const opencodeZenAdapter: ProviderAdapter = {
|
|
|
57
57
|
return undefined;
|
|
58
58
|
},
|
|
59
59
|
|
|
60
|
+
listModels(): ProviderModel[] {
|
|
61
|
+
return OPENCODE_ZEN_CATALOG.map((model) => ({
|
|
62
|
+
id: model.id,
|
|
63
|
+
contextWindow: model.contextWindow,
|
|
64
|
+
quotaPool: OPENCODE_ZEN_PROVIDER_ID,
|
|
65
|
+
source: "catalog",
|
|
66
|
+
}));
|
|
67
|
+
},
|
|
68
|
+
|
|
60
69
|
ownsModel(model: string): boolean {
|
|
61
70
|
return isOpenCodeZenModel(model);
|
|
62
71
|
},
|