tuxevil-rotator 3.0.0 → 3.1.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.
@@ -0,0 +1,240 @@
1
+ import type { AccountRuntime, ProviderCredential } from "../../types.js";
2
+ import type { ForwardedResponse, RequestBody } from "../../proxy.js";
3
+ import type { StreamAccumulator, TokenUsage } from "../adapter.js";
4
+ import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
5
+ import type { RequestInitWithDispatcher } from "../../fetch-with-retry.js";
6
+ import { getCodexAccountId, getCodexCredential, getCodexTokenState } from "./credentials.js";
7
+ import { DEFAULT_CODEX_BASE_URL, CODEX_PROVIDER_ID } from "./oauth.js";
8
+
9
+ const HOP_BY_HOP = new Set([
10
+ "connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
11
+ "te", "trailers", "transfer-encoding", "upgrade", "host", "content-length",
12
+ "x-forwarded-for", "x-forwarded-host", "x-forwarded-proto", "x-forwarded-port",
13
+ "x-real-ip", "forwarded", "via",
14
+ ]);
15
+ const DEFAULT_CODEX_INSTRUCTIONS = "You are a helpful assistant.";
16
+
17
+ function isRecord(value: unknown): value is Record<string, unknown> {
18
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19
+ }
20
+
21
+ function codexFunctionTool(value: unknown): unknown {
22
+ if (!isRecord(value) || value.type !== "function") return value;
23
+ const source = isRecord(value.function) ? value.function : value;
24
+ const tool: Record<string, unknown> = {
25
+ type: "function",
26
+ name: source.name,
27
+ };
28
+ for (const field of ["description", "parameters", "strict"]) {
29
+ if (source[field] !== undefined) tool[field] = source[field];
30
+ }
31
+ return tool;
32
+ }
33
+
34
+ function codexToolChoice(value: unknown): unknown {
35
+ if (!isRecord(value) || value.type !== "function") return value;
36
+ if (isRecord(value.function)) {
37
+ return { type: "function", name: value.function.name };
38
+ }
39
+ return value;
40
+ }
41
+
42
+ export function codexBaseUrl(): string {
43
+ return (process.env.CODEX_BASE_URL?.trim() || DEFAULT_CODEX_BASE_URL).replace(/\/$/, "");
44
+ }
45
+
46
+ export function codexResponsesEndpoint(): string {
47
+ const base = codexBaseUrl();
48
+ return base.endsWith("/responses") ? base : `${base}/responses`;
49
+ }
50
+
51
+ /** Remove stateful Responses fields that reference a backend item Codex cannot recover. */
52
+ export function sanitizeCodexResponsesRequest(
53
+ request: Record<string, unknown>,
54
+ model: string,
55
+ ): Record<string, unknown> {
56
+ const sanitized: Record<string, unknown> = { ...request, model };
57
+ sanitized.instructions = codexInstructions(sanitized.instructions);
58
+ sanitized.store = false;
59
+ sanitized.stream = true;
60
+ if (typeof sanitized.input === "string") {
61
+ sanitized.input = [{
62
+ role: "user",
63
+ content: [{ type: "input_text", text: sanitized.input }],
64
+ }];
65
+ }
66
+ if (Array.isArray(sanitized.tools)) {
67
+ sanitized.tools = sanitized.tools.map(codexFunctionTool);
68
+ }
69
+ if (sanitized.tool_choice !== undefined) {
70
+ sanitized.tool_choice = codexToolChoice(sanitized.tool_choice);
71
+ }
72
+ delete sanitized.previous_response_id;
73
+ delete sanitized.conversation;
74
+ delete sanitized.input_items;
75
+ delete sanitized.background;
76
+ delete sanitized.prompt_cache_key;
77
+ delete sanitized.max_output_tokens;
78
+ // The proxy owns streaming; this field is not accepted by the internal endpoint.
79
+ delete sanitized.stream_options;
80
+ return sanitized;
81
+ }
82
+
83
+ function codexInstructions(value: unknown): string {
84
+ if (typeof value === "string" && value.trim()) return value;
85
+ if (Array.isArray(value)) {
86
+ const text = value
87
+ .map((part) => {
88
+ if (typeof part === "string") return part;
89
+ if (isRecord(part) && typeof part.text === "string") return part.text;
90
+ return "";
91
+ })
92
+ .filter(Boolean)
93
+ .join("\n\n")
94
+ .trim();
95
+ if (text) return text;
96
+ }
97
+ return DEFAULT_CODEX_INSTRUCTIONS;
98
+ }
99
+
100
+ /** Build a native Codex Responses payload from the common proxy request envelope. */
101
+ export function buildCodexPayload(body: RequestBody): Record<string, unknown> {
102
+ const request = isRecord(body.request) ? body.request : {};
103
+ return sanitizeCodexResponsesRequest(request, body.model);
104
+ }
105
+
106
+ function authToken(account: AccountRuntime): string {
107
+ const token = getCodexTokenState(account).accessToken;
108
+ if (!token) throw new Error("Codex access token is unavailable; re-authenticate");
109
+ return token;
110
+ }
111
+
112
+ function forwardHeaders(
113
+ originalHeaders: Record<string, string>,
114
+ account: AccountRuntime,
115
+ payload: Record<string, unknown>,
116
+ ): Record<string, string> {
117
+ const headers: Record<string, string> = { ...originalHeaders };
118
+ for (const key of Object.keys(headers)) {
119
+ const lower = key.toLowerCase();
120
+ if (
121
+ HOP_BY_HOP.has(lower) ||
122
+ lower === "authorization" ||
123
+ lower === "x-goog-api-key" ||
124
+ lower === "x-goog-user-project" ||
125
+ lower === "x-goog-user-agent" ||
126
+ lower.startsWith("x-ollama-") ||
127
+ lower === "chatgpt-account-id" ||
128
+ lower === "accept" ||
129
+ lower === "content-type" ||
130
+ lower === "user-agent" ||
131
+ lower === "openai-beta"
132
+ ) delete headers[key];
133
+ }
134
+ headers.Authorization = `Bearer ${authToken(account)}`;
135
+ const accountId = getCodexAccountId(account.config);
136
+ if (accountId) headers["chatgpt-account-id"] = accountId;
137
+ headers["Content-Type"] = "application/json";
138
+ headers.Accept = payload.stream === false ? "application/json" : "text/event-stream";
139
+ headers["OpenAI-Beta"] = "responses=v1";
140
+ headers["User-Agent"] = "tuxevil-rotator/openai-codex";
141
+ return headers;
142
+ }
143
+
144
+ export async function forwardCodexRequest(
145
+ account: AccountRuntime,
146
+ body: RequestBody,
147
+ originalHeaders: Record<string, string>,
148
+ signal?: AbortSignal,
149
+ ): Promise<ForwardedResponse> {
150
+ const payload = buildCodexPayload(body);
151
+ const response = await fetch(codexResponsesEndpoint(), {
152
+ method: "POST",
153
+ headers: forwardHeaders(originalHeaders, account, payload),
154
+ body: JSON.stringify(payload),
155
+ signal,
156
+ dispatcher: getAccountProxyDispatcher(account, CODEX_PROVIDER_ID),
157
+ } as RequestInitWithDispatcher);
158
+ return { response, endpoint: codexResponsesEndpoint() };
159
+ }
160
+
161
+ function usageFromRecord(record: Record<string, unknown>): TokenUsage | null {
162
+ const usage = isRecord(record.usage)
163
+ ? record.usage
164
+ : isRecord(record.response) && isRecord(record.response.usage)
165
+ ? record.response.usage
166
+ : record;
167
+ const input = typeof usage.input_tokens === "number"
168
+ ? usage.input_tokens
169
+ : typeof usage.prompt_tokens === "number"
170
+ ? usage.prompt_tokens
171
+ : 0;
172
+ const output = typeof usage.output_tokens === "number"
173
+ ? usage.output_tokens
174
+ : typeof usage.completion_tokens === "number"
175
+ ? usage.completion_tokens
176
+ : 0;
177
+ return input > 0 || output > 0 ? { inputTokens: input, outputTokens: output } : null;
178
+ }
179
+
180
+ export function extractCodexUsage(raw: string): TokenUsage | null {
181
+ let found: TokenUsage | null = null;
182
+ for (const line of raw.split(/\r?\n/)) {
183
+ const payload = line.startsWith("data:") ? line.slice(5).trim() : line.trim();
184
+ if (!payload || payload === "[DONE]") continue;
185
+ try {
186
+ const parsed = JSON.parse(payload) as Record<string, unknown>;
187
+ found = usageFromRecord(parsed) ?? found;
188
+ } catch {
189
+ // Ignore malformed SSE chunks; a later response.completed chunk can carry usage.
190
+ }
191
+ }
192
+ return found;
193
+ }
194
+
195
+ export class CodexSseAccumulator implements StreamAccumulator {
196
+ private buffer = "";
197
+ private text = "";
198
+ private usage: TokenUsage | null = null;
199
+
200
+ append(chunkText: string): TokenUsage | null {
201
+ this.buffer += chunkText;
202
+ let newline = this.buffer.indexOf("\n");
203
+ let newlyFound: TokenUsage | null = null;
204
+ while (newline >= 0) {
205
+ const line = this.buffer.slice(0, newline).trim();
206
+ this.buffer = this.buffer.slice(newline + 1);
207
+ if (line.startsWith("data:")) {
208
+ const payload = line.slice(5).trim();
209
+ try {
210
+ const parsed = JSON.parse(payload) as Record<string, unknown>;
211
+ const delta = typeof parsed.delta === "string" ? parsed.delta : "";
212
+ if (delta) this.text += delta;
213
+ const usage = usageFromRecord(parsed);
214
+ if (usage) {
215
+ this.usage = usage;
216
+ newlyFound = usage;
217
+ }
218
+ } catch {
219
+ // Ignore malformed events.
220
+ }
221
+ }
222
+ newline = this.buffer.indexOf("\n");
223
+ }
224
+ return newlyFound;
225
+ }
226
+
227
+ getText(): string { return this.text; }
228
+ final(): TokenUsage | null {
229
+ if (this.buffer.trim()) this.append(`${this.buffer}\n`);
230
+ return this.usage;
231
+ }
232
+ }
233
+
234
+ export function createCodexStreamAccumulator(): CodexSseAccumulator {
235
+ return new CodexSseAccumulator();
236
+ }
237
+
238
+ export function getCodexAuthCredential(account: AccountRuntime): ProviderCredential | undefined {
239
+ return getCodexCredential(account.config);
240
+ }
@@ -0,0 +1,142 @@
1
+ import type { AccountRuntime, AccountConfig } from "../../types.js";
2
+ import type { ProviderAdapter, QuotaFetchContext, CredentialValidationResult } from "../adapter.js";
3
+ import { logger } from "../../logger.js";
4
+ import {
5
+ getCodexAccountId,
6
+ getCodexRefreshToken,
7
+ getCodexTokenState,
8
+ persistCodexRefreshToken,
9
+ setCodexTokenState,
10
+ } from "./credentials.js";
11
+ import {
12
+ CodexOAuthError,
13
+ refreshCodexToken,
14
+ } from "./oauth.js";
15
+ import { runCodexLogin } from "./login.js";
16
+ import {
17
+ CodexSseAccumulator,
18
+ extractCodexUsage,
19
+ forwardCodexRequest,
20
+ } from "./forward.js";
21
+ import { fetchCodexQuota } from "./quota.js";
22
+
23
+ const providerLog = logger.child("provider/openai-codex");
24
+ const refreshFlights = new Map<string, Promise<void>>();
25
+
26
+ function refreshKey(account: AccountRuntime): string {
27
+ return `${account.config.email.toLowerCase()}:${getCodexAccountId(account.config) ?? "unknown"}`;
28
+ }
29
+
30
+ async function ensureCodexToken(account: AccountRuntime): Promise<void> {
31
+ const current = getCodexTokenState(account);
32
+ if (current.accessToken && current.tokenExpires > Date.now() + 60_000) return;
33
+ const key = refreshKey(account);
34
+ const inFlight = refreshFlights.get(key);
35
+ if (inFlight) {
36
+ await inFlight;
37
+ return;
38
+ }
39
+ const operation = (async () => {
40
+ const latest = getCodexTokenState(account);
41
+ if (latest.accessToken && latest.tokenExpires > Date.now() + 60_000) return;
42
+ const refreshToken = getCodexRefreshToken(account.config);
43
+ if (!refreshToken) {
44
+ throw new CodexOAuthError(
45
+ `Account ${account.config.email} has no Codex refresh token; re-authenticate`,
46
+ { code: "missing_refresh_token", reloginRequired: true },
47
+ );
48
+ }
49
+ const refreshed = await refreshCodexToken(refreshToken);
50
+ setCodexTokenState(account, {
51
+ accessToken: refreshed.accessToken,
52
+ tokenExpires: refreshed.expiresAt,
53
+ });
54
+ // Rotating refresh tokens are one-time credentials. Persist the returned
55
+ // generation before allowing another request to use this account.
56
+ try {
57
+ await persistCodexRefreshToken(account, refreshed.refreshToken);
58
+ } catch (error) {
59
+ setCodexTokenState(account, { accessToken: null, tokenExpires: 0 });
60
+ throw new Error("Could not persist the rotated Codex refresh token", { cause: error });
61
+ }
62
+ account.consecutiveErrors = 0;
63
+ })();
64
+ refreshFlights.set(key, operation);
65
+ try {
66
+ await operation;
67
+ } finally {
68
+ if (refreshFlights.get(key) === operation) refreshFlights.delete(key);
69
+ }
70
+ }
71
+
72
+ export async function ensureOpenAICodexToken(account: AccountRuntime): Promise<void> {
73
+ await ensureCodexToken(account);
74
+ }
75
+
76
+ export async function validateCodexCredentials(config: AccountConfig): Promise<CredentialValidationResult> {
77
+ if (config.provider !== "openai-codex" && !(config.credentials ?? []).some((entry) => entry.provider === "openai-codex")) {
78
+ return { ok: false, status: 0, error: "Missing openai-codex provider credential" };
79
+ }
80
+ if (!getCodexRefreshToken(config)) {
81
+ return { ok: false, status: 0, error: "Missing refreshToken for OpenAI Codex" };
82
+ }
83
+ return { ok: true };
84
+ }
85
+
86
+ export const openaiCodexAdapter: ProviderAdapter = {
87
+ id: "openai-codex",
88
+ displayName: "OpenAI Codex",
89
+ credentialKind: "oauth",
90
+ tierRanking: { max: 0, team: 1, pro: 2, plus: 3, free: 4, unknown: 5 },
91
+ features: { circuitBreakers: false, concurrencyLimits: true, proactiveRotation: false },
92
+ runLogin: runCodexLogin,
93
+ validateCredentials: validateCodexCredentials,
94
+
95
+ hasValidCredentials(account): boolean {
96
+ const token = getCodexTokenState(account);
97
+ return Boolean((token.accessToken && token.tokenExpires > Date.now()) || getCodexRefreshToken(account.config));
98
+ },
99
+
100
+ async ensureValidToken(account): Promise<void> {
101
+ try {
102
+ await ensureCodexToken(account);
103
+ } catch (error) {
104
+ providerLog.log("warn", `Codex token refresh failed for ${account.config.email}: ${error instanceof Error ? error.message : "unknown error"}`);
105
+ throw error;
106
+ }
107
+ },
108
+
109
+ getAuthHeader(account): string {
110
+ const token = getCodexTokenState(account).accessToken;
111
+ return token ? `Bearer ${token}` : "Bearer";
112
+ },
113
+
114
+ shouldRetryOnQuotaExhaustion(): boolean { return true; },
115
+
116
+ async fetchQuota(account: AccountRuntime, ctx: QuotaFetchContext): Promise<void> {
117
+ await ensureCodexToken(account);
118
+ await fetchCodexQuota(account, ctx);
119
+ },
120
+
121
+ forwardRequest: forwardCodexRequest,
122
+ createStreamAccumulator: () => new CodexSseAccumulator(),
123
+
124
+ getKickstartModelForPool(): string | undefined { return undefined; },
125
+
126
+ getBenchmark() {
127
+ return {
128
+ body: {
129
+ project: "",
130
+ model: "gpt-5.6-luna",
131
+ request: { model: "gpt-5.6-luna", input: "Reply with one word.", stream: true, store: false },
132
+ },
133
+ parseUsage(raw: string) {
134
+ const usage = extractCodexUsage(raw);
135
+ return usage ? { outputTokens: usage.outputTokens } : null;
136
+ },
137
+ parseText(raw: string) {
138
+ return raw.slice(0, 1000);
139
+ },
140
+ };
141
+ },
142
+ };
@@ -0,0 +1,172 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { createInterface } from "node:readline/promises";
3
+ import { stdin as input, stdout as output } from "node:process";
4
+ import type { AccountConfig } from "../../types.js";
5
+ import {
6
+ buildCodexAuthorizationUrl,
7
+ codexOAuthErrorMessage,
8
+ createCodexAuthorizationFlow,
9
+ exchangeCodexAuthorizationCode,
10
+ getCodexOAuthConfig,
11
+ parseCodexIdentity,
12
+ startCodexCallbackServer,
13
+ type CodexTokens,
14
+ } from "./oauth.js";
15
+
16
+ function isRecord(value: unknown): value is Record<string, unknown> {
17
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18
+ }
19
+
20
+ function firstString(...values: unknown[]): string | undefined {
21
+ return values.find((value): value is string => typeof value === "string" && value.trim().length > 0)?.trim();
22
+ }
23
+
24
+ function tokenContainer(input: Record<string, unknown>): Record<string, unknown> {
25
+ const provider = isRecord(input["openai-codex"]) ? input["openai-codex"] : undefined;
26
+ const providers = isRecord(input.providers) && isRecord(input.providers["openai-codex"])
27
+ ? input.providers["openai-codex"]
28
+ : undefined;
29
+ const tokens = isRecord(input.tokens) ? input.tokens : undefined;
30
+ const providerTokens = provider && isRecord(provider.tokens) ? provider.tokens : undefined;
31
+ const nestedProviderTokens = providers && isRecord(providers.tokens) ? providers.tokens : undefined;
32
+ return {
33
+ ...input,
34
+ ...(provider ?? {}),
35
+ ...(providers ?? {}),
36
+ ...(tokens ?? {}),
37
+ ...(providerTokens ?? {}),
38
+ ...(nestedProviderTokens ?? {}),
39
+ };
40
+ }
41
+
42
+ export interface ParsedCodexAuth {
43
+ account: AccountConfig;
44
+ accessToken?: string;
45
+ idToken?: string;
46
+ }
47
+
48
+ /** Parse Codex CLI, pi-ai, Hermes and flat JSON exports without accepting raw CLI tokens. */
49
+ export function parseCodexAuthImport(input: unknown): ParsedCodexAuth {
50
+ if (!isRecord(input)) throw new Error("Invalid Codex auth import: expected a JSON object");
51
+ const data = tokenContainer(input);
52
+ const accessToken = firstString(data.access_token, data.accessToken, data.access, input.access_token);
53
+ const refreshToken = firstString(data.refresh_token, data.refreshToken, data.refresh, input.refresh_token);
54
+ if (!refreshToken) throw new Error("Invalid Codex auth import: refresh_token is required");
55
+ const idToken = firstString(data.id_token, data.idToken);
56
+ const identity = parseCodexIdentity(accessToken, idToken);
57
+ const email = firstString(
58
+ data.email,
59
+ data.account_email,
60
+ data.accountEmail,
61
+ input.email,
62
+ identity.email,
63
+ );
64
+ const providerAccountId = firstString(
65
+ data.providerAccountId,
66
+ data.account_id,
67
+ data.accountId,
68
+ data.chatgpt_account_id,
69
+ identity.providerAccountId,
70
+ );
71
+ if (!email && !providerAccountId) {
72
+ throw new Error("Invalid Codex auth import: email or ChatGPT account id is required");
73
+ }
74
+ const stableEmail = email ?? `${providerAccountId}@codex.local`;
75
+ return {
76
+ account: {
77
+ email: stableEmail,
78
+ label: stableEmail.split("@")[0],
79
+ credentials: [{
80
+ provider: "openai-codex",
81
+ refreshToken,
82
+ ...(providerAccountId ? { providerAccountId } : {}),
83
+ }],
84
+ },
85
+ ...(accessToken ? { accessToken } : {}),
86
+ ...(idToken ? { idToken } : {}),
87
+ };
88
+ }
89
+
90
+ export async function importCodexAuthFile(path: string): Promise<ParsedCodexAuth> {
91
+ let parsed: unknown;
92
+ try {
93
+ parsed = JSON.parse(await readFile(path, "utf8")) as unknown;
94
+ } catch {
95
+ throw new Error(`Could not read Codex auth import file: ${path}`);
96
+ }
97
+ return parseCodexAuthImport(parsed);
98
+ }
99
+
100
+ function parseCallbackInput(value: string): { code?: string; state?: string } {
101
+ const trimmed = value.trim();
102
+ if (!trimmed) return {};
103
+ try {
104
+ const url = new URL(trimmed);
105
+ return { code: url.searchParams.get("code") ?? undefined, state: url.searchParams.get("state") ?? undefined };
106
+ } catch {
107
+ // Continue with a pasted query string or code.
108
+ }
109
+ const params = new URLSearchParams(trimmed.startsWith("?") ? trimmed.slice(1) : trimmed);
110
+ if (params.has("code")) return { code: params.get("code") ?? undefined, state: params.get("state") ?? undefined };
111
+ return { code: trimmed };
112
+ }
113
+
114
+ export async function runCodexLogin(): Promise<AccountConfig> {
115
+ const config = getCodexOAuthConfig();
116
+ const flow = createCodexAuthorizationFlow(config);
117
+ console.log("Open this URL to authenticate with OpenAI Codex:");
118
+ console.log(flow.url);
119
+
120
+ let code: string | undefined;
121
+ let callback: Awaited<ReturnType<typeof startCodexCallbackServer>> | null = null;
122
+ try {
123
+ callback = await startCodexCallbackServer(flow.state, config);
124
+ const timeout = new Promise<null>((resolve) => {
125
+ const timer = setTimeout(() => resolve(null), 180_000);
126
+ timer.unref?.();
127
+ });
128
+ code = (await Promise.race([callback.waitForCode(), timeout])) ?? undefined;
129
+ } catch {
130
+ // Port conflicts are recoverable through the manual callback fallback.
131
+ } finally {
132
+ await callback?.close();
133
+ }
134
+
135
+ if (!code) {
136
+ const readline = createInterface({ input, output });
137
+ try {
138
+ const pasted = await readline.question("Paste the complete OAuth callback URL (or code): ");
139
+ const parsed = parseCallbackInput(pasted);
140
+ if (parsed.state && parsed.state !== flow.state) throw new Error("OAuth state mismatch");
141
+ code = parsed.code;
142
+ } finally {
143
+ readline.close();
144
+ }
145
+ }
146
+ if (!code) throw new Error("Codex OAuth timed out or returned no authorization code");
147
+
148
+ let tokens: CodexTokens;
149
+ try {
150
+ tokens = await exchangeCodexAuthorizationCode(code, flow.verifier, config);
151
+ } catch (error) {
152
+ throw new Error(codexOAuthErrorMessage(error), { cause: error });
153
+ }
154
+ const identity = parseCodexIdentity(tokens.accessToken, tokens.idToken);
155
+ const email = identity.email ?? (identity.providerAccountId ? `${identity.providerAccountId}@codex.local` : undefined);
156
+ if (!email) throw new Error("Codex OAuth did not return an account identity");
157
+ return {
158
+ email,
159
+ label: email.split("@")[0],
160
+ credentials: [{
161
+ provider: "openai-codex",
162
+ refreshToken: tokens.refreshToken,
163
+ ...(identity.providerAccountId ? { providerAccountId: identity.providerAccountId } : {}),
164
+ }],
165
+ };
166
+ }
167
+
168
+ export function codexLoginUrlForTests(): string {
169
+ const config = getCodexOAuthConfig();
170
+ const flow = createCodexAuthorizationFlow(config);
171
+ return buildCodexAuthorizationUrl(config, flow.state, "test");
172
+ }