@opengeni/codex 0.2.22 → 0.2.23-canary.1
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.
- package/dist/images.d.ts +1 -0
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/images.ts +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/billing.ts","../src/device-code.ts","../src/bounded-operation.ts","../src/refresh.ts","../src/normalize.ts","../src/usage-normalize.ts","../src/reset-credits.ts","../src/api-client.ts","../src/request-context.ts","../src/response-timeout.ts","../src/fetch.ts","../src/opaque-artifact.ts","../src/mcp-sanitize.ts","../src/oversized-image-card.ts","../src/model-output-truncation.ts","../src/images.ts","../src/realtime.ts"],"sourcesContent":["import { CODEX_MODEL_ID_PREFIX } from \"./constants\";\n\n/**\n * Pure NECESSARY condition for a Codex-billed turn: the model id is namespaced\n * for the Codex subscription provider (`codex/<slug>`).\n *\n * This is NOT sufficient to bypass billing — an active, connected workspace\n * credential and the deployment flag (`settings.codexSubscriptionEnabled`) are\n * ALSO required (see `isCodexBilledTurn`/`workspaceCodexSubscriptionActive` in\n * `@opengeni/db`). Used only as a cheap, synchronous short-circuit so the common\n * non-codex path never issues a credential read.\n */\nexport function isCodexBilledModel(model: string | null | undefined): boolean {\n return typeof model === \"string\" && model.startsWith(CODEX_MODEL_ID_PREFIX);\n}\n","// Device-code (headless) login flow for a ChatGPT/Codex subscription.\n// Grounded in codex-rs device_code_auth.rs:67-145 + server.rs:732-766 (spec §1.1).\n// Every call takes an injectable fetch so tests can supply a fake.\n\nimport {\n CODEX_AUTH_BASE,\n CODEX_CLIENT_ID,\n CODEX_DEVICE_REDIRECT_URI,\n CODEX_DEVICE_VERIFICATION_URL,\n CODEX_TOKEN_URL,\n} from \"./constants\";\n\nexport type CodexFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;\n\nexport type CodexDeviceStart = {\n deviceAuthId: string;\n userCode: string;\n verificationUri: string;\n intervalSeconds: number;\n};\n\nexport type CodexTokens = { idToken: string; accessToken: string; refreshToken: string };\n\nexport type CodexPollResult =\n | { status: \"pending\" }\n | { status: \"expired\" }\n | { status: \"authorized\"; authorizationCode: string; codeVerifier: string };\n\nexport class CodexDeviceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CodexDeviceError\";\n }\n}\n\n/** Step 1: POST {auth}/deviceauth/usercode {client_id}. device_code_auth.rs:67-95 */\nexport async function startDeviceCode(fetchImpl: CodexFetch = fetch): Promise<CodexDeviceStart> {\n const res = await fetchImpl(`${CODEX_AUTH_BASE}/deviceauth/usercode`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ client_id: CODEX_CLIENT_ID }),\n });\n if (res.status === 404) {\n throw new CodexDeviceError(\"device code login is not enabled for this Codex server\");\n }\n if (!res.ok) {\n throw new CodexDeviceError(`device code request failed with status ${res.status}`);\n }\n const body = (await res.json()) as {\n device_auth_id: string;\n user_code?: string;\n usercode?: string;\n interval?: string | number;\n };\n return {\n deviceAuthId: body.device_auth_id,\n userCode: body.user_code ?? body.usercode ?? \"\",\n verificationUri: CODEX_DEVICE_VERIFICATION_URL,\n intervalSeconds: normalizeInterval(body.interval),\n };\n}\n\n/** Clamp the poll interval to a sane minimum: a missing/0/NaN value must not become a 0-delay poll loop. */\nfunction normalizeInterval(raw: string | number | undefined): number {\n const n = typeof raw === \"string\" ? Number.parseInt(raw.trim(), 10) : raw;\n return typeof n === \"number\" && Number.isFinite(n) && n >= 1 ? n : 5;\n}\n\n/** Step 3 (single, non-blocking): POST {auth}/deviceauth/token. 403/404 => pending. device_code_auth.rs:106-145 */\nexport async function pollDeviceCode(\n input: { deviceAuthId: string; userCode: string },\n fetchImpl: CodexFetch = fetch,\n): Promise<CodexPollResult> {\n const res = await fetchImpl(`${CODEX_AUTH_BASE}/deviceauth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ device_auth_id: input.deviceAuthId, user_code: input.userCode }),\n });\n if (res.ok) {\n const body = (await res.json()) as { authorization_code: string; code_verifier: string };\n return {\n status: \"authorized\",\n authorizationCode: body.authorization_code,\n codeVerifier: body.code_verifier,\n };\n }\n if (res.status === 403 || res.status === 404) {\n return { status: \"pending\" };\n }\n throw new CodexDeviceError(`device auth failed with status ${res.status}`);\n}\n\n/** Step 4: POST {issuer}/oauth/token form-encoded grant_type=authorization_code. server.rs:732-766 */\nexport async function exchangeDeviceCode(\n input: { authorizationCode: string; codeVerifier: string },\n fetchImpl: CodexFetch = fetch,\n): Promise<CodexTokens> {\n const form = new URLSearchParams({\n grant_type: \"authorization_code\",\n code: input.authorizationCode,\n redirect_uri: CODEX_DEVICE_REDIRECT_URI,\n client_id: CODEX_CLIENT_ID,\n code_verifier: input.codeVerifier,\n });\n const res = await fetchImpl(CODEX_TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: form.toString(),\n });\n if (!res.ok) {\n throw new CodexDeviceError(`device code exchange failed with status ${res.status}`);\n }\n const body = (await res.json()) as {\n id_token: string;\n access_token: string;\n refresh_token: string;\n };\n return {\n idToken: body.id_token,\n accessToken: body.access_token,\n refreshToken: body.refresh_token,\n };\n}\n","export type CodexOperationFailureReason = \"network_error\" | \"timeout\";\n\n/**\n * Bound the complete provider operation, including response-body consumption.\n *\n * AbortController makes native fetch release its socket, while Promise.race is\n * the backstop for injected/custom fetch implementations that ignore `signal`.\n * The losing operation is rejection-handled and can never become an unhandled\n * promise after the caller has received the timeout result.\n */\nexport async function runBoundedCodexOperation<T>(\n operation: (signal: AbortSignal) => Promise<T>,\n timeoutMs: number,\n): Promise<{ ok: true; value: T } | { ok: false; reason: CodexOperationFailureReason }> {\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new Error(\"Codex operation timeout must be positive\");\n }\n\n const controller = new AbortController();\n let timedOut = false;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const work = operation(controller.signal).then(\n (value) => ({ ok: true as const, value }),\n () => ({\n ok: false as const,\n reason:\n timedOut || controller.signal.aborted ? (\"timeout\" as const) : (\"network_error\" as const),\n }),\n );\n const deadline = new Promise<{ ok: false; reason: \"timeout\" }>((resolve) => {\n timeout = setTimeout(() => {\n timedOut = true;\n controller.abort();\n resolve({ ok: false, reason: \"timeout\" });\n }, timeoutMs);\n });\n\n try {\n return await Promise.race([work, deadline]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n","// Token refresh + JWT helpers + permanent-failure classification.\n// Refresh is JSON-bodied (exchange is form-encoded — spec §1.1 contrasts these).\n// Classification mirrors codex-rs manager.rs:180-184.\n\nimport { CODEX_CLIENT_ID, CODEX_ID_TOKEN_AUTH_CLAIM, CODEX_TOKEN_URL } from \"./constants\";\nimport type { CodexFetch } from \"./device-code\";\nimport { runBoundedCodexOperation } from \"./bounded-operation\";\n\nconst CODEX_REFRESH_TIMEOUT_MS = 5_000;\n\n/** Permanent — the workspace must reconnect (status => needs_relogin). */\nexport class CodexReloginRequired extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CodexReloginRequired\";\n }\n}\n\n/** Transient — safe to retry later. */\nexport class CodexRefreshTransient extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CodexRefreshTransient\";\n }\n}\n\n/** Only present fields are returned (the server may rotate any subset). */\nexport type CodexRefreshTokens = {\n idToken?: string | undefined;\n accessToken?: string | undefined;\n refreshToken?: string | undefined;\n};\n\n/** POST {issuer}/oauth/token JSON {client_id, grant_type:\"refresh_token\", refresh_token}. manager.rs:1336-1340 */\nexport async function refreshCodexToken(\n refreshToken: string,\n fetchImpl: CodexFetch = fetch,\n timeoutMs = CODEX_REFRESH_TIMEOUT_MS,\n): Promise<CodexRefreshTokens> {\n const fetched = await runBoundedCodexOperation(async (signal) => {\n const res = await fetchImpl(CODEX_TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n client_id: CODEX_CLIENT_ID,\n grant_type: \"refresh_token\",\n refresh_token: refreshToken,\n }),\n signal,\n });\n return { res, text: await res.text() };\n }, timeoutMs);\n if (!fetched.ok) {\n throw new CodexRefreshTransient(`Codex token refresh ${fetched.reason}`);\n }\n const { res, text } = fetched.value;\n if (!res.ok) {\n const code = extractRefreshErrorCode(text);\n const msg = code ? PERMANENT_REFRESH_FAILURES[code] : undefined;\n if (msg) {\n throw new CodexReloginRequired(msg);\n }\n if (res.status === 401) {\n throw new CodexReloginRequired(\n \"Your Codex session could not be refreshed. Please disconnect and sign in again.\",\n );\n }\n throw new CodexRefreshTransient(`Failed to refresh Codex token: ${res.status}`);\n }\n const body = JSON.parse(text) as {\n id_token?: string;\n access_token?: string;\n refresh_token?: string;\n };\n return {\n idToken: body.id_token,\n accessToken: body.access_token,\n refreshToken: body.refresh_token,\n };\n}\n\n// Codes that mean the refresh token is permanently dead -> reconnect required.\n// Includes the standard OAuth `invalid_grant` alongside the Codex-specific codes.\nconst PERMANENT_REFRESH_FAILURES: Record<string, string> = {\n refresh_token_expired:\n \"Your Codex refresh token has expired. Please disconnect and sign in again.\",\n refresh_token_reused:\n \"Your Codex refresh token was already used. Please disconnect and sign in again.\",\n refresh_token_invalidated:\n \"Your Codex refresh token was revoked. Please disconnect and sign in again.\",\n invalid_grant: \"Your Codex session is no longer valid. Please disconnect and sign in again.\",\n};\n\n/** Pull an error code from any of the shapes the auth server may return. */\nfunction extractRefreshErrorCode(text: string): string | undefined {\n try {\n const o = JSON.parse(text) as Record<string, unknown>;\n const err = o.error;\n if (typeof err === \"string\") {\n return err; // { \"error\": \"invalid_grant\" }\n }\n if (err && typeof err === \"object\") {\n const e = err as Record<string, unknown>;\n if (typeof e.code === \"string\") return e.code; // { \"error\": { \"code\": \"...\" } }\n if (typeof e.type === \"string\") return e.type;\n }\n if (typeof o.code === \"string\") return o.code; // { \"code\": \"...\" }\n if (typeof o.type === \"string\") return o.type;\n } catch {\n /* not JSON */\n }\n return undefined;\n}\n\n/** Decode a JWT payload (base64url, no signature check). */\nexport function decodeJwtPayload(jwt: string): Record<string, unknown> | null {\n const part = jwt.split(\".\")[1];\n if (!part) {\n return null;\n }\n try {\n const json = Buffer.from(part.replace(/-/g, \"+\").replace(/_/g, \"/\"), \"base64\").toString(\"utf8\");\n return JSON.parse(json) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n/** access-token `exp` claim -> Date | null. token_data.rs:101-105 */\nexport function accessTokenExpiry(accessToken: string): Date | null {\n const payload = decodeJwtPayload(accessToken);\n return typeof payload?.exp === \"number\" ? new Date(payload.exp * 1000) : null;\n}\n\n/** id_token -> {chatgptAccountId, planType, isFedramp}. server.rs:827-832; token_data.rs:71-99 */\nexport function parseIdToken(idToken: string): {\n chatgptAccountId: string | null;\n planType: string | null;\n isFedramp: boolean;\n email: string | null;\n} {\n const payload = decodeJwtPayload(idToken);\n const auth = (payload?.[CODEX_ID_TOKEN_AUTH_CLAIM] ?? {}) as Record<string, unknown>;\n return {\n chatgptAccountId: typeof auth.chatgpt_account_id === \"string\" ? auth.chatgpt_account_id : null,\n planType: typeof auth.chatgpt_plan_type === \"string\" ? auth.chatgpt_plan_type : null,\n isFedramp: auth.chatgpt_account_is_fedramp === true,\n // The user's own email (standard OIDC `email` claim on the id_token); a\n // non-secret display field for the accounts UI. Null when absent.\n email: typeof payload?.email === \"string\" ? payload.email : null,\n };\n}\n","// Pure request-body + model-slug transforms for the ChatGPT/Codex backend.\n//\n// Per the verified NORMALIZATION VERDICT (CODEX-IMPL-PACKET §0), against our\n// @openai/agents stack we do EXACTLY this and no more:\n// - force store:false\n// - union include with reasoning.encrypted_content\n// - strip max_output_tokens / max_completion_tokens\n// - reasoning effort minimal -> low\n// - normalize the model slug (longest-prefix against the live catalog)\n// - strip every item `id` and `status` but PRESERVE `call_id`\n// We do NOT filter item_reference (the SDK never emits it) and do NOT convert\n// orphaned tool outputs (the SDK's runner already prunes by call_id).\n//\n// `status` is an output annotation SuperGrok (and some Responses items) persist\n// on messages / function_call / function_call_output. Codex's strict input\n// schema 400s `Unknown parameter: 'input[N].status'` — observed live on a\n// portable SuperGrok → Codex switch. Pairing uses `call_id`, never `status`.\n\nconst MINIMAL = \"minimal\";\n\n// The ChatGPT/Codex backend is a STRICT ALLOWLIST: it 400s on ANY top-level field\n// the Codex CLI itself does not send (confirmed live against the backend —\n// \"Unsupported parameter: temperature / top_p / metadata / previous_response_id /\n// logprobs / user / safety_identifier / truncation / max_tool_calls /\n// background / conversation\", and \"Unsupported tool type: mcp\").\n// `service_tier` is allowlisted for Codex Fast mode (`priority`; config may say\n// `fast` and maps to the same request value). Our @openai/agents stack adds\n// several other fields, so after our transforms we keep ONLY the codex\n// Responses payload fields (CODEX-SUBSCRIPTION-SPEC §1 field table).\nconst CODEX_ALLOWED_TOP_LEVEL_KEYS = new Set<string>([\n \"model\",\n \"instructions\",\n \"input\",\n \"tools\",\n \"tool_choice\",\n \"parallel_tool_calls\",\n \"reasoning\",\n \"store\",\n \"stream\",\n \"include\",\n \"prompt_cache_key\",\n \"text\",\n \"service_tier\",\n]);\n\n/** Mutates a parsed Responses request body in place and returns it. Pure + synchronous + unit-testable. */\nexport function normalizeCodexRequestBody(\n body: Record<string, unknown>,\n resolveModel: (slug: string) => string,\n): Record<string, unknown> {\n body.store = false; // ChatGPT backend REQUIRES store=false (spec §1.3)\n body.stream = true; // ChatGPT backend REQUIRES stream=true (confirmed live: 400 \"Stream must be set to true\").\n\n // include MUST contain reasoning.encrypted_content (stateless continuity, spec §1.6)\n const include = Array.isArray(body.include)\n ? (body.include as unknown[]).filter((v): v is string => typeof v === \"string\")\n : [];\n if (!include.includes(\"reasoning.encrypted_content\")) {\n include.push(\"reasoning.encrypted_content\");\n }\n body.include = include;\n\n // reasoning effort: minimal -> low (backend rejects minimal). spec §1.5\n const reasoning = body.reasoning as { effort?: string } | null | undefined;\n if (reasoning && reasoning.effort === MINIMAL) {\n reasoning.effort = \"low\";\n }\n\n // model slug: longest-prefix against the live catalog. spec §1.4\n if (typeof body.model === \"string\") {\n body.model = resolveModel(body.model);\n }\n\n // strip every item id and status; PRESERVE call_id. spec §1.6 / verdict §0(b)\n // (This also covers tool_search items: the backend accepts an id-less\n // tool_search_call/output pair correlated by call_id — verified live — and\n // stripping the provider-stored `tsc_…` id here sanitizes BOTH replay paths.)\n // `status` is output-only on Codex input items. New rows omit it at persist;\n // this wire strip remains defense for already-stored SuperGrok rows and\n // mid-turn SDK items.\n if (Array.isArray(body.input)) {\n for (const item of body.input as unknown[]) {\n if (!item || typeof item !== \"object\") {\n continue;\n }\n const record = item as Record<string, unknown>;\n if (\"id\" in record) {\n delete record.id;\n }\n if (\"status\" in record) {\n delete record.status;\n }\n // A replayed tool_search_call must carry `arguments` as an OBJECT — the\n // backend 400s a string (\"Invalid type for 'input[N].arguments': expected\n // an object\", verified live). The live wire emits an object (the SDK's\n // protocol schema is z.unknown() and round-trips it), so this only fires\n // for a defensively-stringified row; unparseable strings fall back to {}.\n if (record.type === \"tool_search_call\" && typeof record.arguments === \"string\") {\n try {\n const parsed = JSON.parse(record.arguments) as unknown;\n record.arguments = parsed && typeof parsed === \"object\" ? parsed : {};\n } catch {\n record.arguments = {};\n }\n }\n }\n }\n\n // Drop hosted-MCP tool entries: the backend rejects them (\"Unsupported tool\n // type: mcp\"). OpenGeni's MCP servers are client-connected, so their tools\n // already arrive as `function` tools — this only sheds a stray `mcp` entry.\n if (Array.isArray(body.tools)) {\n body.tools = (body.tools as unknown[]).filter(\n (t) => !(t && typeof t === \"object\" && (t as Record<string, unknown>).type === \"mcp\"),\n );\n }\n\n // Final allowlist: shed every other top-level field our @openai/agents stack\n // may have added (temperature, top_p, metadata, previous_response_id,\n // max_output_tokens, truncation, …) so the strict backend does not 400.\n for (const key of Object.keys(body)) {\n if (!CODEX_ALLOWED_TOP_LEVEL_KEYS.has(key)) {\n delete body[key];\n }\n }\n return body;\n}\n\n/**\n * Copy-on-write form for model clients that may retain converted input items.\n * Only records the mutable normalizer can touch are copied; large content,\n * tools, and unchanged protocol items remain shared immutable values.\n */\nexport function normalizedCodexRequestBody(\n body: Readonly<Record<string, unknown>>,\n resolveModel: (slug: string) => string,\n): Record<string, unknown> {\n const projected: Record<string, unknown> = { ...body };\n if (body.reasoning && typeof body.reasoning === \"object\" && !Array.isArray(body.reasoning)) {\n projected.reasoning = { ...(body.reasoning as Record<string, unknown>) };\n }\n if (Array.isArray(body.input)) {\n projected.input = body.input.map((item) => {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) return item;\n const record = item as Record<string, unknown>;\n return \"id\" in record ||\n \"status\" in record ||\n (record.type === \"tool_search_call\" && typeof record.arguments === \"string\")\n ? { ...record }\n : item;\n });\n }\n return normalizeCodexRequestBody(projected, resolveModel);\n}\n\n/**\n * Build a longest-prefix model resolver. Catalog slugs come from GET /models\n * (api-client.ts). One leading `namespace/` segment is stripped first; an\n * unknown slug returns the fallback (caller should log — spec §1.4 step 4).\n */\nexport function buildModelResolver(\n liveSlugs: readonly string[],\n fallbackSlug: string,\n): (slug: string) => string {\n return (requested: string): string => {\n const stripped = requested.includes(\"/\")\n ? requested.slice(requested.indexOf(\"/\") + 1)\n : requested;\n let best = \"\";\n for (const slug of liveSlugs) {\n if (stripped.startsWith(slug) && slug.length > best.length) {\n best = slug;\n }\n }\n return best || fallbackSlug;\n };\n}\n","// Normalizer for GET /wham/usage (P2). The live body exposes `used_percent` +\n// reset timing per window and NO raw used/limit/remaining integer counts (the only\n// raw counts live under `credits.approx_*_messages`). So the brief's\n// used/limit/remaining/percent/resetAt shape is SYNTHESIZED off `used_percent`,\n// with `percent` authoritative and used/limit/remaining carried on a normalized\n// 0–100 scale (limit = 100). `remaining = 100 - percent` is the P3 rotation key\n// (rotationStrategy:\"most_remaining\" ranks by max(min(fiveHour, weekly).remaining)).\n//\n// Windows are identified by `limit_window_seconds` (18000 ⇒ 5h, 604800 ⇒ weekly),\n// NEVER by position. A 200 may carry `limit_reached:true`; a 404 carries a\n// limit-reached body. The parser is zod over rate_limit.{primary,secondary}_window.\n\nimport * as z from \"zod/v4\";\nimport {\n parseCodexRateLimitResetCreditsSummary,\n type CodexRateLimitResetCreditsSummary,\n} from \"./reset-credits\";\n\n/** The 5-hour (primary) window's `limit_window_seconds`. */\nexport const CODEX_FIVE_HOUR_WINDOW_SECONDS = 18000;\n/** The weekly (secondary) window's `limit_window_seconds`. */\nexport const CODEX_WEEKLY_WINDOW_SECONDS = 604800;\n\n/** One normalized usage window (applied to BOTH primary_window and secondary_window). */\nexport type CodexUsageWindow = {\n used: number; // = percent (0–100 scale, limit = 100)\n limit: number; // = 100 (normalized; the provider gives no raw cap)\n remaining: number; // = 100 - percent ← P3 rotation key\n percent: number; // = used_percent (authoritative)\n resetAt: string | null; // ISO 8601, from reset_at*1000 (absolute), or derived from reset_after_seconds\n resetAfterSeconds: number | null; // from reset_after_seconds (skew-free countdown)\n limitWindowSeconds: number; // 18000 | 604800 — identify the window, never positional\n};\n\n/** One additional (per-feature) limit (forward-compat; P2 renders nothing from it). */\nexport type CodexAdditionalLimit = {\n limitName: string;\n meteredFeature: string;\n fiveHour: CodexUsageWindow | null;\n weekly: CodexUsageWindow | null;\n};\n\nexport type CodexUsageStatus = \"ok\" | \"limit_reached\" | \"error\" | \"no-data\";\n\n/** The normalized usage payload — the P2/P3 contract. */\nexport type CodexUsagePayload = {\n status: CodexUsageStatus;\n planType: string | null; // \"pro\" | \"plus\" | ... (rate row label)\n fiveHour: CodexUsageWindow | null; // ← rate_limit.primary_window (limitWindowSeconds === 18000)\n weekly: CodexUsageWindow | null; // ← rate_limit.secondary_window (604800)\n limitReached: boolean; // rate_limit.limit_reached || !rate_limit.allowed\n fetchedAt: string; // ISO; server stamp\n /**\n * Authoritative count-only reset-credit summary from the usage response.\n * Detail rows are fetched separately and are never synthesized from this.\n */\n rateLimitResetCredits: CodexRateLimitResetCreditsSummary | null;\n /** Present only on a refresh/auth failure path; carries the precise reason. */\n reason?: \"needs_relogin\" | undefined;\n // forward-compat, populated but unused in P2:\n additionalLimits?: CodexAdditionalLimit[] | undefined;\n credits?:\n | {\n hasCredits: boolean;\n unlimited: boolean;\n overageLimitReached: boolean;\n balance: string;\n }\n | undefined;\n};\n\n/**\n * Build a normalized window from the PERSISTED cache columns (used_percent +\n * absolute reset timestamp). The same 0–100 synthesis as the live path, with the\n * skew-free countdown derived from `resetAt − now` at read time. Returns null when\n * there is no cached percent yet. `limitWindowSeconds` is the constant that\n * identifies the window (18000 ⇒ 5h, 604800 ⇒ weekly).\n */\nexport function buildCodexUsageWindowFromCache(\n usedPercent: number | null | undefined,\n resetAt: Date | string | null | undefined,\n limitWindowSeconds: number,\n): CodexUsageWindow | null {\n if (typeof usedPercent !== \"number\") {\n return null;\n }\n const percent = clampPercent(usedPercent);\n const resetDate = resetAt ? new Date(resetAt) : null;\n const resetIso = resetDate && !Number.isNaN(resetDate.getTime()) ? resetDate.toISOString() : null;\n const resetAfterSeconds =\n resetDate && !Number.isNaN(resetDate.getTime())\n ? Math.max(0, Math.round((resetDate.getTime() - Date.now()) / 1000))\n : null;\n return {\n used: percent,\n limit: 100,\n remaining: 100 - percent,\n percent,\n resetAt: resetIso,\n resetAfterSeconds,\n limitWindowSeconds,\n };\n}\n\nconst windowSchema = z\n .object({\n used_percent: z.number().optional(),\n reset_after_seconds: z.number().optional(),\n reset_at: z.number().optional(),\n limit_window_seconds: z.number().optional(),\n })\n .nullish();\n\nconst rateLimitSchema = z\n .object({\n allowed: z.boolean().optional(),\n limit_reached: z.boolean().optional(),\n primary_window: windowSchema,\n secondary_window: windowSchema,\n })\n .nullish();\n\nconst additionalLimitSchema = z.object({\n limit_name: z.string().optional(),\n metered_feature: z.string().optional(),\n primary_window: windowSchema,\n secondary_window: windowSchema,\n});\n\nconst creditsSchema = z\n .object({\n has_credits: z.boolean().optional(),\n unlimited: z.boolean().optional(),\n overage_limit_reached: z.boolean().optional(),\n balance: z.union([z.string(), z.number()]).optional(),\n })\n .nullish();\n\nconst usageBodySchema = z.object({\n plan_type: z.string().nullish(),\n rate_limit: rateLimitSchema,\n additional_limits: z.array(additionalLimitSchema).nullish(),\n credits: creditsSchema,\n});\n\ntype RawWindow = z.infer<typeof windowSchema>;\n\nfunction clampPercent(value: number): number {\n if (!Number.isFinite(value)) return 0;\n return Math.min(100, Math.max(0, Math.round(value)));\n}\n\n/** Build a normalized window from a raw provider window, or null when it carries no percent. */\nfunction normalizeWindow(w: RawWindow): CodexUsageWindow | null {\n if (!w || typeof w.used_percent !== \"number\") {\n return null;\n }\n const percent = clampPercent(w.used_percent);\n const resetAfterSeconds =\n typeof w.reset_after_seconds === \"number\"\n ? Math.max(0, Math.round(w.reset_after_seconds))\n : null;\n let resetAt: string | null = null;\n if (typeof w.reset_at === \"number\") {\n resetAt = new Date(w.reset_at * 1000).toISOString(); // epoch SECONDS → ms\n } else if (resetAfterSeconds != null) {\n resetAt = new Date(Date.now() + resetAfterSeconds * 1000).toISOString();\n }\n return {\n used: percent,\n limit: 100,\n remaining: 100 - percent,\n percent,\n resetAt,\n resetAfterSeconds,\n limitWindowSeconds: typeof w.limit_window_seconds === \"number\" ? w.limit_window_seconds : 0,\n };\n}\n\n/**\n * Map the two named windows to fiveHour/weekly by `limit_window_seconds`\n * (18000 vs 604800), NEVER by position; fall back to position (primary ⇒ 5h,\n * secondary ⇒ weekly) only for a window whose limit_window_seconds is absent.\n */\nfunction pickWindows(\n primary: RawWindow,\n secondary: RawWindow,\n): { fiveHour: CodexUsageWindow | null; weekly: CodexUsageWindow | null } {\n let fiveHour: CodexUsageWindow | null = null;\n let weekly: CodexUsageWindow | null = null;\n // Track each unplaced window with the slot it came from, so the positional\n // fallback can place it (re-normalizing produces a fresh object that would\n // never match by reference — the bug this replaces).\n const unplaced: Array<{\n slot: \"primary\" | \"secondary\";\n window: CodexUsageWindow;\n }> = [];\n for (const [slot, raw] of [\n [\"primary\", primary],\n [\"secondary\", secondary],\n ] as const) {\n const nw = normalizeWindow(raw);\n if (!nw) continue;\n if (nw.limitWindowSeconds === CODEX_WEEKLY_WINDOW_SECONDS) {\n weekly = nw;\n } else if (nw.limitWindowSeconds === CODEX_FIVE_HOUR_WINDOW_SECONDS) {\n fiveHour = nw;\n } else {\n unplaced.push({ slot, window: nw });\n }\n }\n // Positional fallback for windows whose limit_window_seconds was absent/unknown\n // (primary ⇒ 5h, secondary ⇒ weekly).\n for (const { slot, window } of unplaced) {\n if (slot === \"primary\" && !fiveHour) fiveHour = window;\n else if (slot === \"secondary\" && !weekly) weekly = window;\n }\n return { fiveHour, weekly };\n}\n\n/**\n * Normalize a /wham/usage fetch result into the P2/P3 contract.\n *\n * @param httpStatus the HTTP status from fetchCodexUsage (404 ⇒ a limit body)\n * @param rawPayload the parsed JSON body (or null when the body was unreadable)\n */\nexport function normalizeCodexUsage(httpStatus: number, rawPayload: unknown): CodexUsagePayload {\n const fetchedAt = new Date().toISOString();\n const parsed = usageBodySchema.safeParse(rawPayload);\n const body = parsed.success ? parsed.data : null;\n\n const base: CodexUsagePayload = {\n status: \"no-data\",\n planType: body?.plan_type ?? null,\n fiveHour: null,\n weekly: null,\n limitReached: false,\n fetchedAt,\n rateLimitResetCredits: parseCodexRateLimitResetCreditsSummary(rawPayload),\n };\n\n // A non-404 HTTP error, or a body we could not parse at all, is an error state.\n if ((httpStatus >= 400 && httpStatus !== 404) || body == null) {\n return { ...base, status: \"error\" };\n }\n\n const rate = body.rate_limit ?? null;\n const { fiveHour, weekly } = pickWindows(\n rate?.primary_window ?? null,\n rate?.secondary_window ?? null,\n );\n const limitReached =\n !!(rate?.limit_reached || rate?.allowed === false) ||\n (fiveHour?.percent ?? 0) >= 100 ||\n (weekly?.percent ?? 0) >= 100;\n\n const additionalLimits: CodexAdditionalLimit[] | undefined = body.additional_limits\n ? body.additional_limits.map((al) => {\n const windows = pickWindows(al.primary_window ?? null, al.secondary_window ?? null);\n return {\n limitName: al.limit_name ?? \"\",\n meteredFeature: al.metered_feature ?? \"\",\n fiveHour: windows.fiveHour,\n weekly: windows.weekly,\n };\n })\n : undefined;\n\n const credits = body.credits\n ? {\n hasCredits: body.credits.has_credits ?? false,\n unlimited: body.credits.unlimited ?? false,\n overageLimitReached: body.credits.overage_limit_reached ?? false,\n balance: body.credits.balance != null ? String(body.credits.balance) : \"0\",\n }\n : undefined;\n\n // Status derivation: 404 ⇒ limit_reached; a 200 may still carry limit_reached;\n // succeeded-but-no-windows ⇒ no-data; otherwise ok.\n let status: CodexUsageStatus;\n if (httpStatus === 404 || limitReached) {\n status = \"limit_reached\";\n } else if (!fiveHour && !weekly) {\n status = \"no-data\";\n } else {\n status = \"ok\";\n }\n\n return {\n ...base,\n status,\n fiveHour,\n weekly,\n limitReached,\n ...(additionalLimits ? { additionalLimits } : {}),\n ...(credits ? { credits } : {}),\n };\n}\n\n/**\n * Whether one live /wham/usage response authoritatively contradicts an older\n * quota refusal. `ok` proves the base allowance is open; every surfaced\n * feature-specific window must also remain below exhaustion because the older\n * model refusal may have belonged to one of those limits. Missing/no-data and\n * malformed/error responses never repair cooldown state.\n */\nexport function codexUsageConfirmsQuotaAvailable(payload: CodexUsagePayload): boolean {\n if (payload.status !== \"ok\" || payload.limitReached) return false;\n return !payload.additionalLimits?.some(\n (limit) => (limit.fiveHour?.percent ?? 0) >= 100 || (limit.weekly?.percent ?? 0) >= 100,\n );\n}\n","// Exact Codex rust-v0.144.6 rate-limit-reset-credit protocol normalization.\n// Provenance: stable commit 5d1fbf26c43abc65a203928b2e31561cb039e06d;\n// protocol-bearing files are byte-identical from rust-v0.144.1 through v0.144.6.\n//\n// Upstream sources (stable tag target 5d1fbf26c43abc65a203928b2e31561cb039e06d):\n// - codex-rs/backend-client/src/types.rs\n// - codex-rs/backend-client/src/client/rate_limit_resets.rs\n// - codex-rs/app-server-protocol/src/protocol/v2/account.rs\n//\n// The backend wire is snake_case. Public OpenGeni callers only receive the\n// normalized camelCase types below. Unknown reset types/statuses remain visible\n// but fail closed as `unknown`; they are never made actionable by this parser.\n\nimport * as z from \"zod/v4\";\n\nexport const CODEX_RATE_LIMIT_RESET_OUTCOMES = [\n \"reset\",\n \"nothingToReset\",\n \"noCredit\",\n \"alreadyRedeemed\",\n] as const;\n\nexport type CodexRateLimitResetOutcome = (typeof CODEX_RATE_LIMIT_RESET_OUTCOMES)[number];\nexport type CodexRateLimitResetType = \"codexRateLimits\" | \"unknown\";\nexport type CodexRateLimitResetCreditStatus = \"available\" | \"redeeming\" | \"redeemed\" | \"unknown\";\n\nexport type CodexRateLimitResetCredit = {\n id: string;\n resetType: CodexRateLimitResetType;\n status: CodexRateLimitResetCreditStatus;\n /** Unix seconds, matching account/rateLimits/read in Codex v0.144.6. */\n grantedAt: number;\n /** Unix seconds, or null when the provider says the credit does not expire. */\n expiresAt: number | null;\n title: string | null;\n description: string | null;\n};\n\nexport type CodexRateLimitResetCreditsDetails = {\n availableCount: number;\n credits: CodexRateLimitResetCredit[];\n};\n\nexport type CodexRateLimitResetCreditsSummary = {\n availableCount: number;\n /** null means the provider supplied an authoritative count but no detail rows. */\n credits: null;\n};\n\nexport type CodexRateLimitResetConsumeResponse = {\n outcome: CodexRateLimitResetOutcome;\n};\n\nconst nonNegativeInteger = z.number().int().nonnegative();\nconst backendTimestamp = z.string().datetime({ offset: true });\n\nconst backendCreditSchema = z\n .object({\n id: z.string().min(1),\n reset_type: z.string().min(1),\n status: z.string().min(1),\n granted_at: backendTimestamp,\n expires_at: backendTimestamp.nullish(),\n title: z.string().nullish(),\n description: z.string().nullish(),\n })\n .passthrough();\n\nconst backendDetailsSchema = z\n .object({\n credits: z.array(backendCreditSchema),\n available_count: nonNegativeInteger,\n })\n .passthrough();\n\nconst backendUsageSummarySchema = z\n .object({\n rate_limit_reset_credits: z\n .object({ available_count: nonNegativeInteger })\n .passthrough()\n .nullish(),\n })\n .passthrough();\n\nconst backendConsumeOutcomes = [\n \"reset\",\n \"nothing_to_reset\",\n \"no_credit\",\n \"already_redeemed\",\n] as const;\n\nconst backendConsumeSchema = z\n .object({\n code: z.enum(backendConsumeOutcomes),\n // The app-server intentionally discards this field. OpenGeni also refetches\n // rather than inferring post-redemption state from it.\n windows_reset: nonNegativeInteger.default(0),\n })\n .passthrough();\n\nfunction normalizedResetType(value: string): CodexRateLimitResetType {\n return value === \"codex_rate_limits\" ? \"codexRateLimits\" : \"unknown\";\n}\n\nfunction normalizedCreditStatus(value: string): CodexRateLimitResetCreditStatus {\n if (value === \"available\" || value === \"redeeming\" || value === \"redeemed\") {\n return value;\n }\n return \"unknown\";\n}\n\n/** Parse the exact detailed-credit backend response. Unknown rows stay view-only. */\nexport function parseCodexRateLimitResetCreditsDetails(\n payload: unknown,\n): CodexRateLimitResetCreditsDetails | null {\n const parsed = backendDetailsSchema.safeParse(payload);\n if (!parsed.success) return null;\n return {\n availableCount: parsed.data.available_count,\n credits: parsed.data.credits.map((credit) => ({\n id: credit.id,\n resetType: normalizedResetType(credit.reset_type),\n status: normalizedCreditStatus(credit.status),\n grantedAt: Math.floor(Date.parse(credit.granted_at) / 1000),\n expiresAt:\n credit.expires_at == null ? null : Math.floor(Date.parse(credit.expires_at) / 1000),\n title: credit.title ?? null,\n description: credit.description ?? null,\n })),\n };\n}\n\n/** Parse the count-only summary carried by GET /wham/usage. */\nexport function parseCodexRateLimitResetCreditsSummary(\n payload: unknown,\n): CodexRateLimitResetCreditsSummary | null {\n const parsed = backendUsageSummarySchema.safeParse(payload);\n const availableCount = parsed.success\n ? parsed.data.rate_limit_reset_credits?.available_count\n : undefined;\n return availableCount === undefined ? null : { availableCount, credits: null };\n}\n\n/** Parse one of the exact four v0.144.6 consume outcomes. Unknowns fail closed. */\nexport function parseCodexRateLimitResetConsumeResponse(\n payload: unknown,\n): CodexRateLimitResetConsumeResponse | null {\n const parsed = backendConsumeSchema.safeParse(payload);\n if (!parsed.success) return null;\n const outcomes: Record<(typeof backendConsumeOutcomes)[number], CodexRateLimitResetOutcome> = {\n reset: \"reset\",\n nothing_to_reset: \"nothingToReset\",\n no_credit: \"noCredit\",\n already_redeemed: \"alreadyRedeemed\",\n };\n return { outcome: outcomes[parsed.data.code] };\n}\n","// Thin ChatGPT/Codex API client used outside the streamed turn: the login-check\n// (GET /codex/models) and the usage/limits readback (GET /wham/usage). spec §1.4, §1.8, §F.\n\nimport { CODEX_ORIGINATOR, CODEX_RESPONSES_BASE, CODEX_WHAM_BASE } from \"./constants\";\nimport type { CodexFetch } from \"./device-code\";\nimport {\n parseCodexRateLimitResetConsumeResponse,\n parseCodexRateLimitResetCreditsDetails,\n type CodexRateLimitResetConsumeResponse,\n type CodexRateLimitResetCreditsDetails,\n} from \"./reset-credits\";\nimport { runBoundedCodexOperation } from \"./bounded-operation\";\n\nexport type CodexAuthHeaders = {\n accessToken: string;\n chatgptAccountId: string | null;\n isFedramp: boolean;\n clientVersion: string;\n};\n\nconst CODEX_READ_TIMEOUT_MS = 5_000;\nconst RESET_CREDIT_DETAILS_TIMEOUT_MS = 5_000;\nconst RESET_CREDIT_CONSUME_TIMEOUT_MS = 10_000;\n\nexport type ResetCreditFetchFailureReason =\n | \"http_error\"\n | \"invalid_response\"\n | \"network_error\"\n | \"timeout\";\n\n/** Server-only headers shared by every ChatGPT/Codex subscription transport. */\nexport function codexSubscriptionHeaders(a: CodexAuthHeaders): Record<string, string> {\n return {\n Authorization: `Bearer ${a.accessToken}`,\n ...(a.chatgptAccountId ? { \"ChatGPT-Account-ID\": a.chatgptAccountId } : {}),\n originator: CODEX_ORIGINATOR,\n \"User-Agent\": `${CODEX_ORIGINATOR}/${a.clientVersion}`,\n version: a.clientVersion,\n ...(a.isFedramp ? { \"X-OpenAI-Fedramp\": \"true\" } : {}),\n };\n}\n\n/** GET /codex/models — login-check + live catalog. A 200 means the token is accepted. spec §1.4/§F */\nexport async function fetchCodexModels(\n a: CodexAuthHeaders,\n fetchImpl: CodexFetch = fetch,\n timeoutMs = CODEX_READ_TIMEOUT_MS,\n): Promise<{ ok: boolean; status: number; slugs: string[] }> {\n const fetched = await runBoundedCodexOperation(async (signal) => {\n const res = await fetchImpl(\n `${CODEX_RESPONSES_BASE}/models?client_version=${encodeURIComponent(a.clientVersion)}`,\n { method: \"GET\", headers: codexSubscriptionHeaders(a), signal },\n );\n if (!res.ok) {\n await res.arrayBuffer().catch(() => undefined);\n return { ok: false, status: res.status, slugs: [] as string[] };\n }\n const body = (await res.json()) as { models?: Array<{ slug?: string }> };\n const slugs = (body.models ?? [])\n .map((model) => model.slug)\n .filter((slug): slug is string => typeof slug === \"string\");\n return { ok: true, status: res.status, slugs };\n }, timeoutMs);\n return fetched.ok ? fetched.value : { ok: false, status: 0, slugs: [] };\n}\n\n/** GET /wham/usage — authoritative limits. NB the WHAM base is /backend-api, NOT /codex (spec §1.8a). */\nexport async function fetchCodexUsage(\n a: CodexAuthHeaders,\n fetchImpl: CodexFetch = fetch,\n timeoutMs = CODEX_READ_TIMEOUT_MS,\n): Promise<{ status: number; payload: unknown }> {\n const fetched = await runBoundedCodexOperation(async (signal) => {\n const res = await fetchImpl(`${CODEX_WHAM_BASE}/wham/usage`, {\n method: \"GET\",\n headers: codexSubscriptionHeaders(a),\n signal,\n });\n // A 404 may carry a usage-limit body; the route layer normalizes it to a limits state (spec §1.8c).\n const payload = res.ok || res.status === 404 ? await res.json().catch(() => null) : null;\n if (!res.ok && res.status !== 404) await res.arrayBuffer().catch(() => undefined);\n return { status: res.status, payload };\n }, timeoutMs);\n if (!fetched.ok) throw new Error(`Codex usage request ${fetched.reason}`);\n return fetched.value;\n}\n\n/**\n * GET /wham/rate-limit-reset-credits — detailed earned reset credits.\n *\n * A non-2xx or malformed body returns an explicit non-ok result. The caller may\n * fall back to the count-only summary embedded in /wham/usage, but must never\n * invent actionable rows from that count.\n */\nexport async function fetchCodexRateLimitResetCredits(\n a: CodexAuthHeaders,\n fetchImpl: CodexFetch = fetch,\n timeoutMs = RESET_CREDIT_DETAILS_TIMEOUT_MS,\n): Promise<\n | { ok: true; status: number; details: CodexRateLimitResetCreditsDetails }\n | { ok: false; status: number; reason: ResetCreditFetchFailureReason }\n> {\n const fetched = await runBoundedCodexOperation(async (signal) => {\n const res = await fetchImpl(`${CODEX_WHAM_BASE}/wham/rate-limit-reset-credits`, {\n method: \"GET\",\n headers: codexSubscriptionHeaders(a),\n signal,\n });\n if (!res.ok) {\n // Drain the body without retaining/logging it. Provider error bodies may\n // contain account-specific details and are not part of this contract.\n await res.arrayBuffer().catch(() => undefined);\n return {\n ok: false as const,\n status: res.status,\n reason: \"http_error\" as const,\n };\n }\n const details = parseCodexRateLimitResetCreditsDetails(await res.json().catch(() => null));\n return details\n ? { ok: true as const, status: res.status, details }\n : {\n ok: false as const,\n status: res.status,\n reason: \"invalid_response\" as const,\n };\n }, timeoutMs);\n return fetched.ok ? fetched.value : { ok: false, status: 0, reason: fetched.reason };\n}\n\n/**\n * POST /wham/rate-limit-reset-credits/consume with the exact v0.144.6 body.\n * `idempotencyKey` identifies one logical human redemption and MUST be reused\n * by the server on retries. Supplying `creditId` is preferred; omission leaves\n * provider selection in control and is therefore not used by OpenGeni's\n * human-only flow.\n */\nexport async function consumeCodexRateLimitResetCredit(\n a: CodexAuthHeaders,\n input: { idempotencyKey: string; creditId?: string | undefined },\n fetchImpl: CodexFetch = fetch,\n timeoutMs = RESET_CREDIT_CONSUME_TIMEOUT_MS,\n): Promise<\n | { ok: true; status: number; result: CodexRateLimitResetConsumeResponse }\n | {\n ok: false;\n status: number;\n reason: ResetCreditFetchFailureReason | \"invalid_request\";\n }\n> {\n if (input.idempotencyKey.length === 0 || input.creditId === \"\") {\n return { ok: false, status: 0, reason: \"invalid_request\" };\n }\n const fetched = await runBoundedCodexOperation(async (signal) => {\n const res = await fetchImpl(`${CODEX_WHAM_BASE}/wham/rate-limit-reset-credits/consume`, {\n method: \"POST\",\n headers: {\n ...codexSubscriptionHeaders(a),\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n redeem_request_id: input.idempotencyKey,\n ...(input.creditId ? { credit_id: input.creditId } : {}),\n }),\n signal,\n });\n if (!res.ok) {\n await res.arrayBuffer().catch(() => undefined);\n return {\n ok: false as const,\n status: res.status,\n reason: \"http_error\" as const,\n };\n }\n const result = parseCodexRateLimitResetConsumeResponse(await res.json().catch(() => null));\n return result\n ? { ok: true as const, status: res.status, result }\n : {\n ok: false as const,\n status: res.status,\n reason: \"invalid_response\" as const,\n };\n }, timeoutMs);\n return fetched.ok ? fetched.value : { ok: false, status: 0, reason: fetched.reason };\n}\n","// Per-request Codex context, carried via AsyncLocalStorage.\n//\n// The runtime caches one OpenAI client per provider id (process-wide), so the\n// per-workspace token must NOT be baked into the client. Instead the worker sets\n// this context around the model run, and codexSubscriptionFetch reads it at call\n// time — one cached client, correct per-workspace token, no cross-tenant leak.\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport type CodexTokenSnapshot = {\n accessToken: string;\n chatgptAccountId: string | null;\n isFedramp: boolean;\n};\n\n/**\n * Multi-account P4 (Part A): a full usage snapshot scraped FOR FREE from the\n * `x-codex-primary-*` / `x-codex-secondary-*` response headers the codex backend\n * stamps on every `/codex/responses` turn (success AND 429 hard-cap). Integer-\n * identical to GET /wham/usage but with zero extra round-trip. parseCodexUsageHeaders\n * returns this only when BOTH windows parse, so a write is always a full 5-column\n * snapshot (no partial-window clobber). Shape mirrors db's CodexAccountUsageSnapshot\n * (non-null here: a partial read is filtered to null upstream, never half-written).\n */\nexport type CodexUsageHeaderSnapshot = {\n primaryUsedPercent: number;\n primaryResetAt: Date;\n secondaryUsedPercent: number;\n secondaryResetAt: Date;\n checkedAt: Date;\n};\n\nexport type CodexResponseTimeoutClass = \"connect\" | \"headers\" | \"idle_stream\" | \"whole_request\";\n\nexport type CodexResponseTimeoutPolicy = {\n /** Maximum wait for response headers, including DNS/TCP/TLS establishment. */\n headersTimeoutMs: number;\n /** Maximum silence between response-body chunks after headers arrive. */\n streamIdleTimeoutMs: number;\n /** Maximum wall time for one logical Responses request. */\n wholeRequestTimeoutMs: number;\n /**\n * Reserved compatibility field. It is currently normalized to zero because\n * an absent response does not prove that the provider never accepted a\n * request, so automatic replay is not safe without an operation receipt.\n */\n noByteRetries: number;\n retryBackoffMs: number;\n};\n\nexport type CodexModelRequestEvent = {\n requestId: string;\n transportAttempt: number;\n phase: \"started\" | \"headers\" | \"first_byte\" | \"completed\" | \"failed\" | \"timed_out\";\n model?: string;\n durationMs: number;\n responseObserved: boolean;\n timeoutPolicy: CodexResponseTimeoutPolicy;\n timeoutClass?: CodexResponseTimeoutClass;\n providerRequestId?: string;\n status?: number;\n willRetry?: boolean;\n};\n\nexport type CodexRequestOpaqueArtifacts = {\n requestId: string;\n fingerprints: readonly string[];\n};\n\n/**\n * Durable execution fence invoked immediately before a provider request is\n * dispatched. Errors are intentionally not classified here: the owning worker\n * must receive typed lease-loss failures unchanged.\n */\nexport type CodexBeforeProviderDispatch = () => Promise<void> | void;\n\nexport type CodexRequestPreparationPhase =\n | \"transport_entry\"\n | \"credential_ready\"\n | \"wire_request_ready\";\n\nexport type CodexRequestContext = {\n clientVersion: string;\n /**\n * Stable per-session affinity id, sent as the `session_id` header on every\n * request. This is the backend's STICKY CACHE-ROUTING key — measured\n * 2026-07-12 with byte-identical ~99k-token gpt-5.6-sol requests on one idle\n * account: without the header, repeat requests hit the prompt cache ~50% of\n * the time (a per-request routing lottery across cache shards; matches the\n * prod fleet's 48.6%); with a stable session_id, 10/10 requests hit at the\n * 99.0% ceiling — Codex CLI parity (the CLI always sends it; its own last-3d\n * token-weighted rate here is 94%). `prompt_cache_key` in the body only\n * influences routing and does NOT pin it. Use the SAME value as\n * prompt_cache_key (the OpenGeni sessionId) so routing and cache key agree.\n */\n sessionId?: string;\n /** Worker-supplied: proactive refresh + single-flight + db persist. */\n getToken: () => Promise<CodexTokenSnapshot>;\n /** Forced refresh used for the 401 retry. */\n refresh: () => Promise<CodexTokenSnapshot>;\n /** Model-slug resolver (longest-prefix against the live catalog). */\n resolveModel: (slug: string) => string;\n /**\n * Multi-account P4 (Part A): fire-and-forget usage-header sink. Called by\n * codexSubscriptionFetch on EVERY response (sync, non-throwing, never awaited)\n * with the parsed full-window snapshot. The worker records the latest into the\n * P2 usage cache once per turn in its `finally` — packages/codex stays db-free.\n */\n onUsageHeaders?: (snapshot: CodexUsageHeaderSnapshot) => void;\n /** Optional per-run override, primarily for deterministic transport tests. */\n responseTimeoutPolicy?: Partial<CodexResponseTimeoutPolicy>;\n /**\n * Synchronous, best-effort diagnostics for the request lifecycle. This hook\n * runs before the durable audit sink and MUST remain non-blocking: a throw is\n * swallowed by the transport and it must never receive request bodies/auth.\n */\n onModelRequestDiagnostic?: (event: CodexModelRequestEvent) => void;\n /** Bounded synchronous checkpoints for pre-network request preparation. */\n onRequestPreparationDiagnostic?: (phase: CodexRequestPreparationPhase) => void;\n /** Worker-owned durable audit sink; payloads never contain request bodies or auth. */\n onModelRequestEvent?: (event: CodexModelRequestEvent) => Promise<void> | void;\n /** Exact opaque artifacts on the normalized wire request, never their ciphertext. */\n onRequestOpaqueArtifacts?: (artifacts: CodexRequestOpaqueArtifacts) => void;\n /**\n * Durable execution fence. Runs after request preparation and audit, and\n * immediately before each actual provider dispatch, including auth retries.\n */\n beforeProviderDispatch?: CodexBeforeProviderDispatch;\n /** Stable request identity supplied by the owning durable execution. */\n nextRequestId?: () => string;\n /**\n * Optional Codex beta feature flags advertised as `x-codex-beta-features`\n * (comma-separated). Used for remote compaction v2 (`remote_compaction_v2`).\n */\n betaFeatures?: readonly string[];\n /**\n * Optional turn analytics / routing metadata sent as `x-codex-turn-metadata`\n * (JSON). Body `metadata` is stripped by normalize — never put request_kind there.\n */\n turnMetadata?: Record<string, unknown>;\n};\n\nexport const codexRequestStorage = new AsyncLocalStorage<CodexRequestContext>();\n\n/** Nest a Codex ALS scope with header overrides (e.g. remote compaction v2). */\nexport function withCodexRequestOverrides<T>(\n overrides: Pick<CodexRequestContext, \"betaFeatures\" | \"turnMetadata\">,\n fn: () => T,\n): T {\n const current = codexRequestStorage.getStore();\n if (!current) return fn();\n return codexRequestStorage.run({ ...current, ...overrides }, fn);\n}\n","import {\n CODEX_RESPONSE_HEADERS_TIMEOUT_MS,\n CODEX_RESPONSE_NO_BYTE_RETRIES,\n CODEX_RESPONSE_RETRY_BACKOFF_MS,\n CODEX_RESPONSE_STREAM_IDLE_TIMEOUT_MS,\n CODEX_RESPONSE_WHOLE_TIMEOUT_MS,\n} from \"./constants\";\nimport type { CodexResponseTimeoutClass, CodexResponseTimeoutPolicy } from \"./request-context\";\n\nexport const CODEX_RESPONSE_TIMEOUT_ERROR_TYPE = \"opengeni_codex_response_timeout\";\n\nexport const DEFAULT_CODEX_RESPONSE_TIMEOUT_POLICY: CodexResponseTimeoutPolicy = Object.freeze({\n headersTimeoutMs: CODEX_RESPONSE_HEADERS_TIMEOUT_MS,\n streamIdleTimeoutMs: CODEX_RESPONSE_STREAM_IDLE_TIMEOUT_MS,\n wholeRequestTimeoutMs: CODEX_RESPONSE_WHOLE_TIMEOUT_MS,\n noByteRetries: CODEX_RESPONSE_NO_BYTE_RETRIES,\n retryBackoffMs: CODEX_RESPONSE_RETRY_BACKOFF_MS,\n});\n\nfunction positiveFinite(value: number | undefined, fallback: number): number {\n return value !== undefined && Number.isFinite(value) && value > 0 ? value : fallback;\n}\n\nexport function resolveCodexResponseTimeoutPolicy(\n override: Partial<CodexResponseTimeoutPolicy> | undefined,\n): CodexResponseTimeoutPolicy {\n return {\n headersTimeoutMs: positiveFinite(\n override?.headersTimeoutMs,\n DEFAULT_CODEX_RESPONSE_TIMEOUT_POLICY.headersTimeoutMs,\n ),\n streamIdleTimeoutMs: positiveFinite(\n override?.streamIdleTimeoutMs,\n DEFAULT_CODEX_RESPONSE_TIMEOUT_POLICY.streamIdleTimeoutMs,\n ),\n wholeRequestTimeoutMs: positiveFinite(\n override?.wholeRequestTimeoutMs,\n DEFAULT_CODEX_RESPONSE_TIMEOUT_POLICY.wholeRequestTimeoutMs,\n ),\n // Automatic replay is fail-closed until the provider operation can be\n // durably read/reconciled. Keep the field for policy/event compatibility,\n // but never let a caller opt back into an unproved retry.\n noByteRetries: 0,\n retryBackoffMs:\n override?.retryBackoffMs !== undefined &&\n Number.isFinite(override.retryBackoffMs) &&\n override.retryBackoffMs >= 0\n ? override.retryBackoffMs\n : DEFAULT_CODEX_RESPONSE_TIMEOUT_POLICY.retryBackoffMs,\n };\n}\n\nexport class CodexResponseTimeoutError extends Error {\n readonly code = CODEX_RESPONSE_TIMEOUT_ERROR_TYPE;\n readonly type = CODEX_RESPONSE_TIMEOUT_ERROR_TYPE;\n\n constructor(\n readonly timeoutClass: CodexResponseTimeoutClass,\n readonly requestId: string,\n readonly responseObserved: boolean,\n message = `Codex response ${timeoutClass.replaceAll(\"_\", \" \")} timed out`,\n ) {\n super(message);\n this.name = \"CodexResponseTimeoutError\";\n }\n}\n\nexport type CodexResponseTimeoutInfo = {\n timeoutClass: CodexResponseTimeoutClass;\n requestId: string | null;\n responseObserved: boolean;\n message: string;\n};\n\nfunction parseTimeoutClass(value: unknown): CodexResponseTimeoutClass | null {\n return value === \"connect\" ||\n value === \"headers\" ||\n value === \"idle_stream\" ||\n value === \"whole_request\"\n ? value\n : null;\n}\n\n/**\n * Recover structured transport timeouts through SDK wrapping. The optional\n * legacy match is deliberately opt-in: `Request timed out.` alone has no\n * provider provenance and the worker enables it only for a confirmed Codex\n * subscription turn.\n */\nexport function classifyCodexResponseTimeoutError(\n error: unknown,\n options: { allowLegacyRequestTimeout?: boolean } = {},\n): CodexResponseTimeoutInfo | null {\n let current: unknown = error;\n for (let depth = 0; depth < 8 && current && typeof current === \"object\"; depth += 1) {\n const value = current as Record<string, unknown>;\n const nested =\n value.error && typeof value.error === \"object\"\n ? (value.error as Record<string, unknown>)\n : undefined;\n const type =\n (typeof value.type === \"string\" ? value.type : undefined) ??\n (typeof value.code === \"string\" ? value.code : undefined) ??\n (typeof nested?.type === \"string\" ? nested.type : undefined) ??\n (typeof nested?.code === \"string\" ? nested.code : undefined);\n if (type === CODEX_RESPONSE_TIMEOUT_ERROR_TYPE || value.name === \"CodexResponseTimeoutError\") {\n const klass =\n parseTimeoutClass(value.timeoutClass) ??\n parseTimeoutClass(nested?.timeout_class) ??\n \"headers\";\n return {\n timeoutClass: klass,\n requestId:\n (typeof value.requestId === \"string\" ? value.requestId : undefined) ??\n (typeof nested?.request_id === \"string\" ? nested.request_id : null),\n responseObserved:\n typeof value.responseObserved === \"boolean\"\n ? value.responseObserved\n : nested?.response_observed === true,\n message:\n (typeof value.message === \"string\" ? value.message : undefined) ??\n (typeof nested?.message === \"string\" ? nested.message : \"Codex response timed out\"),\n };\n }\n current = value.cause;\n }\n\n if (options.allowLegacyRequestTimeout && error && typeof error === \"object\") {\n const value = error as Record<string, unknown>;\n if (\n value.name === \"APIConnectionTimeoutError\" ||\n (value.message === \"Request timed out.\" && value.name === \"Error\")\n ) {\n return {\n timeoutClass: \"headers\",\n requestId: null,\n responseObserved: false,\n message: String(value.message ?? \"Request timed out.\"),\n };\n }\n }\n return null;\n}\n\nexport function isPreHeadersTimeoutError(error: unknown): CodexResponseTimeoutClass | null {\n const structured = classifyCodexResponseTimeoutError(error);\n if (structured && !structured.responseObserved) {\n return structured.timeoutClass;\n }\n if (!error || typeof error !== \"object\") return null;\n const value = error as Record<string, unknown>;\n const code = typeof value.code === \"string\" ? value.code : \"\";\n const name = typeof value.name === \"string\" ? value.name : \"\";\n const message = typeof value.message === \"string\" ? value.message : String(error);\n if (/^(?:ETIMEDOUT|UND_ERR_CONNECT_TIMEOUT)$/i.test(code) || /ConnectTimeout/i.test(name)) {\n return \"connect\";\n }\n return /connect(?:ion)?[^.]*timed?\\s*out/i.test(`${name} ${message}`) ? \"connect\" : null;\n}\n","// codexSubscriptionFetch — the transport installed on the OpenAI client for the\n// \"codex-subscription\" provider. Mirrors the runtime's computerCallNormalizingFetch\n// pattern: wraps a base fetch and returns a (input, init) => Promise<Response>.\n//\n// It reads the per-request Codex context from AsyncLocalStorage at CALL time, so a\n// single process-cached client serves every workspace with the correct token. It:\n// - rewrites /responses -> /codex/responses\n// - injects the subscription auth headers (omits OpenAI-Beta on SSE; spec §1.2)\n// - normalizes the request body (spec §0 verdict)\n// - retries once on 401 after a forced token refresh (spec §1.9)\n// Stream parsing is delegated to the SDK (SSE passthrough; spec §0(d)).\n\nimport { randomUUID } from \"node:crypto\";\nimport { CODEX_ORIGINATOR } from \"./constants\";\nimport { normalizeCodexRequestBody } from \"./normalize\";\nimport { opaqueProviderArtifactFingerprints } from \"./opaque-artifact\";\nimport {\n codexRequestStorage,\n type CodexModelRequestEvent,\n type CodexRequestPreparationPhase,\n type CodexRequestContext,\n type CodexResponseTimeoutPolicy,\n type CodexTokenSnapshot,\n type CodexUsageHeaderSnapshot,\n} from \"./request-context\";\n\nfunction emitRequestPreparationDiagnostic(\n ctx: CodexRequestContext,\n phase: CodexRequestPreparationPhase,\n): void {\n try {\n ctx.onRequestPreparationDiagnostic?.(phase);\n } catch {\n // Diagnostic observers are non-blocking and cannot affect transport.\n }\n}\nimport {\n CODEX_RESPONSE_TIMEOUT_ERROR_TYPE,\n CodexResponseTimeoutError,\n classifyCodexResponseTimeoutError,\n isPreHeadersTimeoutError,\n resolveCodexResponseTimeoutPolicy,\n} from \"./response-timeout\";\n\nexport type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n\n/**\n * Internal provenance marker copied onto buffered non-OK Codex responses.\n * OpenAI's APIError preserves response headers, which lets the worker\n * distinguish a model-provider refusal from an unrelated sandbox/MCP HTTP\n * error that happened during the same Codex turn.\n */\nexport const CODEX_TRANSPORT_ERROR_HEADER = \"x-opengeni-codex-transport-error\";\n/** Internal transport handoff; always removed before network I/O. */\nexport const CODEX_REQUEST_BODY_NORMALIZED_HEADER = \"x-opengeni-request-body-normalized\";\nconst REPLAYABLE_REQUEST_BODY_FACTORY = Symbol.for(\"opengeni.replayable-request-body-factory\");\n\ntype ReplayableRequestInit = RequestInit & {\n [REPLAYABLE_REQUEST_BODY_FACTORY]?: () => ReadableStream<Uint8Array>;\n};\n/** Internal resolved-model handoff; always removed before network I/O. */\nexport const CODEX_REQUEST_MODEL_HEADER = \"x-opengeni-request-model\";\n/** Internal durable request-identity handoff; always removed before network I/O. */\nexport const CODEX_REQUEST_ID_HEADER = \"x-opengeni-request-id\";\n/** Internal original response-mode handoff; always removed before network I/O. */\nexport const CODEX_REQUEST_CALLER_STREAM_HEADER = \"x-opengeni-request-caller-stream\";\nconst MAX_CODEX_ERROR_BODY_BYTES = 64 * 1024;\n\nfunction headersCarryCodexTransportMarker(headers: unknown): boolean {\n if (!headers || typeof headers !== \"object\") return false;\n const getter = (headers as { get?: unknown }).get;\n if (typeof getter === \"function\") {\n return getter.call(headers, CODEX_TRANSPORT_ERROR_HEADER) === \"1\";\n }\n const record = headers as Record<string, unknown>;\n return (\n record[CODEX_TRANSPORT_ERROR_HEADER] === \"1\" ||\n record[CODEX_TRANSPORT_ERROR_HEADER.toLowerCase()] === \"1\"\n );\n}\n\n/** True only for an error produced from this Codex transport's non-OK response. */\nexport function isCodexTransportError(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; depth < 6 && current && typeof current === \"object\"; depth += 1) {\n const value = current as Record<string, unknown>;\n if (headersCarryCodexTransportMarker(value.headers)) return true;\n current = value.cause;\n }\n return false;\n}\n\nexport type CodexEncryptedArtifactRejection = {\n status: 400;\n kind: \"encrypted_content_rejected\";\n};\n\n/**\n * Classify only the provider's definitive request rejection for an opaque\n * reasoning artifact that it can no longer decrypt/parse. A Codex transport\n * marker plus HTTP 400 proves this request was rejected before inference; the\n * semantic match prevents unrelated malformed prompts from entering recovery.\n */\nexport function classifyCodexEncryptedArtifactRejection(\n error: unknown,\n): CodexEncryptedArtifactRejection | null {\n if (!isCodexTransportError(error)) return null;\n let current: unknown = error;\n for (let depth = 0; depth < 6 && current && typeof current === \"object\"; depth += 1) {\n const value = current as Record<string, unknown>;\n const body =\n value.error && typeof value.error === \"object\"\n ? (value.error as Record<string, unknown>)\n : null;\n const status = Number(value.status ?? body?.status);\n const message = [\n typeof value.message === \"string\" ? value.message : \"\",\n typeof body?.message === \"string\" ? body.message : \"\",\n typeof value.code === \"string\" ? value.code : \"\",\n typeof body?.code === \"string\" ? body.code : \"\",\n typeof value.type === \"string\" ? value.type : \"\",\n typeof body?.type === \"string\" ? body.type : \"\",\n ]\n .join(\" \")\n .toLowerCase();\n const unsupportedFieldShape =\n /(?:invalid value|supported values?|unsupported|unknown (?:field|parameter|value))/.test(\n message,\n );\n if (\n status === 400 &&\n !unsupportedFieldShape &&\n /(?:encrypted[_ ]content|encrypted reasoning|reasoning artifact)/.test(message) &&\n /(?:decrypt(?:ed|ion)?|could not be parsed|cannot be parsed|failed to parse)/.test(message)\n ) {\n return { status: 400, kind: \"encrypted_content_rejected\" };\n }\n current = value.cause;\n }\n return null;\n}\n\n/** Parse an integer header value; null when absent or not a finite integer. */\nfunction parseIntHeader(value: string | null): number | null {\n if (value === null) {\n return null;\n }\n const n = Number.parseInt(value.trim(), 10);\n return Number.isFinite(n) ? n : null;\n}\n\n/**\n * Resolve a window reset instant from the response headers: prefer the absolute\n * `*-reset-at` (epoch SECONDS → ms, mirroring codex-token-resolver's usage parse),\n * else the relative `*-reset-after-seconds` from now, else now (a missing reset\n * reads as \"already cleared\" — availableAt treats an elapsed reset as a bounded\n * default cooldown, so the ranker never strands on it).\n */\nfunction resolveResetAt(headers: Headers, atKey: string, afterKey: string, nowMs: number): Date {\n const at = parseIntHeader(headers.get(atKey));\n if (at !== null) {\n return new Date(at * 1000);\n }\n const after = parseIntHeader(headers.get(afterKey));\n if (after !== null) {\n return new Date(nowMs + after * 1000);\n }\n return new Date(nowMs);\n}\n\n/**\n * Multi-account P4 (Part A): scrape the full usage snapshot the codex backend\n * stamps on every `/codex/responses` response in `x-codex-primary-*` /\n * `x-codex-secondary-*` headers (integer-identical to GET /wham/usage, for free).\n *\n * CRITICAL clobber-fix: return null unless BOTH windows expose a valid used-percent\n * integer. recordCodexAccountUsage writes all five columns unconditionally, so a\n * primary-only snapshot would null the weekly column. Both windows are always\n * emitted together on `/codex/responses`; gating on both makes every write a full\n * 5-column snapshot byte-identical to the poll path, and a malformed/absent header\n * set simply no-ops (the /wham/usage poll fallback still covers it).\n */\nexport function parseCodexUsageHeaders(headers: Headers): CodexUsageHeaderSnapshot | null {\n const primaryUsedPercent = parseIntHeader(headers.get(\"x-codex-primary-used-percent\"));\n const secondaryUsedPercent = parseIntHeader(headers.get(\"x-codex-secondary-used-percent\"));\n if (primaryUsedPercent === null || secondaryUsedPercent === null) {\n return null; // not a full both-windows snapshot — no-op (never a partial clobber)\n }\n const nowMs = Date.now();\n return {\n primaryUsedPercent,\n primaryResetAt: resolveResetAt(\n headers,\n \"x-codex-primary-reset-at\",\n \"x-codex-primary-reset-after-seconds\",\n nowMs,\n ),\n secondaryUsedPercent,\n secondaryResetAt: resolveResetAt(\n headers,\n \"x-codex-secondary-reset-at\",\n \"x-codex-secondary-reset-after-seconds\",\n nowMs,\n ),\n checkedAt: new Date(nowMs),\n };\n}\n\ntype RequestAudit = {\n ctx: CodexRequestContext;\n requestId: string;\n transportAttempt: number;\n model?: string;\n logicalStartedAt: number;\n attemptStartedAtMonotonic: number;\n policy: CodexResponseTimeoutPolicy;\n terminalOutcome: RequestTerminalOutcome | null;\n};\n\ntype RequestTerminalOutcome = \"completed\" | \"failed\" | \"timed_out\";\n\ntype SemanticTerminalState = {\n phase: \"completed\" | \"failed\" | null;\n /** Non-streaming callers must parse the complete SSE body before settling. */\n deferTransportTerminal: boolean;\n};\n\ntype CodexSseEvent = {\n type?: string;\n response?: Record<string, unknown>;\n error?: unknown;\n code?: unknown;\n message?: unknown;\n param?: unknown;\n item?: unknown;\n};\n\ntype CodexSseTerminalClassification =\n | { phase: \"completed\" }\n | {\n phase: \"failed\";\n rawError: unknown;\n fallbackCode: string;\n fallbackMessage: string;\n }\n | null;\n\nfunction classifyCodexSseTerminal(ev: CodexSseEvent): CodexSseTerminalClassification {\n if (ev.type === \"response.failed\") {\n return {\n phase: \"failed\",\n rawError: ev.response?.error,\n fallbackCode: \"response_failed\",\n fallbackMessage: \"The Codex response failed\",\n };\n }\n if (ev.type === \"error\" || ev.type === \"response.error\") {\n return {\n phase: \"failed\",\n rawError: ev.error ?? ev.response?.error ?? ev,\n fallbackCode: \"response_error\",\n fallbackMessage: \"The Codex response stream reported an error\",\n };\n }\n if (ev.type === \"response.incomplete\") {\n const details = ev.response?.incomplete_details;\n const reason =\n details && typeof details === \"object\"\n ? (details as Record<string, unknown>).reason\n : undefined;\n return {\n phase: \"failed\",\n rawError: {\n code: \"response_incomplete\",\n message:\n typeof reason === \"string\" && reason.length > 0\n ? `The Codex response was incomplete (${reason})`\n : \"The Codex response was incomplete\",\n },\n fallbackCode: \"response_incomplete\",\n fallbackMessage: \"The Codex response was incomplete\",\n };\n }\n if (ev.type !== \"response.completed\" && ev.type !== \"response.done\") {\n return null;\n }\n if (!ev.response) {\n return null;\n }\n\n const responseStatus = ev.response.status;\n if (\n (responseStatus !== undefined && responseStatus !== \"completed\") ||\n (ev.response.error !== null && ev.response.error !== undefined)\n ) {\n const incomplete = responseStatus === \"incomplete\";\n return {\n phase: \"failed\",\n rawError: ev.response.error,\n fallbackCode: incomplete ? \"response_incomplete\" : \"response_failed\",\n fallbackMessage: incomplete\n ? \"The Codex response was incomplete\"\n : \"The Codex response failed\",\n };\n }\n return { phase: \"completed\" };\n}\n\nfunction markSemanticTerminal(state: SemanticTerminalState, phase: \"completed\" | \"failed\"): void {\n if (state.phase === null) {\n state.phase = phase;\n }\n}\n\nfunction terminalOutcomeForPhase(\n phase: CodexModelRequestEvent[\"phase\"],\n): RequestTerminalOutcome | null {\n if (phase === \"completed\" || phase === \"failed\" || phase === \"timed_out\") {\n return phase;\n }\n return null;\n}\n\nfunction requestEventFor(\n audit: RequestAudit,\n event: Omit<\n CodexModelRequestEvent,\n \"requestId\" | \"transportAttempt\" | \"model\" | \"durationMs\" | \"timeoutPolicy\"\n >,\n): CodexModelRequestEvent {\n return {\n requestId: audit.requestId,\n transportAttempt: audit.transportAttempt,\n ...(audit.model ? { model: audit.model } : {}),\n durationMs: Math.max(0, performance.now() - audit.attemptStartedAtMonotonic),\n timeoutPolicy: audit.policy,\n ...event,\n };\n}\n\nasync function emitRequestEvent(\n audit: RequestAudit,\n event: Omit<\n CodexModelRequestEvent,\n \"requestId\" | \"transportAttempt\" | \"model\" | \"durationMs\" | \"timeoutPolicy\"\n >,\n): Promise<boolean> {\n const terminalOutcome = terminalOutcomeForPhase(event.phase);\n if (terminalOutcome !== null) {\n if (audit.terminalOutcome !== null) {\n return false;\n }\n // Fence before invoking either observer. The durable observer may reject,\n // but a later transport callback must never turn that one terminal into a\n // contradictory second terminal.\n audit.terminalOutcome = terminalOutcome;\n }\n const observed = requestEventFor(audit, event);\n try {\n audit.ctx.onModelRequestDiagnostic?.(observed);\n } catch {\n // Diagnostic observers are strictly non-blocking and cannot affect transport.\n }\n await audit.ctx.onModelRequestEvent?.(observed);\n return true;\n}\n\nfunction providerRequestId(headers: Headers): string | undefined {\n return headers.get(\"x-request-id\") ?? headers.get(\"request-id\") ?? undefined;\n}\n\nasync function fetchBeforeHeaders(\n base: FetchLike,\n input: string,\n init: RequestInit,\n audit: RequestAudit,\n): Promise<Response> {\n const elapsed = Date.now() - audit.logicalStartedAt;\n const wholeRemainingMs = audit.policy.wholeRequestTimeoutMs - elapsed;\n const timeoutClass =\n wholeRemainingMs <= audit.policy.headersTimeoutMs ? \"whole_request\" : \"headers\";\n const deadlineMs = Math.max(1, Math.min(audit.policy.headersTimeoutMs, wholeRemainingMs));\n if (wholeRemainingMs <= 0) {\n throw new CodexResponseTimeoutError(\"whole_request\", audit.requestId, false);\n }\n\n const externalSignal = init.signal;\n if (externalSignal?.aborted) throw externalSignal.reason;\n const controller = new AbortController();\n const forwardAbort = () => controller.abort(externalSignal?.reason);\n externalSignal?.addEventListener(\"abort\", forwardAbort, { once: true });\n const basePromise = base(input, { ...init, signal: controller.signal });\n let deadlineError: CodexResponseTimeoutError | null = null;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n deadlineError = new CodexResponseTimeoutError(timeoutClass, audit.requestId, false);\n reject(deadlineError);\n }, deadlineMs);\n });\n try {\n return await Promise.race([basePromise, deadline]);\n } catch (error) {\n if (deadlineError) {\n controller.abort(deadlineError);\n void basePromise\n .then((late) => late.body?.cancel(deadlineError ?? undefined))\n .catch(() => undefined);\n throw deadlineError;\n }\n throw error;\n } finally {\n if (timer) clearTimeout(timer);\n externalSignal?.removeEventListener(\"abort\", forwardAbort);\n }\n}\n\nasync function observedResponse(\n res: Response,\n audit: RequestAudit,\n externalSignal: AbortSignal | null | undefined,\n semanticTerminal?: SemanticTerminalState,\n): Promise<Response> {\n const requestId = providerRequestId(res.headers);\n if (!res.body) {\n if (semanticTerminal) markSemanticTerminal(semanticTerminal, \"failed\");\n await emitRequestEvent(audit, {\n phase: semanticTerminal?.phase ?? (res.ok ? \"completed\" : \"failed\"),\n responseObserved: true,\n status: res.status,\n ...(requestId ? { providerRequestId: requestId } : {}),\n });\n return res;\n }\n\n const reader = res.body.getReader();\n let terminal = false;\n let firstByte = false;\n let idleTimer: ReturnType<typeof setTimeout> | undefined;\n let wholeTimer: ReturnType<typeof setTimeout> | undefined;\n let armIdle: () => void = () => undefined;\n let abortFromOutside: (() => void) | undefined;\n\n const clearTimers = () => {\n if (idleTimer) clearTimeout(idleTimer);\n if (wholeTimer) clearTimeout(wholeTimer);\n if (abortFromOutside) externalSignal?.removeEventListener(\"abort\", abortFromOutside);\n };\n\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n const timeOut = (klass: \"idle_stream\" | \"whole_request\") => {\n if (terminal) return;\n terminal = true;\n clearTimers();\n const semanticPhase = semanticTerminal?.phase;\n const phase = semanticPhase ?? \"timed_out\";\n const error = new CodexResponseTimeoutError(klass, audit.requestId, true);\n void reader.cancel(error).catch(() => undefined);\n void emitRequestEvent(audit, {\n phase,\n responseObserved: true,\n ...(phase === \"timed_out\" ? { timeoutClass: klass } : {}),\n status: res.status,\n ...(requestId ? { providerRequestId: requestId } : {}),\n }).then(\n () => (phase === \"completed\" ? controller.close() : controller.error(error)),\n () => (phase === \"completed\" ? controller.close() : controller.error(error)),\n );\n };\n armIdle = () => {\n if (idleTimer) clearTimeout(idleTimer);\n idleTimer = setTimeout(() => timeOut(\"idle_stream\"), audit.policy.streamIdleTimeoutMs);\n };\n armIdle();\n const wholeRemaining = Math.max(\n 1,\n audit.policy.wholeRequestTimeoutMs - (Date.now() - audit.logicalStartedAt),\n );\n wholeTimer = setTimeout(() => timeOut(\"whole_request\"), wholeRemaining);\n abortFromOutside = () => {\n if (terminal) return;\n terminal = true;\n clearTimers();\n const reason = externalSignal?.reason ?? new DOMException(\"Aborted\", \"AbortError\");\n void reader.cancel(reason).catch(() => undefined);\n void emitRequestEvent(audit, {\n phase: semanticTerminal?.phase ?? \"failed\",\n responseObserved: true,\n status: res.status,\n ...(requestId ? { providerRequestId: requestId } : {}),\n }).then(\n () =>\n semanticTerminal?.phase === \"completed\" ? controller.close() : controller.error(reason),\n () =>\n semanticTerminal?.phase === \"completed\" ? controller.close() : controller.error(reason),\n );\n };\n if (externalSignal?.aborted) {\n abortFromOutside();\n } else {\n externalSignal?.addEventListener(\"abort\", abortFromOutside, {\n once: true,\n });\n }\n },\n async pull(controller) {\n if (terminal) return;\n try {\n const chunk = await reader.read();\n if (terminal) return;\n if (chunk.done) {\n terminal = true;\n clearTimers();\n if (semanticTerminal && semanticTerminal.phase === null) {\n if (!semanticTerminal.deferTransportTerminal) {\n markSemanticTerminal(semanticTerminal, \"failed\");\n }\n }\n if (!semanticTerminal?.deferTransportTerminal || semanticTerminal.phase !== null) {\n await emitRequestEvent(audit, {\n phase: semanticTerminal?.phase ?? (res.ok ? \"completed\" : \"failed\"),\n responseObserved: true,\n status: res.status,\n ...(requestId ? { providerRequestId: requestId } : {}),\n });\n }\n controller.close();\n return;\n }\n if (!firstByte) {\n firstByte = true;\n // Deliver the provider byte before durable audit I/O. Audit latency\n // is not provider silence and must not manufacture an idle timeout.\n if (idleTimer) clearTimeout(idleTimer);\n controller.enqueue(chunk.value);\n await emitRequestEvent(audit, {\n phase: \"first_byte\",\n responseObserved: true,\n status: res.status,\n ...(requestId ? { providerRequestId: requestId } : {}),\n });\n if (!terminal) armIdle();\n return;\n }\n armIdle();\n controller.enqueue(chunk.value);\n } catch (error) {\n if (terminal) return;\n terminal = true;\n clearTimers();\n const semanticPhase = semanticTerminal?.phase;\n if (semanticTerminal && semanticPhase === null) {\n markSemanticTerminal(semanticTerminal, \"failed\");\n }\n await emitRequestEvent(audit, {\n phase: semanticPhase ?? \"failed\",\n responseObserved: true,\n status: res.status,\n ...(requestId ? { providerRequestId: requestId } : {}),\n });\n if (semanticPhase === \"completed\") {\n controller.close();\n } else {\n controller.error(error);\n }\n }\n },\n async cancel(reason) {\n if (!terminal) {\n terminal = true;\n clearTimers();\n if (semanticTerminal && semanticTerminal.phase === null) {\n markSemanticTerminal(semanticTerminal, \"failed\");\n }\n await emitRequestEvent(audit, {\n phase: semanticTerminal?.phase ?? \"failed\",\n responseObserved: true,\n status: res.status,\n ...(requestId ? { providerRequestId: requestId } : {}),\n }).catch(() => undefined);\n }\n await reader.cancel(reason).catch(() => undefined);\n },\n });\n const headers = new Headers(res.headers);\n headers.delete(\"content-length\");\n return new Response(body, {\n status: res.status,\n statusText: res.statusText,\n headers,\n });\n}\n\nfunction timeoutErrorResponse(info: {\n timeoutClass: \"connect\" | \"headers\" | \"idle_stream\" | \"whole_request\";\n requestId: string;\n responseObserved: boolean;\n message: string;\n}): Response {\n return new Response(\n JSON.stringify({\n error: {\n type: CODEX_RESPONSE_TIMEOUT_ERROR_TYPE,\n code: CODEX_RESPONSE_TIMEOUT_ERROR_TYPE,\n message: info.message,\n timeout_class: info.timeoutClass,\n response_observed: info.responseObserved,\n request_id: info.requestId,\n },\n }),\n {\n status: 504,\n headers: {\n \"content-type\": \"application/json\",\n \"x-should-retry\": \"false\",\n [CODEX_TRANSPORT_ERROR_HEADER]: \"1\",\n },\n },\n );\n}\n\nexport function codexSubscriptionFetch(base: FetchLike = globalThis.fetch): FetchLike {\n return async (input, init) => {\n const ctx = codexRequestStorage.getStore();\n if (!ctx) {\n return base(input, init); // not a codex turn — passthrough, untouched\n }\n emitRequestPreparationDiagnostic(ctx, \"transport_entry\");\n\n const rawUrl =\n typeof input === \"string\" ? input : input instanceof URL ? input.toString() : input.url;\n // /responses -> /codex/responses, idempotent: the negative lookbehind skips\n // URLs whose base already includes /codex (avoids /codex/codex/responses).\n const rewritten = rawUrl.replace(/(?<!\\/codex)\\/responses(\\b|$)/, \"/codex/responses$1\");\n\n const policy = resolveCodexResponseTimeoutPolicy(ctx.responseTimeoutPolicy);\n const handedRequestId = new Headers(init?.headers).get(CODEX_REQUEST_ID_HEADER);\n const requestId = handedRequestId ?? ctx.nextRequestId?.() ?? randomUUID();\n const logicalStartedAt = Date.now();\n let transportAttempt = 0;\n\n const attempt = async (\n auth: CodexTokenSnapshot,\n authenticationAttempt: number,\n ): Promise<Response> => {\n const headers = new Headers(init?.headers);\n const bodyAlreadyNormalized = headers.get(CODEX_REQUEST_BODY_NORMALIZED_HEADER) === \"1\";\n const normalizedModel = headers.get(CODEX_REQUEST_MODEL_HEADER) ?? undefined;\n const normalizedCallerStream = headers.get(CODEX_REQUEST_CALLER_STREAM_HEADER);\n headers.delete(CODEX_REQUEST_BODY_NORMALIZED_HEADER);\n headers.delete(CODEX_REQUEST_MODEL_HEADER);\n headers.delete(CODEX_REQUEST_ID_HEADER);\n headers.delete(CODEX_REQUEST_CALLER_STREAM_HEADER);\n headers.set(\"Authorization\", `Bearer ${auth.accessToken}`);\n if (auth.chatgptAccountId) {\n headers.set(\"ChatGPT-Account-ID\", auth.chatgptAccountId);\n }\n headers.set(\"originator\", CODEX_ORIGINATOR);\n headers.set(\"User-Agent\", `${CODEX_ORIGINATOR}/${ctx.clientVersion}`);\n headers.set(\"version\", ctx.clientVersion);\n headers.set(\"accept\", \"text/event-stream\");\n headers.set(\"content-type\", \"application/json\");\n if (ctx.sessionId) {\n // Backend sticky cache-routing key (see CodexRequestContext.sessionId):\n // without it, byte-identical resends miss the prompt cache ~half the\n // time; with it they pin to a warm shard and hit at the ceiling.\n headers.set(\"session_id\", ctx.sessionId);\n }\n if (auth.isFedramp) {\n headers.set(\"X-OpenAI-Fedramp\", \"true\");\n }\n headers.delete(\"OpenAI-Beta\"); // omit on SSE (spec §1.2); fallback: \"responses=experimental\" if backend 400s\n headers.delete(\"x-api-key\");\n // Codex CLI advertises betas via x-codex-beta-features (not OpenAI-Beta).\n if (ctx.betaFeatures && ctx.betaFeatures.length > 0) {\n headers.set(\"x-codex-beta-features\", ctx.betaFeatures.join(\",\"));\n }\n // Turn analytics / request_kind live in x-codex-turn-metadata — body\n // metadata is stripped by normalizeCodexRequestBody and rejected upstream.\n if (ctx.turnMetadata && Object.keys(ctx.turnMetadata).length > 0) {\n headers.set(\"x-codex-turn-metadata\", JSON.stringify(ctx.turnMetadata));\n }\n\n // The backend is streaming-only; force stream=true on the wire but remember\n // the caller's intent for legacy/unowned non-streaming consumers. The owned\n // compaction path consumes the same streaming model boundary as normal turns.\n let callerWantsStream = bodyAlreadyNormalized ? normalizedCallerStream !== \"0\" : true;\n let model: string | undefined = normalizedModel;\n let requestOpaqueArtifacts: string[] = [];\n const replayableBodyFactory = (init as ReplayableRequestInit | undefined)?.[\n REPLAYABLE_REQUEST_BODY_FACTORY\n ];\n const nextInit: RequestInit = {\n ...init,\n headers,\n ...(replayableBodyFactory ? { body: replayableBodyFactory() } : {}),\n };\n if (!bodyAlreadyNormalized && typeof init?.body === \"string\") {\n try {\n const parsed = JSON.parse(init.body) as Record<string, unknown>;\n callerWantsStream = parsed.stream === true;\n const normalized = normalizeCodexRequestBody(parsed, ctx.resolveModel);\n model = typeof normalized.model === \"string\" ? normalized.model : undefined;\n nextInit.body = JSON.stringify(normalized);\n requestOpaqueArtifacts = opaqueProviderArtifactFingerprints(normalized.input);\n } catch {\n // This is the final request-policy boundary for the strict Responses\n // endpoint. Never let malformed bytes bypass the reviewed policy.\n throw new Error(\"Model request could not be prepared\");\n }\n } else if (!bodyAlreadyNormalized) {\n throw new Error(\"Model request could not be prepared\");\n }\n if (!bodyAlreadyNormalized) {\n ctx.onRequestOpaqueArtifacts?.({\n requestId,\n fingerprints: requestOpaqueArtifacts,\n });\n }\n headers.set(\n \"Idempotency-Key\",\n authenticationAttempt === 0 ? requestId : `${requestId}:auth-${authenticationAttempt}`,\n );\n if (process.env.CODEX_DEBUG) {\n console.error(\"[codex-debug] request dispatched\", {\n method: \"POST\",\n origin: \"codex-subscription\",\n route: \"codex_responses\",\n stream: callerWantsStream,\n });\n }\n let res: Response;\n transportAttempt += 1;\n const audit: RequestAudit = {\n ctx,\n requestId,\n transportAttempt,\n ...(model ? { model } : {}),\n logicalStartedAt,\n attemptStartedAtMonotonic: performance.now(),\n policy,\n terminalOutcome: null,\n };\n emitRequestPreparationDiagnostic(ctx, \"wire_request_ready\");\n await emitRequestEvent(audit, {\n phase: \"started\",\n responseObserved: false,\n });\n const semanticTerminal: SemanticTerminalState = {\n phase: null,\n deferTransportTerminal: !callerWantsStream,\n };\n try {\n await ctx.beforeProviderDispatch?.();\n res = await fetchBeforeHeaders(base, rewritten, nextInit, audit);\n const upstreamRequestId = providerRequestId(res.headers);\n await emitRequestEvent(audit, {\n phase: \"headers\",\n responseObserved: true,\n status: res.status,\n ...(upstreamRequestId ? { providerRequestId: upstreamRequestId } : {}),\n });\n res = await observedResponse(res, audit, nextInit.signal, semanticTerminal);\n } catch (error) {\n if (nextInit.signal?.aborted) {\n await emitRequestEvent(audit, {\n phase: \"failed\",\n responseObserved: false,\n }).catch(() => undefined);\n throw error;\n }\n const klass = isPreHeadersTimeoutError(error);\n if (!klass) {\n await emitRequestEvent(audit, {\n phase: \"failed\",\n responseObserved: false,\n });\n throw error;\n }\n // An absent response does not prove that the provider never accepted\n // this operation. Until a provider-specific receipt can prove\n // non-acceptance or resume the same operation, never replay it.\n // Audit persistence must not replace the typed transport timeout.\n await emitRequestEvent(audit, {\n phase: \"timed_out\",\n responseObserved: false,\n timeoutClass: klass,\n willRetry: false,\n }).catch(() => undefined);\n throw new CodexResponseTimeoutError(klass, requestId, false);\n }\n // Multi-account P4 (Part A): scrape the usage headers ONCE, before the\n // OK/!res.ok branch, so the same fire-and-forget read also covers the 429\n // hard-cap path (an exhausted serving account stamps its own fresh\n // used_percent with no extra fetch). Sync + non-throwing + never awaited;\n // `if (usage)` makes an absent/malformed header set a safe no-op. We read\n // res.headers only — the SSE body is never touched here.\n const usage = parseCodexUsageHeaders(res.headers);\n if (usage) {\n ctx.onUsageHeaders?.(usage);\n }\n if (process.env.CODEX_DEBUG && !res.ok) {\n // Never log provider bodies, identifiers, or headers: they can contain\n // request-derived or account content. A bounded status is sufficient.\n console.error(\"[codex-debug] request failed\", {\n origin: \"codex-subscription\",\n route: \"codex_responses\",\n status: res.status,\n });\n }\n // The backend leaves terminal response.output empty and delivers assistant\n // items through output_item.done. The typed model reducer reconstructs normal\n // streaming calls; only the legacy non-streaming transport fallback collapses\n // SSE into one JSON response here.\n if (!res.ok) {\n // Buffer the error body once and re-emit it as a concrete JSON Response.\n // A streaming responses request whose error body is left as the raw\n // (possibly SSE / already-streamed) Response makes the SDK throw\n // \"<status> status code (no body)\" — the JSON error (type/message/\n // resets_in_seconds) is lost, so a 429 usage cap surfaces as a generic,\n // wrongly-retryable rate-limit. Re-emitting a clean application/json\n // Response lets the SDK reconstruct error.error for EVERY codex error\n // (401/400/5xx too). For a hard usage cap we also pin x-should-retry:false\n // so the SDK does not burn its retry budget on a limit that won't lift.\n const buffered = await bufferCodexErrorResponse(res);\n const upstreamRequestId = providerRequestId(res.headers);\n markSemanticTerminal(semanticTerminal, \"failed\");\n await emitRequestEvent(audit, {\n phase: \"failed\",\n responseObserved: true,\n status: res.status,\n ...(upstreamRequestId ? { providerRequestId: upstreamRequestId } : {}),\n }).catch(() => undefined);\n return buffered;\n }\n if (callerWantsStream) {\n res = validateCodexStream(res, (phase) => {\n markSemanticTerminal(semanticTerminal, phase);\n });\n } else {\n res = await sseToJsonResponse(res, audit, semanticTerminal);\n }\n return res;\n };\n\n try {\n const token = await ctx.getToken();\n emitRequestPreparationDiagnostic(ctx, \"credential_ready\");\n let res = await attempt(token, 0);\n if (res.status === 401) {\n res = await attempt(await ctx.refresh(), 1); // single refresh-on-401 retry (spec §1.9)\n }\n return res;\n } catch (error) {\n const timeout = classifyCodexResponseTimeoutError(error);\n if (!timeout) throw error;\n return timeoutErrorResponse({\n timeoutClass: timeout.timeoutClass,\n requestId: timeout.requestId ?? requestId,\n responseObserved: timeout.responseObserved,\n message: timeout.message,\n });\n }\n };\n}\n\n/** The codex backend's hard-cap error type (ChatGPT/Codex usage limit reached). */\nexport const CODEX_USAGE_LIMIT_ERROR_TYPE = \"usage_limit_reached\";\n\nexport type CodexUsageLimitInfo = {\n /** Seconds until the usage cap resets, when the backend reported it. */\n resetsInSeconds: number | null;\n};\n\n/**\n * Classify a thrown error as a ChatGPT/Codex usage-cap (429 usage_limit_reached)\n * and extract the reset window. The SDK surfaces the codex backend's 429 as an\n * OpenAI APIError whose `.type` (and `.error.type`) is `usage_limit_reached` and\n * whose `.error.resets_in_seconds` carries the cap reset. Walks the cause chain\n * and tolerates the message-only shape so it survives any SDK re-wrapping.\n * Returns null for anything that is not a usage cap.\n */\nexport function classifyCodexUsageLimitError(error: unknown): CodexUsageLimitInfo | null {\n let cur: unknown = error;\n for (let depth = 0; depth < 6 && cur && typeof cur === \"object\"; depth++) {\n const e = cur as Record<string, unknown>;\n const body = (e.error && typeof e.error === \"object\" ? e.error : undefined) as\n | Record<string, unknown>\n | undefined;\n const type =\n (typeof e.type === \"string\" ? e.type : undefined) ??\n (typeof body?.type === \"string\" ? body.type : undefined);\n const message = typeof e.message === \"string\" ? e.message : \"\";\n const status = Number(e.status);\n if (\n type === CODEX_USAGE_LIMIT_ERROR_TYPE ||\n message.includes(CODEX_USAGE_LIMIT_ERROR_TYPE) ||\n (status === 429 && /usage limit/i.test(message))\n ) {\n const resets =\n (typeof body?.resets_in_seconds === \"number\" ? body.resets_in_seconds : undefined) ??\n (typeof e.resets_in_seconds === \"number\" ? (e.resets_in_seconds as number) : undefined) ??\n null;\n return { resetsInSeconds: resets };\n }\n cur = e.cause;\n }\n return null;\n}\n\n/**\n * Buffer a non-OK codex Response and re-emit it as a clean `application/json`\n * Response so the SDK can reconstruct `error.error` from the body. A 429 usage\n * cap (`error.type === \"usage_limit_reached\"`) is a HARD limit, not transient\n * backpressure, so we pin `x-should-retry: false` to stop the SDK retrying it.\n * Reading the body here also drains the socket of a discarded 401 (no leak).\n */\nasync function bufferCodexErrorResponse(res: Response): Promise<Response> {\n const { text: bodyText, truncated } = await readBoundedResponseText(\n res,\n MAX_CODEX_ERROR_BODY_BYTES,\n );\n const headers = new Headers(res.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.set(CODEX_TRANSPORT_ERROR_HEADER, \"1\");\n headers.delete(\"content-length\"); // body re-serialized\n headers.delete(\"content-encoding\"); // text() already decoded any gzip\n let errorType: string | undefined;\n let responseBody = bodyText;\n try {\n const parsed = JSON.parse(bodyText) as { error?: { type?: unknown } };\n errorType = typeof parsed.error?.type === \"string\" ? parsed.error.type : undefined;\n } catch {\n /* non-JSON error body — leave as-is, no retry-header override */\n }\n if (truncated) {\n responseBody = JSON.stringify({\n error: {\n type: \"provider_error_body_too_large\",\n code: \"provider_error_body_too_large\",\n message: `The provider returned an error body larger than ${MAX_CODEX_ERROR_BODY_BYTES} bytes`,\n },\n });\n headers.set(\"x-opengeni-provider-error-truncated\", \"1\");\n }\n if (errorType === CODEX_USAGE_LIMIT_ERROR_TYPE) {\n headers.set(\"x-should-retry\", \"false\");\n }\n return new Response(responseBody, {\n status: res.status,\n statusText: res.statusText,\n headers,\n });\n}\n\nasync function readBoundedResponseText(\n response: Response,\n maxBytes: number,\n): Promise<{ text: string; truncated: boolean }> {\n if (!response.body) return { text: \"\", truncated: false };\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const parts: string[] = [];\n let bytes = 0;\n let truncated = false;\n try {\n while (bytes < maxBytes) {\n const next = await reader.read();\n if (next.done) {\n parts.push(decoder.decode());\n return { text: parts.join(\"\"), truncated };\n }\n const remaining = maxBytes - bytes;\n const accepted =\n next.value.byteLength > remaining ? next.value.subarray(0, remaining) : next.value;\n bytes += accepted.byteLength;\n parts.push(decoder.decode(accepted, { stream: true }));\n if (accepted.byteLength !== next.value.byteLength) {\n truncated = true;\n break;\n }\n if (bytes >= maxBytes) {\n // Reaching the hard cap is sufficient to classify the body as\n // oversized. Probing for one more chunk can wait forever when an\n // upstream producer stops emitting without closing its stream.\n truncated = true;\n break;\n }\n }\n } catch {\n truncated = true;\n } finally {\n // Cancellation is advisory cleanup. Some Fetch/Streams implementations do\n // not settle cancel() until the producer exits; never let an oversized\n // provider error hold the request open behind that implementation detail.\n if (truncated) void reader.cancel().catch(() => undefined);\n }\n return { text: parts.join(\"\"), truncated };\n}\n\n/**\n * Collapse a Responses SSE stream into the single JSON Response object a\n * non-streaming `responses.create` caller expects: the terminal response.*\n * event carries the full `response` payload.\n */\nasync function sseToJsonResponse(\n res: Response,\n audit: RequestAudit,\n semanticTerminal: SemanticTerminalState,\n): Promise<Response> {\n const upstreamRequestId = providerRequestId(res.headers);\n const text = await res.text();\n let final: Record<string, unknown> | null = null;\n let terminalError: Response | null = null;\n const items: unknown[] = []; // assembled from output_item.done (the codex backend\n // leaves response.completed.response.output empty and emits the items separately).\n for (const data of sseDataPayloads(text)) {\n if (!data || data === \"[DONE]\") {\n continue;\n }\n try {\n const ev = JSON.parse(data) as CodexSseEvent;\n if (ev.type === \"response.output_item.done\" && ev.item !== undefined) {\n items.push(ev.item);\n } else {\n const terminal = classifyCodexSseTerminal(ev);\n if (terminal?.phase === \"failed\") {\n terminalError = codexSseFailureResponse(\n res,\n terminal.rawError,\n terminal.fallbackCode,\n terminal.fallbackMessage,\n {\n eventType: ev.type,\n responseId: ev.response?.id,\n responseStatus: ev.response?.status,\n },\n );\n } else if (terminal?.phase === \"completed\") {\n final = ev.response ?? null;\n }\n }\n } catch {\n /* ignore non-JSON keepalive lines */\n }\n }\n if (terminalError) {\n markSemanticTerminal(semanticTerminal, \"failed\");\n await emitRequestEvent(audit, {\n phase: \"failed\",\n responseObserved: true,\n status: res.status,\n ...(upstreamRequestId ? { providerRequestId: upstreamRequestId } : {}),\n });\n return terminalError;\n }\n if (!final) {\n markSemanticTerminal(semanticTerminal, \"failed\");\n await emitRequestEvent(audit, {\n phase: \"failed\",\n responseObserved: true,\n status: res.status,\n ...(upstreamRequestId ? { providerRequestId: upstreamRequestId } : {}),\n });\n return codexSseFailureResponse(\n res,\n null,\n \"invalid_sse_terminal\",\n \"The Codex response stream ended without a terminal response\",\n );\n }\n if (final && items.length > 0) {\n final = { ...final, output: items }; // prefer the assembled items over an empty output array\n }\n if (process.env.CODEX_DEBUG) {\n console.error(\n `[codex-debug] sse->json items=${items.length} outputLen=${Array.isArray(final?.output) ? (final.output as unknown[]).length : \"?\"}`,\n );\n }\n markSemanticTerminal(semanticTerminal, \"completed\");\n await emitRequestEvent(audit, {\n phase: \"completed\",\n responseObserved: true,\n status: res.status,\n ...(upstreamRequestId ? { providerRequestId: upstreamRequestId } : {}),\n });\n const headers = new Headers(res.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.delete(\"content-length\");\n return new Response(JSON.stringify(final), { status: 200, headers });\n}\n\nconst NON_RETRYABLE_SSE_ERROR_CODES = new Set([\n \"bio_policy\",\n \"context_length_exceeded\",\n \"cyber_policy\",\n \"insufficient_quota\",\n \"invalid_prompt\",\n \"usage_limit_reached\",\n]);\n\n/**\n * Project the data payloads from a complete SSE body. EventSource accepts LF,\n * CRLF, and bare CR line endings; splitting only on `\\n\\n` can therefore merge\n * a standards-valid terminal failure into the preceding event and silently\n * turn it into `{}`. Preserve the SSE rule that multiple data lines are joined\n * with `\\n`, and tolerate a final event without a trailing blank line as the\n * previous transport parser did.\n */\nfunction sseDataPayloads(text: string): string[] {\n const payloads: string[] = [];\n let dataLines: string[] = [];\n const dispatch = () => {\n if (dataLines.length > 0) payloads.push(dataLines.join(\"\\n\"));\n dataLines = [];\n };\n\n for (const line of text.split(/\\r\\n|\\r|\\n/)) {\n if (line === \"\") {\n dispatch();\n continue;\n }\n if (line === \"data\") {\n dataLines.push(\"\");\n continue;\n }\n if (!line.startsWith(\"data:\")) continue;\n const value = line.slice(5);\n dataLines.push(value.startsWith(\" \") ? value.slice(1) : value);\n }\n dispatch();\n return payloads;\n}\n\nconst CODEX_TERMINAL_ERROR_FIELD_MAX_BYTES = 256;\nconst CODEX_TERMINAL_ERROR_MESSAGE_MAX_BYTES = 4 * 1024;\nconst CODEX_TERMINAL_ERROR_TRUNCATION_MARKER = \"… [truncated]\";\n\nfunction boundedTerminalErrorField(\n value: unknown,\n maxBytes: number,\n): { value?: string; truncated: boolean } {\n if (typeof value !== \"string\") return { truncated: false };\n const encoder = new TextEncoder();\n const encoded = encoder.encode(value);\n if (encoded.byteLength <= maxBytes) return { value, truncated: false };\n\n const markerBytes = encoder.encode(CODEX_TERMINAL_ERROR_TRUNCATION_MARKER).byteLength;\n let prefixEnd = Math.max(0, maxBytes - markerBytes);\n while (prefixEnd > 0 && (encoded[prefixEnd]! & 0xc0) === 0x80) {\n prefixEnd -= 1;\n }\n return {\n value: `${new TextDecoder().decode(encoded.subarray(0, prefixEnd))}${CODEX_TERMINAL_ERROR_TRUNCATION_MARKER}`,\n truncated: true,\n };\n}\n\n/**\n * Convert a terminal error carried inside an HTTP-200 SSE stream into the\n * ordinary non-2xx JSON error contract expected by the OpenAI SDK. Codex CLI\n * treats the same events as provider failures; returning a successful `{}`\n * loses the actual cause and makes compaction look semantically empty.\n */\nfunction codexSseFailureResponse(\n source: Response,\n rawError: unknown,\n fallbackCode: string,\n fallbackMessage: string,\n metadata: {\n eventType?: unknown;\n responseId?: unknown;\n responseStatus?: unknown;\n } = {},\n): Response {\n const projection = codexSseFailureProjection(\n source,\n rawError,\n fallbackCode,\n fallbackMessage,\n metadata,\n );\n return new Response(JSON.stringify({ error: projection.error }), {\n status: projection.status,\n headers: projection.headers,\n });\n}\n\nexport type CodexSseFailureProjection = {\n status: number;\n error: {\n type: string;\n code: string;\n message: string;\n param?: string;\n event_type?: string;\n response_id?: string;\n response_status?: string;\n diagnostic_truncated?: true;\n };\n headers: Headers;\n};\n\nfunction codexSseFailureProjection(\n source: Response,\n rawError: unknown,\n fallbackCode: string,\n fallbackMessage: string,\n metadata: {\n eventType?: unknown;\n responseId?: unknown;\n responseStatus?: unknown;\n } = {},\n): CodexSseFailureProjection {\n const record =\n rawError && typeof rawError === \"object\" && !Array.isArray(rawError)\n ? (rawError as Record<string, unknown>)\n : {};\n const typeField = boundedTerminalErrorField(record.type, CODEX_TERMINAL_ERROR_FIELD_MAX_BYTES);\n const codeField = boundedTerminalErrorField(record.code, CODEX_TERMINAL_ERROR_FIELD_MAX_BYTES);\n const messageField = boundedTerminalErrorField(\n record.message ?? (typeof rawError === \"string\" ? rawError : undefined),\n CODEX_TERMINAL_ERROR_MESSAGE_MAX_BYTES,\n );\n const paramField = boundedTerminalErrorField(record.param, CODEX_TERMINAL_ERROR_FIELD_MAX_BYTES);\n const eventTypeField = boundedTerminalErrorField(\n metadata.eventType,\n CODEX_TERMINAL_ERROR_FIELD_MAX_BYTES,\n );\n const responseIdField = boundedTerminalErrorField(\n metadata.responseId,\n CODEX_TERMINAL_ERROR_FIELD_MAX_BYTES,\n );\n const responseStatusField = boundedTerminalErrorField(\n metadata.responseStatus,\n CODEX_TERMINAL_ERROR_FIELD_MAX_BYTES,\n );\n const providerType =\n typeField.value === \"error\" ||\n typeField.value === \"response.error\" ||\n typeField.value === \"response.failed\"\n ? undefined\n : typeField.value;\n const code =\n (codeField.value?.length ? codeField.value : undefined) ??\n (providerType?.length ? providerType : undefined) ??\n fallbackCode;\n const diagnosticTruncated =\n typeField.truncated ||\n codeField.truncated ||\n messageField.truncated ||\n paramField.truncated ||\n eventTypeField.truncated ||\n responseIdField.truncated ||\n responseStatusField.truncated ||\n Object.keys(record).some((key) => ![\"type\", \"code\", \"message\", \"param\"].includes(key)) ||\n (rawError !== null &&\n rawError !== undefined &&\n typeof rawError !== \"string\" &&\n (typeof rawError !== \"object\" || Array.isArray(rawError)));\n const error: CodexSseFailureProjection[\"error\"] = {\n type: providerType?.length ? providerType : code,\n code,\n message: messageField.value?.length ? messageField.value : fallbackMessage,\n ...(paramField.value?.length ? { param: paramField.value } : {}),\n ...(eventTypeField.value?.length ? { event_type: eventTypeField.value } : {}),\n ...(responseIdField.value?.length ? { response_id: responseIdField.value } : {}),\n ...(responseStatusField.value?.length ? { response_status: responseStatusField.value } : {}),\n ...(diagnosticTruncated ? { diagnostic_truncated: true } : {}),\n };\n const status =\n code === \"rate_limit_exceeded\" ||\n code === \"usage_limit_reached\" ||\n code === \"insufficient_quota\"\n ? 429\n : NON_RETRYABLE_SSE_ERROR_CODES.has(code)\n ? 400\n : 502;\n const headers = new Headers(source.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.set(CODEX_TRANSPORT_ERROR_HEADER, \"1\");\n // A terminal event means the provider already accepted and completed this\n // request. Never let the OpenAI SDK replay it merely because we synthesized\n // a non-2xx response to preserve the terminal failure.\n headers.set(\"x-should-retry\", \"false\");\n headers.delete(\"content-length\");\n headers.delete(\"content-encoding\");\n return { status, error, headers };\n}\n\n/**\n * A provider terminal carried inside an accepted HTTP-200 stream. The OpenAI\n * SDK cannot turn that late terminal into a non-2xx APIError because headers\n * have already been accepted, so the body transform throws this equivalent\n * bounded shape. Provider-supplied message/param text remains exact within the\n * explicit terminal-field byte contract; retry classification is additive and\n * never substitutes for the source diagnostic.\n */\nexport class CodexStreamingTerminalError extends Error {\n readonly status: number;\n readonly code: string;\n readonly type: string;\n readonly eventType?: string;\n readonly responseId?: string;\n readonly responseStatus?: string;\n readonly headers: Headers;\n readonly error: Record<string, unknown>;\n\n constructor(projection: CodexSseFailureProjection) {\n super(projection.error.message);\n this.name = \"CodexStreamingTerminalError\";\n this.status = projection.status;\n this.code = projection.error.code;\n this.type = projection.error.type;\n if (projection.error.event_type !== undefined) {\n this.eventType = projection.error.event_type;\n }\n if (projection.error.response_id !== undefined) {\n this.responseId = projection.error.response_id;\n }\n if (projection.error.response_status !== undefined) {\n this.responseStatus = projection.error.response_status;\n }\n this.headers = projection.headers;\n this.error = {\n type: projection.error.type,\n code: projection.error.code,\n message: projection.error.message,\n ...(projection.error.param ? { param: projection.error.param } : {}),\n ...(projection.error.event_type ? { event_type: projection.error.event_type } : {}),\n ...(projection.error.response_id ? { response_id: projection.error.response_id } : {}),\n ...(projection.error.response_status\n ? { response_status: projection.error.response_status }\n : {}),\n ...(projection.error.diagnostic_truncated ? { diagnostic_truncated: true } : {}),\n };\n }\n}\n\nfunction codexSseFailureError(\n source: Response,\n rawError: unknown,\n fallbackCode: string,\n publicMessage: string,\n metadata: {\n eventType?: unknown;\n responseId?: unknown;\n responseStatus?: unknown;\n } = {},\n): CodexStreamingTerminalError {\n return new CodexStreamingTerminalError(\n codexSseFailureProjection(source, rawError, fallbackCode, publicMessage, metadata),\n );\n}\n\n/**\n * Preserve a live Responses SSE stream byte-for-byte while translating only\n * provider-specific terminal failures into typed transport errors. Successful\n * output reconstruction belongs to the model reducer, so this layer retains no\n * duplicate output-item graph.\n */\nfunction validateCodexStream(\n res: Response,\n onSemanticTerminal?: (phase: \"completed\" | \"failed\") => void,\n): Response {\n if (!res.body) {\n onSemanticTerminal?.(\"failed\");\n const error = codexSseFailureError(\n res,\n null,\n \"invalid_sse_terminal\",\n \"The Codex response stream ended without a terminal response\",\n );\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.error(error);\n },\n });\n const headers = new Headers(res.headers);\n headers.delete(\"content-length\");\n return new Response(body, {\n status: res.status,\n statusText: res.statusText,\n headers,\n });\n }\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let buffer = \"\";\n let successfulTerminalSeen = false;\n const emitCompleteBlocks = (\n controller: TransformStreamDefaultController<Uint8Array>,\n final: boolean,\n ) => {\n let boundary = findSseBlockBoundary(buffer, final);\n while (boundary) {\n const block = buffer.slice(0, boundary.start);\n const separator = buffer.slice(boundary.start, boundary.end);\n buffer = buffer.slice(boundary.end);\n successfulTerminalSeen ||= inspectCodexSseBlock(block, res, onSemanticTerminal);\n controller.enqueue(encoder.encode(`${block}${separator}`));\n boundary = findSseBlockBoundary(buffer, final);\n }\n };\n const transform = new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n buffer += decoder.decode(chunk, { stream: true });\n emitCompleteBlocks(controller, false);\n },\n flush(controller) {\n buffer += decoder.decode();\n emitCompleteBlocks(controller, true);\n if (buffer.length > 0) {\n successfulTerminalSeen ||= inspectCodexSseBlock(buffer, res, onSemanticTerminal);\n controller.enqueue(encoder.encode(buffer));\n buffer = \"\";\n }\n if (!successfulTerminalSeen) {\n throw codexSseFailureError(\n res,\n null,\n \"invalid_sse_terminal\",\n \"The Codex response stream ended without a terminal response\",\n );\n }\n },\n });\n const headers = new Headers(res.headers);\n headers.delete(\"content-length\");\n return new Response(res.body.pipeThrough(transform), {\n status: res.status,\n headers,\n });\n}\n\ntype SseBlockBoundary = { start: number; end: number };\n\n/**\n * Find two consecutive SSE line endings without misreading one CRLF as a bare\n * CR followed by a bare LF. A trailing CR is intentionally held until the next\n * chunk (or final flush), because only then can it be distinguished from the\n * first byte of CRLF.\n */\nfunction findSseBlockBoundary(value: string, final: boolean): SseBlockBoundary | null {\n for (let index = 0; index < value.length; index += 1) {\n const firstEnd = sseLineEndingEnd(value, index, final);\n if (firstEnd === null) continue;\n const secondEnd = sseLineEndingEnd(value, firstEnd, final);\n if (secondEnd !== null) {\n return { start: index, end: secondEnd };\n }\n index = firstEnd - 1;\n }\n return null;\n}\n\nfunction sseLineEndingEnd(value: string, index: number, final: boolean): number | null {\n const current = value[index];\n if (current === \"\\n\") return index + 1;\n if (current !== \"\\r\") return null;\n if (index + 1 < value.length) {\n return value[index + 1] === \"\\n\" ? index + 2 : index + 1;\n }\n return final ? index + 1 : null;\n}\n\nconst CODEX_TERMINAL_TYPE_HINTS = [\n '\"response.completed\"',\n '\"response.done\"',\n '\"response.failed\"',\n '\"response.incomplete\"',\n '\"response.error\"',\n '\"error\"',\n] as const;\n\n/**\n * Parse only blocks that can be terminal. Ordinary deltas and output items pass\n * without object allocation; failed/error/incomplete terminals throw before the\n * model can mistake them for an ordinary response_done event.\n */\nfunction inspectCodexSseBlock(\n block: string,\n source: Response,\n onSemanticTerminal?: (phase: \"completed\" | \"failed\") => void,\n): boolean {\n const lines = block.split(/\\r\\n|\\r|\\n/);\n const dataStr = lines\n .filter((l) => l.startsWith(\"data:\"))\n .map((l) => l.slice(5).trim())\n .join(\"\\n\");\n if (!dataStr || dataStr === \"[DONE]\") {\n return false;\n }\n if (!CODEX_TERMINAL_TYPE_HINTS.some((terminalType) => dataStr.includes(terminalType))) {\n return false;\n }\n let ev: CodexSseEvent;\n try {\n ev = JSON.parse(dataStr);\n } catch {\n return false;\n }\n const terminal = classifyCodexSseTerminal(ev);\n if (terminal?.phase === \"failed\") {\n onSemanticTerminal?.(\"failed\");\n throw codexSseFailureError(\n source,\n terminal.rawError,\n terminal.fallbackCode,\n terminal.fallbackMessage,\n {\n eventType: ev.type,\n responseId: ev.response?.id,\n responseStatus: ev.response?.status,\n },\n );\n }\n if (terminal?.phase === \"completed\") {\n onSemanticTerminal?.(\"completed\");\n return true;\n }\n return false;\n}\n","import { createHash } from \"node:crypto\";\n\n/** Stable, content-hiding identity for one opaque provider artifact. */\nexport function opaqueProviderArtifactFingerprint(item: unknown): string | null {\n if (!item || typeof item !== \"object\") return null;\n const record = item as Record<string, unknown>;\n if (record.type !== \"reasoning\" && record.type !== \"compaction\") return null;\n const providerData =\n record.providerData && typeof record.providerData === \"object\"\n ? (record.providerData as Record<string, unknown>)\n : null;\n const ciphertext =\n (typeof record.encrypted_content === \"string\" && record.encrypted_content) ||\n (typeof record.encryptedContent === \"string\" && record.encryptedContent) ||\n (typeof providerData?.encrypted_content === \"string\" && providerData.encrypted_content) ||\n (typeof providerData?.encryptedContent === \"string\" && providerData.encryptedContent) ||\n null;\n if (!ciphertext) return null;\n return `${record.type}:${createHash(\"sha256\").update(ciphertext).digest(\"hex\")}`;\n}\n\n/** Exact opaque artifacts present in one normalized provider input array. */\nexport function opaqueProviderArtifactFingerprints(input: unknown): string[] {\n if (!Array.isArray(input)) return [];\n return input.flatMap((item) => {\n const fingerprint = opaqueProviderArtifactFingerprint(item);\n return fingerprint ? [fingerprint] : [];\n });\n}\n","// The codex_apps connector MCP is incompatible with the Responses API tool\n// contract in two ways that each fail the whole turn:\n//\n// 1. NAMES. Connector tools are named like \"vercel.deploy_to_vercel\" (dots).\n// The Responses API requires every function-tool name to match\n// ^[A-Za-z0-9_-]+$, so the request 400s (\"Invalid 'tools[0].name': string\n// does not match pattern\"). We cannot just rename them in tools/list — the\n// model would then call a name the MCP server does not know. So we remap\n// BIDIRECTIONALLY at the transport: sanitize the name (and remember the\n// mapping) on the tools/list RESPONSE, and reverse it back to the original on\n// the tools/call REQUEST.\n//\n// 2. OUTPUT SCHEMAS. 122 of 217 tools return an empty `outputSchema: {}` (no\n// `type`). @modelcontextprotocol/sdk validates every tool's outputSchema as a\n// strict `{ type: \"object\", ... }` and ZodErrors the WHOLE tools/list. Since\n// codex_apps runs with cacheToolsList:false it re-lists per turn, so that\n// error (thrown during tool enumeration, outside the best-effort connect\n// wrapper) fails the turn. We drop any non-object outputSchema before the\n// validator sees it — safe, as outputSchema is an advisory hint only.\n\nimport { CODEX_APPS_MCP_SERVER_ID } from \"./constants\";\nimport type { FetchLike } from \"./fetch\";\n\nconst VALID_TOOL_NAME = /^[a-zA-Z0-9_-]+$/;\n\n// The Responses API rejects a function-tool name longer than 64 chars (it 400s\n// the WHOLE turn). Some namespaced connector tool names exceed this, and the\n// collision-disambiguation suffix only lengthens names, so the mapper must cap\n// length too — not just charset.\nconst MAX_TOOL_NAME_LEN = 64;\n\n// CRITICAL: this sanitizer runs on the codex_apps tools/list wire BEFORE OpenGeni's\n// PrefixedMcpServer (packages/runtime) prepends `<serverId>__` to every tool name\n// (prefixedMcpToolName). The 64-char limit applies to that FINAL prefixed name the\n// model sees, so a name we cap at 64 here becomes 64 + 12 = 76 after prefixing and\n// 400s the whole turn. Reserve the runtime prefix so `codex_apps__<sanitized>` is\n// always <= 64. The sanitizer owns the server id, so the reservation is exact and\n// stays self-contained (no runtime import). The reverse mapping is unaffected: the\n// mapper is keyed on the pre-prefix sanitized name, which is what tools/call carries\n// back after PrefixedMcpServer strips its prefix.\nconst RUNTIME_TOOL_NAME_PREFIX_LEN = CODEX_APPS_MCP_SERVER_ID.length + \"__\".length; // `codex_apps__` = 12\nconst EFFECTIVE_MAX_TOOL_NAME_LEN = MAX_TOOL_NAME_LEN - RUNTIME_TOOL_NAME_PREFIX_LEN; // 52\n\n/** Short, stable, charset-legal hash of a string (djb2 → base36). Deterministic. */\nfunction shortHash(input: string): string {\n let h = 5381;\n for (let i = 0; i < input.length; i++) {\n h = ((h << 5) + h + input.charCodeAt(i)) >>> 0; // h * 33 + c, kept unsigned\n }\n return h.toString(36);\n}\n\n/** Truncate to <= EFFECTIVE_MAX_TOOL_NAME_LEN (reserving the runtime prefix), appending `_<hash(original)>` so the result stays unique + deterministic. */\nfunction capLength(candidate: string, original: string): string {\n if (candidate.length <= EFFECTIVE_MAX_TOOL_NAME_LEN) {\n return candidate;\n }\n const suffix = `_${shortHash(original)}`;\n return candidate.slice(0, Math.max(0, EFFECTIVE_MAX_TOOL_NAME_LEN - suffix.length)) + suffix;\n}\n\n/**\n * Maps connector tool names to a Responses-API-legal charset and back. One\n * instance per codex_apps transport (i.e. per turn): tools/list populates it,\n * tools/call reads it. Idempotent across repeat listings.\n */\nexport class ToolNameMapper {\n private readonly sanitizedToOriginal = new Map<string, string>();\n private readonly used = new Set<string>();\n\n /** Return a legal, unique name (<= EFFECTIVE_MAX_TOOL_NAME_LEN, so `<prefix>__name` <= 64) for `original`, recording the reverse mapping. */\n sanitize(original: string): string {\n let candidate = VALID_TOOL_NAME.test(original)\n ? original\n : original.replace(/[^a-zA-Z0-9_-]/g, \"_\") || \"tool\";\n // Enforce the Responses-API 64-char cap (stable hash suffix keyed on the\n // ORIGINAL → deterministic across repeat listings, distinct originals don't\n // collide after truncation).\n candidate = capLength(candidate, original);\n // Disambiguate a genuine collision with a DIFFERENT original (never with\n // the same original — that keeps repeat listings stable/idempotent). Re-cap\n // after each suffix so disambiguation never re-breaches the effective limit.\n if (this.used.has(candidate) && this.sanitizedToOriginal.get(candidate) !== original) {\n const base = candidate;\n let n = 2;\n do {\n const suffix = `_${n++}`;\n candidate =\n (base.length + suffix.length > EFFECTIVE_MAX_TOOL_NAME_LEN\n ? base.slice(0, EFFECTIVE_MAX_TOOL_NAME_LEN - suffix.length)\n : base) + suffix;\n } while (this.used.has(candidate));\n }\n this.used.add(candidate);\n this.sanitizedToOriginal.set(candidate, original);\n return candidate;\n }\n\n /** Reverse a sanitized name back to the MCP server's original, if known. */\n toOriginal(sanitized: string): string | undefined {\n return this.sanitizedToOriginal.get(sanitized);\n }\n}\n\n/**\n * Drop bad outputSchemas + sanitize tool names on a JSON-RPC tools/list result, in place.\n *\n * When `namespaceSink` is provided, accumulate each tool's ORIGINAL\n * connector namespace (the segment BEFORE the first dot, e.g. `github` from\n * `github.create_issue`) into it — captured HERE because this pass sees the original\n * dotted name BEFORE mapper.sanitize rewrites the dot away. Only dotted names carry a\n * connector namespace; un-dotted (already-legal) names are not connectors and are skipped.\n */\nfunction sanitizeToolsInRpcMessage(\n message: unknown,\n mapper: ToolNameMapper,\n namespaceSink?: Set<string>,\n): void {\n if (!message || typeof message !== \"object\") {\n return;\n }\n const tools = (message as { result?: { tools?: unknown } }).result?.tools;\n if (!Array.isArray(tools)) {\n return;\n }\n for (const tool of tools) {\n if (!tool || typeof tool !== \"object\") {\n continue;\n }\n const record = tool as Record<string, unknown>;\n if (\"outputSchema\" in record) {\n // Drop EVERY outputSchema, not just malformed/empty ones. The MCP SDK client\n // caches a validator for any tool that declares an outputSchema and validates\n // each tool CALL's `structuredContent` against it — and the codex_apps\n // connectors return results that do NOT match their own declared schemas\n // (e.g. the schema requires a `result` property the response omits), so the\n // SDK throws `McpError -32602: Structured content does not match the tool's\n // output schema` and EVERY such connector tool call fails (observed live:\n // gmail_search_emails / gmail_get_profile / gmail_list_labels all -32602ed).\n // outputSchema is advisory — the agent reads the text `content` regardless —\n // so dropping it makes the connector tools usable. This also subsumes the\n // empty-`{}` case the strict Tool schema rejected at tools/list time.\n delete record.outputSchema;\n }\n if (typeof record.name === \"string\") {\n if (namespaceSink && record.name.includes(\".\")) {\n const namespace = record.name.slice(0, record.name.indexOf(\".\"));\n if (namespace) {\n namespaceSink.add(namespace);\n }\n }\n record.name = mapper.sanitize(record.name);\n }\n }\n}\n\n/**\n * Surface a tool CALL's `structuredContent` to the model by inlining it as a text\n * `content` block, in place.\n *\n * WHY. The @openai/agents MCP bridge forwards ONLY `result.content` to the model\n * (agents-core shims/mcp-server: `const result = parsed.content`) and DISCARDS\n * `result.structuredContent`. The codex_apps connectors return the real payload in\n * `structuredContent` and a bare `\"Action completed.\"` placeholder in `content`\n * (verified live: `gmail.get_profile` → content=[{text:\"Action completed.\"}],\n * structuredContent={id,name,email,…}). Without this the agent's tool call\n * \"succeeds\" but carries NO data — the model sees only the placeholder. Appending\n * the structured payload as a text block makes the data reach the model while\n * leaving the original content untouched.\n *\n * No-op when there is no `structuredContent` — so a tools/list response (or any\n * result without it) passes through unchanged. Valid object payloads stay intact\n * for protocol-aware consumers. Invalid optional values (such as null) are removed\n * after any useful value is copied into `content`, because the MCP client validates\n * this field as an object before the tool can return. Runs after the outputSchema drop.\n */\nfunction inlineStructuredContentInRpcMessage(message: unknown): void {\n if (!message || typeof message !== \"object\") {\n return;\n }\n const result = (message as { result?: unknown }).result;\n if (!result || typeof result !== \"object\") {\n return;\n }\n const record = result as Record<string, unknown>;\n if (!(\"structuredContent\" in record)) {\n return;\n }\n const structured = record.structuredContent;\n if (structured !== undefined && structured !== null) {\n const text = typeof structured === \"string\" ? structured : JSON.stringify(structured);\n const content = Array.isArray(record.content) ? [...record.content] : [];\n content.push({ type: \"text\", text });\n record.content = content;\n }\n if (typeof structured !== \"object\" || structured === null || Array.isArray(structured)) {\n delete record.structuredContent;\n }\n}\n\n/** Sanitize a single JSON body (application/json MCP response). */\nexport function sanitizeMcpJsonBody(\n text: string,\n mapper: ToolNameMapper = new ToolNameMapper(),\n namespaceSink?: Set<string>,\n): string {\n try {\n const parsed = JSON.parse(text);\n sanitizeToolsInRpcMessage(parsed, mapper, namespaceSink);\n inlineStructuredContentInRpcMessage(parsed);\n return JSON.stringify(parsed);\n } catch {\n return text; // not JSON we understand — leave untouched\n }\n}\n\n/** Sanitize an SSE body: each JSON-RPC message rides on a `data:` line. */\nexport function sanitizeMcpSseBody(\n text: string,\n mapper: ToolNameMapper = new ToolNameMapper(),\n namespaceSink?: Set<string>,\n): string {\n return text\n .split(\"\\n\")\n .map((line) => {\n if (!line.startsWith(\"data:\")) {\n return line;\n }\n const payload = line.slice(\"data:\".length).trimStart();\n try {\n const parsed = JSON.parse(payload);\n sanitizeToolsInRpcMessage(parsed, mapper, namespaceSink);\n inlineStructuredContentInRpcMessage(parsed);\n return `data: ${JSON.stringify(parsed)}`;\n } catch {\n return line;\n }\n })\n .join(\"\\n\");\n}\n\n/** Reverse a sanitized tools/call name back to the original; returns null if no rewrite is needed. */\nexport function remapToolCallRequestBody(body: string, mapper: ToolNameMapper): string | null {\n try {\n const message = JSON.parse(body) as { method?: unknown; params?: { name?: unknown } };\n if (message.method !== \"tools/call\") {\n return null;\n }\n const name = message.params?.name;\n if (typeof name !== \"string\") {\n return null;\n }\n const original = mapper.toOriginal(name);\n if (original === undefined || original === name) {\n return null;\n }\n message.params!.name = original;\n return JSON.stringify(message);\n } catch {\n return null;\n }\n}\n\n/**\n * Wrap a base fetch so the codex_apps MCP transport is Responses-API-compatible:\n * tools/list responses get their names sanitized + bad outputSchemas dropped (and\n * the name mapping recorded), and tools/call requests get their name reversed back\n * to the MCP server's original. Only the POST request/response is buffered; the\n * long-lived GET notification SSE stream is passed through untouched.\n *\n * An optional `namespaceSink` Set accumulates the ORIGINAL-dotted\n * connector namespaces seen across every tools/list this turn (captured before the\n * dot is sanitized away). The runtime reads the live by-reference Set only to keep\n * this turn's `tool_search` description accurate; it is never persisted or used\n * for inference selection.\n */\nexport function codexAppsSanitizingFetch(\n base: FetchLike = globalThis.fetch,\n namespaceSink?: Set<string>,\n): FetchLike {\n const mapper = new ToolNameMapper();\n return async (input, init) => {\n // Outgoing: reverse a sanitized tools/call name to the server's original.\n let nextInit = init;\n if (init && typeof init.body === \"string\" && (init.method ?? \"GET\").toUpperCase() === \"POST\") {\n const remapped = remapToolCallRequestBody(init.body, mapper);\n if (remapped !== null) {\n nextInit = { ...init, body: remapped };\n }\n }\n const res = await base(input, nextInit);\n const method = (\n init?.method ?? (input instanceof Request ? input.method : \"GET\")\n ).toUpperCase();\n if (method !== \"POST\" || !res.ok || !res.body) {\n return res;\n }\n const contentType = res.headers.get(\"content-type\") ?? \"\";\n const isJson = contentType.includes(\"application/json\");\n const isSse = contentType.includes(\"text/event-stream\");\n if (!isJson && !isSse) {\n return res;\n }\n const originalBody = await res.text();\n const sanitized = isJson\n ? sanitizeMcpJsonBody(originalBody, mapper, namespaceSink)\n : sanitizeMcpSseBody(originalBody, mapper, namespaceSink);\n const headers = new Headers(res.headers);\n headers.delete(\"content-length\"); // body length changed\n headers.delete(\"content-encoding\");\n return new Response(sanitized, { status: res.status, statusText: res.statusText, headers });\n };\n}\n","/**\n * Protocol-valid image shown to the model when an inline tool image exceeds the\n * hard model-input allowance. The image channel cannot carry a text marker, so\n * the omission itself is rendered as a legible PNG instead of corrupting the\n * original base64 or pretending the placeholder is the real screenshot.\n *\n * Generated with the dependency-free bitmap/PNG encoder documented in\n * `scripts/gen-screenshot-error-card.mjs`; the source image is 1,076x284 RGBA\n * and 5,255 bytes. Rendered text:\n *\n * SCREEN CAPTURE OMITTED\n * THE SCREEN CAPTURE IS TOO LARGE.\n * THIS IS A PLACEHOLDER, NOT THE REAL SCREEN.\n * DO NOT SAY THIS IS THE REAL SCREEN.\n * TELL THE USER TO TAKE A SMALLER CAPTURE.\n */\nexport const MODEL_TOOL_OUTPUT_OVERSIZED_IMAGE_CARD_DATA_URL =\n \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDQAAAEcCAYAAAA4KeSGAAAUTklEQVR42u3cO5JTvRaAUcZAEXTA0BhZT9GJE8fNEBojbWk/VrCi+2OMjqzHd6vOj88/P78AAAAAKvlhEAAAAABBAwAAAEDQAAAAABA0AAAAAEEDAAAAQNAAAAAAEDQAAAAAQQMAAABA0AAAAAAQNAAAAABBAwAAAEDQAAAAABA0AAAAAEEDAAAAQNAAAAAAEDQAAAAAQQMAAABA0AAAAAAQNAAAAAAEDQAAAEDQAAAAABA0AAAAAAQNAAAAQND4T6/nY8npz8/+faO//7ufvzofbv8gsj3v6r+n2/On+vhkn//Rv+9s65vPP/v7AgAQNAQNQUPQEDQEDUFDcBA0AABBQ9AQNAQNQUPQEDQEDZ8vaAAAgoagIWgIGoKGoCFoCBqCBgBAtqARfYDJ/vnRF7ps43P6wmP+3A1K2f989d9v9vm/euHdvZ7Yf3w/AEDQEDQEDUFD0BA0BA1BQzAQNAAAQcOBUtAQNAQNQUPQEDQEDUEDABA0XEgFDfNH0BA0BA37j+8HAAgagoagEfX52S+EgoagIWjcG5/qLx0WNAQNAEDQcCEVNAQNQUPQEDQEDUEDAEDQEDQEDfNH0BA0BA37j6ABAAgagoagIWgIGoKGoCFoCAaCBgAwK2i8+9K3bC+VfPf7rn7/6p8vaOwd/9WXKO5+yWL1oFHt9yVoCBo7//3Z9l9BAwAQNAQNQUPQEDQEDUFD0BA0AABBQ9AQNAQNQUPQEDQEDUFD0AAABA1BQ9AQNA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NoCBqChqAhaNgQBQ3rj6AhaAgagobzifOhoCFoIGgIGi4UgoagIWgIGoKGoCFoCBqChqAhaAgaCBqChqAhaAgagoagIWgIGoKGoCFo2L8EDUHD/EfQ8FJQQcNLQf1++v/9gobx8VJQL/XNun55KWjvl75OCxrdxtf+JVAgaNgQHUhdaB3IPH9Bw4HQ/BY0BA1BQ9AQNOxfCBouZIKGoGF8BQ3PX9BwILS+CRqChv1L0LB/2b8QNAQNQcOG5ffjQChoWH8cCAUNQcP5TdBwPrR/CRoIGjZEB1IXWkHjY/NLTz1/QSPT+tN9PjsQCxrOb31+74KG/avSfPaSUUFD0BA0BA2/H0HD78v4CBqChqAhaNi/BA37l6CBoGHDEjQEDUHDgVDQsP4IGoKGoCFoCBqChv1L0EDQEDRcKAQNQUPQEDQcCK1vgoagIWgIGoKG/UvQEDQy/2BXdft8F4pZ47/7+0aPx+nflwv72flj/cl1Yay2vlX//Z5eP83P3p9fff+qNj7V17/T58Pq+5egIWgIGoKGoCFoCBqChvVH0BA0BA1Bw/4laAgaggaChqAhaDjwCxoOhIKGoCFoCBrmp6AhaAgagoaggaAhaLhQCBqChqAhaAgagoagIWgIGoKGoCFoCBqCBgAAAICgAQAAACBoAAAAAIIGAAAAgKABAAAAIGgAAAAAggYAAACAoAEAAAAgaAAAAACCBgAAAICgAQAAACBoAAAAAAgaAAAAgKABAAAAIGgAAAAACBoAAACAoAEAAAAgaAAAAAAIGgAAAICgAQAAACBoAAAAAAgaAAAAgKABAAAAIGgAAAAAbPAXSdffkpULfXUAAAAASUVORK5CYII=\";\n","/**\n * Canonical model-facing tool-output truncation.\n *\n * Ported from openai/codex `rust-v0.144.6` (commit\n * 5d1fbf26c43abc65a203928b2e31561cb039e06d):\n *\n * - `codex-rs/utils/string/src/truncate.rs`\n * - `codex-rs/utils/output-truncation/src/lib.rs`\n * - `codex-rs/core/src/context_manager/history.rs`\n *\n * The live gpt-5.6 model catalog declares a 10,000-token truncation policy.\n * Codex applies a 1.2x allowance before serializing a function-call output, so\n * the effective textual payload budget is 12,000 approximate tokens. Images,\n * files, and encrypted content are preserved; textual content shares one\n * sequential budget and carries an explicit head/tail truncation marker.\n *\n * This module deliberately has no database or Agents SDK dependency. Both the\n * runtime request seam and the database history boundary call the same pure\n * function, so replayed conversation truth is identical to live model input.\n */\n\nimport { MODEL_TOOL_OUTPUT_OVERSIZED_IMAGE_CARD_DATA_URL } from \"./oversized-image-card\";\n\nexport { MODEL_TOOL_OUTPUT_OVERSIZED_IMAGE_CARD_DATA_URL } from \"./oversized-image-card\";\n\nexport type ModelHistoryItem = Record<string, unknown>;\n\ntype WithoutOutputOnlyProviderDataFields<T> = T extends ModelHistoryItem ? Omit<T, \"status\"> : T;\n\ntype WithoutOutputOnlyProviderDataField<T extends ModelHistoryItem> = \"providerData\" extends keyof T\n ? string extends keyof T\n ? {\n providerData?: WithoutOutputOnlyProviderDataFields<T[\"providerData\"]>;\n }\n : object extends Pick<T, Extract<keyof T, \"providerData\">>\n ? {\n providerData?: WithoutOutputOnlyProviderDataFields<T[\"providerData\"]>;\n }\n : {\n providerData: WithoutOutputOnlyProviderDataFields<T[\"providerData\"]>;\n }\n : object;\n\ntype WithoutOutputOnlyHistoryItemFields<T extends ModelHistoryItem> = T extends unknown\n ? Omit<T, \"status\" | \"providerData\"> & WithoutOutputOnlyProviderDataField<T>\n : never;\n\n/**\n * Responses output items carry `status` (`in_progress` / `completed` /\n * `incomplete`). That field is not conversation meaning — pairing is `call_id`\n * — and Codex's input schema 400s it (`Unknown parameter: 'input[N].status'`).\n * SuperGrok accepts items with or without it. The SDK also nests `status` on\n * `providerData` (reasoning items) and flattens it back onto the request.\n * Canonical history therefore omits both at persist so portable sessions can\n * cross Responses providers.\n */\nexport function omitOutputOnlyHistoryItemFields<T extends ModelHistoryItem>(\n item: T,\n): WithoutOutputOnlyHistoryItemFields<T> {\n if (!item || typeof item !== \"object\") {\n return item as unknown as WithoutOutputOnlyHistoryItemFields<T>;\n }\n const providerData =\n item.providerData && typeof item.providerData === \"object\"\n ? (item.providerData as Record<string, unknown>)\n : null;\n const hasTopStatus = \"status\" in item;\n const hasNestedStatus = Boolean(providerData && \"status\" in providerData);\n if (!hasTopStatus && !hasNestedStatus) {\n return item as unknown as WithoutOutputOnlyHistoryItemFields<T>;\n }\n const next = { ...item };\n if (hasTopStatus) delete (next as Record<string, unknown>).status;\n if (hasNestedStatus && providerData) {\n const { status: _dropped, ...rest } = providerData;\n (next as Record<string, unknown>).providerData = rest;\n }\n return next as unknown as WithoutOutputOnlyHistoryItemFields<T>;\n}\n\n/** Persist/replay boundary: drop output-only fields, then bound tool output. */\nexport function canonicalizePersistedHistoryItem<T extends ModelHistoryItem>(\n item: T,\n policyTokens = DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,\n): WithoutOutputOnlyHistoryItemFields<T> {\n return boundModelToolOutputItem(omitOutputOnlyHistoryItemFields(item), policyTokens);\n}\n\nexport const CODEX_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS = 10_000;\nexport const CODEX_TOOL_OUTPUT_SERIALIZATION_ALLOWANCE = 1.2;\nexport const DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS =\n CODEX_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS;\n\nconst APPROX_BYTES_PER_TOKEN = 4;\n// Twelve decimal digits already describe ~4 TB at four bytes/token, far beyond\n// any JavaScript string the runtime can materialize. Bounding the digit run is\n// security-significant: otherwise a forged multi-megabyte run of digits could\n// make `markerBytes` as large as the entire untrusted tool result and bypass the\n// cap below.\nconst TOKEN_TRUNCATION_MARKER = /…\\d{1,12} tokens truncated…/u;\nconst TOOL_RESULT_TYPES = new Set([\n \"function_call_result\",\n \"function_call_output\",\n \"computer_call_result\",\n \"custom_tool_call_output\",\n \"shell_call_output\",\n \"apply_patch_call_output\",\n]);\nconst STRUCTURAL_STRING_KEYS = new Set([\n \"type\",\n \"role\",\n \"status\",\n \"name\",\n \"id\",\n \"callId\",\n \"call_id\",\n \"namespace\",\n \"detail\",\n \"mimeType\",\n \"media_type\",\n]);\nconst MODEL_TOOL_OUTPUT_MAX_DEPTH = 12;\nconst MODEL_TOOL_OUTPUT_MAX_CONTAINER_ENTRIES = 255;\nconst MODEL_TOOL_OUTPUT_MAX_TOTAL_ENTRIES = 2_048;\nconst MODEL_TOOL_OUTPUT_MAX_PROPERTY_KEY_BYTES = 256;\nconst MODEL_TOOL_OUTPUT_MAX_STRUCTURAL_STRING_TOKENS = 64;\nconst MODEL_TOOL_OUTPUT_STRUCTURAL_STRING_BUDGET_TOKENS = 1_024;\nexport const MODEL_TOOL_OUTPUT_OPAQUE_PAYLOAD_MAX_BYTES = 8 * 1024 * 1024;\n\nconst DEPTH_OMISSION_MARKER =\n \"[OpenGeni omitted subtree: maximum structured tool-output depth exceeded]\";\nconst CYCLE_OMISSION_MARKER = \"[OpenGeni omitted subtree: cyclic tool output]\";\nconst STRUCTURAL_STRING_OMISSION_MARKER =\n \"[OpenGeni omitted structural string: structural budget exhausted]\";\nconst TEXT_FIELD_OMISSION_MARKER = /^\\[omitted text field \\d+ \\.\\.\\.\\]$/u;\nconst TEXT_ITEMS_OMISSION_MARKER = /^\\[omitted \\d+ text items \\.\\.\\.\\]$/u;\nconst STRUCTURAL_ENTRIES_OMISSION_MARKER =\n /^\\[OpenGeni omitted \\d+ structured (?:array items|object properties)\\]$/u;\nconst OPAQUE_PAYLOAD_OMISSION_MARKER =\n /^\\[OpenGeni omitted (?:image|file|encrypted) payload: \\d+ bytes exceeded the bounded model-input allowance\\]$/u;\nconst STRUCTURAL_PROPERTIES_MARKER_KEY = \"__opengeni_omitted_properties__\";\n\ntype OpaqueProtocolKind = \"image\" | \"file\" | \"encrypted\";\n\ntype ModelOutputBoundState = {\n remaining: number;\n remainingStructural: number;\n remainingEntries: number;\n remainingOpaqueBytes: number;\n opaqueOmissions: number;\n lastOpaqueOmissionMarker: string | null;\n omitted: number;\n seen: WeakSet<object>;\n};\n\nexport function modelToolOutputSerializationBudgetTokens(\n policyTokens = DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,\n): number {\n return Math.ceil(Math.max(0, policyTokens) * CODEX_TOOL_OUTPUT_SERIALIZATION_ALLOWANCE);\n}\n\nexport function approximateTokenCount(value: string): number {\n return Math.ceil(Buffer.byteLength(value, \"utf8\") / APPROX_BYTES_PER_TOKEN);\n}\n\n/** Exact Codex-style middle truncation for a token policy. */\nexport function truncateMiddleWithTokenBudget(value: string, maxTokens: number): string {\n if (value.length === 0) return value;\n const maxBytes = Math.max(0, maxTokens) * APPROX_BYTES_PER_TOKEN;\n const valueBytes = Buffer.byteLength(value, \"utf8\");\n if (maxTokens > 0 && valueBytes <= maxBytes) return value;\n // Codex applies this transform once while recording history, so its marker\n // sits just outside the content budget. OpenGeni deliberately enforces the\n // same policy both at canonical persistence and at the final provider seam.\n // Recognize only an output whose excess is no larger than its own canonical\n // marker; this makes that repeated enforcement byte-idempotent without letting\n // an arbitrary oversized string bypass the cap merely by containing marker-like\n // text. The first application remains byte-for-byte Codex 0.144.6 behavior.\n const existingMarker = value.match(TOKEN_TRUNCATION_MARKER)?.[0];\n if (existingMarker && valueBytes <= maxBytes + Buffer.byteLength(existingMarker, \"utf8\")) {\n return value;\n }\n if (maxBytes === 0) {\n return `…${approximateTokenCount(value)} tokens truncated…`;\n }\n\n const leftBudget = Math.floor(maxBytes / 2);\n const rightBudget = maxBytes - leftBudget;\n // Do not materialize `Array.from(value)`: production tool results can be\n // multi-megabyte strings and one JS element per code point multiplies peak\n // memory. A single UTF-8 buffer gives bounded scans at the two cut points.\n const bytes = Buffer.from(value, \"utf8\");\n let leftEnd = Math.min(leftBudget, bytes.length);\n while (leftEnd > 0 && leftEnd < bytes.length && isUtf8ContinuationByte(bytes[leftEnd]!)) {\n leftEnd -= 1;\n }\n let rightStart = Math.max(0, bytes.length - rightBudget);\n while (rightStart < bytes.length && isUtf8ContinuationByte(bytes[rightStart]!)) {\n rightStart += 1;\n }\n const left = bytes.subarray(0, leftEnd).toString(\"utf8\");\n const right = bytes.subarray(rightStart).toString(\"utf8\");\n const removedBytes = Math.max(0, valueBytes - maxBytes);\n const removedTokens = Math.ceil(removedBytes / APPROX_BYTES_PER_TOKEN);\n return `${left}…${removedTokens} tokens truncated…${right}`;\n}\n\nfunction isUtf8ContinuationByte(value: number): boolean {\n return (value & 0xc0) === 0x80;\n}\n\n/**\n * Bound every model-visible tool-result item. Non-result items are returned by\n * reference. Result items are cloned only when their textual output changes.\n */\nexport function boundModelToolOutputItem<T extends ModelHistoryItem>(\n item: T,\n policyTokens = DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,\n): T {\n const type = typeof item.type === \"string\" ? item.type : \"\";\n if (!TOOL_RESULT_TYPES.has(type)) return item;\n const budget = modelToolOutputSerializationBudgetTokens(policyTokens);\n const boundedOutput = boundToolOutputValue(item.output, budget);\n return boundedOutput === item.output ? item : ({ ...item, output: boundedOutput } as T);\n}\n\nexport function boundModelToolOutputItems<T extends ModelHistoryItem>(\n items: readonly T[],\n policyTokens = DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,\n): T[] {\n let bounded: T[] | null = null;\n for (const [index, item] of items.entries()) {\n const next = boundModelToolOutputItem(item, policyTokens);\n if (next !== item && bounded === null) bounded = items.slice(0, index);\n bounded?.push(next);\n }\n return bounded ?? (items as T[]);\n}\n\nfunction boundToolOutputValue(output: unknown, budgetTokens: number): unknown {\n const state = modelOutputBoundState(budgetTokens);\n if (typeof output === \"string\") {\n if (isGeneratedModelOutputMarker(output)) {\n observeGeneratedMarkerBudget(output, state);\n return output;\n }\n // Text-transport computer/view_image tools use a data URL because Chat\n // Completions has no structured image result. It is still image protocol,\n // not textual tool output; truncating its base64 permanently corrupts it.\n if (isImageDataUrl(output)) return boundOpaqueProtocolString(output, state, \"image\");\n return truncateMiddleWithTokenBudget(output, budgetTokens);\n }\n if (Array.isArray(output)) {\n // Responses content arrays have an explicit text/image/file protocol and\n // follow Codex's sequential item policy exactly. Shell/apply adapters can\n // instead return arrays of objects containing stdout/stderr; those share\n // the same total text budget through the generic leaf walker.\n // Inspect only the prefix the boundary can retain. Cardinality itself does\n // not make an otherwise-valid Responses content list invalid, and scanning\n // an untrusted 100k-item tail merely to classify it defeats the bound.\n const isProtocolContent = isResponsesProtocolContentPrefix(output);\n return isProtocolContent\n ? boundStructuredOutputItems(output, state)\n : boundTextLeaves(output, state);\n }\n if (!output || typeof output !== \"object\") return output;\n\n const record = output as Record<string, unknown>;\n // Shell/apply-patch result objects are not structured Responses content, but\n // can contain arbitrarily large stdout/stderr leaves. Preserve useful shape\n // while sharing bounded text, structural, entry, depth, and opaque-protocol\n // budgets across the whole value.\n return boundTextLeaves(record, state);\n}\n\nfunction modelOutputBoundState(budgetTokens: number): ModelOutputBoundState {\n return {\n remaining: Math.max(0, budgetTokens),\n remainingStructural: MODEL_TOOL_OUTPUT_STRUCTURAL_STRING_BUDGET_TOKENS,\n remainingEntries: MODEL_TOOL_OUTPUT_MAX_TOTAL_ENTRIES,\n remainingOpaqueBytes: MODEL_TOOL_OUTPUT_OPAQUE_PAYLOAD_MAX_BYTES,\n opaqueOmissions: 0,\n lastOpaqueOmissionMarker: null,\n omitted: 0,\n seen: new WeakSet(),\n };\n}\n\nfunction boundStructuredOutputItems(items: unknown[], state: ModelOutputBoundState): unknown[] {\n let omitted = 0;\n let changed = false;\n const out: unknown[] = [];\n let processed = 0;\n // A canonical first pass can contain one typed structural trailer beyond the\n // ordinary 255 retained parts. Preserve that exact terminal trailer when a\n // durable/provider/recovery boundary applies the function again. Limiting\n // this exception to an already-bounded array prevents an arbitrary huge tail\n // with a marker-shaped last element from bypassing the first-pass count.\n const terminalStructuralMarker =\n items.length <= MODEL_TOOL_OUTPUT_MAX_CONTAINER_ENTRIES + 1 &&\n isTypedStructuralArrayOmissionMarker(items.at(-1))\n ? items.at(-1)\n : null;\n let preservedTerminalStructuralMarker = false;\n for (let index = 0; index < items.length; index += 1) {\n const item = items[index];\n if (processed >= MODEL_TOOL_OUTPUT_MAX_CONTAINER_ENTRIES || state.remainingEntries <= 0) {\n if (terminalStructuralMarker && index <= items.length - 1) {\n out.push(terminalStructuralMarker);\n preservedTerminalStructuralMarker = true;\n }\n break;\n }\n processed += 1;\n state.remainingEntries -= 1;\n const record = item as Record<string, unknown>;\n if (record.type === \"input_text\" && isGeneratedModelOutputMarker(record.text)) {\n const bounded = boundTextLeaves(item, state, 1);\n out.push(bounded);\n if (item === terminalStructuralMarker) preservedTerminalStructuralMarker = true;\n if (bounded !== item) changed = true;\n continue;\n }\n if (record.type === \"input_text\" && state.remaining === 0) {\n omitted += 1;\n changed = true;\n continue;\n }\n const bounded = boundResponsesProtocolContentItem(record, state);\n out.push(bounded);\n if (item === terminalStructuralMarker) preservedTerminalStructuralMarker = true;\n if (bounded !== item) changed = true;\n }\n if (omitted > 0) {\n out.push({\n type: \"input_text\",\n text: `[omitted ${omitted} text items ...]`,\n });\n }\n const structurallyOmitted = preservedTerminalStructuralMarker ? 0 : items.length - processed;\n if (structurallyOmitted > 0) {\n out.push(typedStructuredArrayOmissionMarker(structurallyOmitted));\n changed = true;\n }\n return changed ? out : items;\n}\n\nfunction boundResponsesProtocolContentItem(\n item: Record<string, unknown>,\n state: ModelOutputBoundState,\n): Record<string, unknown> {\n const opaqueOmissionsBefore = state.opaqueOmissions;\n const bounded = boundTextLeaves(item, state, 1) as Record<string, unknown>;\n // Agents interprets fileId/file_id (and nested image.id) as a provider file\n // reference. Replacing only that string with our data URL would manufacture\n // a fictitious file_id. Normalize the whole overflowing image part instead,\n // removing every ID field while staying inside the Responses content union.\n if (item.type === \"input_image\" && state.opaqueOmissions > opaqueOmissionsBefore) {\n return {\n type: \"input_image\",\n imageUrl: MODEL_TOOL_OUTPUT_OVERSIZED_IMAGE_CARD_DATA_URL,\n };\n }\n // A marker string in `input_file.file` is interpreted by pinned Agents as a\n // file_url. Replace the whole content part instead, so every generated\n // omission remains inside the Responses text/image/file union without\n // inventing a URL or file ID. This also covers cumulative opaque exhaustion.\n if (item.type === \"input_file\" && state.opaqueOmissions > opaqueOmissionsBefore) {\n return typedProtocolTextMarker(\n state.lastOpaqueOmissionMarker ??\n \"[OpenGeni omitted file payload: 0 bytes exceeded the bounded model-input allowance]\",\n );\n }\n return bounded;\n}\n\nfunction boundTextLeaves(\n value: unknown,\n state: ModelOutputBoundState,\n depth = 0,\n opaqueKind: OpaqueProtocolKind | null = null,\n): unknown {\n if (typeof value === \"string\") {\n if (isGeneratedModelOutputMarker(value)) {\n observeGeneratedMarkerBudget(value, state);\n return value;\n }\n if (opaqueKind || isImageDataUrl(value)) {\n return boundOpaqueProtocolString(value, state, opaqueKind ?? \"image\");\n }\n if (state.remaining === 0) {\n state.omitted += 1;\n return `[omitted text field ${state.omitted} ...]`;\n }\n const cost = approximateTokenCount(value);\n if (cost <= state.remaining) {\n state.remaining -= cost;\n return value;\n }\n const bounded = truncateMiddleWithTokenBudget(value, state.remaining);\n state.remaining = 0;\n return bounded;\n }\n if (!value || typeof value !== \"object\") return value;\n if (depth >= MODEL_TOOL_OUTPUT_MAX_DEPTH) return DEPTH_OMISSION_MARKER;\n if (state.seen.has(value)) return CYCLE_OMISSION_MARKER;\n state.seen.add(value);\n if (Array.isArray(value)) {\n const out: unknown[] = [];\n let processed = 0;\n let changed = false;\n for (let index = 0; index < value.length; index += 1) {\n const entry = value[index];\n if (processed >= MODEL_TOOL_OUTPUT_MAX_CONTAINER_ENTRIES || state.remainingEntries <= 0) {\n // A prior pass can add exactly one structural trailer beyond the normal\n // item allowance. Retain only that final trailer for replay idempotence;\n // marker-shaped untrusted entries otherwise consume the same caps as\n // every other entry and cannot form an unbounded bypass.\n if (\n index === value.length - 1 &&\n typeof entry === \"string\" &&\n STRUCTURAL_ENTRIES_OMISSION_MARKER.test(entry)\n ) {\n out.push(entry);\n }\n break;\n }\n processed += 1;\n state.remainingEntries -= 1;\n const bounded = boundTextLeaves(entry, state, depth + 1, opaqueKind);\n out.push(bounded);\n if (bounded !== entry) changed = true;\n }\n const omitted = value.length - out.length;\n if (omitted > 0) {\n out.push(structuredEntriesOmissionMarker(omitted, \"array\"));\n changed = true;\n }\n state.seen.delete(value);\n return changed ? out : value;\n }\n const record = value as Record<string, unknown>;\n const recordOpaqueKind = nonTextProtocolKind(record.type) ?? opaqueKind;\n const entries = Object.entries(record);\n const out: Record<string, unknown> = {};\n let processed = 0;\n let omitted = 0;\n let changed = false;\n for (let index = 0; index < entries.length; index += 1) {\n const [key, entry] = entries[index]!;\n if (processed >= MODEL_TOOL_OUTPUT_MAX_CONTAINER_ENTRIES || state.remainingEntries <= 0) {\n // As with arrays, a bounded prior pass may have appended one final marker\n // property after filling the normal property allowance. Preserve only\n // that terminal marker; forged/interspersed marker properties remain\n // ordinary bounded input.\n if (index === entries.length - 1 && isGeneratedStructuralMarkerProperty(key, entry)) {\n out[key] = entry;\n break;\n }\n omitted += entries.length - index;\n break;\n }\n processed += 1;\n state.remainingEntries -= 1;\n if (Buffer.byteLength(key, \"utf8\") > MODEL_TOOL_OUTPUT_MAX_PROPERTY_KEY_BYTES) {\n omitted += 1;\n changed = true;\n continue;\n }\n const childOpaqueKind = opaqueKindForChild(recordOpaqueKind, key);\n if (typeof entry === \"string\" && childOpaqueKind) {\n const bounded = boundTextLeaves(entry, state, depth + 1, childOpaqueKind);\n out[key] = bounded;\n if (bounded !== entry) changed = true;\n continue;\n }\n if (typeof entry === \"string\" && STRUCTURAL_STRING_KEYS.has(key)) {\n const bounded = boundStructuralString(entry, state);\n out[key] = bounded;\n if (bounded !== entry) changed = true;\n continue;\n }\n const bounded = boundTextLeaves(entry, state, depth + 1, childOpaqueKind);\n out[key] = bounded;\n if (bounded !== entry) changed = true;\n }\n if (omitted > 0) {\n out[uniqueStructuralMarkerKey(out)] = structuredEntriesOmissionMarker(omitted, \"object\");\n changed = true;\n }\n state.seen.delete(value);\n return changed ? out : value;\n}\n\nfunction boundStructuralString(value: string, state: ModelOutputBoundState): string {\n if (isGeneratedModelOutputMarker(value)) {\n observeGeneratedMarkerBudget(value, state);\n return value;\n }\n if (state.remainingStructural === 0) return STRUCTURAL_STRING_OMISSION_MARKER;\n const cost = approximateTokenCount(value);\n const allowance = Math.min(\n MODEL_TOOL_OUTPUT_MAX_STRUCTURAL_STRING_TOKENS,\n state.remainingStructural,\n );\n if (cost <= allowance) {\n state.remainingStructural -= cost;\n return value;\n }\n state.remainingStructural -= allowance;\n return truncateMiddleWithTokenBudget(value, allowance);\n}\n\nfunction boundOpaqueProtocolString(\n value: string,\n state: ModelOutputBoundState,\n kind: OpaqueProtocolKind,\n): string {\n // A prior pass can only have produced this exact static value. Treat it as a\n // consumed image allowance so applying the boundary again is byte-idempotent\n // even when more image fields follow it in the same structured result.\n if (kind === \"image\" && value === MODEL_TOOL_OUTPUT_OVERSIZED_IMAGE_CARD_DATA_URL) {\n state.remainingOpaqueBytes = 0;\n return value;\n }\n const bytes = Buffer.byteLength(value, \"utf8\");\n if (bytes <= state.remainingOpaqueBytes) {\n state.remainingOpaqueBytes -= bytes;\n return value;\n }\n state.remainingOpaqueBytes = 0;\n if (kind === \"image\") {\n state.opaqueOmissions += 1;\n return MODEL_TOOL_OUTPUT_OVERSIZED_IMAGE_CARD_DATA_URL;\n }\n const marker = `[OpenGeni omitted ${kind} payload: ${bytes} bytes exceeded the bounded model-input allowance]`;\n state.opaqueOmissions += 1;\n state.lastOpaqueOmissionMarker = marker;\n return marker;\n}\n\nfunction nonTextProtocolKind(value: unknown): OpaqueProtocolKind | null {\n if (value === \"image\" || value === \"input_image\" || value === \"computer_screenshot\") {\n return \"image\";\n }\n if (value === \"file\" || value === \"input_file\") return \"file\";\n if (value === \"encrypted_content\") return \"encrypted\";\n return null;\n}\n\nfunction opaqueKindForChild(\n kind: OpaqueProtocolKind | null,\n key: string,\n): OpaqueProtocolKind | null {\n if (!kind) return null;\n const opaqueKeys =\n kind === \"image\"\n ? [\"image\", \"image_url\", \"imageUrl\", \"file_id\", \"fileId\", \"id\", \"data\", \"url\", \"source\"]\n : kind === \"file\"\n ? [\n \"file\",\n \"file_data\",\n \"fileData\",\n \"file_url\",\n \"fileUrl\",\n \"file_id\",\n \"fileId\",\n \"id\",\n \"data\",\n \"url\",\n \"content\",\n \"source\",\n ]\n : [\"encrypted_content\", \"content\", \"data\"];\n return opaqueKeys.includes(key) ? kind : null;\n}\n\nfunction structuredEntriesOmissionMarker(count: number, container: \"array\" | \"object\"): string {\n return `[OpenGeni omitted ${count} structured ${container === \"array\" ? \"array items\" : \"object properties\"}]`;\n}\n\nfunction typedProtocolTextMarker(text: string): Record<string, unknown> {\n return { type: \"input_text\", text };\n}\n\nfunction typedStructuredArrayOmissionMarker(count: number): Record<string, unknown> {\n return typedProtocolTextMarker(structuredEntriesOmissionMarker(count, \"array\"));\n}\n\nfunction isTypedStructuralArrayOmissionMarker(value: unknown): boolean {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const record = value as Record<string, unknown>;\n return (\n record.type === \"input_text\" &&\n typeof record.text === \"string\" &&\n STRUCTURAL_ENTRIES_OMISSION_MARKER.test(record.text) &&\n record.text.includes(\"structured array items\")\n );\n}\n\nfunction isGeneratedModelOutputMarker(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n (value === DEPTH_OMISSION_MARKER ||\n value === CYCLE_OMISSION_MARKER ||\n value === STRUCTURAL_STRING_OMISSION_MARKER ||\n TEXT_FIELD_OMISSION_MARKER.test(value) ||\n TEXT_ITEMS_OMISSION_MARKER.test(value) ||\n STRUCTURAL_ENTRIES_OMISSION_MARKER.test(value) ||\n OPAQUE_PAYLOAD_OMISSION_MARKER.test(value))\n );\n}\n\nfunction observeGeneratedMarkerBudget(value: string, state: ModelOutputBoundState): void {\n if (TEXT_FIELD_OMISSION_MARKER.test(value) || TEXT_ITEMS_OMISSION_MARKER.test(value)) {\n state.remaining = 0;\n }\n if (value === STRUCTURAL_STRING_OMISSION_MARKER) state.remainingStructural = 0;\n if (OPAQUE_PAYLOAD_OMISSION_MARKER.test(value)) state.remainingOpaqueBytes = 0;\n}\n\nfunction isGeneratedStructuralMarkerProperty(key: string, value: unknown): boolean {\n return (\n key.startsWith(STRUCTURAL_PROPERTIES_MARKER_KEY) &&\n typeof value === \"string\" &&\n STRUCTURAL_ENTRIES_OMISSION_MARKER.test(value)\n );\n}\n\nfunction uniqueStructuralMarkerKey(record: Record<string, unknown>): string {\n let key = STRUCTURAL_PROPERTIES_MARKER_KEY;\n let suffix = 1;\n while (Object.hasOwn(record, key)) {\n key = `${STRUCTURAL_PROPERTIES_MARKER_KEY}_${suffix}`;\n suffix += 1;\n }\n return key;\n}\n\nfunction isResponsesProtocolContentPrefix(output: unknown[]): boolean {\n if (output.length === 0) return false;\n const retainedPrefixLength = Math.min(output.length, MODEL_TOOL_OUTPUT_MAX_CONTAINER_ENTRIES);\n for (let index = 0; index < retainedPrefixLength; index += 1) {\n const item = output[index];\n if (!item || typeof item !== \"object\" || Array.isArray(item)) return false;\n const record = item as Record<string, unknown>;\n if (record.type === \"input_text\" && typeof record.text === \"string\") continue;\n if (record.type === \"input_image\") continue;\n if (record.type === \"input_file\") continue;\n return false;\n }\n return true;\n}\n\nfunction isImageDataUrl(value: string): boolean {\n return /^data:image\\/[a-z0-9.+-]+;base64,/i.test(value);\n}\n","import { CODEX_CLIENT_VERSION, CODEX_ORIGINATOR, CODEX_RESPONSES_BASE } from \"./constants\";\nimport type { CodexRequestContext, CodexTokenSnapshot } from \"./request-context\";\nimport type { FetchLike } from \"./fetch\";\nimport { pinnedFetch, readJsonBase64Field, readResponseTextBounded } from \"@opengeni/network\";\n\nconst CODEX_IMAGE_MODEL = \"gpt-image-2\";\nconst CODEX_IMAGE_RESPONSE_MAX_BYTES = 90 * 1024 * 1024;\nconst CODEX_IMAGE_ERROR_MAX_BYTES = 64 * 1024;\nconst CODEX_IMAGE_MAX_BYTES = 64 * 1024 * 1024;\nconst CODEX_IMAGE_REQUEST_TIMEOUT_MS = 5 * 60_000;\nconst CODEX_IMAGE_MAX_REFERENCES = 5;\n\nconst codexImageFetch: FetchLike = async (input, init) =>\n await pinnedFetch(\n input,\n init,\n {\n environment: \"production\",\n integrationsAllowPrivateNetworkTargets: false,\n },\n {\n label: \"Codex image generation\",\n requireHttpsOutsideLocalTest: true,\n },\n );\n\nexport type CodexGeneratedImage = {\n bytes: Uint8Array;\n declaredMediaType: \"image/png\";\n};\n\nexport type CodexImageReferenceInput = Readonly<{\n mediaType: \"image/png\" | \"image/jpeg\" | \"image/webp\";\n bytes: Uint8Array;\n}>;\n\nexport class CodexImageApiError extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message);\n this.name = \"CodexImageApiError\";\n }\n}\n\nexport class CodexImageRequestTimeoutError extends Error {\n constructor(readonly timeoutMs: number) {\n super(`Codex image generation timed out after ${Math.ceil(timeoutMs / 1_000)} seconds`);\n this.name = \"CodexImageRequestTimeoutError\";\n }\n}\n\n/**\n * Execute Codex's standalone, client-side image tool against the same\n * ChatGPT/Codex account as the owning model turn. Only a definitive 401 is\n * retried, after refreshing auth; ambiguous transport/5xx outcomes are never\n * replayed because an image request may already have incurred work or cost.\n */\nexport async function generateCodexSubscriptionImage(input: {\n prompt: string;\n references?: readonly CodexImageReferenceInput[];\n turnId: string;\n context: Pick<\n CodexRequestContext,\n \"clientVersion\" | \"getToken\" | \"refresh\" | \"beforeProviderDispatch\"\n >;\n abortSignal?: AbortSignal;\n fetch?: FetchLike;\n /** Internal test/host override; one absolute budget covers auth retry and body streaming. */\n requestTimeoutMs?: number;\n}): Promise<CodexGeneratedImage> {\n const fetchImpl = input.fetch ?? codexImageFetch;\n const timeoutMs = input.requestTimeoutMs ?? CODEX_IMAGE_REQUEST_TIMEOUT_MS;\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {\n throw new RangeError(\"Codex image request timeout must be a positive safe integer\");\n }\n const references = input.references ?? [];\n if (references.length > CODEX_IMAGE_MAX_REFERENCES) {\n throw new RangeError(\n `Codex image editing accepts at most ${CODEX_IMAGE_MAX_REFERENCES} images`,\n );\n }\n for (const reference of references) {\n if (reference.bytes.byteLength === 0) throw new Error(\"Codex image reference is empty\");\n }\n const deadline = new AbortController();\n const timer = setTimeout(\n () => deadline.abort(new CodexImageRequestTimeoutError(timeoutMs)),\n timeoutMs,\n );\n const signal = input.abortSignal\n ? AbortSignal.any([input.abortSignal, deadline.signal])\n : deadline.signal;\n const request = async (auth: CodexTokenSnapshot): Promise<Response> => {\n const headers = codexImageHeaders(auth, input.context.clientVersion, input.turnId);\n await input.context.beforeProviderDispatch?.();\n return await fetchImpl(\n `${CODEX_RESPONSES_BASE}/${references.length > 0 ? \"images/edits\" : \"images/generations\"}`,\n {\n method: \"POST\",\n redirect: \"error\",\n headers,\n body: JSON.stringify(\n references.length > 0\n ? {\n images: references.map((reference) => ({\n image_url: `data:${reference.mediaType};base64,${Buffer.from(reference.bytes).toString(\"base64\")}`,\n })),\n prompt: input.prompt,\n background: \"auto\",\n model: CODEX_IMAGE_MODEL,\n quality: \"auto\",\n size: \"auto\",\n }\n : {\n prompt: input.prompt,\n background: \"auto\",\n model: CODEX_IMAGE_MODEL,\n quality: \"auto\",\n size: \"auto\",\n },\n ),\n signal,\n },\n );\n };\n\n const operation = (async (): Promise<CodexGeneratedImage> => {\n let response = await request(await input.context.getToken());\n if (response.status === 401) {\n await response.body?.cancel().catch(() => undefined);\n response = await request(await input.context.refresh());\n }\n if (!response.ok) {\n const detail = await readResponseTextBounded(\n response,\n CODEX_IMAGE_ERROR_MAX_BYTES,\n \"Codex image error\",\n { signal },\n ).catch(() => \"\");\n throw new CodexImageApiError(\n response.status,\n detail\n ? `Codex image generation failed (${response.status}): ${boundedErrorMessage(detail)}`\n : `Codex image generation failed (${response.status})`,\n );\n }\n\n const bytes = await readJsonBase64Field(response, {\n fieldName: \"b64_json\",\n shape: \"string\",\n maxResponseBytes: CODEX_IMAGE_RESPONSE_MAX_BYTES,\n maxDecodedBytes: CODEX_IMAGE_MAX_BYTES,\n label: \"Codex image generation\",\n signal,\n });\n return { bytes, declaredMediaType: \"image/png\" };\n })();\n let removeAbortListener = (): void => undefined;\n const aborted = new Promise<never>((_resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n if (signal.aborted) {\n onAbort();\n return;\n }\n signal.addEventListener(\"abort\", onAbort, { once: true });\n removeAbortListener = () => signal.removeEventListener(\"abort\", onAbort);\n });\n try {\n // The race is the backstop for credential resolvers and injected transports\n // that do not observe AbortSignal. Promise.race attaches a rejection handler\n // to the losing operation, so it cannot become an unhandled rejection.\n return await Promise.race([operation, aborted]);\n } finally {\n removeAbortListener();\n clearTimeout(timer);\n }\n}\n\nfunction codexImageHeaders(\n auth: CodexTokenSnapshot,\n clientVersion: string,\n turnId: string,\n): Headers {\n const headers = new Headers({\n Authorization: `Bearer ${auth.accessToken}`,\n accept: \"application/json\",\n \"content-type\": \"application/json\",\n originator: CODEX_ORIGINATOR,\n \"User-Agent\": `${CODEX_ORIGINATOR}/${clientVersion || CODEX_CLIENT_VERSION}`,\n version: clientVersion || CODEX_CLIENT_VERSION,\n \"x-codex-image-turn-id\": turnId,\n });\n if (auth.chatgptAccountId) headers.set(\"ChatGPT-Account-ID\", auth.chatgptAccountId);\n if (auth.isFedramp) headers.set(\"X-OpenAI-Fedramp\", \"true\");\n return headers;\n}\n\nfunction boundedErrorMessage(body: string): string {\n let message = body;\n try {\n const value = JSON.parse(body) as {\n error?: { message?: unknown };\n message?: unknown;\n };\n const candidate = value.error?.message ?? value.message;\n if (typeof candidate === \"string\") message = candidate;\n } catch {\n // Preserve a bounded non-JSON provider diagnostic.\n }\n return message.replace(/\\s+/g, \" \").trim().slice(0, 1_000);\n}\n","import { codexSubscriptionHeaders, type CodexAuthHeaders } from \"./api-client\";\nimport {\n CODEX_REALTIME_CALL_TIMEOUT_MS,\n CODEX_REALTIME_CONFIG_ID,\n CODEX_REALTIME_CONFIG_TIMEOUT_MS,\n CODEX_REALTIME_DEFAULT_VOICE,\n CODEX_REALTIME_MODEL,\n CODEX_REALTIME_PROVIDER_ARCHITECTURE_FALLBACK,\n CODEX_REALTIME_PROVIDER_MODEL_FALLBACK,\n CODEX_REALTIME_VERSION,\n CODEX_RESPONSES_BASE,\n CODEX_WHAM_BASE,\n} from \"./constants\";\nimport type { CodexFetch } from \"./device-code\";\nimport {\n CODEX_REALTIME_INITIAL_ITEMS_MAX_COUNT,\n CODEX_REALTIME_INITIAL_ITEMS_MAX_TOKENS,\n type CodexRealtimeInitialItem,\n} from \"./realtime-v3\";\n\nconst MAX_REALTIME_SDP_BYTES = 1024 * 1024;\nconst MAX_REALTIME_PROVIDER_VALUE_LENGTH = 128;\nconst REALTIME_PROVIDER_VALUE = /^[a-z0-9][a-z0-9._-]*$/i;\nconst REALTIME_CALL_ID =\n /^(?:rtc_.+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;\n\nexport const CODEX_REALTIME_VOICES = [\n \"juniper\",\n \"maple\",\n \"spruce\",\n \"ember\",\n \"vale\",\n \"breeze\",\n \"arbor\",\n \"sol\",\n \"cove\",\n] as const;\n\nexport type CodexRealtimeVoice = (typeof CODEX_REALTIME_VOICES)[number];\n\nexport type CodexRealtimeCallInput = {\n /** Browser-created WebRTC offer. It must negotiate an audio media section. */\n sdp: string;\n /** This transport intentionally supports only Codex's Frameless/V3 protocol. */\n version: typeof CODEX_REALTIME_VERSION;\n /** Server-owned session/thread binding; sent upstream but never returned. */\n sessionId: string;\n /** Server-projected ordinary-session history for Frameless V3 bootstrap. */\n initialItems?: CodexRealtimeInitialItem[] | undefined;\n instructions?: string | undefined;\n voice?: CodexRealtimeVoice | undefined;\n};\n\nexport type CodexRealtimeCallResult = {\n sdp: string;\n version: typeof CODEX_REALTIME_VERSION;\n model: typeof CODEX_REALTIME_MODEL;\n};\n\nexport type CodexRealtimeErrorCode =\n | \"invalid_request\"\n | \"incompatible\"\n | \"authentication\"\n | \"entitlement\"\n | \"rate_limited\"\n | \"provider\"\n | \"invalid_response\"\n | \"network\"\n | \"timeout\"\n | \"cancelled\";\n\n/** Safe provider failure: it contains no response body, credential, or account identity. */\nexport class CodexRealtimeError extends Error {\n constructor(\n readonly code: CodexRealtimeErrorCode,\n message: string,\n readonly providerStatus: number | null = null,\n ) {\n super(message);\n this.name = \"CodexRealtimeError\";\n }\n}\n\nexport type CodexRealtimeCallOptions = {\n signal?: AbortSignal | undefined;\n timeoutMs?: number | undefined;\n providerConfig?: CodexRealtimeProviderConfig | undefined;\n};\n\nexport type CodexRealtimeProviderConfig = {\n architecture: string;\n model: string;\n version: typeof CODEX_REALTIME_VERSION;\n};\n\nconst FALLBACK_REALTIME_PROVIDER_CONFIG: CodexRealtimeProviderConfig = {\n architecture: CODEX_REALTIME_PROVIDER_ARCHITECTURE_FALLBACK,\n model: CODEX_REALTIME_PROVIDER_MODEL_FALLBACK,\n version: CODEX_REALTIME_VERSION,\n};\n\n/**\n * Resolve the provider-controlled Codex voice model without changing the\n * stable OpenGeni model id. ChatGPT rotates this config independently of Codex\n * releases; pinning the old value caused deterministic call-creation failures.\n */\nexport async function fetchCodexRealtimeProviderConfig(\n auth: CodexAuthHeaders,\n fetchImpl: CodexFetch = fetch,\n options: {\n signal?: AbortSignal | undefined;\n timeoutMs?: number | undefined;\n } = {},\n): Promise<CodexRealtimeProviderConfig> {\n if (options.signal?.aborted) {\n throw new CodexRealtimeError(\"cancelled\", \"Codex realtime request cancelled\");\n }\n const controller = new AbortController();\n const timeoutMs = options.timeoutMs ?? CODEX_REALTIME_CONFIG_TIMEOUT_MS;\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n const onAbort = (): void => controller.abort(options.signal?.reason);\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n try {\n const response = await fetchImpl(`${CODEX_WHAM_BASE}/wham/statsig/bootstrap`, {\n method: \"POST\",\n headers: {\n ...codexSubscriptionHeaders(auth),\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n app_session_id: crypto.randomUUID(),\n app_version: auth.clientVersion,\n brand_name: \"Codex\",\n build_flavor: \"stable\",\n locale: \"en-US\",\n stable_id: auth.chatgptAccountId ?? \"opengeni-server\",\n system_name: \"OpenGeni\",\n system_version: \"server\",\n window_type: \"local\",\n }),\n signal: controller.signal,\n });\n if (response.status === 401) {\n await response.body?.cancel().catch(() => undefined);\n throw new CodexRealtimeError(\n \"authentication\",\n \"Codex subscription rejected authentication\",\n response.status,\n );\n }\n if (!response.ok) {\n await response.body?.cancel().catch(() => undefined);\n return FALLBACK_REALTIME_PROVIDER_CONFIG;\n }\n const outer = (await response.json().catch(() => null)) as {\n statsigPayload?: unknown;\n } | null;\n if (typeof outer?.statsigPayload !== \"string\") return FALLBACK_REALTIME_PROVIDER_CONFIG;\n const payload = JSON.parse(outer.statsigPayload) as {\n dynamic_configs?: Record<string, { value?: Record<string, unknown> }>;\n };\n const value = payload.dynamic_configs?.[CODEX_REALTIME_CONFIG_ID]?.value;\n const version = value?.version;\n if (version !== undefined && version !== CODEX_REALTIME_VERSION) {\n throw new CodexRealtimeError(\n \"incompatible\",\n `Codex realtime remote configuration requires ${String(version)}`,\n );\n }\n const architecture = validProviderValue(value?.architecture)\n ? value.architecture\n : FALLBACK_REALTIME_PROVIDER_CONFIG.architecture;\n const model = validProviderValue(value?.model)\n ? value.model\n : FALLBACK_REALTIME_PROVIDER_CONFIG.model;\n return { architecture, model, version: CODEX_REALTIME_VERSION };\n } catch (error) {\n if (error instanceof CodexRealtimeError) throw error;\n if (options.signal?.aborted) {\n throw new CodexRealtimeError(\"cancelled\", \"Codex realtime request cancelled\");\n }\n return FALLBACK_REALTIME_PROVIDER_CONFIG;\n } finally {\n clearTimeout(timeout);\n options.signal?.removeEventListener(\"abort\", onAbort);\n }\n}\n\n/**\n * Create one native subscription-authenticated Codex GPT-Live V3 WebRTC call.\n *\n * There is deliberately no API-key or WebSocket fallback and no transport\n * retry. A caller may refresh the same connected subscription after one 401,\n * but this adapter always performs exactly one provider request.\n */\nexport async function createCodexRealtimeCall(\n auth: CodexAuthHeaders,\n input: CodexRealtimeCallInput,\n fetchImpl: CodexFetch = fetch,\n options: CodexRealtimeCallOptions = {},\n): Promise<CodexRealtimeCallResult> {\n validateRealtimeInput(input);\n const timeoutMs = options.timeoutMs ?? CODEX_REALTIME_CALL_TIMEOUT_MS;\n const providerConfig = options.providerConfig ?? FALLBACK_REALTIME_PROVIDER_CONFIG;\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime timeout must be positive\");\n }\n if (options.signal?.aborted) {\n throw new CodexRealtimeError(\"cancelled\", \"Codex realtime request cancelled\");\n }\n if (providerConfig.version !== CODEX_REALTIME_VERSION) {\n throw new CodexRealtimeError(\n \"incompatible\",\n `Codex realtime provider configuration requires ${providerConfig.version}`,\n );\n }\n if (\n !validProviderValue(providerConfig.architecture) ||\n !validProviderValue(providerConfig.model)\n ) {\n throw new CodexRealtimeError(\n \"invalid_request\",\n \"Codex realtime provider configuration is invalid\",\n );\n }\n\n const controller = new AbortController();\n let timedOut = false;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let rejectCancellation: ((error: CodexRealtimeError) => void) | undefined;\n const cancellation = new Promise<never>((_resolve, reject) => {\n rejectCancellation = reject;\n });\n const onAbort = (): void => {\n controller.abort(options.signal?.reason);\n rejectCancellation?.(new CodexRealtimeError(\"cancelled\", \"Codex realtime request cancelled\"));\n };\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n const deadline = new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(() => {\n timedOut = true;\n controller.abort();\n reject(new CodexRealtimeError(\"timeout\", \"Codex realtime request timed out\"));\n }, timeoutMs);\n });\n\n const request = (async (): Promise<CodexRealtimeCallResult> => {\n const response = await fetchImpl(\n `${CODEX_RESPONSES_BASE}/realtime/calls?intent=quicksilver&architecture=${encodeURIComponent(providerConfig.architecture)}`,\n {\n method: \"POST\",\n headers: {\n ...codexSubscriptionHeaders(auth),\n \"content-type\": \"application/json\",\n \"openai-alpha\": \"quicksilver=v2\",\n \"session-id\": input.sessionId,\n \"thread-id\": input.sessionId,\n },\n body: JSON.stringify({\n sdp: input.sdp,\n session: {\n instructions: input.instructions ?? \"\",\n audio: {\n output: { voice: input.voice ?? CODEX_REALTIME_DEFAULT_VOICE },\n },\n delegation: { type: \"client\" },\n model: providerConfig.model,\n ...(input.initialItems?.length\n ? {\n initial_items: input.initialItems.map((item) => ({\n type: \"message\",\n role: item.role,\n content: [\n {\n type: item.role === \"assistant\" ? \"output_text\" : \"input_text\",\n text: item.text,\n },\n ],\n })),\n }\n : {}),\n },\n }),\n signal: controller.signal,\n },\n );\n\n if (!response.ok) {\n await response.body?.cancel().catch(() => undefined);\n throw providerHttpError(response.status);\n }\n const location = response.headers.get(\"location\");\n if (!location || !validRealtimeLocation(location)) {\n await response.body?.cancel().catch(() => undefined);\n throw new CodexRealtimeError(\n \"invalid_response\",\n \"Codex realtime response did not identify a compatible call\",\n response.status,\n );\n }\n const sdp = await readBoundedSdp(response);\n if (!isAudioSdp(sdp)) {\n throw new CodexRealtimeError(\n \"invalid_response\",\n \"Codex realtime response was not an audio SDP answer\",\n response.status,\n );\n }\n return {\n sdp,\n version: CODEX_REALTIME_VERSION,\n model: CODEX_REALTIME_MODEL,\n };\n })();\n\n try {\n // Promise.race attaches rejection handlers to every branch, so a custom\n // fetch that ignores AbortSignal cannot produce a late unhandled rejection.\n return await Promise.race([request, cancellation, deadline]);\n } catch (error) {\n if (error instanceof CodexRealtimeError) throw error;\n if (options.signal?.aborted) {\n throw new CodexRealtimeError(\"cancelled\", \"Codex realtime request cancelled\");\n }\n if (timedOut || controller.signal.aborted) {\n throw new CodexRealtimeError(\"timeout\", \"Codex realtime request timed out\");\n }\n throw new CodexRealtimeError(\"network\", \"Codex realtime provider request failed\");\n } finally {\n if (timeout) clearTimeout(timeout);\n options.signal?.removeEventListener(\"abort\", onAbort);\n }\n}\n\nfunction validProviderValue(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length <= MAX_REALTIME_PROVIDER_VALUE_LENGTH &&\n REALTIME_PROVIDER_VALUE.test(value)\n );\n}\n\n/** Shared pin→active selection for worker turns and direct realtime calls. */\nexport function selectCodexCredentialId(args: {\n sessionPinnedCredentialId: string | null;\n activeCredentialId: string | null;\n connectedIds: ReadonlySet<string>;\n}): string | null {\n if (args.sessionPinnedCredentialId && args.connectedIds.has(args.sessionPinnedCredentialId)) {\n return args.sessionPinnedCredentialId;\n }\n if (args.activeCredentialId && args.connectedIds.has(args.activeCredentialId)) {\n return args.activeCredentialId;\n }\n return null;\n}\n\nfunction validateRealtimeInput(input: CodexRealtimeCallInput): void {\n if (input.version !== CODEX_REALTIME_VERSION) {\n throw new CodexRealtimeError(\n \"incompatible\",\n `Codex realtime requires ${CODEX_REALTIME_VERSION}`,\n );\n }\n if (!input.sessionId || input.sessionId.length > 128) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime session id is invalid\");\n }\n if (new TextEncoder().encode(input.sdp).byteLength > MAX_REALTIME_SDP_BYTES) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime SDP offer is too large\");\n }\n if (!isAudioSdp(input.sdp)) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime requires an audio SDP offer\");\n }\n if (input.voice !== undefined && !CODEX_REALTIME_VOICES.includes(input.voice)) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime voice is unsupported\");\n }\n const initialItems = input.initialItems ?? [];\n if (initialItems.length > CODEX_REALTIME_INITIAL_ITEMS_MAX_COUNT) {\n throw new CodexRealtimeError(\n \"invalid_request\",\n `Codex realtime history exceeds ${CODEX_REALTIME_INITIAL_ITEMS_MAX_COUNT} items`,\n );\n }\n let estimatedTokens = 0;\n for (const item of initialItems) {\n if (\n (item.role !== \"user\" && item.role !== \"developer\" && item.role !== \"assistant\") ||\n typeof item.text !== \"string\"\n ) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime history item is invalid\");\n }\n const itemTokens = Math.ceil(new TextEncoder().encode(item.text).byteLength / 4);\n if (itemTokens > CODEX_REALTIME_INITIAL_ITEMS_MAX_TOKENS) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime history item is too large\");\n }\n estimatedTokens += itemTokens;\n }\n if (estimatedTokens > CODEX_REALTIME_INITIAL_ITEMS_MAX_TOKENS) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime history is too large\");\n }\n}\n\nfunction providerHttpError(status: number): CodexRealtimeError {\n if (status === 401) {\n return new CodexRealtimeError(\n \"authentication\",\n \"Codex subscription rejected authentication\",\n status,\n );\n }\n if (status === 403) {\n return new CodexRealtimeError(\n \"entitlement\",\n \"Codex subscription lacks realtime entitlement\",\n status,\n );\n }\n if (status === 404) {\n return new CodexRealtimeError(\n \"incompatible\",\n \"Codex subscription realtime is unavailable\",\n status,\n );\n }\n if (status === 429) {\n return new CodexRealtimeError(\"rate_limited\", \"Codex realtime is rate limited\", status);\n }\n return new CodexRealtimeError(\"provider\", \"Codex realtime provider request failed\", status);\n}\n\nfunction validRealtimeLocation(location: string): boolean {\n const path = location.split(\"?\", 1)[0] ?? \"\";\n const segment = path.split(\"/\").filter(Boolean).at(-1) ?? \"\";\n return REALTIME_CALL_ID.test(segment);\n}\n\nfunction isAudioSdp(sdp: string): boolean {\n return /^v=0(?:\\r?\\n)/.test(sdp) && /(?:^|\\r?\\n)m=audio\\s/m.test(sdp);\n}\n\nasync function readBoundedSdp(response: Response): Promise<string> {\n const declared = Number(response.headers.get(\"content-length\"));\n if (Number.isFinite(declared) && declared > MAX_REALTIME_SDP_BYTES) {\n await response.body?.cancel().catch(() => undefined);\n throw new CodexRealtimeError(\n \"invalid_response\",\n \"Codex realtime SDP answer is too large\",\n response.status,\n );\n }\n if (!response.body) return \"\";\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n while (true) {\n const next = await reader.read();\n if (next.done) break;\n total += next.value.byteLength;\n if (total > MAX_REALTIME_SDP_BYTES) {\n await reader.cancel();\n throw new CodexRealtimeError(\n \"invalid_response\",\n \"Codex realtime SDP answer is too large\",\n response.status,\n );\n }\n chunks.push(next.value);\n }\n } finally {\n reader.releaseLock();\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n try {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n throw new CodexRealtimeError(\n \"invalid_response\",\n \"Codex realtime SDP answer was not valid UTF-8\",\n response.status,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYO,SAAS,mBAAmB,OAA2C;AAC5E,SAAO,OAAO,UAAU,YAAY,MAAM,WAAW,qBAAqB;AAC5E;;;ACcO,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAGA,eAAsB,gBAAgB,YAAwB,OAAkC;AAC9F,QAAM,MAAM,MAAM,UAAU,GAAG,eAAe,wBAAwB;AAAA,IACpE,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAC9C,MAAM,KAAK,UAAU,EAAE,WAAW,gBAAgB,CAAC;AAAA,EACrD,CAAC;AACD,MAAI,IAAI,WAAW,KAAK;AACtB,UAAM,IAAI,iBAAiB,wDAAwD;AAAA,EACrF;AACA,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,IAAI,iBAAiB,0CAA0C,IAAI,MAAM,EAAE;AAAA,EACnF;AACA,QAAM,OAAQ,MAAM,IAAI,KAAK;AAM7B,SAAO;AAAA,IACL,cAAc,KAAK;AAAA,IACnB,UAAU,KAAK,aAAa,KAAK,YAAY;AAAA,IAC7C,iBAAiB;AAAA,IACjB,iBAAiB,kBAAkB,KAAK,QAAQ;AAAA,EAClD;AACF;AA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AI,CAAC,SAAS,KAAM,QAAO;AAC3B,QAAM,SAAS,SAAS,KAAK,UAAU;AACvC,QAAM,SAAuB,CAAC;AAC9B,MAAI,QAAQ;AACZ,MAAI;AACF,WAAO,MAAM;AACX,YAAM,OAAO,MAAM,OAAO,KAAK;AAC/B,UAAI,KAAK,KAAM;AACf,eAAS,KAAK,MAAM;AACpB,UAAI,QAAQ,wBAAwB;AAClC,cAAM,OAAO,OAAO;AACpB,cAAM,IAAI;AAAA,UACR;AAAA,UACA;AAAA,UACA,SAAS;AAAA,QACX;AAAA,MACF;AACA,aAAO,KAAK,KAAK,KAAK;AAAA,IACxB;AAAA,EACF,UAAE;AACA,WAAO,YAAY;AAAA,EACrB;AACA,QAAM,QAAQ,IAAI,WAAW,KAAK;AAClC,MAAI,SAAS;AACb,aAAW,SAAS,QAAQ;AAC1B,UAAM,IAAI,OAAO,MAAM;AACvB,cAAU,MAAM;AAAA,EAClB;AACA,MAAI;AACF,WAAO,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC,EAAE,OAAO,KAAK;AAAA,EAC/D,QAAQ;AACN,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,MACA,SAAS;AAAA,IACX;AAAA,EACF;AACF;","names":["res","z","headers","bounded","out","processed","changed","omitted"]}
|
|
1
|
+
{"version":3,"sources":["../src/billing.ts","../src/device-code.ts","../src/bounded-operation.ts","../src/refresh.ts","../src/normalize.ts","../src/usage-normalize.ts","../src/reset-credits.ts","../src/api-client.ts","../src/request-context.ts","../src/response-timeout.ts","../src/fetch.ts","../src/opaque-artifact.ts","../src/mcp-sanitize.ts","../src/oversized-image-card.ts","../src/model-output-truncation.ts","../src/images.ts","../src/realtime.ts"],"sourcesContent":["import { CODEX_MODEL_ID_PREFIX } from \"./constants\";\n\n/**\n * Pure NECESSARY condition for a Codex-billed turn: the model id is namespaced\n * for the Codex subscription provider (`codex/<slug>`).\n *\n * This is NOT sufficient to bypass billing — an active, connected workspace\n * credential and the deployment flag (`settings.codexSubscriptionEnabled`) are\n * ALSO required (see `isCodexBilledTurn`/`workspaceCodexSubscriptionActive` in\n * `@opengeni/db`). Used only as a cheap, synchronous short-circuit so the common\n * non-codex path never issues a credential read.\n */\nexport function isCodexBilledModel(model: string | null | undefined): boolean {\n return typeof model === \"string\" && model.startsWith(CODEX_MODEL_ID_PREFIX);\n}\n","// Device-code (headless) login flow for a ChatGPT/Codex subscription.\n// Grounded in codex-rs device_code_auth.rs:67-145 + server.rs:732-766 (spec §1.1).\n// Every call takes an injectable fetch so tests can supply a fake.\n\nimport {\n CODEX_AUTH_BASE,\n CODEX_CLIENT_ID,\n CODEX_DEVICE_REDIRECT_URI,\n CODEX_DEVICE_VERIFICATION_URL,\n CODEX_TOKEN_URL,\n} from \"./constants\";\n\nexport type CodexFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;\n\nexport type CodexDeviceStart = {\n deviceAuthId: string;\n userCode: string;\n verificationUri: string;\n intervalSeconds: number;\n};\n\nexport type CodexTokens = { idToken: string; accessToken: string; refreshToken: string };\n\nexport type CodexPollResult =\n | { status: \"pending\" }\n | { status: \"expired\" }\n | { status: \"authorized\"; authorizationCode: string; codeVerifier: string };\n\nexport class CodexDeviceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CodexDeviceError\";\n }\n}\n\n/** Step 1: POST {auth}/deviceauth/usercode {client_id}. device_code_auth.rs:67-95 */\nexport async function startDeviceCode(fetchImpl: CodexFetch = fetch): Promise<CodexDeviceStart> {\n const res = await fetchImpl(`${CODEX_AUTH_BASE}/deviceauth/usercode`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ client_id: CODEX_CLIENT_ID }),\n });\n if (res.status === 404) {\n throw new CodexDeviceError(\"device code login is not enabled for this Codex server\");\n }\n if (!res.ok) {\n throw new CodexDeviceError(`device code request failed with status ${res.status}`);\n }\n const body = (await res.json()) as {\n device_auth_id: string;\n user_code?: string;\n usercode?: string;\n interval?: string | number;\n };\n return {\n deviceAuthId: body.device_auth_id,\n userCode: body.user_code ?? body.usercode ?? \"\",\n verificationUri: CODEX_DEVICE_VERIFICATION_URL,\n intervalSeconds: normalizeInterval(body.interval),\n };\n}\n\n/** Clamp the poll interval to a sane minimum: a missing/0/NaN value must not become a 0-delay poll loop. */\nfunction normalizeInterval(raw: string | number | undefined): number {\n const n = typeof raw === \"string\" ? Number.parseInt(raw.trim(), 10) : raw;\n return typeof n === \"number\" && Number.isFinite(n) && n >= 1 ? n : 5;\n}\n\n/** Step 3 (single, non-blocking): POST {auth}/deviceauth/token. 403/404 => pending. device_code_auth.rs:106-145 */\nexport async function pollDeviceCode(\n input: { deviceAuthId: string; userCode: string },\n fetchImpl: CodexFetch = fetch,\n): Promise<CodexPollResult> {\n const res = await fetchImpl(`${CODEX_AUTH_BASE}/deviceauth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ device_auth_id: input.deviceAuthId, user_code: input.userCode }),\n });\n if (res.ok) {\n const body = (await res.json()) as { authorization_code: string; code_verifier: string };\n return {\n status: \"authorized\",\n authorizationCode: body.authorization_code,\n codeVerifier: body.code_verifier,\n };\n }\n if (res.status === 403 || res.status === 404) {\n return { status: \"pending\" };\n }\n throw new CodexDeviceError(`device auth failed with status ${res.status}`);\n}\n\n/** Step 4: POST {issuer}/oauth/token form-encoded grant_type=authorization_code. server.rs:732-766 */\nexport async function exchangeDeviceCode(\n input: { authorizationCode: string; codeVerifier: string },\n fetchImpl: CodexFetch = fetch,\n): Promise<CodexTokens> {\n const form = new URLSearchParams({\n grant_type: \"authorization_code\",\n code: input.authorizationCode,\n redirect_uri: CODEX_DEVICE_REDIRECT_URI,\n client_id: CODEX_CLIENT_ID,\n code_verifier: input.codeVerifier,\n });\n const res = await fetchImpl(CODEX_TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: form.toString(),\n });\n if (!res.ok) {\n throw new CodexDeviceError(`device code exchange failed with status ${res.status}`);\n }\n const body = (await res.json()) as {\n id_token: string;\n access_token: string;\n refresh_token: string;\n };\n return {\n idToken: body.id_token,\n accessToken: body.access_token,\n refreshToken: body.refresh_token,\n };\n}\n","export type CodexOperationFailureReason = \"network_error\" | \"timeout\";\n\n/**\n * Bound the complete provider operation, including response-body consumption.\n *\n * AbortController makes native fetch release its socket, while Promise.race is\n * the backstop for injected/custom fetch implementations that ignore `signal`.\n * The losing operation is rejection-handled and can never become an unhandled\n * promise after the caller has received the timeout result.\n */\nexport async function runBoundedCodexOperation<T>(\n operation: (signal: AbortSignal) => Promise<T>,\n timeoutMs: number,\n): Promise<{ ok: true; value: T } | { ok: false; reason: CodexOperationFailureReason }> {\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new Error(\"Codex operation timeout must be positive\");\n }\n\n const controller = new AbortController();\n let timedOut = false;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const work = operation(controller.signal).then(\n (value) => ({ ok: true as const, value }),\n () => ({\n ok: false as const,\n reason:\n timedOut || controller.signal.aborted ? (\"timeout\" as const) : (\"network_error\" as const),\n }),\n );\n const deadline = new Promise<{ ok: false; reason: \"timeout\" }>((resolve) => {\n timeout = setTimeout(() => {\n timedOut = true;\n controller.abort();\n resolve({ ok: false, reason: \"timeout\" });\n }, timeoutMs);\n });\n\n try {\n return await Promise.race([work, deadline]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n","// Token refresh + JWT helpers + permanent-failure classification.\n// Refresh is JSON-bodied (exchange is form-encoded — spec §1.1 contrasts these).\n// Classification mirrors codex-rs manager.rs:180-184.\n\nimport { CODEX_CLIENT_ID, CODEX_ID_TOKEN_AUTH_CLAIM, CODEX_TOKEN_URL } from \"./constants\";\nimport type { CodexFetch } from \"./device-code\";\nimport { runBoundedCodexOperation } from \"./bounded-operation\";\n\nconst CODEX_REFRESH_TIMEOUT_MS = 5_000;\n\n/** Permanent — the workspace must reconnect (status => needs_relogin). */\nexport class CodexReloginRequired extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CodexReloginRequired\";\n }\n}\n\n/** Transient — safe to retry later. */\nexport class CodexRefreshTransient extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CodexRefreshTransient\";\n }\n}\n\n/** Only present fields are returned (the server may rotate any subset). */\nexport type CodexRefreshTokens = {\n idToken?: string | undefined;\n accessToken?: string | undefined;\n refreshToken?: string | undefined;\n};\n\n/** POST {issuer}/oauth/token JSON {client_id, grant_type:\"refresh_token\", refresh_token}. manager.rs:1336-1340 */\nexport async function refreshCodexToken(\n refreshToken: string,\n fetchImpl: CodexFetch = fetch,\n timeoutMs = CODEX_REFRESH_TIMEOUT_MS,\n): Promise<CodexRefreshTokens> {\n const fetched = await runBoundedCodexOperation(async (signal) => {\n const res = await fetchImpl(CODEX_TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n client_id: CODEX_CLIENT_ID,\n grant_type: \"refresh_token\",\n refresh_token: refreshToken,\n }),\n signal,\n });\n return { res, text: await res.text() };\n }, timeoutMs);\n if (!fetched.ok) {\n throw new CodexRefreshTransient(`Codex token refresh ${fetched.reason}`);\n }\n const { res, text } = fetched.value;\n if (!res.ok) {\n const code = extractRefreshErrorCode(text);\n const msg = code ? PERMANENT_REFRESH_FAILURES[code] : undefined;\n if (msg) {\n throw new CodexReloginRequired(msg);\n }\n if (res.status === 401) {\n throw new CodexReloginRequired(\n \"Your Codex session could not be refreshed. Please disconnect and sign in again.\",\n );\n }\n throw new CodexRefreshTransient(`Failed to refresh Codex token: ${res.status}`);\n }\n const body = JSON.parse(text) as {\n id_token?: string;\n access_token?: string;\n refresh_token?: string;\n };\n return {\n idToken: body.id_token,\n accessToken: body.access_token,\n refreshToken: body.refresh_token,\n };\n}\n\n// Codes that mean the refresh token is permanently dead -> reconnect required.\n// Includes the standard OAuth `invalid_grant` alongside the Codex-specific codes.\nconst PERMANENT_REFRESH_FAILURES: Record<string, string> = {\n refresh_token_expired:\n \"Your Codex refresh token has expired. Please disconnect and sign in again.\",\n refresh_token_reused:\n \"Your Codex refresh token was already used. Please disconnect and sign in again.\",\n refresh_token_invalidated:\n \"Your Codex refresh token was revoked. Please disconnect and sign in again.\",\n invalid_grant: \"Your Codex session is no longer valid. Please disconnect and sign in again.\",\n};\n\n/** Pull an error code from any of the shapes the auth server may return. */\nfunction extractRefreshErrorCode(text: string): string | undefined {\n try {\n const o = JSON.parse(text) as Record<string, unknown>;\n const err = o.error;\n if (typeof err === \"string\") {\n return err; // { \"error\": \"invalid_grant\" }\n }\n if (err && typeof err === \"object\") {\n const e = err as Record<string, unknown>;\n if (typeof e.code === \"string\") return e.code; // { \"error\": { \"code\": \"...\" } }\n if (typeof e.type === \"string\") return e.type;\n }\n if (typeof o.code === \"string\") return o.code; // { \"code\": \"...\" }\n if (typeof o.type === \"string\") return o.type;\n } catch {\n /* not JSON */\n }\n return undefined;\n}\n\n/** Decode a JWT payload (base64url, no signature check). */\nexport function decodeJwtPayload(jwt: string): Record<string, unknown> | null {\n const part = jwt.split(\".\")[1];\n if (!part) {\n return null;\n }\n try {\n const json = Buffer.from(part.replace(/-/g, \"+\").replace(/_/g, \"/\"), \"base64\").toString(\"utf8\");\n return JSON.parse(json) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n/** access-token `exp` claim -> Date | null. token_data.rs:101-105 */\nexport function accessTokenExpiry(accessToken: string): Date | null {\n const payload = decodeJwtPayload(accessToken);\n return typeof payload?.exp === \"number\" ? new Date(payload.exp * 1000) : null;\n}\n\n/** id_token -> {chatgptAccountId, planType, isFedramp}. server.rs:827-832; token_data.rs:71-99 */\nexport function parseIdToken(idToken: string): {\n chatgptAccountId: string | null;\n planType: string | null;\n isFedramp: boolean;\n email: string | null;\n} {\n const payload = decodeJwtPayload(idToken);\n const auth = (payload?.[CODEX_ID_TOKEN_AUTH_CLAIM] ?? {}) as Record<string, unknown>;\n return {\n chatgptAccountId: typeof auth.chatgpt_account_id === \"string\" ? auth.chatgpt_account_id : null,\n planType: typeof auth.chatgpt_plan_type === \"string\" ? auth.chatgpt_plan_type : null,\n isFedramp: auth.chatgpt_account_is_fedramp === true,\n // The user's own email (standard OIDC `email` claim on the id_token); a\n // non-secret display field for the accounts UI. Null when absent.\n email: typeof payload?.email === \"string\" ? payload.email : null,\n };\n}\n","// Pure request-body + model-slug transforms for the ChatGPT/Codex backend.\n//\n// Per the verified NORMALIZATION VERDICT (CODEX-IMPL-PACKET §0), against our\n// @openai/agents stack we do EXACTLY this and no more:\n// - force store:false\n// - union include with reasoning.encrypted_content\n// - strip max_output_tokens / max_completion_tokens\n// - reasoning effort minimal -> low\n// - normalize the model slug (longest-prefix against the live catalog)\n// - strip every item `id` and `status` but PRESERVE `call_id`\n// We do NOT filter item_reference (the SDK never emits it) and do NOT convert\n// orphaned tool outputs (the SDK's runner already prunes by call_id).\n//\n// `status` is an output annotation SuperGrok (and some Responses items) persist\n// on messages / function_call / function_call_output. Codex's strict input\n// schema 400s `Unknown parameter: 'input[N].status'` — observed live on a\n// portable SuperGrok → Codex switch. Pairing uses `call_id`, never `status`.\n\nconst MINIMAL = \"minimal\";\n\n// The ChatGPT/Codex backend is a STRICT ALLOWLIST: it 400s on ANY top-level field\n// the Codex CLI itself does not send (confirmed live against the backend —\n// \"Unsupported parameter: temperature / top_p / metadata / previous_response_id /\n// logprobs / user / safety_identifier / truncation / max_tool_calls /\n// background / conversation\", and \"Unsupported tool type: mcp\").\n// `service_tier` is allowlisted for Codex Fast mode (`priority`; config may say\n// `fast` and maps to the same request value). Our @openai/agents stack adds\n// several other fields, so after our transforms we keep ONLY the codex\n// Responses payload fields (CODEX-SUBSCRIPTION-SPEC §1 field table).\nconst CODEX_ALLOWED_TOP_LEVEL_KEYS = new Set<string>([\n \"model\",\n \"instructions\",\n \"input\",\n \"tools\",\n \"tool_choice\",\n \"parallel_tool_calls\",\n \"reasoning\",\n \"store\",\n \"stream\",\n \"include\",\n \"prompt_cache_key\",\n \"text\",\n \"service_tier\",\n]);\n\n/** Mutates a parsed Responses request body in place and returns it. Pure + synchronous + unit-testable. */\nexport function normalizeCodexRequestBody(\n body: Record<string, unknown>,\n resolveModel: (slug: string) => string,\n): Record<string, unknown> {\n body.store = false; // ChatGPT backend REQUIRES store=false (spec §1.3)\n body.stream = true; // ChatGPT backend REQUIRES stream=true (confirmed live: 400 \"Stream must be set to true\").\n\n // include MUST contain reasoning.encrypted_content (stateless continuity, spec §1.6)\n const include = Array.isArray(body.include)\n ? (body.include as unknown[]).filter((v): v is string => typeof v === \"string\")\n : [];\n if (!include.includes(\"reasoning.encrypted_content\")) {\n include.push(\"reasoning.encrypted_content\");\n }\n body.include = include;\n\n // reasoning effort: minimal -> low (backend rejects minimal). spec §1.5\n const reasoning = body.reasoning as { effort?: string } | null | undefined;\n if (reasoning && reasoning.effort === MINIMAL) {\n reasoning.effort = \"low\";\n }\n\n // model slug: longest-prefix against the live catalog. spec §1.4\n if (typeof body.model === \"string\") {\n body.model = resolveModel(body.model);\n }\n\n // strip every item id and status; PRESERVE call_id. spec §1.6 / verdict §0(b)\n // (This also covers tool_search items: the backend accepts an id-less\n // tool_search_call/output pair correlated by call_id — verified live — and\n // stripping the provider-stored `tsc_…` id here sanitizes BOTH replay paths.)\n // `status` is output-only on Codex input items. New rows omit it at persist;\n // this wire strip remains defense for already-stored SuperGrok rows and\n // mid-turn SDK items.\n if (Array.isArray(body.input)) {\n for (const item of body.input as unknown[]) {\n if (!item || typeof item !== \"object\") {\n continue;\n }\n const record = item as Record<string, unknown>;\n if (\"id\" in record) {\n delete record.id;\n }\n if (\"status\" in record) {\n delete record.status;\n }\n // A replayed tool_search_call must carry `arguments` as an OBJECT — the\n // backend 400s a string (\"Invalid type for 'input[N].arguments': expected\n // an object\", verified live). The live wire emits an object (the SDK's\n // protocol schema is z.unknown() and round-trips it), so this only fires\n // for a defensively-stringified row; unparseable strings fall back to {}.\n if (record.type === \"tool_search_call\" && typeof record.arguments === \"string\") {\n try {\n const parsed = JSON.parse(record.arguments) as unknown;\n record.arguments = parsed && typeof parsed === \"object\" ? parsed : {};\n } catch {\n record.arguments = {};\n }\n }\n }\n }\n\n // Drop hosted-MCP tool entries: the backend rejects them (\"Unsupported tool\n // type: mcp\"). OpenGeni's MCP servers are client-connected, so their tools\n // already arrive as `function` tools — this only sheds a stray `mcp` entry.\n if (Array.isArray(body.tools)) {\n body.tools = (body.tools as unknown[]).filter(\n (t) => !(t && typeof t === \"object\" && (t as Record<string, unknown>).type === \"mcp\"),\n );\n }\n\n // Final allowlist: shed every other top-level field our @openai/agents stack\n // may have added (temperature, top_p, metadata, previous_response_id,\n // max_output_tokens, truncation, …) so the strict backend does not 400.\n for (const key of Object.keys(body)) {\n if (!CODEX_ALLOWED_TOP_LEVEL_KEYS.has(key)) {\n delete body[key];\n }\n }\n return body;\n}\n\n/**\n * Copy-on-write form for model clients that may retain converted input items.\n * Only records the mutable normalizer can touch are copied; large content,\n * tools, and unchanged protocol items remain shared immutable values.\n */\nexport function normalizedCodexRequestBody(\n body: Readonly<Record<string, unknown>>,\n resolveModel: (slug: string) => string,\n): Record<string, unknown> {\n const projected: Record<string, unknown> = { ...body };\n if (body.reasoning && typeof body.reasoning === \"object\" && !Array.isArray(body.reasoning)) {\n projected.reasoning = { ...(body.reasoning as Record<string, unknown>) };\n }\n if (Array.isArray(body.input)) {\n projected.input = body.input.map((item) => {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) return item;\n const record = item as Record<string, unknown>;\n return \"id\" in record ||\n \"status\" in record ||\n (record.type === \"tool_search_call\" && typeof record.arguments === \"string\")\n ? { ...record }\n : item;\n });\n }\n return normalizeCodexRequestBody(projected, resolveModel);\n}\n\n/**\n * Build a longest-prefix model resolver. Catalog slugs come from GET /models\n * (api-client.ts). One leading `namespace/` segment is stripped first; an\n * unknown slug returns the fallback (caller should log — spec §1.4 step 4).\n */\nexport function buildModelResolver(\n liveSlugs: readonly string[],\n fallbackSlug: string,\n): (slug: string) => string {\n return (requested: string): string => {\n const stripped = requested.includes(\"/\")\n ? requested.slice(requested.indexOf(\"/\") + 1)\n : requested;\n let best = \"\";\n for (const slug of liveSlugs) {\n if (stripped.startsWith(slug) && slug.length > best.length) {\n best = slug;\n }\n }\n return best || fallbackSlug;\n };\n}\n","// Normalizer for GET /wham/usage (P2). The live body exposes `used_percent` +\n// reset timing per window and NO raw used/limit/remaining integer counts (the only\n// raw counts live under `credits.approx_*_messages`). So the brief's\n// used/limit/remaining/percent/resetAt shape is SYNTHESIZED off `used_percent`,\n// with `percent` authoritative and used/limit/remaining carried on a normalized\n// 0–100 scale (limit = 100). `remaining = 100 - percent` is the P3 rotation key\n// (rotationStrategy:\"most_remaining\" ranks by max(min(fiveHour, weekly).remaining)).\n//\n// Windows are identified by `limit_window_seconds` (18000 ⇒ 5h, 604800 ⇒ weekly),\n// NEVER by position. A 200 may carry `limit_reached:true`; a 404 carries a\n// limit-reached body. The parser is zod over rate_limit.{primary,secondary}_window.\n\nimport * as z from \"zod/v4\";\nimport {\n parseCodexRateLimitResetCreditsSummary,\n type CodexRateLimitResetCreditsSummary,\n} from \"./reset-credits\";\n\n/** The 5-hour (primary) window's `limit_window_seconds`. */\nexport const CODEX_FIVE_HOUR_WINDOW_SECONDS = 18000;\n/** The weekly (secondary) window's `limit_window_seconds`. */\nexport const CODEX_WEEKLY_WINDOW_SECONDS = 604800;\n\n/** One normalized usage window (applied to BOTH primary_window and secondary_window). */\nexport type CodexUsageWindow = {\n used: number; // = percent (0–100 scale, limit = 100)\n limit: number; // = 100 (normalized; the provider gives no raw cap)\n remaining: number; // = 100 - percent ← P3 rotation key\n percent: number; // = used_percent (authoritative)\n resetAt: string | null; // ISO 8601, from reset_at*1000 (absolute), or derived from reset_after_seconds\n resetAfterSeconds: number | null; // from reset_after_seconds (skew-free countdown)\n limitWindowSeconds: number; // 18000 | 604800 — identify the window, never positional\n};\n\n/** One additional (per-feature) limit (forward-compat; P2 renders nothing from it). */\nexport type CodexAdditionalLimit = {\n limitName: string;\n meteredFeature: string;\n fiveHour: CodexUsageWindow | null;\n weekly: CodexUsageWindow | null;\n};\n\nexport type CodexUsageStatus = \"ok\" | \"limit_reached\" | \"error\" | \"no-data\";\n\n/** The normalized usage payload — the P2/P3 contract. */\nexport type CodexUsagePayload = {\n status: CodexUsageStatus;\n planType: string | null; // \"pro\" | \"plus\" | ... (rate row label)\n fiveHour: CodexUsageWindow | null; // ← rate_limit.primary_window (limitWindowSeconds === 18000)\n weekly: CodexUsageWindow | null; // ← rate_limit.secondary_window (604800)\n limitReached: boolean; // rate_limit.limit_reached || !rate_limit.allowed\n fetchedAt: string; // ISO; server stamp\n /**\n * Authoritative count-only reset-credit summary from the usage response.\n * Detail rows are fetched separately and are never synthesized from this.\n */\n rateLimitResetCredits: CodexRateLimitResetCreditsSummary | null;\n /** Present only on a refresh/auth failure path; carries the precise reason. */\n reason?: \"needs_relogin\" | undefined;\n // forward-compat, populated but unused in P2:\n additionalLimits?: CodexAdditionalLimit[] | undefined;\n credits?:\n | {\n hasCredits: boolean;\n unlimited: boolean;\n overageLimitReached: boolean;\n balance: string;\n }\n | undefined;\n};\n\n/**\n * Build a normalized window from the PERSISTED cache columns (used_percent +\n * absolute reset timestamp). The same 0–100 synthesis as the live path, with the\n * skew-free countdown derived from `resetAt − now` at read time. Returns null when\n * there is no cached percent yet. `limitWindowSeconds` is the constant that\n * identifies the window (18000 ⇒ 5h, 604800 ⇒ weekly).\n */\nexport function buildCodexUsageWindowFromCache(\n usedPercent: number | null | undefined,\n resetAt: Date | string | null | undefined,\n limitWindowSeconds: number,\n): CodexUsageWindow | null {\n if (typeof usedPercent !== \"number\") {\n return null;\n }\n const percent = clampPercent(usedPercent);\n const resetDate = resetAt ? new Date(resetAt) : null;\n const resetIso = resetDate && !Number.isNaN(resetDate.getTime()) ? resetDate.toISOString() : null;\n const resetAfterSeconds =\n resetDate && !Number.isNaN(resetDate.getTime())\n ? Math.max(0, Math.round((resetDate.getTime() - Date.now()) / 1000))\n : null;\n return {\n used: percent,\n limit: 100,\n remaining: 100 - percent,\n percent,\n resetAt: resetIso,\n resetAfterSeconds,\n limitWindowSeconds,\n };\n}\n\nconst windowSchema = z\n .object({\n used_percent: z.number().optional(),\n reset_after_seconds: z.number().optional(),\n reset_at: z.number().optional(),\n limit_window_seconds: z.number().optional(),\n })\n .nullish();\n\nconst rateLimitSchema = z\n .object({\n allowed: z.boolean().optional(),\n limit_reached: z.boolean().optional(),\n primary_window: windowSchema,\n secondary_window: windowSchema,\n })\n .nullish();\n\nconst additionalLimitSchema = z.object({\n limit_name: z.string().optional(),\n metered_feature: z.string().optional(),\n primary_window: windowSchema,\n secondary_window: windowSchema,\n});\n\nconst creditsSchema = z\n .object({\n has_credits: z.boolean().optional(),\n unlimited: z.boolean().optional(),\n overage_limit_reached: z.boolean().optional(),\n balance: z.union([z.string(), z.number()]).optional(),\n })\n .nullish();\n\nconst usageBodySchema = z.object({\n plan_type: z.string().nullish(),\n rate_limit: rateLimitSchema,\n additional_limits: z.array(additionalLimitSchema).nullish(),\n credits: creditsSchema,\n});\n\ntype RawWindow = z.infer<typeof windowSchema>;\n\nfunction clampPercent(value: number): number {\n if (!Number.isFinite(value)) return 0;\n return Math.min(100, Math.max(0, Math.round(value)));\n}\n\n/** Build a normalized window from a raw provider window, or null when it carries no percent. */\nfunction normalizeWindow(w: RawWindow): CodexUsageWindow | null {\n if (!w || typeof w.used_percent !== \"number\") {\n return null;\n }\n const percent = clampPercent(w.used_percent);\n const resetAfterSeconds =\n typeof w.reset_after_seconds === \"number\"\n ? Math.max(0, Math.round(w.reset_after_seconds))\n : null;\n let resetAt: string | null = null;\n if (typeof w.reset_at === \"number\") {\n resetAt = new Date(w.reset_at * 1000).toISOString(); // epoch SECONDS → ms\n } else if (resetAfterSeconds != null) {\n resetAt = new Date(Date.now() + resetAfterSeconds * 1000).toISOString();\n }\n return {\n used: percent,\n limit: 100,\n remaining: 100 - percent,\n percent,\n resetAt,\n resetAfterSeconds,\n limitWindowSeconds: typeof w.limit_window_seconds === \"number\" ? w.limit_window_seconds : 0,\n };\n}\n\n/**\n * Map the two named windows to fiveHour/weekly by `limit_window_seconds`\n * (18000 vs 604800), NEVER by position; fall back to position (primary ⇒ 5h,\n * secondary ⇒ weekly) only for a window whose limit_window_seconds is absent.\n */\nfunction pickWindows(\n primary: RawWindow,\n secondary: RawWindow,\n): { fiveHour: CodexUsageWindow | null; weekly: CodexUsageWindow | null } {\n let fiveHour: CodexUsageWindow | null = null;\n let weekly: CodexUsageWindow | null = null;\n // Track each unplaced window with the slot it came from, so the positional\n // fallback can place it (re-normalizing produces a fresh object that would\n // never match by reference — the bug this replaces).\n const unplaced: Array<{\n slot: \"primary\" | \"secondary\";\n window: CodexUsageWindow;\n }> = [];\n for (const [slot, raw] of [\n [\"primary\", primary],\n [\"secondary\", secondary],\n ] as const) {\n const nw = normalizeWindow(raw);\n if (!nw) continue;\n if (nw.limitWindowSeconds === CODEX_WEEKLY_WINDOW_SECONDS) {\n weekly = nw;\n } else if (nw.limitWindowSeconds === CODEX_FIVE_HOUR_WINDOW_SECONDS) {\n fiveHour = nw;\n } else {\n unplaced.push({ slot, window: nw });\n }\n }\n // Positional fallback for windows whose limit_window_seconds was absent/unknown\n // (primary ⇒ 5h, secondary ⇒ weekly).\n for (const { slot, window } of unplaced) {\n if (slot === \"primary\" && !fiveHour) fiveHour = window;\n else if (slot === \"secondary\" && !weekly) weekly = window;\n }\n return { fiveHour, weekly };\n}\n\n/**\n * Normalize a /wham/usage fetch result into the P2/P3 contract.\n *\n * @param httpStatus the HTTP status from fetchCodexUsage (404 ⇒ a limit body)\n * @param rawPayload the parsed JSON body (or null when the body was unreadable)\n */\nexport function normalizeCodexUsage(httpStatus: number, rawPayload: unknown): CodexUsagePayload {\n const fetchedAt = new Date().toISOString();\n const parsed = usageBodySchema.safeParse(rawPayload);\n const body = parsed.success ? parsed.data : null;\n\n const base: CodexUsagePayload = {\n status: \"no-data\",\n planType: body?.plan_type ?? null,\n fiveHour: null,\n weekly: null,\n limitReached: false,\n fetchedAt,\n rateLimitResetCredits: parseCodexRateLimitResetCreditsSummary(rawPayload),\n };\n\n // A non-404 HTTP error, or a body we could not parse at all, is an error state.\n if ((httpStatus >= 400 && httpStatus !== 404) || body == null) {\n return { ...base, status: \"error\" };\n }\n\n const rate = body.rate_limit ?? null;\n const { fiveHour, weekly } = pickWindows(\n rate?.primary_window ?? null,\n rate?.secondary_window ?? null,\n );\n const limitReached =\n !!(rate?.limit_reached || rate?.allowed === false) ||\n (fiveHour?.percent ?? 0) >= 100 ||\n (weekly?.percent ?? 0) >= 100;\n\n const additionalLimits: CodexAdditionalLimit[] | undefined = body.additional_limits\n ? body.additional_limits.map((al) => {\n const windows = pickWindows(al.primary_window ?? null, al.secondary_window ?? null);\n return {\n limitName: al.limit_name ?? \"\",\n meteredFeature: al.metered_feature ?? \"\",\n fiveHour: windows.fiveHour,\n weekly: windows.weekly,\n };\n })\n : undefined;\n\n const credits = body.credits\n ? {\n hasCredits: body.credits.has_credits ?? false,\n unlimited: body.credits.unlimited ?? false,\n overageLimitReached: body.credits.overage_limit_reached ?? false,\n balance: body.credits.balance != null ? String(body.credits.balance) : \"0\",\n }\n : undefined;\n\n // Status derivation: 404 ⇒ limit_reached; a 200 may still carry limit_reached;\n // succeeded-but-no-windows ⇒ no-data; otherwise ok.\n let status: CodexUsageStatus;\n if (httpStatus === 404 || limitReached) {\n status = \"limit_reached\";\n } else if (!fiveHour && !weekly) {\n status = \"no-data\";\n } else {\n status = \"ok\";\n }\n\n return {\n ...base,\n status,\n fiveHour,\n weekly,\n limitReached,\n ...(additionalLimits ? { additionalLimits } : {}),\n ...(credits ? { credits } : {}),\n };\n}\n\n/**\n * Whether one live /wham/usage response authoritatively contradicts an older\n * quota refusal. `ok` proves the base allowance is open; every surfaced\n * feature-specific window must also remain below exhaustion because the older\n * model refusal may have belonged to one of those limits. Missing/no-data and\n * malformed/error responses never repair cooldown state.\n */\nexport function codexUsageConfirmsQuotaAvailable(payload: CodexUsagePayload): boolean {\n if (payload.status !== \"ok\" || payload.limitReached) return false;\n return !payload.additionalLimits?.some(\n (limit) => (limit.fiveHour?.percent ?? 0) >= 100 || (limit.weekly?.percent ?? 0) >= 100,\n );\n}\n","// Exact Codex rust-v0.144.6 rate-limit-reset-credit protocol normalization.\n// Provenance: stable commit 5d1fbf26c43abc65a203928b2e31561cb039e06d;\n// protocol-bearing files are byte-identical from rust-v0.144.1 through v0.144.6.\n//\n// Upstream sources (stable tag target 5d1fbf26c43abc65a203928b2e31561cb039e06d):\n// - codex-rs/backend-client/src/types.rs\n// - codex-rs/backend-client/src/client/rate_limit_resets.rs\n// - codex-rs/app-server-protocol/src/protocol/v2/account.rs\n//\n// The backend wire is snake_case. Public OpenGeni callers only receive the\n// normalized camelCase types below. Unknown reset types/statuses remain visible\n// but fail closed as `unknown`; they are never made actionable by this parser.\n\nimport * as z from \"zod/v4\";\n\nexport const CODEX_RATE_LIMIT_RESET_OUTCOMES = [\n \"reset\",\n \"nothingToReset\",\n \"noCredit\",\n \"alreadyRedeemed\",\n] as const;\n\nexport type CodexRateLimitResetOutcome = (typeof CODEX_RATE_LIMIT_RESET_OUTCOMES)[number];\nexport type CodexRateLimitResetType = \"codexRateLimits\" | \"unknown\";\nexport type CodexRateLimitResetCreditStatus = \"available\" | \"redeeming\" | \"redeemed\" | \"unknown\";\n\nexport type CodexRateLimitResetCredit = {\n id: string;\n resetType: CodexRateLimitResetType;\n status: CodexRateLimitResetCreditStatus;\n /** Unix seconds, matching account/rateLimits/read in Codex v0.144.6. */\n grantedAt: number;\n /** Unix seconds, or null when the provider says the credit does not expire. */\n expiresAt: number | null;\n title: string | null;\n description: string | null;\n};\n\nexport type CodexRateLimitResetCreditsDetails = {\n availableCount: number;\n credits: CodexRateLimitResetCredit[];\n};\n\nexport type CodexRateLimitResetCreditsSummary = {\n availableCount: number;\n /** null means the provider supplied an authoritative count but no detail rows. */\n credits: null;\n};\n\nexport type CodexRateLimitResetConsumeResponse = {\n outcome: CodexRateLimitResetOutcome;\n};\n\nconst nonNegativeInteger = z.number().int().nonnegative();\nconst backendTimestamp = z.string().datetime({ offset: true });\n\nconst backendCreditSchema = z\n .object({\n id: z.string().min(1),\n reset_type: z.string().min(1),\n status: z.string().min(1),\n granted_at: backendTimestamp,\n expires_at: backendTimestamp.nullish(),\n title: z.string().nullish(),\n description: z.string().nullish(),\n })\n .passthrough();\n\nconst backendDetailsSchema = z\n .object({\n credits: z.array(backendCreditSchema),\n available_count: nonNegativeInteger,\n })\n .passthrough();\n\nconst backendUsageSummarySchema = z\n .object({\n rate_limit_reset_credits: z\n .object({ available_count: nonNegativeInteger })\n .passthrough()\n .nullish(),\n })\n .passthrough();\n\nconst backendConsumeOutcomes = [\n \"reset\",\n \"nothing_to_reset\",\n \"no_credit\",\n \"already_redeemed\",\n] as const;\n\nconst backendConsumeSchema = z\n .object({\n code: z.enum(backendConsumeOutcomes),\n // The app-server intentionally discards this field. OpenGeni also refetches\n // rather than inferring post-redemption state from it.\n windows_reset: nonNegativeInteger.default(0),\n })\n .passthrough();\n\nfunction normalizedResetType(value: string): CodexRateLimitResetType {\n return value === \"codex_rate_limits\" ? \"codexRateLimits\" : \"unknown\";\n}\n\nfunction normalizedCreditStatus(value: string): CodexRateLimitResetCreditStatus {\n if (value === \"available\" || value === \"redeeming\" || value === \"redeemed\") {\n return value;\n }\n return \"unknown\";\n}\n\n/** Parse the exact detailed-credit backend response. Unknown rows stay view-only. */\nexport function parseCodexRateLimitResetCreditsDetails(\n payload: unknown,\n): CodexRateLimitResetCreditsDetails | null {\n const parsed = backendDetailsSchema.safeParse(payload);\n if (!parsed.success) return null;\n return {\n availableCount: parsed.data.available_count,\n credits: parsed.data.credits.map((credit) => ({\n id: credit.id,\n resetType: normalizedResetType(credit.reset_type),\n status: normalizedCreditStatus(credit.status),\n grantedAt: Math.floor(Date.parse(credit.granted_at) / 1000),\n expiresAt:\n credit.expires_at == null ? null : Math.floor(Date.parse(credit.expires_at) / 1000),\n title: credit.title ?? null,\n description: credit.description ?? null,\n })),\n };\n}\n\n/** Parse the count-only summary carried by GET /wham/usage. */\nexport function parseCodexRateLimitResetCreditsSummary(\n payload: unknown,\n): CodexRateLimitResetCreditsSummary | null {\n const parsed = backendUsageSummarySchema.safeParse(payload);\n const availableCount = parsed.success\n ? parsed.data.rate_limit_reset_credits?.available_count\n : undefined;\n return availableCount === undefined ? null : { availableCount, credits: null };\n}\n\n/** Parse one of the exact four v0.144.6 consume outcomes. Unknowns fail closed. */\nexport function parseCodexRateLimitResetConsumeResponse(\n payload: unknown,\n): CodexRateLimitResetConsumeResponse | null {\n const parsed = backendConsumeSchema.safeParse(payload);\n if (!parsed.success) return null;\n const outcomes: Record<(typeof backendConsumeOutcomes)[number], CodexRateLimitResetOutcome> = {\n reset: \"reset\",\n nothing_to_reset: \"nothingToReset\",\n no_credit: \"noCredit\",\n already_redeemed: \"alreadyRedeemed\",\n };\n return { outcome: outcomes[parsed.data.code] };\n}\n","// Thin ChatGPT/Codex API client used outside the streamed turn: the login-check\n// (GET /codex/models) and the usage/limits readback (GET /wham/usage). spec §1.4, §1.8, §F.\n\nimport { CODEX_ORIGINATOR, CODEX_RESPONSES_BASE, CODEX_WHAM_BASE } from \"./constants\";\nimport type { CodexFetch } from \"./device-code\";\nimport {\n parseCodexRateLimitResetConsumeResponse,\n parseCodexRateLimitResetCreditsDetails,\n type CodexRateLimitResetConsumeResponse,\n type CodexRateLimitResetCreditsDetails,\n} from \"./reset-credits\";\nimport { runBoundedCodexOperation } from \"./bounded-operation\";\n\nexport type CodexAuthHeaders = {\n accessToken: string;\n chatgptAccountId: string | null;\n isFedramp: boolean;\n clientVersion: string;\n};\n\nconst CODEX_READ_TIMEOUT_MS = 5_000;\nconst RESET_CREDIT_DETAILS_TIMEOUT_MS = 5_000;\nconst RESET_CREDIT_CONSUME_TIMEOUT_MS = 10_000;\n\nexport type ResetCreditFetchFailureReason =\n | \"http_error\"\n | \"invalid_response\"\n | \"network_error\"\n | \"timeout\";\n\n/** Server-only headers shared by every ChatGPT/Codex subscription transport. */\nexport function codexSubscriptionHeaders(a: CodexAuthHeaders): Record<string, string> {\n return {\n Authorization: `Bearer ${a.accessToken}`,\n ...(a.chatgptAccountId ? { \"ChatGPT-Account-ID\": a.chatgptAccountId } : {}),\n originator: CODEX_ORIGINATOR,\n \"User-Agent\": `${CODEX_ORIGINATOR}/${a.clientVersion}`,\n version: a.clientVersion,\n ...(a.isFedramp ? { \"X-OpenAI-Fedramp\": \"true\" } : {}),\n };\n}\n\n/** GET /codex/models — login-check + live catalog. A 200 means the token is accepted. spec §1.4/§F */\nexport async function fetchCodexModels(\n a: CodexAuthHeaders,\n fetchImpl: CodexFetch = fetch,\n timeoutMs = CODEX_READ_TIMEOUT_MS,\n): Promise<{ ok: boolean; status: number; slugs: string[] }> {\n const fetched = await runBoundedCodexOperation(async (signal) => {\n const res = await fetchImpl(\n `${CODEX_RESPONSES_BASE}/models?client_version=${encodeURIComponent(a.clientVersion)}`,\n { method: \"GET\", headers: codexSubscriptionHeaders(a), signal },\n );\n if (!res.ok) {\n await res.arrayBuffer().catch(() => undefined);\n return { ok: false, status: res.status, slugs: [] as string[] };\n }\n const body = (await res.json()) as { models?: Array<{ slug?: string }> };\n const slugs = (body.models ?? [])\n .map((model) => model.slug)\n .filter((slug): slug is string => typeof slug === \"string\");\n return { ok: true, status: res.status, slugs };\n }, timeoutMs);\n return fetched.ok ? fetched.value : { ok: false, status: 0, slugs: [] };\n}\n\n/** GET /wham/usage — authoritative limits. NB the WHAM base is /backend-api, NOT /codex (spec §1.8a). */\nexport async function fetchCodexUsage(\n a: CodexAuthHeaders,\n fetchImpl: CodexFetch = fetch,\n timeoutMs = CODEX_READ_TIMEOUT_MS,\n): Promise<{ status: number; payload: unknown }> {\n const fetched = await runBoundedCodexOperation(async (signal) => {\n const res = await fetchImpl(`${CODEX_WHAM_BASE}/wham/usage`, {\n method: \"GET\",\n headers: codexSubscriptionHeaders(a),\n signal,\n });\n // A 404 may carry a usage-limit body; the route layer normalizes it to a limits state (spec §1.8c).\n const payload = res.ok || res.status === 404 ? await res.json().catch(() => null) : null;\n if (!res.ok && res.status !== 404) await res.arrayBuffer().catch(() => undefined);\n return { status: res.status, payload };\n }, timeoutMs);\n if (!fetched.ok) throw new Error(`Codex usage request ${fetched.reason}`);\n return fetched.value;\n}\n\n/**\n * GET /wham/rate-limit-reset-credits — detailed earned reset credits.\n *\n * A non-2xx or malformed body returns an explicit non-ok result. The caller may\n * fall back to the count-only summary embedded in /wham/usage, but must never\n * invent actionable rows from that count.\n */\nexport async function fetchCodexRateLimitResetCredits(\n a: CodexAuthHeaders,\n fetchImpl: CodexFetch = fetch,\n timeoutMs = RESET_CREDIT_DETAILS_TIMEOUT_MS,\n): Promise<\n | { ok: true; status: number; details: CodexRateLimitResetCreditsDetails }\n | { ok: false; status: number; reason: ResetCreditFetchFailureReason }\n> {\n const fetched = await runBoundedCodexOperation(async (signal) => {\n const res = await fetchImpl(`${CODEX_WHAM_BASE}/wham/rate-limit-reset-credits`, {\n method: \"GET\",\n headers: codexSubscriptionHeaders(a),\n signal,\n });\n if (!res.ok) {\n // Drain the body without retaining/logging it. Provider error bodies may\n // contain account-specific details and are not part of this contract.\n await res.arrayBuffer().catch(() => undefined);\n return {\n ok: false as const,\n status: res.status,\n reason: \"http_error\" as const,\n };\n }\n const details = parseCodexRateLimitResetCreditsDetails(await res.json().catch(() => null));\n return details\n ? { ok: true as const, status: res.status, details }\n : {\n ok: false as const,\n status: res.status,\n reason: \"invalid_response\" as const,\n };\n }, timeoutMs);\n return fetched.ok ? fetched.value : { ok: false, status: 0, reason: fetched.reason };\n}\n\n/**\n * POST /wham/rate-limit-reset-credits/consume with the exact v0.144.6 body.\n * `idempotencyKey` identifies one logical human redemption and MUST be reused\n * by the server on retries. Supplying `creditId` is preferred; omission leaves\n * provider selection in control and is therefore not used by OpenGeni's\n * human-only flow.\n */\nexport async function consumeCodexRateLimitResetCredit(\n a: CodexAuthHeaders,\n input: { idempotencyKey: string; creditId?: string | undefined },\n fetchImpl: CodexFetch = fetch,\n timeoutMs = RESET_CREDIT_CONSUME_TIMEOUT_MS,\n): Promise<\n | { ok: true; status: number; result: CodexRateLimitResetConsumeResponse }\n | {\n ok: false;\n status: number;\n reason: ResetCreditFetchFailureReason | \"invalid_request\";\n }\n> {\n if (input.idempotencyKey.length === 0 || input.creditId === \"\") {\n return { ok: false, status: 0, reason: \"invalid_request\" };\n }\n const fetched = await runBoundedCodexOperation(async (signal) => {\n const res = await fetchImpl(`${CODEX_WHAM_BASE}/wham/rate-limit-reset-credits/consume`, {\n method: \"POST\",\n headers: {\n ...codexSubscriptionHeaders(a),\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n redeem_request_id: input.idempotencyKey,\n ...(input.creditId ? { credit_id: input.creditId } : {}),\n }),\n signal,\n });\n if (!res.ok) {\n await res.arrayBuffer().catch(() => undefined);\n return {\n ok: false as const,\n status: res.status,\n reason: \"http_error\" as const,\n };\n }\n const result = parseCodexRateLimitResetConsumeResponse(await res.json().catch(() => null));\n return result\n ? { ok: true as const, status: res.status, result }\n : {\n ok: false as const,\n status: res.status,\n reason: \"invalid_response\" as const,\n };\n }, timeoutMs);\n return fetched.ok ? fetched.value : { ok: false, status: 0, reason: fetched.reason };\n}\n","// Per-request Codex context, carried via AsyncLocalStorage.\n//\n// The runtime caches one OpenAI client per provider id (process-wide), so the\n// per-workspace token must NOT be baked into the client. Instead the worker sets\n// this context around the model run, and codexSubscriptionFetch reads it at call\n// time — one cached client, correct per-workspace token, no cross-tenant leak.\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport type CodexTokenSnapshot = {\n accessToken: string;\n chatgptAccountId: string | null;\n isFedramp: boolean;\n};\n\n/**\n * Multi-account P4 (Part A): a full usage snapshot scraped FOR FREE from the\n * `x-codex-primary-*` / `x-codex-secondary-*` response headers the codex backend\n * stamps on every `/codex/responses` turn (success AND 429 hard-cap). Integer-\n * identical to GET /wham/usage but with zero extra round-trip. parseCodexUsageHeaders\n * returns this only when BOTH windows parse, so a write is always a full 5-column\n * snapshot (no partial-window clobber). Shape mirrors db's CodexAccountUsageSnapshot\n * (non-null here: a partial read is filtered to null upstream, never half-written).\n */\nexport type CodexUsageHeaderSnapshot = {\n primaryUsedPercent: number;\n primaryResetAt: Date;\n secondaryUsedPercent: number;\n secondaryResetAt: Date;\n checkedAt: Date;\n};\n\nexport type CodexResponseTimeoutClass = \"connect\" | \"headers\" | \"idle_stream\" | \"whole_request\";\n\nexport type CodexResponseTimeoutPolicy = {\n /** Maximum wait for response headers, including DNS/TCP/TLS establishment. */\n headersTimeoutMs: number;\n /** Maximum silence between response-body chunks after headers arrive. */\n streamIdleTimeoutMs: number;\n /** Maximum wall time for one logical Responses request. */\n wholeRequestTimeoutMs: number;\n /**\n * Reserved compatibility field. It is currently normalized to zero because\n * an absent response does not prove that the provider never accepted a\n * request, so automatic replay is not safe without an operation receipt.\n */\n noByteRetries: number;\n retryBackoffMs: number;\n};\n\nexport type CodexModelRequestEvent = {\n requestId: string;\n transportAttempt: number;\n phase: \"started\" | \"headers\" | \"first_byte\" | \"completed\" | \"failed\" | \"timed_out\";\n model?: string;\n durationMs: number;\n responseObserved: boolean;\n timeoutPolicy: CodexResponseTimeoutPolicy;\n timeoutClass?: CodexResponseTimeoutClass;\n providerRequestId?: string;\n status?: number;\n willRetry?: boolean;\n};\n\nexport type CodexRequestOpaqueArtifacts = {\n requestId: string;\n fingerprints: readonly string[];\n};\n\n/**\n * Durable execution fence invoked immediately before a provider request is\n * dispatched. Errors are intentionally not classified here: the owning worker\n * must receive typed lease-loss failures unchanged.\n */\nexport type CodexBeforeProviderDispatch = () => Promise<void> | void;\n\nexport type CodexRequestPreparationPhase =\n | \"transport_entry\"\n | \"credential_ready\"\n | \"wire_request_ready\";\n\nexport type CodexRequestContext = {\n clientVersion: string;\n /**\n * Stable per-session affinity id, sent as the `session_id` header on every\n * request. This is the backend's STICKY CACHE-ROUTING key — measured\n * 2026-07-12 with byte-identical ~99k-token gpt-5.6-sol requests on one idle\n * account: without the header, repeat requests hit the prompt cache ~50% of\n * the time (a per-request routing lottery across cache shards; matches the\n * prod fleet's 48.6%); with a stable session_id, 10/10 requests hit at the\n * 99.0% ceiling — Codex CLI parity (the CLI always sends it; its own last-3d\n * token-weighted rate here is 94%). `prompt_cache_key` in the body only\n * influences routing and does NOT pin it. Use the SAME value as\n * prompt_cache_key (the OpenGeni sessionId) so routing and cache key agree.\n */\n sessionId?: string;\n /** Worker-supplied: proactive refresh + single-flight + db persist. */\n getToken: () => Promise<CodexTokenSnapshot>;\n /** Forced refresh used for the 401 retry. */\n refresh: () => Promise<CodexTokenSnapshot>;\n /** Model-slug resolver (longest-prefix against the live catalog). */\n resolveModel: (slug: string) => string;\n /**\n * Multi-account P4 (Part A): fire-and-forget usage-header sink. Called by\n * codexSubscriptionFetch on EVERY response (sync, non-throwing, never awaited)\n * with the parsed full-window snapshot. The worker records the latest into the\n * P2 usage cache once per turn in its `finally` — packages/codex stays db-free.\n */\n onUsageHeaders?: (snapshot: CodexUsageHeaderSnapshot) => void;\n /** Optional per-run override, primarily for deterministic transport tests. */\n responseTimeoutPolicy?: Partial<CodexResponseTimeoutPolicy>;\n /**\n * Synchronous, best-effort diagnostics for the request lifecycle. This hook\n * runs before the durable audit sink and MUST remain non-blocking: a throw is\n * swallowed by the transport and it must never receive request bodies/auth.\n */\n onModelRequestDiagnostic?: (event: CodexModelRequestEvent) => void;\n /** Bounded synchronous checkpoints for pre-network request preparation. */\n onRequestPreparationDiagnostic?: (phase: CodexRequestPreparationPhase) => void;\n /** Worker-owned durable audit sink; payloads never contain request bodies or auth. */\n onModelRequestEvent?: (event: CodexModelRequestEvent) => Promise<void> | void;\n /** Exact opaque artifacts on the normalized wire request, never their ciphertext. */\n onRequestOpaqueArtifacts?: (artifacts: CodexRequestOpaqueArtifacts) => void;\n /**\n * Durable execution fence. Runs after request preparation and audit, and\n * immediately before each actual provider dispatch, including auth retries.\n */\n beforeProviderDispatch?: CodexBeforeProviderDispatch;\n /** Stable request identity supplied by the owning durable execution. */\n nextRequestId?: () => string;\n /**\n * Optional Codex beta feature flags advertised as `x-codex-beta-features`\n * (comma-separated). Used for remote compaction v2 (`remote_compaction_v2`).\n */\n betaFeatures?: readonly string[];\n /**\n * Optional turn analytics / routing metadata sent as `x-codex-turn-metadata`\n * (JSON). Body `metadata` is stripped by normalize — never put request_kind there.\n */\n turnMetadata?: Record<string, unknown>;\n};\n\nexport const codexRequestStorage = new AsyncLocalStorage<CodexRequestContext>();\n\n/** Nest a Codex ALS scope with header overrides (e.g. remote compaction v2). */\nexport function withCodexRequestOverrides<T>(\n overrides: Pick<CodexRequestContext, \"betaFeatures\" | \"turnMetadata\">,\n fn: () => T,\n): T {\n const current = codexRequestStorage.getStore();\n if (!current) return fn();\n return codexRequestStorage.run({ ...current, ...overrides }, fn);\n}\n","import {\n CODEX_RESPONSE_HEADERS_TIMEOUT_MS,\n CODEX_RESPONSE_NO_BYTE_RETRIES,\n CODEX_RESPONSE_RETRY_BACKOFF_MS,\n CODEX_RESPONSE_STREAM_IDLE_TIMEOUT_MS,\n CODEX_RESPONSE_WHOLE_TIMEOUT_MS,\n} from \"./constants\";\nimport type { CodexResponseTimeoutClass, CodexResponseTimeoutPolicy } from \"./request-context\";\n\nexport const CODEX_RESPONSE_TIMEOUT_ERROR_TYPE = \"opengeni_codex_response_timeout\";\n\nexport const DEFAULT_CODEX_RESPONSE_TIMEOUT_POLICY: CodexResponseTimeoutPolicy = Object.freeze({\n headersTimeoutMs: CODEX_RESPONSE_HEADERS_TIMEOUT_MS,\n streamIdleTimeoutMs: CODEX_RESPONSE_STREAM_IDLE_TIMEOUT_MS,\n wholeRequestTimeoutMs: CODEX_RESPONSE_WHOLE_TIMEOUT_MS,\n noByteRetries: CODEX_RESPONSE_NO_BYTE_RETRIES,\n retryBackoffMs: CODEX_RESPONSE_RETRY_BACKOFF_MS,\n});\n\nfunction positiveFinite(value: number | undefined, fallback: number): number {\n return value !== undefined && Number.isFinite(value) && value > 0 ? value : fallback;\n}\n\nexport function resolveCodexResponseTimeoutPolicy(\n override: Partial<CodexResponseTimeoutPolicy> | undefined,\n): CodexResponseTimeoutPolicy {\n return {\n headersTimeoutMs: positiveFinite(\n override?.headersTimeoutMs,\n DEFAULT_CODEX_RESPONSE_TIMEOUT_POLICY.headersTimeoutMs,\n ),\n streamIdleTimeoutMs: positiveFinite(\n override?.streamIdleTimeoutMs,\n DEFAULT_CODEX_RESPONSE_TIMEOUT_POLICY.streamIdleTimeoutMs,\n ),\n wholeRequestTimeoutMs: positiveFinite(\n override?.wholeRequestTimeoutMs,\n DEFAULT_CODEX_RESPONSE_TIMEOUT_POLICY.wholeRequestTimeoutMs,\n ),\n // Automatic replay is fail-closed until the provider operation can be\n // durably read/reconciled. Keep the field for policy/event compatibility,\n // but never let a caller opt back into an unproved retry.\n noByteRetries: 0,\n retryBackoffMs:\n override?.retryBackoffMs !== undefined &&\n Number.isFinite(override.retryBackoffMs) &&\n override.retryBackoffMs >= 0\n ? override.retryBackoffMs\n : DEFAULT_CODEX_RESPONSE_TIMEOUT_POLICY.retryBackoffMs,\n };\n}\n\nexport class CodexResponseTimeoutError extends Error {\n readonly code = CODEX_RESPONSE_TIMEOUT_ERROR_TYPE;\n readonly type = CODEX_RESPONSE_TIMEOUT_ERROR_TYPE;\n\n constructor(\n readonly timeoutClass: CodexResponseTimeoutClass,\n readonly requestId: string,\n readonly responseObserved: boolean,\n message = `Codex response ${timeoutClass.replaceAll(\"_\", \" \")} timed out`,\n ) {\n super(message);\n this.name = \"CodexResponseTimeoutError\";\n }\n}\n\nexport type CodexResponseTimeoutInfo = {\n timeoutClass: CodexResponseTimeoutClass;\n requestId: string | null;\n responseObserved: boolean;\n message: string;\n};\n\nfunction parseTimeoutClass(value: unknown): CodexResponseTimeoutClass | null {\n return value === \"connect\" ||\n value === \"headers\" ||\n value === \"idle_stream\" ||\n value === \"whole_request\"\n ? value\n : null;\n}\n\n/**\n * Recover structured transport timeouts through SDK wrapping. The optional\n * legacy match is deliberately opt-in: `Request timed out.` alone has no\n * provider provenance and the worker enables it only for a confirmed Codex\n * subscription turn.\n */\nexport function classifyCodexResponseTimeoutError(\n error: unknown,\n options: { allowLegacyRequestTimeout?: boolean } = {},\n): CodexResponseTimeoutInfo | null {\n let current: unknown = error;\n for (let depth = 0; depth < 8 && current && typeof current === \"object\"; depth += 1) {\n const value = current as Record<string, unknown>;\n const nested =\n value.error && typeof value.error === \"object\"\n ? (value.error as Record<string, unknown>)\n : undefined;\n const type =\n (typeof value.type === \"string\" ? value.type : undefined) ??\n (typeof value.code === \"string\" ? value.code : undefined) ??\n (typeof nested?.type === \"string\" ? nested.type : undefined) ??\n (typeof nested?.code === \"string\" ? nested.code : undefined);\n if (type === CODEX_RESPONSE_TIMEOUT_ERROR_TYPE || value.name === \"CodexResponseTimeoutError\") {\n const klass =\n parseTimeoutClass(value.timeoutClass) ??\n parseTimeoutClass(nested?.timeout_class) ??\n \"headers\";\n return {\n timeoutClass: klass,\n requestId:\n (typeof value.requestId === \"string\" ? value.requestId : undefined) ??\n (typeof nested?.request_id === \"string\" ? nested.request_id : null),\n responseObserved:\n typeof value.responseObserved === \"boolean\"\n ? value.responseObserved\n : nested?.response_observed === true,\n message:\n (typeof value.message === \"string\" ? value.message : undefined) ??\n (typeof nested?.message === \"string\" ? nested.message : \"Codex response timed out\"),\n };\n }\n current = value.cause;\n }\n\n if (options.allowLegacyRequestTimeout && error && typeof error === \"object\") {\n const value = error as Record<string, unknown>;\n if (\n value.name === \"APIConnectionTimeoutError\" ||\n (value.message === \"Request timed out.\" && value.name === \"Error\")\n ) {\n return {\n timeoutClass: \"headers\",\n requestId: null,\n responseObserved: false,\n message: String(value.message ?? \"Request timed out.\"),\n };\n }\n }\n return null;\n}\n\nexport function isPreHeadersTimeoutError(error: unknown): CodexResponseTimeoutClass | null {\n const structured = classifyCodexResponseTimeoutError(error);\n if (structured && !structured.responseObserved) {\n return structured.timeoutClass;\n }\n if (!error || typeof error !== \"object\") return null;\n const value = error as Record<string, unknown>;\n const code = typeof value.code === \"string\" ? value.code : \"\";\n const name = typeof value.name === \"string\" ? value.name : \"\";\n const message = typeof value.message === \"string\" ? value.message : String(error);\n if (/^(?:ETIMEDOUT|UND_ERR_CONNECT_TIMEOUT)$/i.test(code) || /ConnectTimeout/i.test(name)) {\n return \"connect\";\n }\n return /connect(?:ion)?[^.]*timed?\\s*out/i.test(`${name} ${message}`) ? \"connect\" : null;\n}\n","// codexSubscriptionFetch — the transport installed on the OpenAI client for the\n// \"codex-subscription\" provider. Mirrors the runtime's computerCallNormalizingFetch\n// pattern: wraps a base fetch and returns a (input, init) => Promise<Response>.\n//\n// It reads the per-request Codex context from AsyncLocalStorage at CALL time, so a\n// single process-cached client serves every workspace with the correct token. It:\n// - rewrites /responses -> /codex/responses\n// - injects the subscription auth headers (omits OpenAI-Beta on SSE; spec §1.2)\n// - normalizes the request body (spec §0 verdict)\n// - retries once on 401 after a forced token refresh (spec §1.9)\n// Stream parsing is delegated to the SDK (SSE passthrough; spec §0(d)).\n\nimport { randomUUID } from \"node:crypto\";\nimport { CODEX_ORIGINATOR } from \"./constants\";\nimport { normalizeCodexRequestBody } from \"./normalize\";\nimport { opaqueProviderArtifactFingerprints } from \"./opaque-artifact\";\nimport {\n codexRequestStorage,\n type CodexModelRequestEvent,\n type CodexRequestPreparationPhase,\n type CodexRequestContext,\n type CodexResponseTimeoutPolicy,\n type CodexTokenSnapshot,\n type CodexUsageHeaderSnapshot,\n} from \"./request-context\";\n\nfunction emitRequestPreparationDiagnostic(\n ctx: CodexRequestContext,\n phase: CodexRequestPreparationPhase,\n): void {\n try {\n ctx.onRequestPreparationDiagnostic?.(phase);\n } catch {\n // Diagnostic observers are non-blocking and cannot affect transport.\n }\n}\nimport {\n CODEX_RESPONSE_TIMEOUT_ERROR_TYPE,\n CodexResponseTimeoutError,\n classifyCodexResponseTimeoutError,\n isPreHeadersTimeoutError,\n resolveCodexResponseTimeoutPolicy,\n} from \"./response-timeout\";\n\nexport type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n\n/**\n * Internal provenance marker copied onto buffered non-OK Codex responses.\n * OpenAI's APIError preserves response headers, which lets the worker\n * distinguish a model-provider refusal from an unrelated sandbox/MCP HTTP\n * error that happened during the same Codex turn.\n */\nexport const CODEX_TRANSPORT_ERROR_HEADER = \"x-opengeni-codex-transport-error\";\n/** Internal transport handoff; always removed before network I/O. */\nexport const CODEX_REQUEST_BODY_NORMALIZED_HEADER = \"x-opengeni-request-body-normalized\";\nconst REPLAYABLE_REQUEST_BODY_FACTORY = Symbol.for(\"opengeni.replayable-request-body-factory\");\n\ntype ReplayableRequestInit = RequestInit & {\n [REPLAYABLE_REQUEST_BODY_FACTORY]?: () => ReadableStream<Uint8Array>;\n};\n/** Internal resolved-model handoff; always removed before network I/O. */\nexport const CODEX_REQUEST_MODEL_HEADER = \"x-opengeni-request-model\";\n/** Internal durable request-identity handoff; always removed before network I/O. */\nexport const CODEX_REQUEST_ID_HEADER = \"x-opengeni-request-id\";\n/** Internal original response-mode handoff; always removed before network I/O. */\nexport const CODEX_REQUEST_CALLER_STREAM_HEADER = \"x-opengeni-request-caller-stream\";\nconst MAX_CODEX_ERROR_BODY_BYTES = 64 * 1024;\n\nfunction headersCarryCodexTransportMarker(headers: unknown): boolean {\n if (!headers || typeof headers !== \"object\") return false;\n const getter = (headers as { get?: unknown }).get;\n if (typeof getter === \"function\") {\n return getter.call(headers, CODEX_TRANSPORT_ERROR_HEADER) === \"1\";\n }\n const record = headers as Record<string, unknown>;\n return (\n record[CODEX_TRANSPORT_ERROR_HEADER] === \"1\" ||\n record[CODEX_TRANSPORT_ERROR_HEADER.toLowerCase()] === \"1\"\n );\n}\n\n/** True only for an error produced from this Codex transport's non-OK response. */\nexport function isCodexTransportError(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; depth < 6 && current && typeof current === \"object\"; depth += 1) {\n const value = current as Record<string, unknown>;\n if (headersCarryCodexTransportMarker(value.headers)) return true;\n current = value.cause;\n }\n return false;\n}\n\nexport type CodexEncryptedArtifactRejection = {\n status: 400;\n kind: \"encrypted_content_rejected\";\n};\n\n/**\n * Classify only the provider's definitive request rejection for an opaque\n * reasoning artifact that it can no longer decrypt/parse. A Codex transport\n * marker plus HTTP 400 proves this request was rejected before inference; the\n * semantic match prevents unrelated malformed prompts from entering recovery.\n */\nexport function classifyCodexEncryptedArtifactRejection(\n error: unknown,\n): CodexEncryptedArtifactRejection | null {\n if (!isCodexTransportError(error)) return null;\n let current: unknown = error;\n for (let depth = 0; depth < 6 && current && typeof current === \"object\"; depth += 1) {\n const value = current as Record<string, unknown>;\n const body =\n value.error && typeof value.error === \"object\"\n ? (value.error as Record<string, unknown>)\n : null;\n const status = Number(value.status ?? body?.status);\n const message = [\n typeof value.message === \"string\" ? value.message : \"\",\n typeof body?.message === \"string\" ? body.message : \"\",\n typeof value.code === \"string\" ? value.code : \"\",\n typeof body?.code === \"string\" ? body.code : \"\",\n typeof value.type === \"string\" ? value.type : \"\",\n typeof body?.type === \"string\" ? body.type : \"\",\n ]\n .join(\" \")\n .toLowerCase();\n const unsupportedFieldShape =\n /(?:invalid value|supported values?|unsupported|unknown (?:field|parameter|value))/.test(\n message,\n );\n if (\n status === 400 &&\n !unsupportedFieldShape &&\n /(?:encrypted[_ ]content|encrypted reasoning|reasoning artifact)/.test(message) &&\n /(?:decrypt(?:ed|ion)?|could not be parsed|cannot be parsed|failed to parse)/.test(message)\n ) {\n return { status: 400, kind: \"encrypted_content_rejected\" };\n }\n current = value.cause;\n }\n return null;\n}\n\n/** Parse an integer header value; null when absent or not a finite integer. */\nfunction parseIntHeader(value: string | null): number | null {\n if (value === null) {\n return null;\n }\n const n = Number.parseInt(value.trim(), 10);\n return Number.isFinite(n) ? n : null;\n}\n\n/**\n * Resolve a window reset instant from the response headers: prefer the absolute\n * `*-reset-at` (epoch SECONDS → ms, mirroring codex-token-resolver's usage parse),\n * else the relative `*-reset-after-seconds` from now, else now (a missing reset\n * reads as \"already cleared\" — availableAt treats an elapsed reset as a bounded\n * default cooldown, so the ranker never strands on it).\n */\nfunction resolveResetAt(headers: Headers, atKey: string, afterKey: string, nowMs: number): Date {\n const at = parseIntHeader(headers.get(atKey));\n if (at !== null) {\n return new Date(at * 1000);\n }\n const after = parseIntHeader(headers.get(afterKey));\n if (after !== null) {\n return new Date(nowMs + after * 1000);\n }\n return new Date(nowMs);\n}\n\n/**\n * Multi-account P4 (Part A): scrape the full usage snapshot the codex backend\n * stamps on every `/codex/responses` response in `x-codex-primary-*` /\n * `x-codex-secondary-*` headers (integer-identical to GET /wham/usage, for free).\n *\n * CRITICAL clobber-fix: return null unless BOTH windows expose a valid used-percent\n * integer. recordCodexAccountUsage writes all five columns unconditionally, so a\n * primary-only snapshot would null the weekly column. Both windows are always\n * emitted together on `/codex/responses`; gating on both makes every write a full\n * 5-column snapshot byte-identical to the poll path, and a malformed/absent header\n * set simply no-ops (the /wham/usage poll fallback still covers it).\n */\nexport function parseCodexUsageHeaders(headers: Headers): CodexUsageHeaderSnapshot | null {\n const primaryUsedPercent = parseIntHeader(headers.get(\"x-codex-primary-used-percent\"));\n const secondaryUsedPercent = parseIntHeader(headers.get(\"x-codex-secondary-used-percent\"));\n if (primaryUsedPercent === null || secondaryUsedPercent === null) {\n return null; // not a full both-windows snapshot — no-op (never a partial clobber)\n }\n const nowMs = Date.now();\n return {\n primaryUsedPercent,\n primaryResetAt: resolveResetAt(\n headers,\n \"x-codex-primary-reset-at\",\n \"x-codex-primary-reset-after-seconds\",\n nowMs,\n ),\n secondaryUsedPercent,\n secondaryResetAt: resolveResetAt(\n headers,\n \"x-codex-secondary-reset-at\",\n \"x-codex-secondary-reset-after-seconds\",\n nowMs,\n ),\n checkedAt: new Date(nowMs),\n };\n}\n\ntype RequestAudit = {\n ctx: CodexRequestContext;\n requestId: string;\n transportAttempt: number;\n model?: string;\n logicalStartedAt: number;\n attemptStartedAtMonotonic: number;\n policy: CodexResponseTimeoutPolicy;\n terminalOutcome: RequestTerminalOutcome | null;\n};\n\ntype RequestTerminalOutcome = \"completed\" | \"failed\" | \"timed_out\";\n\ntype SemanticTerminalState = {\n phase: \"completed\" | \"failed\" | null;\n /** Non-streaming callers must parse the complete SSE body before settling. */\n deferTransportTerminal: boolean;\n};\n\ntype CodexSseEvent = {\n type?: string;\n response?: Record<string, unknown>;\n error?: unknown;\n code?: unknown;\n message?: unknown;\n param?: unknown;\n item?: unknown;\n};\n\ntype CodexSseTerminalClassification =\n | { phase: \"completed\" }\n | {\n phase: \"failed\";\n rawError: unknown;\n fallbackCode: string;\n fallbackMessage: string;\n }\n | null;\n\nfunction classifyCodexSseTerminal(ev: CodexSseEvent): CodexSseTerminalClassification {\n if (ev.type === \"response.failed\") {\n return {\n phase: \"failed\",\n rawError: ev.response?.error,\n fallbackCode: \"response_failed\",\n fallbackMessage: \"The Codex response failed\",\n };\n }\n if (ev.type === \"error\" || ev.type === \"response.error\") {\n return {\n phase: \"failed\",\n rawError: ev.error ?? ev.response?.error ?? ev,\n fallbackCode: \"response_error\",\n fallbackMessage: \"The Codex response stream reported an error\",\n };\n }\n if (ev.type === \"response.incomplete\") {\n const details = ev.response?.incomplete_details;\n const reason =\n details && typeof details === \"object\"\n ? (details as Record<string, unknown>).reason\n : undefined;\n return {\n phase: \"failed\",\n rawError: {\n code: \"response_incomplete\",\n message:\n typeof reason === \"string\" && reason.length > 0\n ? `The Codex response was incomplete (${reason})`\n : \"The Codex response was incomplete\",\n },\n fallbackCode: \"response_incomplete\",\n fallbackMessage: \"The Codex response was incomplete\",\n };\n }\n if (ev.type !== \"response.completed\" && ev.type !== \"response.done\") {\n return null;\n }\n if (!ev.response) {\n return null;\n }\n\n const responseStatus = ev.response.status;\n if (\n (responseStatus !== undefined && responseStatus !== \"completed\") ||\n (ev.response.error !== null && ev.response.error !== undefined)\n ) {\n const incomplete = responseStatus === \"incomplete\";\n return {\n phase: \"failed\",\n rawError: ev.response.error,\n fallbackCode: incomplete ? \"response_incomplete\" : \"response_failed\",\n fallbackMessage: incomplete\n ? \"The Codex response was incomplete\"\n : \"The Codex response failed\",\n };\n }\n return { phase: \"completed\" };\n}\n\nfunction markSemanticTerminal(state: SemanticTerminalState, phase: \"completed\" | \"failed\"): void {\n if (state.phase === null) {\n state.phase = phase;\n }\n}\n\nfunction terminalOutcomeForPhase(\n phase: CodexModelRequestEvent[\"phase\"],\n): RequestTerminalOutcome | null {\n if (phase === \"completed\" || phase === \"failed\" || phase === \"timed_out\") {\n return phase;\n }\n return null;\n}\n\nfunction requestEventFor(\n audit: RequestAudit,\n event: Omit<\n CodexModelRequestEvent,\n \"requestId\" | \"transportAttempt\" | \"model\" | \"durationMs\" | \"timeoutPolicy\"\n >,\n): CodexModelRequestEvent {\n return {\n requestId: audit.requestId,\n transportAttempt: audit.transportAttempt,\n ...(audit.model ? { model: audit.model } : {}),\n durationMs: Math.max(0, performance.now() - audit.attemptStartedAtMonotonic),\n timeoutPolicy: audit.policy,\n ...event,\n };\n}\n\nasync function emitRequestEvent(\n audit: RequestAudit,\n event: Omit<\n CodexModelRequestEvent,\n \"requestId\" | \"transportAttempt\" | \"model\" | \"durationMs\" | \"timeoutPolicy\"\n >,\n): Promise<boolean> {\n const terminalOutcome = terminalOutcomeForPhase(event.phase);\n if (terminalOutcome !== null) {\n if (audit.terminalOutcome !== null) {\n return false;\n }\n // Fence before invoking either observer. The durable observer may reject,\n // but a later transport callback must never turn that one terminal into a\n // contradictory second terminal.\n audit.terminalOutcome = terminalOutcome;\n }\n const observed = requestEventFor(audit, event);\n try {\n audit.ctx.onModelRequestDiagnostic?.(observed);\n } catch {\n // Diagnostic observers are strictly non-blocking and cannot affect transport.\n }\n await audit.ctx.onModelRequestEvent?.(observed);\n return true;\n}\n\nfunction providerRequestId(headers: Headers): string | undefined {\n return headers.get(\"x-request-id\") ?? headers.get(\"request-id\") ?? undefined;\n}\n\nasync function fetchBeforeHeaders(\n base: FetchLike,\n input: string,\n init: RequestInit,\n audit: RequestAudit,\n): Promise<Response> {\n const elapsed = Date.now() - audit.logicalStartedAt;\n const wholeRemainingMs = audit.policy.wholeRequestTimeoutMs - elapsed;\n const timeoutClass =\n wholeRemainingMs <= audit.policy.headersTimeoutMs ? \"whole_request\" : \"headers\";\n const deadlineMs = Math.max(1, Math.min(audit.policy.headersTimeoutMs, wholeRemainingMs));\n if (wholeRemainingMs <= 0) {\n throw new CodexResponseTimeoutError(\"whole_request\", audit.requestId, false);\n }\n\n const externalSignal = init.signal;\n if (externalSignal?.aborted) throw externalSignal.reason;\n const controller = new AbortController();\n const forwardAbort = () => controller.abort(externalSignal?.reason);\n externalSignal?.addEventListener(\"abort\", forwardAbort, { once: true });\n const basePromise = base(input, { ...init, signal: controller.signal });\n let deadlineError: CodexResponseTimeoutError | null = null;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n deadlineError = new CodexResponseTimeoutError(timeoutClass, audit.requestId, false);\n reject(deadlineError);\n }, deadlineMs);\n });\n try {\n return await Promise.race([basePromise, deadline]);\n } catch (error) {\n if (deadlineError) {\n controller.abort(deadlineError);\n void basePromise\n .then((late) => late.body?.cancel(deadlineError ?? undefined))\n .catch(() => undefined);\n throw deadlineError;\n }\n throw error;\n } finally {\n if (timer) clearTimeout(timer);\n externalSignal?.removeEventListener(\"abort\", forwardAbort);\n }\n}\n\nasync function observedResponse(\n res: Response,\n audit: RequestAudit,\n externalSignal: AbortSignal | null | undefined,\n semanticTerminal?: SemanticTerminalState,\n): Promise<Response> {\n const requestId = providerRequestId(res.headers);\n if (!res.body) {\n if (semanticTerminal) markSemanticTerminal(semanticTerminal, \"failed\");\n await emitRequestEvent(audit, {\n phase: semanticTerminal?.phase ?? (res.ok ? \"completed\" : \"failed\"),\n responseObserved: true,\n status: res.status,\n ...(requestId ? { providerRequestId: requestId } : {}),\n });\n return res;\n }\n\n const reader = res.body.getReader();\n let terminal = false;\n let firstByte = false;\n let idleTimer: ReturnType<typeof setTimeout> | undefined;\n let wholeTimer: ReturnType<typeof setTimeout> | undefined;\n let armIdle: () => void = () => undefined;\n let abortFromOutside: (() => void) | undefined;\n\n const clearTimers = () => {\n if (idleTimer) clearTimeout(idleTimer);\n if (wholeTimer) clearTimeout(wholeTimer);\n if (abortFromOutside) externalSignal?.removeEventListener(\"abort\", abortFromOutside);\n };\n\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n const timeOut = (klass: \"idle_stream\" | \"whole_request\") => {\n if (terminal) return;\n terminal = true;\n clearTimers();\n const semanticPhase = semanticTerminal?.phase;\n const phase = semanticPhase ?? \"timed_out\";\n const error = new CodexResponseTimeoutError(klass, audit.requestId, true);\n void reader.cancel(error).catch(() => undefined);\n void emitRequestEvent(audit, {\n phase,\n responseObserved: true,\n ...(phase === \"timed_out\" ? { timeoutClass: klass } : {}),\n status: res.status,\n ...(requestId ? { providerRequestId: requestId } : {}),\n }).then(\n () => (phase === \"completed\" ? controller.close() : controller.error(error)),\n () => (phase === \"completed\" ? controller.close() : controller.error(error)),\n );\n };\n armIdle = () => {\n if (idleTimer) clearTimeout(idleTimer);\n idleTimer = setTimeout(() => timeOut(\"idle_stream\"), audit.policy.streamIdleTimeoutMs);\n };\n armIdle();\n const wholeRemaining = Math.max(\n 1,\n audit.policy.wholeRequestTimeoutMs - (Date.now() - audit.logicalStartedAt),\n );\n wholeTimer = setTimeout(() => timeOut(\"whole_request\"), wholeRemaining);\n abortFromOutside = () => {\n if (terminal) return;\n terminal = true;\n clearTimers();\n const reason = externalSignal?.reason ?? new DOMException(\"Aborted\", \"AbortError\");\n void reader.cancel(reason).catch(() => undefined);\n void emitRequestEvent(audit, {\n phase: semanticTerminal?.phase ?? \"failed\",\n responseObserved: true,\n status: res.status,\n ...(requestId ? { providerRequestId: requestId } : {}),\n }).then(\n () =>\n semanticTerminal?.phase === \"completed\" ? controller.close() : controller.error(reason),\n () =>\n semanticTerminal?.phase === \"completed\" ? controller.close() : controller.error(reason),\n );\n };\n if (externalSignal?.aborted) {\n abortFromOutside();\n } else {\n externalSignal?.addEventListener(\"abort\", abortFromOutside, {\n once: true,\n });\n }\n },\n async pull(controller) {\n if (terminal) return;\n try {\n const chunk = await reader.read();\n if (terminal) return;\n if (chunk.done) {\n terminal = true;\n clearTimers();\n if (semanticTerminal && semanticTerminal.phase === null) {\n if (!semanticTerminal.deferTransportTerminal) {\n markSemanticTerminal(semanticTerminal, \"failed\");\n }\n }\n if (!semanticTerminal?.deferTransportTerminal || semanticTerminal.phase !== null) {\n await emitRequestEvent(audit, {\n phase: semanticTerminal?.phase ?? (res.ok ? \"completed\" : \"failed\"),\n responseObserved: true,\n status: res.status,\n ...(requestId ? { providerRequestId: requestId } : {}),\n });\n }\n controller.close();\n return;\n }\n if (!firstByte) {\n firstByte = true;\n // Deliver the provider byte before durable audit I/O. Audit latency\n // is not provider silence and must not manufacture an idle timeout.\n if (idleTimer) clearTimeout(idleTimer);\n controller.enqueue(chunk.value);\n await emitRequestEvent(audit, {\n phase: \"first_byte\",\n responseObserved: true,\n status: res.status,\n ...(requestId ? { providerRequestId: requestId } : {}),\n });\n if (!terminal) armIdle();\n return;\n }\n armIdle();\n controller.enqueue(chunk.value);\n } catch (error) {\n if (terminal) return;\n terminal = true;\n clearTimers();\n const semanticPhase = semanticTerminal?.phase;\n if (semanticTerminal && semanticPhase === null) {\n markSemanticTerminal(semanticTerminal, \"failed\");\n }\n await emitRequestEvent(audit, {\n phase: semanticPhase ?? \"failed\",\n responseObserved: true,\n status: res.status,\n ...(requestId ? { providerRequestId: requestId } : {}),\n });\n if (semanticPhase === \"completed\") {\n controller.close();\n } else {\n controller.error(error);\n }\n }\n },\n async cancel(reason) {\n if (!terminal) {\n terminal = true;\n clearTimers();\n if (semanticTerminal && semanticTerminal.phase === null) {\n markSemanticTerminal(semanticTerminal, \"failed\");\n }\n await emitRequestEvent(audit, {\n phase: semanticTerminal?.phase ?? \"failed\",\n responseObserved: true,\n status: res.status,\n ...(requestId ? { providerRequestId: requestId } : {}),\n }).catch(() => undefined);\n }\n await reader.cancel(reason).catch(() => undefined);\n },\n });\n const headers = new Headers(res.headers);\n headers.delete(\"content-length\");\n return new Response(body, {\n status: res.status,\n statusText: res.statusText,\n headers,\n });\n}\n\nfunction timeoutErrorResponse(info: {\n timeoutClass: \"connect\" | \"headers\" | \"idle_stream\" | \"whole_request\";\n requestId: string;\n responseObserved: boolean;\n message: string;\n}): Response {\n return new Response(\n JSON.stringify({\n error: {\n type: CODEX_RESPONSE_TIMEOUT_ERROR_TYPE,\n code: CODEX_RESPONSE_TIMEOUT_ERROR_TYPE,\n message: info.message,\n timeout_class: info.timeoutClass,\n response_observed: info.responseObserved,\n request_id: info.requestId,\n },\n }),\n {\n status: 504,\n headers: {\n \"content-type\": \"application/json\",\n \"x-should-retry\": \"false\",\n [CODEX_TRANSPORT_ERROR_HEADER]: \"1\",\n },\n },\n );\n}\n\nexport function codexSubscriptionFetch(base: FetchLike = globalThis.fetch): FetchLike {\n return async (input, init) => {\n const ctx = codexRequestStorage.getStore();\n if (!ctx) {\n return base(input, init); // not a codex turn — passthrough, untouched\n }\n emitRequestPreparationDiagnostic(ctx, \"transport_entry\");\n\n const rawUrl =\n typeof input === \"string\" ? input : input instanceof URL ? input.toString() : input.url;\n // /responses -> /codex/responses, idempotent: the negative lookbehind skips\n // URLs whose base already includes /codex (avoids /codex/codex/responses).\n const rewritten = rawUrl.replace(/(?<!\\/codex)\\/responses(\\b|$)/, \"/codex/responses$1\");\n\n const policy = resolveCodexResponseTimeoutPolicy(ctx.responseTimeoutPolicy);\n const handedRequestId = new Headers(init?.headers).get(CODEX_REQUEST_ID_HEADER);\n const requestId = handedRequestId ?? ctx.nextRequestId?.() ?? randomUUID();\n const logicalStartedAt = Date.now();\n let transportAttempt = 0;\n\n const attempt = async (\n auth: CodexTokenSnapshot,\n authenticationAttempt: number,\n ): Promise<Response> => {\n const headers = new Headers(init?.headers);\n const bodyAlreadyNormalized = headers.get(CODEX_REQUEST_BODY_NORMALIZED_HEADER) === \"1\";\n const normalizedModel = headers.get(CODEX_REQUEST_MODEL_HEADER) ?? undefined;\n const normalizedCallerStream = headers.get(CODEX_REQUEST_CALLER_STREAM_HEADER);\n headers.delete(CODEX_REQUEST_BODY_NORMALIZED_HEADER);\n headers.delete(CODEX_REQUEST_MODEL_HEADER);\n headers.delete(CODEX_REQUEST_ID_HEADER);\n headers.delete(CODEX_REQUEST_CALLER_STREAM_HEADER);\n headers.set(\"Authorization\", `Bearer ${auth.accessToken}`);\n if (auth.chatgptAccountId) {\n headers.set(\"ChatGPT-Account-ID\", auth.chatgptAccountId);\n }\n headers.set(\"originator\", CODEX_ORIGINATOR);\n headers.set(\"User-Agent\", `${CODEX_ORIGINATOR}/${ctx.clientVersion}`);\n headers.set(\"version\", ctx.clientVersion);\n headers.set(\"accept\", \"text/event-stream\");\n headers.set(\"content-type\", \"application/json\");\n if (ctx.sessionId) {\n // Backend sticky cache-routing key (see CodexRequestContext.sessionId):\n // without it, byte-identical resends miss the prompt cache ~half the\n // time; with it they pin to a warm shard and hit at the ceiling.\n headers.set(\"session_id\", ctx.sessionId);\n }\n if (auth.isFedramp) {\n headers.set(\"X-OpenAI-Fedramp\", \"true\");\n }\n headers.delete(\"OpenAI-Beta\"); // omit on SSE (spec §1.2); fallback: \"responses=experimental\" if backend 400s\n headers.delete(\"x-api-key\");\n // Codex CLI advertises betas via x-codex-beta-features (not OpenAI-Beta).\n if (ctx.betaFeatures && ctx.betaFeatures.length > 0) {\n headers.set(\"x-codex-beta-features\", ctx.betaFeatures.join(\",\"));\n }\n // Turn analytics / request_kind live in x-codex-turn-metadata — body\n // metadata is stripped by normalizeCodexRequestBody and rejected upstream.\n if (ctx.turnMetadata && Object.keys(ctx.turnMetadata).length > 0) {\n headers.set(\"x-codex-turn-metadata\", JSON.stringify(ctx.turnMetadata));\n }\n\n // The backend is streaming-only; force stream=true on the wire but remember\n // the caller's intent for legacy/unowned non-streaming consumers. The owned\n // compaction path consumes the same streaming model boundary as normal turns.\n let callerWantsStream = bodyAlreadyNormalized ? normalizedCallerStream !== \"0\" : true;\n let model: string | undefined = normalizedModel;\n let requestOpaqueArtifacts: string[] = [];\n const replayableBodyFactory = (init as ReplayableRequestInit | undefined)?.[\n REPLAYABLE_REQUEST_BODY_FACTORY\n ];\n const nextInit: RequestInit = {\n ...init,\n headers,\n ...(replayableBodyFactory ? { body: replayableBodyFactory() } : {}),\n };\n if (!bodyAlreadyNormalized && typeof init?.body === \"string\") {\n try {\n const parsed = JSON.parse(init.body) as Record<string, unknown>;\n callerWantsStream = parsed.stream === true;\n const normalized = normalizeCodexRequestBody(parsed, ctx.resolveModel);\n model = typeof normalized.model === \"string\" ? normalized.model : undefined;\n nextInit.body = JSON.stringify(normalized);\n requestOpaqueArtifacts = opaqueProviderArtifactFingerprints(normalized.input);\n } catch {\n // This is the final request-policy boundary for the strict Responses\n // endpoint. Never let malformed bytes bypass the reviewed policy.\n throw new Error(\"Model request could not be prepared\");\n }\n } else if (!bodyAlreadyNormalized) {\n throw new Error(\"Model request could not be prepared\");\n }\n if (!bodyAlreadyNormalized) {\n ctx.onRequestOpaqueArtifacts?.({\n requestId,\n fingerprints: requestOpaqueArtifacts,\n });\n }\n headers.set(\n \"Idempotency-Key\",\n authenticationAttempt === 0 ? requestId : `${requestId}:auth-${authenticationAttempt}`,\n );\n if (process.env.CODEX_DEBUG) {\n console.error(\"[codex-debug] request dispatched\", {\n method: \"POST\",\n origin: \"codex-subscription\",\n route: \"codex_responses\",\n stream: callerWantsStream,\n });\n }\n let res: Response;\n transportAttempt += 1;\n const audit: RequestAudit = {\n ctx,\n requestId,\n transportAttempt,\n ...(model ? { model } : {}),\n logicalStartedAt,\n attemptStartedAtMonotonic: performance.now(),\n policy,\n terminalOutcome: null,\n };\n emitRequestPreparationDiagnostic(ctx, \"wire_request_ready\");\n await emitRequestEvent(audit, {\n phase: \"started\",\n responseObserved: false,\n });\n const semanticTerminal: SemanticTerminalState = {\n phase: null,\n deferTransportTerminal: !callerWantsStream,\n };\n try {\n await ctx.beforeProviderDispatch?.();\n res = await fetchBeforeHeaders(base, rewritten, nextInit, audit);\n const upstreamRequestId = providerRequestId(res.headers);\n await emitRequestEvent(audit, {\n phase: \"headers\",\n responseObserved: true,\n status: res.status,\n ...(upstreamRequestId ? { providerRequestId: upstreamRequestId } : {}),\n });\n res = await observedResponse(res, audit, nextInit.signal, semanticTerminal);\n } catch (error) {\n if (nextInit.signal?.aborted) {\n await emitRequestEvent(audit, {\n phase: \"failed\",\n responseObserved: false,\n }).catch(() => undefined);\n throw error;\n }\n const klass = isPreHeadersTimeoutError(error);\n if (!klass) {\n await emitRequestEvent(audit, {\n phase: \"failed\",\n responseObserved: false,\n });\n throw error;\n }\n // An absent response does not prove that the provider never accepted\n // this operation. Until a provider-specific receipt can prove\n // non-acceptance or resume the same operation, never replay it.\n // Audit persistence must not replace the typed transport timeout.\n await emitRequestEvent(audit, {\n phase: \"timed_out\",\n responseObserved: false,\n timeoutClass: klass,\n willRetry: false,\n }).catch(() => undefined);\n throw new CodexResponseTimeoutError(klass, requestId, false);\n }\n // Multi-account P4 (Part A): scrape the usage headers ONCE, before the\n // OK/!res.ok branch, so the same fire-and-forget read also covers the 429\n // hard-cap path (an exhausted serving account stamps its own fresh\n // used_percent with no extra fetch). Sync + non-throwing + never awaited;\n // `if (usage)` makes an absent/malformed header set a safe no-op. We read\n // res.headers only — the SSE body is never touched here.\n const usage = parseCodexUsageHeaders(res.headers);\n if (usage) {\n ctx.onUsageHeaders?.(usage);\n }\n if (process.env.CODEX_DEBUG && !res.ok) {\n // Never log provider bodies, identifiers, or headers: they can contain\n // request-derived or account content. A bounded status is sufficient.\n console.error(\"[codex-debug] request failed\", {\n origin: \"codex-subscription\",\n route: \"codex_responses\",\n status: res.status,\n });\n }\n // The backend leaves terminal response.output empty and delivers assistant\n // items through output_item.done. The typed model reducer reconstructs normal\n // streaming calls; only the legacy non-streaming transport fallback collapses\n // SSE into one JSON response here.\n if (!res.ok) {\n // Buffer the error body once and re-emit it as a concrete JSON Response.\n // A streaming responses request whose error body is left as the raw\n // (possibly SSE / already-streamed) Response makes the SDK throw\n // \"<status> status code (no body)\" — the JSON error (type/message/\n // resets_in_seconds) is lost, so a 429 usage cap surfaces as a generic,\n // wrongly-retryable rate-limit. Re-emitting a clean application/json\n // Response lets the SDK reconstruct error.error for EVERY codex error\n // (401/400/5xx too). For a hard usage cap we also pin x-should-retry:false\n // so the SDK does not burn its retry budget on a limit that won't lift.\n const buffered = await bufferCodexErrorResponse(res);\n const upstreamRequestId = providerRequestId(res.headers);\n markSemanticTerminal(semanticTerminal, \"failed\");\n await emitRequestEvent(audit, {\n phase: \"failed\",\n responseObserved: true,\n status: res.status,\n ...(upstreamRequestId ? { providerRequestId: upstreamRequestId } : {}),\n }).catch(() => undefined);\n return buffered;\n }\n if (callerWantsStream) {\n res = validateCodexStream(res, (phase) => {\n markSemanticTerminal(semanticTerminal, phase);\n });\n } else {\n res = await sseToJsonResponse(res, audit, semanticTerminal);\n }\n return res;\n };\n\n try {\n const token = await ctx.getToken();\n emitRequestPreparationDiagnostic(ctx, \"credential_ready\");\n let res = await attempt(token, 0);\n if (res.status === 401) {\n res = await attempt(await ctx.refresh(), 1); // single refresh-on-401 retry (spec §1.9)\n }\n return res;\n } catch (error) {\n const timeout = classifyCodexResponseTimeoutError(error);\n if (!timeout) throw error;\n return timeoutErrorResponse({\n timeoutClass: timeout.timeoutClass,\n requestId: timeout.requestId ?? requestId,\n responseObserved: timeout.responseObserved,\n message: timeout.message,\n });\n }\n };\n}\n\n/** The codex backend's hard-cap error type (ChatGPT/Codex usage limit reached). */\nexport const CODEX_USAGE_LIMIT_ERROR_TYPE = \"usage_limit_reached\";\n\nexport type CodexUsageLimitInfo = {\n /** Seconds until the usage cap resets, when the backend reported it. */\n resetsInSeconds: number | null;\n};\n\n/**\n * Classify a thrown error as a ChatGPT/Codex usage-cap (429 usage_limit_reached)\n * and extract the reset window. The SDK surfaces the codex backend's 429 as an\n * OpenAI APIError whose `.type` (and `.error.type`) is `usage_limit_reached` and\n * whose `.error.resets_in_seconds` carries the cap reset. Walks the cause chain\n * and tolerates the message-only shape so it survives any SDK re-wrapping.\n * Returns null for anything that is not a usage cap.\n */\nexport function classifyCodexUsageLimitError(error: unknown): CodexUsageLimitInfo | null {\n let cur: unknown = error;\n for (let depth = 0; depth < 6 && cur && typeof cur === \"object\"; depth++) {\n const e = cur as Record<string, unknown>;\n const body = (e.error && typeof e.error === \"object\" ? e.error : undefined) as\n | Record<string, unknown>\n | undefined;\n const type =\n (typeof e.type === \"string\" ? e.type : undefined) ??\n (typeof body?.type === \"string\" ? body.type : undefined);\n const message = typeof e.message === \"string\" ? e.message : \"\";\n const status = Number(e.status);\n if (\n type === CODEX_USAGE_LIMIT_ERROR_TYPE ||\n message.includes(CODEX_USAGE_LIMIT_ERROR_TYPE) ||\n (status === 429 && /usage limit/i.test(message))\n ) {\n const resets =\n (typeof body?.resets_in_seconds === \"number\" ? body.resets_in_seconds : undefined) ??\n (typeof e.resets_in_seconds === \"number\" ? (e.resets_in_seconds as number) : undefined) ??\n null;\n return { resetsInSeconds: resets };\n }\n cur = e.cause;\n }\n return null;\n}\n\n/**\n * Buffer a non-OK codex Response and re-emit it as a clean `application/json`\n * Response so the SDK can reconstruct `error.error` from the body. A 429 usage\n * cap (`error.type === \"usage_limit_reached\"`) is a HARD limit, not transient\n * backpressure, so we pin `x-should-retry: false` to stop the SDK retrying it.\n * Reading the body here also drains the socket of a discarded 401 (no leak).\n */\nasync function bufferCodexErrorResponse(res: Response): Promise<Response> {\n const { text: bodyText, truncated } = await readBoundedResponseText(\n res,\n MAX_CODEX_ERROR_BODY_BYTES,\n );\n const headers = new Headers(res.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.set(CODEX_TRANSPORT_ERROR_HEADER, \"1\");\n headers.delete(\"content-length\"); // body re-serialized\n headers.delete(\"content-encoding\"); // text() already decoded any gzip\n let errorType: string | undefined;\n let responseBody = bodyText;\n try {\n const parsed = JSON.parse(bodyText) as { error?: { type?: unknown } };\n errorType = typeof parsed.error?.type === \"string\" ? parsed.error.type : undefined;\n } catch {\n /* non-JSON error body — leave as-is, no retry-header override */\n }\n if (truncated) {\n responseBody = JSON.stringify({\n error: {\n type: \"provider_error_body_too_large\",\n code: \"provider_error_body_too_large\",\n message: `The provider returned an error body larger than ${MAX_CODEX_ERROR_BODY_BYTES} bytes`,\n },\n });\n headers.set(\"x-opengeni-provider-error-truncated\", \"1\");\n }\n if (errorType === CODEX_USAGE_LIMIT_ERROR_TYPE) {\n headers.set(\"x-should-retry\", \"false\");\n }\n return new Response(responseBody, {\n status: res.status,\n statusText: res.statusText,\n headers,\n });\n}\n\nasync function readBoundedResponseText(\n response: Response,\n maxBytes: number,\n): Promise<{ text: string; truncated: boolean }> {\n if (!response.body) return { text: \"\", truncated: false };\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const parts: string[] = [];\n let bytes = 0;\n let truncated = false;\n try {\n while (bytes < maxBytes) {\n const next = await reader.read();\n if (next.done) {\n parts.push(decoder.decode());\n return { text: parts.join(\"\"), truncated };\n }\n const remaining = maxBytes - bytes;\n const accepted =\n next.value.byteLength > remaining ? next.value.subarray(0, remaining) : next.value;\n bytes += accepted.byteLength;\n parts.push(decoder.decode(accepted, { stream: true }));\n if (accepted.byteLength !== next.value.byteLength) {\n truncated = true;\n break;\n }\n if (bytes >= maxBytes) {\n // Reaching the hard cap is sufficient to classify the body as\n // oversized. Probing for one more chunk can wait forever when an\n // upstream producer stops emitting without closing its stream.\n truncated = true;\n break;\n }\n }\n } catch {\n truncated = true;\n } finally {\n // Cancellation is advisory cleanup. Some Fetch/Streams implementations do\n // not settle cancel() until the producer exits; never let an oversized\n // provider error hold the request open behind that implementation detail.\n if (truncated) void reader.cancel().catch(() => undefined);\n }\n return { text: parts.join(\"\"), truncated };\n}\n\n/**\n * Collapse a Responses SSE stream into the single JSON Response object a\n * non-streaming `responses.create` caller expects: the terminal response.*\n * event carries the full `response` payload.\n */\nasync function sseToJsonResponse(\n res: Response,\n audit: RequestAudit,\n semanticTerminal: SemanticTerminalState,\n): Promise<Response> {\n const upstreamRequestId = providerRequestId(res.headers);\n const text = await res.text();\n let final: Record<string, unknown> | null = null;\n let terminalError: Response | null = null;\n const items: unknown[] = []; // assembled from output_item.done (the codex backend\n // leaves response.completed.response.output empty and emits the items separately).\n for (const data of sseDataPayloads(text)) {\n if (!data || data === \"[DONE]\") {\n continue;\n }\n try {\n const ev = JSON.parse(data) as CodexSseEvent;\n if (ev.type === \"response.output_item.done\" && ev.item !== undefined) {\n items.push(ev.item);\n } else {\n const terminal = classifyCodexSseTerminal(ev);\n if (terminal?.phase === \"failed\") {\n terminalError = codexSseFailureResponse(\n res,\n terminal.rawError,\n terminal.fallbackCode,\n terminal.fallbackMessage,\n {\n eventType: ev.type,\n responseId: ev.response?.id,\n responseStatus: ev.response?.status,\n },\n );\n } else if (terminal?.phase === \"completed\") {\n final = ev.response ?? null;\n }\n }\n } catch {\n /* ignore non-JSON keepalive lines */\n }\n }\n if (terminalError) {\n markSemanticTerminal(semanticTerminal, \"failed\");\n await emitRequestEvent(audit, {\n phase: \"failed\",\n responseObserved: true,\n status: res.status,\n ...(upstreamRequestId ? { providerRequestId: upstreamRequestId } : {}),\n });\n return terminalError;\n }\n if (!final) {\n markSemanticTerminal(semanticTerminal, \"failed\");\n await emitRequestEvent(audit, {\n phase: \"failed\",\n responseObserved: true,\n status: res.status,\n ...(upstreamRequestId ? { providerRequestId: upstreamRequestId } : {}),\n });\n return codexSseFailureResponse(\n res,\n null,\n \"invalid_sse_terminal\",\n \"The Codex response stream ended without a terminal response\",\n );\n }\n if (final && items.length > 0) {\n final = { ...final, output: items }; // prefer the assembled items over an empty output array\n }\n if (process.env.CODEX_DEBUG) {\n console.error(\n `[codex-debug] sse->json items=${items.length} outputLen=${Array.isArray(final?.output) ? (final.output as unknown[]).length : \"?\"}`,\n );\n }\n markSemanticTerminal(semanticTerminal, \"completed\");\n await emitRequestEvent(audit, {\n phase: \"completed\",\n responseObserved: true,\n status: res.status,\n ...(upstreamRequestId ? { providerRequestId: upstreamRequestId } : {}),\n });\n const headers = new Headers(res.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.delete(\"content-length\");\n return new Response(JSON.stringify(final), { status: 200, headers });\n}\n\nconst NON_RETRYABLE_SSE_ERROR_CODES = new Set([\n \"bio_policy\",\n \"context_length_exceeded\",\n \"cyber_policy\",\n \"insufficient_quota\",\n \"invalid_prompt\",\n \"usage_limit_reached\",\n]);\n\n/**\n * Project the data payloads from a complete SSE body. EventSource accepts LF,\n * CRLF, and bare CR line endings; splitting only on `\\n\\n` can therefore merge\n * a standards-valid terminal failure into the preceding event and silently\n * turn it into `{}`. Preserve the SSE rule that multiple data lines are joined\n * with `\\n`, and tolerate a final event without a trailing blank line as the\n * previous transport parser did.\n */\nfunction sseDataPayloads(text: string): string[] {\n const payloads: string[] = [];\n let dataLines: string[] = [];\n const dispatch = () => {\n if (dataLines.length > 0) payloads.push(dataLines.join(\"\\n\"));\n dataLines = [];\n };\n\n for (const line of text.split(/\\r\\n|\\r|\\n/)) {\n if (line === \"\") {\n dispatch();\n continue;\n }\n if (line === \"data\") {\n dataLines.push(\"\");\n continue;\n }\n if (!line.startsWith(\"data:\")) continue;\n const value = line.slice(5);\n dataLines.push(value.startsWith(\" \") ? value.slice(1) : value);\n }\n dispatch();\n return payloads;\n}\n\nconst CODEX_TERMINAL_ERROR_FIELD_MAX_BYTES = 256;\nconst CODEX_TERMINAL_ERROR_MESSAGE_MAX_BYTES = 4 * 1024;\nconst CODEX_TERMINAL_ERROR_TRUNCATION_MARKER = \"… [truncated]\";\n\nfunction boundedTerminalErrorField(\n value: unknown,\n maxBytes: number,\n): { value?: string; truncated: boolean } {\n if (typeof value !== \"string\") return { truncated: false };\n const encoder = new TextEncoder();\n const encoded = encoder.encode(value);\n if (encoded.byteLength <= maxBytes) return { value, truncated: false };\n\n const markerBytes = encoder.encode(CODEX_TERMINAL_ERROR_TRUNCATION_MARKER).byteLength;\n let prefixEnd = Math.max(0, maxBytes - markerBytes);\n while (prefixEnd > 0 && (encoded[prefixEnd]! & 0xc0) === 0x80) {\n prefixEnd -= 1;\n }\n return {\n value: `${new TextDecoder().decode(encoded.subarray(0, prefixEnd))}${CODEX_TERMINAL_ERROR_TRUNCATION_MARKER}`,\n truncated: true,\n };\n}\n\n/**\n * Convert a terminal error carried inside an HTTP-200 SSE stream into the\n * ordinary non-2xx JSON error contract expected by the OpenAI SDK. Codex CLI\n * treats the same events as provider failures; returning a successful `{}`\n * loses the actual cause and makes compaction look semantically empty.\n */\nfunction codexSseFailureResponse(\n source: Response,\n rawError: unknown,\n fallbackCode: string,\n fallbackMessage: string,\n metadata: {\n eventType?: unknown;\n responseId?: unknown;\n responseStatus?: unknown;\n } = {},\n): Response {\n const projection = codexSseFailureProjection(\n source,\n rawError,\n fallbackCode,\n fallbackMessage,\n metadata,\n );\n return new Response(JSON.stringify({ error: projection.error }), {\n status: projection.status,\n headers: projection.headers,\n });\n}\n\nexport type CodexSseFailureProjection = {\n status: number;\n error: {\n type: string;\n code: string;\n message: string;\n param?: string;\n event_type?: string;\n response_id?: string;\n response_status?: string;\n diagnostic_truncated?: true;\n };\n headers: Headers;\n};\n\nfunction codexSseFailureProjection(\n source: Response,\n rawError: unknown,\n fallbackCode: string,\n fallbackMessage: string,\n metadata: {\n eventType?: unknown;\n responseId?: unknown;\n responseStatus?: unknown;\n } = {},\n): CodexSseFailureProjection {\n const record =\n rawError && typeof rawError === \"object\" && !Array.isArray(rawError)\n ? (rawError as Record<string, unknown>)\n : {};\n const typeField = boundedTerminalErrorField(record.type, CODEX_TERMINAL_ERROR_FIELD_MAX_BYTES);\n const codeField = boundedTerminalErrorField(record.code, CODEX_TERMINAL_ERROR_FIELD_MAX_BYTES);\n const messageField = boundedTerminalErrorField(\n record.message ?? (typeof rawError === \"string\" ? rawError : undefined),\n CODEX_TERMINAL_ERROR_MESSAGE_MAX_BYTES,\n );\n const paramField = boundedTerminalErrorField(record.param, CODEX_TERMINAL_ERROR_FIELD_MAX_BYTES);\n const eventTypeField = boundedTerminalErrorField(\n metadata.eventType,\n CODEX_TERMINAL_ERROR_FIELD_MAX_BYTES,\n );\n const responseIdField = boundedTerminalErrorField(\n metadata.responseId,\n CODEX_TERMINAL_ERROR_FIELD_MAX_BYTES,\n );\n const responseStatusField = boundedTerminalErrorField(\n metadata.responseStatus,\n CODEX_TERMINAL_ERROR_FIELD_MAX_BYTES,\n );\n const providerType =\n typeField.value === \"error\" ||\n typeField.value === \"response.error\" ||\n typeField.value === \"response.failed\"\n ? undefined\n : typeField.value;\n const code =\n (codeField.value?.length ? codeField.value : undefined) ??\n (providerType?.length ? providerType : undefined) ??\n fallbackCode;\n const diagnosticTruncated =\n typeField.truncated ||\n codeField.truncated ||\n messageField.truncated ||\n paramField.truncated ||\n eventTypeField.truncated ||\n responseIdField.truncated ||\n responseStatusField.truncated ||\n Object.keys(record).some((key) => ![\"type\", \"code\", \"message\", \"param\"].includes(key)) ||\n (rawError !== null &&\n rawError !== undefined &&\n typeof rawError !== \"string\" &&\n (typeof rawError !== \"object\" || Array.isArray(rawError)));\n const error: CodexSseFailureProjection[\"error\"] = {\n type: providerType?.length ? providerType : code,\n code,\n message: messageField.value?.length ? messageField.value : fallbackMessage,\n ...(paramField.value?.length ? { param: paramField.value } : {}),\n ...(eventTypeField.value?.length ? { event_type: eventTypeField.value } : {}),\n ...(responseIdField.value?.length ? { response_id: responseIdField.value } : {}),\n ...(responseStatusField.value?.length ? { response_status: responseStatusField.value } : {}),\n ...(diagnosticTruncated ? { diagnostic_truncated: true } : {}),\n };\n const status =\n code === \"rate_limit_exceeded\" ||\n code === \"usage_limit_reached\" ||\n code === \"insufficient_quota\"\n ? 429\n : NON_RETRYABLE_SSE_ERROR_CODES.has(code)\n ? 400\n : 502;\n const headers = new Headers(source.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.set(CODEX_TRANSPORT_ERROR_HEADER, \"1\");\n // A terminal event means the provider already accepted and completed this\n // request. Never let the OpenAI SDK replay it merely because we synthesized\n // a non-2xx response to preserve the terminal failure.\n headers.set(\"x-should-retry\", \"false\");\n headers.delete(\"content-length\");\n headers.delete(\"content-encoding\");\n return { status, error, headers };\n}\n\n/**\n * A provider terminal carried inside an accepted HTTP-200 stream. The OpenAI\n * SDK cannot turn that late terminal into a non-2xx APIError because headers\n * have already been accepted, so the body transform throws this equivalent\n * bounded shape. Provider-supplied message/param text remains exact within the\n * explicit terminal-field byte contract; retry classification is additive and\n * never substitutes for the source diagnostic.\n */\nexport class CodexStreamingTerminalError extends Error {\n readonly status: number;\n readonly code: string;\n readonly type: string;\n readonly eventType?: string;\n readonly responseId?: string;\n readonly responseStatus?: string;\n readonly headers: Headers;\n readonly error: Record<string, unknown>;\n\n constructor(projection: CodexSseFailureProjection) {\n super(projection.error.message);\n this.name = \"CodexStreamingTerminalError\";\n this.status = projection.status;\n this.code = projection.error.code;\n this.type = projection.error.type;\n if (projection.error.event_type !== undefined) {\n this.eventType = projection.error.event_type;\n }\n if (projection.error.response_id !== undefined) {\n this.responseId = projection.error.response_id;\n }\n if (projection.error.response_status !== undefined) {\n this.responseStatus = projection.error.response_status;\n }\n this.headers = projection.headers;\n this.error = {\n type: projection.error.type,\n code: projection.error.code,\n message: projection.error.message,\n ...(projection.error.param ? { param: projection.error.param } : {}),\n ...(projection.error.event_type ? { event_type: projection.error.event_type } : {}),\n ...(projection.error.response_id ? { response_id: projection.error.response_id } : {}),\n ...(projection.error.response_status\n ? { response_status: projection.error.response_status }\n : {}),\n ...(projection.error.diagnostic_truncated ? { diagnostic_truncated: true } : {}),\n };\n }\n}\n\nfunction codexSseFailureError(\n source: Response,\n rawError: unknown,\n fallbackCode: string,\n publicMessage: string,\n metadata: {\n eventType?: unknown;\n responseId?: unknown;\n responseStatus?: unknown;\n } = {},\n): CodexStreamingTerminalError {\n return new CodexStreamingTerminalError(\n codexSseFailureProjection(source, rawError, fallbackCode, publicMessage, metadata),\n );\n}\n\n/**\n * Preserve a live Responses SSE stream byte-for-byte while translating only\n * provider-specific terminal failures into typed transport errors. Successful\n * output reconstruction belongs to the model reducer, so this layer retains no\n * duplicate output-item graph.\n */\nfunction validateCodexStream(\n res: Response,\n onSemanticTerminal?: (phase: \"completed\" | \"failed\") => void,\n): Response {\n if (!res.body) {\n onSemanticTerminal?.(\"failed\");\n const error = codexSseFailureError(\n res,\n null,\n \"invalid_sse_terminal\",\n \"The Codex response stream ended without a terminal response\",\n );\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.error(error);\n },\n });\n const headers = new Headers(res.headers);\n headers.delete(\"content-length\");\n return new Response(body, {\n status: res.status,\n statusText: res.statusText,\n headers,\n });\n }\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let buffer = \"\";\n let successfulTerminalSeen = false;\n const emitCompleteBlocks = (\n controller: TransformStreamDefaultController<Uint8Array>,\n final: boolean,\n ) => {\n let boundary = findSseBlockBoundary(buffer, final);\n while (boundary) {\n const block = buffer.slice(0, boundary.start);\n const separator = buffer.slice(boundary.start, boundary.end);\n buffer = buffer.slice(boundary.end);\n successfulTerminalSeen ||= inspectCodexSseBlock(block, res, onSemanticTerminal);\n controller.enqueue(encoder.encode(`${block}${separator}`));\n boundary = findSseBlockBoundary(buffer, final);\n }\n };\n const transform = new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n buffer += decoder.decode(chunk, { stream: true });\n emitCompleteBlocks(controller, false);\n },\n flush(controller) {\n buffer += decoder.decode();\n emitCompleteBlocks(controller, true);\n if (buffer.length > 0) {\n successfulTerminalSeen ||= inspectCodexSseBlock(buffer, res, onSemanticTerminal);\n controller.enqueue(encoder.encode(buffer));\n buffer = \"\";\n }\n if (!successfulTerminalSeen) {\n throw codexSseFailureError(\n res,\n null,\n \"invalid_sse_terminal\",\n \"The Codex response stream ended without a terminal response\",\n );\n }\n },\n });\n const headers = new Headers(res.headers);\n headers.delete(\"content-length\");\n return new Response(res.body.pipeThrough(transform), {\n status: res.status,\n headers,\n });\n}\n\ntype SseBlockBoundary = { start: number; end: number };\n\n/**\n * Find two consecutive SSE line endings without misreading one CRLF as a bare\n * CR followed by a bare LF. A trailing CR is intentionally held until the next\n * chunk (or final flush), because only then can it be distinguished from the\n * first byte of CRLF.\n */\nfunction findSseBlockBoundary(value: string, final: boolean): SseBlockBoundary | null {\n for (let index = 0; index < value.length; index += 1) {\n const firstEnd = sseLineEndingEnd(value, index, final);\n if (firstEnd === null) continue;\n const secondEnd = sseLineEndingEnd(value, firstEnd, final);\n if (secondEnd !== null) {\n return { start: index, end: secondEnd };\n }\n index = firstEnd - 1;\n }\n return null;\n}\n\nfunction sseLineEndingEnd(value: string, index: number, final: boolean): number | null {\n const current = value[index];\n if (current === \"\\n\") return index + 1;\n if (current !== \"\\r\") return null;\n if (index + 1 < value.length) {\n return value[index + 1] === \"\\n\" ? index + 2 : index + 1;\n }\n return final ? index + 1 : null;\n}\n\nconst CODEX_TERMINAL_TYPE_HINTS = [\n '\"response.completed\"',\n '\"response.done\"',\n '\"response.failed\"',\n '\"response.incomplete\"',\n '\"response.error\"',\n '\"error\"',\n] as const;\n\n/**\n * Parse only blocks that can be terminal. Ordinary deltas and output items pass\n * without object allocation; failed/error/incomplete terminals throw before the\n * model can mistake them for an ordinary response_done event.\n */\nfunction inspectCodexSseBlock(\n block: string,\n source: Response,\n onSemanticTerminal?: (phase: \"completed\" | \"failed\") => void,\n): boolean {\n const lines = block.split(/\\r\\n|\\r|\\n/);\n const dataStr = lines\n .filter((l) => l.startsWith(\"data:\"))\n .map((l) => l.slice(5).trim())\n .join(\"\\n\");\n if (!dataStr || dataStr === \"[DONE]\") {\n return false;\n }\n if (!CODEX_TERMINAL_TYPE_HINTS.some((terminalType) => dataStr.includes(terminalType))) {\n return false;\n }\n let ev: CodexSseEvent;\n try {\n ev = JSON.parse(dataStr);\n } catch {\n return false;\n }\n const terminal = classifyCodexSseTerminal(ev);\n if (terminal?.phase === \"failed\") {\n onSemanticTerminal?.(\"failed\");\n throw codexSseFailureError(\n source,\n terminal.rawError,\n terminal.fallbackCode,\n terminal.fallbackMessage,\n {\n eventType: ev.type,\n responseId: ev.response?.id,\n responseStatus: ev.response?.status,\n },\n );\n }\n if (terminal?.phase === \"completed\") {\n onSemanticTerminal?.(\"completed\");\n return true;\n }\n return false;\n}\n","import { createHash } from \"node:crypto\";\n\n/** Stable, content-hiding identity for one opaque provider artifact. */\nexport function opaqueProviderArtifactFingerprint(item: unknown): string | null {\n if (!item || typeof item !== \"object\") return null;\n const record = item as Record<string, unknown>;\n if (record.type !== \"reasoning\" && record.type !== \"compaction\") return null;\n const providerData =\n record.providerData && typeof record.providerData === \"object\"\n ? (record.providerData as Record<string, unknown>)\n : null;\n const ciphertext =\n (typeof record.encrypted_content === \"string\" && record.encrypted_content) ||\n (typeof record.encryptedContent === \"string\" && record.encryptedContent) ||\n (typeof providerData?.encrypted_content === \"string\" && providerData.encrypted_content) ||\n (typeof providerData?.encryptedContent === \"string\" && providerData.encryptedContent) ||\n null;\n if (!ciphertext) return null;\n return `${record.type}:${createHash(\"sha256\").update(ciphertext).digest(\"hex\")}`;\n}\n\n/** Exact opaque artifacts present in one normalized provider input array. */\nexport function opaqueProviderArtifactFingerprints(input: unknown): string[] {\n if (!Array.isArray(input)) return [];\n return input.flatMap((item) => {\n const fingerprint = opaqueProviderArtifactFingerprint(item);\n return fingerprint ? [fingerprint] : [];\n });\n}\n","// The codex_apps connector MCP is incompatible with the Responses API tool\n// contract in two ways that each fail the whole turn:\n//\n// 1. NAMES. Connector tools are named like \"vercel.deploy_to_vercel\" (dots).\n// The Responses API requires every function-tool name to match\n// ^[A-Za-z0-9_-]+$, so the request 400s (\"Invalid 'tools[0].name': string\n// does not match pattern\"). We cannot just rename them in tools/list — the\n// model would then call a name the MCP server does not know. So we remap\n// BIDIRECTIONALLY at the transport: sanitize the name (and remember the\n// mapping) on the tools/list RESPONSE, and reverse it back to the original on\n// the tools/call REQUEST.\n//\n// 2. OUTPUT SCHEMAS. 122 of 217 tools return an empty `outputSchema: {}` (no\n// `type`). @modelcontextprotocol/sdk validates every tool's outputSchema as a\n// strict `{ type: \"object\", ... }` and ZodErrors the WHOLE tools/list. Since\n// codex_apps runs with cacheToolsList:false it re-lists per turn, so that\n// error (thrown during tool enumeration, outside the best-effort connect\n// wrapper) fails the turn. We drop any non-object outputSchema before the\n// validator sees it — safe, as outputSchema is an advisory hint only.\n\nimport { CODEX_APPS_MCP_SERVER_ID } from \"./constants\";\nimport type { FetchLike } from \"./fetch\";\n\nconst VALID_TOOL_NAME = /^[a-zA-Z0-9_-]+$/;\n\n// The Responses API rejects a function-tool name longer than 64 chars (it 400s\n// the WHOLE turn). Some namespaced connector tool names exceed this, and the\n// collision-disambiguation suffix only lengthens names, so the mapper must cap\n// length too — not just charset.\nconst MAX_TOOL_NAME_LEN = 64;\n\n// CRITICAL: this sanitizer runs on the codex_apps tools/list wire BEFORE OpenGeni's\n// PrefixedMcpServer (packages/runtime) prepends `<serverId>__` to every tool name\n// (prefixedMcpToolName). The 64-char limit applies to that FINAL prefixed name the\n// model sees, so a name we cap at 64 here becomes 64 + 12 = 76 after prefixing and\n// 400s the whole turn. Reserve the runtime prefix so `codex_apps__<sanitized>` is\n// always <= 64. The sanitizer owns the server id, so the reservation is exact and\n// stays self-contained (no runtime import). The reverse mapping is unaffected: the\n// mapper is keyed on the pre-prefix sanitized name, which is what tools/call carries\n// back after PrefixedMcpServer strips its prefix.\nconst RUNTIME_TOOL_NAME_PREFIX_LEN = CODEX_APPS_MCP_SERVER_ID.length + \"__\".length; // `codex_apps__` = 12\nconst EFFECTIVE_MAX_TOOL_NAME_LEN = MAX_TOOL_NAME_LEN - RUNTIME_TOOL_NAME_PREFIX_LEN; // 52\n\n/** Short, stable, charset-legal hash of a string (djb2 → base36). Deterministic. */\nfunction shortHash(input: string): string {\n let h = 5381;\n for (let i = 0; i < input.length; i++) {\n h = ((h << 5) + h + input.charCodeAt(i)) >>> 0; // h * 33 + c, kept unsigned\n }\n return h.toString(36);\n}\n\n/** Truncate to <= EFFECTIVE_MAX_TOOL_NAME_LEN (reserving the runtime prefix), appending `_<hash(original)>` so the result stays unique + deterministic. */\nfunction capLength(candidate: string, original: string): string {\n if (candidate.length <= EFFECTIVE_MAX_TOOL_NAME_LEN) {\n return candidate;\n }\n const suffix = `_${shortHash(original)}`;\n return candidate.slice(0, Math.max(0, EFFECTIVE_MAX_TOOL_NAME_LEN - suffix.length)) + suffix;\n}\n\n/**\n * Maps connector tool names to a Responses-API-legal charset and back. One\n * instance per codex_apps transport (i.e. per turn): tools/list populates it,\n * tools/call reads it. Idempotent across repeat listings.\n */\nexport class ToolNameMapper {\n private readonly sanitizedToOriginal = new Map<string, string>();\n private readonly used = new Set<string>();\n\n /** Return a legal, unique name (<= EFFECTIVE_MAX_TOOL_NAME_LEN, so `<prefix>__name` <= 64) for `original`, recording the reverse mapping. */\n sanitize(original: string): string {\n let candidate = VALID_TOOL_NAME.test(original)\n ? original\n : original.replace(/[^a-zA-Z0-9_-]/g, \"_\") || \"tool\";\n // Enforce the Responses-API 64-char cap (stable hash suffix keyed on the\n // ORIGINAL → deterministic across repeat listings, distinct originals don't\n // collide after truncation).\n candidate = capLength(candidate, original);\n // Disambiguate a genuine collision with a DIFFERENT original (never with\n // the same original — that keeps repeat listings stable/idempotent). Re-cap\n // after each suffix so disambiguation never re-breaches the effective limit.\n if (this.used.has(candidate) && this.sanitizedToOriginal.get(candidate) !== original) {\n const base = candidate;\n let n = 2;\n do {\n const suffix = `_${n++}`;\n candidate =\n (base.length + suffix.length > EFFECTIVE_MAX_TOOL_NAME_LEN\n ? base.slice(0, EFFECTIVE_MAX_TOOL_NAME_LEN - suffix.length)\n : base) + suffix;\n } while (this.used.has(candidate));\n }\n this.used.add(candidate);\n this.sanitizedToOriginal.set(candidate, original);\n return candidate;\n }\n\n /** Reverse a sanitized name back to the MCP server's original, if known. */\n toOriginal(sanitized: string): string | undefined {\n return this.sanitizedToOriginal.get(sanitized);\n }\n}\n\n/**\n * Drop bad outputSchemas + sanitize tool names on a JSON-RPC tools/list result, in place.\n *\n * When `namespaceSink` is provided, accumulate each tool's ORIGINAL\n * connector namespace (the segment BEFORE the first dot, e.g. `github` from\n * `github.create_issue`) into it — captured HERE because this pass sees the original\n * dotted name BEFORE mapper.sanitize rewrites the dot away. Only dotted names carry a\n * connector namespace; un-dotted (already-legal) names are not connectors and are skipped.\n */\nfunction sanitizeToolsInRpcMessage(\n message: unknown,\n mapper: ToolNameMapper,\n namespaceSink?: Set<string>,\n): void {\n if (!message || typeof message !== \"object\") {\n return;\n }\n const tools = (message as { result?: { tools?: unknown } }).result?.tools;\n if (!Array.isArray(tools)) {\n return;\n }\n for (const tool of tools) {\n if (!tool || typeof tool !== \"object\") {\n continue;\n }\n const record = tool as Record<string, unknown>;\n if (\"outputSchema\" in record) {\n // Drop EVERY outputSchema, not just malformed/empty ones. The MCP SDK client\n // caches a validator for any tool that declares an outputSchema and validates\n // each tool CALL's `structuredContent` against it — and the codex_apps\n // connectors return results that do NOT match their own declared schemas\n // (e.g. the schema requires a `result` property the response omits), so the\n // SDK throws `McpError -32602: Structured content does not match the tool's\n // output schema` and EVERY such connector tool call fails (observed live:\n // gmail_search_emails / gmail_get_profile / gmail_list_labels all -32602ed).\n // outputSchema is advisory — the agent reads the text `content` regardless —\n // so dropping it makes the connector tools usable. This also subsumes the\n // empty-`{}` case the strict Tool schema rejected at tools/list time.\n delete record.outputSchema;\n }\n if (typeof record.name === \"string\") {\n if (namespaceSink && record.name.includes(\".\")) {\n const namespace = record.name.slice(0, record.name.indexOf(\".\"));\n if (namespace) {\n namespaceSink.add(namespace);\n }\n }\n record.name = mapper.sanitize(record.name);\n }\n }\n}\n\n/**\n * Surface a tool CALL's `structuredContent` to the model by inlining it as a text\n * `content` block, in place.\n *\n * WHY. The @openai/agents MCP bridge forwards ONLY `result.content` to the model\n * (agents-core shims/mcp-server: `const result = parsed.content`) and DISCARDS\n * `result.structuredContent`. The codex_apps connectors return the real payload in\n * `structuredContent` and a bare `\"Action completed.\"` placeholder in `content`\n * (verified live: `gmail.get_profile` → content=[{text:\"Action completed.\"}],\n * structuredContent={id,name,email,…}). Without this the agent's tool call\n * \"succeeds\" but carries NO data — the model sees only the placeholder. Appending\n * the structured payload as a text block makes the data reach the model while\n * leaving the original content untouched.\n *\n * No-op when there is no `structuredContent` — so a tools/list response (or any\n * result without it) passes through unchanged. Valid object payloads stay intact\n * for protocol-aware consumers. Invalid optional values (such as null) are removed\n * after any useful value is copied into `content`, because the MCP client validates\n * this field as an object before the tool can return. Runs after the outputSchema drop.\n */\nfunction inlineStructuredContentInRpcMessage(message: unknown): void {\n if (!message || typeof message !== \"object\") {\n return;\n }\n const result = (message as { result?: unknown }).result;\n if (!result || typeof result !== \"object\") {\n return;\n }\n const record = result as Record<string, unknown>;\n if (!(\"structuredContent\" in record)) {\n return;\n }\n const structured = record.structuredContent;\n if (structured !== undefined && structured !== null) {\n const text = typeof structured === \"string\" ? structured : JSON.stringify(structured);\n const content = Array.isArray(record.content) ? [...record.content] : [];\n content.push({ type: \"text\", text });\n record.content = content;\n }\n if (typeof structured !== \"object\" || structured === null || Array.isArray(structured)) {\n delete record.structuredContent;\n }\n}\n\n/** Sanitize a single JSON body (application/json MCP response). */\nexport function sanitizeMcpJsonBody(\n text: string,\n mapper: ToolNameMapper = new ToolNameMapper(),\n namespaceSink?: Set<string>,\n): string {\n try {\n const parsed = JSON.parse(text);\n sanitizeToolsInRpcMessage(parsed, mapper, namespaceSink);\n inlineStructuredContentInRpcMessage(parsed);\n return JSON.stringify(parsed);\n } catch {\n return text; // not JSON we understand — leave untouched\n }\n}\n\n/** Sanitize an SSE body: each JSON-RPC message rides on a `data:` line. */\nexport function sanitizeMcpSseBody(\n text: string,\n mapper: ToolNameMapper = new ToolNameMapper(),\n namespaceSink?: Set<string>,\n): string {\n return text\n .split(\"\\n\")\n .map((line) => {\n if (!line.startsWith(\"data:\")) {\n return line;\n }\n const payload = line.slice(\"data:\".length).trimStart();\n try {\n const parsed = JSON.parse(payload);\n sanitizeToolsInRpcMessage(parsed, mapper, namespaceSink);\n inlineStructuredContentInRpcMessage(parsed);\n return `data: ${JSON.stringify(parsed)}`;\n } catch {\n return line;\n }\n })\n .join(\"\\n\");\n}\n\n/** Reverse a sanitized tools/call name back to the original; returns null if no rewrite is needed. */\nexport function remapToolCallRequestBody(body: string, mapper: ToolNameMapper): string | null {\n try {\n const message = JSON.parse(body) as { method?: unknown; params?: { name?: unknown } };\n if (message.method !== \"tools/call\") {\n return null;\n }\n const name = message.params?.name;\n if (typeof name !== \"string\") {\n return null;\n }\n const original = mapper.toOriginal(name);\n if (original === undefined || original === name) {\n return null;\n }\n message.params!.name = original;\n return JSON.stringify(message);\n } catch {\n return null;\n }\n}\n\n/**\n * Wrap a base fetch so the codex_apps MCP transport is Responses-API-compatible:\n * tools/list responses get their names sanitized + bad outputSchemas dropped (and\n * the name mapping recorded), and tools/call requests get their name reversed back\n * to the MCP server's original. Only the POST request/response is buffered; the\n * long-lived GET notification SSE stream is passed through untouched.\n *\n * An optional `namespaceSink` Set accumulates the ORIGINAL-dotted\n * connector namespaces seen across every tools/list this turn (captured before the\n * dot is sanitized away). The runtime reads the live by-reference Set only to keep\n * this turn's `tool_search` description accurate; it is never persisted or used\n * for inference selection.\n */\nexport function codexAppsSanitizingFetch(\n base: FetchLike = globalThis.fetch,\n namespaceSink?: Set<string>,\n): FetchLike {\n const mapper = new ToolNameMapper();\n return async (input, init) => {\n // Outgoing: reverse a sanitized tools/call name to the server's original.\n let nextInit = init;\n if (init && typeof init.body === \"string\" && (init.method ?? \"GET\").toUpperCase() === \"POST\") {\n const remapped = remapToolCallRequestBody(init.body, mapper);\n if (remapped !== null) {\n nextInit = { ...init, body: remapped };\n }\n }\n const res = await base(input, nextInit);\n const method = (\n init?.method ?? (input instanceof Request ? input.method : \"GET\")\n ).toUpperCase();\n if (method !== \"POST\" || !res.ok || !res.body) {\n return res;\n }\n const contentType = res.headers.get(\"content-type\") ?? \"\";\n const isJson = contentType.includes(\"application/json\");\n const isSse = contentType.includes(\"text/event-stream\");\n if (!isJson && !isSse) {\n return res;\n }\n const originalBody = await res.text();\n const sanitized = isJson\n ? sanitizeMcpJsonBody(originalBody, mapper, namespaceSink)\n : sanitizeMcpSseBody(originalBody, mapper, namespaceSink);\n const headers = new Headers(res.headers);\n headers.delete(\"content-length\"); // body length changed\n headers.delete(\"content-encoding\");\n return new Response(sanitized, { status: res.status, statusText: res.statusText, headers });\n };\n}\n","/**\n * Protocol-valid image shown to the model when an inline tool image exceeds the\n * hard model-input allowance. The image channel cannot carry a text marker, so\n * the omission itself is rendered as a legible PNG instead of corrupting the\n * original base64 or pretending the placeholder is the real screenshot.\n *\n * Generated with the dependency-free bitmap/PNG encoder documented in\n * `scripts/gen-screenshot-error-card.mjs`; the source image is 1,076x284 RGBA\n * and 5,255 bytes. Rendered text:\n *\n * SCREEN CAPTURE OMITTED\n * THE SCREEN CAPTURE IS TOO LARGE.\n * THIS IS A PLACEHOLDER, NOT THE REAL SCREEN.\n * DO NOT SAY THIS IS THE REAL SCREEN.\n * TELL THE USER TO TAKE A SMALLER CAPTURE.\n */\nexport const MODEL_TOOL_OUTPUT_OVERSIZED_IMAGE_CARD_DATA_URL =\n \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDQAAAEcCAYAAAA4KeSGAAAUTklEQVR42u3cO5JTvRaAUcZAEXTA0BhZT9GJE8fNEBojbWk/VrCi+2OMjqzHd6vOj88/P78AAAAAKvlhEAAAAABBAwAAAEDQAAAAABA0AAAAAEEDAAAAQNAAAAAAEDQAAAAAQQMAAABA0AAAAAAQNAAAAABBAwAAAEDQAAAAABA0AAAAAEEDAAAAQNAAAAAAEDQAAAAAQQMAAABA0AAAAAAQNAAAAAAEDQAAAEDQAAAAABA0AAAAAAQNAAAAQND4T6/nY8npz8/+faO//7ufvzofbv8g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aAgagoaggaAhaLhQCBqChqAhaAgagoagIWgIGoKGoCFoCBqCBgAAAICgAQAAACBoAAAAAIIGAAAAgKABAAAAIGgAAAAAggYAAACAoAEAAAAgaAAAAACCBgAAAICgAQAAACBoAAAAAAgaAAAAgKABAAAAIGgAAAAACBoAAACAoAEAAAAgaAAAAAAIGgAAAICgAQAAACBoAAAAAAgaAAAAgKABAAAAIGgAAAAAbPAXSdffkpULfXUAAAAASUVORK5CYII=\";\n","/**\n * Canonical model-facing tool-output truncation.\n *\n * Ported from openai/codex `rust-v0.144.6` (commit\n * 5d1fbf26c43abc65a203928b2e31561cb039e06d):\n *\n * - `codex-rs/utils/string/src/truncate.rs`\n * - `codex-rs/utils/output-truncation/src/lib.rs`\n * - `codex-rs/core/src/context_manager/history.rs`\n *\n * The live gpt-5.6 model catalog declares a 10,000-token truncation policy.\n * Codex applies a 1.2x allowance before serializing a function-call output, so\n * the effective textual payload budget is 12,000 approximate tokens. Images,\n * files, and encrypted content are preserved; textual content shares one\n * sequential budget and carries an explicit head/tail truncation marker.\n *\n * This module deliberately has no database or Agents SDK dependency. Both the\n * runtime request seam and the database history boundary call the same pure\n * function, so replayed conversation truth is identical to live model input.\n */\n\nimport { MODEL_TOOL_OUTPUT_OVERSIZED_IMAGE_CARD_DATA_URL } from \"./oversized-image-card\";\n\nexport { MODEL_TOOL_OUTPUT_OVERSIZED_IMAGE_CARD_DATA_URL } from \"./oversized-image-card\";\n\nexport type ModelHistoryItem = Record<string, unknown>;\n\ntype WithoutOutputOnlyProviderDataFields<T> = T extends ModelHistoryItem ? Omit<T, \"status\"> : T;\n\ntype WithoutOutputOnlyProviderDataField<T extends ModelHistoryItem> = \"providerData\" extends keyof T\n ? string extends keyof T\n ? {\n providerData?: WithoutOutputOnlyProviderDataFields<T[\"providerData\"]>;\n }\n : object extends Pick<T, Extract<keyof T, \"providerData\">>\n ? {\n providerData?: WithoutOutputOnlyProviderDataFields<T[\"providerData\"]>;\n }\n : {\n providerData: WithoutOutputOnlyProviderDataFields<T[\"providerData\"]>;\n }\n : object;\n\ntype WithoutOutputOnlyHistoryItemFields<T extends ModelHistoryItem> = T extends unknown\n ? Omit<T, \"status\" | \"providerData\"> & WithoutOutputOnlyProviderDataField<T>\n : never;\n\n/**\n * Responses output items carry `status` (`in_progress` / `completed` /\n * `incomplete`). That field is not conversation meaning — pairing is `call_id`\n * — and Codex's input schema 400s it (`Unknown parameter: 'input[N].status'`).\n * SuperGrok accepts items with or without it. The SDK also nests `status` on\n * `providerData` (reasoning items) and flattens it back onto the request.\n * Canonical history therefore omits both at persist so portable sessions can\n * cross Responses providers.\n */\nexport function omitOutputOnlyHistoryItemFields<T extends ModelHistoryItem>(\n item: T,\n): WithoutOutputOnlyHistoryItemFields<T> {\n if (!item || typeof item !== \"object\") {\n return item as unknown as WithoutOutputOnlyHistoryItemFields<T>;\n }\n const providerData =\n item.providerData && typeof item.providerData === \"object\"\n ? (item.providerData as Record<string, unknown>)\n : null;\n const hasTopStatus = \"status\" in item;\n const hasNestedStatus = Boolean(providerData && \"status\" in providerData);\n if (!hasTopStatus && !hasNestedStatus) {\n return item as unknown as WithoutOutputOnlyHistoryItemFields<T>;\n }\n const next = { ...item };\n if (hasTopStatus) delete (next as Record<string, unknown>).status;\n if (hasNestedStatus && providerData) {\n const { status: _dropped, ...rest } = providerData;\n (next as Record<string, unknown>).providerData = rest;\n }\n return next as unknown as WithoutOutputOnlyHistoryItemFields<T>;\n}\n\n/** Persist/replay boundary: drop output-only fields, then bound tool output. */\nexport function canonicalizePersistedHistoryItem<T extends ModelHistoryItem>(\n item: T,\n policyTokens = DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,\n): WithoutOutputOnlyHistoryItemFields<T> {\n return boundModelToolOutputItem(omitOutputOnlyHistoryItemFields(item), policyTokens);\n}\n\nexport const CODEX_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS = 10_000;\nexport const CODEX_TOOL_OUTPUT_SERIALIZATION_ALLOWANCE = 1.2;\nexport const DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS =\n CODEX_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS;\n\nconst APPROX_BYTES_PER_TOKEN = 4;\n// Twelve decimal digits already describe ~4 TB at four bytes/token, far beyond\n// any JavaScript string the runtime can materialize. Bounding the digit run is\n// security-significant: otherwise a forged multi-megabyte run of digits could\n// make `markerBytes` as large as the entire untrusted tool result and bypass the\n// cap below.\nconst TOKEN_TRUNCATION_MARKER = /…\\d{1,12} tokens truncated…/u;\nconst TOOL_RESULT_TYPES = new Set([\n \"function_call_result\",\n \"function_call_output\",\n \"computer_call_result\",\n \"custom_tool_call_output\",\n \"shell_call_output\",\n \"apply_patch_call_output\",\n]);\nconst STRUCTURAL_STRING_KEYS = new Set([\n \"type\",\n \"role\",\n \"status\",\n \"name\",\n \"id\",\n \"callId\",\n \"call_id\",\n \"namespace\",\n \"detail\",\n \"mimeType\",\n \"media_type\",\n]);\nconst MODEL_TOOL_OUTPUT_MAX_DEPTH = 12;\nconst MODEL_TOOL_OUTPUT_MAX_CONTAINER_ENTRIES = 255;\nconst MODEL_TOOL_OUTPUT_MAX_TOTAL_ENTRIES = 2_048;\nconst MODEL_TOOL_OUTPUT_MAX_PROPERTY_KEY_BYTES = 256;\nconst MODEL_TOOL_OUTPUT_MAX_STRUCTURAL_STRING_TOKENS = 64;\nconst MODEL_TOOL_OUTPUT_STRUCTURAL_STRING_BUDGET_TOKENS = 1_024;\nexport const MODEL_TOOL_OUTPUT_OPAQUE_PAYLOAD_MAX_BYTES = 8 * 1024 * 1024;\n\nconst DEPTH_OMISSION_MARKER =\n \"[OpenGeni omitted subtree: maximum structured tool-output depth exceeded]\";\nconst CYCLE_OMISSION_MARKER = \"[OpenGeni omitted subtree: cyclic tool output]\";\nconst STRUCTURAL_STRING_OMISSION_MARKER =\n \"[OpenGeni omitted structural string: structural budget exhausted]\";\nconst TEXT_FIELD_OMISSION_MARKER = /^\\[omitted text field \\d+ \\.\\.\\.\\]$/u;\nconst TEXT_ITEMS_OMISSION_MARKER = /^\\[omitted \\d+ text items \\.\\.\\.\\]$/u;\nconst STRUCTURAL_ENTRIES_OMISSION_MARKER =\n /^\\[OpenGeni omitted \\d+ structured (?:array items|object properties)\\]$/u;\nconst OPAQUE_PAYLOAD_OMISSION_MARKER =\n /^\\[OpenGeni omitted (?:image|file|encrypted) payload: \\d+ bytes exceeded the bounded model-input allowance\\]$/u;\nconst STRUCTURAL_PROPERTIES_MARKER_KEY = \"__opengeni_omitted_properties__\";\n\ntype OpaqueProtocolKind = \"image\" | \"file\" | \"encrypted\";\n\ntype ModelOutputBoundState = {\n remaining: number;\n remainingStructural: number;\n remainingEntries: number;\n remainingOpaqueBytes: number;\n opaqueOmissions: number;\n lastOpaqueOmissionMarker: string | null;\n omitted: number;\n seen: WeakSet<object>;\n};\n\nexport function modelToolOutputSerializationBudgetTokens(\n policyTokens = DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,\n): number {\n return Math.ceil(Math.max(0, policyTokens) * CODEX_TOOL_OUTPUT_SERIALIZATION_ALLOWANCE);\n}\n\nexport function approximateTokenCount(value: string): number {\n return Math.ceil(Buffer.byteLength(value, \"utf8\") / APPROX_BYTES_PER_TOKEN);\n}\n\n/** Exact Codex-style middle truncation for a token policy. */\nexport function truncateMiddleWithTokenBudget(value: string, maxTokens: number): string {\n if (value.length === 0) return value;\n const maxBytes = Math.max(0, maxTokens) * APPROX_BYTES_PER_TOKEN;\n const valueBytes = Buffer.byteLength(value, \"utf8\");\n if (maxTokens > 0 && valueBytes <= maxBytes) return value;\n // Codex applies this transform once while recording history, so its marker\n // sits just outside the content budget. OpenGeni deliberately enforces the\n // same policy both at canonical persistence and at the final provider seam.\n // Recognize only an output whose excess is no larger than its own canonical\n // marker; this makes that repeated enforcement byte-idempotent without letting\n // an arbitrary oversized string bypass the cap merely by containing marker-like\n // text. The first application remains byte-for-byte Codex 0.144.6 behavior.\n const existingMarker = value.match(TOKEN_TRUNCATION_MARKER)?.[0];\n if (existingMarker && valueBytes <= maxBytes + Buffer.byteLength(existingMarker, \"utf8\")) {\n return value;\n }\n if (maxBytes === 0) {\n return `…${approximateTokenCount(value)} tokens truncated…`;\n }\n\n const leftBudget = Math.floor(maxBytes / 2);\n const rightBudget = maxBytes - leftBudget;\n // Do not materialize `Array.from(value)`: production tool results can be\n // multi-megabyte strings and one JS element per code point multiplies peak\n // memory. A single UTF-8 buffer gives bounded scans at the two cut points.\n const bytes = Buffer.from(value, \"utf8\");\n let leftEnd = Math.min(leftBudget, bytes.length);\n while (leftEnd > 0 && leftEnd < bytes.length && isUtf8ContinuationByte(bytes[leftEnd]!)) {\n leftEnd -= 1;\n }\n let rightStart = Math.max(0, bytes.length - rightBudget);\n while (rightStart < bytes.length && isUtf8ContinuationByte(bytes[rightStart]!)) {\n rightStart += 1;\n }\n const left = bytes.subarray(0, leftEnd).toString(\"utf8\");\n const right = bytes.subarray(rightStart).toString(\"utf8\");\n const removedBytes = Math.max(0, valueBytes - maxBytes);\n const removedTokens = Math.ceil(removedBytes / APPROX_BYTES_PER_TOKEN);\n return `${left}…${removedTokens} tokens truncated…${right}`;\n}\n\nfunction isUtf8ContinuationByte(value: number): boolean {\n return (value & 0xc0) === 0x80;\n}\n\n/**\n * Bound every model-visible tool-result item. Non-result items are returned by\n * reference. Result items are cloned only when their textual output changes.\n */\nexport function boundModelToolOutputItem<T extends ModelHistoryItem>(\n item: T,\n policyTokens = DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,\n): T {\n const type = typeof item.type === \"string\" ? item.type : \"\";\n if (!TOOL_RESULT_TYPES.has(type)) return item;\n const budget = modelToolOutputSerializationBudgetTokens(policyTokens);\n const boundedOutput = boundToolOutputValue(item.output, budget);\n return boundedOutput === item.output ? item : ({ ...item, output: boundedOutput } as T);\n}\n\nexport function boundModelToolOutputItems<T extends ModelHistoryItem>(\n items: readonly T[],\n policyTokens = DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,\n): T[] {\n let bounded: T[] | null = null;\n for (const [index, item] of items.entries()) {\n const next = boundModelToolOutputItem(item, policyTokens);\n if (next !== item && bounded === null) bounded = items.slice(0, index);\n bounded?.push(next);\n }\n return bounded ?? (items as T[]);\n}\n\nfunction boundToolOutputValue(output: unknown, budgetTokens: number): unknown {\n const state = modelOutputBoundState(budgetTokens);\n if (typeof output === \"string\") {\n if (isGeneratedModelOutputMarker(output)) {\n observeGeneratedMarkerBudget(output, state);\n return output;\n }\n // Text-transport computer/view_image tools use a data URL because Chat\n // Completions has no structured image result. It is still image protocol,\n // not textual tool output; truncating its base64 permanently corrupts it.\n if (isImageDataUrl(output)) return boundOpaqueProtocolString(output, state, \"image\");\n return truncateMiddleWithTokenBudget(output, budgetTokens);\n }\n if (Array.isArray(output)) {\n // Responses content arrays have an explicit text/image/file protocol and\n // follow Codex's sequential item policy exactly. Shell/apply adapters can\n // instead return arrays of objects containing stdout/stderr; those share\n // the same total text budget through the generic leaf walker.\n // Inspect only the prefix the boundary can retain. Cardinality itself does\n // not make an otherwise-valid Responses content list invalid, and scanning\n // an untrusted 100k-item tail merely to classify it defeats the bound.\n const isProtocolContent = isResponsesProtocolContentPrefix(output);\n return isProtocolContent\n ? boundStructuredOutputItems(output, state)\n : boundTextLeaves(output, state);\n }\n if (!output || typeof output !== \"object\") return output;\n\n const record = output as Record<string, unknown>;\n // Shell/apply-patch result objects are not structured Responses content, but\n // can contain arbitrarily large stdout/stderr leaves. Preserve useful shape\n // while sharing bounded text, structural, entry, depth, and opaque-protocol\n // budgets across the whole value.\n return boundTextLeaves(record, state);\n}\n\nfunction modelOutputBoundState(budgetTokens: number): ModelOutputBoundState {\n return {\n remaining: Math.max(0, budgetTokens),\n remainingStructural: MODEL_TOOL_OUTPUT_STRUCTURAL_STRING_BUDGET_TOKENS,\n remainingEntries: MODEL_TOOL_OUTPUT_MAX_TOTAL_ENTRIES,\n remainingOpaqueBytes: MODEL_TOOL_OUTPUT_OPAQUE_PAYLOAD_MAX_BYTES,\n opaqueOmissions: 0,\n lastOpaqueOmissionMarker: null,\n omitted: 0,\n seen: new WeakSet(),\n };\n}\n\nfunction boundStructuredOutputItems(items: unknown[], state: ModelOutputBoundState): unknown[] {\n let omitted = 0;\n let changed = false;\n const out: unknown[] = [];\n let processed = 0;\n // A canonical first pass can contain one typed structural trailer beyond the\n // ordinary 255 retained parts. Preserve that exact terminal trailer when a\n // durable/provider/recovery boundary applies the function again. Limiting\n // this exception to an already-bounded array prevents an arbitrary huge tail\n // with a marker-shaped last element from bypassing the first-pass count.\n const terminalStructuralMarker =\n items.length <= MODEL_TOOL_OUTPUT_MAX_CONTAINER_ENTRIES + 1 &&\n isTypedStructuralArrayOmissionMarker(items.at(-1))\n ? items.at(-1)\n : null;\n let preservedTerminalStructuralMarker = false;\n for (let index = 0; index < items.length; index += 1) {\n const item = items[index];\n if (processed >= MODEL_TOOL_OUTPUT_MAX_CONTAINER_ENTRIES || state.remainingEntries <= 0) {\n if (terminalStructuralMarker && index <= items.length - 1) {\n out.push(terminalStructuralMarker);\n preservedTerminalStructuralMarker = true;\n }\n break;\n }\n processed += 1;\n state.remainingEntries -= 1;\n const record = item as Record<string, unknown>;\n if (record.type === \"input_text\" && isGeneratedModelOutputMarker(record.text)) {\n const bounded = boundTextLeaves(item, state, 1);\n out.push(bounded);\n if (item === terminalStructuralMarker) preservedTerminalStructuralMarker = true;\n if (bounded !== item) changed = true;\n continue;\n }\n if (record.type === \"input_text\" && state.remaining === 0) {\n omitted += 1;\n changed = true;\n continue;\n }\n const bounded = boundResponsesProtocolContentItem(record, state);\n out.push(bounded);\n if (item === terminalStructuralMarker) preservedTerminalStructuralMarker = true;\n if (bounded !== item) changed = true;\n }\n if (omitted > 0) {\n out.push({\n type: \"input_text\",\n text: `[omitted ${omitted} text items ...]`,\n });\n }\n const structurallyOmitted = preservedTerminalStructuralMarker ? 0 : items.length - processed;\n if (structurallyOmitted > 0) {\n out.push(typedStructuredArrayOmissionMarker(structurallyOmitted));\n changed = true;\n }\n return changed ? out : items;\n}\n\nfunction boundResponsesProtocolContentItem(\n item: Record<string, unknown>,\n state: ModelOutputBoundState,\n): Record<string, unknown> {\n const opaqueOmissionsBefore = state.opaqueOmissions;\n const bounded = boundTextLeaves(item, state, 1) as Record<string, unknown>;\n // Agents interprets fileId/file_id (and nested image.id) as a provider file\n // reference. Replacing only that string with our data URL would manufacture\n // a fictitious file_id. Normalize the whole overflowing image part instead,\n // removing every ID field while staying inside the Responses content union.\n if (item.type === \"input_image\" && state.opaqueOmissions > opaqueOmissionsBefore) {\n return {\n type: \"input_image\",\n imageUrl: MODEL_TOOL_OUTPUT_OVERSIZED_IMAGE_CARD_DATA_URL,\n };\n }\n // A marker string in `input_file.file` is interpreted by pinned Agents as a\n // file_url. Replace the whole content part instead, so every generated\n // omission remains inside the Responses text/image/file union without\n // inventing a URL or file ID. This also covers cumulative opaque exhaustion.\n if (item.type === \"input_file\" && state.opaqueOmissions > opaqueOmissionsBefore) {\n return typedProtocolTextMarker(\n state.lastOpaqueOmissionMarker ??\n \"[OpenGeni omitted file payload: 0 bytes exceeded the bounded model-input allowance]\",\n );\n }\n return bounded;\n}\n\nfunction boundTextLeaves(\n value: unknown,\n state: ModelOutputBoundState,\n depth = 0,\n opaqueKind: OpaqueProtocolKind | null = null,\n): unknown {\n if (typeof value === \"string\") {\n if (isGeneratedModelOutputMarker(value)) {\n observeGeneratedMarkerBudget(value, state);\n return value;\n }\n if (opaqueKind || isImageDataUrl(value)) {\n return boundOpaqueProtocolString(value, state, opaqueKind ?? \"image\");\n }\n if (state.remaining === 0) {\n state.omitted += 1;\n return `[omitted text field ${state.omitted} ...]`;\n }\n const cost = approximateTokenCount(value);\n if (cost <= state.remaining) {\n state.remaining -= cost;\n return value;\n }\n const bounded = truncateMiddleWithTokenBudget(value, state.remaining);\n state.remaining = 0;\n return bounded;\n }\n if (!value || typeof value !== \"object\") return value;\n if (depth >= MODEL_TOOL_OUTPUT_MAX_DEPTH) return DEPTH_OMISSION_MARKER;\n if (state.seen.has(value)) return CYCLE_OMISSION_MARKER;\n state.seen.add(value);\n if (Array.isArray(value)) {\n const out: unknown[] = [];\n let processed = 0;\n let changed = false;\n for (let index = 0; index < value.length; index += 1) {\n const entry = value[index];\n if (processed >= MODEL_TOOL_OUTPUT_MAX_CONTAINER_ENTRIES || state.remainingEntries <= 0) {\n // A prior pass can add exactly one structural trailer beyond the normal\n // item allowance. Retain only that final trailer for replay idempotence;\n // marker-shaped untrusted entries otherwise consume the same caps as\n // every other entry and cannot form an unbounded bypass.\n if (\n index === value.length - 1 &&\n typeof entry === \"string\" &&\n STRUCTURAL_ENTRIES_OMISSION_MARKER.test(entry)\n ) {\n out.push(entry);\n }\n break;\n }\n processed += 1;\n state.remainingEntries -= 1;\n const bounded = boundTextLeaves(entry, state, depth + 1, opaqueKind);\n out.push(bounded);\n if (bounded !== entry) changed = true;\n }\n const omitted = value.length - out.length;\n if (omitted > 0) {\n out.push(structuredEntriesOmissionMarker(omitted, \"array\"));\n changed = true;\n }\n state.seen.delete(value);\n return changed ? out : value;\n }\n const record = value as Record<string, unknown>;\n const recordOpaqueKind = nonTextProtocolKind(record.type) ?? opaqueKind;\n const entries = Object.entries(record);\n const out: Record<string, unknown> = {};\n let processed = 0;\n let omitted = 0;\n let changed = false;\n for (let index = 0; index < entries.length; index += 1) {\n const [key, entry] = entries[index]!;\n if (processed >= MODEL_TOOL_OUTPUT_MAX_CONTAINER_ENTRIES || state.remainingEntries <= 0) {\n // As with arrays, a bounded prior pass may have appended one final marker\n // property after filling the normal property allowance. Preserve only\n // that terminal marker; forged/interspersed marker properties remain\n // ordinary bounded input.\n if (index === entries.length - 1 && isGeneratedStructuralMarkerProperty(key, entry)) {\n out[key] = entry;\n break;\n }\n omitted += entries.length - index;\n break;\n }\n processed += 1;\n state.remainingEntries -= 1;\n if (Buffer.byteLength(key, \"utf8\") > MODEL_TOOL_OUTPUT_MAX_PROPERTY_KEY_BYTES) {\n omitted += 1;\n changed = true;\n continue;\n }\n const childOpaqueKind = opaqueKindForChild(recordOpaqueKind, key);\n if (typeof entry === \"string\" && childOpaqueKind) {\n const bounded = boundTextLeaves(entry, state, depth + 1, childOpaqueKind);\n out[key] = bounded;\n if (bounded !== entry) changed = true;\n continue;\n }\n if (typeof entry === \"string\" && STRUCTURAL_STRING_KEYS.has(key)) {\n const bounded = boundStructuralString(entry, state);\n out[key] = bounded;\n if (bounded !== entry) changed = true;\n continue;\n }\n const bounded = boundTextLeaves(entry, state, depth + 1, childOpaqueKind);\n out[key] = bounded;\n if (bounded !== entry) changed = true;\n }\n if (omitted > 0) {\n out[uniqueStructuralMarkerKey(out)] = structuredEntriesOmissionMarker(omitted, \"object\");\n changed = true;\n }\n state.seen.delete(value);\n return changed ? out : value;\n}\n\nfunction boundStructuralString(value: string, state: ModelOutputBoundState): string {\n if (isGeneratedModelOutputMarker(value)) {\n observeGeneratedMarkerBudget(value, state);\n return value;\n }\n if (state.remainingStructural === 0) return STRUCTURAL_STRING_OMISSION_MARKER;\n const cost = approximateTokenCount(value);\n const allowance = Math.min(\n MODEL_TOOL_OUTPUT_MAX_STRUCTURAL_STRING_TOKENS,\n state.remainingStructural,\n );\n if (cost <= allowance) {\n state.remainingStructural -= cost;\n return value;\n }\n state.remainingStructural -= allowance;\n return truncateMiddleWithTokenBudget(value, allowance);\n}\n\nfunction boundOpaqueProtocolString(\n value: string,\n state: ModelOutputBoundState,\n kind: OpaqueProtocolKind,\n): string {\n // A prior pass can only have produced this exact static value. Treat it as a\n // consumed image allowance so applying the boundary again is byte-idempotent\n // even when more image fields follow it in the same structured result.\n if (kind === \"image\" && value === MODEL_TOOL_OUTPUT_OVERSIZED_IMAGE_CARD_DATA_URL) {\n state.remainingOpaqueBytes = 0;\n return value;\n }\n const bytes = Buffer.byteLength(value, \"utf8\");\n if (bytes <= state.remainingOpaqueBytes) {\n state.remainingOpaqueBytes -= bytes;\n return value;\n }\n state.remainingOpaqueBytes = 0;\n if (kind === \"image\") {\n state.opaqueOmissions += 1;\n return MODEL_TOOL_OUTPUT_OVERSIZED_IMAGE_CARD_DATA_URL;\n }\n const marker = `[OpenGeni omitted ${kind} payload: ${bytes} bytes exceeded the bounded model-input allowance]`;\n state.opaqueOmissions += 1;\n state.lastOpaqueOmissionMarker = marker;\n return marker;\n}\n\nfunction nonTextProtocolKind(value: unknown): OpaqueProtocolKind | null {\n if (value === \"image\" || value === \"input_image\" || value === \"computer_screenshot\") {\n return \"image\";\n }\n if (value === \"file\" || value === \"input_file\") return \"file\";\n if (value === \"encrypted_content\") return \"encrypted\";\n return null;\n}\n\nfunction opaqueKindForChild(\n kind: OpaqueProtocolKind | null,\n key: string,\n): OpaqueProtocolKind | null {\n if (!kind) return null;\n const opaqueKeys =\n kind === \"image\"\n ? [\"image\", \"image_url\", \"imageUrl\", \"file_id\", \"fileId\", \"id\", \"data\", \"url\", \"source\"]\n : kind === \"file\"\n ? [\n \"file\",\n \"file_data\",\n \"fileData\",\n \"file_url\",\n \"fileUrl\",\n \"file_id\",\n \"fileId\",\n \"id\",\n \"data\",\n \"url\",\n \"content\",\n \"source\",\n ]\n : [\"encrypted_content\", \"content\", \"data\"];\n return opaqueKeys.includes(key) ? kind : null;\n}\n\nfunction structuredEntriesOmissionMarker(count: number, container: \"array\" | \"object\"): string {\n return `[OpenGeni omitted ${count} structured ${container === \"array\" ? \"array items\" : \"object properties\"}]`;\n}\n\nfunction typedProtocolTextMarker(text: string): Record<string, unknown> {\n return { type: \"input_text\", text };\n}\n\nfunction typedStructuredArrayOmissionMarker(count: number): Record<string, unknown> {\n return typedProtocolTextMarker(structuredEntriesOmissionMarker(count, \"array\"));\n}\n\nfunction isTypedStructuralArrayOmissionMarker(value: unknown): boolean {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const record = value as Record<string, unknown>;\n return (\n record.type === \"input_text\" &&\n typeof record.text === \"string\" &&\n STRUCTURAL_ENTRIES_OMISSION_MARKER.test(record.text) &&\n record.text.includes(\"structured array items\")\n );\n}\n\nfunction isGeneratedModelOutputMarker(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n (value === DEPTH_OMISSION_MARKER ||\n value === CYCLE_OMISSION_MARKER ||\n value === STRUCTURAL_STRING_OMISSION_MARKER ||\n TEXT_FIELD_OMISSION_MARKER.test(value) ||\n TEXT_ITEMS_OMISSION_MARKER.test(value) ||\n STRUCTURAL_ENTRIES_OMISSION_MARKER.test(value) ||\n OPAQUE_PAYLOAD_OMISSION_MARKER.test(value))\n );\n}\n\nfunction observeGeneratedMarkerBudget(value: string, state: ModelOutputBoundState): void {\n if (TEXT_FIELD_OMISSION_MARKER.test(value) || TEXT_ITEMS_OMISSION_MARKER.test(value)) {\n state.remaining = 0;\n }\n if (value === STRUCTURAL_STRING_OMISSION_MARKER) state.remainingStructural = 0;\n if (OPAQUE_PAYLOAD_OMISSION_MARKER.test(value)) state.remainingOpaqueBytes = 0;\n}\n\nfunction isGeneratedStructuralMarkerProperty(key: string, value: unknown): boolean {\n return (\n key.startsWith(STRUCTURAL_PROPERTIES_MARKER_KEY) &&\n typeof value === \"string\" &&\n STRUCTURAL_ENTRIES_OMISSION_MARKER.test(value)\n );\n}\n\nfunction uniqueStructuralMarkerKey(record: Record<string, unknown>): string {\n let key = STRUCTURAL_PROPERTIES_MARKER_KEY;\n let suffix = 1;\n while (Object.hasOwn(record, key)) {\n key = `${STRUCTURAL_PROPERTIES_MARKER_KEY}_${suffix}`;\n suffix += 1;\n }\n return key;\n}\n\nfunction isResponsesProtocolContentPrefix(output: unknown[]): boolean {\n if (output.length === 0) return false;\n const retainedPrefixLength = Math.min(output.length, MODEL_TOOL_OUTPUT_MAX_CONTAINER_ENTRIES);\n for (let index = 0; index < retainedPrefixLength; index += 1) {\n const item = output[index];\n if (!item || typeof item !== \"object\" || Array.isArray(item)) return false;\n const record = item as Record<string, unknown>;\n if (record.type === \"input_text\" && typeof record.text === \"string\") continue;\n if (record.type === \"input_image\") continue;\n if (record.type === \"input_file\") continue;\n return false;\n }\n return true;\n}\n\nfunction isImageDataUrl(value: string): boolean {\n return /^data:image\\/[a-z0-9.+-]+;base64,/i.test(value);\n}\n","import { CODEX_CLIENT_VERSION, CODEX_ORIGINATOR, CODEX_RESPONSES_BASE } from \"./constants\";\nimport type { CodexRequestContext, CodexTokenSnapshot } from \"./request-context\";\nimport type { FetchLike } from \"./fetch\";\nimport { pinnedFetch, readJsonBase64Field, readResponseTextBounded } from \"@opengeni/network\";\n\nexport const CODEX_IMAGE_MODEL = \"gpt-image-2.5-sunburst\";\nconst CODEX_IMAGE_RESPONSE_MAX_BYTES = 90 * 1024 * 1024;\nconst CODEX_IMAGE_ERROR_MAX_BYTES = 64 * 1024;\nconst CODEX_IMAGE_MAX_BYTES = 64 * 1024 * 1024;\nconst CODEX_IMAGE_REQUEST_TIMEOUT_MS = 5 * 60_000;\nconst CODEX_IMAGE_MAX_REFERENCES = 5;\n\nconst codexImageFetch: FetchLike = async (input, init) =>\n await pinnedFetch(\n input,\n init,\n {\n environment: \"production\",\n integrationsAllowPrivateNetworkTargets: false,\n },\n {\n label: \"Codex image generation\",\n requireHttpsOutsideLocalTest: true,\n },\n );\n\nexport type CodexGeneratedImage = {\n bytes: Uint8Array;\n declaredMediaType: \"image/png\";\n};\n\nexport type CodexImageReferenceInput = Readonly<{\n mediaType: \"image/png\" | \"image/jpeg\" | \"image/webp\";\n bytes: Uint8Array;\n}>;\n\nexport class CodexImageApiError extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message);\n this.name = \"CodexImageApiError\";\n }\n}\n\nexport class CodexImageRequestTimeoutError extends Error {\n constructor(readonly timeoutMs: number) {\n super(`Codex image generation timed out after ${Math.ceil(timeoutMs / 1_000)} seconds`);\n this.name = \"CodexImageRequestTimeoutError\";\n }\n}\n\n/**\n * Execute Codex's standalone, client-side image tool against the same\n * ChatGPT/Codex account as the owning model turn. Only a definitive 401 is\n * retried, after refreshing auth; ambiguous transport/5xx outcomes are never\n * replayed because an image request may already have incurred work or cost.\n */\nexport async function generateCodexSubscriptionImage(input: {\n prompt: string;\n references?: readonly CodexImageReferenceInput[];\n turnId: string;\n context: Pick<\n CodexRequestContext,\n \"clientVersion\" | \"getToken\" | \"refresh\" | \"beforeProviderDispatch\"\n >;\n abortSignal?: AbortSignal;\n fetch?: FetchLike;\n /** Internal test/host override; one absolute budget covers auth retry and body streaming. */\n requestTimeoutMs?: number;\n}): Promise<CodexGeneratedImage> {\n const fetchImpl = input.fetch ?? codexImageFetch;\n const timeoutMs = input.requestTimeoutMs ?? CODEX_IMAGE_REQUEST_TIMEOUT_MS;\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {\n throw new RangeError(\"Codex image request timeout must be a positive safe integer\");\n }\n const references = input.references ?? [];\n if (references.length > CODEX_IMAGE_MAX_REFERENCES) {\n throw new RangeError(\n `Codex image editing accepts at most ${CODEX_IMAGE_MAX_REFERENCES} images`,\n );\n }\n for (const reference of references) {\n if (reference.bytes.byteLength === 0) throw new Error(\"Codex image reference is empty\");\n }\n const deadline = new AbortController();\n const timer = setTimeout(\n () => deadline.abort(new CodexImageRequestTimeoutError(timeoutMs)),\n timeoutMs,\n );\n const signal = input.abortSignal\n ? AbortSignal.any([input.abortSignal, deadline.signal])\n : deadline.signal;\n const request = async (auth: CodexTokenSnapshot): Promise<Response> => {\n const headers = codexImageHeaders(auth, input.context.clientVersion, input.turnId);\n await input.context.beforeProviderDispatch?.();\n return await fetchImpl(\n `${CODEX_RESPONSES_BASE}/${references.length > 0 ? \"images/edits\" : \"images/generations\"}`,\n {\n method: \"POST\",\n redirect: \"error\",\n headers,\n body: JSON.stringify(\n references.length > 0\n ? {\n images: references.map((reference) => ({\n image_url: `data:${reference.mediaType};base64,${Buffer.from(reference.bytes).toString(\"base64\")}`,\n })),\n prompt: input.prompt,\n background: \"auto\",\n model: CODEX_IMAGE_MODEL,\n quality: \"auto\",\n size: \"auto\",\n }\n : {\n prompt: input.prompt,\n background: \"auto\",\n model: CODEX_IMAGE_MODEL,\n quality: \"auto\",\n size: \"auto\",\n },\n ),\n signal,\n },\n );\n };\n\n const operation = (async (): Promise<CodexGeneratedImage> => {\n let response = await request(await input.context.getToken());\n if (response.status === 401) {\n await response.body?.cancel().catch(() => undefined);\n response = await request(await input.context.refresh());\n }\n if (!response.ok) {\n const detail = await readResponseTextBounded(\n response,\n CODEX_IMAGE_ERROR_MAX_BYTES,\n \"Codex image error\",\n { signal },\n ).catch(() => \"\");\n throw new CodexImageApiError(\n response.status,\n detail\n ? `Codex image generation failed (${response.status}): ${boundedErrorMessage(detail)}`\n : `Codex image generation failed (${response.status})`,\n );\n }\n\n const bytes = await readJsonBase64Field(response, {\n fieldName: \"b64_json\",\n shape: \"string\",\n maxResponseBytes: CODEX_IMAGE_RESPONSE_MAX_BYTES,\n maxDecodedBytes: CODEX_IMAGE_MAX_BYTES,\n label: \"Codex image generation\",\n signal,\n });\n return { bytes, declaredMediaType: \"image/png\" };\n })();\n let removeAbortListener = (): void => undefined;\n const aborted = new Promise<never>((_resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n if (signal.aborted) {\n onAbort();\n return;\n }\n signal.addEventListener(\"abort\", onAbort, { once: true });\n removeAbortListener = () => signal.removeEventListener(\"abort\", onAbort);\n });\n try {\n // The race is the backstop for credential resolvers and injected transports\n // that do not observe AbortSignal. Promise.race attaches a rejection handler\n // to the losing operation, so it cannot become an unhandled rejection.\n return await Promise.race([operation, aborted]);\n } finally {\n removeAbortListener();\n clearTimeout(timer);\n }\n}\n\nfunction codexImageHeaders(\n auth: CodexTokenSnapshot,\n clientVersion: string,\n turnId: string,\n): Headers {\n const headers = new Headers({\n Authorization: `Bearer ${auth.accessToken}`,\n accept: \"application/json\",\n \"content-type\": \"application/json\",\n originator: CODEX_ORIGINATOR,\n \"User-Agent\": `${CODEX_ORIGINATOR}/${clientVersion || CODEX_CLIENT_VERSION}`,\n version: clientVersion || CODEX_CLIENT_VERSION,\n \"x-codex-image-turn-id\": turnId,\n });\n if (auth.chatgptAccountId) headers.set(\"ChatGPT-Account-ID\", auth.chatgptAccountId);\n if (auth.isFedramp) headers.set(\"X-OpenAI-Fedramp\", \"true\");\n return headers;\n}\n\nfunction boundedErrorMessage(body: string): string {\n let message = body;\n try {\n const value = JSON.parse(body) as {\n error?: { message?: unknown };\n message?: unknown;\n };\n const candidate = value.error?.message ?? value.message;\n if (typeof candidate === \"string\") message = candidate;\n } catch {\n // Preserve a bounded non-JSON provider diagnostic.\n }\n return message.replace(/\\s+/g, \" \").trim().slice(0, 1_000);\n}\n","import { codexSubscriptionHeaders, type CodexAuthHeaders } from \"./api-client\";\nimport {\n CODEX_REALTIME_CALL_TIMEOUT_MS,\n CODEX_REALTIME_CONFIG_ID,\n CODEX_REALTIME_CONFIG_TIMEOUT_MS,\n CODEX_REALTIME_DEFAULT_VOICE,\n CODEX_REALTIME_MODEL,\n CODEX_REALTIME_PROVIDER_ARCHITECTURE_FALLBACK,\n CODEX_REALTIME_PROVIDER_MODEL_FALLBACK,\n CODEX_REALTIME_VERSION,\n CODEX_RESPONSES_BASE,\n CODEX_WHAM_BASE,\n} from \"./constants\";\nimport type { CodexFetch } from \"./device-code\";\nimport {\n CODEX_REALTIME_INITIAL_ITEMS_MAX_COUNT,\n CODEX_REALTIME_INITIAL_ITEMS_MAX_TOKENS,\n type CodexRealtimeInitialItem,\n} from \"./realtime-v3\";\n\nconst MAX_REALTIME_SDP_BYTES = 1024 * 1024;\nconst MAX_REALTIME_PROVIDER_VALUE_LENGTH = 128;\nconst REALTIME_PROVIDER_VALUE = /^[a-z0-9][a-z0-9._-]*$/i;\nconst REALTIME_CALL_ID =\n /^(?:rtc_.+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;\n\nexport const CODEX_REALTIME_VOICES = [\n \"juniper\",\n \"maple\",\n \"spruce\",\n \"ember\",\n \"vale\",\n \"breeze\",\n \"arbor\",\n \"sol\",\n \"cove\",\n] as const;\n\nexport type CodexRealtimeVoice = (typeof CODEX_REALTIME_VOICES)[number];\n\nexport type CodexRealtimeCallInput = {\n /** Browser-created WebRTC offer. It must negotiate an audio media section. */\n sdp: string;\n /** This transport intentionally supports only Codex's Frameless/V3 protocol. */\n version: typeof CODEX_REALTIME_VERSION;\n /** Server-owned session/thread binding; sent upstream but never returned. */\n sessionId: string;\n /** Server-projected ordinary-session history for Frameless V3 bootstrap. */\n initialItems?: CodexRealtimeInitialItem[] | undefined;\n instructions?: string | undefined;\n voice?: CodexRealtimeVoice | undefined;\n};\n\nexport type CodexRealtimeCallResult = {\n sdp: string;\n version: typeof CODEX_REALTIME_VERSION;\n model: typeof CODEX_REALTIME_MODEL;\n};\n\nexport type CodexRealtimeErrorCode =\n | \"invalid_request\"\n | \"incompatible\"\n | \"authentication\"\n | \"entitlement\"\n | \"rate_limited\"\n | \"provider\"\n | \"invalid_response\"\n | \"network\"\n | \"timeout\"\n | \"cancelled\";\n\n/** Safe provider failure: it contains no response body, credential, or account identity. */\nexport class CodexRealtimeError extends Error {\n constructor(\n readonly code: CodexRealtimeErrorCode,\n message: string,\n readonly providerStatus: number | null = null,\n ) {\n super(message);\n this.name = \"CodexRealtimeError\";\n }\n}\n\nexport type CodexRealtimeCallOptions = {\n signal?: AbortSignal | undefined;\n timeoutMs?: number | undefined;\n providerConfig?: CodexRealtimeProviderConfig | undefined;\n};\n\nexport type CodexRealtimeProviderConfig = {\n architecture: string;\n model: string;\n version: typeof CODEX_REALTIME_VERSION;\n};\n\nconst FALLBACK_REALTIME_PROVIDER_CONFIG: CodexRealtimeProviderConfig = {\n architecture: CODEX_REALTIME_PROVIDER_ARCHITECTURE_FALLBACK,\n model: CODEX_REALTIME_PROVIDER_MODEL_FALLBACK,\n version: CODEX_REALTIME_VERSION,\n};\n\n/**\n * Resolve the provider-controlled Codex voice model without changing the\n * stable OpenGeni model id. ChatGPT rotates this config independently of Codex\n * releases; pinning the old value caused deterministic call-creation failures.\n */\nexport async function fetchCodexRealtimeProviderConfig(\n auth: CodexAuthHeaders,\n fetchImpl: CodexFetch = fetch,\n options: {\n signal?: AbortSignal | undefined;\n timeoutMs?: number | undefined;\n } = {},\n): Promise<CodexRealtimeProviderConfig> {\n if (options.signal?.aborted) {\n throw new CodexRealtimeError(\"cancelled\", \"Codex realtime request cancelled\");\n }\n const controller = new AbortController();\n const timeoutMs = options.timeoutMs ?? CODEX_REALTIME_CONFIG_TIMEOUT_MS;\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n const onAbort = (): void => controller.abort(options.signal?.reason);\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n try {\n const response = await fetchImpl(`${CODEX_WHAM_BASE}/wham/statsig/bootstrap`, {\n method: \"POST\",\n headers: {\n ...codexSubscriptionHeaders(auth),\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n app_session_id: crypto.randomUUID(),\n app_version: auth.clientVersion,\n brand_name: \"Codex\",\n build_flavor: \"stable\",\n locale: \"en-US\",\n stable_id: auth.chatgptAccountId ?? \"opengeni-server\",\n system_name: \"OpenGeni\",\n system_version: \"server\",\n window_type: \"local\",\n }),\n signal: controller.signal,\n });\n if (response.status === 401) {\n await response.body?.cancel().catch(() => undefined);\n throw new CodexRealtimeError(\n \"authentication\",\n \"Codex subscription rejected authentication\",\n response.status,\n );\n }\n if (!response.ok) {\n await response.body?.cancel().catch(() => undefined);\n return FALLBACK_REALTIME_PROVIDER_CONFIG;\n }\n const outer = (await response.json().catch(() => null)) as {\n statsigPayload?: unknown;\n } | null;\n if (typeof outer?.statsigPayload !== \"string\") return FALLBACK_REALTIME_PROVIDER_CONFIG;\n const payload = JSON.parse(outer.statsigPayload) as {\n dynamic_configs?: Record<string, { value?: Record<string, unknown> }>;\n };\n const value = payload.dynamic_configs?.[CODEX_REALTIME_CONFIG_ID]?.value;\n const version = value?.version;\n if (version !== undefined && version !== CODEX_REALTIME_VERSION) {\n throw new CodexRealtimeError(\n \"incompatible\",\n `Codex realtime remote configuration requires ${String(version)}`,\n );\n }\n const architecture = validProviderValue(value?.architecture)\n ? value.architecture\n : FALLBACK_REALTIME_PROVIDER_CONFIG.architecture;\n const model = validProviderValue(value?.model)\n ? value.model\n : FALLBACK_REALTIME_PROVIDER_CONFIG.model;\n return { architecture, model, version: CODEX_REALTIME_VERSION };\n } catch (error) {\n if (error instanceof CodexRealtimeError) throw error;\n if (options.signal?.aborted) {\n throw new CodexRealtimeError(\"cancelled\", \"Codex realtime request cancelled\");\n }\n return FALLBACK_REALTIME_PROVIDER_CONFIG;\n } finally {\n clearTimeout(timeout);\n options.signal?.removeEventListener(\"abort\", onAbort);\n }\n}\n\n/**\n * Create one native subscription-authenticated Codex GPT-Live V3 WebRTC call.\n *\n * There is deliberately no API-key or WebSocket fallback and no transport\n * retry. A caller may refresh the same connected subscription after one 401,\n * but this adapter always performs exactly one provider request.\n */\nexport async function createCodexRealtimeCall(\n auth: CodexAuthHeaders,\n input: CodexRealtimeCallInput,\n fetchImpl: CodexFetch = fetch,\n options: CodexRealtimeCallOptions = {},\n): Promise<CodexRealtimeCallResult> {\n validateRealtimeInput(input);\n const timeoutMs = options.timeoutMs ?? CODEX_REALTIME_CALL_TIMEOUT_MS;\n const providerConfig = options.providerConfig ?? FALLBACK_REALTIME_PROVIDER_CONFIG;\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime timeout must be positive\");\n }\n if (options.signal?.aborted) {\n throw new CodexRealtimeError(\"cancelled\", \"Codex realtime request cancelled\");\n }\n if (providerConfig.version !== CODEX_REALTIME_VERSION) {\n throw new CodexRealtimeError(\n \"incompatible\",\n `Codex realtime provider configuration requires ${providerConfig.version}`,\n );\n }\n if (\n !validProviderValue(providerConfig.architecture) ||\n !validProviderValue(providerConfig.model)\n ) {\n throw new CodexRealtimeError(\n \"invalid_request\",\n \"Codex realtime provider configuration is invalid\",\n );\n }\n\n const controller = new AbortController();\n let timedOut = false;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let rejectCancellation: ((error: CodexRealtimeError) => void) | undefined;\n const cancellation = new Promise<never>((_resolve, reject) => {\n rejectCancellation = reject;\n });\n const onAbort = (): void => {\n controller.abort(options.signal?.reason);\n rejectCancellation?.(new CodexRealtimeError(\"cancelled\", \"Codex realtime request cancelled\"));\n };\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n const deadline = new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(() => {\n timedOut = true;\n controller.abort();\n reject(new CodexRealtimeError(\"timeout\", \"Codex realtime request timed out\"));\n }, timeoutMs);\n });\n\n const request = (async (): Promise<CodexRealtimeCallResult> => {\n const response = await fetchImpl(\n `${CODEX_RESPONSES_BASE}/realtime/calls?intent=quicksilver&architecture=${encodeURIComponent(providerConfig.architecture)}`,\n {\n method: \"POST\",\n headers: {\n ...codexSubscriptionHeaders(auth),\n \"content-type\": \"application/json\",\n \"openai-alpha\": \"quicksilver=v2\",\n \"session-id\": input.sessionId,\n \"thread-id\": input.sessionId,\n },\n body: JSON.stringify({\n sdp: input.sdp,\n session: {\n instructions: input.instructions ?? \"\",\n audio: {\n output: { voice: input.voice ?? CODEX_REALTIME_DEFAULT_VOICE },\n },\n delegation: { type: \"client\" },\n model: providerConfig.model,\n ...(input.initialItems?.length\n ? {\n initial_items: input.initialItems.map((item) => ({\n type: \"message\",\n role: item.role,\n content: [\n {\n type: item.role === \"assistant\" ? \"output_text\" : \"input_text\",\n text: item.text,\n },\n ],\n })),\n }\n : {}),\n },\n }),\n signal: controller.signal,\n },\n );\n\n if (!response.ok) {\n await response.body?.cancel().catch(() => undefined);\n throw providerHttpError(response.status);\n }\n const location = response.headers.get(\"location\");\n if (!location || !validRealtimeLocation(location)) {\n await response.body?.cancel().catch(() => undefined);\n throw new CodexRealtimeError(\n \"invalid_response\",\n \"Codex realtime response did not identify a compatible call\",\n response.status,\n );\n }\n const sdp = await readBoundedSdp(response);\n if (!isAudioSdp(sdp)) {\n throw new CodexRealtimeError(\n \"invalid_response\",\n \"Codex realtime response was not an audio SDP answer\",\n response.status,\n );\n }\n return {\n sdp,\n version: CODEX_REALTIME_VERSION,\n model: CODEX_REALTIME_MODEL,\n };\n })();\n\n try {\n // Promise.race attaches rejection handlers to every branch, so a custom\n // fetch that ignores AbortSignal cannot produce a late unhandled rejection.\n return await Promise.race([request, cancellation, deadline]);\n } catch (error) {\n if (error instanceof CodexRealtimeError) throw error;\n if (options.signal?.aborted) {\n throw new CodexRealtimeError(\"cancelled\", \"Codex realtime request cancelled\");\n }\n if (timedOut || controller.signal.aborted) {\n throw new CodexRealtimeError(\"timeout\", \"Codex realtime request timed out\");\n }\n throw new CodexRealtimeError(\"network\", \"Codex realtime provider request failed\");\n } finally {\n if (timeout) clearTimeout(timeout);\n options.signal?.removeEventListener(\"abort\", onAbort);\n }\n}\n\nfunction validProviderValue(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length <= MAX_REALTIME_PROVIDER_VALUE_LENGTH &&\n REALTIME_PROVIDER_VALUE.test(value)\n );\n}\n\n/** Shared pin→active selection for worker turns and direct realtime calls. */\nexport function selectCodexCredentialId(args: {\n sessionPinnedCredentialId: string | null;\n activeCredentialId: string | null;\n connectedIds: ReadonlySet<string>;\n}): string | null {\n if (args.sessionPinnedCredentialId && args.connectedIds.has(args.sessionPinnedCredentialId)) {\n return args.sessionPinnedCredentialId;\n }\n if (args.activeCredentialId && args.connectedIds.has(args.activeCredentialId)) {\n return args.activeCredentialId;\n }\n return null;\n}\n\nfunction validateRealtimeInput(input: CodexRealtimeCallInput): void {\n if (input.version !== CODEX_REALTIME_VERSION) {\n throw new CodexRealtimeError(\n \"incompatible\",\n `Codex realtime requires ${CODEX_REALTIME_VERSION}`,\n );\n }\n if (!input.sessionId || input.sessionId.length > 128) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime session id is invalid\");\n }\n if (new TextEncoder().encode(input.sdp).byteLength > MAX_REALTIME_SDP_BYTES) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime SDP offer is too large\");\n }\n if (!isAudioSdp(input.sdp)) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime requires an audio SDP offer\");\n }\n if (input.voice !== undefined && !CODEX_REALTIME_VOICES.includes(input.voice)) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime voice is unsupported\");\n }\n const initialItems = input.initialItems ?? [];\n if (initialItems.length > CODEX_REALTIME_INITIAL_ITEMS_MAX_COUNT) {\n throw new CodexRealtimeError(\n \"invalid_request\",\n `Codex realtime history exceeds ${CODEX_REALTIME_INITIAL_ITEMS_MAX_COUNT} items`,\n );\n }\n let estimatedTokens = 0;\n for (const item of initialItems) {\n if (\n (item.role !== \"user\" && item.role !== \"developer\" && item.role !== \"assistant\") ||\n typeof item.text !== \"string\"\n ) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime history item is invalid\");\n }\n const itemTokens = Math.ceil(new TextEncoder().encode(item.text).byteLength / 4);\n if (itemTokens > CODEX_REALTIME_INITIAL_ITEMS_MAX_TOKENS) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime history item is too large\");\n }\n estimatedTokens += itemTokens;\n }\n if (estimatedTokens > CODEX_REALTIME_INITIAL_ITEMS_MAX_TOKENS) {\n throw new CodexRealtimeError(\"invalid_request\", \"Codex realtime history is too large\");\n }\n}\n\nfunction providerHttpError(status: number): CodexRealtimeError {\n if (status === 401) {\n return new CodexRealtimeError(\n \"authentication\",\n \"Codex subscription rejected authentication\",\n status,\n );\n }\n if (status === 403) {\n return new CodexRealtimeError(\n \"entitlement\",\n \"Codex subscription lacks realtime entitlement\",\n status,\n );\n }\n if (status === 404) {\n return new CodexRealtimeError(\n \"incompatible\",\n \"Codex subscription realtime is unavailable\",\n status,\n );\n }\n if (status === 429) {\n return new CodexRealtimeError(\"rate_limited\", \"Codex realtime is rate limited\", status);\n }\n return new CodexRealtimeError(\"provider\", \"Codex realtime provider request failed\", status);\n}\n\nfunction validRealtimeLocation(location: string): boolean {\n const path = location.split(\"?\", 1)[0] ?? \"\";\n const segment = path.split(\"/\").filter(Boolean).at(-1) ?? \"\";\n return REALTIME_CALL_ID.test(segment);\n}\n\nfunction isAudioSdp(sdp: string): boolean {\n return /^v=0(?:\\r?\\n)/.test(sdp) && /(?:^|\\r?\\n)m=audio\\s/m.test(sdp);\n}\n\nasync function readBoundedSdp(response: Response): Promise<string> {\n const declared = Number(response.headers.get(\"content-length\"));\n if (Number.isFinite(declared) && declared > MAX_REALTIME_SDP_BYTES) {\n await response.body?.cancel().catch(() => undefined);\n throw new CodexRealtimeError(\n \"invalid_response\",\n \"Codex realtime SDP answer is too large\",\n response.status,\n );\n }\n if (!response.body) return \"\";\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n while (true) {\n const next = await reader.read();\n if (next.done) break;\n total += next.value.byteLength;\n if (total > MAX_REALTIME_SDP_BYTES) {\n await reader.cancel();\n throw new CodexRealtimeError(\n \"invalid_response\",\n \"Codex realtime SDP answer is too large\",\n response.status,\n );\n }\n chunks.push(next.value);\n }\n } finally {\n reader.releaseLock();\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n try {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n throw new CodexRealtimeError(\n \"invalid_response\",\n \"Codex realtime SDP answer was not valid UTF-8\",\n response.status,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYO,SAAS,mBAAmB,OAA2C;AAC5E,SAAO,OAAO,UAAU,YAAY,MAAM,WAAW,qBAAqB;AAC5E;;;ACcO,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAGA,eAAsB,gBAAgB,YAAwB,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