The Open Framework for Building Agents
refactor(eve): prepare integration setup before apply (#1787)
OwenKephart4e433b5b08a6
diff --git a/.changeset/bright-setup-foundations.md b/.changeset/bright-setup-foundations.mdindex 8a763673e..d56d9308a 100644--- a/.changeset/bright-setup-foundations.md+++ b/.changeset/bright-setup-foundations.md@@ -2,4 +2,4 @@"eve": patch----Add wire-safe setup questions and shared interactive/headless prerequisite handling for answer-backed integration setup flows.+Update `eve add` to better support agent-based invocation of guided setup flows. Interactive setup links a Vercel project when needed; after each deployable setup, `/add` offers to add more by default, deploy to production, or finish.diff --git a/.changeset/tidy-add-deploy-loop.md b/.changeset/tidy-add-deploy-loop.mddeleted file mode 100644index 6b7951495..000000000--- a/.changeset/tidy-add-deploy-loop.md+++ /dev/null@@ -1,5 +0,0 @@-----"eve": patch------Let `/add` collect multiple deployable integrations before creating one production deployment. After each deployable setup, `/add` offers to add more by default, deploy to production, or finish, while keeping setup details for the final result.diff --git a/packages/eve/src/cli/commands/integration-setup.test.ts b/packages/eve/src/cli/commands/integration-setup.test.tsindex 2785d92ce..3b4bd605d 100644--- a/packages/eve/src/cli/commands/integration-setup.test.ts+++ b/packages/eve/src/cli/commands/integration-setup.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import { createFakePrompter } from "#internal/testing/fake-prompter.js";+import { ensureVercelProject } from "#setup/flows/ensure-vercel-project.js";import { runIntegrationSetup } from "#setup/integrations/runner.js";import { runIntegrationSetupCommand } from "./integration-setup.js";@@ -13,6 +14,7 @@ vi.mock("#setup/scaffold/index.js", async (importOriginal) => ({isEveProject,}));vi.mock("#setup/integrations/runner.js", () => ({ runIntegrationSetup: vi.fn() }));+vi.mock("#setup/flows/ensure-vercel-project.js", () => ({ ensureVercelProject: vi.fn() }));function logger(): RegistryCommandLogger & { errors: string[] } {const errors: string[] = [];@@ -45,9 +47,21 @@ describe("runIntegrationSetupCommand", () => {expect(runIntegrationSetup).toHaveBeenCalledWith("web",- expect.objectContaining({ appRoot: "/project", prompter: fake.prompter }),+ expect.objectContaining({+ appRoot: "/project",+ prompter: fake.prompter,+ resolveVercelProject: expect.any(Function),+ }),undefined,);+ const resolveVercelProject =+ vi.mocked(runIntegrationSetup).mock.calls[0]?.[1].resolveVercelProject;+ await resolveVercelProject?.("GitHub");+ expect(ensureVercelProject).toHaveBeenCalledWith({+ appRoot: "/project",+ prompter: fake.prompter,+ signal: undefined,+ });expect(output.errors).toEqual([]);});});diff --git a/packages/eve/src/cli/commands/integration-setup.ts b/packages/eve/src/cli/commands/integration-setup.tsindex fbde737bd..83cda88e6 100644--- a/packages/eve/src/cli/commands/integration-setup.ts+++ b/packages/eve/src/cli/commands/integration-setup.ts@@ -1,3 +1,4 @@+import { ensureVercelProject } from "#setup/flows/ensure-vercel-project.js";import { createPrompter, type Prompter } from "#setup/prompter.js";import { createRegistrySetupClient } from "#setup/registry-setup-client.js";import {@@ -43,8 +44,13 @@ export async function runIntegrationSetupCommand({appRoot,prompter,+ resolveVercelProject: () =>+ ensureVercelProject({+ appRoot,+ prompter,+ signal: client?.signal ?? options.signal,+ }),signal: client?.signal ?? options.signal,- yes: options.yes,},dependencies.runnerDeps,);diff --git a/packages/eve/src/setup/integrations/discord/setup.test.ts b/packages/eve/src/setup/integrations/discord/setup.test.tsindex 0436bdf3f..4bd33b8ac 100644--- a/packages/eve/src/setup/integrations/discord/setup.test.ts+++ b/packages/eve/src/setup/integrations/discord/setup.test.ts@@ -1,120 +1,67 @@import { describe, expect, it, vi } from "vitest";-import { createFakePrompter } from "#internal/testing/fake-prompter.js";-import type { Asker, Question } from "#setup/ask.js";+import { headlessAsker, withAnswers } from "#setup/ask.js";import { integrationSetupEnvironment } from "../shared/environment.js";-import { createIntegrationSetupUi } from "../shared/ui.js";-import { setupDiscord, type DiscordSetupDeps } from "./setup.js";--function asker(answers: Record<string, string>): Asker {- return {- ask: async <T>(question: Question<T>) => answers[question.key] as T,- askEditable: async () => {- throw new Error("Unexpected editable question");- },- askMany: async () => [],- };-}+import { createSetupContexts } from "../shared/ui.js";+import { applyDiscordSetup, prepareDiscordSetup, type DiscordSetupDeps } from "./setup.js";+const ANSWERS = {+ "discord-bot-token": " bot-token ",+ "discord-command-name": "ask",+ "discord-command-description": "Ask the eve agent",+};function deps(): DiscordSetupDeps {return {configureEndpoint: vi.fn(async () => {}),deriveConnectorSlug: vi.fn(async () => "agent" as never),- ensureVercelProject: vi.fn(async () => ({ orgId: "team-id", projectId: "project-id" })),- provisionConnector: vi.fn(async () => ({ id: "scl_discord", uid: "discord/agent" })),+ provisionConnector: vi.fn(async () => ({ id: "connector", uid: "discord/agent" })),registerCommand: vi.fn(async () => {}),- resolveApplication: vi.fn(async () => ({- id: "app-1",- name: "Agent",- publicKey: "public-key",- })),+ resolveApplication: vi.fn(async () => ({ id: "app", name: "Agent", publicKey: "key" })),writeTextFile: vi.fn(async () => {}),};}+function contexts(+ answers: Record<string, unknown>,+ resolveVercelProject = vi.fn(async () => ({ orgId: "team", projectId: "project" })),+) {+ return createSetupContexts({+ appRoot: "/project",+ asker: withAnswers(answers)(headlessAsker()),+ environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),+ prompter: createFakePrompter().prompter,+ resolveVercelProject,+ });+}describe("Discord setup", () => {- it("provisions Connect, registers the command and callback, and scaffolds the channel", async () => {- const fake = createFakePrompter();+ it("prepares all input before applying", async () => {const effects = deps();-- await expect(- setupDiscord(- {- appRoot: "/project",- environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),- ui: createIntegrationSetupUi({- asker: asker({- "discord-bot-token": " bot-token ",- "discord-command-name": "ask",- "discord-command-description": "Ask the eve agent",- }),- prompter: fake.prompter,- }),- },- effects,- ),- ).resolves.toMatchObject({ kind: "done" });-+ const ctx = contexts(ANSWERS);+ const plan = await prepareDiscordSetup(ctx.prepare, effects);+ expect(effects.resolveApplication).not.toHaveBeenCalled();+ await applyDiscordSetup(plan, ctx.apply, effects);expect(effects.resolveApplication).toHaveBeenCalledWith("bot-token");- expect(effects.provisionConnector).toHaveBeenCalledWith(- expect.objectContaining({ botToken: "bot-token" }),- );- expect(effects.registerCommand).toHaveBeenCalledWith("app-1", "bot-token", {- name: "ask",- description: "Ask the eve agent",- });- expect(effects.configureEndpoint).toHaveBeenCalledWith("bot-token", "scl_discord");expect(effects.writeTextFile).toHaveBeenCalledWith("/project/agent/channels/discord.ts",- expect.stringContaining('connectDiscordCredentials("discord/agent")'),+ expect.stringContaining("discord/agent"),{ force: undefined },);});-- it("prefills the command name and description", async () => {- const questions: Question<unknown>[] = [];+ it("refuses missing input before mutation", async () => {const effects = deps();- await setupDiscord(- {- appRoot: "/project",- environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),- ui: createIntegrationSetupUi({- asker: {- ask: async <T>(question: Question<T>) => {- questions.push(question as Question<unknown>);- if (question.key === "discord-bot-token") return "bot-token" as T;- return question.detected as T;- },- askEditable: async () => {- throw new Error("Unexpected editable question");- },- askMany: async () => [],- },- prompter: createFakePrompter().prompter,- }),- },- effects,- );-- expect(questions).toEqual(- expect.arrayContaining([- expect.objectContaining({ key: "discord-command-name", detected: "ask" }),- expect.objectContaining({- key: "discord-command-description",- detected: "Ask the eve agent",- }),- ]),- );+ await expect(prepareDiscordSetup(contexts({}).prepare, effects)).rejects.toMatchObject({+ prerequisite: { kind: "environment", variable: "DISCORD_BOT_TOKEN" },+ });+ expect(effects.resolveApplication).not.toHaveBeenCalled();});-- it("requires an authenticated Vercel CLI", async () => {- const fake = createFakePrompter();+ it("requires a linked project", async () => {+ const effects = deps();+ const resolveVercelProject = vi.fn(async () => {+ throw new Error("eve link");+ });await expect(- setupDiscord({- appRoot: "/project",- environment: integrationSetupEnvironment("logged-out", { kind: "unresolved" }),- ui: createIntegrationSetupUi({ asker: asker({}), prompter: fake.prompter }),- }),- ).rejects.toThrow("vercel login");+ prepareDiscordSetup(contexts(ANSWERS, resolveVercelProject).prepare, effects),+ ).rejects.toThrow("eve link");+ expect(effects.provisionConnector).not.toHaveBeenCalled();});});diff --git a/packages/eve/src/setup/integrations/discord/setup.ts b/packages/eve/src/setup/integrations/discord/setup.tsindex 330698510..698917a59 100644--- a/packages/eve/src/setup/integrations/discord/setup.ts+++ b/packages/eve/src/setup/integrations/discord/setup.ts@@ -1,15 +1,14 @@import { join } from "node:path";import { text } from "#setup/ask.js";-import { ensureVercelProject } from "#setup/flows/ensure-vercel-project.js";+import type { VercelProjectReference } from "#setup/project-resolution.js";import { deriveSlackConnectorSlug } from "#setup/scaffold/index.js";import { writeTextFile } from "#setup/scaffold/files.js";-import { WizardCancelledError } from "#setup/step.js";-import type {- IntegrationSetupContext,- IntegrationSetupResult,- SetupIntegration,+import {+ defineSetupIntegration,+ type SetupApplyContext,+ type SetupPrepareContext,} from "../types.js";import {configureDiscordInteractionsEndpoint,@@ -21,7 +20,6 @@ import { provisionDiscordConnector } from "./connect.js";export interface DiscordSetupDeps {configureEndpoint: typeof configureDiscordInteractionsEndpoint;deriveConnectorSlug: typeof deriveSlackConnectorSlug;- ensureVercelProject: typeof ensureVercelProject;provisionConnector: typeof provisionDiscordConnector;registerCommand: typeof registerDiscordCommand;resolveApplication: typeof resolveDiscordApplication;@@ -31,7 +29,6 @@ export interface DiscordSetupDeps {const defaultDeps: DiscordSetupDeps = {configureEndpoint: configureDiscordInteractionsEndpoint,deriveConnectorSlug: deriveSlackConnectorSlug,- ensureVercelProject,provisionConnector: provisionDiscordConnector,registerCommand: registerDiscordCommand,resolveApplication: resolveDiscordApplication,@@ -57,119 +54,114 @@ export default discordChannel({`;}-/** Runs guided Discord connector, command, and channel setup. */-export async function setupDiscord(- context: IntegrationSetupContext,+export interface DiscordSetupPlan {+ botToken: string;+ commandName: string;+ commandDescription: string;+ project: VercelProjectReference;+ slug: string;+}++export async function prepareDiscordSetup(+ context: SetupPrepareContext,deps: DiscordSetupDeps = defaultDeps,-): Promise<IntegrationSetupResult> {+): Promise<DiscordSetupPlan> {if (context.environment.vercel.kind === "unavailable") {throw new Error("Discord setup requires an authenticated Vercel CLI. Run `vercel login`, then retry.",);}- try {- const applicationInstructions = [- "Create a Discord application or open an existing one, then go to Bot → Reset Token and copy the new bot token.",- "Create: https://discord.com/developers/applications?new_application=true",- "Existing applications: https://discord.com/developers/applications",- ];- if (context.ui.prompter.acknowledge) {- await context.ui.prompter.acknowledge({- message: "Discord application",- lines: applicationInstructions,- });- } else {- context.ui.prompter.log.info(`Discord application\n${applicationInstructions.join("\n")}`);- }- const botToken = (- await context.ui.asker.ask(- text({- key: "discord-bot-token",- message: "Discord bot token",- required: true,- sensitive: true,- environment: "DISCORD_BOT_TOKEN",- }),- )- ).trim();- const commandName = await context.ui.asker.ask(- text({- key: "discord-command-name",- message: "Discord command name",- detected: "ask",- required: true,- validate: validateCommandName,- }),- );- const commandDescription = await context.ui.asker.ask(+ context.presenter.log.info(+ "Create a Discord application or open an existing one, then go to Bot → Reset Token and copy the new bot token.\nCreate: https://discord.com/developers/applications?new_application=true\nExisting applications: https://discord.com/developers/applications",+ );+ const botToken = (+ await context.asker.ask(text({- key: "discord-command-description",- message: "Discord command description",- detected: "Ask the eve agent",+ key: "discord-bot-token",+ message: "Discord bot token",required: true,- validate: (value) =>- value.trim().length === 0- ? "Command description is required."- : value.trim().length > 100- ? "Command description must be 100 characters or fewer."- : null,+ sensitive: true,+ environment: "DISCORD_BOT_TOKEN",}),- );- const application = await deps.resolveApplication(botToken);- const project = await deps.ensureVercelProject({- appRoot: context.appRoot,- prompter: context.ui.prompter,- signal: context.signal,- });- const connector = await deps.provisionConnector({- botToken,- log: context.ui.prompter.log,- project,- projectRoot: context.appRoot,- slug: await deps.deriveConnectorSlug(context.appRoot),- signal: context.signal,- });- await deps.registerCommand(application.id, botToken, {- name: commandName.trim(),- description: commandDescription.trim(),- });- // Connect configures this automatically when supported; the explicit call- // makes setup deterministic while older API deployments are still live.- await deps.configureEndpoint(botToken, connector.id);- await deps.writeTextFile(- join(context.appRoot, "agent/channels/discord.ts"),- connectTemplate(connector.uid),- { force: context.force },- );- const installUrl =- `https://discord.com/oauth2/authorize?client_id=${encodeURIComponent(application.id)}` +- `&scope=${encodeURIComponent("bot applications.commands")}&permissions=3072`;- context.ui.nextSteps([- `Install the Discord application, then try /${commandName.trim()}: ${installUrl}`,- ]);- return {- kind: "done",- completion: {- deploymentRequired: true,- facts: [- {- label: "Discord application dashboard",- value: `https://discord.com/developers/applications/${application.id}/information`,- kind: "url",- },- ],+ )+ ).trim();+ const commandName = await context.asker.ask(+ text({+ key: "discord-command-name",+ message: "Discord command name",+ detected: "ask",+ required: true,+ validate: validateCommandName,+ }),+ );+ const commandDescription = await context.asker.ask(+ text({+ key: "discord-command-description",+ message: "Discord command description",+ detected: "Ask the eve agent",+ required: true,+ validate: (value) =>+ value.trim().length === 0+ ? "Command description is required."+ : value.trim().length > 100+ ? "Command description must be 100 characters or fewer."+ : null,+ }),+ );+ const project = await context.resolveVercelProject("Discord");+ return {+ botToken,+ commandName: commandName.trim(),+ commandDescription: commandDescription.trim(),+ project,+ slug: await deps.deriveConnectorSlug(context.appRoot),+ };+}++export async function applyDiscordSetup(+ plan: DiscordSetupPlan,+ context: SetupApplyContext,+ deps: DiscordSetupDeps = defaultDeps,+) {+ const application = await deps.resolveApplication(plan.botToken);+ const connector = await deps.provisionConnector({+ botToken: plan.botToken,+ log: context.presenter.log,+ project: plan.project,+ projectRoot: context.appRoot,+ slug: plan.slug,+ signal: context.signal,+ });+ await deps.registerCommand(application.id, plan.botToken, {+ name: plan.commandName,+ description: plan.commandDescription,+ });+ await deps.configureEndpoint(plan.botToken, connector.id);+ await deps.writeTextFile(+ join(context.appRoot, "agent/channels/discord.ts"),+ connectTemplate(connector.uid),+ { force: context.force },+ );+ const installUrl = `https://discord.com/oauth2/authorize?client_id=${encodeURIComponent(application.id)}&scope=${encodeURIComponent("bot applications.commands")}&permissions=3072`;+ context.presenter.nextSteps([+ `Install the Discord application, then try /${plan.commandName}: ${installUrl}`,+ ]);+ return {+ deploymentRequired: true as const,+ facts: [+ {+ label: "Discord application dashboard",+ value: `https://discord.com/developers/applications/${application.id}/information`,+ kind: "url" as const,},- };- } catch (error) {- if (error instanceof WizardCancelledError) return { kind: "cancelled" };- throw error;- }+ ],+ };}-/** Discord setup registration. */-export const DISCORD_SETUP: SetupIntegration = {+export const DISCORD_SETUP = defineSetupIntegration({kind: "discord",label: "Discord",hint: "Slash commands and interactions",- setup: setupDiscord,-};+ prepare: prepareDiscordSetup,+ apply: applyDiscordSetup,+});diff --git a/packages/eve/src/setup/integrations/github/setup.test.ts b/packages/eve/src/setup/integrations/github/setup.test.tsindex e79b428ff..acb698bcc 100644--- a/packages/eve/src/setup/integrations/github/setup.test.ts+++ b/packages/eve/src/setup/integrations/github/setup.test.ts@@ -1,102 +1,59 @@import { describe, expect, it, vi } from "vitest";-import { createFakePrompter } from "#internal/testing/fake-prompter.js";-import type { Asker } from "#setup/ask.js";-+import { headlessAsker, InteractionRequired, withAnswers } from "#setup/ask.js";import { integrationSetupEnvironment } from "../shared/environment.js";-import { createIntegrationSetupUi } from "../shared/ui.js";-import { setupGitHub, type GitHubSetupDeps } from "./setup.js";+import { createSetupContexts } from "../shared/ui.js";+import { applyGitHubSetup, prepareGitHubSetup, type GitHubSetupDeps } from "./setup.js";function deps(): GitHubSetupDeps {return {deriveConnectorSlug: vi.fn(async () => "agent" as never),- ensureVercelProject: vi.fn(async () => ({ orgId: "team-id", projectId: "project-id" })),- provisionConnector: vi.fn(async () => ({- appSlug: "agent",- id: "scl_github",- uid: "github/agent",- })),+ provisionConnector: vi.fn(async () => ({ appSlug: "agent", id: "id", uid: "github/agent" })),writeTextFile: vi.fn(async () => {}),};}+function contexts(+ answers: Record<string, unknown>,+ resolveVercelProject = vi.fn(async () => ({ orgId: "team", projectId: "project" })),+) {+ return createSetupContexts({+ appRoot: "/project",+ asker: withAnswers(answers)(headlessAsker()),+ environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),+ prompter: createFakePrompter().prompter,+ resolveVercelProject,+ });+}describe("GitHub setup", () => {- function asker(events = ["issue_comment", "pull_request_review_comment"]): Asker {- return {- ask: vi.fn(),- askEditable: vi.fn(),- askMany: vi.fn(async () => events) as Asker["askMany"],- };- }-- it("provisions Connect, routes the selected webhooks, and scaffolds matching handlers", async () => {- const fake = createFakePrompter();+ it("prepares before provisioning and scaffolding", async () => {const effects = deps();- const selectedEvents = ["issue_comment", "issues", "pull_request"];-- await expect(- setupGitHub(- {- appRoot: "/project",- environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),- ui: createIntegrationSetupUi({ asker: asker(selectedEvents), prompter: fake.prompter }),- },- effects,- ),- ).resolves.toMatchObject({ kind: "done", completion: { deploymentRequired: true } });-- expect(effects.provisionConnector).toHaveBeenCalledWith(- expect.objectContaining({ events: selectedEvents }),- );+ const ctx = contexts({ "github-events": ["issue_comment", "issues"] });+ const plan = await prepareGitHubSetup(ctx.prepare, effects);+ expect(effects.provisionConnector).not.toHaveBeenCalled();+ await expect(applyGitHubSetup(plan, ctx.apply, effects)).resolves.toMatchObject({+ deploymentRequired: true,+ });expect(effects.writeTextFile).toHaveBeenCalledWith("/project/agent/channels/github.ts",- expect.stringContaining('connectGitHubCredentials("github/agent")'),+ expect.stringContaining("onIssue"),{ force: undefined },);- const scaffold = vi.mocked(effects.writeTextFile).mock.calls[0]?.[1] ?? "";- expect(scaffold).toContain('botName: "agent"');- expect(scaffold).toContain("onIssue(ctx, issue)");- expect(scaffold).toContain("onPullRequest(ctx, pullRequest)");});-- it("recommends comment events that the default scaffold handles", async () => {- const fake = createFakePrompter();- const askMany = vi.fn(async () => [- "issue_comment",- "pull_request_review_comment",- ]) as Asker["askMany"];-- await setupGitHub(- {- appRoot: "/project",- environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),- ui: createIntegrationSetupUi({- asker: { ask: vi.fn(), askEditable: vi.fn(), askMany },- prompter: fake.prompter,- }),- },- deps(),- );-- expect(askMany).toHaveBeenCalledWith(- expect.objectContaining({- key: "github-events",- recommended: ["issue_comment", "pull_request_review_comment"],- }),+ it("refuses missing input before discovery", async () => {+ const effects = deps();+ await expect(prepareGitHubSetup(contexts({}).prepare, effects)).rejects.toBeInstanceOf(+ InteractionRequired,);+ expect(effects.provisionConnector).not.toHaveBeenCalled();});-- it("requires an authenticated Vercel CLI", async () => {- const fake = createFakePrompter();- await expect(- setupGitHub({- appRoot: "/project",- environment: integrationSetupEnvironment("logged-out", { kind: "unresolved" }),- ui: createIntegrationSetupUi({- asker: asker(),- prompter: fake.prompter,- }),- }),- ).rejects.toThrow("vercel login");+ it("requires a linked project", async () => {+ const effects = deps();+ const resolveVercelProject = vi.fn(async () => {+ throw new Error("eve link");+ });+ const ctx = contexts({ "github-events": ["issue_comment"] }, resolveVercelProject);+ await expect(prepareGitHubSetup(ctx.prepare, effects)).rejects.toThrow("eve link");+ expect(effects.provisionConnector).not.toHaveBeenCalled();});});diff --git a/packages/eve/src/setup/integrations/github/setup.ts b/packages/eve/src/setup/integrations/github/setup.tsindex d79741193..4da1eed34 100644--- a/packages/eve/src/setup/integrations/github/setup.ts+++ b/packages/eve/src/setup/integrations/github/setup.ts@@ -1,28 +1,25 @@import { join } from "node:path";import type { MultiSelectQuestion } from "#setup/ask.js";-import { ensureVercelProject } from "#setup/flows/ensure-vercel-project.js";+import type { VercelProjectReference } from "#setup/project-resolution.js";import { deriveSlackConnectorSlug } from "#setup/scaffold/index.js";import { writeTextFile } from "#setup/scaffold/files.js";-import { WizardCancelledError } from "#setup/step.js";-import type {- IntegrationSetupContext,- IntegrationSetupResult,- SetupIntegration,+import {+ defineSetupIntegration,+ type SetupApplyContext,+ type SetupPrepareContext,} from "../types.js";import { provisionGitHubConnector } from "./connect.js";export interface GitHubSetupDeps {deriveConnectorSlug: typeof deriveSlackConnectorSlug;- ensureVercelProject: typeof ensureVercelProject;provisionConnector: typeof provisionGitHubConnector;writeTextFile: typeof writeTextFile;}const defaultDeps: GitHubSetupDeps = {deriveConnectorSlug: deriveSlackConnectorSlug,- ensureVercelProject,provisionConnector: provisionGitHubConnector,writeTextFile,};@@ -40,12 +37,7 @@ const GITHUB_EVENT_OPTIONS = [value: "pull_request_review_comment",hint: "Reply when a new inline review comment includes `@<bot-name>`.",},- {- id: "issues",- label: "New issues",- value: "issues",- hint: "Add comments to new issues.",- },+ { id: "issues", label: "New issues", value: "issues", hint: "Add comments to new issues." },{id: "pull_request",label: "New PRs",@@ -66,6 +58,7 @@ const githubEventsQuestion: MultiSelectQuestion<GitHubWebhookEvent> = {message: "What should this GitHub App respond to?",options: GITHUB_EVENT_OPTIONS,recommended: DEFAULT_GITHUB_EVENTS,+ required: true,requireSelection: true,};@@ -90,7 +83,6 @@ function connectTemplate(].filter((handler): handler is string => handler !== undefined);const defaultAuthImport = handlers.length > 0 ? ", defaultGitHubAuth" : "";const handlerBlock = handlers.length > 0 ? `\n${handlers.join("\n")}` : "";-return `import { connectGitHubCredentials } from "@vercel/connect/eve";import { githubChannel${defaultAuthImport} } from "eve/channels/github";@@ -101,62 +93,59 @@ export default githubChannel({`;}-/** Runs guided GitHub App connector and channel setup. */-export async function setupGitHub(- context: IntegrationSetupContext,+export interface GitHubSetupPlan {+ events: readonly GitHubWebhookEvent[];+ project: VercelProjectReference;+ slug: string;+}++export async function prepareGitHubSetup(+ context: SetupPrepareContext,deps: GitHubSetupDeps = defaultDeps,-): Promise<IntegrationSetupResult> {+): Promise<GitHubSetupPlan> {if (context.environment.vercel.kind === "unavailable") {throw new Error("GitHub setup requires an authenticated Vercel CLI. Run `vercel login`, then retry.",);}- try {- context.ui.prompter.log.info("GitHub App");- context.ui.prompter.log.info(- "Vercel Connect creates a GitHub App and routes verified webhooks to your deployed agent.",- );- const events = await context.ui.asker.askMany(githubEventsQuestion);- const project = await deps.ensureVercelProject({- appRoot: context.appRoot,- prompter: context.ui.prompter,- signal: context.signal,- });- const connector = await deps.provisionConnector({- log: context.ui.prompter.log,- events,- project,- projectRoot: context.appRoot,- slug: await deps.deriveConnectorSlug(context.appRoot),- signal: context.signal,- });- await deps.writeTextFile(- join(context.appRoot, "agent/channels/github.ts"),- connectTemplate(connector.uid, connector.appSlug, events),- { force: context.force },- );- const dashboardUrl = "https://vercel.com/d?to=/%5Bteam%5D/~/connect&title=Open+Vercel+Connect";- context.ui.nextSteps([- "Deploy the agent, then open the GitHub App in Vercel Connect and install it in the organization or account where you want to use it.",- `Add @${connector.appSlug} to a new issue, pull request, or review comment to invoke the agent. GitHub may not autocomplete or render the token as a linked mention.`,- ]);- return {- kind: "done",- completion: {- facts: [{ label: "GitHub App dashboard", value: dashboardUrl, kind: "url" }],- deploymentRequired: true,- },- };- } catch (error) {- if (error instanceof WizardCancelledError) return { kind: "cancelled" };- throw error;- }+ const events = await context.asker.askMany(githubEventsQuestion);+ const project = await context.resolveVercelProject("GitHub");+ return { events, project, slug: await deps.deriveConnectorSlug(context.appRoot) };+}++export async function applyGitHubSetup(+ plan: GitHubSetupPlan,+ context: SetupApplyContext,+ deps: GitHubSetupDeps = defaultDeps,+) {+ context.presenter.log.info("GitHub App");+ context.presenter.log.info(+ "Vercel Connect creates a GitHub App and routes verified webhooks to your deployed agent.",+ );+ const connector = await deps.provisionConnector({+ log: context.presenter.log,+ events: plan.events,+ project: plan.project,+ projectRoot: context.appRoot,+ slug: plan.slug,+ signal: context.signal,+ });+ await deps.writeTextFile(+ join(context.appRoot, "agent/channels/github.ts"),+ connectTemplate(connector.uid, connector.appSlug, plan.events),+ { force: context.force },+ );+ context.presenter.nextSteps([+ "Deploy the agent, then open the GitHub App in Vercel Connect and install it in the organization or account where you want to use it.",+ `Add @${connector.appSlug} to a new issue, pull request, or review comment to invoke the agent. GitHub may not autocomplete or render the token as a linked mention.`,+ ]);+ return { facts: [], deploymentRequired: true as const };}-/** GitHub App setup registration. */-export const GITHUB_SETUP: SetupIntegration = {+export const GITHUB_SETUP = defineSetupIntegration({kind: "github",label: "GitHub",hint: "Respond to issues, pull requests, and comments",- setup: setupGitHub,-};+ prepare: prepareGitHubSetup,+ apply: applyGitHubSetup,+});diff --git a/packages/eve/src/setup/integrations/linear/setup.test.ts b/packages/eve/src/setup/integrations/linear/setup.test.tsindex 10abcd272..582f9d077 100644--- a/packages/eve/src/setup/integrations/linear/setup.test.ts+++ b/packages/eve/src/setup/integrations/linear/setup.test.ts@@ -1,116 +1,69 @@import { describe, expect, it, vi } from "vitest";-import { createFakePrompter } from "#internal/testing/fake-prompter.js";-import type { Asker, Question } from "#setup/ask.js";-+import { headlessAsker, withAnswers, withPolicy } from "#setup/ask.js";import { integrationSetupEnvironment } from "../shared/environment.js";-import { createIntegrationSetupUi } from "../shared/ui.js";-import { linearSafeConnectorSlug, setupLinear, type LinearSetupDeps } from "./setup.js";+import { createSetupContexts } from "../shared/ui.js";+import {+ applyLinearSetup,+ linearSafeConnectorSlug,+ prepareLinearSetup,+ type LinearSetupDeps,+} from "./setup.js";function deps(): LinearSetupDeps {return {attachConnector: vi.fn(async () => {}),deriveConnectorSlug: vi.fn(async () => "agent" as never),- ensureVercelProject: vi.fn(async () => ({ orgId: "team-id", projectId: "project-id" })),findConnector: vi.fn(async () => undefined),- provisionConnector: vi.fn(async () => ({ id: "scl_linear", uid: "linear/agent" })),+ provisionConnector: vi.fn(async () => ({ id: "connector", uid: "linear/agent" })),writeTextFile: vi.fn(async () => {}),};}--function recommendedAsker(): Asker {- const ask = async <T>(question: Question<T>): Promise<T> => question.recommended as T;- const askEditable: Asker["askEditable"] = async () => {- throw new Error("Unexpected editable question");- };- const askMany: Asker["askMany"] = async () => [];- return { ask, askEditable, askMany };+function contexts(+ answers: Record<string, unknown> = {},+ resolveVercelProject = vi.fn(async () => ({ orgId: "team", projectId: "project" })),+) {+ return createSetupContexts({+ appRoot: "/project",+ asker: withAnswers(answers)(withPolicy("assume")(headlessAsker())),+ environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),+ prompter: createFakePrompter().prompter,+ resolveVercelProject,+ });}describe("Linear setup", () => {- it("removes Linear from managed app names", () => {+ it("normalizes connector names", () => {expect(linearSafeConnectorSlug("eve-linear-agent")).toBe("eve-agent");expect(linearSafeConnectorSlug("linear")).toBe("agent");});-- it("provisions Connect, routes Agent Session events, and scaffolds the channel", async () => {- const fake = createFakePrompter();+ it("prepares before provisioning", async () => {const effects = deps();-- const result = await setupLinear(- {- appRoot: "/project",- environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),- ui: createIntegrationSetupUi({ asker: recommendedAsker(), prompter: fake.prompter }),- },- effects,- );-- expect(result).toMatchObject({- kind: "done",- completion: {- facts: [- {- label: "Linear app dashboard",- value: "https://vercel.com/d?to=/%5Bteam%5D/~/connect&title=Open+Vercel+Connect",- kind: "url",- },- {- label: "Linear installation next step",- value:- "Deploy the agent, then open the Linear app in Vercel Connect and install it in the workspace where you want to delegate issues and comments.",- },- {- label: "How to invoke the Linear agent",- value:- "Delegate an issue or mention the agent in an Agent Session to start a conversation.",- },- { label: "Linear workspace", value: "https://linear.app", kind: "url" },- ],- },- });-+ const ctx = contexts();+ const plan = await prepareLinearSetup(ctx.prepare, effects);+ expect(effects.provisionConnector).not.toHaveBeenCalled();+ await applyLinearSetup(plan, ctx.apply, effects);expect(effects.provisionConnector).toHaveBeenCalledWith(expect.objectContaining({ slug: "agent" }),);- expect(effects.writeTextFile).toHaveBeenCalledWith(- "/project/agent/channels/linear.ts",- expect.stringContaining('connectLinearCredentials("linear/agent")'),- { force: undefined },- );});-- it("reuses an existing connector when selected", async () => {- const fake = createFakePrompter();+ it("prepares reuse without attaching", async () => {const effects = deps();- vi.mocked(effects.findConnector).mockResolvedValue({ id: "scl_existing", uid: "linear/agent" });- const asker = recommendedAsker();-- await expect(- setupLinear(- {- appRoot: "/project",- environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),- ui: createIntegrationSetupUi({ asker, prompter: fake.prompter }),- },- effects,- ),- ).resolves.toMatchObject({ kind: "done" });-- expect(effects.attachConnector).toHaveBeenCalledWith(- expect.objectContaining({ connector: { id: "scl_existing", uid: "linear/agent" } }),- );- expect(effects.provisionConnector).not.toHaveBeenCalled();+ vi.mocked(effects.findConnector).mockResolvedValue({ id: "existing", uid: "linear/agent" });+ const ctx = contexts({ "linear.existing-connector": "reuse" });+ const plan = await prepareLinearSetup(ctx.prepare, effects);+ expect(effects.attachConnector).not.toHaveBeenCalled();+ await applyLinearSetup(plan, ctx.apply, effects);+ expect(effects.attachConnector).toHaveBeenCalledOnce();});-- it("requires an authenticated Vercel CLI", async () => {- const fake = createFakePrompter();+ it("requires a linked project", async () => {+ const effects = deps();+ const resolveVercelProject = vi.fn(async () => {+ throw new Error("eve link");+ });await expect(- setupLinear({- appRoot: "/project",- environment: integrationSetupEnvironment("logged-out", { kind: "unresolved" }),- ui: createIntegrationSetupUi({ asker: recommendedAsker(), prompter: fake.prompter }),- }),- ).rejects.toThrow("vercel login");+ prepareLinearSetup(contexts({}, resolveVercelProject).prepare, effects),+ ).rejects.toThrow("eve link");+ expect(effects.findConnector).not.toHaveBeenCalled();});});diff --git a/packages/eve/src/setup/integrations/linear/setup.ts b/packages/eve/src/setup/integrations/linear/setup.tsindex efef30a33..dcfcce117 100644--- a/packages/eve/src/setup/integrations/linear/setup.ts+++ b/packages/eve/src/setup/integrations/linear/setup.ts@@ -1,15 +1,15 @@import { join } from "node:path";import { select, text } from "#setup/ask.js";-import { ensureVercelProject } from "#setup/flows/ensure-vercel-project.js";+import type { VercelProjectReference } from "#setup/project-resolution.js";import { deriveSlackConnectorSlug, normalizeSlackConnectorSlug } from "#setup/scaffold/index.js";import { writeTextFile } from "#setup/scaffold/files.js";import { WizardCancelledError } from "#setup/step.js";-import type {- IntegrationSetupContext,- IntegrationSetupResult,- SetupIntegration,+import {+ defineSetupIntegration,+ type SetupApplyContext,+ type SetupPrepareContext,} from "../types.js";import {attachLinearConnector,@@ -21,7 +21,6 @@ import {export interface LinearSetupDeps {attachConnector: typeof attachLinearConnector;deriveConnectorSlug: typeof deriveSlackConnectorSlug;- ensureVercelProject: typeof ensureVercelProject;findConnector: typeof findLinearConnector;provisionConnector: typeof provisionLinearConnector;writeTextFile: typeof writeTextFile;@@ -30,13 +29,11 @@ export interface LinearSetupDeps {const defaultDeps: LinearSetupDeps = {attachConnector: attachLinearConnector,deriveConnectorSlug: deriveSlackConnectorSlug,- ensureVercelProject,findConnector: findLinearConnector,provisionConnector: provisionLinearConnector,writeTextFile,};-/** Linear does not allow its brand name in a managed app's name. */export function linearSafeConnectorSlug(slug: string): string {const withoutLinear = slug.replaceAll(/linear/gi, "").replace(/[-_]{2,}/g, "-");return normalizeSlackConnectorSlug(withoutLinear || "agent");@@ -52,14 +49,28 @@ export default linearChannel({`;}-async function chooseConnector(- context: IntegrationSetupContext,- deps: LinearSetupDeps,- project: Awaited<ReturnType<typeof ensureVercelProject>>,-): Promise<LinearConnectorRef | undefined> {+type ConnectorPlan =+ | { kind: "reuse"; connector: LinearConnectorRef }+ | { kind: "create"; slug: string };++export interface LinearSetupPlan {+ connector: ConnectorPlan;+ project: VercelProjectReference;+}++export async function prepareLinearSetup(+ context: SetupPrepareContext,+ deps: LinearSetupDeps = defaultDeps,+): Promise<LinearSetupPlan> {+ if (context.environment.vercel.kind === "unavailable") {+ throw new Error(+ "Linear setup requires an authenticated Vercel CLI. Run `vercel login`, then retry.",+ );+ }+ const project = await context.resolveVercelProject("Linear");const defaultSlug = linearSafeConnectorSlug(await deps.deriveConnectorSlug(context.appRoot));const slug = linearSafeConnectorSlug(- await context.ui.asker.ask(+ await context.asker.ask(text({key: "linear.connector-name",message: "Name your Linear agent",@@ -75,109 +86,73 @@ async function chooseConnector(slug,signal: context.signal,});- if (existing !== undefined) {- const choice = await context.ui.asker.ask(- select({- key: "linear.existing-connector",- message: `A Linear connector named "${slug}" already exists. What would you like to do?`,- options: [- { id: "reuse", label: "Reuse existing connector", value: "reuse" as const },- { id: "new", label: "Create a new connector", value: "new" as const },- { id: "exit", label: "Exit setup", value: "exit" as const },- ],- recommended: "reuse" as const,+ if (existing === undefined) return { project, connector: { kind: "create", slug } };+ const choice = await context.asker.ask(+ select({+ key: "linear.existing-connector",+ message: `A Linear connector named "${slug}" already exists. What would you like to do?`,+ options: [+ { id: "reuse", label: "Reuse existing connector", value: "reuse" as const },+ { id: "new", label: "Create a new connector", value: "new" as const },+ { id: "exit", label: "Exit setup", value: "exit" as const },+ ],+ recommended: "reuse" as const,+ }),+ );+ if (choice === "exit") throw new WizardCancelledError();+ if (choice === "reuse") return { project, connector: { kind: "reuse", connector: existing } };+ const newSlug = linearSafeConnectorSlug(+ await context.asker.ask(+ text({+ key: "linear.new-connector-name",+ message: "Name the new Linear agent",+ recommended: `${slug}-2`,+ validate: (value) =>+ value.trim().length === 0 ? "A Linear agent name is required." : null,}),- );- if (choice === "exit") return undefined;- if (choice === "reuse") {- await deps.attachConnector({- connector: existing,- log: context.ui.prompter.log,- project,- projectRoot: context.appRoot,- signal: context.signal,- });- return existing;- }- }-- const connectorSlug =- existing === undefined- ? slug- : linearSafeConnectorSlug(- await context.ui.asker.ask(- text({- key: "linear.new-connector-name",- message: "Name the new Linear agent",- recommended: `${slug}-2`,- validate: (value) =>- value.trim().length === 0 ? "A Linear agent name is required." : null,- }),- ),- );- return deps.provisionConnector({- log: context.ui.prompter.log,- project,- projectRoot: context.appRoot,- slug: connectorSlug,- signal: context.signal,- });+ ),+ );+ return { project, connector: { kind: "create", slug: newSlug } };}-/** Runs guided Linear Agent Session connector and channel setup. */-export async function setupLinear(- context: IntegrationSetupContext,+export async function applyLinearSetup(+ plan: LinearSetupPlan,+ context: SetupApplyContext,deps: LinearSetupDeps = defaultDeps,-): Promise<IntegrationSetupResult> {- if (context.environment.vercel.kind === "unavailable") {- throw new Error(- "Linear setup requires an authenticated Vercel CLI. Run `vercel login`, then retry.",- );- }- try {- const project = await deps.ensureVercelProject({- appRoot: context.appRoot,- prompter: context.ui.prompter,- signal: context.signal,- });- const connector = await chooseConnector(context, deps, project);- if (connector === undefined) return { kind: "cancelled" };- await deps.writeTextFile(- join(context.appRoot, "agent/channels/linear.ts"),- connectTemplate(connector.uid),- { force: context.force },- );- const dashboardUrl = "https://vercel.com/d?to=/%5Bteam%5D/~/connect&title=Open+Vercel+Connect";- return {- kind: "done",- completion: {- facts: [- { label: "Linear app dashboard", value: dashboardUrl, kind: "url" },- {- label: "Linear installation next step",- value:- "Deploy the agent, then open the Linear app in Vercel Connect and install it in the workspace where you want to delegate issues and comments.",- },- {- label: "How to invoke the Linear agent",- value:- "Delegate an issue or mention the agent in an Agent Session to start a conversation.",- },- { label: "Linear workspace", value: "https://linear.app", kind: "url" },- ],- deploymentRequired: true,- },- };- } catch (error) {- if (error instanceof WizardCancelledError) return { kind: "cancelled" };- throw error;- }+) {+ const connector =+ plan.connector.kind === "reuse"+ ? (await deps.attachConnector({+ connector: plan.connector.connector,+ log: context.presenter.log,+ project: plan.project,+ projectRoot: context.appRoot,+ signal: context.signal,+ }),+ plan.connector.connector)+ : await deps.provisionConnector({+ log: context.presenter.log,+ project: plan.project,+ projectRoot: context.appRoot,+ slug: plan.connector.slug,+ signal: context.signal,+ });+ await deps.writeTextFile(+ join(context.appRoot, "agent/channels/linear.ts"),+ connectTemplate(connector.uid),+ { force: context.force },+ );+ context.presenter.nextSteps([+ "Deploy the agent, then open the Linear app in Vercel Connect and install it in the workspace where you want to delegate issues and comments.",+ "Delegate an issue or mention the agent in an Agent Session to start a conversation.",+ ]);+ return { facts: [], deploymentRequired: true as const };}-/** Linear Agent Session setup registration. */-export const LINEAR_SETUP: SetupIntegration = {+export const LINEAR_SETUP = defineSetupIntegration({kind: "linear",label: "Linear Agent",hint: "Delegate Linear issues and comments",- setup: setupLinear,-};+ prepare: prepareLinearSetup,+ apply: applyLinearSetup,+});diff --git a/packages/eve/src/setup/integrations/photon/setup-flow.test.ts b/packages/eve/src/setup/integrations/photon/setup-flow.test.tsindex 521ea18aa..a741bb372 100644--- a/packages/eve/src/setup/integrations/photon/setup-flow.test.ts+++ b/packages/eve/src/setup/integrations/photon/setup-flow.test.ts@@ -1,93 +1,73 @@import { describe, expect, it, vi } from "vitest";-import { createFakePrompter } from "#internal/testing/fake-prompter.js";--import type { Asker, Question } from "../../ask.js";+import { headlessAsker, InteractionRequired, withAnswers } from "#setup/ask.js";import { integrationSetupEnvironment } from "../shared/environment.js";-import { createIntegrationSetupUi } from "../shared/ui.js";-import { setupPhoton, type PhotonSetupDeps } from "./setup-flow.js";--function asker(answers: Record<string, string>): Asker {- return {- ask: async <T>(question: Question<T>) => answers[question.key] as T,- askEditable: async () => {- throw new Error("Unexpected editable question");- },- askMany: async () => [],- };-}+import { createSetupContexts } from "../shared/ui.js";+import { applyPhotonSetup, preparePhotonSetup, type PhotonSetupDeps } from "./setup-flow.js";+const ANSWERS = {+ "photon-credentials": "portable",+ "photon-project-source": "create",+ "photon-project-name": "Agent Messages",+ "photon-phone-number": "+15551234567",+};function deps(): PhotonSetupDeps {return {appendEnv: vi.fn(async () => ({ written: [], skipped: [] })),deriveConnectorSlug: vi.fn(async () => "agent" as never),- ensureVercelProject: vi.fn(async () => ({ orgId: "team-id", projectId: "project-id" })),findDedicatedLine: vi.fn(async () => undefined),openUrl: vi.fn(),- provisionConnector: vi.fn(),+ provisionConnector: vi.fn(async () => ({ id: "connector", uid: "photon/agent" })),provisionProject: vi.fn(async () => ({- projectId: "project-id",- projectSecret: "project-secret",+ projectId: "photon",+ projectSecret: "secret",cleanup: vi.fn(async () => {}),})),useProject: vi.fn(),writeTextFile: vi.fn(async () => {}),};}+function contexts(+ answers: Record<string, unknown>,+ auth: "authenticated" | "cli-missing" = "authenticated",+ resolveVercelProject = vi.fn(async () => ({ orgId: "team", projectId: "project" })),+) {+ return createSetupContexts({+ appRoot: "/project",+ asker: withAnswers(answers)(headlessAsker()),+ environment: integrationSetupEnvironment(auth, { kind: "unresolved" }),+ prompter: createFakePrompter().prompter,+ resolveVercelProject,+ });+}describe("Photon setup", () => {- it("scaffolds portable credentials when Vercel Connect is unavailable", async () => {- const fake = createFakePrompter({ single: () => "portable" });+ it("collects all decisions before mutation", async () => {const effects = deps();-await expect(- setupPhoton({- agentName: "agent",- projectPath: "/project",- environment: integrationSetupEnvironment("cli-missing", { kind: "unresolved" }),- ui: createIntegrationSetupUi({- asker: asker({ "photon-phone-number": "+15551234567" }),- prompter: fake.prompter,- }),- deps: effects,- }),- ).resolves.toMatchObject({ kind: "done" });-- expect(effects.appendEnv).toHaveBeenCalledWith("/project/.env.local", {- IMESSAGE_PROJECT_ID: "project-id",- IMESSAGE_PROJECT_SECRET: "project-secret",- });- expect(effects.provisionConnector).not.toHaveBeenCalled();- expect(effects.writeTextFile).toHaveBeenCalledWith(- "/project/agent/channels/photon.ts",- expect.stringContaining("IMESSAGE_WEBHOOK_SECRET"),- { force: undefined },- );+ preparePhotonSetup(+ contexts({ "photon-credentials": "portable", "photon-project-source": "create" }).prepare,+ effects,+ ),+ ).rejects.toBeInstanceOf(InteractionRequired);+ expect(effects.provisionProject).not.toHaveBeenCalled();+ expect(effects.writeTextFile).not.toHaveBeenCalled();});-- it("uses the agent name in the default Photon project name", async () => {- const fake = createFakePrompter({ single: () => "portable" });+ it("applies a portable plan", async () => {const effects = deps();-- await setupPhoton({- agentName: "weather-agent",- projectPath: "/project",- environment: integrationSetupEnvironment("cli-missing", { kind: "unresolved" }),- ui: createIntegrationSetupUi({- asker: asker({ "photon-phone-number": "+15551234567" }),- prompter: fake.prompter,- }),- deps: effects,- });-+ const ctx = contexts(ANSWERS, "cli-missing");+ const plan = await preparePhotonSetup(ctx.prepare, effects);+ expect(effects.provisionProject).not.toHaveBeenCalled();+ await applyPhotonSetup(plan, ctx.apply, effects);expect(effects.provisionProject).toHaveBeenCalledWith(- expect.objectContaining({ projectName: "eve · weather-agent" }),+ expect.objectContaining({ projectName: "Agent Messages" }),);+ expect(effects.appendEnv).toHaveBeenCalledWith("/project/.env.local", {+ IMESSAGE_PROJECT_ID: "photon",+ IMESSAGE_PROJECT_SECRET: "secret",+ });});-it("uses an existing dedicated project without asking for an operator number", async () => {- const answers: ("portable" | "existing")[] = ["portable", "existing"];- const fake = createFakePrompter({ single: () => answers.shift() ?? "existing" });const effects = deps();vi.mocked(effects.findDedicatedLine).mockResolvedValue("+15550000000");vi.mocked(effects.useProject).mockResolvedValue({@@ -96,22 +76,15 @@ describe("Photon setup", () => {assignedPhoneNumber: "+15550000000",cleanup: vi.fn(async () => {}),});+ const ctx = contexts({+ "photon-credentials": "portable",+ "photon-project-source": "existing",+ "photon-project-id": "project-id",+ "photon-project-secret": "project-secret",+ });- await expect(- setupPhoton({- agentName: "agent",- projectPath: "/project",- environment: integrationSetupEnvironment("cli-missing", { kind: "unresolved" }),- ui: createIntegrationSetupUi({- asker: asker({- "photon-project-id": "project-id",- "photon-project-secret": "project-secret",- }),- prompter: fake.prompter,- }),- deps: effects,- }),- ).resolves.toMatchObject({ kind: "done", assignedPhoneNumber: "+15550000000" });+ const plan = await preparePhotonSetup(ctx.prepare, effects);+ await applyPhotonSetup(plan, ctx.apply, effects);expect(effects.useProject).toHaveBeenCalledWith({projectId: "project-id",@@ -121,17 +94,21 @@ describe("Photon setup", () => {});});- it("requires Vercel login when Connect is selected without an authenticated CLI", async () => {- const fake = createFakePrompter({ single: () => "vercel" });-+ it("requires a linked project for Connect", async () => {+ const effects = deps();+ const resolveVercelProject = vi.fn(async () => {+ throw new Error("eve link");+ });await expect(- setupPhoton({- agentName: "agent",- projectPath: "/project",- environment: integrationSetupEnvironment("cli-missing", { kind: "unresolved" }),- ui: createIntegrationSetupUi({ asker: asker({}), prompter: fake.prompter }),- deps: deps(),- }),- ).rejects.toThrow("vercel login");+ preparePhotonSetup(+ contexts(+ { ...ANSWERS, "photon-credentials": "vercel" },+ "authenticated",+ resolveVercelProject,+ ).prepare,+ effects,+ ),+ ).rejects.toThrow("eve link");+ expect(effects.provisionProject).not.toHaveBeenCalled();});});diff --git a/packages/eve/src/setup/integrations/photon/setup-flow.ts b/packages/eve/src/setup/integrations/photon/setup-flow.tsindex f34bc653d..1c6564309 100644--- a/packages/eve/src/setup/integrations/photon/setup-flow.ts+++ b/packages/eve/src/setup/integrations/photon/setup-flow.ts@@ -1,7 +1,12 @@-import { join } from "node:path";+import { basename, join } from "node:path";-import { text } from "../../ask.js";+import { select, text } from "../../ask.js";import { appendEnv } from "../../append-env.js";+import type { VercelProjectReference } from "../../project-resolution.js";+import { openUrl } from "../../primitives/open-url.js";+import { deriveSlackConnectorSlug } from "../../scaffold/index.js";+import { writeTextFile } from "../../scaffold/files.js";+import type { SetupApplyContext, SetupPrepareContext } from "../types.js";import { provisionPhotonConnector } from "./connect.js";import {findDedicatedPhotonLine,@@ -10,40 +15,20 @@ import {validatePhotonPhoneNumber,type PhotonManagedProject,} from "./management.js";-import { openUrl } from "../../primitives/open-url.js";-import { deriveSlackConnectorSlug } from "../../scaffold/index.js";-import { writeTextFile } from "../../scaffold/files.js";-import { WizardCancelledError } from "../../step.js";-import type { IntegrationSetupEnvironment } from "../shared/environment.js";-import type { IntegrationSetupUi } from "../shared/ui.js";-import { ensureVercelProject } from "../../flows/ensure-vercel-project.js";-/** Inputs for Photon project provisioning and channel scaffolding. */-export interface PhotonSetupOptions {+export interface PhotonSetupPlan {agentName: string;- projectPath: string;- environment: IntegrationSetupEnvironment;- ui: IntegrationSetupUi;- signal?: AbortSignal;- force?: boolean;- deps?: PhotonSetupDeps;-}--/** Outcome of Photon project provisioning and channel scaffolding. */-export type PhotonSetupResult =- | { kind: "done"; assignedPhoneNumber?: string; dashboardUrl: string }- | { kind: "cancelled" };--interface PhotonSetupPlan {credentials: "vercel-connect" | "environment";photonProject: "create" | { projectId: string; projectSecret: string };photonProjectName?: string;+ dedicatedLine?: string;+ phoneNumber?: string;+ vercelProject?: VercelProjectReference;}export interface PhotonSetupDeps {appendEnv: typeof appendEnv;deriveConnectorSlug: typeof deriveSlackConnectorSlug;- ensureVercelProject: typeof ensureVercelProject;findDedicatedLine: typeof findDedicatedPhotonLine;openUrl: typeof openUrl;provisionConnector: typeof provisionPhotonConnector;@@ -55,7 +40,6 @@ export interface PhotonSetupDeps {const defaultDeps: PhotonSetupDeps = {appendEnv,deriveConnectorSlug: deriveSlackConnectorSlug,- ensureVercelProject,findDedicatedLine: findDedicatedPhotonLine,openUrl,provisionConnector: provisionPhotonConnector,@@ -89,48 +73,75 @@ export default photonIMessageChannel({`;}-async function choosePhotonProject(- options: PhotonSetupOptions,-): Promise<Pick<PhotonSetupPlan, "photonProject" | "photonProjectName">> {- const defaultName = `eve · ${options.agentName || "agent"}`;- const projectOptions = [- {+export async function preparePhotonSetup(+ context: SetupPrepareContext,+ deps: PhotonSetupDeps = defaultDeps,+): Promise<PhotonSetupPlan> {+ const agentName = basename(context.appRoot);+ const credentials = await context.asker.ask(+ select({+ key: "photon-credentials",+ message: "How would you like to configure Photon?",+ options: [+ {+ id: "vercel",+ value: "vercel-connect" as const,+ label: "Set up Vercel Connect",+ hint: "Use a linked Vercel project",+ },+ {+ id: "portable",+ value: "environment" as const,+ label: "Use portable credentials",+ hint: "Configure the Photon webhook manually after deployment",+ },+ ],+ recommended:+ context.environment.vercel.kind === "available"+ ? ("vercel-connect" as const)+ : ("environment" as const),+ required: true,+ }),+ );+ if (credentials === "vercel-connect" && context.environment.vercel.kind === "unavailable") {+ throw new Error(+ "Vercel Connect requires an authenticated Vercel CLI. Run `vercel login`, then retry Photon setup.",+ );+ }+ const defaultName = `eve · ${agentName || "agent"}`;+ const project = await context.asker.askEditable({+ key: "photon-project-source",+ message: "Photon project",+ options: [+ {+ id: "create",+ value: "create" as const,+ label: "Create a new Photon project",+ hint: `Name: ${defaultName}`,+ },+ {+ id: "existing",+ value: "existing" as const,+ label: "Use an existing Photon project",+ hint: "Enter its project credentials",+ },+ ],+ recommended: "create" as const,+ required: true,+ editable: {+ key: "photon-project-name",value: "create" as const,- label: "Create a new Photon project",- hint: `Name: ${defaultName}`,+ label: "Name",+ recommended: defaultName,+ validate: (value) => (value.trim().length === 0 ? "Project name cannot be empty." : null),},- {- value: "existing" as const,- label: "Use an existing Photon project",- hint: "Enter its project credentials",- },- ];- const editable = options.ui.prompter.selectEditable- ? await options.ui.prompter.selectEditable<"create" | "existing">({- message: "Photon project",- options: projectOptions,- initialValue: "create",- editable: {- value: "create",- defaultValue: defaultName,- formatHint: (value) => `Name: ${value}`,- validate: (value) =>- value.trim().length === 0 ? "Project name cannot be empty." : undefined,- },- })- : undefined;- const source =- editable?.value ??- (await options.ui.prompter.select<"create" | "existing">({- message: "Photon project",- options: projectOptions,- initialValue: "create",- }));- if (source === "existing") {- const projectId = await options.ui.asker.ask(+ });+ let photonProject: PhotonSetupPlan["photonProject"] = "create";+ if (project.value === "existing") {+ const projectId = await context.asker.ask(text({ key: "photon-project-id", message: "Photon project ID", required: true }),);- const projectSecret = await options.ui.asker.ask(+ const projectSecret = await context.asker.ask(text({key: "photon-project-secret",message: "Photon project secret",@@ -139,74 +150,63 @@ async function choosePhotonProject(environment: "IMESSAGE_PROJECT_SECRET",}),);- return { photonProject: { projectId: projectId.trim(), projectSecret: projectSecret.trim() } };+ photonProject = { projectId: projectId.trim(), projectSecret: projectSecret.trim() };}-- return {- photonProject: "create",- photonProjectName: editable?.kind === "edited" ? editable.text.trim() : defaultName,+ const dedicatedLine =+ photonProject === "create" ? undefined : await deps.findDedicatedLine(photonProject);+ const phoneNumber =+ dedicatedLine === undefined+ ? await context.asker.ask(+ text({+ key: "photon-phone-number",+ message: "Your iMessage phone number",+ placeholder: "+15551234567",+ required: true,+ validate: validatePhotonPhoneNumber,+ }),+ )+ : undefined;+ const vercelProject =+ credentials === "vercel-connect" ? await context.resolveVercelProject("Photon") : undefined;+ const plan: PhotonSetupPlan = {+ agentName,+ credentials,+ photonProject,+ dedicatedLine,+ phoneNumber,};-}--async function chooseSetupPlan(- options: PhotonSetupOptions,-): Promise<PhotonSetupPlan | "cancelled"> {- try {- const destination = await options.ui.prompter.select<"vercel" | "portable">({- message: "How would you like to configure Photon?",- options: [- {- value: "vercel",- label: "Set up Vercel Connect",- hint:- options.environment.vercel.kind === "available"- ? "Link this project and configure Photon automatically"- : "Log in to Vercel and link this project",- },- {- value: "portable",- label: "Use portable credentials",- hint: "Configure the Photon webhook manually after deployment",- },- ],- initialValue: options.environment.vercel.kind === "available" ? "vercel" : "portable",- });- if (destination === "vercel" && options.environment.vercel.kind === "unavailable") {- throw new Error(- "Vercel Connect requires an authenticated Vercel CLI. Run `vercel login`, then retry Photon setup.",- );- }- const photon = await choosePhotonProject(options);- return { credentials: destination === "vercel" ? "vercel-connect" : "environment", ...photon };- } catch (error) {- if (error instanceof WizardCancelledError) return "cancelled";- throw error;- }+ if (project.value === "create") plan.photonProjectName = project.text ?? defaultName;+ if (vercelProject !== undefined) plan.vercelProject = vercelProject;+ return plan;}async function resolvePhotonProject(- options: PhotonSetupOptions,plan: PhotonSetupPlan,- phoneNumber: string | undefined,- dedicatedLine: string | undefined,+ context: SetupApplyContext,deps: PhotonSetupDeps,): Promise<PhotonManagedProject> {- if (plan.photonProject !== "create") {- return deps.useProject({ ...plan.photonProject, dedicatedLine, phoneNumber });- }- if (phoneNumber === undefined) throw new Error("Photon phone number is required.");- const spinner = options.ui.prompter.log.spinner?.("Waiting for Photon approval…", {+ if (plan.photonProject !== "create")+ return deps.useProject({+ ...plan.photonProject,+ dedicatedLine: plan.dedicatedLine,+ phoneNumber: plan.phoneNumber,+ });+ if (plan.phoneNumber === undefined) throw new Error("Photon phone number is required.");+ const spinner = context.presenter.log.spinner?.("Waiting for Photon approval…", {kind: "external-action",emphasis: "browser",});try {return await deps.provisionProject({- projectName: plan.photonProjectName ?? `eve · ${options.agentName || "agent"}`,- phoneNumber,- signal: options.signal,+ projectName: plan.photonProjectName ?? `eve · ${plan.agentName || "agent"}`,+ phoneNumber: plan.phoneNumber,+ signal: context.signal,onAuthorization(authorization) {- options.ui.prompter.log.message(`Authorize Photon: ${authorization.verificationUrl}`);- options.ui.prompter.log.message(`Photon code: ${authorization.userCode}`);+ context.presenter.beginExternalAction({+ message: "Authorize Photon",+ url: authorization.verificationUrl,+ userCode: authorization.userCode,+ });deps.openUrl(authorization.verificationUrl);},});@@ -215,89 +215,62 @@ async function resolvePhotonProject(}}-async function scaffoldPhoton(- options: PhotonSetupOptions,+export async function applyPhotonSetup(plan: PhotonSetupPlan,- deps: PhotonSetupDeps,-): Promise<{ assignedPhoneNumber?: string; dashboardUrl: string }> {- const dedicatedLine =- plan.photonProject === "create" ? undefined : await deps.findDedicatedLine(plan.photonProject);- const phoneNumber =- plan.photonProject !== "create" && dedicatedLine !== undefined- ? undefined- : await options.ui.asker.ask(- text({- key: "photon-phone-number",- message: "Your iMessage phone number",- placeholder: "+15551234567",- required: true,- validate: validatePhotonPhoneNumber,- }),- );- const projectRoot = options.projectPath;- const managedProject = await resolvePhotonProject(- options,- plan,- phoneNumber,- dedicatedLine,- deps,- );+ context: SetupApplyContext,+ deps: PhotonSetupDeps = defaultDeps,+) {+ const managedProject = await resolvePhotonProject(plan, context, deps);try {- const channelPath = join(projectRoot, "agent/channels/photon.ts");+ const channelPath = join(context.appRoot, "agent/channels/photon.ts");if (plan.credentials === "vercel-connect") {- const slug = await deps.deriveConnectorSlug(projectRoot, options.agentName);- const project = await deps.ensureVercelProject({- appRoot: projectRoot,- prompter: options.ui.prompter,- signal: options.signal,- });+ const slug = await deps.deriveConnectorSlug(context.appRoot, plan.agentName);const connector = await deps.provisionConnector({credentials: managedProject,- log: options.ui.prompter.log,- project,- projectRoot,+ log: context.presenter.log,+ project: plan.vercelProject!,+ projectRoot: context.appRoot,slug,- signal: options.signal,+ signal: context.signal,});await deps.writeTextFile(channelPath, connectTemplate(connector.uid), {- force: options.force,+ force: context.force,});} else {- await deps.appendEnv(join(projectRoot, ".env.local"), {+ await deps.appendEnv(join(context.appRoot, ".env.local"), {IMESSAGE_PROJECT_ID: managedProject.projectId,IMESSAGE_PROJECT_SECRET: managedProject.projectSecret,});- await deps.writeTextFile(channelPath, PORTABLE_TEMPLATE, { force: options.force });- options.ui.nextSteps([+ await deps.writeTextFile(channelPath, PORTABLE_TEMPLATE, { force: context.force });+ context.presenter.nextSteps(["Deploy the agent, then create a Photon webhook pointing to https://<your-host>/eve/v1/photon.","Copy the webhook signing secret into IMESSAGE_WEBHOOK_SECRET, alongside IMESSAGE_PROJECT_ID and IMESSAGE_PROJECT_SECRET, in your host's encrypted environment variables.",]);}- options.ui.prompter.log.success("Scaffolded channel: photon");- if (managedProject.assignedPhoneNumber !== undefined) {- options.ui.prompter.note(managedProject.assignedPhoneNumber, "Text your agent", {+ context.presenter.log.success("Scaffolded channel: photon");+ if (managedProject.assignedPhoneNumber !== undefined)+ context.presenter.note(managedProject.assignedPhoneNumber, "Text your agent", {tone: "success",});- }const dashboardUrl = `https://app.photon.codes/dashboard/${managedProject.projectId}`;- options.ui.prompter.note(dashboardUrl, "Photon project", { tone: "success" });- return managedProject.assignedPhoneNumber === undefined- ? { dashboardUrl }- : { assignedPhoneNumber: managedProject.assignedPhoneNumber, dashboardUrl };+ context.presenter.note(dashboardUrl, "Photon project", { tone: "success" });+ return {+ facts: [+ { label: "Photon project dashboard", value: dashboardUrl, kind: "url" as const },+ ...(managedProject.assignedPhoneNumber === undefined+ ? []+ : [+ {+ label: "Agent phone number",+ value: managedProject.assignedPhoneNumber,+ kind: "phone" as const,+ },+ ]),+ ],+ deploymentRequired: true as const,+ };} catch (error) {await managedProject.cleanup().catch(() => {});throw error;}}--/** Provisions a Photon project and scaffolds its iMessage channel. */-export async function setupPhoton(options: PhotonSetupOptions): Promise<PhotonSetupResult> {- try {- const plan = await chooseSetupPlan(options);- if (plan === "cancelled") return { kind: "cancelled" };- return { kind: "done", ...(await scaffoldPhoton(options, plan, options.deps ?? defaultDeps)) };- } catch (error) {- if (error instanceof WizardCancelledError) return { kind: "cancelled" };- throw error;- }-}diff --git a/packages/eve/src/setup/integrations/photon/setup.ts b/packages/eve/src/setup/integrations/photon/setup.tsindex 90cd28cd5..73f1d5458 100644--- a/packages/eve/src/setup/integrations/photon/setup.ts+++ b/packages/eve/src/setup/integrations/photon/setup.ts@@ -1,41 +1,10 @@-import { basename } from "node:path";+import { defineSetupIntegration } from "../types.js";+import { applyPhotonSetup, preparePhotonSetup } from "./setup-flow.js";-import { setupPhoton } from "./setup-flow.js";--import type { SetupIntegration } from "../types.js";--/** Photon project provisioning and iMessage channel scaffolding. */-export const PHOTON_SETUP: SetupIntegration = {+export const PHOTON_SETUP = defineSetupIntegration({kind: "photon",label: "Photon",hint: "Messages through Photon",- async setup(context) {- const result = await setupPhoton({- agentName: basename(context.appRoot),- projectPath: context.appRoot,- environment: context.environment,- ui: context.ui,- signal: context.signal,- force: context.force,- });- if (result.kind === "cancelled") return result;- return {- kind: "done",- completion: {- deploymentRequired: true,- facts: [- ...(result.assignedPhoneNumber === undefined- ? []- : [- {- label: "Agent phone number",- value: result.assignedPhoneNumber,- kind: "phone" as const,- },- ]),- { label: "Photon project dashboard", value: result.dashboardUrl, kind: "url" as const },- ],- },- };- },-};+ prepare: preparePhotonSetup,+ apply: applyPhotonSetup,+});diff --git a/packages/eve/src/setup/integrations/registry.test.ts b/packages/eve/src/setup/integrations/registry.test.tsindex 893c8dbce..68fdec0af 100644--- a/packages/eve/src/setup/integrations/registry.test.ts+++ b/packages/eve/src/setup/integrations/registry.test.ts@@ -1,51 +1,38 @@import { describe, expect, it } from "vitest";-import { createFakePrompter } from "#internal/testing/fake-prompter.js";import type { Asker } from "#setup/ask.js";--import { integrationSetupEnvironment } from "./shared/environment.js";-import { setupIntegration } from "./registry.js";import { WizardCancelledError } from "../step.js";+import { setupIntegration } from "./registry.js";+import { integrationSetupEnvironment } from "./shared/environment.js";+import { createSetupContexts } from "./shared/ui.js";-const unusedAsker: Asker = {+const asker: Asker = {ask: async <T>() => undefined as T,- askEditable: async () => {- throw new Error("Unexpected editable question");- },+ askEditable: async <T>() => ({ value: undefined as T }),askMany: async () => [],};-function context(prompter = createFakePrompter().prompter) {- return {- appRoot: "/tmp/project",- environment: integrationSetupEnvironment("logged-out", { kind: "unresolved" } as const),- ui: {- asker: unusedAsker,- prompter,- confirm: async () => false,- nextSteps: () => {},- },- };-}-describe("setup integrations", () => {- it("keeps Slack credential-picker cancellation as a structured result", async () => {- const fake = createFakePrompter({- single: () => {+ it("folds prepare cancellation", async () => {+ const cancelling = {+ ...asker,+ ask: async () => {throw new WizardCancelledError();},+ };+ const contexts = createSetupContexts({+ appRoot: "/project",+ asker: cancelling,+ environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),+ prompter: createFakePrompter().prompter,+ resolveVercelProject: async () => ({ orgId: "team", projectId: "project" }),});-- await expect(setupIntegration("slack").setup(context(fake.prompter))).resolves.toEqual({- kind: "cancelled",- });+ await expect(setupIntegration("slack").run(contexts)).resolves.toEqual({ kind: "cancelled" });});-- it("registers guided GitHub setup", () => {+ it("registers GitHub", () => {expect(setupIntegration("github")).toMatchObject({ kind: "github", label: "GitHub" });});-- it("rejects an unknown integration", () => {+ it("rejects unknown integrations", () => {expect(() => setupIntegration("unknown")).toThrow('Integration setup "unknown" is not available',);diff --git a/packages/eve/src/setup/integrations/registry.ts b/packages/eve/src/setup/integrations/registry.tsindex eb3a46821..24a3a787e 100644--- a/packages/eve/src/setup/integrations/registry.ts+++ b/packages/eve/src/setup/integrations/registry.ts@@ -27,4 +27,4 @@ export function setupIntegration(kind: string): SetupIntegration {return integration;}-export { createIntegrationSetupUi } from "./shared/ui.js";+export { createSetupContexts, createSetupPresenter } from "./shared/ui.js";diff --git a/packages/eve/src/setup/integrations/runner.ts b/packages/eve/src/setup/integrations/runner.tsindex f41064648..7b30710e4 100644--- a/packages/eve/src/setup/integrations/runner.ts+++ b/packages/eve/src/setup/integrations/runner.ts@@ -1,5 +1,9 @@-import { interactiveAsker } from "#setup/ask.js";-import { detectDeployment, projectResolutionFromDeployment } from "#setup/project-resolution.js";+import { interactiveAsker, type Asker } from "#setup/ask.js";+import {+ detectDeployment,+ projectResolutionFromDeployment,+ type VercelProjectReference,+} from "#setup/project-resolution.js";import type { Prompter } from "#setup/prompter.js";import { getVercelAuthStatus } from "#setup/vercel-project.js";@@ -7,7 +11,8 @@ import {integrationSetupEnvironment,describeIntegrationSetupEnvironment,} from "./shared/environment.js";-import { createIntegrationSetupUi } from "./shared/ui.js";+import { resolveIntegrationVercelProject } from "./shared/vercel-project.js";+import { createSetupContexts } from "./shared/ui.js";import { setupIntegration } from "./registry.js";import type { IntegrationSetupResult } from "./types.js";@@ -15,11 +20,17 @@ import type { IntegrationSetupResult } from "./types.js";export interface RunIntegrationSetupOptions {appRoot: string;prompter: Prompter;+ /** Defaults to the interactive adapter; agent drivers inject an answer-backed asker. */+ asker?: Asker;signal?: AbortSignal;- yes?: boolean;+ force?: boolean;+ beginExternalAction?: (input: { url: string; userCode?: string; message: string }) => void;+ resolveVercelProject?: SetupProjectResolver;}/** Effects shared by the built-in integration setup runner. */+export type SetupProjectResolver = (integration: string) => Promise<VercelProjectReference>;+export interface IntegrationSetupRunnerDeps {detectDeployment: typeof detectDeployment;getVercelAuthStatus: typeof getVercelAuthStatus;@@ -46,15 +57,23 @@ export async function runIntegrationSetup(const project = projectResolutionFromDeployment(deployment);const environment = integrationSetupEnvironment(authStatus, project);options.prompter.log.info(describeIntegrationSetupEnvironment(environment));- const context = {- environment,- appRoot: options.appRoot,- ui: createIntegrationSetupUi({- asker: interactiveAsker(options.prompter),+ return integration.run(+ createSetupContexts({+ appRoot: options.appRoot,+ asker: options.asker ?? interactiveAsker(options.prompter),+ environment,prompter: options.prompter,+ resolveVercelProject:+ options.resolveVercelProject ??+ ((integration) =>+ resolveIntegrationVercelProject({+ appRoot: options.appRoot,+ integration,+ signal: options.signal,+ })),+ signal: options.signal,+ force: options.force,+ beginExternalAction: options.beginExternalAction,}),- yes: options.yes,- signal: options.signal,- };- return integration.setup(context);+ );}diff --git a/packages/eve/src/setup/integrations/shared/ui.test.ts b/packages/eve/src/setup/integrations/shared/ui.test.tsindex 3ccab13b8..e222a0b0b 100644--- a/packages/eve/src/setup/integrations/shared/ui.test.ts+++ b/packages/eve/src/setup/integrations/shared/ui.test.ts@@ -1,24 +1,29 @@-import { describe, expect, it } from "vitest";-+import { describe, expect, it, vi } from "vitest";import { createFakePrompter } from "#internal/testing/fake-prompter.js";+import { createSetupPresenter } from "./ui.js";-import { interactiveAsker } from "../../ask.js";-import { createIntegrationSetupUi } from "./ui.js";--describe("createIntegrationSetupUi", () => {- it("renders integration-owned next steps through the shared notice", () => {+describe("createSetupPresenter", () => {+ it("renders next steps as a note", () => {const fake = createFakePrompter();- const ui = createIntegrationSetupUi({- asker: interactiveAsker(fake.prompter),- prompter: fake.prompter,- });-- ui.nextSteps(["Set TOKEN in .env.local.", "Configure the webhook."]);-- expect(fake.prompter.note).toHaveBeenCalledWith(- "Set TOKEN in .env.local.\nConfigure the webhook.",+ createSetupPresenter(fake.prompter).nextSteps(["Deploy", "Open the app"]);+ expect(vi.mocked(fake.prompter.note)).toHaveBeenCalledWith(+ "Deploy\nOpen the app","Next steps",{ tone: "success" },);});++ it("announces when an external action begins", () => {+ const beginExternalAction = vi.fn();+ createSetupPresenter(createFakePrompter().prompter, beginExternalAction).beginExternalAction({+ message: "Authorize Photon",+ url: "https://example.com/authorize",+ userCode: "ABCD",+ });+ expect(beginExternalAction).toHaveBeenCalledWith({+ message: "Authorize Photon",+ url: "https://example.com/authorize",+ userCode: "ABCD",+ });+ });});diff --git a/packages/eve/src/setup/integrations/shared/ui.ts b/packages/eve/src/setup/integrations/shared/ui.tsindex d2fe9bc4a..108a65d4d 100644--- a/packages/eve/src/setup/integrations/shared/ui.ts+++ b/packages/eve/src/setup/integrations/shared/ui.ts@@ -1,32 +1,50 @@-import { confirm, SkippedSignal, type Asker } from "../../ask.js";+import type { Asker } from "../../ask.js";import type { Prompter } from "../../prompter.js";+import type { SetupApplyContext, SetupPrepareContext, SetupPresenter } from "../types.js";-/** UI capabilities available to a channel-owned setup hook. */-export interface IntegrationSetupUi {- readonly asker: Asker;- readonly prompter: Prompter;- confirm(input: { key: string; message: string; recommended?: boolean }): Promise<boolean>;- nextSteps(lines: readonly string[]): void;+export function createSetupPresenter(+ prompter: Prompter,+ beginExternalAction?: (input: { url: string; userCode?: string; message: string }) => void,+): SetupPresenter {+ return {+ log: prompter.log,+ note: prompter.note.bind(prompter),+ nextSteps(lines) {+ if (lines.length > 0) prompter.note(lines.join("\n"), "Next steps", { tone: "success" });+ },+ beginExternalAction(input) {+ if (beginExternalAction !== undefined) {+ beginExternalAction(input);+ return;+ }+ prompter.log.message(input.message);+ prompter.log.message(input.url);+ if (input.userCode !== undefined) prompter.log.message(`Code: ${input.userCode}`);+ },+ };}-/** Adapts the shared setup asker and prompter to the channel hook UI. */-export function createIntegrationSetupUi(input: {+export function createSetupContexts(input: {+ appRoot: string;asker: Asker;+ environment: SetupPrepareContext["environment"];prompter: Prompter;-}): IntegrationSetupUi {+ resolveVercelProject: SetupPrepareContext["resolveVercelProject"];+ signal?: AbortSignal;+ force?: boolean;+ beginExternalAction?: (input: { url: string; userCode?: string; message: string }) => void;+}): { prepare: SetupPrepareContext; apply: SetupApplyContext } {+ const presenter = createSetupPresenter(input.prompter, input.beginExternalAction);+ const apply: SetupApplyContext = { appRoot: input.appRoot, presenter };+ if (input.signal !== undefined) apply.signal = input.signal;+ if (input.force !== undefined) apply.force = input.force;return {- ...input,- async confirm(question) {- try {- return await input.asker.ask(confirm(question));- } catch (error) {- if (error instanceof SkippedSignal) return false;- throw error;- }- },- nextSteps(lines) {- if (lines.length === 0) return;- input.prompter.note(lines.join("\n"), "Next steps", { tone: "success" });+ prepare: {+ ...apply,+ asker: input.asker,+ environment: input.environment,+ resolveVercelProject: input.resolveVercelProject,},+ apply,};}diff --git a/packages/eve/src/setup/integrations/shared/vercel-project.test.ts b/packages/eve/src/setup/integrations/shared/vercel-project.test.tsnew file mode 100644index 000000000..380fb3c74--- /dev/null+++ b/packages/eve/src/setup/integrations/shared/vercel-project.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it, vi } from "vitest";+import { resolveIntegrationVercelProject } from "./vercel-project.js";++describe("resolveIntegrationVercelProject", () => {+ it("returns an existing project link", async () => {+ await expect(+ resolveIntegrationVercelProject({+ appRoot: "/project",+ integration: "Slack",+ deps: { readProjectLink: vi.fn(async () => ({ orgId: "team", projectId: "project" })) },+ }),+ ).resolves.toEqual({ orgId: "team", projectId: "project" });+ });+ it("requires the caller to link an unresolved project", async () => {+ await expect(+ resolveIntegrationVercelProject({+ appRoot: "/project",+ integration: "Slack",+ deps: { readProjectLink: vi.fn(async () => undefined) },+ }),+ ).rejects.toMatchObject({+ prerequisite: { kind: "command", code: "vercel-project-link", command: "eve link" },+ });+ });+});diff --git a/packages/eve/src/setup/integrations/shared/vercel-project.ts b/packages/eve/src/setup/integrations/shared/vercel-project.tsnew file mode 100644index 000000000..0c1293a5d--- /dev/null+++ b/packages/eve/src/setup/integrations/shared/vercel-project.ts@@ -0,0 +1,28 @@+import { readProjectLink, type VercelProjectReference } from "#setup/project-resolution.js";++import { SetupPrerequisiteRequired } from "./prerequisite.js";++export interface IntegrationVercelProjectDeps {+ readProjectLink: typeof readProjectLink;+}++const defaultDeps: IntegrationVercelProjectDeps = { readProjectLink };++/** Requires the caller to link a Vercel project before integration setup begins applying. */+export async function resolveIntegrationVercelProject(input: {+ appRoot: string;+ integration: string;+ signal?: AbortSignal;+ deps?: IntegrationVercelProjectDeps;+}): Promise<VercelProjectReference> {+ input.signal?.throwIfAborted();+ const project = await (input.deps ?? defaultDeps).readProjectLink(input.appRoot);+ if (project !== undefined) return project;++ throw new SetupPrerequisiteRequired({+ kind: "command",+ code: "vercel-project-link",+ message: `Vercel Connect setup requires a linked Vercel project. Run \`eve link\`, then retry ${input.integration} setup.`,+ command: "eve link",+ });+}diff --git a/packages/eve/src/setup/integrations/slack/setup.test.ts b/packages/eve/src/setup/integrations/slack/setup.test.tsindex cc7966238..82105017d 100644--- a/packages/eve/src/setup/integrations/slack/setup.test.ts+++ b/packages/eve/src/setup/integrations/slack/setup.test.ts@@ -1,57 +1,87 @@import { describe, expect, it, vi } from "vitest";-import { createFakePrompter } from "#internal/testing/fake-prompter.js";+import { headlessAsker, InteractionRequired, withAnswers, withPolicy } from "#setup/ask.js";import type { SlackConnectorSlug } from "#setup/scaffold/index.js";-import { integrationSetupEnvironment } from "../shared/environment.js";-import { createIntegrationSetupUi } from "../shared/ui.js";-import { setupSlack, type SlackSetupDeps } from "./setup.js";+import { createSetupContexts } from "../shared/ui.js";+import { applySlackSetup, prepareSlackSetup, type SlackSetupDeps } from "./setup.js";-describe("setupSlack", () => {- it("uses Vercel Connect without prompting for credentials in non-interactive mode", async () => {- const fake = createFakePrompter({- single: () => {- throw new Error("credential selection must not be prompted");- },- });- const provisionSlackbot = vi.fn(async () => ({+function channelResult() {+ return {+ kind: "slack" as const,+ action: "created" as const,+ filesWritten: [],+ filesOverwritten: [],+ filesSkipped: [],+ packageJsonUpdated: [],+ slackConnectorSlug: "agent" as SlackConnectorSlug,+ };+}+function deps(): SlackSetupDeps {+ return {+ deriveSlackConnectorSlug: vi.fn(async () => "agent" as SlackConnectorSlug),+ ensureChannel: vi.fn(async () => channelResult()),+ inspectConnectors: vi.fn(async () => ({+ state: "not-found" as const,+ connectorUids: new Set<string>(),+ })),+ provisionSlackbot: vi.fn(async () => ({state: "attached" as const,- connectorUid: "uid",- }));- const effects = {- deriveSlackConnectorSlug: vi.fn(async () => "agent" as SlackConnectorSlug),- ensureChannel: vi.fn(async () => ({- kind: "slack" as const,- action: "created" as const,- filesWritten: [],- filesOverwritten: [],- filesSkipped: [],- packageJsonUpdated: [],- slackConnectorSlug: "agent" as SlackConnectorSlug,- })),- ensureVercelProject: vi.fn(async () => ({ orgId: "org-id", projectId: "project-id" })),- provisionSlackbot,- reconcileSlackUid: vi.fn(),- } as SlackSetupDeps;+ connectorUid: "slack/agent",+ })),+ reconcileSlackUid: vi.fn(async () => true),+ };+}+function contexts(answers: Record<string, unknown>, assume = false) {+ const base = headlessAsker();+ return createSetupContexts({+ appRoot: "/project",+ asker: withAnswers(answers)(assume ? withPolicy("assume")(base) : base),+ environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),+ prompter: createFakePrompter().prompter,+ resolveVercelProject: vi.fn(async () => ({ orgId: "team", projectId: "project" })),+ });+}- await expect(- setupSlack(- {- appRoot: "/project",- environment: integrationSetupEnvironment("authenticated", { kind: "unresolved" }),- ui: createIntegrationSetupUi({- asker: { ask: vi.fn(), askEditable: vi.fn(), askMany: vi.fn() },- prompter: fake.prompter,- }),- yes: true,- },- effects,- ),- ).resolves.toEqual({- kind: "done",- completion: { facts: [], deploymentRequired: true },+describe("Slack setup", () => {+ it("accepts recommendations before apply", async () => {+ const effects = deps();+ const ctx = contexts({}, true);+ const plan = await prepareSlackSetup(ctx.prepare, effects);+ expect(effects.provisionSlackbot).not.toHaveBeenCalled();+ await applySlackSetup(plan, ctx.apply, effects);+ expect(effects.provisionSlackbot).toHaveBeenCalledOnce();+ });+ it("scaffolds portable credentials without provisioning", async () => {+ const effects = deps();+ const ctx = contexts({ "slack-credentials": "portable" });+ const plan = await prepareSlackSetup(ctx.prepare, effects);+ await applySlackSetup(plan, ctx.apply, effects);+ expect(effects.ensureChannel).toHaveBeenCalledWith(+ expect.objectContaining({ slackCredentials: "environment" }),+ );+ expect(effects.provisionSlackbot).not.toHaveBeenCalled();+ });+ it("refuses missing credentials before discovery", async () => {+ const effects = deps();+ await expect(prepareSlackSetup(contexts({}).prepare, effects)).rejects.toBeInstanceOf(+ InteractionRequired,+ );+ expect(effects.deriveSlackConnectorSlug).not.toHaveBeenCalled();+ });+ it("resolves connector choice during prepare", async () => {+ const connector = { id: "existing", uid: "slack/existing" };+ const effects = deps();+ vi.mocked(effects.inspectConnectors).mockResolvedValue({+ state: "found",+ connectors: [connector],+ preferred: connector,+ connectorUids: new Set([connector.uid]),});-- expect(provisionSlackbot).toHaveBeenCalledOnce();+ const ctx = contexts({ "slack-credentials": "vercel", "slack-connector": connector.uid });+ const plan = await prepareSlackSetup(ctx.prepare, effects);+ await applySlackSetup(plan, ctx.apply, effects);+ const options = vi.mocked(effects.provisionSlackbot).mock.calls[0]?.[4];+ expect(await options?.selectConnector?.([], undefined)).toBe(connector);});});diff --git a/packages/eve/src/setup/integrations/slack/setup.ts b/packages/eve/src/setup/integrations/slack/setup.tsindex 03fa584f8..ca412c85b 100644--- a/packages/eve/src/setup/integrations/slack/setup.ts+++ b/packages/eve/src/setup/integrations/slack/setup.ts@@ -1,23 +1,26 @@+import { select } from "#setup/ask.js";+import type { VercelProjectReference } from "#setup/project-resolution.js";import {deriveSlackConnectorSlug,ensureChannel,type SlackConnectorSlug,} from "#setup/scaffold/index.js";-import { ensureVercelProject } from "#setup/flows/ensure-vercel-project.js";import {+ inspectSlackbotConnectors,provisionSlackbot,reconcileSlackUid,- type ProvisionSlackbotOptions,type ProvisionSlackbotResult,+ type SlackConnectorRef,+ type SlackConnectorSelection,} from "#setup/slackbot.js";-import { WizardCancelledError } from "#setup/step.js";import { slackMessageDeepLink } from "#setup/slack-connect.js";+import { WizardCancelledError } from "#setup/step.js";import { installScaffoldDependencies, reportOverwrittenFiles } from "../shared/scaffold.js";-import type {- IntegrationSetupContext,- IntegrationSetupResult,- SetupIntegration,+import {+ defineSetupIntegration,+ type SetupApplyContext,+ type SetupPrepareContext,} from "../types.js";const SLACK_REQUIRES_VERCEL = "Slack setup with Vercel Connect requires a linked Vercel project.";@@ -74,11 +77,10 @@ function slackbotFailureCopy(result: SlackbotFailure): { reason: string; followU}}-/** Effects used by Slack setup. */export interface SlackSetupDeps {deriveSlackConnectorSlug: typeof deriveSlackConnectorSlug;ensureChannel: typeof ensureChannel;- ensureVercelProject: typeof ensureVercelProject;+ inspectConnectors: typeof inspectSlackbotConnectors;provisionSlackbot: typeof provisionSlackbot;reconcileSlackUid: typeof reconcileSlackUid;}@@ -86,172 +88,175 @@ export interface SlackSetupDeps {const defaultDeps: SlackSetupDeps = {deriveSlackConnectorSlug,ensureChannel,- ensureVercelProject,+ inspectConnectors: inspectSlackbotConnectors,provisionSlackbot,reconcileSlackUid,};-async function chooseCredentials(- context: IntegrationSetupContext,-): Promise<"vercel-connect" | "environment" | "cancelled"> {- if (context.yes) return "vercel-connect";- try {- return (await context.ui.prompter.select<"vercel" | "portable">({+type SlackSetupPlan =+ | { credentials: "environment"; slug: SlackConnectorSlug }+ | {+ credentials: "vercel-connect";+ slug: SlackConnectorSlug;+ project: VercelProjectReference;+ connector: SlackConnectorSelection;+ };++async function chooseConnector(+ context: SetupPrepareContext,+ connectors: readonly SlackConnectorRef[],+ preferred: SlackConnectorRef | undefined,+): Promise<SlackConnectorSelection> {+ if (connectors.length === 0) return "create";+ return context.asker.ask(+ select({+ key: "slack-connector",+ message: "Which Slack app would you like to use?",+ options: [+ ...connectors.map((connector) => ({+ id: connector.uid,+ value: connector,+ label: `Use ${connector.uid}`,+ hint: connector.uid === preferred?.uid ? "Matches this agent" : undefined,+ })),+ { id: "create", value: "create" as const, label: "Create a new Slack app" },+ ],+ recommended: preferred ?? connectors[0] ?? ("create" as const),+ required: true,+ }),+ );+}++export async function prepareSlackSetup(+ context: SetupPrepareContext,+ deps: SlackSetupDeps = defaultDeps,+): Promise<SlackSetupPlan> {+ const credentials = await context.asker.ask(+ select({+ key: "slack-credentials",message: "How would you like to configure Slack?",options: [- { value: "vercel", label: "Set up Vercel Connect", hint: "Sign in and link this project" },{- value: "portable",+ id: "vercel",+ value: "vercel-connect" as const,+ label: "Set up Vercel Connect",+ hint: "Use a linked Vercel project",+ },+ {+ id: "portable",+ value: "environment" as const,label: "Use portable credentials",hint: "Read Slack tokens from environment variables",},],- })) === "portable"- ? "environment"- : "vercel-connect";- } catch (error) {- if (error instanceof WizardCancelledError) return "cancelled";- throw error;- }-}--async function provisionSlack(- context: IntegrationSetupContext,- deps: SlackSetupDeps,- slug: SlackConnectorSlug,-): Promise<Extract<ProvisionSlackbotResult, { state: "attached" }>> {- const provisionOptions: ProvisionSlackbotOptions = {- selectConnector: async (connectors, preferred) => {- if (context.yes) return preferred ?? connectors[0]!;- const selected = await context.ui.prompter.select<string>({- message: "Which Slack app would you like to use?",- options: [- ...connectors.map((connector) => {- const option: { value: string; label: string; hint?: string } = {- value: connector.uid,- label: `Use ${connector.uid}`,- };- if (connector.uid === preferred?.uid) option.hint = "Matches this agent";- return option;- }),- { value: "create", label: "Create a new Slack app" },- ],- initialValue: preferred?.uid,- });- return selected === "create"- ? "create"- : connectors.find((connector) => connector.uid === selected)!;- },- };- if (context.signal !== undefined) provisionOptions.signal = context.signal;- if (context.ui.prompter.awaitChoice !== undefined) {- provisionOptions.awaitChoice = context.ui.prompter.awaitChoice;+ recommended: "vercel-connect" as const,+ required: true,+ }),+ );+ const slug = await deps.deriveSlackConnectorSlug(context.appRoot);+ if (credentials === "environment") return { credentials, slug };+ if (context.environment.vercel.kind === "unavailable") {+ throw new Error(+ "Vercel Connect requires an authenticated Vercel CLI. Run `vercel login`, then retry Slack setup.",+ );}- const result = await deps.provisionSlackbot(- context.ui.prompter.log,+ const project = await context.resolveVercelProject("Slack");+ if (project.projectId.length === 0) throw new Error(SLACK_REQUIRES_VERCEL);+ const lookup = await deps.inspectConnectors(+ context.presenter.log,context.appRoot,slug,- undefined,- provisionOptions,+ context.signal,);- context.signal?.throwIfAborted();- if (result.state === "cancelled") throw new WizardCancelledError();- if (result.state !== "attached") {- const copy = slackbotFailureCopy(result);- throw new Error(`${copy.reason} ${copy.followUp}`);- }- return result;+ const connector =+ lookup.state === "found"+ ? await chooseConnector(context, lookup.connectors, lookup.preferred)+ : "create";+ return { credentials, slug, project, connector };}-/** Runs the Slack setup flow. Exported for direct integration tests. */-export async function setupSlack(- context: IntegrationSetupContext,+export async function applySlackSetup(+ plan: SlackSetupPlan,+ context: SetupApplyContext,deps: SlackSetupDeps = defaultDeps,-): Promise<IntegrationSetupResult> {- const credentials = await chooseCredentials(context);- if (credentials === "cancelled") return { kind: "cancelled" };- if (credentials === "vercel-connect" && context.environment.vercel.kind === "unavailable") {- throw new Error(- "Vercel Connect requires an authenticated Vercel CLI. Run `vercel login`, then retry Slack setup.",- );- }-- const slug = await deps.deriveSlackConnectorSlug(context.appRoot);- if (credentials === "environment") {+) {+ if (plan.credentials === "environment") {const result = await deps.ensureChannel({projectRoot: context.appRoot,kind: "slack",- slackConnectorSlug: slug,+ slackConnectorSlug: plan.slug,slackCredentials: "environment",force: context.force,skipDependencyMutation: true,});- reportOverwrittenFiles(context.ui.prompter.log, result.filesOverwritten);- context.ui.prompter.log.success("Scaffolded channel: slack");- context.ui.nextSteps([+ reportOverwrittenFiles(context.presenter.log, result.filesOverwritten);+ context.presenter.log.success("Scaffolded channel: slack");+ context.presenter.nextSteps(["Set SLACK_BOT_TOKEN and SLACK_SIGNING_SECRET in .env.local (listed in .env.example).","Configure your Slack app to send events to /eve/v1/slack on your public agent URL.",]);- return {- kind: "done",- completion: { facts: [], deploymentRequired: true },- };+ return { facts: [], deploymentRequired: true as const };}-- const project = await deps.ensureVercelProject({- appRoot: context.appRoot,- prompter: context.ui.prompter,- signal: context.signal,- });- if (project.projectId.length === 0) throw new Error(SLACK_REQUIRES_VERCEL);- const slackbot = await provisionSlack(context, deps, slug);- const result = await deps.ensureChannel({+ const result = await deps.provisionSlackbot(+ context.presenter.log,+ context.appRoot,+ plan.slug,+ undefined,+ {+ signal: context.signal,+ selectConnector: async () => plan.connector,+ },+ );+ context.signal?.throwIfAborted();+ if (result.state === "cancelled") throw new WizardCancelledError();+ if (result.state !== "attached") {+ const copy = slackbotFailureCopy(result);+ throw new Error(`${copy.reason} ${copy.followUp}`);+ }+ const channel = await deps.ensureChannel({projectRoot: context.appRoot,kind: "slack",- slackConnectorUid: slackbot.connectorUid,- slackConnectorSlug: slug,+ slackConnectorUid: result.connectorUid,+ slackConnectorSlug: plan.slug,force: context.force,skipDependencyMutation: true,});- reportOverwrittenFiles(context.ui.prompter.log, result.filesOverwritten);- if (result.action === "skipped") {+ reportOverwrittenFiles(context.presenter.log, channel.filesOverwritten);+ if (channel.action === "skipped") {const ready = await deps.reconcileSlackUid(- context.ui.prompter.log,+ context.presenter.log,context.appRoot,- slackbot,- `slack/${slug}`,+ result,+ `slack/${plan.slug}`,);if (!ready) throw new Error("Slack connector UID update is required before deployment.");}- context.ui.prompter.log.success("Scaffolded channel: slack");+ context.presenter.log.success("Scaffolded channel: slack");await installScaffoldDependencies({- changed: result.packageJsonUpdated.length > 0,- log: context.ui.prompter.log,+ changed: channel.packageJsonUpdated.length > 0,+ log: context.presenter.log,projectPath: context.appRoot,signal: context.signal,});return {- kind: "done",- completion: {- facts:- slackbot.chatUrl === undefined- ? []- : [- {- label: "Agent Slack DM",- value: slackMessageDeepLink(slackbot.chatUrl),- kind: "url",- },- ],- deploymentRequired: true,- },+ facts:+ result.chatUrl === undefined+ ? []+ : [+ {+ label: "Agent Slack DM",+ value: slackMessageDeepLink(result.chatUrl),+ kind: "url" as const,+ },+ ],+ deploymentRequired: true as const,};}-/** Slack setup registration. */-export const SLACK_SETUP: SetupIntegration = {+export const SLACK_SETUP = defineSetupIntegration({kind: "slack",label: "Slack",hint: "Slack app mentions and DMs",- setup: setupSlack,-};+ prepare: prepareSlackSetup,+ apply: applySlackSetup,+});diff --git a/packages/eve/src/setup/integrations/types.ts b/packages/eve/src/setup/integrations/types.tsindex de4ced18f..d5331e188 100644--- a/packages/eve/src/setup/integrations/types.ts+++ b/packages/eve/src/setup/integrations/types.ts@@ -1,27 +1,72 @@+import type { Asker } from "#setup/ask.js";+import type { Prompter } from "#setup/prompter.js";+import type { VercelProjectReference } from "#setup/project-resolution.js";import type { RegistrySetupCompletion } from "#setup/registry-setup-protocol.js";+import { WizardCancelledError } from "#setup/step.js";import type { IntegrationSetupEnvironment } from "./shared/environment.js";-import type { IntegrationSetupUi } from "./shared/ui.js";-/** Inputs available to one registry-owned integration setup flow. */-export interface IntegrationSetupContext {+export type SetupPresenter = Pick<Prompter, "log" | "note"> & {+ nextSteps(lines: readonly string[]): void;+ beginExternalAction(input: { url: string; userCode?: string; message: string }): void;+};++export interface SetupPrepareContext {readonly appRoot: string;+ readonly asker: Asker;readonly environment: IntegrationSetupEnvironment;- readonly ui: IntegrationSetupUi;- readonly signal?: AbortSignal;- readonly force?: boolean;- readonly yes?: boolean;+ readonly presenter: SetupPresenter;+ readonly resolveVercelProject: (integration: string) => Promise<VercelProjectReference>;+ signal?: AbortSignal;+ force?: boolean;+}++export interface SetupApplyContext {+ readonly appRoot: string;+ readonly presenter: SetupPresenter;+ signal?: AbortSignal;+ force?: boolean;}-/** Outcome from one registry-owned integration setup flow. */export type IntegrationSetupResult =| { readonly kind: "done"; readonly completion: RegistrySetupCompletion }| { readonly kind: "cancelled" };-/** One built-in registry-owned integration setup flow. */-export interface SetupIntegration {+interface SetupIntegrationDefinition<Plan> {readonly kind: string;readonly label: string;readonly hint?: string;- setup(context: IntegrationSetupContext): Promise<IntegrationSetupResult>;+ prepare(context: SetupPrepareContext): Promise<Plan>;+ apply(plan: Plan, context: SetupApplyContext): Promise<RegistrySetupCompletion>;+}++export interface SetupIntegration {+ readonly kind: string;+ readonly label: string;+ hint?: string;+ run(input: {+ prepare: SetupPrepareContext;+ apply: SetupApplyContext;+ }): Promise<IntegrationSetupResult>;+}++/** Captures an integration's private plan type behind one executable lifecycle. */+export function defineSetupIntegration<Plan>(+ definition: SetupIntegrationDefinition<Plan>,+): SetupIntegration {+ const registered: SetupIntegration = {+ kind: definition.kind,+ label: definition.label,+ async run(contexts) {+ try {+ const plan = await definition.prepare(contexts.prepare);+ return { kind: "done", completion: await definition.apply(plan, contexts.apply) };+ } catch (error) {+ if (error instanceof WizardCancelledError) return { kind: "cancelled" };+ throw error;+ }+ },+ };+ if (definition.hint !== undefined) registered.hint = definition.hint;+ return registered;}diff --git a/packages/eve/src/setup/integrations/web/setup.test.ts b/packages/eve/src/setup/integrations/web/setup.test.tsnew file mode 100644index 000000000..5f5db35c8--- /dev/null+++ b/packages/eve/src/setup/integrations/web/setup.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it, vi } from "vitest";+import { createFakePrompter } from "#internal/testing/fake-prompter.js";+import { headlessAsker } from "#setup/ask.js";+import { integrationSetupEnvironment } from "../shared/environment.js";+import { createSetupContexts } from "../shared/ui.js";+import { applyWebSetup, prepareWebSetup, type WebSetupDeps } from "./setup.js";++function deps(): WebSetupDeps {+ return {+ detectPackageManager: vi.fn(async () => ({+ kind: "pnpm" as const,+ source: "lockfile" as const,+ })),+ ensureChannel: vi.fn(async () => ({+ kind: "web" as const,+ action: "created" as const,+ filesWritten: [],+ filesOverwritten: [],+ filesSkipped: [],+ packageJsonUpdated: [+ { path: "/project/package.json", dependencies: ["eve"], devDependencies: [], scripts: [] },+ ],+ nodeEngineOverride: undefined,+ competingNextConfigFiles: [],+ })),+ installScaffoldDependencies: vi.fn(async () => {}),+ };+}++describe("Web setup", () => {+ it("prepares and applies without semantic questions", async () => {+ const effects = deps();+ const ctx = createSetupContexts({+ appRoot: "/project",+ asker: headlessAsker(),+ environment: integrationSetupEnvironment("cli-missing", { kind: "unresolved" }),+ prompter: createFakePrompter().prompter,+ resolveVercelProject: async () => ({ orgId: "team", projectId: "project" }),+ });+ const plan = await prepareWebSetup(ctx.prepare, effects);+ await applyWebSetup(plan, ctx.apply, effects);+ expect(effects.ensureChannel).toHaveBeenCalledWith(+ expect.objectContaining({ configureVercelServices: false, skipDependencyMutation: true }),+ );+ expect(effects.installScaffoldDependencies).toHaveBeenCalledWith(+ expect.objectContaining({ changed: true, projectPath: "/project" }),+ );+ });+});diff --git a/packages/eve/src/setup/integrations/web/setup.ts b/packages/eve/src/setup/integrations/web/setup.tsindex 6ce274eee..754761493 100644--- a/packages/eve/src/setup/integrations/web/setup.ts+++ b/packages/eve/src/setup/integrations/web/setup.ts@@ -3,7 +3,11 @@ import { formatNodeEngineOverrideWarning } from "#setup/node-engine.js";import { ensureChannel, type EnsureChannelOptions } from "#setup/scaffold/index.js";import { installScaffoldDependencies, reportOverwrittenFiles } from "../shared/scaffold.js";-import type { SetupIntegration } from "../types.js";+import {+ defineSetupIntegration,+ type SetupApplyContext,+ type SetupPrepareContext,+} from "../types.js";function reportCompetingNextConfigFiles(log: Parameters<typeof reportOverwrittenFiles>[0],@@ -16,48 +20,78 @@ function reportCompetingNextConfigFiles(}}-/** Web Chat scaffolding. */-export const WEB_SETUP: SetupIntegration = {+export interface WebSetupDeps {+ detectPackageManager: typeof detectPackageManager;+ ensureChannel: typeof ensureChannel;+ installScaffoldDependencies: typeof installScaffoldDependencies;+}++const defaultDeps: WebSetupDeps = {+ detectPackageManager,+ ensureChannel,+ installScaffoldDependencies,+};++export interface WebSetupPlan {+ configureVercelServices: boolean;+ packageManager: Awaited<ReturnType<typeof detectPackageManager>>["kind"];+}++export async function prepareWebSetup(+ context: SetupPrepareContext,+ deps: WebSetupDeps = defaultDeps,+): Promise<WebSetupPlan> {+ return {+ packageManager: (await deps.detectPackageManager(context.appRoot)).kind,+ configureVercelServices: context.environment.vercel.kind === "available",+ };+}++export async function applyWebSetup(+ plan: WebSetupPlan,+ context: SetupApplyContext,+ deps: WebSetupDeps = defaultDeps,+) {+ context.presenter.log.message("Scaffolding Web Chat channel files...");+ const options: EnsureChannelOptions = {+ projectRoot: context.appRoot,+ kind: "web",+ packageManager: plan.packageManager,+ configureVercelServices: plan.configureVercelServices,+ force: context.force,+ skipDependencyMutation: true,+ };+ const result = await deps.ensureChannel(options);+ reportOverwrittenFiles(context.presenter.log, result.filesOverwritten);+ if (+ result.kind === "web" &&+ result.action !== "skipped" &&+ result.nodeEngineOverride !== undefined+ ) {+ context.presenter.log.warning(formatNodeEngineOverrideWarning(result.nodeEngineOverride));+ }+ reportCompetingNextConfigFiles(+ context.presenter.log,+ "competingNextConfigFiles" in result ? result.competingNextConfigFiles : undefined,+ );+ if (result.action === "skipped") {+ context.presenter.log.info("Next.js project detected. Skipping Web Chat scaffolding.");+ return { facts: [] };+ }+ context.presenter.log.success("Scaffolded channel: web");+ await deps.installScaffoldDependencies({+ changed: result.packageJsonUpdated.length > 0,+ log: context.presenter.log,+ projectPath: context.appRoot,+ signal: context.signal,+ });+ return { facts: [], deploymentRequired: true as const };+}++export const WEB_SETUP = defineSetupIntegration({kind: "web",label: "Web Chat",hint: "Browser-based chat interface",- async setup(context) {- context.ui.prompter.log.message("Scaffolding Web Chat channel files...");- const options: EnsureChannelOptions = {- projectRoot: context.appRoot,- kind: "web",- packageManager: (await detectPackageManager(context.appRoot)).kind,- configureVercelServices: context.environment.vercel.kind === "available",- force: context.force,- skipDependencyMutation: true,- };- const result = await ensureChannel(options);- reportOverwrittenFiles(context.ui.prompter.log, result.filesOverwritten);- if (- result.kind === "web" &&- result.action !== "skipped" &&- result.nodeEngineOverride !== undefined- ) {- context.ui.prompter.log.warning(formatNodeEngineOverrideWarning(result.nodeEngineOverride));- }- reportCompetingNextConfigFiles(- context.ui.prompter.log,- "competingNextConfigFiles" in result ? result.competingNextConfigFiles : undefined,- );- if (result.action === "skipped") {- context.ui.prompter.log.info("Next.js project detected. Skipping Web Chat scaffolding.");- return { kind: "done", completion: { facts: [] } };- }- context.ui.prompter.log.success("Scaffolded channel: web");- await installScaffoldDependencies({- changed: result.packageJsonUpdated.length > 0,- log: context.ui.prompter.log,- projectPath: context.appRoot,- signal: context.signal,- });- return {- kind: "done",- completion: { facts: [], deploymentRequired: true },- };- },-};+ prepare: prepareWebSetup,+ apply: applyWebSetup,+});diff --git a/packages/eve/src/setup/slackbot.ts b/packages/eve/src/setup/slackbot.tsindex 2afc398d0..296a0b418 100644--- a/packages/eve/src/setup/slackbot.ts+++ b/packages/eve/src/setup/slackbot.ts@@ -25,6 +25,7 @@ import {listSlackConnectors,type SlackConnectLifecycleDeps,type SlackConnectorCleanupResult,+ type SlackConnectorLookup,} from "./slack-connect-lifecycle.js";// Re-exported so the Connect parsers remain importable from the provisioning@@ -315,6 +316,27 @@ async function raceAttemptAgainstChoice(input: {*/export type SlackConnectorSelection = SlackConnectorRef | "create";+/** Read-only connector inventory used to resolve the create/reuse decision before provisioning. */+export async function inspectSlackbotConnectors(+ log: ChannelSetupLog,+ projectRoot: string,+ slug: string,+ signal?: AbortSignal,+ deps: SlackbotProvisionDeps = defaultDeps,+): Promise<Extract<SlackConnectorLookup, { state: "found" | "not-found" }>> {+ const projectLink = await (deps.readProjectLink ?? readProjectLink)(projectRoot);+ const lookup = await findSlackConnector(+ deps,+ projectRoot,+ projectLink?.projectId,+ `slack/${slug}`,+ createPromptCommandOutput(log),+ signal,+ );+ if (lookup.state === "failed") throw new Error(lookup.message);+ return lookup;+}+export interface ProvisionSlackbotOptions {/*** Cancels the caller's whole operation. The promise rejects after attempting