Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

test(openai-codex): cover auth binding, 401 refresh, /models discovery

Jack Rudenkoacf5e5425768
diff --git a/packages/cli/src/adapters/codex-api-format.test.ts b/packages/cli/src/adapters/codex-api-format.test.ts
new file mode 100644
index 00000000..7be2ca23
--- /dev/null
+++ b/packages/cli/src/adapters/codex-api-format.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { CodexAPIFormat } from "./codex-api-format.js";
+
+const capture: {
+ model: string;
+ instructions: string;
+ max_output_tokens: number;
+ input: Array<{ type: string; role: string; content: Array<{ type: string; text: string }> }>;
+} = JSON.parse(
+ readFileSync(
+ new URL("../test-fixtures/code-mode/claude-code-request-body.json", import.meta.url),
+ "utf8"
+ )
+);
+// Derived structural Claude Code inputs from the captured outbound request:
+// instructions become system text; input_text becomes a Claude Code text block.
+const messages = capture.input
+ .filter((item) => item.type === "message" && item.role === "user")
+ .slice(0, 1)
+ .map((item) => ({
+ role: item.role,
+ content: item.content
+ .filter((block) => block.type === "input_text")
+ .map((block) => ({ type: "text", text: block.text })),
+ }));
+const notice = "IMPORTANT: You are NOT Claude."; // Contract: implementation-log.md C1 identity notice.
+
+describe("T5 Codex instructions identity filtering", () => {
+ test("REQ-8 TEST-9 string instructions contain the identity notice and the original captured text", () => {
+ // Use captured prose paragraphs, not the full persona's identity claim or
+ // its three-newline formatting (whitespace normalization is not specified).
+ const original = capture.instructions
+ .split(/\n{2,}/)
+ .slice(1, 3)
+ .join("\n\n");
+ const payload = new CodexAPIFormat(capture.model).buildPayload(
+ { system: original, max_tokens: capture.max_output_tokens, messages },
+ messages,
+ []
+ );
+
+ expect(typeof payload.instructions).toBe("string");
+ expect(payload.instructions).toContain(notice);
+ expect(payload.instructions).toContain(original);
+ expect(payload.instructions.indexOf(notice)).toBeLessThan(
+ payload.instructions.indexOf(original)
+ );
+ });
+
+ test("REQ-8 TEST-10 block-array instructions join the original text with two newlines after the notice", () => {
+ const parts: string[] = capture.instructions.split(/\n{2,}/).slice(1, 4);
+ expect(parts).toHaveLength(3);
+ const system = parts.map((text) => ({ type: "text", text }));
+ const payload = new CodexAPIFormat(capture.model).buildPayload(
+ { system, max_tokens: capture.max_output_tokens, messages },
+ messages,
+ []
+ );
+
+ expect(typeof payload.instructions).toBe("string");
+ expect(payload.instructions).toContain(notice);
+ expect(payload.instructions).toContain(parts.join("\n\n"));
+ expect(payload.instructions).not.toContain("[object Object]");
+ });
+});
diff --git a/packages/cli/src/handlers/composed-handler-codex-auth.test.ts b/packages/cli/src/handlers/composed-handler-codex-auth.test.ts
new file mode 100644
index 00000000..c01590a1
--- /dev/null
+++ b/packages/cli/src/handlers/composed-handler-codex-auth.test.ts
@@ -0,0 +1,228 @@
+import { afterEach, describe, expect, spyOn, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import type { Context } from "hono";
+import { CodexAPIFormat } from "../adapters/codex-api-format.js";
+import type { CredentialArm } from "../auth/credentials/types.js";
+import type { AuthBinding, ProviderTransport } from "../providers/transport/types.js";
+import { ComposedHandler } from "./composed-handler.js";
+import { type LegAuthBinding, isSameCredentialSilo } from "./shared/responses-leg-issuer.js";
+
+const capture: {
+ model: string;
+ max_output_tokens: number;
+ input: Array<{ type: string; role: string; content: Array<{ type: string; text: string }> }>;
+} = JSON.parse(
+ readFileSync(
+ new URL("../test-fixtures/code-mode/claude-code-request-body.json", import.meta.url),
+ "utf8"
+ )
+);
+// Derived structural inbound messages from the real outbound request's input_text blocks.
+// This is not a new protocol capture; source: test-fixtures/code-mode/claude-code-request-body.json.
+function request() {
+ return {
+ model: capture.model,
+ max_tokens: capture.max_output_tokens,
+ stream: false,
+ messages: capture.input
+ .filter((item) => item.type === "message" && item.role === "user")
+ .slice(0, 1)
+ .map((item) => ({
+ role: item.role,
+ content: item.content
+ .filter((block) => block.type === "input_text")
+ .map((block) => ({ type: "text", text: block.text })),
+ })),
+ };
+}
+function binding(
+ account: string,
+ token: string,
+ endpoint: string,
+ arm: CredentialArm | undefined = "oauth"
+): AuthBinding {
+ return {
+ auth: {
+ arm,
+ endpoint,
+ headers: { Authorization: `Bearer ${token}`, "chatgpt-account-id": account },
+ },
+ };
+}
+function context(): Context {
+ return {
+ req: {
+ header: (name?: string) =>
+ name === undefined ? {} : name === "x-claudish-no-recovery" ? "1" : undefined,
+ },
+ header() {},
+ body: (body: BodyInit | null, init?: ResponseInit) => new Response(body, init),
+ json: (body: unknown, status = 200) =>
+ new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json" },
+ }),
+ } as unknown as Context;
+}
+function transport(initial: AuthBinding, refreshed: () => Promise<AuthBinding>): ProviderTransport {
+ return {
+ name: "openai-codex",
+ displayName: "OpenAI Codex",
+ streamFormat: "openai-responses-sse",
+ refreshAuth: async () => initial,
+ forceRefreshAuth: refreshed,
+ getEndpoint: (_model, bound) => bound?.auth?.endpoint ?? "https://unbound.invalid/responses",
+ getHeaders: async (_request, bound) => bound?.auth?.headers ?? {},
+ } as ProviderTransport;
+}
+function handler(t: ProviderTransport) {
+ return new ComposedHandler(t, `cx@${capture.model}`, capture.model, 0, {
+ codeMode: "off",
+ adapter: new CodexAPIFormat(capture.model),
+ });
+}
+const realFetch = globalThis.fetch;
+afterEach(() => {
+ globalThis.fetch = realFetch;
+});
+
+function upstream(statuses: number[]) {
+ const sent: Array<{ endpoint: string; authorization: string | null; account: string | null }> =
+ [];
+ globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
+ const headers = new Headers(init?.headers);
+ sent.push({
+ endpoint: String(url),
+ authorization: headers.get("authorization"),
+ account: headers.get("chatgpt-account-id"),
+ });
+ const status = statuses.shift();
+ if (status === undefined) throw new Error("unexpected additional outgoing request");
+ // Status-only upstream failures: no hand-crafted Responses/SSE body.
+ return new Response(null, { status });
+ }) as typeof fetch;
+ return sent;
+}
+
+describe("T5 primary-request OAuth 401 behavior", () => {
+ test("REQ-2 TEST-4 recomputes endpoint and headers from a same-account refresh", async () => {
+ const a = binding("account-a", "TOKEN_OLD", "https://old.invalid/codex/responses");
+ const fresh = binding("account-a", "TOKEN_NEW", "https://new.invalid/codex/responses");
+ const sent = upstream([401, 503]);
+ const h = handler(transport(a, async () => fresh));
+ try {
+ const response = await h.handle(context(), request());
+
+ expect(response.status).toBe(503);
+ expect(sent).toEqual([
+ { endpoint: a.auth!.endpoint!, authorization: "Bearer TOKEN_OLD", account: "account-a" },
+ {
+ endpoint: fresh.auth!.endpoint!,
+ authorization: "Bearer TOKEN_NEW",
+ account: "account-a",
+ },
+ ]);
+ } finally {
+ await h.shutdown();
+ }
+ });
+
+ test("REQ-5 REQ-6 TEST-5 answers 401 not resent when refresh changes account", async () => {
+ const a = binding("account-a", "TOKEN_A", "https://a.invalid/codex/responses");
+ const b = binding("account-b", "TOKEN_B", "https://b.invalid/codex/responses");
+ const sent = upstream([401]);
+ const h = handler(transport(a, async () => b));
+ const logs: string[] = [];
+ const stderr = spyOn(process.stderr, "write").mockImplementation(((chunk: unknown) => {
+ logs.push(String(chunk));
+ return true;
+ }) as typeof process.stderr.write);
+ try {
+ const response = await h.handle(context(), request());
+ const body = await response.text();
+
+ expect(response.status).toBe(401);
+ expect(body).toContain("Codex sign-in changed during the request; it was not resent");
+ expect(sent).toEqual([
+ { endpoint: a.auth!.endpoint!, authorization: "Bearer TOKEN_A", account: "account-a" },
+ ]);
+ // R2-6 specifies this stderr summary; the separate `Not resent:` line
+ // is a debug-log seam, not a promise about stderr's formatting.
+ expect(logs.join("\n")).toContain(
+ "HTTP 401; the sign-in changed to another account during the request, so it was not resent."
+ );
+ expect(logs.join("\n")).not.toContain("HTTP 401 after auth retry");
+ } finally {
+ stderr.mockRestore();
+ await h.shutdown();
+ }
+ });
+
+ test.each(["api-key", undefined] as const)(
+ "REQ-3 TEST-6 a request with arm %s never attempts forced OAuth refresh",
+ async (arm) => {
+ // Explicitly assign arm so undefined does not take binding()'s OAuth default.
+ const initial = binding("account-a", "API_KEY", "https://key.invalid/v1/responses");
+ initial.auth!.arm = arm;
+ const sent = upstream([401]);
+ const h = handler(
+ transport(initial, async () =>
+ binding("account-b", "OAUTH_TOKEN", "https://b.invalid/codex/responses")
+ )
+ );
+ try {
+ const response = await h.handle(context(), request());
+
+ // The ordinary terminal-auth path is remapped to 400 by the supplied
+ // project invariant; retain the actual 401 in the error envelope.
+ const body = (await response.json()) as {
+ error: { upstream_status: number; message: string };
+ };
+ expect(response.status).toBe(400);
+ expect(body.error.upstream_status).toBe(401);
+ expect(sent).toHaveLength(1);
+ expect(body.error.message).not.toContain("sign-in changed");
+ } finally {
+ await h.shutdown();
+ }
+ }
+ );
+
+ test("REQ-7 TEST-7 classifies a refresh connection fault instead of inventing a 401", async () => {
+ const sent = upstream([401]);
+ // Structural error input from Bun's documented connection vocabulary; never a real socket.
+ const error = Object.assign(
+ new TypeError("Unable to connect. Is the computer able to access the url?"),
+ { code: "ConnectionRefused" }
+ );
+ const h = handler(
+ transport(binding("account-a", "TOKEN_A", "https://a.invalid/codex/responses"), async () => {
+ throw error;
+ })
+ );
+ try {
+ const response = await h.handle(context(), request());
+ const body = (await response.json()) as { error: { type: string } };
+
+ expect(response.status).not.toBe(401);
+ expect(response.status).toBe(400);
+ expect(body.error.type).toBe("connection_error");
+ expect(sent).toHaveLength(1);
+ } finally {
+ await h.shutdown();
+ }
+ });
+});
+
+describe("T5 public credential-silo predicate", () => {
+ const oauth = (accountKey: string): LegAuthBinding => ({ auth: { arm: "oauth" }, accountKey });
+ test.each([
+ ["same OAuth account", oauth("account-a"), oauth("account-a"), true],
+ ["different OAuth account", oauth("account-a"), oauth("account-b"), false],
+ ["OAuth to api-key", oauth("account-a"), { auth: { arm: "api-key" } }, false],
+ ["api-key to OAuth", { auth: { arm: "api-key" } }, oauth("account-a"), false],
+ ["same api-key arm", { auth: { arm: "api-key" } }, { auth: { arm: "api-key" } }, true],
+ ] as const)("REQ-5 TEST-8 %s returns %s", (_name, a, b, same) => {
+ expect(isSameCredentialSilo(a, b)).toBe(same);
+ });
+});
diff --git a/packages/cli/src/profile-config-code-mode.test.ts b/packages/cli/src/profile-config-code-mode.test.ts
new file mode 100644
index 00000000..f9dbb27c
--- /dev/null
+++ b/packages/cli/src/profile-config-code-mode.test.ts
@@ -0,0 +1,91 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { parseArgs } from "./cli.js";
+import { setConfigFileOverride } from "./config-override.js";
+import { loadConfig, readCodeMode, saveConfig } from "./profile-config.js";
+
+let dir: string;
+let file: string;
+let previousSetting: string | undefined;
+const realFetch = globalThis.fetch;
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "claudish-t5-code-mode-"));
+ file = join(dir, "config.json");
+ setConfigFileOverride(file);
+ previousSetting = process.env.CLAUDISH_CODE_MODE;
+ delete process.env.CLAUDISH_CODE_MODE;
+ globalThis.fetch = (async () => {
+ throw new Error("T5 forbids network access");
+ }) as unknown as typeof fetch;
+ writeFileSync(file, JSON.stringify({ profiles: {}, apiKeys: {} }));
+});
+afterEach(() => {
+ globalThis.fetch = realFetch;
+ if (previousSetting === undefined) delete process.env.CLAUDISH_CODE_MODE;
+ else process.env.CLAUDISH_CODE_MODE = previousSetting;
+ setConfigFileOverride(null);
+ rmSync(dir, { recursive: true, force: true });
+});
+const args = ["--model", "[email protected]", "--stdin", "--quiet"];
+
+describe("T5 code-mode configuration", () => {
+ test.each(["auto", "on", "off"] as const)(
+ "REQ-16 TEST-23 --code-mode %s beats conflicting environment and profile settings",
+ async (setting) => {
+ writeFileSync(file, JSON.stringify({ codeMode: setting === "off" ? "on" : "off" }));
+ process.env.CLAUDISH_CODE_MODE = setting === "auto" ? "off" : "auto";
+
+ const config = await parseArgs([...args, "--code-mode", setting]);
+
+ expect(config.codeMode).toBe(setting);
+ expect(config.claudeArgs).not.toContain("--code-mode");
+ }
+ );
+
+ test("REQ-16 TEST-24 environment setting beats the conflicting profile setting", async () => {
+ writeFileSync(file, JSON.stringify({ codeMode: "on" }));
+ process.env.CLAUDISH_CODE_MODE = "off";
+
+ expect((await parseArgs(args)).codeMode).toBe("off");
+ });
+
+ test("REQ-16 TEST-25 the profile setting is used without a flag or environment override", async () => {
+ writeFileSync(file, JSON.stringify({ codeMode: "auto" }));
+
+ expect((await parseArgs(args)).codeMode).toBe("auto");
+ });
+
+ test("REQ-16 TEST-26 an absent setting defaults to off", async () => {
+ expect((await parseArgs(args)).codeMode).toBe("off");
+ });
+
+ test.each(["auto", "on", "off"] as const)(
+ "REQ-17 TEST-27 loadConfig/saveConfig preserves codeMode %s through repeated round trips",
+ (setting) => {
+ writeFileSync(file, JSON.stringify({ codeMode: setting }));
+
+ for (let cycle = 0; cycle < 3; cycle++) saveConfig(loadConfig());
+
+ expect(loadConfig().codeMode).toBe(setting);
+ expect(JSON.parse(readFileSync(file, "utf8")).codeMode).toBe(setting);
+ }
+ );
+
+ test("REQ-18 TEST-28 a project setting overrides the global setting through injected paths", () => {
+ const project = join(dir, ".claudish.json");
+ writeFileSync(file, JSON.stringify({ codeMode: "off" }));
+ writeFileSync(project, JSON.stringify({ codeMode: "on" }));
+
+ expect(readCodeMode({ global: () => file, project: () => project })).toBe("on");
+ });
+
+ test("REQ-18 TEST-29 a project with no codeMode falls back to the global setting", () => {
+ const project = join(dir, ".claudish.json");
+ writeFileSync(file, JSON.stringify({ codeMode: "auto" }));
+ writeFileSync(project, "{}");
+
+ expect(readCodeMode({ global: () => file, project: () => project })).toBe("auto");
+ });
+});
diff --git a/packages/cli/src/providers/codex-models-discovery.test.ts b/packages/cli/src/providers/codex-models-discovery.test.ts
new file mode 100644
index 00000000..2f1b2d4f
--- /dev/null
+++ b/packages/cli/src/providers/codex-models-discovery.test.ts
@@ -0,0 +1,296 @@
+import { afterEach, beforeEach, describe, expect, jest, test } from "bun:test";
+import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ type CodexDiscoveryOptions,
+ clearCodexModelsMemo,
+ codexModelsUrl,
+ getCodexModelInfo,
+} from "./codex-models-discovery.js";
+import type { AuthBinding } from "./transport/types.js";
+
+const capturedBytes = readFileSync(
+ new URL("../test-fixtures/code-mode/codex-models-response.json", import.meta.url),
+ "utf8"
+);
+const captured: {
+ models: Array<{
+ slug: string;
+ tool_mode?: string;
+ use_responses_lite?: boolean;
+ default_reasoning_level?: string;
+ default_verbosity?: string;
+ truncation_policy?: { mode: string; limit: number };
+ }>;
+} = JSON.parse(capturedBytes);
+const sol = captured.models.find((model) => model.slug === "gpt-6.1-sol");
+if (!sol) throw new Error("real /models capture must contain gpt-6.1-sol");
+const expected = {
+ slug: sol.slug,
+ toolMode: sol.tool_mode,
+ useResponsesLite: sol.use_responses_lite,
+ defaultReasoningLevel: sol.default_reasoning_level,
+ defaultVerbosity: sol.default_verbosity,
+ truncationPolicy: sol.truncation_policy,
+};
+let home: string;
+const realFetch = globalThis.fetch;
+beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), "claudish-t5-discovery-"));
+ clearCodexModelsMemo();
+ globalThis.fetch = (async () => {
+ throw new Error("T5 forbids network access");
+ }) as unknown as typeof fetch;
+});
+afterEach(() => {
+ jest.useRealTimers();
+ clearCodexModelsMemo();
+ globalThis.fetch = realFetch;
+ rmSync(home, { recursive: true, force: true });
+});
+function binding(
+ account = "account-a",
+ endpoint = "https://chatgpt.com/backend-api/codex/responses"
+): AuthBinding {
+ return {
+ auth: {
+ arm: "oauth",
+ endpoint,
+ headers: { Authorization: "Bearer TOKEN", "chatgpt-account-id": account },
+ },
+ };
+}
+function capturedResponse() {
+ return new Response(capturedBytes, { headers: { "content-type": "application/json" } });
+}
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+async function flushMicrotasks() {
+ for (let n = 0; n < 12; n++) await Promise.resolve();
+}
+function options(
+ fetchImpl: CodexDiscoveryOptions["fetchImpl"],
+ extra: Partial<CodexDiscoveryOptions> = {}
+): CodexDiscoveryOptions {
+ return { codexHome: home, fetchImpl, now: () => 1000, ...extra };
+}
+
+describe("T5 Codex /models discovery", () => {
+ test("REQ-9 TEST-11 translates captured gpt-6.1-sol metadata and matches slugs case-insensitively", async () => {
+ const opts = options((async () => capturedResponse()) as unknown as typeof fetch);
+
+ const info = await getCodexModelInfo("GPT-6.1-SOL", binding(), "key-a", opts);
+
+ // Concrete values are pinned to the evidence, not model data from memory.
+ expect(sol.tool_mode).toBe("code_mode_only");
+ expect(sol.use_responses_lite).toBe(true);
+ expect(sol.truncation_policy).toEqual({ mode: "tokens", limit: 10000 });
+ expect(info).toEqual(expected);
+ });
+
+ test("REQ-10 TEST-12 concurrent lookups share one outgoing fetch", async () => {
+ const response = deferred<Response>();
+ const started = deferred<void>();
+ const sent: string[] = [];
+ const opts = options((async (url: string | URL | Request) => {
+ sent.push(String(url));
+ started.resolve();
+ return response.promise;
+ }) as typeof fetch);
+
+ const first = getCodexModelInfo(sol.slug, binding(), "key-a", opts);
+ const second = getCodexModelInfo(sol.slug.toUpperCase(), binding(), "key-a", opts);
+ await started.promise;
+ response.resolve(capturedResponse());
+ const results = await Promise.all([first, second]);
+
+ expect(sent).toHaveLength(1);
+ expect(results).toEqual([expected, expected]);
+ });
+
+ test("REQ-10 TEST-13 memo is scoped to the account rather than the model or process", async () => {
+ const sent: string[] = [];
+ const opts = options((async (_url, init) => {
+ sent.push(new Headers(init?.headers).get("chatgpt-account-id")!);
+ return capturedResponse();
+ }) as typeof fetch);
+
+ expect(await getCodexModelInfo(sol.slug, binding("account-a"), "key-a", opts)).toEqual(
+ expected
+ );
+ expect(await getCodexModelInfo(sol.slug, binding("account-b"), "key-b", opts)).toEqual(
+ expected
+ );
+ expect(await getCodexModelInfo(sol.slug, binding("account-a"), "key-a", opts)).toEqual(
+ expected
+ );
+ expect(sent).toEqual(["account-a", "account-b"]);
+ });
+
+ test("REQ-11 TEST-14 returns undefined for a slug absent from the captured body", async () => {
+ expect(
+ await getCodexModelInfo(
+ "t5-does-not-exist",
+ binding(),
+ "key-a",
+ options((async () => capturedResponse()) as unknown as typeof fetch)
+ )
+ ).toBeUndefined();
+ });
+
+ test("REQ-11 TEST-15 resolves undefined when fetch throws and no fallback cache exists", async () => {
+ const opts = options((async () => {
+ throw new TypeError("discovery unavailable");
+ }) as unknown as typeof fetch);
+
+ await expect(getCodexModelInfo(sol.slug, binding(), "key-a", opts)).resolves.toBeUndefined();
+ expect(readdirSync(home)).toEqual([]);
+ });
+
+ test("REQ-12 TEST-16 derives the models URL and sends this binding's headers plus JSON accept", async () => {
+ const auth = binding("account-a", "https://edge.invalid/account/codex/responses");
+ const sent: Array<{ url: URL; headers: Headers; signal: AbortSignal | null | undefined }> = [];
+ const opts = options((async (url, init) => {
+ sent.push({
+ url: new URL(String(url)),
+ headers: new Headers(init?.headers),
+ signal: init?.signal,
+ });
+ return capturedResponse();
+ }) as typeof fetch);
+
+ expect(codexModelsUrl(auth, "0.161.0")).toBe(
+ "https://edge.invalid/account/codex/models?client_version=0.161.0"
+ );
+ expect(await getCodexModelInfo(sol.slug, auth, "key-a", opts)).toEqual(expected);
+ expect(sent).toHaveLength(1);
+ expect(sent[0]!.url.origin).toBe("https://edge.invalid");
+ expect(sent[0]!.url.pathname).toBe("/account/codex/models");
+ expect(sent[0]!.url.searchParams.get("client_version")).toBeTruthy();
+ expect(sent[0]!.headers.get("authorization")).toBe("Bearer TOKEN");
+ expect(sent[0]!.headers.get("chatgpt-account-id")).toBe("account-a");
+ expect(sent[0]!.headers.get("accept")).toBe("application/json");
+ expect(sent[0]!.signal).toBeInstanceOf(AbortSignal);
+ });
+
+ test("REQ-11 REQ-12 TEST-17 unsupported endpoint returns unknown without sending discovery", async () => {
+ const sent: string[] = [];
+ const auth = binding("account-a", "https://edge.invalid/chat/completions");
+ const opts = options((async (url) => {
+ sent.push(String(url));
+ return capturedResponse();
+ }) as typeof fetch);
+
+ expect(codexModelsUrl(auth, "0.161.0")).toBeUndefined();
+ expect(await getCodexModelInfo(sol.slug, auth, "key-a", opts)).toBeUndefined();
+ expect(sent).toEqual([]);
+ });
+
+ test("REQ-13 TEST-18 refetches only after the one-hour memo TTL expires", async () => {
+ let now = 1000;
+ const sent: number[] = [];
+ const opts = options(
+ (async () => {
+ sent.push(now);
+ return capturedResponse();
+ }) as unknown as typeof fetch,
+ { now: () => now }
+ );
+
+ expect(await getCodexModelInfo(sol.slug, binding(), "key-a", opts)).toEqual(expected);
+ now += 3_600_000 - 1;
+ expect(await getCodexModelInfo(sol.slug, binding(), "key-a", opts)).toEqual(expected);
+ expect(sent).toHaveLength(1);
+ now += 2;
+ expect(await getCodexModelInfo(sol.slug, binding(), "key-a", opts)).toEqual(expected);
+ expect(sent).toHaveLength(2);
+ });
+
+ test("REQ-13 TEST-19 a failed expired refetch retains the last good answer", async () => {
+ let now = 1000;
+ const sent: number[] = [];
+ const opts = options(
+ (async () => {
+ sent.push(now);
+ if (sent.length > 1) throw new TypeError("refetch unavailable");
+ return capturedResponse();
+ }) as unknown as typeof fetch,
+ { now: () => now }
+ );
+ expect(await getCodexModelInfo(sol.slug, binding(), "key-a", opts)).toEqual(expected);
+
+ now += 3_600_001;
+ expect(await getCodexModelInfo(sol.slug, binding(), "key-a", opts)).toEqual(expected);
+ await flushMicrotasks();
+ expect(sent).toHaveLength(2);
+ expect(await getCodexModelInfo(sol.slug, binding(), "key-a", opts)).toEqual(expected);
+ });
+
+ test("REQ-14 TEST-20 stops waiting at two seconds and later reuses the background result", async () => {
+ jest.useFakeTimers();
+ const response = deferred<Response>();
+ const started = deferred<void>();
+ const sent: string[] = [];
+ const opts = options((async (url) => {
+ sent.push(String(url));
+ started.resolve();
+ return response.promise;
+ }) as typeof fetch);
+ let settled = false;
+ const lookup = getCodexModelInfo(sol.slug, binding(), "key-a", opts).then((info) => {
+ settled = true;
+ return info;
+ });
+ await started.promise;
+ await flushMicrotasks();
+
+ jest.advanceTimersByTime(1999);
+ await flushMicrotasks();
+ expect(settled).toBe(false);
+ jest.advanceTimersByTime(1);
+ await expect(lookup).resolves.toBeUndefined();
+ response.resolve(capturedResponse());
+ await flushMicrotasks();
+
+ expect(await getCodexModelInfo(sol.slug, binding(), "key-a", opts)).toEqual(expected);
+ expect(sent).toHaveLength(1);
+ });
+
+ test("REQ-15 TEST-21 reads an injected models cache without changing any of its bytes", async () => {
+ const cacheFile = join(home, "models_cache.json");
+ // Derived cache envelope, not a protocol capture: models are copied unchanged
+ // from codex-models-response.json; timestamp/client_version are cache metadata.
+ const cacheBytes = JSON.stringify({
+ fetched_at: new Date().toISOString(),
+ client_version: "0.161.0",
+ models: captured.models,
+ });
+ writeFileSync(cacheFile, cacheBytes);
+ const before = readdirSync(home);
+ const opts = options((async () => {
+ throw new TypeError("offline");
+ }) as unknown as typeof fetch);
+
+ expect(await getCodexModelInfo(sol.slug, binding(), "key-a", opts)).toEqual(expected);
+ expect(readFileSync(cacheFile, "utf8")).toBe(cacheBytes);
+ expect(readdirSync(home)).toEqual(before);
+ });
+
+ test("REQ-15 TEST-22 successful discovery never persists models to the injected home", async () => {
+ expect(
+ await getCodexModelInfo(
+ sol.slug,
+ binding(),
+ "key-a",
+ options((async () => capturedResponse()) as unknown as typeof fetch)
+ )
+ ).toEqual(expected);
+ expect(readdirSync(home)).toEqual([]);
+ });
+});
diff --git a/packages/cli/src/providers/transport/openai-codex.test.ts b/packages/cli/src/providers/transport/openai-codex.test.ts
new file mode 100644
index 00000000..3a3cf294
--- /dev/null
+++ b/packages/cli/src/providers/transport/openai-codex.test.ts
@@ -0,0 +1,168 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { clearSignedArm } from "../../auth/credentials/billing-probe.js";
+import type { RequestAuth } from "../../auth/credentials/types.js";
+import type { RemoteProvider } from "../../handlers/shared/remote-provider-types.js";
+import { type CodexOAuthRefresher, OpenAICodexTransport } from "./openai-codex.js";
+import type { AuthBinding } from "./types.js";
+
+const provider: RemoteProvider = {
+ name: "openai-codex",
+ baseUrl: "https://api.openai.com",
+ apiPath: "/v1/responses",
+ apiKeyEnvVar: "OPENAI_CODEX_API_KEY",
+ prefixes: ["cx@", "codex@"],
+};
+const capture = JSON.parse(
+ readFileSync(
+ new URL("../../test-fixtures/code-mode/claude-code-request-body.json", import.meta.url),
+ "utf8"
+ )
+);
+const realFetch = globalThis.fetch;
+afterEach(() => {
+ globalThis.fetch = realFetch;
+ clearSignedArm("openai-codex");
+});
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+function auth(account: string, token: string, endpoint: string): RequestAuth {
+ return {
+ arm: "oauth",
+ endpoint,
+ headers: { Authorization: `Bearer ${token}`, "chatgpt-account-id": account },
+ // Derived request transform: same store/include fields as the real request capture.
+ transformPayload: (payload) => ({ ...payload, store: capture.store, include: capture.include }),
+ };
+}
+function noNetwork() {
+ globalThis.fetch = (async () => {
+ throw new Error("T5 forbids network access");
+ }) as unknown as typeof fetch;
+}
+
+describe("T5 request-scoped Codex auth bindings", () => {
+ test("REQ-1 TEST-1 keeps the first request's endpoint and headers after an overlapping refresh", async () => {
+ noNetwork();
+ const a: AuthBinding = {
+ auth: auth("account-a", "TOKEN_A", "https://a.invalid/codex/responses"),
+ };
+ const b = {
+ ...auth("account-b", "TOKEN_B", "https://b.invalid/codex/responses"),
+ transformPayload: undefined,
+ };
+ const refreshEntered = deferred<void>();
+ const refreshDone = deferred<void>();
+ const refresher: CodexOAuthRefresher = {
+ async refreshToken() {
+ refreshEntered.resolve();
+ await refreshDone.promise;
+ },
+ async mintOAuthAuth() {
+ return b;
+ },
+ };
+ const transport = new OpenAICodexTransport(provider, capture.model, "API_KEY", refresher);
+ const firstCanSign = deferred<void>();
+ const firstRequest = (async () => {
+ await firstCanSign.promise;
+ return {
+ endpoint: transport.getEndpoint(capture.model, a),
+ headers: new Headers(await transport.getHeaders(undefined, a)),
+ payload: transport.transformPayload(
+ (() => {
+ // Remove captured OAuth fields so only A's transform can supply them.
+ const payload = structuredClone(capture);
+ delete payload.store;
+ delete payload.include;
+ return payload;
+ })(),
+ undefined,
+ a
+ ),
+ };
+ })();
+
+ const secondRefresh = transport.forceRefreshAuth();
+ await refreshEntered.promise;
+ refreshDone.resolve();
+ const secondBinding = await secondRefresh;
+ firstCanSign.resolve();
+ const first = await firstRequest;
+
+ expect(first.endpoint).toBe(a.auth!.endpoint!);
+ expect(first.headers.get("authorization")).toBe("Bearer TOKEN_A");
+ expect(first.headers.get("chatgpt-account-id")).toBe("account-a");
+ expect(first.payload.store).toBe(capture.store);
+ expect(first.payload.include).toEqual(capture.include);
+ expect(transport.getEndpoint(capture.model, secondBinding)).toBe(b.endpoint!);
+ expect(
+ new Headers(await transport.getHeaders(undefined, secondBinding)).get("authorization")
+ ).toBe("Bearer TOKEN_B");
+ });
+
+ test("REQ-1 REQ-3 TEST-2 an explicit null binding stays on the api-key path after OAuth refresh", async () => {
+ noNetwork();
+ const transport = new OpenAICodexTransport(provider, capture.model, "API_KEY", {
+ async refreshToken() {},
+ async mintOAuthAuth() {
+ return auth("account-a", "OAUTH_TOKEN", "https://a.invalid/codex/responses");
+ },
+ });
+ await transport.forceRefreshAuth();
+
+ const binding: AuthBinding = { auth: null };
+ const headers = new Headers(await transport.getHeaders(undefined, binding));
+ // Derived from the captured request; remove OAuth-only fields before testing the base transform.
+ const payload = structuredClone(capture);
+ delete payload.store;
+ delete payload.include;
+ const transformed = transport.transformPayload(payload, undefined, binding);
+
+ expect(transport.getEndpoint(capture.model, binding)).toBe(
+ "https://api.openai.com/v1/responses"
+ );
+ expect(headers.get("authorization")).toBe("Bearer API_KEY");
+ expect(headers.get("chatgpt-account-id")).toBeNull();
+ expect(transformed.store).toBeUndefined();
+ expect(transformed.include).toBeUndefined();
+ });
+
+ test("REQ-7 TEST-3 rethrows the identical connection failure from the injected refresher", async () => {
+ noNetwork();
+ // Error test data, not protocol data. Bun's connection vocabulary is already documented
+ // by composed-handler-connection-error.test.ts; no socket or OAuth singleton is touched.
+ const error = Object.assign(
+ new TypeError("Unable to connect. Is the computer able to access the url?"),
+ { code: "ConnectionRefused" }
+ );
+ const transport = new OpenAICodexTransport(provider, capture.model, "API_KEY", {
+ async refreshToken() {
+ throw error;
+ },
+ async mintOAuthAuth() {
+ throw new Error("must not mint after failed rotation");
+ },
+ });
+
+ await expect(transport.forceRefreshAuth()).rejects.toBe(error);
+ });
+
+ test("REQ-3 forced refresh cannot substitute an api-key artifact when OAuth minting returns null", async () => {
+ noNetwork();
+ const transport = new OpenAICodexTransport(provider, capture.model, "API_KEY", {
+ async refreshToken() {},
+ async mintOAuthAuth() {
+ return null;
+ },
+ });
+
+ expect(await transport.forceRefreshAuth()).toEqual({ auth: null });
+ });
+});