Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): Add `onMessage` hook w/ `isSubscribed` utility (#1046)

Ben Pankow3ffaf1288b7c
diff --git a/.changeset/calm-threads-continue.md b/.changeset/calm-threads-continue.md
new file mode 100644
index 000000000..afcadd267
--- /dev/null
+++ b/.changeset/calm-threads-continue.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Added a Slack `onMessage` hook with `isBotMentioned()` and `isSubscribed()` helpers for custom message routing.
diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdx
index f55f43acd..6578a0795 100644
--- a/docs/channels/slack.mdx
+++ b/docs/channels/slack.mdx
@@ -36,7 +36,11 @@ export default slackChannel({
});
```
-`connectSlackCredentials` returns `{ botToken, webhookVerifier }`, keeping token rotation, multi-workspace tenancy, and request verification inside Connect rather than your code. Deploy once the trigger destination and channel file are ready:
+`connectSlackCredentials` returns `{ botToken, webhookVerifier }`, keeping token rotation, multi-workspace tenancy, and request verification inside Connect rather than your code.
+
+### Deploy
+
+Deploy once the trigger destination and channel file are ready:
```bash
VERCEL_USE_EXPERIMENTAL_FRAMEWORKS=1 vercel deploy --prod
@@ -46,16 +50,43 @@ VERCEL_USE_EXPERIMENTAL_FRAMEWORKS=1 vercel deploy --prod
## How the channel handles inbound events
-### Dispatch
+### Message hooks
+
+Message hooks return `{ auth }` to dispatch, `null` to drop, or `{ auth, context }` to inject background into history.
+
+- `onMessage(ctx, message)` handles Slack `message` events. `ctx.isBotMentioned()` and `ctx.isSubscribed()` support mention and active-thread policies; check `message.author?.isBot` when bot messages should be ignored.
+- `onAppMention(ctx, message)` handles only `app_mention` and takes precedence over `onMessage`. Its default derives workspace-scoped auth and posts `Thinking…`.
+- `onDirectMessage(ctx, message)` handles only DMs and takes precedence over `onMessage`. Bot-authored messages and edits are filtered first; Slack requires `message.im` and `im:history`.
+
+| Incoming event | Handler order |
+| ---------------------- | ------------------------------------------------------------------- |
+| App mention | `onAppMention` → `onMessage` → `onEvent` → built-in mention default |
+| Direct message | `onDirectMessage` → `onMessage` → `onEvent` → built-in DM default |
+| Other Slack message | `onMessage` → `onEvent` → ignore |
+| Other Events API event | `onEvent` → ignore |
+
+Only the first available handler runs. A message hook returning `null` drops the message; it does not continue down the table.
+
+`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 its text, preserving speaker attribution without profile lookups.
-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.
+#### Continue conversations without repeated mentions
-- `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.
+Use `onMessage` to handle explicit mentions and continue replies in threads with an active eve session:
-`onInteraction(action, ctx)` separately handles `block_actions` callbacks not consumed by HITL.
+```ts title="agent/channels/slack.ts"
+export default slackChannel({
+ credentials: connectSlackCredentials("slack/my-agent"),
+ async onMessage(ctx, message) {
+ if (message.author?.isBot) return null;
+ const isDirectMessage = message.raw.channel_type === "im";
+ return isDirectMessage || ctx.isBotMentioned() || (await ctx.isSubscribed())
+ ? { auth: null }
+ : null;
+ },
+});
+```
-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.
+`isBotMentioned()` identifies an explicit mention. `isSubscribed()` checks whether the message belongs to a thread with an active eve session. For Vercel Connect, open **Advanced** when creating the connector and add `message.channels` under **Trigger Event Types** and `channels:history` under **Bot Scopes**. Private channels additionally need `message.groups` and `groups:history`.
### Other Events API callbacks
@@ -87,7 +118,7 @@ export default slackChannel({
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` 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.
diff --git a/packages/eve/src/channel/resolve-active-session.test.ts b/packages/eve/src/channel/resolve-active-session.test.ts
new file mode 100644
index 000000000..99f1426c5
--- /dev/null
+++ b/packages/eve/src/channel/resolve-active-session.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { createResolveActiveSessionFn } from "#channel/resolve-active-session.js";
+import type { Runtime } from "#channel/types.js";
+
+function runtime(): Runtime {
+ return {
+ cancelTurn: vi.fn(),
+ deliver: vi.fn(),
+ getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),
+ resolveSession: vi.fn(),
+ run: vi.fn(),
+ };
+}
+
+describe("createResolveActiveSessionFn", () => {
+ it("resolves a channel-local continuation using the authored channel name", async () => {
+ const mockRuntime = runtime();
+ vi.mocked(mockRuntime.resolveSession).mockResolvedValue({ sessionId: "session-1" });
+
+ await expect(
+ createResolveActiveSessionFn(mockRuntime, "support")({ continuationToken: "C1:T1" }),
+ ).resolves.toEqual({ sessionId: "session-1" });
+ expect(mockRuntime.resolveSession).toHaveBeenCalledWith("support:C1:T1");
+ });
+
+ it("returns undefined for an inactive continuation", async () => {
+ const mockRuntime = runtime();
+ vi.mocked(mockRuntime.resolveSession).mockResolvedValue(undefined);
+
+ await expect(
+ createResolveActiveSessionFn(mockRuntime, "support")({ continuationToken: "C1:T1" }),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/channel/resolve-active-session.ts b/packages/eve/src/channel/resolve-active-session.ts
new file mode 100644
index 000000000..c982157e6
--- /dev/null
+++ b/packages/eve/src/channel/resolve-active-session.ts
@@ -0,0 +1,10 @@
+import type { ResolveActiveSessionFn } from "#channel/routes.js";
+import type { Runtime } from "#channel/types.js";
+
+/** Builds a channel-scoped lookup for the active owner of a continuation token. */
+export function createResolveActiveSessionFn(
+ runtime: Runtime,
+ channelName: string,
+): ResolveActiveSessionFn {
+ return ({ continuationToken }) => runtime.resolveSession(`${channelName}:${continuationToken}`);
+}
diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.ts
index 82ac43772..2273430ed 100644
--- a/packages/eve/src/channel/routes.ts
+++ b/packages/eve/src/channel/routes.ts
@@ -20,6 +20,11 @@ type WebSocketHeaders = Headers | readonly (readonly [string, string])[] | Recor
*/
export interface RouteHandlerArgs<TState = undefined> {
send: SendFn<TState>;
+ /**
+ * Resolves the session currently owning a channel-local continuation token.
+ * This point-in-time lookup does not reserve the continuation.
+ */
+ resolveActiveSession: ResolveActiveSessionFn;
cancel: CancelFn;
getSession: GetSessionFn;
/**
@@ -63,6 +68,11 @@ export type SendFn<TState = undefined> = (
options: SendOptions<TState>,
) => Promise<Session>;
+/** Resolves the active owner of a channel-local continuation token. */
+export type ResolveActiveSessionFn = (options: {
+ readonly continuationToken: string;
+}) => Promise<{ readonly sessionId: string } | undefined>;
+
type BaseSendOptions = {
auth: SessionAuthContext | null;
callback?: SessionCallback;
diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.ts
index 1446de8ab..18f90cf74 100644
--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts
+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts
@@ -248,6 +248,7 @@ function createCancelRouteCaller(): (
send: () => {
throw new Error("cancel route must not send");
},
+ resolveActiveSession: async () => undefined,
cancel: () => {
throw new Error("cancel route must not use the channel cancel helper");
},
diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
index dc03c70ea..52915f8f6 100644
--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
@@ -8,6 +8,7 @@ import type { DeliverInput, RunInput, Runtime } from "#channel/types.js";
import type { RouteHandlerArgs, WebSocketRouteHooks } from "#channel/routes.js";
import { createCancelFn } from "#channel/cancel.js";
import { createSendFn } from "#channel/send.js";
+import { createResolveActiveSessionFn } from "#channel/resolve-active-session.js";
import { createGetSessionFn } from "#channel/session.js";
import { createLogger, logError } from "#internal/logging.js";
import { readTrustedDevelopmentClientAddress } from "#internal/nitro/dev-client-address.js";
@@ -188,6 +189,7 @@ function buildRouteArgs(
const adapter = channel?.adapter ?? { kind: "channel" };
const agent = createRouteAgent(bundle.runtime, requestId);
const send = createSendFn(bundle.runtime, adapter, channelName, { requestId });
+ const resolveActiveSession = createResolveActiveSessionFn(bundle.runtime, channelName);
const cancel = createCancelFn(bundle.runtime, channelName);
const getSession = createGetSessionFn(bundle.runtime);
const receive = createCrossChannelReceiveFn(
@@ -199,6 +201,7 @@ function buildRouteArgs(
attachAgentInfoRouteResponse(
{
send,
+ resolveActiveSession,
cancel,
getSession,
receive,
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
index 5be912ce1..ab0afefdb 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
@@ -117,6 +117,7 @@ async function firePost(
}),
{
getSession: vi.fn() as any,
+ resolveActiveSession: async () => undefined,
cancel: vi.fn(),
params: {},
receive: vi.fn() as any,
@@ -172,6 +173,7 @@ describe("chatSdkChannel", () => {
new Request("https://example.com/eve/v1/test?crc_token=abc123", { method: "GET" }),
{
getSession: vi.fn() as any,
+ resolveActiveSession: async () => undefined,
cancel: vi.fn(),
params: {},
receive: vi.fn() as any,
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index 4d7d5b38f..1b3198d89 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -74,6 +74,7 @@ function createEveCreateHandler(input: EveChannelInput) {
async fetch(req: Request) {
const args: RouteHandlerArgs = {
send: mockSend,
+ resolveActiveSession: async () => undefined,
cancel: vi.fn(),
getSession: vi.fn(),
receive: vi.fn() as any,
@@ -116,6 +117,7 @@ function createEveContinueHandler(input: EveChannelInput) {
async fetch(req: Request) {
const args: RouteHandlerArgs = {
send: mockSend,
+ resolveActiveSession: async () => undefined,
cancel: vi.fn(),
getSession: mockGetSession,
receive: vi.fn() as any,
@@ -148,6 +150,7 @@ function createEveCancelHandler(input: EveChannelInput) {
const args = attachRouteAgent(
{
send: vi.fn(),
+ resolveActiveSession: async () => undefined,
cancel: vi.fn(),
getSession: vi.fn(),
receive: vi.fn() as any,
@@ -195,6 +198,7 @@ function createEveStreamHandler(input: EveChannelInput) {
async fetch(url: string) {
const args: RouteHandlerArgs = {
send: vi.fn(),
+ resolveActiveSession: async () => undefined,
cancel: vi.fn(),
getSession: mockGetSession,
receive: vi.fn() as any,
diff --git a/packages/eve/src/public/channels/github/githubChannel.test.ts b/packages/eve/src/public/channels/github/githubChannel.test.ts
index 17a23e610..f7cc36257 100644
--- a/packages/eve/src/public/channels/github/githubChannel.test.ts
+++ b/packages/eve/src/public/channels/github/githubChannel.test.ts
@@ -172,6 +172,7 @@ async function firePost(
const response = await post.handler(request, {
cancel: vi.fn(),
+ resolveActiveSession: async () => undefined,
getSession: vi.fn() as any,
params: {},
receive: vi.fn() as any,
diff --git a/packages/eve/src/public/channels/linear/linearChannel.test.ts b/packages/eve/src/public/channels/linear/linearChannel.test.ts
index ff519972a..34b7865bf 100644
--- a/packages/eve/src/public/channels/linear/linearChannel.test.ts
+++ b/packages/eve/src/public/channels/linear/linearChannel.test.ts
@@ -127,6 +127,7 @@ async function firePost(
const response = await post.handler(request, {
cancel: vi.fn(),
+ resolveActiveSession: async () => undefined,
getSession: vi.fn() as any,
params: {},
receive: vi.fn() as any,
diff --git a/packages/eve/src/public/channels/slack/inbound.test.ts b/packages/eve/src/public/channels/slack/inbound.test.ts
index 025114b58..34d6cbac1 100644
--- a/packages/eve/src/public/channels/slack/inbound.test.ts
+++ b/packages/eve/src/public/channels/slack/inbound.test.ts
@@ -4,6 +4,7 @@ import { parseSlackWebhookBody } from "#compiled/@chat-adapter/slack/webhook.js"
import {
parseAppMentionEvent,
parseDirectMessageEvent,
+ parseMessageEvent,
parseSlackEventEnvelope,
slackMessageFromWebhookPayload,
} from "#public/channels/slack/inbound.js";
@@ -160,6 +161,35 @@ describe("parseAppMentionEvent", () => {
});
});
+describe("parseMessageEvent", () => {
+ it("preserves bot and subtype message events for onMessage", () => {
+ const bot = parseMessageEvent({
+ type: "event_callback",
+ event: {
+ type: "message",
+ bot_id: "B01",
+ user: "U_BOT",
+ text: "automated",
+ channel: "C01",
+ ts: "2.0",
+ },
+ });
+ const subtype = parseMessageEvent({
+ type: "event_callback",
+ event: {
+ type: "message",
+ subtype: "message_changed",
+ text: "edited",
+ channel: "C01",
+ ts: "3.0",
+ },
+ });
+
+ expect(bot?.author?.isBot).toBe(true);
+ expect(subtype?.raw.subtype).toBe("message_changed");
+ });
+});
+
describe("parseDirectMessageEvent", () => {
it("returns a SlackMessage for a plain IM message event", () => {
const message = parseDirectMessageEvent({
diff --git a/packages/eve/src/public/channels/slack/inbound.ts b/packages/eve/src/public/channels/slack/inbound.ts
index 4012c553b..dd0642621 100644
--- a/packages/eve/src/public/channels/slack/inbound.ts
+++ b/packages/eve/src/public/channels/slack/inbound.ts
@@ -131,6 +131,10 @@ interface SlackMessageEvent {
export interface SlackEventCallback {
readonly type: "event_callback";
readonly team_id?: string;
+ readonly authorizations?: readonly {
+ readonly is_bot?: boolean;
+ readonly user_id?: string;
+ }[];
readonly event?: { readonly type?: string } & Record<string, unknown>;
readonly event_id?: string;
readonly event_time?: number;
@@ -187,6 +191,22 @@ export function parseAppMentionEvent(envelope: SlackEventCallback): SlackMessage
* - the message was posted by a bot (`bot_id` set) — this prevents the
* bot's own DM replies from re-triggering the handler.
*/
+/** Returns the bot user id attached to a Slack event authorization. */
+export function slackEventBotUserId(envelope: SlackEventCallback): string | undefined {
+ const authorization = envelope.authorizations?.find(
+ (entry) => entry.is_bot === true && typeof entry.user_id === "string",
+ );
+ return authorization?.user_id;
+}
+
+/** Parses a Slack message event without applying bot or subtype policy. */
+export function parseMessageEvent(envelope: SlackEventCallback): SlackMessage | null {
+ if (envelope.type !== "event_callback") return null;
+ const event = envelope.event;
+ if (!event || event.type !== "message") return null;
+ return buildSlackMessage(event as SlackMessageEvent, envelope.team_id);
+}
+
export function parseDirectMessageEvent(envelope: SlackEventCallback): SlackMessage | null {
if (envelope.type !== "event_callback") return null;
const event = envelope.event;
@@ -194,16 +214,20 @@ export function parseDirectMessageEvent(envelope: SlackEventCallback): SlackMess
const message = event as SlackMessageEvent;
if (message.channel_type !== "im") return null;
+ if (!isHumanMessage(message)) return null;
+
+ return buildSlackMessage(message, envelope.team_id);
+}
+
+function isHumanMessage(message: SlackMessageEvent): boolean {
if (
typeof message.subtype === "string" &&
message.subtype.length > 0 &&
message.subtype !== "file_share"
) {
- return null;
+ return false;
}
- if (typeof message.bot_id === "string" && message.bot_id.length > 0) return null;
-
- return buildSlackMessage(message, envelope.team_id);
+ return !(typeof message.bot_id === "string" && message.bot_id.length > 0);
}
export function slackMessageFromWebhookPayload(
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index 86688219f..60bb1df2a 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -227,11 +227,17 @@ function buildDirectMessageBody(overrides?: {
function buildEventBody(
event: Record<string, unknown>,
- overrides?: { eventId?: string; eventTime?: number; teamId?: string },
+ overrides?: {
+ authorizations?: readonly Record<string, unknown>[];
+ eventId?: string;
+ eventTime?: number;
+ teamId?: string;
+ },
): string {
mentionCounter += 1;
return JSON.stringify({
api_app_id: "A01",
+ authorizations: overrides?.authorizations,
event,
event_id: overrides?.eventId ?? `Ev${mentionCounter}`,
event_time: overrides?.eventTime ?? 1_700_000_000,
@@ -243,6 +249,7 @@ function buildEventBody(
async function firePost(
channel: unknown,
request: Request,
+ overrides: { readonly resolveActiveSession?: ReturnType<typeof vi.fn> } = {},
): Promise<{
response: Response;
send: ReturnType<typeof vi.fn>;
@@ -258,6 +265,8 @@ async function firePost(
const response = await post.handler(request, {
send,
+ resolveActiveSession:
+ overrides.resolveActiveSession ?? vi.fn().mockResolvedValue({ sessionId: "s1" }),
waitUntil,
getSession: vi.fn() as any,
params: {},
@@ -1348,6 +1357,110 @@ describe("slackChannel() inbound mention pipeline", () => {
});
});
+describe("slackChannel() onMessage", () => {
+ it("exposes mention and subscription helpers", async () => {
+ const observed: Array<{ mentioned: boolean; subscribed: boolean }> = [];
+ const onMessage = vi.fn(async (ctx) => {
+ observed.push({
+ mentioned: ctx.isBotMentioned(),
+ subscribed: await ctx.isSubscribed(),
+ });
+ return null;
+ });
+ const channel = slackChannel({
+ credentials: { botToken: "xoxb-test", signingSecret: SIGNING_SECRET },
+ onMessage,
+ });
+
+ const mention = buildMentionBody({ text: "<@U_BOT> help" });
+ await firePost(channel, buildSignedRequest({ body: mention.body }));
+
+ const reply = buildEventBody(
+ {
+ channel: "C01",
+ channel_type: "channel",
+ text: "continue",
+ thread_ts: "1700000000.000100",
+ ts: "1700000000.000200",
+ type: "message",
+ user: "U01",
+ },
+ { authorizations: [{ is_bot: true, user_id: "U_BOT" }] },
+ );
+ await firePost(channel, buildSignedRequest({ body: reply }));
+
+ expect(observed).toEqual([
+ { mentioned: true, subscribed: true },
+ { mentioned: false, subscribed: true },
+ ]);
+ });
+
+ it("allows a simple mention-or-subscription policy", async () => {
+ const channel = slackChannel({
+ credentials: { botToken: "xoxb-test", signingSecret: SIGNING_SECRET },
+ async onMessage(ctx) {
+ return ctx.isBotMentioned() || (await ctx.isSubscribed()) ? { auth: null } : null;
+ },
+ });
+ const reply = buildEventBody(
+ {
+ channel: "C01",
+ channel_type: "channel",
+ text: "continue",
+ thread_ts: "1700000000.000100",
+ ts: "1700000000.000200",
+ type: "message",
+ user: "U01",
+ },
+ { authorizations: [{ is_bot: true, user_id: "U_BOT" }] },
+ );
+
+ const { send } = await firePost(channel, buildSignedRequest({ body: reply }));
+
+ expect(send).toHaveBeenCalledWith(
+ expect.objectContaining({ message: expect.any(String) }),
+ expect.objectContaining({ continuationToken: "C01:1700000000.000100" }),
+ );
+ });
+
+ it("passes bot-authored messages to onMessage", async () => {
+ const onMessage = vi.fn((_ctx, _message: { author?: { isBot: boolean } }) => null);
+ const channel = slackChannel({
+ credentials: { botToken: "xoxb-test", signingSecret: SIGNING_SECRET },
+ onMessage,
+ });
+ const body = buildEventBody({
+ bot_id: "B01",
+ channel: "C01",
+ text: "automated",
+ ts: "1700000000.000200",
+ type: "message",
+ user: "U_BOT",
+ });
+
+ await firePost(channel, buildSignedRequest({ body }));
+
+ expect(onMessage).toHaveBeenCalledTimes(1);
+ expect(onMessage.mock.calls[0]![1].author?.isBot).toBe(true);
+ });
+
+ it("gives specialized message hooks precedence", async () => {
+ const onAppMention = vi.fn(() => null);
+ const onMessage = vi.fn(() => ({ auth: null }));
+ const channel = slackChannel({
+ credentials: { botToken: "xoxb-test", signingSecret: SIGNING_SECRET },
+ onAppMention,
+ onMessage,
+ });
+ const { body } = buildMentionBody();
+
+ await firePost(channel, buildSignedRequest({ body }));
+
+ expect(onAppMention).toHaveBeenCalledTimes(1);
+ expect(onMessage).not.toHaveBeenCalled();
+ });
+});
+
describe("slackChannel() generic Events API 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.ts
index 7eadd14ff..b076f39b6 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -30,7 +30,9 @@ import {
defaultOnDirectMessage,
} from "#public/channels/slack/defaults.js";
import {
+ parseMessageEvent,
type SlackEvent,
+ slackEventBotUserId,
type SlackEventEnvelope,
type SlackInboundContext,
type SlackMessage,
@@ -283,12 +285,25 @@ export interface SlackInboundEventContext {
readonly envelope: SlackEventEnvelope;
/** Starts a turn on this Slack channel using the proactive receive contract. */
readonly receive: SlackEventReceiveFn;
+ /** Resolves the active eve session for a Slack channel thread. */
+ readonly resolveActiveSession: (target: {
+ readonly channelId: string;
+ readonly threadTs: string;
+ }) => Promise<{ readonly sessionId: string } | undefined>;
/** 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;
}
+/** Message-scoped context handed to `slackChannel({ onMessage })`. */
+export interface SlackInboundMessageContext extends SlackContext {
+ /** Returns whether this message belongs to a thread with an active eve session. */
+ isSubscribed(): Promise<boolean>;
+ /** Returns whether the inbound event explicitly mentions this bot. */
+ isBotMentioned(): boolean;
+}
+
export interface SlackInteractionAction {
readonly actionId: string;
readonly value?: string;
@@ -422,6 +437,13 @@ export interface SlackChannelConfig {
*/
readonly threadContext?: LoadThreadContextMessagesOptions;
+ /**
+ * Handles human-authored Slack messages. Specialized `onAppMention` and
+ * `onDirectMessage` handlers take precedence for their event types. Other
+ * channel messages are ignored when this hook is omitted.
+ */
+ onMessage?(ctx: SlackInboundMessageContext, message: SlackMessage): SlackInboundResultOrPromise;
+
/**
* Invoked when a Slack `app_mention` event arrives (only `app_mention`;
* other event types are ignored). Decides whether to dispatch and with
@@ -599,7 +621,7 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
routes: [
POST<SlackChannelState>(
config.route ?? SLACK_CHANNEL_DEFAULT_ROUTE,
- async (req, { send, waitUntil }) => {
+ async (req, { resolveActiveSession, send, waitUntil }) => {
const body = await verifyInbound(req, config.credentials);
if (body === null) return new Response("unauthorized", { status: 401 });
@@ -614,6 +636,7 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
return handleEventPost({
body,
send,
+ resolveActiveSession,
waitUntil,
config,
uploadPolicy,
@@ -730,6 +753,9 @@ async function handleEventPost(input: {
readonly body: string;
readonly headers: Headers;
readonly send: SendFn<SlackChannelState>;
+ readonly resolveActiveSession: (options: {
+ readonly continuationToken: string;
+ }) => Promise<{ readonly sessionId: string } | undefined>;
readonly waitUntil: (task: Promise<unknown>) => void;
readonly config: SlackChannelConfig;
readonly uploadPolicy: UploadPolicy;
@@ -761,6 +787,7 @@ async function handleEventPost(input: {
// 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);
@@ -776,9 +803,21 @@ async function handleEventPost(input: {
threadContext: config.threadContext,
uploadPolicy: input.uploadPolicy,
});
- const authored = kind === "app_mention" ? config.onAppMention : config.onDirectMessage;
- if (authored !== undefined) {
- dispatch = dispatchMessageWith(authored);
+ const specialized = kind === "app_mention" ? config.onAppMention : config.onDirectMessage;
+ const handler = specialized ?? config.onMessage;
+ if (handler !== undefined) {
+ dispatch = () =>
+ dispatchSlackMessage({
+ botUserId: slackEventBotUserId(envelope),
+ credentials: config.credentials,
+ handler,
+ kind,
+ message,
+ resolveActiveSession: input.resolveActiveSession,
+ send: input.send,
+ threadContext: config.threadContext,
+ uploadPolicy: input.uploadPolicy,
+ });
} else {
builtinDefault = dispatchMessageWith(
kind === "app_mention" ? defaultOnAppMention : defaultOnDirectMessage,
@@ -787,9 +826,31 @@ async function handleEventPost(input: {
}
}
- // 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.
+ if (dispatch === null && config.onMessage !== undefined) {
+ const message = parseMessageEvent(envelope);
+ if (message !== null) {
+ const botUserId = slackEventBotUserId(envelope);
+ // Slack also emits message.channels for an app mention. The app_mention
+ // callback owns that user action so the generic message is not duplicated.
+ if (botUserId === undefined || !message.text.includes(`<@${botUserId}`)) {
+ dispatch = () =>
+ dispatchSlackMessage({
+ botUserId,
+ credentials: config.credentials,
+ handler: config.onMessage!,
+ kind: "channel_message",
+ message,
+ resolveActiveSession: input.resolveActiveSession,
+ send: input.send,
+ threadContext: config.threadContext,
+ uploadPolicy: input.uploadPolicy,
+ });
+ }
+ }
+ }
+
+ // Specialized handlers retain their bot/subtype filters. onMessage receives
+ // every structurally valid message event; onEvent remains the raw fallback.
const onEvent = config.onEvent;
if (dispatch === null && onEvent !== undefined) {
dispatch = () =>
@@ -797,6 +858,7 @@ async function handleEventPost(input: {
credentials: config.credentials,
envelope,
handler: onEvent,
+ resolveActiveSession: input.resolveActiveSession,
send: input.send,
});
}
@@ -822,11 +884,68 @@ async function handleEventPost(input: {
return new Response("ok");
}
+async function dispatchSlackMessage(input: {
+ readonly botUserId: string | undefined;
+ readonly credentials: SlackChannelCredentials | undefined;
+ readonly handler: NonNullable<SlackChannelConfig["onMessage"]>;
+ readonly kind: "app_mention" | "channel_message" | "direct_message";
+ readonly message: SlackMessage;
+ readonly resolveActiveSession: (options: {
+ readonly continuationToken: string;
+ }) => Promise<{ readonly sessionId: string } | undefined>;
+ readonly send: SendFn<SlackChannelState>;
+ readonly threadContext: LoadThreadContextMessagesOptions | undefined;
+ readonly uploadPolicy: UploadPolicy;
+}): Promise<void> {
+ const { thread, slack } = buildSlackBinding({
+ botToken: input.credentials?.botToken,
+ channelId: input.message.channelId,
+ threadTs: input.message.threadTs,
+ teamId: input.message.teamId,
+ });
+ const ctx: SlackInboundMessageContext = {
+ isBotMentioned: () =>
+ input.kind === "app_mention" ||
+ (input.botUserId !== undefined && input.message.text.includes(`<@${input.botUserId}`)),
+ isSubscribed: async () =>
+ (await input.resolveActiveSession({
+ continuationToken: slackContinuationToken(input.message.channelId, input.message.threadTs),
+ })) !== undefined,
+ slack,
+ thread,
+ };
+
+ let result;
+ try {
+ result = await input.handler(ctx, input.message);
+ } catch (error) {
+ logError(log, `${input.kind} handler failed`, error, {
+ channelId: input.message.channelId,
+ });
+ return;
+ }
+ if (result === null || result === undefined) return;
+
+ await deliverSlackMessage({
+ credentials: input.credentials,
+ kind: input.kind,
+ message: input.message,
+ result,
+ send: input.send,
+ thread,
+ threadContext: input.threadContext,
+ uploadPolicy: input.uploadPolicy,
+ });
+}
+
/** 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 resolveActiveSession: (options: {
+ readonly continuationToken: string;
+ }) => Promise<{ readonly sessionId: string } | undefined>;
readonly send: SendFn<SlackChannelState>;
}): Promise<void> {
const eventTeamId = input.envelope.event.team_id;
@@ -845,6 +964,10 @@ async function dispatchSlackEvent(input: {
send: input.send,
teamId,
}),
+ resolveActiveSession: ({ channelId, threadTs }) =>
+ input.resolveActiveSession({
+ continuationToken: slackContinuationToken(channelId, threadTs),
+ }),
slack: buildSlackWorkspaceHandle({
botToken: input.credentials?.botToken,
teamId,
@@ -923,6 +1046,29 @@ async function dispatchInboundMessage(input: {
}
if (result === null || result === undefined) return;
+ await deliverSlackMessage({
+ credentials: input.credentials,
+ kind,
+ message,
+ result,
+ send: input.send,
+ thread,
+ threadContext: input.threadContext,
+ uploadPolicy: input.uploadPolicy,
+ });
+}
+
+async function deliverSlackMessage(input: {
+ readonly credentials: SlackChannelCredentials | undefined;
+ readonly kind: string;
+ readonly message: SlackMessage;
+ readonly result: Exclude<SlackInboundResult, null>;
+ readonly send: SendFn<SlackChannelState>;
+ readonly thread: SlackThread;
+ readonly threadContext: LoadThreadContextMessagesOptions | undefined;
+ readonly uploadPolicy: UploadPolicy;
+}): Promise<void> {
+ const { message, thread } = input;
// This runs in the webhook's `waitUntil` task; an unguarded throw would
// reject silently into the dispatch `allSettled` ("no response, no logs").
try {
@@ -950,14 +1096,14 @@ async function dispatchInboundMessage(input: {
fileParts,
);
- const channelContext = result.context ?? [];
+ const channelContext = input.result.context ?? [];
await input.send(
channelContext.length === 0
? { message: turnMessage }
: { message: turnMessage, context: channelContext },
{
- auth: result.auth,
+ auth: input.result.auth,
continuationToken: slackContinuationToken(message.channelId, message.threadTs),
state: {
channelId: message.channelId,
@@ -969,6 +1115,6 @@ async function dispatchInboundMessage(input: {
},
);
} catch (error) {
- logError(log, `${kind} delivery failed`, error, { channelId: message.channelId });
+ logError(log, `${input.kind} delivery failed`, error, { channelId: message.channelId });
}
}
diff --git a/packages/eve/src/public/channels/teams/teamsChannel.test.ts b/packages/eve/src/public/channels/teams/teamsChannel.test.ts
index 9413748b2..e66bfbfbd 100644
--- a/packages/eve/src/public/channels/teams/teamsChannel.test.ts
+++ b/packages/eve/src/public/channels/teams/teamsChannel.test.ts
@@ -40,6 +40,7 @@ async function firePost(
}),
{
getSession: vi.fn(),
+ resolveActiveSession: async () => undefined,
cancel: vi.fn(),
params: {},
receive: vi.fn(),
diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.ts
index 354c1432f..e7e2019f1 100644
--- a/packages/eve/src/public/definitions/channel.ts
+++ b/packages/eve/src/public/definitions/channel.ts
@@ -35,6 +35,7 @@ export type {
SendFn,
SendOptions,
SendPayload,
+ ResolveActiveSessionFn,
GetSessionFn,
WebSocketMessage,
WebSocketPeer,
diff --git a/packages/eve/test/eve-run-stream-channel.test.ts b/packages/eve/test/eve-run-stream-channel.test.ts
index 58f65ab46..39f4f3e64 100644
--- a/packages/eve/test/eve-run-stream-channel.test.ts
+++ b/packages/eve/test/eve-run-stream-channel.test.ts
@@ -185,6 +185,7 @@ function createArgs(input: {
}): RouteHandlerArgs {
return {
send: vi.fn(),
+ resolveActiveSession: async () => undefined,
cancel: vi.fn(),
getSession: input.getSession,
receive: vi.fn() as any,
diff --git a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts
index 3af3cae1e..38035df8d 100644
--- a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts
+++ b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts
@@ -171,6 +171,7 @@ describe("cross-channel receive end-to-end", () => {
}),
{
receive,
+ resolveActiveSession: async () => undefined,
send: async () => {
throw new Error("webhook should delegate to args.receive()");
},