The Open Framework for Building Agents
feat(eve): add `experimental_chatgpt` model support (#515)
Ruic8f00aaec6c0
diff --git a/.changeset/codex-transport-core.md b/.changeset/codex-transport-core.mdnew file mode 100644index 000000000..6b0fcac4e--- /dev/null+++ b/.changeset/codex-transport-core.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add `experimental_chatgpt` under the new `eve/models/openai` subpath: it returns an AI SDK language model served through the local Codex login (`codex login`), billed to the ChatGPT subscription, and defaults to `gpt-5.6-sol`. Direct provider API request errors now also surface their upstream message when one is available.diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.mdindex 26db699ed..665482501 100644--- a/docs/reference/typescript-api.md+++ b/docs/reference/typescript-api.md@@ -86,6 +86,7 @@ A few non-`define*` helpers round out the set: `disableTool` and `ExperimentalWo| `eve/context` | `defineState`, session and state types || `eve/sandbox` | `defineSandbox`, backends || `eve/instrumentation` | `defineInstrumentation`, `isChannel` |+| `eve/models/openai` | `experimental_chatgpt` || `eve/evals` | `defineEval`, `defineEvalConfig`, `mockModel`, eval types || `eve/evals/expect` | `includes`, `equals`, `matches`, `similarity` || `eve/evals/reporters` | `Braintrust`, `JUnit`, `EvalReporter` |@@ -96,6 +97,22 @@ A few non-`define*` helpers round out the set: `disableTool` and `ExperimentalWoExported types ship from the same entrypoint as the helper they describe (for example `ToolDefinition` and `ToolContext` from `eve/tools`). For the exhaustive list, read `packages/eve/src/public/index.ts`.+## ChatGPT subscription models++`experimental_chatgpt()` from `eve/models/openai` serves an OpenAI model through the local Codex login and bills the ChatGPT subscription. With no argument, it selects `gpt-5.6-sol`:++```ts title="agent/agent.ts"+import { defineAgent } from "eve";+import { experimental_chatgpt } from "eve/models/openai";++export default defineAgent({+ model: experimental_chatgpt(),+ modelContextWindowTokens: 200_000,+});+```++Pass another bare OpenAI model slug to override the default. The helper reads credentials from `codex login`, so use it only where that local login exists.+## What to read next- [`agent.ts`](../agent-config): the agent config these helpers configurediff --git a/packages/eve/package.json b/packages/eve/package.jsonindex 715436a17..6ef3d95bc 100644--- a/packages/eve/package.json+++ b/packages/eve/package.json@@ -111,6 +111,11 @@"import": "./dist/src/public/tools/defaults.js","default": "./dist/src/public/tools/defaults.js"},+ "./models/openai": {+ "types": "./dist/src/public/models/openai/index.d.ts",+ "import": "./dist/src/public/models/openai/index.js",+ "default": "./dist/src/public/models/openai/index.js"+ },"./connections": {"types": "./dist/src/public/connections/index.d.ts","import": "./dist/src/public/connections/index.js",diff --git a/packages/eve/src/harness/model-call-error.test.ts b/packages/eve/src/harness/model-call-error.test.tsindex 3976180f8..116626df4 100644--- a/packages/eve/src/harness/model-call-error.test.ts+++ b/packages/eve/src/harness/model-call-error.test.ts@@ -80,6 +80,21 @@ function gatewayModelCallError(input: {return error;}+function directApiCallError(input: {+ readonly data?: Record<string, unknown>;+ readonly message?: string;+ readonly responseBody?: string;+ readonly statusCode?: number;+}): Error {+ return Object.assign(new Error(input.message ?? "AI_APICallError"), {+ data: input.data,+ isRetryable: false,+ name: "AI_APICallError",+ responseBody: input.responseBody,+ statusCode: input.statusCode,+ });+}+describe("isNoOutputGeneratedError", () => {it("matches the AI SDK error by name", () => {expect(isNoOutputGeneratedError(noOutputGeneratedError())).toBe(true);@@ -300,6 +315,100 @@ describe("summarizeKnownModelCallRequestError", () => {message: "AI Gateway rejected the model request before the agent produced a response.",});});++ it("uses nested OpenAI error.code messages when the top-level API message is generic", () => {+ const data = {+ error: {+ code: { message: "The requested model does not support this tool." },+ message: "AI_APICallError",+ type: "invalid_request_error",+ },+ };+ const summary = summarizeKnownModelCallRequestError(+ directApiCallError({+ data,+ responseBody: JSON.stringify(data),+ statusCode: 400,+ }),+ );++ expect(summary).toEqual({+ name: "Model provider API error",+ message: "The requested model does not support this tool.",+ });+ });++ it("uses the direct API error message when there is no response body", () => {+ const summary = summarizeKnownModelCallRequestError(+ directApiCallError({+ message: "No endpoints found for anthropic/claude-3.5-haiku",+ statusCode: 404,+ }),+ );++ expect(summary).toEqual({+ name: "Model provider API error",+ message: "No endpoints found for anthropic/claude-3.5-haiku",+ });+ });++ it("falls back to HTTP status and response body for direct generic API call errors", () => {+ const responseBody = JSON.stringify({+ error: {+ message: "AI_APICallError",+ type: "invalid_request_error",+ },+ });+ const summary = summarizeKnownModelCallRequestError(+ directApiCallError({+ responseBody,+ statusCode: 400,+ }),+ );++ expect(summary).toEqual({+ name: "Model provider API error",+ message: `Model provider API request failed (HTTP 400, invalid_request_error): ${responseBody}`,+ });+ });++ it("does not promote bare parameter names from the error body to the summary", () => {+ const data = {+ error: {+ message: "Bad Request",+ type: "invalid_request_error",+ param: "input",+ },+ };+ const summary = summarizeKnownModelCallRequestError(+ directApiCallError({+ data,+ responseBody: JSON.stringify(data),+ statusCode: 400,+ }),+ );++ expect(summary?.message).not.toBe("input");+ expect(summary?.message).toContain("Model provider API request failed (HTTP 400");+ });++ it("keeps the generic framing for transient upstream failures", () => {+ // A 503/429 that exhausts retries is an availability problem, not a+ // request rejection; summarizing it as "rejected" sends users to debug+ // their configuration.+ const summary = summarizeKnownModelCallRequestError(+ gatewayModelCallError({+ gatewayName: "GatewayInternalServerError",+ gatewayType: "overloaded_error",+ statusCode: 503,+ upstreamMessage: "Service temporarily unavailable",+ upstreamStatusCode: 503,+ upstreamType: "overloaded_error",+ }),+ );++ expect(summary).toBeNull();+ });});/**@@ -507,4 +616,24 @@ describe("extractModelCallErrorDetails", () => {});expect(JSON.stringify(details)).not.toContain("large schema");});++ it("keeps direct API response snippets when no parsed API message is useful", () => {+ const responseBody = JSON.stringify({+ error: { message: "AI_APICallError", type: "invalid_request_error" },+ });+ const details = extractModelCallErrorDetails(+ directApiCallError({+ responseBody,+ statusCode: 400,+ }),+ );++ expect(details).toMatchObject({+ responseBodySnippet: responseBody,+ statusCode: 400,+ upstreamMessage: "AI_APICallError",+ upstreamStatusCode: 400,+ upstreamType: "invalid_request_error",+ });+ });});diff --git a/packages/eve/src/harness/model-call-error.ts b/packages/eve/src/harness/model-call-error.tsindex 848790008..540006b77 100644--- a/packages/eve/src/harness/model-call-error.ts+++ b/packages/eve/src/harness/model-call-error.ts@@ -4,6 +4,7 @@ import { toError } from "#shared/errors.js";import { isTurnCancellation } from "#harness/turn-cancellation.js";const RESPONSE_BODY_SNIPPET_LIMIT = 1_000;+const API_ERROR_SUMMARY_LIMIT = 800;const GATEWAY_MODEL_REQUEST_REJECTED_MESSAGE ="AI Gateway rejected the model request before the agent produced a response.";@@ -48,6 +49,8 @@ export interface ModelCallConfigErrorSummary {}interface ModelCallErrorSignals {+ readonly apiCallError: boolean;+ readonly apiErrorMessage?: string;readonly gatewayName?: string;readonly gatewayType?: string;readonly generationId?: string;@@ -130,6 +133,23 @@ export function summarizeKnownModelCallRequestError(const signals = readModelCallErrorSignals(error);+ // Transient upstream failures (throttles, overloads) keep the generic+ // retry-exhausted framing; a summary here would read as a terminal+ // rejection and send users to debug their configuration.+ if (isTransientHttpStatus(signals.statusCode ?? signals.upstreamStatusCode)) {+ return null;+ }++ const apiSummary = signals.apiErrorMessage;+ if (apiSummary !== undefined) {+ return {+ name: isGatewayErrorSignal(signals)+ ? "AI Gateway model request rejected"+ : "Model provider API error",+ message: apiSummary,+ };+ }+if (signals.statusCode === 400 && isGatewayErrorSignal(signals)) {return {name: "AI Gateway model request rejected",@@ -137,9 +157,23 @@ export function summarizeKnownModelCallRequestError(};}+ const apiCallSummary = formatApiCallErrorFallback(signals);+ if (apiCallSummary !== undefined) {+ return {+ name: isGatewayErrorSignal(signals)+ ? "AI Gateway model request rejected"+ : "Model provider API error",+ message: apiCallSummary,+ };+ }+return null;}+function isTransientHttpStatus(status: number | undefined): boolean {+ return status === 408 || status === 429 || (status !== undefined && status >= 500);+}+/*** Returns the distinct upstream tool types referenced by any* "tool type 'X' is not supported" rejection in an AI Gateway error's@@ -216,6 +250,7 @@ export function extractModelCallErrorDetails(error: unknown): JsonObject {const signals = readModelCallErrorSignals(error);const details: Record<string, JsonValue> = {};+ appendJsonField(details, "apiErrorMessage", signals.apiErrorMessage);appendJsonField(details, "gatewayName", signals.gatewayName);appendJsonField(details, "gatewayType", signals.gatewayType);appendJsonField(details, "statusCode", signals.statusCode);@@ -395,6 +430,10 @@ function readModelCallErrorSignals(error: unknown): ModelCallErrorSignals {const upstreamBody = readGatewayErrorBody(upstreamError);return {+ apiCallError: upstreamError !== undefined,+ apiErrorMessage:+ upstreamBody?.apiErrorMessage ??+ firstInformativeApiMessage([readErrorMessage(upstreamError)]),gatewayName: readErrorName(gatewayError),gatewayType: readStringField(gatewayError, "type"),generationId: readStringField(gatewayError, "generationId") ?? upstreamBody?.generationId,@@ -438,6 +477,7 @@ function findUpstreamApiCallError(error: unknown): unknown {function readGatewayErrorBody(error: unknown):| {+ readonly apiErrorMessage?: string;readonly generationId?: string;readonly message?: string;readonly type?: string;@@ -462,6 +502,7 @@ function readGatewayErrorBody(error: unknown):function readGatewayErrorBodyFromValue(value: unknown):| {+ readonly apiErrorMessage?: string;readonly generationId?: string;readonly message?: string;readonly type?: string;@@ -469,13 +510,20 @@ function readGatewayErrorBodyFromValue(value: unknown):| undefined {if (!isObject(value)) return undefined;const error = readObjectField(value, "error");- if (error === undefined) return undefined;const generationId = readStringField(value, "generationId");- const message = readStringField(error, "message");- const type = readStringField(error, "type");- return message === undefined && type === undefined && generationId === undefined+ const message = readStringField(error, "message") ?? readStringField(value, "message");+ const type = readStringField(error, "type") ?? readStringField(value, "type");+ const apiErrorMessage = firstInformativeApiMessage([+ message,+ ...readNestedApiErrorMessages(error),+ ...readNestedApiErrorMessages(value),+ ]);+ return message === undefined &&+ type === undefined &&+ generationId === undefined &&+ apiErrorMessage === undefined? undefined- : { generationId, message, type };+ : { apiErrorMessage, generationId, message, type };}function readStatusCode(error: unknown): number | undefined {@@ -505,6 +553,78 @@ function readObjectField(value: unknown, key: string): Record<string, unknown> |return isObject(field) ? field : undefined;}+function readNestedApiErrorMessages(value: unknown): readonly string[] {+ if (!isObject(value)) return [];+ const messages: string[] = [];+ appendString(messages, readStringField(value, "message"));+ appendString(messages, readStringField(value, "error_description"));+ appendNestedApiFieldMessages(messages, value.error);+ // `code` can carry a structured rejection ({ message }) on OpenAI-shaped+ // bodies. `param` and `status` never hold prose - promoting them surfaced+ // bare field names ("input") as the user-facing error.+ appendNestedApiFieldMessages(messages, value.code);++ return messages;+}++function appendNestedApiFieldMessages(out: string[], value: unknown): void {+ if (typeof value === "string") {+ appendString(out, value);+ return;+ }+ if (!isObject(value)) return;+ appendString(out, readStringField(value, "message"));+ appendString(out, readStringField(value, "error"));+ appendString(out, readStringField(value, "description"));+ appendString(out, readStringField(value, "error_description"));+ appendNestedApiFieldMessages(out, value.error);+}++function appendString(out: string[], value: string | undefined): void {+ if (value !== undefined) out.push(value);+}++function firstInformativeApiMessage(messages: readonly (string | undefined)[]): string | undefined {+ for (const message of messages) {+ if (message !== undefined && isInformativeApiMessage(message)) {+ return truncateSnippet(message, API_ERROR_SUMMARY_LIMIT);+ }+ }+ return undefined;+}++function isInformativeApiMessage(message: string): boolean {+ const normalized = message.trim();+ return (+ normalized.length > 0 &&+ normalized !== "[object Object]" &&+ normalized !== "AI_APICallError" &&+ normalized !== "Bad Request" &&+ normalized !== "Internal Server Error"+ );+}++function formatApiCallErrorFallback(signals: ModelCallErrorSignals): string | undefined {+ if (!signals.apiCallError) return undefined;+ const status = signals.statusCode ?? signals.upstreamStatusCode;+ const body = signals.responseBodySnippet;+ const type =+ signals.upstreamType !== undefined && isInformativeApiMessage(signals.upstreamType)+ ? signals.upstreamType+ : undefined;+ if (status === undefined && body === undefined && type === undefined) {+ return undefined;+ }+ const qualifiers = [status === undefined ? undefined : `HTTP ${status}`, type]+ .filter((part): part is string => part !== undefined)+ .join(", ");+ const prefix =+ qualifiers.length === 0+ ? "Model provider API request failed"+ : `Model provider API request failed (${qualifiers})`;+ return body === undefined ? `${prefix}.` : `${prefix}: ${body}`;+}+function isRetryableGatewayType(type: string | undefined): boolean {return type === "overloaded_error" || type === "rate_limit_exceeded" || type === "timeout_error";}diff --git a/packages/eve/src/public/models/openai/chatgpt/auth.test.ts b/packages/eve/src/public/models/openai/chatgpt/auth.test.tsnew file mode 100644index 000000000..2b58e0db0--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/auth.test.ts@@ -0,0 +1,147 @@+import { describe, expect, it } from "vitest";++import {+ assertCodexAuthStateAuthenticated,+ parseCodexAuth,+ readCodexJwtExpirationMs,+} from "./auth.js";+import { createUnsignedJwt } from "./unsigned-jwt.js";++const PATHS = { authPath: "/home/user/.codex/auth.json", codexHome: "/home/user/.codex" };++describe("Codex auth state", () => {+ it("parses OAuth login state from auth.json without leaking tokens into the state view", () => {+ const { state, credentials } = parseCodexAuth(+ JSON.stringify({+ auth_mode: "chatgpt",+ OPENAI_API_KEY: null,+ tokens: {+ access_token: "access-token",+ account_id: "acct_123",+ id_token: "id-token",+ refresh_token: "refresh-token",+ },+ last_refresh: "2026-06-29T20:00:00.000Z",+ }),+ PATHS,+ );++ expect(state).toEqual({+ kind: "authenticated",+ accountId: "acct_123",+ authMode: "chatgpt",+ authPath: PATHS.authPath,+ codexHome: PATHS.codexHome,+ lastRefresh: "2026-06-29T20:00:00.000Z",+ });+ expect(JSON.stringify(state)).not.toContain("access-token");+ expect(JSON.stringify(state)).not.toContain("refresh-token");+ expect(credentials).toEqual({+ kind: "chatgpt",+ accessToken: "access-token",+ accountId: "acct_123",+ authPath: PATHS.authPath,+ codexHome: PATHS.codexHome,+ idToken: "id-token",+ lastRefresh: "2026-06-29T20:00:00.000Z",+ refreshToken: "refresh-token",+ });+ });++ it("parses API-key login state and credentials", () => {+ const { state, credentials } = parseCodexAuth(+ JSON.stringify({ auth_mode: "api-key", OPENAI_API_KEY: "sk-test" }),+ PATHS,+ );++ expect(state).toEqual({+ kind: "authenticated",+ authMode: "api-key",+ authPath: PATHS.authPath,+ codexHome: PATHS.codexHome,+ });+ expect(credentials).toEqual({+ kind: "api-key",+ apiKey: "sk-test",+ authPath: PATHS.authPath,+ codexHome: PATHS.codexHome,+ });+ });++ it("falls back to the API key when a chatgpt mode marker has no usable tokens", () => {+ // Stale `auth_mode: "chatgpt"` left behind after tokens were cleared must+ // not outrank a usable API key in the same file.+ const { state, credentials } = parseCodexAuth(+ JSON.stringify({ auth_mode: "chatgpt", tokens: {}, OPENAI_API_KEY: "sk-live" }),+ PATHS,+ );++ expect(state).toMatchObject({ kind: "authenticated", authMode: "api-key" });+ expect(credentials).toMatchObject({ kind: "api-key", apiKey: "sk-live" });+ });++ it("honors an explicit api-key mode over residual OAuth tokens", () => {+ // `codex login --api-key` keeps the old tokens block around; the explicit+ // mode marker decides which credential eve uses.+ const { state, credentials } = parseCodexAuth(+ JSON.stringify({+ auth_mode: "api-key",+ OPENAI_API_KEY: "sk-live",+ tokens: { access_token: "stale-access", refresh_token: "stale-refresh" },+ }),+ PATHS,+ );++ expect(state).toMatchObject({ kind: "authenticated", authMode: "api-key" });+ expect(credentials).toMatchObject({ kind: "api-key", apiKey: "sk-live" });+ });++ it("prefers usable OAuth tokens when no explicit mode is set", () => {+ const { state, credentials } = parseCodexAuth(+ JSON.stringify({+ OPENAI_API_KEY: "sk-live",+ tokens: { access_token: "access-token", refresh_token: "refresh-token" },+ }),+ PATHS,+ );++ expect(state).toMatchObject({ kind: "authenticated", authMode: "chatgpt" });+ expect(credentials).toMatchObject({ kind: "chatgpt", accessToken: "access-token" });+ });++ it("reads JWT expiry without exposing token contents", () => {+ const token = createUnsignedJwt({ exp: 1_783_405_980 });++ expect(readCodexJwtExpirationMs(token)).toBe(1_783_405_980_000);+ expect(readCodexJwtExpirationMs("not.jwt")).toBeUndefined();+ });++ it("treats auth.json with no usable credential as missing login state", () => {+ expect(parseCodexAuth(JSON.stringify({ tokens: {} }), PATHS)).toEqual({+ state: {+ kind: "missing",+ authPath: PATHS.authPath,+ codexHome: PATHS.codexHome,+ },+ });+ });++ it("throws an actionable login error for missing or invalid state", () => {+ expect(() =>+ assertCodexAuthStateAuthenticated({+ kind: "missing",+ authPath: PATHS.authPath,+ codexHome: PATHS.codexHome,+ }),+ ).toThrow("codex login");++ expect(() =>+ assertCodexAuthStateAuthenticated({+ kind: "invalid",+ authPath: PATHS.authPath,+ codexHome: PATHS.codexHome,+ reason: "bad json",+ }),+ ).toThrow("could not be read");+ });+});diff --git a/packages/eve/src/public/models/openai/chatgpt/auth.ts b/packages/eve/src/public/models/openai/chatgpt/auth.tsnew file mode 100644index 000000000..5ca7423bb--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/auth.ts@@ -0,0 +1,372 @@+import { readFile, writeFile } from "node:fs/promises";+import { homedir } from "node:os";+import { join } from "node:path";++import { decodeJwt } from "#compiled/jose/index.js";+import { z } from "#compiled/zod/index.js";+import { toErrorMessage } from "#shared/errors.js";+import { isObject } from "#shared/guards.js";++export type CodexAuthMode = "api-key" | "chatgpt";++export type CodexAuthState =+ | {+ readonly kind: "authenticated";+ readonly accountId?: string;+ readonly authMode: CodexAuthMode;+ readonly authPath: string;+ readonly codexHome: string;+ readonly lastRefresh?: string;+ }+ | {+ readonly kind: "missing";+ readonly authPath: string;+ readonly codexHome: string;+ }+ | {+ readonly kind: "invalid";+ readonly authPath: string;+ readonly codexHome: string;+ readonly reason: string;+ };++export interface ReadCodexAuthStateOptions {+ readonly codexHome?: string;+}++export interface CodexApiKeyCredentials {+ readonly apiKey: string;+ readonly authPath: string;+ readonly codexHome: string;+ readonly kind: "api-key";+}++export interface CodexChatGptCredentials {+ readonly accessToken?: string;+ readonly accountId?: string;+ readonly authPath: string;+ readonly codexHome: string;+ readonly idToken?: string;+ readonly kind: "chatgpt";+ readonly lastRefresh?: string;+ readonly refreshToken?: string;+}++export type CodexAuthCredentials = CodexApiKeyCredentials | CodexChatGptCredentials;++/**+ * One read of the Codex login state: the reportable state view plus, when+ * authenticated, the credentials the transport uses. Both views derive from+ * the same parse and the same credential selection, so they cannot disagree.+ */+export interface CodexAuthSnapshot {+ readonly state: CodexAuthState;+ /** Set exactly when `state.kind` is `"authenticated"`. */+ readonly credentials?: CodexAuthCredentials;+}++export interface CodexRefreshedTokens {+ readonly accessToken: string;+ readonly accountId?: string;+ readonly idToken?: string;+ readonly refreshToken: string;+}++const TOKEN_REFRESH_SKEW_MS = 60_000;++const codexAuthTokensSchema = z+ .object({+ access_token: z.string().nullable().optional(),+ account_id: z.string().nullable().optional(),+ id_token: z.string().nullable().optional(),+ refresh_token: z.string().nullable().optional(),+ })+ .passthrough();++const codexAuthFileSchema = z+ .object({+ OPENAI_API_KEY: z.string().nullable().optional(),+ auth_mode: z.string().nullable().optional(),+ last_refresh: z.string().nullable().optional(),+ tokens: codexAuthTokensSchema.nullable().optional(),+ })+ .passthrough();++type CodexAuthFile = z.infer<typeof codexAuthFileSchema>;+type ParsedCodexAuthFile =+ | { readonly kind: "parsed"; readonly value: CodexAuthFile }+ | { readonly kind: "invalid"; readonly reason: string };++export async function readCodexAuth(+ options: ReadCodexAuthStateOptions = {},+): Promise<CodexAuthSnapshot> {+ const codexHome = options.codexHome ?? resolveDefaultCodexHome();+ const authPath = join(codexHome, "auth.json");++ let raw: string;+ try {+ raw = await readFile(authPath, "utf8");+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {+ return { state: { kind: "missing", authPath, codexHome } };+ }+ return {+ state: { kind: "invalid", authPath, codexHome, reason: toErrorMessage(error) },+ };+ }++ return parseCodexAuth(raw, { authPath, codexHome });+}++export async function readCodexAuthCredentials(+ options: ReadCodexAuthStateOptions = {},+): Promise<CodexAuthCredentials> {+ const snapshot = await readCodexAuth(options);+ if (snapshot.credentials !== undefined) {+ return snapshot.credentials;+ }+ assertCodexAuthStateAuthenticated(snapshot.state);+ // Unreachable: parseCodexAuth pairs every authenticated state with credentials.+ throw new Error(+ `Codex login state at ${snapshot.state.authPath} did not include usable credentials.`,+ );+}++export function parseCodexAuth(+ raw: string,+ input: {+ readonly authPath: string;+ readonly codexHome: string;+ },+): CodexAuthSnapshot {+ const parsed = parseCodexAuthFile(raw);+ if (parsed.kind === "invalid") {+ return {+ state: {+ kind: "invalid",+ authPath: input.authPath,+ codexHome: input.codexHome,+ reason: parsed.reason,+ },+ };+ }++ const selection = selectCodexCredentials(parsed.value);+ if (selection.kind === "none") {+ return {+ state: { kind: "missing", authPath: input.authPath, codexHome: input.codexHome },+ };+ }++ if (selection.kind === "api-key") {+ return {+ state: {+ kind: "authenticated",+ authMode: "api-key",+ authPath: input.authPath,+ codexHome: input.codexHome,+ },+ credentials: {+ kind: "api-key",+ apiKey: selection.apiKey,+ authPath: input.authPath,+ codexHome: input.codexHome,+ },+ };+ }++ return {+ state: {+ kind: "authenticated",+ authMode: "chatgpt",+ authPath: input.authPath,+ codexHome: input.codexHome,+ ...(selection.accountId !== undefined && { accountId: selection.accountId }),+ ...(selection.lastRefresh !== undefined && { lastRefresh: selection.lastRefresh }),+ },+ credentials: {+ kind: "chatgpt",+ authPath: input.authPath,+ codexHome: input.codexHome,+ ...(selection.accessToken !== undefined && { accessToken: selection.accessToken }),+ ...(selection.accountId !== undefined && { accountId: selection.accountId }),+ ...(selection.idToken !== undefined && { idToken: selection.idToken }),+ ...(selection.lastRefresh !== undefined && { lastRefresh: selection.lastRefresh }),+ ...(selection.refreshToken !== undefined && { refreshToken: selection.refreshToken }),+ },+ };+}++type CodexCredentialSelection =+ | { readonly kind: "api-key"; readonly apiKey: string }+ | {+ readonly kind: "chatgpt";+ readonly accessToken?: string;+ readonly accountId?: string;+ readonly idToken?: string;+ readonly lastRefresh?: string;+ readonly refreshToken?: string;+ }+ | { readonly kind: "none" };++/**+ * Picks which credential in auth.json is active. An explicit `auth_mode`+ * wins when its credential is usable; otherwise the usable credential the+ * file actually carries wins, ChatGPT tokens first (they are the Codex CLI's+ * primary login). A `tokens` block with no usable token never outranks an+ * API key, and stale tokens never outrank an explicit `auth_mode: "api-key"`.+ */+function selectCodexCredentials(auth: CodexAuthFile): CodexCredentialSelection {+ const apiKey = readNonEmptyString(auth.OPENAI_API_KEY);+ const tokens = auth.tokens ?? undefined;+ const accessToken = readNonEmptyString(tokens?.access_token);+ const refreshToken = readNonEmptyString(tokens?.refresh_token);+ const hasUsableTokens = accessToken !== undefined || refreshToken !== undefined;+ const preferApiKey = auth.auth_mode === "api-key" && apiKey !== undefined;++ if (hasUsableTokens && !preferApiKey) {+ const accountId =+ readNonEmptyString(tokens?.account_id) ??+ extractCodexAccountIdFromToken(readNonEmptyString(tokens?.id_token)) ??+ extractCodexAccountIdFromToken(accessToken);+ const idToken = readNonEmptyString(tokens?.id_token);+ const lastRefresh = readNonEmptyString(auth.last_refresh);+ return {+ kind: "chatgpt",+ ...(accessToken !== undefined && { accessToken }),+ ...(accountId !== undefined && { accountId }),+ ...(idToken !== undefined && { idToken }),+ ...(lastRefresh !== undefined && { lastRefresh }),+ ...(refreshToken !== undefined && { refreshToken }),+ };+ }++ if (apiKey !== undefined) {+ return { kind: "api-key", apiKey };+ }++ return { kind: "none" };+}++function parseCodexAuthFile(raw: string): ParsedCodexAuthFile {+ let parsedJson: unknown;+ try {+ parsedJson = JSON.parse(raw);+ } catch (error) {+ return { kind: "invalid", reason: toErrorMessage(error) };+ }++ const parsed = codexAuthFileSchema.safeParse(parsedJson);+ if (!parsed.success) {+ return { kind: "invalid", reason: "auth.json must match the Codex auth schema." };+ }++ return { kind: "parsed", value: parsed.data };+}++export async function writeCodexAuthCredentials(input: {+ readonly credentials: CodexChatGptCredentials;+ readonly now?: () => Date;+ readonly tokens: CodexRefreshedTokens;+}): Promise<CodexChatGptCredentials> {+ const raw = await readFile(input.credentials.authPath, "utf8");+ const parsed: unknown = JSON.parse(raw);+ if (!isObject(parsed)) {+ throw new Error(+ `Codex login state at ${input.credentials.authPath} must contain a JSON object.`,+ );+ }++ const existingTokens = isObject(parsed.tokens) ? parsed.tokens : {};+ const accountId =+ input.tokens.accountId ??+ input.credentials.accountId ??+ extractCodexAccountIdFromToken(input.tokens.idToken) ??+ extractCodexAccountIdFromToken(input.tokens.accessToken);+ const idToken = input.tokens.idToken ?? input.credentials.idToken;+ const lastRefresh = (input.now ?? (() => new Date()))().toISOString();+ const next = {+ ...parsed,+ auth_mode: "chatgpt",+ tokens: {+ ...existingTokens,+ access_token: input.tokens.accessToken,+ refresh_token: input.tokens.refreshToken,+ ...(accountId !== undefined && { account_id: accountId }),+ ...(idToken !== undefined && { id_token: idToken }),+ },+ last_refresh: lastRefresh,+ };++ await writeFile(input.credentials.authPath, `${JSON.stringify(next, null, 2)}\n`, "utf8");++ return {+ kind: "chatgpt",+ accessToken: input.tokens.accessToken,+ authPath: input.credentials.authPath,+ codexHome: input.credentials.codexHome,+ lastRefresh,+ refreshToken: input.tokens.refreshToken,+ ...(accountId !== undefined && { accountId }),+ ...(idToken !== undefined && { idToken }),+ };+}++export function assertCodexAuthStateAuthenticated(state: CodexAuthState): void {+ if (state.kind === "authenticated") {+ return;+ }++ if (state.kind === "missing") {+ throw new Error(+ `Codex login state was not found at ${state.authPath}. Run \`codex login\` before using experimental_chatgpt.`,+ );+ }++ throw new Error(+ `Codex login state at ${state.authPath} could not be read: ${state.reason}. Run \`codex login\` again before using experimental_chatgpt.`,+ );+}++function resolveDefaultCodexHome(): string {+ return process.env.CODEX_HOME?.trim() || join(homedir(), ".codex");+}++function readNonEmptyString(value: unknown): string | undefined {+ return typeof value === "string" && value.trim() !== "" ? value : undefined;+}++export function readCodexJwtExpirationMs(token: string | undefined): number | undefined {+ const claims = parseCodexJwtClaims(token);+ if (claims === undefined || typeof claims.exp !== "number") return undefined;+ return claims.exp * 1000;+}++export function isFreshCodexAccessToken(accessToken: string | undefined, now: number): boolean {+ if (accessToken === undefined) return false;+ const expiresAt = readCodexJwtExpirationMs(accessToken);+ return expiresAt === undefined || expiresAt - TOKEN_REFRESH_SKEW_MS > now;+}++export function extractCodexAccountIdFromToken(token: string | undefined): string | undefined {+ const claims = parseCodexJwtClaims(token);+ if (claims === undefined) return undefined;+ const authClaims = claims["https://api.openai.com/auth"];+ const organizations = claims.organizations;+ return (+ readNonEmptyString(claims.chatgpt_account_id) ??+ readNonEmptyString(isObject(authClaims) ? authClaims.chatgpt_account_id : undefined) ??+ readNonEmptyString(+ Array.isArray(organizations) && isObject(organizations[0]) ? organizations[0].id : undefined,+ )+ );+}++function parseCodexJwtClaims(token: string | undefined): Record<string, unknown> | undefined {+ if (token === undefined) return undefined;+ try {+ return decodeJwt(token);+ } catch {+ return undefined;+ }+}diff --git a/packages/eve/src/public/models/openai/chatgpt/model.test.ts b/packages/eve/src/public/models/openai/chatgpt/model.test.tsnew file mode 100644index 000000000..9df8076ab--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/model.test.ts@@ -0,0 +1,118 @@+import { describe, expect, it } from "vitest";++import { createCodexSubscriptionModel } from "./model.js";+import { createUnsignedJwt } from "./unsigned-jwt.js";++const CODEX_ENDPOINT = "https://chatgpt.test/backend-api/codex/responses";++describe("Codex model", () => {+ it("creates an OpenAI Responses model under the Codex provider namespace", () => {+ const model = createCodexSubscriptionModel(+ { model: " gpt-5.4 " },+ {+ fetch: async () => Response.json({ ok: true }),+ readCredentials: async () => ({+ kind: "api-key",+ apiKey: "sk-test",+ authPath: "/home/user/.codex/auth.json",+ codexHome: "/home/user/.codex",+ }),+ },+ );++ expect(model).toMatchObject({+ modelId: "gpt-5.4",+ provider: "codex.responses",+ specificationVersion: "v4",+ });+ });++ it("rejects an empty Codex model id", () => {+ expect(() => createCodexSubscriptionModel({ model: " " })).toThrow(+ 'Expected "model" to name a Codex model.',+ );+ });++ it("disables response storage before OpenAI Responses prompt conversion", async () => {+ const requests: RecordedRequest[] = [];+ const model = createCodexSubscriptionModel(+ { model: "gpt-5.2-codex" },+ {+ codexApiEndpoint: CODEX_ENDPOINT,+ fetch: createRecordingFetch(requests),+ readCredentials: async () => ({+ kind: "chatgpt",+ accessToken: createUnsignedJwt({ exp: 2_000_000_000 }),+ authPath: "/home/user/.codex/auth.json",+ codexHome: "/home/user/.codex",+ }),+ },+ );++ await model.doGenerate({+ prompt: [+ { role: "user", content: [{ type: "text", text: "hello" }] },+ {+ role: "assistant",+ content: [+ {+ type: "text",+ text: "previous answer",+ providerOptions: {+ openai: {+ itemId: "msg_070f78d118bbc2a4016a4565689d4c8190b455e3c0b74eaf90",+ phase: "final_answer",+ },+ },+ },+ ],+ },+ ],+ providerOptions: { openai: { store: true } },+ });++ expect(requests).toHaveLength(1);+ expect(requests[0]?.url).toBe(CODEX_ENDPOINT);+ const body = JSON.parse(requests[0]?.body ?? "{}");+ expect(body.store).toBe(false);+ expect(body.input).toEqual([+ { role: "user", content: [{ type: "input_text", text: "hello" }] },+ {+ role: "assistant",+ content: [{ type: "output_text", text: "previous answer" }],+ phase: "final_answer",+ },+ ]);+ expect(JSON.stringify(body)).not.toContain("item_reference");+ expect(JSON.stringify(body)).not.toContain(+ "msg_070f78d118bbc2a4016a4565689d4c8190b455e3c0b74eaf90",+ );+ });+});++interface RecordedRequest {+ readonly body: string | undefined;+ readonly url: string;+}++function createRecordingFetch(requests: RecordedRequest[]): typeof fetch {+ return async (input, init) => {+ requests.push({+ body: typeof init?.body === "string" ? init.body : undefined,+ url: input instanceof Request ? input.url : input.toString(),+ });+ return Response.json({+ created_at: 0,+ id: "resp_1",+ model: "gpt-5.2-codex",+ output: [+ {+ content: [{ annotations: [], text: "ok", type: "output_text" }],+ id: "msg_new",+ role: "assistant",+ type: "message",+ },+ ],+ });+ };+}diff --git a/packages/eve/src/public/models/openai/chatgpt/model.ts b/packages/eve/src/public/models/openai/chatgpt/model.tsnew file mode 100644index 000000000..fd3f85bf1--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/model.ts@@ -0,0 +1,128 @@+import { createOpenAI } from "#compiled/@ai-sdk/openai/index.js";+import type {+ LanguageModelV4,+ LanguageModelV4CallOptions,+} from "#compiled/@ai-sdk/provider/index.js";+import { createCodexFetch, type CodexTransportOptions } from "./transport.js";+import { isObject } from "#shared/guards.js";++const CODEX_LOCAL_AUTH_API_KEY = "codex-local-auth";++/** Configures the Codex model selected by the local Codex login. */+export interface CodexModelOptions {+ /** OpenAI model ID passed to the Codex Responses endpoint, for example `gpt-5.6-sol`. */+ readonly model: string;+}++// Test seam for the direct Codex transport boundary.+export function createCodexSubscriptionModel(+ input: CodexModelOptions,+ options: CodexTransportOptions = {},+): LanguageModelV4 {+ const model = input.model.trim();+ if (model.length === 0) {+ throw new Error('Expected "model" to name a Codex model.');+ }++ const openaiModel = createOpenAI({+ apiKey: CODEX_LOCAL_AUTH_API_KEY,+ fetch: createCodexFetch(options),+ name: "codex",+ }).responses(model);++ // The Codex backend rejects stored responses and server-side item ids, so+ // every call goes through normalizeCodexCallOptions before delegation.+ return {+ specificationVersion: openaiModel.specificationVersion,+ provider: openaiModel.provider,+ modelId: openaiModel.modelId,+ get supportedUrls() {+ return openaiModel.supportedUrls;+ },+ doGenerate: (callOptions: LanguageModelV4CallOptions) =>+ openaiModel.doGenerate(normalizeCodexCallOptions(callOptions)),+ doStream: (callOptions: LanguageModelV4CallOptions) =>+ openaiModel.doStream(normalizeCodexCallOptions(callOptions)),+ };+}++function normalizeCodexCallOptions(+ options: LanguageModelV4CallOptions,+): LanguageModelV4CallOptions {+ const providerOptions = options.providerOptions;+ const openaiOptions = providerOptions?.openai ?? {};++ return {+ ...options,+ prompt: stripOpenAIItemIdsFromPrompt(options.prompt),+ providerOptions: {+ ...providerOptions,+ openai: {+ ...openaiOptions,+ store: false,+ },+ },+ };+}++function stripOpenAIItemIdsFromPrompt(+ prompt: LanguageModelV4CallOptions["prompt"],+): LanguageModelV4CallOptions["prompt"] {+ return stripOpenAIItemIds(prompt, new WeakMap()) as LanguageModelV4CallOptions["prompt"];+}++/**+ * Copy-on-write: rebuilds only the spine of paths that actually carry an+ * OpenAI `itemId`, so untouched prompt content — the bulk of a long+ * conversation, tool outputs, file parts — is shared, not cloned, on every+ * model call.+ */+function stripOpenAIItemIds(value: unknown, memo: WeakMap<object, unknown>): unknown {+ if (typeof value !== "object" || value === null) {+ return value;+ }+ const memoized = memo.get(value);+ if (memoized !== undefined) {+ return memoized;+ }+ // In-progress marker: a cycle resolves to the original reference.+ memo.set(value, value);++ if (Array.isArray(value)) {+ let changed = false;+ const next = value.map((item) => {+ const stripped = stripOpenAIItemIds(item, memo);+ if (stripped !== item) changed = true;+ return stripped;+ });+ const result = changed ? next : value;+ memo.set(value, result);+ return result;+ }++ if (!isObject(value)) {+ return value;+ }++ let changed = false;+ const next: Record<string, unknown> = {};+ for (const [key, entryValue] of Object.entries(value)) {+ let stripped = stripOpenAIItemIds(entryValue, memo);+ if (key === "providerOptions" || key === "providerMetadata") {+ stripped = withoutOpenAIItemId(stripped);+ }+ if (stripped !== entryValue) changed = true;+ next[key] = stripped;+ }+ const result = changed ? next : value;+ memo.set(value, result);+ return result;+}++function withoutOpenAIItemId(value: unknown): unknown {+ if (!isObject(value) || !isObject(value.openai) || !("itemId" in value.openai)) {+ return value;+ }+ const { itemId: _itemId, ...openaiOptions } = value.openai;+ return { ...value, openai: openaiOptions };+}diff --git a/packages/eve/src/public/models/openai/chatgpt/transport.test.ts b/packages/eve/src/public/models/openai/chatgpt/transport.test.tsnew file mode 100644index 000000000..b60aa4472--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/transport.test.ts@@ -0,0 +1,222 @@+import { describe, expect, it, vi } from "vitest";++import type {+ CodexAuthCredentials,+ CodexChatGptCredentials,+ CodexRefreshedTokens,+} from "./auth.js";+import { createCodexFetch, rewriteCodexEndpoint } from "./transport.js";+import { createUnsignedJwt } from "./unsigned-jwt.js";++const CODEX_ENDPOINT = "https://chatgpt.test/backend-api/codex/responses";+const ISSUER = "https://auth.test";++describe("Codex direct transport", () => {+ it("rewrites OAuth Responses requests to the Codex backend with refreshed ChatGPT auth", async () => {+ const refreshedAccessToken = createUnsignedJwt({+ exp: 2_000_000_000,+ "https://api.openai.com/auth": { chatgpt_account_id: "acct-new" },+ });+ const requests: RecordedRequest[] = [];+ const httpFetch = createRecordingFetch(requests, async (url) => {+ if (url === `${ISSUER}/oauth/token`) {+ return Response.json({+ access_token: refreshedAccessToken,+ id_token: createUnsignedJwt({ chatgpt_account_id: "acct-new" }),+ refresh_token: "refresh-new",+ });+ }+ return Response.json({ ok: true });+ });+ const writeCredentials = vi.fn(+ async (input: {+ readonly credentials: CodexChatGptCredentials;+ readonly tokens: CodexRefreshedTokens;+ }): Promise<CodexChatGptCredentials> => ({+ kind: "chatgpt",+ accessToken: input.tokens.accessToken,+ accountId: input.tokens.accountId,+ authPath: input.credentials.authPath,+ codexHome: input.credentials.codexHome,+ refreshToken: input.tokens.refreshToken,+ }),+ );+ const codexFetch = createCodexFetch({+ codexApiEndpoint: CODEX_ENDPOINT,+ fetch: httpFetch,+ issuer: ISSUER,+ now: () => 1_800_000_000_000,+ readCredentials: async () => ({+ kind: "chatgpt",+ accessToken: createUnsignedJwt({ exp: 1 }),+ authPath: "/home/user/.codex/auth.json",+ codexHome: "/home/user/.codex",+ refreshToken: "refresh-old",+ }),+ writeCredentials,+ });++ await codexFetch("https://api.openai.com/v1/responses", {+ body: '{"stream":true}',+ headers: {+ authorization: "Bearer placeholder",+ "content-type": "application/json",+ },+ method: "POST",+ });++ expect(requests).toHaveLength(2);+ expect(requests[0]?.url).toBe(`${ISSUER}/oauth/token`);+ expect(requests[0]?.body).toContain("grant_type=refresh_token");+ expect(requests[0]?.body).toContain("refresh_token=refresh-old");+ expect(writeCredentials).toHaveBeenCalledWith({+ credentials: expect.objectContaining({ refreshToken: "refresh-old" }),+ tokens: expect.objectContaining({+ accessToken: refreshedAccessToken,+ accountId: "acct-new",+ refreshToken: "refresh-new",+ }),+ });+ expect(requests[1]).toMatchObject({+ method: "POST",+ url: CODEX_ENDPOINT,+ });+ expect(JSON.parse(requests[1]?.body ?? "{}")).toEqual({ stream: true });+ expect(requests[1]?.headers.get("authorization")).toBe(`Bearer ${refreshedAccessToken}`);+ expect(requests[1]?.headers.get("ChatGPT-Account-Id")).toBe("acct-new");+ expect(requests[1]?.headers.get("originator")).toBe("eve");+ expect(requests[1]?.headers.get("content-type")).toBe("application/json");+ });++ it("leaves API-key auth on the OpenAI API endpoint", async () => {+ const requests: RecordedRequest[] = [];+ const codexFetch = createCodexFetch({+ fetch: createRecordingFetch(requests),+ readCredentials: async (): Promise<CodexAuthCredentials> => ({+ kind: "api-key",+ apiKey: "sk-test",+ authPath: "/home/user/.codex/auth.json",+ codexHome: "/home/user/.codex",+ }),+ });++ await codexFetch("https://api.openai.com/v1/responses", {+ headers: { authorization: "Bearer placeholder" },+ method: "POST",+ });++ expect(requests).toHaveLength(1);+ expect(requests[0]?.url).toBe("https://api.openai.com/v1/responses");+ expect(requests[0]?.headers.get("authorization")).toBe("Bearer sk-test");+ expect(requests[0]?.headers.has("ChatGPT-Account-Id")).toBe(false);+ expect(requests[0]?.headers.get("originator")).toBe("eve");+ });++ it("leaves API-key request bodies unchanged", async () => {+ const requests: RecordedRequest[] = [];+ const codexFetch = createCodexFetch({+ fetch: createRecordingFetch(requests),+ readCredentials: async (): Promise<CodexAuthCredentials> => ({+ kind: "api-key",+ apiKey: "sk-test",+ authPath: "/home/user/.codex/auth.json",+ codexHome: "/home/user/.codex",+ }),+ });++ await codexFetch("https://api.openai.com/v1/responses", {+ body: '{"model":"gpt-5.2-codex","input":[],"store":true}',+ method: "POST",+ });++ expect(requests).toHaveLength(1);+ expect(requests[0]?.body).toBe('{"model":"gpt-5.2-codex","input":[],"store":true}');+ });++ it("deduplicates concurrent ChatGPT token refreshes", async () => {+ const requests: RecordedRequest[] = [];+ let releaseRefresh: (() => void) | undefined;+ const refreshGate = new Promise<void>((resolve) => {+ releaseRefresh = resolve;+ });+ const httpFetch = createRecordingFetch(requests, async (url) => {+ if (url === `${ISSUER}/oauth/token`) {+ await refreshGate;+ return Response.json({+ access_token: createUnsignedJwt({ exp: 2_000_000_000 }),+ refresh_token: "refresh-new",+ });+ }+ return Response.json({ ok: true });+ });+ const writeCredentials = vi.fn(+ async (input: {+ readonly credentials: CodexChatGptCredentials;+ readonly tokens: CodexRefreshedTokens;+ }): Promise<CodexChatGptCredentials> => ({+ ...input.credentials,+ accessToken: input.tokens.accessToken,+ refreshToken: input.tokens.refreshToken,+ }),+ );+ const codexFetch = createCodexFetch({+ codexApiEndpoint: CODEX_ENDPOINT,+ fetch: httpFetch,+ issuer: ISSUER,+ now: () => 1_800_000_000_000,+ readCredentials: async () => ({+ kind: "chatgpt",+ authPath: "/home/user/.codex/auth.json",+ codexHome: "/home/user/.codex",+ refreshToken: "refresh-old",+ }),+ writeCredentials,+ });++ const first = codexFetch("https://api.openai.com/v1/responses");+ const second = codexFetch("https://api.openai.com/v1/responses");+ await vi.waitFor(() =>+ expect(requests.filter((request) => request.url === `${ISSUER}/oauth/token`)).toHaveLength(1),+ );+ releaseRefresh?.();+ await Promise.all([first, second]);++ expect(requests.filter((request) => request.url === `${ISSUER}/oauth/token`)).toHaveLength(1);+ expect(writeCredentials).toHaveBeenCalledOnce();+ expect(requests.filter((request) => request.url === CODEX_ENDPOINT)).toHaveLength(2);+ });++ it("matches OpenCode's OAuth URL rewrite boundary", () => {+ expect(rewriteCodexEndpoint("https://api.openai.com/v1/responses", CODEX_ENDPOINT)).toBe(+ CODEX_ENDPOINT,+ );+ expect(rewriteCodexEndpoint("https://api.openai.com/chat/completions", CODEX_ENDPOINT)).toBe(+ CODEX_ENDPOINT,+ );+ expect(rewriteCodexEndpoint("https://api.openai.com/v1/models", CODEX_ENDPOINT)).toBe(+ "https://api.openai.com/v1/models",+ );+ });+});++interface RecordedRequest {+ readonly body: string | undefined;+ readonly headers: Headers;+ readonly method: string | undefined;+ readonly url: string;+}++function createRecordingFetch(+ requests: RecordedRequest[],+ responseForUrl: (url: string) => Response | Promise<Response> = () => Response.json({ ok: true }),+): typeof fetch {+ return async (input, init) => {+ requests.push({+ body: typeof init?.body === "string" ? init.body : undefined,+ headers: new Headers(init?.headers),+ method: init?.method,+ url: input instanceof Request ? input.url : input.toString(),+ });+ return responseForUrl(requests[requests.length - 1]!.url);+ };+}diff --git a/packages/eve/src/public/models/openai/chatgpt/transport.ts b/packages/eve/src/public/models/openai/chatgpt/transport.tsnew file mode 100644index 000000000..92abc3826--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/transport.ts@@ -0,0 +1,230 @@+import { z } from "#compiled/zod/index.js";+import {+ extractCodexAccountIdFromToken,+ isFreshCodexAccessToken,+ readCodexAuthCredentials,+ writeCodexAuthCredentials,+ type CodexAuthCredentials,+ type CodexChatGptCredentials,+ type CodexRefreshedTokens,+} from "./auth.js";+const CODEX_API_ENDPOINT = "https://chatgpt.com/backend-api/codex/responses";+const OPENAI_AUTH_ISSUER = "https://auth.openai.com";+const OPENAI_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";++type Fetch = typeof globalThis.fetch;+type FetchInput = Parameters<Fetch>[0];+type CodexCredentialsWriter = (input: {+ readonly credentials: CodexChatGptCredentials;+ readonly tokens: CodexRefreshedTokens;+}) => Promise<CodexChatGptCredentials>;+type RefreshChatGptCredentialsInput = {+ readonly clientId: string;+ readonly credentials: CodexChatGptCredentials & { readonly refreshToken: string };+ readonly fetch: Fetch;+ readonly issuer: string;+ readonly writeCredentials: CodexCredentialsWriter;+};++export interface CodexTransportOptions {+ readonly clientId?: string;+ readonly codexApiEndpoint?: string;+ readonly fetch?: Fetch;+ readonly issuer?: string;+ readonly now?: () => number;+ readonly readCredentials?: () => Promise<CodexAuthCredentials>;+ readonly writeCredentials?: CodexCredentialsWriter;+}++const codexRefreshResponseSchema = z+ .object({+ access_token: z.string().trim().min(1),+ id_token: z.string().trim().min(1).optional(),+ refresh_token: z.string().trim().min(1),+ })+ .passthrough();++/**+ * AI SDK's OpenAI client gives eve one per-request hook: `fetch`. Codex needs+ * that hook to choose credentials and endpoint per login mode, not just to swap+ * the base URL. API-key logins stay on OpenAI's Responses endpoint; ChatGPT+ * logins use the Codex backend with a refreshed bearer token.+ */+export function createCodexFetch(options: CodexTransportOptions = {}): Fetch {+ const httpFetch = options.fetch ?? fetch;+ const readCredentials = options.readCredentials ?? readCodexAuthCredentials;+ const now = options.now ?? Date.now;+ const writeCredentials = options.writeCredentials ?? createDefaultCodexCredentialsWriter(now);+ const issuer = options.issuer ?? OPENAI_AUTH_ISSUER;+ const clientId = options.clientId ?? OPENAI_CLIENT_ID;+ const codexApiEndpoint = options.codexApiEndpoint ?? CODEX_API_ENDPOINT;+ let refreshPromise: Promise<CodexChatGptCredentials> | undefined;++ return async (input: FetchInput, init?: RequestInit): Promise<Response> => {+ const credentials = await readCredentials();+ const headers = cloneHeaders(+ init?.headers ?? (input instanceof Request ? input.headers : undefined),+ );+ headers.delete("authorization");+ headers.delete("Authorization");+ headers.set("originator", "eve");++ if (credentials.kind === "api-key") {+ headers.set("authorization", `Bearer ${credentials.apiKey}`);+ return httpFetch(input, fetchInit(input, init, headers));+ }++ const chatGptCredentials = await authenticateChatGpt();+ headers.set("authorization", `Bearer ${chatGptCredentials.accessToken}`);+ if (chatGptCredentials.accountId !== undefined) {+ headers.set("ChatGPT-Account-Id", chatGptCredentials.accountId);+ }++ // Response storage (`store: false`, which the Codex backend requires) is+ // injected by createCodexSubscriptionModel's call-options wrapper — the+ // transport only owns credentials and the endpoint rewrite.+ return httpFetch(+ rewriteCodexEndpoint(requestUrl(input), codexApiEndpoint),+ fetchInit(input, init, headers),+ );++ async function authenticateChatGpt(): Promise<+ CodexChatGptCredentials & { readonly accessToken: string }+ > {+ if (credentials.kind !== "chatgpt") {+ throw new Error("Expected ChatGPT Codex credentials.");+ }+ if (+ credentials.accessToken !== undefined &&+ isFreshCodexAccessToken(credentials.accessToken, now())+ ) {+ return { ...credentials, accessToken: credentials.accessToken };+ }+ const refreshToken = credentials.refreshToken;+ if (refreshToken === undefined) {+ throw new Error(+ `Codex ChatGPT login state at ${credentials.authPath} does not include a refresh token. Run \`codex login\` again before using experimental_chatgpt.`,+ );+ }+ if (refreshPromise === undefined) {+ refreshPromise = refreshChatGptCredentials({+ clientId,+ credentials: { ...credentials, refreshToken },+ fetch: httpFetch,+ issuer,+ writeCredentials,+ }).finally(() => {+ refreshPromise = undefined;+ });+ }+ const refreshed = await refreshPromise;+ if (refreshed.accessToken === undefined) {+ throw new Error("Codex token refresh did not return an access token.");+ }+ return { ...refreshed, accessToken: refreshed.accessToken };+ }+ };+}++export function rewriteCodexEndpoint(input: string, codexApiEndpoint = CODEX_API_ENDPOINT): string {+ const url = new URL(input);+ if (url.pathname.includes("/v1/responses") || url.pathname.includes("/chat/completions")) {+ return codexApiEndpoint;+ }+ return input;+}++async function refreshChatGptCredentials(+ input: RefreshChatGptCredentialsInput,+): Promise<CodexChatGptCredentials> {+ const response = await input.fetch(`${input.issuer}/oauth/token`, {+ body: new URLSearchParams({+ client_id: input.clientId,+ grant_type: "refresh_token",+ refresh_token: input.credentials.refreshToken,+ }).toString(),+ headers: { "Content-Type": "application/x-www-form-urlencoded" },+ method: "POST",+ });+ if (!response.ok) {+ throw new Error(+ `Codex token refresh failed with status ${response.status}. Run \`codex login\` again.`,+ );+ }++ const tokens = parseRefreshResponse(await response.json());+ return input.writeCredentials({+ credentials: input.credentials,+ tokens: {+ ...tokens,+ accountId:+ tokens.accountId ??+ input.credentials.accountId ??+ extractCodexAccountIdFromToken(tokens.idToken) ??+ extractCodexAccountIdFromToken(tokens.accessToken),+ },+ });+}++function parseRefreshResponse(value: unknown): CodexRefreshedTokens {+ const parsed = codexRefreshResponseSchema.safeParse(value);+ if (!parsed.success) {+ throw new Error("Codex token refresh did not return access_token and refresh_token.");+ }+ const accessToken = parsed.data.access_token;+ const refreshToken = parsed.data.refresh_token;+ const idToken = parsed.data.id_token;++ return {+ accessToken,+ refreshToken,+ ...(idToken !== undefined && { idToken }),+ accountId:+ extractCodexAccountIdFromToken(idToken) ?? extractCodexAccountIdFromToken(accessToken),+ };+}++function createDefaultCodexCredentialsWriter(now: () => number): CodexCredentialsWriter {+ return (input) =>+ writeCodexAuthCredentials({+ ...input,+ now: () => new Date(now()),+ });+}++function cloneHeaders(input: RequestInit["headers"] | undefined): Headers {+ const headers = new Headers(input);+ return headers;+}++function requestUrl(input: FetchInput): string {+ if (input instanceof Request) return input.url;+ return input.toString();+}++function fetchInit(+ input: FetchInput,+ init: RequestInit | undefined,+ headers: Headers,+): RequestInit {+ if (init !== undefined) {+ return { ...init, headers };+ }+ if (input instanceof Request) {+ return {+ body: input.body,+ cache: input.cache,+ credentials: input.credentials,+ headers,+ integrity: input.integrity,+ keepalive: input.keepalive,+ method: input.method,+ mode: input.mode,+ redirect: input.redirect,+ referrer: input.referrer,+ referrerPolicy: input.referrerPolicy,+ signal: input.signal,+ };+ }+ return { headers };+}diff --git a/packages/eve/src/public/models/openai/chatgpt/unsigned-jwt.ts b/packages/eve/src/public/models/openai/chatgpt/unsigned-jwt.tsnew file mode 100644index 000000000..29c1337b4--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/unsigned-jwt.ts@@ -0,0 +1,11 @@+import { Buffer } from "node:buffer";++/**+ * Builds an unsigned JWT (`alg: "none"`, fake signature) whose payload the+ * Codex auth helpers can decode. Test fixture only — no crypto involved.+ */+export function createUnsignedJwt(payload: object): string {+ const header = Buffer.from(JSON.stringify({ alg: "none" })).toString("base64url");+ const body = Buffer.from(JSON.stringify(payload)).toString("base64url");+ return `${header}.${body}.sig`;+}diff --git a/packages/eve/src/public/models/openai/index.test.ts b/packages/eve/src/public/models/openai/index.test.tsnew file mode 100644index 000000000..1432e042f--- /dev/null+++ b/packages/eve/src/public/models/openai/index.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from "vitest";++import { experimental_chatgpt } from "./index.js";++describe("experimental_chatgpt", () => {+ it("defaults to gpt-5.6-sol", () => {+ const model = experimental_chatgpt();++ if (typeof model === "string") throw new Error("expected a model instance");+ expect(model.modelId).toBe("gpt-5.6-sol");+ });++ it("creates a Codex-served model from a bare OpenAI slug", () => {+ const model = experimental_chatgpt("gpt-5.5");++ expect(typeof model).toBe("object");+ if (typeof model === "string") throw new Error("expected a model instance");+ expect(model.modelId).toBe("gpt-5.5");+ expect(model.provider).toContain("codex");+ });++ it("strips an openai/ provider prefix", () => {+ const model = experimental_chatgpt("openai/gpt-5.5");++ if (typeof model === "string") throw new Error("expected a model instance");+ expect(model.modelId).toBe("gpt-5.5");+ });++ it("rejects a non-OpenAI provider-qualified id", () => {+ expect(() => experimental_chatgpt("anthropic/claude-sonnet-4.6")).toThrow(+ 'experimental_chatgpt serves OpenAI models through the local ChatGPT login; received "anthropic/claude-sonnet-4.6".',+ );+ });++ it("rejects an empty model", () => {+ expect(() => experimental_chatgpt(" ")).toThrow("name an OpenAI model");+ expect(() => experimental_chatgpt("openai/")).toThrow("name an OpenAI model");+ });+});diff --git a/packages/eve/src/public/models/openai/index.ts b/packages/eve/src/public/models/openai/index.tsnew file mode 100644index 000000000..4ccee40cb--- /dev/null+++ b/packages/eve/src/public/models/openai/index.ts@@ -0,0 +1,54 @@+import type { LanguageModel } from "ai";+import { createCodexSubscriptionModel } from "./chatgpt/model.js";++const OPENAI_PROVIDER_PREFIX = "openai/";+const DEFAULT_CHATGPT_MODEL = "gpt-5.6-sol";++/**+ * Creates a language model billed to the local ChatGPT subscription instead+ * of an API key, served through the Codex backend the `codex login` flow+ * authorizes.+ *+ * Defaults to `gpt-5.6-sol`. Pass a bare OpenAI model slug or an+ * `openai/`-prefixed id to override it; the Codex backend serves OpenAI models+ * only, so any other provider-qualified id is rejected. Model availability is+ * enforced by the Codex backend per account at call time, not at compile time.+ *+ * Credentials are read from the Codex CLI login on the machine the agent+ * runs on, so this model works in local dev and fails in a deployment.+ * Branch on environment for production, and set `modelContextWindowTokens`+ * because Codex models carry no AI Gateway metadata:+ *+ * ```ts+ * export default defineAgent({+ * model:+ * process.env.NODE_ENV === "production"+ * ? "anthropic/claude-sonnet-4.6"+ * : experimental_chatgpt(),+ * modelContextWindowTokens: 200_000,+ * });+ * ```+ *+ * Experimental: the Codex backend is not a public API contract and may+ * change or reject subscription-backed access without notice.+ */+export function experimental_chatgpt(model = DEFAULT_CHATGPT_MODEL): LanguageModel {+ const trimmed = model.trim();+ const slug = trimmed.startsWith(OPENAI_PROVIDER_PREFIX)+ ? trimmed.slice(OPENAI_PROVIDER_PREFIX.length)+ : trimmed;++ if (slug.length === 0) {+ throw new Error(+ 'Expected experimental_chatgpt "model" to name an OpenAI model, for example "gpt-5.6-sol".',+ );+ }++ if (slug.includes("/")) {+ throw new Error(+ `experimental_chatgpt serves OpenAI models through the local ChatGPT login; received "${model}".`,+ );+ }++ return createCodexSubscriptionModel({ model: slug });+}