Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

[1/2] feat(slack): support shortcuts (#2661)

Ben Pankowd87cf4050ceb
diff --git a/.changeset/tidy-shrimps-wave.md b/.changeset/tidy-shrimps-wave.md
new file mode 100644
index 000000000..a90851bdf
--- /dev/null
+++ b/.changeset/tidy-shrimps-wave.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Add an `onShortcut` hook to the Slack channel for message and global shortcuts. Shortcut handlers receive normalized payload data and workspace-scoped Slack API access.
diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdx
index f506eedc0..a0879f15a 100644
--- a/docs/channels/slack.mdx
+++ b/docs/channels/slack.mdx
@@ -57,7 +57,7 @@ This option does not create or install the Slack app. Configure it in [Slack app
2. Install or reinstall the app, copy its Bot User OAuth Token to `SLACK_BOT_TOKEN`, and copy the signing secret from **Basic Information** to `SLACK_SIGNING_SECRET`.
3. 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 or HITL prompts.
+5. Under **Interactivity & Shortcuts**, use the same Request URL when the agent uses buttons, shortcuts, or HITL prompts.
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).
@@ -156,6 +156,8 @@ Only the first available handler runs. A message hook returning `null` drops the
`onInteraction(action, ctx)` separately handles user-owned `block_actions` callbacks. eve-owned HITL buttons and modal submissions go through `onInputResponse(ctx, submission)` instead. eve attaches the triggering Slack user id to the same model message as its text, preserving speaker attribution without profile lookups.
+Use `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.
+
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.
@@ -364,7 +366,7 @@ const session = await ctx.resolveSession({ target });
### Slack API calls outside a handler
-Inside inbound webhook handlers such as `onAppMention`, `onEvent`, `onInteraction`, 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`, 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
messages, for example, has no inbound Slack request. For that, call the
same primitive the handle uses directly:
diff --git a/packages/eve/src/public/channels/slack/index.ts b/packages/eve/src/public/channels/slack/index.ts
index acc819d27..bf583afc7 100644
--- a/packages/eve/src/public/channels/slack/index.ts
+++ b/packages/eve/src/public/channels/slack/index.ts
@@ -35,6 +35,9 @@ export {
type SlackInstrumentationMetadata,
type SlackInteractionAction,
type SlackInteractionContext,
+ type SlackShortcut,
+ type SlackShortcutContext,
+ type SlackShortcutMessage,
type SlackMentionResult,
type SlackMentionResultOrPromise,
type SlackReceiveTarget,
diff --git a/packages/eve/src/public/channels/slack/interactions.test.ts b/packages/eve/src/public/channels/slack/interactions.test.ts
index 68d0ef98f..082265edb 100644
--- a/packages/eve/src/public/channels/slack/interactions.test.ts
+++ b/packages/eve/src/public/channels/slack/interactions.test.ts
@@ -1,7 +1,10 @@
import { describe, expect, it } from "vitest";
import { parseSlackWebhookBody } from "#compiled/@chat-adapter/slack/webhook.js";
-import { parseBlockActionsPayload } from "#public/channels/slack/interactions.js";
+import {
+ parseBlockActionsPayload,
+ parseShortcutPayload,
+} from "#public/channels/slack/interactions.js";
function makePayload(overrides: Record<string, unknown>): Record<string, unknown> {
return {
@@ -19,6 +22,65 @@ function makePayload(overrides: Record<string, unknown>): Record<string, unknown
};
}
+describe("parseShortcutPayload", () => {
+ it("normalizes a message shortcut", () => {
+ expect(
+ parseShortcutPayload({
+ type: "message_action",
+ callback_id: "summarize_message",
+ trigger_id: "trigger-123",
+ team: { id: "T_INSTALLATION" },
+ user: { id: "U01", username: "ada", team_id: "T_ACTOR" },
+ channel: { id: "C01" },
+ message: {
+ text: "Please summarize this",
+ ts: "1700000000.000200",
+ thread_ts: "1700000000.000100",
+ user: "U02",
+ },
+ response_url: "https://hooks.slack.com/actions/example",
+ }),
+ ).toEqual({
+ type: "message_action",
+ callbackId: "summarize_message",
+ triggerId: "trigger-123",
+ teamId: "T_ACTOR",
+ user: { id: "U01", username: "ada", name: undefined },
+ channelId: "C01",
+ message: {
+ text: "Please summarize this",
+ ts: "1700000000.000200",
+ threadTs: "1700000000.000100",
+ userId: "U02",
+ },
+ responseUrl: "https://hooks.slack.com/actions/example",
+ });
+ });
+
+ it("normalizes a global shortcut without message fields", () => {
+ expect(
+ parseShortcutPayload({
+ type: "shortcut",
+ callback_id: "new_request",
+ trigger_id: "trigger-456",
+ team: { id: "T01" },
+ user: { id: "U01", name: "ada" },
+ }),
+ ).toEqual({
+ type: "shortcut",
+ callbackId: "new_request",
+ triggerId: "trigger-456",
+ teamId: "T01",
+ user: { id: "U01", username: undefined, name: "ada" },
+ });
+ });
+
+ it("rejects malformed and unrelated interaction payloads", () => {
+ expect(parseShortcutPayload({ type: "block_actions" })).toBeNull();
+ expect(parseShortcutPayload({ type: "shortcut", callback_id: "missing-fields" })).toBeNull();
+ });
+});
+
describe("parseBlockActionsPayload", () => {
it("exposes the actor as a nested user object on each parsed action", () => {
const parsed = parseBlockActionsPayload(
diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.ts
index 008848d5a..a7b1abbd4 100644
--- a/packages/eve/src/public/channels/slack/interactions.ts
+++ b/packages/eve/src/public/channels/slack/interactions.ts
@@ -1,7 +1,7 @@
/**
- * Slack `block_actions` + `view_submission` wire handling. It decodes and
- * authorizes framework HITL responses, opens freeform modals inline before
- * Slack's trigger expires, and forwards user-owned actions to `onInteraction`.
+ * 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.
*/
import {
@@ -13,6 +13,7 @@ import {
import { createLogger } from "#internal/logging.js";
import {
buildSlackBinding,
+ buildSlackWorkspaceHandle,
resolveSlackBotToken,
slackContinuationToken,
} from "#public/channels/slack/api.js";
@@ -44,6 +45,8 @@ import type {
SlackInteractionAction,
SlackInteractionContext,
SlackInteractionUser,
+ SlackShortcut,
+ SlackShortcutContext,
} from "#public/channels/slack/slackChannel.js";
import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";
import { bindSlackSessionOperations } from "#public/channels/slack/session-operations.js";
@@ -238,7 +241,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,
- * and forwards anything else to `config.onInteraction`.
+ * forwards other block actions to `config.onInteraction`, and forwards Slack
+ * shortcuts to `config.onShortcut`.
*/
export async function handleInteractionPost(
rawBody: string,
@@ -265,7 +269,20 @@ export async function handleInteractionPost(
return handleViewSubmission(payload, ctx, deps);
}
- if (payload.kind !== "block_actions") return ack;
+ if (payload.kind === "unsupported") {
+ const shortcut = parseShortcutPayload(payload.raw);
+ if (shortcut !== null) {
+ dispatchShortcut(shortcut, readInstallationTeamId(payload.raw), ctx, deps);
+ return new Response(null, { status: 200 });
+ }
+ log.warn("unsupported Slack interaction payload ignored", { type: payload.type });
+ return ack;
+ }
+
+ if (payload.kind !== "block_actions") {
+ log.warn("unsupported Slack interaction payload ignored", { type: payload.kind });
+ return ack;
+ }
const interaction = parseBlockActionsPayload(payload);
if (!interaction) return ack;
@@ -348,6 +365,111 @@ export async function handleInteractionPost(
return ack;
}
+/** Normalizes Slack's two shortcut payload variants. */
+export function parseShortcutPayload(raw: unknown): SlackShortcut | null {
+ if (!isObjectRecord(raw)) return null;
+ const type = raw.type;
+ if (type !== "message_action" && type !== "shortcut") return null;
+
+ const callbackId = readRequiredString(raw.callback_id);
+ const triggerId = readRequiredString(raw.trigger_id);
+ const userBlock = isObjectRecord(raw.user) ? raw.user : undefined;
+ const userId = readRequiredString(userBlock?.id);
+ if (callbackId === null || triggerId === null || userId === null) return null;
+
+ const teamBlock = isObjectRecord(raw.team) ? raw.team : undefined;
+ const teamId = readOptionalString(userBlock?.team_id) ?? readOptionalString(teamBlock?.id);
+ const user: SlackInteractionUser = {
+ id: userId,
+ username: readOptionalString(userBlock?.username),
+ name: readOptionalString(userBlock?.name),
+ };
+
+ if (type === "shortcut") {
+ return { type, callbackId, triggerId, user, teamId };
+ }
+
+ const channelBlock = isObjectRecord(raw.channel) ? raw.channel : undefined;
+ const messageBlock = isObjectRecord(raw.message) ? raw.message : undefined;
+ const channelId = readRequiredString(channelBlock?.id);
+ const messageTs = readRequiredString(messageBlock?.ts);
+ if (channelId === null || messageTs === null || messageBlock === undefined) return null;
+
+ return {
+ type,
+ callbackId,
+ triggerId,
+ user,
+ teamId,
+ channelId,
+ message: {
+ text: typeof messageBlock.text === "string" ? messageBlock.text : "",
+ ts: messageTs,
+ threadTs: readOptionalString(messageBlock.thread_ts),
+ userId: readOptionalString(messageBlock.user),
+ },
+ responseUrl: readOptionalString(raw.response_url),
+ };
+}
+
+function readRequiredString(value: unknown): string | null {
+ return typeof value === "string" && value.length > 0 ? value : null;
+}
+
+function readOptionalString(value: unknown): string | undefined {
+ return typeof value === "string" && value.length > 0 ? value : undefined;
+}
+
+function dispatchShortcut(
+ shortcut: SlackShortcut,
+ installationTeamId: string | undefined,
+ ctx: { readonly waitUntil: (task: Promise<unknown>) => void },
+ deps: InteractionHandlerDeps,
+): void {
+ const onShortcut = deps.config.onShortcut;
+ if (onShortcut === undefined) {
+ log.warn("Slack shortcut ignored because onShortcut is not configured", {
+ type: shortcut.type,
+ });
+ return;
+ }
+
+ const shortcutCtx: SlackShortcutContext = buildShortcutContext({
+ config: deps.config,
+ installationTeamId,
+ teamId: shortcut.teamId,
+ });
+ dispatchInteractionHook(() => onShortcut(shortcut, shortcutCtx), ctx, "shortcut handler failed");
+}
+
+function buildShortcutContext(input: {
+ readonly config: SlackChannelConfig;
+ readonly installationTeamId: string | undefined;
+ readonly teamId: string | undefined;
+}): SlackShortcutContext {
+ return {
+ slack: buildSlackWorkspaceHandle({
+ botToken: input.config.credentials?.botToken,
+ installationTeamId: input.installationTeamId,
+ teamId: input.teamId,
+ }),
+ };
+}
+
+function dispatchInteractionHook(
+ handler: () => void | Promise<void>,
+ ctx: { readonly waitUntil: (task: Promise<unknown>) => void },
+ failureMessage: string,
+): void {
+ ctx.waitUntil(
+ Promise.resolve()
+ .then(handler)
+ .catch((error: unknown) => {
+ log.error(failureMessage, { error });
+ }),
+ );
+}
+
async function dispatchBlockInputResponses(input: {
readonly ctx: {
from: ChannelFrom<SlackChannelState>;
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index ca9a45280..b734c5114 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -2622,6 +2622,82 @@ describe("slackChannel() HITL interaction pipeline", () => {
}
});
+ 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) => {
+ expect(shortcut).toMatchObject({
+ type: "message_action",
+ callbackId: "summarize_message",
+ triggerId: "trigger-123",
+ channelId: "C01",
+ message: {
+ text: "Please summarize this",
+ ts: "1700000000.000010",
+ threadTs: "1700000000.000001",
+ userId: "U02",
+ },
+ user: { id: "U01", username: "ada" },
+ teamId: "T_ACTOR",
+ });
+ expect(ctx.slack.teamId).toBe("T_ACTOR");
+ await ctx.slack.request("auth.test", {});
+ });
+ const channel = slackChannel({ credentials: { botToken }, onShortcut });
+
+ const { response, waitUntil } = await firePost(
+ channel,
+ buildSignedInteractionRequest({
+ type: "message_action",
+ callback_id: "summarize_message",
+ trigger_id: "trigger-123",
+ team: { id: "T_INSTALLATION" },
+ user: { id: "U01", username: "ada", team_id: "T_ACTOR" },
+ channel: { id: "C01" },
+ message: {
+ text: "Please summarize this",
+ ts: "1700000000.000010",
+ thread_ts: "1700000000.000001",
+ user: "U02",
+ },
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ await expect(response.text()).resolves.toBe("");
+ expect(onShortcut).toHaveBeenCalledTimes(1);
+ expect(waitUntil).toHaveBeenCalledTimes(1);
+ expect(botToken).toHaveBeenCalledWith({ teamId: "T_INSTALLATION" });
+ 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("delivers global shortcuts without channel or message fields", async () => {
+ const onShortcut = vi.fn();
+ const channel = slackChannel({ onShortcut });
+
+ await firePost(
+ channel,
+ buildSignedInteractionRequest({
+ type: "shortcut",
+ callback_id: "new_request",
+ trigger_id: "trigger-456",
+ team: { id: "T01" },
+ user: { id: "U01", name: "ada" },
+ }),
+ );
+
+ expect(onShortcut).toHaveBeenCalledWith(
+ {
+ type: "shortcut",
+ callbackId: "new_request",
+ triggerId: "trigger-456",
+ teamId: "T01",
+ user: { id: "U01", username: undefined, name: "ada" },
+ },
+ expect.objectContaining({ slack: expect.any(Object) }),
+ );
+ });
+
it("cancels the interaction's Slack thread from onInteraction", async () => {
const channel = slackChannel({
credentials: { botToken: "xoxb-test" },
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index d1327f3c1..4d3873936 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -396,6 +396,12 @@ export interface SlackInboundMessageContext extends SlackContext, SlackSessionOp
/** Interaction-scoped context handed to `slackChannel({ onInteraction })`. */
export interface SlackInteractionContext extends SlackContext, SlackSessionOperations {}
+/** Workspace-scoped context handed to `slackChannel({ onShortcut })`. */
+export interface SlackShortcutContext {
+ /** 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. */
@@ -433,7 +439,7 @@ export interface SlackInteractionAction {
readonly user: SlackInteractionUser;
}
-/** Slack actor on {@link SlackInteractionAction.user}, mirroring `body.user`. */
+/** Slack actor on an interactive payload, mirroring `body.user`. */
export interface SlackInteractionUser {
readonly id: string;
/** Modern canonical display handle. */
@@ -442,6 +448,34 @@ export interface SlackInteractionUser {
readonly name?: string;
}
+/** Message selected through a Slack message shortcut. */
+export interface SlackShortcutMessage {
+ readonly text: string;
+ readonly ts: string;
+ readonly threadTs?: string;
+ readonly userId?: string;
+}
+
+/** Decoded Slack message shortcut or global shortcut. */
+export type SlackShortcut =
+ | {
+ readonly type: "message_action";
+ readonly callbackId: string;
+ readonly triggerId: string;
+ readonly user: SlackInteractionUser;
+ readonly teamId?: string;
+ readonly channelId: string;
+ readonly message: SlackShortcutMessage;
+ readonly responseUrl?: string;
+ }
+ | {
+ readonly type: "shortcut";
+ readonly callbackId: string;
+ readonly triggerId: string;
+ readonly user: SlackInteractionUser;
+ readonly teamId?: string;
+ };
+
/** Decoded eve-owned HITL response submitted through Slack interactivity. */
export type SlackInputResponseSubmission =
| {
@@ -651,6 +685,15 @@ export interface SlackChannelConfig {
ctx: SlackInteractionContext,
): void | Promise<void>;
+ /**
+ * Handles Slack message shortcuts (`message_action`) and global shortcuts
+ * (`shortcut`) with workspace-scoped Slack Web API access.
+ *
+ * eve returns `200 OK` immediately and keeps the handler alive through
+ * `waitUntil()`. Errors are caught and logged.
+ */
+ onShortcut?(shortcut: SlackShortcut, ctx: SlackShortcutContext): 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 keep