The Open Framework for Building Agents
feat(eve): slack - add generic event handler (#1044)
Andrew Barba1a618ba89e26
diff --git a/.changeset/tidy-slack-events.md b/.changeset/tidy-slack-events.mdnew file mode 100644index 000000000..0b94ebcfd--- /dev/null+++ b/.changeset/tidy-slack-events.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add a generic Slack `onEvent` fallback for subscribed Events API callbacks. Handlers can use a Slack-bound `receive` function to start zero, one, or many agent turns while authored mention and direct-message handlers retain precedence.diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex d45e21c54..f55f43acd 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -44,18 +44,53 @@ VERCEL_USE_EXPERIMENTAL_FRAMEWORKS=1 vercel deploy --prod`VERCEL_USE_EXPERIMENTAL_FRAMEWORKS=1` lets the Vercel CLI recognize eve as a framework during the build. eve's own setup commands set the same flag.-## How the channel handles messages+## How the channel handles inbound events### Dispatch-Inbound hooks decide whether to dispatch a turn and with what `auth`. Return `{ auth }` to dispatch, `null` to drop, or `{ auth, context }` to inject background into history.+The message hooks decide whether to dispatch a turn and with what `auth`. Return `{ auth }` to dispatch, `null` to drop, or `{ auth, context }` to inject background into history.- `onAppMention(ctx, message)` handles `app_mention` events. The default derives workspace-scoped auth and posts a `Thinking…` indicator.- `onDirectMessage(ctx, message)` handles `message.im` events (needs `im:history` scope). Bot-authored messages and edits are filtered out first.-- `onInteraction(action, ctx)` handles `block_actions` callbacks not consumed by HITL.++`onInteraction(action, ctx)` separately handles `block_actions` callbacks not consumed by HITL.eve attaches the triggering Slack user id to the same model message as the message text. This keeps speaker attribution intact when several people use one thread without making profile lookup requests.+### Other Events API callbacks++Use `onEvent` for subscribed events such as `reaction_added`, `team_join`, or `channel_created`. It receives the raw, open-ended Slack event and owns control flow. `ctx.receive(options)` is the current Slack channel's pre-bound form of the schedule API's `receive(slack, options)`: call it zero, one, or many times to start turns. Each call accepts `message`, `target`, and `auth`, and returns the resulting session.++```ts title="agent/channels/slack.ts"+import { connectSlackCredentials } from "@vercel/connect/eve";+import { slackChannel } from "eve/channels/slack";++const onboardingChannels = ["C0123ABC", "C0456DEF"];++export default slackChannel({+ credentials: connectSlackCredentials("slack/my-agent"),+ async onEvent({ receive }, event) {+ if (event.type !== "team_join") return;++ await Promise.all(+ onboardingChannels.map((channelId) =>+ receive({+ message: `A user joined the Slack workspace. Onboard them from this event:\n${JSON.stringify(event)}`,+ target: { channelId },+ auth: null,+ }),+ ),+ );+ },+});+```++The webhook invocation already keeps an awaited `onEvent` handler alive. Use `ctx.waitUntil(promise)` for deliberately detached work, matching a handler-form schedule. `ctx.slack.request(operation, body)` provides workspace-scoped Slack Web API access, while `ctx.envelope` carries delivery metadata such as `team_id`, `event_id`, and `event_time`. Calls to `ctx.receive` automatically seed the callback's team id into Slack session state.++Authored specific handlers take precedence. If both `onAppMention` and `onEvent` are present, an `app_mention` runs only `onAppMention`; the same rule applies to `onDirectMessage`. When `onEvent` is present without the matching specific handler, it receives that event instead of the built-in mention or DM default. Bot-authored and subtype DMs rejected by `onDirectMessage` can still reach `onEvent`. When `onEvent` is omitted, the existing mention and DM defaults remain unchanged and other events are acknowledged and ignored.++`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.+You get the triggering mention by default, but not the earlier replies in the thread. Enable `threadContext` to fetch and inject them with every message attributed by stable Slack user id. Use `since: "last-agent-reply"` so repeated mentions inject only what is new:```ts@@ -78,7 +113,7 @@ export default slackChannel({### Slack API calls outside a handler-Inside webhook-side handlers (`onAppMention`, `onInteraction`, `events`),+Inside webhook-side handlers (`onAppMention`, `onEvent`, `onInteraction`, `events`),`ctx.slack.request(operation, body)` is the raw-API escape hatch. Outsidethose contexts there is no handle — a schedule resolving reactions on oldmessages, for example, has no inbound Slack request. For that, call the@@ -105,7 +140,7 @@ when you need the bearer token itself.### Delivery-The default handlers reply in-thread and show progress. Typing indicators post automatically: `Thinking…` on inbound, `Working…` on `turn.started`, a truncated reasoning snippet on `reasoning.appended`, and an action label on `actions.requested` — the tool name plus its most telling argument (`grep useEveAgent`, `read_file agent/agent.ts`), the subagent or remote-agent name for dispatched calls, and `+N more` when the model requests several actions at once. The model's own pre-tool narration, when present, takes precedence over the derived label. Reasoning snippets build progressively: extensions of at least four characters appear immediately, while smaller streamed deltas use the five-second refresh interval to avoid one Slack request per token. Override `events["reasoning.appended"]` if you prefer generic wording. Override `onAppMention` or the `events` handlers to customize.+The default handlers reply in-thread and show progress. Typing indicators post automatically: `Thinking…` on inbound, `Working…` on `turn.started`, a truncated reasoning snippet on `reasoning.appended`, and an action label on `actions.requested` — the tool name plus its most telling argument (`grep useEveAgent`, `read_file agent/agent.ts`), the subagent or remote-agent name for dispatched calls, and `+N more` when the model requests several actions at once. The model's own pre-tool narration, when present, takes precedence over the derived label. Reasoning snippets build progressively: extensions of at least four characters appear immediately, while smaller streamed deltas use the five-second refresh interval to avoid one Slack request per token. Override `events["reasoning.appended"]` if you prefer generic wording. Override an inbound handler or the `events` handlers to customize.Outbound text preserves bare `@` tokens as literal text. To mention a user, embed Slack's `<@USER_ID>` syntax directly or use `channel.thread.mentionUser(userId)`.diff --git a/packages/eve/src/public/channels/slack/api.ts b/packages/eve/src/public/channels/slack/api.tsindex a46dc3ed0..2f48a9aab 100644--- a/packages/eve/src/public/channels/slack/api.ts+++ b/packages/eve/src/public/channels/slack/api.ts@@ -307,6 +307,34 @@ export interface SlackHandle {): Promise<SlackUploadFilesResult>;}+/**+ * Workspace-scoped Slack API handle exposed to generic inbound event+ * handlers. Events such as `team_join` and `reaction_added` are not always+ * bound to one message thread, so this surface deliberately exposes only+ * workspace identity and the raw Web API escape hatch.+ */+export interface SlackWorkspaceHandle {+ /** Slack team id carried by the Events API envelope, when present. */+ readonly teamId: string | undefined;++ /**+ * POST to a Slack Web API method. Returns Slack's raw JSON response.+ * Callers must check `response.ok` themselves.+ */+ request(operation: string, body: unknown): Promise<SlackApiResponse>;+}++/** Builds the workspace-scoped API handle used by generic event callbacks. */+export function buildSlackWorkspaceHandle(input: {+ readonly botToken: SlackBotToken | undefined;+ readonly teamId: string | undefined;+}): SlackWorkspaceHandle {+ return {+ teamId: input.teamId,+ request: createSlackRequester(input.botToken),+ };+}+/*** The `{ thread, slack }` pair exposed through `ctx` to every mention* handler, interaction handler, and event handler. Returned bydiff --git a/packages/eve/src/public/channels/slack/inbound.test.ts b/packages/eve/src/public/channels/slack/inbound.test.tsindex 7e3c86888..025114b58 100644--- a/packages/eve/src/public/channels/slack/inbound.test.ts+++ b/packages/eve/src/public/channels/slack/inbound.test.ts@@ -4,9 +4,56 @@ import { parseSlackWebhookBody } from "#compiled/@chat-adapter/slack/webhook.js"import {parseAppMentionEvent,parseDirectMessageEvent,+ parseSlackEventEnvelope,slackMessageFromWebhookPayload,} from "#public/channels/slack/inbound.js";+describe("parseSlackEventEnvelope", () => {+ it("preserves an arbitrary Events API payload and its delivery envelope", () => {+ const envelope = parseSlackEventEnvelope(+ JSON.stringify({+ api_app_id: "A01",+ event: {+ item: { channel: "C01", ts: "1700000000.000100", type: "message" },+ reaction: "eyes",+ type: "reaction_added",+ user: "U01",+ },+ event_id: "Ev01",+ event_time: 1_700_000_000,+ team_id: "T01",+ type: "event_callback",+ }),+ );++ expect(envelope).toMatchObject({+ api_app_id: "A01",+ event: {+ item: { channel: "C01", ts: "1700000000.000100", type: "message" },+ reaction: "eyes",+ type: "reaction_added",+ user: "U01",+ },+ event_id: "Ev01",+ event_time: 1_700_000_000,+ team_id: "T01",+ });+ });++ it("returns null for non-event callbacks and missing event types", () => {+ expect(+ parseSlackEventEnvelope(JSON.stringify({ challenge: "abc", type: "url_verification" })),+ ).toBeNull();+ expect(+ parseSlackEventEnvelope(JSON.stringify({ event: { user: "U01" }, type: "event_callback" })),+ ).toBeNull();+ });++ it("throws for invalid JSON", () => {+ expect(() => parseSlackEventEnvelope("not-json")).toThrow();+ });+});+describe("parseAppMentionEvent", () => {it("returns a SlackMessage with mrkdwn re-rendered as GFM", () => {const message = parseAppMentionEvent({diff --git a/packages/eve/src/public/channels/slack/inbound.ts b/packages/eve/src/public/channels/slack/inbound.tsindex 683f3e9df..4012c553b 100644--- a/packages/eve/src/public/channels/slack/inbound.ts+++ b/packages/eve/src/public/channels/slack/inbound.ts@@ -20,6 +20,7 @@ import type {} from "#compiled/@chat-adapter/slack/webhook.js";import { slackMrkdwnToGfm } from "#public/channels/slack/mrkdwn.js";+import { isObject } from "#shared/guards.js";/*** Author metadata for an inbound Slack message. Channel-owned shape;@@ -75,6 +76,16 @@ export interface SlackMessage {readonly raw: Record<string, unknown>;}+/**+ * Open-ended Slack Events API payload handed to `slackChannel({ onEvent })`.+ * `type` is the Slack event discriminator; all event-specific fields pass+ * through unchanged from the signed webhook body.+ */+export interface SlackEvent {+ readonly type: string;+ readonly [key: string]: unknown;+}+/*** Slack `app_mention` event envelope (subset of fields the channel* actually reads).@@ -126,6 +137,30 @@ export interface SlackEventCallback {readonly [key: string]: unknown;}+/**+ * Validated Slack Events API callback envelope handed to `onEvent` through+ * {@link SlackInboundEventContext}. Unlike the permissive parser input type,+ * this shape always carries an event with a non-empty `type` discriminator.+ */+export interface SlackEventEnvelope extends SlackEventCallback {+ readonly event: SlackEvent;+}++/**+ * Parses a raw JSON webhook body into an open-ended Slack Events API envelope.+ * Returns `null` for URL verification, interactivity, and malformed callback+ * payloads. Invalid JSON is allowed to throw so the route can log it once.+ */+export function parseSlackEventEnvelope(body: string): SlackEventEnvelope | null {+ const envelope = JSON.parse(body) as unknown;+ if (!isObject(envelope) || envelope.type !== "event_callback") return null;++ const event = envelope.event;+ if (!isObject(event) || typeof event.type !== "string" || event.type.length === 0) return null;++ return envelope as SlackEventEnvelope;+}+/*** Parses a Slack `app_mention` event into a {@link SlackMessage}.*diff --git a/packages/eve/src/public/channels/slack/index.ts b/packages/eve/src/public/channels/slack/index.tsindex 84f733493..e342996f6 100644--- a/packages/eve/src/public/channels/slack/index.ts+++ b/packages/eve/src/public/channels/slack/index.ts@@ -19,22 +19,28 @@ export {type SlackChannelState,type SlackContext,type SlackEventContext,+ type SlackEventReceiveFn,+ type SlackEventReceiveOptions,type SlackHandle,+ type SlackInboundEventContext,type SlackInboundResult,type SlackInboundResultOrPromise,- type SlackInstrumentationMetadata,type SlackInitialMessage,+ type SlackInstrumentationMetadata,type SlackInteractionAction,type SlackMentionResult,type SlackMentionResultOrPromise,type SlackReceiveTarget,type SlackThread,type SlackWebhookVerifier,+ type SlackWorkspaceHandle,} from "#public/channels/slack/slackChannel.js";export type {SlackAttachment,SlackAuthor,+ SlackEvent,+ SlackEventEnvelope,SlackInboundContext,SlackMessage,} from "#public/channels/slack/inbound.js";diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.tsindex 68a30dd0c..86688219f 100644--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts@@ -225,6 +225,21 @@ function buildDirectMessageBody(overrides?: {return { body, channel, ts };}+function buildEventBody(+ event: Record<string, unknown>,+ overrides?: { eventId?: string; eventTime?: number; teamId?: string },+): string {+ mentionCounter += 1;+ return JSON.stringify({+ api_app_id: "A01",+ event,+ event_id: overrides?.eventId ?? `Ev${mentionCounter}`,+ event_time: overrides?.eventTime ?? 1_700_000_000,+ team_id: overrides?.teamId ?? "T01",+ type: "event_callback",+ });+}+async function firePost(channel: unknown,request: Request,@@ -1333,6 +1348,261 @@ describe("slackChannel() inbound mention pipeline", () => {});});+describe("slackChannel() generic Events API pipeline", () => {+ const ORIGINAL_SIGNING_SECRET = process.env.SLACK_SIGNING_SECRET;+ const ORIGINAL_BOT_TOKEN = process.env.SLACK_BOT_TOKEN;+ let fetchMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ process.env.SLACK_SIGNING_SECRET = SIGNING_SECRET;+ fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ ok: true }), {+ headers: { "content-type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);+ });++ afterAll(() => {+ if (ORIGINAL_SIGNING_SECRET === undefined) {+ delete process.env.SLACK_SIGNING_SECRET;+ } else {+ process.env.SLACK_SIGNING_SECRET = ORIGINAL_SIGNING_SECRET;+ }+ if (ORIGINAL_BOT_TOKEN === undefined) {+ delete process.env.SLACK_BOT_TOKEN;+ } else {+ process.env.SLACK_BOT_TOKEN = ORIGINAL_BOT_TOKEN;+ }+ });++ it("passes arbitrary Events API payloads with workspace API access", async () => {+ const onEvent = vi.fn(async (ctx, event) => {+ expect(event).toEqual({+ item: { channel: "C01", ts: "1700000000.000001", type: "message" },+ reaction: "eyes",+ type: "reaction_added",+ user: "U01",+ });+ expect(ctx.envelope).toMatchObject({+ api_app_id: "A01",+ event_id: "Ev_reaction",+ event_time: 1_700_000_123,+ team_id: "T_WORKSPACE",+ });+ expect(ctx.slack.teamId).toBe("T_WORKSPACE");+ await ctx.slack.request("reactions.get", {+ channel: "C01",+ timestamp: "1700000000.000001",+ });+ });+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ onEvent,+ });+ const body = buildEventBody(+ {+ item: { channel: "C01", ts: "1700000000.000001", type: "message" },+ reaction: "eyes",+ type: "reaction_added",+ user: "U01",+ },+ { eventId: "Ev_reaction", eventTime: 1_700_000_123, teamId: "T_WORKSPACE" },+ );++ const { response, send } = await firePost(channel, buildSignedRequest({ body }));++ expect(response.status).toBe(200);+ expect(onEvent).toHaveBeenCalledTimes(1);+ expect(send).not.toHaveBeenCalled();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(String(fetchMock.mock.calls[0]![0])).toBe("https://slack.com/api/reactions.get");+ });++ it("can start multiple turns through the pre-bound receive function", async () => {+ const auth = {+ attributes: { source: "reaction" },+ authenticator: "test",+ principalId: "U01",+ principalType: "user" as const,+ };+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ async onEvent({ receive }, event) {+ expect(event.type).toBe("reaction_added");+ await Promise.all([+ receive({+ auth,+ message: "Investigate the first message.",+ target: { channelId: "C01", threadTs: "1700000000.000001" },+ }),+ receive({+ auth: null,+ message: "Investigate the second message.",+ target: { channelId: "C02", threadTs: "1700000000.000002" },+ }),+ ]);+ },+ });+ const body = buildEventBody(+ { reaction: "eyes", type: "reaction_added", user: "U01" },+ { teamId: "T_WORKSPACE" },+ );++ const { send } = await firePost(channel, buildSignedRequest({ body }));++ expect(send).toHaveBeenCalledTimes(2);+ expect(send.mock.calls.map(([message]) => message)).toEqual([+ "Investigate the first message.",+ "Investigate the second message.",+ ]);+ expect(send.mock.calls.map(([, options]) => options.continuationToken)).toEqual([+ "C01:1700000000.000001",+ "C02:1700000000.000002",+ ]);+ expect(send.mock.calls.map(([, options]) => options.state.teamId)).toEqual([+ "T_WORKSPACE",+ "T_WORKSPACE",+ ]);+ expect(send.mock.calls[0]![1].auth).toEqual(auth);+ expect(send.mock.calls[1]![1].auth).toBeNull();+ });++ it("keeps detached receive calls alive through the handler waitUntil", async () => {+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ onEvent(ctx) {+ ctx.waitUntil(+ ctx.receive({+ auth: null,+ message: "Run detached work.",+ target: { channelId: "C01" },+ }),+ );+ },+ });+ const body = buildEventBody({ type: "team_join", user: { id: "U01" } });++ const { send, waitUntil } = await firePost(channel, buildSignedRequest({ body }));++ expect(send).toHaveBeenCalledTimes(1);+ expect(waitUntil).toHaveBeenCalledTimes(1);+ });++ it("uses onEvent instead of the mention default when no onAppMention is authored", async () => {+ const onEvent = vi.fn();+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ onEvent,+ });+ const { body } = buildMentionBody();++ const { send } = await firePost(channel, buildSignedRequest({ body }));++ expect(onEvent).toHaveBeenCalledTimes(1);+ expect(onEvent.mock.calls[0]![1]).toMatchObject({ type: "app_mention" });+ expect(send).not.toHaveBeenCalled();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("uses onEvent instead of the DM default when no onDirectMessage is authored", async () => {+ const onEvent = vi.fn();+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ onEvent,+ });+ const { body } = buildDirectMessageBody();++ const { send } = await firePost(channel, buildSignedRequest({ body }));++ expect(onEvent).toHaveBeenCalledTimes(1);+ expect(onEvent.mock.calls[0]![1]).toMatchObject({ channel_type: "im", type: "message" });+ expect(send).not.toHaveBeenCalled();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("gives an authored onAppMention precedence over onEvent", async () => {+ const onAppMention = vi.fn().mockReturnValue(null);+ const onEvent = vi.fn();+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ onAppMention,+ onEvent,+ });+ const { body } = buildMentionBody();++ await firePost(channel, buildSignedRequest({ body }));++ expect(onAppMention).toHaveBeenCalledTimes(1);+ expect(onEvent).not.toHaveBeenCalled();+ });++ it("gives an authored onDirectMessage precedence over onEvent", async () => {+ const onDirectMessage = vi.fn().mockReturnValue(null);+ const onEvent = vi.fn();+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ onDirectMessage,+ onEvent,+ });+ const { body } = buildDirectMessageBody();++ await firePost(channel, buildSignedRequest({ body }));++ expect(onDirectMessage).toHaveBeenCalledTimes(1);+ expect(onEvent).not.toHaveBeenCalled();+ });++ it("routes DMs rejected by the specialized filter to onEvent", async () => {+ const onDirectMessage = vi.fn();+ const onEvent = vi.fn();+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ onDirectMessage,+ onEvent,+ });+ const { body } = buildDirectMessageBody({ botId: "B01" });++ await firePost(channel, buildSignedRequest({ body }));++ expect(onDirectMessage).not.toHaveBeenCalled();+ expect(onEvent).toHaveBeenCalledTimes(1);+ expect(onEvent.mock.calls[0]![1]).toMatchObject({ bot_id: "B01", type: "message" });+ });++ it("deduplicates generic events by event_id", async () => {+ const onEvent = vi.fn();+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ onEvent,+ });+ const body = buildEventBody(+ { type: "reaction_added", user: "U01" },+ { eventId: "Ev_duplicate" },+ );++ await firePost(channel, buildSignedRequest({ body }));+ await firePost(channel, buildSignedRequest({ body }));++ expect(onEvent).toHaveBeenCalledTimes(1);+ });++ it("acks and logs handler failures without starting a turn", async () => {+ const onEvent = vi.fn().mockRejectedValue(new Error("event failed"));+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ onEvent,+ });+ const body = buildEventBody({ type: "reaction_added", user: "U01" });++ const { response, send } = await firePost(channel, buildSignedRequest({ body }));++ expect(response.status).toBe(200);+ expect(onEvent).toHaveBeenCalledTimes(1);+ expect(send).not.toHaveBeenCalled();+ });+});+describe("slackChannel() inbound direct message pipeline", () => {const ORIGINAL_SIGNING_SECRET = process.env.SLACK_SIGNING_SECRET;const ORIGINAL_BOT_TOKEN = process.env.SLACK_BOT_TOKEN;diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.tsindex 4b2374b3d..7eadd14ff 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -1,6 +1,7 @@import { parseSlackWebhookBody } from "#compiled/@chat-adapter/slack/webhook.js";-import type { SessionHandle } from "#channel/session.js";+import type { CrossChannelReceiveOptions } from "#channel/cross-channel-receive.js";+import type { Session, SessionHandle } from "#channel/session.js";import type { SessionAuthContext } from "#channel/types.js";import type { CardElement } from "#compiled/chat/index.js";import type { SessionContext } from "#public/definitions/callback-context.js";@@ -10,10 +11,12 @@ import { createLogger, logError } from "#internal/logging.js";import type { HandleMessageStreamEvent } from "#protocol/message.js";import {buildSlackBinding,+ buildSlackWorkspaceHandle,slackContinuationToken,type SlackBotToken,type SlackHandle,type SlackThread,+ type SlackWorkspaceHandle,} from "#public/channels/slack/api.js";import {buildSlackTurnMessage,@@ -27,8 +30,11 @@ import {defaultOnDirectMessage,} from "#public/channels/slack/defaults.js";import {+ type SlackEvent,+ type SlackEventEnvelope,type SlackInboundContext,type SlackMessage,+ parseSlackEventEnvelope,slackMessageFromWebhookPayload,} from "#public/channels/slack/inbound.js";import {@@ -92,6 +98,7 @@ export type {SlackBotToken,SlackHandle,SlackThread,+ SlackWorkspaceHandle,} from "#public/channels/slack/api.js";export type { SlackWebhookVerifier } from "#public/channels/slack/verify.js";@@ -252,6 +259,36 @@ export interface SlackInitialMessage {readonly fallbackText?: string;}+/**+ * One imperative turn start requested by a generic Slack event handler.+ * The schedule API's `receive(slack, options)` payload with the Slack+ * channel already bound by the inbound webhook.+ */+export type SlackEventReceiveOptions = CrossChannelReceiveOptions<SlackReceiveTarget>;++/**+ * Starts a session on the current Slack channel from `onEvent`. Call it zero,+ * one, or many times; each invocation returns the resulting session.+ */+export type SlackEventReceiveFn = (options: SlackEventReceiveOptions) => Promise<Session>;++/**+ * Imperative surface handed to `slackChannel({ onEvent })`. Generic Events API+ * payloads are not necessarily tied to one thread, so the context exposes a+ * workspace API handle plus a Slack-bound `receive` function rather than the+ * thread-scoped {@link SlackContext} used by message handlers.+ */+export interface SlackInboundEventContext {+ /** The complete signed Events API callback envelope. */+ readonly envelope: SlackEventEnvelope;+ /** Starts a turn on this Slack channel using the proactive receive contract. */+ readonly receive: SlackEventReceiveFn;+ /** Workspace-scoped Slack identity and raw Web API escape hatch. */+ readonly slack: SlackWorkspaceHandle;+ /** Keeps detached handler work alive after the Slack webhook is acknowledged. */+ readonly waitUntil: (task: Promise<unknown>) => void;+}+export interface SlackInteractionAction {readonly actionId: string;readonly value?: string;@@ -420,6 +457,24 @@ export interface SlackChannelConfig {*/onDirectMessage?(ctx: SlackContext, message: SlackMessage): SlackInboundResultOrPromise;+ /**+ * Fallback handler for signed Slack Events API callbacks. An authored+ * `onAppMention` or `onDirectMessage` takes precedence for events accepted+ * by that specialized handler; otherwise the raw event arrives here. When+ * neither a specialized handler nor `onEvent` is authored, mentions and DMs+ * retain their built-in defaults and other event types are ignored.+ *+ * The handler owns control flow. Call `ctx.receive(...)` zero, one, or many+ * times to start turns on Slack, and use `ctx.waitUntil(...)` for detached+ * work. The return value is ignored. Runs after the webhook has been+ * acknowledged through the host's `waitUntil` mechanism. Errors are caught+ * and logged and never fall through to another handler.+ *+ * URL verification, slash commands, and interactive payloads are not Events+ * API callbacks and do not reach this handler.+ */+ onEvent?(ctx: SlackInboundEventContext, event: SlackEvent): void | Promise<void>;+/*** Handler for Slack `block_actions` interactive callbacks (button* clicks, select changes, etc.) **not** consumed by the framework's@@ -480,13 +535,13 @@ export interface SlackChannel extends Channel<* connection-auth event handlers. Defaults apply per field: pass* `onAppMention` to fully replace the default mention pipeline (auth* derivation plus `"Thinking..."` typing), or an `events[type]` handler to- * replace only that one event. Unsupplied fields keep their defaults.+ * replace only that one event. When `onEvent` is authored it becomes the+ * fallback ahead of unsupplied mention and DM defaults; otherwise unsupplied+ * fields keep their defaults.*/export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {const uploadPolicy = mergeUploadPolicy(config.uploadPolicy);const slackFetchFile = createSlackFetchFile({ botToken: config.credentials?.botToken });- const onAppMention = config.onAppMention ?? defaultOnAppMention;- const onDirectMessage = config.onDirectMessage ?? defaultOnDirectMessage;const authorizationRequiredOverride = config.events?.["authorization.required"];const turnStartedHandler = config.events?.["turn.started"] ?? defaultEvents["turn.started"]!;const mergedEvents: SlackChannelInternalEvents = {@@ -560,68 +615,81 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {body,send,waitUntil,- onAppMention,- onDirectMessage,+ config,uploadPolicy,- threadContext: config.threadContext,handledEvents,headers: req.headers,- credentials: config.credentials,});},),],- async receive(input, { send }) {- const receiveTarget = input.target as Partial<SlackReceiveTarget>;- const channelId = receiveTarget.channelId;- if (!channelId || typeof channelId !== "string") {- throw new Error("slackChannel().receive requires target.channelId.");- }- const requestedThreadTs =- typeof receiveTarget.threadTs === "string" ? receiveTarget.threadTs : "";- const initialMessage = receiveTarget.initialMessage;- if (initialMessage && requestedThreadTs.length > 0) {- throw new Error(- "slackChannel().receive: `threadTs` and `initialMessage` are mutually exclusive.",- );- }+ receive(input, { send }) {+ return receiveOnSlack(input, { credentials: config.credentials, send });+ },- let threadTs = requestedThreadTs;- if (initialMessage) {- const { thread } = buildSlackBinding({- botToken: config.credentials?.botToken,- channelId,- threadTs: "",- teamId: undefined,- });- const postInput: { card: CardElement; fallbackText?: string } = {- card: initialMessage.card,- };- if (initialMessage.fallbackText !== undefined) {- postInput.fallbackText = initialMessage.fallbackText;- }- const posted = await thread.post(postInput);- threadTs = posted.id;- }+ events: mergedEvents,+ });+}- // Threadless proactive runs need distinct identities until their first- // Slack post supplies the real thread timestamp and re-keys the session.- const continuationThreadTs = threadTs || crypto.randomUUID();+/**+ * Shared proactive Slack receive path used by both the channel's public+ * `receive` hook and the pre-bound function exposed to `onEvent`.+ */+async function receiveOnSlack(+ input: SlackEventReceiveOptions,+ deps: {+ readonly credentials: SlackChannelCredentials | undefined;+ readonly send: SendFn<SlackChannelState>;+ /** Slack team id seeded into session state, when the trigger carried one. */+ readonly teamId?: string;+ },+): Promise<Session> {+ const receiveTarget = input.target as Partial<SlackReceiveTarget>;+ const channelId = receiveTarget.channelId;+ if (!channelId || typeof channelId !== "string") {+ throw new Error("slackChannel().receive requires target.channelId.");+ }+ const requestedThreadTs =+ typeof receiveTarget.threadTs === "string" ? receiveTarget.threadTs : "";+ const initialMessage = receiveTarget.initialMessage;+ if (initialMessage && requestedThreadTs.length > 0) {+ throw new Error(+ "slackChannel().receive: `threadTs` and `initialMessage` are mutually exclusive.",+ );+ }- return send(input.message, {- auth: input.auth,- continuationToken: slackContinuationToken(channelId, continuationThreadTs),- state: {- channelId,- threadTs: threadTs || null,- teamId: null,- triggeringUserId: null,- },- });- },+ let threadTs = requestedThreadTs;+ if (initialMessage) {+ const { thread } = buildSlackBinding({+ botToken: deps.credentials?.botToken,+ channelId,+ threadTs: "",+ teamId: deps.teamId,+ });+ const postInput: { card: CardElement; fallbackText?: string } = {+ card: initialMessage.card,+ };+ if (initialMessage.fallbackText !== undefined) {+ postInput.fallbackText = initialMessage.fallbackText;+ }+ const posted = await thread.post(postInput);+ threadTs = posted.id;+ }- events: mergedEvents,+ // Threadless proactive runs need distinct identities until their first+ // Slack post supplies the real thread timestamp and re-keys the session.+ const continuationThreadTs = threadTs || crypto.randomUUID();++ return deps.send(input.message, {+ auth: input.auth,+ continuationToken: slackContinuationToken(channelId, continuationThreadTs),+ state: {+ channelId,+ threadTs: threadTs || null,+ teamId: deps.teamId ?? null,+ triggeringUserId: null,+ },});}@@ -653,29 +721,26 @@ function shouldDropSlackHttpTimeoutRetry(headers: Headers): boolean {}/**- * Handles an inbound non-interactivity Slack POST: parses the JSON- * envelope, answers the URL-verification challenge, routes- * `app_mention` events through `onAppMention` and `message`- * events with `channel_type: "im"` through `onDirectMessage`, and- * dispatches matching events via {@link dispatchInboundMessage} under- * `waitUntil`. Returns the route's `200 OK` Response in every case- * (Slack only cares that the webhook ACKs immediately).+ * Handles an inbound non-interactivity Slack POST: parses the JSON envelope,+ * answers URL verification, selects one authored specific handler, generic+ * fallback, or built-in message default, and schedules it under `waitUntil`.+ * Returns `200 OK` in every case because Slack only requires an immediate ACK.*/async function handleEventPost(input: {readonly body: string;readonly headers: Headers;readonly send: SendFn<SlackChannelState>;readonly waitUntil: (task: Promise<unknown>) => void;- readonly onAppMention: NonNullable<SlackChannelConfig["onAppMention"]>;- readonly onDirectMessage: NonNullable<SlackChannelConfig["onDirectMessage"]>;+ readonly config: SlackChannelConfig;readonly uploadPolicy: UploadPolicy;- readonly threadContext: LoadThreadContextMessagesOptions | undefined;- readonly credentials: SlackChannelCredentials | undefined;readonly handledEvents: Set<string>;}): Promise<Response> {+ const { config } = input;let payload;+ let envelope: SlackEventEnvelope | null;try {payload = parseSlackWebhookBody(input.body, { headers: input.headers });+ envelope = parseSlackEventEnvelope(input.body);} catch (error) {log.warn("inbound webhook body is not valid JSON", { error });return new Response("ok");@@ -688,59 +753,117 @@ async function handleEventPost(input: {});}- if (payload.kind === "unsupported") return new Response("ok");+ if (envelope === null) return new Response("ok");++ // Handler precedence, in fall-through order:+ // 1) an authored mention/DM handler for its own event kind,+ // 2) an authored generic `onEvent` fallback,+ // 3) the built-in mention/DM defaults.+ let dispatch: (() => Promise<void>) | null = null;+ let builtinDefault: (() => Promise<void>) | null = null;+ if (payload.kind === "app_mention" || payload.kind === "direct_message") {+ const kind = payload.kind;+ const message = slackMessageFromWebhookPayload(payload);+ if (message !== null) {+ const dispatchMessageWith =+ (handler: NonNullable<SlackChannelConfig["onAppMention"]>) => () =>+ dispatchInboundMessage({+ credentials: config.credentials,+ handler,+ kind,+ message,+ send: input.send,+ threadContext: config.threadContext,+ uploadPolicy: input.uploadPolicy,+ });+ const authored = kind === "app_mention" ? config.onAppMention : config.onDirectMessage;+ if (authored !== undefined) {+ dispatch = dispatchMessageWith(authored);+ } else {+ builtinDefault = dispatchMessageWith(+ kind === "app_mention" ? defaultOnAppMention : defaultOnDirectMessage,+ );+ }+ }+ }- if (payload.kind !== "app_mention" && payload.kind !== "direct_message") {- return new Response("ok");+ // Specialized message handlers intentionally reject bot-authored/subtype+ // DMs and malformed message events. A generic handler still receives the+ // raw Events API payload because those events are within its broader scope.+ const onEvent = config.onEvent;+ if (dispatch === null && onEvent !== undefined) {+ dispatch = () =>+ dispatchSlackEvent({+ credentials: config.credentials,+ envelope,+ handler: onEvent,+ send: input.send,+ });}- if (payload.eventId) {- if (input.handledEvents.has(payload.eventId)) {+ dispatch ??= builtinDefault;+ if (dispatch === null) return new Response("ok");++ const eventId = envelope.event_id;+ if (eventId) {+ if (input.handledEvents.has(eventId)) {log.warn("received a duplicate event", {- event_id: payload.eventId,- event_time: payload.eventTime,+ event_id: eventId,+ event_time: envelope.event_time,retry_num: payload.retry?.num ?? "(null)",retry_reason: payload.retry?.reason ?? "(null)",});return new Response("ok");}- markEventHandled(payload.eventId, input.handledEvents);+ markEventHandled(eventId, input.handledEvents);}- const message = slackMessageFromWebhookPayload(payload);- if (!message) return new Response("ok");+ input.waitUntil(dispatch());+ return new Response("ok");+}- if (payload.kind === "app_mention") {- input.waitUntil(- dispatchInboundMessage({- kind: "app_mention",- message,- handler: input.onAppMention,- send: input.send,- uploadPolicy: input.uploadPolicy,- threadContext: input.threadContext,+/** Runs a generic Events API handler with an imperative Slack receive surface. */+async function dispatchSlackEvent(input: {+ readonly credentials: SlackChannelCredentials | undefined;+ readonly envelope: SlackEventEnvelope;+ readonly handler: NonNullable<SlackChannelConfig["onEvent"]>;+ readonly send: SendFn<SlackChannelState>;+}): Promise<void> {+ const eventTeamId = input.envelope.event.team_id;+ const teamId =+ typeof eventTeamId === "string"+ ? eventTeamId+ : typeof input.envelope.team_id === "string"+ ? input.envelope.team_id+ : undefined;+ const waitUntilTasks: Promise<unknown>[] = [];+ const ctx: SlackInboundEventContext = {+ envelope: input.envelope,+ receive: (options) =>+ receiveOnSlack(options, {credentials: input.credentials,- }),- );- return new Response("ok");- }-- if (payload.kind === "direct_message") {- input.waitUntil(- dispatchInboundMessage({- kind: "direct_message",- message,- handler: input.onDirectMessage,send: input.send,- uploadPolicy: input.uploadPolicy,- threadContext: input.threadContext,- credentials: input.credentials,+ teamId,}),- );- return new Response("ok");+ slack: buildSlackWorkspaceHandle({+ botToken: input.credentials?.botToken,+ teamId,+ }),+ waitUntil(task) {+ waitUntilTasks.push(task);+ },+ };++ try {+ await input.handler(ctx, input.envelope.event);+ } catch (error) {+ logError(log, "event handler failed", error, {+ eventId: input.envelope.event_id,+ eventType: input.envelope.event.type,+ });}- return new Response("ok");+ await Promise.allSettled(waitUntilTasks);}/**