The Open Framework for Building Agents
fix(eve): recover registry setup from a logged-out Vercel CLI (#4483)
prha89704cb49468
diff --git a/.changeset/registry-setup-vercel-login.md b/.changeset/registry-setup-vercel-login.mdnew file mode 100644index 000000000..3dba91e06--- /dev/null+++ b/.changeset/registry-setup-vercel-login.md@@ -0,0 +1,5 @@+---+"eve": patch+---++When a registry item's setup needs a logged-in Vercel CLI, `/add` in `eve dev` now offers to run `vercel login` and then finishes setup without reinstalling the item. Items whose setup fails after their files are installed now show as "setup not finished" with the reason, instead of "Couldn't add". `eve add --non-interactive` reports a `vercel login` prerequisite (exit 2) instead of a raw `vercel connect` failure. eve now detects a logged-out Vercel CLI from `vercel whoami --format json`, so newer CLIs that print only "Logged out." are no longer misreported as a transient error. The self-modification agent no longer describes an item as added before its setup panel has run.diff --git a/packages/eve/src/cli/commands/integration-connect.test.ts b/packages/eve/src/cli/commands/integration-connect.test.tsindex 3b08709be..75258d777 100644--- a/packages/eve/src/cli/commands/integration-connect.test.ts+++ b/packages/eve/src/cli/commands/integration-connect.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import { createFakePrompter } from "#internal/testing/fake-prompter.js";+import { HumanActionRequiredError } from "#setup/human-action.js";import { WizardCancelledError } from "#setup/step.js";import { runIntegrationConnect, runIntegrationConnectCommand } from "./integration-connect.js";@@ -20,6 +21,7 @@ function dependencies(overrides: Record<string, unknown> = {}) {createPrompter: () => fake.prompter,ensureVercelProject: vi.fn(async () => PROJECT),readProjectLink: vi.fn(async () => PROJECT),+ requireAuth: vi.fn(async () => {}),setupConnectionConnector: vi.fn(async () => ({kind: "existing" as const,connectorUid: "linear/real",@@ -156,6 +158,41 @@ describe("runIntegrationConnect", () => {expect(process.exitCode).toBe(2);});+ it("reports a logged-out CLI on a linked project as a vercel login prerequisite", async () => {+ const output = {+ errors: [] as string[],+ log: vi.fn(),+ error: vi.fn((message) => output.errors.push(message)),+ };+ const deps = dependencies({+ requireAuth: vi.fn(async () => {+ throw new HumanActionRequiredError({+ kind: "vercel-login",+ command: "vercel login",+ reason: "The Vercel CLI is not logged in.",+ });+ }),+ });++ await runIntegrationConnectCommand(+ output,+ "/project",+ "notion",+ "mcp.notion.com",+ undefined,+ { nonInteractive: true },+ deps,+ );++ expect(JSON.parse(output.errors[0]!)).toMatchObject({+ type: "blocked",+ status: "prerequisite_required",+ prerequisite: { kind: "command", code: "vercel-login", command: "vercel login" },+ });+ expect(process.exitCode).toBe(2);+ expect(deps.setupConnectionConnector).not.toHaveBeenCalled();+ });+it("does not create an interactive prompter for a non-interactive command", async () => {const createPrompter = vi.fn(() => createFakePrompter().prompter);const deps = dependencies({ createPrompter });diff --git a/packages/eve/src/cli/commands/integration-connect.ts b/packages/eve/src/cli/commands/integration-connect.tsindex 6ab7510b6..038848c3a 100644--- a/packages/eve/src/cli/commands/integration-connect.ts+++ b/packages/eve/src/cli/commands/integration-connect.ts@@ -11,11 +11,12 @@ import {type EnsureVercelProjectDeps,} from "#setup/flows/ensure-vercel-project.js";import { createHeadlessPrompter } from "#setup/headless.js";-import { SetupPrerequisiteRequired } from "#setup/integrations/shared/prerequisite.js";+import { setupPrerequisiteOf } from "#setup/integrations/shared/prerequisite.js";import { resolveIntegrationVercelProject } from "#setup/integrations/shared/vercel-project.js";import { readProjectLink } from "#setup/project-resolution.js";import { createPrompter, type Prompter } from "#setup/prompter.js";import { createRegistrySetupClient } from "#setup/registry-setup-client.js";+import { requireAuth } from "#setup/vercel-project.js";import { updateConnectionConnectorUid } from "#setup/scaffold/update/update-connection-connector.js";import { WizardCancelledError } from "#setup/step.js";@@ -35,6 +36,7 @@ export interface IntegrationConnectDependencies {ensureVercelProject: typeof ensureVercelProject;ensureVercelProjectDeps?: Partial<EnsureVercelProjectDeps>;readProjectLink: typeof readProjectLink;+ requireAuth: typeof requireAuth;setupConnectionConnector: typeof setupConnectionConnector;cleanupCreatedConnectionConnector: typeof cleanupCreatedConnectionConnector;updateConnectionConnectorUid: typeof updateConnectionConnectorUid;@@ -43,6 +45,7 @@ export interface IntegrationConnectDependencies {const defaultDependencies: IntegrationConnectDependencies = {ensureVercelProject,readProjectLink,+ requireAuth,setupConnectionConnector,cleanupCreatedConnectionConnector,updateConnectionConnectorUid,@@ -66,7 +69,14 @@ export async function runIntegrationConnect(input: {prompter.intro(`Set up ${input.slug}`);let project = await dependencies.readProjectLink(input.appRoot);- if (project === undefined) {+ if (project !== undefined) {+ // An existing link skips project provisioning and its login check, so+ // verify the CLI session here: otherwise a logged-out CLI surfaces only as+ // an opaque `vercel connect` exit code instead of the `vercel login` action.+ await dependencies.requireAuth(input.appRoot, nonInteractive ? undefined : prompter, {+ signal,+ });+ } else {if (nonInteractive) {project = await resolveIntegrationVercelProject({appRoot: input.appRoot,@@ -152,13 +162,14 @@ export async function runIntegrationConnectCommand(} catch (error) {client?.fail(error);if (client !== undefined) return;- if (options.nonInteractive && error instanceof SetupPrerequisiteRequired) {+ const prerequisite = setupPrerequisiteOf(error);+ if (options.nonInteractive && prerequisite !== undefined) {logger.error(serializeHeadlessSetupEvent({version: 1,type: "blocked",status: "prerequisite_required",- prerequisite: error.prerequisite,+ prerequisite,}),);process.exitCode = 2;diff --git a/packages/eve/src/cli/commands/integration-setup.ts b/packages/eve/src/cli/commands/integration-setup.tsindex 0104e2d22..6ca189dd1 100644--- a/packages/eve/src/cli/commands/integration-setup.ts+++ b/packages/eve/src/cli/commands/integration-setup.ts@@ -10,7 +10,7 @@ import { WEB_CHAT_TEAM_REQUIREMENT } from "#setup/integrations/web/auth-options.import { ensureVercelProject } from "#setup/flows/ensure-vercel-project.js";import { resolveEveProjectContext } from "#internal/project-context.js";import { createHeadlessPrompter } from "#setup/headless.js";-import { SetupPrerequisiteRequired } from "#setup/integrations/shared/prerequisite.js";+import { setupPrerequisiteOf } from "#setup/integrations/shared/prerequisite.js";import { createPrompter, type Prompter } from "#setup/prompter.js";import { createRegistrySetupClient, type SetupProcess } from "#setup/registry-setup-client.js";import {@@ -121,6 +121,7 @@ export async function runIntegrationSetupCommand(} catch (error) {client?.fail(error);if (client !== undefined) return;+ const prerequisite = setupPrerequisiteOf(error);if (options.nonInteractive && error instanceof InteractionRequired) {logger.error(serializeHeadlessSetupEvent({@@ -142,13 +143,13 @@ export async function runIntegrationSetupCommand(}),);process.exitCode = 2;- } else if (options.nonInteractive && error instanceof SetupPrerequisiteRequired) {+ } else if (options.nonInteractive && prerequisite !== undefined) {logger.error(serializeHeadlessSetupEvent({version: 1,type: "blocked",status: "prerequisite_required",- prerequisite: error.prerequisite,+ prerequisite,}),);process.exitCode = 2;diff --git a/packages/eve/src/cli/commands/registry-declared-setups.ts b/packages/eve/src/cli/commands/registry-declared-setups.tsindex 34a446128..b744d3905 100644--- a/packages/eve/src/cli/commands/registry-declared-setups.ts+++ b/packages/eve/src/cli/commands/registry-declared-setups.ts@@ -3,11 +3,42 @@ import { createPrompter, type Prompter } from "#setup/prompter.js";import { WizardCancelledError } from "#setup/step.js";import { mergeRegistrySetupCompletions } from "#setup/registry-setup-completion.js";import type { RegistrySetupCompletion } from "#setup/registry-setup-protocol.js";+import {+ SetupPrerequisiteRequired,+ setupPrerequisiteOf,+ type SetupPrerequisite,+} from "#setup/integrations/shared/prerequisite.js";import type { RegistryCommandLogger, RegistrySetupDependencies } from "./registry.js";import type { RegistrySetupCommand } from "./registry-setup-command.js";import { headlessSetupContinuation, serializeHeadlessSetupEvent } from "./setup-headless.js";+/**+ * A declared setup that failed after the item's source was installed. Keeps+ * the original error as `cause` so interactive callers can report the item as+ * installed-but-not-set-up and recover from a structured prerequisite (for+ * example `vercel login`) instead of parsing the message.+ */+export class RegistrySetupFailedError extends Error {+ readonly item: string;+ readonly resumeCommand: string;+ /** The failure without the resume hint, for callers that render it separately. */+ readonly reason: string;++ constructor(input: { item: string; resumeCommand: string; cause: unknown }) {+ const reason = input.cause instanceof Error ? input.cause.message : String(input.cause);+ super(`${reason} Try again with \`${input.resumeCommand}\`.`, { cause: input.cause });+ this.name = "RegistrySetupFailedError";+ this.item = input.item;+ this.resumeCommand = input.resumeCommand;+ this.reason = reason;+ }++ get prerequisite(): SetupPrerequisite | undefined {+ return setupPrerequisiteOf(this.cause);+ }+}+interface DeclaredSetupOptions {yes?: boolean;force?: boolean;@@ -62,7 +93,12 @@ export async function runDeclaredSetups(input: {);if (result.kind === "cancelled") return false;if (result.kind === "blocked") {- if (!input.options.nonInteractive) throw new Error("Setup requires more input.");+ if (!input.options.nonInteractive) {+ if (result.blocker.status === "prerequisite_required") {+ throw new SetupPrerequisiteRequired(result.blocker.prerequisite);+ }+ throw new Error("Setup requires more input.");+ }input.logger.error(serializeHeadlessSetupEvent({version: 1,@@ -109,6 +145,10 @@ export async function runDeclaredSetups(input: {process.exitCode = 1;return false;}- throw new Error(`${message} Try again with \`${input.resumeCommand}\`.`);+ throw new RegistrySetupFailedError({+ item: input.item,+ resumeCommand: input.resumeCommand,+ cause: error,+ });}}diff --git a/packages/eve/src/cli/commands/registry-recovery.ts b/packages/eve/src/cli/commands/registry-recovery.tsindex 6e3647c22..1c681f193 100644--- a/packages/eve/src/cli/commands/registry-recovery.ts+++ b/packages/eve/src/cli/commands/registry-recovery.ts@@ -38,11 +38,13 @@ export async function runRegistryAction<T>(logger: RegistryCommandLogger,_appRoot: string,action: () => Promise<T>,+ options: { rethrow?: (error: unknown) => boolean } = {},): Promise<T | undefined> {try {return await action();} catch (error) {if (error instanceof WizardCancelledError) return undefined;+ if (options.rethrow?.(error) === true) throw error;logger.error(errorMessage(error));process.exitCode = 1;return undefined;diff --git a/packages/eve/src/cli/commands/registry.test.ts b/packages/eve/src/cli/commands/registry.test.tsindex 304fdd2e4..2e2f45634 100644--- a/packages/eve/src/cli/commands/registry.test.ts+++ b/packages/eve/src/cli/commands/registry.test.ts@@ -902,6 +902,68 @@ describe("registry commands", () => {});});+ it("returns setup blocked on a prerequisite after install as unfinished, not failed", async () => {+ const fake = createFakePrompter();+ const prerequisite = {+ kind: "command" as const,+ code: "vercel-login",+ message: "The Vercel CLI is not logged in.",+ command: "vercel login",+ };+ const runSetup = vi.fn(async () => ({+ kind: "blocked" as const,+ blocker: { status: "prerequisite_required" as const, prerequisite },+ }));+ getRegistryItems.mockResolvedValue([+ {+ meta: { eve: { setup: [{ package: "eve", bin: "eve", args: ["integration", "setup"] }] } },+ },+ ]);++ await expect(+ installRegistryItem(+ "/project",+ "connection/notion",+ { prompter: fake.prompter, silent: true },+ { loadSetupCommandRunner: async () => runSetup },+ ),+ ).resolves.toEqual({+ output: [],+ setupIncomplete: {+ resumeCommand: "eve add connection/notion --skip-install",+ reason: "The Vercel CLI is not logged in.",+ prerequisite,+ },+ });+ expect(addRegistryItems).toHaveBeenCalled();+ expect(process.exitCode).toBeUndefined();+ });++ it("keeps the CLI's setup failure message and resume hint", async () => {+ const logger = createLogger();+ const runSetup = vi.fn(async () => {+ throw new Error("vercel connect list exited with code 1.");+ });+ getRegistryItems.mockResolvedValue([+ {+ meta: { eve: { setup: [{ package: "@acme/slack", bin: "eve-slack", args: ["setup"] }] } },+ },+ ]);++ await runAddCommand(+ logger,+ "/project",+ "channel/slack",+ { yes: true },+ { loadSetupCommandRunner: async () => runSetup },+ );++ expect(logger.errors).toEqual([+ "vercel connect list exited with code 1. Try again with `eve add channel/slack --skip-install`.",+ ]);+ expect(process.exitCode).toBe(1);+ });+it("runs setup directly without installing the item", async () => {const logger = createLogger();const runSetup = vi.fn(async () => ({ kind: "completed" as const, facts: [] }));diff --git a/packages/eve/src/cli/commands/registry.ts b/packages/eve/src/cli/commands/registry.tsindex 13d08e00f..da6a83239 100644--- a/packages/eve/src/cli/commands/registry.ts+++ b/packages/eve/src/cli/commands/registry.ts@@ -7,13 +7,14 @@ import {} from "#compiled/shadcn-registry/index.js";import semver from "#compiled/semver/index.js";import { resolveInstalledPackageInfo } from "#internal/application/package.js";+import type { SetupPrerequisite } from "#setup/integrations/shared/prerequisite.js";import { createPrompter, type Prompter } from "#setup/prompter.js";import type { RegistrySetupCompletion } from "#setup/registry-setup-protocol.js";import { WizardCancelledError } from "#setup/step.js";import { hasInteractiveTerminal } from "./preconditions.js";import { installRegistryItemTransaction } from "./registry-install-transaction.js";-import { runDeclaredSetups } from "./registry-declared-setups.js";+import { RegistrySetupFailedError, runDeclaredSetups } from "./registry-declared-setups.js";import {errorMessage,reportRegistryCompletion as reportCompletion,@@ -44,6 +45,15 @@ import {} from "./registry-project.js";export { runRegistryAddCommand } from "./registry-add-command.js";export type { RegistryCommandLogger } from "./registry-recovery.js";+/** Source was installed, but the item's setup was cancelled, skipped, or failed. */+export interface RegistrySetupIncomplete {+ resumeCommand: string;+ /** Why setup failed; absent when it was cancelled or skipped. */+ reason?: string;+ /** A structured action that unblocks setup, such as `vercel login`. */+ prerequisite?: SetupPrerequisite;+}+export interface AddCommandOptions {skipInstall?: boolean;overwrite?: boolean;@@ -81,6 +91,8 @@ type RunAddCommandOptions = AddCommandOptions & {prompter?: Prompter;signal?: AbortSignal;setupAuthorized?: boolean;+ /** Throw {@link RegistrySetupFailedError} to the caller instead of logging it. */+ throwSetupFailures?: boolean;};/** One discoverable item from an eve-compatible registry catalog. */@@ -412,8 +424,7 @@ export async function installRegistryItem(): Promise<{output: readonly string[];setup?: RegistrySetupCompletion;- /** Files were added, but setup was cancelled or skipped. */- setupIncomplete?: { resumeCommand: string };+ setupIncomplete?: RegistrySetupIncomplete;}> {let failure: string | undefined;const output: string[] = [];@@ -424,17 +435,32 @@ export async function installRegistryItem(log: (message) => output.push(message),};const previousExitCode = process.exitCode;- const setup = await runAddCommand(- logger,- appRoot,- item,- {- ...options,- yes: options.prompter === undefined ? true : options.yes,- setupAuthorized: options.prompter !== undefined,- },- dependencies,- );+ let setup: Awaited<ReturnType<typeof runAddCommand>>;+ try {+ setup = await runAddCommand(+ logger,+ appRoot,+ item,+ {+ ...options,+ yes: options.prompter === undefined ? true : options.yes,+ setupAuthorized: options.prompter !== undefined,+ throwSetupFailures: true,+ },+ dependencies,+ );+ } catch (error) {+ process.exitCode = previousExitCode;+ if (!(error instanceof RegistrySetupFailedError)) throw error;+ // The source is already installed, so this is unfinished setup rather+ // than a failed add; keep the reason and any prerequisite for recovery.+ const incomplete: RegistrySetupIncomplete = {+ resumeCommand: error.resumeCommand,+ reason: error.reason,+ };+ if (error.prerequisite !== undefined) incomplete.prerequisite = error.prerequisite;+ return { output, setupIncomplete: incomplete };+ }process.exitCode = previousExitCode;if (failure !== undefined) throw new Error(failure);if (setup === false) throw new WizardCancelledError();@@ -459,7 +485,7 @@ export async function runAddCommand(if (options.silent !== true) logger.log(setupReminder(item, outcome));return "setup-incomplete" as const;};- return runRegistryAction(logger, appRoot, async () => {+ const action = async () => {const address = itemAddress(item);const projectRoot =address === itemAddress("channel/web") && options.skipInstall !== true@@ -594,6 +620,10 @@ export async function runAddCommand(});if (completion === false && !options.nonInteractive) return setupIncomplete("cancelled");return reportCompletion(logger, item, completion, options);+ };+ return runRegistryAction(logger, appRoot, action, {+ rethrow: (error) =>+ options.throwSetupFailures === true && error instanceof RegistrySetupFailedError,});}/** Lists registry items from every configured source or one selected source. */diff --git a/packages/eve/src/cli/dev/tui/registry-result-message.test.ts b/packages/eve/src/cli/dev/tui/registry-result-message.test.tsindex e792e214f..d792fa29e 100644--- a/packages/eve/src/cli/dev/tui/registry-result-message.test.ts+++ b/packages/eve/src/cli/dev/tui/registry-result-message.test.ts@@ -42,6 +42,7 @@ describe("registryCommandOutcome", () => {{kind: "incomplete",title: "channel/slack",+ address: "channel/slack",resumeCommand: "eve add channel/slack --skip-install",},],@@ -57,6 +58,27 @@ describe("registryCommandOutcome", () => {});});+ it("reports setup that failed after install as unfinished, with its reason", () => {+ expect(+ registryCommandOutcome({+ outcomes: [+ {+ kind: "incomplete",+ title: "connection/notion",+ address: "connection/notion",+ resumeCommand: "eve add connection/notion --skip-install",+ reason: "The Vercel CLI is not logged in.",+ },+ ],+ }),+ ).toEqual({+ failed: false,+ summary: "Added connection/notion · setup not finished",+ message:+ "The Vercel CLI is not logged in.\nFinish with `eve add connection/notion --skip-install`",+ });+ });+it("reports a cancellation before installation without detail", () => {expect(registryCommandOutcome({ outcomes: [{ kind: "cancelled", title: "connection/sentry" }] }),diff --git a/packages/eve/src/cli/dev/tui/registry-result-message.ts b/packages/eve/src/cli/dev/tui/registry-result-message.tsindex 6282500d2..40413ba67 100644--- a/packages/eve/src/cli/dev/tui/registry-result-message.ts+++ b/packages/eve/src/cli/dev/tui/registry-result-message.ts@@ -41,7 +41,10 @@ function outcomeDetails(outcome: RegistrySessionOutcome): string[] {];}case "incomplete":- return [`Finish with \`${outcome.resumeCommand}\``];+ return [+ ...(outcome.reason === undefined ? [] : [outcome.reason]),+ `Finish with \`${outcome.resumeCommand}\``,+ ];case "failed":return outcome.message.replace(" Try again with `", "\nTry again with `").split("\n");case "cancelled":diff --git a/packages/eve/src/cli/dev/tui/setup-commands.test.ts b/packages/eve/src/cli/dev/tui/setup-commands.test.tsindex ac58eb642..56c69515a 100644--- a/packages/eve/src/cli/dev/tui/setup-commands.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-commands.test.ts@@ -76,14 +76,13 @@ function run(input: {agentRoot?: string;useDefaultPrompter?: boolean;upgradeChoice?: "upgrade" | "later";+ loginChoice?: "login" | "later";withExclusiveTerminal?: TuiSetupCommandInput["withExclusiveTerminal"];initialRegistryAddress?: string;initialLoginConnection?: TuiSetupCommandInput["initialLoginConnection"];}) {- const { upgradeChoice } = input;- const fake = createFakePrompter(- upgradeChoice === undefined ? {} : { single: () => upgradeChoice },- );+ const choice = input.upgradeChoice ?? input.loginChoice;+ const fake = createFakePrompter(choice === undefined ? {} : { single: () => choice });const commandInput: TuiSetupCommandInput = {command: input.command,appRoot: APP_ROOT,@@ -209,6 +208,74 @@ describe("runTuiSetupCommand", () => {);});+ describe("setup blocked on a logged-out Vercel CLI", () => {+ const blocked = registryResult({+ outcomes: [+ {+ kind: "incomplete",+ title: "connection/notion",+ address: "connection/notion",+ resumeCommand: "eve add connection/notion --skip-install",+ reason: "The Vercel CLI is not logged in.",+ prerequisite: {+ kind: "command",+ code: "vercel-login",+ message: "The Vercel CLI is not logged in.",+ command: "vercel login",+ },+ },+ ],+ });++ it("logs in to the Vercel CLI and resumes only the item's setup", async () => {+ const runRegistryFlow = vi+ .fn<TuiSetupFlows["runRegistryFlow"]>()+ .mockResolvedValueOnce(blocked)+ .mockResolvedValueOnce(+ registryResult({+ outcomes: [{ kind: "installed", title: "connection/notion", facts: [], output: [] }],+ }),+ );+ const runLoginFlow = vi.fn<NonNullable<TuiSetupFlows["runLoginFlow"]>>(async () => ({+ kind: "logged-in",+ }));++ const outcome = await run({+ command: "add",+ initialRegistryAddress: "connection/notion",+ flows: fakeFlows({ runRegistryFlow, runLoginFlow }),+ loginChoice: "login",+ });++ expect(runLoginFlow).toHaveBeenCalledWith(expect.objectContaining({ appRoot: APP_ROOT }));+ expect(runRegistryFlow).toHaveBeenLastCalledWith(+ expect.objectContaining({ initialAddress: "connection/notion", skipInstall: true }),+ );+ expect(outcome).toMatchObject({ summary: "Added connection/notion" });+ expect(outcome.failed).toBeUndefined();+ });++ it("leaves the item installed with setup unfinished when login is declined", async () => {+ const runRegistryFlow = vi.fn<TuiSetupFlows["runRegistryFlow"]>(async () => blocked);+ const runLoginFlow = vi.fn<NonNullable<TuiSetupFlows["runLoginFlow"]>>();++ const outcome = await run({+ command: "add",+ initialRegistryAddress: "connection/notion",+ flows: fakeFlows({ runRegistryFlow, runLoginFlow }),+ loginChoice: "later",+ });++ expect(runLoginFlow).not.toHaveBeenCalled();+ expect(runRegistryFlow).toHaveBeenCalledOnce();+ expect(outcome).toMatchObject({+ summary: "Added connection/notion · setup not finished",+ message:+ "The Vercel CLI is not logged in.\nFinish with `eve add connection/notion --skip-install`",+ });+ });+ });+it("keeps flow warnings only as notes on the add outcome", async () => {const renderer = fakePanelRenderer();const runRegistryFlow = vi.fn<TuiSetupFlows["runRegistryFlow"]>(async ({ prompter }) => {@@ -218,6 +285,7 @@ describe("runTuiSetupCommand", () => {{kind: "incomplete",title: "channel/slack",+ address: "channel/slack",resumeCommand: "eve add channel/slack --skip-install",},],diff --git a/packages/eve/src/cli/dev/tui/setup-commands.ts b/packages/eve/src/cli/dev/tui/setup-commands.tsindex 706591efb..b6706d05e 100644--- a/packages/eve/src/cli/dev/tui/setup-commands.ts+++ b/packages/eve/src/cli/dev/tui/setup-commands.ts@@ -2,6 +2,7 @@ import type { ModelAccessChange, ModelConnectionSelection } from "#shared/model-import { runModelLogin } from "#setup/flows/model-login.js";import { LOGIN_CONNECTION_OPTIONS } from "#setup/flows/model-login-options.js";import { HumanActionRequiredError } from "#setup/human-action.js";+import { runLoginFlow } from "#setup/flows/login.js";import { runDeployFlow } from "#setup/flows/deploy.js";import {runInstallVercelCliFlow,@@ -70,6 +71,7 @@ export interface TuiSetupFlows {runInstallVercelCliFlow: typeof runInstallVercelCliFlow;runRegistryFlow: typeof runRegistryFlow;runDeployFlow: typeof runDeployFlow;+ runLoginFlow?: typeof runLoginFlow;}/** Setup owns flow-close behavior; the command adapter receives only the transcript outcome. */@@ -282,22 +284,31 @@ async function executeSetupCommand(};}case "add": {- const flow = await flows.runRegistryFlow({+ const runAdd = (overrides: { initialAddress?: string; skipInstall?: boolean }) =>+ flows.runRegistryFlow({+ appRoot,+ installRoot: input.agentRoot,+ prompter,+ signal,+ onScreen: input.onOnboardingScreen,+ onItemStart: registryItemProgress(renderer),+ runItem: runRegistryItem,+ ...overrides,+ });+ const flow = await runAdd({ initialAddress: input.initialRegistryAddress });+ if (flow.kind === "cancelled" || flow.result.outcomes.length === 0) {+ return cancelledSetupResult();+ }+ const result = await recoverVercelLoginSetup(flow.result, {appRoot,- installRoot: input.agentRoot,prompter,signal,- initialAddress: input.initialRegistryAddress,- onScreen: input.onOnboardingScreen,- onItemStart: registryItemProgress(renderer),- runItem: runRegistryItem,+ runLoginFlow: flows.runLoginFlow ?? runLoginFlow,+ resumeSetup: (address) => runAdd({ initialAddress: address, skipInstall: true }),});- if (flow.kind === "cancelled" || flow.result.outcomes.length === 0) {- return cancelledSetupResult();- }- const outcome = registryResult(flow.result, warnings);- if (flow.result.cancelled === true) outcome.partial = true;- if (flow.result.deployed === "production") outcome.effect = { kind: "deployed" };+ const outcome = registryResult(result, warnings);+ if (result.cancelled === true) outcome.partial = true;+ if (result.deployed === "production") outcome.effect = { kind: "deployed" };return outcome;}case "deploy": {@@ -422,6 +433,65 @@ function withRegistryResults(};}+/**+ * Offers `vercel login` when an installed item's setup stopped on a logged-out+ * Vercel CLI, then resumes only that item's setup. `/login` connects eve's+ * model access and does not log in the CLI that registry setup drives, so+ * without this the user is left retrying an add that can never succeed.+ */+async function recoverVercelLoginSetup(+ result: RegistrySessionResult,+ input: {+ appRoot: string;+ prompter: Prompter;+ signal: AbortSignal;+ runLoginFlow: typeof runLoginFlow;+ resumeSetup: (address: string) => ReturnType<typeof runRegistryFlow>;+ },+): Promise<RegistrySessionResult> {+ const blocked = result.outcomes.filter(+ (outcome) => outcome.kind === "incomplete" && outcome.prerequisite?.code === "vercel-login",+ );+ if (blocked.length === 0) return result;++ let choice: "login" | "later";+ try {+ choice = await input.prompter.select({+ message: "Setup needs the Vercel CLI, which isn't logged in. Log in now?",+ options: [+ {+ value: "login",+ label: "Log in to Vercel",+ description: "Runs `vercel login` in your browser, then finishes setup",+ },+ { value: "later", label: "Not now" },+ ],+ initialValue: "login",+ });+ } catch {+ choice = "later";+ }+ if (choice === "later") return result;++ const login = await input.runLoginFlow({+ appRoot: input.appRoot,+ prompter: input.prompter,+ signal: input.signal,+ });+ if (login.kind !== "logged-in" && login.kind !== "already") return result;++ const outcomes = [...result.outcomes];+ let deployed = result.deployed;+ for (const outcome of blocked) {+ if (outcome.kind !== "incomplete") continue;+ const resumed = await input.resumeSetup(outcome.address);+ if (resumed.kind !== "done" || resumed.result.outcomes.length !== 1) continue;+ outcomes[outcomes.indexOf(outcome)] = resumed.result.outcomes[0]!;+ deployed ??= resumed.result.deployed;+ }+ return { ...result, outcomes, ...(deployed !== undefined && { deployed }) };+}+/*** Offers to upgrade an old Vercel CLI when setup reports an unsupported* capability. This prompt is intentionally at the TUI boundary: shared setupdiff --git a/packages/eve/src/self-modification/extension/subagents/agent/instructions.ts b/packages/eve/src/self-modification/extension/subagents/agent/instructions.tsindex 68d36107e..e634e13ab 100644--- a/packages/eve/src/self-modification/extension/subagents/agent/instructions.ts+++ b/packages/eve/src/self-modification/extension/subagents/agent/instructions.ts@@ -23,7 +23,7 @@ For investigation tasks, report the findings and supporting evidence requested bconst localGuidance = `## Local environment-The registry_add tool will complete installation for items that need no setup. In the local dev TUI, a \`needs-terminal\` result from the tool call automatically opens the existing setup panel for the user to complete setup there. In headless development, if a \`needs-terminal\` result includes \`nextCommand\`, present that exact value as the only shell command in your response. Never infer, construct, or rewrite a command: installing an item uses \`eve add <item>\`; \`eve registry add\` configures registry namespace mappings and does not install items.+The registry_add tool will complete installation for items that need no setup. In the local dev TUI, a \`needs-terminal\` result queues the existing setup panel, which opens after your reply and reports the setup outcome itself. Until then nothing is installed: say that setup continues in the panel and never describe the item as added, connected, or set up. In headless development, if a \`needs-terminal\` result includes \`nextCommand\`, present that exact value as the only shell command in your response. Never infer, construct, or rewrite a command: installing an item uses \`eve add <item>\`; \`eve registry add\` configures registry namespace mappings and does not install items.Local eve dev logs are mounted read-only at /logs. Local trace segments are mounted read-only at /traces when available. For latency, failure, token, or behavior analysis, load and follow the \`trace_analysis\` skill. Trace searches are scoped to the invoking conversation and exclude the current investigation by default.diff --git a/packages/eve/src/self-modification/extension/subagents/agent/tools/registry_add.ts b/packages/eve/src/self-modification/extension/subagents/agent/tools/registry_add.tsindex 26d39666f..fb4c8c29d 100644--- a/packages/eve/src/self-modification/extension/subagents/agent/tools/registry_add.ts+++ b/packages/eve/src/self-modification/extension/subagents/agent/tools/registry_add.ts@@ -110,8 +110,10 @@ export function handoffMessage(input: {readonly title: string;}): { readonly message: string; readonly nextCommand?: string } {if (input.interactiveClient) {+ // The panel opens only after this turn ends, so nothing has happened yet.+ // The model must not report the item as added, connected, or opened.return {- message: `${input.title} was not installed by this tool. ${input.reason} Continue in the setup panel that opens here; do not ask the developer to run another command.`,+ message: `${input.title} has not been installed yet. ${input.reason} Its setup panel opens after this reply, asks for anything setup needs, and reports whether setup succeeded; tell the developer to complete it there, and do not describe ${input.title} as added, connected, or set up. Do not ask the developer to run another command.`,};}const nextCommand = `eve add ${input.address}`;diff --git a/packages/eve/src/self-modification/registry-add.test.ts b/packages/eve/src/self-modification/registry-add.test.tsindex 3a8e75b44..8658df297 100644--- a/packages/eve/src/self-modification/registry-add.test.ts+++ b/packages/eve/src/self-modification/registry-add.test.ts@@ -235,8 +235,9 @@ describe("addLocalRegistryItem", () => {});expect(result.nextCommand).toBeUndefined();- expect(result.message).toContain("setup panel");- expect(result.message).toContain("do not ask the developer to run another command");+ expect(result.message).toContain("has not been installed yet");+ expect(result.message).toContain("opens after this reply");+ expect(result.message).toContain("Do not ask the developer to run another command");});it("installs an exact item from a configured registry without restricting its address", async () => {diff --git a/packages/eve/src/setup/flows/registry-session.ts b/packages/eve/src/setup/flows/registry-session.tsindex 681233a04..99e9972d8 100644--- a/packages/eve/src/setup/flows/registry-session.ts+++ b/packages/eve/src/setup/flows/registry-session.ts@@ -1,3 +1,4 @@+import type { SetupPrerequisite } from "#setup/integrations/shared/prerequisite.js";import type { Prompter } from "#setup/prompter.js";import { detectDeployment } from "#setup/project-resolution.js";import type { RegistrySetupCompletion, RegistrySetupFact } from "#setup/registry-setup-protocol.js";@@ -16,8 +17,17 @@ export type RegistrySessionOutcome =facts: readonly RegistrySetupFact[];output: readonly string[];}- /** Files were added, but the item's setup was cancelled or skipped. */- | { kind: "incomplete"; title: string; resumeCommand: string }+ /** Files were added, but the item's setup was cancelled, skipped, or failed. */+ | {+ kind: "incomplete";+ title: string;+ /** Registry address, used to resume setup without reinstalling. */+ address: string;+ resumeCommand: string;+ /** Why setup failed; absent when it was cancelled or skipped. */+ reason?: string;+ prerequisite?: SetupPrerequisite;+ }/** User-facing installation error, including any actionable follow-up lines. */| { kind: "failed"; title: string; message: string }/** Stopped before anything was written. */@@ -33,7 +43,10 @@ export interface RegistrySessionResult {interface RegistrySession {add(title: string, output: readonly string[], setup?: RegistrySetupCompletion): void;- addIncomplete(title: string, resumeCommand: string): void;+ addIncomplete(+ title: string,+ incomplete: Omit<Extract<RegistrySessionOutcome, { kind: "incomplete" }>, "kind" | "title">,+ ): void;addFailure(title: string, message: string): void;addCancellation(title: string): void;result(deployed?: "production"): RegistrySessionResult;@@ -61,8 +74,8 @@ export function createRegistrySession(deps: RegistrySessionDeps): RegistrySessiodeploymentRequired ||= setup.deploymentRequired === true;},- addIncomplete(title, resumeCommand) {- outcomes.push({ kind: "incomplete", title, resumeCommand });+ addIncomplete(title, incomplete) {+ outcomes.push({ kind: "incomplete", title, ...incomplete });},addFailure(title, message) {diff --git a/packages/eve/src/setup/flows/registry.test.ts b/packages/eve/src/setup/flows/registry.test.tsindex 796286aa3..899c4b4a0 100644--- a/packages/eve/src/setup/flows/registry.test.ts+++ b/packages/eve/src/setup/flows/registry.test.ts@@ -139,6 +139,7 @@ describe("runRegistryFlow", () => {{kind: "incomplete",title: "channel/slack",+ address: "channel/slack",resumeCommand: "eve add channel/slack --skip-install",},],diff --git a/packages/eve/src/setup/flows/registry.ts b/packages/eve/src/setup/flows/registry.tsindex 043fe98e0..1eef07d91 100644--- a/packages/eve/src/setup/flows/registry.ts+++ b/packages/eve/src/setup/flows/registry.ts@@ -44,6 +44,8 @@ export async function runRegistryFlow(input: {signal?: AbortSignal;/** Registry item supplied by `/add <item>`, installed directly. */initialAddress?: string;+ /** Rerun the item's setup only; its source is already installed. */+ skipInstall?: boolean;onScreen?: (input: { screen: "registry_install"; registrySelectedCount?: number }) => void;onItemStart?: (item: Item, index: number, total: number) => void;/** Gives each installation its own cancellation boundary without ending the batch. */@@ -102,13 +104,17 @@ export async function runRegistryFlow(input: {const install = (signal = input.signal) =>installRegistryItem(installRoot, item.address, {silent: true,+ ...(input.skipInstall === true && { skipInstall: true }),prompter: input.prompter,signal,});const run = () => (input.runItem === undefined ? install() : input.runItem(install));const installed = await (input.prompter.withExclusiveTerminal?.(run) ?? run());if (installed.setupIncomplete !== undefined) {- activeSession.addIncomplete(label(item), installed.setupIncomplete.resumeCommand);+ activeSession.addIncomplete(label(item), {+ address: item.address,+ ...installed.setupIncomplete,+ });} else {activeSession.add(label(item), installed.output, installed.setup);}diff --git a/packages/eve/src/setup/integrations/shared/prerequisite.ts b/packages/eve/src/setup/integrations/shared/prerequisite.tsindex 4fc9abe46..c157649eb 100644--- a/packages/eve/src/setup/integrations/shared/prerequisite.ts+++ b/packages/eve/src/setup/integrations/shared/prerequisite.ts@@ -1,3 +1,5 @@+import { HumanActionRequiredError } from "../../human-action.js";+export type SetupPrerequisite =| { kind: "command"; code: string; message: string; command: string }| { kind: "environment"; code: string; message: string; variable: string; sensitive: true };@@ -12,3 +14,23 @@ export class SetupPrerequisiteRequired extends Error {this.prerequisite = prerequisite;}}++/**+ * The structured prerequisite behind a setup error, if any. Shared Vercel+ * provisioning steps throw {@link HumanActionRequiredError} (for example+ * `vercel login`); setup callers report it as a command prerequisite so the+ * action survives process and protocol boundaries instead of being flattened+ * into an unactionable message.+ */+export function setupPrerequisiteOf(error: unknown): SetupPrerequisite | undefined {+ if (error instanceof SetupPrerequisiteRequired) return error.prerequisite;+ if (error instanceof HumanActionRequiredError) {+ return {+ kind: "command",+ code: error.action.kind,+ message: error.action.reason,+ command: error.action.command,+ };+ }+ return undefined;+}diff --git a/packages/eve/src/setup/registry-setup-client.test.ts b/packages/eve/src/setup/registry-setup-client.test.tsindex bee215854..84e610287 100644--- a/packages/eve/src/setup/registry-setup-client.test.ts+++ b/packages/eve/src/setup/registry-setup-client.test.ts@@ -3,6 +3,7 @@ import { EventEmitter } from "node:events";import { afterEach, describe, expect, it, vi } from "vitest";import { InteractionRequired, select } from "./ask.js";+import { HumanActionRequiredError } from "./human-action.js";import { createRegistrySetupClient, type RegistrySetupClient } from "./registry-setup-client.js";import type { RegistrySetupChildMessage } from "./registry-setup-protocol.js";@@ -71,6 +72,35 @@ describe("createRegistrySetupClient", () => {});});+ it("reports a Vercel human action as a command prerequisite, not a flattened failure", () => {+ const processStub = new SetupProcessStub();+ const setup = client(processStub);++ setup.fail(+ new HumanActionRequiredError({+ kind: "vercel-login",+ command: "vercel login",+ reason: "The Vercel CLI is not logged in.",+ }),+ );++ expect(processStub.sent.at(-1)).toEqual({+ type: "result",+ outcome: {+ kind: "blocked",+ blocker: {+ status: "prerequisite_required",+ prerequisite: {+ kind: "command",+ code: "vercel-login",+ message: "The Vercel CLI is not logged in.",+ command: "vercel login",+ },+ },+ },+ });+ });+it("reports only the first terminal outcome", () => {const processStub = new SetupProcessStub();const setup = client(processStub);diff --git a/packages/eve/src/setup/registry-setup-client.ts b/packages/eve/src/setup/registry-setup-client.tsindex 1101b5c2e..e155ade16 100644--- a/packages/eve/src/setup/registry-setup-client.ts+++ b/packages/eve/src/setup/registry-setup-client.ts@@ -1,5 +1,5 @@import { InteractionRequired, InvalidAnswerError } from "./ask.js";-import { SetupPrerequisiteRequired } from "./integrations/shared/prerequisite.js";+import { setupPrerequisiteOf } from "./integrations/shared/prerequisite.js";import type {EditableSelectOptions,MultiSelectOptions,@@ -47,10 +47,8 @@ function registrySetupBlocker(issue: { code: "invalid_answer", message: error.message },};}- if (error instanceof SetupPrerequisiteRequired) {- return { status: "prerequisite_required", prerequisite: error.prerequisite };- }- return undefined;+ const prerequisite = setupPrerequisiteOf(error);+ return prerequisite === undefined ? undefined : { status: "prerequisite_required", prerequisite };}function registrySetupError(error: unknown): { message: string; details?: readonly string[] } {diff --git a/packages/eve/src/setup/vercel-project.test.ts b/packages/eve/src/setup/vercel-project.test.tsindex a1d4bebdf..c45595653 100644--- a/packages/eve/src/setup/vercel-project.test.ts+++ b/packages/eve/src/setup/vercel-project.test.ts@@ -19,6 +19,7 @@ import {pickTeam,requireAuth,resolveProjectByNameOrId,+ resolveTeam,validateTeam,} from "./vercel-project.js";@@ -85,7 +86,7 @@ describe("getVercelAuthStatus", () => {mockedCaptureVercel.mockResolvedValueOnce(captured("acme\n"));await expect(getVercelAuthStatus("/tmp/eve-agent")).resolves.toBe("authenticated");expect(mockedCaptureVercel).toHaveBeenCalledWith(- ["whoami"],+ ["whoami", "--format", "json"],expect.objectContaining({ cwd: "/tmp/eve-agent" }),);});@@ -96,17 +97,34 @@ describe("getVercelAuthStatus", () => {await expect(getVercelAuthStatus("/tmp/eve-agent")).resolves.toBe("authenticated");expect(mockedCaptureVercel).toHaveBeenCalledWith(- ["whoami", "--scope", "team_demo"],+ ["whoami", "--format", "json", "--scope", "team_demo"],expect.objectContaining({ cwd: "/tmp/eve-agent" }),);});it.each([+ ["no saved token (CLI 62)", '{\n "loggedIn": false\n}\n'],+ [+ "no saved token (agent error)",+ JSON.stringify({ loggedIn: false, status: "action_required", reason: "login_required" }),+ ],+ [+ "rejected token (agent error)",+ JSON.stringify({ status: "error", reason: "not_authorized", userActionRequired: true }),+ ],+ ])("reports logged-out from whoami's structured JSON: %s", async (_case, stdout) => {+ mockedCaptureVercel.mockResolvedValueOnce(failedCapture(stdout));+ await expect(getVercelAuthStatus("/tmp/eve-agent")).resolves.toBe("logged-out");+ });++ it.each([+ 'Error: No existing credentials found. Please run `vercel login` or pass "--token"',"Error: Not authenticated","Vercel CLI 62.1.0\nError: Not authorized","Error: The specified token is not valid. Use `vercel login` to generate a new token.",+ "Error: The token provided via VERCEL_TOKEN environment variable is not valid. Please provide a valid token.","Error: You do not have access to the specified account\nLearn More: https://err.sh/vercel/scope-not-accessible",- ])("reports logged-out for an authentication-recovery diagnostic: %s", async (stderr) => {+ ])("falls back to the diagnostic text when whoami prints no JSON: %s", async (stderr) => {mockedCaptureVercel.mockResolvedValueOnce(failedCapture("", stderr));await expect(getVercelAuthStatus("/tmp/eve-agent")).resolves.toBe("logged-out");});@@ -158,6 +176,16 @@ describe("requireAuth", () => {});});+describe("resolveTeam", () => {+ it("falls back to the whoami principal when no team is current", async () => {+ stubVercel({+ teams: [],+ whoami: JSON.stringify({ username: "alice", team: null, plan: "hobby" }),+ });+ await expect(resolveTeam("/tmp/eve-agent", undefined)).resolves.toBe("alice");+ });+});+describe("pickTeam", () => {it("shows a spinner around the team pull and stops it before selection", async () => {stubVercel({diff --git a/packages/eve/src/setup/vercel-project.ts b/packages/eve/src/setup/vercel-project.tsindex a21bbc385..66d5a4415 100644--- a/packages/eve/src/setup/vercel-project.ts+++ b/packages/eve/src/setup/vercel-project.ts@@ -128,7 +128,8 @@ export async function assertNewProjectNameAvailable(* API error and the user is already authenticated.*/function requireVercelLogin(failure?: VercelCaptureFailure): never {- const base = "Provisioning a Vercel project requires you to be logged in to Vercel.";+ const base =+ "The Vercel CLI is not logged in to an account with access to this project. Run `vercel login`.";const stderr = failure?.stderr.trim();const reason = failure? `${base} The Vercel CLI check did not succeed: ${failure.message}${stderr ? ` ${stderr}` : ""}`@@ -143,58 +144,125 @@ function requireVercelLogin(failure?: VercelCaptureFailure): never {*/const WHOAMI_TIMEOUT_MS = 10_000;+/**+ * Structured `vercel whoami --format json` output. A missing saved token is+ * `{ loggedIn: false }`; newer CLIs also report rejected credentials as an+ * agent error with a `reason`. Logged in, it carries the principal.+ */+const WhoamiJsonSchema = z.object({+ loggedIn: z.boolean().optional(),+ reason: z.string().optional(),+ username: z.string().optional(),+ app: z.object({ id: z.string() }).optional(),+});++const LOGIN_REQUIRED_REASONS = new Set([+ "login_required",+ "not_authorized",+ "scope_not_accessible",+]);++/** Reads whoami's JSON, tolerating CLIs that print it after a banner line or not at all. */+function parseWhoamiJson(stdout: string): z.infer<typeof WhoamiJsonSchema> | undefined {+ const start = stdout.indexOf("{");+ const end = stdout.lastIndexOf("}");+ if (start === -1 || end < start) return undefined;+ try {+ const parsed = WhoamiJsonSchema.safeParse(JSON.parse(stdout.slice(start, end + 1)));+ return parsed.success ? parsed.data : undefined;+ } catch {+ return undefined;+ }+}++type WhoamiProbe =+ | { status: "authenticated"; stdout: string }+ | {+ status: Exclude<VercelAuthStatus, "authenticated">;+ failure: VercelCaptureFailure;+ };+/*** Runs the bounded, read-only `vercel whoami` probe shared by the auth checks.* A linked team project is the user's explicit scope choice, so authenticate* against that owner instead of whichever account scope the CLI last selected.*/-async function probeWhoami(projectRoot: string, options: VercelProjectOperationOptions) {+async function probeWhoami(+ projectRoot: string,+ options: VercelProjectOperationOptions,+): Promise<WhoamiProbe> {const link = await readProjectLink(projectRoot);- const args = ["whoami", ...(link?.orgId.startsWith("team_") ? ["--scope", link.orgId] : [])];- return captureVercel(args, {+ const args = [+ "whoami",+ "--format",+ "json",+ ...(link?.orgId.startsWith("team_") ? ["--scope", link.orgId] : []),+ ];+ const result = await captureVercel(args, {cwd: projectRoot,signal: options.signal,timeoutMs: WHOAMI_TIMEOUT_MS,});+ options.signal?.throwIfAborted();+ if (result.ok) return { status: "authenticated", stdout: result.stdout };+ return { status: classifyWhoamiFailure(result.failure), failure: result.failure };+}++/**+ * Classifies a failed `whoami`. ENOENT means the binary isn't installed. The+ * CLI's structured JSON is authoritative for a logged-out session; only when it+ * gives none (rejected tokens on some CLI versions, CLIs without JSON output)+ * do we fall back to recognizing the diagnostic text. Anything unrecognized is+ * a transient fault (DNS, network, API error, timeout), never a login prompt.+ */+function classifyWhoamiFailure(+ failure: VercelCaptureFailure,+): Exclude<VercelAuthStatus, "authenticated"> {+ if (failure.errno === "ENOENT") return "cli-missing";+ const json = parseWhoamiJson(failure.stdout);+ if (+ json?.loggedIn === false ||+ (json?.reason !== undefined && LOGIN_REQUIRED_REASONS.has(json.reason))+ ) {+ return "logged-out";+ }+ return isLoggedOutDiagnostic(failure) ? "logged-out" : "unavailable";}/**- * Whether a failed `whoami` explicitly calls for authentication recovery- * rather than reporting a transient fault (DNS, network, API error, timeout).+ * Text fallback for CLIs that report a rejected or missing login without JSON.* Vercel reports an invalid stored token directly, but a linked team can mask* that diagnostic with `scope-not-accessible`; both require a fresh login.*/-function isLoggedOutFailure(failure: VercelCaptureFailure): boolean {+function isLoggedOutDiagnostic(failure: VercelCaptureFailure): boolean {const text = `${failure.stdout} ${failure.stderr}`.toLowerCase();return (text.includes("credentials") ||text.includes("not authenticated") ||text.includes("not authorized") ||text.includes("not logged in") ||- text.includes("specified token is not valid") ||+ /token\b.*\bis not valid/u.test(text) ||text.includes("scope-not-accessible") ||text.includes("do not have access to the specified account"));}/**- * Throws the right outcome for a failed `vercel whoami`. ENOENT means the- * binary isn't installed (its own action, not a login that would fail- * identically); the explicit not-authenticated diagnostic is a login action;- * anything else is a transient fault surfaced as a plain error, so the caller- * reports "try again" rather than mislabeling it "log in".+ * Throws the right outcome for a failed `vercel whoami`: a missing CLI and a+ * logged-out session are each their own action; anything else is a transient+ * fault surfaced as a plain error, so the caller reports "try again" rather+ * than mislabeling it "log in".*/-function requireVercelAuth(failure: VercelCaptureFailure): never {- if (failure.errno === "ENOENT") {+function requireVercelAuth(probe: Exclude<WhoamiProbe, { status: "authenticated" }>): never {+ const { failure } = probe;+ if (probe.status === "cli-missing") {throw new HumanActionRequiredError({kind: "vercel-cli-missing",command: "npm i -g vercel@latest",reason: failure.message,});}- if (isLoggedOutFailure(failure)) {- requireVercelLogin(failure);- }+ if (probe.status === "logged-out") requireVercelLogin(failure);const stderr = failure.stderr.trim();throw new Error(`Couldn't verify your Vercel login: ${failure.message}${stderr ? ` ${stderr}` : ""}`,@@ -205,8 +273,7 @@ function requireVercelAuth(failure: VercelCaptureFailure): never {* The Vercel auth state, read-only. `cli-missing` (ENOENT) and `unavailable` (a* transient network/API fault) are each kept distinct from `logged-out` so a* caller never tells the user to log in when the real cause is a missing CLI or- * an unreachable network. `logged-out` is claimed only from the explicit- * not-authenticated diagnostic.+ * an unreachable network.*/export type VercelAuthStatus = "authenticated" | "logged-out" | "cli-missing" | "unavailable";@@ -214,11 +281,7 @@ export async function getVercelAuthStatus(projectRoot: string,options: VercelProjectOperationOptions = {},): Promise<VercelAuthStatus> {- const result = await probeWhoami(projectRoot, options);- options.signal?.throwIfAborted();- if (result.ok) return "authenticated";- if (result.failure.errno === "ENOENT") return "cli-missing";- return isLoggedOutFailure(result.failure) ? "logged-out" : "unavailable";+ return (await probeWhoami(projectRoot, options)).status;}/**@@ -232,11 +295,8 @@ export async function requireAuth(options: VercelProjectOperationOptions = {},): Promise<void> {const check = async () => {- const result = await probeWhoami(projectRoot, options);- options.signal?.throwIfAborted();- if (!result.ok) {- requireVercelAuth(result.failure);- }+ const probe = await probeWhoami(projectRoot, options);+ if (probe.status !== "authenticated") requireVercelAuth(probe);};if (prompter === undefined) {await check();@@ -262,12 +322,10 @@ async function whoamiScope(projectRoot: string,options: VercelProjectOperationOptions,): Promise<string> {- const result = await probeWhoami(projectRoot, options);- options.signal?.throwIfAborted();- if (!result.ok) {- requireVercelAuth(result.failure);- }- return result.stdout.trim();+ const probe = await probeWhoami(projectRoot, options);+ if (probe.status !== "authenticated") requireVercelAuth(probe);+ const json = parseWhoamiJson(probe.stdout);+ return json?.username ?? json?.app?.id ?? probe.stdout.trim();}/**