The Open Framework for Building Agents
feat(eve): add guided Discord setup (#1475)
Ben Pankowcec672d4dc32
diff --git a/.changeset/discord-guided-setup.md b/.changeset/discord-guided-setup.mdnew file mode 100644index 000000000..690037583--- /dev/null+++ b/.changeset/discord-guided-setup.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add guided Discord setup through `eve add channel/discord`, including Vercel Connect provisioning, trigger attachment, interactions endpoint configuration, slash-command registration, and channel scaffolding.diff --git a/apps/docs/registry.json b/apps/docs/registry.jsonindex 0cec1502f..7097418fe 100644--- a/apps/docs/registry.json+++ b/apps/docs/registry.json@@ -1092,19 +1092,19 @@"name": "channel/discord","type": "registry:item","title": "Discord",- "description": "Run your agent as a Discord bot across servers and threads.",- "envVars": {- "DISCORD_APPLICATION_ID": "",- "DISCORD_BOT_TOKEN": "",- "DISCORD_PUBLIC_KEY": ""- },- "files": [- {- "path": "registry/channels/discord.ts",- "type": "registry:file",- "target": "agent/channels/discord.ts"+ "description": "Connect an eve agent to Discord with guided connector and slash-command setup.",+ "dependencies": ["@vercel/[email protected]"],+ "meta": {+ "eve": {+ "setup": {+ "command": "eve",+ "package": "eve",+ "bin": "eve",+ "args": ["integration", "setup", "discord"]+ },+ "requires": ">=0.30.0"}- ]+ }},{"name": "channel/teams",diff --git a/apps/docs/registry/channels/discord.ts b/apps/docs/registry/channels/discord.tsdeleted file mode 100644index e641924a7..000000000--- a/apps/docs/registry/channels/discord.ts+++ /dev/null@@ -1,8 +0,0 @@-import { discordChannel } from "eve/channels/discord";--export default discordChannel({- credentials: {- botToken: () => process.env.DISCORD_BOT_TOKEN!,- publicKey: () => process.env.DISCORD_PUBLIC_KEY!,- },-});diff --git a/apps/docs/scripts/validate-channel-registry.ts b/apps/docs/scripts/validate-channel-registry.tsindex 38e0ec2d1..9f58f8eb0 100644--- a/apps/docs/scripts/validate-channel-registry.ts+++ b/apps/docs/scripts/validate-channel-registry.ts@@ -34,6 +34,7 @@ const registrySlugsByCatalogSlug: Readonly<Record<string, string>> = {};const setupKindsByCatalogSlug: Readonly<Record<string, string>> = {+ discord: "discord",eve: "web",photon: "photon",};@@ -110,7 +111,12 @@ for (const [index, item] of items.entries()) {if (entry === undefined) throw new Error(`Unexpected channel registry item "${item.name}".`);const registrySlug = expectedSlugs[index];- if (entry.slug === "slack" || entry.slug === "eve" || entry.slug === "photon") {+ if (+ entry.slug === "slack" ||+ entry.slug === "discord" ||+ entry.slug === "eve" ||+ entry.slug === "photon"+ ) {const expectedArgs = ["integration","setup",diff --git a/docs/channels/discord.mdx b/docs/channels/discord.mdxindex cbe0553d4..6697ed15a 100644--- a/docs/channels/discord.mdx+++ b/docs/channels/discord.mdx@@ -4,31 +4,28 @@ description: "Reach your agent from Discord HTTP Interactions, including slash ctype: integration----The Discord channel wires your agent into Discord's HTTP Interactions, including slash and application commands, message components, and modal submissions. Discord enforces a three-second ACK deadline, so the channel verifies inbound requests, acknowledges the command right away, and runs the eve work in the background. See [Channels](./overview) for the contract this builds on.+The Discord channel wires your agent into Discord's HTTP Interactions, including slash and application commands, message components, and modal submissions. Discord enforces a three-second ACK deadline, so the channel acknowledges the command right away and runs the eve work in the background. Credentials and inbound request verification run through [Vercel Connect](../guides/auth-and-route-protection), so Discord's bot token stays out of your environment and Connect verifies Discord's signature before forwarding an interaction to eve. See [Channels](./overview) for the contract this builds on.-## Set up Connect+## Set up Discord-Create a Discord connector with **Bot and interactions** enabled, copy its UID (e.g. `discord/my-agent`), and attach this project as the trigger destination at eve's Discord route:+Run the guided setup from your eve project:```bash-npm install -g vercel@latest-vercel connect create discord --triggers-vercel connect attach <uid> --triggers --trigger-path /eve/v1/discord --yes+pnpm eve add channel/discord```-You can also create the connector from the [Connect dashboard](https://vercel.com/d?to=/%5Bteam%5D/~/connect&title=Go+to+Connect). Connect stores the bot token, verifies Discord's signed interactions, and forwards them to your project with Vercel OIDC.+The setup guides you through creating a Discord application and bot, then:-Open the connector's **Triggers** section and copy its webhook URL (`https://connect.vercel.com/trigger/<connector-id>`). In the [Discord Developer Portal](https://discord.com/developers/applications), open your application, go to **General Information**, paste the URL into **Interactions Endpoint URL**, and save. Discord sends a signed validation request before accepting the URL.+- validates the bot token;+- creates a Vercel Connect client and attaches `/eve/v1/discord` as its trigger destination;+- registers an application command with a required `message` option;+- configures the Discord application's Interactions Endpoint URL;+- scaffolds the channel with Connect-managed credentials; and+- prints the bot installation URL.-## Add the channel+The command defaults to `/ask` with the description **Ask the eve agent**. You can edit both during setup. Discord global commands can take up to an hour to appear after registration.-Install the Connect SDK:--```bash-npm install @vercel/connect-```--Then create:+The generated channel looks like this:```ts title="agent/channels/discord.ts"import { connectDiscordCredentials } from "@vercel/connect/eve";@@ -39,23 +36,11 @@ export default discordChannel({});```-`connectDiscordCredentials` supplies the application ID and bot token from Connect and verifies forwarded interactions with Vercel OIDC. The route is `POST /eve/v1/discord` by default.--### Direct credentials--To connect Discord without Vercel Connect, provide credentials through environment variables:--```bash-DISCORD_PUBLIC_KEY=... # verifies X-Signature-Ed25519 + X-Signature-Timestamp-DISCORD_APPLICATION_ID=... # edits the deferred response and sends followups-DISCORD_BOT_TOKEN=... # proactive messages + fallback + typing indicators-```--Or pass the same values through `credentials: { applicationId, botToken, publicKey }`. Paste the deployed `/eve/v1/discord` URL into your Discord application's Interactions Endpoint URL.+The route is `POST /eve/v1/discord` by default. Connect resolves the application ID and bot token lazily and verifies forwarded interactions with same-project Vercel OIDC.-## Register a command+### Configure Discord manually-Registering commands is on you, not the channel. Use Discord's API or the Developer Portal. A string option named `message` lines up with eve's default prompt extraction:+If you do not use the guided Connect setup, register a command with Discord's API or the Developer Portal. A string option named `message` lines up with eve's default prompt extraction:```bashcurl -X PUT "https://discord.com/api/v10/applications/$DISCORD_APPLICATION_ID/commands" \@@ -64,7 +49,7 @@ curl -X PUT "https://discord.com/api/v10/applications/$DISCORD_APPLICATION_ID/co"options":[{"name":"message","description":"What should the agent do?","type":3,"required":true}]}]'```-Use guild commands during development for faster propagation.+Then configure the public `https://…/eve/v1/discord` route as the application's Interactions Endpoint URL. Pass `credentials: { applicationId, botToken, publicKey }` to `discordChannel`, or set the corresponding `DISCORD_APPLICATION_ID`, `DISCORD_BOT_TOKEN`, and `DISCORD_PUBLIC_KEY` environment variables.## How the channel handles messagesdiff --git a/packages/eve/src/setup/integrations/discord/api.test.ts b/packages/eve/src/setup/integrations/discord/api.test.tsnew file mode 100644index 000000000..e33b087f5--- /dev/null+++ b/packages/eve/src/setup/integrations/discord/api.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it, vi } from "vitest";++import {+ configureDiscordInteractionsEndpoint,+ registerDiscordCommand,+ resolveDiscordApplication,+} from "./api.js";++describe("Discord setup API", () => {+ it("resolves application metadata from a bot token", async () => {+ const fetchImpl = vi.fn(async () =>+ Response.json({ id: "app-1", name: "Agent", verify_key: "public-key" }),+ ) as typeof fetch;++ await expect(resolveDiscordApplication("bot-token", fetchImpl)).resolves.toEqual({+ id: "app-1",+ name: "Agent",+ publicKey: "public-key",+ });+ });++ it("registers the default message command shape", async () => {+ const fetchImpl = vi.fn(async () => Response.json({ id: "command-1" })) as typeof fetch;++ await registerDiscordCommand(+ "app-1",+ "bot-token",+ { name: "ask", description: "Ask the eve agent" },+ fetchImpl,+ );++ expect(fetchImpl).toHaveBeenCalledWith(+ "https://discord.com/api/v10/applications/app-1/commands",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({+ name: "ask",+ description: "Ask the eve agent",+ type: 1,+ options: [+ {+ name: "message",+ description: "What should the agent do?",+ type: 3,+ required: true,+ },+ ],+ }),+ }),+ );+ });++ it("sets the Connect interaction callback URL", async () => {+ const fetchImpl = vi.fn(async () => Response.json({ id: "app-1" })) as typeof fetch;++ await configureDiscordInteractionsEndpoint("bot-token", "scl_discord", fetchImpl);++ expect(fetchImpl).toHaveBeenCalledWith(+ "https://discord.com/api/v10/applications/@me",+ expect.objectContaining({+ method: "PATCH",+ body: JSON.stringify({+ interactions_endpoint_url: "https://connect.vercel.com/trigger/scl_discord",+ }),+ }),+ );+ });+});diff --git a/packages/eve/src/setup/integrations/discord/api.ts b/packages/eve/src/setup/integrations/discord/api.tsnew file mode 100644index 000000000..5133c3687--- /dev/null+++ b/packages/eve/src/setup/integrations/discord/api.ts@@ -0,0 +1,104 @@+import { z } from "zod";++const DISCORD_API_BASE_URL = "https://discord.com/api/v10";++const DiscordApplicationSchema = z.object({+ id: z.string(),+ name: z.string(),+ verify_key: z.string(),+});++/** Non-secret Discord application metadata resolved from a bot token. */+export interface DiscordApplication {+ id: string;+ name: string;+ publicKey: string;+}++async function discordRequest(+ botToken: string,+ path: string,+ init: RequestInit,+ fetchImpl: typeof fetch,+): Promise<Response> {+ return fetchImpl(`${DISCORD_API_BASE_URL}${path}`, {+ ...init,+ headers: {+ authorization: `Bot ${botToken}`,+ "content-type": "application/json",+ ...init.headers,+ },+ });+}++/** Validates a bot token and returns its Discord application. */+export async function resolveDiscordApplication(+ botToken: string,+ fetchImpl: typeof fetch = fetch,+): Promise<DiscordApplication> {+ const response = await discordRequest(+ botToken,+ "/oauth2/applications/@me",+ { method: "GET" },+ fetchImpl,+ );+ if (!response.ok) throw new Error(`Discord rejected the bot token (HTTP ${response.status}).`);+ const parsed = DiscordApplicationSchema.safeParse(await response.json());+ if (!parsed.success) throw new Error("Discord returned incomplete application details.");+ return { id: parsed.data.id, name: parsed.data.name, publicKey: parsed.data.verify_key };+}++/** Registers the global command consumed by the default Discord channel. */+export async function registerDiscordCommand(+ applicationId: string,+ botToken: string,+ command: { name: string; description: string },+ fetchImpl: typeof fetch = fetch,+): Promise<void> {+ const response = await discordRequest(+ botToken,+ `/applications/${encodeURIComponent(applicationId)}/commands`,+ {+ method: "POST",+ body: JSON.stringify({+ name: command.name,+ description: command.description,+ type: 1,+ options: [+ {+ name: "message",+ description: "What should the agent do?",+ type: 3,+ required: true,+ },+ ],+ }),+ },+ fetchImpl,+ );+ if (!response.ok) {+ throw new Error(`Discord command registration failed (HTTP ${response.status}).`);+ }+}++/** Points Discord HTTP Interactions at a persisted Connect connector. */+export async function configureDiscordInteractionsEndpoint(+ botToken: string,+ connectorId: string,+ fetchImpl: typeof fetch = fetch,+): Promise<void> {+ const response = await discordRequest(+ botToken,+ "/applications/@me",+ {+ method: "PATCH",+ body: JSON.stringify({+ interactions_endpoint_url: `https://connect.vercel.com/trigger/${encodeURIComponent(connectorId)}`,+ }),+ },+ fetchImpl,+ );+ if (!response.ok) {+ throw new Error(`Discord rejected the interactions endpoint (HTTP ${response.status}).`);+ }+}diff --git a/packages/eve/src/setup/integrations/discord/connect.test.ts b/packages/eve/src/setup/integrations/discord/connect.test.tsnew file mode 100644index 000000000..857a8bed5--- /dev/null+++ b/packages/eve/src/setup/integrations/discord/connect.test.ts@@ -0,0 +1,96 @@+import { describe, expect, it, vi } from "vitest";++import type { ChannelSetupLog } from "#setup/cli/index.js";+import { parseCreatedDiscordConnector, provisionDiscordConnector } from "./connect.js";++function log(): ChannelSetupLog {+ return {+ message: vi.fn(),+ info: vi.fn(),+ success: vi.fn(),+ warning: vi.fn(),+ error: vi.fn(),+ commandOutput: vi.fn(),+ };+}++describe("Discord Connect provisioning", () => {+ it("parses an app-scoped Discord connector", () => {+ expect(+ parseCreatedDiscordConnector(+ JSON.stringify({+ id: "scl_discord",+ uid: "discord/agent",+ supportedSubjectTypes: ["app"],+ }),+ ),+ ).toEqual({ id: "scl_discord", uid: "discord/agent" });+ });++ it("creates the connector with stdin credentials and replaces its trigger", async () => {+ const runVercelCaptureStdout = vi.fn(async () => ({+ ok: true as const,+ stdout: JSON.stringify({+ id: "scl_discord",+ uid: "discord/agent",+ supportedSubjectTypes: ["app"],+ }),+ stderr: "",+ }));+ const runVercel = vi.fn(async () => true);++ await expect(+ provisionDiscordConnector({+ botToken: "bot-token",+ log: log(),+ project: { orgId: "team_123", projectId: "prj_123" },+ projectRoot: "/project",+ slug: "agent",+ deps: { runVercel, runVercelCaptureStdout },+ }),+ ).resolves.toEqual({ id: "scl_discord", uid: "discord/agent" });++ expect(runVercelCaptureStdout).toHaveBeenCalledWith(+ [+ "connect",+ "create",+ "discord",+ "--connector-type",+ "discord",+ "--data",+ "@-",+ "--name",+ "agent",+ "--triggers",+ "-F",+ "json",+ "--scope",+ "team_123",+ ],+ expect.objectContaining({+ cwd: "/project",+ nonInteractive: true,+ stdin: JSON.stringify({ botToken: "bot-token" }),+ }),+ );+ expect(runVercel).toHaveBeenNthCalledWith(+ 2,+ [+ "connect",+ "attach",+ "discord/agent",+ "--project",+ "prj_123",+ "--environment",+ "production",+ "--triggers",+ "--trigger-path",+ "/eve/v1/discord",+ "--yes",+ "--scope",+ "team_123",+ ],+ expect.objectContaining({ cwd: "/project", nonInteractive: true }),+ );+ });+});diff --git a/packages/eve/src/setup/integrations/discord/connect.ts b/packages/eve/src/setup/integrations/discord/connect.tsnew file mode 100644index 000000000..1723ffc54--- /dev/null+++ b/packages/eve/src/setup/integrations/discord/connect.ts@@ -0,0 +1,107 @@+import { createPromptCommandOutput, withPhase, type ChannelSetupLog } from "#setup/cli/index.js";+import { replaceConnectTrigger } from "#setup/connect-provisioning.js";+import type { VercelProjectReference } from "#setup/project-resolution.js";+import { runVercel, runVercelCaptureStdout } from "#setup/primitives/run-vercel.js";+import { z } from "zod";++export const DISCORD_TRIGGER_PATH = "/eve/v1/discord";++export interface DiscordConnectorRef {+ id: string;+ uid: string;+}++export interface ProvisionDiscordConnectorDeps {+ runVercel: typeof runVercel;+ runVercelCaptureStdout: typeof runVercelCaptureStdout;+}++const DiscordConnectorRefSchema = z.object({+ id: z.string().min(1),+ uid: z.string().min(1),+ supportedSubjectTypes: z.array(z.string()).refine((types) => types.includes("app")),+});++/** Parses `vercel connect create -F json` output for a Discord connector. */+export function parseCreatedDiscordConnector(stdout: string): DiscordConnectorRef | undefined {+ try {+ const parsed = DiscordConnectorRefSchema.safeParse(JSON.parse(stdout));+ return parsed.success ? { id: parsed.data.id, uid: parsed.data.uid } : undefined;+ } catch {+ return undefined;+ }+}++/** Creates a Discord connector and attaches its trigger to eve's route. */+export async function provisionDiscordConnector(input: {+ botToken: string;+ log: ChannelSetupLog;+ project: VercelProjectReference;+ projectRoot: string;+ slug: string;+ signal?: AbortSignal;+ deps?: ProvisionDiscordConnectorDeps;+}): Promise<DiscordConnectorRef> {+ const deps = input.deps ?? { runVercel, runVercelCaptureStdout };+ const onOutput = createPromptCommandOutput(input.log);+ const result = await withPhase(input.log, "Creating Discord connector...", () =>+ deps.runVercelCaptureStdout(+ [+ "connect",+ "create",+ "discord",+ "--connector-type",+ "discord",+ "--data",+ "@-",+ "--name",+ input.slug,+ "--triggers",+ "-F",+ "json",+ "--scope",+ input.project.orgId,+ ],+ {+ cwd: input.projectRoot,+ nonInteractive: true,+ onOutput,+ signal: input.signal,+ stdin: JSON.stringify({ botToken: input.botToken.trim() }),+ },+ ),+ );+ input.signal?.throwIfAborted();+ if (!result.ok) {+ const detail = [result.stderr, result.stdout].find(+ (value): value is string => value !== undefined && value.trim().length > 0,+ );+ throw new Error(+ detail+ ? `Discord connector creation failed:\n${detail}`+ : "Discord connector creation failed.",+ );+ }+ const connector = parseCreatedDiscordConnector(result.stdout);+ if (connector === undefined) throw new Error("Vercel returned an invalid Discord connector.");++ const attachment = await withPhase(input.log, "Connecting Discord interactions...", () =>+ replaceConnectTrigger({+ connectorUid: connector.uid,+ projectRoot: input.projectRoot,+ projectId: input.project.projectId,+ orgId: input.project.orgId,+ environment: "production",+ triggerPath: DISCORD_TRIGGER_PATH,+ onOutput,+ signal: input.signal,+ deps,+ }),+ );+ if (attachment.state !== "attached") {+ throw new Error(+ `Discord connector was created, but its trigger could not be attached. Run \`vercel connect attach ${connector.uid} --project ${input.project.projectId} --environment production --triggers --trigger-path ${DISCORD_TRIGGER_PATH} --yes --scope ${input.project.orgId}\`.`,+ );+ }+ return connector;+}diff --git a/packages/eve/src/setup/integrations/discord/setup.test.ts b/packages/eve/src/setup/integrations/discord/setup.test.tsnew file mode 100644index 000000000..921f17a7c--- /dev/null+++ b/packages/eve/src/setup/integrations/discord/setup.test.ts@@ -0,0 +1,114 @@+import { describe, expect, it, vi } from "vitest";++import { createFakePrompter } from "#internal/testing/fake-prompter.js";+import type { Asker, Question } 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,+ askMany: async () => [],+ };+}++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" })),+ registerCommand: vi.fn(async () => {}),+ resolveApplication: vi.fn(async () => ({+ id: "app-1",+ name: "Agent",+ publicKey: "public-key",+ })),+ writeTextFile: vi.fn(async () => {}),+ };+}++describe("Discord setup", () => {+ it("provisions Connect, registers the command and callback, and scaffolds the channel", async () => {+ const fake = createFakePrompter();+ 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" });++ 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")'),+ { force: undefined },+ );+ });++ it("prefills the command name and description", async () => {+ const questions: Question<unknown>[] = [];+ 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;+ },+ 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",+ }),+ ]),+ );+ });++ it("requires an authenticated Vercel CLI", async () => {+ const fake = createFakePrompter();+ await expect(+ setupDiscord({+ appRoot: "/project",+ environment: integrationSetupEnvironment("logged-out", { kind: "unresolved" }),+ ui: createIntegrationSetupUi({ asker: asker({}), prompter: fake.prompter }),+ }),+ ).rejects.toThrow("vercel login");+ });+});diff --git a/packages/eve/src/setup/integrations/discord/setup.ts b/packages/eve/src/setup/integrations/discord/setup.tsnew file mode 100644index 000000000..748a8e6a9--- /dev/null+++ b/packages/eve/src/setup/integrations/discord/setup.ts@@ -0,0 +1,171 @@+import { join } from "node:path";++import { text } from "#setup/ask.js";+import { ensureVercelProject } from "#setup/flows/ensure-vercel-project.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,+} from "../types.js";+import {+ configureDiscordInteractionsEndpoint,+ registerDiscordCommand,+ resolveDiscordApplication,+} from "./api.js";+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;+ writeTextFile: typeof writeTextFile;+}++const defaultDeps: DiscordSetupDeps = {+ configureEndpoint: configureDiscordInteractionsEndpoint,+ deriveConnectorSlug: deriveSlackConnectorSlug,+ ensureVercelProject,+ provisionConnector: provisionDiscordConnector,+ registerCommand: registerDiscordCommand,+ resolveApplication: resolveDiscordApplication,+ writeTextFile,+};++function validateCommandName(value: string): string | null {+ const name = value.trim();+ if (!name) return "Command name is required.";+ if (name.length > 32) return "Command name must be 32 characters or fewer.";+ return /^[a-z0-9_-]+$/.test(name)+ ? null+ : "Use lowercase letters, numbers, hyphens, or underscores.";+}++function connectTemplate(uid: string): string {+ return `import { connectDiscordCredentials } from "@vercel/connect/eve";+import { discordChannel } from "eve/channels/discord";++export default discordChannel({+ credentials: connectDiscordCredentials(${JSON.stringify(uid)}),+});+`;+}++/** Runs guided Discord connector, command, and channel setup. */+export async function setupDiscord(+ context: IntegrationSetupContext,+ deps: DiscordSetupDeps = defaultDeps,+): Promise<IntegrationSetupResult> {+ 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,+ }),+ )+ ).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(+ 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 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",+ facts: [+ {+ label: "Discord application",+ value: `https://discord.com/developers/applications/${application.id}/information`,+ kind: "url",+ },+ ],+ };+ } catch (error) {+ if (error instanceof WizardCancelledError) return { kind: "cancelled" };+ throw error;+ }+}++/** Discord setup registration. */+export const DISCORD_SETUP: SetupIntegration = {+ kind: "discord",+ label: "Discord",+ hint: "Slash commands and interactions",+ setup: setupDiscord,+};diff --git a/packages/eve/src/setup/integrations/registry.ts b/packages/eve/src/setup/integrations/registry.tsindex 2120953a6..1aa4e495a 100644--- a/packages/eve/src/setup/integrations/registry.ts+++ b/packages/eve/src/setup/integrations/registry.ts@@ -1,3 +1,4 @@+import { DISCORD_SETUP } from "./discord/setup.js";import { PHOTON_SETUP } from "./photon/setup.js";import { SLACK_SETUP } from "./slack/setup.js";import type { SetupIntegration } from "./types.js";@@ -7,6 +8,7 @@ import { WEB_SETUP } from "./web/setup.js";export const SETUP_INTEGRATIONS: readonly SetupIntegration[] = [WEB_SETUP,SLACK_SETUP,+ DISCORD_SETUP,PHOTON_SETUP,];diff --git a/packages/eve/src/setup/prompter.ts b/packages/eve/src/setup/prompter.tsindex 8e537ccac..3b49d4aaa 100644--- a/packages/eve/src/setup/prompter.ts+++ b/packages/eve/src/setup/prompter.ts@@ -369,6 +369,7 @@ function textPrompt(validate: opts.validate ? (value) => opts.validate?.(value ?? "") : undefined,placeholder: opts.placeholder,defaultValue: opts.defaultValue,+ initialValue: opts.defaultValue,render() {const head = header(this.state, opts.message, resolvedCount);const placeholderRendered = opts.placeholder