tuxevil-rotator 3.0.0 → 3.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 +37 -0
- package/README.md +20 -6
- package/package.json +1 -1
- package/src/account-store.ts +37 -5
- package/src/cli.ts +24 -3
- package/src/compat/model-specs.ts +1 -0
- package/src/compat.ts +540 -24
- package/src/config-normalize.ts +73 -30
- package/src/dashboard.ts +43 -42
- package/src/index.ts +1 -0
- package/src/onboarding.ts +349 -21
- package/src/providers/adapter.ts +18 -0
- package/src/providers/credential-helpers.ts +64 -0
- package/src/providers/google-antigravity/index.ts +9 -0
- package/src/providers/google-antigravity/quota.ts +2 -1
- package/src/providers/google-antigravity/translators.ts +83 -24
- package/src/providers/ollama/index.ts +8 -0
- package/src/providers/ollama/quota.ts +2 -1
- package/src/providers/openai-codex/catalog.ts +117 -0
- package/src/providers/openai-codex/compat.ts +556 -0
- package/src/providers/openai-codex/credentials.ts +82 -0
- package/src/providers/openai-codex/forward.ts +240 -0
- package/src/providers/openai-codex/index.ts +153 -0
- package/src/providers/openai-codex/login.ts +172 -0
- package/src/providers/openai-codex/oauth.ts +359 -0
- package/src/providers/openai-codex/quota.ts +231 -0
- package/src/providers/opencode-zen/catalog.ts +37 -0
- package/src/providers/opencode-zen/credentials.ts +31 -0
- package/src/providers/opencode-zen/forward.ts +214 -0
- package/src/providers/opencode-zen/index.ts +73 -0
- package/src/providers/opencode-zen/login.ts +81 -0
- package/src/providers/opencode-zen/quota.ts +67 -0
- package/src/providers/registry.ts +24 -5
- package/src/proxy.ts +75 -27
- package/src/rate-limit-parser.ts +2 -1
- package/src/rotator.ts +259 -48
- package/src/spend-logger.ts +2 -0
- package/src/static/dashboard-keys.js +152 -2
- package/src/static/dashboard.js +161 -37
- package/src/types.ts +83 -1
- package/src/validators.ts +11 -2
- package/tools/telemetry-receiver/receiver.js +14 -0
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { createServer, type Server } from "node:http";
|
|
3
|
+
|
|
4
|
+
export const CODEX_PROVIDER_ID = "openai-codex";
|
|
5
|
+
export const DEFAULT_CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
|
|
6
|
+
export const DEFAULT_CODEX_AUTHORIZE_URL = "https://auth.openai.com/oauth/authorize";
|
|
7
|
+
export const DEFAULT_CODEX_TOKEN_URL = "https://auth.openai.com/oauth/token";
|
|
8
|
+
export const DEFAULT_CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex";
|
|
9
|
+
export const DEFAULT_CODEX_CALLBACK_HOST = "127.0.0.1";
|
|
10
|
+
export const DEFAULT_CODEX_CALLBACK_PORT = 1455;
|
|
11
|
+
export const DEFAULT_CODEX_REDIRECT_HOST = "localhost";
|
|
12
|
+
export const DEFAULT_CODEX_SCOPE = "openid profile email offline_access";
|
|
13
|
+
const CODEX_AUTH_CLAIM = "https://api.openai.com/auth";
|
|
14
|
+
|
|
15
|
+
export interface CodexOAuthConfig {
|
|
16
|
+
clientId: string;
|
|
17
|
+
authorizeUrl: string;
|
|
18
|
+
tokenUrl: string;
|
|
19
|
+
redirectUri: string;
|
|
20
|
+
callbackHost: string;
|
|
21
|
+
callbackPort: number;
|
|
22
|
+
scope: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface CodexTokens {
|
|
26
|
+
accessToken: string;
|
|
27
|
+
refreshToken: string;
|
|
28
|
+
expiresAt: number;
|
|
29
|
+
idToken?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface CodexIdentity {
|
|
33
|
+
email?: string;
|
|
34
|
+
providerAccountId?: string;
|
|
35
|
+
planType?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export class CodexOAuthError extends Error {
|
|
39
|
+
readonly status?: number;
|
|
40
|
+
readonly code: string;
|
|
41
|
+
readonly reloginRequired: boolean;
|
|
42
|
+
|
|
43
|
+
constructor(
|
|
44
|
+
message: string,
|
|
45
|
+
options: { code?: string; status?: number; reloginRequired?: boolean } = {},
|
|
46
|
+
) {
|
|
47
|
+
super(message);
|
|
48
|
+
this.name = "CodexOAuthError";
|
|
49
|
+
this.code = options.code ?? "codex_oauth_error";
|
|
50
|
+
this.status = options.status;
|
|
51
|
+
this.reloginRequired = options.reloginRequired ?? false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function env(name: string, fallback: string): string {
|
|
56
|
+
const value = process.env[name]?.trim();
|
|
57
|
+
return value || fallback;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function parsePort(value: string | undefined): number {
|
|
61
|
+
const parsed = Number(value);
|
|
62
|
+
return Number.isInteger(parsed) && parsed >= 0 && parsed <= 65535
|
|
63
|
+
? parsed
|
|
64
|
+
: DEFAULT_CODEX_CALLBACK_PORT;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function getCodexOAuthConfig(overrides: Partial<NodeJS.ProcessEnv> = {}): CodexOAuthConfig {
|
|
68
|
+
const get = (name: string, fallback: string): string =>
|
|
69
|
+
overrides[name]?.trim() || env(name, fallback);
|
|
70
|
+
const callbackHost = get("CODEX_OAUTH_CALLBACK_HOST", DEFAULT_CODEX_CALLBACK_HOST);
|
|
71
|
+
const callbackPort = parsePort(
|
|
72
|
+
overrides.CODEX_OAUTH_CALLBACK_PORT ?? process.env.CODEX_OAUTH_CALLBACK_PORT,
|
|
73
|
+
);
|
|
74
|
+
const redirectUri = get(
|
|
75
|
+
"CODEX_OAUTH_REDIRECT_URI",
|
|
76
|
+
`http://${DEFAULT_CODEX_REDIRECT_HOST}:${callbackPort}/auth/callback`,
|
|
77
|
+
);
|
|
78
|
+
return {
|
|
79
|
+
clientId: get("CODEX_OAUTH_CLIENT_ID", DEFAULT_CODEX_CLIENT_ID),
|
|
80
|
+
authorizeUrl: get("CODEX_OAUTH_AUTHORIZE_URL", DEFAULT_CODEX_AUTHORIZE_URL),
|
|
81
|
+
tokenUrl: get("CODEX_OAUTH_TOKEN_URL", DEFAULT_CODEX_TOKEN_URL),
|
|
82
|
+
redirectUri,
|
|
83
|
+
callbackHost,
|
|
84
|
+
callbackPort,
|
|
85
|
+
scope: get("CODEX_OAUTH_SCOPE", DEFAULT_CODEX_SCOPE),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function base64UrlEncode(value: Uint8Array): string {
|
|
90
|
+
return Buffer.from(value).toString("base64url");
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function generatePKCE(): { verifier: string; challenge: string } {
|
|
94
|
+
const verifier = base64UrlEncode(randomBytes(32));
|
|
95
|
+
const challenge = base64UrlEncode(createHash("sha256").update(verifier).digest());
|
|
96
|
+
return { verifier, challenge };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function createOAuthState(): string {
|
|
100
|
+
return randomBytes(24).toString("hex");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function buildCodexAuthorizationUrl(
|
|
104
|
+
config: CodexOAuthConfig,
|
|
105
|
+
state: string,
|
|
106
|
+
challenge: string,
|
|
107
|
+
): string {
|
|
108
|
+
const url = new URL(config.authorizeUrl);
|
|
109
|
+
url.searchParams.set("response_type", "code");
|
|
110
|
+
url.searchParams.set("client_id", config.clientId);
|
|
111
|
+
url.searchParams.set("redirect_uri", config.redirectUri);
|
|
112
|
+
url.searchParams.set("scope", config.scope);
|
|
113
|
+
url.searchParams.set("code_challenge", challenge);
|
|
114
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
115
|
+
url.searchParams.set("state", state);
|
|
116
|
+
// These flags are part of the Codex CLI flow and do not contain secrets.
|
|
117
|
+
url.searchParams.set("id_token_add_organizations", "true");
|
|
118
|
+
url.searchParams.set("codex_cli_simplified_flow", "true");
|
|
119
|
+
url.searchParams.set("originator", "codex_cli_rs");
|
|
120
|
+
// Force a fresh ChatGPT session so adding a second Codex account does not
|
|
121
|
+
// silently reuse the first browser session.
|
|
122
|
+
url.searchParams.set("prompt", "login");
|
|
123
|
+
return url.toString();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function html(title: string, message: string): string {
|
|
127
|
+
const escaped = message.replace(/[&<>"]|'/g, (char) =>
|
|
128
|
+
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]!,
|
|
129
|
+
);
|
|
130
|
+
return `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title></head><body><h1>${title}</h1><p>${escaped}</p></body></html>`;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export interface CodexCallbackServer {
|
|
134
|
+
server: Server;
|
|
135
|
+
address: string;
|
|
136
|
+
waitForCode(): Promise<string | null>;
|
|
137
|
+
close(): Promise<void>;
|
|
138
|
+
cancel(): void;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function isLoopbackHost(host: string): boolean {
|
|
142
|
+
const normalized = host.toLowerCase().replace(/^\[|\]$/g, "");
|
|
143
|
+
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Start a loopback-only callback server and reject callbacks with a bad state. */
|
|
147
|
+
export async function startCodexCallbackServer(
|
|
148
|
+
state: string,
|
|
149
|
+
options: Pick<CodexOAuthConfig, "callbackHost" | "callbackPort" | "redirectUri"> = getCodexOAuthConfig(),
|
|
150
|
+
): Promise<CodexCallbackServer> {
|
|
151
|
+
if (!isLoopbackHost(options.callbackHost)) {
|
|
152
|
+
throw new CodexOAuthError("Codex OAuth callback must bind to a loopback host.", {
|
|
153
|
+
code: "invalid_callback_host",
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
let resolveCode: (code: string | null) => void = () => undefined;
|
|
157
|
+
let settled = false;
|
|
158
|
+
const result = new Promise<string | null>((resolve) => {
|
|
159
|
+
resolveCode = (code) => {
|
|
160
|
+
if (settled) return;
|
|
161
|
+
settled = true;
|
|
162
|
+
resolve(code);
|
|
163
|
+
};
|
|
164
|
+
});
|
|
165
|
+
const callbackPath = new URL(options.redirectUri).pathname || "/auth/callback";
|
|
166
|
+
const server = createServer((request, response) => {
|
|
167
|
+
try {
|
|
168
|
+
const url = new URL(request.url ?? "/", `http://${options.callbackHost}`);
|
|
169
|
+
if (url.pathname !== callbackPath) {
|
|
170
|
+
response.writeHead(404, { "content-type": "text/html; charset=utf-8" });
|
|
171
|
+
response.end(html("Codex OAuth", "Callback route not found."));
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (url.searchParams.get("state") !== state) {
|
|
175
|
+
response.writeHead(400, { "content-type": "text/html; charset=utf-8" });
|
|
176
|
+
response.end(html("Codex OAuth", "The OAuth state was invalid."));
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const error = url.searchParams.get("error");
|
|
180
|
+
const code = url.searchParams.get("code");
|
|
181
|
+
if (error || !code) {
|
|
182
|
+
response.writeHead(400, { "content-type": "text/html; charset=utf-8" });
|
|
183
|
+
response.end(html("Codex OAuth", "The authorization was cancelled or did not return a code."));
|
|
184
|
+
resolveCode(null);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
188
|
+
response.end(html("Codex OAuth", "Authentication completed. You can close this window."));
|
|
189
|
+
resolveCode(code);
|
|
190
|
+
} catch {
|
|
191
|
+
response.writeHead(500, { "content-type": "text/html; charset=utf-8" });
|
|
192
|
+
response.end(html("Codex OAuth", "Could not process the callback."));
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
await new Promise<void>((resolve, reject) => {
|
|
197
|
+
const onError = (error: Error): void => {
|
|
198
|
+
server.off("listening", onListening);
|
|
199
|
+
reject(error);
|
|
200
|
+
};
|
|
201
|
+
const onListening = (): void => {
|
|
202
|
+
server.off("error", onError);
|
|
203
|
+
resolve();
|
|
204
|
+
};
|
|
205
|
+
server.once("error", onError);
|
|
206
|
+
server.once("listening", onListening);
|
|
207
|
+
server.listen(options.callbackPort, options.callbackHost);
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
const addressInfo = server.address();
|
|
211
|
+
const port = typeof addressInfo === "object" && addressInfo ? addressInfo.port : options.callbackPort;
|
|
212
|
+
return {
|
|
213
|
+
server,
|
|
214
|
+
address: `http://${options.callbackHost}:${port}${callbackPath}`,
|
|
215
|
+
waitForCode: () => result,
|
|
216
|
+
cancel: () => resolveCode(null),
|
|
217
|
+
close: async () => {
|
|
218
|
+
resolveCode(null);
|
|
219
|
+
if (!server.listening) return;
|
|
220
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function decodeJwtPayload(token: string): Record<string, unknown> | null {
|
|
226
|
+
try {
|
|
227
|
+
const payload = token.split(".")[1];
|
|
228
|
+
if (!payload) return null;
|
|
229
|
+
return JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as Record<string, unknown>;
|
|
230
|
+
} catch {
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function parseCodexIdentity(...tokens: Array<string | undefined>): CodexIdentity {
|
|
236
|
+
const result: CodexIdentity = {};
|
|
237
|
+
for (const token of tokens) {
|
|
238
|
+
if (!token) continue;
|
|
239
|
+
const payload = decodeJwtPayload(token);
|
|
240
|
+
if (!payload) continue;
|
|
241
|
+
if (!result.email && typeof payload.email === "string") result.email = payload.email;
|
|
242
|
+
const auth = payload[CODEX_AUTH_CLAIM];
|
|
243
|
+
if (auth && typeof auth === "object" && !Array.isArray(auth)) {
|
|
244
|
+
const claims = auth as Record<string, unknown>;
|
|
245
|
+
if (!result.providerAccountId && typeof claims.chatgpt_account_id === "string") {
|
|
246
|
+
result.providerAccountId = claims.chatgpt_account_id;
|
|
247
|
+
}
|
|
248
|
+
if (!result.planType && typeof claims.chatgpt_plan_type === "string") {
|
|
249
|
+
result.planType = claims.chatgpt_plan_type;
|
|
250
|
+
}
|
|
251
|
+
if (!result.email && typeof claims.email === "string") result.email = claims.email;
|
|
252
|
+
}
|
|
253
|
+
if (!result.providerAccountId && typeof payload.chatgpt_account_id === "string") {
|
|
254
|
+
result.providerAccountId = payload.chatgpt_account_id;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return result;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function parseTokenError(response: Response, body: unknown): CodexOAuthError {
|
|
261
|
+
const record = body && typeof body === "object" && !Array.isArray(body)
|
|
262
|
+
? body as Record<string, unknown>
|
|
263
|
+
: {};
|
|
264
|
+
const nested = record.error && typeof record.error === "object" && !Array.isArray(record.error)
|
|
265
|
+
? record.error as Record<string, unknown>
|
|
266
|
+
: null;
|
|
267
|
+
const code = typeof nested?.code === "string"
|
|
268
|
+
? nested.code
|
|
269
|
+
: typeof nested?.type === "string"
|
|
270
|
+
? nested.type
|
|
271
|
+
: typeof record.error === "string"
|
|
272
|
+
? record.error
|
|
273
|
+
: `http_${response.status}`;
|
|
274
|
+
const relogin = response.status === 401 || response.status === 403 ||
|
|
275
|
+
["invalid_grant", "invalid_token", "refresh_token_reused"].includes(code);
|
|
276
|
+
const message = code === "refresh_token_reused"
|
|
277
|
+
? "Codex refresh token was already used by another client; re-authentication is required."
|
|
278
|
+
: `Codex OAuth request failed (${response.status}, ${code}).`;
|
|
279
|
+
return new CodexOAuthError(message, { code, status: response.status, reloginRequired: relogin });
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async function postToken(
|
|
283
|
+
params: URLSearchParams,
|
|
284
|
+
config: CodexOAuthConfig,
|
|
285
|
+
previousRefreshToken?: string,
|
|
286
|
+
): Promise<CodexTokens> {
|
|
287
|
+
const response = await fetch(config.tokenUrl, {
|
|
288
|
+
method: "POST",
|
|
289
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
290
|
+
body: params,
|
|
291
|
+
});
|
|
292
|
+
let body: unknown = null;
|
|
293
|
+
try { body = await response.json(); } catch { /* handled below */ }
|
|
294
|
+
if (!response.ok) throw parseTokenError(response, body);
|
|
295
|
+
const record = body && typeof body === "object" && !Array.isArray(body)
|
|
296
|
+
? body as Record<string, unknown>
|
|
297
|
+
: {};
|
|
298
|
+
const accessToken = typeof record.access_token === "string" ? record.access_token : "";
|
|
299
|
+
const refreshToken = typeof record.refresh_token === "string" && record.refresh_token
|
|
300
|
+
? record.refresh_token
|
|
301
|
+
: previousRefreshToken ?? "";
|
|
302
|
+
const expiresIn = typeof record.expires_in === "number" ? record.expires_in : 3600;
|
|
303
|
+
if (!accessToken || !refreshToken) {
|
|
304
|
+
throw new CodexOAuthError("Codex OAuth response did not include usable tokens.", {
|
|
305
|
+
code: "token_response_incomplete",
|
|
306
|
+
reloginRequired: true,
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
return {
|
|
310
|
+
accessToken,
|
|
311
|
+
refreshToken,
|
|
312
|
+
expiresAt: Date.now() + Math.max(1, expiresIn) * 1000,
|
|
313
|
+
idToken: typeof record.id_token === "string" ? record.id_token : undefined,
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export async function exchangeCodexAuthorizationCode(
|
|
318
|
+
code: string,
|
|
319
|
+
verifier: string,
|
|
320
|
+
config: CodexOAuthConfig = getCodexOAuthConfig(),
|
|
321
|
+
): Promise<CodexTokens> {
|
|
322
|
+
return postToken(new URLSearchParams({
|
|
323
|
+
grant_type: "authorization_code",
|
|
324
|
+
client_id: config.clientId,
|
|
325
|
+
code,
|
|
326
|
+
redirect_uri: config.redirectUri,
|
|
327
|
+
code_verifier: verifier,
|
|
328
|
+
}), config);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export async function refreshCodexToken(
|
|
332
|
+
refreshToken: string,
|
|
333
|
+
config: CodexOAuthConfig = getCodexOAuthConfig(),
|
|
334
|
+
): Promise<CodexTokens> {
|
|
335
|
+
if (!refreshToken.trim()) {
|
|
336
|
+
throw new CodexOAuthError("Codex refresh token is missing; re-authentication is required.", {
|
|
337
|
+
code: "missing_refresh_token",
|
|
338
|
+
reloginRequired: true,
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
return postToken(new URLSearchParams({
|
|
342
|
+
grant_type: "refresh_token",
|
|
343
|
+
refresh_token: refreshToken,
|
|
344
|
+
client_id: config.clientId,
|
|
345
|
+
}), config, refreshToken);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export function createCodexAuthorizationFlow(
|
|
349
|
+
config: CodexOAuthConfig = getCodexOAuthConfig(),
|
|
350
|
+
): { verifier: string; state: string; url: string } {
|
|
351
|
+
const { verifier, challenge } = generatePKCE();
|
|
352
|
+
const state = createOAuthState();
|
|
353
|
+
return { verifier, state, url: buildCodexAuthorizationUrl(config, state, challenge) };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export function codexOAuthErrorMessage(error: unknown): string {
|
|
357
|
+
if (error instanceof CodexOAuthError) return error.message;
|
|
358
|
+
return "Codex OAuth request failed; re-authentication may be required.";
|
|
359
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import type { AccountRuntime, ModelQuota } from "../../types.js";
|
|
2
|
+
import type { QuotaFetchContext } from "../adapter.js";
|
|
3
|
+
import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
|
|
4
|
+
import { getCodexAccountId, getCodexTokenState } from "./credentials.js";
|
|
5
|
+
import { CODEX_PROVIDER_ID } from "./oauth.js";
|
|
6
|
+
import { sortQuotaPools } from "../registry.js";
|
|
7
|
+
|
|
8
|
+
export const CODEX_QUOTA_MODEL_KEY = "openai-codex";
|
|
9
|
+
export const CODEX_SPARK_QUOTA_MODEL_KEY = "openai-codex-spark";
|
|
10
|
+
export const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
|
|
11
|
+
export const CODEX_QUOTA_CACHE_TTL_MS = 60_000;
|
|
12
|
+
export const CODEX_QUOTA_TIMEOUT_MS = 8_000;
|
|
13
|
+
|
|
14
|
+
export interface CodexQuotaWindow {
|
|
15
|
+
usedPercent: number;
|
|
16
|
+
percentRemaining: number;
|
|
17
|
+
resetAt: string | null;
|
|
18
|
+
resetAfterSeconds: number | null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface CodexQuotaSnapshot {
|
|
22
|
+
primary: CodexQuotaWindow;
|
|
23
|
+
secondary: CodexQuotaWindow;
|
|
24
|
+
spark?: { primary?: CodexQuotaWindow; secondary?: CodexQuotaWindow };
|
|
25
|
+
bankedResetCredits?: number;
|
|
26
|
+
rateLimitReachedType?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function record(value: unknown): Record<string, unknown> {
|
|
30
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
31
|
+
? value as Record<string, unknown>
|
|
32
|
+
: {};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function number(value: unknown): number | null {
|
|
36
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
37
|
+
if (typeof value === "string" && value.trim()) {
|
|
38
|
+
const parsed = Number(value);
|
|
39
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function resetAt(window: Record<string, unknown>): { at: string | null; after: number | null } {
|
|
45
|
+
const absolute = number(window.reset_at ?? window.resetAt);
|
|
46
|
+
if (absolute !== null && absolute > 0) {
|
|
47
|
+
const millis = absolute > 10_000_000_000 ? absolute : absolute * 1000;
|
|
48
|
+
return { at: new Date(millis).toISOString(), after: Math.max(0, Math.round((millis - Date.now()) / 1000)) };
|
|
49
|
+
}
|
|
50
|
+
const after = number(window.reset_after_seconds ?? window.resetAfterSeconds);
|
|
51
|
+
return {
|
|
52
|
+
at: after !== null && after > 0 ? new Date(Date.now() + after * 1000).toISOString() : null,
|
|
53
|
+
after: after !== null && after > 0 ? after : null,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function parseCodexQuotaWindow(value: unknown): CodexQuotaWindow | null {
|
|
58
|
+
const window = record(value);
|
|
59
|
+
if (Object.keys(window).length === 0) return null;
|
|
60
|
+
const used = number(window.used_percent ?? window.usedPercent);
|
|
61
|
+
const reset = resetAt(window);
|
|
62
|
+
const usedPercent = Math.max(0, Math.min(100, used ?? 0));
|
|
63
|
+
return {
|
|
64
|
+
usedPercent,
|
|
65
|
+
percentRemaining: Math.max(0, Math.min(100, 100 - usedPercent)),
|
|
66
|
+
resetAt: reset.at,
|
|
67
|
+
resetAfterSeconds: reset.after,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function findAdditionalLimit(data: Record<string, unknown>, matcher: (text: string) => boolean): Record<string, unknown> {
|
|
72
|
+
const limits = data.additional_rate_limits ?? data.additionalRateLimits;
|
|
73
|
+
if (!Array.isArray(limits)) return {};
|
|
74
|
+
for (const item of limits) {
|
|
75
|
+
const entry = record(item);
|
|
76
|
+
const descriptor = [entry.limit_name, entry.limitName, entry.metered_feature, entry.meteredFeature, entry.limit_id, entry.limitId, entry.id, entry.name]
|
|
77
|
+
.filter((part): part is string => typeof part === "string")
|
|
78
|
+
.join(" ")
|
|
79
|
+
.toLowerCase();
|
|
80
|
+
if (matcher(descriptor)) return record(entry.rate_limit ?? entry.rateLimit);
|
|
81
|
+
}
|
|
82
|
+
return {};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function parseCodexUsageResponse(value: unknown): CodexQuotaSnapshot | null {
|
|
86
|
+
const data = record(value);
|
|
87
|
+
const rateLimit = record(data.rate_limit ?? data.rateLimit);
|
|
88
|
+
const primary = parseCodexQuotaWindow(rateLimit.primary_window ?? rateLimit.primaryWindow);
|
|
89
|
+
const secondary = parseCodexQuotaWindow(rateLimit.secondary_window ?? rateLimit.secondaryWindow);
|
|
90
|
+
if (!primary && !secondary) return null;
|
|
91
|
+
const empty: CodexQuotaWindow = { usedPercent: 0, percentRemaining: 100, resetAt: null, resetAfterSeconds: null };
|
|
92
|
+
const sparkRateLimit = findAdditionalLimit(data, (text) => text.includes("spark"));
|
|
93
|
+
const sparkPrimary = parseCodexQuotaWindow(sparkRateLimit.primary_window ?? sparkRateLimit.primaryWindow);
|
|
94
|
+
const sparkSecondary = parseCodexQuotaWindow(sparkRateLimit.secondary_window ?? sparkRateLimit.secondaryWindow);
|
|
95
|
+
const credits = record(data.rate_limit_reset_credits ?? data.rateLimitResetCredits);
|
|
96
|
+
const banked = number(credits.available_count ?? credits.availableCount);
|
|
97
|
+
const reached = data.rate_limit_reached_type ?? data.rateLimitReachedType;
|
|
98
|
+
return {
|
|
99
|
+
primary: primary ?? empty,
|
|
100
|
+
secondary: secondary ?? empty,
|
|
101
|
+
...(sparkPrimary || sparkSecondary ? { spark: { primary: sparkPrimary ?? undefined, secondary: sparkSecondary ?? undefined } } : {}),
|
|
102
|
+
...(banked !== null ? { bankedResetCredits: banked } : {}),
|
|
103
|
+
...(typeof reached === "string" && reached.trim() ? { rateLimitReachedType: reached.trim() } : {}),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function dominantWindow(snapshot: CodexQuotaSnapshot): CodexQuotaWindow {
|
|
108
|
+
return snapshot.primary.usedPercent >= snapshot.secondary.usedPercent
|
|
109
|
+
? snapshot.primary
|
|
110
|
+
: snapshot.secondary;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function timerType(window: CodexQuotaWindow): "fresh" | "5h" | "7d" {
|
|
114
|
+
if (!window.resetAt) return "fresh";
|
|
115
|
+
const remaining = new Date(window.resetAt).getTime() - Date.now();
|
|
116
|
+
return remaining > 24 * 60 * 60 * 1000 ? "7d" : "5h";
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function codexQuotaRows(snapshot: CodexQuotaSnapshot): ModelQuota[] {
|
|
120
|
+
const dominant = dominantWindow(snapshot);
|
|
121
|
+
const rows: ModelQuota[] = [{
|
|
122
|
+
modelKey: CODEX_QUOTA_MODEL_KEY,
|
|
123
|
+
displayName: "Codex",
|
|
124
|
+
providerId: CODEX_PROVIDER_ID,
|
|
125
|
+
percentRemaining: dominant.percentRemaining,
|
|
126
|
+
resetTime: dominant.resetAt,
|
|
127
|
+
timerType: timerType(dominant),
|
|
128
|
+
}];
|
|
129
|
+
if (snapshot.spark) {
|
|
130
|
+
const spark = snapshot.spark.primary && snapshot.spark.secondary
|
|
131
|
+
? snapshot.spark.primary.usedPercent >= snapshot.spark.secondary.usedPercent ? snapshot.spark.primary : snapshot.spark.secondary
|
|
132
|
+
: snapshot.spark.primary ?? snapshot.spark.secondary;
|
|
133
|
+
if (spark) rows.push({
|
|
134
|
+
modelKey: CODEX_SPARK_QUOTA_MODEL_KEY,
|
|
135
|
+
displayName: "Codex Spark",
|
|
136
|
+
providerId: CODEX_PROVIDER_ID,
|
|
137
|
+
percentRemaining: spark.percentRemaining,
|
|
138
|
+
resetTime: spark.resetAt,
|
|
139
|
+
timerType: timerType(spark),
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
return rows;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const quotaCache = new Map<string, { fetchedAt: number; snapshot: CodexQuotaSnapshot }>();
|
|
146
|
+
let lastQuotaFetchAt = 0;
|
|
147
|
+
let quotaFetchChain = Promise.resolve();
|
|
148
|
+
|
|
149
|
+
async function throttleQuotaFetch(): Promise<void> {
|
|
150
|
+
const previous = quotaFetchChain;
|
|
151
|
+
let release!: () => void;
|
|
152
|
+
quotaFetchChain = new Promise<void>((resolve) => { release = resolve; });
|
|
153
|
+
await previous;
|
|
154
|
+
const wait = Math.max(0, 250 - (Date.now() - lastQuotaFetchAt));
|
|
155
|
+
if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
|
|
156
|
+
lastQuotaFetchAt = Date.now();
|
|
157
|
+
release();
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function cacheKey(account: AccountRuntime): string {
|
|
161
|
+
return `${account.config.email.toLowerCase()}:${getCodexAccountId(account.config) ?? "unknown"}`;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function clearCodexQuotaCache(): void { quotaCache.clear(); }
|
|
165
|
+
|
|
166
|
+
export async function fetchCodexQuota(
|
|
167
|
+
account: AccountRuntime,
|
|
168
|
+
ctx: QuotaFetchContext,
|
|
169
|
+
): Promise<void> {
|
|
170
|
+
const key = cacheKey(account);
|
|
171
|
+
const cached = quotaCache.get(key);
|
|
172
|
+
if (cached && Date.now() - cached.fetchedAt < CODEX_QUOTA_CACHE_TTL_MS) {
|
|
173
|
+
applyQuotaRows(account, cached.snapshot);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const token = getCodexTokenState(account).accessToken;
|
|
177
|
+
if (!token) return;
|
|
178
|
+
try {
|
|
179
|
+
await throttleQuotaFetch();
|
|
180
|
+
const headers: Record<string, string> = {
|
|
181
|
+
Authorization: `Bearer ${token}`,
|
|
182
|
+
Accept: "application/json",
|
|
183
|
+
};
|
|
184
|
+
const accountId = getCodexAccountId(account.config);
|
|
185
|
+
if (accountId) headers["chatgpt-account-id"] = accountId;
|
|
186
|
+
const response = await fetch(process.env.CODEX_USAGE_URL?.trim() || CODEX_USAGE_URL, {
|
|
187
|
+
method: "GET",
|
|
188
|
+
headers,
|
|
189
|
+
signal: AbortSignal.timeout(CODEX_QUOTA_TIMEOUT_MS),
|
|
190
|
+
dispatcher: getAccountProxyDispatcher(account, CODEX_PROVIDER_ID),
|
|
191
|
+
} as RequestInit & { dispatcher?: unknown });
|
|
192
|
+
if (response.status === 401 || response.status === 403) {
|
|
193
|
+
const message = `Codex usage endpoint returned ${response.status}; re-authentication required`;
|
|
194
|
+
ctx.markProviderInvalid?.(account, CODEX_PROVIDER_ID, message);
|
|
195
|
+
ctx.log(`${account.config.email}: ${message}`);
|
|
196
|
+
quotaCache.delete(key);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (response.status === 429 || response.status >= 500) {
|
|
200
|
+
const cooldown = Math.min(5 * 60_000, Math.max(30_000, Number(response.headers.get("retry-after")) * 1000 || 60_000));
|
|
201
|
+
ctx.setProviderCooldown?.(account, CODEX_PROVIDER_ID, cooldown);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (!response.ok) return;
|
|
205
|
+
const snapshot = parseCodexUsageResponse(await response.json());
|
|
206
|
+
if (!snapshot) return;
|
|
207
|
+
quotaCache.set(key, { fetchedAt: Date.now(), snapshot });
|
|
208
|
+
applyQuotaRows(account, snapshot);
|
|
209
|
+
account.lastQuotaPoll = Date.now();
|
|
210
|
+
} catch {
|
|
211
|
+
// Quota is best-effort and never blocks a generation request.
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function applyQuotaRows(account: AccountRuntime, snapshot: CodexQuotaSnapshot): void {
|
|
216
|
+
const other = (account.quota ?? []).filter(
|
|
217
|
+
(quota) => quota.providerId !== CODEX_PROVIDER_ID,
|
|
218
|
+
);
|
|
219
|
+
const codexRows = codexQuotaRows(snapshot);
|
|
220
|
+
account.quota = sortQuotaPools([...other, ...codexRows]);
|
|
221
|
+
|
|
222
|
+
account.lastPollByProvider ??= {};
|
|
223
|
+
account.lastPollByProvider[CODEX_PROVIDER_ID] = codexRows
|
|
224
|
+
.map((q) => {
|
|
225
|
+
const remain = q.resetTime
|
|
226
|
+
? Math.round((new Date(q.resetTime).getTime() - Date.now()) / 60000) + "m"
|
|
227
|
+
: "no_reset";
|
|
228
|
+
return `[${q.modelKey}: ${q.timerType} ${q.percentRemaining}% in ${remain}]`;
|
|
229
|
+
})
|
|
230
|
+
.join(" | ");
|
|
231
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// OpenCode Zen provider model catalog and endpoint constants.
|
|
2
|
+
|
|
3
|
+
export const OPENCODE_ZEN_BASE_URL = "https://opencode.ai/zen/v1";
|
|
4
|
+
export const OPENCODE_ZEN_MODELS_URL = "https://opencode.ai/zen/v1/models";
|
|
5
|
+
export const OPENCODE_ZEN_CHAT_URL = "https://opencode.ai/zen/v1/chat/completions";
|
|
6
|
+
|
|
7
|
+
export const OPENCODE_ZEN_FREE_MODELS = [
|
|
8
|
+
"deepseek-v4-flash-free",
|
|
9
|
+
"nemotron-3.5-lightning-free",
|
|
10
|
+
"nemotron-3-ultra-free",
|
|
11
|
+
"mimo-v2.5-free",
|
|
12
|
+
"hy3-free",
|
|
13
|
+
] as const;
|
|
14
|
+
|
|
15
|
+
export type OpenCodeZenModel = (typeof OPENCODE_ZEN_FREE_MODELS)[number];
|
|
16
|
+
|
|
17
|
+
export interface OpenCodeZenModelSpec {
|
|
18
|
+
id: string;
|
|
19
|
+
contextWindow: number;
|
|
20
|
+
free: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const OPENCODE_ZEN_CATALOG: OpenCodeZenModelSpec[] = OPENCODE_ZEN_FREE_MODELS.map(
|
|
24
|
+
(id) => ({
|
|
25
|
+
id,
|
|
26
|
+
contextWindow: 128000,
|
|
27
|
+
free: true,
|
|
28
|
+
}),
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
const OPENCODE_ZEN_MODEL_SET = new Set<string>(OPENCODE_ZEN_FREE_MODELS);
|
|
32
|
+
|
|
33
|
+
export function isOpenCodeZenModel(model: string): boolean {
|
|
34
|
+
if (!model) return false;
|
|
35
|
+
if (OPENCODE_ZEN_MODEL_SET.has(model)) return true;
|
|
36
|
+
return model.endsWith("-free");
|
|
37
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// OpenCode Zen credential helpers and validation.
|
|
2
|
+
|
|
3
|
+
import type { AccountConfig } from "../../types.js";
|
|
4
|
+
import type { CredentialValidationResult } from "../adapter.js";
|
|
5
|
+
import { getCredential } from "../credential-helpers.js";
|
|
6
|
+
|
|
7
|
+
export const OPENCODE_ZEN_PROVIDER_ID = "opencode-zen";
|
|
8
|
+
|
|
9
|
+
export function getOpenCodeZenApiKey(config: AccountConfig): string | undefined {
|
|
10
|
+
return getCredential(config, OPENCODE_ZEN_PROVIDER_ID)?.apiKey ?? config.apiKey;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function validateCredentials(
|
|
14
|
+
config: AccountConfig,
|
|
15
|
+
): Promise<CredentialValidationResult> {
|
|
16
|
+
const key = getOpenCodeZenApiKey(config);
|
|
17
|
+
if (typeof key !== "string" || key.trim() === "") {
|
|
18
|
+
return {
|
|
19
|
+
ok: false,
|
|
20
|
+
status: 0,
|
|
21
|
+
error: "OpenCode Zen account is missing an apiKey",
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
return { ok: true };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function defaultAccountEmail(apiKey: string): string {
|
|
28
|
+
const clean = apiKey.trim();
|
|
29
|
+
const suffix = clean.length > 8 ? clean.slice(-8) : clean;
|
|
30
|
+
return `zen-${suffix}@opencode.ai`;
|
|
31
|
+
}
|