The Open Framework for Building Agents
[2/2] feat(slack): support slash commands (#2667)
Ben Pankowf0622995ae86
diff --git a/.changeset/slack-commands-wave.md b/.changeset/slack-commands-wave.mdnew file mode 100644index 000000000..b1233aa90--- /dev/null+++ b/.changeset/slack-commands-wave.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Slack channels can now handle signed slash command payloads with `onSlashCommand`, including command arguments, actor and channel identity, trigger metadata, and workspace-scoped Slack API access.diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex a0879f15a..d496d9e13 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -1,10 +1,10 @@---title: "Slack"-description: "Reach your agent from Slack app mentions and DMs with Vercel Connect-managed credentials, threaded replies, and interactive buttons."+description: "Reach your agent from Slack app mentions, DMs, slash commands, and interactive callbacks."type: integration----The Slack channel puts your agent inside a workspace. It answers `@mentions` and DMs, replies in threads, shows typing indicators, and turns human-in-the-loop (HITL) prompts into buttons. [Vercel Connect](https://vercel.com/kb/guide/vercel-connect) is the recommended setup: it manages the Slack bot token, verifies inbound requests, supports token rotation and multiple workspace installations, and forwards events to your agent without copying Slack secrets into your project environment. If you cannot use Vercel Connect, you can provide the bot token and signing secret through environment variables. See [Channels](./overview) for the contract this builds on.+The Slack channel puts your agent inside a workspace. It handles `@mentions`, DMs, slash commands, shortcuts, and interactive callbacks; replies in threads; shows typing indicators; and turns human-in-the-loop (HITL) prompts into buttons. [Vercel Connect](https://vercel.com/kb/guide/vercel-connect) is the recommended setup: it manages the Slack bot token, verifies inbound requests, supports token rotation and multiple workspace installations, and forwards events to your agent without copying Slack secrets into your project environment. If you cannot use Vercel Connect, you can provide the bot token and signing secret through environment variables. See [Channels](./overview) for the contract this builds on.## Add the channel@@ -58,6 +58,7 @@ This option does not create or install the Slack app. Configure it in [Slack app3. Set both values in `.env.local` for local development or in the target runtime's environment, then start or deploy the agent at a public URL.4. Under **Event Subscriptions**, set the Request URL to `https://your-agent.example/eve/v1/slack`. Subscribe to `app_mention`, plus `message.im` for DMs.5. Under **Interactivity & Shortcuts**, use the same Request URL when the agent uses buttons, shortcuts, or HITL prompts.+6. Under **Slash Commands**, create each command your app handles and use the same Request URL.Add the matching message events and history scopes if you also want unmentioned thread replies, as described in [Continue conversations without repeated mentions](#continue-conversations-without-repeated-mentions).@@ -158,6 +159,23 @@ Only the first available handler runs. A message hook returning `null` drops theUse `onShortcut(shortcut, ctx)` for message shortcuts and global shortcuts configured under **Interactivity & Shortcuts** in your Slack app. The handler receives the shortcut callback ID, user, workspace, and trigger ID. Message shortcuts also include the selected message and channel. The context exposes workspace-scoped Slack API access because global shortcuts have no channel or message. eve acknowledges shortcut requests immediately and keeps their handlers alive in the background.+Use `onSlashCommand(command, ctx)` for commands configured under **Slash Commands** in your Slack app. The handler receives the command name, argument text, invoking user, channel, workspace, trigger ID, and response URL. It also receives workspace-scoped Slack API access. eve acknowledges slash commands immediately with an empty `200 OK` response and keeps the handler alive in the background:++```ts title="agent/channels/slack.ts"+import { slackChannel } from "eve/channels/slack";++export default slackChannel({+ async onSlashCommand(command, ctx) {+ if (command.command !== "/ask") return;+ await ctx.slack.request("chat.postEphemeral", {+ channel: command.channelId,+ user: command.user.id,+ text: `Received: ${command.text}`,+ });+ },+});+```+The model-visible `<slack_message>` includes `sender_id`, `bot_user_id` when available, and the `is_mentioned` value from `ctx.isBotMentioned()`. Its `<content>` keeps `<@USER_ID>` intact while converting other mrkdwn to Markdown; routing is unchanged.When a Slack message shares another Slack message, eve extracts the forwarded message body from Slack's message-unfurl attachment and includes it in `<content>`. The original top-level comment, when present, remains alongside the forwarded content.@@ -362,11 +380,11 @@ const session = await ctx.resolveSession({ target });`onEvent` is the raw fallback after the message hooks. If an event is not claimed by `onAppMention`, `onDirectMessage`, or `onMessage`, an authored `onEvent` receives it; otherwise eve applies the built-in mention/DM default or ignores it.-`onEvent` covers JSON `event_callback` deliveries only. URL verification, slash commands, and interactive payloads do not reach it. Add every desired event and required OAuth scope to the Slack app's Event Subscriptions configuration; eve can only handle events Slack sends.+`onEvent` covers JSON `event_callback` deliveries only. URL verification, slash commands, and interactive payloads do not reach it. Slash commands reach `onSlashCommand`; add every desired event and required OAuth scope to the Slack app's Event Subscriptions configuration so other callbacks reach their handlers.### Slack API calls outside a handler-Inside inbound webhook handlers such as `onAppMention`, `onEvent`, `onInteraction`, `onShortcut`, and `onInputResponse`, `ctx.slack.request(operation, body)` is the raw-API escape hatch. Inside an `events` handler, use `channel.slack.request(...)` instead. Outside those contexts there is no handle — a schedule resolving reactions on old+Inside inbound webhook handlers such as `onAppMention`, `onEvent`, `onInteraction`, `onShortcut`, `onSlashCommand`, and `onInputResponse`, `ctx.slack.request(operation, body)` is the raw-API escape hatch. Inside an `events` handler, use `channel.slack.request(...)` instead. Outside those contexts there is no handle — a schedule resolving reactions on oldmessages, for example, has no inbound Slack request. For that, call thesame primitive the handle uses directly:diff --git a/packages/eve/src/public/channels/slack/index.ts b/packages/eve/src/public/channels/slack/index.tsindex bf583afc7..54e33d77d 100644--- a/packages/eve/src/public/channels/slack/index.ts+++ b/packages/eve/src/public/channels/slack/index.ts@@ -35,6 +35,8 @@ export {type SlackInstrumentationMetadata,type SlackInteractionAction,type SlackInteractionContext,+ type SlackSlashCommand,+ type SlackSlashCommandContext,type SlackShortcut,type SlackShortcutContext,type SlackShortcutMessage,diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.tsindex a7b1abbd4..1eb15a36d 100644--- a/packages/eve/src/public/channels/slack/interactions.ts+++ b/packages/eve/src/public/channels/slack/interactions.ts@@ -1,7 +1,7 @@/*** Slack interactivity wire handling. It decodes and authorizes framework HITL* responses, opens freeform modals inline before Slack's trigger expires, and- * forwards user-owned actions and shortcuts to their authored hooks.+ * forwards user-owned actions, shortcuts, and slash commands to their authored hooks.*/import {@@ -50,6 +50,7 @@ import type {} from "#public/channels/slack/slackChannel.js";import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";import { bindSlackSessionOperations } from "#public/channels/slack/session-operations.js";+import { dispatchSlashCommand } from "#public/channels/slack/slash-command.js";import { parseInputResponse } from "#shared/input.js";const log = createLogger("slack.interactions");@@ -241,8 +242,8 @@ export interface InteractionHandlerDeps {* `view_submission` payloads to the freeform-answer flow, intercepts* "Type your answer" button clicks to open a modal, resolves* framework HITL clicks through `onInputResponse` to the parked session,- * forwards other block actions to `config.onInteraction`, and forwards Slack- * shortcuts to `config.onShortcut`.+ * forwards other block actions to `config.onInteraction`, shortcuts to+ * `config.onShortcut`, and slash commands to `config.onSlashCommand`.*/export async function handleInteractionPost(rawBody: string,@@ -269,6 +270,11 @@ export async function handleInteractionPost(return handleViewSubmission(payload, ctx, deps);}+ if (payload.kind === "slash_command") {+ dispatchSlashCommand(payload, ctx, deps.config);+ return new Response(null, { status: 200 });+ }+if (payload.kind === "unsupported") {const shortcut = parseShortcutPayload(payload.raw);if (shortcut !== null) {diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.tsindex b734c5114..65d36daae 100644--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts@@ -192,6 +192,27 @@ function buildSignedInteractionRequest(payload: Record<string, unknown>): Reques});}+function buildSignedSlashCommandRequest(overrides: Record<string, string> = {}): Request {+ const body = new URLSearchParams({+ command: "/ask",+ text: "summarize this channel",+ user_id: "U01",+ user_name: "ada",+ team_id: "T01",+ channel_id: "C01",+ channel_name: "general",+ enterprise_id: "E01",+ is_enterprise_install: "true",+ trigger_id: "trigger-123",+ response_url: "https://hooks.slack.com/commands/example",+ ...overrides,+ }).toString();+ return buildSignedRequest({+ body,+ contentType: "application/x-www-form-urlencoded",+ });+}+let mentionCounter = 0;function buildMentionBody(overrides?: {@@ -2622,6 +2643,47 @@ describe("slackChannel() HITL interaction pipeline", () => {}});+ it("delivers slash commands with workspace-scoped Slack API access", async () => {+ const botToken = vi.fn((_context: { readonly teamId?: string }) => "xoxb-test");+ const onSlashCommand = vi.fn(async (command, ctx) => {+ expect(command).toEqual({+ command: "/ask",+ text: "summarize this channel",+ user: { id: "U01", username: "ada" },+ teamId: "T01",+ channelId: "C01",+ channelName: "general",+ enterpriseId: "E01",+ isEnterpriseInstall: true,+ triggerId: "trigger-123",+ responseUrl: "https://hooks.slack.com/commands/example",+ });+ expect(ctx.slack.teamId).toBe("T01");+ await ctx.slack.request("auth.test", {});+ });+ const channel = slackChannel({ credentials: { botToken }, onSlashCommand });++ const { response, waitUntil } = await firePost(channel, buildSignedSlashCommandRequest());++ expect(response.status).toBe(200);+ await expect(response.text()).resolves.toBe("");+ expect(onSlashCommand).toHaveBeenCalledTimes(1);+ expect(waitUntil).toHaveBeenCalledTimes(1);+ expect(botToken).toHaveBeenCalledWith({ teamId: "T01" });+ expect(String(fetchMock.mock.calls[0]?.[0])).toBe("https://slack.com/api/auth.test");+ expect((fetchMock.mock.calls[0]?.[1] as RequestInit | undefined)?.method).toBe("POST");+ });++ it("acknowledges slash commands without a configured handler", async () => {+ const channel = slackChannel({});++ const { response, waitUntil } = await firePost(channel, buildSignedSlashCommandRequest());++ expect(response.status).toBe(200);+ await expect(response.text()).resolves.toBe("");+ expect(waitUntil).not.toHaveBeenCalled();+ });+it("delivers message shortcuts with workspace-scoped Slack API access", async () => {const botToken = vi.fn((_context: { readonly teamId?: string }) => "xoxb-test");const onShortcut = vi.fn(async (shortcut, ctx) => {diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.tsindex 4d3873936..404cb239f 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -402,6 +402,12 @@ export interface SlackShortcutContext {readonly slack: SlackWorkspaceHandle;}+/** Workspace-scoped context handed to `slackChannel({ onSlashCommand })`. */+export interface SlackSlashCommandContext {+ /** Slack workspace identity and raw Web API escape hatch. */+ readonly slack: SlackWorkspaceHandle;+}+/** Context handed to `slackChannel({ onInputResponse })` before eve resumes HITL. */export interface SlackInputResponseContext extends SlackContext {/** Auth derived from the Slack user who submitted the signed interaction. */@@ -448,6 +454,21 @@ export interface SlackInteractionUser {readonly name?: string;}+/** Decoded Slack slash command invocation. */+export interface SlackSlashCommand {+ /** Configured command name, including its leading slash. */+ readonly command: string;+ readonly text: string;+ readonly user: SlackInteractionUser;+ readonly teamId?: string;+ readonly channelId: string;+ readonly channelName?: string;+ readonly enterpriseId?: string;+ readonly isEnterpriseInstall: boolean;+ readonly triggerId?: string;+ readonly responseUrl?: string;+}+/** Message selected through a Slack message shortcut. */export interface SlackShortcutMessage {readonly text: string;@@ -694,6 +715,16 @@ export interface SlackChannelConfig {*/onShortcut?(shortcut: SlackShortcut, ctx: SlackShortcutContext): void | Promise<void>;+ /**+ * Handles Slack slash commands configured with this channel's webhook route.+ * The command includes the configured command name, arguments, invoking user,+ * channel, workspace, trigger ID, and response URL.+ *+ * eve returns an empty `200 OK` immediately and keeps the handler alive+ * through `waitUntil()`. Errors are caught and logged.+ */+ onSlashCommand?(command: SlackSlashCommand, ctx: SlackSlashCommandContext): void | Promise<void>;+/*** Authorizes an eve-owned HITL answer before the pending input resolves.* Return `{ auth }` to accept the response, or `null` to reject it and keepdiff --git a/packages/eve/src/public/channels/slack/slash-command.ts b/packages/eve/src/public/channels/slack/slash-command.tsnew file mode 100644index 000000000..98ed773f2--- /dev/null+++ b/packages/eve/src/public/channels/slack/slash-command.ts@@ -0,0 +1,61 @@+import { type parseSlackWebhookBody } from "#compiled/@chat-adapter/slack/webhook.js";++import { createLogger } from "#internal/logging.js";+import { buildSlackWorkspaceHandle } from "#public/channels/slack/api.js";+import type {+ SlackChannelConfig,+ SlackSlashCommand,+ SlackSlashCommandContext,+} from "#public/channels/slack/slackChannel.js";++const log = createLogger("slack.slash-command");++type SlashCommandPayload = Extract<+ ReturnType<typeof parseSlackWebhookBody>,+ { kind: "slash_command" }+>;++export function dispatchSlashCommand(+ payload: SlashCommandPayload,+ ctx: { readonly waitUntil: (task: Promise<unknown>) => void },+ config: SlackChannelConfig,+): void {+ const command = parseSlashCommandPayload(payload);+ const onSlashCommand = config.onSlashCommand;+ if (onSlashCommand === undefined) {+ log.warn("Slack slash command ignored because onSlashCommand is not configured", {+ command: command.command,+ });+ return;+ }++ const commandCtx: SlackSlashCommandContext = {+ slack: buildSlackWorkspaceHandle({+ botToken: config.credentials?.botToken,+ installationTeamId: command.teamId,+ teamId: command.teamId,+ }),+ };+ ctx.waitUntil(+ Promise.resolve()+ .then(() => onSlashCommand(command, commandCtx))+ .catch((error: unknown) => {+ log.error("slash command handler failed", { error });+ }),+ );+}++function parseSlashCommandPayload(payload: SlashCommandPayload): SlackSlashCommand {+ return {+ command: payload.command,+ text: payload.text,+ user: { id: payload.userId, username: payload.userName },+ teamId: payload.teamId,+ channelId: payload.channelId,+ channelName: payload.channelName,+ enterpriseId: payload.enterpriseId,+ isEnterpriseInstall: payload.isEnterpriseInstall,+ triggerId: payload.triggerId,+ responseUrl: payload.responseUrl,+ };+}