Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

[3/4] feat(eve): scaffold the Discord Gateway relay from eve add channel/discord (#5032)

Ben Pankow87962a09f93c
diff --git a/.changeset/discord-gateway-setup.md b/.changeset/discord-gateway-setup.md
new file mode 100644
index 000000000..00ca10286
--- /dev/null
+++ b/.changeset/discord-gateway-setup.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+`eve add channel/discord` now first asks whether people reach the agent through DMs, mentions, and threads, or a slash command. The first scaffolds the Discord Gateway relay in `daemon/`, registers it as a Vercel Daemon in `vercel.json`, enables `gateway` on the channel, turns on the bot's Message Content intent when Discord allows it, and skips registering `/ask`; the second keeps today's slash command setup and is what `--yes` picks. Non-interactive runs answer `discord-messages` with `"gateway"` or `"commands"`.
diff --git a/docs/channels/discord.mdx b/docs/channels/discord.mdx
index 971e8e934..dbb3f4942 100644
--- a/docs/channels/discord.mdx
+++ b/docs/channels/discord.mdx
@@ -14,19 +14,24 @@ Run the guided setup from your eve project:
pnpm eve add channel/discord
```
-The setup guides you through creating a Discord application and bot, then:
+The setup first asks how people should reach the agent: through **DMs, mentions, and threads**, or through **a slash command**. It then guides you through creating a Discord application and bot, and:
- signs you in to Vercel and creates or links a project when needed;
- 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 and an optional `file` attachment option;
-- configures the Discord application's Interactions Endpoint URL;
+- configures the Discord application's Interactions Endpoint URL, which buttons such as HITL choices and sign-ins use either way;
+- for DMs, mentions, and threads, writes the [Gateway relay](#run-the-relay-as-a-vercel-daemon) in `daemon/`, registers it in `vercel.json` in the project's first function region, and turns on the bot's Message Content intent when Discord allows it;
+- for a slash command, registers it with a required `message` option and an optional `file` attachment option;
- scaffolds the channel with Connect-managed credentials; and
- prints the bot installation URL.
-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.
+The slash 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. A bot that answers messages can take slash commands too: register one as described in [Configure Discord manually](#configure-discord-manually), and the channel handles it.
-The generated channel looks like this:
+In a non-interactive run, answer `discord-messages` with `"gateway"` for DMs, mentions, and threads, or `"commands"` for a slash command. `--yes` picks the slash command, because the relay is experimental and runs as an always-on Vercel Daemon.
+
+If your project configures Vercel in `vercel.ts`, setup leaves it alone and prints the `daemons` entry to add to it.
+
+The generated channel looks like this, plus `gateway: {}` when the agent answers messages:
```ts title="agent/channels/discord.ts"
import { connectDiscordCredentials } from "@vercel/connect/eve";
@@ -79,7 +84,7 @@ Vercel Connect is optional here too: without `credentials`, the channel reads `D
### Run the relay as a Vercel Daemon
-A Vercel Daemon keeps the relay connected. Daemons are in beta. Put the relay in its own directory with the same credentials as the agent:
+A Vercel Daemon keeps the relay connected. Vercel Daemons are in beta. When you choose to answer messages, `eve add channel/discord` writes these files for you. To add them yourself, put the relay in its own directory with the same credentials as the agent:
```ts title="daemon/main.ts"
import { connectDiscordCredentials } from "@vercel/connect/eve";
@@ -87,6 +92,7 @@ import { experimental_runDiscordGatewayRelay } from "eve/channels/discord/gatewa
await experimental_runDiscordGatewayRelay({
credentials: connectDiscordCredentials("discord/my-agent"),
+ messageContent: false,
url: process.env.EVE_URL,
});
```
@@ -102,14 +108,14 @@ await experimental_runDiscordGatewayRelay({
}
```
-Run `npm install` in `daemon/` to create the `package-lock.json` the image installs from:
+The image installs from `package-lock.json` too, if you commit one in `daemon/`:
```dockerfile title="daemon/Dockerfile"
FROM node:24-slim
WORKDIR /app
ENV NODE_ENV=production
-COPY package.json package-lock.json ./
-RUN npm ci --omit=dev
+COPY package*.json ./
+RUN npm install --omit=dev --no-audit --no-fund
COPY main.ts ./
USER node
CMD ["node", "main.ts"]
@@ -119,7 +125,6 @@ Register the daemon in `vercel.json` with exactly one instance:
```json title="vercel.json"
{
- "framework": "eve",
"daemons": {
"discord-gateway": {
"root": "daemon",
@@ -202,7 +207,7 @@ A mention in a text channel starts a thread, as the Slack channel does, so each
Mention the bot's user, not the role with the same name that Discord creates for it. Discord's autocomplete offers both, and a role mention doesn't address the bot.
-Discord sends the text of messages that neither mention the bot nor arrive as a DM only to bots with the privileged **Message Content** intent. Without it, thread follow-ups that skip the mention, and replies whose author turned off the reply ping, arrive empty and are ignored. To request the intent, enable **Message Content Intent** under **Bot** in the Discord Developer Portal, then pass `messageContent: true` to `experimental_runDiscordGatewayRelay`. Discord refuses the relay's connection if you request the intent before enabling it, and the relay stops with an error naming the close code.
+Discord sends the text of messages that neither mention the bot nor arrive as a DM only to bots with the privileged **Message Content** intent. Without it, thread follow-ups that skip the mention, and replies whose author turned off the reply ping, arrive empty and are ignored. `eve add channel/discord` turns the intent on and sets `messageContent: true` when Discord allows it, which it does for bots in fewer than 100 servers. Otherwise, enable **Message Content Intent** under **Bot** in the Discord Developer Portal, then pass `messageContent: true` to `experimental_runDiscordGatewayRelay`. Discord refuses the relay's connection if you request the intent before enabling it, and the relay stops with an error naming the close code.
To choose which messages run the agent, under what `auth`, or which session they join, set `gateway.onMessage(ctx, message)`. It runs for every message from a person and returns `{ auth }` to dispatch or `null` to ignore. `message.addressed` reports whether the default would answer, and `message.referencedMessageId` names the message it replies to. `defaultDiscordMessageAuth(message)` gives the author the same principal `defaultDiscordAuth` gives them for commands and button presses, so requester-only approvals work across both:
diff --git a/packages/eve/src/setup/integrations/discord/api.test.ts b/packages/eve/src/setup/integrations/discord/api.test.ts
index bc64a9a13..6b575e685 100644
--- a/packages/eve/src/setup/integrations/discord/api.test.ts
+++ b/packages/eve/src/setup/integrations/discord/api.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import {
configureDiscordInteractionsEndpoint,
+ enableDiscordMessageContentIntent,
registerDiscordCommand,
resolveDiscordApplication,
} from "./api.js";
@@ -71,4 +72,43 @@ describe("Discord setup API", () => {
}),
);
});
+
+ describe("enableDiscordMessageContentIntent", () => {
+ function discordApp(flags: number, patchStatus = 200) {
+ return vi.fn<typeof fetch>(async (_url, init) =>
+ init?.method === "PATCH"
+ ? new Response("{}", { status: patchStatus })
+ : Response.json({ flags }),
+ );
+ }
+
+ it("turns on the limited intent and keeps the other limited intents set", async () => {
+ // Limited guild members (1 << 15) set, plus an unrelated read-only flag (1 << 23).
+ const fetchImpl = discordApp((1 << 15) | (1 << 23));
+
+ await expect(enableDiscordMessageContentIntent("bot-token", fetchImpl)).resolves.toBe(true);
+
+ expect(fetchImpl).toHaveBeenLastCalledWith(
+ "https://discord.com/api/v10/applications/@me",
+ expect.objectContaining({
+ body: JSON.stringify({ flags: (1 << 15) | (1 << 19) }),
+ method: "PATCH",
+ }),
+ );
+ });
+
+ it("leaves an app whose Message Content intent is already approved alone", async () => {
+ const fetchImpl = discordApp(1 << 18);
+
+ await expect(enableDiscordMessageContentIntent("bot-token", fetchImpl)).resolves.toBe(true);
+
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ });
+
+ it("reports a refusal, as for a verified app that needs approval", async () => {
+ await expect(
+ enableDiscordMessageContentIntent("bot-token", discordApp(0, 403)),
+ ).resolves.toBe(false);
+ });
+ });
});
diff --git a/packages/eve/src/setup/integrations/discord/api.ts b/packages/eve/src/setup/integrations/discord/api.ts
index 0fcf95595..b88afa9f1 100644
--- a/packages/eve/src/setup/integrations/discord/api.ts
+++ b/packages/eve/src/setup/integrations/discord/api.ts
@@ -108,3 +108,39 @@ export async function configureDiscordInteractionsEndpoint(
throw new Error(`Discord rejected the interactions endpoint (HTTP ${response.status}).`);
}
}
+
+// Application flags: Message Content approved for a verified app, or self-served below 100 servers.
+const GATEWAY_MESSAGE_CONTENT = 1 << 18;
+const GATEWAY_MESSAGE_CONTENT_LIMITED = 1 << 19;
+// The only flags an app may set itself: the limited presence, members, and message content intents.
+const EDITABLE_INTENT_FLAGS = (1 << 13) | (1 << 15) | GATEWAY_MESSAGE_CONTENT_LIMITED;
+
+const DiscordApplicationFlagsSchema = z.object({ flags: z.number().optional() });
+
+/**
+ * Turns on the Message Content intent, so messages that don't mention the bot,
+ * such as thread follow-ups, arrive with their text. Returns `false` when
+ * Discord refuses, as it does for a verified app in 100 or more servers, which
+ * needs Discord's approval instead.
+ */
+export async function enableDiscordMessageContentIntent(
+ botToken: string,
+ fetchImpl: typeof fetch = fetch,
+): Promise<boolean> {
+ const current = await discordRequest(botToken, "/applications/@me", { method: "GET" }, fetchImpl);
+ if (!current.ok) return false;
+ const flags = DiscordApplicationFlagsSchema.safeParse(await current.json()).data?.flags ?? 0;
+ if ((flags & (GATEWAY_MESSAGE_CONTENT | GATEWAY_MESSAGE_CONTENT_LIMITED)) !== 0) return true;
+ const response = await discordRequest(
+ botToken,
+ "/applications/@me",
+ {
+ method: "PATCH",
+ body: JSON.stringify({
+ flags: (flags & EDITABLE_INTENT_FLAGS) | GATEWAY_MESSAGE_CONTENT_LIMITED,
+ }),
+ },
+ fetchImpl,
+ );
+ return response.ok;
+}
diff --git a/packages/eve/src/setup/integrations/discord/daemon.test.ts b/packages/eve/src/setup/integrations/discord/daemon.test.ts
new file mode 100644
index 000000000..4a7cb08bb
--- /dev/null
+++ b/packages/eve/src/setup/integrations/discord/daemon.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+
+import { withDiscordDaemon } from "./daemon.js";
+
+const DAEMON = { entrypoint: "Dockerfile", instances: { iad1: 1 }, root: "daemon" };
+
+describe("withDiscordDaemon", () => {
+ it("creates vercel.json with the daemon when there is none", () => {
+ expect(JSON.parse(withDiscordDaemon(undefined)!)).toEqual({
+ $schema: "https://openapi.vercel.sh/vercel.json",
+ daemons: { "discord-gateway": DAEMON },
+ });
+ });
+
+ it("adds the daemon beside the project's own settings and daemons", () => {
+ const existing = JSON.stringify({ daemons: { worker: { root: "worker" } }, regions: ["sfo1"] });
+
+ expect(JSON.parse(withDiscordDaemon(existing)!)).toEqual({
+ // The relay runs in the project's first function region.
+ daemons: {
+ "discord-gateway": { ...DAEMON, instances: { sfo1: 1 } },
+ worker: { root: "worker" },
+ },
+ regions: ["sfo1"],
+ });
+ });
+
+ it("leaves a vercel.json that already has the daemon untouched", () => {
+ const existing = JSON.stringify({ daemons: { "discord-gateway": { root: "relay" } } });
+
+ expect(withDiscordDaemon(existing)).toBeUndefined();
+ });
+
+ it("refuses a daemons value it would have to replace", () => {
+ expect(() => withDiscordDaemon(JSON.stringify({ daemons: ["worker"] }))).toThrow(
+ "`daemons` value that isn't an object",
+ );
+ });
+
+ it("refuses a vercel.json it can't parse instead of overwriting it", () => {
+ expect(() => withDiscordDaemon("{ nope")).toThrow("vercel.json contains invalid JSON");
+ });
+});
diff --git a/packages/eve/src/setup/integrations/discord/daemon.ts b/packages/eve/src/setup/integrations/discord/daemon.ts
new file mode 100644
index 000000000..0d04117ce
--- /dev/null
+++ b/packages/eve/src/setup/integrations/discord/daemon.ts
@@ -0,0 +1,110 @@
+import { readFile } from "node:fs/promises";
+
+import { isErrnoCode, isObject } from "#shared/guards.js";
+import { DEFAULT_CONNECT_PACKAGE_VERSION } from "#setup/scaffold/version-tokens.js";
+import {
+ formatEveDependencySpecifier,
+ resolveEvePackageContract,
+} from "#setup/scaffold/create/project.js";
+
+/** Name of the Vercel Daemon that holds the Discord Gateway connection. */
+export const DISCORD_DAEMON_NAME = "discord-gateway";
+
+/** Directory of the relay, relative to the project root. */
+export const DISCORD_DAEMON_ROOT = "daemon";
+
+// Exactly one instance: each Gateway connection receives every message.
+function discordDaemon(region: string) {
+ return { root: DISCORD_DAEMON_ROOT, entrypoint: "Dockerfile", instances: { [region]: 1 } };
+}
+
+/** Vercel's default function region, for projects that don't set one. */
+const DEFAULT_REGION = "iad1";
+
+/** The relay's files, by path relative to {@link DISCORD_DAEMON_ROOT}. */
+export function discordDaemonFiles(
+ connectorUid: string,
+ options: { readonly messageContent: boolean } = { messageContent: false },
+): Readonly<Record<string, string>> {
+ const packageJson = {
+ private: true,
+ type: "module",
+ dependencies: {
+ "@vercel/connect": DEFAULT_CONNECT_PACKAGE_VERSION,
+ eve: formatEveDependencySpecifier(resolveEvePackageContract().version),
+ },
+ };
+ return {
+ ".dockerignore": "node_modules\n",
+ Dockerfile: `FROM node:24-slim
+WORKDIR /app
+ENV NODE_ENV=production
+COPY package*.json ./
+RUN npm install --omit=dev --no-audit --no-fund
+COPY main.ts ./
+USER node
+CMD ["node", "main.ts"]
+`,
+ "main.ts": `import { connectDiscordCredentials } from "@vercel/connect/eve";
+import { experimental_runDiscordGatewayRelay } from "eve/channels/discord/gateway";
+
+await experimental_runDiscordGatewayRelay({
+ credentials: connectDiscordCredentials(${JSON.stringify(connectorUid)}),
+ // Lets thread follow-ups that don't mention the bot arrive with their text. Needs
+ // Message Content Intent under Bot in the Discord Developer Portal, or Discord refuses the relay.
+ messageContent: ${String(options.messageContent)},
+ // Defaults to the project's production URL; set EVE_URL to relay to \`eve dev\`.
+ url: process.env.EVE_URL,
+});
+`,
+ "package.json": `${JSON.stringify(packageJson, null, 2)}\n`,
+ };
+}
+
+/** The `daemons` entry to add by hand to a project configured through `vercel.ts`. */
+export function discordDaemonEntry(): string {
+ return `daemons: ${JSON.stringify({ [DISCORD_DAEMON_NAME]: discordDaemon(DEFAULT_REGION) })}`;
+}
+
+/**
+ * `vercel.json` with the relay's daemon added, given its current contents or
+ * `undefined` when there is none. Returns `undefined` when a daemon of the same
+ * name already exists, so the file is left as it is.
+ */
+export function withDiscordDaemon(vercelJson: string | undefined): string | undefined {
+ let config: Record<string, unknown> = { $schema: "https://openapi.vercel.sh/vercel.json" };
+ if (vercelJson !== undefined) {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(vercelJson);
+ } catch {
+ throw new Error("vercel.json contains invalid JSON; fix it, then run the setup again.");
+ }
+ if (!isObject(parsed)) throw new Error("vercel.json must contain a JSON object.");
+ config = parsed;
+ }
+ if (config.daemons !== undefined && !isObject(config.daemons)) {
+ throw new Error(
+ "vercel.json has a `daemons` value that isn't an object; fix it, then run the setup again.",
+ );
+ }
+ const daemons = isObject(config.daemons) ? config.daemons : {};
+ if (daemons[DISCORD_DAEMON_NAME] !== undefined) return undefined;
+ // Run beside the project's functions, so forwarding stays in one region.
+ const region =
+ Array.isArray(config.regions) && typeof config.regions[0] === "string"
+ ? config.regions[0]
+ : DEFAULT_REGION;
+ const daemon = discordDaemon(region);
+ return `${JSON.stringify({ ...config, daemons: { ...daemons, [DISCORD_DAEMON_NAME]: daemon } }, null, 2)}\n`;
+}
+
+/** Reads a text file, or `undefined` when there is none. */
+export async function readTextFile(path: string): Promise<string | undefined> {
+ try {
+ return await readFile(path, "utf8");
+ } catch (error) {
+ if (isErrnoCode(error, "ENOENT")) return undefined;
+ throw error;
+ }
+}
diff --git a/packages/eve/src/setup/integrations/discord/setup.test.ts b/packages/eve/src/setup/integrations/discord/setup.test.ts
index 968e0b5e0..47d53674a 100644
--- a/packages/eve/src/setup/integrations/discord/setup.test.ts
+++ b/packages/eve/src/setup/integrations/discord/setup.test.ts
@@ -5,20 +5,34 @@ import { integrationSetupEnvironment } from "../shared/environment.js";
import { createSetupContexts } from "../shared/ui.js";
import { applyDiscordSetup, prepareDiscordSetup, type DiscordSetupDeps } from "./setup.js";
-const ANSWERS = {
+const COMMAND_ANSWERS = {
+ "discord-messages": "commands",
"discord-bot-token": " bot-token ",
"discord-command-name": "ask",
"discord-command-description": "Ask the eve agent",
};
-function deps(): DiscordSetupDeps {
- return {
+// Answering messages asks no command questions, so none are supplied.
+const GATEWAY_ANSWERS = {
+ "discord-messages": "gateway",
+ "discord-bot-token": " bot-token ",
+};
+function deps(
+ files: Record<string, string> = { "/project/vercel.json": '{ "framework": "eve" }' },
+ messageContentAllowed = true,
+) {
+ const effects: DiscordSetupDeps = {
configureEndpoint: vi.fn(async () => {}),
deriveConnectorSlug: vi.fn(async () => "agent" as never),
+ enableMessageContent: vi.fn(async () => messageContentAllowed),
provisionConnector: vi.fn(async () => ({ id: "connector", uid: "discord/agent" })),
+ readTextFile: vi.fn(async (path: string) => files[path]),
registerCommand: vi.fn(async () => {}),
resolveApplication: vi.fn(async () => ({ id: "app", name: "Agent", publicKey: "key" })),
writeTextFile: vi.fn(async () => {}),
};
+ const written = () =>
+ new Map(vi.mocked(effects.writeTextFile).mock.calls.map(([path, content]) => [path, content]));
+ return { effects, written };
}
function contexts(
answers: Record<string, unknown>,
@@ -33,44 +47,138 @@ function contexts(
resolveVercelProject,
});
}
+async function runSetup(answers: Record<string, unknown>, effects: DiscordSetupDeps) {
+ const ctx = contexts(answers);
+ return await applyDiscordSetup(
+ await prepareDiscordSetup(ctx.prepare, effects),
+ ctx.apply,
+ effects,
+ );
+}
+const installUrl = (permissions: string) =>
+ `https://discord.com/oauth2/authorize?client_id=app&scope=bot%20applications.commands&permissions=${permissions}`;
describe("Discord setup", () => {
- it("prepares all input before applying", async () => {
- const effects = deps();
- const ctx = contexts(ANSWERS);
+ it("registers a slash command without the relay when people use a command", async () => {
+ const { effects, written } = deps();
+ const ctx = contexts(COMMAND_ANSWERS);
const plan = await prepareDiscordSetup(ctx.prepare, effects);
expect(effects.resolveApplication).not.toHaveBeenCalled();
- await applyDiscordSetup(plan, ctx.apply, effects);
+ const completion = await applyDiscordSetup(plan, ctx.apply, effects);
+
expect(effects.resolveApplication).toHaveBeenCalledWith("bot-token");
- expect(effects.writeTextFile).toHaveBeenCalledWith(
- "/project/agent/channels/discord.ts",
- expect.stringContaining("discord/agent"),
- { force: undefined },
+ expect(effects.registerCommand).toHaveBeenCalledWith("app", "bot-token", {
+ description: "Ask the eve agent",
+ name: "ask",
+ });
+ expect([...written().keys()]).toEqual(["/project/agent/channels/discord.ts"]);
+ expect(written().get("/project/agent/channels/discord.ts")).not.toContain("gateway");
+ expect(completion.facts).toContainEqual({
+ kind: "url",
+ label: "Discord bot install URL",
+ value: installUrl("3072"),
+ });
+ });
+
+ it("scaffolds the Gateway relay and skips the slash command when people message the bot", async () => {
+ const { effects, written } = deps();
+
+ const completion = await runSetup(GATEWAY_ANSWERS, effects);
+
+ expect(effects.registerCommand).not.toHaveBeenCalled();
+ expect(effects.configureEndpoint).toHaveBeenCalledWith("bot-token", "connector");
+ expect(written().get("/project/agent/channels/discord.ts")).toContain("gateway: {},");
+ expect(written().get("/project/daemon/main.ts")).toContain(
+ 'experimental_runDiscordGatewayRelay({\n credentials: connectDiscordCredentials("discord/agent")',
+ );
+ // Setup turned the intent on, so thread follow-ups work without a mention.
+ expect(effects.enableMessageContent).toHaveBeenCalledWith("bot-token");
+ expect(written().get("/project/daemon/main.ts")).toContain("messageContent: true,");
+ expect([...written().keys()]).toEqual(
+ expect.arrayContaining([
+ "/project/daemon/Dockerfile",
+ "/project/daemon/package.json",
+ "/project/daemon/.dockerignore",
+ ]),
);
+ expect(JSON.parse(written().get("/project/vercel.json")!)).toEqual({
+ daemons: {
+ "discord-gateway": { entrypoint: "Dockerfile", instances: { iad1: 1 }, root: "daemon" },
+ },
+ framework: "eve",
+ });
+ // View Channels, Send Messages, Read Message History, Create Public Threads, Send Messages in Threads.
+ expect(completion.facts).toContainEqual({
+ kind: "url",
+ label: "Discord bot install URL",
+ value: installUrl(String(1024 + 2048 + 65536 + 2 ** 35 + 2 ** 38)),
+ });
+ });
+
+ it("scaffolds the relay without Message Content and says how to fix it when Discord refuses", async () => {
+ const { effects, written } = deps(undefined, false);
+
+ const completion = await runSetup(GATEWAY_ANSWERS, effects);
+
+ expect(written().get("/project/daemon/main.ts")).toContain("messageContent: false,");
+ expect(completion.facts).toContainEqual({
+ label: "Enable Message Content",
+ value: expect.stringContaining("Discord Developer Portal"),
+ });
+ });
+
+ it("leaves vercel.ts alone and reports the daemon entry to add", async () => {
+ const { effects, written } = deps({ "/project/vercel.ts": "export default withEve({});" });
+
+ const completion = await runSetup(GATEWAY_ANSWERS, effects);
+
+ expect(written().has("/project/vercel.json")).toBe(false);
+ expect(written().has("/project/vercel.ts")).toBe(false);
+ expect(completion.facts).toContainEqual({
+ label: "Add to the config vercel.ts exports",
+ value: expect.stringContaining('"discord-gateway"'),
+ });
});
+
+ it("refuses an existing relay file before provisioning anything", async () => {
+ const { effects } = deps({ "/project/daemon/main.ts": "// authored" });
+ const resolveVercelProject = vi.fn(async () => ({ orgId: "team", projectId: "project" }));
+
+ await expect(
+ prepareDiscordSetup(contexts(GATEWAY_ANSWERS, resolveVercelProject).prepare, effects),
+ ).rejects.toThrow("/project/daemon/main.ts");
+ expect(resolveVercelProject).not.toHaveBeenCalled();
+ expect(effects.provisionConnector).not.toHaveBeenCalled();
+ });
+
it("refuses missing input before mutation", async () => {
- const effects = deps();
- await expect(prepareDiscordSetup(contexts({}).prepare, effects)).rejects.toMatchObject({
+ const { effects } = deps();
+ await expect(
+ prepareDiscordSetup(contexts({ "discord-messages": "gateway" }).prepare, effects),
+ ).rejects.toMatchObject({
prerequisite: { kind: "environment", variable: "DISCORD_BOT_TOKEN" },
});
expect(effects.resolveApplication).not.toHaveBeenCalled();
});
it("requires a linked project", async () => {
- const effects = deps();
+ const { effects } = deps();
const resolveVercelProject = vi.fn(async () => {
throw new Error("eve link");
});
await expect(
- prepareDiscordSetup(contexts(ANSWERS, resolveVercelProject).prepare, effects),
+ prepareDiscordSetup(contexts(COMMAND_ANSWERS, resolveVercelProject).prepare, effects),
).rejects.toThrow("eve link");
expect(effects.provisionConnector).not.toHaveBeenCalled();
});
it("routes logged-out setup through the project resolver", async () => {
- const effects = deps();
+ const { effects } = deps();
const resolveVercelProject = vi.fn(async () => ({ orgId: "team", projectId: "project" }));
await expect(
- prepareDiscordSetup(contexts(ANSWERS, resolveVercelProject, "logged-out").prepare, effects),
+ prepareDiscordSetup(
+ contexts(COMMAND_ANSWERS, resolveVercelProject, "logged-out").prepare,
+ effects,
+ ),
).resolves.toMatchObject({ project: { orgId: "team", projectId: "project" } });
expect(resolveVercelProject).toHaveBeenCalledWith("Discord");
});
diff --git a/packages/eve/src/setup/integrations/discord/setup.ts b/packages/eve/src/setup/integrations/discord/setup.ts
index 009b1fdba..88cca4e36 100644
--- a/packages/eve/src/setup/integrations/discord/setup.ts
+++ b/packages/eve/src/setup/integrations/discord/setup.ts
@@ -1,9 +1,9 @@
-import { join } from "node:path";
+import { join, relative } from "node:path";
-import { text } from "#setup/ask.js";
+import { select, text } from "#setup/ask.js";
import type { VercelProjectReference } from "#setup/project-resolution.js";
import { deriveSlackConnectorSlug } from "#setup/scaffold/index.js";
-import { writeTextFile } from "#setup/scaffold/files.js";
+import { WriteFileExistsError, writeTextFile } from "#setup/scaffold/files.js";
import {
defineSetupIntegration,
@@ -12,15 +12,26 @@ import {
} from "../types.js";
import {
configureDiscordInteractionsEndpoint,
+ enableDiscordMessageContentIntent,
registerDiscordCommand,
resolveDiscordApplication,
} from "./api.js";
import { provisionDiscordConnector } from "./connect.js";
+import {
+ DISCORD_DAEMON_NAME,
+ DISCORD_DAEMON_ROOT,
+ discordDaemonEntry,
+ discordDaemonFiles,
+ readTextFile,
+ withDiscordDaemon,
+} from "./daemon.js";
export interface DiscordSetupDeps {
configureEndpoint: typeof configureDiscordInteractionsEndpoint;
deriveConnectorSlug: typeof deriveSlackConnectorSlug;
+ enableMessageContent: typeof enableDiscordMessageContentIntent;
provisionConnector: typeof provisionDiscordConnector;
+ readTextFile: typeof readTextFile;
registerCommand: typeof registerDiscordCommand;
resolveApplication: typeof resolveDiscordApplication;
writeTextFile: typeof writeTextFile;
@@ -29,7 +40,9 @@ export interface DiscordSetupDeps {
const defaultDeps: DiscordSetupDeps = {
configureEndpoint: configureDiscordInteractionsEndpoint,
deriveConnectorSlug: deriveSlackConnectorSlug,
+ enableMessageContent: enableDiscordMessageContentIntent,
provisionConnector: provisionDiscordConnector,
+ readTextFile,
registerCommand: registerDiscordCommand,
resolveApplication: resolveDiscordApplication,
writeTextFile,
@@ -44,28 +57,65 @@ function validateCommandName(value: string): string | null {
: "Use lowercase letters, numbers, hyphens, or underscores.";
}
-function connectTemplate(uid: string): string {
+function connectTemplate(uid: string, gateway: boolean): string {
return `import { connectDiscordCredentials } from "@vercel/connect/eve";
import { discordChannel } from "eve/channels/discord";
export default discordChannel({
- credentials: connectDiscordCredentials(${JSON.stringify(uid)}),
+ credentials: connectDiscordCredentials(${JSON.stringify(uid)}),${gateway ? "\n gateway: {}," : ""}
});
`;
}
+/** View Channels and Send Messages, for slash command replies. */
+const COMMAND_PERMISSIONS = "3072";
+/** Also Read Message History, Create Public Threads, and Send Messages in Threads. */
+const GATEWAY_PERMISSIONS = "309237713920";
+
interface DiscordSetupPlan {
botToken: string;
- commandName: string;
- commandDescription: string;
+ /** The slash command to register; absent when the agent answers messages instead. */
+ command?: { readonly name: string; readonly description: string };
+ /** How to register the Gateway relay; absent for slash commands only. */
+ gateway?: DiscordGatewayPlan;
project: VercelProjectReference;
slug: string;
}
+/** The project's Vercel config, checked before anything is written. */
+type DiscordGatewayPlan =
+ /** `vercel.json` with the daemon added, or `undefined` when it's already there. */
+ | { readonly vercelJson: string | undefined }
+ /** The project configures Vercel in `vercel.ts`, which setup doesn't edit. */
+ | { readonly vercelTs: { readonly registered: boolean } };
+
export async function prepareDiscordSetup(
context: SetupPrepareContext,
deps: DiscordSetupDeps = defaultDeps,
): Promise<DiscordSetupPlan> {
+ const messages = await context.asker.ask(
+ select({
+ key: "discord-messages",
+ message: "How should people reach the agent in Discord?",
+ options: [
+ {
+ id: "gateway",
+ value: "gateway" as const,
+ label: "DMs, mentions, and threads",
+ hint: "Adds an experimental Discord Gateway relay that runs as a Vercel Daemon",
+ },
+ {
+ id: "commands",
+ value: "commands" as const,
+ label: "A slash command",
+ hint: "No long-running process",
+ },
+ ],
+ // An experimental, always-on relay is a choice to make, not one for `--yes` to make silently.
+ recommended: "commands" as const,
+ required: true,
+ }),
+ );
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",
);
@@ -80,7 +130,24 @@ export async function prepareDiscordSetup(
}),
)
).trim();
- const commandName = await context.asker.ask(
+ const command = messages === "commands" ? await askCommand(context) : undefined;
+ // Checked before anything remote or on disk changes, so a conflict leaves nothing half-done.
+ const gateway = await preflightFiles(context, messages === "gateway", deps);
+ const project = await context.resolveVercelProject("Discord");
+ const plan: DiscordSetupPlan = {
+ botToken,
+ project,
+ slug: await deps.deriveConnectorSlug(context.appRoot),
+ };
+ if (command !== undefined) plan.command = command;
+ if (gateway !== undefined) plan.gateway = gateway;
+ return plan;
+}
+
+async function askCommand(
+ context: SetupPrepareContext,
+): Promise<{ readonly name: string; readonly description: string }> {
+ const name = await context.asker.ask(
text({
key: "discord-command-name",
message: "Discord command name",
@@ -89,7 +156,7 @@ export async function prepareDiscordSetup(
validate: validateCommandName,
}),
);
- const commandDescription = await context.asker.ask(
+ const description = await context.asker.ask(
text({
key: "discord-command-description",
message: "Discord command description",
@@ -103,13 +170,37 @@ export async function prepareDiscordSetup(
: null,
}),
);
- const project = await context.resolveVercelProject("Discord");
+ return { name: name.trim(), description: description.trim() };
+}
+
+/** Refuses files setup would overwrite without `--force`, and reads the project's Vercel config. */
+async function preflightFiles(
+ context: SetupPrepareContext,
+ gateway: boolean,
+ deps: DiscordSetupDeps,
+): Promise<DiscordGatewayPlan | undefined> {
+ const targets = [
+ join(context.appRoot, "agent/channels/discord.ts"),
+ ...(gateway
+ ? Object.keys(discordDaemonFiles("")).map((path) =>
+ join(context.projectRoot, DISCORD_DAEMON_ROOT, path),
+ )
+ : []),
+ ];
+ if (!context.force) {
+ for (const path of targets) {
+ if ((await deps.readTextFile(path)) !== undefined) throw new WriteFileExistsError(path);
+ }
+ }
+ if (!gateway) return undefined;
+ const vercelTs = await deps.readTextFile(join(context.projectRoot, "vercel.ts"));
+ if (vercelTs !== undefined) {
+ return { vercelTs: { registered: vercelTs.includes(DISCORD_DAEMON_NAME) } };
+ }
return {
- botToken,
- commandName: commandName.trim(),
- commandDescription: commandDescription.trim(),
- project,
- slug: await deps.deriveConnectorSlug(context.appRoot),
+ vercelJson: withDiscordDaemon(
+ await deps.readTextFile(join(context.projectRoot, "vercel.json")),
+ ),
};
}
@@ -127,28 +218,68 @@ export async function applyDiscordSetup(
slug: plan.slug,
signal: context.signal,
});
- await deps.registerCommand(application.id, plan.botToken, {
- name: plan.commandName,
- description: plan.commandDescription,
- });
+ if (plan.command !== undefined) {
+ await deps.registerCommand(application.id, plan.botToken, plan.command);
+ }
+ // Button presses, including on sign-ins, arrive as interactions even without a command.
await deps.configureEndpoint(plan.botToken, connector.id);
+ const { gateway } = plan;
await deps.writeTextFile(
join(context.appRoot, "agent/channels/discord.ts"),
- connectTemplate(connector.uid),
+ connectTemplate(connector.uid, gateway !== undefined),
{ force: context.force },
);
- const installUrl = `https://discord.com/oauth2/authorize?client_id=${encodeURIComponent(application.id)}&scope=${encodeURIComponent("bot applications.commands")}&permissions=3072`;
+ const facts: { label: string; value: string; kind?: "url" }[] = [];
+ if (gateway !== undefined) {
+ // Without it, a thread's follow-ups arrive empty unless they mention the bot.
+ const messageContent = await deps.enableMessageContent(plan.botToken).catch(() => false);
+ if (!messageContent) {
+ facts.push({
+ label: "Enable Message Content",
+ value: `Discord didn't let setup turn on Message Content Intent, so thread follow-ups must mention the bot. Turn it on under Bot in the Discord Developer Portal, then set messageContent: true in ${DISCORD_DAEMON_ROOT}/main.ts.`,
+ });
+ }
+ for (const [path, content] of Object.entries(
+ discordDaemonFiles(connector.uid, { messageContent }),
+ )) {
+ await deps.writeTextFile(join(context.projectRoot, DISCORD_DAEMON_ROOT, path), content, {
+ force: context.force,
+ });
+ }
+ if ("vercelJson" in gateway && gateway.vercelJson !== undefined) {
+ await deps.writeTextFile(join(context.projectRoot, "vercel.json"), gateway.vercelJson, {
+ force: true,
+ });
+ }
+ if ("vercelTs" in gateway && !gateway.vercelTs.registered) {
+ facts.push({
+ label: `Add to the config ${relative(context.appRoot, join(context.projectRoot, "vercel.ts")) || "vercel.ts"} exports`,
+ value: discordDaemonEntry(),
+ });
+ }
+ }
+ const installUrl = `https://discord.com/oauth2/authorize?client_id=${encodeURIComponent(application.id)}&scope=${encodeURIComponent("bot applications.commands")}&permissions=${gateway !== undefined ? GATEWAY_PERMISSIONS : COMMAND_PERMISSIONS}`;
context.presenter.nextSteps([
- `Install the Discord application, then try /${plan.commandName}: ${installUrl}`,
+ plan.command !== undefined
+ ? `Install the bot from its install URL, then try /${plan.command.name}.`
+ : "Install the bot from its install URL, then DM it or mention it in a channel.",
+ ...(gateway !== undefined
+ ? [
+ `Deploy to start the experimental Gateway relay in ${DISCORD_DAEMON_ROOT}/. Run one instance per bot.`,
+ ]
+ : []),
]);
return {
deploymentRequired: true as const,
+ // A fact, unlike a next step, stays visible after `/add` in `eve dev` collapses its panel.
facts: [
+ { label: "Discord bot install URL", value: installUrl, kind: "url" as const },
{
label: "Discord application dashboard",
value: `https://discord.com/developers/applications/${application.id}/information`,
kind: "url" as const,
},
+ ...facts,
],
};
}
@@ -156,7 +287,7 @@ export async function applyDiscordSetup(
export const DISCORD_SETUP = defineSetupIntegration({
kind: "discord",
label: "Discord",
- hint: "Slash commands and interactions",
+ hint: "Messages, DMs, and slash commands",
prepare: prepareDiscordSetup,
apply: applyDiscordSetup,
});