The Open Framework for Building Agents
feat(eve): recover remote TUI authentication (#111)
Ruia63dfa2eaa90
diff --git a/.changeset/project-search-ranking.md b/.changeset/project-search-ranking.mdnew file mode 100644index 000000000..8f70d7170--- /dev/null+++ b/.changeset/project-search-ranking.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Project search now resolves exact names directly and ranks one fallback result page, avoiding unbounded substring-match pagination for short queries.diff --git a/.changeset/remote-auth-owner-id.md b/.changeset/remote-auth-owner-id.mdnew file mode 100644index 000000000..4b57adae7--- /dev/null+++ b/.changeset/remote-auth-owner-id.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Fixed `/vc:auth` rejecting a freshly selected Vercel project with "The local Vercel OIDC token does not match the resolved deployment: owner_id." The verified deployment now takes its owner id from Vercel's response instead of the team slug used to scope the lookup, so it matches the OIDC token's `owner_id` claim.diff --git a/.changeset/remote-auth-resolve-from-url.md b/.changeset/remote-auth-resolve-from-url.mdnew file mode 100644index 000000000..e0f1ae7de--- /dev/null+++ b/.changeset/remote-auth-resolve-from-url.md@@ -0,0 +1,5 @@+---+"eve": patch+---++`/vc:auth` now resolves the target Vercel project and owning team directly from the deployment URL instead of prompting you to pick a team and project. You can authenticate any deployment you can access — including custom domains and aliases — without a picker, and when access is denied (for example an expired team SSO session) it re-authenticates and retries.diff --git a/.changeset/remote-info-best-effort.md b/.changeset/remote-info-best-effort.mdnew file mode 100644index 000000000..81efff730--- /dev/null+++ b/.changeset/remote-info-best-effort.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Remote `eve dev --url` now treats `/eve/v1/info` as best-effort inspection rather than a connection gate. Once authentication succeeds and the deployment is reachable, the session connects even when the agent info route is absent (confirmed via the public health route) or returns an unrecognized shape (e.g. a deployment built from an older eve). Inspection-only data is simply omitted from the header in that case, and the underlying parse failure now names the offending fields instead of an opaque message.diff --git a/.changeset/remote-tui-oidc.md b/.changeset/remote-tui-oidc.mdnew file mode 100644index 000000000..84697d287--- /dev/null+++ b/.changeset/remote-tui-oidc.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Remote `eve dev --url` sessions now show deployment and authentication state, try refreshed project-scoped OIDC credentials at startup, and open a cancellable `/vc:auth` recovery flow when access is rejected. The flow can update the target project's Trusted Sources after confirmation.diff --git a/.changeset/vc-commands-rename.md b/.changeset/vc-commands-rename.mdnew file mode 100644index 000000000..817f02a36--- /dev/null+++ b/.changeset/vc-commands-rename.md@@ -0,0 +1,5 @@+---+"eve": patch+---++The dev TUI's `/vc` and `/login` commands are now `/vc:install` and `/vc:login`, matching `/vc:auth`, and both are available in remote (`eve dev --url`) sessions. You can install the Vercel CLI or log in while connected to a remote — the prerequisites `/vc:auth` may need — instead of only in a local session.diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.mdindex d62b73e9b..0312bb7b4 100644--- a/docs/guides/dev-tui.md+++ b/docs/guides/dev-tui.md@@ -24,23 +24,26 @@ The conversation streams straight into your terminal's normal scrollback, so youEach turn renders without boxes. A colored gutter glyph marks who is speaking, tool calls collapse to a one-line summary (`✓ get_weather city="SF" → 73°F`), and a subagent's work is indented beneath its `◆` header. When input is ready, the prompt stays bare until you type. A green circle-dot pulses while the agent is waiting to answer and disappears when reasoning or answer content begins.-A persistent line beneath the prompt or status shows the model, the session's token flow (`↑ 394.4K ↓ 4.3K`), the linked Vercel project and team (`▲ my-agent (acme)`), and a yellow `/deploy pending` marker once a channel added this session still needs `/deploy`. The Vercel segment stays hidden until the directory is linked.+A persistent line beneath the prompt or status shows the model, the session's token flow (`↑ 394.4K ↓ 4.3K`), the linked Vercel project, and a yellow `/deploy pending` marker once a channel added this session still needs `/deploy`. The Vercel segment stays hidden until the directory is linked. Remote sessions lead with a padded `↗ project (environment)` badge, or the host when Vercel cannot resolve the deployment. The badge is gray while checking or unavailable, yellow while authentication is required or failed, and blue when connected. Remote status lines omit AI Gateway endpoint state.Errors render compactly with docs links highlighted. A code bug escaping your agent's own code shows its stack trace dim beneath the error headline. Dev-server rebuilds condense into one status row that updates in place (`tui/setup-panel.ts changed · rebuilding…`, then `· rebuilt`); only the latest rebuild shows, and paths shrink to their last two components.## 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 and channel setup use the same green square pulse as the build phase. 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). |-| `/deploy` | Ships the agent to Vercel production, linking the directory first when it is unlinked. |-| `/loglevel` | Switches which logs the transcript shows. See [Control what logs show](#control-what-logs-show). |-| `/new` | Starts a fresh session. |-| `/exit` | Quits the TUI. |-| `/help` | Lists every command. |+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`, `/vc:auth`) 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.++| 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). |+| `/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 the Vercel CLI into an account. Available locally and on a remote session. |+| `/vc:auth` | Resolves the remote's Vercel project from its deployment URL, refreshes its OIDC token, and confirms any required Trusted Sources rule. Remote only. |+| `/loglevel` | Switches which logs the transcript shows. See [Control what logs show](#control-what-logs-show). |+| `/new` | Starts a fresh session. |+| `/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`.@@ -119,7 +122,15 @@ Pass a URL and the TUI talks to a running deployment instead of starting a localeve dev https://<your-app>```-The bare URL is shorthand for `--url`; `--host`, `--port`, and `--no-ui` cannot be combined with a remote target. Eve gets the expected Vercel owner and project from `VERCEL_ORG_ID` and `VERCEL_PROJECT_ID` when both are set, or from the current directory's Vercel link otherwise. It verifies the exact deployment origin before attaching a freshly resolved project-scoped OIDC token or `VERCEL_AUTOMATION_BYPASS_SECRET`. Unverified URLs remain anonymous, and credential-bearing requests do not follow redirects. See [Deployment](./deployment) for the smoke-test flow.+The bare URL is shorthand for `--url`; it cannot be combined with `--host`, `--port`, or `--no-ui`.++At startup the TUI gets the expected Vercel owner and project from `VERCEL_ORG_ID` and `VERCEL_PROJECT_ID` when both are set, or from the current directory's Vercel link otherwise. It asks Vercel to prove that the remote origin belongs to that project. Only that proof allows the client to request a project-scoped OIDC token—refreshing an expired development token when refresh credentials exist—or attach an automation-bypass secret; an unverified URL is probed anonymously. The TUI then requests `/eve/v1/info`, with a ten-second timeout. A successful response marks the remote ready. An eve OIDC challenge, Vercel Deployment Protection challenge, or `TRUSTED_SOURCES_ENVIRONMENT_MISMATCH` opens `/vc:auth` automatically; ordinary network failures and server errors remain remote-availability errors and do not start an authentication flow. Esc or Ctrl-C cancels the authentication flow.++`/vc:auth` can use the directory's current Vercel project or show your Vercel teams and their existing projects. If the CLI is logged out, the same panel runs the browser login first. The flow verifies that the selected project owns the remote deployment, asks before adding any required Trusted Sources rule, and requests a project-scoped token through `@vercel/oidc`. It does not relink the directory or modify `.env.local`. Finally, it retries `/eve/v1/info` to prove the credential works. A failure reports any login or Trusted Sources update that completed before it stopped.++The project-scoped token represents the selected project's Development environment. Vercel already allows a project's Development environment to call its own Preview deployments by default. For a Production or custom-environment target, `/vc:auth` shows the exact Development-to-target rule before changing that project's Trusted Sources. Eve preserves existing entries. When it creates an explicit rule, it also carries Vercel's default self-access rows forward because saved rules replace those defaults. See Vercel's [Trusted Sources guide](https://vercel.com/docs/deployment-protection/methods-to-bypass-deployment-protection/trusted-sources), [error reference](https://vercel.com/docs/errors/trusted_sources_environment_mismatch), and [OIDC token anatomy](https://vercel.com/docs/oidc/reference#oidc-token-anatomy).++`VERCEL_AUTOMATION_BYPASS_SECRET` remains available for a Protection Bypass for Automation token. See [Deployment](./deployment) for the smoke-test flow.## What to read nextdiff --git a/packages/eve/src/cli/dev/tui/blocks.ts b/packages/eve/src/cli/dev/tui/blocks.tsindex 4154ae379..424ff3d45 100644--- a/packages/eve/src/cli/dev/tui/blocks.ts+++ b/packages/eve/src/cli/dev/tui/blocks.ts@@ -67,7 +67,7 @@ export interface Block {*/detail?: string;- /** Tool / connection lifecycle status. */+ /** Tool, connection, or synthetic command lifecycle status. */status?: ToolStatus;/** When true, treat `body` as pre-styled and only wrap + indent it. */preformatted?: boolean;@@ -376,21 +376,20 @@ function renderWarning(block: Block, width: number, theme: Theme): string[] {}function paintCommands(line: string, theme: Theme): string {- return line.replace(/\/[a-z-]+/g, (token) =>+ return line.replace(/\/[a-z:-]+/g, (token) =>isPromptControlCommand(token) ? theme.colors.blue(token) : token,);}/**- * A typed slash command, echoed in the user-message grammar (the gutter bar —- * the user typed it) with the command itself blue to mark the dispatch.- * Deliberately NOT the prompt glyph: `❯` marks the live input line, and- * consumers (the e2e harness, anything reading scrollback) rendezvous on it- * to know a prompt is ready — an echo reusing it would match forever.+ * A slash command invocation under the user gutter. Automatic commands use+ * the same row so their result can follow it. The `❯` glyph remains exclusive+ * to live input because the TUI tests use it to detect a ready prompt.*/function renderCommand(block: Block, theme: Theme): string[] {const c = theme.colors;- return [`${c.cyan(theme.glyph.user)} ${c.blue(block.body ?? "")}`];+ const status = block.status === "error" ? `${c.red(theme.glyph.error)} ` : "";+ return [`${c.cyan(theme.glyph.user)} ${status}${c.blue(block.body ?? "")}`];}/**diff --git a/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts b/packages/eve/src/cli/dev/tui/prompt-command-handler.test.tsindex 2b1163213..81e8536f0 100644--- a/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts+++ b/packages/eve/src/cli/dev/tui/prompt-command-handler.test.ts@@ -2,10 +2,21 @@ import pc from "picocolors";import { describe, expect, it, vi } from "vitest";import { createPromptCommandHandler } from "./prompt-command-handler.js";+import type { RemoteAuthCompletion, RemoteConnectionController } from "./remote-connection.js";import type { AgentTUIRenderer, PromptCommandHandlerContext } from "./runner.js";import type { SetupFlowRenderer } from "./setup-flow.js";const APP_ROOT = "/tmp/weather-agent";+const LOCAL_TARGET = {+ kind: "local",+ serverUrl: "http://localhost:3000",+ workspaceRoot: APP_ROOT,+} as const;+const REMOTE_TARGET = {+ kind: "remote",+ serverUrl: "https://example.com/",+ workspaceRoot: APP_ROOT,+} as const;function context(renderer: Partial<AgentTUIRenderer> = {}): PromptCommandHandlerContext {return {@@ -44,7 +55,7 @@ describe("createPromptCommandHandler", () => {({ kind: "changed", to: slug }) as const,);const handler = createPromptCommandHandler({- appRoot: APP_ROOT,+ target: LOCAL_TARGET,applyModel,modelChangeRefusal: async () => null,});@@ -69,7 +80,7 @@ describe("createPromptCommandHandler", () => {({ kind: "changed", to: slug }) as const,);const handler = createPromptCommandHandler({- appRoot: APP_ROOT,+ target: LOCAL_TARGET,applyModel,modelChangeRefusal: async () => "Model is pinned to the external provider `anthropic`.",});@@ -85,7 +96,10 @@ describe("createPromptCommandHandler", () => {it("sends a bare /model down the setup-flow path, not a bespoke picker", async () => {const applyModel = vi.fn(async () => ({ kind: "rejected", message: "unused" }) as const);const readInputQuestion = vi.fn(async () => ({ optionId: "openai/gpt-5" }));- const handler = createPromptCommandHandler({ appRoot: APP_ROOT, applyModel });+ const handler = createPromptCommandHandler({+ target: LOCAL_TARGET,+ applyModel,+ });// No setupFlow on the renderer: the flow path reports itself instead of// falling back to the old readInputQuestion picker.@@ -100,7 +114,9 @@ describe("createPromptCommandHandler", () => {});it("reports that model changes need the local dev server", async () => {- const handler = createPromptCommandHandler({});+ const handler = createPromptCommandHandler({+ target: REMOTE_TARGET,+ });await expect(handler.handle({ type: "extension", name: "model", argument: "" }, context()),@@ -124,7 +140,7 @@ describe("createPromptCommandHandler", () => {try {const setupFlow = setupFlowRenderer();- const handler = createPromptCommandHandler({ appRoot: APP_ROOT });+ const handler = createPromptCommandHandler({ target: LOCAL_TARGET });await expect(handler.handle(@@ -146,6 +162,92 @@ describe("createPromptCommandHandler", () => {}});+ it("reports a login that completed before remote authentication was cancelled", async () => {+ const setupFlow = setupFlowRenderer();+ const remoteConnection: RemoteConnectionController = {+ current: () => ({+ target: REMOTE_TARGET,+ connection: {+ state: "auth-required",+ challenge: { kind: "eve-oidc" },+ },+ }),+ check: async () => ({+ state: "auth-required",+ challenge: { kind: "eve-oidc" },+ }),+ authenticate: async () => ({+ kind: "cancelled",+ completedMutations: [{ kind: "vercel-login" }],+ }),+ reportFailure: () => ({ state: "checking" }),+ dispose() {},+ };+ const handler = createPromptCommandHandler({+ target: REMOTE_TARGET,+ });++ await expect(+ handler.handle(+ { type: "extension", name: "vc:auth", argument: "" },+ {+ ...context({ setupFlow }),+ remoteConnection,+ },+ ),+ ).resolves.toEqual({+ message: "/vc:auth cancelled after logging in to Vercel.",+ });+ expect(setupFlow.begin).toHaveBeenCalledWith("Authenticate via Vercel OIDC", "pulse");+ expect(setupFlow.end).toHaveBeenCalledWith({ preserveDiagnostics: true });+ });++ it("reports mutations that completed before /vc:auth was interrupted", async () => {+ const setupFlow = {+ ...setupFlowRenderer(),+ waitForInterrupt: () => ({ promise: Promise.resolve(), dispose: vi.fn() }),+ } satisfies SetupFlowRenderer;+ const remoteConnection: RemoteConnectionController = {+ current: () => ({+ target: REMOTE_TARGET,+ connection: { state: "auth-required", challenge: { kind: "eve-oidc" } },+ }),+ check: async () => ({+ state: "auth-required",+ challenge: { kind: "eve-oidc" },+ }),+ authenticate: async (_attempt, signal) =>+ await new Promise<RemoteAuthCompletion>((resolve) => {+ signal?.addEventListener(+ "abort",+ () =>+ resolve({+ kind: "cancelled" as const,+ completedMutations: [+ { kind: "trusted-sources-updated", targetProjectName: "remote-agent" },+ ],+ }),+ { once: true },+ );+ }),+ reportFailure: () => ({ state: "checking" }),+ dispose() {},+ };+ const handler = createPromptCommandHandler({+ target: REMOTE_TARGET,+ });++ await expect(+ handler.handle(+ { type: "extension", name: "vc:auth", argument: "" },+ { ...context({ setupFlow }), remoteConnection },+ ),+ ).resolves.toEqual({+ message:+ "/vc:auth interrupted. Completed before interruption: updated Trusted Sources for remote-agent.",+ });+ });+it("folds setup-module load failures at the command adapter boundary", async () => {vi.doMock("./setup-commands.js", () => {throw new Error("Cannot find package 'oxc-parser'");@@ -153,7 +255,9 @@ describe("createPromptCommandHandler", () => {try {const setupFlow = setupFlowRenderer();- const handler = createPromptCommandHandler({ appRoot: APP_ROOT });+ const handler = createPromptCommandHandler({+ target: LOCAL_TARGET,+ });await expect(handler.handle({ type: "extension", name: "model", argument: "" }, context({ setupFlow })),diff --git a/packages/eve/src/cli/dev/tui/prompt-command-handler.ts b/packages/eve/src/cli/dev/tui/prompt-command-handler.tsindex eaf0944d0..becc7977f 100644--- a/packages/eve/src/cli/dev/tui/prompt-command-handler.ts+++ b/packages/eve/src/cli/dev/tui/prompt-command-handler.ts@@ -6,19 +6,23 @@ import type {PromptCommandHandlerContext,PromptCommandOutcome,} from "./runner.js";-import type { PromptCommand } from "./prompt-commands.js";+import { isPromptCommandAvailableFor, type PromptCommand } from "./prompt-commands.js";+import type { RemoteAuthFlow } from "./remote-auth.js";import type { TuiSetupCommandInput, TuiSetupFlows } from "./setup-commands.js";+import type { DevelopmentTuiTarget } from "./target.js";type ExtensionCommand = Extract<PromptCommand, { type: "extension" }>;export interface PromptCommandHandlerOptions {- readonly appRoot?: string;+ readonly target: DevelopmentTuiTarget;/** Test seam; defaults to the model flow's shared source-change apply. */readonly applyModel?: (input: { appRoot: string; slug: string }) => Promise<ApplyModelOutcome>;/** Test seam; defaults to the model flow's external-provider refusal check. */readonly modelChangeRefusal?: (appRoot: string) => Promise<string | null>;/** Test seam; forwarded to runTuiSetupCommand's injectable flows. */readonly flows?: Partial<TuiSetupFlows>;+ /** Test seam for remote authentication. */+ readonly remoteAuthFlow?: RemoteAuthFlow;}export function createPromptCommandHandler(@@ -29,8 +33,12 @@ export function createPromptCommandHandler(command: ExtensionCommand,context: PromptCommandHandlerContext,): Promise<PromptCommandOutcome> {- const appRoot = options.appRoot;- if (appRoot === undefined) {+ const { target } = options;+ // Local-only commands invoked on a remote target are rejected here; the+ // allowlist is derived from each command's `targets` so dispatch can't+ // drift from discovery. (vc:auth's remote-only direction is enforced in+ // its own branch below.)+ if (target.kind === "remote" && !isPromptCommandAvailableFor(command.name, "remote")) {return {message: `/${command.name} needs eve dev running the local server (it is not available with --url).`,};@@ -39,6 +47,13 @@ export function createPromptCommandHandler(// `/model <slug>` applies directly; only the bare command opens the// configure menu flow below.if (command.name === "model" && command.argument.length > 0) {+ if (target.kind !== "local") {+ return {+ message:+ "/model needs eve dev running the local server (it is not available with --url).",+ };+ }+ const appRoot = target.workspaceRoot;// Package-loading failures are command outcomes at this CLI boundary.try {const {@@ -69,6 +84,28 @@ export function createPromptCommandHandler(return { message: `/${command.name} is not supported by this renderer.` };}+ if (command.name === "vc:auth") {+ if (target.kind !== "remote" || context.remoteConnection === undefined) {+ return { message: "/vc:auth is not available in this session." };+ }+ let runRemoteAuthCommand: (typeof import("./remote-auth-command.js"))["runRemoteAuthCommand"];+ try {+ ({ runRemoteAuthCommand } = await import("./remote-auth-command.js"));+ } catch (error) {+ return { message: `/vc:auth failed: ${toErrorMessage(error)}` };+ }+ const message = await runRemoteAuthCommand({+ connection: context.remoteConnection,+ flow: options.remoteAuthFlow,+ renderer: flow,+ });+ return { message };+ }++ // Availability is the `targets` allowlist checked above; the remaining+ // setup commands run against `workspaceRoot`, which both a local and a+ // remote target carry (`/vc:install` and `/vc:login` only need a working+ // directory, not the local dev server).let setupCommands: typeof import("./setup-commands.js");try {setupCommands = await import("./setup-commands.js");@@ -82,7 +119,7 @@ export function createPromptCommandHandler(try {const commandInput: TuiSetupCommandInput = {command: command.name,- appRoot,+ appRoot: target.workspaceRoot,renderer: flow,};if (context.initialModelStep !== undefined) {diff --git a/packages/eve/src/cli/dev/tui/prompt-commands.test.ts b/packages/eve/src/cli/dev/tui/prompt-commands.test.tsindex fb2db0232..72eb53b7a 100644--- a/packages/eve/src/cli/dev/tui/prompt-commands.test.ts+++ b/packages/eve/src/cli/dev/tui/prompt-commands.test.ts@@ -4,6 +4,7 @@ import {formatPromptCommandHelp,isPromptControlCommand,parsePromptCommand,+ promptCommandsFor,PROMPT_COMMANDS,} from "./prompt-commands.js";@@ -34,14 +35,19 @@ describe("parsePromptCommand", () => {});it("parses the setup commands", () => {- expect(parsePromptCommand("/vc")).toEqual({+ expect(parsePromptCommand("/vc:install")).toEqual({type: "extension",- name: "vc",+ name: "vc:install",argument: "",});- expect(parsePromptCommand("/login")).toEqual({+ expect(parsePromptCommand("/vc:login")).toEqual({type: "extension",- name: "login",+ name: "vc:login",+ argument: "",+ });+ expect(parsePromptCommand("/vc:auth")).toEqual({+ type: "extension",+ name: "vc:auth",argument: "",});expect(parsePromptCommand("/channels")).toEqual({@@ -77,6 +83,8 @@ describe("parsePromptCommand", () => {it("rejects near-misses and ordinary prompts", () => {expect(parsePromptCommand("/models")).toBeNull();expect(parsePromptCommand("/vercel")).toBeNull();+ expect(parsePromptCommand("/vc")).toBeNull();+ expect(parsePromptCommand("/login")).toBeNull();expect(parsePromptCommand("/channels extra")).toBeNull();expect(parsePromptCommand("tell me about /channels")).toBeNull();expect(parsePromptCommand("/")).toBeNull();@@ -85,6 +93,44 @@ describe("parsePromptCommand", () => {});});+describe("promptCommandsFor", () => {+ it("exposes project commands only for local sessions", () => {+ const names = promptCommandsFor("local").map((command) => command.name);+ expect(names).toContain("model");+ expect(names).toContain("channels");+ expect(names).toContain("deploy");+ expect(names).toContain("vc:install");+ expect(names).toContain("vc:login");+ expect(names).not.toContain("vc:auth");+ });++ it("exposes remote OIDC auth and the Vercel CLI commands for remote sessions", () => {+ const names = promptCommandsFor("remote").map((command) => command.name);+ expect(names).toContain("vc:install");+ expect(names).toContain("vc:login");+ expect(names).toContain("vc:auth");+ expect(names).not.toContain("model");+ expect(names).not.toContain("channels");+ expect(names).not.toContain("deploy");+ });++ it("filters discovery without weakening global recognition", () => {+ const remote = promptCommandsFor("remote");+ expect(parsePromptCommand("/vc:auth")).toEqual({+ type: "extension",+ name: "vc:auth",+ argument: "",+ });+ expect(parsePromptCommand("/model")).toEqual({+ type: "extension",+ name: "model",+ argument: "",+ });+ expect(formatPromptCommandHelp(remote)).toContain("/vc:auth");+ expect(formatPromptCommandHelp(remote)).not.toContain("/model");+ });+});+describe("isPromptControlCommand", () => {it("is true exactly for recognized commands", () => {expect(isPromptControlCommand("/new")).toBe(true);diff --git a/packages/eve/src/cli/dev/tui/prompt-commands.ts b/packages/eve/src/cli/dev/tui/prompt-commands.tsindex 905609236..987031c5d 100644--- a/packages/eve/src/cli/dev/tui/prompt-commands.ts+++ b/packages/eve/src/cli/dev/tui/prompt-commands.ts@@ -1,4 +1,13 @@-export type PromptCommandExtensionName = "model" | "channels" | "deploy" | "login" | "vc";+export type PromptCommandExtensionName =+ | "model"+ | "channels"+ | "deploy"+ | "vc:install"+ | "vc:login";++type PromptCommandName = PromptCommandExtensionName | "vc:auth";++type PromptCommandTarget = "local" | "remote";/** The slash commands the prompt accepts. */export type PromptCommand =@@ -6,7 +15,7 @@ export type PromptCommand =| { type: "exit" }| { type: "help" }| { type: "loglevel"; argument: string }- | { type: "extension"; name: PromptCommandExtensionName; argument: string };+ | { type: "extension"; name: PromptCommandName; argument: string };/*** Metadata for one slash command. The registry describes commands — their@@ -27,12 +36,16 @@ export interface PromptCommandSpec {readonly build: (argument: string) => PromptCommand;}+interface PromptCommandDefinition extends PromptCommandSpec {+ readonly targets: readonly PromptCommandTarget[];+}+/*** Every slash command the prompt accepts, in typeahead display order. One* module owns the command list so the runner's dispatch, the renderer's* transcript-echo suppression, and command discovery cannot drift apart.*/-export const PROMPT_COMMANDS: readonly PromptCommandSpec[] = [+const PROMPT_COMMAND_DEFINITIONS = [// `help` leads so that the typeahead's default highlight — what a bare `/`// plus Enter submits — is the safest command, not session-resetting `/new`.{@@ -41,6 +54,7 @@ export const PROMPT_COMMANDS: readonly PromptCommandSpec[] = [description: "Show available commands",takesArgument: false,build: () => ({ type: "help" }),+ targets: ["local", "remote"],},{name: "new",@@ -48,20 +62,31 @@ export const PROMPT_COMMANDS: readonly PromptCommandSpec[] = [description: "Start a fresh session",takesArgument: false,build: () => ({ type: "new" }),+ targets: ["local", "remote"],},{- name: "vc",+ name: "vc:install",aliases: [],description: "Install the Vercel CLI",takesArgument: false,- build: () => ({ type: "extension", name: "vc", argument: "" }),+ build: () => ({ type: "extension", name: "vc:install", argument: "" }),+ targets: ["local", "remote"],},{- name: "login",+ name: "vc:login",aliases: [],description: "Log in to Vercel",takesArgument: false,- build: () => ({ type: "extension", name: "login", argument: "" }),+ build: () => ({ type: "extension", name: "vc:login", argument: "" }),+ targets: ["local", "remote"],+ },+ {+ name: "vc:auth",+ aliases: [],+ description: "Authenticate this remote via Vercel OIDC",+ takesArgument: false,+ build: () => ({ type: "extension", name: "vc:auth", argument: "" }),+ targets: ["remote"],},{name: "model",@@ -70,6 +95,7 @@ export const PROMPT_COMMANDS: readonly PromptCommandSpec[] = [argumentHint: "[provider/model]",takesArgument: true,build: (argument) => ({ type: "extension", name: "model", argument }),+ targets: ["local"],},{name: "loglevel",@@ -78,6 +104,7 @@ export const PROMPT_COMMANDS: readonly PromptCommandSpec[] = [argumentHint: "[all|stderr|sandbox|none]",takesArgument: true,build: (argument) => ({ type: "loglevel", argument }),+ targets: ["local", "remote"],},{name: "channels",@@ -85,6 +112,7 @@ export const PROMPT_COMMANDS: readonly PromptCommandSpec[] = [description: "Add chat channels to the agent",takesArgument: false,build: () => ({ type: "extension", name: "channels", argument: "" }),+ targets: ["local"],},{name: "deploy",@@ -92,6 +120,7 @@ export const PROMPT_COMMANDS: readonly PromptCommandSpec[] = [description: "Deploy the agent to Vercel",takesArgument: false,build: () => ({ type: "extension", name: "deploy", argument: "" }),+ targets: ["local"],},{name: "exit",@@ -99,8 +128,27 @@ export const PROMPT_COMMANDS: readonly PromptCommandSpec[] = [description: "Quit the TUI",takesArgument: false,build: () => ({ type: "exit" }),+ targets: ["local", "remote"],},-];+] satisfies readonly PromptCommandDefinition[];++export const PROMPT_COMMANDS: readonly PromptCommandSpec[] = PROMPT_COMMAND_DEFINITIONS;++export function promptCommandsFor(target: PromptCommandTarget): readonly PromptCommandSpec[] {+ return PROMPT_COMMAND_DEFINITIONS.filter((definition) =>+ definition.targets.some((supportedTarget) => supportedTarget === target),+ );+}++/** Whether a command runs against this target — the one authority dispatch shares with discovery. */+export function isPromptCommandAvailableFor(+ name: PromptCommandName,+ target: PromptCommandTarget,+): boolean {+ const definition = PROMPT_COMMAND_DEFINITIONS.find((entry) => entry.name === name);+ const targets: readonly PromptCommandTarget[] | undefined = definition?.targets;+ return targets?.includes(target) ?? false;+}/*** Recognizes the slash commands the prompt accepts. `/new` clears the@@ -132,8 +180,10 @@ export function isPromptControlCommand(prompt: string): boolean {* The table `/help` prints: one line per command — slash name, argument* hint, and aliases padded into a column, description after.*/-export function formatPromptCommandHelp(): string {- const entries = PROMPT_COMMANDS.map((spec) => {+export function formatPromptCommandHelp(+ commands: readonly PromptCommandSpec[] = PROMPT_COMMANDS,+): string {+ const entries = commands.map((spec) => {const hint = spec.argumentHint === undefined ? "" : ` ${spec.argumentHint}`;const aliases = spec.aliases.map((alias) => ` (/${alias})`).join("");return { invocation: `/${spec.name}${hint}${aliases}`, description: spec.description };diff --git a/packages/eve/src/cli/dev/tui/remote-auth-command.ts b/packages/eve/src/cli/dev/tui/remote-auth-command.tsnew file mode 100644index 000000000..50a117bd5--- /dev/null+++ b/packages/eve/src/cli/dev/tui/remote-auth-command.ts@@ -0,0 +1,129 @@+import { WizardCancelledError } from "#setup/step.js";++import { createTuiPrompter } from "./tui-prompter.js";+import { runRemoteAuthFlow, type RemoteAuthFlow } from "./remote-auth.js";+import { describeRemoteAuthCompletedMutations } from "./remote-auth-result.js";+import type { RemoteConnectionController, RemoteConnectionState } from "./remote-connection.js";+import type { SetupFlowPrompterRenderer, SetupFlowRenderer } from "./setup-flow.js";+import { remoteHost } from "./target.js";++interface RemoteAuthCommandInput {+ readonly connection: RemoteConnectionController;+ readonly flow?: RemoteAuthFlow;+ readonly renderer: SetupFlowRenderer;+}++function shouldConfigureTrustedSources(connection: RemoteConnectionState): boolean {+ switch (connection.state) {+ case "auth-required":+ case "auth-failed":+ return connection.challenge.kind === "vercel-deployment-protection";+ case "unavailable":+ return connection.failure.code === "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH";+ case "checking":+ case "authenticating":+ case "ready":+ return false;+ }+}++function unavailableAfterAuthentication(host: string, message: string): string {+ const [reason = message, ...details] = message.split(/\n\s*\n/u);+ const sentence = /[.!?]$/u.test(reason.trim()) ? reason.trim() : `${reason.trim()}.`;+ return [+ `Authentication was refreshed, but ${host} is unavailable: ${sentence}`,+ ...details.map((detail) => detail.trim()).filter((detail) => detail.length > 0),+ ].join("\n\n");+}++function mutedRenderer(+ renderer: SetupFlowPrompterRenderer,+ isMuted: () => boolean,+): SetupFlowPrompterRenderer {+ return {+ readSelect: (options) =>+ isMuted() ? Promise.resolve(undefined) : renderer.readSelect(options),+ readEditableSelect: (options) =>+ isMuted() ? Promise.resolve(undefined) : renderer.readEditableSelect(options),+ readText: (options) => (isMuted() ? Promise.resolve(undefined) : renderer.readText(options)),+ readAcknowledge: (options) =>+ isMuted() ? Promise.resolve() : renderer.readAcknowledge(options),+ readChoice: (options) =>+ isMuted()+ ? { choice: Promise.resolve(undefined), close: () => {} }+ : renderer.readChoice(options),+ setStatus: (text) => {+ if (!isMuted()) renderer.setStatus(text);+ },+ renderLine: (text, tone) => {+ if (!isMuted() || tone === "warning" || tone === "error") {+ renderer.renderLine(text, tone);+ }+ },+ renderOutput: (text) => {+ if (!isMuted()) renderer.renderOutput(text);+ },+ };+}++/** Runs `/vc:auth` through one TUI panel, connection operation, and auth flow. */+export async function runRemoteAuthCommand(input: RemoteAuthCommandInput): Promise<string> {+ // The pulsing square, matching /vc:install and /vc:login (and model/channels).+ input.renderer.begin("Authenticate via Vercel OIDC", "pulse");+ let preserveFlowDiagnostics = true;+ let interrupted = false;+ const controller = new AbortController();+ const interrupt = input.renderer.waitForInterrupt();+ const target = input.connection.current().target;+ try {+ const runFlow = input.flow ?? runRemoteAuthFlow;+ const configureTrustedSources = shouldConfigureTrustedSources(+ input.connection.current().connection,+ );+ const prompter = createTuiPrompter(mutedRenderer(input.renderer, () => interrupted));+ const execution = input.connection.authenticate(async (signal) => {+ const result = await runFlow({+ workspaceRoot: target.workspaceRoot,+ serverUrl: target.serverUrl,+ configureTrustedSources,+ prompter,+ signal,+ });+ preserveFlowDiagnostics = result.kind === "failed";+ return result;+ }, controller.signal);+ const first = await Promise.race([+ execution.then((outcome) => ({ kind: "completed", outcome }) as const),+ interrupt.promise.then(() => ({ kind: "interrupted" }) as const),+ ]);+ if (first.kind === "interrupted") {+ interrupted = true;+ preserveFlowDiagnostics = true;+ controller.abort(new WizardCancelledError());+ }+ const outcome = first.kind === "completed" ? first.outcome : await execution;+ switch (outcome.kind) {+ case "authenticated":+ return `Authenticated ${remoteHost(target)} via Vercel OIDC.`;+ case "cancelled": {+ if (interrupted) {+ const completed = describeRemoteAuthCompletedMutations(outcome.completedMutations);+ return completed.length === 0+ ? "/vc:auth interrupted."+ : `/vc:auth interrupted. Completed before interruption: ${completed.join(", ")}.`;+ }+ return outcome.completedMutations.some((mutation) => mutation.kind === "vercel-login")+ ? "/vc:auth cancelled after logging in to Vercel."+ : "/vc:auth cancelled.";+ }+ case "failed":+ return outcome.message;+ case "unavailable":+ return unavailableAfterAuthentication(remoteHost(target), outcome.failure.message);+ }+ } finally {+ interrupt.dispose();+ input.renderer.setStatus(undefined);+ input.renderer.end({ preserveDiagnostics: preserveFlowDiagnostics });+ }+}diff --git a/packages/eve/src/cli/dev/tui/remote-auth-result.ts b/packages/eve/src/cli/dev/tui/remote-auth-result.tsindex ea98b8b54..d03764a79 100644--- a/packages/eve/src/cli/dev/tui/remote-auth-result.ts+++ b/packages/eve/src/cli/dev/tui/remote-auth-result.ts@@ -1,6 +1,11 @@import type { VerifiedVercelTarget } from "#setup/vercel-deployment.js";-export type RemoteAuthCompletedMutation = { readonly kind: "vercel-login" };+export type RemoteAuthCompletedMutation =+ | { readonly kind: "vercel-login" }+ | {+ readonly kind: "trusted-sources-updated";+ readonly targetProjectName: string;+ };export type RemoteAuthPreparation =| {@@ -27,6 +32,8 @@ export function describeRemoteAuthCompletedMutations(switch (mutation.kind) {case "vercel-login":return "logged in to Vercel";+ case "trusted-sources-updated":+ return `updated Trusted Sources for ${mutation.targetProjectName}`;}});}@@ -41,3 +48,18 @@ export function appendRemoteAuthMutationSummary(? message: `${message} Completed before the failure: ${completed.join(", ")}.`;}++/** Formats a Vercel Deployment Protection challenge for the remote TUI. */+export function formatRemoteAuthChallengeMessage(serverUrl: string): string {+ return [+ `Vercel Deployment Protection blocked the request to ${serverUrl}.`,+ "",+ "To access the deployment from `eve dev`, do one of:",+ " • Run `/vc:auth` to select a Vercel project and refresh its OIDC token.",+ " • Set VERCEL_AUTOMATION_BYPASS_SECRET to a Protection Bypass for",+ " Automation token (Project Settings → Deployment Protection).",+ " • Disable Deployment Protection on the target deployment.",+ "",+ "Docs: https://vercel.com/docs/deployment-protection",+ ].join("\n");+}diff --git a/packages/eve/src/cli/dev/tui/remote-auth.test.ts b/packages/eve/src/cli/dev/tui/remote-auth.test.tsnew file mode 100644index 000000000..ef1da1d10--- /dev/null+++ b/packages/eve/src/cli/dev/tui/remote-auth.test.ts@@ -0,0 +1,306 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { createFakePrompter } from "#internal/testing/fake-prompter.js";+import { resolveTestVercelTarget } from "#internal/testing/verified-vercel-target.js";++import { runRemoteAuthFlow, type RemoteAuthFlowDeps } from "./remote-auth.js";+import { formatRemoteAuthChallengeMessage } from "./remote-auth-result.js";++const WORKSPACE_ROOT = "/app/weather-agent";+const HOST = "vpoke.playground-vercel.tools";+const SERVER_URL = `https://${HOST}/`;+const OWNER_ID = "team_acme";+const PROJECT_ID = "prj_remote";++const TARGET = await resolveTestVercelTarget({+ host: HOST,+ projectId: PROJECT_ID,+ ownerId: OWNER_ID,+ projectName: "remote-agent",+});+const TRUSTED_SOURCE_GRANT = {+ ownerId: OWNER_ID,+ projectId: PROJECT_ID,+ projectName: "remote-agent",+ targetEnvironment: "production",+} as const;++function oidcToken(ownerId: string, projectId: string, version = "1"): string {+ const encode = (value: unknown): string =>+ Buffer.from(JSON.stringify(value)).toString("base64url");+ return `${encode({ alg: "none" })}.${encode({ owner_id: ownerId, project_id: projectId, version })}.signature`;+}++type LoginResult = Awaited<ReturnType<RemoteAuthFlowDeps["runLoginFlow"]>>;+type DeploymentResult = Awaited<ReturnType<RemoteAuthFlowDeps["resolveVercelDeployment"]>>;+type PreparationResult = Awaited<+ ReturnType<RemoteAuthFlowDeps["prepareVercelTrustedSourceAccess"]>+>;+type ApplicationResult = Awaited<ReturnType<RemoteAuthFlowDeps["applyVercelTrustedSourceAccess"]>>;++interface HarnessOptions {+ readonly logins?: readonly LoginResult[];+ readonly deployments?: readonly DeploymentResult[];+ readonly preparation?: PreparationResult;+ readonly application?: ApplicationResult;+ readonly token?:+ | { readonly kind: "present"; readonly value: string }+ | { readonly kind: "missing" };+ readonly configureTrustedSources?: boolean;+}++function createHarness(options: HarnessOptions = {}) {+ const operations: string[] = [];+ const logins = options.logins ?? [{ kind: "already" }];+ const deployments = options.deployments ?? [{ kind: "resolved", target: TARGET }];+ let loginCall = 0;+ let deploymentCall = 0;+ let token =+ options.token?.kind === "missing"+ ? undefined+ : (options.token?.value ?? oidcToken(OWNER_ID, PROJECT_ID));++ // No `select` is expected: the flow resolves from the URL with no picker.+ const { prompter } = createFakePrompter({+ single: () => {+ throw new Error("unexpected select prompt");+ },+ });++ const deps: RemoteAuthFlowDeps = {+ runLoginFlow: vi.fn<RemoteAuthFlowDeps["runLoginFlow"]>(async () => {+ operations.push("login");+ return logins[Math.min(loginCall++, logins.length - 1)]!;+ }),+ resolveVercelDeployment: vi.fn<RemoteAuthFlowDeps["resolveVercelDeployment"]>(async () => {+ operations.push("deployment");+ return deployments[Math.min(deploymentCall++, deployments.length - 1)]!;+ }),+ resolveOidcToken: vi.fn<RemoteAuthFlowDeps["resolveOidcToken"]>(async () => {+ operations.push("token");+ return token === undefined+ ? { kind: "resolution-failed", message: "Vercel did not issue an OIDC token." }+ : { kind: "resolved", token };+ }),+ prepareVercelTrustedSourceAccess: vi.fn<RemoteAuthFlowDeps["prepareVercelTrustedSourceAccess"]>(+ async () => {+ operations.push("prepare-ts");+ return options.preparation ?? { kind: "unchanged" };+ },+ ),+ applyVercelTrustedSourceAccess: vi.fn<RemoteAuthFlowDeps["applyVercelTrustedSourceAccess"]>(+ async () => {+ operations.push("apply-ts");+ return options.application ?? { kind: "unchanged" };+ },+ ),+ };++ return {+ deps,+ operations,+ prompter,+ setToken(value: string | undefined) {+ token = value;+ },+ run: (signal?: AbortSignal) =>+ runRemoteAuthFlow({+ workspaceRoot: WORKSPACE_ROOT,+ serverUrl: SERVER_URL,+ configureTrustedSources: options.configureTrustedSources,+ prompter,+ signal,+ deps,+ }),+ };+}++afterEach(() => vi.restoreAllMocks());++describe("runRemoteAuthFlow", () => {+ it("resolves the deployment from the URL and prepares the session token", async () => {+ const harness = createHarness();++ await expect(harness.run()).resolves.toMatchObject({ kind: "prepared" });++ expect(harness.deps.resolveVercelDeployment).toHaveBeenCalledWith({+ workspaceRoot: WORKSPACE_ROOT,+ host: HOST,+ signal: undefined,+ });+ expect(harness.deps.resolveOidcToken).toHaveBeenCalledWith({+ ownerId: OWNER_ID,+ projectId: PROJECT_ID,+ forceRefresh: true,+ });+ expect(harness.operations).toEqual(["login", "deployment", "token"]);+ });++ it("re-authenticates and resolves again when access is initially forbidden", async () => {+ const harness = createHarness({+ logins: [{ kind: "already" }, { kind: "logged-in" }],+ deployments: [{ kind: "forbidden" }, { kind: "resolved", target: TARGET }],+ });++ await expect(harness.run()).resolves.toMatchObject({+ kind: "prepared",+ completedMutations: [{ kind: "vercel-login" }],+ });+ expect(harness.operations).toEqual(["login", "deployment", "login", "deployment", "token"]);+ expect(harness.deps.resolveVercelDeployment).toHaveBeenCalledTimes(2);+ expect(harness.deps.runLoginFlow).toHaveBeenNthCalledWith(2, {+ appRoot: WORKSPACE_ROOT,+ force: true,+ prompter: harness.prompter,+ signal: undefined,+ });+ });++ it("gets Trusted Sources consent, applies it, then requests the session token", async () => {+ const harness = createHarness({+ configureTrustedSources: true,+ preparation: { kind: "approved", grant: TRUSTED_SOURCE_GRANT },+ application: { kind: "updated", targetProjectName: "remote-agent" },+ });++ await expect(harness.run()).resolves.toMatchObject({ kind: "prepared" });++ expect(harness.operations).toEqual(["login", "deployment", "prepare-ts", "apply-ts", "token"]);+ expect(harness.deps.prepareVercelTrustedSourceAccess).toHaveBeenCalledWith(+ expect.objectContaining({ target: TARGET }),+ );+ });++ it("returns a live token resolver that refreshes the project-scoped token", async () => {+ const harness = createHarness();++ const result = await harness.run();+ expect(result).toMatchObject({ kind: "prepared" });+ if (result.kind !== "prepared") throw new Error("Expected a prepared result");++ const rotated = oidcToken(OWNER_ID, PROJECT_ID, "2");+ harness.setToken(rotated);+ await expect(result.resolveToken()).resolves.toBe(rotated);+ expect(harness.deps.resolveOidcToken).toHaveBeenNthCalledWith(1, {+ ownerId: OWNER_ID,+ projectId: PROJECT_ID,+ forceRefresh: true,+ });+ expect(harness.deps.resolveOidcToken).toHaveBeenNthCalledWith(2, TARGET.deployment);+ });++ it("cancels when login is cancelled", async () => {+ const harness = createHarness({ logins: [{ kind: "cancelled" }] });++ await expect(harness.run()).resolves.toEqual({ kind: "cancelled", completedMutations: [] });+ expect(harness.operations).not.toContain("deployment");+ });++ it("cancels Trusted Sources consent before changing remote access", async () => {+ const harness = createHarness({+ configureTrustedSources: true,+ preparation: { kind: "cancelled" },+ });++ await expect(harness.run()).resolves.toEqual({ kind: "cancelled", completedMutations: [] });+ expect(harness.operations).not.toContain("apply-ts");+ expect(harness.operations).not.toContain("token");+ });++ it("cancels an abort that arrives before the first mutation", async () => {+ const abort = new AbortController();+ const harness = createHarness();+ vi.mocked(harness.deps.resolveVercelDeployment).mockImplementationOnce(async () => {+ abort.abort();+ return { kind: "resolved", target: TARGET };+ });++ await expect(harness.run(abort.signal)).resolves.toEqual({+ kind: "cancelled",+ completedMutations: [],+ });+ expect(harness.operations).not.toContain("token");+ });++ it.each([+ {+ name: "Vercel CLI",+ options: { logins: [{ kind: "cli-missing" }] },+ message: "not installed",+ },+ {+ name: "deployment not found",+ options: { deployments: [{ kind: "not-found" }] },+ message: "did not resolve",+ },+ {+ name: "access still forbidden after re-auth",+ options: {+ logins: [{ kind: "already" }, { kind: "already" }],+ deployments: [{ kind: "forbidden" }, { kind: "forbidden" }],+ },+ message: "Re-authenticate",+ },+ {+ name: "deployment verification",+ options: {+ deployments: [+ {+ kind: "failed",+ failure: {+ cause: "vercel",+ failure: { code: 1, stdout: "", stderr: "", message: "boom" },+ },+ },+ ],+ },+ message: "Could not verify",+ },+ {+ name: "OIDC token",+ options: { token: { kind: "missing" } },+ message: "did not issue an OIDC token",+ },+ {+ name: "Trusted Sources",+ options: {+ configureTrustedSources: true,+ preparation: { kind: "failed", message: "Vercel rejected the policy update." },+ },+ message: "Vercel rejected the policy update",+ },+ {+ name: "Trusted Sources apply",+ options: {+ configureTrustedSources: true,+ preparation: { kind: "approved", grant: TRUSTED_SOURCE_GRANT },+ application: { kind: "failed", message: "Vercel rejected the policy update." },+ },+ message: "Vercel rejected the policy update",+ },+ ] satisfies readonly { name: string; options: HarnessOptions; message: string }[])(+ "reports the $name failure",+ async ({ options, message }) => {+ const harness = createHarness(options);++ await expect(harness.run()).resolves.toMatchObject({+ kind: "failed",+ message: expect.stringContaining(message),+ });+ },+ );+});++describe("formatRemoteAuthChallengeMessage", () => {+ it("renders TUI recovery actions without the raw challenge HTML", () => {+ const message = formatRemoteAuthChallengeMessage("https://example.vercel.app");++ expect(message).toContain("https://example.vercel.app");+ expect(message).toContain("/vc:auth");+ expect(message).toContain("VERCEL_AUTOMATION_BYPASS_SECRET");+ expect(message).toContain("Disable Deployment Protection");+ expect(message).toContain("https://vercel.com/docs/deployment-protection");+ expect(message).not.toContain("<");+ expect(message).not.toContain("doctype");+ });+});diff --git a/packages/eve/src/cli/dev/tui/remote-auth.ts b/packages/eve/src/cli/dev/tui/remote-auth.tsnew file mode 100644index 000000000..de3ff1e61--- /dev/null+++ b/packages/eve/src/cli/dev/tui/remote-auth.ts@@ -0,0 +1,214 @@+import { resolveDevelopmentOidcToken } from "#services/dev-client/request-headers.js";+import { formatDevelopmentOidcTokenFailure } from "#services/dev-client/vercel-auth-error.js";+import { runLoginFlow, type LoginFlowResult } from "#setup/flows/login.js";+import type { Prompter } from "#setup/prompter.js";+import {+ resolveVercelDeployment,+ type VercelDeploymentResolutionFailure,+ type VerifiedVercelTarget,+} from "#setup/vercel-deployment.js";+import { WizardCancelledError } from "#setup/step.js";+import {+ applyVercelTrustedSourceAccess,+ prepareVercelTrustedSourceAccess,+ type VercelTrustedSourceGrant,+} from "./vercel-trusted-sources.js";+import {+ appendRemoteAuthMutationSummary,+ type RemoteAuthCompletedMutation,+ type RemoteAuthPreparation,+} from "./remote-auth-result.js";+import { toErrorMessage } from "#shared/errors.js";++/** Injectable entry point for the remote authentication flow. */+export type RemoteAuthFlow = typeof runRemoteAuthFlow;+export interface RemoteAuthFlowDeps {+ readonly runLoginFlow: typeof runLoginFlow;+ readonly resolveVercelDeployment: typeof resolveVercelDeployment;+ readonly resolveOidcToken: typeof resolveDevelopmentOidcToken;+ readonly prepareVercelTrustedSourceAccess: typeof prepareVercelTrustedSourceAccess;+ readonly applyVercelTrustedSourceAccess: typeof applyVercelTrustedSourceAccess;+}++const defaultDeps: RemoteAuthFlowDeps = {+ runLoginFlow,+ resolveVercelDeployment,+ resolveOidcToken: resolveDevelopmentOidcToken,+ prepareVercelTrustedSourceAccess,+ applyVercelTrustedSourceAccess,+};++function failed(+ message: string,+ completedMutations: readonly RemoteAuthCompletedMutation[] = [],+): Extract<RemoteAuthPreparation, { kind: "failed" }> {+ return {+ kind: "failed",+ message: appendRemoteAuthMutationSummary(message, completedMutations),+ completedMutations: [...completedMutations],+ };+}++function cancelled(+ completedMutations: readonly RemoteAuthCompletedMutation[] = [],+): Extract<RemoteAuthPreparation, { kind: "cancelled" }> {+ return { kind: "cancelled", completedMutations: [...completedMutations] };+}++function loginFailure(result: LoginFlowResult): RemoteAuthPreparation | undefined {+ switch (result.kind) {+ case "already":+ case "logged-in":+ return undefined;+ case "cancelled":+ return cancelled();+ case "cli-missing":+ return failed(+ "The Vercel CLI is not installed. Install it with `npm i -g vercel@latest`, then retry /vc:auth.",+ );+ case "failed":+ return failed("Vercel login did not complete. Retry /vc:auth.");+ case "unavailable":+ return failed(+ "Vercel could not verify your account. Check your connection, then retry /vc:auth.",+ );+ }+}++function deploymentFailureMessage(failure: VercelDeploymentResolutionFailure): string {+ return failure.cause === "vercel" ? failure.failure.message : failure.message;+}++/**+ * Authenticates a remote by resolving its deployment URL to the owning Vercel+ * project, updating Trusted Sources when needed and keeping the resolved+ * credential in this TUI session.+ */+export async function runRemoteAuthFlow(input: {+ readonly workspaceRoot: string;+ readonly serverUrl: string;+ readonly configureTrustedSources?: boolean;+ readonly prompter: Prompter;+ readonly signal?: AbortSignal;+ readonly deps?: Partial<RemoteAuthFlowDeps>;+}): Promise<RemoteAuthPreparation> {+ const { workspaceRoot, serverUrl, prompter, signal } = input;+ const host = new URL(serverUrl).host;+ const deps: RemoteAuthFlowDeps = { ...defaultDeps, ...input.deps };+ const completedMutations: RemoteAuthCompletedMutation[] = [];+ let mutationStarted = false;++ try {+ // Authenticate first so the resolve runs under real credentials. When the+ // user is already logged in this is a no-op and shows no dialogue.+ const login = await deps.runLoginFlow({ appRoot: workspaceRoot, prompter, signal });+ const loginOutcome = loginFailure(login);+ if (loginOutcome !== undefined) return loginOutcome;+ if (login.kind === "logged-in") completedMutations.push({ kind: "vercel-login" });++ // A deployment hostname is globally unique, so Vercel resolves the project+ // and owning team straight from the URL under the caller's own access — no+ // team/project picker. If access is denied (for example an expired team SSO+ // session), re-authenticate through the same dialogue and resolve once more.+ let resolution = await deps.resolveVercelDeployment({ workspaceRoot, host, signal });+ if (resolution.kind === "forbidden") {+ const reauth = await deps.runLoginFlow({+ appRoot: workspaceRoot,+ force: true,+ prompter,+ signal,+ });+ const reauthOutcome = loginFailure(reauth);+ if (reauthOutcome !== undefined) return reauthOutcome;+ if (reauth.kind === "logged-in") completedMutations.push({ kind: "vercel-login" });+ signal?.throwIfAborted();+ resolution = await deps.resolveVercelDeployment({ workspaceRoot, host, signal });+ }++ let target: VerifiedVercelTarget;+ switch (resolution.kind) {+ case "resolved":+ target = resolution.target;+ break;+ case "cancelled":+ return cancelled(completedMutations);+ case "forbidden":+ return failed(+ `Could not access ${host}. Re-authenticate (for example to complete a team's SSO), then retry /vc:auth.`,+ completedMutations,+ );+ case "not-found":+ return failed(+ `Vercel did not resolve ${host} as a deployment you can access. If it belongs to a team that enforces SSO, re-authenticate and retry /vc:auth.`,+ completedMutations,+ );+ case "project-mismatch":+ return failed(+ `Could not verify ${host}: Vercel resolved project ${resolution.actualProjectId}, not ${resolution.expectedProjectId}.`,+ completedMutations,+ );+ case "failed":+ return failed(+ `Could not verify ${host} through Vercel: ${deploymentFailureMessage(resolution.failure)}`,+ completedMutations,+ );+ }++ let trustedSourcesGrant: VercelTrustedSourceGrant | undefined;+ if (input.configureTrustedSources === true) {+ const trustedSources = await deps.prepareVercelTrustedSourceAccess({+ workspaceRoot,+ target,+ prompter,+ signal,+ });+ signal?.throwIfAborted();+ if (trustedSources.kind === "cancelled") return cancelled(completedMutations);+ if (trustedSources.kind === "failed") {+ return failed(trustedSources.message, completedMutations);+ }+ if (trustedSources.kind === "approved") trustedSourcesGrant = trustedSources.grant;+ }++ signal?.throwIfAborted();+ if (trustedSourcesGrant !== undefined) {+ mutationStarted = true;+ const trustedSources = await deps.applyVercelTrustedSourceAccess({+ workspaceRoot,+ grant: trustedSourcesGrant,+ signal,+ });+ if (trustedSources.kind === "failed") {+ return failed(trustedSources.message, completedMutations);+ }+ if (trustedSources.kind === "updated") {+ completedMutations.push({+ kind: "trusted-sources-updated",+ targetProjectName: trustedSources.targetProjectName,+ });+ }+ }++ const tokenResolution = await deps.resolveOidcToken({+ ownerId: target.deployment.ownerId,+ projectId: target.deployment.projectId,+ forceRefresh: true,+ });+ signal?.throwIfAborted();+ if (tokenResolution.kind !== "resolved") {+ return failed(formatDevelopmentOidcTokenFailure(tokenResolution), completedMutations);+ }+ let token = tokenResolution.token.trim();+ const resolveToken = async (): Promise<string> => {+ const refreshed = await deps.resolveOidcToken(target.deployment);+ if (refreshed.kind === "resolved") token = refreshed.token.trim();+ return token;+ };+ return { kind: "prepared", target, resolveToken, completedMutations: [...completedMutations] };+ } catch (error) {+ if (!mutationStarted && (error instanceof WizardCancelledError || signal?.aborted === true)) {+ return cancelled(completedMutations);+ }+ return failed(`Could not authenticate ${host}: ${toErrorMessage(error)}`, completedMutations);+ }+}diff --git a/packages/eve/src/cli/dev/tui/remote-connection-probe.ts b/packages/eve/src/cli/dev/tui/remote-connection-probe.tsindex 3464d4626..d45e828c7 100644--- a/packages/eve/src/cli/dev/tui/remote-connection-probe.ts+++ b/packages/eve/src/cli/dev/tui/remote-connection-probe.ts@@ -1,5 +1,9 @@-import { ClientError, type Client } from "#client/index.js";-import { isVercelAuthChallenge } from "#services/dev-client/vercel-auth-error.js";+import { AgentInfoResponseError, ClientError, type Client } from "#client/index.js";+import {+ formatVercelTrustedSourcesFailure,+ isVercelAuthChallenge,+ vercelTrustedSourcesErrorCode,+} from "#services/dev-client/vercel-auth-error.js";import { toErrorMessage } from "#shared/errors.js";import { isObject } from "#shared/guards.js";@@ -10,6 +14,8 @@ export type RemoteProbeResult = Extract<{ state: "ready" | "auth-required" | "unavailable" }>;+export type RemoteProbePhase = "connection-check" | "authentication-verification";+function isEveOidcChallenge(error: unknown): boolean {if (!(error instanceof ClientError) || error.status !== 401) return false;@@ -26,7 +32,7 @@ function isEveOidcChallenge(error: unknown): boolean {}}-export function classifyRemoteError(error: unknown): RemoteProbeResult {+export function classifyRemoteError(error: unknown, phase: RemoteProbePhase): RemoteProbeResult {if (isVercelAuthChallenge(error)) {return {state: "auth-required",@@ -40,7 +46,22 @@ export function classifyRemoteError(error: unknown): RemoteProbeResult {};}if (error instanceof ClientError) {- return { state: "unavailable", failure: { message: error.message } };+ const code = vercelTrustedSourcesErrorCode(error.message);+ if (+ phase === "connection-check" &&+ error.status === 403 &&+ code === "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH"+ ) {+ return {+ state: "auth-required",+ challenge: { kind: "vercel-deployment-protection" },+ };+ }+ const failure = { message: formatVercelTrustedSourcesFailure(error.message) };+ return {+ state: "unavailable",+ failure: code === undefined ? failure : { ...failure, code },+ };}return {state: "unavailable",@@ -48,12 +69,39 @@ export function classifyRemoteError(error: unknown): RemoteProbeResult {};}+/**+ * Confirms the target is a live eve deployment via the always-public health+ * route. Used to corroborate a missing info route before declaring a connection+ * ready, so a host that simply 404s everything is not mistaken for a degraded+ * deployment whose `/eve/v1/info` is absent.+ */+async function probeDeploymentHealth(client: Client): Promise<boolean> {+ try {+ const health: unknown = await client.health();+ return isObject(health) && health.ok === true;+ } catch {+ return false;+ }+}+export async function probeRemoteInfo(input: {readonly client: Client;+ readonly phase: RemoteProbePhase;}): Promise<RemoteProbeResult> {try {return { state: "ready", info: await input.client.info() };} catch (error) {- return classifyRemoteError(error);+ // Inspection is best-effort: an authorized response we cannot use must not+ // block the connection, since the conversation transport does not depend on+ // `/eve/v1/info`.+ if (+ error instanceof AgentInfoResponseError ||+ (error instanceof ClientError && error.status === 404)+ ) {+ // The info route can be missing or use an older payload shape. Only call+ // the target ready once the public health route confirms a live Eve server.+ if (await probeDeploymentHealth(input.client)) return { state: "ready" };+ }+ return classifyRemoteError(error, input.phase);}}diff --git a/packages/eve/src/cli/dev/tui/remote-connection-types.ts b/packages/eve/src/cli/dev/tui/remote-connection-types.tsindex 51fe9f3e6..169c7c8c8 100644--- a/packages/eve/src/cli/dev/tui/remote-connection-types.ts+++ b/packages/eve/src/cli/dev/tui/remote-connection-types.ts@@ -14,12 +14,17 @@ export type RemoteAuthChallenge =| { readonly kind: "vercel-deployment-protection" };interface RemoteRequestFailure {+ readonly code?: string;readonly message: string;}export type RemoteConnectionState =| { readonly state: "checking" }- | { readonly state: "ready"; readonly info: AgentInfoResult }+ // `info` is best-effort: a connection is ready once auth is satisfied and the+ // deployment is reachable. Inspection data is absent when the deployment's+ // `/eve/v1/info` is missing or returns an unrecognized shape (e.g. version+ // skew); the conversation transport does not depend on it.+ | { readonly state: "ready"; readonly info?: AgentInfoResult }| {readonly state: "auth-required";readonly challenge: RemoteAuthChallenge;diff --git a/packages/eve/src/cli/dev/tui/remote-connection.test.ts b/packages/eve/src/cli/dev/tui/remote-connection.test.tsindex 0e90350a8..519aebb94 100644--- a/packages/eve/src/cli/dev/tui/remote-connection.test.ts+++ b/packages/eve/src/cli/dev/tui/remote-connection.test.ts@@ -1,6 +1,11 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { Client, ClientError, type AgentInfoResult } from "#client/index.js";+import {+ AgentInfoResponseError,+ Client,+ ClientError,+ type AgentInfoResult,+} from "#client/index.js";import { resolveTestVercelTarget } from "#internal/testing/verified-vercel-target.js";import {createDevelopmentCredentialGate,@@ -83,6 +88,11 @@ const VERCEL_SSO_CHALLENGE = `<a href="https://vercel.com/sso-api?url=https%3A%2F%2Fvpoke.playground-vercel.tools">Vercel Authentication</a>`;+const TRUSTED_SOURCES_MISMATCH = [+ "The caller environment is not permitted.",+ "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH",+].join("\n\n");+function eveUnauthorized(error = "Authorization is required for this route."): ClientError {return new ClientError(401, JSON.stringify({ code: "unauthorized", error, ok: false }));}@@ -157,6 +167,22 @@ describe("createRemoteConnectionController", () => {challenge: { kind: "vercel-deployment-protection" },},},+ {+ name: "a 403 Trusted Sources environment mismatch",+ error: new ClientError(403, TRUSTED_SOURCES_MISMATCH),+ expected: {+ state: "auth-required",+ challenge: { kind: "vercel-deployment-protection" },+ },+ },+ {+ name: "the same Trusted Sources code on a non-403 response",+ error: new ClientError(500, TRUSTED_SOURCES_MISMATCH),+ expected: {+ state: "unavailable",+ failure: { code: "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH" },+ },+ },{name: "an ordinary HTTP failure",error: new ClientError(503, "Unavailable"),@@ -167,15 +193,63 @@ describe("createRemoteConnectionController", () => {error: new Error("offline"),expected: { state: "unavailable", failure: { message: "offline" } },},- {- name: "an invalid response",- error: new SyntaxError("bad JSON"),- expected: { state: "unavailable", failure: { message: "bad JSON" } },- },])("classifies $name", async ({ error, expected }) => {await expect(checkFailure(error)).resolves.toMatchObject(expected);});+ it("stays ready after an unusable info payload when health confirms Eve", async () => {+ const harness = createHarness({+ info: async () => {+ throw new AgentInfoResponseError(["agent: Required"]);+ },+ });+ const health = vi.spyOn(harness.client, "health").mockResolvedValue({+ ok: true,+ status: "ready",+ workflowId: "wf_test",+ });++ await expect(harness.controller.check()).resolves.toEqual({ state: "ready" });+ expect(health).toHaveBeenCalledOnce();+ });++ it("is unavailable after an unusable info payload when health cannot confirm Eve", async () => {+ const harness = createHarness({+ info: async () => {+ throw new AgentInfoResponseError(["agent: Required"]);+ },+ });+ vi.spyOn(harness.client, "health").mockRejectedValue(new ClientError(404, "Not Found"));++ await expect(harness.controller.check()).resolves.toMatchObject({ state: "unavailable" });+ });++ it("stays ready when the info route is missing but health confirms a live deployment", async () => {+ const harness = createHarness({+ info: async () => {+ throw new ClientError(404, "Not Found");+ },+ });+ vi.spyOn(harness.client, "health").mockResolvedValue({+ ok: true,+ status: "ready",+ workflowId: "wf_test",+ });++ await expect(harness.controller.check()).resolves.toEqual({ state: "ready" });+ });++ it("is unavailable when the info route is missing and health does not confirm a deployment", async () => {+ const harness = createHarness({+ info: async () => {+ throw new ClientError(404, "Not Found");+ },+ });+ vi.spyOn(harness.client, "health").mockRejectedValue(new ClientError(404, "Not Found"));++ await expect(harness.controller.check()).resolves.toMatchObject({ state: "unavailable" });+ });+it("resolves ambient credentials only after deployment authority is established", async () => {const pending = deferred<VercelDeploymentResolution>();const resolveDeployment = vi.fn(() => pending.promise);@@ -252,7 +326,7 @@ describe("createRemoteConnectionController", () => {kind: "prepared",target: VERIFIED_TARGET,resolveToken: async () => "rejected-token",- completedMutations: [{ kind: "vercel-login" }],+ completedMutations: [{ kind: "trusted-sources-updated", targetProjectName: "remote-agent" }],}));const harness = createHarness({ info });@@ -261,7 +335,7 @@ describe("createRemoteConnectionController", () => {kind: "failed",message:"The selected Vercel project did not authorize vpoke.playground-vercel.tools. " +- "Completed before the failure: logged in to Vercel.",+ "Completed before the failure: updated Trusted Sources for remote-agent.",});expect(attempt).toHaveBeenCalledOnce();expect(info).toHaveBeenCalledTimes(2);diff --git a/packages/eve/src/cli/dev/tui/remote-connection.ts b/packages/eve/src/cli/dev/tui/remote-connection.tsindex 19beaf18d..e93d9f33a 100644--- a/packages/eve/src/cli/dev/tui/remote-connection.ts+++ b/packages/eve/src/cli/dev/tui/remote-connection.ts@@ -33,8 +33,11 @@ function challengeFor(state: RemoteConnectionState): RemoteAuthChallenge {return state.challenge;case "checking":case "ready":- case "unavailable":return { kind: "eve-oidc" };+ case "unavailable":+ return state.failure.code === "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH"+ ? { kind: "vercel-deployment-protection" }+ : { kind: "eve-oidc" };}}@@ -113,7 +116,10 @@ export function createRemoteConnectionController(return connection;}restoreActiveCredentials = restoreCredentials;- const probe = await probeRemoteInfo({ client: options.client });+ const probe = await probeRemoteInfo({+ client: options.client,+ phase: "connection-check",+ });if (!isCurrent(operation.generation)) return connection;return update(probe);},@@ -169,7 +175,10 @@ export function createRemoteConnectionController(update({ state: "auth-failed", challenge });return { kind: "failed", message };}- const verified = await probeRemoteInfo({ client: options.client });+ const verified = await probeRemoteInfo({+ client: options.client,+ phase: "authentication-verification",+ });if (!isCurrent(operation.generation)) {restoreCandidateCredentials();return { kind: "cancelled", completedMutations: preparation.completedMutations };@@ -212,7 +221,7 @@ export function createRemoteConnectionController(reportFailure(error: unknown): RemoteConnectionState {operationAbort?.abort();operationGeneration += 1;- return update(classifyRemoteError(error));+ return update(classifyRemoteError(error, "connection-check"));},dispose(): void {diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex 51e821e6a..11fe11690 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -2,11 +2,14 @@ import { afterEach, describe, expect, it, vi } from "vitest";import {Client,+ ClientError,MessageResponse,type AgentInfoResult,type ClientSession,type HandleMessageStreamEvent,} from "#client/index.js";+import { resolveTestVercelTarget } from "#internal/testing/verified-vercel-target.js";+import { createDevelopmentCredentialGate } from "#services/dev-client/credential-gate.js";import {EveTUIRunner,@@ -18,10 +21,20 @@ import {type PromptCommandOutcome,} from "./runner.js";import { createPromptCommandHandler } from "./prompt-command-handler.js";+import { promptCommandsFor } from "./prompt-commands.js";+import type { RemoteAuthFlow } from "./remote-auth.js";+import type { RemoteAuthCompletedMutation } from "./remote-auth-result.js";import type { BootDetection, SetupIssue } from "./setup-issues.js";+import type { SetupFlowRenderer } from "./setup-flow.js";import { createFakeSetupFlowRenderer } from "./test/fake-setup-flow-renderer.js";import type { VercelStatusSnapshot } from "./vercel-status.js";+const REMOTE_VERIFIED_TARGET = await resolveTestVercelTarget({+ host: "vpoke.playground-vercel.tools",+ projectId: "prj_inbound",+ projectName: "inbound",+});+/*** Real `Client` whose network-touching methods are replaced by vi spies.* Keeps the runner's option types honest (no double casts) while still@@ -179,6 +192,26 @@ function fakeRenderer(overrides: Partial<AgentTUIRenderer> = {}): AgentTUIRender};}+function idleSetupFlow(): SetupFlowRenderer {+ return {+ begin: vi.fn(),+ end: vi.fn(),+ readSelect: vi.fn(async () => undefined),+ readEditableSelect: vi.fn(async () => undefined),+ readProviderPicker: vi.fn(async () => undefined),+ readText: vi.fn(async () => undefined),+ readAcknowledge: vi.fn(async () => {}),+ readChoice: vi.fn(() => ({ choice: Promise.resolve(undefined), close: vi.fn() })),+ setStatus: vi.fn(),+ renderLine: vi.fn(),+ renderOutput: vi.fn(),+ waitForInterrupt: () => ({+ promise: new Promise<void>(() => {}),+ dispose: vi.fn(),+ }),+ };+}+function createDeferred<T>() {let resolve!: (value: T | PromiseLike<T>) => void;let reject!: (reason?: unknown) => void;@@ -1088,7 +1121,14 @@ describe("EveTUIRunner setup commands", () => {session,renderer,name: "Weather Agent",- promptCommandHandler: createPromptCommandHandler({}),+ availablePromptCommands: promptCommandsFor("remote"),+ promptCommandHandler: createPromptCommandHandler({+ target: {+ kind: "remote",+ workspaceRoot: "/tmp/weather-agent",+ serverUrl: "https://example.com/",+ },+ }),});await runner.run();@@ -1106,7 +1146,13 @@ describe("EveTUIRunner setup commands", () => {renderer,name: "Weather Agent",appRoot: "/tmp/weather-agent",- promptCommandHandler: createPromptCommandHandler({ appRoot: "/tmp/weather-agent" }),+ promptCommandHandler: createPromptCommandHandler({+ target: {+ kind: "local",+ serverUrl: "http://localhost:3000",+ workspaceRoot: "/tmp/weather-agent",+ },+ }),});await runner.run();@@ -1116,6 +1162,194 @@ describe("EveTUIRunner setup commands", () => {});});+describe("EveTUIRunner remote authentication", () => {+ const target = {+ kind: "remote",+ serverUrl: "https://vpoke.playground-vercel.tools",+ workspaceRoot: "/tmp/weather-agent",+ } as const;++ function remoteOptions() {+ return {+ target,+ credentials: createDevelopmentCredentialGate(target.serverUrl),+ resolveDeployment: async () => ({ kind: "not-found" }) as const,+ resolveOidcToken: async () => ({+ kind: "resolution-failed" as const,+ message: "No ambient token in this test.",+ }),+ };+ }++ function unauthorized(): ClientError {+ return new ClientError(+ 401,+ '{"ok":false,"code":"unauthorized","error":"Authorization is required for this route."}',+ );+ }++ function successfulAuth(+ completedMutations: readonly RemoteAuthCompletedMutation[] = [],+ ): RemoteAuthFlow {+ return vi.fn<RemoteAuthFlow>(async () => ({+ kind: "prepared",+ target: REMOTE_VERIFIED_TARGET,+ resolveToken: async () => "fresh-token",+ completedMutations,+ }));+ }++ async function runRemoteAuth(input: {+ client: Client;+ flow: RemoteAuthFlow;+ renderer?: Partial<AgentTUIRenderer>;+ }): Promise<void> {+ await new EveTUIRunner({+ session: input.client.session(),+ client: input.client,+ renderer: fakeRenderer({ setupFlow: idleSetupFlow(), ...input.renderer }),+ serverUrl: target.serverUrl,+ availablePromptCommands: promptCommandsFor("remote"),+ promptCommandHandler: createPromptCommandHandler({+ target,+ remoteAuthFlow: input.flow,+ }),+ remote: remoteOptions(),+ }).run();+ }++ it("runs /vc:auth once at startup after the exact remote auth challenge", async () => {+ const client = stubClient();+ vi.spyOn(client, "info")+ .mockRejectedValueOnce(unauthorized())+ .mockResolvedValueOnce(AGENT_INFO);+ const commandInvocations: Array<{ text: string; status: "failed" | undefined }> = [];+ const flow = successfulAuth();++ await runRemoteAuth({+ client,+ flow,+ renderer: {+ renderCommandInvocation: (text, status) => commandInvocations.push({ text, status }),+ },+ });++ expect(flow).toHaveBeenCalledOnce();+ expect(commandInvocations).toEqual([{ text: "/vc:auth", status: undefined }]);+ });++ it("requests Trusted Sources repair for an environment mismatch", async () => {+ const client = stubClient();+ const mismatch = new ClientError(+ 403,+ "The caller environment is not permitted.\n\n" ++ "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH\n\niad1::request-id",+ );+ vi.spyOn(client, "info").mockRejectedValueOnce(mismatch).mockResolvedValueOnce(AGENT_INFO);+ const flow = successfulAuth();++ await runRemoteAuth({ client, flow });++ expect(flow).toHaveBeenCalledWith(expect.objectContaining({ configureTrustedSources: true }));+ });++ it("renders a failed automatic /vc:auth as one command result without the request id", async () => {+ const client = stubClient();+ vi.spyOn(client, "info")+ .mockRejectedValueOnce(unauthorized())+ .mockRejectedValueOnce(+ new ClientError(+ 403,+ "Your trusted sources OIDC token's environment is not permitted to access this deployment\n\n" ++ "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH\n\niad1::zgc5p-1781730251155-85842c28901b",+ ),+ );+ const commandInvocations: Array<{ text: string; status: "failed" | undefined }> = [];+ const commandResults: string[] = [];+ const flow = successfulAuth([+ { kind: "trusted-sources-updated", targetProjectName: "remote-agent" },+ ]);++ await runRemoteAuth({+ client,+ flow,+ renderer: {+ renderCommandInvocation: (text, status) => commandInvocations.push({ text, status }),+ renderCommandResult: (message) => commandResults.push(message),+ },+ });++ expect(commandInvocations).toEqual([{ text: "/vc:auth", status: "failed" }]);+ expect(commandResults).toEqual([+ "Authentication was refreshed, but vpoke.playground-vercel.tools is unavailable: " ++ "Your trusted sources OIDC token's environment is not permitted to access this deployment.\n\n" ++ "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH Completed before the failure: updated Trusted Sources for remote-agent.",+ ]);+ });++ it("does not start authentication for an ordinary remote HTTP failure", async () => {+ const client = stubClient();+ vi.spyOn(client, "info").mockRejectedValue(new ClientError(503, "Unavailable"));+ const flow = successfulAuth();++ await runRemoteAuth({ client, flow });++ expect(flow).not.toHaveBeenCalled();+ });++ it("demotes a ready remote after turn dispatch fails", async () => {+ const client = stubClient();+ vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);+ const session = client.session();+ vi.spyOn(session, "send").mockRejectedValue(new Error("socket down"));+ const statuses: string[] = [];+ const readPrompt = vi.fn().mockResolvedValueOnce("hello").mockResolvedValueOnce(undefined);++ await new EveTUIRunner({+ session,+ client,+ renderer: fakeRenderer({+ readPrompt,+ setRemoteConnectionStatus: (snapshot) => statuses.push(snapshot.connection.state),+ }),+ serverUrl: target.serverUrl,+ remote: remoteOptions(),+ }).run();++ expect(statuses.at(-1)).toBe("unavailable");+ });++ it("keeps a ready remote connected after an agent session failure", async () => {+ const client = stubClient();+ vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);+ const session = sessionYielding([+ {+ type: "session.failed",+ data: { code: "HookConflictError", message: "HookConflictError: token in use" },+ },+ ]);+ const statuses: string[] = [];+ const readPrompt = vi.fn().mockResolvedValueOnce("hello").mockResolvedValueOnce(undefined);++ await new EveTUIRunner({+ session,+ client,+ renderer: fakeRenderer({+ readPrompt,+ renderStream: vi.fn(async (result) => {+ for await (const event of result.events as AsyncIterable<unknown>) void event;+ }),+ setRemoteConnectionStatus: (snapshot) => statuses.push(snapshot.connection.state),+ }),+ serverUrl: target.serverUrl,+ remote: remoteOptions(),+ }).run();++ expect(statuses.at(-1)).toBe("ready");+ expect(statuses).not.toContain("unavailable");+ });+});+describe("EveTUIRunner renderer teardown", () => {it("shuts the renderer down when the run loop exits with an error", async () => {// The terminal renderer's shutdown restores the captured stdout/stderr@@ -1690,7 +1924,13 @@ describe("EveTUIRunner command outcome rendering", () => {session,renderer,name: "Weather Agent",- promptCommandHandler: createPromptCommandHandler({}),+ promptCommandHandler: createPromptCommandHandler({+ target: {+ kind: "remote",+ workspaceRoot: "/tmp/weather-agent",+ serverUrl: "https://example.com/",+ },+ }),});await runner.run();diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex 0e371c254..b1e800311 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -45,8 +45,17 @@ import { parseLogDisplayMode } from "./log-display-mode.js";import {formatPromptCommandHelp,parsePromptCommand,+ PROMPT_COMMANDS,type PromptCommand,+ type PromptCommandSpec,} from "./prompt-commands.js";+import {+ createRemoteConnectionController,+ type RemoteConnectionController,+ type RemoteConnectionControllerOptions,+ type RemoteConnectionSnapshot,+} from "./remote-connection.js";+import type { DevelopmentCredentialGate } from "#services/dev-client/credential-gate.js";import {BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,@@ -61,6 +70,7 @@ import {type SetupIssue,} from "./setup-issues.js";import type { SetupFlowRenderer } from "./setup-flow.js";+import type { RemoteDevelopmentTarget } from "./target.js";import type {AssistantResponseStatsMode,LogDisplayMode,@@ -194,6 +204,8 @@ export type AgentTUIRenderer = {renderSetupWarning?(text: string): void;/** Clears the setup attention line once its issue is resolved. */clearSetupWarning?(): void;+ /** Commits the startup `/vc:auth` invocation to the transcript. */+ renderCommandInvocation?(text: string, status?: "failed"): void;renderCommandResult?(text: string): void;readonly setupFlow?: SetupFlowRenderer;readPrompt?(options?: AgentTUISessionOptions): Promise<string | undefined>;@@ -265,6 +277,8 @@ export type AgentTUIRenderer = {* line ignore it.*/setVercelStatus?(status: VercelStatusSnapshot): void;+ /** Sets the remote deployment badge and its current connection/authentication state. */+ setRemoteConnectionStatus?(status: RemoteConnectionSnapshot): void;/*** Clears the rendered transcript and resets per-conversation display* state, leaving the UI interactive on a fresh screen. Used by the@@ -283,6 +297,7 @@ export interface PromptCommandHandlerContext {readonly title: string;/** Provider entry authorized by confirmed boot-time model-access evidence. */readonly initialModelStep?: "provider";+ readonly remoteConnection?: RemoteConnectionController;}/** What one handled slash command leaves behind for the runner to apply. */@@ -337,6 +352,15 @@ export type EveTUIRunnerOptions = TuiDisplayOptions & {initialInput?: string;/** Handles non-core slash commands without adding feature branches to the runner. */promptCommandHandler?: PromptCommandHandler;+ /** Commands shown in discovery for this local or remote session. */+ availablePromptCommands?: readonly PromptCommandSpec[];+ /** Remote target and mutable OIDC token source, when connected through `--url`. */+ remote?: {+ readonly target: RemoteDevelopmentTarget;+ readonly credentials: DevelopmentCredentialGate;+ readonly resolveOidcToken: NonNullable<RemoteConnectionControllerOptions["resolveOidcToken"]>;+ readonly resolveDeployment: NonNullable<RemoteConnectionControllerOptions["resolveDeployment"]>;+ };/** Boot-time installation-state checks; defaults to the built-ins. */bootDetections?: readonly BootDetection[];/** Test seam for the status line's Vercel link probe; defaults to the real one. */@@ -372,6 +396,8 @@ export class EveTUIRunner {/** Seeds the first prompt's editable buffer; consumed once in {@link #run}. */readonly #initialInput?: string;readonly #promptCommandHandler?: PromptCommandHandler;+ readonly #availablePromptCommands: readonly PromptCommandSpec[];+ readonly #remoteConnection?: RemoteConnectionController;readonly #bootDetections: readonly BootDetection[];readonly #getVercelAuthStatus: typeof getVercelAuthStatus;#onBootProgress?: DevBootProgressReporter;@@ -474,11 +500,25 @@ export class EveTUIRunner {if (options.promptCommandHandler !== undefined) {this.#promptCommandHandler = options.promptCommandHandler;}+ this.#availablePromptCommands = options.availablePromptCommands ?? PROMPT_COMMANDS;+ if (options.remote !== undefined) {+ if (this.#client === undefined) {+ throw new Error("A remote TUI requires a configured development client.");+ }+ this.#remoteConnection = createRemoteConnectionController({+ client: this.#client,+ credentials: options.remote.credentials,+ target: options.remote.target,+ onChange: (snapshot) => this.#renderer.setRemoteConnectionStatus?.(snapshot),+ resolveOidcToken: options.remote.resolveOidcToken,+ resolveDeployment: options.remote.resolveDeployment,+ });+ }this.#bootDetections = options.bootDetections ?? BOOT_DETECTIONS;this.#getVercelAuthStatus = options.getVercelAuthStatus ?? getVercelAuthStatus;if (options.onBootProgress !== undefined) this.#onBootProgress = options.onBootProgress;- if (options.serverUrl !== undefined) {- this.#serverUrl = options.serverUrl;+ if (options.serverUrl !== undefined) this.#serverUrl = options.serverUrl;+ if (options.serverUrl !== undefined && options.remote === undefined) {this.#runtimeArtifacts = createDevelopmentRuntimeArtifactSessionRefresher({serverUrl: options.serverUrl,});@@ -499,14 +539,19 @@ export class EveTUIRunner {}let info: AgentInfoResult | undefined;- try {- info = await devBootPhase(- "connecting to agent",- () => (this.#client ? this.#client.info() : Promise.resolve(undefined)),- this.#onBootProgress,- );- } catch {- info = undefined;+ if (this.#remoteConnection !== undefined) {+ const connection = await this.#remoteConnection.check();+ if (connection.state === "ready") info = connection.info;+ } else {+ try {+ info = await devBootPhase(+ "connecting to agent",+ () => (this.#client ? this.#client.info() : Promise.resolve(undefined)),+ this.#onBootProgress,+ );+ } catch {+ info = undefined;+ }}this.#reportBeforeFirstPaint();const headerInfo = this.#replaceAgentInfo(info);@@ -549,6 +594,7 @@ export class EveTUIRunner {// Drops any in-flight link probe so a late resolution cannot paint// into a torn-down terminal.this.#vercelStatus?.dispose();+ this.#remoteConnection?.dispose();}}@@ -564,6 +610,13 @@ export class EveTUIRunner {let initialDraft = this.#initialInput;await this.#renderAgentHeader();+ if (this.#remoteConnection?.current().connection.state === "auth-required") {+ await this.#executeExtensionCommand(+ { type: "extension", name: "vc:auth", argument: "" },+ title,+ "startup",+ );+ }this.#subscribeDevelopmentSandboxLogs();// Fire-and-forget: the link identity is network-bound to resolve, and the// first prompt must not wait on it. The segment appears when it lands.@@ -626,7 +679,7 @@ export class EveTUIRunner {// Help renders locally; unlike extension commands it must work even// without a prompt-command handler (e.g. remote --url sessions).if (command?.type === "help") {- this.#renderCommandOutcome(formatPromptCommandHelp());+ this.#renderCommandOutcome(formatPromptCommandHelp(this.#availablePromptCommands));pendingInputResponses = undefined;streamWithoutPrompt = false;prompt = undefined;@@ -647,26 +700,8 @@ export class EveTUIRunner {try {const initialModelStep =command.name === "model" ? automaticSetup?.initialModelStep : undefined;- const context: PromptCommandHandlerContext =- initialModelStep === undefined- ? { renderer: this.#renderer, title }- : { renderer: this.#renderer, title, initialModelStep };automaticSetup = undefined;- const outcome =- this.#promptCommandHandler === undefined- ? { message: `/${command.name} is not available in this session.` }- : await this.#promptCommandHandler.handle(command, context);- if (outcome?.message !== undefined) this.#renderCommandOutcome(outcome.message);- const effect = outcome?.effect;- if (effect?.kind === "model-access-changed") {- this.#vercelStatus?.applyEffect({ kind: "refresh-identity" });- this.#authHintStale = true;- await this.#refreshModelAccess();- } else if (effect !== undefined) {- this.#vercelStatus?.applyEffect(effect);- this.#authHintStale = true;- void this.#refreshSetupAttention(this.#agentInfo);- }+ await this.#executeExtensionCommand(command, title, "command", initialModelStep);} catch (error) {if (isInterruptedError(error)) return;throw error;@@ -902,6 +937,7 @@ export class EveTUIRunner {// as in-stream failures so it renders as an inline region right// where the assistant response would have appeared, then let the// loop recover onto a fresh session before the next prompt.+ this.#remoteConnection?.reportFailure(error);this.#sessionFailed = true;return {events: errorOnlyTUIStream({@@ -980,8 +1016,8 @@ export class EveTUIRunner {/*** Re-evaluates the attention line after a setup command changed local state,- * so a fixed issue clears (e.g. the `not logged in · /login` line disappears- * once `/login` succeeds) instead of lingering stale. Authoritative: unlike+ * so a fixed issue clears (e.g. the `not logged in · /vc:login` line disappears+ * once `/vc:login` succeeds) instead of lingering stale. Authoritative: unlike* the boot probe it re-reads detections and auth and is not stale-guarded.*/async #refreshSetupAttention(info: AgentInfoResult | undefined): Promise<void> {@@ -1017,7 +1053,8 @@ export class EveTUIRunner {});}- #renderCommandOutcome(text: string): void {+ #renderCommandOutcome(text: string | undefined): void {+ if (text === undefined) return;if (this.#renderer.renderCommandResult !== undefined) {this.#renderer.renderCommandResult(text);return;@@ -1025,6 +1062,73 @@ export class EveTUIRunner {this.#renderer.renderNotice?.(text);}+ async #handleExtensionCommand(+ command: Extract<PromptCommand, { type: "extension" }>,+ input: Pick<PromptCommandHandlerContext, "initialModelStep" | "title">,+ ): Promise<PromptCommandOutcome | undefined> {+ const handler = this.#promptCommandHandler;+ if (handler === undefined)+ return { message: `/${command.name} is not available in this session.` };++ return await handler.handle(command, {+ renderer: this.#renderer,+ title: input.title,+ initialModelStep: input.initialModelStep,+ remoteConnection: this.#remoteConnection,+ });+ }++ #renderStartupCommandInvocation(+ command: Extract<PromptCommand, { type: "extension" }>,+ trigger: "startup" | "command",+ ): void {+ if (trigger !== "startup") return;++ const state = this.#remoteConnection?.current().connection.state;+ const status = state === "auth-failed" || state === "unavailable" ? "failed" : undefined;+ const argument = command.argument.length === 0 ? "" : ` ${command.argument}`;+ this.#renderer.renderCommandInvocation?.(`/${command.name}${argument}`, status);+ }++ async #applyCommandEffect(effect: PromptCommandOutcome["effect"]): Promise<void> {+ if (effect?.kind === "model-access-changed") {+ this.#vercelStatus?.applyEffect({ kind: "refresh-identity" });+ this.#authHintStale = true;+ await this.#refreshModelAccess();+ return;+ }+ if (effect === undefined) return;++ this.#vercelStatus?.applyEffect(effect);+ this.#authHintStale = true;+ void this.#refreshSetupAttention(this.#agentInfo);+ }++ async #executeExtensionCommand(+ command: Extract<PromptCommand, { type: "extension" }>,+ title: string,+ trigger: "startup" | "command",+ initialModelStep?: "provider",+ ): Promise<void> {+ const outcome = await this.#handleExtensionCommand(command, { initialModelStep, title });+ this.#renderStartupCommandInvocation(command, trigger);+ this.#renderCommandOutcome(outcome?.message);+ await this.#applyCommandEffect(outcome?.effect);+ this.#refreshHeaderFromRemoteConnection();+ }++ #refreshHeaderFromRemoteConnection(): void {+ const connection = this.#remoteConnection?.current().connection;+ if (connection?.state !== "ready" || connection.info === this.#agentInfo) return;+ this.#agentInfo = connection.info;+ if (this.#serverUrl === undefined) return;+ this.#renderer.renderAgentHeader?.({+ info: connection.info,+ name: this.#name,+ serverUrl: this.#serverUrl,+ });+ }+/*** Applies `/loglevel [all|stderr|sandbox|none]` against the renderer's buffered* log filter and returns the one-line outcome. A bare `/loglevel` reports@@ -1414,6 +1518,7 @@ function createRenderer(options: EveTUIRunnerOptions): AgentTUIRenderer {assistantResponseStats: options.assistantResponseStats,contextSize: options.contextSize,logs: options.logs,+ availablePromptCommands: options.availablePromptCommands,input: options.userInput,output: options.screen,});diff --git a/packages/eve/src/cli/dev/tui/setup-commands.test.ts b/packages/eve/src/cli/dev/tui/setup-commands.test.tsindex 0489bb91a..32a684b8e 100644--- a/packages/eve/src/cli/dev/tui/setup-commands.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-commands.test.ts@@ -71,7 +71,7 @@ function fakeFlows(overrides: Partial<TuiSetupFlows> = {}): TuiSetupFlows {}function run(input: {- command: "vc" | "login" | "model" | "channels" | "deploy";+ command: "vc:install" | "vc:login" | "model" | "channels" | "deploy";flows: TuiSetupFlows;renderer?: TuiSetupCommandRenderer;initialModelStep?: "provider";@@ -91,14 +91,14 @@ function run(input: {}describe("runTuiSetupCommand", () => {- it("uses the build pulse only for model and channel loading", () => {+ it("uses the build pulse for every setup command except deploy", () => {expect(Object.fromEntries(Object.entries(SETUP_FLOW_CONFIG).map(([command, config]) => [command, config.indicator]),),).toEqual({- vc: "spinner",- login: "spinner",+ "vc:install": "pulse",+ "vc:login": "pulse",model: "pulse",channels: "pulse",deploy: "spinner",@@ -523,7 +523,7 @@ describe("runTuiSetupCommand", () => {const flows = fakeFlows({runLoginFlow: vi.fn<TuiSetupFlows["runLoginFlow"]>(async () => ({ kind: "logged-in" })),});- await expect(run({ command: "login", flows })).resolves.toEqual({+ await expect(run({ command: "vc:login", flows })).resolves.toEqual({message: "Logged in to Vercel.",preserveFlowDiagnostics: false,effect: { kind: "refresh-identity" },@@ -534,18 +534,19 @@ describe("runTuiSetupCommand", () => {const flows = fakeFlows({runLoginFlow: vi.fn<TuiSetupFlows["runLoginFlow"]>(async () => ({ kind: "already" })),});- await expect(run({ command: "login", flows })).resolves.toEqual({+ await expect(run({ command: "vc:login", flows })).resolves.toEqual({message: "You're already logged in to Vercel.",preserveFlowDiagnostics: false,});});- it("routes a missing CLI from /login to /vc", async () => {+ it("routes a missing CLI from /vc:login to /vc:install", async () => {const flows = fakeFlows({runLoginFlow: vi.fn<TuiSetupFlows["runLoginFlow"]>(async () => ({ kind: "cli-missing" })),});- await expect(run({ command: "login", flows })).resolves.toEqual({- message: "The Vercel CLI isn't installed — run /vc to install it, then retry /login.",+ await expect(run({ command: "vc:login", flows })).resolves.toEqual({+ message:+ "The Vercel CLI isn't installed — run /vc:install to install it, then retry /vc:login.",preserveFlowDiagnostics: true,});});@@ -554,13 +555,13 @@ describe("runTuiSetupCommand", () => {const flows = fakeFlows({runLoginFlow: vi.fn<TuiSetupFlows["runLoginFlow"]>(async () => ({ kind: "unavailable" })),});- await expect(run({ command: "login", flows })).resolves.toEqual({- message: "Couldn't reach Vercel — check your connection, then retry /login.",+ await expect(run({ command: "vc:login", flows })).resolves.toEqual({+ message: "Couldn't reach Vercel — check your connection, then retry /vc:login.",preserveFlowDiagnostics: true,});});- it("routes a vercel-login action error to /login instead of a raw failure", async () => {+ it("routes a vercel-login action error to /vc:login instead of a raw failure", async () => {const flows = fakeFlows({runDeployFlow: vi.fn<TuiSetupFlows["runDeployFlow"]>(async () => {throw new HumanActionRequiredError({@@ -571,12 +572,12 @@ describe("runTuiSetupCommand", () => {}),});await expect(run({ command: "deploy", flows })).resolves.toEqual({- message: "You're not logged in to Vercel — run /login, then retry /deploy.",+ message: "You're not logged in to Vercel — run /vc:login, then retry /deploy.",preserveFlowDiagnostics: true,});});- it("routes a forbidden (SSO) scope error to /login with a re-auth message", async () => {+ it("routes a forbidden (SSO) scope error to /vc:login with a re-auth message", async () => {const flows = fakeFlows({runDeployFlow: vi.fn<TuiSetupFlows["runDeployFlow"]>(async () => {throw new HumanActionRequiredError({@@ -588,7 +589,7 @@ describe("runTuiSetupCommand", () => {});await expect(run({ command: "deploy", flows })).resolves.toEqual({message:- "Vercel denied access to that team — run /login to re-authenticate (for example to complete SSO), or pick a team you can access, then retry /deploy.",+ "Vercel denied access to that team — run /vc:login to re-authenticate (for example to complete SSO), or pick a team you can access, then retry /deploy.",preserveFlowDiagnostics: true,});});@@ -608,7 +609,7 @@ describe("runTuiSetupCommand", () => {});});- it("routes a missing-CLI action to the install command instead of /login", async () => {+ it("routes a missing-CLI action to the install command instead of /vc:login", async () => {const flows = fakeFlows({runDeployFlow: vi.fn<TuiSetupFlows["runDeployFlow"]>(async () => {throw new HumanActionRequiredError({@@ -619,7 +620,8 @@ describe("runTuiSetupCommand", () => {}),});await expect(run({ command: "deploy", flows })).resolves.toEqual({- message: "The Vercel CLI isn't installed — run /vc to install it, then retry /deploy.",+ message:+ "The Vercel CLI isn't installed — run /vc:install to install it, then retry /deploy.",preserveFlowDiagnostics: true,});});@@ -630,8 +632,8 @@ describe("runTuiSetupCommand", () => {kind: "installed",})),});- await expect(run({ command: "vc", flows })).resolves.toEqual({- message: "Installed the Vercel CLI. Run /login next.",+ await expect(run({ command: "vc:install", flows })).resolves.toEqual({+ message: "Installed the Vercel CLI. Run /vc:login next.",preserveFlowDiagnostics: false,effect: { kind: "refresh-identity" },});@@ -643,13 +645,13 @@ describe("runTuiSetupCommand", () => {kind: "already",})),});- await expect(run({ command: "vc", flows })).resolves.toEqual({+ await expect(run({ command: "vc:install", flows })).resolves.toEqual({message: "The Vercel CLI is already installed.",preserveFlowDiagnostics: false,});});- it("routes a /channels provisioning login error to /login (not the raw message)", async () => {+ it("routes a /channels provisioning login error to /vc:login (not the raw message)", async () => {// Provisioning throws before any channel lands, so the flow re-throws and// the command catch routes it — the same path /deploy uses.const flows = fakeFlows({@@ -662,12 +664,12 @@ describe("runTuiSetupCommand", () => {}),});await expect(run({ command: "channels", flows })).resolves.toEqual({- message: "You're not logged in to Vercel — run /login, then retry /channels.",+ message: "You're not logged in to Vercel — run /vc:login, then retry /channels.",preserveFlowDiagnostics: true,});});- it("routes a deploy-and-chat login action to /login while keeping channels added", async () => {+ it("routes a deploy-and-chat login action to /vc:login while keeping channels added", async () => {const flows = fakeFlows({runChannelsFlow: vi.fn<TuiSetupFlows["runChannelsFlow"]>(async () => ({kind: "deploy-and-chat",@@ -683,7 +685,8 @@ describe("runTuiSetupCommand", () => {}),});await expect(run({ command: "channels", flows })).resolves.toEqual({- message: "Channels added. You're not logged in to Vercel — run /login, then retry /deploy.",+ message:+ "Channels added. You're not logged in to Vercel — run /vc:login, then retry /deploy.",preserveFlowDiagnostics: true,effect: { kind: "channels-added" },});diff --git a/packages/eve/src/cli/dev/tui/setup-commands.ts b/packages/eve/src/cli/dev/tui/setup-commands.tsindex bd8d7c87f..c62c8d99f 100644--- a/packages/eve/src/cli/dev/tui/setup-commands.ts+++ b/packages/eve/src/cli/dev/tui/setup-commands.ts@@ -26,8 +26,8 @@ export type TuiSetupCommand = PromptCommandExtensionName;* move past their opening question.*/export const SETUP_FLOW_CONFIG = {- vc: { title: "Install the Vercel CLI", indicator: "spinner" },- login: { title: "Log in to Vercel", indicator: "spinner" },+ "vc:install": { title: "Install the Vercel CLI", indicator: "pulse" },+ "vc:login": { title: "Log in to Vercel", indicator: "pulse" },model: { title: "Configure the agent model", indicator: "pulse" },channels: { title: "Agent channels", indicator: "pulse" },deploy: { title: "Deploy to Vercel", indicator: "spinner" },@@ -164,12 +164,12 @@ async function executeSetupCommand(try {switch (command) {- case "vc": {+ case "vc:install": {return installVercelCliResultMessage(await flows.runInstallVercelCliFlow({ appRoot, prompter, signal }),);}- case "login": {+ case "vc:login": {return loginResultMessage(await flows.runLoginFlow({ appRoot, prompter, signal }));}case "model": {@@ -291,11 +291,11 @@ function vercelActionOutcome(error: unknown, command: string): TuiSetupCommandRefunction vercelActionMessage(kind: string, command: string): string | undefined {switch (kind) {case "vercel-login":- return `You're not logged in to Vercel — run /login, then retry /${command}.`;+ return `You're not logged in to Vercel — run /vc:login, then retry /${command}.`;case "vercel-forbidden":- return `Vercel denied access to that team — run /login to re-authenticate (for example to complete SSO), or pick a team you can access, then retry /${command}.`;+ return `Vercel denied access to that team — run /vc:login to re-authenticate (for example to complete SSO), or pick a team you can access, then retry /${command}.`;case "vercel-cli-missing":- return `The Vercel CLI isn't installed — run /vc to install it, then retry /${command}.`;+ return `The Vercel CLI isn't installed — run /vc:install to install it, then retry /${command}.`;default:return undefined;}@@ -359,7 +359,7 @@ async function runDeployAndChat(function installVercelCliResultMessage(result: InstallVercelCliResult): TuiSetupCommandResult {switch (result.kind) {case "cancelled":- return { message: "/vc cancelled.", preserveFlowDiagnostics: false };+ return { message: "/vc:install cancelled.", preserveFlowDiagnostics: false };case "already":return { message: "The Vercel CLI is already installed.", preserveFlowDiagnostics: false };case "failed":@@ -370,7 +370,7 @@ function installVercelCliResultMessage(result: InstallVercelCliResult): TuiSetup};case "installed":return {- message: "Installed the Vercel CLI. Run /login next.",+ message: "Installed the Vercel CLI. Run /vc:login next.",preserveFlowDiagnostics: false,// The CLI now resolves, so the status line's identity probe can run.effect: { kind: "refresh-identity" },@@ -382,17 +382,18 @@ function installVercelCliResultMessage(result: InstallVercelCliResult): TuiSetupfunction loginResultMessage(result: LoginFlowResult): TuiSetupCommandResult {switch (result.kind) {case "cancelled":- return { message: "/login cancelled.", preserveFlowDiagnostics: false };+ return { message: "/vc:login cancelled.", preserveFlowDiagnostics: false };case "already":return { message: "You're already logged in to Vercel.", preserveFlowDiagnostics: false };case "cli-missing":return {- message: "The Vercel CLI isn't installed — run /vc to install it, then retry /login.",+ message:+ "The Vercel CLI isn't installed — run /vc:install to install it, then retry /vc:login.",preserveFlowDiagnostics: true,};case "failed":return {- message: "Vercel login didn't complete — run /login to try again.",+ message: "Vercel login didn't complete — run /vc:login to try again.",preserveFlowDiagnostics: true,};case "logged-in":@@ -405,7 +406,7 @@ function loginResultMessage(result: LoginFlowResult): TuiSetupCommandResult {};case "unavailable":return {- message: "Couldn't reach Vercel — check your connection, then retry /login.",+ message: "Couldn't reach Vercel — check your connection, then retry /vc:login.",preserveFlowDiagnostics: true,};}diff --git a/packages/eve/src/cli/dev/tui/setup-issues.test.ts b/packages/eve/src/cli/dev/tui/setup-issues.test.tsindex 44323172c..6072c4fc7 100644--- a/packages/eve/src/cli/dev/tui/setup-issues.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-issues.test.ts@@ -184,13 +184,13 @@ describe("formatSetupIssuesLine", () => {// outside the cheap-and-local BOOT_DETECTIONS and is rendered by the runner.expect(BOOT_DETECTIONS.some((detection) => detection.id === "login")).toBe(false);expect(formatSetupIssuesLine([LOGIN_SETUP_ISSUE])).toBe(- "1 setup issue: not logged in · /login",+ "1 setup issue: not logged in · /vc:login",);});it("formats the CLI-missing hint, which points at its own fix command", () => {expect(formatSetupIssuesLine([CLI_MISSING_SETUP_ISSUE])).toBe(- "1 setup issue: Vercel CLI not found · /vc",+ "1 setup issue: Vercel CLI not found · /vc:install",);});});diff --git a/packages/eve/src/cli/dev/tui/setup-issues.ts b/packages/eve/src/cli/dev/tui/setup-issues.tsindex 56d8c4fcc..dc183a668 100644--- a/packages/eve/src/cli/dev/tui/setup-issues.ts+++ b/packages/eve/src/cli/dev/tui/setup-issues.ts@@ -169,19 +169,19 @@ export const BOOT_DETECTIONS: readonly BootDetection[] = [modelProvider];export const LOGIN_SETUP_ISSUE: SetupIssue = {kind: "attention",label: "not logged in",- command: "/login",+ command: "/vc:login",};/*** The CLI-missing hint, surfaced by the same off-critical-path probe as* {@link LOGIN_SETUP_ISSUE}. When the `vercel` binary is absent the probe* reports this instead of the login hint, so the diagnostic points at its fix- * command (`/vc`) rather than a logged-out state the probe can't determine.+ * command (`/vc:install`) rather than a logged-out state the probe can't determine.*/export const CLI_MISSING_SETUP_ISSUE: SetupIssue = {kind: "attention",label: "Vercel CLI not found",- command: "/vc",+ command: "/vc:install",};/**diff --git a/packages/eve/src/cli/dev/tui/status-line.test.ts b/packages/eve/src/cli/dev/tui/status-line.test.tsindex 2648cef87..b42bd75cb 100644--- a/packages/eve/src/cli/dev/tui/status-line.test.ts+++ b/packages/eve/src/cli/dev/tui/status-line.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";import { buildStatusLine } from "./status-line.js";import { stripAnsi, visibleLength } from "./terminal-text.js";import { createTheme } from "./theme.js";+import type { RemoteConnectionSnapshot } from "./remote-connection.js";const theme = createTheme();const plain = createTheme({ color: false });@@ -10,6 +11,30 @@ const ascii = createTheme({ color: false, unicode: false });const identity = { projectName: "my-agent", teamName: "acme" };const connected = { kind: "gateway", connected: true, credential: "oidc" } as const;+const remoteTarget = {+ kind: "remote",+ serverUrl: "https://vpoke.playground-vercel.tools",+ workspaceRoot: "/tmp/weather-agent",+} as const;++function remote(connection: RemoteConnectionSnapshot["connection"]): RemoteConnectionSnapshot {+ return { target: remoteTarget, connection };+}++function deployedRemote(+ connection: RemoteConnectionSnapshot["connection"],+): RemoteConnectionSnapshot {+ return {+ ...remote(connection),+ deployment: {+ provider: "vercel",+ ownerId: "team_acme",+ projectId: "prj_inbound",+ projectName: "inbound",+ environment: "production",+ },+ };+}describe("buildStatusLine", () => {it("renders all segments in order with dot separators", () => {@@ -27,6 +52,17 @@ describe("buildStatusLine", () => {);});+ it("strips terminal controls from a remote model id", () => {+ expect(+ buildStatusLine({+ model: "openai/gpt\x1b[31m-5\n",+ remote: remote({ state: "ready", info: {} as never }),+ theme: plain,+ width: 120,+ }),+ ).toBe(" ↗ vpoke.playground-vercel.tools · openai/gpt-5");+ });+it("dims every segment except the yellow pending-deploy marker", () => {const line = buildStatusLine({model: "anthropic/claude-sonnet-4-6",@@ -169,4 +205,143 @@ describe("buildStatusLine", () => {});expect(stripAnsi(line!)).toBe("m - ! AI Gateway");});++ it("renders the remote badge first and projects each authentication state", () => {+ expect(+ buildStatusLine({+ remote: remote({ state: "checking" }),+ theme: plain,+ width: 120,+ }),+ ).toBe(" ↗ vpoke.playground-vercel.tools · Checking access…");+ expect(+ buildStatusLine({+ remote: remote({+ state: "auth-required",+ challenge: { kind: "eve-oidc" },+ }),+ theme: plain,+ width: 120,+ }),+ ).toBe(" ↗ vpoke.playground-vercel.tools · Authenticate via OIDC");+ expect(+ buildStatusLine({+ remote: remote({+ state: "authenticating",+ challenge: { kind: "eve-oidc" },+ }),+ theme: plain,+ width: 120,+ }),+ ).toBe(" ↗ vpoke.playground-vercel.tools · Authenticating via OIDC…");+ expect(+ buildStatusLine({+ remote: remote({+ state: "auth-failed",+ challenge: { kind: "eve-oidc" },+ }),+ theme: plain,+ width: 120,+ }),+ ).toBe(" ↗ vpoke.playground-vercel.tools · Authentication failed");+ expect(+ buildStatusLine({+ remote: remote({+ state: "unavailable",+ failure: { message: "offline" },+ }),+ theme: plain,+ width: 120,+ }),+ ).toBe(" ↗ vpoke.playground-vercel.tools · Remote unavailable");+ expect(+ buildStatusLine({+ remote: deployedRemote({ state: "ready", info: {} as never }),+ theme: plain,+ width: 120,+ }),+ ).toBe(" ↗ inbound (production) ");+ });++ it("paints the remote badge from its connection state", () => {+ const disconnected = buildStatusLine({+ remote: remote({+ state: "unavailable",+ failure: { message: "offline" },+ }),+ theme,+ width: 120,+ })!;+ const notConnected = buildStatusLine({+ remote: remote({+ state: "auth-required",+ challenge: { kind: "eve-oidc" },+ }),+ theme,+ width: 120,+ })!;+ const connectedLine = buildStatusLine({+ remote: deployedRemote({ state: "ready", info: {} as never }),+ theme,+ width: 120,+ })!;++ expect(disconnected).toContain(+ "\x1b[7m\x1b[33m ↗ vpoke.playground-vercel.tools \x1b[39m\x1b[27m",+ );+ expect(notConnected).toContain(+ "\x1b[7m\x1b[33m ↗ vpoke.playground-vercel.tools \x1b[39m\x1b[27m",+ );+ expect(notConnected).not.toContain("\x1b[43m");+ expect(notConnected).not.toContain("/vc:auth");+ expect(connectedLine).toContain("\x1b[7m\x1b[34m ↗ inbound (production) \x1b[39m\x1b[27m");+ const badges = `${disconnected}${notConnected}${connectedLine}`;+ expect(badges).not.toContain("\x1b[44m");+ expect(badges).not.toContain("\x1b[100m");+ });++ it("omits endpoint status for a remote and preserves the badge as width narrows", () => {+ const line = buildStatusLine({+ remote: deployedRemote({ state: "ready", info: {} as never }),+ model: "openai/gpt-5.5",+ tokens: "↑ 200 ↓ 100",+ endpoint: { kind: "gateway", connected: false },+ theme,+ width: 120,+ })!;++ expect(stripAnsi(line)).not.toContain("AI Gateway");+ expect(+ stripAnsi(+ buildStatusLine({+ remote: deployedRemote({ state: "ready", info: {} as never }),+ model: "openai/gpt-5.5",+ tokens: "↑ 200 ↓ 100",+ theme: plain,+ width: 24,+ })!,+ ),+ ).toBe(" ↗ inbound (production) ");+ });++ it("closes the remote badge style when the narrowest variant is clipped", () => {+ const line = buildStatusLine({+ remote: deployedRemote({ state: "ready", info: {} as never }),+ theme,+ width: 8,+ });++ expect(line).toBeDefined();+ expect(line?.endsWith("\x1b[0m")).toBe(true);+ expect(stripAnsi(line ?? "")).toBe(" ↗ inbou");+ });++ it("uses the ASCII separator when unicode is unavailable", () => {+ const line = buildStatusLine({+ remote: remote({ state: "checking" }),+ theme: ascii,+ width: 120,+ });+ expect(line).toBe(" -> vpoke.playground-vercel.tools - Checking access…");+ });});diff --git a/packages/eve/src/cli/dev/tui/status-line.ts b/packages/eve/src/cli/dev/tui/status-line.tsindex 157f6bf90..b49c70c60 100644--- a/packages/eve/src/cli/dev/tui/status-line.ts+++ b/packages/eve/src/cli/dev/tui/status-line.ts@@ -1,6 +1,8 @@-import { sliceVisible, visibleLength } from "./terminal-text.js";+import { clipVisible, stripAnsi, visibleLength } from "./terminal-text.js";import type { Theme } from "./theme.js";import type { LogDisplayMode } from "./log-display-mode.js";+import type { RemoteConnectionSnapshot } from "./remote-connection.js";+import { remoteHost } from "./target.js";import type { VercelStatusSnapshot } from "./vercel-status.js";import type { ModelEndpointStatus } from "#shared/model-endpoint-status.js";@@ -20,67 +22,130 @@ export interface StatusLineInput {endpoint?: ModelEndpointStatus;/** Workspace-scoped Vercel state; identity absent while unlinked or still resolving. */vercel?: VercelStatusSnapshot;+ /** Remote server identity and its current connection/authentication state. */+ remote?: RemoteConnectionSnapshot;theme: Theme;width: number;}+function renderModel(+ input: Pick<StatusLineInput, "model" | "remote" | "theme">,+): string | undefined {+ if (input.model === undefined) return undefined;+ const model =+ input.remote === undefined ? input.model : stripAnsi(input.model).replace(/\s+/gu, " ").trim();+ return input.theme.colors.dim(model);+}++function renderEndpoint(+ input: Pick<StatusLineInput, "endpoint" | "remote" | "theme" | "vercel">,+): string | undefined {+ if (input.remote !== undefined || input.endpoint === undefined) return undefined;++ const c = input.theme.colors;+ if (input.endpoint.kind === "external") return c.dim("External endpoint");+ if (!input.endpoint.connected) return c.yellow(`${input.theme.glyph.warning} AI Gateway`);++ const projectName = input.vercel?.identity?.projectName;+ return c.dim(projectName === undefined ? "AI Gateway" : `AI Gateway (${projectName})`);+}+/**- * Builds the dev TUI's persistent one-row status line:- *- * `model · tokens · AI Gateway (project) · /deploy pending`- *- * The model-endpoint segment folds in the linked project name when connected- * (`AI Gateway (project)`), drops to a bare `AI Gateway` when connected without- * a linked project, and goes yellow with a `⚠` when the gateway has no usable- * credential. Everything else renders dim except the yellow action signals (a- * pending deploy, the not-connected gateway). On narrow widths segments degrade- * in order, the endpoint first and then the model, keeping tokens and the- * pending-deploy marker longest. A transient `logs: <mode>` segment from a- * Ctrl+L cycle leads the row when present and is kept longest of all. Segments- * stay recoverable from the agent header in scrollback. Returns undefined when- * no segment has content so callers skip the row.+ * Builds `↗ project (environment) · model · tokens · /deploy pending`.+ * Remote sessions omit endpoint state and keep their badge as the final+ * narrow-width fallback. Returns undefined when every segment is empty.*/export function buildStatusLine(input: StatusLineInput): string | undefined {const { theme, width } = input;const c = theme.colors;const logLevel = input.logLevel === undefined ? undefined : c.cyan(`logs: ${input.logLevel}`);- const model = input.model === undefined ? undefined : c.dim(input.model);+ const model = renderModel(input);const tokens = input.tokens === undefined ? undefined : c.dim(input.tokens);const pending = input.vercel?.pendingDeploy ? c.yellow("/deploy pending") : undefined;-- // The model-endpoint segment. Connected folds in the linked project name;- // not-connected is the one actionable signal, so it goes yellow with a ⚠.- const projectName = input.vercel?.identity?.projectName;- const endpoint =- input.endpoint === undefined- ? undefined- : input.endpoint.kind === "external"- ? c.dim("External endpoint")- : input.endpoint.connected- ? c.dim(projectName === undefined ? "AI Gateway" : `AI Gateway (${projectName})`)- : c.yellow(`${theme.glyph.warning} AI Gateway`);+ const remote = input.remote === undefined ? undefined : formatRemoteStatus(input.remote, theme);+ const endpoint = renderEndpoint(input);const separator = ` ${c.dim(theme.glyph.dot)} `;const compose = (segments: ReadonlyArray<string | undefined>): string =>segments.filter((segment) => segment !== undefined).join(separator);- // Descending fidelity; the first variant that fits wins. The transient- // logs hint leads every variant and gets a stand-alone fallback, so a- // Ctrl+L cycle is always visible even at a bare prompt or a narrow width.+ // Descending fidelity; the first variant that fits wins. The remote target+ // leads every variant and gets the final stand-alone fallback. Without a+ // remote, the logs hint retains its previous priority.const variants = [- compose([logLevel, model, tokens, endpoint, pending]),- compose([logLevel, model, tokens, pending]),- compose([logLevel, tokens, pending]),- compose([logLevel]),+ compose([remote?.full, logLevel, model, tokens, endpoint, pending]),+ compose([remote?.full, logLevel, model, tokens, pending]),+ compose([remote?.full, logLevel, tokens, pending]),+ compose([remote?.full, logLevel]),+ compose([remote?.badge, logLevel]),+ compose([remote?.badge]),];if (variants[0]!.length === 0) return undefined;for (const variant of variants) {if (variant.length > 0 && visibleLength(variant) <= width) return variant;}- // Nothing fits whole: clip the narrowest variant that still has content- // (later variants can be empty, e.g. a model-only line has no tokens row).+ // Later variants can be empty, for example when a model-only line has no tokens.const narrowest = variants.findLast((variant) => variant.length > 0)!;- return sliceVisible(narrowest, width);+ return clipVisible(narrowest, width);+}++function formatRemoteStatus(+ snapshot: RemoteConnectionSnapshot,+ theme: Theme,+): { readonly full: string; readonly badge: string } {+ const c = theme.colors;+ const label =+ snapshot.deployment === undefined+ ? remoteHost(snapshot.target)+ : `${snapshot.deployment.projectName} (${snapshot.deployment.environment})`;+ const arrow = theme.unicode ? "↗" : "->";+ const badge = formatRemoteBadge(` ${arrow} ${label} `, snapshot.connection.state, theme);+ const separator = ` ${c.dim(theme.glyph.dot)} `;+ let suffix: string | undefined;++ switch (snapshot.connection.state) {+ case "checking":+ suffix = c.dim("Checking access…");+ break;+ case "ready":+ break;+ case "auth-required":+ suffix = c.yellow("Authenticate via OIDC");+ break;+ case "authenticating":+ suffix = c.dim("Authenticating via OIDC…");+ break;+ case "auth-failed":+ suffix = c.yellow("Authentication failed");+ break;+ case "unavailable":+ suffix = c.yellow("Remote unavailable");+ break;+ }++ return {+ badge,+ full: suffix === undefined ? badge : `${badge}${separator}${suffix}`,+ };+}++function formatRemoteBadge(+ label: string,+ state: RemoteConnectionSnapshot["connection"]["state"],+ theme: Theme,+): string {+ const c = theme.colors;+ switch (state) {+ case "checking":+ return c.inverse(c.gray(label));+ case "ready":+ return c.inverse(c.blue(label));+ case "unavailable":+ case "auth-required":+ case "authenticating":+ case "auth-failed":+ return c.inverse(c.yellow(label));+ }}diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.tsindex ec898a0aa..6ad0d22cf 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts@@ -9,6 +9,7 @@ import {} from "#internal/nitro/host/dev-watcher-log.js";import type { AgentTUIStreamEvent, AgentTUIStreamResult } from "./runner.js";+import { promptCommandsFor } from "./prompt-commands.js";import { TerminalRenderer } from "./terminal-renderer.js";import { MockScreen, MockUserInput } from "./test/mock-terminal.js";@@ -675,7 +676,7 @@ describe("TerminalRenderer (inline scrollback)", () => {it("clears the setup attention line once its issue is resolved", () => {const { screen, renderer } = makeRenderer();- renderer.renderSetupWarning("1 setup issue: not logged in · /login");+ renderer.renderSetupWarning("1 setup issue: not logged in · /vc:login");expect(screen.snapshot()).toContain("not logged in");renderer.clearSetupWarning();@@ -691,6 +692,22 @@ describe("TerminalRenderer (inline scrollback)", () => {expect(screen.snapshot()).toContain("\u23bf /model cancelled.");});+ it("marks a failed automatic command and keeps its multiline outcome in one result block", () => {+ const { screen, renderer } = makeRenderer();+ renderer.renderCommandInvocation("/vc:auth", "failed");+ renderer.renderCommandResult(+ "Authentication was refreshed, but example.vercel.app is unavailable: Access denied.\n\n" ++ "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH",+ );+ renderer.shutdown();++ const snapshot = screen.snapshot();+ expect(snapshot).toContain("▌ ⨯ /vc:auth");+ expect(snapshot).toContain("⎿ Authentication was refreshed");+ expect(snapshot).toContain("TRUSTED_SOURCES_ENVIRONMENT_MISMATCH");+ expect(snapshot).not.toContain("· Authentication was refreshed");+ });+it("shows a bare prompt with no placeholder and accepts typing", async () => {const { screen, input, renderer } = makeRenderer();@@ -2548,6 +2565,48 @@ describe("TerminalRenderer command typeahead", () => {await answer;renderer.shutdown();});++ it("uses the target-specific command list for typeahead", async () => {+ const screen = new MockScreen({ columns: 80, rows: 30 });+ const input = new MockUserInput();+ const renderer = new TerminalRenderer({+ input,+ output: screen,+ captureForeignOutput: false,+ unicode: true,+ availablePromptCommands: promptCommandsFor("remote"),+ });++ const prompt = renderer.readPrompt();+ input.type("/");+ const snapshot = screen.snapshot();+ expect(snapshot).toContain("Authenticate this remote via Vercel OIDC");+ expect(snapshot).not.toContain("Configure the agent's model and provider");+ input.enter();+ await prompt;+ renderer.shutdown();+ });++ it("echoes a known unavailable command as a command, not chat", async () => {+ const screen = new MockScreen({ columns: 80, rows: 30 });+ const input = new MockUserInput();+ const renderer = new TerminalRenderer({+ input,+ output: screen,+ captureForeignOutput: false,+ unicode: true,+ availablePromptCommands: promptCommandsFor("remote"),+ });++ const prompt = renderer.readPrompt();+ input.type("/model");+ input.enter();++ await expect(prompt).resolves.toBe("/model");+ renderer.shutdown();+ expect(screen.snapshot()).toContain("▌ /model");+ expect(screen.snapshot()).not.toContain("❯ /model");+ });});describe("TerminalRenderer status line", () => {@@ -2632,6 +2691,49 @@ describe("TerminalRenderer status line", () => {renderer.shutdown();});+ it("lays out the remote authentication panel and inset status line", async () => {+ const { screen, input, renderer } = makeRenderer(100, 40);+ renderer.renderNotice("anchor");+ renderer.setRemoteConnectionStatus({+ target: {+ kind: "remote",+ serverUrl: "https://vpoke.playground-vercel.tools",+ workspaceRoot: "/tmp/weather-agent",+ },+ connection: {+ state: "authenticating",+ challenge: { kind: "eve-oidc" },+ },+ });++ renderer.setupFlow.begin("Authenticate via Vercel OIDC");+ const answer = renderer.setupFlow.readSelect({+ kind: "search",+ message: "Select your team",+ placeholder: "type to search teams",+ options: [+ { value: "vercel", label: "Vercel" },+ { value: "labs", label: "Vercel Labs" },+ ],+ });++ const lines = screen.snapshot().split("\n");+ const title = lines.indexOf(" Authenticate via Vercel OIDC");+ expect(lines.slice(title, title + 3)).toEqual([+ " Authenticate via Vercel OIDC",+ "",+ " Select your team",+ ]);+ const status = lines.indexOf(" ↗ vpoke.playground-vercel.tools · Authenticating via OIDC…");+ expect(status).toBeGreaterThan(title);+ expect(lines[status - 1]).toBe("");++ input.send("\x1b");+ await expect(answer).resolves.toBeUndefined();+ renderer.setupFlow.end({ preserveDiagnostics: false });+ renderer.shutdown();+ });+it("keeps the running token total after the turn indicator disappears", async () => {const { screen, renderer } = makeRenderer();await renderer.renderStream(diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.tsindex e9bdc8dda..b045f3900 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts@@ -27,7 +27,12 @@ import {typeaheadFor,type CommandTypeaheadState,} from "./command-typeahead.js";-import { isPromptControlCommand, parsePromptCommand, PROMPT_COMMANDS } from "./prompt-commands.js";+import {+ isPromptControlCommand,+ parsePromptCommand,+ PROMPT_COMMANDS,+ type PromptCommandSpec,+} from "./prompt-commands.js";import {renderFlowPanel,renderAcknowledgeQuestion,@@ -103,6 +108,7 @@ import {stripTerminalControls,} from "./terminal-text.js";import type { VercelStatusSnapshot } from "./vercel-status.js";+import type { RemoteConnectionSnapshot } from "./remote-connection.js";import { summarizeToolArgs, summarizeToolResult } from "./tool-format.js";import { reduceSetupSelectInput, setupSelectionIntent } from "./setup-selection-input.js";import {@@ -199,6 +205,7 @@ type SetupFlowState = {* a `vercel deploy` build error) survives the settle.*/const FLOW_OUTPUT_BUFFER_CAP = 40;+const STATUS_LINE_LEFT_PADDING = " ";const defaultAssistantResponseStats: AssistantResponseStatsMode = "tokensPerSecond";@@ -215,6 +222,8 @@ export type TerminalRendererOptions = {logs?: LogDisplayMode;color?: boolean;unicode?: boolean;+ /** Slash commands available in this local or remote session. */+ availablePromptCommands?: readonly PromptCommandSpec[];};export type AgentHeaderOptions = {@@ -282,6 +291,7 @@ export class TerminalRenderer implements AgentTUIRenderer {readonly #assistantResponseStats: AssistantResponseStatsMode;readonly #defaultContextSize?: number;readonly #captureForeignOutput: boolean;+ readonly #availablePromptCommands: readonly PromptCommandSpec[];/** Which captured log sources render. Mutable via {@link setLogDisplayMode}. */#logs: LogDisplayMode;@@ -324,6 +334,8 @@ export class TerminalRenderer implements AgentTUIRenderer {#connectionAuthPendingCount = 0;/** Vercel segment of the bottom status line; pushed by the runner. */#vercelStatus?: VercelStatusSnapshot;+ /** Remote target and connection/authentication state; pushed by the runner. */+ #remoteConnection?: RemoteConnectionSnapshot;#inputText = "";#inputCursor = 0;readonly #promptHistory = new PromptHistory();@@ -383,7 +395,7 @@ export class TerminalRenderer implements AgentTUIRenderer {#pendingEchoedPrompt?: string;/** The active setup flow's bordered panel: progress, question, status. */#setupFlow?: SetupFlowState;- /** The clearable setup attention line (`⚠ … · /login`), rendered in the live footer. */+ /** The clearable setup attention line (`⚠ … · /vc:login`), rendered in the live footer. */#setupAttention?: string;/** Armed by {@link SetupFlowRenderer.waitForInterrupt}; fired by the idle key trap. */#flowInterrupt?: () => void;@@ -425,6 +437,7 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#contextSize = options?.contextSize;this.#captureForeignOutput = options?.captureForeignOutput ?? this.#output === process.stdout;this.#logs = options?.logs ?? "none";+ this.#availablePromptCommands = options?.availablePromptCommands ?? PROMPT_COMMANDS;}/**@@ -466,7 +479,7 @@ export class TerminalRenderer implements AgentTUIRenderer {let editor: LineState = lineOf(stripPromptControlCharacters(options?.initialDraft ?? ""));this.#promptHistory.begin(editor.text);this.#syncInput(editor);- this.#typeahead = typeaheadFor(PROMPT_COMMANDS, editor.text);+ this.#typeahead = typeaheadFor(this.#availablePromptCommands, editor.text);this.#startCaretBlink();this.#paint();@@ -475,7 +488,7 @@ export class TerminalRenderer implements AgentTUIRenderer {editor = next;this.#showCaret();this.#syncInput(editor);- this.#typeahead = typeaheadFor(PROMPT_COMMANDS, next.text, this.#typeahead);+ this.#typeahead = typeaheadFor(this.#availablePromptCommands, next.text, this.#typeahead);this.#paint();};const recall = (entry: string | undefined) => {@@ -1031,6 +1044,11 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#paint();}+ setRemoteConnectionStatus(status: RemoteConnectionSnapshot): void {+ this.#remoteConnection = status;+ this.#paint();+ }+reset(): void {this.#blocks = [];this.#blockById.clear();@@ -1087,7 +1105,7 @@ export class TerminalRenderer implements AgentTUIRenderer {/*** Sets the setup attention line (yellow `⚠`, commands blue) as a live footer* element above the prompt. Unlike committed scrollback, it can be cleared:- * once the underlying issue is fixed (e.g. `/login` succeeds) the runner calls+ * once the underlying issue is fixed (e.g. `/vc:login` succeeds) the runner calls* {@link clearSetupWarning} and the line disappears rather than lingering* stale in the transcript.*/@@ -1113,6 +1131,21 @@ export class TerminalRenderer implements AgentTUIRenderer {this.#paint();}+ /** Commits a slash-command invocation that was started without prompt input. */+ renderCommandInvocation(text: string, status?: "failed"): void {+ const content = stripTerminalControls(text);+ if (content.trim().length === 0) return;+ this.#start();+ const block: Block = {+ kind: "command",+ body: content,+ live: false,+ };+ if (status === "failed") block.status = "error";+ this.#pushBlock(block);+ this.#paint();+ }+/*** Commits one command's outcome under its invocation with the elbow* connector (` ⎿ /model cancelled.`), Claude Code's sub-result grammar.@@ -2694,6 +2727,7 @@ export class TerminalRenderer implements AgentTUIRenderer {content,};rows.push(...renderFlowPanel(state, this.#theme, width));+ this.#pushRemoteStatusLine(rows, width);return rows;}@@ -2778,7 +2812,12 @@ export class TerminalRenderer implements AgentTUIRenderer {* pending deploy) when any segment has content.*/#pushStatusLine(rows: string[], width: number): void {- const input: Parameters<typeof buildStatusLine>[0] = { theme: this.#theme, width };+ const padding = this.#remoteConnection === undefined ? "" : STATUS_LINE_LEFT_PADDING;+ const contentWidth = Math.max(1, width - padding.length);+ const input: Parameters<typeof buildStatusLine>[0] = {+ theme: this.#theme,+ width: contentWidth,+ };if (this.#logLevelHintActive) input.logLevel = this.#logs;const model = this.#agentHeader?.info?.agent.model.id;if (model !== undefined) input.model = model;@@ -2796,8 +2835,22 @@ export class TerminalRenderer implements AgentTUIRenderer {input.tokens = formatTokenFlow(flow, this.#theme.glyph);}if (this.#vercelStatus !== undefined) input.vercel = this.#vercelStatus;+ if (this.#remoteConnection !== undefined) input.remote = this.#remoteConnection;const line = buildStatusLine(input);- if (line !== undefined) rows.push(line);+ if (line !== undefined) rows.push(clip(`${padding}${line}`, width));+ }++ #pushRemoteStatusLine(rows: string[], width: number): void {+ if (this.#remoteConnection === undefined) return;+ const contentWidth = Math.max(1, width - STATUS_LINE_LEFT_PADDING.length);+ const line = buildStatusLine({+ remote: this.#remoteConnection,+ theme: this.#theme,+ width: contentWidth,+ });+ if (line !== undefined) {+ rows.push("", clip(`${STATUS_LINE_LEFT_PADDING}${line}`, width));+ }}#statusMeta(): string {diff --git a/packages/eve/src/cli/dev/tui/test/index.ts b/packages/eve/src/cli/dev/tui/test/index.tsindex 7ae4efcd3..d719fa331 100644--- a/packages/eve/src/cli/dev/tui/test/index.ts+++ b/packages/eve/src/cli/dev/tui/test/index.ts@@ -8,6 +8,7 @@export { EveTUIRunner } from "../runner.js";export type { EveTUIRunnerOptions } from "../runner.js";export { createPromptCommandHandler } from "../prompt-command-handler.js";+export { promptCommandsFor } from "../prompt-commands.js";export { TerminalRenderer } from "../terminal-renderer.js";export { MockScreen, MockUserInput } from "./mock-terminal.js";// The dev watcher's real log-line formatter, so smoke tests can drive thediff --git a/packages/eve/src/cli/dev/tui/tui.ts b/packages/eve/src/cli/dev/tui/tui.tsindex 991423fde..6e21882ce 100644--- a/packages/eve/src/cli/dev/tui/tui.ts+++ b/packages/eve/src/cli/dev/tui/tui.ts@@ -1,19 +1,20 @@import { Client } from "#client/index.js";-import { resolveDevelopmentClientOptions } from "#services/dev-client/client-options.js";-import {- resolveVerifiedRemoteDevelopmentClient,- type VerifiedRemoteDevelopmentClient,-} from "#setup/verified-remote-client.js";+import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";import {- formatVercelAuthChallengeMessage,- isVercelAuthChallenge,-} from "#services/dev-client/vercel-auth-error.js";+ resolveDevelopmentClientOptions,+ 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 { isVercelAuthChallenge } from "#services/dev-client/vercel-auth-error.js";+import { resolveVercelDeployment } from "#setup/vercel-deployment.js";import { toErrorMessage } from "#shared/errors.js";-import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";import { createPromptCommandHandler } from "./prompt-command-handler.js";+import { promptCommandsFor } from "./prompt-commands.js";+import { formatRemoteAuthChallengeMessage } from "./remote-auth-result.js";import { EveTUIRunner, type EveTUIRunnerOptions } from "./runner.js";-import type { DevelopmentTuiTarget } from "./target.js";+import { remoteHost, type DevelopmentTuiTarget, type RemoteDevelopmentTarget } from "./target.js";import type { TuiDisplayOptions } from "./types.js";export type { DevelopmentTuiTarget } from "./target.js";@@ -31,20 +32,36 @@ export interface RunDevelopmentTuiInput extends TuiDisplayOptions {readonly onBootProgress?: DevBootProgressReporter;}-async function resolveClientOptions(- target: DevelopmentTuiTarget,-): Promise<VerifiedRemoteDevelopmentClient> {- if (target.kind === "local") {- return {- options: resolveDevelopmentClientOptions(target.serverUrl),- lastOidcTokenFailure: () => undefined,+function prepareRemoteTarget(target: RemoteDevelopmentTarget) {+ const credentials = createDevelopmentCredentialGate(target.serverUrl);+ return {+ target,+ credentials,+ resolveOidcToken: resolveDevelopmentOidcToken,+ resolveDeployment: (signal: AbortSignal) =>+ resolveVercelDeployment({+ workspaceRoot: target.workspaceRoot,+ host: remoteHost(target),+ signal,+ }),+ } satisfies NonNullable<EveTUIRunnerOptions["remote"]>;+}++type PreparedDevelopmentTuiTarget =+ | {+ readonly kind: "local";+ readonly target: Extract<DevelopmentTuiTarget, { kind: "local" }>;+ }+ | {+ readonly kind: "remote";+ readonly target: RemoteDevelopmentTarget;+ readonly remote: NonNullable<EveTUIRunnerOptions["remote"]>;};- }- return await resolveVerifiedRemoteDevelopmentClient({- serverUrl: target.serverUrl,- workspaceRoot: target.workspaceRoot,- });+function prepareDevelopmentTarget(target: DevelopmentTuiTarget): PreparedDevelopmentTuiTarget {+ return target.kind === "local"+ ? { kind: "local", target }+ : { kind: "remote", target, remote: prepareRemoteTarget(target) };}/**@@ -58,25 +75,35 @@ async function resolveClientOptions(*/export async function runDevelopmentTui(input: RunDevelopmentTuiInput): Promise<void> {const { target, initialInput, onBootProgress, ...display } = input;+ const prepared = prepareDevelopmentTarget(target);const { serverUrl } = target;- const { options: clientOptions, lastOidcTokenFailure } = await resolveClientOptions(target);- const client = new Client(clientOptions);+ const client = new Client(+ prepared.kind === "local"+ ? resolveDevelopmentClientOptions(serverUrl)+ : resolveRemoteDevelopmentClientOptions({+ serverUrl,+ credentials: prepared.remote.credentials,+ }),+ );const options: EveTUIRunnerOptions = {...display,session: client.session(),client,serverUrl,- promptCommandHandler: createPromptCommandHandler(- target.kind === "local" ? { appRoot: target.workspaceRoot } : {},- ),+ promptCommandHandler: createPromptCommandHandler({ target }),+ availablePromptCommands: promptCommandsFor(target.kind),formatTransportError: (error) =>isVercelAuthChallenge(error)- ? formatVercelAuthChallengeMessage({ serverUrl, oidcTokenFailure: lastOidcTokenFailure() })+ ? formatRemoteAuthChallengeMessage(serverUrl): toErrorMessage(error),};- if (target.kind === "local") options.appRoot = target.workspaceRoot;+ if (prepared.kind === "local") {+ options.appRoot = prepared.target.workspaceRoot;+ } else {+ options.remote = prepared.remote;+ }if (initialInput !== undefined) options.initialInput = initialInput;if (onBootProgress !== undefined) options.onBootProgress = onBootProgress;diff --git a/packages/eve/src/cli/run.ts b/packages/eve/src/cli/run.tsindex 4d4d6b0f9..5cf53e378 100644--- a/packages/eve/src/cli/run.ts+++ b/packages/eve/src/cli/run.ts@@ -514,13 +514,7 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm};if (remoteServerUrl) {- logger.log(- renderCliTaggedLine(theme, {- message: `connecting to ${remoteServerUrl}`,- tag: "dev",- tone: "info",- }),- );+ logger.log(`↗ remote mode targeting ${theme.info(new URL(remoteServerUrl).host)}`);if (mode === "headless") {logger.log(diff --git a/packages/eve/src/client/agent-info-error.ts b/packages/eve/src/client/agent-info-error.tsnew file mode 100644index 000000000..550afd25a--- /dev/null+++ b/packages/eve/src/client/agent-info-error.ts@@ -0,0 +1,23 @@+/**+ * Error thrown when the agent info route returns an authorized response whose+ * body is not a recognized agent-info payload.+ *+ * Distinct from {@link ClientError}: the request succeeded and authorization+ * was satisfied, but the inspection payload is unusable — a body that is not+ * JSON, or JSON that does not match the current schema (typically a version+ * skew between the deployment and this client). The conversation transport does+ * not depend on `/eve/v1/info`, so callers that only need a working connection+ * can treat this as "connected, no inspection data". The carried {@link issues}+ * let diagnostics name the offending fields instead of an opaque string.+ */+export class AgentInfoResponseError extends Error {+ /** Schema issue summaries, e.g. `"agent.model.id: Required"`. Empty when the body was not JSON. */+ readonly issues: readonly string[];++ constructor(issues: readonly string[] = []) {+ const detail = issues.length === 0 ? "" : ` (${issues.join("; ")})`;+ super(`The server returned an unrecognized response from the eve agent info route.${detail}`);+ this.name = "AgentInfoResponseError";+ this.issues = issues;+ }+}diff --git a/packages/eve/src/client/client.test.ts b/packages/eve/src/client/client.test.tsindex d1d25db9d..baf602b31 100644--- a/packages/eve/src/client/client.test.ts+++ b/packages/eve/src/client/client.test.ts@@ -1,5 +1,6 @@import { afterEach, describe, expect, it, vi } from "vitest";+import { AgentInfoResponseError } from "#client/agent-info-error.js";import { Client } from "#client/client.js";import type { AgentInfoResult } from "#client/types.js";import { resolveTestVercelTarget } from "#internal/testing/verified-vercel-target.js";@@ -161,7 +162,7 @@ describe("Client request policy", () => {);const client = new Client({ host: "https://eve.test" });- await expect(client.info()).rejects.toThrow(SyntaxError);+ await expect(client.info()).rejects.toThrow(AgentInfoResponseError);});it("rejects an incomplete agent info payload", async () => {@@ -175,7 +176,34 @@ describe("Client request policy", () => {);const client = new Client({ host: "https://eve.test" });- await expect(client.info()).rejects.toThrow(SyntaxError);+ await expect(client.info()).rejects.toThrow(AgentInfoResponseError);+ });++ it("names the offending fields when the agent info payload is incomplete", async () => {+ vi.spyOn(globalThis, "fetch").mockResolvedValue(+ Response.json({+ agent: { model: { id: "openai/gpt-5.5" } },+ diagnostics: { discoveryErrors: 0, discoveryWarnings: 0 },+ kind: "eve-agent-info",+ version: 1,+ }),+ );+ const client = new Client({ host: "https://eve.test" });++ const error = await client.info().catch((cause: unknown) => cause);++ expect(error).toBeInstanceOf(AgentInfoResponseError);+ expect((error as AgentInfoResponseError).issues.length).toBeGreaterThan(0);+ expect((error as AgentInfoResponseError).message).toContain(":");+ });++ it("rejects a non-JSON body from the agent info route", async () => {+ vi.spyOn(globalThis, "fetch").mockResolvedValue(+ new Response("<!doctype html>", { headers: { "content-type": "text/html" } }),+ );+ const client = new Client({ host: "https://eve.test" });++ await expect(client.info()).rejects.toThrow(AgentInfoResponseError);});it.each([null, { kind: "gateway", connected: true }, { kind: "external" }])(@@ -192,7 +220,7 @@ describe("Client request policy", () => {);const client = new Client({ host: "https://eve.test" });- await expect(client.info()).rejects.toThrow(SyntaxError);+ await expect(client.info()).rejects.toThrow(AgentInfoResponseError);},);});diff --git a/packages/eve/src/client/client.ts b/packages/eve/src/client/client.tsindex e4a5642bc..605430386 100644--- a/packages/eve/src/client/client.ts+++ b/packages/eve/src/client/client.ts@@ -1,4 +1,5 @@import { EVE_HEALTH_ROUTE_PATH, EVE_INFO_ROUTE_PATH } from "#protocol/routes.js";+import { AgentInfoResponseError } from "#client/agent-info-error.js";import { AgentInfoResultSchema } from "#client/agent-info-schema.js";import { ClientError } from "#client/client-error.js";import { ClientSession } from "#client/session.js";@@ -66,6 +67,10 @@ export class Client {* OIDC outside local development.** @throws {ClientError} If the server returns a non-successful status.+ * @throws {AgentInfoResponseError} If an authorized response carries a body+ * that is not a recognized agent-info payload (not JSON, or a mismatched+ * shape). Inspection is best-effort: a working connection does not depend on+ * this route, so connection probes treat this distinctly from a failed request.*/async info(): Promise<AgentInfoResult> {const response = await this.fetch(EVE_INFO_ROUTE_PATH);@@ -75,10 +80,20 @@ export class Client {throw new ClientError(response.status, body);}- const result = AgentInfoResultSchema.safeParse(await response.json());+ let payload: unknown;+ try {+ payload = await response.json();+ } catch {+ throw new AgentInfoResponseError();+ }++ const result = AgentInfoResultSchema.safeParse(payload);if (!result.success) {- throw new SyntaxError(- "The server returned an unrecognized response from the Eve agent info route.",+ throw new AgentInfoResponseError(+ result.error.issues.slice(0, 5).map((issue) => {+ const path = issue.path.join(".");+ return path.length === 0 ? issue.message : `${path}: ${issue.message}`;+ }),);}diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.tsindex 7e74162f8..50502553e 100644--- a/packages/eve/src/client/index.ts+++ b/packages/eve/src/client/index.ts@@ -4,6 +4,7 @@export { EveAgentStore } from "#client/eve-agent-store.js";export { Client } from "#client/client.js";+export { AgentInfoResponseError } from "#client/agent-info-error.js";export { ClientError } from "#client/client-error.js";export { defaultMessageReducer } from "#client/message-reducer.js";export { createDataUrlFilePart, createTextWithFileContent } from "#client/file-parts.js";diff --git a/packages/eve/src/internal/testing/verified-vercel-target.ts b/packages/eve/src/internal/testing/verified-vercel-target.tsindex 22c4726a0..ab62b128b 100644--- a/packages/eve/src/internal/testing/verified-vercel-target.ts+++ b/packages/eve/src/internal/testing/verified-vercel-target.ts@@ -4,6 +4,7 @@ import { resolveVercelDeployment, type VerifiedVercelTarget } from "#setup/verceexport async function resolveTestVercelTarget(input: {readonly host: string;readonly projectId?: string;+ readonly ownerId?: string;readonly projectName?: string;readonly environment?: "preview" | "production";}): Promise<VerifiedVercelTarget> {@@ -12,13 +13,14 @@ export async function resolveTestVercelTarget(input: {workspaceRoot: "/test-workspace",host: input.host,source: {- orgId: "team_test",+ orgId: input.ownerId ?? "team_test",projectId: input.projectId ?? "prj_test",},deps: {captureVercel: async () => ({ok: true,stdout: JSON.stringify({+ ownerId: input.ownerId ?? "team_test",projectId: input.projectId ?? "prj_test",name: input.projectName ?? "test-project",target: environment,diff --git a/packages/eve/src/services/dev-client/request-headers.test.ts b/packages/eve/src/services/dev-client/request-headers.test.tsindex b651e1526..7412c320b 100644--- a/packages/eve/src/services/dev-client/request-headers.test.ts+++ b/packages/eve/src/services/dev-client/request-headers.test.ts@@ -33,6 +33,21 @@ describe("resolveDevelopmentOidcToken", () => {});});+ it("forces a refresh for an explicitly selected project", async () => {+ const expected = token({ owner_id: target.ownerId, project_id: target.projectId });+ vi.mocked(getVercelOidcToken).mockResolvedValue(expected);++ await expect(resolveDevelopmentOidcToken({ ...target, forceRefresh: true })).resolves.toEqual({+ kind: "resolved",+ token: expected,+ });+ expect(getVercelOidcToken).toHaveBeenCalledWith({+ team: target.ownerId,+ project: target.projectId,+ expirationBufferMs: Number.MAX_SAFE_INTEGER,+ });+ });+it("reports a token minted for a different project", async () => {vi.mocked(getVercelOidcToken).mockResolvedValue(token({ owner_id: target.ownerId, project_id: "prj_other" }),diff --git a/packages/eve/src/services/dev-client/request-headers.ts b/packages/eve/src/services/dev-client/request-headers.tsindex 034363ab1..fef4fc9f9 100644--- a/packages/eve/src/services/dev-client/request-headers.ts+++ b/packages/eve/src/services/dev-client/request-headers.ts@@ -11,6 +11,8 @@ const VercelOidcClaimsSchema = z.object({export interface DevelopmentOidcTarget {readonly ownerId: string;readonly projectId: string;+ /** Ignore an ambient token and ask Vercel for this exact project. */+ readonly forceRefresh?: boolean;}type VercelOidcClaimName = keyof z.infer<typeof VercelOidcClaimsSchema>;@@ -46,9 +48,12 @@ export async function resolveDevelopmentOidcToken(input: DevelopmentOidcTarget,): Promise<DevelopmentOidcTokenResolution> {try {- const token = (- await getVercelOidcToken({ team: input.ownerId, project: input.projectId })- ).trim();+ const options: NonNullable<Parameters<typeof getVercelOidcToken>[0]> = {+ team: input.ownerId,+ project: input.projectId,+ };+ if (input.forceRefresh === true) options.expirationBufferMs = Number.MAX_SAFE_INTEGER;+ const token = (await getVercelOidcToken(options)).trim();return validateDevelopmentOidcToken(token, input);} catch (error) {return { kind: "resolution-failed", message: toErrorMessage(error) };diff --git a/packages/eve/src/services/dev-client/vercel-auth-error.test.ts b/packages/eve/src/services/dev-client/vercel-auth-error.test.tsindex 444c992ec..8f4391f40 100644--- a/packages/eve/src/services/dev-client/vercel-auth-error.test.ts+++ b/packages/eve/src/services/dev-client/vercel-auth-error.test.ts@@ -4,6 +4,7 @@ import { ClientError } from "#client/client-error.js";import {formatVercelAuthChallengeMessage,isVercelAuthChallenge,+ vercelTrustedSourcesErrorCode,} from "#services/dev-client/vercel-auth-error.js";/**@@ -66,27 +67,21 @@ describe("isVercelAuthChallenge", () => {});});-describe("formatVercelAuthChallengeMessage", () => {- it("renders the target URL and the supported escape hatches", () => {- const message = formatVercelAuthChallengeMessage({- serverUrl: "https://example.vercel.app",- });-- expect(message).toContain("https://example.vercel.app");- expect(message).toContain("VERCEL_AUTOMATION_BYPASS_SECRET");- expect(message).toContain("Disable Deployment Protection");- // Documentation pointer keeps the message actionable when neither- // escape hatch fits the user's setup.- expect(message).toContain("https://vercel.com/docs/deployment-protection");+describe("vercelTrustedSourcesErrorCode", () => {+ it("extracts the stable code without retaining the request id", () => {+ expect(+ vercelTrustedSourcesErrorCode(+ [+ "The caller environment is not permitted.",+ "TRUSTED_SOURCES_ENVIRONMENT_MISMATCH",+ "iad1::request-id",+ ].join("\n\n"),+ ),+ ).toBe("TRUSTED_SOURCES_ENVIRONMENT_MISMATCH");});- it("does not include the raw HTML challenge body", () => {- const message = formatVercelAuthChallengeMessage({- serverUrl: "https://example.vercel.app",- });-- expect(message).not.toContain("<");- expect(message).not.toContain("doctype");+ it("returns undefined for an unrelated error", () => {+ expect(vercelTrustedSourcesErrorCode("Unavailable")).toBeUndefined();});it("includes invalid local OIDC claims in the repair context", () => {diff --git a/packages/eve/src/services/dev-client/vercel-auth-error.ts b/packages/eve/src/services/dev-client/vercel-auth-error.tsindex 4c8fb3e28..7d9fda7b2 100644--- a/packages/eve/src/services/dev-client/vercel-auth-error.ts+++ b/packages/eve/src/services/dev-client/vercel-auth-error.ts@@ -23,40 +23,37 @@ import { isObject } from "#shared/guards.js";* SSO challenge page. The page is generated server-side by Vercel and* its markup includes a stable `<title>` plus the SSO redirect URL.*- * Substring matching (rather than parsing the HTML) is intentional:- * the page changes shape over time but these tokens have remained- * stable, and a forgiving matcher keeps `eve dev` resilient when- * minor markup tweaks ship.+ * Both markers are required. Substring matching avoids coupling the CLI to the+ * page's DOM structure while keeping a generic error page out of the auth flow.*/const VERCEL_AUTH_CHALLENGE_MARKERS: readonly string[] = ["vercel.com/sso-api","<title>Authentication Required</title>",- "Vercel Authentication",];-/**- * Heuristic: returns `true` when the response body looks like a- * Vercel Deployment Protection SSO challenge.- *- * Matching is substring-based against {@link VERCEL_AUTH_CHALLENGE_MARKERS}- * so the CLI keeps degrading gracefully when Vercel tweaks the page.- */+const TRUSTED_SOURCES_ERROR_CODE = /^TRUSTED_SOURCES_[A-Z0-9_]+$/u;++/** Returns the stable Trusted Sources code embedded in a Vercel error message. */+export function vercelTrustedSourcesErrorCode(message: string): string | undefined {+ for (const line of message.replaceAll("\r\n", "\n").trim().split("\n")) {+ const candidate = line.trim();+ if (TRUSTED_SOURCES_ERROR_CODE.test(candidate)) return candidate;+ }+ return undefined;+}++/** Returns whether the body carries the complete Vercel SSO challenge signature. */function bodyLooksLikeVercelAuthChallenge(body: string): boolean {return body.length > 0 && VERCEL_AUTH_CHALLENGE_MARKERS.every((marker) => body.includes(marker));}/**- * Returns `true` when the thrown error is the Vercel Deployment- * Protection SSO challenge.+ * Returns `true` for an HTTP 401 carrying Vercel's protection challenge.** Accepts both real {@link ClientError} instances and structurally* compatible duck-typed errors (`{ status: number, body: string }`)* so callers can detect the challenge regardless of whether the* error survived a network/IPC boundary.- *- * Exported so the dev REPL and other dev-client consumers can render- * a focused authentication directive instead of dumping the SSO- * challenge HTML to the terminal.*/export function isVercelAuthChallenge(error: unknown): boolean {if (error instanceof ClientError) {@@ -72,14 +69,8 @@ export function isVercelAuthChallenge(error: unknown): boolean {}/**- * Builds the human-readable message rendered when- * {@link isVercelAuthChallenge} returns `true`.- *- * The message states the cause, the target URL, and the supported escape- * hatches (link the project so an OIDC token can be minted, set an- * automation bypass token, or disable protection). It is intentionally- * short — multi-line CLI output is harder to scan than a focused- * directive.+ * Builds the human-readable repair message for the existing dev-client+ * challenge surface, including a structured local OIDC failure when known.*/export function formatVercelAuthChallengeMessage(input: {readonly serverUrl: string;@@ -87,7 +78,7 @@ export function formatVercelAuthChallengeMessage(input: {}): string {const lines = [`Vercel Deployment Protection blocked the request to ${input.serverUrl}.`];if (input.oidcTokenFailure !== undefined) {- lines.push("", formatOidcTokenFailure(input.oidcTokenFailure));+ lines.push("", formatDevelopmentOidcTokenFailure(input.oidcTokenFailure));}lines.push("",@@ -103,7 +94,7 @@ export function formatVercelAuthChallengeMessage(input: {return lines.join("\n");}-function formatOidcTokenFailure(failure: DevelopmentOidcTokenFailure): string {+export function formatDevelopmentOidcTokenFailure(failure: DevelopmentOidcTokenFailure): string {switch (failure.kind) {case "resolution-failed":return `The local Vercel OIDC token could not be resolved: ${failure.message}`;@@ -121,3 +112,19 @@ function formatOidcTokenFailure(failure: DevelopmentOidcTokenFailure): string {}}}++/**+ * Keeps the actionable Trusted Sources reason and stable error code while+ * dropping Vercel's per-request id. The id is useful in platform logs but is+ * noise in a command result and changes on every retry.+ */+export function formatVercelTrustedSourcesFailure(message: string): string {+ const lines = message.replaceAll("\r\n", "\n").trim().split("\n");+ const codeIndex = lines.findIndex((line) => TRUSTED_SOURCES_ERROR_CODE.test(line.trim()));+ if (codeIndex < 0) return message;+ const code = lines[codeIndex]!.trim();++ const reason = lines.slice(0, codeIndex).join("\n").trim();+ if (reason.length === 0) return message;+ return `${reason}\n\n${code}`;+}diff --git a/packages/eve/src/setup/flows/channels.test.ts b/packages/eve/src/setup/flows/channels.test.tsindex 4400edac3..a9748d800 100644--- a/packages/eve/src/setup/flows/channels.test.ts+++ b/packages/eve/src/setup/flows/channels.test.ts@@ -256,13 +256,13 @@ describe("runChannelsFlow", () => {});});- it("points a Vercel-dependent channel at /login when logged out, even if linked", async () => {+ it("points a Vercel-dependent channel at /vc:login when logged out, even if linked", async () => {// Authentication is a separate axis from link: a linked-but-logged-out- // directory still cannot provision, so the row routes to /login, not /model.+ // directory still cannot provision, so the row routes to /vc:login, not /model.for (const deployment of [UNLINKED, LINKED]) {expect(await slackRowFor({ deployment, authStatus: "logged-out" })).toMatchObject({disabled: true,- disabledReason: "Log in to Vercel first, see /login",+ disabledReason: "Log in to Vercel first, see /vc:login",disabledReasonTone: "warning",});}@@ -271,7 +271,7 @@ describe("runChannelsFlow", () => {it("points a Vercel-dependent channel at the CLI install when the CLI is missing", async () => {expect(await slackRowFor({ deployment: UNLINKED, authStatus: "cli-missing" })).toMatchObject({disabled: true,- disabledReason: "Vercel CLI not found, see /vc",+ disabledReason: "Vercel CLI not found, see /vc:install",disabledReasonTone: "warning",});});@@ -526,7 +526,7 @@ describe("runChannelsFlow", () => {const addChannelsDeps = createAddChannelsDeps();// Provisioning runs before the slack file is scaffolded, so a logged-out// failure throws with no channel landed; the flow must re-throw it (the- // command handler routes it to /login) rather than swallow it.+ // command handler routes it to /vc:login) rather than swallow it.addChannelsDeps.provisionSlackbot = vi.fn(async () => {throw new HumanActionRequiredError({kind: "vercel-login",diff --git a/packages/eve/src/setup/flows/install-vercel-cli.ts b/packages/eve/src/setup/flows/install-vercel-cli.tsindex 9a7005782..b1aeb83fd 100644--- a/packages/eve/src/setup/flows/install-vercel-cli.ts+++ b/packages/eve/src/setup/flows/install-vercel-cli.ts@@ -43,7 +43,7 @@ function globalInstallArguments(kind: PackageManagerKind): string[] {}/**- * THE INSTALL FLOW for the dev TUI's `/vc`: the fix command for the+ * THE INSTALL FLOW for the dev TUI's `/vc:install`: the fix command for the* "Vercel CLI not found" diagnostic, so every diagnostic has a matching* command. Short-circuits when the CLI already resolves; otherwise runs a* global install with the project's package manager, streaming output to thediff --git a/packages/eve/src/setup/flows/login.test.ts b/packages/eve/src/setup/flows/login.test.tsindex 5e6049088..d2bcec85c 100644--- a/packages/eve/src/setup/flows/login.test.ts+++ b/packages/eve/src/setup/flows/login.test.ts@@ -32,6 +32,23 @@ describe("runLoginFlow", () => {expect(runVercelLogin).not.toHaveBeenCalled();});+ it("opens vercel login when a caller explicitly forces re-authentication", async () => {+ const { prompter } = createFakePrompter({});+ const runVercelLogin = vi.fn<LoginFlowDeps["runVercelLogin"]>(async () => true);+ const input = {+ appRoot: APP_ROOT,+ prompter,+ force: true,+ deps: {+ getVercelAuthStatus: authProbe("authenticated", "authenticated"),+ runVercelLogin,+ },+ };++ await expect(runLoginFlow(input)).resolves.toEqual({ kind: "logged-in" });+ expect(runVercelLogin).toHaveBeenCalledWith(expect.objectContaining({ cwd: APP_ROOT }));+ });+it("runs vercel login and confirms with a re-probe on success", async () => {const runVercelLogin = vi.fn<LoginFlowDeps["runVercelLogin"]>(async () => true);// First probe: logged out; second probe (after login): logged in.diff --git a/packages/eve/src/setup/flows/login.ts b/packages/eve/src/setup/flows/login.tsindex 3a28848ca..6ec73c3a6 100644--- a/packages/eve/src/setup/flows/login.ts+++ b/packages/eve/src/setup/flows/login.ts@@ -99,7 +99,7 @@ async function runVercelLoginWithControls(}/**- * THE LOGIN FLOW for the dev TUI's `/login`. Short-circuits when already+ * THE LOGIN FLOW for the dev TUI's `/vc:login`. Short-circuits when already* authenticated; otherwise runs `vercel login` as a browser flow the TUI waits* on (see {@link runVercelLoginWithControls}) and re-probes after, so a* half-finished or abandoned login reports `failed`, never a false success.@@ -107,6 +107,8 @@ async function runVercelLoginWithControls(export async function runLoginFlow(input: {appRoot: string;prompter: Prompter;+ /** Run the browser login even when the account-level Vercel session is valid. */+ force?: boolean;signal?: AbortSignal;deps?: Partial<LoginFlowDeps>;}): Promise<LoginFlowResult> {@@ -120,7 +122,8 @@ export async function runLoginFlow(input: {signal?.throwIfAborted();switch (initialStatus) {case "authenticated":- return { kind: "already" };+ if (input.force !== true) return { kind: "already" };+ break;case "cli-missing":return { kind: "cli-missing" };case "unavailable":diff --git a/packages/eve/src/setup/vercel-deployment.test.ts b/packages/eve/src/setup/vercel-deployment.test.tsindex 22e9c4a87..17b67184e 100644--- a/packages/eve/src/setup/vercel-deployment.test.ts+++ b/packages/eve/src/setup/vercel-deployment.test.ts@@ -1,4 +1,4 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import type { VercelCaptureResult } from "#setup/primitives/index.js";@@ -7,90 +7,136 @@ import {type VercelDeploymentResolutionDeps,} from "./vercel-deployment.js";-beforeEach(() => {- vi.stubEnv("VERCEL_ORG_ID", "");- vi.stubEnv("VERCEL_PROJECT_ID", "");-});+afterEach(() => vi.restoreAllMocks());-afterEach(() => {- vi.unstubAllEnvs();-});+const STANDARD = {+ ownerId: "team_a",+ projectId: "prj_target",+ name: "inbound",+ target: "production",+ customEnvironment: null,+};describe("resolveVercelDeployment", () => {- it("uses a complete Vercel project environment before the on-disk link", async () => {- vi.stubEnv("VERCEL_ORG_ID", "team_env");- vi.stubEnv("VERCEL_PROJECT_ID", "prj_env");- const readProjectLink = vi.fn<VercelDeploymentResolutionDeps["readProjectLink"]>(async () => ({- orgId: "team_link",- projectId: "prj_link",- }));+ it("resolves from the host alone, without a scope, when no source is provided", async () => {const captureVercel = vi.fn<VercelDeploymentResolutionDeps["captureVercel"]>(async () => ({ok: true,- stdout: JSON.stringify({- projectId: "prj_env",- name: "inbound",- target: "preview",- }),+ stdout: JSON.stringify({ ...STANDARD, ownerId: "team_resolved" }),}));await expect(resolveVercelDeployment({workspaceRoot: "/repo",host: "inbound.example.com",- deps: { captureVercel, readProjectLink },+ deps: { captureVercel },}),).resolves.toMatchObject({kind: "resolved",target: {- deployment: { ownerId: "team_env", projectId: "prj_env" },+ origin: "https://inbound.example.com",+ deployment: {+ provider: "vercel",+ ownerId: "team_resolved",+ projectId: "prj_target",+ projectName: "inbound",+ environment: "production",+ },},});- expect(readProjectLink).not.toHaveBeenCalled();+ expect(captureVercel).toHaveBeenCalledWith(+ ["api", "/v13/deployments/inbound.example.com", "--raw"],+ expect.objectContaining({ cwd: "/repo", nonInteractive: true, timeoutMs: 10_000 }),+ );});- it("resolves a standard deployment whose custom environment is null", async () => {- const response: VercelCaptureResult = {+ it("scopes the lookup and cross-checks the project when a source is provided", async () => {+ const captureVercel = vi.fn<VercelDeploymentResolutionDeps["captureVercel"]>(async () => ({ok: true,- stdout: JSON.stringify({- projectId: "prj_target",- name: "inbound",- target: null,- customEnvironment: null,+ stdout: JSON.stringify(STANDARD),+ }));++ await expect(+ resolveVercelDeployment({+ workspaceRoot: "/repo",+ host: "inbound.example.com",+ source: { orgId: "team_a", projectId: "prj_target" },+ deps: { captureVercel },}),- };- const captureVercel = vi.fn<VercelDeploymentResolutionDeps["captureVercel"]>(- async () => response,+ ).resolves.toMatchObject({+ kind: "resolved",+ target: { deployment: { ownerId: "team_a", projectId: "prj_target" } },+ });+ expect(captureVercel).toHaveBeenCalledWith(+ ["api", "/v13/deployments/inbound.example.com", "--scope", "team_a", "--raw"],+ expect.objectContaining({ cwd: "/repo" }),);+ });++ it("derives the canonical owner id from the response, not the queried scope", async () => {+ const captureVercel = vi.fn<VercelDeploymentResolutionDeps["captureVercel"]>(async () => ({+ ok: true,+ stdout: JSON.stringify({ ...STANDARD, ownerId: "team_acme" }),+ }));const resolution = await resolveVercelDeployment({workspaceRoot: "/repo",host: "inbound.example.com",- deps: {- captureVercel,- readProjectLink: async () => ({ orgId: "team_a", projectId: "prj_target" }),- },+ // The caller may scope with a team slug, but the OIDC owner_id claim is+ // the canonical team_* id; the target must carry the id Vercel returned.+ source: { orgId: "acme", projectId: "prj_target" },+ deps: { captureVercel },});expect(resolution).toMatchObject({kind: "resolved",- target: {- origin: "https://inbound.example.com",- deployment: {- provider: "vercel",- ownerId: "team_a",- projectId: "prj_target",- projectName: "inbound",- environment: "preview",- },- },+ target: { deployment: { ownerId: "team_acme", projectId: "prj_target" } },});-expect(captureVercel).toHaveBeenCalledWith(- ["api", "/v13/deployments/inbound.example.com", "--scope", "team_a", "--raw"],- expect.objectContaining({ cwd: "/repo", nonInteractive: true, timeoutMs: 10_000 }),+ ["api", "/v13/deployments/inbound.example.com", "--scope", "acme", "--raw"],+ expect.objectContaining({ cwd: "/repo" }),);});+ it("reports a denied scope as forbidden so the caller can re-authenticate", async () => {+ const captureVercel = vi.fn<VercelDeploymentResolutionDeps["captureVercel"]>(async () => ({+ ok: false,+ failure: {+ code: 1,+ stdout: JSON.stringify({ error: { code: "forbidden", message: "SSO required" } }),+ stderr: "",+ message: "vercel api /v13/deployments/inbound.example.com exited with code 1.",+ },+ }));++ await expect(+ resolveVercelDeployment({+ workspaceRoot: "/repo",+ host: "inbound.example.com",+ deps: { captureVercel },+ }),+ ).resolves.toEqual({ kind: "forbidden" });+ });++ it("rejects a deployment from a different project under the same owner", async () => {+ await expect(+ resolveVercelDeployment({+ workspaceRoot: "/repo",+ host: "other.example.com",+ source: { orgId: "team_a", projectId: "prj_source" },+ deps: {+ captureVercel: async () => ({+ ok: true,+ stdout: JSON.stringify({ ...STANDARD, projectId: "prj_other", name: "other" }),+ }),+ },+ }),+ ).resolves.toEqual({+ kind: "project-mismatch",+ expectedProjectId: "prj_source",+ actualProjectId: "prj_other",+ });+ });+it("distinguishes not-found, operational, and invalid-response failures", async () => {const captures: VercelCaptureResult[] = [{@@ -99,12 +145,7 @@ describe("resolveVercelDeployment", () => {},{ok: false,- failure: {- code: null,- stdout: "",- stderr: "",- message: "vercel api timed out.",- },+ failure: { code: null, stdout: "", stderr: "", message: "vercel api timed out." },},{ ok: true, stdout: "not json" },{ ok: true, stdout: JSON.stringify({ projectId: "prj_target" }) },@@ -142,47 +183,6 @@ describe("resolveVercelDeployment", () => {});});- it("rejects a deployment from a different project under the same owner", async () => {- await expect(- resolveVercelDeployment({- workspaceRoot: "/repo",- host: "other.example.com",- source: { orgId: "team_a", projectId: "prj_source" },- deps: {- captureVercel: async () => ({- ok: true,- stdout: JSON.stringify({- projectId: "prj_other",- name: "other",- target: "preview",- customEnvironment: null,- }),- }),- },- }),- ).resolves.toEqual({- kind: "project-mismatch",- expectedProjectId: "prj_source",- actualProjectId: "prj_other",- });- });-- it("reports an unscoped lookup without invoking the Vercel CLI", async () => {- const captureVercel = vi.fn<VercelDeploymentResolutionDeps["captureVercel"]>();-- await expect(- resolveVercelDeployment({- workspaceRoot: "/repo",- host: "inbound.example.com",- deps: {- captureVercel,- readProjectLink: async () => undefined,- },- }),- ).resolves.toEqual({ kind: "unscoped" });- expect(captureVercel).not.toHaveBeenCalled();- });-it("does not infer not-found from an operational error's command text", async () => {await expect(resolveVercelDeployment({@@ -194,7 +194,7 @@ describe("resolveVercelDeployment", () => {ok: false,failure: {code: 1,- stdout: JSON.stringify({ error: { code: "forbidden", message: "Forbidden" } }),+ stdout: JSON.stringify({ error: { code: "internal", message: "boom" } }),stderr: "",message: "vercel api /v13/deployments/preview-404.example.com exited with code 1.",},diff --git a/packages/eve/src/setup/vercel-deployment.ts b/packages/eve/src/setup/vercel-deployment.tsindex 3432d9294..c5c1f1386 100644--- a/packages/eve/src/setup/vercel-deployment.ts+++ b/packages/eve/src/setup/vercel-deployment.ts@@ -1,14 +1,15 @@import { captureVercel, type VercelCaptureFailure } from "#setup/primitives/index.js";-import {- projectReferenceFromEnvironment,- readProjectLink,- type VercelProjectReference,-} from "#setup/project-resolution.js";+import type { VercelProjectReference } from "#setup/project-resolution.js";import { z } from "zod";-import { isNotFoundApiFailure, normalizeVercelApiResult } from "./vercel-api-failure.js";+import {+ isForbiddenApiFailure,+ isNotFoundApiFailure,+ normalizeVercelApiResult,+} from "./vercel-api-failure.js";const VercelDeploymentSchema = z.object({+ ownerId: z.string().min(1),projectId: z.string().min(1),name: z.string().min(1),target: z.string().nullable().optional(),@@ -42,7 +43,7 @@ export type VercelDeploymentResolutionFailure =export type VercelDeploymentResolution =| { readonly kind: "resolved"; readonly target: VerifiedVercelTarget }| { readonly kind: "not-found" }- | { readonly kind: "unscoped" }+ | { readonly kind: "forbidden" }| {readonly kind: "project-mismatch";readonly expectedProjectId: string;@@ -56,10 +57,9 @@ export type VercelDeploymentResolution =export interface VercelDeploymentResolutionDeps {readonly captureVercel: typeof captureVercel;- readonly readProjectLink: typeof readProjectLink;}-const defaultDeps: VercelDeploymentResolutionDeps = { captureVercel, readProjectLink };+const defaultDeps: VercelDeploymentResolutionDeps = { captureVercel };const DEPLOYMENT_LOOKUP_TIMEOUT_MS = 10_000;function environmentForDeployment(deployment: z.infer<typeof VercelDeploymentSchema>): string {@@ -78,19 +78,19 @@ export async function resolveVercelDeployment(input: {readonly deps?: Partial<VercelDeploymentResolutionDeps>;}): Promise<VercelDeploymentResolution> {const deps = { ...defaultDeps, ...input.deps };- const source =- input.source ??- projectReferenceFromEnvironment(process.env) ??- (await deps.readProjectLink(input.workspaceRoot));- if (source === undefined) return { kind: "unscoped" };+ // A deployment hostname is globally unique, so Vercel resolves it under the+ // caller's own access without a scope — including a team-owned deployment+ // resolved from a personal default scope. An optional `source` (a known+ // project link) scopes the lookup and is cross-checked below, but its absence+ // is not fatal: the host alone yields the canonical owner and project.+ const source = input.source;const result = normalizeVercelApiResult(await deps.captureVercel(["api",`/v13/deployments/${encodeURIComponent(input.host)}`,- "--scope",- source.orgId,+ ...(source !== undefined ? ["--scope", source.orgId] : []),"--raw",],{@@ -106,6 +106,9 @@ export async function resolveVercelDeployment(input: {return { kind: "cancelled" };}if (isNotFoundApiFailure(result.failure)) return { kind: "not-found" };+ // A denied scope (e.g. an expired team SSO session) is distinct from a+ // genuine miss: the caller can re-authenticate and retry.+ if (isForbiddenApiFailure(result.failure)) return { kind: "forbidden" };return { kind: "failed", failure: { cause: "vercel", failure: result.failure } };}@@ -130,7 +133,7 @@ export async function resolveVercelDeployment(input: {};}- if (parsed.data.projectId !== source.projectId) {+ if (source !== undefined && parsed.data.projectId !== source.projectId) {return {kind: "project-mismatch",expectedProjectId: source.projectId,@@ -147,7 +150,11 @@ export async function resolveVercelDeployment(input: {origin,deployment: {provider: "vercel",- ownerId: source.orgId,+ // The OIDC `owner_id` claim and Trusted Sources key on the canonical+ // team/owner id. Vercel's response carries it, so the verified target+ // takes the owner from there rather than from any scope the caller may+ // have queried with (which can be a slug).+ ownerId: parsed.data.ownerId,projectId: parsed.data.projectId,projectName: parsed.data.name,environment: environmentForDeployment(parsed.data),diff --git a/packages/eve/src/setup/vercel-project-api.test.ts b/packages/eve/src/setup/vercel-project-api.test.tsindex 80ff1ebc5..de4d27b95 100644--- a/packages/eve/src/setup/vercel-project-api.test.ts+++ b/packages/eve/src/setup/vercel-project-api.test.ts@@ -110,57 +110,58 @@ describe("listRecentProjects", () => {});describe("searchProjects", () => {- it("searches every matching page under the selected team", async () => {- mockedCaptureVercel- .mockResolvedValueOnce(- captured({- projects: [{ id: "prj_a", name: "agent" }],- pagination: { next: 7 },- }),- )- .mockResolvedValueOnce(- captured({- projects: [- { id: "prj_a", name: "agent" },- { id: "prj_b", name: "agent-api" },- ],- pagination: { next: null },- }),- );+ it("returns a ranked matching page and its continuation cursor", async () => {+ mockedCaptureVercel.mockResolvedValue(+ captured({+ projects: [+ { id: "prj_infix", name: "env" },+ { id: "prj_prefix", name: "v-api" },+ { id: "prj_exact", name: "v" },+ ],+ pagination: { next: 7 },+ }),+ );- await expect(searchProjects("/repo", "team-a", " agent ")).resolves.toEqual([- { id: "prj_a", name: "agent" },- { id: "prj_b", name: "agent-api" },- ]);- expect(mockedCaptureVercel).toHaveBeenNthCalledWith(- 1,- ["project", "ls", "--format", "json", "--scope", "team-a", "--filter", "agent"],+ await expect(searchProjects("/repo", "team-a", " V ")).resolves.toEqual({+ projects: [+ { id: "prj_exact", name: "v" },+ { id: "prj_prefix", name: "v-api" },+ { id: "prj_infix", name: "env" },+ ],+ next: 7,+ });+ expect(mockedCaptureVercel).toHaveBeenCalledOnce();+ expect(mockedCaptureVercel).toHaveBeenCalledWith(+ ["project", "ls", "--format", "json", "--scope", "team-a", "--filter", "V"],{ cwd: "/repo", signal: undefined, timeoutMs: 15_000 },);- expect(mockedCaptureVercel).toHaveBeenNthCalledWith(- 2,- [- "project",- "ls",- "--format",- "json",- "--scope",- "team-a",- "--filter",- "agent",- "--next",- "7",+ });++ it("loads and ranks a requested continuation page", async () => {+ mockedCaptureVercel.mockResolvedValue(+ captured({+ projects: [+ { id: "prj_infix", name: "env" },+ { id: "prj_prefix", name: "v-api" },+ ],+ pagination: { next: null },+ }),+ );+ const continuation = { next: 7 };++ await expect(searchProjects("/repo", "team-a", "v", continuation)).resolves.toEqual({+ projects: [+ { id: "prj_prefix", name: "v-api" },+ { id: "prj_infix", name: "env" },],+ });+ expect(mockedCaptureVercel).toHaveBeenCalledWith(+ ["project", "ls", "--format", "json", "--scope", "team-a", "--filter", "v", "--next", "7"],{ cwd: "/repo", signal: undefined, timeoutMs: 15_000 },);});- it("rejects empty queries and repeated cursors", async () => {+ it("rejects empty queries", async () => {await expect(searchProjects("/repo", "team-a", " ")).rejects.toThrow("cannot be empty");-- mockedCaptureVercel.mockResolvedValue(captured({ projects: [], pagination: { next: 7 } }));- await expect(searchProjects("/repo", "team-a", "agent")).rejects.toThrow(- "repeated pagination cursor",- );});});diff --git a/packages/eve/src/setup/vercel-project-api.ts b/packages/eve/src/setup/vercel-project-api.tsindex 53942715d..470efdaec 100644--- a/packages/eve/src/setup/vercel-project-api.ts+++ b/packages/eve/src/setup/vercel-project-api.ts@@ -7,7 +7,8 @@ import type { VercelProjectOperationOptions } from "./project-resolution.js";export type { VercelProjectOperationOptions };-const PROJECT_LIST_TIMEOUT_MS = 15_000;+/** Shared deadline for Vercel project list and exact-lookup requests. */+export const VERCEL_PROJECT_REQUEST_TIMEOUT_MS = 15_000;const VercelTeamListEntrySchema = z.object({name: z.string(),@@ -24,6 +25,12 @@ const VercelProjectListEntrySchema = z.object({export type VercelProjectListEntry = z.infer<typeof VercelProjectListEntrySchema>;+/** One ranked Vercel project search page and its optional continuation cursor. */+export interface VercelProjectSearchPage {+ readonly projects: VercelProjectListEntry[];+ readonly next?: number;+}+const VercelPaginationSchema = z.object({next: z.number().int().nonnegative().nullable().optional(),});@@ -133,7 +140,7 @@ async function fetchProjectPage(const result = await captureVercel(args, {cwd: projectRoot,signal: options.signal,- timeoutMs: PROJECT_LIST_TIMEOUT_MS,+ timeoutMs: VERCEL_PROJECT_REQUEST_TIMEOUT_MS,});options.signal?.throwIfAborted();if (!result.ok) {@@ -154,18 +161,35 @@ export async function listRecentProjects(return (await fetchProjectPage(projectRoot, team, options)).items;}-/** Searches every matching Vercel project page in one account scope. */+function projectSearchRank(project: VercelProjectListEntry, query: string): number {+ const name = project.name.toLowerCase();+ const normalizedQuery = query.toLowerCase();+ if (name === normalizedQuery) return 0;+ if (name.startsWith(normalizedQuery)) return 1;+ return 2;+}++/** Ranks exact and prefix project-name matches ahead of substring matches. */+export function rankProjectSearchResults(+ projects: readonly VercelProjectListEntry[],+ query: string,+): VercelProjectListEntry[] {+ const search = query.trim();+ return [...projects].sort(+ (left, right) => projectSearchRank(left, search) - projectSearchRank(right, search),+ );+}++/** Searches one ranked Vercel project page and retains its continuation cursor. */export async function searchProjects(projectRoot: string,team: string,query: string,- options: VercelProjectOperationOptions = {},-): Promise<VercelProjectListEntry[]> {+ options: VercelProjectOperationOptions & { readonly next?: number } = {},+): Promise<VercelProjectSearchPage> {const search = query.trim();if (search.length === 0) throw new Error("Project search query cannot be empty.");- return drainPages(- `project search in ${team}`,- (project) => project.id,- (next) => fetchProjectPage(projectRoot, team, { ...options, search, next }),- );+ const page = await fetchProjectPage(projectRoot, team, { ...options, search });+ const projects = rankProjectSearchResults(page.items, search);+ return page.next === undefined ? { projects } : { projects, next: page.next };}diff --git a/packages/eve/src/setup/vercel-project.test.ts b/packages/eve/src/setup/vercel-project.test.tsindex 312b68c21..d61a146bf 100644--- a/packages/eve/src/setup/vercel-project.test.ts+++ b/packages/eve/src/setup/vercel-project.test.ts@@ -83,8 +83,8 @@ describe("vercelAuthBlockerReason", () => {vercelAuthBlockerReason("unavailable"),]).toEqual([undefined,- "Vercel CLI not found, see /vc",- "Log in to Vercel first, see /login",+ "Vercel CLI not found, see /vc:install",+ "Log in to Vercel first, see /vc:login","Couldn't reach Vercel, check your connection",]);});@@ -196,7 +196,7 @@ describe("pickProject", () => {expect(stop).toHaveBeenCalledTimes(1);});- it("searches the full team scope after a CLI picker search", async () => {+ it("falls back to one ranked project-search page when no exact project exists", async () => {mockedCaptureVercel.mockResolvedValueOnce(captured({@@ -206,6 +206,11 @@ describe("pickProject", () => {],}),)+ .mockResolvedValueOnce(+ failedCapture(+ JSON.stringify({ error: { code: "not_found", message: "Project not found" } }),+ ),+ ).mockResolvedValueOnce(captured({ projects: [{ id: "prj_found", name: "found" }] }));const single = vi.fn()@@ -221,9 +226,9 @@ describe("pickProject", () => {.mockImplementationOnce((options) => {expect(options.search).toBe(true);expect(options.options.map((option: { label: string }) => option.label)).toEqual([+ "found","older","newer",- "found",]);return "prj_found";});@@ -236,32 +241,95 @@ describe("pickProject", () => {});expect(mockedCaptureVercel).toHaveBeenNthCalledWith(2,+ ["api", "/v9/projects/found", "--scope", "team-a", "--raw"],+ { cwd: "/repo", signal: undefined, timeoutMs: 15_000 },+ );+ expect(mockedCaptureVercel).toHaveBeenNthCalledWith(+ 3,["project", "ls", "--format", "json", "--scope", "team-a", "--filter", "found"],{ cwd: "/repo", signal: undefined, timeoutMs: 15_000 },);});- it("loads full-team results into a repainting picker", async () => {+ it("loads the next search page when the first ranked page is incomplete", async () => {mockedCaptureVercel.mockResolvedValueOnce(captured({ projects: [{ id: "prj_recent", name: "recent" }] }))- .mockResolvedValueOnce(captured({ projects: [{ id: "prj_found", name: "found" }] }));+ .mockResolvedValueOnce(+ failedCapture(+ JSON.stringify({ error: { code: "not_found", message: "Project not found" } }),+ ),+ )+ .mockResolvedValueOnce(+ captured({+ projects: [{ id: "prj_infix", name: "env" }],+ pagination: { next: 7 },+ }),+ )+ .mockResolvedValueOnce(+ captured({+ projects: [{ id: "prj_prefix", name: "v-api" }],+ pagination: { next: null },+ }),+ );+ const single = vi+ .fn()+ .mockImplementationOnce(() => "\0search-project:v")+ .mockImplementationOnce((options) => {+ const more = options.options.find((option: { label: string }) =>+ option.label.startsWith("Show more matches"),+ );+ if (more === undefined) throw new Error("Expected a project-search continuation option.");+ return more.value;+ })+ .mockImplementationOnce((options) => {+ expect(options.options.map((option: { label: string }) => option.label)).toEqual([+ "v-api",+ "env",+ "recent",+ ]);+ return "prj_prefix";+ });+ const { prompter } = createFakePrompter({ single });++ await expect(pickProject(prompter, "/repo", "team-a")).resolves.toEqual({+ kind: "existing",+ project: { projectId: "prj_prefix", projectName: "v-api" },+ team: "team-a",+ });+ });++ it("promotes exact project matches in the repainting picker", async () => {+ mockedCaptureVercel+ .mockResolvedValueOnce(captured({ projects: [{ id: "prj_versioned", name: "versioned" }] }))+ .mockResolvedValueOnce(captured({ id: "prj_v", name: "v" }));const single = vi.fn(async (options) => {- const loaded = await options.searchAction.load("found");- expect(loaded.map((option: { label: string }) => option.label)).toEqual(["recent", "found"]);- return "prj_found";+ const loaded = await options.searchAction.load("v");+ expect(loaded.map((option: { label: string }) => option.label)).toEqual(["v", "versioned"]);+ return "prj_v";});const { prompter } = createFakePrompter({ single });await expect(pickProject(prompter, "/repo", "team-a")).resolves.toEqual({kind: "existing",- project: { projectId: "prj_found", projectName: "found" },+ project: { projectId: "prj_v", projectName: "v" },team: "team-a",});+ expect(mockedCaptureVercel).toHaveBeenCalledTimes(2);+ expect(mockedCaptureVercel).toHaveBeenNthCalledWith(+ 2,+ ["api", "/v9/projects/v", "--scope", "team-a", "--raw"],+ { cwd: "/repo", signal: undefined, timeoutMs: 15_000 },+ );});- it("refreshes a recent project when a full-team search returns it", async () => {+ it("refreshes a recent project when a search result returns it", async () => {mockedCaptureVercel.mockResolvedValueOnce(captured({ projects: [{ id: "prj_recent", name: "recent" }] }))+ .mockResolvedValueOnce(+ failedCapture(+ JSON.stringify({ error: { code: "not_found", message: "Project not found" } }),+ ),+ ).mockResolvedValueOnce(captured({projects: [@@ -275,10 +343,10 @@ describe("pickProject", () => {.mockImplementationOnce(() => "\0search-project:found").mockImplementationOnce((options) => {expect(options.options.map((option: { label: string }) => option.label)).toEqual([- "recent-updated","found",+ "recent-updated",]);- expect(options.initialValue).toBe("prj_recent");+ expect(options.initialValue).toBe("prj_found");return "prj_found";});const { prompter } = createFakePrompter({ single });@@ -290,9 +358,14 @@ describe("pickProject", () => {});});- it("reports an empty full-team search and reopens the picker", async () => {+ it("reports an empty project search and reopens the picker", async () => {mockedCaptureVercel.mockResolvedValueOnce(captured({ projects: [{ id: "prj_recent", name: "recent" }] }))+ .mockResolvedValueOnce(+ failedCapture(+ JSON.stringify({ error: { code: "not_found", message: "Project not found" } }),+ ),+ ).mockResolvedValueOnce(captured({ projects: [] }));const single = vi.fn()@@ -366,7 +439,7 @@ describe("assertNewProjectNameAvailable", () => {);expect(mockedCaptureVercel).toHaveBeenCalledWith(["api", "/v9/projects/my-agent", "--scope", "team-a", "--raw"],- { cwd: "/tmp/eve-agent" },+ { cwd: "/tmp/eve-agent", signal: undefined, timeoutMs: 15_000 },);});@@ -401,6 +474,19 @@ describe("resolveProjectByNameOrId", () => {{ projectId: "prj_existing", projectName: "my-agent" },);});++ it("bounds the direct lookup with the project request deadline", async () => {+ mockedCaptureVercel.mockResolvedValue(+ captured({ id: "prj_existing", name: "my-agent", accountId: "team_a" }),+ );++ await resolveProjectByNameOrId("/tmp/eve-agent", "team-a", "my-agent");++ expect(mockedCaptureVercel).toHaveBeenCalledWith(+ ["api", "/v9/projects/my-agent", "--scope", "team-a", "--raw"],+ { cwd: "/tmp/eve-agent", signal: undefined, timeoutMs: 15_000 },+ );+ });});describe("linkProject", () => {@@ -487,7 +573,7 @@ describe("linkProject", () => {expect(mockedCaptureVercel).toHaveBeenNthCalledWith(1,["api", "/v9/projects/my-agent", "--scope", "team-a", "--raw"],- { cwd: "/tmp/eve-agent" },+ { cwd: "/tmp/eve-agent", signal: undefined, timeoutMs: 15_000 },);expect(mockedCaptureVercel).toHaveBeenNthCalledWith(2,diff --git a/packages/eve/src/setup/vercel-project.ts b/packages/eve/src/setup/vercel-project.tsindex 09b7f718e..ca62aa97a 100644--- a/packages/eve/src/setup/vercel-project.ts+++ b/packages/eve/src/setup/vercel-project.ts@@ -22,10 +22,12 @@ import {listRecentProjects,listTeams,parseVercelJson,+ rankProjectSearchResults,requireVercelTeamAccess,searchProjects,type VercelProjectListEntry,type VercelProjectOperationOptions,+ VERCEL_PROJECT_REQUEST_TIMEOUT_MS,} from "./vercel-project-api.js";const VercelProjectReferenceSchema = z.object({@@ -66,7 +68,11 @@ export async function resolveProjectByNameOrId(const result = normalizeVercelApiResult(await captureVercel(["api", `/v9/projects/${encodeURIComponent(projectNameOrId)}`, "--scope", team, "--raw"],- { cwd: projectRoot, signal: options.signal },+ {+ cwd: projectRoot,+ signal: options.signal,+ timeoutMs: VERCEL_PROJECT_REQUEST_TIMEOUT_MS,+ },),);if (result.ok) {@@ -226,9 +232,9 @@ export function vercelAuthBlockerReason(authStatus: VercelAuthStatus): string |case "authenticated":return undefined;case "cli-missing":- return "Vercel CLI not found, see /vc";+ return "Vercel CLI not found, see /vc:install";case "logged-out":- return "Log in to Vercel first, see /login";+ return "Log in to Vercel first, see /vc:login";case "unavailable":return "Couldn't reach Vercel, check your connection";default: {@@ -373,12 +379,46 @@ export async function pickTeam(}const SEARCH_PROJECT_PREFIX = "\0search-project:";+const SEARCH_MORE_PROJECTS_PREFIX = "\0search-more-projects:";++type ProjectSearchResults = Awaited<ReturnType<typeof searchProjects>>;++interface ProjectSearchContinuation {+ readonly query: string;+ readonly next: number;+}-function appendProjects(+function searchMoreProjectsValue(continuation: ProjectSearchContinuation): string {+ return `${SEARCH_MORE_PROJECTS_PREFIX}${continuation.next}:${continuation.query}`;+}++function prioritizeSearchResults(existing: readonly VercelProjectListEntry[],found: readonly VercelProjectListEntry[],): VercelProjectListEntry[] {- return [...new Map([...existing, ...found].map((project) => [project.id, project])).values()];+ const projects = new Map(found.map((project) => [project.id, project]));+ for (const project of existing) {+ if (!projects.has(project.id)) projects.set(project.id, project);+ }+ return [...projects.values()];+}++async function findProjectSearchResults(+ projectRoot: string,+ team: string,+ query: string,+ options: VercelProjectOperationOptions,+ next?: number,+): Promise<ProjectSearchResults> {+ const search = query.trim();+ if (search.length === 0) throw new Error("Project search query cannot be empty.");++ if (next === undefined) {+ const exact = await resolveProjectByNameOrId(projectRoot, team, search, options);+ if (exact !== null) return { projects: [{ id: exact.projectId, name: exact.projectName }] };+ }++ return await searchProjects(projectRoot, team, search, { ...options, next });}/** Picks an existing project under a team, or a name to create when none exist. */@@ -391,6 +431,29 @@ export async function pickProject(let projects = await withSpinner(prompter, whimsyFor("projects", team), () =>listRecentProjects(projectRoot, team, options),);+ let searchResults: readonly VercelProjectListEntry[] = [];+ let searchContinuation: ProjectSearchContinuation | undefined;+ const projectOptions = () => {+ const result = projects.map((project) => ({ value: project.id, label: project.name }));+ if (searchContinuation !== undefined) {+ result.push({+ value: searchMoreProjectsValue(searchContinuation),+ label: `Show more matches for '${searchContinuation.query}'`,+ });+ }+ return result;+ };+ const applySearchResults = (+ query: string,+ found: ProjectSearchResults,+ append: boolean,+ ): void => {+ const existing = append ? searchResults : [];+ searchResults = rankProjectSearchResults([...existing, ...found.projects], query);+ projects = prioritizeSearchResults(projects, searchResults);+ searchContinuation =+ found.next === undefined ? undefined : { query: query.trim(), next: found.next };+ };if (projects.length === 0) {if (options.allowCreateWhenEmpty === false) {throw new Error(@@ -414,14 +477,33 @@ export async function pickProject(label: (query) => `Search for '${query}'`,value: (query) => `${SEARCH_PROJECT_PREFIX}${query}`,load: async (query) => {- const found = await searchProjects(projectRoot, team, query, { signal: options.signal });- projects = appendProjects(projects, found);- return projects.map((project) => ({ value: project.id, label: project.name }));+ const found = await findProjectSearchResults(projectRoot, team, query, {+ signal: options.signal,+ });+ applySearchResults(query, found, false);+ return projectOptions();},},- options: projects.map((project) => ({ value: project.id, label: project.name })),+ options: projectOptions(),initialValue: projects[0]?.id,});+ const continuation = searchContinuation;+ if (continuation !== undefined && selected === searchMoreProjectsValue(continuation)) {+ const found = await withSpinner(+ prompter,+ `Searching ${team} for "${continuation.query}"...`,+ () =>+ findProjectSearchResults(+ projectRoot,+ team,+ continuation.query,+ { signal: options.signal },+ continuation.next,+ ),+ );+ applySearchResults(continuation.query, found, true);+ continue;+ }const query = selected.startsWith(SEARCH_PROJECT_PREFIX)? selected.slice(SEARCH_PROJECT_PREFIX.length): undefined;@@ -436,13 +518,13 @@ export async function pickProject(}const found = await withSpinner(prompter, `Searching ${team} for "${query}"...`, () =>- searchProjects(projectRoot, team, query, { signal: options.signal }),+ findProjectSearchResults(projectRoot, team, query, { signal: options.signal }),);- if (found.length === 0) {+ applySearchResults(query, found, false);+ if (found.projects.length === 0 && found.next === undefined) {prompter.note(`No projects matched "${query}" in ${team}.`);continue;}- projects = appendProjects(projects, found);}}diff --git a/packages/eve/test/scenarios/dev-command-url.scenario.test.ts b/packages/eve/test/scenarios/dev-command-url.scenario.test.tsindex 6388a818d..331c9cebb 100644--- a/packages/eve/test/scenarios/dev-command-url.scenario.test.ts+++ b/packages/eve/test/scenarios/dev-command-url.scenario.test.ts@@ -75,9 +75,9 @@ describe("runCli dev URL support", () => {}),}),);- expect(logger.log.mock.calls.map(([message]) => String(message)).join("\n")).toContain(- "connecting to https://example.com/",- );+ const devOutput = logger.log.mock.calls.map(([message]) => String(message)).join("\n");+ expect(devOutput).toContain("↗ remote mode targeting");+ expect(devOutput).toContain("example.com");});it("rejects local server flags when using --url", async () => {diff --git a/packages/eve/test/tui-client/lib/tui.ts b/packages/eve/test/tui-client/lib/tui.tsindex cd2e34acd..814d7c5ac 100644--- a/packages/eve/test/tui-client/lib/tui.ts+++ b/packages/eve/test/tui-client/lib/tui.ts@@ -10,6 +10,7 @@ export {AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,EveTUIRunner,createPromptCommandHandler,+ promptCommandsFor,type EveTUIRunnerOptions,formatChangeDetectedLogLine,MockScreen,diff --git a/packages/eve/test/tui-client/tui-packed-install-model.ts b/packages/eve/test/tui-client/tui-packed-install-model.tsindex d99c82b0a..42739ceb5 100644--- a/packages/eve/test/tui-client/tui-packed-install-model.ts+++ b/packages/eve/test/tui-client/tui-packed-install-model.ts@@ -45,7 +45,9 @@ interface PackedTuiHarness {send(sequence: string): void;ctrlC(): void;};- createPromptCommandHandler: (options: { appRoot?: string }) => unknown;+ createPromptCommandHandler: (options: {+ target: { kind: "local"; serverUrl: string; workspaceRoot: string };+ }) => unknown;}void (async () => {@@ -105,7 +107,13 @@ void (async () => {userInput: input,name: "Packed install model command",appRoot: consumerRoot,- promptCommandHandler: createPromptCommandHandler({ appRoot: consumerRoot }),+ promptCommandHandler: createPromptCommandHandler({+ target: {+ kind: "local",+ serverUrl: "http://127.0.0.1:0",+ workspaceRoot: consumerRoot,+ },+ }),bootDetections: [{id: "test-unconfigured-provider",diff --git a/packages/eve/test/tui-client/tui-slash-commands.ts b/packages/eve/test/tui-client/tui-slash-commands.tsindex ea025a92f..8adafb263 100644--- a/packages/eve/test/tui-client/tui-slash-commands.ts+++ b/packages/eve/test/tui-client/tui-slash-commands.ts@@ -3,7 +3,13 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { Client } from "eve/client";-import { createPromptCommandHandler, EveTUIRunner, MockScreen, MockUserInput } from "./lib/tui.ts";+import {+ createPromptCommandHandler,+ EveTUIRunner,+ MockScreen,+ MockUserInput,+ promptCommandsFor,+} from "./lib/tui.ts";import { theme } from "./lib/theme.ts";@@ -13,7 +19,7 @@ import { theme } from "./lib/theme.ts";* 1. A turn against an unreachable server renders an error region.* 2. `/new` clears the transcript and starts a fresh session, the error* region disappears and the screen returns to the empty prompt.- * 3. `/deploy` (with no local setup context) renders the local-only notice+ * 3. `/deploy` (in a remote command context) renders the local-only notice* instead of suspending into a setup flow.* 4. `/exit` terminates the runner, exactly as Ctrl+C would.* 5. Local `/channels` opens the real setup picker, Escape cancels it, and@@ -34,7 +40,14 @@ void (async () => {screen,userInput: input,name: "TUI slash commands",- promptCommandHandler: createPromptCommandHandler({}),+ availablePromptCommands: promptCommandsFor("remote"),+ promptCommandHandler: createPromptCommandHandler({+ target: {+ kind: "remote",+ serverUrl: UNREACHABLE_HOST,+ workspaceRoot: process.cwd(),+ },+ }),});const runPromise = runner.run().catch((error: unknown) => {@@ -63,26 +76,12 @@ void (async () => {}console.log(theme.muted("[tui-slash-commands] /new cleared the transcript"));- // The command handler has no appRoot (this session is not a local `eve dev`),- // so the setup commands answer with the local-only notice instead of- // suspending into a flow. Proves parse → dispatch → notice with no network.+ // Remote setup commands return a local-only notice instead of opening a flow.input.type("/deploy");input.enter();await screen.waitForText("/deploy needs eve dev running the local server", 5_000);console.log(theme.muted("[tui-slash-commands] /deploy rendered the local-only notice"));- await screen.waitForText("❯", 5_000);- input.type("/login");- input.enter();- await screen.waitForText("/login needs eve dev running the local server", 5_000);- console.log(theme.muted("[tui-slash-commands] /login rendered the local-only notice"));-- await screen.waitForText("❯", 5_000);- input.type("/vc");- input.enter();- await screen.waitForText("/vc needs eve dev running the local server", 5_000);- console.log(theme.muted("[tui-slash-commands] /vc rendered the local-only notice"));-await screen.waitForText("❯", 5_000);input.type("/exit");input.enter();@@ -114,7 +113,10 @@ async function runLocalChannelsCancellation(): Promise<void> {userInput: input,name: "TUI local setup",appRoot,- promptCommandHandler: createPromptCommandHandler({ appRoot }),+ availablePromptCommands: promptCommandsFor("local"),+ promptCommandHandler: createPromptCommandHandler({+ target: { kind: "local", serverUrl: UNREACHABLE_HOST, workspaceRoot: appRoot },+ }),});const runPromise = runner.run();diff --git a/packages/eve/test/tui-client/tui-status-line.ts b/packages/eve/test/tui-client/tui-status-line.tsindex 37571c908..4b1fb13df 100644--- a/packages/eve/test/tui-client/tui-status-line.ts+++ b/packages/eve/test/tui-client/tui-status-line.ts@@ -51,7 +51,7 @@ async function runPendingDeployCycle(): Promise<void> {name: "TUI status line",appRoot,promptCommandHandler: createPromptCommandHandler({- appRoot,+ target: { kind: "local", serverUrl: UNREACHABLE_HOST, workspaceRoot: appRoot },flows: {runChannelsFlow: async () => ({ kind: "done", addedChannels: ["slack"] }),runDeployFlow: async () => ({ kind: "deployed" }),@@ -109,7 +109,9 @@ async function runUnlinkedShowsNoVercelSegment(): Promise<void> {userInput: input,name: "TUI status line unlinked",appRoot,- promptCommandHandler: createPromptCommandHandler({ appRoot }),+ promptCommandHandler: createPromptCommandHandler({+ target: { kind: "local", serverUrl: UNREACHABLE_HOST, workspaceRoot: appRoot },+ }),});const runPromise = runner.run();