The Open Framework for Building Agents
Attach oversized Slack replies as Markdown files (#3228)
e0-gh-vercel-connect[bot]8c00b8e01deb
diff --git a/.changeset/calm-results-attach.md b/.changeset/calm-results-attach.mdnew file mode 100644index 000000000..371a0f557--- /dev/null+++ b/.changeset/calm-results-attach.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Upload Slack responses longer than the native Markdown limit as Markdown snippets. Preserve upload errors for channel error logging instead of replacing them with a generic notice.diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex e52c5bbb2..3215ede64 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -53,7 +53,7 @@ Use this fallback when the agent does not run on Vercel or Vercel Connect is unaThis option does not create or install the Slack app. Configure it in [Slack app settings](https://api.slack.com/apps):-1. Add the `app_mentions:read` and `chat:write` bot scopes. Add `im:history` for DMs, `files:read` for inbound attachments, and `files:write` when the agent uploads files.+1. Add the `app_mentions:read` and `chat:write` bot scopes. Add `im:history` for DMs, `files:read` for inbound attachments, and `files:write` for explicit uploads and automatic long-response snippets.2. Install or reinstall the app, copy its Bot User OAuth Token to `SLACK_BOT_TOKEN`, and copy the signing secret from **Basic Information** to `SLACK_SIGNING_SECRET`.3. Set both values in `.env.local` for local development or in the target runtime's environment, then start or deploy the agent at a public URL.4. Under **Event Subscriptions**, set the Request URL to `https://your-agent.example/eve/v1/slack`. Subscribe to `app_mention`, plus `message.im` for DMs.@@ -133,6 +133,7 @@ Check the delivery path in order so you can identify where a Slack event stops:| Setup says it could not remove an existing trigger destination | Check the connector's destinations in the Connect dashboard. `vercel connect detach` removes project token access, not trigger destinations. | Edit or remove the stale destination in the dashboard, then register `/eve/v1/slack` with `vercel connect attach`. || Mentions never reach the deployment | Confirm that the connector trigger destination uses the intended project and branch, enables triggers, and points to `/eve/v1/slack`. | Edit or remove stale destinations in the Connect dashboard, then register the intended destination with `vercel connect attach`. || Mentions work but DMs or thread replies do not | Check the Slack app's Event Subscriptions and OAuth scopes. DMs require `message.im` and `im:history`; channel replies require the matching message event and history scope. | Add the missing events or scopes, then reinstall the Slack app if Slack requires it. |+| A long response cannot be uploaded as a snippet | Check whether the installed Slack app has the `files:write` bot scope. | Add `files:write`, then reinstall the Slack app so the new scope takes effect. || A preview request receives an authentication page or protection error | Check whether the branch domain is exempt or the direct Slack request URL includes `x-vercel-protection-bypass`. Slack cannot complete an interactive Vercel Authentication challenge. | Add a Deployment Protection Exception for the branch domain, or add the automation bypass query parameter to a Slack app that uses environment-variable credentials. || The webhook reaches the deployment but the agent does not reply | Open the project's Vercel runtime logs, then inspect the session in **Agent Runs** when your team has access. | Use the first missing or failed stage to narrow the issue to channel dispatch, the agent run, or outbound Slack delivery. |@@ -414,11 +415,13 @@ when you need the bearer token itself.The default handlers reply in-thread and show activity. Typing indicators post automatically: `Thinking…` on inbound, `Working…` on `turn.started`, a truncated reasoning snippet on `reasoning.appended`, and an action label on `actions.requested` — the tool name plus its most telling argument (`grep useEveAgent`, `read_file agent/agent.ts`), the subagent or remote-agent name for dispatched calls, and `+N more` when the model requests several actions at once. The model's own pre-tool narration, when present, takes precedence over the derived label. Reasoning snippets build progressively: extensions of at least four characters appear immediately, while smaller streamed deltas use the five-second refresh interval to avoid one Slack request per token. Override `events["reasoning.appended"]` if you prefer generic wording. Override an inbound handler or the `events` handlers to customize.+The built-in `message.completed` handler renders responses up to 12,000 characters inline. Longer responses are uploaded unchanged as a Markdown snippet named `eve-response.md` with a short in-thread note, which requires the `files:write` bot scope. Upload failures are logged by the channel dispatcher; they do not trigger a model retry. An authored `events["message.completed"]` handler replaces this behavior and owns its own delivery limits.+Outbound text preserves bare `@` tokens as literal text. To mention a user, embed Slack's `<@USER_ID>` syntax directly or use `channel.thread.mentionUser(userId)`.When a session starts without a `threadTs` (say, from a schedule's `to(slack, target).send(...)`), eve gives it a unique temporary continuation token. The first agent post anchors the session to the Slack message timestamp, and later posts and mentions resume that same session. Pass `initialMessage` with a `Card` to land a structured anchor first instead. `threadTs` and `initialMessage` are mutually exclusive.-The example below overrides `onAppMention` to gate on an authored message and posts the completed reply to the thread. Event handlers receive `(eventData, channel, ctx)`, with Slack platform handles on `channel.thread` and `channel.slack`:+The example below overrides `onAppMention` to gate on an authored message. The built-in completion handler still posts the reply and uploads long responses as snippets. Event handlers receive `(eventData, channel, ctx)`, with Slack platform handles on `channel.thread` and `channel.slack`:```tsimport { defaultSlackAuth, slackChannel } from "eve/channels/slack";@@ -428,12 +431,6 @@ export default slackChannel({credentials: connectSlackCredentials("slack/my-agent"),onAppMention: (ctx, message) =>message.author ? { auth: defaultSlackAuth(message, ctx) } : null,- events: {- "message.completed"(eventData, channel, ctx) {- if (eventData.finishReason === "tool-calls") return;- if (eventData.message) channel.thread.post(eventData.message);- },- },});```diff --git a/packages/eve/src/public/channels/slack/api.ts b/packages/eve/src/public/channels/slack/api.tsindex 9a6b39e30..0755d9019 100644--- a/packages/eve/src/public/channels/slack/api.ts+++ b/packages/eve/src/public/channels/slack/api.ts@@ -173,6 +173,8 @@ export type SlackPostInput = SlackPostWithFiles &* thread.*/export interface SlackUploadFilesOptions {+ /** Upload as snippets with this Slack syntax type (for example, `markdown`). */+ readonly snippetType?: string;/** Override the channel id. Defaults to the binding's `channelId`. */readonly channelId?: string;/** Override the thread ts. Defaults to the binding's `threadTs`. */@@ -420,7 +422,8 @@ export function buildSlackBinding(input: {): Promise<SlackUploadFilesResult> {const channelId = options?.channelId ?? input.channelId;const threadTs = options?.threadTs ?? currentThreadTs;- return uploadSlackFiles(files.map(toSlackFileUpload), {+ const uploads = files.map((file) => toSlackFileUpload(file, options?.snippetType));+ return uploadSlackFiles(uploads, {...createSlackApiOptions(input.botToken, context),channelId: channelId || undefined,initialComment: options?.initialComment,@@ -648,10 +651,11 @@ function normalizeSlackApiBody(body: unknown): Record<string, unknown> {return {};}-function toSlackFileUpload(file: FileUpload): SlackFileUpload {+function toSlackFileUpload(file: FileUpload, snippetType?: string): SlackFileUpload {return {data: normalizeFileData(file.data),filename: file.filename,+ snippetType,};}diff --git a/packages/eve/src/public/channels/slack/defaults.ts b/packages/eve/src/public/channels/slack/defaults.tsindex d61a4f75c..34ddb77b0 100644--- a/packages/eve/src/public/channels/slack/defaults.ts+++ b/packages/eve/src/public/channels/slack/defaults.ts@@ -17,6 +17,7 @@ import {} from "#public/channels/slack/hitl.js";import type { SlackMessage } from "#public/channels/slack/inbound.js";import {+ SLACK_MARKDOWN_TEXT_MAX_LENGTH,SLACK_MAX_BLOCKS_PER_MESSAGE,truncateMessageText,truncateTypingStatus,@@ -33,6 +34,8 @@ import type { InputRequest } from "#shared/input.js";const log = createLogger("slack.defaults");const REASONING_TYPING_REFRESH_INTERVAL_MS = 5_000;const REASONING_TYPING_MIN_PROGRESS_CHARS = 4;+const LONG_RESPONSE_FILENAME = "eve-response.md";+const LONG_RESPONSE_NOTICE = "Here's a snippet with the full response.";interface ReasoningAccumulator {readonly stepIndex: number;readonly text: string;@@ -264,6 +267,40 @@ function groupInputRequestPostParts(}));}+/**+ * Delivers a completed default Slack reply without sending content that+ * exceeds Slack's native Markdown limit. Long replies stay intact as one+ * Markdown snippet instead of being truncated or split across messages.+ */+export async function postCompletedSlackReply(+ channel: SlackContext,+ message: string,+): Promise<void> {+ if (message.length <= SLACK_MARKDOWN_TEXT_MAX_LENGTH) {+ await channel.thread.post(message);+ return;+ }++ const file = {+ data: new Blob([message], { type: "text/markdown" }),+ filename: LONG_RESPONSE_FILENAME,+ mimeType: "text/markdown",+ };++ const hasThread = channel.slack.threadTs.length > 0;+ if (!hasThread) {+ // Uploads cannot anchor proactive sessions; post the notice first.+ const anchor = await channel.thread.post(LONG_RESPONSE_NOTICE);+ if (!anchor.id || channel.slack.threadTs.length === 0) {+ throw new Error("Slack did not return a thread timestamp for the long response notice.");+ }+ }+ await channel.slack.uploadFiles([file], {+ initialComment: hasThread ? LONG_RESPONSE_NOTICE : undefined,+ snippetType: "markdown",+ });+}+/*** Built-in Slack event handlers — typing indicators, error replies,* and the connection-authorization status flow. Each is overridable@@ -398,7 +435,7 @@ export const defaultEvents: SlackChannelInternalEvents = {await channel.thread.startTyping();return;}- await channel.thread.post(event.message);+ await postCompletedSlackReply(channel, event.message);},async "turn.failed"(event, channel, _ctx) {diff --git a/packages/eve/src/public/channels/slack/limits.ts b/packages/eve/src/public/channels/slack/limits.tsindex d8b21cf6e..2e4766af1 100644--- a/packages/eve/src/public/channels/slack/limits.ts+++ b/packages/eve/src/public/channels/slack/limits.ts@@ -44,6 +44,13 @@ export const SLACK_CARD_SUBTEXT_MAX_LENGTH = 200;*/export const SLACK_MESSAGE_TEXT_MAX_LENGTH = 40000;+/**+ * Slack's native `markdown_text` field on `chat.postMessage` is capped at+ * 12000 characters. Default agent replies use this field so headings, tables,+ * and other Markdown render natively.+ */+export const SLACK_MARKDOWN_TEXT_MAX_LENGTH = 12000;+/*** `chat.postMessage` rejects payloads with more than 50 blocks* (`invalid_blocks`).diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.tsindex 86d6eb022..25ac1f57a 100644--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts@@ -15,6 +15,7 @@ import {type ObservedChannelDelivery,} from "#internal/testing/mocks/mock-channel-operations.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";+import { experimental_slackActivityStatus } from "#public/channels/slack/activity.js";import { decodeSlackApiBody } from "#public/channels/slack/api-encoding.js";import {HITL_ACTION_PREFIX,@@ -25,6 +26,7 @@ import {} from "#public/channels/slack/hitl.js";import {SLACK_CARD_BODY_TEXT_MAX_LENGTH,+ SLACK_MARKDOWN_TEXT_MAX_LENGTH,SLACK_MAX_BLOCKS_PER_MESSAGE,SLACK_MESSAGE_TEXT_MAX_LENGTH,SLACK_SECTION_TEXT_MAX_LENGTH,@@ -85,6 +87,42 @@ function parseSlackRequestBody(init: RequestInit | undefined): Record<string, unreturn decodeSlackApiBody(init.body, contentType) as Record<string, unknown>;}+function useSuccessfulSlackFileUpload(+ fetchMock: ReturnType<typeof vi.fn>,+ postTs = "1700000001.000001",+): string[] {+ const uploadedBodies: string[] = [];+ fetchMock.mockImplementation(async (input: string | URL | Request, init?: RequestInit) => {+ const url = String(input);+ if (url === "https://slack.com/api/chat.postMessage") {+ return new Response(JSON.stringify({ ok: true, ts: postTs }), {+ headers: { "content-type": "application/json" },+ });+ }+ if (url === "https://slack.com/api/files.getUploadURLExternal") {+ return new Response(+ JSON.stringify({+ file_id: "F01",+ ok: true,+ upload_url: "https://files.slack.com/upload/F01",+ }),+ { headers: { "content-type": "application/json" } },+ );+ }+ if (url === "https://files.slack.com/upload/F01") {+ uploadedBodies.push(await new Response(init?.body ?? null).text());+ return new Response("OK");+ }+ if (url === "https://slack.com/api/files.completeUploadExternal") {+ return new Response(JSON.stringify({ files: [{ id: "F01" }], ok: true }), {+ headers: { "content-type": "application/json" },+ });+ }+ throw new Error(`Unexpected Slack request: ${url}`);+ });+ return uploadedBodies;+}+function withState(adapter: ChannelAdapter<any>,state: Record<string, unknown>,@@ -114,6 +152,15 @@ function callEvent(return contextStorage.run(stubAlsContext, () => callAdapterEventHandler(adapter, event, ctx));}+function callCompletionHandler(+ adapter: ChannelAdapter,+ event: UnstampedMessageStreamEvent,+ ctx: any,+) {+ if (event.type !== "message.completed") throw new Error("Expected message.completed");+ return contextStorage.run(stubAlsContext, () => adapter["message.completed"]!(event.data, ctx));+}+/*** Accessor whose `set` writes are captured so tests can assert on* `continuation.rekey` flowing through the SessionHandle. Returns@@ -436,6 +483,150 @@ describe("slackChannel() default event handlers", () => {});});+ it("message.completed keeps a reply at the Markdown limit inline", async () => {+ const adapter = withState(+ getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),+ THREAD_STATE,+ );+ const ctx = buildAdapterContext(adapter, stubAccessor());+ const message = "x".repeat(SLACK_MARKDOWN_TEXT_MAX_LENGTH);++ await callEvent(+ adapter,+ makeEvent("message.completed", {+ finishReason: "stop",+ message,+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ }),+ ctx,+ );++ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(String(fetchMock.mock.calls[0]![0])).toBe("https://slack.com/api/chat.postMessage");+ expect(parseSlackRequestBody(fetchMock.mock.calls[0]![1] as RequestInit)).toMatchObject({+ markdown_text: message,+ });+ });++ it("message.completed uploads an oversized reply as a Markdown snippet", async () => {+ const uploadedBodies = useSuccessfulSlackFileUpload(fetchMock);+ const adapter = withState(+ getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),+ THREAD_STATE,+ );+ const ctx = buildAdapterContext(adapter, stubAccessor());+ const message = `# Changelog\n\n${"é🦊".repeat(SLACK_MARKDOWN_TEXT_MAX_LENGTH)}`;++ await callEvent(+ adapter,+ makeEvent("message.completed", {+ finishReason: "stop",+ message,+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ }),+ ctx,+ );++ const urls = fetchMock.mock.calls.map(([input]) => String(input));+ expect(urls).toEqual([+ "https://slack.com/api/files.getUploadURLExternal",+ "https://files.slack.com/upload/F01",+ "https://slack.com/api/files.completeUploadExternal",+ ]);+ expect(uploadedBodies).toEqual([message]);+ expect(parseSlackRequestBody(fetchMock.mock.calls[0]![1] as RequestInit)).toMatchObject({+ filename: "eve-response.md",+ snippet_type: "markdown",+ length: String(new TextEncoder().encode(message).byteLength),+ });+ expect(parseSlackRequestBody(fetchMock.mock.calls[2]![1] as RequestInit)).toMatchObject({+ channel_id: "C01",+ files: [{ id: "F01", title: "eve-response.md" }],+ initial_comment: "Here's a snippet with the full response.",+ thread_ts: "1700000000.000001",+ });+ });++ it.each([+ ["files.getUploadURLExternal", "missing_scope"],+ ["files.completeUploadExternal", "channel_not_found"],+ ])("message.completed propagates %s failure", async (method, error) => {+ useSuccessfulSlackFileUpload(fetchMock);+ const successfulFetch = fetchMock.getMockImplementation() as typeof fetch;+ fetchMock.mockImplementation(async (input: string | URL | Request) => {+ const url = String(input);+ if (url === `https://slack.com/api/${method}`) {+ return new Response(JSON.stringify({ error, ok: false }), {+ headers: { "content-type": "application/json" },+ });+ }+ if (url === "https://slack.com/api/chat.postMessage") {+ return new Response(JSON.stringify({ ok: true, ts: "1700000001.000001" }), {+ headers: { "content-type": "application/json" },+ });+ }+ return successfulFetch(input);+ });+ const adapter = withState(+ getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),+ THREAD_STATE,+ );+ const ctx = buildAdapterContext(adapter, stubAccessor());+ const message = "x".repeat(SLACK_MARKDOWN_TEXT_MAX_LENGTH + 1);++ await expect(+ callCompletionHandler(+ adapter,+ makeEvent("message.completed", {+ finishReason: "stop",+ message,+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ }),+ ctx,+ ),+ ).rejects.toThrow(error);++ expect(fetchMock).toHaveBeenCalledTimes(method === "files.getUploadURLExternal" ? 1 : 3);+ });++ it("activity-owned message.completed uses the same oversized reply snippet", async () => {+ const uploadedBodies = useSuccessfulSlackFileUpload(fetchMock);+ const adapter = withState(+ getAdapter(+ slackChannel({+ activity: { renderers: [experimental_slackActivityStatus()] },+ credentials: { botToken: "xoxb-test" },+ }),+ ),+ THREAD_STATE,+ );+ const ctx = buildAdapterContext(adapter, stubAccessor());+ const message = "x".repeat(SLACK_MARKDOWN_TEXT_MAX_LENGTH + 1);++ await callEvent(+ adapter,+ makeEvent("message.completed", {+ finishReason: "stop",+ message,+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ }),+ ctx,+ );++ expect(uploadedBodies).toEqual([message]);+ expect(fetchMock.mock.calls.map(([input]) => String(input))).not.toContain(+ "https://slack.com/api/chat.postMessage",+ );+ });+it("message.completed skips post when finishReason is tool-calls", async () => {const adapter = withState(getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),@@ -1407,6 +1598,89 @@ describe("rebuildSlackContext", () => {const allTokenWrites = writes.filter(([key]) => key === "eve.continuationToken");expect(allTokenWrites).toHaveLength(1);});++ it("anchors a threadless session before uploading an oversized reply snippet", async () => {+ const fetchMock = vi.fn();+ const uploadedBodies = useSuccessfulSlackFileUpload(fetchMock, "1800000000.123456");+ vi.stubGlobal("fetch", fetchMock);+ const adapter = withState(+ getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),+ {+ channelId: "C01",+ threadTs: null,+ teamId: null,+ },+ );+ const { accessor, writes } = captureAccessor("slack:C01:");+ const ctx = buildAdapterContext(adapter, accessor);+ const message = "x".repeat(SLACK_MARKDOWN_TEXT_MAX_LENGTH + 1);++ await callEvent(+ adapter,+ makeEvent("message.completed", {+ finishReason: "stop",+ message,+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ }),+ ctx,+ );++ expect(uploadedBodies).toEqual([message]);+ const anchorBody = parseSlackRequestBody(fetchMock.mock.calls[0]![1] as RequestInit);+ expect(anchorBody).toMatchObject({+ channel: "C01",+ markdown_text: "Here's a snippet with the full response.",+ });+ expect(anchorBody.thread_ts).toBeUndefined();+ expect(parseSlackRequestBody(fetchMock.mock.calls[1]![1] as RequestInit)).toMatchObject({+ snippet_type: "markdown",+ });+ const completeBody = parseSlackRequestBody(fetchMock.mock.calls[3]![1] as RequestInit);+ expect(completeBody.thread_ts).toBe("1800000000.123456");+ expect(completeBody.initial_comment).toBeUndefined();+ expect((adapter.state as { threadTs: string | null }).threadTs).toBe("1800000000.123456");+ expect(writes.filter(([key]) => key === "eve.continuationToken")).toEqual([+ ["eve.continuationToken", "slack:C01:1800000000.123456"],+ ]);+ });++ it("does not upload a threadless reply when Slack omits the anchor timestamp", async () => {+ const fetchMock = vi.fn().mockImplementation(() =>+ Promise.resolve(+ new Response(JSON.stringify({ ok: true }), {+ headers: { "content-type": "application/json" },+ }),+ ),+ );+ vi.stubGlobal("fetch", fetchMock);+ const adapter = withState(+ getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),+ {+ channelId: "C01",+ threadTs: null,+ teamId: null,+ },+ );+ const ctx = buildAdapterContext(adapter, stubAccessor());++ await expect(+ callCompletionHandler(+ adapter,+ makeEvent("message.completed", {+ finishReason: "stop",+ message: "x".repeat(SLACK_MARKDOWN_TEXT_MAX_LENGTH + 1),+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ }),+ ctx,+ ),+ ).rejects.toThrow("Slack did not return a thread timestamp");++ expect(fetchMock).toHaveBeenCalledTimes(1);+ });});describe("defaultSlackAuth", () => {diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.tsindex e975d0198..c9c8562f6 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -36,6 +36,7 @@ import {defaultInputRequestedHandler,defaultOnAppMention,defaultOnDirectMessage,+ postCompletedSlackReply,} from "#public/channels/slack/defaults.js";import {parseMessageEvent,@@ -767,7 +768,7 @@ const activityOwnedMessageCompleted: NonNullable<SlackChannelEvents["message.com) => {channel.state.pendingToolCallMessage = null;if (event.finishReason !== "tool-calls" && event.message) {- await channel.thread.post(event.message);+ await postCompletedSlackReply(channel, event.message);}};