File size: 8,281 Bytes
5d0a52f
 
 
 
 
 
0d2f54c
3d01305
 
5d0a52f
 
 
3d01305
5d0a52f
 
 
 
d07b5c0
0c8b3c0
 
 
5d0a52f
5f8456f
 
0c8b3c0
 
 
 
 
 
 
 
 
 
5d0a52f
0c8b3c0
 
142c9c4
0c8b3c0
 
 
 
 
 
5d0a52f
 
 
 
 
 
4ebb914
5d0a52f
 
 
 
 
 
4ebb914
5d0a52f
 
 
 
 
4ebb914
5d0a52f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d01305
 
0d2f54c
 
 
 
 
0c8b3c0
5d0a52f
 
 
 
0c8b3c0
5d0a52f
 
0c8b3c0
5f8456f
 
 
 
0c8b3c0
5f8456f
 
0c8b3c0
5f8456f
 
 
 
0c8b3c0
5f8456f
 
5d0a52f
 
d07b5c0
 
5d0a52f
 
 
 
d07b5c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c8b3c0
d07b5c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c8b3c0
d07b5c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c8b3c0
d07b5c0
 
 
 
5d0a52f
 
3d01305
0d2f54c
5d0a52f
 
 
 
 
 
44b20f4
 
d07b5c0
 
5d0a52f
3d01305
 
44b20f4
3d01305
 
 
 
0d2f54c
3d01305
0d2f54c
3d01305
0c8b3c0
3d01305
0d2f54c
b1107bc
0d2f54c
 
 
b1107bc
 
 
 
 
 
 
 
 
 
 
5d0a52f
0d2f54c
3d01305
5d0a52f
 
3d01305
 
 
0d2f54c
5d0a52f
 
 
 
0c8b3c0
5d0a52f
0c8b3c0
 
5d0a52f
 
 
0c8b3c0
 
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
/**
 * 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 { createWebSocketResponse, type WsCreateRequest } from "./ws-transport.js";
import { parseSSEBlock, parseSSEStream } from "./codex-sse.js";
import { fetchUsage } from "./codex-usage.js";
import { fetchModels, probeEndpoint as probeEndpointFn } from "./codex-models.js";
import type { CookieJar } from "./cookie-jar.js";
import type { BackendModelEntry } from "../models/model-store.js";

// Re-export types from codex-types.ts for backward compatibility
export type {
  CodexResponsesRequest,
  CodexContentPart,
  CodexInputItem,
  CodexSSEEvent,
  CodexUsageRateWindow,
  CodexUsageRateLimit,
  CodexUsageResponse,
} from "./codex-types.js";

// Re-export SSE utilities for consumers that used them via CodexApi
export { parseSSEBlock, parseSSEStream } from "./codex-sse.js";

import {
  CodexApiError,
  type CodexResponsesRequest,
  type CodexSSEEvent,
  type CodexUsageResponse,
} from "./codex-types.js";

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. Delegates to standalone fetchUsage(). */
  async getUsage(): Promise<CodexUsageResponse> {
    const headers = this.applyHeaders(
      buildHeaders(this.token, this.accountId),
    );
    return fetchUsage(headers, this.proxyUrl);
  }

  /** Fetch available models from the Codex backend. Probes known endpoints; returns null if none respond. */
  async getModels(): Promise<BackendModelEntry[] | null> {
    const headers = this.applyHeaders(
      buildHeaders(this.token, this.accountId),
    );
    return fetchModels(headers, this.proxyUrl);
  }

  /** Probe a backend endpoint and return raw JSON (for debug). */
  async probeEndpoint(path: string): Promise<Record<string, unknown> | null> {
    const headers = this.applyHeaders(
      buildHeaders(this.token, this.accountId),
    );
    return probeEndpointFn(path, headers, this.proxyUrl);
  }

  /**
   * Create a response (streaming).
   * Routes to WebSocket when previous_response_id is present (HTTP SSE doesn't support it).
   * Falls back to HTTP SSE if WebSocket fails.
   */
  async createResponse(
    request: CodexResponsesRequest,
    signal?: AbortSignal,
  ): Promise<Response> {
    if (request.useWebSocket) {
      try {
        return await this.createResponseViaWebSocket(request, signal);
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        console.warn(`[CodexApi] WebSocket failed (${msg}), falling back to HTTP SSE`);
        const { previous_response_id: _, useWebSocket: _ws, ...httpRequest } = request;
        return this.createResponseViaHttp(httpRequest as CodexResponsesRequest, signal);
      }
    }
    return this.createResponseViaHttp(request, signal);
  }

  /**
   * Create a response via WebSocket (for previous_response_id support).
   * Returns a Response with SSE-formatted body, compatible with parseStream().
   * No Content-Type header — WebSocket upgrade handles auth via same headers.
   */
  private async createResponseViaWebSocket(
    request: CodexResponsesRequest,
    signal?: AbortSignal,
  ): Promise<Response> {
    const config = getConfig();
    const baseUrl = config.api.base_url;
    const wsUrl = baseUrl.replace(/^https?:/, "wss:") + "/codex/responses";

    const headers = this.applyHeaders(
      buildHeaders(this.token, this.accountId),
    );
    headers["OpenAI-Beta"] = "responses_websockets=2026-02-06";
    headers["x-openai-internal-codex-residency"] = "us";

    const wsRequest: WsCreateRequest = {
      type: "response.create",
      model: request.model,
      instructions: request.instructions ?? "",
      input: request.input,
    };
    if (request.previous_response_id) {
      wsRequest.previous_response_id = request.previous_response_id;
    }
    if (request.reasoning) wsRequest.reasoning = request.reasoning;
    if (request.tools?.length) wsRequest.tools = request.tools;
    if (request.tool_choice) wsRequest.tool_choice = request.tool_choice;
    if (request.text) wsRequest.text = request.text;

    return createWebSocketResponse(wsUrl, headers, wsRequest, signal, this.proxyUrl);
  }

  /**
   * Create a response via HTTP SSE (default transport).
   * Uses curl-impersonate for TLS fingerprinting.
   * No wall-clock timeout — header timeout + AbortSignal provide protection.
   */
  private async createResponseViaHttp(
    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";
    headers["OpenAI-Beta"] = "responses_websockets=2026-02-06";

    const { service_tier: _st, previous_response_id: _pid, useWebSocket: _ws, ...bodyFields } = request;
    const body = JSON.stringify(bodyFields);

    let transportRes;
    try {
      transportRes = await transport.post(url, headers, body, signal, undefined, this.proxyUrl);
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      throw new CodexApiError(0, msg);
    }

    this.captureCookies(transportRes.setCookieHeaders);

    if (transportRes.status < 200 || transportRes.status >= 300) {
      const MAX_ERROR_BODY = 1024 * 1024;
      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.
   * Delegates to the standalone parseSSEStream() function.
   */
  async *parseStream(response: Response): AsyncGenerator<CodexSSEEvent> {
    yield* parseSSEStream(response);
  }
}

// Re-export CodexApiError for backward compatibility
export { CodexApiError } from "./codex-types.js";