Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): slack - preserve message sender attribution (#298)

Andrew Barba72b3d0e8d52b
diff --git a/.changeset/tidy-sloths-attribute.md b/.changeset/tidy-sloths-attribute.md
new file mode 100644
index 000000000..48c211e9b
--- /dev/null
+++ b/.changeset/tidy-sloths-attribute.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Keep Slack sender ids attached to their message text and add an opt-in `threadContext` setting that injects ID-attributed thread replies since a configurable boundary. Workflow titles retain the original Slack text, while later turns and authorization prompts consistently use the current caller.
diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdx
index 76526a575..8321ea70d 100644
--- a/docs/channels/custom.mdx
+++ b/docs/channels/custom.mdx
@@ -46,7 +46,7 @@ export default defineChannel({
Declare routes with the `POST()` and `GET()` helpers. Each route handler receives the raw `Request` and a helpers object:
-- `send(message, { auth, continuationToken, state? })` starts or resumes a session. Returns a `Session`.
+- `send(message, { auth, continuationToken, state?, title? })` starts or resumes a session. `title` overrides the new workflow session's display title without changing the model message. Returns a `Session`.
- `getSession(sessionId)` looks up an existing session. The returned `Session` exposes `getEventStream({ startIndex? })` for streaming.
- `receive(channel, ...)` hands inbound work to a different channel for cross-channel hand-off.
- `params` holds route parameters extracted from the path pattern.
@@ -182,7 +182,7 @@ When a parent agent dispatches a subagent, the framework forwards the parent's c
## Continuation tokens
-Each call to `send(message, { auth, continuationToken, state? })` from a channel route addresses a session by its channel-local raw token. The framework prepends the channel name, derived from the file stem under `agent/channels/`, before handing the token to the runtime.
+Each call to `send(message, { auth, continuationToken, state?, title? })` from a channel route addresses a session by its channel-local raw token. The framework prepends the channel name, derived from the file stem under `agent/channels/`, before handing the token to the runtime.
```ts
import { slackContinuationToken } from "eve/channels/slack";
diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdx
index 00ac5b3d7..ea9ca1d1b 100644
--- a/docs/channels/slack.mdx
+++ b/docs/channels/slack.mdx
@@ -54,28 +54,22 @@ Inbound hooks decide whether to dispatch a turn and with what `auth`. Return `{
- `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.
-You get the triggering mention by default, but not the earlier replies in the thread. Pull them in with `loadThreadContextMessages` and return them as `context`, which eve appends to history as user messages the model sees on every later turn. Use `since: "last-agent-reply"` so repeated mentions in one thread inject only what is new:
+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.
+
+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
-import { defaultSlackAuth, loadThreadContextMessages, slackChannel } from "eve/channels/slack";
+import { slackChannel } from "eve/channels/slack";
import { connectSlackCredentials } from "@vercel/connect/eve";
export default slackChannel({
credentials: connectSlackCredentials("slack/my-agent"),
- async onAppMention(ctx, message) {
- const auth = defaultSlackAuth(message, ctx);
- const prior = await loadThreadContextMessages(ctx.thread, message, {
- since: "last-agent-reply",
- });
- if (prior.length === 0) return { auth };
- const transcript = prior
- .map((m) => `${m.isMe ? "you" : (m.user ?? "user")}: ${m.markdown}`)
- .join("\n");
- return { auth, context: [`Recent thread messages since your last reply:\n\n${transcript}`] };
- },
+ threadContext: { since: "last-agent-reply" },
});
```
+`threadContext` performs one `conversations.replies` request for each triggering thread reply and requires the matching Slack history scope. Omit it when the agent should see only direct mentions. `loadThreadContextMessages` remains available when you need custom filtering or non-model processing of the raw thread messages.
+
### 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 tool status on `actions.requested`. 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.
diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.ts
index a747f73ff..f6c685c08 100644
--- a/packages/eve/src/channel/routes.ts
+++ b/packages/eve/src/channel/routes.ts
@@ -66,6 +66,11 @@ type BaseSendOptions = {
callback?: SessionCallback;
continuationToken: string;
mode?: RunMode;
+ /**
+ * Human-readable title for a newly started workflow session. Defaults to
+ * the first user message and is ignored when resuming an existing session.
+ */
+ title?: string;
};
/**
diff --git a/packages/eve/src/channel/send.test.ts b/packages/eve/src/channel/send.test.ts
index f826da885..74fe31d1f 100644
--- a/packages/eve/src/channel/send.test.ts
+++ b/packages/eve/src/channel/send.test.ts
@@ -216,4 +216,20 @@ describe("createSendFn", () => {
const runInput = vi.mocked(runtime.run).mock.calls[0]![0];
expect(runInput.adapter.state).toEqual({ channelId: "C1", threadTs: "T1" });
});
+
+ it("keeps an explicit workflow title separate from the model message", async () => {
+ const runtime = createRuntime(new RuntimeNoActiveSessionError("test:token"));
+ const send = createSendFn(runtime, ADAPTER, "test");
+ const message = "<slack_message>\n<content>ship it</content>\n</slack_message>";
+
+ await send(message, {
+ auth: null,
+ continuationToken: "token",
+ title: "ship it",
+ });
+
+ const runInput = vi.mocked(runtime.run).mock.calls[0]![0];
+ expect(runInput.input.message).toBe(message);
+ expect(runInput.title).toBe("ship it");
+ });
});
diff --git a/packages/eve/src/channel/send.ts b/packages/eve/src/channel/send.ts
index 0504b4a53..145907741 100644
--- a/packages/eve/src/channel/send.ts
+++ b/packages/eve/src/channel/send.ts
@@ -24,6 +24,7 @@ export function createSendFn<TState = undefined>(
const callback = (options as { callback?: SendOptions<TState>["callback"] }).callback;
const mode = (options as { mode?: SendOptions<TState>["mode"] }).mode ?? "conversation";
const state = (options as { state?: TState }).state;
+ const title = (options as { title?: string }).title;
const rawToken = (options as { continuationToken: string }).continuationToken;
const continuationToken = `${channelName}:${rawToken}`;
@@ -75,6 +76,7 @@ export function createSendFn<TState = undefined>(
input: { message: message ?? "", context, outputSchema },
mode,
requestId: metadata.requestId,
+ title,
};
const handle = await runtime.run(runInput);
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index b68d803b7..51ae1b143 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -240,6 +240,11 @@ export interface RunInput {
readonly capabilities?: SessionCapabilities;
/** Inbound channel request id used to correlate workflow attributes. */
readonly requestId?: string;
+ /**
+ * Human-readable workflow title for top-level sessions. When omitted, the
+ * runtime derives `$eve.title` from {@link input.message}.
+ */
+ readonly title?: string;
/**
* Optional terminal callback. When present, the runtime posts a single
* callback when the session completes or fails.
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index 87c64fea5..f15e4c185 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -189,6 +189,25 @@ describe("createWorkflowRuntime#run", () => {
);
});
+ it("uses an explicit title without changing the workflow model input", async () => {
+ const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
+ mockBundleAndRun(compiledArtifactsSource);
+ startMock.mockResolvedValue({ runId: "driver-run" });
+ const message = "<slack_message>\n<content>ship it</content>\n</slack_message>";
+
+ await buildRuntime(compiledArtifactsSource).run({
+ adapter,
+ auth: null,
+ input: { message },
+ mode: "conversation",
+ title: "ship it",
+ });
+
+ const [, workflowInput, startOptions] = startMock.mock.calls[0]!;
+ expect(workflowInput[0].input.message).toBe(message);
+ expect(startOptions.attributes["$eve.title"]).toBe("ship it");
+ });
+
it("serializes the channel request id into workflow context", async () => {
vi.stubEnv("VERCEL_ENV", "production");
const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index 431c486c6..10d1f3c16 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -105,7 +105,7 @@ export function createWorkflowRuntime(config: {
const attributes =
parentLineage.sessionId === undefined
? buildSessionAttributes({
- inputMessage: input.input.message,
+ inputMessage: input.title ?? input.input.message,
serializedContext,
})
: buildSubagentRootAttributes({
diff --git a/packages/eve/src/public/channels/slack/attachments.test.ts b/packages/eve/src/public/channels/slack/attachments.test.ts
index 619b42e6a..66f6a9645 100644
--- a/packages/eve/src/public/channels/slack/attachments.test.ts
+++ b/packages/eve/src/public/channels/slack/attachments.test.ts
@@ -271,7 +271,7 @@ describe("collectInboundFileParts", () => {
expect(refresh).not.toHaveBeenCalled();
});
- it("falls back to the latest non-bot thread message when the mention has no attachments", async () => {
+ it("reuses fetched thread messages when the mention has no attachments", async () => {
const refresh = vi.fn().mockResolvedValue(undefined);
const thread = makeSlackThread({
refresh,
@@ -298,7 +298,7 @@ describe("collectInboundFileParts", () => {
policy: DEFAULT_UPLOAD_POLICY,
});
- expect(refresh).toHaveBeenCalledOnce();
+ expect(refresh).not.toHaveBeenCalled();
expect(parts).toHaveLength(1);
expect((parts[0]!.data as URL).href).toBe("https://files.slack.com/a/b/earlier.csv");
});
diff --git a/packages/eve/src/public/channels/slack/attachments.ts b/packages/eve/src/public/channels/slack/attachments.ts
index 1ba387746..9c1c6fe24 100644
--- a/packages/eve/src/public/channels/slack/attachments.ts
+++ b/packages/eve/src/public/channels/slack/attachments.ts
@@ -90,11 +90,13 @@ export async function collectInboundFileParts(input: {
if (fromMention.length > 0) return fromMention;
if (isUploadsDisabled(input.policy)) return [];
- try {
- await input.thread.refresh();
- } catch (error) {
- log.warn("slack thread refresh failed for attachment collection", { error });
- return [];
+ if (input.thread.recentMessages.length === 0) {
+ try {
+ await input.thread.refresh();
+ } catch (error) {
+ log.warn("slack thread refresh failed for attachment collection", { error });
+ return [];
+ }
}
const recent = input.thread.recentMessages;
diff --git a/packages/eve/src/public/channels/slack/auth.ts b/packages/eve/src/public/channels/slack/auth.ts
index c8f6084ea..7674978c0 100644
--- a/packages/eve/src/public/channels/slack/auth.ts
+++ b/packages/eve/src/public/channels/slack/auth.ts
@@ -10,6 +10,13 @@ interface SlackAuthContextInput {
readonly userName?: string;
}
+/** Returns the Slack user id carried by a Slack-derived auth context. */
+export function slackUserIdFromAuthContext(auth: SessionAuthContext | null): string | undefined {
+ if (auth?.authenticator !== "slack-webhook") return undefined;
+ const userId = auth.attributes.user_id;
+ return typeof userId === "string" && userId.length > 0 ? userId : undefined;
+}
+
/**
* Builds the Slack-derived session auth context used by inbound
* messages and signed interactivity callbacks.
diff --git a/packages/eve/src/public/channels/slack/defaults.test.ts b/packages/eve/src/public/channels/slack/defaults.test.ts
index c96bffce5..80a8afb3b 100644
--- a/packages/eve/src/public/channels/slack/defaults.test.ts
+++ b/packages/eve/src/public/channels/slack/defaults.test.ts
@@ -4,7 +4,21 @@ import type { SessionContext } from "#public/definitions/callback-context.js";
import { defaultEvents } from "#public/channels/slack/defaults.js";
import type { SlackChannelState, SlackEventContext } from "#public/channels/slack/slackChannel.js";
-const sessionCtx = {} as SessionContext;
+function sessionContext(
+ current: SessionContext["session"]["auth"]["current"] = null,
+): SessionContext {
+ return {
+ getSandbox: vi.fn(),
+ getSkill: vi.fn(),
+ session: {
+ auth: { current, initiator: null },
+ id: "test-session",
+ turn: { id: "test-turn", sequence: 0 },
+ },
+ };
+}
+
+const sessionCtx = sessionContext();
function buildChannelStub(state: Partial<SlackChannelState> = {}) {
const postEphemeral = vi.fn().mockResolvedValue({ id: "eph1" });
@@ -53,6 +67,20 @@ describe("defaultEvents authorization.required", () => {
expect(channel.state.pendingAuthMessageTs).toEqual({ notion: "ts1" });
});
+ it("targets the current Slack caller instead of stale channel state", async () => {
+ const { channel, postEphemeral } = buildChannelStub({ triggeringUserId: "U_FIRST" });
+ const currentCaller = sessionContext({
+ attributes: { user_id: "U_CURRENT" },
+ authenticator: "slack-webhook",
+ principalId: "slack:T01:U_CURRENT",
+ principalType: "user",
+ });
+
+ await defaultEvents["authorization.required"]!(authRequiredEvent(), channel, currentCaller);
+
+ expect(postEphemeral.mock.calls[0]?.[0]).toBe("U_CURRENT");
+ });
+
it("renders the device user code in the ephemeral blocks and fallback text", async () => {
const { channel, postEphemeral } = buildChannelStub({ triggeringUserId: "U777" });
diff --git a/packages/eve/src/public/channels/slack/defaults.ts b/packages/eve/src/public/channels/slack/defaults.ts
index 4cb38f02b..8e97587f0 100644
--- a/packages/eve/src/public/channels/slack/defaults.ts
+++ b/packages/eve/src/public/channels/slack/defaults.ts
@@ -1,7 +1,7 @@
import type { SessionAuthContext } from "#channel/types.js";
import { createLogger, extractErrorId, formatErrorHint } from "#internal/logging.js";
-import { buildSlackAuthContext } from "#public/channels/slack/auth.js";
+import { buildSlackAuthContext, slackUserIdFromAuthContext } from "#public/channels/slack/auth.js";
import {
buildAuthCompletedText,
buildAuthEphemeralBlocks,
@@ -195,9 +195,12 @@ export const defaultEvents: SlackChannelInternalEvents = {
);
},
- async "authorization.required"(event, channel, _ctx) {
+ async "authorization.required"(event, channel, ctx) {
const displayName = event.authorization?.displayName ?? formatConnectionDisplayName(event.name);
- const triggeringUserId = channel.state.triggeringUserId ?? null;
+ const triggeringUserId =
+ slackUserIdFromAuthContext(ctx.session.auth.current) ??
+ channel.state.triggeringUserId ??
+ null;
const challengeUrl = event.authorization?.url;
// Post a public, link-free status so everyone in the thread can see
diff --git a/packages/eve/src/public/channels/slack/inbound.test.ts b/packages/eve/src/public/channels/slack/inbound.test.ts
index 69175d172..447414aeb 100644
--- a/packages/eve/src/public/channels/slack/inbound.test.ts
+++ b/packages/eve/src/public/channels/slack/inbound.test.ts
@@ -1,20 +1,6 @@
import { describe, expect, it } from "vitest";
-import {
- formatSlackContextBlock,
- parseAppMentionEvent,
- parseDirectMessageEvent,
- type SlackInboundContext,
-} from "#public/channels/slack/inbound.js";
-
-const FULL_CONTEXT: SlackInboundContext = {
- channelId: "C01",
- fullName: "Jane Smith",
- teamId: "T01",
- threadTs: "1700000000.000001",
- userId: "U01",
- userName: "jane.smith",
-};
+import { parseAppMentionEvent, parseDirectMessageEvent } from "#public/channels/slack/inbound.js";
describe("parseAppMentionEvent", () => {
it("returns a SlackMessage with mrkdwn re-rendered as GFM", () => {
@@ -276,28 +262,3 @@ describe("parseDirectMessageEvent", () => {
expect(result).toBeNull();
});
});
-
-describe("formatSlackContextBlock", () => {
- it("renders every available field between tag delimiters", () => {
- const block = formatSlackContextBlock(FULL_CONTEXT);
- expect(block.startsWith("<slack_context>")).toBe(true);
- expect(block.endsWith("</slack_context>")).toBe(true);
- expect(block).toContain("user_id: U01");
- expect(block).toContain("user_name: jane.smith");
- expect(block).toContain("full_name: Jane Smith");
- expect(block).toContain("channel_id: C01");
- expect(block).toContain("thread_ts: 1700000000.000001");
- expect(block).toContain("team_id: T01");
- });
-
- it("omits optional fields that are not supplied", () => {
- const block = formatSlackContextBlock({
- channelId: "C01",
- threadTs: "1.0",
- userId: "U01",
- });
- expect(block).not.toContain("user_name");
- expect(block).not.toContain("full_name");
- expect(block).not.toContain("team_id");
- });
-});
diff --git a/packages/eve/src/public/channels/slack/inbound.ts b/packages/eve/src/public/channels/slack/inbound.ts
index e4a57ad3d..65f2d813e 100644
--- a/packages/eve/src/public/channels/slack/inbound.ts
+++ b/packages/eve/src/public/channels/slack/inbound.ts
@@ -8,10 +8,9 @@
* a channel-owned {@link SlackMessage}, with the body's text already
* re-rendered as GFM markdown so the agent does not see raw
* `<@U…>` / `<https://…|…>` fragments.
- * 2. {@link formatSlackContextBlock} renders a `<slack_context>` block
- * naming the actor, channel, and thread. The channel delivers it as
- * a dedicated context entry so the agent always knows who and where
- * it is talking.
+ * 2. The channel renders the actor, message, channel, and thread as one
+ * attributed model message so speaker identity cannot drift away from
+ * the content it describes.
*/
import { slackMrkdwnToGfm } from "#public/channels/slack/mrkdwn.js";
@@ -232,7 +231,7 @@ function inferAttachmentType(mimeType: string | undefined): "image" | "file" | "
}
/**
- * Verified inbound identity used to render a `<slack_context>` block.
+ * Verified inbound identity used to attribute a model-visible Slack message.
*
* Channel-owned shape so the helper does not depend on the inbound
* `SlackMessage` and is therefore trivially testable in isolation.
@@ -245,22 +244,3 @@ export interface SlackInboundContext {
readonly threadTs: string;
readonly teamId?: string;
}
-
-/**
- * Renders one {@link SlackInboundContext} as a `<slack_context>` block.
- * Lines are deterministic and tag-delimited so the agent can match the
- * block in its prompt.
- */
-export function formatSlackContextBlock(context: SlackInboundContext): string {
- const lines = [
- "<slack_context>",
- `user_id: ${context.userId}`,
- ...(context.userName ? [`user_name: ${context.userName}`] : []),
- ...(context.fullName ? [`full_name: ${context.fullName}`] : []),
- `channel_id: ${context.channelId}`,
- `thread_ts: ${context.threadTs}`,
- ...(context.teamId ? [`team_id: ${context.teamId}`] : []),
- "</slack_context>",
- ];
- return lines.join("\n");
-}
diff --git a/packages/eve/src/public/channels/slack/model-context.test.ts b/packages/eve/src/public/channels/slack/model-context.test.ts
new file mode 100644
index 000000000..ab11a12eb
--- /dev/null
+++ b/packages/eve/src/public/channels/slack/model-context.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from "vitest";
+
+import type { SlackThreadMessage } from "#public/channels/slack/api.js";
+import {
+ formatSlackInboundMessage,
+ formatSlackThreadContext,
+} from "#public/channels/slack/model-context.js";
+
+function threadMessage(input: {
+ readonly botId?: string;
+ readonly isMe?: boolean;
+ readonly text: string;
+ readonly ts: string;
+ readonly user?: string;
+}): SlackThreadMessage {
+ return {
+ botId: input.botId,
+ isMe: input.isMe ?? false,
+ markdown: input.text,
+ raw: {},
+ text: input.text,
+ threadTs: "1700000000.000001",
+ ts: input.ts,
+ user: input.user,
+ };
+}
+
+describe("Slack model context", () => {
+ it("keeps the triggering sender id and content in one attributed message", () => {
+ const block = formatSlackInboundMessage(
+ {
+ channelId: "C01",
+ teamId: "T01",
+ threadTs: "1700000000.000001",
+ userId: "U_CURRENT",
+ },
+ {
+ markdown: "Who owns the deploy?",
+ ts: "1700000000.000004",
+ },
+ );
+
+ expect(block).toBe(
+ [
+ "<slack_message>",
+ "sender_type: user",
+ "sender_id: U_CURRENT",
+ "channel_id: C01",
+ "thread_ts: 1700000000.000001",
+ "message_ts: 1700000000.000004",
+ "team_id: T01",
+ "<content>",
+ "Who owns the deploy?",
+ "</content>",
+ "</slack_message>",
+ ].join("\n"),
+ );
+ });
+
+ it("attributes every fetched thread message by stable Slack id", () => {
+ const block = formatSlackThreadContext([
+ threadMessage({ text: "I own the API.", ts: "1.1", user: "U_BACKEND" }),
+ threadMessage({ text: "I own the UI.", ts: "1.2", user: "U_FRONTEND" }),
+ threadMessage({ botId: "B_AGENT", isMe: true, text: "Noted.", ts: "1.3" }),
+ ]);
+
+ expect(block).toContain("sender_id: U_BACKEND");
+ expect(block).toContain("sender_id: U_FRONTEND");
+ expect(block).toContain("sender_type: agent");
+ expect(block).toContain("sender_id: B_AGENT");
+ expect(block).toContain("I own the API.");
+ expect(block).toContain("I own the UI.");
+ });
+
+ it("omits empty thread context", () => {
+ expect(formatSlackThreadContext([])).toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/public/channels/slack/model-context.ts b/packages/eve/src/public/channels/slack/model-context.ts
new file mode 100644
index 000000000..2cb47020f
--- /dev/null
+++ b/packages/eve/src/public/channels/slack/model-context.ts
@@ -0,0 +1,80 @@
+import type { SlackThreadMessage } from "#public/channels/slack/api.js";
+import type { SlackInboundContext } from "#public/channels/slack/inbound.js";
+
+interface SlackModelMessageInput {
+ readonly channelId?: string;
+ readonly content: string;
+ readonly senderId?: string;
+ readonly senderType: "agent" | "bot" | "unknown" | "user";
+ readonly teamId?: string;
+ readonly threadTs: string;
+ readonly ts: string;
+}
+
+/**
+ * Renders one Slack message with its sender identity attached to the same
+ * model-visible message. Slack user ids are stable and require no profile
+ * lookup, so they remain the canonical speaker identity.
+ */
+export function formatSlackModelMessage(input: SlackModelMessageInput): string {
+ return [
+ "<slack_message>",
+ `sender_type: ${input.senderType}`,
+ ...(input.senderId ? [`sender_id: ${input.senderId}`] : []),
+ ...(input.channelId ? [`channel_id: ${input.channelId}`] : []),
+ `thread_ts: ${input.threadTs}`,
+ `message_ts: ${input.ts}`,
+ ...(input.teamId ? [`team_id: ${input.teamId}`] : []),
+ "<content>",
+ input.content,
+ "</content>",
+ "</slack_message>",
+ ].join("\n");
+}
+
+/** Renders the triggering inbound Slack message as one attributed block. */
+export function formatSlackInboundMessage(
+ context: SlackInboundContext,
+ message: { readonly markdown: string; readonly ts: string },
+): string {
+ return formatSlackModelMessage({
+ channelId: context.channelId,
+ content: message.markdown,
+ senderId: context.userId || undefined,
+ senderType: context.userId ? "user" : "unknown",
+ teamId: context.teamId,
+ threadTs: context.threadTs,
+ ts: message.ts,
+ });
+}
+
+/**
+ * Renders fetched Slack replies as explicitly attributed background context.
+ * Returns `undefined` when there are no messages to add to the turn.
+ */
+export function formatSlackThreadContext(
+ messages: readonly SlackThreadMessage[],
+): string | undefined {
+ if (messages.length === 0) return undefined;
+
+ return [
+ "<slack_thread_context>",
+ ...messages.map((message) =>
+ formatSlackModelMessage({
+ content: message.markdown,
+ senderId: message.user ?? message.botId,
+ senderType: slackThreadSenderType(message),
+ threadTs: message.threadTs,
+ ts: message.ts,
+ }),
+ ),
+ "</slack_thread_context>",
+ ].join("\n");
+}
+
+function slackThreadSenderType(message: SlackThreadMessage): SlackModelMessageInput["senderType"] {
+ if (message.isMe) return "agent";
+ if (message.botId) return "bot";
+ if (message.user) return "user";
+ return "unknown";
+}
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index 8e57b283b..bc892ec4e 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -163,25 +163,29 @@ let mentionCounter = 0;
function buildMentionBody(overrides?: {
channel?: string;
+ threadTs?: string;
ts?: string;
text?: string;
teamId?: string;
+ user?: string;
}): { body: string; channel: string; ts: string } {
mentionCounter += 1;
const channel = overrides?.channel ?? "C01";
const ts = overrides?.ts ?? `1700000000.${String(mentionCounter).padStart(6, "0")}`;
+ const event: Record<string, unknown> = {
+ type: "app_mention",
+ user: overrides?.user ?? "U01",
+ text: overrides?.text ?? "hello",
+ channel,
+ ts,
+ event_ts: ts,
+ };
+ if (overrides?.threadTs) event.thread_ts = overrides.threadTs;
const body = JSON.stringify({
type: "event_callback",
team_id: overrides?.teamId ?? "T01",
event_id: `Ev${mentionCounter}`,
- event: {
- type: "app_mention",
- user: "U01",
- text: overrides?.text ?? "hello",
- channel,
- ts,
- event_ts: ts,
- },
+ event,
});
return { body, channel, ts };
}
@@ -471,6 +475,44 @@ describe("slackChannel() default event handlers", () => {
});
});
+ it("refreshes triggeringUserId from the current Slack caller on every turn", async () => {
+ const onTurnStarted = vi.fn();
+ const adapter = withState(
+ getAdapter(
+ slackChannel({
+ events: { "turn.started": onTurnStarted },
+ }),
+ ),
+ { ...THREAD_STATE, triggeringUserId: "U_FIRST" },
+ );
+ const ctx = buildAdapterContext(adapter, stubAccessor());
+ const callerContext = new ContextContainer();
+ callerContext.setVirtualContext(SessionKey, {
+ sessionId: "test-session",
+ auth: {
+ current: {
+ attributes: { user_id: "U_CURRENT" },
+ authenticator: "slack-webhook",
+ principalId: "slack:T01:U_CURRENT",
+ principalType: "user",
+ },
+ initiator: null,
+ },
+ turn: { id: "test-turn", sequence: 1 },
+ });
+
+ await contextStorage.run(callerContext, () =>
+ callAdapterEventHandler(
+ adapter,
+ makeEvent("turn.started", { sequence: 1, stepIndex: 0, turnId: "t2" }),
+ ctx,
+ ),
+ );
+
+ expect(ctx.state.triggeringUserId).toBe("U_CURRENT");
+ expect(onTurnStarted).toHaveBeenCalledOnce();
+ });
+
it("reasoning.appended calls assistant.threads.setStatus with a truncated snippet", async () => {
const adapter = withState(
getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),
@@ -960,7 +1002,7 @@ describe("slackChannel() inbound mention pipeline", () => {
expect(second.send).not.toHaveBeenCalled();
});
- it("prepends the slack_context block before onAppMention context in send()", async () => {
+ it("keeps Slack attribution in the message and authored context separate", async () => {
const channel = slackChannel({
credentials: { botToken: "xoxb-test" },
onAppMention: () => ({ auth: null, context: ["prior thread context"] }),
@@ -971,15 +1013,14 @@ describe("slackChannel() inbound mention pipeline", () => {
expect(send).toHaveBeenCalledTimes(1);
const [payload] = send.mock.calls[0]!;
- const { context } = payload as { context: readonly string[] };
- expect(context).toHaveLength(2);
- expect(context[0]).toContain("<slack_context>");
- expect(context[0]).toContain("user_id: U01");
- expect(context[1]).toBe("prior thread context");
- expect((payload as { message?: unknown }).message).toBeDefined();
+ const { context, message } = payload as { context: readonly string[]; message: string };
+ expect(context).toEqual(["prior thread context"]);
+ expect(message).toContain("<slack_message>");
+ expect(message).toContain("sender_id: U01");
+ expect(message).toContain("<content>\nhello\n</content>");
});
- it("delivers the slack_context block even when onAppMention returns no context", async () => {
+ it("attributes the inbound message without adding a separate context entry", async () => {
const channel = slackChannel({
credentials: { botToken: "xoxb-test" },
onAppMention: () => ({ auth: null }),
@@ -989,10 +1030,84 @@ describe("slackChannel() inbound mention pipeline", () => {
const { send } = await firePost(channel, buildSignedRequest({ body }));
expect(send).toHaveBeenCalledTimes(1);
- const [payload] = send.mock.calls[0]!;
- const { context } = payload as { context: readonly string[] };
- expect(context).toHaveLength(1);
- expect(context[0]).toContain("<slack_context>");
+ const [payload, options] = send.mock.calls[0]!;
+ const { context, message } = payload as { context?: readonly string[]; message: string };
+ expect(context).toBeUndefined();
+ expect(message).toContain("sender_id: U01");
+ expect(message).toContain("message_ts:");
+ expect(options.title).toBe("hello");
+ });
+
+ it("adds one ID-attributed thread transcript without extra profile lookups", async () => {
+ const threadTs = "1700000000.000001";
+ const currentTs = "1700000000.000005";
+ fetchMock.mockImplementation(async (request: string | URL | Request) => {
+ const url = String(request);
+ if (url.includes("conversations.replies")) {
+ return new Response(
+ JSON.stringify({
+ ok: true,
+ messages: [
+ { user: "U_ROOT", text: "root", ts: threadTs, thread_ts: threadTs },
+ {
+ bot_id: "B_AGENT",
+ text: "What changed?",
+ ts: "1700000000.000002",
+ thread_ts: threadTs,
+ },
+ {
+ user: "U_BACKEND",
+ text: "I changed the API.",
+ ts: "1700000000.000003",
+ thread_ts: threadTs,
+ },
+ {
+ user: "U_FRONTEND",
+ text: "I changed the UI.",
+ ts: "1700000000.000004",
+ thread_ts: threadTs,
+ },
+ {
+ user: "U_CURRENT",
+ text: "Summarize ownership.",
+ ts: currentTs,
+ thread_ts: threadTs,
+ },
+ ],
+ }),
+ { headers: { "content-type": "application/json" } },
+ );
+ }
+ return new Response(JSON.stringify({ ok: true, ts: "1700000001.000001" }), {
+ headers: { "content-type": "application/json" },
+ });
+ });
+ const channel = slackChannel({
+ credentials: { botToken: "xoxb-test" },
+ onAppMention: () => ({ auth: null }),
+ threadContext: { since: "last-agent-reply" },
+ });
+ const { body } = buildMentionBody({
+ threadTs,
+ ts: currentTs,
+ text: "Summarize ownership.",
+ user: "U_CURRENT",
+ });
+
+ const { send } = await firePost(channel, buildSignedRequest({ body }));
+
+ const [{ message }] = send.mock.calls[0]! as [{ message: string }];
+ expect(message).toContain("<slack_thread_context>");
+ expect(message).toContain("sender_id: U_BACKEND");
+ expect(message).toContain("sender_id: U_FRONTEND");
+ expect(message).toContain("sender_id: U_CURRENT");
+ expect(message).not.toContain("sender_id: U_ROOT");
+ expect(
+ fetchMock.mock.calls.filter(([request]) => String(request).includes("conversations.replies")),
+ ).toHaveLength(1);
+ expect(fetchMock.mock.calls.some(([request]) => String(request).includes("users.info"))).toBe(
+ false,
+ );
});
it("does not dispatch when onAppMention resolves to null", async () => {
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index a54e3d126..93ec408df 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -25,13 +25,21 @@ import {
defaultOnDirectMessage,
} from "#public/channels/slack/defaults.js";
import {
- formatSlackContextBlock,
parseAppMentionEvent,
parseDirectMessageEvent,
type SlackEventCallback,
type SlackInboundContext,
type SlackMessage,
} from "#public/channels/slack/inbound.js";
+import {
+ formatSlackInboundMessage,
+ formatSlackThreadContext,
+} from "#public/channels/slack/model-context.js";
+import {
+ loadThreadContextMessages,
+ type LoadThreadContextMessagesOptions,
+} from "#public/channels/slack/thread.js";
+import { slackUserIdFromAuthContext } from "#public/channels/slack/auth.js";
import { SLACK_CHANNEL_DEFAULT_ROUTE } from "#public/channels/slack/constants.js";
import { handleInteractionPost } from "#public/channels/slack/interactions.js";
import {
@@ -373,6 +381,14 @@ export interface SlackChannelConfig {
*/
readonly uploadPolicy?: UploadPolicyInput;
+ /**
+ * Adds earlier replies from the current Slack thread to each triggering
+ * turn. Messages are rendered with their Slack sender ids attached so a
+ * multi-user transcript retains unambiguous speaker attribution. Omit this
+ * option to avoid fetching thread history.
+ */
+ readonly threadContext?: LoadThreadContextMessagesOptions;
+
/**
* Invoked when a Slack `app_mention` event arrives (only `app_mention`;
* other event types are ignored). Decides whether to dispatch and with
@@ -476,9 +492,17 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
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 = {
...defaultEvents,
...config.events,
+ async "turn.started"(data, channel, ctx) {
+ const triggeringUserId = slackUserIdFromAuthContext(ctx.session.auth.current);
+ if (triggeringUserId !== undefined) {
+ channel.state.triggeringUserId = triggeringUserId;
+ }
+ await turnStartedHandler(data, channel, ctx);
+ },
"input.requested": config.events?.["input.requested"] ?? defaultInputRequestedHandler(),
"authorization.required":
authorizationRequiredOverride === undefined
@@ -543,6 +567,7 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
onAppMention,
onDirectMessage,
uploadPolicy,
+ threadContext: config.threadContext,
handledEvents,
headers: req.headers,
credentials: config.credentials,
@@ -648,6 +673,7 @@ async function handleEventPost(input: {
readonly onAppMention: NonNullable<SlackChannelConfig["onAppMention"]>;
readonly onDirectMessage: NonNullable<SlackChannelConfig["onDirectMessage"]>;
readonly uploadPolicy: UploadPolicy;
+ readonly threadContext: LoadThreadContextMessagesOptions | undefined;
readonly credentials: SlackChannelCredentials | undefined;
readonly handledEvents: Set<string>;
}): Promise<Response> {
@@ -688,6 +714,7 @@ async function handleEventPost(input: {
handler: input.onAppMention,
send: input.send,
uploadPolicy: input.uploadPolicy,
+ threadContext: input.threadContext,
credentials: input.credentials,
}),
);
@@ -703,6 +730,7 @@ async function handleEventPost(input: {
handler: input.onDirectMessage,
send: input.send,
uploadPolicy: input.uploadPolicy,
+ threadContext: input.threadContext,
credentials: input.credentials,
}),
);
@@ -748,6 +776,7 @@ async function dispatchInboundMessage(input: {
| NonNullable<SlackChannelConfig["onDirectMessage"]>;
readonly send: SendFn<SlackChannelState>;
readonly uploadPolicy: UploadPolicy;
+ readonly threadContext: LoadThreadContextMessagesOptions | undefined;
readonly credentials: SlackChannelCredentials | undefined;
}): Promise<void> {
const { message, kind } = input;
@@ -771,12 +800,16 @@ async function dispatchInboundMessage(input: {
// This runs in the webhook's `waitUntil` task; an unguarded throw would
// reject silently into the dispatch `allSettled` ("no response, no logs").
try {
+ const priorMessages =
+ input.threadContext === undefined
+ ? []
+ : await loadThreadContextMessages(thread, message, input.threadContext);
+ const threadContext = formatSlackThreadContext(priorMessages);
const fileParts = await collectInboundFileParts({
mention: message,
thread,
policy: input.uploadPolicy,
});
- const turnMessage = buildSlackTurnMessage(message.markdown, fileParts);
const inboundContext: SlackInboundContext = {
channelId: message.channelId,
fullName: message.author?.fullName,
@@ -785,14 +818,18 @@ async function dispatchInboundMessage(input: {
userId: message.author?.userId ?? "",
userName: message.author?.userName,
};
+ const attributedMessage = formatSlackInboundMessage(inboundContext, message);
+ const turnMessage = buildSlackTurnMessage(
+ threadContext === undefined ? attributedMessage : `${threadContext}\n\n${attributedMessage}`,
+ fileParts,
+ );
const channelContext = result.context ?? [];
await input.send(
- {
- message: turnMessage,
- context: [formatSlackContextBlock(inboundContext), ...channelContext],
- },
+ channelContext.length === 0
+ ? { message: turnMessage }
+ : { message: turnMessage, context: channelContext },
{
auth: result.auth,
continuationToken: slackContinuationToken(message.channelId, message.threadTs),
@@ -802,6 +839,7 @@ async function dispatchInboundMessage(input: {
teamId: message.teamId ?? null,
triggeringUserId: inboundContext.userId || null,
},
+ title: message.markdown,
},
);
} catch (error) {