The Open Framework for Building Agents
feat(eve): consolidate model provider onboarding (#166)
Ruid82e8d1d12f5
diff --git a/.changeset/model-provider-onboarding.md b/.changeset/model-provider-onboarding.mdnew file mode 100644index 000000000..848b0bd5d--- /dev/null+++ b/.changeset/model-provider-onboarding.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Consolidate model provider setup into one choice between project-backed AI Gateway, an inline `AI_GATEWAY_API_KEY`, and direct provider credentials. Gateway key validation now reports its latest result inline without leaving stale errors in the setup panel.diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.mdindex a3137cf28..d62b73e9b 100644--- a/docs/guides/dev-tui.md+++ b/docs/guides/dev-tui.md@@ -16,7 +16,7 @@ On startup the TUI prints a brand line with your agent's name, plus a rotating tUse /channels to add more ways to reach your agent.```-If agent discovery reported problems, an error and warning count renders between the two lines. Instructions, tools, skills, and subagents are one `eve info` away, and `/help` lists every command. The TUI also runs a startup check. When the runtime confirms that no model provider is configured, it opens the `/model` provider questions before the first prompt. When the available evidence cannot confirm that state, missing setup remains visible as an attention line, with each command's outcome hanging under it on a `⎿` connector.+If agent discovery reported problems, an error and warning count renders between the two lines. Instructions, tools, skills, and subagents are one `eve info` away, and `/help` lists every command. The TUI also runs a startup check. When the runtime confirms that no model provider is configured, it opens the `/model` provider picker before the first prompt. Unknown or linked-but-incomplete credential states remain visible as an attention line, with each command's outcome hanging under it on a `⎿` connector.## Reading the transcript@@ -46,11 +46,11 @@ Each command echoes as an invocation line, asks through a bordered panel that ta### Configure the model and provider-Bare `/model` opens the configure menu. When no provider is configured, it opens the provider questions directly; Esc returns to the configure menu. "Change model" runs the same searchable model picker setup uses (the Vercel AI Gateway catalog, pre-selected on the model the runtime is serving). A model change is written into your agent's authored source, and the command reports success only after eve confirms the new id. `/model <provider/model-id>` applies one directly, skipping the menu.+Bare `/model` opens the configure menu. When no provider is configured, it opens the provider picker directly and Esc returns to the configure menu. "Change model" runs the same searchable model picker setup uses (the Vercel AI Gateway catalog, pre-selected on the model the runtime is serving). A model change is written into your agent's authored source, and the command reports success only after eve confirms the new id. A completed model or provider change closes the menu and returns its result to the transcript; Done or Esc closes it without a change. `/model <provider/model-id>` applies one directly, skipping the menu.-The provider row opens the provider questions: which model provider to use, and how to connect. Picking something other than Vercel AI Gateway shows wiring instructions for your own provider and stops there, leaving any existing setup untouched. For Vercel AI Gateway, you either paste your own `AI_GATEWAY_API_KEY` (saved straight to `.env.local`) or connect via a project. Connecting via a project asks for a Vercel team, opens that team's recent projects, and lets you search all projects for older matches. Vercel links the selected project, eve verifies its project ID, then pulls its environment into `.env.local`. The dev TUI reloads env files, re-reads the runtime's model endpoint, and clears the setup warning automatically; no restart is needed.+The provider row opens one menu: AI Gateway via a project, AI Gateway via `AI_GATEWAY_API_KEY`, or **Other providers**. The key option becomes a masked input when highlighted. Enter validates it without replacing the menu. A rejected key shows a red `⨯ Invalid key` beside the masked value; retrying or editing clears that result. With a non-empty key, the first Esc or Ctrl-C clears the input and the second cancels the menu. An accepted key is saved to `.env.local`. The project option asks for a Vercel team, opens that team's recent projects, and lets you search all projects for older matches. Vercel links the selected project, eve verifies its project ID, then pulls its environment into `.env.local`. The **Other providers** option shows direct-provider wiring instructions and leaves the existing setup untouched. The dev server reloads env files and refreshes the status bar automatically, with no restart needed.-The provider row demands attention (a bold yellow "Configure provider" with "Required to enable the agent") until a link or gateway credential is detected, then names the connection afterward (for example "AI Gateway (Linked to my-project in my-team)"). Each action's latest outcome stays visible beneath the menu (for example "✓ Model changed to openai/gpt-5.5"). When a turn fails because AI Gateway authentication is missing or stale, the error points you at `/model` directly.+The provider row demands attention (a bold yellow "Configure model access" with a yellow "Not configured" hint that dims when unselected and uses the terminal foreground when selected) until a link or gateway credential is detected, then names the connection afterward (for example "AI Gateway (Linked to my-project in my-team)"). Setup menus mark the cursor row with a padded, filled-arrow inverse label that inherits the row's accent: blue normally and yellow for warning rows. In stacked menus, the selected row's description appears directly beneath that option. The completed command's outcome stays in the transcript after the panel closes. When a turn fails because AI Gateway authentication is missing or stale, the error points you at `/model` directly.### Add a channeldiff --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 164dace0f..2b1163213 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@@ -23,6 +23,7 @@ function setupFlowRenderer() {end: vi.fn(),readSelect: vi.fn(async () => undefined),readEditableSelect: vi.fn(async () => undefined),+ readProviderPicker: vi.fn(async () => undefined),readText: vi.fn(async () => undefined),readAcknowledge: vi.fn(async () => {}),readChoice: vi.fn(() => ({ choice: Promise.resolve(undefined), close: vi.fn() })),diff --git a/packages/eve/src/cli/dev/tui/provider-picker.ts b/packages/eve/src/cli/dev/tui/provider-picker.tsnew file mode 100644index 000000000..1ff33618d--- /dev/null+++ b/packages/eve/src/cli/dev/tui/provider-picker.ts@@ -0,0 +1,146 @@+import type { PromptOption } from "#setup/cli/index.js";+import {+ initialSelectState,+ reduceSelect,+ selectValueAtCursor,+ type SelectState,+} from "#setup/cli/select-state.js";+import type { ProviderConnection, ProviderPickerChoice } from "#setup/flows/provider.js";+import type { GatewayKeyValidation } from "#setup/validate-gateway-key.js";++import { EMPTY_LINE, type LineState } from "./line-editor.js";++/** The provider key row is either inert, editable, checking, or rejected. */+export type ProviderPickerPhase =+ | { kind: "inactive" }+ | { kind: "editing"; editor: LineState }+ | { kind: "validating"; editor: LineState; key: string }+ | { kind: "invalid"; editor: LineState; message: string };++/** One provider picker interaction: ordinary select state plus its key field. */+export interface ProviderPickerState {+ select: SelectState;+ phase: ProviderPickerPhase;+}++/** Semantic input after terminal-key and line-editor decoding. */+export type ProviderPickerEvent =+ | { type: "move"; direction: "up" | "down" }+ | { type: "edit"; editor: LineState }+ | { type: "cancel" }+ | { type: "submit" }+ | { type: "validated"; validation: GatewayKeyValidation };++/** One state transition; abort controllers remain in the terminal renderer. */+export type ProviderPickerTransition =+ | { kind: "ignore"; state: ProviderPickerState }+ | { kind: "render"; state: ProviderPickerState }+ | { kind: "clear"; state: ProviderPickerState }+ | { kind: "cancel" }+ | { kind: "validate"; state: ProviderPickerState; key: string }+ | { kind: "settle"; result: ProviderPickerChoice };++function keyPhase(+ select: SelectState,+ options: readonly PromptOption<ProviderConnection>[],+): ProviderPickerPhase {+ return selectValueAtCursor(options, select.cursor) === "own-key"+ ? { kind: "editing", editor: EMPTY_LINE }+ : { kind: "inactive" };+}++/** Creates the select and blank inline key field for one provider menu. */+export function initialProviderPickerState(+ options: readonly PromptOption<ProviderConnection>[],+ initialValue: ProviderConnection,+): ProviderPickerState {+ const select = initialSelectState({ options, defaultValue: initialValue });+ return { select, phase: keyPhase(select, options) };+}++function ignore(state: ProviderPickerState): ProviderPickerTransition {+ return { kind: "ignore", state };+}++/** Applies one provider-menu event without creating terminal resources. */+export function transitionProviderPicker(+ state: ProviderPickerState,+ event: ProviderPickerEvent,+ options: readonly PromptOption<ProviderConnection>[],+): ProviderPickerTransition {+ if (event.type === "cancel") {+ if (state.phase.kind !== "inactive" && state.phase.editor.text.length > 0) {+ return {+ kind: "clear",+ state: { select: state.select, phase: { kind: "editing", editor: EMPTY_LINE } },+ };+ }+ return { kind: "cancel" };+ }++ if (state.phase.kind === "validating") {+ if (event.type !== "validated") return ignore(state);+ if (event.validation.kind === "invalid") {+ return {+ kind: "render",+ state: {+ select: state.select,+ phase: {+ kind: "invalid",+ editor: state.phase.editor,+ message: event.validation.message,+ },+ },+ };+ }+ return {+ kind: "settle",+ result: { kind: "inline-key", key: state.phase.key, validation: event.validation },+ };+ }++ switch (event.type) {+ case "move": {+ const select = reduceSelect(state.select, { type: event.direction }, { options });+ if (select === state.select) return ignore(state);+ return { kind: "render", state: { select, phase: keyPhase(select, options) } };+ }+ case "edit":+ if (state.phase.kind === "inactive") return ignore(state);+ return {+ kind: "render",+ state: { select: state.select, phase: { kind: "editing", editor: event.editor } },+ };+ case "submit": {+ const value = selectValueAtCursor(options, state.select.cursor);+ if (value === "project" || value === "external") {+ return { kind: "settle", result: { kind: value } };+ }+ if (value !== "own-key" || state.phase.kind === "inactive") return ignore(state);+ const key = state.phase.editor.text.trim();+ if (key.length === 0) {+ return {+ kind: "render",+ state: {+ select: state.select,+ phase: {+ kind: "invalid",+ editor: state.phase.editor,+ message: "API key cannot be empty.",+ },+ },+ };+ }+ return {+ kind: "validate",+ state: {+ select: state.select,+ phase: { kind: "validating", editor: state.phase.editor, key },+ },+ key,+ };+ }+ case "validated":+ return ignore(state);+ }+}diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex 3c63c621f..51e821e6a 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -129,6 +129,7 @@ const AGENT_INFO: AgentInfoResult = {afterEach(() => {vi.unstubAllGlobals();+ vi.unstubAllEnvs();vi.useRealTimers();});@@ -1380,6 +1381,7 @@ describe("EveTUIRunner boot setup detection", () => {...AGENT_INFO.agent,model: {...AGENT_INFO.agent.model,+ routing: { kind: "gateway", target: "openai" },endpoint: { kind: "gateway", connected: false },},},@@ -1503,17 +1505,7 @@ describe("EveTUIRunner boot setup detection", () => {);});- it("refreshes the gateway endpoint after automatic provider setup", async () => {- const connectedInfo: AgentInfoResult = {- ...AGENT_INFO,- agent: {- ...AGENT_INFO.agent,- model: {- ...AGENT_INFO.agent.model,- endpoint: { kind: "gateway", connected: true, credential: "api-key" },- },- },- };+ it("normalizes a committed local key after automatic provider setup", async () => {const clearSetupWarning = vi.fn();const headers: AgentTUIAgentHeader[] = [];const detect = vi.fn(({ info }: { info?: AgentInfoResult }) =>@@ -1528,7 +1520,10 @@ describe("EveTUIRunner boot setup detection", () => {: [],);const { client, runner } = providerSetupRefreshRunner({- refreshInfo: async () => connectedInfo,+ refreshInfo: async () => {+ vi.stubEnv("AI_GATEWAY_API_KEY", "test-key");+ return disconnectedGatewayInfo;+ },bootDetections: [{ id: "test", detect }],renderer: {clearSetupWarning,@@ -1540,7 +1535,11 @@ describe("EveTUIRunner boot setup detection", () => {await vi.waitFor(() => expect(clearSetupWarning).toHaveBeenCalled());expect(client.info).toHaveBeenCalledTimes(2);- expect(detect.mock.calls.at(-1)?.[0].info).toBe(connectedInfo);+ expect(detect.mock.calls.at(-1)?.[0].info?.agent.model.endpoint).toEqual({+ kind: "gateway",+ connected: true,+ credential: "api-key",+ });expect(headers.map((header) => header.info?.agent.model.endpoint)).toEqual([{ kind: "gateway", connected: false },{ kind: "gateway", connected: true, credential: "api-key" },diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex 9189209ae..0e371c254 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -55,6 +55,7 @@ import {formatSetupIssuesLine,LOGIN_SETUP_ISSUE,orderedSetupIssues,+ resolveModelProviderState,type BootDetection,type BootDetectionContext,type SetupIssue,@@ -508,22 +509,25 @@ export class EveTUIRunner {info = undefined;}this.#reportBeforeFirstPaint();- this.#replaceAgentInfo(info);- await this.#renderSetupIssues(info);+ const headerInfo = this.#replaceAgentInfo(info);+ await this.#renderSetupIssues(headerInfo);}- #replaceAgentInfo(info: AgentInfoResult | undefined): void {- this.#agentInfo = info;+ #replaceAgentInfo(info: AgentInfoResult | undefined): AgentInfoResult | undefined {+ const headerInfo =+ this.#appRoot === undefined ? info : resolveModelProviderState(info, process.env);+ this.#agentInfo = headerInfo;const serverUrl = this.#serverUrl;- if (serverUrl === undefined) return;+ if (serverUrl === undefined) return headerInfo;const header: AgentTUIAgentHeader = {name: this.#name,serverUrl,};- if (info !== undefined) header.info = info;+ if (headerInfo !== undefined) header.info = headerInfo;if (this.#appRoot !== undefined) header.tip = this.#headerTip;this.#renderer.renderAgentHeader?.(header);+ return headerInfo;}#reportBeforeFirstPaint(): void {@@ -1056,16 +1060,16 @@ export class EveTUIRunner {/*** Setup commands can write env files before the dev watcher reloads them.- * Reload first, then replace the cached `/info` response that owns the status- * bar's endpoint state. The slower Vercel auth probe stays off the prompt path.+ * 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.*/async #refreshModelAccess(): Promise<void> {const appRoot = this.#appRoot;if (appRoot === undefined) return;loadDevelopmentEnvironmentFiles(appRoot);- const refreshedInfo = await this.#readAgentInfo();- this.#replaceAgentInfo(refreshedInfo);+ 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 e10baedb1..0489bb91a 100644--- a/packages/eve/src/cli/dev/tui/setup-commands.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-commands.test.ts@@ -28,6 +28,7 @@ function fakePanelRenderer(): TuiSetupCommandRenderer & {return {readSelect: vi.fn(async () => []),readEditableSelect: vi.fn(async () => undefined),+ readProviderPicker: vi.fn(async () => undefined),readText: vi.fn(async () => ""),readAcknowledge: vi.fn(async () => {}),readChoice: vi.fn(() => ({ choice: Promise.resolve(undefined), close: vi.fn() })),@@ -110,7 +111,12 @@ describe("runTuiSetupCommand", () => {message: "Model changed to openai/gpt-5.5. Live on your next prompt.",preserveFlowDiagnostics: false,});- expect(flows.runModelFlow).toHaveBeenCalledWith(expect.objectContaining({ appRoot: APP_ROOT }));+ expect(flows.runModelFlow).toHaveBeenCalledWith(+ expect.objectContaining({+ appRoot: APP_ROOT,+ deps: expect.objectContaining({ runProviderFlow: expect.any(Function) }),+ }),+ );});it("forwards an automatic provider entry to the model flow", async () => {diff --git a/packages/eve/src/cli/dev/tui/setup-commands.ts b/packages/eve/src/cli/dev/tui/setup-commands.tsindex 01c422bd5..bd8d7c87f 100644--- a/packages/eve/src/cli/dev/tui/setup-commands.ts+++ b/packages/eve/src/cli/dev/tui/setup-commands.ts@@ -7,6 +7,7 @@ import {} 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 { runProviderFlow, type ProviderPicker } from "#setup/flows/provider.js";import { openUrl } from "#setup/primitives/open-url.js";import type { Prompter } from "#setup/prompter.js";import { slackMessageDeepLink } from "#setup/slack-connect.js";@@ -34,7 +35,9 @@ export const SETUP_FLOW_CONFIG = {/** The prompter surface plus the working-state interrupt trap a command races against. */export type TuiSetupCommandRenderer = TuiPrompterRenderer &- Pick<SetupFlowRenderer, "waitForInterrupt">;+ Pick<SetupFlowRenderer, "readProviderPicker" | "waitForInterrupt">;++type MuteableSetupRenderer = TuiPrompterRenderer & Pick<SetupFlowRenderer, "readProviderPicker">;export interface TuiSetupCommandInput {command: TuiSetupCommand;@@ -73,14 +76,16 @@ export interface TuiSetupCommandResult {* output drops while the flow unwinds.*/function muteableRenderer(- renderer: TuiPrompterRenderer,+ renderer: TuiSetupCommandRenderer,isMuted: () => boolean,-): TuiPrompterRenderer {+): MuteableSetupRenderer {return {readSelect: (options) =>isMuted() ? Promise.resolve(undefined) : renderer.readSelect(options),readEditableSelect: (options) =>isMuted() ? Promise.resolve(undefined) : renderer.readEditableSelect(options),+ readProviderPicker: (options) =>+ isMuted() ? Promise.resolve(undefined) : renderer.readProviderPicker(options),readText: (options) => (isMuted() ? Promise.resolve(undefined) : renderer.readText(options)),readAcknowledge: (options) =>isMuted() ? Promise.resolve() : renderer.readAcknowledge(options),@@ -116,13 +121,12 @@ export async function runTuiSetupCommand(const { command } = input;let interrupted = false;const controller = new AbortController();- const prompter = (input.createPrompter ?? createTuiPrompter)(- muteableRenderer(input.renderer, () => interrupted),- );+ const renderer = muteableRenderer(input.renderer, () => interrupted);+ const prompter = (input.createPrompter ?? createTuiPrompter)(renderer);const interrupt = input.renderer.waitForInterrupt();const INTERRUPTED = Symbol("interrupted");- const execution = executeSetupCommand(input, prompter, controller.signal);+ const execution = executeSetupCommand(input, prompter, renderer, controller.signal);try {const outcome = await Promise.race([execution, interrupt.promise.then(() => INTERRUPTED)]);if (outcome !== INTERRUPTED) return outcome as TuiSetupCommandResult;@@ -145,6 +149,7 @@ export async function runTuiSetupCommand(async function executeSetupCommand(input: TuiSetupCommandInput,prompter: Prompter,+ renderer: MuteableSetupRenderer,signal: AbortSignal,): Promise<TuiSetupCommandResult> {const { command, appRoot } = input;@@ -168,10 +173,15 @@ async function executeSetupCommand(return loginResultMessage(await flows.runLoginFlow({ appRoot, prompter, signal }));}case "model": {+ const pickProvider: ProviderPicker = (request) => renderer.readProviderPicker(request);const modelInput: Parameters<TuiSetupFlows["runModelFlow"]>[0] = {appRoot,prompter,signal,+ deps: {+ runProviderFlow: (providerInput) =>+ runProviderFlow({ ...providerInput, picker: pickProvider }),+ },};if (input.initialModelStep !== undefined) {modelInput.initialStep = input.initialModelStep;diff --git a/packages/eve/src/cli/dev/tui/setup-flow.ts b/packages/eve/src/cli/dev/tui/setup-flow.tsindex 8504b22e8..be8d93b33 100644--- a/packages/eve/src/cli/dev/tui/setup-flow.ts+++ b/packages/eve/src/cli/dev/tui/setup-flow.ts@@ -1,5 +1,6 @@import type { ChannelSetupChoice, ChannelSetupChoiceOptions } from "#setup/cli/index.js";import type { SearchActionOption } from "#setup/cli/select-state.js";+import type { ProviderPickerChoice, ProviderPickerRequest } from "#setup/flows/provider.js";import type { SelectNotice } from "#setup/prompter.js";import type { SetupPanelOption } from "./setup-panel.js";@@ -72,6 +73,8 @@ export interface SetupFlowRenderer {validate?: (value: string) => string | undefined;};}): Promise<SetupEditableSelectResult | undefined>;+ /** Provider-only picker with masked async validation. Not part of Prompter. */+ readProviderPicker(options: ProviderPickerRequest): Promise<ProviderPickerChoice | undefined>;readText(options: {message: string;placeholder?: string;diff --git a/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts b/packages/eve/src/cli/dev/tui/setup-issues.integration.test.tsindex 85e958a82..4778410dd 100644--- a/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts@@ -58,9 +58,13 @@ async function linkedAppRoot(): Promise<string> {}describe("BOOT_DETECTIONS against a real directory", () => {- it("stays quiet when linked with a credential present", async () => {+ it("stays quiet when a compiled gateway model has a credential present", async () => {const appRoot = await linkedAppRoot();- const issues = await detectSetupIssues({ appRoot, env: { AI_GATEWAY_API_KEY: "k" } });+ const issues = await detectSetupIssues({+ appRoot,+ env: { AI_GATEWAY_API_KEY: "k" },+ info: DISCONNECTED_GATEWAY_INFO,+ });expect(issues).toEqual([]);});diff --git a/packages/eve/src/cli/dev/tui/setup-issues.test.ts b/packages/eve/src/cli/dev/tui/setup-issues.test.tsindex b34a509ad..44323172c 100644--- a/packages/eve/src/cli/dev/tui/setup-issues.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-issues.test.ts@@ -8,6 +8,7 @@ import {formatSetupIssuesLine,LOGIN_SETUP_ISSUE,orderedSetupIssues,+ resolveModelProviderState,type BootDetectionContext,} from "./setup-issues.js";@@ -87,9 +88,47 @@ describe("BOOT_DETECTIONS", () => {});});- it("stays quiet when either gateway credential is present, linked or not", async () => {- expect(await detectSetupIssues(context({ env: { AI_GATEWAY_API_KEY: "key" } }))).toEqual([]);- expect(await detectSetupIssues(context({ env: { VERCEL_OIDC_TOKEN: "token" } }))).toEqual([]);+ it.each([+ ["AI_GATEWAY_API_KEY", "key"],+ ["VERCEL_OIDC_TOKEN", "token"],+ ])(+ "treats a newly loaded gateway credential as configured while runtime info catches up",+ async (key, value) => {+ const info = infoWithRouting(+ { kind: "gateway", target: "openai" },+ { kind: "gateway", connected: false },+ );++ await expect(detectSetupIssues(context({ env: { [key]: value }, info }))).resolves.toEqual(+ [],+ );+ },+ );++ it("uses compiled gateway routing before a stale endpoint kind", () => {+ const info = infoWithRouting(+ { kind: "gateway", target: "openai" },+ { kind: "external", provider: "anthropic" },+ );++ expect(resolveModelProviderState(info, { AI_GATEWAY_API_KEY: "key" })).toMatchObject({+ agent: {+ model: {+ endpoint: { kind: "gateway", connected: true, credential: "api-key" },+ },+ },+ });+ });++ it.each([+ ["AI_GATEWAY_API_KEY", "key"],+ ["VERCEL_OIDC_TOKEN", "token"],+ ])("does not infer AI Gateway routing from a local credential alone", async (key, value) => {+ const issues = await detectSetupIssues(context({ env: { [key]: value } }));++ expect(issues).toEqual([+ { kind: "attention", label: "model provider not linked", command: "/model" },+ ]);});it("stays quiet for an external-provider model — gateway linking/credentials don't apply", async () => {@@ -108,7 +147,8 @@ describe("BOOT_DETECTIONS", () => {});it("skips a throwing detection instead of failing the boot", async () => {- const issues = await detectSetupIssues(context({ env: { AI_GATEWAY_API_KEY: "k" } }), [+ const info = infoWithRouting({ kind: "gateway", target: "openai" });+ const issues = await detectSetupIssues(context({ env: { AI_GATEWAY_API_KEY: "k" }, info }), [{id: "broken",detect: () => {diff --git a/packages/eve/src/cli/dev/tui/setup-issues.ts b/packages/eve/src/cli/dev/tui/setup-issues.tsindex 4b4044dba..56d8c4fcc 100644--- a/packages/eve/src/cli/dev/tui/setup-issues.ts+++ b/packages/eve/src/cli/dev/tui/setup-issues.ts@@ -40,24 +40,81 @@ export interface BootDetection {detect(context: BootDetectionContext): SetupIssue[] | Promise<SetupIssue[]>;}-type ModelProviderAccess = "configured" | "unconfigured" | "unknown";+type ModelProviderAccess =+ | { kind: "unknown" }+ | { kind: "external" }+ | {+ kind: "gateway";+ runtime:+ | { status: "connected"; credential: "api-key" | "oidc" }+ | { status: "disconnected" }+ | { status: "unknown" };+ };++function hasEnvValue(env: Record<string, string | undefined>, key: string): boolean {+ const value = env[key];+ return value !== undefined && value.trim().length > 0;+}++/**+ * Resolves the local TUI's current model-provider state into the agent-info+ * snapshot it caches. The local TUI and dev server share `process.env`, so a+ * loaded credential is usable even when an earlier `/info` response says+ * disconnected.+ */+export function resolveModelProviderState(+ info: AgentInfoResult | undefined,+ env: Record<string, string | undefined>,+): AgentInfoResult | undefined {+ const access = modelProviderAccess({ env, info });+ if (info === undefined || access.kind !== "gateway" || access.runtime.status !== "connected") {+ return info;+ }+ const { credential } = access.runtime;++ const model = info.agent.model;+ const endpoint = model.endpoint;+ if (endpoint?.kind === "gateway" && endpoint.connected && endpoint.credential === credential) {+ return info;+ }++ return {+ ...info,+ agent: {+ ...info.agent,+ model: {+ ...model,+ endpoint: { kind: "gateway", connected: true, credential },+ },+ },+ };+}/** Classifies only evidence the boot path can actually observe. */function modelProviderAccess(context: Pick<BootDetectionContext, "env" | "info">,): ModelProviderAccess {- const endpoint = context.info?.agent.model.endpoint;- if (endpoint?.kind === "external") return "configured";- if (endpoint?.kind === "gateway") {- return endpoint.connected ? "configured" : "unconfigured";+ const model = context.info?.agent.model;+ if (model?.routing?.kind === "external") return { kind: "external" };+ if (model?.routing?.kind !== "gateway") return { kind: "unknown" };++ // The compiled routing decides whether gateway credentials apply. A freshly+ // loaded API key outranks a stale OIDC endpoint, matching gateway resolution.+ if (hasEnvValue(context.env, "AI_GATEWAY_API_KEY")) {+ return { kind: "gateway", runtime: { status: "connected", credential: "api-key" } };}-- // Older servers omit the composed endpoint status. Their routing and the- // dev process's loaded env can prove configuration, but absence proves- // nothing about credentials available only inside the running server.- if (context.info?.agent.model.routing?.kind === "external") return "configured";- if (context.env.AI_GATEWAY_API_KEY || context.env.VERCEL_OIDC_TOKEN) return "configured";- return "unknown";+ const endpoint = model.endpoint;+ if (endpoint?.kind === "gateway" && endpoint.connected) {+ return {+ kind: "gateway",+ runtime: { status: "connected", credential: endpoint.credential },+ };+ }+ if (hasEnvValue(context.env, "VERCEL_OIDC_TOKEN")) {+ return { kind: "gateway", runtime: { status: "connected", credential: "oidc" } };+ }+ if (endpoint?.kind === "gateway") return { kind: "gateway", runtime: { status: "disconnected" } };+ return { kind: "gateway", runtime: { status: "unknown" } };}/**@@ -66,29 +123,32 @@ function modelProviderAccess(* linking and credentials don't apply (and /model can't reconfigure it). For a* gateway model it reports only the most-root cause; an unlinked directory* implies missing OIDC, so listing both would double-count what /model's- * provider step fixes in one pass. The composed runtime endpoint is- * authoritative when available; legacy routing and local env can prove a- * provider is configured, but their absence remains unknown and cannot launch- * setup. A hint, not an error: the model call stays the source of truth.+ * provider step fixes in one pass. The header and detection receive the same+ * local-credential-normalized endpoint snapshot. Their absence remains+ * unknown and cannot launch setup. A hint, not an error: the model call stays+ * the source of truth.*/const modelProvider: BootDetection = {id: "model-provider",async detect({ appRoot, env, info }) {const access = modelProviderAccess({ env, info });- if (access === "configured") {- return [];+ if (access.kind === "external") return [];+ if (access.kind === "gateway") {+ if (access.runtime.status === "connected") return [];+ if (access.runtime.status === "disconnected") {+ const linked = await pathExists(join(appRoot, ".vercel", "project.json"));+ return [+ {+ kind: "model-provider-unconfigured",+ label: linked ? "AI Gateway credentials missing" : "model provider not linked",+ command: "/model",+ },+ ];+ }}+const linked = await pathExists(join(appRoot, ".vercel", "project.json"));- if (access === "unconfigured") {- return [- {- kind: "model-provider-unconfigured",- label: linked ? "AI Gateway credentials missing" : "model provider not linked",- command: "/model",- },- ];- }if (linked) {return [{ kind: "attention", label: "AI Gateway credentials missing", command: "/model" }];}diff --git a/packages/eve/src/cli/dev/tui/setup-panel.test.ts b/packages/eve/src/cli/dev/tui/setup-panel.test.tsindex c02c2d9fc..671c4ccf2 100644--- a/packages/eve/src/cli/dev/tui/setup-panel.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-panel.test.ts@@ -7,6 +7,7 @@ import {renderFlowPanel,renderSelectQuestion,renderTextQuestion,+ type SetupPanelOption,} from "./setup-panel.js";import { stripAnsi } from "./terminal-text.js";import { createTheme } from "./theme.js";@@ -130,6 +131,32 @@ describe("renderFlowPanel", () => {});describe("renderSelectQuestion", () => {+ it("shows a stacked menu's selected-row description beneath that option", () => {+ const options: SetupPanelOption[] = [+ { value: "model", label: "Change model", description: "The model your agent uses" },+ {+ value: "provider",+ label: "Configure model access",+ description: "How your agent reaches the model provider",+ },+ ];+ const rows = renderSelectQuestion(+ {+ kind: "stacked",+ message: "",+ options,+ select: initialSelectState({ options, defaultValue: "provider" }),+ },+ theme,+ 80,+ );++ expect(rows.indexOf(" How your agent reaches the model provider")).toBe(+ rows.findIndex((row) => row.includes("▶ Configure model access")) + 1,+ );+ expect(rows.join("\n")).not.toContain("The model your agent uses");+ });+it("paints an unnumbered single-select with one state-glyph column", () => {const rows = renderSelectQuestion({@@ -388,22 +415,25 @@ describe("renderSelectQuestion", () => {{ value: "new", label: "Create a new project", hint: "Named 'weather-agent'" },{ value: "link", label: "Link an existing project" },];- const baseEdit = {- optionValue: "new",- defaultValue: "weather-agent",- formatHint: (value: string) => `Named '${value}'`,- caretVisible: true,- };+ const renameEditor = (editor: ReturnType<typeof lineOf>) =>+ ({+ kind: "rename",+ editor,+ defaultValue: "weather-agent",+ formatHint: (value: string) => `Named '${value}'`,+ }) as const;+ const baseEdit = { optionValue: "new", caretVisible: true };// Hovering the editable row: the seeded default reads back with the caret// parked after it, never wedged before the name, and the footer says so.const hover = renderSelectQuestion({- kind: "editable",+ kind: "inline-edit",+ layout: "task-list",message: "Vercel project",options,select: initialSelectState({ options }),- edit: { ...baseEdit, editor: lineOf("weather-agent") },+ edit: { ...baseEdit, editor: renameEditor(lineOf("weather-agent")) },},theme,80,@@ -415,11 +445,12 @@ describe("renderSelectQuestion", () => {// Caret off (blink) collapses to nothing — no stray space before the quote.const hoverOff = renderSelectQuestion({- kind: "editable",+ kind: "inline-edit",+ layout: "task-list",message: "Vercel project",options,select: initialSelectState({ options }),- edit: { ...baseEdit, caretVisible: false, editor: lineOf("weather-agent") },+ edit: { ...baseEdit, caretVisible: false, editor: renameEditor(lineOf("weather-agent")) },},theme,80,@@ -430,11 +461,12 @@ describe("renderSelectQuestion", () => {// A backspaced field renders the shortened name with the caret at its end.const edited = renderSelectQuestion({- kind: "editable",+ kind: "inline-edit",+ layout: "task-list",message: "Vercel project",options,select: initialSelectState({ options }),- edit: { ...baseEdit, editor: lineOf("weather-fixtur") },+ edit: { ...baseEdit, editor: renameEditor(lineOf("weather-fixtur")) },},theme,80,@@ -442,24 +474,71 @@ describe("renderSelectQuestion", () => {expect(edited.join("\n")).toContain("Named 'weather-fixtur▏'");});- it("hides the rename caret and hint when the cursor is off the editable row", () => {+ it("keeps a long masked key's inline failure visible within a narrow panel", () => {+ const options = [+ {+ value: "own-key",+ label: "AI Gateway via AI_GATEWAY_API_KEY",+ hint: "> type your key",+ },+ ];+ const width = 44;+ const rows = renderSelectQuestion(+ {+ kind: "inline-edit",+ layout: "stacked",+ message: "Provider",+ options,+ select: initialSelectState({ options }),+ edit: {+ optionValue: "own-key",+ caretVisible: false,+ editor: {+ kind: "key",+ phase: {+ kind: "invalid",+ editor: lineOf(`sk-${"x".repeat(80)}`),+ message: "The AI Gateway rejected this key.",+ },+ },+ },+ },+ colorTheme,+ width,+ );+ const row = rows.find((line) => line.includes("Invalid key"));+ const plain = stripAnsi(row ?? "");++ expect(plain).toContain("…");+ expect(plain).toContain(" ⨯ Invalid key");+ expect(plain.length).toBeLessThanOrEqual(width);+ expect(row).toContain(+ colorTheme.colors.red(`${colorTheme.glyph.error} ${colorTheme.colors.bold("Invalid key")}`),+ );+ });++ it("hides the rename cursor and hint when the cursor is off the editable row", () => {const options = [{ value: "new", label: "Create a new project", hint: "Named 'weather-agent'" },{ value: "link", label: "Link an existing project" },];const rows = renderSelectQuestion({- kind: "editable",+ kind: "inline-edit",+ layout: "task-list",message: "Vercel project",options,// Cursor parked on the second (non-editable) row.select: { ...initialSelectState({ options }), cursor: 1 },edit: {optionValue: "new",- defaultValue: "weather-agent",- formatHint: (value: string) => `Named '${value}'`,caretVisible: true,- editor: lineOf(""),+ editor: {+ kind: "rename",+ editor: lineOf(""),+ defaultValue: "weather-agent",+ formatHint: (value: string) => `Named '${value}'`,+ },},},theme,@@ -533,7 +612,8 @@ describe("renderSelectQuestion", () => {it("keeps a stacked hint dim across an embedded bold span", () => {const colored = createTheme({ color: true, unicode: true });- const options = [+ const options: SetupPanelOption[] = [+ { value: "model", label: "Change model" },{value: "provider",label: "Change provider",@@ -556,12 +636,48 @@ describe("renderSelectQuestion", () => {expect(text).toContain("\x1b[1mmy-agent\x1b[22m\x1b[2m)");});+ it("uses the terminal foreground for a selected yellow hint and dims it otherwise", () => {+ const hint = colorTheme.colors.yellow("Not configured");+ const options: SetupPanelOption[] = [+ { value: "model", label: "Change model" },+ {+ value: "provider",+ label: "Configure model access",+ hint,+ },+ ];+ const selectedRows = renderSelectQuestion(+ {+ kind: "stacked",+ message: "",+ options,+ select: initialSelectState({ options, defaultValue: "provider" }),+ },+ colorTheme,+ 80,+ );+ const unselectedRows = renderSelectQuestion(+ {+ kind: "stacked",+ message: "",+ options,+ select: initialSelectState({ options, defaultValue: "model" }),+ },+ colorTheme,+ 80,+ );++ expect(selectedRows).toContain(" Not configured");+ expect(selectedRows).not.toContain(` ${hint}`);+ expect(unselectedRows).toContain(` ${colorTheme.colors.dim(hint)}`);+ });+it("keeps a warning row yellow under the cursor highlight", () => {- const options = [+ const options: SetupPanelOption[] = [{value: "provider",label: "Configure model access",- accent: "warning" as const,+ accent: "warning",},];const rows = renderSelectQuestion(@@ -580,6 +696,30 @@ describe("renderSelectQuestion", () => {);});+ it("renders each line of a stacked hint beneath its option", () => {+ const options = [+ {+ value: "project",+ label: "AI Gateway via Project",+ hint: "Authenticates with AI Gateway automatically\nin a new or existing project. No keys to manage.",+ },+ ];+ const rows = renderSelectQuestion(+ {+ kind: "stacked",+ message: "Which model provider do you want to use?",+ options,+ select: initialSelectState({ options }),+ },+ theme,+ 80,+ );++ expect(rows).toContain(" Authenticates with AI Gateway automatically");+ expect(rows).toContain(" in a new or existing project. No keys to manage.");+ expect(rows.every((row) => !row.includes("\n"))).toBe(true);+ });+it("renders checkboxes and the Submit row for a multi-select", () => {const select = initialSelectState({options: OPTIONS,@@ -702,18 +842,13 @@ describe("renderTextQuestion", () => {const text = rows.join("\n");expect(rows[0]).toBe(" Project name");- // The input line sits directly under the message — no blank row between.expect(rows[1]).toContain("my-agent");expect(text).toContain("enter to submit · esc to cancel");});it("draws the blinking cursor as a block over the grapheme under it", () => {const rows = renderTextQuestion(- {- message: "Project name",- editor: { text: "hello", cursor: 3 },- mask: false,- },+ { message: "Project name", editor: { text: "hello", cursor: 3 }, mask: false },colorTheme,60,true,diff --git a/packages/eve/src/cli/dev/tui/setup-panel.ts b/packages/eve/src/cli/dev/tui/setup-panel.tsindex 76bcac63c..d5fdd65bd 100644--- a/packages/eve/src/cli/dev/tui/setup-panel.ts+++ b/packages/eve/src/cli/dev/tui/setup-panel.ts@@ -29,6 +29,7 @@ import {} from "#setup/cli/select-state.js";import type { SelectNotice } from "#setup/prompter.js";+import type { ProviderPickerPhase } from "./provider-picker.js";import { maskLine, visibleLine, type LineState } from "./line-editor.js";import type { Theme } from "./theme.js";import {@@ -61,23 +62,36 @@ interface SetupSelectPanelBase extends SetupQuestionPanelBase {loadingFrame?: string;}-interface SetupEditableRow {- /**- * The row whose hint is a live rename field. Hovering it (cursor on the row)- * makes it editable directly — typing and backspace edit the name in place —- * so the editor's text and a blinking caret render only on that row.- */+/**+ * A menu row that turns into an inline editor while the cursor rests on it.+ * `optionValue` names the row; the `editor` discriminant chooses the widget —+ * an in-place rename field, or a masked provider-key field with its own+ * validation phases. Hovering the row makes it editable directly (typing and+ * backspace edit in place), so the editor's text and a blinking caret render+ * only on that row. Layout and inline editing are orthogonal, so the editor+ * travels as a payload rather than as its own panel `kind`.+ */+interface SetupInlineEditRow {optionValue: string;- editor: LineState;- defaultValue: string;- formatHint: (value: string) => string;caretVisible: boolean;+ editor:+ | {+ kind: "rename";+ editor: LineState;+ defaultValue: string;+ formatHint: (value: string) => string;+ }+ | {+ kind: "key";+ phase: ProviderPickerPhase;+ };}/*** Select presentation variants. The discriminant owns the interaction grammar* so feature combinations are deliberate rather than resolved by conditional- * precedence inside the renderer.+ * precedence inside the renderer. Inline editing is the exception: it composes+ * with a layout instead of defining one, so `inline-edit` carries both.*/type SetupOptionSelectPanelState =| (SetupSelectPanelBase & { kind: "single" })@@ -86,7 +100,11 @@ type SetupOptionSelectPanelState =| (SetupSelectPanelBase & { kind: "searchable-multi"; placeholder?: string })| (SetupSelectPanelBase & { kind: "stacked" })| (SetupSelectPanelBase & { kind: "task-list" })- | (SetupSelectPanelBase & { kind: "editable"; edit: SetupEditableRow });+ | (SetupSelectPanelBase & {+ kind: "inline-edit";+ layout: "stacked" | "task-list";+ edit: SetupInlineEditRow;+ });interface SetupActionsPanelState {kind: "actions";@@ -169,6 +187,7 @@ function questionFooter(hints: readonly string[], theme: Theme): string[] {const BOLD_OR_DIM_CLOSE = "\x1b[22m";const DIM_OPEN = "\x1b[2m";+const ANSI_FOREGROUND_COLOR = new RegExp(`${String.fromCharCode(27)}\\[(?:3[0-9]|9[0-7])m`, "g");/*** Dims a line that may carry embedded bold spans (e.g. a flow bolding a@@ -179,6 +198,11 @@ function dimWithEmphasis(text: string, theme: Theme): string {return theme.colors.dim(text.replaceAll(BOLD_OR_DIM_CLOSE, `${BOLD_OR_DIM_CLOSE}${DIM_OPEN}`));}+/** A selected row must not inherit an authored hint color. */+function foregroundWithEmphasis(text: string): string {+ return text.replaceAll(DIM_OPEN, "").replace(ANSI_FOREGROUND_COLOR, "");+}+function toneGlyph(tone: FlowPanelLine["tone"], theme: Theme): string {const c = theme.colors;switch (tone) {@@ -295,18 +319,13 @@ interface SelectPresentation {selection: "single" | "multiple";filter: { placeholder: string | undefined } | undefined;layout: SelectLayout;- edit: SetupEditableRow | undefined;+ edit: SetupInlineEditRow | undefined;}function selectPresentation(state: SetupOptionSelectPanelState): SelectPresentation {switch (state.kind) {case "single":- return {- selection: "single",- filter: undefined,- layout: "plain",- edit: undefined,- };+ return { selection: "single", filter: undefined, layout: "plain", edit: undefined };case "search":return {selection: "single",@@ -315,12 +334,7 @@ function selectPresentation(state: SetupOptionSelectPanelState): SelectPresentatedit: undefined,};case "multi":- return {- selection: "multiple",- filter: undefined,- layout: "plain",- edit: undefined,- };+ return { selection: "multiple", filter: undefined, layout: "plain", edit: undefined };case "searchable-multi":return {selection: "multiple",@@ -329,26 +343,11 @@ function selectPresentation(state: SetupOptionSelectPanelState): SelectPresentatedit: undefined,};case "stacked":- return {- selection: "single",- filter: undefined,- layout: "stacked",- edit: undefined,- };+ return { selection: "single", filter: undefined, layout: "stacked", edit: undefined };case "task-list":- return {- selection: "single",- filter: undefined,- layout: "task-list",- edit: undefined,- };- case "editable":- return {- selection: "single",- filter: undefined,- layout: "task-list",- edit: state.edit,- };+ return { selection: "single", filter: undefined, layout: "task-list", edit: undefined };+ case "inline-edit":+ return { selection: "single", filter: undefined, layout: state.layout, edit: state.edit };}}@@ -401,19 +400,72 @@ function noticeBody(notice: SelectNotice, layout: SelectLayout, theme: Theme): sreturn notice.text;}-function editableOption(+function renameHint(option: SetupPanelOption,- isCursor: boolean,- edit: SetupEditableRow | undefined,+ caretVisible: boolean,+ rename: Extract<SetupInlineEditRow["editor"], { kind: "rename" }>,theme: Theme,): SetupPanelOption {- if (!isCursor || edit?.optionValue !== option.value) return option;-- const value = edit.editor.text || edit.defaultValue;- const caretAt = edit.editor.text.length === 0 ? value.length : edit.editor.cursor;- const caret = edit.caretVisible ? theme.colors.cyan(theme.glyph.caret) : "";+ const value = rename.editor.text || rename.defaultValue;+ const caretAt = rename.editor.text.length === 0 ? value.length : rename.editor.cursor;+ const caret = caretVisible ? theme.colors.cyan(theme.glyph.caret) : "";const editableValue = `${value.slice(0, caretAt)}${caret}${value.slice(caretAt)}`;- return { ...option, hint: edit.formatHint(editableValue) };+ return { ...option, hint: rename.formatHint(editableValue) };+}++function keyHint(+ option: SetupPanelOption,+ caretVisible: boolean,+ key: Extract<SetupInlineEditRow["editor"], { kind: "key" }>,+ theme: Theme,+ maxHintWidth: number,+): SetupPanelOption {+ const phase = key.phase;+ if (phase.kind === "inactive") return option;++ const display = maskLine(phase.editor);+ const cursorEnabled = phase.kind !== "validating" && phase.kind !== "invalid";+ let prefix = "";+ let suffix = "";+ if (phase.kind === "validating") {+ prefix = "Validating… ";+ } else if (phase.kind === "invalid") {+ suffix = ` ${theme.colors.red(`${theme.glyph.error} ${theme.colors.bold("Invalid key")}`)}`;+ }++ const placeholder = phase.editor.text.length === 0 ? "type your key" : undefined;+ const cursorLine = placeholder === undefined ? display : { text: placeholder, cursor: 0 };+ const inputWidth = Math.max(1, maxHintWidth - visibleLength(`> ${prefix}${suffix}`));+ const visible = visibleLine(cursorLine, inputWidth, theme.glyph.ellipsis);+ const value = cursorEnabled+ ? renderInputWithBlockCursor({+ ...visible,+ visible: caretVisible,+ inverse: theme.colors.inverse,+ })+ : renderInputText(`${visible.before}${visible.under}${visible.after}`);+ return { ...option, hint: `> ${prefix}${value}${suffix}` };+}++/**+ * Applies the inline editor's live hint to its bound row when the cursor rests+ * on it. Every other row — and every row when the cursor is elsewhere — renders+ * unchanged. The bound row's `editor` discriminant selects the widget.+ */+function inlineEditOption(+ option: SetupPanelOption,+ isCursor: boolean,+ edit: SetupInlineEditRow | undefined,+ theme: Theme,+ maxHintWidth: number,+): SetupPanelOption {+ if (!isCursor || edit === undefined || option.value !== edit.optionValue) return option;+ switch (edit.editor.kind) {+ case "rename":+ return renameHint(option, edit.caretVisible, edit.editor, theme);+ case "key":+ return keyHint(option, edit.caretVisible, edit.editor, theme, maxHintWidth);+ }}function optionWithoutStackedHint(@@ -453,10 +505,21 @@ function appendSelectOptionRows(input: {end: number;cursor: number;visibleLabelWidth: number;+ width: number;theme: Theme;}): void {- const { rows, state, presentation, visible, start, end, cursor, visibleLabelWidth, theme } =- input;+ const {+ rows,+ state,+ presentation,+ visible,+ start,+ end,+ cursor,+ visibleLabelWidth,+ width,+ theme,+ } = input;const c = theme.colors;for (let index = start; index < end; index += 1) {@@ -466,7 +529,11 @@ function appendSelectOptionRows(input: {rows.push("");}- const rendered = editableOption(option, isCursor, presentation.edit, theme);+ const inlineHintWidth =+ presentation.layout === "stacked"+ ? Math.max(1, width - 6)+ : Math.max(1, width - Math.max(visibleLabelWidth, option.label.length) - 9);+ const rendered = inlineEditOption(option, isCursor, presentation.edit, theme, inlineHintWidth);const { option: rowOption, stackedHint } = optionWithoutStackedHint(rendered,presentation.layout,@@ -477,18 +544,37 @@ function appendSelectOptionRows(input: {isCursor,isChecked: presentation.selection === "multiple" && state.select.selected.has(option.value),placeholder: optionUsesPlaceholder(presentation, index, visible.length),- hintPadding: visibleLabelWidth - option.label.length,+ hintPadding: Math.max(0, visibleLabelWidth - rowOption.label.length),theme,})}`,);if (stackedHint !== undefined) {- rows.push(` ${renderOptionRowContinuation(dimWithEmphasis(stackedHint, theme))}`);+ const editRow = presentation.edit;+ const isActiveProviderKey =+ isCursor &&+ editRow !== undefined &&+ editRow.optionValue === option.value &&+ editRow.editor.kind === "key" &&+ editRow.editor.phase.kind !== "inactive";+ for (const line of stackedHint.split("\n")) {+ const renderedHint = !isCursor+ ? dimWithEmphasis(line, theme)+ : isActiveProviderKey+ ? line+ : foregroundWithEmphasis(line);+ rows.push(` ${renderOptionRowContinuation(renderedHint)}`);+ }}// Disabled descriptions explain why an inert row cannot be selected, so// keep them visible even though the cursor skips that row.if (option.description !== undefined && (option.disabled === true || isCursor)) {- rows.push(` ${c.dim(option.description)}`);+ const description = c.dim(option.description);+ rows.push(+ presentation.layout === "stacked"+ ? ` ${renderOptionRowContinuation(description)}`+ : ` ${description}`,+ );}if (presentation.layout === "stacked" && index < end - 1) rows.push("");}@@ -533,14 +619,25 @@ function selectFooterHints(cursor: number,): string[] {const hints: string[] = [];- if (presentation.edit !== undefined && visible[cursor]?.value === presentation.edit.optionValue) {- hints.push("type to rename");+ let cancelHint = "esc to cancel";+ const edit = presentation.edit;+ if (edit !== undefined && visible[cursor]?.value === edit.optionValue) {+ if (edit.editor.kind === "key") {+ const phase = edit.editor.phase;+ if (phase.kind !== "inactive" && phase.editor.text.length > 0) {+ cancelHint = "esc to clear";+ }+ if (phase.kind === "validating") return [cancelHint];+ hints.push("type your key");+ } else {+ hints.push("type to rename");+ }}if (presentation.filter !== undefined) hints.push("type to filter");hints.push("↑/↓ move");hints.push(presentation.selection === "multiple" ? "space to toggle" : "enter to select");if (presentation.selection === "multiple") hints.push("enter on Submit to confirm");- hints.push("esc to cancel");+ hints.push(cancelHint);return hints;}@@ -589,9 +686,8 @@ export function renderSelectQuestion(const submitIndex = presentation.selection === "multiple" ? submitRowIndex(visible) : -1;const cursor = state.select.cursor;- // An empty message (e.g. a panel-titled menu) contributes no header rows;- // the panel's own spacing does the separating.const rows = selectMessageRows(state.message, presentation.layout, theme);+if (presentation.filter !== undefined) {rows.push(` ${searchFilter(@@ -639,6 +735,7 @@ export function renderSelectQuestion(end,cursor,visibleLabelWidth,+ width,theme,});appendSubmitRow(rows, cursor, submitIndex, theme);diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.tsindex 87d9652cc..ec898a0aa 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts@@ -1763,27 +1763,118 @@ describe("TerminalRenderer setup panel", () => {renderer.shutdown();});- it("returns an untouched editable row as a plain selection", async () => {- const { input, renderer } = makeRenderer();+ it("validates a masked key without replacing the provider frame", async () => {+ const { screen, input, renderer } = makeRenderer();+ let resolveValidation:+ | ((result: { kind: "valid" } | { kind: "invalid"; message: string }) => void)+ | undefined;+ const validate = vi.fn(+ () =>+ new Promise<{ kind: "valid" } | { kind: "invalid"; message: string }>((resolve) => {+ resolveValidation = resolve;+ }),+ );- const answer = renderer.setupFlow.readEditableSelect?.({- message: "Vercel project",- options: [- { value: "new", label: "Create a new project", hint: "Named 'weather-agent'" },- { value: "link", label: "Link an existing project" },- ],- initialValue: "new",- editable: {- value: "new",- defaultValue: "weather-agent",- formatHint: (value) => `Named '${value}'`,+ const answer = renderer.setupFlow.readProviderPicker({+ message: "Provider",+ options: [{ value: "own-key", label: "AI Gateway via AI_GATEWAY_API_KEY" }],+ initialValue: "own-key",+ validateInlineKey: validate,+ });++ expect(screen.rawOutput()).toContain("\x1b[7m");+ input.type("bad-key");+ input.enter();+ expect(screen.snapshot()).toContain("Provider");+ expect(screen.snapshot()).toContain("•••••••");+ expect(screen.snapshot()).not.toContain("bad-key");+ expect(screen.snapshot()).toContain("Validating…");++ resolveValidation?.({ kind: "invalid", message: "Rejected." });+ await vi.waitFor(() => {+ expect(screen.snapshot()).toContain("Invalid key");+ });+ input.type("x");+ expect(screen.snapshot()).not.toContain("Invalid key");++ input.enter();+ resolveValidation?.({ kind: "valid" });+ await expect(answer).resolves.toEqual({+ kind: "inline-key",+ key: "bad-keyx",+ validation: { kind: "valid" },+ });+ expect(validate).toHaveBeenCalledTimes(2);+ renderer.shutdown();+ });++ it.each([+ { name: "Escape", sequence: "\x1b", waitForEscape: true },+ { name: "Ctrl-C", sequence: "\u0003", waitForEscape: false },+ ])(+ "clears a masked key before $name cancels its editable row",+ async ({ sequence, waitForEscape }) => {+ 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",+ validateInlineKey: async () => ({ kind: "valid" }),+ });+ let settled = false;+ void answer.finally(() => {+ settled = true;+ });++ input.type("sk-secret");+ expect(screen.snapshot()).toContain("esc to clear");+ input.send(sequence);+ if (waitForEscape) await new Promise((resolve) => setTimeout(resolve, 50));++ expect(settled).toBe(false);+ expect(screen.snapshot()).not.toContain("•••••••••");+ expect(screen.snapshot()).toContain("type your key");+ expect(screen.snapshot()).toContain("esc to cancel");++ input.send(sequence);+ if (waitForEscape) await new Promise((resolve) => setTimeout(resolve, 50));+ await expect(answer).resolves.toBeUndefined();+ renderer.shutdown();+ },+ );++ it("aborts stale validation and keeps the latest result", async () => {+ const { input, renderer } = makeRenderer();+ 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",+ validateInlineKey: (key, signal) => {+ return new Promise<{ kind: "valid" }>((resolve) => {+ validations.push({ key, signal, finish: () => resolve({ kind: "valid" }) });+ });},});- expect(answer).toBeDefined();- // Enter without editing resolves to the default name, not a rename.+ input.type("sk-first");+ input.enter();+ await vi.waitFor(() => expect(validations).toHaveLength(1));+ input.send("\u0003");+ expect(validations[0]?.signal.aborted).toBe(true);+ input.type("sk-second");input.enter();- await expect(answer).resolves.toEqual({ kind: "selected", value: "new" });+ await vi.waitFor(() => expect(validations).toHaveLength(2));++ validations[0]?.finish();+ await Promise.resolve();+ await Promise.resolve();+ validations[1]?.finish();+ await expect(answer).resolves.toEqual({+ kind: "inline-key",+ key: "sk-second",+ validation: { kind: "valid" },+ });renderer.shutdown();});@@ -2472,14 +2563,25 @@ describe("TerminalRenderer status line", () => {serverUrl: "http://localhost:3000",info: agentInfoWithModel("anthropic/claude-sonnet-4-6", {kind: "gateway",- connected: true,- credential: "oidc",+ connected: false,}),});const prompt = renderer.readPrompt();renderer.setVercelStatus(vercelStatus);+ expect(screen.snapshot()).toContain("⚠ AI Gateway");++ renderer.renderAgentHeader({+ name: "Weather Agent",+ serverUrl: "http://localhost:3000",+ info: agentInfoWithModel("anthropic/claude-sonnet-4-6", {+ kind: "gateway",+ connected: true,+ credential: "oidc",+ }),+ });+const lines = screen.snapshot().split("\n");const promptRow = lines.findIndex((line) => line.includes("❯"));expect(promptRow).toBeGreaterThan(-1);@@ -2487,6 +2589,7 @@ describe("TerminalRenderer status line", () => {expect(statusRow).toContain("anthropic/claude-sonnet-4-6");// The linked project folds into the connected gateway label.expect(statusRow).toContain("AI Gateway (my-agent)");+ expect(statusRow).not.toContain("⚠ AI Gateway");// No token segment before any turn reports usage (↑ 0 ↓ 0 is noise).expect(statusRow).not.toContain("↑ 0");expect(statusRow).not.toContain("/deploy pending");diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.tsindex 8015e7d3c..e9bdc8dda 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts@@ -46,6 +46,7 @@ import type {SetupSelectRequest,} from "./setup-flow.js";import type { SelectNotice } from "#setup/prompter.js";+import type { ProviderPickerChoice, ProviderPickerRequest } from "#setup/flows/provider.js";import {initialSelectState,reduceSelect,@@ -73,6 +74,11 @@ import {renderBlockLines,} from "./blocks.js";import { formatDevRebuildStatus, summarizeChangedFiles } from "./dev-rebuild-status.js";+import {+ initialProviderPickerState,+ transitionProviderPicker,+ type ProviderPickerEvent,+} from "./provider-picker.js";import { buildAgentHeader } from "./agent-header.js";import {EMPTY_LINE,@@ -388,6 +394,7 @@ export class TerminalRenderer implements AgentTUIRenderer {end: (options) => this.#endSetupFlow(options?.preserveDiagnostics ?? true),readSelect: (options) => this.#readSetupSelect(options),readEditableSelect: (options) => this.#readSetupEditableSelect(options),+ readProviderPicker: (options) => this.#readProviderPicker(options),readText: (options) => this.#readSetupText(options),readAcknowledge: (options) => this.#readSetupAcknowledge(options),readChoice: (options) => this.#readSetupChoice(options),@@ -1408,25 +1415,25 @@ export class TerminalRenderer implements AgentTUIRenderer {flow.question = (width) => {const state: SetupSelectPanelState = {- kind: "editable",+ kind: "inline-edit",+ layout: "task-list",message: opts.message,options: opts.options,select,edit: {optionValue: opts.editable.value,- editor,- defaultValue: opts.editable.defaultValue,- formatHint: opts.editable.formatHint,caretVisible: this.#caretVisible,+ editor: {+ kind: "rename",+ editor,+ defaultValue: opts.editable.defaultValue,+ formatHint: opts.editable.formatHint,+ },},};if (error !== undefined) state.error = error;return renderSelectQuestion(state, this.#theme, width);};- // Hovering the editable row makes it a live field: seed the editor with the- // default (caret blinking at the end) so typing and backspace edit it in- // place — no → to enter or ← to leave. Moving off the row clears the field- // and stops the blink; returning re-seeds the default.const onEditableRow = () =>selectValueAtCursor([...opts.options], select.cursor) === opts.editable.value;const syncEditableRow = () => {@@ -1462,8 +1469,6 @@ export class TerminalRenderer implements AgentTUIRenderer {settle({ kind: "selected", value });return;}- // An untouched field resolves as a plain selection (the default name);- // any edit resolves as the renamed text.const text = (editor.text || opts.editable.defaultValue).trim();const invalid = opts.editable.validate?.(text);if (invalid !== undefined) {@@ -1496,8 +1501,6 @@ export class TerminalRenderer implements AgentTUIRenderer {break;}- // Text keys edit the hovered row's name in place; on a non-editable row- // there is nothing to type into, so they are ignored.if (!onEditableRow()) return;const edited = applyLineEditorKey(editor, key);if (edited !== undefined) applyEditor(edited);@@ -1507,6 +1510,130 @@ export class TerminalRenderer implements AgentTUIRenderer {return await question.promise;}+ async #readProviderPicker(+ opts: ProviderPickerRequest,+ ): Promise<ProviderPickerChoice | undefined> {+ const flow = this.#beginSetupQuestion();+ let interaction = initialProviderPickerState(opts.options, opts.initialValue);+ let validation: AbortController | undefined;++ flow.question = (width) =>+ renderSelectQuestion(+ {+ kind: "inline-edit",+ layout: "stacked",+ message: opts.message,+ options: opts.options,+ select: interaction.select,+ edit: {+ optionValue: "own-key",+ caretVisible: this.#caretVisible,+ editor: { kind: "key", phase: interaction.phase },+ },+ },+ this.#theme,+ width,+ );++ const syncCaret = () => {+ if (interaction.phase.kind === "editing" || interaction.phase.kind === "invalid") {+ this.#startCaretBlink();+ } else {+ this.#stopCaretBlink();+ }+ };+ syncCaret();+ this.#paint();++ const question = this.#captureSetupQuestion<ProviderPickerChoice | undefined>(+ (key, settle, reject) => {+ const dispatch = (event: ProviderPickerEvent) => {+ const transition = transitionProviderPicker(interaction, event, opts.options);+ switch (transition.kind) {+ case "ignore":+ return;+ case "clear":+ validation?.abort();+ validation = undefined;+ interaction = transition.state;+ syncCaret();+ this.#paint();+ return;+ case "cancel":+ settle(undefined);+ return;+ case "render":+ interaction = transition.state;+ syncCaret();+ this.#paint();+ return;+ case "validate": {+ interaction = transition.state;+ syncCaret();+ this.#paint();+ const controller = new AbortController();+ validation = controller;+ let result: ReturnType<typeof opts.validateInlineKey>;+ try {+ result = opts.validateInlineKey(transition.key, controller.signal);+ } catch (error) {+ reject(error);+ return;+ }+ void result.then(+ (outcome) => {+ if (validation !== controller || controller.signal.aborted) return;+ validation = undefined;+ dispatch({ type: "validated", validation: outcome });+ },+ (error: unknown) => {+ if (validation !== controller || controller.signal.aborted) return;+ validation = undefined;+ reject(error);+ },+ );+ return;+ }+ case "settle":+ settle(transition.result);+ return;+ }+ };++ const intent = setupSelectionIntent(key);+ switch (intent?.kind) {+ case "cancel":+ dispatch({ type: "cancel" });+ return;+ case "move":+ dispatch({ type: "move", direction: intent.direction });+ return;+ case "submit":+ dispatch({ type: "submit" });+ return;+ case "repaint":+ this.#paint();+ return;+ case undefined:+ break;+ }++ if (interaction.phase.kind !== "editing" && interaction.phase.kind !== "invalid") return;+ const edited = applyLineEditorKey(interaction.phase.editor, key);+ if (edited !== undefined) {+ this.#showCaret();+ dispatch({ type: "edit", editor: edited });+ }+ },+ () => {+ validation?.abort();+ validation = undefined;+ this.#stopCaretBlink();+ },+ );+ return await question.promise;+ }+/*** Asks one text question through the bordered setup panel. `mask` renders* bullets (passwords); `validate` paints its message red inside the panel@@ -1652,13 +1779,19 @@ export class TerminalRenderer implements AgentTUIRenderer {* only the repeated input attachment and panel teardown lifecycle.*/#captureSetupQuestion<T>(- consume: (key: TerminalKey, settle: (value: T) => void) => void,+ consume: (+ key: TerminalKey,+ settle: (value: T) => void,+ reject: (error: unknown) => void,+ ) => void,beforeClose?: () => void,): { promise: Promise<T>; settle(value: T): void } {let settled = false;let resolve!: (value: T) => void;- const promise = new Promise<T>((resolvePromise) => {+ let rejectPromise!: (error: unknown) => void;+ const promise = new Promise<T>((resolvePromise, reject) => {resolve = resolvePromise;+ rejectPromise = reject;});const settle = (value: T): void => {if (settled) return;@@ -1667,7 +1800,14 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#closeSetupQuestion();resolve(value);};- this.#consumeKey = (key) => consume(key, settle);+ const reject = (error: unknown): void => {+ if (settled) return;+ settled = true;+ beforeClose?.();+ this.#closeSetupQuestion();+ rejectPromise(error);+ };+ this.#consumeKey = (key) => consume(key, settle, reject);this.#attachInput();return { promise, settle };}@@ -2642,9 +2782,8 @@ export class TerminalRenderer implements AgentTUIRenderer {if (this.#logLevelHintActive) input.logLevel = this.#logs;const model = this.#agentHeader?.info?.agent.model.id;if (model !== undefined) input.model = model;- // The runtime boundary owns endpoint readiness: the dev server computes it- // from its full process.env and returns it on /eve/v1/info, so the status- // bar (local or --url) reads one authority instead of re-deriving locally.+ // The runner resolves model-provider state with `/info` before caching this+ // header, so the status bar consumes that shared snapshot.const endpoint = this.#agentHeader?.info?.agent.model.endpoint;if (endpoint !== undefined) input.endpoint = endpoint;// Skip the token segment entirely until a turn moves a token — a `↑ 0 ↓ 0`diff --git a/packages/eve/src/cli/dev/tui/test/fake-setup-flow-renderer.ts b/packages/eve/src/cli/dev/tui/test/fake-setup-flow-renderer.tsindex 3c2b31540..941538a93 100644--- a/packages/eve/src/cli/dev/tui/test/fake-setup-flow-renderer.ts+++ b/packages/eve/src/cli/dev/tui/test/fake-setup-flow-renderer.ts@@ -3,11 +3,13 @@ import type { SetupFlowRenderer } from "../setup-flow.js";export function createFakeSetupFlowRenderer(overrides: Partial<SetupFlowRenderer> = {},): SetupFlowRenderer {+ const { readProviderPicker = async () => undefined, ...rest } = overrides;return {begin: () => {},end: () => {},readSelect: async () => undefined,readEditableSelect: async () => undefined,+ readProviderPicker,readText: async () => undefined,readAcknowledge: async () => {},readChoice: () => ({ choice: Promise.resolve(undefined), close: () => {} }),@@ -18,6 +20,6 @@ export function createFakeSetupFlowRenderer(promise: new Promise<void>(() => {}),dispose: () => {},}),- ...overrides,+ ...rest,};}diff --git a/packages/eve/src/setup/flows/model.test.ts b/packages/eve/src/setup/flows/model.test.tsindex 3eea785af..e005a07f6 100644--- a/packages/eve/src/setup/flows/model.test.ts+++ b/packages/eve/src/setup/flows/model.test.ts@@ -47,7 +47,7 @@ function flowDeps(overrides: Partial<ModelFlowDeps> = {}): Partial<ModelFlowDepsdetectProviderStatus: vi.fn(async () => ({ kind: "gateway-project", projectName: "my-agent" }) as const,),- runVercelFlow: vi.fn(async () => ({ kind: "done" }) as const),+ runProviderFlow: vi.fn(async () => ({ kind: "done" }) as const),...overrides,};}@@ -106,13 +106,19 @@ describe("runModelFlow", () => {expect(menuPaints).toEqual([{options: [- { value: "model", label: "Change model", hint: "anthropic/claude-sonnet-4.6" },+ {+ value: "model",+ label: "Change model",+ hint: "anthropic/claude-sonnet-4.6",+ description: "The model your agent uses",+ },{value: "provider",label: "Change provider",hint: `AI Gateway (Linked to ${pc.bold("my-agent")})`,+ description: "How your agent reaches the model provider",},- { value: "done", label: "Done" },+ { value: "done", label: "Done", description: "Return to the prompt" },],notices: [],hintLayout: "stacked",@@ -130,7 +136,7 @@ describe("runModelFlow", () => {editable: false,})),// Even though detection finds nothing, external routing must NOT surface- // the "Configure provider / Required" gateway UX.+ // the "Configure model access" gateway UX.detectProviderStatus: vi.fn(async () => ({ kind: "unset" }) as const),});@@ -145,7 +151,6 @@ describe("runModelFlow", () => {value: "model",label: "Change model",disabled: true,- // Disabled because the model isn't a string literal, not because of routing.description: "Set via an SDK model call in agent.ts; edit the source to change it",},{@@ -154,9 +159,8 @@ describe("runModelFlow", () => {disabled: true,description: "Disabled in external endpoint mode",},- { value: "done", label: "Done" },+ { value: "done", label: "Done", description: "Return to the prompt" },],- // One yellow notice explains why both rows are inert.notices: [{tone: "warning",@@ -164,7 +168,6 @@ describe("runModelFlow", () => {},],hintLayout: "stacked",- // Both action rows are disabled, so the menu opens on Done.initialValue: "done",},]);@@ -198,8 +201,9 @@ describe("runModelFlow", () => {value: "provider",label: "Change provider",hint: "AI Gateway (AI_GATEWAY_API_KEY in .env.local)",+ description: "How your agent reaches the model provider",},- { value: "done", label: "Done" },+ { value: "done", label: "Done", description: "Return to the prompt" },]);// Gateway routing gets no external-restriction notice.expect(menuPaints[0]?.notices).toEqual([]);@@ -229,6 +233,7 @@ describe("runModelFlow", () => {value: "provider",label: "Change provider",hint: `AI Gateway (Linked to ${pc.bold("my-agent")} in ${pc.bold("my-team")})`,+ description: "How your agent reaches the model provider",});});@@ -251,6 +256,7 @@ describe("runModelFlow", () => {value: "provider",label: "Change provider",hint: "AI Gateway (AI_GATEWAY_API_KEY in .env.local)",+ description: "How your agent reaches the model provider",});});@@ -272,7 +278,7 @@ describe("runModelFlow", () => {expect(deps.readCurrentModel).toHaveBeenCalledTimes(1);});- it("returns a rejection without repainting the menu", async () => {+ it("returns a rejected model result without claiming the model changed", async () => {const { prompter, menuPaints } = scriptedPrompter({menu: ["model"],picker: ["openai/gpt-5.5"],@@ -297,10 +303,10 @@ describe("runModelFlow", () => {.fn<ModelFlowDeps["detectProviderStatus"]>().mockResolvedValueOnce({ kind: "unset" }).mockResolvedValueOnce({ kind: "gateway-project", projectName: "my-agent" });- const runVercelFlow = vi.fn<ModelFlowDeps["runVercelFlow"]>(+ const runProviderFlow = vi.fn<ModelFlowDeps["runProviderFlow"]>(async () => ({ kind: "done", credential: "AI_GATEWAY_API_KEY" }) as const,);- const deps = flowDeps({ detectProviderStatus, runVercelFlow });+ const deps = flowDeps({ detectProviderStatus, runProviderFlow });await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({kind: "done",@@ -310,17 +316,17 @@ describe("runModelFlow", () => {},});- expect(runVercelFlow).toHaveBeenCalledWith(expect.objectContaining({ appRoot: APP_ROOT }));+ expect(runProviderFlow).toHaveBeenCalledWith(expect.objectContaining({ appRoot: APP_ROOT }));expect(detectProviderStatus).toHaveBeenCalledTimes(2);expect(menuPaints).toHaveLength(0);});it("honors confirmed provider entry when link metadata looks configured", async () => {const { prompter, menuPaints } = scriptedPrompter({ menu: [] });- const runVercelFlow = vi.fn<ModelFlowDeps["runVercelFlow"]>(+ const runProviderFlow = vi.fn<ModelFlowDeps["runProviderFlow"]>(async () => ({ kind: "done", credential: "VERCEL_OIDC_TOKEN" }) as const,);- const deps = flowDeps({ runVercelFlow });+ const deps = flowDeps({ runProviderFlow });await expect(runModelFlow({@@ -337,14 +343,53 @@ describe("runModelFlow", () => {},});- expect(runVercelFlow).toHaveBeenCalledWith(expect.objectContaining({ appRoot: APP_ROOT }));+ expect(runProviderFlow).toHaveBeenCalledWith(expect.objectContaining({ appRoot: APP_ROOT }));expect(menuPaints).toHaveLength(0);});+ it("refreshes provider state after a committed setup is 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",+ envFile: ".env.local",+ });+ const runProviderFlow = vi.fn<ModelFlowDeps["runProviderFlow"]>(async () => {+ controller.abort();+ return { kind: "done", credential: "AI_GATEWAY_API_KEY" };+ });+ const deps = flowDeps({ detectProviderStatus, runProviderFlow });++ await expect(+ runModelFlow({+ appRoot: APP_ROOT,+ prompter,+ initialStep: "provider",+ signal: controller.signal,+ deps,+ }),+ ).resolves.toEqual({+ kind: "done",+ providerOutcome: {+ credential: "AI_GATEWAY_API_KEY",+ status: {+ kind: "gateway-key",+ envKey: "AI_GATEWAY_API_KEY",+ envFile: ".env.local",+ },+ },+ });+ expect(detectProviderStatus.mock.calls[1]?.[1]).toEqual({});+ });+it("treats the external-provider branch as informational — no notice, no outcome", async () => {const { prompter, menuPaints } = scriptedPrompter({ menu: ["provider", "esc"] });const deps = flowDeps({- runVercelFlow: vi.fn(async () => ({ kind: "done", outcome: "external-provider" }) as const),+ runProviderFlow: vi.fn(async () => ({ kind: "external-provider" }) as const),});// Nothing changed on disk (any existing gateway link is untouched), so@@ -360,7 +405,7 @@ describe("runModelFlow", () => {it("returns to the menu after a cancelled sub-flow and folds an empty exit", async () => {const { prompter, menuPaints } = scriptedPrompter({ menu: ["provider", "esc"] });const deps = flowDeps({- runVercelFlow: vi.fn(async () => ({ kind: "cancelled" }) as const),+ runProviderFlow: vi.fn(async () => ({ kind: "cancelled" }) as const),});await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({@@ -406,7 +451,7 @@ describe("runModelFlow", () => {it("lands on Done after the external-provider branch", async () => {const { prompter, menuPaints } = scriptedPrompter({ menu: ["provider", "esc"] });const deps = flowDeps({- runVercelFlow: vi.fn(async () => ({ kind: "done", outcome: "external-provider" }) as const),+ runProviderFlow: vi.fn(async () => ({ kind: "external-provider" }) as const),});await runModelFlow({ appRoot: APP_ROOT, prompter, deps });@@ -419,7 +464,7 @@ describe("runModelFlow", () => {await runModelFlow({appRoot: APP_ROOT,prompter: provider.prompter,- deps: flowDeps({ runVercelFlow: vi.fn(async () => ({ kind: "cancelled" }) as const) }),+ deps: flowDeps({ runProviderFlow: vi.fn(async () => ({ kind: "cancelled" }) as const) }),});expect(provider.menuPaints[1]?.initialValue).toBe("provider");diff --git a/packages/eve/src/setup/flows/model.ts b/packages/eve/src/setup/flows/model.tsindex 1a32a3d6c..3aaeb89da 100644--- a/packages/eve/src/setup/flows/model.ts+++ b/packages/eve/src/setup/flows/model.ts@@ -29,7 +29,7 @@ import { WizardCancelledError } from "../step.js";import { withSpinner } from "../with-spinner.js";import { inProjectSetupState, prompterSink } from "./in-project.js";-import { runVercelFlow } from "./vercel.js";+import { runProviderFlow } from "./provider.js";/** The current model id, its routing, and whether `/model` can rewrite it. */export interface CurrentAgentModel {@@ -57,7 +57,7 @@ export interface ModelFlowDeps {/** Reads how the model is backed right now, for the menu's provider row. */detectProviderStatus: typeof detectModelProviderStatus;/** The provider sub-flow behind the menu's provider row. */- runVercelFlow: typeof runVercelFlow;+ runProviderFlow: typeof runProviderFlow;}/**@@ -130,7 +130,7 @@ function providerStatusHint(* string literal, so an SDK model call (`gateway(...)` / `anthropic(...)`) is* disabled regardless of how it routes. The provider row keys off routing: an* external endpoint disables it (gateway credentials don't apply); a gateway- * endpoint gates it bold-yellow "Configure provider" until a link or credential+ * 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.*/@@ -142,7 +142,11 @@ function modelMenuRows(): SelectOption<ModelMenuRow>[] {let modelRow: SelectOption<ModelMenuRow>;if (editable) {- modelRow = { value: "model", label: "Change model" };+ modelRow = {+ value: "model",+ label: "Change model",+ description: "The model your agent uses",+ };if (current !== null) modelRow.hint = current;} else {modelRow = {@@ -156,19 +160,17 @@ function modelMenuRows(let providerRow: SelectOption<ModelMenuRow>;if (routing?.kind === "external") {providerRow = {+ disabled: true,value: "provider",label: "Change provider",- disabled: true,description: "Disabled in external endpoint mode",};} else if (provider.kind === "unset") {providerRow = {value: "provider",- // The label's own color covers every glyph, so it holds whether or not- // the cursor row's accent wrap is around it. `accent: "warning"` turns the- // cursor pointer yellow to match.- label: pc.bold(pc.yellow("Configure provider")),- hint: "Required to enable the agent",+ label: pc.bold("Configure model access"),+ hint: pc.yellow("Not configured"),+ description: "How your agent reaches the model provider",accent: "warning",};} else {@@ -176,12 +178,17 @@ function modelMenuRows(value: "provider",label: "Change provider",hint: providerStatusHint(provider, pc.bold),+ description: "How your agent reaches the model provider",};}// An explicit exit row, like the channels list — Esc works too, but the menu// must not make Esc the only way out.- return [modelRow, providerRow, { value: "done", label: "Done" }];+ return [+ modelRow,+ providerRow,+ { value: "done", label: "Done", description: "Return to the prompt" },+ ];}/**@@ -223,9 +230,9 @@ export async function detectModelProviderStatus(* onboarding uses ({@link selectModel}), pre-selected on the model the* runtime currently serves, then the static source edit that bakes the* choice into `agent.ts` (activation is the dev server's HMR watcher).- * The provider row runs {@link runVercelFlow} — the provider gate (AI- * Gateway or your own), then link-or-paste-a-key.- * Completed model and provider changes return to the prompt with their result.+ * The provider row runs {@link runProviderFlow}, whose single menu chooses a+ * project-backed gateway, an inline gateway key, or an external provider.+ * A completed model or provider change returns to the prompt with its result.* Cancelled flows and external-provider instructions return to the menu.*/export async function runModelFlow(input: {@@ -241,15 +248,15 @@ export async function runModelFlow(input: {readCurrentModel: readCurrentAgentModel,applyModel: changeAgentModel,detectProviderStatus: detectModelProviderStatus,- runVercelFlow,+ runProviderFlow,...input.deps,};// The model read is local, the provider status is a `vercel` round-trip;// one ephemeral spinner covers both so the menu paints with no persisted// loading lines.- const detectProvider = (): Promise<ModelProviderStatus> =>- deps.detectProviderStatus(appRoot, { signal });+ const detectProvider = (useFlowSignal = true): Promise<ModelProviderStatus> =>+ deps.detectProviderStatus(appRoot, useFlowSignal && signal !== undefined ? { signal } : {});let [{ id: current, routing, editable }, provider] = await withSpinner(prompter,"Checking the project…",@@ -322,23 +329,25 @@ export async function runModelFlow(input: {break;}- const result = await deps.runVercelFlow({ appRoot, prompter, signal });- signal?.throwIfAborted();+ const result = await deps.runProviderFlow({ appRoot, prompter, signal });// Backing out of the provider sub-flow changed nothing; the cursor stays on// the provider row so a retry is one keypress away.if (result.kind === "cancelled") {+ if (signal?.aborted) return { kind: "cancelled" };nextSelection = "provider";continue;}// External-provider setup only shows instructions, so keep the menu open.- if ("outcome" in result) {+ if (result.kind === "external-provider") {+ if (signal?.aborted) return { kind: "cancelled" };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.- provider = await withSpinner(prompter, "Checking the project…", detectProvider);- signal?.throwIfAborted();+ // 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.credential !== undefined) providerOutcome.credential = result.credential;break;diff --git a/packages/eve/src/setup/flows/provider.test.ts b/packages/eve/src/setup/flows/provider.test.tsnew file mode 100644index 000000000..9fa951a38--- /dev/null+++ b/packages/eve/src/setup/flows/provider.test.ts@@ -0,0 +1,160 @@+import { describe, expect, it, vi } from "vitest";++import { createFakePrompter } from "#internal/testing/fake-prompter.js";+import type { VercelAuthStatus } from "#setup/vercel-project.js";++import {+ EXTERNAL_PROVIDER_INSTRUCTIONS,+ EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE,+ PROVIDER_QUESTION,+ runProviderFlow,+ type ProviderFlowDeps,+ type ProviderPicker,+} from "./provider.js";++const APP_ROOT = "/app/my-agent";++function createDeps() {+ return {+ getVercelAuthStatus: vi.fn(async (): Promise<VercelAuthStatus> => "authenticated"),+ runLinkFlow: vi.fn<ProviderFlowDeps["runLinkFlow"]>(async () => ({+ kind: "done",+ credential: "VERCEL_OIDC_TOKEN",+ })),+ appendEnv: vi.fn<ProviderFlowDeps["appendEnv"]>(async () => ({+ written: ["AI_GATEWAY_API_KEY"],+ skipped: [],+ })),+ validateGatewayApiKey: vi.fn<ProviderFlowDeps["validateGatewayApiKey"]>(async () => ({+ kind: "valid",+ })),+ };+}++describe("runProviderFlow", () => {+ it("hands the Dev TUI one project, inline-key, and direct-provider menu", 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",+ "external",+ ]);+ expect(request.initialValue).toBe("project");+ return { kind: "project" };+ };++ const result = await runProviderFlow({+ appRoot: APP_ROOT,+ prompter: fake.prompter,+ picker,+ deps,+ });++ expect(result).toEqual({ kind: "done", credential: "VERCEL_OIDC_TOKEN" });+ expect(deps.runLinkFlow).toHaveBeenCalledExactlyOnceWith({+ appRoot: APP_ROOT,+ prompter: fake.prompter,+ projectSelection: "create-or-link",+ });+ });++ it("persists the accepted inline key and does not revalidate it after submission", async () => {+ const fake = createFakePrompter();+ const deps = createDeps();+ const picker: ProviderPicker = async (request) => {+ 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 };+ };++ const result = await runProviderFlow({+ appRoot: APP_ROOT,+ prompter: fake.prompter,+ picker,+ deps,+ });++ expect(result).toEqual({ kind: "done", credential: "AI_GATEWAY_API_KEY" });+ expect(deps.validateGatewayApiKey).toHaveBeenCalledExactlyOnceWith(+ "sk-inline",+ expect.any(AbortSignal),+ );+ expect(deps.appendEnv).toHaveBeenCalledExactlyOnceWith(+ `${APP_ROOT}/.env.local`,+ { AI_GATEWAY_API_KEY: "sk-inline" },+ { force: true },+ );+ });++ it("returns the committed key when interruption races the env write", async () => {+ const fake = createFakePrompter();+ const deps = createDeps();+ const picker: ProviderPicker = async () => ({+ kind: "inline-key",+ key: "sk-committed",+ validation: { kind: "valid" },+ });+ const writeStarted = Promise.withResolvers<void>();+ const releaseWrite = Promise.withResolvers<void>();+ deps.appendEnv.mockImplementationOnce(async () => {+ writeStarted.resolve();+ await releaseWrite.promise;+ return { written: ["AI_GATEWAY_API_KEY"], skipped: [] };+ });+ const controller = new AbortController();++ const execution = runProviderFlow({+ appRoot: APP_ROOT,+ prompter: fake.prompter,+ picker,+ signal: controller.signal,+ deps,+ });+ await writeStarted.promise;+ controller.abort();+ releaseWrite.resolve();++ await expect(execution).resolves.toEqual({+ kind: "done",+ credential: "AI_GATEWAY_API_KEY",+ });+ });++ it("shows direct-provider instructions without changing credentials", async () => {+ const fake = createFakePrompter();+ const deps = createDeps();++ const result = await runProviderFlow({+ appRoot: APP_ROOT,+ prompter: fake.prompter,+ picker: async () => ({ kind: "external" }),+ deps,+ });++ expect(result).toEqual({ kind: "external-provider" });+ expect(fake.prompter.acknowledge).toHaveBeenCalledExactlyOnceWith({+ message: EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE,+ lines: EXTERNAL_PROVIDER_INSTRUCTIONS,+ });+ expect(deps.appendEnv).not.toHaveBeenCalled();+ });++ it("folds a cancelled provider picker into the flow's cancelled result", async () => {+ const fake = createFakePrompter();+ const deps = createDeps();++ await expect(+ runProviderFlow({+ appRoot: APP_ROOT,+ prompter: fake.prompter,+ picker: async () => undefined,+ deps,+ }),+ ).resolves.toEqual({ kind: "cancelled" });+ expect(deps.runLinkFlow).not.toHaveBeenCalled();+ });+});diff --git a/packages/eve/src/setup/flows/provider.ts b/packages/eve/src/setup/flows/provider.tsnew file mode 100644index 000000000..98a7422a2--- /dev/null+++ b/packages/eve/src/setup/flows/provider.ts@@ -0,0 +1,229 @@+import pc from "picocolors";++import { appendEnv } from "../append-env.js";+import {+ AI_GATEWAY_API_KEY_ENV_FILE,+ AI_GATEWAY_API_KEY_ENV_VAR,+ writeAiGatewayApiKey,+} from "../ai-gateway-api-key.js";+import type { Prompter, SelectOption } from "../prompter.js";+import { WizardCancelledError } from "../step.js";+import { validateGatewayApiKey, type GatewayKeyValidation } from "../validate-gateway-key.js";+import {+ getVercelAuthStatus,+ vercelAuthBlockerReason,+ type VercelAuthStatus,+} from "../vercel-project.js";+import { withSpinner } from "../with-spinner.js";++import { runLinkFlow, type LinkFlowResult } from "./link.js";++export type ProviderConnection = "project" | "own-key" | "external";++export const PROVIDER_QUESTION = "Which model provider do you want to use?";++export const EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE = "Using another model provider";+export const EXTERNAL_PROVIDER_INSTRUCTIONS: readonly string[] = [+ `Set your provider's API key in ${AI_GATEWAY_API_KEY_ENV_FILE} — e.g. ANTHROPIC_API_KEY or OPENAI_API_KEY.`,+ 'In agent/agent.ts, set `model` to a provider-authored model — e.g. `anthropic("claude-opus-4.8")` from `@ai-sdk/anthropic`.',+ "See https://eve.dev/docs/agent-config for details.",+ "A running `eve dev` reloads env files automatically — no restart needed.",+];++/** Injected for tests; defaults to the real link flow, env write, and key check. */+export interface ProviderFlowDeps {+ getVercelAuthStatus: typeof getVercelAuthStatus;+ runLinkFlow: typeof runLinkFlow;+ appendEnv: typeof appendEnv;+ validateGatewayApiKey: typeof validateGatewayApiKey;+}++export type ProviderFlowResult =+ | LinkFlowResult+ | {+ kind: "external-provider";+ /** The user runs a non-gateway provider; nothing was linked or written. */+ };++type AcceptedGatewayKeyValidation = Exclude<GatewayKeyValidation, { kind: "invalid" }>;++/** A provider choice, including the accepted evidence for an inline key. */+export type ProviderPickerChoice =+ | { kind: "project" }+ | { kind: "external" }+ | {+ kind: "inline-key";+ key: string;+ validation: AcceptedGatewayKeyValidation;+ };++/** Private Dev TUI request for the provider's one-screen chooser. */+export interface ProviderPickerRequest {+ message: string;+ options: readonly SelectOption<ProviderConnection>[];+ initialValue: ProviderConnection;+ validateInlineKey(key: string, signal: AbortSignal): Promise<GatewayKeyValidation>;+}++/** Renderer-owned provider chooser; only the Dev TUI invokes this flow. */+export type ProviderPicker = (+ request: ProviderPickerRequest,+) => Promise<ProviderPickerChoice | undefined>;++function projectConnectionOption(+ authStatus: VercelAuthStatus | undefined,+): SelectOption<ProviderConnection> {+ const option: SelectOption<ProviderConnection> = {+ value: "project",+ label: "AI Gateway via Project",+ hint: "Authenticates with AI Gateway automatically\nin a new or existing project. No keys to manage.",+ };+ const disabledReason = authStatus === undefined ? undefined : vercelAuthBlockerReason(authStatus);+ return disabledReason === undefined+ ? option+ : { ...option, disabled: true, disabledReason, disabledReasonTone: "warning" };+}++function providerOptions(+ authStatus: VercelAuthStatus | undefined,+): SelectOption<ProviderConnection>[] {+ return [+ projectConnectionOption(authStatus),+ {+ value: "own-key",+ label: `AI Gateway via ${AI_GATEWAY_API_KEY_ENV_VAR}`,+ hint: "> type your key",+ },+ {+ value: "external",+ label: "Other providers",+ hint: "Connect directly to a model provider\nvia OPENAI_API_KEY or ANTHROPIC_API_KEY.",+ },+ ];+}++async function selectProvider(input: {+ picker?: ProviderPicker;+ options: SelectOption<ProviderConnection>[];+ initialValue: ProviderConnection;+ validateInlineKey: (key: string, signal: AbortSignal) => Promise<GatewayKeyValidation>;+}): Promise<ProviderPickerChoice> {+ const request: ProviderPickerRequest = {+ message: PROVIDER_QUESTION,+ options: input.options,+ initialValue: input.initialValue,+ validateInlineKey: input.validateInlineKey,+ };+ if (input.picker === undefined) {+ throw new Error("The provider flow requires the Dev TUI provider picker.");+ }+ const choice = await input.picker(request);+ if (choice === undefined) throw new WizardCancelledError();+ return choice;+}++/**+ * 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.+ */+export async function runProviderFlow(input: {+ appRoot: string;+ prompter: Prompter;+ signal?: AbortSignal;+ picker?: ProviderPicker;+ deps?: Partial<ProviderFlowDeps>;+}): Promise<ProviderFlowResult> {+ const { appRoot, prompter, signal } = input;+ const deps: ProviderFlowDeps = {+ getVercelAuthStatus,+ runLinkFlow,+ appendEnv,+ validateGatewayApiKey,+ ...input.deps,+ };++ let authStatus: VercelAuthStatus | undefined;+ let initialValue: ProviderConnection = "project";+ let keyChoice: Extract<ProviderPickerChoice, { kind: "inline-key" }>;++ try {+ while (true) {+ const choice = await selectProvider({+ picker: input.picker,+ options: providerOptions(authStatus),+ initialValue,+ validateInlineKey: (key, validationSignal) =>+ deps.validateGatewayApiKey(+ key,+ signal === undefined ? validationSignal : AbortSignal.any([signal, validationSignal]),+ ),+ });++ if (choice.kind === "external") {+ if (prompter.acknowledge) {+ await prompter.acknowledge({+ message: EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE,+ lines: EXTERNAL_PROVIDER_INSTRUCTIONS,+ });+ } else {+ prompter.note(+ EXTERNAL_PROVIDER_INSTRUCTIONS.join("\n"),+ EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE,+ );+ }+ return { kind: "external-provider" };+ }++ if (choice.kind === "inline-key") {+ keyChoice = choice;+ break;+ }++ const auth = await withSpinner(prompter, "Checking your Vercel login…", () =>+ deps.getVercelAuthStatus(appRoot, { signal }),+ );+ signal?.throwIfAborted();+ authStatus = auth;+ if (vercelAuthBlockerReason(authStatus) !== undefined) {+ initialValue = "own-key";+ continue;+ }+ return await deps.runLinkFlow({+ appRoot,+ prompter,+ signal,+ projectSelection: "create-or-link",+ });+ }+ } catch (error) {+ if (error instanceof WizardCancelledError) return { kind: "cancelled" };+ throw error;+ }++ const key = keyChoice.key.trim();+ const validation = keyChoice.validation;+ signal?.throwIfAborted();++ if (validation.kind === "inconclusive") {+ prompter.log.warning(+ `Couldn't reach the gateway to validate (${validation.message}). Saving the key anyway.`,+ );+ } else {+ prompter.log.success(`${pc.green("✓")} ${pc.bold("Valid key")}`);+ }++ const location = await writeAiGatewayApiKey({+ projectRoot: appRoot,+ apiKey: key,+ appendEnv: deps.appendEnv,+ });+ // The env write is the commit point. A concurrent interrupt may mute the+ // remaining UI, but the caller must still refresh model access for the key+ // that is now on disk.+ prompter.log.success(`Saved ${location.envKey} to ${location.envFile}.`);+ return { kind: "done", credential: location.envKey };+}diff --git a/packages/eve/src/setup/flows/vercel.test.ts b/packages/eve/src/setup/flows/vercel.test.tsdeleted file mode 100644index 45a2cc5c5..000000000--- a/packages/eve/src/setup/flows/vercel.test.ts+++ /dev/null@@ -1,219 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import { createFakePrompter } from "#internal/testing/fake-prompter.js";-import type { PrompterValue, SingleSelectOptions } from "#setup/prompter.js";-import { WizardCancelledError } from "#setup/step.js";-import type { VercelAuthStatus } from "#setup/vercel-project.js";--import {- CONNECTION_QUESTION,- EXTERNAL_PROVIDER_INSTRUCTIONS,- EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE,- PROVIDER_QUESTION,- runVercelFlow,- type VercelFlowDeps,-} from "./vercel.js";--const APP_ROOT = "/app/my-agent";--/** Answers the two entry questions; anything else is a test failure. */-function answers(provider: PrompterValue, connection?: PrompterValue) {- return (opts: SingleSelectOptions<PrompterValue>): PrompterValue => {- if (opts.message === PROVIDER_QUESTION) return provider;- if (opts.message === CONNECTION_QUESTION && connection !== undefined) return connection;- throw new Error(`Unexpected select: ${opts.message}`);- };-}--function createDeps() {- return {- getVercelAuthStatus: vi.fn(async (): Promise<VercelAuthStatus> => "authenticated"),- runLinkFlow: vi.fn<VercelFlowDeps["runLinkFlow"]>(async () => ({- kind: "done",- credential: "VERCEL_OIDC_TOKEN",- })),- appendEnv: vi.fn<VercelFlowDeps["appendEnv"]>(async () => ({- written: ["AI_GATEWAY_API_KEY"],- skipped: [],- })),- validateGatewayApiKey: vi.fn<VercelFlowDeps["validateGatewayApiKey"]>(async () => ({- kind: "valid",- })),- };-}--describe("runVercelFlow", () => {- it("delegates to the link flow for AI Gateway via a project", async () => {- const fake = createFakePrompter({ single: answers("gateway", "project") });- const deps = createDeps();-- const result = await runVercelFlow({ appRoot: APP_ROOT, prompter: fake.prompter, deps });-- expect(result).toEqual({ kind: "done", credential: "VERCEL_OIDC_TOKEN" });- // A project-less agent must be able to create its first project here, so- // the branch drives the link flow in create-or-link mode (not the- // existing-only mode `eve link` uses).- expect(deps.runLinkFlow).toHaveBeenCalledExactlyOnceWith({- appRoot: APP_ROOT,- prompter: fake.prompter,- projectSelection: "create-or-link",- });- expect(deps.appendEnv).not.toHaveBeenCalled();- expect(fake.prompter.acknowledge).not.toHaveBeenCalled();- });-- it("disables project linking when the Vercel CLI is missing", async () => {- let connectionPrompt: SingleSelectOptions<PrompterValue> | undefined;- const fake = createFakePrompter({- single: (opts) => {- if (opts.message === PROVIDER_QUESTION) return "gateway";- if (opts.message === CONNECTION_QUESTION) {- connectionPrompt = opts;- return "own-key";- }- throw new Error(`Unexpected select: ${opts.message}`);- },- password: () => "sk-gateway-test",- });- const deps = createDeps();- deps.getVercelAuthStatus.mockResolvedValueOnce("cli-missing");-- await runVercelFlow({ appRoot: APP_ROOT, prompter: fake.prompter, deps });-- expect(connectionPrompt?.options[0]).toEqual({- value: "project",- label: "Connect via a project",- hint: "vercel link + env pull",- disabled: true,- disabledReason: "Vercel CLI not found, see /vc",- disabledReasonTone: "warning",- });- expect(deps.runLinkFlow).not.toHaveBeenCalled();- });-- it("writes a pasted AI Gateway key to .env.local, trimmed", async () => {- const fake = createFakePrompter({- single: answers("gateway", "own-key"),- password: () => " sk-gateway-test ",- });- const deps = createDeps();-- const result = await runVercelFlow({ appRoot: APP_ROOT, prompter: fake.prompter, deps });-- expect(result).toEqual({ kind: "done", credential: "AI_GATEWAY_API_KEY" });- // The trimmed key is validated against the gateway before it is saved.- expect(deps.validateGatewayApiKey).toHaveBeenCalledExactlyOnceWith(- "sk-gateway-test",- undefined,- );- expect(deps.appendEnv).toHaveBeenCalledExactlyOnceWith(- `${APP_ROOT}/.env.local`,- { AI_GATEWAY_API_KEY: "sk-gateway-test" },- { force: true },- );- expect(deps.runLinkFlow).not.toHaveBeenCalled();- expect(fake.prompter.log.success).toHaveBeenCalledWith(- "Saved AI_GATEWAY_API_KEY to .env.local.",- );- });-- it("re-prompts when the gateway rejects the key, then saves the corrected one", async () => {- const keys = ["bad-key", "good-key"];- const fake = createFakePrompter({- single: answers("gateway", "own-key"),- password: () => keys.shift() ?? "good-key",- });- const deps = createDeps();- deps.validateGatewayApiKey- .mockResolvedValueOnce({ kind: "invalid", message: "The AI Gateway rejected this key." })- .mockResolvedValueOnce({ kind: "valid" });-- const result = await runVercelFlow({ appRoot: APP_ROOT, prompter: fake.prompter, deps });-- expect(result).toEqual({ kind: "done", credential: "AI_GATEWAY_API_KEY" });- expect(deps.validateGatewayApiKey).toHaveBeenCalledTimes(2);- expect(fake.prompter.log.error).toHaveBeenCalledOnce();- // Only the corrected key is written, exactly once.- expect(deps.appendEnv).toHaveBeenCalledExactlyOnceWith(- `${APP_ROOT}/.env.local`,- { AI_GATEWAY_API_KEY: "good-key" },- { force: true },- );- });-- it("saves the key with a warning when validation is inconclusive", async () => {- const fake = createFakePrompter({- single: answers("gateway", "own-key"),- password: () => "sk-offline",- });- const deps = createDeps();- deps.validateGatewayApiKey.mockResolvedValueOnce({- kind: "inconclusive",- message: "network down",- });-- const result = await runVercelFlow({ appRoot: APP_ROOT, prompter: fake.prompter, deps });-- expect(result).toEqual({ kind: "done", credential: "AI_GATEWAY_API_KEY" });- expect(fake.prompter.log.warning).toHaveBeenCalledOnce();- expect(deps.appendEnv).toHaveBeenCalledOnce();- });-- it("shows provider instructions and ends with the external-provider outcome", async () => {- const fake = createFakePrompter({ single: answers("other") });- const deps = createDeps();-- const result = await runVercelFlow({ appRoot: APP_ROOT, prompter: fake.prompter, deps });-- expect(result).toEqual({ kind: "done", outcome: "external-provider" });- expect(fake.prompter.acknowledge).toHaveBeenCalledExactlyOnceWith({- message: EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE,- lines: EXTERNAL_PROVIDER_INSTRUCTIONS,- });- expect(deps.runLinkFlow).not.toHaveBeenCalled();- expect(deps.appendEnv).not.toHaveBeenCalled();- });-- it("falls back to note when the prompter lacks acknowledge", async () => {- const fake = createFakePrompter({ single: answers("other") });- delete fake.prompter.acknowledge;- const deps = createDeps();-- const result = await runVercelFlow({ appRoot: APP_ROOT, prompter: fake.prompter, deps });-- expect(result).toEqual({ kind: "done", outcome: "external-provider" });- expect(fake.prompter.note).toHaveBeenCalledWith(- EXTERNAL_PROVIDER_INSTRUCTIONS.join("\n"),- EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE,- );- });-- it("folds Esc on the entry questions into cancelled", async () => {- const fake = createFakePrompter({- single: () => {- throw new WizardCancelledError();- },- });- const deps = createDeps();-- const result = await runVercelFlow({ appRoot: APP_ROOT, prompter: fake.prompter, deps });-- expect(result).toEqual({ kind: "cancelled" });- expect(deps.runLinkFlow).not.toHaveBeenCalled();- });-- it("folds Esc on the key paste into cancelled without writing", async () => {- const fake = createFakePrompter({- single: answers("gateway", "own-key"),- password: () => {- throw new WizardCancelledError();- },- });- const deps = createDeps();-- const result = await runVercelFlow({ appRoot: APP_ROOT, prompter: fake.prompter, deps });-- expect(result).toEqual({ kind: "cancelled" });- expect(deps.appendEnv).not.toHaveBeenCalled();- });-});diff --git a/packages/eve/src/setup/flows/vercel.ts b/packages/eve/src/setup/flows/vercel.tsdeleted file mode 100644index b326fdab0..000000000--- a/packages/eve/src/setup/flows/vercel.ts+++ /dev/null@@ -1,219 +0,0 @@-import pc from "picocolors";--import {- AI_GATEWAY_API_KEY_ENV_FILE,- AI_GATEWAY_API_KEY_ENV_VAR,- writeAiGatewayApiKey,-} from "../ai-gateway-api-key.js";-import { appendEnv } from "../append-env.js";-import type { Prompter, SelectOption } from "../prompter.js";-import { WizardCancelledError } from "../step.js";-import { validateGatewayApiKey } from "../validate-gateway-key.js";-import { getVercelAuthStatus, type VercelAuthStatus } from "../vercel-project.js";-import { withSpinner } from "../with-spinner.js";--import { runLinkFlow, type LinkFlowResult } from "./link.js";--type GatewayConnection = "project" | "own-key";--export const PROVIDER_QUESTION = "Which model provider do you want to use?";-export const CONNECTION_QUESTION = "How do you want to connect to AI Gateway?";--export const EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE = "Using another model provider";-export const EXTERNAL_PROVIDER_INSTRUCTIONS: readonly string[] = [- `Set your provider's API key in ${AI_GATEWAY_API_KEY_ENV_FILE} — e.g. ANTHROPIC_API_KEY or OPENAI_API_KEY.`,- 'In agent/agent.ts, set `model` to a provider-authored model — e.g. `anthropic("claude-opus-4.8")` from `@ai-sdk/anthropic`.',- "See https://eve.dev/docs/agent-config for details.",- "A running `eve dev` reloads env files automatically — no restart needed.",-];--/** Injected for tests; defaults to the real link flow, env write, and key check. */-export interface VercelFlowDeps {- getVercelAuthStatus: typeof getVercelAuthStatus;- runLinkFlow: typeof runLinkFlow;- appendEnv: typeof appendEnv;- validateGatewayApiKey: typeof validateGatewayApiKey;-}--export type VercelFlowResult =- | LinkFlowResult- | {- kind: "done";- /** The user runs a non-gateway provider; nothing was linked or written. */- outcome: "external-provider";- };--function projectConnectionOption(authStatus: VercelAuthStatus): SelectOption<GatewayConnection> {- const option: SelectOption<GatewayConnection> = {- value: "project",- label: "Connect via a project",- hint: "vercel link + env pull",- };-- switch (authStatus) {- case "authenticated":- return option;- case "cli-missing":- return {- ...option,- disabled: true,- disabledReason: "Vercel CLI not found, see /vc",- disabledReasonTone: "warning",- };- case "logged-out":- return {- ...option,- disabled: true,- disabledReason: "Log in to Vercel first, see /login",- disabledReasonTone: "warning",- };- case "unavailable":- return {- ...option,- disabled: true,- disabledReason: "Couldn't reach Vercel, check your connection",- disabledReasonTone: "warning",- };- default: {- const exhaustive: never = authStatus;- return exhaustive;- }- }-}--/**- * THE PROVIDER FLOW behind the dev TUI `/model` menu's provider row- * (`eve link` keeps {@link runLinkFlow}'s shape). Two entry questions make- * the provider choice explicit before any link machinery runs: a provider- * gate (AI Gateway, or instructions for everything else) and a connection- * gate (link a project, or paste an `AI_GATEWAY_API_KEY` that lands in- * `.env.local`). The "Connect via a project" branch runs the link flow in- * create-or-link mode (link detection and all), so a project-less agent can- * create its first project rather than dead-end on an empty list.- */-export async function runVercelFlow(input: {- appRoot: string;- prompter: Prompter;- signal?: AbortSignal;- deps?: Partial<VercelFlowDeps>;-}): Promise<VercelFlowResult> {- const { appRoot, prompter, signal } = input;- const deps: VercelFlowDeps = {- getVercelAuthStatus,- runLinkFlow,- appendEnv,- validateGatewayApiKey,- ...input.deps,- };-- let provider: "gateway" | "other";- let connection: GatewayConnection | undefined;- try {- provider = await prompter.select<"gateway" | "other">({- message: PROVIDER_QUESTION,- options: [- { value: "gateway", label: "Vercel AI Gateway", hint: "one key, every model" },- { value: "other", label: "Something else", hint: "use your own provider credentials" },- ],- hintLayout: "stacked",- });- if (provider === "gateway") {- const authStatus = await withSpinner(prompter, "Checking your Vercel login…", async () => {- const status = await deps.getVercelAuthStatus(appRoot, { signal });- signal?.throwIfAborted();- return status;- });-- connection = await prompter.select<GatewayConnection>({- message: CONNECTION_QUESTION,- options: [- projectConnectionOption(authStatus),- {- value: "own-key",- label: "Use my own key",- hint: `paste an ${AI_GATEWAY_API_KEY_ENV_VAR}`,- },- ],- hintLayout: "stacked",- });- }- } catch (error) {- // Backing out of the entry questions keeps everything as it was — fold- // the cancel the same way the link flow's re-link gate does.- if (error instanceof WizardCancelledError) {- return { kind: "cancelled" };- }- throw error;- }-- if (provider === "other") {- if (prompter.acknowledge) {- await prompter.acknowledge({- message: EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE,- lines: EXTERNAL_PROVIDER_INSTRUCTIONS,- });- } else {- prompter.note(- EXTERNAL_PROVIDER_INSTRUCTIONS.join("\n"),- EXTERNAL_PROVIDER_INSTRUCTIONS_TITLE,- );- }- return { kind: "done", outcome: "external-provider" };- }-- if (connection === "own-key") {- // Loop so a rejected key returns to the same prompt to retry (or Esc to- // cancel), rather than saving a key we know the gateway won't accept.- while (true) {- let key: string;- try {- key = await prompter.password({- message: `Enter your ${AI_GATEWAY_API_KEY_ENV_VAR}`,- validate: (value) => (value.trim().length === 0 ? "API key cannot be empty." : undefined),- });- } catch (error) {- if (error instanceof WizardCancelledError) {- return { kind: "cancelled" };- }- throw error;- }- signal?.throwIfAborted();-- const trimmed = key.trim();- const validation = await withSpinner(prompter, "Validating…", () =>- deps.validateGatewayApiKey(trimmed, signal),- );- signal?.throwIfAborted();-- if (validation.kind === "invalid") {- prompter.log.error(`${validation.message} Check the key and try again, or Esc to cancel.`);- continue;- }- if (validation.kind === "inconclusive") {- prompter.log.warning(- `Couldn't reach the gateway to validate (${validation.message}). Saving the key anyway.`,- );- } else {- prompter.log.success(`${pc.green("✓")} ${pc.bold("Valid key")}`);- }-- const location = await writeAiGatewayApiKey({- projectRoot: appRoot,- apiKey: trimmed,- appendEnv: deps.appendEnv,- });- signal?.throwIfAborted();- prompter.log.success(`Saved ${location.envKey} to ${location.envFile}.`);- return { kind: "done", credential: AI_GATEWAY_API_KEY_ENV_VAR };- }- } else {- // A fresh agent often has no Vercel project yet, so this branch can create- // one — unlike `eve link`, which links an existing project.- return await deps.runLinkFlow({- appRoot,- prompter,- signal,- projectSelection: "create-or-link",- });- }-}