File size: 13,602 Bytes
5d0a52f
 
 
 
 
 
0d2f54c
3d01305
 
5d0a52f
 
 
3d01305
5d0a52f
 
 
 
 
5f8456f
 
 
5d0a52f
 
 
 
 
 
 
7366e72
 
5d0a52f
 
ab2754a
 
5d0a52f
 
142c9c4
 
 
 
 
5d0a52f
142c9c4
5d0a52f
ab2754a
 
 
5d0a52f
 
 
 
 
 
 
 
 
 
 
 
4ebb914
5d0a52f
 
 
 
 
 
4ebb914
5d0a52f
 
 
 
 
4ebb914
5d0a52f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d01305
 
0d2f54c
 
 
 
 
5d0a52f
 
 
 
 
 
3d01305
5d0a52f
 
 
 
 
 
3d01305
 
 
347f81b
 
5d0a52f
3d01305
 
4ebb914
3d01305
 
 
 
5d0a52f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f8456f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ebb914
5f8456f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ebb914
5f8456f
 
 
 
 
 
5d0a52f
 
 
 
 
 
 
 
 
3d01305
0d2f54c
5d0a52f
 
 
 
 
 
 
ffcac87
3d01305
 
ffcac87
3d01305
 
 
 
0d2f54c
 
3d01305
0d2f54c
3d01305
 
b1107bc
3d01305
0d2f54c
b1107bc
0d2f54c
 
 
b1107bc
 
 
 
 
 
 
 
 
 
 
5d0a52f
0d2f54c
3d01305
5d0a52f
 
3d01305
 
 
0d2f54c
5d0a52f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6c3bb0
5d0a52f
cf0807a
5d0a52f
 
 
 
 
 
d6c3bb0
 
 
5d0a52f
 
 
 
 
 
cf0807a
 
 
 
5d0a52f
 
 
 
 
 
cf0807a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d0a52f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/**
 * CodexApi — client for the Codex Responses API.
 *
 * Endpoint: POST /backend-api/codex/responses
 * This is the API the Codex CLI actually uses.
 * It requires: instructions, store: false, stream: true.
 *
 * All upstream requests go through the TLS transport layer
 * (curl CLI or libcurl FFI) to avoid Cloudflare TLS fingerprinting.
 */

import { getConfig } from "../config.js";
import { getTransport } from "../tls/transport.js";
import {
  buildHeaders,
  buildHeadersWithContentType,
} from "../fingerprint/manager.js";
import type { CookieJar } from "./cookie-jar.js";
import type { BackendModelEntry } from "../models/model-store.js";

let _firstModelFetchLogged = false;

export interface CodexResponsesRequest {
  model: string;
  instructions: string;
  input: CodexInputItem[];
  stream: true;
  store: false;
  /** Optional: reasoning effort + summary mode */
  reasoning?: { effort?: string; summary?: string };
  /** Optional: tools available to the model */
  tools?: unknown[];
  /** Optional: tool choice strategy */
  tool_choice?: string | { type: string; name: string };
}

/** Structured content part for multimodal Codex input. */
export type CodexContentPart =
  | { type: "input_text"; text: string }
  | { type: "input_image"; image_url: string };

export type CodexInputItem =
  | { role: "user"; content: string | CodexContentPart[] }
  | { role: "assistant"; content: string }
  | { role: "system"; content: string }
  | { type: "function_call"; id?: string; call_id: string; name: string; arguments: string }
  | { type: "function_call_output"; call_id: string; output: string };

/** Parsed SSE event from the Codex Responses stream */
export interface CodexSSEEvent {
  event: string;
  data: unknown;
}

export class CodexApi {
  private token: string;
  private accountId: string | null;
  private cookieJar: CookieJar | null;
  private entryId: string | null;
  private proxyUrl: string | null | undefined;

  constructor(
    token: string,
    accountId: string | null,
    cookieJar?: CookieJar | null,
    entryId?: string | null,
    proxyUrl?: string | null,
  ) {
    this.token = token;
    this.accountId = accountId;
    this.cookieJar = cookieJar ?? null;
    this.entryId = entryId ?? null;
    this.proxyUrl = proxyUrl;
  }

  setToken(token: string): void {
    this.token = token;
  }

  /** Build headers with cookies injected. */
  private applyHeaders(headers: Record<string, string>): Record<string, string> {
    if (this.cookieJar && this.entryId) {
      const cookie = this.cookieJar.getCookieHeader(this.entryId);
      if (cookie) headers["Cookie"] = cookie;
    }
    return headers;
  }

  /** Capture Set-Cookie headers from transport response into the jar. */
  private captureCookies(setCookieHeaders: string[]): void {
    if (this.cookieJar && this.entryId && setCookieHeaders.length > 0) {
      this.cookieJar.captureRaw(this.entryId, setCookieHeaders);
    }
  }

  /**
   * Query official Codex usage/quota.
   * GET /backend-api/codex/usage
   */
  async getUsage(): Promise<CodexUsageResponse> {
    const config = getConfig();
    const transport = getTransport();
    const url = `${config.api.base_url}/codex/usage`;

    const headers = this.applyHeaders(
      buildHeaders(this.token, this.accountId),
    );
    headers["Accept"] = "application/json";
    // When transport lacks Chrome TLS fingerprint, downgrade Accept-Encoding
    // to encodings system curl can always decompress.
    if (!transport.isImpersonate()) {
      headers["Accept-Encoding"] = "gzip, deflate";
    }

    let body: string;
    try {
      const result = await transport.get(url, headers, 15, this.proxyUrl);
      body = result.body;
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      throw new CodexApiError(0, `transport GET failed: ${msg}`);
    }

    try {
      const parsed = JSON.parse(body) as CodexUsageResponse;
      // Validate we got actual usage data (not an error page)
      if (!parsed.rate_limit) {
        throw new CodexApiError(502, `Unexpected response: ${body.slice(0, 200)}`);
      }
      return parsed;
    } catch (e) {
      if (e instanceof CodexApiError) throw e;
      throw new CodexApiError(502, `Invalid JSON from /codex/usage: ${body.slice(0, 200)}`);
    }
  }

  /**
   * Fetch available models from the Codex backend.
   * Probes known endpoints; returns null if none respond.
   */
  async getModels(): Promise<BackendModelEntry[] | null> {
    const config = getConfig();
    const transport = getTransport();
    const baseUrl = config.api.base_url;

    // Endpoints to probe (most specific first)
    const endpoints = [
      `${baseUrl}/codex/models`,
      `${baseUrl}/models`,
      `${baseUrl}/sentinel/chat-requirements`,
    ];

    const headers = this.applyHeaders(
      buildHeaders(this.token, this.accountId),
    );
    headers["Accept"] = "application/json";
    if (!transport.isImpersonate()) {
      headers["Accept-Encoding"] = "gzip, deflate";
    }

    for (const url of endpoints) {
      try {
        const result = await transport.get(url, headers, 15, this.proxyUrl);
        const parsed = JSON.parse(result.body) as Record<string, unknown>;

        // sentinel/chat-requirements returns { chat_models: { models: [...], ... } }
        const sentinel = parsed.chat_models as Record<string, unknown> | undefined;
        const models = sentinel?.models ?? parsed.models ?? parsed.data ?? parsed.categories;
        if (Array.isArray(models) && models.length > 0) {
          console.log(`[CodexApi] getModels() found ${models.length} entries from ${url}`);
          if (!_firstModelFetchLogged) {
            console.log(`[CodexApi] Raw response keys: ${Object.keys(parsed).join(", ")}`);
            console.log(`[CodexApi] Raw model sample: ${JSON.stringify(models[0]).slice(0, 500)}`);
            if (models.length > 1) {
              console.log(`[CodexApi] Raw model sample[1]: ${JSON.stringify(models[1]).slice(0, 500)}`);
            }
            _firstModelFetchLogged = true;
          }
          // Flatten nested categories into a single list
          const flattened: BackendModelEntry[] = [];
          for (const item of models) {
            if (item && typeof item === "object") {
              const entry = item as Record<string, unknown>;
              if (Array.isArray(entry.models)) {
                for (const sub of entry.models as BackendModelEntry[]) {
                  flattened.push(sub);
                }
              } else {
                flattened.push(item as BackendModelEntry);
              }
            }
          }
          if (flattened.length > 0) {
            console.log(`[CodexApi] getModels() total after flatten: ${flattened.length} models`);
            return flattened;
          }
        }
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        console.log(`[CodexApi] Probe ${url} failed: ${msg}`);
        continue;
      }
    }

    return null;
  }

  /**
   * Probe a backend endpoint and return raw JSON (for debug).
   */
  async probeEndpoint(path: string): Promise<Record<string, unknown> | null> {
    const config = getConfig();
    const transport = getTransport();
    const url = `${config.api.base_url}${path}`;

    const headers = this.applyHeaders(
      buildHeaders(this.token, this.accountId),
    );
    headers["Accept"] = "application/json";
    if (!transport.isImpersonate()) {
      headers["Accept-Encoding"] = "gzip, deflate";
    }

    try {
      const result = await transport.get(url, headers, 15, this.proxyUrl);
      return JSON.parse(result.body) as Record<string, unknown>;
    } catch {
      return null;
    }
  }

  /**
   * Create a response (streaming).
   * Returns the raw Response so the caller can process the SSE stream.
   */
  async createResponse(
    request: CodexResponsesRequest,
    signal?: AbortSignal,
  ): Promise<Response> {
    const config = getConfig();
    const transport = getTransport();
    const baseUrl = config.api.base_url;
    const url = `${baseUrl}/codex/responses`;

    const headers = this.applyHeaders(
      buildHeadersWithContentType(this.token, this.accountId),
    );
    headers["Accept"] = "text/event-stream";

    // No wall-clock timeout for streaming SSE — header timeout + AbortSignal provide protection
    let transportRes;
    try {
      transportRes = await transport.post(url, headers, JSON.stringify(request), signal, undefined, this.proxyUrl);
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      throw new CodexApiError(0, msg);
    }

    // Capture cookies
    this.captureCookies(transportRes.setCookieHeaders);

    if (transportRes.status < 200 || transportRes.status >= 300) {
      // Read the body for error details (cap at 1MB to prevent memory spikes)
      const MAX_ERROR_BODY = 1024 * 1024; // 1MB
      const reader = transportRes.body.getReader();
      const chunks: Uint8Array[] = [];
      let totalSize = 0;
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        totalSize += value.byteLength;
        if (totalSize <= MAX_ERROR_BODY) {
          chunks.push(value);
        } else {
          const overshoot = totalSize - MAX_ERROR_BODY;
          if (value.byteLength > overshoot) {
            chunks.push(value.subarray(0, value.byteLength - overshoot));
          }
          reader.cancel();
          break;
        }
      }
      const errorBody = Buffer.concat(chunks).toString("utf-8");
      throw new CodexApiError(transportRes.status, errorBody);
    }

    return new Response(transportRes.body, {
      status: transportRes.status,
      headers: transportRes.headers,
    });
  }

  /**
   * Parse SSE stream from a Codex Responses API response.
   * Yields individual events.
   */
  async *parseStream(
    response: Response,
  ): AsyncGenerator<CodexSSEEvent> {
    if (!response.body) {
      throw new Error("Response body is null — cannot stream");
    }

    const reader = response.body
      .pipeThrough(new TextDecoderStream())
      .getReader();

    const MAX_SSE_BUFFER = 10 * 1024 * 1024; // 10MB
    let buffer = "";
    let yieldedAny = false;
    try {
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += value;
        if (buffer.length > MAX_SSE_BUFFER) {
          throw new Error(`SSE buffer exceeded ${MAX_SSE_BUFFER} bytes — aborting stream`);
        }
        const parts = buffer.split("\n\n");
        buffer = parts.pop()!;

        for (const part of parts) {
          if (!part.trim()) continue;
          const evt = this.parseSSEBlock(part);
          if (evt) {
            yieldedAny = true;
            yield evt;
          }
        }
      }

      // Process remaining buffer
      if (buffer.trim()) {
        const evt = this.parseSSEBlock(buffer);
        if (evt) {
          yieldedAny = true;
          yield evt;
        }
      }

      // Non-SSE response detection: if the entire stream yielded no SSE events
      // but has content, the upstream likely returned a plain JSON error body.
      if (!yieldedAny && buffer.trim()) {
        let errorMessage = buffer.trim();
        try {
          const parsed = JSON.parse(errorMessage) as Record<string, unknown>;
          const errObj = typeof parsed.error === "object" && parsed.error !== null
            ? (parsed.error as Record<string, unknown>)
            : undefined;
          errorMessage =
            (typeof parsed.detail === "string" ? parsed.detail : null)
            ?? (typeof errObj?.message === "string" ? errObj.message : null)
            ?? errorMessage;
        } catch { /* use raw text */ }
        yield {
          event: "error",
          data: { error: { type: "error", code: "non_sse_response", message: errorMessage } },
        };
      }
    } finally {
      reader.releaseLock();
    }
  }

  private parseSSEBlock(block: string): CodexSSEEvent | null {
    let event = "";
    const dataLines: string[] = [];

    for (const line of block.split("\n")) {
      if (line.startsWith("event:")) {
        event = line.slice(6).trim();
      } else if (line.startsWith("data:")) {
        dataLines.push(line.slice(5).trimStart());
      }
    }

    if (!event && dataLines.length === 0) return null;

    const raw = dataLines.join("\n");
    if (raw === "[DONE]") return null;

    let data: unknown;
    try {
      data = JSON.parse(raw);
    } catch {
      data = raw;
    }

    return { event, data };
  }
}

/** Response from GET /backend-api/codex/usage */
export interface CodexUsageRateWindow {
  used_percent: number;
  limit_window_seconds: number;
  reset_after_seconds: number;
  reset_at: number;
}

export interface CodexUsageRateLimit {
  allowed: boolean;
  limit_reached: boolean;
  primary_window: CodexUsageRateWindow | null;
  secondary_window: CodexUsageRateWindow | null;
}

export interface CodexUsageResponse {
  plan_type: string;
  rate_limit: CodexUsageRateLimit;
  code_review_rate_limit: CodexUsageRateLimit | null;
  credits: unknown;
  promo: unknown;
}

export class CodexApiError extends Error {
  constructor(
    public readonly status: number,
    public readonly body: string,
  ) {
    let detail: string;
    try {
      const parsed = JSON.parse(body);
      detail = parsed.detail ?? parsed.error?.message ?? body;
    } catch {
      detail = body;
    }
    super(`Codex API error (${status}): ${detail}`);
  }
}