Skip to content

Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy

Rust

initial bun proxy scaffold

Raine Virta9f649ae10275
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..c2658d7
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+node_modules/
diff --git a/bun.lock b/bun.lock
new file mode 100644
index 0000000..e594201
--- /dev/null
+++ b/bun.lock
@@ -0,0 +1,29 @@
+{
+ "lockfileVersion": 1,
+ "configVersion": 1,
+ "workspaces": {
+ "": {
+ "name": "claude-code-chatgpt-proxy",
+ "dependencies": {
+ "gpt-tokenizer": "^2.9.0",
+ },
+ "devDependencies": {
+ "@types/bun": "latest",
+ "typescript": "^5.6.0",
+ },
+ },
+ },
+ "packages": {
+ "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.12" } }, "sha512-DBv81elK+/VSwXHDlnH3Qduw+KxkTIWi7TXkAeh24zpi5l0B2kUg9Ga3tb4nJaPcOFswflgi/yAvMVBPrxMB+A=="],
+
+ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.19.0" } }, "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ=="],
+
+ "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-HqOLj5PoFajAQciOMRiIZGNoKxDJSr6qigAttOX40vJuSp6DN/CxWp9s3C1Xwm4oH7ybueITwiaOcWXoYVoRkA=="],
+
+ "gpt-tokenizer": ["[email protected]", "", {}, "sha512-YSpexBL/k4bfliAzMrRqn3M6+it02LutVyhVpDeMKrC/O9+pCe/5s8U2hYKa2vFLD5/vHhsKc8sOn/qGqII8Kg=="],
+
+ "typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
+
+ "undici-types": ["[email protected]", "", {}, "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg=="],
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..d8a07e7
--- /dev/null
+++ b/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "claude-code-chatgpt-proxy",
+ "version": "0.0.1",
+ "private": true,
+ "type": "module",
+ "bin": {
+ "ccxp": "./src/cli.ts"
+ },
+ "scripts": {
+ "start": "bun run src/cli.ts serve",
+ "auth": "bun run src/cli.ts auth login",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "gpt-tokenizer": "^2.9.0"
+ },
+ "devDependencies": {
+ "@types/bun": "latest",
+ "typescript": "^5.6.0"
+ }
+}
diff --git a/src/anthropic/schema.ts b/src/anthropic/schema.ts
new file mode 100644
index 0000000..a8d784a
--- /dev/null
+++ b/src/anthropic/schema.ts
@@ -0,0 +1,62 @@
+export interface AnthropicTextBlock {
+ type: "text"
+ text: string
+ cache_control?: { type: "ephemeral" }
+}
+
+export interface AnthropicImageBlock {
+ type: "image"
+ source:
+ | { type: "base64"; media_type: string; data: string }
+ | { type: "url"; url: string }
+}
+
+export interface AnthropicToolUseBlock {
+ type: "tool_use"
+ id: string
+ name: string
+ input: unknown
+}
+
+export interface AnthropicToolResultBlock {
+ type: "tool_result"
+ tool_use_id: string
+ content: string | Array<AnthropicTextBlock | AnthropicImageBlock>
+ is_error?: boolean
+}
+
+export type AnthropicContentBlock =
+ | AnthropicTextBlock
+ | AnthropicImageBlock
+ | AnthropicToolUseBlock
+ | AnthropicToolResultBlock
+
+export interface AnthropicMessage {
+ role: "user" | "assistant"
+ content: string | AnthropicContentBlock[]
+}
+
+export interface AnthropicTool {
+ name: string
+ description?: string
+ input_schema: unknown
+}
+
+export interface AnthropicRequest {
+ model: string
+ messages: AnthropicMessage[]
+ system?: string | AnthropicTextBlock[]
+ tools?: AnthropicTool[]
+ tool_choice?: { type: "auto" | "any" | "tool" | "none"; name?: string }
+ max_tokens?: number
+ temperature?: number
+ top_p?: number
+ stream?: boolean
+ thinking?: { type: string; [k: string]: unknown }
+ output_config?: {
+ effort?: "low" | "medium" | "high"
+ format?: { type: "json_schema"; schema: unknown; name?: string }
+ }
+ context_management?: unknown
+ metadata?: unknown
+}
diff --git a/src/auth/constants.ts b/src/auth/constants.ts
new file mode 100644
index 0000000..1daf900
--- /dev/null
+++ b/src/auth/constants.ts
@@ -0,0 +1,7 @@
+export const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"
+export const ISSUER = "https://auth.openai.com"
+export const CODEX_API_ENDPOINT = "https://chatgpt.com/backend-api/codex/responses"
+export const OAUTH_PORT = 1455
+export const OAUTH_REDIRECT_URI = `http://localhost:${OAUTH_PORT}/auth/callback`
+export const ORIGINATOR = "codex-tui"
+export const REFRESH_MARGIN_MS = 5 * 60 * 1000
diff --git a/src/auth/device.ts b/src/auth/device.ts
new file mode 100644
index 0000000..21d815c
--- /dev/null
+++ b/src/auth/device.ts
@@ -0,0 +1,52 @@
+import { CLIENT_ID, ISSUER } from "./constants.ts"
+import type { TokenResponse } from "./jwt.ts"
+
+const POLL_SAFETY_MARGIN_MS = 3000
+
+export async function runDeviceLogin(): Promise<TokenResponse> {
+ const init = await fetch(`${ISSUER}/api/accounts/deviceauth/usercode`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ client_id: CLIENT_ID }),
+ })
+ if (!init.ok) throw new Error(`Device init failed: ${init.status}`)
+ const data = (await init.json()) as {
+ device_auth_id: string
+ user_code: string
+ interval: string
+ }
+ const intervalMs = Math.max(parseInt(data.interval) || 5, 1) * 1000
+
+ console.log(`\nVisit: ${ISSUER}/codex/device\nEnter code: ${data.user_code}\n`)
+
+ while (true) {
+ const resp = await fetch(`${ISSUER}/api/accounts/deviceauth/token`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ device_auth_id: data.device_auth_id,
+ user_code: data.user_code,
+ }),
+ })
+ if (resp.ok) {
+ const body = (await resp.json()) as { authorization_code: string; code_verifier: string }
+ const tokenResp = await fetch(`${ISSUER}/oauth/token`, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ grant_type: "authorization_code",
+ code: body.authorization_code,
+ redirect_uri: `${ISSUER}/deviceauth/callback`,
+ client_id: CLIENT_ID,
+ code_verifier: body.code_verifier,
+ }).toString(),
+ })
+ if (!tokenResp.ok) throw new Error(`Token exchange failed: ${tokenResp.status}`)
+ return (await tokenResp.json()) as TokenResponse
+ }
+ if (resp.status !== 403 && resp.status !== 404) {
+ throw new Error(`Device poll failed: ${resp.status}`)
+ }
+ await new Promise((r) => setTimeout(r, intervalMs + POLL_SAFETY_MARGIN_MS))
+ }
+}
diff --git a/src/auth/jwt.ts b/src/auth/jwt.ts
new file mode 100644
index 0000000..ee5e75d
--- /dev/null
+++ b/src/auth/jwt.ts
@@ -0,0 +1,46 @@
+export interface IdTokenClaims {
+ chatgpt_account_id?: string
+ organizations?: Array<{ id: string }>
+ email?: string
+ "https://api.openai.com/auth"?: {
+ chatgpt_account_id?: string
+ }
+}
+
+export function parseJwtClaims(token: string): IdTokenClaims | undefined {
+ const parts = token.split(".")
+ if (parts.length !== 3) return undefined
+ try {
+ return JSON.parse(Buffer.from(parts[1]!, "base64url").toString())
+ } catch {
+ return undefined
+ }
+}
+
+export function extractAccountIdFromClaims(claims: IdTokenClaims): string | undefined {
+ return (
+ claims.chatgpt_account_id ||
+ claims["https://api.openai.com/auth"]?.chatgpt_account_id ||
+ claims.organizations?.[0]?.id
+ )
+}
+
+export interface TokenResponse {
+ id_token?: string
+ access_token: string
+ refresh_token: string
+ expires_in?: number
+}
+
+export function extractAccountId(tokens: TokenResponse): string | undefined {
+ if (tokens.id_token) {
+ const claims = parseJwtClaims(tokens.id_token)
+ const accountId = claims && extractAccountIdFromClaims(claims)
+ if (accountId) return accountId
+ }
+ if (tokens.access_token) {
+ const claims = parseJwtClaims(tokens.access_token)
+ return claims ? extractAccountIdFromClaims(claims) : undefined
+ }
+ return undefined
+}
diff --git a/src/auth/manager.ts b/src/auth/manager.ts
new file mode 100644
index 0000000..e7610d0
--- /dev/null
+++ b/src/auth/manager.ts
@@ -0,0 +1,75 @@
+import { CLIENT_ID, ISSUER, REFRESH_MARGIN_MS } from "./constants.ts"
+import { extractAccountId, type TokenResponse } from "./jwt.ts"
+import { loadAuth, saveAuth, type StoredAuth } from "./token-store.ts"
+
+let cached: StoredAuth | undefined
+let inflight: Promise<StoredAuth> | undefined
+
+export async function getAuth(): Promise<StoredAuth> {
+ if (!cached) {
+ const stored = await loadAuth()
+ if (!stored) throw new Error("Not authenticated. Run: ccxp auth login")
+ cached = stored
+ }
+ if (cached.expires - REFRESH_MARGIN_MS > Date.now()) {
+ return cached
+ }
+ if (inflight) return inflight
+ inflight = refreshNow(cached).finally(() => {
+ inflight = undefined
+ })
+ return inflight
+}
+
+export async function forceRefresh(): Promise<StoredAuth> {
+ if (!cached) {
+ const stored = await loadAuth()
+ if (!stored) throw new Error("Not authenticated")
+ cached = stored
+ }
+ if (inflight) return inflight
+ inflight = refreshNow(cached).finally(() => {
+ inflight = undefined
+ })
+ return inflight
+}
+
+async function refreshNow(current: StoredAuth): Promise<StoredAuth> {
+ const resp = await fetch(`${ISSUER}/oauth/token`, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ grant_type: "refresh_token",
+ refresh_token: current.refresh,
+ client_id: CLIENT_ID,
+ }).toString(),
+ })
+ if (!resp.ok) throw new Error(`Token refresh failed: ${resp.status} ${await resp.text()}`)
+ const tokens = (await resp.json()) as TokenResponse
+ const accountId = extractAccountId(tokens) || current.accountId
+ const next: StoredAuth = {
+ access: tokens.access_token,
+ refresh: tokens.refresh_token || current.refresh,
+ expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
+ accountId,
+ }
+ await saveAuth(next)
+ cached = next
+ return next
+}
+
+export async function persistInitialTokens(tokens: TokenResponse): Promise<StoredAuth> {
+ const auth: StoredAuth = {
+ access: tokens.access_token,
+ refresh: tokens.refresh_token,
+ expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
+ accountId: extractAccountId(tokens),
+ }
+ await saveAuth(auth)
+ cached = auth
+ return auth
+}
+
+export function resetCache(): void {
+ cached = undefined
+}
diff --git a/src/auth/pkce.ts b/src/auth/pkce.ts
new file mode 100644
index 0000000..d071b82
--- /dev/null
+++ b/src/auth/pkce.ts
@@ -0,0 +1,117 @@
+import { createServer } from "node:http"
+import { CLIENT_ID, ISSUER, OAUTH_PORT, OAUTH_REDIRECT_URI, ORIGINATOR } from "./constants.ts"
+import type { TokenResponse } from "./jwt.ts"
+
+export interface PkceCodes {
+ verifier: string
+ challenge: string
+}
+
+export async function generatePKCE(): Promise<PkceCodes> {
+ const verifier = generateRandomString(43)
+ const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))
+ return { verifier, challenge: base64UrlEncode(hash) }
+}
+
+function generateRandomString(length: number): string {
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
+ const bytes = crypto.getRandomValues(new Uint8Array(length))
+ return Array.from(bytes)
+ .map((b) => chars[b % chars.length])
+ .join("")
+}
+
+function base64UrlEncode(buffer: ArrayBuffer): string {
+ const bytes = new Uint8Array(buffer)
+ let binary = ""
+ for (const b of bytes) binary += String.fromCharCode(b)
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")
+}
+
+export function generateState(): string {
+ return base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)).buffer)
+}
+
+export function buildAuthorizeUrl(pkce: PkceCodes, state: string): string {
+ const params = new URLSearchParams({
+ response_type: "code",
+ client_id: CLIENT_ID,
+ redirect_uri: OAUTH_REDIRECT_URI,
+ scope: "openid profile email offline_access",
+ code_challenge: pkce.challenge,
+ code_challenge_method: "S256",
+ id_token_add_organizations: "true",
+ codex_cli_simplified_flow: "true",
+ state,
+ originator: ORIGINATOR,
+ })
+ return `${ISSUER}/oauth/authorize?${params.toString()}`
+}
+
+export async function exchangeCodeForTokens(code: string, pkce: PkceCodes): Promise<TokenResponse> {
+ const response = await fetch(`${ISSUER}/oauth/token`, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ grant_type: "authorization_code",
+ code,
+ redirect_uri: OAUTH_REDIRECT_URI,
+ client_id: CLIENT_ID,
+ code_verifier: pkce.verifier,
+ }).toString(),
+ })
+ if (!response.ok) throw new Error(`Token exchange failed: ${response.status} ${await response.text()}`)
+ return (await response.json()) as TokenResponse
+}
+
+export async function runBrowserLogin(): Promise<TokenResponse> {
+ const pkce = await generatePKCE()
+ const state = generateState()
+ const authUrl = buildAuthorizeUrl(pkce, state)
+
+ return new Promise<TokenResponse>((resolve, reject) => {
+ const server = createServer((req, res) => {
+ const url = new URL(req.url || "/", `http://localhost:${OAUTH_PORT}`)
+ if (url.pathname !== "/auth/callback") {
+ res.writeHead(404)
+ res.end("Not found")
+ return
+ }
+ const code = url.searchParams.get("code")
+ const receivedState = url.searchParams.get("state")
+ const error = url.searchParams.get("error")
+ if (error || !code || receivedState !== state) {
+ const msg = error || "Invalid callback"
+ res.writeHead(400, { "Content-Type": "text/plain" })
+ res.end(`Auth failed: ${msg}`)
+ server.close()
+ reject(new Error(msg))
+ return
+ }
+ exchangeCodeForTokens(code, pkce)
+ .then((tokens) => {
+ res.writeHead(200, { "Content-Type": "text/html" })
+ res.end("<html><body><h1>Authorization Successful</h1><p>You can close this window.</p></body></html>")
+ server.close()
+ resolve(tokens)
+ })
+ .catch((err) => {
+ res.writeHead(500, { "Content-Type": "text/plain" })
+ res.end(String(err))
+ server.close()
+ reject(err)
+ })
+ })
+ server.listen(OAUTH_PORT, () => {
+ console.log(`Open this URL in your browser to authorize:\n\n ${authUrl}\n`)
+ })
+ server.on("error", reject)
+ setTimeout(
+ () => {
+ server.close()
+ reject(new Error("OAuth timeout"))
+ },
+ 5 * 60 * 1000,
+ )
+ })
+}
diff --git a/src/auth/token-store.ts b/src/auth/token-store.ts
new file mode 100644
index 0000000..900bd67
--- /dev/null
+++ b/src/auth/token-store.ts
@@ -0,0 +1,45 @@
+import { mkdir, readFile, writeFile, chmod } from "node:fs/promises"
+import { dirname, join } from "node:path"
+import { homedir } from "node:os"
+
+export interface StoredAuth {
+ access: string
+ refresh: string
+ expires: number
+ accountId?: string
+}
+
+const DIR = join(homedir(), ".config", "claude-code-chatgpt-proxy")
+const FILE = join(DIR, "auth.json")
+
+export async function loadAuth(): Promise<StoredAuth | undefined> {
+ try {
+ const raw = await readFile(FILE, "utf8")
+ return JSON.parse(raw) as StoredAuth
+ } catch (err: any) {
+ if (err?.code === "ENOENT") return undefined
+ throw err
+ }
+}
+
+export async function saveAuth(auth: StoredAuth): Promise<void> {
+ await mkdir(dirname(FILE), { recursive: true })
+ await writeFile(FILE, JSON.stringify(auth, null, 2), "utf8")
+ try {
+ await chmod(FILE, 0o600)
+ } catch {
+ // best-effort
+ }
+}
+
+export async function clearAuth(): Promise<void> {
+ try {
+ await writeFile(FILE, "", "utf8")
+ } catch {
+ // noop
+ }
+}
+
+export function authPath(): string {
+ return FILE
+}
diff --git a/src/cli.ts b/src/cli.ts
new file mode 100644
index 0000000..f84becf
--- /dev/null
+++ b/src/cli.ts
@@ -0,0 +1,83 @@
+#!/usr/bin/env bun
+import { runBrowserLogin } from "./auth/pkce.ts"
+import { runDeviceLogin } from "./auth/device.ts"
+import { persistInitialTokens } from "./auth/manager.ts"
+import { loadAuth, authPath, clearAuth } from "./auth/token-store.ts"
+import { startServer } from "./server.ts"
+import { createLogger, logDir } from "./log.ts"
+
+const log = createLogger("cli")
+
+async function main() {
+ const [, , cmd, sub] = process.argv
+ switch (cmd) {
+ case "serve":
+ case undefined: {
+ const port = Number(process.env.PORT ?? 11434)
+ startServer({ port })
+ console.log(`Proxy listening on http://localhost:${port}`)
+ console.log(`Logs: ${logDir()}/proxy.log`)
+ console.log()
+ console.log("Configure Claude Code:")
+ console.log(` export ANTHROPIC_BASE_URL="http://localhost:${port}"`)
+ console.log(` export ANTHROPIC_AUTH_TOKEN="anything"`)
+ console.log(` export ANTHROPIC_MODEL="gpt-5.2-codex"`)
+ console.log(` export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1"`)
+ return
+ }
+ case "auth": {
+ if (sub === "login") {
+ const tokens = await runBrowserLogin()
+ const saved = await persistInitialTokens(tokens)
+ console.log(`Auth saved to ${authPath()}`)
+ if (saved.accountId) console.log(`Account: ${saved.accountId}`)
+ return
+ }
+ if (sub === "device") {
+ const tokens = await runDeviceLogin()
+ const saved = await persistInitialTokens(tokens)
+ console.log(`Auth saved to ${authPath()}`)
+ if (saved.accountId) console.log(`Account: ${saved.accountId}`)
+ return
+ }
+ if (sub === "status") {
+ const auth = await loadAuth()
+ if (!auth) {
+ console.log("Not authenticated")
+ process.exit(1)
+ }
+ const ms = auth.expires - Date.now()
+ console.log(`Account: ${auth.accountId ?? "(none)"}`)
+ console.log(`Expires: ${new Date(auth.expires).toISOString()} (in ${Math.floor(ms / 1000)}s)`)
+ console.log(`File: ${authPath()}`)
+ return
+ }
+ if (sub === "logout") {
+ await clearAuth()
+ console.log("Logged out")
+ return
+ }
+ usageAndExit()
+ return
+ }
+ default:
+ usageAndExit()
+ }
+}
+
+function usageAndExit(): never {
+ console.log(`Usage:
+ ccxp serve Run proxy (PORT env, default 11434)
+ ccxp auth login Browser OAuth (PKCE)
+ ccxp auth device Device-code OAuth
+ ccxp auth status Show current auth
+ ccxp auth logout Clear stored auth
+`)
+ process.exit(2)
+}
+
+main().catch((err) => {
+ log.error("cli fatal", { err: String(err), stack: (err as Error)?.stack })
+ console.error(err)
+ process.exit(1)
+})
diff --git a/src/codex/client.ts b/src/codex/client.ts
new file mode 100644
index 0000000..9046a67
--- /dev/null
+++ b/src/codex/client.ts
@@ -0,0 +1,112 @@
+import { CODEX_API_ENDPOINT, ORIGINATOR } from "../auth/constants.ts"
+import { forceRefresh, getAuth } from "../auth/manager.ts"
+import { createLogger } from "../log.ts"
+import type { ResponsesRequest } from "../translate/request.ts"
+
+const log = createLogger("codex.client")
+
+export interface CodexPostOptions {
+ sessionId?: string
+ signal?: AbortSignal
+}
+
+export interface CodexResponse {
+ body: ReadableStream<Uint8Array>
+ status: number
+ headers: Headers
+}
+
+export async function postCodex(
+ body: ResponsesRequest,
+ opts: CodexPostOptions = {},
+): Promise<CodexResponse> {
+ let auth = await getAuth()
+ let resp = await doFetch(auth.access, auth.accountId, body, opts)
+
+ if (resp.status === 401) {
+ log.warn("got 401, refreshing token", {})
+ try {
+ auth = await forceRefresh()
+ resp = await doFetch(auth.access, auth.accountId, body, opts)
+ } catch (err) {
+ log.error("refresh after 401 failed", { err: String(err) })
+ }
+ }
+
+ if (resp.status === 403) {
+ const text = await safeText(resp)
+ log.error("403 from upstream (non-refreshable)", { body: text })
+ throw new CodexError(403, "Forbidden", text)
+ }
+
+ if (resp.status === 429) {
+ const retryAfter = resp.headers.get("retry-after") || undefined
+ const text = await safeText(resp)
+ throw new CodexError(429, "Rate limited", text, { retryAfter })
+ }
+
+ if (!resp.ok) {
+ const text = await safeText(resp)
+ throw new CodexError(resp.status, "Upstream error", text)
+ }
+
+ if (!resp.body) throw new CodexError(500, "Upstream returned no body")
+
+ return { body: resp.body, status: resp.status, headers: resp.headers }
+}
+
+async function doFetch(
+ accessToken: string,
+ accountId: string | undefined,
+ body: ResponsesRequest,
+ opts: CodexPostOptions,
+): Promise<Response> {
+ const headers = new Headers({
+ "Content-Type": "application/json",
+ accept: "text/event-stream",
+ authorization: `Bearer ${accessToken}`,
+ originator: ORIGINATOR,
+ "openai-beta": "responses=experimental",
+ })
+ if (accountId) headers.set("ChatGPT-Account-Id", accountId)
+ if (opts.sessionId) {
+ headers.set("session_id", opts.sessionId)
+ headers.set("x-client-request-id", opts.sessionId)
+ headers.set("x-codex-window-id", `${opts.sessionId}:0`)
+ }
+
+ log.debug("posting to codex", {
+ url: CODEX_API_ENDPOINT,
+ model: body.model,
+ inputCount: body.input.length,
+ toolCount: body.tools?.length ?? 0,
+ sessionId: opts.sessionId,
+ })
+
+ return fetch(CODEX_API_ENDPOINT, {
+ method: "POST",
+ headers,
+ body: JSON.stringify(body),
+ signal: opts.signal,
+ })
+}
+
+async function safeText(resp: Response): Promise<string> {
+ try {
+ return await resp.text()
+ } catch {
+ return ""
+ }
+}
+
+export class CodexError extends Error {
+ constructor(
+ public status: number,
+ message: string,
+ public detail?: string,
+ public meta?: { retryAfter?: string },
+ ) {
+ super(message)
+ this.name = "CodexError"
+ }
+}
diff --git a/src/count-tokens.ts b/src/count-tokens.ts
new file mode 100644
index 0000000..217fd3d
--- /dev/null
+++ b/src/count-tokens.ts
@@ -0,0 +1,38 @@
+import { encode } from "gpt-tokenizer/model/gpt-4o"
+import type { AnthropicRequest } from "./anthropic/schema.ts"
+
+export function countTokens(req: AnthropicRequest): number {
+ let total = 0
+ if (req.system) {
+ const text =
+ typeof req.system === "string"
+ ? req.system
+ : req.system.map((b) => b.text || "").join("\n")
+ total += encode(text).length
+ }
+ for (const msg of req.messages) {
+ if (typeof msg.content === "string") {
+ total += encode(msg.content).length
+ continue
+ }
+ for (const block of msg.content) {
+ if (block.type === "text") total += encode(block.text).length
+ else if (block.type === "tool_use") total += encode(JSON.stringify(block.input ?? {})).length + encode(block.name).length
+ else if (block.type === "tool_result") {
+ const text =
+ typeof block.content === "string"
+ ? block.content
+ : block.content.map((b) => (b.type === "text" ? b.text : "")).join("\n")
+ total += encode(text).length
+ }
+ }
+ }
+ for (const tool of req.tools ?? []) {
+ total += encode(tool.name).length
+ if (tool.description) total += encode(tool.description).length
+ total += encode(JSON.stringify(tool.input_schema ?? {})).length
+ }
+ // Rough per-message overhead
+ total += req.messages.length * 4
+ return total
+}
diff --git a/src/log.ts b/src/log.ts
new file mode 100644
index 0000000..7a72b11
--- /dev/null
+++ b/src/log.ts
@@ -0,0 +1,120 @@
+import { mkdir, appendFile, stat, rename } from "node:fs/promises"
+import { createWriteStream, type WriteStream } from "node:fs"
+import { join } from "node:path"
+import { homedir } from "node:os"
+
+const MAX_LOG_BYTES = 20 * 1024 * 1024 // 20 MiB
+const REDACT_KEYS = new Set([
+ "authorization",
+ "Authorization",
+ "access",
+ "access_token",
+ "refresh",
+ "refresh_token",
+ "id_token",
+ "code",
+ "code_verifier",
+ "ChatGPT-Account-Id",
+ "chatgpt-account-id",
+ "x-api-key",
+])
+
+function stateDir(): string {
+ const base = process.env.XDG_STATE_HOME || join(homedir(), ".local", "state")
+ return join(base, "claude-code-chatgpt-proxy")
+}
+
+export function logDir(): string {
+ return stateDir()
+}
+
+let stream: WriteStream | undefined
+let rotating: Promise<void> | undefined
+
+async function ensureStream(): Promise<WriteStream> {
+ if (stream) return stream
+ const dir = stateDir()
+ await mkdir(dir, { recursive: true })
+ const file = join(dir, "proxy.log")
+ stream = createWriteStream(file, { flags: "a" })
+ return stream
+}
+
+async function maybeRotate(): Promise<void> {
+ if (rotating) return rotating
+ rotating = (async () => {
+ try {
+ const dir = stateDir()
+ const file = join(dir, "proxy.log")
+ const s = await stat(file).catch(() => undefined)
+ if (!s || s.size < MAX_LOG_BYTES) return
+ const rotated = join(dir, `proxy.log.${Date.now()}`)
+ if (stream) {
+ stream.end()
+ stream = undefined
+ }
+ await rename(file, rotated).catch(() => {})
+ } finally {
+ rotating = undefined
+ }
+ })()
+ return rotating
+}
+
+function redact(value: unknown, depth = 0): unknown {
+ if (depth > 6) return "[depth-limit]"
+ if (value == null) return value
+ if (typeof value === "string") {
+ if (value.length > 4000) return value.slice(0, 4000) + `…[${value.length - 4000} more]`
+ return value
+ }
+ if (typeof value !== "object") return value
+ if (Array.isArray(value)) return value.map((v) => redact(v, depth + 1))
+ const out: Record<string, unknown> = {}
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
+ if (REDACT_KEYS.has(k)) {
+ out[k] = typeof v === "string" ? `[redacted len=${v.length}]` : "[redacted]"
+ } else {
+ out[k] = redact(v, depth + 1)
+ }
+ }
+ return out
+}
+
+type Level = "debug" | "info" | "warn" | "error"
+
+async function write(level: Level, service: string, msg: string, fields?: Record<string, unknown>): Promise<void> {
+ const line = JSON.stringify({
+ t: new Date().toISOString(),
+ level,
+ service,
+ msg,
+ ...(fields ? { fields: redact(fields) as Record<string, unknown> } : {}),
+ })
+ try {
+ const s = await ensureStream()
+ s.write(line + "\n")
+ void maybeRotate()
+ } catch {
+ // swallow; also print to stderr for visibility
+ }
+ if (level === "error" || level === "warn" || process.env.CCXP_LOG_STDERR) {
+ process.stderr.write(line + "\n")
+ }
+}
+
+export interface Logger {
+ debug(msg: string, fields?: Record<string, unknown>): void
+ info(msg: string, fields?: Record<string, unknown>): void
+ warn(msg: string, fields?: Record<string, unknown>): void
+ error(msg: string, fields?: Record<string, unknown>): void
+}
+
+export function createLogger(service: string): Logger {
+ return {
+ debug: (msg, fields) => void write("debug", service, msg, fields),
+ info: (msg, fields) => void write("info", service, msg, fields),
+ warn: (msg, fields) => void write("warn", service, msg, fields),
+ error: (msg, fields) => void write("error", service, msg, fields),
+ }
+}
diff --git a/src/server.ts b/src/server.ts
new file mode 100644
index 0000000..cb798d6
--- /dev/null
+++ b/src/server.ts
@@ -0,0 +1,245 @@
+import { createLogger, logDir } from "./log.ts"
+import type { AnthropicRequest } from "./anthropic/schema.ts"
+import { assertAllowedModel, ModelNotAllowedError } from "./translate/model-allowlist.ts"
+import { isTitleGenRequest, translateRequest } from "./translate/request.ts"
+import { translateStream } from "./translate/stream.ts"
+import { accumulateResponse } from "./translate/accumulate.ts"
+import { encodeSseEvent } from "./translate/sse.ts"
+import { CodexError, postCodex } from "./codex/client.ts"
+import { countTokens } from "./count-tokens.ts"
+
+const log = createLogger("server")
+
+export interface ServeOptions {
+ port: number
+}
+
+export function startServer(opts: ServeOptions): { stop: () => void; port: number } {
+ const server = Bun.serve({
+ port: opts.port,
+ async fetch(req) {
+ const url = new URL(req.url)
+ const start = Date.now()
+ const reqId = crypto.randomUUID()
+ log.info("request", { reqId, method: req.method, path: url.pathname, query: url.search })
+ try {
+ const resp = await route(req, url, reqId)
+ log.info("response", { reqId, status: resp.status, ms: Date.now() - start })
+ return resp
+ } catch (err) {
+ log.error("handler error", { reqId, err: String(err), stack: (err as Error)?.stack })
+ return jsonError(500, "internal_error", String(err))
+ }
+ },
+ })
+ log.info("server listening", { port: server.port, logDir: logDir() })
+ return {
+ port: Number(server.port),
+ stop: () => server.stop(),
+ }
+}
+
+async function route(req: Request, url: URL, reqId: string): Promise<Response> {
+ if (url.pathname === "/healthz") {
+ return new Response(JSON.stringify({ ok: true }), {
+ headers: { "content-type": "application/json" },
+ })
+ }
+
+ if (req.method === "POST" && url.pathname === "/v1/messages/count_tokens") {
+ const body = (await req.json()) as AnthropicRequest
+ const tokens = countTokens(body)
+ log.debug("count_tokens", { reqId, tokens })
+ return new Response(JSON.stringify({ input_tokens: tokens }), {
+ headers: { "content-type": "application/json" },
+ })
+ }
+
+ if (req.method === "POST" && url.pathname === "/v1/messages") {
+ return handleMessages(req, reqId)
+ }
+
+ return jsonError(404, "not_found", `No route for ${req.method} ${url.pathname}`)
+}
+
+async function handleMessages(req: Request, reqId: string): Promise<Response> {
+ let body: AnthropicRequest
+ try {
+ body = (await req.json()) as AnthropicRequest
+ } catch (err) {
+ return jsonError(400, "invalid_request_error", `Invalid JSON: ${err}`)
+ }
+
+ const sessionId = req.headers.get("x-claude-code-session-id") || undefined
+ const messageId = `msg_${crypto.randomUUID().replace(/-/g, "")}`
+ const wantStream = body.stream !== false
+
+ log.debug("anthropic request", {
+ reqId,
+ model: body.model,
+ messageCount: body.messages?.length,
+ toolCount: body.tools?.length ?? 0,
+ stream: wantStream,
+ sessionId,
+ hasTitleGenFormat: isTitleGenRequest(body),
+ })
+
+ // Title-generation stub: Claude Code fires this in parallel for session titles.
+ if (isTitleGenRequest(body)) {
+ return titleGenStub({ messageId, model: body.model, wantStream })
+ }
+
+ try {
+ assertAllowedModel(body.model)
+ } catch (err) {
+ if (err instanceof ModelNotAllowedError) {
+ return jsonError(
+ 400,
+ "invalid_request_error",
+ `Model "${err.model}" is not in the Codex OAuth allowlist`,
+ )
+ }
+ throw err
+ }
+
+ const translated = translateRequest(body, { sessionId })
+ log.debug("translated request", {
+ reqId,
+ inputItems: translated.input.length,
+ tools: translated.tools?.length ?? 0,
+ hasInstructions: !!translated.instructions,
+ promptCacheKey: translated.prompt_cache_key,
+ })
+
+ let upstream
+ try {
+ upstream = await postCodex(translated, { sessionId, signal: req.signal })
+ } catch (err) {
+ if (err instanceof CodexError) {
+ log.warn("codex error", { reqId, status: err.status, detail: err.detail })
+ if (err.status === 429) {
+ const headers: Record<string, string> = { "content-type": "application/json" }
+ if (err.meta?.retryAfter) headers["retry-after"] = err.meta.retryAfter
+ return new Response(
+ JSON.stringify({
+ type: "error",
+ error: { type: "rate_limit_error", message: err.detail || err.message },
+ }),
+ { status: 429, headers },
+ )
+ }
+ const type =
+ err.status === 401 || err.status === 403 ? "authentication_error" : "api_error"
+ return jsonError(err.status, type, err.detail || err.message)
+ }
+ throw err
+ }
+
+ if (wantStream) {
+ const stream = translateStream(upstream.body, { messageId, model: body.model })
+ return new Response(stream, {
+ status: 200,
+ headers: {
+ "content-type": "text/event-stream",
+ "cache-control": "no-cache",
+ connection: "keep-alive",
+ },
+ })
+ }
+
+ const result = await accumulateResponse(upstream.body, { messageId, model: body.model })
+ return new Response(JSON.stringify(result), {
+ headers: { "content-type": "application/json" },
+ })
+}
+
+function titleGenStub(opts: {
+ messageId: string
+ model: string
+ wantStream: boolean
+}): Response {
+ const content = [{ type: "text" as const, text: JSON.stringify({ title: "Session" }) }]
+ if (!opts.wantStream) {
+ return new Response(
+ JSON.stringify({
+ id: opts.messageId,
+ type: "message",
+ role: "assistant",
+ model: opts.model,
+ content,
+ stop_reason: "end_turn",
+ stop_sequence: null,
+ usage: {
+ input_tokens: 0,
+ output_tokens: 0,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ },
+ }),
+ { headers: { "content-type": "application/json" } },
+ )
+ }
+ const enc = new TextEncoder()
+ const stream = new ReadableStream<Uint8Array>({
+ start(controller) {
+ const emit = (event: string, data: unknown) =>
+ controller.enqueue(enc.encode(encodeSseEvent(event, data)))
+ emit("message_start", {
+ type: "message_start",
+ message: {
+ id: opts.messageId,
+ type: "message",
+ role: "assistant",
+ model: opts.model,
+ content: [],
+ stop_reason: null,
+ stop_sequence: null,
+ usage: {
+ input_tokens: 0,
+ output_tokens: 0,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ },
+ },
+ })
+ emit("ping", { type: "ping" })
+ emit("content_block_start", {
+ type: "content_block_start",
+ index: 0,
+ content_block: { type: "text", text: "" },
+ })
+ emit("content_block_delta", {
+ type: "content_block_delta",
+ index: 0,
+ delta: { type: "text_delta", text: content[0]!.text },
+ })
+ emit("content_block_stop", { type: "content_block_stop", index: 0 })
+ emit("message_delta", {
+ type: "message_delta",
+ delta: { stop_reason: "end_turn", stop_sequence: null },
+ usage: {
+ input_tokens: 0,
+ output_tokens: 0,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ },
+ })
+ emit("message_stop", { type: "message_stop" })
+ controller.close()
+ },
+ })
+ return new Response(stream, {
+ headers: {
+ "content-type": "text/event-stream",
+ "cache-control": "no-cache",
+ connection: "keep-alive",
+ },
+ })
+}
+
+function jsonError(status: number, type: string, message: string): Response {
+ return new Response(JSON.stringify({ type: "error", error: { type, message } }), {
+ status,
+ headers: { "content-type": "application/json" },
+ })
+}
diff --git a/src/translate/accumulate.ts b/src/translate/accumulate.ts
new file mode 100644
index 0000000..7cefc2c
--- /dev/null
+++ b/src/translate/accumulate.ts
@@ -0,0 +1,129 @@
+import { parseSseStream } from "./sse.ts"
+
+export interface AnthropicNonStreamResponse {
+ id: string
+ type: "message"
+ role: "assistant"
+ model: string
+ content: Array<
+ | { type: "text"; text: string }
+ | { type: "tool_use"; id: string; name: string; input: unknown }
+ >
+ stop_reason: "end_turn" | "tool_use" | "max_tokens" | null
+ stop_sequence: null
+ usage: {
+ input_tokens: number
+ output_tokens: number
+ cache_creation_input_tokens: number
+ cache_read_input_tokens: number
+ }
+}
+
+/**
+ * Drive the Codex SSE stream to completion and produce a single Anthropic
+ * non-streaming response object. Used when the client asked for stream:false.
+ */
+export async function accumulateResponse(
+ upstream: ReadableStream<Uint8Array>,
+ opts: { messageId: string; model: string },
+): Promise<AnthropicNonStreamResponse> {
+ const blocks = new Map<
+ number,
+ | { kind: "text"; text: string }
+ | { kind: "tool"; id: string; name: string; args: string }
+ >()
+ const itemToOutputIndex = new Map<string, number>()
+ let sawToolUse = false
+ let usage: any
+ const orderedIndices: number[] = []
+
+ const ensureOrder = (i: number) => {
+ if (!orderedIndices.includes(i)) orderedIndices.push(i)
+ }
+
+ for await (const evt of parseSseStream(upstream)) {
+ if (!evt.data) continue
+ let p: any
+ try {
+ p = JSON.parse(evt.data)
+ } catch {
+ continue
+ }
+ const t = p.type || evt.event || ""
+ if (t === "response.output_item.added") {
+ const item = p.item
+ const oi = p.output_index
+ if (!item) continue
+ if (item.type === "message") {
+ blocks.set(oi, { kind: "text", text: "" })
+ ensureOrder(oi)
+ if (item.id) itemToOutputIndex.set(item.id, oi)
+ } else if (item.type === "function_call") {
+ sawToolUse = true
+ blocks.set(oi, { kind: "tool", id: item.call_id, name: item.name, args: "" })
+ ensureOrder(oi)
+ }
+ continue
+ }
+ if (t === "response.output_text.delta") {
+ let oi = p.output_index
+ if (typeof oi !== "number" && p.item_id) oi = itemToOutputIndex.get(p.item_id)
+ const b = typeof oi === "number" ? blocks.get(oi) : undefined
+ if (b && b.kind === "text") b.text += p.delta ?? ""
+ continue
+ }
+ if (t === "response.function_call_arguments.delta") {
+ const b = blocks.get(p.output_index)
+ if (b && b.kind === "tool") b.args += p.delta ?? ""
+ continue
+ }
+ if (t === "response.function_call_arguments.done") {
+ const b = blocks.get(p.output_index)
+ if (b && b.kind === "tool" && !b.args && typeof p.arguments === "string") b.args = p.arguments
+ continue
+ }
+ if (t === "response.output_item.done") {
+ const item = p.item
+ const b = blocks.get(p.output_index)
+ if (b && b.kind === "tool" && !b.args && typeof item?.arguments === "string") b.args = item.arguments
+ continue
+ }
+ if (t === "response.completed") {
+ usage = p.response?.usage
+ continue
+ }
+ }
+
+ const content: AnthropicNonStreamResponse["content"] = []
+ for (const i of orderedIndices) {
+ const b = blocks.get(i)
+ if (!b) continue
+ if (b.kind === "text") {
+ if (b.text) content.push({ type: "text", text: b.text })
+ } else {
+ let input: unknown = {}
+ try {
+ input = b.args ? JSON.parse(b.args) : {}
+ } catch {
+ input = { _raw: b.args }
+ }
+ content.push({ type: "tool_use", id: b.id, name: b.name, input })
+ }
+ }
+
+ return {
+ id: opts.messageId,
+ type: "message",
+ role: "assistant",
+ model: opts.model,
+ content,
+ stop_reason: sawToolUse ? "tool_use" : "end_turn",
+ stop_sequence: null,
+ usage: {
+ input_tokens: usage?.input_tokens ?? 0,
+ output_tokens: usage?.output_tokens ?? 0,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: usage?.input_tokens_details?.cached_tokens ?? 0,
+ },
+ }
+}
diff --git a/src/translate/model-allowlist.ts b/src/translate/model-allowlist.ts
new file mode 100644
index 0000000..403b602
--- /dev/null
+++ b/src/translate/model-allowlist.ts
@@ -0,0 +1,23 @@
+export const ALLOWED_MODELS = new Set([
+ "gpt-5.1-codex",
+ "gpt-5.1-codex-max",
+ "gpt-5.1-codex-mini",
+ "gpt-5.2",
+ "gpt-5.2-codex",
+ "gpt-5.3-codex",
+ "gpt-5.4",
+ "gpt-5.4-mini",
+])
+
+export function assertAllowedModel(model: string): void {
+ if (!ALLOWED_MODELS.has(model)) {
+ throw new ModelNotAllowedError(model)
+ }
+}
+
+export class ModelNotAllowedError extends Error {
+ constructor(public model: string) {
+ super(`Model not allowed: ${model}`)
+ this.name = "ModelNotAllowedError"
+ }
+}
diff --git a/src/translate/request.ts b/src/translate/request.ts
new file mode 100644
index 0000000..a89f9fc
--- /dev/null
+++ b/src/translate/request.ts
@@ -0,0 +1,186 @@
+import type {
+ AnthropicContentBlock,
+ AnthropicMessage,
+ AnthropicRequest,
+ AnthropicTextBlock,
+ AnthropicTool,
+} from "../anthropic/schema.ts"
+
+export interface ResponsesRequest {
+ model: string
+ instructions?: string
+ input: ResponsesInputItem[]
+ tools?: ResponsesTool[]
+ tool_choice?: "auto" | "none" | "required"
+ parallel_tool_calls?: boolean
+ store: false
+ stream: true
+ include?: string[]
+ prompt_cache_key?: string
+ reasoning?: { effort?: "low" | "medium" | "high" }
+ text?: { verbosity?: "low" | "medium" | "high" }
+}
+
+export type ResponsesInputItem =
+ | {
+ type: "message"
+ role: "user" | "assistant" | "developer" | "system"
+ content: ResponsesContentPart[]
+ }
+ | {
+ type: "function_call"
+ call_id: string
+ name: string
+ arguments: string
+ }
+ | {
+ type: "function_call_output"
+ call_id: string
+ output: string
+ }
+
+export type ResponsesContentPart =
+ | { type: "input_text"; text: string }
+ | { type: "output_text"; text: string }
+ | { type: "input_image"; image_url: string }
+
+export interface ResponsesTool {
+ type: "function"
+ name: string
+ description?: string
+ parameters: unknown
+ strict?: boolean
+}
+
+export interface TranslateOptions {
+ sessionId?: string
+}
+
+export function isTitleGenRequest(req: AnthropicRequest): boolean {
+ return req.output_config?.format?.type === "json_schema"
+}
+
+export function translateRequest(req: AnthropicRequest, opts: TranslateOptions = {}): ResponsesRequest {
+ const instructions = buildInstructions(req.system)
+ const input = buildInput(req.messages)
+ const tools = req.tools?.map(toResponsesTool)
+
+ const out: ResponsesRequest = {
+ model: req.model,
+ input,
+ store: false,
+ stream: true,
+ include: ["reasoning.encrypted_content"],
+ parallel_tool_calls: true,
+ tool_choice: mapToolChoice(req.tool_choice),
+ text: { verbosity: "low" },
+ }
+ if (instructions) out.instructions = instructions
+ if (tools && tools.length) out.tools = tools
+ if (opts.sessionId) out.prompt_cache_key = opts.sessionId
+ const effort = req.output_config?.effort
+ if (effort) out.reasoning = { effort }
+ return out
+}
+
+function mapToolChoice(
+ choice: AnthropicRequest["tool_choice"],
+): "auto" | "none" | "required" | undefined {
+ if (!choice) return "auto"
+ switch (choice.type) {
+ case "auto":
+ return "auto"
+ case "none":
+ return "none"
+ case "any":
+ case "tool":
+ return "required"
+ }
+}
+
+function buildInstructions(system: AnthropicRequest["system"]): string | undefined {
+ if (!system) return undefined
+ const blocks: AnthropicTextBlock[] =
+ typeof system === "string" ? [{ type: "text", text: system }] : system
+ const texts = blocks
+ .filter((b) => b && b.type === "text" && typeof b.text === "string")
+ .map((b) => b.text)
+ .filter((t) => !t.startsWith("x-anthropic-billing-header:"))
+ if (!texts.length) return undefined
+ return texts.join("\n\n")
+}
+
+function buildInput(messages: AnthropicMessage[]): ResponsesInputItem[] {
+ const out: ResponsesInputItem[] = []
+ for (const msg of messages) {
+ const blocks = normalizeContent(msg.content)
+ if (msg.role === "user") {
+ // Split into message parts vs function_call_output items
+ const parts: ResponsesContentPart[] = []
+ for (const block of blocks) {
+ if (block.type === "text") {
+ parts.push({ type: "input_text", text: block.text })
+ } else if (block.type === "image") {
+ parts.push({ type: "input_image", image_url: imageToUrl(block) })
+ } else if (block.type === "tool_result") {
+ if (parts.length) {
+ out.push({ type: "message", role: "user", content: parts.splice(0) })
+ }
+ out.push({
+ type: "function_call_output",
+ call_id: block.tool_use_id,
+ output: toolResultToString(block.content),
+ })
+ }
+ }
+ if (parts.length) out.push({ type: "message", role: "user", content: parts })
+ } else {
+ // assistant
+ const textParts: ResponsesContentPart[] = []
+ const toolCalls: ResponsesInputItem[] = []
+ for (const block of blocks) {
+ if (block.type === "text") {
+ textParts.push({ type: "output_text", text: block.text })
+ } else if (block.type === "tool_use") {
+ toolCalls.push({
+ type: "function_call",
+ call_id: block.id,
+ name: block.name,
+ arguments: JSON.stringify(block.input ?? {}),
+ })
+ }
+ }
+ if (textParts.length) {
+ out.push({ type: "message", role: "assistant", content: textParts })
+ }
+ for (const tc of toolCalls) out.push(tc)
+ }
+ }
+ return out
+}
+
+function normalizeContent(content: AnthropicMessage["content"]): AnthropicContentBlock[] {
+ if (typeof content === "string") return [{ type: "text", text: content }]
+ return content
+}
+
+function imageToUrl(block: Extract<AnthropicContentBlock, { type: "image" }>): string {
+ if (block.source.type === "url") return block.source.url
+ return `data:${block.source.media_type};base64,${block.source.data}`
+}
+
+function toolResultToString(content: string | Array<AnthropicTextBlock | { type: "image" }>): string {
+ if (typeof content === "string") return content
+ return content
+ .map((b) => (b.type === "text" ? b.text : "[image]"))
+ .join("\n")
+}
+
+function toResponsesTool(tool: AnthropicTool): ResponsesTool {
+ return {
+ type: "function",
+ name: tool.name,
+ description: tool.description,
+ parameters: tool.input_schema,
+ }
+}
diff --git a/src/translate/sse.ts b/src/translate/sse.ts
new file mode 100644
index 0000000..3099bff
--- /dev/null
+++ b/src/translate/sse.ts
@@ -0,0 +1,49 @@
+export interface SseEvent {
+ event?: string
+ data: string
+}
+
+export function encodeSseEvent(event: string, data: unknown): string {
+ return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`
+}
+
+export async function* parseSseStream(body: ReadableStream<Uint8Array>): AsyncGenerator<SseEvent> {
+ const reader = body.getReader()
+ const decoder = new TextDecoder()
+ let buf = ""
+ try {
+ while (true) {
+ const { value, done } = await reader.read()
+ if (done) break
+ buf += decoder.decode(value, { stream: true })
+ let idx: number
+ while ((idx = buf.indexOf("\n\n")) !== -1) {
+ const raw = buf.slice(0, idx)
+ buf = buf.slice(idx + 2)
+ const evt = parseEventBlock(raw)
+ if (evt) yield evt
+ }
+ }
+ if (buf.trim()) {
+ const evt = parseEventBlock(buf)
+ if (evt) yield evt
+ }
+ } finally {
+ reader.releaseLock()
+ }
+}
+
+function parseEventBlock(raw: string): SseEvent | undefined {
+ let event: string | undefined
+ const dataLines: string[] = []
+ for (const line of raw.split("\n")) {
+ if (!line || line.startsWith(":")) continue
+ const colon = line.indexOf(":")
+ const field = colon === -1 ? line : line.slice(0, colon)
+ const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "")
+ if (field === "event") event = value
+ else if (field === "data") dataLines.push(value)
+ }
+ if (!dataLines.length && !event) return undefined
+ return { event, data: dataLines.join("\n") }
+}
diff --git a/src/translate/stream.ts b/src/translate/stream.ts
new file mode 100644
index 0000000..20c08a8
--- /dev/null
+++ b/src/translate/stream.ts
@@ -0,0 +1,298 @@
+import { encodeSseEvent, parseSseStream } from "./sse.ts"
+import { createLogger } from "../log.ts"
+
+const log = createLogger("translate.stream")
+
+interface CodexUsage {
+ input_tokens?: number
+ output_tokens?: number
+ input_tokens_details?: { cached_tokens?: number }
+ output_tokens_details?: { reasoning_tokens?: number }
+}
+
+interface TextBlockState {
+ kind: "text"
+ index: number
+}
+
+interface ToolBlockState {
+ kind: "tool"
+ index: number
+ itemId: string
+ callId: string
+ name: string
+ argsAccum: string
+ hadDelta: boolean
+}
+
+type BlockState = TextBlockState | ToolBlockState
+
+export interface StreamTranslateOptions {
+ messageId: string
+ model: string
+ // If provided, writes translated events here; otherwise returns a ReadableStream
+ onEvent?: (event: string, data: unknown) => void
+}
+
+/**
+ * Translate a Codex Responses SSE stream into Anthropic SSE events.
+ * Returns a ReadableStream<Uint8Array> of Anthropic SSE ready to pipe to client.
+ */
+export function translateStream(
+ upstream: ReadableStream<Uint8Array>,
+ opts: { messageId: string; model: string },
+): ReadableStream<Uint8Array> {
+ const encoder = new TextEncoder()
+ return new ReadableStream<Uint8Array>({
+ async start(controller) {
+ const emit = (event: string, data: unknown) => {
+ controller.enqueue(encoder.encode(encodeSseEvent(event, data)))
+ }
+ try {
+ await runStream(upstream, opts, emit)
+ } catch (err) {
+ log.error("stream translation error", { err: String(err) })
+ emit("error", { type: "error", error: { type: "api_error", message: String(err) } })
+ } finally {
+ controller.close()
+ }
+ },
+ })
+}
+
+async function runStream(
+ upstream: ReadableStream<Uint8Array>,
+ opts: { messageId: string; model: string },
+ emit: (event: string, data: unknown) => void,
+): Promise<void> {
+ let messageStarted = false
+ let anthropicIndex = 0
+ // Keyed by output_index
+ const blocksByIndex = new Map<number, BlockState>()
+ // Map item_id → output_index for text deltas
+ const itemToOutputIndex = new Map<string, number>()
+ let sawToolUse = false
+ let finalUsage: CodexUsage | undefined
+ let rateLimitReached = false
+ let rateLimitResetSeconds: number | undefined
+
+ const ensureMessageStart = () => {
+ if (messageStarted) return
+ messageStarted = true
+ emit("message_start", {
+ type: "message_start",
+ message: {
+ id: opts.messageId,
+ type: "message",
+ role: "assistant",
+ model: opts.model,
+ content: [],
+ stop_reason: null,
+ stop_sequence: null,
+ usage: {
+ input_tokens: 0,
+ output_tokens: 0,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ },
+ },
+ })
+ emit("ping", { type: "ping" })
+ }
+
+ for await (const evt of parseSseStream(upstream)) {
+ if (!evt.data) continue
+ let payload: any
+ try {
+ payload = JSON.parse(evt.data)
+ } catch {
+ log.warn("invalid json in sse data", { data: evt.data.slice(0, 200) })
+ continue
+ }
+ const type: string = payload.type || evt.event || ""
+
+ if (type === "codex.rate_limits") {
+ if (payload.rate_limits?.limit_reached) {
+ rateLimitReached = true
+ rateLimitResetSeconds = payload.rate_limits?.primary?.reset_after_seconds
+ }
+ continue
+ }
+
+ if (type === "response.created" || type === "response.in_progress") {
+ ensureMessageStart()
+ continue
+ }
+
+ if (type === "response.output_item.added") {
+ const item = payload.item
+ const outputIndex: number = payload.output_index
+ if (!item) continue
+ if (item.type === "reasoning") {
+ // drop
+ continue
+ }
+ if (item.type === "message") {
+ ensureMessageStart()
+ const idx = anthropicIndex++
+ const state: TextBlockState = { kind: "text", index: idx }
+ blocksByIndex.set(outputIndex, state)
+ if (item.id) itemToOutputIndex.set(item.id, outputIndex)
+ emit("content_block_start", {
+ type: "content_block_start",
+ index: idx,
+ content_block: { type: "text", text: "" },
+ })
+ continue
+ }
+ if (item.type === "function_call") {
+ ensureMessageStart()
+ sawToolUse = true
+ const idx = anthropicIndex++
+ const state: ToolBlockState = {
+ kind: "tool",
+ index: idx,
+ itemId: item.id,
+ callId: item.call_id,
+ name: item.name,
+ argsAccum: "",
+ hadDelta: false,
+ }
+ blocksByIndex.set(outputIndex, state)
+ emit("content_block_start", {
+ type: "content_block_start",
+ index: idx,
+ content_block: {
+ type: "tool_use",
+ id: item.call_id,
+ name: item.name,
+ input: {},
+ },
+ })
+ continue
+ }
+ continue
+ }
+
+ if (type === "response.output_text.delta") {
+ const outputIndex: number | undefined = payload.output_index
+ const itemId: string | undefined = payload.item_id
+ let state: BlockState | undefined
+ if (typeof outputIndex === "number") state = blocksByIndex.get(outputIndex)
+ if (!state && itemId) {
+ const mapped = itemToOutputIndex.get(itemId)
+ if (mapped !== undefined) state = blocksByIndex.get(mapped)
+ }
+ if (!state || state.kind !== "text") continue
+ const delta: string = payload.delta ?? ""
+ if (!delta) continue
+ emit("content_block_delta", {
+ type: "content_block_delta",
+ index: state.index,
+ delta: { type: "text_delta", text: delta },
+ })
+ continue
+ }
+
+ if (type === "response.function_call_arguments.delta") {
+ const outputIndex: number = payload.output_index
+ const state = blocksByIndex.get(outputIndex)
+ if (!state || state.kind !== "tool") continue
+ const delta: string = payload.delta ?? ""
+ if (!delta) continue
+ state.argsAccum += delta
+ state.hadDelta = true
+ emit("content_block_delta", {
+ type: "content_block_delta",
+ index: state.index,
+ delta: { type: "input_json_delta", partial_json: delta },
+ })
+ continue
+ }
+
+ if (type === "response.function_call_arguments.done") {
+ // Full args available; nothing to emit here (deltas already sent, or
+ // we flush on output_item.done if none were sent).
+ const outputIndex: number = payload.output_index
+ const state = blocksByIndex.get(outputIndex)
+ if (!state || state.kind !== "tool") continue
+ if (typeof payload.arguments === "string" && !state.argsAccum) {
+ state.argsAccum = payload.arguments
+ }
+ continue
+ }
+
+ if (type === "response.output_item.done") {
+ const item = payload.item
+ const outputIndex: number = payload.output_index
+ if (!item) continue
+ if (item.type === "reasoning") continue
+ const state = blocksByIndex.get(outputIndex)
+ if (!state) continue
+ if (state.kind === "tool") {
+ if (!state.hadDelta && typeof item.arguments === "string" && item.arguments.length) {
+ emit("content_block_delta", {
+ type: "content_block_delta",
+ index: state.index,
+ delta: { type: "input_json_delta", partial_json: item.arguments },
+ })
+ }
+ }
+ emit("content_block_stop", { type: "content_block_stop", index: state.index })
+ blocksByIndex.delete(outputIndex)
+ continue
+ }
+
+ if (type === "response.completed") {
+ finalUsage = payload.response?.usage
+ continue
+ }
+
+ if (type === "response.failed" || type === "response.error" || type === "error") {
+ const message = payload?.response?.error?.message || payload?.error?.message || "Upstream error"
+ emit("error", { type: "error", error: { type: "api_error", message } })
+ return
+ }
+ }
+
+ if (!messageStarted) {
+ // Upstream produced nothing — still emit a minimal envelope so Claude Code doesn't hang.
+ ensureMessageStart()
+ }
+
+ if (rateLimitReached) {
+ emit("error", {
+ type: "error",
+ error: {
+ type: "rate_limit_error",
+ message: `rate limit reached; retry after ${rateLimitResetSeconds ?? "?"}s`,
+ },
+ })
+ return
+ }
+
+ const usage = mapUsage(finalUsage)
+ emit("message_delta", {
+ type: "message_delta",
+ delta: {
+ stop_reason: sawToolUse ? "tool_use" : "end_turn",
+ stop_sequence: null,
+ },
+ usage,
+ })
+ emit("message_stop", { type: "message_stop" })
+}
+
+function mapUsage(u: CodexUsage | undefined): {
+ input_tokens: number
+ output_tokens: number
+ cache_creation_input_tokens: number
+ cache_read_input_tokens: number
+} {
+ return {
+ input_tokens: u?.input_tokens ?? 0,
+ output_tokens: u?.output_tokens ?? 0,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: u?.input_tokens_details?.cached_tokens ?? 0,
+ }
+}
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..d44a4ba
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,18 @@
+{
+ "compilerOptions": {
+ "target": "ESNext",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "lib": ["ESNext"],
+ "types": ["bun-types"],
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "resolveJsonModule": true,
+ "allowImportingTsExtensions": true,
+ "noEmit": true,
+ "verbatimModuleSyntax": false
+ },
+ "include": ["src/**/*.ts"]
+}