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.
Files changed (42) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +20 -6
  3. package/package.json +1 -1
  4. package/src/account-store.ts +37 -5
  5. package/src/cli.ts +24 -3
  6. package/src/compat/model-specs.ts +1 -0
  7. package/src/compat.ts +540 -24
  8. package/src/config-normalize.ts +73 -30
  9. package/src/dashboard.ts +43 -42
  10. package/src/index.ts +1 -0
  11. package/src/onboarding.ts +349 -21
  12. package/src/providers/adapter.ts +18 -0
  13. package/src/providers/credential-helpers.ts +64 -0
  14. package/src/providers/google-antigravity/index.ts +9 -0
  15. package/src/providers/google-antigravity/quota.ts +2 -1
  16. package/src/providers/google-antigravity/translators.ts +83 -24
  17. package/src/providers/ollama/index.ts +8 -0
  18. package/src/providers/ollama/quota.ts +2 -1
  19. package/src/providers/openai-codex/catalog.ts +117 -0
  20. package/src/providers/openai-codex/compat.ts +556 -0
  21. package/src/providers/openai-codex/credentials.ts +82 -0
  22. package/src/providers/openai-codex/forward.ts +240 -0
  23. package/src/providers/openai-codex/index.ts +153 -0
  24. package/src/providers/openai-codex/login.ts +172 -0
  25. package/src/providers/openai-codex/oauth.ts +359 -0
  26. package/src/providers/openai-codex/quota.ts +231 -0
  27. package/src/providers/opencode-zen/catalog.ts +37 -0
  28. package/src/providers/opencode-zen/credentials.ts +31 -0
  29. package/src/providers/opencode-zen/forward.ts +214 -0
  30. package/src/providers/opencode-zen/index.ts +73 -0
  31. package/src/providers/opencode-zen/login.ts +81 -0
  32. package/src/providers/opencode-zen/quota.ts +67 -0
  33. package/src/providers/registry.ts +24 -5
  34. package/src/proxy.ts +75 -27
  35. package/src/rate-limit-parser.ts +2 -1
  36. package/src/rotator.ts +259 -48
  37. package/src/spend-logger.ts +2 -0
  38. package/src/static/dashboard-keys.js +152 -2
  39. package/src/static/dashboard.js +161 -37
  40. package/src/types.ts +83 -1
  41. package/src/validators.ts +11 -2
  42. package/tools/telemetry-receiver/receiver.js +14 -0
@@ -0,0 +1,556 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { Readable } from "node:stream";
3
+ import type { RequestBody } from "../../proxy.js";
4
+ import {
5
+ flattenHeaders,
6
+ type RotationAttemptContext,
7
+ type RotationOutcome,
8
+ withRotation,
9
+ } from "../../proxy.js";
10
+ import type { AccountRotator } from "../../rotator.js";
11
+ import type { OpenAIChatCompletionRequest, OpenAIResponsesRequest, CompatCompletion, OpenAIToolCall } from "../google-antigravity/translators.js";
12
+ import { buildRotatorResponseHeaders } from "../../response-headers.js";
13
+ import { logSpend } from "../../spend-logger.js";
14
+ import {
15
+ buildCodexPayload,
16
+ createCodexStreamAccumulator,
17
+ extractCodexUsage,
18
+ } from "./forward.js";
19
+ import { sanitizeCodexResponsesRequest } from "./forward.js";
20
+
21
+ function isRecord(value: unknown): value is Record<string, unknown> {
22
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23
+ }
24
+
25
+ function writeJson(res: ServerResponse, status: number, value: unknown, headers: Record<string, string> = {}): void {
26
+ res.writeHead(status, { "content-type": "application/json", ...headers });
27
+ res.end(JSON.stringify(value));
28
+ }
29
+
30
+ export interface CodexCompatOptions {
31
+ callType?: string;
32
+ apiKeyHash?: string | null;
33
+ requesterIp?: string | null;
34
+ rawRequest?: unknown;
35
+ }
36
+
37
+ function recordCodexTokenUsage(
38
+ rotator: AccountRotator,
39
+ model: string,
40
+ completion: CompatCompletion,
41
+ ): void {
42
+ if (completion.inputTokens > 0 || completion.outputTokens > 0) {
43
+ rotator.recordTokenUsage(model, completion.inputTokens, completion.outputTokens);
44
+ }
45
+ }
46
+
47
+ function recordCodexOutcome(
48
+ rotator: AccountRotator,
49
+ body: RequestBody,
50
+ context: RotationAttemptContext,
51
+ statusCode: number,
52
+ completion: CompatCompletion,
53
+ options?: CodexCompatOptions,
54
+ totalMs = Date.now() - context.requestStartMs,
55
+ ): void {
56
+ const ttfbMs = completion.firstByteMs ?? totalMs;
57
+ rotator.recordLatency(body.displayModel || body.model, ttfbMs, totalMs);
58
+ rotator.recordRequestLog({
59
+ model: context.displayModelKey,
60
+ account: context.label,
61
+ statusCode,
62
+ ttfbMs,
63
+ totalMs,
64
+ inputTokens: completion.inputTokens,
65
+ outputTokens: completion.outputTokens,
66
+ });
67
+ logSpend({
68
+ requestId: context.requestId,
69
+ apiKeyHash: options?.apiKeyHash || null,
70
+ model: context.displayModelKey,
71
+ accountEmail: context.label,
72
+ callType: options?.callType || "compat",
73
+ status: statusCode >= 200 && statusCode < 300 ? "success" : "failure",
74
+ promptTokens: completion.inputTokens,
75
+ completionTokens: completion.outputTokens,
76
+ totalTokens: completion.inputTokens + completion.outputTokens,
77
+ startTime: new Date(context.requestStartMs).toISOString(),
78
+ endTime: new Date().toISOString(),
79
+ ttfbMs,
80
+ durationMs: totalMs,
81
+ requestMessages: options?.rawRequest || body.request || body,
82
+ responseContent: completion.rawResponse || (completion.text ? { text: completion.text } : null),
83
+ requesterIp: options?.requesterIp || null,
84
+ });
85
+ }
86
+
87
+ function recordCodexFailure(
88
+ rotator: AccountRotator,
89
+ body: RequestBody,
90
+ outcome: RotationOutcome<CompatCompletion>,
91
+ options?: CodexCompatOptions,
92
+ ): void {
93
+ if (outcome.ok || !outcome.context) return;
94
+ recordCodexOutcome(
95
+ rotator,
96
+ body,
97
+ outcome.context,
98
+ outcome.status,
99
+ { text: "", inputTokens: 0, outputTokens: 0 },
100
+ options,
101
+ outcome.totalMs,
102
+ );
103
+ }
104
+
105
+ function messageContent(value: unknown): unknown {
106
+ if (typeof value === "string") return value;
107
+ if (!Array.isArray(value)) return value ?? "";
108
+ return value.map((part) => {
109
+ if (!isRecord(part)) return part;
110
+ if (part.type === "text" || part.type === "input_text") return { type: "input_text", text: part.text ?? "" };
111
+ if (part.type === "image_url" && isRecord(part.image_url)) return { type: "input_image", image_url: part.image_url.url };
112
+ return part;
113
+ });
114
+ }
115
+
116
+ function instructionText(value: unknown): string {
117
+ if (typeof value === "string") return value.trim();
118
+ if (!Array.isArray(value)) return "";
119
+ return value
120
+ .map((part) => {
121
+ if (typeof part === "string") return part;
122
+ return isRecord(part) && typeof part.text === "string" ? part.text : "";
123
+ })
124
+ .filter(Boolean)
125
+ .join("\n\n")
126
+ .trim();
127
+ }
128
+
129
+ /** Convert Chat Completions function tools to the Responses tool shape. */
130
+ function chatToolToResponsesTool(value: unknown): unknown {
131
+ if (!isRecord(value) || value.type !== "function" || !isRecord(value.function)) return value;
132
+ const fn = value.function;
133
+ const tool: Record<string, unknown> = {
134
+ type: "function",
135
+ name: fn.name,
136
+ };
137
+ for (const field of ["description", "parameters", "strict"]) {
138
+ if (fn[field] !== undefined) tool[field] = fn[field];
139
+ }
140
+ return tool;
141
+ }
142
+
143
+ function chatToolChoiceToResponsesChoice(value: unknown): unknown {
144
+ if (!isRecord(value) || value.type !== "function" || !isRecord(value.function)) return value;
145
+ return { type: "function", name: value.function.name };
146
+ }
147
+
148
+ /** Convert OpenAI Chat Completions messages into native Responses input items. */
149
+ export function chatToCodexResponsesRequest(request: OpenAIChatCompletionRequest): Record<string, unknown> {
150
+ const input: unknown[] = [];
151
+ const instructions: string[] = [];
152
+ for (const message of request.messages) {
153
+ const item = message as unknown as Record<string, unknown>;
154
+ const role = typeof item.role === "string" ? item.role : "user";
155
+ if (role === "system" || role === "developer") {
156
+ const text = instructionText(item.content);
157
+ if (text) instructions.push(text);
158
+ continue;
159
+ }
160
+ if (role === "tool") {
161
+ input.push({ type: "function_call_output", call_id: item.tool_call_id, output: String(item.content ?? "") });
162
+ continue;
163
+ }
164
+ if (Array.isArray(item.tool_calls)) {
165
+ for (const call of item.tool_calls) {
166
+ if (!isRecord(call) || !isRecord(call.function)) continue;
167
+ input.push({
168
+ type: "function_call",
169
+ call_id: call.id,
170
+ name: call.function.name,
171
+ arguments: typeof call.function.arguments === "string" ? call.function.arguments : JSON.stringify(call.function.arguments ?? {}),
172
+ });
173
+ }
174
+ if (!item.content) continue;
175
+ }
176
+ input.push({ role: role === "system" ? "developer" : role, content: messageContent(item.content) });
177
+ }
178
+ const result: Record<string, unknown> = {
179
+ model: request.model,
180
+ instructions: instructions.join("\n\n"),
181
+ input,
182
+ stream: true,
183
+ store: false,
184
+ };
185
+ if (Array.isArray(request.tools) && request.tools.length > 0) {
186
+ result.tools = request.tools.map(chatToolToResponsesTool);
187
+ }
188
+ if (request.tool_choice !== undefined) {
189
+ result.tool_choice = chatToolChoiceToResponsesChoice(request.tool_choice);
190
+ }
191
+ // The ChatGPT Codex OAuth endpoint rejects Responses' max_output_tokens
192
+ // field, so keep the request compatible with its native contract. The
193
+ // public Chat Completions limit cannot be represented on this endpoint.
194
+ const raw = request as unknown as Record<string, unknown>;
195
+ if (isRecord(raw.reasoning)) result.reasoning = raw.reasoning;
196
+ else if (typeof raw.reasoning_effort === "string") result.reasoning = { effort: raw.reasoning_effort };
197
+ return sanitizeCodexResponsesRequest(result, request.model);
198
+ }
199
+
200
+ export function parseCodexResponse(raw: string): CompatCompletion {
201
+ let parsed: Record<string, unknown> = {};
202
+ try { parsed = JSON.parse(raw) as Record<string, unknown>; } catch { /* stream-like response */ }
203
+ const output = Array.isArray(parsed.output) ? parsed.output : [];
204
+ let text = "";
205
+ let thinkingText = "";
206
+ const toolCalls: OpenAIToolCall[] = [];
207
+ for (const item of output) {
208
+ if (!isRecord(item)) continue;
209
+ if (item.type === "message" && Array.isArray(item.content)) {
210
+ for (const content of item.content) {
211
+ if (!isRecord(content)) continue;
212
+ if ((content.type === "output_text" || content.type === "text") && typeof content.text === "string") text += content.text;
213
+ if (content.type === "refusal" && typeof content.refusal === "string") text += content.refusal;
214
+ }
215
+ }
216
+ if (item.type === "reasoning" && Array.isArray(item.summary)) {
217
+ for (const summary of item.summary) if (isRecord(summary) && typeof summary.text === "string") thinkingText += summary.text;
218
+ }
219
+ if (item.type === "function_call") {
220
+ toolCalls.push({
221
+ id: typeof item.call_id === "string" ? item.call_id : `call_${toolCalls.length}`,
222
+ type: "function",
223
+ function: { name: typeof item.name === "string" ? item.name : "unknown", arguments: typeof item.arguments === "string" ? item.arguments : JSON.stringify(item.arguments ?? {}) },
224
+ });
225
+ }
226
+ }
227
+ if (!text && typeof parsed.output_text === "string") text = parsed.output_text;
228
+ const usage = extractCodexUsage(raw);
229
+ return {
230
+ text,
231
+ thinkingText: thinkingText || undefined,
232
+ inputTokens: usage?.inputTokens ?? 0,
233
+ outputTokens: usage?.outputTokens ?? 0,
234
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
235
+ rawResponse: parsed,
236
+ };
237
+ }
238
+
239
+ export function parseCodexResponseBody(raw: string): CompatCompletion {
240
+ const trimmed = raw.trim();
241
+ if (!trimmed.startsWith("event:") && !trimmed.startsWith("data:")) {
242
+ return parseCodexResponse(raw);
243
+ }
244
+ const accumulator = createCodexStreamAccumulator();
245
+ let eventName = "";
246
+ const toolCalls: OpenAIToolCall[] = [];
247
+ let completed: CompatCompletion | null = null;
248
+ for (const line of raw.split(/\r?\n/)) {
249
+ if (line.startsWith("event:")) {
250
+ eventName = line.slice(6).trim();
251
+ continue;
252
+ }
253
+ if (!line.startsWith("data:")) continue;
254
+ const payload = line.slice(5).trim();
255
+ if (!payload || payload === "[DONE]") continue;
256
+ let parsed: Record<string, unknown>;
257
+ try { parsed = JSON.parse(payload) as Record<string, unknown>; } catch { continue; }
258
+ const type = eventName || (typeof parsed.type === "string" ? parsed.type : "");
259
+ if (type === "response.completed" && isRecord(parsed.response)) {
260
+ completed = parseCodexResponse(JSON.stringify(parsed.response));
261
+ continue;
262
+ }
263
+ if (type === "response.output_item.added" && isRecord(parsed.item) && parsed.item.type === "function_call") {
264
+ const item = parsed.item;
265
+ toolCalls.push({
266
+ id: typeof item.call_id === "string" ? item.call_id : `call_${toolCalls.length}`,
267
+ type: "function",
268
+ function: {
269
+ name: typeof item.name === "string" ? item.name : "unknown",
270
+ arguments: "",
271
+ },
272
+ });
273
+ continue;
274
+ }
275
+ if (type === "response.output_item.done" && isRecord(parsed.item) && parsed.item.type === "function_call") {
276
+ const item = parsed.item;
277
+ const call = toolCalls.find((candidate) => candidate.id === item.call_id);
278
+ if (call) {
279
+ if (typeof item.name === "string") call.function.name = item.name;
280
+ if (typeof item.arguments === "string") call.function.arguments = item.arguments;
281
+ }
282
+ continue;
283
+ }
284
+ if (type === "response.function_call_arguments.delta" && typeof parsed.delta === "string") {
285
+ const call = toolCalls.at(-1);
286
+ if (call) call.function.arguments += parsed.delta;
287
+ continue;
288
+ }
289
+ if (type === "response.output_text.delta" && typeof parsed.delta === "string") {
290
+ accumulator.append(`data: ${JSON.stringify({ delta: parsed.delta })}\n`);
291
+ }
292
+ }
293
+ if (completed) {
294
+ if (toolCalls.length > 0 && !completed.toolCalls) completed.toolCalls = toolCalls;
295
+ if (!completed.text) completed.text = accumulator.getText();
296
+ return completed;
297
+ }
298
+ const usage = extractCodexUsage(raw);
299
+ return {
300
+ text: accumulator.getText(),
301
+ inputTokens: usage?.inputTokens ?? 0,
302
+ outputTokens: usage?.outputTokens ?? 0,
303
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
304
+ rawResponse: {},
305
+ };
306
+ }
307
+
308
+ function codexResponseJson(
309
+ completion: CompatCompletion,
310
+ model: string,
311
+ ): Record<string, unknown> {
312
+ const id = `resp-${Date.now().toString(36)}`;
313
+ const output: unknown[] = [];
314
+ if (completion.text || !completion.toolCalls?.length) {
315
+ output.push({
316
+ id: `${id}-msg`,
317
+ type: "message",
318
+ status: "completed",
319
+ role: "assistant",
320
+ content: [
321
+ {
322
+ type: "output_text",
323
+ text: completion.text,
324
+ annotations: [],
325
+ },
326
+ ],
327
+ });
328
+ }
329
+ for (const call of completion.toolCalls ?? []) {
330
+ output.push({
331
+ id: call.id,
332
+ type: "function_call",
333
+ call_id: call.id,
334
+ name: call.function.name,
335
+ arguments: call.function.arguments,
336
+ status: "completed",
337
+ });
338
+ }
339
+ return {
340
+ id,
341
+ object: "response",
342
+ created_at: Math.floor(Date.now() / 1000),
343
+ status: "completed",
344
+ model,
345
+ output,
346
+ output_text: completion.text,
347
+ usage: {
348
+ input_tokens: completion.inputTokens,
349
+ output_tokens: completion.outputTokens,
350
+ total_tokens: completion.inputTokens + completion.outputTokens,
351
+ },
352
+ };
353
+ }
354
+
355
+ function upstreamHeaders(response: Response, context: { account?: { healthScore: number }; requestStartMs: number; label: string; retries: number }, model: string): Record<string, string> {
356
+ const headers: Record<string, string> = {};
357
+ response.headers.forEach((value, key) => {
358
+ if (key !== "connection" && key !== "transfer-encoding" && key !== "content-length") headers[key] = value;
359
+ });
360
+ Object.assign(headers, buildRotatorResponseHeaders({
361
+ accountLabel: context.label,
362
+ model,
363
+ ttfbMs: Date.now() - context.requestStartMs,
364
+ healthScore: context.account?.healthScore,
365
+ retries: context.retries,
366
+ routingPolicy: "timer-first",
367
+ }));
368
+ return headers;
369
+ }
370
+
371
+ async function pipeNativeResponses(
372
+ response: Response,
373
+ req: IncomingMessage,
374
+ res: ServerResponse,
375
+ context: { account?: { healthScore: number }; requestStartMs: number; label: string; retries: number },
376
+ model: string,
377
+ ): Promise<CompatCompletion> {
378
+ res.writeHead(response.status, upstreamHeaders(response, context, model));
379
+ if (!response.body) {
380
+ res.end();
381
+ return { text: "", inputTokens: 0, outputTokens: 0 };
382
+ }
383
+ const stream = Readable.fromWeb(response.body as import("node:stream/web").ReadableStream);
384
+ const accumulator = createCodexStreamAccumulator();
385
+ const streamStartMs = Date.now();
386
+ let firstByteMs: number | undefined;
387
+ const close = (): void => { if (!stream.destroyed) stream.destroy(); };
388
+ req.once("close", close);
389
+ try {
390
+ for await (const chunk of stream) {
391
+ if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
392
+ accumulator.append(chunk.toString());
393
+ if (!res.writableEnded) res.write(chunk);
394
+ }
395
+ } finally {
396
+ req.off("close", close);
397
+ if (!res.writableEnded) res.end();
398
+ }
399
+ const usage = accumulator.final();
400
+ return {
401
+ text: accumulator.getText(),
402
+ inputTokens: usage?.inputTokens ?? 0,
403
+ outputTokens: usage?.outputTokens ?? 0,
404
+ firstByteMs,
405
+ };
406
+ }
407
+
408
+ function emitChatChunk(res: ServerResponse, model: string, id: string, delta: Record<string, unknown>, finishReason: string | null = null, usage?: Record<string, number>): void {
409
+ res.write(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta, finish_reason: finishReason }], ...(usage ? { usage } : {}) })}\n\n`);
410
+ }
411
+
412
+ async function pipeCodexAsChat(
413
+ response: Response,
414
+ req: IncomingMessage,
415
+ res: ServerResponse,
416
+ model: string,
417
+ context: { account?: { healthScore: number }; requestStartMs: number; label: string; retries: number },
418
+ ): Promise<CompatCompletion> {
419
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive", ...upstreamHeaders(response, context, model) });
420
+ const id = `chatcmpl-${Date.now().toString(36)}`;
421
+ emitChatChunk(res, model, id, { role: "assistant" });
422
+ if (!response.body) {
423
+ emitChatChunk(res, model, id, {}, "stop");
424
+ res.end("data: [DONE]\n\n");
425
+ return { text: "", inputTokens: 0, outputTokens: 0 };
426
+ }
427
+ const stream = Readable.fromWeb(response.body as import("node:stream/web").ReadableStream);
428
+ let buffer = "";
429
+ let eventName = "";
430
+ let inputTokens = 0;
431
+ let outputTokens = 0;
432
+ let toolIndex = 0;
433
+ const streamStartMs = Date.now();
434
+ let firstByteMs: number | undefined;
435
+ const close = (): void => { if (!stream.destroyed) stream.destroy(); };
436
+ req.once("close", close);
437
+ const handle = (payload: string, event: string): void => {
438
+ let data: Record<string, unknown>;
439
+ try { data = JSON.parse(payload) as Record<string, unknown>; } catch { return; }
440
+ const delta = typeof data.delta === "string" ? data.delta : "";
441
+ if (event === "response.output_text.delta" && delta) emitChatChunk(res, model, id, { content: delta });
442
+ if (event === "response.reasoning_summary_text.delta" && delta) emitChatChunk(res, model, id, { reasoning_content: delta });
443
+ if (event === "response.output_item.added" && isRecord(data.item) && data.item.type === "function_call") {
444
+ const item = data.item;
445
+ emitChatChunk(res, model, id, { tool_calls: [{ index: toolIndex, id: item.call_id, type: "function", function: { name: item.name, arguments: "" } }] });
446
+ toolIndex++;
447
+ }
448
+ if (event === "response.function_call_arguments.delta" && delta) emitChatChunk(res, model, id, { tool_calls: [{ index: Math.max(0, toolIndex - 1), function: { arguments: delta } }] });
449
+ if (event === "response.completed" && isRecord(data.response)) {
450
+ const usage = extractCodexUsage(JSON.stringify(data.response));
451
+ inputTokens = usage?.inputTokens ?? inputTokens;
452
+ outputTokens = usage?.outputTokens ?? outputTokens;
453
+ }
454
+ };
455
+ try {
456
+ for await (const chunk of stream) {
457
+ if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
458
+ buffer += chunk.toString();
459
+ let newline = buffer.indexOf("\n");
460
+ while (newline >= 0) {
461
+ const line = buffer.slice(0, newline).replace(/\r$/, "");
462
+ buffer = buffer.slice(newline + 1);
463
+ if (line.startsWith("event:")) eventName = line.slice(6).trim();
464
+ else if (line.startsWith("data:")) handle(line.slice(5).trim(), eventName);
465
+ newline = buffer.indexOf("\n");
466
+ }
467
+ }
468
+ } finally { req.off("close", close); }
469
+ emitChatChunk(res, model, id, {}, toolIndex > 0 ? "tool_calls" : "stop");
470
+ if (inputTokens > 0 || outputTokens > 0) emitChatChunk(res, model, id, {}, null, { prompt_tokens: inputTokens, completion_tokens: outputTokens, total_tokens: inputTokens + outputTokens });
471
+ res.end("data: [DONE]\n\n");
472
+ return { text: "", inputTokens, outputTokens, firstByteMs };
473
+ }
474
+
475
+ export async function serveCodexResponses(
476
+ req: IncomingMessage,
477
+ res: ServerResponse,
478
+ rotator: AccountRotator,
479
+ request: OpenAIResponsesRequest,
480
+ options?: CodexCompatOptions,
481
+ ): Promise<void> {
482
+ const body: RequestBody = { project: "", model: request.model, request: buildCodexPayload({ project: "", model: request.model, request }) };
483
+ const controller = new AbortController();
484
+ const abort = (): void => controller.abort();
485
+ req.once("aborted", abort);
486
+ res.once("close", abort);
487
+ try {
488
+ const outcome = await withRotation(rotator, request.model, flattenHeaders(req.headers), body, async (response, context) => {
489
+ if (request.stream) {
490
+ const completion = await pipeNativeResponses(response, req, res, context, request.model);
491
+ recordCodexTokenUsage(rotator, request.model, completion);
492
+ recordCodexOutcome(rotator, body, context, response.status, completion, options);
493
+ return completion;
494
+ }
495
+ const raw = await response.text();
496
+ const headers = upstreamHeaders(response, context, request.model);
497
+ const completion = parseCodexResponseBody(raw);
498
+ const responseBody = raw.trim().startsWith("{")
499
+ ? JSON.parse(raw) as unknown
500
+ : codexResponseJson(completion, request.model);
501
+ writeJson(res, response.status, responseBody, headers);
502
+ recordCodexTokenUsage(rotator, request.model, completion);
503
+ recordCodexOutcome(rotator, body, context, response.status, completion, options);
504
+ return completion;
505
+ }, controller.signal);
506
+ recordCodexFailure(rotator, body, outcome, options);
507
+ if (!outcome.ok && !res.headersSent) writeJson(res, outcome.status, { error: { message: outcome.errorText, type: "upstream_error" } });
508
+ } finally {
509
+ req.off("aborted", abort);
510
+ res.off("close", abort);
511
+ }
512
+ }
513
+
514
+ export async function serveCodexChat(
515
+ req: IncomingMessage,
516
+ res: ServerResponse,
517
+ rotator: AccountRotator,
518
+ request: OpenAIChatCompletionRequest,
519
+ options?: CodexCompatOptions,
520
+ ): Promise<void> {
521
+ const codexRequest = chatToCodexResponsesRequest(request);
522
+ const body: RequestBody = { project: "", model: request.model, request: codexRequest };
523
+ const controller = new AbortController();
524
+ const abort = (): void => controller.abort();
525
+ req.once("aborted", abort);
526
+ res.once("close", abort);
527
+ try {
528
+ const outcome = await withRotation(rotator, request.model, flattenHeaders(req.headers), body, async (response, context) => {
529
+ if (request.stream) {
530
+ const completion = await pipeCodexAsChat(response, req, res, request.model, context);
531
+ recordCodexTokenUsage(rotator, request.model, completion);
532
+ recordCodexOutcome(rotator, body, context, response.status, completion, options);
533
+ return completion;
534
+ }
535
+ const raw = await response.text();
536
+ const completion = parseCodexResponseBody(raw);
537
+ const hasTools = Boolean(completion.toolCalls?.length);
538
+ writeJson(res, response.status, {
539
+ id: `chatcmpl-${Date.now().toString(36)}`,
540
+ object: "chat.completion",
541
+ created: Math.floor(Date.now() / 1000),
542
+ model: request.model,
543
+ choices: [{ index: 0, message: { role: "assistant", content: hasTools ? null : completion.text, ...(hasTools ? { tool_calls: completion.toolCalls } : {}), ...(completion.thinkingText ? { reasoning_content: completion.thinkingText } : {}) }, finish_reason: hasTools ? "tool_calls" : "stop" }],
544
+ usage: { prompt_tokens: completion.inputTokens, completion_tokens: completion.outputTokens, total_tokens: completion.inputTokens + completion.outputTokens },
545
+ }, upstreamHeaders(response, context, request.model));
546
+ recordCodexTokenUsage(rotator, request.model, completion);
547
+ recordCodexOutcome(rotator, body, context, response.status, completion, options);
548
+ return completion;
549
+ }, controller.signal);
550
+ recordCodexFailure(rotator, body, outcome, options);
551
+ if (!outcome.ok && !res.headersSent) writeJson(res, outcome.status, { error: { message: outcome.errorText, type: "upstream_error" } });
552
+ } finally {
553
+ req.off("aborted", abort);
554
+ res.off("close", abort);
555
+ }
556
+ }
@@ -0,0 +1,82 @@
1
+ import type { AccountConfig, AccountRuntime, ProviderCredential } from "../../types.js";
2
+ import { loadConfig, saveAccountsConfig } from "../../config-storage.js";
3
+ import { getCredential } from "../credential-helpers.js";
4
+ import { CODEX_PROVIDER_ID } from "./oauth.js";
5
+
6
+ export interface ProviderTokenState {
7
+ accessToken: string | null;
8
+ tokenExpires: number;
9
+ }
10
+
11
+ export function getCodexCredential(account: AccountConfig): ProviderCredential | undefined {
12
+ return getCredential(account, CODEX_PROVIDER_ID) as ProviderCredential | undefined;
13
+ }
14
+
15
+ export function getCodexRefreshToken(account: AccountConfig): string | undefined {
16
+ const value = getCodexCredential(account)?.refreshToken;
17
+ return typeof value === "string" && value.trim() ? value : undefined;
18
+ }
19
+
20
+ export function getCodexAccountId(account: AccountConfig): string | undefined {
21
+ const value = getCodexCredential(account)?.providerAccountId;
22
+ return typeof value === "string" && value.trim() ? value : undefined;
23
+ }
24
+
25
+ export function getCodexTokenState(account: AccountRuntime): ProviderTokenState {
26
+ return account.providerTokens?.[CODEX_PROVIDER_ID] ?? {
27
+ accessToken: null,
28
+ tokenExpires: 0,
29
+ };
30
+ }
31
+
32
+ export function setCodexTokenState(account: AccountRuntime, state: ProviderTokenState): void {
33
+ account.providerTokens ??= {};
34
+ account.providerTokens[CODEX_PROVIDER_ID] = state;
35
+ }
36
+
37
+ /**
38
+ * Persist a rotated refresh token in the same atomic settings transaction as
39
+ * the rest of accounts.json. The per-account lock prevents two requests from
40
+ * writing different generations of a one-time refresh token out of order.
41
+ */
42
+ const persistenceLocks = new Map<string, Promise<void>>();
43
+
44
+ export async function persistCodexRefreshToken(
45
+ account: AccountRuntime,
46
+ refreshToken: string,
47
+ ): Promise<void> {
48
+ await persistCodexCredentialRefresh(loadConfig(), account, refreshToken);
49
+ }
50
+
51
+ /** Persist one credential while preserving every sibling account/provider. */
52
+ export async function persistCodexCredentialRefresh(
53
+ config: Parameters<typeof saveAccountsConfig>[0],
54
+ account: AccountRuntime,
55
+ refreshToken: string,
56
+ ): Promise<void> {
57
+ const email = account.config.email.toLowerCase();
58
+ const previous = persistenceLocks.get(email) ?? Promise.resolve();
59
+ const next = previous.catch(() => undefined).then(async () => {
60
+ const accountConfig = config.accounts.find(
61
+ (entry) => entry.email.toLowerCase() === email,
62
+ );
63
+ if (!accountConfig) throw new Error("Codex account disappeared while refreshing");
64
+ const credentials = [...(accountConfig.credentials ?? account.config.credentials ?? [])];
65
+ const index = credentials.findIndex((entry) => entry.provider === CODEX_PROVIDER_ID);
66
+ if (index < 0) throw new Error("Codex credential is no longer present; re-authenticate");
67
+ credentials[index] = { ...credentials[index], refreshToken };
68
+ accountConfig.credentials = credentials;
69
+ account.config.credentials = credentials;
70
+ await saveAccountsConfig(config);
71
+ });
72
+ persistenceLocks.set(email, next);
73
+ try {
74
+ await next;
75
+ } finally {
76
+ if (persistenceLocks.get(email) === next) persistenceLocks.delete(email);
77
+ }
78
+ }
79
+
80
+ export function isCodexCredential(config: AccountConfig): boolean {
81
+ return Boolean(getCodexRefreshToken(config));
82
+ }