The Open Framework for Building Agents
feat(eve): add /connect setup flow (#327)
Rui24faac00ba08
diff --git a/.changeset/connect-command.md b/.changeset/connect-command.mdnew file mode 100644index 000000000..e3afb4d61--- /dev/null+++ b/.changeset/connect-command.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Add a searchable `/connect` flow to the local dev TUI. It scaffolds an MCP connection, resolves its Vercel Connect connector, and reuses the model setup flow to create or link a Vercel project when needed. Local Vercel users now authorize Connect with their Vercel user ID instead of a reserved OIDC issuer.diff --git a/apps/frameworks/next/agent/channels/eve.ts b/apps/frameworks/next/agent/channels/eve.tsindex 4a3b240b5..2dc2fe6ac 100644--- a/apps/frameworks/next/agent/channels/eve.ts+++ b/apps/frameworks/next/agent/channels/eve.ts@@ -31,5 +31,5 @@ function authjsSession(): AuthFn<Request> {}export default eveChannel({- auth: [authjsSession(), localDev(), vercelOidc()],+ auth: [authjsSession(), vercelOidc(), localDev()],});diff --git a/apps/templates/web-chat-next/agent/channels/eve.ts b/apps/templates/web-chat-next/agent/channels/eve.tsindex 9c665bea5..dafc1220f 100644--- a/apps/templates/web-chat-next/agent/channels/eve.ts+++ b/apps/templates/web-chat-next/agent/channels/eve.ts@@ -3,10 +3,10 @@ import { localDev, placeholderAuth, vercelOidc } from "eve/channels/auth";export default eveChannel({auth: [- // Open on localhost for `eve dev` and the REPL; ignored in production.- localDev(),// Lets the eve TUI and your Vercel deployments reach the deployed agent.vercelOidc(),+ // Open on localhost for `eve dev` and the REPL; ignored in production.+ localDev(),// This placeholder will not allow browser requests in production.// Replace it with your app's auth provider, like Auth.js or Clerk,// or use none() for a public demo.diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdxindex dda6631aa..6cb5a298d 100644--- a/docs/channels/eve.mdx+++ b/docs/channels/eve.mdx@@ -12,7 +12,7 @@ import { eveChannel } from "eve/channels/eve";import { localDev, vercelOidc } from "eve/channels/auth";export default eveChannel({- auth: [localDev(), vercelOidc()],+ auth: [vercelOidc(), localDev()],});```@@ -54,7 +54,7 @@ The `auth` option decides who can call these routes. The built-in helpers coverNeither admits browser users or external clients in production. For a public app, wire the channel to your own auth (Clerk, Auth.js, your own OIDC/JWT verification, an API-key verifier, or any custom `AuthFn`). Vercel OIDC is optional; use it only when Vercel-issued deployment tokens are part of your trust model.-`eve init` scaffolds an `agent/channels/eve.ts` with a production placeholder so you replace it before going live. The generated channel allows Vercel OIDC and localhost, and includes `placeholderAuth()`, which returns a setup-focused 401 in production until you swap it for real auth. Delete the file and eve falls back to `[localDev(), vercelOidc()]`, which still does not admit browser users in production.+`eve init` scaffolds an `agent/channels/eve.ts` with a production placeholder so you replace it before going live. The generated channel checks Vercel OIDC before falling back to localhost access, and includes `placeholderAuth()`, which returns a setup-focused 401 in production until you swap it for real auth. Delete the file and eve falls back to `[vercelOidc(), localDev()]`, which still does not admit browser users in production.For the full auth model and helper list, see [Auth & route protection](../guides/auth-and-route-protection).@@ -67,7 +67,7 @@ import { eveChannel, defaultEveAuth } from "eve/channels/eve";import { localDev, vercelOidc } from "eve/channels/auth";export default eveChannel({- auth: [localDev(), vercelOidc()],+ auth: [vercelOidc(), localDev()],onMessage(ctx, message) {const callerId = ctx.eve.caller?.principalId ?? "anonymous";return {diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex 859df965c..3ec193195 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -108,7 +108,7 @@ Start with the [TypeScript SDK](../guides/client/overview) guide. It covers basicurl http://127.0.0.1:3000/eve/v1/info```-The route uses the same default auth chain as the eve channel (`[localDev(), vercelOidc()]`). Locally it answers anonymously; a deployed Vercel target requires a valid OIDC bearer, with a same-project bypass for in-deployment callers. See [auth & route protection](../guides/auth-and-route-protection).+The route uses the same default auth chain as the eve channel (`[vercelOidc(), localDev()]`). A local Vercel OIDC bearer takes precedence; other local requests fall back to development access. A deployed Vercel target requires a valid OIDC bearer, with a same-project bypass for in-deployment callers. See [auth & route protection](../guides/auth-and-route-protection).## Dispatch orderdiff --git a/docs/guides/auth-and-route-protection.md b/docs/guides/auth-and-route-protection.mdindex f7d6ec9a8..4737e28f8 100644--- a/docs/guides/auth-and-route-protection.md+++ b/docs/guides/auth-and-route-protection.md@@ -27,7 +27,7 @@ import { eveChannel } from "eve/channels/eve";import { localDev, vercelOidc } from "eve/channels/auth";export default eveChannel({- auth: [localDev(), vercelOidc()],+ auth: [vercelOidc(), localDev()],});```@@ -62,11 +62,11 @@ function appSession(): AuthFn<Request> {}export default eveChannel({- auth: [appSession(), localDev(), vercelOidc()],+ auth: [appSession(), vercelOidc(), localDev()],});```-Put your own providers ahead of the catch-all helpers. Any entry that doesn't recognize the caller returns `null`, and the walk moves on. On non-Vercel hosts, omit `vercelOidc()` unless you specifically want to accept Vercel-issued tokens.+Put your own providers ahead of the catch-all helpers. `localDev()` is the final fallback: put `vercelOidc()` before it so a local Vercel OIDC bearer can resolve a user instead of being shadowed by the synthetic local principal. Any entry that doesn't recognize the caller returns `null`, and the walk moves on. On non-Vercel hosts, omit `vercelOidc()` unless you specifically want to accept Vercel-issued tokens.To reject with a precise status instead of skipping, throw:@@ -197,11 +197,11 @@ import { eveChannel } from "eve/channels/eve";import { localDev, placeholderAuth, vercelOidc } from "eve/channels/auth";export default eveChannel({- auth: [localDev(), vercelOidc(), placeholderAuth()],+ auth: [vercelOidc(), localDev(), placeholderAuth()],});```-In production, `placeholderAuth()` returns a structured `401` so a generated web chat app can say "auth isn't configured yet" instead of throwing an internal error. Replace it before a browser caller submits a production request: swap in your app's `AuthFn` or one of the shipped helpers. Delete the authored channel file entirely and eve falls back to the framework default `[localDev(), vercelOidc()]`, which also rejects production browser traffic.+In production, `placeholderAuth()` returns a structured `401` so a generated web chat app can say "auth isn't configured yet" instead of throwing an internal error. Replace it before a browser caller submits a production request: swap in your app's `AuthFn` or one of the shipped helpers. Delete the authored channel file entirely and eve falls back to the framework default `[vercelOidc(), localDev()]`, which also rejects production browser traffic.You do not have to keep `vercelOidc()` in the final policy. For a self-hosted app, an app-embedded frontend, or any deployment that uses a non-Vercel identity system, use `httpBasic()`, `jwtHmac()`, `jwtEcdsa()`, generic `oidc()`, or a custom `AuthFn` that maps your verified user/session/API key into a `SessionAuthContext`.diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.mdindex 702fa38cb..6d5efb82b 100644--- a/docs/guides/dev-tui.md+++ b/docs/guides/dev-tui.md@@ -30,12 +30,13 @@ Errors render compactly with docs links highlighted. A code bug escaping your ag## Slash commands-Each command echoes as an invocation line, asks through a bordered panel that takes the input area's place (one question at a time, separate from the chat transcript), and finishes with a one-line `⎿` result. Loading states stay on the ephemeral status line instead of piling into the transcript; model, channel, and the Vercel CLI commands (`/vc:install`, `/vc:login`) use the same green square pulse as the build phase, while `/deploy` keeps a spinner. Setup menus render the selected option with a filled arrow and an inverse label padded by one space on each side. Text prompts use a blinking block cursor over the character at the caret. The selected label is blue normally and yellow for warning rows.+Each command echoes as an invocation line, asks through a bordered panel that takes the input area's place (one question at a time, separate from the chat transcript), and finishes with a one-line `⎿` result. Loading states stay on the ephemeral status line instead of piling into the transcript; model, channel, connection, and the Vercel CLI commands (`/vc:install`, `/vc:login`) use the same green square pulse as the build phase, while `/deploy` keeps a spinner. A connection setup waiting for browser action changes that pulse and the word "browser" to yellow. Setup menus render the selected option with a filled arrow and an inverse label padded by one space on each side. Text prompts use a blinking block cursor over the character at the caret. The selected label is blue normally and yellow for warning rows.| Command | Does || ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ || `/model` | Opens a configure menu that loops until Done (or Esc). See [Configure the model and provider](#configure-the-model-and-provider). || `/channels` | Shows the agent's channel list and adds the one you pick. See [Add a channel](#add-a-channel). |+| `/connect` | Shows the Vercel Connect MCP catalog and configures the server you pick. See [Add a connection](#add-a-connection). || `/deploy` | Ships the agent to Vercel production, linking the directory first when it is unlinked. || `/vc:install` | Installs the Vercel CLI. Available locally and on a remote session. || `/vc:login` | Logs in to Vercel locally. On a remote session, resolves the deployment's project, refreshes its OIDC token, and confirms any required Trusted Sources rule. |@@ -44,7 +45,7 @@ Each command echoes as an invocation line, asks through a bordered panel that ta| `/exit` | Quits the TUI. || `/help` | Lists the commands available for the current local or remote session. |-`/model`, `/channels`, and `/deploy` manage the project and are available only when `eve dev` runs the server locally, not when connected to a remote server with `--url`.+`/model`, `/channels`, `/connect`, and `/deploy` manage the local agent or its linked project. They are available only when `eve dev` runs the server locally, not when connected to a remote server with `--url`.### Configure the model and provider@@ -58,6 +59,12 @@ The provider row demands attention (a bold yellow "Configure model access" with`/channels` shows the agent's channel list. Already-registered channels render as checked, focusable rows with an "Already installed" hint. Picking one adds it (including the Slack Connect provisioning), then installs the dependencies the scaffold added so the dev server can load the new channels right away. After each addition the list repaints with the channel checked, until Done (or Esc) leaves the flow.+### Add a connection++`/connect` shows a searchable list of MCP servers available through Vercel Connect. Already-authored connections remain checked. Logged-out users are directed to `/vc:login`. When the directory is not linked, selecting a server opens the same team and project flow used by `/model`, including creating a project or linking an existing one.++For a selected server, eve first tries to attach the provider's canonical connector. If that fails, choose an existing connector from a searchable list or create one with a specific name. The fallback stays scoped to the team selected by the linked project. A connector created by the current attempt is removed if attachment or connection-file patching fails. Successful setup writes `agent/connections/<name>.ts`, records the attached connector UID, installs the new dependency so the dev server can load it, then returns to the main prompt.+## Keyboard shortcutsChat and freeform `ask_question` inputs behave like a shell line editor.@@ -83,7 +90,7 @@ When the agent needs something from you, the TUI asks inline.- Tool approvals are a `y` or `n`.- Option questions let you pick with `↑` / `↓` and `Enter`, or you can compose a multi-line freeform answer.-- If a tool needs an authorized [connection](../connections), the URL shows up right in the transcript, and the turn picks back up once you finish the flow.+- If a tool needs an authorized [connection](../connections), the URL shows up right in the transcript, and the turn picks back up once you finish the flow. The same local `eve dev` server owns the callback route, so keep that command running until the browser returns. `eve dev --url` connects to an already-running server and does not start a local callback host.## Control what logs showdiff --git a/docs/guides/frontend/nextjs.mdx b/docs/guides/frontend/nextjs.mdxindex 62521f127..0ee3ec89d 100644--- a/docs/guides/frontend/nextjs.mdx+++ b/docs/guides/frontend/nextjs.mdx@@ -61,13 +61,13 @@ const agent = useEveAgent({});```-The default eve channel is fail-closed. With no `agent/channels/eve.ts` authored, eve registers `eveChannel({ auth: [localDev(), vercelOidc()] })`: `localDev()` opens the routes on localhost, `vercelOidc()` admits Vercel OIDC callers in production, and everything else gets a `401`. To run your app's own auth policy, add `agent/channels/eve.ts`:+The default eve channel is fail-closed. With no `agent/channels/eve.ts` authored, eve registers `eveChannel({ auth: [vercelOidc(), localDev()] })`: `vercelOidc()` gets the first chance to resolve a Vercel caller, `localDev()` opens the remaining localhost requests, and everything else gets a `401`. To run your app's own auth policy, add `agent/channels/eve.ts`:```ts title="agent/channels/eve.ts"import { eveChannel } from "eve/channels/eve";import { localDev, vercelOidc } from "eve/channels/auth";-export default eveChannel({ auth: [localDev(), vercelOidc()] });+export default eveChannel({ auth: [vercelOidc(), localDev()] });```For a public demo, use `none()` (also from `eve/channels/auth`) to skip authentication. See [Channels](../../channels/overview) and [Auth & route protection](../auth-and-route-protection).diff --git a/docs/guides/frontend/nuxt.mdx b/docs/guides/frontend/nuxt.mdxindex 832ad0947..b8a67f31b 100644--- a/docs/guides/frontend/nuxt.mdx+++ b/docs/guides/frontend/nuxt.mdx@@ -60,13 +60,13 @@ async function handleSubmit() {</template>```-The default eve channel is fail-closed. With no `agent/channels/eve.ts` authored, eve registers `eveChannel({ auth: [localDev(), vercelOidc()] })`: `localDev()` opens the routes on localhost, `vercelOidc()` admits Vercel OIDC callers in production, and everything else gets a `401`. To run your own auth policy, add `agent/channels/eve.ts`:+The default eve channel is fail-closed. With no `agent/channels/eve.ts` authored, eve registers `eveChannel({ auth: [vercelOidc(), localDev()] })`: `vercelOidc()` gets the first chance to resolve a Vercel caller, `localDev()` opens the remaining localhost requests, and everything else gets a `401`. To run your own auth policy, add `agent/channels/eve.ts`:```ts title="agent/channels/eve.ts"import { eveChannel } from "eve/channels/eve";import { localDev, vercelOidc } from "eve/channels/auth";-export default eveChannel({ auth: [localDev(), vercelOidc()] });+export default eveChannel({ auth: [vercelOidc(), localDev()] });```For a public demo, use `none()` (also from `eve/channels/auth`) to skip authentication. See [Channels](../../channels/overview) and [Auth & route protection](../auth-and-route-protection).diff --git a/docs/guides/frontend/sveltekit.mdx b/docs/guides/frontend/sveltekit.mdxindex 0ae554cf0..c4a3774b0 100644--- a/docs/guides/frontend/sveltekit.mdx+++ b/docs/guides/frontend/sveltekit.mdx@@ -69,13 +69,13 @@ With the plugin in `vite.config.ts`, components call [`useEveAgent`](./use-eve-a</form>```-The default eve channel is fail-closed. With no `agent/channels/eve.ts` authored, eve registers `eveChannel({ auth: [localDev(), vercelOidc()] })`: `localDev()` opens the routes on localhost, `vercelOidc()` admits Vercel OIDC callers in production, and everything else gets a `401`. To set your own auth policy, add `agent/channels/eve.ts`:+The default eve channel is fail-closed. With no `agent/channels/eve.ts` authored, eve registers `eveChannel({ auth: [vercelOidc(), localDev()] })`: `vercelOidc()` gets the first chance to resolve a Vercel caller, `localDev()` opens the remaining localhost requests, and everything else gets a `401`. To set your own auth policy, add `agent/channels/eve.ts`:```ts title="agent/channels/eve.ts"import { eveChannel } from "eve/channels/eve";import { localDev, vercelOidc } from "eve/channels/auth";-export default eveChannel({ auth: [localDev(), vercelOidc()] });+export default eveChannel({ auth: [vercelOidc(), localDev()] });```For a public demo, use `none()` (also from `eve/channels/auth`) to skip authentication. See [Channels](../../channels/overview) and [Auth & route protection](../auth-and-route-protection).diff --git a/docs/tutorial/ship-it.mdx b/docs/tutorial/ship-it.mdxindex a9998546e..e2c9cfc11 100644--- a/docs/tutorial/ship-it.mdx+++ b/docs/tutorial/ship-it.mdx@@ -113,7 +113,7 @@ const appAuth: AuthFn<Request> = async (request) => {};export default eveChannel({- auth: [appAuth, localDev(), vercelOidc()],+ auth: [appAuth, vercelOidc(), localDev()],});```diff --git a/docs/tutorial/team-playbooks.mdx b/docs/tutorial/team-playbooks.mdxindex a26fbaeb5..126fa3160 100644--- a/docs/tutorial/team-playbooks.mdx+++ b/docs/tutorial/team-playbooks.mdx@@ -71,7 +71,7 @@ const devTeam: AuthFn<Request> = () =>};export default eveChannel({- auth: [devTeam, localDev(), vercelOidc(), placeholderAuth()],+ auth: [devTeam, vercelOidc(), localDev(), placeholderAuth()],});```diff --git a/packages/eve/src/cli/dev/tui/agent-header.test.ts b/packages/eve/src/cli/dev/tui/agent-header.test.tsindex d53ca4d92..33d8b34e2 100644--- a/packages/eve/src/cli/dev/tui/agent-header.test.ts+++ b/packages/eve/src/cli/dev/tui/agent-header.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";import type { AgentInfoResult, AgentInfoToolEntry } from "#client/index.js";import { AGENT_HEADER_TIPS, buildAgentHeader, pickAgentHeaderTip } from "./agent-header.js";+import { stripAnsi } from "./terminal-text.js";import { createTheme } from "./theme.js";const FRAMEWORK_TOOL: AgentInfoToolEntry = {@@ -133,6 +134,25 @@ describe("buildAgentHeader", () => {expect(remote.join("\n")).not.toContain("/channels");});+ it("renders the /connect tip with a blue command", () => {+ const colorTheme = createTheme({ color: true, unicode: false });+ const tip = AGENT_HEADER_TIPS.find((candidate) => candidate.includes("/connect"));++ expect(tip).toBe("Tip: /connect to seamlessly add MCP Connections to your agent");+ if (tip === undefined) return;++ const line = buildAgentHeader({+ name: "weather-agent",+ info: INFO,+ theme: colorTheme,+ width: 120,+ tip,+ }).at(-1);++ expect(stripAnsi(line ?? "")).toBe(` ${tip}`);+ expect(line).toContain(colorTheme.colors.blue("/connect"));+ });+it("keeps the discovery-diagnostics line when the compiler reported problems", () => {const info: AgentInfoResult = {...INFO,diff --git a/packages/eve/src/cli/dev/tui/agent-header.ts b/packages/eve/src/cli/dev/tui/agent-header.tsindex 9035c54d8..8ea3cddda 100644--- a/packages/eve/src/cli/dev/tui/agent-header.ts+++ b/packages/eve/src/cli/dev/tui/agent-header.ts@@ -7,6 +7,7 @@*/import type { AgentInfoResult } from "#client/index.js";+import { isPromptControlCommand } from "./prompt-commands.js";import type { Theme } from "./theme.js";import { truncate } from "./tool-format.js";@@ -30,6 +31,7 @@ export const AGENT_HEADER_TIPS: readonly string[] = ["Use /channels to add more ways to reach your agent.","Use /deploy to see your agent go live.","Type /help to see every command.",+ "Tip: /connect to seamlessly add MCP Connections to your agent",];/** Picks one tip; `random` is a test seam over Math.random. */@@ -75,12 +77,21 @@ export function buildAgentHeader(input: AgentHeaderInput): string[] {}if (input.tip !== undefined) {- lines.push(` ${c.dim(truncate(input.tip, Math.max(8, width - 2)))}`);+ lines.push(` ${renderTip(input.tip, Math.max(8, width - 2), theme)}`);}return lines;}+function renderTip(tip: string, width: number, theme: Theme): string {+ return truncate(tip, width)+ .split(/(\/[a-z:-]+)/u)+ .map((part) =>+ isPromptControlCommand(part) ? theme.colors.blue(part) : theme.colors.dim(part),+ )+ .join("");+}+function plural(count: number): string {return count === 1 ? "" : "s";}diff --git a/packages/eve/src/cli/dev/tui/prompt-commands.test.ts b/packages/eve/src/cli/dev/tui/prompt-commands.test.tsindex e41553e80..9caad9fa0 100644--- a/packages/eve/src/cli/dev/tui/prompt-commands.test.ts+++ b/packages/eve/src/cli/dev/tui/prompt-commands.test.ts@@ -94,6 +94,7 @@ describe("promptCommandsFor", () => {const names = promptCommandsFor("local").map((command) => command.name);expect(names).toContain("model");expect(names).toContain("channels");+ expect(names).toContain("connect");expect(names).toContain("deploy");expect(names).toContain("vc:install");expect(names).toContain("vc:login");@@ -107,6 +108,7 @@ describe("promptCommandsFor", () => {expect(names).not.toContain("vc:auth");expect(names).not.toContain("model");expect(names).not.toContain("channels");+ expect(names).not.toContain("connect");expect(names).not.toContain("deploy");});diff --git a/packages/eve/src/cli/dev/tui/prompt-commands.ts b/packages/eve/src/cli/dev/tui/prompt-commands.tsindex 0839d69f9..be7bac701 100644--- a/packages/eve/src/cli/dev/tui/prompt-commands.ts+++ b/packages/eve/src/cli/dev/tui/prompt-commands.ts@@ -1,6 +1,7 @@export type PromptCommandExtensionName =| "model"| "channels"+ | "connect"| "deploy"| "vc:install"| "vc:login";@@ -104,6 +105,14 @@ const PROMPT_COMMAND_DEFINITIONS = [build: () => ({ type: "extension", name: "channels", argument: "" }),targets: ["local"],},+ {+ name: "connect",+ aliases: [],+ description: "Add an MCP server through Vercel Connect",+ takesArgument: false,+ build: () => ({ type: "extension", name: "connect", argument: "" }),+ targets: ["local"],+ },{name: "deploy",aliases: [],diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex 8cd47c4df..3a1de2de7 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -662,6 +662,57 @@ describe("EveTUIRunner native continuation state", () => {});});+describe("EveTUIRunner connection authorization", () => {+ it("continues a parked interactive authorization session until the callback completes", async () => {+ const prompts: Array<string | undefined> = ["connect linear", undefined];+ const updates: Array<{ name: string; state: string }> = [];+ const pendingCounts: number[] = [];+ const session = sessionYielding([+ {+ type: "authorization.required",+ data: {+ authorization: { url: "https://connect.vercel.com/authorize/linear" },+ description: "Authorization required for linear",+ name: "linear",+ webhookUrl: "https://eve.test/connections/linear/callback",+ },+ },+ { type: "session.waiting", data: { wait: "connection-authorization" } },+ ]);+ vi.spyOn(session, "stream").mockImplementation(async function* () {+ yield {+ type: "authorization.completed",+ data: { name: "linear", outcome: "authorized" },+ } as HandleMessageStreamEvent;+ yield {+ type: "session.waiting",+ data: { wait: "next-user-message" },+ } as HandleMessageStreamEvent;+ });+ const renderer: AgentTUIRenderer = {+ readPrompt: vi.fn(async () => prompts.shift()),+ upsertConnectionAuth: (update) => updates.push({ name: update.name, state: update.state }),+ setConnectionAuthPendingCount: (count) => pendingCounts.push(count),+ renderStream: vi.fn(async (result) => {+ for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {+ void event;+ }+ }),+ };++ const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });+ await runner.run();++ expect(session.stream).toHaveBeenCalledTimes(1);+ expect(updates).toEqual([+ { name: "linear", state: "required" },+ { name: "linear", state: "pending" },+ { name: "linear", state: "authorized" },+ ]);+ expect(pendingCounts).toEqual([1, 0]);+ });+});+describe("EveTUIRunner failure rendering", () => {it("renders one error block for a step/turn/session failure cascade", async () => {const prompts: Array<string | undefined> = ["hello", undefined];@@ -1692,6 +1743,46 @@ describe("EveTUIRunner Vercel status line", () => {expect(info).toHaveBeenCalledTimes(2);});+ it("forces a runtime rebuild after /connect adds a connection", async () => {+ const client = stubClient();+ vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);+ const requests: URL[] = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: Parameters<typeof fetch>[0]) => {+ const url = new URL(+ typeof input === "string" ? input : input instanceof URL ? input : input.url,+ );+ requests.push(url);+ return Response.json({ revision: url.searchParams.get("force") === "1" ? "next" : "base" });+ }),+ );+ const prompts: Array<string | undefined> = ["/connect", undefined];+ const renderer = fakeRenderer({ readPrompt: vi.fn(async () => prompts.shift()) });+ const connectOutcome = {+ message: "Connections added: linear.",+ effect: { kind: "connection-added" },+ } satisfies PromptCommandOutcome;++ const runner = new EveTUIRunner({+ session: stubSession(),+ client,+ renderer,+ serverUrl: "http://localhost:3000",+ name: "Weather Agent",+ promptCommandHandler: { handle: async () => connectOutcome },+ });+ await runner.run();++ expect(+ requests.some(+ (url) =>+ url.pathname === "/eve/v1/dev/runtime-artifacts/rebuild" &&+ url.searchParams.get("force") === "1",+ ),+ ).toBe(true);+ });+it("never pushes Vercel status for a remote --url session", async () => {const setVercelStatus = vi.fn();const renderer = fakeRenderer({ setVercelStatus });diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex 2a14e9190..4ca89f07c 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -304,8 +304,8 @@ export interface PromptCommandHandlerContext {export interface PromptCommandOutcome {/** Outcome line rendered under the echoed command; absent renders nothing. */message?: string;- /** Post-command work; model access also re-probes the Vercel identity. */- effect?: VercelStatusEffect | { kind: "model-access-changed" };+ /** Post-command work after setup settles. */+ effect?: VercelStatusEffect | { kind: "connection-added" } | { kind: "model-access-changed" };}export interface PromptCommandHandler {@@ -716,76 +716,88 @@ export class EveTUIRunner {hasRunTurn = true;}- const result = await this.#streamTurn({+ let result = await this.#streamTurn({prompt: streamWithoutPrompt ? undefined : prompt,inputResponses: pendingInputResponses,});+ let submittedPrompt = prompt;+ let respondedToInputRequest = false;try {- await this.#renderer.renderStream(result, {- title,- submittedPrompt: prompt,- continueSession: Boolean(this.#renderer.readPrompt),- tools: this.#tools,- reasoning: this.#reasoning,- subagents: this.#subagents,- connectionAuth: this.#connectionAuth,- assistantResponseStats: this.#assistantResponseStats,- contextSize: this.#contextSize,- });+ while (true) {+ await this.#renderer.renderStream(result, {+ title,+ submittedPrompt,+ continueSession: Boolean(this.#renderer.readPrompt),+ tools: this.#tools,+ reasoning: this.#reasoning,+ subagents: this.#subagents,+ connectionAuth: this.#connectionAuth,+ assistantResponseStats: this.#assistantResponseStats,+ contextSize: this.#contextSize,+ });- const approvalRequests = result.turnState?.pendingApprovals ?? [];- const questionRequests = result.turnState?.pendingQuestions ?? [];+ const approvalRequests = result.turnState?.pendingApprovals ?? [];+ const questionRequests = result.turnState?.pendingQuestions ?? [];- if (approvalRequests.length > 0 || questionRequests.length > 0) {- const responses: InputResponse[] = [];+ if (approvalRequests.length > 0 || questionRequests.length > 0) {+ const responses: InputResponse[] = [];- if (approvalRequests.length > 0) {- if (!this.#renderer.readToolApproval) {- throw new Error(- "Tool approval was requested, but the renderer does not support tool approval input.",- );- }+ if (approvalRequests.length > 0) {+ if (!this.#renderer.readToolApproval) {+ throw new Error(+ "Tool approval was requested, but the renderer does not support tool approval input.",+ );+ }- for (const request of approvalRequests) {- const response = await this.#renderer.readToolApproval(request, { title });- responses.push({- requestId: request.approvalId,- optionId: response.approved ? "approve" : "deny",- });- this.#pendingInputRequests.delete(request.approvalId);+ for (const request of approvalRequests) {+ const response = await this.#renderer.readToolApproval(request, { title });+ responses.push({+ requestId: request.approvalId,+ optionId: response.approved ? "approve" : "deny",+ });+ this.#pendingInputRequests.delete(request.approvalId);+ }}- }- if (questionRequests.length > 0) {- if (!this.#renderer.readInputQuestion) {- throw new Error(- "An interactive question was requested, but the renderer does not support input questions.",- );- }+ if (questionRequests.length > 0) {+ if (!this.#renderer.readInputQuestion) {+ throw new Error(+ "An interactive question was requested, but the renderer does not support input questions.",+ );+ }- for (const inputRequest of questionRequests) {- const question = toAgentTUIInputQuestion(inputRequest);- const response = await this.#renderer.readInputQuestion(question, { title });- if (response === undefined) {- continue;+ for (const inputRequest of questionRequests) {+ const question = toAgentTUIInputQuestion(inputRequest);+ const response = await this.#renderer.readInputQuestion(question, { title });+ if (response === undefined) {+ continue;+ }+ const inputResponse: InputResponse = { requestId: inputRequest.requestId };+ if (response.optionId !== undefined) inputResponse.optionId = response.optionId;+ if (response.text !== undefined) inputResponse.text = response.text;+ responses.push(inputResponse);+ this.#pendingInputRequests.delete(inputRequest.requestId);}- const inputResponse: InputResponse = { requestId: inputRequest.requestId };- if (response.optionId !== undefined) inputResponse.optionId = response.optionId;- if (response.text !== undefined) inputResponse.text = response.text;- responses.push(inputResponse);- this.#pendingInputRequests.delete(inputRequest.requestId);}++ streamWithoutPrompt = true;+ pendingInputResponses = responses;+ prompt = undefined;+ respondedToInputRequest = true;+ break;}- streamWithoutPrompt = true;- pendingInputResponses = responses;- prompt = undefined;- continue;- }+ if (this.#enterPendingConnectionAuthorization(result)) {+ result = this.#streamConnectionAuthorization();+ submittedPrompt = undefined;+ continue;+ }- if (result.turnState && result.turnState.boundaryEvent === undefined) {- this.#sessionFailed = true;+ if (result.turnState && result.turnState.boundaryEvent === undefined) {+ this.#sessionFailed = true;+ }+ break;}} catch (error) {if (isInterruptedError(error)) {@@ -795,6 +807,10 @@ export class EveTUIRunner {throw error;}+ if (respondedToInputRequest) {+ continue;+ }+streamWithoutPrompt = false;pendingInputResponses = undefined;prompt = undefined;@@ -825,6 +841,7 @@ export class EveTUIRunner {this.#pendingInputRequests.clear();this.#connectionAuthRuns.clear();this.#pendingConnectionAuths.clear();+ this.#renderer.setConnectionAuthPendingCount?.(0);if (this.#client) {this.#session = this.#client.session();@@ -952,12 +969,31 @@ export class EveTUIRunner {};}- const turnState = createTurnState();+ return this.#createTUIStreamResult(response, () => abortController.abort());+ }+ /**+ * Follows the same session after an interactive authorization callback.+ * `send()` stops at the parked `session.waiting` boundary; the callback's+ * completion events arrive in the next durable turn on `session.stream()`.+ */+ #streamConnectionAuthorization(): AgentTUIStreamResult {+ const abortController = new AbortController();+ return this.#createTUIStreamResult(+ this.#session.stream({ signal: abortController.signal }),+ () => abortController.abort(),+ );+ }++ #createTUIStreamResult(+ events: AsyncIterable<HandleMessageStreamEvent>,+ abort: () => void,+ ): AgentTUIStreamResult {+ const turnState = createTurnState();return {- abort: () => abortController.abort(),+ abort,events: eveEventsToTUIStream({- events: response,+ events,pendingInputRequests: this.#pendingInputRequests,subagentRuns: this.#subagentRuns,turnState,@@ -1096,6 +1132,13 @@ export class EveTUIRunner {}async #applyCommandEffect(effect: PromptCommandOutcome["effect"]): Promise<void> {+ if (effect?.kind === "connection-added") {+ this.#vercelStatus?.applyEffect({ kind: "refresh-identity" });+ this.#authHintStale = true;+ await this.#refreshConnectionRuntime();+ await this.#refreshModelAccess();+ return;+ }if (effect?.kind === "model-access-changed") {this.#vercelStatus?.applyEffect({ kind: "refresh-identity" });this.#authHintStale = true;@@ -1109,6 +1152,18 @@ export class EveTUIRunner {void this.#refreshSetupAttention(this.#agentInfo);}+ async #refreshConnectionRuntime(): Promise<void> {+ const client = this.#client;+ const runtimeArtifacts = this.#runtimeArtifacts;+ if (client === undefined || runtimeArtifacts === undefined) return;++ this.#session = await runtimeArtifacts.refreshAfterSourceChange({+ createSession: () => client.session(),+ onRuntimeArtifactsChanged: () => this.#handleRuntimeArtifactsChanged(),+ session: this.#session,+ });+ }+async #executeExtensionCommand(command: Extract<PromptCommand, { type: "extension" }>,title: string,@@ -1216,6 +1271,31 @@ export class EveTUIRunner {this.#emitConnectionAuthUpdate(run);}+ /**+ * Marks framework-owned OAuth challenges as parked only after the current+ * turn has reached its `session.waiting` boundary. A `webhookUrl` is the+ * runtime's proof that a later callback turn can complete the challenge.+ */+ #enterPendingConnectionAuthorization(result: AgentTUIStreamResult): boolean {+ if (result.turnState?.boundaryEvent !== "session.waiting") {+ return false;+ }++ let added = false;+ for (const run of this.#connectionAuthRuns.values()) {+ if (run.state !== "required" || run.webhookUrl === undefined) continue;+ run.state = "pending";+ this.#pendingConnectionAuths.add(run.name);+ this.#emitConnectionAuthUpdate(run);+ added = true;+ }++ if (added) {+ this.#renderer.setConnectionAuthPendingCount?.(this.#pendingConnectionAuths.size);+ }+ return this.#pendingConnectionAuths.size > 0;+ }+#handleConnectionAuthCompleted(event: AuthorizationCompletedStreamEvent): void {const existing = this.#connectionAuthRuns.get(event.data.name);const run: ConnectionAuthRun = existing ?? {diff --git a/packages/eve/src/cli/dev/tui/setup-commands.test.ts b/packages/eve/src/cli/dev/tui/setup-commands.test.tsindex 32a684b8e..1e0afbca4 100644--- a/packages/eve/src/cli/dev/tui/setup-commands.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-commands.test.ts@@ -62,6 +62,10 @@ function fakeFlows(overrides: Partial<TuiSetupFlows> = {}): TuiSetupFlows {kind: "done",addedChannels: [],})),+ runConnectionsFlow: vi.fn<TuiSetupFlows["runConnectionsFlow"]>(async () => ({+ kind: "done",+ addedConnections: [],+ })),runDeployFlow: vi.fn<TuiSetupFlows["runDeployFlow"]>(async () => ({kind: "deployed",productionUrl: "https://my-agent.vercel.app",@@ -71,7 +75,7 @@ function fakeFlows(overrides: Partial<TuiSetupFlows> = {}): TuiSetupFlows {}function run(input: {- command: "vc:install" | "vc:login" | "model" | "channels" | "deploy";+ command: "vc:install" | "vc:login" | "model" | "channels" | "connect" | "deploy";flows: TuiSetupFlows;renderer?: TuiSetupCommandRenderer;initialModelStep?: "provider";@@ -101,6 +105,7 @@ describe("runTuiSetupCommand", () => {"vc:login": "pulse",model: "pulse",channels: "pulse",+ connect: "pulse",deploy: "spinner",});});@@ -321,6 +326,44 @@ describe("runTuiSetupCommand", () => {});});+ it.each([+ [+ "configured",+ { kind: "done", addedConnections: ["linear", "notion"] },+ "Connections added: linear, notion.",+ { kind: "connection-added" },+ ],+ [+ "empty",+ { kind: "done", addedConnections: [] },+ "No connections added.",+ { kind: "model-access-changed" },+ ],+ ["cancelled", { kind: "cancelled" }, "/connect cancelled.", { kind: "model-access-changed" }],+ [+ "partially failed",+ { kind: "failed", addedConnections: ["linear"], message: "install failed" },+ "Connection files changed, but /connect failed: install failed",+ { kind: "connection-added" },+ ],+ [+ "failed before a connection file was written",+ { kind: "failed", addedConnections: [], message: "connector setup failed" },+ "/connect failed: connector setup failed",+ { kind: "model-access-changed" },+ ],+ ] as const)("reports %s connection flows", async (_case, result, message, effect) => {+ const runConnectionsFlow = vi.fn(async () => result);+ await expect(+ run({ command: "connect", flows: fakeFlows({ runConnectionsFlow }) }),+ ).resolves.toEqual({+ message,+ preserveFlowDiagnostics: true,+ effect,+ });+ expect(runConnectionsFlow).toHaveBeenCalledWith(expect.objectContaining({ appRoot: APP_ROOT }));+ });+it("keeps deploy pending when channel files landed before a sub-flow failure", async () => {const flows = fakeFlows({runChannelsFlow: vi.fn<TuiSetupFlows["runChannelsFlow"]>(async () => ({diff --git a/packages/eve/src/cli/dev/tui/setup-commands.ts b/packages/eve/src/cli/dev/tui/setup-commands.tsindex c62c8d99f..3a2dc2e78 100644--- a/packages/eve/src/cli/dev/tui/setup-commands.ts+++ b/packages/eve/src/cli/dev/tui/setup-commands.ts@@ -1,5 +1,6 @@import { HumanActionRequiredError } from "#setup/human-action.js";import { runChannelsFlow } from "#setup/flows/channels.js";+import { runConnectionsFlow } from "#setup/flows/connections.js";import { runDeployFlow } from "#setup/flows/deploy.js";import {runInstallVercelCliFlow,@@ -30,6 +31,7 @@ export const SETUP_FLOW_CONFIG = {"vc:login": { title: "Log in to Vercel", indicator: "pulse" },model: { title: "Configure the agent model", indicator: "pulse" },channels: { title: "Agent channels", indicator: "pulse" },+ connect: { title: "Agent connections", indicator: "pulse" },deploy: { title: "Deploy to Vercel", indicator: "spinner" },} satisfies Record<TuiSetupCommand, { title: string; indicator: SetupFlowIndicator }>;@@ -59,6 +61,7 @@ export interface TuiSetupFlows {runLoginFlow: typeof runLoginFlow;runModelFlow: typeof runModelFlow;runChannelsFlow: typeof runChannelsFlow;+ runConnectionsFlow: typeof runConnectionsFlow;runDeployFlow: typeof runDeployFlow;}@@ -67,7 +70,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 | { kind: "connection-added" } | { kind: "model-access-changed" };}/**@@ -108,7 +111,7 @@ function muteableRenderer(}/**- * Runs one TUI setup command (/model, /channels, /deploy) over the+ * Runs one TUI setup command (/model, /channels, /connect, /deploy) over the* shared setup flows, asking through the TUI's own bordered panel. Never throws:* every outcome — done, cancelled, failed — folds into the returned command* result. Ctrl-C or Esc on the working indicator (no question open) aborts the@@ -158,6 +161,7 @@ async function executeSetupCommand(runLoginFlow,runModelFlow,runChannelsFlow,+ runConnectionsFlow,runDeployFlow,...input.flows,};@@ -235,6 +239,41 @@ async function executeSetupCommand(};}}+ case "connect": {+ const result = await flows.runConnectionsFlow({ appRoot, prompter, signal });+ switch (result.kind) {+ case "cancelled":+ return {+ message: "/connect cancelled.",+ preserveFlowDiagnostics: true,+ effect: { kind: "model-access-changed" },+ };+ case "failed":+ return {+ message:+ result.addedConnections.length === 0+ ? `/connect failed: ${result.message}`+ : `Connection files changed, but /connect failed: ${result.message}`,+ preserveFlowDiagnostics: true,+ effect:+ result.addedConnections.length === 0+ ? { kind: "model-access-changed" }+ : { kind: "connection-added" },+ };+ case "done":+ return {+ message:+ result.addedConnections.length === 0+ ? "No connections added."+ : `Connections added: ${result.addedConnections.join(", ")}.`,+ preserveFlowDiagnostics: true,+ effect:+ result.addedConnections.length === 0+ ? { kind: "model-access-changed" }+ : { kind: "connection-added" },+ };+ }+ }case "deploy": {const result = await flows.runDeployFlow({ appRoot, prompter, interactive: true, signal });if (result.kind === "cancelled") {diff --git a/packages/eve/src/cli/dev/tui/setup-flow.ts b/packages/eve/src/cli/dev/tui/setup-flow.tsindex be8d93b33..affbf616a 100644--- a/packages/eve/src/cli/dev/tui/setup-flow.ts+++ b/packages/eve/src/cli/dev/tui/setup-flow.ts@@ -12,6 +12,9 @@ export type SetupEditableSelectResult =/** Animation shown while a setup flow is between questions. */export type SetupFlowIndicator = "spinner" | "pulse";+/** Ephemeral setup status, with external user action distinct from background work. */+export type SetupFlowStatus = string | { kind: "external-action"; text: string; emphasis: string };+interface SetupSelectRequestBase {message: string;options: readonly SetupPanelOption[];@@ -29,6 +32,7 @@ interface SetupSearchAction extends SearchActionOption {interface SetupSearchSelectRequest extends SetupSelectRequestBase {kind: "search";+ layout?: "task-list";initialValue?: string;placeholder?: string;searchAction?: SetupSearchAction;@@ -92,7 +96,7 @@ export interface SetupFlowRenderer {* whichever settles first wins.*/readChoice(options: ChannelSetupChoiceOptions): ChannelSetupChoice;- setStatus(text: string | undefined): void;+ setStatus(status: SetupFlowStatus | undefined): void;renderLine(text: string, tone: "info" | "success" | "warning" | "error"): void;renderOutput(text: string): void;/**diff --git a/packages/eve/src/cli/dev/tui/setup-panel.test.ts b/packages/eve/src/cli/dev/tui/setup-panel.test.tsindex db39d6289..58e859540 100644--- a/packages/eve/src/cli/dev/tui/setup-panel.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-panel.test.ts@@ -73,7 +73,11 @@ describe("renderFlowPanel", () => {lines: [],content: {kind: "status",- status: { text: "Loading teams…", indicator: { glyph: "⠼", color: "yellow" } },+ status: {+ kind: "progress",+ text: "Loading teams…",+ indicator: { glyph: "⠼", color: "yellow" },+ },},},theme,@@ -91,6 +95,7 @@ describe("renderFlowPanel", () => {content: {kind: "status",status: {+ kind: "progress",text: "Checking the project…",indicator: { glyph: "▪", color: "green" },},@@ -112,6 +117,7 @@ describe("renderFlowPanel", () => {content: {kind: "question",status: {+ kind: "progress",text: "Creating a Slackbot through Vercel Connect…",indicator: { glyph: "▪", color: "green" },},@@ -241,11 +247,12 @@ describe("renderSelectQuestion", () => {focusHint: "Already installed",},{ value: "slack", label: "Slack", hint: "Creates slackbot and deploys to Vercel" },- { value: "done", label: "Done" },+ { value: "done", label: "Done", trailingAction: true },];const rows = renderSelectQuestion({- kind: "task-list",+ kind: "search",+ layout: "task-list",message: "Where will you chat with your agent?",options,notices: [@@ -263,16 +270,19 @@ describe("renderSelectQuestion", () => {expect(rows).not.toContain(" ✓ Terminal UI");// An unfocused completed row keeps its check.expect(rows).toContain(" ✓ Web Chat");- expect(rows).toContain(" ◦ Slack · Creates slackbot and deploys to Vercel");expect(rows).toContain(" Done");- expect(rows).toContain(" ⚠ Overwrote /tmp/weather-agent");- expect(rows).toContain(" ✓ Scaffolded channel: web");- expect(rows.indexOf(" Done")).toBeLessThan(- rows.indexOf(" ⚠ Overwrote /tmp/weather-agent"),- );+ 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(+ warning,+ );+ expect(warning).toBeLessThan(success);+ expect(success).toBeLessThan(done);+ expect([rows[warning - 1], rows[done - 1]]).toEqual(["", ""]);expect(rows.at(-1)).toContain("↑/↓ move · enter to select · esc to cancel");- const coloredRow = renderSelectQuestion(+ const coloredRows = renderSelectQuestion({kind: "task-list",message: "Where will you chat with your agent?",@@ -281,7 +291,8 @@ describe("renderSelectQuestion", () => {},colorTheme,80,- ).find((row) => row.includes("Terminal UI"));+ );+ 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[2mTerminal UI\x1b[22m");diff --git a/packages/eve/src/cli/dev/tui/setup-panel.ts b/packages/eve/src/cli/dev/tui/setup-panel.tsindex 34ea52661..102cb8200 100644--- a/packages/eve/src/cli/dev/tui/setup-panel.ts+++ b/packages/eve/src/cli/dev/tui/setup-panel.ts@@ -94,7 +94,11 @@ interface SetupInlineEditRow {*/type SetupOptionSelectPanelState =| (SetupSelectPanelBase & { kind: "single" })- | (SetupSelectPanelBase & { kind: "search"; placeholder?: string })+ | (SetupSelectPanelBase & {+ kind: "search";+ layout?: "task-list";+ placeholder?: string;+ })| (SetupSelectPanelBase & { kind: "multi" })| (SetupSelectPanelBase & { kind: "searchable-multi"; placeholder?: string })| (SetupSelectPanelBase & { kind: "stacked" })@@ -149,16 +153,26 @@ export interface FlowPanelIndicator {color: "green" | "yellow";}+/** One live flow status after its animation frame and visual intent are resolved. */+export type FlowPanelStatus =+ | { kind: "progress"; text: string; indicator: FlowPanelIndicator }+ | {+ kind: "external-action";+ text: string;+ emphasis: string;+ indicator: FlowPanelIndicator;+ };+export type FlowPanelContent =| {kind: "question";rows: readonly string[];/** The install wait keeps its indicator above the concurrent actions. */- status?: { text: string; indicator: FlowPanelIndicator };+ status?: FlowPanelStatus;}| {kind: "status";- status: { text: string; indicator: FlowPanelIndicator };+ status: FlowPanelStatus;/** Latest child-process output shown transiently beneath the status. */preview?: string;}@@ -228,6 +242,21 @@ function renderIndicator(indicator: FlowPanelIndicator, theme: Theme): string {: theme.colors.yellow(indicator.glyph);}+function renderStatusText(status: FlowPanelStatus, theme: Theme): string {+ if (status.kind === "progress") return theme.colors.dim(status.text);++ const start = status.text.indexOf(status.emphasis);+ if (start === -1) return theme.colors.dim(status.text);+ const end = start + status.emphasis.length;+ return `${theme.colors.dim(status.text.slice(0, start))}${theme.colors.yellow(+ status.text.slice(start, end),+ )}${theme.colors.dim(status.text.slice(end))}`;+}++function renderFlowPanelStatus(status: FlowPanelStatus, theme: Theme): string {+ return `${renderIndicator(status.indicator, theme)} ${renderStatusText(status, theme)}`;+}+/*** Paints the bordered flow panel. Everything a running command produces lives* here — progress, questions, the status indicator — and the panel vanishes@@ -255,17 +284,12 @@ export function renderFlowPanel(state: FlowPanelState, theme: Theme, width: numbcase "question":// The install wait's question rides beneath its live status indicator.if (state.content.status !== undefined) {- rows.push(- ` ${renderIndicator(state.content.status.indicator, theme)} ${c.dim(state.content.status.text)}`,- "",- );+ rows.push(` ${renderFlowPanelStatus(state.content.status, theme)}`, "");}rows.push(...state.content.rows);break;case "status":- rows.push(- ` ${renderIndicator(state.content.status.indicator, theme)} ${c.dim(state.content.status.text)}`,- );+ rows.push(` ${renderFlowPanelStatus(state.content.status, theme)}`);if (state.content.preview !== undefined) {rows.push(` ${c.dim(state.content.preview)}`);}@@ -335,7 +359,7 @@ function selectPresentation(state: SetupOptionSelectPanelState): SelectPresentatreturn {selection: "single",filter: { placeholder: state.placeholder },- layout: "plain",+ layout: state.layout ?? "plain",edit: undefined,};case "multi":@@ -494,13 +518,10 @@ function optionWithoutStackedHint(function optionUsesPlaceholder(presentation: SelectPresentation,- index: number,- optionCount: number,+ isTrailingTaskAction: boolean,): boolean {// A type-ahead list draws no placeholder dots — the filter row leads instead.- const isFiltered = presentation.filter !== undefined;- // The task list's trailing action (Done) reads as a button, not an option.- const isTrailingTaskAction = presentation.layout === "task-list" && index === optionCount - 1;+ const isFiltered = presentation.filter !== undefined && presentation.layout !== "task-list";// Checklists and the explicit menu layouts (stacked, task-list) present every// row as a pickable option, so each carries the placeholder dot.const isMultiSelect = presentation.selection === "multiple";@@ -520,7 +541,7 @@ function appendSelectOptionRows(input: {visibleLabelWidth: number;width: number;theme: Theme;-}): void {+}): boolean {const {rows,state,@@ -534,11 +555,18 @@ function appendSelectOptionRows(input: {theme,} = input;const c = theme.colors;+ let renderedTrailingTaskAction = false;for (let index = start; index < end; index += 1) {const option = visible[index]!;const isCursor = index === cursor;- if (presentation.layout === "task-list" && index === end - 1 && index > start) {+ const isTrailingTaskAction =+ presentation.layout === "task-list" && option.trailingAction === true;+ if (isTrailingTaskAction) {+ appendSelectNotices(rows, state.notices, presentation.layout, theme, width);+ renderedTrailingTaskAction = true;+ }+ if (isTrailingTaskAction && (index > start || (state.notices?.length ?? 0) > 0)) {rows.push("");}@@ -556,7 +584,7 @@ function appendSelectOptionRows(input: {option: rowOption,isCursor,isChecked: presentation.selection === "multiple" && state.select.selected.has(option.value),- placeholder: optionUsesPlaceholder(presentation, index, visible.length),+ placeholder: optionUsesPlaceholder(presentation, isTrailingTaskAction),hintPadding: Math.max(0, visibleLabelWidth - rowOption.label.length),theme,})}`,@@ -591,6 +619,7 @@ function appendSelectOptionRows(input: {}if (presentation.layout === "stacked" && index < end - 1) rows.push("");}+ return renderedTrailingTaskAction;}function appendSubmitRow(rows: string[], cursor: number, submitIndex: number, theme: Theme): void {@@ -739,7 +768,7 @@ export function renderSelectQuestion(rows.push(` ${c.dim("(no matches)")}`);}- appendSelectOptionRows({+ const renderedTrailingTaskAction = appendSelectOptionRows({rows,state,presentation,@@ -757,7 +786,9 @@ export function renderSelectQuestion(rows.push(` ${c.dim(`↑↓ ${visible.length} options, showing ${start + 1}–${end}`)}`);}- appendSelectNotices(rows, state.notices, presentation.layout, theme, width);+ if (!renderedTrailingTaskAction) {+ appendSelectNotices(rows, state.notices, presentation.layout, theme, width);+ }if (state.error !== undefined) {rows.push("", ` ${c.red(state.error)}`);diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.tsindex 6ec11b6de..0024a8fed 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts@@ -271,6 +271,29 @@ describe("TerminalRenderer (inline scrollback)", () => {renderer.shutdown();});+ it("keeps the authorization wait status while consuming a callback stream", async () => {+ const { screen, renderer } = makeRenderer();+ renderer.setConnectionAuthPendingCount(1);+ let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;+ const rendering = renderer.renderStream(+ {+ events: new ReadableStream<AgentTUIStreamEvent>({+ start(controller) {+ streamController = controller;+ },+ }),+ },+ { continueSession: true },+ );++ await Promise.resolve();+ expect(screen.snapshot()).toContain("Waiting for connection authorization…");++ streamController?.close();+ await rendering;+ renderer.shutdown();+ });+it("uses the turn pulse while waiting for the first stream event", async () => {vi.useFakeTimers();try {@@ -586,6 +609,45 @@ describe("TerminalRenderer (inline scrollback)", () => {expect(snapshot).toContain("✓ bash");});+ it("settles an authorization block when its callback arrives in a later stream pass", async () => {+ const { screen, renderer } = makeRenderer();+ renderer.renderAgentHeader({ name: "Weather Agent", serverUrl: "http://localhost:3000" });+ renderer.upsertConnectionAuth({+ name: "linear",+ description: "Authorization required for linear",+ state: "required",+ challenge: { url: "https://connect.vercel.com/authorize/linear" },+ });++ await renderer.renderStream(streamOf([{ type: "finish" }]), { continueSession: true });++ renderer.upsertConnectionAuth({+ name: "linear",+ description: "Authorization required for linear",+ state: "pending",+ challenge: { url: "https://connect.vercel.com/authorize/linear" },+ });+ expect(screen.snapshot()).toContain("linear · authorization · pending");++ await renderer.renderStream(streamOf([{ type: "finish" }]), { continueSession: true });++ renderer.upsertConnectionAuth({+ name: "linear",+ description: "Authorization required for linear",+ state: "authorized",+ challenge: { url: "https://connect.vercel.com/authorize/linear" },+ });+ renderer.shutdown();++ const snapshot = screen.snapshot();+ expect(snapshot).toContain("linear · authorization · authorized");+ expect(snapshot).toContain("Authorization complete");+ expect(snapshot).not.toContain("linear · authorization · required");+ expect(snapshot).not.toContain("linear · authorization · pending");+ expect(snapshot).not.toContain("Authorization required for linear");+ expect(snapshot).not.toContain("https://connect.vercel.com/authorize/linear");+ });+it("does not commit partial live assistant rows while streaming over the viewport", async () => {const { screen, renderer } = makeRenderer(34, 8);const words = Array.from(@@ -2030,6 +2092,21 @@ describe("TerminalRenderer setup flow session", () => {}});+ it("uses the attention color for an external-action pulse", () => {+ const { screen, renderer } = makeRenderer();++ renderer.setupFlow.begin("Agent connections", "pulse");+ renderer.setupFlow.setStatus({+ kind: "external-action",+ text: "Waiting for you to complete setup in the browser…",+ emphasis: "browser",+ });++ expect(screen.rawOutput()).toContain("\x1b[33m▪\x1b[39m");+ expect(screen.rawOutput()).toContain("\x1b[33mbrowser\x1b[39m");+ renderer.shutdown();+ });+it("uses an ASCII fallback for pulse setup flows", () => {const screen = new MockScreen({ columns: 80, rows: 30 });const input = new MockUserInput();@@ -2131,7 +2208,7 @@ describe("TerminalRenderer setup flow session", () => {focusHint: "Already installed",},{ value: "slack", label: "Slack", hint: "Creates slackbot and deploys to Vercel" },- { value: "done", label: "Done" },+ { value: "done", label: "Done", trailingAction: true },];renderer.setupFlow.begin("Agent channels");@@ -2150,7 +2227,8 @@ describe("TerminalRenderer setup flow session", () => {"warning",);const second = renderer.setupFlow.readSelect({- kind: "task-list",+ kind: "search",+ layout: "task-list",message: "Where will you chat with your agent?",options,});@@ -2177,11 +2255,6 @@ describe("TerminalRenderer setup flow session", () => {expect(snapshot).not.toContain("✓ Terminal UI");expect(snapshot).toContain("✓ Web Chat");expect(snapshot).toContain("Slack · Creates slackbot and deploys to Vercel");- expect(snapshot.indexOf("Done")).toBeLessThan(snapshot.indexOf("Overwrote /tmp/weather-agent"));- expect(snapshot.indexOf("Overwrote /tmp/weather-agent")).toBeLessThan(- snapshot.indexOf("Scaffolded channel: web"),- );- expect(snapshot.indexOf("Scaffolded channel: web")).toBeLessThan(snapshot.indexOf("↑/↓ move"));expect(snapshot).toContain("Dependency installation failed.");input.send("\x1b");@@ -2202,7 +2275,7 @@ describe("TerminalRenderer setup flow session", () => {completed: true,focusHint: "Already installed",},- { value: "done", label: "Done" },+ { value: "done", label: "Done", trailingAction: true },],});let settled = false;diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.tsindex 8f206d1a3..9c4edf5e9 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts@@ -41,6 +41,7 @@ import {type FlowPanelContent,type FlowPanelIndicator,type FlowPanelLine,+ type FlowPanelStatus,type SetupPanelOption,type SetupSelectPanelState,} from "./setup-panel.js";@@ -48,6 +49,7 @@ import type {SetupEditableSelectResult,SetupFlowIndicator,SetupFlowRenderer,+ SetupFlowStatus,SetupSelectRequest,} from "./setup-flow.js";import type { SelectNotice } from "#setup/prompter.js";@@ -177,6 +179,10 @@ function completedTurnStatus(interrupted: boolean, continueSession: boolean): sttype SetupFlowIndicatorState = { kind: "spinner" } | { kind: "pulse"; startedAtMs: number };+type SetupFlowStatusState =+ | { kind: "progress"; text: string }+ | { kind: "external-action"; text: string; emphasis: string };+type TurnIndicatorState =| { kind: "idle" }| { kind: "waiting"; startedAtMs: number }@@ -186,7 +192,7 @@ type SetupFlowState = {title: string;indicator: SetupFlowIndicatorState;lines: FlowPanelLine[];- status?: string;+ status?: SetupFlowStatusState;/** Latest subprocess output line; replaced per write, never persisted. */preview?: string;/** Recent subprocess output, flushed as context when a warning settles it. */@@ -641,7 +647,7 @@ export class TerminalRenderer implements AgentTUIRenderer {if (this.#turnIndicator.kind !== "waiting") {this.#turnIndicator = { kind: "waiting", startedAtMs: Date.now() };}- this.#status = STATUS.processing;+ this.#status = this.#connectionAuthPendingCount > 0 ? STATUS.connectionAuth : STATUS.processing;this.#addSubmittedPrompt(options?.submittedPrompt);this.#interrupted = false;this.#totalTokens = undefined;@@ -1007,18 +1013,14 @@ export class TerminalRenderer implements AgentTUIRenderer {upsertConnectionAuth(update: ConnectionAuthUpdate): void {if (this.#connectionAuth === "hidden") return;- const isTerminal =- update.state === "authorized" ||- update.state === "declined" ||- update.state === "failed" ||- update.state === "timed-out";+ const terminalMessage = connectionAuthTerminalMessage(update.state);this.#upsertBlock({id: connectionAuthSectionId(update.name),kind: "connection-auth",title: `${stripTerminalControls(update.name)} · authorization · ${update.state}`,- body: formatConnectionAuthContent(update),+ body: formatConnectionAuthContent(update, terminalMessage),preformatted: true,- live: !isTerminal,+ live: terminalMessage === undefined,});this.#paint();}@@ -1297,7 +1299,7 @@ export class TerminalRenderer implements AgentTUIRenderer {};let notices = opts.notices;- if (opts.kind === "task-list") {+ if (opts.kind === "task-list" || (opts.kind === "search" && opts.layout === "task-list")) {const start = flow.taskListLineStart ?? flow.lines.length;const outcomes: SelectNotice[] = flow.lines.slice(start)@@ -1381,7 +1383,7 @@ export class TerminalRenderer implements AgentTUIRenderer {): ReturnType<SetupFlowRenderer["readChoice"]> {this.#start();const flow = this.#requireSetupFlow();- flow.status = opts.status;+ flow.status = { kind: "progress", text: stripTerminalControls(opts.status) };// No action is pre-selected: the user must move into the action group before// Enter can act, rather than firing "Try again" by reflex.let cursor: number | undefined;@@ -1901,8 +1903,17 @@ export class TerminalRenderer implements AgentTUIRenderer {* status into the working indicator; `undefined` clears it. Nothing is ever* committed to the transcript.*/- #setFlowStatus(text: string | undefined): void {- const content = text === undefined ? undefined : stripTerminalControls(text);+ #setFlowStatus(status: SetupFlowStatus | undefined): void {+ const content: SetupFlowStatusState | undefined =+ status === undefined+ ? undefined+ : typeof status === "string"+ ? { kind: "progress", text: stripTerminalControls(status) }+ : {+ kind: "external-action",+ text: stripTerminalControls(status.text),+ emphasis: stripTerminalControls(status.emphasis),+ };if (this.#setupFlow !== undefined) {this.#setupFlow.status = content;if (content === undefined) this.#setupFlow.preview = undefined;@@ -1918,7 +1929,7 @@ export class TerminalRenderer implements AgentTUIRenderer {}this.#start();this.#startWorking();- this.#status = content;+ this.#status = content.text;this.#paint();}@@ -2262,10 +2273,16 @@ export class TerminalRenderer implements AgentTUIRenderer {#finalizeAllBlocks() {for (const block of this.#blocks) {- // Blocks awaiting an approval decision or action.result stay live past- // the end of the stream. Committing them here would freeze the pending- // glyph into scrollback before the later decision/result can settle it.- if (block.status === "approval" || block.status === "running") continue;+ // Blocks awaiting an approval decision, action.result, or OAuth callback+ // stay live past this stream boundary so their later terminal update can+ // replace the same transcript block.+ if (+ block.status === "approval" ||+ block.status === "running" ||+ (block.kind === "connection-auth" && block.live)+ ) {+ continue;+ }block.live = false;}}@@ -2675,7 +2692,7 @@ export class TerminalRenderer implements AgentTUIRenderer {return isProgressPulseVisible(Date.now() - startedAtMs) ? glyph : " ";}- #setupFlowIndicator(flow: SetupFlowState): FlowPanelIndicator {+ #setupFlowIndicator(flow: SetupFlowState, status?: SetupFlowStatusState): FlowPanelIndicator {if (flow.indicator.kind === "spinner") {return { glyph: this.#spinnerFrame(), color: "yellow" };}@@ -2684,7 +2701,7 @@ export class TerminalRenderer implements AgentTUIRenderer {flow.indicator.startedAtMs,this.#theme.unicode ? PROGRESS_PULSE_GLYPH : PROGRESS_PULSE_ASCII_GLYPH,),- color: "green",+ color: status?.kind === "external-action" ? "yellow" : "green",};}@@ -2698,7 +2715,9 @@ export class TerminalRenderer implements AgentTUIRenderer {// very state the line shows (link, pending deploy, model), so mid-flow// values are guaranteed stale; it reappears, refreshed, when the// panel closes.- const indicator = this.#setupFlowIndicator(flow);+ const indicator = this.#setupFlowIndicator(flow, flow.status);+ const status: FlowPanelStatus | undefined =+ flow.status === undefined ? undefined : { ...flow.status, indicator };let content: FlowPanelContent;// A live status indicator rides alongside an open question only when one is// explicitly set (the install wait); ordinary questions leave it cleared,@@ -2706,15 +2725,15 @@ export class TerminalRenderer implements AgentTUIRenderer {if (flow.question !== undefined) {const rows = flow.question(width);content = { kind: "question", rows };- if (flow.status !== undefined) {- content = { kind: "question", rows, status: { text: flow.status, indicator } };+ if (status !== undefined) {+ content = { kind: "question", rows, status };}- } else if (flow.status !== undefined) {- content = { kind: "status", status: { text: flow.status, indicator } };+ } else if (status !== undefined) {+ content = { kind: "status", status };if (flow.preview !== undefined) {content = {kind: "status",- status: { text: flow.status, indicator },+ status,preview: flow.preview,};}@@ -3403,15 +3422,38 @@ function connectionAuthSectionId(connectionName: string): string {return `connection-auth:${connectionName}`;}-function formatConnectionAuthContent(update: ConnectionAuthUpdate): string {+function connectionAuthTerminalMessage(state: ConnectionAuthUpdate["state"]): string | undefined {+ switch (state) {+ case "authorized":+ return "Authorization complete";+ case "declined":+ return "Authorization declined";+ case "failed":+ return "Authorization failed";+ case "timed-out":+ return "Authorization timed out";+ case "required":+ case "pending":+ return undefined;+ }+}++function formatConnectionAuthContent(+ update: ConnectionAuthUpdate,+ terminalMessage: string | undefined,+): string {const lines: string[] = [];- const description = stripTerminalControls(update.description);- if (description.length > 0) lines.push(description);- const challenge = update.challenge;- if (challenge?.url) lines.push(`URL: ${stripTerminalControls(challenge.url)}`);- if (challenge?.userCode) lines.push(`Code: ${stripTerminalControls(challenge.userCode)}`);- if (challenge?.expiresAt) lines.push(`Expires: ${stripTerminalControls(challenge.expiresAt)}`);- if (challenge?.instructions) lines.push(stripTerminalControls(challenge.instructions));+ if (terminalMessage !== undefined) {+ lines.push(terminalMessage);+ } else {+ const description = stripTerminalControls(update.description);+ if (description.length > 0) lines.push(description);+ const challenge = update.challenge;+ if (challenge?.url) lines.push(`URL: ${stripTerminalControls(challenge.url)}`);+ if (challenge?.userCode) lines.push(`Code: ${stripTerminalControls(challenge.userCode)}`);+ if (challenge?.expiresAt) lines.push(`Expires: ${stripTerminalControls(challenge.expiresAt)}`);+ if (challenge?.instructions) lines.push(stripTerminalControls(challenge.instructions));+ }if (update.reason !== undefined) {const reason = stripTerminalControls(update.reason);if (reason.length > 0) lines.push(`Reason: ${reason}`);diff --git a/packages/eve/src/cli/dev/tui/tui-prompter.test.ts b/packages/eve/src/cli/dev/tui/tui-prompter.test.tsindex 38c92de00..d14ffe69e 100644--- a/packages/eve/src/cli/dev/tui/tui-prompter.test.ts+++ b/packages/eve/src/cli/dev/tui/tui-prompter.test.ts@@ -48,6 +48,7 @@ describe("createTuiPrompter", () => {prompter.select({message: "Project to link",search: true,+ hintLayout: "inline",searchAction: {label: (query) => `Search for '${query}'`,value: (query) => `search:${query}`,@@ -58,6 +59,7 @@ describe("createTuiPrompter", () => {expect(renderer.readSelect).toHaveBeenCalledWith(expect.objectContaining({kind: "search",+ layout: "task-list",searchAction: { label: expect.any(Function) },}),);diff --git a/packages/eve/src/cli/dev/tui/tui-prompter.ts b/packages/eve/src/cli/dev/tui/tui-prompter.tsindex 8d1e789f2..f231b3880 100644--- a/packages/eve/src/cli/dev/tui/tui-prompter.ts+++ b/packages/eve/src/cli/dev/tui/tui-prompter.ts@@ -9,6 +9,7 @@ import type {} from "#setup/prompter.js";import { createSelectOptionCodec } from "#setup/cli/select-option-codec.js";import { searchActionQuery } from "#setup/cli/select-state.js";+import type { SetupSpinnerIntent } from "#setup/cli/index.js";import { WizardCancelledError } from "#setup/step.js";import type { SetupFlowPrompterRenderer, SetupSelectRequest } from "./setup-flow.js";@@ -59,13 +60,14 @@ function setupSelectRequest<T extends PrompterValue>(return withNotices(request);}- if (opts.search === true && opts.hintLayout !== undefined) {- throw new Error("Searchable setup questions do not support a hint layout.");+ if (opts.search === true && opts.hintLayout === "stacked") {+ throw new Error("Searchable setup questions do not support a stacked hint layout.");}let request: SetupSelectRequest;if (opts.search === true) {request = { ...base, kind: "search" };+ if (opts.hintLayout === "inline") request.layout = "task-list";if (opts.placeholder !== undefined) request.placeholder = opts.placeholder;if (opts.searchAction !== undefined) {request.searchAction = { label: opts.searchAction.label };@@ -205,8 +207,12 @@ export function createTuiPrompter(renderer: TuiPrompterRenderer): Prompter {renderer.renderLine(title, "info");for (const entry of lines) renderer.renderLine(` ${entry}`, "info");},- spinner(message) {- renderer.setStatus(message);+ spinner(message, intent?: SetupSpinnerIntent) {+ renderer.setStatus(+ intent?.kind === "external-action"+ ? { kind: "external-action", text: message, emphasis: intent.emphasis }+ : message,+ );let stopped = false;return {stop() {diff --git a/packages/eve/src/cli/dev/tui/tui.ts b/packages/eve/src/cli/dev/tui/tui.tsindex 6e21882ce..ff0dd595f 100644--- a/packages/eve/src/cli/dev/tui/tui.ts+++ b/packages/eve/src/cli/dev/tui/tui.ts@@ -1,11 +1,14 @@import { Client } from "#client/index.js";import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";import {- resolveDevelopmentClientOptions,+ resolveLocalDevelopmentClientOptions,resolveRemoteDevelopmentClientOptions,} from "#services/dev-client/client-options.js";import { createDevelopmentCredentialGate } from "#services/dev-client/credential-gate.js";-import { resolveDevelopmentOidcToken } from "#services/dev-client/request-headers.js";+import {+ resolveDevelopmentOidcToken,+ resolveLinkedDevelopmentOidcToken,+} from "#services/dev-client/request-headers.js";import { isVercelAuthChallenge } from "#services/dev-client/vercel-auth-error.js";import { resolveVercelDeployment } from "#setup/vercel-deployment.js";import { toErrorMessage } from "#shared/errors.js";@@ -80,7 +83,10 @@ export async function runDevelopmentTui(input: RunDevelopmentTuiInput): Promise<const client = new Client(prepared.kind === "local"- ? resolveDevelopmentClientOptions(serverUrl)+ ? resolveLocalDevelopmentClientOptions({+ serverUrl,+ token: () => resolveLinkedDevelopmentOidcToken(prepared.target.workspaceRoot),+ }): resolveRemoteDevelopmentClientOptions({serverUrl,credentials: prepared.remote.credentials,diff --git a/packages/eve/src/cli/dev/ui-options.ts b/packages/eve/src/cli/dev/ui-options.tsnew file mode 100644index 000000000..920a58ee2--- /dev/null+++ b/packages/eve/src/cli/dev/ui-options.ts@@ -0,0 +1,46 @@+import type {+ AssistantResponseStatsMode,+ LogDisplayMode,+ TerminalPartDisplayMode,+ TuiDisplayOptions,+} from "#cli/dev/tui/types.js";++/** Parsed `eve dev` options that control terminal-UI behavior. */+export interface DevelopmentTuiOptions {+ readonly assistantResponseStats?: AssistantResponseStatsMode;+ readonly connectionAuth?: TerminalPartDisplayMode;+ readonly contextSize?: number;+ readonly logs?: LogDisplayMode;+ readonly reasoning?: TerminalPartDisplayMode;+ readonly subagents?: TerminalPartDisplayMode;+ readonly tools?: TerminalPartDisplayMode;+ readonly ui?: boolean;+}++/** Whether `eve dev` launches the terminal UI or keeps only the server running. */+export type DevUiMode = "tui" | "headless";++/** Resolves the UI mode from parsed flags and terminal interactivity. */+export function resolveDevUiMode(input: {+ readonly options: Pick<DevelopmentTuiOptions, "ui">;+ readonly interactive: boolean;+}): DevUiMode {+ return input.options.ui === false || !input.interactive ? "headless" : "tui";+}++/** Builds terminal-UI display options with the defaults used by `eve dev`. */+export function resolveTuiDisplayOptions(options: DevelopmentTuiOptions): TuiDisplayOptions {+ const display: TuiDisplayOptions = {+ logs: options.logs ?? "stderr",+ reasoning: options.reasoning ?? "full",+ tools: options.tools ?? "auto-collapsed",+ };++ if (options.subagents !== undefined) display.subagents = options.subagents;+ if (options.connectionAuth !== undefined) display.connectionAuth = options.connectionAuth;+ if (options.assistantResponseStats !== undefined) {+ display.assistantResponseStats = options.assistantResponseStats;+ }+ if (options.contextSize !== undefined) display.contextSize = options.contextSize;+ return display;+}diff --git a/packages/eve/src/cli/run.test.ts b/packages/eve/src/cli/run.test.tsindex 47922424c..2ad5cf86a 100644--- a/packages/eve/src/cli/run.test.ts+++ b/packages/eve/src/cli/run.test.ts@@ -128,6 +128,56 @@ describe("eve dev --input", () => {});describe("eve dev --url protocol", () => {+ it("uses the local TUI credential path only for this app's running dev server", async () => {+ const runDevelopmentTui = vi.fn(async () => {});++ await withInteractiveTerminal(() =>+ runCli(+ ["dev", "--url", "http://127.0.0.1:2000"],+ { error: () => {}, log: () => {} },+ {+ isActiveDevelopmentServerForApp: async () => true,+ runDevelopmentTui,+ },+ ),+ );++ expect(runDevelopmentTui).toHaveBeenCalledWith(+ expect.objectContaining({+ target: {+ kind: "local",+ serverUrl: "http://127.0.0.1:2000/",+ workspaceRoot: process.cwd(),+ },+ }),+ );+ });++ it("keeps an unverified loopback URL on the remote credential path", async () => {+ const runDevelopmentTui = vi.fn(async () => {});++ await withInteractiveTerminal(() =>+ runCli(+ ["dev", "--url", "http://127.0.0.1:2000"],+ { error: () => {}, log: () => {} },+ {+ isActiveDevelopmentServerForApp: async () => false,+ runDevelopmentTui,+ },+ ),+ );++ expect(runDevelopmentTui).toHaveBeenCalledWith(+ expect.objectContaining({+ target: {+ kind: "remote",+ serverUrl: "http://127.0.0.1:2000/",+ workspaceRoot: process.cwd(),+ },+ }),+ );+ });+it("rejects an http:// remote URL up front instead of crashing during connect", async () => {await expect(runCli(["dev", "--url", "http://my-app.vercel.app"], { error: () => {}, log: () => {} }),diff --git a/packages/eve/src/cli/run.ts b/packages/eve/src/cli/run.tsindex 29544413a..dd4e0ddd7 100644--- a/packages/eve/src/cli/run.ts+++ b/packages/eve/src/cli/run.ts@@ -5,6 +5,7 @@ import { resolveInstalledPackageInfo } from "#internal/application/package.js";import { isCodingAgentLaunch } from "#cli/agent-detection.js";import { eveCliBanner } from "#cli/banner.js";import { registerProjectCommands } from "#cli/commands/register-project-commands.js";+import { resolveDevUiMode, resolveTuiDisplayOptions } from "#cli/dev/ui-options.js";import type { RunDevelopmentTuiInput } from "#cli/dev/tui/tui.js";import { LOG_DISPLAY_MODES, parseLogDisplayMode } from "#cli/dev/tui/log-display-mode.js";import { resolveTuiTitle, type DevelopmentTuiTarget } from "#cli/dev/tui/target.js";@@ -21,9 +22,10 @@ import type {AssistantResponseStatsMode,LogDisplayMode,TerminalPartDisplayMode,- TuiDisplayOptions,} from "#cli/dev/tui/types.js";+export { resolveDevUiMode, resolveTuiDisplayOptions };+interface CliLogger {error(message: string): void;log(message: string): void;@@ -52,6 +54,10 @@ interface ProductionCliOptions {interface CliRuntimeDependencies {isCodingAgentLaunch(): Promise<boolean>;+ isActiveDevelopmentServerForApp(input: {+ readonly appRoot: string;+ readonly serverUrl: string;+ }): Promise<boolean>;buildHost(appRoot: string): Promise<string>;printApplicationInfo(logger: CliLogger,@@ -134,6 +140,9 @@ async function loadStartHost(): Promise<CliRuntimeDependencies["startHost"]> {return (await import("#internal/nitro/host.js")).createDevelopmentServer;}+const loadIsActiveDevelopmentServerForApp = async () =>+ (await import("#internal/nitro/host.js")).isActiveDevelopmentServerForApp;+async function loadStartProductionHost(): Promise<CliRuntimeDependencies["startProductionHost"]> {return (await import("#internal/nitro/host.js")).startProductionServer;}@@ -237,54 +246,6 @@ function parseContextSizeOption(value: string): number {return size;}-/**- * The interactive UI `eve dev` runs against a server.- *- * - `tui` — the default terminal UI.- * - `headless` — no UI: just keep the server running (`--no-ui`, or a- * non-interactive terminal).- *- * Exported for unit coverage of the flag-routing contract.- */-export type DevUiMode = "tui" | "headless";--/**- * Resolves which UI `eve dev` should run from the parsed flags and whether- * the terminal is interactive. `--no-ui` and non-TTY terminals force- * `headless`; otherwise the terminal UI runs.- */-export function resolveDevUiMode(input: {- options: Pick<DevelopmentCliOptions, "ui">;- interactive: boolean;-}): DevUiMode {- if (input.options.ui === false || !input.interactive) {- return "headless";- }-- return "tui";-}--/**- * Builds the terminal-UI display options for `eve dev`. Tools default to- * `auto-collapsed`, reasoning to `full`, and stderr logs are visible so- * long-running local sandbox work can report progress.- */-export function resolveTuiDisplayOptions(options: DevelopmentCliOptions): TuiDisplayOptions {- const display: TuiDisplayOptions = {- logs: options.logs ?? "stderr",- reasoning: options.reasoning ?? "full",- tools: options.tools ?? "auto-collapsed",- };-- if (options.subagents !== undefined) display.subagents = options.subagents;- if (options.connectionAuth !== undefined) display.connectionAuth = options.connectionAuth;- if (options.assistantResponseStats !== undefined) {- display.assistantResponseStats = options.assistantResponseStats;- }- if (options.contextSize !== undefined) display.contextSize = options.contextSize;- return display;-}-function hasInteractiveTerminal(): boolean {return Boolean(process.stdin.isTTY && process.stdout.isTTY);}@@ -499,6 +460,12 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Commif (options.input !== undefined && mode === "headless") {throw new InvalidArgumentError("--input requires the interactive UI.");}+ let existingLocalDevelopmentServer = false;+ if (remoteServerUrl !== undefined) {+ const isActive =+ runtime.isActiveDevelopmentServerForApp ?? (await loadIsActiveDevelopmentServerForApp());+ existingLocalDevelopmentServer = await isActive({ appRoot, serverUrl: remoteServerUrl });+ }const runInteractiveUi = async (input: {readonly appRoot?: string;@@ -513,7 +480,7 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm);const display = resolveTuiDisplayOptions(options);const target: DevelopmentTuiTarget =- remoteServerUrl === undefined+ remoteServerUrl === undefined || existingLocalDevelopmentServer? {kind: "local",serverUrl: input.serverUrl,@@ -534,7 +501,9 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Commif (remoteServerUrl) {const { loadDevelopmentEnvironmentFiles } = await import("#cli/dev/environment.js");loadDevelopmentEnvironmentFiles(appRoot);- logger.log(`↗ remote mode targeting ${theme.info(new URL(remoteServerUrl).host)}`);+ logger.log(+ `↗ ${existingLocalDevelopmentServer ? "local" : "remote"} mode targeting ${theme.info(new URL(remoteServerUrl).host)}`,+ );if (mode === "headless") {logger.log(diff --git a/packages/eve/src/client/client.ts b/packages/eve/src/client/client.tsindex 605430386..87aec69b7 100644--- a/packages/eve/src/client/client.ts+++ b/packages/eve/src/client/client.ts@@ -194,8 +194,7 @@ export class Client {// Skip the header entirely on an empty token rather than emitting a// malformed `Bearer ` value the server has to reject. The dev client's// OIDC resolver returns "" when no token is available locally; the- // request then goes out unauthenticated and the framework's- // `vercelOidc()` channel handler returns a clean 401.+ // request then follows the framework channel's local-dev fallback.const token = (await resolveTokenValue(auth.bearer)).trim();return token.length === 0 ? {} : { authorization: `Bearer ${token}` };}diff --git a/packages/eve/src/internal/nitro/host.ts b/packages/eve/src/internal/nitro/host.tsindex 79dd257ae..17028846b 100644--- a/packages/eve/src/internal/nitro/host.ts+++ b/packages/eve/src/internal/nitro/host.ts@@ -1,5 +1,8 @@export { buildApplication } from "#internal/nitro/host/build-application.js";-export { createDevelopmentServer } from "#internal/nitro/host/start-development-server.js";+export {+ createDevelopmentServer,+ isActiveDevelopmentServerForApp,+} from "#internal/nitro/host/start-development-server.js";export { startProductionServer } from "#internal/nitro/host/start-production-server.js";export type {DevelopmentServer,diff --git a/packages/eve/src/internal/nitro/host/configure-nitro-routes.test.ts b/packages/eve/src/internal/nitro/host/configure-nitro-routes.test.tsindex 4376e9477..e87413bc2 100644--- a/packages/eve/src/internal/nitro/host/configure-nitro-routes.test.ts+++ b/packages/eve/src/internal/nitro/host/configure-nitro-routes.test.ts@@ -275,19 +275,14 @@ describe("configureNitroRoutes", () => {method: "GET",route: "/eve/v1/dev/runtime-artifacts",});- expect(devNitro.options.handlers).toContainEqual({- handler: "#eve-route/eve/v1/dev/runtime-artifacts/rebuild",- method: "POST",- route: "/eve/v1/dev/runtime-artifacts/rebuild",- });- expect(prodNitro.options.handlers).not.toContainEqual(+ expect(devNitro.options.handlers).not.toContainEqual(expect.objectContaining({- route: "/eve/v1/dev/runtime-artifacts",+ route: "/eve/v1/dev/runtime-artifacts/rebuild",}),);expect(prodNitro.options.handlers).not.toContainEqual(expect.objectContaining({- route: "/eve/v1/dev/runtime-artifacts/rebuild",+ route: "/eve/v1/dev/runtime-artifacts",}),);});diff --git a/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts b/packages/eve/src/internal/nitro/host/configure-nitro-routes.tsindex 86311928b..1f59aad96 100644--- a/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts+++ b/packages/eve/src/internal/nitro/host/configure-nitro-routes.ts@@ -4,7 +4,6 @@ import { dirname, join, relative } from "node:path";import type { Nitro } from "nitro/types";import {EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,- EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,@@ -377,15 +376,6 @@ export async function configureNitroRoutes(),route: EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,});- addFrameworkVirtualHandler(nitro, {- args: JSON.stringify({ appRoot: artifactsConfig.appRoot }),- handlerExport: "handleDevRuntimeArtifactsRebuildRequest",- method: "POST",- modulePath: resolvePackageSourceFilePath(- "src/internal/nitro/routes/dev-runtime-artifacts.ts",- ),- route: EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH,- });addFrameworkVirtualHandler(nitro, {args: JSON.stringify({ appRoot: artifactsConfig.appRoot }),handlerExport: "handleDevScheduleDispatchRequest",diff --git a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.ts b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.scenario.test.tsindex 0ddb39cbe..8a9a30cb4 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@@ -176,6 +176,27 @@ afterEach(async () => {});describe("startAuthoredSourceWatcher", () => {+ it("rebuilds when a local setup action knows authored source changed", async () => {+ const previousHost = createPreparedHost();+ const nextHost = createPreparedHost();+ const nitroStub = createNitroStub();+ prepareApplicationHostMock.mockResolvedValueOnce(nextHost);++ const watcher = await startAuthoredSourceWatcher({+ nitro: nitroStub.nitro,+ preparedHost: previousHost,+ });++ try {+ await watcher.rebuild();++ expect(prepareApplicationHostMock).toHaveBeenCalledWith(previousHost.appRoot, { dev: true });+ expect(clearCompiledRuntimeAgentBundleCacheMock).toHaveBeenCalledTimes(1);+ } finally {+ await watcher.close();+ }+ });+it("ignores generated output directories while watching authored source roots", async () => {const watcher = await startAuthoredSourceWatcher({nitro: createNitroStub().nitro,diff --git a/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.ts b/packages/eve/src/internal/nitro/host/dev-authored-source-watcher.tsindex 01a12136b..d7d449c14 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@@ -14,7 +14,6 @@ import {} from "#internal/nitro/host/channel-routes.js";import { prepareApplicationHost } from "#internal/nitro/host/prepare-application-host.js";import { resolveNitroCompiledArtifactsSource } from "#internal/nitro/routes/runtime-artifacts.js";-import { registerDevelopmentRebuildHandle } from "#internal/nitro/host/dev-rebuild-registry.js";import type { PreparedApplicationHost } from "#internal/nitro/host/types.js";import {getDevelopmentEnvironmentFilePaths,@@ -72,6 +71,7 @@ interface DevelopmentWatcherNitro {export interface AuthoredSourceWatcherHandle {close(): Promise<void>;flush(): Promise<void>;+ rebuild(): Promise<void>;}/**@@ -104,16 +104,11 @@ export async function startAuthoredSourceWatcher(input: {});const watcherReady = waitForWatcherReady(watcher);- const flush = async () => {+ const rebuild = async (force: boolean) => {if (closed) {return;}- if (debounceTimer !== undefined) {- clearTimeout(debounceTimer);- debounceTimer = undefined;- }-queue = queue.then(async () => {if (closed) {@@ -121,7 +116,7 @@ export async function startAuthoredSourceWatcher(input: {}const changeEvents = [...pendingEvents.values()];- if (changeEvents.length === 0) {+ if (!force && changeEvents.length === 0) {return;}@@ -137,7 +132,9 @@ export async function startAuthoredSourceWatcher(input: {previousHost.appRoot,changedPaths,);- console.log(formatChangeDetectedLogLine(previousHost.appRoot, changeEvents));+ if (changeEvents.length > 0) {+ console.log(formatChangeDetectedLogLine(previousHost.appRoot, changeEvents));+ }try {if (hasEnvironmentChange) {@@ -196,8 +193,20 @@ export async function startAuthoredSourceWatcher(input: {});await queue;};- const unregisterRebuildHandle = registerDevelopmentRebuildHandle(currentHost.appRoot, { flush });-+ const flush = async () => {+ if (debounceTimer !== undefined) {+ clearTimeout(debounceTimer);+ debounceTimer = undefined;+ }+ await rebuild(false);+ };+ const forceRebuild = async () => {+ if (debounceTimer !== undefined) {+ clearTimeout(debounceTimer);+ debounceTimer = undefined;+ }+ await rebuild(true);+ };watcher.on("all", (event, changedPath) => {if (closed || !isWatcherReady) {return;@@ -220,7 +229,6 @@ export async function startAuthoredSourceWatcher(input: {return {async close() {closed = true;- unregisterRebuildHandle();if (debounceTimer !== undefined) {clearTimeout(debounceTimer);@@ -231,6 +239,7 @@ export async function startAuthoredSourceWatcher(input: {await queue;},flush,+ rebuild: forceRebuild,};}diff --git a/packages/eve/src/internal/nitro/host/dev-rebuild-registry.ts b/packages/eve/src/internal/nitro/host/dev-rebuild-registry.tsdeleted file mode 100644index b3cd82499..000000000--- a/packages/eve/src/internal/nitro/host/dev-rebuild-registry.ts+++ /dev/null@@ -1,25 +0,0 @@-import { resolve } from "node:path";--export interface DevelopmentRebuildHandle {- flush(): Promise<void>;-}--const developmentRebuildHandles = new Map<string, DevelopmentRebuildHandle>();--export function registerDevelopmentRebuildHandle(- appRoot: string,- handle: DevelopmentRebuildHandle,-): () => void {- const key = resolve(appRoot);- developmentRebuildHandles.set(key, handle);-- return () => {- if (developmentRebuildHandles.get(key) === handle) {- developmentRebuildHandles.delete(key);- }- };-}--export async function flushDevelopmentRebuild(appRoot: string): Promise<void> {- await developmentRebuildHandles.get(resolve(appRoot))?.flush();-}diff --git a/packages/eve/src/internal/nitro/host/start-development-server.test.ts b/packages/eve/src/internal/nitro/host/start-development-server.test.tsindex e0f4dddb4..a6c48ff50 100644--- a/packages/eve/src/internal/nitro/host/start-development-server.test.ts+++ b/packages/eve/src/internal/nitro/host/start-development-server.test.ts@@ -287,6 +287,33 @@ describe("normalizeDevelopmentServerClientUrl", () => {});});+describe("isActiveDevelopmentServerForApp", () => {+ it("matches only this app's recorded healthy loopback server", async () => {+ const { isActiveDevelopmentServerForApp } = await import("./start-development-server.js");+ seedStateRecord({ url: "http://127.0.0.1:42123/" });+ mocks.fetch.mockResolvedValue(new Response(null, { status: 200 }));+ vi.stubGlobal("fetch", mocks.fetch);++ try {+ await expect(+ isActiveDevelopmentServerForApp({+ appRoot: "/tmp/eve-test",+ serverUrl: "http://127.0.0.1:42123/",+ }),+ ).resolves.toBe(true);+ await expect(+ isActiveDevelopmentServerForApp({+ appRoot: "/tmp/eve-test",+ serverUrl: "http://127.0.0.1:42124/",+ }),+ ).resolves.toBe(false);+ } finally {+ mocks.files.clear();+ vi.unstubAllGlobals();+ }+ });+});+describe("createDevelopmentServer", () => {beforeEach(() => {vi.clearAllMocks();diff --git a/packages/eve/src/internal/nitro/host/start-development-server.ts b/packages/eve/src/internal/nitro/host/start-development-server.tsindex 29f6ae41d..860ab5fd3 100644--- a/packages/eve/src/internal/nitro/host/start-development-server.ts+++ b/packages/eve/src/internal/nitro/host/start-development-server.ts@@ -75,6 +75,34 @@ export function normalizeDevelopmentServerClientUrl(serverUrl: string): string {return serverUrl;}+/**+ * Returns whether a supplied URL identifies this app's healthy local development+ * server. Only that server receives the local TUI credential path.+ */+export async function isActiveDevelopmentServerForApp(input: {+ readonly appRoot: string;+ readonly serverUrl: string;+}): Promise<boolean> {+ try {+ const project = await resolveDiscoveryProject(input.appRoot);+ const recordedServerUrl = await new DevelopmentServerState(project).read();+ if (+ recordedServerUrl === undefined ||+ !isLoopbackServerUrl(recordedServerUrl) ||+ !(await isEveServerHealthy(recordedServerUrl))+ ) {+ return false;+ }++ return (+ new URL(recordedServerUrl).origin ===+ new URL(normalizeDevelopmentServerClientUrl(input.serverUrl)).origin+ );+ } catch {+ return false;+ }+}+function isAddressInUseError(error: unknown): error is NodeJS.ErrnoException {return error instanceof Error && "code" in error && error.code === "EADDRINUSE";}diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.tsindex c31d7264d..06cdaf8e3 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts@@ -4,7 +4,9 @@ import { describe, expect, it, vi } from "vitest";import { CHANNEL_SENTINEL, type CompiledChannel } from "#channel/compiled-channel.js";import type { RouteHandlerArgs } from "#channel/routes.js";import type { DeliverInput, RunInput, Runtime } from "#channel/types.js";+import { readVercelProjectLink } from "#internal/vercel/project-link.js";import type { RouteContext } from "#public/definitions/channel.js";+import { resolveVercelOidcCurrentProject } from "#runtime/governance/auth/vercel-oidc-project.js";import type { ResolvedChannelDefinition } from "#runtime/types.js";import {dispatchChannelRequest,@@ -16,7 +18,12 @@ vi.mock("#internal/nitro/routes/runtime-stack.js", () => ({resolveNitroChannelRuntimeBundle: vi.fn(),}));+vi.mock("#internal/vercel/project-link.js", () => ({+ readVercelProjectLink: vi.fn(),+}));+const mockedResolveNitroChannelRuntimeBundle = vi.mocked(resolveNitroChannelRuntimeBundle);+const mockedReadVercelProjectLink = vi.mocked(readVercelProjectLink);const runtime = {} as Runtime;function createDeferred<T>() {@@ -54,6 +61,49 @@ function createEvent(input?: {}describe("dispatchChannelRequest", () => {+ it("supplies the current linked project to Vercel OIDC during local development", async () => {+ mockedReadVercelProjectLink+ .mockResolvedValueOnce({ orgId: "team_1", projectId: "prj_first" })+ .mockResolvedValueOnce({ orgId: "team_1", projectId: "prj_second" });+ const currentProjects: Array<Awaited<ReturnType<typeof resolveVercelOidcCurrentProject>>> = [];+ mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({+ channels: [+ {+ handler: async (request) => {+ currentProjects.push(await resolveVercelOidcCurrentProject(request));+ return new Response("ok");+ },+ fetch: async () => new Response("not used"),+ logicalPath: "agent/channels/eve.ts",+ method: "POST",+ name: "eve",+ sourceId: "channel-eve",+ sourceKind: "module",+ urlPath: "/eve/v1/session",+ } satisfies ResolvedChannelDefinition,+ ],+ runtime,+ });++ const response = await dispatchChannelRequest(+ createEvent({ waitUntil: vi.fn() }),+ "POST /eve/v1/session",+ { appRoot: "/app/agent", dev: true },+ );+ const nextResponse = await dispatchChannelRequest(+ createEvent({ waitUntil: vi.fn() }),+ "POST /eve/v1/session",+ { appRoot: "/app/agent", dev: true },+ );++ expect(response.status).toBe(200);+ expect(nextResponse.status).toBe(200);+ expect(currentProjects).toEqual([+ { environment: "development", projectId: "prj_first" },+ { environment: "development", projectId: "prj_second" },+ ]);+ });+it("returns the response before background work settles when Nitro provides waitUntil", async () => {const deferred = createDeferred<void>();const waitUntil = vi.fn<(task: Promise<unknown>) => void>();diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.tsindex 0a48f3d05..45f30a9e5 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts@@ -9,8 +9,10 @@ import type { RouteHandlerArgs, WebSocketRouteHooks } from "#channel/routes.js";import { createSendFn } from "#channel/send.js";import { createGetSessionFn } from "#channel/session.js";import { createLogger, logError } from "#internal/logging.js";+import { readVercelProjectLink } from "#internal/vercel/project-link.js";import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";import { resolveNitroChannelRuntimeBundle } from "#internal/nitro/routes/runtime-stack.js";+import { withVercelOidcProjectResolver } from "#runtime/governance/auth/vercel-oidc-project.js";const log = createLogger("channel.dispatch");@@ -60,10 +62,12 @@ export async function dispatchChannelRequest(let response: Response;try {- if (matchedChannel.handler) {- // Authored CompiledChannel route — build RouteHandlerArgs.- response = await matchedChannel.handler(event.req, routeArgs.args);- } else {+ response = await withDevelopmentVercelOidcContext(config, event.req, async () => {+ if (matchedChannel.handler) {+ // Authored CompiledChannel route — build RouteHandlerArgs.+ return await matchedChannel.handler(event.req, routeArgs.args);+ }+// Framework-internal fetch-only channel (e.g. the connection// callback route). Build a RouteContext with the agent handle.const ctx: RouteContext = {@@ -73,8 +77,8 @@ export async function dispatchChannelRequest(requestIp: routeArgs.args.requestIp,};- response = await matchedChannel.fetch(event.req, ctx);- }+ return await matchedChannel.fetch(event.req, ctx);+ });} catch (error) {// Without this a handler throw is only Nitro's default 5xx, with no eve log.const errorId = logError(log, "channel handler threw", error, {@@ -108,10 +112,15 @@ export async function dispatchChannelWebSocketRequest();}+ const websocket = matchedChannel.websocket;const routeArgs = buildRouteArgs(event, bundle, matchedChannel.name);try {- const hooks = await matchedChannel.websocket(event.req, routeArgs.args);+ const hooks = await withDevelopmentVercelOidcContext(+ config,+ event.req,+ async () => await websocket(event.req, routeArgs.args),+ );flushBackgroundTasks(event, routeArgs.backgroundTasks, routeKey, matchedChannel.name);return hooks;} catch (error) {@@ -127,6 +136,30 @@ export async function dispatchChannelWebSocketRequest(}}+async function withDevelopmentVercelOidcContext<T>(+ config: NitroArtifactsConfig,+ request: Request,+ callback: () => Promise<T>,+): Promise<T> {+ const appRoot = config.appRoot;+ if (config.dev !== true || appRoot === undefined) {+ return await callback();+ }++ return await withVercelOidcProjectResolver(+ {+ request,+ resolveCurrentProject: async () => {+ const link = await readVercelProjectLink(appRoot);+ return link === undefined+ ? undefined+ : { environment: "development", projectId: link.projectId };+ },+ },+ callback,+ );+}+function buildRouteArgs(event: H3Event,bundle: Awaited<ReturnType<typeof resolveNitroChannelRuntimeBundle>>,diff --git a/packages/eve/src/internal/nitro/routes/dev-runtime-artifacts.test.ts b/packages/eve/src/internal/nitro/routes/dev-runtime-artifacts.test.tsindex a130044cc..49e9f24b6 100644--- a/packages/eve/src/internal/nitro/routes/dev-runtime-artifacts.test.ts+++ b/packages/eve/src/internal/nitro/routes/dev-runtime-artifacts.test.ts@@ -1,7 +1,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({- flushDevelopmentRebuild: vi.fn(),readDevelopmentRuntimeArtifactsRevision: vi.fn(),}));@@ -15,12 +14,7 @@ vi.mock("#internal/nitro/dev-runtime-artifacts.js", async () => {};});-vi.mock("#internal/nitro/host/dev-rebuild-registry.js", () => ({- flushDevelopmentRebuild: mocks.flushDevelopmentRebuild,-}));-beforeEach(() => {- mocks.flushDevelopmentRebuild.mockReset();mocks.readDevelopmentRuntimeArtifactsRevision.mockReset();});@@ -41,20 +35,4 @@ describe("handleDevRuntimeArtifactsRequest", () => {});expect(mocks.readDevelopmentRuntimeArtifactsRevision).toHaveBeenCalledWith("/tmp/app");});-- it("flushes queued rebuilds before returning the current revision", async () => {- const { handleDevRuntimeArtifactsRebuildRequest } =- await import("#internal/nitro/routes/dev-runtime-artifacts.js");- mocks.readDevelopmentRuntimeArtifactsRevision.mockReturnValueOnce({- revision: "/tmp/app/.eve/dev-runtime/snapshots/next",- });-- const response = await handleDevRuntimeArtifactsRebuildRequest({ appRoot: "/tmp/app" });-- expect(response.status).toBe(200);- expect(await response.json()).toEqual({- revision: "/tmp/app/.eve/dev-runtime/snapshots/next",- });- expect(mocks.flushDevelopmentRebuild).toHaveBeenCalledWith("/tmp/app");- });});diff --git a/packages/eve/src/internal/nitro/routes/dev-runtime-artifacts.ts b/packages/eve/src/internal/nitro/routes/dev-runtime-artifacts.tsindex 61674d5f9..f2e3d999a 100644--- a/packages/eve/src/internal/nitro/routes/dev-runtime-artifacts.ts+++ b/packages/eve/src/internal/nitro/routes/dev-runtime-artifacts.ts@@ -1,5 +1,4 @@import { readDevelopmentRuntimeArtifactsRevision } from "#internal/nitro/dev-runtime-artifacts.js";-import { flushDevelopmentRebuild } from "#internal/nitro/host/dev-rebuild-registry.js";/*** Builds the dev-only runtime artifact revision response.@@ -15,10 +14,3 @@ export function handleDevRuntimeArtifactsRequest(input: { appRoot: string }): Re},});}--export async function handleDevRuntimeArtifactsRebuildRequest(input: {- appRoot: string;-}): Promise<Response> {- await flushDevelopmentRebuild(input.appRoot);- return handleDevRuntimeArtifactsRequest(input);-}diff --git a/packages/eve/src/internal/nitro/routes/info.ts b/packages/eve/src/internal/nitro/routes/info.tsindex 164775039..0cc5743ec 100644--- a/packages/eve/src/internal/nitro/routes/info.ts+++ b/packages/eve/src/internal/nitro/routes/info.ts@@ -63,7 +63,7 @@ export async function handleAgentInfoRequest(input: AgentInfoRouteInput,request: Request,): Promise<Response> {- const authResult = await routeAuth(request, [localDev(), vercelOidc()]);+ const authResult = await routeAuth(request, [vercelOidc(), localDev()]);if (authResult instanceof Response) return authResult;return new Response(JSON.stringify(await createAgentInfoPayload(input)), {diff --git a/packages/eve/src/internal/vercel/project-link.ts b/packages/eve/src/internal/vercel/project-link.tsnew file mode 100644index 000000000..da1ecd6e5--- /dev/null+++ b/packages/eve/src/internal/vercel/project-link.ts@@ -0,0 +1,26 @@+import { readFile } from "node:fs/promises";+import { join } from "node:path";++import { z } from "#compiled/zod/index.js";++export const VercelProjectLinkSchema = z.object({+ projectId: z.string().min(1),+ orgId: z.string().min(1),+ projectName: z.string().min(1).optional(),+});++/** Validated Vercel owner and project identifiers from `.vercel/project.json`. */+export type VercelProjectLink = z.infer<typeof VercelProjectLinkSchema>;++/** Reads a validated Vercel project link without mutating local project state. */+export async function readVercelProjectLink(+ projectPath: string,+): Promise<VercelProjectLink | undefined> {+ try {+ const raw = await readFile(join(projectPath, ".vercel", "project.json"), "utf8");+ const parsed = VercelProjectLinkSchema.safeParse(JSON.parse(raw));+ return parsed.success ? parsed.data : undefined;+ } catch {+ return undefined;+ }+}diff --git a/packages/eve/src/public/channels/auth.test.ts b/packages/eve/src/public/channels/auth.test.tsindex d29f8e531..bfc626f62 100644--- a/packages/eve/src/public/channels/auth.test.ts+++ b/packages/eve/src/public/channels/auth.test.ts@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { EVE_CREATE_SESSION_ROUTE_PATH } from "#protocol/routes.js";import type { SessionAuthContext } from "#channel/types.js";+import { withVercelOidcProjectResolver } from "#runtime/governance/auth/vercel-oidc-project.js";import {type AuthFn,createIpAllowList,@@ -694,6 +695,135 @@ describe("verifyVercelOidc", () => {}});+ it("authenticates a development Vercel user token as a user principal", async () => {+ vi.stubEnv("VERCEL_PROJECT_ID", "prj_current");+ vi.stubEnv("VERCEL_TARGET_ENV", "development");++ const issuer = await installMockedVercelIssuer("development-user-accept");+ try {+ const token = await issuer.signToken({+ environment: "development",+ owner: "acme",+ owner_id: "team_acme",+ project: "weather-agent",+ project_id: "prj_current",+ sub: "owner:acme:project:weather-agent:environment:development",+ user_id: "user_ada",+ });++ const result = await verifyVercelOidc(token);++ expect(result.ok).toBe(true);+ if (result.ok) {+ expect(result.sessionAuth).toMatchObject({+ authenticator: "oidc",+ principalType: "user",+ subject: "user_ada",+ });+ }+ } finally {+ issuer.restore();+ }+ });++ it("uses an explicit current-project binding for a development user token", async () => {+ vi.stubEnv("VERCEL_PROJECT_ID", "");+ vi.stubEnv("VERCEL_TARGET_ENV", "");+ vi.stubEnv("VERCEL_ENV", "");++ const issuer = await installMockedVercelIssuer("development-user-explicit-project");+ try {+ const token = await issuer.signToken({+ environment: "development",+ project_id: "prj_current",+ sub: "owner:acme:project:weather-agent:environment:development",+ user_id: "user_ada",+ });++ const result = await verifyVercelOidc(token, {+ currentVercelProject: {+ environment: "development",+ projectId: "prj_current",+ },+ });++ expect(result.ok).toBe(true);+ if (result.ok) {+ expect(result.sessionAuth).toMatchObject({+ principalType: "user",+ subject: "user_ada",+ });+ }+ } finally {+ issuer.restore();+ }+ });++ it("authenticates a development user token as a service principal on preview", async () => {+ vi.stubEnv("VERCEL_PROJECT_ID", "prj_current");+ vi.stubEnv("VERCEL_TARGET_ENV", "preview");++ const issuer = await installMockedVercelIssuer("development-user-preview-service");+ try {+ const token = await issuer.signToken({+ environment: "development",+ project_id: "prj_current",+ sub: "owner:acme:project:weather-agent:environment:development",+ user_id: "user_ada",+ });++ const result = await verifyVercelOidc(token);++ expect(result.ok).toBe(true);+ if (result.ok) {+ expect(result.sessionAuth).toMatchObject({+ principalType: "service",+ subject: "owner:acme:project:weather-agent:environment:development",+ });+ }+ } finally {+ issuer.restore();+ }+ });++ it("rejects a development user token on production", async () => {+ vi.stubEnv("VERCEL_PROJECT_ID", "prj_current");+ vi.stubEnv("VERCEL_TARGET_ENV", "production");++ const issuer = await installMockedVercelIssuer("development-user-production-reject");+ try {+ const token = await issuer.signToken({+ environment: "development",+ project_id: "prj_current",+ sub: "owner:acme:project:weather-agent:environment:development",+ user_id: "user_ada",+ });++ await expect(verifyVercelOidc(token)).resolves.toEqual({ ok: false });+ } finally {+ issuer.restore();+ }+ });++ it("rejects a user_id claim outside development", async () => {+ vi.stubEnv("VERCEL_PROJECT_ID", "prj_current");+ vi.stubEnv("VERCEL_TARGET_ENV", "preview");++ const issuer = await installMockedVercelIssuer("non-development-user-id");+ try {+ const token = await issuer.signToken({+ environment: "preview",+ project_id: "prj_current",+ sub: "owner:acme:project:weather-agent:environment:preview",+ user_id: "user_ada",+ });++ await expect(verifyVercelOidc(token)).resolves.toEqual({ ok: false });+ } finally {+ issuer.restore();+ }+ });+it("rejects a Vercel-issued token whose project_id does not match VERCEL_PROJECT_ID", async () => {// Demonstrates the security fix: a token minted for an unrelated// Vercel project (with a fully valid signature, audience, and issuer@@ -1154,6 +1284,52 @@ describe("vercelOidc strategy helper", () => {});await expect(Promise.resolve(authFn(request))).resolves.toBeNull();});++ it("uses the local host's linked project binding only for bearer requests", async () => {+ vi.stubEnv("VERCEL_PROJECT_ID", "");+ vi.stubEnv("VERCEL_TARGET_ENV", "");+ vi.stubEnv("VERCEL_ENV", "");+ const issuer = await installMockedVercelIssuer("local-host-binding");++ try {+ const resolveCurrentProject = vi.fn(() => ({+ environment: "development" as const,+ projectId: "prj_linked",+ }));+ const authFn = vercelOidc();+ const unauthenticatedRequest = new Request("http://localhost/eve/v1/session");+ await expect(+ withVercelOidcProjectResolver(+ { request: unauthenticatedRequest, resolveCurrentProject },+ async () => await authFn(unauthenticatedRequest),+ ),+ ).resolves.toBeNull();+ expect(resolveCurrentProject).not.toHaveBeenCalled();++ const token = await issuer.signToken({+ environment: "development",+ project_id: "prj_linked",+ sub: "owner:acme:project:weather-agent:environment:development",+ user_id: "user_ada",+ });+ const request = new Request("http://localhost/eve/v1/session", {+ headers: { authorization: `Bearer ${token}` },+ });+ const result = await withVercelOidcProjectResolver(+ {+ request,+ resolveCurrentProject,+ },+ async () => await authFn(request),+ );++ expect(result).toMatchObject({ principalType: "user", subject: "user_ada" });+ expect(resolveCurrentProject).toHaveBeenCalledTimes(1);+ } finally {+ issuer.restore();+ vi.unstubAllEnvs();+ }+ });});describe("httpBasic strategy helper", () => {diff --git a/packages/eve/src/public/channels/auth.ts b/packages/eve/src/public/channels/auth.tsindex 396eb131b..774a482f1 100644--- a/packages/eve/src/public/channels/auth.ts+++ b/packages/eve/src/public/channels/auth.ts@@ -13,6 +13,7 @@ import { authenticateHttpBasicStrategy } from "#runtime/governance/auth/http-basimport { authenticateJwtEcdsaStrategy } from "#runtime/governance/auth/jwt-ecdsa.js";import { authenticateJwtHmacStrategy } from "#runtime/governance/auth/jwt-hmac.js";import { authenticateOidcStrategy } from "#runtime/governance/auth/oidc.js";+import { resolveVercelOidcCurrentProject } from "#runtime/governance/auth/vercel-oidc-project.js";import {createRuntimeSessionAuthContext,type ResolvedJwtEcdsaAuthStrategy,@@ -268,6 +269,7 @@ export async function verifyOidc(const result = await runOidcVerification(token, {...config,acceptCurrentVercelProject: false,+ currentVercelProject: undefined,});return result.kind === "authenticated"? { ok: true, sessionAuth: createRuntimeSessionAuthContext(result.principal) }@@ -284,13 +286,16 @@ export async function verifyOidc(*/async function runOidcVerification(token: string | null,- config: VerifyOidcConfig & { readonly acceptCurrentVercelProject: boolean },+ config: VerifyOidcConfig & {+ readonly acceptCurrentVercelProject: boolean;+ readonly currentVercelProject: ResolvedOidcAuthStrategy["currentVercelProject"] | undefined;+ },): Promise<RouteStrategyAuthenticationResult> {if (token === null || token.length === 0) {return { kind: "not-authenticated" };}- const strategy: ResolvedOidcAuthStrategy = {+ const baseStrategy = {acceptCurrentVercelProject: config.acceptCurrentVercelProject,audiences: [...config.audiences],clockSkewSeconds: config.clockSkewSeconds ?? 30,@@ -300,7 +305,11 @@ async function runOidcVerification(kind: "oidc",...(config.claims === undefined ? {} : { claims: config.claims }),...(config.subjects === undefined ? {} : { subjects: config.subjects }),- };+ } satisfies ResolvedOidcAuthStrategy;+ const strategy =+ config.currentVercelProject === undefined+ ? baseStrategy+ : { ...baseStrategy, currentVercelProject: config.currentVercelProject };return await authenticateOidcStrategy({ strategy, token });}@@ -530,7 +539,7 @@ export async function routeAuth(* error. Replace it before serving real users:** ```ts- * eveChannel({ auth: [localDev(), vercelOidc(), placeholderAuth()] });+ * eveChannel({ auth: [vercelOidc(), localDev(), placeholderAuth()] });* ```** Outside production it returns `null`, so the auth walk keeps the same local@@ -578,8 +587,8 @@ export function none<TEvent = unknown>(): AuthFn<TEvent> {** Matching requests get a synthetic principal with `principalType:* "local-dev"`. Every other request returns `null`, skipping to the next- * entry under {@link routeAuth}, which makes `[localDev(), vercelOidc()]`- * the canonical "open on localhost, Vercel OIDC in prod" pattern.+ * entry under {@link routeAuth}, which makes `[vercelOidc(), localDev()]`+ * the canonical "Vercel OIDC when present, open on localhost otherwise" pattern.** The check is not based on bare `process.env.VERCEL`: a deployment* outside Vercel (Fly, Railway, raw container) leaves `VERCEL` unset and@@ -627,7 +636,8 @@ const LOOPBACK_HOSTNAMES: ReadonlySet<string> = new Set(["localhost", "[::1]"]);*/const LOOPBACK_IPV4_PREFIX = /^127\./;-function isLoopbackRequest(request: Request): boolean {+/** Returns whether a request URL names a loopback host accepted by {@link localDev}. */+export function isLoopbackRequest(request: Request): boolean {let hostname: string;try {hostname = new URL(request.url).hostname;@@ -679,6 +689,15 @@ const VERCEL_OIDC_AUDIENCE_PREFIX = "https://vercel.com/";* Options for {@link verifyVercelOidc} and {@link vercelOidc}.*/export interface VerifyVercelOidcOptions {+ /**+ * Explicit current-project binding for the verified token. When omitted,+ * the verifier reads `VERCEL_PROJECT_ID` and `VERCEL_TARGET_ENV` /+ * `VERCEL_ENV` from the runtime environment.+ */+ readonly currentVercelProject?: {+ readonly environment?: string;+ readonly projectId: string;+ };/*** Optional `sub` patterns granting callers access on top of the always-on* current-project bypass. Patterns use AWS IAM-style `*` wildcards and may@@ -694,23 +713,25 @@ export interface VerifyVercelOidcOptions {** Acceptance rule:*- * - Tokens whose `project_id` matches `VERCEL_PROJECT_ID` are **always**- * accepted regardless of `subjects`, so the deployment's own runtime- * callers (subagent, internal fetches) authenticate without being- * enumerated.+ * - Current-project tokens that reach the service/runtime path are accepted+ * regardless of `subjects`, so the deployment's own runtime callers+ * (subagent, internal fetches) authenticate without being enumerated.* - Tokens with an `external_sub` claim authenticate as- * `principalType: "user"` when they match the current `VERCEL_PROJECT_ID`- * (if set) and `VERCEL_TARGET_ENV` / `VERCEL_ENV` (if set). `external_sub`+ * `principalType: "user"` when they match the configured current project+ * and environment. `external_sub`* becomes the eve subject, `external_iss` or `connector_id` the eve issuer* when present, and string-valued OIDC profile claims (`name`, `picture`,* `email`) are exposed as auth attributes.+ * - Development tokens with a `user_id` claim authenticate as+ * `principalType: "user"` only when both the token and configured current+ * project environment are `development`. A same-project preview target may+ * use one as a `"service"` principal; other target environments reject it.* - Tokens from other Vercel projects are accepted **only** when their `sub`* matches one of {@link VerifyVercelOidcOptions.subjects}.*- * The `environment` claim is not constrained: production, preview, and- * development tokens for the current project all authenticate. Non-user- * principals are tagged `"runtime"` when the token's `environment` matches- * the current deployment, otherwise `"service"`.+ * Tokens without a `user_id` claim are accepted for the current project in+ * production, preview, and development. They are tagged `"runtime"` when the+ * token's `environment` matches the current deployment, otherwise `"service"`.*/export async function verifyVercelOidc(token: string | null,@@ -751,13 +772,15 @@ export async function verifyVercelOidc(}// `acceptCurrentVercelProject: true` activates the same-project bypass- // inside the OIDC verifier so any token minted for `VERCEL_PROJECT_ID`+ // inside the OIDC verifier so any token minted for the configured project// is accepted regardless of `subjects`. The supplied `subjects`// matcher (defaulting to an empty list that matches nothing)// determines which **other** callers are allowed in.+ const currentVercelProject = resolveCurrentVercelProject(opts);const result = await runOidcVerification(token, {acceptCurrentVercelProject: true,audiences: claims.audiences,+ currentVercelProject,issuer: claims.issuer,subjects: opts.subjects ?? [],});@@ -781,6 +804,20 @@ export async function verifyVercelOidc(return { ok: false };}+function resolveCurrentVercelProject(+ opts: VerifyVercelOidcOptions,+): NonNullable<ResolvedOidcAuthStrategy["currentVercelProject"]> | undefined {+ if (opts.currentVercelProject !== undefined) return opts.currentVercelProject;++ const projectId = process.env.VERCEL_PROJECT_ID?.trim();+ if (projectId === undefined || projectId.length === 0) return undefined;++ const environment = process.env.VERCEL_TARGET_ENV?.trim() || process.env.VERCEL_ENV?.trim();+ return environment === undefined || environment.length === 0+ ? { projectId }+ : { environment, projectId };+}+/*** Allowed values for {@link VercelSubjectInput.environment}. Use `"*"`* to match any of `production`, `preview`, and `development` for the@@ -880,11 +917,27 @@ function assertVercelSubjectSegment(field: "teamSlug" | "projectName", value: stexport function vercelOidc(opts: VerifyVercelOidcOptions = {}): AuthFn<Request> {return async (request) => {const token = extractBearerToken(request.headers.get("authorization"));- const result = await verifyVercelOidc(token, opts);+ const currentVercelProject =+ opts.currentVercelProject ??+ (token !== null && isLocalDevelopmentVercelOidcRequest(request)+ ? await resolveVercelOidcCurrentProject(request)+ : undefined);+ const result = await verifyVercelOidc(+ token,+ currentVercelProject === undefined ? opts : { ...opts, currentVercelProject },+ );return result.ok ? result.sessionAuth : null;};}+function isLocalDevelopmentVercelOidcRequest(request: Request): boolean {+ if (process.env.VERCEL_ENV === "development") return true;+ if (process.env.VERCEL_ENV === "preview" || process.env.VERCEL_ENV === "production") {+ return false;+ }+ return isLoopbackRequest(request);+}+/** Returns an {@link AuthFn} that verifies HTTP Basic credentials via {@link verifyHttpBasic}. */export function httpBasic(credentials: HttpBasicCredentials): AuthFn<Request> {return (request) => {diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts b/packages/eve/src/runtime/agent/mock-model-adapter.test.tsindex 6249eb625..aefe8e49a 100644--- a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts+++ b/packages/eve/src/runtime/agent/mock-model-adapter.test.ts@@ -1,7 +1,14 @@-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import type { BootstrapGenerateResult } from "#runtime/agent/bootstrap-model-utils.js";-import { createMockAuthoredRuntimeModel } from "#runtime/agent/mock-model-adapter.js";+import {+ createMockAuthoredRuntimeModel,+ shouldMockAuthoredRuntimeModels,+} from "#runtime/agent/mock-model-adapter.js";++afterEach(() => {+ vi.unstubAllEnvs();+});async function generateWithPrompt(prompt: unknown,@@ -23,6 +30,13 @@ async function generateWithPrompt(}describe("createMockAuthoredRuntimeModel", () => {+ it("activates for the explicit spawned-server test seam", () => {+ vi.stubEnv("NODE_ENV", "production");+ vi.stubEnv("EVE_MOCK_AUTHORED_MODELS", "1");++ expect(shouldMockAuthoredRuntimeModels()).toBe(true);+ });+it("activates a matching skill when the available skill line includes a workspace path", async () => {const result = await generateWithPrompt([{diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.ts b/packages/eve/src/runtime/agent/mock-model-adapter.tsindex 2ddadd7a8..98a648462 100644--- a/packages/eve/src/runtime/agent/mock-model-adapter.ts+++ b/packages/eve/src/runtime/agent/mock-model-adapter.ts@@ -35,6 +35,7 @@ import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";const MOCK_RUNTIME_MODEL_PROVIDER = "eve-runtime-mock";const LOAD_SKILL_TOOL_CALL_ID = "call_load_skill";+const MOCK_AUTHORED_MODELS_ENV = "EVE_MOCK_AUTHORED_MODELS";type BootstrapGenerateOptions = Parameters<MockLanguageModelV3["doGenerate"]>[0];interface BootstrapToolResult {@@ -57,11 +58,12 @@ const bootstrapWeatherPayloadSchema = z/*** Returns true when authored runtime models should resolve through the* dedicated deterministic mock adapter. The adapter is internal to the test- * tiers: it activates only under `NODE_ENV=test`, keeping the unit,- * integration, and scenario suites deterministic and credential-free.+ * tiers: unit, integration, and scenario tests activate it through+ * `NODE_ENV=test`; spawned smoke servers use the explicit opt-in environment+ * variable so their package-manager build keeps its normal environment.*/export function shouldMockAuthoredRuntimeModels(): boolean {- return process.env.NODE_ENV === "test";+ return process.env.NODE_ENV === "test" || process.env[MOCK_AUTHORED_MODELS_ENV] === "1";}/**diff --git a/packages/eve/src/runtime/connections/principal.test.ts b/packages/eve/src/runtime/connections/principal.test.tsindex 17fcd2313..219cc72e9 100644--- a/packages/eve/src/runtime/connections/principal.test.ts+++ b/packages/eve/src/runtime/connections/principal.test.ts@@ -35,6 +35,11 @@ const userAuthDef: AuthorizationDefinition = {principalType: "user",};+const connectUserAuthDef: AuthorizationDefinition = {+ ...userAuthDef,+ vercelConnect: { connector: "mcp.notion.com/notion" },+};+describe("principalKey", () => {it("collapses every app principal to the string 'app'", () => {expect(principalKey({ type: "app" })).toBe("app");@@ -50,6 +55,10 @@ describe("principalKey", () => {const bob = principalKey({ id: "bob", issuer: "idp", type: "user" });expect(alice).not.toBe(bob);});++ it("keys an issuerless native Vercel user by its user id", () => {+ expect(principalKey({ id: "user_123", type: "user" })).toBe("user:user_123");+ });});describe("resolveConnectionPrincipal", () => {@@ -90,6 +99,50 @@ describe("resolveConnectionPrincipal", () => {});});+ it("projects a Vercel development user without its reserved OIDC issuer", () => {+ const ctx = ctxWithAuth(+ userAuth({+ attributes: { environment: "development", user_id: "user_123" },+ authenticator: "oidc",+ issuer: "https://oidc.vercel.com/team_123",+ principalId: "https://oidc.vercel.com/team_123:user_123",+ subject: "user_123",+ }),+ );++ const principal = contextStorage.run(ctx, () =>+ resolveConnectionPrincipal("notion", connectUserAuthDef),+ );++ expect(principal).toEqual({+ attributes: { environment: "development", user_id: "user_123" },+ id: "user_123",+ type: "user",+ });+ });++ it("preserves a Vercel development user's issuer for non-Connect authorization", () => {+ const ctx = ctxWithAuth(+ userAuth({+ attributes: { environment: "development", user_id: "user_123" },+ authenticator: "oidc",+ issuer: "https://oidc.vercel.com/team_123",+ principalId: "https://oidc.vercel.com/team_123:user_123",+ subject: "user_123",+ }),+ );++ const principal = contextStorage.run(ctx, () =>+ resolveConnectionPrincipal("custom", userAuthDef),+ );++ expect(principal).toMatchObject({+ id: "https://oidc.vercel.com/team_123:user_123",+ issuer: "https://oidc.vercel.com/team_123",+ type: "user",+ });+ });+it("preserves the full SessionAuthContext attributes on the principal", () => {const attributes = { email: "[email protected]", roles: ["admin", "viewer"] };const ctx = ctxWithAuth(userAuth({ attributes }));@@ -130,6 +183,19 @@ describe("resolveConnectionPrincipal", () => {).toThrow(/active session is scoped to "service"/);});+ it("explains when a local Connect request has no Vercel user", () => {+ const ctx = ctxWithAuth({+ attributes: {},+ authenticator: "local-dev",+ principalId: "local-dev",+ principalType: "local-dev",+ });++ expect(() =>+ contextStorage.run(ctx, () => resolveConnectionPrincipal("notion", connectUserAuthDef)),+ ).toThrow(/fell back to local development access/);+ });+it("accepts an explicit ctx argument and bypasses AsyncLocalStorage", () => {const ctx = ctxWithAuth(userAuth({ issuer: "idp", principalId: "u1" }));diff --git a/packages/eve/src/runtime/connections/principal.ts b/packages/eve/src/runtime/connections/principal.tsindex a9a689bff..13cbef558 100644--- a/packages/eve/src/runtime/connections/principal.ts+++ b/packages/eve/src/runtime/connections/principal.ts@@ -11,7 +11,7 @@*/import { type AlsContext, contextStorage } from "#context/container.js";-import { AuthKey } from "#context/keys.js";+import { AuthKey, type SessionAuthContext } from "#context/keys.js";import { ConnectionAuthorizationFailedError } from "#public/connections/errors.js";import type { AuthorizationDefinition, ConnectionPrincipal } from "#runtime/connections/types.js";@@ -24,11 +24,16 @@ import type { AuthorizationDefinition, ConnectionPrincipal } from "#runtime/conn* issuer prefix prevents collisions when the same `id` across* identity providers (for example Slack `U123` vs Google `U123`)* would otherwise alias to the same cache slot.+ * - `{ type: "user", id }` → `"user:${id}"`. This is the native+ * Vercel Connect user projection.*/export function principalKey(principal: ConnectionPrincipal): string {if (principal.type === "app") {return "app";}+ if (principal.issuer === undefined) {+ return `user:${principal.id}`;+ }return `user:${principal.issuer}:${principal.id}`;}@@ -85,12 +90,20 @@ export function resolveConnectionPrincipal(const current = ctx?.get(AuthKey);if (current === null || current === undefined || current.principalType !== "user") {throw new ConnectionAuthorizationFailedError(connectionName, {- message: buildUserPrincipalRequiredMessage(connectionName, ctx, current?.principalType),+ message: buildUserPrincipalRequiredMessage(connectionName, authorization, ctx, current),reason: "principal_required",retryable: false,});}+ if (authorization.vercelConnect !== undefined && isVercelDevelopmentUser(current)) {+ return {+ attributes: current.attributes,+ id: current.subject ?? current.principalId,+ type: "user",+ };+ }+return {attributes: current.attributes,id: current.principalId,@@ -99,18 +112,32 @@ export function resolveConnectionPrincipal(};}+function isVercelDevelopmentUser(current: SessionAuthContext): boolean {+ return (+ current.authenticator === "oidc" &&+ current.issuer?.startsWith("https://oidc.vercel.com/") === true &&+ current.attributes.environment === "development" &&+ current.subject === current.attributes.user_id+ );+}+function buildUserPrincipalRequiredMessage(connectionName: string,+ authorization: AuthorizationDefinition,ctx: AlsContext | undefined,- currentPrincipalType: string | undefined,+ current: SessionAuthContext | null | undefined,): string {let detail: string;if (ctx === undefined) {detail = "it was invoked outside an eve context, so no authenticated user can be resolved.";- } else if (currentPrincipalType === undefined) {+ } else if (current === undefined || current === null) {detail = "the active session has no authenticated user.";+ } else if (authorization.vercelConnect !== undefined && current.authenticator === "local-dev") {+ detail =+ "the local request fell back to local development access instead of authenticating a Vercel user. " ++ "Ensure this directory is linked and the Vercel CLI can mint a Vercel OIDC token, then retry.";} else {- detail = `the active session is scoped to "${currentPrincipalType}", not an authenticated user.`;+ detail = `the active session is scoped to "${current.principalType}", not an authenticated user.`;}return (diff --git a/packages/eve/src/runtime/connections/types.ts b/packages/eve/src/runtime/connections/types.tsindex 8a281ecb9..453589fd9 100644--- a/packages/eve/src/runtime/connections/types.ts+++ b/packages/eve/src/runtime/connections/types.ts@@ -83,13 +83,16 @@ export type ToolFilterDefinition =* - `{ type: "user", id, issuer }`: per end-user identity; the token* cache keys on `issuer + id` so the same `id` across different* IdPs (Slack `U123` vs Google `U123`) never collides.+ * - `{ type: "user", id }`: Vercel Connect's native user subject, used for a+ * verified Vercel development user. The Vercel OIDC issuer is not forwarded+ * because Connect rejects it.*/export type ConnectionPrincipal =| { readonly type: "app" }| {readonly type: "user";readonly id: string;- readonly issuer: string;+ readonly issuer?: string;readonly attributes?: Readonly<Record<string, string | readonly string[]>>;};diff --git a/packages/eve/src/runtime/framework-channels/index.test.ts b/packages/eve/src/runtime/framework-channels/index.test.tsnew file mode 100644index 000000000..83d200841--- /dev/null+++ b/packages/eve/src/runtime/framework-channels/index.test.ts@@ -0,0 +1,46 @@+import type { AuthFn } from "#public/channels/auth.js";+import type { EveChannelInput } from "#public/channels/eve.js";+import { afterEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ localDev: vi.fn(),+ vercelOidc: vi.fn(),+}));++let capturedAuth: EveChannelInput["auth"] | undefined;++vi.mock("#public/channels/auth.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("#public/channels/auth.js")>()),+ localDev: mocks.localDev,+ vercelOidc: mocks.vercelOidc,+}));++vi.mock("#public/channels/eve.js", () => ({+ eveChannel(input: EveChannelInput) {+ capturedAuth = input.auth;+ return { adapter: {}, routes: [] };+ },+}));++import { getFrameworkChannelDefinitions } from "./index.js";++afterEach(() => {+ capturedAuth = undefined;+ mocks.localDev.mockReset();+ mocks.vercelOidc.mockReset();+});++describe("framework eve channel auth", () => {+ it("uses Vercel OIDC before the local-development fallback", () => {+ const vercelAuth: AuthFn<Request> = () => null;+ const localAuth: AuthFn<Request> = () => null;+ mocks.vercelOidc.mockReturnValue(vercelAuth);+ mocks.localDev.mockReturnValue(localAuth);++ getFrameworkChannelDefinitions();++ expect(capturedAuth).toEqual([vercelAuth, localAuth]);+ expect(mocks.vercelOidc).toHaveBeenCalledWith();+ expect(mocks.localDev).toHaveBeenCalledWith();+ });+});diff --git a/packages/eve/src/runtime/framework-channels/index.ts b/packages/eve/src/runtime/framework-channels/index.tsindex bd2a20050..975540a00 100644--- a/packages/eve/src/runtime/framework-channels/index.ts+++ b/packages/eve/src/runtime/framework-channels/index.ts@@ -15,15 +15,12 @@ import type { ResolvedChannelDefinition } from "#runtime/types.js";const EVE_CHANNEL_NAME = "eve";/**- * Framework default for the eve channel. Mirrors verbatim the scaffold- * written by eve into `agent/channels/eve.ts`, so the- * behavior of "no authored file" and "scaffolded file untouched" is- * byte-identical — and the local-dev / Vercel branching lives in a- * single named helper (`localDev`) instead of an env check buried in- * the framework.+ * Framework default for the eve channel.*/export function getFrameworkChannelDefinitions(): readonly ResolvedChannelDefinition[] {- const compiled = eveChannel({ auth: [localDev(), vercelOidc()] }) as CompiledChannel;+ const compiled = eveChannel({+ auth: [vercelOidc(), localDev()],+ }) as CompiledChannel;const result: ResolvedChannelDefinition[] = [];diff --git a/packages/eve/src/runtime/governance/auth/oidc.ts b/packages/eve/src/runtime/governance/auth/oidc.tsindex 367b68793..c54f84d8f 100644--- a/packages/eve/src/runtime/governance/auth/oidc.ts+++ b/packages/eve/src/runtime/governance/auth/oidc.ts@@ -56,8 +56,8 @@ export async function authenticateOidcStrategy(input: {if (typeof verified.payload.external_sub !== "string" ||verified.payload.external_sub.length === 0 ||- !currentVercelProjectMatches({ payload: verified.payload }) ||- !currentVercelEnvironmentMatches({ payload: verified.payload })+ !currentVercelProjectMatches({ payload: verified.payload, strategy: input.strategy }) ||+ !currentVercelEnvironmentMatches({ payload: verified.payload, strategy: input.strategy })) {return {kind: "caller-not-allowed",@@ -76,6 +76,46 @@ export async function authenticateOidcStrategy(input: {};}+ const hasDevelopmentUserSubject =+ input.strategy.acceptCurrentVercelProject &&+ input.strategy.issuer.startsWith("https://oidc.vercel.com/") &&+ verified.payload.user_id !== undefined;+ if (hasDevelopmentUserSubject) {+ if (+ typeof verified.payload.user_id !== "string" ||+ verified.payload.user_id.length === 0 ||+ verified.payload.environment !== "development" ||+ !currentVercelProjectMatches({ payload: verified.payload, strategy: input.strategy })+ ) {+ return {+ kind: "caller-not-allowed",+ };+ }++ if (+ currentVercelEnvironmentMatches({ payload: verified.payload, strategy: input.strategy })+ ) {+ return {+ kind: "authenticated",+ principal: createJwtAuthenticatedCallerPrincipal({+ authenticator: "oidc",+ payload: verified.payload,+ principalType: "user",+ subjectClaim: "user_id",+ }),+ };+ }++ if (input.strategy.currentVercelProject?.environment !== "preview") {+ return {+ kind: "caller-not-allowed",+ };+ }++ // Preview may use a same-project development credential only through the+ // generic service path below, never as the user embedded in the token.+ }+if (typeof verified.payload.sub !== "string" || verified.payload.sub.length === 0) {return {kind: "not-authenticated",@@ -87,9 +127,11 @@ export async function authenticateOidcStrategy(input: {isCurrentVercelProjectToken({issuer: input.strategy.issuer,payload: verified.payload,+ strategy: input.strategy,});const isCurrentVercelRuntimeToken =- isCurrentProjectToken && isCurrentVercelEnvironmentToken({ payload: verified.payload });+ isCurrentProjectToken &&+ isCurrentVercelEnvironmentToken({ payload: verified.payload, strategy: input.strategy });if (!isCurrentProjectToken &&@@ -171,47 +213,56 @@ async function getOidcDiscoveryDocument(function isCurrentVercelProjectToken(input: {readonly issuer: string;readonly payload: JWTPayload;+ readonly strategy: ResolvedOidcAuthStrategy;}): boolean {if (!input.issuer.startsWith("https://oidc.vercel.com")) {return false;}- const currentProjectId = process.env.VERCEL_PROJECT_ID?.trim();- if (currentProjectId === undefined || currentProjectId.length === 0) {+ const currentProject = input.strategy.currentVercelProject;+ if (currentProject === undefined) {return false;}return (- typeof input.payload.project_id === "string" && input.payload.project_id === currentProjectId+ typeof input.payload.project_id === "string" &&+ input.payload.project_id === currentProject.projectId);}/**- * Returns whether the token's `project_id` claim matches the deployment's- * `VERCEL_PROJECT_ID`. Fails closed: when `VERCEL_PROJECT_ID` is unset this- * returns `false`, so an external-subject ("user") token cannot authenticate- * on a deployment that has not pinned its project. Mirrors the fail-closed- * {@link isCurrentVercelProjectToken} used by the service/runtime branch.+ * Returns whether the token's `project_id` claim matches the configured+ * current project. Fails closed when that project is absent, so a user token+ * cannot authenticate without an explicit project bind. Mirrors the+ * fail-closed {@link isCurrentVercelProjectToken} used by the+ * service/runtime branch.*/-function currentVercelProjectMatches(input: { readonly payload: JWTPayload }): boolean {- const currentProjectId = process.env.VERCEL_PROJECT_ID?.trim();- if (currentProjectId === undefined || currentProjectId.length === 0) {+function currentVercelProjectMatches(input: {+ readonly payload: JWTPayload;+ readonly strategy: ResolvedOidcAuthStrategy;+}): boolean {+ const currentProject = input.strategy.currentVercelProject;+ if (currentProject === undefined) {return false;}return (- typeof input.payload.project_id === "string" && input.payload.project_id === currentProjectId+ typeof input.payload.project_id === "string" &&+ input.payload.project_id === currentProject.projectId);}/**- * Returns whether a verified JWT's `environment` claim matches the- * current Vercel deployment environment. Combined with+ * Returns whether a verified JWT's `environment` claim matches the configured+ * current Vercel environment. Combined with* {@link isCurrentVercelProjectToken} to upgrade `principalType` from* `"service"` to `"runtime"` when the caller is the deployment itself.*/-function isCurrentVercelEnvironmentToken(input: { readonly payload: JWTPayload }): boolean {- const currentEnvironment = getCurrentVercelEnvironment();+function isCurrentVercelEnvironmentToken(input: {+ readonly payload: JWTPayload;+ readonly strategy: ResolvedOidcAuthStrategy;+}): boolean {+ const currentEnvironment = input.strategy.currentVercelProject?.environment;if (currentEnvironment === undefined || currentEnvironment.length === 0) {return false;}@@ -223,13 +274,15 @@ function isCurrentVercelEnvironmentToken(input: { readonly payload: JWTPayload }}/**- * Returns whether the token's `environment` claim matches the current Vercel- * deployment environment. Fails closed: when the environment cannot be- * resolved this returns `false`, so an external-subject ("user") token cannot- * authenticate on a deployment with no resolvable environment.+ * Returns whether the token's `environment` claim matches the configured+ * current Vercel environment. Fails closed when that environment is absent,+ * so a user token cannot authenticate without an explicit environment bind.*/-function currentVercelEnvironmentMatches(input: { readonly payload: JWTPayload }): boolean {- const currentEnvironment = getCurrentVercelEnvironment();+function currentVercelEnvironmentMatches(input: {+ readonly payload: JWTPayload;+ readonly strategy: ResolvedOidcAuthStrategy;+}): boolean {+ const currentEnvironment = input.strategy.currentVercelProject?.environment;if (currentEnvironment === undefined || currentEnvironment.length === 0) {return false;}@@ -239,7 +292,3 @@ function currentVercelEnvironmentMatches(input: { readonly payload: JWTPayload }input.payload.environment === currentEnvironment);}--function getCurrentVercelEnvironment(): string | undefined {- return process.env.VERCEL_TARGET_ENV?.trim() || process.env.VERCEL_ENV?.trim() || undefined;-}diff --git a/packages/eve/src/runtime/governance/auth/types.ts b/packages/eve/src/runtime/governance/auth/types.tsindex 33e3f7f9c..5867e3178 100644--- a/packages/eve/src/runtime/governance/auth/types.ts+++ b/packages/eve/src/runtime/governance/auth/types.ts@@ -31,6 +31,12 @@ export interface ResolvedTokenClaimMatchers {readonly subjects?: readonly string[];}+/** One Vercel project and environment accepted by a Vercel OIDC strategy. */+export interface CurrentVercelProject {+ readonly environment?: string;+ readonly projectId: string;+}+/*** Resolved HTTP Basic auth strategy.*/@@ -70,27 +76,26 @@ export interface ResolvedJwtEcdsaAuthStrategy extends ResolvedTokenClaimMatchersexport interface ResolvedOidcAuthStrategy extends ResolvedTokenClaimMatchers {/*** Vercel-platform extension. When `true` and the token's issuer is- * a Vercel OIDC issuer, tokens minted for the current- * `VERCEL_PROJECT_ID` are accepted unconditionally — in addition to+ * a Vercel OIDC issuer, tokens minted for the configured current project+ * are accepted unconditionally — in addition to* the author-supplied `subjects`/`claims` matchers — so the* deployment's own runtime callers (subagent, internal fetches)- * always authenticate. Tokens that additionally match the current- * `VERCEL_TARGET_ENV` / `VERCEL_ENV` are tagged+ * always authenticate. Tokens that additionally match the configured+ * current environment are tagged* `principalType: "runtime"`; other current-project tokens are* tagged `"service"`.*- * Vercel OIDC tokens with an `external_sub` claim are user tokens.- * They must satisfy the current project/environment constraints when- * those environment variables are configured, and then authenticate as- * `principalType: "user"` with `external_sub` as their subject and- * `external_iss` / `connector_id` as their issuer when present.+ * Vercel OIDC tokens with an `external_sub` claim are user tokens. So are+ * development tokens with a `user_id` claim when the configured environment+ * is `development`. Both must satisfy the current project/environment bind.*- * Set exclusively by `verifyVercelOidc`. The generic public+ * Set exclusively by Vercel-specific verification. The generic public* `verifyOidc` always passes `false`.*/readonly acceptCurrentVercelProject: boolean;readonly audiences: readonly string[];readonly clockSkewSeconds: number;+ readonly currentVercelProject?: CurrentVercelProject;readonly discoveryUrl: string;readonly issuer: string;readonly kind: "oidc";diff --git a/packages/eve/src/runtime/governance/auth/vercel-oidc-project.ts b/packages/eve/src/runtime/governance/auth/vercel-oidc-project.tsnew file mode 100644index 000000000..87885653f--- /dev/null+++ b/packages/eve/src/runtime/governance/auth/vercel-oidc-project.ts@@ -0,0 +1,51 @@+import type { CurrentVercelProject } from "#runtime/governance/auth/types.js";++type VercelOidcProjectResolver = () =>+ | CurrentVercelProject+ | undefined+ | Promise<CurrentVercelProject | undefined>;++const VERCEL_OIDC_PROJECT_RESOLVERS = Symbol.for("eve.vercel-oidc-project-resolvers");++type VercelOidcProjectResolverGlobal = typeof globalThis & {+ [VERCEL_OIDC_PROJECT_RESOLVERS]?: WeakMap<Request, VercelOidcProjectResolver>;+};++const globalResolverRegistry = globalThis as VercelOidcProjectResolverGlobal;++if (globalResolverRegistry[VERCEL_OIDC_PROJECT_RESOLVERS] === undefined) {+ globalResolverRegistry[VERCEL_OIDC_PROJECT_RESOLVERS] = new WeakMap();+}++const projectResolvers = globalResolverRegistry[VERCEL_OIDC_PROJECT_RESOLVERS];++/**+ * Binds the current local project only to one request. The global symbol makes+ * the binding visible to both Nitro-inlined and disk-imported eve modules.+ */+export async function withVercelOidcProjectResolver<T>(+ input: {+ readonly request: Request;+ readonly resolveCurrentProject: VercelOidcProjectResolver;+ },+ callback: () => Promise<T> | T,+): Promise<T> {+ const previous = projectResolvers.get(input.request);+ projectResolvers.set(input.request, input.resolveCurrentProject);+ try {+ return await callback();+ } finally {+ if (previous === undefined) {+ projectResolvers.delete(input.request);+ } else {+ projectResolvers.set(input.request, previous);+ }+ }+}++export async function resolveVercelOidcCurrentProject(+ request: Request,+): Promise<CurrentVercelProject | undefined> {+ const resolver = projectResolvers.get(request);+ return resolver === undefined ? undefined : await resolver();+}diff --git a/packages/eve/src/services/dev-client.test.ts b/packages/eve/src/services/dev-client.test.tsindex fca3461e0..ecef7ca42 100644--- a/packages/eve/src/services/dev-client.test.ts+++ b/packages/eve/src/services/dev-client.test.ts@@ -93,6 +93,67 @@ describe("runtime-artifact refresher session rotation", () => {});describe("createDevelopmentRuntimeArtifactSessionRefresher", () => {+ it("forces a rebuild and rotates an active session after a known source change", async () => {+ const requests: Array<{ method: string; url: string }> = [];+ const fetchMock = createDevFetchMock({+ requests,+ revisions: ["snapshot-a", "snapshot-b"],+ });+ vi.stubGlobal("fetch", fetchMock);+ const client = new Client({ host: "http://localhost:3000" });+ const refresher = createDevelopmentRuntimeArtifactSessionRefresher({+ serverUrl: "http://localhost:3000",+ });+ let session = client.session();++ session = await refresher.refreshIdle({+ createSession: () => client.session(),+ session,+ });+ await (await session.send({ message: "first" })).result();+ const before = session;++ session = await refresher.refreshAfterSourceChange({+ createSession: () => client.session(),+ session,+ });++ expect(session).not.toBe(before);+ expect(+ requests.some((request) => {+ const url = new URL(request.url);+ return (+ request.method === "POST" &&+ url.pathname === "/eve/v1/dev/runtime-artifacts/rebuild" &&+ url.searchParams.get("force") === "1"+ );+ }),+ ).toBe(true);+ });++ it("rotates an active session after a known source change without a baseline revision", async () => {+ const fetchMock = createDevFetchMock({+ requests: [],+ revisions: ["snapshot-b"],+ });+ vi.stubGlobal("fetch", fetchMock);+ const client = new Client({ host: "http://localhost:3000" });+ const refresher = createDevelopmentRuntimeArtifactSessionRefresher({+ serverUrl: "http://localhost:3000",+ });+ let session = client.session();++ await (await session.send({ message: "first" })).result();+ const before = session;++ session = await refresher.refreshAfterSourceChange({+ createSession: () => client.session(),+ session,+ });++ expect(session).not.toBe(before);+ });+it("reports local dev artifact revision changes for normal prompts", async () => {const requests: Array<{ method: string; url: string }> = [];const fetchMock = createDevFetchMock({diff --git a/packages/eve/src/services/dev-client.ts b/packages/eve/src/services/dev-client.tsindex fc891d7b4..94bc19253 100644--- a/packages/eve/src/services/dev-client.ts+++ b/packages/eve/src/services/dev-client.ts@@ -31,6 +31,17 @@ export interface DevelopmentRuntimeArtifactSessionRefresher {readonly session: ClientSession;}): Promise<ClientSession>;+ /**+ * Forces one rebuild after a local setup action wrote authored source.+ */+ refreshAfterSourceChange(input: {+ readonly createSession: () => ClientSession;+ readonly onRuntimeArtifactsChanged?: (+ change: DevelopmentRuntimeArtifactChange,+ ) => void | Promise<void>;+ readonly session: ClientSession;+ }): Promise<ClientSession>;+/*** Checks for a runtime-artifact revision change while the UI is idle.*/@@ -88,12 +99,29 @@ class LocalDevelopmentRuntimeArtifactSessionRefresher implements DevelopmentRuntreturn await this.#refreshSession({ ...input, rebuild: false });}+ async refreshAfterSourceChange(input: {+ readonly createSession: () => ClientSession;+ readonly onRuntimeArtifactsChanged?: (+ change: DevelopmentRuntimeArtifactChange,+ ) => void | Promise<void>;+ readonly session: ClientSession;+ }): Promise<ClientSession> {+ return await this.#refreshSession({+ ...input,+ force: true,+ rebuild: true,+ resetActiveSession: true,+ });+ }+async #refreshSession(input: {readonly createSession: () => ClientSession;readonly onRuntimeArtifactsChanged?: (change: DevelopmentRuntimeArtifactChange,) => void | Promise<void>;+ readonly force?: boolean;readonly rebuild: boolean;+ readonly resetActiveSession?: boolean;readonly session: ClientSession;}): Promise<ClientSession> {if (!this.#isLocal) {@@ -102,7 +130,10 @@ class LocalDevelopmentRuntimeArtifactSessionRefresher implements DevelopmentRuntconst revision =(input.rebuild- ? await rebuildDevelopmentRuntimeArtifacts({ serverUrl: this.#serverUrl })+ ? await rebuildDevelopmentRuntimeArtifacts({+ force: input.force,+ serverUrl: this.#serverUrl,+ }): undefined) ??(await readDevelopmentRuntimeArtifactsRevision({ serverUrl: this.#serverUrl }));if (revision === undefined) {@@ -111,10 +142,13 @@ class LocalDevelopmentRuntimeArtifactSessionRefresher implements DevelopmentRuntlet session = input.session;const previousRevision = this.#artifactRevision;- if (previousRevision !== undefined && previousRevision !== revision) {+ const revisionChanged = previousRevision !== undefined && previousRevision !== revision;+ if (revisionChanged || input.resetActiveSession === true) {if (session.state.continuationToken !== undefined) {session = input.createSession();}+ }+ if (revisionChanged) {await input.onRuntimeArtifactsChanged?.({ previousRevision, revision });}this.#artifactRevision = revision;diff --git a/packages/eve/src/services/dev-client/client-options.test.ts b/packages/eve/src/services/dev-client/client-options.test.tsindex f62db2fe8..1cd6625a3 100644--- a/packages/eve/src/services/dev-client/client-options.test.ts+++ b/packages/eve/src/services/dev-client/client-options.test.ts@@ -1,7 +1,8 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import {resolveDevelopmentClientOptions,+ resolveLocalDevelopmentClientOptions,resolveRemoteDevelopmentClientOptions,} from "./client-options.js";import { createDevelopmentCredentialGate } from "./credential-gate.js";@@ -32,6 +33,21 @@ describe("resolveDevelopmentClientOptions", () => {}});+ it("uses an explicit per-request bearer for the local TUI server", () => {+ const token = vi.fn(async () => "user-oidc-token");++ const options = resolveLocalDevelopmentClientOptions({+ serverUrl: "http://127.0.0.1:3000",+ token,+ });++ expect(options).toMatchObject({+ auth: { bearer: token },+ host: "http://127.0.0.1:3000",+ redirect: "manual",+ });+ });+it("binds an authorized credential gate to a non-redirecting client", () => {const credentials = createDevelopmentCredentialGate("https://verified.example.com");diff --git a/packages/eve/src/services/dev-client/client-options.ts b/packages/eve/src/services/dev-client/client-options.tsindex f69c462d9..d29d5119d 100644--- a/packages/eve/src/services/dev-client/client-options.ts+++ b/packages/eve/src/services/dev-client/client-options.ts@@ -11,6 +11,18 @@ export function resolveDevelopmentClientOptions(serverUrl: string): ClientOptionreturn { host: serverUrl };}+/** Builds a non-redirecting local client with an explicit per-request bearer source. */+export function resolveLocalDevelopmentClientOptions(input: {+ readonly serverUrl: string;+ readonly token: () => Promise<string>;+}): ClientOptions {+ return {+ auth: { bearer: input.token },+ host: input.serverUrl,+ redirect: "manual",+ };+}+/** Builds non-redirecting client options backed by one verified credential gate. */export function resolveRemoteDevelopmentClientOptions(input: {readonly credentials: DevelopmentCredentialGate;diff --git a/packages/eve/src/services/dev-client/request-headers.test.ts b/packages/eve/src/services/dev-client/request-headers.test.tsindex 7412c320b..7897d3bf0 100644--- a/packages/eve/src/services/dev-client/request-headers.test.ts+++ b/packages/eve/src/services/dev-client/request-headers.test.ts@@ -1,13 +1,21 @@import { getVercelOidcToken } from "#compiled/@vercel/oidc/index.js";+import { readVercelProjectLink } from "#internal/vercel/project-link.js";import { afterEach, describe, expect, it, vi } from "vitest";-import { resolveDevelopmentOidcToken } from "./request-headers.js";+import {+ resolveDevelopmentOidcToken,+ resolveLinkedDevelopmentOidcToken,+} from "./request-headers.js";vi.mock("#compiled/@vercel/oidc/index.js", async (importOriginal) => ({...(await importOriginal<typeof import("#compiled/@vercel/oidc/index.js")>()),getVercelOidcToken: vi.fn(),}));+vi.mock("#internal/vercel/project-link.js", () => ({+ readVercelProjectLink: vi.fn(),+}));+const target = { ownerId: "team_expected", projectId: "prj_expected" } as const;function token(claims: Record<string, string>): string {@@ -16,6 +24,7 @@ function token(claims: Record<string, string>): string {afterEach(() => {vi.mocked(getVercelOidcToken).mockReset();+ vi.mocked(readVercelProjectLink).mockReset();});describe("resolveDevelopmentOidcToken", () => {@@ -99,3 +108,131 @@ describe("resolveDevelopmentOidcToken", () => {});});});++describe("resolveLinkedDevelopmentOidcToken", () => {+ it("uses the current local project link to resolve the request bearer", async () => {+ vi.mocked(readVercelProjectLink).mockResolvedValue({+ orgId: target.ownerId,+ projectId: target.projectId,+ });+ const expected = token({+ environment: "development",+ owner_id: target.ownerId,+ project_id: target.projectId,+ user_id: "user_ada",+ });+ vi.mocked(getVercelOidcToken).mockResolvedValue(expected);++ await expect(resolveLinkedDevelopmentOidcToken("/workspace")).resolves.toBe(expected);+ expect(getVercelOidcToken).toHaveBeenCalledWith({+ team: target.ownerId,+ project: target.projectId,+ });+ });++ it("refreshes a stale token after the linked project changes", async () => {+ vi.mocked(readVercelProjectLink).mockResolvedValue({+ orgId: target.ownerId,+ projectId: target.projectId,+ });+ const stale = token({+ environment: "development",+ owner_id: target.ownerId,+ project_id: "prj_previous",+ user_id: "user_ada",+ });+ const refreshed = token({+ environment: "development",+ owner_id: target.ownerId,+ project_id: target.projectId,+ user_id: "user_ada",+ });+ vi.mocked(getVercelOidcToken).mockResolvedValueOnce(stale).mockResolvedValueOnce(refreshed);++ await expect(resolveLinkedDevelopmentOidcToken("/workspace")).resolves.toBe(refreshed);+ expect(getVercelOidcToken).toHaveBeenNthCalledWith(1, {+ team: target.ownerId,+ project: target.projectId,+ });+ expect(getVercelOidcToken).toHaveBeenNthCalledWith(2, {+ team: target.ownerId,+ project: target.projectId,+ expirationBufferMs: Number.MAX_SAFE_INTEGER,+ });+ });++ it("refreshes a matching token that cannot authenticate a local user", async () => {+ vi.mocked(readVercelProjectLink).mockResolvedValue({+ orgId: target.ownerId,+ projectId: target.projectId,+ });+ const deploymentToken = token({+ environment: "preview",+ owner_id: target.ownerId,+ project_id: target.projectId,+ });+ const refreshed = token({+ environment: "development",+ owner_id: target.ownerId,+ project_id: target.projectId,+ user_id: "user_ada",+ });+ vi.mocked(getVercelOidcToken)+ .mockResolvedValueOnce(deploymentToken)+ .mockResolvedValueOnce(refreshed);++ await expect(resolveLinkedDevelopmentOidcToken("/workspace")).resolves.toBe(refreshed);+ expect(getVercelOidcToken).toHaveBeenNthCalledWith(2, {+ team: target.ownerId,+ project: target.projectId,+ expirationBufferMs: Number.MAX_SAFE_INTEGER,+ });+ });++ it("does not send a bearer when the local directory is unlinked", async () => {+ vi.mocked(readVercelProjectLink).mockResolvedValue(undefined);++ await expect(resolveLinkedDevelopmentOidcToken("/workspace")).resolves.toBe("");+ expect(getVercelOidcToken).not.toHaveBeenCalled();+ });++ it("falls back to no bearer when the local OIDC token is unavailable", async () => {+ vi.mocked(readVercelProjectLink).mockResolvedValue({+ orgId: target.ownerId,+ projectId: target.projectId,+ });+ vi.mocked(getVercelOidcToken).mockRejectedValue(new Error("not logged in"));++ await expect(resolveLinkedDevelopmentOidcToken("/workspace")).resolves.toBe("");+ });++ it("reads the current project link for every request", async () => {+ const first = token({+ environment: "development",+ owner_id: "team_first",+ project_id: "prj_first",+ user_id: "user_ada",+ });+ const second = token({+ environment: "development",+ owner_id: "team_second",+ project_id: "prj_second",+ user_id: "user_ada",+ });+ vi.mocked(readVercelProjectLink)+ .mockResolvedValueOnce({ orgId: "team_first", projectId: "prj_first" })+ .mockResolvedValueOnce({ orgId: "team_second", projectId: "prj_second" });+ vi.mocked(getVercelOidcToken).mockResolvedValueOnce(first).mockResolvedValueOnce(second);++ await expect(resolveLinkedDevelopmentOidcToken("/workspace")).resolves.toBe(first);+ await expect(resolveLinkedDevelopmentOidcToken("/workspace")).resolves.toBe(second);+ expect(getVercelOidcToken).toHaveBeenNthCalledWith(1, {+ team: "team_first",+ project: "prj_first",+ });+ expect(getVercelOidcToken).toHaveBeenNthCalledWith(2, {+ team: "team_second",+ project: "prj_second",+ });+ });+});diff --git a/packages/eve/src/services/dev-client/request-headers.ts b/packages/eve/src/services/dev-client/request-headers.tsindex fef4fc9f9..b551d9ad8 100644--- a/packages/eve/src/services/dev-client/request-headers.ts+++ b/packages/eve/src/services/dev-client/request-headers.ts@@ -1,4 +1,5 @@import { getVercelOidcToken } from "#compiled/@vercel/oidc/index.js";+import { readVercelProjectLink } from "#internal/vercel/project-link.js";import { toErrorMessage } from "#shared/errors.js";import { z } from "zod";@@ -7,6 +8,11 @@ const VercelOidcClaimsSchema = z.object({project_id: z.string().min(1),});+const LocalDevelopmentUserOidcClaimsSchema = VercelOidcClaimsSchema.extend({+ environment: z.literal("development"),+ user_id: z.string().min(1),+});+/** Vercel owner and project expected to have minted an OIDC token. */export interface DevelopmentOidcTarget {readonly ownerId: string;@@ -60,18 +66,49 @@ export async function resolveDevelopmentOidcToken(}}+/**+ * Resolves the current linked project's Vercel OIDC token for a local TUI request.+ *+ * An unavailable token deliberately becomes no bearer, so ordinary local+ * requests still reach `localDev()`; user-scoped Connect requests then report+ * that they need a Vercel user rather than trusting a client-supplied failure.+ */+export async function resolveLinkedDevelopmentOidcToken(workspaceRoot: string): Promise<string> {+ const link = await readVercelProjectLink(workspaceRoot);+ if (link === undefined) return "";++ const target = {+ ownerId: link.orgId,+ projectId: link.projectId,+ };+ const result = await resolveDevelopmentOidcToken(target);+ if (result.kind === "resolved" && isLocalDevelopmentUserToken(result.token)) return result.token;++ // @vercel/oidc can return an unexpired ambient token before it honors the+ // linked target. A local Connect request needs a development user token, so+ // retry only those stale or non-user candidates with an explicit refresh.+ if (result.kind !== "resolved" && result.kind !== "target-mismatch") return "";+ const refreshed = await resolveDevelopmentOidcToken({ ...target, forceRefresh: true });+ return refreshed.kind === "resolved" && isLocalDevelopmentUserToken(refreshed.token)+ ? refreshed.token+ : "";+}++function isLocalDevelopmentUserToken(token: string): boolean {+ const decoded = decodeOidcPayload(token);+ return decoded !== undefined && LocalDevelopmentUserOidcClaimsSchema.safeParse(decoded).success;+}+function validateDevelopmentOidcToken(token: string,input: DevelopmentOidcTarget,): Exclude<DevelopmentOidcTokenResolution, { readonly kind: "resolution-failed" }> {- const payload = token.split(".")[1];- if (!payload) return { kind: "malformed-token", reason: "missing-payload" };-- let decoded: unknown;- try {- decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));- } catch {- return { kind: "malformed-token", reason: "invalid-json-payload" };+ const decoded = decodeOidcPayload(token);+ if (decoded === undefined) {+ const payload = token.split(".")[1];+ return payload+ ? { kind: "malformed-token", reason: "invalid-json-payload" }+ : { kind: "malformed-token", reason: "missing-payload" };}const claims = VercelOidcClaimsSchema.safeParse(decoded);@@ -93,6 +130,16 @@ function validateDevelopmentOidcToken(return { kind: "resolved", token };}+function decodeOidcPayload(token: string): unknown | undefined {+ const payload = token.split(".")[1];+ if (!payload) return undefined;+ try {+ return JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));+ } catch {+ return undefined;+ }+}+/*** Vercel header used to bypass preview protection for framework-owned routes* during local CLI development. Paired with a Protection Bypass fordiff --git a/packages/eve/src/services/dev-client/runtime-artifacts.ts b/packages/eve/src/services/dev-client/runtime-artifacts.tsindex c6a658de2..88e453263 100644--- a/packages/eve/src/services/dev-client/runtime-artifacts.ts+++ b/packages/eve/src/services/dev-client/runtime-artifacts.ts@@ -26,10 +26,12 @@ export async function readDevelopmentRuntimeArtifactsRevision(input: {}export async function rebuildDevelopmentRuntimeArtifacts(input: {+ readonly force?: boolean;readonly serverUrl: string;}): Promise<string | undefined> {try {const url = new URL(EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH, input.serverUrl);+ if (input.force === true) url.searchParams.set("force", "1");const response = await fetch(url, { method: "POST" });return await parseDevelopmentRuntimeArtifactsRevision(response);} catch {diff --git a/packages/eve/src/setup/boxes/add-connections.test.ts b/packages/eve/src/setup/boxes/add-connections.test.tsindex 76d8bc088..135e3596f 100644--- a/packages/eve/src/setup/boxes/add-connections.test.ts+++ b/packages/eve/src/setup/boxes/add-connections.test.ts@@ -42,7 +42,10 @@ function makeBoxes(asker: headless ? headlessAsker() : interactiveAsker(options.prompter),headless,}),- addConnections({ prompter: options.prompter, deps: options.deps }),+ addConnections({+ prompter: options.prompter,+ deps: options.deps,+ }),];}@@ -59,14 +62,40 @@ function createDeps() {envKeysAdded: [],envKeysRequired: [],})),+ listAuthoredConnections: vi.fn<AddConnectionsDeps["listAuthoredConnections"]>(async () => []),+ readProjectLink: vi.fn<AddConnectionsDeps["readProjectLink"]>(async () => ({+ orgId: "org_1",+ projectId: "prj_demo",+ })),setupConnectionConnector: vi.fn<AddConnectionsDeps["setupConnectionConnector"]>(async () => ({- kind: "patched",- created: true,+ kind: "existing",connectorUid: "oauth/connector-1",})),+ cleanupCreatedConnectionConnector: vi.fn<+ AddConnectionsDeps["cleanupCreatedConnectionConnector"]+ >(async () => {}),};}+function createdConnectorDeps() {+ const deps = createDeps();+ deps.setupConnectionConnector.mockResolvedValueOnce({+ kind: "created",+ connectorUid: "linear/new",+ connectorId: "scl_new",+ });+ return deps;+}++function runCreatedConnector(deps: ReturnType<typeof createDeps>) {+ return runInteractive(+ makeBoxes({ prompter: createPrompter(), presetConnections: ["linear"], deps }),+ resolvedState(),+ silentSink,+ snapshot,+ );+}+function resolvedState(): SetupState {const state = createDefaultSetupState();state.projectPath = { kind: "resolved", inPlace: false, path: "/tmp/project" };@@ -118,10 +147,16 @@ describe("selectConnections + addConnections boxes", () => {expect.objectContaining({slug: "linear",service: "mcp.linear.app",- connectionFilePath: "/tmp/project/agent/connections/linear.ts",projectRoot: "/tmp/project",}),);+ expect(deps.ensureConnection).toHaveBeenCalledWith(+ expect.objectContaining({+ entry: expect.objectContaining({+ auth: expect.objectContaining({ connector: "oauth/connector-1" }),+ }),+ }),+ );});test("uses the picker selection when no preset is given", async () => {@@ -186,11 +221,12 @@ describe("selectConnections + addConnections boxes", () => {entry: expect.objectContaining({slug: "mycorp",mcp: { url: "https://mcp.mycorp.dev/sse" },- auth: { kind: "connect", connector: "mycorp" },+ auth: { kind: "connect", connector: "oauth/connector-1" },}),}),);- // The custom MCP host becomes the Connect service.+ // Custom MCP URLs retain the host fallback because only curated providers+ // declare a verified Vercel Connect service identifier.expect(deps.setupConnectionConnector).toHaveBeenCalledWith(expect.objectContaining({ slug: "mycorp", service: "mcp.mycorp.dev" }),);@@ -272,6 +308,7 @@ describe("selectConnections + addConnections boxes", () => {test("skips provisioning when the connection file already exists", async () => {const deps = createDeps();+ deps.listAuthoredConnections.mockResolvedValueOnce(["linear"]);deps.ensureConnection.mockResolvedValueOnce({slug: "linear",protocol: "mcp",@@ -294,6 +331,25 @@ describe("selectConnections + addConnections boxes", () => {);});+ test("removes a connector created before a scaffold failure", async () => {+ const deps = createdConnectorDeps();+ deps.ensureConnection.mockRejectedValueOnce(new Error("write failed"));++ await expect(runCreatedConnector(deps)).rejects.toThrow("write failed");+ expect(deps.cleanupCreatedConnectionConnector).toHaveBeenCalledWith(+ expect.objectContaining({ connectorId: "scl_new" }),+ );+ });++ test("reports both scaffold and connector cleanup failures", async () => {+ const deps = createdConnectorDeps();+ deps.ensureConnection.mockRejectedValueOnce(new Error("write failed"));+ deps.cleanupCreatedConnectionConnector.mockRejectedValueOnce(+ new Error("remove scl_new manually"),+ );+ await expect(runCreatedConnector(deps)).rejects.toThrow("write failed remove scl_new manually");+ });+test("is skipped in headless mode when no connections are requested", async () => {const deps = createDeps();const boxes = makeBoxes({ prompter: createPrompter(), headless: true, deps });@@ -330,10 +386,6 @@ describe("selectConnections + addConnections boxes", () => {// project stays unresolved: the link box did not record a resolution.state.project = { kind: "unresolved" };const deps = createDeps();- deps.setupConnectionConnector.mockImplementation(async (opts) => {- await opts.linkProject?.();- return { kind: "patched", created: true, connectorUid: "oauth/linear-1" };- });const boxes = makeBoxes({prompter: createPrompter(),presetConnections: ["linear"],@@ -344,22 +396,4 @@ describe("selectConnections + addConnections boxes", () => {/none was resolved/,);});-- test("hands the linked project id to the connector provisioning step", async () => {- const deps = createDeps();- let linkedProjectId: string | undefined;- deps.setupConnectionConnector.mockImplementation(async (opts) => {- linkedProjectId = await opts.linkProject?.();- return { kind: "patched", created: true, connectorUid: "oauth/linear-1" };- });- const boxes = makeBoxes({- prompter: createPrompter(),- presetConnections: ["linear"],- deps,- });-- await runInteractive(boxes, resolvedState(), silentSink, snapshot);-- expect(linkedProjectId).toBe("prj_demo");- });});diff --git a/packages/eve/src/setup/boxes/add-connections.ts b/packages/eve/src/setup/boxes/add-connections.tsindex 0426325eb..ff360ef73 100644--- a/packages/eve/src/setup/boxes/add-connections.ts+++ b/packages/eve/src/setup/boxes/add-connections.ts@@ -1,10 +1,20 @@-import { ensureConnection, type ConnectionMutationResult } from "#setup/scaffold/index.js";+import {+ ensureConnection,+ listAuthoredConnections,+ type ConnectionInput,+ type ConnectionMutationResult,+} from "#setup/scaffold/index.js";import type { ChannelSetupLog } from "#setup/cli/index.js";-import { setupConnectionConnector } from "../connection-connector.js";+import {+ cleanupCreatedConnectionConnector,+ setupConnectionConnector,+} from "../connection-connector.js";+import { canonicalConnectorNameForEntry } from "../scaffold/connections/catalog.js";import {isProjectResolved,mergeProjectResolution,+ readProjectLink,type ProjectResolution,} from "../project-resolution.js";import type { Prompter } from "../prompter.js";@@ -16,12 +26,16 @@ import { CONNECT_REQUIRES_VERCEL } from "./select-connections.js";/** Injected for tests; defaults to the real scaffold and Connect effects. */export interface AddConnectionsDeps {ensureConnection: typeof ensureConnection;+ listAuthoredConnections: typeof listAuthoredConnections;+ readProjectLink: typeof readProjectLink;setupConnectionConnector: typeof setupConnectionConnector;+ cleanupCreatedConnectionConnector: typeof cleanupCreatedConnectionConnector;}export interface AddConnectionsOptions {- /** Carries the follow-up log lines and `perform`'s progress output. The box never prompts. */+ /** Carries connector selection prompts and provisioning output. */prompter: Prompter;+ signal?: AbortSignal;deps?: AddConnectionsDeps;}@@ -38,17 +52,28 @@ function logFollowUp(log: ChannelSetupLog, result: ConnectionMutationResult): vo}}+function withConnectorUid(entry: ConnectionInput, connectorUid: string): ConnectionInput {+ if (entry.auth?.kind !== "connect") {+ throw new Error(`Connection ${entry.slug} is not configured for Vercel Connect.`);+ }+ return { ...entry, auth: { ...entry.auth, connector: connectorUid } };+}+/*** THE CONNECTIONS BOX: executes the {@link ConnectionPlan}s the- * select-connections box recorded during the interview. Prompts for nothing —- * every decision (slug, protocol, entry, provisioning mode) was resolved at- * selection time — and only runs effects: the file scaffold, the follow-up log- * lines, and the Connect connector provisioning against the linked project.+ * select-connections box recorded during the interview. It scaffolds each file+ * and resolves the concrete Connect connector against the linked project.*/export function addConnections(options: AddConnectionsOptions,): SetupBox<SetupState, null, ProjectResolution> {- const deps = options.deps ?? { ensureConnection, setupConnectionConnector };+ const deps = options.deps ?? {+ ensureConnection,+ listAuthoredConnections,+ readProjectLink,+ setupConnectionConnector,+ cleanupCreatedConnectionConnector,+ };return {id: "add-connections",@@ -67,57 +92,96 @@ export function addConnections(const projectRoot = requireProjectPath(state);const noVercel = !hasVercelProject(state);const project = state.project;+ const authored = new Set(await deps.listAuthoredConnections(projectRoot));for (const plan of state.connectionSelection) {- const result = await deps.ensureConnection({- projectRoot,- slug: plan.slug,- protocol: plan.protocol,- entry: plan.entry,- });- logFollowUp(log, result);- // Whether the file already existed is only known at effect time; an- // existing connection keeps its connector, so provisioning is skipped.- if (result.action === "skipped") continue;+ if (authored.has(plan.slug)) {+ const result = await deps.ensureConnection({+ projectRoot,+ slug: plan.slug,+ protocol: plan.protocol,+ entry: plan.entry,+ });+ logFollowUp(log, result);+ continue;+ }++ let entry = plan.entry;+ let createdConnectorId: string | undefined;switch (plan.provision.kind) {- case "connect":- await deps.setupConnectionConnector({+ case "connect": {+ const canonicalConnectorName = canonicalConnectorNameForEntry(plan.entry);+ if (canonicalConnectorName === undefined) {+ throw new Error(`Connection ${plan.slug} has no canonical connector name.`);+ }+ const connector = await deps.setupConnectionConnector({log,+ prompter: options.prompter,projectRoot,- slug: result.slug,+ slug: plan.slug,service: plan.provision.service,- connectionFilePath: result.filePath,- // The project was linked up front by the link box; Connect- // provisioning reuses it. The link box is a hard invariant once- // Vercel is in play: an unresolved project here means it did not- // run or did not record a resolution.- linkProject: async () => {- if (noVercel) {- throw new Error(CONNECT_REQUIRES_VERCEL);- }- if (!isProjectResolved(project)) {- throw new Error(- "Expected a linked Vercel project for Connect, but none was resolved.",- );- }- return projectIdFromResolution(project);- },+ canonicalConnectorName,+ project: await resolveConnectionProject({+ noVercel,+ project,+ projectRoot,+ readProjectLink: deps.readProjectLink,+ }),+ signal: options.signal,});+ entry = withConnectorUid(entry, connector.connectorUid);+ if (connector.kind === "created") createdConnectorId = connector.connectorId;break;+ }case "command-hint":log.info(- `Run \`vercel connect create ${plan.provision.service} --name ${result.slug}\`, then set the connector UID in agent/connections/${result.slug}.ts.`,+ `Run \`vercel connect create ${plan.provision.service} --name ${plan.slug}\`, then set the connector UID in agent/connections/${plan.slug}.ts.`,);break;case "connect-manual":log.warning(- `Could not determine a Connect service for ${result.slug}. Create the connector manually and set its UID in agent/connections/${result.slug}.ts.`,+ `Could not determine a Connect service for ${plan.slug}. Create the connector manually and set its UID in agent/connections/${plan.slug}.ts.`,);break;case "none":break;}++ let result: ConnectionMutationResult;+ try {+ result = await deps.ensureConnection({+ projectRoot,+ slug: plan.slug,+ protocol: plan.protocol,+ entry,+ });+ } catch (error) {+ if (createdConnectorId !== undefined) {+ try {+ await deps.cleanupCreatedConnectionConnector({+ log,+ projectRoot,+ connectorId: createdConnectorId,+ });+ } catch (cleanupError) {+ throw new AggregateError(+ [error, cleanupError],+ `${error instanceof Error ? error.message : String(error)} ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,+ );+ }+ }+ throw error;+ }+ if (result.action === "skipped" && createdConnectorId !== undefined) {+ await deps.cleanupCreatedConnectionConnector({+ log,+ projectRoot,+ connectorId: createdConnectorId,+ });+ }+ logFollowUp(log, result);+ if (result.action !== "skipped") authored.add(result.slug);}return project;},@@ -127,3 +191,26 @@ export function addConnections(},};}++async function resolveConnectionProject(input: {+ noVercel: boolean;+ project: ProjectResolution;+ projectRoot: string;+ readProjectLink: typeof readProjectLink;+}) {+ if (input.noVercel) {+ throw new Error(CONNECT_REQUIRES_VERCEL);+ }+ if (!isProjectResolved(input.project)) {+ throw new Error("Expected a linked Vercel project for Connect, but none was resolved.");+ }++ const linkedProject = await input.readProjectLink(input.projectRoot);+ if (+ linkedProject === undefined ||+ linkedProject.projectId !== projectIdFromResolution(input.project)+ ) {+ throw new Error("A linked Vercel project is required. Run `eve link`, then retry /connect.");+ }+ return linkedProject;+}diff --git a/packages/eve/src/setup/boxes/resolve-provisioning.ts b/packages/eve/src/setup/boxes/resolve-provisioning.tsindex eb60300a0..c4aea58bd 100644--- a/packages/eve/src/setup/boxes/resolve-provisioning.ts+++ b/packages/eve/src/setup/boxes/resolve-provisioning.ts@@ -77,6 +77,7 @@ export interface ResolveProvisioningOptions {* team selection to the existing-project picker.*/projectSelection?: "create-or-link" | "existing-only";+ teamSelectMessage?: (currentTeam: string) => string;deps?: ResolveProvisioningDeps;}@@ -292,7 +293,8 @@ export function resolveProvisioning(if (deployVercel) {await deps.requireAuth(parent(), prompter, { signal });- const team = await deps.pickTeam(prompter, parent(), undefined, { signal });+ const teamOptions = { signal, selectMessage: options.teamSelectMessage };+ const team = await deps.pickTeam(prompter, parent(), undefined, teamOptions);const projectOptions = [{value: "new" as const,diff --git a/packages/eve/src/setup/cli/channel-setup-prompter.ts b/packages/eve/src/setup/cli/channel-setup-prompter.tsindex e7c43e0d6..a31ce655c 100644--- a/packages/eve/src/setup/cli/channel-setup-prompter.ts+++ b/packages/eve/src/setup/cli/channel-setup-prompter.ts@@ -28,6 +28,11 @@ export interface ChannelSetupChoice {/** Optional interaction capability for a long-running setup operation. */export type ChannelSetupAwaitChoice = (options: ChannelSetupChoiceOptions) => ChannelSetupChoice;+/** Why a live setup indicator is waiting. */+export type SetupSpinnerIntent =+ | { kind: "progress" }+ | { kind: "external-action"; emphasis: string };+/** Status and subprocess output operations used by shared setup flows. */export interface ChannelSetupLog {message(text: string): void;@@ -44,7 +49,7 @@ export interface ChannelSetupLog {* (which have no live status surface) can omit it and callers fall back to* a persisted message.*/- spinner?(message: string): { stop(): void };+ spinner?(message: string, intent?: SetupSpinnerIntent): { stop(): void };}/**@@ -57,8 +62,9 @@ export async function withPhase<T>(log: ChannelSetupLog,message: string,task: () => Promise<T>,+ intent?: SetupSpinnerIntent,): Promise<T> {- const spinner = log.spinner?.(message);+ const spinner = log.spinner?.(message, intent);if (!spinner) log.message(message);try {return await task();diff --git a/packages/eve/src/setup/cli/index.ts b/packages/eve/src/setup/cli/index.tsindex 039efd4ee..88c384e59 100644--- a/packages/eve/src/setup/cli/index.ts+++ b/packages/eve/src/setup/cli/index.ts@@ -6,6 +6,7 @@ export {type ChannelSetupChoiceOptions,type ChannelSetupLog,type DisabledChannelReasons,+ type SetupSpinnerIntent,withPhase,} from "./channel-setup-prompter.js";export { createPromptCommandOutput, type PromptCommandLog } from "./command-output.js";diff --git a/packages/eve/src/setup/cli/prompt-ui.ts b/packages/eve/src/setup/cli/prompt-ui.tsindex 795ec442e..2553b5993 100644--- a/packages/eve/src/setup/cli/prompt-ui.ts+++ b/packages/eve/src/setup/cli/prompt-ui.ts@@ -34,6 +34,8 @@ export interface PromptColors {export interface PromptOption<T extends PromptValue> {value: T;label: string;+ /** Completion action kept after searchable results instead of being filtered. */+ trailingAction?: boolean;/** Supporting copy; stacked prompts render newline-separated text on separate rows. */hint?: string;/** Short inline annotation shown dimmed only while the cursor is on this row. */diff --git a/packages/eve/src/setup/cli/select-state.test.ts b/packages/eve/src/setup/cli/select-state.test.tsindex 1b6fd213a..0f7863d33 100644--- a/packages/eve/src/setup/cli/select-state.test.ts+++ b/packages/eve/src/setup/cli/select-state.test.ts@@ -49,15 +49,21 @@ describe("filterOptions", () => {});it("returns nothing when no option matches", () => {- expect(filterOptions(OPTIONS, "zzz")).toEqual([]);+ const done = { value: "done", label: "Done", trailingAction: true };+ expect(filterOptions([...OPTIONS, done], "zzz")).toEqual([done]);});it("appends the search action after local matches", () => {- const visible = filterOptions([{ value: "veto", label: "veto" }], "v", {- label: (query) => `Search for '${query}'`,- });+ const visible = filterOptions(+ [+ { value: "veto", label: "veto" },+ { value: "done", label: "Done", trailingAction: true },+ ],+ "v",+ { label: (query) => `Search for '${query}'` },+ );- expect(visible.map((option) => option.label)).toEqual(["veto", "Search for 'v'"]);+ expect(visible.map((option) => option.label)).toEqual(["veto", "Search for 'v'", "Done"]);expect(searchActionQuery(visible[1]?.value ?? "")).toBe("v");});diff --git a/packages/eve/src/setup/cli/select-state.ts b/packages/eve/src/setup/cli/select-state.tsindex 8f8289d0d..88dd53cf0 100644--- a/packages/eve/src/setup/cli/select-state.ts+++ b/packages/eve/src/setup/cli/select-state.ts@@ -76,13 +76,16 @@ export function filterOptions(const normalizedQuery = query.toLowerCase();const matches = options.filter((option) =>- option.label.toLowerCase().includes(normalizedQuery) ||- option.value.toLowerCase().includes(normalizedQuery) ||- (option.hint?.toLowerCase().includes(normalizedQuery) ?? false) ||- (option.focusHint?.toLowerCase().includes(normalizedQuery) ?? false),+ option.trailingAction !== true &&+ (option.label.toLowerCase().includes(normalizedQuery) ||+ option.value.toLowerCase().includes(normalizedQuery) ||+ (option.hint?.toLowerCase().includes(normalizedQuery) ?? false) ||+ (option.focusHint?.toLowerCase().includes(normalizedQuery) ?? false)),);- if (searchAction === undefined) return matches;- return [...matches, { value: searchActionValue(query), label: searchAction.label(query) }];+ if (searchAction !== undefined) {+ matches.push({ value: searchActionValue(query), label: searchAction.label(query) });+ }+ return [...matches, ...options.filter((option) => option.trailingAction === true)];}/** A row the cursor can land on: neither disabled nor locked. */diff --git a/packages/eve/src/setup/connection-connector.integration.test.ts b/packages/eve/src/setup/connection-connector.integration.test.tsindex ae42f2a76..25ea23add 100644--- a/packages/eve/src/setup/connection-connector.integration.test.ts+++ b/packages/eve/src/setup/connection-connector.integration.test.ts@@ -1,17 +1,14 @@-import { mkdtemp, mkdir, readFile, writeFile, rm } from "node:fs/promises";+import { mkdtemp, rm } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";-import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import type { ChannelSetupLog } from "#setup/cli/index.js";+import { createFakePrompter } from "#internal/testing/fake-prompter.js";import { captureVercel, runVercel, runVercelCaptureStdout } from "#setup/primitives/run-vercel.js";+import type { PrompterValue, SingleSelectOptions } from "#setup/prompter.js";-import {- parseCreatedConnector,- pickConnectConnector,- setupConnectionConnector,-} from "./connection-connector.js";+import { parseCreatedConnector, setupConnectionConnector } from "./connection-connector.js";vi.mock("#setup/primitives/run-vercel.js", () => ({captureVercel: vi.fn(),@@ -19,374 +16,222 @@ vi.mock("#setup/primitives/run-vercel.js", () => ({runVercelCaptureStdout: vi.fn(),}));-const mockedCaptureVercel = vi.mocked(captureVercel);-const mockedRunVercel = vi.mocked(runVercel);-const mockedRunVercelCaptureStdout = vi.mocked(runVercelCaptureStdout);-+const capture = vi.mocked(captureVercel);+const run = vi.mocked(runVercel);+const create = vi.mocked(runVercelCaptureStdout);const SERVICE = "mcp.linear.app";+const CANONICAL_UID = "mcp.linear.app/linear";+const CANONICAL_NAME = "linear";++function jsonResult(value: unknown) {+ return { ok: true as const, stdout: JSON.stringify(value) };+}-/** `vercel connect create … -F json` stdout payload on CLI 54.x. */-function createConnectorJson(uid: string, id = "scl_linear"): string {- return JSON.stringify({ uid, id, type: "oauth", name: "linear" });+function connectorResult(uid: string, id: string, subject: "app" | "user") {+ return jsonResult({ uid, id, service: SERVICE, supportedSubjectTypes: [subject] });}-describe("parseCreatedConnector", () => {- test("reads uid and id from `vercel connect create -F json` stdout", () => {- expect(parseCreatedConnector(createConnectorJson("linear/my-agent", "scl_1"))).toEqual({- uid: "linear/my-agent",+describe("connector response parsing", () => {+ it("rejects created connectors without user support", () => {+ const response = { uid: "linear/acme", id: "scl_1", supportedSubjectTypes: ["user"] };+ expect(parseCreatedConnector(JSON.stringify(response))).toEqual({+ uid: "linear/acme",id: "scl_1",});- });-- test("tolerates surrounding whitespace", () => {- expect(parseCreatedConnector(`\n ${createConnectorJson("linear/x")} \n`)?.uid).toBe(- "linear/x",- );- });-- test("returns undefined for empty, non-JSON, or shape-mismatched stdout", () => {- expect(parseCreatedConnector("")).toBeUndefined();- expect(parseCreatedConnector(" ")).toBeUndefined();- expect(parseCreatedConnector("Vercel CLI 54.9.1")).toBeUndefined();- expect(parseCreatedConnector(JSON.stringify({ uid: "linear/x" }))).toBeUndefined();- expect(parseCreatedConnector(JSON.stringify({ id: "scl_1" }))).toBeUndefined();- expect(parseCreatedConnector(JSON.stringify([1, 2, 3]))).toBeUndefined();- });-});--describe("pickConnectConnector", () => {- test("reads the `connectors` key emitted by `vercel connect list -F json`", () => {- const list = {- connectors: [{ uid: "linear/my-agent", id: "scl_1", type: "oauth", createdAt: 1 }],- };- expect(pickConnectConnector(list, SERVICE, undefined)?.uid).toBe("linear/my-agent");- });-- test("prefers a connector attached to the project", () => {- const list = {- connectors: [- { uid: "linear/a", id: "1", type: "oauth", createdAt: 1, projects: [] },- { uid: "linear/b", id: "2", type: "oauth", createdAt: 2, projects: [{ id: "prj_1" }] },- ],- };- expect(pickConnectConnector(list, SERVICE, "prj_1")?.uid).toBe("linear/b");- });-- test("falls back to the newest connector when none are attached", () => {- const list = {- connectors: [- { uid: "linear/a", id: "1", type: "oauth", createdAt: 1 },- { uid: "linear/b", id: "2", type: "oauth", createdAt: 5 },- ],- };- expect(pickConnectConnector(list, SERVICE, undefined)?.uid).toBe("linear/b");- });-- test("accepts connectors whose type is not `oauth` (managed MCP connectors)", () => {- const list = { connectors: [{ uid: "linear/mcp", id: "1", type: "mcp", createdAt: 1 }] };- expect(pickConnectConnector(list, SERVICE, undefined)?.uid).toBe("linear/mcp");- });-- test("defensively skips connectors whose reported service differs", () => {- const list = {- connectors: [- { uid: "notion/x", id: "1", type: "oauth", service: "mcp.notion.com", createdAt: 8 },- { uid: "linear/x", id: "2", type: "oauth", service: SERVICE, createdAt: 1 },- ],- };- expect(pickConnectConnector(list, SERVICE, undefined)?.uid).toBe("linear/x");- });-- test("falls back to the legacy `clients` key for older CLI builds", () => {- const list = { clients: [{ uid: "linear/legacy", id: "1", type: "oauth", createdAt: 1 }] };- expect(pickConnectConnector(list, SERVICE, undefined)?.uid).toBe("linear/legacy");- });-- test("returns undefined for malformed input", () => {- expect(pickConnectConnector(null, SERVICE, undefined)).toBeUndefined();- expect(pickConnectConnector({}, SERVICE, undefined)).toBeUndefined();- expect(pickConnectConnector({ connectors: "nope" }, SERVICE, undefined)).toBeUndefined();+ expect(+ parseCreatedConnector(JSON.stringify({ ...response, supportedSubjectTypes: ["app"] })),+ ).toBeUndefined();});});-function createTestLog(): ChannelSetupLog {- return {- message: vi.fn(),- info: vi.fn(),- success: vi.fn(),- warning: vi.fn(),- error: vi.fn(),- commandOutput: vi.fn(),- };-}--/** Connector list payload as emitted by `vercel connect list -F json` on CLI 54.x. */-function connectListV54(connectorUid: string, projectId: string) {- return JSON.stringify({- connectors: [- {- uid: connectorUid,- id: "scl_linear",- name: "linear",- type: "oauth",- typeName: "Linear",- createdAt: 2,- icon: null,- backgroundColor: null,- accentColor: null,- projects: [{ id: projectId, name: "my-agent" }],- hasMoreProjects: false,- },- ],- cursor: undefined,- });-}--describe("setupConnectionConnector (end-to-end)", () => {+describe("setupConnectionConnector", () => {let projectRoot: string;- let connectionFilePath: string;- const PROJECT_ID = "prj_ExampleProjectId0000000000";beforeEach(async () => {- vi.clearAllMocks();- // The connector attach succeeds by default; failure is exercised separately.- mockedRunVercel.mockResolvedValue(true);- projectRoot = await mkdtemp(join(tmpdir(), "eve-setup-connection-"));- await mkdir(join(projectRoot, ".vercel"), { recursive: true });- await writeFile(- join(projectRoot, ".vercel", "project.json"),- JSON.stringify({ projectId: PROJECT_ID, orgId: "team_x" }),- "utf8",- );- await mkdir(join(projectRoot, "agent", "connections"), { recursive: true });- connectionFilePath = join(projectRoot, "agent", "connections", "linear.ts");- // Mirrors the scaffolder's emitted `auth: connect("<slug>")` placeholder.- await writeFile(- connectionFilePath,- [- 'import { defineMcpClientConnection } from "eve/connections";',- 'import { connect } from "@vercel/connect";',- "",- "export default defineMcpClientConnection({",- ' url: "https://mcp.linear.app/sse",',- ' auth: connect("linear"),',- "});",- "",- ].join("\n"),- "utf8",- );+ capture.mockReset();+ run.mockReset();+ create.mockReset();+ projectRoot = await mkdtemp(join(tmpdir(), "eve-connect-"));});afterEach(async () => {await rm(projectRoot, { recursive: true, force: true });});- test("resolves the UID from `connect create -F json` without a follow-up list", async () => {- mockedRunVercelCaptureStdout.mockResolvedValue({- ok: true,- stdout: createConnectorJson("linear/my-agent"),- });-- const result = await setupConnectionConnector({- log: createTestLog(),+ function options(prompter = createFakePrompter().prompter) {+ return {+ log: prompter.log,+ prompter,projectRoot,slug: "linear",service: SERVICE,- connectionFilePath,- });-- expect(result).toEqual({ kind: "patched", created: true, connectorUid: "linear/my-agent" });-- // Created with the catalog service identifier, slug name, and JSON output.- expect(mockedRunVercelCaptureStdout).toHaveBeenCalledWith(- ["connect", "create", SERVICE, "--name", "linear", "-F", "json"],- expect.objectContaining({ cwd: projectRoot }),+ canonicalConnectorName: CANONICAL_NAME,+ project: { projectId: "prj_1", orgId: "org_1" },+ };+ }++ it("attaches the canonical connector only after confirming user authorization", async () => {+ capture+ .mockResolvedValueOnce(+ jsonResult({ connectors: [{ uid: CANONICAL_UID, id: "scl_canonical" }] }),+ )+ .mockResolvedValueOnce(connectorResult(CANONICAL_UID, "scl_canonical", "user"));+ run.mockResolvedValue(true);++ await expect(setupConnectionConnector(options())).resolves.toEqual({+ kind: "existing",+ connectorUid: CANONICAL_UID,+ });+ expect(capture).toHaveBeenCalledWith(+ expect.arrayContaining(["connect", "list", "--service", SERVICE]),+ expect.any(Object),);- // The authoritative create payload makes the flaky list lookup unnecessary.- expect(mockedCaptureVercel).not.toHaveBeenCalled();- // The connector is attached to the linked project so the agent can call it.- expect(mockedRunVercel).toHaveBeenCalledWith(- ["connect", "attach", "linear/my-agent", "--yes"],- expect.objectContaining({ cwd: projectRoot }),+ expect(capture).toHaveBeenCalledWith(+ ["api", "/v1/connect/connectors/scl_canonical", "--scope", "org_1", "--raw"],+ expect.any(Object),);- // The generated connect("…") UID was rewritten on disk.- const patched = await readFile(connectionFilePath, "utf8");- expect(patched).toContain('connect("linear/my-agent")');- expect(patched).not.toContain('connect("linear")');- });-- test("warns but still patches when attaching the connector to the project fails", async () => {- mockedRunVercelCaptureStdout.mockResolvedValue({- ok: true,- stdout: createConnectorJson("linear/my-agent"),- });- mockedRunVercel.mockResolvedValue(false);- const log = createTestLog();-- const result = await setupConnectionConnector({- log,- projectRoot,- slug: "linear",- service: SERVICE,- connectionFilePath,- });-- // Attach failure is non-fatal: the connector exists and the file is patched.- expect(result).toEqual({ kind: "patched", created: true, connectorUid: "linear/my-agent" });- expect(log.warning).toHaveBeenCalledWith(- expect.stringContaining("could not attach it to this project"),+ expect(create).not.toHaveBeenCalled();+ expect(run).toHaveBeenCalledWith(+ ["connect", "attach", CANONICAL_UID, "--yes", "--scope", "org_1"],+ expect.any(Object),);- expect(await readFile(connectionFilePath, "utf8")).toContain('connect("linear/my-agent")');});- test("falls back to a service-scoped list when create emits no parseable JSON", async () => {- mockedRunVercelCaptureStdout.mockResolvedValue({ ok: true, stdout: "Vercel CLI 54.9.1\n" });- mockedCaptureVercel.mockResolvedValue({- ok: true,- stdout: connectListV54("linear/my-agent", PROJECT_ID),- });-- const result = await setupConnectionConnector({- log: createTestLog(),- projectRoot,- slug: "linear",- service: SERVICE,- connectionFilePath,- });-- expect(result).toEqual({ kind: "patched", created: true, connectorUid: "linear/my-agent" });- expect(mockedCaptureVercel).toHaveBeenCalledWith(- ["connect", "list", "-F", "json", "--all-projects", "--service", SERVICE],- expect.objectContaining({ cwd: projectRoot }),+ it("finds a canonical connector by name instead of assuming its UID namespace", async () => {+ const canonicalName = "linear";+ const actualUid = "linear/default";+ capture+ .mockResolvedValueOnce(+ jsonResult({ connectors: [{ uid: actualUid, id: "scl_canonical", name: canonicalName }] }),+ )+ .mockResolvedValueOnce(connectorResult(actualUid, "scl_canonical", "user"));+ run.mockResolvedValue(true);++ await expect(+ setupConnectionConnector({ ...options(), canonicalConnectorName: canonicalName }),+ ).resolves.toEqual({+ kind: "existing",+ connectorUid: actualUid,+ });+ expect(run).toHaveBeenCalledWith(+ ["connect", "attach", actualUid, "--yes", "--scope", "org_1"],+ expect.any(Object),);- expect(await readFile(connectionFilePath, "utf8")).toContain('connect("linear/my-agent")');});- test("fallback still resolves the legacy `clients` key from older CLI builds", async () => {- mockedRunVercelCaptureStdout.mockResolvedValue({ ok: true, stdout: "" });- mockedCaptureVercel.mockResolvedValue({- ok: true,- stdout: JSON.stringify({- clients: [- { uid: "linear/legacy", id: "scl_legacy", type: "oauth", createdAt: 1, projects: [] },- ],- }),+ it("does not attach an app-only canonical connector", async () => {+ capture+ .mockResolvedValueOnce(+ jsonResult({ connectors: [{ uid: CANONICAL_UID, id: "scl_canonical" }] }),+ )+ .mockResolvedValueOnce(connectorResult(CANONICAL_UID, "scl_canonical", "app"));+ create.mockResolvedValue(connectorResult("linear/linear-2", "scl_created", "user"));+ run.mockResolvedValue(true);+ const fake = createFakePrompter({+ single: () => "create",+ text: (input) => input.defaultValue!,});- const result = await setupConnectionConnector({- log: createTestLog(),- projectRoot,- slug: "linear",- service: SERVICE,- connectionFilePath,+ await expect(setupConnectionConnector(options(fake.prompter))).resolves.toEqual({+ kind: "created",+ connectorId: "scl_created",+ connectorUid: "linear/linear-2",});-- expect(result).toEqual({ kind: "patched", created: true, connectorUid: "linear/legacy" });- expect(await readFile(connectionFilePath, "utf8")).toContain('connect("linear/legacy")');- });-- test("reports create-failed and leaves the file untouched when create fails", async () => {- mockedRunVercelCaptureStdout.mockResolvedValue({ ok: false, stdout: "" });-- const result = await setupConnectionConnector({- log: createTestLog(),- projectRoot,- slug: "linear",- service: SERVICE,- connectionFilePath,- });-- expect(result).toEqual({ kind: "create-failed", created: false });- expect(mockedCaptureVercel).not.toHaveBeenCalled();- expect(await readFile(connectionFilePath, "utf8")).toContain('connect("linear")');+ expect(run).not.toHaveBeenCalledWith(+ ["connect", "attach", CANONICAL_UID, "--yes", "--scope", "org_1"],+ expect.any(Object),+ );});- test("links a Vercel project when none is linked yet, then attaches", async () => {- // Start unlinked: the gateway step used an API key/local provider, or this- // is a fresh `eve connections add` checkout.- await rm(join(projectRoot, ".vercel", "project.json"), { force: true });- mockedRunVercelCaptureStdout.mockResolvedValue({- ok: true,- stdout: createConnectorJson("linear/my-agent"),- });- // `vercel link` writes `.vercel/project.json`; everything else succeeds.- mockedRunVercel.mockImplementation(async (args) => {- if (args[0] === "link") {- await writeFile(- join(projectRoot, ".vercel", "project.json"),- JSON.stringify({ projectId: PROJECT_ID, orgId: "team_x" }),- "utf8",- );- }- return true;+ it("paginates and offers only existing connectors that support user authorization", async () => {+ run.mockResolvedValue(true);+ capture+ .mockResolvedValueOnce(+ jsonResult({+ connectors: [{ uid: "linear/app", id: "scl_app" }],+ cursor: "next_page",+ }),+ )+ .mockResolvedValueOnce(jsonResult({ connectors: [{ uid: "linear/user", id: "scl_user" }] }))+ .mockResolvedValueOnce(connectorResult("linear/app", "scl_app", "app"))+ .mockResolvedValueOnce(connectorResult("linear/user", "scl_user", "user"));+ const answers = ["find", "linear/user"];+ const selectOptions: SingleSelectOptions<PrompterValue>[] = [];+ const fake = createFakePrompter({+ single: (input) => {+ selectOptions.push(input);+ return answers.shift()!;+ },});- const log = createTestLog();- const result = await setupConnectionConnector({- log,- projectRoot,- slug: "linear",- service: SERVICE,- connectionFilePath,+ await expect(setupConnectionConnector(options(fake.prompter))).resolves.toEqual({+ kind: "existing",+ connectorUid: "linear/user",});-- expect(result).toEqual({ kind: "patched", created: true, connectorUid: "linear/my-agent" });- // Linked first, then attached to the now-linked project.- expect(mockedRunVercel).toHaveBeenCalledWith(- ["link"],- expect.objectContaining({ cwd: projectRoot }),+ expect(capture).toHaveBeenCalledWith(+ expect.arrayContaining(["--next", "next_page"]),+ expect.any(Object),);- expect(mockedRunVercel).toHaveBeenCalledWith(- ["connect", "attach", "linear/my-agent", "--yes"],- expect.objectContaining({ cwd: projectRoot }),+ expect(capture).toHaveBeenCalledWith(+ expect.arrayContaining(["--scope", "org_1"]),+ expect.any(Object),);- expect(await readFile(connectionFilePath, "utf8")).toContain('connect("linear/my-agent")');- });-- test("creates the connector but skips attach when linking does not complete", async () => {- await rm(join(projectRoot, ".vercel", "project.json"), { force: true });- mockedRunVercelCaptureStdout.mockResolvedValue({- ok: true,- stdout: createConnectorJson("linear/my-agent"),- });- // `vercel link` is declined/fails, so no project.json is written.- mockedRunVercel.mockResolvedValue(false);- mockedCaptureVercel.mockResolvedValue({ ok: true, stdout: JSON.stringify({ connectors: [] }) });- const log = createTestLog();-- const result = await setupConnectionConnector({- log,- projectRoot,- slug: "linear",- service: SERVICE,- connectionFilePath,- });-- // The connector still exists and the file is patched; attach is skipped.- expect(result).toEqual({ kind: "patched", created: true, connectorUid: "linear/my-agent" });- expect(mockedRunVercel).not.toHaveBeenCalledWith(- ["connect", "attach", "linear/my-agent", "--yes"],- expect.anything(),+ expect(fake.selectMessages).toEqual([+ "Which connector should linear use?",+ "Select a connector for linear",+ ]);+ expect(selectOptions[0]).toMatchObject({+ hintLayout: "inline",+ notices: [{ tone: "warning", text: `Could not find a connector named ${CANONICAL_NAME}.` }],+ });+ expect(selectOptions[1]).toMatchObject({+ hintLayout: "inline",+ placeholder: "type to search connectors",+ search: true,+ });+ });++ it("removes a created connector when attach fails", async () => {+ run.mockResolvedValueOnce(false).mockResolvedValueOnce(false).mockResolvedValueOnce(true);+ capture+ .mockResolvedValueOnce(+ jsonResult({ connectors: [{ uid: CANONICAL_UID, id: "scl_existing", name: "Linear" }] }),+ )+ .mockResolvedValueOnce(connectorResult(CANONICAL_UID, "scl_existing", "user"));+ create.mockResolvedValue(connectorResult("linear/linear-2", "scl_created", "user"));+ const fake = createFakePrompter({+ single: () => "create",+ text: (input) => input.defaultValue!,+ });++ await expect(setupConnectionConnector(options(fake.prompter))).rejects.toThrow(+ "Could not attach linear/linear-2",+ );+ expect(create).toHaveBeenCalledWith(+ ["connect", "create", SERVICE, "--name", "linear-2", "-F", "json", "--scope", "org_1"],+ expect.any(Object),);- expect(log.warning).toHaveBeenCalledWith(- expect.stringContaining("no Vercel project is linked"),+ expect(run).toHaveBeenLastCalledWith(+ ["connect", "remove", "scl_created", "--disconnect-all", "--yes", "--scope", "org_1"],+ expect.any(Object),);- expect(await readFile(connectionFilePath, "utf8")).toContain('connect("linear/my-agent")');});- test("reports connector-unresolved when neither create nor the list yield a UID", async () => {- mockedRunVercelCaptureStdout.mockResolvedValue({ ok: true, stdout: "" });- mockedCaptureVercel.mockResolvedValue({ ok: true, stdout: JSON.stringify({ connectors: [] }) });-- const result = await setupConnectionConnector({- log: createTestLog(),- projectRoot,- slug: "linear",- service: SERVICE,- connectionFilePath,+ it("recovers a partially created connector id from CLI progress and removes it", async () => {+ run.mockResolvedValueOnce(false).mockResolvedValueOnce(true);+ capture.mockResolvedValue(jsonResult({ connectors: [] }));+ create.mockImplementation(async (_args, createOptions) => {+ createOptions.onOutput?.({ stream: "stderr", text: "Connector created: scl_partial" });+ return { ok: false, stdout: "" };});+ const fake = createFakePrompter({ single: () => "create", text: () => "acme" });- expect(result).toEqual({ kind: "connector-unresolved", created: true });- expect(await readFile(connectionFilePath, "utf8")).toContain('connect("linear")');+ await expect(setupConnectionConnector(options(fake.prompter))).rejects.toThrow(+ `Could not create the ${SERVICE} connector`,+ );+ expect(run).toHaveBeenLastCalledWith(+ ["connect", "remove", "scl_partial", "--disconnect-all", "--yes", "--scope", "org_1"],+ expect.any(Object),+ );});});diff --git a/packages/eve/src/setup/connection-connector.ts b/packages/eve/src/setup/connection-connector.tsindex 0cd0eee29..a8aa569f8 100644--- a/packages/eve/src/setup/connection-connector.ts+++ b/packages/eve/src/setup/connection-connector.ts@@ -1,252 +1,380 @@-import { readFile } from "node:fs/promises";-import { join } from "node:path";--import { createPromptCommandOutput, type ChannelSetupLog } from "#setup/cli/index.js";+import { createPromptCommandOutput, type ChannelSetupLog, withPhase } from "#setup/cli/index.js";+import type { ProcessOutputHandler } from "#setup/primitives/process-output.js";+import type { Prompter } from "#setup/prompter.js";+import { readProjectLink, type VercelProjectReference } from "#setup/project-resolution.js";import { captureVercel, runVercel, runVercelCaptureStdout } from "#setup/primitives/run-vercel.js";-import { updateConnectionConnectorUid } from "#setup/scaffold/update/update-connection-connector.js";-/** Controls connector provisioning while adding a Connect-backed connection. */+/** Controls connector selection while adding a Connect-backed connection. */export interface SetupConnectionConnectorOptions {- /** Status and command output stream through this log (rail styling preserved). */log: ChannelSetupLog;+ prompter: Prompter;projectRoot: string;- /** Connection slug; also the connector `--name`. */slug: string;- /** `vercel connect create <service>` identifier (e.g. `mcp.linear.app`). */service: string;- /** Generated `agent/connections/<slug>.ts` whose `connect("…")` is patched. */- connectionFilePath: string;- /**- * Links a Vercel project before Connect provisioning when the caller owns a- * richer linking flow (e.g. shared team selection). Returns the linked- * project id, or `undefined` when linking did not complete. When omitted,- * falls back to a bare `vercel link`.- */- linkProject?: () => Promise<string | undefined>;-}--/** Outcome of the Connect create-and-patch sequence for a connection. */-export type SetupConnectionConnectorResult =- | { kind: "create-failed"; created: false }- | { kind: "connector-unresolved"; created: true }- | { kind: "patch-failed"; created: true; connectorUid: string }- | { kind: "patched"; created: true; connectorUid: string };--interface VercelConnectListClient {- uid?: unknown;- id?: unknown;- type?: unknown;- service?: unknown;- createdAt?: unknown;- projects?: unknown;-}--interface VercelConnectListResponse {- /** `vercel connect list -F json` (current CLI). */- connectors?: unknown;- /** Older CLI builds emitted the same array under `clients`. */- clients?: unknown;+ canonicalConnectorName: string;+ project: VercelProjectReference;+ signal?: AbortSignal;}-/** Identifiers returned by Vercel Connect for an OAuth connector. */+/** Connector identity returned by the Vercel CLI. */export interface ConnectConnectorRef {uid: string;id: string;+ name?: string;}-/**- * Reads the connector identifiers from `vercel connect create … -F json`- * stdout. This is the authoritative source for the just-created connector's- * UID — it avoids a follow-up `connect list`, which can momentarily 404/rate- * limit right after creation and cannot disambiguate when a service already- * has multiple connectors. Returns `undefined` when stdout is empty or not the- * expected JSON (e.g. an older CLI without `-F json` support on `create`).- */-export function parseCreatedConnector(stdout: string): ConnectConnectorRef | undefined {- const trimmed = stdout.trim();- if (!trimmed) return undefined;- let parsed: unknown;+export type SetupConnectionConnectorResult =+ | { kind: "existing"; connectorUid: string }+ | { kind: "created"; connectorUid: string; connectorId: string };++type ConnectorResolution =+ | { kind: "existing"; connector: ConnectConnectorRef }+ | { kind: "created"; connector: ConnectConnectorRef };++const CREATED_CONNECTOR = /\bConnector created:\s*(scl_[A-Za-z0-9_-]+)\b/u;++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function parseJson(source: string): unknown {try {- parsed = JSON.parse(trimmed);+ return JSON.parse(source);} catch {return undefined;}- if (typeof parsed !== "object" || parsed === null) return undefined;- const { uid, id } = parsed as { uid?: unknown; id?: unknown };- if (typeof uid !== "string" || typeof id !== "string") return undefined;- return { uid, id };-}--function attachedToProject(raw: VercelConnectListClient, projectId: string | undefined): boolean {- if (projectId === undefined) return false;- if (!Array.isArray(raw.projects)) return false;- return raw.projects.some(- (project) =>- typeof project === "object" &&- project !== null &&- (project as { id?: unknown }).id === projectId,- );}-/**- * Finds the connector to wire into the generated connection. The list is- * expected to be scoped to the requested service server-side (via- * `--service`), since `vercel connect list -F json` does not include a- * `service` field per connector. Prefers, in order: the connector already- * attached to this project, then the newest connector. When Connect does- * report a `service` field, mismatches are still skipped defensively.- */-export function pickConnectConnector(- listJson: unknown,- service: string,- projectId: string | undefined,-): ConnectConnectorRef | undefined {- if (typeof listJson !== "object" || listJson === null) return undefined;- const response = listJson as VercelConnectListResponse;- const connectors = response.connectors ?? response.clients;- if (!Array.isArray(connectors)) return undefined;+function parseConnectorRef(value: unknown): ConnectConnectorRef | undefined {+ if (!isRecord(value) || typeof value["uid"] !== "string" || typeof value["id"] !== "string") {+ return undefined;+ }+ const connector: ConnectConnectorRef = { uid: value["uid"], id: value["id"] };+ if (typeof value["name"] === "string") connector.name = value["name"];+ return connector;+}- let attached: { ref: ConnectConnectorRef; createdAt: number } | undefined;- let newest: { ref: ConnectConnectorRef; createdAt: number } | undefined;+/** Parses a created connector that can issue user credentials. */+export function parseCreatedConnector(stdout: string): ConnectConnectorRef | undefined {+ const value = parseJson(stdout);+ const connector = parseConnectorRef(value);+ if (!isRecord(value) || connector === undefined) return undefined;+ const subjects = value["supportedSubjectTypes"];+ return Array.isArray(subjects) && subjects.includes("user") ? connector : undefined;+}- for (const raw of connectors as VercelConnectListClient[]) {- if (typeof raw.service === "string" && raw.service !== service) continue;- if (typeof raw.uid !== "string" || typeof raw.id !== "string") continue;+function parseConnectorList(+ candidates: readonly unknown[],+ service: string,+): ConnectConnectorRef[] {+ const connectors: ConnectConnectorRef[] = [];+ for (const candidate of candidates) {+ if (!isRecord(candidate)) continue;+ if (typeof candidate["service"] === "string" && candidate["service"] !== service) continue;+ const connector = parseConnectorRef(candidate);+ if (connector !== undefined) connectors.push(connector);+ }+ return connectors;+}- const ref: ConnectConnectorRef = { uid: raw.uid, id: raw.id };- const createdAt = typeof raw.createdAt === "number" ? raw.createdAt : 0;+function parseConnectorListPage(+ value: unknown,+ service: string,+): { connectors: ConnectConnectorRef[]; cursor?: string } | undefined {+ if (!isRecord(value) || !Array.isArray(value["connectors"])) return undefined;+ const cursor = typeof value["cursor"] === "string" ? value["cursor"] : undefined;+ return cursor === undefined+ ? { connectors: parseConnectorList(value["connectors"], service) }+ : { connectors: parseConnectorList(value["connectors"], service), cursor };+}- if (!newest || createdAt > newest.createdAt) {- newest = { ref, createdAt };+async function listConnectors(+ options: SetupConnectionConnectorOptions,+ project: VercelProjectReference,+ onOutput: ProcessOutputHandler,+): Promise<ConnectConnectorRef[]> {+ const connectors: ConnectConnectorRef[] = [];+ const seenCursors = new Set<string>();+ let cursor: string | undefined;+ do {+ const args = [+ "connect",+ "list",+ "-F",+ "json",+ "--all-projects",+ "--service",+ options.service,+ "--scope",+ project.orgId,+ ];+ if (cursor !== undefined) args.push("--next", cursor);+ const result = await captureVercel(args, {+ cwd: options.projectRoot,+ onOutput,+ signal: options.signal,+ });+ if (!result.ok) throw new Error(result.failure.message);+ const page = parseJson(result.stdout);+ const parsed = parseConnectorListPage(page, options.service);+ if (parsed === undefined) {+ throw new Error(`Vercel returned an invalid connector list for ${options.service}.`);}- if (attachedToProject(raw, projectId) && (!attached || createdAt > attached.createdAt)) {- attached = { ref, createdAt };+ connectors.push(...parsed.connectors);+ const next = parsed.cursor;+ if (next !== undefined && seenCursors.has(next)) {+ throw new Error(`The connector list repeated cursor ${next}.`);}- }-- return (attached ?? newest)?.ref;+ if (next !== undefined) seenCursors.add(next);+ cursor = next;+ } while (cursor !== undefined);+ return connectors;}-async function readProjectId(projectRoot: string): Promise<string | undefined> {- try {- const raw = await readFile(join(projectRoot, ".vercel", "project.json"), "utf8");- const parsed = JSON.parse(raw) as { projectId?: unknown };- return typeof parsed.projectId === "string" ? parsed.projectId : undefined;- } catch {- return undefined;+async function supportsUserAuthorization(+ options: SetupConnectionConnectorOptions,+ project: VercelProjectReference,+ connector: ConnectConnectorRef,+ onOutput: ProcessOutputHandler,+): Promise<boolean> {+ const endpoint = `/v1/connect/connectors/${encodeURIComponent(connector.id)}`;+ const result = await captureVercel(["api", endpoint, "--scope", project.orgId, "--raw"], {+ cwd: options.projectRoot,+ onOutput,+ signal: options.signal,+ });+ if (!result.ok) throw new Error(`Could not verify connector ${connector.uid}.`);+ const value = parseJson(result.stdout);+ if (+ !isRecord(value) ||+ value["id"] !== connector.id ||+ value["uid"] !== connector.uid ||+ (typeof value["service"] === "string" && value["service"] !== options.service)+ ) {+ throw new Error(`Vercel returned invalid details for connector ${connector.uid}.`);}+ const subjects = value["supportedSubjectTypes"];+ return Array.isArray(subjects) && subjects.includes("user");}-/**- * Connect attach requires a linked Vercel project. The connection step can run- * before one exists — the gateway step used an API key or a local provider, or- * `eve connections add` ran in a fresh checkout — so link one first. Returns the- * resolved project id, or `undefined` when linking did not complete.- */-async function ensureLinkedProject(- log: ChannelSetupLog,- projectRoot: string,- onOutput: ReturnType<typeof createPromptCommandOutput>,-): Promise<string | undefined> {- const existing = await readProjectId(projectRoot);- if (existing) return existing;- log.message("Linking a Vercel project for Connect...");- await runVercel(["link"], { cwd: projectRoot, onOutput });- return readProjectId(projectRoot);-}--async function findConnector(- projectRoot: string,- service: string,- projectId: string | undefined,- onOutput: ReturnType<typeof createPromptCommandOutput>,-): Promise<ConnectConnectorRef | undefined> {- const result = await captureVercel(- ["connect", "list", "-F", "json", "--all-projects", "--service", service],- {- cwd: projectRoot,- onOutput,- },- );- if (!result.ok) return undefined;- try {- return pickConnectConnector(JSON.parse(result.stdout), service, projectId);- } catch {- return undefined;+function connectorNames(connectors: readonly ConnectConnectorRef[]): Set<string> {+ const names = new Set<string>();+ for (const connector of connectors) {+ if (connector.name !== undefined) names.add(connector.name.toLowerCase());+ const uidName = connector.uid.slice(connector.uid.lastIndexOf("/") + 1).trim();+ if (uidName.length > 0) names.add(uidName.toLowerCase());}+ return names;}-/**- * Creates a Vercel Connect OAuth connector for a connection and rewrites the- * generated `connect("…")` call to the connector UID Connect assigns. The- * `vercel connect create` step is interactive (it opens a browser to complete- * the OAuth grant); callers should only invoke this from an interactive flow.- */-export async function setupConnectionConnector(- options: SetupConnectionConnectorOptions,-): Promise<SetupConnectionConnectorResult> {- const { log, projectRoot, slug, service, connectionFilePath } = options;- const onOutput = createPromptCommandOutput(log);+function connectorMatchesCanonicalName(connector: ConnectConnectorRef, name: string): boolean {+ const canonical = name.toLowerCase();+ if (connector.name?.toLowerCase() === canonical) return true;+ const uidName = connector.uid.slice(connector.uid.lastIndexOf("/") + 1).trim();+ return uidName.toLowerCase() === canonical;+}- const projectId = options.linkProject- ? await options.linkProject()- : await ensureLinkedProject(log, projectRoot, onOutput);+function nextConnectorName(slug: string, names: ReadonlySet<string>): string {+ if (!names.has(slug.toLowerCase())) return slug;+ let suffix = 2;+ while (names.has(`${slug}-${suffix}`.toLowerCase())) suffix += 1;+ return `${slug}-${suffix}`;+}- log.message(`Connecting ${slug} via Vercel Connect...`);- const create = await runVercelCaptureStdout(- ["connect", "create", service, "--name", slug, "-F", "json"],- { cwd: projectRoot, onOutput },- );- if (!create.ok) {- log.warning(- `Could not create the connector. Run \`vercel connect create ${service} --name ${slug}\`, then set the UID in agent/connections/${slug}.ts.`,+/** Removes a connector created by this setup attempt. */+export async function cleanupCreatedConnectionConnector(input: {+ log: ChannelSetupLog;+ projectRoot: string;+ connectorId: string;+ /** The linked Vercel owner; inferred from the project link when omitted. */+ orgId?: string;+}): Promise<void> {+ const orgId = input.orgId ?? (await readProjectLink(input.projectRoot))?.orgId;+ const args = ["connect", "remove", input.connectorId, "--disconnect-all", "--yes"];+ if (orgId !== undefined) args.push("--scope", orgId);+ const removed = await runVercel(args, {+ cwd: input.projectRoot,+ onOutput: createPromptCommandOutput(input.log),+ });+ if (!removed) {+ throw new Error(+ `Could not remove connector ${input.connectorId}; run \`vercel connect remove ${input.connectorId} --disconnect-all --yes\`.`,);- return { kind: "create-failed", created: false };}+}- // Authoritative path: the just-created connector's UID is on `create` stdout.- // Fall back to a service-scoped `connect list` only when the CLI emits no- // parseable JSON (e.g. an older build without `-F json` on `create`).- let ref = parseCreatedConnector(create.stdout);- if (!ref) {- // The `Connecting ...` status stays active so this fallback lookup reads- // as part of the same step rather than a separate line.- ref = await findConnector(projectRoot, service, projectId, onOutput);- }- if (!ref) {- log.warning(- `Could not locate the connector. Run \`vercel connect list --all-projects\` to find its UID, then set it in agent/connections/${slug}.ts.`,- );- return { kind: "connector-unresolved", created: true };- }+async function attach(+ options: SetupConnectionConnectorOptions,+ project: VercelProjectReference,+ connectorUid: string,+ onOutput: ProcessOutputHandler,+): Promise<boolean> {+ return runVercel(["connect", "attach", connectorUid, "--yes", "--scope", project.orgId], {+ cwd: options.projectRoot,+ onOutput,+ signal: options.signal,+ });+}- // Attach the connector to the linked project so the agent can call it from- // its builds and runtime. `vercel connect create` only creates the connector;- // without this attach it shows "No projects connected yet" in the dashboard.- if (!projectId) {- log.warning(- `Created connector ${ref.uid} but no Vercel project is linked, so it isn't attached. Run \`vercel link\`, then \`vercel connect attach ${ref.uid} --yes\`.`,- );- } else {- const attached = await runVercel(["connect", "attach", ref.uid, "--yes"], {- cwd: projectRoot,- onOutput,+async function resolveFallbackConnector(+ options: SetupConnectionConnectorOptions,+ project: VercelProjectReference,+ onOutput: ProcessOutputHandler,+ connectors: readonly ConnectConnectorRef[],+ initialNotice: string,+): Promise<ConnectorResolution> {+ let notice = initialNotice;+ while (true) {+ const choice = await options.prompter.select<"find" | "create">({+ message: `Which connector should ${options.slug} use?`,+ hintLayout: "inline",+ notices: [{ tone: "warning", text: notice }],+ options: [+ { value: "find", label: "Find a new one", hint: "Browse existing connectors" },+ { value: "create", label: "Create a new one", hint: "Register another connector" },+ ],});- if (!attached) {- log.warning(- `Created connector ${ref.uid} but could not attach it to this project. Run \`vercel connect attach ${ref.uid} --yes\`.`,- );+ if (choice === "find") {+ const supported: ConnectConnectorRef[] = [];+ for (const connector of connectors) {+ if (await supportsUserAuthorization(options, project, connector, onOutput)) {+ supported.push(connector);+ }+ }+ if (supported.length === 0) {+ notice = `No existing ${options.service} connectors support user authorization.`;+ continue;+ }+ const byUid = new Map(supported.map((connector) => [connector.uid, connector]));+ const uid = await options.prompter.select<string>({+ message: `Select a connector for ${options.slug}`,+ hintLayout: "inline",+ search: true,+ placeholder: "type to search connectors",+ options: supported.map((connector) => ({+ value: connector.uid,+ label: connector.uid,+ hint: connector.name ?? connector.id,+ })),+ });+ const connector = byUid.get(uid);+ if (connector === undefined) throw new Error(`Connector ${uid} is no longer available.`);+ return { kind: "existing", connector };}- }- const { patched } = await updateConnectionConnectorUid(connectionFilePath, ref.uid);- if (!patched) {- log.warning(- `Created connector ${ref.uid}. Update \`connect("…")\` in agent/connections/${slug}.ts to "${ref.uid}".`,+ const names = connectorNames(connectors);+ const name = (+ await options.prompter.text({+ message: "New connector name",+ defaultValue: nextConnectorName(options.slug, names),+ validate: (value) => {+ const normalized = value.trim().toLowerCase();+ if (normalized.length === 0) return "A name is required.";+ return names.has(normalized) ? "A connector with this name already exists." : undefined;+ },+ })+ ).trim();+ const transcript: string[] = [];+ const createOutput: ProcessOutputHandler = (line) => {+ transcript.push(line.text);+ onOutput(line);+ };+ const created = await withPhase(+ options.log,+ "Waiting for you to complete setup in the browser…",+ () =>+ runVercelCaptureStdout(+ [+ "connect",+ "create",+ options.service,+ "--name",+ name,+ "-F",+ "json",+ "--scope",+ project.orgId,+ ],+ { cwd: options.projectRoot, onOutput: createOutput, signal: options.signal },+ ),+ { kind: "external-action", emphasis: "browser" },);- return { kind: "patch-failed", created: true, connectorUid: ref.uid };+ const raw = parseConnectorRef(parseJson(created.stdout));+ const ownedId = raw?.id ?? CREATED_CONNECTOR.exec(transcript.join("\n"))?.[1];+ const connector = created.ok ? parseCreatedConnector(created.stdout) : undefined;+ if (connector !== undefined) return { kind: "created", connector };+ const message = created.ok+ ? `The ${options.service} connector does not support user authorization.`+ : `Could not create the ${options.service} connector.`;+ if (ownedId !== undefined) {+ try {+ await cleanupCreatedConnectionConnector({+ log: options.log,+ projectRoot: options.projectRoot,+ connectorId: ownedId,+ orgId: project.orgId,+ });+ } catch (error) {+ const cleanup = error instanceof Error ? error.message : String(error);+ throw new Error(`${message} ${cleanup}`);+ }+ options.signal?.throwIfAborted();+ }+ throw new Error(message);}+}- log.success(`Linked ${slug} to ${ref.uid}`);- return { kind: "patched", created: true, connectorUid: ref.uid };+/** Attaches the canonical connector by name first, then offers explicit Find/Create fallbacks. */+export async function setupConnectionConnector(+ options: SetupConnectionConnectorOptions,+): Promise<SetupConnectionConnectorResult> {+ const onOutput = createPromptCommandOutput(options.log);+ const project = options.project;+ const connectors = await listConnectors(options, project, onOutput);+ const canonical = connectors.find((connector) =>+ connectorMatchesCanonicalName(connector, options.canonicalConnectorName),+ );+ let notice = `Could not find a connector named ${options.canonicalConnectorName}.`;++ if (canonical !== undefined) {+ if (await supportsUserAuthorization(options, project, canonical, onOutput)) {+ if (await attach(options, project, canonical.uid, onOutput)) {+ options.log.success(`Attached ${canonical.uid} connector`);+ return { kind: "existing", connectorUid: canonical.uid };+ }+ options.signal?.throwIfAborted();+ notice = `Could not attach ${canonical.uid}.`;+ } else {+ notice = `${canonical.uid} does not support user authorization.`;+ }+ }++ const resolution = await resolveFallbackConnector(options, project, onOutput, connectors, notice);+ if (!(await attach(options, project, resolution.connector.uid, onOutput))) {+ if (resolution.kind === "created") {+ const message = `Could not attach ${resolution.connector.uid} to the linked project.`;+ try {+ await cleanupCreatedConnectionConnector({+ log: options.log,+ projectRoot: options.projectRoot,+ connectorId: resolution.connector.id,+ orgId: project.orgId,+ });+ } catch (error) {+ const cleanup = error instanceof Error ? error.message : String(error);+ throw new Error(`${message} ${cleanup}`);+ }+ options.signal?.throwIfAborted();+ throw new Error(message);+ }+ throw new Error(`Could not attach ${resolution.connector.uid} to the linked project.`);+ }+ options.log.success(`Attached ${resolution.connector.uid} connector`);+ return resolution.kind === "created"+ ? {+ kind: "created",+ connectorUid: resolution.connector.uid,+ connectorId: resolution.connector.id,+ }+ : { kind: "existing", connectorUid: resolution.connector.uid };}diff --git a/packages/eve/src/setup/flows/channels.test.ts b/packages/eve/src/setup/flows/channels.test.tsindex a9748d800..878f1441e 100644--- a/packages/eve/src/setup/flows/channels.test.ts+++ b/packages/eve/src/setup/flows/channels.test.ts@@ -152,7 +152,7 @@ describe("runChannelsFlow", () => {expect(result).toEqual({ kind: "done", addedChannels: [] });expect(addChannelsDeps.ensureChannel).not.toHaveBeenCalled();- expect(listPaints[0]?.at(-1)).toMatchObject({ value: "done", label: "Done" });+ expect(listPaints[0]?.at(-1)).toMatchObject({ value: "done", trailingAction: true });});it("defaults the cursor to Done when every channel is already added or unavailable", async () => {diff --git a/packages/eve/src/setup/flows/channels.ts b/packages/eve/src/setup/flows/channels.tsindex 1fb7fc8fa..05156335c 100644--- a/packages/eve/src/setup/flows/channels.ts+++ b/packages/eve/src/setup/flows/channels.ts@@ -216,7 +216,7 @@ function channelListRows(if (channel.hint !== undefined) row.hint = channel.hint;rows.push(row);}- rows.push({ value: "done", label: "Done" });+ rows.push({ value: "done", label: "Done", trailingAction: true });return rows;}diff --git a/packages/eve/src/setup/flows/connections.test.ts b/packages/eve/src/setup/flows/connections.test.tsnew file mode 100644index 000000000..dcc456fdb--- /dev/null+++ b/packages/eve/src/setup/flows/connections.test.ts@@ -0,0 +1,198 @@+import { describe, expect, it, vi } from "vitest";++import { createFakePrompter } from "#internal/testing/fake-prompter.js";+import type { AddConnectionsDeps } from "#setup/boxes/add-connections.js";+import type { DeploymentInfo } from "#setup/project-resolution.js";+import type { PrompterValue, SingleSelectOptions } from "#setup/prompter.js";+import { WizardCancelledError } from "#setup/step.js";++import {+ CONNECTIONS_PROMPT_MESSAGE,+ runConnectionsFlow,+ type ConnectionsFlowDeps,+} from "./connections.js";++const APP_ROOT = "/app/agent";+const LINKED: DeploymentInfo = { state: "linked", projectId: "prj_1", orgId: "org_1" };++function scriptConnectionList(queue: Array<PrompterValue | "cancel">) {+ const requests: SingleSelectOptions<PrompterValue>[] = [];+ return {+ requests,+ single(options: SingleSelectOptions<PrompterValue>): PrompterValue {+ if (options.message !== CONNECTIONS_PROMPT_MESSAGE) {+ throw new Error(`Unexpected select: ${options.message}`);+ }+ requests.push(options);+ const next = queue.shift();+ if (next === undefined) throw new Error("Connection list exhausted its scripted picks.");+ if (next === "cancel") throw new WizardCancelledError();+ return next;+ },+ };+}++function addConnectionDeps(): AddConnectionsDeps {+ return {+ ensureConnection: vi.fn<AddConnectionsDeps["ensureConnection"]>(async (options) => ({+ slug: options.slug ?? options.entry.slug,+ protocol: options.protocol,+ action: "created",+ filePath: `${APP_ROOT}/agent/connections/${options.slug ?? options.entry.slug}.ts`,+ filesWritten: [`${APP_ROOT}/agent/connections/${options.slug ?? options.entry.slug}.ts`],+ filesSkipped: [],+ packageJsonUpdated: [],+ envKeysAdded: [],+ envKeysRequired: [],+ })),+ setupConnectionConnector: vi.fn<AddConnectionsDeps["setupConnectionConnector"]>(async () =>+ Object.freeze({ kind: "existing", connectorUid: "mcp.linear.app/linear" }),+ ),+ listAuthoredConnections: vi.fn(async () => []),+ readProjectLink: vi.fn(async () => ({ orgId: "org_1", projectId: "prj_1" })),+ cleanupCreatedConnectionConnector: vi.fn(async () => {}),+ };+}++function runConnectionFlow(+ list: ReturnType<typeof scriptConnectionList>,+ deps: Partial<ConnectionsFlowDeps> = {},+) {+ const defaults: ConnectionsFlowDeps = {+ detectDeployment: vi.fn(async () => LINKED),+ detectPackageManager: vi.fn(async () => Object.freeze({ kind: "pnpm", source: "default" })),+ ensureConnectionDependencies: vi.fn(async () => []),+ getVercelAuthStatus: vi.fn(() => Promise.resolve<"authenticated">("authenticated")),+ listAuthoredConnections: vi.fn(async () => []),+ runLinkFlow: vi.fn(async () => Object.freeze({ kind: "done" })),+ runPackageManagerInstall: vi.fn(async () => true),+ addConnections: addConnectionDeps(),+ };+ return runConnectionsFlow({+ appRoot: APP_ROOT,+ prompter: createFakePrompter({ single: list.single }).prompter,+ deps: { ...defaults, ...deps },+ });+}++describe("runConnectionsFlow", () => {+ it("returns a terminal success after adding a catalog connection", async () => {+ const listAuthoredConnections = vi+ .fn(async () => [] as string[])+ .mockResolvedValueOnce([])+ .mockResolvedValue(["linear"]);+ const list = scriptConnectionList(["linear"]);++ await expect(runConnectionFlow(list, { listAuthoredConnections })).resolves.toEqual({+ kind: "done",+ addedConnections: ["linear"],+ });++ expect(list.requests[0]).toMatchObject({+ hintLayout: "inline",+ search: true,+ placeholder: "type to search MCP servers",+ });+ expect(list.requests[0]?.options.map((row) => row.value)).toEqual([+ "linear",+ "notion",+ "datadog",+ "honeycomb",+ "done",+ ]);+ expect(list.requests).toHaveLength(1);+ });++ it("defaults to Done when every catalog connection is already authored", async () => {+ const list = scriptConnectionList(["done"]);+ await runConnectionFlow(list, {+ listAuthoredConnections: vi.fn(async () => ["linear", "notion", "datadog", "honeycomb"]),+ });++ expect(list.requests[0]?.initialValue).toBe("done");+ });++ it("blocks logged-out rows", async () => {+ const loggedOutList = scriptConnectionList(["cancel"]);+ await expect(+ runConnectionFlow(loggedOutList, {+ detectDeployment: vi.fn(() => Promise.resolve<DeploymentInfo>({ state: "unlinked" })),+ getVercelAuthStatus: vi.fn(async (): Promise<"logged-out"> => "logged-out"),+ }),+ ).resolves.toEqual({ kind: "cancelled" });+ expect(loggedOutList.requests[0]?.options.find((row) => row.value === "linear")).toMatchObject({+ disabled: true,+ disabledReason: "Log in to Vercel first, see /vc:login",+ });+ });++ it("runs the shared create-or-link flow before configuring an unlinked project", async () => {+ const detectDeployment = vi+ .fn<ConnectionsFlowDeps["detectDeployment"]>()+ .mockResolvedValueOnce({ state: "unlinked" })+ .mockResolvedValueOnce(LINKED);+ const runLinkFlow = vi.fn<ConnectionsFlowDeps["runLinkFlow"]>(async () => ({ kind: "done" }));+ const listAuthoredConnections = vi+ .fn(async () => [] as string[])+ .mockResolvedValueOnce([])+ .mockResolvedValue(["linear"]);+ const list = scriptConnectionList(["linear"]);+ await expect(+ runConnectionFlow(list, {+ detectDeployment,+ listAuthoredConnections,+ runLinkFlow,+ }),+ ).resolves.toEqual({ kind: "done", addedConnections: ["linear"] });++ const linkInput = runLinkFlow.mock.calls[0]?.[0];+ expect(linkInput?.projectSelection).toBe("create-or-link");+ expect(linkInput?.teamSelectMessage?.("Acme")).toBe(+ "You need to link to a project to use Vercel Connect.\n\nSelect your team",+ );+ });++ it("returns a terminal cancellation when project linking is cancelled", async () => {+ const runLinkFlow = vi.fn(async () => Object.freeze({ kind: "cancelled" }));+ const list = scriptConnectionList(["linear"]);++ await expect(+ runConnectionFlow(list, {+ detectDeployment: vi.fn(() => Promise.resolve<DeploymentInfo>({ state: "unlinked" })),+ runLinkFlow,+ }),+ ).resolves.toEqual({ kind: "cancelled" });+ expect(list.requests).toHaveLength(1);+ });++ it("returns a terminal failure when connector setup fails", async () => {+ const list = scriptConnectionList(["linear"]);+ const addConnections = addConnectionDeps();+ vi.mocked(addConnections.setupConnectionConnector).mockRejectedValueOnce(+ new Error("Could not create the mcp.linear.app connector."),+ );++ await expect(runConnectionFlow(list, { addConnections })).resolves.toEqual({+ kind: "failed",+ addedConnections: [],+ message: "Could not create the mcp.linear.app connector.",+ });+ expect(list.requests).toHaveLength(1);+ });++ it("installs dependencies before provisioning a connector", async () => {+ const list = scriptConnectionList(["linear"]);+ const addConnections = addConnectionDeps();+ const runPackageManagerInstall = vi.fn(async () => false);++ await expect(+ runConnectionFlow(list, { addConnections, runPackageManagerInstall }),+ ).resolves.toEqual({+ kind: "failed",+ addedConnections: [],+ message: "Dependency installation failed. Run `pnpm install`.",+ });++ expect(addConnections.setupConnectionConnector).not.toHaveBeenCalled();+ });+});diff --git a/packages/eve/src/setup/flows/connections.ts b/packages/eve/src/setup/flows/connections.tsnew file mode 100644index 000000000..157f407b8--- /dev/null+++ b/packages/eve/src/setup/flows/connections.ts@@ -0,0 +1,204 @@+import {+ CONNECTION_CATALOG,+ ensureConnectionDependencies,+ listAuthoredConnections,+} from "#setup/scaffold/index.js";+import { createPromptCommandOutput, withPhase } from "#setup/cli/index.js";+import { detectPackageManager } from "#setup/package-manager.js";+import { runPackageManagerInstall } from "#setup/primitives/pm/run.js";+import { toErrorMessage } from "#shared/errors.js";++import { interactiveAsker } from "../ask.js";+import { addConnections, type AddConnectionsDeps } from "../boxes/add-connections.js";+import { selectConnections } from "../boxes/select-connections.js";+import {+ detectDeployment,+ isProjectResolved,+ projectResolutionFromDeployment,+} from "../project-resolution.js";+import type { Prompter, SelectOption, SingleSelectOptions } from "../prompter.js";+import { runInteractive, type AnySetupBox } from "../runner.js";+import { snapshotSetupState, type SetupState } from "../state.js";+import { WizardCancelledError } from "../step.js";+import {+ getVercelAuthStatus,+ vercelAuthBlockerReason,+ type VercelAuthStatus,+} from "../vercel-project.js";+import { withSpinner } from "../with-spinner.js";++import { inProjectSetupState, prompterSink } from "./in-project.js";+import { runLinkFlow } from "./link.js";++export const CONNECTIONS_PROMPT_MESSAGE =+ "Select an MCP server to add to your agent through Vercel Connect";++const CONNECT_CONNECTIONS = CONNECTION_CATALOG.filter((entry) => entry.auth.kind === "connect");++export interface ConnectionsFlowDeps {+ detectDeployment: typeof detectDeployment;+ detectPackageManager: typeof detectPackageManager;+ getVercelAuthStatus: typeof getVercelAuthStatus;+ runLinkFlow: typeof runLinkFlow;+ ensureConnectionDependencies: typeof ensureConnectionDependencies;+ listAuthoredConnections: typeof listAuthoredConnections;+ runPackageManagerInstall: typeof runPackageManagerInstall;+ addConnections?: AddConnectionsDeps;+}++export type ConnectionsFlowResult =+ | { kind: "done"; addedConnections: readonly string[] }+ | { kind: "cancelled" }+ | { kind: "failed"; addedConnections: readonly string[]; message: string };++function connectionRows(+ authored: ReadonlySet<string>,+ authStatus: VercelAuthStatus,+): SelectOption<string>[] {+ const blocker = vercelAuthBlockerReason(authStatus);+ const rows: SelectOption<string>[] = CONNECT_CONNECTIONS.map((entry) => {+ const row = { value: entry.slug, label: entry.label };+ if (authored.has(entry.slug)) {+ return { ...row, completed: true, focusHint: "Already added" };+ }+ if (blocker !== undefined) {+ return {+ ...row,+ disabled: true,+ disabledReason: blocker,+ disabledReasonTone: "warning",+ };+ }+ return { ...row, hint: entry.hint };+ });+ rows.push({ value: "done", label: "Done", trailingAction: true });+ return rows;+}++async function pickConnection(+ prompter: Prompter,+ authored: ReadonlySet<string>,+ authStatus: VercelAuthStatus,+): Promise<string | undefined> {+ const options = connectionRows(authored, authStatus);+ const request: SingleSelectOptions<string> = {+ message: CONNECTIONS_PROMPT_MESSAGE,+ options,+ hintLayout: "inline",+ search: true,+ placeholder: "type to search MCP servers",+ };+ if (+ !options.some(+ (option) => option.value !== "done" && option.disabled !== true && option.completed !== true,+ )+ ) {+ request.initialValue = "done";+ }+ try {+ return await prompter.select(request);+ } catch (error) {+ if (error instanceof WizardCancelledError) return undefined;+ throw error;+ }+}++/** Runs `/connect`, linking a project on first selection when needed. */+export async function runConnectionsFlow(input: {+ appRoot: string;+ prompter: Prompter;+ signal?: AbortSignal;+ deps?: Partial<ConnectionsFlowDeps>;+}): Promise<ConnectionsFlowResult> {+ const { appRoot, prompter, signal } = input;+ const deps: ConnectionsFlowDeps = {+ detectDeployment,+ detectPackageManager,+ ensureConnectionDependencies,+ getVercelAuthStatus,+ listAuthoredConnections,+ runLinkFlow,+ runPackageManagerInstall,+ ...input.deps,+ };+ const [deployment, initialAuthored, authStatus] = await withSpinner(+ prompter,+ "Checking the project…",+ () =>+ Promise.all([+ deps.detectDeployment(appRoot, { signal }),+ deps.listAuthoredConnections(appRoot),+ deps.getVercelAuthStatus(appRoot, { signal }),+ ]),+ );+ signal?.throwIfAborted();++ let state = inProjectSetupState(appRoot, projectResolutionFromDeployment(deployment));+ const authored = new Set(initialAuthored);+ const selected = await pickConnection(prompter, authored, authStatus);+ if (selected === undefined) return { kind: "cancelled" };+ if (selected === "done" || authored.has(selected)) {+ return { kind: "done", addedConnections: [] };+ }++ try {+ if (!isProjectResolved(state.project)) {+ const link = await deps.runLinkFlow({+ appRoot,+ prompter,+ signal,+ projectSelection: "create-or-link",+ teamSelectMessage: () =>+ "You need to link to a project to use Vercel Connect.\n\nSelect your team",+ });+ if (link.kind === "cancelled") return { kind: "cancelled" };++ const deploymentAfterLink = await withSpinner(prompter, "Checking the project…", () =>+ deps.detectDeployment(appRoot, { signal }),+ );+ const project = projectResolutionFromDeployment(deploymentAfterLink);+ if (!isProjectResolved(project)) throw new Error("Project link was not found after linking.");+ state = { ...state, project };+ }++ const packageManager = await deps.detectPackageManager(appRoot);+ await deps.ensureConnectionDependencies({ projectRoot: appRoot });+ const installed = await withPhase(+ prompter.log,+ `Installing connection dependencies (${packageManager.kind} install)...`,+ () =>+ deps.runPackageManagerInstall(packageManager.kind, appRoot, {+ onOutput: createPromptCommandOutput(prompter.log),+ signal,+ }),+ );+ if (!installed) {+ throw new Error(`Dependency installation failed. Run \`${packageManager.kind} install\`.`);+ }++ const boxes: AnySetupBox<SetupState>[] = [+ selectConnections({ asker: interactiveAsker(prompter), presetConnections: [selected] }),+ addConnections({ prompter, signal, deps: deps.addConnections }),+ ];++ const result = await runInteractive(boxes, state, prompterSink(prompter), {+ snapshot: snapshotSetupState,+ signal,+ });+ if (result.kind !== "done") return { kind: "cancelled" };++ const updatedAuthored = new Set(await deps.listAuthoredConnections(appRoot));+ if (!updatedAuthored.has(selected)) {+ throw new Error(`Connection "${selected}" was not added.`);+ }+ return { kind: "done", addedConnections: [selected] };+ } catch (error) {+ if (error instanceof WizardCancelledError) return { kind: "cancelled" };+ const updatedAuthored = new Set(await deps.listAuthoredConnections(appRoot));+ return {+ kind: "failed",+ addedConnections: updatedAuthored.has(selected) ? [selected] : [],+ message: toErrorMessage(error),+ };+ }+}diff --git a/packages/eve/src/setup/flows/link.test.ts b/packages/eve/src/setup/flows/link.test.tsindex 774850c0c..b9ae1516c 100644--- a/packages/eve/src/setup/flows/link.test.ts+++ b/packages/eve/src/setup/flows/link.test.ts@@ -129,6 +129,8 @@ describe("runLinkFlow", () => {});it("offers create when the caller passes create-or-link (the /model branch)", async () => {+ const teamSelectMessage = () =>+ "You need to link to a project to use Vercel Connect.\n\nSelect your team";const { prompter } = createFakePrompter({single: (opts) => {if (stripVTControlCharacters(opts.message) === "Vercel project") return "new";@@ -142,6 +144,7 @@ describe("runLinkFlow", () => {prompter,deps,projectSelection: "create-or-link",+ teamSelectMessage,});expect(result).toEqual({ kind: "done", credential: "VERCEL_OIDC_TOKEN" });@@ -149,6 +152,13 @@ describe("runLinkFlow", () => {// existing-project picker — the opposite of the existing-only default.expect(deps.resolveProvisioning?.pickNewProjectName).toHaveBeenCalled();expect(deps.resolveProvisioning?.pickProject).not.toHaveBeenCalled();+ expect(deps.resolveProvisioning?.pickTeam).toHaveBeenCalledWith(+ expect.anything(),+ APP_ROOT,+ undefined,+ expect.objectContaining({ selectMessage: teamSelectMessage }),+ );+ expect(prompter.log.message).not.toHaveBeenCalled();});it("runs the pickers on re-link even when the on-disk link is adoptable", async () => {diff --git a/packages/eve/src/setup/flows/link.ts b/packages/eve/src/setup/flows/link.tsindex 27088d42d..3db9afd63 100644--- a/packages/eve/src/setup/flows/link.ts+++ b/packages/eve/src/setup/flows/link.ts@@ -64,6 +64,7 @@ export async function runLinkFlow(input: {* branch, where a fresh agent has no project yet).*/projectSelection?: "create-or-link" | "existing-only";+ teamSelectMessage?: (currentTeam: string) => string;deps?: Partial<LinkFlowDeps>;}): Promise<LinkFlowResult> {const { appRoot, prompter, signal, projectSelection = "existing-only" } = input;@@ -87,7 +88,7 @@ export async function runLinkFlow(input: {deps.findEnvFileWithKey(appRoot, "VERCEL_OIDC_TOKEN"),]);const credentialFile = gatewayKey ?? oidc;- if (credentialFile !== undefined) {+ if (credentialFile !== undefined && input.teamSelectMessage === undefined) {prompter.log.message(`This directory is not linked to a Vercel project yet — the model currently runs on credentials from ${credentialFile}.`,);@@ -134,6 +135,7 @@ export async function runLinkFlow(input: {// agent can create its first project here instead of dead-ending on an// empty project list.projectSelection,+ teamSelectMessage: input.teamSelectMessage,deps: deps.resolveProvisioning,}),linkVercelProject({ prompter, deps: deps.linkProject }),diff --git a/packages/eve/src/setup/project-resolution.ts b/packages/eve/src/setup/project-resolution.tsindex 651167a66..fcfcfffd0 100644--- a/packages/eve/src/setup/project-resolution.ts+++ b/packages/eve/src/setup/project-resolution.ts@@ -1,7 +1,12 @@-import { readFile, stat } from "node:fs/promises";+import { stat } from "node:fs/promises";import { join } from "node:path";import { z } from "zod";+import {+ readVercelProjectLink,+ type VercelProjectLink,+ VercelProjectLinkSchema,+} from "#internal/vercel/project-link.js";import { captureVercel } from "./primitives/run-vercel.js";/** Link and production-deployment status for a Vercel project directory. */@@ -15,18 +20,13 @@ export interface DeploymentInfo {productionUrl?: string;}-const VercelProjectReferenceSchema = z.object({- projectId: z.string().min(1),- orgId: z.string().min(1),- projectName: z.string().min(1).optional(),-});const VercelProjectEnvironmentSchema = z.object({- VERCEL_ORG_ID: VercelProjectReferenceSchema.shape.orgId,- VERCEL_PROJECT_ID: VercelProjectReferenceSchema.shape.projectId,+ VERCEL_ORG_ID: VercelProjectLinkSchema.shape.orgId,+ VERCEL_PROJECT_ID: VercelProjectLinkSchema.shape.projectId,});/** Validated Vercel owner and project identifiers. */-export type VercelProjectReference = z.infer<typeof VercelProjectReferenceSchema>;+export type VercelProjectReference = VercelProjectLink;/** Parses the complete Vercel owner and project environment pair. */export function projectReferenceFromEnvironment(@@ -59,13 +59,7 @@ export async function readProjectLink(projectPath: string,): Promise<VercelProjectReference | undefined> {await assertNoLegacyProjectLinkDirectory(projectPath);- try {- const raw = await readFile(join(projectPath, ".vercel", "project.json"), "utf8");- const parsed = VercelProjectReferenceSchema.safeParse(JSON.parse(raw));- return parsed.success ? parsed.data : undefined;- } catch {- return undefined;- }+ return await readVercelProjectLink(projectPath);}interface VercelApiProject {diff --git a/packages/eve/src/setup/prompter.ts b/packages/eve/src/setup/prompter.tsindex 0f36b75b2..256aaf413 100644--- a/packages/eve/src/setup/prompter.ts+++ b/packages/eve/src/setup/prompter.ts@@ -33,6 +33,8 @@ export type PrompterValue = string | number | boolean;export interface SelectOption<T extends PrompterValue> {value: T;label: string;+ /** Completion action kept after searchable results instead of being filtered. */+ trailingAction?: boolean;hint?: string;/** Short inline annotation shown dimmed only while the cursor is on this row. */focusHint?: string;diff --git a/packages/eve/src/setup/scaffold/connections/catalog.test.ts b/packages/eve/src/setup/scaffold/connections/catalog.test.tsindex ee5f07275..2e08953f8 100644--- a/packages/eve/src/setup/scaffold/connections/catalog.test.ts+++ b/packages/eve/src/setup/scaffold/connections/catalog.test.ts@@ -1,6 +1,7 @@import { describe, expect, test } from "vitest";import {+ canonicalConnectorNameForEntry,catalogSlugs,CONNECTION_CATALOG,connectorServiceForEntry,@@ -41,12 +42,13 @@ describe("catalog integrity", () => {test("every Connect entry resolves a `vercel connect create` service", () => {for (const entry of CONNECTION_CATALOG) {expect(connectorServiceForEntry(entry)).toBeTruthy();+ expect(canonicalConnectorNameForEntry(entry)).toBeTruthy();}});});describe("connectorServiceForEntry", () => {- test("prefers the explicit service over the MCP host", () => {+ test("prefers the explicit service over the MCP endpoint", () => {expect(connectorServiceForEntry({mcp: { url: "https://mcp.example.com/sse" },@@ -71,6 +73,26 @@ describe("connectorServiceForEntry", () => {});});+describe("canonicalConnectorNameForEntry", () => {+ test("uses the configured connector name without inferring a UID namespace", () => {+ expect(canonicalConnectorNameForEntry(getCatalogEntry("notion")!)).toBe("notion");+ expect(+ canonicalConnectorNameForEntry({+ auth: { kind: "connect", connector: "custom", service: "mcp.example.com/mcp" },+ }),+ ).toBe("custom");+ });+});++describe("curated Connect services", () => {+ test("uses the provider's managed service identifier", () => {+ expect(connectorServiceForEntry(getCatalogEntry("linear")!)).toBe("mcp.linear.app");+ expect(connectorServiceForEntry(getCatalogEntry("notion")!)).toBe("mcp.notion.com");+ expect(connectorServiceForEntry(getCatalogEntry("datadog")!)).toBe("mcp.datadoghq.com");+ expect(connectorServiceForEntry(getCatalogEntry("honeycomb")!)).toBe("mcp.honeycomb.io");+ });+});+describe("mcpServiceHost", () => {test("extracts the host from a URL", () => {expect(mcpServiceHost("https://mcp.linear.app/sse")).toBe("mcp.linear.app");diff --git a/packages/eve/src/setup/scaffold/connections/catalog.ts b/packages/eve/src/setup/scaffold/connections/catalog.tsindex f9ec660cd..c93c46c39 100644--- a/packages/eve/src/setup/scaffold/connections/catalog.ts+++ b/packages/eve/src/setup/scaffold/connections/catalog.ts@@ -42,8 +42,9 @@ export type ConnectionAuthSpec =* It starts as a placeholder and is rewritten to the real connector UID once* the connector is provisioned (see {@link service}). `service` is the* managed-connector identifier passed to `vercel connect create <service>`- * (e.g. the MCP host `mcp.linear.app`); when omitted, the connector must be- * created out of band and its UID set by hand.+ * (e.g. `mcp.linear.app`); when omitted, eve falls back to the MCP endpoint+ * host. It is distinct from the connector UID, which Vercel assigns when the+ * connector is created or listed.*/| { kind: "connect"; connector: string; service?: string }/** Static bearer token read from a single environment variable. */@@ -102,6 +103,9 @@ export const CUSTOM_CONNECTION_SLUG = "custom";* when the scaffolder emits its template. Every connection in the catalog must* have an entry here — {@link buildCatalogEntry} throws otherwise.*/+// The service is Vercel's managed provider identifier, not the MCP endpoint+// URL. Keep these provider-owned keys explicit instead of deriving them from+// the endpoint path.const CONNECTION_AUTH: Readonly<Record<string, ConnectionAuthSpec>> = {linear: { kind: "connect", connector: "linear", service: "mcp.linear.app" },notion: { kind: "connect", connector: "notion", service: "mcp.notion.com" },@@ -182,9 +186,9 @@ export function isValidConnectionSlug(slug: string): boolean {/*** The `vercel connect create <service>` identifier for a Connect-backed- * connection: the explicit `auth.service` when set, otherwise the host of the- * MCP endpoint (e.g. `mcp.linear.app`). Returns `undefined` when neither is- * available, in which case the connector must be provisioned out of band.+ * connection: the explicit `auth.service` when set, otherwise the MCP host.+ * Returns `undefined` when neither is available, in which case the connector+ * must be provisioned out of band.*/export function connectorServiceForEntry(entry: Pick<ConnectionCatalogEntry, "mcp" | "auth">,@@ -194,6 +198,15 @@ export function connectorServiceForEntry(return mcpServiceHost(entry.mcp?.url);}+/** Canonical connector name attempted before offering discovery or creation. */+export function canonicalConnectorNameForEntry(entry: {+ auth?: ConnectionAuthSpec;+}): string | undefined {+ if (entry.auth?.kind !== "connect") return undefined;+ const name = entry.auth.connector.trim();+ return name.length > 0 ? name : undefined;+}+/** Extracts the bare host from an MCP URL, or `undefined` when unparseable. */export function mcpServiceHost(url: string | undefined): string | undefined {if (!url) return undefined;diff --git a/packages/eve/src/setup/scaffold/create/web-template.ts b/packages/eve/src/setup/scaffold/create/web-template.tsindex 089c66a78..a3b092b79 100644--- a/packages/eve/src/setup/scaffold/create/web-template.ts+++ b/packages/eve/src/setup/scaffold/create/web-template.ts@@ -3,7 +3,7 @@export const WEB_APP_TEMPLATE_FILES = {"agent/channels/eve.ts":- 'import { eveChannel } from "eve/channels/eve";\nimport { localDev, placeholderAuth, vercelOidc } from "eve/channels/auth";\n\nexport default eveChannel({\n auth: [\n // Open on localhost for `eve dev` and the REPL; ignored in production.\n localDev(),\n // Lets the eve TUI and your Vercel deployments reach the deployed agent.\n vercelOidc(),\n // This placeholder will not allow browser requests in production.\n // Replace it with your app\'s auth provider, like Auth.js or Clerk,\n // or use none() for a public demo.\n placeholderAuth(),\n ],\n});\n',+ 'import { eveChannel } from "eve/channels/eve";\nimport { localDev, placeholderAuth, vercelOidc } from "eve/channels/auth";\n\nexport default eveChannel({\n auth: [\n // Lets the eve TUI and your Vercel deployments reach the deployed agent.\n vercelOidc(),\n // Open on localhost for `eve dev` and the REPL; ignored in production.\n localDev(),\n // This placeholder will not allow browser requests in production.\n // Replace it with your app\'s auth provider, like Auth.js or Clerk,\n // or use none() for a public demo.\n placeholderAuth(),\n ],\n});\n',"app/_components/agent-chat.tsx":'"use client";\n\nimport { useEveAgent } from "eve/react";\nimport { AlertCircleIcon } from "lucide-react";\nimport {\n Conversation,\n ConversationContent,\n ConversationScrollButton,\n} from "@/components/ai-elements/conversation";\nimport {\n PromptInput,\n type PromptInputMessage,\n PromptInputSubmit,\n PromptInputTextarea,\n} from "@/components/ai-elements/prompt-input";\nimport { cn } from "@/lib/utils";\nimport { AgentMessage } from "./agent-message";\n\nconst AGENT_NAME = "__EVE_INIT_APP_NAME__";\n\ntype AgentStatus = ReturnType<typeof useEveAgent>["status"];\n\nexport function AgentChat() {\n const agent = useEveAgent();\n const isBusy = agent.status === "submitted" || agent.status === "streaming";\n const isEmpty = agent.data.messages.length === 0;\n\n const handleSubmit = async (message: PromptInputMessage) => {\n const text = message.text.trim();\n if (!text || isBusy) return;\n\n await agent.send({ message: text });\n };\n\n const composer = (\n <PromptInput onSubmit={handleSubmit}>\n <PromptInputTextarea placeholder="Send a message…" />\n <PromptInputSubmit onStop={agent.stop} status={agent.status} />\n </PromptInput>\n );\n\n return (\n <main className="flex h-dvh flex-col overflow-hidden bg-background text-foreground">\n {isEmpty ? null : (\n <header className="flex h-14 shrink-0 items-center justify-center gap-3 pl-4 pr-2">\n <span className="flex min-w-0 items-center gap-2">\n <span className="truncate text-muted-foreground text-sm">{AGENT_NAME}</span>\n <StatusDot status={agent.status} />\n </span>\n </header>\n )}\n\n {agent.error ? (\n <div className="mx-auto w-full max-w-3xl shrink-0 px-4 pt-2 sm:px-6">\n <div className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2.5 text-sm">\n <AlertCircleIcon className="mt-0.5 size-4 shrink-0 text-destructive" />\n <div>\n <p className="font-medium">Request failed</p>\n <p className="mt-0.5 text-muted-foreground">{agent.error.message}</p>\n </div>\n </div>\n </div>\n ) : null}\n\n {isEmpty ? null : (\n <Conversation className="min-h-0 flex-1">\n <ConversationContent className="mx-auto w-full max-w-3xl gap-6 px-4 py-6 sm:px-6">\n {agent.data.messages.map((message, index) => (\n <AgentMessage\n canRespond={!isBusy}\n isStreaming={\n agent.status === "streaming" && index === agent.data.messages.length - 1\n }\n key={message.id}\n message={message}\n onInputResponses={(inputResponses) => agent.send({ inputResponses })}\n />\n ))}\n </ConversationContent>\n <ConversationScrollButton />\n </Conversation>\n )}\n\n <div\n className={cn(\n "mx-auto w-full px-4 sm:px-6",\n isEmpty\n ? "flex max-w-xl flex-1 flex-col items-center justify-center gap-8 pb-[10vh]"\n : "max-w-3xl shrink-0 pb-6",\n )}\n >\n {isEmpty ? (\n <div className="flex flex-col items-center gap-3 text-center">\n <h1 className="font-medium text-5xl tracking-tighter">{AGENT_NAME}</h1>\n </div>\n ) : null}\n <div className="w-full">{composer}</div>\n </div>\n </main>\n );\n}\n\nfunction StatusDot({ status }: { readonly status: AgentStatus }) {\n const isLive = status === "submitted" || status === "streaming";\n const tone =\n status === "error"\n ? "bg-destructive"\n : isLive\n ? "bg-emerald-500"\n : status === "ready"\n ? "bg-muted-foreground"\n : "bg-muted-foreground/50";\n\n return (\n <span className="relative flex size-1">\n {isLive ? (\n <span\n className={cn(\n "absolute inline-flex size-full animate-ping rounded-full opacity-75",\n tone,\n )}\n />\n ) : null}\n <span className={cn("relative inline-flex size-1 rounded-full transition-colors", tone)} />\n </span>\n );\n}\n',"app/_components/agent-message.tsx":diff --git a/packages/eve/src/setup/scaffold/index.ts b/packages/eve/src/setup/scaffold/index.tsindex f3661b865..b5c469a37 100644--- a/packages/eve/src/setup/scaffold/index.ts+++ b/packages/eve/src/setup/scaffold/index.ts@@ -27,11 +27,13 @@ export { SCAFFOLDABLE_CHANNELS, type ScaffoldableChannel } from "./channels-cataexport {ensureConnection,+ ensureConnectionDependencies,listAuthoredConnections,type ConnectionInput,type ConnectionMutationAction,type ConnectionMutationResult,type EnsureConnectionOptions,+ type EnsureConnectionDependenciesOptions,} from "./update/connections.js";export {diff --git a/packages/eve/src/setup/scaffold/update/connections.ts b/packages/eve/src/setup/scaffold/update/connections.tsindex 2f2e057bf..ee6e7f606 100644--- a/packages/eve/src/setup/scaffold/update/connections.ts+++ b/packages/eve/src/setup/scaffold/update/connections.ts@@ -53,6 +53,11 @@ export interface EnsureConnectionOptions {connectPackageVersion?: string;}+export interface EnsureConnectionDependenciesOptions {+ projectRoot: string;+ connectPackageVersion?: string;+}+function resolveAuth(entry: ConnectionInput): ConnectionAuthSpec {return entry.auth ?? { kind: "none" };}@@ -158,6 +163,17 @@ async function ensureConnectDependency(];}+/** Adds the package dependency required by a Connect-auth connection. */+export async function ensureConnectionDependencies(+ options: EnsureConnectionDependenciesOptions,+): Promise<PackageJsonMutation[]> {+ const version = resolveVersionToken(+ "connectPackageVersion",+ options.connectPackageVersion ?? DEFAULT_CONNECT_PACKAGE_VERSION,+ );+ return ensureConnectDependency(join(options.projectRoot, "package.json"), version);+}+function envKeyPresent(source: string, key: string): boolean {const pattern = new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`, "m");return pattern.test(source);diff --git a/packages/eve/test/scenarios/agent-info-route.scenario.test.ts b/packages/eve/test/scenarios/agent-info-route.scenario.test.tsindex e314a801e..26a62f2f8 100644--- a/packages/eve/test/scenarios/agent-info-route.scenario.test.ts+++ b/packages/eve/test/scenarios/agent-info-route.scenario.test.ts@@ -71,10 +71,10 @@ describe("handleAgentInfoRequest", () => {});it("returns 401 without a Vercel OIDC bearer token when the request is addressed to a public hostname", async () => {- // The default chain `[localDev(), vercelOidc()]` must reject public+ // The default chain `[vercelOidc(), localDev()]` must reject public// traffic that arrives without a token, regardless of `process.env`.- // `localDev()` skips because the request URL is not loopback;- // `vercelOidc()` rejects because there is no bearer token.+ // `vercelOidc()` skips because there is no bearer token; `localDev()`+ // skips because the request URL is not loopback.const { agentRoot, appRoot } = await createAppRoot("eve-agent-info-route-deployed-",APP_ROOT_OPTIONS,diff --git a/packages/eve/test/scenarios/verify-oidc.scenario.test.ts b/packages/eve/test/scenarios/verify-oidc.scenario.test.tsindex 0f0baa0d4..8d6627079 100644--- a/packages/eve/test/scenarios/verify-oidc.scenario.test.ts+++ b/packages/eve/test/scenarios/verify-oidc.scenario.test.ts@@ -1,7 +1,7 @@import { createServer } from "node:http";import { exportJWK, generateKeyPair, SignJWT } from "jose";-import { afterEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";import { authenticateOidcStrategy } from "../../src/runtime/governance/auth/oidc.js";@@ -16,15 +16,8 @@ import { authenticateOidcStrategy } from "../../src/runtime/governance/auth/oidc* verifier tests (`verifyVercelOidc`, `verifyJwtHmac`, etc.) live* alongside the source module under `src/public/channels/auth.test.ts`.*/-afterEach(() => {- vi.unstubAllEnvs();-});-describe("authenticateOidcStrategy", () => {it("upgrades a current-project Vercel token to principalType: runtime", async () => {- vi.stubEnv("VERCEL_PROJECT_ID", "prj_test");- vi.stubEnv("VERCEL_TARGET_ENV", "preview");-const oidcServer = await startOidcTestIssuer();try {@@ -47,6 +40,10 @@ describe("authenticateOidcStrategy", () => {acceptCurrentVercelProject: true,audiences: ["https://vercel.com/acme"],clockSkewSeconds: 30,+ currentVercelProject: {+ environment: "preview",+ projectId: "prj_test",+ },discoveryUrl: oidcServer.discoveryUrl,issuer: oidcServer.issuer,kind: "oidc",diff --git a/packages/eve/test/tui-client/tui-connection-auth-states.ts b/packages/eve/test/tui-client/tui-connection-auth-states.tsindex f53af28f5..5c908ebb7 100644--- a/packages/eve/test/tui-client/tui-connection-auth-states.ts+++ b/packages/eve/test/tui-client/tui-connection-auth-states.ts@@ -13,15 +13,17 @@ import { theme } from "./lib/theme.ts";* emit `_completed` in this repo (interactive auth* requires a `principalType: "user"` session, which apps/fixtures/agent-tui-client* doesn't currently provide). This smoke fills that gap with a- * `FakeSession` that returns a synthetic event stream, so we get+ * `FakeSession` that separates the parked request stream from the callback+ * continuation stream, so we get* deterministic coverage of:** 1. `_required` with a populated challenge (URL, user code,* instructions). That proves the renderer surfaces all three* challenge fields, which the live smoke can't show.- * 2. `_completed` with `outcome: "authorized"`. That proves the- * right-title transitions, the status bar override clears,- * and the section becomes terminal.+ * 2. `_completed` with `outcome: "authorized"` after `session.waiting`.+ * That proves the root TUI follows `session.stream()` until the OAuth+ * callback resumes the durable workflow, flips the right-title, clears+ * the status-bar override, and settles the section.* 3. A second turn with `outcome: "failed"` + a reason. That* proves the failure path renders distinctly and the reason* string surfaces in the section content.@@ -29,9 +31,14 @@ import { theme } from "./lib/theme.ts";class FakeSession extends ClientSession {readonly #turns: ReadonlyArray<readonly HandleMessageStreamEvent[]>;+ readonly #continuations: ReadonlyArray<readonly HandleMessageStreamEvent[]>;#turnIndex = 0;+ #continuationIndex = 0;- constructor(turns: ReadonlyArray<readonly HandleMessageStreamEvent[]>) {+ constructor(input: {+ turns: ReadonlyArray<readonly HandleMessageStreamEvent[]>;+ continuations: ReadonlyArray<readonly HandleMessageStreamEvent[]>;+ }) {super({host: "http://fake.invalid",@@ -41,7 +48,8 @@ class FakeSession extends ClientSession {},{ streamIndex: 0 },);- this.#turns = turns;+ this.#turns = input.turns;+ this.#continuations = input.continuations;}override async send<TOutput = unknown>(): Promise<MessageResponse<TOutput>> {@@ -50,19 +58,26 @@ class FakeSession extends ClientSession {return new MessageResponse<TOutput>({sessionId: "fake-session",continuationToken: `fake-token-${this.#turnIndex}`,- createStream: async function* () {- for (const event of events) {- yield event;- // Pacing so the renderer paints between each event AND the- // smoke's `waitForCondition` (50ms poll) has time to observe- // intermediate states. Real streams have natural pacing from- // the HTTP transport; a synchronous yield burst makes- // intermediate states impossible to assert on.- await sleep(200);- }- },+ createStream: () => pacedEvents(events),});}++ override stream(): AsyncIterable<HandleMessageStreamEvent> {+ const events = this.#continuations[this.#continuationIndex] ?? [];+ this.#continuationIndex += 1;+ return pacedEvents(events);+ }+}++async function* pacedEvents(+ events: readonly HandleMessageStreamEvent[],+): AsyncGenerator<HandleMessageStreamEvent> {+ for (const event of events) {+ yield event;+ // Pacing gives the renderer and smoke assertions a chance to observe+ // each lifecycle state between events, as the HTTP transport does live.+ await sleep(200);+ }}const turnId = "turn-0";@@ -88,13 +103,17 @@ const firstTurn: HandleMessageStreamEvent[] = [sequence: next(),stepIndex,turnId,- webhookUrl: "http://localhost:3000/.well-known/eve/v1/connections/stub-mcp/callback/xyz",+ webhookUrl: "http://localhost:3000/eve/v1/connections/stub-mcp/callback/xyz",},},- // In a real workflow, the next events arrive only after the webhook- // callback fires and `completeAuthorization` resolves. The synthetic- // stream emits them after a short delay (above, via the per-event- // sleep) so the smoke can observe the intermediate state.+ {+ type: "step.completed",+ data: { finishReason: "stop", sequence: next(), stepIndex, turnId },+ },+ { type: "session.waiting", data: { wait: "next-user-message" } },+];++const firstCallbackTurn: HandleMessageStreamEvent[] = [{type: "authorization.completed",data: {@@ -127,8 +146,17 @@ const secondTurn: HandleMessageStreamEvent[] = [sequence: next(),stepIndex,turnId: secondTurnId,+ webhookUrl: "http://localhost:3000/eve/v1/connections/other-mcp/callback/xyz",},},+ {+ type: "step.completed",+ data: { finishReason: "stop", sequence: next(), stepIndex, turnId: secondTurnId },+ },+ { type: "session.waiting", data: { wait: "next-user-message" } },+];++const secondCallbackTurn: HandleMessageStreamEvent[] = [{type: "authorization.completed",data: {@@ -150,7 +178,10 @@ const secondTurn: HandleMessageStreamEvent[] = [process.env.EVE_TUI_UNICODE = "1";void (async () => {- const session = new FakeSession([firstTurn, secondTurn]);+ const session = new FakeSession({+ turns: [firstTurn, secondTurn],+ continuations: [firstCallbackTurn, secondCallbackTurn],+ });const screen = new MockScreen({ columns: 100, rows: 40 });const input = new MockUserInput();const runner = new EveTUIRunner({@@ -202,6 +233,25 @@ void (async () => {});console.log(theme.muted("[states] right-title flipped to authorized"));+ await waitForCondition(+ () => {+ const snap = screen.snapshot();+ return (+ snap.includes("Authorization complete") &&+ !snap.includes("Authorization required for stub-mcp") &&+ !snap.includes("URL: https://example.com/authorize/stub-mcp") &&+ !snap.includes("Code: STUB-1234") &&+ !snap.includes("Visit the URL above")+ );+ },+ {+ timeoutMs: 5_000,+ label: "completed authorization replaces the stale challenge body",+ onTimeout: () => screen.snapshot(),+ },+ );+ console.log(theme.muted("[states] completed authorization body replaced the challenge"));+await waitForCondition(() => !screen.snapshot().includes("Waiting for connection authorization"),{diff --git a/packages/eve/test/tui-client/tui-subagents-weather.ts b/packages/eve/test/tui-client/tui-subagents-weather.tsindex 18e2209cf..1c0af8597 100644--- a/packages/eve/test/tui-client/tui-subagents-weather.ts+++ b/packages/eve/test/tui-client/tui-subagents-weather.ts@@ -4,7 +4,7 @@ import { setTimeout as sleep } from "node:timers/promises";import { Client } from "eve/client";import { EveTUIRunner, MockScreen, MockUserInput } from "./lib/tui.ts";-import { run } from "./lib/run.ts";+import { run, type RunOptions } from "./lib/run.ts";import { theme } from "./lib/theme.ts";/**@@ -33,7 +33,15 @@ const TICKER = "GOOG";const PRICE = "178.92";process.env.EVE_TUI_UNICODE = "1";-run({ app: "agent-subagents-hitl", kind: "local-build" }, async (target) => {+const WEATHER_SMOKE_TARGET: RunOptions = {+ app: "agent-subagents-hitl",+ kind: "local-build",+ // The spawned server must use the deterministic authored-model adapter;+ // otherwise this TUI rendering smoke depends on an AI Gateway credential.+ startEnv: { ...process.env, EVE_MOCK_AUTHORED_MODELS: "1" },+};++run(WEATHER_SMOKE_TARGET, async (target) => {const client = new Client({ host: target.baseUrl });const session = client.session();const screen = new MockScreen({ columns: 140, rows: 60 });diff --git a/packages/eve/vitest.scenario.config.ts b/packages/eve/vitest.scenario.config.tsindex a8f767fc1..028878b48 100644--- a/packages/eve/vitest.scenario.config.ts+++ b/packages/eve/vitest.scenario.config.ts@@ -7,8 +7,9 @@ import { defineConfig } from "vitest/config";* listeners, real compile/bundle pipelines, or real workflow on-disk state.* Scenario tests take seconds to run and frequently mutate* `process.cwd`/`process.env`, so each file runs in its own forked worker- * process to guarantee isolation. Tests within a single file still run- * sequentially.+ * process. Some scenarios also rebuild the workspace package, which clears+ * its shared `dist/` directory; files therefore run serially. Tests within a+ * single file still run sequentially.** Nothing in this tier is expected to be hermetic. Keep the set small —* anything that can be expressed through the in-memory `AppHarness` belongs@@ -30,6 +31,7 @@ export default defineConfig({test: {environment: "node",exclude: ["**/node_modules/**", "test/vercel/**"],+ fileParallelism: false,globalSetup: ["./test/setup/pack-scenario-tarball.ts"],include: ["src/**/*.scenario.test.ts", "test/scenarios/**/*.scenario.test.ts"],setupFiles: ["./test/setup/mock-ai-gateway.ts"],