chat / adapter-slack
AGENTS.md2.4k starsChanged 59 days agoMITView on GitHub
Guidance for coding agents working inside the Slack adapter package. The top-level repository AGENTS.md covers monorepo-wide build, lint, and release rules — read it first. This file documents the adapter-specific surface, conventions, and pitfalls. @chat-adapter/slack connects a Chat SDK bot to a Slack workspace. It covers: - HTTP webhook endpoint at /api/webhooks/slack (events, slash commands, interactivity, view submissions, block_suggestion options loads, OAuth callback dispatch). - Optional Socket Mode transport with a forwarding mechanism for serverless platforms (Vercel cron → transient…
- Reads credentials
- Deletes or force-pushes
Trending
Quiet since March.thin dataabout the whole repository
Who's talking about vercel/chat
- @camilleroux.com“Un SDK TypeScript unifié pour créer des chatbots qui fonctionnent sur Slack, Teams, Google Chat, Discord, …”Bluesky · Mar 3, 2026 · 3 likes
- @technews4869.bsky.social“github.com/vercel/chat GitHub - vercel/chat: A unified TypeScript SDK for building chat bots across Slack, …”Bluesky · Mar 7, 2026 · 1 likes
- @yug1224.com“チャットアプリ開発に使える統一SDKを提供するツールらしい 様々なプラットフォーム対応で便利そうだな yug1224 starred vercel/chat https://github.com/vercel/chat”Bluesky · Mar 7, 2026 · 1 likes
- @news.humancoders.com“Vercel lance Chat SDK : un SDK TypeScript unifié pour créer des bots multi-plateformes”Bluesky · Mar 5, 2026 · 1 likes
- @github-trending-js.bsky.social“🔥 Hot Repo! 🔥 (100+ new stars) 📦 vercel / chat ⭐ 871 (+121) 🗒 TypeScript A unified TypeScript SDK for …”Bluesky · Feb 27, 2026 · 1 likes
The biggest 5 of 5 mentions linking to the repository that our crawl found. Each line is their own headline.
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository44 other files it gives its agents.
- AGENTS.mdAGENTS.md
- apps/docs/AGENTS.mdAGENTS.md
- chat-sdkAGENTS.md
- packages/adapter-discord/AGENTS.mdAGENTS.md
- packages/adapter-gchat/AGENTS.mdAGENTS.md
- packages/adapter-github/AGENTS.mdAGENTS.md
- packages/adapter-instagram/AGENTS.mdAGENTS.md
- packages/adapter-linear/AGENTS.mdAGENTS.md
- packages/adapter-messenger/AGENTS.mdAGENTS.md
- packages/adapter-notion/AGENTS.mdAGENTS.md
- packages/adapter-teams/AGENTS.mdAGENTS.md
- packages/adapter-telegram/AGENTS.mdAGENTS.md
- packages/adapter-web/AGENTS.mdAGENTS.md
- packages/adapter-whatsapp/AGENTS.mdAGENTS.md
- packages/chat/src/adapters/AGENTS.mdAGENTS.md
- packages/create-chat-sdk/AGENTS.mdAGENTS.md
- packages/create-chat-sdk/_template/AGENTS.mdAGENTS.md
- packages/state-ioredis/AGENTS.mdAGENTS.md
- packages/state-memory/AGENTS.mdAGENTS.md
- packages/state-pg/AGENTS.mdAGENTS.md
- packages/state-redis/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- packages/adapter-discord/CLAUDE.mdCLAUDE.md
- packages/adapter-gchat/CLAUDE.mdCLAUDE.md
- packages/adapter-github/CLAUDE.mdCLAUDE.md
- packages/adapter-linear/CLAUDE.mdCLAUDE.md
- packages/adapter-messenger/CLAUDE.mdCLAUDE.md
- packages/adapter-slack/CLAUDE.mdCLAUDE.md
- packages/adapter-teams/CLAUDE.mdCLAUDE.md
- packages/adapter-telegram/CLAUDE.mdCLAUDE.md
- packages/adapter-web/CLAUDE.mdCLAUDE.md
- packages/adapter-whatsapp/CLAUDE.mdCLAUDE.md
- packages/create-chat-sdk/CLAUDE.mdCLAUDE.md
- packages/create-chat-sdk/_template/CLAUDE.mdCLAUDE.md
- packages/state-ioredis/CLAUDE.mdCLAUDE.md
- packages/state-memory/CLAUDE.mdCLAUDE.md
- packages/state-pg/CLAUDE.mdCLAUDE.md
- packages/state-redis/CLAUDE.mdCLAUDE.md
- add-adapterSkill
- technical-writerSkill
- chat-sdkSkill
- chat-sdkSkill
- chat-sdkSkill
- chat-sdkSkill
The file
We split this AGENTS.md into the rules it gives an agent
3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 206
When updating these converters, mirror changes in cards.ts so the fallback text on Block Kit blocks stays accurate.
- Very specific: line 331
When adding a feature, prefer extending an existing fixture in sample-messages.md rather than fabricating a payload from scratch.
- Very specific: line 336
All exports are export function, export const, or export class — no default exports.
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md — @chat-adapter/slack
Guidance for coding agents working inside the Slack adapter package. The top-level repository AGENTS.md covers monorepo-wide build, lint, and release rules — read it first. This file documents the adapter-specific surface, conventions, and pitfalls.
Overview
@chat-adapter/slack connects a Chat SDK bot to a Slack workspace. It
covers:
- HTTP webhook endpoint at
/api/webhooks/slack(events, slash commands, interactivity, view submissions, block_suggestion options loads, OAuth callback dispatch). - Optional Socket Mode transport with a forwarding mechanism for serverless platforms (Vercel cron → transient WebSocket → forwarded HTTP).
- Single-workspace bot tokens or multi-workspace OAuth (with token encryption-at-rest and an external installation provider hook).
- Block Kit rendering for cards, modals, ephemeral messages, slash commands, scheduled messages, file uploads, and the Slack Assistants API.
- Native streaming via
chat.startStream/chat.appendStream/chat.stopStream(including structured task/plan chunks), with an automatic post-and-edit fallback for threads without streaming context and Slack flavours without the streaming methods (e.g. GovSlack; alsonativeStreaming: false).
The adapter is the first Chat SDK target and the most fully-featured —
several conventions in packages/chat were originally shaped here.
Directory layout
packages/adapter-slack/
├── src/
│ ├── index.ts # SlackAdapter class + createSlackAdapter factory
│ ├── index.test.ts # unit tests for adapter behaviour
│ ├── cards.ts # PostableMessage / Card → Block Kit
│ ├── cards.test.ts
│ ├── crypto.ts # AES-256-GCM bot token encryption helpers
│ ├── crypto.test.ts
│ ├── markdown.ts # SlackFormatConverter (mdast ↔ mrkdwn)
│ ├── markdown.test.ts
│ ├── modals.ts # Modal element conversion + view metadata
│ └── modals.test.ts
├── sample-messages.md # real webhook payloads used as fixtures
├── package.json
├── tsconfig.json
├── tsup.config.ts # ESM bundle config
├── vitest.config.ts
└── README.md # user-facing quick startsample-messages.md is a curated set of real webhook payloads — extend
it whenever you fix a parser bug or add support for a new event so the
fixture corpus stays representative.
Build, test, typecheck
# from the package directory
pnpm build # tsup ESM bundle → dist/
pnpm dev # tsup --watch
pnpm test # vitest run --coverage
pnpm test:watch # vitest interactive
pnpm typecheck # tsc --noEmit
pnpm clean # rm -rf dist
# from the repo root
pnpm --filter @chat-adapter/slack build
pnpm --filter @chat-adapter/slack testTests in this package are pure unit tests (Vitest). Integration tests
that hit the real Slack API live in
packages/integration-tests/src/slack.test.ts and replay tests live in
packages/integration-tests/src/replay-*.test.ts — both run against
recorded fixtures, so they don't need workspace credentials.
Public surface
The package's main exports (see src/index.ts):
createSlackAdapter(config?)— primary factory. Auto-detectsSLACK_BOT_TOKEN,SLACK_SIGNING_SECRET,SLACK_APP_TOKEN,SLACK_CLIENT_ID,SLACK_CLIENT_SECRET,SLACK_ENCRYPTION_KEY. When any auth-related field is passed explicitly, env-fallback for the remaining auth fields is disabled to prevent accidental mode mixing.SlackAdapterclass — implements the Chat SDKAdapter<SlackThreadId, unknown>interface. Public methods includehandleWebhook,postMessage,editMessage,deleteMessage,addReaction,removeReaction,startTyping,openModal,getInstallation,setInstallation,deleteInstallation,handleOAuthCallback,withBotToken,setSuggestedPrompts,setAssistantStatus,setSessionStatus,setAssistantTitle,publishHomeView,startSocketModeListener.SlackAdapterConfig,SlackBotToken,SlackInstallation,SlackThreadId,SlackEvent,SlackReactionEvent,SlackAdapterMode,SlackOAuthCallbackOptions— configuration and event types.cardToBlockKit,cardToFallbackText— exposed for advanced users who need to render Block Kit outside the adapter.decodeKey,EncryptedTokenData— encryption helpers for callers that manage installations themselves.
Thread ID format
slack:{channelId}:{threadTs}channelId is the Slack channel (C… / G… / D…), threadTs is the
parent message timestamp with the dot intact (e.g.
1234567890.123456). The adapter exposes encodeThreadId /
decodeThreadId so other code can build IDs without string
concatenation.
For Slack Assistants API events, the parent message timestamp is the assistant thread root — same encoding applies.
Webhook flow
SlackAdapter.handleWebhook(request, options) is the single entry point
the chat instance routes Slack traffic through. It dispatches based on
the Slack event envelope:
- Verification — verify the
X-Slack-SignatureHMAC against the raw body usingsigningSecret, or call the user-suppliedwebhookVerifierif configured. Both checks use a constant-time string comparison vianode:crypto.timingSafeEqual. - Body type — JSON for events / view submissions / OAuth, URL-form for slash commands and interactive payloads.
- Routing
event_callback→handleSlackEvent→chat.handleIncomingMessage(or one of the assistant-thread / reaction / channel-join handlers).view_submission,view_closed→ modal lifecycle.block_actions→chat.handleAction.block_suggestion→chat.handleOptionsLoad(3 s SLA, hard timeout at 2.5 s — seeOPTIONS_LOAD_TIMEOUT_MS).slash_command→chat.handleSlashCommand.
waitUntil— long-running side effects (unfurl polling, AI streaming, modal pushes after the response) are scheduled via thewaitUntilprovided by the host (next/serverafter,@vercel/functionswaitUntil, or a custom shim).
Authentication modes
Single-workspace
Bot token (xoxb-…) + signing secret. The adapter uses the bot token
directly for every API call and does not touch the state adapter.
Multi-workspace OAuth
Provide clientId + clientSecret and an OAuth redirect URL that
calls adapter.handleOAuthCallback(request, { redirectUri }). The
adapter:
- Exchanges the auth code via
oauth.v2.access. - Persists the resulting
SlackInstallation(bot token, scopes, team metadata, optional enterprise metadata) in the configured state adapter under{installationKeyPrefix}:{teamId}(or:{enterpriseId}for org-wide installs). - Encrypts the bot token with AES-256-GCM if
encryptionKeyis set.
Token rotation
botToken accepts either a string or () => string | Promise<string>.
The function is invoked per API call, so it composes naturally with
Slack token rotation (12-hour TTL) or lazy fetches from a secret
manager. Cache inside the resolver if the lookup is expensive.
withBotToken
AsyncLocalStorage is used to scope a bot token for a callback so
out-of-webhook code (cron jobs, queues) can post to a specific
workspace without mutating adapter state. Always wrap such code in
adapter.withBotToken(install.botToken, async () => { … }).
External installation provider
installationProvider.getInstallation is read-only and bypasses the
state adapter for token resolution. setInstallation,
deleteInstallation, and handleOAuthCallback continue to write to
the internal state adapter, so external providers must export those
writes themselves if they need to round-trip them.
Format conversion
SlackFormatConverter (in markdown.ts) implements:
toAst(text)— Slack mrkdwn → mdast. Handles<@U…>,<#C…>,<!subteam^…>, link/email syntax (<url|label>), bold (*…*), italic (_…_), strike (~…~), inline code, code fences, and blockquotes. Mentions resolve via theusers.info/usergroups.listcalls keyed by user-info cache to avoid round-trips.fromAst(ast)— mdast → mrkdwn. Lists, blockquotes, inline emphasis, links and code blocks all round-trip. Tables are flattened to fenced text because Slack mrkdwn has no table primitive.renderPostable(message)—PostableMessage→ mrkdwn. Used for fallback text on Block Kit messages and for ephemeral messages.
When updating these converters, mirror changes in cards.ts so the
fallback text on Block Kit blocks stays accurate.
Cards & rich content
cardToBlockKit (in cards.ts) translates the Chat SDK Card JSX
shape into Slack Block Kit:
<Section>→sectionblocks;<Header>→headerblocks.<Field>→ side-by-sidemrkdwnfields.<Image>→imageblocks (max 5 MB or viaimage_url).<Actions>and<Button>→actionsblocks withbuttonelements.<LinkButton>becomes abuttonwithurlset (no callback).<Select>→static_select,multi_static_select, orexternal_select(whenloadOptionsis supplied).<Divider>→divider.<Table>is rendered as a fixed-widthmrkdwnblock — Slack has no native table primitive.
cardToFallbackText produces a plain-text rendering used as the message
text so notifications, search, and screen readers still get usable
content.
Modals
openModal, pushModal, and updateModal accept either Chat SDK modal
JSX or pre-built Slack views. modals.ts handles the translation:
Modal.callbackId→view.callback_id.Modal.title/Modal.submitLabel/Modal.closeLabel→ matching view fields.TextInput,Select,RadioSelect,Checkbox,DatePicker,TimePicker,UserSelect,ChannelSelect,ConversationSelectare all mapped to the corresponding Block Kit element.- Per-modal metadata (callback URL, custom params, AI plan id) is
base64url-JSON-encoded into
view.private_metadataand decoded on submission.
Streaming
stream() consumes AsyncIterable<string | StreamChunk> and uses
Slack's native streaming API via the @slack/web-api chatStream
helper (chat.startStream → chat.appendStream → chat.stopStream).
Plain strings go through StreamingMarkdownRenderer so incremental
markdown stays valid (no half-formed tags); structured task_update /
plan_update chunks are passed through as native chunk payloads
(task_display_mode: "plan" groups them into a plan). stopBlocks
(the StreamingPlan endWith option) attach Block Kit to the final
message on chat.stopStream.
With agentView enabled, startTyping and stream completion manage the
Agent Sessions lifecycle through agents.sessions.setStatus, and
agent_session_stopped aborts the active Thread.signal. Keep the legacy
assistant.threads.* path intact for agentView: false until Slack retires
assistant_view in February 2027.
Fallback to post-and-edit (chat.update deltas, throttled by
updateIntervalMs) happens at three levels:
stream()returnsnullbefore consuming anything (no thread context, no recipient context,nativeStreaming: false, or a latched unsupported workspace) — the chat core runs its own post-and-edit.- The first native call is rejected (e.g. GovSlack
unknown_method, feature not enabled) — the adapter switches to internal post-and-edit mid-stream without losing consumed text, and latches native streaming off for permanent platform errors. - A structured chunk is rejected (missing scope/feature) — the chunk is skipped and text streaming continues.
Failures after native content has rendered still propagate — mixing the
two surfaces would duplicate output. The one exception is Slack expiring
a stream (message_not_in_streaming_state): the adapter continues in a
new message with any text Slack had not confirmed.
Slack expires a native stream after roughly five minutes, so stream()
works in segments: once a segment is streamSegmentMaxAgeMs old (the
clock starts at the first call Slack accepts, not at construction), the
next paragraph break (or, after a 30 s grace, the next line break)
finalizes it and a new chatStream continues the reply. Rotation closes
and reopens an open code fence, repeats a table header, replays the plan
and open task cards, and keeps session_status: "processing" with
agentView. Tests drive this with a mocked Date.now(); see the
"native stream rotation" describe block.
Socket Mode
Socket Mode is opt-in via mode: "socket" and appToken (xapp-…).
On serverless, use startSocketModeListener from a cron route — the
listener accepts events for durationMs, then forwards each as an
HTTP request to your existing webhook URL (so all webhook handlers
keep working unchanged). Forwarded requests are signed with
socketForwardingSecret (defaults to SLACK_SOCKET_FORWARDING_SECRET,
falling back to appToken).
Slack quirks worth remembering
- 3-second response SLAs. Events, slash commands, view
submissions, and block_suggestion all enforce them. Schedule any
follow-up work via
waitUntil. textis required alongside Block Kit blocks. The adapter sets it tocardToFallbackTextautomatically; if you bypass the adapter, set it yourself.- DM channels (
D…) reuse the user ID foruser.id— never trust channel IDs as the only identity hint. - Slack truncates blocks silently at 50 per message; the adapter splits oversize Block Kit payloads into multiple messages and links them with a "View more" actions row.
- Reaction events include both
reaction_addedandreaction_removed— keepaddReaction/removeReactionsymmetric. - Token encryption-at-rest is opt-in.
encryptionKeymust be a base64-encoded 32-byte key; rotate it by reading old installations, re-encrypting, and writing back.
Testing approach
- Unit tests (
*.test.ts) — colocated with each module. Test the parsers, format converter, card builder, and crypto helpers in isolation usingcreateMockStatefrompackages/chat/src/mock-adapter.ts. - Replay tests —
packages/integration-tests/src/replay-*.test.tsfeed recorded fixtures through the full webhook flow. Re-record by running the bot locally against a real workspace and exporting viapnpm recording:export <session-id>fromexamples/nextjs-chat. - Adapter contract tests — exercise
Adapterinterface conformance via the shared test kit atpackages/tests.
When adding a feature, prefer extending an existing fixture in
sample-messages.md rather than fabricating a payload from scratch.
Coding conventions
- All exports are
export function,export const, orexport class— no default exports. - Public types live alongside the implementation in
src/index.tsand are re-exported from the package entry. Internal-only types stay in their dedicated module (crypto.ts,modals.ts). - The adapter never calls
process.envoutside thecreateSlackAdapterfactory; runtime code receives explicit config. - Webhook handlers must return
Responsesynchronously; long work goes throughwaitUntil. - Errors thrown to chat-sdk callers come from
@chat-adapter/shared(AuthenticationError,AdapterRateLimitError,NetworkError,ValidationError) — don't invent new error classes. - Top-level regex literals only. Several exist in
index.ts(SLACK_USER_ID_PATTERN,TRAILING_SLASH_PATTERN, etc.); follow the same pattern.
Releases
This package ships with the rest of the monorepo on a fixed Changesets
schedule. Behavioural changes need a changeset (pnpm changeset,
choose @chat-adapter/slack plus chat if a public type changed).
README updates, sample-message additions, and AGENTS.md edits are
docs-only — no changeset required.
Resources
- How to build an AI agent for Slack with Chat SDK and AI SDK — Build a Slack AI agent using Chat SDK, AI SDK's ToolLoopAgent, and Vercel AI Gateway. Covers project setup, tool definitions, streaming responses, deployment to Vercel, and scaling tool selection with toolpick.
- How to build a Slack bot that manages files in Vercel Blob — Build a Slack bot that lists, reads, uploads, and deletes files in Vercel Blob through tool calls. Uses Chat SDK, AI SDK's ToolLoopAgent, and Files SDK's
createFileToolsfactory with approval-gated write tools and a read-only mode. - How to build a Slack bot with Next.js and Redis — Walks through building a Slack bot with Next.js, covering project setup, Slack app configuration, event handling, interactive features, and deployment.
See all guides and templates at chat-sdk.dev/resources.
Where to look next
- User-facing docs:
apps/docs/content/adapters/official/slack.mdx - README:
packages/adapter-slack/README.md - Shared error/utility helpers:
packages/adapter-shared/src/index.ts - Core Adapter contract:
packages/chat/src/adapter.ts - Sample webhook payloads:
packages/adapter-slack/sample-messages.md
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

