Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): onboarding - go from init directly to chat (#3356)

Andrew Barba7b17b27f45e8
diff --git a/.changeset/compact-model-footer.md b/.changeset/compact-model-footer.md
new file mode 100644
index 000000000..941fd9bea
--- /dev/null
+++ b/.changeset/compact-model-footer.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Simplify the TUI footer by removing the local port and separating the model and connection with dots. Vercel account connections show the resolved team slug instead of a team ID.
diff --git a/.changeset/faster-model-connection.md b/.changeset/faster-model-connection.md
new file mode 100644
index 000000000..c3ef2ef9b
--- /dev/null
+++ b/.changeset/faster-model-connection.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Model login shares resolved credentials with the running agent, avoids rebuilds for account, team, and key changes, and refreshes agent information without delaying chat. Clear status messages show when to finish browser sign-in and what eve is waiting for, without flashing indicators for quick steps.
diff --git a/.changeset/local-workflow-health-probe.md b/.changeset/local-workflow-health-probe.md
new file mode 100644
index 000000000..ca9f66ca0
--- /dev/null
+++ b/.changeset/local-workflow-health-probe.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Fix a local workflow health-check failure after model or source changes. Capability probes no longer look up a run before it exists, avoiding a spurious queue error and startup delay.
diff --git a/.changeset/login-team-switch.md b/.changeset/login-team-switch.md
new file mode 100644
index 000000000..38aca413c
--- /dev/null
+++ b/.changeset/login-team-switch.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Allow switching Vercel teams through `/login` by always showing the team picker when multiple teams are available. The current team is highlighted rather than silently selected; automatic startup still reuses the saved connection.
diff --git a/.changeset/muted-vercel-footer.md b/.changeset/muted-vercel-footer.md
new file mode 100644
index 000000000..5fd2379d6
--- /dev/null
+++ b/.changeset/muted-vercel-footer.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Match the Vercel label's color to the surrounding model and team text in the TUI footer.
diff --git a/.changeset/prominent-empty-prompt.md b/.changeset/prominent-empty-prompt.md
new file mode 100644
index 000000000..7d81d9f62
--- /dev/null
+++ b/.changeset/prominent-empty-prompt.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Use the same full-size arrow for empty and populated TUI prompts, with the empty arrow in the terminal's default foreground color for better visibility.
diff --git a/.changeset/quiet-model-login.md b/.changeset/quiet-model-login.md
new file mode 100644
index 000000000..ddefb4798
--- /dev/null
+++ b/.changeset/quiet-model-login.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Open the TUI directly after init, connect models through `/login` without requiring a Vercel project, and store local credentials securely. Add direct OpenAI and Anthropic model helpers, apply model selections immediately, and simplify menus and `/add` to get to chat sooner. Vercel CLI installation and login now run during deployment instead of separate `/vc:install` and `/vc:login` commands.
diff --git a/.changeset/remote-trusted-sources-startup.md b/.changeset/remote-trusted-sources-startup.md
new file mode 100644
index 000000000..d37886661
--- /dev/null
+++ b/.changeset/remote-trusted-sources-startup.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Restore guided Trusted Sources setup when Deployment Protection blocks `eve dev --url`. eve reuses the existing Vercel CLI session, asks before changing project access, and verifies the connection before returning to chat.
diff --git a/.changeset/sandbox-release-image.md b/.changeset/sandbox-release-image.md
new file mode 100644
index 000000000..4f8ea7425
--- /dev/null
+++ b/.changeset/sandbox-release-image.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Use the base release version for default sandbox images when running commit or git-ref tarballs. Build metadata such as `+git.<sha>` no longer produces invalid image tags for Docker, microsandbox, or Vercel Sandbox.
diff --git a/.changeset/search-add-capabilities.md b/.changeset/search-add-capabilities.md
new file mode 100644
index 000000000..953d90b72
--- /dev/null
+++ b/.changeset/search-add-capabilities.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Search `/add` by capabilities such as iMessage or SMS, as well as item names and addresses. The picker now searches catalog titles and descriptions without adding extra text to menu rows.
diff --git a/.changeset/settled-startup-presentation.md b/.changeset/settled-startup-presentation.md
new file mode 100644
index 000000000..4929e3aee
--- /dev/null
+++ b/.changeset/settled-startup-presentation.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Keep the composer available while startup connects your model and prepares chat, with animated progress and prompts only when input is needed. Preserve drafts and queued messages through setup, and announce readiness only after the runtime refresh succeeds.
diff --git a/.changeset/stable-prompt-hint.md b/.changeset/stable-prompt-hint.md
new file mode 100644
index 000000000..d723c16e8
--- /dev/null
+++ b/.changeset/stable-prompt-hint.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Replace rotating TUI prompt suggestions with a stable “Send a message…” placeholder that does not assume agent capabilities.
diff --git a/.changeset/steer-on-enter.md b/.changeset/steer-on-enter.md
new file mode 100644
index 000000000..4d6070a1f
--- /dev/null
+++ b/.changeset/steer-on-enter.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Pressing Enter during a TUI response now steers the active agent immediately instead of queuing the message until the turn finishes. Startup messages and sessions without steering support continue to queue.
diff --git a/.changeset/steering-gutter-color.md b/.changeset/steering-gutter-color.md
new file mode 100644
index 000000000..13cd6c23a
--- /dev/null
+++ b/.changeset/steering-gutter-color.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Distinguish steered TUI messages with a yellow left gutter instead of an extra arrow row. Queued messages also render without an arrow row.
diff --git a/apps/package-artifacts/package.json b/apps/package-artifacts/package.json
index bae5f96e9..b91a68465 100644
--- a/apps/package-artifacts/package.json
+++ b/apps/package-artifacts/package.json
@@ -12,6 +12,7 @@
"@vercel/blob": "2.4.0"
},
"devDependencies": {
+ "eve": "workspace:*",
"vitest": "catalog:"
}
}
diff --git a/docs/agent-config.md b/docs/agent-config.md
index 7e73a91cb..af5579198 100644
--- a/docs/agent-config.md
+++ b/docs/agent-config.md
@@ -28,24 +28,22 @@ A config that selects a static Gateway model is compile-only. A config that cont
`model` accepts a gateway model id string, which routes through the [Vercel AI Gateway](https://vercel.com/docs/ai-gateway). To call a provider directly and configure the model in code, pass a provider-authored `LanguageModel`.
-Provider-specific AI SDK packages are regular project dependencies. A fresh `eve init` app includes the core `ai` package, but it does not install every provider package. Install the provider package you import, then set that provider's API key:
-
-```bash
-npm install @ai-sdk/anthropic
-```
+Use eve's helpers for direct OpenAI or Anthropic access without installing another provider package:
```ts title="agent/agent.ts"
-import { anthropic } from "@ai-sdk/anthropic";
import { defineAgent } from "eve";
+import { anthropic } from "eve/models/anthropic";
export default defineAgent({
- model: anthropic("claude-opus-4-8"),
+ model: anthropic(), // claude-sonnet-5
});
```
-Direct provider model ids use the provider's native format. For Anthropic, the
-version uses hyphens (`claude-opus-4-8`), while the Gateway id above uses a dot
-(`anthropic/claude-opus-4.8`).
+`openai()` from `eve/models/openai` defaults to `gpt-5.6-luna-fast`. Both helpers accept an optional native provider model ID and use `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`. During local development they can also use credentials saved through `/login`. Deployments require their API key in the server environment.
+
+For a local ChatGPT subscription, use `chatgpt()` from `eve/models/openai` and sign in with `/login`. It defaults to `gpt-5.6-luna-fast` and cannot run in a deployment.
+
+`/login` can switch a static Gateway string to an eve helper and manage its import. `/model` changes the selected model and settings immediately. Custom provider SDK calls and dynamic expressions retain their authored behavior and require manual source edits. You can still install an AI SDK provider package and pass its `LanguageModel` when you need provider-specific configuration.
Model use is subject to the terms, data-processing commitments, retention behavior, and available controls of the selected provider and routing path. Review the [AI Gateway model catalog](https://vercel.com/ai-gateway/models) for gateway-routed models, and review the provider's terms when you configure a direct `LanguageModel`.
diff --git a/docs/getting-started.mdx b/docs/getting-started.mdx
index c9129f2b3..4a03412fd 100644
--- a/docs/getting-started.mdx
+++ b/docs/getting-started.mdx
@@ -12,7 +12,7 @@ You need:
- npm, which Node.js includes
- A credential for the model your agent uses
-The default scaffolded model routes through the Vercel AI Gateway. Set `AI_GATEWAY_API_KEY`, or link a Vercel project to use `VERCEL_OIDC_TOKEN`. To use a model provider directly, install its AI SDK provider package and set the provider's API key.
+Connect a ChatGPT subscription, a Vercel account, or an AI Gateway, OpenAI, or Anthropic API key in the terminal UI. You do not need a Vercel project to start chatting.
Choose a model, provider, and channel that meet your data-processing and compliance requirements.
@@ -24,7 +24,11 @@ Run `eve init` with a project name:
npx eve@latest init my-agent
```
-The command creates the project, installs dependencies, and initializes Git. After scaffolding, eve offers to start the development server or, if a supported coding agent is installed, to open the project in the coding agent.
+The command creates the project, installs dependencies, initializes Git, and opens the terminal UI. eve reuses an available model connection or opens `/login`. Once connected, type your first message. Channel and integration setup is optional; use `/add` when you need it.
+
+In `/add`, search by name or capability, such as `iMessage` or `SMS`. The picker matches item names, addresses, titles, and descriptions. Select an item to install it and complete its required setup.
+
+During startup, the status line shows what eve is waiting for. If you choose a Vercel account, finish signing in in your browser and select a team when prompted. eve checks that team's AI Gateway access and applies the connection before returning to the composer. Changing only the account, team, or key does not rebuild your agent. Once connected, you can send your first message while the agent information refreshes in the background; no restart is required.
To add eve to a project that already has a `package.json`, run this command from its root before you create any `agent/` files:
@@ -44,7 +48,7 @@ npx eve@latest init my-agent --model openai/gpt-5.6-terra --reasoning high
## Run the agent
-Choose **Start eve dev** after scaffolding, or run this from the project root:
+The terminal UI opens after interactive initialization. To return later, run this from the project root:
```bash
npm run dev
diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.md
index 004f2864d..37f066ee0 100644
--- a/docs/guides/dev-tui.md
+++ b/docs/guides/dev-tui.md
@@ -9,42 +9,65 @@ description: "Use eve locally or connect to a deployed agent from an interactive
eve dev
```
+The footer shows the active model and connection separated by dots. Vercel account connections show the team slug once it resolves; the local server port is omitted.
+
The transcript remains in your terminal scrollback after you exit. Run `/help` in the UI to see the commands available in the current session.
## Commands
-| Command | Description |
-| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| `/model` | Configure the model and its provider. Pass a model ID to set it directly: `/model provider/model-id`. |
-| `/add` | Select and install channels, MCP connections, extensions, and observability integrations. Pass an item address to confirm and install it directly: `/add channel/slack`. |
-| `/deploy` | Deploy the agent to Vercel production. Links the directory first if needed. |
-| `/vc:install` | Install the Vercel CLI. |
-| `/vc:login` | Log in to Vercel or restore access to a remote deployment. |
-| `/info` | Show the resolved application, compiled artifacts, discovery diagnostics, and messaging routes. |
-| `/loglevel` | Choose which server and agent logs appear in the transcript. |
-| `/traces` | Open the local trace viewer. Pass a trace ID prefix to open a specific trace. |
-| `/reset` | Start a fresh session. |
-| `/cancel` | Cancel the current turn without discarding settled context. |
-| `/clear` | Clear the session's model-message history. `/new` is an alias. |
-| `/compact` | Compact the current session's context. |
-| `/exit` | Quit the UI. |
-| `/help` | List available commands. |
-
-`/model`, `/add`, `/deploy`, `/info`, and `/traces` are available when `eve dev` runs locally. They are unavailable when the UI connects to a server with `--url`.
+| Command | Description |
+| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `/login` | Connect a ChatGPT subscription, Vercel account, or provider API key. |
+| `/model` | Choose the model and its settings. Pass a model ID to set it directly: `/model provider/model-id`. |
+| `/add` | Select and install channels, MCP connections, extensions, and observability integrations. Pass an item address to install it directly: `/add channel/slack`. |
+| `/deploy` | Deploy the agent to Vercel production. Installs the Vercel CLI, signs in, and links the directory if needed. |
+| `/info` | Show the resolved application, compiled artifacts, discovery diagnostics, and messaging routes. |
+| `/loglevel` | Choose which server and agent logs appear in the transcript. |
+| `/traces` | Open the local trace viewer. Pass a trace ID prefix to open a specific trace. |
+| `/reset` | Start a fresh session. |
+| `/cancel` | Cancel the current turn without discarding settled context. |
+| `/clear` | Clear the session's model-message history. `/new` is an alias. |
+| `/compact` | Compact the current session's context. |
+| `/exit` | Quit the UI. |
+| `/help` | List available commands. |
+
+`/login`, `/model`, `/add`, `/deploy`, `/info`, and `/traces` are available when `eve dev` runs locally. They are unavailable when the UI connects to a server with `--url`.
## Set up a new agent
-After `eve init`, the terminal UI guides you through **Model**, **Channels**, **Integrations**, and **Review** before the first chat prompt. The progress rail keeps the four steps visible throughout onboarding. Model setup can install or upgrade the Vercel CLI, open Vercel login, and resume project linking without leaving the flow.
+After interactive `eve init`, the TUI opens directly. eve keeps the project's selected connection. For a new connection, it checks explicit environment credentials, the saved machine default, and then the Vercel CLI's current team. Existing project OIDC connections remain supported. Automatic Vercel reuse validates account access without creating or linking a project.
-Model and Vercel changes take effect when you complete Model, then onboarding continues to Channels. Channel and integration selections remain drafts until you finish Review. You can move back and forth between Channels, Integrations, and Review; use `/model` after onboarding to change the committed model configuration.
+During startup, the composer stays visible while a progress indicator names the connection being checked and shows when eve is preparing your chat. Type a message and press `Enter` to queue it for when the agent is ready. A picker temporarily takes over input when a choice or API key is needed; your draft returns afterward. If setup is cancelled or fails, queued messages return to the draft.
-## Add an integration
+If no connection is ready, `/login` offers:
+
+1. Vercel Account
+2. Vercel AI Gateway API Key
+3. ChatGPT Subscription
+4. OpenAI API Key
+5. Anthropic API Key
+
+Vercel account login opens a browser. When multiple teams are available, `/login` shows a searchable team picker with the current project or CLI team highlighted so you can switch teams. A sole available team is selected automatically. Automatic startup reuses the selected connection without opening this picker. Account-token access to Gateway depends on availability for your account and team; if it is unavailable, choose an API key or another connection.
+
+Type to filter a menu, press `Enter` to select, or `Esc` to return to chat. Dismissing a setup menu adds no cancellation message to the transcript; completed work and failures still appear. Arrow navigation is also available. Cancelling login preserves your draft. If a connection fails, retry `/login`; eve does not silently switch providers.
+
+### Credentials and deployment
+
+eve saves API keys and eve-owned OAuth refresh credentials in the OS secret store through just-secrets. It saves the last successful login as the machine default and records the project's connection and team separately as nonsecret metadata in `.eve/provider.json`. Newly entered keys are never written into project files. A key explicitly selected through `/login` takes precedence over another key for that provider in your shell; a project connected through environment credentials continues to use its environment. Vercel CLI retains ownership of its credentials and refresh tokens.
-Bare `/add` opens the standalone planner on **Channels**. It does not include model configuration. The progress rail shows selection counts as you move between **Channels**, **Integrations**, and **Review**.
+Local discovery runs only in development. Deployments need explicitly provisioned `AI_GATEWAY_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, or supported project OIDC credentials. ChatGPT subscription models are local-only. `/login` does not link a deployment or authenticate a remote server; `/deploy` handles Vercel CLI installation and account login when needed.
-Press `Space` or `Enter` to toggle the highlighted item. Press `Right Arrow` to preserve the current selections and continue, `Left Arrow` to preserve them and go back, or `Esc` to cancel. Installation requires `Enter` on **Install and set up** from Review. During installation, `Esc` cancels only the active item and continues with the remaining selections. The final summary reports installed, cancelled, and failed items separately.
+### Models and settings
-Pass an item address to `/add` to confirm and install that exact address without opening the planner:
+`/model` opens the model picker and settings. Each completed selection applies immediately and returns to chat; there is no final Done step. A successful login or model change takes effect on the next prompt.
+
+OpenAI, ChatGPT, and Gateway connections default to `gpt-5.6-luna-fast`; Anthropic defaults to `claude-sonnet-5`. An explicitly authored compatible model stays selected. If a new default is unavailable, eve offers the connection's available models. Dynamic or custom model expressions must be edited in `agent.ts`.
+
+## Add an integration
+
+`/add` opens one searchable catalog of channels, connections, extensions, and integrations. Type to filter and press `Enter` to install one item and run its required setup. The flow returns to chat afterward.
+
+Pass an item address to install it directly:
```text
/add channel/slack
@@ -53,13 +76,13 @@ Pass an item address to `/add` to confirm and install that exact address without
/add @acme/analytics
```
-The UI installs planner selections in order and offers deployment once after the batch when an installed item requires it.
+Required authorization or deployment setup still runs for the selected item. Press `Esc` to cancel setup; files already installed remain in the project.
## Work with the agent
Type a message and press `Enter` to send it. When the agent asks a question or requests tool approval, respond in the prompt shown by the UI. Connection authorization can open a browser; keep local `eve dev` running until the browser returns to it.
-While a turn is running, `Enter` queues a follow-up message. Press `Esc` or `Ctrl+C` to cancel the turn; when messages are queued, this uses the oldest queued message as the next turn instead. If a direct cancellation requested with `/cancel` or `Ctrl+C` does not settle, press `Ctrl+C` to stop waiting. The UI then returns to the prompt and asks you to press `Ctrl+C` again to exit. At an idle prompt, press `Ctrl+C` twice to exit.
+While a turn is running, `Enter` sends your message to steer the agent at its next execution boundary. Slash commands wait until the turn ends, except `/cancel`, which cancels directly. If the session does not support steering, messages queue for the next turn. Press `Esc` or `Ctrl+C` to cancel the turn; when messages are queued, this uses the oldest queued message as the next turn instead. If a direct cancellation requested with `/cancel` or `Ctrl+C` does not settle, press `Ctrl+C` to stop waiting. The UI then returns to the prompt and asks you to press `Ctrl+C` again to exit. At an idle prompt, press `Ctrl+C` twice to exit.
| Key | Action |
| ------------- | ----------------------------------------------------------------------------------------------------------------------- |
@@ -104,7 +127,9 @@ eve dev https://user:[email protected]
eve dev https://your-app.example.com -H 'Authorization: Bearer your_token_here'
```
-For a Vercel deployment that needs authentication, run `/vc:login` and follow the prompt. Remote sessions do not modify the local project's Vercel link or `.env.local`.
+Remote Vercel sessions reuse an existing authorized CLI session. They do not open an account login flow or modify the local project's Vercel link or `.env.local`.
+
+When Deployment Protection blocks startup, eve verifies the target project and asks before adding a Trusted Sources rule for development access to that deployment's environment. After approval, eve applies the rule and checks access again before returning to chat. Cancelling preserves your draft; restart `eve dev <url>` to try again. If you cannot change the project's policy, provide `VERCEL_AUTOMATION_BYPASS_SECRET` or ask a project administrator to configure access in Deployment Protection settings.
## What to read next
diff --git a/docs/protocols/acp.md b/docs/protocols/acp.md
index 19756d5a7..1981036bf 100644
--- a/docs/protocols/acp.md
+++ b/docs/protocols/acp.md
@@ -15,7 +15,7 @@ Without a URL, the client starts one process from the eve application root. It s
eve acp https://agent.example.com
```
-For a recognized Vercel deployment, eve verifies the exact origin and resolves a short-lived project-scoped OIDC token from the local Vercel session. If login or a Trusted Sources change is required, run `eve dev <url>` and complete `/vc:login` before launching ACP. `VERCEL_AUTOMATION_BYPASS_SECRET` remains available for deployments configured with a Protection Bypass for Automation token.
+For a recognized Vercel deployment, eve verifies the exact origin and resolves a short-lived project-scoped OIDC token from the local Vercel session. Remote access requires an existing authorized Vercel session; account login runs during local deployment. Configure required Trusted Sources access in the target project before launching ACP. `VERCEL_AUTOMATION_BYPASS_SECRET` remains available for deployments configured with a Protection Bypass for Automation token.
## Configure Zed
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index a4d400d48..fb4cfd8f7 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -57,7 +57,7 @@ Creates a new agent app or adds an agent to an existing app. Always installs dep
Existing packages do not need a target-selection prompt: run `eve init` from the project directory or `eve init path/to/app`. New projects in non-interactive environments need a new directory name, such as `eve init my-agent`.
-After scaffolding, a human terminal usually continues into `eve dev`. Enable the self-modification subagent to edit your agent from the dev session. Otherwise, if a coding-agent REPL is on `PATH`, you can launch it to make changes instead of opening the TUI. Fresh projects use the parent workspace's package manager when there is one; otherwise they use the manager that launched `eve init`.
+After scaffolding in an interactive human terminal, eve opens the TUI directly. Noninteractive and coding-agent invocations return without starting an interactive session. Fresh projects use the parent workspace's package manager when there is one; otherwise they use the manager that launched `eve init`.
| Flag | Type | Default | Description |
| ---------------------- | ------ | -------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
@@ -234,7 +234,7 @@ Pass a bare URL and the UI connects to that server instead of booting a local on
`eve acp` reserves stdin and stdout for newline-delimited JSON-RPC and sends diagnostics to stderr. Without a URL, it supervises an isolated local development server. With a URL, it bridges ACP to that server's existing eve HTTP API and accepts the same URL credentials and request headers as `eve dev <url>`. Pass `--scope <team>` when the active Vercel scope does not own the deployment; `EVE_VERCEL_SCOPE` provides the same value for managed harnesses. See [Agent Client Protocol (ACP)](../protocols/acp) for client configuration and capability limits.
-A fresh `eve init` starts onboarding before the first prompt: the TUI installs the Vercel CLI if needed, asks you to log in if needed, guides you through model configuration, then lets you choose channels and integrations. Other `--input` text stays editable in the prompt.
+A fresh `eve init` opens the TUI and reuses an available model connection or opens `/login`. No Vercel project, channels, integrations, or review step is required before chat. Use `/model` to change models and settings, and `/add` to install an addition. Other `--input` text stays editable in the prompt. See [Terminal UI](../guides/dev-tui) for credential precedence and login options.
For a URL target protected by HTTP Basic auth, put the credentials in the URL. eve sends them as a Basic `Authorization` header and strips them from the server URL before connecting:
diff --git a/docs/reference/telemetry.md b/docs/reference/telemetry.md
index a32434464..1948c4401 100644
--- a/docs/reference/telemetry.md
+++ b/docs/reference/telemetry.md
@@ -12,7 +12,7 @@ eve collects usage data from its CLI to help improve its commands and developmen
eve sends the following information to Vercel:
- The eve version, operating system, CPU architecture, and whether stdin is a terminal.
-- The command you ran, its outcome, and setup or onboarding steps when applicable. When setup or onboarding fails, eve sends a bounded category describing the failed step. It does not send the underlying error.
+- The command you ran, its outcome, and setup or onboarding steps when applicable, including connection-ready and first-response timing. When setup or onboarding fails, eve sends a bounded category describing the failed step. It does not send the underlying error.
- For `eve dev`, whether you connected to a local or remote agent and whether the UI was interactive or headless.
- Random identifiers for the CLI session, installation, and project, plus whether the installation and project identifiers are ephemeral or persistent.
diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.md
index d8feff553..ecefa89b0 100644
--- a/docs/reference/typescript-api.md
+++ b/docs/reference/typescript-api.md
@@ -135,7 +135,8 @@ import template from "../../prompts/template.txt?raw";
| `eve/sandbox` | `defineSandbox`, backends |
| `eve/instrumentation` | `defineInstrumentation`, `isChannel` |
| `eve/local-dev` | `getLocalDevCapability`, `LocalDevCapability` |
-| `eve/models/openai` | `chatgpt`, deprecated `experimental_chatgpt` |
+| `eve/models/openai` | `openai`, `chatgpt`, deprecated `experimental_chatgpt` |
+| `eve/models/anthropic` | `anthropic` |
| `eve/evals` | `defineEval`, `defineEvalConfig`, `mockModel`, eval types |
| `eve/evals/expect` | `includes`, `equals`, `matches`, `similarity` |
| `eve/evals/reporters` | `Braintrust`, `JUnit`, `EvalReporter` |
@@ -169,9 +170,15 @@ The function returns `LocalDevCapability | undefined`. It returns a capability o
Run source mutations inside `withSuspendedSource()`. It acquires a unique watcher lease, waits for your asynchronous callback to settle, and then releases the lease. Concurrent or nested calls cannot resume each other early, and releasing the final lease rebuilds the runtime artifacts. The callback's return value is returned, and its error is rethrown after release. If suspension cannot be acquired, the callback does not run. If the host cannot confirm release after a retry, the method throws an actionable error; restart `eve dev` before making more source changes.
+## Direct provider models
+
+`openai(model?)` from `eve/models/openai` and `anthropic(model?)` from `eve/models/anthropic` return eve-owned model instances using the vendored providers. They accept only an optional model ID. Defaults are `gpt-5.6-luna-fast` and `claude-sonnet-5`, respectively.
+
+Use `/login` for local credentials, or set `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`. Local secret-store discovery is disabled in deployments; provision server credentials explicitly. See [Set the model](../agent-config#set-the-model) for an example.
+
## ChatGPT subscription models
-`chatgpt()` from `eve/models/openai` serves an OpenAI model through your local ChatGPT login and bills the ChatGPT subscription. With no argument, it selects `gpt-5.6-sol`:
+`chatgpt()` from `eve/models/openai` serves an OpenAI model through your local ChatGPT login and bills the ChatGPT subscription. With no argument, it selects `gpt-5.6-luna-fast`:
```ts title="agent/agent.ts"
import { defineAgent } from "eve";
@@ -188,7 +195,7 @@ Pass another bare OpenAI model slug to override the default. `experimental_chatg
eve uses one local authentication path with two credential owners:
-1. Run `eve dev`, open `/model`, and select **Provider** → **ChatGPT subscription**.
+1. Run `eve dev`, open `/login`, and select **ChatGPT subscription**.
2. If `codex` is on `PATH`, eve uses `codex app-server` and launches `codex login` when sign-in is needed. Codex owns credential storage and refresh.
3. If the Codex binary is not found, eve falls back to direct browser sign-in and owns the saved session and refresh. If the browser does not open, use the URL printed in the terminal.
@@ -206,9 +213,9 @@ ChatGPT subscription credentials are local user credentials. `eve deploy` blocks
Troubleshooting:
-- **`chatgpt-sub login`**: open `/model` and select **Provider** → **ChatGPT subscription** to sign in again. eve launches `codex login` when Codex is available, or its direct sign-in flow when it is not.
+- **`chatgpt-sub login`**: open `/login` and select **ChatGPT subscription** to sign in again. eve launches `codex login` when Codex is available, or its direct sign-in flow when it is not.
- **`chatgpt-sub unavailable` with Codex installed**: update or restart Codex and retry. eve does not mask app-server failures by switching to a different saved session.
-- **`chatgpt-sub unavailable` without Codex**: follow the reported OS credential-store recovery steps, or check your network connection if token refresh failed. Retry from `/model`. If eve reports an invalid stored session, sign in again to replace it.
+- **`chatgpt-sub unavailable` without Codex**: follow the reported OS credential-store recovery steps, or check your network connection if token refresh failed. Retry from `/login`. If eve reports an invalid stored session, sign in again to replace it.
- **Model rejected by the backend**: model availability depends on the signed-in ChatGPT account. Pick another supported OpenAI model.
- **Device sign-in unavailable**: enable device code authorization in ChatGPT security settings, or sign in from a local terminal with port 1455 available.
diff --git a/docs/sandbox.mdx b/docs/sandbox.mdx
index d167e4860..ffa6a3d9c 100644
--- a/docs/sandbox.mdx
+++ b/docs/sandbox.mdx
@@ -168,7 +168,7 @@ With `backend` omitted, eve uses `defaultBackend()`, which resolves on first use
3. **microsandbox** when the host supports it: macOS on Apple Silicon, or glibc Linux with KVM enabled.
4. **just-bash** as the dependency-free fallback.
-By default, Docker and microsandbox pull `ghcr.io/vercel/eve` while Vercel Sandbox pulls `vcr.vercel.com/vercel/eve/base`. Each image tag matches the installed eve version. Set `EVE_SANDBOX_IMAGE_TAG` to replace the version-derived tag for these default images. An explicit `image` passed to `docker()`, `microsandbox()`, or `vercel()` takes precedence. A snapshot `source` on `vercel()` takes precedence over its `image` because Vercel Sandbox treats them as mutually exclusive.
+By default, Docker and microsandbox pull `ghcr.io/vercel/eve` while Vercel Sandbox pulls `vcr.vercel.com/vercel/eve/base`. Each image tag matches the installed eve version without build metadata: a commit tarball version such as `0.56.0+git.4c27b3e37fa36d84` uses image tag `0.56.0`. Set `EVE_SANDBOX_IMAGE_TAG` to replace the version-derived tag for these default images. An explicit `image` passed to `docker()`, `microsandbox()`, or `vercel()` takes precedence. A snapshot `source` on `vercel()` takes precedence over its `image` because Vercel Sandbox treats them as mutually exclusive.
On every backend, authored commands run as the non-root `vercel-sandbox` user through a non-interactive `bash -lc` login shell. `/workspace` and `$HOME` are writable, `$HOME/.local/bin` is on `PATH` for user-scoped executables, and system paths such as `/usr/local` stay root-owned. Use passwordless `sudo` when setup genuinely needs system-wide changes; `sudo` resets the environment, so pass through variables like `NPM_CONFIG_PREFIX` explicitly if a privileged step depends on them.
@@ -188,11 +188,11 @@ export default defineSandbox({
### Docker
-`docker()` drives the Docker CLI directly. By default, it uses the `ghcr.io/vercel/eve` image tag matching the installed eve version. eve creates `/workspace` and verifies Bash during framework setup, before authored bootstrap code runs. Configure it through `docker({ image, env, pullPolicy, networkPolicy })`, and install authored runtime tools in sandbox bootstrap or provide them through a custom image. Templates are committed as local Docker images and reused across sessions when the sandbox source, seed files, `revalidationKey`, and Docker backend options still match. Sessions run as long-lived containers whose filesystems persist `/workspace` changes across turns for the same durable session. `eve dev` prunes stale template images in the background.
+`docker()` drives the Docker CLI directly. By default, it uses the `ghcr.io/vercel/eve` image tag matching the installed eve version without build metadata. eve creates `/workspace` and verifies Bash during framework setup, before authored bootstrap code runs. Configure it through `docker({ image, env, pullPolicy, networkPolicy })`, and install authored runtime tools in sandbox bootstrap or provide them through a custom image. Templates are committed as local Docker images and reused across sessions when the sandbox source, seed files, `revalidationKey`, and Docker backend options still match. Sessions run as long-lived containers whose filesystems persist `/workspace` changes across turns for the same durable session. `eve dev` prunes stale template images in the background.
### microsandbox
-`microsandbox()` runs each sandbox in a lightweight local VM with snapshot-backed templates, a `vercel-sandbox` user, and a firewall capable of domain-level network policies and credential brokering. It is the closest local match to hosted Vercel Sandbox. By default, it uses the `ghcr.io/vercel/eve` image tag matching the installed eve version. During framework setup, before authored bootstrap code runs, eve verifies Bash and creates `/workspace` and the sandbox user. Install authored runtime tools in sandbox bootstrap or provide them through a custom image. Supported hosts are macOS on Apple Silicon, or Linux (glibc) with KVM. The `microsandbox` npm package and its VM runtime are not bundled with eve, so `eve dev` installs both automatically when missing (disable with `setup: { autoInstall: false }`); production processes fail with actionable install errors instead.
+`microsandbox()` runs each sandbox in a lightweight local VM with snapshot-backed templates, a `vercel-sandbox` user, and a firewall capable of domain-level network policies and credential brokering. It is the closest local match to hosted Vercel Sandbox. By default, it uses the `ghcr.io/vercel/eve` image tag matching the installed eve version without build metadata. During framework setup, before authored bootstrap code runs, eve verifies Bash and creates `/workspace` and the sandbox user. Install authored runtime tools in sandbox bootstrap or provide them through a custom image. Supported hosts are macOS on Apple Silicon, or Linux (glibc) with KVM. The `microsandbox` npm package and its VM runtime are not bundled with eve, so `eve dev` installs both automatically when missing (disable with `setup: { autoInstall: false }`); production processes fail with actionable install errors instead.
### just-bash
diff --git a/e2e/fixtures/agent-basic-runtime/evals/runtime/first-chat.eval.ts b/e2e/fixtures/agent-basic-runtime/evals/runtime/first-chat.eval.ts
new file mode 100644
index 000000000..82a1427d0
--- /dev/null
+++ b/e2e/fixtures/agent-basic-runtime/evals/runtime/first-chat.eval.ts
@@ -0,0 +1,28 @@
+import { defineEval } from "eve/evals";
+import { equals } from "eve/evals/expect";
+
+export default defineEval({
+ description: "A fresh session streams its first answer without an onboarding interview.",
+ async test(t) {
+ const turn = await t.send(
+ 'Alice is starting her first chat. Reply with "Ready to chat, Alice." without calling tools.',
+ );
+ t.succeeded();
+ t.usedNoTools();
+ t.messageIncludes("Ready to chat, Alice.");
+ await t.require(
+ turn.events.some((event) => event.type === "message.appended"),
+ equals(true),
+ );
+ await t.require(
+ turn.events.some((event) => event.type === "message.completed"),
+ equals(true),
+ );
+ await t.require(
+ turn.events.some(
+ (event) => event.type === "authorization.required" || event.type === "input.requested",
+ ),
+ equals(false),
+ );
+ },
+});
diff --git a/packages/eve/package.json b/packages/eve/package.json
index 312a83d01..624233f9e 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -211,6 +211,11 @@
"eve-source": "./dist/src/public/workflow-modules.d.ts",
"types": "./dist/src/public/workflow-modules.d.ts"
},
+ "./models/anthropic": {
+ "types": "./dist/src/public/models/anthropic/index.d.ts",
+ "import": "./dist/src/public/models/anthropic/index.js",
+ "default": "./dist/src/public/models/anthropic/index.js"
+ },
"./models/openai": {
"types": "./dist/src/public/models/openai/index.d.ts",
"import": "./dist/src/public/models/openai/index.js",
diff --git a/packages/eve/src/cli/commands/init-repl.integration.test.ts b/packages/eve/src/cli/commands/init-repl.integration.test.ts
deleted file mode 100644
index ae38d0dde..000000000
--- a/packages/eve/src/cli/commands/init-repl.integration.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import { isCodingAgentReplAvailable, resolveCodingAgentRepl } from "./init-repl.js";
-
-let temporaryDirectory: string | undefined;
-
-afterEach(async () => {
- vi.unstubAllEnvs();
- if (temporaryDirectory !== undefined) {
- await rm(temporaryDirectory, { force: true, recursive: true });
- temporaryDirectory = undefined;
- }
-});
-
-describe("isCodingAgentReplAvailable", () => {
- it("finds an executable coding-agent REPL on PATH", async () => {
- temporaryDirectory = await mkdtemp(join(tmpdir(), "eve-init-repl-"));
- const executableName = process.platform === "win32" ? "claude.EXE" : "claude";
- const executablePath = join(temporaryDirectory, executableName);
- await writeFile(executablePath, "", "utf8");
- await chmod(executablePath, 0o755);
- vi.stubEnv("PATH", temporaryDirectory);
- if (process.platform === "win32") vi.stubEnv("PATHEXT", ".EXE");
-
- await expect(isCodingAgentReplAvailable("claude")).resolves.toBe(true);
- await expect(isCodingAgentReplAvailable("codex")).resolves.toBe(false);
-
- // The resolver returns the full path so the spawn can run shell-free.
- await expect(resolveCodingAgentRepl("claude")).resolves.toBe(executablePath);
- await expect(resolveCodingAgentRepl("codex")).resolves.toBeNull();
- });
-});
diff --git a/packages/eve/src/cli/commands/init-repl.test.ts b/packages/eve/src/cli/commands/init-repl.test.ts
deleted file mode 100644
index 345df4279..000000000
--- a/packages/eve/src/cli/commands/init-repl.test.ts
+++ /dev/null
@@ -1,230 +0,0 @@
-import { ChildProcess, spawn } from "node:child_process";
-
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { createFakePrompter, type FakePrompterConfig } from "#internal/testing/fake-prompter.js";
-
-import {
- replSpawnPlan,
- selectInitHandoff,
- spawnCodingAgentRepl,
- type CodingAgentRepl,
- type InitReplDependencies,
-} from "./init-repl.js";
-
-vi.mock("node:child_process", async (importOriginal) => ({
- ...(await importOriginal<typeof import("node:child_process")>()),
- spawn: vi.fn(),
-}));
-
-const mockedSpawn = vi.mocked(spawn);
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-afterEach(() => {
- vi.unstubAllEnvs();
-});
-
-function dependencies(
- input: {
- available?: readonly string[];
- interactive?: boolean;
- onSelect?: FakePrompterConfig["single"];
- } = {},
-): InitReplDependencies {
- const fake = createFakePrompter({ single: input.onSelect });
- return {
- createPrompter: vi.fn(() => fake.prompter),
- hasInteractiveTerminal: vi.fn(() => input.interactive ?? true),
- isCodingAgentReplAvailable: vi.fn(
- async (command) => input.available?.includes(command) ?? false,
- ),
- };
-}
-
-describe("selectInitHandoff", () => {
- it("keeps non-interactive sessions on the direct eve dev path", async () => {
- const deps = dependencies({ interactive: false, available: ["claude"] });
-
- await expect(selectInitHandoff({ deps, agentName: "weather-bot" })).resolves.toBe("eve-dev");
- expect(deps.isCodingAgentReplAvailable).not.toHaveBeenCalled();
- expect(deps.createPrompter).not.toHaveBeenCalled();
- });
-
- it("keeps the direct eve dev path when no supported REPL is installed", async () => {
- const deps = dependencies();
-
- await expect(selectInitHandoff({ deps, agentName: "weather-bot" })).resolves.toBe("eve-dev");
- expect(
- vi.mocked(deps.isCodingAgentReplAvailable).mock.calls.map(([command]) => command),
- ).toEqual(["claude", "codex", "cursor-agent", "droid", "gemini", "opencode", "pi"]);
- expect(deps.createPrompter).not.toHaveBeenCalled();
- });
-
- it("starts every availability check before waiting for one to finish", async () => {
- let releaseAvailabilityChecks: () => void;
- const availabilityGate = new Promise<void>((resolve) => {
- releaseAvailabilityChecks = resolve;
- });
- const isCodingAgentReplAvailable = vi.fn(async (_command: CodingAgentRepl) => {
- await availabilityGate;
- return false;
- });
- const deps: InitReplDependencies = {
- createPrompter: vi.fn(),
- hasInteractiveTerminal: vi.fn(() => true),
- isCodingAgentReplAvailable,
- };
-
- const handoff = selectInitHandoff({ deps, agentName: "weather-bot" });
- const checksStartedBeforeAnyFinished = isCodingAgentReplAvailable.mock.calls.length;
- releaseAvailabilityChecks!();
-
- await expect(handoff).resolves.toBe("eve-dev");
- expect(checksStartedBeforeAnyFinished).toBe(7);
- });
-
- it("offers only available REPLs and preserves eve dev as the default", async () => {
- const deps = dependencies({
- available: ["codex"],
- onSelect: (options) => {
- expect(options.message).toBe("How would you like to continue?");
- expect(options.initialValue).toBe("eve-dev");
- expect(options.options.map((option) => option.value)).toEqual(["eve-dev", "codex", "exit"]);
- expect(options.options.map((option) => option.focusHint)).toEqual([
- "talk to 'weather-bot' in your terminal",
- "build 'weather-bot' using Codex",
- "return to your terminal",
- ]);
- // Hints are focus-only, like the dev TUI lists, so no always-on hint is set.
- expect(options.options.every((option) => option.hint === undefined)).toBe(true);
- return "codex";
- },
- });
-
- await expect(selectInitHandoff({ deps, agentName: "weather-bot" })).resolves.toBe("codex");
- });
-});
-
-describe("replSpawnPlan", () => {
- // A prompt with the newline and cmd metacharacters that break a shell launch.
- const PROMPT = "line one\nline two (with parens) & a pipe |";
-
- // Each REPL seeds its prompt differently once spawned shell-free: most take a
- // bare positional prompt, Gemini needs `-i`, opencode needs `--prompt`.
- it.each([
- { command: "claude", args: [PROMPT] },
- { command: "codex", args: [PROMPT] },
- { command: "cursor-agent", args: [PROMPT] },
- { command: "droid", args: [PROMPT] },
- { command: "gemini", args: ["-i", PROMPT] },
- { command: "opencode", args: ["--prompt", PROMPT] },
- { command: "pi", args: [PROMPT] },
- ] as const)("seeds $command verbatim when spawned shell-free", ({ command, args }) => {
- expect(replSpawnPlan(command, "/usr/local/bin/agent", PROMPT, "linux")).toEqual({
- file: "/usr/local/bin/agent",
- args,
- shell: false,
- seeded: true,
- });
- });
-
- it("spawns a resolved Windows .exe shell-free, prompt intact", () => {
- expect(replSpawnPlan("claude", "C:\\bin\\claude.EXE", PROMPT, "win32")).toEqual({
- file: "C:\\bin\\claude.EXE",
- args: [PROMPT],
- shell: false,
- seeded: true,
- });
- });
-
- it("launches a Windows .cmd shim bare, leaving the prompt unseeded", () => {
- expect(replSpawnPlan("claude", "C:\\bin\\claude.CMD", PROMPT, "win32")).toEqual({
- file: "claude",
- args: [],
- shell: true,
- seeded: false,
- });
- });
-
- it("launches bare when the command does not resolve", () => {
- expect(replSpawnPlan("claude", null, PROMPT, "linux")).toEqual({
- file: "claude",
- args: [],
- shell: false,
- seeded: false,
- });
- expect(replSpawnPlan("claude", null, PROMPT, "win32").shell).toBe(true);
- });
-});
-
-describe("spawnCodingAgentRepl", () => {
- const PROMPT = "Help the user build their eve agent.";
-
- async function awaitSpawn(): Promise<void> {
- await vi.waitFor(() => expect(mockedSpawn).toHaveBeenCalled());
- }
-
- it("spawns the resolved executable shell-free and resolves true on clean exit", async () => {
- const child = new ChildProcess();
- mockedSpawn.mockReturnValue(child);
-
- const result = spawnCodingAgentRepl({
- command: "claude",
- cwd: "/tmp/triage-bot",
- prompt: PROMPT,
- resolvePath: async () => "/usr/local/bin/claude",
- });
- await awaitSpawn();
- child.emit("close", 0);
-
- await expect(result).resolves.toBe(true);
- expect(mockedSpawn).toHaveBeenCalledWith(
- "/usr/local/bin/claude",
- [PROMPT],
- expect.objectContaining({ cwd: "/tmp/triage-bot", shell: false, stdio: "inherit" }),
- );
- });
-
- it("surfaces the prompt and launches bare when the command cannot be seeded", async () => {
- const child = new ChildProcess();
- mockedSpawn.mockReturnValue(child);
- const onPromptUnseeded = vi.fn();
-
- const result = spawnCodingAgentRepl({
- command: "claude",
- cwd: "/tmp/triage-bot",
- prompt: PROMPT,
- resolvePath: async () => null,
- onPromptUnseeded,
- });
- await awaitSpawn();
- child.emit("close", 0);
-
- await expect(result).resolves.toBe(true);
- expect(onPromptUnseeded).toHaveBeenCalledWith(PROMPT);
- expect(mockedSpawn).toHaveBeenCalledWith(
- "claude",
- [],
- expect.objectContaining({ cwd: "/tmp/triage-bot", stdio: "inherit" }),
- );
- });
-
- it("resolves false when the spawn errors", async () => {
- const child = new ChildProcess();
- mockedSpawn.mockReturnValue(child);
-
- const result = spawnCodingAgentRepl({
- command: "claude",
- cwd: "/tmp/triage-bot",
- prompt: PROMPT,
- resolvePath: async () => "/usr/local/bin/claude",
- });
- await awaitSpawn();
- child.emit("error", new Error("spawn failed"));
-
- await expect(result).resolves.toBe(false);
- });
-});
diff --git a/packages/eve/src/cli/commands/init-repl.ts b/packages/eve/src/cli/commands/init-repl.ts
deleted file mode 100644
index 0f32a6724..000000000
--- a/packages/eve/src/cli/commands/init-repl.ts
+++ /dev/null
@@ -1,218 +0,0 @@
-import { spawn } from "node:child_process";
-import { constants } from "node:fs";
-import { access, stat } from "node:fs/promises";
-import { delimiter, extname, join } from "node:path";
-
-import { createPrompter, type Prompter, type SelectOption } from "#setup/prompter.js";
-
-import { hasInteractiveTerminal } from "./preconditions.js";
-
-// `promptArgs` is each harness's documented way to open its interactive REPL
-// seeded with an initial prompt. Most take a bare positional argument; Gemini
-// treats a positional as a one-shot query and needs `-i`, and opencode treats a
-// positional as a project path and needs `--prompt`.
-const positional = (prompt: string) => [prompt];
-const CODING_AGENT_REPLS = [
- { command: "claude", label: "Claude Code", promptArgs: positional },
- { command: "codex", label: "Codex", promptArgs: positional },
- { command: "cursor-agent", label: "Cursor", promptArgs: positional },
- { command: "droid", label: "Droid", promptArgs: positional },
- { command: "gemini", label: "Gemini CLI", promptArgs: (prompt: string) => ["-i", prompt] },
- { command: "opencode", label: "opencode", promptArgs: (prompt: string) => ["--prompt", prompt] },
- { command: "pi", label: "Pi", promptArgs: positional },
-] as const;
-
-// Node exposes no PATH/PATHEXT-aware executable resolver, so availability is
-// probed by hand. `executableNames` reads the OS's own `PATHEXT` first; this
-// list is only the fallback for the rare shell that leaves it unset.
-const WINDOWS_EXECUTABLE_EXTENSIONS = [".COM", ".EXE", ".BAT", ".CMD"];
-
-type CodingAgentReplDefinition = (typeof CODING_AGENT_REPLS)[number];
-
-/** A coding-agent REPL that can take over the terminal after `eve init`. */
-export type CodingAgentRepl = CodingAgentReplDefinition["command"];
-
-/** The one post-init continuation point for a human terminal session. */
-export type InitHandoff = "exit" | "eve-dev" | CodingAgentRepl;
-
-export interface InitReplDependencies {
- createPrompter(): Prompter;
- hasInteractiveTerminal(): boolean;
- isCodingAgentReplAvailable(command: CodingAgentRepl): Promise<boolean>;
-}
-
-const defaultDependencies: InitReplDependencies = {
- createPrompter,
- hasInteractiveTerminal,
- isCodingAgentReplAvailable,
-};
-
-function executableNames(command: string): readonly string[] {
- if (process.platform !== "win32") return [command];
-
- const extensions = process.env.PATHEXT?.split(";").filter(Boolean);
- return (extensions && extensions.length > 0 ? extensions : WINDOWS_EXECUTABLE_EXTENSIONS).map(
- (extension) => `${command}${extension}`,
- );
-}
-
-async function isExecutable(filePath: string): Promise<boolean> {
- try {
- if (!(await stat(filePath)).isFile()) return false;
- await access(filePath, constants.X_OK);
- return true;
- } catch {
- return false;
- }
-}
-
-/** The full path of the named REPL's executable on `PATH`, or null if absent. */
-export async function resolveCodingAgentRepl(command: CodingAgentRepl): Promise<string | null> {
- const path = process.env.PATH;
- if (path === undefined || path.length === 0) return null;
-
- for (const directory of path.split(delimiter)) {
- if (directory.length === 0) continue;
- for (const executableName of executableNames(command)) {
- const candidate = join(directory, executableName);
- if (await isExecutable(candidate)) return candidate;
- }
- }
- return null;
-}
-
-/** True when the named REPL resolves to an executable on the current `PATH`. */
-export async function isCodingAgentReplAvailable(command: CodingAgentRepl): Promise<boolean> {
- return (await resolveCodingAgentRepl(command)) !== null;
-}
-
-// `focusHint` (not `hint`) so the menu reads like the dev TUI lists: only the
-// highlighted row shows its hint, rather than every row at once.
-function handoffOptions(
- availableRepls: readonly CodingAgentReplDefinition[],
- agentName: string,
-): SelectOption<InitHandoff>[] {
- return [
- {
- value: "eve-dev",
- label: "Start eve dev",
- focusHint: `talk to '${agentName}' in your terminal`,
- },
- ...availableRepls.map((repl) => ({
- value: repl.command,
- label: `Open ${repl.label}`,
- focusHint: `build '${agentName}' using ${repl.label}`,
- })),
- {
- value: "exit",
- label: "Exit",
- focusHint: "return to your terminal",
- },
- ];
-}
-
-/**
- * Offers any locally installed coding-agent REPLs immediately before the
- * existing `eve dev` handoff. Non-interactive sessions, and systems with none
- * of them on `PATH`, keep the prior direct-to-dev behavior.
- */
-export async function selectInitHandoff(input: {
- agentName: string;
- deps?: Partial<InitReplDependencies>;
-}): Promise<InitHandoff> {
- const dependencies: InitReplDependencies = { ...defaultDependencies, ...input.deps };
- if (!dependencies.hasInteractiveTerminal()) return "eve-dev";
-
- const availability = await Promise.all(
- CODING_AGENT_REPLS.map(({ command }) => dependencies.isCodingAgentReplAvailable(command)),
- );
- const availableRepls = CODING_AGENT_REPLS.filter((_, index) => availability[index]);
- if (availableRepls.length === 0) return "eve-dev";
-
- return dependencies.createPrompter().select<InitHandoff>({
- message: "How would you like to continue?",
- options: handoffOptions(availableRepls, input.agentName),
- initialValue: "eve-dev",
- });
-}
-
-function codingAgentRepl(command: CodingAgentRepl): CodingAgentReplDefinition {
- const definition = CODING_AGENT_REPLS.find((repl) => repl.command === command);
- if (definition === undefined) {
- throw new Error(`Unsupported coding-agent REPL "${command}".`);
- }
- return definition;
-}
-
-// Only PE executables (.exe/.com) can be launched without a shell on Windows;
-// .cmd/.bat shims must go through cmd.exe. Everything on POSIX runs directly.
-function isDirectlySpawnable(resolvedPath: string, platform: NodeJS.Platform): boolean {
- if (platform !== "win32") return true;
- const extension = extname(resolvedPath).toLowerCase();
- return extension === ".exe" || extension === ".com";
-}
-
-interface ReplSpawnPlan {
- file: string;
- args: readonly string[];
- shell: boolean;
- /** False means the prompt is not in argv and the caller must surface it. */
- seeded: boolean;
-}
-
-/**
- * Decides how to launch a REPL from its resolved executable path. A directly
- * spawnable executable runs without a shell, so the multi-line prompt passes
- * through argv verbatim. A `.cmd`/`.bat` shim (or an unresolved command) can
- * only run via cmd.exe, which cannot carry the prompt's newlines or
- * metacharacters in an argument, so it launches the bare REPL and reports the
- * prompt as unseeded.
- */
-export function replSpawnPlan(
- command: CodingAgentRepl,
- resolvedPath: string | null,
- prompt: string,
- platform: NodeJS.Platform = process.platform,
-): ReplSpawnPlan {
- if (resolvedPath !== null && isDirectlySpawnable(resolvedPath, platform)) {
- return {
- file: resolvedPath,
- args: codingAgentRepl(command).promptArgs(prompt),
- shell: false,
- seeded: true,
- };
- }
- return { file: command, args: [], shell: platform === "win32", seeded: false };
-}
-
-/** Starts the selected coding-agent REPL in the newly initialized project. */
-export async function spawnCodingAgentRepl(input: {
- command: CodingAgentRepl;
- cwd: string;
- prompt: string;
- /** Surfaces the prompt when it could not be seeded into the REPL's argv. */
- onPromptUnseeded?: (prompt: string) => void;
- resolvePath?: (command: CodingAgentRepl) => Promise<string | null>;
-}): Promise<boolean> {
- const resolvePath = input.resolvePath ?? resolveCodingAgentRepl;
- const plan = replSpawnPlan(input.command, await resolvePath(input.command), input.prompt);
- if (!plan.seeded) {
- input.onPromptUnseeded?.(input.prompt);
- }
- return new Promise((resolve) => {
- const child = spawn(plan.file, plan.args, {
- cwd: input.cwd,
- shell: plan.shell,
- stdio: "inherit",
- });
- let settled = false;
- const settle = (ok: boolean) => {
- if (settled) return;
- settled = true;
- resolve(ok);
- };
-
- child.once("error", () => settle(false));
- child.once("close", (code) => settle(code === 0));
- });
-}
diff --git a/packages/eve/src/cli/commands/init-self-modification.ts b/packages/eve/src/cli/commands/init-self-modification.ts
deleted file mode 100644
index 686a2b9e5..000000000
--- a/packages/eve/src/cli/commands/init-self-modification.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { createPrompter, type Prompter } from "#setup/prompter.js";
-
-import { hasInteractiveTerminal } from "./preconditions.js";
-
-export interface InitSelfModificationDependencies {
- createPrompter(): Prompter;
- hasInteractiveTerminal(): boolean;
-}
-
-const defaultDependencies: InitSelfModificationDependencies = {
- createPrompter,
- hasInteractiveTerminal,
-};
-
-/** Offers eve's self-modification subagent before the external coding-agent handoff. */
-export async function selectInitSelfModification(
- dependencies: InitSelfModificationDependencies = defaultDependencies,
-): Promise<boolean> {
- if (!dependencies.hasInteractiveTerminal()) return false;
-
- return dependencies.createPrompter().select({
- message: "Enable local self-modification?",
- description:
- "Self-modification adds a subagent that can edit your agent's source during local development.",
- options: [
- {
- value: true,
- label: "Enable self-modification",
- focusHint: "let your eve agent make source changes in dev",
- },
- {
- value: false,
- label: "Not now",
- focusHint: "continue with eve dev or an external coding agent",
- },
- ],
- initialValue: false,
- });
-}
diff --git a/packages/eve/src/cli/commands/init.integration.test.ts b/packages/eve/src/cli/commands/init.integration.test.ts
index 2e83cb9c9..84be67fe1 100644
--- a/packages/eve/src/cli/commands/init.integration.test.ts
+++ b/packages/eve/src/cli/commands/init.integration.test.ts
@@ -20,10 +20,8 @@ import {
type ScaffoldBaseProjectOptions,
} from "#setup/scaffold/index.js";
import { pathExists } from "#setup/path-exists.js";
-import { WizardCancelledError } from "#setup/step.js";
import type { GitInitResult } from "./init-git.js";
-import { initAgentReplPrompt } from "./agent-instructions.js";
import {
EVE_INIT_PACKAGE_SPEC_ENV,
runInitCommand,
@@ -71,14 +69,6 @@ function dependencies(
runPackageManagerInstall: ReturnType<
typeof vi.fn<InitCommandDependencies["runPackageManagerInstall"]>
>;
- installSelfModification: ReturnType<
- typeof vi.fn<InitCommandDependencies["installSelfModification"]>
- >;
- selectInitHandoff: ReturnType<typeof vi.fn<InitCommandDependencies["selectInitHandoff"]>>;
- selectInitSelfModification: ReturnType<
- typeof vi.fn<InitCommandDependencies["selectInitSelfModification"]>
- >;
- spawnCodingAgentRepl: ReturnType<typeof vi.fn<InitCommandDependencies["spawnCodingAgentRepl"]>>;
spawnPackageManager: ReturnType<typeof vi.fn<InitCommandDependencies["spawnPackageManager"]>>;
tryInitializeGit: ReturnType<typeof vi.fn<InitCommandDependencies["tryInitializeGit"]>>;
validateModelSlug: ReturnType<typeof vi.fn<InitCommandDependencies["validateModelSlug"]>>;
@@ -112,10 +102,7 @@ function dependencies(
webPackageVersions: { ...WEB_VERSIONS, ...options.webPackageVersions },
}),
runPackageManagerInstall: vi.fn(async () => packageInstallResult()),
- installSelfModification: vi.fn(async () => {}),
- selectInitHandoff: vi.fn(async () => "eve-dev"),
- selectInitSelfModification: vi.fn(async () => false),
- spawnCodingAgentRepl: vi.fn(async () => true),
+ hasInteractiveTerminal: () => true,
spawnPackageManager: vi.fn(async () => packageProcessResult()),
tryInitializeGit: vi.fn(async () => gitResult),
validateModelSlug: vi.fn(async () => null),
@@ -144,6 +131,14 @@ afterEach(() => {
});
describe("runInitCommand", () => {
+ it("returns after scaffolding without opening the TUI in a noninteractive terminal", async () => {
+ const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-headless-"));
+ const deps = { ...dependencies(), hasInteractiveTerminal: () => false };
+ await runInitCommand(logger(), parentDirectory, "agent", {}, deps);
+ expect(deps.spawnPackageManager).not.toHaveBeenCalled();
+ expect(deps.runPackageManagerInstall).toHaveBeenCalled();
+ });
+
it("creates an agent workspace from comma-separated names", async () => {
const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-agents-"));
const output = logger();
@@ -170,7 +165,6 @@ describe("runInitCommand", () => {
await expect(readFile(join(projectRoot, "tsconfig.json"), "utf8")).resolves.toContain(
'"agents/**/*.ts"',
);
- expect(deps.selectInitHandoff).toHaveBeenCalledWith({ agentName: "operations" });
expect(deps.spawnPackageManager).toHaveBeenCalledWith("pnpm", projectRoot, [
"exec",
"eve",
@@ -365,30 +359,6 @@ describe("runInitCommand", () => {
expect(deps.runPackageManagerInstall).not.toHaveBeenCalled();
});
- it("installs self-modification before Git initialization and skips the coding-agent handoff", async () => {
- const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-self-modification-"));
- const output = logger();
- const deps = dependencies();
- deps.selectInitSelfModification.mockResolvedValue(true);
-
- await runInitCommand(output, parentDirectory, "my-agent", {}, deps);
-
- const projectPath = join(parentDirectory, "my-agent");
- expect(deps.installSelfModification).toHaveBeenCalledWith(projectPath);
- expect(deps.installSelfModification.mock.invocationCallOrder[0]).toBeLessThan(
- deps.tryInitializeGit.mock.invocationCallOrder[0]!,
- );
- expect(deps.selectInitHandoff).not.toHaveBeenCalled();
- expect(deps.spawnCodingAgentRepl).not.toHaveBeenCalled();
- expect(deps.spawnPackageManager).toHaveBeenCalledWith("pnpm", projectPath, [
- "exec",
- "eve",
- "dev",
- "--onboard",
- ]);
- expect(stripAnsi(output.messages.join("\n"))).toContain("✓ Enabled self-modification");
- });
-
it("does not offer self-modification when init was launched by a coding agent", async () => {
const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-agent-launched-selfmod-"));
const output = logger();
@@ -396,71 +366,6 @@ describe("runInitCommand", () => {
deps.isCodingAgentLaunch.mockResolvedValue(true);
await runInitCommand(output, parentDirectory, "my-agent", {}, deps);
-
- expect(deps.selectInitSelfModification).not.toHaveBeenCalled();
- expect(deps.installSelfModification).not.toHaveBeenCalled();
- });
-
- it("opens the selected coding-agent REPL instead of starting eve dev", async () => {
- const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-repl-handoff-"));
- const output = logger();
- const deps = dependencies();
- deps.selectInitHandoff.mockResolvedValue("codex");
-
- await runInitCommand(output, parentDirectory, "my-agent", {}, deps);
-
- const projectPath = join(parentDirectory, "my-agent");
- expect(deps.spawnCodingAgentRepl).toHaveBeenCalledWith(
- expect.objectContaining({
- command: "codex",
- cwd: projectPath,
- prompt: expect.stringContaining("pnpm exec eve dev --no-ui"),
- }),
- );
- const prompt = deps.spawnCodingAgentRepl.mock.calls[0]?.[0].prompt;
- expect(prompt).toBe(
- initAgentReplPrompt({
- devCommand: "pnpm exec eve dev",
- }),
- );
- expect(prompt).toContain("What should the agent do?");
- expect(prompt).toContain("HMR development server");
- expect(prompt).not.toContain(projectPath);
- expect(prompt).not.toContain("{{");
- expect(deps.spawnPackageManager).not.toHaveBeenCalled();
- expect(output.messages.at(-1)).toContain("$ codex");
- });
-
- it("keeps a completed init successful when its optional handoff is cancelled", async () => {
- const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-repl-cancelled-"));
- const output = logger();
- const deps = dependencies();
- deps.selectInitHandoff.mockRejectedValue(new WizardCancelledError());
-
- await expect(
- runInitCommand(output, parentDirectory, "my-agent", {}, deps),
- ).resolves.toBeUndefined();
-
- const projectPath = join(parentDirectory, "my-agent");
- await expect(pathExists(join(projectPath, "agent/agent.ts"))).resolves.toBe(true);
- expect(deps.spawnCodingAgentRepl).not.toHaveBeenCalled();
- expect(deps.spawnPackageManager).not.toHaveBeenCalled();
- expect(output.errors).toEqual([]);
- });
-
- it("exits after init without starting a handoff when selected", async () => {
- const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-exit-handoff-"));
- const output = logger();
- const deps = dependencies();
- deps.selectInitHandoff.mockResolvedValue("exit");
-
- await runInitCommand(output, parentDirectory, "my-agent", {}, deps);
-
- const projectPath = join(parentDirectory, "my-agent");
- await expect(pathExists(join(projectPath, "agent/agent.ts"))).resolves.toBe(true);
- expect(deps.spawnCodingAgentRepl).not.toHaveBeenCalled();
- expect(deps.spawnPackageManager).not.toHaveBeenCalled();
- expect(output.errors).toEqual([]);
});
it("uses an explicit init package spec for fresh project scaffolds", async () => {
@@ -1305,8 +1210,6 @@ describe("runInitCommand", () => {
expect.anything(),
);
expect(deps.tryInitializeGit).toHaveBeenCalledWith(parentDirectory);
- expect(deps.selectInitHandoff).not.toHaveBeenCalled();
- expect(deps.spawnCodingAgentRepl).not.toHaveBeenCalled();
expect(deps.spawnPackageManager).not.toHaveBeenCalled();
expect(output.messages.join("\n")).toContain("Created an eve agent in");
});
@@ -1331,8 +1234,6 @@ describe("runInitCommand", () => {
expect(deps.tryInitializeGit).toHaveBeenCalledWith(projectPath);
// The dev server is handed off as text, never spawned — the dev TUI would
// wedge the launching agent. The handoff's content is the unit test's job.
- expect(deps.selectInitHandoff).not.toHaveBeenCalled();
- expect(deps.spawnCodingAgentRepl).not.toHaveBeenCalled();
expect(deps.spawnPackageManager).not.toHaveBeenCalled();
const messages = stripAnsi(output.messages.join("\n"));
expect(messages).toContain(`✓ Model ${DEFAULT_AGENT_MODEL_ID} (eve default)`);
diff --git a/packages/eve/src/cli/commands/init.ts b/packages/eve/src/cli/commands/init.ts
index f9ef3bf18..925775cc0 100644
--- a/packages/eve/src/cli/commands/init.ts
+++ b/packages/eve/src/cli/commands/init.ts
@@ -43,7 +43,7 @@ import {
type EvePackageContract,
} from "#setup/scaffold/create/project.js";
-import { initAgentDevHandoff, initAgentReplPrompt } from "./agent-instructions.js";
+import { initAgentDevHandoff } from "./agent-instructions.js";
import {
installProgressDetail,
INSTALL_OUTPUT_FALLBACK_LINES,
@@ -66,8 +66,7 @@ import {
type PreparedInitProject,
} from "./init-project.js";
import { cleanupFreshInitTarget, workspaceFailureNote } from "./init-recovery.js";
-import { selectInitSelfModification } from "./init-self-modification.js";
-import { selectInitHandoff, spawnCodingAgentRepl, type InitHandoff } from "./init-repl.js";
+import { hasInteractiveTerminal } from "./preconditions.js";
import { resolveInitTarget } from "./init-target.js";
export type { InitCliLogger, InitCommandOptions } from "./init-agent-workspace.js";
@@ -81,10 +80,7 @@ export interface InitCommandDependencies {
now: () => number;
runPackageManagerInstall: typeof runPackageManagerInstall;
scaffoldBaseProject: typeof scaffoldBaseProject;
- selectInitHandoff: typeof selectInitHandoff;
- selectInitSelfModification: typeof selectInitSelfModification;
- installSelfModification(appRoot: string): Promise<void>;
- spawnCodingAgentRepl: typeof spawnCodingAgentRepl;
+ hasInteractiveTerminal: typeof hasInteractiveTerminal;
spawnPackageManager: typeof spawnPackageManager;
tryInitializeGit: typeof tryInitializeGit;
validateModelSlug: typeof validateModelSlug;
@@ -99,13 +95,7 @@ const defaultDependencies: InitCommandDependencies = {
now: () => performance.now(),
runPackageManagerInstall,
scaffoldBaseProject,
- selectInitHandoff,
- selectInitSelfModification,
- installSelfModification: async (appRoot) => {
- const { installRegistryItem } = await import("./registry.js");
- await installRegistryItem(appRoot, "eve/self-modification", { silent: true, skipSetup: true });
- },
- spawnCodingAgentRepl,
+ hasInteractiveTerminal,
spawnPackageManager,
tryInitializeGit,
validateModelSlug,
@@ -300,10 +290,7 @@ async function runInitSteps(input: {
const debug = isLogLevelEnabled("debug");
const initTarget = await resolveInitTarget({ parentDirectory, target });
const evePackage = resolveInitEvePackageOverride();
- const selfModificationEnabled =
- !agentLaunched && options.agents === undefined
- ? await dependencies.selectInitSelfModification()
- : false;
+ const selfModificationEnabled = false;
let progress = startCliLiveRow(logger);
let activeInitStep: EveCliSetupStep = "scaffold";
@@ -475,13 +462,6 @@ async function runInitSteps(input: {
}
initLog.debug("dependencies installed", { ms: installElapsedMs });
- if (selfModificationEnabled) {
- activeInitStep = "registry_install";
- trackStep?.(activeInitStep);
- progress.update("Enabling self-modification");
- await dependencies.installSelfModification(project.projectPath);
- }
-
if (project.kind === "created") {
activeInitStep = "initialize_git";
trackStep?.(activeInitStep);
@@ -615,37 +595,8 @@ export async function runInitCommand(
return;
}
- let handoff: InitHandoff;
- if (result.selfModificationEnabled) {
- handoff = "eve-dev";
- } else {
- try {
- handoff = await dependencies.selectInitHandoff({ agentName: basename(result.projectPath) });
- } catch (error) {
- if (error instanceof WizardCancelledError) return;
- throw error;
- }
- }
- if (handoff === "exit") return;
- if (handoff !== "eve-dev") {
- logger.log(pc.dim(`$ ${handoff}`));
- if (
- !(await dependencies.spawnCodingAgentRepl({
- command: handoff,
- cwd: result.projectPath,
- prompt: initAgentReplPrompt({ devCommand: agentDevCommand }),
- // A `.cmd`/`.bat` shim can't take the multi-line prompt on its command
- // line, so print it for the user to paste once the REPL opens.
- onPromptUnseeded: (prompt) => {
- logger.log(
- pc.yellow(`Could not seed ${handoff} automatically. Paste this prompt into it:`),
- );
- logger.log(prompt);
- },
- }))
- ) {
- throw new Error(`Coding-agent REPL exited unsuccessfully in "${result.projectPath}".`);
- }
+ if (!dependencies.hasInteractiveTerminal()) {
+ logger.log(agentHandoff);
return;
}
diff --git a/packages/eve/src/cli/commands/registry.test.ts b/packages/eve/src/cli/commands/registry.test.ts
index 23b17635c..40e4b2b35 100644
--- a/packages/eve/src/cli/commands/registry.test.ts
+++ b/packages/eve/src/cli/commands/registry.test.ts
@@ -935,6 +935,7 @@ describe("registry commands", () => {
registry: "https://eve.dev/r/registry.json",
name: "channel/photon-imessage",
title: "Photon iMessage",
+ description: "iMessage through Photon, with guided project and phone setup.",
addCommandArgument: "https://eve.dev/r/channel/photon-imessage.json",
},
{
@@ -949,7 +950,11 @@ describe("registry commands", () => {
await expect(browseRegistryCatalog("/project", { query: "sdk" })).resolves.toMatchObject({
items: [
- { name: "channel/photon-imessage", title: "Photon iMessage" },
+ {
+ name: "channel/photon-imessage",
+ title: "Photon iMessage",
+ description: "iMessage through Photon, with guided project and phone setup.",
+ },
{ name: "extension/ai-sdk-tools", title: "AI SDK Tools" },
],
});
diff --git a/packages/eve/src/cli/dev/environment.ts b/packages/eve/src/cli/dev/environment.ts
index 428da7ec2..94e1cdf75 100644
--- a/packages/eve/src/cli/dev/environment.ts
+++ b/packages/eve/src/cli/dev/environment.ts
@@ -1,10 +1,11 @@
+import { MODEL_CONNECTION_ENV } from "#shared/model-helper.js";
import { readFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { parseEnv } from "node:util";
import { findEveProjectRoot } from "#internal/eve-project-root.js";
import { isObject } from "#shared/guards.js";
-import { readProviderSelectionSync } from "#setup/provider-settings.js";
+import { readProviderSettingsSync } from "#setup/provider-settings.js";
/**
* Development environment files loaded by local CLI commands such as
@@ -71,9 +72,6 @@ export function readDevelopmentEnvironmentHostValues(
getDevelopmentEnvironmentLoader(appRoot).environmentRoot,
);
const hostKeys = new Set(fileValues.keys());
- // Project selection can suppress a shell-only key. Keep that transition in
- // the host fingerprint so the worker that inherited the key is replaced.
- hostKeys.add("AI_GATEWAY_API_KEY");
for (const key of [...hostKeys].sort((left, right) => left.localeCompare(right))) {
values[key] = process.env[key] ?? null;
@@ -102,28 +100,38 @@ function createDevelopmentEnvironmentLoader(
appRoot: string,
environmentRoot: string,
): DevelopmentEnvironmentLoader {
- const protectedValues = new Map(Object.entries(process.env));
- const protectedKeys = new Set(protectedValues.keys());
+ const protectedKeys = new Set(Object.keys(process.env));
const managedValues = new Map<string, string>();
const stageReload = (): DevelopmentEnvironmentReload => {
const previousManagedValues = new Map(managedValues);
const nextValues = readDevelopmentEnvironmentValues(environmentRoot);
- const preferProjectOidc = applyProviderSelection(appRoot, nextValues);
- const affectedKeys = new Set([...managedValues.keys(), ...nextValues.keys()]);
- if (preferProjectOidc) {
- affectedKeys.add("AI_GATEWAY_API_KEY");
- protectedKeys.delete("AI_GATEWAY_API_KEY");
- } else if (protectedValues.has("AI_GATEWAY_API_KEY")) {
- protectedKeys.add("AI_GATEWAY_API_KEY");
- process.env.AI_GATEWAY_API_KEY = protectedValues.get("AI_GATEWAY_API_KEY");
- }
+ const settings = readProviderSettingsSync(appRoot);
+ const affectedKeys = new Set([
+ ...managedValues.keys(),
+ ...nextValues.keys(),
+ MODEL_CONNECTION_ENV,
+ "EVE_MODEL_TEAM",
+ "EVE_MODEL_TEAM_NAME",
+ "EVE_MODEL_KEY_SOURCE",
+ ]);
const previousEnvironment = new Map(
[...affectedKeys].map((key) => [key, process.env[key]] as const),
);
let settled = false;
+ if (settings) process.env[MODEL_CONNECTION_ENV] = settings.selected;
+ else delete process.env[MODEL_CONNECTION_ENV];
+ const keySource = settings?.keySource;
+ if (keySource) process.env.EVE_MODEL_KEY_SOURCE = keySource;
+ else delete process.env.EVE_MODEL_KEY_SOURCE;
+ if (settings?.teamId && settings.teamName) {
+ process.env.EVE_MODEL_TEAM = settings.teamId;
+ process.env.EVE_MODEL_TEAM_NAME = settings.teamName;
+ } else {
+ delete process.env.EVE_MODEL_TEAM;
+ delete process.env.EVE_MODEL_TEAM_NAME;
+ }
- if (preferProjectOidc) delete process.env.AI_GATEWAY_API_KEY;
applyDevelopmentEnvironmentValues({
managedValues,
nextValues,
@@ -163,12 +171,6 @@ function createDevelopmentEnvironmentLoader(
};
}
-function applyProviderSelection(appRoot: string, values: Map<string, string>): boolean {
- if (readProviderSelectionSync(appRoot) !== "ai-gateway-project") return false;
- values.delete("AI_GATEWAY_API_KEY");
- return true;
-}
-
function applyDevelopmentEnvironmentValues(input: {
readonly managedValues: Map<string, string>;
readonly nextValues: ReadonlyMap<string, string>;
diff --git a/packages/eve/src/cli/dev/run-interactive-ui.ts b/packages/eve/src/cli/dev/run-interactive-ui.ts
index bc35d269d..98f869586 100644
--- a/packages/eve/src/cli/dev/run-interactive-ui.ts
+++ b/packages/eve/src/cli/dev/run-interactive-ui.ts
@@ -67,7 +67,7 @@ export async function runInteractiveDevelopmentUi(input: {
serverUrl: input.server.serverUrl,
}))
) {
- throw new Error("Could not pause the development server for integration setup.");
+ throw new Error("Could not pause the development server for setup.");
}
let outcome:
| { readonly error: unknown; readonly ok: false }
@@ -88,7 +88,7 @@ export async function runInteractiveDevelopmentUi(input: {
(await resumeDevelopmentRuntimeArtifacts(release)) === undefined
) {
throw new Error(
- "Could not resume the eve development server after integration setup. Restart eve dev before making further source changes.",
+ "Could not resume the eve development server after setup. Restart eve dev before making further source changes.",
outcome.ok ? undefined : { cause: outcome.error },
);
}
diff --git a/packages/eve/src/cli/dev/tui/agent-header.test.ts b/packages/eve/src/cli/dev/tui/agent-header.test.ts
index a6b50a020..2b609819d 100644
--- a/packages/eve/src/cli/dev/tui/agent-header.test.ts
+++ b/packages/eve/src/cli/dev/tui/agent-header.test.ts
@@ -22,12 +22,12 @@ describe("buildAgentHeader", () => {
const card = plain.join("\n");
const titleIndex = plain.findIndex((line) => line.includes("Weather Agent"));
- expect(plain[0]).toBe(`╭${"─".repeat(66)}╮`);
- expect(plain[titleIndex]).toMatch(/^│ ☰eve \(v\d+\.\d+\.\d+\) +Weather Agent │$/u);
+ expect(plain).toHaveLength(1);
+ expect(plain[titleIndex]).toMatch(/^eve v\d+\.\d+\.\d+ +Weather Agent$/u);
expect(card).not.toContain("model");
expect(card).not.toContain("instructions");
expect(card).not.toContain("⣿");
- expect(lines[0]).toBe(theme.colors.dim(plain[0]!));
+ expect(lines[0]).toContain(theme.colors.bold("eve"));
});
it("renders only known fields before agent inspection", () => {
@@ -40,21 +40,21 @@ describe("buildAgentHeader", () => {
}).join("\n");
expect(card).toContain("weather-agent");
- expect(card).toContain("Tip: Use the /help command to see every command.");
+ expect(card).toContain("Use the /help command to see every command.");
});
it("renders the /add tip with a blue command", () => {
const theme = createTheme({ color: true, unicode: false });
const tip = AGENT_HEADER_TIPS.find((candidate) => candidate.includes("/add"));
- expect(tip).toBe("Use the /add command to install an integration.");
+ expect(tip).toBe("/add to extend your agent · /help for commands");
if (tip === undefined) return;
const line = buildAgentHeader({ info: INFO, theme, width: 120, tip }).find((candidate) =>
- candidate.includes("Tip:"),
+ candidate.includes("/add"),
);
- expect(stripAnsi(line ?? "")).toContain(`| Tip: ${tip}`);
+ expect(stripAnsi(line ?? "")).toContain(tip);
expect(line).toContain(theme.colors.blue("/add"));
});
diff --git a/packages/eve/src/cli/dev/tui/agent-header.ts b/packages/eve/src/cli/dev/tui/agent-header.ts
index 1b5c725c1..ce8d89dfb 100644
--- a/packages/eve/src/cli/dev/tui/agent-header.ts
+++ b/packages/eve/src/cli/dev/tui/agent-header.ts
@@ -2,7 +2,7 @@
import type { AgentInfoResult } from "#client/index.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
-import { clipVisible, visibleLength } from "#cli/ui/terminal-text.js";
+import { clipVisible } from "#cli/ui/terminal-text.js";
import { isPromptControlCommand } from "./prompt-commands.js";
import type { Theme } from "./theme.js";
@@ -23,9 +23,7 @@ export interface AgentHeaderInput {
* slash commands, so callers only attach a tip to local `eve dev` sessions.
*/
export const AGENT_HEADER_TIPS: readonly string[] = [
- "Use the /add command to install an integration.",
- "Use the /deploy command to deploy your agent.",
- "Use the /help command to see every command.",
+ "/add to extend your agent · /help for commands",
];
/** Picks one tip; `random` is a test seam over Math.random. */
@@ -42,40 +40,11 @@ export function buildAgentHeader(input: AgentHeaderInput): string[] {
const { theme, info, width } = input;
const c = theme.colors;
const version = resolveInstalledPackageInfo().version;
- // Leave the terminal's final column untouched so terminals that wrap on a
- // write there do not add an untracked row beneath the live region.
- const cardWidth = Math.min(68, Math.max(0, width - 1));
-
- const brand = `${c.dim("☰")}${c.bold("eve")} ${c.dim(`(v${version})`)}`;
- if (cardWidth < 4) return [clipVisible(brand, width)];
-
- const horizontal = theme.unicode ? "─" : "-";
- const vertical = theme.unicode ? "│" : "|";
- const topLeft = theme.unicode ? "╭" : "+";
- const topRight = theme.unicode ? "╮" : "+";
- const bottomLeft = theme.unicode ? "╰" : "+";
- const bottomRight = theme.unicode ? "╯" : "+";
- const innerWidth = cardWidth - 2;
- const border = horizontal.repeat(innerWidth);
- const row = (text = "", ambiguousWidth = 0): string => {
- const available = Math.max(0, innerWidth - 2);
- const body = clipVisible(text, available);
- const padding = Math.max(0, available - visibleLength(body) - ambiguousWidth);
- return `${c.dim(vertical)} ${body}${" ".repeat(padding)} ${c.dim(vertical)}`;
- };
-
+ const available = Math.max(0, width - 1);
const agentName = info?.agent.name ?? input.name;
- const title =
- agentName === undefined ? brand : spreadRow(brand, c.bold(agentName), innerWidth - 2, 1);
- const lines = [c.dim(`${topLeft}${border}${topRight}`)];
- // U+2630 is East Asian Ambiguous and renders as two cells in some
- // terminals, so reserve its second cell explicitly inside the card.
- lines.push(row(title, 1));
- lines.push(row());
- if (input.tip !== undefined) {
- lines.push(row(`${c.bold("Tip:")} ${renderTip(input.tip, innerWidth - 7, theme)}`));
- }
- lines.push(c.dim(`${bottomLeft}${border}${bottomRight}`));
+ const title = `${c.bold("eve")} ${c.dim(`v${version}`)}${agentName ? ` ${agentName}` : ""}`;
+ const lines = [clipVisible(title, available)];
+ if (input.tip) lines.push(renderTip(input.tip, available, theme));
if (info && (info.diagnostics.discoveryErrors > 0 || info.diagnostics.discoveryWarnings > 0)) {
const parts: string[] = [];
@@ -101,14 +70,6 @@ export function buildAgentHeader(input: AgentHeaderInput): string[] {
return lines;
}
-function spreadRow(left: string, right: string, width: number, ambiguousWidth: number): string {
- const available = Math.max(1, width - ambiguousWidth);
- const clippedLeft = clipVisible(left, Math.max(1, available - visibleLength(right) - 1));
- const clippedRight = clipVisible(right, Math.max(1, available - visibleLength(clippedLeft) - 1));
- const gap = Math.max(1, available - visibleLength(clippedLeft) - visibleLength(clippedRight));
- return `${clippedLeft}${" ".repeat(gap)}${clippedRight}`;
-}
-
function renderTip(tip: string, width: number, theme: Theme): string {
return clipVisible(
tip
diff --git a/packages/eve/src/cli/dev/tui/blocks.test.ts b/packages/eve/src/cli/dev/tui/blocks.test.ts
index cee0fdc9b..30db0e213 100644
--- a/packages/eve/src/cli/dev/tui/blocks.test.ts
+++ b/packages/eve/src/cli/dev/tui/blocks.test.ts
@@ -276,22 +276,22 @@ describe("renderBlockLines", () => {
expect(lines).toEqual([" ※ subagent(self:4)"]);
});
- it("marks steered and queued user messages with a gutter arrow", () => {
+ it("renders steered and queued messages without extra arrow rows", () => {
const steered = render({
kind: "user",
body: "need to be\n\nsuper accurate",
promptOrigin: "steer",
});
- expect(steered).toEqual(["↑", "│ need to be", "│ ", "│ super accurate"]);
+ expect(steered).toEqual(["│ need to be", "│ ", "│ super accurate"]);
const queued = render({ kind: "user", body: "later then", promptOrigin: "queue" });
- expect(queued).toEqual(["│ later then", "↑"]);
+ expect(queued).toEqual(["│ later then"]);
// An ordinary typed prompt keeps its bare bar.
expect(render({ kind: "user", body: "hello" })).toEqual(["│ hello"]);
});
- it("colors the provenance arrow with the user bar's accent", () => {
+ it("colors the steered message gutter yellow", () => {
const colorTheme = createTheme({ color: true, unicode: true });
const rows = renderBlockLines(
{ kind: "user", body: "go", promptOrigin: "steer" },
@@ -299,9 +299,7 @@ describe("renderBlockLines", () => {
colorTheme,
{ activityPulse: "▪" },
);
- // Same cyan as the `│` gutter bar.
- expect(rows[0]).toBe("\x1b[36m↑\x1b[39m");
- expect(rows[1]).toContain("\x1b[36m│\x1b[39m");
+ expect(rows).toEqual(["\x1b[33m│\x1b[39m go"]);
});
it("pulses the in-progress subagent mark by intensity, with a quiet label", () => {
@@ -510,7 +508,7 @@ describe("error block coloring", () => {
{
kind: "error",
title: "Error",
- body: "HookConflictError: token in use\n╰▶ docs: https://workflow-sdk.dev/err/hook-conflict",
+ body: "HookConflictError: token in use\n╰› docs: https://workflow-sdk.dev/err/hook-conflict",
},
80,
colorTheme,
diff --git a/packages/eve/src/cli/dev/tui/blocks.ts b/packages/eve/src/cli/dev/tui/blocks.ts
index cce716626..5724696e2 100644
--- a/packages/eve/src/cli/dev/tui/blocks.ts
+++ b/packages/eve/src/cli/dev/tui/blocks.ts
@@ -71,12 +71,7 @@ export interface Block {
subtitle?: string;
/** Main multi-line content (markdown for prose, plain for logs). */
body?: string;
- /**
- * User blocks only: how a mid-turn message reached the transcript. A
- * steered message (Esc pop, displacing the running turn) marks itself
- * with the accent arrow above its bar; a queued one (drained at the turn
- * boundary) carries the arrow below. Absent for ordinary typed prompts.
- */
+ /** User blocks only: steered messages use a yellow gutter. */
promptOrigin?: "steer" | "queue";
/** Reasoning trace shown above `body` (subagent steps). */
reasoning?: string;
@@ -269,16 +264,12 @@ function renderBody(
}
function renderUser(block: Block, width: number, theme: Theme): string[] {
- const bar = theme.colors.cyan(theme.glyph.user);
+ const bar =
+ block.promptOrigin === "steer"
+ ? theme.colors.yellow(theme.glyph.user)
+ : theme.colors.cyan(theme.glyph.user);
const lines = wrap(block.body ?? "", width - 2);
- const rows = lines.map((line) => `${bar} ${line}`);
- // Mid-turn provenance rides the gutter in the bar's own accent: a steered
- // message pushed itself ahead of the running turn (arrow above), a queued
- // one waited for the boundary (arrow below).
- const arrow = theme.colors.cyan(theme.glyph.arrowUp);
- if (block.promptOrigin === "steer") return [arrow, ...rows];
- if (block.promptOrigin === "queue") return [...rows, arrow];
- return rows;
+ return lines.map((line) => `${bar} ${line}`);
}
function renderProse(
@@ -444,9 +435,8 @@ function paintCommands(line: string, theme: Theme): string {
/**
* A slash command invocation under the user gutter. Automatic commands use
- * the same row so their result can follow it. The `❯`/`›` glyphs remain
- * exclusive to live input because the TUI tests use `›` (the empty prompt's
- * quiet mark) to detect a ready prompt.
+ * the same row so their result can follow it. The `❯` glyph remains
+ * exclusive to live input because the TUI tests use `❯` to detect a ready prompt.
*/
function renderCommand(block: Block, theme: Theme): string[] {
const c = theme.colors;
diff --git a/packages/eve/src/cli/dev/tui/command-typeahead.test.ts b/packages/eve/src/cli/dev/tui/command-typeahead.test.ts
index e69f1f6bd..2770c34c5 100644
--- a/packages/eve/src/cli/dev/tui/command-typeahead.test.ts
+++ b/packages/eve/src/cli/dev/tui/command-typeahead.test.ts
@@ -134,13 +134,11 @@ describe("renderCommandSuggestions", () => {
const state = moveTypeaheadSelection(typeaheadFor(COMMANDS, "/"), 1);
const colored = createTheme({ color: true, unicode: true });
const rendered = renderCommandSuggestions(state, colored, 80);
- expect(rendered[1]).toContain(
- colored.colors.inverse(colored.colors.blue(` ${colored.glyph.selectedPointer} /model `)),
- );
+ expect(rendered[1]).toContain(colored.colors.bold(` ${colored.glyph.selectedPointer} /model`));
const rows = rendered.map(stripAnsi);
expect(rows).toHaveLength(COMMANDS.length);
expect(rows[0]?.startsWith(" /help")).toBe(true);
- expect(rows[1]?.startsWith(" ▶ /model ")).toBe(true);
+ expect(rows[1]?.startsWith(" › /model ")).toBe(true);
expect(rows[1]).toContain(theme.glyph.selectedPointer);
expect(rows[0]).not.toContain(theme.glyph.selectedPointer);
expect(rows[1]).toContain("/model");
diff --git a/packages/eve/src/cli/dev/tui/command-typeahead.ts b/packages/eve/src/cli/dev/tui/command-typeahead.ts
index d443e66fb..ebb1dfa33 100644
--- a/packages/eve/src/cli/dev/tui/command-typeahead.ts
+++ b/packages/eve/src/cli/dev/tui/command-typeahead.ts
@@ -149,14 +149,8 @@ export function renderCommandSuggestions(
const name = `/${spec.name}`;
const content = isCursor ? `${theme.glyph.selectedPointer} ${name}` : ` ${name}`;
const selection = renderCursorRow(content, isCursor, c);
- let detail = invocation(spec).slice(`/${spec.name}`.length);
- let pad = " ".repeat(column - invocation(spec).length);
- // The selected label's trailing inverse cell replaces the first suffix
- // space so aliases and descriptions stay in the same columns.
- if (isCursor) {
- if (detail.startsWith(" ")) detail = detail.slice(1);
- else pad = pad.slice(1);
- }
+ const detail = invocation(spec).slice(`/${spec.name}`.length);
+ const pad = " ".repeat(column - invocation(spec).length);
return `${selection}${c.dim(detail)}${pad}${c.dim(spec.description)}`;
});
diff --git a/packages/eve/src/cli/dev/tui/message-queue.ts b/packages/eve/src/cli/dev/tui/message-queue.ts
index 95709f9e4..ce2373975 100644
--- a/packages/eve/src/cli/dev/tui/message-queue.ts
+++ b/packages/eve/src/cli/dev/tui/message-queue.ts
@@ -2,7 +2,8 @@
* The pinned message-queue panel: client-side state and pure rendering for
* messages submitted while a turn is still streaming.
*
- * Enter queues the draft (up to {@link MESSAGE_QUEUE_LIMIT}); each queued
+ * When steering is unavailable, Enter queues the draft (up to
+ * {@link MESSAGE_QUEUE_LIMIT}); each queued
* message waits for the turn to end, where the whole queue coalesces into
* the next turn's message. Esc or Ctrl+C pops the oldest message to steer the
* conversation instead of waiting: the renderer sends the popped message to
diff --git a/packages/eve/src/cli/dev/tui/model-editor.test.ts b/packages/eve/src/cli/dev/tui/model-editor.test.ts
index 07fdd5657..861ff0ef0 100644
--- a/packages/eve/src/cli/dev/tui/model-editor.test.ts
+++ b/packages/eve/src/cli/dev/tui/model-editor.test.ts
@@ -1,472 +1,104 @@
import { describe, expect, it } from "vitest";
-
-import type { GatewayModelCapabilities } from "#setup/boxes/model-capabilities.js";
import type { ModelSettingsRequest } from "#setup/flows/model.js";
-
import {
initialModelEditorState,
modelEditorMenuRows,
- reasoningPositions,
transitionModelEditor,
- type ModelEditorEvent,
type ModelEditorState,
+ type ModelEditorEvent,
} from "./model-editor.js";
-
-const OPTIONS = [
- {
- id: "anthropic/claude-sonnet-5",
- value: "anthropic/claude-sonnet-5",
- label: "Claude Sonnet 5",
- hint: "Anthropic",
- featured: true,
+const request: ModelSettingsRequest = {
+ model: {
+ kind: "pick",
+ current: "openai/gpt-5.6-luna-fast",
+ options: [
+ { value: "openai/gpt-5.6-luna-fast", label: "Luna" },
+ { value: "anthropic/claude-sonnet-5", label: "Sonnet" },
+ { value: "test/no-reasoning", label: "Simple" },
+ ],
},
- { id: "xai/grok-4.5", value: "xai/grok-4.5", label: "Grok 4.5", hint: "xAI" },
- { id: "test/no-frills", value: "test/no-frills", label: "No Frills", hint: "Test" },
-] as const;
-
-const CAPABILITIES: Record<string, GatewayModelCapabilities> = {
- "anthropic/claude-sonnet-5": {
- reasoning: true,
- reasoningLevels: ["none", "minimal", "low", "medium", "high", "xhigh"],
- fastMode: true,
- },
- "xai/grok-4.5": { reasoning: true, reasoningLevels: ["low", "high"], fastMode: true },
- "test/no-frills": { reasoning: false, reasoningLevels: [], fastMode: false },
+ reasoning: "high",
+ serviceTier: { kind: "priority" },
+ settingsEditable: true,
+ externalRouting: false,
+ capabilitiesFor: (id) =>
+ id === "test/no-reasoning"
+ ? { reasoning: false, reasoningLevels: [], fastMode: false }
+ : { reasoning: true, reasoningLevels: ["low", "high"], fastMode: true },
};
-
-function request(overrides: Partial<ModelSettingsRequest> = {}): ModelSettingsRequest {
- return {
- model: { kind: "pick", options: [...OPTIONS], current: "anthropic/claude-sonnet-5" },
- reasoning: null,
- serviceTier: { kind: "standard" },
- settingsEditable: true,
- externalRouting: false,
- capabilitiesFor: (modelId) => (modelId === null ? undefined : CAPABILITIES[modelId]),
- ...overrides,
- };
-}
-
-/** Applies events in order, asserting none of them settles or cancels. */
-function drive(
- req: ModelSettingsRequest,
- state: ModelEditorState,
- events: ModelEditorEvent[],
-): ModelEditorState {
- let current = state;
+function drive(events: ModelEditorEvent[], req = request): ModelEditorState {
+ let state = initialModelEditorState(req);
for (const event of events) {
- const transition = transitionModelEditor(current, event, req);
- if (transition.kind !== "render" && transition.kind !== "ignore") {
- throw new Error(`Unexpected ${transition.kind} transition for ${JSON.stringify(event)}`);
- }
- current = transition.state;
+ const result = transitionModelEditor(state, event, req);
+ if (result.kind !== "render" && result.kind !== "ignore")
+ throw new Error(`Unexpected ${result.kind}`);
+ state = result.state;
}
- return current;
+ return state;
}
-
-describe("initialModelEditorState", () => {
- it("opens the menu on the Model row with the draft seeded from authored values", () => {
- const req = request({ reasoning: "high", serviceTier: { kind: "priority" } });
- const state = initialModelEditorState(req);
-
- expect(state.screen).toEqual({ kind: "menu", cursor: "model" });
- expect(state.draft).toEqual({
- modelId: "anthropic/claude-sonnet-5",
- reasoning: "high",
- tier: "priority",
- });
- expect(state.capabilities?.reasoning).toBe(true);
- });
-
- it("opens a fixed-model menu on the first pickable row", () => {
- const req = request({
- model: { kind: "fixed", current: "anthropic/claude-sonnet-5", reason: "SDK model call" },
- });
- expect(initialModelEditorState(req).screen).toEqual({ kind: "menu", cursor: "reasoning" });
- });
-
- it("lands on Done when a fixed no-frills model disables everything else", () => {
- const req = request({
- model: { kind: "fixed", current: "test/no-frills", reason: "SDK model call" },
- });
- expect(initialModelEditorState(req).screen).toEqual({ kind: "menu", cursor: "done" });
- });
-});
-
-describe("modelEditorMenuRows", () => {
- it("derives pickable rows for a fully-capable pick", () => {
- const state = initialModelEditorState(request());
- const rows = modelEditorMenuRows(request(), state.draft, state.capabilities);
- expect(rows.map((row) => [row.value, row.disabled ?? false])).toEqual([
- ["model", false],
- ["reasoning", false],
- ["tier", false],
- ["done", false],
- ]);
- });
-
- it("disables the model row for an SDK model call, carrying the reason", () => {
- const req = request({
- model: { kind: "fixed", current: "anthropic/claude-sonnet-5", reason: "SDK model call" },
- });
- const state = initialModelEditorState(req);
- expect(modelEditorMenuRows(req, state.draft, state.capabilities)[0]).toEqual({
- value: "model",
- label: "Model",
- disabled: true,
- description: "SDK model call",
- });
- });
-
- it("disables reasoning with its explanation and omits the tier for a no-frills model", () => {
- const req = request({
- model: { kind: "pick", options: [...OPTIONS], current: "test/no-frills" },
- });
- const state = initialModelEditorState(req);
- const rows = modelEditorMenuRows(req, state.draft, state.capabilities);
- expect(rows.map((row) => row.value)).toEqual(["model", "reasoning", "done"]);
- expect(rows[1]).toMatchObject({
- disabled: true,
- description: "Not supported by the selected model",
- });
- });
-
- it("keeps a static tier row for custom tiers and external routing", () => {
- const state = initialModelEditorState(request());
- const custom = modelEditorMenuRows(
- request({ serviceTier: { kind: "custom", value: "flex" } }),
- state.draft,
- state.capabilities,
- );
- expect(custom.find((row) => row.value === "tier")).toMatchObject({
- disabled: true,
- description: "Custom (flex) — authored in agent.ts",
- });
-
- const external = modelEditorMenuRows(
- request({ externalRouting: true }),
- state.draft,
- state.capabilities,
- );
- expect(external.find((row) => row.value === "tier")).toMatchObject({
- disabled: true,
- description: "Disabled for a direct external provider",
- });
- });
-});
-
-describe("reasoningPositions", () => {
- it("orders notches as the supported levels, inserting a drafted stray", () => {
- expect(reasoningPositions(CAPABILITIES["xai/grok-4.5"], "medium")).toEqual([
- "low",
- "medium",
- "high",
- ]);
- });
-
- it("offers every level when the catalog does not know the model", () => {
- expect(reasoningPositions(undefined, "default")).toEqual([
- "none",
- "minimal",
- "low",
- "medium",
- "high",
- "xhigh",
- ]);
- });
-});
-
-describe("menu screen", () => {
- it("moves the cursor with wrap while skipping disabled rows", () => {
- const req = request({
- model: { kind: "pick", options: [...OPTIONS], current: "test/no-frills" },
- });
- let state = initialModelEditorState(req);
- // Rows: model / reasoning(disabled) / done — down skips the disabled row.
- state = drive(req, state, [{ type: "move", direction: "down" }]);
- expect(state.screen).toEqual({ kind: "menu", cursor: "done" });
- state = drive(req, state, [{ type: "move", direction: "down" }]);
- expect(state.screen).toEqual({ kind: "menu", cursor: "model" });
- });
-
- it("cancels straight out from the menu", () => {
- const req = request();
- expect(transitionModelEditor(initialModelEditorState(req), { type: "cancel" }, req)).toEqual({
- kind: "cancel",
+describe("model editor", () => {
+ it("has model, reasoning and tier settings without a Done row", () => {
+ const state = initialModelEditorState(request);
+ expect(
+ modelEditorMenuRows(request, state.draft, state.capabilities).map((row) => row.value),
+ ).toEqual(["model", "reasoning", "tier"]);
+ });
+ it("applies a filtered model on Enter", () => {
+ const state = drive([{ type: "submit" }, { type: "char", char: "Sonnet" }]);
+ expect(transitionModelEditor(state, { type: "submit" }, request)).toEqual({
+ kind: "settle",
+ result: { model: "anthropic/claude-sonnet-5" },
});
});
-
- it("opens the model list on Enter and walks past inline rows instead", () => {
- const req = request({ reasoning: "high", serviceTier: { kind: "priority" } });
- const state = initialModelEditorState(req);
-
- const model = transitionModelEditor(state, { type: "submit" }, req);
- expect(model.kind).toBe("render");
- if (model.kind !== "render") return;
- expect(model.state.screen.kind).toBe("model");
-
- // Enter on an inline value row is just a downward step.
- const onReasoning = drive(req, state, [{ type: "move", direction: "down" }]);
- const stepped = drive(req, onReasoning, [{ type: "submit" }]);
- expect(stepped.screen).toEqual({ kind: "menu", cursor: "tier" });
- expect(stepped.draft.reasoning).toBe("high");
- });
-});
-
-describe("model sub-screen", () => {
- it("filters, clears the filter on Esc, and returns to the menu on a second Esc", () => {
- const req = request();
- let state = drive(req, initialModelEditorState(req), [{ type: "submit" }]);
- state = drive(req, state, [
- { type: "char", char: "g" },
- { type: "char", char: "r" },
- ]);
- expect(state.screen.kind === "model" && state.screen.select.filter).toBe("gr");
-
- state = drive(req, state, [{ type: "cancel" }]);
- expect(state.screen.kind === "model" && state.screen.select.filter).toBe("");
-
- state = drive(req, state, [{ type: "cancel" }]);
- expect(state.screen).toEqual({ kind: "menu", cursor: "model" });
- // Esc changed nothing.
- expect(state.draft.modelId).toBe("anthropic/claude-sonnet-5");
- });
-
- it("commits a pick into the draft, recomputes capabilities, and returns to the menu", () => {
- const req = request();
- let state = drive(req, initialModelEditorState(req), [
+ it("clears a filter before returning to settings on Esc", () => {
+ const state = drive([
{ type: "submit" },
- { type: "char", char: "grok" },
+ { type: "char", char: "Luna" },
+ { type: "cancel" },
+ { type: "cancel" },
]);
- state = drive(req, state, [{ type: "submit" }]);
-
expect(state.screen).toEqual({ kind: "menu", cursor: "model" });
- expect(state.draft.modelId).toBe("xai/grok-4.5");
- expect(state.capabilities?.reasoningLevels).toEqual(["low", "high"]);
+ expect(transitionModelEditor(state, { type: "cancel" }, request)).toEqual({ kind: "cancel" });
});
-
- it("snaps a drafted level the picked model cannot serve to its closest supported one", () => {
- const req = request({ reasoning: "xhigh" });
- let state = drive(req, initialModelEditorState(req), [
- { type: "submit" },
- { type: "char", char: "grok" },
- { type: "submit" },
- ]);
- // grok supports only low/high: xhigh lands on high, not a stray notch.
- expect(state.draft.reasoning).toBe("high");
-
- // A model with no adjustable reasoning clears the level entirely.
- state = drive(req, state, [
- { type: "submit" },
- { type: "char", char: "frills" },
- { type: "submit" },
- ]);
- expect(state.draft.reasoning).toBe("default");
+ it("does not submit a filter with no matches", () => {
+ const state = drive([{ type: "submit" }, { type: "char", char: "missing" }]);
+ expect(transitionModelEditor(state, { type: "submit" }, request).kind).toBe("ignore");
});
-
- it("keeps a supported drafted level and an unset draft across picks", () => {
- const req = request({ reasoning: "low" });
- const state = drive(req, initialModelEditorState(req), [
- { type: "submit" },
- { type: "char", char: "grok" },
- { type: "submit" },
- ]);
- expect(state.draft.reasoning).toBe("low");
-
- const unset = request();
- const picked = drive(unset, initialModelEditorState(unset), [
- { type: "submit" },
- { type: "char", char: "frills" },
- { type: "submit" },
- ]);
- expect(picked.draft.reasoning).toBe("default");
- });
-
- it("ignores submit when the filter matches nothing", () => {
- const req = request();
- const state = drive(req, initialModelEditorState(req), [
- { type: "submit" },
- { type: "char", char: "zzz" },
- ]);
- expect(transitionModelEditor(state, { type: "submit" }, req).kind).toBe("ignore");
- });
-});
-
-describe("inline reasoning adjust", () => {
- function onReasoning(req: ModelSettingsRequest): ModelEditorState {
- return drive(req, initialModelEditorState(req), [{ type: "move", direction: "down" }]);
- }
-
- it("adjusts the draft by one step and wraps as a ring at both ends", () => {
- const req = request({ reasoning: "high" });
- let state = onReasoning(req);
- state = drive(req, state, [{ type: "adjust", direction: "right" }]);
- expect(state.draft.reasoning).toBe("xhigh");
- expect(state.screen).toEqual({ kind: "menu", cursor: "reasoning" });
-
- // Right past the top wraps to the first level; left wraps back.
- state = drive(req, state, [{ type: "adjust", direction: "right" }]);
- expect(state.draft.reasoning).toBe("none");
- state = drive(req, state, [{ type: "adjust", direction: "left" }]);
- expect(state.draft.reasoning).toBe("xhigh");
- });
-
- it("enters the ring from an unset draft: right at the lowest, left at the highest", () => {
- const req = request();
- let state = onReasoning(req);
- expect(state.draft.reasoning).toBe("default");
-
- const entered = drive(req, state, [{ type: "adjust", direction: "left" }]);
- expect(entered.draft.reasoning).toBe("xhigh");
-
- state = drive(req, state, [{ type: "adjust", direction: "right" }]);
- expect(state.draft.reasoning).toBe("none");
- });
-
- it("ignores adjust away from the value rows", () => {
- const req = request();
- const state = initialModelEditorState(req);
- expect(state.screen).toEqual({ kind: "menu", cursor: "model" });
- expect(transitionModelEditor(state, { type: "adjust", direction: "right" }, req).kind).toBe(
- "ignore",
- );
- });
-});
-
-describe("inline tier adjust", () => {
- it("flips the tier on either arrow — a two-value ring, so Tab always acts", () => {
- const req = request();
- let state = drive(req, initialModelEditorState(req), [
- { type: "move", direction: "down" },
- { type: "move", direction: "down" },
- ]);
- expect(state.screen).toEqual({ kind: "menu", cursor: "tier" });
-
- state = drive(req, state, [{ type: "adjust", direction: "right" }]);
- expect(state.draft.tier).toBe("priority");
- state = drive(req, state, [{ type: "adjust", direction: "right" }]);
- expect(state.draft.tier).toBe("standard");
- state = drive(req, state, [{ type: "adjust", direction: "left" }]);
- expect(state.draft.tier).toBe("priority");
- });
-
- it("drops a drafted priority tier when the picked model prices no fast mode", () => {
- // Drafted (not authored) priority: the pick must reset it, or the hidden
- // row leaves it stuck and it leaks into the settle result.
- const req = request();
- let state = drive(req, initialModelEditorState(req), [
- { type: "move", direction: "down" },
- { type: "move", direction: "down" },
- { type: "adjust", direction: "right" }, // tier → priority
- { type: "move", direction: "up" },
- { type: "move", direction: "up" },
- { type: "submit" },
- { type: "char", char: "frills" },
- { type: "submit" }, // model → test/no-frills, fastMode: false
- ]);
- expect(state.draft.tier).toBe("standard");
-
- // Priority survives a pick between two fast-mode models.
- const priority = request({ serviceTier: { kind: "priority" } });
- state = drive(priority, initialModelEditorState(priority), [
- { type: "submit" },
- { type: "char", char: "grok" },
- { type: "submit" },
- ]);
- expect(state.draft.tier).toBe("priority");
- });
-
- it("hides the tier row after a pick of a model without the tier", () => {
- const req = request();
- let state = drive(req, initialModelEditorState(req), [
- { type: "submit" },
- { type: "char", char: "frills" },
- { type: "submit" },
- ]);
- const rows = modelEditorMenuRows(req, state.draft, state.capabilities);
- expect(rows.map((row) => row.value)).toEqual(["model", "reasoning", "done"]);
- // The menu cursor stays valid: moving down from Model skips to Done.
- state = drive(req, state, [{ type: "move", direction: "down" }]);
- expect(state.screen).toEqual({ kind: "menu", cursor: "done" });
- });
-});
-
-describe("settling", () => {
- function toDone(req: ModelSettingsRequest, state: ModelEditorState): ModelEditorState {
- let current = state;
- for (
- let i = 0;
- i < 4 && (current.screen.kind !== "menu" || current.screen.cursor !== "done");
- i += 1
- ) {
- current = drive(req, current, [{ type: "move", direction: "down" }]);
- }
- return current;
- }
-
- it("settles with only the fields that differ from the authored values", () => {
- const req = request({ reasoning: "medium" });
- let state = drive(req, initialModelEditorState(req), [
- { type: "submit" },
- { type: "char", char: "grok" },
- { type: "submit" }, // model → xai/grok-4.5
- { type: "move", direction: "down" },
- { type: "adjust", direction: "right" }, // medium (stray between low/high) → high
+ it("applies a reasoning choice on Enter", () => {
+ const state = drive([
{ type: "move", direction: "down" },
- { type: "adjust", direction: "right" }, // tier → priority
+ { type: "adjust", direction: "left" },
]);
- state = toDone(req, state);
-
- expect(transitionModelEditor(state, { type: "submit" }, req)).toEqual({
- kind: "settle",
- result: { model: "xai/grok-4.5", reasoning: "high", serviceTier: "priority" },
- });
- });
-
- it("settles with an empty result when nothing changed", () => {
- const req = request();
- const state = toDone(req, initialModelEditorState(req));
- expect(transitionModelEditor(state, { type: "submit" }, req)).toEqual({
+ expect(transitionModelEditor(state, { type: "submit" }, request)).toEqual({
kind: "settle",
- result: {},
+ result: { reasoning: "low" },
});
});
-
- it("maps a dropped tier to its remove sentinel", () => {
- const req = request({ serviceTier: { kind: "priority" } });
- let state = drive(req, initialModelEditorState(req), [
+ it("applies a service tier choice on Enter", () => {
+ const state = drive([
{ type: "move", direction: "down" },
{ type: "move", direction: "down" },
- { type: "adjust", direction: "left" }, // priority → standard
+ { type: "adjust", direction: "left" },
]);
- state = toDone(req, state);
-
- expect(transitionModelEditor(state, { type: "submit" }, req)).toEqual({
+ expect(transitionModelEditor(state, { type: "submit" }, request)).toEqual({
kind: "settle",
result: { serviceTier: "standard" },
});
});
-
- it("settles an authored priority tier down to standard when the pick loses fast mode", () => {
- const req = request({ serviceTier: { kind: "priority" } });
- let state = drive(req, initialModelEditorState(req), [
- { type: "submit" },
- { type: "char", char: "frills" },
- { type: "submit" },
- ]);
- state = toDone(req, state);
-
- expect(transitionModelEditor(state, { type: "submit" }, req)).toEqual({
+ it("drops incompatible reasoning and priority tier when changing models", () => {
+ const state = drive([{ type: "submit" }, { type: "char", char: "Simple" }]);
+ expect(transitionModelEditor(state, { type: "submit" }, request)).toEqual({
kind: "settle",
- result: { model: "test/no-frills", serviceTier: "standard" },
+ result: { model: "test/no-reasoning", reasoning: "default", serviceTier: "standard" },
});
});
-
- it("never reports tier changes for custom configurations", () => {
- const req = request({ serviceTier: { kind: "custom", value: "flex" } });
- const state = toDone(req, initialModelEditorState(req));
- expect(transitionModelEditor(state, { type: "submit" }, req)).toEqual({
- kind: "settle",
- result: {},
- });
+ it("leaves an SDK model fixed while allowing supported settings", () => {
+ const req: ModelSettingsRequest = {
+ ...request,
+ model: { kind: "fixed", current: "custom", reason: "Authored in agent.ts" },
+ };
+ const state = initialModelEditorState(req);
+ expect(state.screen).toEqual({ kind: "menu", cursor: "reasoning" });
+ expect(modelEditorMenuRows(req, state.draft, state.capabilities)[0]?.disabled).toBe(true);
});
});
diff --git a/packages/eve/src/cli/dev/tui/model-editor.ts b/packages/eve/src/cli/dev/tui/model-editor.ts
index 0beb9db69..c8816856f 100644
--- a/packages/eve/src/cli/dev/tui/model-editor.ts
+++ b/packages/eve/src/cli/dev/tui/model-editor.ts
@@ -23,7 +23,7 @@ export type ModelEditorScreen =
| { kind: "menu"; cursor: ModelEditorRowId }
| { kind: "model"; select: SelectState };
-/** The in-progress values; nothing lands in source until the menu's Done. */
+/** The in-progress values; a completed selection is applied immediately. */
export interface ModelEditorDraft {
modelId: string | null;
reasoning: "default" | ReasoningLevel;
@@ -195,7 +195,6 @@ export function modelEditorMenuRows(
rows.push({ value: "tier", label: "Service tier", disabled: true, description: tier.text });
}
- rows.push({ value: "done", label: "Done" });
return rows;
}
@@ -325,8 +324,7 @@ function transitionMenu(
if (cursor === "done") {
return { kind: "settle", result: settleResult(request, state.draft) };
}
- // Enter on an inline value confirms nothing new — it just walks on.
- return transitionMenu(state, { type: "move", direction: "down" }, request, cursor);
+ return { kind: "settle", result: settleResult(request, state.draft) };
}
case "char":
case "backspace":
@@ -364,22 +362,14 @@ function transitionModelScreen(
if (value === undefined) return ignore(state);
const capabilities = request.capabilitiesFor(value);
return {
- kind: "render",
- state: {
- screen: { kind: "menu", cursor: "model" },
- draft: {
- ...state.draft,
- modelId: value,
- // A level the new model cannot serve must not survive the pick.
- reasoning: snapReasoningToCapabilities(state.draft.reasoning, capabilities),
- // Nor a priority tier the new model prices no fast mode for — the
- // hidden tier row would leave it drafted with no way to toggle it
- // back, and it would leak into the settle result.
- tier:
- capabilities !== undefined && !capabilities.fastMode ? "standard" : state.draft.tier,
- },
- capabilities,
- },
+ kind: "settle",
+ result: settleResult(request, {
+ ...state.draft,
+ modelId: value,
+ reasoning: snapReasoningToCapabilities(state.draft.reasoning, capabilities),
+ tier:
+ capabilities !== undefined && !capabilities.fastMode ? "standard" : state.draft.tier,
+ }),
};
}
case "adjust":
diff --git a/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts b/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts
index e3ba04c8e..b5a08ca85 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
@@ -2,7 +2,6 @@ import pc from "picocolors";
import { describe, expect, it, vi } from "vitest";
import { createPromptCommandHandler } from "./prompt-command-handler.js";
-import type { RemoteAuthCompletion, RemoteConnectionController } from "./remote-connection.js";
import type { AgentTUIRenderer, PromptCommandHandlerContext } from "./runner.js";
import type { SetupFlowRenderer } from "./setup-flow.js";
@@ -144,7 +143,7 @@ describe("createPromptCommandHandler", () => {
const runTuiSetupCommand = vi.fn(async () => ({
message: "AI Gateway via API key selected.",
preserveFlowDiagnostics: false,
- effect: { kind: "model-access-changed" } as const,
+ effect: { kind: "model-access-changed", reload: true } as const,
}));
vi.doMock("./setup-commands.js", () => ({
SETUP_FLOW_CONFIG: {
@@ -164,7 +163,7 @@ describe("createPromptCommandHandler", () => {
),
).resolves.toEqual({
message: "AI Gateway via API key selected.",
- effect: { kind: "model-access-changed" },
+ effect: { kind: "model-access-changed", reload: true },
});
expect(runTuiSetupCommand).toHaveBeenCalledWith(
expect.objectContaining({ initialModelStep: "provider" }),
@@ -214,127 +213,52 @@ describe("createPromptCommandHandler", () => {
}
});
- it("keeps the setup panel open for an immediate onboarding handoff", async () => {
- const runTuiSetupCommand = vi.fn(async () => ({
- message: "Vercel CLI installed.",
- preserveFlowDiagnostics: false,
- }));
+ it.each([false, true])("holds login open through runtime refresh (failure: %s)", async (fail) => {
vi.doMock("./setup-commands.js", () => ({
- SETUP_FLOW_CONFIG: {
- "vc:install": { title: "Install the Vercel CLI", indicator: "pulse" },
- },
- runTuiSetupCommand,
+ SETUP_FLOW_CONFIG: { login: { title: "Connect a model", indicator: "pulse" } },
+ runTuiSetupCommand: async () => ({
+ message: "Connected.",
+ effect: { kind: "model-access-changed", reload: true },
+ preserveFlowDiagnostics: false,
+ }),
}));
-
try {
const setupFlow = setupFlowRenderer();
- const handler = createPromptCommandHandler({ target: LOCAL_TARGET });
- const handoffContext = Object.assign(context({ setupFlow }), {
- keepSetupFlowOpen: true,
+ let release!: () => void;
+ const pending = new Promise<void>((resolve) => {
+ release = resolve;
});
-
- await handler.handle({ type: "extension", name: "vc:install", argument: "" }, handoffContext);
-
- expect(setupFlow.begin).toHaveBeenCalledWith("Install the Vercel CLI", "pulse");
+ const settleOutcome = vi.fn(async () => {
+ await pending;
+ return fail
+ ? { tone: "error" as const, message: "The agent could not reload." }
+ : { message: "Connected." };
+ });
+ const handler = createPromptCommandHandler({ target: LOCAL_TARGET });
+ const result = handler.handle(
+ { type: "extension", name: "login", argument: "" },
+ { ...context({ setupFlow }), settleOutcome },
+ );
+ await vi.waitFor(() => expect(settleOutcome).toHaveBeenCalledOnce());
expect(setupFlow.end).not.toHaveBeenCalled();
+ release();
+ const outcome = await result;
+ if (outcome === undefined) throw new Error("Expected a login outcome");
+ expect(setupFlow.end).toHaveBeenCalledOnce();
+ expect(outcome.effect).toBeUndefined();
+ if (fail) {
+ expect(outcome.tone).toBe("error");
+ expect(outcome.message).toContain("could not reload");
+ expect(outcome.message).not.toContain("private runtime failure");
+ } else {
+ expect(outcome.message).toBe("Connected.");
+ }
} finally {
vi.doUnmock("./setup-commands.js");
vi.resetModules();
}
});
- it("reports a login that completed before remote authentication was cancelled", async () => {
- const setupFlow = setupFlowRenderer();
- const runLoginFlow = vi.fn(async () => ({ kind: "cancelled" as const }));
- const remoteConnection: RemoteConnectionController = {
- current: () => ({
- target: REMOTE_TARGET,
- connection: {
- state: "auth-required",
- challenge: { kind: "eve-oidc" },
- },
- }),
- check: async () => ({
- state: "auth-required",
- challenge: { kind: "eve-oidc" },
- }),
- authenticate: async () => ({
- kind: "cancelled",
- completedMutations: [{ kind: "vercel-login" }],
- }),
- reportFailure: () => ({ state: "checking" }),
- dispose() {},
- };
- const handler = createPromptCommandHandler({
- target: REMOTE_TARGET,
- flows: { runLoginFlow },
- });
-
- await expect(
- handler.handle(
- { type: "extension", name: "vc:login", argument: "" },
- {
- ...context({ setupFlow }),
- remoteConnection,
- },
- ),
- ).resolves.toEqual({
- message: "/vc:login dismissed after logging in to Vercel.",
- });
- expect(runLoginFlow).not.toHaveBeenCalled();
- expect(setupFlow.begin).toHaveBeenCalledWith("Authenticate via Vercel OIDC", "pulse");
- expect(setupFlow.end).toHaveBeenCalledWith({ preserveDiagnostics: true });
- });
-
- it("reports mutations that completed before remote /vc:login was interrupted", async () => {
- const setupFlow = {
- ...setupFlowRenderer(),
- waitForInterrupt: () => ({ promise: Promise.resolve("ctrl-c" as const), dispose: vi.fn() }),
- } satisfies SetupFlowRenderer;
- const runLoginFlow = vi.fn(async () => ({ kind: "cancelled" as const }));
- const remoteConnection: RemoteConnectionController = {
- current: () => ({
- target: REMOTE_TARGET,
- connection: { state: "auth-required", challenge: { kind: "eve-oidc" } },
- }),
- check: async () => ({
- state: "auth-required",
- challenge: { kind: "eve-oidc" },
- }),
- authenticate: async (_attempt, signal) =>
- await new Promise<RemoteAuthCompletion>((resolve) => {
- signal?.addEventListener(
- "abort",
- () =>
- resolve({
- kind: "cancelled" as const,
- completedMutations: [
- { kind: "trusted-sources-updated", targetProjectName: "remote-agent" },
- ],
- }),
- { once: true },
- );
- }),
- reportFailure: () => ({ state: "checking" }),
- dispose() {},
- };
- const handler = createPromptCommandHandler({
- target: REMOTE_TARGET,
- flows: { runLoginFlow },
- });
-
- await expect(
- handler.handle(
- { type: "extension", name: "vc:login", argument: "" },
- { ...context({ setupFlow }), remoteConnection },
- ),
- ).resolves.toEqual({
- message:
- "/vc:login interrupted. Completed before interruption: updated Trusted Sources for remote-agent.",
- });
- expect(runLoginFlow).not.toHaveBeenCalled();
- });
-
it("folds setup-module load failures at the command adapter boundary", async () => {
vi.doMock("./setup-commands.js", () => {
throw new Error("Cannot find package 'oxc-parser'");
diff --git a/packages/eve/src/cli/dev/tui/prompt-command-handler.ts b/packages/eve/src/cli/dev/tui/prompt-command-handler.ts
index 18ca9fe91..e4d3a7f1d 100644
--- a/packages/eve/src/cli/dev/tui/prompt-command-handler.ts
+++ b/packages/eve/src/cli/dev/tui/prompt-command-handler.ts
@@ -7,7 +7,6 @@ import type {
PromptCommandOutcome,
} from "./runner.js";
import { isPromptCommandAvailableFor, type PromptCommand } from "./prompt-commands.js";
-import type { RemoteAuthFlow } from "./remote-auth.js";
import type { TuiSetupCommandInput, TuiSetupFlows } from "./setup-commands.js";
import type { DevelopmentTuiTarget } from "./target.js";
@@ -21,8 +20,6 @@ export interface PromptCommandHandlerOptions {
readonly modelChangeRefusal?: (appRoot: string) => Promise<string | null>;
/** Test seam; forwarded to runTuiSetupCommand's injectable flows. */
readonly flows?: Partial<TuiSetupFlows>;
- /** Test seam for remote authentication. */
- readonly remoteAuthFlow?: RemoteAuthFlow;
}
export function createPromptCommandHandler(
@@ -81,26 +78,6 @@ export function createPromptCommandHandler(
return { message: `/${command.name} is not supported by this renderer.` };
}
- if (command.name === "vc:login" && target.kind === "remote") {
- if (context.remoteConnection === undefined) {
- return { message: "/vc:login is not available in this session." };
- }
- let runRemoteAuthCommand: (typeof import("./remote-auth-command.js"))["runRemoteAuthCommand"];
- try {
- ({ runRemoteAuthCommand } = await import("./remote-auth-command.js"));
- } catch (error) {
- return { message: `/vc:login failed: ${toErrorMessage(error)}` };
- }
- const message = await runRemoteAuthCommand({
- connection: context.remoteConnection,
- flow: options.remoteAuthFlow,
- renderer: flow,
- });
- return { message };
- }
-
- // The remaining setup commands run against the local workspace, except
- // `/vc:install`, which needs only a working directory on a remote session.
let setupCommands: typeof import("./setup-commands.js");
try {
setupCommands = await import("./setup-commands.js");
@@ -109,8 +86,7 @@ export function createPromptCommandHandler(
}
const { runTuiSetupCommand, SETUP_FLOW_CONFIG } = setupCommands;
const flowConfig = SETUP_FLOW_CONFIG[command.name];
- flow.begin(context.setupFlowTitle ?? flowConfig.title, flowConfig.indicator);
- flow.setNavigation?.(context.setupFlowNavigation);
+ flow.begin(flowConfig.title, flowConfig.indicator);
let preserveFlowDiagnostics = true;
try {
const commandInput: TuiSetupCommandInput = {
@@ -124,9 +100,6 @@ export function createPromptCommandHandler(
if (context.initialModelStep !== undefined) {
commandInput.initialModelStep = context.initialModelStep;
}
- if (context.registryPlannerContext !== undefined) {
- commandInput.registryPlannerContext = context.registryPlannerContext;
- }
if (context.onOnboardingScreen !== undefined) {
commandInput.onOnboardingScreen = context.onOnboardingScreen;
}
@@ -138,11 +111,10 @@ export function createPromptCommandHandler(
const result = await runTuiSetupCommand(commandInput);
preserveFlowDiagnostics = result.preserveFlowDiagnostics;
const { preserveFlowDiagnostics: _preserve, partial: _partial, ...outcome } = result;
+ if (context.settleOutcome !== undefined) return await context.settleOutcome(outcome);
return outcome;
} finally {
- if (context.keepSetupFlowOpen !== true) {
- flow.end({ preserveDiagnostics: preserveFlowDiagnostics });
- }
+ flow.end({ preserveDiagnostics: preserveFlowDiagnostics });
}
},
};
diff --git a/packages/eve/src/cli/dev/tui/prompt-commands.test.ts b/packages/eve/src/cli/dev/tui/prompt-commands.test.ts
index 58ea5bba3..f41572f3b 100644
--- a/packages/eve/src/cli/dev/tui/prompt-commands.test.ts
+++ b/packages/eve/src/cli/dev/tui/prompt-commands.test.ts
@@ -43,16 +43,8 @@ describe("parsePromptCommand", () => {
});
it("parses the setup commands", () => {
- expect(parsePromptCommand("/vc:install")).toEqual({
- type: "extension",
- name: "vc:install",
- argument: "",
- });
- expect(parsePromptCommand("/vc:login")).toEqual({
- type: "extension",
- name: "vc:login",
- argument: "",
- });
+ expect(parsePromptCommand("/vc:install")).toBeNull();
+ expect(parsePromptCommand("/vc:login")).toBeNull();
expect(parsePromptCommand("/deploy")).toEqual({
type: "extension",
name: "deploy",
@@ -110,7 +102,11 @@ describe("parsePromptCommand", () => {
expect(parsePromptCommand("/models")).toBeNull();
expect(parsePromptCommand("/vercel")).toBeNull();
expect(parsePromptCommand("/vc")).toBeNull();
- expect(parsePromptCommand("/login")).toBeNull();
+ expect(parsePromptCommand("/login")).toEqual({
+ type: "extension",
+ name: "login",
+ argument: "",
+ });
expect(parsePromptCommand("/vc:auth")).toBeNull();
expect(parsePromptCommand("/channels")).toBeNull();
expect(parsePromptCommand("tell me about /channels")).toBeNull();
@@ -127,15 +123,15 @@ describe("promptCommandsFor", () => {
expect(names).toContain("model");
expect(names).toContain("add");
expect(names).toContain("deploy");
- expect(names).toContain("vc:install");
- expect(names).toContain("vc:login");
+ expect(names).not.toContain("vc:install");
+ expect(names).not.toContain("vc:login");
expect(names).not.toContain("vc:auth");
});
it("exposes the Vercel CLI commands for remote sessions", () => {
const names = promptCommandsFor("remote").map((command) => command.name);
- expect(names).toContain("vc:install");
- expect(names).toContain("vc:login");
+ expect(names).not.toContain("vc:install");
+ expect(names).not.toContain("vc:login");
expect(names).not.toContain("vc:auth");
expect(names).not.toContain("info");
expect(names).not.toContain("model");
@@ -151,7 +147,7 @@ describe("promptCommandsFor", () => {
name: "model",
argument: "",
});
- expect(formatPromptCommandHelp(remote)).toContain("/vc:login");
+ expect(formatPromptCommandHelp(remote)).not.toContain("/vc:login");
expect(formatPromptCommandHelp(remote)).not.toContain("/vc:auth");
expect(formatPromptCommandHelp(remote)).not.toContain("/model");
});
diff --git a/packages/eve/src/cli/dev/tui/prompt-commands.ts b/packages/eve/src/cli/dev/tui/prompt-commands.ts
index 93f42d646..f345c762c 100644
--- a/packages/eve/src/cli/dev/tui/prompt-commands.ts
+++ b/packages/eve/src/cli/dev/tui/prompt-commands.ts
@@ -1,4 +1,4 @@
-export type PromptCommandExtensionName = "model" | "add" | "deploy" | "vc:install" | "vc:login";
+export type PromptCommandExtensionName = "login" | "model" | "add" | "deploy";
type PromptCommandTarget = "local" | "remote";
@@ -95,25 +95,17 @@ const PROMPT_COMMAND_DEFINITIONS = [
targets: ["local", "remote"],
},
{
- name: "vc:install",
+ name: "login",
aliases: [],
- description: "Install the Vercel CLI",
+ description: "Connect a model provider",
takesArgument: false,
- build: () => ({ type: "extension", name: "vc:install", argument: "" }),
- targets: ["local", "remote"],
- },
- {
- name: "vc:login",
- aliases: [],
- description: "Authenticate with Vercel",
- takesArgument: false,
- build: () => ({ type: "extension", name: "vc:login", argument: "" }),
- targets: ["local", "remote"],
+ build: () => ({ type: "extension", name: "login", argument: "" }),
+ targets: ["local"],
},
{
name: "model",
aliases: [],
- description: "Configure the agent's model and provider",
+ description: "Choose a model and its settings",
argumentHint: "[provider/model]",
takesArgument: true,
build: (argument) => ({ type: "extension", name: "model", argument }),
diff --git a/packages/eve/src/cli/dev/tui/prompt-placeholder.test.ts b/packages/eve/src/cli/dev/tui/prompt-placeholder.test.ts
deleted file mode 100644
index ee4782a52..000000000
--- a/packages/eve/src/cli/dev/tui/prompt-placeholder.test.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- PROMPT_PLACEHOLDER_MESSAGES,
- promptPlaceholder,
- promptPlaceholderCycleMs,
-} from "./prompt-placeholder.js";
-
-describe("promptPlaceholder", () => {
- it("holds each message for one cycle and rotates through the whole set", () => {
- expect(promptPlaceholder(0)).toBe(PROMPT_PLACEHOLDER_MESSAGES[0]);
- expect(promptPlaceholder(promptPlaceholderCycleMs - 1)).toBe(PROMPT_PLACEHOLDER_MESSAGES[0]);
- expect(promptPlaceholder(promptPlaceholderCycleMs)).toBe(PROMPT_PLACEHOLDER_MESSAGES[1]);
- expect(promptPlaceholder(promptPlaceholderCycleMs * PROMPT_PLACEHOLDER_MESSAGES.length)).toBe(
- PROMPT_PLACEHOLDER_MESSAGES[0],
- );
- });
-
- it("clamps a negative clock to the first message", () => {
- expect(promptPlaceholder(-100)).toBe(PROMPT_PLACEHOLDER_MESSAGES[0]);
- });
-});
diff --git a/packages/eve/src/cli/dev/tui/prompt-placeholder.ts b/packages/eve/src/cli/dev/tui/prompt-placeholder.ts
deleted file mode 100644
index 66b10d3f1..000000000
--- a/packages/eve/src/cli/dev/tui/prompt-placeholder.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/**
- * The empty prompt's rotating invitation, written in the agent's own voice
- * ("my capabilities") since the prompt is a message to it. Messages point at
- * things an eve agent can actually do out of the box, so an idle prompt
- * doubles as a hint surface. The caret-blink repaint keeps the rotation
- * moving without its own timer.
- */
-
-export const PROMPT_PLACEHOLDER_MESSAGES: readonly string[] = [
- "Ask about my capabilities",
- "Have me explore the workspace",
- "Refine my instructions",
-];
-
-/** How long each message holds before the rotation advances. */
-export const promptPlaceholderCycleMs = 6_000;
-
-/** Picks the message for the given time since the renderer started. */
-export function promptPlaceholder(elapsedMs: number): string {
- const index = Math.floor(Math.max(0, elapsedMs) / promptPlaceholderCycleMs);
- return PROMPT_PLACEHOLDER_MESSAGES[index % PROMPT_PLACEHOLDER_MESSAGES.length]!;
-}
diff --git a/packages/eve/src/cli/dev/tui/question-panel.test.ts b/packages/eve/src/cli/dev/tui/question-panel.test.ts
index 1037e0c4f..e7d36086d 100644
--- a/packages/eve/src/cli/dev/tui/question-panel.test.ts
+++ b/packages/eve/src/cli/dev/tui/question-panel.test.ts
@@ -31,16 +31,15 @@ function render(state: {
}
describe("renderQuestionPanel", () => {
- it("opens with the rule hugging the prompt and closes on the dismiss hint", () => {
+ it("opens with a borderless prompt and closes on the dismiss hint", () => {
const rows = render({ cursor: 0 });
- expect(rows[0]).toBe("▔".repeat(60));
+ expect(rows[0]).toBe(" What type of options would you like to see?");
expect(rows).toContain(" What type of options would you like to see?");
- expect(rows.find((row) => row.includes("1. Available Tools"))).toContain("▶");
+ expect(rows.find((row) => row.includes("1. Available Tools"))).toContain("›");
expect(rows).toContain(" See 4 tools I can use");
expect(rows).toContain(" 2. Connected Services");
- // The rule hugs the question; the panel closes on its one quiet hint.
- expect(rows[1]).toBe(" What type of options would you like to see?");
+ expect(rows[1]).toBe("");
expect(rows.at(-1)).toBe(" Esc to dismiss");
});
@@ -48,9 +47,9 @@ describe("renderQuestionPanel", () => {
const rows = render({ cursor: 1 });
const selected = rows.find((row) => row.includes("Connected Services"));
- expect(selected).toContain(" ▶ 2. Connected Services ");
+ expect(selected).toContain(" › 2. Connected Services ");
expect(selected).toContain("↵");
- expect(rows.find((row) => row.includes("Available Tools"))).not.toContain("▶");
+ expect(rows.find((row) => row.includes("Available Tools"))).not.toContain("›");
});
it("keeps every row's number and label in the same columns as the cursor moves", () => {
diff --git a/packages/eve/src/cli/dev/tui/question-panel.ts b/packages/eve/src/cli/dev/tui/question-panel.ts
index 22054f8ee..e5a4fc904 100644
--- a/packages/eve/src/cli/dev/tui/question-panel.ts
+++ b/packages/eve/src/cli/dev/tui/question-panel.ts
@@ -30,7 +30,7 @@ export interface QuestionPanelState {
/** Rows under the cursor paint like the setup panel's selected option. */
function selectedRow(text: string, theme: Theme): string {
const c = theme.colors;
- return `${c.inverse(c.blue(` ${theme.glyph.selectedPointer} ${text} `))} ${c.dim("↵")}`;
+ return `${c.bold(` ${theme.glyph.selectedPointer} ${text}`)} ${c.dim("↵")}`;
}
export function renderQuestionPanel(
@@ -41,7 +41,7 @@ export function renderQuestionPanel(
const c = theme.colors;
const g = theme.glyph;
// The rule hugs the question — no blank row between them.
- const rows: string[] = [c.dim(g.hrule.repeat(Math.max(1, width)))];
+ const rows: string[] = [];
// The prompt is model-authored and can span paragraphs. Embedded newlines
// MUST split before width-wrapping: a row that secretly holds newlines
diff --git a/packages/eve/src/cli/dev/tui/registry-result-message.test.ts b/packages/eve/src/cli/dev/tui/registry-result-message.test.ts
index ea4c51a54..313c4e71c 100644
--- a/packages/eve/src/cli/dev/tui/registry-result-message.test.ts
+++ b/packages/eve/src/cli/dev/tui/registry-result-message.test.ts
@@ -17,7 +17,7 @@ describe("formatRegistrySessionResult", () => {
failures: [
{
title: "Slack",
- message: "Vercel CLI is not authenticated.\nRun /vc:login, then try again.",
+ message: "Vercel CLI is not authenticated.\nRun /deploy, then try again.",
},
],
}),
@@ -30,7 +30,7 @@ describe("formatRegistrySessionResult", () => {
" Configured MCP connection.\n\n" +
" ⨯ Slack\n" +
" Vercel CLI is not authenticated.\n" +
- " Run /vc:login, then try again.",
+ " Run /deploy, then try again.",
);
});
diff --git a/packages/eve/src/cli/dev/tui/remote-auth-command.ts b/packages/eve/src/cli/dev/tui/remote-auth-command.ts
deleted file mode 100644
index b9dcd79f8..000000000
--- a/packages/eve/src/cli/dev/tui/remote-auth-command.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-import { WizardCancelledError } from "#setup/step.js";
-
-import { createTuiPrompter } from "./tui-prompter.js";
-import { runRemoteAuthFlow, type RemoteAuthFlow } from "./remote-auth.js";
-import { describeRemoteAuthCompletedMutations } from "./remote-auth-result.js";
-import type { RemoteConnectionController, RemoteConnectionState } from "./remote-connection.js";
-import type { SetupFlowPrompterRenderer, SetupFlowRenderer } from "./setup-flow.js";
-import { remoteHost } from "./target.js";
-
-interface RemoteAuthCommandInput {
- readonly connection: RemoteConnectionController;
- readonly flow?: RemoteAuthFlow;
- readonly renderer: SetupFlowRenderer;
-}
-
-function shouldConfigureTrustedSources(connection: RemoteConnectionState): boolean {
- switch (connection.state) {
- case "auth-required":
- case "auth-failed":
- return connection.challenge.kind === "vercel-deployment-protection";
- case "unavailable":
- return connection.failure.code === "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH";
- case "checking":
- case "authenticating":
- case "ready":
- return false;
- }
-}
-
-function unavailableAfterAuthentication(host: string, message: string): string {
- const [reason = message, ...details] = message.split(/\n\s*\n/u);
- const sentence = /[.!?]$/u.test(reason.trim()) ? reason.trim() : `${reason.trim()}.`;
- return [
- `Authentication was refreshed, but ${host} is unavailable: ${sentence}`,
- ...details.map((detail) => detail.trim()).filter((detail) => detail.length > 0),
- ].join("\n\n");
-}
-
-function mutedRenderer(
- renderer: SetupFlowPrompterRenderer,
- isMuted: () => boolean,
-): SetupFlowPrompterRenderer {
- return {
- readSelect: (options) =>
- isMuted() ? Promise.resolve(undefined) : renderer.readSelect(options),
- readEditableSelect: (options) =>
- isMuted() ? Promise.resolve(undefined) : renderer.readEditableSelect(options),
- readText: (options) => (isMuted() ? Promise.resolve(undefined) : renderer.readText(options)),
- readAcknowledge: (options) =>
- isMuted() ? Promise.resolve() : renderer.readAcknowledge(options),
- readChoice: (options) =>
- isMuted()
- ? { choice: Promise.resolve(undefined), close: () => {} }
- : renderer.readChoice(options),
- setStatus: (text) => {
- if (!isMuted()) renderer.setStatus(text);
- },
- renderLine: (text, tone) => {
- if (!isMuted() || tone === "warning" || tone === "error") {
- renderer.renderLine(text, tone);
- }
- },
- renderOutput: (text) => {
- if (!isMuted()) renderer.renderOutput(text);
- },
- withInheritedStdio: (task) => renderer.withInheritedStdio(task),
- withExclusiveTerminal: (task) =>
- renderer.withExclusiveTerminal?.(task) ?? renderer.withInheritedStdio(task),
- };
-}
-
-/** Runs remote `/vc:login` through one TUI panel, connection operation, and auth flow. */
-export async function runRemoteAuthCommand(input: RemoteAuthCommandInput): Promise<string> {
- // The pulsing square, matching /vc:install, /vc:login, and /model.
- input.renderer.begin("Authenticate via Vercel OIDC", "pulse");
- let preserveFlowDiagnostics = true;
- let interrupted = false;
- const controller = new AbortController();
- const interrupt = input.renderer.waitForInterrupt();
- const target = input.connection.current().target;
- try {
- const runFlow = input.flow ?? runRemoteAuthFlow;
- const configureTrustedSources = shouldConfigureTrustedSources(
- input.connection.current().connection,
- );
- const prompter = createTuiPrompter(mutedRenderer(input.renderer, () => interrupted));
- const execution = input.connection.authenticate(async (signal) => {
- const result = await runFlow({
- workspaceRoot: target.workspaceRoot,
- serverUrl: target.serverUrl,
- configureTrustedSources,
- prompter,
- signal,
- });
- preserveFlowDiagnostics = result.kind === "failed";
- return result;
- }, controller.signal);
- const first = await Promise.race([
- execution.then((outcome) => ({ kind: "completed", outcome }) as const),
- interrupt.promise.then(() => ({ kind: "interrupted" }) as const),
- ]);
- if (first.kind === "interrupted") {
- interrupted = true;
- preserveFlowDiagnostics = true;
- controller.abort(new WizardCancelledError());
- }
- const outcome = first.kind === "completed" ? first.outcome : await execution;
- switch (outcome.kind) {
- case "authenticated":
- return `Authenticated ${remoteHost(target)} via Vercel OIDC.`;
- case "cancelled": {
- if (interrupted) {
- const completed = describeRemoteAuthCompletedMutations(outcome.completedMutations);
- return completed.length === 0
- ? "/vc:login interrupted."
- : `/vc:login interrupted. Completed before interruption: ${completed.join(", ")}.`;
- }
- return outcome.completedMutations.some((mutation) => mutation.kind === "vercel-login")
- ? "/vc:login dismissed after logging in to Vercel."
- : "/vc:login dismissed.";
- }
- case "failed":
- return outcome.message;
- case "unavailable":
- return unavailableAfterAuthentication(remoteHost(target), outcome.failure.message);
- }
- } finally {
- interrupt.dispose();
- input.renderer.setStatus(undefined);
- input.renderer.end({ preserveDiagnostics: preserveFlowDiagnostics });
- }
-}
diff --git a/packages/eve/src/cli/dev/tui/remote-auth-result.ts b/packages/eve/src/cli/dev/tui/remote-auth-result.ts
index c726233b6..50731b734 100644
--- a/packages/eve/src/cli/dev/tui/remote-auth-result.ts
+++ b/packages/eve/src/cli/dev/tui/remote-auth-result.ts
@@ -55,7 +55,8 @@ export function formatRemoteAuthChallengeMessage(serverUrl: string): string {
`Vercel Deployment Protection blocked the request to ${serverUrl}.`,
"",
"To access the deployment from `eve dev`, do one of:",
- " • Run `/vc:login` to authenticate this remote via Vercel OIDC.",
+ " • Reconnect with an existing Vercel CLI session authorized for this",
+ " deployment to configure Trusted Sources when prompted.",
" • Set VERCEL_AUTOMATION_BYPASS_SECRET to a Protection Bypass for",
" Automation token (Project Settings → Deployment Protection).",
" • Disable Deployment Protection on the target deployment.",
diff --git a/packages/eve/src/cli/dev/tui/remote-auth.test.ts b/packages/eve/src/cli/dev/tui/remote-auth.test.ts
index ee159958c..4785f2bb9 100644
--- a/packages/eve/src/cli/dev/tui/remote-auth.test.ts
+++ b/packages/eve/src/cli/dev/tui/remote-auth.test.ts
@@ -214,24 +214,16 @@ describe("runRemoteAuthFlow", () => {
});
});
- it("re-authenticates and resolves again when access is initially forbidden", async () => {
+ it("does not open another login when remote access is forbidden", async () => {
const harness = createHarness({
- logins: [{ kind: "already" }, { kind: "logged-in" }],
- deployments: [{ kind: "forbidden" }, { kind: "resolved", target: TARGET }],
- });
-
- await expect(harness.run()).resolves.toMatchObject({
- kind: "prepared",
- completedMutations: [{ kind: "vercel-login" }],
- });
- expect(harness.operations).toEqual(["login", "deployment", "login", "deployment", "token"]);
- expect(harness.deps.resolveVercelDeployment).toHaveBeenCalledTimes(2);
- expect(harness.deps.runLoginFlow).toHaveBeenNthCalledWith(2, {
- appRoot: WORKSPACE_ROOT,
- force: true,
- prompter: harness.prompter,
- signal: undefined,
+ logins: [{ kind: "already" }],
+ deployments: [{ kind: "forbidden" }],
});
+ await expect(harness.run()).resolves.toMatchObject({ kind: "failed" });
+ expect(harness.operations).toEqual(["login", "deployment"]);
+ expect(harness.deps.runLoginFlow).toHaveBeenCalledWith(
+ expect.objectContaining({ allowLogin: false }),
+ );
});
it("gets Trusted Sources consent, applies it, then requests the session token", async () => {
@@ -317,7 +309,7 @@ describe("runRemoteAuthFlow", () => {
logins: [{ kind: "already" }, { kind: "already" }],
deployments: [{ kind: "forbidden" }, { kind: "forbidden" }],
},
- message: "Re-authenticate",
+ message: "Check your team access",
},
{
name: "deployment verification",
@@ -374,7 +366,7 @@ describe("formatRemoteAuthChallengeMessage", () => {
const message = formatRemoteAuthChallengeMessage("https://example.vercel.app");
expect(message).toContain("https://example.vercel.app");
- expect(message).toContain("/vc:login");
+ expect(message).toContain("existing Vercel CLI session");
expect(message).toContain("VERCEL_AUTOMATION_BYPASS_SECRET");
expect(message).toContain("Disable Deployment Protection");
expect(message).toContain("https://vercel.com/docs/deployment-protection");
diff --git a/packages/eve/src/cli/dev/tui/remote-auth.ts b/packages/eve/src/cli/dev/tui/remote-auth.ts
index b431d5b62..50d45cc6d 100644
--- a/packages/eve/src/cli/dev/tui/remote-auth.ts
+++ b/packages/eve/src/cli/dev/tui/remote-auth.ts
@@ -69,14 +69,14 @@ function loginFailure(result: LoginFlowResult): RemoteAuthPreparation | undefine
return cancelled();
case "cli-missing":
return failed(
- "The Vercel CLI is not installed. Install it with `npm i -g vercel@latest`, then retry /vc:login.",
+ "The Vercel CLI is not installed. Install it with `npm i -g vercel@latest`, then reconnect.",
);
case "failed":
- return failed("Vercel login did not complete. Retry /vc:login.");
- case "unavailable":
return failed(
- "Vercel could not verify your account. Check your connection, then retry /vc:login.",
+ "Vercel login did not complete. Connect your Vercel account when deploying the local project, then reconnect.",
);
+ case "unavailable":
+ return failed("Vercel could not verify your account. Check your connection, then reconnect.");
}
}
@@ -124,7 +124,12 @@ export async function runRemoteAuthFlow(input: {
try {
// Authenticate first so the resolve runs under real credentials. When the
// user is already logged in this is a no-op and shows no dialogue.
- const login = await deps.runLoginFlow({ appRoot: workspaceRoot, prompter, signal });
+ const login = await deps.runLoginFlow({
+ appRoot: workspaceRoot,
+ prompter,
+ signal,
+ allowLogin: false,
+ });
const loginOutcome = loginFailure(login);
if (loginOutcome !== undefined) return loginOutcome;
if (login.kind === "logged-in") completedMutations.push({ kind: "vercel-login" });
@@ -132,19 +137,6 @@ export async function runRemoteAuthFlow(input: {
// Prefer direct host resolution. If the active Vercel scope cannot see the
// deployment, the picker supplies an explicit team scope.
let resolution = await deps.resolveVercelDeployment({ workspaceRoot, host, signal });
- if (resolution.kind === "forbidden") {
- const reauth = await deps.runLoginFlow({
- appRoot: workspaceRoot,
- force: true,
- prompter,
- signal,
- });
- const reauthOutcome = loginFailure(reauth);
- if (reauthOutcome !== undefined) return reauthOutcome;
- if (reauth.kind === "logged-in") completedMutations.push({ kind: "vercel-login" });
- signal?.throwIfAborted();
- resolution = await deps.resolveVercelDeployment({ workspaceRoot, host, signal });
- }
if (resolution.kind === "not-found") {
try {
const scope = await selectVercelDeploymentScope(
@@ -175,7 +167,7 @@ export async function runRemoteAuthFlow(input: {
return cancelled(completedMutations);
case "forbidden":
return failed(
- `Could not access ${host}. Re-authenticate (for example to complete a team's SSO), then retry /vc:login.`,
+ `Could not access ${host}. Check your team access and SSO, then reconnect.`,
completedMutations,
);
case "not-found":
diff --git a/packages/eve/src/cli/dev/tui/remote-startup.ts b/packages/eve/src/cli/dev/tui/remote-startup.ts
new file mode 100644
index 000000000..2acf22ce6
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/remote-startup.ts
@@ -0,0 +1,56 @@
+import { WizardCancelledError } from "#setup/step.js";
+
+import type { RemoteAuthFlow } from "./remote-auth.js";
+import type { RemoteAuthCompletion, RemoteConnectionController } from "./remote-connection.js";
+import type { SetupFlowRenderer } from "./setup-flow.js";
+import { createTuiPrompter } from "./tui-prompter.js";
+
+/** Offers consented deployment access repair after a remote startup challenge. */
+export async function prepareRemoteTuiAccess(input: {
+ connection: RemoteConnectionController;
+ renderer: SetupFlowRenderer;
+ signal?: AbortSignal;
+ runAuthFlow?: RemoteAuthFlow;
+}): Promise<RemoteAuthCompletion | undefined> {
+ const { connection, renderer } = input;
+ const { connection: state, target } = connection.current();
+ if (
+ state.state !== "auth-required" ||
+ state.challenge.kind !== "vercel-deployment-protection" ||
+ input.signal?.aborted
+ ) {
+ return;
+ }
+
+ const controller = new AbortController();
+ const signal = input.signal
+ ? AbortSignal.any([input.signal, controller.signal])
+ : controller.signal;
+ renderer.begin("Deployment access");
+ // Install the idle trap before the flow opens a question and takes ownership of input.
+ const interrupt = renderer.waitForInterrupt();
+ try {
+ const execution = connection.authenticate(async (signal) => {
+ const runAuthFlow = input.runAuthFlow ?? (await import("./remote-auth.js")).runRemoteAuthFlow;
+ if (signal.aborted) return { kind: "cancelled", completedMutations: [] };
+ return runAuthFlow({
+ workspaceRoot: target.workspaceRoot,
+ serverUrl: target.serverUrl,
+ configureTrustedSources: true,
+ prompter: createTuiPrompter(renderer),
+ signal,
+ });
+ }, signal);
+ const outcome = await Promise.race([
+ execution.then((result) => ({ kind: "settled" as const, result })),
+ interrupt.promise.then(() => ({ kind: "interrupted" as const })),
+ ]);
+ if (outcome.kind === "settled") return outcome.result;
+ controller.abort(new WizardCancelledError());
+ return await execution;
+ } finally {
+ interrupt.dispose();
+ renderer.setStatus(undefined);
+ renderer.end({ preserveDiagnostics: false });
+ }
+}
diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.ts
index 2725863e9..7ec2d2f17 100644
--- a/packages/eve/src/cli/dev/tui/runner.test.ts
+++ b/packages/eve/src/cli/dev/tui/runner.test.ts
@@ -886,7 +886,7 @@ describe("EveTUIRunner idle session follow", () => {
await expect(runner.run()).resolves.toBeUndefined();
expect(handle).toHaveBeenCalledWith(
- { type: "extension", name: "model", argument: "" },
+ { type: "extension", name: "login", argument: "" },
expect.objectContaining({ initialModelStep: "provider" }),
);
expect(renderIdleStream).not.toHaveBeenCalled();
@@ -2056,6 +2056,43 @@ describe("EveTUIRunner initial input", () => {
);
});
+ it.each(["cancelled", "error"] as const)(
+ "keeps startup input through login and restores queued messages on %s",
+ async (result) => {
+ const login = createDeferred<void>();
+ const startup = {
+ headerTip: "/help",
+ finish: vi.fn(() => ({ draft: "still editing", queuedPrompt: "Hello Alice" })),
+ };
+ const handle = vi.fn(async () => {
+ await login.promise;
+ return result === "cancelled" ? { cancelled: true as const } : { tone: "error" as const };
+ });
+ const session = stubSession();
+ vi.spyOn(session, "send");
+ const renderer = fakeRenderer({ setupFlow: createFakeSetupFlowRenderer() });
+ const runner = new EveTUIRunner({
+ session,
+ renderer,
+ startup,
+ appRoot: "/tmp/agent",
+ onboard: true,
+ bootDetections: [],
+ promptCommandHandler: { handle },
+ });
+ const run = runner.run();
+ await vi.waitFor(() => expect(handle).toHaveBeenCalledOnce());
+ expect(startup.finish).not.toHaveBeenCalled();
+ login.resolve();
+ await run;
+ expect(startup.finish).toHaveBeenCalledOnce();
+ expect(session.send).not.toHaveBeenCalled();
+ expect(renderer.readPrompt).toHaveBeenCalledWith(
+ expect.objectContaining({ initialDraft: "Hello Alice\n\nstill editing" }),
+ );
+ },
+ );
+
it("sends startup messages queued while the agent builds", async () => {
const client = stubClient();
vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);
@@ -3092,6 +3129,7 @@ describe("EveTUIRunner remote authentication", () => {
client: Client;
flow: RemoteAuthFlow;
renderer?: Partial<AgentTUIRenderer>;
+ initialInput?: string;
resolveDeployment?: NonNullable<RemoteConnectionControllerOptions["resolveDeployment"]>;
}): Promise<void> {
await new EveTUIRunner({
@@ -3102,13 +3140,13 @@ describe("EveTUIRunner remote authentication", () => {
availablePromptCommands: promptCommandsFor("remote"),
promptCommandHandler: createPromptCommandHandler({
target,
- remoteAuthFlow: input.flow,
}),
- remote: remoteOptions(input.resolveDeployment),
+ remote: { ...remoteOptions(input.resolveDeployment), runAuthFlow: input.flow },
+ initialInput: input.initialInput,
}).run();
}
- it("runs /vc:login after an unresolved host returns an authentication challenge", async () => {
+ it("does not open login after a remote authentication challenge", async () => {
const client = stubClient();
const order: string[] = [];
let infoCalls = 0;
@@ -3137,78 +3175,184 @@ describe("EveTUIRunner remote authentication", () => {
},
});
- expect(order).toEqual(["info", "login", "info"]);
- expect(commandInvocations).toEqual([{ text: "/vc:login", status: undefined }]);
+ expect(order).toEqual(["info"]);
+ expect(commandInvocations).toEqual([]);
});
- it("runs /vc:login once at startup after Vercel redirects to its SSO challenge", async () => {
- const client = stubClient();
- vi.spyOn(client, "info")
- .mockRejectedValueOnce(new ClientError(302, "Redirecting...", { location: VERCEL_SSO_URL }))
- .mockResolvedValueOnce(AGENT_INFO);
- const commandInvocations: Array<{ text: string; status: "failed" | undefined }> = [];
- const flow = successfulAuth();
-
- await runRemoteAuth({
- client,
- flow,
- renderer: {
- renderCommandInvocation: (text, status) => commandInvocations.push({ text, status }),
- },
- });
+ it.each([
+ new ClientError(302, "Redirecting...", { location: VERCEL_SSO_URL }),
+ new ClientError(403, "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH"),
+ ])(
+ "repairs Deployment Protection at startup without echoing a login command (%s)",
+ async (challenge) => {
+ const client = stubClient();
+ vi.spyOn(client, "info").mockRejectedValueOnce(challenge).mockResolvedValueOnce(AGENT_INFO);
+ const commandInvocations: Array<{ text: string; status: "failed" | undefined }> = [];
+ const flow = successfulAuth();
+ const statuses: string[] = [];
+ const renderAgentHeader = vi.fn();
+
+ await runRemoteAuth({
+ client,
+ flow,
+ renderer: {
+ renderCommandInvocation: (text, status) => commandInvocations.push({ text, status }),
+ setRemoteConnectionStatus: (snapshot) => statuses.push(snapshot.connection.state),
+ renderAgentHeader,
+ },
+ });
- expect(flow).toHaveBeenCalledOnce();
- expect(flow).toHaveBeenCalledWith(expect.objectContaining({ configureTrustedSources: true }));
- expect(commandInvocations).toEqual([{ text: "/vc:login", status: undefined }]);
- });
+ expect(flow).toHaveBeenCalledWith(
+ expect.objectContaining({
+ configureTrustedSources: true,
+ workspaceRoot: target.workspaceRoot,
+ serverUrl: target.serverUrl,
+ }),
+ );
+ expect(client.info).toHaveBeenCalledTimes(2);
+ expect(statuses).toContain("authenticating");
+ expect(statuses.at(-1)).toBe("ready");
+ expect(renderAgentHeader).toHaveBeenLastCalledWith(
+ expect.objectContaining({ info: AGENT_INFO }),
+ );
+ expect(commandInvocations).toEqual([]);
+ },
+ );
- it("requests Trusted Sources repair for an environment mismatch", async () => {
+ it("does not open setup when existing remote credentials already work", async () => {
const client = stubClient();
- const mismatch = new ClientError(
- 403,
- "The caller environment is not permitted.\n\n" +
- "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH\n\niad1::request-id",
- );
- vi.spyOn(client, "info").mockRejectedValueOnce(mismatch).mockResolvedValueOnce(AGENT_INFO);
+ vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);
const flow = successfulAuth();
-
- await runRemoteAuth({ client, flow });
-
- expect(flow).toHaveBeenCalledWith(expect.objectContaining({ configureTrustedSources: true }));
+ const setupFlow = idleSetupFlow();
+ await runRemoteAuth({ client, flow, renderer: { setupFlow } });
+ expect(flow).not.toHaveBeenCalled();
+ expect(setupFlow.begin).not.toHaveBeenCalled();
});
- it("renders a failed automatic /vc:login as one command result without the request id", async () => {
+ it("sends the first message after the repaired connection is verified", async () => {
const client = stubClient();
+ const order: string[] = [];
vi.spyOn(client, "info")
- .mockRejectedValueOnce(unauthorized())
- .mockRejectedValueOnce(
- new ClientError(
- 403,
- "Your trusted sources OIDC token's environment is not permitted to access this deployment\n\n" +
- "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH\n\niad1::zgc5p-1781730251155-85842c28901b",
- ),
+ .mockRejectedValueOnce(new ClientError(302, "Redirecting...", { location: VERCEL_SSO_URL }))
+ .mockImplementationOnce(async () => {
+ order.push("verified");
+ return AGENT_INFO;
+ });
+ const session = sessionYielding([{ type: "session.waiting" }]);
+ const renderer = fakeRenderer({
+ setupFlow: idleSetupFlow(),
+ readPrompt: vi
+ .fn()
+ .mockImplementationOnce(async () => {
+ order.push("prompt");
+ return "Hello Alice";
+ })
+ .mockResolvedValueOnce(undefined),
+ });
+ await new EveTUIRunner({
+ session,
+ client,
+ renderer,
+ serverUrl: target.serverUrl,
+ remote: { ...remoteOptions(), runAuthFlow: successfulAuth() },
+ }).run();
+ expect(order).toEqual(["verified", "prompt"]);
+ expect(session.send).toHaveBeenCalledWith("Hello Alice", expect.any(Object));
+ expect(renderer.renderStream).toHaveBeenCalledOnce();
+ });
+
+ it.each(["cancelled", "failed"] as const)(
+ "preserves the draft and closes %s remote setup without retrying",
+ async (kind) => {
+ const client = stubClient();
+ vi.spyOn(client, "info").mockRejectedValue(
+ new ClientError(302, "Redirecting...", { location: VERCEL_SSO_URL }),
);
- const commandInvocations: Array<{ text: string; status: "failed" | undefined }> = [];
- const commandResults: string[] = [];
+ const flow = vi.fn<RemoteAuthFlow>(async () =>
+ kind === "cancelled"
+ ? { kind: "cancelled", completedMutations: [] }
+ : {
+ kind: "failed",
+ message:
+ "Could not update Trusted Sources. Check project permissions, then reconnect.",
+ completedMutations: [],
+ },
+ );
+ const setupFlow = idleSetupFlow();
+ const readPrompt = vi.fn(async () => undefined);
+ const renderCommandResult = vi.fn();
+ await runRemoteAuth({
+ client,
+ flow,
+ initialInput: "Hello Alice",
+ renderer: { setupFlow, readPrompt, renderCommandResult },
+ });
+ expect(flow).toHaveBeenCalledOnce();
+ expect(client.info).toHaveBeenCalledOnce();
+ expect(setupFlow.end).toHaveBeenCalledWith({ preserveDiagnostics: false });
+ expect(readPrompt).toHaveBeenCalledWith(
+ expect.objectContaining({ initialDraft: "Hello Alice" }),
+ );
+ if (kind === "cancelled") expect(renderCommandResult).not.toHaveBeenCalled();
+ else
+ expect(renderCommandResult).toHaveBeenCalledWith(
+ expect.stringContaining("Check project permissions"),
+ "error",
+ );
+ },
+ );
+
+ it("reports a failed access check after applying Trusted Sources instead of declaring success", async () => {
+ const client = stubClient();
+ vi.spyOn(client, "info").mockRejectedValue(
+ new ClientError(302, "Redirecting...", { location: VERCEL_SSO_URL }),
+ );
const flow = successfulAuth([
- { kind: "trusted-sources-updated", targetProjectName: "remote-agent" },
+ { kind: "trusted-sources-updated", targetProjectName: "inbound" },
]);
-
+ const renderCommandResult = vi.fn();
+ const statuses: string[] = [];
await runRemoteAuth({
client,
flow,
renderer: {
- renderCommandInvocation: (text, status) => commandInvocations.push({ text, status }),
- renderCommandResult: (message) => commandResults.push(message),
+ renderCommandResult,
+ setRemoteConnectionStatus: (snapshot) => statuses.push(snapshot.connection.state),
},
});
+ expect(flow).toHaveBeenCalledOnce();
+ expect(client.info).toHaveBeenCalledTimes(2);
+ expect(statuses.at(-1)).toBe("auth-failed");
+ expect(renderCommandResult).toHaveBeenCalledWith(
+ expect.stringContaining("updated Trusted Sources for inbound"),
+ "error",
+ );
+ });
- expect(commandInvocations).toEqual([{ text: "/vc:login", status: "failed" }]);
- expect(commandResults).toEqual([
- "Authentication was refreshed, but vpoke.playground-vercel.tools is unavailable: " +
- "Your trusted sources OIDC token's environment is not permitted to access this deployment.\n\n" +
- "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH Completed before the failure: updated Trusted Sources for remote-agent.",
- ]);
+ it("aborts remote setup during an idle wait and waits for cleanup before releasing input", async () => {
+ const client = stubClient();
+ vi.spyOn(client, "info").mockRejectedValue(
+ new ClientError(302, "Redirecting...", { location: VERCEL_SSO_URL }),
+ );
+ const interrupt = Promise.withResolvers<"escape" | "ctrl-c">();
+ let cleanedUp = false;
+ const flow = vi.fn<RemoteAuthFlow>(async ({ signal }) => {
+ interrupt.resolve("escape");
+ await new Promise<void>((resolve) =>
+ signal!.addEventListener("abort", () => resolve(), { once: true }),
+ );
+ cleanedUp = true;
+ return { kind: "cancelled", completedMutations: [] };
+ });
+ const dispose = vi.fn();
+ const setupFlow = createFakeSetupFlowRenderer({
+ waitForInterrupt: () => ({ promise: interrupt.promise, dispose }),
+ end: () => expect(cleanedUp).toBe(true),
+ });
+ await runRemoteAuth({ client, flow, renderer: { setupFlow } });
+ expect(cleanedUp).toBe(true);
+ expect(dispose).toHaveBeenCalledOnce();
+ expect(client.info).toHaveBeenCalledOnce();
});
it("does not start authentication for an ordinary remote HTTP failure", async () => {
@@ -3626,66 +3770,69 @@ describe("EveTUIRunner Vercel status line", () => {
expect(detectIdentity).toHaveBeenCalledTimes(2);
});
- it("refreshes agent info only after a model-access change", async () => {
- const runtimeRequests: Array<{ method: string; url: URL }> = [];
- vi.stubGlobal(
- "fetch",
- vi.fn(async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
- runtimeRequests.push({
- method: init?.method ?? "GET",
- url: new URL(
- typeof input === "string" ? input : input instanceof URL ? input : input.url,
- ),
- });
- return Response.json({ revision: "snapshot-a" });
- }),
- );
- const client = stubClient();
- const info = vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);
- const prompts: Array<string | undefined> = ["/deploy", "/model", undefined];
- const infoCallsAtPrompt: number[] = [];
- const renderer = fakeRenderer({
- readPrompt: vi.fn(async () => {
- infoCallsAtPrompt.push(info.mock.calls.length);
- return prompts.shift();
- }),
- });
- const deployOutcome: PromptCommandOutcome = {
- message: "Deployed.",
- effect: { kind: "deployed" },
- };
- const modelOutcome: PromptCommandOutcome = {
- message: "Connected to AI Gateway.",
- effect: { kind: "model-access-changed" },
- };
+ it.each([true, false])(
+ "refreshes agent info and only rebuilds when requested (reload: %s)",
+ async (reload) => {
+ const runtimeRequests: Array<{ method: string; url: URL }> = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
+ runtimeRequests.push({
+ method: init?.method ?? "GET",
+ url: new URL(
+ typeof input === "string" ? input : input instanceof URL ? input : input.url,
+ ),
+ });
+ return Response.json({ revision: "snapshot-a" });
+ }),
+ );
+ const client = stubClient();
+ const info = vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);
+ const prompts: Array<string | undefined> = ["/deploy", "/model", undefined];
+ const infoCallsAtPrompt: number[] = [];
+ const renderer = fakeRenderer({
+ readPrompt: vi.fn(async () => {
+ infoCallsAtPrompt.push(info.mock.calls.length);
+ return prompts.shift();
+ }),
+ });
+ const deployOutcome: PromptCommandOutcome = {
+ message: "Deployed.",
+ effect: { kind: "deployed" },
+ };
+ const modelOutcome: PromptCommandOutcome = {
+ message: "Connected to AI Gateway.",
+ effect: { kind: "model-access-changed", reload },
+ };
- const runner = new EveTUIRunner({
- session: stubSession(),
- client,
- renderer,
- serverUrl: "http://localhost:3000",
- name: "Weather Agent",
- appRoot: "/tmp/weather-agent",
- bootDetections: [],
- detectProjectIdentity: vi.fn(async () => undefined),
- promptCommandHandler: {
- handle: async (command) => (command.name === "model" ? modelOutcome : deployOutcome),
- },
- });
+ const runner = new EveTUIRunner({
+ session: stubSession(),
+ client,
+ renderer,
+ serverUrl: "http://localhost:3000",
+ name: "Weather Agent",
+ appRoot: "/tmp/weather-agent",
+ bootDetections: [],
+ detectProjectIdentity: vi.fn(async () => undefined),
+ promptCommandHandler: {
+ handle: async (command) => (command.name === "model" ? modelOutcome : deployOutcome),
+ },
+ });
- await runner.run();
+ await runner.run();
- expect(infoCallsAtPrompt).toEqual([1, 1, 2]);
- expect(info).toHaveBeenCalledTimes(2);
- expect(
- runtimeRequests.some(
- (request) =>
- request.method === "POST" &&
- request.url.pathname === "/eve/v1/dev/runtime-artifacts/rebuild" &&
- request.url.searchParams.get("force") === "1",
- ),
- ).toBe(true);
- });
+ expect(infoCallsAtPrompt).toEqual([1, 1, 2]);
+ expect(info).toHaveBeenCalledTimes(2);
+ expect(
+ runtimeRequests.some(
+ (request) =>
+ request.method === "POST" &&
+ request.url.pathname === "/eve/v1/dev/runtime-artifacts/rebuild" &&
+ request.url.searchParams.get("force") === "1",
+ ),
+ ).toBe(reload);
+ },
+ );
it("never pushes Vercel status for a remote --url session", async () => {
const setVercelStatus = vi.fn();
@@ -3838,10 +3985,18 @@ describe("EveTUIRunner boot setup detection", () => {
getVercelAuthStatus: vi.fn(async (): Promise<"authenticated"> => "authenticated"),
promptCommandHandler: {
handle: async (command) =>
- command.name === "model"
+ command.name === "login"
? {
message: "AI Gateway via API key selected.",
- effect: { kind: "model-access-changed" },
+ effect: {
+ kind: "model-access-changed",
+ reload: false,
+ model: {
+ id: "gpt-5",
+ routing: { kind: "gateway", target: "openai" },
+ endpoint: { kind: "gateway", connected: true, credential: "api-key" },
+ },
+ },
}
: { message: "/add dismissed." },
},
@@ -3860,186 +4015,6 @@ describe("EveTUIRunner boot setup detection", () => {
expect(warnings).toEqual(["1 setup issue: AI Gateway credentials · /model"]);
});
- it("runs initial onboarding as one-way model and registry phases", async () => {
- const order: string[] = [];
- const results: string[] = [];
- const stages: string[] = [];
- const handle = vi.fn(async (command: { name: string }) => {
- order.push(command.name);
- return command.name === "model"
- ? { message: "/model failed: provider unavailable", tone: "error" as const }
- : { message: `/${command.name} dismissed.` };
- });
- const renderer = fakeRenderer({
- readPrompt: vi.fn(async (options?: AgentTUISessionOptions) => {
- order.push("prompt");
- expect(options?.initialDraft).toBeUndefined();
- return undefined;
- }),
- renderCommandResult: (message) => results.push(message),
- setupFlow: createFakeSetupFlowRenderer(),
- });
- const runner = new EveTUIRunner({
- session: sessionYielding([]),
- renderer,
- name: "Weather Agent",
- appRoot: "/tmp/weather-agent",
- onboard: true,
- bootDetections: [],
- onOnboardingStep: ({ step }) => stages.push(step),
- onOnboardingTerminal: ({ step, result }) => stages.push(`${step}_${result}`),
- promptCommandHandler: { handle },
- });
-
- await runner.run();
-
- expect(order).toEqual(["model", "prompt"]);
- expect(stages).toEqual(["model_provider", "model_provider_error"]);
- expect(results).toContain("/model failed: provider unavailable");
- expect(handle).toHaveBeenCalledWith(
- { type: "extension", name: "model", argument: "" },
- expect.objectContaining({
- renderer,
- title: "Weather Agent",
- initialModelStep: "provider",
- keepSetupFlowOpen: true,
- setupFlowNavigation: {
- kind: "planner",
- activeStep: 0,
- firstNavigableStep: 1,
- steps: [
- { label: "Model", complete: false },
- { label: "Channels" },
- { label: "Integrations" },
- { label: "Review" },
- ],
- },
- }),
- );
- expect(handle).not.toHaveBeenCalledWith(
- { type: "extension", name: "add", argument: "" },
- expect.anything(),
- );
- });
-
- it("moves from Model to Channels and preserves diagnostics after a failed registry phase", async () => {
- const order: string[] = [];
- const stages: string[] = [];
- const end = vi.fn(() => order.push("end"));
- const handle = vi.fn(async (command: { name: string }) => {
- order.push(command.name);
- return command.name === "add"
- ? { message: "/add failed", tone: "error" as const }
- : { message: "model ready" };
- });
- const renderer = fakeRenderer({
- readPrompt: vi.fn(async () => {
- order.push("prompt");
- return undefined;
- }),
- setupFlow: createFakeSetupFlowRenderer({ end }),
- });
- const runner = new EveTUIRunner({
- session: sessionYielding([]),
- renderer,
- name: "Weather Agent",
- appRoot: "/tmp/weather-agent",
- onboard: true,
- bootDetections: [],
- onOnboardingStep: ({ step }) => stages.push(step),
- onOnboardingTerminal: ({ step, result }) => stages.push(`${step}_${result}`),
- promptCommandHandler: { handle },
- });
-
- await runner.run();
-
- expect(order).toEqual(["model", "add", "end", "prompt"]);
- expect(stages).toEqual(["model_provider", "registry_channels", "registry_channels_error"]);
- expect(end).toHaveBeenCalledWith({ preserveDiagnostics: true });
- expect(handle).toHaveBeenNthCalledWith(
- 2,
- { type: "extension", name: "add", argument: "" },
- expect.not.objectContaining({ setupFlowNavigation: expect.anything() }),
- );
- expect(handle).toHaveBeenNthCalledWith(
- 2,
- { type: "extension", name: "add", argument: "" },
- expect.objectContaining({
- registryPlannerContext: {
- prefixSteps: [{ label: "Model", complete: true }],
- reviewMessage: "Review your agent",
- primaryActionLabel: "Install and finish setup",
- emptyActionLabel: "Finish setup",
- },
- }),
- );
- });
-
- it("keeps the completed /add result after onboarding", async () => {
- const renderCommandInvocation = vi.fn();
- const renderCommandResult = vi.fn();
- const stages: string[] = [];
- const runner = new EveTUIRunner({
- session: sessionYielding([]),
- renderer: fakeRenderer({
- readPrompt: vi.fn(async () => undefined),
- renderCommandInvocation,
- renderCommandResult,
- setupFlow: createFakeSetupFlowRenderer(),
- }),
- name: "Weather Agent",
- appRoot: "/tmp/weather-agent",
- onboard: true,
- bootDetections: [],
- onOnboardingStep: ({ step }) => stages.push(step),
- onOnboardingTerminal: ({ step, result }) => stages.push(`${step}_${result}`),
- promptCommandHandler: {
- handle: async (command) =>
- command.name === "model"
- ? { message: "Model ready" }
- : { message: "Added Web Chat", tone: "success" as const },
- },
- });
-
- await runner.run();
-
- expect(stages).toEqual(["model_provider", "registry_channels", "registry_channels_completed"]);
- expect(renderCommandInvocation).toHaveBeenCalledWith("/add", undefined);
- expect(renderCommandResult).toHaveBeenCalledWith("Added Web Chat", "success");
- });
-
- it("does not render a detached /add dismissed result when onboarding is cancelled", async () => {
- const renderCommandResult = vi.fn();
- const stages: string[] = [];
- const renderer = fakeRenderer({
- readPrompt: vi.fn(async () => undefined),
- renderCommandResult,
- setupFlow: createFakeSetupFlowRenderer(),
- });
- const runner = new EveTUIRunner({
- session: sessionYielding([]),
- renderer,
- name: "Weather Agent",
- appRoot: "/tmp/weather-agent",
- onboard: true,
- bootDetections: [],
- onOnboardingStep: ({ step }) => stages.push(step),
- onOnboardingTerminal: ({ step, result }) => stages.push(`${step}_${result}`),
- getVercelAuthStatus: vi.fn(async () => "authenticated" as const),
- promptCommandHandler: {
- handle: async (command) =>
- command.name === "model"
- ? { message: "Model ready" }
- : { message: "/add dismissed.", cancelled: true as const },
- },
- });
-
- await runner.run();
-
- expect(stages).toEqual(["model_provider", "registry_channels", "registry_channels_cancelled"]);
- expect(renderCommandResult).not.toHaveBeenCalledWith("/add dismissed.", expect.anything());
- });
-
it("does not auto-open /model outside the prefilled onboarding launch", async () => {
const handle = vi.fn(async () => ({ message: "/model dismissed." }));
const runner = new EveTUIRunner({
@@ -4086,6 +4061,105 @@ describe("EveTUIRunner boot setup detection", () => {
expect(handle).not.toHaveBeenCalled();
});
+ it("releases the composer while /info is still pending and ignores its result after exit", async () => {
+ const refreshed = createDeferred<AgentInfoResult>();
+ const renderAgentHeader = vi.fn();
+ const renderCommandResult = vi.fn();
+ const renderSetupWarning = vi.fn();
+ const readPrompt = vi.fn(async () => undefined);
+ const setStartupPhase = vi.fn();
+ const { client, runner } = providerSetupRefreshRunner({
+ refreshInfo: () => refreshed.promise,
+ bootDetections: [],
+ renderer: {
+ renderAgentHeader,
+ renderCommandResult,
+ renderSetupWarning,
+ readPrompt,
+ setStartupPhase,
+ },
+ });
+ const run = runner.run();
+ await vi.waitFor(() => expect(readPrompt).toHaveBeenCalledOnce());
+ expect(client.info).toHaveBeenCalledTimes(2);
+ expect(renderCommandResult).toHaveBeenCalledOnce();
+ expect(renderSetupWarning).not.toHaveBeenCalled();
+ expect(setStartupPhase).toHaveBeenLastCalledWith(undefined);
+ await run;
+ const paints = renderAgentHeader.mock.calls.length;
+ refreshed.resolve(AGENT_INFO);
+ await Promise.resolve();
+ expect(renderAgentHeader).toHaveBeenCalledTimes(paints);
+ });
+
+ it("sends the first message while post-login info is pending", async () => {
+ const refreshed = createDeferred<AgentInfoResult>();
+ const client = stubClient();
+ vi.spyOn(client, "info")
+ .mockResolvedValueOnce(disconnectedGatewayInfo)
+ .mockImplementation(() => refreshed.promise);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => Response.json({ revision: "snapshot-a" })),
+ );
+ const session = sessionYielding([]);
+ const prompts = ["Hello", undefined];
+ const runner = new EveTUIRunner({
+ client,
+ session,
+ name: "Weather Agent",
+ serverUrl: "http://localhost:3000",
+ appRoot: "/tmp/weather-agent",
+ onboard: true,
+ bootDetections: [],
+ detectProjectIdentity: vi.fn(async () => undefined),
+ renderer: fakeRenderer({
+ readPrompt: vi.fn(async () => prompts.shift()),
+ setupFlow: createFakeSetupFlowRenderer(),
+ }),
+ promptCommandHandler: {
+ handle: async () => ({
+ message: "Connected.",
+ effect: {
+ kind: "model-access-changed",
+ reload: false,
+ model: {
+ id: "gpt-5",
+ routing: { kind: "gateway", target: "openai" },
+ endpoint: { kind: "gateway", connected: true, credential: "oauth", team: "alice" },
+ },
+ },
+ }),
+ },
+ });
+ const run = runner.run();
+ try {
+ await vi.waitFor(() => expect(session.send).toHaveBeenCalled());
+ } finally {
+ refreshed.resolve(AGENT_INFO);
+ await run;
+ }
+ });
+
+ it("releases the composer without waiting on unrelated setup diagnostics", async () => {
+ const diagnostics = createDeferred<Awaited<ReturnType<BootDetection["detect"]>>>();
+ const detect = vi.fn(() => diagnostics.promise);
+ const readPrompt = vi.fn(async () => undefined);
+ const { runner } = providerSetupRefreshRunner({
+ refreshInfo: async () => AGENT_INFO,
+ bootDetections: [{ id: "slow", detect }],
+ renderer: { readPrompt },
+ });
+ const run = runner.run();
+ try {
+ await vi.waitFor(() => expect(readPrompt).toHaveBeenCalledOnce());
+ expect(detect).toHaveBeenCalledOnce();
+ } finally {
+ diagnostics.resolve([]);
+ await run;
+ }
+ });
+
it("normalizes a committed local key after automatic provider setup", async () => {
const clearSetupWarning = vi.fn();
const headers: AgentTUIAgentHeader[] = [];
@@ -4122,12 +4196,13 @@ describe("EveTUIRunner boot setup detection", () => {
credential: "api-key",
});
expect(headers.map((header) => header.info?.agent.model.endpoint)).toEqual([
- { kind: "gateway", connected: false },
+ { kind: "gateway", connected: true, credential: "api-key" },
]);
});
it("drops stale disconnected evidence when the post-setup info refresh fails", async () => {
const clearSetupWarning = vi.fn();
+ const renderCommandResult = vi.fn();
const headers: AgentTUIAgentHeader[] = [];
const detect = vi.fn(({ info }: { info?: AgentInfoResult }) =>
info?.agent.model.endpoint?.kind === "gateway" && !info.agent.model.endpoint.connected
@@ -4147,6 +4222,7 @@ describe("EveTUIRunner boot setup detection", () => {
bootDetections: [{ id: "test", detect }],
renderer: {
clearSetupWarning,
+ renderCommandResult,
renderAgentHeader: (header) => headers.push(header),
},
});
@@ -4154,9 +4230,13 @@ describe("EveTUIRunner boot setup detection", () => {
await runner.run();
await vi.waitFor(() => expect(clearSetupWarning).toHaveBeenCalled());
+ expect(renderCommandResult).toHaveBeenCalledWith("AI Gateway via API key selected.", undefined);
expect(client.info).toHaveBeenCalledTimes(2);
- expect(detect.mock.calls.at(-1)?.[0].info).toBeUndefined();
- expect(headers.at(-1)?.info).toBe(disconnectedGatewayInfo);
+ expect(detect).not.toHaveBeenCalled();
+ expect(headers.at(-1)?.info?.agent.model.endpoint).toMatchObject({
+ kind: "gateway",
+ connected: true,
+ });
});
it("stays quiet without a local setup context, even with issues", async () => {
@@ -4644,3 +4724,31 @@ describe("EveTUIRunner command shutdown", () => {
expect(renderer.requestInterrupt).toHaveBeenCalledOnce();
});
});
+
+it("starts onboarding with only login and preserves the input draft", async () => {
+ const order: string[] = [];
+ const handle = vi.fn(async (command: { name: string }) => {
+ order.push(command.name);
+ return { message: "Connected." };
+ });
+ const renderer = fakeRenderer({
+ setupFlow: createFakeSetupFlowRenderer(),
+ readPrompt: vi.fn(async (options?: AgentTUISessionOptions) => {
+ order.push("prompt");
+ expect(options?.initialDraft).toBe("Hello Alice");
+ return undefined;
+ }),
+ });
+ const runner = new EveTUIRunner({
+ session: sessionYielding([]),
+ renderer,
+ name: "Agent",
+ appRoot: "/tmp/agent",
+ onboard: true,
+ initialInput: "Hello Alice",
+ bootDetections: [],
+ promptCommandHandler: { handle },
+ });
+ await runner.run();
+ expect(order).toEqual(["login", "prompt"]);
+});
diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.ts
index 02987f834..e46eeb050 100644
--- a/packages/eve/src/cli/dev/tui/runner.ts
+++ b/packages/eve/src/cli/dev/tui/runner.ts
@@ -1,3 +1,4 @@
+import type { ModelAccessChange } from "#shared/model-connection.js";
import { SteeringStream } from "#cli/dev/tui/steering-stream.js";
import {
type ActionResultStreamEvent,
@@ -21,11 +22,7 @@ import {
ClientSession,
} from "#client/index.js";
import { renderApplicationInfo } from "#cli/commands/info.js";
-import type {
- EveCliSetupStep,
- EveCliSetupStepEvent,
- EveCliSetupTerminalEvent,
-} from "#cli/telemetry/index.js";
+import type { EveCliSetupStepEvent, EveCliSetupTerminalEvent } from "#cli/telemetry/index.js";
import type { OnboardingScreenEvent } from "./setup-commands.js";
import { loadDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";
import { subscribeDevelopmentSandboxPrewarmLogs } from "#execution/sandbox/development-prewarm.js";
@@ -72,6 +69,9 @@ import {
type RemoteConnectionControllerOptions,
type RemoteConnectionSnapshot,
} from "./remote-connection.js";
+import type { RemoteAuthFlow } from "./remote-auth.js";
+import { describeRemoteAuthCompletedMutations } from "./remote-auth-result.js";
+import { prepareRemoteTuiAccess } from "./remote-startup.js";
import type { DevelopmentCredentialGate } from "#services/dev-client/credential-gate.js";
import {
BOOT_DETECTIONS,
@@ -85,8 +85,6 @@ import {
type BootDetectionContext,
type SetupIssue,
} from "./setup-issues.js";
-import type { RegistryPlannerContext } from "#setup/flows/registry.js";
-import type { PlannerNavigation } from "#setup/prompter.js";
import type { SetupFlowRenderer } from "./setup-flow.js";
import type { TraceViewerRenderer } from "./traces/trace-viewer-session.js";
import type { RemoteDevelopmentTarget } from "./target.js";
@@ -265,6 +263,8 @@ export type AgentTUIRenderer = {
* without a header simply skip it.
*/
renderAgentHeader?(header: AgentTUIAgentHeader): void;
+ /** Keeps preliminary connection diagnostics out of the startup presentation. */
+ setStartupPhase?(phase: "starting" | "connecting" | "updating" | undefined): void;
/**
* Commits a single informational line to the transcript. Used for session
* recovery and slash-command results. Optional.
@@ -284,7 +284,7 @@ export type AgentTUIRenderer = {
renderSetupWarning?(text: string): void;
/** Clears the setup attention line once its issue is resolved. */
clearSetupWarning?(): void;
- /** Commits the startup `/vc:login` invocation to the transcript. */
+ /** Commits the startup `/deploy` invocation to the transcript. */
renderCommandInvocation?(text: string, status?: "failed"): void;
renderCommandResult?(text: string, tone?: "success" | "error"): void;
readonly setupFlow?: SetupFlowRenderer;
@@ -399,20 +399,11 @@ export interface PromptCommandHandlerContext {
readonly title: string;
/** Provider entry authorized by confirmed boot-time model-access evidence. */
readonly initialModelStep?: "provider";
- readonly registryPlannerContext?: RegistryPlannerContext;
readonly onOnboardingScreen?: (input: OnboardingScreenEvent) => void;
- /** Overrides the standalone command title inside a composed setup journey. */
- readonly setupFlowTitle?: string;
- /** Progress owned by an enclosing journey while this command runs. */
- readonly setupFlowNavigation?: PlannerNavigation;
/** Live ChatGPT identity shown only inside model configuration UI. */
readonly chatGptAccountLabel?: string;
- /**
- * Leaves the current setup panel mounted for the next automatic onboarding
- * command. The runner closes it if no next command can proceed.
- */
- readonly keepSetupFlowOpen?: true;
- readonly remoteConnection?: RemoteConnectionController;
+ /** Settles runtime changes before the setup panel releases the screen. */
+ readonly settleOutcome?: (outcome: PromptCommandOutcome) => Promise<PromptCommandOutcome>;
readonly withExclusiveTerminal?: <T>(task: () => Promise<T>) => Promise<T>;
readonly disabledConnectionReasons?: Readonly<Record<string, string>>;
}
@@ -424,7 +415,7 @@ export interface PromptCommandOutcome {
/** Promotes an outcome to a top-level status. */
tone?: "success" | "error";
/** Post-command work after setup settles. */
- effect?: VercelStatusEffect | { kind: "model-access-changed" };
+ effect?: VercelStatusEffect | ModelAccessChange;
cancelled?: true;
}
@@ -491,6 +482,8 @@ export type EveTUIRunnerOptions = TuiDisplayOptions & {
readonly credentials: DevelopmentCredentialGate;
readonly resolveOidcToken: NonNullable<RemoteConnectionControllerOptions["resolveOidcToken"]>;
readonly resolveDeployment: NonNullable<RemoteConnectionControllerOptions["resolveDeployment"]>;
+ /** Test seam for consented deployment access repair. */
+ readonly runAuthFlow?: RemoteAuthFlow;
};
/** Boot-time installation-state checks; defaults to the built-ins. */
bootDetections?: readonly BootDetection[];
@@ -537,13 +530,15 @@ export class EveTUIRunner {
#startupPrompt?: string;
/** Explicit fresh-agent onboarding handoff from `eve init`. */
readonly #onboard: boolean;
+ #reportedFirstResponse = false;
readonly #onOnboardingStep?: EveTUIRunnerOptions["onOnboardingStep"];
readonly #onOnboardingTerminal?: EveTUIRunnerOptions["onOnboardingTerminal"];
- #initialOnboardingActive = false;
+ #startupActive = true;
readonly #promptCommandHandler?: PromptCommandHandler;
readonly #availablePromptCommands: readonly PromptCommandSpec[];
readonly #withExclusiveTerminal?: <T>(task: () => Promise<T>) => Promise<T>;
readonly #remoteConnection?: RemoteConnectionController;
+ readonly #remoteAuthFlow?: RemoteAuthFlow;
readonly #bootDetections: readonly BootDetection[];
readonly #getVercelAuthStatus: typeof getVercelAuthStatus;
readonly #inspectApplication: typeof inspectApplication;
@@ -558,6 +553,8 @@ export class EveTUIRunner {
* "not logged in" hint over a session the user has since logged into.
*/
#authHintStale = false;
+ #setupAttentionRevision = 0;
+ #agentInfoRevision = 0;
/** Cheap-and-local boot detection issues, cached so the auth probe can re-combine. */
#bootIssues: SetupIssue[] = [];
/** The current Vercel auth issue (login / CLI-missing), or undefined when fine. */
@@ -678,6 +675,7 @@ export class EveTUIRunner {
}
this.#availablePromptCommands = options.availablePromptCommands ?? PROMPT_COMMANDS;
if (options.remote !== undefined) {
+ this.#remoteAuthFlow = options.remote.runAuthFlow;
if (this.#client === undefined) {
throw new Error("A remote TUI requires a configured development client.");
}
@@ -707,12 +705,12 @@ export class EveTUIRunner {
* header. Never throws: a missing or unauthorized `/eve/v1/info` simply
* yields a header without the agent's configuration detail.
*/
- async #renderAgentHeader(): Promise<string | undefined> {
+ async #loadInitialAgentInfo(): Promise<void> {
const serverUrl = this.#serverUrl;
if (serverUrl === undefined) {
this.#reportBeforeFirstPaint();
if (!this.#onboard) await this.#renderSetupIssues(undefined);
- return this.#finishStartup();
+ return;
}
let info: AgentInfoResult | undefined;
@@ -734,11 +732,9 @@ export class EveTUIRunner {
}
}
}
- const initialDraft = this.#finishStartup();
this.#reportBeforeFirstPaint();
const headerInfo = this.#replaceAgentInfo(info);
if (!this.#onboard) await this.#renderSetupIssues(headerInfo);
- return initialDraft;
}
#finishStartup(): string | undefined {
@@ -752,14 +748,14 @@ export class EveTUIRunner {
this.#appRoot === undefined ? info : normalizeLocalModelEndpoint(info, process.env);
this.#agentInfo = headerInfo;
const serverUrl = this.#serverUrl;
- if (serverUrl === undefined || this.#initialOnboardingActive) return headerInfo;
+ if (serverUrl === undefined || this.#startupActive) return headerInfo;
const header: AgentTUIAgentHeader = {
name: this.#name,
serverUrl,
};
if (headerInfo !== undefined) header.info = headerInfo;
- if (this.#appRoot !== undefined) header.tip = this.#headerTip;
+ if (this.#appRoot !== undefined && !this.#onboard) header.tip = this.#headerTip;
this.#renderer.renderAgentHeader?.(header);
return headerInfo;
}
@@ -800,17 +796,8 @@ export class EveTUIRunner {
let hasRunTurn = false;
let followCurrentSession = false;
let streamWithoutPrompt = false;
- let initialDraft = await this.#renderAgentHeader();
- if (this.#startupPrompt !== undefined) {
- prompt = this.#startupPrompt;
- }
- if (this.#remoteConnection?.current().connection.state === "auth-required") {
- await this.#executeExtensionCommand(
- { type: "extension", name: "vc:login", argument: "" },
- title,
- { trigger: "startup" },
- );
- }
+ this.#renderer.setStartupPhase?.("starting");
+ await this.#loadInitialAgentInfo();
this.#subscribeDevelopmentSandboxLogs();
// Fire-and-forget: the link identity is network-bound to resolve, and the
// first prompt must not wait on it. The segment appears when it lands.
@@ -818,19 +805,58 @@ export class EveTUIRunner {
this.#mcpConnectionStatus?.refresh();
const initialAgentOnboarding =
- this.#onboard &&
+ (this.#onboard ||
+ (this.#agentInfo?.agent.model.endpoint?.kind === "gateway" &&
+ !this.#agentInfo.agent.model.endpoint.connected)) &&
this.#appRoot !== undefined &&
this.#promptCommandHandler !== undefined &&
this.#renderer.setupFlow !== undefined;
- if (initialAgentOnboarding) {
- initialDraft = undefined;
- this.#initialOnboardingActive = true;
- try {
- await this.#runInitialAgentOnboarding(title);
- } finally {
- this.#initialOnboardingActive = false;
+ let startupOutcome: PromptCommandOutcome | undefined;
+ if (this.#remoteConnection !== undefined && this.#renderer.setupFlow !== undefined) {
+ const access = await prepareRemoteTuiAccess({
+ connection: this.#remoteConnection,
+ renderer: this.#renderer.setupFlow,
+ signal: this.#lifecycle?.signal,
+ runAuthFlow: this.#remoteAuthFlow,
+ });
+ if (access?.kind === "authenticated") {
+ const connection = this.#remoteConnection.current().connection;
+ if (connection.state === "ready") this.#replaceAgentInfo(connection.info);
+ } else if (access?.kind === "failed" || access?.kind === "unavailable") {
+ startupOutcome = {
+ tone: "error",
+ message: access.kind === "failed" ? access.message : access.failure.message,
+ };
+ } else if (access?.kind === "cancelled") {
+ startupOutcome = { cancelled: true };
+ if (access.completedMutations.length > 0) {
+ startupOutcome.message = `Completed before cancellation: ${describeRemoteAuthCompletedMutations(access.completedMutations).join(", ")}.`;
+ }
}
}
+ if (initialAgentOnboarding) {
+ this.#renderer.setStartupPhase?.("connecting");
+ startupOutcome = await this.#runInitialAgentOnboarding(title);
+ }
+
+ let initialDraft = this.#finishStartup();
+ if (startupOutcome?.cancelled || startupOutcome?.tone === "error") {
+ initialDraft = [this.#startupPrompt, initialDraft].filter(Boolean).join("\n\n") || undefined;
+ } else {
+ prompt = this.#startupPrompt;
+ }
+ this.#startupActive = false;
+ this.#replaceAgentInfo(this.#agentInfo);
+ this.#paintSetupAttention();
+ this.#renderer.setStartupPhase?.(undefined);
+ if (initialAgentOnboarding) {
+ this.#renderStartupCommandInvocation(
+ { type: "extension", name: "login", argument: "" },
+ "startup",
+ startupOutcome?.tone,
+ );
+ }
+ this.#renderCommandOutcome(startupOutcome?.message, startupOutcome?.tone);
while (true) {
if (this.#lifecycle?.signal.aborted === true || this.#renderer.exitRequested?.() === true) {
@@ -1325,8 +1351,7 @@ export class EveTUIRunner {
const now = Date.now();
if (shouldRefreshChatGptAuth && now - lastChatGptAuthRefresh >= idleChatGptAuthPollMs) {
lastChatGptAuthRefresh = now;
- const refreshedInfo = await this.#readAgentInfo();
- if (refreshedInfo !== undefined) this.#replaceAgentInfo(refreshedInfo);
+ void this.#refreshAgentInfo();
}
} finally {
refreshing = false;
@@ -1608,6 +1633,12 @@ export class EveTUIRunner {
void this.#requestTurnCancellation(turnState, sourceSession);
},
events: eveEventsToTUIStream({
+ onAssistantResponse: () => {
+ if (this.#onboard && !this.#reportedFirstResponse) {
+ this.#reportedFirstResponse = true;
+ this.#onOnboardingStep?.({ flow: "onboarding", step: "first_response" });
+ }
+ },
events: steering ?? events,
pendingInputRequests: this.#pendingInputRequests,
turnState,
@@ -1665,6 +1696,7 @@ export class EveTUIRunner {
/** Repaints the attention line from the cached detection + auth issues, or clears it. */
#paintSetupAttention(): void {
+ if (this.#startupActive) return;
const issues = orderedSetupIssues(this.#bootIssues, this.#authIssue);
if (issues.length > 0) {
this.#renderer.renderSetupWarning?.(formatSetupIssuesLine(issues));
@@ -1676,7 +1708,7 @@ export class EveTUIRunner {
/** Checks Vercel auth after boot without delaying the first prompt. */
async #probeAuthIssue(): Promise<void> {
const appRoot = this.#appRoot;
- if (appRoot === undefined) return;
+ if (appRoot === undefined || process.env.EVE_MODEL_CONNECTION !== "ai-gateway-project") return;
let status: VercelAuthStatus;
try {
status = await this.#getVercelAuthStatus(appRoot, { signal: this.#authProbeAbort.signal });
@@ -1690,27 +1722,31 @@ export class EveTUIRunner {
/**
* Re-evaluates the attention line after a setup command changed local state,
- * so a fixed issue clears (e.g. the `not logged in · /vc:login` line disappears
- * once `/vc:login` succeeds) instead of lingering stale. Authoritative: unlike
+ * so a fixed issue clears (e.g. the `not logged in · /deploy` line disappears
+ * once `/deploy` succeeds) instead of lingering stale. Authoritative: unlike
* the boot probe it re-reads detections and auth and is not stale-guarded.
*/
async #refreshSetupAttention(info: AgentInfoResult | undefined): Promise<void> {
const appRoot = this.#appRoot;
if (appRoot === undefined) return;
if (this.#renderer.renderSetupWarning === undefined) return;
+ const revision = ++this.#setupAttentionRevision;
const context: BootDetectionContext = { appRoot, env: process.env };
if (info !== undefined) context.info = info;
try {
- this.#bootIssues = await detectSetupIssues(context, this.#bootDetections);
- const status = await this.#getVercelAuthStatus(appRoot, {
- signal: this.#authProbeAbort.signal,
- });
- this.#authIssue = authIssueForStatus(status);
+ const [issues, auth] = await Promise.all([
+ detectSetupIssues(context, this.#bootDetections),
+ process.env.EVE_MODEL_CONNECTION === "ai-gateway-project"
+ ? this.#getVercelAuthStatus(appRoot, { signal: this.#authProbeAbort.signal })
+ : undefined,
+ ]);
+ if (this.#disposed || revision !== this.#setupAttentionRevision) return;
+ this.#bootIssues = issues;
+ this.#authIssue = auth === undefined ? undefined : authIssueForStatus(auth);
+ this.#paintSetupAttention();
} catch {
return;
}
- if (this.#disposed) return;
- this.#paintSetupAttention();
}
#subscribeDevelopmentSandboxLogs(): void {
@@ -1738,15 +1774,7 @@ export class EveTUIRunner {
async #handleExtensionCommand(
command: Extract<PromptCommand, { type: "extension" }>,
- input: Pick<
- PromptCommandHandlerContext,
- | "initialModelStep"
- | "registryPlannerContext"
- | "setupFlowTitle"
- | "setupFlowNavigation"
- | "keepSetupFlowOpen"
- | "title"
- >,
+ input: Pick<PromptCommandHandlerContext, "initialModelStep" | "title">,
): Promise<PromptCommandOutcome | undefined> {
const handler = this.#promptCommandHandler;
if (handler === undefined)
@@ -1756,11 +1784,11 @@ export class EveTUIRunner {
const baseContext: PromptCommandHandlerContext = {
...input,
renderer: this.#renderer,
+ settleOutcome: (outcome) => this.#settleCommandOutcome(outcome),
chatGptAccountLabel:
endpoint?.kind === "chatgpt" && endpoint.state === "ready"
? endpoint.accountLabel
: undefined,
- remoteConnection: this.#remoteConnection,
withExclusiveTerminal: this.#withExclusiveTerminal,
};
const disabledConnectionReasons = this.#mcpConnectionStatus?.current();
@@ -1768,9 +1796,6 @@ export class EveTUIRunner {
disabledConnectionReasons !== undefined && Object.keys(disabledConnectionReasons).length > 0
? { ...baseContext, disabledConnectionReasons }
: baseContext;
- if (input.keepSetupFlowOpen === true) {
- return await handler.handle(command, { ...context, keepSetupFlowOpen: true });
- }
return await handler.handle(command, context);
}
@@ -1792,7 +1817,7 @@ export class EveTUIRunner {
if (effect?.kind === "model-access-changed") {
this.#vercelStatus?.applyEffect({ kind: "refresh-identity" });
this.#authHintStale = true;
- await this.#refreshModelAccess();
+ await this.#refreshModelAccess(effect);
return;
}
if (effect === undefined) return;
@@ -1802,147 +1827,72 @@ export class EveTUIRunner {
void this.#refreshSetupAttention(this.#agentInfo);
}
+ async #settleCommandOutcome(outcome: PromptCommandOutcome): Promise<PromptCommandOutcome> {
+ if (outcome.effect === undefined) return outcome;
+ const refreshTimer =
+ outcome.effect.kind === "model-access-changed" && outcome.effect.reload
+ ? setTimeout(() => {
+ if (this.#startupActive) this.#renderer.setStartupPhase?.("updating");
+ this.#renderer.setupFlow?.setStatus("Loading selected model…");
+ }, 150)
+ : undefined;
+ try {
+ await this.#applyCommandEffect(outcome.effect);
+ const { effect: _effect, ...settled } = outcome;
+ return settled;
+ } catch {
+ return {
+ tone: "error",
+ message:
+ "Settings were saved, but the agent could not reload. Retry the command or restart eve dev.",
+ };
+ } finally {
+ clearTimeout(refreshTimer);
+ }
+ }
+
async #executeExtensionCommand(
command: Extract<PromptCommand, { type: "extension" }>,
title: string,
input: {
readonly trigger: "startup" | "command";
readonly initialModelStep?: "provider";
- readonly registryPlannerContext?: RegistryPlannerContext;
readonly onOnboardingScreen?: PromptCommandHandlerContext["onOnboardingScreen"];
- readonly setupFlowTitle?: string;
- readonly setupFlowNavigation?: PlannerNavigation;
- readonly keepSetupFlowOpen?: true;
readonly suppressSuccessfulTranscript?: true;
readonly suppressCancelledTranscript?: true;
},
): Promise<PromptCommandOutcome | undefined> {
- const outcome = await this.#handleExtensionCommand(command, { ...input, title });
+ const pendingOutcome = await this.#handleExtensionCommand(command, { ...input, title });
+ const outcome =
+ pendingOutcome === undefined ? undefined : await this.#settleCommandOutcome(pendingOutcome);
const suppressTranscript =
(input.suppressSuccessfulTranscript === true && outcome?.tone !== "error") ||
(input.suppressCancelledTranscript === true && outcome?.cancelled === true);
- if (!suppressTranscript) {
- this.#renderStartupCommandInvocation(command, input.trigger, outcome?.tone);
- }
- if (!suppressTranscript) this.#renderCommandOutcome(outcome?.message, outcome?.tone);
- await this.#applyCommandEffect(outcome?.effect);
+ if (!suppressTranscript && input.trigger !== "startup")
+ this.#renderCommandOutcome(outcome?.message, outcome?.tone);
this.#refreshHeaderFromRemoteConnection();
return outcome;
}
- #onboardingNavigation(activeStep: number): PlannerNavigation {
- return {
- kind: "planner",
- activeStep,
- firstNavigableStep: 1,
- steps: [
- { label: "Model", complete: activeStep > 0 },
- { label: "Channels" },
- { label: "Integrations" },
- { label: "Review" },
- ],
- };
- }
-
- /** Runs fresh-agent setup as two cohesive, one-way phases. */
- async #runInitialAgentOnboarding(title: string): Promise<void> {
- const journey = {
- keepSetupFlowOpen: true as const,
- setupFlowTitle: `Set up ${title}`,
- trigger: "startup" as const,
- };
-
- let activeStep: EveCliSetupStep = "model_provider";
- const onOnboardingScreen: NonNullable<PromptCommandHandlerContext["onOnboardingScreen"]> = (
- input,
- ) => {
- activeStep = input.screen;
- this.#onOnboardingStep?.({
- flow: "onboarding",
- step: input.screen,
- registrySelectedCount: input.registrySelectedCount,
- });
- };
- onOnboardingScreen({ screen: "model_provider" });
- let modelOutcome: PromptCommandOutcome | undefined;
- try {
- modelOutcome = await this.#executeExtensionCommand(
- { type: "extension", name: "model", argument: "" },
- title,
- {
- ...journey,
- suppressSuccessfulTranscript: true,
- initialModelStep: "provider",
- setupFlowNavigation: this.#onboardingNavigation(0),
- onOnboardingScreen,
- },
- );
- } catch (error) {
- this.#onOnboardingTerminal?.({ flow: "onboarding", step: activeStep, result: "error" });
- throw error;
- }
- if (modelOutcome?.tone === "error" || modelOutcome?.cancelled === true) {
- this.#onOnboardingTerminal?.({
- flow: "onboarding",
- step: activeStep,
- result: modelOutcome.cancelled === true ? "cancelled" : "error",
- });
- this.#renderer.setupFlow?.end({ preserveDiagnostics: modelOutcome.tone === "error" });
- return;
- }
-
- let addOutcome: PromptCommandOutcome | undefined;
- activeStep = "registry_channels";
- const onRegistryScreen: NonNullable<PromptCommandHandlerContext["onOnboardingScreen"]> = (
- input,
- ) => {
- activeStep = input.screen;
- this.#onOnboardingStep?.({
- flow: "onboarding",
- step: input.screen,
- registrySelectedCount: input.registrySelectedCount,
- });
- };
- try {
- onRegistryScreen({ screen: "registry_channels" });
- addOutcome = await this.#executeExtensionCommand(
- { type: "extension", name: "add", argument: "" },
- title,
- {
- ...journey,
- onOnboardingScreen: onRegistryScreen,
- registryPlannerContext: {
- prefixSteps: [{ label: "Model", complete: true }],
- reviewMessage: "Review your agent",
- primaryActionLabel: "Install and finish setup",
- emptyActionLabel: "Finish setup",
- },
- },
- );
- } catch (error) {
- this.#onOnboardingTerminal?.({ flow: "onboarding", step: activeStep, result: "error" });
- throw error;
- } finally {
- if (addOutcome !== undefined) {
- this.#onOnboardingTerminal?.({
- flow: "onboarding",
- step: activeStep,
- result:
- addOutcome.cancelled === true
- ? "cancelled"
- : addOutcome.tone === "error"
- ? "error"
- : "completed",
- });
- }
- // `/add` is the final onboarding phase. Release the shared panel so the
- // ordinary chat prompt can own input, retaining deploy/setup evidence on failure.
- this.#renderer.setupFlow?.end({ preserveDiagnostics: addOutcome?.tone === "error" });
- }
+ async #runInitialAgentOnboarding(title: string): Promise<PromptCommandOutcome | undefined> {
+ this.#onOnboardingStep?.({ flow: "onboarding", step: "model_provider" });
+ const outcome = await this.#executeExtensionCommand(
+ { type: "extension", name: "login", argument: "" },
+ title,
+ { trigger: "startup", initialModelStep: "provider" },
+ );
+ if (!outcome?.cancelled && outcome?.tone !== "error")
+ this.#onOnboardingStep?.({ flow: "onboarding", step: "connection_ready" });
+ this.#onOnboardingTerminal?.({
+ flow: "onboarding",
+ step: "model_provider",
+ result: outcome?.cancelled ? "cancelled" : outcome?.tone === "error" ? "error" : "completed",
+ });
+ return outcome;
}
#refreshHeaderFromRemoteConnection(): void {
- if (this.#initialOnboardingActive) return;
+ if (this.#startupActive) return;
const connection = this.#remoteConnection?.current().connection;
if (connection?.state !== "ready" || connection.info === this.#agentInfo) return;
this.#agentInfo = connection.info;
@@ -2025,20 +1975,38 @@ export class EveTUIRunner {
}
}
- /**
- * Setup commands can write authored source and env files. Force the local
- * runtime snapshot to catch up, then cache the credential-normalized `/info`
- * shared by the status bar and setup detector. The Vercel auth probe stays
- * off the prompt path.
- */
- async #refreshModelAccess(): Promise<void> {
+ async #refreshModelAccess(effect: ModelAccessChange): Promise<void> {
const appRoot = this.#appRoot;
if (appRoot === undefined) return;
-
+ // Invalidate inspections started before this selection, including watcher notifications.
+ ++this.#agentInfoRevision;
+ ++this.#setupAttentionRevision;
await loadDevelopmentEnvironmentFiles(appRoot);
- await this.#runtimeArtifacts?.refreshAfterSourceChange({});
- const refreshedInfo = this.#replaceAgentInfo(await this.#readAgentInfo());
- void this.#refreshSetupAttention(refreshedInfo);
+ if (effect.reload) await this.#runtimeArtifacts?.refreshAfterSourceChange({});
+ if (effect.model && this.#agentInfo) {
+ this.#replaceAgentInfo({
+ ...this.#agentInfo,
+ agent: {
+ ...this.#agentInfo.agent,
+ model: { ...this.#agentInfo.agent.model, ...effect.model },
+ },
+ });
+ } else this.#replaceAgentInfo(this.#agentInfo);
+ this.#bootIssues = [];
+ this.#authIssue = undefined;
+ this.#paintSetupAttention();
+ void this.#refreshAgentInfo();
+ }
+
+ async #refreshAgentInfo(notify = false): Promise<void> {
+ const previousInfo = this.#agentInfo;
+ const revision = ++this.#agentInfoRevision;
+ const nextInfo = await this.#readAgentInfo();
+ if (this.#disposed || revision !== this.#agentInfoRevision || nextInfo === undefined) return;
+ this.#replaceAgentInfo(nextInfo);
+ if (notify && !this.#renderer.renderAgentHeader)
+ this.#renderer.renderNotice?.(formatAgentUpdateNotice(previousInfo, nextInfo));
+ void this.#refreshSetupAttention(this.#agentInfo);
}
async #readAgentInfo(): Promise<AgentInfoResult | undefined> {
@@ -2049,14 +2017,8 @@ export class EveTUIRunner {
return probe.kind === "ready" ? probe.info : undefined;
}
- async #handleRuntimeArtifactsChanged(): Promise<void> {
- const previousInfo = this.#agentInfo;
- const nextInfo = await this.#readAgentInfo();
- if (nextInfo !== undefined) this.#replaceAgentInfo(nextInfo);
-
- if (!this.#renderer.renderAgentHeader || nextInfo === undefined) {
- this.#renderer.renderNotice?.(formatAgentUpdateNotice(previousInfo, nextInfo));
- }
+ #handleRuntimeArtifactsChanged(): void {
+ void this.#refreshAgentInfo(true);
}
#handleConnectionAuthRequired(event: AuthorizationRequiredStreamEvent): void {
@@ -2169,6 +2131,7 @@ function formatAgentUpdateNotice(
type EveStreamTranslatorInput = {
events: AsyncIterable<MessageStreamEvent>;
+ onAssistantResponse?: () => void;
pendingInputRequests: Map<string, InputRequest>;
turnState: AgentTUITurnState;
onSubagentCalled?: (event: SubagentCalledStreamEvent) => void;
@@ -2303,6 +2266,7 @@ async function* eveEventsToTUIStream(
const delta = appended.data.messageDelta;
if (delta.length === 0) break;
state.text += delta;
+ if (delta) input.onAssistantResponse?.();
yield { type: "assistant-delta", id: partGenerationId(base, state.generation), delta };
break;
}
@@ -2338,6 +2302,7 @@ async function* eveEventsToTUIStream(
} else if (message.startsWith(state.text)) {
const suffix = message.slice(state.text.length);
if (suffix.length > 0) {
+ if (suffix) input.onAssistantResponse?.();
yield { type: "assistant-delta", id, delta: suffix };
}
state.text = message;
diff --git a/packages/eve/src/cli/dev/tui/setup-commands.test.ts b/packages/eve/src/cli/dev/tui/setup-commands.test.ts
index 725252ccb..8f258e54f 100644
--- a/packages/eve/src/cli/dev/tui/setup-commands.test.ts
+++ b/packages/eve/src/cli/dev/tui/setup-commands.test.ts
@@ -61,7 +61,6 @@ function fakeFlows(overrides: Partial<TuiSetupFlows> = {}): TuiSetupFlows {
runInstallVercelCliFlow: vi.fn<TuiSetupFlows["runInstallVercelCliFlow"]>(async () => ({
kind: "installed",
})),
- runLoginFlow: vi.fn<TuiSetupFlows["runLoginFlow"]>(async () => ({ kind: "logged-in" })),
runModelFlow: vi.fn<TuiSetupFlows["runModelFlow"]>(async () => ({
kind: "done",
accessChanged: true,
@@ -77,7 +76,7 @@ function fakeFlows(overrides: Partial<TuiSetupFlows> = {}): TuiSetupFlows {
}
function run(input: {
- command: "vc:install" | "vc:login" | "model" | "add" | "deploy";
+ command: "model" | "add" | "deploy";
flows: TuiSetupFlows;
renderer?: TuiSetupCommandRenderer;
initialModelStep?: "provider";
@@ -186,8 +185,7 @@ describe("runTuiSetupCommand", () => {
Object.entries(SETUP_FLOW_CONFIG).map(([command, config]) => [command, config.indicator]),
),
).toEqual({
- "vc:install": "pulse",
- "vc:login": "pulse",
+ login: "pulse",
model: "pulse",
add: "pulse",
deploy: "spinner",
@@ -199,12 +197,12 @@ describe("runTuiSetupCommand", () => {
await expect(run({ command: "model", flows })).resolves.toEqual({
message: "Model changed to openai/gpt-5.5. Live on your next prompt.",
preserveFlowDiagnostics: false,
- effect: { kind: "model-access-changed" },
+ effect: { kind: "model-access-changed", reload: true },
});
expect(flows.runModelFlow).toHaveBeenCalledWith(
expect.objectContaining({
appRoot: APP_ROOT,
- deps: expect.objectContaining({ runProviderFlow: expect.any(Function) }),
+ deps: expect.objectContaining({ pickModelSettings: expect.any(Function) }),
}),
);
});
@@ -284,7 +282,7 @@ describe("runTuiSetupCommand", () => {
"Model changed to openai/gpt-5.5. Live on your next prompt.\n" +
"AI Gateway via Project selected.",
preserveFlowDiagnostics: false,
- effect: { kind: "model-access-changed" },
+ effect: { kind: "model-access-changed", reload: true },
});
});
@@ -299,7 +297,7 @@ describe("runTuiSetupCommand", () => {
await expect(run({ command: "model", flows })).resolves.toEqual({
message: "AI Gateway via Project selected.",
preserveFlowDiagnostics: false,
- effect: { kind: "model-access-changed" },
+ effect: { kind: "model-access-changed", reload: true },
});
});
@@ -314,7 +312,7 @@ describe("runTuiSetupCommand", () => {
await expect(run({ command: "model", flows })).resolves.toEqual({
message: "AI Gateway via API key selected.",
preserveFlowDiagnostics: false,
- effect: { kind: "model-access-changed" },
+ effect: { kind: "model-access-changed", reload: true },
});
});
@@ -329,7 +327,7 @@ describe("runTuiSetupCommand", () => {
await expect(run({ command: "model", flows })).resolves.toEqual({
message: "ChatGPT subscription selected.",
preserveFlowDiagnostics: false,
- effect: { kind: "model-access-changed" },
+ effect: { kind: "model-access-changed", reload: true },
});
});
@@ -338,7 +336,7 @@ describe("runTuiSetupCommand", () => {
runModelFlow: vi.fn<TuiSetupFlows["runModelFlow"]>(async () => ({ kind: "cancelled" })),
});
await expect(run({ command: "model", flows })).resolves.toEqual({
- message: "/model dismissed.",
+ message: "",
cancelled: true,
preserveFlowDiagnostics: false,
});
@@ -445,11 +443,14 @@ describe("runTuiSetupCommand", () => {
],
["empty", registryResult(), "No integrations selected."],
["deployed", registryResult({ deployed: "production" }), "No integrations selected."],
- ["cancelled", { kind: "cancelled" as const }, "/add dismissed."],
+ ["cancelled", { kind: "cancelled" as const }, ""],
] as const)("reports a %s registry flow", async (_case, result, message) => {
const runRegistryFlow = vi.fn(async () => result);
const outcome = await run({ command: "add", flows: fakeFlows({ runRegistryFlow }) });
- expect(outcome).toMatchObject({ message, preserveFlowDiagnostics: true });
+ expect(outcome).toMatchObject({
+ message,
+ preserveFlowDiagnostics: result.kind !== "cancelled",
+ });
if (result.kind === "done" && result.result.items.length > 0)
expect(outcome.tone).toBe("success");
if (result.kind === "done" && result.result.deployed === "production") {
@@ -579,10 +580,10 @@ describe("runTuiSetupCommand", () => {
renderer.fireInterrupt("ctrl-c");
await expect(result).resolves.toEqual({
- message: "/add interrupted.",
+ message: "",
cancelled: true,
- tone: "error",
- preserveFlowDiagnostics: true,
+ tone: undefined,
+ preserveFlowDiagnostics: false,
});
});
@@ -601,10 +602,10 @@ describe("runTuiSetupCommand", () => {
renderer.fireInterrupt();
await expect(result).resolves.toEqual({
- message: "/add interrupted.",
+ message: "",
cancelled: true,
- tone: "error",
- preserveFlowDiagnostics: true,
+ tone: undefined,
+ preserveFlowDiagnostics: false,
});
});
@@ -632,52 +633,11 @@ describe("runTuiSetupCommand", () => {
renderer.fireInterrupt();
await expect(result).resolves.toEqual({
- message: "/model interrupted.",
- tone: "error",
- preserveFlowDiagnostics: true,
- effect: { kind: "model-access-changed" },
- });
- });
-
- it("reports a completed login and refreshes the link identity", async () => {
- const flows = fakeFlows({
- runLoginFlow: vi.fn<TuiSetupFlows["runLoginFlow"]>(async () => ({ kind: "logged-in" })),
- });
- await expect(run({ command: "vc:login", flows })).resolves.toEqual({
- message: "Logged in to Vercel.",
- preserveFlowDiagnostics: false,
- effect: { kind: "refresh-identity" },
- });
- });
-
- it("reports an already-authenticated login as a no-op", async () => {
- const flows = fakeFlows({
- runLoginFlow: vi.fn<TuiSetupFlows["runLoginFlow"]>(async () => ({ kind: "already" })),
- });
- await expect(run({ command: "vc:login", flows })).resolves.toEqual({
- message: "You're already logged in to Vercel.",
+ message: "",
+ cancelled: true,
+ tone: undefined,
preserveFlowDiagnostics: false,
- });
- });
-
- it("routes a missing CLI from /vc:login to /vc:install", async () => {
- const flows = fakeFlows({
- runLoginFlow: vi.fn<TuiSetupFlows["runLoginFlow"]>(async () => ({ kind: "cli-missing" })),
- });
- await expect(run({ command: "vc:login", flows })).resolves.toEqual({
- message:
- "The Vercel CLI isn't installed — run /vc:install to install it, then retry /vc:login.",
- preserveFlowDiagnostics: true,
- });
- });
-
- it("reports an unavailable Vercel API without asking the user to log in again", async () => {
- const flows = fakeFlows({
- runLoginFlow: vi.fn<TuiSetupFlows["runLoginFlow"]>(async () => ({ kind: "unavailable" })),
- });
- await expect(run({ command: "vc:login", flows })).resolves.toEqual({
- message: "Couldn't reach Vercel — check your connection, then retry /vc:login.",
- preserveFlowDiagnostics: true,
+ effect: { kind: "model-access-changed", reload: true },
});
});
@@ -697,13 +657,13 @@ describe("runTuiSetupCommand", () => {
});
await expect(run({ command: "add", flows })).resolves.toMatchObject({
- message: expect.stringMatching(/^Added Web Chat[\s\S]*run \/vc:login/),
+ message: expect.stringMatching(/^Added Web Chat[\s\S]*run \/deploy/),
partial: true,
tone: "error",
});
});
- it("routes a forbidden (SSO) scope error to /vc:login with a re-auth message", async () => {
+ it("routes a forbidden (SSO) scope error to /deploy with a re-auth message", async () => {
const flows = fakeFlows({
runDeployFlow: vi.fn<TuiSetupFlows["runDeployFlow"]>(async () => {
throw new HumanActionRequiredError({
@@ -715,7 +675,7 @@ describe("runTuiSetupCommand", () => {
});
await expect(run({ command: "deploy", flows })).resolves.toEqual({
message:
- "Vercel denied access to that team — run /vc:login to re-authenticate (for example to complete SSO), or pick a team you can access, then retry /deploy.",
+ "Vercel denied access to that team — check your team access and SSO, then retry /deploy.",
tone: "error",
preserveFlowDiagnostics: true,
});
@@ -736,7 +696,7 @@ describe("runTuiSetupCommand", () => {
});
});
- it("routes a missing-CLI action to the install command instead of /vc:login", async () => {
+ it("routes a missing-CLI action to the install command instead of /deploy", async () => {
const flows = fakeFlows({
runDeployFlow: vi.fn<TuiSetupFlows["runDeployFlow"]>(async () => {
throw new HumanActionRequiredError({
@@ -747,35 +707,9 @@ describe("runTuiSetupCommand", () => {
}),
});
await expect(run({ command: "deploy", flows })).resolves.toEqual({
- message:
- "The Vercel CLI isn't installed — run /vc:install to install it, then retry /deploy.",
+ message: "The Vercel CLI isn't installed — run /deploy to install it, then retry /deploy.",
tone: "error",
preserveFlowDiagnostics: true,
});
});
-
- it("reports an installed CLI and refreshes the link identity", async () => {
- const flows = fakeFlows({
- runInstallVercelCliFlow: vi.fn<TuiSetupFlows["runInstallVercelCliFlow"]>(async () => ({
- kind: "installed",
- })),
- });
- await expect(run({ command: "vc:install", flows })).resolves.toEqual({
- message: "Installed the Vercel CLI. Run /vc:login next.",
- preserveFlowDiagnostics: false,
- effect: { kind: "refresh-identity" },
- });
- });
-
- it("reports an already-installed CLI as a no-op", async () => {
- const flows = fakeFlows({
- runInstallVercelCliFlow: vi.fn<TuiSetupFlows["runInstallVercelCliFlow"]>(async () => ({
- kind: "already",
- })),
- });
- await expect(run({ command: "vc:install", flows })).resolves.toEqual({
- message: "The Vercel CLI is already installed.",
- preserveFlowDiagnostics: false,
- });
- });
});
diff --git a/packages/eve/src/cli/dev/tui/setup-commands.ts b/packages/eve/src/cli/dev/tui/setup-commands.ts
index bb208530d..ecf5c29fc 100644
--- a/packages/eve/src/cli/dev/tui/setup-commands.ts
+++ b/packages/eve/src/cli/dev/tui/setup-commands.ts
@@ -1,18 +1,15 @@
+import type { ModelAccessChange } from "#shared/model-connection.js";
+import { runModelLogin } from "#setup/flows/model-login.js";
import { HumanActionRequiredError } from "#setup/human-action.js";
import { runDeployFlow } from "#setup/flows/deploy.js";
import {
runInstallVercelCliFlow,
type InstallVercelCliResult,
} from "#setup/flows/install-vercel-cli.js";
-import { runLoginFlow, type LoginFlowResult } from "#setup/flows/login.js";
+
import { runModelFlow } from "#setup/flows/model.js";
import type { ProviderSelection } from "#setup/provider-settings.js";
-import { runProviderFlow, type ProviderPicker } from "#setup/flows/provider.js";
-import {
- RegistryFlowFailedError,
- runRegistryFlow,
- type RegistryPlannerContext,
-} from "#setup/flows/registry.js";
+import { RegistryFlowFailedError, runRegistryFlow } from "#setup/flows/registry.js";
import type { Prompter } from "#setup/prompter.js";
import { WizardCancelledError } from "#setup/step.js";
@@ -34,8 +31,7 @@ export type TuiSetupCommand = PromptCommandExtensionName;
* move past their opening question.
*/
export const SETUP_FLOW_CONFIG = {
- "vc:install": { title: "Install the Vercel CLI", indicator: "pulse" },
- "vc:login": { title: "Log in to Vercel", indicator: "pulse" },
+ login: { title: "Connecting your model", indicator: "pulse" },
model: { title: "Configure the agent model", indicator: "pulse" },
add: { title: "Add to your agent", indicator: "pulse" },
deploy: { title: "Deploy to Vercel", indicator: "spinner" },
@@ -74,11 +70,10 @@ export interface TuiSetupCommandInput {
/** Registry address supplied by `/add <item>`, confirmed and installed directly. */
initialRegistryAddress?: string;
/** Presentation and navigation supplied by an enclosing setup journey. */
- registryPlannerContext?: RegistryPlannerContext;
onOnboardingScreen?: (input: OnboardingScreenEvent) => void;
/** Live ChatGPT identity shown only inside model configuration UI. */
chatGptAccountLabel?: string;
- /** Suspends development runtime artifacts while registry installation and setup mutate them. */
+ /** Groups setup writes under one runtime update. */
withExclusiveTerminal?<T>(task: () => Promise<T>): Promise<T>;
createPrompter?: (renderer: TuiPrompterRenderer) => Prompter;
/** Test seam; defaults to the real setup flows. */
@@ -86,8 +81,8 @@ export interface TuiSetupCommandInput {
}
export interface TuiSetupFlows {
+ runModelLogin?: typeof runModelLogin;
runInstallVercelCliFlow: typeof runInstallVercelCliFlow;
- runLoginFlow: typeof runLoginFlow;
runModelFlow: typeof runModelFlow;
runRegistryFlow: typeof runRegistryFlow;
runDeployFlow: typeof runDeployFlow;
@@ -104,7 +99,7 @@ export interface TuiSetupCommandResult {
/** Keep warning/error lines after the bordered panel closes. */
preserveFlowDiagnostics: boolean;
/** Status refresh required after the command settles. */
- effect?: VercelStatusEffect | { kind: "model-access-changed" };
+ effect?: VercelStatusEffect | ModelAccessChange;
}
/**
@@ -157,6 +152,10 @@ function muteableRenderer(
};
}
+function cancelledSetupResult(): TuiSetupCommandResult {
+ return { message: "", cancelled: true, preserveFlowDiagnostics: false };
+}
+
/**
* Runs one TUI setup command (/model, /add, /deploy) over the
* shared setup flows, asking through the TUI's own bordered panel. Never throws:
@@ -220,9 +219,8 @@ export async function runTuiSetupCommand(
? outcome
: {
...outcome,
- message: `/${command} interrupted.`,
- tone: "error",
- preserveFlowDiagnostics: true,
+ ...cancelledSetupResult(),
+ tone: undefined,
};
}
} finally {
@@ -247,7 +245,6 @@ async function executeSetupCommand(
const { command, appRoot } = input;
const flows: TuiSetupFlows = {
runInstallVercelCliFlow,
- runLoginFlow,
runModelFlow,
runRegistryFlow,
runDeployFlow,
@@ -256,16 +253,32 @@ async function executeSetupCommand(
try {
switch (command) {
- case "vc:install": {
- return installVercelCliResultMessage(
- await flows.runInstallVercelCliFlow({ appRoot, prompter, signal }),
- );
- }
- case "vc:login": {
- return loginResultMessage(await flows.runLoginFlow({ appRoot, prompter, signal }));
+ case "login": {
+ const result = await (flows.runModelLogin ?? runModelLogin)({
+ appRoot,
+ agentRoot: input.agentRoot,
+ prompter,
+ signal,
+ automatic: input.initialModelStep === "provider",
+ withConnectionUpdate: input.withExclusiveTerminal,
+ });
+ return result.kind === "cancelled"
+ ? {
+ message: "Connect a model with /login when you’re ready.",
+ cancelled: true,
+ preserveFlowDiagnostics: false,
+ }
+ : {
+ message: "Connected. Start chatting · /add to extend your agent",
+ effect: {
+ kind: "model-access-changed",
+ reload: result.reload,
+ ...(result.model && { model: result.model }),
+ },
+ preserveFlowDiagnostics: false,
+ };
}
case "model": {
- const pickProvider: ProviderPicker = (request) => renderer.readProviderPicker(request);
const modelInput: Parameters<TuiSetupFlows["runModelFlow"]>[0] = {
appRoot: input.agentRoot ?? appRoot,
environmentRoot: appRoot,
@@ -274,17 +287,6 @@ async function executeSetupCommand(
chatGptAccountLabel: input.chatGptAccountLabel,
deps: {
pickModelSettings: (request) => renderer.readModelEditor(request),
- runProviderFlow: (providerInput) =>
- runProviderFlow({
- ...providerInput,
- picker: pickProvider,
- recoverHumanAction: (error) =>
- recoverVercelHumanAction(error, flows, {
- appRoot,
- prompter,
- signal,
- }),
- }),
},
};
if (input.initialModelStep !== undefined) {
@@ -295,14 +297,7 @@ async function executeSetupCommand(
}
const result = await flows.runModelFlow(modelInput);
if (result.kind === "cancelled") {
- return {
- message:
- result.discardedDraft === true
- ? "/model dismissed. Drafted changes were discarded; Done commits them."
- : "/model dismissed.",
- cancelled: true,
- preserveFlowDiagnostics: false,
- };
+ return cancelledSetupResult();
}
// One line per completed menu action: the apply line (it already
// distinguishes success from a rejected slug), then the provider
@@ -319,7 +314,7 @@ async function executeSetupCommand(
// A model edit can also move routing between AI Gateway and ChatGPT.
// The runner rebuilds authored artifacts before refreshing model access.
if (result.accessChanged) {
- outcome.effect = { kind: "model-access-changed" };
+ outcome.effect = { kind: "model-access-changed", reload: true };
}
return outcome;
}
@@ -329,13 +324,12 @@ async function executeSetupCommand(
prompter,
signal,
initialAddress: input.initialRegistryAddress,
- plannerContext: input.registryPlannerContext,
onScreen: input.onOnboardingScreen,
onItemStart: registryItemProgress(renderer),
runItem: runRegistryItem,
});
if (flow.kind === "cancelled") {
- return { message: "/add dismissed.", cancelled: true, preserveFlowDiagnostics: true };
+ return cancelledSetupResult();
}
const result = flow.result;
const tone = registryResultTone(result);
@@ -357,11 +351,12 @@ async function executeSetupCommand(
case "deploy": {
const result = await flows.runDeployFlow({ appRoot, prompter, interactive: true, signal });
if (result.kind === "cancelled") {
- return { message: "/deploy dismissed.", preserveFlowDiagnostics: true };
+ return cancelledSetupResult();
}
if (result.kind === "needs-link") {
return {
- message: "Not linked to a Vercel project — run /model to connect one first.",
+ message:
+ "Not linked to a Vercel project. Run eve deploy in an interactive terminal to link it.",
preserveFlowDiagnostics: true,
};
}
@@ -382,11 +377,7 @@ async function executeSetupCommand(
}
} catch (error) {
if (error instanceof WizardCancelledError) {
- return {
- message: `/${command} dismissed.`,
- cancelled: true,
- preserveFlowDiagnostics: command !== "model",
- };
+ return cancelledSetupResult();
}
const actionableError = error instanceof RegistryFlowFailedError ? error.cause : error;
const upgrade = await vercelCliUpgradeOutcome(actionableError, command, flows, {
@@ -416,81 +407,6 @@ async function executeSetupCommand(
}
}
-async function recoverVercelHumanAction(
- error: HumanActionRequiredError,
- flows: TuiSetupFlows,
- input: { appRoot: string; prompter: Prompter; signal: AbortSignal },
-): Promise<"retry" | "cancel"> {
- const action = error.action.kind;
- if (
- action !== "vercel-cli-missing" &&
- action !== "vercel-cli-upgrade" &&
- action !== "vercel-login" &&
- action !== "vercel-forbidden"
- ) {
- throw error;
- }
-
- const repair =
- action === "vercel-cli-missing"
- ? { label: "Install Vercel CLI", message: "The Vercel CLI is required. Install it now?" }
- : action === "vercel-cli-upgrade"
- ? {
- label: "Upgrade Vercel CLI",
- message: "Your Vercel CLI needs an update. Upgrade it now?",
- }
- : {
- label:
- action === "vercel-forbidden" ? "Re-authenticate with Vercel" : "Log in to Vercel",
- message:
- action === "vercel-forbidden"
- ? "Vercel denied access to that team. Re-authenticate and continue?"
- : "You need to log in to Vercel to continue.",
- };
-
- let choice: "repair" | "cancel";
- try {
- choice = await input.prompter.select({
- message: repair.message,
- options: [
- { value: "repair", label: `${repair.label} and continue` },
- { value: "cancel", label: "Choose another option" },
- ],
- initialValue: "repair",
- });
- } catch {
- return "cancel";
- }
- if (choice === "cancel") return "cancel";
-
- if (action === "vercel-cli-missing" || action === "vercel-cli-upgrade") {
- const result = await flows.runInstallVercelCliFlow({
- appRoot: input.appRoot,
- prompter: input.prompter,
- signal: input.signal,
- upgrade: action === "vercel-cli-upgrade",
- });
- if (result.kind === "installed" || result.kind === "already") return "retry";
- input.prompter.log.warning(
- result.kind === "failed" && result.reason !== undefined
- ? `Couldn't ${action === "vercel-cli-upgrade" ? "upgrade" : "install"} the Vercel CLI: ${result.reason}`
- : `Couldn't ${action === "vercel-cli-upgrade" ? "upgrade" : "install"} the Vercel CLI.`,
- );
- return "cancel";
- }
-
- const login = await flows.runLoginFlow({
- appRoot: input.appRoot,
- prompter: input.prompter,
- signal: input.signal,
- force: action === "vercel-forbidden",
- });
- // Device-login output belongs only to the login attempt. Clear it before
- // either linking or the provider picker resumes.
- input.prompter.replaceContent?.();
- return login.kind === "logged-in" || login.kind === "already" ? "retry" : "cancel";
-}
-
function withRegistryResults(
outcome: TuiSetupCommandResult,
error: unknown,
@@ -620,11 +536,11 @@ function vercelActionOutcome(error: unknown, command: string): TuiSetupCommandRe
function vercelActionMessage(kind: string, command: string): string | undefined {
switch (kind) {
case "vercel-login":
- return `You're not logged in to Vercel — run /vc:login, then retry /${command}.`;
+ return `You're not logged in to Vercel — run /deploy to connect your Vercel account, then retry /${command}.`;
case "vercel-forbidden":
- return `Vercel denied access to that team — run /vc:login to re-authenticate (for example to complete SSO), or pick a team you can access, then retry /${command}.`;
+ return `Vercel denied access to that team — check your team access and SSO, then retry /${command}.`;
case "vercel-cli-missing":
- return `The Vercel CLI isn't installed — run /vc:install to install it, then retry /${command}.`;
+ return `The Vercel CLI isn't installed — run /deploy to install it, then retry /${command}.`;
case "vercel-cli-upgrade":
return `The Vercel CLI needs an update — run \`vercel upgrade\`, then retry /${command}.`;
default:
@@ -632,63 +548,6 @@ function vercelActionMessage(kind: string, command: string): string | undefined
}
}
-/** Folds an {@link InstallVercelCliResult} into the command's one-line outcome. */
-function installVercelCliResultMessage(result: InstallVercelCliResult): TuiSetupCommandResult {
- switch (result.kind) {
- case "cancelled":
- return { message: "/vc:install dismissed.", preserveFlowDiagnostics: false };
- case "already":
- return { message: "The Vercel CLI is already installed.", preserveFlowDiagnostics: false };
- case "failed":
- return {
- message:
- "Couldn't install the Vercel CLI — install it manually with `npm i -g vercel@latest`.",
- preserveFlowDiagnostics: true,
- };
- case "installed":
- return {
- message: "Installed the Vercel CLI. Run /vc:login next.",
- preserveFlowDiagnostics: false,
- // The CLI now resolves, so the status line's identity probe can run.
- effect: { kind: "refresh-identity" },
- };
- }
-}
-
-/** Folds a {@link LoginFlowResult} into the command's one-line outcome. */
-function loginResultMessage(result: LoginFlowResult): TuiSetupCommandResult {
- switch (result.kind) {
- case "cancelled":
- return { message: "/vc:login dismissed.", preserveFlowDiagnostics: false };
- case "already":
- return { message: "You're already logged in to Vercel.", preserveFlowDiagnostics: false };
- case "cli-missing":
- return {
- message:
- "The Vercel CLI isn't installed — run /vc:install to install it, then retry /vc:login.",
- preserveFlowDiagnostics: true,
- };
- case "failed":
- return {
- message: "Vercel login didn't complete — run /vc:login to try again.",
- preserveFlowDiagnostics: true,
- };
- case "logged-in":
- return {
- message: "Logged in to Vercel.",
- preserveFlowDiagnostics: false,
- // A now-valid `whoami` lets a previously-linked directory resolve its
- // project identity for the status line.
- effect: { kind: "refresh-identity" },
- };
- case "unavailable":
- return {
- message: "Couldn't reach Vercel — check your connection, then retry /vc:login.",
- preserveFlowDiagnostics: true,
- };
- }
-}
-
function providerSelectionMessage(selection: ProviderSelection): string {
if (selection === "chatgpt") return "ChatGPT subscription selected.";
return selection === "ai-gateway-project"
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.ts
index 9432407b9..f47a54139 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
@@ -55,7 +55,7 @@ describe("BOOT_DETECTIONS against a real directory", () => {
const appRoot = await linkedAppRoot();
const issues = await detectSetupIssues({ appRoot, env: {} });
expect(issues).toEqual([
- { kind: "attention", label: "AI Gateway credentials missing", command: "/model" },
+ { kind: "attention", label: "AI Gateway credentials missing", command: "/login" },
]);
});
@@ -71,12 +71,12 @@ describe("BOOT_DETECTIONS against a real directory", () => {
{
kind: "attention",
label: "AI Gateway credentials missing",
- command: "/model",
+ command: "/login",
},
]);
});
- it("opens model setup from the prefilled onboarding prompt when inspection is unavailable", async () => {
+ it("opens only login during onboarding when inspection is unavailable", async () => {
const appRoot = await linkedAppRoot();
const client = new Client({ host: "http://localhost:3000" });
vi.spyOn(client, "info").mockRejectedValue(new Error("inspection unavailable"));
@@ -112,45 +112,11 @@ describe("BOOT_DETECTIONS against a real directory", () => {
await runner.run();
- expect(handle).toHaveBeenNthCalledWith(
- 1,
- { type: "extension", name: "model", argument: "" },
- expect.objectContaining({
- renderer,
- title: "eve",
- initialModelStep: "provider",
- keepSetupFlowOpen: true,
- setupFlowTitle: "Set up eve",
- setupFlowNavigation: {
- kind: "planner",
- activeStep: 0,
- firstNavigableStep: 1,
- steps: [
- { label: "Model", complete: false },
- { label: "Channels" },
- { label: "Integrations" },
- { label: "Review" },
- ],
- },
- }),
- );
- expect(handle).toHaveBeenNthCalledWith(
- 2,
- { type: "extension", name: "add", argument: "" },
- expect.objectContaining({
- renderer,
- title: "eve",
- keepSetupFlowOpen: true,
- setupFlowTitle: "Set up eve",
- registryPlannerContext: {
- prefixSteps: [{ label: "Model", complete: true }],
- reviewMessage: "Review your agent",
- primaryActionLabel: "Install and finish setup",
- emptyActionLabel: "Finish setup",
- },
- }),
+ expect(handle).toHaveBeenCalledExactlyOnceWith(
+ { type: "extension", name: "login", argument: "" },
+ expect.objectContaining({ renderer, title: "eve", initialModelStep: "provider" }),
);
expect(readPrompt).toHaveBeenCalledOnce();
- expect(order).toEqual(["model", "add", "prompt"]);
+ expect(order).toEqual(["login", "prompt"]);
});
});
diff --git a/packages/eve/src/cli/dev/tui/setup-issues.test.ts b/packages/eve/src/cli/dev/tui/setup-issues.test.ts
index 488964c5c..8d0127242 100644
--- a/packages/eve/src/cli/dev/tui/setup-issues.test.ts
+++ b/packages/eve/src/cli/dev/tui/setup-issues.test.ts
@@ -37,9 +37,7 @@ function infoWithRouting(
describe("BOOT_DETECTIONS", () => {
it("keeps an unavailable runtime diagnostic-only", async () => {
const issues = await detectSetupIssues(context());
- expect(issues).toEqual([
- { kind: "attention", label: "model provider not linked", command: "/model" },
- ]);
+ expect(issues).toEqual([{ kind: "attention", label: "connect a model", command: "/login" }]);
});
it("diagnoses a disconnected gateway", async () => {
@@ -52,8 +50,8 @@ describe("BOOT_DETECTIONS", () => {
expect(issues).toEqual([
{
kind: "attention",
- label: "model provider not linked",
- command: "/model",
+ label: "connect a model",
+ command: "/login",
},
]);
});
@@ -96,9 +94,7 @@ describe("BOOT_DETECTIONS", () => {
])("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" },
- ]);
+ expect(issues).toEqual([{ kind: "attention", label: "connect a model", command: "/login" }]);
});
it("stays quiet for an external-provider model — gateway linking/credentials don't apply", async () => {
@@ -135,18 +131,18 @@ describe("formatSetupIssuesLine", () => {
it("mirrors the Claude Code attention-line shape", () => {
expect(
formatSetupIssuesLine([
- { kind: "attention", label: "AI Gateway credentials", command: "/model" },
+ { kind: "attention", label: "AI Gateway credentials", command: "/login" },
]),
- ).toBe("1 setup issue: AI Gateway credentials · /model");
+ ).toBe("1 setup issue: AI Gateway credentials · /login");
});
it("pluralizes and joins multiple issues", () => {
expect(
formatSetupIssuesLine([
- { kind: "attention", label: "AI Gateway credentials", command: "/model" },
+ { kind: "attention", label: "AI Gateway credentials", command: "/login" },
{ kind: "attention", label: "Channels", command: "/channels" },
]),
- ).toBe("2 setup issues: AI Gateway credentials · /model, Channels · /channels");
+ ).toBe("2 setup issues: AI Gateway credentials · /login, Channels · /channels");
});
it("formats the logged-out hint, which is not a boot detection", () => {
@@ -154,13 +150,13 @@ describe("formatSetupIssuesLine", () => {
// outside the cheap-and-local BOOT_DETECTIONS and is rendered by the runner.
expect(BOOT_DETECTIONS.some((detection) => detection.id === "login")).toBe(false);
expect(formatSetupIssuesLine([LOGIN_SETUP_ISSUE])).toBe(
- "1 setup issue: not logged in · /vc:login",
+ "1 setup issue: not logged in · /deploy",
);
});
it("formats the CLI-missing hint, which points at its own fix command", () => {
expect(formatSetupIssuesLine([CLI_MISSING_SETUP_ISSUE])).toBe(
- "1 setup issue: Vercel CLI not found · /vc:install",
+ "1 setup issue: Vercel CLI not found · /deploy",
);
});
});
@@ -169,8 +165,8 @@ describe("orderedSetupIssues", () => {
it("puts the auth prerequisite before the boot detections", () => {
const modelIssue = {
kind: "attention" as const,
- label: "model provider not linked",
- command: "/model" as const,
+ label: "connect a model",
+ command: "/login" as const,
};
expect(orderedSetupIssues([modelIssue], CLI_MISSING_SETUP_ISSUE)).toEqual([
CLI_MISSING_SETUP_ISSUE,
@@ -184,8 +180,26 @@ describe("orderedSetupIssues", () => {
it("returns the boot issues unchanged when no auth prerequisite is unmet", () => {
const boot = [
- { kind: "attention" as const, label: "AI Gateway credentials missing", command: "/model" },
+ { kind: "attention" as const, label: "AI Gateway credentials missing", command: "/login" },
];
expect(orderedSetupIssues(boot, undefined)).toEqual(boot);
});
});
+
+it("preserves a validated Vercel connection and team when a shell Gateway key also exists", () => {
+ const info = infoWithRouting(
+ { kind: "gateway", target: "openai" },
+ {
+ kind: "gateway",
+ connected: true,
+ credential: "oauth",
+ team: "alice",
+ },
+ );
+ expect(
+ normalizeLocalModelEndpoint(info, {
+ EVE_MODEL_CONNECTION: "vercel",
+ AI_GATEWAY_API_KEY: "other-key",
+ }),
+ ).toBe(info);
+});
diff --git a/packages/eve/src/cli/dev/tui/setup-issues.ts b/packages/eve/src/cli/dev/tui/setup-issues.ts
index 378bf1e61..6694067fd 100644
--- a/packages/eve/src/cli/dev/tui/setup-issues.ts
+++ b/packages/eve/src/cli/dev/tui/setup-issues.ts
@@ -40,7 +40,7 @@ type ModelProviderAccess =
| {
kind: "gateway";
runtime:
- | { status: "connected"; credential: "api-key" | "oidc" }
+ | { status: "connected"; credential: "api-key" | "oidc" | "oauth" }
| { status: "disconnected" }
| { status: "unknown" };
};
@@ -102,9 +102,15 @@ function modelProviderAccess(
// ranking delegates to the one precedence authority; the server-reported
// endpoint snapshot slots between a freshly loaded key (which outranks a
// stale snapshot) and a local OIDC token (which the snapshot outranks).
+ const selected = context.env.EVE_MODEL_CONNECTION;
const local = resolveGatewayCredential({
- apiKeyInEnv: hasEnvValue(context.env["AI_GATEWAY_API_KEY"]),
- oidcAvailable: hasEnvValue(context.env["VERCEL_OIDC_TOKEN"]),
+ apiKeyInEnv:
+ (selected === undefined ||
+ (selected === "ai-gateway-key" && context.env.EVE_MODEL_KEY_SOURCE !== "secret")) &&
+ hasEnvValue(context.env.AI_GATEWAY_API_KEY),
+ oidcAvailable:
+ (selected === undefined || selected === "ai-gateway-project") &&
+ hasEnvValue(context.env.VERCEL_OIDC_TOKEN),
});
if (local?.credential === "api-key") {
return { kind: "gateway", runtime: { status: "connected", credential: "api-key" } };
@@ -146,8 +152,8 @@ const modelProvider: BootDetection = {
return [
{
kind: "attention",
- label: linked ? "AI Gateway credentials missing" : "model provider not linked",
- command: "/model",
+ label: linked ? "AI Gateway credentials missing" : "connect a model",
+ command: "/login",
},
];
}
@@ -155,9 +161,9 @@ const modelProvider: BootDetection = {
const linked = await pathExists(join(appRoot, ".vercel", "project.json"));
if (linked) {
- return [{ kind: "attention", label: "AI Gateway credentials missing", command: "/model" }];
+ return [{ kind: "attention", label: "AI Gateway credentials missing", command: "/login" }];
}
- return [{ kind: "attention", label: "model provider not linked", command: "/model" }];
+ return [{ kind: "attention", label: "connect a model", command: "/login" }];
},
};
@@ -174,19 +180,19 @@ export const BOOT_DETECTIONS: readonly BootDetection[] = [modelProvider];
export const LOGIN_SETUP_ISSUE: SetupIssue = {
kind: "attention",
label: "not logged in",
- command: "/vc:login",
+ command: "/deploy",
};
/**
* The CLI-missing hint, surfaced by the same off-critical-path probe as
* {@link LOGIN_SETUP_ISSUE}. When the `vercel` binary is absent the probe
* reports this instead of the login hint, so the diagnostic points at its fix
- * command (`/vc:install`) rather than a logged-out state the probe can't determine.
+ * command (`/deploy`) rather than a logged-out state the probe can't determine.
*/
export const CLI_MISSING_SETUP_ISSUE: SetupIssue = {
kind: "attention",
label: "Vercel CLI not found",
- command: "/vc:install",
+ command: "/deploy",
};
/**
diff --git a/packages/eve/src/cli/dev/tui/setup-panel.test.ts b/packages/eve/src/cli/dev/tui/setup-panel.test.ts
index 2f8943f72..05ff13927 100644
--- a/packages/eve/src/cli/dev/tui/setup-panel.test.ts
+++ b/packages/eve/src/cli/dev/tui/setup-panel.test.ts
@@ -8,7 +8,6 @@ import {
renderModelEditorQuestion,
renderSelectQuestion,
renderTextQuestion,
- type SetupPanelOption,
} from "./setup-panel.js";
import { stripAnsi } from "#cli/ui/terminal-text.js";
import { createTheme } from "./theme.js";
@@ -27,6 +26,22 @@ const PLANNER_NAVIGATION = {
};
describe("renderFlowPanel", () => {
+ it.each(["Add to your agent", "Connect a model"])("renders %s only once", (title) => {
+ const rows = renderFlowPanel(
+ {
+ title,
+ lines: [],
+ content: {
+ kind: "question",
+ title,
+ rows: [" type to filter"],
+ },
+ },
+ colorTheme,
+ 80,
+ );
+ expect(stripAnsi(rows.join("\n")).split(title)).toHaveLength(2);
+ });
it("aligns the base-foreground title, progress, and question content", () => {
const rows = renderFlowPanel(
{
@@ -37,7 +52,7 @@ describe("renderFlowPanel", () => {
],
content: {
kind: "question",
- rows: [" Vercel project", "", " ▷ Create a new project"],
+ rows: [" Vercel project", "", " › Create a new project"],
},
},
theme,
@@ -45,11 +60,11 @@ describe("renderFlowPanel", () => {
);
const text = rows.join("\n");
- expect(rows[0]).toBe("▔".repeat(59));
- expect(rows[1]).toBe(" /deploy");
+ expect(rows[0]).toBe(" /deploy");
+ expect(text).not.toContain("▔");
expect(text).toContain(" · Creating Vercel project…");
expect(text).toContain(" ✓ Linked");
- expect(text).toContain(" ▷ Create a new project");
+ expect(text).toContain(" › Create a new project");
});
it("renders multiline diagnostics as separate terminal rows", () => {
@@ -148,7 +163,7 @@ describe("renderFlowPanel", () => {
text: "Creating a Slackbot through Vercel Connect…",
indicator: { glyph: "▪", color: "green" },
},
- rows: [" ◦ Try again", " ◦ Cancel"],
+ rows: [" Try again", " Cancel"],
},
},
theme,
@@ -156,14 +171,37 @@ describe("renderFlowPanel", () => {
).join("\n");
expect(text).toContain("▪ Creating a Slackbot through Vercel Connect…");
- expect(text).toContain("◦ Try again");
- expect(text).toContain("◦ Cancel");
+ expect(text).toContain(" Try again");
+ expect(text).toContain(" Cancel");
// The spinner leads; the actions follow.
expect(text.indexOf("Creating a Slackbot")).toBeLessThan(text.indexOf("Try again"));
});
});
describe("renderSelectQuestion", () => {
+ it.each([32, 100])(
+ "filters by capability without displaying search metadata at width %i",
+ (width) => {
+ const options = [
+ { value: "blooio", label: "Blooio", keywords: ["Send and receive iMessage and SMS."] },
+ { value: "slack", label: "Slack" },
+ ];
+ const text = renderSelectQuestion(
+ {
+ kind: "search",
+ message: "Add to your agent",
+ options,
+ select: { ...initialSelectState({ options }), filter: "imessage" },
+ },
+ theme,
+ width,
+ ).join("\n");
+ expect(text).toContain("› Blooio");
+ expect(text).not.toContain("Slack");
+ expect(text).not.toContain("Send and receive");
+ },
+ );
+
it("renders question context beneath the heading and above compact actions", () => {
const rows = renderSelectQuestion(
{
@@ -195,37 +233,11 @@ describe("renderSelectQuestion", () => {
" Source: Official eve registry",
" Packages: @agent-browser/eve",
"",
- " ▶ Add to project ",
+ " › Add to project",
" Back",
]);
});
- 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(
{
@@ -243,29 +255,12 @@ describe("renderSelectQuestion", () => {
expect(text).not.toContain("▔".repeat(10));
// The lone hint sits one space past its own label — the longer hint-less
// "Link an existing project" no longer pads the column open.
- expect(text).toContain(" ▶ Create a new project · fastest");
+ expect(text).toContain(" › Create a new project · fastest");
expect(text).toContain(" Link an existing project");
expect(text).not.toContain("1.");
expect(text).toContain("esc to cancel");
});
- it("uses the theme's ASCII option placeholder", () => {
- const ascii = createTheme({ color: false, unicode: false });
- const rows = renderSelectQuestion(
- {
- kind: "stacked",
- message: "Vercel project",
- options: OPTIONS,
- select: initialSelectState({ options: OPTIONS }),
- },
- ascii,
- 60,
- );
-
- expect(rows).toContain(" . Link an existing project");
- expect(rows.join("\n")).not.toContain("◦");
- });
-
it("drops the numbers for a lone option", () => {
const lone = [{ value: "relink", label: "Link to another project" }];
const text = renderSelectQuestion(
@@ -279,7 +274,7 @@ describe("renderSelectQuestion", () => {
60,
).join("\n");
- expect(text).toContain(" ▶ Link to another project ");
+ expect(text).toContain(" › Link to another project");
expect(text).not.toContain("1.");
const colored = renderSelectQuestion(
@@ -292,7 +287,7 @@ describe("renderSelectQuestion", () => {
colorTheme,
60,
).join("\n");
- expect(colored).toContain("\x1b[7m\x1b[34m ▶ Link to another project \x1b[39m\x1b[27m");
+ expect(colored).toContain("\x1b[1m › Link to another project\x1b[22m");
});
it("renders completed task rows as focusable but not highlighted actions", () => {
@@ -329,7 +324,7 @@ describe("renderSelectQuestion", () => {
);
// The focused completed row reads as inert: a dim pointer, not a check.
- expect(rows).toContain(" ▷ Terminal UI · Already installed");
+ expect(rows).toContain(" › Terminal UI · Already installed");
expect(rows).not.toContain(" ✓ Terminal UI");
// An unfocused completed row keeps its check.
expect(rows).toContain(" ✓ Web Chat");
@@ -337,7 +332,7 @@ describe("renderSelectQuestion", () => {
const warning = rows.indexOf(" ⚠ Overwrote /tmp/weather-agent");
const success = rows.indexOf(" ✓ Scaffolded channel: web");
const done = rows.indexOf(" Done");
- expect(rows.indexOf(" ◦ Slack · Creates slackbot and deploys to Vercel")).toBeLessThan(
+ expect(rows.indexOf(" Slack · Creates slackbot and deploys to Vercel")).toBeLessThan(
warning,
);
expect(warning).toBeLessThan(success);
@@ -357,7 +352,7 @@ describe("renderSelectQuestion", () => {
);
const coloredRow = coloredRows.find((row) => row.includes("Terminal UI"));
// Focused completed row: dim pointer matching the dim label, never green or cyan.
- expect(coloredRow).toContain("\x1b[2m▷\x1b[22m");
+ expect(coloredRow).toContain("\x1b[2m›\x1b[22m");
expect(coloredRow).toContain("\x1b[2mTerminal UI\x1b[22m");
expect(coloredRow).toContain("\x1b[2m · Already installed\x1b[22m");
expect(coloredRow).not.toContain("\x1b[32m");
@@ -375,7 +370,7 @@ describe("renderSelectQuestion", () => {
theme,
60,
).join("\n");
- expect(multi).toContain(" ▶ Create a new project ");
+ expect(multi).toContain(" › Create a new project ");
expect(multi).not.toContain("1.");
const searchable = renderSelectQuestion(
@@ -438,29 +433,6 @@ describe("renderSelectQuestion", () => {
);
});
- it("rides a disabled row's description on its own dim sub-line, not inline", () => {
- const plain = createTheme({ color: false });
- const options = [
- { value: "model", label: "Change model", disabled: true, description: "Disabled here" },
- { value: "done", label: "Done" },
- ];
- const text = renderSelectQuestion(
- {
- kind: "single",
- message: "Configure the agent model",
- options,
- select: initialSelectState({ options }),
- },
- plain,
- 80,
- ).join("\n");
-
- // The reason sits under the row, indented to the label column, not as an
- // inline parenthetical.
- expect(text).toContain("Change model\n Disabled here");
- expect(text).not.toContain("Change model (Disabled here)");
- });
-
it("wraps a long notice with a hanging indent under the glyph", () => {
const plain = createTheme({ color: false });
const options = [{ value: "done", label: "Done" }];
@@ -648,38 +620,6 @@ describe("renderSelectQuestion", () => {
expect(rows.at(-1)).not.toContain("type to rename");
});
- it("stacks hints under labels with separators and trailing notices", () => {
- const options = [
- { value: "model", label: "Change model", hint: "anthropic/claude-sonnet-5" },
- { value: "provider", label: "Change provider", hint: "AI Gateway via Project" },
- ];
- const rows = renderSelectQuestion(
- {
- kind: "stacked",
- message: "Configure the agent's model",
- options,
- notices: [{ tone: "success", text: "Model changed to openai/gpt-5.5" }],
- select: initialSelectState({ options }),
- },
- theme,
- 80,
- );
-
- expect(rows).toEqual([
- " Configure the agent's model",
- "",
- " ▶ Change model ",
- " anthropic/claude-sonnet-5",
- "",
- " ◦ Change provider",
- " AI Gateway via Project",
- "",
- " ✓ Model changed to openai/gpt-5.5",
- "",
- " ↑/↓ move · enter to select · esc to cancel",
- ]);
- });
-
it("owns emphasis for stacked and multiline select headings", () => {
const colored = createTheme({ color: true, unicode: true });
const stacked = renderSelectQuestion(
@@ -708,138 +648,6 @@ describe("renderSelectQuestion", () => {
expect(linked[1]).toBe(" \x1b[1mweather-agent-001 in Internal Playground\x1b[22m");
});
- it("keeps a stacked hint dim across an embedded bold span", () => {
- const colored = createTheme({ color: true, unicode: true });
- const options: SetupPanelOption[] = [
- { value: "model", label: "Change model" },
- {
- value: "provider",
- label: "Change provider",
- hint: "Selected (\x1b[1mvalue\x1b[22m)",
- },
- ];
- const text = renderSelectQuestion(
- {
- kind: "stacked",
- message: "Configure the agent's model",
- options,
- select: initialSelectState({ options }),
- },
- colored,
- 80,
- ).join("\n");
-
- // Bold's close (SGR 22) also ends dim — the renderer re-opens dim so the
- // hint's tail does not pop to full brightness.
- expect(text).toContain("\x1b[1mvalue\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 blue accent span inside the selected row's hint", () => {
- const hint = `xai/grok-4.5${colorTheme.colors.blue("@high ↯")}`;
- const options: SetupPanelOption[] = [
- { value: "model", label: "Change model", hint },
- { value: "done", label: "Done" },
- ];
- const rows = renderSelectQuestion(
- {
- kind: "stacked",
- message: "",
- options,
- select: initialSelectState({ options, defaultValue: "model" }),
- },
- colorTheme,
- 80,
- );
-
- // Blue survives the cursor row's foreground normalization; other authored
- // colors (see the yellow test above) still strip.
- expect(rows).toContain(` xai/grok-4.5${colorTheme.colors.blue("@high ↯")}`);
- });
-
- it("keeps a warning row yellow under the cursor highlight", () => {
- const options: SetupPanelOption[] = [
- {
- value: "provider",
- label: "Configure model access",
- accent: "warning",
- },
- ];
- const rows = renderSelectQuestion(
- {
- kind: "stacked",
- message: "",
- options,
- select: initialSelectState({ options }),
- },
- colorTheme,
- 80,
- );
-
- expect(rows).toContain(
- ` ${colorTheme.colors.inverse(colorTheme.colors.yellow(" ▶ Configure model access "))}`,
- );
- });
-
- it("renders each line of a stacked hint beneath its option", () => {
- const options = [
- {
- value: "ai-gateway-project",
- label: "AI Gateway via Project",
- hint: "Authenticates with AI Gateway automatically\nin a new or existing project. No keys to manage.",
- },
- ];
- 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,
@@ -857,7 +665,7 @@ describe("renderSelectQuestion", () => {
60,
).join("\n");
- expect(text).toContain("▶ Create a new project");
+ expect(text).toContain("› Create a new project");
expect(text).toContain("✓ Link an existing project");
expect(text).toContain("Submit");
expect(text).toContain("space to toggle");
@@ -890,132 +698,7 @@ describe("renderSelectQuestion", () => {
expect(text).toContain("Telegram");
});
- it("renders planner progress and navigation without a Submit row", () => {
- const options = [{ value: "web", label: "Web Chat", hint: "Built-in chat UI" }];
- const text = renderSelectQuestion(
- {
- kind: "searchable-multi",
- navigation: PLANNER_NAVIGATION,
- message: "Where should people reach your agent?",
- options,
- select: initialSelectState({ options, initialValues: ["web"] }),
- },
- colorTheme,
- 80,
- ).join("\n");
- const plain = stripAnsi(text);
-
- expect(text).toContain(
- colorTheme.colors.inverse(colorTheme.colors.blue(colorTheme.colors.bold(" Channels (1) "))),
- );
- expect(plain).toContain("Channels (1) → Integrations · Review");
- expect(plain).toContain("1 selected");
- expect(plain).toContain("space/enter toggle · → next");
- expect(plain).not.toContain("← back");
- expect(plain).not.toContain("Submit");
- });
-
- it("keeps the planner rail width stable as the active step changes", () => {
- const options = [{ value: "next", label: "Continue" }];
- const widths = PLANNER_NAVIGATION.steps.map((_, activeStep) => {
- const [rail] = renderSelectQuestion(
- {
- kind: "single",
- navigation: { ...PLANNER_NAVIGATION, activeStep },
- message: "Continue setup",
- options,
- select: initialSelectState({ options }),
- },
- colorTheme,
- 80,
- );
- return stripAnsi(rail ?? "").length;
- });
-
- expect(new Set(widths)).toEqual(new Set([40]));
- });
-
- it("advertises only available planner directions", () => {
- const options = [{ value: "install", label: "Install and set up" }];
- const review = renderSelectQuestion(
- {
- kind: "single",
- navigation: { ...PLANNER_NAVIGATION, activeStep: 2 },
- message: "Review additions",
- options,
- select: initialSelectState({ options }),
- },
- theme,
- 80,
- ).join("\n");
- const integrations = renderSelectQuestion(
- {
- kind: "searchable-multi",
- navigation: { ...PLANNER_NAVIGATION, activeStep: 1 },
- message: "Select integrations",
- options,
- select: initialSelectState({ options }),
- },
- theme,
- 80,
- ).join("\n");
-
- expect(review).toContain("Channels · Integrations ← Review ");
- expect(review).toContain("enter to select · ← back");
- expect(review).not.toContain("→ next");
- expect(integrations).toContain("Channels ← Integrations → Review");
- expect(integrations).toContain("space/enter toggle · ←/→ steps");
- });
-
- it("does not advertise arrows before planner navigation becomes available", () => {
- const options = [{ value: "model", label: "Use recommended model" }];
- const text = renderSelectQuestion(
- {
- kind: "single",
- navigation: {
- kind: "planner",
- activeStep: 0,
- firstNavigableStep: 1,
- steps: [{ label: "Model" }, { label: "Channels" }, { label: "Integrations" }],
- },
- message: "Choose a model",
- options,
- select: initialSelectState({ options }),
- },
- theme,
- 80,
- ).join("\n");
-
- expect(text).toContain(" Model · Channels · Integrations");
- expect(text).toContain("enter to select · esc to cancel");
- expect(text).not.toContain("→ next");
- });
-
- it("does not advertise navigation into completed prefix steps", () => {
- const options = [{ value: "web", label: "Web Chat" }];
- const text = renderSelectQuestion(
- {
- kind: "searchable-multi",
- navigation: {
- kind: "planner",
- activeStep: 1,
- firstNavigableStep: 1,
- steps: [{ label: "Model" }, { label: "Channels" }, { label: "Integrations" }],
- },
- message: "Select channels",
- options,
- select: initialSelectState({ options }),
- },
- theme,
- 80,
- ).join("\n");
-
- expect(text).toContain("Model · Channels → Integrations");
- expect(text).toContain("space/enter toggle · → next");
- expect(text).not.toContain("← back");
- });
-
- it("windows the railed list to five rows with an Esc-only footer", () => {
+ it("windows the compact list to five rows with a selection hint", () => {
const many = Array.from({ length: 20 }, (_, index) => ({
value: `model-${index}`,
label: `Model ${index}`,
@@ -1034,13 +717,13 @@ describe("renderSelectQuestion", () => {
const text = rows.join("\n");
// The filter rail sits in the option rows' glyph column.
- expect(text).toContain(" ▏ type to filter");
- expect(text).toContain(" ▶ Model 0");
- expect(text).toContain(" ▏ Model 4");
+ expect(text).toContain(" type to filter");
+ expect(text).toContain(" › Model 0");
+ expect(text).toContain(" Model 4");
expect(text).not.toContain("Model 5");
// The list scrolls silently: no count row, Esc is the whole footer.
expect(text).not.toContain("options, showing");
- expect(text).toContain("esc to cancel");
+ expect(text).toContain("Esc back");
expect(text).not.toContain("type to filter ·");
expect(text).not.toContain("↑/↓ move");
});
@@ -1086,27 +769,8 @@ describe("renderSelectQuestion", () => {
expect(rows[waiting + 1]).toBe("");
expect(retry).toBe(waiting + 2);
expect(rows[waiting]).toContain("· Waiting for you to complete setup in the browser");
- expect(rows.some((row) => row.includes("◦ Try again"))).toBe(true);
- expect(rows.some((row) => row.includes("◦ Cancel"))).toBe(true);
- });
-
- it("focuses actions independently from the inert context row", () => {
- const rows = renderSelectQuestion(
- {
- kind: "actions",
- context: "Waiting for you to complete setup in the browser",
- actions: ACTIONS,
- cursor: 0,
- },
- colorTheme,
- 70,
- );
- const context = rows.find((line) => line.includes("Waiting for you to complete setup"));
- const retry = rows.find((line) => line.includes("Try again"));
-
- expect(context).toContain("\x1b[2m· Waiting for you to complete setup in the browser\x1b[22m");
- expect(context).not.toContain("▷");
- expect(retry).toContain(colorTheme.colors.inverse(colorTheme.colors.blue(" ▶ Try again ")));
+ expect(rows.some((row) => row.includes(" Try again"))).toBe(true);
+ expect(rows.some((row) => row.includes(" Cancel"))).toBe(true);
});
});
@@ -1260,24 +924,6 @@ describe("renderModelEditorQuestion", () => {
} as never;
}
- it("paints the value menu with a hint line per row and a bare Done", () => {
- const text = renderModelEditorQuestion(
- { request: editorRequest(), state: editorState() },
- theme,
- 80,
- ).join("\n");
-
- expect(text).toContain("▶ Model");
- expect(text).toContain("anthropic/claude-sonnet-5");
- expect(text).toContain("Reasoning effort");
- // The mini track rides the hint: value first, notches joined by ━.
- expect(text).toContain("●─◉─○ medium");
- expect(text).toContain("Service tier");
- expect(text).toContain("normal");
- expect(text).toContain("Done");
- expect(text).toContain("↑/↓ move");
- });
-
it("summarizes a fast-mode draft and an unset level on the menu hints", () => {
const text = renderModelEditorQuestion(
{
@@ -1325,7 +971,7 @@ describe("renderModelEditorQuestion", () => {
expect(text).not.toContain("Service tier");
});
- it("lists model ids on a caret rail with an inverse cursor row and enter badge", () => {
+ it("lists model ids with a bold selection and enter badge", () => {
const rows = renderModelEditorQuestion(
{
request: editorRequest(),
@@ -1342,15 +988,15 @@ describe("renderModelEditorQuestion", () => {
const text = rows.join("\n");
expect(text).toContain("Select the model");
- expect(text).toContain(" ▏ type to search");
- expect(text).toContain(" ▶ openai/gpt-5.6-sol ");
+ expect(text).toContain(" type to search");
+ expect(text).toContain(" › openai/gpt-5.6-sol ");
expect(text).toContain("↵");
- expect(text).toContain(" ▏ anthropic/claude-sonnet-5");
+ expect(text).toContain(" anthropic/claude-sonnet-5");
// Five rows in view, no count row, Esc-only footer.
expect(text).toContain("openai/gpt-5.6-luna");
expect(text).not.toContain("google/gemini-3.5");
expect(text).not.toContain("options, showing");
- expect(text).toContain("esc to cancel");
+ expect(text).toContain("Esc back");
});
it("falls back to ASCII track glyphs without unicode", () => {
@@ -1367,3 +1013,43 @@ describe("renderModelEditorQuestion", () => {
expect(text).toContain("*-O-. medium");
});
});
+
+describe("compact menus", () => {
+ it.each([32, 80])("keeps options on single borderless rows at %i columns", (columns) => {
+ const options = [
+ { value: "a", label: "Vercel account", hint: "Team Alice\nConnected" },
+ { value: "b", label: "OpenAI API key" },
+ ];
+ const rows = renderSelectQuestion(
+ {
+ kind: "stacked",
+ message: "Connect a model",
+ options,
+ select: initialSelectState({ options }),
+ },
+ colorTheme,
+ columns,
+ );
+ const text = stripAnsi(rows.join("\n"));
+ expect(text).toContain("› Vercel account");
+ expect(text).toContain("OpenAI API key");
+ expect(rows.join("\n")).not.toContain("\x1b[7m");
+ expect(rows.join("\n")).toContain("\x1b[1m");
+ expect(text).not.toContain("▔");
+ expect(
+ rows
+ .filter((row) => stripAnsi(row).includes("Team Alice"))
+ .every((row) => stripAnsi(row).includes("Vercel account")),
+ ).toBe(true);
+ });
+ it("keeps warning labels legible without selection backgrounds", () => {
+ const options = [{ value: "a", label: "Reconnect", tone: "warning" as const }];
+ const rows = renderSelectQuestion(
+ { kind: "single", message: "", options, select: initialSelectState({ options }) },
+ colorTheme,
+ 80,
+ );
+ expect(stripAnsi(rows.join("\n"))).toContain("› Reconnect");
+ expect(rows.join("\n")).not.toContain("\x1b[7m");
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/setup-panel.ts b/packages/eve/src/cli/dev/tui/setup-panel.ts
index 4819c4fbf..53f24277b 100644
--- a/packages/eve/src/cli/dev/tui/setup-panel.ts
+++ b/packages/eve/src/cli/dev/tui/setup-panel.ts
@@ -1,26 +1,7 @@
-/**
- * Pure rendering for the bordered setup flow panel — the input-region variant
- * a setup command runs inside for its whole duration (the Claude Code
- * `/model`-panel grammar): a full-width rule, the command as a blue title,
- * the flow's recent progress lines, and the active question (numbered option
- * rows or a text field) or the ephemeral status spinner. Behavior state comes
- * from the shared select reducer (`#setup/cli/select-state.js`); this module
- * only paints rows, so the renderer hosts lifecycle and keys while tests
- * assert on strings.
- *
- * Column grammar: the panel adds a one-space left margin to every row under
- * the rule, while each section contributes two more spaces. Titles, spinners,
- * notices, filter prompts, and option-state glyphs therefore all begin at
- * column 3.
- */
+/** Pure borderless setup menus. Interaction and terminal lifecycle belong to the renderer. */
import type { ChannelSetupAction, PromptOption } from "#setup/cli/index.js";
-import {
- renderOptionRow,
- renderOptionRowContinuation,
- renderCursorRow,
- resolveOptionRowState,
-} from "#setup/cli/option-row.js";
+import { renderOptionRow, renderCursorRow, resolveOptionRowState } from "#setup/cli/option-row.js";
import {
filterOptions,
submitRowIndex,
@@ -185,6 +166,7 @@ export type FlowPanelStatus =
export type FlowPanelContent =
| {
kind: "question";
+ title?: string;
rows: readonly string[];
/** The install wait keeps its indicator above the concurrent actions. */
status?: FlowPanelStatus;
@@ -217,51 +199,21 @@ const RAILED_VIEW_SIZE = 5;
/** The flow panel keeps only the freshest progress in view. */
const FLOW_PANEL_LINE_CAP = 6;
-function questionFooter(hints: readonly string[], theme: Theme): string[] {
+function questionFooter(hints: readonly string[], theme: Theme, width?: number): string[] {
const c = theme.colors;
- return ["", ` ${c.dim(c.italic(hints.join(` ${theme.glyph.dot} `)))}`];
+ const text = hints.join(` ${theme.glyph.dot} `);
+ const lines = width === undefined ? [text] : wrapVisibleLine(text, Math.max(1, width - 3));
+ return ["", ...lines.map((line) => ` ${c.dim(line)}`)];
}
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");
-const BLUE_OPEN = "\x1b[34m";
-const FOREGROUND_RESET = "\x1b[39m";
-
-/**
- * Dims a line that may carry embedded bold spans (e.g. a flow bolding a
- * project name inside a hint): SGR 22 closes bold AND dim together, so dim is
- * re-opened after each close or the line's tail would render full-bright.
- */
-function dimWithEmphasis(text: string, theme: Theme): string {
- return theme.colors.dim(text.replaceAll(BOLD_OR_DIM_CLOSE, `${BOLD_OR_DIM_CLOSE}${DIM_OPEN}`));
-}
-
/** Restores normal intensity for a span nested inside an otherwise dim hint. */
function solidWithinDim(text: string, theme: Theme): string {
if (!theme.color) return text;
return `${BOLD_OR_DIM_CLOSE}${text}${DIM_OPEN}`;
}
-/** A selected row must not inherit an authored hint color. */
-function foregroundWithEmphasis(text: string): string {
- // Blue is the accent the selected row keeps (drafted values, adjust hints);
- // every other authored color normalizes to the highlight's foreground, and a
- // reset survives only when it closes a kept blue span.
- let blueOpen = false;
- return text.replaceAll(DIM_OPEN, "").replace(ANSI_FOREGROUND_COLOR, (code) => {
- if (code === BLUE_OPEN) {
- blueOpen = true;
- return code;
- }
- if (code === FOREGROUND_RESET && blueOpen) {
- blueOpen = false;
- return code;
- }
- return "";
- });
-}
-
function toneGlyph(tone: FlowPanelLine["tone"], theme: Theme): string {
const c = theme.colors;
switch (tone) {
@@ -297,8 +249,27 @@ function renderFlowPanelStatus(status: FlowPanelStatus, theme: Theme): string {
return `${renderIndicator(status.indicator, theme)} ${renderStatusText(status, theme)}`;
}
+export function flowMessageRows(lines: readonly FlowPanelLine[], theme: Theme): string[] {
+ const c = theme.colors;
+ const rows: string[] = [];
+ const recent = lines.slice(-FLOW_PANEL_LINE_CAP);
+ for (const line of recent) {
+ const text = line.text.split("\n");
+ for (const [index, part] of text.entries()) {
+ const body = line.tone === "info" ? c.dim(part) : part;
+ const prefix = index === 0 ? `${toneGlyph(line.tone, theme)} ` : " ";
+ rows.push(` ${prefix}${body}`);
+ }
+ }
+ if (recent.length > 0) {
+ rows.push("");
+ }
+
+ return rows;
+}
+
/**
- * Paints the bordered flow panel. Everything a running command produces lives
+ * Paints the setup flow panel. Everything a running command produces lives
* here — progress, questions, the status indicator — and the panel vanishes
* wholesale when the command resolves; only the command echo and the elbow
* outcome persist in the transcript.
@@ -307,27 +278,15 @@ export function renderFlowPanel(state: FlowPanelState, theme: Theme, width: numb
const c = theme.colors;
// Avoid the terminal's final column: writing into it can trigger an implicit
// wrap that the live-region row counter cannot observe, leaking old frames.
- const rows: string[] = [c.dim(theme.glyph.hrule.repeat(Math.max(1, width - 1)))];
- if (state.title.length > 0) {
- rows.push(` ${c.bold(state.title)}`);
- }
- rows.push("");
+ const rows: string[] = [];
+ const title =
+ state.content.kind === "question" ? (state.content.title ?? state.title) : state.title;
+ if (title.length > 0) rows.push(` ${c.bold(title)}`, "");
if (state.navigation?.kind === "planner") {
rows.push(...plannerStepRows(state.navigation, undefined, theme));
}
- const recent = state.lines.slice(-FLOW_PANEL_LINE_CAP);
- for (const line of recent) {
- const text = line.text.split("\n");
- for (const [index, part] of text.entries()) {
- const body = line.tone === "info" ? c.dim(part) : part;
- const prefix = index === 0 ? `${toneGlyph(line.tone, theme)} ` : " ";
- rows.push(` ${prefix}${body}`);
- }
- }
- if (recent.length > 0) {
- rows.push("");
- }
+ rows.push(...flowMessageRows(state.lines, theme));
switch (state.content.kind) {
case "question":
@@ -360,9 +319,7 @@ export function renderFlowPanel(state: FlowPanelState, theme: Theme, width: numb
// One breathable left margin for everything under the rule; blank rows
// stay empty so spacing assertions and trailing-whitespace trims hold.
- return rows.map((row, index) =>
- index === 0 || row.length === 0 ? clip(row, width) : clip(` ${row}`, width),
- );
+ return rows.map((row) => (row.length === 0 ? clip(row, width) : clip(` ${row}`, width)));
}
function optionRow(input: {
@@ -383,7 +340,7 @@ function optionRow(input: {
pointer: theme.glyph.pointer,
selectedPointer: theme.glyph.selectedPointer,
success: theme.glyph.success,
- placeholder: railed ? theme.glyph.caret : theme.glyph.option,
+ placeholder: theme.glyph.option,
dot: railed ? "" : theme.glyph.dot,
warning: theme.glyph.warning,
},
@@ -458,7 +415,7 @@ function plannerStepRows(
const complete = step.complete === true ? `${theme.glyph.success} ` : "";
const text = `${complete}${step.label}${count}`;
return index === navigation.activeStep
- ? theme.colors.inverse(theme.colors.blue(theme.colors.bold(` ${text} `)))
+ ? theme.colors.bold(` ${text}`)
: step.complete === true
? theme.colors.green(text)
: theme.colors.dim(text);
@@ -498,9 +455,7 @@ function searchFilter(
let input = caret;
if (railed) {
// The railed list's filter line: `▏ query▏`, or the dim placeholder.
- input = `${caret} ${
- filter.length > 0 ? filter + caret : theme.colors.dim(placeholder ?? "type to search")
- }`;
+ input = filter.length > 0 ? filter + caret : theme.colors.dim(placeholder ?? "type to filter");
} else if (filter.length > 0) {
input = filter + caret;
} else if (placeholder !== undefined) {
@@ -632,17 +587,6 @@ function inlineEditOption(
}
}
-function optionWithoutStackedHint(
- option: SetupPanelOption,
- layout: SelectLayout,
-): { option: SetupPanelOption; stackedHint: string | undefined } {
- if (layout !== "stacked" || option.hint === undefined) {
- return { option, stackedHint: undefined };
- }
- const { hint, ...rest } = option;
- return { option: rest, stackedHint: hint };
-}
-
function optionUsesPlaceholder(
presentation: SelectPresentation,
isTrailingTaskAction: boolean,
@@ -681,7 +625,6 @@ function appendSelectOptionRows(input: {
width,
theme,
} = input;
- const c = theme.colors;
let renderedTrailingTaskAction = false;
for (let index = start; index < end; index += 1) {
@@ -702,10 +645,14 @@ function appendSelectOptionRows(input: {
? 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,
- );
+ const editingKey = presentation.edit?.editor.kind === "key" && isCursor;
+ const rowOption = {
+ ...rendered,
+ hint: (
+ rendered.hint ?? (isCursor || option.disabled ? option.description : undefined)
+ )?.replace(/\s*\n\s*/gu, " "),
+ };
+ if (editingKey) rowOption.hint = undefined;
const railed = isRailedSearch(presentation);
// Railed lists carry the Enter affordance on the cursor row by default;
// an explicit cursorBadge (the provider picker's `↵ change`) still wins.
@@ -727,29 +674,7 @@ function appendSelectOptionRows(input: {
})}${badge}`,
);
- if (stackedHint !== undefined) {
- 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(` ${renderOptionRowContinuation(c.dim(option.description))}`);
- }
- if (presentation.layout === "stacked" && index < end - 1) rows.push("");
+ if (editingKey && rendered.hint) rows.push(` ${rendered.hint}`);
}
return renderedTrailingTaskAction;
}
@@ -979,9 +904,10 @@ export function renderSelectQuestion(
rows.push(
...questionFooter(
railed
- ? ["esc to cancel"]
+ ? ["Enter select", "Esc back"]
: selectFooterHints(presentation, visible, cursor, plannerNavigation),
theme,
+ width,
),
);
return rows.map((row) => clip(row, width));
@@ -1043,13 +969,14 @@ export function renderModelEditorQuestion(
input: ModelEditorPanelInput,
theme: Theme,
width: number,
+ message = MODEL_EDITOR_MESSAGE,
): string[] {
const { request, state } = input;
switch (state.screen.kind) {
case "menu":
return renderModelEditorMenu(input, state.screen.cursor, theme, width);
case "model":
- return renderModelEditorModelScreen(request, state.screen.select, theme, width);
+ return renderModelEditorModelScreen(request, state.screen.select, theme, width, message);
}
}
@@ -1121,13 +1048,14 @@ function renderModelEditorModelScreen(
select: SelectState,
theme: Theme,
width: number,
+ message: string,
): string[] {
// The catalog list IS the shared railed searchable select — the same
// component behind the team and project pickers.
return renderSelectQuestion(
{
kind: "search",
- message: MODEL_EDITOR_MESSAGE,
+ message,
options: request.model.kind === "pick" ? request.model.options : [],
placeholder: "type to search",
select,
@@ -1150,7 +1078,8 @@ export function renderTextQuestion(
const body = notice.tone === "info" ? c.dim(notice.text) : notice.text;
rows.push(`${toneGlyph(notice.tone, theme)} ${body}`);
}
- rows.push(...state.message.split("\n").map((line) => ` ${c.bold(line)}`));
+ if (state.message !== "")
+ rows.push(...state.message.split("\n").map((line) => ` ${c.bold(line)}`));
const budget = Math.max(4, width - 4);
const display = state.mask ? maskLine(state.editor) : state.editor;
@@ -1184,7 +1113,7 @@ export function renderAcknowledgeQuestion(
width: number,
): string[] {
const c = theme.colors;
- const rows: string[] = [` ${c.bold(state.message)}`];
+ const rows: string[] = state.message === "" ? [] : [` ${c.bold(state.message)}`];
if (state.lines.length > 0) {
rows.push("");
for (const line of state.lines) {
diff --git a/packages/eve/src/cli/dev/tui/status-line.test.ts b/packages/eve/src/cli/dev/tui/status-line.test.ts
index 745fc78a6..b4caed6d6 100644
--- a/packages/eve/src/cli/dev/tui/status-line.test.ts
+++ b/packages/eve/src/cli/dev/tui/status-line.test.ts
@@ -37,20 +37,29 @@ function deployedRemote(
}
describe("buildStatusLine", () => {
- it("leads local sessions with a gray colon-prefixed port badge", () => {
- const input = {
- serverPort: "3000",
- model: "openai/gpt-5.5",
- } as const;
+ it("shows a Vercel team slug without a local port or routing prose", () => {
+ const line = buildStatusLine({
+ model: "openai/gpt-5.6-luna-fast",
+ endpoint: { kind: "gateway", connected: true, credential: "oauth", team: "team_internal" },
+ vercel: { modelTeamSlug: "acme" },
+ theme: plain,
+ width: 120,
+ });
+ expect(line).toBe("openai/gpt-5.6-luna-fast · Vercel · acme");
+ });
- const line = buildStatusLine({ ...input, theme, width: 120 })!;
- expect(stripAnsi(line)).toBe(" :3000 openai/gpt-5.5");
- expect(buildStatusLine({ ...input, theme: plain, width: " :3000 ".length })).toBe(" :3000 ");
- expect(line).toContain("\x1b[7m\x1b[90m :3000 \x1b[39m\x1b[27m");
- expect(line).not.toContain("\x1b[7m\x1b[34m :3000 ");
+ it("omits raw team IDs while the slug is unavailable", () => {
+ expect(
+ buildStatusLine({
+ model: "m",
+ endpoint: { kind: "gateway", connected: true, credential: "oauth", team: "team_internal" },
+ theme: plain,
+ width: 120,
+ }),
+ ).toBe("m · Vercel");
});
- it("renders all segments in order with whitespace separators", () => {
+ it("renders all segments in order with dot separators", () => {
const line = buildStatusLine({
model: "anthropic/claude-sonnet-5",
endpoint: connected,
@@ -59,7 +68,7 @@ describe("buildStatusLine", () => {
width: 120,
});
- expect(line).toBe("anthropic/claude-sonnet-5 via ai-gateway(oidc:my-agent)");
+ expect(line).toBe("anthropic/claude-sonnet-5 · ai-gateway(oidc:my-agent)");
});
it("folds the reasoning level and Fast mode marker into the model segment", () => {
@@ -73,7 +82,7 @@ describe("buildStatusLine", () => {
width: 120,
});
- expect(line).toBe("xai/grok-4.5@xhigh ↯ via ai-gateway(oidc:my-agent)");
+ expect(line).toBe("xai/grok-4.5@xhigh ↯ · ai-gateway(oidc:my-agent)");
});
it("dims the whole model segment, reasoning level and fast marker included", () => {
@@ -132,7 +141,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(withProject).toBe("m via ai-gateway(oidc:my-agent)");
+ expect(withProject).toBe("m · ai-gateway(oidc:my-agent)");
// OIDC without a resolved project name: bare scope.
const noProject = buildStatusLine({
@@ -141,7 +150,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(noProject).toBe("m via ai-gateway(oidc)");
+ expect(noProject).toBe("m · ai-gateway(oidc)");
});
it("right-aligns monochrome build status and preserves it at narrow widths", () => {
@@ -176,7 +185,7 @@ describe("buildStatusLine", () => {
} as const;
const full = buildStatusLine({ ...input, width: 120 })!;
- expect(full.startsWith("logs: sandbox ")).toBe(true);
+ expect(full.startsWith("logs: sandbox · ")).toBe(true);
// Narrow enough that only the leading hint survives.
expect(buildStatusLine({ ...input, width: 13 })).toBe("logs: sandbox");
@@ -199,7 +208,7 @@ describe("buildStatusLine", () => {
theme: plain,
};
const full = buildStatusLine({ ...input, width: 200 })!;
- expect(full).toContain("via ai-gateway(oidc:my-agent)");
+ expect(full).toContain("ai-gateway(oidc:my-agent)");
const noEndpoint = buildStatusLine({ ...input, width: visibleLength(full) - 1 })!;
expect(noEndpoint).not.toContain("ai-gateway");
@@ -216,7 +225,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(external).toBe("anthropic/claude-sonnet-5 via anthropic⌝");
+ expect(external).toBe("anthropic/claude-sonnet-5 · anthropic⌝");
const linked = buildStatusLine({
model: "m",
@@ -225,7 +234,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(linked).toBe("m via ai-gateway(oidc:my-agent)");
+ expect(linked).toBe("m · ai-gateway(oidc:my-agent)");
const apiKey = buildStatusLine({
model: "m",
@@ -236,7 +245,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(apiKey).toBe("m via ai-gateway(api-key)");
+ expect(apiKey).toBe("m · ai-gateway(api-key)");
const chatgpt = buildStatusLine({
model: "openai/gpt-5.6-sol",
@@ -244,7 +253,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(chatgpt).toBe("openai/gpt-5.6-sol via chatgpt-sub⌝");
+ expect(chatgpt).toBe("openai/gpt-5.6-sol · chatgpt-sub⌝");
const chatgptLogin = buildStatusLine({
model: "openai/gpt-5.6-sol",
@@ -252,7 +261,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(chatgptLogin).toBe("openai/gpt-5.6-sol ⚠ chatgpt-sub login · /model");
+ expect(chatgptLogin).toBe("openai/gpt-5.6-sol · ⚠ chatgpt-sub login · /login");
const notConnected = buildStatusLine({
model: "m",
@@ -260,7 +269,7 @@ describe("buildStatusLine", () => {
theme: plain,
width: 120,
});
- expect(notConnected).toBe("m ⚠ ai-gateway");
+ expect(notConnected).toBe("m · ⚠ ai-gateway");
});
it("paints only the not-connected endpoint yellow", () => {
@@ -277,8 +286,8 @@ describe("buildStatusLine", () => {
width: 120,
});
// Only the gateway stands at the terminal's default foreground — no
- // explicit white, no bold; via/scope stay dim around it.
- expect(linked).toContain("\x1b[2mvia \x1b[22mai-gateway\x1b[2m(oidc)\x1b[22m");
+ // explicit white, no bold; the scope stays dim.
+ expect(linked).toContain("ai-gateway\x1b[2m(oidc)\x1b[22m");
expect(linked).not.toContain("\x1b[97m");
expect(linked).not.toContain("\x1b[1mai-gateway");
@@ -289,7 +298,7 @@ describe("buildStatusLine", () => {
theme,
width: 120,
});
- expect(external).toContain("\x1b[2mvia chatgpt-sub\x1b[22m⌝");
+ expect(external).toContain("\x1b[2mchatgpt-sub\x1b[22m⌝");
expect(external).not.toContain("\x1b[1m");
});
@@ -300,7 +309,7 @@ describe("buildStatusLine", () => {
theme: ascii,
width: 120,
});
- expect(stripAnsi(gateway!)).toBe("m ! ai-gateway");
+ expect(stripAnsi(gateway!)).toBe("m · ! ai-gateway");
const chatgpt = buildStatusLine({
model: "openai/gpt-5.6-sol",
@@ -308,7 +317,7 @@ describe("buildStatusLine", () => {
theme: ascii,
width: 120,
});
- expect(stripAnsi(chatgpt!)).toBe("openai/gpt-5.6-sol via chatgpt-sub^");
+ expect(stripAnsi(chatgpt!)).toBe("openai/gpt-5.6-sol · chatgpt-sub^");
});
it("renders the remote badge first and projects each authentication state", () => {
@@ -398,8 +407,8 @@ describe("buildStatusLine", () => {
"\x1b[7m\x1b[33m ↗ vpoke.playground-vercel.tools \x1b[39m\x1b[27m",
);
expect(notConnected).not.toContain("\x1b[43m");
- expect(notConnected).not.toContain("/vc:login");
- expect(disconnected).not.toContain("/vc:login");
+ expect(notConnected).not.toContain("/deploy");
+ expect(disconnected).not.toContain("/deploy");
expect(connectedLine).toContain("\x1b[7m\x1b[34m ↗ inbound (production) \x1b[39m\x1b[27m");
const badges = `${disconnected}${notConnected}${connectedLine}`;
expect(badges).not.toContain("\x1b[44m");
@@ -440,7 +449,7 @@ describe("buildStatusLine", () => {
expect(stripAnsi(line ?? "")).toBe(" ↗ inbou");
});
- it("keeps whitespace separators when unicode is unavailable", () => {
+ it("keeps dot separators when unicode is unavailable", () => {
const line = buildStatusLine({
remote: remote({ state: "checking" }),
theme: ascii,
diff --git a/packages/eve/src/cli/dev/tui/status-line.ts b/packages/eve/src/cli/dev/tui/status-line.ts
index 159ef1e08..028546f3c 100644
--- a/packages/eve/src/cli/dev/tui/status-line.ts
+++ b/packages/eve/src/cli/dev/tui/status-line.ts
@@ -24,8 +24,6 @@ function formatDevBuildStatus(status: DevBuildStatus, theme: Theme): string {
export interface StatusLineInput {
/** Transient authored-source build state, independent of the server log filter. */
devBuild?: DevBuildStatus;
- /** Port of the connected local development server; omitted for remote sessions. */
- serverPort?: string;
/** Resolved model slug, e.g. "anthropic/claude-sonnet-5"; absent when `/eve/v1/info` failed. */
model?: string;
/** Authored reasoning effort, rendered bold after the model id, e.g. `(xhigh)`. */
@@ -68,14 +66,6 @@ function renderModel(
return c.dim(formatModelSummary(summary));
}
-function renderServerPort(
- input: Pick<StatusLineInput, "remote" | "serverPort" | "theme">,
-): string | undefined {
- if (input.remote !== undefined || input.serverPort === undefined) return undefined;
- const c = input.theme.colors;
- return c.inverse(c.gray(` :${input.serverPort} `));
-}
-
/** Provider slugs whose display name differs from the AI SDK's identifier. */
const EXTERNAL_PROVIDER_DISPLAY_NAMES: Readonly<Record<string, string>> = {
// `chatgpt()` wraps the Codex backend; what the user connected is their
@@ -83,63 +73,50 @@ const EXTERNAL_PROVIDER_DISPLAY_NAMES: Readonly<Record<string, string>> = {
codex: "chatgpt-sub",
};
-/**
- * The endpoint reads as the model's routing clause (`via ai-gateway(oidc:…)`),
- * so it fuses onto the model segment with a plain space instead of standing
- * behind a `·` separator. Only the disconnected warning stands alone. The
- * clause is keyed strictly off the credential the AI SDK will actually use —
- * an `api-key` never shows the linked project, because the link is not what
- * authenticates the call.
- */
function renderEndpoint(
input: Pick<StatusLineInput, "endpoint" | "remote" | "theme" | "vercel">,
-): { readonly text: string; readonly standalone: boolean } | undefined {
+): string | undefined {
if (input.remote !== undefined || input.endpoint === undefined) return undefined;
const c = input.theme.colors;
const g = input.theme.glyph;
- // Only the gateway stands at the terminal's DEFAULT foreground — plain,
- // not bold — while `via` and the credential scope stay dim around it;
- // external providers render fully quiet. Explicit bright-white (SGR 97)
- // would vanish on light themes.
- const clause = (name: string, suffix: string) => `${c.dim("via ")}${name}${c.dim(suffix)}`;
+ const clause = (name: string, suffix: string) => `${name}${c.dim(suffix)}`;
if (input.endpoint.kind === "external") {
const provider =
EXTERNAL_PROVIDER_DISPLAY_NAMES[input.endpoint.provider] ?? input.endpoint.provider;
// The `⌝` mark stays at the terminal's default foreground — full
// intensity on any theme — while the clause around it is dim.
- return { text: `${c.dim(`via ${provider}`)}${g.external}`, standalone: false };
+ return `${c.dim(provider)}${g.external}`;
}
if (input.endpoint.kind === "chatgpt") {
switch (input.endpoint.state) {
case "ready":
- return { text: `${c.dim("via chatgpt-sub")}${g.external}`, standalone: false };
+ return `${c.dim("chatgpt-sub")}${g.external}`;
case "checking":
- return { text: c.dim("chatgpt-sub checking…"), standalone: true };
+ return c.dim("chatgpt-sub checking…");
case "signed-out":
case "reauth-required":
- return { text: c.yellow(`${g.warning} chatgpt-sub login · /model`), standalone: true };
+ return c.yellow(`${g.warning} chatgpt-sub login · /login`);
case "unavailable":
- return { text: c.yellow(`${g.warning} chatgpt-sub unavailable`), standalone: true };
+ return c.yellow(`${g.warning} chatgpt-sub unavailable`);
}
}
if (!input.endpoint.connected) {
- return { text: c.yellow(`${g.warning} ai-gateway`), standalone: true };
+ return c.yellow(`${g.warning} ai-gateway`);
}
if (input.endpoint.credential === "api-key") {
- return { text: clause("ai-gateway", "(api-key)"), standalone: false };
+ return clause("ai-gateway", "(api-key)");
+ }
+ if (input.endpoint.credential === "oauth") {
+ const slug = input.vercel?.modelTeamSlug;
+ return c.dim(slug ? `Vercel · ${slug}` : "Vercel");
}
const projectName = input.vercel?.identity?.projectName;
const scope = projectName === undefined ? "oidc" : `oidc:${projectName}`;
- return { text: clause("ai-gateway", `(${scope})`), standalone: false };
+ return clause("ai-gateway", `(${scope})`);
}
-/**
- * Builds a leading local `:port` or remote badge followed by the model (with
- * its reasoning level and Fast mode marker), and endpoint
- * segments. Both badges are the final narrow-width fallback. Remote sessions
- * omit endpoint state. Returns undefined when every segment is empty.
- */
+/** Builds model and connection segments, preserving the remote badge at narrow widths. */
export function buildStatusLine(input: StatusLineInput): string | undefined {
const { theme, width } = input;
const c = theme.colors;
@@ -147,21 +124,13 @@ export function buildStatusLine(input: StatusLineInput): string | undefined {
const devBuild =
input.devBuild === undefined ? undefined : formatDevBuildStatus(input.devBuild, theme);
const logLevel = input.logLevel === undefined ? undefined : c.cyan(`logs: ${input.logLevel}`);
- const serverPort = renderServerPort(input);
const model = renderModel(input);
const remote = input.remote === undefined ? undefined : formatRemoteStatus(input.remote, theme);
const endpoint = renderEndpoint(input);
- const leading = remote?.full ?? serverPort;
- const badge = remote?.badge ?? serverPort;
-
- // A routing clause rides the model segment itself; the disconnected
- // warning (or a clause with no model to attach to) stays its own segment.
- const fused = endpoint !== undefined && !endpoint.standalone && model !== undefined;
- const modelSegment = fused ? `${model} ${endpoint.text}` : model;
- const endpointSegment = endpoint === undefined || fused ? undefined : endpoint.text;
+ const leading = remote?.full;
+ const badge = remote?.badge;
- // Whitespace separators: the dim segments read as columns without bullets.
- const separator = " ";
+ const separator = c.dim(" · ");
const compose = (
target: string | undefined,
segments: ReadonlyArray<string | undefined>,
@@ -172,7 +141,7 @@ export function buildStatusLine(input: StatusLineInput): string | undefined {
};
const leftVariants = [
- compose(leading, [logLevel, modelSegment, endpointSegment]),
+ compose(leading, [logLevel, model, endpoint]),
compose(leading, [logLevel, model]),
compose(leading, [logLevel]),
compose(badge, [logLevel]),
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
index 4e4bc6211..f29f58190 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
@@ -13,7 +13,6 @@ import {
import type { AgentTUIStreamEvent, AgentTUIStreamResult, SubagentToolUpdate } from "./runner.js";
import { promptCommandsFor } from "./prompt-commands.js";
-import { PROMPT_PLACEHOLDER_MESSAGES } from "./prompt-placeholder.js";
import { TerminalRenderer } from "./terminal-renderer.js";
import { MockScreen, MockUserInput } from "./test/mock-terminal.js";
@@ -186,8 +185,8 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
const snapshot = screen.snapshot();
- expect(snapshot).toMatch(/☰eve \(v\d+\.\d+\.\d+\).*Weather Agent/u);
- expect(snapshot).toContain("Tip: Use the /deploy command to deploy your agent.");
+ expect(snapshot).toMatch(/eve v\d+\.\d+\.\d+.*Weather Agent/u);
+ expect(snapshot).toContain("Use the /deploy command to deploy your agent.");
expect(snapshot).not.toContain("http://localhost:3000");
});
@@ -216,7 +215,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
const snapshot = screen.snapshot();
expect(snapshot).toContain("new-model");
expect(snapshot).not.toContain("old-model");
- expect(snapshot.match(/☰eve/gu)).toHaveLength(1);
+ expect(snapshot.match(/eve v\d/gu)).toHaveLength(1);
expect(snapshot).toContain("hello");
expect(snapshot).toContain("still here");
renderer.shutdown();
@@ -650,10 +649,10 @@ describe("TerminalRenderer (inline scrollback)", () => {
// The label types itself out: one character at t=0.
let barRow = lines.findIndex((line) => line === "▪ W 1s");
expect(barRow).toBeGreaterThan(-1);
- // The pending prompt row wears the same quiet `›` as the idle one
+ // The pending prompt row wears the same default-color `❯` as the idle one
// beneath the bar; the status line follows it.
expect(lines[barRow + 1]).toBe("");
- expect(lines[barRow + 2]).toContain("›");
+ expect(lines[barRow + 2]).toContain("❯");
expect(lines[barRow + 4]).toContain("gpt-5");
// The duration ticks live while the pulse blinks on the shared beat.
@@ -662,7 +661,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
// Fully revealed once the reveal window has passed.
barRow = lines.findIndex((line) => line.includes("Working for 2s"));
expect(barRow).toBeGreaterThan(-1);
- expect(lines[barRow + 2]).toContain("›");
+ expect(lines[barRow + 2]).toContain("❯");
expect(lines[barRow + 4]).toContain("gpt-5");
streamController?.close();
@@ -1546,6 +1545,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
const second = renderer.readPrompt();
expect(countOccurrences(screen.snapshot(), "└ Done in")).toBe(1);
input.ctrlC();
+ expect(screen.snapshot()).toContain("❯");
input.ctrlC();
await expect(second).rejects.toThrow();
renderer.shutdown();
@@ -1566,10 +1566,10 @@ describe("TerminalRenderer (inline scrollback)", () => {
);
await Promise.resolve();
- // Empty: the quiet idle mark.
- expect(screen.snapshot()).toContain("›");
+ // Empty: the default-color prompt mark.
+ expect(screen.snapshot()).toContain("❯");
- // A typed draft flips to the active mark, but dim — Enter is inert, so
+ // A typed draft dims the mark — Enter is inert, so
// the cyan ready state would overclaim.
input.type("next question");
await screen.waitForText("❯ next question");
@@ -1660,7 +1660,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
it("clears the setup attention line once its issue is resolved", () => {
const { screen, renderer } = makeRenderer();
- renderer.renderSetupWarning("1 setup issue: not logged in · /vc:login");
+ renderer.renderSetupWarning("1 setup issue: not logged in · /deploy");
expect(screen.snapshot()).toContain("not logged in");
renderer.clearSetupWarning();
@@ -1718,7 +1718,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
it("marks a failed automatic command and keeps its multiline outcome in one result block", () => {
const { screen, renderer } = makeRenderer();
- renderer.renderCommandInvocation("/vc:login", "failed");
+ renderer.renderCommandInvocation("/deploy", "failed");
renderer.renderCommandResult(
"Authentication was refreshed, but example.vercel.app is unavailable: Access denied.\n\n" +
"TRUSTED_SOURCES_ENVIRONMENT_MISMATCH",
@@ -1727,7 +1727,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
const snapshot = screen.snapshot();
- expect(snapshot).toContain("│ ⨯ /vc:login");
+ expect(snapshot).toContain("│ ⨯ /deploy");
expect(snapshot).toContain("⎿ Authentication was refreshed");
expect(snapshot).toContain("TRUSTED_SOURCES_ENVIRONMENT_MISMATCH");
expect(snapshot).not.toContain("· Authentication was refreshed");
@@ -1739,15 +1739,14 @@ describe("TerminalRenderer (inline scrollback)", () => {
const prompt = renderer.readPrompt();
// A bare prompt before any info/turn has no status row (no ↑ 0 ↓ 0 counter).
expect(screen.snapshot()).not.toContain("↑ 0");
- // Empty buffer: the quiet `›` gutter with the rotation's first message.
- expect(screen.snapshot()).toContain(`› ${PROMPT_PLACEHOLDER_MESSAGES[0]}`);
- expect(screen.snapshot()).not.toContain("❯");
+ // Empty buffer: the default-color `❯` gutter with the message invitation.
+ expect(screen.snapshot()).toContain("❯ Send a message…");
expect(screen.rawOutput()).not.toContain("\x1b[48;5;");
input.type("hello");
- // Typing swaps in the active prompt mark and clears the invitation.
+ // Typing colors the prompt mark and clears the invitation.
expect(screen.snapshot()).toContain("❯ hello");
- expect(screen.snapshot()).not.toContain(PROMPT_PLACEHOLDER_MESSAGES[0]);
+ expect(screen.snapshot()).not.toContain("Send a message…");
input.enter();
expect(screen.snapshot()).toContain("W 1s");
expect(await prompt).toBe("hello");
@@ -1825,6 +1824,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
// crossing the 20K input threshold is what earns the row.
expect(screen.snapshot()).toContain("└ Done in 1s ── ↑ 20.5K ↓ 43");
input.ctrlC();
+ expect(screen.snapshot()).toContain("❯");
input.ctrlC();
await expect(second).rejects.toThrow();
renderer.shutdown();
@@ -1853,6 +1853,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
const second = renderer.readPrompt();
expect(screen.snapshot()).not.toContain("\n└ ");
input.ctrlC();
+ expect(screen.snapshot()).toContain("❯");
input.ctrlC();
await expect(second).rejects.toThrow();
renderer.shutdown();
@@ -1862,21 +1863,20 @@ describe("TerminalRenderer (inline scrollback)", () => {
const { screen, input, renderer } = makeRenderer();
const first = renderer.readPrompt();
- expect(screen.snapshot()).toContain(`› ${PROMPT_PLACEHOLDER_MESSAGES[0]}`);
+ expect(screen.snapshot()).toContain("❯ Send a message…");
input.type("hello");
input.enter();
expect(await first).toBe("hello");
- // Once the user has spoken, the empty prompt keeps the quiet `›` but
- // drops the invitation text; typing still swaps in the active `❯`.
+ // Once the user has spoken, the empty prompt keeps the default-color `❯` but
+ // drops the invitation text; typing still colors the active `❯`.
const second = renderer.readPrompt();
- expect(screen.snapshot()).toContain("›");
- expect(screen.snapshot()).not.toContain("❯");
- expect(screen.snapshot()).not.toContain(PROMPT_PLACEHOLDER_MESSAGES[0]);
+ expect(screen.snapshot()).toContain("❯");
+ expect(screen.snapshot()).not.toContain("Send a message…");
input.type("again");
expect(screen.snapshot()).toContain("❯ again");
input.ctrlC();
- expect(screen.snapshot()).not.toContain("❯");
+ expect(screen.snapshot()).toContain("❯");
input.ctrlC();
await expect(second).rejects.toThrow();
renderer.shutdown();
@@ -1916,7 +1916,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
expect(barRow).toBeGreaterThan(-1);
expect(screen.snapshot()).not.toContain("the plan is to check the forecast");
// The pending prompt row holds its place below, then the status line.
- expect(lines[barRow + 2]).toContain("›");
+ expect(lines[barRow + 2]).toContain("❯");
expect(lines[barRow + 4]).toContain("gpt-5");
streamController?.enqueue({ type: "reasoning-complete", id: "r1" });
@@ -1982,9 +1982,9 @@ describe("TerminalRenderer (inline scrollback)", () => {
);
await vi.waitFor(() => {
- // Empty draft: the pending prompt wears the same quiet `›` as idle
+ // Empty draft: the pending prompt wears the same default-color `❯` as idle
// (readiness is signalled by the turn bar's absence, not the glyph).
- expect(screen.snapshot()).toContain("›");
+ expect(screen.snapshot()).toContain("❯");
});
input.type("follow-up question");
// Enter mid-turn queues the draft into the panel and clears the buffer.
@@ -2020,7 +2020,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
);
await vi.waitFor(() => {
- expect(screen.snapshot()).toContain("›");
+ expect(screen.snapshot()).toContain("❯");
});
input.type("/cancel");
input.enter();
@@ -2055,7 +2055,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
);
await vi.waitFor(() => {
- expect(screen.snapshot()).toContain("›");
+ expect(screen.snapshot()).toContain("❯");
});
input.type("/cancel");
input.enter();
@@ -2079,12 +2079,8 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
});
- it("sends the oldest queued message on Esc without cancelling the turn", async () => {
+ it("steers each Enter message without cancelling the turn", async () => {
const { screen, input, renderer } = makeRenderer();
- const escape = async () => {
- input.send("\x1b");
- await new Promise((resolve) => setTimeout(resolve, 50));
- };
let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
const cancel = vi.fn();
const steer = vi.fn(async () => {});
@@ -2102,28 +2098,22 @@ describe("TerminalRenderer (inline scrollback)", () => {
);
await vi.waitFor(() => {
- expect(screen.snapshot()).toContain("›");
+ expect(screen.snapshot()).toContain("❯");
});
input.type("go north");
input.enter();
input.type("go south");
input.enter();
- await vi.waitFor(() => {
- expect(screen.snapshot()).toContain("Queue 2/5");
- });
-
- await escape();
expect(cancel).not.toHaveBeenCalled();
- expect(steer).toHaveBeenCalledWith("go north");
- expect(screen.snapshot()).toContain("Queue 1/5");
+ expect(steer).toHaveBeenNthCalledWith(1, "go north");
+ expect(steer).toHaveBeenNthCalledWith(2, "go south");
+ expect(screen.snapshot()).not.toContain("Queue");
- // The server settles the cancelled turn and the stream reaches its boundary.
streamController?.enqueue({ type: "finish" });
streamController?.close();
await rendering;
- // The popped message steers; the remaining one stays queued behind it.
- expect(renderer.takeQueuedPrompt()).toBe("go south");
+ expect(renderer.takeQueuedPrompt()).toBeUndefined();
renderer.shutdown();
});
@@ -2147,7 +2137,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
{ submittedPrompt: "long task", continueSession: true },
);
await vi.waitFor(() => {
- expect(screen.snapshot()).toContain("›");
+ expect(screen.snapshot()).toContain("❯");
});
await escape();
@@ -2226,12 +2216,8 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
});
- it("marks steered and queued prompts with their provenance arrow", async () => {
+ it("renders steered and queued prompts without provenance arrow rows", async () => {
const { screen, input, renderer } = makeRenderer();
- const escape = async () => {
- input.send("\x1b");
- await new Promise((resolve) => setTimeout(resolve, 50));
- };
const closedStream = () =>
new ReadableStream<AgentTUIStreamEvent>({
start(controller) {
@@ -2239,11 +2225,12 @@ describe("TerminalRenderer (inline scrollback)", () => {
},
});
- // Steer: queue a message mid-turn and pop it with Esc.
+ // Enter steers immediately without a cancellation key.
+ const steer = vi.fn(async () => {});
let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
const first = renderer.renderStream(
{
- steer: vi.fn(async () => {}),
+ steer,
events: new ReadableStream<AgentTUIStreamEvent>({
start(controller) {
streamController = controller;
@@ -2253,11 +2240,12 @@ describe("TerminalRenderer (inline scrollback)", () => {
{ submittedPrompt: "long task", continueSession: true },
);
await vi.waitFor(() => {
- expect(screen.snapshot()).toContain("›");
+ expect(screen.snapshot()).toContain("❯");
});
input.type("go north");
input.enter();
- await escape();
+ expect(steer).toHaveBeenCalledWith("go north");
+ expect(screen.snapshot()).not.toContain("Queue 1/5");
streamController?.enqueue({ type: "finish" });
streamController?.close();
await first;
@@ -2265,7 +2253,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
expect(renderer.takeQueuedPrompt()).toBeUndefined();
let lines = screen.snapshot().split("\n");
const steerIndex = lines.findIndex((line) => line.includes("│ go north"));
- expect(lines[steerIndex - 1]?.trim()).toBe("↑");
+ expect(lines[steerIndex - 1]?.trim()).not.toBe("↑");
// Queue: a message that waited for the natural boundary.
let secondController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
@@ -2298,7 +2286,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
);
lines = screen.snapshot().split("\n");
const queueIndex = lines.findIndex((line) => line.includes("│ go south"));
- expect(lines[queueIndex + 1]?.trim()).toBe("↑");
+ expect(lines[queueIndex + 1]?.trim()).not.toBe("↑");
// The ordinary typed prompts carry no arrow.
const typedIndex = lines.findIndex((line) => line.includes("│ long task"));
@@ -2307,6 +2295,61 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
});
+ it("preserves a rejected Enter steering message for recovery", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ const steer = vi.fn(async () => {
+ throw new Error("Session unavailable");
+ });
+ let controller: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const rendering = renderer.renderStream(
+ {
+ steer,
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(value) {
+ controller = value;
+ },
+ }),
+ },
+ { submittedPrompt: "long task", continueSession: true },
+ );
+ await screen.waitForText("❯");
+ input.type("change direction");
+ input.enter();
+ await screen.waitForText("Steering failed");
+ expect(steer).toHaveBeenCalledWith("change direction");
+ controller?.enqueue({ type: "finish" });
+ controller?.close();
+ await rendering;
+ expect(renderer.takeQueuedPrompt()).toBe("change direction");
+ renderer.shutdown();
+ });
+
+ it("keeps slash commands out of the steering message", async () => {
+ const { screen, input, renderer } = makeRenderer();
+ const steer = vi.fn(async () => {});
+ let controller: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const rendering = renderer.renderStream(
+ {
+ steer,
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(value) {
+ controller = value;
+ },
+ }),
+ },
+ { submittedPrompt: "long task", continueSession: true },
+ );
+ await screen.waitForText("❯");
+ input.type("/model");
+ input.enter();
+ expect(steer).not.toHaveBeenCalled();
+ controller?.enqueue({ type: "finish" });
+ controller?.close();
+ await rendering;
+ expect(renderer.takeQueuedPrompt()).toBe("/model");
+ renderer.shutdown();
+ });
+
it("keeps the draft in place when the queue is full", async () => {
const { screen, input, renderer } = makeRenderer();
let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
@@ -2321,7 +2364,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
{ submittedPrompt: "long task", continueSession: true },
);
await vi.waitFor(() => {
- expect(screen.snapshot()).toContain("›");
+ expect(screen.snapshot()).toContain("❯");
});
for (let index = 1; index <= 5; index += 1) {
@@ -2362,7 +2405,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
{ submittedPrompt: "long task", continueSession: true },
);
await vi.waitFor(() => {
- expect(screen.snapshot()).toContain("›");
+ expect(screen.snapshot()).toContain("❯");
});
input.type("first");
input.enter();
@@ -2404,9 +2447,9 @@ describe("TerminalRenderer (inline scrollback)", () => {
);
await vi.waitFor(() => {
- // The pending prompt already shows `›` — but the live bar keeps the
+ // The pending prompt already shows `❯` — but the live bar keeps the
// idle predicate false.
- expect(screen.snapshot()).toContain("›");
+ expect(screen.snapshot()).toContain("❯");
});
await expect(screen.waitForIdlePrompt(200)).rejects.toThrow(/idle prompt/u);
@@ -2438,10 +2481,10 @@ describe("TerminalRenderer (inline scrollback)", () => {
title: "weather-agent",
});
expect(screen.snapshot()).toContain("weather-agent");
- expect(screen.snapshot()).toContain("Tip: Use the /help command");
+ expect(screen.snapshot()).toContain("Use the /help command");
expect(screen.snapshot()).not.toContain("model");
expect(screen.snapshot()).not.toContain("loading");
- expect(screen.snapshot()).toContain("Building your agent");
+ expect(screen.snapshot()).toContain("Starting agent");
expect(screen.snapshot()).toContain("weather");
input.type(" tomorrow");
@@ -2471,6 +2514,100 @@ describe("TerminalRenderer (inline scrollback)", () => {
startupRenderer.shutdown();
});
+ it.each([32, 80])(
+ "defers startup warnings until connection readiness at %i columns",
+ (columns) => {
+ const { renderer, screen } = makeRenderer(columns);
+ renderer.beginStartupDraft({ initialDraft: "Hello Alice", tip: "/help", title: "Agent" });
+ renderer.renderSetupWarning("Model disconnected · /login");
+ expect(screen.snapshot()).not.toContain("Model disconnected");
+ renderer.setStartupPhase("connecting");
+ expect(screen.snapshot()).toContain("Reading saved connection");
+ expect(screen.snapshot()).not.toContain("Model disconnected");
+ expect(renderer.finishStartupDraft()).toEqual({
+ draft: "Hello Alice",
+ queuedPrompt: undefined,
+ });
+ renderer.setStartupPhase(undefined);
+ expect(screen.snapshot()).toContain("Model disconnected");
+ renderer.shutdown();
+ },
+ );
+
+ it.each([32, 80])(
+ "keeps startup editable across connection work and questions at %i columns",
+ async (columns) => {
+ const { renderer, screen, input } = makeRenderer(columns);
+ renderer.beginStartupDraft({ initialDraft: "Hello", tip: "/help", title: "Agent" });
+ const composerRow = screen
+ .snapshot()
+ .split("\n")
+ .findIndex((line) => line.includes("Hello"));
+ renderer.setStartupPhase("connecting");
+ renderer.setupFlow.begin("Connect a model", "pulse");
+ const interrupt = renderer.setupFlow.waitForInterrupt();
+ renderer.setupFlow.setStatus("Connecting with Vercel…");
+ expect(screen.snapshot()).toContain("Connecting with Vercel");
+ expect(screen.snapshot()).not.toContain("Connect a model");
+ expect(screen.snapshot()).not.toContain("Working");
+ expect(
+ screen
+ .snapshot()
+ .split("\n")
+ .findIndex((line) => line.includes("Hello")),
+ ).toBe(composerRow);
+ input.type(" 世界");
+ expect(screen.snapshot()).toContain("Hello 世界");
+ const answer = renderer.setupFlow.readSelect({
+ kind: "search",
+ message: "Connect a model",
+ options: [
+ { value: "vercel", label: "Vercel Account" },
+ { value: "openai", label: "OpenAI API Key" },
+ ],
+ });
+ expect(screen.snapshot()).toContain("Connect a model");
+ expect(screen.snapshot()).not.toContain("Hello 世界");
+ input.type("OpenAI");
+ input.enter();
+ await expect(answer).resolves.toEqual(["openai"]);
+ renderer.setupFlow.setStatus("Checking connection…");
+ input.type("!");
+ expect(screen.snapshot()).toContain("Hello 世界!");
+ input.enter();
+ renderer.setStartupPhase("updating");
+ renderer.setupFlow.setStatus("Loading selected model…");
+ input.type("Next message");
+ expect(screen.snapshot()).toContain("Loading selected model");
+ expect(screen.snapshot()).not.toContain("Working");
+ interrupt.dispose();
+ renderer.setupFlow.end({ preserveDiagnostics: false });
+ input.type(" too");
+ expect(renderer.finishStartupDraft()).toEqual({
+ draft: "Next message too",
+ queuedPrompt: "Hello 世界!",
+ });
+ renderer.setStartupPhase(undefined);
+ renderer.shutdown();
+ },
+ );
+
+ it("restores the startup draft after a masked key question is cancelled", async () => {
+ const { renderer, input, screen } = makeRenderer();
+ renderer.beginStartupDraft({ initialDraft: "My message", tip: "/help", title: "Agent" });
+ renderer.setupFlow.begin("Connect a model", "pulse");
+ const answer = renderer.setupFlow.readText({ message: "API key", mask: true });
+ input.type("private-test-key");
+ expect(screen.snapshot()).not.toContain("private-test-key");
+ input.send("\x1b");
+ await expect(answer).resolves.toBeUndefined();
+ renderer.setupFlow.end({ preserveDiagnostics: false });
+ expect(screen.snapshot()).toContain("My message");
+ expect(renderer.finishStartupDraft().draft).toBe("My message");
+ renderer.setStartupPhase(undefined);
+ renderer.shutdown();
+ });
+
it("lets Ctrl-C stop an editing-only startup draft", () => {
const screen = new MockScreen({ columns: 80, rows: 30 });
const input = new MockUserInput();
@@ -2583,7 +2720,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.shutdown();
});
- it("renders the question overlay with numbered rows and an inverse-blue cursor", async () => {
+ it("renders the question overlay with numbered rows and a bold cursor", async () => {
const { screen, input, renderer } = makeRenderer();
const answer = renderer.readInputQuestion({
@@ -2599,10 +2736,10 @@ describe("TerminalRenderer (inline scrollback)", () => {
const snapshot = screen.snapshot();
const lines = snapshot.split("\n");
const selected = lines.find((line) => line.includes("AI Gateway"));
- expect(selected).toContain(" ▶ 1. AI Gateway ");
+ expect(selected).toContain(" › 1. AI Gateway ");
expect(selected).toContain("↵");
- expect(screen.rawOutput()).toContain("\x1b[7m");
- expect(screen.rawOutput()).toContain("\x1b[34m");
+ expect(screen.rawOutput()).not.toContain("\x1b[7m");
+ expect(screen.rawOutput()).toContain("\x1b[1m");
// Every option's description rides its own row, cursor or not.
expect(lines).toContain(" Managed access");
expect(lines).toContain(" Direct access");
@@ -2617,7 +2754,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
.split("\n")
.find((line) => line.includes("AI Gateway"));
expect(unselected).toContain("1. AI Gateway");
- expect(unselected).not.toContain("▶");
+ expect(unselected).not.toContain("›");
input.send("k");
input.enter();
@@ -3813,7 +3950,7 @@ describe("TerminalRenderer (inline scrollback)", () => {
renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });
renderer.shutdown();
- expect(countOccurrences(screen.snapshot(), "☰eve (v")).toBe(1);
+ expect(countOccurrences(screen.snapshot(), "eve v")).toBe(1);
});
it("reset clears committed transcript rows", () => {
@@ -4242,38 +4379,13 @@ describe("TerminalRenderer setup panel", () => {
});
// The value menu opens on the Model row.
- expect(screen.snapshot()).toContain("▶ Model");
+ expect(screen.snapshot()).toContain("› Model");
input.enter();
expect(screen.snapshot()).toContain("Select the model");
input.type("grok");
expect(screen.snapshot()).toContain("xai/grok-4.5");
input.enter();
- // Back on the menu, the model hint carries the pick.
- expect(screen.snapshot()).toContain("xai/grok-4.5");
-
- // Reasoning adjusts inline on its row: right enters the scale at the
- // lowest level, another right (via Tab, which mimics it) walks up.
- input.down();
- expect(screen.snapshot()).toContain("▶ Reasoning effort");
- input.right();
- expect(screen.snapshot()).toContain("◉─○ low");
- input.send("\t");
- expect(screen.snapshot()).toContain("●─◉ high");
-
- input.down();
- expect(screen.snapshot()).toContain("▶ Service tier");
- expect(screen.snapshot()).toContain("normal");
- input.right();
- expect(screen.snapshot()).toContain("fast ↯");
-
- input.down();
- input.enter();
-
- await expect(answer).resolves.toEqual({
- model: "xai/grok-4.5",
- reasoning: "high",
- serviceTier: "priority",
- });
+ await expect(answer).resolves.toEqual({ model: "xai/grok-4.5" });
renderer.setupFlow.end({ preserveDiagnostics: false });
renderer.shutdown();
});
@@ -4304,13 +4416,13 @@ describe("TerminalRenderer setup panel", () => {
await new Promise((resolve) => setTimeout(resolve, 50));
expect(settled).toBe(false);
// The first Esc only cleared the filter; the list is still open.
- expect(screen.snapshot()).toContain("▏ type to search");
+ expect(screen.snapshot()).toContain("type to search");
input.send("\x1b");
await new Promise((resolve) => setTimeout(resolve, 50));
expect(settled).toBe(false);
// Back on the menu.
- expect(screen.snapshot()).toContain("▶ Model");
+ expect(screen.snapshot()).toContain("› Model");
input.send("\x1b");
await expect(answer).resolves.toBeUndefined();
@@ -4496,7 +4608,7 @@ describe("TerminalRenderer setup flow session", () => {
expect(snapshot).toContain("Project linked. Connected to AI Gateway via VERCEL_OIDC_TOKEN.");
});
- it("renders questions inside the open flow panel under its title", async () => {
+ it("gives the active question the flow heading", async () => {
const { screen, input, renderer } = makeRenderer();
renderer.setupFlow.begin("/deploy");
@@ -4508,7 +4620,7 @@ describe("TerminalRenderer setup flow session", () => {
});
const snapshot = screen.snapshot();
- expect(snapshot).toContain("/deploy");
+ expect(snapshot).not.toContain("/deploy");
expect(snapshot).toContain("This directory is not linked yet.");
expect(snapshot).toContain("Vercel project");
@@ -4578,7 +4690,7 @@ describe("TerminalRenderer setup flow session", () => {
expect(snapshot).not.toContain("Slack channel was not added");
expect(snapshot).not.toContain("Scaffolding Web Chat channel files");
// Focused completed row reads inert: a dim pointer, not a check.
- expect(snapshot).toContain("▷ Terminal UI · Already installed");
+ expect(snapshot).toContain("› Terminal UI · Already installed");
expect(snapshot).not.toContain("✓ Terminal UI");
expect(snapshot).toContain("✓ Web Chat");
expect(snapshot).toContain("Slack · Creates slackbot and deploys to Vercel");
@@ -4998,7 +5110,7 @@ describe("TerminalRenderer command typeahead", () => {
const snapshot = screen.snapshot();
expect(snapshot).toContain("/help");
expect(snapshot).toContain("Show available commands");
- expect(snapshot).toContain("Configure the agent's model and provider");
+ expect(snapshot).toContain("Choose a model and its settings");
const promptLine = snapshot.split("\n").find((line) => line.includes("❯ /"));
expect(promptLine?.startsWith("❯ /")).toBe(true);
@@ -5020,7 +5132,7 @@ describe("TerminalRenderer command typeahead", () => {
expect(snapshot).toContain("/model");
expect(snapshot).toContain("[provider/model]");
// ...and the dropdown (with its description column) is gone.
- expect(snapshot).not.toContain("Configure the agent's model and provider");
+ expect(snapshot).not.toContain("Choose a model and its settings");
input.enter();
expect(await prompt).toBe("/model");
@@ -5097,7 +5209,7 @@ describe("TerminalRenderer command typeahead", () => {
});
input.type("m");
- expect(screen.snapshot()).toContain("Configure the agent's model and provider");
+ expect(screen.snapshot()).toContain("Choose a model and its settings");
input.enter();
expect(await prompt).toBe("/model");
renderer.shutdown();
@@ -5132,8 +5244,8 @@ describe("TerminalRenderer command typeahead", () => {
const prompt = renderer.readPrompt();
input.type("/");
const snapshot = screen.snapshot();
- expect(snapshot).toContain("Authenticate with Vercel");
- expect(snapshot).not.toContain("Configure the agent's model and provider");
+ expect(snapshot).not.toContain("Authenticate with Vercel");
+ expect(snapshot).not.toContain("Choose a model and its settings");
input.enter();
await prompt;
renderer.shutdown();
@@ -5166,7 +5278,7 @@ describe("TerminalRenderer status line", () => {
identity: { projectName: "my-agent", teamName: "acme" },
};
- it("renders the local server, model, and Vercel link under the prompt row", async () => {
+ it("renders the model and Vercel link without the local port under the prompt row", async () => {
const { screen, input, renderer } = makeRenderer();
renderer.renderAgentHeader({
name: "Weather Agent",
@@ -5193,14 +5305,13 @@ describe("TerminalRenderer status line", () => {
});
const lines = screen.snapshot().split("\n");
- const promptRow = lines.findIndex((line) => line.includes("›"));
+ const promptRow = lines.findIndex((line) => line.includes("❯"));
expect(promptRow).toBeGreaterThan(-1);
const statusRow = lines.slice(promptRow + 1).join("\n");
- expect(statusRow).toContain(":3000");
+ expect(statusRow).not.toContain(":3000");
expect(statusRow).toContain("anthropic/claude-sonnet-5");
- expect(statusRow.indexOf(":3000")).toBeLessThan(statusRow.indexOf("anthropic/claude-sonnet-5"));
// The linked project folds into the connected gateway label.
- expect(statusRow).toContain("via ai-gateway(oidc:my-agent)");
+ expect(statusRow).toContain("· ai-gateway(oidc: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");
@@ -5226,13 +5337,13 @@ describe("TerminalRenderer status line", () => {
}),
});
renderer.setVercelStatus(vercelStatus);
- expect(screen.snapshot()).toContain("via ai-gateway(oidc:my-agent)");
+ expect(screen.snapshot()).toContain("· ai-gateway(oidc:my-agent)");
renderer.setupFlow.begin("Connect to Vercel");
- expect(screen.snapshot()).not.toContain("via ai-gateway(oidc:my-agent)");
+ expect(screen.snapshot()).not.toContain("· ai-gateway(oidc:my-agent)");
renderer.setupFlow.end({ preserveDiagnostics: false });
- expect(screen.snapshot()).toContain("via ai-gateway(oidc:my-agent)");
+ expect(screen.snapshot()).toContain("· ai-gateway(oidc:my-agent)");
renderer.shutdown();
});
@@ -5263,12 +5374,9 @@ describe("TerminalRenderer status line", () => {
});
const lines = screen.snapshot().split("\n");
- const title = lines.indexOf(" Authenticate via Vercel OIDC");
- expect(lines.slice(title, title + 3)).toEqual([
- " Authenticate via Vercel OIDC",
- "",
- " Select your team",
- ]);
+ const title = lines.indexOf(" Select your team");
+ expect(title).toBeGreaterThanOrEqual(0);
+ expect(lines).not.toContain(" Authenticate via Vercel OIDC");
const status = lines.indexOf(" ↗ vpoke.playground-vercel.tools Authenticating via OIDC…");
expect(status).toBeGreaterThan(title);
expect(lines[status - 1]).toBe("");
@@ -5375,7 +5483,7 @@ describe("TerminalRenderer status line", () => {
const snapshot = screen.snapshot();
expect(snapshot).toContain("anthropic/claude-sonnet-5");
- expect(snapshot).toContain("via ai-gateway(oidc:my-agent)");
+ expect(snapshot).toContain("· ai-gateway(oidc:my-agent)");
// A fresh conversation clears the token flow entirely (↑ 0 ↓ 0 is noise).
expect(snapshot).not.toContain("↑ 0");
expect(snapshot).not.toContain("↑ 500");
@@ -5383,3 +5491,40 @@ describe("TerminalRenderer status line", () => {
renderer.shutdown();
});
});
+
+describe("setup interaction transitions", () => {
+ it.each([32, 80])(
+ "anchors the heading from loading through filtering at %i columns",
+ async (columns) => {
+ const { screen, input, renderer } = makeRenderer(columns);
+ renderer.setupFlow.begin("Add to your agent");
+ const titleRow = () =>
+ screen
+ .snapshot()
+ .split("\n")
+ .findIndex((row) => row.includes("Add to your agent"));
+ const initialRow = titleRow();
+ renderer.setupFlow.setStatus("Loading catalog…");
+ expect(titleRow()).toBe(initialRow);
+ const answer = renderer.setupFlow.readSelect({
+ kind: "search",
+ message: "Add to your agent",
+ options: [
+ { value: "slack", label: "Slack" },
+ { value: "linear", label: "Linear" },
+ ],
+ });
+ expect(titleRow()).toBe(initialRow);
+ expect(screen.snapshot().split("Add to your agent")).toHaveLength(2);
+ input.type("sl");
+ expect(titleRow()).toBe(initialRow);
+ input.send("\x1b");
+ input.send("\x1b");
+ await expect(answer).resolves.toBeUndefined();
+ expect(screen.snapshot()).not.toContain("Working…");
+ renderer.setupFlow.end({ preserveDiagnostics: false });
+ renderer.shutdown();
+ expect(screen.snapshot()).not.toContain("Add to your agent");
+ },
+ );
+});
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
index 5e32ce954..69a35987e 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
@@ -38,6 +38,7 @@ import {
import {
enterBadge,
renderFlowPanel,
+ flowMessageRows,
renderAcknowledgeQuestion,
renderModelEditorQuestion,
renderSelectQuestion,
@@ -143,7 +144,6 @@ import {
import { FileContentCache } from "./file-content-cache.js";
import { groupToolBlocksForDisplay } from "./tool-block-groups.js";
import { renderQuestionPanel } from "./question-panel.js";
-import { promptPlaceholder } from "./prompt-placeholder.js";
import { TurnClock } from "./turn-clock.js";
import {
allTodoItemsSettled,
@@ -254,6 +254,7 @@ type SetupFlowState = {
/** Recent subprocess output, flushed as context when a warning settles it. */
outputBuffer: string[];
question?: (width: number) => string[];
+ questionTitle?: string;
/** First line produced after the previous task-list question settled. */
taskListLineStart?: number;
/** Task-list questions render their latest outcomes inside the question. */
@@ -409,6 +410,10 @@ export class TerminalRenderer implements AgentTUIRenderer {
readonly #fileContents = new FileContentCache();
readonly #subagentHeaders = new Set<string>();
#agentHeader?: AgentHeaderOptions;
+ #startupPhase?: "starting" | "connecting" | "updating";
+ #startupEditor?: LineState;
+ #startupConsumer?: (key: TerminalKey) => void;
+ #startupStartedAt = 0;
#startupHeader?: { readonly name: string; readonly tip: string };
#agentHeaderRendered = false;
/** The last committed header body, to skip re-committing an unchanged banner. */
@@ -449,7 +454,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
* must not suggest unrelated things to try.
*/
#promptPlaceholderActive = false;
- readonly #promptPlaceholderStartedAtMs = Date.now();
/** Placeholder retires for good once the user has sent a first message. */
#hasUserMessage = false;
/** Armed by a chat submit; the end-of-turn stats line consumes it. */
@@ -544,7 +548,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
#questionPanel?: (width: number) => string[];
/** The active setup flow's bordered panel: progress, question, status. */
#setupFlow?: SetupFlowState;
- /** The clearable setup attention line (`⚠ … · /vc:login`), rendered in the live footer. */
+ /** The clearable setup attention line (`⚠ … · /deploy`), rendered in the live footer. */
#setupAttention?: string;
/**
* The pinned todo panel above the input, replaced wholesale by each `todo`
@@ -560,7 +564,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
#todoCommittedSignature?: string;
/**
* Messages submitted while a turn streams, pinned in a panel directly
- * above the input. Enter queues, `/cancel` cancels directly, and Esc or
+ * above the input when steering is unavailable. `/cancel` cancels directly, and Esc or
* Ctrl+C pops-to-steer or cancels immediately when empty; the runner drains
* via {@link takeQueuedPrompt} at a clean turn boundary and
* {@link readPrompt} restores any leftovers as a draft.
@@ -576,7 +580,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
/**
* Provenance of the next runner-submitted prompt, remembered between
* {@link takeQueuedPrompt} and the echo in {@link #addSubmittedPrompt} so
- * the user block can carry its steer/queue gutter arrow.
+ * the user block can use the steering gutter color.
*/
#nextSubmittedPromptOrigin?: "steer" | "queue";
/** True once this stream's prompt requested cancellation. */
@@ -647,6 +651,13 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#availablePromptCommands = options?.availablePromptCommands ?? PROMPT_COMMANDS;
}
+ setStartupPhase(phase: "starting" | "connecting" | "updating" | undefined): void {
+ this.#startupPhase = phase;
+ if (phase === undefined) this.#stopTicker();
+ else this.#startTicker();
+ this.#paint();
+ }
+
/**
* Commits the startup agent header (brand mark + resolved configuration) to
* scrollback before the first prompt. Later calls (dev HMR refreshing fields
@@ -656,6 +667,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
* Committed scrollback is never cleared or replayed.
*/
renderAgentHeader(options: AgentHeaderOptions): void {
+ this.#startupHeader = undefined;
this.#title = options.name;
this.#agentHeader = options;
this.#start();
@@ -671,29 +683,41 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#agentHeaderRendered = true;
this.#agentHeaderBody = body;
- // Commit the header to scrollback with no footer; the first `readPrompt`
- // paints the input line beneath it. Startup intentionally preserves the
- // user's existing scrollback instead of clearing the terminal.
- this.#live.flush(this.#renderAgentHeaderRows(), []);
+ // Preserve the live presentation when the startup header enters scrollback.
+ this.#live.flush(this.#renderAgentHeaderRows(), this.#footerRows(this.#width()));
}
beginStartupDraft(options: { initialDraft?: string; tip: string; title: string }): void {
this.#start({ title: options.title });
this.#inputActive = true;
this.#promptPlaceholderActive = true;
+ this.#startupPhase = "starting";
this.#startupHeader = { name: options.title, tip: options.tip };
+ this.#startupStartedAt = Date.now();
let editor = lineOf(stripPromptControlCharacters(options.initialDraft ?? ""));
+ this.#startupEditor = editor;
this.#syncInput(editor);
this.#startCaretBlink();
+ this.#startTicker();
this.#paint();
const apply = (next: LineState) => {
editor = next;
+ this.#startupEditor = next;
this.#showCaret();
this.#syncInput(editor);
this.#paint();
};
- this.#consumeKey = (key) => {
+ this.#startupConsumer = (key) => {
+ if (key.type === "escape" && this.#flowInterrupt !== undefined) {
+ this.#flowInterrupt("escape");
+ return;
+ }
+ if (key.type === "ctrl-c" && this.#flowInterrupt !== undefined) {
+ this.#requestExit();
+ this.#flowInterrupt("ctrl-c");
+ return;
+ }
const edited = applyLineEditorKey(editor, key, { multiline: true });
if (edited !== undefined) {
apply(edited);
@@ -705,18 +729,28 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
if (key.type === "ctrl-c") this.#onExitRequest?.();
};
+ this.#resumeStartupDraft();
+ }
+
+ #resumeStartupDraft(): void {
+ if (this.#startupEditor === undefined || this.#startupConsumer === undefined) return;
+ this.#clearKeyFlush();
+ this.#syncInput(this.#startupEditor);
+ this.#inputActive = true;
+ this.#consumeKey = this.#startupConsumer;
this.#attachInput();
}
finishStartupDraft(): { draft: string; queuedPrompt: string | undefined } {
const result = {
- draft: this.#inputText,
+ draft: this.#startupEditor?.text ?? this.#inputText,
queuedPrompt: this.#messageQueue.takePrompt(),
};
+ this.#startupEditor = undefined;
+ this.#startupConsumer = undefined;
this.#detachInput();
this.#stopCaretBlink();
this.#inputActive = false;
- this.#startupHeader = undefined;
this.#promptPlaceholderActive = false;
return result;
}
@@ -918,7 +952,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
* Consumes the next prompt produced by mid-turn input — the staged Esc
* steer message, or the whole queue coalesced into one. The runner calls
* this at a clean turn boundary and submits the result directly; the
- * remembered origin marks the echoed user block with its gutter arrow.
+ * remembered origin determines the echoed user block's gutter color.
*/
takeQueuedPrompt(): string | undefined {
const steering = this.#messageQueue.view().steering;
@@ -1769,7 +1803,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
/**
* Sets the setup attention line (yellow `⚠`, commands blue) as a live footer
* element above the prompt. Unlike committed scrollback, it can be cleared:
- * once the underlying issue is fixed (e.g. `/vc:login` succeeds) the runner calls
+ * once the underlying issue is fixed (e.g. `/deploy` succeeds) the runner calls
* {@link clearSetupWarning} and the line disappears rather than lingering
* stale in the transcript.
*/
@@ -1825,13 +1859,13 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
/**
- * Opens the bordered flow panel for one setup command. Until the flow ends,
+ * Opens the setup flow for one command. Until the flow ends,
* every flow line, question, and status renders inside it; the transcript
* above stays untouched.
*/
#beginSetupFlow(title: string, indicator: SetupFlowIndicator = "spinner"): void {
this.#start();
- this.#inputActive = false;
+ if (this.#startupEditor === undefined) this.#inputActive = false;
this.#turnIndicator = { kind: "idle" };
this.#status = "";
const indicatorState: SetupFlowIndicatorState =
@@ -1866,7 +1900,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
const flow = this.#setupFlow;
if (flow === undefined) return;
this.#setupFlow = undefined;
- this.#stopTicker();
+ if (this.#startupEditor !== undefined) this.#resumeStartupDraft();
+ else this.#stopTicker();
if (preserveDiagnostics) {
let evidence: string[] = [];
@@ -1903,7 +1938,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
* resolve.
*/
async #readSetupSelect(opts: SetupSelectRequest): Promise<SetupSelectResult> {
- const flow = this.#beginSetupQuestion();
+ const flow = this.#beginSetupQuestion(opts.message);
const multiple = isMultiSelectRequest(opts);
const searchAction = opts.kind === "search" ? opts.searchAction : undefined;
let selectOptions: readonly SetupPanelOption[] = opts.options;
@@ -1988,7 +2023,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
flow.hideLinesWhileQuestion = true;
}
const panelState = (): SetupOptionPanelState => {
- const state: SetupOptionPanelState = { ...opts, options: selectOptions, select };
+ const state: SetupOptionPanelState = { ...opts, message: "", options: selectOptions, select };
if (notices !== undefined && notices.length > 0) state.notices = notices;
if (error !== undefined) state.error = error;
if (loading) state.loadingFrame = this.#spinnerFrame();
@@ -2144,7 +2179,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
validate?: (value: string) => string | undefined;
};
}): Promise<SetupEditableSelectResult | undefined> {
- const flow = this.#beginSetupQuestion();
+ const flow = this.#beginSetupQuestion(opts.message);
const initial: Parameters<typeof initialSelectState>[0] = { options: opts.options };
if (opts.initialValue !== undefined) initial.defaultValue = opts.initialValue;
@@ -2156,7 +2191,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
const state: SetupSelectPanelState = {
kind: "inline-edit",
layout: "task-list",
- message: opts.message,
+ message: "",
options: opts.options,
select,
edit: {
@@ -2254,7 +2289,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
async #readProviderPicker(
opts: ProviderPickerRequest,
): Promise<ProviderPickerChoice | undefined> {
- const flow = this.#beginSetupQuestion();
+ const flow = this.#beginSetupQuestion(opts.message);
let interaction = initialProviderPickerState(opts.options, opts.initialValue);
let validation: AbortController | undefined;
@@ -2274,7 +2309,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
const panel: SetupSelectPanelState = {
kind: "inline-edit",
layout: "stacked",
- message: opts.message,
+ message: "",
options: opts.options,
select: interaction.select,
edit: {
@@ -2395,11 +2430,11 @@ export class TerminalRenderer implements AgentTUIRenderer {
* on Esc/Ctrl-C.
*/
async #readModelEditor(opts: ModelSettingsRequest): Promise<ModelSettingsResult | undefined> {
- const flow = this.#beginSetupQuestion();
+ const flow = this.#beginSetupQuestion("Select the model");
let interaction = initialModelEditorState(opts);
flow.question = (width) =>
- renderModelEditorQuestion({ request: opts, state: interaction }, this.#theme, width);
+ renderModelEditorQuestion({ request: opts, state: interaction }, this.#theme, width, "");
this.#paint();
const question = this.#captureSetupQuestion<ModelSettingsResult | undefined>((key, settle) => {
@@ -2478,14 +2513,14 @@ export class TerminalRenderer implements AgentTUIRenderer {
validate?: (value: string) => string | undefined;
notices?: readonly SelectNotice[];
}): Promise<string | undefined> {
- const flow = this.#beginSetupQuestion();
+ const flow = this.#beginSetupQuestion(opts.message);
let editor: LineState = lineOf("");
let error: string | undefined;
flow.question = (width) => {
const state: Parameters<typeof renderTextQuestion>[0] = {
- message: opts.message,
+ message: "",
editor,
mask: opts.mask === true,
};
@@ -2546,10 +2581,10 @@ export class TerminalRenderer implements AgentTUIRenderer {
* is nothing to cancel, so this never returns a cancellation.
*/
async #readSetupAcknowledge(opts: { message: string; lines: readonly string[] }): Promise<void> {
- const flow = this.#beginSetupQuestion();
+ const flow = this.#beginSetupQuestion(opts.message);
flow.question = (width) =>
- renderAcknowledgeQuestion({ message: opts.message, lines: opts.lines }, this.#theme, width);
+ renderAcknowledgeQuestion({ message: "", lines: opts.lines }, this.#theme, width);
this.#paint();
const question = this.#captureSetupQuestion<void>((key, settle) => {
@@ -2570,12 +2605,13 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
/** Enters the common inactive-input state owned by an open setup question. */
- #beginSetupQuestion(): SetupFlowState {
+ #beginSetupQuestion(title: string): SetupFlowState {
this.#start();
this.#inputActive = false;
this.#turnIndicator = { kind: "idle" };
this.#status = "";
const flow = this.#requireSetupFlow();
+ flow.questionTitle = stripTerminalControls(title);
// A standard question means the preceding background operation settled.
// Clear its transient item summary and timer before painting the prompt.
if (flow.status !== undefined) {
@@ -2608,14 +2644,17 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#setupFlow = undefined;
} else if (this.#setupFlow !== undefined) {
this.#setupFlow.question = undefined;
+ this.#setupFlow.questionTitle = undefined;
this.#setupFlow.hideLinesWhileQuestion = false;
}
this.#consumeKey = undefined;
this.#detachInput();
// Back to the working state: the interrupt trap covers the gap until the
// next question (or the flow's end).
- if (this.#setupFlow !== undefined) this.#armFlowIdleTrap();
- this.#paint();
+ if (this.#startupEditor !== undefined) this.#resumeStartupDraft();
+ else if (this.#setupFlow !== undefined) this.#armFlowIdleTrap();
+ // The next phase paints its complete state; the flow ticker covers slow work.
+ if (this.#setupFlow === undefined) this.#paint();
}
/**
@@ -2694,6 +2733,10 @@ export class TerminalRenderer implements AgentTUIRenderer {
* re-arms.
*/
#armFlowIdleTrap(interruptible = true): void {
+ if (this.#startupEditor !== undefined) {
+ this.#resumeStartupDraft();
+ return;
+ }
if (this.#flowInterrupt === undefined) return;
const consumer = (key: TerminalKey): void => {
if (interruptible && (key.type === "ctrl-c" || key.type === "escape")) {
@@ -3220,10 +3263,11 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#paint();
break;
}
- // Mid-turn Enter queues the draft as a message for the next turn
- // (or for a steer-key pop). A full queue keeps the draft in place —
- // the panel header says why — rather than silently dropping input.
- if (this.#messageQueue.enqueue(message)) {
+ const send = this.#sendSteering;
+ if (send !== undefined && parsePromptCommand(message) === null) {
+ this.#streamDraft = EMPTY_LINE;
+ this.#submitSteering(message, send);
+ } else if (this.#messageQueue.enqueue(message)) {
this.#streamDraft = EMPTY_LINE;
}
this.#paint();
@@ -3252,13 +3296,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
const send = this.#sendSteering;
if (send !== undefined) {
const message = this.#messageQueue.takeSteering()!;
- this.#nextSubmittedPromptOrigin = "steer";
- this.#addSubmittedPrompt(message);
- void send(message).catch((error) => {
- this.#messageQueue.restoreSteering(message);
- this.#addErrorBlock("Steering failed", toErrorMessage(error));
- this.#paint();
- });
+ this.#submitSteering(message, send);
}
} else {
this.#cancelRequestedByUser = true;
@@ -3278,6 +3316,16 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
}
+ #submitSteering(message: string, send: (message: string) => Promise<void>): void {
+ this.#nextSubmittedPromptOrigin = "steer";
+ this.#addSubmittedPrompt(message);
+ void send(message).catch((error) => {
+ this.#messageQueue.restoreSteering(message);
+ this.#addErrorBlock("Steering failed", toErrorMessage(error));
+ this.#paint();
+ });
+ }
+
#startCaretBlink() {
this.#stopCaretBlink();
this.#showCaret();
@@ -4186,7 +4234,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
const flow = this.#setupFlow;
- if (flow !== undefined) {
+ if (flow !== undefined && (this.#startupEditor === undefined || flow.question !== undefined)) {
// No status line under an open flow panel: the flow is mutating the
// very state the line shows (link, pending deploy, model), so mid-flow
// values are guaranteed stale; it reappears, refreshed, when the
@@ -4205,9 +4253,9 @@ export class TerminalRenderer implements AgentTUIRenderer {
// so their panels stay status-free as before.
if (flow.question !== undefined) {
const rows = flow.question(width);
- content = { kind: "question", rows };
+ content = { kind: "question", title: flow.questionTitle, rows };
if (status !== undefined) {
- content = { kind: "question", rows, status };
+ content = { kind: "question", title: flow.questionTitle, rows, status };
}
} else if (status !== undefined) {
content = { kind: "status", status };
@@ -4245,10 +4293,18 @@ export class TerminalRenderer implements AgentTUIRenderer {
return rows;
}
+ if (flow !== undefined) {
+ rows.push(
+ ...flowMessageRows(flow.lines, this.#theme).map((row) =>
+ row.length === 0 ? "" : clip(` ${row}`, width),
+ ),
+ );
+ }
+
// The setup attention line rides above the pinned panels as a live
// element, so resolving its issue clears it instead of leaving it stale
// in scrollback.
- if (this.#setupAttention !== undefined) {
+ if (this.#startupPhase === undefined && this.#setupAttention !== undefined) {
rows.push(...renderAttentionRows(this.#setupAttention, width, this.#theme), "");
}
@@ -4302,9 +4358,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
const isCommand = isPromptControlCommand(this.#inputText);
const ghost = inlineHint ? c.dim(` ${inlineHint}`) : "";
const statusRows: string[] = [];
- if (this.#startupHeader !== undefined) {
- statusRows.push(clip(c.dim(`${this.#theme.glyph.dot} Building your agent…`), width));
- }
this.#pushStatusLine(statusRows, width);
// Keep one transcript row above the footer and one separator below the
// prompt. Everything already in `rows` has higher-level footer ownership
@@ -4320,12 +4373,15 @@ export class TerminalRenderer implements AgentTUIRenderer {
ghost,
maxRows: maxPromptRows,
};
- // An empty chat prompt always wears the quiet `›`; the rotating
+ // An empty chat prompt keeps the full-size prompt mark; the
// invitation text rides it only until the user's first message.
if (this.#promptPlaceholderActive && this.#inputText.length === 0) {
- promptRows.placeholder = this.#hasUserMessage
- ? ""
- : promptPlaceholder(Date.now() - this.#promptPlaceholderStartedAtMs);
+ promptRows.placeholder =
+ this.#startupEditor !== undefined
+ ? "Message · Enter to queue"
+ : this.#hasUserMessage
+ ? ""
+ : "Send a message…";
}
rows.push(...promptInputRows(promptRows));
rows.push(...statusRows);
@@ -4424,8 +4480,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
*/
#pushStreamingPrompt(rows: string[], width: number): void {
if (!this.#streamDraftActive) return;
- // An empty pending prompt wears the same quiet `›` as the idle one; a
- // typed draft flips to a DIM `❯` (inert — Enter does nothing yet).
+ // An empty pending prompt wears the same `❯` as the idle one; a
+ // typed draft dims the `❯` (inert — Enter does nothing yet).
// Readiness is therefore NOT detectable from the glyph — MockScreen's
// `waitForIdlePrompt` discriminates by the live turn bar's absence.
this.#pushDraftPrompt(rows, width, { inert: true });
@@ -4452,6 +4508,20 @@ export class TerminalRenderer implements AgentTUIRenderer {
/** Appends the persistent bottom status line below the prompt when it has content. */
#pushStatusLine(rows: string[], width: number): void {
+ if (this.#startupPhase !== undefined) {
+ const labels = {
+ starting: "Starting agent…",
+ connecting: "Reading saved connection…",
+ updating: "Loading selected model…",
+ };
+ const label = this.#setupFlow?.status?.text ?? labels[this.#startupPhase];
+ const pulse = this.#progressPulseGlyph(
+ this.#startupStartedAt,
+ this.#theme.unicode ? PROGRESS_PULSE_GLYPH : PROGRESS_PULSE_ASCII_GLYPH,
+ );
+ rows.push(clip(this.#theme.colors.dim(`${pulse} ${label}`), width));
+ return;
+ }
const padding = this.#remoteConnection === undefined ? "" : STATUS_LINE_LEFT_PADDING;
const contentWidth = Math.max(1, width - padding.length);
const input: Parameters<typeof buildStatusLine>[0] = {
@@ -4462,11 +4532,6 @@ export class TerminalRenderer implements AgentTUIRenderer {
input.devBuild = this.#devBuildStatus;
}
if (this.#logLevelHintActive) input.logLevel = this.#logs;
- const serverUrl = this.#agentHeader?.serverUrl;
- if (serverUrl !== undefined && this.#remoteConnection === undefined) {
- const serverPort = new URL(serverUrl).port;
- if (serverPort.length > 0) input.serverPort = serverPort;
- }
const agentModel = this.#agentHeader?.info?.agent.model;
if (agentModel?.id !== undefined) input.model = agentModel.id;
// "provider-default" is the absent-setting sentinel, not a level worth showing.
@@ -4887,9 +4952,9 @@ interface PromptInputRowsInput {
readonly ghost: string;
readonly maxRows: number;
/**
- * Present on an empty chat prompt: switches the gutter to the quiet `›`.
+ * Present on an empty chat prompt: shows invitation text behind the caret.
* Non-empty text renders dim behind the caret; the empty string keeps the
- * quiet mark with a bare caret (the post-first-message state).
+ * prompt mark with a bare caret (the post-first-message state).
*/
placeholder?: string;
/** Anchored-but-inert prompt (streaming turn): typed drafts show a dim `❯`. */
@@ -4917,8 +4982,7 @@ function promptInputRows({
const c = theme.colors;
if (text.length === 0 && placeholder !== undefined) {
- // The empty state trades the active `❯` for a quiet `›` and lets the
- // caret rest on the placeholder's first character, like the setup
+ // The caret rests on the placeholder's first character, like the setup
// panel's text fields.
const body = renderInputWithBlockCursor({
...visibleLine(
@@ -4930,7 +4994,7 @@ function promptInputRows({
inverse: c.inverse,
render: (segment) => c.dim(renderInputText(segment)),
});
- return [clip(`${c.dim(theme.glyph.promptIdle)} ${body}`, width), ""];
+ return [clip(`${theme.glyph.prompt} ${body}`, width), ""];
}
const style = (segment: string): string => {
@@ -4944,8 +5008,7 @@ function promptInputRows({
0,
Math.min(layout.caretRow - visibleCount + 1, layout.rows.length - visibleCount),
);
- // An inert prompt's typed draft flips the mark like the active prompt,
- // but keeps it dim: the state is legible without claiming readiness.
+ // An inert prompt's typed draft keeps the mark dim: the state is legible without claiming readiness.
const promptGlyph = inert === true ? c.dim(theme.glyph.prompt) : c.cyan(theme.glyph.prompt);
const ellipsis = c.dim(theme.glyph.ellipsis);
// Reserve the gutter and the block cursor's trailing cell at end-of-line.
diff --git a/packages/eve/src/cli/dev/tui/test/mock-terminal.ts b/packages/eve/src/cli/dev/tui/test/mock-terminal.ts
index 7edc928a7..e2c2dd23b 100644
--- a/packages/eve/src/cli/dev/tui/test/mock-terminal.ts
+++ b/packages/eve/src/cli/dev/tui/test/mock-terminal.ts
@@ -127,9 +127,9 @@ export class MockScreen extends EventEmitter implements TerminalOutput {
}
/**
- * Resolves once the runner parks at an idle prompt: a column-0 `›` row
+ * Resolves once the runner parks at an idle prompt: a column-0 `❯` row
* with no live turn bar on screen. A streaming turn keeps an identical
- * `›` prompt anchored (Enter inert), so the glyph alone cannot signal
+ * `❯` prompt anchored (Enter inert), so the glyph alone cannot signal
* readiness — the bar's absence is the discriminator.
*/
async waitForIdlePrompt(timeoutMs = 1000) {
@@ -147,7 +147,7 @@ export class MockScreen extends EventEmitter implements TerminalOutput {
// ASCII brand mark, and every TUI smoke script pins EVE_TUI_UNICODE=1.
const idle = () => {
const snapshot = this.snapshot();
- return /^[›❯]/mu.test(snapshot) && !liveTurnBar.test(snapshot);
+ return /^[❯]/mu.test(snapshot) && !liveTurnBar.test(snapshot);
};
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
diff --git a/packages/eve/src/cli/dev/tui/theme.ts b/packages/eve/src/cli/dev/tui/theme.ts
index 9b8a5902f..47d6353f2 100644
--- a/packages/eve/src/cli/dev/tui/theme.ts
+++ b/packages/eve/src/cli/dev/tui/theme.ts
@@ -99,8 +99,6 @@ export interface ThemeGlyphs {
option: string;
/** `❯` — the input prompt mark. */
prompt: string;
- /** `›` — the prompt mark's quiet form while the buffer is empty. */
- promptIdle: string;
/** `⎿` — hangs a command's result under its invocation. */
elbow: string;
/** `▔` — strong full-width rule opening the bottom question panel. */
@@ -150,11 +148,10 @@ const UNICODE_GLYPHS: ThemeGlyphs = {
question: "?",
connection: "●",
arrow: "→",
- pointer: "▷",
- selectedPointer: "▶",
- option: "◦",
+ pointer: "›",
+ selectedPointer: "›",
+ option: " ",
prompt: "❯",
- promptIdle: "›",
elbow: "⎿",
hrule: "▔",
dash: "─",
@@ -193,7 +190,6 @@ const ASCII_GLYPHS: ThemeGlyphs = {
selectedPointer: ">",
option: ".",
prompt: ">",
- promptIdle: ">",
elbow: "`-",
hrule: "=",
dash: "-",
diff --git a/packages/eve/src/cli/dev/tui/vercel-status.test.ts b/packages/eve/src/cli/dev/tui/vercel-status.test.ts
index fcb9c3be8..b26a7a4cc 100644
--- a/packages/eve/src/cli/dev/tui/vercel-status.test.ts
+++ b/packages/eve/src/cli/dev/tui/vercel-status.test.ts
@@ -1,7 +1,11 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { createVercelStatusTracker, type VercelStatusSnapshot } from "./vercel-status.js";
+vi.mock("#internal/model-auth/vercel-team.js", () => ({
+ resolveModelTeamSlug: async () => undefined,
+}));
+
const identity = { projectName: "my-agent", teamName: "acme" };
function collect(): {
@@ -14,11 +18,38 @@ function collect(): {
async function settled(): Promise<void> {
// Two microtask hops: one for the probe's await, one for the emit.
- await Promise.resolve();
- await Promise.resolve();
+ for (let i = 0; i < 10; i++) await Promise.resolve();
}
describe("createVercelStatusTracker", () => {
+ it("resolves a projectless model team slug without a deployment identity", async () => {
+ const { snapshots, onChange } = collect();
+ const tracker = createVercelStatusTracker({
+ appRoot: "/app",
+ onChange,
+ detectIdentity: async () => undefined,
+ resolveTeamSlug: async () => "acme",
+ });
+ tracker.refreshIdentity();
+ await settled();
+ expect(snapshots).toEqual([{ modelTeamSlug: "acme" }]);
+ });
+
+ it("keeps deployment status usable when the model team lookup fails", async () => {
+ const { snapshots, onChange } = collect();
+ const tracker = createVercelStatusTracker({
+ appRoot: "/app",
+ onChange,
+ detectIdentity: async () => identity,
+ resolveTeamSlug: async () => {
+ throw new Error("offline");
+ },
+ });
+ tracker.refreshIdentity();
+ await settled();
+ expect(snapshots).toEqual([{ identity }]);
+ });
+
it("emits the resolved identity after a refresh", async () => {
const { snapshots, onChange } = collect();
const tracker = createVercelStatusTracker({
diff --git a/packages/eve/src/cli/dev/tui/vercel-status.ts b/packages/eve/src/cli/dev/tui/vercel-status.ts
index f5619be1d..ddb17f0e5 100644
--- a/packages/eve/src/cli/dev/tui/vercel-status.ts
+++ b/packages/eve/src/cli/dev/tui/vercel-status.ts
@@ -1,9 +1,11 @@
+import { resolveModelTeamSlug } from "#internal/model-auth/vercel-team.js";
import { detectProjectIdentity, type ProjectIdentity } from "#setup/project-resolution.js";
/** Workspace-scoped Vercel state shown in the dev TUI's status line. */
export interface VercelStatusSnapshot {
/** Resolved link identity; absent while unlinked or while a probe is in flight. */
identity?: ProjectIdentity;
+ modelTeamSlug?: string;
}
/**
@@ -20,11 +22,11 @@ export interface VercelStatusTrackerOptions {
onChange: (snapshot: VercelStatusSnapshot) => void;
/** Test seam; defaults to the real network-bound probe. */
detectIdentity?: typeof detectProjectIdentity;
+ resolveTeamSlug?: typeof resolveModelTeamSlug;
}
/**
- * Owns the Vercel segment of the dev TUI status line: one cached link
- * identity. The identity probe is network-bound (it shells `vercel api`), so it runs only at startup and
+ * Owns the Vercel segment of the dev TUI status line: cached deployment identity and model-account team slug. The identity probe is network-bound (it shells `vercel api`), so it runs only at startup and
* after provider setup or a /deploy — never on a poll. A linked directory
* whose `vercel` CLI call fails resolves to the raw project id as the name
* (see {@link detectProjectIdentity}); an unlinked one resolves to no identity,
@@ -45,14 +47,20 @@ export function createVercelStatusTracker(
): VercelStatusTracker {
const detectIdentity = options.detectIdentity ?? detectProjectIdentity;
let identity: ProjectIdentity | undefined;
+ let modelTeamSlug: string | undefined;
// Incremented on every refresh and on dispose, so a slow probe that loses
- // the race (e.g. startup probe vs. a /vercel re-link's probe) can never
+ // the race (e.g. startup probe vs. a /login refresh) can never
// overwrite the newer result.
let epoch = 0;
let disposed = false;
let identityProbeAbort: AbortController | undefined;
- const snapshot = (): VercelStatusSnapshot => (identity === undefined ? {} : { identity });
+ const snapshot = (): VercelStatusSnapshot => {
+ const value: VercelStatusSnapshot = {};
+ if (identity !== undefined) value.identity = identity;
+ if (modelTeamSlug !== undefined) value.modelTeamSlug = modelTeamSlug;
+ return value;
+ };
const emit = (): void => {
if (disposed) return;
@@ -68,8 +76,14 @@ export function createVercelStatusTracker(
const probeEpoch = epoch;
void (async () => {
let resolved: ProjectIdentity | undefined;
+ let slug: string | undefined;
try {
- resolved = await detectIdentity(options.appRoot, { signal: probeAbort.signal });
+ [resolved, slug] = await Promise.all([
+ detectIdentity(options.appRoot, { signal: probeAbort.signal }),
+ (options.resolveTeamSlug ?? resolveModelTeamSlug)(probeAbort.signal).catch(
+ () => undefined,
+ ),
+ ]);
} catch {
// detectProjectIdentity never throws today; if a future change does,
// keep the last known identity rather than killing the prompt loop.
@@ -81,6 +95,7 @@ export function createVercelStatusTracker(
}
if (disposed || probeEpoch !== epoch) return;
identity = resolved;
+ modelTeamSlug = slug;
emit();
})();
};
diff --git a/packages/eve/src/cli/run.test.ts b/packages/eve/src/cli/run.test.ts
index c847b31af..c7b44540f 100644
--- a/packages/eve/src/cli/run.test.ts
+++ b/packages/eve/src/cli/run.test.ts
@@ -488,6 +488,54 @@ describe("eve dev --input", () => {
).rejects.toThrow("--input requires the interactive UI");
});
+ it.each([false, true])(
+ "starts the composer before the host is ready (onboard: %s)",
+ async (onboard) => {
+ let release!: () => void;
+ const ready = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const startup = {
+ renderer: {},
+ finish: vi.fn(() => ({ draft: "", queuedPrompt: undefined })),
+ shutdown: vi.fn(async () => {}),
+ };
+ const startDevelopmentTuiStartup = vi.fn(async () => startup);
+ const runDevelopmentTui = vi.fn(async () => {});
+ vi.doMock("#cli/dev/tui/tui.js", () => ({ startDevelopmentTuiStartup, runDevelopmentTui }));
+ const startHost = vi.fn(() => ({
+ start: async () => {
+ await ready;
+ return {
+ kind: "started" as const,
+ appRoot: "/canonical/app",
+ url: "http://127.0.0.1:4321/",
+ };
+ },
+ close: async () => {},
+ }));
+ try {
+ await withInteractiveTerminal(async () => {
+ const run = runCli(
+ onboard ? ["dev", "--onboard"] : ["dev"],
+ { error: () => {}, log: () => {} },
+ { startHost },
+ );
+ try {
+ await vi.waitFor(() => expect(startDevelopmentTuiStartup).toHaveBeenCalledOnce());
+ expect(runDevelopmentTui).not.toHaveBeenCalled();
+ } finally {
+ release();
+ await run;
+ }
+ });
+ expect(runDevelopmentTui).toHaveBeenCalledWith(expect.objectContaining({ startup }));
+ } finally {
+ vi.doUnmock("#cli/dev/tui/tui.js");
+ }
+ },
+ );
+
it("forwards the internal init onboarding handoff to the local TUI", async () => {
const startHost = vi.fn(() => ({
start: async () => ({
diff --git a/packages/eve/src/cli/run.ts b/packages/eve/src/cli/run.ts
index 1fa072ccd..ea2aac1f6 100644
--- a/packages/eve/src/cli/run.ts
+++ b/packages/eve/src/cli/run.ts
@@ -461,7 +461,7 @@ export function createCliProgram(
let tuiStartup: DevelopmentTuiStartup | undefined;
const tuiStartupPromise =
- mode === "tui" && options.onboard !== true && runtime.runDevelopmentTui === undefined
+ mode === "tui" && runtime.runDevelopmentTui === undefined
? loadDevelopmentTuiModule().then((module) => {
onBootProgress({ type: "before-first-paint" });
return module.startDevelopmentTuiStartup({
diff --git a/packages/eve/src/cli/telemetry/index.test.ts b/packages/eve/src/cli/telemetry/index.test.ts
index 8e271d177..fd5388192 100644
--- a/packages/eve/src/cli/telemetry/index.test.ts
+++ b/packages/eve/src/cli/telemetry/index.test.ts
@@ -148,6 +148,27 @@ describe("createEveCliTelemetry", () => {
});
});
+ it("records timestamped connection readiness and first response without content", async () => {
+ vi.stubEnv("NODE_ENV", "production");
+ vi.stubEnv("EVE_TELEMETRY_DEBUG", "1");
+ const write = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
+ const telemetry = createEveCliTelemetry("1.0.0");
+ telemetry.trackCommand("dev");
+ telemetry.trackSetupStep({ flow: "onboarding", step: "connection_ready" });
+ telemetry.trackSetupTerminal({
+ flow: "onboarding",
+ step: "model_provider",
+ result: "completed",
+ });
+ telemetry.trackSetupStep({ flow: "onboarding", step: "first_response" });
+ await telemetry.flush();
+ const events = JSON.parse(String(write.mock.calls[0]?.[0]).replace("[eve telemetry] ", ""));
+ for (const value of ["connection_ready", "first_response"])
+ expect(events).toContainEqual(
+ expect.objectContaining({ key: "setup_step", value, event_time: expect.any(Number) }),
+ );
+ });
+
it("records the furthest init stage without error details", async () => {
vi.stubEnv("NODE_ENV", "production");
vi.stubEnv("EVE_TELEMETRY_DEBUG", "1");
diff --git a/packages/eve/src/cli/telemetry/index.ts b/packages/eve/src/cli/telemetry/index.ts
index 788d1f3e5..4a682ea5e 100644
--- a/packages/eve/src/cli/telemetry/index.ts
+++ b/packages/eve/src/cli/telemetry/index.ts
@@ -27,6 +27,8 @@ export type EveCliSetupStep =
| "install_dependencies"
| "initialize_git"
| "handoff"
+ | "connection_ready"
+ | "first_response"
| "model_provider"
| "model_settings"
| "registry_channels"
@@ -100,6 +102,8 @@ function setupFailureCode(step: EveCliSetupStep): EveCliSetupFailureCode {
return "git_initialization";
case "handoff":
return "handoff";
+ case "connection_ready":
+ case "first_response":
case "model_provider":
case "model_settings":
case "registry_channels":
diff --git a/packages/eve/src/client/agent-info-schema.ts b/packages/eve/src/client/agent-info-schema.ts
index 4f6311da8..8cbe0f0db 100644
--- a/packages/eve/src/client/agent-info-schema.ts
+++ b/packages/eve/src/client/agent-info-schema.ts
@@ -83,7 +83,8 @@ const modelEndpoint = z.union([
.object({
kind: z.literal("gateway"),
connected: z.literal(true),
- credential: z.enum(["api-key", "oidc"]),
+ credential: z.enum(["api-key", "oidc", "oauth"]),
+ team: z.optional(z.string()),
})
.strict(),
z.object({ kind: z.literal("gateway"), connected: z.literal(false) }).strict(),
diff --git a/packages/eve/src/execution/sandbox/bindings/eve-image.test.ts b/packages/eve/src/execution/sandbox/bindings/eve-image.test.ts
index f4e4d75ad..c7c899eea 100644
--- a/packages/eve/src/execution/sandbox/bindings/eve-image.test.ts
+++ b/packages/eve/src/execution/sandbox/bindings/eve-image.test.ts
@@ -1,7 +1,8 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+const packageInfo = vi.hoisted(() => ({ name: "eve", version: "1.2.3" }));
vi.mock("#internal/application/package.js", () => ({
- resolveInstalledPackageInfo: () => ({ name: "eve", version: "1.2.3" }),
+ resolveInstalledPackageInfo: () => packageInfo,
}));
import {
@@ -12,6 +13,10 @@ import {
} from "#execution/sandbox/bindings/eve-image.js";
describe("eve sandbox image", () => {
+ beforeEach(() => {
+ packageInfo.version = "1.2.3";
+ vi.stubEnv("EVE_SANDBOX_IMAGE_TAG", "");
+ });
afterEach(() => {
vi.unstubAllEnvs();
vi.resetModules();
@@ -27,7 +32,22 @@ describe("eve sandbox image", () => {
expect(VERCEL_EVE_SANDBOX_IMAGE).toBe("vcr.vercel.com/vercel/eve/base:1.2.3");
});
+ it.each([
+ ["0.56.0+git.4c27b3e37fa36d84", "0.56.0"],
+ ["0.56.0+main.4c27b3e37fa36d84", "0.56.0"],
+ ["0.56.0-beta.1+git.4c27b3e37fa36d84", "0.56.0-beta.1"],
+ ])("uses the release image for artifact version %s", async (version, tag) => {
+ packageInfo.version = version;
+ vi.resetModules();
+ const images = await import("#execution/sandbox/bindings/eve-image.js");
+ expect(images.resolveEveSandboxImage()).toBe(`ghcr.io/vercel/eve:${tag}`);
+ expect(images.DEFAULT_EVE_SANDBOX_IMAGE).toBe(`ghcr.io/vercel/eve:${tag}`);
+ expect(images.resolveVercelEveSandboxImage()).toBe(`vcr.vercel.com/vercel/eve/base:${tag}`);
+ expect(images.VERCEL_EVE_SANDBOX_IMAGE).toBe(`vcr.vercel.com/vercel/eve/base:${tag}`);
+ });
+
it("uses EVE_SANDBOX_IMAGE_TAG for both registries", async () => {
+ packageInfo.version = "0.56.0+git.4c27b3e37fa36d84";
vi.stubEnv("EVE_SANDBOX_IMAGE_TAG", "latest");
vi.resetModules();
diff --git a/packages/eve/src/execution/sandbox/bindings/eve-image.ts b/packages/eve/src/execution/sandbox/bindings/eve-image.ts
index 7face7880..5bbffe5bf 100644
--- a/packages/eve/src/execution/sandbox/bindings/eve-image.ts
+++ b/packages/eve/src/execution/sandbox/bindings/eve-image.ts
@@ -1,4 +1,5 @@
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
+import { stripVersionBuildMetadata } from "#shared/package-version.js";
const GHCR_EVE_SANDBOX_IMAGE_REPOSITORY = "ghcr.io/vercel/eve";
const VERCEL_EVE_SANDBOX_IMAGE_REPOSITORY = "vcr.vercel.com/vercel/eve/base";
@@ -15,7 +16,7 @@ function resolveEveSandboxImageTag(): string {
const override = process.env.EVE_SANDBOX_IMAGE_TAG?.trim();
return override !== undefined && override.length > 0
? override
- : resolveInstalledPackageInfo().version;
+ : stripVersionBuildMetadata(resolveInstalledPackageInfo().version);
}
export const DEFAULT_EVE_SANDBOX_IMAGE = resolveEveSandboxImage();
diff --git a/packages/eve/src/internal/model-auth/api-key.ts b/packages/eve/src/internal/model-auth/api-key.ts
new file mode 100644
index 000000000..5ff9c0765
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/api-key.ts
@@ -0,0 +1,27 @@
+import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
+import { MODEL_CONNECTION_ENV } from "#shared/model-helper.js";
+import { readModelSecret, modelKeySecretName } from "./store.js";
+
+const KEY_ENV = {
+ openai: "OPENAI_API_KEY",
+ anthropic: "ANTHROPIC_API_KEY",
+ "ai-gateway-key": "AI_GATEWAY_API_KEY",
+} as const;
+
+export async function resolveModelApiKey(provider: keyof typeof KEY_ENV): Promise<string> {
+ const value = process.env[KEY_ENV[provider]];
+ const source =
+ isEveDevEnvironment() && process.env[MODEL_CONNECTION_ENV] === provider
+ ? process.env.EVE_MODEL_KEY_SOURCE
+ : undefined;
+ if (value?.trim() && source !== "secret") return value;
+ if (isEveDevEnvironment() && source !== "environment") {
+ const stored = await readModelSecret(modelKeySecretName(provider));
+ if (stored) return stored;
+ }
+ if (source === "secret")
+ throw new Error("The selected saved API key is unavailable. Run /login to reconnect.");
+ throw new Error(
+ `Set ${KEY_ENV[provider]}${isEveDevEnvironment() ? " or connect with /login" : " in the server environment"}.`,
+ );
+}
diff --git a/packages/eve/src/internal/model-auth/available-models.test.ts b/packages/eve/src/internal/model-auth/available-models.test.ts
new file mode 100644
index 000000000..b496303d0
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/available-models.test.ts
@@ -0,0 +1,32 @@
+import { afterEach, expect, it, vi } from "vitest";
+vi.mock("#public/models/openai/chatgpt/token-broker.js", () => ({
+ getDefaultCodexTokenBroker: () => ({
+ getToken: async () => ({ token: "test-token", accountId: "test-account" }),
+ }),
+}));
+import { availableHelperModels } from "./available-models.js";
+
+afterEach(() => vi.unstubAllGlobals());
+
+it("loads ChatGPT catalogs with large embedded model instructions after sign-in", async () => {
+ const fetch = vi.fn(async () =>
+ Response.json({
+ models: [{ slug: "gpt-5.6-luna-fast", instructions: "x".repeat(300_000) }],
+ }),
+ );
+ vi.stubGlobal("fetch", fetch);
+ await expect(availableHelperModels("chatgpt")).resolves.toEqual(["gpt-5.6-luna-fast"]);
+ expect(fetch).toHaveBeenCalledWith(
+ expect.stringContaining("/backend-api/codex/models"),
+ expect.objectContaining({
+ headers: expect.objectContaining({ "ChatGPT-Account-Id": "test-account" }),
+ }),
+ );
+});
+
+it("still bounds catalog response sizes", async () => {
+ vi.stubGlobal("fetch", async () =>
+ Response.json({ models: [], padding: "x".repeat(8 * 1024 * 1024) }),
+ );
+ await expect(availableHelperModels("chatgpt")).rejects.toThrow("too large");
+});
diff --git a/packages/eve/src/internal/model-auth/available-models.ts b/packages/eve/src/internal/model-auth/available-models.ts
new file mode 100644
index 000000000..f4326b0f1
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/available-models.ts
@@ -0,0 +1,57 @@
+import { isObject } from "#shared/guards.js";
+import { getDefaultCodexTokenBroker } from "#public/models/openai/chatgpt/token-broker.js";
+import { authJson } from "./vercel.js";
+import { resolveModelApiKey } from "./transport.js";
+
+const MODEL_CATALOG_MAX_BYTES = 8 * 1024 * 1024;
+
+export async function availableDirectModels(
+ provider: "openai" | "anthropic",
+ key: string,
+ signal?: AbortSignal,
+): Promise<string[]> {
+ const value = await authJson(
+ provider === "openai"
+ ? "https://api.openai.com/v1/models"
+ : "https://api.anthropic.com/v1/models?limit=1000",
+ {
+ headers:
+ provider === "openai"
+ ? { authorization: `Bearer ${key}` }
+ : { "x-api-key": key, "anthropic-version": "2023-06-01" },
+ signal,
+ },
+ MODEL_CATALOG_MAX_BYTES,
+ );
+ if (!Array.isArray(value.data))
+ throw new Error("The provider could not validate this key. Check it and retry /login.");
+ return value.data.flatMap((model) =>
+ isObject(model) && typeof model.id === "string" ? [model.id] : [],
+ );
+}
+
+export async function availableHelperModels(
+ provider: "openai" | "anthropic" | "chatgpt",
+ signal?: AbortSignal,
+): Promise<string[]> {
+ if (provider !== "chatgpt")
+ return availableDirectModels(provider, await resolveModelApiKey(provider), signal);
+ const token = await getDefaultCodexTokenBroker().getToken({ reason: "request" });
+ const headers: Record<string, string> = {
+ authorization: `Bearer ${token.token}`,
+ originator: "eve",
+ };
+ if (token.accountId) headers["ChatGPT-Account-Id"] = token.accountId;
+ const value = await authJson(
+ "https://chatgpt.com/backend-api/codex/models?client_version=0.148.0",
+ { headers, signal },
+ MODEL_CATALOG_MAX_BYTES,
+ );
+ if (!Array.isArray(value.models))
+ throw new Error("Could not load ChatGPT models. Check your connection and retry /login.");
+ return value.models.flatMap((model) =>
+ isObject(model) && typeof model.slug === "string" && model.visibility !== "hide"
+ ? [model.slug]
+ : [],
+ );
+}
diff --git a/packages/eve/src/internal/model-auth/development-broker-client.ts b/packages/eve/src/internal/model-auth/development-broker-client.ts
new file mode 100644
index 000000000..892750d60
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/development-broker-client.ts
@@ -0,0 +1,56 @@
+import { createHash } from "node:crypto";
+import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
+import { isLoopbackHostname } from "#shared/network-address.js";
+import {
+ DEVELOPMENT_WORKFLOW_SECRET_ENV,
+ DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,
+} from "#internal/workflow/development-world-protocol.js";
+import { authJson } from "./vercel.js";
+import {
+ DEVELOPMENT_MODEL_CREDENTIAL_ROUTE,
+ DEVELOPMENT_MODEL_REJECTED_HEADER,
+ type DevelopmentModelCredential,
+ type DevelopmentModelProvider,
+} from "./development-broker-protocol.js";
+
+export function developmentModelBrokerAvailable(): boolean {
+ return (
+ isEveDevEnvironment() &&
+ Boolean(process.env.EVE_DEV_CONTROL_URL && process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV])
+ );
+}
+
+export async function readDevelopmentModelCredential(
+ provider: DevelopmentModelProvider,
+ rejectedToken?: string,
+ signal?: AbortSignal | null,
+): Promise<DevelopmentModelCredential | undefined> {
+ if (!developmentModelBrokerAvailable()) return undefined;
+ const url = new URL(DEVELOPMENT_MODEL_CREDENTIAL_ROUTE, process.env.EVE_DEV_CONTROL_URL);
+ if (!isLoopbackHostname(url.hostname) || url.protocol !== "http:" || url.username || url.password)
+ throw new Error("The local model connection is unavailable. Restart eve dev.");
+ url.searchParams.set("provider", provider);
+ const headers: Record<string, string> = {
+ [DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER]: process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]!,
+ };
+ if (rejectedToken)
+ headers[DEVELOPMENT_MODEL_REJECTED_HEADER] = createHash("sha256")
+ .update(rejectedToken)
+ .digest("hex");
+ // The host may wait for the refresh lock and complete two OAuth requests.
+ const value = await authJson(url.href, { headers, signal }, 256_000, 75_000);
+ if (
+ typeof value.token !== "string" ||
+ !value.token ||
+ !["api-key", "oauth", "oidc"].includes(String(value.kind))
+ )
+ throw new Error("The model connection is unavailable. Run /login to reconnect.");
+ return {
+ kind: value.kind as DevelopmentModelCredential["kind"],
+ token: value.token,
+ ...(typeof value.teamId === "string" && { teamId: value.teamId }),
+ ...(typeof value.teamName === "string" && { teamName: value.teamName }),
+ ...(typeof value.accountId === "string" && { accountId: value.accountId }),
+ ...(typeof value.accountLabel === "string" && { accountLabel: value.accountLabel }),
+ };
+}
diff --git a/packages/eve/src/internal/model-auth/development-broker-protocol.ts b/packages/eve/src/internal/model-auth/development-broker-protocol.ts
new file mode 100644
index 000000000..75f79d029
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/development-broker-protocol.ts
@@ -0,0 +1,13 @@
+export const DEVELOPMENT_MODEL_CREDENTIAL_ROUTE = "/eve/v1/dev/internal/model-credential";
+export const DEVELOPMENT_MODEL_REJECTED_HEADER = "x-eve-model-rejected-token-sha256";
+export type DevelopmentModelProvider = "gateway" | "openai" | "anthropic" | "chatgpt";
+
+/** Only transported over the authenticated local control plane; never persisted. */
+export interface DevelopmentModelCredential {
+ readonly kind: "api-key" | "oauth" | "oidc";
+ readonly token: string;
+ readonly teamId?: string;
+ readonly teamName?: string;
+ readonly accountId?: string;
+ readonly accountLabel?: string;
+}
diff --git a/packages/eve/src/internal/model-auth/development-broker-server.ts b/packages/eve/src/internal/model-auth/development-broker-server.ts
new file mode 100644
index 000000000..4931ae38d
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/development-broker-server.ts
@@ -0,0 +1,60 @@
+import { createHash } from "node:crypto";
+import { loadDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";
+import { timingSafeEqualStrings } from "#internal/nitro/dev-client-address.js";
+import { DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER } from "#internal/workflow/development-world-protocol.js";
+import { getDefaultCodexTokenBroker } from "#public/models/openai/chatgpt/token-broker.js";
+import { resolveModelApiKey } from "./api-key.js";
+import { resolveGatewayModelCredential } from "./gateway-credential.js";
+import {
+ DEVELOPMENT_MODEL_CREDENTIAL_ROUTE,
+ DEVELOPMENT_MODEL_REJECTED_HEADER,
+ type DevelopmentModelCredential,
+} from "./development-broker-protocol.js";
+
+export async function handleDevelopmentModelCredentialRequest(
+ request: Request,
+ input: { appRoot: string; secret: string },
+): Promise<Response | undefined> {
+ const url = new URL(request.url);
+ if (url.pathname !== DEVELOPMENT_MODEL_CREDENTIAL_ROUTE) return undefined;
+ const headers = { "cache-control": "no-store" };
+ const authorization = request.headers.get(DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER);
+ if (authorization === null || !timingSafeEqualStrings(authorization, input.secret))
+ return Response.json({ error: "Unauthorized" }, { status: 401, headers });
+ if (request.method !== "GET")
+ return Response.json({ error: "Method not allowed" }, { status: 405, headers });
+ const provider = url.searchParams.get("provider");
+ const rejected = request.headers.get(DEVELOPMENT_MODEL_REJECTED_HEADER);
+ if (
+ !["gateway", "chatgpt", "openai", "anthropic"].includes(provider ?? "") ||
+ (rejected !== null && !/^[a-f0-9]{64}$/u.test(rejected))
+ )
+ return Response.json({ error: "Invalid credential request" }, { status: 400, headers });
+ const wasRejected = (token: string) =>
+ rejected === createHash("sha256").update(token).digest("hex");
+ try {
+ await loadDevelopmentEnvironmentFiles(input.appRoot);
+ let credential: DevelopmentModelCredential;
+ if (provider === "gateway") {
+ credential = await resolveGatewayModelCredential();
+ if (wasRejected(credential.token) && credential.kind === "oauth")
+ credential = await resolveGatewayModelCredential(credential.token);
+ } else if (provider === "chatgpt") {
+ const broker = getDefaultCodexTokenBroker();
+ let token = await broker.getToken({ reason: "request" });
+ if (wasRejected(token.token)) token = await broker.getToken({ reason: "rejected" });
+ credential = { kind: "oauth", ...token };
+ } else {
+ credential = {
+ kind: "api-key",
+ token: await resolveModelApiKey(provider as "openai" | "anthropic"),
+ };
+ }
+ return Response.json(credential, { headers });
+ } catch {
+ return Response.json(
+ { error: "The model connection is unavailable. Run /login to reconnect." },
+ { status: 503, headers },
+ );
+ }
+}
diff --git a/packages/eve/src/internal/model-auth/development-broker-session.integration.test.ts b/packages/eve/src/internal/model-auth/development-broker-session.integration.test.ts
new file mode 100644
index 000000000..9987c772f
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/development-broker-session.integration.test.ts
@@ -0,0 +1,65 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { DEVELOPMENT_WORKFLOW_SECRET_ENV } from "#internal/workflow/development-world-protocol.js";
+const stored = vi.hoisted(() => new Map<string, string>());
+vi.mock("#compiled/just-secrets/index.js", () => ({
+ secrets: {
+ get: async ({ name }: { name: string }) => stored.get(name) ?? null,
+ set: async ({ name, value }: { name: string; value: string }) => {
+ stored.set(name, value);
+ },
+ },
+}));
+vi.mock("#cli/dev/environment.js", () => ({ loadDevelopmentEnvironmentFiles: async () => {} }));
+import { writeVercelSession } from "./store.js";
+import { VERCEL_MODEL_CLIENT_ID } from "./vercel.js";
+import { handleDevelopmentModelCredentialRequest } from "./development-broker-server.js";
+import { readDevelopmentModelCredential } from "./development-broker-client.js";
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ stored.clear();
+});
+it("shares the access token returned by OAuth without refreshing it in the runtime", async () => {
+ const origin = "http://localhost:4567";
+ const secret = "local-transport-secret";
+ vi.stubEnv("EVE_DEV", "1");
+ vi.stubEnv("EVE_DEV_CONTROL_URL", origin);
+ vi.stubEnv(DEVELOPMENT_WORKFLOW_SECRET_ENV, secret);
+ vi.stubEnv("EVE_MODEL_CONNECTION", "vercel");
+ vi.stubEnv("EVE_MODEL_TEAM", "team_a");
+ vi.stubEnv("EVE_MODEL_TEAM_NAME", "alice");
+ const accessToken = "large-access-token".repeat(600);
+ await writeVercelSession(
+ {
+ accessToken,
+ refreshToken: "rotating-refresh-token",
+ expiresAt: Date.now() + 3600000,
+ teamId: "team_a",
+ teamName: "alice",
+ },
+ VERCEL_MODEL_CLIENT_ID,
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: Parameters<typeof fetch>[0], init?: RequestInit) => {
+ expect(String(url).startsWith(origin)).toBe(true);
+ return (
+ (await handleDevelopmentModelCredentialRequest(new Request(url, init), {
+ appRoot: "/fixture",
+ secret,
+ })) ?? new Response(null, { status: 404 })
+ );
+ }),
+ );
+ for (let worker = 0; worker < 2; worker++) {
+ expect(await readDevelopmentModelCredential("gateway")).toMatchObject({
+ token: accessToken,
+ teamId: "team_a",
+ teamName: "alice",
+ });
+ }
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(stored.get("vercel")).not.toContain(accessToken);
+ expect(JSON.parse(stored.get("vercel")!).refreshToken).toBe("rotating-refresh-token");
+});
diff --git a/packages/eve/src/internal/model-auth/development-broker.integration.test.ts b/packages/eve/src/internal/model-auth/development-broker.integration.test.ts
new file mode 100644
index 000000000..dfe5f6714
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/development-broker.integration.test.ts
@@ -0,0 +1,237 @@
+import { createHash } from "node:crypto";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import {
+ DEVELOPMENT_WORKFLOW_SECRET_ENV,
+ DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,
+} from "#internal/workflow/development-world-protocol.js";
+import {
+ DEVELOPMENT_MODEL_CREDENTIAL_ROUTE,
+ DEVELOPMENT_MODEL_REJECTED_HEADER,
+} from "./development-broker-protocol.js";
+
+const mocks = vi.hoisted(() => ({
+ environment: vi.fn(),
+ gateway: vi.fn(),
+ key: vi.fn(),
+ chatgpt: vi.fn(),
+}));
+vi.mock("#cli/dev/environment.js", () => ({ loadDevelopmentEnvironmentFiles: mocks.environment }));
+vi.mock("./gateway-credential.js", () => ({ resolveGatewayModelCredential: mocks.gateway }));
+vi.mock("./api-key.js", () => ({ resolveModelApiKey: mocks.key }));
+vi.mock("#public/models/openai/chatgpt/token-broker.js", () => ({
+ getDefaultCodexTokenBroker: () => ({ getToken: mocks.chatgpt }),
+}));
+import { handleDevelopmentModelCredentialRequest } from "./development-broker-server.js";
+import { readDevelopmentModelCredential } from "./development-broker-client.js";
+import { createDirectModelFetch, localGatewayModel } from "./transport.js";
+import { createCodexFetch } from "#public/models/openai/chatgpt/transport.js";
+
+const origin = "http://localhost:4567";
+const secret = "fixture-transport-secret-that-is-not-a-model-token";
+const host = { appRoot: "/fixture", secret };
+const upstream = vi.fn();
+const brokerRequests: Request[] = [];
+beforeEach(() => {
+ vi.resetAllMocks();
+ brokerRequests.length = 0;
+ vi.stubEnv("EVE_DEV", "1");
+ vi.stubEnv("EVE_DEV_CONTROL_URL", origin);
+ vi.stubEnv(DEVELOPMENT_WORKFLOW_SECRET_ENV, secret);
+ mocks.gateway.mockResolvedValue({
+ kind: "oauth",
+ token: "account-token",
+ teamId: "team_a",
+ teamName: "alice",
+ });
+ mocks.key.mockResolvedValue("key-token");
+ mocks.chatgpt.mockResolvedValue({ token: "chatgpt-token", accountId: "account-a" });
+ upstream.mockResolvedValue(new Response("{}"));
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: Parameters<typeof fetch>[0], init?: RequestInit) => {
+ if (!String(url).startsWith(origin)) return upstream(url, init);
+ const request = new Request(url, init);
+ brokerRequests.push(request);
+ return (
+ (await handleDevelopmentModelCredentialRequest(request, host)) ??
+ new Response(null, { status: 404 })
+ );
+ }),
+ );
+});
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+});
+
+it("rejects unauthenticated and invalid requests before reading any credentials", async () => {
+ for (const headers of [{}, { [DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER]: "wrong" }]) {
+ const response = await handleDevelopmentModelCredentialRequest(
+ new Request(`${origin}${DEVELOPMENT_MODEL_CREDENTIAL_ROUTE}?provider=gateway`, { headers }),
+ host,
+ );
+ expect(response?.status).toBe(401);
+ expect(await response?.text()).not.toContain("account-token");
+ }
+ const headers = { [DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER]: secret };
+ for (const provider of ["", "arbitrary-secret"]) {
+ const response = await handleDevelopmentModelCredentialRequest(
+ new Request(`${origin}${DEVELOPMENT_MODEL_CREDENTIAL_ROUTE}?provider=${provider}`, {
+ headers,
+ }),
+ host,
+ );
+ expect(response?.status).toBe(400);
+ }
+ expect(mocks.environment).not.toHaveBeenCalled();
+ expect(mocks.gateway).not.toHaveBeenCalled();
+ expect(mocks.key).not.toHaveBeenCalled();
+});
+
+it("reads current host credentials and teams without restarting workers", async () => {
+ expect(await readDevelopmentModelCredential("gateway")).toMatchObject({
+ token: "account-token",
+ teamName: "alice",
+ });
+ mocks.gateway.mockResolvedValue({
+ kind: "oauth",
+ token: "account-token",
+ teamId: "team_b",
+ teamName: "bob",
+ });
+ expect(await readDevelopmentModelCredential("gateway")).toMatchObject({
+ token: "account-token",
+ teamId: "team_b",
+ teamName: "bob",
+ });
+ expect(mocks.gateway.mock.calls).toEqual([[], []]);
+ expect(mocks.environment).toHaveBeenCalledWith("/fixture");
+ expect(upstream).not.toHaveBeenCalled();
+});
+
+it("refreshes only the rejected token and never puts tokens in URLs", async () => {
+ mocks.gateway
+ .mockResolvedValueOnce({ kind: "oauth", token: "old-token" })
+ .mockResolvedValue({ kind: "oauth", token: "new-token" });
+ expect(await readDevelopmentModelCredential("gateway", "old-token")).toMatchObject({
+ token: "new-token",
+ });
+ expect(mocks.gateway.mock.calls).toEqual([[], ["old-token"]]);
+ expect(brokerRequests[0]?.headers.get(DEVELOPMENT_MODEL_REJECTED_HEADER)).toBe(
+ createHash("sha256").update("old-token").digest("hex"),
+ );
+ expect(brokerRequests[0]?.url).not.toContain("old-token");
+ await readDevelopmentModelCredential("gateway", "old-token");
+ expect(mocks.gateway).toHaveBeenCalledTimes(3);
+});
+
+it.each(["openai", "anthropic"] as const)(
+ "uses host-owned %s keys only in provider headers",
+ async (provider) => {
+ const url =
+ provider === "openai"
+ ? "https://api.openai.com/v1/responses"
+ : "https://api.anthropic.com/v1/messages";
+ const body = JSON.stringify({ model: "fixture", messages: [] });
+ await createDirectModelFetch(provider)(url, { method: "POST", body });
+ const [sentUrl, init] = upstream.mock.calls[0]!;
+ expect(sentUrl).toBe(url);
+ expect(init.body).toBe(body);
+ expect(init.headers.get(provider === "openai" ? "authorization" : "x-api-key")).toBe(
+ provider === "openai" ? "Bearer key-token" : "key-token",
+ );
+ expect(init.headers.has(DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER)).toBe(false);
+ },
+);
+
+it("shares the host ChatGPT broker for requests and rejected-token refresh", async () => {
+ mocks.chatgpt
+ .mockResolvedValueOnce({ token: "old-token", accountId: "alice" })
+ .mockResolvedValueOnce({ token: "old-token", accountId: "alice" })
+ .mockResolvedValue({ token: "new-token", accountId: "bob" });
+ upstream
+ .mockResolvedValueOnce(new Response(null, { status: 401 }))
+ .mockResolvedValueOnce(new Response("{}"));
+ await createCodexFetch()("https://api.openai.com/v1/responses", { method: "POST", body: "{}" });
+ expect(mocks.chatgpt.mock.calls).toEqual([
+ [{ reason: "request" }],
+ [{ reason: "request" }],
+ [{ reason: "rejected" }],
+ ]);
+ expect(upstream.mock.calls[1]?.[1].headers.get("authorization")).toBe("Bearer new-token");
+ expect(upstream.mock.calls[1]?.[1].headers.get("ChatGPT-Account-Id")).toBe("bob");
+});
+
+it("keeps broker failures actionable without exposing resolver errors", async () => {
+ mocks.gateway.mockRejectedValue(new Error("secret-provider-response"));
+ await expect(readDevelopmentModelCredential("gateway")).rejects.toThrow("Run /login");
+ const response = await handleDevelopmentModelCredentialRequest(brokerRequests[0]!, host);
+ expect(response?.headers.get("cache-control")).toBe("no-store");
+ expect(await response?.text()).not.toContain("secret-provider-response");
+});
+
+it("never contacts the broker in deployment or sends its secret to a remote URL", async () => {
+ vi.stubEnv("EVE_DEV", "");
+ expect(await readDevelopmentModelCredential("gateway")).toBeUndefined();
+ vi.stubEnv("EVE_DEV", "1");
+ vi.stubEnv("EVE_DEV_CONTROL_URL", "https://example.com");
+ await expect(readDevelopmentModelCredential("gateway")).rejects.toThrow("Restart eve dev");
+ expect(fetch).not.toHaveBeenCalled();
+});
+
+it("streams through the same Gateway model after switching teams and then to a key", async () => {
+ const model = localGatewayModel("openai/gpt-5.6-luna-fast");
+ if (!model || typeof model === "string") throw new Error("Expected a Gateway model");
+ expect(JSON.stringify(model)).not.toContain("account-token");
+ expect(mocks.gateway).not.toHaveBeenCalled();
+ upstream.mockImplementation(
+ async () =>
+ new Response(
+ [
+ 'data: {"type":"text-start","id":"text-1"}\n\n',
+ 'data: {"type":"text-delta","id":"text-1","delta":"Hello Alice."}\n\n',
+ 'data: {"type":"text-end","id":"text-1"}\n\n',
+ ].join(""),
+ { headers: { "content-type": "text/event-stream" } },
+ ),
+ );
+ const connections = [
+ { kind: "oauth", token: "account-token", teamId: "team_a" },
+ { kind: "oauth", token: "account-token", teamId: "team_b" },
+ { kind: "api-key", token: "gateway-key" },
+ ];
+ for (const connection of connections) {
+ mocks.gateway.mockResolvedValue(connection);
+ const result = await model.doStream({
+ prompt: [{ role: "user", content: [{ type: "text", text: "Hello" }] }],
+ });
+ let text = "";
+ for await (const event of result.stream) {
+ if (event.type === "error") throw event.error;
+ if (event.type === "text-delta") text += event.delta;
+ }
+ expect(text).toBe("Hello Alice.");
+ const [url, init] = upstream.mock.calls.at(-1)!;
+ expect(new URL(String(url)).origin).toBe("https://ai-gateway.vercel.sh");
+ expect(init.headers.get("authorization")).toBe(`Bearer ${connection.token}`);
+ expect(init.headers.get("x-vercel-ai-gateway-team")).toBe(connection.teamId ?? null);
+ expect(init.headers.has(DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER)).toBe(false);
+ expect(init.body).not.toContain(connection.token);
+ }
+});
+
+it("cancels credential lookup with the model request", async () => {
+ const controller = new AbortController();
+ controller.abort(new Error("request-cancelled"));
+ vi.mocked(fetch).mockImplementation(async (_url, init) => {
+ init?.signal?.throwIfAborted();
+ throw new Error("Expected the cancellation signal");
+ });
+ await expect(
+ createDirectModelFetch("openai")("https://api.openai.com/v1/responses", {
+ signal: controller.signal,
+ }),
+ ).rejects.toThrow("request-cancelled");
+ expect(mocks.key).not.toHaveBeenCalled();
+ expect(upstream).not.toHaveBeenCalled();
+});
diff --git a/packages/eve/src/internal/model-auth/gateway-credential.ts b/packages/eve/src/internal/model-auth/gateway-credential.ts
new file mode 100644
index 000000000..8a53f14ed
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/gateway-credential.ts
@@ -0,0 +1,33 @@
+import { getVercelOidcToken } from "#compiled/@vercel/oidc/index.js";
+import { MODEL_CONNECTION_ENV } from "#shared/model-helper.js";
+import { resolveModelApiKey } from "./api-key.js";
+import { readVercelCliConnection, refreshVercelCliConnection } from "./vercel-cli.js";
+import { resolveVercelSession } from "./vercel.js";
+import type { DevelopmentModelCredential } from "./development-broker-protocol.js";
+
+export async function resolveGatewayModelCredential(
+ rejectedToken?: string,
+): Promise<DevelopmentModelCredential> {
+ const selected = process.env[MODEL_CONNECTION_ENV];
+ if (selected === "vercel" || selected === "vercel-cli") {
+ if (selected === "vercel-cli" && rejectedToken) await refreshVercelCliConnection();
+ const session =
+ selected === "vercel"
+ ? await resolveVercelSession(rejectedToken)
+ : await readVercelCliConnection();
+ if (!session) throw new Error("Vercel CLI credentials are unavailable. Run /login.");
+ return {
+ kind: "oauth",
+ token: "accessToken" in session ? session.accessToken : session.token,
+ teamId: process.env.EVE_MODEL_TEAM ?? session.teamId,
+ teamName:
+ process.env.EVE_MODEL_TEAM_NAME ??
+ ("teamName" in session ? session.teamName : session.teamId),
+ };
+ }
+ if (selected === "ai-gateway-key")
+ return { kind: "api-key", token: await resolveModelApiKey("ai-gateway-key") };
+ if (selected !== "ai-gateway-project" && process.env.AI_GATEWAY_API_KEY?.trim())
+ return { kind: "api-key", token: process.env.AI_GATEWAY_API_KEY };
+ return { kind: "oidc", token: await getVercelOidcToken() };
+}
diff --git a/packages/eve/src/internal/model-auth/providers.integration.test.ts b/packages/eve/src/internal/model-auth/providers.integration.test.ts
new file mode 100644
index 000000000..7af8f65c6
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/providers.integration.test.ts
@@ -0,0 +1,123 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+const mocks = vi.hoisted(() => ({ read: vi.fn(), session: vi.fn() }));
+vi.mock("./store.js", () => ({
+ readModelSecret: mocks.read,
+ modelKeySecretName: (name: string) => `${name}-key`,
+}));
+vi.mock("./vercel.js", () => ({
+ resolveVercelSession: mocks.session,
+ VERCEL_TEAM_HEADER: "x-vercel-ai-gateway-team",
+}));
+import { openai } from "#public/models/openai/index.js";
+import { anthropic } from "#public/models/anthropic/index.js";
+import { localGatewayModel } from "./transport.js";
+beforeEach(() => {
+ vi.stubEnv("EVE_DEV", "1");
+ vi.stubEnv("OPENAI_API_KEY", "");
+ vi.stubEnv("ANTHROPIC_API_KEY", "");
+ mocks.read.mockResolvedValue("test-secret");
+ mocks.session.mockResolvedValue({ accessToken: "account-token", teamId: "team_original" });
+});
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ vi.resetAllMocks();
+});
+it.each([
+ ["openai", "https://api.openai.com/v1/responses"],
+ ["anthropic", "https://api.anthropic.com/v1/messages"],
+])(
+ "routes the public %s helper to its direct endpoint without exposing keys in the body",
+ async (provider, endpoint) => {
+ const fetch = vi.fn(
+ async (_url: Parameters<typeof globalThis.fetch>[0], _init?: RequestInit) =>
+ new Response("", { status: 401 }),
+ );
+ vi.stubGlobal("fetch", fetch);
+ const model = provider === "openai" ? openai() : anthropic();
+ if (typeof model === "string") throw new Error("Expected a provider model");
+ await expect(
+ model.doStream({ prompt: [{ role: "user", content: [{ type: "text", text: "Hello" }] }] }),
+ ).rejects.toThrow();
+ expect(fetch).toHaveBeenCalledOnce();
+ const [url, init] = fetch.mock.calls[0]!;
+ expect(url).toBe(endpoint);
+ const headers = new Headers(init?.headers);
+ expect(headers.get(provider === "openai" ? "authorization" : "x-api-key")).toBe(
+ provider === "openai" ? "Bearer test-secret" : "test-secret",
+ );
+ expect(init?.body).not.toContain("test-secret");
+ },
+);
+it("sends account credentials and the project team to Gateway, then refreshes once on rejection", async () => {
+ vi.stubEnv("EVE_MODEL_CONNECTION", "vercel");
+ vi.stubEnv("EVE_MODEL_TEAM", "team_project");
+ mocks.session
+ .mockResolvedValueOnce({ accessToken: "old-token", teamId: "team_original" })
+ .mockResolvedValueOnce({ accessToken: "new-token", teamId: "team_original" });
+ const requests: { url: string; headers: Headers; body: unknown }[] = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url, init) => {
+ requests.push({ url: String(url), headers: new Headers(init?.headers), body: init?.body });
+ return new Response("", { status: 401 });
+ }),
+ );
+ const model = localGatewayModel("openai/gpt-5.6-luna-fast");
+ if (!model || typeof model === "string") throw new Error("Expected Gateway model");
+ await expect(
+ model.doStream({ prompt: [{ role: "user", content: [{ type: "text", text: "Hello" }] }] }),
+ ).rejects.toThrow();
+ expect(requests).toHaveLength(2);
+ expect(new URL(requests[0]!.url).hostname).toBe("ai-gateway.vercel.sh");
+ expect(requests[0]!.headers.get("authorization")).toBe("Bearer old-token");
+ expect(requests[1]!.headers.get("authorization")).toBe("Bearer new-token");
+ expect(
+ requests.every((request) => request.headers.get("x-vercel-ai-gateway-team") === "team_project"),
+ ).toBe(true);
+ expect(JSON.stringify(requests.map((request) => request.body))).not.toContain("token");
+});
+
+it("streams the first response with a newly saved connection", async () => {
+ const item = { type: "message", id: "msg_1", role: "assistant", content: [] };
+ const events = [
+ { type: "response.output_item.added", output_index: 0, item },
+ {
+ type: "response.output_text.delta",
+ item_id: "msg_1",
+ output_index: 0,
+ delta: "Hello Alice.",
+ },
+ { type: "response.output_item.done", output_index: 0, item },
+ {
+ type: "response.completed",
+ response: {
+ id: "resp_1",
+ created_at: 0,
+ model: "gpt-5.6-luna-fast",
+ status: "completed",
+ usage: { input_tokens: 3, output_tokens: 3 },
+ },
+ },
+ ];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), {
+ headers: { "content-type": "text/event-stream" },
+ }),
+ ),
+ );
+ const model = openai();
+ if (typeof model === "string") throw new Error("Expected OpenAI model");
+ const result = await model.doStream({
+ prompt: [{ role: "user", content: [{ type: "text", text: "Hello" }] }],
+ });
+ let text = "";
+ for await (const event of result.stream) {
+ if (event.type === "error") throw event.error;
+ if (event.type === "text-delta") text += event.delta;
+ }
+ expect(text).toBe("Hello Alice.");
+});
diff --git a/packages/eve/src/internal/model-auth/store.test.ts b/packages/eve/src/internal/model-auth/store.test.ts
new file mode 100644
index 000000000..5b9ef01b7
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/store.test.ts
@@ -0,0 +1,46 @@
+import { beforeEach, expect, it, vi } from "vitest";
+const mocks = vi.hoisted(() => ({ get: vi.fn(), set: vi.fn() }));
+vi.mock("#compiled/just-secrets/index.js", () => ({ secrets: mocks }));
+import { readVercelSession, writeVercelSession, writeModelSecret } from "./store.js";
+const clientId = "client-a";
+beforeEach(() => vi.resetAllMocks());
+it("stores only refresh credentials, keeping large access tokens in memory", async () => {
+ const session = {
+ accessToken: "large-token".repeat(600),
+ refreshToken: "refresh",
+ expiresAt: Date.now() + 100000,
+ teamId: "team_a",
+ teamName: "Alice",
+ };
+ await writeVercelSession(session, clientId);
+ const stored = mocks.set.mock.calls[0]![0];
+ expect(stored.service).toBe("eve");
+ expect(stored.value).toContain(clientId);
+ expect(stored.value).not.toContain(session.accessToken);
+ expect(stored.value).not.toContain("accessToken");
+ mocks.get.mockResolvedValue(stored.value);
+ expect(await readVercelSession(clientId)).toEqual(session);
+});
+it("invalidates an access token after another process rotates the refresh credential", async () => {
+ mocks.get.mockResolvedValue(
+ JSON.stringify({ clientId, refreshToken: "rotated", teamId: "team_a", teamName: "Alice" }),
+ );
+ expect(await readVercelSession(clientId)).toMatchObject({ accessToken: "", expiresAt: 0 });
+});
+it("ignores sessions issued to a different OAuth client", async () => {
+ mocks.get.mockResolvedValue(
+ JSON.stringify({
+ clientId: "client-b",
+ refreshToken: "refresh",
+ teamId: "team_a",
+ teamName: "Alice",
+ }),
+ );
+ expect(await readVercelSession(clientId)).toBeUndefined();
+});
+it("does not leak credential values when secure storage fails", async () => {
+ mocks.set.mockRejectedValue(new Error("secret-value"));
+ await expect(writeModelSecret("openai-key", "secret-value")).rejects.toThrow(
+ "Cannot save to the OS secret store",
+ );
+});
diff --git a/packages/eve/src/internal/model-auth/store.ts b/packages/eve/src/internal/model-auth/store.ts
new file mode 100644
index 000000000..c44ff3e13
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/store.ts
@@ -0,0 +1,105 @@
+import { isModelConnection, type ModelConnectionSelection } from "#shared/model-connection.js";
+export { isModelConnection, type ModelConnectionSelection } from "#shared/model-connection.js";
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { randomUUID } from "node:crypto";
+import { secrets } from "#compiled/just-secrets/index.js";
+import { isObject } from "#shared/guards.js";
+
+export interface VercelSession {
+ accessToken: string;
+ refreshToken: string;
+ expiresAt: number;
+ teamId: string;
+ teamName: string;
+}
+
+export async function readModelSecret(name: string): Promise<string | undefined> {
+ try {
+ const value = await secrets.get({ service: "eve", name });
+ if (value !== null && Buffer.byteLength(value) > 2560) throw new Error();
+ return value ?? undefined;
+ } catch {
+ throw new Error("Cannot read the OS secret store. Unlock it and retry /login.");
+ }
+}
+
+export async function writeModelSecret(name: string, value: string): Promise<void> {
+ try {
+ if (Buffer.byteLength(value) > 2560) throw new Error();
+ await secrets.set({ service: "eve", name, value });
+ } catch {
+ throw new Error("Cannot save to the OS secret store. Unlock it and retry /login.");
+ }
+}
+
+let cachedVercelSession: VercelSession | undefined;
+let cachedVercelSessionClientId: string | undefined;
+
+export async function writeVercelSession(session: VercelSession, clientId: string): Promise<void> {
+ const { accessToken: _accessToken, expiresAt: _expiresAt, ...stored } = session;
+ await writeModelSecret("vercel", JSON.stringify({ clientId, ...stored }));
+ cachedVercelSession = session;
+ cachedVercelSessionClientId = clientId;
+}
+
+export async function readVercelSession(clientId: string): Promise<VercelSession | undefined> {
+ const raw = await readModelSecret("vercel");
+ if (raw === undefined) return undefined;
+ let value: unknown;
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ throw new Error("Saved Vercel login is invalid. Run /login to sign in again.");
+ }
+ if (!isObject(value) || value.clientId !== clientId) return undefined;
+ if (
+ typeof value.refreshToken !== "string" ||
+ typeof value.teamId !== "string" ||
+ typeof value.teamName !== "string"
+ ) {
+ throw new Error("Saved Vercel login is invalid. Run /login to sign in again.");
+ }
+ return {
+ accessToken:
+ cachedVercelSessionClientId === clientId &&
+ cachedVercelSession?.refreshToken === value.refreshToken
+ ? cachedVercelSession.accessToken
+ : "",
+ refreshToken: value.refreshToken,
+ expiresAt:
+ cachedVercelSessionClientId === clientId &&
+ cachedVercelSession?.refreshToken === value.refreshToken
+ ? cachedVercelSession.expiresAt
+ : 0,
+ teamId: value.teamId,
+ teamName: value.teamName,
+ };
+}
+
+export async function readDefaultConnection(): Promise<ModelConnectionSelection | undefined> {
+ try {
+ const value: unknown = JSON.parse(
+ await readFile(join(homedir(), ".eve", "connection.json"), "utf8"),
+ );
+ if (isObject(value) && (isModelConnection(value.selected) || value.selected === "vercel-cli"))
+ return value.selected;
+ } catch {
+ /* A missing preference does not require authentication. */
+ }
+ return undefined;
+}
+
+export async function writeDefaultConnection(selected: ModelConnectionSelection): Promise<void> {
+ const dir = join(homedir(), ".eve");
+ await mkdir(dir, { recursive: true });
+ const target = join(dir, "connection.json");
+ const temporary = `${target}.${randomUUID()}.tmp`;
+ await writeFile(temporary, `${JSON.stringify({ selected })}\n`, { mode: 0o600 });
+ await rename(temporary, target);
+}
+
+export function modelKeySecretName(provider: "openai" | "anthropic" | "ai-gateway-key"): string {
+ return provider === "ai-gateway-key" ? provider : `${provider}-key`;
+}
diff --git a/packages/eve/src/internal/model-auth/transport.test.ts b/packages/eve/src/internal/model-auth/transport.test.ts
new file mode 100644
index 000000000..3d31ef11f
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/transport.test.ts
@@ -0,0 +1,77 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+const mocks = vi.hoisted(() => ({ read: vi.fn(), session: vi.fn(), cli: vi.fn(), fetch: vi.fn() }));
+vi.mock("./store.js", () => ({
+ readModelSecret: mocks.read,
+ modelKeySecretName: (name: string) => (name === "ai-gateway-key" ? name : `${name}-key`),
+}));
+vi.mock("./vercel.js", () => ({
+ VERCEL_TEAM_HEADER: "x-vercel-ai-gateway-team",
+ resolveVercelSession: mocks.session,
+}));
+vi.mock("./vercel-cli.js", () => ({ readVercelCliConnection: mocks.cli }));
+import { createDirectModelFetch, localGatewayModel, resolveModelApiKey } from "./transport.js";
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.stubGlobal("fetch", mocks.fetch.mockResolvedValue(new Response("{}")));
+ vi.stubEnv("EVE_DEV", "1");
+ vi.stubEnv("EVE_MODEL_KEY_SOURCE", undefined);
+ vi.stubEnv("OPENAI_API_KEY", "");
+ vi.stubEnv("ANTHROPIC_API_KEY", "");
+ mocks.read.mockResolvedValue("stored-secret");
+});
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+});
+describe("model credentials", () => {
+ it.each(["openai", "anthropic"] as const)(
+ "injects %s credentials only into request headers",
+ async (provider) => {
+ const body = JSON.stringify({ model: "example", messages: [] });
+ await createDirectModelFetch(provider)(
+ provider === "openai"
+ ? "https://api.openai.com/v1/responses"
+ : "https://api.anthropic.com/v1/messages",
+ { method: "POST", body },
+ );
+ const [, request] = mocks.fetch.mock.calls[0]!;
+ expect(request.body).toBe(body);
+ expect(request.headers.get(provider === "openai" ? "authorization" : "x-api-key")).toBe(
+ provider === "openai" ? "Bearer stored-secret" : "stored-secret",
+ );
+ expect(body).not.toContain("stored-secret");
+ },
+ );
+ it("uses explicit server keys without reading the machine secret store", async () => {
+ vi.stubEnv("EVE_DEV", "");
+ vi.stubEnv("OPENAI_API_KEY", "server-key");
+ expect(await resolveModelApiKey("openai")).toBe("server-key");
+ expect(mocks.read).not.toHaveBeenCalled();
+ });
+ it("never falls back to machine credentials in production", async () => {
+ vi.stubEnv("EVE_DEV", "");
+ await expect(resolveModelApiKey("anthropic")).rejects.toThrow("server environment");
+ expect(mocks.read).not.toHaveBeenCalled();
+ vi.stubEnv("EVE_MODEL_CONNECTION", "vercel");
+ expect(localGatewayModel("openai/gpt-5.6-luna-fast")).toBeUndefined();
+ });
+ it("does not place a credential in a model's serializable identity", () => {
+ vi.stubEnv("EVE_MODEL_CONNECTION", "vercel");
+ const model = localGatewayModel("openai/gpt-5.6-luna-fast");
+ expect(JSON.stringify(model)).not.toContain("stored-secret");
+ expect(mocks.session).not.toHaveBeenCalled();
+ });
+});
+
+it("honors a project key chosen in /login over a different shell key", async () => {
+ vi.stubEnv("EVE_MODEL_CONNECTION", "openai");
+ vi.stubEnv("EVE_MODEL_KEY_SOURCE", "secret");
+ vi.stubEnv("OPENAI_API_KEY", "different-shell-key");
+ expect(await resolveModelApiKey("openai")).toBe("stored-secret");
+});
+it("does not replace a missing environment connection with a stored key", async () => {
+ vi.stubEnv("EVE_MODEL_CONNECTION", "openai");
+ vi.stubEnv("EVE_MODEL_KEY_SOURCE", "environment");
+ await expect(resolveModelApiKey("openai")).rejects.toThrow("OPENAI_API_KEY");
+ expect(mocks.read).not.toHaveBeenCalled();
+});
diff --git a/packages/eve/src/internal/model-auth/transport.ts b/packages/eve/src/internal/model-auth/transport.ts
new file mode 100644
index 000000000..72c604b2a
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/transport.ts
@@ -0,0 +1,66 @@
+import { createGateway, type LanguageModel } from "ai";
+import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
+import { resolveModelApiKey } from "./api-key.js";
+import {
+ developmentModelBrokerAvailable,
+ readDevelopmentModelCredential,
+} from "./development-broker-client.js";
+import { resolveGatewayModelCredential } from "./gateway-credential.js";
+import { VERCEL_TEAM_HEADER } from "./vercel.js";
+import { MODEL_CONNECTION_ENV } from "#shared/model-helper.js";
+
+export { MODEL_CONNECTION_ENV } from "#shared/model-helper.js";
+export { resolveModelApiKey } from "./api-key.js";
+
+export function createDirectModelFetch(provider: "openai" | "anthropic"): typeof fetch {
+ return async (url, init) => {
+ const headers = new Headers(init?.headers);
+ const credential = await readDevelopmentModelCredential(provider, undefined, init?.signal);
+ const key = credential?.token ?? (await resolveModelApiKey(provider));
+ headers.set(
+ provider === "openai" ? "authorization" : "x-api-key",
+ provider === "openai" ? `Bearer ${key}` : key,
+ );
+ return fetch(url, { ...init, headers });
+ };
+}
+
+/** Resolve the connection for every request, including models constructed before /login. */
+export function localGatewayModel(id: string): LanguageModel | undefined {
+ if (!isEveDevEnvironment()) return undefined;
+ const selected = process.env[MODEL_CONNECTION_ENV];
+ if (
+ !developmentModelBrokerAvailable() &&
+ selected !== "vercel" &&
+ selected !== "vercel-cli" &&
+ selected !== "ai-gateway-key" &&
+ selected !== "ai-gateway-project"
+ )
+ return undefined;
+ const resolve = async (rejectedToken?: string, signal?: AbortSignal | null) =>
+ (await readDevelopmentModelCredential("gateway", rejectedToken, signal)) ??
+ (await resolveGatewayModelCredential(rejectedToken));
+ return createGateway({
+ apiKey: "eve-local-credential",
+ fetch: async (url, init) => {
+ const headers = new Headers(init?.headers);
+ const authenticate = (credential: Awaited<ReturnType<typeof resolve>>) => {
+ headers.set("authorization", `Bearer ${credential.token}`);
+ headers.delete(VERCEL_TEAM_HEADER);
+ if (credential.teamId) headers.set(VERCEL_TEAM_HEADER, credential.teamId);
+ };
+ const credential = await resolve(undefined, init?.signal);
+ authenticate(credential);
+ const response = await fetch(url, { ...init, headers });
+ if (
+ response.status !== 401 ||
+ credential.kind !== "oauth" ||
+ (init?.body !== undefined && init.body !== null && typeof init.body !== "string")
+ )
+ return response;
+ await response.body?.cancel();
+ authenticate(await resolve(credential.token, init?.signal));
+ return fetch(url, { ...init, headers });
+ },
+ })(id);
+}
diff --git a/packages/eve/src/internal/model-auth/vercel-cli.test.ts b/packages/eve/src/internal/model-auth/vercel-cli.test.ts
new file mode 100644
index 000000000..df8f23468
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/vercel-cli.test.ts
@@ -0,0 +1,73 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { join } from "node:path";
+const mocks = vi.hoisted(() => ({
+ read: vi.fn(),
+ realpath: vi.fn(),
+ password: vi.fn(),
+ entry: vi.fn(),
+}));
+vi.mock("node:fs/promises", () => ({ readFile: mocks.read, realpath: mocks.realpath }));
+vi.mock("node:os", () => ({ homedir: () => "/test/home" }));
+vi.mock("node:module", () => ({
+ createRequire: () => () => ({
+ Entry: class {
+ constructor(service: string, name: string) {
+ mocks.entry(service, name);
+ }
+ getPassword() {
+ return mocks.password();
+ }
+ },
+ }),
+}));
+import { readVercelCliConnection } from "./vercel-cli.js";
+const base =
+ process.platform === "darwin"
+ ? "/test/home/Library/Application Support"
+ : "/test/home/.local/share";
+const configPath = join(base, "com.vercel.cli", "config.json");
+const authPath = join(base, "com.vercel.cli", "auth.json");
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.stubEnv("VERCEL_TOKEN", "");
+ vi.stubEnv("VERCEL_TOKEN_STORAGE", undefined);
+ vi.stubEnv("XDG_DATA_HOME", undefined);
+ vi.stubEnv("PATH", "/cli/bin");
+ mocks.realpath.mockResolvedValue("/cli/node_modules/vercel/dist/index.js");
+});
+afterEach(() => vi.unstubAllEnvs());
+function files(storage: string) {
+ mocks.read.mockImplementation(async (path: string) => {
+ if (path === configPath) return JSON.stringify({ currentTeam: "team_a", credStorage: storage });
+ if (path === authPath)
+ return JSON.stringify({ token: "file-token", refreshToken: "never-copy-me" });
+ throw new Error("ENOENT");
+ });
+}
+it("reads file credentials and returns no refresh token", async () => {
+ files("file");
+ expect(await readVercelCliConnection()).toEqual({ token: "file-token", teamId: "team_a" });
+ expect(mocks.entry).not.toHaveBeenCalled();
+});
+it.each(["auto", "keyring"])("reads raw CLI keyring entries in %s mode", async (storage) => {
+ files(storage);
+ mocks.password.mockReturnValue(
+ JSON.stringify({ token: "keyring-token", refreshToken: "never-copy-me" }),
+ );
+ expect(await readVercelCliConnection()).toEqual({ token: "keyring-token", teamId: "team_a" });
+ expect(mocks.entry).toHaveBeenCalledWith(
+ "com.vercel.vercel-cli",
+ expect.stringMatching(/^cli:[a-f0-9]{16}$/),
+ );
+});
+it("falls back to file credentials when automatic keyring access is unavailable", async () => {
+ files("auto");
+ mocks.password.mockImplementation(() => {
+ throw new Error("Keyring unavailable");
+ });
+ expect(await readVercelCliConnection()).toEqual({ token: "file-token", teamId: "team_a" });
+});
+it("does not guess a team when the CLI has no selection", async () => {
+ mocks.read.mockResolvedValue("{}");
+ expect(await readVercelCliConnection()).toBeUndefined();
+});
diff --git a/packages/eve/src/internal/model-auth/vercel-cli.ts b/packages/eve/src/internal/model-auth/vercel-cli.ts
new file mode 100644
index 000000000..9670d572d
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/vercel-cli.ts
@@ -0,0 +1,108 @@
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import { createHash } from "node:crypto";
+import { readFile, realpath } from "node:fs/promises";
+import { homedir } from "node:os";
+import { delimiter, join } from "node:path";
+import { createRequire } from "node:module";
+import { isObject } from "#shared/guards.js";
+
+async function readObject(path: string): Promise<Record<string, unknown> | undefined> {
+ try {
+ const raw = await readFile(path, "utf8");
+ if (Buffer.byteLength(raw) > 65_536) return undefined;
+ const parsed: unknown = JSON.parse(raw);
+ return isObject(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+async function readCliConfiguration(): Promise<
+ { directory: string; config: Record<string, unknown>; teamId: string } | undefined
+> {
+ const home = homedir();
+ const base =
+ process.platform === "darwin"
+ ? join(home, "Library", "Application Support")
+ : process.platform === "win32"
+ ? (process.env.APPDATA ?? join(home, "AppData", "Roaming"))
+ : (process.env.XDG_DATA_HOME ?? join(home, ".local", "share"));
+ for (const dir of [join(base, "com.vercel.cli"), join(home, ".now"), join(base, "now")]) {
+ const config = await readObject(join(dir, "config.json"));
+ if (config === undefined) continue;
+ const teamId = typeof config.currentTeam === "string" ? config.currentTeam : undefined;
+ if (!teamId) return undefined;
+ return { directory: dir, config, teamId };
+ }
+ return undefined;
+}
+
+export async function readVercelCliTeam(): Promise<string | undefined> {
+ return (await readCliConfiguration())?.teamId;
+}
+
+/** Read-only: Vercel CLI retains ownership of its credentials and token rotation. */
+export async function readVercelCliConnection(): Promise<
+ { token: string; teamId: string } | undefined
+> {
+ const configuration = await readCliConfiguration();
+ if (!configuration) return undefined;
+ const { directory: dir, config, teamId } = configuration;
+ if (process.env.VERCEL_TOKEN) return { token: process.env.VERCEL_TOKEN, teamId };
+ const storage = process.env.VERCEL_TOKEN_STORAGE ?? config.credStorage ?? "file";
+ const path = join(dir, "auth.json");
+ let auth: Record<string, unknown> | undefined;
+ if (storage === "file") auth = await readObject(path);
+ if (!auth && (storage === "keyring" || storage === "auto")) {
+ const name = `cli:${createHash("sha256").update(path).digest("hex").slice(0, 16)}`;
+ try {
+ const raw = await readCliKeyring(name);
+ const value: unknown = raw && raw.length <= 65_536 ? JSON.parse(raw) : undefined;
+ if (isObject(value)) auth = value;
+ } catch {
+ if (storage === "keyring") return undefined;
+ }
+ if (!auth && storage === "auto") auth = await readObject(path);
+ }
+ if (typeof auth?.token !== "string" || !auth.token) return undefined;
+ return { token: auth.token, teamId };
+}
+
+export async function refreshVercelCliConnection(): Promise<void> {
+ try {
+ await promisify(execFile)("vercel", ["whoami"], {
+ timeout: 15_000,
+ maxBuffer: 65_536,
+ windowsHide: true,
+ });
+ } catch {
+ throw new Error("Vercel CLI access expired. Run /login to reconnect.");
+ }
+}
+
+// Use the CLI's own native adapter: just-secrets intentionally uses a different key encoding.
+async function readCliKeyring(name: string): Promise<string | undefined> {
+ for (const directory of (process.env.PATH ?? "").split(delimiter)) {
+ try {
+ const executable = await realpath(
+ join(directory, process.platform === "win32" ? "vercel.cmd" : "vercel"),
+ );
+ let require = createRequire(executable);
+ if (process.platform === "win32")
+ require = createRequire(require.resolve("vercel/package.json"));
+ try {
+ require = createRequire(require.resolve("@vercel/cli-auth/package.json"));
+ } catch {
+ // Older CLI installs may expose the native adapter directly.
+ }
+ const keyring = require("@napi-rs/keyring") as {
+ Entry: new (service: string, account: string) => { getPassword(): string | null };
+ };
+ return new keyring.Entry("com.vercel.vercel-cli", name).getPassword() ?? undefined;
+ } catch {
+ // Other PATH entries may contain the installed CLI and its native adapter.
+ }
+ }
+ return undefined;
+}
diff --git a/packages/eve/src/internal/model-auth/vercel-team.test.ts b/packages/eve/src/internal/model-auth/vercel-team.test.ts
new file mode 100644
index 000000000..fabfba5a2
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/vercel-team.test.ts
@@ -0,0 +1,54 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { resolveModelTeamSlug } from "./vercel-team.js";
+
+const mocks = vi.hoisted(() => ({ cli: vi.fn(), session: vi.fn(), json: vi.fn() }));
+vi.mock("./vercel-cli.js", () => ({ readVercelCliConnection: mocks.cli }));
+vi.mock("./vercel.js", () => ({
+ resolveVercelSession: mocks.session,
+ vercelApiJson: mocks.json,
+}));
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.stubEnv("EVE_MODEL_TEAM", undefined);
+ mocks.cli.mockResolvedValue({ token: "cli-token", teamId: "team_cli" });
+ mocks.session.mockResolvedValue({ accessToken: "oauth-token", teamId: "team_oauth" });
+ mocks.json.mockResolvedValue({ id: "team_cli", name: "Acme Incorporated", slug: "acme" });
+});
+afterEach(() => vi.unstubAllEnvs());
+
+describe("resolveModelTeamSlug", () => {
+ it.each(["vercel", "vercel-cli"])(
+ "resolves the selected project team for %s",
+ async (selected) => {
+ vi.stubEnv("EVE_MODEL_CONNECTION", selected);
+ vi.stubEnv("EVE_MODEL_TEAM", "team_override");
+ const signal = new AbortController().signal;
+ expect(await resolveModelTeamSlug(signal)).toBe("acme");
+ expect(mocks.json).toHaveBeenCalledWith("https://api.vercel.com/v2/teams/team_override", {
+ headers: { authorization: `Bearer ${selected === "vercel" ? "oauth-token" : "cli-token"}` },
+ signal,
+ });
+ },
+ );
+ it("uses the CLI's current team when no project team is selected", async () => {
+ vi.stubEnv("EVE_MODEL_CONNECTION", "vercel-cli");
+ await resolveModelTeamSlug();
+ expect(mocks.json).toHaveBeenCalledWith(
+ "https://api.vercel.com/v2/teams/team_cli",
+ expect.anything(),
+ );
+ });
+ it("does not access Vercel credentials for API key connections", async () => {
+ vi.stubEnv("EVE_MODEL_CONNECTION", "openai");
+ expect(await resolveModelTeamSlug()).toBeUndefined();
+ expect(mocks.cli).not.toHaveBeenCalled();
+ expect(mocks.session).not.toHaveBeenCalled();
+ expect(mocks.json).not.toHaveBeenCalled();
+ });
+ it("does not substitute a display name or ID for a missing slug", async () => {
+ vi.stubEnv("EVE_MODEL_CONNECTION", "vercel-cli");
+ mocks.json.mockResolvedValue({ id: "team_cli", name: "Acme" });
+ expect(await resolveModelTeamSlug()).toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/internal/model-auth/vercel-team.ts b/packages/eve/src/internal/model-auth/vercel-team.ts
new file mode 100644
index 000000000..a5be90f9a
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/vercel-team.ts
@@ -0,0 +1,31 @@
+import { resolveVercelSession, vercelApiJson } from "./vercel.js";
+import { readVercelCliConnection } from "./vercel-cli.js";
+import { readVercelResourceSlug } from "#internal/vercel/api-resource.js";
+
+let knownTeam: { teamId: string; slug: string } | undefined;
+
+export function rememberModelTeamSlug(teamId: string, slug: string): void {
+ knownTeam = { teamId, slug };
+}
+
+/** Resolves display metadata without changing credentials or linking a project. */
+export async function resolveModelTeamSlug(signal?: AbortSignal): Promise<string | undefined> {
+ const selected = process.env.EVE_MODEL_CONNECTION;
+ if (selected !== "vercel" && selected !== "vercel-cli") return undefined;
+ const selectedTeam = process.env.EVE_MODEL_TEAM;
+ if (selectedTeam && knownTeam?.teamId === selectedTeam) return knownTeam.slug;
+ const credential =
+ selected === "vercel" ? await resolveVercelSession() : await readVercelCliConnection();
+ if (!credential) return undefined;
+ const teamId = process.env.EVE_MODEL_TEAM ?? credential.teamId;
+ if (knownTeam?.teamId === teamId) return knownTeam.slug;
+ const token = "accessToken" in credential ? credential.accessToken : credential.token;
+ const team = await vercelApiJson(
+ `https://api.vercel.com/v2/teams/${encodeURIComponent(teamId)}`,
+ {
+ headers: { authorization: `Bearer ${token}` },
+ signal,
+ },
+ );
+ return readVercelResourceSlug(team);
+}
diff --git a/packages/eve/src/internal/model-auth/vercel.test.ts b/packages/eve/src/internal/model-auth/vercel.test.ts
new file mode 100644
index 000000000..d555a64ad
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/vercel.test.ts
@@ -0,0 +1,91 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+const mocks = vi.hoisted(() => ({
+ read: vi.fn(),
+ write: vi.fn(),
+ mkdir: vi.fn(),
+ rm: vi.fn(),
+ fetch: vi.fn(),
+}));
+vi.mock("./store.js", () => ({ readVercelSession: mocks.read, writeVercelSession: mocks.write }));
+vi.mock("node:fs/promises", () => ({ mkdir: mocks.mkdir, rm: mocks.rm, stat: vi.fn() }));
+import {
+ authJson,
+ vercelApiJson,
+ vercelOAuthEndpoints,
+ resolveVercelSession,
+ VERCEL_MODEL_CLIENT_ID,
+} from "./vercel.js";
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.stubGlobal("fetch", mocks.fetch);
+ mocks.fetch.mockResolvedValueOnce(
+ Response.json({
+ device_authorization_endpoint: "https://api.vercel.com/login/oauth/device-authorization",
+ token_endpoint: "https://api.vercel.com/login/oauth/token",
+ }),
+ );
+});
+it("refreshes expired OAuth access and saves rotation before releasing the lock", async () => {
+ mocks.read.mockResolvedValue({
+ accessToken: "old",
+ refreshToken: "refresh",
+ expiresAt: 0,
+ teamId: "team_a",
+ teamName: "Alice",
+ });
+ mocks.fetch.mockResolvedValue(
+ Response.json({ access_token: "new", refresh_token: "rotated", expires_in: 3600 }),
+ );
+ expect(await resolveVercelSession()).toMatchObject({
+ accessToken: "new",
+ refreshToken: "rotated",
+ teamId: "team_a",
+ });
+ const [url, init] = mocks.fetch.mock.calls[1]!;
+ expect(url).toBe("https://api.vercel.com/login/oauth/token");
+ expect(init.body.get("refresh_token")).toBe("refresh");
+ expect(mocks.write).toHaveBeenCalledOnce();
+ expect(mocks.write).toHaveBeenCalledWith(expect.anything(), VERCEL_MODEL_CLIENT_ID);
+ expect(mocks.rm.mock.invocationCallOrder[0]).toBeGreaterThan(
+ mocks.write.mock.invocationCallOrder[0]!,
+ );
+});
+it("reuses a fresh token without refreshing or writing credentials", async () => {
+ mocks.read.mockResolvedValue({ accessToken: "fresh", expiresAt: Date.now() + 3600000 });
+ expect(await resolveVercelSession()).toMatchObject({ accessToken: "fresh" });
+ expect(mocks.fetch).not.toHaveBeenCalled();
+});
+it("releases the lock after a failed refresh without replacing the session", async () => {
+ mocks.read.mockResolvedValue({ accessToken: "old", refreshToken: "refresh", expiresAt: 0 });
+ mocks.fetch.mockResolvedValue(Response.json({ error: "invalid_grant" }, { status: 400 }));
+ await expect(resolveVercelSession()).rejects.toThrow("Retry /login");
+ expect(mocks.write).not.toHaveBeenCalled();
+ expect(mocks.rm).toHaveBeenCalledOnce();
+});
+
+afterEach(() => vi.unstubAllGlobals());
+
+it("uses the published OAuth endpoints", async () => {
+ expect(await vercelOAuthEndpoints()).toEqual({
+ device: "https://api.vercel.com/login/oauth/device-authorization",
+ token: "https://api.vercel.com/login/oauth/token",
+ });
+});
+it("rejects discovery endpoints outside Vercel", async () => {
+ mocks.fetch.mockReset().mockResolvedValue(
+ Response.json({
+ device_authorization_endpoint: "https://untrusted.example/device",
+ token_endpoint: "https://api.vercel.com/login/oauth/token",
+ }),
+ );
+ await expect(vercelOAuthEndpoints()).rejects.toThrow("unexpected OAuth endpoint");
+});
+it("allows bounded model catalogs larger than OAuth responses", async () => {
+ const catalog = { models: [{ slug: "test", instructions: "x".repeat(300_000) }] };
+ mocks.fetch.mockReset().mockImplementation(async () => Response.json(catalog));
+ await expect(authJson("https://chatgpt.com/models", {}, 8 * 1024 * 1024)).resolves.toEqual(
+ catalog,
+ );
+ await expect(authJson("https://vercel.com/token")).rejects.toThrow("too large");
+ await expect(vercelApiJson("https://api.vercel.com/v2/teams")).resolves.toEqual(catalog);
+});
diff --git a/packages/eve/src/internal/model-auth/vercel.ts b/packages/eve/src/internal/model-auth/vercel.ts
new file mode 100644
index 000000000..2207971dd
--- /dev/null
+++ b/packages/eve/src/internal/model-auth/vercel.ts
@@ -0,0 +1,172 @@
+import { mkdir, rm, stat } from "node:fs/promises";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
+import { isObject, isErrnoCode } from "#shared/guards.js";
+import { readVercelSession, writeVercelSession, type VercelSession } from "./store.js";
+
+export const VERCEL_MODEL_CLIENT_ID = "cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp";
+export const VERCEL_OAUTH_ISSUER = "https://vercel.com";
+export const VERCEL_TEAM_HEADER = "x-vercel-ai-gateway-team";
+const VERCEL_API_MAX_BYTES = 8 * 1024 * 1024;
+
+export async function authJson(
+ url: string,
+ init: RequestInit = {},
+ maxBytes = 256_000,
+ timeoutMs = 15_000,
+): Promise<Record<string, unknown>> {
+ const timeout = AbortSignal.timeout(timeoutMs);
+ const response = await fetch(url, {
+ ...init,
+ redirect: "error",
+ signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout,
+ });
+ const reader = response.body?.getReader();
+ let raw = "";
+ const decoder = new TextDecoder();
+ if (reader) {
+ try {
+ let bytes = 0;
+ while (true) {
+ const result = await reader.read();
+ if (result.done) break;
+ bytes += result.value.byteLength;
+ if (bytes > maxBytes)
+ throw new Error("Authentication response was too large. Retry /login.");
+ raw += decoder.decode(result.value, { stream: true });
+ }
+ raw += decoder.decode();
+ } finally {
+ await reader.cancel();
+ }
+ }
+ let value: unknown;
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ throw new Error("The provider returned an invalid authentication response. Retry /login.");
+ }
+ if (!isObject(value))
+ throw new Error("The provider returned an invalid authentication response. Retry /login.");
+ if (!response.ok && typeof value.error !== "string")
+ throw new Error(`Authentication failed (${response.status}). Retry /login.`);
+ return value;
+}
+
+export function vercelApiJson(
+ url: string,
+ init: RequestInit = {},
+): Promise<Record<string, unknown>> {
+ return authJson(url, init, VERCEL_API_MAX_BYTES);
+}
+
+export async function vercelOAuthEndpoints(signal?: AbortSignal): Promise<{
+ device: string;
+ token: string;
+}> {
+ const metadata = await authJson(`${VERCEL_OAUTH_ISSUER}/.well-known/openid-configuration`, {
+ signal,
+ });
+ const endpoint = (value: unknown): string => {
+ const url = typeof value === "string" ? URL.parse(value) : null;
+ if (
+ !url ||
+ ![VERCEL_OAUTH_ISSUER, "https://api.vercel.com"].includes(url.origin) ||
+ url.username ||
+ url.password
+ )
+ throw new Error("Vercel returned an unexpected OAuth endpoint. Retry /login.");
+ return url.href;
+ };
+ return {
+ device: endpoint(metadata.device_authorization_endpoint),
+ token: endpoint(metadata.token_endpoint),
+ };
+}
+
+export function sessionFromToken(
+ value: Record<string, unknown>,
+ previous?: VercelSession,
+): VercelSession {
+ if (typeof value.error === "string") throw new Error("Vercel login expired. Retry /login.");
+ if (
+ typeof value.access_token !== "string" ||
+ typeof value.expires_in !== "number" ||
+ !Number.isFinite(value.expires_in) ||
+ value.expires_in <= 0
+ )
+ throw new Error("Vercel did not return a usable token. Retry /login.");
+ const refreshToken =
+ typeof value.refresh_token === "string" ? value.refresh_token : previous?.refreshToken;
+ if (!refreshToken) throw new Error("Vercel did not return a refresh token. Retry /login.");
+ return {
+ accessToken: value.access_token,
+ refreshToken,
+ expiresAt: Date.now() + value.expires_in * 1000,
+ teamId: previous?.teamId ?? "",
+ teamName: previous?.teamName ?? "",
+ };
+}
+
+export async function resolveVercelSession(rejectedToken?: string): Promise<VercelSession> {
+ let session = await readVercelSession(VERCEL_MODEL_CLIENT_ID);
+ if (!session) throw new Error("Sign in to Vercel with /login.");
+ if (session.expiresAt > Date.now() + 60_000 && session.accessToken !== rejectedToken)
+ return session;
+ const dir = join(homedir(), ".eve", "auth");
+ await mkdir(dir, { recursive: true, mode: 0o700 });
+ const lock = join(dir, "vercel-refresh.lock");
+ const deadline = Date.now() + 35_000;
+ while (true) {
+ try {
+ await mkdir(lock);
+ break;
+ } catch (error) {
+ if (!isErrnoCode(error, "EEXIST")) throw error;
+ const info = await stat(lock).catch(() => undefined);
+ if (info && Date.now() - info.mtimeMs > 300_000) {
+ await rm(lock, { recursive: true, force: true });
+ continue;
+ }
+ if (Date.now() > deadline)
+ throw new Error("Vercel credentials are busy. Close other eve sessions and retry /login.");
+ await delay(100);
+ }
+ }
+ try {
+ session = await readVercelSession(VERCEL_MODEL_CLIENT_ID);
+ if (!session) throw new Error("Sign in to Vercel with /login.");
+ if (session.expiresAt > Date.now() + 60_000 && session.accessToken !== rejectedToken)
+ return session;
+ const endpoints = await vercelOAuthEndpoints();
+ const token = await authJson(endpoints.token, {
+ method: "POST",
+ body: new URLSearchParams({
+ client_id: VERCEL_MODEL_CLIENT_ID,
+ grant_type: "refresh_token",
+ refresh_token: session.refreshToken,
+ }),
+ });
+ session = sessionFromToken(token, session);
+ await writeVercelSession(session, VERCEL_MODEL_CLIENT_ID);
+ return session;
+ } finally {
+ await rm(lock, { recursive: true, force: true });
+ }
+}
+
+export async function validateVercelAccess(
+ token: string,
+ teamId: string,
+ signal?: AbortSignal,
+): Promise<void> {
+ const value = await authJson(
+ `https://ai-gateway.vercel.sh/coding-agent/v1/credits?teamId=${encodeURIComponent(teamId)}`,
+ { headers: { authorization: `Bearer ${token}` }, signal },
+ );
+ if (value.error)
+ throw new Error(
+ "Vercel could not authorize AI Gateway for this team. Choose another team or connection in /login.",
+ );
+}
diff --git a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts
index 562dcf7e4..c7730eb74 100644
--- a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts
@@ -226,7 +226,7 @@ describe("startAuthoredSourceWatcher", () => {
}
});
- it("watches root config, provider selection, env, workspace lockfiles, and tsconfig extends", async () => {
+ it("watches authored config and environment files but excludes connection metadata", async () => {
const workspaceRoot = await mkdtemp(join(tmpdir(), "eve-dev-watch-root-"));
const appRoot = join(workspaceRoot, "apps", "watch-agent");
temporaryDirectories.push(workspaceRoot);
@@ -248,7 +248,10 @@ describe("startAuthoredSourceWatcher", () => {
const paths = getInitialWatchPaths();
expect(paths).toContain(join(appRoot, "package.json"));
expect(paths).toContain(join(appRoot, ".env.local"));
- expect(paths).toContain(join(appRoot, ".eve", "provider.json"));
+ expect(paths).not.toContain(join(appRoot, ".eve", "provider.json"));
+ expect(
+ mockedWatcher.watch.mock.calls[0]?.[1]?.ignored?.(join(appRoot, ".eve", "provider.json")),
+ ).toBe(true);
expect(paths).toContain(join(workspaceRoot, "pnpm-lock.yaml"));
expect(paths).toContain(join(workspaceRoot, "tsconfig.base.json"));
} finally {
diff --git a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.ts b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.ts
index 1afc5fec1..4e6d15546 100644
--- a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.ts
+++ b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.ts
@@ -8,7 +8,6 @@ import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/ty
import type { DevelopmentWorkspaceExtension } from "#internal/nitro/host/dev-workspace-extensions.js";
import type { DevelopmentAuthoredRebuildCoordinator } from "#internal/nitro/host/dev-authored-rebuild-coordinator.js";
import { getDevelopmentEnvironmentFilePaths } from "#cli/dev/environment.js";
-import { providerSettingsPath } from "#setup/provider-settings.js";
import {
AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,
STRUCTURAL_RELOAD_LOG_LINE,
@@ -77,8 +76,7 @@ export async function startAuthoredSourceWatcher(input: {
},
followSymlinks: false,
ignoreInitial: true,
- ignored: (path) =>
- shouldIgnoreWatcherPath(path, currentHost.appRoot, currentHost.workspaceExtensions),
+ ignored: (path) => shouldIgnoreWatcherPath(path, currentHost.workspaceExtensions),
});
const watcherReady = waitForWatcherReady(watcher);
@@ -219,7 +217,6 @@ async function resolveAuthoredWatchPaths(
join(host.appRoot, "jsconfig.json"),
join(host.appRoot, "tsconfig.json"),
join(host.appRoot, TS_CONFIG_GLOB_NAME),
- providerSettingsPath(host.appRoot),
]);
const tsconfigPaths = await resolveTsConfigWatchPaths(host.appRoot);
const sourceSnapshotWatchPaths = await resolveDevelopmentSourceSnapshotWatchPaths(host.appRoot);
@@ -332,15 +329,13 @@ async function resolveTsConfigWatchPaths(appRoot: string): Promise<string[]> {
function shouldIgnoreWatcherPath(
path: string,
- appRoot: string,
workspaceExtensions: readonly DevelopmentWorkspaceExtension[],
): boolean {
const normalizedPath = normalize(path);
const pathParts = normalizedPath.split(sep).filter(Boolean);
- const isProviderSettings = normalizedPath === normalize(providerSettingsPath(appRoot));
return (
- (!isProviderSettings && pathParts.some((part) => WATCHER_IGNORED_DIRECTORY_NAMES.has(part))) ||
+ pathParts.some((part) => WATCHER_IGNORED_DIRECTORY_NAMES.has(part)) ||
workspaceExtensions.some((extension) => isPathInsideOrEqual(path, extension.config.outDir))
);
}
diff --git a/packages/eve/src/internal/nitro/host/dev-environment-watcher.integration.test.ts b/packages/eve/src/internal/nitro/host/dev-environment-watcher.integration.test.ts
index 50c26b624..a204e9377 100644
--- a/packages/eve/src/internal/nitro/host/dev-environment-watcher.integration.test.ts
+++ b/packages/eve/src/internal/nitro/host/dev-environment-watcher.integration.test.ts
@@ -43,33 +43,33 @@ describe("development environment reload transactions", () => {
expect(process.env.EVE_WATCH_ENV_SHELL).toBe("from-parent");
});
- it("honors the persisted Gateway credential selection over available keys", async () => {
+ it("loads connection settings separately from explicit environment keys", async () => {
const appRoot = await createEnvironmentApp();
await writeFile(join(appRoot, ".env.local"), "AI_GATEWAY_API_KEY=from-file\n");
await mkdir(join(appRoot, ".eve"));
await writeFile(join(appRoot, ".eve", "provider.json"), '{"selected":"ai-gateway-project"}\n');
await loadDevelopmentEnvironmentFiles(appRoot);
- expect(process.env.AI_GATEWAY_API_KEY).toBeUndefined();
+ expect(process.env.AI_GATEWAY_API_KEY).toBe("from-file");
await writeFile(join(appRoot, ".eve", "provider.json"), '{"selected":"ai-gateway-key"}\n');
await loadDevelopmentEnvironmentFiles(appRoot);
expect(process.env.AI_GATEWAY_API_KEY).toBe("from-file");
});
- it("fingerprints suppression of a shell Gateway key for Project OIDC", async () => {
+ it("does not change the host fingerprint when selecting Project OIDC", async () => {
const appRoot = await createEnvironmentApp();
process.env.AI_GATEWAY_API_KEY = "from-parent";
await loadDevelopmentEnvironmentFiles(appRoot);
- expect(readDevelopmentEnvironmentHostValues(appRoot).AI_GATEWAY_API_KEY).toBe("from-parent");
+ const previous = readDevelopmentEnvironmentHostValues(appRoot);
await mkdir(join(appRoot, ".eve"));
await writeFile(join(appRoot, ".eve", "provider.json"), '{"selected":"ai-gateway-project"}\n');
await loadDevelopmentEnvironmentFiles(appRoot);
- expect(process.env.AI_GATEWAY_API_KEY).toBeUndefined();
- expect(readDevelopmentEnvironmentHostValues(appRoot).AI_GATEWAY_API_KEY).toBeNull();
+ expect(process.env.AI_GATEWAY_API_KEY).toBe("from-parent");
+ expect(readDevelopmentEnvironmentHostValues(appRoot)).toEqual(previous);
});
it("loads, watches, fingerprints, and reloads workspace-root env", async () => {
diff --git a/packages/eve/src/internal/nitro/host/start-development-server.ts b/packages/eve/src/internal/nitro/host/start-development-server.ts
index 5086a15ea..80bc7fd94 100644
--- a/packages/eve/src/internal/nitro/host/start-development-server.ts
+++ b/packages/eve/src/internal/nitro/host/start-development-server.ts
@@ -1,3 +1,4 @@
+import { handleDevelopmentModelCredentialRequest } from "#internal/model-auth/development-broker-server.js";
import { EVE_DEV_ENV_FLAG } from "#internal/application/optional-package-install.js";
import type { Nitro } from "nitro/types";
@@ -209,8 +210,14 @@ function addDevelopmentControlHandler(input: {
readonly devServer: DrainedNitroDevServer;
readonly getWatcher: () => AuthoredSourceWatcherHandle | undefined;
readonly workflowWorld: ParentDevelopmentWorkflowWorld | undefined;
+ readonly transportSecret: string;
}): void {
input.devServer.setControlHandler(async (request) => {
+ const credentialResponse = await handleDevelopmentModelCredentialRequest(request, {
+ appRoot: input.appRoot,
+ secret: input.transportSecret,
+ });
+ if (credentialResponse !== undefined) return credentialResponse;
const worldResponse = await input.workflowWorld?.handleRequest(request);
if (worldResponse !== undefined) {
return worldResponse;
@@ -463,6 +470,7 @@ async function startNitroDevelopmentServer(
devServer: activeDevServer,
getWatcher: () => authoredSourceWatcher,
workflowWorld,
+ transportSecret: workflowTransportSecret,
});
const hostname =
options.host ?? activeNitro.options.devServer.hostname ?? DEFAULT_DEVELOPMENT_SERVER_HOST;
diff --git a/packages/eve/src/internal/nitro/routes/info.ts b/packages/eve/src/internal/nitro/routes/info.ts
index ccf8f57bf..270d61bb4 100644
--- a/packages/eve/src/internal/nitro/routes/info.ts
+++ b/packages/eve/src/internal/nitro/routes/info.ts
@@ -1,3 +1,10 @@
+import {
+ developmentModelBrokerAvailable,
+ readDevelopmentModelCredential,
+} from "#internal/model-auth/development-broker-client.js";
+import type { ChatGptAuthState } from "#public/models/openai/chatgpt/token-broker.js";
+import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
+import { resolveGatewayModelCredential } from "#internal/model-auth/gateway-credential.js";
import { getVercelOidcToken } from "#compiled/@vercel/oidc/index.js";
import { hasEnvValue } from "#internal/resolve-model-endpoint-status.js";
import { buildAgentInfoResponse } from "#internal/nitro/routes/agent-info/build-agent-info-response.js";
@@ -26,12 +33,20 @@ async function createAgentInfoPayload(input: NitroArtifactsConfig) {
routing === undefined
? { apiKey: false, oidc: false }
: await resolveGatewayCredentialPresence(routing),
- ...(isChatGptModelRouting(routing)
- ? { chatgptAuth: await getDefaultCodexTokenBroker().refreshState() }
- : {}),
+ ...(isChatGptModelRouting(routing) ? { chatgptAuth: await resolveChatGptAuthState() } : {}),
});
}
+async function resolveChatGptAuthState(): Promise<ChatGptAuthState> {
+ if (!developmentModelBrokerAvailable()) return getDefaultCodexTokenBroker().refreshState();
+ try {
+ const credential = await readDevelopmentModelCredential("chatgpt");
+ return { kind: "ready", accountLabel: credential?.accountLabel };
+ } catch {
+ return { kind: "signed-out" };
+ }
+}
+
/**
* Mirrors the AI Gateway credential selection order. The Vercel OIDC SDK owns
* request-context, environment, and linked-project token resolution; lookup
@@ -40,6 +55,21 @@ async function createAgentInfoPayload(input: NitroArtifactsConfig) {
async function resolveGatewayCredentialPresence(
routing: ModelRouting,
): Promise<GatewayCredentialPresence> {
+ if (routing.kind === "gateway" && isEveDevEnvironment()) {
+ try {
+ const credential =
+ (await readDevelopmentModelCredential("gateway")) ??
+ (await resolveGatewayModelCredential());
+ return {
+ apiKey: credential.kind === "api-key",
+ oidc: credential.kind === "oidc",
+ account: credential.kind === "oauth",
+ team: credential.teamName,
+ };
+ } catch {
+ return { apiKey: false, oidc: false };
+ }
+ }
const apiKey = hasEnvValue(process.env.AI_GATEWAY_API_KEY);
if (routing.kind === "external" || apiKey) {
diff --git a/packages/eve/src/internal/resolve-model-endpoint-status.ts b/packages/eve/src/internal/resolve-model-endpoint-status.ts
index e7d3cef91..99c270186 100644
--- a/packages/eve/src/internal/resolve-model-endpoint-status.ts
+++ b/packages/eve/src/internal/resolve-model-endpoint-status.ts
@@ -12,6 +12,8 @@ export interface GatewayCredentialPresence {
readonly apiKey: boolean;
/** A Vercel OIDC token is available (`VERCEL_OIDC_TOKEN` or a linked project). */
readonly oidc: boolean;
+ readonly account?: boolean;
+ readonly team?: string;
}
/** True when an environment value is present and non-blank. */
@@ -90,6 +92,13 @@ export function resolveModelEndpointStatus(
}
return { kind: "external", provider: routing.provider };
}
+ if (credentials.account)
+ return {
+ kind: "gateway",
+ connected: true,
+ credential: "oauth",
+ team: credentials.team,
+ };
const resolution = resolveGatewayCredential({
apiKeyInEnv: credentials.apiKey,
oidcAvailable: credentials.oidc,
diff --git a/packages/eve/src/internal/vercel/api-resource.test.ts b/packages/eve/src/internal/vercel/api-resource.test.ts
new file mode 100644
index 000000000..2d223e2ab
--- /dev/null
+++ b/packages/eve/src/internal/vercel/api-resource.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest";
+
+import { readVercelResourceName, readVercelResourceSlug } from "./api-resource.js";
+
+describe("Vercel API resource identity", () => {
+ it("prefers a display name and falls back to a valid slug", () => {
+ expect(readVercelResourceName({ name: "Acme Inc.", slug: "acme" })).toBe("Acme Inc.");
+ expect(readVercelResourceName({ slug: "acme-platform" })).toBe("acme-platform");
+ });
+
+ it("rejects empty names and invalid slugs", () => {
+ expect(readVercelResourceName({ name: "", slug: "Acme Team" })).toBeUndefined();
+ expect(readVercelResourceSlug({ slug: "Acme Team" })).toBeUndefined();
+ expect(readVercelResourceSlug(null)).toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/internal/vercel/api-resource.ts b/packages/eve/src/internal/vercel/api-resource.ts
new file mode 100644
index 000000000..5f4df4174
--- /dev/null
+++ b/packages/eve/src/internal/vercel/api-resource.ts
@@ -0,0 +1,16 @@
+function readNonEmptyStringField(value: unknown, field: string): string | undefined {
+ if (typeof value !== "object" || value === null || !(field in value)) return undefined;
+ const candidate = (value as Record<string, unknown>)[field];
+ return typeof candidate === "string" && candidate.length > 0 ? candidate : undefined;
+}
+
+/** Reads a Vercel resource's display name, falling back to its slug. */
+export function readVercelResourceName(value: unknown): string | undefined {
+ return readNonEmptyStringField(value, "name") ?? readVercelResourceSlug(value);
+}
+
+/** Reads a validated Vercel resource slug. */
+export function readVercelResourceSlug(value: unknown): string | undefined {
+ const slug = readNonEmptyStringField(value, "slug");
+ return slug !== undefined && /^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(slug) ? slug : undefined;
+}
diff --git a/packages/eve/src/internal/workflow/development-world-client.ts b/packages/eve/src/internal/workflow/development-world-client.ts
index 3a1c0a8f3..52b62a3fd 100644
--- a/packages/eve/src/internal/workflow/development-world-client.ts
+++ b/packages/eve/src/internal/workflow/development-world-client.ts
@@ -235,7 +235,8 @@ function createQueueHandler(
* an untrusted caller controls participates.
*/
async function resolveDeliveryGenerationId(message: unknown): Promise<string> {
- if (!isRecord(message)) {
+ // Capability probes may name a run before start() persists its record.
+ if (!isRecord(message) || message.__healthCheck === true) {
return await call<string>("resolveLatestDeploymentId");
}
const runInput = isRecord(message.runInput) ? message.runInput : undefined;
diff --git a/packages/eve/src/internal/workflow/development-world-server.integration.test.ts b/packages/eve/src/internal/workflow/development-world-server.integration.test.ts
index b17efc81c..32d61086c 100644
--- a/packages/eve/src/internal/workflow/development-world-server.integration.test.ts
+++ b/packages/eve/src/internal/workflow/development-world-server.integration.test.ts
@@ -213,6 +213,36 @@ describe("parent development Workflow World", () => {
}
});
+ it("routes a pre-start health check to the active generation before its run exists", async () => {
+ const appRoot = await createScratchDirectory("eve-parent-workflow-health-check-");
+ await seedGeneration(appRoot, "generation-b");
+ const world = createWorld({ activeGenerationId: () => "generation-b", appRoot });
+ connectWorkerToWorld(world, appRoot);
+
+ try {
+ await world.start();
+ const payload = { __healthCheck: true, correlationId: "probe", runId: RUN_ID };
+ const handled = vi.fn(async () => {
+ expect(getDevelopmentWorkflowGeneration()?.generationId).toBe("generation-b");
+ });
+ const handler = createDevelopmentWorkflowWorld().createQueueHandler(QUEUE_PREFIX, handled);
+ const response = await handler(
+ new Request("http://localhost/.well-known/workflow/v1/flow", {
+ body: JSON.stringify(payload),
+ headers: {
+ ...deliveryHeaders({}),
+ "x-vqs-queue-name": `${QUEUE_PREFIX}health_check`,
+ },
+ method: "POST",
+ }),
+ );
+ expect(response.status, await response.text()).toBe(200);
+ expect(handled).toHaveBeenCalledWith(payload, expect.any(Object));
+ } finally {
+ await world.close();
+ }
+ });
+
it("acknowledges and drops a delivery whose generation is permanently missing", async () => {
const appRoot = await createScratchDirectory("eve-parent-workflow-dropped-delivery-");
await seedGeneration(appRoot, "generation-a");
diff --git a/packages/eve/src/public/models/anthropic/index.ts b/packages/eve/src/public/models/anthropic/index.ts
new file mode 100644
index 000000000..3c4e1d8ca
--- /dev/null
+++ b/packages/eve/src/public/models/anthropic/index.ts
@@ -0,0 +1,13 @@
+import type { LanguageModel } from "ai";
+import { createAnthropic } from "#compiled/@ai-sdk/anthropic/index.js";
+import { createDirectModelFetch } from "#internal/model-auth/transport.js";
+
+/** Creates a direct Anthropic model. Uses ANTHROPIC_API_KEY, or /login credentials in local development. */
+export function anthropic(model = "claude-sonnet-5"): LanguageModel {
+ const id = model.trim().replace(/^anthropic\//u, "");
+ if (!id || id.includes("/")) throw new Error("Expected an Anthropic model ID.");
+ return createAnthropic({
+ apiKey: "eve-local-credential",
+ fetch: createDirectModelFetch("anthropic"),
+ })(id);
+}
diff --git a/packages/eve/src/public/models/openai/chatgpt/codex-app-server.ts b/packages/eve/src/public/models/openai/chatgpt/codex-app-server.ts
index 01644e6ab..593b58284 100644
--- a/packages/eve/src/public/models/openai/chatgpt/codex-app-server.ts
+++ b/packages/eve/src/public/models/openai/chatgpt/codex-app-server.ts
@@ -90,7 +90,7 @@ export class CodexAppServerClient implements CodexAppServer {
throw input.forceRefresh
? new ChatGptSignInRequiredError()
: new ChatGptSignedOutError(
- "ChatGPT subscription is not signed in to Codex. Run `codex login` or sign in from /model.",
+ "ChatGPT subscription is not signed in to Codex. Run `codex login` or sign in from /login.",
);
}
let token = tokenFromCodex(status.authToken);
diff --git a/packages/eve/src/public/models/openai/chatgpt/credential-store.ts b/packages/eve/src/public/models/openai/chatgpt/credential-store.ts
index 0e5db3052..4f570fbac 100644
--- a/packages/eve/src/public/models/openai/chatgpt/credential-store.ts
+++ b/packages/eve/src/public/models/openai/chatgpt/credential-store.ts
@@ -26,7 +26,7 @@ const MAX_SECRET_BYTES = 2560;
export class ChatGptInvalidStoredSessionError extends Error {
constructor() {
super(
- "The ChatGPT session in the OS secret store is invalid. Sign in again from /model to replace it.",
+ "The ChatGPT session in the OS secret store is invalid. Sign in again from /login to replace it.",
);
}
}
@@ -231,6 +231,6 @@ function secretStoreError(): Error {
? "Allow Windows PowerShell and Credential Manager access in your user session."
: "Unlock your login keychain and allow credential access.";
return new Error(
- `Could not access ChatGPT credentials in the OS secret store. ${recovery} Retry from /model.`,
+ `Could not access ChatGPT credentials in the OS secret store. ${recovery} Retry from /login.`,
);
}
diff --git a/packages/eve/src/public/models/openai/chatgpt/oauth.ts b/packages/eve/src/public/models/openai/chatgpt/oauth.ts
index df05f2533..1be0ae60d 100644
--- a/packages/eve/src/public/models/openai/chatgpt/oauth.ts
+++ b/packages/eve/src/public/models/openai/chatgpt/oauth.ts
@@ -59,7 +59,7 @@ export async function requestChatGptTokens(
throw new ChatGptSignInRequiredError();
}
throw new Error(
- `ChatGPT authentication failed (HTTP ${response.status}). Retry sign-in from /model.`,
+ `ChatGPT authentication failed (HTTP ${response.status}). Retry sign-in from /login.`,
);
}
const value = await readChatGptAuthResponse(response);
@@ -71,7 +71,7 @@ export async function requestChatGptTokens(
: options.previous?.refreshToken;
if (!accessToken || !refreshToken || !isObject(value)) {
throw new Error(
- "ChatGPT authentication did not return a usable session. Retry sign-in from /model.",
+ "ChatGPT authentication did not return a usable session. Retry sign-in from /login.",
);
}
const idToken = typeof value.id_token === "string" ? value.id_token : undefined;
@@ -92,7 +92,7 @@ export async function requestChatGptTokens(
: (readCodexJwtExpirationMs(accessToken) ?? now + 3600_000);
if (!Number.isFinite(expiresAt) || expiresAt <= now) {
throw new Error(
- "ChatGPT authentication returned an expired session. Retry sign-in from /model.",
+ "ChatGPT authentication returned an expired session. Retry sign-in from /login.",
);
}
return {
@@ -107,7 +107,7 @@ export async function requestChatGptTokens(
export async function readChatGptAuthResponse(response: Response): Promise<unknown> {
const reader = response.body?.getReader();
if (!reader)
- throw new Error("ChatGPT authentication returned an empty response. Retry from /model.");
+ throw new Error("ChatGPT authentication returned an empty response. Retry from /login.");
try {
const chunks: Uint8Array[] = [];
let bytes = 0;
@@ -121,7 +121,7 @@ export async function readChatGptAuthResponse(response: Response): Promise<unkno
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
} catch {
await reader.cancel().catch(() => {});
- throw new Error("ChatGPT authentication returned an invalid response. Retry from /model.");
+ throw new Error("ChatGPT authentication returned an invalid response. Retry from /login.");
} finally {
reader.releaseLock();
}
diff --git a/packages/eve/src/public/models/openai/chatgpt/transport.ts b/packages/eve/src/public/models/openai/chatgpt/transport.ts
index 51ccd777d..f0a1264dc 100644
--- a/packages/eve/src/public/models/openai/chatgpt/transport.ts
+++ b/packages/eve/src/public/models/openai/chatgpt/transport.ts
@@ -1,3 +1,4 @@
+import { readDevelopmentModelCredential } from "#internal/model-auth/development-broker-client.js";
import { isObject } from "#shared/guards.js";
import { getDefaultCodexTokenBroker, type CodexTokenBroker } from "./token-broker.js";
@@ -19,18 +20,26 @@ export interface CodexTransportOptions {
*/
export function createCodexFetch(options: CodexTransportOptions = {}): Fetch {
const httpFetch = options.fetch ?? fetch;
- const broker = options.broker ?? getDefaultCodexTokenBroker();
+ const resolveToken = async (rejectedToken?: string, signal?: AbortSignal | null) => {
+ const reason = rejectedToken === undefined ? "request" : "rejected";
+ if (options.broker) return options.broker.getToken({ reason });
+ return (
+ (await readDevelopmentModelCredential("chatgpt", rejectedToken, signal)) ??
+ (await getDefaultCodexTokenBroker().getToken({ reason }))
+ );
+ };
const codexApiEndpoint = options.codexApiEndpoint ?? CODEX_API_ENDPOINT;
return async (input: FetchInput, init?: RequestInit): Promise<Response> => {
const url = rewriteCodexEndpoint(requestUrl(input), codexApiEndpoint);
const requestInit = stripInputItemIds(init);
- const token = await broker.getToken({ reason: "request" });
+ const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined);
+ const token = await resolveToken(undefined, signal);
const first = await httpFetch(url, authenticatedInit(input, requestInit, token));
if (first.status !== 401 || !isReplayable(input, init)) return first;
await first.body?.cancel();
- const refreshed = await broker.getToken({ reason: "rejected" });
+ const refreshed = await resolveToken(token.token, signal);
return httpFetch(url, authenticatedInit(input, requestInit, refreshed));
};
}
diff --git a/packages/eve/src/public/models/openai/index.test.ts b/packages/eve/src/public/models/openai/index.test.ts
index dc3a8bd2a..df84f36cf 100644
--- a/packages/eve/src/public/models/openai/index.test.ts
+++ b/packages/eve/src/public/models/openai/index.test.ts
@@ -3,10 +3,10 @@ import { describe, expect, it } from "vitest";
import { chatgpt, experimental_chatgpt } from "./index.js";
describe("chatgpt", () => {
- it("defaults to gpt-5.6-sol", () => {
+ it("defaults to gpt-5.6-luna-fast", () => {
const model = chatgpt();
if (typeof model === "string") throw new Error("expected a model instance");
- expect(model.modelId).toBe("gpt-5.6-sol");
+ expect(model.modelId).toBe("gpt-5.6-luna-fast");
});
it("creates a Codex-served model from a bare OpenAI slug", () => {
diff --git a/packages/eve/src/public/models/openai/index.ts b/packages/eve/src/public/models/openai/index.ts
index bcdff4744..39bb7cf0a 100644
--- a/packages/eve/src/public/models/openai/index.ts
+++ b/packages/eve/src/public/models/openai/index.ts
@@ -1,12 +1,14 @@
+import { createOpenAI } from "#compiled/@ai-sdk/openai/index.js";
+import { createDirectModelFetch } from "#internal/model-auth/transport.js";
import type { LanguageModel } from "ai";
import { DEFAULT_CHATGPT_MODEL_ID, normalizeChatGptModelId } from "#shared/chatgpt-model.js";
import { createCodexSubscriptionModel } from "./chatgpt/model.js";
/**
* Creates a language model billed to the local ChatGPT subscription instead
- * of an API key. Sign in through `/model` in `eve dev`.
+ * of an API key. Sign in through `/login` in `eve dev`.
*
- * Defaults to `gpt-5.6-sol`. Pass a bare OpenAI model slug or an
+ * Defaults to `gpt-5.6-luna-fast`. Pass a bare OpenAI model slug or an
* `openai/`-prefixed id to override it; the Codex backend serves OpenAI models
* only, so any other provider-qualified id is rejected. Model availability is
* enforced by the Codex backend per account at call time, not at compile time.
@@ -42,3 +44,13 @@ export function chatgpt(model = DEFAULT_CHATGPT_MODEL_ID): LanguageModel {
/** @deprecated Use {@link chatgpt}. */
export const experimental_chatgpt = chatgpt;
+
+/** Creates a direct OpenAI model. Uses OPENAI_API_KEY, or /login credentials in local development. */
+export function openai(model = "gpt-5.6-luna-fast"): LanguageModel {
+ const id = model.trim().replace(/^openai\//u, "");
+ if (!id || id.includes("/")) throw new Error("Expected an OpenAI model ID.");
+ return createOpenAI({
+ apiKey: "eve-local-credential",
+ fetch: createDirectModelFetch("openai"),
+ }).responses(id);
+}
diff --git a/packages/eve/src/public/sandbox/docker-sandbox.ts b/packages/eve/src/public/sandbox/docker-sandbox.ts
index 5856651dd..cbe0abd47 100644
--- a/packages/eve/src/public/sandbox/docker-sandbox.ts
+++ b/packages/eve/src/public/sandbox/docker-sandbox.ts
@@ -25,7 +25,7 @@ export interface DockerSandboxCreateOptions {
/**
* Base container image for templates and sessions. Defaults to eve's
* published `ghcr.io/vercel/eve` image, tagged with the installed eve
- * version or `EVE_SANDBOX_IMAGE_TAG` when set. Framework setup creates
+ * version without build metadata or `EVE_SANDBOX_IMAGE_TAG` when set. Framework setup creates
* `/workspace` and verifies Bash. Install
* any authored runtime tools in sandbox bootstrap or provide them through a
* custom image.
diff --git a/packages/eve/src/public/sandbox/microsandbox-sandbox.ts b/packages/eve/src/public/sandbox/microsandbox-sandbox.ts
index ef05c12b8..daae6dea3 100644
--- a/packages/eve/src/public/sandbox/microsandbox-sandbox.ts
+++ b/packages/eve/src/public/sandbox/microsandbox-sandbox.ts
@@ -17,7 +17,7 @@ export interface MicrosandboxSandboxCreateOptions {
* Python, or ripgrep in sandbox bootstrap or provide them through a
* custom image.
*
- * @default The `ghcr.io/vercel/eve` tag matching the installed eve version, or `EVE_SANDBOX_IMAGE_TAG` when set.
+ * @default The `ghcr.io/vercel/eve` tag matching the installed eve version without build metadata, or `EVE_SANDBOX_IMAGE_TAG` when set.
*/
readonly image?: string;
/** Number of virtual CPUs assigned to each sandbox. @default 1 */
diff --git a/packages/eve/src/public/sandbox/vercel-sandbox.ts b/packages/eve/src/public/sandbox/vercel-sandbox.ts
index df21886bb..66cca21be 100644
--- a/packages/eve/src/public/sandbox/vercel-sandbox.ts
+++ b/packages/eve/src/public/sandbox/vercel-sandbox.ts
@@ -30,7 +30,7 @@ type VercelSandboxAuthorCreateOptions<T> = T extends unknown
* author-supplied values.
*
* `runtime` is excluded: eve defaults to its published
- * `vcr.vercel.com/vercel/eve/base` image tagged with the installed eve version
+ * `vcr.vercel.com/vercel/eve/base` image tagged with the installed eve version without build metadata
* or `EVE_SANDBOX_IMAGE_TAG` when `image` is not supplied. Both are mutually
* exclusive with a stock runtime.
*
diff --git a/packages/eve/src/runtime/agent/resolve-model.ts b/packages/eve/src/runtime/agent/resolve-model.ts
index 8cfbd5757..44164d8e2 100644
--- a/packages/eve/src/runtime/agent/resolve-model.ts
+++ b/packages/eve/src/runtime/agent/resolve-model.ts
@@ -1,3 +1,4 @@
+import { localGatewayModel } from "#internal/model-auth/transport.js";
import type { LanguageModel } from "ai";
import type { CompiledModuleMap } from "#compiler/module-map.js";
import type { ContextAccessor } from "#context/key.js";
@@ -66,7 +67,7 @@ export async function resolveRuntimeModelReference(
return await loadSourceBackedRuntimeModelReference(reference, scope);
}
- return reference.id;
+ return localGatewayModel(reference.id) ?? reference.id;
}
async function loadSourceBackedRuntimeModelReference(
diff --git a/packages/eve/src/setup/cli/option-row.test.ts b/packages/eve/src/setup/cli/option-row.test.ts
index 390e58975..8b2b03adc 100644
--- a/packages/eve/src/setup/cli/option-row.test.ts
+++ b/packages/eve/src/setup/cli/option-row.test.ts
@@ -46,7 +46,7 @@ describe("renderOptionRow", () => {
test("highlights the cursor row in inverse blue and keeps its hint outside", () => {
expect(row({ label: "Yes", hint: "Create a project", isCursor: true })).toBe(
- "<inverse><blue> ▶ Yes </blue></inverse><dim>· Create a project</dim>",
+ " › Yes<dim> · Create a project</dim>",
);
});
@@ -67,12 +67,12 @@ describe("renderOptionRow", () => {
" <yellow>Configure provider</yellow>",
);
expect(row({ label: "Configure provider", isCursor: true, accent: "warning" })).toBe(
- "<inverse><yellow> ▶ Configure provider </yellow></inverse>",
+ "<yellow> › Configure provider</yellow>",
);
});
test("an un-hovered available row shows the placeholder dot when asked", () => {
- expect(row({ label: "Slack", placeholder: true })).toBe(" <dim>◦</dim> Slack");
+ expect(row({ label: "Slack", placeholder: true })).toBe(" <dim> </dim> Slack");
});
test("a checked row off the cursor shows a green check (single column, no checkbox)", () => {
@@ -89,7 +89,7 @@ describe("renderOptionRow", () => {
isCursor: true,
state: { kind: "available", checked: true },
}),
- ).toBe("<inverse><blue> ✓ Web Chat </blue></inverse>");
+ ).toBe(" ✓ Web Chat");
});
test("a completed row under the cursor reads as inert: a dim pointer and dim label", () => {
@@ -100,7 +100,7 @@ describe("renderOptionRow", () => {
state: { kind: "completed" },
focusHint: "Already installed",
}),
- ).toBe(" <dim>▷</dim> <dim>Web Chat</dim><dim> · Already installed</dim>");
+ ).toBe(" <dim>›</dim> <dim>Web Chat</dim><dim> · Already installed</dim>");
});
test("a completed row off the cursor keeps its green check", () => {
@@ -134,7 +134,7 @@ describe("renderOptionRow", () => {
state: { kind: "disabled", reason: "needs a Vercel project" },
placeholder: true,
}),
- ).toBe(" <dim>◦</dim> <dim>Slack (needs a Vercel project)</dim>");
+ ).toBe(" <dim> </dim> <dim>Slack (needs a Vercel project)</dim>");
});
test("a disabled row under the cursor reads as inert: a dim pointer, not the placeholder", () => {
@@ -145,7 +145,7 @@ describe("renderOptionRow", () => {
state: { kind: "disabled" },
placeholder: true,
}),
- ).toBe(" <dim>▷</dim> <dim>Waiting</dim>");
+ ).toBe(" <dim>›</dim> <dim>Waiting</dim>");
});
test("warning-toned disabled rows keep the label dim and show a yellow alert annotation", () => {
@@ -164,14 +164,14 @@ describe("renderOptionRow", () => {
test("a hint tab-aligns behind a padded label column", () => {
expect(
row({ label: "Slack", hint: "creates a slackbot", placeholder: true, hintPadding: 6 }),
- ).toBe(" <dim>◦</dim> Slack<dim> · creates a slackbot</dim>");
+ ).toBe(" <dim> </dim> Slack<dim> · creates a slackbot</dim>");
});
test("a persistent hint shows on any row; a focus hint only under the cursor", () => {
expect(row({ label: "Slack", hint: "persistent" })).toBe(" Slack<dim> · persistent</dim>");
expect(row({ label: "Slack", focusHint: "only on hover" })).toBe(" Slack");
expect(row({ label: "Slack", isCursor: true, focusHint: "only on hover" })).toBe(
- "<inverse><blue> ▶ Slack </blue></inverse><dim>· only on hover</dim>",
+ " › Slack<dim> · only on hover</dim>",
);
});
diff --git a/packages/eve/src/setup/cli/option-row.ts b/packages/eve/src/setup/cli/option-row.ts
index 6ab59313d..094696ef8 100644
--- a/packages/eve/src/setup/cli/option-row.ts
+++ b/packages/eve/src/setup/cli/option-row.ts
@@ -14,6 +14,7 @@
/** The color primitives the row painter needs; satisfied by both the TUI theme and the CLI palette. */
export interface RowColors {
blue(text: string): string;
+ bold?(text: string): string;
dim(text: string): string;
green(text: string): string;
inverse(text: string): string;
@@ -38,10 +39,10 @@ export interface RowGlyphs {
/** Canonical unicode glyphs; the CLI prompts render with these. */
export const UNICODE_ROW_GLYPHS: RowGlyphs = {
- pointer: "▷",
- selectedPointer: "▶",
+ pointer: "›",
+ selectedPointer: "›",
success: "✓",
- placeholder: "◦",
+ placeholder: " ",
dot: "·",
warning: "⚠",
};
@@ -181,12 +182,12 @@ function optionRowPresentation(input: OptionRowInput): OptionRowPresentation {
export function renderCursorRow(
text: string,
selected: boolean,
- colors: Pick<RowColors, "blue" | "inverse" | "yellow">,
+ colors: Pick<RowColors, "blue" | "inverse" | "yellow" | "bold">,
accent?: "warning",
): string {
if (!selected) return ` ${text}`;
- const color = accent === "warning" ? colors.yellow : colors.blue;
- return colors.inverse(color(` ${text} `));
+ const color = accent === "warning" ? colors.yellow : (colors.bold ?? ((value: string) => value));
+ return color(` ${text}`);
}
/** Prefixes a continuation line so its text starts in the option label column. */
@@ -210,7 +211,7 @@ export function renderOptionRow(input: OptionRowInput): string {
if (input.isCursor && input.focusHint !== undefined) hintText = input.focusHint;
let hint = "";
if (hintText !== undefined) {
- const separatorWidth = Math.max(0, (input.hintPadding ?? 0) + 1 - Number(selected));
+ const separatorWidth = Math.max(0, (input.hintPadding ?? 0) + 1);
hint = c.dim(`${" ".repeat(separatorWidth)}${glyphs.dot} ${hintText}`);
}
const content = `${glyph} ${label}`;
diff --git a/packages/eve/src/setup/cli/prompt-ui.test.ts b/packages/eve/src/setup/cli/prompt-ui.test.ts
index 7c8d6d8f2..eabe89510 100644
--- a/packages/eve/src/setup/cli/prompt-ui.test.ts
+++ b/packages/eve/src/setup/cli/prompt-ui.test.ts
@@ -77,9 +77,7 @@ describe("renderSelectPrompt", () => {
state: "active",
});
- expect(rendered).toContain(
- "<inverse><blue> ▶ Yes </blue></inverse><dim>· Create or link a project</dim>",
- );
+ expect(rendered).toContain("<b> › Yes</b><dim> · Create or link a project</dim>");
// No check or legacy checkbox glyphs on a single-select row.
expect(rendered).not.toContain("✓");
expect(rendered).not.toContain("◻");
@@ -123,9 +121,7 @@ describe("renderSelectPrompt", () => {
});
// The description indents to the option label column.
- expect(rendered).toContain(
- "<inverse><blue> ▶ No </blue></inverse>\n│ <dim>Set up locally and wire yourself</dim>",
- );
+ expect(rendered).toContain("<b> › No</b>\n│ <dim>Set up locally and wire yourself</dim>");
// The non-highlighted option keeps its description hidden.
expect(rendered).not.toContain("Fastest path to production");
});
@@ -230,7 +226,7 @@ describe("renderMultiselectPrompt", () => {
});
// Cursor row (Web Chat): the pointer. Selected row off-cursor (Slack): a check.
- expect(rendered).toContain("<inverse><blue> ▶ Web Chat </blue></inverse>");
+ expect(rendered).toContain(" › Web Chat");
expect(rendered).toContain("<green>✓</green> Slack");
// No key legend: the Submit row carries the confirm affordance.
expect(rendered).not.toContain("space");
@@ -255,9 +251,7 @@ describe("renderMultiselectPrompt", () => {
expect(render(0)).toContain("│\n│ <dim><b>Submit</b></dim> <green>✓</green>");
// Cursor one past the options sits on the Submit row: the pointer plus a
// bright label.
- expect(render(2)).toContain(
- "<inverse><blue> ▶ <b>Submit</b> </blue></inverse><green>✓</green>",
- );
+ expect(render(2)).toContain("<b> › <b>Submit</b></b> <green>✓</green>");
const visible = (text: string) => text.replaceAll(/<[^>]+>/g, "");
const unselected = visible(render(0))
.split("\n")
@@ -296,7 +290,7 @@ describe("renderMultiselectPrompt", () => {
state: "active",
});
- expect(rendered).toContain("<inverse><blue> ▶ Web Chat </blue></inverse>");
+ expect(rendered).toContain(" › Web Chat");
// A locked row is mandatory rather than user-selected, so both its check
// and label stay dim while the reason remains inline.
expect(rendered).toContain(
@@ -344,7 +338,7 @@ describe("renderSearchableSelect", () => {
submitDisplay: "",
});
- expect(rendered).toContain("<inverse><blue> ▶ alpha </blue></inverse>");
+ expect(rendered).toContain(" › alpha");
expect(rendered).toContain("<cyan>enter</cyan><dim> to select</dim>");
expect(rendered).not.toContain("space");
expect(rendered).not.toContain("◻");
@@ -364,7 +358,7 @@ describe("renderSearchableSelect", () => {
submitDisplay: "",
});
- expect(rendered).toContain("<inverse><blue> ▶ alpha </blue></inverse>");
+ expect(rendered).toContain(" › alpha");
expect(rendered).toContain("<green>✓</green> beta");
expect(rendered).toContain("<dim><b>Submit</b></dim> <green>✓</green>");
// The Submit row replaces the key legend; only the filter hint remains.
@@ -386,9 +380,9 @@ describe("renderSearchableSelect", () => {
submitDisplay: "",
});
- expect(rendered).toContain("<inverse><blue> ▶ <b>Submit</b> </blue></inverse><green>✓</green>");
+ expect(rendered).toContain("<b> › <b>Submit</b></b> <green>✓</green>");
// No option row carries the pointer while the cursor sits on Submit.
- expect(rendered).not.toContain("<inverse><blue> ▶ alpha </blue></inverse>");
+ expect(rendered).not.toContain(" › alpha");
});
test("a leading featured run sizes the default viewport; scrolling reaches the rest", () => {
diff --git a/packages/eve/src/setup/cli/prompt-ui.ts b/packages/eve/src/setup/cli/prompt-ui.ts
index f07a0f655..ff91e49ff 100644
--- a/packages/eve/src/setup/cli/prompt-ui.ts
+++ b/packages/eve/src/setup/cli/prompt-ui.ts
@@ -35,6 +35,8 @@ export interface PromptColors {
export interface PromptOption<T extends PromptValue> {
value: T;
label: string;
+ /** Additional searchable text that is never rendered in the menu. */
+ keywords?: readonly string[];
/** Completion action kept after searchable results instead of being filtered. */
trailingAction?: boolean;
/** Supporting copy; stacked prompts render newline-separated text on separate rows. */
@@ -378,7 +380,7 @@ export function renderSubmitRow(
const content = isCursor
? `${UNICODE_ROW_GLYPHS.selectedPointer} ${bold}`
: ` ${colors.dim(bold)}`;
- const suffixSeparator = isCursor ? "" : " ";
+ const suffixSeparator = " ";
return `${renderCursorRow(content, isCursor, colors)}${suffixSeparator}${colors.green(UNICODE_ROW_GLYPHS.success)}`;
}
diff --git a/packages/eve/src/setup/cli/select-state.test.ts b/packages/eve/src/setup/cli/select-state.test.ts
index 6bc8faa25..684066681 100644
--- a/packages/eve/src/setup/cli/select-state.test.ts
+++ b/packages/eve/src/setup/cli/select-state.test.ts
@@ -48,6 +48,14 @@ describe("filterOptions", () => {
expect(filterOptions(options, "installed")).toEqual(options);
});
+ it("matches hidden keywords without filtering out trailing actions", () => {
+ const option = { value: "blooio", label: "Blooio", keywords: ["iMessage", "SMS"] };
+ const done = { value: "done", label: "Done", trailingAction: true, keywords: ["iMessage"] };
+ expect(filterOptions([option, done], " IMESSAGE ")).toEqual([option, done]);
+ expect(filterOptions([option, done], "sms")).toEqual([option, done]);
+ expect(filterOptions([option, done], "email")).toEqual([done]);
+ });
+
it("returns nothing when no option matches", () => {
const done = { value: "done", label: "Done", trailingAction: true };
expect(filterOptions([...OPTIONS, done], "zzz")).toEqual([done]);
diff --git a/packages/eve/src/setup/cli/select-state.ts b/packages/eve/src/setup/cli/select-state.ts
index 88dd53cf0..83955d760 100644
--- a/packages/eve/src/setup/cli/select-state.ts
+++ b/packages/eve/src/setup/cli/select-state.ts
@@ -61,7 +61,7 @@ export function submitRowIndex(visible: readonly PromptOption<string>[]): number
}
/**
- * Case-insensitive substring match across an option's label, value, and hints.
+ * Case-insensitive substring match across an option's label, value, hints, and keywords.
* An empty query returns every option, so the cursor can always scroll the
* full list; `featured` only shapes the searchable picker's default viewport,
* not which rows exist.
@@ -80,7 +80,9 @@ export function filterOptions(
(option.label.toLowerCase().includes(normalizedQuery) ||
option.value.toLowerCase().includes(normalizedQuery) ||
(option.hint?.toLowerCase().includes(normalizedQuery) ?? false) ||
- (option.focusHint?.toLowerCase().includes(normalizedQuery) ?? false)),
+ (option.focusHint?.toLowerCase().includes(normalizedQuery) ?? false) ||
+ (option.keywords?.some((keyword) => keyword.toLowerCase().includes(normalizedQuery)) ??
+ false)),
);
if (searchAction !== undefined) {
matches.push({ value: searchActionValue(query), label: searchAction.label(query) });
diff --git a/packages/eve/src/setup/flows/chatgpt-auth.scenario.test.ts b/packages/eve/src/setup/flows/chatgpt-auth.scenario.test.ts
index d8ca6da16..f4323f484 100644
--- a/packages/eve/src/setup/flows/chatgpt-auth.scenario.test.ts
+++ b/packages/eve/src/setup/flows/chatgpt-auth.scenario.test.ts
@@ -101,7 +101,7 @@ describe("native ChatGPT browser login", () => {
accessToken: "access",
refreshToken: "refresh",
});
- expect(options.log).toHaveBeenLastCalledWith("ChatGPT subscription connected.");
+ expect(options.log).not.toHaveBeenCalledWith("ChatGPT subscription connected.");
expect(options.log.mock.calls.flat().join("\n")).not.toContain("refresh");
});
diff --git a/packages/eve/src/setup/flows/chatgpt-auth.ts b/packages/eve/src/setup/flows/chatgpt-auth.ts
index be4d24e9b..169725fe3 100644
--- a/packages/eve/src/setup/flows/chatgpt-auth.ts
+++ b/packages/eve/src/setup/flows/chatgpt-auth.ts
@@ -109,7 +109,6 @@ async function signInWithOwnedCredentials(
broker,
"ChatGPT sign-in could not be verified. Retry from /model.",
);
- log("ChatGPT subscription connected.");
} catch (error) {
signal.throwIfAborted();
throw error;
diff --git a/packages/eve/src/setup/flows/deploy.test.ts b/packages/eve/src/setup/flows/deploy.test.ts
index 8be1f3d58..57fb66660 100644
--- a/packages/eve/src/setup/flows/deploy.test.ts
+++ b/packages/eve/src/setup/flows/deploy.test.ts
@@ -132,7 +132,7 @@ describe("runDeployFlow", () => {
});
expect(result).toEqual({ kind: "deployed", productionUrl: "https://my-agent.vercel.app" });
- expect(login).not.toHaveBeenCalled();
+ expect(login).toHaveBeenCalledOnce();
expect(fake.selectMessages).toEqual([]);
expect(deployDeps.runVercel).toHaveBeenCalledWith(
["deploy", "--prod", "--yes"],
@@ -252,3 +252,45 @@ describe("runDeployFlow", () => {
);
});
});
+
+it("installs the missing CLI and logs in before deploying an already-linked project", async () => {
+ const login = createLoginFlow();
+ login.mockResolvedValueOnce({ kind: "cli-missing" }).mockResolvedValueOnce({ kind: "logged-in" });
+ const install = vi.fn(async () => ({ kind: "installed" as const }));
+ const deploy = createDeployProjectDeps();
+ await expect(
+ runDeployFlow({
+ appRoot: APP_ROOT,
+ prompter: createFakePrompter().prompter,
+ interactive: true,
+ deps: {
+ detectDeployment: async () => LINKED,
+ runLoginFlow: login,
+ runInstallVercelCliFlow: install,
+ deployProject: deploy,
+ },
+ }),
+ ).resolves.toEqual({ kind: "deployed", productionUrl: "https://my-agent.vercel.app" });
+ expect(install).toHaveBeenCalledOnce();
+ expect(login).toHaveBeenCalledTimes(2);
+ expect(deploy.runVercel.mock.invocationCallOrder[0]).toBeGreaterThan(
+ login.mock.invocationCallOrder[1]!,
+ );
+});
+
+it.each(["failed", "unavailable"] as const)("does not deploy when login is %s", async (kind) => {
+ const deploy = createDeployProjectDeps();
+ await expect(
+ runDeployFlow({
+ appRoot: APP_ROOT,
+ prompter: createFakePrompter().prompter,
+ interactive: true,
+ deps: {
+ detectDeployment: async () => LINKED,
+ runLoginFlow: createLoginFlow({ kind }),
+ deployProject: deploy,
+ },
+ }),
+ ).rejects.toThrow(/retry/i);
+ expect(deploy.runVercel).not.toHaveBeenCalled();
+});
diff --git a/packages/eve/src/setup/flows/deploy.ts b/packages/eve/src/setup/flows/deploy.ts
index 786d0df7e..16e9571ae 100644
--- a/packages/eve/src/setup/flows/deploy.ts
+++ b/packages/eve/src/setup/flows/deploy.ts
@@ -20,6 +20,7 @@ import { snapshotSetupState, type SetupState } from "../state.js";
import { withSpinner } from "../with-spinner.js";
import { inProjectSetupState, prompterSink } from "./in-project.js";
+import { runInstallVercelCliFlow } from "./install-vercel-cli.js";
import { runLoginFlow } from "./login.js";
/** Injected for tests; defaults to the real detection and box effects. */
@@ -27,6 +28,7 @@ export interface DeployFlowDeps {
detectDeployment: typeof detectDeployment;
inspectApplication: typeof inspectApplication;
runLoginFlow: typeof runLoginFlow;
+ runInstallVercelCliFlow: typeof runInstallVercelCliFlow;
resolveProvisioning?: ResolveProvisioningDeps;
linkProject?: LinkProjectDeps;
deployProject?: DeployProjectDeps;
@@ -44,15 +46,8 @@ function productionUrlOf(project: ProjectResolution): string | undefined {
}
/**
- * THE DEPLOY FLOW, shared by `eve deploy` and the dev TUI's `/deploy`. Link
- * state is the safety-critical input for a deploy, so it is re-detected at
- * decision time, never trusted from an earlier render. An already-linked
- * project goes straight to the deploy box; an unlinked one walks the same
- * login and team/project flow as onboarding (resolve-provisioning with the
- * deploy gate pre-answered — invoking deploy IS the deploy decision), then
- * links non-interactively so the deploy box never hits its bare-`vercel link`
- * fallback. A non-interactive run with no link refuses with `needs-link`
- * before any side effect.
+ * Interactive deployment prepares CLI access before linking or deploying.
+ * Noninteractive deployment never installs tools or starts browser login.
*/
export async function runDeployFlow(input: {
appRoot: string;
@@ -67,6 +62,7 @@ export async function runDeployFlow(input: {
detectDeployment,
inspectApplication,
runLoginFlow,
+ runInstallVercelCliFlow,
...input.deps,
};
@@ -90,9 +86,24 @@ export async function runDeployFlow(input: {
if (!linked && !interactive) {
return { kind: "needs-link" };
}
- if (!linked) {
- const login = await deps.runLoginFlow({ appRoot, prompter, signal });
+ if (interactive) {
+ let login = await deps.runLoginFlow({ appRoot, prompter, signal });
+ if (login.kind === "cli-missing") {
+ const install = await deps.runInstallVercelCliFlow({ appRoot, prompter, signal });
+ if (install.kind === "cancelled") return { kind: "cancelled" };
+ if (install.kind === "failed")
+ throw new Error(
+ "Could not install the Vercel CLI. Install it with `npm i -g vercel@latest`, then retry deployment.",
+ );
+ login = await deps.runLoginFlow({ appRoot, prompter, signal });
+ }
if (login.kind === "cancelled") return { kind: "cancelled" };
+ if (login.kind !== "already" && login.kind !== "logged-in")
+ throw new Error(
+ login.kind === "unavailable"
+ ? "Could not reach Vercel. Check your connection and retry deployment."
+ : "Vercel login did not complete. Retry deployment to sign in.",
+ );
}
const state = inProjectSetupState(appRoot, project, { deploymentPending: true });
diff --git a/packages/eve/src/setup/flows/ensure-vercel-project.test.ts b/packages/eve/src/setup/flows/ensure-vercel-project.test.ts
index 80f54d30a..f863792a0 100644
--- a/packages/eve/src/setup/flows/ensure-vercel-project.test.ts
+++ b/packages/eve/src/setup/flows/ensure-vercel-project.test.ts
@@ -24,6 +24,7 @@ describe("ensureVercelProject", () => {
appRoot: "/project",
prompter,
signal: undefined,
+ allowLogin: false,
});
expect(readProjectLink).toHaveBeenCalledOnce();
});
diff --git a/packages/eve/src/setup/flows/ensure-vercel-project.ts b/packages/eve/src/setup/flows/ensure-vercel-project.ts
index d92b1bfdd..365e7ed00 100644
--- a/packages/eve/src/setup/flows/ensure-vercel-project.ts
+++ b/packages/eve/src/setup/flows/ensure-vercel-project.ts
@@ -34,6 +34,7 @@ export async function ensureVercelProject(input: {
appRoot: input.appRoot,
prompter: input.prompter,
signal: input.signal,
+ allowLogin: false,
});
if (login.kind === "cancelled") throw new WizardCancelledError();
if (login.kind !== "already" && login.kind !== "logged-in") {
diff --git a/packages/eve/src/setup/flows/install-vercel-cli.ts b/packages/eve/src/setup/flows/install-vercel-cli.ts
index eeb1b5aaa..50a0a8eaf 100644
--- a/packages/eve/src/setup/flows/install-vercel-cli.ts
+++ b/packages/eve/src/setup/flows/install-vercel-cli.ts
@@ -67,9 +67,8 @@ function summarizeUpgradeFailure(stderr: readonly string[]): string | undefined
}
/**
- * THE INSTALL FLOW for the dev TUI's `/vc:install`: the fix command for the
- * "Vercel CLI not found" diagnostic, so every diagnostic has a matching
- * command. Short-circuits when the CLI already resolves; otherwise runs a
+ * Prepares the Vercel CLI during deployment. Short-circuits when the CLI
+ * already resolves; otherwise runs a
* global install with the project's package manager, streaming output to the
* rail, then re-probes. A global install can exit clean yet leave the binary
* off PATH (pnpm/yarn global bins commonly aren't), so success is confirmed by
diff --git a/packages/eve/src/setup/flows/login-first-response.integration.test.ts b/packages/eve/src/setup/flows/login-first-response.integration.test.ts
new file mode 100644
index 000000000..786d29332
--- /dev/null
+++ b/packages/eve/src/setup/flows/login-first-response.integration.test.ts
@@ -0,0 +1,100 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { createFakePrompter } from "#internal/testing/fake-prompter.js";
+const state = vi.hoisted(() => ({
+ key: "",
+ model: vi.fn(),
+ selection: vi.fn(),
+ defaults: vi.fn(),
+}));
+vi.mock("#internal/model-auth/store.js", async (original) => ({
+ ...(await original<typeof import("#internal/model-auth/store.js")>()),
+ readModelSecret: async () => state.key,
+ writeModelSecret: async (_name: string, key: string) => {
+ state.key = key;
+ },
+ writeDefaultConnection: state.defaults,
+}));
+vi.mock("#setup/provider-settings.js", async (original) => ({
+ ...(await original<typeof import("#setup/provider-settings.js")>()),
+ writeProviderSelection: state.selection,
+}));
+vi.mock("#services/inspect-application.js", () => ({
+ inspectApplication: async () => ({
+ compiledState: {
+ manifest: {
+ config: { model: { id: "openai/gpt-5.6-luna-fast", routing: { kind: "gateway" } } },
+ },
+ },
+ }),
+}));
+vi.mock("./model-source-change.js", () => ({
+ readAuthoredModelSelection: async () => "openai/gpt-5.6-luna-fast",
+ changeValidatedAgentModel: state.model,
+}));
+import { runModelLogin } from "./model-login.js";
+import { openai } from "#public/models/openai/index.js";
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ vi.resetAllMocks();
+ state.key = "";
+});
+it("logs in and streams the first response without exposing the entered key", async () => {
+ vi.stubEnv("EVE_DEV", "1");
+ vi.stubEnv("OPENAI_API_KEY", "");
+ state.model.mockResolvedValue({ kind: "changed" });
+ const item = { type: "message", id: "msg_1", role: "assistant", content: [] };
+ const events = [
+ { type: "response.output_item.added", output_index: 0, item },
+ {
+ type: "response.output_text.delta",
+ item_id: "msg_1",
+ output_index: 0,
+ delta: "Hello Alice.",
+ },
+ { type: "response.output_item.done", output_index: 0, item },
+ {
+ type: "response.completed",
+ response: {
+ id: "resp_1",
+ created_at: 0,
+ model: "gpt-5.6-luna-fast",
+ status: "completed",
+ usage: { input_tokens: 3, output_tokens: 3 },
+ },
+ },
+ ];
+ const fetch = vi.fn(async (url: Parameters<typeof globalThis.fetch>[0], init?: RequestInit) => {
+ expect(new Headers(init?.headers).get("authorization")).toBe("Bearer fixture-key");
+ if (String(url).endsWith("/models"))
+ return Response.json({ data: [{ id: "gpt-5.6-luna-fast" }] });
+ expect(String(url)).toBe("https://api.openai.com/v1/responses");
+ expect(init?.body).not.toContain("fixture-key");
+ return new Response(events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), {
+ headers: { "content-type": "text/event-stream" },
+ });
+ });
+ vi.stubGlobal("fetch", fetch);
+ const fake = createFakePrompter({ single: () => "openai", password: () => "fixture-key" });
+ expect(await runModelLogin({ appRoot: "/fixture", prompter: fake.prompter })).toMatchObject({
+ kind: "ready",
+ reload: true,
+ });
+ expect(state.model).toHaveBeenCalledWith({
+ appRoot: "/fixture",
+ slug: "openai-api/gpt-5.6-luna-fast",
+ });
+ expect(state.defaults).toHaveBeenCalledWith("openai");
+ expect(JSON.stringify(fake)).not.toContain("fixture-key");
+ const model = openai();
+ if (typeof model === "string") throw new Error("Expected a model");
+ const response = await model.doStream({
+ prompt: [{ role: "user", content: [{ type: "text", text: "Hello" }] }],
+ });
+ let text = "";
+ for await (const event of response.stream) {
+ if (event.type === "error") throw event.error;
+ if (event.type === "text-delta") text += event.delta;
+ }
+ expect(text).toBe("Hello Alice.");
+});
diff --git a/packages/eve/src/setup/flows/login.test.ts b/packages/eve/src/setup/flows/login.test.ts
index bebc93849..c17b2a4a7 100644
--- a/packages/eve/src/setup/flows/login.test.ts
+++ b/packages/eve/src/setup/flows/login.test.ts
@@ -141,3 +141,16 @@ describe("runLoginFlow", () => {
expect(runVercelLogin.mock.calls[0]?.[0].signal?.aborted).toBe(true);
});
});
+
+it("does not start browser login when remote access only permits credential reuse", async () => {
+ const runVercelLogin = vi.fn(async () => true);
+ await expect(
+ runLoginFlow({
+ appRoot: APP_ROOT,
+ prompter: createFakePrompter().prompter,
+ allowLogin: false,
+ deps: { getVercelAuthStatus: authProbe("logged-out"), runVercelLogin },
+ }),
+ ).resolves.toEqual({ kind: "failed" });
+ expect(runVercelLogin).not.toHaveBeenCalled();
+});
diff --git a/packages/eve/src/setup/flows/login.ts b/packages/eve/src/setup/flows/login.ts
index 1e2405e5a..75f88a107 100644
--- a/packages/eve/src/setup/flows/login.ts
+++ b/packages/eve/src/setup/flows/login.ts
@@ -103,7 +103,7 @@ async function runVercelLoginWithControls(
}
/**
- * THE LOGIN FLOW for the dev TUI's `/vc:login`. Short-circuits when already
+ * THE LOGIN FLOW for the dev TUI's `/deploy`. Short-circuits when already
* authenticated; otherwise runs `vercel login` as a browser flow the TUI waits
* on (see {@link runVercelLoginWithControls}) and re-probes after, so a
* half-finished or abandoned login reports `failed`, never a false success.
@@ -113,6 +113,8 @@ export async function runLoginFlow(input: {
prompter: Prompter;
/** Run the browser login even when the account-level Vercel session is valid. */
force?: boolean;
+ /** False for remote access: reuse the existing session without opening a browser. */
+ allowLogin?: boolean;
signal?: AbortSignal;
deps?: Partial<LoginFlowDeps>;
}): Promise<LoginFlowResult> {
@@ -149,6 +151,8 @@ export async function runLoginFlow(input: {
}
}
+ if (input.allowLogin === false) return { kind: "failed" };
+
const outcome = await runVercelLoginWithControls(deps, appRoot, onOutput, prompter, signal);
if (outcome === "cancelled") return { kind: "cancelled" };
if (!outcome) return { kind: "failed" };
diff --git a/packages/eve/src/setup/flows/model-login-connection.ts b/packages/eve/src/setup/flows/model-login-connection.ts
new file mode 100644
index 000000000..a38464d34
--- /dev/null
+++ b/packages/eve/src/setup/flows/model-login-connection.ts
@@ -0,0 +1,130 @@
+import { getVercelOidcToken } from "#compiled/@vercel/oidc/index.js";
+import { availableDirectModels } from "#internal/model-auth/available-models.js";
+import {
+ modelKeySecretName,
+ readVercelSession,
+ writeModelSecret,
+ type ModelConnectionSelection,
+} from "#internal/model-auth/store.js";
+import { resolveModelApiKey } from "#internal/model-auth/transport.js";
+import {
+ readVercelCliConnection,
+ refreshVercelCliConnection,
+} from "#internal/model-auth/vercel-cli.js";
+import {
+ resolveVercelSession,
+ validateVercelAccess,
+ VERCEL_MODEL_CLIENT_ID,
+} from "#internal/model-auth/vercel.js";
+import { getDefaultCodexTokenBroker } from "#public/models/openai/chatgpt/token-broker.js";
+import type { Prompter } from "#setup/prompter.js";
+import { withLoginProgress } from "./model-login-progress.js";
+import { validateGatewayApiKey } from "#setup/validate-gateway-key.js";
+import { ensureChatGptAuth } from "./chatgpt-auth.js";
+import { loginVercelModel } from "./vercel-model-login.js";
+
+export const CONNECTION_OPTIONS = [
+ { value: "vercel", label: "Vercel Account" },
+ { value: "ai-gateway-key", label: "Vercel AI Gateway API Key" },
+ { value: "chatgpt", label: "ChatGPT Subscription" },
+ { value: "openai", label: "OpenAI API Key" },
+ { value: "anthropic", label: "Anthropic API Key" },
+] as const;
+
+type Team = { teamId: string; teamName: string };
+
+/** Evidence from this login attempt; credentials stay with their existing owner. */
+export interface ValidatedModelConnection {
+ selected: ModelConnectionSelection;
+ team?: Team;
+ availableModels?: string[];
+}
+
+export async function reuseModelConnection(
+ selected: ModelConnectionSelection,
+ team: Team | undefined,
+ signal?: AbortSignal,
+): Promise<ValidatedModelConnection | undefined> {
+ switch (selected) {
+ case "chatgpt":
+ return (await getDefaultCodexTokenBroker().refreshState()).kind === "ready"
+ ? { selected }
+ : undefined;
+ case "vercel": {
+ if (!(await readVercelSession(VERCEL_MODEL_CLIENT_ID))) return undefined;
+ const session = await resolveVercelSession();
+ team ??= { teamId: session.teamId, teamName: session.teamName };
+ await validateVercelAccess(session.accessToken, team.teamId, signal);
+ return { selected, team };
+ }
+ case "vercel-cli": {
+ let cli = await readVercelCliConnection();
+ if (!cli) return undefined;
+ team ??= { teamId: cli.teamId, teamName: cli.teamId };
+ try {
+ await validateVercelAccess(cli.token, team.teamId, signal);
+ } catch {
+ signal?.throwIfAborted();
+ await refreshVercelCliConnection();
+ cli = await readVercelCliConnection();
+ if (!cli) return undefined;
+ await validateVercelAccess(cli.token, team.teamId, signal);
+ }
+ return { selected, team };
+ }
+ case "ai-gateway-project":
+ return (await getVercelOidcToken().catch(() => undefined)) ? { selected } : undefined;
+ case "ai-gateway-key": {
+ const key = await resolveModelApiKey(selected);
+ return (await validateGatewayApiKey(key, signal)).kind === "valid" ? { selected } : undefined;
+ }
+ case "openai":
+ case "anthropic":
+ return {
+ selected,
+ availableModels: await availableDirectModels(
+ selected,
+ await resolveModelApiKey(selected),
+ signal,
+ ),
+ };
+ }
+}
+
+export async function authenticateModelConnection(input: {
+ selected: ModelConnectionSelection;
+ team?: Team;
+ prompter: Prompter;
+ signal?: AbortSignal;
+}): Promise<ValidatedModelConnection> {
+ const { selected, prompter, signal } = input;
+ if (selected === "vercel") {
+ return { selected, team: await loginVercelModel(prompter, signal, input.team?.teamId) };
+ }
+ if (selected === "chatgpt") {
+ await ensureChatGptAuth({ signal, log: (message) => prompter.log.info(message) });
+ return { selected };
+ }
+ if (selected === "vercel-cli" || selected === "ai-gateway-project") {
+ throw new Error("Choose a connection with /login.");
+ }
+ const label = CONNECTION_OPTIONS.find((option) => option.value === selected)!.label;
+ const key = (
+ await prompter.password({
+ message: label,
+ validate: (value) => (value.trim() ? undefined : "Enter an API key."),
+ })
+ ).trim();
+ const availableModels = await withLoginProgress(prompter, `Checking ${label}…`, async () => {
+ if (selected !== "ai-gateway-key") return availableDirectModels(selected, key, signal);
+ if ((await validateGatewayApiKey(key, signal)).kind !== "valid") {
+ throw new Error(
+ "Could not validate the Gateway key. Check the key and your connection, then retry.",
+ );
+ }
+ return undefined;
+ });
+ signal?.throwIfAborted();
+ await writeModelSecret(modelKeySecretName(selected), key);
+ return { selected, availableModels };
+}
diff --git a/packages/eve/src/setup/flows/model-login-progress.ts b/packages/eve/src/setup/flows/model-login-progress.ts
new file mode 100644
index 000000000..cd28e34e6
--- /dev/null
+++ b/packages/eve/src/setup/flows/model-login-progress.ts
@@ -0,0 +1,26 @@
+import type { Prompter } from "#setup/prompter.js";
+import { withSpinner } from "#setup/with-spinner.js";
+import { createLogger } from "#internal/logging.js";
+
+const log = createLogger("setup.model-login");
+
+type LoginStage = "source_inspection" | "gateway_catalog" | "authentication" | "activation";
+
+/** Fixed stage names and durations only: no credentials, team names, or provider responses. */
+export async function measureLoginStage<T>(stage: LoginStage, task: () => Promise<T>): Promise<T> {
+ const started = performance.now();
+ try {
+ return await task();
+ } finally {
+ log.debug(stage, { elapsedMs: Math.round(performance.now() - started) });
+ }
+}
+
+/** Avoid painting a loading phase for quick local work. */
+export function withLoginProgress<T>(
+ prompter: Prompter,
+ message: string,
+ task: () => Promise<T>,
+): Promise<T> {
+ return withSpinner(prompter, message, task, 150);
+}
diff --git a/packages/eve/src/setup/flows/model-login.test.ts b/packages/eve/src/setup/flows/model-login.test.ts
new file mode 100644
index 000000000..006166efb
--- /dev/null
+++ b/packages/eve/src/setup/flows/model-login.test.ts
@@ -0,0 +1,464 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createFakePrompter } from "#internal/testing/fake-prompter.js";
+import { WizardCancelledError } from "#setup/step.js";
+const mocks = vi.hoisted(() => ({
+ readSelection: vi.fn(),
+ team: vi.fn(),
+ readDefault: vi.fn(),
+ readSecret: vi.fn(),
+ readSession: vi.fn(),
+ writeSecret: vi.fn(),
+ writeSelection: vi.fn(),
+ writeDefault: vi.fn(),
+ inspect: vi.fn(),
+ change: vi.fn(),
+ authored: vi.fn(),
+ cli: vi.fn(),
+ validate: vi.fn(),
+ session: vi.fn(),
+ chatgpt: vi.fn(),
+ chatgptState: vi.fn(),
+ oauth: vi.fn(),
+ models: vi.fn(),
+ gateway: vi.fn(),
+ settingsMatch: vi.fn(),
+ catalog: vi.fn(),
+}));
+vi.mock("#setup/provider-settings.js", () => ({
+ providerSettingsMatch: mocks.settingsMatch,
+ readProviderSelection: mocks.readSelection,
+ readProviderTeamSync: mocks.team,
+ readProviderKeySourceSync: vi.fn(),
+ writeProviderSelection: mocks.writeSelection,
+ resolveAvailableProviders: vi.fn(async () => []),
+}));
+vi.mock("#internal/model-auth/store.js", async (original) => ({
+ ...(await original<typeof import("#internal/model-auth/store.js")>()),
+ readDefaultConnection: mocks.readDefault,
+ readModelSecret: mocks.readSecret,
+ readVercelSession: mocks.readSession,
+ writeModelSecret: mocks.writeSecret,
+ writeDefaultConnection: mocks.writeDefault,
+}));
+vi.mock("#services/inspect-application.js", () => ({ inspectApplication: mocks.inspect }));
+vi.mock("./model-source-change.js", () => ({
+ changeValidatedAgentModel: mocks.change,
+ readAuthoredModelSelection: mocks.authored,
+}));
+vi.mock("#internal/model-auth/vercel-cli.js", () => ({ readVercelCliConnection: mocks.cli }));
+vi.mock("#internal/model-auth/vercel.js", () => ({
+ authJson: mocks.models,
+ resolveVercelSession: mocks.session,
+ validateVercelAccess: mocks.validate,
+ VERCEL_MODEL_CLIENT_ID: "client-id",
+}));
+vi.mock("./chatgpt-auth.js", () => ({ ensureChatGptAuth: mocks.chatgpt }));
+vi.mock("./vercel-model-login.js", () => ({ loginVercelModel: mocks.oauth }));
+vi.mock("#public/models/openai/chatgpt/token-broker.js", () => ({
+ getDefaultCodexTokenBroker: () => ({
+ refreshState: mocks.chatgptState,
+ getToken: async () => ({ token: "chat-token" }),
+ }),
+}));
+vi.mock("../boxes/select-model.js", () => ({
+ fetchGatewayCatalog: mocks.catalog,
+}));
+vi.mock("#setup/validate-gateway-key.js", () => ({ validateGatewayApiKey: mocks.gateway }));
+import { environmentConnection, runModelLogin } from "./model-login.js";
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.stubEnv("EVE_DEV", "1");
+ for (const key of [
+ "OPENAI_API_KEY",
+ "ANTHROPIC_API_KEY",
+ "AI_GATEWAY_API_KEY",
+ "VERCEL_OIDC_TOKEN",
+ ])
+ vi.stubEnv(key, "");
+ mocks.inspect.mockResolvedValue({
+ compiledState: {
+ manifest: {
+ config: {
+ model: { id: "openai/gpt-5.6-luna-fast", routing: { kind: "gateway", target: "openai" } },
+ },
+ },
+ },
+ });
+ vi.stubEnv("EVE_MODEL_TEAM", undefined);
+ vi.stubEnv("EVE_MODEL_KEY_SOURCE", undefined);
+ vi.stubEnv("EVE_MODEL_CONNECTION", undefined);
+ mocks.session.mockResolvedValue({ accessToken: "access", teamId: "team_123", teamName: "Alice" });
+ mocks.readSession.mockResolvedValue({ refreshToken: "refresh" });
+ mocks.authored.mockResolvedValue("openai/gpt-5.6-luna-fast");
+ mocks.oauth.mockResolvedValue({ teamId: "team_123", teamName: "Alice" });
+ mocks.catalog.mockResolvedValue([{ id: "openai/gpt-5.6-luna-fast", type: "language" }]);
+ mocks.change.mockResolvedValue({ kind: "changed" });
+ mocks.readSecret.mockResolvedValue("stored-key");
+ mocks.models.mockResolvedValue({
+ data: [{ id: "gpt-5.6-luna-fast" }, { id: "claude-sonnet-5" }],
+ models: [{ slug: "gpt-5.6-luna-fast" }],
+ });
+ mocks.gateway.mockResolvedValue({ kind: "valid" });
+ mocks.chatgptState.mockResolvedValue({ kind: "ready", reload: true });
+});
+
+describe("model login", () => {
+ it.each(["vercel", "ai-gateway-key", "chatgpt", "openai", "anthropic"])(
+ "connects %s and returns directly to chat",
+ async (selected) => {
+ const fake = createFakePrompter({ single: () => selected, password: () => "new-key" });
+ expect(await runModelLogin({ appRoot: "/agent", prompter: fake.prompter })).toMatchObject({
+ kind: "ready",
+ reload: ["openai", "anthropic", "chatgpt"].includes(selected),
+ });
+ expect(fake.selectMessages).toEqual(["Choose a connection"]);
+ expect(mocks.writeSelection.mock.calls[0]?.slice(0, 2)).toEqual(["/agent", selected]);
+ expect(mocks.writeDefault).toHaveBeenCalledWith(selected);
+ if (["openai", "anthropic", "ai-gateway-key"].includes(selected))
+ expect(mocks.writeSecret).toHaveBeenCalledWith(
+ selected === "ai-gateway-key" ? selected : `${selected}-key`,
+ "new-key",
+ );
+ if (selected === "vercel") expect(mocks.oauth).toHaveBeenCalledOnce();
+ if (selected === "chatgpt") expect(mocks.chatgpt).toHaveBeenCalledOnce();
+ },
+ );
+ it("reuses the CLI team without any prompts or project linking", async () => {
+ mocks.cli.mockResolvedValue({ token: "cli-token", teamId: "team_123" });
+ const fake = createFakePrompter();
+ expect(
+ await runModelLogin({ appRoot: "/agent", prompter: fake.prompter, automatic: true }),
+ ).toMatchObject({ kind: "ready", reload: false });
+ expect(fake.selectMessages).toEqual([]);
+ expect(mocks.validate).toHaveBeenCalledWith("cli-token", "team_123", expect.any(AbortSignal));
+ expect(mocks.writeSecret).not.toHaveBeenCalled();
+ });
+ it("keeps project selection ahead of environment and machine preferences", async () => {
+ mocks.readSelection.mockResolvedValue("chatgpt");
+ vi.stubEnv("AI_GATEWAY_API_KEY", "explicit-key");
+ mocks.readDefault.mockResolvedValue("vercel");
+ await runModelLogin({
+ appRoot: "/agent",
+ prompter: createFakePrompter().prompter,
+ automatic: true,
+ });
+ expect(mocks.writeSelection).toHaveBeenCalledWith("/agent", "chatgpt", undefined, undefined);
+ expect(mocks.cli).not.toHaveBeenCalled();
+ });
+ it("returns to the composer on cancellation without replacing a broken explicit connection", async () => {
+ mocks.readSelection.mockResolvedValue("vercel");
+ mocks.session.mockRejectedValue(new Error("expired"));
+ const fake = createFakePrompter({
+ single: () => {
+ throw new WizardCancelledError();
+ },
+ });
+ expect(
+ await runModelLogin({ appRoot: "/agent", prompter: fake.prompter, automatic: true }),
+ ).toEqual({ kind: "cancelled" });
+ expect(mocks.cli).not.toHaveBeenCalled();
+ expect(mocks.writeSelection).not.toHaveBeenCalled();
+ });
+ it("opens login without warning when a saved Vercel session belongs to another client", async () => {
+ mocks.readSelection.mockResolvedValue("vercel");
+ mocks.readSession.mockResolvedValue(undefined);
+ const fake = createFakePrompter({
+ single: () => {
+ throw new WizardCancelledError();
+ },
+ });
+ expect(
+ await runModelLogin({ appRoot: "/agent", prompter: fake.prompter, automatic: true }),
+ ).toEqual({ kind: "cancelled" });
+ expect(fake.prompter.log.warning).not.toHaveBeenCalled();
+ expect(mocks.session).not.toHaveBeenCalled();
+ });
+ it("does not save a rejected key", async () => {
+ mocks.gateway.mockResolvedValue({ kind: "invalid" });
+ let calls = 0;
+ const fake = createFakePrompter({
+ single: () => {
+ if (calls++) throw new WizardCancelledError();
+ return "ai-gateway-key";
+ },
+ password: () => "bad-key",
+ });
+ expect(await runModelLogin({ appRoot: "/agent", prompter: fake.prompter })).toEqual({
+ kind: "cancelled",
+ });
+ expect(mocks.writeSecret).not.toHaveBeenCalled();
+ });
+ it("asks for an available model if the preferred model is unavailable", async () => {
+ mocks.models.mockResolvedValue({ data: [{ id: "available-model" }] });
+ const answers = ["openai", "available-model"];
+ const fake = createFakePrompter({ single: () => answers.shift()!, password: () => "new-key" });
+ await runModelLogin({ appRoot: "/agent", prompter: fake.prompter });
+ expect(mocks.change).toHaveBeenCalledWith({
+ appRoot: "/agent",
+ slug: "openai-api/available-model",
+ });
+ });
+ it("reuses the machine default without a connection picker", async () => {
+ mocks.readDefault.mockResolvedValue("chatgpt");
+ const fake = createFakePrompter();
+ expect(
+ await runModelLogin({ appRoot: "/agent", prompter: fake.prompter, automatic: true }),
+ ).toMatchObject({ kind: "ready", reload: true });
+ expect(fake.selectMessages).toEqual([]);
+ expect(mocks.cli).not.toHaveBeenCalled();
+ });
+ it("preserves the project's team when the CLI has switched teams", async () => {
+ mocks.readSelection.mockResolvedValue("vercel-cli");
+ mocks.team.mockReturnValue({ teamId: "team_project", teamName: "Project team" });
+ mocks.cli.mockResolvedValue({ token: "cli-token", teamId: "team_other" });
+ vi.stubEnv("EVE_MODEL_TEAM", "team_project");
+ const fake = createFakePrompter();
+ expect(
+ await runModelLogin({ appRoot: "/agent", prompter: fake.prompter, automatic: true }),
+ ).toMatchObject({ kind: "ready", reload: false });
+ expect(mocks.validate).toHaveBeenCalledWith(
+ "cli-token",
+ "team_project",
+ expect.any(AbortSignal),
+ );
+ expect(mocks.writeSelection).toHaveBeenCalledWith(
+ "/agent",
+ "vercel-cli",
+ {
+ teamId: "team_project",
+ teamName: "Project team",
+ },
+ undefined,
+ );
+ });
+ it("returns to chat when key entry is cancelled", async () => {
+ const fake = createFakePrompter({
+ single: () => "openai",
+ password: () => {
+ throw new WizardCancelledError();
+ },
+ });
+ expect(await runModelLogin({ appRoot: "/agent", prompter: fake.prompter })).toEqual({
+ kind: "cancelled",
+ });
+ expect(mocks.writeSelection).not.toHaveBeenCalled();
+ });
+ it("keeps the selected connection intact when secure storage is unavailable", async () => {
+ mocks.writeSecret.mockRejectedValue(new Error("Unlock the OS secret store and retry /login."));
+ let picks = 0;
+ const fake = createFakePrompter({
+ single: () => {
+ if (picks++) throw new WizardCancelledError();
+ return "openai";
+ },
+ password: () => "key",
+ });
+ expect(await runModelLogin({ appRoot: "/agent", prompter: fake.prompter })).toEqual({
+ kind: "cancelled",
+ });
+ expect(mocks.writeSelection).not.toHaveBeenCalled();
+ expect(mocks.change).not.toHaveBeenCalled();
+ });
+ it("honors explicit environment credentials in a deterministic order", () => {
+ expect(environmentConnection({ OPENAI_API_KEY: "openai" })).toBe("openai");
+ expect(environmentConnection({ ANTHROPIC_API_KEY: "anthropic" })).toBe("anthropic");
+ expect(environmentConnection({ AI_GATEWAY_API_KEY: "gateway", OPENAI_API_KEY: "openai" })).toBe(
+ "ai-gateway-key",
+ );
+ });
+});
+
+afterEach(() => vi.unstubAllEnvs());
+
+it.each(["openai", "anthropic"] as const)(
+ "does not mistake a foreign %s model for an eve helper",
+ async (provider) => {
+ mocks.authored.mockResolvedValue(undefined);
+ mocks.inspect.mockResolvedValue({
+ compiledState: {
+ manifest: {
+ config: {
+ model: { id: "custom-model", source: {}, routing: { kind: "external", provider } },
+ },
+ },
+ },
+ });
+ mocks.change.mockResolvedValue({
+ kind: "rejected",
+ message: "Model is not an eve helper. Edit agent.ts.",
+ });
+ let attempts = 0;
+ const fake = createFakePrompter({
+ single: () => {
+ if (attempts++) throw new WizardCancelledError();
+ return provider;
+ },
+ password: () => "new-key",
+ });
+ await expect(runModelLogin({ appRoot: "/agent", prompter: fake.prompter })).resolves.toEqual({
+ kind: "cancelled",
+ });
+ expect(mocks.change).toHaveBeenCalledOnce();
+ expect(mocks.writeSelection).not.toHaveBeenCalled();
+ expect(mocks.writeDefault).not.toHaveBeenCalled();
+ },
+);
+it("preserves an explicitly authored eve helper's compatible custom model", async () => {
+ mocks.inspect.mockResolvedValue({
+ compiledState: {
+ manifest: {
+ config: {
+ model: {
+ id: "custom-model",
+ source: {},
+ routing: { kind: "external", provider: "openai" },
+ },
+ },
+ },
+ },
+ });
+ mocks.authored.mockResolvedValue("openai-api/custom-model");
+ const fake = createFakePrompter({ single: () => "openai", password: () => "new-key" });
+ await expect(
+ runModelLogin({ appRoot: "/agent", prompter: fake.prompter }),
+ ).resolves.toMatchObject({
+ kind: "ready",
+ reload: false,
+ });
+ expect(mocks.change).not.toHaveBeenCalled();
+});
+
+it("reuses CLI validation and source inspection exactly once", async () => {
+ mocks.cli.mockResolvedValue({ token: "cli-token", teamId: "team_123" });
+ await runModelLogin({
+ appRoot: "/agent",
+ automatic: true,
+ prompter: createFakePrompter().prompter,
+ });
+ expect(mocks.validate).toHaveBeenCalledOnce();
+ expect(mocks.cli).toHaveBeenCalledOnce();
+ expect(mocks.authored).toHaveBeenCalledOnce();
+ expect(mocks.inspect).not.toHaveBeenCalled();
+ expect(mocks.catalog).toHaveBeenCalledOnce();
+});
+
+it.each(["openai", "anthropic"] as const)(
+ "retains %s models from automatic credential validation",
+ async (selected) => {
+ mocks.readSelection.mockResolvedValue(selected);
+ await runModelLogin({
+ appRoot: "/agent",
+ automatic: true,
+ prompter: createFakePrompter().prompter,
+ });
+ expect(mocks.models).toHaveBeenCalledOnce();
+ expect(mocks.inspect).not.toHaveBeenCalled();
+ },
+);
+
+it("overlaps Gateway catalog loading with OAuth and does not validate the returned team again", async () => {
+ const oauth = Promise.withResolvers<{ teamId: string; teamName: string }>();
+ const catalogStarted = Promise.withResolvers<void>();
+ mocks.oauth.mockReturnValue(oauth.promise);
+ mocks.catalog.mockImplementation(async () => {
+ catalogStarted.resolve();
+ return [{ id: "openai/gpt-5.6-luna-fast", type: "language" }];
+ });
+ const result = runModelLogin({
+ appRoot: "/agent",
+ prompter: createFakePrompter({ single: () => "vercel" }).prompter,
+ });
+ await catalogStarted.promise;
+ expect(mocks.oauth).toHaveBeenCalledOnce();
+ expect(mocks.writeSelection).not.toHaveBeenCalled();
+ oauth.resolve({ teamId: "team_selected", teamName: "Selected" });
+ await result;
+ expect(mocks.writeSelection).toHaveBeenCalledWith(
+ "/agent",
+ "vercel",
+ { teamId: "team_selected", teamName: "Selected" },
+ undefined,
+ );
+ expect(mocks.session).not.toHaveBeenCalled();
+ expect(mocks.validate).not.toHaveBeenCalled();
+});
+
+it("leaves an unchanged connection alone", async () => {
+ mocks.readSelection.mockResolvedValue("vercel-cli");
+ mocks.settingsMatch.mockResolvedValue(true);
+ mocks.cli.mockResolvedValue({ token: "cli-token", teamId: "team_123" });
+ const withConnectionUpdate = vi.fn();
+ await expect(
+ runModelLogin({
+ appRoot: "/agent",
+ automatic: true,
+ prompter: createFakePrompter().prompter,
+ withConnectionUpdate,
+ }),
+ ).resolves.toMatchObject({ kind: "ready", reload: false });
+ expect(mocks.change).not.toHaveBeenCalled();
+ expect(mocks.writeSelection).not.toHaveBeenCalled();
+ expect(withConnectionUpdate).not.toHaveBeenCalled();
+});
+
+it("waits for a single runtime activation before reporting a changed connection ready", async () => {
+ const activation = Promise.withResolvers<void>();
+ const written = Promise.withResolvers<void>();
+ const withConnectionUpdate = vi.fn(async (task: () => Promise<void>): Promise<void> => {
+ await task();
+ written.resolve();
+ await activation.promise;
+ });
+ let ready = false;
+ const result = runModelLogin({
+ appRoot: "/agent",
+ prompter: createFakePrompter({ single: () => "openai", password: () => "key" }).prompter,
+ withConnectionUpdate,
+ }).then((value) => {
+ ready = true;
+ return value;
+ });
+ await written.promise;
+ expect(ready).toBe(false);
+ expect(mocks.change).toHaveBeenCalledOnce();
+ expect(mocks.writeSelection).toHaveBeenCalledOnce();
+ activation.resolve();
+ expect(await result).toMatchObject({ kind: "ready", reload: false });
+ expect(withConnectionUpdate).toHaveBeenCalledOnce();
+});
+
+it("does not save a connection when an overlapping catalog request fails", async () => {
+ mocks.catalog.mockRejectedValue(new Error("Gateway is unavailable."));
+ let picks = 0;
+ const prompter = createFakePrompter({
+ single: () => {
+ if (picks++) throw new WizardCancelledError();
+ return "vercel";
+ },
+ }).prompter;
+ expect(await runModelLogin({ appRoot: "/agent", prompter })).toEqual({ kind: "cancelled" });
+ expect(mocks.writeSelection).not.toHaveBeenCalled();
+ expect(mocks.writeDefault).not.toHaveBeenCalled();
+});
+
+it("changes teams without recompiling an unchanged Gateway model", async () => {
+ const withConnectionUpdate = vi.fn();
+ mocks.settingsMatch.mockResolvedValue(false);
+ const result = await runModelLogin({
+ appRoot: "/agent",
+ withConnectionUpdate,
+ prompter: createFakePrompter({ single: () => "vercel" }).prompter,
+ });
+ expect(result).toMatchObject({
+ kind: "ready",
+ reload: false,
+ model: {
+ id: "openai/gpt-5.6-luna-fast",
+ endpoint: { kind: "gateway", connected: true, credential: "oauth", team: "Alice" },
+ },
+ });
+ expect(mocks.writeSelection).toHaveBeenCalledOnce();
+ expect(mocks.change).not.toHaveBeenCalled();
+ expect(withConnectionUpdate).not.toHaveBeenCalled();
+});
diff --git a/packages/eve/src/setup/flows/model-login.ts b/packages/eve/src/setup/flows/model-login.ts
new file mode 100644
index 000000000..e638d43ba
--- /dev/null
+++ b/packages/eve/src/setup/flows/model-login.ts
@@ -0,0 +1,314 @@
+import { resolveModelEndpointStatus } from "#internal/resolve-model-endpoint-status.js";
+import { classifyModelRouting } from "#internal/classify-model-routing.js";
+import type { ConnectedModel } from "#shared/model-connection.js";
+import { measureLoginStage, withLoginProgress } from "./model-login-progress.js";
+import { availableHelperModels } from "#internal/model-auth/available-models.js";
+import { fetchGatewayCatalog } from "../boxes/select-model.js";
+import { inspectApplication } from "#services/inspect-application.js";
+import {
+ isModelConnection,
+ readDefaultConnection,
+ writeDefaultConnection,
+ type ModelConnectionSelection,
+} from "#internal/model-auth/store.js";
+import { MODEL_CONNECTION_ENV } from "#internal/model-auth/transport.js";
+import { parseModelHelper, MODEL_HELPERS } from "#shared/model-helper.js";
+import {
+ readProviderSelection,
+ readProviderTeamSync,
+ readProviderKeySourceSync,
+ resolveAvailableProviders,
+ writeProviderSelection,
+ providerSettingsMatch,
+ type ProviderSettings,
+} from "#setup/provider-settings.js";
+import type { Prompter } from "#setup/prompter.js";
+import { WizardCancelledError } from "#setup/step.js";
+import { changeValidatedAgentModel, readAuthoredModelSelection } from "./model-source-change.js";
+import {
+ authenticateModelConnection,
+ CONNECTION_OPTIONS,
+ reuseModelConnection,
+ type ValidatedModelConnection,
+} from "./model-login-connection.js";
+
+export function environmentConnection(
+ env: Record<string, string | undefined>,
+): ModelConnectionSelection | undefined {
+ if (env.AI_GATEWAY_API_KEY?.trim()) return "ai-gateway-key";
+ if (env.VERCEL_OIDC_TOKEN?.trim()) return "ai-gateway-project";
+ if (env.OPENAI_API_KEY?.trim()) return "openai";
+ if (env.ANTHROPIC_API_KEY?.trim()) return "anthropic";
+ return undefined;
+}
+
+interface LoginModel {
+ selection?: string;
+ external: boolean;
+}
+
+async function readLoginModel(agentRoot: string): Promise<LoginModel> {
+ const selection = await readAuthoredModelSelection(agentRoot);
+ if (selection !== undefined)
+ return { selection, external: parseModelHelper(selection) !== undefined };
+ // Dynamic models still need routing inspection, but ordinary source literals
+ // and eve helpers do not need to compile the agent just to sign in.
+ const inspection = await inspectApplication(agentRoot);
+ const model = inspection.compiledState?.manifest.config.model;
+ return {
+ selection:
+ model?.routing.kind === "gateway" && model.source === undefined ? model.id : undefined,
+ external: model?.routing.kind === "external",
+ };
+}
+
+function modelSelection(selected: ModelConnectionSelection, model: LoginModel) {
+ const helper =
+ selected === "chatgpt" || selected === "openai" || selected === "anthropic"
+ ? selected
+ : undefined;
+ const authored = model.selection === undefined ? undefined : parseModelHelper(model.selection);
+ const compatible = helper
+ ? authored?.helper === helper
+ : model.selection !== undefined && !model.external;
+ const defaultId = helper ? MODEL_HELPERS[helper].defaultModel : "openai/gpt-5.6-luna-fast";
+ const currentId = authored?.id ?? model.selection;
+ return { helper, compatible, defaultId, needsModels: !compatible || currentId === defaultId };
+}
+
+type LoginInput = {
+ appRoot: string;
+ agentRoot?: string;
+ prompter: Prompter;
+ automatic?: boolean;
+ signal?: AbortSignal;
+ /** Applies writes under one watcher lease and waits for runtime activation. */
+ withConnectionUpdate?(task: () => Promise<void>): Promise<void>;
+};
+
+export type ModelLoginResult =
+ | { kind: "ready"; reload: boolean; model?: ConnectedModel }
+ | { kind: "cancelled" };
+
+async function applyConnection(
+ input: LoginInput,
+ connection: ValidatedModelConnection,
+ model: LoginModel,
+ models: string[] | undefined,
+): Promise<ModelLoginResult> {
+ const { appRoot, prompter, signal } = input;
+ const { selected, team } = connection;
+ const { helper, compatible, defaultId, needsModels } = modelSelection(selected, model);
+ let slug: string | undefined;
+ if (needsModels) {
+ const available =
+ connection.availableModels ??
+ models ??
+ (helper
+ ? await withLoginProgress(prompter, "Loading available models…", () =>
+ availableHelperModels(helper, signal),
+ )
+ : []);
+ let id = defaultId;
+ if (!available.includes(id)) {
+ if (available.length === 0)
+ throw new Error(
+ "No models are available for this connection. Choose another connection with /login.",
+ );
+ id = await prompter.select({
+ message: "Choose an available model",
+ search: true,
+ options: available.map((id) => ({ value: id, label: id })),
+ });
+ }
+ const next = helper ? MODEL_HELPERS[helper].prefix + id : id;
+ if (!compatible || next !== model.selection) slug = next;
+ }
+ const keyConnection =
+ selected === "openai" || selected === "anthropic" || selected === "ai-gateway-key";
+ const keySource = !keyConnection
+ ? undefined
+ : input.automatic
+ ? (readProviderKeySourceSync(appRoot) ??
+ (environmentConnection(process.env) === selected ? "environment" : "secret"))
+ : "secret";
+ const settings: ProviderSettings = { selected, ...team, keySource };
+ const settingsChanged = !(await providerSettingsMatch(appRoot, settings));
+ const save = async () => {
+ signal?.throwIfAborted();
+ if (slug !== undefined) {
+ const outcome = await changeValidatedAgentModel({
+ appRoot: input.agentRoot ?? appRoot,
+ slug,
+ });
+ if (outcome.kind === "rejected") throw new Error(outcome.message);
+ }
+ if (settingsChanged) await writeProviderSelection(appRoot, selected, team, keySource);
+ process.env[MODEL_CONNECTION_ENV] = selected;
+ if (keySource) process.env.EVE_MODEL_KEY_SOURCE = keySource;
+ else delete process.env.EVE_MODEL_KEY_SOURCE;
+ if (team) {
+ process.env.EVE_MODEL_TEAM = team.teamId;
+ process.env.EVE_MODEL_TEAM_NAME = team.teamName;
+ } else {
+ delete process.env.EVE_MODEL_TEAM;
+ delete process.env.EVE_MODEL_TEAM_NAME;
+ }
+ };
+ if (slug !== undefined) {
+ await withLoginProgress(prompter, "Loading selected model…", () =>
+ measureLoginStage("activation", () =>
+ input.withConnectionUpdate ? input.withConnectionUpdate(save) : save(),
+ ),
+ );
+ } else await save();
+ if (!input.automatic) await writeDefaultConnection(selected);
+ const selection = slug ?? model.selection;
+ const id = helper && selection ? parseModelHelper(selection)?.id : selection;
+ let connectedModel: ConnectedModel | undefined;
+ if (id) {
+ const routing = helper
+ ? { kind: "external" as const, provider: MODEL_HELPERS[helper].provider }
+ : classifyModelRouting(id);
+ connectedModel = {
+ id,
+ routing,
+ endpoint: resolveModelEndpointStatus(
+ routing,
+ {
+ apiKey: selected === "ai-gateway-key",
+ oidc: selected === "ai-gateway-project",
+ account: selected === "vercel" || selected === "vercel-cli",
+ team: team?.teamName,
+ },
+ { state: "ready" },
+ ),
+ };
+ }
+ return {
+ kind: "ready",
+ reload: slug !== undefined && input.withConnectionUpdate === undefined,
+ ...(connectedModel && { model: connectedModel }),
+ };
+}
+
+export async function runModelLogin(input: LoginInput): Promise<ModelLoginResult> {
+ const { appRoot, prompter, signal } = input;
+ let modelPromise: Promise<LoginModel> | undefined;
+ const getModel = () =>
+ (modelPromise ??= measureLoginStage("source_inspection", () =>
+ readLoginModel(input.agentRoot ?? appRoot),
+ ));
+
+ const connect = async (
+ selected: ModelConnectionSelection,
+ automatic: boolean,
+ ): Promise<ModelLoginResult | undefined> => {
+ const controller = new AbortController();
+ const attemptSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
+ // Public catalog work can overlap browser sign-in. Capture its failure so
+ // it cannot abandon an active prompt or become an unhandled rejection.
+ const preparation = getModel()
+ .then(async (model) => {
+ const selection = modelSelection(selected, model);
+ const models =
+ !selection.helper && selection.needsModels
+ ? (await measureLoginStage("gateway_catalog", () => fetchGatewayCatalog(attemptSignal)))
+ .filter((model) => model.type === "language")
+ .map((model) => model.id)
+ : undefined;
+ return { model, models };
+ })
+ .then(
+ (value) => ({ value }),
+ (error) => ({ error }),
+ );
+ try {
+ const team = readProviderTeamSync(appRoot);
+ const connection = await measureLoginStage("authentication", async () =>
+ automatic
+ ? await withLoginProgress(prompter, "Checking model access…", () =>
+ reuseModelConnection(selected, team, attemptSignal),
+ )
+ : await authenticateModelConnection({ selected, team, prompter, signal: attemptSignal }),
+ );
+ if (!connection) return undefined;
+ const prepared = await withLoginProgress(
+ prompter,
+ "Loading available models…",
+ () => preparation,
+ );
+ if ("error" in prepared) throw prepared.error;
+ return await applyConnection(
+ { ...input, automatic, signal: attemptSignal },
+ connection,
+ prepared.value.model,
+ prepared.value.models,
+ );
+ } finally {
+ controller.abort();
+ }
+ };
+
+ try {
+ if (input.automatic) {
+ const { model, selected } = await withLoginProgress(
+ prompter,
+ "Reading saved connection…",
+ async () => {
+ const [model, existing, available, machineDefault] = await Promise.all([
+ getModel(),
+ readProviderSelection(appRoot),
+ resolveAvailableProviders(appRoot),
+ readDefaultConnection(),
+ ]);
+ const authoredHelper =
+ model.selection === undefined ? undefined : parseModelHelper(model.selection)?.helper;
+ return {
+ model,
+ selected:
+ existing ??
+ authoredHelper ??
+ environmentConnection(process.env) ??
+ (available.includes("ai-gateway-project") ? "ai-gateway-project" : undefined) ??
+ machineDefault ??
+ ("vercel-cli" as const),
+ };
+ },
+ );
+ if (model.external && model.selection === undefined) return { kind: "ready", reload: false };
+ try {
+ const result = await connect(selected, true);
+ if (result) return result;
+ } catch (error) {
+ modelPromise = undefined;
+ signal?.throwIfAborted();
+ prompter.log.warning(
+ error instanceof Error ? error.message : "Could not connect automatically. Retry /login.",
+ );
+ }
+ }
+ while (true) {
+ const selected = await prompter.select({
+ message: "Choose a connection",
+ search: true,
+ options: [...CONNECTION_OPTIONS],
+ });
+ if (!isModelConnection(selected)) throw new Error("Choose a model connection.");
+ try {
+ const result = await connect(selected, false);
+ if (result) return result;
+ } catch (error) {
+ modelPromise = undefined;
+ if (error instanceof WizardCancelledError) return { kind: "cancelled" };
+ signal?.throwIfAborted();
+ prompter.log.warning(
+ error instanceof Error ? error.message : "Connection failed. Retry /login.",
+ );
+ }
+ }
+ } catch (error) {
+ if (error instanceof WizardCancelledError) return { kind: "cancelled" };
+ throw error;
+ }
+}
diff --git a/packages/eve/src/setup/flows/model-source-change.scenario.test.ts b/packages/eve/src/setup/flows/model-source-change.scenario.test.ts
new file mode 100644
index 000000000..721da44e8
--- /dev/null
+++ b/packages/eve/src/setup/flows/model-source-change.scenario.test.ts
@@ -0,0 +1,79 @@
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, expect, it, vi } from "vitest";
+import {
+ changeAgentModel,
+ changeValidatedAgentModel,
+ changeAgentModelSettings,
+ readAuthoredModelSelection,
+} from "./model-source-change.js";
+
+const roots: string[] = [];
+afterEach(async () => {
+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
+});
+it.each(["flat", "nested", "agent-directory"])(
+ "rewrites models and settings from a %s starting path",
+ async (layout) => {
+ const root = await mkdtemp(join(tmpdir(), "eve-model-layout-"));
+ roots.push(root);
+ const agentRoot = layout === "flat" ? root : join(root, "agent");
+ await mkdir(agentRoot, { recursive: true });
+ await writeFile(join(root, "package.json"), '{"type":"module"}');
+ const file = join(agentRoot, "agent.ts");
+ await writeFile(
+ file,
+ 'import { defineAgent } from "eve"; export default defineAgent({model: "openai/gpt-5.6-luna-fast"});',
+ );
+ const startPath = layout === "agent-directory" ? agentRoot : root;
+ await expect(
+ changeAgentModel({ appRoot: startPath, slug: "openai-api/gpt-5.6-luna-fast" }),
+ ).resolves.toMatchObject({ kind: "changed" });
+ await expect(readAuthoredModelSelection(startPath)).resolves.toBe(
+ "openai-api/gpt-5.6-luna-fast",
+ );
+ await expect(
+ changeAgentModelSettings({
+ appRoot: startPath,
+ patch: {
+ model: { kind: "set", value: "anthropic-api/claude-sonnet-5" },
+ reasoning: { kind: "keep" },
+ gatewayServiceTier: { kind: "keep" },
+ },
+ }),
+ ).resolves.toMatchObject({ kind: "changed" });
+ expect(await readFile(file, "utf8")).toContain('anthropic("claude-sonnet-5")');
+ },
+);
+
+it.each([false, true])(
+ "applies catalog-validated selections while preserving source guards (dynamic: %s)",
+ async (dynamic) => {
+ const root = await mkdtemp(join(tmpdir(), "eve-model-validated-"));
+ roots.push(root);
+ await writeFile(join(root, "package.json"), '{"type":"module"}');
+ const file = join(root, "agent.ts");
+ const source = dynamic
+ ? 'import { defineAgent } from "eve"; export default defineAgent({model: getModel()});'
+ : 'import { defineAgent } from "eve"; export default defineAgent({model: "openai/gpt-5.6-luna-fast"});';
+ await writeFile(file, source);
+ const fetch = vi.fn(() => {
+ throw new Error("Unexpected catalog request");
+ });
+ vi.stubGlobal("fetch", fetch);
+ try {
+ const result = await changeValidatedAgentModel({
+ appRoot: root,
+ slug: "openai/catalog-validated-model",
+ });
+ expect(result.kind).toBe(dynamic ? "rejected" : "changed");
+ expect(fetch).not.toHaveBeenCalled();
+ const edited = await readFile(file, "utf8");
+ if (dynamic) expect(edited).toBe(source);
+ else expect(edited).toContain('"openai/catalog-validated-model"');
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ },
+);
diff --git a/packages/eve/src/setup/flows/model-source-change.ts b/packages/eve/src/setup/flows/model-source-change.ts
index f3b3a4013..0a44a1692 100644
--- a/packages/eve/src/setup/flows/model-source-change.ts
+++ b/packages/eve/src/setup/flows/model-source-change.ts
@@ -1,4 +1,8 @@
+import { parseModelHelper } from "#shared/model-helper.js";
import { join } from "node:path";
+import { readFile } from "node:fs/promises";
+import { resolveDiscoveryProject } from "#discover/project.js";
+import { readModelSelectionFromSource } from "#source-change/apply-model-selection.js";
import { createCompiledRuntimeModelCatalogLoader } from "#compiler/model-catalog.js";
import { discoverAgent } from "#discover/discover-agent.js";
@@ -8,10 +12,7 @@ import type {
AgentModelSetting,
AgentModelSettingsPatch,
} from "#source-change/apply-agent-model-settings.js";
-import {
- CHATGPT_MODEL_SELECTION_PREFIX,
- parseChatGptModelSelection,
-} from "#shared/chatgpt-model.js";
+import { CHATGPT_MODEL_SELECTION_PREFIX } from "#shared/chatgpt-model.js";
import { createStaticSourceChange } from "#source-change/static-source-change.js";
import pc from "#compiled/picocolors/index.js";
@@ -74,8 +75,8 @@ export async function changeAgentModelSettings(input: {
if (rejection !== null) return { kind: "rejected", message: rejection };
}
- const agentRoot = join(appRoot, "agent");
- const { manifest } = await discoverAgent({ agentRoot, appRoot });
+ const project = await resolveDiscoveryProject(appRoot);
+ const { manifest } = await discoverAgent(project);
const result = await createStaticSourceChange(manifest).updateModelSettings(patch);
if (result.kind === "bail") {
return {
@@ -108,8 +109,17 @@ export async function changeAgentModel(input: {
const rejection = await validateModelSlug(appRoot, slug);
if (rejection !== null) return { kind: "rejected", message: rejection };
- const agentRoot = join(appRoot, "agent");
- const { manifest } = await discoverAgent({ agentRoot, appRoot });
+ return changeValidatedAgentModel(input);
+}
+
+/** Applies a selection already confirmed by the provider catalog, retaining source-edit guards. */
+export async function changeValidatedAgentModel(input: {
+ readonly appRoot: string;
+ readonly slug: string;
+}): Promise<ApplyModelOutcome> {
+ const { appRoot, slug } = input;
+ const project = await resolveDiscoveryProject(appRoot);
+ const { manifest } = await discoverAgent(project);
const result = await createStaticSourceChange(manifest).updateModelName(slug);
if (result.kind === "bail") {
return {
@@ -123,7 +133,7 @@ export async function changeAgentModel(input: {
}
export async function validateModelSlug(appRoot: string, slug: string): Promise<string | null> {
- if (parseChatGptModelSelection(slug) !== undefined) return null;
+ if (parseModelHelper(slug) !== undefined) return null;
if (slug.startsWith(CHATGPT_MODEL_SELECTION_PREFIX)) {
return "Choose a bare OpenAI model id after `chatgpt/`.";
}
@@ -142,3 +152,12 @@ export async function validateModelSlug(appRoot: string, slug: string): Promise<
}
return null;
}
+
+/** Uses the same source grammar as model edits, never the provider endpoint. */
+export async function readAuthoredModelSelection(startPath: string): Promise<string | undefined> {
+ const project = await resolveDiscoveryProject(startPath);
+ const { manifest } = await discoverAgent(project);
+ if (!manifest.configModule) return undefined;
+ const source = await readFile(join(project.agentRoot, manifest.configModule.logicalPath), "utf8");
+ return readModelSelectionFromSource(source);
+}
diff --git a/packages/eve/src/setup/flows/model.test.ts b/packages/eve/src/setup/flows/model.test.ts
index 90f53c35e..02e8dab06 100644
--- a/packages/eve/src/setup/flows/model.test.ts
+++ b/packages/eve/src/setup/flows/model.test.ts
@@ -1,885 +1,150 @@
-import pc from "picocolors";
import { describe, expect, it, vi } from "vitest";
-
import { createFakePrompter } from "#internal/testing/fake-prompter.js";
-import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";
-import type { GatewayCatalogModel } from "#setup/boxes/select-model.js";
-import type {
- PrompterValue,
- SelectNotice,
- SelectOption,
- SingleSelectOptions,
-} from "#setup/prompter.js";
-import { WizardCancelledError } from "#setup/step.js";
-
-import {
- MODEL_MENU_MESSAGE,
- runModelFlow,
- type ModelFlowDeps,
- type ModelSettingsRequest,
-} from "./model.js";
-
-const APP_ROOT = "/app/my-agent";
-
-const CATALOG: GatewayCatalogModel[] = [
- {
- id: "openai/gpt-5.6-luna-fast",
- name: "GPT-5.6 Luna Fast",
- type: "language",
- owned_by: "openai",
- tags: ["reasoning"],
- },
- {
- id: "anthropic/claude-sonnet-5",
- name: "Claude Sonnet 5",
- type: "language",
- owned_by: "anthropic",
- tags: ["reasoning", "web-search"],
- pricing: { service_tiers: { priority: {} } },
- },
- {
- id: "openai/gpt-5.5",
- name: "GPT-5.5",
- type: "language",
- owned_by: "openai",
- tags: ["reasoning", "web-search"],
- pricing: { service_tiers: { priority: {} } },
- },
- // Advertises neither the reasoning tag nor a priority tier, so capability
- // lookups have a catalog-listed model with no adjustable controls.
- {
- id: "test/no-frills",
- name: "No Frills",
- type: "language",
- owned_by: "test",
- tags: ["web-search"],
- },
-];
-
-function flowDeps(overrides: Partial<ModelFlowDeps> = {}): Partial<ModelFlowDeps> {
+import { runModelFlow, type CurrentAgentModel, type ModelFlowDeps } from "./model.js";
+
+const provenance = vi.hoisted(() => ({ inspect: vi.fn(), authored: vi.fn(), models: vi.fn() }));
+vi.mock("#services/inspect-application.js", () => ({ inspectApplication: provenance.inspect }));
+vi.mock("./model-source-change.js", async (original) => ({
+ ...(await original<typeof import("./model-source-change.js")>()),
+ readAuthoredModelSelection: provenance.authored,
+}));
+vi.mock("#internal/model-auth/available-models.js", () => ({
+ availableHelperModels: provenance.models,
+}));
+
+function deps(overrides: Partial<ModelFlowDeps> = {}): Partial<ModelFlowDeps> {
return {
- readCurrentModel: vi.fn(async () => ({
- id: "anthropic/claude-sonnet-5",
- routing: { kind: "gateway", target: "anthropic" } as const,
+ readCurrentModel: vi.fn(async (): Promise<CurrentAgentModel> => ({
+ id: "openai/gpt-5.6-luna-fast",
+ routing: { kind: "gateway", target: "openai" },
reasoning: null,
- serviceTier: { kind: "standard" } as const,
+ serviceTier: { kind: "standard" },
editable: true,
settingsEditable: true,
})),
- applySettings: vi.fn(
- async ({ patch }: Parameters<ModelFlowDeps["applySettings"]>[0]) =>
- ({
- kind: "changed",
- changed: ["model"],
- model: patch.model.kind === "set" ? patch.model.value : undefined,
- }) as const,
- ),
- selectModel: { fetchModels: async () => CATALOG },
- pickModelSettings: vi.fn(async () => undefined),
- resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-project"] as const),
- readProviderSelection: vi.fn(async () => "ai-gateway-project" as const),
- runProviderFlow: vi.fn(async () => ({ kind: "ai-gateway-project" }) as const),
- ensureChatGptAuth: vi.fn(async () => {}),
- writeProviderSelection: vi.fn(async () => {}),
+ selectModel: { fetchModels: vi.fn(async () => []) },
+ pickModelSettings: vi.fn(async () => ({ model: "anthropic/claude-sonnet-5" })),
+ applySettings: vi.fn(async () => ({ kind: "changed", changed: ["model"] }) as const),
...overrides,
};
}
-/** One painted menu: its option rows plus the notice lines shown with them. */
-interface MenuPaint {
- options: SelectOption<PrompterValue>[];
- notices: readonly SelectNotice[];
- hintLayout: string | undefined;
- /** The row the menu opened on (cursor pre-selection) for that lap. */
- initialValue: PrompterValue | undefined;
-}
-
-/**
- * Answers the root menu from a script (throwing the cancel error for "esc")
- * and records every painted menu. The composite model screen is not a prompter
- * question — tests script it through the `pickModelSettings` dep instead.
- */
-function scriptedPrompter(input: { menu: (PrompterValue | "esc")[] }) {
- const menuPaints: MenuPaint[] = [];
- const menuScript = [...input.menu];
- const fake = createFakePrompter({
- single: (opts: SingleSelectOptions<PrompterValue>) => {
- if (opts.message !== MODEL_MENU_MESSAGE) {
- throw new Error(`Unexpected prompt: "${opts.message}"`);
- }
- menuPaints.push({
- options: opts.options,
- notices: opts.notices ?? [],
- hintLayout: opts.hintLayout,
- initialValue: opts.initialValue,
- });
- const next = menuScript.shift();
- if (next === undefined) throw new Error("Menu painted more times than scripted.");
- if (next === "esc") throw new WizardCancelledError();
- return next;
- },
- });
- return { ...fake, menuPaints };
-}
-
describe("runModelFlow", () => {
- it("paints a stacked menu with the running model and configured provider", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps: flowDeps() })).resolves.toEqual({
- kind: "cancelled",
- });
-
- expect(menuPaints).toEqual([
- {
- options: [
- {
- value: "model",
- label: "Change model",
- hint: "anthropic/claude-sonnet-5",
- description: "The model, its reasoning effort, and the Gateway service tier",
- },
- {
- value: "provider",
- label: "Change provider",
- hint: "AI Gateway via Project",
- description: "How your agent reaches the model provider",
- },
- { value: "done", label: "Done" },
- ],
- notices: [],
- hintLayout: "stacked",
- initialValue: "model",
- },
- ]);
- });
-
- it("keeps the stored provider selection independent from authored routing", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });
- const deps = flowDeps({
- readCurrentModel: vi.fn(async () => ({
- id: "chatgpt/gpt-5.6-sol",
- routing: { kind: "external", provider: "codex" } as const,
- reasoning: null,
- serviceTier: { kind: "standard" } as const,
- editable: true,
- settingsEditable: true,
- })),
- resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-project"] as const),
- readProviderSelection: vi.fn(async () => "ai-gateway-project" as const),
- });
-
- await runModelFlow({
- appRoot: APP_ROOT,
- prompter,
- chatGptAccountLabel: "[email protected]",
- deps,
- });
-
- expect(menuPaints[0]?.options[1]).toMatchObject({
- value: "provider",
- label: "Change provider",
- hint: "AI Gateway via Project",
- description: "How your agent reaches the model provider",
- });
- expect(menuPaints[0]?.notices).toEqual([]);
- });
-
- it("keeps ChatGPT authentication inside the model flow panel", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["provider"] });
- const stopSpinner = vi.fn();
- prompter.log.spinner = vi.fn((message) => ({
- stop: message.startsWith("Waiting for ChatGPT") ? stopSpinner : vi.fn(),
- }));
- const ensureChatGptAuth = vi.fn<ModelFlowDeps["ensureChatGptAuth"]>(async (options) => {
- options?.log?.("Sign in to ChatGPT in your browser.");
- });
- const deps = flowDeps({
- ensureChatGptAuth,
- runProviderFlow: vi.fn(async () => ({ kind: "chatgpt" }) as const),
- });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "done",
- accessChanged: true,
- modelMessage: `Model changed to ${pc.bold("chatgpt/gpt-5.6-sol")}. Live on your next prompt.`,
- providerSelection: "chatgpt",
- });
-
- expect(menuPaints[0]?.options.map((option) => option.value)).toEqual([
- "model",
- "provider",
- "done",
- ]);
- expect(menuPaints).toHaveLength(1);
- expect(prompter.log.spinner).toHaveBeenCalledWith(
- "Waiting for ChatGPT sign-in in your browser…",
- { kind: "external-action", emphasis: "browser" },
- );
- expect(prompter.log.info).toHaveBeenCalledWith("Sign in to ChatGPT in your browser.");
- expect(stopSpinner).toHaveBeenCalledOnce();
- expect(ensureChatGptAuth).toHaveBeenCalledOnce();
- expect(deps.applySettings).toHaveBeenCalledWith({
- appRoot: APP_ROOT,
+ it("opens settings directly and applies a selection without a review or provider prompt", async () => {
+ const fake = createFakePrompter();
+ const flow = deps();
+ const result = await runModelFlow({ appRoot: "/agent", prompter: fake.prompter, deps: flow });
+ expect(fake.selectMessages).toEqual([]);
+ expect(flow.applySettings).toHaveBeenCalledWith({
+ appRoot: "/agent",
patch: {
- model: { kind: "set", value: "chatgpt/gpt-5.6-sol" },
+ model: { kind: "set", value: "anthropic/claude-sonnet-5" },
reasoning: { kind: "keep" },
- gatewayServiceTier: { kind: "remove" },
+ gatewayServiceTier: { kind: "keep" },
},
});
- expect(deps.runProviderFlow).toHaveBeenCalledWith(
- expect.objectContaining({
- availableProviders: ["chatgpt", "ai-gateway-project"],
- selectedProvider: "ai-gateway-project",
+ expect(result).toMatchObject({ kind: "done", accessChanged: true });
+ });
+ it("cancels without touching authored settings", async () => {
+ const flow = deps({ pickModelSettings: vi.fn(async () => undefined) });
+ expect(
+ await runModelFlow({
+ appRoot: "/agent",
+ prompter: createFakePrompter().prompter,
+ deps: flow,
}),
- );
- expect(deps.writeProviderSelection).toHaveBeenCalledWith(APP_ROOT, "chatgpt");
+ ).toEqual({ kind: "cancelled" });
+ expect(flow.applySettings).not.toHaveBeenCalled();
});
-
- it("does not store a provider selection when its required source edit is rejected", async () => {
- const { prompter } = scriptedPrompter({ menu: ["provider"] });
- const deps = flowDeps({
- runProviderFlow: vi.fn(async () => ({ kind: "chatgpt" }) as const),
+ it("reports a rejected edit without claiming a change", async () => {
+ const flow = deps({
applySettings: vi.fn(
- async () => ({ kind: "rejected", message: "Couldn't update agent.ts." }) as const,
+ async () => ({ kind: "rejected", message: "Edit agent.ts manually." }) as const,
),
});
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "done",
- accessChanged: true,
- modelMessage: "Couldn't update agent.ts.",
- });
-
- expect(deps.ensureChatGptAuth).toHaveBeenCalledOnce();
- expect(deps.writeProviderSelection).not.toHaveBeenCalled();
- });
-
- it("switches ChatGPT back to Gateway through the provider selection", async () => {
- const { prompter } = scriptedPrompter({ menu: ["provider"] });
- const applySettings = vi.fn<ModelFlowDeps["applySettings"]>(async ({ patch }) => ({
- kind: "changed",
- changed: ["model"],
- model: patch.model.kind === "set" ? patch.model.value : undefined,
- }));
- const deps = flowDeps({
- readCurrentModel: vi.fn(async () => ({
- id: "chatgpt/gpt-5.6-sol",
- routing: { kind: "external", provider: "codex" } as const,
- reasoning: null,
- serviceTier: { kind: "standard" } as const,
- editable: true,
- settingsEditable: true,
- })),
- resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-project"] as const),
- readProviderSelection: vi.fn(async () => "chatgpt" as const),
- runProviderFlow: vi.fn(async () => ({ kind: "ai-gateway-project" }) as const),
- applySettings,
- });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "done",
- accessChanged: true,
- modelMessage: `Model changed to ${pc.bold(DEFAULT_AGENT_MODEL_ID)}. Live on your next prompt.`,
- providerSelection: "ai-gateway-project",
- });
-
- expect(applySettings).toHaveBeenCalledWith({
- appRoot: APP_ROOT,
- patch: {
- model: { kind: "set", value: DEFAULT_AGENT_MODEL_ID },
- reasoning: { kind: "keep" },
- gatewayServiceTier: { kind: "keep" },
- },
- });
- expect(deps.ensureChatGptAuth).not.toHaveBeenCalled();
- expect(deps.writeProviderSelection).toHaveBeenCalledWith(APP_ROOT, "ai-gateway-project");
+ expect(
+ await runModelFlow({
+ appRoot: "/agent",
+ prompter: createFakePrompter().prompter,
+ deps: flow,
+ }),
+ ).toEqual({ kind: "done", accessChanged: false, modelMessage: "Edit agent.ts manually." });
});
-
- it("reauthenticates when ChatGPT is selected again", async () => {
- const { prompter } = scriptedPrompter({ menu: ["provider"] });
- const deps = flowDeps({
- readCurrentModel: vi.fn(async () => ({
- id: "chatgpt/gpt-5.6-sol",
- routing: { kind: "external", provider: "codex" } as const,
- reasoning: null,
- serviceTier: { kind: "standard" } as const,
- editable: true,
- settingsEditable: true,
- })),
- resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-key"] as const),
- readProviderSelection: vi.fn(async () => "chatgpt" as const),
- runProviderFlow: vi.fn(async () => ({ kind: "chatgpt" }) as const),
- });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "done",
- accessChanged: true,
- modelMessage: "ChatGPT login ready.",
- providerSelection: "chatgpt",
+ it("removes default reasoning and standard service tier rather than writing sentinels", async () => {
+ const flow = deps({
+ pickModelSettings: vi.fn(
+ async () => ({ reasoning: "default", serviceTier: "standard" }) as const,
+ ),
});
-
- expect(deps.ensureChatGptAuth).toHaveBeenCalledOnce();
- expect(deps.runProviderFlow).toHaveBeenCalledWith(
+ await runModelFlow({ appRoot: "/agent", prompter: createFakePrompter().prompter, deps: flow });
+ expect(flow.applySettings).toHaveBeenCalledWith(
expect.objectContaining({
- availableProviders: ["chatgpt", "ai-gateway-key"],
- selectedProvider: "chatgpt",
+ patch: {
+ model: { kind: "keep" },
+ reasoning: { kind: "remove" },
+ gatewayServiceTier: { kind: "remove" },
+ },
}),
);
- expect(deps.applySettings).not.toHaveBeenCalled();
- expect(deps.writeProviderSelection).toHaveBeenCalledWith(APP_ROOT, "chatgpt");
- });
-
- it("summarizes authored reasoning and Fast mode on the model row hint", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });
- const deps = flowDeps({
- readCurrentModel: vi.fn(async () => ({
- id: "xai/grok-4.5",
- routing: { kind: "gateway", target: "xai" } as const,
- reasoning: "high" as const,
- serviceTier: { kind: "priority" } as const,
- editable: true,
- settingsEditable: true,
- })),
- });
-
- await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
-
- expect(menuPaints[0]?.options[0]?.hint).toBe("xai/grok-4.5@high ↯");
});
+});
- it("keeps the model row for an external-provider model and never asks to configure a provider", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });
- const deps = flowDeps({
- readCurrentModel: vi.fn(async () => ({
- id: "anthropic/claude-sonnet-5",
- routing: { kind: "external", provider: "anthropic" } as const,
- reasoning: null,
- serviceTier: { kind: "standard" } as const,
- editable: false,
- settingsEditable: true,
- })),
- // Even though detection finds nothing, external routing must NOT surface
- // the "Configure model access" gateway UX.
- resolveAvailableProviders: vi.fn(async () => ["chatgpt"] as const),
- readProviderSelection: vi.fn(async () => "ai-gateway-project" as const),
- });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "cancelled",
- });
-
- expect(menuPaints).toEqual([
- {
- options: [
- {
- value: "model",
- label: "Change model",
- hint: "anthropic/claude-sonnet-5",
- description:
- "Reasoning and service tier; the model itself is an SDK model call in agent.ts",
- },
- {
- value: "provider",
- label: "Change provider",
- disabled: true,
- description: "Disabled in external endpoint mode",
- },
- { value: "done", label: "Done" },
- ],
- notices: [
- {
- tone: "warning",
- text: "`agent.ts` specifies the model provider directly. Model, provider, and service-tier changes stay source-owned; reasoning remains configurable here.",
+it.each(["openai", "anthropic"])(
+ "keeps a foreign %s call fixed without requesting eve credentials",
+ async (provider) => {
+ provenance.models.mockClear();
+ provenance.authored.mockResolvedValue(undefined);
+ provenance.inspect.mockResolvedValue({
+ compiledState: {
+ manifest: {
+ config: {
+ source: {},
+ model: { id: "custom-model", source: {}, routing: { kind: "external", provider } },
},
- ],
- hintLayout: "stacked",
- initialValue: "model",
- },
- ]);
- });
-
- it("disables the Change model row only when nothing at all is editable", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });
- const deps = flowDeps({
- readCurrentModel: vi.fn(async () => ({
- id: "anthropic/claude-sonnet-5",
- routing: { kind: "gateway", target: "anthropic" } as const,
- reasoning: null,
- serviceTier: { kind: "standard" } as const,
- editable: false,
- settingsEditable: false,
- })),
- });
-
- await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
-
- expect(menuPaints[0]?.options[0]).toEqual({
- value: "model",
- label: "Change model",
- disabled: true,
- description: "Set via an SDK model call in agent.ts; edit the source to change it",
- });
- expect(menuPaints[0]?.initialValue).toBe("provider");
- });
-
- it("opens the composite screen with catalog options, authored values, and capabilities", async () => {
- const { prompter } = scriptedPrompter({ menu: ["model", "esc"] });
- let captured: ModelSettingsRequest | undefined;
- const pickModelSettings = vi.fn(async (request: ModelSettingsRequest) => {
- captured = request;
- return undefined;
- });
- const deps = flowDeps({ pickModelSettings });
-
- await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
-
- expect(captured?.model).toEqual({
- kind: "pick",
- options: expect.arrayContaining([
- expect.objectContaining({ value: "openai/gpt-5.6-luna-fast", featured: true }),
- expect.objectContaining({ value: "anthropic/claude-sonnet-5" }),
- expect.objectContaining({ value: "test/no-frills" }),
- ]),
- current: "anthropic/claude-sonnet-5",
- });
- if (captured?.model.kind !== "pick") throw new Error("Expected a model picker.");
- expect(captured.model.options.map((option) => option.value)).not.toContain(
- "chatgpt/gpt-5.6-sol",
- );
- expect(captured?.reasoning).toBeNull();
- expect(captured?.serviceTier).toEqual({ kind: "standard" });
- expect(captured?.settingsEditable).toBe(true);
- expect(captured?.externalRouting).toBe(false);
- expect(captured?.capabilitiesFor("test/no-frills")).toEqual({
- reasoning: false,
- reasoningLevels: [],
- fastMode: false,
- });
- expect(captured?.capabilitiesFor("unknown/model")).toBeUndefined();
- });
-
- it("fixes the model section for a gateway-routed SDK model call", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["model", "esc"] });
- let captured: ModelSettingsRequest | undefined;
- const deps = flowDeps({
- // `gateway("…")` instance: gateway-routed, but not a string literal eve can rewrite.
- readCurrentModel: vi.fn(async () => ({
- id: "anthropic/claude-sonnet-5",
- routing: { kind: "gateway", target: "anthropic" } as const,
- reasoning: null,
- serviceTier: { kind: "standard" } as const,
- editable: false,
- settingsEditable: true,
- })),
- pickModelSettings: vi.fn(async (request: ModelSettingsRequest) => {
- captured = request;
- return undefined;
- }),
- resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-key"] as const),
- readProviderSelection: vi.fn(async () => "ai-gateway-key" as const),
- });
-
- await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
-
- expect(captured?.model).toEqual({
- kind: "fixed",
- current: "anthropic/claude-sonnet-5",
- reason: "Set via an SDK model call in agent.ts; edit the source to change it",
- });
- // Gateway routing gets no external-restriction notice.
- expect(menuPaints[0]?.notices).toEqual([]);
- });
-
- it("completes via Done without requiring a model change", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["done"] });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps: flowDeps() })).resolves.toEqual({
- kind: "done",
- accessChanged: false,
- });
- expect(menuPaints).toHaveLength(1);
- });
-
- it("names the selected Project provider on the provider row", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });
- const deps = flowDeps({
- resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-project"] as const),
- readProviderSelection: vi.fn(async () => "ai-gateway-project" as const),
- });
-
- await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
-
- expect(menuPaints[0]?.options[1]).toEqual({
- value: "provider",
- label: "Change provider",
- hint: "AI Gateway via Project",
- description: "How your agent reaches the model provider",
- });
- });
-
- it("defaults to an available API key when no selection is stored", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });
- const deps = flowDeps({
- resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-key"] as const),
- readProviderSelection: vi.fn(async () => undefined),
- });
-
- await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
-
- expect(menuPaints[0]?.options[1]).toEqual({
- value: "provider",
- label: "Change provider",
- hint: "AI Gateway via AI_GATEWAY_API_KEY",
- description: "How your agent reaches the model provider",
- });
- });
-
- it("applies a picked model once on Done and returns to the prompt", async () => {
- const { prompter, menuPaints, selectMessages } = scriptedPrompter({
- menu: ["model", "done"],
- });
- const deps = flowDeps({
- pickModelSettings: vi.fn(async () => ({ model: "openai/gpt-5.5" })),
- });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "done",
- accessChanged: true,
- modelMessage: `Model changed to ${pc.bold("openai/gpt-5.5")}. Live on your next prompt.`,
- });
-
- expect(selectMessages).toEqual([MODEL_MENU_MESSAGE, MODEL_MENU_MESSAGE]);
- expect(menuPaints).toHaveLength(2);
- // The second lap lands on Done and shows the drafted slug on the hint.
- expect(menuPaints[1]?.initialValue).toBe("done");
- expect(menuPaints[1]?.options[0]?.hint).toBe("openai/gpt-5.5");
- expect(deps.applySettings).toHaveBeenCalledWith({
- appRoot: APP_ROOT,
- patch: {
- model: { kind: "set", value: "openai/gpt-5.5" },
- reasoning: { kind: "keep" },
- gatewayServiceTier: { kind: "keep" },
+ },
},
});
- expect(deps.readCurrentModel).toHaveBeenCalledTimes(1);
- });
-
- it("returns a rejected model result without claiming the model changed", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["model", "done"] });
- const deps = flowDeps({
- pickModelSettings: vi.fn(async () => ({ model: "openai/gpt-5.5" })),
- applySettings: vi.fn(
- async () => ({ kind: "rejected", message: "Couldn't confirm the id." }) as const,
- ),
- });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "done",
- accessChanged: false,
- modelMessage: "Couldn't confirm the id.",
- });
-
- expect(menuPaints).toHaveLength(2);
- });
-
- it("drafts reasoning and Fast mode from the screen, then applies both once on Done", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["model", "done"] });
- const deps = flowDeps({
- pickModelSettings: vi.fn(async () => ({
- reasoning: "high" as const,
- serviceTier: "priority" as const,
- })),
- applySettings: vi.fn<ModelFlowDeps["applySettings"]>(async () => ({
- kind: "changed" as const,
- changed: ["reasoning", "fast-mode"] as const,
- reasoning: "high" as const,
- fastMode: true,
- })),
- });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "done",
- accessChanged: true,
- modelMessage:
- "Model settings updated: reasoning high, Fast mode on. Live on your next prompt.",
- });
-
- expect(menuPaints).toHaveLength(2);
- expect(menuPaints[1]?.options[0]?.hint).toBe("anthropic/claude-sonnet-5@high ↯");
- expect(deps.applySettings).toHaveBeenCalledTimes(1);
- expect(deps.applySettings).toHaveBeenCalledWith({
- appRoot: APP_ROOT,
- patch: {
- model: { kind: "keep" },
- reasoning: { kind: "set", value: "high" },
- gatewayServiceTier: { kind: "set", value: "priority" },
- },
- });
- });
-
- it("maps the remove sentinels onto remove patches", async () => {
- const { prompter } = scriptedPrompter({ menu: ["model", "done"] });
- const deps = flowDeps({
- readCurrentModel: vi.fn(async () => ({
- id: "anthropic/claude-sonnet-5",
- routing: { kind: "gateway", target: "anthropic" } as const,
- reasoning: "high" as const,
- serviceTier: { kind: "priority" } as const,
- editable: true,
- settingsEditable: true,
- })),
- pickModelSettings: vi.fn(async () => ({
- reasoning: "default" as const,
- serviceTier: "standard" as const,
- })),
- });
-
- await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
-
- expect(deps.applySettings).toHaveBeenCalledWith({
- appRoot: APP_ROOT,
- patch: {
- model: { kind: "keep" },
- reasoning: { kind: "remove" },
- gatewayServiceTier: { kind: "remove" },
- },
- });
- });
-
- it("discards a model-settings draft when the root menu is cancelled, and says so", async () => {
- const { prompter } = scriptedPrompter({ menu: ["model", "esc"] });
- const deps = flowDeps({
- pickModelSettings: vi.fn(async () => ({ reasoning: "low" as const })),
- });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "cancelled",
- discardedDraft: true,
- });
- expect(deps.applySettings).not.toHaveBeenCalled();
- });
-
- it("does not infer the stored provider selection from a model edit", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["model", "done"] });
- const deps = flowDeps({
- readCurrentModel: vi.fn(async () => ({
- id: "chatgpt/gpt-5.6-sol",
- routing: { kind: "external", provider: "codex" } as const,
- reasoning: null,
- serviceTier: { kind: "standard" } as const,
- editable: true,
- settingsEditable: true,
- })),
- resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-project"] as const),
- readProviderSelection: vi.fn(async () => "chatgpt" as const),
- pickModelSettings: vi.fn(async () => ({ model: "openai/gpt-5.5" })),
- });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "done",
- accessChanged: true,
- modelMessage: `Model changed to ${pc.bold("openai/gpt-5.5")}. Live on your next prompt.`,
- });
-
- expect(menuPaints[1]?.options[1]).toMatchObject({
- value: "provider",
- hint: "ChatGPT subscription",
- });
- expect(deps.writeProviderSelection).not.toHaveBeenCalled();
- });
-
- it("passes a custom Gateway service tier through to the screen untouched", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["model", "esc"] });
- let captured: ModelSettingsRequest | undefined;
- const deps = flowDeps({
- readCurrentModel: vi.fn(async () => ({
- id: "anthropic/claude-sonnet-5",
- routing: { kind: "gateway", target: "anthropic" } as const,
- reasoning: "medium" as const,
- serviceTier: { kind: "custom", value: "flex" } as const,
- editable: true,
- settingsEditable: true,
- })),
- pickModelSettings: vi.fn(async (request: ModelSettingsRequest) => {
- captured = request;
- return undefined;
- }),
- });
-
- await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
-
- expect(captured?.serviceTier).toEqual({ kind: "custom", value: "flex" });
- // A custom tier is not Fast mode: no marker on the root hint.
- expect(menuPaints[0]?.options[0]?.hint).toBe("anthropic/claude-sonnet-5@medium");
- });
-
- it("completes after confirming unchanged model settings", async () => {
- const { prompter } = scriptedPrompter({ menu: ["model", "done"] });
- const deps = flowDeps({ pickModelSettings: vi.fn(async () => ({})) });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "done",
- accessChanged: false,
- });
- expect(deps.applySettings).not.toHaveBeenCalled();
- });
-
- it("opens provider setup directly when none is configured", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: [] });
- const resolveAvailableProviders = vi.fn<ModelFlowDeps["resolveAvailableProviders"]>(
- async () => ["chatgpt"],
- );
- const runProviderFlow = vi.fn<ModelFlowDeps["runProviderFlow"]>(async () => ({
- kind: "ai-gateway-key",
- }));
- const deps = flowDeps({
- resolveAvailableProviders,
- readProviderSelection: vi.fn(async () => undefined),
- runProviderFlow,
- });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "done",
- accessChanged: true,
- providerSelection: "ai-gateway-key",
+ const picker = vi.fn(async () => undefined);
+ await runModelFlow({
+ appRoot: "/agent",
+ prompter: createFakePrompter().prompter,
+ deps: { pickModelSettings: picker, selectModel: { fetchModels: async () => [] } },
});
-
- // No stored selection and no key default to Project setup.
- expect(runProviderFlow).toHaveBeenCalledWith(
+ expect(picker).toHaveBeenCalledWith(
expect.objectContaining({
- appRoot: APP_ROOT,
- availableProviders: ["chatgpt"],
- selectedProvider: "ai-gateway-project",
- }),
- );
- expect(resolveAvailableProviders).toHaveBeenCalledTimes(1);
- expect(menuPaints).toHaveLength(0);
- expect(deps.writeProviderSelection).toHaveBeenCalledWith(APP_ROOT, "ai-gateway-key");
- });
-
- it("honors confirmed provider entry when link metadata looks configured", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: [] });
- const runProviderFlow = vi.fn<ModelFlowDeps["runProviderFlow"]>(async () => ({
- kind: "ai-gateway-project",
- }));
- const deps = flowDeps({ runProviderFlow });
-
- await expect(
- runModelFlow({
- appRoot: APP_ROOT,
- prompter,
- initialStep: "provider",
- deps,
+ model: expect.objectContaining({ kind: "fixed", current: "custom-model" }),
}),
- ).resolves.toEqual({
- kind: "done",
- accessChanged: true,
- providerSelection: "ai-gateway-project",
- });
-
- expect(runProviderFlow).toHaveBeenCalledWith(expect.objectContaining({ appRoot: APP_ROOT }));
- expect(menuPaints).toHaveLength(0);
- expect(deps.writeProviderSelection).toHaveBeenCalledWith(APP_ROOT, "ai-gateway-project");
- });
-
- it("preserves a committed provider selection when interrupted", async () => {
- const { prompter } = scriptedPrompter({ menu: [] });
- const controller = new AbortController();
- const resolveAvailableProviders = vi.fn<ModelFlowDeps["resolveAvailableProviders"]>(
- async () => ["chatgpt", "ai-gateway-project"],
);
- const runProviderFlow = vi.fn<ModelFlowDeps["runProviderFlow"]>(async () => {
- controller.abort();
- return { kind: "ai-gateway-key" };
- });
- const deps = flowDeps({ resolveAvailableProviders, runProviderFlow });
-
- await expect(
- runModelFlow({
- appRoot: APP_ROOT,
- prompter,
- initialStep: "provider",
- signal: controller.signal,
- deps,
- }),
- ).resolves.toEqual({
- kind: "done",
- accessChanged: true,
- providerSelection: "ai-gateway-key",
- });
- expect(resolveAvailableProviders).toHaveBeenCalledTimes(1);
- });
-
- it("completes without persisted changes after direct-provider instructions", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["provider", "done"] });
- const deps = flowDeps({
- runProviderFlow: vi.fn(async () => ({ kind: "external-provider" }) as const),
- });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "done",
- accessChanged: false,
- });
-
- expect(deps.resolveAvailableProviders).toHaveBeenCalledTimes(1);
- expect(deps.writeProviderSelection).not.toHaveBeenCalled();
- expect(menuPaints[1]?.notices).toEqual([]);
- });
-
- 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({
- runProviderFlow: vi.fn(async () => ({ kind: "cancelled" }) as const),
- });
-
- await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({
- kind: "cancelled",
- });
-
- // A cancelled sub-flow changed nothing, so availability is not re-read.
- expect(deps.resolveAvailableProviders).toHaveBeenCalledTimes(1);
- expect(menuPaints).toHaveLength(2);
- expect(menuPaints[1]?.notices).toEqual([]);
- expect(deps.applySettings).not.toHaveBeenCalled();
- });
-
- describe("cursor pre-selection", () => {
- it("opens on the model row when a provider is already set", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["esc"] });
- const deps = flowDeps({
- resolveAvailableProviders: vi.fn(async () => ["chatgpt", "ai-gateway-project"] as const),
- readProviderSelection: vi.fn(async () => "ai-gateway-project" as const),
- });
-
- await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
-
- expect(menuPaints[0]?.initialValue).toBe("model");
- });
-
- it("lands on Done after the external-provider branch", async () => {
- const { prompter, menuPaints } = scriptedPrompter({ menu: ["provider", "esc"] });
- const deps = flowDeps({
- runProviderFlow: vi.fn(async () => ({ kind: "external-provider" }) as const),
- });
-
- await runModelFlow({ appRoot: APP_ROOT, prompter, deps });
-
- expect(menuPaints[1]?.initialValue).toBe("done");
- });
-
- it("keeps the cursor on the row a cancelled sub-flow came from", async () => {
- const provider = scriptedPrompter({ menu: ["provider", "esc"] });
- await runModelFlow({
- appRoot: APP_ROOT,
- prompter: provider.prompter,
- deps: flowDeps({ runProviderFlow: vi.fn(async () => ({ kind: "cancelled" }) as const) }),
- });
- expect(provider.menuPaints[1]?.initialValue).toBe("provider");
-
- const model = scriptedPrompter({ menu: ["model", "esc"] });
- await runModelFlow({ appRoot: APP_ROOT, prompter: model.prompter, deps: flowDeps() });
- expect(model.menuPaints[1]?.initialValue).toBe("model");
- });
+ expect(provenance.models).not.toHaveBeenCalled();
+ },
+);
+it("loads a proven eve helper's model catalog", async () => {
+ provenance.authored.mockResolvedValue("openai-api/custom-model");
+ provenance.models.mockResolvedValue(["custom-model"]);
+ provenance.inspect.mockResolvedValue({
+ compiledState: {
+ manifest: {
+ config: {
+ source: {},
+ model: {
+ id: "custom-model",
+ source: {},
+ routing: { kind: "external", provider: "openai" },
+ },
+ },
+ },
+ },
});
+ const picker = vi.fn(async () => undefined);
+ await runModelFlow({
+ appRoot: "/agent",
+ prompter: createFakePrompter().prompter,
+ deps: { pickModelSettings: picker, selectModel: { fetchModels: async () => [] } },
+ });
+ expect(provenance.models).toHaveBeenCalledWith("openai", undefined);
+ expect(picker).toHaveBeenCalledWith(
+ expect.objectContaining({
+ model: expect.objectContaining({ kind: "pick", current: "openai-api/custom-model" }),
+ }),
+ );
});
diff --git a/packages/eve/src/setup/flows/model.ts b/packages/eve/src/setup/flows/model.ts
index a402cb3d2..3807c101d 100644
--- a/packages/eve/src/setup/flows/model.ts
+++ b/packages/eve/src/setup/flows/model.ts
@@ -1,22 +1,13 @@
+import { availableHelperModels } from "#internal/model-auth/available-models.js";
+import type { ModelHelper } from "#shared/model-helper.js";
+import { MODEL_HELPERS, parseModelHelper } from "#shared/model-helper.js";
import { inspectApplication } from "#services/inspect-application.js";
-import {
- readProviderSelection,
- resolveAvailableProviders,
- writeProviderSelection,
- type ProviderSelection,
-} from "#setup/provider-settings.js";
-import type {
- AgentModelSettingsPatch,
- FieldPatch,
-} from "#source-change/apply-agent-model-settings.js";
-
-import pc from "#compiled/picocolors/index.js";
+import type { ProviderSelection } from "#setup/provider-settings.js";
+import type { AgentModelSettingsPatch } from "#source-change/apply-agent-model-settings.js";
-import { AI_GATEWAY_API_KEY_ENV_VAR } from "../ai-gateway-api-key.js";
import {
fetchGatewayCatalog,
modelOptionsFromCatalog,
- type GatewayCatalogModel,
type SelectModelDeps,
} from "../boxes/select-model.js";
import {
@@ -25,31 +16,23 @@ import {
type ReasoningLevel,
} from "../boxes/model-capabilities.js";
import type { AgentReasoningDefinition, ModelRouting } from "#shared/agent-definition.js";
-import {
- DEFAULT_CHATGPT_MODEL_SELECTION,
- isChatGptModelRouting,
- parseChatGptModelSelection,
-} from "#shared/chatgpt-model.js";
-import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";
import {
readGatewayServiceTier,
type GatewayServiceTierState,
} from "#shared/gateway-service-tier.js";
-import { formatModelSummary } from "#shared/model-summary.js";
-import type { Prompter, SelectNotice, SelectOption } from "../prompter.js";
-import { WizardCancelledError } from "../step.js";
+import type { Prompter, SelectOption } from "../prompter.js";
import { withSpinner } from "../with-spinner.js";
import {
changeAgentModelSettings,
+ readAuthoredModelSelection,
formatApplyModelSettingsOutcome,
type ApplyModelSettingsOutcome,
} from "./model-source-change.js";
-import { ensureChatGptAuth } from "./chatgpt-auth.js";
-import { runProviderFlow } from "./provider.js";
/** The current model id, its routing, and whether `/model` can rewrite it. */
export interface CurrentAgentModel {
id: string | null;
+ helper?: ModelHelper;
routing: ModelRouting | null;
reasoning: AgentReasoningDefinition | null;
serviceTier: GatewayServiceTierState;
@@ -87,7 +70,7 @@ export interface ModelSettingsRequest {
}
/**
- * The screen's draft on Done. Each field is present only when it differs from
+ * A completed model or setting selection. Each field is present only when it differs from
* the authored value; `"default"` and `"standard"` mean "remove the setting".
*/
export interface ModelSettingsResult {
@@ -117,21 +100,12 @@ export interface ModelFlowDeps {
selectModel?: SelectModelDeps;
/** The composite Change-model screen; the dev TUI renderer implements it. */
pickModelSettings?: ModelSettingsPicker;
- /** Resolves provider credentials available to this project. */
- resolveAvailableProviders: typeof resolveAvailableProviders;
- /** Reads the explicit provider selection, if one has been made. */
- readProviderSelection: typeof readProviderSelection;
- /** The provider sub-flow behind the menu's provider row. */
- runProviderFlow: typeof runProviderFlow;
- /** Ensures eve has a usable ChatGPT login before selecting the subscription. */
- ensureChatGptAuth: typeof ensureChatGptAuth;
- writeProviderSelection: typeof writeProviderSelection;
}
export type ModelFlowResult =
| {
kind: "cancelled";
- /** True when Esc dropped drafted setting changes that Done would commit. */
+ /** Whether an incomplete selection was discarded. */
discardedDraft?: boolean;
}
| {
@@ -144,143 +118,7 @@ export type ModelFlowResult =
providerSelection?: ProviderSelection;
};
-// The bordered panel's title ("Configure the agent model") is the menu's header,
-// so the select itself carries no message — avoiding a redundant second title.
-export const MODEL_MENU_MESSAGE = "";
-
-type ModelMenuRow = "model" | "provider" | "done";
-
-function providerSelectionHint(
- provider: ProviderSelection,
- chatGptAccountLabel: string | undefined,
-): string {
- if (provider === "chatgpt") {
- return chatGptAccountLabel === undefined
- ? "ChatGPT subscription"
- : `ChatGPT subscription (${chatGptAccountLabel})`;
- }
- return provider === "ai-gateway-project"
- ? "AI Gateway via Project"
- : `AI Gateway via ${AI_GATEWAY_API_KEY_ENV_VAR}`;
-}
-
-/**
- * The composite screen's catalog rows: the ids themselves as labels, so the
- * railed list shows slugs and the editor's filter matches exactly what the
- * painter windows. Onboarding keeps the name-labeled options.
- */
-function modelListRows(
- catalog: readonly GatewayCatalogModel[] | undefined,
-): SelectOption<string>[] {
- return modelOptionsFromCatalog(catalog).map((option) => {
- const row: SelectOption<string> = { value: option.value, label: option.value };
- if (option.featured === true) row.featured = true;
- return row;
- });
-}
-
-/**
- * The Change model row's value line: the drafted slug plus its reasoning level
- * and Fast mode marker, mirroring the status line's model segment
- * (`xai/grok-4.5@high ↯`).
- */
-function formatModelDraftHint(
- model: string,
- reasoning: ReasoningLevel | null,
- serviceTier: GatewayServiceTierState,
-): string {
- const summary: Parameters<typeof formatModelSummary>[0] = { model };
- if (reasoning !== null) summary.reasoning = reasoning;
- if (serviceTier.kind === "priority") summary.fastGlyph = "↯";
- return formatModelSummary(summary);
-}
-
-/**
- * The model configuration menu. The Change model row opens the composite
- * screen owning the model id, reasoning effort, and service tier; Done is the
- * only row that commits drafted source changes.
- *
- * The model row stays enabled while either the model string or the config
- * object is rewritable — for an SDK model call (`gateway(...)`,
- * `anthropic(...)`) the composite opens with the model fixed and only the
- * settings adjustable. The provider row keys off routing: an external endpoint
- * disables it (gateway credentials don't apply); a gateway endpoint gates it
- * bold-yellow "Configure model access" until a link or credential is
- * detectable (the genuine "no provider connected" state), then "Change
- * provider" with the stored selection. Authored routing does not resolve that
- * preference.
- */
-function modelMenuRows(
- current: string | null,
- reasoning: ReasoningLevel | null,
- serviceTier: GatewayServiceTierState,
- selectedProvider: ProviderSelection,
- providerConfigured: boolean,
- chatGptAccountLabel: string | undefined,
- routing: ModelRouting | null,
- editable: boolean,
- settingsEditable: boolean,
-): SelectOption<ModelMenuRow>[] {
- let modelRow: SelectOption<ModelMenuRow>;
- if (editable || settingsEditable) {
- modelRow = {
- value: "model",
- label: "Change model",
- description: editable
- ? "The model, its reasoning effort, and the Gateway service tier"
- : "Reasoning and service tier; the model itself is an SDK model call in agent.ts",
- };
- if (current !== null) {
- modelRow.hint = formatModelDraftHint(current, reasoning, serviceTier);
- }
- } else {
- modelRow = {
- value: "model",
- label: "Change model",
- disabled: true,
- description: "Set via an SDK model call in agent.ts; edit the source to change it",
- };
- }
-
- let providerRow: SelectOption<ModelMenuRow>;
- if (routing?.kind === "external" && !isChatGptModelRouting(routing)) {
- providerRow = {
- disabled: true,
- value: "provider",
- label: "Change provider",
- description: "Disabled in external endpoint mode",
- };
- } else if (!providerConfigured) {
- providerRow = {
- value: "provider",
- label: pc.bold("Configure model access"),
- hint: pc.yellow("Not configured"),
- description: "How your agent reaches the model provider",
- accent: "warning",
- };
- } else {
- providerRow = {
- value: "provider",
- label: "Change provider",
- hint: providerSelectionHint(selectedProvider, chatGptAccountLabel),
- 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" }];
-}
-
-/**
- * THE MODEL FLOW for the dev TUI's `/model`: a root menu whose Change model
- * row opens the composite model screen (catalog pick, reasoning-effort slider,
- * service-tier toggle) and whose provider row runs {@link runProviderFlow}.
- * Authored setting changes stay in memory until Done, then land through one
- * source transform and atomic rename. A completed provider change commits the
- * current draft and returns to the prompt; cancelled flows and
- * external-provider instructions return to the menu.
- */
+/** Selects a model or setting and applies the completed edit immediately. */
export async function runModelFlow(input: {
/** Selected agent root whose authored model settings are edited. */
appRoot: string;
@@ -296,282 +134,81 @@ export async function runModelFlow(input: {
deps?: Partial<ModelFlowDeps>;
}): Promise<ModelFlowResult> {
const { appRoot, prompter, signal } = input;
- const environmentRoot = input.environmentRoot ?? appRoot;
const deps: ModelFlowDeps = {
readCurrentModel: readCurrentAgentModel,
applySettings: changeAgentModelSettings,
- resolveAvailableProviders,
- readProviderSelection,
- runProviderFlow,
- ensureChatGptAuth,
- writeProviderSelection,
...input.deps,
};
- // One ephemeral spinner covers the local model/provider reads and catalog
- // fetch so the menu paints with no persisted loading lines. A failed catalog
- // fetch degrades to unknown capabilities, never to an error.
- const fetchCatalog = deps.selectModel?.fetchModels ?? fetchGatewayCatalog;
- const [currentModel, availableProviders, storedProviderSelection, catalog] = await withSpinner(
- prompter,
- "Checking the project…",
- () =>
- Promise.all([
- deps.readCurrentModel(appRoot),
- deps.resolveAvailableProviders(
- environmentRoot,
- signal === undefined ? { env: process.env } : { signal, env: process.env },
- ),
- deps.readProviderSelection(environmentRoot),
- fetchCatalog(signal).catch((): GatewayCatalogModel[] | undefined => undefined),
- ]),
+ const [currentModel, catalog] = await withSpinner(prompter, "Loading models…", () =>
+ Promise.all([
+ deps.readCurrentModel(appRoot),
+ (deps.selectModel?.fetchModels ?? fetchGatewayCatalog)(signal).catch(() => undefined),
+ ]),
);
+ const helper =
+ currentModel.helper === undefined
+ ? undefined
+ : ([currentModel.helper, MODEL_HELPERS[currentModel.helper]] as const);
+ const options = helper
+ ? (await availableHelperModels(helper[0], signal)).map((id) => ({
+ value: helper[1].prefix + id,
+ label: id,
+ }))
+ : modelOptionsFromCatalog(catalog);
+ if (!deps.pickModelSettings) throw new Error("The model picker is unavailable.");
+ const result = await deps.pickModelSettings({
+ model: currentModel.editable
+ ? {
+ kind: "pick",
+ options,
+ current:
+ helper && currentModel.id
+ ? helper[1].prefix + currentModel.id.replace(/^[^/]+\//u, "")
+ : currentModel.id,
+ }
+ : {
+ kind: "fixed",
+ current: currentModel.id,
+ reason: "This model is configured in agent.ts.",
+ },
+ reasoning: currentModel.reasoning === "provider-default" ? null : currentModel.reasoning,
+ serviceTier: currentModel.serviceTier,
+ settingsEditable: currentModel.settingsEditable,
+ externalRouting: currentModel.routing?.kind === "external",
+ capabilitiesFor: (id) =>
+ gatewayModelCapabilities(
+ catalog,
+ helper && id
+ ? `${helper[0] === "chatgpt" ? "openai" : helper[0]}/${id.slice(helper[1].prefix.length)}`
+ : id,
+ ),
+ });
+ if (!result) return { kind: "cancelled" };
signal?.throwIfAborted();
-
- let { id: current, routing, serviceTier, editable, settingsEditable } = currentModel;
- // An authored "provider-default" is the absent-setting sentinel, not a level.
- let reasoning: ReasoningLevel | null =
- currentModel.reasoning === "provider-default" ? null : currentModel.reasoning;
- const selectedProvider =
- storedProviderSelection ??
- (availableProviders.includes("ai-gateway-key") ? "ai-gateway-key" : "ai-gateway-project");
- const providerConfigured = availableProviders.includes(selectedProvider);
- let nextProviderSelection: ProviderSelection | undefined;
- const patch: {
- model: FieldPatch<string>;
- reasoning: FieldPatch<AgentReasoningDefinition>;
- gatewayServiceTier: FieldPatch<"priority">;
- } = {
- model: { kind: "keep" },
- reasoning: { kind: "keep" },
- gatewayServiceTier: { kind: "keep" },
- };
-
- let lastApply: ApplyModelSettingsOutcome | undefined;
- let committedProviderSelection: ProviderSelection | undefined;
- let shouldAuthenticateChatGpt = false;
- let completed = false;
- let commitDraft = false;
- const sourceOwnedExternalRouting =
- routing?.kind === "external" && !isChatGptModelRouting(routing);
- const externalNotice: SelectNotice | undefined = sourceOwnedExternalRouting
- ? {
- tone: "warning",
- text: "`agent.ts` specifies the model provider directly. Model, provider, and service-tier changes stay source-owned; reasoning remains configurable here.",
- }
- : undefined;
-
- // Start at the first useful row. Cancellation keeps the current row.
- let nextSelection: ModelMenuRow =
- !providerConfigured && routing?.kind !== "external"
- ? "provider"
- : editable || settingsEditable
- ? "model"
- : "provider";
- // A gateway model with no provider cannot run. Skip the menu's extra Enter
- // and open provider setup as soon as that state is confirmed.
- let openProviderFirst =
- routing?.kind !== "external" && (input.initialStep === "provider" || !providerConfigured);
-
- while (true) {
- let pick: ModelMenuRow;
- if (openProviderFirst) {
- openProviderFirst = false;
- pick = "provider";
- } else {
- try {
- pick = await prompter.select<ModelMenuRow>({
- message: MODEL_MENU_MESSAGE,
- options: modelMenuRows(
- current,
- reasoning,
- isChatGptModelRouting(routing) ? { kind: "standard" } : serviceTier,
- selectedProvider,
- providerConfigured,
- input.chatGptAccountLabel,
- routing,
- editable,
- settingsEditable,
- ),
- hintLayout: "stacked",
- initialValue: nextSelection,
- notices: externalNotice === undefined ? [] : [externalNotice],
- });
- } catch (error) {
- if (!(error instanceof WizardCancelledError)) throw error;
- // Esc discards the draft. Say so: before drafts existed, a completed
- // model pick applied immediately, so a silent drop reads as success.
- if (hasModelSettingsChanges(patch)) return { kind: "cancelled", discardedDraft: true };
- break;
- }
- }
-
- if (pick === "done") {
- completed = true;
- commitDraft = true;
- break;
- }
-
- if (pick === "model") {
- input.onScreen?.("model_settings");
- const pickModelSettings = deps.pickModelSettings;
- if (pickModelSettings === undefined) {
- throw new Error("runModelFlow requires a pickModelSettings dep to open the model screen.");
- }
- const request: ModelSettingsRequest = {
- model: editable
- ? { kind: "pick", options: modelListRows(catalog), current }
- : {
- kind: "fixed",
- current,
- reason: "Set via an SDK model call in agent.ts; edit the source to change it",
- },
- reasoning,
- serviceTier: isChatGptModelRouting(routing) ? { kind: "standard" } : serviceTier,
- settingsEditable,
- externalRouting: sourceOwnedExternalRouting,
- capabilitiesFor: (modelId) => gatewayModelCapabilities(catalog, modelId),
- };
- const result = await pickModelSettings(request);
- signal?.throwIfAborted();
- if (result === undefined) {
- nextSelection = "model";
- continue;
- }
- if (result.model !== undefined) {
- current = result.model;
- routing = routingForModelSelection(result.model);
- patch.model = { kind: "set", value: result.model };
- }
- if (result.reasoning !== undefined) {
- reasoning = result.reasoning === "default" ? null : result.reasoning;
- patch.reasoning =
- reasoning === null ? { kind: "remove" } : { kind: "set", value: reasoning };
- }
- if (result.serviceTier !== undefined && !isChatGptModelRouting(routing)) {
- serviceTier =
- result.serviceTier === "priority" ? { kind: "priority" } : { kind: "standard" };
- patch.gatewayServiceTier =
- result.serviceTier === "priority"
- ? { kind: "set", value: "priority" }
- : { kind: "remove" };
- }
- nextSelection = "done";
- continue;
- }
-
- input.onScreen?.("model_provider");
- const result = await deps.runProviderFlow({
- appRoot: environmentRoot,
- prompter,
- signal,
- availableProviders,
- selectedProvider,
- });
- // Backing out of the provider sub-flow changed nothing; the cursor stays on
- // the provider row so a retry is one keypress away.
- if (result.kind === "cancelled") {
- if (signal?.aborted) return { kind: "cancelled" };
- nextSelection = "provider";
- continue;
- }
- // Direct-provider setup remains source-owned. Acknowledging the instructions
- // returns to Done so the user can explicitly continue without persisting a
- // misleading eve provider selection.
- if (result.kind === "external-provider") {
- if (signal?.aborted) return { kind: "cancelled" };
- nextSelection = "done";
- continue;
- }
- nextProviderSelection = result.kind;
- if (nextProviderSelection === "chatgpt") {
- shouldAuthenticateChatGpt = true;
- if (!isChatGptModelRouting(routing)) {
- patch.model = { kind: "set", value: DEFAULT_CHATGPT_MODEL_SELECTION };
- patch.gatewayServiceTier = { kind: "remove" };
- }
- } else if (isChatGptModelRouting(routing)) {
- patch.model = { kind: "set", value: DEFAULT_AGENT_MODEL_ID };
- }
- commitDraft = true;
- break;
- }
-
- const selectsChatGpt =
- patch.model.kind === "set" && parseChatGptModelSelection(patch.model.value) !== undefined;
- if (commitDraft && selectsChatGpt) {
- patch.gatewayServiceTier = { kind: "remove" };
- shouldAuthenticateChatGpt = true;
- }
- if (commitDraft && shouldAuthenticateChatGpt) {
- await authenticateChatGpt(deps, prompter, signal);
- }
-
- if (commitDraft && hasModelSettingsChanges(patch)) {
- lastApply = await deps.applySettings({ appRoot, patch });
- }
- if (commitDraft && nextProviderSelection !== undefined && lastApply?.kind !== "rejected") {
- await deps.writeProviderSelection(environmentRoot, nextProviderSelection);
- committedProviderSelection = nextProviderSelection;
- }
- if (lastApply !== undefined && committedProviderSelection === undefined) {
- signal?.throwIfAborted();
- }
-
- if (
- lastApply === undefined &&
- committedProviderSelection === undefined &&
- !shouldAuthenticateChatGpt
- ) {
- return completed ? { kind: "done", accessChanged: false } : { kind: "cancelled" };
- }
- const done: Extract<ModelFlowResult, { kind: "done" }> = {
+ const applied = await deps.applySettings({
+ appRoot,
+ patch: {
+ model: result.model === undefined ? { kind: "keep" } : { kind: "set", value: result.model },
+ reasoning:
+ result.reasoning === undefined
+ ? { kind: "keep" }
+ : result.reasoning === "default"
+ ? { kind: "remove" }
+ : { kind: "set", value: result.reasoning },
+ gatewayServiceTier:
+ result.serviceTier === undefined
+ ? { kind: "keep" }
+ : result.serviceTier === "standard"
+ ? { kind: "remove" }
+ : { kind: "set", value: "priority" },
+ },
+ });
+ return {
kind: "done",
- accessChanged:
- lastApply?.kind === "changed" ||
- committedProviderSelection !== undefined ||
- shouldAuthenticateChatGpt,
+ accessChanged: applied.kind === "changed",
+ modelMessage: formatApplyModelSettingsOutcome(applied),
};
- if (lastApply !== undefined) done.modelMessage = formatApplyModelSettingsOutcome(lastApply);
- else if (shouldAuthenticateChatGpt) done.modelMessage = "ChatGPT login ready.";
- if (committedProviderSelection !== undefined) {
- done.providerSelection = committedProviderSelection;
- }
- return done;
-}
-
-function routingForModelSelection(selection: string): ModelRouting {
- if (parseChatGptModelSelection(selection) !== undefined) {
- return { kind: "external", provider: "codex" };
- }
- return { kind: "gateway", target: selection.split("/")[0] ?? "" };
-}
-
-async function authenticateChatGpt(
- deps: ModelFlowDeps,
- prompter: Prompter,
- signal: AbortSignal | undefined,
-): Promise<void> {
- const spinner = prompter.log.spinner?.("Waiting for ChatGPT sign-in in your browser…", {
- kind: "external-action",
- emphasis: "browser",
- });
- try {
- await deps.ensureChatGptAuth({
- signal,
- log: (message) => prompter.log.info(message),
- });
- } finally {
- spinner?.stop();
- }
-}
-
-function hasModelSettingsChanges(patch: AgentModelSettingsPatch): boolean {
- return (
- patch.model.kind !== "keep" ||
- patch.reasoning.kind !== "keep" ||
- patch.gatewayServiceTier.kind !== "keep"
- );
}
/**
@@ -584,15 +221,19 @@ async function readCurrentAgentModel(appRoot: string): Promise<CurrentAgentModel
const { compiledState } = await inspectApplication(appRoot);
const config = compiledState?.manifest.config;
const model = config?.model;
- // A source-backed model (an SDK model call) carries `source`; a string id
- // does not, and only a string is a literal the editor can rewrite.
- const chatgpt = isChatGptModelRouting(model?.routing);
+ const authored =
+ model?.source === undefined ? undefined : await readAuthoredModelSelection(appRoot);
+ const helper = authored === undefined ? undefined : parseModelHelper(authored)?.helper;
return {
- id: chatgpt && model !== undefined ? `chatgpt/${model.id}` : (model?.id ?? null),
+ id:
+ helper && model !== undefined
+ ? `${MODEL_HELPERS[helper].prefix}${model.id}`
+ : (model?.id ?? null),
+ helper,
routing: model?.routing ?? null,
reasoning: config?.reasoning ?? null,
serviceTier: readGatewayServiceTier(model?.providerOptions),
- editable: model !== undefined && (model.source === undefined || chatgpt),
+ editable: model !== undefined && (model.source === undefined || helper !== undefined),
settingsEditable: config?.source !== undefined,
};
} catch {
diff --git a/packages/eve/src/setup/flows/provider-selection-cycle.integration.test.ts b/packages/eve/src/setup/flows/provider-selection-cycle.integration.test.ts
index a93bf2d0b..5c3ad14f0 100644
--- a/packages/eve/src/setup/flows/provider-selection-cycle.integration.test.ts
+++ b/packages/eve/src/setup/flows/provider-selection-cycle.integration.test.ts
@@ -1,108 +1,82 @@
-import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { afterEach, describe, expect, it, vi } from "vitest";
-
+import { afterEach, expect, it, vi } from "vitest";
import { createFakePrompter } from "#internal/testing/fake-prompter.js";
-import { DEFAULT_CHATGPT_MODEL_SELECTION } from "#shared/chatgpt-model.js";
-import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";
-import {
- readProviderSelection,
- writeProviderSelection,
- type ProviderSelection,
-} from "#setup/provider-settings.js";
-
-import { runModelFlow, type CurrentAgentModel, type ModelFlowDeps } from "./model.js";
-import { runProviderFlow, type ProviderFlowDeps, type ProviderPickerChoice } from "./provider.js";
-
+const mocks = vi.hoisted(() => ({ secrets: new Map<string, string>(), defaults: vi.fn() }));
+vi.mock("#internal/model-auth/store.js", async (original) => ({
+ ...(await original<typeof import("#internal/model-auth/store.js")>()),
+ readModelSecret: async (name: string) => mocks.secrets.get(name),
+ writeModelSecret: async (name: string, key: string) => {
+ mocks.secrets.set(name, key);
+ },
+ writeDefaultConnection: mocks.defaults,
+}));
+vi.mock("#services/inspect-application.js", () => ({
+ inspectApplication: async () => ({
+ compiledState: {
+ manifest: {
+ config: { model: { id: "openai/gpt-5.6-luna-fast", routing: { kind: "gateway" } } },
+ },
+ },
+ }),
+}));
+vi.mock("./model-source-change.js", () => ({
+ readAuthoredModelSelection: async () => "openai/gpt-5.6-luna-fast",
+ changeValidatedAgentModel: async () => ({ kind: "changed" }),
+}));
+vi.mock("#internal/model-auth/available-models.js", () => ({
+ availableDirectModels: async () => ["gpt-5.6-luna-fast", "claude-sonnet-5"],
+ availableHelperModels: async () => ["gpt-5.6-luna-fast", "claude-sonnet-5"],
+}));
+vi.mock("#internal/model-auth/vercel.js", () => ({
+ resolveVercelSession: async () => ({
+ accessToken: "account-secret",
+ teamId: "team_alice",
+ teamName: "Alice",
+ }),
+ validateVercelAccess: async () => {},
+}));
+vi.mock("./vercel-model-login.js", () => ({
+ loginVercelModel: async () => ({ teamId: "team_alice", teamName: "Alice" }),
+}));
+vi.mock("./chatgpt-auth.js", () => ({ ensureChatGptAuth: async () => {} }));
+vi.mock("../boxes/select-model.js", () => ({
+ fetchGatewayCatalog: async () => [{ id: "openai/gpt-5.6-luna-fast", type: "language" }],
+}));
+vi.mock("#setup/validate-gateway-key.js", () => ({
+ validateGatewayApiKey: async () => ({ kind: "valid" }),
+}));
+import { runModelLogin } from "./model-login.js";
+import { readProviderSelection, readProviderTeamSync } from "#setup/provider-settings.js";
const roots: string[] = [];
-
afterEach(async () => {
+ vi.unstubAllEnvs();
+ mocks.secrets.clear();
+ vi.clearAllMocks();
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
-
-describe("provider selection", () => {
- it("cycles among independently available providers", async () => {
- const root = await mkdtemp(join(tmpdir(), "eve-provider-selection-"));
- roots.push(root);
- await writeFile(join(root, ".env.local"), "AI_GATEWAY_API_KEY=key\nVERCEL_OIDC_TOKEN=token\n");
- await writeProviderSelection(root, "ai-gateway-project");
-
- let currentModel: CurrentAgentModel = {
- id: DEFAULT_AGENT_MODEL_ID,
- routing: { kind: "gateway", target: "openai" },
- reasoning: null,
- serviceTier: { kind: "standard" },
- editable: true,
- settingsEditable: true,
- };
- const choices: ProviderPickerChoice[] = [
- { kind: "chatgpt" },
- { kind: "ai-gateway-project" },
- { kind: "ai-gateway-key", key: "replacement-key", validation: { kind: "valid" } },
- { kind: "ai-gateway-project" },
- ];
- const providerDeps: ProviderFlowDeps = {
- getVercelAuthStatus: vi.fn<ProviderFlowDeps["getVercelAuthStatus"]>(
- async () => "authenticated",
- ),
- runLinkFlow: vi.fn<ProviderFlowDeps["runLinkFlow"]>(async () => ({ kind: "done" })),
- appendEnv: vi.fn<ProviderFlowDeps["appendEnv"]>(async () => ({
- written: ["AI_GATEWAY_API_KEY"],
- skipped: [],
- })),
- validateGatewayApiKey: vi.fn<ProviderFlowDeps["validateGatewayApiKey"]>(async () => ({
- kind: "valid",
- })),
- };
- const applySettings = vi.fn<ModelFlowDeps["applySettings"]>(async ({ patch }) => {
- if (patch.model.kind !== "set") return { kind: "unchanged" };
- const chatGpt = patch.model.value === DEFAULT_CHATGPT_MODEL_SELECTION;
- currentModel = {
- ...currentModel,
- id: patch.model.value,
- routing: chatGpt
- ? { kind: "external", provider: "codex" }
- : { kind: "gateway", target: patch.model.value.split("/")[0] ?? "" },
- };
- return { kind: "changed", changed: ["model"], model: patch.model.value };
+it("switches all five connections while keeping keys out of project files", async () => {
+ vi.stubEnv("EVE_DEV", "1");
+ for (const key of ["OPENAI_API_KEY", "ANTHROPIC_API_KEY", "AI_GATEWAY_API_KEY"])
+ vi.stubEnv(key, "");
+ const root = await mkdtemp(join(tmpdir(), "eve-model-login-"));
+ roots.push(root);
+ await writeFile(join(root, ".env.local"), "USER_SETTING=preserved\n");
+ for (const selected of ["chatgpt", "vercel", "ai-gateway-key", "openai", "anthropic"]) {
+ const fake = createFakePrompter({ single: () => selected, password: () => "entered-secret" });
+ expect(await runModelLogin({ appRoot: root, prompter: fake.prompter })).toMatchObject({
+ kind: "ready",
+ reload: ["chatgpt", "openai", "anthropic"].includes(selected),
});
- const deps: Partial<ModelFlowDeps> = {
- readCurrentModel: vi.fn(async () => currentModel),
- applySettings,
- selectModel: { fetchModels: async () => [] },
- runProviderFlow: (input) =>
- runProviderFlow({
- ...input,
- picker: async () => {
- const choice = choices.shift();
- if (choice === undefined) throw new Error("Provider choice script exhausted");
- return choice;
- },
- deps: providerDeps,
- }),
- ensureChatGptAuth: vi.fn(async () => {}),
- };
-
- const selectNextProvider = async (expected: ProviderSelection): Promise<void> => {
- const { prompter } = createFakePrompter({ single: () => "provider" });
- await expect(runModelFlow({ appRoot: root, prompter, deps })).resolves.toMatchObject({
- kind: "done",
- providerSelection: expected,
- });
- await expect(readProviderSelection(root)).resolves.toBe(expected);
- };
-
- await selectNextProvider("chatgpt");
- await selectNextProvider("ai-gateway-project");
- await selectNextProvider("ai-gateway-key");
- await selectNextProvider("ai-gateway-project");
-
- expect(choices).toEqual([]);
- expect(providerDeps.runLinkFlow).not.toHaveBeenCalled();
- expect(providerDeps.getVercelAuthStatus).not.toHaveBeenCalled();
- expect(providerDeps.appendEnv).toHaveBeenCalledOnce();
- expect(deps.ensureChatGptAuth).toHaveBeenCalledOnce();
- expect(applySettings).toHaveBeenCalledTimes(2);
- });
+ expect(await readProviderSelection(root)).toBe(selected);
+ expect(mocks.defaults).toHaveBeenLastCalledWith(selected);
+ const metadata = await readFile(join(root, ".eve/provider.json"), "utf8");
+ expect(metadata).not.toContain("entered-secret");
+ expect(metadata).not.toContain("account-secret");
+ if (selected === "vercel") expect(readProviderTeamSync(root)?.teamId).toBe("team_alice");
+ else expect(readProviderTeamSync(root)).toBeUndefined();
+ expect(await readFile(join(root, ".env.local"), "utf8")).toBe("USER_SETTING=preserved\n");
+ }
+ expect(mocks.secrets.size).toBe(3);
});
diff --git a/packages/eve/src/setup/flows/registry.test.ts b/packages/eve/src/setup/flows/registry.test.ts
index 17ab8e1a4..44dfcd516 100644
--- a/packages/eve/src/setup/flows/registry.test.ts
+++ b/packages/eve/src/setup/flows/registry.test.ts
@@ -1,558 +1,114 @@
import { describe, expect, it, vi } from "vitest";
-
import { createFakePrompter } from "#internal/testing/fake-prompter.js";
-import { HumanActionRequiredError } from "#setup/human-action.js";
-import { PlannerNavigationError } from "#setup/prompter.js";
+import { createSelectOptionCodec } from "#setup/cli/select-option-codec.js";
+import { filterOptions } from "#setup/cli/select-state.js";
import { WizardCancelledError } from "#setup/step.js";
-
import { runRegistryFlow, type RegistryFlowDeps } from "./registry.js";
-
-const APP_ROOT = "/tmp/agent";
-
-function deps(overrides: Partial<RegistryFlowDeps> = {}): RegistryFlowDeps {
+function deps(): RegistryFlowDeps {
return {
browseRegistryCatalog: vi.fn(async () => ({
+ items: [{ address: "connection/linear", name: "Linear", source: "Vercel" }],
+ total: 1,
+ errors: [],
+ })),
+ installRegistryItem: vi.fn(async () => ({ output: [] })),
+ detectDeployment: vi.fn(async () => ({ state: "unlinked" }) as const),
+ runDeployFlow: vi.fn(async () => ({ kind: "deployed" }) as const),
+ };
+}
+describe("runRegistryFlow", () => {
+ it("finds providers by capability or title and installs the filtered selection", async () => {
+ const flow = deps();
+ flow.browseRegistryCatalog = vi.fn(async () => ({
items: [
{
- address: "channel/web",
- name: "channel/web",
- title: "Web Chat",
- description: "A chat UI for your agent",
+ address: "channel/blooio",
+ name: "channel/blooio",
+ title: "Blooio",
+ description: "Send and receive iMessage, RCS, and SMS through Blooio.",
+ source: "Vercel",
+ },
+ {
+ address: "channel/linq",
+ name: "channel/linq",
+ title: "Linq",
+ description: "Connect an eve agent to iMessage and SMS through Linq.",
source: "Vercel",
},
{
- address: "connection/linear",
- name: "connection/linear",
- title: "Linear",
- description: "Issue tracking",
+ address: "channel/teams",
+ name: "channel/teams",
+ title: "Microsoft Teams",
source: "Vercel",
},
],
- total: 2,
+ total: 3,
errors: [],
- })),
- installRegistryItem: vi.fn(async () => ({ output: [] })),
- detectDeployment: vi.fn(async () => ({ state: "unlinked" as const })),
- runDeployFlow: vi.fn(async () => ({ kind: "deployed" as const })),
- ...overrides,
- };
-}
-
-describe("runRegistryFlow", () => {
- it("plans channels and integrations together, then installs the full plan in order", async () => {
- const answers = ["install"];
- const selections = [["channel/web"], ["connection/linear"]];
- const fake = createFakePrompter({
- single: () => answers.shift()!,
- multiple: () => selections.shift()!,
- });
- const flowDeps = deps();
- const starts: string[] = [];
-
- await expect(
- runRegistryFlow({
- appRoot: APP_ROOT,
- prompter: fake.prompter,
- deps: flowDeps,
- onItemStart: (item, index, total) => starts.push(`${item.address}:${index + 1}/${total}`),
- }),
- ).resolves.toEqual({
- kind: "done",
- result: {
- items: [
- { title: "Web Chat", facts: [], output: [] },
- { title: "Linear", facts: [], output: [] },
- ],
- failures: [],
- },
- });
-
- expect(starts).toEqual(["channel/web:1/2", "connection/linear:2/2"]);
- expect(flowDeps.installRegistryItem).toHaveBeenNthCalledWith(
- 1,
- APP_ROOT,
- "channel/web",
- expect.objectContaining({ silent: true, prompter: fake.prompter }),
- );
- expect(flowDeps.installRegistryItem).toHaveBeenNthCalledWith(
- 2,
- APP_ROOT,
- "connection/linear",
- expect.objectContaining({ silent: true, prompter: fake.prompter }),
- );
- });
-
- it("orders first-party Photon before non-featured channel providers", async () => {
- const channelLabels: string[] = [];
- const fake = createFakePrompter({
- multiple: (options) => {
- if (options.message === "Where should people reach your agent?") {
- channelLabels.push(...options.options.map((option) => option.label));
- }
- return [];
- },
- single: () => "install",
- });
- const flowDeps = deps({
- browseRegistryCatalog: vi.fn(async () => ({
- items: [
- { address: "channel/blooio", name: "channel/blooio", title: "Blooio", source: "Vercel" },
- {
- address: "channel/photon-imessage",
- name: "channel/photon-imessage",
- title: "Photon iMessage",
- source: "Vercel",
- },
- ],
- total: 2,
- errors: [],
- })),
- });
-
- await runRegistryFlow({ appRoot: APP_ROOT, prompter: fake.prompter, deps: flowDeps });
-
- expect(channelLabels).toEqual(["Photon iMessage", "Blooio"]);
- });
-
- it("lets the user browse, retain selections, and review the plan before installing", async () => {
- const answers = ["install"];
- const prompts: unknown[] = [];
- const fake = createFakePrompter({
- single: (options) => {
- prompts.push(options);
- return answers.shift()!;
- },
- multiple: (options) => {
- prompts.push(options);
- return options.message === "What should your agent be able to work with?"
- ? ["connection/linear"]
- : [];
- },
- });
-
- await runRegistryFlow({ appRoot: APP_ROOT, prompter: fake.prompter, deps: deps() });
-
- expect(prompts[0]).toMatchObject({
- message: "Where should people reach your agent?",
- description: "You can add more later with /add.",
- multiple: true,
- search: true,
- placeholder: "Search channels",
- });
- expect(prompts[1]).toMatchObject({
- message: "What should your agent be able to work with?",
- multiple: true,
- search: true,
- placeholder: "Search integrations",
- });
- expect(prompts[2]).toMatchObject({
- message: "Review additions",
- navigation: {
- kind: "planner",
- activeStep: 2,
- steps: [{ label: "Channels" }, { label: "Integrations", count: 1 }, { label: "Review" }],
- },
- metadata: [{ label: "Integrations", value: "Linear" }],
- options: [
- { value: "install", label: "Install and set up" },
- { value: "back", label: "Back" },
- ],
- });
- });
-
- it("prefixes onboarding progress without changing standalone review", async () => {
- const prompts: unknown[] = [];
+ }));
const fake = createFakePrompter({
single: (options) => {
- prompts.push(options);
- return "install";
- },
- multiple: (options) => {
- prompts.push(options);
- return [];
- },
- });
-
- await runRegistryFlow({
- appRoot: APP_ROOT,
- prompter: fake.prompter,
- deps: deps(),
- plannerContext: {
- prefixSteps: [{ label: "Model", complete: true }],
- reviewMessage: "Review your agent",
- emptyActionLabel: "Finish setup",
- },
- });
-
- expect(prompts[0]).toMatchObject({
- navigation: {
- activeStep: 1,
- steps: [
- { label: "Model", complete: true },
- { label: "Channels" },
- { label: "Integrations" },
- { label: "Review" },
- ],
- },
- });
- expect(prompts[2]).toMatchObject({
- metadata: [],
- options: [
- { value: "install", label: "Finish setup" },
- { value: "back", label: "Back" },
- ],
- });
+ const codec = createSelectOptionCodec(options.options);
+ const matches = filterOptions(codec.options, " iMESSAGE ");
+ expect(matches.map((option) => codec.decode(option.value))).toEqual([
+ "channel/blooio",
+ "channel/linq",
+ ]);
+ expect(filterOptions(codec.options, "microsoft").map((option) => option.label)).toEqual([
+ "channel/teams",
+ ]);
+ expect(filterOptions(codec.options, "unrelated")).toEqual([]);
+ return codec.decode(matches[0]!.value);
+ },
+ });
+ await runRegistryFlow({ appRoot: "/agent", prompter: fake.prompter, deps: flow });
+ expect(flow.installRegistryItem).toHaveBeenCalledWith(
+ "/agent",
+ "channel/blooio",
+ expect.any(Object),
+ );
});
-
- it("starts bare /add on channels and keeps empty Review open", async () => {
- const prompts: unknown[] = [];
- const screens: Array<{ screen: string; registrySelectedCount?: number }> = [];
+ it("searches one catalog and installs the chosen item without a review", async () => {
+ const flow = deps();
const fake = createFakePrompter({
single: (options) => {
- prompts.push(options);
- return "install";
- },
- multiple: (options) => {
- prompts.push(options);
- return [];
+ expect(options.search).toBe(true);
+ return "connection/linear";
},
});
-
- await runRegistryFlow({
- appRoot: APP_ROOT,
- prompter: fake.prompter,
- onScreen: (screen) => screens.push(screen),
- deps: deps(),
- });
-
- expect(screens).toEqual([
- { screen: "registry_channels" },
- { screen: "registry_integrations" },
- { screen: "registry_review", registrySelectedCount: 0 },
- { screen: "registry_install" },
- ]);
- expect(prompts).toMatchObject([
- { message: "Where should people reach your agent?" },
- { message: "What should your agent be able to work with?" },
- {
- message: "Review additions",
- description: "No channels or integrations selected.",
- options: [
- { value: "install", label: "Finish without adding" },
- { value: "back", label: "Back" },
- ],
- },
- ]);
- });
-
- it("preserves selections while navigating forward and back with arrow keys", async () => {
- let lap = 0;
- const fake = createFakePrompter({
- single: () => "install",
- multiple: (options) => {
- lap += 1;
- if (lap === 1) throw new PlannerNavigationError("forward", ["channel/web"]);
- if (lap === 2) throw new PlannerNavigationError("back", ["connection/linear"]);
- if (lap === 3) {
- expect(options.initialValues).toEqual(["channel/web"]);
- return ["channel/web"];
- }
- expect(options.initialValues).toEqual(["connection/linear"]);
- return ["connection/linear"];
- },
- });
- const installRegistryItem = vi.fn<RegistryFlowDeps["installRegistryItem"]>(async () => ({
- output: [],
- }));
-
- await runRegistryFlow({
- appRoot: APP_ROOT,
- prompter: fake.prompter,
- deps: deps({ installRegistryItem }),
- });
-
- expect(installRegistryItem).toHaveBeenCalledTimes(2);
- });
-
- it("puts curated choices first while preserving registry order for the remaining entries", async () => {
- const prompts: unknown[] = [];
- const fake = createFakePrompter({
- single: () => "install",
- multiple: (options) => {
- prompts.push(options);
- return [];
- },
- });
- await runRegistryFlow({
- appRoot: APP_ROOT,
- prompter: fake.prompter,
- deps: deps({
- browseRegistryCatalog: vi.fn(async () => ({
- items: [
- {
- address: "channel/discord",
- name: "channel/discord",
- title: "Discord",
- source: "Vercel",
- },
- { address: "channel/slack", name: "channel/slack", title: "Slack", source: "Vercel" },
- { address: "channel/web", name: "channel/web", title: "Web Chat", source: "Vercel" },
- {
- address: "channel/github",
- name: "channel/github",
- title: "GitHub",
- source: "Vercel",
- },
- {
- address: "channel/telegram",
- name: "channel/telegram",
- title: "Telegram",
- source: "Vercel",
- },
- ],
- total: 5,
- errors: [],
- })),
- }),
- });
-
expect(
- (prompts[0] as { options: { value: string }[] }).options.map((option) => option.value),
- ).toEqual([
- "channel/web",
- "channel/slack",
- "channel/github",
- "channel/discord",
- "channel/telegram",
- ]);
- });
-
- it("confirms and installs an explicitly requested address without opening the planner", async () => {
- const prompts: unknown[] = [];
- const fake = createFakePrompter({
- single: (options) => {
- prompts.push(options);
- return "install";
- },
- });
- const browseRegistryCatalog = vi.fn<RegistryFlowDeps["browseRegistryCatalog"]>();
- const installRegistryItem = vi.fn<RegistryFlowDeps["installRegistryItem"]>(async () => ({
- output: [],
- }));
-
- await runRegistryFlow({
- appRoot: APP_ROOT,
- prompter: fake.prompter,
- initialAddress: "@acme/analytics",
- deps: deps({ browseRegistryCatalog, installRegistryItem }),
- });
-
- expect(prompts).toMatchObject([
- {
- message: "Add @acme/analytics?",
- options: [
- { value: "install", label: "Install and set up" },
- { value: "cancel", label: "Cancel" },
- ],
- },
- ]);
- expect(browseRegistryCatalog).not.toHaveBeenCalled();
- expect(installRegistryItem).toHaveBeenCalledWith(
- APP_ROOT,
- "@acme/analytics",
- expect.objectContaining({ silent: true }),
+ (await runRegistryFlow({ appRoot: "/agent", prompter: fake.prompter, deps: flow })).kind,
+ ).toBe("done");
+ expect(fake.selectMessages).toEqual(["Add to your agent"]);
+ expect(flow.installRegistryItem).toHaveBeenCalledOnce();
+ expect(flow.installRegistryItem).toHaveBeenCalledWith(
+ "/agent",
+ "connection/linear",
+ expect.any(Object),
);
});
-
- it("surfaces registry source failures on the planner", async () => {
- const prompts: unknown[] = [];
- const fake = createFakePrompter({
- single: () => "install",
- multiple: (options) => {
- prompts.push(options);
- return [];
- },
- });
-
+ it("installs an explicit address without another confirmation", async () => {
+ const flow = deps();
+ const fake = createFakePrompter();
await runRegistryFlow({
- appRoot: APP_ROOT,
+ appRoot: "/agent",
+ initialAddress: "connection/linear",
prompter: fake.prompter,
- deps: deps({
- browseRegistryCatalog: vi.fn(async () => ({
- items: [],
- total: 0,
- errors: [{ registry: "@acme", message: "Authentication required" }],
- })),
- }),
- });
-
- expect(prompts[0]).toMatchObject({
- notices: [{ tone: "warning", text: "@acme: Authentication required" }],
- });
- });
-
- it("propagates cancellation during installation instead of recording a failure", async () => {
- const answers = ["install"];
- const selections = [["channel/web"], []];
- const fake = createFakePrompter({
- single: () => answers.shift()!,
- multiple: () => selections.shift()!,
- });
- const controller = new AbortController();
- const reason = new Error("Setup interrupted");
- const installRegistryItem = vi.fn<RegistryFlowDeps["installRegistryItem"]>(async () => {
- controller.abort(reason);
- throw reason;
- });
-
- await expect(
- runRegistryFlow({
- appRoot: APP_ROOT,
- prompter: fake.prompter,
- signal: controller.signal,
- deps: deps({ installRegistryItem }),
- }),
- ).rejects.toBe(reason);
- expect(fake.selectMessages).not.toContain("Couldn't add Web Chat");
- });
-
- it("keeps a skipped installation failure in the result and proceeds with later items", async () => {
- const answers = ["install", "skip"];
- const selections = [["channel/web"], ["connection/linear"]];
- const fake = createFakePrompter({
- single: () => answers.shift()!,
- multiple: () => selections.shift()!,
- });
- const installRegistryItem = vi
- .fn<RegistryFlowDeps["installRegistryItem"]>()
- .mockRejectedValueOnce(new Error("Missing WEB_TOKEN\nSet it in your environment."))
- .mockResolvedValueOnce({ output: [] });
-
- await expect(
- runRegistryFlow({
- appRoot: APP_ROOT,
- prompter: fake.prompter,
- deps: deps({ installRegistryItem }),
- }),
- ).resolves.toMatchObject({
- kind: "done",
- result: {
- items: [expect.objectContaining({ title: "Linear" })],
- failures: [
- expect.objectContaining({
- title: "Web Chat",
- message: "Missing WEB_TOKEN\nSet it in your environment.",
- }),
- ],
- },
+ deps: flow,
});
- expect(fake.selectMessages).toContain("Couldn't add Web Chat");
+ expect(fake.selectMessages).toEqual([]);
+ expect(flow.browseRegistryCatalog).not.toHaveBeenCalled();
+ expect(flow.installRegistryItem).toHaveBeenCalledOnce();
});
-
- it("preserves an installation failure when its recovery prompt is cancelled", async () => {
- let prompt = 0;
+ it("cancels before installing anything", async () => {
+ const flow = deps();
const fake = createFakePrompter({
- single: () => (++prompt === 1 ? "install" : Promise.reject(new WizardCancelledError())),
- });
-
- await expect(
- runRegistryFlow({
- appRoot: APP_ROOT,
- prompter: fake.prompter,
- initialAddress: "channel/web",
- deps: deps({
- installRegistryItem: vi.fn(async () => {
- throw new Error("Missing WEB_TOKEN\nSet it in your environment.");
- }),
- }),
- }),
- ).resolves.toMatchObject({
- result: {
- failures: [{ title: "web", message: expect.stringContaining("WEB_TOKEN") }],
- cancelled: true,
+ single: () => {
+ throw new WizardCancelledError();
},
});
- });
-
- it("preserves a cancelled item when a later item fails fatally", async () => {
- const answers = ["install"];
- const selections = [["channel/web"], ["connection/linear"]];
- const fake = createFakePrompter({
- single: () => answers.shift()!,
- multiple: () => selections.shift()!,
- });
- const cause = new HumanActionRequiredError({
- kind: "vercel-login",
- command: "vercel login",
- reason: "Authentication required.",
- });
- const installRegistryItem = vi
- .fn<RegistryFlowDeps["installRegistryItem"]>()
- .mockRejectedValueOnce(new WizardCancelledError())
- .mockRejectedValueOnce(cause);
-
- await expect(
- runRegistryFlow({
- appRoot: APP_ROOT,
- prompter: fake.prompter,
- deps: deps({ installRegistryItem }),
- }),
- ).rejects.toMatchObject({
- cause,
- completed: {
- outcomes: [{ kind: "cancelled", title: "Web Chat" }],
- },
- });
- });
-
- it("lets structured setup failures reach the command boundary", async () => {
- const answers = ["install"];
- const selections = [["channel/web"], []];
- const fake = createFakePrompter({
- single: () => answers.shift()!,
- multiple: () => selections.shift()!,
- });
- const error = new HumanActionRequiredError({
- kind: "vercel-cli-upgrade",
- command: "vercel upgrade",
- reason: "The installed Vercel CLI is too old.",
- });
-
- await expect(
- runRegistryFlow({
- appRoot: APP_ROOT,
- prompter: fake.prompter,
- deps: deps({
- installRegistryItem: vi.fn(async () => {
- throw error;
- }),
- }),
- }),
- ).rejects.toBe(error);
- expect(fake.selectMessages).not.toContain("Couldn't add Web Chat");
- });
-
- it("offers deployment once after the selected batch completes", async () => {
- const answers = ["install", "deploy", "yes"];
- const fake = createFakePrompter({
- single: () => answers.shift()!,
- multiple: () => ["channel/web"],
- });
- const replaceContent = vi.fn();
- fake.prompter.replaceContent = replaceContent;
- const flowDeps = deps({
- detectDeployment: vi.fn(async () => ({ state: "linked" as const, projectId: "prj_1" })),
- installRegistryItem: vi.fn(async () => ({
- output: [],
- setup: { facts: [], deploymentRequired: true as const },
- })),
- });
-
- await expect(
- runRegistryFlow({ appRoot: APP_ROOT, prompter: fake.prompter, deps: flowDeps }),
- ).resolves.toMatchObject({ kind: "done", result: { deployed: "production" } });
- expect(flowDeps.runDeployFlow).toHaveBeenCalledOnce();
- expect(replaceContent).toHaveBeenCalledWith();
- expect(fake.selectMessages).not.toContain("Add an integration");
+ expect(
+ await runRegistryFlow({ appRoot: "/agent", prompter: fake.prompter, deps: flow }),
+ ).toEqual({ kind: "cancelled" });
+ expect(flow.installRegistryItem).not.toHaveBeenCalled();
});
});
diff --git a/packages/eve/src/setup/flows/registry.ts b/packages/eve/src/setup/flows/registry.ts
index 6ab397a93..b581a13e6 100644
--- a/packages/eve/src/setup/flows/registry.ts
+++ b/packages/eve/src/setup/flows/registry.ts
@@ -1,32 +1,14 @@
import type { RegistryCatalogItem } from "#cli/commands/registry.js";
import { HumanActionRequiredError } from "#setup/human-action.js";
-import { PlannerNavigationError } from "#setup/prompter.js";
-import type {
- MultiSelectOptions,
- Prompter,
- SelectNotice,
- SelectOption,
- SingleSelectOptions,
-} from "#setup/prompter.js";
+import type { Prompter, SingleSelectOptions } from "#setup/prompter.js";
import { WizardCancelledError } from "#setup/step.js";
import { withSpinner } from "#setup/with-spinner.js";
import { createRegistrySession, type RegistrySessionResult } from "./registry-session.js";
type Item = RegistryCatalogItem;
-type Section = keyof typeof SECTIONS;
-type PlannerScreen = Section | "review";
-
-const PLANNER_STEPS = ["Channels", "Integrations", "Review"] as const;
-
-export interface RegistryPlannerContext {
- /** Steps owned by an enclosing journey, rendered before the registry steps. */
- prefixSteps?: readonly { label: string; complete?: boolean }[];
- /** Facts owned by the enclosing journey, rendered before registry selections. */
- reviewMetadata?: readonly { label: string; value: string }[];
- reviewMessage?: string;
- primaryActionLabel?: string;
- emptyActionLabel?: string;
+function label(item: Item): string {
+ return item.name;
}
export interface RegistryFlowDeps {
@@ -46,235 +28,6 @@ export class RegistryFlowFailedError extends Error {
}
}
-const SECTIONS = {
- channels: {
- title: "Where should people reach your agent?",
- description: "You can add more later with /add.",
- featured: [
- "channel/web",
- "channel/slack",
- "channel/github",
- "channel/linear",
- "channel/photon-imessage",
- ],
- includes: (item: Item) => item.name.startsWith("channel/"),
- },
- integrations: {
- title: "What should your agent be able to work with?",
- featured: [
- "extension/github-tools",
- "connection/linear",
- "connection/notion",
- "connection/vercel",
- "extension/agent-browser",
- "eve/self-modification",
- ],
- includes: (item: Item) => !item.name.startsWith("channel/"),
- },
-} as const;
-
-function label(item: Item): string {
- return item.title ?? item.name.split("/").at(-1) ?? item.name;
-}
-
-function isPlannerItem(section: Section, item: Item): boolean {
- return item.name.includes("/") && SECTIONS[section].includes(item);
-}
-
-function orderedSectionItems(section: Section, catalog: readonly Item[]): Item[] {
- const matching = catalog.filter((item) => isPlannerItem(section, item));
- const featured = SECTIONS[section].featured
- .map((name) => matching.find((item) => item.name === name))
- .filter((item): item is Item => item !== undefined);
- const featuredAddresses = new Set(featured.map((item) => item.address));
- return [...featured, ...matching.filter((item) => !featuredAddresses.has(item.address))];
-}
-
-function plannerLabel(item: Item): string {
- return item.name === "connection/linear" ? "Linear MCP" : label(item);
-}
-
-function sectionRows(section: Section, catalog: readonly Item[]): SelectOption<string>[] {
- return orderedSectionItems(section, catalog).map((item) => ({
- value: item.address,
- label: plannerLabel(item),
- hint: item.description,
- }));
-}
-
-function selectedInSection(
- section: Section,
- catalog: readonly Item[],
- selected: ReadonlySet<string>,
-): string[] {
- return catalog
- .filter((item) => isPlannerItem(section, item) && selected.has(item.address))
- .map((item) => item.address);
-}
-
-function plannerNavigation(
- activeStep: number,
- input: {
- catalog: readonly Item[];
- selected: ReadonlySet<string>;
- plannerContext?: RegistryPlannerContext;
- },
-): NonNullable<MultiSelectOptions<string>["navigation"]> {
- const prefix = (input.plannerContext?.prefixSteps ?? []).map((step) => ({
- label: step.label,
- complete: step.complete,
- }));
- return {
- kind: "planner",
- activeStep: prefix.length + activeStep,
- firstNavigableStep: prefix.length,
- steps: [
- ...prefix,
- ...PLANNER_STEPS.map((label, index) => {
- if (index === 2) return { label };
- const section = index === 0 ? "channels" : "integrations";
- const count = selectedInSection(section, input.catalog, input.selected).length;
- return count === 0 ? { label } : { label, count };
- }),
- ],
- };
-}
-
-function replaceSectionSelection(input: {
- section: Section;
- catalog: readonly Item[];
- selected: Set<string>;
- addresses: readonly string[];
-}): void {
- for (const item of input.catalog) {
- if (isPlannerItem(input.section, item)) input.selected.delete(item.address);
- }
- for (const address of input.addresses) input.selected.add(address);
-}
-
-async function editSection(input: {
- section: Section;
- prompter: Prompter;
- catalog: readonly Item[];
- selected: Set<string>;
- notices?: readonly SelectNotice[];
-}): Promise<"back" | "forward"> {
- const { section, catalog, prompter, selected } = input;
- const request: MultiSelectOptions<string> = {
- message: SECTIONS[section].title,
- multiple: true,
- search: true,
- placeholder: section === "channels" ? "Search channels" : "Search integrations",
- navigation: plannerNavigation(section === "channels" ? 0 : 1, input),
- initialValues: selectedInSection(section, catalog, selected),
- options: sectionRows(section, catalog),
- };
- if (section === "channels") request.description = SECTIONS.channels.description;
- if (input.notices !== undefined) request.notices = input.notices;
- try {
- const addresses = await prompter.select(request);
- replaceSectionSelection({ section, catalog, selected, addresses });
- return "forward";
- } catch (error) {
- if (!(error instanceof PlannerNavigationError)) throw error;
- const addresses = error.values.map((value) => {
- if (typeof value !== "string")
- throw new Error("Registry planner returned a non-string item.");
- return value;
- });
- replaceSectionSelection({ section, catalog, selected, addresses });
- return error.direction;
- }
-}
-
-async function editPlan(input: {
- prompter: Prompter;
- catalog: readonly Item[];
- itemsByAddress: ReadonlyMap<string, Item>;
- selected: Set<string>;
- notices?: readonly SelectNotice[];
- plannerContext?: RegistryPlannerContext;
- onScreen?: (input: {
- screen: "registry_channels" | "registry_integrations" | "registry_review" | "registry_install";
- registrySelectedCount?: number;
- }) => void;
-}): Promise<"install" | "cancelled"> {
- let screen: PlannerScreen = "channels";
- let notices = input.notices;
- while (true) {
- if (screen !== "review") {
- input.onScreen?.({
- screen: screen === "channels" ? "registry_channels" : "registry_integrations",
- });
- try {
- const direction = await editSection({
- ...input,
- section: screen,
- notices,
- });
- notices = undefined;
- if (direction === "back") {
- if (screen === "integrations") screen = "channels";
- } else {
- screen = screen === "channels" ? "integrations" : "review";
- }
- } catch (error) {
- if (!(error instanceof WizardCancelledError)) throw error;
- return "cancelled";
- }
- continue;
- }
-
- try {
- input.onScreen?.({ screen: "registry_review", registrySelectedCount: input.selected.size });
- const hasSelections = input.selected.size > 0;
- const selectedItems = [...input.selected].map((address) => {
- const item = input.itemsByAddress.get(address);
- if (item === undefined)
- throw new Error(`Registry item "${address}" is no longer available.`);
- return item;
- });
- const channels = selectedItems.filter((item) => item.name.startsWith("channel/"));
- const integrations = selectedItems.filter((item) => !item.name.startsWith("channel/"));
- const selectionMetadata = [
- ...(channels.length === 0
- ? []
- : [{ label: "Channels", value: channels.map(label).join(", ") }]),
- ...(integrations.length === 0
- ? []
- : [{ label: "Integrations", value: integrations.map(label).join(", ") }]),
- ];
- const request: SingleSelectOptions<"install" | "back"> = {
- message: input.plannerContext?.reviewMessage ?? "Review additions",
- metadata: [...(input.plannerContext?.reviewMetadata ?? []), ...selectionMetadata],
- navigation: plannerNavigation(2, input),
- options: [
- {
- value: "install",
- label: hasSelections
- ? (input.plannerContext?.primaryActionLabel ?? "Install and set up")
- : (input.plannerContext?.emptyActionLabel ?? "Finish without adding"),
- },
- { value: "back", label: "Back" },
- ],
- };
- if (!hasSelections) request.description = "No channels or integrations selected.";
- if (notices !== undefined) request.notices = notices;
- const review = await input.prompter.select(request);
- notices = undefined;
- if (review === "install") return "install";
- } catch (error) {
- if (error instanceof PlannerNavigationError && error.direction === "back") {
- screen = "integrations";
- continue;
- }
- if (!(error instanceof WizardCancelledError)) throw error;
- return "cancelled";
- }
- screen = "integrations";
- }
-}
-
function hasSettledOutcomes(
result: RegistrySessionResult | undefined,
): result is RegistrySessionResult {
@@ -284,18 +37,14 @@ function hasSettledOutcomes(
);
}
-/** Collects a channel and integration plan, then installs every chosen item in order. */
+/** Searches the catalog and installs one selected item with its required setup. */
export async function runRegistryFlow(input: {
appRoot: string;
prompter: Prompter;
signal?: AbortSignal;
- /** Registry item supplied by `/add <item>`, confirmed and installed directly. */
+ /** Registry item supplied by `/add <item>`, installed directly. */
initialAddress?: string;
- plannerContext?: RegistryPlannerContext;
- onScreen?: (input: {
- screen: "registry_channels" | "registry_integrations" | "registry_review" | "registry_install";
- registrySelectedCount?: number;
- }) => void;
+ onScreen?: (input: { screen: "registry_install"; registrySelectedCount?: number }) => void;
onItemStart?: (item: Item, index: number, total: number) => void;
/** Gives each installation its own cancellation boundary without ending the batch. */
runItem?<T>(task: (signal?: AbortSignal) => Promise<T>): Promise<T>;
@@ -306,14 +55,6 @@ export async function runRegistryFlow(input: {
const initialAddress = input.initialAddress?.trim();
let items: Item[];
if (initialAddress !== undefined && initialAddress !== "") {
- const confirmed = await input.prompter.select({
- message: `Add ${initialAddress}?`,
- options: [
- { value: "install" as const, label: "Install and set up" },
- { value: "cancel" as const, label: "Cancel" },
- ],
- });
- if (confirmed === "cancel") return { kind: "cancelled" };
items = [{ address: initialAddress, name: initialAddress, source: "Registry" }];
} else {
const browseRegistryCatalog =
@@ -323,28 +64,24 @@ export async function runRegistryFlow(input: {
browseRegistryCatalog(input.appRoot),
);
const catalog = [...catalogResult.items];
- const selected = new Set<string>();
- const notices = catalogResult.errors.map((error) => ({
- tone: "warning" as const,
- text: `${error.registry}: ${error.message}`,
- }));
- const itemsByAddress = new Map(catalog.map((item) => [item.address, item]));
- const plan = await editPlan({
- prompter: input.prompter,
- catalog,
- itemsByAddress,
- selected,
- notices,
- plannerContext: input.plannerContext,
- onScreen: input.onScreen,
- });
- if (plan !== "install") return { kind: "cancelled" };
- items = [...selected].map((address) => {
- const item = itemsByAddress.get(address);
- if (item === undefined)
- throw new Error(`Registry item "${address}" is no longer available.`);
- return item;
+ const address = await input.prompter.select({
+ message: "Add to your agent",
+ search: true,
+ options: catalog.map((item) => ({
+ value: item.address,
+ label: item.name,
+ hint: item.address,
+ keywords: [item.title ?? "", item.description ?? ""],
+ })),
+ notices: catalogResult.errors.map((error) => ({
+ tone: "warning" as const,
+ text: `${error.registry}: ${error.message}`,
+ })),
});
+ const item = catalog.find((item) => item.address === address);
+ if (item === undefined)
+ throw new Error("That registry item is no longer available. Run /add to try again.");
+ items = [item];
}
const installRegistryItem =
diff --git a/packages/eve/src/setup/flows/vercel-model-login.test.ts b/packages/eve/src/setup/flows/vercel-model-login.test.ts
new file mode 100644
index 000000000..668262b26
--- /dev/null
+++ b/packages/eve/src/setup/flows/vercel-model-login.test.ts
@@ -0,0 +1,150 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { WizardCancelledError } from "#setup/step.js";
+import { createFakePrompter } from "#internal/testing/fake-prompter.js";
+const mocks = vi.hoisted(() => ({
+ json: vi.fn(),
+ validate: vi.fn(),
+ write: vi.fn(),
+ cli: vi.fn(),
+ open: vi.fn(),
+}));
+vi.mock("node:timers/promises", () => ({ setTimeout: vi.fn(async () => {}) }));
+vi.mock("#internal/model-auth/vercel.js", async (original) => ({
+ ...(await original<typeof import("#internal/model-auth/vercel.js")>()),
+ authJson: mocks.json,
+ vercelOAuthEndpoints: async () => ({
+ device: "https://api.vercel.com/login/oauth/device-authorization",
+ token: "https://api.vercel.com/login/oauth/token",
+ }),
+ vercelApiJson: mocks.json,
+ validateVercelAccess: mocks.validate,
+}));
+vi.mock("#internal/model-auth/store.js", () => ({ writeVercelSession: mocks.write }));
+vi.mock("#internal/model-auth/vercel-cli.js", () => ({ readVercelCliTeam: mocks.cli }));
+vi.mock("#setup/primitives/open-url.js", () => ({ openUrl: mocks.open }));
+import { loginVercelModel } from "./vercel-model-login.js";
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.json
+ .mockResolvedValueOnce({
+ device_code: "device",
+ user_code: "ABCD",
+ verification_uri: "https://vercel.com/oauth/device",
+ interval: 1,
+ expires_in: 60,
+ })
+ .mockResolvedValueOnce({ access_token: "access", refresh_token: "refresh", expires_in: 3600 });
+});
+afterEach(() => vi.restoreAllMocks());
+it.each([undefined, "team_b"])(
+ "lets an explicit login switch away from the current team (project: %s)",
+ async (projectTeam) => {
+ mocks.json.mockResolvedValueOnce({
+ teams: [
+ { id: "team_a", name: "Alice" },
+ { id: "team_b", name: "Bob" },
+ ],
+ });
+ mocks.cli.mockResolvedValue("team_b");
+ const fake = createFakePrompter({
+ single: (options) => {
+ expect(options.initialValue).toBe("team_b");
+ expect(options.search).toBe(true);
+ return "team_a";
+ },
+ });
+ await loginVercelModel(fake.prompter, undefined, projectTeam);
+ expect(mocks.json.mock.calls[0]![1].body.get("scope")).toBe("openid offline_access");
+ expect(fake.selectMessages).toEqual(["Choose a Vercel team"]);
+ expect(mocks.validate).toHaveBeenCalledWith("access", "team_a", undefined);
+ expect(mocks.write.mock.calls[0]![0]).toMatchObject({
+ teamId: "team_a",
+ teamName: "Alice",
+ refreshToken: "refresh",
+ });
+ expect(mocks.write.mock.calls[0]![1]).toBe("cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp");
+ },
+);
+it("asks for a team when the CLI selection is unavailable", async () => {
+ mocks.json.mockResolvedValueOnce({
+ teams: [
+ { id: "team_a", name: "Alice" },
+ { id: "team_b", name: "Bob" },
+ ],
+ });
+ const fake = createFakePrompter({ single: () => "team_a" });
+ await loginVercelModel(fake.prompter);
+ expect(fake.selectMessages).toEqual(["Choose a Vercel team"]);
+});
+it("does not save a team rejected by Gateway", async () => {
+ mocks.json.mockResolvedValueOnce({ teams: [{ id: "team_a", name: "Alice" }] });
+ mocks.validate.mockRejectedValue(new Error("Unavailable"));
+ await expect(loginVercelModel(createFakePrompter().prompter)).rejects.toThrow("Unavailable");
+ expect(mocks.write).not.toHaveBeenCalled();
+});
+
+it("selects the only team without prompting", async () => {
+ mocks.json.mockResolvedValueOnce({ teams: [{ id: "team_only", name: "Only team" }] });
+ const fake = createFakePrompter();
+ await loginVercelModel(fake.prompter);
+ expect(fake.selectMessages).toEqual([]);
+ expect(mocks.validate).toHaveBeenCalledWith("access", "team_only", undefined);
+});
+
+it("preserves the saved session when team selection is cancelled", async () => {
+ mocks.json.mockResolvedValueOnce({
+ teams: [
+ { id: "team_a", name: "Alice" },
+ { id: "team_b", name: "Bob" },
+ ],
+ });
+ const fake = createFakePrompter({
+ single: () => {
+ throw new WizardCancelledError();
+ },
+ });
+ await expect(loginVercelModel(fake.prompter, undefined, "team_b")).rejects.toBeInstanceOf(
+ WizardCancelledError,
+ );
+ expect(mocks.validate).not.toHaveBeenCalled();
+ expect(mocks.write).not.toHaveBeenCalled();
+});
+
+it("lets another team be selected after Gateway rejects the first choice", async () => {
+ mocks.json.mockResolvedValueOnce({
+ teams: [
+ { id: "team_a", name: "Alice" },
+ { id: "team_b", name: "Bob" },
+ ],
+ });
+ mocks.validate.mockRejectedValueOnce(new Error("Unavailable")).mockResolvedValueOnce(undefined);
+ let attempt = 0;
+ const fake = createFakePrompter({ single: () => (attempt++ === 0 ? "team_a" : "team_b") });
+ await loginVercelModel(fake.prompter);
+ expect(fake.selectMessages).toEqual(["Choose a Vercel team", "Choose a Vercel team"]);
+ expect(mocks.write).toHaveBeenCalledOnce();
+ expect(mocks.write).toHaveBeenCalledWith(
+ expect.objectContaining({ teamId: "team_b" }),
+ "cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",
+ );
+});
+
+it("returns the validated team and retains its slug for the footer", async () => {
+ mocks.json.mockResolvedValueOnce({
+ teams: [{ id: "team_cached", name: "Alice Inc", slug: "alice" }],
+ });
+ expect(await loginVercelModel(createFakePrompter().prompter)).toEqual({
+ teamId: "team_cached",
+ teamName: "Alice Inc",
+ });
+ expect(mocks.validate).toHaveBeenCalledOnce();
+ const { resolveModelTeamSlug } = await import("#internal/model-auth/vercel-team.js");
+ vi.stubEnv("EVE_MODEL_CONNECTION", "vercel");
+ vi.stubEnv("EVE_MODEL_TEAM", "team_cached");
+ try {
+ expect(await resolveModelTeamSlug()).toBe("alice");
+ expect(mocks.json).toHaveBeenCalledTimes(3);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+});
diff --git a/packages/eve/src/setup/flows/vercel-model-login.ts b/packages/eve/src/setup/flows/vercel-model-login.ts
new file mode 100644
index 000000000..d12eded75
--- /dev/null
+++ b/packages/eve/src/setup/flows/vercel-model-login.ts
@@ -0,0 +1,159 @@
+import { setTimeout as delay } from "node:timers/promises";
+import { isObject } from "#shared/guards.js";
+import {
+ authJson,
+ vercelApiJson,
+ vercelOAuthEndpoints,
+ sessionFromToken,
+ validateVercelAccess,
+ VERCEL_MODEL_CLIENT_ID,
+ VERCEL_OAUTH_ISSUER,
+} from "#internal/model-auth/vercel.js";
+import { readVercelCliTeam } from "#internal/model-auth/vercel-cli.js";
+import { writeVercelSession } from "#internal/model-auth/store.js";
+import { withLoginProgress } from "./model-login-progress.js";
+import { rememberModelTeamSlug } from "#internal/model-auth/vercel-team.js";
+import { openUrl } from "#setup/primitives/open-url.js";
+import type { Prompter } from "#setup/prompter.js";
+
+export async function loginVercelModel(
+ prompter: Prompter,
+ signal?: AbortSignal,
+ preferredTeamId?: string,
+): Promise<{ teamId: string; teamName: string }> {
+ const { endpoints, device } = await withLoginProgress(
+ prompter,
+ "Opening Vercel sign-in…",
+ async () => {
+ const endpoints = await vercelOAuthEndpoints(signal);
+ const device = await authJson(endpoints.device, {
+ method: "POST",
+ body: new URLSearchParams({
+ client_id: VERCEL_MODEL_CLIENT_ID,
+ scope: "openid offline_access",
+ }),
+ signal,
+ });
+ return { endpoints, device };
+ },
+ );
+ if (
+ typeof device.device_code !== "string" ||
+ typeof device.verification_uri !== "string" ||
+ typeof device.user_code !== "string"
+ )
+ throw new Error("Could not start Vercel sign-in. Retry /login.");
+ const url =
+ typeof device.verification_uri_complete === "string"
+ ? device.verification_uri_complete
+ : device.verification_uri;
+ const parsed = URL.parse(url);
+ if (parsed?.origin !== VERCEL_OAUTH_ISSUER)
+ throw new Error("Vercel returned an unexpected sign-in URL. Retry /login.");
+ prompter.log.info(`Open ${url} · code ${device.user_code}`);
+ openUrl(url);
+ let interval =
+ typeof device.interval === "number" ? Math.max(1, Math.min(30, device.interval)) : 5;
+ const duration = typeof device.expires_in === "number" ? Math.min(600, device.expires_in) : 300;
+ const deadline = Date.now() + duration * 1000;
+ const spinner = prompter.log.spinner?.("Finish signing in to Vercel in your browser", {
+ kind: "external-action",
+ emphasis: "your browser",
+ });
+ let session;
+ try {
+ while (Date.now() < deadline) {
+ await delay(interval * 1000, undefined, { signal });
+ const token = await authJson(endpoints.token, {
+ method: "POST",
+ body: new URLSearchParams({
+ client_id: VERCEL_MODEL_CLIENT_ID,
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
+ device_code: device.device_code,
+ }),
+ signal,
+ });
+ if (token.error === "authorization_pending") continue;
+ if (token.error === "slow_down") {
+ interval = Math.min(30, interval + 5);
+ continue;
+ }
+ if (token.error) throw new Error("Vercel sign-in was declined or expired. Retry /login.");
+ session = sessionFromToken(token);
+ break;
+ }
+ } finally {
+ spinner?.stop();
+ }
+ if (!session) throw new Error("Vercel sign-in timed out. Retry /login.");
+ const [teams, cliTeam] = await withLoginProgress(prompter, "Loading Vercel teams…", () =>
+ Promise.all([loadTeams(session.accessToken, signal), readVercelCliTeam()]),
+ );
+ const preferred =
+ teams.find((team) => team.id === preferredTeamId) ?? teams.find((team) => team.id === cliTeam);
+ let team = teams.length === 1 ? teams[0] : undefined;
+ while (true) {
+ if (!team) {
+ const id = await prompter.select({
+ message: "Choose a Vercel team",
+ search: true,
+ initialValue: preferred?.id,
+ options: teams.map((team) => ({ value: team.id, label: team.name })),
+ });
+ team = teams.find((candidate) => candidate.id === id);
+ }
+ if (!team) throw new Error("That Vercel team is no longer available. Retry /login.");
+ const selectedTeam = team;
+ try {
+ await withLoginProgress(
+ prompter,
+ `Checking AI Gateway access for ${team.slug ?? team.name}…`,
+ () => validateVercelAccess(session.accessToken, selectedTeam.id, signal),
+ );
+ break;
+ } catch (error) {
+ signal?.throwIfAborted();
+ if (teams.length === 1) throw error;
+ prompter.log.warning(
+ "AI Gateway is unavailable for that team. Choose another team or press Esc to return.",
+ );
+ team = undefined;
+ }
+ }
+ session.teamId = team.id;
+ session.teamName = team.name;
+ signal?.throwIfAborted();
+ await writeVercelSession(session, VERCEL_MODEL_CLIENT_ID);
+ if (team.slug) rememberModelTeamSlug(team.id, team.slug);
+ return { teamId: team.id, teamName: team.name };
+}
+
+async function loadTeams(token: string, signal?: AbortSignal) {
+ const teams: { id: string; name: string; slug?: string }[] = [];
+ let until: number | undefined;
+ for (let page = 0; page < 20; page++) {
+ const data = await vercelApiJson(
+ `https://api.vercel.com/v2/teams?limit=100${until === undefined ? "" : `&until=${until}`}`,
+ { headers: { authorization: `Bearer ${token}` }, signal },
+ );
+ if (!Array.isArray(data.teams)) throw new Error("Could not list Vercel teams. Retry /login.");
+ for (const team of data.teams) {
+ if (isObject(team) && typeof team.id === "string" && typeof team.name === "string")
+ teams.push({
+ id: team.id,
+ name: team.name,
+ slug: typeof team.slug === "string" ? team.slug : undefined,
+ });
+ }
+ until =
+ isObject(data.pagination) && typeof data.pagination.next === "number"
+ ? data.pagination.next
+ : undefined;
+ if (until === undefined) break;
+ }
+ if (teams.length === 0)
+ throw new Error(
+ "No Vercel team is available. Join a team or choose another connection in /login.",
+ );
+ return teams;
+}
diff --git a/packages/eve/src/setup/project-resolution.ts b/packages/eve/src/setup/project-resolution.ts
index c668b9a5c..8a3c34041 100644
--- a/packages/eve/src/setup/project-resolution.ts
+++ b/packages/eve/src/setup/project-resolution.ts
@@ -7,6 +7,7 @@ import {
type VercelProjectLink,
VercelProjectLinkSchema,
} from "#internal/vercel/project-link.js";
+import { readVercelResourceName } from "#internal/vercel/api-resource.js";
import { captureVercel } from "./primitives/run-vercel.js";
/** Link and production-deployment status for a Vercel project directory. */
@@ -137,11 +138,6 @@ export interface ProjectIdentity {
teamName?: string;
}
-interface VercelApiNamed {
- name?: unknown;
- slug?: unknown;
-}
-
/** Reads a `name` (or `slug` fallback) off a Vercel API resource, or undefined. */
async function fetchVercelName(
apiPath: string,
@@ -155,10 +151,7 @@ async function fetchVercelName(
});
if (!result.ok) return undefined;
try {
- const parsed = JSON.parse(result.stdout) as VercelApiNamed;
- if (typeof parsed.name === "string" && parsed.name.length > 0) return parsed.name;
- if (typeof parsed.slug === "string" && parsed.slug.length > 0) return parsed.slug;
- return undefined;
+ return readVercelResourceName(JSON.parse(result.stdout));
} catch {
return undefined;
}
diff --git a/packages/eve/src/setup/prompter.ts b/packages/eve/src/setup/prompter.ts
index f111e2293..e9a8ca5db 100644
--- a/packages/eve/src/setup/prompter.ts
+++ b/packages/eve/src/setup/prompter.ts
@@ -34,6 +34,8 @@ export type PrompterValue = string | number | boolean;
export interface SelectOption<T extends PrompterValue> {
value: T;
label: string;
+ /** Additional searchable text that is never rendered in the menu. */
+ keywords?: readonly string[];
/** Completion action kept after searchable results instead of being filtered. */
trailingAction?: boolean;
hint?: string;
@@ -128,7 +130,7 @@ export interface SelectCommonOptions<T extends PrompterValue> {
options: SelectOption<T>[];
/**
* Add a type-ahead filter line. The filter is a case-insensitive substring
- * match against each option's label, value, and hint.
+ * match against each option's label, value, hints, and keywords.
*/
search?: boolean;
/** Placeholder shown in the filter line while it is empty (with `search`). */
diff --git a/packages/eve/src/setup/provider-settings.integration.test.ts b/packages/eve/src/setup/provider-settings.integration.test.ts
index 6bd676740..729a4ab47 100644
--- a/packages/eve/src/setup/provider-settings.integration.test.ts
+++ b/packages/eve/src/setup/provider-settings.integration.test.ts
@@ -5,8 +5,9 @@ import { afterEach, describe, expect, it } from "vitest";
import {
providerSettingsPath,
+ providerSettingsMatch,
readProviderSelection,
- readProviderSelectionSync,
+ readProviderSettingsSync,
resolveAvailableProviders,
writeProviderSelection,
} from "./provider-settings.js";
@@ -47,7 +48,7 @@ describe("provider settings", () => {
await writeProviderSelection(root, "ai-gateway-project");
await expect(readProviderSelection(root)).resolves.toBe("ai-gateway-project");
- expect(readProviderSelectionSync(root)).toBe("ai-gateway-project");
+ expect(readProviderSettingsSync(root)?.selected).toBe("ai-gateway-project");
expect(providerSettingsPath(root)).toBe(join(root, ".eve", "provider.json"));
});
@@ -56,6 +57,26 @@ describe("provider settings", () => {
roots.push(root);
await expect(readProviderSelection(root)).resolves.toBeUndefined();
- expect(readProviderSelectionSync(root)).toBeUndefined();
+ expect(readProviderSettingsSync(root)?.selected).toBeUndefined();
});
});
+
+it("compares connection, team, and key source before deciding whether activation is needed", async () => {
+ const root = await mkdtemp(join(tmpdir(), "eve-provider-settings-"));
+ roots.push(root);
+ const team = { teamId: "team_a", teamName: "Alice" };
+ expect(await providerSettingsMatch(root, { selected: "vercel", ...team })).toBe(false);
+ await writeProviderSelection(root, "vercel", team);
+ expect(await providerSettingsMatch(root, { selected: "vercel", ...team })).toBe(true);
+ expect(await providerSettingsMatch(root, { selected: "vercel", ...team, teamId: "team_b" })).toBe(
+ false,
+ );
+ expect(await providerSettingsMatch(root, { selected: "vercel-cli", ...team })).toBe(false);
+ await writeProviderSelection(root, "openai", undefined, "environment");
+ expect(await providerSettingsMatch(root, { selected: "openai", keySource: "environment" })).toBe(
+ true,
+ );
+ expect(await providerSettingsMatch(root, { selected: "openai", keySource: "secret" })).toBe(
+ false,
+ );
+});
diff --git a/packages/eve/src/setup/provider-settings.ts b/packages/eve/src/setup/provider-settings.ts
index 60f162669..1309679bd 100644
--- a/packages/eve/src/setup/provider-settings.ts
+++ b/packages/eve/src/setup/provider-settings.ts
@@ -1,5 +1,7 @@
+import { atomicWriteFile } from "#shared/atomic-write-file.js";
+import { isModelConnection, type ModelConnectionSelection } from "#shared/model-connection.js";
import { readFileSync } from "node:fs";
-import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { mkdir, readFile } from "node:fs/promises";
import { join } from "node:path";
import { hasEnvValue } from "#internal/resolve-model-endpoint-status.js";
@@ -8,9 +10,7 @@ import { AI_GATEWAY_API_KEY_ENV_VAR } from "#setup/ai-gateway-api-key.js";
import { findEnvFileWithKey } from "#setup/boxes/detect-ai-gateway.js";
import { readProjectLink } from "#setup/project-resolution.js";
-const PROVIDER_SELECTIONS = ["chatgpt", "ai-gateway-key", "ai-gateway-project"] as const;
-
-export type ProviderSelection = (typeof PROVIDER_SELECTIONS)[number];
+export type ProviderSelection = ModelConnectionSelection;
export function providerSettingsPath(appRoot: string): string {
return join(appRoot, ".eve", "provider.json");
@@ -56,24 +56,58 @@ export async function readProviderSelection(
}
}
-/** Synchronous counterpart for the synchronous dev-environment loader. */
-export function readProviderSelectionSync(appRoot: string): ProviderSelection | undefined {
+export function readProviderSettingsSync(appRoot: string): ProviderSettings | undefined {
try {
- return parseProviderSelection(JSON.parse(readFileSync(providerSettingsPath(appRoot), "utf8")));
+ const value: unknown = JSON.parse(readFileSync(providerSettingsPath(appRoot), "utf8"));
+ if (!isObject(value) || !isProviderSelection(value.selected)) return undefined;
+ return {
+ selected: value.selected,
+ ...(typeof value.teamId === "string" &&
+ typeof value.teamName === "string" && { teamId: value.teamId, teamName: value.teamName }),
+ ...((value.keySource === "environment" || value.keySource === "secret") && {
+ keySource: value.keySource,
+ }),
+ };
} catch {
return undefined;
}
}
+export interface ProviderSettings {
+ selected: ProviderSelection;
+ teamId?: string;
+ teamName?: string;
+ keySource?: "environment" | "secret";
+}
+
+export async function providerSettingsMatch(
+ appRoot: string,
+ settings: ProviderSettings,
+): Promise<boolean> {
+ try {
+ const current = JSON.parse(await readFile(providerSettingsPath(appRoot), "utf8"));
+ return (
+ isObject(current) &&
+ current.selected === settings.selected &&
+ current.teamId === settings.teamId &&
+ current.teamName === settings.teamName &&
+ current.keySource === settings.keySource
+ );
+ } catch {
+ return false;
+ }
+}
+
export async function writeProviderSelection(
appRoot: string,
selected: ProviderSelection,
+ team?: { teamId: string; teamName: string },
+ keySource?: "environment" | "secret",
): Promise<void> {
await mkdir(join(appRoot, ".eve"), { recursive: true });
- await writeFile(
+ await atomicWriteFile(
providerSettingsPath(appRoot),
- `${JSON.stringify({ selected }, null, 2)}\n`,
- "utf8",
+ `${JSON.stringify({ selected, ...team, keySource }, null, 2)}\n`,
);
}
@@ -82,5 +116,18 @@ function parseProviderSelection(value: unknown): ProviderSelection | undefined {
}
function isProviderSelection(value: unknown): value is ProviderSelection {
- return PROVIDER_SELECTIONS.some((selection) => selection === value);
+ return isModelConnection(value) || value === "vercel-cli" || value === "ai-gateway-project";
+}
+
+export function readProviderTeamSync(
+ appRoot: string,
+): { teamId: string; teamName: string } | undefined {
+ const settings = readProviderSettingsSync(appRoot);
+ return settings?.teamId && settings.teamName
+ ? { teamId: settings.teamId, teamName: settings.teamName }
+ : undefined;
+}
+
+export function readProviderKeySourceSync(appRoot: string): "environment" | "secret" | undefined {
+ return readProviderSettingsSync(appRoot)?.keySource;
}
diff --git a/packages/eve/src/setup/vercel-project.test.ts b/packages/eve/src/setup/vercel-project.test.ts
index 0a4d6e839..c3dc68bba 100644
--- a/packages/eve/src/setup/vercel-project.test.ts
+++ b/packages/eve/src/setup/vercel-project.test.ts
@@ -83,8 +83,8 @@ describe("vercelAuthBlockerReason", () => {
vercelAuthBlockerReason("unavailable"),
]).toEqual([
undefined,
- "Vercel CLI not found, see /vc:install",
- "Log in to Vercel first, see /vc:login",
+ "Vercel CLI not found, see /deploy",
+ "Log in to Vercel first, see /deploy",
"Couldn't reach Vercel, check your connection",
]);
});
diff --git a/packages/eve/src/setup/vercel-project.ts b/packages/eve/src/setup/vercel-project.ts
index 8fd40a284..67eb4afaf 100644
--- a/packages/eve/src/setup/vercel-project.ts
+++ b/packages/eve/src/setup/vercel-project.ts
@@ -243,9 +243,9 @@ export function vercelAuthBlockerReason(authStatus: VercelAuthStatus): string |
case "authenticated":
return undefined;
case "cli-missing":
- return "Vercel CLI not found, see /vc:install";
+ return "Vercel CLI not found, see /deploy";
case "logged-out":
- return "Log in to Vercel first, see /vc:login";
+ return "Log in to Vercel first, see /deploy";
case "unavailable":
return "Couldn't reach Vercel, check your connection";
default: {
diff --git a/packages/eve/src/setup/with-spinner.test.ts b/packages/eve/src/setup/with-spinner.test.ts
index 28ec28b11..a3d5fa042 100644
--- a/packages/eve/src/setup/with-spinner.test.ts
+++ b/packages/eve/src/setup/with-spinner.test.ts
@@ -40,3 +40,36 @@ describe("withSpinner", () => {
expect(task).toHaveBeenCalledOnce();
});
});
+
+it("does not flash a spinner for quick work", async () => {
+ vi.useFakeTimers();
+ try {
+ const { prompter } = createFakePrompter();
+ const spinner = vi.fn();
+ prompter.log.spinner = spinner;
+ await withSpinner(prompter, "Loading…", async () => 42, 150);
+ await vi.advanceTimersByTimeAsync(200);
+ expect(spinner).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+});
+
+it("shows slow work and clears its spinner on failure", async () => {
+ vi.useFakeTimers();
+ try {
+ const { prompter } = createFakePrompter();
+ const stop = vi.fn();
+ prompter.log.spinner = vi.fn(() => ({ stop }));
+ const task = Promise.withResolvers<void>();
+ const result = withSpinner(prompter, "Loading…", () => task.promise, 150);
+ const assertion = expect(result).rejects.toThrow("Failed");
+ await vi.advanceTimersByTimeAsync(150);
+ expect(prompter.log.spinner).toHaveBeenCalledExactlyOnceWith("Loading…");
+ task.reject(new Error("Failed"));
+ await assertion;
+ expect(stop).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ }
+});
diff --git a/packages/eve/src/setup/with-spinner.ts b/packages/eve/src/setup/with-spinner.ts
index 445597cae..1c4ec3df3 100644
--- a/packages/eve/src/setup/with-spinner.ts
+++ b/packages/eve/src/setup/with-spinner.ts
@@ -5,11 +5,18 @@ export async function withSpinner<T>(
prompter: Prompter,
message: string,
task: () => Promise<T>,
+ delayMs = 0,
): Promise<T> {
- const spinner = prompter.log.spinner?.(message);
+ let spinner: ReturnType<NonNullable<Prompter["log"]["spinner"]>> | undefined;
+ const start = () => {
+ spinner = prompter.log.spinner?.(message);
+ };
+ const timer = delayMs > 0 ? setTimeout(start, delayMs) : undefined;
+ if (timer === undefined) start();
try {
return await task();
} finally {
+ clearTimeout(timer);
spinner?.stop();
}
}
diff --git a/packages/eve/src/shared/chatgpt-model.ts b/packages/eve/src/shared/chatgpt-model.ts
index 46f1c7cc3..2edaef801 100644
--- a/packages/eve/src/shared/chatgpt-model.ts
+++ b/packages/eve/src/shared/chatgpt-model.ts
@@ -1,6 +1,6 @@
import type { ModelRouting } from "./agent-definition.js";
-export const DEFAULT_CHATGPT_MODEL_ID = "gpt-5.6-sol";
+export const DEFAULT_CHATGPT_MODEL_ID = "gpt-5.6-luna-fast";
export const CHATGPT_MODEL_SELECTION_PREFIX = "chatgpt/";
export const DEFAULT_CHATGPT_MODEL_SELECTION = `${CHATGPT_MODEL_SELECTION_PREFIX}${DEFAULT_CHATGPT_MODEL_ID}`;
diff --git a/packages/eve/src/shared/model-connection.ts b/packages/eve/src/shared/model-connection.ts
new file mode 100644
index 000000000..2ed40b9dc
--- /dev/null
+++ b/packages/eve/src/shared/model-connection.ts
@@ -0,0 +1,21 @@
+import type { ModelRouting } from "./agent-definition.js";
+import type { ModelEndpointStatus } from "./model-endpoint-status.js";
+export const CONNECTIONS = ["chatgpt", "vercel", "ai-gateway-key", "openai", "anthropic"] as const;
+export type ModelConnection = (typeof CONNECTIONS)[number];
+export type ModelConnectionSelection = ModelConnection | "ai-gateway-project" | "vercel-cli";
+export function isModelConnection(value: unknown): value is ModelConnection {
+ return CONNECTIONS.some((connection) => connection === value);
+}
+
+export interface ConnectedModel {
+ id: string;
+ routing: ModelRouting;
+ endpoint: ModelEndpointStatus;
+}
+
+/** Whether a completed connection or model edit still needs runtime activation. */
+export interface ModelAccessChange {
+ kind: "model-access-changed";
+ reload: boolean;
+ model?: ConnectedModel;
+}
diff --git a/packages/eve/src/shared/model-endpoint-status.ts b/packages/eve/src/shared/model-endpoint-status.ts
index fe116784d..535587e2a 100644
--- a/packages/eve/src/shared/model-endpoint-status.ts
+++ b/packages/eve/src/shared/model-endpoint-status.ts
@@ -28,5 +28,5 @@ export type ModelEndpointStatus =
state: ChatGptEndpointState;
accountLabel?: string;
}
- | { kind: "gateway"; connected: true; credential: "api-key" | "oidc" }
+ | { kind: "gateway"; connected: true; credential: "api-key" | "oidc" | "oauth"; team?: string }
| { kind: "gateway"; connected: false };
diff --git a/packages/eve/src/shared/model-helper.ts b/packages/eve/src/shared/model-helper.ts
new file mode 100644
index 000000000..2fcc6403e
--- /dev/null
+++ b/packages/eve/src/shared/model-helper.ts
@@ -0,0 +1,34 @@
+export const MODEL_CONNECTION_ENV = "EVE_MODEL_CONNECTION";
+export const MODEL_HELPERS = {
+ chatgpt: {
+ module: "eve/models/openai",
+ prefix: "chatgpt/",
+ defaultModel: "gpt-5.6-luna-fast",
+ provider: "codex",
+ },
+ openai: {
+ module: "eve/models/openai",
+ prefix: "openai-api/",
+ defaultModel: "gpt-5.6-luna-fast",
+ provider: "openai",
+ },
+ anthropic: {
+ module: "eve/models/anthropic",
+ prefix: "anthropic-api/",
+ defaultModel: "claude-sonnet-5",
+ provider: "anthropic",
+ },
+} as const;
+export type ModelHelper = keyof typeof MODEL_HELPERS;
+export function parseModelHelper(
+ selection: string,
+): { helper: ModelHelper; id: string } | undefined {
+ for (const helper of Object.keys(MODEL_HELPERS) as ModelHelper[]) {
+ const { prefix } = MODEL_HELPERS[helper];
+ if (selection.startsWith(prefix)) {
+ const id = selection.slice(prefix.length);
+ if (id && id === id.trim() && !id.includes("/")) return { helper, id };
+ }
+ }
+ return undefined;
+}
diff --git a/packages/eve/src/shared/package-version.ts b/packages/eve/src/shared/package-version.ts
new file mode 100644
index 000000000..926bd0aed
--- /dev/null
+++ b/packages/eve/src/shared/package-version.ts
@@ -0,0 +1,4 @@
+/** Build metadata identifies a package artifact, not a separately published release. */
+export function stripVersionBuildMetadata(version: string): string {
+ return version.split("+", 1)[0]!;
+}
diff --git a/packages/eve/src/source-change/agent-config-ast.ts b/packages/eve/src/source-change/agent-config-ast.ts
index e96183f64..172e024de 100644
--- a/packages/eve/src/source-change/agent-config-ast.ts
+++ b/packages/eve/src/source-change/agent-config-ast.ts
@@ -10,6 +10,11 @@ import { parseWithNitroRolldownAst } from "#internal/bundler/nitro-rolldown.js";
export type Program = { readonly body?: readonly AstNode[] };
export type AstNode = {
+ readonly source?: AstNode;
+ readonly specifiers?: readonly AstNode[];
+ readonly local?: AstNode;
+ readonly imported?: AstNode;
+ readonly importKind?: string;
readonly arguments?: readonly AstNode[];
readonly callee?: AstNode;
readonly computed?: boolean;
@@ -45,7 +50,7 @@ type ParseError = {
};
export type ParsedAgentObject =
- | { readonly kind: "ok"; readonly object: ObjectExpression }
+ | { readonly kind: "ok"; readonly object: ObjectExpression; readonly program: Program }
| { readonly kind: "bail"; readonly reason: string; readonly line: number };
/** Parses a source and locates the `export default defineAgent({ ... })` object. */
@@ -74,7 +79,7 @@ export async function parseAgentObject(sourceText: string): Promise<ParsedAgentO
const object = findDefineAgentObject(parsed.program ?? parsed);
return object === undefined
? { kind: "bail", reason: "no `export default defineAgent({ ... })` call found", line: 1 }
- : { kind: "ok", object };
+ : { kind: "ok", object, program: parsed.program ?? parsed };
}
/**
diff --git a/packages/eve/src/source-change/apply-model-selection.test.ts b/packages/eve/src/source-change/apply-model-selection.test.ts
index 22d58b53d..c641126f6 100644
--- a/packages/eve/src/source-change/apply-model-selection.test.ts
+++ b/packages/eve/src/source-change/apply-model-selection.test.ts
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vitest";
-import { applyModelSelectionToSource } from "./apply-model-selection.js";
+import {
+ applyModelSelectionToSource,
+ readModelSelectionFromSource,
+} from "./apply-model-selection.js";
const SCAFFOLD = `import { defineAgent } from "eve";
@@ -39,7 +42,7 @@ describe("applyModelSelectionToSource", () => {
expect(result.kind).toBe("applied");
if (result.kind !== "applied") return;
- expect(result.from).toBe("chatgpt/gpt-5.6-sol");
+ expect(result.from).toBe("chatgpt/gpt-5.6-luna-fast");
expect(result.nextSource).not.toContain("eve/models/openai");
expect(result.nextSource).toContain('model: "openai/gpt-5.5"');
});
@@ -127,3 +130,48 @@ describe("applyModelSelectionToSource", () => {
});
});
});
+
+it.each([
+ ["openai-api/gpt-5.6-luna-fast", "openai", "eve/models/openai"],
+ ["anthropic-api/claude-sonnet-5", "anthropic", "eve/models/anthropic"],
+])("switches a Gateway string to %s and back safely", async (selection, helper, module) => {
+ const source =
+ 'import { defineAgent } from "eve";\nexport default defineAgent({ model: "openai/gpt-5.6-luna-fast" });';
+ const result = await applyModelSelectionToSource(source, selection);
+ expect(result.kind).toBe("applied");
+ if (result.kind !== "applied") return;
+ expect(result.nextSource).toContain(`import { ${helper} } from "${module}";`);
+ const back = await applyModelSelectionToSource(result.nextSource, "anthropic/claude-sonnet-5");
+ expect(back.kind).toBe("applied");
+ if (back.kind === "applied") expect(back.nextSource).not.toContain(`import { ${helper} }`);
+});
+
+it("refuses to shadow a custom provider import", async () => {
+ const result = await applyModelSelectionToSource(
+ 'import { openai } from "@ai-sdk/openai";\nexport default defineAgent({ model: "anthropic/claude-sonnet-5" });',
+ "openai-api/gpt-5.6-luna-fast",
+ );
+ expect(result.kind).toBe("bail");
+});
+
+it("does not recognize a commented import as an eve helper", async () => {
+ const source =
+ '// import { openai } from "eve/models/openai";\nconst openai = customProvider;\nexport default defineAgent({ model: openai("example") });';
+ expect((await applyModelSelectionToSource(source, "anthropic/claude-sonnet-5")).kind).toBe(
+ "bail",
+ );
+});
+
+it.each(["openai", "anthropic"])(
+ "distinguishes eve's %s helper from a foreign provider import",
+ async (helper) => {
+ const config = `export default defineAgent({model: ${helper}("custom-model")});`;
+ const module = helper === "openai" ? "eve/models/openai" : "eve/models/anthropic";
+ await expect(
+ readModelSelectionFromSource(`import { ${helper} } from "${module}"; ${config}`),
+ ).resolves.toBe(`${helper}-api/custom-model`);
+ await expect(
+ readModelSelectionFromSource(`import { ${helper} } from "@ai-sdk/${helper}"; ${config}`),
+ ).resolves.toBeUndefined();
+ },
+);
diff --git a/packages/eve/src/source-change/apply-model-selection.ts b/packages/eve/src/source-change/apply-model-selection.ts
index 77c2e9eec..d1b98d3cc 100644
--- a/packages/eve/src/source-change/apply-model-selection.ts
+++ b/packages/eve/src/source-change/apply-model-selection.ts
@@ -7,13 +7,9 @@ import {
unwrapExpression,
type AstNode,
type ObjectExpression,
+ type Program,
} from "./agent-config-ast.js";
-import {
- CHATGPT_MODEL_SELECTION_PREFIX,
- DEFAULT_CHATGPT_MODEL_SELECTION,
- normalizeChatGptModelId,
- parseChatGptModelSelection,
-} from "#shared/chatgpt-model.js";
+import { MODEL_HELPERS, parseModelHelper, type ModelHelper } from "#shared/model-helper.js";
export type SourceEdit =
| {
@@ -28,7 +24,17 @@ export type SourceEdit =
readonly line: number;
};
-/** Rewrites between a Gateway string model and an eve-owned `chatgpt()` call. */
+/** Reads only model expressions the source editor can safely rewrite. */
+export async function readModelSelectionFromSource(
+ sourceText: string,
+): Promise<string | undefined> {
+ const parsed = await parseAgentObject(sourceText);
+ if (parsed.kind === "bail") return undefined;
+ const value = findModelValue(parsed.object);
+ return value === undefined ? undefined : currentSelection(value, parsed.program);
+}
+
+/** Rewrites between a Gateway string model and an eve-owned model helper. */
export async function applyModelSelectionToSource(
sourceText: string,
selection: string,
@@ -44,31 +50,56 @@ export async function applyModelSelectionToSource(
};
}
- const current = currentSelection(value);
+ const current = currentSelection(value, parsed.program);
if (current === undefined) {
return {
kind: "bail",
- reason: "`model` is neither a string literal nor an eve `chatgpt()` call",
+ reason: "`model` is neither a string literal nor an eve model helper",
line: lineAt(sourceText, value.start),
};
}
- const chatGptModelId = parseChatGptModelSelection(selection);
+ const helperSelection = parseModelHelper(selection);
+ if (helperSelection) {
+ const helper = helperSelection.helper;
+ const imported = hasHelperImport(parsed.program, helper);
+ if (!imported && hasIdentifier(parsed.program, helper)) {
+ return {
+ kind: "bail",
+ reason: `Cannot safely introduce the ${helper} import; that name is already used`,
+ line: lineAt(sourceText, value.start),
+ };
+ }
+ }
const replacement =
- chatGptModelId !== undefined
- ? `chatgpt(${JSON.stringify(chatGptModelId)})`
+ helperSelection !== undefined
+ ? `${helperSelection.helper}(${JSON.stringify(helperSelection.id)})`
: `${sourceText[value.start] === "'" ? "'" : '"'}${escapeForQuote(
selection,
sourceText[value.start] === "'" ? "'" : '"',
)}${sourceText[value.start] === "'" ? "'" : '"'}`;
let nextSource = sourceText.slice(0, value.start) + replacement + sourceText.slice(value.end);
- if (chatGptModelId !== undefined) {
- nextSource = ensureChatGptImport(nextSource);
- } else if (
- parseChatGptModelSelection(current) !== undefined &&
- !/\bchatgpt\s*\(/u.test(nextSource)
- ) {
- nextSource = removeChatGptImport(nextSource);
+ if (helperSelection !== undefined)
+ nextSource = hasHelperImport(parsed.program, helperSelection.helper)
+ ? nextSource
+ : `import { ${helperSelection.helper} } from "${MODEL_HELPERS[helperSelection.helper].module}";\n${nextSource}`;
+ const previous = parseModelHelper(current);
+ if (previous && previous.helper !== helperSelection?.helper) {
+ const withImport = await parseAgentObject(nextSource);
+ const declaration =
+ withImport.kind === "ok" ? helperImport(withImport.program, previous.helper) : undefined;
+ const withoutImport =
+ declaration?.start !== undefined && declaration.end !== undefined
+ ? nextSource.slice(0, declaration.start) +
+ removeHelperImport(
+ nextSource.slice(declaration.start, declaration.end),
+ previous.helper,
+ ) +
+ nextSource.slice(declaration.end)
+ : nextSource;
+ const parsedNext = await parseAgentObject(withoutImport);
+ if (parsedNext.kind === "ok" && !hasIdentifier(parsedNext.program, previous.helper))
+ nextSource = withoutImport;
}
return { kind: "applied", from: current, to: selection, nextSource };
}
@@ -83,55 +114,72 @@ function findModelValue(object: ObjectExpression): AstNode | undefined {
return undefined;
}
-function currentSelection(value: AstNode): string | undefined {
+function currentSelection(value: AstNode, program: Program): string | undefined {
if (value.type === "Literal" && typeof value.value === "string") return value.value;
if (value.type !== "CallExpression" || !isAstNode(value.callee)) return undefined;
const callee = unwrapExpression(value.callee);
- if (callee.type !== "Identifier" || callee.name !== "chatgpt") return undefined;
+ if (
+ callee.type !== "Identifier" ||
+ typeof callee.name !== "string" ||
+ !(callee.name in MODEL_HELPERS)
+ )
+ return undefined;
+ const helper = callee.name as ModelHelper;
+ const spec = MODEL_HELPERS[helper];
+ if (!hasHelperImport(program, helper)) return undefined;
+ if ((value.arguments?.length ?? 0) > 1) return undefined;
const argument = value.arguments?.[0];
- if (argument === undefined) return DEFAULT_CHATGPT_MODEL_SELECTION;
+ if (argument === undefined) return spec.prefix + spec.defaultModel;
if (!isAstNode(argument)) return undefined;
const unwrapped = unwrapExpression(argument);
if (unwrapped.type !== "Literal" || typeof unwrapped.value !== "string") return undefined;
- const modelId = normalizeChatGptModelId(unwrapped.value);
- return modelId === undefined ? undefined : `${CHATGPT_MODEL_SELECTION_PREFIX}${modelId}`;
+ const id = unwrapped.value
+ .trim()
+ .replace(new RegExp(`^${helper === "chatgpt" ? "openai" : helper}/`, "u"), "");
+ return id && !id.includes("/") ? spec.prefix + id : undefined;
}
-function ensureChatGptImport(source: string): string {
- const existing = source.match(/import\s*\{([^}]*)\}\s*from\s*["']eve\/models\/openai["'];?/u);
- if (existing !== null) {
- const names = existing[1]!
+function helperImportPattern(helper: ModelHelper): RegExp {
+ return new RegExp(
+ `import\\s*\\{([^}]*)\\}\\s*from\\s*["']${MODEL_HELPERS[helper].module}["'];?`,
+ "u",
+ );
+}
+
+function removeHelperImport(source: string, helper: ModelHelper): string {
+ return source.replace(helperImportPattern(helper), (full, contents: string) => {
+ const names = contents
.split(",")
.map((name) => name.trim())
.filter(Boolean);
- if (names.includes("chatgpt")) return source;
- const replacement = `import { ${[...names, "chatgpt"].join(", ")} } from "eve/models/openai";`;
- return (
- source.slice(0, existing.index) +
- replacement +
- source.slice(existing.index! + existing[0].length)
- );
- }
- const imports = [...source.matchAll(/^import .*;\s*$/gmu)];
- const insertion = imports.at(-1);
- const offset = insertion === undefined ? 0 : insertion.index! + insertion[0].length;
- const prefix = offset === 0 ? "" : "\n";
- return `${source.slice(0, offset)}${prefix}import { chatgpt } from "eve/models/openai";${source.slice(offset)}`;
+ const remaining = names.filter((name) => name !== helper);
+ if (remaining.length === names.length) return full;
+ return remaining.length === 0
+ ? ""
+ : `import { ${remaining.join(", ")} } from "${MODEL_HELPERS[helper].module}";`;
+ });
}
-function removeChatGptImport(source: string): string {
- return source.replace(
- /import\s*\{([^}]*)\}\s*from\s*["']eve\/models\/openai["'];?\n?/u,
- (full, contents: string) => {
- const names = contents
- .split(",")
- .map((name) => name.trim())
- .filter(Boolean);
- const remaining = names.filter((name) => name !== "chatgpt");
- if (remaining.length === names.length) return full;
- return remaining.length === 0
- ? ""
- : `import { ${remaining.join(", ")} } from "eve/models/openai";\n`;
- },
+function hasIdentifier(value: unknown, name: string): boolean {
+ if (value === null || typeof value !== "object") return false;
+ if (isAstNode(value) && value.type === "Identifier" && value.name === name) return true;
+ return Object.values(value).some((child) => hasIdentifier(child, name));
+}
+
+function helperImport(program: Program, helper: ModelHelper): AstNode | undefined {
+ return program.body?.find(
+ (node) =>
+ node.type === "ImportDeclaration" &&
+ node.source?.value === MODEL_HELPERS[helper].module &&
+ node.importKind !== "type" &&
+ node.specifiers?.some(
+ (specifier) =>
+ specifier.imported?.name === helper &&
+ specifier.local?.name === helper &&
+ specifier.importKind !== "type",
+ ),
);
}
+function hasHelperImport(program: Program, helper: ModelHelper): boolean {
+ return helperImport(program, helper) !== undefined;
+}
diff --git a/packages/eve/test/scenarios/add-to-chat.scenario.test.ts b/packages/eve/test/scenarios/add-to-chat.scenario.test.ts
new file mode 100644
index 000000000..7cd6d7d29
--- /dev/null
+++ b/packages/eve/test/scenarios/add-to-chat.scenario.test.ts
@@ -0,0 +1,57 @@
+import { createServer } from "node:http";
+import { readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { useTemporaryAppRoots } from "../../src/internal/testing/use-temporary-app-roots.js";
+import { createFakePrompter } from "../../src/internal/testing/fake-prompter.js";
+import { runRegistryFlow } from "../../src/setup/flows/registry.js";
+import { compileAgent } from "../../src/compiler/compile-agent.js";
+import { getCompiledRuntimeAgentBundle } from "../../src/runtime/sessions/compiled-agent-cache.js";
+import { createAuthoredSourceRuntimeCompiledArtifactsSource } from "../../src/internal/application/runtime-compiled-artifacts-source.js";
+const createAppRoot = useTemporaryAppRoots();
+it("installs an addressed addition without a review and makes it available to the agent", async () => {
+ const { appRoot, agentRoot } = await createAppRoot("eve-add-chat-");
+ await writeFile(
+ join(appRoot, "package.json"),
+ JSON.stringify({ name: "eve-add-chat", type: "module", dependencies: { eve: "*" } }),
+ );
+ await writeFile(join(agentRoot, "instructions.md"), "Help Alice with her work.\n");
+ const content =
+ "---\ndescription: Greet Alice when starting a conversation.\n---\nSay hello to Alice.\n";
+ const item = {
+ name: "greeting",
+ type: "registry:file",
+ files: [
+ { path: "greeting.md", target: "agent/skills/greeting.md", type: "registry:file", content },
+ ],
+ };
+ const server = createServer((_request, response) => {
+ response.setHeader("content-type", "application/json");
+ response.end(JSON.stringify(item));
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ try {
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("Expected a registry port");
+ const fake = createFakePrompter();
+ const result = await runRegistryFlow({
+ appRoot,
+ prompter: fake.prompter,
+ initialAddress: `http://127.0.0.1:${address.port}/greeting.json`,
+ });
+ expect(result.kind).toBe("done");
+ expect(fake.selectMessages).toEqual([]);
+ expect(await readFile(join(agentRoot, "skills/greeting.md"), "utf8")).toBe(content);
+ await compileAgent({ startPath: appRoot });
+ const bundle = await getCompiledRuntimeAgentBundle({
+ compiledArtifactsSource: createAuthoredSourceRuntimeCompiledArtifactsSource(appRoot),
+ });
+ expect(bundle.resolvedAgent.skills).toEqual(
+ expect.arrayContaining([expect.objectContaining({ name: "greeting" })]),
+ );
+ } finally {
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve())),
+ );
+ }
+});
diff --git a/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.ts b/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.ts
index 268c4312d..bb56a7655 100644
--- a/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.ts
+++ b/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.ts
@@ -1,9 +1,11 @@
+import { createFakeVercelOidcToken } from "../../src/internal/testing/vercel-oidc-token.js";
import { existsSync } from "node:fs";
import { realpath, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
+import { writeProviderSelection } from "../../src/setup/provider-settings.js";
import { EVE_HEALTH_ROUTE_PATH } from "../../src/protocol/routes.js";
import {
readDevelopmentRuntimeArtifactsSnapshotRoot,
@@ -74,6 +76,49 @@ function createCandidateChannelSource(): string {
}
describe("eve dev server rebuild transactions", () => {
+ it(
+ "switches Gateway credentials through the host without rebuilding or replacing the worker",
+ async () => {
+ const app = await scenarioApp(TRANSACTIONAL_REBUILD_DESCRIPTOR);
+ await writeProviderSelection(app.appRoot, "ai-gateway-key", undefined, "environment");
+ const oidcToken = createFakeVercelOidcToken({ exp: Math.floor(Date.now() / 1000) + 3600 });
+ const server = await startEveDev(app.appRoot, {
+ env: {
+ AI_GATEWAY_API_KEY: "fixture-gateway-key",
+ VERCEL_OIDC_TOKEN: oidcToken,
+ },
+ });
+ try {
+ const revision = await readDevelopmentRevision(server.url);
+ const worker = await fetchText(server.url, "/worker-id");
+ expect((await fetchAgentInfo(server.url)).agent.model.endpoint).toMatchObject({
+ connected: true,
+ credential: "api-key",
+ });
+ await writeProviderSelection(app.appRoot, "ai-gateway-project");
+ expect((await fetchAgentInfo(server.url)).agent.model.endpoint).toMatchObject({
+ connected: true,
+ credential: "oidc",
+ });
+ // Let an accidental provider-file watch reach its rebuild debounce.
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ expect(await readDevelopmentRevision(server.url)).toBe(revision);
+ expect(await fetchText(server.url, "/worker-id")).toBe(worker);
+ expect(server.stdout()).not.toContain("provider.json");
+ expect(server.stdout() + server.stderr()).not.toContain("fixture-gateway-key");
+ expect(server.stdout() + server.stderr()).not.toContain(oidcToken);
+ const unauthorized = await fetch(
+ new URL("/eve/v1/dev/internal/model-credential?provider=gateway", server.url),
+ );
+ expect(unauthorized.status).toBe(401);
+ expect(await unauthorized.text()).not.toContain(oidcToken);
+ } finally {
+ await server.stop();
+ }
+ },
+ DEV_SERVER_SCENARIO_TIMEOUT_MS,
+ );
+
it(
"scopes a local-dev capability through the host and releases its watcher lease",
async () => {
diff --git a/packages/eve/test/scenarios/eve-init.scenario.test.ts b/packages/eve/test/scenarios/eve-init.scenario.test.ts
index 3ecc91406..a88dea2c8 100644
--- a/packages/eve/test/scenarios/eve-init.scenario.test.ts
+++ b/packages/eve/test/scenarios/eve-init.scenario.test.ts
@@ -259,10 +259,6 @@ describe("eve init smoke", () => {
args: ["--dir", canonicalProjectDir, "install", "--no-frozen-lockfile"],
cwd: canonicalProjectDir,
},
- {
- args: ["--dir", canonicalProjectDir, "exec", "eve", "dev", "--onboard"],
- cwd: canonicalProjectDir,
- },
]);
expect(result.stdout).toContain("Created an eve agent in ");
expect(result.stdout).toContain("Preparing project...");
@@ -297,9 +293,9 @@ describe("eve init smoke", () => {
expect(await readFile(join(projectDir, "next.config.ts"), "utf8")).toContain(
"export default withEve(nextConfig);",
);
- const [installCall, devCall] = await fakePnpm.readCalls();
+ const [installCall, ...remainingCalls] = await fakePnpm.readCalls();
expect(installCall?.args.slice(-2)).toEqual(["install", "--no-frozen-lockfile"]);
- expect(devCall?.args.slice(-4)).toEqual(["exec", "eve", "dev", "--onboard"]);
+ expect(remainingCalls).toEqual([]);
});
it("adds Web Chat through npm without writing pnpm configuration", async () => {
@@ -323,10 +319,6 @@ describe("eve init smoke", () => {
args: ["install"],
cwd: canonicalProjectDir,
},
- {
- args: ["exec", "--", "eve", "dev", "--onboard"],
- cwd: canonicalProjectDir,
- },
]);
});
@@ -364,7 +356,7 @@ describe("eve init smoke", () => {
);
const calls = await fakePnpm.readCalls();
expect(calls[0]?.args.slice(-2)).toEqual(["install", "--no-frozen-lockfile"]);
- expect(calls[1]?.args.slice(-3)).toEqual(["exec", "eve", "dev"]);
+ expect(calls).toHaveLength(1);
});
it("scaffolds the current directory for a coding agent that omits the target", async () => {
@@ -424,10 +416,6 @@ describe("eve init smoke", () => {
args: ["--dir", canonicalProjectDir, "install", "--no-frozen-lockfile"],
cwd: canonicalProjectDir,
},
- {
- args: ["--dir", canonicalProjectDir, "exec", "eve", "dev", "--onboard"],
- cwd: canonicalProjectDir,
- },
]);
});
diff --git a/packages/eve/test/scenarios/runtime-model-resolution.scenario.test.ts b/packages/eve/test/scenarios/runtime-model-resolution.scenario.test.ts
index 7ee49e570..9016ee6dc 100644
--- a/packages/eve/test/scenarios/runtime-model-resolution.scenario.test.ts
+++ b/packages/eve/test/scenarios/runtime-model-resolution.scenario.test.ts
@@ -22,6 +22,36 @@ afterEach(() => {
});
describe("runtime model resolution", () => {
+ it.each([
+ ["openai", "eve/models/openai", "gpt-5.6-luna-fast"],
+ ["anthropic", "eve/models/anthropic", "claude-sonnet-5"],
+ ])(
+ "compiles and rehydrates the eve %s helper without capturing credentials",
+ async (helper, module, id) => {
+ vi.stubEnv("NODE_ENV", "development");
+ vi.stubEnv(
+ helper === "openai" ? "OPENAI_API_KEY" : "ANTHROPIC_API_KEY",
+ "compile-must-not-capture-this-key",
+ );
+ const { agentRoot, appRoot } = await createAppRoot("eve-direct-model-", APP_ROOT_OPTIONS);
+ await writeFile(
+ join(agentRoot, "agent.ts"),
+ `import { defineAgent } from "eve";\nimport { ${helper} } from "${module}";\nexport default defineAgent({ model: ${helper}(), modelContextWindowTokens: 100000 });\n`,
+ );
+ await writeFile(join(agentRoot, "instructions.md"), "Help Alice get started.\n");
+ await compileAgent({ startPath: appRoot });
+ const compiledArtifactsSource = createAuthoredSourceRuntimeCompiledArtifactsSource(appRoot);
+ const bundle = await getCompiledRuntimeAgentBundle({ compiledArtifactsSource });
+ expect(JSON.stringify(bundle.turnAgent)).not.toContain("compile-must-not-capture-this-key");
+ if (!bundle.turnAgent.model) throw new Error("Expected a compiled model");
+ const model = await resolveRuntimeModelReference(bundle.turnAgent.model, {
+ moduleMap: bundle.moduleMap,
+ nodeId: bundle.nodeId,
+ });
+ expect(model).toMatchObject({ modelId: id });
+ },
+ );
+
it("keeps the bootstrap sentinel separate from the default authored runtime model", () => {
expect(BOOTSTRAP_RUNTIME_MODEL_ID).not.toBe(TEST_DEFAULT_MODEL_ID);
expect(
diff --git a/packages/eve/test/tui-client/tui-packed-install-model.ts b/packages/eve/test/tui-client/tui-packed-install-model.ts
index 73d3987b8..a153fa316 100644
--- a/packages/eve/test/tui-client/tui-packed-install-model.ts
+++ b/packages/eve/test/tui-client/tui-packed-install-model.ts
@@ -1,5 +1,5 @@
import { spawn } from "node:child_process";
-import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
@@ -15,7 +15,7 @@ import { theme } from "./lib/theme.ts";
* dependency still resolves and the bug ships. This test packs the built
* package (`pnpm pack`), installs the tarball into an empty project with npm
* (which installs only declared dependencies, exactly like a user install),
- * and drives the installed TUI through the prefilled onboarding provider setup.
+ * and drives the installed TUI through first-run connection setup with a minimal agent.
*
* Regression: eve 0.6.x–0.7.0 imported `oxc-parser` from the `/model` flow
* while declaring it only as a devDependency. In a scaffolded project the
@@ -54,6 +54,18 @@ interface PackedTuiHarness {
void (async () => {
const consumerRoot = await mkdtemp(join(tmpdir(), "eve-packed-install-"));
try {
+ // A packed-install smoke must not discover the developer's real model accounts.
+ process.env.HOME = consumerRoot;
+ process.env.USERPROFILE = consumerRoot;
+ process.env.XDG_DATA_HOME = join(consumerRoot, "data");
+ for (const key of [
+ "OPENAI_API_KEY",
+ "ANTHROPIC_API_KEY",
+ "AI_GATEWAY_API_KEY",
+ "VERCEL_OIDC_TOKEN",
+ "VERCEL_TOKEN",
+ ])
+ delete process.env[key];
const tarballPath = join(consumerRoot, "eve.tgz");
// `--config.ignore-scripts=true` skips `prepack` (a full rebuild): the
@@ -86,6 +98,18 @@ void (async () => {
);
console.log(theme.muted("[tui-packed-install] consumer npm install completed"));
+ // Login reads the authored model before deciding which connection to reuse.
+ // Match the scaffold's layout while keeping eve's install free of devDependencies.
+ const agentRoot = join(consumerRoot, "agent");
+ await mkdir(agentRoot);
+ await Promise.all([
+ writeFile(
+ join(agentRoot, "agent.ts"),
+ 'import { defineAgent } from "eve";\n\nexport default defineAgent({\n model: "openai/gpt-5.6-luna-fast",\n});\n',
+ ),
+ writeFile(join(agentRoot, "instructions.md"), "Help Alice with her questions.\n"),
+ ]);
+
// Imported by file URL: the harness is not on the package's `exports`
// map, and the point is to load the *installed* module graph — every
// bare specifier in it resolves against the consumer's node_modules.
@@ -98,7 +122,7 @@ void (async () => {
const screen = new MockScreen({ columns: 100, rows: 40 });
const input = new MockUserInput();
const runner = new EveTUIRunner({
- // `/model` runs before the first chat turn, so no client session exists yet.
+ // `/login` runs before the first chat turn, so no client session exists yet.
screen,
userInput: input,
name: "Packed install model command",
@@ -119,7 +143,7 @@ void (async () => {
{
kind: "attention",
label: "model provider not linked",
- command: "/model",
+ command: "/login",
},
],
},
@@ -131,15 +155,13 @@ void (async () => {
// The provider picker paints inside the shared onboarding journey before
// the first prompt only when its module graph loads — the exact surface
// the oxc-parser regression crashed.
- await screen.waitForText("Set up Packed install model command", 15_000);
- await screen.waitForText("Which model provider do you want to use?", 15_000);
- console.log(theme.muted("[tui-packed-install] /model opened provider setup"));
+
+ await screen.waitForText("Choose a connection", 15_000);
+ await screen.waitForText("Anthropic API Key", 5_000);
+ console.log(theme.muted("[tui-packed-install] /login opened connection setup"));
input.send("\x1b");
- await screen.waitForText("Change model", 5_000);
- input.send("\x1b");
- // Initial onboarding suppresses the standalone command transcript; cancelling
- // the required model phase returns directly to chat.
+ // Cancelling first-run connection setup returns directly to chat.
await screen.waitForIdlePrompt(5_000);
input.type("/exit");
@@ -149,11 +171,7 @@ void (async () => {
} catch (error) {
console.error(`[tui-packed-install] screen at failure:\n${screen.snapshot()}`);
input.ctrlC();
- // ctrl-C is a no-op while the `/model` menu is parked waiting for a
- // selection, so an unbounded `await runPromise` hangs here — the `throw`
- // never runs, the outer catch never sets `process.exitCode`, and the idle
- // event loop drains to a false exit-0. Bound the unwind so the failure
- // always lands.
+ // Bound cleanup so a stalled runner cannot prevent the failure from being reported.
await withTimeout(runPromise, 2_000, "runner did not unwind after ctrl-C").catch(() => {});
throw error;
}
diff --git a/packages/eve/test/tui-client/tui-questions-freeform.ts b/packages/eve/test/tui-client/tui-questions-freeform.ts
index af68b2d44..c37062cce 100644
--- a/packages/eve/test/tui-client/tui-questions-freeform.ts
+++ b/packages/eve/test/tui-client/tui-questions-freeform.ts
@@ -52,7 +52,7 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
input.type(promptLines.join(" · "));
input.enter();
- await screen.waitForText("▶ 1. Production", 60_000);
+ await screen.waitForText("› 1. Production", 60_000);
console.log(theme.muted("[tui-freeform] select UI live, highlight on Production"));
await sleep(500);
@@ -61,7 +61,7 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
input.emit("data", Buffer.from("\x1B[B")); // → Staging
input.emit("data", Buffer.from("\x1B[B")); // → Preview
input.emit("data", Buffer.from("\x1B[B")); // → Type your own answer
- await screen.waitForText("▶ 4. Type your own answer", 2_000);
+ await screen.waitForText("› 4. Type your own answer", 2_000);
console.log(theme.muted("[tui-freeform] highlight moved to freeform row"));
// The freeform row focuses its inline elbow editor the moment the cursor
diff --git a/packages/eve/test/tui-client/tui-questions.ts b/packages/eve/test/tui-client/tui-questions.ts
index 0f8c614ad..85afd1044 100644
--- a/packages/eve/test/tui-client/tui-questions.ts
+++ b/packages/eve/test/tui-client/tui-questions.ts
@@ -19,7 +19,7 @@ import { theme } from "./lib/theme.ts";
* 3. Type a prompt that asks the model to call `ask_question` with
* two options (red/blue).
* 4. Wait for the question overlay to display the numbered select
- * indicator (`▶ 1. <label>`), which proves the question UI is up.
+ * indicator (`› 1. <label>`), which proves the question UI is up.
* 5. Send Down arrow + Enter to pick the second option (blue).
* 6. Wait for the answered marker (`⎿ <label>`) in the transcript.
* 7. Wait for the post-answer assistant turn to render. The runner
@@ -62,7 +62,7 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
input.type(promptLines.join(" · "));
input.enter();
- await screen.waitForText("▶ 1. Red", 60_000);
+ await screen.waitForText("› 1. Red", 60_000);
console.log(theme.muted("[tui-questions] select UI is live, highlight on Red"));
// Bridges a server-side race where the park hook isn't yet
@@ -72,7 +72,7 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
await sleep(500);
input.emit("data", Buffer.from("\x1B[B"));
- await screen.waitForText("▶ 2. Blue", 2_000);
+ await screen.waitForText("› 2. Blue", 2_000);
console.log(theme.muted("[tui-questions] highlight moved to Blue"));
input.enter();
diff --git a/packages/eve/test/tui-client/tui-queue-steer.ts b/packages/eve/test/tui-client/tui-steer.ts
similarity index 55%
rename from packages/eve/test/tui-client/tui-queue-steer.ts
rename to packages/eve/test/tui-client/tui-steer.ts
index a152a7d6f..104a97898 100644
--- a/packages/eve/test/tui-client/tui-queue-steer.ts
+++ b/packages/eve/test/tui-client/tui-steer.ts
@@ -8,18 +8,13 @@ import { run } from "./lib/run.ts";
import { theme } from "./lib/theme.ts";
/**
- * End-to-end proof of the mid-turn message queue, Ctrl+C steering, single-Esc
- * cooperative cancellation, and double-Ctrl+C exit against a live server:
+ * End-to-end proof of steer-on-Enter, single-Esc cooperative cancellation,
+ * and double-Ctrl+C exit against a live server:
*
- * 1. Start a long turn, then submit two messages while it streams —
- * both must land in the pinned `↑ Queue n/5` panel, not the turn.
- * 2. Ctrl+C pops the oldest queued message and submits it for steering;
- * the popped message joins the running turn at its next committed
- * boundary without cancelling the model or tool work already in flight.
- * 3. The remaining queued message auto-drains as the following turn.
- * 4. The steered echo carries the `↑` provenance arrow above its bar,
- * the queued one below, and the runner returns to an idle prompt.
- * 5. With no message queued, one Esc cancels another long turn, then a
+ * 1. Start a long turn, then press Enter on a follow-up while it streams.
+ * The message steers immediately without entering the queue panel.
+ * 2. The steered message is answered and the runner returns to an idle prompt.
+ * 3. With no message queued, one Esc cancels another long turn, then a
* follow-up succeeds on the preserved session.
*
* The tokens prove delivery order end-to-end: each must appear twice
@@ -27,7 +22,6 @@ import { theme } from "./lib/theme.ts";
*/
const STEER_TOKEN = "STEER-MARKER-B7Q";
-const QUEUE_TOKEN = "QUEUE-MARKER-K4Z";
const CANCEL_FOLLOW_UP_TOKEN = "CANCEL-FOLLOW-UP-MARKER-P8N";
process.env.EVE_TUI_UNICODE = "1";
@@ -39,7 +33,7 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
client,
screen,
userInput: input,
- name: "TUI queue/steer smoke",
+ name: "TUI steer smoke",
});
const runPromise = runner.run().catch((error: unknown) => {
@@ -57,49 +51,17 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
await screen.waitForText("Working for", 30_000);
input.type(`Reply with one short sentence containing the token ${STEER_TOKEN}.`);
+ const steeringOutputStart = screen.rawOutput().length;
input.enter();
- await screen.waitForText("Queue 1/5", 10_000);
- input.type(`Reply with one short sentence containing the token ${QUEUE_TOKEN}.`);
- input.enter();
- await screen.waitForText("Queue 2/5", 10_000);
- console.log(theme.muted("[tui-queue-steer] two messages queued behind the running turn"));
-
- // Admission can clear the transient Steering label before the next render.
- // The echoed message, answer, and provenance arrow prove accepted steering.
- input.ctrlC();
await waitForTwice(screen, STEER_TOKEN, 120_000, "steered turn echo + reply");
- console.log(theme.muted("[tui-queue-steer] steered message answered"));
-
- await waitForTwice(screen, QUEUE_TOKEN, 120_000, "auto-drained turn echo + reply");
- console.log(theme.muted("[tui-queue-steer] remaining queue auto-drained"));
+ if (screen.rawOutput().slice(steeringOutputStart).includes("Queue 1/5")) {
+ throw new Error(`Enter queued the follow-up instead of steering:\n${screen.snapshot()}`);
+ }
+ console.log(theme.muted("[tui-steer] steered message answered"));
await screen.waitForIdlePrompt(60_000);
- // Provenance arrows: steered above its bar, queued below.
- const lines = screen.snapshot().split("\n");
- const steerEcho = lines.findIndex((line) =>
- line.includes(`│ Reply with one short sentence containing the token ${STEER_TOKEN}`),
- );
- if (steerEcho <= 0 || lines[steerEcho - 1]?.trim() !== "↑") {
- throw new Error(
- `Steered echo is missing its ↑ marker above the bar:\n${lines
- .slice(Math.max(0, steerEcho - 2), steerEcho + 1)
- .join("\n")}`,
- );
- }
- const queueEcho = lines.findIndex((line) =>
- line.includes(`│ Reply with one short sentence containing the token ${QUEUE_TOKEN}`),
- );
- if (queueEcho < 0 || lines[queueEcho + 1]?.trim() !== "↑") {
- throw new Error(
- `Queued echo is missing its ↑ marker below the bar:\n${lines
- .slice(queueEcho, queueEcho + 3)
- .join("\n")}`,
- );
- }
- console.log(theme.muted("[tui-queue-steer] provenance arrows rendered"));
-
const cancellationOutputStart = screen.rawOutput().length;
input.type("Write a story of about 500 words about lighthouses. Do not use any tools.");
input.enter();
@@ -116,13 +78,13 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {
"single-Esc cancellation",
);
await screen.waitForIdlePrompt(30_000);
- console.log(theme.muted("[tui-queue-steer] one empty-queue Esc cancelled the turn"));
+ console.log(theme.muted("[tui-steer] one empty-queue Esc cancelled the turn"));
input.type(`Reply with one short sentence containing the token ${CANCEL_FOLLOW_UP_TOKEN}.`);
input.enter();
await waitForTwice(screen, CANCEL_FOLLOW_UP_TOKEN, 120_000, "post-cancellation follow-up");
await screen.waitForIdlePrompt(60_000);
- console.log(theme.muted("[tui-queue-steer] preserved session answered after cancellation"));
+ console.log(theme.muted("[tui-steer] preserved session answered after cancellation"));
input.ctrlC();
await screen.waitForText("Press Ctrl+C again to exit", 5_000);
diff --git a/packages/eve/test/tui-client/tui-traces.ts b/packages/eve/test/tui-client/tui-traces.ts
index 72d666312..9952de5d1 100644
--- a/packages/eve/test/tui-client/tui-traces.ts
+++ b/packages/eve/test/tui-client/tui-traces.ts
@@ -212,7 +212,7 @@ void (async () => {
await screen.waitForText("smoke prompt", 5_000);
await screen.waitForText("smoke reply", 5_000);
await screen.waitForText("get_weather", 5_000);
- if (screen.snapshot().includes("›")) {
+ if (screen.snapshot().includes("❯")) {
throw new Error(`The chat prompt leaked into the viewer frame:\n${screen.snapshot()}`);
}
console.log(theme.muted("[tui-traces] /traces opened on the conversation cards"));
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1a7f945a7..56097ae60 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -580,6 +580,9 @@ importers:
specifier: 2.4.0
version: 2.4.0
devDependencies:
+ eve:
+ specifier: workspace:*
+ version: link:../../packages/eve
vitest:
specifier: 'catalog:'
diff --git a/research/init-to-chat.md b/research/init-to-chat.md
new file mode 100644
index 000000000..f96a8b851
--- /dev/null
+++ b/research/init-to-chat.md
@@ -0,0 +1,33 @@
+---
+issue: TBD
+status: in-progress
+last_updated: "2026-09-16"
+---
+
+# From init to chat
+
+Interactive `eve init` scaffolds and opens the TUI. Connection readiness replaces the model, channels, integrations, and review interview. `/login` connects; `/model` selects models and settings; `/add` searches and installs one addition immediately.
+
+The public direct-provider surfaces are `openai(model?)` from `eve/models/openai` and `anthropic(model?)` from `eve/models/anthropic`, alongside `chatgpt(model?)`. Defaults are `gpt-5.6-luna-fast` and `claude-sonnet-5`. Source edits recognize eve-owned helpers and reject unsafe custom expressions.
+
+A project's choice wins over discovery. New connections prefer explicit environment credentials, the machine default, then Vercel CLI's current team. Projectless Gateway requests carry the account token and validated `x-vercel-ai-gateway-team` header. CLI credential rotation remains CLI-owned. eve-owned refresh credentials and keys use just-secrets; rotating access tokens remain in memory behind a credential broker and cross-process refresh lock. Authored files, generated artifacts, and workflow state contain no discovered secrets. Local discovery never supplies deployment credentials.
+
+Menus retain eve's renderer and scrollback with borderless rows, a `›` marker, bold selection, dim secondary text, filtering, and Enter/Esc navigation. Authorization semantics and required setup remain intact. Connection-ready and first-response telemetry contains timing and state only.
+
+Release acceptance requires projectless Gateway account-token support for the intended audience; this backend capability is feature-gated. The OAuth client ID is isolated and shared with Vercel CLI for its supported device authorization flow. Deterministic tests cover routing and failure behavior. Local acceptance on 2026-09-14 also validated the existing CLI account/team and streamed a `gpt-5.6-luna-fast` response without a linked project. CI fixture evals remain the end-to-end gate.
+
+Vercel CLI installation and account login belong to interactive deployment, including already-linked projects. `/vc:install` and `/vc:login` are removed. Remote chat reuses existing credentials without starting a browser login; noninteractive deployment remains nonblocking.
+
+The setup panel owns one heading across loading and questions. Question painters supply the body; they do not repeat the heading. Closing a question hands presentation to the next phase without an immediate idle repaint. Routine cancellation has one quiet outcome, while partial work and failures retain their reports.
+
+## Connection activation
+
+Authentication returns validated connection metadata and any model list obtained during validation. Local model inspection reads editable source without compiling; dynamic expressions retain routing inspection and safe refusal. Gateway catalog loading overlaps authentication, while provider-specific model lists wait for credentials. Catalog failures are collected without abandoning browser prompts.
+
+Activation compares the intended project settings before writing. Only model source changes acquire a runtime suspension lease and wait for activation. Account, team, and key changes are atomic metadata updates; they do not recompile the agent or replace its worker.
+
+The development host owns credential resolution. Workers request current credentials through the authenticated loopback control plane, reusing the host’s OAuth access token and ChatGPT broker across worker replacements. Rejected-token fingerprints allow refresh without placing tokens in URLs. Credential selection happens at request time; deployments continue using their explicit server credentials.
+
+Successful login returns nonsecret model and connection metadata directly to the TUI. `/info` and setup diagnostics refresh in the background, with revision checks discarding stale results. Neither a failed inspection nor a pending footer refresh delays the first message. Source activation still completes before a changed model is used.
+
+Status text describes the current wait: browser sign-in, team loading, Gateway access, model availability, or loading the selected model. Local settings reads and credential validation have distinct labels. Loading indicators wait 150 ms to avoid flashing for quick work. Fixed-name debug events measure source inspection, catalog loading, authentication, and activation without recording credentials or team details.