chat 4.26.0 → 4.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/{chunk-OPV5U4WG.js → chunk-AN7MRAVW.js} +39 -0
  2. package/dist/index.d.ts +220 -6
  3. package/dist/index.js +321 -50
  4. package/dist/{jsx-runtime-DxATbnrP.d.ts → jsx-runtime-Co9uV6l7.d.ts} +39 -5
  5. package/dist/jsx-runtime.d.ts +1 -1
  6. package/dist/jsx-runtime.js +1 -1
  7. package/docs/adapters.mdx +28 -28
  8. package/docs/api/chat.mdx +85 -1
  9. package/docs/api/message.mdx +5 -1
  10. package/docs/api/thread.mdx +23 -1
  11. package/docs/contributing/publishing.mdx +33 -0
  12. package/docs/files.mdx +1 -0
  13. package/docs/getting-started.mdx +1 -11
  14. package/docs/meta.json +0 -2
  15. package/docs/modals.mdx +73 -1
  16. package/docs/streaming.mdx +13 -5
  17. package/docs/threads-messages-channels.mdx +34 -0
  18. package/package.json +3 -2
  19. package/resources/guides/create-a-discord-support-bot-with-nuxt-and-redis.md +180 -0
  20. package/resources/guides/how-to-build-a-slack-bot-with-next-js-and-redis.md +134 -0
  21. package/resources/guides/how-to-build-an-ai-agent-for-slack-with-chat-sdk-and-ai-sdk.md +220 -0
  22. package/resources/guides/run-and-track-deploys-from-slack.md +270 -0
  23. package/resources/guides/ship-a-github-code-review-bot-with-hono-and-redis.md +147 -0
  24. package/resources/guides/triage-form-submissions-with-chat-sdk.md +178 -0
  25. package/resources/templates.json +19 -0
  26. package/docs/guides/code-review-hono.mdx +0 -241
  27. package/docs/guides/discord-nuxt.mdx +0 -227
  28. package/docs/guides/durable-chat-sessions-nextjs.mdx +0 -337
  29. package/docs/guides/meta.json +0 -10
  30. package/docs/guides/scheduled-posts-neon.mdx +0 -447
  31. package/docs/guides/slack-nextjs.mdx +0 -234
@@ -1,241 +0,0 @@
1
- ---
2
- title: Code review GitHub bot with Hono and Redis
3
- description: This guide walks through building a GitHub bot that reviews pull requests on demand. When a user @mentions the bot on a PR, Chat SDK picks up the mention, spins up a Vercel Sandbox with the repo cloned, and uses AI SDK to analyze the diff.
4
- type: guide
5
- prerequisites: []
6
- related:
7
- - /adapters/github
8
- - /docs/state/redis
9
- ---
10
-
11
- ## Prerequisites
12
-
13
- - Node.js 18+
14
- - [pnpm](https://pnpm.io) (or npm/yarn)
15
- - A GitHub repository where you have admin access
16
- - A Redis instance for state management
17
- - A [Vercel](https://vercel.com) account
18
-
19
- ## Create a Hono app
20
-
21
- Scaffold a new Hono project and install dependencies:
22
-
23
- ```sh title="Terminal"
24
- pnpm create hono my-review-bot
25
- cd my-review-bot
26
- pnpm add @octokit/rest @vercel/functions @vercel/sandbox ai bash-tool chat @chat-adapter/github @chat-adapter/state-redis
27
- ```
28
-
29
- <Callout type="info">
30
- Select the `vercel` template when prompted by `create-hono`. This sets up the project for Vercel deployment with the correct entry point.
31
- </Callout>
32
-
33
- ## Configure a GitHub webhook
34
-
35
- 1. Go to your repository **Settings** then **Webhooks** then **Add webhook**
36
- 2. Set **Payload URL** to `https://your-domain.com/api/webhooks/github`
37
- 3. Set **Content type** to `application/json`
38
- 4. Set a **Secret** and save it — you'll need this as `GITHUB_WEBHOOK_SECRET`
39
- 5. Under **Which events would you like to trigger this webhook?**, select **Let me select individual events** and check:
40
- - **Issue comments** (for @mention on the PR conversation tab)
41
- - **Pull request review comments** (for @mention on inline review threads)
42
-
43
- ### Get credentials
44
-
45
- 1. Go to [Settings > Developer settings > Personal access tokens](https://github.com/settings/tokens) and create a token with `repo` scope — you'll need this as `GITHUB_TOKEN`
46
- 2. Copy the **Webhook secret** you set above — you'll need this as `GITHUB_WEBHOOK_SECRET`
47
-
48
- ## Configure environment variables
49
-
50
- Create a `.env` file in your project root:
51
-
52
- ```bash title=".env"
53
- GITHUB_TOKEN=ghp_your_personal_access_token
54
- GITHUB_WEBHOOK_SECRET=your_webhook_secret
55
- REDIS_URL=redis://localhost:6379
56
- BOT_USERNAME=my-review-bot
57
- ```
58
-
59
- The model (`anthropic/claude-sonnet-4.6`) uses AI Gateway. Develop locally by linking to your Vercel project with `vc link` then pulling your OIDC token with `vc pull --environment development`.
60
-
61
- ## Define the review function
62
-
63
- Create the core review logic. This clones the repo into a Vercel Sandbox, then uses AI SDK with a bash tool to let Claude analyze the diff and read files directly.
64
-
65
- ```typescript title="src/review.ts" lineNumbers
66
- import { Sandbox } from "@vercel/sandbox";
67
- import { ToolLoopAgent, stepCountIs } from "ai";
68
- import { createBashTool } from "bash-tool";
69
-
70
- interface ReviewInput {
71
- owner: string;
72
- repo: string;
73
- prBranch: string;
74
- baseBranch: string;
75
- }
76
-
77
- export async function reviewPullRequest(input: ReviewInput): Promise<string> {
78
- const { owner, repo, prBranch, baseBranch } = input;
79
-
80
- const sandbox = await Sandbox.create({
81
- source: {
82
- type: "git",
83
- url: `https://github.com/${owner}/${repo}`,
84
- username: "x-access-token",
85
- password: process.env.GITHUB_TOKEN,
86
- depth: 50,
87
- },
88
- timeout: 5 * 60 * 1000,
89
- });
90
-
91
- try {
92
- await sandbox.runCommand("git", ["fetch", "origin", prBranch, baseBranch]);
93
- await sandbox.runCommand("git", ["checkout", prBranch]);
94
-
95
- const diffResult = await sandbox.runCommand("git", [
96
- "diff",
97
- `origin/${baseBranch}...HEAD`,
98
- ]);
99
- const diff = await diffResult.output("stdout");
100
-
101
- const { tools } = await createBashTool({ sandbox });
102
-
103
- const agent = new ToolLoopAgent({
104
- model: "anthropic/claude-sonnet-4.6",
105
- tools,
106
- stopWhen: stepCountIs(20),
107
- });
108
-
109
- const result = await agent.generate({
110
- prompt: `You are reviewing a pull request for bugs and issues.
111
-
112
- Here is the diff for this PR:
113
-
114
- \`\`\`diff
115
- ${diff}
116
- \`\`\`
117
-
118
- Use the bash and readFile tools to inspect any files you need more context on.
119
-
120
- Look for bugs, security issues, performance problems, and missing error handling.
121
- Organize findings by severity (critical, warning, suggestion).
122
- If the code looks good, say so.`,
123
- });
124
-
125
- return result.text;
126
- } finally {
127
- await sandbox.stop();
128
- }
129
- }
130
- ```
131
-
132
- The `createBashTool` gives the agent `bash`, `readFile`, and `writeFile` tools — all scoped to the sandbox. The agent can run `git diff`, read source files, and explore the repo freely without any code escaping the sandbox.
133
-
134
- The function returns the review text instead of posting it directly. This lets the Chat SDK handler post it as a threaded reply.
135
-
136
- ## Create the bot
137
-
138
- Create a `Chat` instance with the GitHub adapter. When someone @mentions the bot on a PR, it fetches the PR metadata, runs the review, and posts the result back to the thread.
139
-
140
- ```typescript title="src/bot.ts" lineNumbers
141
- import { Chat } from "chat";
142
- import { createGitHubAdapter } from "@chat-adapter/github";
143
- import { createRedisState } from "@chat-adapter/state-redis";
144
- import { Octokit } from "@octokit/rest";
145
- import { reviewPullRequest } from "./review";
146
- import type { GitHubRawMessage } from "@chat-adapter/github";
147
-
148
- const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });
149
-
150
- export const bot = new Chat({
151
- userName: process.env.BOT_USERNAME!,
152
- adapters: {
153
- github: createGitHubAdapter(),
154
- },
155
- state: createRedisState(),
156
- });
157
-
158
- bot.onNewMention(async (thread, message) => {
159
- const raw = message.raw as GitHubRawMessage;
160
- const { owner, repo, prNumber } = {
161
- owner: raw.repository.owner.login,
162
- repo: raw.repository.name,
163
- prNumber: raw.prNumber,
164
- };
165
-
166
- // Fetch PR branch info
167
- const { data: pr } = await octokit.pulls.get({
168
- owner,
169
- repo,
170
- pull_number: prNumber,
171
- });
172
-
173
- await thread.post("Starting code review...");
174
- await thread.subscribe();
175
-
176
- const review = await reviewPullRequest({
177
- owner,
178
- repo,
179
- prBranch: pr.head.ref,
180
- baseBranch: pr.base.ref,
181
- });
182
-
183
- await thread.post(review);
184
- });
185
-
186
- bot.onSubscribedMessage(async (thread, message) => {
187
- await thread.post(
188
- "I've already reviewed this PR. @mention me on a new PR to start another review."
189
- );
190
- });
191
- ```
192
-
193
- `onNewMention` fires when a user @mentions the bot — for example, `@codereview can you review this?`. The handler extracts the PR details from the message's raw payload, runs the sandboxed review, and posts the result. Calling `thread.subscribe()` lets the bot respond to follow-up messages in the same thread.
194
-
195
- ## Handle the webhook
196
-
197
- Create the Hono app with a single webhook route that delegates to Chat SDK:
198
-
199
- ```typescript title="src/index.ts" lineNumbers
200
- import { Hono } from "hono";
201
- import { waitUntil } from "@vercel/functions";
202
- import { bot } from "./bot";
203
-
204
- const app = new Hono();
205
-
206
- app.post("/api/webhooks/github", async (c) => {
207
- const handler = bot.webhooks.github;
208
- if (!handler) {
209
- return c.text("GitHub adapter not configured", 404);
210
- }
211
-
212
- return handler(c.req.raw, { waitUntil });
213
- });
214
-
215
- export default app;
216
- ```
217
-
218
- Chat SDK's GitHub adapter handles signature verification, event parsing, and routing internally. The `waitUntil` option ensures the review completes after the HTTP response is sent — required on serverless platforms where the function would otherwise terminate before your handlers finish.
219
-
220
- ## Test locally
221
-
222
- 1. Start your development server (`pnpm dev`)
223
- 2. Expose it with a tunnel (e.g. `ngrok http 3000`)
224
- 3. Update the webhook URL in your GitHub repository settings to your tunnel URL
225
- 4. Open a pull request
226
- 5. Comment `@my-review-bot can you review this?` — the bot should respond with "Starting code review..." followed by the full review
227
-
228
- ## Deploy to Vercel
229
-
230
- Deploy your bot to Vercel:
231
-
232
- ```sh title="Terminal"
233
- vercel deploy
234
- ```
235
-
236
- After deployment, set your environment variables in the Vercel dashboard (`GITHUB_TOKEN`, `GITHUB_WEBHOOK_SECRET`, `REDIS_URL`, `BOT_USERNAME`). Update the webhook URL in your GitHub repository settings to your production URL.
237
-
238
- ## Next steps
239
-
240
- - [GitHub adapter](/adapters/github) — Authentication options, thread model, and full configuration reference
241
- - [State Adapters](/docs/state) — Production state adapters (Redis, PostgreSQL, ioredis) for subscriptions and distributed locking
@@ -1,227 +0,0 @@
1
- ---
2
- title: Discord support bot with Nuxt and Redis
3
- description: This guide walks through building a Discord support bot with Nuxt, covering project setup, Discord app configuration, Gateway forwarding, AI-powered responses, and deployment.
4
- type: guide
5
- prerequisites: []
6
- related:
7
- - /adapters/discord
8
- - /docs/cards
9
- - /docs/actions
10
- ---
11
-
12
- ## Prerequisites
13
-
14
- - Node.js 18+
15
- - [pnpm](https://pnpm.io) (or npm/yarn)
16
- - A Discord server where you have admin access
17
- - A Redis instance for state management
18
-
19
- ## Create a Nuxt app
20
-
21
- Scaffold a new Nuxt project and install Chat SDK dependencies:
22
-
23
- ```sh title="Terminal"
24
- npx nuxi@latest init my-discord-bot
25
- cd my-discord-bot
26
- pnpm add chat @chat-adapter/discord @chat-adapter/state-redis ai @ai-sdk/anthropic
27
- ```
28
-
29
- ## Create a Discord app
30
-
31
- 1. Go to [discord.com/developers/applications](https://discord.com/developers/applications)
32
- 2. Click **New Application**, give it a name, and click **Create**
33
- 3. Go to **Bot** in the sidebar and click **Reset Token** — copy the token, you'll need this as `DISCORD_BOT_TOKEN`
34
- 4. Under **Privileged Gateway Intents**, enable **Message Content Intent**
35
- 5. Go to **General Information** and copy the **Application ID** and **Public Key** — you'll need these as `DISCORD_APPLICATION_ID` and `DISCORD_PUBLIC_KEY`
36
-
37
- ### Set up the Interactions endpoint
38
-
39
- 1. In **General Information**, set the **Interactions Endpoint URL** to `https://your-domain.com/api/webhooks/discord`
40
- 2. Discord will send a PING to verify the endpoint — you'll need to deploy first or use a tunnel
41
-
42
- ### Invite the bot to your server
43
-
44
- 1. Go to **OAuth2** in the sidebar
45
- 2. Under **OAuth2 URL Generator**, select the `bot` scope
46
- 3. Under **Bot Permissions**, select:
47
- - Send Messages
48
- - Create Public Threads
49
- - Send Messages in Threads
50
- - Read Message History
51
- - Add Reactions
52
- - Use Slash Commands
53
- 4. Copy the generated URL and open it in your browser to invite the bot
54
-
55
- ## Configure environment variables
56
-
57
- Create a `.env` file in your project root:
58
-
59
- ```bash title=".env"
60
- DISCORD_BOT_TOKEN=your_bot_token
61
- DISCORD_PUBLIC_KEY=your_public_key
62
- DISCORD_APPLICATION_ID=your_application_id
63
- REDIS_URL=redis://localhost:6379
64
- ANTHROPIC_API_KEY=your_anthropic_api_key
65
- ```
66
-
67
- ## Create the bot
68
-
69
- Create `server/lib/bot.ts` with a `Chat` instance configured with the Discord adapter. This bot uses AI SDK to answer support questions:
70
-
71
- ```typescript title="server/lib/bot.tsx" lineNumbers
72
- import { Chat, Card, CardText as Text, Actions, Button, Divider } from "chat";
73
- import { createDiscordAdapter } from "@chat-adapter/discord";
74
- import { createRedisState } from "@chat-adapter/state-redis";
75
- import { generateText } from "ai";
76
- import { anthropic } from "@ai-sdk/anthropic";
77
-
78
- export const bot = new Chat({
79
- userName: "support-bot",
80
- adapters: {
81
- discord: createDiscordAdapter(),
82
- },
83
- state: createRedisState(),
84
- });
85
-
86
- bot.onNewMention(async (thread) => {
87
- await thread.subscribe();
88
- await thread.post(
89
- <Card title="Support">
90
- <Text>Hey! I'm here to help. Ask your question in this thread and I'll do my best to answer it.</Text>
91
- <Divider />
92
- <Actions>
93
- <Button id="escalate" style="danger">Escalate to Human</Button>
94
- </Actions>
95
- </Card>
96
- );
97
- });
98
-
99
- bot.onSubscribedMessage(async (thread, message) => {
100
- await thread.startTyping();
101
-
102
- const { text } = await generateText({
103
- model: anthropic("claude-sonnet-4-5-20250514"),
104
- system: "You are a friendly support bot. Answer questions concisely. If you don't know the answer, say so and suggest the user click 'Escalate to Human'.",
105
- prompt: message.text,
106
- });
107
-
108
- await thread.post(text);
109
- });
110
-
111
- bot.onAction("escalate", async (event) => {
112
- await event.thread.post(
113
- `${event.user.fullName} requested human support. A team member will follow up shortly.`
114
- );
115
- });
116
- ```
117
-
118
- <Callout type="info">
119
- The file extension must be `.tsx` (not `.ts`) when using JSX components like `Card` and `Button`. Make sure your `tsconfig.json` has `"jsx": "react-jsx"` and `"jsxImportSource": "chat"`.
120
- </Callout>
121
-
122
- `onNewMention` fires when a user @mentions the bot. Calling `thread.subscribe()` tells the SDK to track that thread, so subsequent messages trigger `onSubscribedMessage` where AI SDK generates a response.
123
-
124
- ## Create the webhook route
125
-
126
- Create a server route that handles incoming Discord webhooks:
127
-
128
- ```typescript title="server/api/webhooks/[platform].post.ts" lineNumbers
129
- import { bot } from "../lib/bot";
130
-
131
- type Platform = keyof typeof bot.webhooks;
132
-
133
- export default defineEventHandler(async (event) => {
134
- const platform = getRouterParam(event, "platform") as Platform;
135
-
136
- const handler = bot.webhooks[platform];
137
- if (!handler) {
138
- throw createError({ statusCode: 404, message: `Unknown platform: ${platform}` });
139
- }
140
-
141
- const request = toWebRequest(event);
142
-
143
- return handler(request, {
144
- waitUntil: (task) => event.waitUntil(task),
145
- });
146
- });
147
- ```
148
-
149
- This creates a `POST /api/webhooks/discord` endpoint. The `waitUntil` option ensures message processing completes after the HTTP response is sent.
150
-
151
- ## Set up the Gateway forwarder
152
-
153
- Discord doesn't push messages to webhooks like Slack does. Instead, messages arrive through the Gateway WebSocket. The Discord adapter includes a built-in Gateway listener that connects to the WebSocket and forwards events to your webhook endpoint.
154
-
155
- Create a route that starts the Gateway listener:
156
-
157
- ```typescript title="server/api/discord/gateway.get.ts" lineNumbers
158
- import { bot } from "../../lib/bot";
159
-
160
- export default defineEventHandler(async (event) => {
161
- await bot.initialize();
162
-
163
- const discord = bot.getAdapter("discord");
164
- if (!discord) {
165
- throw createError({ statusCode: 404, message: "Discord adapter not configured" });
166
- }
167
-
168
- const baseUrl = process.env.NUXT_PUBLIC_SITE_URL || "http://localhost:3000";
169
- const webhookUrl = `${baseUrl}/api/webhooks/discord`;
170
-
171
- const durationMs = 10 * 60 * 1000; // 10 minutes
172
-
173
- return discord.startGatewayListener(
174
- { waitUntil: (task: Promise<unknown>) => event.waitUntil(task) },
175
- durationMs,
176
- undefined,
177
- webhookUrl,
178
- );
179
- });
180
- ```
181
-
182
- The Gateway listener connects to Discord's WebSocket, receives messages, and forwards them to your webhook endpoint for processing. In production, you'll want a cron job to restart it periodically.
183
-
184
- ## Test locally
185
-
186
- 1. Start your development server (`pnpm dev`)
187
- 2. Trigger the Gateway listener by visiting `http://localhost:3000/api/discord/gateway` in your browser
188
- 3. Expose your server with a tunnel (e.g. `ngrok http 3000`)
189
- 4. Update the **Interactions Endpoint URL** in your Discord app settings to your tunnel URL (e.g. `https://abc123.ngrok.io/api/webhooks/discord`)
190
- 5. @mention the bot in your Discord server — it should respond with a support card
191
- 6. Reply in the thread — AI SDK should generate a response
192
- 7. Click **Escalate to Human** — the bot should post an escalation message
193
-
194
- ## Add a cron job for production
195
-
196
- The Gateway listener runs for a fixed duration. In production, set up a cron job to restart it automatically. If you're deploying to Vercel, add a `vercel.json`:
197
-
198
- ```json title="vercel.json"
199
- {
200
- "crons": [
201
- {
202
- "path": "/api/discord/gateway",
203
- "schedule": "*/9 * * * *"
204
- }
205
- ]
206
- }
207
- ```
208
-
209
- This restarts the Gateway listener every 9 minutes, ensuring continuous connectivity. Protect the endpoint with a `CRON_SECRET` environment variable in production.
210
-
211
- ## Deploy to Vercel
212
-
213
- Deploy your bot to Vercel:
214
-
215
- ```sh title="Terminal"
216
- vercel deploy
217
- ```
218
-
219
- After deployment, set your environment variables in the Vercel dashboard (`DISCORD_BOT_TOKEN`, `DISCORD_PUBLIC_KEY`, `DISCORD_APPLICATION_ID`, `REDIS_URL`, `ANTHROPIC_API_KEY`). Update the **Interactions Endpoint URL** in your Discord app settings to your production URL.
220
-
221
- ## Next steps
222
-
223
- - [Cards](/docs/cards) — Build rich interactive messages with buttons, fields, and selects
224
- - [Actions](/docs/actions) — Handle button clicks, select menus, and other interactions
225
- - [Streaming](/docs/streaming) — Stream AI-generated responses to chat
226
- - [Discord adapter](/adapters/discord) — Full configuration reference and Gateway setup
227
- - [State Adapters](/docs/state) — PostgreSQL, ioredis, and other state adapter options