The Open Framework for Building Agents
feat(eve): promote ChatGPT subscription models (#2158)
Rui00c0a26727f1
diff --git a/.changeset/chatgpt-codex-auth-broker.md b/.changeset/chatgpt-codex-auth-broker.mdnew file mode 100644index 000000000..5bef2df50--- /dev/null+++ b/.changeset/chatgpt-codex-auth-broker.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Promote ChatGPT subscription models to the stable `chatgpt()` API with Codex-owned authentication, automatic token refresh, `eve dev` recovery through `codex login` or `/model`, setup/source-authoring support, and local-only deployment safeguards. The deprecated `experimental_chatgpt()` alias remains available.diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.mdindex adb169bd6..4c3e1a58c 100644--- a/docs/reference/typescript-api.md+++ b/docs/reference/typescript-api.md@@ -89,7 +89,7 @@ A few additional helpers round out the set: `defineGlobTool`, `defineGrepTool`,| `eve/context` | `defineState`, session and state types || `eve/sandbox` | `defineSandbox`, backends || `eve/instrumentation` | `defineInstrumentation`, `isChannel` |-| `eve/models/openai` | `experimental_chatgpt` |+| `eve/models/openai` | `chatgpt`, deprecated `experimental_chatgpt` || `eve/evals` | `defineEval`, `defineEvalConfig`, `mockModel`, eval types || `eve/evals/expect` | `includes`, `equals`, `matches`, `similarity` || `eve/evals/reporters` | `Braintrust`, `JUnit`, `EvalReporter` |@@ -102,19 +102,33 @@ Exported types ship from the same entrypoint as the helper they describe (for ex## 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`:+`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";+import { chatgpt } from "eve/models/openai";export default defineAgent({- model: experimental_chatgpt(),- modelContextWindowTokens: 200_000,+ model: chatgpt(),});```-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.+Pass another bare OpenAI model slug to override the default. `experimental_chatgpt()` remains as a deprecated alias.++Authentication is delegated entirely to the Codex CLI:++1. Install or upgrade `codex` and run `codex login`.+2. `eve dev` asks `codex app-server` for a usable access token. Codex owns refresh and credential persistence; eve does not read or write Codex login files.+3. Normal token expiry is refreshed automatically. If the login is revoked, the status line shows `codex login`; completing login inside or outside eve repairs the running dev session without restarting it.++ChatGPT subscription credentials are local user credentials. `eve deploy` blocks agents whose active model is `chatgpt()` because those credentials are not uploaded to a deployment. Use an environment branch with a deployable model, or switch to an AI Gateway model before deploying.++Troubleshooting:++- **`chatgpt-sub login`**: run `codex login`.+- **`chatgpt-sub unavailable`**: ensure `codex` is installed, current, and available on `PATH`; then restart the command.+- **Model rejected by the backend**: model availability depends on the signed-in ChatGPT account. Pick another supported OpenAI model.+- **SSH/headless login**: run `codex login --device-auth` in another terminal, then return to the still-running `eve dev` session.## What to read nextdiff --git a/packages/eve/src/cli/commands/deploy.ts b/packages/eve/src/cli/commands/deploy.tsindex 4b48cf747..e9bc17566 100644--- a/packages/eve/src/cli/commands/deploy.ts+++ b/packages/eve/src/cli/commands/deploy.ts@@ -47,6 +47,13 @@ export async function runDeployCommand(process.exitCode = 1;return;}+ if (result.kind === "local-model") {+ logger.error(+ "ChatGPT subscription models use local Codex credentials and cannot be deployed. Switch to an AI Gateway or server-authenticated model before running `eve deploy`.",+ );+ process.exitCode = 1;+ return;+ }prompter.outro(result.kind === "cancelled"? "Cancelled."diff --git a/packages/eve/src/cli/dev/environment.ts b/packages/eve/src/cli/dev/environment.tsindex 0f75d8e5a..c8cc07838 100644--- a/packages/eve/src/cli/dev/environment.ts+++ b/packages/eve/src/cli/dev/environment.ts@@ -3,6 +3,7 @@ import { join, resolve } from "node:path";import { parseEnv } from "node:util";import { isObject } from "#shared/guards.js";+import { readProviderSelectionSync } from "#setup/provider-settings.js";/*** Development environment files loaded by local CLI commands such as@@ -63,8 +64,12 @@ export function readDevelopmentEnvironmentHostValues(): Readonly<Record<string, string | null>> {const values: Record<string, string | null> = {};const fileValues = readDevelopmentEnvironmentValues(resolve(appRoot));+ const hostKeys = new Set(fileValues.keys());+ // Project selection can suppress a shell-only key. Keep that transition in+ // the host fingerprint so the worker that inherited the key is replaced.+ hostKeys.add("AI_GATEWAY_API_KEY");- for (const key of [...fileValues.keys()].sort((left, right) => left.localeCompare(right))) {+ for (const key of [...hostKeys].sort((left, right) => left.localeCompare(right))) {values[key] = process.env[key] ?? null;}@@ -85,18 +90,28 @@ function getDevelopmentEnvironmentLoader(appRoot: string): DevelopmentEnvironmen}function createDevelopmentEnvironmentLoader(appRoot: string): DevelopmentEnvironmentLoader {- const protectedKeys = new Set(Object.keys(process.env));+ const protectedValues = new Map(Object.entries(process.env));+ const protectedKeys = new Set(protectedValues.keys());const managedValues = new Map<string, string>();const stageReload = (): DevelopmentEnvironmentReload => {const previousManagedValues = new Map(managedValues);const nextValues = readDevelopmentEnvironmentValues(appRoot);+ const preferProjectOidc = applyProviderSelection(appRoot, nextValues);const affectedKeys = new Set([...managedValues.keys(), ...nextValues.keys()]);+ if (preferProjectOidc) {+ affectedKeys.add("AI_GATEWAY_API_KEY");+ protectedKeys.delete("AI_GATEWAY_API_KEY");+ } else if (protectedValues.has("AI_GATEWAY_API_KEY")) {+ protectedKeys.add("AI_GATEWAY_API_KEY");+ process.env.AI_GATEWAY_API_KEY = protectedValues.get("AI_GATEWAY_API_KEY");+ }const previousEnvironment = new Map([...affectedKeys].map((key) => [key, process.env[key]] as const),);let settled = false;+ if (preferProjectOidc) delete process.env.AI_GATEWAY_API_KEY;applyDevelopmentEnvironmentValues({managedValues,nextValues,@@ -135,6 +150,12 @@ function createDevelopmentEnvironmentLoader(appRoot: string): DevelopmentEnviron};}+function applyProviderSelection(appRoot: string, values: Map<string, string>): boolean {+ if (readProviderSelectionSync(appRoot) !== "ai-gateway-project") return false;+ values.delete("AI_GATEWAY_API_KEY");+ return true;+}+function applyDevelopmentEnvironmentValues(input: {readonly managedValues: Map<string, string>;readonly nextValues: ReadonlyMap<string, string>;diff --git a/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts b/packages/eve/src/cli/dev/tui/prompt-command-handler.test.tsindex 4da4355a0..0423cbd75 100644--- a/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts+++ b/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts@@ -129,7 +129,7 @@ describe("createPromptCommandHandler", () => {it("forwards automatic provider entry and model-access changes", async () => {const runTuiSetupCommand = vi.fn(async () => ({- message: "Connected to AI Gateway via AI_GATEWAY_API_KEY in .env.local.",+ message: "AI Gateway via API key selected.",preserveFlowDiagnostics: false,effect: { kind: "model-access-changed" } as const,}));@@ -150,7 +150,7 @@ describe("createPromptCommandHandler", () => {{ ...context({ setupFlow }), initialModelStep: "provider" },),).resolves.toEqual({- message: "Connected to AI Gateway via AI_GATEWAY_API_KEY in .env.local.",+ message: "AI Gateway via API key selected.",effect: { kind: "model-access-changed" },});expect(runTuiSetupCommand).toHaveBeenCalledWith(diff --git a/packages/eve/src/cli/dev/tui/prompt-command-handler.ts b/packages/eve/src/cli/dev/tui/prompt-command-handler.tsindex d196ccbd8..98f45f2c7 100644--- a/packages/eve/src/cli/dev/tui/prompt-command-handler.ts+++ b/packages/eve/src/cli/dev/tui/prompt-command-handler.ts@@ -117,6 +117,7 @@ export function createPromptCommandHandler(appRoot: target.workspaceRoot,renderer: flow,withExclusiveTerminal: context.withExclusiveTerminal,+ chatGptAccountLabel: context.chatGptAccountLabel,};if (context.initialModelStep !== undefined) {commandInput.initialModelStep = context.initialModelStep;diff --git a/packages/eve/src/cli/dev/tui/provider-picker.ts b/packages/eve/src/cli/dev/tui/provider-picker.tsindex 1ff33618d..7d3b233f0 100644--- a/packages/eve/src/cli/dev/tui/provider-picker.ts+++ b/packages/eve/src/cli/dev/tui/provider-picker.ts@@ -44,7 +44,7 @@ function keyPhase(select: SelectState,options: readonly PromptOption<ProviderConnection>[],): ProviderPickerPhase {- return selectValueAtCursor(options, select.cursor) === "own-key"+ return selectValueAtCursor(options, select.cursor) === "ai-gateway-key"? { kind: "editing", editor: EMPTY_LINE }: { kind: "inactive" };}@@ -95,7 +95,7 @@ export function transitionProviderPicker(}return {kind: "settle",- result: { kind: "inline-key", key: state.phase.key, validation: event.validation },+ result: { kind: "ai-gateway-key", key: state.phase.key, validation: event.validation },};}@@ -113,10 +113,10 @@ export function transitionProviderPicker(};case "submit": {const value = selectValueAtCursor(options, state.select.cursor);- if (value === "project" || value === "external") {+ if (value === "ai-gateway-project" || value === "chatgpt" || value === "external") {return { kind: "settle", result: { kind: value } };}- if (value !== "own-key" || state.phase.kind === "inactive") return ignore(state);+ if (value !== "ai-gateway-key" || state.phase.kind === "inactive") return ignore(state);const key = state.phase.editor.text.trim();if (key.length === 0) {return {diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex df93c2859..3a1b1f4bc 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -2993,6 +2993,19 @@ describe("EveTUIRunner Vercel status line", () => {});it("refreshes agent info only after a model-access change", async () => {+ const runtimeRequests: Array<{ method: string; url: URL }> = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {+ runtimeRequests.push({+ method: init?.method ?? "GET",+ url: new URL(+ typeof input === "string" ? input : input instanceof URL ? input : input.url,+ ),+ });+ return Response.json({ revision: "snapshot-a" });+ }),+ );const client = stubClient();const info = vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);const prompts: Array<string | undefined> = ["/deploy", "/model", undefined];@@ -3030,6 +3043,14 @@ describe("EveTUIRunner Vercel status line", () => {expect(infoCallsAtPrompt).toEqual([1, 1, 2]);expect(info).toHaveBeenCalledTimes(2);+ expect(+ runtimeRequests.some(+ (request) =>+ request.method === "POST" &&+ request.url.pathname === "/eve/v1/dev/runtime-artifacts/rebuild" &&+ request.url.searchParams.get("force") === "1",+ ),+ ).toBe(true);});it("never pushes Vercel status for a remote --url session", async () => {@@ -3185,7 +3206,7 @@ describe("EveTUIRunner boot setup detection", () => {handle: async (command) =>command.name === "model"? {- message: "Connected to AI Gateway via AI_GATEWAY_API_KEY in .env.local.",+ message: "AI Gateway via API key selected.",effect: { kind: "model-access-changed" },}: { message: "/add dismissed." },diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex f46fa2856..eb0a69d06 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -71,7 +71,7 @@ import {formatSetupIssuesLine,LOGIN_SETUP_ISSUE,orderedSetupIssues,- resolveModelProviderState,+ normalizeLocalModelEndpoint,type BootDetection,type BootDetectionContext,type SetupIssue,@@ -107,6 +107,7 @@ export { parsePromptCommand, type PromptCommand } from "./prompt-commands.js";const defaultAssistantResponseStats: AssistantResponseStatsMode = "tokensPerSecond";const idleRuntimeArtifactPollMs = 500;+const idleChatGptAuthPollMs = 5_000;/*** Cooperative-cancel retry cadence: 8 × 250ms covers the turn-dispatch* window (locally the cancel hook is claimed well under a second after the@@ -371,6 +372,8 @@ export interface PromptCommandHandlerContext {readonly title: string;/** Provider entry authorized by confirmed boot-time model-access evidence. */readonly initialModelStep?: "provider";+ /** Live ChatGPT identity shown only inside model configuration UI. */+ readonly chatGptAccountLabel?: string;/*** Leaves the current setup panel mounted for the next automatic onboarding* command. The runner closes it if no next command can proceed.@@ -671,7 +674,7 @@ export class EveTUIRunner {#replaceAgentInfo(info: AgentInfoResult | undefined): AgentInfoResult | undefined {const headerInfo =- this.#appRoot === undefined ? info : resolveModelProviderState(info, process.env);+ this.#appRoot === undefined ? info : normalizeLocalModelEndpoint(info, process.env);this.#agentInfo = headerInfo;const serverUrl = this.#serverUrl;if (serverUrl === undefined) return headerInfo;@@ -1194,6 +1197,7 @@ export class EveTUIRunner {let stopped = false;let refreshing = false;let inFlightRefresh: Promise<void> | undefined;+ let lastChatGptAuthRefresh = 0;const refresh = async () => {if (stopped || refreshing) {return;@@ -1204,6 +1208,16 @@ export class EveTUIRunner {await runtimeArtifacts.refreshIdle({onRuntimeArtifactsChanged: () => this.#handleRuntimeArtifactsChanged(),});+ const endpoint = this.#agentInfo?.agent.model.endpoint;+ const shouldRefreshChatGptAuth =+ endpoint?.kind === "chatgpt" &&+ (endpoint.state === "signed-out" || endpoint.state === "reauth-required");+ const now = Date.now();+ if (shouldRefreshChatGptAuth && now - lastChatGptAuthRefresh >= idleChatGptAuthPollMs) {+ lastChatGptAuthRefresh = now;+ const refreshedInfo = await this.#readAgentInfo();+ if (refreshedInfo !== undefined) this.#replaceAgentInfo(refreshedInfo);+ }} finally {refreshing = false;}@@ -1582,10 +1596,15 @@ export class EveTUIRunner {if (handler === undefined)return { message: `/${command.name} is not available in this session.` };+ const endpoint = this.#agentInfo?.agent.model.endpoint;const baseContext: PromptCommandHandlerContext = {renderer: this.#renderer,title: input.title,initialModelStep: input.initialModelStep,+ chatGptAccountLabel:+ endpoint?.kind === "chatgpt" && endpoint.state === "ready"+ ? endpoint.accountLabel+ : undefined,remoteConnection: this.#remoteConnection,withExclusiveTerminal: this.#withExclusiveTerminal,};@@ -1650,7 +1669,7 @@ export class EveTUIRunner {* Fresh `eve init` launches the TUI with `/model` prefilled. Project-backed* model access depends on the Vercel CLI and a Vercel session, so resolve* only those missing prerequisites before entering the model picker. A probe- * failure still opens `/model`: its own-key and external-provider paths do+ * failure still opens `/model`: its API-key and external-provider paths do* not require Vercel. After model setup, open the categorized registry hub so* a new user has concrete next steps before reaching the chat prompt.*/@@ -1770,16 +1789,17 @@ export class EveTUIRunner {}/**- * Setup commands can write env files before the dev watcher reloads them.- * Reload first, then cache the credential-normalized `/info` snapshot shared- * by the status bar and setup detector. The Vercel auth probe stays off the- * prompt path.+ * Setup commands can write authored source and env files. Force the local+ * runtime snapshot to catch up, then cache the credential-normalized `/info`+ * shared by the status bar and setup detector. The Vercel auth probe stays+ * off the prompt path.*/async #refreshModelAccess(): Promise<void> {const appRoot = this.#appRoot;if (appRoot === undefined) return;loadDevelopmentEnvironmentFiles(appRoot);+ await this.#runtimeArtifacts?.refreshAfterSourceChange({});const refreshedInfo = this.#replaceAgentInfo(await this.#readAgentInfo());void this.#refreshSetupAttention(refreshedInfo);}diff --git a/packages/eve/src/cli/dev/tui/setup-commands.test.ts b/packages/eve/src/cli/dev/tui/setup-commands.test.tsindex f7210d276..fa8dbcc7d 100644--- a/packages/eve/src/cli/dev/tui/setup-commands.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-commands.test.ts@@ -54,6 +54,7 @@ function fakeFlows(overrides: Partial<TuiSetupFlows> = {}): TuiSetupFlows {runLoginFlow: vi.fn<TuiSetupFlows["runLoginFlow"]>(async () => ({ kind: "logged-in" })),runModelFlow: vi.fn<TuiSetupFlows["runModelFlow"]>(async () => ({kind: "done",+ accessChanged: true,modelMessage: "Model changed to openai/gpt-5.5. Live on your next prompt.",})),runRegistryFlow: vi.fn<TuiSetupFlows["runRegistryFlow"]>(async () => ({@@ -76,6 +77,7 @@ function run(input: {renderer?: TuiSetupCommandRenderer;initialModelStep?: "provider";upgradeChoice?: "upgrade" | "later";+ withExclusiveTerminal?: TuiSetupCommandInput["withExclusiveTerminal"];}) {const { upgradeChoice } = input;const fake = createFakePrompter(@@ -91,6 +93,9 @@ function run(input: {if (input.initialModelStep !== undefined) {commandInput.initialModelStep = input.initialModelStep;}+ if (input.withExclusiveTerminal !== undefined) {+ commandInput.withExclusiveTerminal = input.withExclusiveTerminal;+ }return runTuiSetupCommand(commandInput);}@@ -128,6 +133,7 @@ describe("runTuiSetupCommand", () => {await expect(run({ command: "model", flows })).resolves.toEqual({message: "Model changed to openai/gpt-5.5. Live on your next prompt.",preserveFlowDiagnostics: false,+ effect: { kind: "model-access-changed" },});expect(flows.runModelFlow).toHaveBeenCalledWith(expect.objectContaining({@@ -137,6 +143,56 @@ describe("runTuiSetupCommand", () => {);});+ it("does not rebuild model access after a rejected edit", async () => {+ const flows = fakeFlows({+ runModelFlow: vi.fn<TuiSetupFlows["runModelFlow"]>(async () => ({+ kind: "done",+ accessChanged: false,+ modelMessage: "Couldn't confirm the id.",+ })),+ });++ await expect(run({ command: "model", flows })).resolves.toEqual({+ message: "Couldn't confirm the id.",+ preserveFlowDiagnostics: false,+ });+ });++ it("hands model-owned subprocesses both the terminal and suspended runtime", async () => {+ const calls: string[] = [];+ const renderer = fakePanelRenderer();+ renderer.withInheritedStdio = async (task) => {+ calls.push("terminal:release");+ const result = await task();+ calls.push("terminal:restore");+ return result;+ };+ const withExclusiveTerminal = async <T>(task: () => Promise<T>): Promise<T> => {+ calls.push("runtime:suspend");+ const result = await task();+ calls.push("runtime:resume");+ return result;+ };+ const flows = fakeFlows({+ runModelFlow: vi.fn<TuiSetupFlows["runModelFlow"]>(async (input) => {+ await input.withExclusiveTerminal?.(async () => {+ calls.push("codex");+ });+ return { kind: "cancelled" };+ }),+ });++ await run({ command: "model", flows, renderer, withExclusiveTerminal });++ expect(calls).toEqual([+ "terminal:release",+ "runtime:suspend",+ "codex",+ "runtime:resume",+ "terminal:restore",+ ]);+ });+it("forwards an automatic provider entry to the model flow", async () => {const flows = fakeFlows();@@ -147,89 +203,64 @@ describe("runTuiSetupCommand", () => {);});- it("stacks the model and provider outcome lines when both menu actions ran", async () => {+ it("stacks the model and provider selection lines when both menu actions ran", async () => {const flows = fakeFlows({runModelFlow: vi.fn<TuiSetupFlows["runModelFlow"]>(async () => ({kind: "done",+ accessChanged: true,modelMessage: "Model changed to openai/gpt-5.5. Live on your next prompt.",- providerOutcome: {- resolution: {- credential: "api-key",- source: { kind: "env-file", path: ".env.local" },- },- status: { kind: "gateway-project", projectName: "my-agent" },- },+ providerSelection: "ai-gateway-project",})),});await expect(run({ command: "model", flows })).resolves.toEqual({message:"Model changed to openai/gpt-5.5. Live on your next prompt.\n" +- "Project linked. Connected to AI Gateway via AI_GATEWAY_API_KEY.",+ "AI Gateway via Project selected.",preserveFlowDiagnostics: false,effect: { kind: "model-access-changed" },});});- it("reports a provider-only model session with the provider outcome", async () => {+ it("reports a provider-only model session with the provider selection", async () => {const flows = fakeFlows({runModelFlow: vi.fn<TuiSetupFlows["runModelFlow"]>(async () => ({kind: "done",- providerOutcome: {- resolution: { credential: "oidc", file: ".env.local" },- status: { kind: "gateway-project", projectName: "my-agent", teamName: "my-team" },- },+ accessChanged: true,+ providerSelection: "ai-gateway-project",})),});await expect(run({ command: "model", flows })).resolves.toEqual({- message: "Project linked. Connected to AI Gateway via VERCEL_OIDC_TOKEN.",+ message: "AI Gateway via Project selected.",preserveFlowDiagnostics: false,effect: { kind: "model-access-changed" },});});- it("names the shadow when a gateway key outranks the freshly linked OIDC token", async () => {+ it("reports the selected API-key provider without claiming a connection", async () => {const flows = fakeFlows({runModelFlow: vi.fn<TuiSetupFlows["runModelFlow"]>(async () => ({kind: "done",- providerOutcome: {- resolution: {- credential: "api-key",- source: { kind: "shell" },- shadowedOidc: {},- },- status: { kind: "gateway-project", projectName: "my-agent", teamName: "my-team" },- },+ accessChanged: true,+ providerSelection: "ai-gateway-key",})),});await expect(run({ command: "model", flows })).resolves.toEqual({- message:- "Project linked. AI_GATEWAY_API_KEY (shell) outranks the project's " +- "VERCEL_OIDC_TOKEN and stays the active credential — unset it in your shell to run " +- "on the project.",+ message: "AI Gateway via API key selected.",preserveFlowDiagnostics: false,effect: { kind: "model-access-changed" },});});- it("does not claim a link for a pasted key — the outcome names the env file", async () => {+ it("reports the selected ChatGPT subscription", async () => {const flows = fakeFlows({runModelFlow: vi.fn<TuiSetupFlows["runModelFlow"]>(async () => ({kind: "done",- providerOutcome: {- resolution: {- credential: "api-key",- source: { kind: "env-file", path: ".env.local" },- },- status: {- kind: "gateway-key",- envKey: "AI_GATEWAY_API_KEY",- source: { kind: "env-file", path: ".env.local" },- },- },+ accessChanged: true,+ providerSelection: "chatgpt",})),});await expect(run({ command: "model", flows })).resolves.toEqual({- message: "Connected to AI Gateway via AI_GATEWAY_API_KEY in .env.local.",+ message: "ChatGPT subscription selected.",preserveFlowDiagnostics: false,effect: { kind: "model-access-changed" },});@@ -462,17 +493,8 @@ describe("runTuiSetupCommand", () => {() =>resolve({kind: "done",- providerOutcome: {- resolution: {- credential: "api-key",- source: { kind: "env-file", path: ".env.local" },- },- status: {- kind: "gateway-key",- envKey: "AI_GATEWAY_API_KEY",- source: { kind: "env-file", path: ".env.local" },- },- },+ accessChanged: true,+ providerSelection: "ai-gateway-key",}),{ once: true },);diff --git a/packages/eve/src/cli/dev/tui/setup-commands.ts b/packages/eve/src/cli/dev/tui/setup-commands.tsindex c405ef134..a86aa6582 100644--- a/packages/eve/src/cli/dev/tui/setup-commands.ts+++ b/packages/eve/src/cli/dev/tui/setup-commands.ts@@ -5,7 +5,8 @@ import {type InstallVercelCliResult,} from "#setup/flows/install-vercel-cli.js";import { runLoginFlow, type LoginFlowResult } from "#setup/flows/login.js";-import { runModelFlow, type ModelProviderOutcome } from "#setup/flows/model.js";+import { runModelFlow } from "#setup/flows/model.js";+import type { ProviderSelection } from "#setup/provider-settings.js";import { runProviderFlow, type ProviderPicker } from "#setup/flows/provider.js";import { RegistryFlowFailedError, runRegistryFlow } from "#setup/flows/registry.js";import type { Prompter } from "#setup/prompter.js";@@ -46,6 +47,8 @@ export interface TuiSetupCommandInput {renderer: TuiSetupCommandRenderer;/** Initial model-flow step authorized by the runner's boot evidence. */initialModelStep?: "provider";+ /** Live ChatGPT identity shown only inside model configuration UI. */+ chatGptAccountLabel?: string;/** Suspends development runtime artifacts while registry installation and setup mutate them. */withExclusiveTerminal?<T>(task: () => Promise<T>): Promise<T>;/** Test seam; defaults to the real TUI-native prompter over `renderer`. */@@ -213,6 +216,7 @@ async function executeSetupCommand(appRoot,prompter,signal,+ chatGptAccountLabel: input.chatGptAccountLabel,deps: {pickModelSettings: (request) => renderer.readModelEditor(request),runProviderFlow: (providerInput) =>@@ -222,6 +226,8 @@ async function executeSetupCommand(if (input.initialModelStep !== undefined) {modelInput.initialStep = input.initialModelStep;}+ modelInput.withExclusiveTerminal = (task) =>+ renderer.withInheritedStdio(() => input.withExclusiveTerminal?.(task) ?? task());const result = await flows.runModelFlow(modelInput);if (result.kind === "cancelled") {return {@@ -234,19 +240,19 @@ async function executeSetupCommand(}// One line per completed menu action: the apply line (it already// distinguishes success from a rejected slug), then the provider- // outcome when that sub-flow also ran.+ // selection when that sub-flow also ran.const lines: string[] = [];if (result.modelMessage !== undefined) lines.push(result.modelMessage);- if (result.providerOutcome !== undefined) {- lines.push(providerOutcomeMessage(result.providerOutcome));+ if (result.providerSelection !== undefined) {+ lines.push(providerSelectionMessage(result.providerSelection));}const outcome: TuiSetupCommandResult = {message: lines.join("\n"),preserveFlowDiagnostics: false,};- // Provider setup can change both the local env and Vercel identity.- // The runner refreshes the complete model-access view after the flow.- if (result.providerOutcome !== undefined) {+ // A model edit can also move routing between AI Gateway and ChatGPT.+ // The runner rebuilds authored artifacts before refreshing model access.+ if (result.accessChanged) {outcome.effect = { kind: "model-access-changed" };}return outcome;@@ -278,6 +284,13 @@ async function executeSetupCommand(preserveFlowDiagnostics: true,};}+ if (result.kind === "local-model") {+ return {+ message:+ "ChatGPT subscription models are local-only. Switch to an AI Gateway or server-authenticated model before deploying.",+ preserveFlowDiagnostics: true,+ };+ }return {message:result.productionUrl === undefined ? "Deployed." : `Deployed: ${result.productionUrl}`,@@ -496,42 +509,9 @@ function loginResultMessage(result: LoginFlowResult): TuiSetupCommandResult {}}-/**- * The persistent outcome line for /model's completed provider sub-flow. The- * panel's success lines vanish with it, so the outcome carries the substance:- * what the directory now reads (the same detection the menu shows) and which- * credential is ready, or what to do next. "Project linked" is only claimed- * when a link is actually detected — the own-key branch pastes a credential- * without linking anything.- */-function providerOutcomeMessage(outcome: ModelProviderOutcome): string {- const { resolution, status } = outcome;- if (status.kind === "gateway-project") {- if (resolution === undefined) {- return "Project linked. No model credential found; set AI_GATEWAY_API_KEY in .env.local.";- }- if (resolution.credential === "oidc") {- return "Project linked. Connected to AI Gateway via VERCEL_OIDC_TOKEN.";- }- // A gateway key outranks the project's OIDC token at runtime — claiming- // the OIDC connection while the key authenticates every call would split- // this message from the status bar and the actual resolution.- if (resolution.shadowedOidc !== undefined) {- const from = resolution.source.kind === "shell" ? "shell" : resolution.source.path;- const remove =- resolution.source.kind === "shell"- ? "unset it in your shell"- : `remove it from ${resolution.source.path}`;- return (- `Project linked. AI_GATEWAY_API_KEY (${from}) outranks the project's ` +- `VERCEL_OIDC_TOKEN and stays the active credential — ${remove} to run on the project.`- );- }- return "Project linked. Connected to AI Gateway via AI_GATEWAY_API_KEY.";- }- if (status.kind === "gateway-key") {- const where = status.source.kind === "shell" ? "your shell" : status.source.path;- return `Connected to AI Gateway via ${status.envKey} in ${where}.`;- }- return "Provider updated — no gateway credential detected; set AI_GATEWAY_API_KEY in .env.local.";+function providerSelectionMessage(selection: ProviderSelection): string {+ if (selection === "chatgpt") return "ChatGPT subscription selected.";+ return selection === "ai-gateway-project"+ ? "AI Gateway via Project selected."+ : "AI Gateway via API key selected.";}diff --git a/packages/eve/src/cli/dev/tui/setup-issues.test.ts b/packages/eve/src/cli/dev/tui/setup-issues.test.tsindex ae8710af4..e5cee99b4 100644--- a/packages/eve/src/cli/dev/tui/setup-issues.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-issues.test.ts@@ -7,7 +7,7 @@ import {formatSetupIssuesLine,LOGIN_SETUP_ISSUE,orderedSetupIssues,- resolveModelProviderState,+ normalizeLocalModelEndpoint,type BootDetectionContext,} from "./setup-issues.js";@@ -109,7 +109,7 @@ describe("BOOT_DETECTIONS", () => {{ kind: "external", provider: "anthropic" },);- expect(resolveModelProviderState(info, { AI_GATEWAY_API_KEY: "key" })).toMatchObject({+ expect(normalizeLocalModelEndpoint(info, { AI_GATEWAY_API_KEY: "key" })).toMatchObject({agent: {model: {endpoint: { kind: "gateway", connected: true, credential: "api-key" },diff --git a/packages/eve/src/cli/dev/tui/setup-issues.ts b/packages/eve/src/cli/dev/tui/setup-issues.tsindex c6c3fe43f..378bf1e61 100644--- a/packages/eve/src/cli/dev/tui/setup-issues.ts+++ b/packages/eve/src/cli/dev/tui/setup-issues.ts@@ -51,7 +51,7 @@ type ModelProviderAccess =* loaded credential is usable even when an earlier `/info` response says* disconnected.*/-export function resolveModelProviderState(+export function normalizeLocalModelEndpoint(info: AgentInfoResult | undefined,env: Record<string, string | undefined>,): AgentInfoResult | undefined {diff --git a/packages/eve/src/cli/dev/tui/setup-panel.test.ts b/packages/eve/src/cli/dev/tui/setup-panel.test.tsindex 75a7d31e1..4eb491e08 100644--- a/packages/eve/src/cli/dev/tui/setup-panel.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-panel.test.ts@@ -569,7 +569,7 @@ describe("renderSelectQuestion", () => {it("keeps a long masked key's inline failure visible within a narrow panel", () => {const options = [{- value: "own-key",+ value: "ai-gateway-key",label: "AI Gateway via AI_GATEWAY_API_KEY",hint: "> type your key",},@@ -583,7 +583,7 @@ describe("renderSelectQuestion", () => {options,select: initialSelectState({ options }),edit: {- optionValue: "own-key",+ optionValue: "ai-gateway-key",caretVisible: false,editor: {kind: "key",@@ -646,7 +646,7 @@ describe("renderSelectQuestion", () => {it("stacks hints under labels with separators and trailing notices", () => {const options = [{ value: "model", label: "Change model", hint: "anthropic/claude-sonnet-5" },- { value: "provider", label: "Change provider", hint: "AI Gateway (Linked to my-agent)" },+ { value: "provider", label: "Change provider", hint: "AI Gateway via Project" },];const rows = renderSelectQuestion({@@ -667,7 +667,7 @@ describe("renderSelectQuestion", () => {" anthropic/claude-sonnet-5",""," ◦ Change provider",- " AI Gateway (Linked to my-agent)",+ " AI Gateway via Project",""," ✓ Model changed to openai/gpt-5.5","",@@ -710,7 +710,7 @@ describe("renderSelectQuestion", () => {{value: "provider",label: "Change provider",- hint: "AI Gateway (Linked to \x1b[1mmy-agent\x1b[22m)",+ hint: "Selected (\x1b[1mvalue\x1b[22m)",},];const text = renderSelectQuestion(@@ -726,7 +726,7 @@ describe("renderSelectQuestion", () => {// Bold's close (SGR 22) also ends dim — the renderer re-opens dim so the// hint's tail does not pop to full brightness.- expect(text).toContain("\x1b[1mmy-agent\x1b[22m\x1b[2m)");+ expect(text).toContain("\x1b[1mvalue\x1b[22m\x1b[2m)");});it("uses the terminal foreground for a selected yellow hint and dims it otherwise", () => {@@ -814,7 +814,7 @@ describe("renderSelectQuestion", () => {it("renders each line of a stacked hint beneath its option", () => {const options = [{- value: "project",+ value: "ai-gateway-project",label: "AI Gateway via Project",hint: "Authenticates with AI Gateway automatically\nin a new or existing project. No keys to manage.",},diff --git a/packages/eve/src/cli/dev/tui/status-line.test.ts b/packages/eve/src/cli/dev/tui/status-line.test.tsindex 5611bcee7..62c6ee8f4 100644--- a/packages/eve/src/cli/dev/tui/status-line.test.ts+++ b/packages/eve/src/cli/dev/tui/status-line.test.ts@@ -218,12 +218,20 @@ describe("buildStatusLine", () => {const chatgpt = buildStatusLine({model: "openai/gpt-5.6-sol",- endpoint: { kind: "external", provider: "codex" },+ endpoint: { kind: "chatgpt", state: "ready" },theme: plain,width: 120,});expect(chatgpt).toBe("openai/gpt-5.6-sol via chatgpt-sub⌝");+ const chatgptLogin = buildStatusLine({+ model: "openai/gpt-5.6-sol",+ endpoint: { kind: "chatgpt", state: "reauth-required" },+ theme: plain,+ width: 120,+ });+ expect(chatgptLogin).toBe("openai/gpt-5.6-sol ⚠ chatgpt-sub login · codex login");+const notConnected = buildStatusLine({model: "m",endpoint: { kind: "gateway", connected: false },@@ -264,13 +272,21 @@ describe("buildStatusLine", () => {});it("renders ASCII glyphs when unicode is unavailable", () => {- const line = buildStatusLine({+ const gateway = buildStatusLine({model: "m",endpoint: { kind: "gateway", connected: false },theme: ascii,width: 120,});- expect(stripAnsi(line!)).toBe("m ! ai-gateway");+ expect(stripAnsi(gateway!)).toBe("m ! ai-gateway");++ const chatgpt = buildStatusLine({+ model: "openai/gpt-5.6-sol",+ endpoint: { kind: "chatgpt", state: "ready" },+ theme: ascii,+ width: 120,+ });+ expect(stripAnsi(chatgpt!)).toBe("openai/gpt-5.6-sol via chatgpt-sub^");});it("renders the remote badge first and projects each authentication state", () => {diff --git a/packages/eve/src/cli/dev/tui/status-line.ts b/packages/eve/src/cli/dev/tui/status-line.tsindex 2f3b215f1..5ebb78799 100644--- a/packages/eve/src/cli/dev/tui/status-line.ts+++ b/packages/eve/src/cli/dev/tui/status-line.ts@@ -62,8 +62,8 @@ function renderServerPort(/** Provider slugs whose display name differs from the AI SDK's identifier. */const EXTERNAL_PROVIDER_DISPLAY_NAMES: Readonly<Record<string, string>> = {- // `experimental_chatgpt` wraps the Codex backend; what the user connected- // is their ChatGPT subscription, so the bar names that, not the transport.+ // `chatgpt()` wraps the Codex backend; what the user connected is their+ // ChatGPT subscription, so the bar names that, not the transport.codex: "chatgpt-sub",};@@ -94,6 +94,19 @@ function renderEndpoint(// intensity on any theme — while the clause around it is dim.return { text: `${c.dim(`via ${provider}`)}${g.external}`, standalone: false };}+ if (input.endpoint.kind === "chatgpt") {+ switch (input.endpoint.state) {+ case "ready":+ return { text: `${c.dim("via chatgpt-sub")}${g.external}`, standalone: false };+ case "checking":+ return { text: c.dim("chatgpt-sub checking…"), standalone: true };+ case "signed-out":+ case "reauth-required":+ return { text: c.yellow(`${g.warning} chatgpt-sub login · codex login`), standalone: true };+ case "unavailable":+ return { text: c.yellow(`${g.warning} chatgpt-sub unavailable`), standalone: true };+ }+ }if (!input.endpoint.connected) {return { text: c.yellow(`${g.warning} ai-gateway`), standalone: true };}diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.tsindex 00433dae5..8da7b9715 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts@@ -1657,6 +1657,20 @@ describe("TerminalRenderer (inline scrollback)", () => {expect(screen.snapshot()).toContain("\u23bf /model dismissed.");});+ it("strips complete ANSI styles from command outcomes", () => {+ const { screen, renderer } = makeRenderer();+ renderer.renderCommandResult(+ "Model changed to \u001b[1mchatgpt/gpt-5.6-sol\u001b[22m. Live on your next prompt.",+ );+ renderer.shutdown();++ expect(screen.snapshot()).toContain(+ "\u23bf Model changed to chatgpt/gpt-5.6-sol. Live on your next prompt.",+ );+ expect(screen.snapshot()).not.toContain("[1m");+ expect(screen.snapshot()).not.toContain("[22m");+ });+it("hangs a successful command outcome from an elbow into a full-intensity rail", () => {const { screen, renderer } = makeRenderer();renderer.renderCommandResult(@@ -3810,6 +3824,29 @@ describe("TerminalRenderer setup panel", () => {renderer.shutdown();});+ it("selects ChatGPT as a provider sibling", async () => {+ const { screen, input, renderer } = makeRenderer();++ const answer = renderer.setupFlow.readProviderPicker({+ message: "Provider",+ options: [+ { value: "ai-gateway-project", label: "AI Gateway via Project" },+ { value: "ai-gateway-key", label: "AI Gateway via AI_GATEWAY_API_KEY" },+ { value: "chatgpt", label: "ChatGPT subscription" },+ { value: "external", label: "Other providers" },+ ],+ initialValue: "ai-gateway-project",+ validateInlineKey: async () => ({ kind: "valid" }),+ });++ expect(screen.snapshot()).toContain("ChatGPT subscription");+ input.down();+ input.down();+ input.enter();+ await expect(answer).resolves.toEqual({ kind: "chatgpt" });+ renderer.shutdown();+ });+it("validates a masked key without replacing the provider frame", async () => {const { screen, input, renderer } = makeRenderer();let resolveValidation:@@ -3824,8 +3861,8 @@ describe("TerminalRenderer setup panel", () => {const answer = renderer.setupFlow.readProviderPicker({message: "Provider",- options: [{ value: "own-key", label: "AI Gateway via AI_GATEWAY_API_KEY" }],- initialValue: "own-key",+ options: [{ value: "ai-gateway-key", label: "AI Gateway via AI_GATEWAY_API_KEY" }],+ initialValue: "ai-gateway-key",validateInlineKey: validate,});@@ -3847,7 +3884,7 @@ describe("TerminalRenderer setup panel", () => {input.enter();resolveValidation?.({ kind: "valid" });await expect(answer).resolves.toEqual({- kind: "inline-key",+ kind: "ai-gateway-key",key: "bad-keyx",validation: { kind: "valid" },});@@ -3864,8 +3901,8 @@ describe("TerminalRenderer setup panel", () => {const { screen, input, renderer } = makeRenderer();const answer = renderer.setupFlow.readProviderPicker({message: "Provider",- options: [{ value: "own-key", label: "AI Gateway via AI_GATEWAY_API_KEY" }],- initialValue: "own-key",+ options: [{ value: "ai-gateway-key", label: "AI Gateway via AI_GATEWAY_API_KEY" }],+ initialValue: "ai-gateway-key",validateInlineKey: async () => ({ kind: "valid" }),});let settled = false;@@ -3895,8 +3932,8 @@ describe("TerminalRenderer setup panel", () => {const validations: Array<{ key: string; signal: AbortSignal; finish(): void }> = [];const answer = renderer.setupFlow.readProviderPicker({message: "Provider",- options: [{ value: "own-key", label: "AI Gateway key" }],- initialValue: "own-key",+ options: [{ value: "ai-gateway-key", label: "AI Gateway key" }],+ initialValue: "ai-gateway-key",validateInlineKey: (key, signal) => {return new Promise<{ kind: "valid" }>((resolve) => {validations.push({ key, signal, finish: () => resolve({ kind: "valid" }) });@@ -3918,7 +3955,7 @@ describe("TerminalRenderer setup panel", () => {await Promise.resolve();validations[1]?.finish();await expect(answer).resolves.toEqual({- kind: "inline-key",+ kind: "ai-gateway-key",key: "sk-second",validation: { kind: "valid" },});@@ -4055,7 +4092,7 @@ describe("TerminalRenderer setup panel", () => {});describe("TerminalRenderer setup flow session", () => {- it("restores the terminal while a child process inherits stdio", async () => {+ it("discards inherited subprocess output when restoring the transcript", async () => {const { screen, input, renderer } = makeRenderer();renderer.renderNotice("anchor");@@ -4064,11 +4101,15 @@ describe("TerminalRenderer setup flow session", () => {await renderer.setupFlow.withInheritedStdio(async () => {inherited = true;input.pause();+ screen.write("temporary OAuth instructions\n");+ expect(screen.snapshot()).toContain("temporary OAuth instructions");});expect(inherited).toBe(true);expect(input.resumeCalls).toBe(2);+ expect(screen.snapshot()).toContain("anchor");expect(screen.snapshot()).toContain("Add integration");+ expect(screen.snapshot()).not.toContain("temporary OAuth instructions");renderer.setupFlow.end();renderer.shutdown();});diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.tsindex f3a84b260..11d22cd70 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts@@ -1734,7 +1734,7 @@ export class TerminalRenderer implements AgentTUIRenderer {/** Commits one command outcome, promoting explicit status to a top-level result. */renderCommandResult(text: string, tone?: "success" | "error"): void {- const content = stripTerminalControls(text);+ const content = stripAnsi(text);if (content.trim().length === 0) return;this.#start();this.#pushBlock(@@ -2165,7 +2165,7 @@ export class TerminalRenderer implements AgentTUIRenderer {options: opts.options,select: interaction.select,edit: {- optionValue: "own-key",+ optionValue: "ai-gateway-key",caretVisible: this.#caretVisible,editor: { kind: "key", phase: interaction.phase },},@@ -2713,7 +2713,7 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#paint();}- /** Gives an interactive subprocess the real terminal, then restores the live region. */+ /** Gives an interactive subprocess a temporary screen, then restores the transcript. */async #withInheritedStdio<T>(task: () => Promise<T>): Promise<T> {// Setup questions can resolve from the first key in a buffered terminal// chunk. The remaining bytes belong to the child process, not the next@@ -2725,13 +2725,14 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#detachInput();this.#stopTicker();this.#live.clear();- this.#live.showCursor();this.#removeLogCapture();+ this.#altScreen.enter({ cursor: "visible", mouse: false });if (this.#input.isTTY) this.#input.setRawMode?.(false);this.#input.pause();try {return await task();} finally {+ this.#altScreen.exit();if (this.#input.isTTY) this.#input.setRawMode?.(true);// The parent stream must remain paused while the child owns the terminal.// Resume only after its raw mode and key consumer are ready again.diff --git a/packages/eve/src/cli/ui/alt-screen.test.ts b/packages/eve/src/cli/ui/alt-screen.test.tsindex fa731a158..1e3bdb695 100644--- a/packages/eve/src/cli/ui/alt-screen.test.ts+++ b/packages/eve/src/cli/ui/alt-screen.test.ts@@ -31,6 +31,16 @@ describe("AltScreen", () => {expect(screen.active).toBe(false);});+ it("can leave the cursor visible without claiming mouse input", () => {+ const { writes, output } = collectingOutput();+ const screen = new AltScreen(output);++ screen.enter({ cursor: "visible", mouse: false });+ screen.exit();++ expect(writes.join("")).toBe("\x1b[?1049h\x1b[?25h\x1b[?25h\x1b[?1049l");+ });+it("paints frames with absolute row positions, clipped to the height", () => {const { writes, output } = collectingOutput();const screen = new AltScreen(output);diff --git a/packages/eve/src/cli/ui/alt-screen.ts b/packages/eve/src/cli/ui/alt-screen.tsindex ca7ee5ff6..42ce9190a 100644--- a/packages/eve/src/cli/ui/alt-screen.ts+++ b/packages/eve/src/cli/ui/alt-screen.ts@@ -1,5 +1,5 @@/**- * Alternate-screen mode for full-screen modal views (the `/traces` viewer).+ * Alternate-screen mode for temporary full-screen terminal ownership.** The dev TUI's transcript deliberately streams into native scrollback (see* `live-region.ts`), but a modal viewer wants the whole terminal without@@ -29,9 +29,17 @@ export interface AltScreenOutput {write(chunk: string): boolean;}+export interface AltScreenEnterOptions {+ /** Interactive subprocesses need the terminal cursor; rendered views do not. */+ cursor?: "hidden" | "visible";+ /** Rendered views use mouse events; inherited subprocesses retain native selection. */+ mouse?: boolean;+}+export class AltScreen {readonly #write: (chunk: string) => boolean;#active = false;+ #mouse = false;constructor(output: AltScreenOutput) {this.#write = output.write.bind(output);@@ -41,10 +49,15 @@ export class AltScreen {return this.#active;}- /** Switches to the alternate buffer, hides the cursor, enables SGR mouse. */- enter(): void {+ /** Switches to the alternate buffer with view-friendly defaults. */+ enter(options: AltScreenEnterOptions = {}): void {if (this.#active) return;- this.#write(`${ALT_SCREEN_ON}${HIDE_CURSOR}${MOUSE_ON}`);+ const mouse = options.mouse ?? true;+ const cursor = options.cursor ?? "hidden";+ this.#write(+ `${ALT_SCREEN_ON}${cursor === "hidden" ? HIDE_CURSOR : SHOW_CURSOR}${mouse ? MOUSE_ON : ""}`,+ );+ this.#mouse = mouse;this.#active = true;}@@ -79,7 +92,8 @@ export class AltScreen {/** Restores the main screen, cursor, and mouse reporting. */exit(): void {if (!this.#active) return;- this.#write(`${MOUSE_OFF}${SHOW_CURSOR}${ALT_SCREEN_OFF}`);+ this.#write(`${this.#mouse ? MOUSE_OFF : ""}${SHOW_CURSOR}${ALT_SCREEN_OFF}`);+ this.#mouse = false;this.#active = false;}}diff --git a/packages/eve/src/client/agent-info-schema.ts b/packages/eve/src/client/agent-info-schema.tsindex 5ee82a23d..abd7038b4 100644--- a/packages/eve/src/client/agent-info-schema.ts+++ b/packages/eve/src/client/agent-info-schema.ts@@ -16,6 +16,11 @@ const modelRouting = z.discriminatedUnion("kind", [const modelEndpoint = z.union([z.object({ kind: z.literal("external"), provider: z.string() }),+ z.object({+ kind: z.literal("chatgpt"),+ state: z.enum(["checking", "ready", "signed-out", "reauth-required", "unavailable"]),+ accountLabel: z.string().optional(),+ }),z.object({kind: z.literal("gateway"),connected: z.literal(true),diff --git a/packages/eve/src/compiler/normalize-agent-config.test.ts b/packages/eve/src/compiler/normalize-agent-config.test.tsindex 0c06e3e48..49a86469e 100644--- a/packages/eve/src/compiler/normalize-agent-config.test.ts+++ b/packages/eve/src/compiler/normalize-agent-config.test.ts@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { createAgentSourceManifest, createModuleSourceRef } from "#discover/manifest.js";import { defineDynamic } from "#public/definitions/tool.js";+import { chatgpt } from "#public/models/openai/index.js";import { compileAgentConfig } from "#compiler/normalize-agent-config.js";import type { ManifestCompileContext } from "#compiler/normalize-helpers.js";@@ -52,6 +53,29 @@ describe("compileAgentConfig", () => {expect(modelCatalog.getModelLimits).not.toHaveBeenCalled();});+ it("compiles an eve-owned Codex model without AI Gateway metadata", async () => {+ mocks.loadModuleBackedDefinition.mockResolvedValue({ model: chatgpt("gpt-5.6-sol") });+ const manifest = createAgentSourceManifest({+ agentId: "app",+ agentRoot: "/app/agent",+ appRoot: "/app",+ configModule: createModuleSourceRef({ logicalPath: "agent.ts", sourceId: "agent-config" }),+ });+ const modelCatalog = createModelCatalog();++ const compiled = await compileAgentConfig(manifest, { modelCatalog });++ expect(compiled.model).toEqual(+ expect.objectContaining({+ id: "codex/gpt-5.6-sol",+ routing: { kind: "external", provider: "codex" },+ contextWindowTokens: 200_000,+ }),+ );+ expect(modelCatalog.getByProviderModelId).not.toHaveBeenCalled();+ expect(modelCatalog.getModelLimits).not.toHaveBeenCalled();+ });+it("compiles an injected agent definition without reloading agent.ts", async () => {const manifest = createAgentSourceManifest({agentId: "researcher",diff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.tsindex 3d69c76d2..e511a2863 100644--- a/packages/eve/src/compiler/normalize-agent-config.ts+++ b/packages/eve/src/compiler/normalize-agent-config.ts@@ -6,6 +6,7 @@ import { normalizeAgentDefinition } from "#internal/authored-definition/core.js"import { serializeOutputSchema } from "#shared/tool-schema.js";import { formatLanguageModelGatewayId } from "#internal/runtime-model.js";import { classifyModelRouting } from "#internal/classify-model-routing.js";+import { isChatGptModelRouting } from "#shared/chatgpt-model.js";import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";import { toErrorMessage } from "#shared/errors.js";import { parseJsonObject, type JsonObject } from "#shared/json.js";@@ -272,6 +273,14 @@ async function normalizeAuthoredModelReference(input: {};if (input.contextWindowTokens === undefined) {+ // Codex models have no Gateway catalog entry, so use eve's known context limit.+ if (isChatGptModelRouting(sourceBackedModel.routing)) {+ return {+ ...sourceBackedModel,+ contextWindowTokens: 200_000,+ };+ }+try {const providerResult = await input.modelCatalog.getByProviderModelId(languageModel.provider,diff --git a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.tsindex 65055de97..bac8fa316 100644--- a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts+++ b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts@@ -203,7 +203,7 @@ describe("startAuthoredSourceWatcher", () => {}});- it("watches root config, env, workspace lockfiles, and tsconfig extends", async () => {+ it("watches root config, provider selection, env, workspace lockfiles, and tsconfig extends", async () => {const workspaceRoot = await mkdtemp(join(tmpdir(), "eve-dev-watch-root-"));const appRoot = join(workspaceRoot, "apps", "watch-agent");temporaryDirectories.push(workspaceRoot);@@ -225,6 +225,7 @@ describe("startAuthoredSourceWatcher", () => {const paths = getInitialWatchPaths();expect(paths).toContain(join(appRoot, "package.json"));expect(paths).toContain(join(appRoot, ".env.local"));+ expect(paths).toContain(join(appRoot, ".eve", "provider.json"));expect(paths).toContain(join(workspaceRoot, "pnpm-lock.yaml"));expect(paths).toContain(join(workspaceRoot, "tsconfig.base.json"));} finally {diff --git a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.ts b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.tsindex 1623c45f9..8edba3543 100644--- a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.ts+++ b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.ts@@ -8,6 +8,7 @@ import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/tyimport type { DevelopmentWorkspaceExtension } from "#internal/nitro/host/dev-workspace-extensions.js";import type { DevelopmentAuthoredRebuildCoordinator } from "#internal/nitro/host/dev-authored-rebuild-coordinator.js";import { getDevelopmentEnvironmentFilePaths } from "#cli/dev/environment.js";+import { providerSettingsPath } from "#setup/provider-settings.js";import {AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,@@ -76,7 +77,8 @@ export async function startAuthoredSourceWatcher(input: {},followSymlinks: false,ignoreInitial: true,- ignored: (path) => shouldIgnoreWatcherPath(path, currentHost.workspaceExtensions),+ ignored: (path) =>+ shouldIgnoreWatcherPath(path, currentHost.appRoot, currentHost.workspaceExtensions),});const watcherReady = waitForWatcherReady(watcher);@@ -217,6 +219,7 @@ async function resolveAuthoredWatchPaths(join(host.appRoot, "jsconfig.json"),join(host.appRoot, "tsconfig.json"),join(host.appRoot, TS_CONFIG_GLOB_NAME),+ providerSettingsPath(host.appRoot),]);const tsconfigPaths = await resolveTsConfigWatchPaths(host.appRoot);const sourceSnapshotWatchPaths = await resolveDevelopmentSourceSnapshotWatchPaths(host.appRoot);@@ -329,12 +332,15 @@ async function resolveTsConfigWatchPaths(appRoot: string): Promise<string[]> {function shouldIgnoreWatcherPath(path: string,+ appRoot: string,workspaceExtensions: readonly DevelopmentWorkspaceExtension[],): boolean {- const pathParts = normalize(path).split(sep).filter(Boolean);+ const normalizedPath = normalize(path);+ const pathParts = normalizedPath.split(sep).filter(Boolean);+ const isProviderSettings = normalizedPath === normalize(providerSettingsPath(appRoot));return (- pathParts.some((part) => WATCHER_IGNORED_DIRECTORY_NAMES.has(part)) ||+ (!isProviderSettings && pathParts.some((part) => WATCHER_IGNORED_DIRECTORY_NAMES.has(part))) ||workspaceExtensions.some((extension) => isPathInsideOrEqual(path, extension.config.outDir)));}diff --git a/packages/eve/src/internal/nitro/host/dev-environment-watcher.integration.test.ts b/packages/eve/src/internal/nitro/host/dev-environment-watcher.integration.test.tsindex 35e8001fa..3960e281e 100644--- a/packages/eve/src/internal/nitro/host/dev-environment-watcher.integration.test.ts+++ b/packages/eve/src/internal/nitro/host/dev-environment-watcher.integration.test.ts@@ -1,10 +1,11 @@-import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import {loadDevelopmentEnvironmentFiles,+ readDevelopmentEnvironmentHostValues,stageDevelopmentEnvironmentFiles,} from "#cli/dev/environment.js";@@ -13,6 +14,7 @@ const ENV_KEYS = ["EVE_WATCH_ENV_NEW","EVE_WATCH_ENV_SHARED","EVE_WATCH_ENV_SHELL",+ "AI_GATEWAY_API_KEY",] as const;const temporaryDirectories: string[] = [];@@ -39,6 +41,35 @@ describe("development environment reload transactions", () => {expect(process.env.EVE_WATCH_ENV_SHELL).toBe("from-parent");});+ it("honors the persisted Gateway credential selection over available keys", async () => {+ const appRoot = await createEnvironmentApp();+ await writeFile(join(appRoot, ".env.local"), "AI_GATEWAY_API_KEY=from-file\n");+ await mkdir(join(appRoot, ".eve"));+ await writeFile(join(appRoot, ".eve", "provider.json"), '{"selected":"ai-gateway-project"}\n');++ loadDevelopmentEnvironmentFiles(appRoot);+ expect(process.env.AI_GATEWAY_API_KEY).toBeUndefined();++ await writeFile(join(appRoot, ".eve", "provider.json"), '{"selected":"ai-gateway-key"}\n');+ loadDevelopmentEnvironmentFiles(appRoot);+ expect(process.env.AI_GATEWAY_API_KEY).toBe("from-file");+ });++ it("fingerprints suppression of a shell Gateway key for Project OIDC", async () => {+ const appRoot = await createEnvironmentApp();+ process.env.AI_GATEWAY_API_KEY = "from-parent";++ loadDevelopmentEnvironmentFiles(appRoot);+ expect(readDevelopmentEnvironmentHostValues(appRoot).AI_GATEWAY_API_KEY).toBe("from-parent");++ await mkdir(join(appRoot, ".eve"));+ await writeFile(join(appRoot, ".eve", "provider.json"), '{"selected":"ai-gateway-project"}\n');+ loadDevelopmentEnvironmentFiles(appRoot);++ expect(process.env.AI_GATEWAY_API_KEY).toBeUndefined();+ expect(readDevelopmentEnvironmentHostValues(appRoot).AI_GATEWAY_API_KEY).toBeNull();+ });+it("restores the complete prior environment when a candidate is rejected", async () => {const appRoot = await createEnvironmentApp();const envLocalPath = join(appRoot, ".env.local");diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.tsindex 2861a1d77..b4ba86fa5 100644--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.ts+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.ts@@ -27,12 +27,23 @@ import {type GatewayCredentialPresence,resolveModelEndpointStatus,} from "#internal/resolve-model-endpoint-status.js";+import type { ChatGptAuthState } from "#public/models/openai/chatgpt/token-broker.js";++function toChatGptEndpoint(state: ChatGptAuthState | undefined) {+ if (state === undefined) return undefined;+ return {+ state: state.kind,+ ...(state.kind === "ready" &&+ state.accountLabel !== undefined && { accountLabel: state.accountLabel }),+ };+}export function buildAgentInfoResponseFromManifest(data: AgentInfoManifestData,input: {readonly mode: AgentInfoResponse["mode"];readonly gatewayCredentials: GatewayCredentialPresence;+ readonly chatgptAuth?: ChatGptAuthState;},): AgentInfoResponse {const manifest = data.manifest;@@ -100,6 +111,7 @@ export function buildAgentInfoResponseFromManifest(endpoint: resolveModelEndpointStatus(manifest.config.model.routing,input.gatewayCredentials,+ toChatGptEndpoint(input.chatgptAuth),),}: {diff --git a/packages/eve/src/internal/nitro/routes/info.test.ts b/packages/eve/src/internal/nitro/routes/info.test.tsindex 7c7f40596..cf81fb7d8 100644--- a/packages/eve/src/internal/nitro/routes/info.test.ts+++ b/packages/eve/src/internal/nitro/routes/info.test.ts@@ -3,7 +3,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({buildAgentInfoResponseFromManifest: vi.fn(() => ({ kind: "eve-agent-info", version: 2 })),getVercelOidcToken: vi.fn(),- loadAgentInfoManifestData: vi.fn(async () => ({+ refreshChatGptState: vi.fn(async () => ({ kind: "ready" as const })),+ loadAgentInfoManifestData: vi.fn(async (): Promise<unknown> => ({manifest: {config: {model: {@@ -23,6 +24,10 @@ vi.mock("#compiled/@vercel/oidc/index.js", () => ({getVercelOidcToken: mocks.getVercelOidcToken,}));+vi.mock("#public/models/openai/chatgpt/token-broker.js", () => ({+ getDefaultCodexTokenBroker: () => ({ refreshState: mocks.refreshChatGptState }),+}));+vi.mock("#internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js", () => ({buildAgentInfoResponseFromManifest: mocks.buildAgentInfoResponseFromManifest,}));@@ -50,6 +55,17 @@ const GATEWAY_MANIFEST_DATA = {schedules: [],};+const CHATGPT_MANIFEST_DATA = {+ manifest: {+ config: {+ model: {+ routing: { kind: "external" as const, provider: "codex" },+ },+ },+ },+ schedules: [],+};+async function requestAgentInfo(): Promise<Response> {const { handleAgentInfoRequest } = await import("#internal/nitro/routes/info.js");@@ -63,6 +79,7 @@ describe("handleAgentInfoRequest", () => {mocks.buildAgentInfoResponseFromManifest.mockClear();mocks.getVercelOidcToken.mockReset();mocks.getVercelOidcToken.mockRejectedValue(new Error("not linked"));+ mocks.refreshChatGptState.mockClear();mocks.loadAgentInfoManifestData.mockReset();mocks.loadAgentInfoManifestData.mockResolvedValue(GATEWAY_MANIFEST_DATA);mocks.resolveAgentInfoCompiledArtifactsSource.mockClear();@@ -115,4 +132,19 @@ describe("handleAgentInfoRequest", () => {});expect(mocks.getVercelOidcToken).not.toHaveBeenCalled();});++ it("preflights ChatGPT auth for Codex-backed models", async () => {+ mocks.loadAgentInfoManifestData.mockResolvedValue(CHATGPT_MANIFEST_DATA);++ const response = await requestAgentInfo();++ expect(response.status).toBe(200);+ expect(mocks.refreshChatGptState).toHaveBeenCalledOnce();+ expect(mocks.buildAgentInfoResponseFromManifest).toHaveBeenCalledWith(CHATGPT_MANIFEST_DATA, {+ mode: "development",+ gatewayCredentials: { apiKey: false, oidc: false },+ chatgptAuth: { kind: "ready" },+ });+ expect(mocks.getVercelOidcToken).not.toHaveBeenCalled();+ });});diff --git a/packages/eve/src/internal/nitro/routes/info.ts b/packages/eve/src/internal/nitro/routes/info.tsindex 39df13b5e..868e3f90f 100644--- a/packages/eve/src/internal/nitro/routes/info.ts+++ b/packages/eve/src/internal/nitro/routes/info.ts@@ -7,19 +7,28 @@ import {} from "#internal/nitro/routes/agent-info/load-agent-info-data.js";import type { GatewayCredentialPresence } from "#internal/resolve-model-endpoint-status.js";import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";+import { getDefaultCodexTokenBroker } from "#public/models/openai/chatgpt/token-broker.js";import type { ModelRouting } from "#shared/agent-definition.js";+import { isChatGptModelRouting } from "#shared/chatgpt-model.js";async function createAgentInfoPayload(input: NitroArtifactsConfig) {const data = await loadAgentInfoManifestData({compiledArtifactsSource: resolveAgentInfoCompiledArtifactsSource(input),});+ const routing =+ data.manifest.config.dynamicModel === undefined+ ? data.manifest.config.model.routing+ : undefined;return buildAgentInfoResponseFromManifest(data, {mode: input.kind,gatewayCredentials:- data.manifest.config.dynamicModel === undefined- ? await resolveGatewayCredentialPresence(data.manifest.config.model.routing)- : { apiKey: false, oidc: false },+ routing === undefined+ ? { apiKey: false, oidc: false }+ : await resolveGatewayCredentialPresence(routing),+ ...(isChatGptModelRouting(routing)+ ? { chatgptAuth: await getDefaultCodexTokenBroker().refreshState() }+ : {}),});}diff --git a/packages/eve/src/internal/resolve-model-endpoint-status.test.ts b/packages/eve/src/internal/resolve-model-endpoint-status.test.tsindex c589ccb8a..6f61547d3 100644--- a/packages/eve/src/internal/resolve-model-endpoint-status.test.ts+++ b/packages/eve/src/internal/resolve-model-endpoint-status.test.ts@@ -15,6 +15,16 @@ describe("resolveModelEndpointStatus", () => {).toEqual({ kind: "external", provider: "anthropic" });});+ it("reports brokered ChatGPT readiness for the Codex provider", () => {+ expect(+ resolveModelEndpointStatus(+ { kind: "external", provider: "codex" },+ { apiKey: false, oidc: false },+ { state: "reauth-required" },+ ),+ ).toEqual({ kind: "chatgpt", state: "reauth-required" });+ });+it("reports gateway connected via api-key, which outranks oidc", () => {expect(resolveModelEndpointStatus(@@ -50,15 +60,13 @@ describe("resolveGatewayCredential", () => {).toEqual({credential: "api-key",source: { kind: "env-file", path: ".env.local" },- shadowedOidc: { file: ".env" },});});- it("ranks a shell key over the OIDC token it shadows", () => {+ it("ranks a shell key over an OIDC token", () => {expect(resolveGatewayCredential({ apiKeyInEnv: true, oidcAvailable: true })).toEqual({credential: "api-key",source: { kind: "shell" },- shadowedOidc: {},});});diff --git a/packages/eve/src/internal/resolve-model-endpoint-status.ts b/packages/eve/src/internal/resolve-model-endpoint-status.tsindex b1f9e3c0a..e7d3cef91 100644--- a/packages/eve/src/internal/resolve-model-endpoint-status.ts+++ b/packages/eve/src/internal/resolve-model-endpoint-status.ts@@ -1,5 +1,6 @@import type { ModelRouting } from "#shared/agent-definition.js";-import type { ModelEndpointStatus } from "#shared/model-endpoint-status.js";+import { isChatGptModelRouting } from "#shared/chatgpt-model.js";+import type { ChatGptEndpointState, ModelEndpointStatus } from "#shared/model-endpoint-status.js";/*** Presence of the two gateway credentials, read from wherever the caller can@@ -42,19 +43,10 @@ export type GatewayCredentialResolution =credential: "api-key";/** Where the winning key lives; a shell export is not eve's to remove. */source: GatewayCredentialSource;- /** Present when an OIDC token exists that the key shadows. */- shadowedOidc?: { file?: string };}| { credential: "oidc"; file?: string };-/**- * THE one encoding of gateway credential precedence: `AI_GATEWAY_API_KEY`- * (env file first for attribution, then the shell) outranks the OIDC token,- * exactly as the AI SDK gateway provider resolves them. Every surface that- * reports or ranks gateway credentials — the endpoint status, the /model- * provider row, the link outcome, boot detection — must route through this- * function so they can never disagree.- */+/** Ranks Gateway credentials using runtime precedence. */export function resolveGatewayCredential(evidence: GatewayCredentialEvidence,): GatewayCredentialResolution | undefined {@@ -67,11 +59,7 @@ export function resolveGatewayCredential(const hasOidc = evidence.oidcFile !== undefined || evidence.oidcAvailable === true;if (source !== undefined) {- const resolution: GatewayCredentialResolution = { credential: "api-key", source };- if (hasOidc) {- resolution.shadowedOidc = evidence.oidcFile === undefined ? {} : { file: evidence.oidcFile };- }- return resolution;+ return { credential: "api-key", source };}if (hasOidc) {return evidence.oidcFile === undefined@@ -91,8 +79,15 @@ export function resolveGatewayCredential(export function resolveModelEndpointStatus(routing: ModelRouting,credentials: GatewayCredentialPresence,+ chatgpt?: {+ readonly state: ChatGptEndpointState;+ readonly accountLabel?: string;+ },): ModelEndpointStatus {if (routing.kind === "external") {+ if (isChatGptModelRouting(routing) && chatgpt !== undefined) {+ return { kind: "chatgpt", ...chatgpt };+ }return { kind: "external", provider: routing.provider };}const resolution = resolveGatewayCredential({diff --git a/packages/eve/src/public/models/openai/chatgpt/auth.test.ts b/packages/eve/src/public/models/openai/chatgpt/auth.test.tsindex 2b58e0db0..e14cebf8a 100644--- a/packages/eve/src/public/models/openai/chatgpt/auth.test.ts+++ b/packages/eve/src/public/models/openai/chatgpt/auth.test.ts@@ -1,114 +1,13 @@import { describe, expect, it } from "vitest";import {- assertCodexAuthStateAuthenticated,- parseCodexAuth,+ extractCodexAccountIdFromToken,+ extractCodexAccountLabelFromToken,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" });- });-+describe("Codex token metadata", () => {it("reads JWT expiry without exposing token contents", () => {const token = createUnsignedJwt({ exp: 1_783_405_980 });@@ -116,32 +15,35 @@ describe("Codex auth state", () => {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");+ it("reads a human account label from explicit email or an email-shaped subject suffix", () => {+ expect(+ extractCodexAccountLabelFromToken(createUnsignedJwt({ email: "[email protected]" })),+ ).toBe("[email protected]");+ expect(+ extractCodexAccountLabelFromToken(+ createUnsignedJwt({ sub: "samlp|profile-id|[email protected]" }),+ ),+ ).toBe("[email protected]");+ expect(+ extractCodexAccountLabelFromToken(createUnsignedJwt({ sub: "opaque-user-id" })),+ ).toBeUndefined();+ });++ it("reads the ChatGPT account from supported claim shapes", () => {+ expect(+ extractCodexAccountIdFromToken(createUnsignedJwt({ chatgpt_account_id: "acct-direct" })),+ ).toBe("acct-direct");+ expect(+ extractCodexAccountIdFromToken(+ createUnsignedJwt({+ "https://api.openai.com/auth": { chatgpt_account_id: "acct-auth" },+ }),+ ),+ ).toBe("acct-auth");+ expect(+ extractCodexAccountIdFromToken(+ createUnsignedJwt({ organizations: [{ id: "acct-organization" }] }),+ ),+ ).toBe("acct-organization");});});diff --git a/packages/eve/src/public/models/openai/chatgpt/auth.ts b/packages/eve/src/public/models/openai/chatgpt/auth.tsindex 5ca7423bb..38ff8dee8 100644--- a/packages/eve/src/public/models/openai/chatgpt/auth.ts+++ b/packages/eve/src/public/models/openai/chatgpt/auth.ts@@ -1,353 +1,12 @@-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;@@ -362,6 +21,30 @@ export function extractCodexAccountIdFromToken(token: string | undefined): strin);}+/** Human-readable account label from Codex's JWT, without retaining the token. */+export function extractCodexAccountLabelFromToken(token: string | undefined): string | undefined {+ const claims = parseCodexJwtClaims(token);+ if (claims === undefined) return undefined;+ const authClaims = claims["https://api.openai.com/auth"];+ const explicit =+ readEmail(claims.email) ?? readEmail(isObject(authClaims) ? authClaims.email : undefined);+ if (explicit !== undefined) return explicit;++ const subject = readNonEmptyString(claims.sub);+ return subject === undefined ? undefined : readEmail(subject.split("|").at(-1));+}++function readEmail(value: unknown): string | undefined {+ const candidate = readNonEmptyString(value);+ return candidate !== undefined && /^[^@\s]+@[^@\s]+\.[^@\s]+$/u.test(candidate)+ ? candidate+ : undefined;+}++function readNonEmptyString(value: unknown): string | undefined {+ return typeof value === "string" && value.trim() !== "" ? value : undefined;+}+function parseCodexJwtClaims(token: string | undefined): Record<string, unknown> | undefined {if (token === undefined) return undefined;try {diff --git a/packages/eve/src/public/models/openai/chatgpt/codex-app-server.test.ts b/packages/eve/src/public/models/openai/chatgpt/codex-app-server.test.tsnew file mode 100644index 000000000..8d28383e7--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/codex-app-server.test.ts@@ -0,0 +1,98 @@+import { EventEmitter } from "node:events";+import { PassThrough } from "node:stream";++import { describe, expect, it, vi } from "vitest";++import { CodexAppServerClient, type CodexAppServerProcess } from "./codex-app-server.js";++describe("Codex app-server client", () => {+ it("initializes once and requests an auth token without exposing it", async () => {+ const child = new FakeChild();+ const client = new CodexAppServerClient({+ spawnProcess: vi.fn(() => child.asChildProcess()),+ });++ const status = await client.getAuthStatus({ refreshToken: true });++ expect(status).toEqual({+ authMethod: "chatgpt",+ authToken: "secret-token",+ requiresOpenaiAuth: true,+ });+ expect(child.requests.map((request) => request.method)).toEqual([+ "initialize",+ "initialized",+ "getAuthStatus",+ ]);+ expect(child.requests[2]?.params).toEqual({ includeToken: true, refreshToken: true });+ });++ it("reports a missing Codex binary with actionable guidance", async () => {+ const child = new FakeChild({+ failWith: Object.assign(new Error("spawn codex ENOENT"), { code: "ENOENT" }),+ });+ const client = new CodexAppServerClient({+ spawnProcess: vi.fn(() => child.asChildProcess()),+ });++ await expect(client.getAuthStatus({ refreshToken: false })).rejects.toThrow(+ "requires the Codex CLI",+ );+ });+});++interface RpcRequest {+ readonly id?: number;+ readonly method: string;+ readonly params?: unknown;+}++class FakeChild extends EventEmitter {+ readonly stdin = new PassThrough();+ readonly stdout = new PassThrough();+ readonly stderr = new PassThrough();+ readonly requests: RpcRequest[] = [];+ readonly #failWith?: Error;+ #input = "";++ constructor(options: { readonly failWith?: Error } = {}) {+ super();+ this.#failWith = options.failWith;+ this.stdin.on("data", (chunk: Buffer) => this.#receive(chunk.toString()));+ queueMicrotask(() => {+ if (this.#failWith !== undefined) this.emit("error", this.#failWith);+ });+ }++ asChildProcess(): CodexAppServerProcess {+ return this;+ }++ kill(): boolean {+ return true;+ }++ unref(): void {}++ #receive(chunk: string): void {+ this.#input += chunk;+ while (true) {+ const newline = this.#input.indexOf("\n");+ if (newline < 0) return;+ const line = this.#input.slice(0, newline);+ this.#input = this.#input.slice(newline + 1);+ const request = JSON.parse(line) as RpcRequest;+ this.requests.push(request);+ if (request.id === undefined) continue;+ const result =+ request.method === "initialize"+ ? { codexHome: "/tmp/codex" }+ : {+ authMethod: "chatgpt",+ authToken: "secret-token",+ requiresOpenaiAuth: true,+ };+ this.stdout.write(`${JSON.stringify({ id: request.id, result })}\n`);+ }+ }+}diff --git a/packages/eve/src/public/models/openai/chatgpt/codex-app-server.ts b/packages/eve/src/public/models/openai/chatgpt/codex-app-server.tsnew file mode 100644index 000000000..1a7f2c8c6--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/codex-app-server.ts@@ -0,0 +1,253 @@+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import { createInterface, type Interface } from "node:readline";++import { isObject } from "#shared/guards.js";++interface RpcError {+ readonly code?: number;+ readonly message?: string;+}++interface RpcResponse {+ readonly error?: RpcError;+ readonly id?: number;+ readonly result?: unknown;+}++export interface CodexAuthStatus {+ readonly authMethod?: string;+ readonly authToken?: string;+ readonly requiresOpenaiAuth?: boolean;+}++export interface CodexAppServer {+ getAuthStatus(input: { readonly refreshToken: boolean }): Promise<CodexAuthStatus>;+ restart?(): void;+}++export interface CodexAppServerProcess {+ readonly stderr: ChildProcessWithoutNullStreams["stderr"];+ readonly stdin: ChildProcessWithoutNullStreams["stdin"];+ readonly stdout: ChildProcessWithoutNullStreams["stdout"];+ kill(): boolean;+ once(event: "error", listener: (error: Error) => void): this;+ once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;+ unref(): void;+}++type SpawnCodexAppServer = (+ command: string,+ args: readonly string[],+ options: {+ readonly env?: NodeJS.ProcessEnv;+ stdio: ["pipe", "pipe", "pipe"];+ },+) => CodexAppServerProcess;++export interface CodexAppServerOptions {+ readonly command?: string;+ readonly env?: NodeJS.ProcessEnv;+ readonly spawnProcess?: SpawnCodexAppServer;+}++/** Minimal authenticated subset of Codex's JSONL app-server protocol. */+export class CodexAppServerClient implements CodexAppServer {+ readonly #command: string;+ readonly #env: NodeJS.ProcessEnv | undefined;+ readonly #spawnProcess: SpawnCodexAppServer;+ #connection: Promise<CodexAppServerConnection> | undefined;++ constructor(options: CodexAppServerOptions = {}) {+ this.#command = options.command ?? "codex";+ this.#env = options.env;+ this.#spawnProcess = options.spawnProcess ?? spawnCodexAppServer;+ }++ async getAuthStatus(input: { readonly refreshToken: boolean }): Promise<CodexAuthStatus> {+ const connection = await this.#connect();+ try {+ return await connection.getAuthStatus(input);+ } catch (error) {+ if (connection.exited) this.#connection = undefined;+ throw error;+ }+ }++ restart(): void {+ const connection = this.#connection;+ this.#connection = undefined;+ void connection?.then((value) => value.close()).catch(() => undefined);+ }++ #connect(): Promise<CodexAppServerConnection> {+ if (this.#connection === undefined) {+ this.#connection = CodexAppServerConnection.start({+ command: this.#command,+ env: this.#env,+ spawnProcess: this.#spawnProcess,+ }).catch((error: unknown) => {+ this.#connection = undefined;+ throw error;+ });+ }+ return this.#connection;+ }+}++class CodexAppServerConnection {+ readonly #child: CodexAppServerProcess;+ readonly #lines: Interface;+ readonly #pending = new Map<+ number,+ { readonly reject: (error: Error) => void; readonly resolve: (value: unknown) => void }+ >();+ #nextId = 1;+ #exited = false;+ #failure: Error | undefined;++ private constructor(child: CodexAppServerProcess) {+ this.#child = child;+ // The broker must not keep the agent runtime alive during normal shutdown.+ child.unref();+ unrefStream(child.stdin);+ unrefStream(child.stdout);+ unrefStream(child.stderr);+ child.stderr.resume();+ this.#lines = createInterface({ input: child.stdout });+ this.#lines.on("line", (line) => this.#handleLine(line));+ child.once("error", (error) => this.#fail(error));+ child.once("exit", (code, signal) => {+ const suffix = signal === null ? `code ${code ?? "unknown"}` : `signal ${signal}`;+ this.#fail(new Error(`Codex app-server exited with ${suffix}.`));+ });+ }++ get exited(): boolean {+ return this.#exited;+ }++ close(): void {+ this.#child.kill();+ this.#fail(new Error("Codex app-server connection was restarted."));+ }++ static async start(input: {+ readonly command: string;+ readonly env?: NodeJS.ProcessEnv;+ readonly spawnProcess: SpawnCodexAppServer;+ }): Promise<CodexAppServerConnection> {+ let child: CodexAppServerProcess;+ try {+ child = input.spawnProcess(input.command, ["app-server", "--stdio"], {+ env: input.env,+ stdio: ["pipe", "pipe", "pipe"],+ });+ } catch (error) {+ throw codexUnavailableError(error);+ }++ const connection = new CodexAppServerConnection(child);+ try {+ await connection.#request("initialize", {+ capabilities: null,+ clientInfo: { name: "eve", title: "eve", version: "0.35.0" },+ });+ connection.#notify("initialized", {});+ return connection;+ } catch (error) {+ child.kill();+ throw error;+ }+ }++ async getAuthStatus(input: { readonly refreshToken: boolean }): Promise<CodexAuthStatus> {+ const value = await this.#request("getAuthStatus", {+ includeToken: true,+ refreshToken: input.refreshToken,+ });+ if (!isObject(value)) {+ throw new Error("Codex app-server returned an invalid authentication response.");+ }+ return {+ ...(typeof value.authMethod === "string" && { authMethod: value.authMethod }),+ ...(typeof value.authToken === "string" && { authToken: value.authToken }),+ ...(typeof value.requiresOpenaiAuth === "boolean" && {+ requiresOpenaiAuth: value.requiresOpenaiAuth,+ }),+ };+ }++ #request(method: string, params: unknown): Promise<unknown> {+ if (this.#exited) {+ return Promise.reject(this.#failure ?? new Error("Codex app-server is not running."));+ }+ const id = this.#nextId++;+ const response = new Promise<unknown>((resolve, reject) => {+ this.#pending.set(id, { reject, resolve });+ });+ this.#write({ id, method, params });+ return response;+ }++ #notify(method: string, params: unknown): void {+ this.#write({ method, params });+ }++ #write(value: unknown): void {+ this.#child.stdin.write(`${JSON.stringify(value)}\n`);+ }++ #handleLine(line: string): void {+ let value: RpcResponse;+ try {+ value = JSON.parse(line) as RpcResponse;+ } catch {+ return;+ }+ if (typeof value.id !== "number") return;+ const pending = this.#pending.get(value.id);+ if (pending === undefined) return;+ this.#pending.delete(value.id);+ if (value.error !== undefined) {+ pending.reject(+ new Error(value.error.message ?? `Codex app-server request failed (${value.error.code}).`),+ );+ return;+ }+ pending.resolve(value.result);+ }++ #fail(error: Error): void {+ if (this.#exited) return;+ this.#exited = true;+ this.#failure = codexUnavailableError(error);+ this.#lines.close();+ for (const pending of this.#pending.values()) pending.reject(this.#failure);+ this.#pending.clear();+ }+}++function spawnCodexAppServer(+ command: string,+ args: readonly string[],+ options: {+ readonly env?: NodeJS.ProcessEnv;+ stdio: ["pipe", "pipe", "pipe"];+ },+): CodexAppServerProcess {+ return spawn(command, [...args], options);+}++function unrefStream(stream: NodeJS.ReadableStream | NodeJS.WritableStream): void {+ if ("unref" in stream && typeof stream.unref === "function") stream.unref();+}++function codexUnavailableError(error: unknown): Error {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {+ return new Error(+ "ChatGPT subscription authentication requires the Codex CLI. Install or upgrade `codex`, then run `codex login`.",+ );+ }+ const message = error instanceof Error ? error.message : String(error);+ return new Error(`Codex app-server is unavailable: ${message}`);+}diff --git a/packages/eve/src/public/models/openai/chatgpt/model.test.ts b/packages/eve/src/public/models/openai/chatgpt/model.test.tsindex 63c2627c4..7c7411caa 100644--- a/packages/eve/src/public/models/openai/chatgpt/model.test.ts+++ b/packages/eve/src/public/models/openai/chatgpt/model.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { createCodexSubscriptionModel } from "./model.js";-import { createUnsignedJwt } from "./unsigned-jwt.js";+import type { CodexTokenBroker } from "./token-broker.js";const CODEX_ENDPOINT = "https://chatgpt.test/backend-api/codex/responses";@@ -10,13 +10,8 @@ describe("Codex model", () => {const model = createCodexSubscriptionModel({ model: " gpt-5.4 " },{+ broker: fakeBroker(),fetch: async () => Response.json({ ok: true }),- readCredentials: async () => ({- kind: "api-key",- apiKey: "sk-test",- authPath: "/home/user/.codex/auth.json",- codexHome: "/home/user/.codex",- }),},);@@ -38,14 +33,9 @@ describe("Codex model", () => {const model = createCodexSubscriptionModel({ model: "gpt-5.2-codex" },{+ broker: fakeBroker(),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",- }),},);@@ -94,14 +84,9 @@ describe("Codex model", () => {const model = createCodexSubscriptionModel({ model: "gpt-5.2-codex" },{+ broker: fakeBroker(),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",- }),},);@@ -139,6 +124,14 @@ describe("Codex model", () => {});});+function fakeBroker(): CodexTokenBroker {+ return {+ getToken: async () => ({ token: "access-token" }),+ refreshState: async () => ({ kind: "ready" }),+ state: () => ({ kind: "ready" }),+ };+}+interface RecordedRequest {readonly body: string | undefined;readonly url: string;diff --git a/packages/eve/src/public/models/openai/chatgpt/token-broker.test.ts b/packages/eve/src/public/models/openai/chatgpt/token-broker.test.tsnew file mode 100644index 000000000..9878ecce4--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/token-broker.test.ts@@ -0,0 +1,146 @@+import { describe, expect, it, vi } from "vitest";++import type { CodexAppServer } from "./codex-app-server.js";+import { createCodexTokenBroker } from "./token-broker.js";+import { createUnsignedJwt } from "./unsigned-jwt.js";++describe("Codex token broker", () => {+ it("caches a fresh ChatGPT token", async () => {+ const token = createUnsignedJwt({+ exp: 2_000_000_000,+ chatgpt_account_id: "acct-1",+ sub: "samlp|profile|[email protected]",+ });+ const getAuthStatus = vi.fn(async () => ({ authMethod: "chatgpt", authToken: token }));+ const broker = createCodexTokenBroker({+ appServer: { getAuthStatus },+ now: () => 1_800_000_000_000,+ });++ await expect(broker.getToken({ reason: "request" })).resolves.toMatchObject({+ accountId: "acct-1",+ accountLabel: "[email protected]",+ token,+ });+ await broker.getToken({ reason: "request" });++ expect(getAuthStatus).toHaveBeenCalledOnce();+ expect(broker.state()).toMatchObject({+ kind: "ready",+ accountLabel: "[email protected]",+ });+ });++ it("asks Codex to refresh a token within five minutes of expiry", async () => {+ const stale = createUnsignedJwt({ exp: 1_800_000_100 });+ const fresh = createUnsignedJwt({ exp: 2_000_000_000 });+ const getAuthStatus = vi+ .fn<CodexAppServer["getAuthStatus"]>()+ .mockResolvedValueOnce({ authMethod: "chatgpt", authToken: stale })+ .mockResolvedValueOnce({ authMethod: "chatgpt", authToken: fresh });+ const broker = createCodexTokenBroker({+ appServer: { getAuthStatus },+ now: () => 1_800_000_000_000,+ });++ await expect(broker.getToken({ reason: "request" })).resolves.toMatchObject({ token: fresh });+ expect(getAuthStatus).toHaveBeenNthCalledWith(1, { refreshToken: false });+ expect(getAuthStatus).toHaveBeenNthCalledWith(2, { refreshToken: true });+ });++ it("coalesces concurrent forced refreshes", async () => {+ const token = createUnsignedJwt({ exp: 2_000_000_000 });+ let release: (() => void) | undefined;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const getAuthStatus = vi.fn(async () => {+ await gate;+ return { authMethod: "chatgpt", authToken: token };+ });+ const broker = createCodexTokenBroker({ appServer: { getAuthStatus } });++ const first = broker.getToken({ reason: "rejected" });+ const second = broker.getToken({ reason: "rejected" });+ await vi.waitFor(() => expect(getAuthStatus).toHaveBeenCalledOnce());+ release?.();+ await Promise.all([first, second]);++ expect(getAuthStatus).toHaveBeenCalledWith({ refreshToken: true });+ });++ it("forces a refresh after an ordinary resolution is already in flight", async () => {+ const rejected = createUnsignedJwt({ exp: 2_000_000_000, sub: "rejected" });+ const refreshed = createUnsignedJwt({ exp: 2_000_000_000, sub: "refreshed" });+ let release: (() => void) | undefined;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const getAuthStatus = vi+ .fn<CodexAppServer["getAuthStatus"]>()+ .mockImplementationOnce(async () => {+ await gate;+ return { authMethod: "chatgpt", authToken: rejected };+ })+ .mockResolvedValueOnce({ authMethod: "chatgpt", authToken: refreshed });+ const broker = createCodexTokenBroker({ appServer: { getAuthStatus } });++ const request = broker.getToken({ reason: "request" });+ await vi.waitFor(() => expect(getAuthStatus).toHaveBeenCalledOnce());+ const retry = broker.getToken({ reason: "rejected" });+ release?.();++ await expect(request).resolves.toMatchObject({ token: rejected });+ await expect(retry).resolves.toMatchObject({ token: refreshed });+ expect(getAuthStatus).toHaveBeenNthCalledWith(1, { refreshToken: false });+ expect(getAuthStatus).toHaveBeenNthCalledWith(2, { refreshToken: true });+ });++ it("reports signed out when Codex has no ChatGPT token", async () => {+ const broker = createCodexTokenBroker({+ appServer: { getAuthStatus: async () => ({ requiresOpenaiAuth: true }) },+ });++ await expect(broker.getToken({ reason: "request" })).rejects.toThrow("codex login");+ expect(broker.state()).toEqual({ kind: "signed-out" });+ });++ it("reports reauthentication after a rejected token cannot refresh", async () => {+ const broker = createCodexTokenBroker({+ appServer: { getAuthStatus: async () => ({ authMethod: "chatgpt" }) },+ });++ await expect(broker.getToken({ reason: "rejected" })).rejects.toThrow("codex login");+ expect(broker.state()).toEqual({ kind: "reauth-required" });+ });++ it("restarts Codex before probing a repaired signed-out session", async () => {+ const token = createUnsignedJwt({ exp: 2_000_000_000 });+ const restart = vi.fn();+ const getAuthStatus = vi+ .fn<CodexAppServer["getAuthStatus"]>()+ .mockResolvedValueOnce({ requiresOpenaiAuth: true })+ .mockResolvedValueOnce({ authMethod: "chatgpt", authToken: token });+ const broker = createCodexTokenBroker({ appServer: { getAuthStatus, restart } });++ await broker.getToken({ reason: "request" }).catch(() => undefined);+ await expect(broker.refreshState()).resolves.toMatchObject({ kind: "ready" });++ expect(restart).toHaveBeenCalledOnce();+ });++ it("reports an unavailable app-server without including token material", async () => {+ const secret = "secret-bearer-token";+ const broker = createCodexTokenBroker({+ appServer: {+ getAuthStatus: async () => {+ throw new Error("Codex app-server exited");+ },+ },+ });++ const error = await broker.getToken({ reason: "request" }).catch((value: unknown) => value);+ expect(String(error)).not.toContain(secret);+ expect(broker.state()).toMatchObject({ kind: "unavailable" });+ });+});diff --git a/packages/eve/src/public/models/openai/chatgpt/token-broker.ts b/packages/eve/src/public/models/openai/chatgpt/token-broker.tsnew file mode 100644index 000000000..268b93fb7--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/token-broker.ts@@ -0,0 +1,161 @@+import {+ extractCodexAccountIdFromToken,+ extractCodexAccountLabelFromToken,+ readCodexJwtExpirationMs,+} from "./auth.js";+import {+ CodexAppServerClient,+ type CodexAppServer,+ type CodexAppServerOptions,+} from "./codex-app-server.js";++const TOKEN_REFRESH_WINDOW_MS = 5 * 60_000;++export type ChatGptAuthState =+ | { readonly kind: "checking" }+ | {+ readonly accountLabel?: string;+ readonly kind: "ready";+ }+ | { readonly kind: "signed-out" }+ | { readonly kind: "reauth-required" }+ | { readonly kind: "unavailable"; readonly reason: string };++export interface ChatGptToken {+ readonly accountId?: string;+ readonly accountLabel?: string;+ readonly expiresAt?: number;+ readonly token: string;+}++export interface CodexTokenBroker {+ getToken(input: { readonly reason: "rejected" | "request" }): Promise<ChatGptToken>;+ refreshState(): Promise<ChatGptAuthState>;+ state(): ChatGptAuthState;+}++export interface CodexTokenBrokerOptions extends CodexAppServerOptions {+ readonly appServer?: CodexAppServer;+ readonly now?: () => number;+}++export function createCodexTokenBroker(options: CodexTokenBrokerOptions = {}): CodexTokenBroker {+ const appServer = options.appServer ?? new CodexAppServerClient(options);+ const now = options.now ?? Date.now;+ let currentState: ChatGptAuthState = { kind: "checking" };+ let cached: ChatGptToken | undefined;+ let resolution: { readonly forced: boolean; readonly promise: Promise<ChatGptToken> } | undefined;++ return {+ getToken(input) {+ return getToken(input.reason);+ },+ async refreshState() {+ if (currentState.kind === "signed-out" || currentState.kind === "reauth-required") {+ appServer.restart?.();+ }+ cached = undefined;+ try {+ await getToken("request");+ } catch {+ // The state is the reportable result; callers should not need exception control flow.+ }+ return currentState;+ },+ state() {+ return currentState;+ },+ };++ function getToken(reason: "rejected" | "request"): Promise<ChatGptToken> {+ const forced = reason === "rejected";+ if (!forced && cached !== undefined && isFresh(cached, now())) {+ return Promise.resolve(cached);+ }+ if (resolution !== undefined && (!forced || resolution.forced)) {+ return resolution.promise;+ }++ const pending = resolution?.promise;+ const next =+ pending === undefined+ ? resolveToken(forced)+ : pending.catch(() => undefined).then(() => resolveToken(forced));+ const promise = next.finally(() => {+ if (resolution?.promise === promise) resolution = undefined;+ });+ resolution = { forced, promise };+ return promise;+ }++ async function resolveToken(forceRefresh: boolean): Promise<ChatGptToken> {+ try {+ const status = await appServer.getAuthStatus({ refreshToken: forceRefresh });+ if (status.authMethod !== "chatgpt" || status.authToken === undefined) {+ cached = undefined;+ currentState = forceRefresh ? { kind: "reauth-required" } : { kind: "signed-out" };+ throw new Error(+ "ChatGPT subscription authentication is unavailable. Run `codex login`, then retry.",+ );+ }+ const token = tokenFrom(status.authToken);+ if (!forceRefresh && !isFresh(token, now())) {+ const refreshed = await appServer.getAuthStatus({ refreshToken: true });+ if (refreshed.authMethod !== "chatgpt" || refreshed.authToken === undefined) {+ cached = undefined;+ currentState = { kind: "reauth-required" };+ throw new Error(+ "ChatGPT subscription authentication could not be refreshed. Run `codex login`, then retry.",+ );+ }+ return accept(refreshed.authToken);+ }+ cached = token;+ currentState = readyState(token);+ return token;+ } catch (error) {+ if (currentState.kind === "checking" || currentState.kind === "ready") {+ const reason = error instanceof Error ? error.message : String(error);+ currentState = { kind: "unavailable", reason };+ }+ throw error;+ }+ }++ function accept(rawToken: string): ChatGptToken {+ const token = tokenFrom(rawToken);+ cached = token;+ currentState = readyState(token);+ return token;+ }+}++let defaultBroker: CodexTokenBroker | undefined;++export function getDefaultCodexTokenBroker(): CodexTokenBroker {+ defaultBroker ??= createCodexTokenBroker();+ return defaultBroker;+}++function tokenFrom(token: string): ChatGptToken {+ const accountId = extractCodexAccountIdFromToken(token);+ const accountLabel = extractCodexAccountLabelFromToken(token);+ const expiresAt = readCodexJwtExpirationMs(token);+ return {+ token,+ ...(accountId !== undefined && { accountId }),+ ...(accountLabel !== undefined && { accountLabel }),+ ...(expiresAt !== undefined && { expiresAt }),+ };+}++function readyState(token: ChatGptToken): ChatGptAuthState {+ return {+ kind: "ready",+ ...(token.accountLabel !== undefined && { accountLabel: token.accountLabel }),+ };+}++function isFresh(token: ChatGptToken, now: number): boolean {+ return token.expiresAt === undefined || token.expiresAt - TOKEN_REFRESH_WINDOW_MS > now;+}diff --git a/packages/eve/src/public/models/openai/chatgpt/transport.test.ts b/packages/eve/src/public/models/openai/chatgpt/transport.test.tsindex b60aa4472..d5fbe6540 100644--- a/packages/eve/src/public/models/openai/chatgpt/transport.test.ts+++ b/packages/eve/src/public/models/openai/chatgpt/transport.test.ts@@ -1,192 +1,87 @@import { describe, expect, it, vi } from "vitest";-import type {- CodexAuthCredentials,- CodexChatGptCredentials,- CodexRefreshedTokens,-} from "./auth.js";+import type { CodexTokenBroker } from "./token-broker.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" },- });+ it("routes Responses requests through the Codex backend with brokered ChatGPT auth", async () => {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 broker = fakeBroker([{ accountId: "acct-1", token: "access-token" }]);const codexFetch = createCodexFetch({+ broker,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" },+ body: '{"stream":true}',+ headers: { authorization: "[redacted]", "content-type": "application/json" },method: "POST",});+ expect(broker.getToken).toHaveBeenCalledWith({ reason: "request" });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]).toMatchObject({ method: "POST", url: CODEX_ENDPOINT });+ expect(requests[0]?.headers.get("authorization")).toBe("Bearer access-token");+ expect(requests[0]?.headers.get("ChatGPT-Account-Id")).toBe("acct-1");expect(requests[0]?.headers.get("originator")).toBe("eve");});- it("leaves API-key request bodies unchanged", async () => {+ it("refreshes through the broker and replays one string-body request after 401", async () => {const requests: RecordedRequest[] = [];+ const broker = fakeBroker([{ token: "stale-token" }, { token: "fresh-token" }]);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",- }),+ broker,+ codexApiEndpoint: CODEX_ENDPOINT,+ fetch: createRecordingFetch(requests, (request) =>+ Promise.resolve(+ new Response(null, {+ status: request.headers.get("authorization") === "Bearer stale-token" ? 401 : 200,+ }),+ ),+ ),});- await codexFetch("https://api.openai.com/v1/responses", {- body: '{"model":"gpt-5.2-codex","input":[],"store":true}',+ const response = await codexFetch("https://api.openai.com/v1/responses", {+ body: '{"stream":true}',method: "POST",});- expect(requests).toHaveLength(1);- expect(requests[0]?.body).toBe('{"model":"gpt-5.2-codex","input":[],"store":true}');+ expect(response.status).toBe(200);+ expect(broker.getToken).toHaveBeenNthCalledWith(1, { reason: "request" });+ expect(broker.getToken).toHaveBeenNthCalledWith(2, { reason: "rejected" });+ expect(requests.map((request) => request.headers.get("authorization"))).toEqual([+ "Bearer stale-token",+ "Bearer fresh-token",+ ]);+ expect(requests.map((request) => request.body)).toEqual(['{"stream":true}', '{"stream":true}']);});- it("deduplicates concurrent ChatGPT token refreshes", async () => {+ it("does not replay a Request body after 401", 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 broker = fakeBroker([{ token: "stale-token" }]);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,+ broker,+ fetch: createRecordingFetch(requests, () =>+ Promise.resolve(new Response(null, { status: 401 })),+ ),});- 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),+ const response = await codexFetch(+ new Request("https://api.openai.com/v1/responses", {+ body: '{"stream":true}',+ method: "POST",+ }),);- 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);+ expect(response.status).toBe(401);+ expect(broker.getToken).toHaveBeenCalledOnce();+ expect(requests).toHaveLength(1);});- it("matches OpenCode's OAuth URL rewrite boundary", () => {+ it("matches the Codex endpoint rewrite boundary", () => {expect(rewriteCodexEndpoint("https://api.openai.com/v1/responses", CODEX_ENDPOINT)).toBe(CODEX_ENDPOINT,);@@ -206,17 +101,33 @@ interface RecordedRequest {readonly url: string;}+function fakeBroker(+ tokens: Array<{ readonly accountId?: string; readonly token: string }>,+): CodexTokenBroker {+ return {+ getToken: vi.fn(async () => {+ const token = tokens.shift();+ if (token === undefined) throw new Error("No token configured.");+ return token;+ }),+ refreshState: async () => ({ kind: "checking" }),+ state: () => ({ kind: "checking" }),+ };+}+function createRecordingFetch(requests: RecordedRequest[],- responseForUrl: (url: string) => Response | Promise<Response> = () => Response.json({ ok: true }),+ responseForRequest: (request: RecordedRequest) => Promise<Response> = async () =>+ Response.json({ ok: true }),): typeof fetch {return async (input, init) => {- requests.push({+ const request = {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);+ };+ requests.push(request);+ return responseForRequest(request);};}diff --git a/packages/eve/src/public/models/openai/chatgpt/transport.ts b/packages/eve/src/public/models/openai/chatgpt/transport.tsindex 92abc3826..19da2b644 100644--- a/packages/eve/src/public/models/openai/chatgpt/transport.ts+++ b/packages/eve/src/public/models/openai/chatgpt/transport.ts@@ -1,128 +1,35 @@-import { z } from "#compiled/zod/index.js";-import {- extractCodexAccountIdFromToken,- isFreshCodexAccessToken,- readCodexAuthCredentials,- writeCodexAuthCredentials,- type CodexAuthCredentials,- type CodexChatGptCredentials,- type CodexRefreshedTokens,-} from "./auth.js";+import { getDefaultCodexTokenBroker, type CodexTokenBroker } from "./token-broker.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 broker?: CodexTokenBroker;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.+ * Routes OpenAI Responses requests through the Codex backend. Authentication is+ * resolved by the Codex CLI; eve never reads, refreshes, or persists OAuth+ * credentials itself.*/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 broker = options.broker ?? getDefaultCodexTokenBroker();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 };- }+ const url = rewriteCodexEndpoint(requestUrl(input), codexApiEndpoint);+ const token = await broker.getToken({ reason: "request" });+ const first = await httpFetch(url, authenticatedInit(input, init, token));+ if (first.status !== 401 || !isReplayable(input, init)) return first;++ await first.body?.cancel();+ const refreshed = await broker.getToken({ reason: "rejected" });+ return httpFetch(url, authenticatedInit(input, init, refreshed));};}@@ -134,67 +41,30 @@ export function rewriteCodexEndpoint(input: string, codexApiEndpoint = CODEX_APIreturn 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 authenticatedInit(+ input: FetchInput,+ init: RequestInit | undefined,+ token: { readonly accountId?: string; readonly token: string },+): RequestInit {+ const headers = cloneHeaders(+ init?.headers ?? (input instanceof Request ? input.headers : undefined),+ );+ headers.delete("authorization");+ headers.delete("Authorization");+ headers.set("authorization", `Bearer ${token.token}`);+ headers.set("originator", "eve");+ if (token.accountId !== undefined) headers.set("ChatGPT-Account-Id", token.accountId);+ else headers.delete("ChatGPT-Account-Id");+ return fetchInit(input, init, headers);}-function createDefaultCodexCredentialsWriter(now: () => number): CodexCredentialsWriter {- return (input) =>- writeCodexAuthCredentials({- ...input,- now: () => new Date(now()),- });+function isReplayable(input: FetchInput, init: RequestInit | undefined): boolean {+ if (input instanceof Request) return false;+ return !(init?.body instanceof ReadableStream);}function cloneHeaders(input: RequestInit["headers"] | undefined): Headers {- const headers = new Headers(input);- return headers;+ return new Headers(input);}function requestUrl(input: FetchInput): string {@@ -207,9 +77,7 @@ function fetchInit(init: RequestInit | undefined,headers: Headers,): RequestInit {- if (init !== undefined) {- return { ...init, headers };- }+ if (init !== undefined) return { ...init, headers };if (input instanceof Request) {return {body: input.body,diff --git a/packages/eve/src/public/models/openai/index.test.ts b/packages/eve/src/public/models/openai/index.test.tsindex 1432e042f..dc3a8bd2a 100644--- a/packages/eve/src/public/models/openai/index.test.ts+++ b/packages/eve/src/public/models/openai/index.test.ts@@ -1,18 +1,16 @@import { describe, expect, it } from "vitest";-import { experimental_chatgpt } from "./index.js";+import { chatgpt, experimental_chatgpt } from "./index.js";-describe("experimental_chatgpt", () => {+describe("chatgpt", () => {it("defaults to gpt-5.6-sol", () => {- const model = experimental_chatgpt();-+ const model = 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");-+ const model = 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");@@ -20,20 +18,20 @@ describe("experimental_chatgpt", () => {});it("strips an openai/ provider prefix", () => {- const model = experimental_chatgpt("openai/gpt-5.5");-+ const model = 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".',+ expect(() => chatgpt("anthropic/claude-sonnet-4.6")).toThrow(+ '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");+ it("keeps the deprecated alias working", () => {+ const model = experimental_chatgpt("gpt-5.5");+ if (typeof model === "string") throw new Error("expected a model instance");+ expect(model.modelId).toBe("gpt-5.5");});});diff --git a/packages/eve/src/public/models/openai/index.ts b/packages/eve/src/public/models/openai/index.tsindex 4ccee40cb..09ac4ac8a 100644--- a/packages/eve/src/public/models/openai/index.ts+++ b/packages/eve/src/public/models/openai/index.ts@@ -1,9 +1,7 @@import type { LanguageModel } from "ai";+import { DEFAULT_CHATGPT_MODEL_ID, normalizeChatGptModelId } from "#shared/chatgpt-model.js";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@@ -16,39 +14,31 @@ const DEFAULT_CHATGPT_MODEL = "gpt-5.6-sol";** 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:+ * Branch on environment for production:** ```ts* export default defineAgent({* model:* process.env.NODE_ENV === "production"* ? "anthropic/claude-sonnet-4.6"- * : experimental_chatgpt(),- * modelContextWindowTokens: 200_000,+ * : chatgpt(),* });* ```- *- * 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".',- );+export function chatgpt(model = DEFAULT_CHATGPT_MODEL_ID): LanguageModel {+ const slug = normalizeChatGptModelId(model);+ if (slug === undefined && model.trim().replace(/^openai\//u, "").length === 0) {+ throw new Error('Expected chatgpt "model" to name an OpenAI model, for example "gpt-5.6-sol".');}- if (slug.includes("/")) {+ if (slug === undefined) {throw new Error(- `experimental_chatgpt serves OpenAI models through the local ChatGPT login; received "${model}".`,+ `chatgpt serves OpenAI models through the local ChatGPT login; received "${model}".`,);}return createCodexSubscriptionModel({ model: slug });}++/** @deprecated Use {@link chatgpt}. */+export const experimental_chatgpt = chatgpt;diff --git a/packages/eve/src/setup/flows/chatgpt-auth.ts b/packages/eve/src/setup/flows/chatgpt-auth.tsnew file mode 100644index 000000000..a7780420d--- /dev/null+++ b/packages/eve/src/setup/flows/chatgpt-auth.ts@@ -0,0 +1,23 @@+import { spawn } from "node:child_process";++import { getDefaultCodexTokenBroker } from "#public/models/openai/chatgpt/token-broker.js";++/** Ensures Codex owns a usable ChatGPT login before setup authors `chatgpt()`. */+export async function ensureChatGptAuth(): Promise<void> {+ const state = await getDefaultCodexTokenBroker().refreshState();+ if (state.kind === "ready") return;++ const child = spawn("codex", ["login"], { stdio: "inherit" });+ await new Promise<void>((resolve, reject) => {+ child.once("error", reject);+ child.once("exit", (code, signal) => {+ if (code === 0) resolve();+ else reject(new Error(`codex login failed (${signal ?? code ?? "unknown"}).`));+ });+ });++ const refreshed = await getDefaultCodexTokenBroker().refreshState();+ if (refreshed.kind !== "ready") {+ throw new Error("Codex login completed without a usable ChatGPT session.");+ }+}diff --git a/packages/eve/src/setup/flows/deploy.test.ts b/packages/eve/src/setup/flows/deploy.test.tsindex 95124f165..02168da96 100644--- a/packages/eve/src/setup/flows/deploy.test.ts+++ b/packages/eve/src/setup/flows/deploy.test.ts@@ -89,6 +89,31 @@ function createLoginFlow(result: LoginFlowResult = { kind: "already" }) {}describe("runDeployFlow", () => {+ it("blocks a local ChatGPT subscription model before Vercel effects", async () => {+ const fake = createFakePrompter({});+ const detectDeployment = vi.fn(async () => LINKED);++ await expect(+ runDeployFlow({+ appRoot: APP_ROOT,+ prompter: fake.prompter,+ interactive: true,+ deps: {+ detectDeployment,+ inspectApplication: vi.fn(async () => ({+ compiledState: {+ manifest: {+ config: { model: { routing: { kind: "external", provider: "codex" } } },+ },+ },+ })) as never,+ },+ }),+ ).resolves.toEqual({ kind: "local-model" });++ expect(detectDeployment).not.toHaveBeenCalled();+ });+it("deploys an already-linked project without asking anything", async () => {const fake = createFakePrompter({});const deployDeps = createDeployProjectDeps();diff --git a/packages/eve/src/setup/flows/deploy.ts b/packages/eve/src/setup/flows/deploy.tsindex 6de18de87..786d0df7e 100644--- a/packages/eve/src/setup/flows/deploy.ts+++ b/packages/eve/src/setup/flows/deploy.ts@@ -1,3 +1,6 @@+import { inspectApplication } from "#services/inspect-application.js";+import { isChatGptModelRouting } from "#shared/chatgpt-model.js";+import { interactiveAsker, withAnswers } from "../ask.js";import { deployProject, type DeployProjectDeps } from "../boxes/deploy-project.js";import { linkVercelProject, type LinkProjectDeps } from "../boxes/link-project.js";@@ -22,6 +25,7 @@ import { runLoginFlow } from "./login.js";/** Injected for tests; defaults to the real detection and box effects. */export interface DeployFlowDeps {detectDeployment: typeof detectDeployment;+ inspectApplication: typeof inspectApplication;runLoginFlow: typeof runLoginFlow;resolveProvisioning?: ResolveProvisioningDeps;linkProject?: LinkProjectDeps;@@ -31,6 +35,7 @@ export interface DeployFlowDeps {export type DeployFlowResult =| { kind: "deployed"; productionUrl?: string }| { kind: "cancelled" }+ | { kind: "local-model" }/** Unlinked directory in a non-interactive run: refused before any effect. */| { kind: "needs-link" };@@ -58,7 +63,22 @@ export async function runDeployFlow(input: {deps?: Partial<DeployFlowDeps>;}): Promise<DeployFlowResult> {const { appRoot, prompter, interactive, signal } = input;- const deps: DeployFlowDeps = { detectDeployment, runLoginFlow, ...input.deps };+ const deps: DeployFlowDeps = {+ detectDeployment,+ inspectApplication,+ runLoginFlow,+ ...input.deps,+ };++ try {+ const application = await deps.inspectApplication(appRoot);+ const routing = application.compiledState?.manifest.config.model?.routing;+ if (isChatGptModelRouting(routing)) {+ return { kind: "local-model" };+ }+ } catch {+ // Existing deploy behavior remains authoritative when the app has not compiled yet.+ }const project = await withSpinner(prompter, "Checking the current Vercel link...", async () => {const deployment = await deps.detectDeployment(appRoot, { signal });diff --git a/packages/eve/src/setup/flows/link.test.ts b/packages/eve/src/setup/flows/link.test.tsindex fb2742f96..ca7f46093 100644--- a/packages/eve/src/setup/flows/link.test.ts+++ b/packages/eve/src/setup/flows/link.test.ts@@ -95,7 +95,7 @@ afterEach(() => {});describe("runLinkFlow", () => {- it("reports the gateway key as the active credential when it shadows the pulled OIDC token", async () => {+ it("reports the env-file key as active when both credentials exist", async () => {const { prompter } = createFakePrompter({single: (opts) => {if (stripVTControlCharacters(opts.message) === "Vercel project") return "new";@@ -113,19 +113,16 @@ describe("runLinkFlow", () => {projectSelection: "create-or-link",});- // Runtime resolution ranks the key first; reporting OIDC here would- // claim a credential that never authenticates a call.expect(result).toEqual({kind: "done",resolution: {credential: "api-key",source: { kind: "env-file", path: ".env.local" },- shadowedOidc: { file: ".env.local" },},});});- it("reports a shell-exported gateway key shadowing the pulled OIDC token", async () => {+ it("reports the shell key as active when both credentials exist", async () => {vi.stubEnv("AI_GATEWAY_API_KEY", "vck_shell");const { prompter } = createFakePrompter({single: (opts) => {@@ -147,7 +144,6 @@ describe("runLinkFlow", () => {resolution: {credential: "api-key",source: { kind: "shell" },- shadowedOidc: { file: ".env.local" },},});});diff --git a/packages/eve/src/setup/flows/model-source-change.test.ts b/packages/eve/src/setup/flows/model-source-change.test.tsnew file mode 100644index 000000000..1e063682e--- /dev/null+++ b/packages/eve/src/setup/flows/model-source-change.test.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from "vitest";++import { validateModelSlug } from "./model-source-change.js";++describe("validateModelSlug", () => {+ it("accepts a valid ChatGPT selection without consulting the Gateway catalog", async () => {+ await expect(validateModelSlug("/app", "chatgpt/gpt-5.6-sol")).resolves.toBeNull();+ });++ it("rejects a ChatGPT selection whose model is not a bare OpenAI id", async () => {+ await expect(validateModelSlug("/app", "chatgpt/not/a-bare-slug")).resolves.toBe(+ "Choose a bare OpenAI model id after `chatgpt/`.",+ );+ });+});diff --git a/packages/eve/src/setup/flows/model-source-change.ts b/packages/eve/src/setup/flows/model-source-change.tsindex ce22d5da4..8effc82e5 100644--- a/packages/eve/src/setup/flows/model-source-change.ts+++ b/packages/eve/src/setup/flows/model-source-change.ts@@ -8,6 +8,10 @@ import type {AgentModelSetting,AgentModelSettingsPatch,} from "#source-change/apply-agent-model-settings.js";+import {+ CHATGPT_MODEL_SELECTION_PREFIX,+ parseChatGptModelSelection,+} from "#shared/chatgpt-model.js";import { createStaticSourceChange } from "#source-change/static-source-change.js";import pc from "picocolors";@@ -119,6 +123,10 @@ export async function changeAgentModel(input: {}export async function validateModelSlug(appRoot: string, slug: string): Promise<string | null> {+ if (parseChatGptModelSelection(slug) !== undefined) return null;+ if (slug.startsWith(CHATGPT_MODEL_SELECTION_PREFIX)) {+ return "Choose a bare OpenAI model id after `chatgpt/`.";+ }if (!slug.includes("/")) {return `\`${slug}\` isn't a provider/model id (e.g. anthropic/claude-sonnet-5).`;}diff --git a/packages/eve/src/setup/flows/model.test.ts b/packages/eve/src/setup/flows/model.test.tsindex 8d5c01c91..a8fb205a2 100644--- a/packages/eve/src/setup/flows/model.test.ts+++ b/packages/eve/src/setup/flows/model.test.ts@@ -2,6 +2,7 @@ import pc from "picocolors";import { describe, expect, it, vi } from "vitest";import { createFakePrompter } from "#internal/testing/fake-prompter.js";+import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";import type { GatewayCatalogModel } from "#setup/boxes/select-model.js";import type {PrompterValue,@@ -75,10 +76,11 @@ function flowDeps(overrides: Partial<ModelFlowDeps> = {}): Partial<ModelFlowDeps),selectModel: { fetchModels: async () => CATALOG },pickModelSettings: vi.fn(async () => undefined),- detectProviderStatus: vi.fn(- async () => ({ kind: "gateway-project", projectName: "my-agent" }) as const,- ),- runProviderFlow: vi.fn(async () => ({ kind: "done" }) as const),+ resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-project"] as const),+ readProviderSelection: vi.fn(async () => "ai-gateway-project" as const),+ runProviderFlow: vi.fn(async () => ({ kind: "ai-gateway-project" }) as const),+ ensureChatGptAuth: vi.fn(async () => {}),+ writeProviderSelection: vi.fn(async () => {}),...overrides,};}@@ -140,7 +142,7 @@ describe("runModelFlow", () => {{value: "provider",label: "Change provider",- hint: `AI Gateway (Linked to ${pc.bold("my-agent")})`,+ hint: "AI Gateway via Project",description: "How your agent reaches the model provider",},{ value: "done", label: "Done" },@@ -152,6 +154,178 @@ describe("runModelFlow", () => {]);});+ it("keeps the stored provider selection independent from authored routing", async () => {+ const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });+ const deps = flowDeps({+ readCurrentModel: vi.fn(async () => ({+ id: "chatgpt/gpt-5.6-sol",+ routing: { kind: "external", provider: "codex" } as const,+ reasoning: null,+ serviceTier: { kind: "standard" } as const,+ editable: true,+ settingsEditable: true,+ })),+ resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-project"] as const),+ readProviderSelection: vi.fn(async () => "ai-gateway-project" as const),+ });++ await runModelFlow({+ appRoot: APP_ROOT,+ prompter,+ chatGptAccountLabel: "[email protected]",+ deps,+ });++ expect(menuPaints[0]?.options[1]).toMatchObject({+ value: "provider",+ label: "Change provider",+ hint: "AI Gateway via Project",+ description: "How your agent reaches the model provider",+ });+ expect(menuPaints[0]?.notices).toEqual([]);+ });++ it("selects ChatGPT under Change provider through exclusive terminal auth", async () => {+ const { prompter, menuPaints } = scriptedPrompter({ menu: ["provider"] });+ const ensureChatGptAuth = vi.fn(async () => {});+ const deps = flowDeps({+ ensureChatGptAuth,+ runProviderFlow: vi.fn(async () => ({ kind: "chatgpt" }) as const),+ });+ const exclusiveCalls: string[] = [];+ const withExclusiveTerminal = async <T>(task: () => Promise<T>): Promise<T> => {+ exclusiveCalls.push("called");+ return task();+ };++ await expect(+ runModelFlow({ appRoot: APP_ROOT, prompter, deps, withExclusiveTerminal }),+ ).resolves.toEqual({+ kind: "done",+ accessChanged: true,+ modelMessage: `Model changed to ${pc.bold("chatgpt/gpt-5.6-sol")}. Live on your next prompt.`,+ providerSelection: "chatgpt",+ });++ expect(menuPaints[0]?.options.map((option) => option.value)).toEqual([+ "model",+ "provider",+ "done",+ ]);+ expect(menuPaints).toHaveLength(1);+ expect(exclusiveCalls).toEqual(["called"]);+ expect(ensureChatGptAuth).toHaveBeenCalledOnce();+ expect(deps.applySettings).toHaveBeenCalledWith({+ appRoot: APP_ROOT,+ patch: {+ model: { kind: "set", value: "chatgpt/gpt-5.6-sol" },+ reasoning: { kind: "keep" },+ gatewayServiceTier: { kind: "remove" },+ },+ });+ expect(deps.runProviderFlow).toHaveBeenCalledWith(+ expect.objectContaining({+ availableProviders: ["chatgpt", "ai-gateway-project"],+ selectedProvider: "ai-gateway-project",+ }),+ );+ expect(deps.writeProviderSelection).toHaveBeenCalledWith(APP_ROOT, "chatgpt");+ });++ it("does not store a provider selection when its required source edit is rejected", async () => {+ const { prompter } = scriptedPrompter({ menu: ["provider"] });+ const deps = flowDeps({+ runProviderFlow: vi.fn(async () => ({ kind: "chatgpt" }) as const),+ applySettings: vi.fn(+ async () => ({ kind: "rejected", message: "Couldn't update agent.ts." }) as const,+ ),+ });++ await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({+ kind: "done",+ accessChanged: true,+ modelMessage: "Couldn't update agent.ts.",+ });++ expect(deps.ensureChatGptAuth).toHaveBeenCalledOnce();+ expect(deps.writeProviderSelection).not.toHaveBeenCalled();+ });++ it("switches ChatGPT back to Gateway through the provider selection", async () => {+ const { prompter } = scriptedPrompter({ menu: ["provider"] });+ const applySettings = vi.fn<ModelFlowDeps["applySettings"]>(async ({ patch }) => ({+ kind: "changed",+ changed: ["model"],+ model: patch.model.kind === "set" ? patch.model.value : undefined,+ }));+ const deps = flowDeps({+ readCurrentModel: vi.fn(async () => ({+ id: "chatgpt/gpt-5.6-sol",+ routing: { kind: "external", provider: "codex" } as const,+ reasoning: null,+ serviceTier: { kind: "standard" } as const,+ editable: true,+ settingsEditable: true,+ })),+ resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-project"] as const),+ readProviderSelection: vi.fn(async () => "chatgpt" as const),+ runProviderFlow: vi.fn(async () => ({ kind: "ai-gateway-project" }) as const),+ applySettings,+ });++ await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({+ kind: "done",+ accessChanged: true,+ modelMessage: `Model changed to ${pc.bold(DEFAULT_AGENT_MODEL_ID)}. Live on your next prompt.`,+ providerSelection: "ai-gateway-project",+ });++ expect(applySettings).toHaveBeenCalledWith({+ appRoot: APP_ROOT,+ patch: {+ model: { kind: "set", value: DEFAULT_AGENT_MODEL_ID },+ reasoning: { kind: "keep" },+ gatewayServiceTier: { kind: "keep" },+ },+ });+ expect(deps.ensureChatGptAuth).not.toHaveBeenCalled();+ expect(deps.writeProviderSelection).toHaveBeenCalledWith(APP_ROOT, "ai-gateway-project");+ });++ it("reauthenticates when ChatGPT is selected again", async () => {+ const { prompter } = scriptedPrompter({ menu: ["provider"] });+ const deps = flowDeps({+ readCurrentModel: vi.fn(async () => ({+ id: "chatgpt/gpt-5.6-sol",+ routing: { kind: "external", provider: "codex" } as const,+ reasoning: null,+ serviceTier: { kind: "standard" } as const,+ editable: true,+ settingsEditable: true,+ })),+ resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-key"] as const),+ readProviderSelection: vi.fn(async () => "chatgpt" as const),+ runProviderFlow: vi.fn(async () => ({ kind: "chatgpt" }) as const),+ });++ await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({+ kind: "done",+ accessChanged: true,+ modelMessage: "ChatGPT login ready.",+ providerSelection: "chatgpt",+ });++ expect(deps.ensureChatGptAuth).toHaveBeenCalledOnce();+ expect(deps.runProviderFlow).toHaveBeenCalledWith(+ expect.objectContaining({+ availableProviders: ["chatgpt", "ai-gateway-key"],+ selectedProvider: "chatgpt",+ }),+ );+ expect(deps.applySettings).not.toHaveBeenCalled();+ expect(deps.writeProviderSelection).toHaveBeenCalledWith(APP_ROOT, "chatgpt");+ });+it("summarizes authored reasoning and Fast mode on the model row hint", async () => {const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });const deps = flowDeps({@@ -183,7 +357,8 @@ describe("runModelFlow", () => {})),// Even though detection finds nothing, external routing must NOT surface// the "Configure model access" gateway UX.- detectProviderStatus: vi.fn(async () => ({ kind: "unset" }) as const),+ resolveAvailableProviders: vi.fn(async () => ["chatgpt"] as const),+ readProviderSelection: vi.fn(async () => "ai-gateway-project" as const),});await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({@@ -264,6 +439,10 @@ describe("runModelFlow", () => {]),current: "anthropic/claude-sonnet-5",});+ if (captured?.model.kind !== "pick") throw new Error("Expected a model picker.");+ expect(captured.model.options.map((option) => option.value)).not.toContain(+ "chatgpt/gpt-5.6-sol",+ );expect(captured?.reasoning).toBeNull();expect(captured?.serviceTier).toEqual({ kind: "standard" });expect(captured?.settingsEditable).toBe(true);@@ -293,14 +472,8 @@ describe("runModelFlow", () => {captured = request;return undefined;}),- detectProviderStatus: vi.fn(- async () =>- ({- kind: "gateway-key",- envKey: "AI_GATEWAY_API_KEY",- source: { kind: "env-file", path: ".env.local" },- }) as const,- ),+ resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-key"] as const),+ readProviderSelection: vi.fn(async () => "ai-gateway-key" as const),});await runModelFlow({ appRoot: APP_ROOT, prompter, deps });@@ -323,13 +496,11 @@ describe("runModelFlow", () => {expect(menuPaints).toHaveLength(1);});- it("names the linked project on the provider row once a provider is set", async () => {+ it("names the selected Project provider on the provider row", async () => {const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });const deps = flowDeps({- detectProviderStatus: vi.fn(- async () =>- ({ kind: "gateway-project", projectName: "my-agent", teamName: "my-team" }) as const,- ),+ resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-project"] as const),+ readProviderSelection: vi.fn(async () => "ai-gateway-project" as const),});await runModelFlow({ appRoot: APP_ROOT, prompter, deps });@@ -337,22 +508,16 @@ describe("runModelFlow", () => {expect(menuPaints[0]?.options[1]).toEqual({value: "provider",label: "Change provider",- hint: `AI Gateway (Linked to ${pc.bold("my-agent")} in ${pc.bold("my-team")})`,+ hint: "AI Gateway via Project",description: "How your agent reaches the model provider",});});- it("names the credential env file when a gateway key is set without a link", async () => {+ it("defaults to an available API key when no selection is stored", async () => {const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });const deps = flowDeps({- detectProviderStatus: vi.fn(- async () =>- ({- kind: "gateway-key",- envKey: "AI_GATEWAY_API_KEY",- source: { kind: "env-file", path: ".env.local" },- }) as const,- ),+ resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-key"] as const),+ readProviderSelection: vi.fn(async () => undefined),});await runModelFlow({ appRoot: APP_ROOT, prompter, deps });@@ -360,7 +525,7 @@ describe("runModelFlow", () => {expect(menuPaints[0]?.options[1]).toEqual({value: "provider",label: "Change provider",- hint: "AI Gateway (AI_GATEWAY_API_KEY in .env.local)",+ hint: "AI Gateway via AI_GATEWAY_API_KEY",description: "How your agent reaches the model provider",});});@@ -375,6 +540,7 @@ describe("runModelFlow", () => {await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({kind: "done",+ accessChanged: true,modelMessage: `Model changed to ${pc.bold("openai/gpt-5.5")}. Live on your next prompt.`,});@@ -405,6 +571,7 @@ describe("runModelFlow", () => {await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({kind: "done",+ accessChanged: false,modelMessage: "Couldn't confirm the id.",});@@ -428,6 +595,7 @@ describe("runModelFlow", () => {await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({kind: "done",+ accessChanged: true,modelMessage:"Model settings updated: reasoning high, Fast mode on. Live on your next prompt.",});@@ -487,6 +655,35 @@ describe("runModelFlow", () => {expect(deps.applySettings).not.toHaveBeenCalled();});+ it("does not infer the stored provider selection from a model edit", async () => {+ const { prompter, menuPaints } = scriptedPrompter({ menu: ["model", "done"] });+ const deps = flowDeps({+ readCurrentModel: vi.fn(async () => ({+ id: "chatgpt/gpt-5.6-sol",+ routing: { kind: "external", provider: "codex" } as const,+ reasoning: null,+ serviceTier: { kind: "standard" } as const,+ editable: true,+ settingsEditable: true,+ })),+ resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-project"] as const),+ readProviderSelection: vi.fn(async () => "chatgpt" as const),+ pickModelSettings: vi.fn(async () => ({ model: "openai/gpt-5.5" })),+ });++ await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({+ kind: "done",+ accessChanged: true,+ modelMessage: `Model changed to ${pc.bold("openai/gpt-5.5")}. Live on your next prompt.`,+ });++ expect(menuPaints[1]?.options[1]).toMatchObject({+ value: "provider",+ hint: "ChatGPT subscription",+ });+ expect(deps.writeProviderSelection).not.toHaveBeenCalled();+ });+it("passes a custom Gateway service tier through to the screen untouched", async () => {const { prompter, menuPaints } = scriptedPrompter({ menu: ["model", "esc"] });let captured: ModelSettingsRequest | undefined;@@ -524,47 +721,42 @@ describe("runModelFlow", () => {it("opens provider setup directly when none is configured", async () => {const { prompter, menuPaints } = scriptedPrompter({ menu: [] });- const detectProviderStatus = vi- .fn<ModelFlowDeps["detectProviderStatus"]>()- .mockResolvedValueOnce({ kind: "unset" })- .mockResolvedValueOnce({ kind: "gateway-project", projectName: "my-agent" });- const runProviderFlow = vi.fn<ModelFlowDeps["runProviderFlow"]>(- async () =>- ({- kind: "done",- resolution: {- credential: "api-key",- source: { kind: "env-file", path: ".env.local" },- },- }) as const,+ const resolveAvailableProviders = vi.fn<ModelFlowDeps["resolveAvailableProviders"]>(+ async () => ["chatgpt"],);- const deps = flowDeps({ detectProviderStatus, runProviderFlow });+ const runProviderFlow = vi.fn<ModelFlowDeps["runProviderFlow"]>(async () => ({+ kind: "ai-gateway-key",+ }));+ const deps = flowDeps({+ resolveAvailableProviders,+ readProviderSelection: vi.fn(async () => undefined),+ runProviderFlow,+ });await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({kind: "done",- providerOutcome: {- resolution: {- credential: "api-key",- source: { kind: "env-file", path: ".env.local" },- },- status: { kind: "gateway-project", projectName: "my-agent" },- },+ accessChanged: true,+ providerSelection: "ai-gateway-key",});- // The sub-flow learns the detected provider so its menu can mark the active row.+ // No stored selection and no key default to Project setup.expect(runProviderFlow).toHaveBeenCalledWith(- expect.objectContaining({ appRoot: APP_ROOT, currentProvider: { kind: "unset" } }),+ expect.objectContaining({+ appRoot: APP_ROOT,+ availableProviders: ["chatgpt"],+ selectedProvider: "ai-gateway-project",+ }),);- expect(detectProviderStatus).toHaveBeenCalledTimes(2);+ expect(resolveAvailableProviders).toHaveBeenCalledTimes(1);expect(menuPaints).toHaveLength(0);+ expect(deps.writeProviderSelection).toHaveBeenCalledWith(APP_ROOT, "ai-gateway-key");});it("honors confirmed provider entry when link metadata looks configured", async () => {const { prompter, menuPaints } = scriptedPrompter({ menu: [] });- const runProviderFlow = vi.fn<ModelFlowDeps["runProviderFlow"]>(- async () =>- ({ kind: "done", resolution: { credential: "oidc", file: ".env.local" } }) as const,- );+ const runProviderFlow = vi.fn<ModelFlowDeps["runProviderFlow"]>(async () => ({+ kind: "ai-gateway-project",+ }));const deps = flowDeps({ runProviderFlow });await expect(@@ -576,35 +768,26 @@ describe("runModelFlow", () => {}),).resolves.toEqual({kind: "done",- providerOutcome: {- resolution: { credential: "oidc", file: ".env.local" },- status: { kind: "gateway-project", projectName: "my-agent" },- },+ accessChanged: true,+ providerSelection: "ai-gateway-project",});expect(runProviderFlow).toHaveBeenCalledWith(expect.objectContaining({ appRoot: APP_ROOT }));expect(menuPaints).toHaveLength(0);+ expect(deps.writeProviderSelection).toHaveBeenCalledWith(APP_ROOT, "ai-gateway-project");});- it("refreshes provider state after a committed setup is interrupted", async () => {+ it("preserves a committed provider selection when interrupted", async () => {const { prompter } = scriptedPrompter({ menu: [] });const controller = new AbortController();- const detectProviderStatus = vi- .fn<ModelFlowDeps["detectProviderStatus"]>()- .mockResolvedValueOnce({ kind: "gateway-project", projectName: "my-agent" })- .mockResolvedValueOnce({- kind: "gateway-key",- envKey: "AI_GATEWAY_API_KEY",- source: { kind: "env-file", path: ".env.local" },- });+ const resolveAvailableProviders = vi.fn<ModelFlowDeps["resolveAvailableProviders"]>(+ async () => ["chatgpt", "ai-gateway-project"],+ );const runProviderFlow = vi.fn<ModelFlowDeps["runProviderFlow"]>(async () => {controller.abort();- return {- kind: "done",- resolution: { credential: "api-key", source: { kind: "env-file", path: ".env.local" } },- };+ return { kind: "ai-gateway-key" };});- const deps = flowDeps({ detectProviderStatus, runProviderFlow });+ const deps = flowDeps({ resolveAvailableProviders, runProviderFlow });await expect(runModelFlow({@@ -616,16 +799,10 @@ describe("runModelFlow", () => {}),).resolves.toEqual({kind: "done",- providerOutcome: {- resolution: { credential: "api-key", source: { kind: "env-file", path: ".env.local" } },- status: {- kind: "gateway-key",- envKey: "AI_GATEWAY_API_KEY",- source: { kind: "env-file", path: ".env.local" },- },- },+ accessChanged: true,+ providerSelection: "ai-gateway-key",});- expect(detectProviderStatus.mock.calls[1]?.[1]).toEqual({});+ expect(resolveAvailableProviders).toHaveBeenCalledTimes(1);});it("treats the external-provider branch as informational — no notice, no outcome", async () => {@@ -640,7 +817,7 @@ describe("runModelFlow", () => {kind: "cancelled",});- expect(deps.detectProviderStatus).toHaveBeenCalledTimes(1);+ expect(deps.resolveAvailableProviders).toHaveBeenCalledTimes(1);expect(menuPaints[1]?.notices).toEqual([]);});@@ -654,8 +831,8 @@ describe("runModelFlow", () => {kind: "cancelled",});- // A cancelled sub-flow changed nothing, so the status is not re-read.- expect(deps.detectProviderStatus).toHaveBeenCalledTimes(1);+ // A cancelled sub-flow changed nothing, so availability is not re-read.+ expect(deps.resolveAvailableProviders).toHaveBeenCalledTimes(1);expect(menuPaints).toHaveLength(2);expect(menuPaints[1]?.notices).toEqual([]);expect(deps.applySettings).not.toHaveBeenCalled();@@ -665,9 +842,8 @@ describe("runModelFlow", () => {it("opens on the model row when a provider is already set", async () => {const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });const deps = flowDeps({- detectProviderStatus: vi.fn(- async () => ({ kind: "gateway-project", projectName: "my-agent" }) as const,- ),+ resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-project"] as const),+ readProviderSelection: vi.fn(async () => "ai-gateway-project" as const),});await runModelFlow({ appRoot: APP_ROOT, prompter, deps });diff --git a/packages/eve/src/setup/flows/model.ts b/packages/eve/src/setup/flows/model.tsindex 5860f2b87..9d873ac59 100644--- a/packages/eve/src/setup/flows/model.ts+++ b/packages/eve/src/setup/flows/model.ts@@ -1,10 +1,10 @@-import {- hasEnvValue,- resolveGatewayCredential,- type GatewayCredentialResolution,-} from "#internal/resolve-model-endpoint-status.js";-import { inspectApplication } from "#services/inspect-application.js";+import {+ readProviderSelection,+ resolveAvailableProviders,+ writeProviderSelection,+ type ProviderSelection,+} from "#setup/provider-settings.js";import type {AgentModelSettingsPatch,FieldPatch,@@ -13,7 +13,6 @@ import type {import pc from "picocolors";import { AI_GATEWAY_API_KEY_ENV_VAR } from "../ai-gateway-api-key.js";-import { findEnvFileWithKey } from "../boxes/detect-ai-gateway.js";import {fetchGatewayCatalog,modelOptionsFromCatalog,@@ -25,11 +24,13 @@ import {type GatewayModelCapabilities,type ReasoningLevel,} from "../boxes/model-capabilities.js";-import {- detectProjectIdentity,- type VercelProjectOperationOptions,-} from "../project-resolution.js";import type { AgentReasoningDefinition, ModelRouting } from "#shared/agent-definition.js";+import {+ DEFAULT_CHATGPT_MODEL_SELECTION,+ isChatGptModelRouting,+ parseChatGptModelSelection,+} from "#shared/chatgpt-model.js";+import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";import {readGatewayServiceTier,type GatewayServiceTierState,@@ -43,7 +44,8 @@ import {formatApplyModelSettingsOutcome,type ApplyModelSettingsOutcome,} from "./model-source-change.js";-import { runProviderFlow, type ModelProviderStatus } from "./provider.js";+import { ensureChatGptAuth } from "./chatgpt-auth.js";+import { runProviderFlow } from "./provider.js";/** The current model id, its routing, and whether `/model` can rewrite it. */export interface CurrentAgentModel {@@ -115,26 +117,15 @@ export interface ModelFlowDeps {selectModel?: SelectModelDeps;/** The composite Change-model screen; the dev TUI renderer implements it. */pickModelSettings?: ModelSettingsPicker;- /** Reads how the model is backed right now, for the menu's provider row. */- detectProviderStatus: typeof detectModelProviderStatus;+ /** Resolves provider credentials available to this project. */+ resolveAvailableProviders: typeof resolveAvailableProviders;+ /** Reads the explicit provider selection, if one has been made. */+ readProviderSelection: typeof readProviderSelection;/** The provider sub-flow behind the menu's provider row. */runProviderFlow: typeof runProviderFlow;-}--export type { ModelProviderStatus };--/**- * A provider sub-flow run that actually moved the provider: the credential- * the link flow verified landed in an env file (when one did), paired with- * the re-detected {@link ModelProviderStatus} — the same read the menu's- * provider row shows, so every surface reports one truth. The sub-flow's- * external-provider branch only shows instructions — nothing changes on- * disk — so it never surfaces as an outcome.- */-export interface ModelProviderOutcome {- /** The credential resolution the runtime will honor; see {@link LinkFlowResult}. */- resolution?: GatewayCredentialResolution;- status: ModelProviderStatus;+ /** Ensures Codex owns a usable login before selecting ChatGPT. */+ ensureChatGptAuth: typeof ensureChatGptAuth;+ writeProviderSelection: typeof writeProviderSelection;}export type ModelFlowResult =@@ -145,10 +136,12 @@ export type ModelFlowResult =}| {kind: "done";+ /** Whether authored source, auth, or Gateway selection committed. */+ accessChanged: boolean;/** The last apply line, when the model was changed this session. */modelMessage?: string;- /** The last provider sub-flow outcome, when one ran to completion. */- providerOutcome?: ModelProviderOutcome;+ /** The provider selected in a completed provider sub-flow. */+ providerSelection?: ProviderSelection;};// The bordered panel's title ("Configure the agent model") is the menu's header,@@ -157,24 +150,18 @@ export const MODEL_MENU_MESSAGE = "";type ModelMenuRow = "model" | "provider" | "done";-/**- * The provider row's value line. `emphasis` bolds the project and team names- * for the menu (the stacked hint line renders embedded bold safely); the- * plain form feeds notice and outcome copy.- */-function providerStatusHint(- provider: Exclude<ModelProviderStatus, { kind: "unset" }>,- emphasis: (text: string) => string = (text) => text,+function providerSelectionHint(+ provider: ProviderSelection,+ chatGptAccountLabel: string | undefined,): string {- if (provider.kind === "gateway-project") {- const where =- provider.teamName === undefined- ? emphasis(provider.projectName)- : `${emphasis(provider.projectName)} in ${emphasis(provider.teamName)}`;- return `AI Gateway (Linked to ${where})`;+ if (provider === "chatgpt") {+ return chatGptAccountLabel === undefined+ ? "ChatGPT subscription"+ : `ChatGPT subscription (${chatGptAccountLabel})`;}- const where = provider.source.kind === "shell" ? "your shell" : provider.source.path;- return `AI Gateway (${provider.envKey} in ${where})`;+ return provider === "ai-gateway-project"+ ? "AI Gateway via Project"+ : `AI Gateway via ${AI_GATEWAY_API_KEY_ENV_VAR}`;}/**@@ -220,13 +207,16 @@ function formatModelDraftHint(* disables it (gateway credentials don't apply); a gateway endpoint gates it* bold-yellow "Configure model access" until a link or credential is* detectable (the genuine "no provider connected" state), then "Change- * provider" naming it.+ * provider" with the stored selection. Authored routing does not resolve that+ * preference.*/function modelMenuRows(current: string | null,reasoning: ReasoningLevel | null,serviceTier: GatewayServiceTierState,- provider: ModelProviderStatus,+ selectedProvider: ProviderSelection,+ providerConfigured: boolean,+ chatGptAccountLabel: string | undefined,routing: ModelRouting | null,editable: boolean,settingsEditable: boolean,@@ -253,14 +243,14 @@ function modelMenuRows(}let providerRow: SelectOption<ModelMenuRow>;- if (routing?.kind === "external") {+ if (routing?.kind === "external" && !isChatGptModelRouting(routing)) {providerRow = {disabled: true,value: "provider",label: "Change provider",description: "Disabled in external endpoint mode",};- } else if (provider.kind === "unset") {+ } else if (!providerConfigured) {providerRow = {value: "provider",label: pc.bold("Configure model access"),@@ -272,7 +262,7 @@ function modelMenuRows(providerRow = {value: "provider",label: "Change provider",- hint: providerStatusHint(provider, pc.bold),+ hint: providerSelectionHint(selectedProvider, chatGptAccountLabel),description: "How your agent reaches the model provider",};}@@ -282,48 +272,6 @@ function modelMenuRows(return [modelRow, providerRow, { value: "done", label: "Done" }];}-/**- * Reads the provider status the menu shows. Detection order matters: a linked- * project subsumes any pulled credential (the link is what the user manages),- * and `AI_GATEWAY_API_KEY` outranks `VERCEL_OIDC_TOKEN` because it is the one- * the provider sub-flow's own-key branch writes.- */-export async function detectModelProviderStatus(- appRoot: string,- options: VercelProjectOperationOptions = {},- env: Record<string, string | undefined> = process.env,-): Promise<ModelProviderStatus> {- const [identity, gatewayKeyFile, oidcFile] = await Promise.all([- detectProjectIdentity(appRoot, options),- findEnvFileWithKey(appRoot, AI_GATEWAY_API_KEY_ENV_VAR),- findEnvFileWithKey(appRoot, "VERCEL_OIDC_TOKEN"),- ]);- if (identity !== undefined) {- const status: ModelProviderStatus = {- kind: "gateway-project",- projectName: identity.projectName,- };- if (identity.teamName !== undefined) status.teamName = identity.teamName;- return status;- }- const evidence: { apiKeyInEnv: boolean; apiKeyFile?: string; oidcFile?: string } = {- apiKeyInEnv: hasEnvValue(env[AI_GATEWAY_API_KEY_ENV_VAR]),- };- if (gatewayKeyFile !== undefined) evidence.apiKeyFile = gatewayKeyFile;- if (oidcFile !== undefined) evidence.oidcFile = oidcFile;- const resolution = resolveGatewayCredential(evidence);- if (resolution === undefined) return { kind: "unset" };- if (resolution.credential === "api-key") {- return { kind: "gateway-key", envKey: AI_GATEWAY_API_KEY_ENV_VAR, source: resolution.source };- }- return {- kind: "gateway-key",- envKey: "VERCEL_OIDC_TOKEN",- // The resolver only reports an OIDC file we handed it, so it is set here.- source: { kind: "env-file", path: resolution.file! },- };-}-/*** THE MODEL FLOW for the dev TUI's `/model`: a root menu whose Change model* row opens the composite model screen (catalog pick, reasoning-effort slider,@@ -339,31 +287,39 @@ export async function runModelFlow(input: {/** Opens provider setup before the root menu when runtime evidence requires it. */initialStep?: "provider";signal?: AbortSignal;+ /** Gives Codex uncontested inherited stdio while it performs login. */+ withExclusiveTerminal?: <T>(task: () => Promise<T>) => Promise<T>;+ /** Live ChatGPT identity shown in this configuration flow only. */+ chatGptAccountLabel?: string;deps?: Partial<ModelFlowDeps>;}): Promise<ModelFlowResult> {const { appRoot, prompter, signal } = input;const deps: ModelFlowDeps = {readCurrentModel: readCurrentAgentModel,applySettings: changeAgentModelSettings,- detectProviderStatus: detectModelProviderStatus,+ resolveAvailableProviders,+ readProviderSelection,runProviderFlow,+ ensureChatGptAuth,+ writeProviderSelection,...input.deps,};- // The model read is local; the provider status and the catalog are round- // trips. One ephemeral spinner covers all three so the menu paints with no- // persisted loading lines and already knows what the model supports. A- // failed catalog fetch degrades to unknown capabilities, never to an error.- const detectProvider = (useFlowSignal = true): Promise<ModelProviderStatus> =>- deps.detectProviderStatus(appRoot, useFlowSignal && signal !== undefined ? { signal } : {});+ // One ephemeral spinner covers the local model/provider reads and catalog+ // fetch so the menu paints with no persisted loading lines. A failed catalog+ // fetch degrades to unknown capabilities, never to an error.const fetchCatalog = deps.selectModel?.fetchModels ?? fetchGatewayCatalog;- const [currentModel, initialProvider, catalog] = await withSpinner(+ const [currentModel, availableProviders, storedProviderSelection, catalog] = await withSpinner(prompter,"Checking the project…",() =>Promise.all([deps.readCurrentModel(appRoot),- detectProvider(),+ deps.resolveAvailableProviders(+ appRoot,+ signal === undefined ? { env: process.env } : { signal, env: process.env },+ ),+ deps.readProviderSelection(appRoot),fetchCatalog(signal).catch((): GatewayCatalogModel[] | undefined => undefined),]),);@@ -373,7 +329,11 @@ export async function runModelFlow(input: {// An authored "provider-default" is the absent-setting sentinel, not a level.let reasoning: ReasoningLevel | null =currentModel.reasoning === "provider-default" ? null : currentModel.reasoning;- let provider = initialProvider;+ const selectedProvider =+ storedProviderSelection ??+ (availableProviders.includes("ai-gateway-key") ? "ai-gateway-key" : "ai-gateway-project");+ const providerConfigured = availableProviders.includes(selectedProvider);+ let nextProviderSelection: ProviderSelection | undefined;const patch: {model: FieldPatch<string>;reasoning: FieldPatch<AgentReasoningDefinition>;@@ -385,19 +345,21 @@ export async function runModelFlow(input: {};let lastApply: ApplyModelSettingsOutcome | undefined;- let providerOutcome: ModelProviderOutcome | undefined;+ let committedProviderSelection: ProviderSelection | undefined;+ let shouldAuthenticateChatGpt = false;let commitDraft = false;- const externalNotice: SelectNotice | undefined =- routing?.kind === "external"- ? {- tone: "warning",- text: "`agent.ts` specifies the model provider directly. Model, provider, and service-tier changes stay source-owned; reasoning remains configurable here.",- }- : undefined;+ const sourceOwnedExternalRouting =+ routing?.kind === "external" && !isChatGptModelRouting(routing);+ const externalNotice: SelectNotice | undefined = sourceOwnedExternalRouting+ ? {+ tone: "warning",+ text: "`agent.ts` specifies the model provider directly. Model, provider, and service-tier changes stay source-owned; reasoning remains configurable here.",+ }+ : undefined;// Start at the first useful row. Cancellation keeps the current row.let nextSelection: ModelMenuRow =- provider.kind === "unset" && routing?.kind !== "external"+ !providerConfigured && routing?.kind !== "external"? "provider": editable || settingsEditable? "model"@@ -405,7 +367,7 @@ export async function runModelFlow(input: {// A gateway model with no provider cannot run. Skip the menu's extra Enter// and open provider setup as soon as that state is confirmed.let openProviderFirst =- routing?.kind !== "external" && (input.initialStep === "provider" || provider.kind === "unset");+ routing?.kind !== "external" && (input.initialStep === "provider" || !providerConfigured);while (true) {let pick: ModelMenuRow;@@ -419,8 +381,10 @@ export async function runModelFlow(input: {options: modelMenuRows(current,reasoning,- serviceTier,- provider,+ isChatGptModelRouting(routing) ? { kind: "standard" } : serviceTier,+ selectedProvider,+ providerConfigured,+ input.chatGptAccountLabel,routing,editable,settingsEditable,@@ -457,9 +421,9 @@ export async function runModelFlow(input: {reason: "Set via an SDK model call in agent.ts; edit the source to change it",},reasoning,- serviceTier,+ serviceTier: isChatGptModelRouting(routing) ? { kind: "standard" } : serviceTier,settingsEditable,- externalRouting: routing?.kind === "external",+ externalRouting: sourceOwnedExternalRouting,capabilitiesFor: (modelId) => gatewayModelCapabilities(catalog, modelId),};const result = await pickModelSettings(request);@@ -470,7 +434,7 @@ export async function runModelFlow(input: {}if (result.model !== undefined) {current = result.model;- routing = { kind: "gateway", target: result.model.split("/")[0] ?? "" };+ routing = routingForModelSelection(result.model);patch.model = { kind: "set", value: result.model };}if (result.reasoning !== undefined) {@@ -478,7 +442,7 @@ export async function runModelFlow(input: {patch.reasoning =reasoning === null ? { kind: "remove" } : { kind: "set", value: reasoning };}- if (result.serviceTier !== undefined) {+ if (result.serviceTier !== undefined && !isChatGptModelRouting(routing)) {serviceTier =result.serviceTier === "priority" ? { kind: "priority" } : { kind: "standard" };patch.gatewayServiceTier =@@ -494,7 +458,8 @@ export async function runModelFlow(input: {appRoot,prompter,signal,- currentProvider: provider,+ availableProviders,+ selectedProvider,});// Backing out of the provider sub-flow changed nothing; the cursor stays on// the provider row so a retry is one keypress away.@@ -509,33 +474,80 @@ export async function runModelFlow(input: {nextSelection = "done";continue;}- // Only a completed link/own-key sub-flow can move the link or- // credentials, so this is the one place the status is re-read. Once that- // sub-flow commits, finish without the aborted interaction signal so the- // TUI can refresh the state that is already on disk.- provider = await withSpinner(prompter, "Checking the project…", () => detectProvider(false));- providerOutcome = { status: provider };- if (result.kind === "done" && result.resolution !== undefined) {- providerOutcome.resolution = result.resolution;+ nextProviderSelection = result.kind;+ if (nextProviderSelection === "chatgpt") {+ shouldAuthenticateChatGpt = true;+ if (!isChatGptModelRouting(routing)) {+ patch.model = { kind: "set", value: DEFAULT_CHATGPT_MODEL_SELECTION };+ patch.gatewayServiceTier = { kind: "remove" };+ }+ } else if (isChatGptModelRouting(routing)) {+ patch.model = { kind: "set", value: DEFAULT_AGENT_MODEL_ID };}commitDraft = true;break;}+ const selectsChatGpt =+ patch.model.kind === "set" && parseChatGptModelSelection(patch.model.value) !== undefined;+ if (commitDraft && selectsChatGpt) {+ patch.gatewayServiceTier = { kind: "remove" };+ shouldAuthenticateChatGpt = true;+ }+ if (commitDraft && shouldAuthenticateChatGpt) {+ await authenticateChatGpt(deps, input.withExclusiveTerminal);+ }+if (commitDraft && hasModelSettingsChanges(patch)) {lastApply = await deps.applySettings({ appRoot, patch });+ }+ if (commitDraft && nextProviderSelection !== undefined && lastApply?.kind !== "rejected") {+ await deps.writeProviderSelection(appRoot, nextProviderSelection);+ committedProviderSelection = nextProviderSelection;+ }+ if (lastApply !== undefined && committedProviderSelection === undefined) {signal?.throwIfAborted();}- if (lastApply === undefined && providerOutcome === undefined) {+ if (+ lastApply === undefined &&+ committedProviderSelection === undefined &&+ !shouldAuthenticateChatGpt+ ) {return { kind: "cancelled" };}- const done: Extract<ModelFlowResult, { kind: "done" }> = { kind: "done" };+ const done: Extract<ModelFlowResult, { kind: "done" }> = {+ kind: "done",+ accessChanged:+ lastApply?.kind === "changed" ||+ committedProviderSelection !== undefined ||+ shouldAuthenticateChatGpt,+ };if (lastApply !== undefined) done.modelMessage = formatApplyModelSettingsOutcome(lastApply);- if (providerOutcome !== undefined) done.providerOutcome = providerOutcome;+ else if (shouldAuthenticateChatGpt) done.modelMessage = "ChatGPT login ready.";+ if (committedProviderSelection !== undefined) {+ done.providerSelection = committedProviderSelection;+ }return done;}+function routingForModelSelection(selection: string): ModelRouting {+ if (parseChatGptModelSelection(selection) !== undefined) {+ return { kind: "external", provider: "codex" };+ }+ return { kind: "gateway", target: selection.split("/")[0] ?? "" };+}++async function authenticateChatGpt(+ deps: ModelFlowDeps,+ withExclusiveTerminal: (<T>(task: () => Promise<T>) => Promise<T>) | undefined,+): Promise<void> {+ const authenticate = (): Promise<void> => deps.ensureChatGptAuth();+ await (withExclusiveTerminal === undefined+ ? authenticate()+ : withExclusiveTerminal(authenticate));+}+function hasModelSettingsChanges(patch: AgentModelSettingsPatch): boolean {return (patch.model.kind !== "keep" ||@@ -556,12 +568,13 @@ async function readCurrentAgentModel(appRoot: string): Promise<CurrentAgentModelconst model = config?.model;// A source-backed model (an SDK model call) carries `source`; a string id// does not, and only a string is a literal the editor can rewrite.+ const chatgpt = isChatGptModelRouting(model?.routing);return {- id: model?.id ?? null,+ id: chatgpt && model !== undefined ? `chatgpt/${model.id}` : (model?.id ?? null),routing: model?.routing ?? null,reasoning: config?.reasoning ?? null,serviceTier: readGatewayServiceTier(model?.providerOptions),- editable: model !== undefined && model.source === undefined,+ editable: model !== undefined && (model.source === undefined || chatgpt),settingsEditable: config?.source !== undefined,};} catch {@@ -586,9 +599,7 @@ export async function modelChangeRefusalForUneditableModel(appRoot: string,): Promise<string | null> {const { editable, routing } = await readCurrentAgentModel(appRoot);- if (editable) {- return null;- }+ if (editable) return null;const detail =routing?.kind === "external"? `the external provider \`${routing.provider}\``diff --git a/packages/eve/src/setup/flows/provider-selection-cycle.integration.test.ts b/packages/eve/src/setup/flows/provider-selection-cycle.integration.test.tsnew file mode 100644index 000000000..a93bf2d0b--- /dev/null+++ b/packages/eve/src/setup/flows/provider-selection-cycle.integration.test.ts@@ -0,0 +1,108 @@+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++import { createFakePrompter } from "#internal/testing/fake-prompter.js";+import { DEFAULT_CHATGPT_MODEL_SELECTION } from "#shared/chatgpt-model.js";+import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";+import {+ readProviderSelection,+ writeProviderSelection,+ type ProviderSelection,+} from "#setup/provider-settings.js";++import { runModelFlow, type CurrentAgentModel, type ModelFlowDeps } from "./model.js";+import { runProviderFlow, type ProviderFlowDeps, type ProviderPickerChoice } from "./provider.js";++const roots: string[] = [];++afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));+});++describe("provider selection", () => {+ it("cycles among independently available providers", async () => {+ const root = await mkdtemp(join(tmpdir(), "eve-provider-selection-"));+ roots.push(root);+ await writeFile(join(root, ".env.local"), "AI_GATEWAY_API_KEY=key\nVERCEL_OIDC_TOKEN=token\n");+ await writeProviderSelection(root, "ai-gateway-project");++ let currentModel: CurrentAgentModel = {+ id: DEFAULT_AGENT_MODEL_ID,+ routing: { kind: "gateway", target: "openai" },+ reasoning: null,+ serviceTier: { kind: "standard" },+ editable: true,+ settingsEditable: true,+ };+ const choices: ProviderPickerChoice[] = [+ { kind: "chatgpt" },+ { kind: "ai-gateway-project" },+ { kind: "ai-gateway-key", key: "replacement-key", validation: { kind: "valid" } },+ { kind: "ai-gateway-project" },+ ];+ const providerDeps: ProviderFlowDeps = {+ getVercelAuthStatus: vi.fn<ProviderFlowDeps["getVercelAuthStatus"]>(+ async () => "authenticated",+ ),+ runLinkFlow: vi.fn<ProviderFlowDeps["runLinkFlow"]>(async () => ({ kind: "done" })),+ appendEnv: vi.fn<ProviderFlowDeps["appendEnv"]>(async () => ({+ written: ["AI_GATEWAY_API_KEY"],+ skipped: [],+ })),+ validateGatewayApiKey: vi.fn<ProviderFlowDeps["validateGatewayApiKey"]>(async () => ({+ kind: "valid",+ })),+ };+ const applySettings = vi.fn<ModelFlowDeps["applySettings"]>(async ({ patch }) => {+ if (patch.model.kind !== "set") return { kind: "unchanged" };+ const chatGpt = patch.model.value === DEFAULT_CHATGPT_MODEL_SELECTION;+ currentModel = {+ ...currentModel,+ id: patch.model.value,+ routing: chatGpt+ ? { kind: "external", provider: "codex" }+ : { kind: "gateway", target: patch.model.value.split("/")[0] ?? "" },+ };+ return { kind: "changed", changed: ["model"], model: patch.model.value };+ });+ const deps: Partial<ModelFlowDeps> = {+ readCurrentModel: vi.fn(async () => currentModel),+ applySettings,+ selectModel: { fetchModels: async () => [] },+ runProviderFlow: (input) =>+ runProviderFlow({+ ...input,+ picker: async () => {+ const choice = choices.shift();+ if (choice === undefined) throw new Error("Provider choice script exhausted");+ return choice;+ },+ deps: providerDeps,+ }),+ ensureChatGptAuth: vi.fn(async () => {}),+ };++ const selectNextProvider = async (expected: ProviderSelection): Promise<void> => {+ const { prompter } = createFakePrompter({ single: () => "provider" });+ await expect(runModelFlow({ appRoot: root, prompter, deps })).resolves.toMatchObject({+ kind: "done",+ providerSelection: expected,+ });+ await expect(readProviderSelection(root)).resolves.toBe(expected);+ };++ await selectNextProvider("chatgpt");+ await selectNextProvider("ai-gateway-project");+ await selectNextProvider("ai-gateway-key");+ await selectNextProvider("ai-gateway-project");++ expect(choices).toEqual([]);+ expect(providerDeps.runLinkFlow).not.toHaveBeenCalled();+ expect(providerDeps.getVercelAuthStatus).not.toHaveBeenCalled();+ expect(providerDeps.appendEnv).toHaveBeenCalledOnce();+ expect(deps.ensureChatGptAuth).toHaveBeenCalledOnce();+ expect(applySettings).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/eve/src/setup/flows/provider.test.ts b/packages/eve/src/setup/flows/provider.test.tsindex 9ef703478..693f14782 100644--- a/packages/eve/src/setup/flows/provider.test.ts+++ b/packages/eve/src/setup/flows/provider.test.ts@@ -1,4 +1,3 @@-import pc from "picocolors";import { describe, expect, it, vi } from "vitest";import { createFakePrompter } from "#internal/testing/fake-prompter.js";@@ -20,7 +19,6 @@ function createDeps() {getVercelAuthStatus: vi.fn(async (): Promise<VercelAuthStatus> => "authenticated"),runLinkFlow: vi.fn<ProviderFlowDeps["runLinkFlow"]>(async () => ({kind: "done",- resolution: { credential: "oidc", file: ".env.local" },})),appendEnv: vi.fn<ProviderFlowDeps["appendEnv"]>(async () => ({written: ["AI_GATEWAY_API_KEY"],@@ -32,32 +30,51 @@ function createDeps() {};}+type ProviderFlowInput = Parameters<typeof runProviderFlow>[0];++function runTestProviderFlow(+ input: Omit<ProviderFlowInput, "availableProviders" | "selectedProvider"> &+ Partial<Pick<ProviderFlowInput, "availableProviders" | "selectedProvider">>,+) {+ return runProviderFlow({+ availableProviders: ["chatgpt", "ai-gateway-project"],+ selectedProvider: "ai-gateway-project",+ ...input,+ });+}+describe("runProviderFlow", () => {- it("hands the Dev TUI one project, inline-key, and direct-provider menu", async () => {+ it("hands the Dev TUI one menu and lets the active project be replaced", async () => {const fake = createFakePrompter();const deps = createDeps();const picker: ProviderPicker = async (request) => {expect(request.message).toBe(PROVIDER_QUESTION);expect(request.options.map((option) => option.value)).toEqual([- "project",- "own-key",+ "ai-gateway-project",+ "ai-gateway-key",+ "chatgpt","external",]);- expect(request.initialValue).toBe("project");- return { kind: "project" };+ expect(request.options[2]).toMatchObject({+ value: "chatgpt",+ label: "ChatGPT subscription",+ });+ expect(request.options[3]).toMatchObject({+ value: "external",+ label: "Other providers",+ });+ expect(request.initialValue).toBe("ai-gateway-project");+ return { kind: "ai-gateway-project" };};- const result = await runProviderFlow({+ const result = await runTestProviderFlow({appRoot: APP_ROOT,prompter: fake.prompter,picker,deps,});- expect(result).toEqual({- kind: "done",- resolution: { credential: "oidc", file: ".env.local" },- });+ expect(result).toEqual({ kind: "ai-gateway-project" });expect(deps.runLinkFlow).toHaveBeenCalledExactlyOnceWith({appRoot: APP_ROOT,prompter: fake.prompter,@@ -65,49 +82,142 @@ describe("runProviderFlow", () => {});});+ it("returns ChatGPT without touching Gateway setup", async () => {+ const fake = createFakePrompter();+ const deps = createDeps();++ const result = await runTestProviderFlow({+ appRoot: APP_ROOT,+ prompter: fake.prompter,+ picker: async (request) => {+ expect(request.options.map((option) => option.value)).toEqual([+ "ai-gateway-project",+ "ai-gateway-key",+ "chatgpt",+ "external",+ ]);+ return { kind: "chatgpt" };+ },+ deps,+ });++ expect(result).toEqual({ kind: "chatgpt" });+ expect(deps.getVercelAuthStatus).not.toHaveBeenCalled();+ expect(deps.runLinkFlow).not.toHaveBeenCalled();+ expect(deps.appendEnv).not.toHaveBeenCalled();+ });++ it("selects an available linked project without opening the link flow", async () => {+ const fake = createFakePrompter();+ const deps = createDeps();++ const result = await runTestProviderFlow({+ appRoot: APP_ROOT,+ prompter: fake.prompter,+ picker: async () => ({ kind: "ai-gateway-project" }),+ selectedProvider: "chatgpt",+ deps,+ });++ expect(result).toEqual({ kind: "ai-gateway-project" });+ expect(deps.getVercelAuthStatus).not.toHaveBeenCalled();+ expect(deps.runLinkFlow).not.toHaveBeenCalled();+ });+it("checks and describes the active provider, opening the cursor on it", async () => {const fake = createFakePrompter();const deps = createDeps();const linked: ProviderPicker = async (request) => {- expect(request.initialValue).toBe("project");+ expect(request.initialValue).toBe("ai-gateway-project");expect(request.options[0]).toMatchObject({- value: "project",+ value: "ai-gateway-project",checked: true,- hint: `Linked to ${pc.bold("my-agent")} in team ${pc.bold("my-team")}`,+ hint: "Current",});expect(request.options[1]?.checked).toBeUndefined();return undefined;};- await runProviderFlow({+ await runTestProviderFlow({appRoot: APP_ROOT,prompter: fake.prompter,picker: linked,- currentProvider: {- kind: "gateway-project",- projectName: "my-agent",- teamName: "my-team",- },+ selectedProvider: "ai-gateway-project",deps,});const keyed: ProviderPicker = async (request) => {- expect(request.initialValue).toBe("own-key");+ expect(request.initialValue).toBe("ai-gateway-key");expect(request.options[1]).toMatchObject({- value: "own-key",+ value: "ai-gateway-key",checked: true,- hint: "AI_GATEWAY_API_KEY set in .env.local",+ hint: "Current",});return undefined;};- await runProviderFlow({+ await runTestProviderFlow({appRoot: APP_ROOT,prompter: fake.prompter,picker: keyed,- currentProvider: {- kind: "gateway-key",- envKey: "AI_GATEWAY_API_KEY",- source: { kind: "env-file", path: ".env.local" },- },+ selectedProvider: "ai-gateway-key",+ deps,+ });+ });++ it("uses the stored selection when multiple providers are available", async () => {+ const fake = createFakePrompter();+ const deps = createDeps();+ const picker: ProviderPicker = async (request) => {+ expect(request.initialValue).toBe("ai-gateway-project");+ expect(request.options.find((option) => option.value === "ai-gateway-project")?.checked).toBe(+ true,+ );+ expect(+ request.options.find((option) => option.value === "ai-gateway-key")?.checked,+ ).toBeUndefined();+ return undefined;+ };++ await runTestProviderFlow({+ appRoot: APP_ROOT,+ prompter: fake.prompter,+ picker,+ selectedProvider: "ai-gateway-project",+ deps,+ });+ });++ it("preserves cancellation from the project link flow", async () => {+ const fake = createFakePrompter();+ const deps = createDeps();+ deps.runLinkFlow.mockResolvedValueOnce({ kind: "cancelled" });++ await expect(+ runTestProviderFlow({+ appRoot: APP_ROOT,+ prompter: fake.prompter,+ picker: async () => ({ kind: "ai-gateway-project" }),+ deps,+ }),+ ).resolves.toEqual({ kind: "cancelled" });+ });++ it("opens on ChatGPT when it is the selected provider", async () => {+ const fake = createFakePrompter();+ const deps = createDeps();+ const picker: ProviderPicker = async (request) => {+ expect(request.initialValue).toBe("chatgpt");+ expect(request.options.find((option) => option.value === "chatgpt")).toMatchObject({+ checked: true,+ hint: "Current",+ });+ return undefined;+ };++ await runTestProviderFlow({+ appRoot: APP_ROOT,+ prompter: fake.prompter,+ picker,+ selectedProvider: "chatgpt",deps,});});@@ -116,10 +226,14 @@ describe("runProviderFlow", () => {const fake = createFakePrompter();const deps = createDeps();- await runProviderFlow({+ await runTestProviderFlow({appRoot: APP_ROOT,prompter: fake.prompter,- picker: async () => ({ kind: "inline-key", key: "sk-inline", validation: { kind: "valid" } }),+ picker: async () => ({+ kind: "ai-gateway-key",+ key: "sk-inline",+ validation: { kind: "valid" },+ }),deps,});@@ -133,20 +247,17 @@ describe("runProviderFlow", () => {const signal = new AbortController().signal;const validation = await request.validateInlineKey("sk-inline", signal);if (validation.kind === "invalid") throw new Error(validation.message);- return { kind: "inline-key", key: "sk-inline", validation };+ return { kind: "ai-gateway-key", key: "sk-inline", validation };};- const result = await runProviderFlow({+ const result = await runTestProviderFlow({appRoot: APP_ROOT,prompter: fake.prompter,picker,deps,});- expect(result).toEqual({- kind: "done",- resolution: { credential: "api-key", source: { kind: "env-file", path: ".env.local" } },- });+ expect(result).toEqual({ kind: "ai-gateway-key" });expect(deps.validateGatewayApiKey).toHaveBeenCalledExactlyOnceWith("sk-inline",expect.any(AbortSignal),@@ -162,7 +273,7 @@ describe("runProviderFlow", () => {const fake = createFakePrompter();const deps = createDeps();const picker: ProviderPicker = async () => ({- kind: "inline-key",+ kind: "ai-gateway-key",key: "sk-committed",validation: { kind: "valid" },});@@ -175,7 +286,7 @@ describe("runProviderFlow", () => {});const controller = new AbortController();- const execution = runProviderFlow({+ const execution = runTestProviderFlow({appRoot: APP_ROOT,prompter: fake.prompter,picker,@@ -186,17 +297,14 @@ describe("runProviderFlow", () => {controller.abort();releaseWrite.resolve();- await expect(execution).resolves.toEqual({- kind: "done",- resolution: { credential: "api-key", source: { kind: "env-file", path: ".env.local" } },- });+ await expect(execution).resolves.toEqual({ kind: "ai-gateway-key" });});it("shows direct-provider instructions without changing credentials", async () => {const fake = createFakePrompter();const deps = createDeps();- const result = await runProviderFlow({+ const result = await runTestProviderFlow({appRoot: APP_ROOT,prompter: fake.prompter,picker: async () => ({ kind: "external" }),@@ -216,7 +324,7 @@ describe("runProviderFlow", () => {const deps = createDeps();await expect(- runProviderFlow({+ runTestProviderFlow({appRoot: APP_ROOT,prompter: fake.prompter,picker: async () => undefined,diff --git a/packages/eve/src/setup/flows/provider.ts b/packages/eve/src/setup/flows/provider.tsindex c6b310f2f..024a83512 100644--- a/packages/eve/src/setup/flows/provider.ts+++ b/packages/eve/src/setup/flows/provider.ts@@ -1,5 +1,3 @@-import pc from "picocolors";-import { appendEnv } from "../append-env.js";import {AI_GATEWAY_API_KEY_ENV_FILE,@@ -16,27 +14,11 @@ import {} from "../vercel-project.js";import { withSpinner } from "../with-spinner.js";-import type { GatewayCredentialSource } from "#internal/resolve-model-endpoint-status.js";+import type { ProviderSelection } from "#setup/provider-settings.js";-import { runLinkFlow, type LinkFlowResult } from "./link.js";+import { runLinkFlow } from "./link.js";-export type ProviderConnection = "project" | "own-key" | "external";--/**- * How the agent's model is backed right now, as far as the local directory- * shows: a linked Vercel project, a gateway credential in an env file, or- * nothing detectable. An external provider (own ANTHROPIC_API_KEY etc.)- * leaves no marker eve owns, so it reads as `unset`.- */-export type ModelProviderStatus =- | { kind: "unset" }- | { kind: "gateway-project"; projectName: string; teamName?: string }- | {- kind: "gateway-key";- envKey: typeof AI_GATEWAY_API_KEY_ENV_VAR | "VERCEL_OIDC_TOKEN";- /** Where the credential lives — an env file, or the shell for a key. */- source: GatewayCredentialSource;- };+export type ProviderConnection = ProviderSelection | "external";export const PROVIDER_QUESTION = "Which model provider do you want to use?";@@ -56,21 +38,19 @@ export interface ProviderFlowDeps {validateGatewayApiKey: typeof validateGatewayApiKey;}-export type ProviderFlowResult =- | LinkFlowResult- | {- kind: "external-provider";- /** The user runs a non-gateway provider; nothing was linked or written. */- };+export type ProviderFlowResult = {+ kind: ProviderSelection | "cancelled" | "external-provider";+};type AcceptedGatewayKeyValidation = Exclude<GatewayKeyValidation, { kind: "invalid" }>;/** A provider choice, including the accepted evidence for an inline key. */export type ProviderPickerChoice =- | { kind: "project" }+ | { kind: "ai-gateway-project" }+ | { kind: "chatgpt" }| { kind: "external" }| {- kind: "inline-key";+ kind: "ai-gateway-key";key: string;validation: AcceptedGatewayKeyValidation;};@@ -92,7 +72,7 @@ function projectConnectionOption(authStatus: VercelAuthStatus | undefined,): SelectOption<ProviderConnection> {const option: SelectOption<ProviderConnection> = {- value: "project",+ value: "ai-gateway-project",label: "AI Gateway via Project",hint: "Authenticates with AI Gateway automatically\nin a new or existing project. No keys to manage.",};@@ -104,30 +84,31 @@ function projectConnectionOption(function providerOptions(authStatus: VercelAuthStatus | undefined,- current: ModelProviderStatus | undefined,+ selectedProvider: ProviderSelection,): SelectOption<ProviderConnection>[] {let project = projectConnectionOption(authStatus);- if (current?.kind === "gateway-project") {- const where =- current.teamName === undefined- ? pc.bold(current.projectName)- : `${pc.bold(current.projectName)} in team ${pc.bold(current.teamName)}`;- project = { ...project, checked: true, hint: `Linked to ${where}` };+ if (selectedProvider === "ai-gateway-project") {+ project = { ...project, checked: true, hint: "Current" };}- let ownKey: SelectOption<ProviderConnection> = {- value: "own-key",+ let gatewayKey: SelectOption<ProviderConnection> = {+ value: "ai-gateway-key",label: `AI Gateway via ${AI_GATEWAY_API_KEY_ENV_VAR}`,hint: "⎿ type your key",};- if (current?.kind === "gateway-key") {- const where = current.source.kind === "shell" ? "your shell" : current.source.path;- ownKey = { ...ownKey, checked: true, hint: `${current.envKey} set in ${where}` };+ if (selectedProvider === "ai-gateway-key") {+ gatewayKey = { ...gatewayKey, checked: true, hint: "Current" };}return [project,- ownKey,+ gatewayKey,+ {+ value: "chatgpt",+ label: "ChatGPT subscription",+ hint: selectedProvider === "chatgpt" ? "Current" : "Authenticate through the Codex CLI",+ checked: selectedProvider === "chatgpt" || undefined,+ },{value: "external",label: "Other providers",@@ -159,18 +140,21 @@ async function selectProvider(input: {/*** THE PROVIDER FLOW behind the dev TUI `/model` menu's provider row* (`eve link` keeps {@link runLinkFlow}'s shape). One question chooses a- * project-backed AI Gateway connection, an `AI_GATEWAY_API_KEY`, or an- * external provider. The project branch runs the link flow in create-or-link- * mode, so a project-less agent can create its first project rather than- * dead-end on an empty list.+ * project-backed AI Gateway connection, an `AI_GATEWAY_API_KEY`, ChatGPT, or a+ * direct provider. Selecting an available but inactive project only changes+ * the selection; selecting the active project opens the link flow so it can+ * be replaced. A project-less agent can create its first project there rather+ * than dead-end on an empty list.*/export async function runProviderFlow(input: {appRoot: string;prompter: Prompter;signal?: AbortSignal;picker?: ProviderPicker;- /** The detected provider, so the chooser can mark and describe the active row. */- currentProvider?: ModelProviderStatus;+ /** Provider availability resolved before the picker opened. */+ availableProviders: readonly ProviderSelection[];+ /** The current provider selection. */+ selectedProvider: ProviderSelection;deps?: Partial<ProviderFlowDeps>;}): Promise<ProviderFlowResult> {const { appRoot, prompter, signal } = input;@@ -183,17 +167,17 @@ export async function runProviderFlow(input: {};let authStatus: VercelAuthStatus | undefined;+ const { availableProviders, selectedProvider } = input;// The cursor opens on the active provider; a Vercel auth blocker still// re-homes it onto the key row below.- let initialValue: ProviderConnection =- input.currentProvider?.kind === "gateway-key" ? "own-key" : "project";- let keyChoice: Extract<ProviderPickerChoice, { kind: "inline-key" }>;+ let initialValue: ProviderConnection = selectedProvider;+ let keyChoice: Extract<ProviderPickerChoice, { kind: "ai-gateway-key" }>;try {while (true) {const choice = await selectProvider({picker: input.picker,- options: providerOptions(authStatus, input.currentProvider),+ options: providerOptions(authStatus, selectedProvider),initialValue,validateInlineKey: (key, validationSignal) =>deps.validateGatewayApiKey(@@ -217,26 +201,37 @@ export async function runProviderFlow(input: {return { kind: "external-provider" };}- if (choice.kind === "inline-key") {+ if (choice.kind === "chatgpt") return choice;++ if (choice.kind === "ai-gateway-key") {keyChoice = choice;break;}+ if (+ selectedProvider !== "ai-gateway-project" &&+ availableProviders.includes("ai-gateway-project")+ ) {+ return choice;+ }+const auth = await withSpinner(prompter, "Checking your Vercel login…", () =>deps.getVercelAuthStatus(appRoot, { signal }),);signal?.throwIfAborted();authStatus = auth;if (vercelAuthBlockerReason(authStatus) !== undefined) {- initialValue = "own-key";+ initialValue = "ai-gateway-key";continue;}- return await deps.runLinkFlow({+ const result = await deps.runLinkFlow({appRoot,prompter,signal,projectSelection: "create-or-link",});+ if (result.kind === "cancelled") return result;+ return { kind: "ai-gateway-project" };}} catch (error) {if (error instanceof WizardCancelledError) return { kind: "cancelled" };@@ -262,8 +257,5 @@ export async function runProviderFlow(input: {// remaining UI, but the caller must still refresh model access for the key// that is now on disk.prompter.log.success(`${location.envKey} set.`);- return {- kind: "done",- resolution: { credential: "api-key", source: { kind: "env-file", path: location.envFile } },- };+ return { kind: "ai-gateway-key" };}diff --git a/packages/eve/src/setup/provider-settings.integration.test.ts b/packages/eve/src/setup/provider-settings.integration.test.tsnew file mode 100644index 000000000..6bd676740--- /dev/null+++ b/packages/eve/src/setup/provider-settings.integration.test.ts@@ -0,0 +1,61 @@+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import {+ providerSettingsPath,+ readProviderSelection,+ readProviderSelectionSync,+ resolveAvailableProviders,+ writeProviderSelection,+} from "./provider-settings.js";++const roots: string[] = [];++afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));+});++describe("provider settings", () => {+ it("resolves available providers independently from the stored selection", async () => {+ const root = await mkdtemp(join(tmpdir(), "eve-provider-settings-"));+ roots.push(root);+ await writeFile(join(root, ".env.local"), "AI_GATEWAY_API_KEY=key\nVERCEL_OIDC_TOKEN=token\n");++ await expect(resolveAvailableProviders(root, { env: {} })).resolves.toEqual([+ "chatgpt",+ "ai-gateway-key",+ "ai-gateway-project",+ ]);+ await expect(readProviderSelection(root)).resolves.toBeUndefined();++ await writeProviderSelection(root, "chatgpt");++ await expect(resolveAvailableProviders(root, { env: {} })).resolves.toEqual([+ "chatgpt",+ "ai-gateway-key",+ "ai-gateway-project",+ ]);+ await expect(readProviderSelection(root)).resolves.toBe("chatgpt");+ });++ it("stores one normalized provider selection under .eve", async () => {+ const root = await mkdtemp(join(tmpdir(), "eve-provider-settings-"));+ roots.push(root);++ await writeProviderSelection(root, "ai-gateway-project");++ await expect(readProviderSelection(root)).resolves.toBe("ai-gateway-project");+ expect(readProviderSelectionSync(root)).toBe("ai-gateway-project");+ expect(providerSettingsPath(root)).toBe(join(root, ".eve", "provider.json"));+ });++ it("treats missing settings as no explicit selection", async () => {+ const root = await mkdtemp(join(tmpdir(), "eve-provider-settings-"));+ roots.push(root);++ await expect(readProviderSelection(root)).resolves.toBeUndefined();+ expect(readProviderSelectionSync(root)).toBeUndefined();+ });+});diff --git a/packages/eve/src/setup/provider-settings.ts b/packages/eve/src/setup/provider-settings.tsnew file mode 100644index 000000000..60f162669--- /dev/null+++ b/packages/eve/src/setup/provider-settings.ts@@ -0,0 +1,86 @@+import { readFileSync } from "node:fs";+import { mkdir, readFile, writeFile } from "node:fs/promises";+import { join } from "node:path";++import { hasEnvValue } from "#internal/resolve-model-endpoint-status.js";+import { isObject } from "#shared/guards.js";+import { AI_GATEWAY_API_KEY_ENV_VAR } from "#setup/ai-gateway-api-key.js";+import { findEnvFileWithKey } from "#setup/boxes/detect-ai-gateway.js";+import { readProjectLink } from "#setup/project-resolution.js";++const PROVIDER_SELECTIONS = ["chatgpt", "ai-gateway-key", "ai-gateway-project"] as const;++export type ProviderSelection = (typeof PROVIDER_SELECTIONS)[number];++export function providerSettingsPath(appRoot: string): string {+ return join(appRoot, ".eve", "provider.json");+}++export async function resolveAvailableProviders(+ appRoot: string,+ options: {+ signal?: AbortSignal;+ env?: Record<string, string | undefined>;+ } = {},+): Promise<readonly ProviderSelection[]> {+ const { signal, env = process.env } = options;+ signal?.throwIfAborted();+ const [projectLink, gatewayKeyFile, oidcFile] = await Promise.all([+ readProjectLink(appRoot),+ findEnvFileWithKey(appRoot, AI_GATEWAY_API_KEY_ENV_VAR),+ findEnvFileWithKey(appRoot, "VERCEL_OIDC_TOKEN"),+ ]);+ signal?.throwIfAborted();+ const available: ProviderSelection[] = ["chatgpt"];++ if (gatewayKeyFile !== undefined || hasEnvValue(env[AI_GATEWAY_API_KEY_ENV_VAR])) {+ available.push("ai-gateway-key");+ }++ if (projectLink !== undefined || oidcFile !== undefined) {+ available.push("ai-gateway-project");+ }++ return available;+}++export async function readProviderSelection(+ appRoot: string,+): Promise<ProviderSelection | undefined> {+ try {+ return parseProviderSelection(+ JSON.parse(await readFile(providerSettingsPath(appRoot), "utf8")),+ );+ } catch {+ return undefined;+ }+}++/** Synchronous counterpart for the synchronous dev-environment loader. */+export function readProviderSelectionSync(appRoot: string): ProviderSelection | undefined {+ try {+ return parseProviderSelection(JSON.parse(readFileSync(providerSettingsPath(appRoot), "utf8")));+ } catch {+ return undefined;+ }+}++export async function writeProviderSelection(+ appRoot: string,+ selected: ProviderSelection,+): Promise<void> {+ await mkdir(join(appRoot, ".eve"), { recursive: true });+ await writeFile(+ providerSettingsPath(appRoot),+ `${JSON.stringify({ selected }, null, 2)}\n`,+ "utf8",+ );+}++function parseProviderSelection(value: unknown): ProviderSelection | undefined {+ return isObject(value) && isProviderSelection(value.selected) ? value.selected : undefined;+}++function isProviderSelection(value: unknown): value is ProviderSelection {+ return PROVIDER_SELECTIONS.some((selection) => selection === value);+}diff --git a/packages/eve/src/setup/scaffold/create/project.test.ts b/packages/eve/src/setup/scaffold/create/project.test.tsindex 2ebbaf87c..8e41cb78b 100644--- a/packages/eve/src/setup/scaffold/create/project.test.ts+++ b/packages/eve/src/setup/scaffold/create/project.test.ts@@ -1,6 +1,17 @@import { describe, expect, it } from "vitest";-import { byokProviderEnvVar, modelProviderSlug } from "./project.js";+import { agentTemplateFiles, byokProviderEnvVar, modelProviderSlug } from "./project.js";++describe("agent templates", () => {+ it("authors a ChatGPT subscription model with the stable API", () => {+ expect(agentTemplateFiles("chatgpt/gpt-5.6-sol")["agent/agent.ts"]).toContain(+ 'model: chatgpt("gpt-5.6-sol")',+ );+ expect(agentTemplateFiles("chatgpt/gpt-5.6-sol")["agent/agent.ts"]).toContain(+ 'import { chatgpt } from "eve/models/openai"',+ );+ });+});describe("byok provider derivation", () => {it("derives the provider slug from the model id prefix", () => {diff --git a/packages/eve/src/setup/scaffold/create/project.ts b/packages/eve/src/setup/scaffold/create/project.tsindex cff5967e8..42e07660c 100644--- a/packages/eve/src/setup/scaffold/create/project.ts+++ b/packages/eve/src/setup/scaffold/create/project.ts@@ -4,6 +4,7 @@ import { basename, join, resolve } from "node:path";import type { PackageManagerKind } from "../../package-manager.js";import { pinnedNodeEngineMajor } from "../../node-engine.js";import type { AgentReasoningDefinition } from "../../../shared/agent-definition.js";+import { parseChatGptModelSelection } from "../../../shared/chatgpt-model.js";import { SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS } from "../update/module-files.js";import { pathExists, writeTextFile } from "../files.js";import { blockingCreateInPlaceEntries } from "../create-in-place.js";@@ -100,15 +101,26 @@ export function agentTemplateFiles(reasoning?: AgentReasoningDefinition,): Record<string, string> {return {- "agent/agent.ts": BASE_AGENT_TEMPLATE.replaceAll("__EVE_INIT_MODEL__", model).replaceAll(- "__EVE_INIT_REASONING__",- reasoningTemplateLine(reasoning),- ),+ "agent/agent.ts": renderAgentTemplate(model, reasoning),"agent/channels/eve.ts": WEB_APP_TEMPLATE_FILES["agent/channels/eve.ts"],"agent/instructions.md": AGENT_INSTRUCTIONS_TEMPLATE,};}+function renderAgentTemplate(+ model: string,+ reasoning: AgentReasoningDefinition | undefined,+): string {+ const chatGptModelId = parseChatGptModelSelection(model);+ if (chatGptModelId !== undefined) {+ return `import { defineAgent } from "eve";\nimport { chatgpt } from "eve/models/openai";\n\nexport default defineAgent({\n model: chatgpt(${JSON.stringify(chatGptModelId)}),\n${reasoningTemplateLine(reasoning)}});\n`;+ }+ return BASE_AGENT_TEMPLATE.replaceAll("__EVE_INIT_MODEL__", model).replaceAll(+ "__EVE_INIT_REASONING__",+ reasoningTemplateLine(reasoning),+ );+}+function reasoningTemplateLine(reasoning: AgentReasoningDefinition | undefined): string {return reasoning === undefined || reasoning === "provider-default"? ""@@ -116,6 +128,9 @@ function reasoningTemplateLine(reasoning: AgentReasoningDefinition | undefined):}function renderTemplate(content: string, ctx: TemplateContext): string {+ if (content === BASE_AGENT_TEMPLATE && parseChatGptModelSelection(ctx.model) !== undefined) {+ return renderAgentTemplate(ctx.model, ctx.reasoning);+ }return content.replaceAll("__EVE_INIT_APP_NAME__", ctx.appName).replaceAll("__EVE_INIT_MODEL__", ctx.model)diff --git a/packages/eve/src/shared/chatgpt-model.test.ts b/packages/eve/src/shared/chatgpt-model.test.tsnew file mode 100644index 000000000..6a0bbd86b--- /dev/null+++ b/packages/eve/src/shared/chatgpt-model.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from "vitest";++import {+ isChatGptModelRouting,+ normalizeChatGptModelId,+ parseChatGptModelSelection,+} from "./chatgpt-model.js";++describe("ChatGPT model ids", () => {+ it("parses only a bare OpenAI id after the setup prefix", () => {+ expect(parseChatGptModelSelection("chatgpt/gpt-5.6-sol")).toBe("gpt-5.6-sol");+ expect(parseChatGptModelSelection("chatgpt/not/a-bare-slug")).toBeUndefined();+ expect(parseChatGptModelSelection("chatgpt/")).toBeUndefined();+ });++ it("normalizes the public helper's optional openai prefix", () => {+ expect(normalizeChatGptModelId(" openai/gpt-5.5 ")).toBe("gpt-5.5");+ expect(normalizeChatGptModelId("anthropic/claude-sonnet-5")).toBeUndefined();+ });++ it("identifies the Codex external route used by ChatGPT models", () => {+ expect(isChatGptModelRouting({ kind: "external", provider: "codex" })).toBe(true);+ expect(isChatGptModelRouting({ kind: "external", provider: "openai" })).toBe(false);+ expect(isChatGptModelRouting({ kind: "gateway", target: "openai" })).toBe(false);+ });+});diff --git a/packages/eve/src/shared/chatgpt-model.ts b/packages/eve/src/shared/chatgpt-model.tsnew file mode 100644index 000000000..46f1c7cc3--- /dev/null+++ b/packages/eve/src/shared/chatgpt-model.ts@@ -0,0 +1,27 @@+import type { ModelRouting } from "./agent-definition.js";++export const DEFAULT_CHATGPT_MODEL_ID = "gpt-5.6-sol";+export const CHATGPT_MODEL_SELECTION_PREFIX = "chatgpt/";+export const DEFAULT_CHATGPT_MODEL_SELECTION = `${CHATGPT_MODEL_SELECTION_PREFIX}${DEFAULT_CHATGPT_MODEL_ID}`;++/** Returns the bare OpenAI model id encoded by a setup-facing ChatGPT selection. */+export function parseChatGptModelSelection(selection: string): string | undefined {+ if (!selection.startsWith(CHATGPT_MODEL_SELECTION_PREFIX)) return undefined;+ const modelId = selection.slice(CHATGPT_MODEL_SELECTION_PREFIX.length);+ return isBareChatGptModelId(modelId) ? modelId : undefined;+}++export function isChatGptModelRouting(routing: ModelRouting | null | undefined): boolean {+ return routing?.kind === "external" && routing.provider === "codex";+}++/** Normalizes the model argument accepted by the public `chatgpt()` helper. */+export function normalizeChatGptModelId(model: string): string | undefined {+ const trimmed = model.trim();+ const modelId = trimmed.startsWith("openai/") ? trimmed.slice("openai/".length) : trimmed;+ return isBareChatGptModelId(modelId) ? modelId : undefined;+}++function isBareChatGptModelId(modelId: string): boolean {+ return modelId.length > 0 && modelId === modelId.trim() && !modelId.includes("/");+}diff --git a/packages/eve/src/shared/model-endpoint-status.ts b/packages/eve/src/shared/model-endpoint-status.tsindex 78275c5de..fe116784d 100644--- a/packages/eve/src/shared/model-endpoint-status.ts+++ b/packages/eve/src/shared/model-endpoint-status.ts@@ -14,7 +14,19 @@* gateway API key nor an OIDC token. This is the "no provider connected" state* that gates the "provider required" setup prompt.*/+export type ChatGptEndpointState =+ | "checking"+ | "ready"+ | "signed-out"+ | "reauth-required"+ | "unavailable";+export type ModelEndpointStatus =| { kind: "external"; provider: string }+ | {+ kind: "chatgpt";+ state: ChatGptEndpointState;+ accountLabel?: string;+ }| { kind: "gateway"; connected: true; credential: "api-key" | "oidc" }| { kind: "gateway"; connected: false };diff --git a/packages/eve/src/source-change/apply-agent-model-settings.ts b/packages/eve/src/source-change/apply-agent-model-settings.tsindex 82d61acf1..7fff070dc 100644--- a/packages/eve/src/source-change/apply-agent-model-settings.ts+++ b/packages/eve/src/source-change/apply-agent-model-settings.ts@@ -1,7 +1,7 @@import type { AgentReasoningDefinition } from "#shared/agent-definition.js";import { applyAgentConfigStringPath } from "./agent-config-string-path.js";-import { applyModelNameToSource } from "./apply-model-name.js";+import { applyModelSelectionToSource } from "./apply-model-selection.js";export type FieldPatch<T> =| { readonly kind: "keep" }@@ -36,7 +36,7 @@ export async function applyAgentModelSettingsToSource(return { kind: "bail", reason: "the required `model` property cannot be removed", line: 1 };}if (patch.model.kind === "set") {- const edit = await applyModelNameToSource(nextSource, patch.model.value);+ const edit = await applyModelSelectionToSource(nextSource, patch.model.value);if (edit.kind === "bail") return edit;if (edit.nextSource !== nextSource) changed.push("model");nextSource = edit.nextSource;diff --git a/packages/eve/src/source-change/apply-model-name.test.ts b/packages/eve/src/source-change/apply-model-name.test.tsdeleted file mode 100644index 26b2858f1..000000000--- a/packages/eve/src/source-change/apply-model-name.test.ts+++ /dev/null@@ -1,133 +0,0 @@-import { describe, expect, it } from "vitest";--import { applyModelNameToSource } from "#source-change/apply-model-name.js";--const SCAFFOLD = `import { defineAgent } from "eve";--export default defineAgent({- model: "anthropic/claude-sonnet-5",-});-`;--describe("applyModelNameToSource", () => {- it("rewrites the model literal in the canonical scaffold", async () => {- const result = await applyModelNameToSource(SCAFFOLD, "anthropic/claude-opus-4.6");-- expect(result.kind).toBe("applied");- if (result.kind !== "applied") return;- expect(result.from).toBe("anthropic/claude-sonnet-5");- expect(result.to).toBe("anthropic/claude-opus-4.6");- // Only the literal changed; the rest of the file is byte-identical.- expect(result.nextSource).toBe(- SCAFFOLD.replace("anthropic/claude-sonnet-5", "anthropic/claude-opus-4.6"),- );- });-- it("preserves single-quote style", async () => {- const result = await applyModelNameToSource(- `export default defineAgent({ model: 'a/b' });\n`,- "c/d",- );-- expect(result.kind).toBe("applied");- if (result.kind !== "applied") return;- expect(result.nextSource).toContain(`model: 'c/d'`);- });-- it("preserves comments and sibling properties", async () => {- const source = `export default defineAgent({- // primary model- model: "a/b",- experimental: { workflow: { world: "@acme/workflow-world" } },-});-`;- const result = await applyModelNameToSource(source, "c/d");-- expect(result.kind).toBe("applied");- if (result.kind !== "applied") return;- expect(result.nextSource).toContain("// primary model");- expect(result.nextSource).toContain(- 'experimental: { workflow: { world: "@acme/workflow-world" } }',- );- expect(result.nextSource).toContain(`model: "c/d"`);- });-- it("unwraps `satisfies` to the inner literal and leaves the annotation", async () => {- const result = await applyModelNameToSource(- `export default defineAgent({ model: "a/b" satisfies string });\n`,- "c/d",- );-- expect(result.kind).toBe("applied");- if (result.kind !== "applied") return;- expect(result.nextSource).toContain(`model: "c/d" satisfies string`);- });-- it("is a no-op when the value is unchanged", async () => {- const result = await applyModelNameToSource(SCAFFOLD, "anthropic/claude-sonnet-5");-- expect(result.kind).toBe("applied");- if (result.kind !== "applied") return;- expect(result.nextSource).toBe(SCAFFOLD);- });-- it("bails when model is an env reference, not a literal", async () => {- const result = await applyModelNameToSource(- `export default defineAgent({ model: process.env.MODEL ?? "a/b" });\n`,- "c/d",- );-- expect(result.kind).toBe("bail");- });-- it("bails on a template literal", async () => {- const result = await applyModelNameToSource(- "export default defineAgent({ model: `a/${x}` });\n",- "c/d",- );-- expect(result.kind).toBe("bail");- });-- it("bails on a defineDynamic model without touching resolver selections", async () => {- const source = `import { defineAgent, defineDynamic } from "eve";--export default defineAgent({- model: defineDynamic({- events: {- "session.started": () => "anthropic/claude-sonnet-5",- },- }),-});-`;- const result = await applyModelNameToSource(source, "c/d");-- expect(result.kind).toBe("bail");- if (result.kind !== "bail") return;- expect(result.reason).toContain("defineDynamic");- });-- it("bails when there is no defineAgent call", async () => {- const result = await applyModelNameToSource(`export const x = 1;\n`, "c/d");-- expect(result.kind).toBe("bail");- });-- it("bails when model is absent", async () => {- const result = await applyModelNameToSource(- `export default defineAgent({ experimental: { workflow: {} } });\n`,- "c/d",- );-- expect(result.kind).toBe("bail");- });-- it("reports the source line on a bail", async () => {- const source = `export default defineAgent({\n model: someConst,\n});\n`;- const result = await applyModelNameToSource(source, "c/d");-- expect(result.kind).toBe("bail");- if (result.kind !== "bail") return;- expect(result.line).toBeGreaterThanOrEqual(1);- });-});diff --git a/packages/eve/src/source-change/apply-model-name.ts b/packages/eve/src/source-change/apply-model-name.tsdeleted file mode 100644index 86473f85a..000000000--- a/packages/eve/src/source-change/apply-model-name.ts+++ /dev/null@@ -1,108 +0,0 @@-import {- escapeForQuote,- isAstNode,- keyMatches,- lineAt,- parseAgentObject,- unwrapExpression,- type AstNode,- type ObjectExpression,-} from "./agent-config-ast.js";--/**- * Outcome of a source-to-source edit attempt. Pure data. On success it carries- * the rewritten source, so the caller owns the filesystem write.- */-export type SourceEdit =- | {- readonly kind: "applied";- readonly from: string;- readonly to: string;- readonly nextSource: string;- }- | {- readonly kind: "bail";- readonly reason: string;- readonly line: number;- };--type StringLiteral = AstNode & {- readonly end: number;- readonly start: number;- readonly value: string;-};--/**- * Rewrites the `model` string literal passed to `defineAgent({ ... })` in- * `sourceText`, returning the edited source.- *- * Pure transform: parses with Rolldown, finds the literal's byte span, and splices- * only those bytes, so comments, formatting, and quote style everywhere else- * are preserved by construction. Bails (no edit) when `model` is absent or- * isn't a plain string literal. An env reference, a template, an inlined SDK- * model object, or a spread all opt out into the manual path instead.- */-export async function applyModelNameToSource(- sourceText: string,- modelName: string,-): Promise<SourceEdit> {- const parsed = await parseAgentObject(sourceText);- if (parsed.kind === "bail") return parsed;- const object = parsed.object;-- const literal = findStringLiteralProperty(object, "model");- if (literal === undefined) {- return {- kind: "bail",- reason:- "`model` is absent or is not a string literal (e.g. an env reference, a template, an inlined SDK model, or a defineDynamic() dynamic model)",- line: lineAt(sourceText, object.start),- };- }-- const from = literal.value;- if (from === modelName) {- return { kind: "applied", from, to: modelName, nextSource: sourceText };- }-- const quote = literal.raw?.[0] === "'" ? "'" : '"';- const replacement = `${quote}${escapeForQuote(modelName, quote)}${quote}`;- const nextSource =- sourceText.slice(0, literal.start) + replacement + sourceText.slice(literal.end);-- return { kind: "applied", from, to: modelName, nextSource };-}--/**- * Returns the string-literal value node for `key`, or undefined when the- * property is missing, spread, computed, or resolves to a non-string value.- * Deliberately more permissive than the path editor's lookup: a spread- * elsewhere in the object does not block rewriting an explicit `model`- * literal, matching the original `/model <slug>` contract.- */-function findStringLiteralProperty(- object: ObjectExpression,- key: string,-): StringLiteral | undefined {- for (const property of object.properties) {- if (property.type !== "Property" || property.computed || !keyMatches(property.key, key)) {- continue;- }- const rawValue = property.value;- if (!isAstNode(rawValue)) {- continue;- }- const value = unwrapExpression(rawValue);- // All literal kinds share `type: "Literal"`; the typeof guard selects strings.- if (- value.type === "Literal" &&- typeof value.value === "string" &&- value.start !== undefined &&- value.end !== undefined- ) {- return value as StringLiteral;- }- return undefined;- }- return undefined;-}diff --git a/packages/eve/src/source-change/apply-model-selection.test.ts b/packages/eve/src/source-change/apply-model-selection.test.tsnew file mode 100644index 000000000..22d58b53d--- /dev/null+++ b/packages/eve/src/source-change/apply-model-selection.test.ts@@ -0,0 +1,129 @@+import { describe, expect, it } from "vitest";++import { applyModelSelectionToSource } from "./apply-model-selection.js";++const SCAFFOLD = `import { defineAgent } from "eve";++export default defineAgent({+ model: "anthropic/claude-sonnet-5",+});+`;++describe("applyModelSelectionToSource", () => {+ it("switches a Gateway string to chatgpt() and adds its import", async () => {+ const source = `import { defineAgent } from "eve";\n\nexport default defineAgent({\n model: "openai/gpt-5.5",\n});\n`;++ const result = await applyModelSelectionToSource(source, "chatgpt/gpt-5.6-sol");++ expect(result.kind).toBe("applied");+ if (result.kind !== "applied") return;+ expect(result.nextSource).toContain('import { chatgpt } from "eve/models/openai";');+ expect(result.nextSource).toContain('model: chatgpt("gpt-5.6-sol")');+ });++ it("switches chatgpt() back to a Gateway string and removes its sole import", async () => {+ const source = `import { defineAgent } from "eve";\nimport { chatgpt } from "eve/models/openai";\n\nexport default defineAgent({\n model: chatgpt("gpt-5.6-sol"),\n});\n`;++ const result = await applyModelSelectionToSource(source, "anthropic/claude-sonnet-5");++ expect(result.kind).toBe("applied");+ if (result.kind !== "applied") return;+ expect(result.nextSource).not.toContain("eve/models/openai");+ expect(result.nextSource).toContain('model: "anthropic/claude-sonnet-5"');+ });++ it("switches the documented no-argument chatgpt() call back to Gateway", async () => {+ const source = `import { defineAgent } from "eve";\nimport { chatgpt } from "eve/models/openai";\n\nexport default defineAgent({ model: chatgpt() });\n`;++ const result = await applyModelSelectionToSource(source, "openai/gpt-5.5");++ expect(result.kind).toBe("applied");+ if (result.kind !== "applied") return;+ expect(result.from).toBe("chatgpt/gpt-5.6-sol");+ expect(result.nextSource).not.toContain("eve/models/openai");+ expect(result.nextSource).toContain('model: "openai/gpt-5.5"');+ });++ it("normalizes an openai-prefixed chatgpt() argument when changing models", async () => {+ const source = `import { chatgpt } from "eve/models/openai";\nexport default defineAgent({ model: chatgpt("openai/gpt-5.5") });\n`;++ const result = await applyModelSelectionToSource(source, "chatgpt/gpt-5.6-sol");++ expect(result.kind).toBe("applied");+ if (result.kind !== "applied") return;+ expect(result.from).toBe("chatgpt/gpt-5.5");+ expect(result.nextSource).toContain('model: chatgpt("gpt-5.6-sol")');+ });++ it("preserves other imports from eve/models/openai", async () => {+ const source = `import { defineAgent } from "eve";\nimport { chatgpt, other } from "eve/models/openai";\nexport default defineAgent({ model: chatgpt("gpt-5.6-sol") });\n`;++ const result = await applyModelSelectionToSource(source, "openai/gpt-5.5");++ expect(result.kind).toBe("applied");+ if (result.kind !== "applied") return;+ expect(result.nextSource).toContain('import { other } from "eve/models/openai";');+ });++ it("keeps the chatgpt import when another call still uses it", async () => {+ const source = `import { chatgpt } from "eve/models/openai";\nconst fallback = chatgpt("gpt-5.5");\nexport default defineAgent({ model: chatgpt() });\n`;++ const result = await applyModelSelectionToSource(source, "openai/gpt-5.5");++ expect(result.kind).toBe("applied");+ if (result.kind !== "applied") return;+ expect(result.nextSource).toContain('import { chatgpt } from "eve/models/openai";');+ });++ it("rewrites Gateway strings without changing surrounding source", async () => {+ const result = await applyModelSelectionToSource(SCAFFOLD, "anthropic/claude-opus-4.6");++ expect(result.kind).toBe("applied");+ if (result.kind !== "applied") return;+ expect(result.nextSource).toBe(+ SCAFFOLD.replace("anthropic/claude-sonnet-5", "anthropic/claude-opus-4.6"),+ );+ });++ it("preserves single-quote style", async () => {+ const result = await applyModelSelectionToSource(+ `export default defineAgent({ model: 'a/b' });\n`,+ "c/d",+ );++ expect(result.kind).toBe("applied");+ if (result.kind !== "applied") return;+ expect(result.nextSource).toContain(`model: 'c/d'`);+ });++ it("unwraps satisfies while leaving the annotation", async () => {+ const result = await applyModelSelectionToSource(+ `export default defineAgent({ model: "a/b" satisfies string });\n`,+ "c/d",+ );++ expect(result.kind).toBe("applied");+ if (result.kind !== "applied") return;+ expect(result.nextSource).toContain(`model: "c/d" satisfies string`);+ });++ it("is a no-op when the Gateway value is unchanged", async () => {+ const result = await applyModelSelectionToSource(SCAFFOLD, "anthropic/claude-sonnet-5");++ expect(result.kind).toBe("applied");+ if (result.kind !== "applied") return;+ expect(result.nextSource).toBe(SCAFFOLD);+ });++ it.each([+ `export default defineAgent({ model: process.env.MODEL ?? "a/b" });\n`,+ "export default defineAgent({ model: `a/${x}` });\n",+ `export default defineAgent({ model: defineDynamic({ events: {} }) });\n`,+ `export default defineAgent({ instructions: "hello" });\n`,+ `export const x = 1;\n`,+ ])("bails rather than rewriting a non-static model", async (source) => {+ await expect(applyModelSelectionToSource(source, "c/d")).resolves.toMatchObject({+ kind: "bail",+ });+ });+});diff --git a/packages/eve/src/source-change/apply-model-selection.ts b/packages/eve/src/source-change/apply-model-selection.tsnew file mode 100644index 000000000..77c2e9eec--- /dev/null+++ b/packages/eve/src/source-change/apply-model-selection.ts@@ -0,0 +1,137 @@+import {+ escapeForQuote,+ isAstNode,+ keyMatches,+ lineAt,+ parseAgentObject,+ unwrapExpression,+ type AstNode,+ type ObjectExpression,+} from "./agent-config-ast.js";+import {+ CHATGPT_MODEL_SELECTION_PREFIX,+ DEFAULT_CHATGPT_MODEL_SELECTION,+ normalizeChatGptModelId,+ parseChatGptModelSelection,+} from "#shared/chatgpt-model.js";++export type SourceEdit =+ | {+ readonly kind: "applied";+ readonly from: string;+ readonly to: string;+ readonly nextSource: string;+ }+ | {+ readonly kind: "bail";+ readonly reason: string;+ readonly line: number;+ };++/** Rewrites between a Gateway string model and an eve-owned `chatgpt()` call. */+export async function applyModelSelectionToSource(+ sourceText: string,+ selection: string,+): Promise<SourceEdit> {+ const parsed = await parseAgentObject(sourceText);+ if (parsed.kind === "bail") return parsed;+ const value = findModelValue(parsed.object);+ if (value === undefined || value.start === undefined || value.end === undefined) {+ return {+ kind: "bail",+ reason: "`model` is absent or cannot be edited safely",+ line: lineAt(sourceText, parsed.object.start),+ };+ }++ const current = currentSelection(value);+ if (current === undefined) {+ return {+ kind: "bail",+ reason: "`model` is neither a string literal nor an eve `chatgpt()` call",+ line: lineAt(sourceText, value.start),+ };+ }++ const chatGptModelId = parseChatGptModelSelection(selection);+ const replacement =+ chatGptModelId !== undefined+ ? `chatgpt(${JSON.stringify(chatGptModelId)})`+ : `${sourceText[value.start] === "'" ? "'" : '"'}${escapeForQuote(+ selection,+ sourceText[value.start] === "'" ? "'" : '"',+ )}${sourceText[value.start] === "'" ? "'" : '"'}`;+ let nextSource = sourceText.slice(0, value.start) + replacement + sourceText.slice(value.end);+ if (chatGptModelId !== undefined) {+ nextSource = ensureChatGptImport(nextSource);+ } else if (+ parseChatGptModelSelection(current) !== undefined &&+ !/\bchatgpt\s*\(/u.test(nextSource)+ ) {+ nextSource = removeChatGptImport(nextSource);+ }+ return { kind: "applied", from: current, to: selection, nextSource };+}++function findModelValue(object: ObjectExpression): AstNode | undefined {+ for (const property of object.properties) {+ if (property.type !== "Property" || property.computed || !keyMatches(property.key, "model")) {+ continue;+ }+ return isAstNode(property.value) ? unwrapExpression(property.value) : undefined;+ }+ return undefined;+}++function currentSelection(value: AstNode): string | undefined {+ if (value.type === "Literal" && typeof value.value === "string") return value.value;+ if (value.type !== "CallExpression" || !isAstNode(value.callee)) return undefined;+ const callee = unwrapExpression(value.callee);+ if (callee.type !== "Identifier" || callee.name !== "chatgpt") return undefined;+ const argument = value.arguments?.[0];+ if (argument === undefined) return DEFAULT_CHATGPT_MODEL_SELECTION;+ if (!isAstNode(argument)) return undefined;+ const unwrapped = unwrapExpression(argument);+ if (unwrapped.type !== "Literal" || typeof unwrapped.value !== "string") return undefined;+ const modelId = normalizeChatGptModelId(unwrapped.value);+ return modelId === undefined ? undefined : `${CHATGPT_MODEL_SELECTION_PREFIX}${modelId}`;+}++function ensureChatGptImport(source: string): string {+ const existing = source.match(/import\s*\{([^}]*)\}\s*from\s*["']eve\/models\/openai["'];?/u);+ if (existing !== null) {+ const names = existing[1]!+ .split(",")+ .map((name) => name.trim())+ .filter(Boolean);+ if (names.includes("chatgpt")) return source;+ const replacement = `import { ${[...names, "chatgpt"].join(", ")} } from "eve/models/openai";`;+ return (+ source.slice(0, existing.index) ++ replacement ++ source.slice(existing.index! + existing[0].length)+ );+ }+ const imports = [...source.matchAll(/^import .*;\s*$/gmu)];+ const insertion = imports.at(-1);+ const offset = insertion === undefined ? 0 : insertion.index! + insertion[0].length;+ const prefix = offset === 0 ? "" : "\n";+ return `${source.slice(0, offset)}${prefix}import { chatgpt } from "eve/models/openai";${source.slice(offset)}`;+}++function removeChatGptImport(source: string): string {+ return source.replace(+ /import\s*\{([^}]*)\}\s*from\s*["']eve\/models\/openai["'];?\n?/u,+ (full, contents: string) => {+ const names = contents+ .split(",")+ .map((name) => name.trim())+ .filter(Boolean);+ const remaining = names.filter((name) => name !== "chatgpt");+ if (remaining.length === names.length) return full;+ return remaining.length === 0+ ? ""+ : `import { ${remaining.join(", ")} } from "eve/models/openai";\n`;+ },+ );+}diff --git a/packages/eve/src/source-change/static-source-change.ts b/packages/eve/src/source-change/static-source-change.tsindex 2d4ff33b2..7151eee3e 100644--- a/packages/eve/src/source-change/static-source-change.ts+++ b/packages/eve/src/source-change/static-source-change.ts@@ -8,7 +8,7 @@ import {type AgentModelSetting,type AgentModelSettingsPatch,} from "#source-change/apply-agent-model-settings.js";-import { applyModelNameToSource } from "#source-change/apply-model-name.js";+import { applyModelSelectionToSource } from "#source-change/apply-model-selection.js";/*** Outcome of a static source change, returned to upstream callers (CLI, web@@ -104,7 +104,7 @@ async function updateAgentModelName(const absolutePath = join(manifest.agentRoot, source.logicalPath);const sourceText = await readFile(absolutePath, "utf8");- const edit = await applyModelNameToSource(sourceText, modelName);+ const edit = await applyModelSelectionToSource(sourceText, modelName);if (edit.kind === "bail") {return {