The Open Framework for Building Agents
feat(eve): slack - expose cancellation in handler contexts (#1118)
Andrew Barba6c433f483579
diff --git a/.changeset/bright-slack-cancel.md b/.changeset/bright-slack-cancel.mdnew file mode 100644index 000000000..a8f9cc8c0--- /dev/null+++ b/.changeset/bright-slack-cancel.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Expose thread-scoped cancellation in Slack message and interaction contexts, plus target-addressed cancellation in `onEvent`, so authored Slack handlers can stop or replace in-flight turns.diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex 47b79051b..040b8d9bf 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -104,6 +104,25 @@ async onMessage(ctx, message) {Like `threadContext`, this helper calls `conversations.replies` and requires the matching Slack history scope. It observes at most the first 50 messages of the thread, and a failed fetch is logged and swallowed, so the returned list may be empty or stale — treat an unexpected empty list as "don't route" rather than "no participants".+#### Cancel and replace in-flight work++Message hooks (`onMessage`, `onAppMention`, and `onDirectMessage`) receive a thread-bound `ctx.cancel({ turnId? })` helper. Call it before returning `{ auth }` to stop the current turn and queue the new Slack message as replacement input, producing a debounce-like experience:++```ts title="agent/channels/slack.ts"+export default slackChannel({+ credentials: connectSlackCredentials("slack/my-agent"),+ async onMessage(ctx, message) {+ const shouldHandle = ctx.isBotMentioned() || (await ctx.isSubscribed());+ if (!shouldHandle || message.author?.isBot) return null;++ await ctx.cancel();+ return { auth: null };+ },+});+```++`"accepted"` means the cancellation request was consumed; `"no_active_turn"` means the thread had no cancellable turn. Both are successful outcomes, so the hook can still return `{ auth }` to deliver the replacement message. Cancellation never sends input itself. A custom `onInteraction` handler receives the same bound helper, which is useful for a Stop button that should cancel without replacement input.+### Other Events API callbacksUse `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.@@ -134,6 +153,8 @@ 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.+Because a generic event is not necessarily tied to one thread, its cancellation helper takes the target explicitly: `ctx.cancel({ channelId, threadTs, turnId? })`. Pair it with `ctx.receive(...)` when an event should replace in-flight work, or call it alone to stop the turn.+`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/public/channels/slack/index.ts b/packages/eve/src/public/channels/slack/index.tsindex e342996f6..c93cdb22c 100644--- a/packages/eve/src/public/channels/slack/index.ts+++ b/packages/eve/src/public/channels/slack/index.ts@@ -12,25 +12,30 @@ export {type SlackAuthorizationEventContext,type SlackAuthorizationRequiredHandler,type SlackBotToken,+ type SlackCancelOptions,type SlackChannel,type SlackChannelConfig,type SlackChannelCredentials,type SlackChannelEvents,type SlackChannelState,type SlackContext,+ type SlackEventCancelOptions,type SlackEventContext,type SlackEventReceiveFn,type SlackEventReceiveOptions,type SlackHandle,type SlackInboundEventContext,+ type SlackInboundMessageContext,type SlackInboundResult,type SlackInboundResultOrPromise,type SlackInitialMessage,type SlackInstrumentationMetadata,type SlackInteractionAction,+ type SlackInteractionContext,type SlackMentionResult,type SlackMentionResultOrPromise,type SlackReceiveTarget,+ type SlackSessionTarget,type SlackThread,type SlackWebhookVerifier,type SlackWorkspaceHandle,diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.tsindex 78112793e..7b4963dc5 100644--- a/packages/eve/src/public/channels/slack/interactions.ts+++ b/packages/eve/src/public/channels/slack/interactions.ts@@ -49,11 +49,11 @@ import {import type {SlackChannelConfig,SlackChannelState,- SlackContext,SlackInteractionAction,+ SlackInteractionContext,SlackInteractionUser,} from "#public/channels/slack/slackChannel.js";-import type { SendFn } from "#public/definitions/channel.js";+import type { CancelFn, SendFn } from "#public/definitions/channel.js";const log = createLogger("slack.interactions");@@ -339,6 +339,7 @@ export interface InteractionHandlerDeps {export async function handleInteractionPost(rawBody: string,ctx: {+ cancel: CancelFn;send: SendFn<SlackChannelState>;waitUntil: (task: Promise<unknown>) => void;},@@ -423,7 +424,15 @@ export async function handleInteractionPost(threadTs: interaction.threadTs,teamId: interaction.teamId,});- const slackCtx: SlackContext = { thread, slack };+ const slackCtx: SlackInteractionContext = {+ cancel: (options = {}) =>+ ctx.cancel({+ continuationToken,+ turnId: options.turnId,+ }),+ thread,+ slack,+ };for (const action of customActions) {ctx.waitUntil(Promise.resolve(onInteraction(action, slackCtx)).catch((error: unknown) => {diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.tsindex 63f71660d..16f3b2124 100644--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts@@ -249,8 +249,12 @@ function buildEventBody(async function firePost(channel: unknown,request: Request,- overrides: { readonly resolveActiveSession?: ReturnType<typeof vi.fn> } = {},+ overrides: {+ readonly cancel?: ReturnType<typeof vi.fn>;+ readonly resolveActiveSession?: ReturnType<typeof vi.fn>;+ } = {},): Promise<{+ cancel: ReturnType<typeof vi.fn>;response: Response;send: ReturnType<typeof vi.fn>;waitUntil: ReturnType<typeof vi.fn>;@@ -260,10 +264,12 @@ async function firePost(if (!post || !isHttpRouteDefinition(post)) {throw new Error("Expected slack channel to define a POST route.");}+ const cancel = overrides.cancel ?? vi.fn().mockResolvedValue({ status: "accepted" });const send = vi.fn().mockResolvedValue({ id: "s1", continuationToken: "ct" });const waitUntil = vi.fn();const response = await post.handler(request, {+ cancel,send,resolveActiveSession:overrides.resolveActiveSession ?? vi.fn().mockResolvedValue({ sessionId: "s1" }),@@ -280,7 +286,7 @@ async function firePost(await Promise.allSettled(pending);}- return { response, send, waitUntil };+ return { cancel, response, send, waitUntil };}describe("slackChannel() default event handlers", () => {@@ -1078,6 +1084,29 @@ describe("slackChannel() inbound mention pipeline", () => {});});+ it("lets onAppMention cancel the active turn before dispatching its replacement", async () => {+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ async onAppMention(ctx) {+ await ctx.cancel({ turnId: "turn_observed" });+ return { auth: null };+ },+ });+ const { body } = buildMentionBody({+ channel: "C_STEER",+ threadTs: "1700000000.000100",+ });++ const { cancel, send } = await firePost(channel, buildSignedRequest({ body }));++ expect(cancel).toHaveBeenCalledWith({+ continuationToken: "C_STEER:1700000000.000100",+ turnId: "turn_observed",+ });+ expect(send).toHaveBeenCalledTimes(1);+ expect(cancel.mock.invocationCallOrder[0]).toBeLessThan(send.mock.invocationCallOrder[0]!);+ });+it("drops Slack http_timeout retries without dispatching", async () => {const onAppMention = vi.fn().mockReturnValue({ auth: null });const channel = slackChannel({@@ -1604,6 +1633,27 @@ describe("slackChannel() generic Events API pipeline", () => {expect(String(fetchMock.mock.calls[0]![0])).toBe("https://slack.com/api/reactions.get");});+ it("cancels a targeted Slack thread from onEvent", async () => {+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ async onEvent(ctx) {+ await ctx.cancel({+ channelId: "C01",+ threadTs: "1700000000.000001",+ turnId: "turn_observed",+ });+ },+ });+ const body = buildEventBody({ type: "reaction_added", user: "U01" });++ const { cancel } = await firePost(channel, buildSignedRequest({ body }));++ expect(cancel).toHaveBeenCalledWith({+ continuationToken: "C01:1700000000.000001",+ turnId: "turn_observed",+ });+ });+it("can start multiple turns through the pre-bound receive function", async () => {const auth = {attributes: { source: "reaction" },@@ -1976,6 +2026,38 @@ describe("slackChannel() HITL interaction pipeline", () => {}});+ it("cancels the interaction's Slack thread from onInteraction", async () => {+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ async onInteraction(action, ctx) {+ expect(action.actionId).toBe("stop");+ await ctx.cancel({ turnId: "turn_observed" });+ },+ });++ const { cancel, send } = await firePost(+ channel,+ buildSignedInteractionRequest({+ type: "block_actions",+ team: { id: "T01" },+ user: { id: "U01", username: "ada" },+ channel: { id: "C01" },+ message: {+ ts: "1700000000.000010",+ thread_ts: "1700000000.000001",+ blocks: [],+ },+ actions: [{ action_id: "stop", text: { type: "plain_text", text: "Stop" } }],+ }),+ );++ expect(cancel).toHaveBeenCalledWith({+ continuationToken: "C01:1700000000.000001",+ turnId: "turn_observed",+ });+ expect(send).not.toHaveBeenCalled();+ });+it("resumes HITL button answers with the approving Slack user auth", 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.tsindex 198f6f61a..5befdc447 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -2,7 +2,7 @@ import { parseSlackWebhookBody } from "#compiled/@chat-adapter/slack/webhook.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 { CancelTurnResult, SessionAuthContext } from "#channel/types.js";import type { CardElement } from "#compiled/chat/index.js";import type { SessionContext } from "#public/definitions/callback-context.js";import type { ChannelSessionOps } from "#public/definitions/channel.js";@@ -56,7 +56,13 @@ import {type UploadPolicyInput,} from "#public/channels/upload-policy.js";import { verifySlackRequest, type SlackWebhookVerifier } from "#public/channels/slack/verify.js";-import { defineChannel, POST, type Channel, type SendFn } from "#public/definitions/channel.js";+import {+ defineChannel,+ POST,+ type CancelFn,+ type Channel,+ type SendFn,+} from "#public/definitions/channel.js";import { markEventHandled } from "./utils.js";const log = createLogger("slack.channel");@@ -65,8 +71,7 @@ type EventData<T extends HandleMessageStreamEvent["type"]> =Extract<HandleMessageStreamEvent, { type: T }> extends { data: infer D } ? D : undefined;/**- * Pre-dispatch Slack context passed to `onAppMention` and- * `onInteraction`. These hooks run on the inbound webhook side before the+ * Base Slack context for inbound webhook handlers. These hooks run before the* runtime hydrates session state, so `state` is absent here.* {@link thread} owns thread-scoped operations (`post`, `postEphemeral`,* `startTyping`, `refresh`, `listParticipants`, `recentMessages`,@@ -274,6 +279,28 @@ export type SlackEventReceiveOptions = CrossChannelReceiveOptions<SlackReceiveTa*/export type SlackEventReceiveFn = (options: SlackEventReceiveOptions) => Promise<Session>;+/**+ * Slack thread identity used by workspace-scoped inbound helpers.+ */+export interface SlackSessionTarget {+ readonly channelId: string;+ readonly threadTs: string;+}++/**+ * Options for cancelling the turn bound to a message or interaction context.+ * `turnId` guards against a stale request cancelling a newer turn.+ */+export interface SlackCancelOptions {+ readonly turnId?: string;+}++/**+ * Target and optional stale-turn guard accepted by `onEvent`'s cancellation+ * helper.+ */+export interface SlackEventCancelOptions extends SlackSessionTarget, SlackCancelOptions {}+/*** Imperative surface handed to `slackChannel({ onEvent })`. Generic Events API* payloads are not necessarily tied to one thread, so the context exposes a@@ -281,29 +308,50 @@ export type SlackEventReceiveFn = (options: SlackEventReceiveOptions) => Promise* thread-scoped {@link SlackContext} used by message handlers.*/export interface SlackInboundEventContext {+ /**+ * Cancels the active turn for a Slack thread. Both `"accepted"` and+ * `"no_active_turn"` are successful outcomes.+ */+ readonly cancel: (options: SlackEventCancelOptions) => Promise<CancelTurnResult>;/** 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;/** Resolves the active eve session for a Slack channel thread. */- readonly resolveActiveSession: (target: {- readonly channelId: string;- readonly threadTs: string;- }) => Promise<{ readonly sessionId: string } | undefined>;+ readonly resolveActiveSession: (+ target: SlackSessionTarget,+ ) => 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 })`. */+/**+ * Message-scoped context handed to `onMessage`, `onAppMention`, and+ * `onDirectMessage`.+ */export interface SlackInboundMessageContext extends SlackContext {+ /**+ * Cancels the active turn in this message's thread. Both `"accepted"` and+ * `"no_active_turn"` are successful outcomes.+ */+ cancel(options?: SlackCancelOptions): Promise<CancelTurnResult>;/** 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;}+/** Interaction-scoped context handed to `slackChannel({ onInteraction })`. */+export interface SlackInteractionContext extends SlackContext {+ /**+ * Cancels the active turn in the interaction's thread. Both `"accepted"` and+ * `"no_active_turn"` are successful outcomes.+ */+ cancel(options?: SlackCancelOptions): Promise<CancelTurnResult>;+}+export interface SlackInteractionAction {readonly actionId: string;readonly value?: string;@@ -458,7 +506,10 @@ export interface SlackChannelConfig {* non-fatal. Defaults to a workspace-scoped auth derivation that posts a* `"Thinking..."` typing indicator; replacing this replaces both.*/- onAppMention?(ctx: SlackContext, message: SlackMessage): SlackMentionResultOrPromise;+ onAppMention?(+ ctx: SlackInboundMessageContext,+ message: SlackMessage,+ ): SlackMentionResultOrPromise;/*** Invoked on a direct message: a Slack `message` event with@@ -477,7 +528,10 @@ export interface SlackChannelConfig {* Requires the bot's Slack app to subscribe to `message.im` with the* `im:history` scope.*/- onDirectMessage?(ctx: SlackContext, message: SlackMessage): SlackInboundResultOrPromise;+ onDirectMessage?(+ ctx: SlackInboundMessageContext,+ message: SlackMessage,+ ): SlackInboundResultOrPromise;/*** Fallback handler for signed Slack Events API callbacks. An authored@@ -515,7 +569,10 @@ export interface SlackChannelConfig {* used by event handlers. Use `ctx.slack.request(...)` for arbitrary* Slack Web API calls and `action.messageTs` to target `chat.update`.*/- onInteraction?(action: SlackInteractionAction, ctx: SlackContext): void | Promise<void>;+ onInteraction?(+ action: SlackInteractionAction,+ ctx: SlackInteractionContext,+ ): void | Promise<void>;readonly events?: SlackChannelEvents;}@@ -621,7 +678,7 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {routes: [POST<SlackChannelState>(config.route ?? SLACK_CHANNEL_DEFAULT_ROUTE,- async (req, { resolveActiveSession, send, waitUntil }) => {+ async (req, { cancel, resolveActiveSession, send, waitUntil }) => {const body = await verifyInbound(req, config.credentials);if (body === null) return new Response("unauthorized", { status: 401 });@@ -631,10 +688,11 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {const contentType = req.headers.get("content-type") ?? "";if (contentType.includes("application/x-www-form-urlencoded")) {- return handleInteractionPost(body, { send, waitUntil }, { config });+ return handleInteractionPost(body, { cancel, send, waitUntil }, { config });}return handleEventPost({body,+ cancel,send,resolveActiveSession,waitUntil,@@ -751,6 +809,7 @@ function shouldDropSlackHttpTimeoutRetry(headers: Headers): boolean {*/async function handleEventPost(input: {readonly body: string;+ readonly cancel: CancelFn;readonly headers: Headers;readonly send: SendFn<SlackChannelState>;readonly resolveActiveSession: (options: {@@ -796,13 +855,15 @@ async function handleEventPost(input: {if (message !== null && !isSelfAuthoredSlackMessage({ appId, botUserId }, message)) {const dispatchMessageWith =(handler: NonNullable<SlackChannelConfig["onAppMention"]>) => () =>- dispatchInboundMessage({+ dispatchSlackMessage({appId,botUserId,+ cancel: input.cancel,credentials: config.credentials,handler,kind,message,+ resolveActiveSession: input.resolveActiveSession,send: input.send,threadContext: config.threadContext,uploadPolicy: input.uploadPolicy,@@ -814,6 +875,7 @@ async function handleEventPost(input: {dispatchSlackMessage({appId,botUserId,+ cancel: input.cancel,credentials: config.credentials,handler,kind,@@ -841,6 +903,7 @@ async function handleEventPost(input: {dispatchSlackMessage({appId,botUserId,+ cancel: input.cancel,credentials: config.credentials,handler: config.onMessage!,kind: "channel_message",@@ -860,6 +923,7 @@ async function handleEventPost(input: {if (dispatch === null && onEvent !== undefined) {dispatch = () =>dispatchSlackEvent({+ cancel: input.cancel,credentials: config.credentials,envelope,handler: onEvent,@@ -905,6 +969,7 @@ function isSelfAuthoredSlackMessage(async function dispatchSlackMessage(input: {readonly appId: string | undefined;readonly botUserId: string | undefined;+ readonly cancel: CancelFn;readonly credentials: SlackChannelCredentials | undefined;readonly handler: NonNullable<SlackChannelConfig["onMessage"]>;readonly kind: "app_mention" | "channel_message" | "direct_message";@@ -916,6 +981,7 @@ async function dispatchSlackMessage(input: {readonly threadContext: LoadThreadContextMessagesOptions | undefined;readonly uploadPolicy: UploadPolicy;}): Promise<void> {+ const continuationToken = slackContinuationToken(input.message.channelId, input.message.threadTs);const { thread, slack } = buildSlackBinding({appId: input.appId,botToken: input.credentials?.botToken,@@ -925,12 +991,17 @@ async function dispatchSlackMessage(input: {teamId: input.message.teamId,});const ctx: SlackInboundMessageContext = {+ cancel: (options = {}) =>+ input.cancel({+ continuationToken,+ turnId: options.turnId,+ }),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),+ continuationToken,})) !== undefined,slack,thread,@@ -961,6 +1032,7 @@ async function dispatchSlackMessage(input: {/** Runs a generic Events API handler with an imperative Slack receive surface. */async function dispatchSlackEvent(input: {+ readonly cancel: CancelFn;readonly credentials: SlackChannelCredentials | undefined;readonly envelope: SlackEventEnvelope;readonly handler: NonNullable<SlackChannelConfig["onEvent"]>;@@ -978,6 +1050,11 @@ async function dispatchSlackEvent(input: {: undefined;const waitUntilTasks: Promise<unknown>[] = [];const ctx: SlackInboundEventContext = {+ cancel: ({ channelId, threadTs, turnId }) =>+ input.cancel({+ continuationToken: slackContinuationToken(channelId, threadTs),+ turnId,+ }),envelope: input.envelope,receive: (options) =>receiveOnSlack(options, {@@ -1032,57 +1109,6 @@ async function verifyInbound(}}-/**- * Runs the inbound handler for an `app_mention` or direct message and,- * when it returns a non-null result, dispatches the message to the- * runtime via `send`. Errors are caught and logged so a misbehaving- * handler never crashes the webhook ACK.- */-async function dispatchInboundMessage(input: {- readonly appId: string | undefined;- readonly botUserId: string | undefined;- readonly kind: "app_mention" | "direct_message";- readonly message: SlackMessage;- readonly handler:- | NonNullable<SlackChannelConfig["onAppMention"]>- | NonNullable<SlackChannelConfig["onDirectMessage"]>;- readonly send: SendFn<SlackChannelState>;- readonly uploadPolicy: UploadPolicy;- readonly threadContext: LoadThreadContextMessagesOptions | undefined;- readonly credentials: SlackChannelCredentials | undefined;-}): Promise<void> {- const { message, kind } = input;- const { thread, slack } = buildSlackBinding({- appId: input.appId,- botToken: input.credentials?.botToken,- botUserId: input.botUserId,- channelId: message.channelId,- threadTs: message.threadTs,- teamId: message.teamId,- });- const slackCtx: SlackContext = { thread, slack };-- let result;- try {- result = await input.handler(slackCtx, message);- } catch (error) {- logError(log, `${kind} handler failed`, error, { channelId: message.channelId });- return;- }- 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;