Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(slack): add reset to inbound contexts (#1171)

Casey Gowrie1987e12e002d
diff --git a/.changeset/tidy-sloths-reset.md b/.changeset/tidy-sloths-reset.md
new file mode 100644
index 000000000..5596ba14f
--- /dev/null
+++ b/.changeset/tidy-sloths-reset.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Add thread-bound session reset helpers to Slack message and interaction contexts, plus targeted reset support for generic Slack event handlers.
diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdx
index 040b8d9bf..5c03aed3c 100644
--- a/docs/channels/slack.mdx
+++ b/docs/channels/slack.mdx
@@ -104,7 +104,7 @@ 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
+#### Cancel an active turn
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:
@@ -123,6 +123,25 @@ export default slackChannel({
`"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.
+#### Reset a conversation
+
+Use the thread-bound `ctx.reset({ reason? })` helper when the conversation should start over instead. Reset terminally retires the session that currently owns the thread, including any in-flight turn. The next delivered message starts a new session with fresh history, state, and a new session-scoped sandbox:
+
+```ts title="agent/channels/slack.ts"
+export default slackChannel({
+ credentials: connectSlackCredentials("slack/my-agent"),
+ async onMessage(ctx, message) {
+ if (message.text.trim() !== "/new") return null;
+
+ await ctx.reset({ reason: "Slack user requested /new" });
+ await ctx.thread.post("Started a fresh conversation.");
+ return null;
+ },
+});
+```
+
+Reset returns `{ status: "reset", previousSessionId }` when the thread had a session, or `{ status: "no_active_session" }` when it was already free. Both outcomes are successful. Returning `null` after reset consumes the triggering message as a command; return `{ auth }` instead to deliver that message as the first turn of the fresh session. Custom `onInteraction` handlers receive the same bound reset helper, which is useful for a New conversation button.
+
### 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.
@@ -153,7 +172,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.
-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.
+Because a generic event is not necessarily tied to one thread, its session helpers take the target explicitly: `ctx.cancel({ channelId, threadTs, turnId? })` stops in-flight work while retaining the session, and `ctx.reset({ channelId, threadTs, reason? })` retires the session. Pair either one with `ctx.receive(...)` when an event should deliver replacement input, or call it alone to stop or reset the thread.
`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.
diff --git a/packages/eve/src/public/channels/slack/index.ts b/packages/eve/src/public/channels/slack/index.ts
index c93cdb22c..b21e93335 100644
--- a/packages/eve/src/public/channels/slack/index.ts
+++ b/packages/eve/src/public/channels/slack/index.ts
@@ -23,6 +23,7 @@ export {
type SlackEventContext,
type SlackEventReceiveFn,
type SlackEventReceiveOptions,
+ type SlackEventResetOptions,
type SlackHandle,
type SlackInboundEventContext,
type SlackInboundMessageContext,
@@ -35,6 +36,7 @@ export {
type SlackMentionResult,
type SlackMentionResultOrPromise,
type SlackReceiveTarget,
+ type SlackResetOptions,
type SlackSessionTarget,
type SlackThread,
type SlackWebhookVerifier,
diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.ts
index 7b4963dc5..b8ca0d119 100644
--- a/packages/eve/src/public/channels/slack/interactions.ts
+++ b/packages/eve/src/public/channels/slack/interactions.ts
@@ -53,7 +53,7 @@ import type {
SlackInteractionContext,
SlackInteractionUser,
} from "#public/channels/slack/slackChannel.js";
-import type { CancelFn, SendFn } from "#public/definitions/channel.js";
+import type { CancelFn, ResetFn, SendFn } from "#public/definitions/channel.js";
const log = createLogger("slack.interactions");
@@ -340,6 +340,7 @@ export async function handleInteractionPost(
rawBody: string,
ctx: {
cancel: CancelFn;
+ reset: ResetFn;
send: SendFn<SlackChannelState>;
waitUntil: (task: Promise<unknown>) => void;
},
@@ -430,6 +431,11 @@ export async function handleInteractionPost(
continuationToken,
turnId: options.turnId,
}),
+ reset: (options = {}) =>
+ ctx.reset({
+ continuationToken,
+ reason: options.reason,
+ }),
thread,
slack,
};
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index 16f3b2124..630e27a9f 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -251,10 +251,12 @@ async function firePost(
request: Request,
overrides: {
readonly cancel?: ReturnType<typeof vi.fn>;
+ readonly reset?: ReturnType<typeof vi.fn>;
readonly resolveActiveSession?: ReturnType<typeof vi.fn>;
} = {},
): Promise<{
cancel: ReturnType<typeof vi.fn>;
+ reset: ReturnType<typeof vi.fn>;
response: Response;
send: ReturnType<typeof vi.fn>;
waitUntil: ReturnType<typeof vi.fn>;
@@ -265,11 +267,15 @@ async function firePost(
throw new Error("Expected slack channel to define a POST route.");
}
const cancel = overrides.cancel ?? vi.fn().mockResolvedValue({ status: "accepted" });
+ const reset =
+ overrides.reset ??
+ vi.fn().mockResolvedValue({ status: "reset", previousSessionId: "session_previous" });
const send = vi.fn().mockResolvedValue({ id: "s1", continuationToken: "ct" });
const waitUntil = vi.fn();
const response = await post.handler(request, {
cancel,
+ reset,
send,
resolveActiveSession:
overrides.resolveActiveSession ?? vi.fn().mockResolvedValue({ sessionId: "s1" }),
@@ -286,7 +292,7 @@ async function firePost(
await Promise.allSettled(pending);
}
- return { cancel, response, send, waitUntil };
+ return { cancel, reset, response, send, waitUntil };
}
describe("slackChannel() default event handlers", () => {
@@ -1107,6 +1113,29 @@ describe("slackChannel() inbound mention pipeline", () => {
expect(cancel.mock.invocationCallOrder[0]).toBeLessThan(send.mock.invocationCallOrder[0]!);
});
+ it("lets onAppMention reset the thread session before starting a fresh replacement", async () => {
+ const channel = slackChannel({
+ credentials: { botToken: "xoxb-test" },
+ async onAppMention(ctx) {
+ await ctx.reset({ reason: "Slack user requested a fresh conversation" });
+ return { auth: null };
+ },
+ });
+ const { body } = buildMentionBody({
+ channel: "C_RESET",
+ threadTs: "1700000000.000200",
+ });
+
+ const { reset, send } = await firePost(channel, buildSignedRequest({ body }));
+
+ expect(reset).toHaveBeenCalledWith({
+ continuationToken: "C_RESET:1700000000.000200",
+ reason: "Slack user requested a fresh conversation",
+ });
+ expect(send).toHaveBeenCalledTimes(1);
+ expect(reset.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({
@@ -1654,6 +1683,27 @@ describe("slackChannel() generic Events API pipeline", () => {
});
});
+ it("resets a targeted Slack thread from onEvent", async () => {
+ const channel = slackChannel({
+ credentials: { botToken: "xoxb-test" },
+ async onEvent(ctx) {
+ await ctx.reset({
+ channelId: "C01",
+ threadTs: "1700000000.000001",
+ reason: "Reaction requested a fresh conversation",
+ });
+ },
+ });
+ const body = buildEventBody({ type: "reaction_added", user: "U01" });
+
+ const { reset } = await firePost(channel, buildSignedRequest({ body }));
+
+ expect(reset).toHaveBeenCalledWith({
+ continuationToken: "C01:1700000000.000001",
+ reason: "Reaction requested a fresh conversation",
+ });
+ });
+
it("can start multiple turns through the pre-bound receive function", async () => {
const auth = {
attributes: { source: "reaction" },
@@ -2058,6 +2108,43 @@ describe("slackChannel() HITL interaction pipeline", () => {
expect(send).not.toHaveBeenCalled();
});
+ it("resets the interaction's Slack thread from onInteraction", async () => {
+ const channel = slackChannel({
+ credentials: { botToken: "xoxb-test" },
+ async onInteraction(action, ctx) {
+ expect(action.actionId).toBe("new-conversation");
+ await ctx.reset({ reason: "New conversation button clicked" });
+ },
+ });
+
+ const { reset, 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: "new-conversation",
+ text: { type: "plain_text", text: "New conversation" },
+ },
+ ],
+ }),
+ );
+
+ expect(reset).toHaveBeenCalledWith({
+ continuationToken: "C01:1700000000.000001",
+ reason: "New conversation button clicked",
+ });
+ 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.ts
index 5befdc447..7399bf6b9 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -61,6 +61,8 @@ import {
POST,
type CancelFn,
type Channel,
+ type ResetFn,
+ type ResetResult,
type SendFn,
} from "#public/definitions/channel.js";
import { markEventHandled } from "./utils.js";
@@ -295,12 +297,21 @@ export interface SlackCancelOptions {
readonly turnId?: string;
}
+/** Options for resetting the session bound to a message or interaction context. */
+export interface SlackResetOptions {
+ /** Human-readable terminal reason. Do not include credentials or message contents. */
+ readonly reason?: string;
+}
+
/**
* Target and optional stale-turn guard accepted by `onEvent`'s cancellation
* helper.
*/
export interface SlackEventCancelOptions extends SlackSessionTarget, SlackCancelOptions {}
+/** Target and optional terminal reason accepted by `onEvent`'s reset helper. */
+export interface SlackEventResetOptions extends SlackSessionTarget, SlackResetOptions {}
+
/**
* Imperative surface handed to `slackChannel({ onEvent })`. Generic Events API
* payloads are not necessarily tied to one thread, so the context exposes a
@@ -321,6 +332,11 @@ export interface SlackInboundEventContext {
readonly resolveActiveSession: (
target: SlackSessionTarget,
) => Promise<{ readonly sessionId: string } | undefined>;
+ /**
+ * Terminally retires the session for a Slack thread so its next message starts
+ * a fresh session.
+ */
+ readonly reset: (options: SlackEventResetOptions) => Promise<ResetResult>;
/** Workspace-scoped Slack identity and raw Web API escape hatch. */
readonly slack: SlackWorkspaceHandle;
/** Keeps detached handler work alive after the Slack webhook is acknowledged. */
@@ -341,6 +357,11 @@ export interface SlackInboundMessageContext extends SlackContext {
isSubscribed(): Promise<boolean>;
/** Returns whether the inbound event explicitly mentions this bot. */
isBotMentioned(): boolean;
+ /**
+ * Terminally retires this thread's session so its next delivered message
+ * starts with fresh history and state.
+ */
+ reset(options?: SlackResetOptions): Promise<ResetResult>;
}
/** Interaction-scoped context handed to `slackChannel({ onInteraction })`. */
@@ -350,6 +371,11 @@ export interface SlackInteractionContext extends SlackContext {
* `"no_active_turn"` are successful outcomes.
*/
cancel(options?: SlackCancelOptions): Promise<CancelTurnResult>;
+ /**
+ * Terminally retires this thread's session so the continuation token can
+ * start a fresh session.
+ */
+ reset(options?: SlackResetOptions): Promise<ResetResult>;
}
export interface SlackInteractionAction {
@@ -678,7 +704,7 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
routes: [
POST<SlackChannelState>(
config.route ?? SLACK_CHANNEL_DEFAULT_ROUTE,
- async (req, { cancel, resolveActiveSession, send, waitUntil }) => {
+ async (req, { cancel, reset, resolveActiveSession, send, waitUntil }) => {
const body = await verifyInbound(req, config.credentials);
if (body === null) return new Response("unauthorized", { status: 401 });
@@ -688,11 +714,12 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
const contentType = req.headers.get("content-type") ?? "";
if (contentType.includes("application/x-www-form-urlencoded")) {
- return handleInteractionPost(body, { cancel, send, waitUntil }, { config });
+ return handleInteractionPost(body, { cancel, reset, send, waitUntil }, { config });
}
return handleEventPost({
body,
cancel,
+ reset,
send,
resolveActiveSession,
waitUntil,
@@ -810,6 +837,7 @@ function shouldDropSlackHttpTimeoutRetry(headers: Headers): boolean {
async function handleEventPost(input: {
readonly body: string;
readonly cancel: CancelFn;
+ readonly reset: ResetFn;
readonly headers: Headers;
readonly send: SendFn<SlackChannelState>;
readonly resolveActiveSession: (options: {
@@ -864,6 +892,7 @@ async function handleEventPost(input: {
kind,
message,
resolveActiveSession: input.resolveActiveSession,
+ reset: input.reset,
send: input.send,
threadContext: config.threadContext,
uploadPolicy: input.uploadPolicy,
@@ -881,6 +910,7 @@ async function handleEventPost(input: {
kind,
message,
resolveActiveSession: input.resolveActiveSession,
+ reset: input.reset,
send: input.send,
threadContext: config.threadContext,
uploadPolicy: input.uploadPolicy,
@@ -909,6 +939,7 @@ async function handleEventPost(input: {
kind: "channel_message",
message,
resolveActiveSession: input.resolveActiveSession,
+ reset: input.reset,
send: input.send,
threadContext: config.threadContext,
uploadPolicy: input.uploadPolicy,
@@ -928,6 +959,7 @@ async function handleEventPost(input: {
envelope,
handler: onEvent,
resolveActiveSession: input.resolveActiveSession,
+ reset: input.reset,
send: input.send,
});
}
@@ -977,6 +1009,7 @@ async function dispatchSlackMessage(input: {
readonly resolveActiveSession: (options: {
readonly continuationToken: string;
}) => Promise<{ readonly sessionId: string } | undefined>;
+ readonly reset: ResetFn;
readonly send: SendFn<SlackChannelState>;
readonly threadContext: LoadThreadContextMessagesOptions | undefined;
readonly uploadPolicy: UploadPolicy;
@@ -1003,6 +1036,11 @@ async function dispatchSlackMessage(input: {
(await input.resolveActiveSession({
continuationToken,
})) !== undefined,
+ reset: (options = {}) =>
+ input.reset({
+ continuationToken,
+ reason: options.reason,
+ }),
slack,
thread,
};
@@ -1039,6 +1077,7 @@ async function dispatchSlackEvent(input: {
readonly resolveActiveSession: (options: {
readonly continuationToken: string;
}) => Promise<{ readonly sessionId: string } | undefined>;
+ readonly reset: ResetFn;
readonly send: SendFn<SlackChannelState>;
}): Promise<void> {
const eventTeamId = input.envelope.event.team_id;
@@ -1066,6 +1105,11 @@ async function dispatchSlackEvent(input: {
input.resolveActiveSession({
continuationToken: slackContinuationToken(channelId, threadTs),
}),
+ reset: ({ channelId, threadTs, reason }) =>
+ input.reset({
+ continuationToken: slackContinuationToken(channelId, threadTs),
+ reason,
+ }),
slack: buildSlackWorkspaceHandle({
botToken: input.credentials?.botToken,
teamId,