1. Write Bot Logic Once, Native UX Everywhere
Every chat platform invents its own webhook signature scheme, markdown dialect, thread model, and button payload. Vercel Chat SDK (chat) normalizes incoming events into one clean TypeScript API while rendering authentic native cards, modals, and streaming replies per channel.
Quick Navigation
Core Mental Model: Normalized Ingress, Native Egress
Instead of embedding Slack Block Kit JSON or Discord slash-command glue inside your AI agent, route every webhook endpoint into one shared Chat instance running in Next.js, Hono, or Nuxt. Adapters translate inbound webhooks into unified Thread and Message objects, Redis guards thread state against concurrent replies, and AI SDK 7 streams grounded responses back out through each platform’s native UI primitives.
Unified Architecture: 8 Webhook Channels Through One Chat Core
2. Quickstart, @chat-adapter/catalog & Decision Matrix
Go from zero to a multi-platform bot in under a minute. Scaffold a Next.js template without prompts, inspect the bundled offline docs inside node_modules/chat/, and use @chat-adapter/catalog to query adapter capabilities statically.
# Scaffold a Next.js bot project without prompts
npx create-chat-sdk
# Or add Chat SDK + adapters to an existing repo
npm i chat @chat-adapter/slack @chat-adapter/redis
Every install ships version-matched markdown guides in node_modules/chat/docs/, 13 production recipes in node_modules/chat/resources/, and starter blueprints in node_modules/chat/resources/templates.json.
@chat-adapter/catalog)
Replace deprecated chat/adapters imports with @chat-adapter/catalog—a zero-dependency static index of official, vendor-official, and community adapters:
listAdapters()&getCatalogEntry(slug): Discover npm packages, peer deps, and platform vs. state adapter roles before installing.getFeatureSupport(slug): Check streaming, modals, and distributed locking support at build time or runtime.listEnvVars(slug)&getSecretEnvVars(slug): Generate accurate onboarding checklists and secret vaults automatically.
Architectural Decision Matrix: Choosing Your Bot Foundation
| Dimension | Vercel Chat SDK (chat) |
Raw SDKs (@slack/bolt, discord.js, telegraf) |
eve Framework (Greenfield) |
|---|---|---|---|
| Primary Sweet Spot | Multi-platform bots inside Next.js, Hono, Nitro, or Nuxt apps sharing one handler codebase. | Single-platform edge cases needing esoteric socket-mode APIs outside standard messaging. | Greenfield, filesystem-first durable internal agents where Slack is one of several agent channels. |
| Channel Portability | High: Add Slack, Teams, Discord, Telegram, GChat, GitHub, Linear, or Liveblocks via adapters. | Locked: Rewriting a Slack Bolt bot for Teams or Discord means duplicating every route and UI card. | Built-In: Convention-based agent/channels/*.ts files wired straight to durable agent sessions. |
| Concurrency & State | Pluggable @chat-adapter/redis locks threads and persists subscriptions across serverless instances. |
Manual DIY Redis locks; stateful WebSocket clients like discord.js break on serverless cold starts. |
Durable filesystem-backed session history, schedules, and subagents managed by the runtime. |
| Workflow & Auth Pairing | Pairs cleanly with @vercel/connect/chat, AI SDK 7 ToolLoopAgent, and Workflow 5 createWebhook. |
Requires manual OAuth refresh plumbing, custom webhook replay checks, and static bot tokens. | Native @vercel/connect/eve helpers (connectSlackCredentials) and Agent Runs observability. |
eve Directly3. Annotated Tour: Cross-Platform Thread & Card Cockpit
Trace how a single user @-mention flows from an inbound webhook through Redis locking, AI SDK 7 streaming, and an interactive Human-in-the-Loop approval card that resumes a paused Workflow 5 run.
@vercel/connect OIDC Trigger → thread.subscribe() 2
Auth: slack/acme-ops (0 static secrets) 4
v2.14.0 is staged for production. Requesting sign-off below…”
91c4e2a • Target: prod-us-east • Timeout: sleep("24h")wh_tok_771b 7
getFeatureSupport("slack") → streaming: true, modals: true, locking: true
AI Gateway: anthropic/claude-sonnet-4.6
Interface Legend: The 7 Live Runtime Touchpoints
@chat-adapter/catalog map each webhook route to its platform formatter and feature flags.
onNewMention fires on first ping; calling thread.subscribe() routes future thread replies to onSubscribedMessage.
ToolLoopAgent Reply: Pipes AI SDK 7 token streams directly into thread.post() using native live-edit updates where supported.
createWebhook): Button clicks carry an opaque token back to your handler, verifying the clicking user’s authority and calling resumeWebhook(token, payload) to wake the suspended workflow run cleanly.
4. Unified Chat Event Model & Native Adapters
Every adapter translates platform-specific events into four clean lifecycle hooks, letting you write interactive streaming bots, slash commands, Cards, and Modals once while honoring per-platform capabilities from @chat-adapter/catalog.
1. Unified Event Hooks & Streaming Replies
import { Chat } from "chat";
import { createSlackAdapter } from "@chat-adapter/slack";
import { createTeamsAdapter } from "@chat-adapter/teams";
import { createRedisState } from "@chat-adapter/redis";
export const bot = new Chat({
userName: "ops-copilot",
adapters: { slack: createSlackAdapter(), teams: createTeamsAdapter() },
state: createRedisState(),
});
bot.onNewMention(async (thread, msg) => {
await thread.subscribe();
const stream = await supportAgent.stream({ prompt: msg.text });
await thread.post(stream.textStream); // Streams natively per adapter
});
bot.onSubscribedMessage(async (thread, msg) => { /* follow-up turn */ });
bot.onSlashCommand("/triage", async (event) => { /* modal or card */ });2. Capability Checks via @chat-adapter/catalog
| Adapter | Streaming | Modals | Primary Surface |
|---|---|---|---|
| Slack / Teams | Live Edit | Native | Block Kit / Adaptive |
| Discord | Chunk Edit | Native | Embeds & Slash |
| Telegram | Draft / Edit | Inline Buttons | Commands & Topics |
| GitHub / Linear | Final Post | Markdown Links | PR & Issue Threads |
Call getFeatureSupport(slug) before invoking modals or token streaming so your bot degrades gracefully on issue-tracker threads without throwing runtime errors.
Card, Button, and Modal helpers instead of raw JSON payloads. On Slack they render as interactive Block Kit; on Microsoft Teams they emit Adaptive Cards; on GitHub or Linear they automatically render clean Markdown summaries with action links.
5. Redis Thread Locks & Multi-Platform Handler Anatomy
Serverless webhook functions run concurrently across regions. Without a shared state layer, two rapid messages in the same thread overwrite each other’s context and post scrambled replies. Pairing @chat-adapter/redis with durable Workflow handoffs keeps every conversation deterministic.
- Thread Subscriptions: Calling
await thread.subscribe()stores the active thread ID in Redis so users can reply naturally without re-typing@botevery turn. - Per-Thread Mutual Exclusion: Redis distributed locks serialize concurrent webhook deliveries on the same thread key, protecting message history and tool side-effects.
- Zero Cold-Start Drift: Any Vercel Function instance can pick up the next turn seamlessly using shared Redis state.
setInterval in Webhooks- Fast Webhook Ack: Messaging platforms retry or drop webhooks that stall past 3 seconds.
- Avoid
setTimeout/setInterval: Polling loops burn function timeouts and vanish on redeploys. - Offload Long Jobs: Acknowledge the mention, post a streaming status message, and trigger a durable Workflow 5 run via
start()for multi-minute builds or approvals.
Color-Coded Anatomy of a Production Multi-Platform Handler
3-Phase Execution Lifecycle Across Serverless Invocations
| Lifecycle Phase | Primary Mechanism | Why It Matters in Production |
|---|---|---|
| 1. Ingress & Lock | Adapter Verify + Redis Lock | Rejects forged payloads immediately and queues duplicate Slack/Teams retries behind a single thread mutex. |
| 2. Reason & Stream | ToolLoopAgent + AI Gateway |
Routes models via OIDC with automatic provider failover while streaming incremental tokens back to the thread. |
| 3. Pause & Resume | Card Action + Workflow 5 |
Converts multi-hour human sign-offs into zero-compute durable suspensions resumed via resumeWebhook(). |
stopWhen: isStepCount(N)maxSteps (removed in AI SDK 5+). Pass stopWhen: isStepCount(6) to ToolLoopAgent so runaway tool calls terminate predictably before exhausting platform response windows.
6. Zero-Secret Auth with @vercel/connect & Blob Tools
Static long-lived bot tokens sitting inside .env files create rotation headaches and wide blast radii. Pair Chat SDK with Vercel Connect (@vercel/connect/chat) for short-lived OAuth tokens and OIDC-signed triggers, and equip agents with approval-gated Vercel Blob tools.
SLACK_BOT_TOKEN & GITHUB_APP_PRIVATE_KEY SecretsVERCEL_OIDC_TOKEN. Connect holds refresh credentials in its managed vault and mints short-lived app or per-user provider tokens strictly at request time.
@vercel/connect/chat Works- App vs. User Subject: Request
subject: { type: "app" }to post as the bot, orsubject: { type: "user", id }to act strictly with an individual user’s OAuth consent. - Signed Trigger Forwarding: Connect verifies inbound Slack, Teams, Discord, GitHub, and Linear webhooks and forwards them to your route as signed Vercel OIDC requests.
- Native Exceptions: Telegram and Notion continue using their native inbound webhook verification tokens alongside Connect outbound calls.
createFileToolsFactory: Expose Vercel Blob buckets directly toToolLoopAgentso Slack users can list, search, and read reports conversationally.- Read-Only vs. Write Modes: Allow safe read/list calls automatically while placing uploads and deletes behind explicit human approval.
- Scoped Paths: Restrict prefixes per channel or tenant (e.g.
reports/eng/) so bots never traverse unrelated buckets.
// 1. Provision & link connector via CLI: vercel connect create slack && vercel connect attach slack/acme-ops
import { getToken } from "@vercel/connect";
import { ToolLoopAgent, isStepCount } from "ai";
import { createFileTools } from "@vercel/blob/ai"; // Approval-gated Files SDK tools
const slackToken = await getToken("slack/acme-ops", { subject: { type: "app" } });
const fileTools = createFileTools({ prefix: "team-docs/", readOnly: false, requireWriteApproval: true });
export const docsAgent = new ToolLoopAgent({
model: "openai/gpt-5.4", // Routed via AI Gateway with VERCEL_OIDC_TOKEN
tools: fileTools,
stopWhen: isStepCount(6),
});vercel env pullVERCEL_OIDC_TOKEN rotates automatically. Locally, link your directory with vercel link and run vercel env pull whenever your short-lived development OIDC token expires.
7. HITL Approval Cards & Sandbox PR Reviewers
Combine Chat SDK with Workflow 5 to pause multi-day approvals at zero compute cost until someone clicks a button in Slack or Teams, and spin up Vercel Sandbox microVMs whenever a developer @-mentions your bot on a GitHub pull request.
- Create Resumable Gate: Call
const hook = createWebhook()inside a"use workflow"function and passhook.tokeninto your Chat SDK approvalCardbuttons. - Race With Durable Timeouts: Pair
Promise.race([hook, sleep("24h")])so stale deployment requests expire cleanly without holding any server memory. - Validate Approver Identity: Inside
bot.onAction, verifyevent.userbelongs to the authorized release group before callingresumeWebhook().
- Trigger on PR Mention:
@chat-adapter/githubcaptures@bot reviewcomments on any PR thread. - Isolated Firecracker microVM: Launch
await Sandbox.create({ networkPolicy: "deny-all" })via@vercel/sandbox@2, clone the PR branch, and run tests safely. - Grounded PR Feedback: Feed exact diff hunks and failing test output to
ToolLoopAgentand post crisp inline comments back to the PR.
// Workflow 5 HITL gate: suspends cleanly until Slack/Teams button click or 24h durable sleep()
import { createWebhook, sleep } from "workflow";
export async function deployApprovalWorkflow(releaseTag: string, channelId: string) {
"use workflow";
const approvalHook = createWebhook();
await postApprovalCardStep(channelId, releaseTag, approvalHook.token);
const decision = await Promise.race([approvalHook, sleep("24h").then(() => ({ approved: false, reason: "timeout" }))]);
if (decision.approved) await promoteProductionStep(releaseTag);
}
8. 5 Real-World Copy-Paste Recipes
Start faster with these five production architectures drawn from node_modules/chat/resources/guides/. Each recipe pairs the exact adapters, AI SDK 7 primitives, and durability guards required for real traffic.
| Recipe & Channels | Stack & Adapters | Implementation Blueprint |
|---|---|---|
| 1. Streaming AI Slack Bot Slack Threads & DMs |
@chat-adapter/slack@chat-adapter/redisToolLoopAgent + Gateway |
Subscribe on onNewMention, acquire the Redis thread lock, call agent.stream() with anthropic/claude-sonnet-4.6 via AI Gateway, and pipe stream.textStream into thread.post() for live Slack message updates. |
| 2. GitHub PR Diff Reviewer GitHub PR Comments |
@chat-adapter/github@vercel/sandbox@2Hono + Redis |
On PR @bot mention, enqueue a background step that boots an isolated Sandbox.create() microVM, checks out the PR head SHA, runs pnpm test, analyzes changed files with ToolLoopAgent, and replies with exact file-and-line findings. |
| 3. HITL Deploy Gate Card Slack + MS Teams + Linear |
@chat-adapter/slack@chat-adapter/teamsWorkflow 5 createWebhook |
Trigger start(deployApprovalWorkflow) from /deploy. Inside the workflow, call createWebhook(), post a native Card with the token, race against sleep("24h"), validate event.user on click, and call resumeWebhook(). |
| 4. Discord & Telegram Knowledge Bot Discord + Telegram Topics |
@chat-adapter/discord@chat-adapter/telegramNuxt + Redis Locks |
Share one onSubscribedMessage handler across Discord threads and Telegram topics. Check getFeatureSupport() so Discord opens native Modal forms while Telegram falls back cleanly to threaded prompt questions. |
| 5. Zero-Secret Connect Channel Automation Slack + GitHub + Linear |
@vercel/connect/chatVERCEL_OIDC_TOKENConnect Triggers |
Link connectors via vercel connect attach, verify inbound webhooks via Vercel OIDC trigger headers instead of raw secrets, and mint short-lived app or per-user tokens with getToken() right before posting digests. |
ToolLoopAgent and Workflow 5 steps, expanding Recipe 1 from Slack to Microsoft Teams and Google Chat takes adding two entries to adapters: {} and attaching their webhook routes.
9. Webhook Security, Feature Fallbacks & Replay Ops
Production bots face forged webhook probes, bursty retry storms, and subtle differences across messaging platforms. Lock down verification at the edge, inspect adapter capabilities before rendering rich UI, and test every channel offline with deterministic replay fixtures.
- Verify Before Parsing: Let each adapter (or Vercel Connect’s OIDC verifier) validate raw HMAC/Ed25519 signatures and timestamp drift before running any agent code.
- Idempotent Event Keys: Messaging APIs retry if responses exceed 3s. Deduplicate inbound event IDs in Redis with a short TTL so duplicate webhooks never trigger double deploys or double LLM bills.
- Fast Ack, Async Work: Return
200 OKquickly and offload heavy tool loops via Vercel FunctionswaitUntilor Workflow 5start().
- Check
getFeatureSupport(slug): Never assume every adapter supports live token streaming or popup modals. - Modal Fallback: When
modalsis unsupported (e.g., GitHub PR comments or Telegram), collect fields via sequential threaded questions or a signed web link button. - Streaming Fallback: When
streamingis buffered rather than live-edited, buffer chunks cleanly and post one crisp formatted reply to avoid rate-limit429throttling.
Production Operations & Deterministic Testing Matrix
| Operational Area | Chat SDK / Vercel Mechanism | Recommended Production Practice |
|---|---|---|
| 1. Replay Fixtures | fixtures/replay/*.json |
Capture real Slack, Teams, Discord, and GitHub webhook payloads into fixtures/replay/ to run deterministic Vitest suites in CI. |
| 2. Rate-Limit Protection | Adapter edit throttling + Redis | Throttle live stream message edits (e.g., every 400–600ms) so rapid LLM tokens never trigger Slack or Discord 429 penalties. |
| 3. Preview Environment Auth | VERCEL_OIDC_TOKEN / Connect |
Attach separate dev/staging Connect connectors or verify preview webhook URLs have active OIDC and AI Gateway credentials. |
fixtures/replay/ through your local bot.webhooks handler lets you verify mention parsing, Redis lock contention, and Card fallbacks in milliseconds inside CI before deploying.
10. Cross-Tool Synergy: From Mention to Durable Action
Vercel Chat SDK serves as the conversational front door of a unified full-stack AI architecture—connecting zero-secret OAuth credentials, gateway-routed reasoning, and crash-safe execution pods without custom glue servers.
How the Pieces Reinforce Each Other in Production
Vercel Chat SDK absorbs platform webhook differences and manages Redis thread locks, while Vercel Connect guarantees zero static API keys sit in your deployment config and verifies forwarded webhook triggers via OIDC.
AI SDK 7 drives tool-calling loops across AI Gateway models with automatic failover, handing risky code checks to isolated Vercel Sandboxes and multi-hour human sign-offs to Workflow 5 webhooks.
11. Troubleshooting Clinic & Pre-Flight Checklist
Most multi-platform bot bugs trace back to one of seven predictable adapter, concurrency, or auth mistakes. Apply these ten-second fixes, then run the six-point checklist before shipping to production.
| Symptom / Anti-Pattern | Root Cause | 10-Second Fix |
|---|---|---|
1. Mixing @slack/bolt or telegraf |
Platform-specific bot frameworks hijack routes, bypass Redis locks, and break multi-platform portability. | Remove @slack/bolt, discord.js, and telegraf; use chat with @chat-adapter/slack, discord, or telegram. |
| 2. Parallel thread replies race or overwrite context | Serverless webhook invocations execute simultaneously without a distributed thread mutex. | Configure state: createRedisState() with @chat-adapter/redis so Chat SDK locks per thread ID automatically. |
3. Hardcoded bot tokens in .env |
Static SLACK_BOT_TOKEN or GitHub private keys invite rotation failures and wide secret exposure. |
Migrate to @vercel/connect/chat with getToken() and Connect-forwarded OIDC webhook triggers. |
4. setTimeout / setInterval polling times out |
Polling inside serverless webhook functions hits max-duration limits and loses state across deploys. | Move multi-step waits into a "use workflow" function using durable sleep() and createWebhook(). |
5. Importing deprecated chat/adapters |
Legacy subpath is deprecated and pulls unnecessary coupling into onboarding or tooling code. | Import listAdapters, getFeatureSupport, and listEnvVars directly from @chat-adapter/catalog. |
| 6. Streaming or modals crash on GitHub / Telegram | Bot invokes live modals or token-stream edits on adapters whose platform API does not support them. | Inspect getFeatureSupport(slug) first and branch cleanly to threaded follow-ups or buffered final posts. |
| 7. Preview webhooks fail AI calls (401/403) | Missing AI_GATEWAY_API_KEY or expired local/preview VERCEL_OIDC_TOKEN on branch deploys. |
Verify Vercel OIDC is enabled for Preview deployments (or set AI_GATEWAY_API_KEY), and refresh locally with vercel env pull. |
6-Point Pre-Flight Checklist Before Going Live
getFeatureSupport() fallbacks for streaming and modals on every enabled adapter.@chat-adapter/redis handles distributed locks and thread subscriptions across instances.@vercel/connect connectors and OIDC webhook verification.ToolLoopAgent Loops: Configured stopWhen: isStepCount(N) and AI Gateway provider/model routing.createWebhook + sleep() and PR code checks to Vercel Sandbox.fixtures/replay/ in CI.